text
stringlengths 54
60.6k
|
---|
<commit_before><commit_msg>json.hpp update<commit_after><|endoftext|>
|
<commit_before>#include "array.h"
#include "benchmark.h"
#include <random>
#include <iostream>
using namespace array;
// The standard matrix notation is to refer to elements by 'row,
// column'. To make this efficient for typical programs, we're going
// to make the second dimension the dense dim.
template <typename T>
using matrix = array<T, shape<dim<>, dense_dim<>>>;
// Helper functions to get the rows and columns dimension of a matrix.
template <typename T>
const dim<>& rows(const matrix<T>& m) { return m.shape().template dim<0>(); }
template <typename T>
const dense_dim<>& cols(const matrix<T>& m) { return m.shape().template dim<1>(); }
// A textbook implementation of matrix multiplication.
template <typename T>
void multiply_naive(const matrix<T>& a, const matrix<T>& b, matrix<T>& c) {
for (int i : rows(c)) {
for (int j : cols(c)) {
T c_ij = 0;
for (int k : cols(a)) {
c_ij += a(i, k) * b(k, j);
}
c(i, j) = c_ij;
}
}
}
// This implementation of matrix multiplication reorders the loops
// so the inner loop is over the columns of the result. This makes
// it possible to vectorize the inner loop.
template <typename T>
void multiply_cols_innermost(const matrix<T>& a, const matrix<T>& b, matrix<T>& c) {
for (int i : rows(c)) {
for (int j : cols(c)) {
c(i, j) = 0;
}
for (int k : cols(a)) {
for (int j : cols(c)) {
c(i, j) += a(i, k) * b(k, j);
}
}
}
}
// This implementation of matrix multiplication splits the loops over
// the output matrix into chunks, and reorders the inner loops
// innermost to form tiles. This implementation should allow the compiler
// to keep all of the accumulators for the output in registers.
// TODO: It's currently not doing this...
template <typename T>
void multiply_tiles_innermost(const matrix<T>& a, const matrix<T>& b, matrix<T>& c) {
constexpr int tile_M = 32;
constexpr int tile_N = 8;
// TODO: Add helper functions to make this less disgusting.
int tiles_m = rows(c).extent() / tile_M;
int tiles_n = cols(c).extent() / tile_N;
for (int io = 0; io < tiles_m; io++) {
for (int jo = 0; jo < tiles_n; jo++) {
for (int ii = 0; ii < tile_M; ii++) {
int i = io * tile_M + ii;
for (int ji = 0; ji < tile_N; ji++) {
int j = jo * tile_N + ji;
c(i, j) = 0;
}
}
for (int k : cols(a)) {
for (int ii = 0; ii < tile_M; ii++) {
int i = io * tile_M + ii;
for (int ji = 0; ji < tile_N; ji++) {
int j = jo * tile_N + ji;
c(i, j) += a(i, k) * b(k, j);
}
}
}
}
}
}
int main(int argc, const char** argv) {
// Generate two random input matrices.
constexpr int M = 128;
constexpr int K = 256;
constexpr int N = 512;
matrix<float> a({M, K});
matrix<float> b({K, N});
// 'for_each_value' calls the given function with a reference to
// each value in the array. Use this to randomly initialize the
// matrices.
std::mt19937_64 rng;
std::uniform_real_distribution<float> uniform(0, 1);
a.for_each_value([&](float& x) { x = uniform(rng); });
b.for_each_value([&](float& x) { x = uniform(rng); });
// Compute the result using all matrix multiply methods.
matrix<float> c_naive({M, N});
double naive_time = benchmark([&]() {
multiply_naive(a, b, c_naive);
});
std::cout << "naive time: " << naive_time * 1e3 << " ms" << std::endl;
matrix<float> c_cols_innermost({M, N});
double cols_innermost_time = benchmark([&]() {
multiply_cols_innermost(a, b, c_cols_innermost);
});
std::cout << "rows innermost time: " << cols_innermost_time * 1e3 << " ms" << std::endl;
matrix<float> c_tiles_innermost({M, N});
double tiles_innermost_time = benchmark([&]() {
multiply_tiles_innermost(a, b, c_tiles_innermost);
});
std::cout << "tiles innermost time: " << tiles_innermost_time * 1e3 << " ms" << std::endl;
// Verify the results from all methods are equal.
const float epsilon = 1e-4f;
for (int i = 0; i < M; i++) {
for (int j = 0; j < N; j++) {
if (std::abs(c_cols_innermost(i, j) - c_naive(i, j)) > epsilon) {
std::cout
<< "c_cols_innermost(" << i << ", " << j << ") = " << c_cols_innermost(i, j)
<< " != c_naive(" << i << ", " << j << ") = " << c_naive(i, j) << std::endl;
abort();
}
if (std::abs(c_tiles_innermost(i, j) - c_naive(i, j)) > epsilon) {
std::cout
<< "c_tiles_innermost(" << i << ", " << j << ") = " << c_tiles_innermost(i, j)
<< " != c_naive(" << i << ", " << j << ") = " << c_naive(i, j) << std::endl;
abort();
}
}
}
}
<commit_msg>Add comments.<commit_after>#include "array.h"
#include "benchmark.h"
#include <random>
#include <iostream>
using namespace array;
// The standard matrix notation is to refer to elements by 'row,
// column'. To make this efficient for typical programs, we're going
// to make the second dimension the dense dim.
template <typename T>
using matrix = array<T, shape<dim<>, dense_dim<>>>;
// Helper functions to get the rows and columns dimension of a matrix.
template <typename T>
const dim<>& rows(const matrix<T>& m) { return m.shape().template dim<0>(); }
template <typename T>
const dense_dim<>& cols(const matrix<T>& m) { return m.shape().template dim<1>(); }
// A textbook implementation of matrix multiplication.
template <typename T>
void multiply_naive(const matrix<T>& a, const matrix<T>& b, matrix<T>& c) {
for (int i : rows(c)) {
for (int j : cols(c)) {
T c_ij = 0;
for (int k : cols(a)) {
c_ij += a(i, k) * b(k, j);
}
c(i, j) = c_ij;
}
}
}
// This implementation of matrix multiplication reorders the loops
// so the inner loop is over the columns of the result. This makes
// it possible to vectorize the inner loop.
template <typename T>
void multiply_cols_innermost(const matrix<T>& a, const matrix<T>& b, matrix<T>& c) {
for (int i : rows(c)) {
for (int j : cols(c)) {
c(i, j) = 0;
}
for (int k : cols(a)) {
for (int j : cols(c)) {
c(i, j) += a(i, k) * b(k, j);
}
}
}
}
// This implementation of matrix multiplication splits the loops over
// the output matrix into chunks, and reorders the inner loops
// innermost to form tiles. This implementation should allow the compiler
// to keep all of the accumulators for the output in registers.
// TODO: This is slow. It appears to currently keep the tile in registers,
// but doesn't autovectorize like the above loop.
template <typename T>
void multiply_tiles_innermost(const matrix<T>& a, const matrix<T>& b, matrix<T>& c) {
// We want the tiles to be as big as possible without spilling any
// of the accumulator registers to the stack.
constexpr int tile_M = 32;
constexpr int tile_N = 4;
// TODO: Add helper functions to make this less disgusting.
int tiles_m = rows(c).extent() / tile_M;
int tiles_n = cols(c).extent() / tile_N;
for (int io = 0; io < tiles_m; io++) {
for (int jo = 0; jo < tiles_n; jo++) {
for (int ii = 0; ii < tile_M; ii++) {
int i = io * tile_M + ii;
for (int ji = 0; ji < tile_N; ji++) {
int j = jo * tile_N + ji;
c(i, j) = 0;
}
}
for (int k : cols(a)) {
for (int ii = 0; ii < tile_M; ii++) {
int i = io * tile_M + ii;
for (int ji = 0; ji < tile_N; ji++) {
int j = jo * tile_N + ji;
c(i, j) += a(i, k) * b(k, j);
}
}
}
}
}
}
int main(int argc, const char** argv) {
// Generate two random input matrices.
constexpr int M = 128;
constexpr int K = 256;
constexpr int N = 512;
matrix<float> a({M, K});
matrix<float> b({K, N});
// 'for_each_value' calls the given function with a reference to
// each value in the array. Use this to randomly initialize the
// matrices.
std::mt19937_64 rng;
std::uniform_real_distribution<float> uniform(0, 1);
a.for_each_value([&](float& x) { x = uniform(rng); });
b.for_each_value([&](float& x) { x = uniform(rng); });
// Compute the result using all matrix multiply methods.
matrix<float> c_naive({M, N});
double naive_time = benchmark([&]() {
multiply_naive(a, b, c_naive);
});
std::cout << "naive time: " << naive_time * 1e3 << " ms" << std::endl;
matrix<float> c_cols_innermost({M, N});
double cols_innermost_time = benchmark([&]() {
multiply_cols_innermost(a, b, c_cols_innermost);
});
std::cout << "rows innermost time: " << cols_innermost_time * 1e3 << " ms" << std::endl;
matrix<float> c_tiles_innermost({M, N});
double tiles_innermost_time = benchmark([&]() {
multiply_tiles_innermost(a, b, c_tiles_innermost);
});
std::cout << "tiles innermost time: " << tiles_innermost_time * 1e3 << " ms" << std::endl;
// Verify the results from all methods are equal.
const float epsilon = 1e-4f;
for (int i = 0; i < M; i++) {
for (int j = 0; j < N; j++) {
if (std::abs(c_cols_innermost(i, j) - c_naive(i, j)) > epsilon) {
std::cout
<< "c_cols_innermost(" << i << ", " << j << ") = " << c_cols_innermost(i, j)
<< " != c_naive(" << i << ", " << j << ") = " << c_naive(i, j) << std::endl;
abort();
}
if (std::abs(c_tiles_innermost(i, j) - c_naive(i, j)) > epsilon) {
std::cout
<< "c_tiles_innermost(" << i << ", " << j << ") = " << c_tiles_innermost(i, j)
<< " != c_naive(" << i << ", " << j << ") = " << c_naive(i, j) << std::endl;
abort();
}
}
}
}
<|endoftext|>
|
<commit_before>#include <osg/Texture2D>
#include <osg/TexGen>
#include <osg/Material>
#include <osg/LightSource>
#include <osg/Geode>
#include <osg/ShapeDrawable>
#include <osgUtil/CullVisitor>
#include <osgUtil/RenderToTextureStage>
#include "CreateShadowedScene.h"
using namespace osg;
class CreateShadowTextureCullCallback : public osg::NodeCallback
{
public:
CreateShadowTextureCullCallback(osg::Node* shadower,const osg::Vec3& position, const osg::Vec4& ambientLightColor, unsigned int textureUnit):
_shadower(shadower),
_position(position),
_ambientLightColor(ambientLightColor),
_unit(textureUnit),
_shadowState(new osg::StateSet)
{
_texture = new osg::Texture2D;
_texture->setFilter(osg::Texture2D::MIN_FILTER,osg::Texture2D::LINEAR);
_texture->setFilter(osg::Texture2D::MAG_FILTER,osg::Texture2D::LINEAR);
}
virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
{
osgUtil::CullVisitor* cullVisitor = dynamic_cast<osgUtil::CullVisitor*>(nv);
if (cullVisitor && (_texture.valid() && _shadower.valid()))
{
doPreRender(*node,*cullVisitor);
}
else
{
// must traverse the shadower
traverse(node,nv);
}
}
protected:
void doPreRender(osg::Node& node, osgUtil::CullVisitor& cv);
osg::ref_ptr<osg::Node> _shadower;
osg::ref_ptr<osg::Texture2D> _texture;
osg::Vec3 _position;
osg::Vec4 _ambientLightColor;
unsigned int _unit;
osg::ref_ptr<osg::StateSet> _shadowState;
// we need this to get round the order dependance
// of eye linear tex gen...
class MyTexGen : public TexGen
{
public:
void setMatrix(const osg::Matrix& matrix)
{
_matrix = matrix;
}
virtual void apply(osg::State& state) const
{
glPushMatrix();
glLoadMatrixf(_matrix.ptr());
TexGen::apply(state);
glPopMatrix();
}
osg::Matrix _matrix;
};
};
void CreateShadowTextureCullCallback::doPreRender(osg::Node& node, osgUtil::CullVisitor& cv)
{
const osg::BoundingSphere& bs = _shadower->getBound();
if (!bs.valid())
{
osg::notify(osg::WARN) << "bb invalid"<<_shadower.get()<<std::endl;
return;
}
// create the render to texture stage.
osg::ref_ptr<osgUtil::RenderToTextureStage> rtts = new osgUtil::RenderToTextureStage;
// set up lighting.
// currently ignore lights in the scene graph itself..
// will do later.
osgUtil::RenderStage* previous_stage = cv.getCurrentRenderBin()->_stage;
// set up the background color and clear mask.
rtts->setClearColor(osg::Vec4(1.0f,1.0f,1.0f,0.0f));
rtts->setClearMask(previous_stage->getClearMask());
// set up to charge the same RenderStageLighting is the parent previous stage.
rtts->setRenderStageLighting(previous_stage->getRenderStageLighting());
// record the render bin, to be restored after creation
// of the render to text
osgUtil::RenderBin* previousRenderBin = cv.getCurrentRenderBin();
// set the current renderbin to be the newly created stage.
cv.setCurrentRenderBin(rtts.get());
float centerDistance = (_position-bs.center()).length();
float znear = centerDistance+bs.radius();
float zfar = centerDistance-bs.radius();
float zNearRatio = 0.001f;
if (znear<zfar*zNearRatio) znear = zfar*zNearRatio;
// 2:1 aspect ratio as per flag geomtry below.
float top = (bs.radius()/centerDistance)*znear;
float right = top;
// set up projection.
osg::RefMatrix* projection = new osg::RefMatrix;
projection->makeFrustum(-right,right,-top,top,znear,zfar);
cv.pushProjectionMatrix(projection);
osg::RefMatrix* matrix = new osg::RefMatrix;
matrix->makeLookAt(_position,bs.center(),osg::Vec3(0.0f,1.0f,0.0f));
osg::Matrix MV = cv.getModelViewMatrix();
// compute the matrix which takes a vertex from local coords into tex coords
// will use this later to specify osg::TexGen..
osg::Matrix MVPT =
*matrix *
*projection *
osg::Matrix::translate(1.0,1.0,1.0) *
osg::Matrix::scale(0.5f,0.5f,0.5f);
cv.pushModelViewMatrix(matrix);
// make the material black for a shadow.
osg::Material* material = new osg::Material;
material->setAmbient(osg::Material::FRONT_AND_BACK,_ambientLightColor);
material->setDiffuse(osg::Material::FRONT_AND_BACK,osg::Vec4(0.0f,0.0f,0.0f,1.0f));
material->setEmission(osg::Material::FRONT_AND_BACK,osg::Vec4(0.0f,0.0f,0.0f,1.0f));
material->setShininess(osg::Material::FRONT_AND_BACK,0.0f);
_shadowState->setAttribute(material,osg::StateAttribute::OVERRIDE);
cv.pushStateSet(_shadowState.get());
{
// traverse the shadower
_shadower->accept(cv);
}
cv.popStateSet();
// restore the previous model view matrix.
cv.popModelViewMatrix();
// restore the previous model view matrix.
cv.popProjectionMatrix();
// restore the previous renderbin.
cv.setCurrentRenderBin(previousRenderBin);
if (rtts->_renderGraphList.size()==0 && rtts->_bins.size()==0)
{
// getting to this point means that all the shadower has been
// culled by small feature culling or is beyond LOD ranges.
return;
}
int height = 256;
int width = 256;
const osg::Viewport& viewport = *cv.getViewport();
// offset the impostor viewport from the center of the main window
// viewport as often the edges of the viewport might be obscured by
// other windows, which can cause image/reading writing problems.
int center_x = viewport.x()+viewport.width()/2;
int center_y = viewport.y()+viewport.height()/2;
osg::Viewport* new_viewport = new osg::Viewport;
new_viewport->setViewport(center_x-width/2,center_y-height/2,width,height);
rtts->setViewport(new_viewport);
_shadowState->setAttribute(new_viewport);
// and the render to texture stage to the current stages
// dependancy list.
cv.getCurrentRenderBin()->_stage->addToDependencyList(rtts.get());
// if one exist attach texture to the RenderToTextureStage.
if (_texture.valid()) rtts->setTexture(_texture.get());
// set up the stateset to decorate the shadower with the shadow texture
// with the appropriate tex gen coords.
osg::StateSet* stateset = new osg::StateSet;
MyTexGen* texgen = new MyTexGen;
texgen->setMatrix(MV);
texgen->setMode(osg::TexGen::EYE_LINEAR);
texgen->setPlane(osg::TexGen::S,osg::Plane(MVPT(0,0),MVPT(1,0),MVPT(2,0),MVPT(3,0)));
texgen->setPlane(osg::TexGen::T,osg::Plane(MVPT(0,1),MVPT(1,1),MVPT(2,1),MVPT(3,1)));
texgen->setPlane(osg::TexGen::R,osg::Plane(MVPT(0,2),MVPT(1,2),MVPT(2,2),MVPT(3,2)));
texgen->setPlane(osg::TexGen::Q,osg::Plane(MVPT(0,3),MVPT(1,3),MVPT(2,3),MVPT(3,3)));
stateset->setTextureAttributeAndModes(_unit,_texture.get(),osg::StateAttribute::ON);
stateset->setTextureAttribute(_unit,texgen);
stateset->setTextureMode(_unit,GL_TEXTURE_GEN_S,osg::StateAttribute::ON);
stateset->setTextureMode(_unit,GL_TEXTURE_GEN_T,osg::StateAttribute::ON);
stateset->setTextureMode(_unit,GL_TEXTURE_GEN_R,osg::StateAttribute::ON);
stateset->setTextureMode(_unit,GL_TEXTURE_GEN_Q,osg::StateAttribute::ON);
cv.pushStateSet(stateset);
// must traverse the shadower
traverse(&node,&cv);
cv.popStateSet();
}
// set up a light source with the shadower and shodower subgraphs below it
// with the appropriate callbacks set up.
osg::Group* createShadowedScene(osg::Node* shadower,osg::Node* shadowed,const osg::Vec3& lightPosition,float radius,unsigned int textureUnit)
{
osg::LightSource* lightgroup = new osg::LightSource;
osg::Light* light = new osg::Light;
light->setPosition(osg::Vec4(lightPosition,1.0f));
light->setLightNum(0);
lightgroup->setLight(light);
osg::Vec4 ambientLightColor(0.1f,0.1f,0.1f,1.0f);
// add the shadower
lightgroup->addChild(shadower);
// add the shadowed with the callback to generate the shadow texture.
shadowed->setCullCallback(new CreateShadowTextureCullCallback(shadower,lightPosition,ambientLightColor,textureUnit));
lightgroup->addChild(shadowed);
osg::Geode* lightgeode = new osg::Geode;
lightgeode->getOrCreateStateSet()->setMode(GL_LIGHTING,osg::StateAttribute::OFF);
lightgeode->addDrawable(new osg::ShapeDrawable(new osg::Sphere(lightPosition,radius)));
lightgroup->addChild(lightgeode);
return lightgroup;
}
<commit_msg>Changed the shadow texture implemention to use CLAMP_TO_BORDER for the WRAP_S and _T modes. Also set the border colour to 1,1,1,1 to ensure problem blending.<commit_after>#include <osg/Texture2D>
#include <osg/TexGen>
#include <osg/Material>
#include <osg/LightSource>
#include <osg/Geode>
#include <osg/ShapeDrawable>
#include <osgUtil/CullVisitor>
#include <osgUtil/RenderToTextureStage>
#include "CreateShadowedScene.h"
using namespace osg;
class CreateShadowTextureCullCallback : public osg::NodeCallback
{
public:
CreateShadowTextureCullCallback(osg::Node* shadower,const osg::Vec3& position, const osg::Vec4& ambientLightColor, unsigned int textureUnit):
_shadower(shadower),
_position(position),
_ambientLightColor(ambientLightColor),
_unit(textureUnit),
_shadowState(new osg::StateSet)
{
_texture = new osg::Texture2D;
_texture->setFilter(osg::Texture2D::MIN_FILTER,osg::Texture2D::LINEAR);
_texture->setFilter(osg::Texture2D::MAG_FILTER,osg::Texture2D::LINEAR);
_texture->setWrap(osg::Texture2D::WRAP_S,osg::Texture2D::CLAMP_TO_BORDER);
_texture->setWrap(osg::Texture2D::WRAP_T,osg::Texture2D::CLAMP_TO_BORDER);
_texture->setBorderColor(osg::Vec4(1.0f,1.0f,1.0f,1.0f));
}
virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
{
osgUtil::CullVisitor* cullVisitor = dynamic_cast<osgUtil::CullVisitor*>(nv);
if (cullVisitor && (_texture.valid() && _shadower.valid()))
{
doPreRender(*node,*cullVisitor);
}
else
{
// must traverse the shadower
traverse(node,nv);
}
}
protected:
void doPreRender(osg::Node& node, osgUtil::CullVisitor& cv);
osg::ref_ptr<osg::Node> _shadower;
osg::ref_ptr<osg::Texture2D> _texture;
osg::Vec3 _position;
osg::Vec4 _ambientLightColor;
unsigned int _unit;
osg::ref_ptr<osg::StateSet> _shadowState;
// we need this to get round the order dependance
// of eye linear tex gen...
class MyTexGen : public TexGen
{
public:
void setMatrix(const osg::Matrix& matrix)
{
_matrix = matrix;
}
virtual void apply(osg::State& state) const
{
glPushMatrix();
glLoadMatrixf(_matrix.ptr());
TexGen::apply(state);
glPopMatrix();
}
osg::Matrix _matrix;
};
};
void CreateShadowTextureCullCallback::doPreRender(osg::Node& node, osgUtil::CullVisitor& cv)
{
const osg::BoundingSphere& bs = _shadower->getBound();
if (!bs.valid())
{
osg::notify(osg::WARN) << "bb invalid"<<_shadower.get()<<std::endl;
return;
}
// create the render to texture stage.
osg::ref_ptr<osgUtil::RenderToTextureStage> rtts = new osgUtil::RenderToTextureStage;
// set up lighting.
// currently ignore lights in the scene graph itself..
// will do later.
osgUtil::RenderStage* previous_stage = cv.getCurrentRenderBin()->_stage;
// set up the background color and clear mask.
rtts->setClearColor(osg::Vec4(1.0f,1.0f,1.0f,0.0f));
rtts->setClearMask(previous_stage->getClearMask());
// set up to charge the same RenderStageLighting is the parent previous stage.
rtts->setRenderStageLighting(previous_stage->getRenderStageLighting());
// record the render bin, to be restored after creation
// of the render to text
osgUtil::RenderBin* previousRenderBin = cv.getCurrentRenderBin();
// set the current renderbin to be the newly created stage.
cv.setCurrentRenderBin(rtts.get());
float centerDistance = (_position-bs.center()).length();
float znear = centerDistance+bs.radius();
float zfar = centerDistance-bs.radius();
float zNearRatio = 0.001f;
if (znear<zfar*zNearRatio) znear = zfar*zNearRatio;
// 2:1 aspect ratio as per flag geomtry below.
float top = (bs.radius()/centerDistance)*znear;
float right = top;
// set up projection.
osg::RefMatrix* projection = new osg::RefMatrix;
projection->makeFrustum(-right,right,-top,top,znear,zfar);
cv.pushProjectionMatrix(projection);
osg::RefMatrix* matrix = new osg::RefMatrix;
matrix->makeLookAt(_position,bs.center(),osg::Vec3(0.0f,1.0f,0.0f));
osg::Matrix MV = cv.getModelViewMatrix();
// compute the matrix which takes a vertex from local coords into tex coords
// will use this later to specify osg::TexGen..
osg::Matrix MVPT =
*matrix *
*projection *
osg::Matrix::translate(1.0,1.0,1.0) *
osg::Matrix::scale(0.5f,0.5f,0.5f);
cv.pushModelViewMatrix(matrix);
// make the material black for a shadow.
osg::Material* material = new osg::Material;
material->setAmbient(osg::Material::FRONT_AND_BACK,_ambientLightColor);
material->setDiffuse(osg::Material::FRONT_AND_BACK,osg::Vec4(0.0f,0.0f,0.0f,1.0f));
material->setEmission(osg::Material::FRONT_AND_BACK,osg::Vec4(0.0f,0.0f,0.0f,1.0f));
material->setShininess(osg::Material::FRONT_AND_BACK,0.0f);
_shadowState->setAttribute(material,osg::StateAttribute::OVERRIDE);
cv.pushStateSet(_shadowState.get());
{
// traverse the shadower
_shadower->accept(cv);
}
cv.popStateSet();
// restore the previous model view matrix.
cv.popModelViewMatrix();
// restore the previous model view matrix.
cv.popProjectionMatrix();
// restore the previous renderbin.
cv.setCurrentRenderBin(previousRenderBin);
if (rtts->_renderGraphList.size()==0 && rtts->_bins.size()==0)
{
// getting to this point means that all the shadower has been
// culled by small feature culling or is beyond LOD ranges.
return;
}
int height = 256;
int width = 256;
const osg::Viewport& viewport = *cv.getViewport();
// offset the impostor viewport from the center of the main window
// viewport as often the edges of the viewport might be obscured by
// other windows, which can cause image/reading writing problems.
int center_x = viewport.x()+viewport.width()/2;
int center_y = viewport.y()+viewport.height()/2;
osg::Viewport* new_viewport = new osg::Viewport;
new_viewport->setViewport(center_x-width/2,center_y-height/2,width,height);
rtts->setViewport(new_viewport);
_shadowState->setAttribute(new_viewport);
// and the render to texture stage to the current stages
// dependancy list.
cv.getCurrentRenderBin()->_stage->addToDependencyList(rtts.get());
// if one exist attach texture to the RenderToTextureStage.
if (_texture.valid()) rtts->setTexture(_texture.get());
// set up the stateset to decorate the shadower with the shadow texture
// with the appropriate tex gen coords.
osg::StateSet* stateset = new osg::StateSet;
MyTexGen* texgen = new MyTexGen;
texgen->setMatrix(MV);
texgen->setMode(osg::TexGen::EYE_LINEAR);
texgen->setPlane(osg::TexGen::S,osg::Plane(MVPT(0,0),MVPT(1,0),MVPT(2,0),MVPT(3,0)));
texgen->setPlane(osg::TexGen::T,osg::Plane(MVPT(0,1),MVPT(1,1),MVPT(2,1),MVPT(3,1)));
texgen->setPlane(osg::TexGen::R,osg::Plane(MVPT(0,2),MVPT(1,2),MVPT(2,2),MVPT(3,2)));
texgen->setPlane(osg::TexGen::Q,osg::Plane(MVPT(0,3),MVPT(1,3),MVPT(2,3),MVPT(3,3)));
stateset->setTextureAttributeAndModes(_unit,_texture.get(),osg::StateAttribute::ON);
stateset->setTextureAttribute(_unit,texgen);
stateset->setTextureMode(_unit,GL_TEXTURE_GEN_S,osg::StateAttribute::ON);
stateset->setTextureMode(_unit,GL_TEXTURE_GEN_T,osg::StateAttribute::ON);
stateset->setTextureMode(_unit,GL_TEXTURE_GEN_R,osg::StateAttribute::ON);
stateset->setTextureMode(_unit,GL_TEXTURE_GEN_Q,osg::StateAttribute::ON);
cv.pushStateSet(stateset);
// must traverse the shadower
traverse(&node,&cv);
cv.popStateSet();
}
// set up a light source with the shadower and shodower subgraphs below it
// with the appropriate callbacks set up.
osg::Group* createShadowedScene(osg::Node* shadower,osg::Node* shadowed,const osg::Vec3& lightPosition,float radius,unsigned int textureUnit)
{
osg::LightSource* lightgroup = new osg::LightSource;
osg::Light* light = new osg::Light;
light->setPosition(osg::Vec4(lightPosition,1.0f));
light->setLightNum(0);
lightgroup->setLight(light);
osg::Vec4 ambientLightColor(0.1f,0.1f,0.1f,1.0f);
// add the shadower
lightgroup->addChild(shadower);
// add the shadowed with the callback to generate the shadow texture.
shadowed->setCullCallback(new CreateShadowTextureCullCallback(shadower,lightPosition,ambientLightColor,textureUnit));
lightgroup->addChild(shadowed);
osg::Geode* lightgeode = new osg::Geode;
lightgeode->getOrCreateStateSet()->setMode(GL_LIGHTING,osg::StateAttribute::OFF);
lightgeode->addDrawable(new osg::ShapeDrawable(new osg::Sphere(lightPosition,radius)));
lightgroup->addChild(lightgeode);
return lightgroup;
}
<|endoftext|>
|
<commit_before>#include "test.h"
#include "lib/Function.h"
#include "Codegen.h"
#include "ASTNode.h"
#include "lib/Runtime.h"
#include "x86_64/Disassembler.h"
using namespace snow;
using namespace ast;
#include <iostream>
TEST_SUITE(Codegen);
// convenience for building ASTs
#define _function new FunctionDefinition
#define _assign new Assignment
#define _ident new Identifier
#define _call new Call
#define _seq new Sequence
#define _lit_int(val) new Literal(#val, Literal::INTEGER_TYPE)
static SymbolTable table = SymbolTable();
static Handle<Function> compile(RefPtr<FunctionDefinition> def) {
RefPtr<Codegen> codegen = Codegen::create(*def);
table["snow_eval_truth"] = (void*)snow::eval_truth;
table["snow_call"] = (void*)snow::call;
table["snow_get"] = (void*)snow::get;
table["snow_set"] = (void*)snow::set;
table["snow_enter_scope"] = (void*)snow::enter_scope;
table["snow_leave_scope"] = (void*)snow::leave_scope;
table["snow_get_local"] = (void*)snow::get_local;
table["snow_set_parent_scope"] = (void*)snow::set_parent_scope;
RefPtr<CompiledCode> cc = codegen->compile();
cc->export_symbols(table);
cc->link(table);
cc->make_executable();
return new Function(cc);
}
static void dump_disasm(std::ostream& os, Handle<Function> func) {
os << std::endl;
os << x86_64::Disassembler::disassemble(*func->code(), table);
}
TEST_CASE(simple_add) {
RefPtr<FunctionDefinition> def = _function(
_assign(_ident("a"), _lit_int(123)),
_assign(_ident("b"), _lit_int(456)),
_call(_ident("a"), _ident("+"), _seq(_ident("b")))
);
Handle<Function> f = compile(def);
ValueHandle ret = snow::call(NULL, f, 0);
TEST_EQ(integer(ret), 579);
}
TEST_CASE(simple_closure) {
RefPtr<FunctionDefinition> def = _function(
_assign(_ident("a"), _lit_int(123)),
_assign(_ident("func"),
_function(
_assign(_ident("b"), _lit_int(456)),
_call(_ident("b"), _ident("+"), _seq(_ident("a")))
)
),
_call(_ident("func"))
);
Handle<Function> f = compile(def);
//dump_disasm(std::cout, f);
ValueHandle ret = snow::call(NULL, f, 0);
TEST_EQ(integer(ret), 579);
}
<commit_msg>codegen test: new Get and Set nodes<commit_after>#include "test.h"
#include "lib/Function.h"
#include "Codegen.h"
#include "ASTNode.h"
#include "lib/Runtime.h"
#include "x86_64/Disassembler.h"
using namespace snow;
using namespace ast;
#include <iostream>
TEST_SUITE(Codegen);
// convenience for building ASTs
#define _function new FunctionDefinition
#define _assign new Assignment
#define _ident new Identifier
#define _call new Call
#define _seq new Sequence
#define _lit_int(val) new Literal(#val, Literal::INTEGER_TYPE)
#define _get new Get
#define _set new Set
static SymbolTable table = SymbolTable();
static Handle<Function> compile(RefPtr<FunctionDefinition> def) {
RefPtr<Codegen> codegen = Codegen::create(*def);
table["snow_eval_truth"] = (void*)snow::eval_truth;
table["snow_call"] = (void*)snow::call;
table["snow_get"] = (void*)snow::get;
table["snow_set"] = (void*)snow::set;
table["snow_enter_scope"] = (void*)snow::enter_scope;
table["snow_leave_scope"] = (void*)snow::leave_scope;
table["snow_get_local"] = (void*)snow::get_local;
table["snow_set_parent_scope"] = (void*)snow::set_parent_scope;
RefPtr<CompiledCode> cc = codegen->compile();
cc->export_symbols(table);
cc->link(table);
cc->make_executable();
return new Function(cc);
}
static void dump_disasm(std::ostream& os, Handle<Function> func) {
os << std::endl;
os << x86_64::Disassembler::disassemble(*func->code(), table);
}
TEST_CASE(simple_add) {
RefPtr<FunctionDefinition> def = _function(
_assign(_ident("a"), _lit_int(123)),
_assign(_ident("b"), _lit_int(456)),
_call(_ident("a"), _ident("+"), _seq(_ident("b")))
);
Handle<Function> f = compile(def);
ValueHandle ret = snow::call(NULL, f, 0);
TEST_EQ(integer(ret), 579);
}
TEST_CASE(simple_closure) {
RefPtr<FunctionDefinition> def = _function(
_assign(_ident("a"), _lit_int(123)),
_assign(_ident("func"),
_function(
_assign(_ident("b"), _lit_int(456)),
_call(_ident("b"), _ident("+"), _seq(_ident("a")))
)
),
_call(_ident("func"))
);
Handle<Function> f = compile(def);
//dump_disasm(std::cout, f);
ValueHandle ret = snow::call(NULL, f, 0);
TEST_EQ(integer(ret), 579);
}
TEST_CASE(object_get) {
RefPtr<FunctionDefinition> def = _function(
_get(_ident("obj"), _ident("member"))
);
def->arguments.push_back(_ident("obj"));
Handle<Object> obj = new Object;
obj->set("member", value(456LL));
Handle<Function> f = compile(def);
ValueHandle ret = snow::call(NULL, f, 1, obj.value());
TEST_EQ(integer(ret), 456LL);
}
TEST_CASE(object_set) {
RefPtr<FunctionDefinition> def = _function(
_set(_ident("obj"), _ident("member"), _ident("value"))
);
def->arguments.push_back(_ident("obj"));
def->arguments.push_back(_ident("value"));
Handle<Object> obj = new Object;
Handle<Function> f = compile(def);
ValueHandle ret = snow::call(NULL, f, 2, obj.value(), value(456LL));
TEST_EQ(integer(obj->get("member")), 456LL);
}
<|endoftext|>
|
<commit_before>#include "qwindowcompositor.h"
#include <QMouseEvent>
#include <QKeyEvent>
#include <QTouchEvent>
QWindowCompositor::QWindowCompositor(QOpenGLWindow *window)
: WaylandCompositor(window)
, m_window(window)
, m_textureBlitter(0)
, m_renderScheduler(this)
, m_draggingWindow(0)
, m_dragKeyIsPressed(false)
{
enableSubSurfaceExtension();
m_window->makeCurrent();
initializeGLFunctions();
m_textureCache = new QOpenGLTextureCache(m_window->context());
m_textureBlitter = new TextureBlitter();
m_backgroundImage = QImage(QLatin1String(":/background.jpg"));
m_renderScheduler.setSingleShot(true);
connect(&m_renderScheduler,SIGNAL(timeout()),this,SLOT(render()));
glGenFramebuffers(1,&m_surface_fbo);
window->installEventFilter(this);
setRetainedSelectionEnabled(true);
m_renderScheduler.start(0);
}
void QWindowCompositor::surfaceDestroyed(QObject *object)
{
WaylandSurface *surface = static_cast<WaylandSurface *>(object);
m_surfaces.removeOne(surface);
if (inputFocus() == surface || !inputFocus()) // typically reset to 0 already in Compositor::surfaceDestroyed()
setInputFocus(m_surfaces.isEmpty() ? 0 : m_surfaces.last());
m_renderScheduler.start(0);
}
void QWindowCompositor::surfaceMapped()
{
WaylandSurface *surface = qobject_cast<WaylandSurface *>(sender());
QPoint pos;
if (!m_surfaces.contains(surface)) {
uint px = 1 + (qrand() % (m_window->width() - surface->size().width() - 2));
uint py = 1 + (qrand() % (m_window->height() - surface->size().height() - 2));
pos = QPoint(px, py);
surface->setPos(pos);
} else {
surface->setPos(window()->geometry().topLeft());
m_surfaces.removeOne(surface);
}
m_surfaces.append(surface);
setInputFocus(surface);
m_renderScheduler.start(0);
}
void QWindowCompositor::surfaceDamaged(const QRect &rect)
{
WaylandSurface *surface = qobject_cast<WaylandSurface *>(sender());
surfaceDamaged(surface, rect);
}
void QWindowCompositor::surfaceDamaged(WaylandSurface *surface, const QRect &rect)
{
Q_UNUSED(surface)
Q_UNUSED(rect)
m_renderScheduler.start(0);
}
void QWindowCompositor::surfaceCreated(WaylandSurface *surface)
{
connect(surface, SIGNAL(destroyed(QObject *)), this, SLOT(surfaceDestroyed(QObject *)));
connect(surface, SIGNAL(mapped()), this, SLOT(surfaceMapped()));
connect(surface, SIGNAL(damaged(const QRect &)), this, SLOT(surfaceDamaged(const QRect &)));
m_renderScheduler.start(0);
}
QPointF QWindowCompositor::toSurface(WaylandSurface *surface, const QPointF &pos) const
{
return pos - surface->pos();
}
WaylandSurface *QWindowCompositor::surfaceAt(const QPoint &point, QPoint *local)
{
for (int i = m_surfaces.size() - 1; i >= 0; --i) {
WaylandSurface *surface = m_surfaces.at(i);
QRect geo(surface->pos().toPoint(),surface->size());
if (geo.contains(point)) {
if (local)
*local = toSurface(surface, point).toPoint();
return surface;
}
}
return 0;
}
GLuint QWindowCompositor::composeSurface(WaylandSurface *surface)
{
GLuint texture = 0;
glBindFramebuffer(GL_FRAMEBUFFER, m_surface_fbo);
if (surface->type() == WaylandSurface::Shm) {
texture = m_textureCache->bindTexture(QOpenGLContext::currentContext(),surface->image());
} else {
texture = surface->texture(QOpenGLContext::currentContext());
}
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
GL_TEXTURE_2D, texture, 0);
paintChildren(surface,surface);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
GL_TEXTURE_2D,0, 0);
glBindFramebuffer(GL_FRAMEBUFFER,0);
return texture;
}
void QWindowCompositor::paintChildren(WaylandSurface *surface, WaylandSurface *window) {
if (surface->subSurfaces().size() == 0)
return;
QLinkedListIterator<WaylandSurface *> i(surface->subSurfaces());
while (i.hasNext()) {
WaylandSurface *subSurface = i.next();
QPointF p = subSurface->mapTo(window,QPointF(0,0));
if (subSurface->size().isValid()) {
GLuint texture = 0;
if (subSurface->type() == WaylandSurface::Texture) {
texture = subSurface->texture(QOpenGLContext::currentContext());
} else if (surface->type() == WaylandSurface::Shm ) {
texture = m_textureCache->bindTexture(QOpenGLContext::currentContext(),surface->image());
}
QRect geo(p.toPoint(),subSurface->size());
m_textureBlitter->drawTexture(texture,geo,window->size(),0,window->isYInverted(),subSurface->isYInverted());
}
paintChildren(subSurface,window);
}
}
void QWindowCompositor::render()
{
m_window->makeCurrent();
m_backgroundTexture = m_textureCache->bindTexture(QOpenGLContext::currentContext(),m_backgroundImage);
m_textureBlitter->bind();
//Draw the background Image texture
int w = m_window->width();
int h = m_window->height();
QSize imageSize = m_backgroundImage.size();
for (int y = 0; y < h; y += imageSize.height()) {
for (int x = 0; x < w; x += imageSize.width()) {
m_textureBlitter->drawTexture(m_backgroundTexture,QRect(QPoint(x, y),imageSize),window()->size(), 0,true,true);
}
}
foreach (WaylandSurface *surface, m_surfaces) {
GLuint texture = composeSurface(surface);
QRect geo(surface->pos().toPoint(),surface->size());
m_textureBlitter->drawTexture(texture,geo,m_window->size(),0,false,surface->isYInverted());
}
m_textureBlitter->release();
frameFinished();
glFinish();
m_window->swapBuffers();
}
bool QWindowCompositor::eventFilter(QObject *obj, QEvent *event)
{
if (obj != m_window)
return false;
switch (event->type()) {
case QEvent::Expose:
m_renderScheduler.start(0);
break;
case QEvent::MouseButtonPress: {
QPoint local;
QMouseEvent *me = static_cast<QMouseEvent *>(event);
WaylandSurface *targetSurface = surfaceAt(me->pos(), &local);
if (targetSurface) {
if (m_dragKeyIsPressed) {
m_draggingWindow = targetSurface;
m_drag_diff = local;
} else {
if (inputFocus() != targetSurface) {
setInputFocus(targetSurface);
m_surfaces.removeOne(targetSurface);
m_surfaces.append(targetSurface);
m_renderScheduler.start(0);
}
targetSurface->sendMousePressEvent(local, me->button());
}
}
break;
}
case QEvent::MouseButtonRelease: {
WaylandSurface *targetSurface = inputFocus();
if (m_draggingWindow) {
m_draggingWindow = 0;
m_drag_diff = QPoint();
} else if (targetSurface) {
QMouseEvent *me = static_cast<QMouseEvent *>(event);
targetSurface->sendMouseReleaseEvent(toSurface(targetSurface, me->pos()).toPoint(), me->button());
}
break;
}
case QEvent::MouseMove: {
QMouseEvent *me = static_cast<QMouseEvent *>(event);
if (m_draggingWindow) {
m_draggingWindow->setPos(me->posF() - m_drag_diff);
m_renderScheduler.start(0);
} else {
QPoint local;
WaylandSurface *targetSurface = surfaceAt(me->pos(), &local);
if (targetSurface) {
targetSurface->sendMouseMoveEvent(local);
}
}
}
case QEvent::KeyPress: {
QKeyEvent *ke = static_cast<QKeyEvent *>(event);
if (ke->key() == Qt::Key_Meta || ke->key() == Qt::Key_Super_L) {
m_dragKeyIsPressed = true;
}
WaylandSurface *targetSurface = inputFocus();
if (targetSurface)
targetSurface->sendKeyPressEvent(ke->nativeScanCode());
break;
}
case QEvent::KeyRelease: {
QKeyEvent *ke = static_cast<QKeyEvent *>(event);
if (ke->key() == Qt::Key_Meta || ke->key() == Qt::Key_Super_L) {
m_dragKeyIsPressed = false;
}
WaylandSurface *targetSurface = inputFocus();
if (targetSurface)
targetSurface->sendKeyReleaseEvent(ke->nativeScanCode());
break;
}
case QEvent::TouchBegin:
case QEvent::TouchUpdate:
case QEvent::TouchEnd:
{
QSet<WaylandSurface *> targets;
QTouchEvent *te = static_cast<QTouchEvent *>(event);
QList<QTouchEvent::TouchPoint> points = te->touchPoints();
for (int i = 0; i < points.count(); ++i) {
const QTouchEvent::TouchPoint &tp(points.at(i));
QPoint local;
WaylandSurface *targetSurface = surfaceAt(tp.pos().toPoint(), &local);
if (targetSurface) {
targetSurface->sendTouchPointEvent(tp.id(), local.x(), local.y(), tp.state());
targets.insert(targetSurface);
}
}
foreach (WaylandSurface *surface, targets)
surface->sendTouchFrameEvent();
break;
}
default:
break;
}
return false;
}
<commit_msg>Add an option to qwindow-compositor for disabling random positioning<commit_after>#include "qwindowcompositor.h"
#include <QMouseEvent>
#include <QKeyEvent>
#include <QTouchEvent>
QWindowCompositor::QWindowCompositor(QOpenGLWindow *window)
: WaylandCompositor(window)
, m_window(window)
, m_textureBlitter(0)
, m_renderScheduler(this)
, m_draggingWindow(0)
, m_dragKeyIsPressed(false)
{
enableSubSurfaceExtension();
m_window->makeCurrent();
initializeGLFunctions();
m_textureCache = new QOpenGLTextureCache(m_window->context());
m_textureBlitter = new TextureBlitter();
m_backgroundImage = QImage(QLatin1String(":/background.jpg"));
m_renderScheduler.setSingleShot(true);
connect(&m_renderScheduler,SIGNAL(timeout()),this,SLOT(render()));
glGenFramebuffers(1,&m_surface_fbo);
window->installEventFilter(this);
setRetainedSelectionEnabled(true);
m_renderScheduler.start(0);
}
void QWindowCompositor::surfaceDestroyed(QObject *object)
{
WaylandSurface *surface = static_cast<WaylandSurface *>(object);
m_surfaces.removeOne(surface);
if (inputFocus() == surface || !inputFocus()) // typically reset to 0 already in Compositor::surfaceDestroyed()
setInputFocus(m_surfaces.isEmpty() ? 0 : m_surfaces.last());
m_renderScheduler.start(0);
}
void QWindowCompositor::surfaceMapped()
{
WaylandSurface *surface = qobject_cast<WaylandSurface *>(sender());
QPoint pos;
if (!m_surfaces.contains(surface)) {
uint px = 0;
uint py = 0;
if (!QCoreApplication::arguments().contains(QLatin1String("-stickytopleft"))) {
px = 1 + (qrand() % (m_window->width() - surface->size().width() - 2));
py = 1 + (qrand() % (m_window->height() - surface->size().height() - 2));
}
pos = QPoint(px, py);
surface->setPos(pos);
} else {
surface->setPos(window()->geometry().topLeft());
m_surfaces.removeOne(surface);
}
m_surfaces.append(surface);
setInputFocus(surface);
m_renderScheduler.start(0);
}
void QWindowCompositor::surfaceDamaged(const QRect &rect)
{
WaylandSurface *surface = qobject_cast<WaylandSurface *>(sender());
surfaceDamaged(surface, rect);
}
void QWindowCompositor::surfaceDamaged(WaylandSurface *surface, const QRect &rect)
{
Q_UNUSED(surface)
Q_UNUSED(rect)
m_renderScheduler.start(0);
}
void QWindowCompositor::surfaceCreated(WaylandSurface *surface)
{
connect(surface, SIGNAL(destroyed(QObject *)), this, SLOT(surfaceDestroyed(QObject *)));
connect(surface, SIGNAL(mapped()), this, SLOT(surfaceMapped()));
connect(surface, SIGNAL(damaged(const QRect &)), this, SLOT(surfaceDamaged(const QRect &)));
m_renderScheduler.start(0);
}
QPointF QWindowCompositor::toSurface(WaylandSurface *surface, const QPointF &pos) const
{
return pos - surface->pos();
}
WaylandSurface *QWindowCompositor::surfaceAt(const QPoint &point, QPoint *local)
{
for (int i = m_surfaces.size() - 1; i >= 0; --i) {
WaylandSurface *surface = m_surfaces.at(i);
QRect geo(surface->pos().toPoint(),surface->size());
if (geo.contains(point)) {
if (local)
*local = toSurface(surface, point).toPoint();
return surface;
}
}
return 0;
}
GLuint QWindowCompositor::composeSurface(WaylandSurface *surface)
{
GLuint texture = 0;
glBindFramebuffer(GL_FRAMEBUFFER, m_surface_fbo);
if (surface->type() == WaylandSurface::Shm) {
texture = m_textureCache->bindTexture(QOpenGLContext::currentContext(),surface->image());
} else {
texture = surface->texture(QOpenGLContext::currentContext());
}
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
GL_TEXTURE_2D, texture, 0);
paintChildren(surface,surface);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
GL_TEXTURE_2D,0, 0);
glBindFramebuffer(GL_FRAMEBUFFER,0);
return texture;
}
void QWindowCompositor::paintChildren(WaylandSurface *surface, WaylandSurface *window) {
if (surface->subSurfaces().size() == 0)
return;
QLinkedListIterator<WaylandSurface *> i(surface->subSurfaces());
while (i.hasNext()) {
WaylandSurface *subSurface = i.next();
QPointF p = subSurface->mapTo(window,QPointF(0,0));
if (subSurface->size().isValid()) {
GLuint texture = 0;
if (subSurface->type() == WaylandSurface::Texture) {
texture = subSurface->texture(QOpenGLContext::currentContext());
} else if (surface->type() == WaylandSurface::Shm ) {
texture = m_textureCache->bindTexture(QOpenGLContext::currentContext(),surface->image());
}
QRect geo(p.toPoint(),subSurface->size());
m_textureBlitter->drawTexture(texture,geo,window->size(),0,window->isYInverted(),subSurface->isYInverted());
}
paintChildren(subSurface,window);
}
}
void QWindowCompositor::render()
{
m_window->makeCurrent();
m_backgroundTexture = m_textureCache->bindTexture(QOpenGLContext::currentContext(),m_backgroundImage);
m_textureBlitter->bind();
//Draw the background Image texture
int w = m_window->width();
int h = m_window->height();
QSize imageSize = m_backgroundImage.size();
for (int y = 0; y < h; y += imageSize.height()) {
for (int x = 0; x < w; x += imageSize.width()) {
m_textureBlitter->drawTexture(m_backgroundTexture,QRect(QPoint(x, y),imageSize),window()->size(), 0,true,true);
}
}
foreach (WaylandSurface *surface, m_surfaces) {
GLuint texture = composeSurface(surface);
QRect geo(surface->pos().toPoint(),surface->size());
m_textureBlitter->drawTexture(texture,geo,m_window->size(),0,false,surface->isYInverted());
}
m_textureBlitter->release();
frameFinished();
glFinish();
m_window->swapBuffers();
}
bool QWindowCompositor::eventFilter(QObject *obj, QEvent *event)
{
if (obj != m_window)
return false;
switch (event->type()) {
case QEvent::Expose:
m_renderScheduler.start(0);
break;
case QEvent::MouseButtonPress: {
QPoint local;
QMouseEvent *me = static_cast<QMouseEvent *>(event);
WaylandSurface *targetSurface = surfaceAt(me->pos(), &local);
if (targetSurface) {
if (m_dragKeyIsPressed) {
m_draggingWindow = targetSurface;
m_drag_diff = local;
} else {
if (inputFocus() != targetSurface) {
setInputFocus(targetSurface);
m_surfaces.removeOne(targetSurface);
m_surfaces.append(targetSurface);
m_renderScheduler.start(0);
}
targetSurface->sendMousePressEvent(local, me->button());
}
}
break;
}
case QEvent::MouseButtonRelease: {
WaylandSurface *targetSurface = inputFocus();
if (m_draggingWindow) {
m_draggingWindow = 0;
m_drag_diff = QPoint();
} else if (targetSurface) {
QMouseEvent *me = static_cast<QMouseEvent *>(event);
targetSurface->sendMouseReleaseEvent(toSurface(targetSurface, me->pos()).toPoint(), me->button());
}
break;
}
case QEvent::MouseMove: {
QMouseEvent *me = static_cast<QMouseEvent *>(event);
if (m_draggingWindow) {
m_draggingWindow->setPos(me->posF() - m_drag_diff);
m_renderScheduler.start(0);
} else {
QPoint local;
WaylandSurface *targetSurface = surfaceAt(me->pos(), &local);
if (targetSurface) {
targetSurface->sendMouseMoveEvent(local);
}
}
}
case QEvent::KeyPress: {
QKeyEvent *ke = static_cast<QKeyEvent *>(event);
if (ke->key() == Qt::Key_Meta || ke->key() == Qt::Key_Super_L) {
m_dragKeyIsPressed = true;
}
WaylandSurface *targetSurface = inputFocus();
if (targetSurface)
targetSurface->sendKeyPressEvent(ke->nativeScanCode());
break;
}
case QEvent::KeyRelease: {
QKeyEvent *ke = static_cast<QKeyEvent *>(event);
if (ke->key() == Qt::Key_Meta || ke->key() == Qt::Key_Super_L) {
m_dragKeyIsPressed = false;
}
WaylandSurface *targetSurface = inputFocus();
if (targetSurface)
targetSurface->sendKeyReleaseEvent(ke->nativeScanCode());
break;
}
case QEvent::TouchBegin:
case QEvent::TouchUpdate:
case QEvent::TouchEnd:
{
QSet<WaylandSurface *> targets;
QTouchEvent *te = static_cast<QTouchEvent *>(event);
QList<QTouchEvent::TouchPoint> points = te->touchPoints();
for (int i = 0; i < points.count(); ++i) {
const QTouchEvent::TouchPoint &tp(points.at(i));
QPoint local;
WaylandSurface *targetSurface = surfaceAt(tp.pos().toPoint(), &local);
if (targetSurface) {
targetSurface->sendTouchPointEvent(tp.id(), local.x(), local.y(), tp.state());
targets.insert(targetSurface);
}
}
foreach (WaylandSurface *surface, targets)
surface->sendTouchFrameEvent();
break;
}
default:
break;
}
return false;
}
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2004-2015 ZNC, see the NOTICE file for details.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <gtest/gtest.h>
#include <gmock/gmock.h>
#include <QDateTime>
#include <QProcess>
#include <QTcpServer>
#include <QTcpSocket>
#include <QTemporaryDir>
#include <QTextStream>
#include <memory>
#define Z do { if (::testing::Test::HasFatalFailure()) { std::cerr << "At: " << __FILE__ << ":" << __LINE__ << std::endl; return; } } while (0)
namespace {
template <typename Device>
class IO {
public:
IO(Device* device, bool verbose = false) : m_device(device), m_verbose(verbose) {}
virtual ~IO() {}
void ReadUntil(QByteArray pattern) {
auto deadline = QDateTime::currentDateTime().addSecs(30);
while (true) {
int search = m_readed.indexOf(pattern);
if (search != -1) {
m_readed.remove(0, search + pattern.length());
return;
}
if (m_readed.length() > pattern.length()) {
m_readed = m_readed.right(pattern.length());
}
const int timeout_ms = QDateTime::currentDateTime().msecsTo(deadline);
ASSERT_GT(timeout_ms, 0) << "Wanted:" << pattern.toStdString();
ASSERT_TRUE(m_device->waitForReadyRead(timeout_ms)) << "Wanted: " << pattern.toStdString();
QByteArray chunk = m_device->readAll();
if (m_verbose) {
std::cout << chunk.toStdString() << std::flush;
}
m_readed += chunk;
}
}
void Write(QString s = "", bool new_line = true) {
if (!m_device) return;
if (m_verbose) {
std::cout << s.toStdString() << std::flush;
if (new_line) {
std::cout << std::endl;
}
}
s += "\n";
{
QTextStream str(m_device);
str << s;
}
FlushIfCan(m_device);
}
void Close() {
m_device->close();
}
private:
// QTextStream doesn't flush QTcpSocket, and QIODevice doesn't have flush() at all...
static void FlushIfCan(QIODevice*) {}
static void FlushIfCan(QTcpSocket* sock) {
sock->flush();
}
Device* m_device;
bool m_verbose;
QByteArray m_readed;
};
template <typename Device>
IO<Device> WrapIO(Device* d) {
return IO<Device>(d);
}
using Socket = IO<QTcpSocket>;
class Process : public IO<QProcess> {
public:
Process(QString cmd, QStringList args, bool interactive) : IO(&m_proc, true) {
if (!interactive) {
m_proc.setProcessChannelMode(QProcess::ForwardedChannels);
}
m_proc.start(cmd, args);
}
~Process() {
if (m_kill) m_proc.terminate();
[this]() { ASSERT_TRUE(m_proc.waitForFinished()); }();
}
void ShouldFinishItself() {
m_kill = false;
}
private:
bool m_kill = true;
QProcess m_proc;
};
void WriteConfig(QString path) {
Process p("./znc", QStringList() << "--debug" << "--datadir" << path << "--makeconf", true);
p.ReadUntil("Listen on port");Z; p.Write("12345");
p.ReadUntil("Listen using SSL");Z; p.Write();
p.ReadUntil("IPv6");Z; p.Write();
p.ReadUntil("Username");Z; p.Write("user");
p.ReadUntil("password");Z; p.Write("hunter2", false);
p.ReadUntil("Confirm");Z; p.Write("hunter2", false);
p.ReadUntil("Nick [user]");Z; p.Write();
p.ReadUntil("Alternate nick [user_]");Z; p.Write();
p.ReadUntil("Ident [user]");Z; p.Write();
p.ReadUntil("Real name");Z; p.Write();
p.ReadUntil("Bind host");Z; p.Write();
p.ReadUntil("Set up a network?");Z; p.Write();
p.ReadUntil("Name [freenode]");Z; p.Write("test");
p.ReadUntil("Server host (host only)");Z; p.Write("127.0.0.1");
p.ReadUntil("Server uses SSL?");Z; p.Write();
p.ReadUntil("6667");Z; p.Write();
p.ReadUntil("password");Z; p.Write();
p.ReadUntil("channels");Z; p.Write();
p.ReadUntil("Launch ZNC now?");Z; p.Write("no");
p.ShouldFinishItself();
}
TEST(Config, AlreadyExists) {
QTemporaryDir dir;
WriteConfig(dir.path());Z;
Process p("./znc", QStringList() << "--debug" << "--datadir" << dir.path() << "--makeconf", true);
p.ReadUntil("already exists");Z;
}
class ZNCTest : public testing::Test {
protected:
void SetUp() override {
WriteConfig(m_dir.path());Z;
ASSERT_TRUE(m_server.listen(QHostAddress::LocalHost, 6667)) << m_server.errorString().toStdString();Z;
}
Socket ConnectIRCd() {
[this]{ ASSERT_TRUE(m_server.waitForNewConnection(30000 /* msec */)); }();
return WrapIO(m_server.nextPendingConnection());
}
Socket ConnectClient() {
m_clients.emplace_back();
QTcpSocket& sock = m_clients.back();
sock.connectToHost("127.0.0.1", 12345);
[&]{ ASSERT_TRUE(sock.waitForConnected()) << sock.errorString().toStdString(); }();
return WrapIO(&sock);
}
std::unique_ptr<Process> Run() {
return std::unique_ptr<Process>(new Process("./znc", QStringList() << "--debug" << "--datadir" << m_dir.path(), false));
}
Socket LoginClient() {
auto client = ConnectClient();
client.Write("PASS :hunter2");
client.Write("NICK nick");
client.Write("USER user/test x x :x");
return client;
}
QTemporaryDir m_dir;
QTcpServer m_server;
std::list<QTcpSocket> m_clients;
};
TEST_F(ZNCTest, Connect) {
auto znc = Run();Z;
auto ircd = ConnectIRCd();Z;
ircd.ReadUntil("CAP LS");Z;
auto client = ConnectClient();Z;
client.Write("PASS :hunter2");
client.Write("NICK nick");
client.Write("USER user/test x x :x");
client.ReadUntil("Welcome");Z;
client.Close();
client = ConnectClient();Z;
client.Write("PASS :user:hunter2");
client.Write("NICK nick");
client.Write("USER u x x x");
client.ReadUntil("Welcome");Z;
}
TEST_F(ZNCTest, Channel) {
auto znc = Run();Z;
auto ircd = ConnectIRCd();Z;
auto client = LoginClient();Z;
client.ReadUntil("Welcome");Z;
client.Write("JOIN #znc");
client.Close();
ircd.Write(":server 001 nick :Hello");
ircd.ReadUntil("JOIN #znc");Z;
ircd.Write(":nick JOIN #znc nick :Real");
ircd.Write(":server 353 nick #znc :nick");
ircd.Write(":server 366 nick #znc :End of /NAMES list");
client = LoginClient();Z;
client.ReadUntil(":nick JOIN :#znc");Z;
}
} // namespace
<commit_msg>Add one more small test.<commit_after>/*
* Copyright (C) 2004-2015 ZNC, see the NOTICE file for details.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <gtest/gtest.h>
#include <gmock/gmock.h>
#include <QDateTime>
#include <QProcess>
#include <QTcpServer>
#include <QTcpSocket>
#include <QTemporaryDir>
#include <QTextStream>
#include <memory>
#define Z do { if (::testing::Test::HasFatalFailure()) { std::cerr << "At: " << __FILE__ << ":" << __LINE__ << std::endl; return; } } while (0)
namespace {
template <typename Device>
class IO {
public:
IO(Device* device, bool verbose = false) : m_device(device), m_verbose(verbose) {}
virtual ~IO() {}
void ReadUntil(QByteArray pattern) {
auto deadline = QDateTime::currentDateTime().addSecs(30);
while (true) {
int search = m_readed.indexOf(pattern);
if (search != -1) {
m_readed.remove(0, search + pattern.length());
return;
}
if (m_readed.length() > pattern.length()) {
m_readed = m_readed.right(pattern.length());
}
const int timeout_ms = QDateTime::currentDateTime().msecsTo(deadline);
ASSERT_GT(timeout_ms, 0) << "Wanted:" << pattern.toStdString();
ASSERT_TRUE(m_device->waitForReadyRead(timeout_ms)) << "Wanted: " << pattern.toStdString();
QByteArray chunk = m_device->readAll();
if (m_verbose) {
std::cout << chunk.toStdString() << std::flush;
}
m_readed += chunk;
}
}
void Write(QString s = "", bool new_line = true) {
if (!m_device) return;
if (m_verbose) {
std::cout << s.toStdString() << std::flush;
if (new_line) {
std::cout << std::endl;
}
}
s += "\n";
{
QTextStream str(m_device);
str << s;
}
FlushIfCan(m_device);
}
void Close() {
m_device->close();
}
private:
// QTextStream doesn't flush QTcpSocket, and QIODevice doesn't have flush() at all...
static void FlushIfCan(QIODevice*) {}
static void FlushIfCan(QTcpSocket* sock) {
sock->flush();
}
Device* m_device;
bool m_verbose;
QByteArray m_readed;
};
template <typename Device>
IO<Device> WrapIO(Device* d) {
return IO<Device>(d);
}
using Socket = IO<QTcpSocket>;
class Process : public IO<QProcess> {
public:
Process(QString cmd, QStringList args, bool interactive) : IO(&m_proc, true) {
if (!interactive) {
m_proc.setProcessChannelMode(QProcess::ForwardedChannels);
}
m_proc.start(cmd, args);
}
~Process() {
if (m_kill) m_proc.terminate();
[this]() { ASSERT_TRUE(m_proc.waitForFinished()); }();
}
void ShouldFinishItself() {
m_kill = false;
}
private:
bool m_kill = true;
QProcess m_proc;
};
void WriteConfig(QString path) {
Process p("./znc", QStringList() << "--debug" << "--datadir" << path << "--makeconf", true);
p.ReadUntil("Listen on port");Z; p.Write("12345");
p.ReadUntil("Listen using SSL");Z; p.Write();
p.ReadUntil("IPv6");Z; p.Write();
p.ReadUntil("Username");Z; p.Write("user");
p.ReadUntil("password");Z; p.Write("hunter2", false);
p.ReadUntil("Confirm");Z; p.Write("hunter2", false);
p.ReadUntil("Nick [user]");Z; p.Write();
p.ReadUntil("Alternate nick [user_]");Z; p.Write();
p.ReadUntil("Ident [user]");Z; p.Write();
p.ReadUntil("Real name");Z; p.Write();
p.ReadUntil("Bind host");Z; p.Write();
p.ReadUntil("Set up a network?");Z; p.Write();
p.ReadUntil("Name [freenode]");Z; p.Write("test");
p.ReadUntil("Server host (host only)");Z; p.Write("127.0.0.1");
p.ReadUntil("Server uses SSL?");Z; p.Write();
p.ReadUntil("6667");Z; p.Write();
p.ReadUntil("password");Z; p.Write();
p.ReadUntil("channels");Z; p.Write();
p.ReadUntil("Launch ZNC now?");Z; p.Write("no");
p.ShouldFinishItself();
}
TEST(Config, AlreadyExists) {
QTemporaryDir dir;
WriteConfig(dir.path());Z;
Process p("./znc", QStringList() << "--debug" << "--datadir" << dir.path() << "--makeconf", true);
p.ReadUntil("already exists");Z;
}
class ZNCTest : public testing::Test {
protected:
void SetUp() override {
WriteConfig(m_dir.path());Z;
ASSERT_TRUE(m_server.listen(QHostAddress::LocalHost, 6667)) << m_server.errorString().toStdString();Z;
}
Socket ConnectIRCd() {
[this]{ ASSERT_TRUE(m_server.waitForNewConnection(30000 /* msec */)); }();
return WrapIO(m_server.nextPendingConnection());
}
Socket ConnectClient() {
m_clients.emplace_back();
QTcpSocket& sock = m_clients.back();
sock.connectToHost("127.0.0.1", 12345);
[&]{ ASSERT_TRUE(sock.waitForConnected()) << sock.errorString().toStdString(); }();
return WrapIO(&sock);
}
std::unique_ptr<Process> Run() {
return std::unique_ptr<Process>(new Process("./znc", QStringList() << "--debug" << "--datadir" << m_dir.path(), false));
}
Socket LoginClient() {
auto client = ConnectClient();
client.Write("PASS :hunter2");
client.Write("NICK nick");
client.Write("USER user/test x x :x");
return client;
}
QTemporaryDir m_dir;
QTcpServer m_server;
std::list<QTcpSocket> m_clients;
};
TEST_F(ZNCTest, Connect) {
auto znc = Run();Z;
auto ircd = ConnectIRCd();Z;
ircd.ReadUntil("CAP LS");Z;
auto client = ConnectClient();Z;
client.Write("PASS :hunter2");
client.Write("NICK nick");
client.Write("USER user/test x x :x");
client.ReadUntil("Welcome");Z;
client.Close();
client = ConnectClient();Z;
client.Write("PASS :user:hunter2");
client.Write("NICK nick");
client.Write("USER u x x x");
client.ReadUntil("Welcome");Z;
client.Close();
client = ConnectClient();Z;
client.Write("NICK nick");
client.Write("USER user x x x");
client.ReadUntil("Configure your client to send a server password");
client.Close();
ircd.Write(":server 001 nick :Hello");
ircd.ReadUntil("WHO");Z;
}
TEST_F(ZNCTest, Channel) {
auto znc = Run();Z;
auto ircd = ConnectIRCd();Z;
auto client = LoginClient();Z;
client.ReadUntil("Welcome");Z;
client.Write("JOIN #znc");
client.Close();
ircd.Write(":server 001 nick :Hello");
ircd.ReadUntil("JOIN #znc");Z;
ircd.Write(":nick JOIN #znc nick :Real");
ircd.Write(":server 353 nick #znc :nick");
ircd.Write(":server 366 nick #znc :End of /NAMES list");
client = LoginClient();Z;
client.ReadUntil(":nick JOIN :#znc");Z;
}
} // namespace
<|endoftext|>
|
<commit_before>#include <world/core.h>
#include <world/flat.h>
#include <world/terrain.h>
using namespace world;
int main(int argc, char **argv) {
std::unique_ptr<FlatWorld> world(FlatWorld::createDemoFlatWorld());
FlatMapper mapper;
Image output(1024, 1024, ImageType::RGB);
double u = 50000;
mapper.map(*world, output, {{-u, -u, -2000}, {u, u, 4000}});
output.write("map.png");
// Export biomes
auto &ground = dynamic_cast<HeightmapGround &>(world->ground());
GroundBiomes &gb = ground.getWorker<GroundBiomes>();
Image img(1024, 1024, ImageType::RGBA);
gb.exportZones(img, BoundingBox({-u}, {u}), 0);
img.write("zones.png");
std::cout << "Wrote zones" << std::endl;
}<commit_msg>mapper program can now take json as arguments<commit_after>#include <world/core.h>
#include <world/flat.h>
#include <world/terrain.h>
using namespace world;
int main(int argc, char **argv) {
std::unique_ptr<FlatWorld> world;
if (argc > 1) {
world = std::make_unique<FlatWorld>();
world->load(argv[1]);
} else {
world.reset(FlatWorld::createDemoFlatWorld());
}
FlatMapper mapper;
Image output(1024, 1024, ImageType::RGB);
double u = 50000;
mapper.map(*world, output, {{-u, -u, -2000}, {u, u, 4000}});
output.write("map.png");
// Export biomes
auto &ground = dynamic_cast<HeightmapGround &>(world->ground());
auto &gb = ground.getWorker<GroundBiomes>();
Image img(1024, 1024, ImageType::RGBA);
gb.exportZones(img, BoundingBox({-u}, {u}), 0);
img.write("zones.png");
std::cout << "Wrote zones" << std::endl;
}<|endoftext|>
|
<commit_before>/**
*
* 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.
*/
#undef NDEBUG
#include <vector>
#include <string>
#include "HTTPIntegrationBase.h"
#include "HTTPHandlers.h"
#include "utils/IntegrationTestUtils.h"
#include "CivetStream.h"
#include "StreamPipe.h"
#include "OptionalUtils.h"
class C2AcknowledgeHandler : public ServerAwareHandler {
public:
bool handlePost(CivetServer* /*server*/, struct mg_connection* conn) override {
std::string req = readPayload(conn);
rapidjson::Document root;
root.Parse(req.data(), req.size());
if (root.HasMember("operationId")) {
std::lock_guard<std::mutex> guard(mtx_);
acknowledged_operations_.insert(root["operationId"].GetString());
}
mg_printf(conn, "HTTP/1.1 200 OK\r\nContent-Type: "
"text/plain\r\nContent-Length: 0\r\nConnection: close\r\n\r\n");
return true;
}
bool isAcknowledged(const std::string& operation_id) const {
std::lock_guard<std::mutex> guard(mtx_);
return acknowledged_operations_.count(operation_id) > 0;
}
private:
mutable std::mutex mtx_;
std::set<std::string> acknowledged_operations_;
};
class C2HeartbeatHandler : public ServerAwareHandler {
public:
explicit C2HeartbeatHandler(std::string response) : response_(std::move(response)) {}
bool handlePost(CivetServer* /*server*/, struct mg_connection* conn) override {
std::string req = readPayload(conn);
rapidjson::Document root;
root.Parse(req.data(), req.size());
utils::optional<std::string> agent_class;
if (root["agentInfo"].HasMember("agentClass")) {
agent_class = root["agentInfo"]["agentClass"].GetString();
}
{
std::lock_guard<std::mutex> lock(mtx_);
classes_.push_back(agent_class);
}
mg_printf(conn, "HTTP/1.1 200 OK\r\nContent-Type: "
"text/plain\r\nContent-Length: %lu\r\nConnection: close\r\n\r\n",
response_.length());
mg_printf(conn, "%s", response_.c_str());
return true;
}
bool gotClassesInOrder(const std::vector<utils::optional<std::string>>& class_names) {
std::lock_guard<std::mutex> lock(mtx_);
auto it = classes_.begin();
for (const auto& class_name : class_names) {
it = std::find(classes_.begin(), classes_.end(), class_name);
if (it == classes_.end()) {
return false;
}
++it;
}
return true;
}
private:
std::mutex mtx_;
std::vector<utils::optional<std::string>> classes_;
std::string response_;
};
class VerifyC2ClassRequest : public VerifyC2Base {
public:
explicit VerifyC2ClassRequest(std::function<bool()> verify) : verify_(std::move(verify)) {}
void configureC2() override {
configuration->set("nifi.c2.agent.protocol.class", "RESTSender");
configuration->set("nifi.c2.enable", "true");
configuration->set("nifi.c2.agent.heartbeat.period", "100");
configuration->set("nifi.c2.root.classes", "DeviceInfoNode,AgentInformation,FlowInformation");
}
void runAssertions() override {
assert(utils::verifyEventHappenedInPollTime(std::chrono::seconds(3), verify_));
}
private:
std::function<bool()> verify_;
};
int main() {
const std::string class_update_id = "321";
C2HeartbeatHandler heartbeat_handler(R"({
"requested_operations": [{
"operation": "update",
"name": "properties",
"operationId": ")" + class_update_id + R"(",
"args": {
"nifi.c2.agent.class": {"value": "TestClass", "persist": true}
}
}]})");
C2AcknowledgeHandler ack_handler;
VerifyC2ClassRequest harness([&]() -> bool {
return heartbeat_handler.gotClassesInOrder({{}, {"TestClass"}}) &&
ack_handler.isAcknowledged(class_update_id);
});
harness.setUrl("http://localhost:0/api/heartbeat", &heartbeat_handler);
harness.setUrl("http://localhost:0/api/acknowledge", &ack_handler);
harness.setC2Url("/api/heartbeat", "/api/acknowledge");
harness.run();
}
<commit_msg>MINIFICPP-1482 - Fix transient failure<commit_after>/**
*
* 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.
*/
#undef NDEBUG
#include <vector>
#include <string>
#include "HTTPIntegrationBase.h"
#include "HTTPHandlers.h"
#include "utils/IntegrationTestUtils.h"
#include "CivetStream.h"
#include "StreamPipe.h"
#include "OptionalUtils.h"
class C2AcknowledgeHandler : public ServerAwareHandler {
public:
bool handlePost(CivetServer* /*server*/, struct mg_connection* conn) override {
std::string req = readPayload(conn);
rapidjson::Document root;
root.Parse(req.data(), req.size());
if (root.IsObject() && root.HasMember("operationId")) {
std::lock_guard<std::mutex> guard(mtx_);
acknowledged_operations_.insert(root["operationId"].GetString());
}
mg_printf(conn, "HTTP/1.1 200 OK\r\nContent-Type: "
"text/plain\r\nContent-Length: 0\r\nConnection: close\r\n\r\n");
return true;
}
bool isAcknowledged(const std::string& operation_id) const {
std::lock_guard<std::mutex> guard(mtx_);
return acknowledged_operations_.count(operation_id) > 0;
}
private:
mutable std::mutex mtx_;
std::set<std::string> acknowledged_operations_;
};
class C2HeartbeatHandler : public ServerAwareHandler {
public:
explicit C2HeartbeatHandler(std::string response) : response_(std::move(response)) {}
bool handlePost(CivetServer* /*server*/, struct mg_connection* conn) override {
std::string req = readPayload(conn);
rapidjson::Document root;
root.Parse(req.data(), req.size());
utils::optional<std::string> agent_class;
if (root.IsObject() && root["agentInfo"].HasMember("agentClass")) {
agent_class = root["agentInfo"]["agentClass"].GetString();
}
{
std::lock_guard<std::mutex> lock(mtx_);
classes_.push_back(agent_class);
}
mg_printf(conn, "HTTP/1.1 200 OK\r\nContent-Type: "
"text/plain\r\nContent-Length: %lu\r\nConnection: close\r\n\r\n",
response_.length());
mg_printf(conn, "%s", response_.c_str());
return true;
}
bool gotClassesInOrder(const std::vector<utils::optional<std::string>>& class_names) {
std::lock_guard<std::mutex> lock(mtx_);
auto it = classes_.begin();
for (const auto& class_name : class_names) {
it = std::find(classes_.begin(), classes_.end(), class_name);
if (it == classes_.end()) {
return false;
}
++it;
}
return true;
}
private:
std::mutex mtx_;
std::vector<utils::optional<std::string>> classes_;
std::string response_;
};
class VerifyC2ClassRequest : public VerifyC2Base {
public:
explicit VerifyC2ClassRequest(std::function<bool()> verify) : verify_(std::move(verify)) {}
void configureC2() override {
configuration->set("nifi.c2.agent.protocol.class", "RESTSender");
configuration->set("nifi.c2.enable", "true");
configuration->set("nifi.c2.agent.heartbeat.period", "100");
configuration->set("nifi.c2.root.classes", "DeviceInfoNode,AgentInformation,FlowInformation");
}
void runAssertions() override {
assert(utils::verifyEventHappenedInPollTime(std::chrono::seconds(3), verify_));
}
private:
std::function<bool()> verify_;
};
int main() {
const std::string class_update_id = "321";
C2HeartbeatHandler heartbeat_handler(R"({
"requested_operations": [{
"operation": "update",
"name": "properties",
"operationId": ")" + class_update_id + R"(",
"args": {
"nifi.c2.agent.class": {"value": "TestClass", "persist": true}
}
}]})");
C2AcknowledgeHandler ack_handler;
VerifyC2ClassRequest harness([&]() -> bool {
return heartbeat_handler.gotClassesInOrder({{}, {"TestClass"}}) &&
ack_handler.isAcknowledged(class_update_id);
});
harness.setUrl("http://localhost:0/api/heartbeat", &heartbeat_handler);
harness.setUrl("http://localhost:0/api/acknowledge", &ack_handler);
harness.setC2Url("/api/heartbeat", "/api/acknowledge");
harness.run();
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: updateprotocol.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2007-07-06 14:39:13 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* 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., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _COM_SUN_STAR_UNO_XCOMPONENTCONTEXT_HPP_
#include <com/sun/star/uno/XComponentContext.hpp>
#endif
#ifndef _COM_SUN_STAR_TASK_XINTERACTIONHANDLER_HPP_
#include <com/sun/star/task/XInteractionHandler.hpp>
#endif
#ifndef _COM_SUN_STAR_DEPLOYMENT_UPDATEINFORMATIONPROVIDER_HPP_
#include <com/sun/star/deployment/UpdateInformationProvider.hpp>
#endif
#include <vector>
#include "updateinfo.hxx"
// Returns 'true' if successfully connected to the update server
bool checkForUpdates(
UpdateInfo& o_rUpdateInfo,
const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >& rxContext,
const ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionHandler >& rxInteractionHandler,
const ::com::sun::star::uno::Reference< ::com::sun::star::deployment::XUpdateInformationProvider >& rxProvider
);
<commit_msg>INTEGRATION: CWS updchk10 (1.4.24); FILE MERGED 2007/10/29 13:26:40 dv 1.4.24.3: #i82851# Extension manager notifies update check about found updates 2007/10/23 10:54:05 dv 1.4.24.2: #i82851# Support automatic checking for extension updates 2007/10/08 10:40:49 dv 1.4.24.1: added support for autoupdatecheck for extensions<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: updateprotocol.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: ihi $ $Date: 2007-11-19 16:50:14 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* 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., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _COM_SUN_STAR_UNO_XCOMPONENTCONTEXT_HPP_
#include <com/sun/star/uno/XComponentContext.hpp>
#endif
#ifndef _COM_SUN_STAR_TASK_XINTERACTIONHANDLER_HPP_
#include <com/sun/star/task/XInteractionHandler.hpp>
#endif
#ifndef _COM_SUN_STAR_DEPLOYMENT_UPDATEINFORMATIONPROVIDER_HPP_
#include <com/sun/star/deployment/UpdateInformationProvider.hpp>
#endif
#include <vector>
#include "updateinfo.hxx"
// Returns 'true' if successfully connected to the update server
bool checkForUpdates(
UpdateInfo& o_rUpdateInfo,
const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >& rxContext,
const ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionHandler >& rxInteractionHandler,
const ::com::sun::star::uno::Reference< ::com::sun::star::deployment::XUpdateInformationProvider >& rxProvider
);
// Returns 'true' if there are updates for any extension
bool checkForExtensionUpdates(
const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >& rxContext
);
bool checkForPendingUpdates(
const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >& rxContext
);
bool storeExtensionUpdateInfos(
const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >& rxContext,
const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Sequence< rtl::OUString > > &rUpdateInfos
);
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: frameloaderfactory.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: kz $ $Date: 2004-01-28 15:16:19 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* 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., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (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.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef __FILTER_CONFIG_FRAMELOADERFACTORY_HXX_
#define __FILTER_CONFIG_FRAMELOADERFACTORY_HXX_
//_______________________________________________
// includes
#include "basecontainer.hxx"
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSINGLESERVICEFACTORY_HPP_
#include <com/sun/star/lang/XSingleServiceFactory.hpp>
#endif
#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif
//_______________________________________________
// namespace
namespace filter{
namespace config{
namespace css = ::com::sun::star;
//_______________________________________________
// definitions
//_______________________________________________
/** @short implements the service <type scope="com.sun.star.document">FrameLoaderFactory</type>.
*/
class FrameLoaderFactory : public ::cppu::ImplInheritanceHelper1< BaseContainer ,
css::lang::XMultiServiceFactory >
{
//-------------------------------------------
// native interface
public:
//---------------------------------------
// ctor/dtor
/** @short standard ctor to connect this interface wrapper to
the global filter cache instance ...
@param xSMGR
reference to the uno service manager, which created this service instance.
*/
FrameLoaderFactory(const css::uno::Reference< css::lang::XMultiServiceFactory >& xSMGR);
//---------------------------------------
/** @short standard dtor.
*/
virtual ~FrameLoaderFactory();
//-------------------------------------------
// uno interface
public:
//---------------------------------------
// XMultiServiceFactory
virtual css::uno::Reference< css::uno::XInterface > SAL_CALL createInstance(const ::rtl::OUString& sLoader)
throw(css::uno::Exception ,
css::uno::RuntimeException);
virtual css::uno::Reference< css::uno::XInterface > SAL_CALL createInstanceWithArguments(const ::rtl::OUString& sLoader ,
const css::uno::Sequence< css::uno::Any >& lArguments)
throw(css::uno::Exception ,
css::uno::RuntimeException);
virtual css::uno::Sequence< ::rtl::OUString > SAL_CALL getAvailableServiceNames()
throw(css::uno::RuntimeException);
//-------------------------------------------
// static uno helper!
public:
//---------------------------------------
/** @short return the uno implementation name of this class.
@descr Because this information is used at several places
(and mostly an object instance of this class is not possible)
its implemented as a static function!
@return The fix uno implementation name of this class.
*/
static ::rtl::OUString impl_getImplementationName();
//---------------------------------------
/** @short return the list of supported uno services of this class.
@descr Because this information is used at several places
(and mostly an object instance of this class is not possible)
its implemented as a static function!
@return The fix list of uno services supported by this class.
*/
static css::uno::Sequence< ::rtl::OUString > impl_getSupportedServiceNames();
//---------------------------------------
/** @short return a new intsnace of this class.
@descr This method is used by the uno service manager, to create
a new instance of this service if needed.
@param xSMGR
reference to the uno service manager, which require
this new instance. It should be passed to the new object
so it can be used internaly to create own needed uno resources.
@return The new instance of this service as an uno reference.
*/
static css::uno::Reference< css::uno::XInterface > impl_createInstance(const css::uno::Reference< css::lang::XMultiServiceFactory >& xSMGR);
};
} // namespace config
} // namespace filter
#endif // __FILTER_CONFIG_FRAMELOADERFACTORY_HXX_
<commit_msg>INTEGRATION: CWS ooo19126 (1.2.346); FILE MERGED 2005/09/05 14:30:23 rt 1.2.346.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: frameloaderfactory.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-08 21:29:52 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* 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., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef __FILTER_CONFIG_FRAMELOADERFACTORY_HXX_
#define __FILTER_CONFIG_FRAMELOADERFACTORY_HXX_
//_______________________________________________
// includes
#include "basecontainer.hxx"
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSINGLESERVICEFACTORY_HPP_
#include <com/sun/star/lang/XSingleServiceFactory.hpp>
#endif
#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif
//_______________________________________________
// namespace
namespace filter{
namespace config{
namespace css = ::com::sun::star;
//_______________________________________________
// definitions
//_______________________________________________
/** @short implements the service <type scope="com.sun.star.document">FrameLoaderFactory</type>.
*/
class FrameLoaderFactory : public ::cppu::ImplInheritanceHelper1< BaseContainer ,
css::lang::XMultiServiceFactory >
{
//-------------------------------------------
// native interface
public:
//---------------------------------------
// ctor/dtor
/** @short standard ctor to connect this interface wrapper to
the global filter cache instance ...
@param xSMGR
reference to the uno service manager, which created this service instance.
*/
FrameLoaderFactory(const css::uno::Reference< css::lang::XMultiServiceFactory >& xSMGR);
//---------------------------------------
/** @short standard dtor.
*/
virtual ~FrameLoaderFactory();
//-------------------------------------------
// uno interface
public:
//---------------------------------------
// XMultiServiceFactory
virtual css::uno::Reference< css::uno::XInterface > SAL_CALL createInstance(const ::rtl::OUString& sLoader)
throw(css::uno::Exception ,
css::uno::RuntimeException);
virtual css::uno::Reference< css::uno::XInterface > SAL_CALL createInstanceWithArguments(const ::rtl::OUString& sLoader ,
const css::uno::Sequence< css::uno::Any >& lArguments)
throw(css::uno::Exception ,
css::uno::RuntimeException);
virtual css::uno::Sequence< ::rtl::OUString > SAL_CALL getAvailableServiceNames()
throw(css::uno::RuntimeException);
//-------------------------------------------
// static uno helper!
public:
//---------------------------------------
/** @short return the uno implementation name of this class.
@descr Because this information is used at several places
(and mostly an object instance of this class is not possible)
its implemented as a static function!
@return The fix uno implementation name of this class.
*/
static ::rtl::OUString impl_getImplementationName();
//---------------------------------------
/** @short return the list of supported uno services of this class.
@descr Because this information is used at several places
(and mostly an object instance of this class is not possible)
its implemented as a static function!
@return The fix list of uno services supported by this class.
*/
static css::uno::Sequence< ::rtl::OUString > impl_getSupportedServiceNames();
//---------------------------------------
/** @short return a new intsnace of this class.
@descr This method is used by the uno service manager, to create
a new instance of this service if needed.
@param xSMGR
reference to the uno service manager, which require
this new instance. It should be passed to the new object
so it can be used internaly to create own needed uno resources.
@return The new instance of this service as an uno reference.
*/
static css::uno::Reference< css::uno::XInterface > impl_createInstance(const css::uno::Reference< css::lang::XMultiServiceFactory >& xSMGR);
};
} // namespace config
} // namespace filter
#endif // __FILTER_CONFIG_FRAMELOADERFACTORY_HXX_
<|endoftext|>
|
<commit_before>#ifndef VEXCL_TYPES_HPP
#define VEXCL_TYPES_HPP
/*
The MIT License
Copyright (c) 2012 Denis Demidov <[email protected]>
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.
*/
/**
* \file types.hpp
* \author Pascal Germroth <[email protected]>
* \brief C++ sugar for OpenCL vector types, eg. cl::float4, operator+.
*/
#define BIN_OP(type, len, op) \
cl_##type##len &operator op##= (cl_##type##len &a, const cl_##type##len &b) { \
for(size_t i = 0 ; i < len ; i++) a.s[i] op##= b.s[i]; \
return a; \
} \
cl_##type##len operator op(const cl_##type##len &a, const cl_##type##len &b) { \
cl_##type##len res; return res op##= b; \
}
#define CL_VEC_TYPE(type, len) \
namespace std { \
BIN_OP(type, len, +) \
BIN_OP(type, len, -) \
BIN_OP(type, len, *) \
BIN_OP(type, len, /) \
ostream &operator<<(ostream &os, const cl_##type##len &value) { \
os << "(" #type #len ")("; \
for(size_t i = 0 ; i < len ; i++) { \
if(i != 0) os << ','; \
os << value.s[i]; \
} \
return os << ')'; \
} \
} \
namespace cl { \
typedef cl_##type##len type##len; \
}
#define CL_TYPES(type) \
CL_VEC_TYPE(type, 2); \
CL_VEC_TYPE(type, 4); \
CL_VEC_TYPE(type, 8); \
CL_VEC_TYPE(type, 16);
CL_TYPES(float);
CL_TYPES(double);
CL_TYPES(char); CL_TYPES(uchar);
CL_TYPES(short); CL_TYPES(ushort);
CL_TYPES(int); CL_TYPES(uint);
CL_TYPES(long); CL_TYPES(ulong);
#undef BIN_OP
#undef CL_VEC_TYPE
#undef CL_TYPES
#endif
<commit_msg>Fix binary cl_typen operators<commit_after>#ifndef VEXCL_TYPES_HPP
#define VEXCL_TYPES_HPP
/*
The MIT License
Copyright (c) 2012 Denis Demidov <[email protected]>
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.
*/
/**
* \file types.hpp
* \author Pascal Germroth <[email protected]>
* \brief C++ sugar for OpenCL vector types, eg. cl::float4, operator+.
*/
#define BIN_OP(type, len, op) \
cl_##type##len &operator op##= (cl_##type##len &a, const cl_##type##len &b) { \
for(size_t i = 0 ; i < len ; i++) a.s[i] op##= b.s[i]; \
return a; \
} \
cl_##type##len operator op(const cl_##type##len &a, const cl_##type##len &b) { \
cl_##type##len res = a; return res op##= b; \
}
#define CL_VEC_TYPE(type, len) \
namespace std { \
BIN_OP(type, len, +) \
BIN_OP(type, len, -) \
BIN_OP(type, len, *) \
BIN_OP(type, len, /) \
ostream &operator<<(ostream &os, const cl_##type##len &value) { \
os << "(" #type #len ")("; \
for(size_t i = 0 ; i < len ; i++) { \
if(i != 0) os << ','; \
os << value.s[i]; \
} \
return os << ')'; \
} \
} \
namespace cl { \
typedef cl_##type##len type##len; \
}
#define CL_TYPES(type) \
CL_VEC_TYPE(type, 2); \
CL_VEC_TYPE(type, 4); \
CL_VEC_TYPE(type, 8); \
CL_VEC_TYPE(type, 16);
CL_TYPES(float);
CL_TYPES(double);
CL_TYPES(char); CL_TYPES(uchar);
CL_TYPES(short); CL_TYPES(ushort);
CL_TYPES(int); CL_TYPES(uint);
CL_TYPES(long); CL_TYPES(ulong);
#undef BIN_OP
#undef CL_VEC_TYPE
#undef CL_TYPES
#endif
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2012-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:
* 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 Intel Corporation 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.
*/
// written by Roman Dementiev
#define HACK_TO_REMOVE_DUPLICATE_ERROR
#include "cpucounters.h"
#ifdef _MSC_VER
#include <windows.h>
#include "../PCM_Win/windriver.h"
#else
#include <unistd.h>
#endif
#include <iostream>
#include <stdlib.h>
#include <iomanip>
#include <string.h>
#ifdef _MSC_VER
#include "freegetopt/getopt.h"
#endif
void print_usage(const char * progname)
{
std::cout << "Usage " << progname << " [-w value] [-c core] [-a] [-d] msr\n\n";
std::cout << " Reads/writes specified msr (model specific register) \n";
std::cout << " -w value : write the value before reading \n";
std::cout << " -c core : perform msr read/write on specified core (default is 0)\n";
std::cout << " -d : output all numbers in dec (default is hex)\n";
std::cout << " -a : perform msr read/write operations on all cores\n";
std::cout << "\n";
}
int main(int argc, char * argv[])
{
std::cout << "\n Processor Counter Monitor " << PCM_VERSION << "\n";
std::cout << "\n MSR read/write utility\n\n";
uint64 value = 0;
bool write = false;
int core = 0;
int msr = -1;
bool dec = false;
int my_opt = -1;
while ((my_opt = getopt(argc, argv, "w:c:d:a")) != -1)
{
switch (my_opt)
{
case 'w':
write = true;
value = read_number(optarg);
break;
case 'c':
core = (int)read_number(optarg);
break;
case 'd':
dec = true;
break;
case 'a':
core = -1;
break;
default:
print_usage(argv[0]);
return -1;
}
}
if (optind >= argc)
{
print_usage(argv[0]);
return -1;
}
msr = (int)read_number(argv[optind]);
#ifdef _MSC_VER
// Increase the priority a bit to improve context switching delays on Windows
SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
// WARNING: This driver code (msr.sys) is only for testing purposes, not for production use
Driver drv = Driver(Driver::msrLocalPath());
// drv.stop(); // restart driver (usually not needed)
if (!drv.start())
{
std::wcerr << "Can not load MSR driver.\n";
std::wcerr << "You must have a signed driver at " << drv.driverPath() << " and have administrator rights to run this program\n";
return -1;
}
#endif
auto doOne = [&dec, &write, &msr](int core, uint64 value)
{
try {
MsrHandle h(core);
if (!dec) std::cout << std::hex << std::showbase;
if (write)
{
std::cout << " Writing " << value << " to MSR " << msr << " on core " << core << "\n";
if (h.write(msr, value) != 8)
{
std::cout << " Write error!\n";
}
}
value = 0;
if (h.read(msr, &value) == 8)
{
std::cout << " Read value " << value << " from MSR " << msr << " on core " << core << "\n\n";
}
else
{
std::cout << " Read error!\n";
}
}
catch (std::exception & e)
{
std::cerr << "Error accessing MSRs: " << e.what() << "\n";
std::cerr << "Please check if the program can access MSR drivers.\n";
}
};
if (core >= 0)
{
doOne(core, value);
}
else
{
set_signal_handlers();
auto m = PCM::getInstance();
for (uint32 i = 0; i < m->getNumCores(); ++i)
{
if (m->isCoreOnline(i))
{
doOne(i, value);
}
}
}
}
<commit_msg>pcm-msr: fix -d option<commit_after>/*
Copyright (c) 2012-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:
* 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 Intel Corporation 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.
*/
// written by Roman Dementiev
#define HACK_TO_REMOVE_DUPLICATE_ERROR
#include "cpucounters.h"
#ifdef _MSC_VER
#include <windows.h>
#include "../PCM_Win/windriver.h"
#else
#include <unistd.h>
#endif
#include <iostream>
#include <stdlib.h>
#include <iomanip>
#include <string.h>
#ifdef _MSC_VER
#include "freegetopt/getopt.h"
#endif
void print_usage(const char * progname)
{
std::cout << "Usage " << progname << " [-w value] [-c core] [-a] [-d] msr\n\n";
std::cout << " Reads/writes specified msr (model specific register) \n";
std::cout << " -w value : write the value before reading \n";
std::cout << " -c core : perform msr read/write on specified core (default is 0)\n";
std::cout << " -d : output all numbers in dec (default is hex)\n";
std::cout << " -a : perform msr read/write operations on all cores\n";
std::cout << "\n";
}
int main(int argc, char * argv[])
{
std::cout << "\n Processor Counter Monitor " << PCM_VERSION << "\n";
std::cout << "\n MSR read/write utility\n\n";
uint64 value = 0;
bool write = false;
int core = 0;
int msr = -1;
bool dec = false;
int my_opt = -1;
while ((my_opt = getopt(argc, argv, "w:c:da")) != -1)
{
switch (my_opt)
{
case 'w':
write = true;
value = read_number(optarg);
break;
case 'c':
core = (int)read_number(optarg);
break;
case 'd':
dec = true;
break;
case 'a':
core = -1;
break;
default:
print_usage(argv[0]);
return -1;
}
}
if (optind >= argc)
{
print_usage(argv[0]);
return -1;
}
msr = (int)read_number(argv[optind]);
#ifdef _MSC_VER
// Increase the priority a bit to improve context switching delays on Windows
SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
// WARNING: This driver code (msr.sys) is only for testing purposes, not for production use
Driver drv = Driver(Driver::msrLocalPath());
// drv.stop(); // restart driver (usually not needed)
if (!drv.start())
{
std::wcerr << "Can not load MSR driver.\n";
std::wcerr << "You must have a signed driver at " << drv.driverPath() << " and have administrator rights to run this program\n";
return -1;
}
#endif
auto doOne = [&dec, &write, &msr](int core, uint64 value)
{
try {
MsrHandle h(core);
if (!dec) std::cout << std::hex << std::showbase;
if (write)
{
std::cout << " Writing " << value << " to MSR " << msr << " on core " << core << "\n";
if (h.write(msr, value) != 8)
{
std::cout << " Write error!\n";
}
}
value = 0;
if (h.read(msr, &value) == 8)
{
std::cout << " Read value " << value << " from MSR " << msr << " on core " << core << "\n\n";
}
else
{
std::cout << " Read error!\n";
}
}
catch (std::exception & e)
{
std::cerr << "Error accessing MSRs: " << e.what() << "\n";
std::cerr << "Please check if the program can access MSR drivers.\n";
}
};
if (core >= 0)
{
doOne(core, value);
}
else
{
set_signal_handlers();
auto m = PCM::getInstance();
for (uint32 i = 0; i < m->getNumCores(); ++i)
{
if (m->isCoreOnline(i))
{
doOne(i, value);
}
}
}
}
<|endoftext|>
|
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* 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 .
*/
#include <uiconfiguration/imagemanager.hxx>
#include <threadhelp/resetableguard.hxx>
#include <xml/imagesconfiguration.hxx>
#include <uiconfiguration/graphicnameaccess.hxx>
#include <services.h>
#include "imagemanagerimpl.hxx"
#include "properties.h"
#include <com/sun/star/ui/UIElementType.hpp>
#include <com/sun/star/ui/ConfigurationEvent.hpp>
#include <com/sun/star/lang/DisposedException.hpp>
#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/beans/PropertyValue.hpp>
#include <com/sun/star/embed/ElementModes.hpp>
#include <com/sun/star/io/XStream.hpp>
#include <com/sun/star/ui/ImageType.hpp>
#include <vcl/svapp.hxx>
#include <rtl/ustrbuf.hxx>
#include <osl/mutex.hxx>
#include <comphelper/sequence.hxx>
#include <unotools/ucbstreamhelper.hxx>
#include <vcl/pngread.hxx>
#include <vcl/pngwrite.hxx>
//_________________________________________________________________________________________________________________
// namespaces
//_________________________________________________________________________________________________________________
using ::com::sun::star::uno::Sequence;
using ::com::sun::star::uno::XInterface;
using ::com::sun::star::uno::Exception;
using ::com::sun::star::uno::RuntimeException;
using ::com::sun::star::uno::UNO_QUERY;
using ::com::sun::star::uno::Any;
using ::com::sun::star::uno::makeAny;
using ::com::sun::star::graphic::XGraphic;
using namespace ::com::sun::star;
using namespace ::com::sun::star::io;
using namespace ::com::sun::star::embed;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::ui;
// Image sizes for our toolbars/menus
const sal_Int32 IMAGE_SIZE_NORMAL = 16;
const sal_Int32 IMAGE_SIZE_LARGE = 26;
const sal_Int16 MAX_IMAGETYPE_VALUE = ::com::sun::star::ui::ImageType::COLOR_HIGHCONTRAST|
::com::sun::star::ui::ImageType::SIZE_LARGE;
namespace framework
{
//*****************************************************************************************************************
// XInterface, XTypeProvider, XServiceInfo
//*****************************************************************************************************************
DEFINE_XSERVICEINFO_MULTISERVICE_2 ( ImageManager ,
::cppu::OWeakObject ,
"com.sun.star.ui.ImageManager" ,
OUString("com.sun.star.comp.framework.ImageManager")
)
DEFINE_INIT_SERVICE ( ImageManager, {} )
ImageManager::ImageManager( const uno::Reference< uno::XComponentContext >& rxContext ) :
ThreadHelpBase( &Application::GetSolarMutex() )
, m_pImpl( new ImageManagerImpl(rxContext, this, false) )
{
}
ImageManager::~ImageManager()
{
m_pImpl->clear();
}
// XComponent
void SAL_CALL ImageManager::dispose() throw (::com::sun::star::uno::RuntimeException)
{
m_pImpl->dispose();
}
void SAL_CALL ImageManager::addEventListener( const uno::Reference< XEventListener >& xListener ) throw (::com::sun::star::uno::RuntimeException)
{
m_pImpl->addEventListener(xListener);
}
void SAL_CALL ImageManager::removeEventListener( const uno::Reference< XEventListener >& xListener ) throw (::com::sun::star::uno::RuntimeException)
{
/* SAFE AREA ----------------------------------------------------------------------------------------------- */
m_pImpl->removeEventListener(xListener);
}
// Non-UNO methods
void ImageManager::setStorage( const uno::Reference< XStorage >& Storage )
throw (::com::sun::star::uno::RuntimeException)
{
ResetableGuard aLock( m_pImpl->m_aLock );
m_pImpl->m_xUserConfigStorage = Storage;
m_pImpl->implts_initialize();
}
// XInitialization
void SAL_CALL ImageManager::initialize( const Sequence< Any >& aArguments ) throw ( Exception, RuntimeException )
{
m_pImpl->initialize(aArguments);
}
// XImageManager
void SAL_CALL ImageManager::reset()
throw (::com::sun::star::uno::RuntimeException)
{
/* SAFE AREA ----------------------------------------------------------------------------------------------- */
m_pImpl->reset();
}
Sequence< OUString > SAL_CALL ImageManager::getAllImageNames( ::sal_Int16 nImageType )
throw (::com::sun::star::uno::RuntimeException)
{
return m_pImpl->getAllImageNames( nImageType );
}
::sal_Bool SAL_CALL ImageManager::hasImage( ::sal_Int16 nImageType, const OUString& aCommandURL )
throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException)
{
return m_pImpl->hasImage(nImageType,aCommandURL);
}
Sequence< uno::Reference< XGraphic > > SAL_CALL ImageManager::getImages(
::sal_Int16 nImageType,
const Sequence< OUString >& aCommandURLSequence )
throw ( ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException )
{
return m_pImpl->getImages(nImageType,aCommandURLSequence);
}
void SAL_CALL ImageManager::replaceImages(
::sal_Int16 nImageType,
const Sequence< OUString >& aCommandURLSequence,
const Sequence< uno::Reference< XGraphic > >& aGraphicsSequence )
throw ( ::com::sun::star::lang::IllegalArgumentException,
::com::sun::star::lang::IllegalAccessException,
::com::sun::star::uno::RuntimeException)
{
m_pImpl->replaceImages(nImageType,aCommandURLSequence,aGraphicsSequence);
}
void SAL_CALL ImageManager::removeImages( ::sal_Int16 nImageType, const Sequence< OUString >& aCommandURLSequence )
throw ( ::com::sun::star::lang::IllegalArgumentException,
::com::sun::star::lang::IllegalAccessException,
::com::sun::star::uno::RuntimeException)
{
m_pImpl->removeImages(nImageType,aCommandURLSequence);
}
void SAL_CALL ImageManager::insertImages( ::sal_Int16 nImageType, const Sequence< OUString >& aCommandURLSequence, const Sequence< uno::Reference< XGraphic > >& aGraphicSequence )
throw ( ::com::sun::star::container::ElementExistException,
::com::sun::star::lang::IllegalArgumentException,
::com::sun::star::lang::IllegalAccessException,
::com::sun::star::uno::RuntimeException)
{
m_pImpl->insertImages(nImageType,aCommandURLSequence,aGraphicSequence);
}
// XUIConfiguration
void SAL_CALL ImageManager::addConfigurationListener( const uno::Reference< ::com::sun::star::ui::XUIConfigurationListener >& xListener )
throw (::com::sun::star::uno::RuntimeException)
{
m_pImpl->addConfigurationListener(xListener);
}
void SAL_CALL ImageManager::removeConfigurationListener( const uno::Reference< ::com::sun::star::ui::XUIConfigurationListener >& xListener )
throw (::com::sun::star::uno::RuntimeException)
{
/* SAFE AREA ----------------------------------------------------------------------------------------------- */
m_pImpl->removeConfigurationListener(xListener);
}
// XUIConfigurationPersistence
void SAL_CALL ImageManager::reload()
throw ( ::com::sun::star::uno::Exception,
::com::sun::star::uno::RuntimeException )
{
m_pImpl->reload();
}
void SAL_CALL ImageManager::store()
throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException)
{
m_pImpl->store();
}
void SAL_CALL ImageManager::storeToStorage( const uno::Reference< XStorage >& Storage )
throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException)
{
m_pImpl->storeToStorage(Storage);
}
sal_Bool SAL_CALL ImageManager::isModified()
throw (::com::sun::star::uno::RuntimeException)
{
return m_pImpl->isModified();
}
sal_Bool SAL_CALL ImageManager::isReadOnly() throw (::com::sun::star::uno::RuntimeException)
{
return m_pImpl->isReadOnly();
}
} // namespace framework
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>-Werror,-Wunused-const-variable<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* 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 .
*/
#include <uiconfiguration/imagemanager.hxx>
#include <threadhelp/resetableguard.hxx>
#include <xml/imagesconfiguration.hxx>
#include <uiconfiguration/graphicnameaccess.hxx>
#include <services.h>
#include "imagemanagerimpl.hxx"
#include "properties.h"
#include <com/sun/star/lang/DisposedException.hpp>
#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/beans/PropertyValue.hpp>
#include <com/sun/star/embed/ElementModes.hpp>
#include <com/sun/star/io/XStream.hpp>
#include <vcl/svapp.hxx>
#include <rtl/ustrbuf.hxx>
#include <osl/mutex.hxx>
#include <comphelper/sequence.hxx>
#include <unotools/ucbstreamhelper.hxx>
#include <vcl/pngread.hxx>
#include <vcl/pngwrite.hxx>
//_________________________________________________________________________________________________________________
// namespaces
//_________________________________________________________________________________________________________________
using ::com::sun::star::uno::Sequence;
using ::com::sun::star::uno::XInterface;
using ::com::sun::star::uno::Exception;
using ::com::sun::star::uno::RuntimeException;
using ::com::sun::star::uno::UNO_QUERY;
using ::com::sun::star::uno::Any;
using ::com::sun::star::uno::makeAny;
using ::com::sun::star::graphic::XGraphic;
using namespace ::com::sun::star;
using namespace ::com::sun::star::io;
using namespace ::com::sun::star::embed;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::beans;
namespace framework
{
//*****************************************************************************************************************
// XInterface, XTypeProvider, XServiceInfo
//*****************************************************************************************************************
DEFINE_XSERVICEINFO_MULTISERVICE_2 ( ImageManager ,
::cppu::OWeakObject ,
"com.sun.star.ui.ImageManager" ,
OUString("com.sun.star.comp.framework.ImageManager")
)
DEFINE_INIT_SERVICE ( ImageManager, {} )
ImageManager::ImageManager( const uno::Reference< uno::XComponentContext >& rxContext ) :
ThreadHelpBase( &Application::GetSolarMutex() )
, m_pImpl( new ImageManagerImpl(rxContext, this, false) )
{
}
ImageManager::~ImageManager()
{
m_pImpl->clear();
}
// XComponent
void SAL_CALL ImageManager::dispose() throw (::com::sun::star::uno::RuntimeException)
{
m_pImpl->dispose();
}
void SAL_CALL ImageManager::addEventListener( const uno::Reference< XEventListener >& xListener ) throw (::com::sun::star::uno::RuntimeException)
{
m_pImpl->addEventListener(xListener);
}
void SAL_CALL ImageManager::removeEventListener( const uno::Reference< XEventListener >& xListener ) throw (::com::sun::star::uno::RuntimeException)
{
/* SAFE AREA ----------------------------------------------------------------------------------------------- */
m_pImpl->removeEventListener(xListener);
}
// Non-UNO methods
void ImageManager::setStorage( const uno::Reference< XStorage >& Storage )
throw (::com::sun::star::uno::RuntimeException)
{
ResetableGuard aLock( m_pImpl->m_aLock );
m_pImpl->m_xUserConfigStorage = Storage;
m_pImpl->implts_initialize();
}
// XInitialization
void SAL_CALL ImageManager::initialize( const Sequence< Any >& aArguments ) throw ( Exception, RuntimeException )
{
m_pImpl->initialize(aArguments);
}
// XImageManager
void SAL_CALL ImageManager::reset()
throw (::com::sun::star::uno::RuntimeException)
{
/* SAFE AREA ----------------------------------------------------------------------------------------------- */
m_pImpl->reset();
}
Sequence< OUString > SAL_CALL ImageManager::getAllImageNames( ::sal_Int16 nImageType )
throw (::com::sun::star::uno::RuntimeException)
{
return m_pImpl->getAllImageNames( nImageType );
}
::sal_Bool SAL_CALL ImageManager::hasImage( ::sal_Int16 nImageType, const OUString& aCommandURL )
throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException)
{
return m_pImpl->hasImage(nImageType,aCommandURL);
}
Sequence< uno::Reference< XGraphic > > SAL_CALL ImageManager::getImages(
::sal_Int16 nImageType,
const Sequence< OUString >& aCommandURLSequence )
throw ( ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException )
{
return m_pImpl->getImages(nImageType,aCommandURLSequence);
}
void SAL_CALL ImageManager::replaceImages(
::sal_Int16 nImageType,
const Sequence< OUString >& aCommandURLSequence,
const Sequence< uno::Reference< XGraphic > >& aGraphicsSequence )
throw ( ::com::sun::star::lang::IllegalArgumentException,
::com::sun::star::lang::IllegalAccessException,
::com::sun::star::uno::RuntimeException)
{
m_pImpl->replaceImages(nImageType,aCommandURLSequence,aGraphicsSequence);
}
void SAL_CALL ImageManager::removeImages( ::sal_Int16 nImageType, const Sequence< OUString >& aCommandURLSequence )
throw ( ::com::sun::star::lang::IllegalArgumentException,
::com::sun::star::lang::IllegalAccessException,
::com::sun::star::uno::RuntimeException)
{
m_pImpl->removeImages(nImageType,aCommandURLSequence);
}
void SAL_CALL ImageManager::insertImages( ::sal_Int16 nImageType, const Sequence< OUString >& aCommandURLSequence, const Sequence< uno::Reference< XGraphic > >& aGraphicSequence )
throw ( ::com::sun::star::container::ElementExistException,
::com::sun::star::lang::IllegalArgumentException,
::com::sun::star::lang::IllegalAccessException,
::com::sun::star::uno::RuntimeException)
{
m_pImpl->insertImages(nImageType,aCommandURLSequence,aGraphicSequence);
}
// XUIConfiguration
void SAL_CALL ImageManager::addConfigurationListener( const uno::Reference< ::com::sun::star::ui::XUIConfigurationListener >& xListener )
throw (::com::sun::star::uno::RuntimeException)
{
m_pImpl->addConfigurationListener(xListener);
}
void SAL_CALL ImageManager::removeConfigurationListener( const uno::Reference< ::com::sun::star::ui::XUIConfigurationListener >& xListener )
throw (::com::sun::star::uno::RuntimeException)
{
/* SAFE AREA ----------------------------------------------------------------------------------------------- */
m_pImpl->removeConfigurationListener(xListener);
}
// XUIConfigurationPersistence
void SAL_CALL ImageManager::reload()
throw ( ::com::sun::star::uno::Exception,
::com::sun::star::uno::RuntimeException )
{
m_pImpl->reload();
}
void SAL_CALL ImageManager::store()
throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException)
{
m_pImpl->store();
}
void SAL_CALL ImageManager::storeToStorage( const uno::Reference< XStorage >& Storage )
throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException)
{
m_pImpl->storeToStorage(Storage);
}
sal_Bool SAL_CALL ImageManager::isModified()
throw (::com::sun::star::uno::RuntimeException)
{
return m_pImpl->isModified();
}
sal_Bool SAL_CALL ImageManager::isReadOnly() throw (::com::sun::star::uno::RuntimeException)
{
return m_pImpl->isReadOnly();
}
} // namespace framework
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>
|
<commit_before>#include <time.h>
#include <pqxx/pqxx>
#include <random>
#include <iostream>
#include <unordered_map> //hash table
#include "const.h"
#include "pgutils.hpp"
#include "dblog.hpp"
using namespace std;
using namespace pqxx;
//declare all static variables
PGUtils* PGUtils::instance;
//constructor
PGUtils::PGUtils()
: dbconn("dbname=call")
{
}
//public functions
PGUtils* PGUtils::getInstance() //don't need to declare static again
{
if(instance == NULL)
{
instance = new PGUtils();
}
return instance;
}
uint64_t PGUtils::authenticate(string username, string password)
{//TODO: remove error specifics like no user etc and turn it into "authentication failure" or similar
//sql statements
const string hash = "select saltedhash from users where username=$1";
const string auth = "select count(*) from users where username=$1 and saltedhash=crypt($2, $3)";
const string setsession = "update users set sessionid=$1 where username=$2";
//get the salted hash for verification
dbconn.prepare("hash", hash);
work getHash(dbconn);
result resultHash = getHash.prepared("hash")(username).exec();
getHash.commit();
if(resultHash.size() < 1)
{//no use continuing if the user doesn't exist
return ENOUSER;
}
string saltedHash = resultHash[0][0].as<string>();
//now authentiate the user against the db
dbconn.prepare("auth", auth);
work getAuth(dbconn);
result resultAuth = getAuth.prepared("auth")(username)(password)(saltedHash).exec();
getAuth.commit();
if(resultAuth[0][0].as<int>() != 1)
{
return EPASS;
}
// https://stackoverflow.com/questions/440133/how-do-i-create-a-random-alpha-numeric-string-in-c
// https://stackoverflow.com/questions/19665818/best-way-to-generate-random-numbers-using-c11-random-library
//generate random # session key
/*
const char alphanum[] =//leaving out semicolon for command string tokenizing
"0123456789"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz";
random_device rd;
mt19937 mt(rd());
uniform_int_distribution<int> dist (0, sizeof(alphanum)-1);
string sessionid = "";
for(int i=0; i<50; i++)
{//if sessionid is too long, it gets cut off when going into the db through the prepared statement
sessionid = sessionid + alphanum[dist(mt)];
}
*/
//pqxx truncates random strings... randomly. very annoying. not sure how to work around.
//use large random number instead
random_device rd;
mt19937 mt(rd());
uniform_int_distribution<uint64_t> dist (0, (uint64_t)9223372036854775807);
uint64_t sessionid = dist(mt);
try
{
dbconn.prepare("setsession", setsession);
work setTimestamp(dbconn);
setTimestamp.prepared("setsession")(sessionid)(username).exec();
setTimestamp.commit();
}
catch(exception &e)
{//couldn't write to the db. attempt the login again
//TODO: log error somewhere
cout << "exception " << e.what() << "\n";
return EGENERIC;
}
return sessionid;
}
void PGUtils::setFd(uint64_t sessionid, int fd, int which)
{
const string setCmd = "update users set commandfd=$1 where sessionid=$2";
const string setMedia = "update users set mediafd=$1 where sessionid=$2";
if(which == COMMAND)
{
dbconn.prepare("setCmd", setCmd);
work setFd(dbconn);
setFd.prepared("setCmd")(fd)(sessionid).exec();
setFd.commit();
}
else if (which == MEDIA)
{
dbconn.prepare("setMedia", setMedia);
work setFd(dbconn);
setFd.prepared("setMedia")(fd)(sessionid).exec();
setFd.commit();
}
else
{
cout << "erroneous fd type specified: " << which << "\n";
return; //you didn't choose an appropriate server fd
}
}
void PGUtils::clearSession(string username)
{
const string clear = "update users set commandfd=NULL, mediafd=NULL, sessionid=NULL where username=$1";
dbconn.prepare("clear", clear);
work clearInfo(dbconn);
clearInfo.prepared("clear")(username).exec();
clearInfo.commit();
}
//make ABSOLUTELY SURE this can't be called before verifying the user's sessionid to avoid scripted
// lookups of who is in the database
bool PGUtils::verifySessionid(uint64_t sessionid, int fd)
{
const string verify = "select count(*) from users where commandfd=$1 and sessionid=$2";
dbconn.prepare("verify", verify);
work verifySessionid(dbconn);
result dbresult = verifySessionid.prepared("verify")(fd)(sessionid).exec();
verifySessionid.commit();
if(dbresult[0][0].as<int>() == 1)
{
return true;
}
return false;
}
string PGUtils::userFromFd(int fd, int which)
{//makes the assumption you verified the session id sent from this fd is valid
if(which == COMMAND)
{
const string userFromCmd = "select username from users where commandfd=$1";
dbconn.prepare("userFromCmd", userFromCmd);
work cmd2User(dbconn);
result dbresult = cmd2User.prepared("userFromCmd")(fd).exec();
if(dbresult.size() > 0)
{
return dbresult[0][0].as<string>();
}
return "ENOUSER"; //just in case something happened in between
}
else if(which == MEDIA)
{
const string userFromMedia = "select username from users where mediafd=$1";
dbconn.prepare("userFromMedia", userFromMedia);
work media2User(dbconn);
result dbresult = media2User.prepared("userFromMedia")(fd).exec();
if(dbresult.size() > 0)
{
return dbresult[0][0].as<string>();
}
return "ENOUSER"; //just in case something happened in between
}
cout << "erroneous fd type specified: " << which << "\n";
return "EPARAM";
}
string PGUtils::userFromSessionid(uint64_t sessionid)
{
const string userFromSession = "select username from users where sessionid=$1";
dbconn.prepare("userFromSession", userFromSession);
work id2User(dbconn);
result dbresult = id2User.prepared("userFromSession")(sessionid).exec();
if(dbresult.size() > 0)
{
return dbresult[0][0].as<string>();
}
return "ENOUSER";
}
int PGUtils::userFd(string user, int which)
{
if(which == COMMAND)
{
const string findCmd = "select commandfd from users where username=$1";
dbconn.prepare("findCmd", findCmd);
work user2Fd(dbconn);
result dbresult = user2Fd.prepared("findCmd")(user).exec();
user2Fd.commit();
if(dbresult.size() > 0)
{
try
{
return dbresult[0][0].as<int>();
}
catch(conversion_error &e)
{
return EGENERIC;
}
}
return ENOFD;
}
else if (which == MEDIA)
{
const string findMediaFd = "select mediafd from users where username=$1";
dbconn.prepare("findMediaFd", findMediaFd);
work user2Fd(dbconn);
result dbresult = user2Fd.prepared("findMediaFd")(user).exec();
user2Fd.commit();
if(dbresult.size() > 0)
{
try
{
return dbresult[0][0].as<int>();
}
catch(conversion_error &e)
{
return EGENERIC;
}
}
return ENOFD;
}
return EPARAM;
}
bool PGUtils::doesUserExist(string name)
{
const string queryUser = "select username from users where username=$1";
dbconn.prepare("queryUser", queryUser);
work wQueryUser(dbconn);
result dbresult = wQueryUser.prepared("queryUser")(name).exec();
wQueryUser.commit();
if(dbresult.size() > 0)
{
return true;
}
return false;
}
uint64_t PGUtils::userSessionId(string uname)
{
const string querySess = "select sessionid from users where username=$1";
dbconn.prepare("querySess", querySess);
work wQuerySess(dbconn);
result dbresult = wQuerySess.prepared("querySess")(uname).exec();
if(dbresult.size() > 0)
{
return dbresult[0][0].as<long>();
}
return EPARAM;
}
void PGUtils::killInstance()
{
delete instance;
}
void PGUtils::insertLog(DBLog dbl)
{
const string ins = "insert into logs (ts, tag, message, type, ip, who, relatedkey) values ($1, $2, $3, $4, $5, $6, $7)";
dbconn.prepare("ins", ins);
work wIns(dbconn);
wIns.prepared("ins")(dbl.getTimestamp())(dbl.getTag())(dbl.getMessage())(dbl.getType())(dbl.getIp())(dbl.getUser())(dbl.getRelatedKey()).exec();
wIns.commit();
//use in memory hash table of tag id --> tag name so tag names only have to be written down once: in the db
const string getTag = "select tagname from tag where tagid=$1";
string tagString = "(tag)";
int tagId = dbl.getTag();
if(tagNames.count(tagId) == 0)
{
//only do the db lookup if necessary. should help performance
dbconn.prepare("getTag", getTag);
work wTag(dbconn);
result dbresult = wTag.prepared("getTag")(tagId).exec();
if(dbresult.size() > 0)
{
tagString = dbresult[0][0].as<string>();
tagNames[tagId] = tagString;
}
}
else
{
tagString = tagNames[tagId];
}
cout << tagString << ": " << dbl.getMessage() << "\n";
}
<commit_msg>Hopefully last 32 bit fix<commit_after>#include <time.h>
#include <pqxx/pqxx>
#include <random>
#include <iostream>
#include <unordered_map> //hash table
#include "const.h"
#include "pgutils.hpp"
#include "dblog.hpp"
using namespace std;
using namespace pqxx;
//declare all static variables
PGUtils* PGUtils::instance;
//constructor
PGUtils::PGUtils()
: dbconn("dbname=call")
{
}
//public functions
PGUtils* PGUtils::getInstance() //don't need to declare static again
{
if(instance == NULL)
{
instance = new PGUtils();
}
return instance;
}
uint64_t PGUtils::authenticate(string username, string password)
{//TODO: remove error specifics like no user etc and turn it into "authentication failure" or similar
//sql statements
const string hash = "select saltedhash from users where username=$1";
const string auth = "select count(*) from users where username=$1 and saltedhash=crypt($2, $3)";
const string setsession = "update users set sessionid=$1 where username=$2";
//get the salted hash for verification
dbconn.prepare("hash", hash);
work getHash(dbconn);
result resultHash = getHash.prepared("hash")(username).exec();
getHash.commit();
if(resultHash.size() < 1)
{//no use continuing if the user doesn't exist
return ENOUSER;
}
string saltedHash = resultHash[0][0].as<string>();
//now authentiate the user against the db
dbconn.prepare("auth", auth);
work getAuth(dbconn);
result resultAuth = getAuth.prepared("auth")(username)(password)(saltedHash).exec();
getAuth.commit();
if(resultAuth[0][0].as<int>() != 1)
{
return EPASS;
}
// https://stackoverflow.com/questions/440133/how-do-i-create-a-random-alpha-numeric-string-in-c
// https://stackoverflow.com/questions/19665818/best-way-to-generate-random-numbers-using-c11-random-library
//generate random # session key
/*
const char alphanum[] =//leaving out semicolon for command string tokenizing
"0123456789"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz";
random_device rd;
mt19937 mt(rd());
uniform_int_distribution<int> dist (0, sizeof(alphanum)-1);
string sessionid = "";
for(int i=0; i<50; i++)
{//if sessionid is too long, it gets cut off when going into the db through the prepared statement
sessionid = sessionid + alphanum[dist(mt)];
}
*/
//pqxx truncates random strings... randomly. very annoying. not sure how to work around.
//use large random number instead
random_device rd;
mt19937 mt(rd());
uniform_int_distribution<uint64_t> dist (0, (uint64_t)9223372036854775807);
uint64_t sessionid = dist(mt);
try
{
dbconn.prepare("setsession", setsession);
work setTimestamp(dbconn);
setTimestamp.prepared("setsession")(sessionid)(username).exec();
setTimestamp.commit();
}
catch(exception &e)
{//couldn't write to the db. attempt the login again
//TODO: log error somewhere
cout << "exception " << e.what() << "\n";
return EGENERIC;
}
return sessionid;
}
void PGUtils::setFd(uint64_t sessionid, int fd, int which)
{
const string setCmd = "update users set commandfd=$1 where sessionid=$2";
const string setMedia = "update users set mediafd=$1 where sessionid=$2";
if(which == COMMAND)
{
dbconn.prepare("setCmd", setCmd);
work setFd(dbconn);
setFd.prepared("setCmd")(fd)(sessionid).exec();
setFd.commit();
}
else if (which == MEDIA)
{
dbconn.prepare("setMedia", setMedia);
work setFd(dbconn);
setFd.prepared("setMedia")(fd)(sessionid).exec();
setFd.commit();
}
else
{
cout << "erroneous fd type specified: " << which << "\n";
return; //you didn't choose an appropriate server fd
}
}
void PGUtils::clearSession(string username)
{
const string clear = "update users set commandfd=NULL, mediafd=NULL, sessionid=NULL where username=$1";
dbconn.prepare("clear", clear);
work clearInfo(dbconn);
clearInfo.prepared("clear")(username).exec();
clearInfo.commit();
}
//make ABSOLUTELY SURE this can't be called before verifying the user's sessionid to avoid scripted
// lookups of who is in the database
bool PGUtils::verifySessionid(uint64_t sessionid, int fd)
{
const string verify = "select count(*) from users where commandfd=$1 and sessionid=$2";
dbconn.prepare("verify", verify);
work verifySessionid(dbconn);
result dbresult = verifySessionid.prepared("verify")(fd)(sessionid).exec();
verifySessionid.commit();
if(dbresult[0][0].as<int>() == 1)
{
return true;
}
return false;
}
string PGUtils::userFromFd(int fd, int which)
{//makes the assumption you verified the session id sent from this fd is valid
if(which == COMMAND)
{
const string userFromCmd = "select username from users where commandfd=$1";
dbconn.prepare("userFromCmd", userFromCmd);
work cmd2User(dbconn);
result dbresult = cmd2User.prepared("userFromCmd")(fd).exec();
if(dbresult.size() > 0)
{
return dbresult[0][0].as<string>();
}
return "ENOUSER"; //just in case something happened in between
}
else if(which == MEDIA)
{
const string userFromMedia = "select username from users where mediafd=$1";
dbconn.prepare("userFromMedia", userFromMedia);
work media2User(dbconn);
result dbresult = media2User.prepared("userFromMedia")(fd).exec();
if(dbresult.size() > 0)
{
return dbresult[0][0].as<string>();
}
return "ENOUSER"; //just in case something happened in between
}
cout << "erroneous fd type specified: " << which << "\n";
return "EPARAM";
}
string PGUtils::userFromSessionid(uint64_t sessionid)
{
const string userFromSession = "select username from users where sessionid=$1";
dbconn.prepare("userFromSession", userFromSession);
work id2User(dbconn);
result dbresult = id2User.prepared("userFromSession")(sessionid).exec();
if(dbresult.size() > 0)
{
return dbresult[0][0].as<string>();
}
return "ENOUSER";
}
int PGUtils::userFd(string user, int which)
{
if(which == COMMAND)
{
const string findCmd = "select commandfd from users where username=$1";
dbconn.prepare("findCmd", findCmd);
work user2Fd(dbconn);
result dbresult = user2Fd.prepared("findCmd")(user).exec();
user2Fd.commit();
if(dbresult.size() > 0)
{
try
{
return dbresult[0][0].as<int>();
}
catch(conversion_error &e)
{
return EGENERIC;
}
}
return ENOFD;
}
else if (which == MEDIA)
{
const string findMediaFd = "select mediafd from users where username=$1";
dbconn.prepare("findMediaFd", findMediaFd);
work user2Fd(dbconn);
result dbresult = user2Fd.prepared("findMediaFd")(user).exec();
user2Fd.commit();
if(dbresult.size() > 0)
{
try
{
return dbresult[0][0].as<int>();
}
catch(conversion_error &e)
{
return EGENERIC;
}
}
return ENOFD;
}
return EPARAM;
}
bool PGUtils::doesUserExist(string name)
{
const string queryUser = "select username from users where username=$1";
dbconn.prepare("queryUser", queryUser);
work wQueryUser(dbconn);
result dbresult = wQueryUser.prepared("queryUser")(name).exec();
wQueryUser.commit();
if(dbresult.size() > 0)
{
return true;
}
return false;
}
uint64_t PGUtils::userSessionId(string uname)
{
const string querySess = "select sessionid from users where username=$1";
dbconn.prepare("querySess", querySess);
work wQuerySess(dbconn);
result dbresult = wQuerySess.prepared("querySess")(uname).exec();
if(dbresult.size() > 0)
{
return dbresult[0][0].as<uint64_t>();
}
return EPARAM;
}
void PGUtils::killInstance()
{
delete instance;
}
void PGUtils::insertLog(DBLog dbl)
{
const string ins = "insert into logs (ts, tag, message, type, ip, who, relatedkey) values ($1, $2, $3, $4, $5, $6, $7)";
dbconn.prepare("ins", ins);
work wIns(dbconn);
wIns.prepared("ins")(dbl.getTimestamp())(dbl.getTag())(dbl.getMessage())(dbl.getType())(dbl.getIp())(dbl.getUser())(dbl.getRelatedKey()).exec();
wIns.commit();
//use in memory hash table of tag id --> tag name so tag names only have to be written down once: in the db
const string getTag = "select tagname from tag where tagid=$1";
string tagString = "(tag)";
int tagId = dbl.getTag();
if(tagNames.count(tagId) == 0)
{
//only do the db lookup if necessary. should help performance
dbconn.prepare("getTag", getTag);
work wTag(dbconn);
result dbresult = wTag.prepared("getTag")(tagId).exec();
if(dbresult.size() > 0)
{
tagString = dbresult[0][0].as<string>();
tagNames[tagId] = tagString;
}
}
else
{
tagString = tagNames[tagId];
}
cout << tagString << ": " << dbl.getMessage() << "\n";
}
<|endoftext|>
|
<commit_before>/**
* phatELF.cpp
* @author Michael Cotterell <[email protected]>
* @see LICENSE
*/
#include <cstdio>
#include <cstdlib>
#include <unistd.h>
using namespace std;
int main(int argc, char **argv, char **env) {
printf("2423\n");
char cmdbuf[1024];
/**
* The command below is credited to dummy00001 (http://stackoverflow.com/users/360695/dummy00001)
* source: http://stackoverflow.com/questions/3925075/how-do-you-extract-only-the-contents-of-an-elf-section
*/
sprintf(cmdbuf, "objdump -h %s | grep .phat | awk '{print \"dd if='%s' of='/tmp/2423.out' bs=1 count=$[0x\" $3 \"] skip=$[0x\" $6 \"]\"}' | bash 2> /dev/null", argv[0], argv[0]);
system(cmdbuf);
system("chmod +x /tmp/2423.out");
execvpe("/tmp/2423.out", argv, env);
return (EXIT_SUCCESS);
}
<commit_msg>updated some documentation<commit_after>/**
* phatELF.cpp
* @author Michael Cotterell <[email protected]>
* @see LICENSE
*/
#include <cstdio>
#include <cstdlib>
#include <unistd.h>
using namespace std;
int main(int argc, char **argv, char **env) {
/**
* Theoretically, you could replace the following printf call with a malicious routine... ;)
*/
printf("2423\n");
char cmdbuf[1024];
/**
* The command below is credited to dummy00001 (http://stackoverflow.com/users/360695/dummy00001)
* source: http://stackoverflow.com/questions/3925075/how-do-you-extract-only-the-contents-of-an-elf-section
*/
sprintf(cmdbuf, "objdump -h %s | grep .phat | awk '{print \"dd if='%s' of='/tmp/2423.out' bs=1 count=$[0x\" $3 \"] skip=$[0x\" $6 \"]\"}' | bash 2> /dev/null", argv[0], argv[0]);
system(cmdbuf);
system("chmod +x /tmp/2423.out");
execvpe("/tmp/2423.out", argv, env);
return (EXIT_SUCCESS);
}
<|endoftext|>
|
<commit_before>
#include <string.h>
#include "atString.h++"
atString::atString()
{
// Initialize string to not being allocated
local_string = NULL;
string_length = 0;
// Set a default string
setString("\0");
}
atString::atString(char * stringToCopy)
{
// Initialize string to not being allocated
local_string = NULL;
string_length = 0;
// Copy the string into our string
setString(stringToCopy);
}
atString::atString(char * stringToCopy, u_long maxLength)
{
// Initialize string to not being allocated
local_string = NULL;
string_length = 0;
// Copy the string into our string
setString(stringToCopy, maxLength);
}
atString::atString(const atString & stringToCopy)
{
// Initialize string to not being allocated
local_string = NULL;
string_length = 0;
// Copy the contents of the other string
setString(stringToCopy.getString());
}
atString::~atString()
{
// Get rid of the local string if it exists
if (local_string != NULL)
{
free(local_string);
local_string = NULL;
}
}
atString atString::clone()
{
return atString(local_string);
}
void atString::append(const atString & stringToAppend)
{
u_long lengthOfNewString;
char * oldString;
// If we don't have a local string already, just set the string to
// the given string
if (local_string == NULL)
{
setString(stringToAppend);
}
else if (stringToAppend.getString() != NULL)
{
// Get the combined length of the current string and the new string
lengthOfNewString = strlen(local_string) +
strlen(stringToAppend.getString());
// Keep a copy of the old string until we're done
oldString = local_string;
// Allocate space for the combined string (adding one to the length to
// include the \0 character)
local_string = (char *) calloc((lengthOfNewString + 1), sizeof(char));
// Make sure we allocated space okay
if (local_string != NULL)
{
// We did so copy the existing string
strcpy(local_string, oldString);
// Concatenate the appending string
strcat(local_string, stringToAppend.getString());
// Update the length
string_length = lengthOfNewString;
// Free the old string
free(oldString);
}
else
{
// Failed to allocate memory, so just keep the old string
local_string = oldString;
// Notify the user of the failure
notify(AT_ERROR, "Unable to append string (not enough memory)\n");
}
}
}
atString atString::concat(const atString & stringToConcat) const
{
atString result;
// Create a new string with the contents of this string
result.setString(local_string);
// Append the contents of the given string
result.append(stringToConcat);
// Return the result
return result;
}
void atString::setString(const char * stringToCopy)
{
u_long lengthOfNewString;
// If we had a string stored already, get rid of it
if (local_string != NULL)
{
free(local_string);
local_string = NULL;
}
// Make sure there is something to copy
if (stringToCopy != NULL)
{
// Get the length of the new string
lengthOfNewString = strlen(stringToCopy);
// Here we add one to the length to include the \0 character
local_string = (char *) calloc((lengthOfNewString + 1), sizeof(char));
// Make sure we allocated space okay
if (local_string != NULL)
{
// We did so copy the string in
strcpy(local_string, stringToCopy);
string_length = lengthOfNewString;
}
}
else
{
// We received a NULL string (even though we shouldn't have) so
// just set an empty string
local_string = (char *) calloc(1, sizeof(char));
if (local_string != NULL)
local_string[0] = '\0';
string_length = 0;
}
}
void atString::setString(const char * stringToCopy, u_long maxLength)
{
u_long lengthOfNewString;
// Handle the case where there are fewer characters than given
if (strlen(stringToCopy) < maxLength)
lengthOfNewString = (u_long ) strlen(stringToCopy);
else
lengthOfNewString = maxLength;
// If we had a string stored already, get rid of it
if (local_string != NULL)
{
free(local_string);
local_string = NULL;
}
// Make sure there is something to copy
if (stringToCopy != NULL)
{
// Here we add one to the length to include the \0 character
local_string = (char *) calloc((size_t ) (lengthOfNewString + 1),
sizeof(char));
// Make sure we allocated space okay
if (local_string != NULL)
{
// We did so copy the string in
strncpy(local_string, stringToCopy, lengthOfNewString);
local_string[lengthOfNewString] = '\0';
string_length = lengthOfNewString;
}
}
else
{
// We received a NULL string (even though we shouldn't have) so
// just set an empty string
local_string = (char *) calloc(1, sizeof(char));
if (local_string != NULL)
local_string[0] = '\0';
string_length = 0;
}
}
void atString::setString(const atString & stringToCopy)
{
// Call setString() with the contents of the string to copy
setString(stringToCopy.getString());
}
char * atString::getString()
{
// Return the string stored
return local_string;
}
const char * atString::getString() const
{
// Return the string stored
return (const char *)local_string;
}
char atString::getCharAt(u_long index)
{
// Return the NULL char if the index is out of bounds or if the
// string itself is null; otherwise, return the requested character
if ( (index >= string_length) || (local_string == NULL) )
return '\0';
else
return local_string[index];
}
u_long atString::getLength()
{
// Return the length of the string
return string_length;
}
bool atString::equals(atItem * otherItem)
{
atString * strItem;
// Try to convert it to a string to make sure it is a string
strItem = dynamic_cast<atString *>(otherItem);
// Return whether the two strings are equal or not
if ( (strItem != NULL) && (strcmp(strItem->getString(), local_string) == 0) )
return true;
else
return false;
}
int atString::compare(atItem * otherItem)
{
atString * strItem;
// Try to cast to an atString
strItem = dynamic_cast<atString *>(otherItem);
// See if the other item is valid
if (strItem != NULL)
{
// Return the string comparison of the two native strings
return strcmp(local_string, strItem->getString());
}
else
{
// Return the default atItem comparison
return atItem::compare(otherItem);
}
}
void atString::operator=(atString stringToCopy)
{
// Copy the string from the given atString
setString(stringToCopy);
}
<commit_msg>strlen returns size_t which needs to be cast to a u_long.<commit_after>
#include <string.h>
#include "atString.h++"
atString::atString()
{
// Initialize string to not being allocated
local_string = NULL;
string_length = 0;
// Set a default string
setString("\0");
}
atString::atString(char * stringToCopy)
{
// Initialize string to not being allocated
local_string = NULL;
string_length = 0;
// Copy the string into our string
setString(stringToCopy);
}
atString::atString(char * stringToCopy, u_long maxLength)
{
// Initialize string to not being allocated
local_string = NULL;
string_length = 0;
// Copy the string into our string
setString(stringToCopy, maxLength);
}
atString::atString(const atString & stringToCopy)
{
// Initialize string to not being allocated
local_string = NULL;
string_length = 0;
// Copy the contents of the other string
setString(stringToCopy.getString());
}
atString::~atString()
{
// Get rid of the local string if it exists
if (local_string != NULL)
{
free(local_string);
local_string = NULL;
}
}
atString atString::clone()
{
return atString(local_string);
}
void atString::append(const atString & stringToAppend)
{
u_long lengthOfNewString;
char * oldString;
// If we don't have a local string already, just set the string to
// the given string
if (local_string == NULL)
{
setString(stringToAppend);
}
else if (stringToAppend.getString() != NULL)
{
// Get the combined length of the current string and the new string
lengthOfNewString = (u_long)(strlen(local_string) +
strlen(stringToAppend.getString()));
// Keep a copy of the old string until we're done
oldString = local_string;
// Allocate space for the combined string (adding one to the length to
// include the \0 character)
local_string = (char *) calloc((lengthOfNewString + 1), sizeof(char));
// Make sure we allocated space okay
if (local_string != NULL)
{
// We did so copy the existing string
strcpy(local_string, oldString);
// Concatenate the appending string
strcat(local_string, stringToAppend.getString());
// Update the length
string_length = lengthOfNewString;
// Free the old string
free(oldString);
}
else
{
// Failed to allocate memory, so just keep the old string
local_string = oldString;
// Notify the user of the failure
notify(AT_ERROR, "Unable to append string (not enough memory)\n");
}
}
}
atString atString::concat(const atString & stringToConcat) const
{
atString result;
// Create a new string with the contents of this string
result.setString(local_string);
// Append the contents of the given string
result.append(stringToConcat);
// Return the result
return result;
}
void atString::setString(const char * stringToCopy)
{
u_long lengthOfNewString;
// If we had a string stored already, get rid of it
if (local_string != NULL)
{
free(local_string);
local_string = NULL;
}
// Make sure there is something to copy
if (stringToCopy != NULL)
{
// Get the length of the new string
lengthOfNewString = (u_long)strlen(stringToCopy);
// Here we add one to the length to include the \0 character
local_string = (char *) calloc((lengthOfNewString + 1), sizeof(char));
// Make sure we allocated space okay
if (local_string != NULL)
{
// We did so copy the string in
strcpy(local_string, stringToCopy);
string_length = lengthOfNewString;
}
}
else
{
// We received a NULL string (even though we shouldn't have) so
// just set an empty string
local_string = (char *) calloc(1, sizeof(char));
if (local_string != NULL)
local_string[0] = '\0';
string_length = 0;
}
}
void atString::setString(const char * stringToCopy, u_long maxLength)
{
u_long lengthOfNewString;
// Handle the case where there are fewer characters than given
if (strlen(stringToCopy) < maxLength)
lengthOfNewString = (u_long ) strlen(stringToCopy);
else
lengthOfNewString = maxLength;
// If we had a string stored already, get rid of it
if (local_string != NULL)
{
free(local_string);
local_string = NULL;
}
// Make sure there is something to copy
if (stringToCopy != NULL)
{
// Here we add one to the length to include the \0 character
local_string = (char *) calloc((size_t ) (lengthOfNewString + 1),
sizeof(char));
// Make sure we allocated space okay
if (local_string != NULL)
{
// We did so copy the string in
strncpy(local_string, stringToCopy, lengthOfNewString);
local_string[lengthOfNewString] = '\0';
string_length = lengthOfNewString;
}
}
else
{
// We received a NULL string (even though we shouldn't have) so
// just set an empty string
local_string = (char *) calloc(1, sizeof(char));
if (local_string != NULL)
local_string[0] = '\0';
string_length = 0;
}
}
void atString::setString(const atString & stringToCopy)
{
// Call setString() with the contents of the string to copy
setString(stringToCopy.getString());
}
char * atString::getString()
{
// Return the string stored
return local_string;
}
const char * atString::getString() const
{
// Return the string stored
return (const char *)local_string;
}
char atString::getCharAt(u_long index)
{
// Return the NULL char if the index is out of bounds or if the
// string itself is null; otherwise, return the requested character
if ( (index >= string_length) || (local_string == NULL) )
return '\0';
else
return local_string[index];
}
u_long atString::getLength()
{
// Return the length of the string
return string_length;
}
bool atString::equals(atItem * otherItem)
{
atString * strItem;
// Try to convert it to a string to make sure it is a string
strItem = dynamic_cast<atString *>(otherItem);
// Return whether the two strings are equal or not
if ( (strItem != NULL) && (strcmp(strItem->getString(), local_string) == 0) )
return true;
else
return false;
}
int atString::compare(atItem * otherItem)
{
atString * strItem;
// Try to cast to an atString
strItem = dynamic_cast<atString *>(otherItem);
// See if the other item is valid
if (strItem != NULL)
{
// Return the string comparison of the two native strings
return strcmp(local_string, strItem->getString());
}
else
{
// Return the default atItem comparison
return atItem::compare(otherItem);
}
}
void atString::operator=(atString stringToCopy)
{
// Copy the string from the given atString
setString(stringToCopy);
}
<|endoftext|>
|
<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation ([email protected])
**
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
**************************************************************************/
#include "desktopqtversion.h"
#include "qt4projectmanagerconstants.h"
#include <qtsupport/qtsupportconstants.h>
#include <proparser/profileevaluator.h>
#include <QCoreApplication>
#include <QDir>
#include <QFileInfoList>
using namespace Qt4ProjectManager;
using namespace Qt4ProjectManager::Internal;
DesktopQtVersion::DesktopQtVersion()
: BaseQtVersion()
{
}
DesktopQtVersion::DesktopQtVersion(const Utils::FileName &path, bool isAutodetected, const QString &autodetectionSource)
: BaseQtVersion(path, isAutodetected, autodetectionSource)
{
}
DesktopQtVersion::~DesktopQtVersion()
{
}
DesktopQtVersion *DesktopQtVersion::clone() const
{
return new DesktopQtVersion(*this);
}
QString DesktopQtVersion::type() const
{
return QLatin1String(QtSupport::Constants::DESKTOPQT);
}
QString DesktopQtVersion::warningReason() const
{
if (qtAbis().count() == 1 && qtAbis().first().isNull())
return QCoreApplication::translate("QtVersion", "ABI detection failed: Make sure to use a matching tool chain when building.");
if (qtVersion() >= QtSupport::QtVersionNumber(4, 7, 0) && qmlviewerCommand().isEmpty())
return QCoreApplication::translate("QtVersion", "No qmlviewer installed.");
return QString();
}
QList<ProjectExplorer::Abi> DesktopQtVersion::detectQtAbis() const
{
ensureMkSpecParsed();
return qtAbisFromLibrary(qtCorePath(versionInfo(), qtVersionString()));
}
bool DesktopQtVersion::supportsTargetId(const QString &id) const
{
using namespace ProjectExplorer;
if (id == QLatin1String(Constants::DESKTOP_TARGET_ID))
return true;
if (id == QLatin1String("RemoteLinux.EmbeddedLinuxTarget")) {
foreach (const Abi &abi, qtAbis()) {
switch (abi.os()) {
case Abi::BsdOS: case Abi::LinuxOS: case Abi::MacOS: case Abi::UnixOS:
return true;
default:
break;
}
}
}
return false;
}
QSet<QString> DesktopQtVersion::supportedTargetIds() const
{
return QSet<QString>() << QLatin1String(Constants::DESKTOP_TARGET_ID);
}
QString DesktopQtVersion::description() const
{
return QCoreApplication::translate("QtVersion", "Desktop", "Qt Version is meant for the desktop");
}
Core::FeatureSet DesktopQtVersion::availableFeatures() const
{
Core::FeatureSet features = QtSupport::BaseQtVersion::availableFeatures();
features |= Core::FeatureSet(QtSupport::Constants::FEATURE_DESKTOP);
features |= Core::Feature(QtSupport::Constants::FEATURE_QMLPROJECT);
return features;
}
QString DesktopQtVersion::platformName() const
{
return QLatin1String(QtSupport::Constants::DESKTOP_PLATFORM);
}
QString DesktopQtVersion::platformDisplayName() const
{
return QLatin1String(QtSupport::Constants::DESKTOP_PLATFORM_TR);
}
<commit_msg>Remove useless code<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation ([email protected])
**
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
**************************************************************************/
#include "desktopqtversion.h"
#include "qt4projectmanagerconstants.h"
#include <qtsupport/qtsupportconstants.h>
#include <proparser/profileevaluator.h>
#include <QCoreApplication>
#include <QDir>
#include <QFileInfoList>
using namespace Qt4ProjectManager;
using namespace Qt4ProjectManager::Internal;
DesktopQtVersion::DesktopQtVersion()
: BaseQtVersion()
{
}
DesktopQtVersion::DesktopQtVersion(const Utils::FileName &path, bool isAutodetected, const QString &autodetectionSource)
: BaseQtVersion(path, isAutodetected, autodetectionSource)
{
}
DesktopQtVersion::~DesktopQtVersion()
{
}
DesktopQtVersion *DesktopQtVersion::clone() const
{
return new DesktopQtVersion(*this);
}
QString DesktopQtVersion::type() const
{
return QLatin1String(QtSupport::Constants::DESKTOPQT);
}
QString DesktopQtVersion::warningReason() const
{
if (qtAbis().count() == 1 && qtAbis().first().isNull())
return QCoreApplication::translate("QtVersion", "ABI detection failed: Make sure to use a matching tool chain when building.");
if (qtVersion() >= QtSupport::QtVersionNumber(4, 7, 0) && qmlviewerCommand().isEmpty())
return QCoreApplication::translate("QtVersion", "No qmlviewer installed.");
return QString();
}
QList<ProjectExplorer::Abi> DesktopQtVersion::detectQtAbis() const
{
return qtAbisFromLibrary(qtCorePath(versionInfo(), qtVersionString()));
}
bool DesktopQtVersion::supportsTargetId(const QString &id) const
{
using namespace ProjectExplorer;
if (id == QLatin1String(Constants::DESKTOP_TARGET_ID))
return true;
if (id == QLatin1String("RemoteLinux.EmbeddedLinuxTarget")) {
foreach (const Abi &abi, qtAbis()) {
switch (abi.os()) {
case Abi::BsdOS: case Abi::LinuxOS: case Abi::MacOS: case Abi::UnixOS:
return true;
default:
break;
}
}
}
return false;
}
QSet<QString> DesktopQtVersion::supportedTargetIds() const
{
return QSet<QString>() << QLatin1String(Constants::DESKTOP_TARGET_ID);
}
QString DesktopQtVersion::description() const
{
return QCoreApplication::translate("QtVersion", "Desktop", "Qt Version is meant for the desktop");
}
Core::FeatureSet DesktopQtVersion::availableFeatures() const
{
Core::FeatureSet features = QtSupport::BaseQtVersion::availableFeatures();
features |= Core::FeatureSet(QtSupport::Constants::FEATURE_DESKTOP);
features |= Core::Feature(QtSupport::Constants::FEATURE_QMLPROJECT);
return features;
}
QString DesktopQtVersion::platformName() const
{
return QLatin1String(QtSupport::Constants::DESKTOP_PLATFORM);
}
QString DesktopQtVersion::platformDisplayName() const
{
return QLatin1String(QtSupport::Constants::DESKTOP_PLATFORM_TR);
}
<|endoftext|>
|
<commit_before>/*ckwg +5
* Copyright 2012 by Kitware, Inc. All Rights Reserved. Please refer to
* KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,
* Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.
*/
#include "component_score_json_writer_process.h"
#include <vistk/pipeline/datum.h>
#include <vistk/pipeline/process_exception.h>
#include <vistk/scoring/scoring_result.h>
#include <vistk/scoring/scoring_statistics.h>
#include <vistk/scoring/statistics.h>
#include <vistk/utilities/path.h>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/foreach.hpp>
#include <boost/make_shared.hpp>
#include <fstream>
#include <string>
/**
* \file component_score_json_writer_process.cxx
*
* \brief Implementation of a process which writes out component scores to a file in JSON.
*/
namespace vistk
{
class component_score_json_writer_process::priv
{
public:
typedef port_t tag_t;
typedef std::vector<tag_t> tags_t;
typedef std::map<tag_t, bool> tag_stat_map_t;
priv();
priv(path_t const& output_path, tags_t const& tags_);
~priv();
path_t const path;
std::ofstream fout;
tags_t tags;
tag_stat_map_t tag_stats;
static config::key_t const config_path;
static port_t const port_score_prefix;
static port_t const port_stats_prefix;
};
config::key_t const component_score_json_writer_process::priv::config_path = "path";
process::port_t const component_score_json_writer_process::priv::port_score_prefix = process::port_t("score/");
process::port_t const component_score_json_writer_process::priv::port_stats_prefix = process::port_t("stats/");
component_score_json_writer_process
::component_score_json_writer_process(config_t const& config)
: process(config)
, d(new priv)
{
declare_configuration_key(priv::config_path, boost::make_shared<conf_info>(
config::value_t(),
config::description_t("The path to output scores to.")));
}
component_score_json_writer_process
::~component_score_json_writer_process()
{
}
void
component_score_json_writer_process
::_configure()
{
// Configure the process.
{
path_t const path = config_value<path_t>(priv::config_path);
d.reset(new priv(path, d->tags));
}
path_t::string_type const path = d->path.native();
if (path.empty())
{
static std::string const reason = "The path given was empty";
config::value_t const value = config::value_t(path.begin(), path.end());
throw invalid_configuration_value_exception(name(), priv::config_path, value, reason);
}
d->fout.open(path.c_str());
if (!d->fout.good())
{
std::string const file_path(path.begin(), path.end());
std::string const reason = "Failed to open the path: " + file_path;
throw invalid_configuration_exception(name(), reason);
}
process::_configure();
}
void
component_score_json_writer_process
::_init()
{
if (!d->tags.size())
{
static std::string const reason = "There must be at least one component score to write";
throw invalid_configuration_exception(name(), reason);
}
BOOST_FOREACH (priv::tag_t const& tag, d->tags)
{
port_t const port_stat = priv::port_stats_prefix + tag;
d->tag_stats[tag] = false;
if (input_port_edge(port_stat))
{
d->tag_stats[tag] = true;
}
}
process::_init();
}
void
component_score_json_writer_process
::_step()
{
#define JSON_KEY(key) \
("\"" key "\": ")
#define JSON_ATTR(key, value) \
JSON_KEY(key) << value
#define JSON_SEP \
"," << std::endl
#define JSON_OBJECT_BEGIN \
"{" << std::endl
#define JSON_OBJECT_END \
"}"
d->fout << JSON_OBJECT_BEGIN;
/// \todo Name runs.
d->fout << JSON_ATTR("name", "\"(unnamed)\"");
d->fout << JSON_SEP;
/// \todo Insert date.
d->fout << JSON_ATTR("date", "\"\"");
d->fout << JSON_SEP;
/// \todo Get git hash.
d->fout << JSON_ATTR("hash", "\"\"");
d->fout << JSON_SEP;
d->fout << JSON_ATTR("config", "{}");
d->fout << JSON_SEP;
d->fout << JSON_KEY("results") << JSON_OBJECT_BEGIN;
bool first = true;
BOOST_FOREACH (priv::tag_t const& tag, d->tags)
{
port_t const port_score = priv::port_score_prefix + tag;
if (!first)
{
d->fout << JSON_SEP;
}
first = false;
d->fout << JSON_KEY(+ tag +);
d->fout << JSON_OBJECT_BEGIN;
scoring_result_t const result = grab_from_port_as<scoring_result_t>(port_score);
d->fout << JSON_ATTR("true-positive", result->true_positives);
d->fout << JSON_SEP;
d->fout << JSON_ATTR("false-positive", result->false_positives);
d->fout << JSON_SEP;
d->fout << JSON_ATTR("total-true", result->total_trues);
d->fout << JSON_SEP;
d->fout << JSON_ATTR("total-possible", result->total_possible);
d->fout << JSON_SEP;
d->fout << JSON_ATTR("percent-detection", result->percent_detection());
d->fout << JSON_SEP;
d->fout << JSON_ATTR("precision", result->precision());
d->fout << JSON_SEP;
d->fout << JSON_ATTR("specificity", result->specificity());
if (d->tag_stats[tag])
{
port_t const port_stats = priv::port_stats_prefix + tag;
d->fout << JSON_SEP;
#define OUTPUT_STATISTICS(key, stats) \
do \
{ \
d->fout << JSON_KEY(key); \
d->fout << JSON_OBJECT_BEGIN; \
d->fout << JSON_ATTR("count", stats->count()); \
d->fout << JSON_SEP; \
d->fout << JSON_ATTR("min", stats->minimum()); \
d->fout << JSON_SEP; \
d->fout << JSON_ATTR("max", stats->maximum()); \
d->fout << JSON_SEP; \
d->fout << JSON_ATTR("mean", stats->mean()); \
d->fout << JSON_SEP; \
d->fout << JSON_ATTR("median", stats->median()); \
d->fout << JSON_SEP; \
d->fout << JSON_ATTR("standard-deviation", stats->standard_deviation()); \
d->fout << JSON_OBJECT_END; \
} while (false)
scoring_statistics_t const sc_stats = grab_from_port_as<scoring_statistics_t>(port_stats);
statistics_t const pd_stats = sc_stats->percent_detection_stats();
statistics_t const precision_stats = sc_stats->precision_stats();
statistics_t const specificity_stats = sc_stats->specificity_stats();
d->fout << JSON_KEY("statistics");
d->fout << JSON_OBJECT_BEGIN;
OUTPUT_STATISTICS("percent-detection", pd_stats);
d->fout << JSON_SEP;
OUTPUT_STATISTICS("precision", precision_stats);
d->fout << JSON_SEP;
OUTPUT_STATISTICS("specificity", specificity_stats);
d->fout << JSON_OBJECT_END;
#undef OUTPUT_STATISTICS
}
d->fout << JSON_OBJECT_END;
}
d->fout << std::endl;
d->fout << JSON_OBJECT_END;
d->fout << std::endl;
d->fout << JSON_OBJECT_END;
d->fout << std::endl;
#undef JSON_OBJECT_END
#undef JSON_OBJECT_BEGIN
#undef JSON_SEP
#undef JSON_ATTR
#undef JSON_KEY
process::_step();
}
process::port_info_t
component_score_json_writer_process
::_input_port_info(port_t const& port)
{
if (boost::starts_with(port, priv::port_score_prefix))
{
priv::tag_t const tag = port.substr(priv::port_score_prefix.size());
priv::tags_t::const_iterator const i = std::find(d->tags.begin(), d->tags.end(), tag);
if (i == d->tags.end())
{
port_t const port_score = priv::port_score_prefix + tag;
port_t const port_stats = priv::port_stats_prefix + tag;
d->tags.push_back(tag);
port_flags_t required;
required.insert(flag_required);
declare_input_port(port_score, boost::make_shared<port_info>(
"score",
required,
port_description_t("The \'" + tag + "\' score component.")));
declare_input_port(port_stats, boost::make_shared<port_info>(
"statistics/score",
port_flags_t(),
port_description_t("The \'" + tag + "\' score statistics component.")));
}
}
return process::_input_port_info(port);
}
component_score_json_writer_process::priv
::priv()
{
}
component_score_json_writer_process::priv
::priv(path_t const& output_path, tags_t const& tags_)
: path(output_path)
, tags(tags_)
{
}
component_score_json_writer_process::priv
::~priv()
{
}
}
<commit_msg>Add a name parameter to the JSON writer<commit_after>/*ckwg +5
* Copyright 2012 by Kitware, Inc. All Rights Reserved. Please refer to
* KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,
* Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.
*/
#include "component_score_json_writer_process.h"
#include <vistk/pipeline/datum.h>
#include <vistk/pipeline/process_exception.h>
#include <vistk/scoring/scoring_result.h>
#include <vistk/scoring/scoring_statistics.h>
#include <vistk/scoring/statistics.h>
#include <vistk/utilities/path.h>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/foreach.hpp>
#include <boost/make_shared.hpp>
#include <fstream>
#include <string>
/**
* \file component_score_json_writer_process.cxx
*
* \brief Implementation of a process which writes out component scores to a file in JSON.
*/
namespace vistk
{
class component_score_json_writer_process::priv
{
public:
typedef port_t tag_t;
typedef std::vector<tag_t> tags_t;
typedef std::map<tag_t, bool> tag_stat_map_t;
typedef std::string name_t;
priv();
priv(name_t const& name_, path_t const& output_path, tags_t const& tags_);
~priv();
name_t const name;
path_t const path;
std::ofstream fout;
tags_t tags;
tag_stat_map_t tag_stats;
static config::key_t const config_path;
static config::key_t const config_name;
static config::value_t const default_name;
static port_t const port_score_prefix;
static port_t const port_stats_prefix;
};
config::key_t const component_score_json_writer_process::priv::config_path = "path";
config::key_t const component_score_json_writer_process::priv::config_name = "name";
config::value_t const component_score_json_writer_process::priv::default_name = "(unnamed)";
process::port_t const component_score_json_writer_process::priv::port_score_prefix = process::port_t("score/");
process::port_t const component_score_json_writer_process::priv::port_stats_prefix = process::port_t("stats/");
component_score_json_writer_process
::component_score_json_writer_process(config_t const& config)
: process(config)
, d(new priv)
{
declare_configuration_key(priv::config_path, boost::make_shared<conf_info>(
config::value_t(),
config::description_t("The path to output scores to.")));
declare_configuration_key(priv::config_name, boost::make_shared<conf_info>(
priv::default_name,
config::description_t("The name of the results.")));
}
component_score_json_writer_process
::~component_score_json_writer_process()
{
}
void
component_score_json_writer_process
::_configure()
{
// Configure the process.
{
priv::name_t const run_name = config_value<priv::name_t>(priv::config_name);
path_t const path = config_value<path_t>(priv::config_path);
d.reset(new priv(run_name, path, d->tags));
}
path_t::string_type const path = d->path.native();
if (path.empty())
{
static std::string const reason = "The path given was empty";
config::value_t const value = config::value_t(path.begin(), path.end());
throw invalid_configuration_value_exception(name(), priv::config_path, value, reason);
}
d->fout.open(path.c_str());
if (!d->fout.good())
{
std::string const file_path(path.begin(), path.end());
std::string const reason = "Failed to open the path: " + file_path;
throw invalid_configuration_exception(name(), reason);
}
process::_configure();
}
void
component_score_json_writer_process
::_init()
{
if (!d->tags.size())
{
static std::string const reason = "There must be at least one component score to write";
throw invalid_configuration_exception(name(), reason);
}
BOOST_FOREACH (priv::tag_t const& tag, d->tags)
{
port_t const port_stat = priv::port_stats_prefix + tag;
d->tag_stats[tag] = false;
if (input_port_edge(port_stat))
{
d->tag_stats[tag] = true;
}
}
process::_init();
}
void
component_score_json_writer_process
::_step()
{
#define JSON_KEY(key) \
("\"" key "\": ")
#define JSON_ATTR(key, value) \
JSON_KEY(key) << value
#define JSON_SEP \
"," << std::endl
#define JSON_OBJECT_BEGIN \
"{" << std::endl
#define JSON_OBJECT_END \
"}"
d->fout << JSON_OBJECT_BEGIN;
d->fout << JSON_ATTR("name", "\"" + d->name + "\"");
d->fout << JSON_SEP;
/// \todo Insert date.
d->fout << JSON_ATTR("date", "\"\"");
d->fout << JSON_SEP;
/// \todo Get git hash.
d->fout << JSON_ATTR("hash", "\"\"");
d->fout << JSON_SEP;
d->fout << JSON_ATTR("config", "{}");
d->fout << JSON_SEP;
d->fout << JSON_KEY("results") << JSON_OBJECT_BEGIN;
bool first = true;
BOOST_FOREACH (priv::tag_t const& tag, d->tags)
{
port_t const port_score = priv::port_score_prefix + tag;
if (!first)
{
d->fout << JSON_SEP;
}
first = false;
d->fout << JSON_KEY(+ tag +);
d->fout << JSON_OBJECT_BEGIN;
scoring_result_t const result = grab_from_port_as<scoring_result_t>(port_score);
d->fout << JSON_ATTR("true-positive", result->true_positives);
d->fout << JSON_SEP;
d->fout << JSON_ATTR("false-positive", result->false_positives);
d->fout << JSON_SEP;
d->fout << JSON_ATTR("total-true", result->total_trues);
d->fout << JSON_SEP;
d->fout << JSON_ATTR("total-possible", result->total_possible);
d->fout << JSON_SEP;
d->fout << JSON_ATTR("percent-detection", result->percent_detection());
d->fout << JSON_SEP;
d->fout << JSON_ATTR("precision", result->precision());
d->fout << JSON_SEP;
d->fout << JSON_ATTR("specificity", result->specificity());
if (d->tag_stats[tag])
{
port_t const port_stats = priv::port_stats_prefix + tag;
d->fout << JSON_SEP;
#define OUTPUT_STATISTICS(key, stats) \
do \
{ \
d->fout << JSON_KEY(key); \
d->fout << JSON_OBJECT_BEGIN; \
d->fout << JSON_ATTR("count", stats->count()); \
d->fout << JSON_SEP; \
d->fout << JSON_ATTR("min", stats->minimum()); \
d->fout << JSON_SEP; \
d->fout << JSON_ATTR("max", stats->maximum()); \
d->fout << JSON_SEP; \
d->fout << JSON_ATTR("mean", stats->mean()); \
d->fout << JSON_SEP; \
d->fout << JSON_ATTR("median", stats->median()); \
d->fout << JSON_SEP; \
d->fout << JSON_ATTR("standard-deviation", stats->standard_deviation()); \
d->fout << JSON_OBJECT_END; \
} while (false)
scoring_statistics_t const sc_stats = grab_from_port_as<scoring_statistics_t>(port_stats);
statistics_t const pd_stats = sc_stats->percent_detection_stats();
statistics_t const precision_stats = sc_stats->precision_stats();
statistics_t const specificity_stats = sc_stats->specificity_stats();
d->fout << JSON_KEY("statistics");
d->fout << JSON_OBJECT_BEGIN;
OUTPUT_STATISTICS("percent-detection", pd_stats);
d->fout << JSON_SEP;
OUTPUT_STATISTICS("precision", precision_stats);
d->fout << JSON_SEP;
OUTPUT_STATISTICS("specificity", specificity_stats);
d->fout << JSON_OBJECT_END;
#undef OUTPUT_STATISTICS
}
d->fout << JSON_OBJECT_END;
}
d->fout << std::endl;
d->fout << JSON_OBJECT_END;
d->fout << std::endl;
d->fout << JSON_OBJECT_END;
d->fout << std::endl;
#undef JSON_OBJECT_END
#undef JSON_OBJECT_BEGIN
#undef JSON_SEP
#undef JSON_ATTR
#undef JSON_KEY
process::_step();
}
process::port_info_t
component_score_json_writer_process
::_input_port_info(port_t const& port)
{
if (boost::starts_with(port, priv::port_score_prefix))
{
priv::tag_t const tag = port.substr(priv::port_score_prefix.size());
priv::tags_t::const_iterator const i = std::find(d->tags.begin(), d->tags.end(), tag);
if (i == d->tags.end())
{
port_t const port_score = priv::port_score_prefix + tag;
port_t const port_stats = priv::port_stats_prefix + tag;
d->tags.push_back(tag);
port_flags_t required;
required.insert(flag_required);
declare_input_port(port_score, boost::make_shared<port_info>(
"score",
required,
port_description_t("The \'" + tag + "\' score component.")));
declare_input_port(port_stats, boost::make_shared<port_info>(
"statistics/score",
port_flags_t(),
port_description_t("The \'" + tag + "\' score statistics component.")));
}
}
return process::_input_port_info(port);
}
component_score_json_writer_process::priv
::priv()
{
}
component_score_json_writer_process::priv
::priv(name_t const& name_, path_t const& output_path, tags_t const& tags_)
: name(name_)
, path(output_path)
, tags(tags_)
{
}
component_score_json_writer_process::priv
::~priv()
{
}
}
<|endoftext|>
|
<commit_before>#include "textlayout_p.h"
#include "textedit_p.h"
#include "textdocument.h"
#include "textedit.h"
void TextLayout::dirty(int width)
{
viewport = width;
layoutDirty = true;
if (textEdit)
textEdit->viewport()->update();
}
int TextLayout::viewportWidth() const
{
if (!lineBreaking)
return INT_MAX;
return textEdit ? textEdit->viewport()->width() : viewport;
}
int TextLayout::doLayout(int index, QList<TextSection*> *sections) // index is in document coordinates
{
QTextLayout *textLayout = 0;
if (!unusedTextLayouts.isEmpty()) {
textLayout = unusedTextLayouts.takeLast();
textLayout->clearAdditionalFormats();
} else {
textLayout = new QTextLayout;
textLayout->setFont(font);
QTextOption option;
option.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere);
textLayout->setTextOption(option);
}
textLayouts.append(textLayout);
if (index != 0 && bufferReadCharacter(index - 1) != '\n') {
qWarning() << index << viewportPosition << document->read(index - 1, 20)
<< bufferReadCharacter(index - 1);
}
Q_ASSERT(index == 0 || bufferReadCharacter(index - 1) == '\n');
const int max = bufferPosition + buffer.size();
const int lineStart = index;
while (index < max && bufferReadCharacter(index) != '\n')
++index;
const QString string = buffer.mid(lineStart - bufferPosition, index - lineStart);
Q_ASSERT(string.size() == index - lineStart);
Q_ASSERT(!string.contains('\n'));
if (index < max)
++index; // for the newline
textLayout->setText(string);
QMultiMap<int, QTextLayout::FormatRange> formatMap;
if (sections) {
do {
Q_ASSERT(!sections->isEmpty());
TextSection *l = sections->first();
Q_ASSERT(::matchSection(l, textEdit));
Q_ASSERT(l->position() + l->size() >= lineStart);
if (l->position() >= index) {
break;
}
// section is in this QTextLayout
QTextLayout::FormatRange range;
range.start = qMax(0, l->position() - lineStart); // offset in QTextLayout
range.length = qMin(l->position() + l->size(), index) - lineStart - range.start;
range.format = l->format();
formatMap.insertMulti(l->priority(), range);
if (l->position() + l->size() >= index) { // > ### ???
// means section didn't end here. It continues in the next QTextLayout
break;
}
sections->removeFirst();
} while (!sections->isEmpty());
}
QList<QTextLayout::FormatRange> formats = formatMap.values();
int leftMargin = LeftMargin;
int rightMargin = 0;
int topMargin = 0;
int bottomMargin = 0;
if (syntaxHighlighter) {
syntaxHighlighter->d->currentBlockPosition = lineStart;
syntaxHighlighter->d->formatRanges.clear();
syntaxHighlighter->d->currentBlock = string;
syntaxHighlighter->highlightBlock(string);
syntaxHighlighter->d->currentBlock.clear();
if (syntaxHighlighter->d->blockFormat.isValid()) {
blockFormats[textLayout] = syntaxHighlighter->d->blockFormat;
if (syntaxHighlighter->d->blockFormat.hasProperty(QTextFormat::BlockLeftMargin))
leftMargin = syntaxHighlighter->d->blockFormat.leftMargin();
if (syntaxHighlighter->d->blockFormat.hasProperty(QTextFormat::BlockRightMargin))
rightMargin = syntaxHighlighter->d->blockFormat.rightMargin();
if (syntaxHighlighter->d->blockFormat.hasProperty(QTextFormat::BlockTopMargin))
topMargin = syntaxHighlighter->d->blockFormat.topMargin();
if (syntaxHighlighter->d->blockFormat.hasProperty(QTextFormat::BlockBottomMargin))
bottomMargin = syntaxHighlighter->d->blockFormat.bottomMargin();
}
syntaxHighlighter->d->previousBlockState = syntaxHighlighter->d->currentBlockState;
if (!syntaxHighlighter->d->formatRanges.isEmpty())
formats += syntaxHighlighter->d->formatRanges;
}
textLayout->setAdditionalFormats(formats);
textLayout->beginLayout();
forever {
QTextLine line = textLayout->createLine();
if (!line.isValid()) {
break;
}
line.setLineWidth(viewportWidth() - (leftMargin + rightMargin));
if (!lineBreaking)
widest = qMax<int>(widest, line.naturalTextWidth() + (LeftMargin * 2));
// ### support blockformat margins etc
int y = topMargin + lastBottomMargin;
if (!lines.isEmpty()) {
y += int(lines.last().second.rect().bottom());
// QTextLine doesn't seem to get its rect() update until a
// new line has been created (or presumably in endLayout)
}
line.setPosition(QPoint(leftMargin, y));
lines.append(qMakePair(lineStart + line.textStart(), line));
}
lastBottomMargin = bottomMargin;
textLayout->endLayout();
#ifndef QT_NO_DEBUG
for (int i=1; i<lines.size(); ++i) {
Q_ASSERT(lines.at(i).first - (lines.at(i - 1).first + lines.at(i - 1).second.textLength()) <= 1);
}
#endif
contentRect |= textLayout->boundingRect().toRect();
Q_ASSERT(contentRect.right() <= viewportWidth() + LeftMargin);
if (syntaxHighlighter) {
syntaxHighlighter->d->formatRanges.clear();
syntaxHighlighter->d->blockFormat = QTextBlockFormat();
syntaxHighlighter->d->currentBlockPosition = -1;
}
return index;
}
int TextLayout::textPositionAt(const QPoint &p) const
{
QPoint pos = p;
if (pos.x() >= 0 && pos.x() < LeftMargin)
pos.rx() = LeftMargin; // clicking in the margin area should count as the first characters
int textLayoutOffset = viewportPosition;
foreach(const QTextLayout *l, textLayouts) {
if (l->boundingRect().toRect().contains(pos)) {
const int lineCount = l->lineCount();
for (int i=0; i<lineCount; ++i) {
const QTextLine line = l->lineAt(i);
if (line.y() <= pos.y() && pos.y() <= line.height() + line.y()) { // ### < ???
return textLayoutOffset + line.xToCursor(qMax<int>(LeftMargin, pos.x()));
}
}
}
textLayoutOffset += l->text().size() + 1; // + 1 for newlines which aren't in the QTextLayout
}
return -1;
}
QList<TextSection*> TextLayout::relayoutCommon()
{
// widest = -1; // ### should this be relative to current content or remember? What if you remove the line that was the widest?
Q_ASSERT(layoutDirty);
layoutDirty = false;
Q_ASSERT(document);
lines.clear();
unusedTextLayouts = textLayouts;
textLayouts.clear();
contentRect = QRect();
visibleLines = lastVisibleCharacter = -1;
if (syntaxHighlighter) {
syntaxHighlighter->d->previousBlockState = syntaxHighlighter->d->currentBlockState = -1;
}
if (viewportPosition < bufferPosition
|| (bufferPosition + buffer.size() < document->documentSize()
&& buffer.size() - bufferOffset() < MinimumBufferSize)) {
bufferPosition = qMax(0, viewportPosition - MinimumBufferSize);
buffer = document->read(bufferPosition, int(MinimumBufferSize * 2.5));
sections = document->d->getSections(bufferPosition, buffer.size(), TextSection::IncludePartial, textEdit);
} else if (sectionsDirty) {
sections = document->d->getSections(bufferPosition, buffer.size(), TextSection::IncludePartial, textEdit);
}
sectionsDirty = false;
QList<TextSection*> l = sections;
while (!l.isEmpty() && l.first()->position() + l.first()->size() < viewportPosition)
l.takeFirst(); // could cache these as well
return l;
}
void TextLayout::relayoutByGeometry(int height)
{
if (!layoutDirty)
return;
QList<TextSection*> l = relayoutCommon();
const int max = viewportPosition + buffer.size() - bufferOffset(); // in document coordinates
Q_ASSERT(viewportPosition == 0 || bufferReadCharacter(viewportPosition - 1) == '\n');
static const int extraLines = qMax(2, qgetenv("LAZYTEXTEDIT_EXTRA_LINES").toInt());
int index = viewportPosition;
while (index < max) {
index = doLayout(index, l.isEmpty() ? 0 : &l);
Q_ASSERT(index == max || document->readCharacter(index - 1) == '\n');
Q_ASSERT(!textLayouts.isEmpty());
const int y = int(textLayouts.last()->boundingRect().bottom());
if (y >= height) {
if (visibleLines == -1) {
visibleLines = lines.size();
lastVisibleCharacter = index;
} else if (lines.size() >= visibleLines + extraLines) {
break;
}
}
}
if (visibleLines == -1) {
visibleLines = lines.size();
lastVisibleCharacter = index;
}
layoutEnd = qMin(index, max);
qDeleteAll(unusedTextLayouts);
unusedTextLayouts.clear();
Q_ASSERT(viewportPosition < layoutEnd ||
(viewportPosition == layoutEnd && viewportPosition == document->documentSize()));
}
void TextLayout::relayoutByPosition(int size)
{
if (!layoutDirty)
return;
QList<TextSection*> l = relayoutCommon();
const int max = viewportPosition + qMin(size, buffer.size() - bufferOffset());
Q_ASSERT(viewportPosition == 0 || bufferReadCharacter(viewportPosition - 1) == '\n');
int index = viewportPosition;
while (index < max) {
index = doLayout(index, l.isEmpty() ? 0 : &l);
}
layoutEnd = index;
qDeleteAll(unusedTextLayouts);
unusedTextLayouts.clear();
Q_ASSERT(viewportPosition < layoutEnd ||
(viewportPosition == layoutEnd && viewportPosition == document->documentSize()));
}
QTextLayout *TextLayout::layoutForPosition(int pos, int *offset, int *index) const
{
if (offset)
*offset = -1;
if (index)
*index = -1;
if (textLayouts.isEmpty() || pos < viewportPosition || pos > layoutEnd) {
return 0;
}
int textLayoutOffset = viewportPosition;
int i = 0;
foreach(QTextLayout *l, textLayouts) {
if (pos >= textLayoutOffset && pos <= l->text().size() + textLayoutOffset) {
if (offset)
*offset = pos - textLayoutOffset;
if (index)
*index = i;
return l;
}
++i;
textLayoutOffset += l->text().size() + 1;
}
return 0;
}
QTextLine TextLayout::lineForPosition(int pos, int *offsetInLine, int *lineIndex) const
{
if (offsetInLine)
*offsetInLine = -1;
if (lineIndex)
*lineIndex = -1;
if (pos < viewportPosition || pos >= layoutEnd || textLayouts.isEmpty() || lines.isEmpty()) {
return QTextLine();
}
for (int i=0; i<lines.size(); ++i) {
const QPair<int, QTextLine> &line = lines.at(i);
const int lineEnd = line.first + line.second.textLength() + 1; // 1 is for newline characteru
if (pos < lineEnd) {
if (offsetInLine) {
*offsetInLine = pos - line.first;
Q_ASSERT(*offsetInLine >= 0);
Q_ASSERT(*offsetInLine < lineEnd + pos);
}
if (lineIndex) {
*lineIndex = i;
}
return line.second;
}
}
qWarning() << "Couldn't find a line for" << pos << "viewportPosition" << viewportPosition
<< "layoutEnd" << layoutEnd;
Q_ASSERT(0);
return QTextLine();
}
// pos is not necessarily on a newline. Finds closest newline in the
// right direction and sets viewportPosition to that. Updates
// scrollbars if this is a TextEditPrivate
void TextLayout::updatePosition(int pos, Direction direction)
{
if (document->documentSize() == 0) {
viewportPosition = 0;
} else {
Q_ASSERT(document->documentSize() > 0);
int index = document->find('\n', qMax(0, pos + (direction == Backward ? -1 : 0)),
TextDocument::FindMode(direction)).position();
if (index == -1) {
if (direction == Backward) {
index = 0;
} else {
index = document->find('\n', document->documentSize() - 1, TextDocument::FindBackward).position() + 1;
// position after last newline in document
}
} else {
++index;
}
Q_ASSERT(index != -1);
viewportPosition = index;
if (viewportPosition != 0 && document->read(viewportPosition - 1, 1) != QString("\n"))
qWarning() << "viewportPosition" << viewportPosition << document->read(viewportPosition - 1, 10) << this;
Q_ASSERT(viewportPosition == 0 || document->read(viewportPosition - 1, 1) == QString("\n"));
}
dirty(viewportWidth());
if (textEdit) {
TextEditPrivate *p = static_cast<TextEditPrivate*>(this);
p->pendingScrollBarUpdate = true;
p->updateCursorPosition(p->lastHoverPos);
if (!textEdit->verticalScrollBar()->isSliderDown()) {
p->updateScrollBar();
} // sliderReleased is connected to updateScrollBar()
}
}
#ifndef QT_NO_DEBUG_STREAM
QDebug &operator<<(QDebug &str, const QTextLine &line)
{
if (!line.isValid()) {
str << "QTextLine() (invalid)";
return str;
}
str.space() << "lineNumber" << line.lineNumber()
<< "textStart" << line.textStart()
<< "textLength" << line.textLength()
<< "position" << line.position();
return str;
}
#endif
<commit_msg>more robust layout code<commit_after>#include "textlayout_p.h"
#include "textedit_p.h"
#include "textdocument.h"
#include "textedit.h"
void TextLayout::dirty(int width)
{
viewport = width;
layoutDirty = true;
if (textEdit)
textEdit->viewport()->update();
}
int TextLayout::viewportWidth() const
{
if (!lineBreaking)
return INT_MAX;
return textEdit ? textEdit->viewport()->width() : viewport;
}
int TextLayout::doLayout(int index, QList<TextSection*> *sections) // index is in document coordinates
{
QTextLayout *textLayout = 0;
if (!unusedTextLayouts.isEmpty()) {
textLayout = unusedTextLayouts.takeLast();
textLayout->clearAdditionalFormats();
} else {
textLayout = new QTextLayout;
textLayout->setFont(font);
QTextOption option;
option.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere);
textLayout->setTextOption(option);
}
textLayouts.append(textLayout);
if (index != 0 && bufferReadCharacter(index - 1) != '\n') {
qWarning() << index << viewportPosition << document->read(index - 1, 20)
<< bufferReadCharacter(index - 1);
}
Q_ASSERT(index == 0 || bufferReadCharacter(index - 1) == '\n');
const int max = bufferPosition + buffer.size();
const int lineStart = index;
while (index < max && bufferReadCharacter(index) != '\n')
++index;
const QString string = buffer.mid(lineStart - bufferPosition, index - lineStart);
Q_ASSERT(string.size() == index - lineStart);
Q_ASSERT(!string.contains('\n'));
if (index < max)
++index; // for the newline
textLayout->setText(string);
QMultiMap<int, QTextLayout::FormatRange> formatMap;
if (sections) {
do {
Q_ASSERT(!sections->isEmpty());
TextSection *l = sections->first();
Q_ASSERT(::matchSection(l, textEdit));
Q_ASSERT(l->position() + l->size() >= lineStart);
if (l->position() >= index) {
break;
}
// section is in this QTextLayout
QTextLayout::FormatRange range;
range.start = qMax(0, l->position() - lineStart); // offset in QTextLayout
range.length = qMin(l->position() + l->size(), index) - lineStart - range.start;
range.format = l->format();
formatMap.insertMulti(l->priority(), range);
if (l->position() + l->size() >= index) { // > ### ???
// means section didn't end here. It continues in the next QTextLayout
break;
}
sections->removeFirst();
} while (!sections->isEmpty());
}
QList<QTextLayout::FormatRange> formats = formatMap.values();
int leftMargin = LeftMargin;
int rightMargin = 0;
int topMargin = 0;
int bottomMargin = 0;
if (syntaxHighlighter) {
syntaxHighlighter->d->currentBlockPosition = lineStart;
syntaxHighlighter->d->formatRanges.clear();
syntaxHighlighter->d->currentBlock = string;
syntaxHighlighter->highlightBlock(string);
syntaxHighlighter->d->currentBlock.clear();
if (syntaxHighlighter->d->blockFormat.isValid()) {
blockFormats[textLayout] = syntaxHighlighter->d->blockFormat;
if (syntaxHighlighter->d->blockFormat.hasProperty(QTextFormat::BlockLeftMargin))
leftMargin = syntaxHighlighter->d->blockFormat.leftMargin();
if (syntaxHighlighter->d->blockFormat.hasProperty(QTextFormat::BlockRightMargin))
rightMargin = syntaxHighlighter->d->blockFormat.rightMargin();
if (syntaxHighlighter->d->blockFormat.hasProperty(QTextFormat::BlockTopMargin))
topMargin = syntaxHighlighter->d->blockFormat.topMargin();
if (syntaxHighlighter->d->blockFormat.hasProperty(QTextFormat::BlockBottomMargin))
bottomMargin = syntaxHighlighter->d->blockFormat.bottomMargin();
}
syntaxHighlighter->d->previousBlockState = syntaxHighlighter->d->currentBlockState;
if (!syntaxHighlighter->d->formatRanges.isEmpty())
formats += syntaxHighlighter->d->formatRanges;
}
textLayout->setAdditionalFormats(formats);
textLayout->beginLayout();
const int lineWidth = viewportWidth() - (leftMargin + rightMargin);
int localWidest = -1;
forever {
QTextLine line = textLayout->createLine();
if (!line.isValid()) {
break;
}
line.setLineWidth(lineWidth);
if (!lineBreaking)
localWidest = qMax<int>(localWidest, line.naturalTextWidth() + (LeftMargin * 2));
// ### support blockformat margins etc
int y = topMargin + lastBottomMargin;
if (!lines.isEmpty()) {
y += int(lines.last().second.rect().bottom());
// QTextLine doesn't seem to get its rect() update until a
// new line has been created (or presumably in endLayout)
}
line.setPosition(QPoint(leftMargin, y));
lines.append(qMakePair(lineStart + line.textStart(), line));
}
widest = qMax(widest, localWidest);
lastBottomMargin = bottomMargin;
textLayout->endLayout();
#ifndef QT_NO_DEBUG
for (int i=1; i<lines.size(); ++i) {
Q_ASSERT(lines.at(i).first - (lines.at(i - 1).first + lines.at(i - 1).second.textLength()) <= 1);
}
#endif
QRect r = textLayout->boundingRect().toRect();
// this will actually take the entire width set in setLineWidth
// and not what it actually uses.
r.setWidth(localWidest);
contentRect |= r;
Q_ASSERT(contentRect.right() <= viewportWidth() + LeftMargin);
if (syntaxHighlighter) {
syntaxHighlighter->d->formatRanges.clear();
syntaxHighlighter->d->blockFormat = QTextBlockFormat();
syntaxHighlighter->d->currentBlockPosition = -1;
}
return index;
}
int TextLayout::textPositionAt(const QPoint &p) const
{
QPoint pos = p;
if (pos.x() >= 0 && pos.x() < LeftMargin)
pos.rx() = LeftMargin; // clicking in the margin area should count as the first characters
int textLayoutOffset = viewportPosition;
foreach(const QTextLayout *l, textLayouts) {
if (l->boundingRect().toRect().contains(pos)) {
const int lineCount = l->lineCount();
for (int i=0; i<lineCount; ++i) {
const QTextLine line = l->lineAt(i);
if (line.y() <= pos.y() && pos.y() <= line.height() + line.y()) { // ### < ???
return textLayoutOffset + line.xToCursor(qMax<int>(LeftMargin, pos.x()));
}
}
}
textLayoutOffset += l->text().size() + 1; // + 1 for newlines which aren't in the QTextLayout
}
return -1;
}
QList<TextSection*> TextLayout::relayoutCommon()
{
// widest = -1; // ### should this be relative to current content or remember? What if you remove the line that was the widest?
Q_ASSERT(layoutDirty);
layoutDirty = false;
Q_ASSERT(document);
lines.clear();
unusedTextLayouts = textLayouts;
textLayouts.clear();
contentRect = QRect();
visibleLines = lastVisibleCharacter = -1;
if (syntaxHighlighter) {
syntaxHighlighter->d->previousBlockState = syntaxHighlighter->d->currentBlockState = -1;
}
if (viewportPosition < bufferPosition
|| (bufferPosition + buffer.size() < document->documentSize()
&& buffer.size() - bufferOffset() < MinimumBufferSize)) {
bufferPosition = qMax(0, viewportPosition - MinimumBufferSize);
buffer = document->read(bufferPosition, int(MinimumBufferSize * 2.5));
sections = document->d->getSections(bufferPosition, buffer.size(), TextSection::IncludePartial, textEdit);
} else if (sectionsDirty) {
sections = document->d->getSections(bufferPosition, buffer.size(), TextSection::IncludePartial, textEdit);
}
sectionsDirty = false;
QList<TextSection*> l = sections;
while (!l.isEmpty() && l.first()->position() + l.first()->size() < viewportPosition)
l.takeFirst(); // could cache these as well
return l;
}
void TextLayout::relayoutByGeometry(int height)
{
if (!layoutDirty)
return;
QList<TextSection*> l = relayoutCommon();
const int max = viewportPosition + buffer.size() - bufferOffset(); // in document coordinates
Q_ASSERT(viewportPosition == 0 || bufferReadCharacter(viewportPosition - 1) == '\n');
static const int extraLines = qMax(2, qgetenv("LAZYTEXTEDIT_EXTRA_LINES").toInt());
int index = viewportPosition;
while (index < max) {
index = doLayout(index, l.isEmpty() ? 0 : &l);
Q_ASSERT(index == max || document->readCharacter(index - 1) == '\n');
Q_ASSERT(!textLayouts.isEmpty());
const int y = int(textLayouts.last()->boundingRect().bottom());
if (y >= height) {
if (visibleLines == -1) {
visibleLines = lines.size();
lastVisibleCharacter = index;
} else if (lines.size() >= visibleLines + extraLines) {
break;
}
}
}
if (visibleLines == -1) {
visibleLines = lines.size();
lastVisibleCharacter = index;
}
layoutEnd = qMin(index, max);
qDeleteAll(unusedTextLayouts);
unusedTextLayouts.clear();
Q_ASSERT(viewportPosition < layoutEnd ||
(viewportPosition == layoutEnd && viewportPosition == document->documentSize()));
}
void TextLayout::relayoutByPosition(int size)
{
if (!layoutDirty)
return;
QList<TextSection*> l = relayoutCommon();
const int max = viewportPosition + qMin(size, buffer.size() - bufferOffset());
Q_ASSERT(viewportPosition == 0 || bufferReadCharacter(viewportPosition - 1) == '\n');
int index = viewportPosition;
while (index < max) {
index = doLayout(index, l.isEmpty() ? 0 : &l);
}
layoutEnd = index;
qDeleteAll(unusedTextLayouts);
unusedTextLayouts.clear();
Q_ASSERT(viewportPosition < layoutEnd ||
(viewportPosition == layoutEnd && viewportPosition == document->documentSize()));
}
QTextLayout *TextLayout::layoutForPosition(int pos, int *offset, int *index) const
{
if (offset)
*offset = -1;
if (index)
*index = -1;
if (textLayouts.isEmpty() || pos < viewportPosition || pos > layoutEnd) {
return 0;
}
int textLayoutOffset = viewportPosition;
int i = 0;
foreach(QTextLayout *l, textLayouts) {
if (pos >= textLayoutOffset && pos <= l->text().size() + textLayoutOffset) {
if (offset)
*offset = pos - textLayoutOffset;
if (index)
*index = i;
return l;
}
++i;
textLayoutOffset += l->text().size() + 1;
}
return 0;
}
QTextLine TextLayout::lineForPosition(int pos, int *offsetInLine, int *lineIndex) const
{
if (offsetInLine)
*offsetInLine = -1;
if (lineIndex)
*lineIndex = -1;
if (pos < viewportPosition || pos >= layoutEnd || textLayouts.isEmpty() || lines.isEmpty()) {
return QTextLine();
}
for (int i=0; i<lines.size(); ++i) {
const QPair<int, QTextLine> &line = lines.at(i);
const int lineEnd = line.first + line.second.textLength() + 1; // 1 is for newline characteru
if (pos < lineEnd) {
if (offsetInLine) {
*offsetInLine = pos - line.first;
Q_ASSERT(*offsetInLine >= 0);
Q_ASSERT(*offsetInLine < lineEnd + pos);
}
if (lineIndex) {
*lineIndex = i;
}
return line.second;
}
}
qWarning() << "Couldn't find a line for" << pos << "viewportPosition" << viewportPosition
<< "layoutEnd" << layoutEnd;
Q_ASSERT(0);
return QTextLine();
}
// pos is not necessarily on a newline. Finds closest newline in the
// right direction and sets viewportPosition to that. Updates
// scrollbars if this is a TextEditPrivate
void TextLayout::updatePosition(int pos, Direction direction)
{
if (document->documentSize() == 0) {
viewportPosition = 0;
} else {
Q_ASSERT(document->documentSize() > 0);
int index = document->find('\n', qMax(0, pos + (direction == Backward ? -1 : 0)),
TextDocument::FindMode(direction)).position();
if (index == -1) {
if (direction == Backward) {
index = 0;
} else {
index = document->find('\n', document->documentSize() - 1, TextDocument::FindBackward).position() + 1;
// position after last newline in document
}
} else {
++index;
}
Q_ASSERT(index != -1);
viewportPosition = index;
if (viewportPosition != 0 && document->read(viewportPosition - 1, 1) != QString("\n"))
qWarning() << "viewportPosition" << viewportPosition << document->read(viewportPosition - 1, 10) << this;
Q_ASSERT(viewportPosition == 0 || document->read(viewportPosition - 1, 1) == QString("\n"));
}
dirty(viewportWidth());
if (textEdit) {
TextEditPrivate *p = static_cast<TextEditPrivate*>(this);
p->pendingScrollBarUpdate = true;
p->updateCursorPosition(p->lastHoverPos);
if (!textEdit->verticalScrollBar()->isSliderDown()) {
p->updateScrollBar();
} // sliderReleased is connected to updateScrollBar()
}
}
#ifndef QT_NO_DEBUG_STREAM
QDebug &operator<<(QDebug &str, const QTextLine &line)
{
if (!line.isValid()) {
str << "QTextLine() (invalid)";
return str;
}
str.space() << "lineNumber" << line.lineNumber()
<< "textStart" << line.textStart()
<< "textLength" << line.textLength()
<< "position" << line.position();
return str;
}
#endif
<|endoftext|>
|
<commit_before>/*
* Generate code to convert between VHDL types.
*
* Copyright (C) 2008 Nick Gasson ([email protected])
*
* 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 2 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, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "vhdl_syntax.hh"
#include "vhdl_target.h"
#include "support.hh"
#include <cassert>
#include <iostream>
vhdl_expr *vhdl_expr::cast(const vhdl_type *to)
{
//std::cout << "Cast: from=" << type_->get_string()
// << " (" << type_->get_width() << ") "
// << " to=" << to->get_string() << " ("
// << to->get_width() << ")" << std::endl;
if (to->get_name() == type_->get_name()) {
if (to->get_width() == type_->get_width())
return this; // Identical
else
return resize(to->get_width());
}
else if (to->get_name() == VHDL_TYPE_BOOLEAN)
return to_boolean();
else if (to->get_name() == VHDL_TYPE_INTEGER)
return to_integer();
else if (to->get_name() == VHDL_TYPE_UNSIGNED
|| to->get_name() == VHDL_TYPE_SIGNED
|| to->get_name() == VHDL_TYPE_STD_LOGIC_VECTOR)
return to_vector(to->get_name(), to->get_width());
else if (to->get_name() == VHDL_TYPE_STD_LOGIC)
return to_std_logic();
else
assert(false);
}
/*
* Generate code to cast an expression to a vector type (std_logic_vector,
* signed, unsigned).
*/
vhdl_expr *vhdl_expr::to_vector(vhdl_type_name_t name, int w)
{
if (type_->get_name() == VHDL_TYPE_STD_LOGIC) {
vhdl_expr *others = w == 1 ? NULL : new vhdl_const_bit('0');
vhdl_bit_spec_expr *bs =
new vhdl_bit_spec_expr(new vhdl_type(name, w - 1, 0), others);
bs->add_bit(0, this);
return bs;
}
else {
// We have to cast the expression before resizing or the
// wrong sign bit may be extended (i.e. when casting between
// signed/unsigned *and* resizing)
vhdl_type *t = new vhdl_type(name, w - 1, 0);
vhdl_fcall *conv = new vhdl_fcall(t->get_string().c_str(), t);
conv->add_expr(this);
if (w != type_->get_width())
return conv->resize(w);
else
return conv;
}
}
/*
* Convert a generic expression to an Integer.
*/
vhdl_expr *vhdl_expr::to_integer()
{
vhdl_fcall *conv;
if (type_->get_name() == VHDL_TYPE_STD_LOGIC) {
require_support_function(SF_LOGIC_TO_INTEGER);
conv = new vhdl_fcall(support_function::function_name(SF_LOGIC_TO_INTEGER),
vhdl_type::integer());
}
else
conv = new vhdl_fcall("To_Integer", vhdl_type::integer());
conv->add_expr(this);
return conv;
}
/*
* Convert a generic expression to a Boolean.
*/
vhdl_expr *vhdl_expr::to_boolean()
{
if (type_->get_name() == VHDL_TYPE_STD_LOGIC) {
// '1' is true all else are false
vhdl_const_bit *one = new vhdl_const_bit('1');
return new vhdl_binop_expr
(this, VHDL_BINOP_EQ, one, vhdl_type::boolean());
}
else if (type_->get_name() == VHDL_TYPE_UNSIGNED) {
// Need to use a support function for this conversion
require_support_function(SF_UNSIGNED_TO_BOOLEAN);
vhdl_fcall *conv =
new vhdl_fcall(support_function::function_name(SF_UNSIGNED_TO_BOOLEAN),
vhdl_type::boolean());
conv->add_expr(this);
return conv;
}
else if (type_->get_name() == VHDL_TYPE_SIGNED) {
require_support_function(SF_SIGNED_TO_BOOLEAN);
vhdl_fcall *conv =
new vhdl_fcall(support_function::function_name(SF_SIGNED_TO_BOOLEAN),
vhdl_type::boolean());
conv->add_expr(this);
return conv;
}
else {
assert(false);
}
}
/*
* Generate code to convert and expression to std_logic.
*/
vhdl_expr *vhdl_expr::to_std_logic()
{
if (type_->get_name() == VHDL_TYPE_BOOLEAN) {
require_support_function(SF_BOOLEAN_TO_LOGIC);
vhdl_fcall *ah =
new vhdl_fcall(support_function::function_name(SF_BOOLEAN_TO_LOGIC),
vhdl_type::std_logic());
ah->add_expr(this);
return ah;
}
else if (type_->get_name() == VHDL_TYPE_SIGNED) {
require_support_function(SF_SIGNED_TO_LOGIC);
vhdl_fcall *ah =
new vhdl_fcall(support_function::function_name(SF_SIGNED_TO_LOGIC),
vhdl_type::std_logic());
ah->add_expr(this);
return ah;
}
else if (type_->get_name() == VHDL_TYPE_UNSIGNED) {
require_support_function(SF_UNSIGNED_TO_LOGIC);
vhdl_fcall *ah =
new vhdl_fcall(support_function::function_name(SF_UNSIGNED_TO_LOGIC),
vhdl_type::std_logic());
ah->add_expr(this);
return ah;
}
else
assert(false);
}
/*
* Change the width of a signed/unsigned type.
*/
vhdl_expr *vhdl_expr::resize(int newwidth)
{
vhdl_type *rtype;
assert(type_);
if (type_->get_name() == VHDL_TYPE_SIGNED)
rtype = vhdl_type::nsigned(newwidth);
else if (type_->get_name() == VHDL_TYPE_UNSIGNED)
rtype = vhdl_type::nunsigned(newwidth);
else
return this; // Doesn't make sense to resize non-vector type
vhdl_fcall *resize = new vhdl_fcall("Resize", rtype);
resize->add_expr(this);
resize->add_expr(new vhdl_const_int(newwidth));
return resize;
}
vhdl_expr *vhdl_const_int::to_vector(vhdl_type_name_t name, int w)
{
if (name == VHDL_TYPE_SIGNED || name == VHDL_TYPE_UNSIGNED) {
const char *fname = name == VHDL_TYPE_SIGNED
? "To_Signed" : "To_Unsigned";
vhdl_fcall *conv = new vhdl_fcall(fname, new vhdl_type(name, w - 1, 0));
conv->add_expr(this);
conv->add_expr(new vhdl_const_int(w));
return conv;
}
else
return vhdl_expr::to_vector(name, w);
}
int vhdl_const_bits::bits_to_int() const
{
char msb = value_[value_.size() - 1];
int result = 0, bit;
for (int i = sizeof(int)*8 - 1; i >= 0; i--) {
if (i > (int)value_.size() - 1)
bit = msb == '1' ? 1 : 0;
else
bit = value_[i] == '1' ? 1 : 0;
result = (result << 1) | bit;
}
return result;
}
vhdl_expr *vhdl_const_bits::to_std_logic()
{
// VHDL won't let us cast directly between a vector and
// a scalar type
// But we don't need to here as we have the bits available
// Take the least significant bit
char lsb = value_[0];
return new vhdl_const_bit(lsb);
}
vhdl_expr *vhdl_const_bits::to_vector(vhdl_type_name_t name, int w)
{
if (name == VHDL_TYPE_STD_LOGIC_VECTOR) {
// Don't need to do anything
return this;
}
else if (name == VHDL_TYPE_SIGNED || name == VHDL_TYPE_UNSIGNED) {
// Extend with sign bit
value_.resize(w, value_[0]);
return this;
}
else
assert(false);
}
vhdl_expr *vhdl_const_bits::to_integer()
{
return new vhdl_const_int(bits_to_int());
}
vhdl_expr *vhdl_const_bit::to_integer()
{
return new vhdl_const_int(bit_ == '1' ? 1 : 0);
}
vhdl_expr *vhdl_const_bit::to_boolean()
{
return new vhdl_const_bool(bit_ == '1');
}
<commit_msg>Finish cast.cc cleanup<commit_after>/*
* Generate code to convert between VHDL types.
*
* Copyright (C) 2008 Nick Gasson ([email protected])
*
* 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 2 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, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "vhdl_syntax.hh"
#include "vhdl_target.h"
#include "support.hh"
#include <cassert>
#include <iostream>
vhdl_expr *vhdl_expr::cast(const vhdl_type *to)
{
//std::cout << "Cast: from=" << type_->get_string()
// << " (" << type_->get_width() << ") "
// << " to=" << to->get_string() << " ("
// << to->get_width() << ")" << std::endl;
if (to->get_name() == type_->get_name()) {
if (to->get_width() == type_->get_width())
return this; // Identical
else
return resize(to->get_width());
}
else {
switch (to->get_name()) {
case VHDL_TYPE_BOOLEAN:
return to_boolean();
case VHDL_TYPE_INTEGER:
return to_integer();
case VHDL_TYPE_UNSIGNED:
case VHDL_TYPE_SIGNED:
case VHDL_TYPE_STD_LOGIC_VECTOR:
return to_vector(to->get_name(), to->get_width());
case VHDL_TYPE_STD_LOGIC:
return to_std_logic();
default:
assert(false);
}
}
}
/*
* Generate code to cast an expression to a vector type (std_logic_vector,
* signed, unsigned).
*/
vhdl_expr *vhdl_expr::to_vector(vhdl_type_name_t name, int w)
{
if (type_->get_name() == VHDL_TYPE_STD_LOGIC) {
vhdl_expr *others = w == 1 ? NULL : new vhdl_const_bit('0');
vhdl_bit_spec_expr *bs =
new vhdl_bit_spec_expr(new vhdl_type(name, w - 1, 0), others);
bs->add_bit(0, this);
return bs;
}
else {
// We have to cast the expression before resizing or the
// wrong sign bit may be extended (i.e. when casting between
// signed/unsigned *and* resizing)
vhdl_type *t = new vhdl_type(name, w - 1, 0);
vhdl_fcall *conv = new vhdl_fcall(t->get_string().c_str(), t);
conv->add_expr(this);
if (w != type_->get_width())
return conv->resize(w);
else
return conv;
}
}
/*
* Convert a generic expression to an Integer.
*/
vhdl_expr *vhdl_expr::to_integer()
{
vhdl_fcall *conv;
if (type_->get_name() == VHDL_TYPE_STD_LOGIC) {
require_support_function(SF_LOGIC_TO_INTEGER);
conv = new vhdl_fcall(support_function::function_name(SF_LOGIC_TO_INTEGER),
vhdl_type::integer());
}
else
conv = new vhdl_fcall("To_Integer", vhdl_type::integer());
conv->add_expr(this);
return conv;
}
/*
* Convert a generic expression to a Boolean.
*/
vhdl_expr *vhdl_expr::to_boolean()
{
if (type_->get_name() == VHDL_TYPE_STD_LOGIC) {
// '1' is true all else are false
vhdl_const_bit *one = new vhdl_const_bit('1');
return new vhdl_binop_expr
(this, VHDL_BINOP_EQ, one, vhdl_type::boolean());
}
else if (type_->get_name() == VHDL_TYPE_UNSIGNED) {
// Need to use a support function for this conversion
require_support_function(SF_UNSIGNED_TO_BOOLEAN);
vhdl_fcall *conv =
new vhdl_fcall(support_function::function_name(SF_UNSIGNED_TO_BOOLEAN),
vhdl_type::boolean());
conv->add_expr(this);
return conv;
}
else if (type_->get_name() == VHDL_TYPE_SIGNED) {
require_support_function(SF_SIGNED_TO_BOOLEAN);
vhdl_fcall *conv =
new vhdl_fcall(support_function::function_name(SF_SIGNED_TO_BOOLEAN),
vhdl_type::boolean());
conv->add_expr(this);
return conv;
}
else {
assert(false);
}
}
/*
* Generate code to convert and expression to std_logic.
*/
vhdl_expr *vhdl_expr::to_std_logic()
{
if (type_->get_name() == VHDL_TYPE_BOOLEAN) {
require_support_function(SF_BOOLEAN_TO_LOGIC);
vhdl_fcall *ah =
new vhdl_fcall(support_function::function_name(SF_BOOLEAN_TO_LOGIC),
vhdl_type::std_logic());
ah->add_expr(this);
return ah;
}
else if (type_->get_name() == VHDL_TYPE_SIGNED) {
require_support_function(SF_SIGNED_TO_LOGIC);
vhdl_fcall *ah =
new vhdl_fcall(support_function::function_name(SF_SIGNED_TO_LOGIC),
vhdl_type::std_logic());
ah->add_expr(this);
return ah;
}
else if (type_->get_name() == VHDL_TYPE_UNSIGNED) {
require_support_function(SF_UNSIGNED_TO_LOGIC);
vhdl_fcall *ah =
new vhdl_fcall(support_function::function_name(SF_UNSIGNED_TO_LOGIC),
vhdl_type::std_logic());
ah->add_expr(this);
return ah;
}
else
assert(false);
}
/*
* Change the width of a signed/unsigned type.
*/
vhdl_expr *vhdl_expr::resize(int newwidth)
{
vhdl_type *rtype;
assert(type_);
if (type_->get_name() == VHDL_TYPE_SIGNED)
rtype = vhdl_type::nsigned(newwidth);
else if (type_->get_name() == VHDL_TYPE_UNSIGNED)
rtype = vhdl_type::nunsigned(newwidth);
else
return this; // Doesn't make sense to resize non-vector type
vhdl_fcall *resize = new vhdl_fcall("Resize", rtype);
resize->add_expr(this);
resize->add_expr(new vhdl_const_int(newwidth));
return resize;
}
vhdl_expr *vhdl_const_int::to_vector(vhdl_type_name_t name, int w)
{
if (name == VHDL_TYPE_SIGNED || name == VHDL_TYPE_UNSIGNED) {
const char *fname = name == VHDL_TYPE_SIGNED
? "To_Signed" : "To_Unsigned";
vhdl_fcall *conv = new vhdl_fcall(fname, new vhdl_type(name, w - 1, 0));
conv->add_expr(this);
conv->add_expr(new vhdl_const_int(w));
return conv;
}
else
return vhdl_expr::to_vector(name, w);
}
int vhdl_const_bits::bits_to_int() const
{
char msb = value_[value_.size() - 1];
int result = 0, bit;
for (int i = sizeof(int)*8 - 1; i >= 0; i--) {
if (i > (int)value_.size() - 1)
bit = msb == '1' ? 1 : 0;
else
bit = value_[i] == '1' ? 1 : 0;
result = (result << 1) | bit;
}
return result;
}
vhdl_expr *vhdl_const_bits::to_std_logic()
{
// VHDL won't let us cast directly between a vector and
// a scalar type
// But we don't need to here as we have the bits available
// Take the least significant bit
char lsb = value_[0];
return new vhdl_const_bit(lsb);
}
vhdl_expr *vhdl_const_bits::to_vector(vhdl_type_name_t name, int w)
{
if (name == VHDL_TYPE_STD_LOGIC_VECTOR) {
// Don't need to do anything
return this;
}
else if (name == VHDL_TYPE_SIGNED || name == VHDL_TYPE_UNSIGNED) {
// Extend with sign bit
value_.resize(w, value_[0]);
return this;
}
else
assert(false);
}
vhdl_expr *vhdl_const_bits::to_integer()
{
return new vhdl_const_int(bits_to_int());
}
vhdl_expr *vhdl_const_bit::to_integer()
{
return new vhdl_const_int(bit_ == '1' ? 1 : 0);
}
vhdl_expr *vhdl_const_bit::to_boolean()
{
return new vhdl_const_bool(bit_ == '1');
}
<|endoftext|>
|
<commit_before>#pragma once
#include "../types.hpp"
#include "base.hpp"
#include <nlohmann/json.hpp>
#include <pqrs/dispatcher.hpp>
namespace krbn {
namespace manipulator {
namespace manipulators {
class mouse_motion_to_scroll final : public base, public pqrs::dispatcher::extra::dispatcher_client {
public:
mouse_motion_to_scroll(const nlohmann::json& json,
const core_configuration::details::complex_modifications_parameters& parameters) : base() {
try {
if (!json.is_object()) {
throw pqrs::json::unmarshal_error(fmt::format("json must be object, but is `{0}`", json.dump()));
}
for (const auto& [key, value] : json.items()) {
if (key == "from") {
if (!value.is_object()) {
throw pqrs::json::unmarshal_error(fmt::format("`{0}` must be object, but is `{1}`", key, value.dump()));
}
for (const auto& [k, v] : value.items()) {
if (k == "modifiers") {
try {
from_modifiers_definition_ = v.get<from_modifiers_definition>();
} catch (const pqrs::json::unmarshal_error& e) {
throw pqrs::json::unmarshal_error(fmt::format("`{0}.{1}` error: {2}", key, k, e.what()));
}
}
}
}
}
} catch (...) {
detach_from_dispatcher();
throw;
}
}
virtual ~mouse_motion_to_scroll(void) {
detach_from_dispatcher();
}
virtual bool already_manipulated(const event_queue::entry& front_input_event) {
return false;
}
virtual manipulate_result manipulate(event_queue::entry& front_input_event,
const event_queue::queue& input_event_queue,
const std::shared_ptr<event_queue::queue>& output_event_queue,
absolute_time_point now) {
if (output_event_queue) {
// ----------------------------------------
if (!front_input_event.get_valid()) {
return manipulate_result::passed;
}
if (!valid_) {
return manipulate_result::passed;
}
// ----------------------------------------
if (auto new_event = make_new_event(front_input_event, output_event_queue)) {
front_input_event.set_valid(false);
output_event_queue->emplace_back_entry(front_input_event.get_device_id(),
front_input_event.get_event_time_stamp(),
*new_event,
event_type::single,
front_input_event.get_original_event());
return manipulate_result::manipulated;
}
}
return manipulate_result::passed;
}
virtual bool active(void) const {
return false;
}
virtual bool needs_virtual_hid_pointing(void) const {
return true;
}
virtual void handle_device_keys_and_pointing_buttons_are_released_event(const event_queue::entry& front_input_event,
event_queue::queue& output_event_queue) {
}
virtual void handle_device_ungrabbed_event(device_id device_id,
const event_queue::queue& output_event_queue,
absolute_time_point time_stamp) {
}
virtual void handle_pointing_device_event_from_event_tap(const event_queue::entry& front_input_event,
event_queue::queue& output_event_queue) {
}
private:
std::optional<event_queue::event> make_new_event(const event_queue::entry& front_input_event,
const std::shared_ptr<event_queue::queue>& output_event_queue) const {
if (output_event_queue) {
if (auto m = front_input_event.get_event().find<pointing_motion>()) {
if (m->get_x() != 0 ||
m->get_y() != 0) {
// Check mandatory_modifiers and conditions
if (auto modifiers = from_modifiers_definition_.test_modifiers(output_event_queue->get_modifier_flag_manager())) {
// from_mandatory_modifiers = *modifiers;
} else {
return std::nullopt;
}
if (!condition_manager_.is_fulfilled(front_input_event,
output_event_queue->get_manipulator_environment())) {
return std::nullopt;
}
return event_queue::event(pointing_motion(0, 0, m->get_x(), m->get_y()));
}
}
}
return std::nullopt;
}
from_modifiers_definition from_modifiers_definition_;
};
} // namespace manipulators
} // namespace manipulator
} // namespace krbn
<commit_msg>update mouse_motion_to_scroll<commit_after>#pragma once
#include "../types.hpp"
#include "base.hpp"
#include <nlohmann/json.hpp>
#include <pqrs/dispatcher.hpp>
namespace krbn {
namespace manipulator {
namespace manipulators {
class mouse_motion_to_scroll final : public base, public pqrs::dispatcher::extra::dispatcher_client {
public:
mouse_motion_to_scroll(const nlohmann::json& json,
const core_configuration::details::complex_modifications_parameters& parameters) : base(),
accumulated_x_(0),
accumulated_y_(0) {
try {
if (!json.is_object()) {
throw pqrs::json::unmarshal_error(fmt::format("json must be object, but is `{0}`", json.dump()));
}
for (const auto& [key, value] : json.items()) {
if (key == "from") {
if (!value.is_object()) {
throw pqrs::json::unmarshal_error(fmt::format("`{0}` must be object, but is `{1}`", key, value.dump()));
}
for (const auto& [k, v] : value.items()) {
if (k == "modifiers") {
try {
from_modifiers_definition_ = v.get<from_modifiers_definition>();
} catch (const pqrs::json::unmarshal_error& e) {
throw pqrs::json::unmarshal_error(fmt::format("`{0}.{1}` error: {2}", key, k, e.what()));
}
}
}
}
}
} catch (...) {
detach_from_dispatcher();
throw;
}
}
virtual ~mouse_motion_to_scroll(void) {
detach_from_dispatcher();
}
virtual bool already_manipulated(const event_queue::entry& front_input_event) {
return false;
}
virtual manipulate_result manipulate(event_queue::entry& front_input_event,
const event_queue::queue& input_event_queue,
const std::shared_ptr<event_queue::queue>& output_event_queue,
absolute_time_point now) {
if (output_event_queue) {
// ----------------------------------------
if (!front_input_event.get_valid()) {
return manipulate_result::passed;
}
if (!valid_) {
return manipulate_result::passed;
}
// ----------------------------------------
if (auto new_event = make_new_event(front_input_event, output_event_queue)) {
front_input_event.set_valid(false);
auto& from_mandatory_modifiers = new_event->second;
absolute_time_duration time_stamp_delay;
// Post from_mandatory_modifiers key_up
post_lazy_modifier_key_events(front_input_event,
from_mandatory_modifiers,
event_type::key_up,
time_stamp_delay,
*output_event_queue);
// Post new event
{
auto t = front_input_event.get_event_time_stamp();
t.set_time_stamp(t.get_time_stamp() + time_stamp_delay++);
output_event_queue->emplace_back_entry(front_input_event.get_device_id(),
t,
new_event->first,
event_type::single,
front_input_event.get_original_event());
}
// Post from_mandatory_modifiers key_down
post_lazy_modifier_key_events(front_input_event,
from_mandatory_modifiers,
event_type::key_down,
time_stamp_delay,
*output_event_queue);
return manipulate_result::manipulated;
}
}
return manipulate_result::passed;
}
virtual bool active(void) const {
return false;
}
virtual bool needs_virtual_hid_pointing(void) const {
return true;
}
virtual void handle_device_keys_and_pointing_buttons_are_released_event(const event_queue::entry& front_input_event,
event_queue::queue& output_event_queue) {
}
virtual void handle_device_ungrabbed_event(device_id device_id,
const event_queue::queue& output_event_queue,
absolute_time_point time_stamp) {
}
virtual void handle_pointing_device_event_from_event_tap(const event_queue::entry& front_input_event,
event_queue::queue& output_event_queue) {
}
private:
using new_event_t = std::pair<event_queue::event, std::unordered_set<modifier_flag>>;
std::optional<new_event_t> make_new_event(const event_queue::entry& front_input_event,
const std::shared_ptr<event_queue::queue>& output_event_queue) {
if (output_event_queue) {
if (auto m = front_input_event.get_event().find<pointing_motion>()) {
if (m->get_x() != 0 ||
m->get_y() != 0) {
std::unordered_set<modifier_flag> from_mandatory_modifiers;
// Check mandatory_modifiers and conditions
if (auto modifiers = from_modifiers_definition_.test_modifiers(output_event_queue->get_modifier_flag_manager())) {
from_mandatory_modifiers = *modifiers;
} else {
return std::nullopt;
}
if (!condition_manager_.is_fulfilled(front_input_event,
output_event_queue->get_manipulator_environment())) {
return std::nullopt;
}
accumulated_x_ += m->get_x();
accumulated_y_ += m->get_y();
int divisor = 16;
int vertical_wheel = accumulated_y_ / divisor;
int horizontal_wheel = accumulated_x_ / divisor;
accumulated_x_ -= horizontal_wheel * divisor;
accumulated_y_ -= vertical_wheel * divisor;
return std::make_pair(
event_queue::event(pointing_motion(0, 0, -vertical_wheel, horizontal_wheel)),
from_mandatory_modifiers);
}
}
}
return std::nullopt;
}
void post_lazy_modifier_key_events(const event_queue::entry& front_input_event,
const std::unordered_set<modifier_flag>& modifiers,
event_type event_type,
absolute_time_duration& time_stamp_delay,
event_queue::queue& output_event_queue) {
for (const auto& m : modifiers) {
if (auto key_code = types::make_key_code(m)) {
auto t = front_input_event.get_event_time_stamp();
t.set_time_stamp(t.get_time_stamp() + time_stamp_delay++);
event_queue::entry event(front_input_event.get_device_id(),
t,
event_queue::event(*key_code),
event_type,
front_input_event.get_original_event(),
true);
output_event_queue.push_back_entry(event);
}
}
}
from_modifiers_definition from_modifiers_definition_;
int accumulated_x_;
int accumulated_y_;
};
} // namespace manipulators
} // namespace manipulator
} // namespace krbn
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: convert.hxx,v $
*
* $Revision: 1.1.1.1 $
*
* last change: $Author: hr $ $Date: 2000-09-18 16:59:07 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* 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., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (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.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _CONVERT_HXX
#define _CONVERT_HXX
/*
#define _SWAPSHORT(x) ((((x) & 0xFF00)>>8) | (((x) & 0x00FF)<<8))
#define _SWAPLONG(x) ((((x) & 0xFF000000)>>24) | (((x) & 0x00FF0000)>>8) | \
(((x) & 0x0000FF00)<<8) | (((x) & 0x000000FF)<<24))
*/
class Convert
{
public:
static void Swap( long & nValue )
{ nValue = SWAPLONG( nValue ); }
static void Swap( ULONG & nValue )
{ nValue = SWAPLONG( nValue ); }
static void Swap( short & nValue )
{ nValue = SWAPSHORT( nValue ); }
static void Swap( USHORT & nValue )
{ nValue = SWAPSHORT( nValue ); }
static void Swap( Point & aPtr )
{ Swap( aPtr.X() ); Swap( aPtr.Y() ); }
static void Swap( Size & aSize )
{ Swap( aSize.Width() ); Swap( aSize.Height() ); }
static void Swap( Rectangle & rRect )
{ Swap( rRect.Top() ); Swap( rRect.Bottom() );
Swap( rRect.Left() ); Swap( rRect.Right() ); }
/*
static USHORT AnsiFloatSize() const { return 6; }
static float AnsiToFloat( void * pAnsiFloat )
{ return 0; }
static USHORT AnsiDoubleSize() const { return 12; }
static double AnsiToDouble( void * pAnsiDouble )
{ return 0; }
*/
};
#endif // _CONVERT_HXX
<commit_msg>INTEGRATION: CWS ooo19126 (1.1.1.1.1110); FILE MERGED 2005/09/05 14:54:33 rt 1.1.1.1.1110.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: convert.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: rt $ $Date: 2005-09-08 16:58:50 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* 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., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _CONVERT_HXX
#define _CONVERT_HXX
/*
#define _SWAPSHORT(x) ((((x) & 0xFF00)>>8) | (((x) & 0x00FF)<<8))
#define _SWAPLONG(x) ((((x) & 0xFF000000)>>24) | (((x) & 0x00FF0000)>>8) | \
(((x) & 0x0000FF00)<<8) | (((x) & 0x000000FF)<<24))
*/
class Convert
{
public:
static void Swap( long & nValue )
{ nValue = SWAPLONG( nValue ); }
static void Swap( ULONG & nValue )
{ nValue = SWAPLONG( nValue ); }
static void Swap( short & nValue )
{ nValue = SWAPSHORT( nValue ); }
static void Swap( USHORT & nValue )
{ nValue = SWAPSHORT( nValue ); }
static void Swap( Point & aPtr )
{ Swap( aPtr.X() ); Swap( aPtr.Y() ); }
static void Swap( Size & aSize )
{ Swap( aSize.Width() ); Swap( aSize.Height() ); }
static void Swap( Rectangle & rRect )
{ Swap( rRect.Top() ); Swap( rRect.Bottom() );
Swap( rRect.Left() ); Swap( rRect.Right() ); }
/*
static USHORT AnsiFloatSize() const { return 6; }
static float AnsiToFloat( void * pAnsiFloat )
{ return 0; }
static USHORT AnsiDoubleSize() const { return 12; }
static double AnsiToDouble( void * pAnsiDouble )
{ return 0; }
*/
};
#endif // _CONVERT_HXX
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: idxmrk.hxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: vg $ $Date: 2003-04-24 11:00:20 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* 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., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (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.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _IDXMRK_HXX
#define _IDXMRK_HXX
#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_
#include <com/sun/star/container/XNameAccess.hpp>
#endif
#ifndef _BASEDLGS_HXX
#include <sfx2/basedlgs.hxx>
#endif
#ifndef _FIXED_HXX //autogen
#include <vcl/fixed.hxx>
#endif
#ifndef _SV_LSTBOX_HXX
#include <vcl/lstbox.hxx>
#endif
#ifndef _COMBOBOX_HXX //autogen
#include <vcl/combobox.hxx>
#endif
#ifndef _SVX_STDDLG_HXX
#include <svx/stddlg.hxx>
#endif
#ifndef _FIELD_HXX //autogen
#include <vcl/field.hxx>
#endif
#ifndef _GROUP_HXX //autogen
#include <vcl/group.hxx>
#endif
#ifndef _BUTTON_HXX //autogen
#include <vcl/button.hxx>
#endif
#ifndef _IMAGEBTN_HXX //autogen
#include <vcl/imagebtn.hxx>
#endif
#ifndef _SFX_CHILDWIN_HXX //autogen
#include <sfx2/childwin.hxx>
#endif
#ifndef _TOXE_HXX
#include "toxe.hxx"
#endif
#ifndef _STDCTRL_HXX
#include <svtools/stdctrl.hxx>
#endif
#ifndef _COM_SUN_STAR_I18N_XEXTENDEDINDEXENTRYSUPPLIER_HPP_
#include <com/sun/star/i18n/XExtendedIndexEntrySupplier.hpp>
#endif
class SwWrtShell;
class SwTOXMgr;
class SwTOXMark;
/*--------------------------------------------------------------------
Beschreibung: Markierung fuer Verzeichniseintrag einfuegen
--------------------------------------------------------------------*/
class SwIndexMarkFloatDlg;
class SwIndexMarkModalDlg;
class SwIndexMarkDlg : public Window //SvxStandardDialog
{
friend class SwIndexMarkFloatDlg;
friend class SwIndexMarkModalDlg;
FixedText aTypeFT;
ListBox aTypeDCB;
ImageButton aNewBT;
FixedText aEntryFT;
Edit aEntryED;
FixedText aPhoneticFT0;
Edit aPhoneticED0;
FixedText aKeyFT;
ComboBox aKeyDCB;
FixedText aPhoneticFT1;
Edit aPhoneticED1;
FixedText aKey2FT;
ComboBox aKey2DCB;
FixedText aPhoneticFT2;
Edit aPhoneticED2;
FixedText aLevelFT;
NumericField aLevelED;
CheckBox aMainEntryCB;
CheckBox aApplyToAllCB;
CheckBox aSearchCaseSensitiveCB;
CheckBox aSearchCaseWordOnlyCB;
FixedLine aIndexFL;
OKButton aOKBT;
CancelButton aCancelBT;
HelpButton aHelpBT;
PushButton aDelBT;
//PushButton aNewBT;
ImageButton aPrevSameBT;
ImageButton aNextSameBT;
ImageButton aPrevBT;
ImageButton aNextBT;
String aOrgStr;
sal_Int32 nOptionsId;
sal_Bool bDel;
sal_Bool bNewMark;
sal_Bool bSelected;
BOOL bPhoneticED0_ChangedByUser;
BOOL bPhoneticED1_ChangedByUser;
BOOL bPhoneticED2_ChangedByUser;
LanguageType nLangForPhoneticReading; //Language of current text used for phonetic reading proposal
BOOL bIsPhoneticReadingEnabled; //this value states wether phopentic reading is enabled in principle dependend of global cjk settings and language of current entry
com::sun::star::uno::Reference< com::sun::star::i18n::XExtendedIndexEntrySupplier >
xExtendedIndexEntrySupplier;
SwTOXMgr* pTOXMgr;
SwWrtShell* pSh;
void Apply();
void InitControls();
void InsertMark();
void UpdateMark();
DECL_LINK( InsertHdl, Button * );
DECL_LINK( CloseHdl, Button * );
DECL_LINK( DelHdl, Button * );
DECL_LINK( NextHdl, Button * );
DECL_LINK( NextSameHdl, Button * );
DECL_LINK( PrevHdl, Button * );
DECL_LINK( PrevSameHdl, Button * );
DECL_LINK( ModifyHdl, ListBox* pBox = 0 );
DECL_LINK( KeyDCBModifyHdl, ComboBox * );
DECL_LINK( NewUserIdxHdl, Button*);
DECL_LINK( SearchTypeHdl, CheckBox*);
DECL_LINK( PhoneticEDModifyHdl, Edit * );
//this method updates the values from 'nLangForPhoneticReading' and 'bIsPhoneticReadingEnabled'
//it needs to be called ones if this dialog is opened to create a new entry (in InitControls),
//or otherwise it has to be called for each changed TOXMark (in UpdateDialog)
void UpdateLanguageDependenciesForPhoneticReading();
String GetDefaultPhoneticReading( const String& rText );
void UpdateKeyBoxes();
void UpdateDialog();
void InsertUpdate();
virtual void Activate();
public:
SwIndexMarkDlg( Window *pParent,
sal_Bool bNewDlg,
const ResId& rResId,
sal_Int32 _nOptionsId );
~SwIndexMarkDlg();
void ReInitDlg(SwWrtShell& rWrtShell, SwTOXMark* pCurTOXMark = 0);
sal_Bool IsTOXType(const String& rName)
{return LISTBOX_ENTRY_NOTFOUND != aTypeDCB.GetEntryPos(rName);}
};
/* -----------------06.10.99 10:11-------------------
--------------------------------------------------*/
class SwIndexMarkFloatDlg : public SfxModelessDialog
{
SwIndexMarkDlg aDlg;
virtual void Activate();
public:
SwIndexMarkFloatDlg( SfxBindings* pBindings,
SfxChildWindow* pChild,
Window *pParent,
sal_Bool bNew=sal_True);
SwIndexMarkDlg& GetDlg() {return aDlg;}
};
/* -----------------06.10.99 10:33-------------------
--------------------------------------------------*/
class SwIndexMarkModalDlg : public SvxStandardDialog
{
SwIndexMarkDlg aDlg;
public:
SwIndexMarkModalDlg(Window *pParent, SwWrtShell& rSh, SwTOXMark* pCurTOXMark);
SwIndexMarkDlg& GetDlg() {return aDlg;}
virtual void Apply();
};
/* -----------------07.09.99 08:02-------------------
--------------------------------------------------*/
class SwInsertIdxMarkWrapper : public SfxChildWindow
{
protected:
SwInsertIdxMarkWrapper( Window *pParentWindow,
sal_uInt16 nId,
SfxBindings* pBindings,
SfxChildWinInfo* pInfo );
SFX_DECL_CHILDWINDOW(SwInsertIdxMarkWrapper);
public:
void ReInitDlg(SwWrtShell& rWrtShell)
{((SwIndexMarkFloatDlg*)pWindow)->GetDlg().ReInitDlg(rWrtShell);}
};
/* -----------------15.09.99 08:39-------------------
--------------------------------------------------*/
class SwAuthMarkModalDlg;
class SwAuthMarkDlg : public Window
{
static sal_Bool bIsFromComponent;
friend class SwAuthMarkModalDlg;
friend class SwAuthMarkFloatDlg;
RadioButton aFromComponentRB;
RadioButton aFromDocContentRB;
FixedText aAuthorFT;
FixedInfo aAuthorFI;
FixedText aTitleFT;
FixedInfo aTitleFI;
FixedText aEntryFT;
Edit aEntryED;
ListBox aEntryLB;
FixedLine aEntryFL;
OKButton aOKBT;
CancelButton aCancelBT;
HelpButton aHelpBT;
PushButton aCreateEntryPB;
PushButton aEditEntryPB;
String sChangeST;
sal_Bool bNewEntry;
sal_Bool bBibAccessInitialized;
SwWrtShell* pSh;
String m_sColumnTitles[AUTH_FIELD_END];
String m_sFields[AUTH_FIELD_END];
String m_sCreatedEntry[AUTH_FIELD_END];
::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess > xBibAccess;
DECL_LINK(InsertHdl, PushButton*);
DECL_LINK(CloseHdl, PushButton*);
DECL_LINK(CreateEntryHdl, PushButton*);
DECL_LINK(CompEntryHdl, ListBox*);
DECL_LINK(ChangeSourceHdl, RadioButton*);
DECL_LINK(IsEntryAllowedHdl, Edit*);
DECL_LINK(EditModifyHdl, Edit*);
void InitControls();
virtual void Activate();
public:
SwAuthMarkDlg( Window *pParent,
const ResId& rResId,
sal_Bool bNew=sal_True);
~SwAuthMarkDlg();
void ReInitDlg(SwWrtShell& rWrtShell);
};
/* -----------------07.09.99 08:02-------------------
--------------------------------------------------*/
class SwInsertAuthMarkWrapper : public SfxChildWindow
{
protected:
SwInsertAuthMarkWrapper( Window *pParentWindow,
sal_uInt16 nId,
SfxBindings* pBindings,
SfxChildWinInfo* pInfo );
SFX_DECL_CHILDWINDOW(SwInsertAuthMarkWrapper);
public:
void ReInitDlg(SwWrtShell& rWrtShell);
};
/* -----------------06.10.99 10:11-------------------
--------------------------------------------------*/
class SwAuthMarkFloatDlg : public SfxModelessDialog
{
SwAuthMarkDlg aDlg;
virtual void Activate();
public:
SwAuthMarkFloatDlg( SfxBindings* pBindings,
SfxChildWindow* pChild,
Window *pParent,
sal_Bool bNew=sal_True);
SwAuthMarkDlg& GetDlg() {return aDlg;}
};
/* -----------------06.10.99 10:33-------------------
--------------------------------------------------*/
class SwAuthMarkModalDlg : public SvxStandardDialog
{
SwAuthMarkDlg aDlg;
public:
SwAuthMarkModalDlg(Window *pParent, SwWrtShell& rSh);
SwAuthMarkDlg& GetDlg() {return aDlg;}
virtual void Apply();
};
#endif // _IDXMRK_HXX
<commit_msg>INTEGRATION: CWS dialogdiet01 (1.9.416); FILE MERGED 2004/03/26 09:12:04 mwu 1.9.416.1: sw model converted. 20040326<commit_after>/*************************************************************************
*
* $RCSfile: idxmrk.hxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: hr $ $Date: 2004-05-10 16:28:42 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* 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., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (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.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _IDXMRK_HXX
#define _IDXMRK_HXX
//CHINA001 #ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_
//CHINA001 #include <com/sun/star/container/XNameAccess.hpp>
//CHINA001 #endif
//CHINA001 #ifndef _BASEDLGS_HXX
//CHINA001 #include <sfx2/basedlgs.hxx>
//CHINA001 #endif
//CHINA001
//CHINA001 #ifndef _FIXED_HXX //autogen
//CHINA001 #include <vcl/fixed.hxx>
//CHINA001 #endif
//CHINA001 #ifndef _SV_LSTBOX_HXX
//CHINA001 #include <vcl/lstbox.hxx>
//CHINA001 #endif
//CHINA001 #ifndef _COMBOBOX_HXX //autogen
//CHINA001 #include <vcl/combobox.hxx>
//CHINA001 #endif
//CHINA001 #ifndef _SVX_STDDLG_HXX
//CHINA001 #include <svx/stddlg.hxx>
//CHINA001 #endif
//CHINA001
//CHINA001 #ifndef _FIELD_HXX //autogen
//CHINA001 #include <vcl/field.hxx>
//CHINA001 #endif
//CHINA001
//CHINA001 #ifndef _GROUP_HXX //autogen
//CHINA001 #include <vcl/group.hxx>
//CHINA001 #endif
//CHINA001 #ifndef _BUTTON_HXX //autogen
//CHINA001 #include <vcl/button.hxx>
//CHINA001 #endif
//CHINA001
//CHINA001 #ifndef _IMAGEBTN_HXX //autogen
//CHINA001 #include <vcl/imagebtn.hxx>
//CHINA001 #endif
#ifndef _SFX_CHILDWIN_HXX //autogen
#include <sfx2/childwin.hxx>
#endif
//CHINA001 #ifndef _TOXE_HXX
//CHINA001 #include "toxe.hxx"
//CHINA001 #endif
//CHINA001 #ifndef _STDCTRL_HXX
//CHINA001 #include <svtools/stdctrl.hxx>
//CHINA001 #endif
//CHINA001 #ifndef _COM_SUN_STAR_I18N_XEXTENDEDINDEXENTRYSUPPLIER_HPP_
//CHINA001 #include <com/sun/star/i18n/XExtendedIndexEntrySupplier.hpp>
//CHINA001 #endif
#include "swabstdlg.hxx" //CHINA001
class SwWrtShell;
/* -----------------07.09.99 08:02-------------------
--------------------------------------------------*/
class SwInsertIdxMarkWrapper : public SfxChildWindow
{
AbstractMarkFloatDlg* pAbstDlg; //CHINA001
protected:
SwInsertIdxMarkWrapper( Window *pParentWindow,
sal_uInt16 nId,
SfxBindings* pBindings,
SfxChildWinInfo* pInfo );
SFX_DECL_CHILDWINDOW(SwInsertIdxMarkWrapper);
public:
void ReInitDlg(SwWrtShell& rWrtShell);
};
/* -----------------07.09.99 08:02-------------------
--------------------------------------------------*/
class SwInsertAuthMarkWrapper : public SfxChildWindow
{
AbstractMarkFloatDlg* pAbstDlg; //CHINA001
protected:
SwInsertAuthMarkWrapper( Window *pParentWindow,
sal_uInt16 nId,
SfxBindings* pBindings,
SfxChildWinInfo* pInfo );
SFX_DECL_CHILDWINDOW(SwInsertAuthMarkWrapper);
public:
void ReInitDlg(SwWrtShell& rWrtShell);
};
#endif // _IDXMRK_HXX
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: pggrid.hxx,v $
* $Revision: 1.10 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org 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 version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _PGGRID_HXX
#define _PGGRID_HXX
#include <sfx2/tabdlg.hxx>
#include <colex.hxx>
#ifndef _FIELD_HXX
#include <vcl/field.hxx>
#endif
#ifndef _FIXED_HXX
#include <vcl/fixed.hxx>
#endif
#include <svtools/ctrlbox.hxx>
/*--------------------------------------------------------------------
Description: TabPage Format/(Styles/)Page/Text grid
--------------------------------------------------------------------*/
class SwTextGridPage: public SfxTabPage
{
FixedLine aGridTypeFL;
RadioButton aNoGridRB;
RadioButton aLinesGridRB;
RadioButton aCharsGridRB;
CheckBox aSnapToCharsCB;
SwPageGridExample aExampleWN;
FixedLine aLayoutFL;
FixedText aLinesPerPageFT;
NumericField aLinesPerPageNF;
FixedText aTextSizeFT;
MetricField aTextSizeMF;
FixedText aCharsPerLineFT;
NumericField aCharsPerLineNF;
FixedText aCharWidthFT;
MetricField aCharWidthMF;
FixedText aRubySizeFT;
MetricField aRubySizeMF;
CheckBox aRubyBelowCB;
FixedLine aDisplayFL;
CheckBox aDisplayCB;
CheckBox aPrintCB;
FixedText aColorFT;
ColorListBox aColorLB;
Window* aControls[18];
sal_Int32 m_nRubyUserValue;
sal_Bool m_bRubyUserValue;
Size m_aPageSize;
sal_Bool m_bVertical;
sal_Bool m_bSquaredMode;
SwTextGridPage(Window *pParent, const SfxItemSet &rSet);
~SwTextGridPage();
void UpdatePageSize(const SfxItemSet& rSet);
void PutGridItem(SfxItemSet& rSet);
DECL_LINK(GridTypeHdl, RadioButton*);
DECL_LINK(CharorLineChangedHdl, SpinField*);
DECL_LINK(TextSizeChangedHdl, SpinField*);
DECL_LINK(GridModifyHdl, void*);
DECL_LINK(DisplayGridHdl, CheckBox*);
using TabPage::ActivatePage;
using TabPage::DeactivatePage;
public:
static SfxTabPage *Create(Window *pParent, const SfxItemSet &rSet);
static USHORT* GetRanges();
virtual BOOL FillItemSet(SfxItemSet &rSet);
virtual void Reset(const SfxItemSet &rSet);
virtual void ActivatePage( const SfxItemSet& rSet );
virtual int DeactivatePage( SfxItemSet* pSet = 0 );
};
#endif
<commit_msg>INTEGRATION: CWS lcwarnings2 (1.8.180); FILE MERGED 2008/04/17 12:35:15 tl 1.8.180.3: RESYNC: (1.8-1.10); FILE MERGED 2008/03/03 10:09:52 tl 1.8.180.2: #i83458# warning-free code wntmsci11 2008/02/29 14:55:47 tl 1.8.180.1: #i83458# warning free code for wntmsci11<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: pggrid.hxx,v $
* $Revision: 1.11 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org 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 version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _PGGRID_HXX
#define _PGGRID_HXX
#include <sfx2/tabdlg.hxx>
#include <colex.hxx>
#ifndef _FIELD_HXX
#include <vcl/field.hxx>
#endif
#ifndef _FIXED_HXX
#include <vcl/fixed.hxx>
#endif
#include <svtools/ctrlbox.hxx>
/*--------------------------------------------------------------------
Description: TabPage Format/(Styles/)Page/Text grid
--------------------------------------------------------------------*/
class SwTextGridPage: public SfxTabPage
{
FixedLine aGridTypeFL;
RadioButton aNoGridRB;
RadioButton aLinesGridRB;
RadioButton aCharsGridRB;
CheckBox aSnapToCharsCB;
SwPageGridExample aExampleWN;
FixedLine aLayoutFL;
FixedText aLinesPerPageFT;
NumericField aLinesPerPageNF;
FixedText aTextSizeFT;
MetricField aTextSizeMF;
FixedText aCharsPerLineFT;
NumericField aCharsPerLineNF;
FixedText aCharWidthFT;
MetricField aCharWidthMF;
FixedText aRubySizeFT;
MetricField aRubySizeMF;
CheckBox aRubyBelowCB;
FixedLine aDisplayFL;
CheckBox aDisplayCB;
CheckBox aPrintCB;
FixedText aColorFT;
ColorListBox aColorLB;
Window* aControls[18];
sal_Int32 m_nRubyUserValue;
sal_Bool m_bRubyUserValue;
Size m_aPageSize;
sal_Bool m_bVertical;
sal_Bool m_bSquaredMode;
SwTextGridPage(Window *pParent, const SfxItemSet &rSet);
~SwTextGridPage();
void UpdatePageSize(const SfxItemSet& rSet);
void PutGridItem(SfxItemSet& rSet);
DECL_LINK(GridTypeHdl, RadioButton*);
DECL_LINK(CharorLineChangedHdl, SpinField*);
DECL_LINK(TextSizeChangedHdl, SpinField*);
DECL_LINK(GridModifyHdl, void*);
DECL_LINK(DisplayGridHdl, CheckBox*);
using SfxTabPage::ActivatePage;
using SfxTabPage::DeactivatePage;
public:
static SfxTabPage *Create(Window *pParent, const SfxItemSet &rSet);
static USHORT* GetRanges();
virtual BOOL FillItemSet(SfxItemSet &rSet);
virtual void Reset(const SfxItemSet &rSet);
virtual void ActivatePage( const SfxItemSet& rSet );
virtual int DeactivatePage( SfxItemSet* pSet = 0 );
};
#endif
<|endoftext|>
|
<commit_before>// LICENSE/*{{{*/
/*
sxc - Simple Xmpp Client
Copyright (C) 2008 Dennis Felsing, Andreas Waidler
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/>.
*/
/*}}}*/
/* $Id$ */
/**
* @file Errno.hxx
* @author Andreas Waidler
* @brief Contains functions for handling the system errno variable.
*/
#ifndef EXCEPTION_ERRNO_HXX
#define EXCEPTION_ERRNO_HXX
// INCLUDES/*{{{*/
#include <Exception/Type.hxx>
/*}}}*/
namespace Exception
{
/** Transforms the passed errno into an exception type.
*
* @param p_errno The errno that occured and that should be transformed.
*
* @return An Exception::Type that matches the passed errno.
*/
Type errnoToType(int p_errno);
}
#endif // EXCEPTION_ERRNO_HXX
// Use no tabs at all; four spaces indentation; max. eighty chars per line.
// vim: et ts=4 sw=4 tw=80 fo+=c fdm=marker
<commit_msg>Improved docblock in Errno.hxx<commit_after>// LICENSE/*{{{*/
/*
sxc - Simple Xmpp Client
Copyright (C) 2008 Dennis Felsing, Andreas Waidler
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/>.
*/
/*}}}*/
/* $Id$ */
/**
* @file Errno.hxx
* @author Andreas Waidler
* @brief Contains functions for handling the system errno variable.
*/
#ifndef EXCEPTION_ERRNO_HXX
#define EXCEPTION_ERRNO_HXX
// INCLUDES/*{{{*/
#include <Exception/Type.hxx>
/*}}}*/
namespace Exception
{
/** Transforms the passed errno into an exception type.
*
* For a list of possible errno's and their meaning, look at the following
* man pages:
* @li man 2 stat
* @li man 3 mkfifo
*
* @param p_errno The errno that occured and that should be transformed.
* @return An Exception::Type that matches the passed errno.
*/
Type errnoToType(int p_errno);
}
#endif // EXCEPTION_ERRNO_HXX
// Use no tabs at all; four spaces indentation; max. eighty chars per line.
// vim: et ts=4 sw=4 tw=80 fo+=c fdm=marker
<|endoftext|>
|
<commit_before>#include "defs.hpp"
#include <Grappa.hpp>
#include <Collective.hpp>
#include <Delegate.hpp>
#include <ParallelLoop.hpp>
#include <GlobalCompletionEvent.hpp>
#include <GlobalHashSet.hpp>
#include <GlobalCounter.hpp>
#include <Array.hpp>
using namespace Grappa;
namespace d = Grappa::delegate;
DECLARE_int64(cc_hash_size);
static graph g;
static GlobalAddress<graphint> colors;
static GlobalAddress<graphint> visited;
static GlobalAddress<color_t> marks;
static bool changed;
static graphint ncomponents;
struct Edge {
graphint start, end;
bool operator==(const Edge& e) const { return e.start == start && e.end == end; }
friend std::ostream& operator<<(std::ostream& o, const Edge& e);
};
std::ostream& operator<<(std::ostream& o, const Edge& e) {
o << "{" << e.start << "," << e.end << "}";
return o;
}
namespace std {
template <> struct hash<Edge> {
typedef size_t result_type;
typedef Edge argument_type;
size_t operator()(Edge const & e) const noexcept {
return static_cast<size_t>(e.start ^ e.end);
}
};
}
using EdgeHashSet = GlobalHashSet<Edge>;
static GlobalAddress<EdgeHashSet> component_edges;
template< GlobalCompletionEvent * GCE = &impl::local_gce >
void explore(graphint v, graphint mycolor) {
if (mycolor < 0) {
auto claimed = d::call(colors+v, [v](graphint * c){
if (*c < 0) {
*c = v;
return true;
} else {
return false;
}
});
if (!claimed) return;
mycolor = v;
}
// visit neighbors of v
graphint _c[2]; Incoherent<graphint>::RO c(g.edgeStart+v, 2, _c);
forall_localized_async<GCE>(g.endVertex+c[0], c[1]-c[0], [mycolor](graphint& ev){
// TODO: make async
GCE->enroll();
Core origin = mycore();
auto colors_ev = colors+ev;
send_message(colors_ev.core(), [origin,mycolor,colors_ev]{
auto ec = colors_ev.pointer();
size_t ev = colors_ev - colors;
if (*ec < 0) {
*ec = mycolor;
publicTask([ev,origin,mycolor]{
explore<GCE>(ev,mycolor);
complete(make_global(GCE,origin));
});
} else {
// already had color
// TODO: avoid spawning task? (i.e. make insert() async)
privateTask([ec,mycolor,origin]{
Edge edge = (*ec > mycolor) ? Edge{mycolor,*ec} : Edge{*ec,mycolor};
component_edges->insert(edge);
complete(make_global(GCE,origin));
});
}
});
});
}
graphint dfs(graphint root) {
graphint mycolor = root;
// VLOG(0) << "dfs(" << root << ")";
std::function<bool(graphint)> rec = [&mycolor,&rec](graphint v) {
bool found = false;
graphint _c[2]; Incoherent<graphint>::RO c(g.edgeStart+v, 2, _c);
// VLOG(0) << "rec(" << v << ")[" << c[0] << " - " << c[1] << "]";
for (graphint i=c[0]; i<c[1]; i++) {
graphint ev = d::read(g.endVertex+i);
// VLOG(0) << "[" << i-c[0] << "]: " << ev;
if (d::read(visited+ev)) {
mycolor = d::read(colors+ev);
// VLOG(0) << " found -> " << mycolor;
found = true;
break;
} else if (rec(ev)) {
// VLOG(0) << " found (" << mycolor << ")";
found = true;
break;
}
}
return found;
};
// CHECK(rec(root));
return mycolor;
}
template< GlobalCompletionEvent * GCE = &impl::local_gce >
void search(graphint v, graphint mycolor) {
graphint _c[2]; Incoherent<graphint>::RO c(g.edgeStart+v, 2, _c);
forall_localized_async<GCE>(g.endVertex+c[0], c[1]-c[0], [mycolor](graphint& ev){
if (d::fetch_and_add(visited+ev, 1) == 0) {
d::write(colors+ev, mycolor);
publicTask<GCE>([ev,mycolor]{ search(ev, mycolor); });
}
});
}
/// Takes a graph as input and an array with length NV. The array D will store
/// the coloring of each component. The coloring will be using vertex IDs and
/// therefore will be an integer between 0 and NV-1. The function returns the
/// total number of components.
graphint connectedComponents(graph * in_g) {
const auto NV = in_g->numVertices;
auto _component_edges = EdgeHashSet::create(FLAGS_cc_hash_size);
auto _colors = global_alloc<graphint>(NV);
auto _visited = global_alloc<graphint>(NV);
auto _in_g = *in_g;
call_on_all_cores([_colors,_visited,_in_g,_component_edges]{
component_edges = _component_edges;
colors = _colors;
visited = _visited;
g = _in_g;
});
forall_localized(colors, NV, [](int64_t v, graphint& c){ c = -v-1; });
///////////////////////////////////////////////////////////////
// Find component edges
forall_localized<&impl::local_gce,256>(colors, NV, [](int64_t v, graphint& c){
explore(v,c);
});
LOG(INFO) << "cc_intermediate_set_size: " << component_edges->size();
component_edges->forall_keys([](Edge& e){ VLOG(0) << e; });
DVLOG(3) << util::array_str("colors: ", colors, NV, 32);
///////////////////////////////////////////////////////////////
//
int npass = 0;
do {
DVLOG(2) << "npass " << npass;
call_on_all_cores([]{ changed = false; });
// Hook
DVLOG(2) << "hook";
component_edges->forall_keys([NV](Edge& e){
graphint i = e.start, j = e.end;
CHECK_LT(i, NV);
CHECK_LT(j, NV);
graphint ci = d::read(colors+e.start),
cj = d::read(colors+e.end);
CHECK_LT(ci, NV);
CHECK_LT(cj, NV);
bool lchanged = false;
if ( ci < cj ) {
lchanged = lchanged || d::call(colors+cj, [ci,cj](graphint* ccj){
if (*ccj == cj) { *ccj = ci; return true; }
else { return false; }
});
}
if (!lchanged && cj < ci) {
lchanged = lchanged || d::call(colors+ci, [ci,cj](graphint* cci){
if (*cci == ci) { *cci = cj; return true; }
else { return false; }
});
}
if (lchanged) { changed = true; }
});
// Compress
DVLOG(2) << "compress";
component_edges->forall_keys([NV](Edge& e){
auto compress = [NV](graphint i) {
graphint ci, cci, nc;
ci = nc = d::read(colors+i);
CHECK_LT(ci, NV);
CHECK_LT(nc, NV);
while ( nc != (cci=d::read(colors+nc)) ) { nc = d::read(colors+cci); CHECK_LT(nc, NV); }
if (nc != ci) {
changed = true;
d::write(colors+i, nc);
}
};
compress(e.start);
compress(e.end);
});
npass++;
} while (reduce<bool,collective_or>(&changed) == true);
LOG(INFO) << "cc_pram_passes: " << npass;
Grappa::memset(visited, 0, NV);
component_edges->forall_keys([](Edge& e){
auto mycolor = d::read(colors+e.start);
for (auto ev : {e.start, e.end}) {
publicTask([ev,mycolor]{
if (d::fetch_and_add(visited+ev, 1) == 0) {
search(ev,mycolor);
}
});
}
});
DVLOG(3) << util::array_str("colors: ", colors, NV, 32);
auto nca = GlobalCounter::create();
forall_localized(colors, NV, [nca](int64_t v, graphint& c){ if (c == v) nca->incr(); });
graphint ncomponents = nca->count();
nca->destroy();
VLOG(0) << "ncomponents: " << ncomponents;
return ncomponents;
}
<commit_msg>CC: cleanup, add timing<commit_after>#include "defs.hpp"
#include <Grappa.hpp>
#include <Collective.hpp>
#include <Delegate.hpp>
#include <ParallelLoop.hpp>
#include <GlobalCompletionEvent.hpp>
#include <GlobalHashSet.hpp>
#include <GlobalCounter.hpp>
#include <Array.hpp>
using namespace Grappa;
namespace d = Grappa::delegate;
DECLARE_int64(cc_hash_size);
static graph g;
static GlobalAddress<graphint> colors;
static GlobalAddress<graphint> visited;
static GlobalAddress<color_t> marks;
static bool changed;
static graphint ncomponents;
struct Edge {
graphint start, end;
bool operator==(const Edge& e) const { return e.start == start && e.end == end; }
friend std::ostream& operator<<(std::ostream& o, const Edge& e);
};
std::ostream& operator<<(std::ostream& o, const Edge& e) {
o << "{" << e.start << "," << e.end << "}";
return o;
}
namespace std {
template <> struct hash<Edge> {
typedef size_t result_type;
typedef Edge argument_type;
size_t operator()(Edge const & e) const noexcept {
return static_cast<size_t>(e.start ^ e.end);
}
};
}
using EdgeHashSet = GlobalHashSet<Edge>;
static GlobalAddress<EdgeHashSet> component_edges;
template< GlobalCompletionEvent * GCE = &impl::local_gce >
void explore(graphint v, graphint mycolor) {
if (mycolor < 0) {
auto claimed = d::call(colors+v, [v](graphint * c){
if (*c < 0) {
*c = v;
return true;
} else {
return false;
}
});
if (!claimed) return;
mycolor = v;
}
// visit neighbors of v
graphint _c[2]; Incoherent<graphint>::RO c(g.edgeStart+v, 2, _c);
forall_localized_async<GCE>(g.endVertex+c[0], c[1]-c[0], [mycolor](graphint& ev){
// TODO: make async
GCE->enroll();
Core origin = mycore();
auto colors_ev = colors+ev;
send_message(colors_ev.core(), [origin,mycolor,colors_ev]{
auto ec = colors_ev.pointer();
size_t ev = colors_ev - colors;
if (*ec < 0) {
*ec = mycolor;
publicTask([ev,origin,mycolor]{
explore<GCE>(ev,mycolor);
complete(make_global(GCE,origin));
});
} else {
// already had color
// TODO: avoid spawning task? (i.e. make insert() async)
privateTask([ec,mycolor,origin]{
Edge edge = (*ec > mycolor) ? Edge{mycolor,*ec} : Edge{*ec,mycolor};
component_edges->insert(edge);
complete(make_global(GCE,origin));
});
}
});
});
}
graphint dfs(graphint root) {
graphint mycolor = root;
// VLOG(0) << "dfs(" << root << ")";
std::function<bool(graphint)> rec = [&mycolor,&rec](graphint v) {
bool found = false;
graphint _c[2]; Incoherent<graphint>::RO c(g.edgeStart+v, 2, _c);
// VLOG(0) << "rec(" << v << ")[" << c[0] << " - " << c[1] << "]";
for (graphint i=c[0]; i<c[1]; i++) {
graphint ev = d::read(g.endVertex+i);
// VLOG(0) << "[" << i-c[0] << "]: " << ev;
if (d::read(visited+ev)) {
mycolor = d::read(colors+ev);
// VLOG(0) << " found -> " << mycolor;
found = true;
break;
} else if (rec(ev)) {
// VLOG(0) << " found (" << mycolor << ")";
found = true;
break;
}
}
return found;
};
// CHECK(rec(root));
return mycolor;
}
template< GlobalCompletionEvent * GCE = &impl::local_gce >
void search(graphint v, graphint mycolor) {
graphint _c[2]; Incoherent<graphint>::RO c(g.edgeStart+v, 2, _c);
forall_localized_async<GCE>(g.endVertex+c[0], c[1]-c[0], [mycolor](graphint& ev){
if (d::fetch_and_add(visited+ev, 1) == 0) {
d::write(colors+ev, mycolor);
publicTask<GCE>([ev,mycolor]{ search(ev, mycolor); });
}
});
}
void pram_cc() {
const auto NV = g.numVertices;
int npass = 0;
do {
DVLOG(2) << "npass " << npass;
call_on_all_cores([]{ changed = false; });
// Hook
DVLOG(2) << "hook";
component_edges->forall_keys([NV](Edge& e){
graphint i = e.start, j = e.end;
CHECK_LT(i, NV);
CHECK_LT(j, NV);
graphint ci = d::read(colors+e.start),
cj = d::read(colors+e.end);
CHECK_LT(ci, NV);
CHECK_LT(cj, NV);
bool lchanged = false;
if ( ci < cj ) {
lchanged = lchanged || d::call(colors+cj, [ci,cj](graphint* ccj){
if (*ccj == cj) { *ccj = ci; return true; }
else { return false; }
});
}
if (!lchanged && cj < ci) {
lchanged = lchanged || d::call(colors+ci, [ci,cj](graphint* cci){
if (*cci == ci) { *cci = cj; return true; }
else { return false; }
});
}
if (lchanged) { changed = true; }
});
// Compress
DVLOG(2) << "compress";
component_edges->forall_keys([NV](Edge& e){
auto compress = [NV](graphint i) {
graphint ci, cci, nc;
ci = nc = d::read(colors+i);
CHECK_LT(ci, NV);
CHECK_LT(nc, NV);
while ( nc != (cci=d::read(colors+nc)) ) { nc = d::read(colors+cci); CHECK_LT(nc, NV); }
if (nc != ci) {
changed = true;
d::write(colors+i, nc);
}
};
compress(e.start);
compress(e.end);
});
npass++;
} while (reduce<bool,collective_or>(&changed) == true);
LOG(INFO) << "cc_pram_passes: " << npass;
}
/// Takes a graph as input and an array with length NV. The array D will store
/// the coloring of each component. The coloring will be using vertex IDs and
/// therefore will be an integer between 0 and NV-1. The function returns the
/// total number of components.
graphint connectedComponents(graph * in_g) {
double t;
const auto NV = in_g->numVertices;
auto _component_edges = EdgeHashSet::create(FLAGS_cc_hash_size);
auto _colors = global_alloc<graphint>(NV);
auto _visited = global_alloc<graphint>(NV);
auto _in_g = *in_g;
call_on_all_cores([_colors,_visited,_in_g,_component_edges]{
component_edges = _component_edges;
colors = _colors;
visited = _visited;
g = _in_g;
});
///////////////////////////////////////////////////////////////
// Find component edges
t = walltime();
forall_localized(colors, NV, [](int64_t v, graphint& c){ c = -v-1; });
forall_localized<&impl::local_gce,256>(colors, NV, [](int64_t v, graphint& c){
explore(v,c);
});
t = walltime() - t;
LOG(INFO) << "cc_set_size: " << component_edges->size();
LOG(INFO) << "cc_set_insert_time: " << t;
if (VLOG_IS_ON(3)) {
component_edges->forall_keys([](Edge& e){ VLOG(0) << e; });
VLOG(3) << util::array_str("colors: ", colors, NV, 32);
}
///////////////////////////////////////////////////////////////
// Run classic Connected Components algorithm on reduced graph
t = walltime();
pram_cc();
t = walltime() - t;
LOG(INFO) << "cc_reduced_graph_time: " << t;
///////////////////////////////////////////////////////////////
// Propagate colors out to the rest of the vertices
t = walltime();
Grappa::memset(visited, 0, NV);
component_edges->forall_keys([](Edge& e){
auto mycolor = d::read(colors+e.start);
for (auto ev : {e.start, e.end}) {
publicTask([ev,mycolor]{
if (d::fetch_and_add(visited+ev, 1) == 0) {
search(ev,mycolor);
}
});
}
});
t = walltime() - t;
LOG(INFO) << "cc_propagate_time: " << t;
DVLOG(3) << util::array_str("colors: ", colors, NV, 32);
auto nca = GlobalCounter::create();
forall_localized(colors, NV, [nca](int64_t v, graphint& c){ if (c == v) nca->incr(); });
graphint ncomponents = nca->count();
nca->destroy();
return ncomponents;
}
<|endoftext|>
|
<commit_before>#include <stdio.h>
#include "base/at_exit.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/files/file_enumerator.h"
#include "base/i18n/icu_util.h"
#include "base/logging.h"
#include "base/process/memory.h"
#include "base/strings/string_util.h"
#include "base/memory/scoped_ptr.h"
#include "base/stl_util.h"
#include "crypto/secure_hash.h"
#include "crypto/sha2.h"
#include "extensions/browser/content_hash_tree.h"
#include "extensions/browser/computed_hashes.h"
#include "base/base64.h"
#include "base/json/json_reader.h"
#include "base/json/json_writer.h"
#include "base/values.h"
using crypto::kSHA256Length;
using crypto::SecureHash;
namespace {
const char kBlockHashesKey[] = "root_hash";
const char kBlockSizeKey[] = "block_size";
const char kFileHashesKey[] = "files";
const char kPathKey[] = "path";
const char kVersionKey[] = "version";
const int kVersion = 2;
typedef std::set<base::FilePath> SortedFilePathSet;
bool MakePathAbsolute(base::FilePath* file_path) {
DCHECK(file_path);
base::FilePath current_directory;
if (!base::GetCurrentDirectory(¤t_directory))
return false;
if (file_path->IsAbsolute())
return true;
if (current_directory.empty()) {
*file_path = base::MakeAbsoluteFilePath(*file_path);
return true;
}
if (!current_directory.IsAbsolute())
return false;
#ifdef OS_LINUX
//linux might gives "/" as current_directory, return false
if (current_directory.value().length() <= 1)
return false;
#endif
*file_path = current_directory.Append(*file_path);
return true;
}
} // namespace
class MyComputedHashes {
public:
class Writer {
public:
Writer();
~Writer();
// Adds hashes for |relative_path|. Should not be called more than once
// for a given |relative_path|.
void AddHash(const base::FilePath& relative_path,
int block_size,
const std::string& hashes);
bool WriteToFile(const base::FilePath& path);
private:
// Each element of this list contains the path and block hashes for one
// file.
scoped_ptr<base::ListValue> file_list_;
};
// Computes the SHA256 hash of each |block_size| chunk in |contents|, placing
// the results into |hashes|.
static void ComputeHashesForContent(const std::string& contents,
size_t block_size,
std::vector<std::string>* hashes);
};
MyComputedHashes::Writer::Writer() : file_list_(new base::ListValue) {
}
MyComputedHashes::Writer::~Writer() {
}
void MyComputedHashes::Writer::AddHash(const base::FilePath& relative_path,
int block_size,
const std::string& root) {
base::DictionaryValue* dict = new base::DictionaryValue();
file_list_->Append(dict);
dict->SetString(kPathKey,
relative_path.NormalizePathSeparatorsTo('/').AsUTF8Unsafe());
//dict->SetInteger(kBlockSizeKey, block_size);
std::string encoded;
base::Base64Encode(root, &encoded);
base::ReplaceChars(encoded, "=", "", &encoded);
base::ReplaceChars(encoded, "/", "_", &encoded);
base::ReplaceChars(encoded, "+", "-", &encoded);
dict->SetString(kBlockHashesKey, encoded);
}
bool MyComputedHashes::Writer::WriteToFile(const base::FilePath& path) {
std::string json;
base::DictionaryValue top_dictionary;
top_dictionary.SetInteger("block_size", 4096);
top_dictionary.SetInteger("hash_block_size", 4096);
top_dictionary.SetString("format", "treehash");
top_dictionary.Set(kFileHashesKey, file_list_.release());
if (!base::JSONWriter::Write(top_dictionary, &json))
return false;
int written = base::WriteFile(path, json.data(), json.size());
if (static_cast<unsigned>(written) != json.size()) {
LOG(ERROR) << "Error writing " << path.AsUTF8Unsafe()
<< " ; write result:" << written << " expected:" << json.size();
return false;
}
return true;
}
void MyComputedHashes::ComputeHashesForContent(const std::string& contents,
size_t block_size,
std::vector<std::string>* hashes) {
size_t offset = 0;
// Even when the contents is empty, we want to output at least one hash
// block (the hash of the empty string).
do {
const char* block_start = contents.data() + offset;
DCHECK(offset <= contents.size());
size_t bytes_to_read = std::min(contents.size() - offset, block_size);
scoped_ptr<crypto::SecureHash> hash(
crypto::SecureHash::Create(crypto::SecureHash::SHA256));
hash->Update(block_start, bytes_to_read);
hashes->push_back(std::string());
std::string* buffer = &(hashes->back());
buffer->resize(crypto::kSHA256Length);
hash->Finish(string_as_array(buffer), buffer->size());
// If |contents| is empty, then we want to just exit here.
if (bytes_to_read == 0)
break;
offset += bytes_to_read;
} while (offset < contents.size());
}
bool CreateHashes(const base::FilePath& hashes_file, const base::FilePath& work_path) {
// Make sure the directory exists.
if (!base::CreateDirectoryAndGetError(hashes_file.DirName(), NULL))
return false;
base::FilePath root_path(work_path);
MakePathAbsolute(&root_path);
base::FileEnumerator enumerator(root_path,
true, /* recursive */
base::FileEnumerator::FILES);
// First discover all the file paths and put them in a sorted set.
SortedFilePathSet paths;
for (;;) {
base::FilePath full_path = enumerator.Next();
if (full_path.empty())
break;
paths.insert(full_path);
}
// Now iterate over all the paths in sorted order and compute the block hashes
// for each one.
MyComputedHashes::Writer writer;
for (SortedFilePathSet::iterator i = paths.begin(); i != paths.end(); ++i) {
const base::FilePath& full_path = *i;
base::FilePath relative_path;
root_path.AppendRelativePath(full_path, &relative_path);
relative_path = relative_path.NormalizePathSeparatorsTo('/');
std::string contents;
if (!base::ReadFileToString(full_path, &contents)) {
LOG(ERROR) << "Could not read " << full_path.MaybeAsASCII();
continue;
}
// Iterate through taking the hash of each block of size (block_size_) of
// the file.
std::vector<std::string> hashes;
MyComputedHashes::ComputeHashesForContent(contents, 4096, &hashes);
std::string root =
extensions::ComputeTreeHashRoot(hashes, 4096 / crypto::kSHA256Length);
writer.AddHash(relative_path, 4096, root);
}
bool result = writer.WriteToFile(hashes_file);
return result;
}
#if defined(OS_WIN)
int wmain(int argc, wchar_t* argv[]) {
#else
int main(int argc, char* argv[]) {
#endif
base::AtExitManager exit_manager;
base::i18n::InitializeICU();
return CreateHashes(base::FilePath(FILE_PATH_LITERAL("payload.json")),
base::FilePath(FILE_PATH_LITERAL("."))) ? 1 : 0;
}
<commit_msg>fix payload compilation warning<commit_after>#include <stdio.h>
#include "base/at_exit.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/files/file_enumerator.h"
#include "base/i18n/icu_util.h"
#include "base/logging.h"
#include "base/process/memory.h"
#include "base/strings/string_util.h"
#include "base/memory/scoped_ptr.h"
#include "base/stl_util.h"
#include "crypto/secure_hash.h"
#include "crypto/sha2.h"
#include "extensions/browser/content_hash_tree.h"
#include "extensions/browser/computed_hashes.h"
#include "base/base64.h"
#include "base/json/json_reader.h"
#include "base/json/json_writer.h"
#include "base/values.h"
using crypto::kSHA256Length;
using crypto::SecureHash;
namespace {
const char kBlockHashesKey[] = "root_hash";
const char kBlockSizeKey[] = "block_size";
const char kFileHashesKey[] = "files";
const char kPathKey[] = "path";
const char kVersionKey[] = "version";
const int kVersion = 2;
typedef std::set<base::FilePath> SortedFilePathSet;
bool MakePathAbsolute(base::FilePath* file_path) {
DCHECK(file_path);
base::FilePath current_directory;
if (!base::GetCurrentDirectory(¤t_directory))
return false;
if (file_path->IsAbsolute())
return true;
if (current_directory.empty()) {
*file_path = base::MakeAbsoluteFilePath(*file_path);
return true;
}
if (!current_directory.IsAbsolute())
return false;
#ifdef OS_LINUX
//linux might gives "/" as current_directory, return false
if (current_directory.value().length() <= 1)
return false;
#endif
*file_path = current_directory.Append(*file_path);
return true;
}
} // namespace
class MyComputedHashes {
public:
class Writer {
public:
Writer();
~Writer();
// Adds hashes for |relative_path|. Should not be called more than once
// for a given |relative_path|.
void AddHash(const base::FilePath& relative_path,
int block_size,
const std::string& hashes);
bool WriteToFile(const base::FilePath& path);
private:
// Each element of this list contains the path and block hashes for one
// file.
scoped_ptr<base::ListValue> file_list_;
};
// Computes the SHA256 hash of each |block_size| chunk in |contents|, placing
// the results into |hashes|.
static void ComputeHashesForContent(const std::string& contents,
size_t block_size,
std::vector<std::string>* hashes);
};
MyComputedHashes::Writer::Writer() : file_list_(new base::ListValue) {
}
MyComputedHashes::Writer::~Writer() {
}
void MyComputedHashes::Writer::AddHash(const base::FilePath& relative_path,
int block_size,
const std::string& root) {
base::DictionaryValue* dict = new base::DictionaryValue();
file_list_->Append(dict);
dict->SetString(kPathKey,
relative_path.NormalizePathSeparatorsTo('/').AsUTF8Unsafe());
//dict->SetInteger(kBlockSizeKey, block_size);
std::string encoded;
base::Base64Encode(root, &encoded);
base::ReplaceChars(encoded, "=", "", &encoded);
base::ReplaceChars(encoded, "/", "_", &encoded);
base::ReplaceChars(encoded, "+", "-", &encoded);
dict->SetString(kBlockHashesKey, encoded);
}
bool MyComputedHashes::Writer::WriteToFile(const base::FilePath& path) {
std::string json;
base::DictionaryValue top_dictionary;
top_dictionary.SetInteger("block_size", 4096);
top_dictionary.SetInteger("hash_block_size", 4096);
top_dictionary.SetString("format", "treehash");
top_dictionary.Set(kFileHashesKey, file_list_.release());
if (!base::JSONWriter::Write(top_dictionary, &json))
return false;
int written = (int)base::WriteFile(path, json.data(), json.size());
if (static_cast<unsigned>(written) != json.size()) {
LOG(ERROR) << "Error writing " << path.AsUTF8Unsafe()
<< " ; write result:" << written << " expected:" << json.size();
return false;
}
return true;
}
void MyComputedHashes::ComputeHashesForContent(const std::string& contents,
size_t block_size,
std::vector<std::string>* hashes) {
size_t offset = 0;
// Even when the contents is empty, we want to output at least one hash
// block (the hash of the empty string).
do {
const char* block_start = contents.data() + offset;
DCHECK(offset <= contents.size());
size_t bytes_to_read = std::min(contents.size() - offset, block_size);
scoped_ptr<crypto::SecureHash> hash(
crypto::SecureHash::Create(crypto::SecureHash::SHA256));
hash->Update(block_start, bytes_to_read);
hashes->push_back(std::string());
std::string* buffer = &(hashes->back());
buffer->resize(crypto::kSHA256Length);
hash->Finish(string_as_array(buffer), buffer->size());
// If |contents| is empty, then we want to just exit here.
if (bytes_to_read == 0)
break;
offset += bytes_to_read;
} while (offset < contents.size());
}
bool CreateHashes(const base::FilePath& hashes_file, const base::FilePath& work_path) {
// Make sure the directory exists.
if (!base::CreateDirectoryAndGetError(hashes_file.DirName(), NULL))
return false;
base::FilePath root_path(work_path);
MakePathAbsolute(&root_path);
base::FileEnumerator enumerator(root_path,
true, /* recursive */
base::FileEnumerator::FILES);
// First discover all the file paths and put them in a sorted set.
SortedFilePathSet paths;
for (;;) {
base::FilePath full_path = enumerator.Next();
if (full_path.empty())
break;
paths.insert(full_path);
}
// Now iterate over all the paths in sorted order and compute the block hashes
// for each one.
MyComputedHashes::Writer writer;
for (SortedFilePathSet::iterator i = paths.begin(); i != paths.end(); ++i) {
const base::FilePath& full_path = *i;
base::FilePath relative_path;
root_path.AppendRelativePath(full_path, &relative_path);
relative_path = relative_path.NormalizePathSeparatorsTo('/');
std::string contents;
if (!base::ReadFileToString(full_path, &contents)) {
LOG(ERROR) << "Could not read " << full_path.MaybeAsASCII();
continue;
}
// Iterate through taking the hash of each block of size (block_size_) of
// the file.
std::vector<std::string> hashes;
MyComputedHashes::ComputeHashesForContent(contents, 4096, &hashes);
std::string root =
extensions::ComputeTreeHashRoot(hashes, 4096 / crypto::kSHA256Length);
writer.AddHash(relative_path, 4096, root);
}
bool result = writer.WriteToFile(hashes_file);
return result;
}
#if defined(OS_WIN)
int wmain(int argc, wchar_t* argv[]) {
#else
int main(int argc, char* argv[]) {
#endif
base::AtExitManager exit_manager;
base::i18n::InitializeICU();
return CreateHashes(base::FilePath(FILE_PATH_LITERAL("payload.json")),
base::FilePath(FILE_PATH_LITERAL("."))) ? 1 : 0;
}
<|endoftext|>
|
<commit_before>#include <cmath>
#include <ctime>
#include <iostream>
#include <vector>
using namespace std;
vector<long int> v_primes;
void InitVector(long int s) {
v_primes.reserve(s);
v_primes.push_back(2);
}
int main(int argc, char const *argv[]) {
clock_t begin = clock();
auto max = 10000000;
auto lprime = 2;
auto b = static_cast<int>(sqrt(lprime));
auto is_prime = true;
InitVector(max);
auto v_primes_s = v_primes.size();
for (long int i = 3; i < max; i += 2) {
is_prime = true;
b = static_cast<int>(sqrt(i));
for (auto j = 0; b >= v_primes[j]; ++j) {
if (i % v_primes[j] == 0) {
is_prime = false;
}
}
if (is_prime) {
v_primes.push_back(i);
lprime = i;
}
}
clock_t end = clock();
double elapsed_secs = double(end - begin)/CLOCKS_PER_SEC;
cout << "Seconds: " << elapsed_secs << endl;
cout << "Latest prime: " << lprime << endl;
cout << "Number of primes: " << v_primes.size() << endl;
cout << "Primes pr. sec: " << v_primes.size() / elapsed_secs << endl;
return 0;
}<commit_msg>Changed to generic name.<commit_after>#include <cmath>
#include <ctime>
#include <iostream>
#include <vector>
using namespace std;
vector<long int> primes;
void InitVector(long int s) {
primes.reserve(s);
primes.push_back(2);
}
int main(int argc, char const *argv[]) {
clock_t begin = clock();
auto max = 10000000;
auto lprime = 2;
auto b = static_cast<int>(sqrt(lprime));
auto is_prime = true;
InitVector(max);
auto primes_s = primes.size();
for (long int i = 3; i < max; i += 2) {
is_prime = true;
b = static_cast<int>(sqrt(i));
for (auto j = 0; b >= primes[j]; ++j) {
if (i % primes[j] == 0) {
is_prime = false;
}
}
if (is_prime) {
primes.push_back(i);
lprime = i;
}
}
clock_t end = clock();
double elapsed_secs = double(end - begin)/CLOCKS_PER_SEC;
cout << "Seconds: " << elapsed_secs << endl;
cout << "Latest prime: " << lprime << endl;
cout << "Number of primes: " << primes.size() << endl;
cout << "Primes pr. sec: " << primes.size() / elapsed_secs << endl;
return 0;
}<|endoftext|>
|
<commit_before>/*
This macro will add histograms from a list of root files and write them
to a target root file. The target file is newly created and must not be
identical to one of the source files.
Syntax:
hist_add targetfile source1 source2 ...
Author: Sven A. Schmidt, [email protected]
Date: 13.2.2001
This code is based on the hadd.C example by Rene Brun and Dirk Geppert,
which had a problem with directories more than one level deep.
(see macro hadd_old.C for this previous implementation).
I have tested this macro on rootfiles with one and two dimensional
histograms, and two levels of subdirectories. Feel free to send comments
or bug reports to me.
*/
#include "TFile.h"
#include "TH1.h"
#include "TTree.h"
#include "TKey.h"
#include <string.h>
#include <iostream.h>
TList *FileList;
TFile *Target;
void MergeRootfile( TDirectory *target, TList *sourcelist );
int main( int argc, char **argv ) {
FileList = new TList();
if ( argc < 4 ) {
cout << "Usage: " << argv[0] << " <target> <source1> <source2> ...\n";
cout << "supply at least two source files for this to make sense... ;-)\n";
exit( -1 );
}
cout << "Target file: " << argv[1] << endl;
Target = TFile::Open( argv[1], "RECREATE" );
for ( int i = 2; i < argc; i++ ) {
cout << "Source file " << i-1 << ": " << argv[i] << endl;
FileList->Add( TFile::Open( argv[i] ) );
}
MergeRootfile( Target, FileList );
}
// Merge all files from sourcelist into the target directory.
// The directory level (depth) is determined by the target directory's
// current level
void MergeRootfile( TDirectory *target, TList *sourcelist ) {
// cout << "Target path: " << target->GetPath() << endl;
TString path( (char*)strstr( target->GetPath(), ":" ) );
path.Remove( 0, 2 );
TFile *first_source = (TFile*)sourcelist->First();
first_source->cd( path );
TDirectory *current_sourcedir = gDirectory;
// loop over all keys in this directory
TIter nextkey( current_sourcedir->GetListOfKeys() );
while ( TKey *key = (TKey*)nextkey() ) {
// read object from first source file
first_source->cd( path );
TObject *obj = key->ReadObj();
if ( obj->IsA()->InheritsFrom( "TH1" ) ) {
// descendant of TH1 -> merge it
// cout << "Merging histogram " << obj->GetName() << endl;
TH1 *h1 = (TH1*)obj;
// loop over all source files and add the content of the
// correspondant histogram to the one pointed to by "h1"
TFile *nextsource = (TFile*)sourcelist->After( first_source );
while ( nextsource ) {
// make sure we are at the correct directory level by cd'ing to path
nextsource->cd( path );
TH1 *h2 = (TH1*)gDirectory->Get( h1->GetName() );
if ( h2 ) {
h1->Add( h2 );
delete h2; // don't know if this is necessary, i.e. if
// h2 is created by the call to gDirectory above.
}
nextsource = (TFile*)sourcelist->After( nextsource );
}
} else if ( obj->IsA()->InheritsFrom( "TDirectory" ) ) {
// it's a subdirectory
cout << "Found subdirectory " << obj->GetName() << endl;
// create a new subdir of same name and title in the target file
target->cd();
TDirectory *newdir = target->mkdir( obj->GetName(), obj->GetTitle() );
// newdir is now the starting point of another round of merging
// newdir still knows its depth within the target file via
// GetPath(), so we can still figure out where we are in the recursion
MergeRootfile( newdir, sourcelist );
} else {
// object is of no type that we know or can handle
cout << "Unknown object type, name: "
<< obj->GetName() << " title: " << obj->GetTitle() << endl;
}
// now write the merged histogram (which is "in" obj) to the target file
// note that this will just store obj in the current directory level,
// which is not persistent until the complete directory itself is stored
// by "target->Write()" below
if ( obj ) {
target->cd();
obj->Write( key->GetName() );
}
} // while ( ( TKey *key = (TKey*)nextkey() ) )
// save modifications to target file
target->Write();
}
<commit_msg>New version of hadd.C that can be used directly as a macro. Note that this macro is kept as a tutorial. To merge a list of files use the new program hadd in $ROOTSYS/bin/hadd<commit_after>/*
This macro will add histograms from a list of root files and write them
to a target root file. The target file is newly created and must not be
identical to one of the source files.
Author: Sven A. Schmidt, [email protected]
Date: 13.2.2001
This code is based on the hadd.C example by Rene Brun and Dirk Geppert,
which had a problem with directories more than one level deep.
(see macro hadd_old.C for this previous implementation).
To use this macro, modify the file names in function hadd.
NB: This macro is provided as a tutorial.
Use $ROOTSYS/bin/hadd to merge many histogram files
*/
#include "TFile.h"
#include "TH1.h"
#include "TTree.h"
#include "TKey.h"
#include <string.h>
#include <iostream.h>
TList *FileList;
TFile *Target;
void MergeRootfile( TDirectory *target, TList *sourcelist );
void hadd() {
// in an interactive ROOT session, edit the file names
// Target and FileList, then
// root > .L hadd.C
// root > hadd()
Target = TFile::Open( "result.root", "RECREATE" );
FileList = new TList();
FileList->Add( TFile::Open("hsimple1.root") );
FileList->Add( TFile::Open("hsimple2.root") );
MergeRootfile( Target, FileList );
}
void MergeRootfile( TDirectory *target, TList *sourcelist ) {
// Merge all files from sourcelist into the target directory.
// The directory level (depth) is determined by the target directory's
// current level
// cout << "Target path: " << target->GetPath() << endl;
TString path( (char*)strstr( target->GetPath(), ":" ) );
path.Remove( 0, 2 );
TFile *first_source = (TFile*)sourcelist->First();
first_source->cd( path );
TDirectory *current_sourcedir = gDirectory;
// loop over all keys in this directory
TIter nextkey( current_sourcedir->GetListOfKeys() );
TKey *key;
while ( key = (TKey*)nextkey() ) {
// read object from first source file
first_source->cd( path );
TObject *obj = key->ReadObj();
if ( obj->IsA()->InheritsFrom( "TH1" ) ) {
// descendant of TH1 -> merge it
// cout << "Merging histogram " << obj->GetName() << endl;
TH1 *h1 = (TH1*)obj;
// loop over all source files and add the content of the
// correspondant histogram to the one pointed to by "h1"
TFile *nextsource = (TFile*)sourcelist->After( first_source );
while ( nextsource ) {
// make sure we are at the correct directory level by cd'ing to path
nextsource->cd( path );
TH1 *h2 = (TH1*)gDirectory->Get( h1->GetName() );
if ( h2 ) {
h1->Add( h2 );
delete h2; // don't know if this is necessary, i.e. if
// h2 is created by the call to gDirectory above.
}
nextsource = (TFile*)sourcelist->After( nextsource );
}
} else if ( obj->IsA()->InheritsFrom( "TDirectory" ) ) {
// it's a subdirectory
cout << "Found subdirectory " << obj->GetName() << endl;
// create a new subdir of same name and title in the target file
target->cd();
TDirectory *newdir = target->mkdir( obj->GetName(), obj->GetTitle() );
// newdir is now the starting point of another round of merging
// newdir still knows its depth within the target file via
// GetPath(), so we can still figure out where we are in the recursion
MergeRootfile( newdir, sourcelist );
} else {
// object is of no type that we know or can handle
cout << "Unknown object type, name: "
<< obj->GetName() << " title: " << obj->GetTitle() << endl;
}
// now write the merged histogram (which is "in" obj) to the target file
// note that this will just store obj in the current directory level,
// which is not persistent until the complete directory itself is stored
// by "target->Write()" below
if ( obj ) {
target->cd();
obj->Write( key->GetName() );
}
} // while ( ( TKey *key = (TKey*)nextkey() ) )
// save modifications to target file
target->Write();
}
<|endoftext|>
|
<commit_before>#include <cppunit/ui/text/TestRunner.h>
#include <cppunit/TestCaller.h>
#include <cppunit/TestCase.h>
#include <cppunit/extensions/HelperMacros.h>
#include <iostream>
#include <vector>
#include "Hand.h"
class CardTest : public CppUnit::TestCase
{
private:
public:
void testCreateHand()
{//Basic test of creating a hand.
//Set up the hand without cards.
Blackjack::Hand h;
//Verify the hand without cards.
CPPUNIT_ASSERT( h.getNumCards() == 0 );
//Add a card.
h.addCard( Blackjack::Two, Blackjack::Clubs );
//Verify the values.
CPPUNIT_ASSERT( h.getNumCards() == 1 );
CPPUNIT_ASSERT( h.getCard(0).getRank() == Blackjack::Two );
CPPUNIT_ASSERT( h.getCard(0).getSuit() == Blackjack::Clubs );
CPPUNIT_ASSERT( h.getCard(0).getPoints() == 2 );
CPPUNIT_ASSERT( h.getCard(0).isAce() == false );
}
void testAddCardToHand()
{//Basic test of creating a hand.
//Set up the hand without cards.
Blackjack::Hand h;
//Verify the hand without cards.
CPPUNIT_ASSERT( h.getNumCards() == 0 );
//Add a card.
h.addCard( Blackjack::Two, Blackjack::Clubs );
//Verify the values.
CPPUNIT_ASSERT( h.getNumCards() == 1 );
CPPUNIT_ASSERT( h.getCard(0).getRank() == Blackjack::Two );
CPPUNIT_ASSERT( h.getCard(0).getSuit() == Blackjack::Clubs );
CPPUNIT_ASSERT( h.getCard(0).getPoints() == 2 );
CPPUNIT_ASSERT( h.getCard(0).isAce() == false );
//Add another card.
h.addCard( Blackjack::Ace, Blackjack::Hearts );
//Verify the values.
CPPUNIT_ASSERT( h.getNumCards() == 2 );
CPPUNIT_ASSERT( h.getCard(1).getRank() == Blackjack::Ace );
CPPUNIT_ASSERT( h.getCard(1).getSuit() == Blackjack::Hearts );
CPPUNIT_ASSERT( h.getCard(1).getPoints() == 11 );
CPPUNIT_ASSERT( h.getCard(1).isAce() == true );
}
void testClearHand()
{//Basic test of creating a hand.
//Set up the hand without cards.
Blackjack::Hand h;
//Verify the hand without cards.
CPPUNIT_ASSERT( h.getNumCards() == 0 );
//Add a card.
h.addCard( Blackjack::Two, Blackjack::Clubs );
//Verify the values.
CPPUNIT_ASSERT( h.getNumCards() == 1 );
CPPUNIT_ASSERT( h.getCard(0).getRank() == Blackjack::Two );
CPPUNIT_ASSERT( h.getCard(0).getSuit() == Blackjack::Clubs );
CPPUNIT_ASSERT( h.getCard(0).getPoints() == 2 );
CPPUNIT_ASSERT( h.getCard(0).isAce() == false );
//Clear the hand.
h.clearCards();
//Verify the hand's cleared.
CPPUNIT_ASSERT( h.getNumCards() == 0 );
}
//Create the test suite using CPPUnit macros.
CPPUNIT_TEST_SUITE( CardTest );
CPPUNIT_TEST( testCreateHand );
CPPUNIT_TEST( testAddCardToHand );
CPPUNIT_TEST_SUITE_END( );
};
int main()
{
CPPUNIT_TEST_SUITE_REGISTRATION( CardTest );
CppUnit::TextUi::TestRunner runner;
CppUnit::TestFactoryRegistry ®istry = CppUnit::TestFactoryRegistry::getRegistry( );
runner.addTest( registry.makeTest( ) );
if ( runner.run( ) )
{//Runner had success.
return 0;
}
else
{//Runner failed.
return 1;
}
}
<commit_msg>Added a unit test to the Hand code.<commit_after>#include <cppunit/ui/text/TestRunner.h>
#include <cppunit/TestCaller.h>
#include <cppunit/TestCase.h>
#include <cppunit/extensions/HelperMacros.h>
#include <iostream>
#include <vector>
#include "Hand.h"
class CardTest : public CppUnit::TestCase
{
private:
public:
void testCreateHand()
{//Basic test of creating a hand.
//Set up the hand without cards.
Blackjack::Hand h;
//Verify the hand without cards.
CPPUNIT_ASSERT( h.getNumCards() == 0 );
//Add a card.
h.addCard( Blackjack::Two, Blackjack::Clubs );
//Verify the values.
CPPUNIT_ASSERT( h.getNumCards() == 1 );
CPPUNIT_ASSERT( h.getCard(0).getRank() == Blackjack::Two );
CPPUNIT_ASSERT( h.getCard(0).getSuit() == Blackjack::Clubs );
CPPUNIT_ASSERT( h.getCard(0).getPoints() == 2 );
CPPUNIT_ASSERT( h.getCard(0).isAce() == false );
}
void testChangeHand()
{//Basic test of creating a hand.
//Set up the hand without cards.
Blackjack::Hand h;
//Verify the hand without cards.
CPPUNIT_ASSERT( h.getNumCards() == 0 );
//Add a card.
h.addCard( Blackjack::Two, Blackjack::Clubs );
//Verify the values.
CPPUNIT_ASSERT( h.getNumCards() == 1 );
CPPUNIT_ASSERT( h.getCard(0).getRank() == Blackjack::Two );
CPPUNIT_ASSERT( h.getCard(0).getSuit() == Blackjack::Clubs );
CPPUNIT_ASSERT( h.getCard(0).getPoints() == 2 );
CPPUNIT_ASSERT( h.getCard(0).isAce() == false );
//Change a card.
h.getCard(0).setRank( Blackjack::Three );
h.getCard(0).setSuit( Blackjack::Diamonds );
//Verify the new values.
CPPUNIT_ASSERT( h.getNumCards() == 1 );
CPPUNIT_ASSERT( h.getCard(0).getRank() == Blackjack::Three );
CPPUNIT_ASSERT( h.getCard(0).getSuit() == Blackjack::Diamonds );
CPPUNIT_ASSERT( h.getCard(0).getPoints() == 3 );
CPPUNIT_ASSERT( h.getCard(0).isAce() == false );
}
void testAddCardToHand()
{//Basic test of creating a hand.
//Set up the hand without cards.
Blackjack::Hand h;
//Verify the hand without cards.
CPPUNIT_ASSERT( h.getNumCards() == 0 );
//Add a card.
h.addCard( Blackjack::Two, Blackjack::Clubs );
//Verify the values.
CPPUNIT_ASSERT( h.getNumCards() == 1 );
CPPUNIT_ASSERT( h.getCard(0).getRank() == Blackjack::Two );
CPPUNIT_ASSERT( h.getCard(0).getSuit() == Blackjack::Clubs );
CPPUNIT_ASSERT( h.getCard(0).getPoints() == 2 );
CPPUNIT_ASSERT( h.getCard(0).isAce() == false );
//Add another card.
h.addCard( Blackjack::Ace, Blackjack::Hearts );
//Verify the values.
CPPUNIT_ASSERT( h.getNumCards() == 2 );
CPPUNIT_ASSERT( h.getCard(1).getRank() == Blackjack::Ace );
CPPUNIT_ASSERT( h.getCard(1).getSuit() == Blackjack::Hearts );
CPPUNIT_ASSERT( h.getCard(1).getPoints() == 11 );
CPPUNIT_ASSERT( h.getCard(1).isAce() == true );
}
void testClearHand()
{//Basic test of creating a hand.
//Set up the hand without cards.
Blackjack::Hand h;
//Verify the hand without cards.
CPPUNIT_ASSERT( h.getNumCards() == 0 );
//Add a card.
h.addCard( Blackjack::Two, Blackjack::Clubs );
//Verify the values.
CPPUNIT_ASSERT( h.getNumCards() == 1 );
CPPUNIT_ASSERT( h.getCard(0).getRank() == Blackjack::Two );
CPPUNIT_ASSERT( h.getCard(0).getSuit() == Blackjack::Clubs );
CPPUNIT_ASSERT( h.getCard(0).getPoints() == 2 );
CPPUNIT_ASSERT( h.getCard(0).isAce() == false );
//Clear the hand.
h.clearCards();
//Verify the hand's cleared.
CPPUNIT_ASSERT( h.getNumCards() == 0 );
}
//Create the test suite using CPPUnit macros.
CPPUNIT_TEST_SUITE( CardTest );
CPPUNIT_TEST( testCreateHand );
CPPUNIT_TEST( testAddCardToHand );
CPPUNIT_TEST( testChangeHand );
CPPUNIT_TEST( testClearHand );
CPPUNIT_TEST_SUITE_END( );
};
int main()
{
CPPUNIT_TEST_SUITE_REGISTRATION( CardTest );
CppUnit::TextUi::TestRunner runner;
CppUnit::TestFactoryRegistry ®istry = CppUnit::TestFactoryRegistry::getRegistry( );
runner.addTest( registry.makeTest( ) );
if ( runner.run( ) )
{//Runner had success.
return 0;
}
else
{//Runner failed.
return 1;
}
}
<|endoftext|>
|
<commit_before>#include "polygon.h"
#include <algorithm>
fim::PolygonList fim::Polygon::convexDecomposition()
{
fim::PolygonList res;
fim::PolygonQueue processQueue;
processQueue.push(*this);
while(!processQueue.empty()) {
auto tmp = processQueue.front();
processQueue.pop();
int ccPoint = tmp.getConcavePoint();
if (ccPoint == -1) {
res.push_back(tmp);
} else {
auto twoPolygon = tmp.cutPolygon(ccPoint);
for (int i = 0; i < (int)twoPolygon.size(); i++) {
processQueue.push(twoPolygon[i]);
}
}
if (res.size() > 100 || processQueue.size() > 100) {
break;
}
}
return res;
}
int fim::Polygon::indexNormalize(int index)
{
int sz = (int)size();
return (index % sz + sz) % sz;
}
int fim::Polygon::insertPoint(const vec2 & p)
{
int ans = 0;
fim::vec2 lastVec;
fim::segment seg;
for (Polygon::iterator it = begin(); it != end(); ++it) {
if (it != begin()) {
seg = fim::segment(lastVec, *it);
}
if (seg.collidePoint(p)) {
ans = std::distance(begin(), insert(it, p));
break;
}
lastVec = *it;
}
if (ans == 0) insert(begin(), p);
return ans;
}
const fim::vec2 fim::Polygon::getPoint(int index)
{
index = indexNormalize(index);
return (*this)[index];
}
const fim::vec2 fim::Polygon::getVector(int index)
{
return getPoint(index + 1) - getPoint(index);
}
const fim::segment fim::Polygon::getSegment(int index)
{
return fim::segment(getPoint(index), getPoint(index + 1));
}
bool fim::Polygon::isConcavePoint(int index)
{
auto prev = getVector(index - 1);
auto cur = getVector(index);
double cp = prev.crossProduct(cur);
if (cp < 0) return true;
else return false;
}
int fim::Polygon::getConcavePoint()
{
int ans = -1;
int sz = (int)size();
for (int i = 0; i < sz; i++) {
if (isConcavePoint(i)) {
ans = i;
break;
}
}
return ans;
}
static fim::vec2 raySrc;
bool cmpDistanceToSrc(const fim::vec2 & a, const fim::vec2 & b)
{
return (a - raySrc).length() < (b - raySrc).length();
}
fim::Point2List fim::Polygon::collideRay(const fim::vec2 & src, const fim::vec2 & drct)
{
fim::Point2List res;
fim::Point2List uniqueRes;
for (int i = 0; i < (int)size(); i++) {
auto seg = getSegment(i);
fim::vec2 tmp;
if (seg.collideRay(tmp, src, drct)) {
res.push_back(tmp);
}
}
raySrc = src;
std::sort(res.begin(), res.end(), cmpDistanceToSrc);
for (int i = 0; i < (int)res.size(); i++) {
if (i == 0 || res[i] != res[i - 1]) {
uniqueRes.push_back(res[i]);
}
}
return uniqueRes;
}
fim::IndexList fim::Polygon::getVisiblePointIndex(int ccPoint)
{
fim::IndexList res;
auto left = getSegment(ccPoint);
auto right = getSegment(ccPoint - 1);
right.swapAB();
left.b = left.a - left.getVector();
right.b = right.a - right.getVector();
for (int i = 0; i < (int)size(); i++) {
if (i == ccPoint) continue;
auto p = getPoint(i);
if (left.leftOrRight(p) == 1
&& right.leftOrRight(p) == -1) {
auto pl = collideRay(getPoint(ccPoint), p - getPoint(ccPoint));
if (pl.size() == 0 || pl[0] == p)
{
res.push_back(i);
}
}
}
return res;
}
fim::PolygonList fim::Polygon::cutPolygon(int ccPoint, int anoPoint)
{
fim::PolygonList res;
fim::Polygon tmp;
int cur = anoPoint;
tmp.push_back(getPoint(ccPoint));
tmp.push_back(getPoint(anoPoint));
cur = indexNormalize(cur + 1);
while (cur != ccPoint) {
tmp.push_back(getPoint(cur));
cur = indexNormalize(cur + 1);
}
res.push_back(tmp);
tmp.clear();
cur = ccPoint;
tmp.push_back(getPoint(anoPoint));
tmp.push_back(getPoint(ccPoint));
cur = indexNormalize(cur + 1);
while (cur != anoPoint) {
tmp.push_back(getPoint(cur));
cur = indexNormalize(cur + 1);
}
res.push_back(tmp);
return res;
}
fim::PolygonList fim::Polygon::cutPolygon(int ccPoint)
{
fim::PolygonList res;
auto iList = getVisiblePointIndex(ccPoint);
if (!iList.empty()) {
return cutPolygon(ccPoint, iList[0]);
} else {
auto left = -getVector(ccPoint);
auto right = getVector(ccPoint - 1);
auto middleVec = (left.normalize() + right.normalize()) / 2.0;
auto pl = collideRay(getPoint(ccPoint), middleVec);
if (!pl.empty()) {
int loc = insertPoint(pl[0]);
if (loc <= ccPoint) {
ccPoint = indexNormalize(ccPoint + 1);
}
return cutPolygon(ccPoint, loc);
} else {
//TODO: debug output
}
}
return res;
}
<commit_msg>fix insertPoint<commit_after>#include "polygon.h"
#include <algorithm>
fim::PolygonList fim::Polygon::convexDecomposition()
{
fim::PolygonList res;
fim::PolygonQueue processQueue;
processQueue.push(*this);
while(!processQueue.empty()) {
auto tmp = processQueue.front();
processQueue.pop();
int ccPoint = tmp.getConcavePoint();
if (ccPoint == -1) {
res.push_back(tmp);
} else {
auto twoPolygon = tmp.cutPolygon(ccPoint);
for (int i = 0; i < (int)twoPolygon.size(); i++) {
processQueue.push(twoPolygon[i]);
}
}
if (res.size() > 100 || processQueue.size() > 100) {
break;
}
}
return res;
}
int fim::Polygon::indexNormalize(int index)
{
int sz = (int)size();
return (index % sz + sz) % sz;
}
int fim::Polygon::insertPoint(const vec2 & p)
{
int ans = 0;
fim::vec2 lastVec;
fim::segment seg;
for (Polygon::iterator it = begin(); it != end(); ++it) {
if (it != begin()) {
seg = fim::segment(lastVec, *it);
if (seg.collidePoint(p)) {
ans = std::distance(begin(), insert(it, p));
break;
}
}
lastVec = *it;
}
if (ans == 0) insert(begin(), p);
return ans;
}
const fim::vec2 fim::Polygon::getPoint(int index)
{
index = indexNormalize(index);
return (*this)[index];
}
const fim::vec2 fim::Polygon::getVector(int index)
{
return getPoint(index + 1) - getPoint(index);
}
const fim::segment fim::Polygon::getSegment(int index)
{
return fim::segment(getPoint(index), getPoint(index + 1));
}
bool fim::Polygon::isConcavePoint(int index)
{
auto prev = getVector(index - 1);
auto cur = getVector(index);
double cp = prev.crossProduct(cur);
if (cp < 0) return true;
else return false;
}
int fim::Polygon::getConcavePoint()
{
int ans = -1;
int sz = (int)size();
for (int i = 0; i < sz; i++) {
if (isConcavePoint(i)) {
ans = i;
break;
}
}
return ans;
}
static fim::vec2 raySrc;
bool cmpDistanceToSrc(const fim::vec2 & a, const fim::vec2 & b)
{
return (a - raySrc).length() < (b - raySrc).length();
}
fim::Point2List fim::Polygon::collideRay(const fim::vec2 & src, const fim::vec2 & drct)
{
fim::Point2List res;
fim::Point2List uniqueRes;
for (int i = 0; i < (int)size(); i++) {
auto seg = getSegment(i);
fim::vec2 tmp;
if (seg.collideRay(tmp, src, drct)) {
res.push_back(tmp);
}
}
raySrc = src;
std::sort(res.begin(), res.end(), cmpDistanceToSrc);
for (int i = 0; i < (int)res.size(); i++) {
if (i == 0 || res[i] != res[i - 1]) {
uniqueRes.push_back(res[i]);
}
}
return uniqueRes;
}
fim::IndexList fim::Polygon::getVisiblePointIndex(int ccPoint)
{
fim::IndexList res;
auto left = getSegment(ccPoint);
auto right = getSegment(ccPoint - 1);
right.swapAB();
left.b = left.a - left.getVector();
right.b = right.a - right.getVector();
for (int i = 0; i < (int)size(); i++) {
if (i == ccPoint) continue;
auto p = getPoint(i);
if (left.leftOrRight(p) == 1
&& right.leftOrRight(p) == -1) {
auto pl = collideRay(getPoint(ccPoint), p - getPoint(ccPoint));
if (pl.size() == 0 || pl[0] == p)
{
res.push_back(i);
}
}
}
return res;
}
fim::PolygonList fim::Polygon::cutPolygon(int ccPoint, int anoPoint)
{
fim::PolygonList res;
fim::Polygon tmp;
int cur = anoPoint;
tmp.push_back(getPoint(ccPoint));
tmp.push_back(getPoint(anoPoint));
cur = indexNormalize(cur + 1);
while (cur != ccPoint) {
tmp.push_back(getPoint(cur));
cur = indexNormalize(cur + 1);
}
res.push_back(tmp);
tmp.clear();
cur = ccPoint;
tmp.push_back(getPoint(anoPoint));
tmp.push_back(getPoint(ccPoint));
cur = indexNormalize(cur + 1);
while (cur != anoPoint) {
tmp.push_back(getPoint(cur));
cur = indexNormalize(cur + 1);
}
res.push_back(tmp);
return res;
}
fim::PolygonList fim::Polygon::cutPolygon(int ccPoint)
{
fim::PolygonList res;
auto iList = getVisiblePointIndex(ccPoint);
if (!iList.empty()) {
return cutPolygon(ccPoint, iList[0]);
} else {
auto left = -getVector(ccPoint);
auto right = getVector(ccPoint - 1);
auto middleVec = (left.normalize() + right.normalize()) / 2.0;
auto pl = collideRay(getPoint(ccPoint), middleVec);
if (!pl.empty()) {
int loc = insertPoint(pl[0]);
if (loc <= ccPoint) {
ccPoint = indexNormalize(ccPoint + 1);
}
return cutPolygon(ccPoint, loc);
} else {
//TODO: debug output
}
}
return res;
}
<|endoftext|>
|
<commit_before>#include "gtest/gtest.h"
#include "delaunay.h"
namespace {
// The fixture for testing class Foo.
class DelaunayTest : public ::testing::Test {
protected:
// You can remove any or all of the following functions if its body
// is empty.
DelaunayTest() {
// You can do set-up work for each test here.
}
virtual ~DelaunayTest() {
// You can do clean-up work that doesn't throw exceptions here.
}
// If the constructor and destructor are not enough for setting up
// and cleaning up each test, you can define the following methods:
virtual void SetUp() {
// Code here will be called immediately after the constructor (right
// before each test).
}
virtual void TearDown() {
// Code here will be called immediately after each test (right
// before the destructor).
}
// Objects declared here can be used by all tests in the test case for Foo.
};
TEST_F(DelaunayTest, DelaunayFloat) {
std::vector<Vector2<float> > points;
points.push_back(Vector2<float>(0.0f, 0.0f));
points.push_back(Vector2<float>(1.0f, 0.0f));
points.push_back(Vector2<float>(0.0f, 1.0f));
Delaunay<float> triangulation;
const std::vector<Triangle<float> > triangles = triangulation.triangulate(points);
EXPECT_EQ(1, triangles.size());
// const std::vector<Edge<float> > edges = triangulation.getEdges();
}
TEST_F(DelaunayTest, DelaunayDouble) {
std::vector<Vector2<double> > points;
points.push_back(Vector2<double>(0.0, 0.0));
points.push_back(Vector2<double>(1.0, 0.0));
points.push_back(Vector2<double>(0.0, 1.0));
Delaunay<double> triangulation;
const std::vector<Triangle<double> > triangles = triangulation.triangulate(points);
EXPECT_EQ(1, triangles.size());
// const std::vector<Edge<float> > edges = triangulation.getEdges();
}
} // namespace
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}<commit_msg>Add tests with 10000 points to see performance<commit_after>#include "gtest/gtest.h"
#include "delaunay.h"
namespace {
// The fixture for testing class Foo.
class DelaunayTest : public ::testing::Test {
protected:
// You can remove any or all of the following functions if its body
// is empty.
DelaunayTest() {
// You can do set-up work for each test here.
}
virtual ~DelaunayTest() {
// You can do clean-up work that doesn't throw exceptions here.
}
// If the constructor and destructor are not enough for setting up
// and cleaning up each test, you can define the following methods:
virtual void SetUp() {
// Code here will be called immediately after the constructor (right
// before each test).
}
virtual void TearDown() {
// Code here will be called immediately after each test (right
// before the destructor).
}
// Objects declared here can be used by all tests in the test case for Foo.
};
TEST_F(DelaunayTest, DelaunayFloat) {
std::vector<Vector2<float> > points;
points.push_back(Vector2<float>(0.0f, 0.0f));
points.push_back(Vector2<float>(1.0f, 0.0f));
points.push_back(Vector2<float>(0.0f, 1.0f));
Delaunay<float> triangulation;
const std::vector<Triangle<float> > triangles = triangulation.triangulate(points);
EXPECT_EQ(1, triangles.size());
// const std::vector<Edge<float> > edges = triangulation.getEdges();
}
TEST_F(DelaunayTest, DelaunayDouble) {
std::vector<Vector2<double> > points;
points.push_back(Vector2<double>(0.0, 0.0));
points.push_back(Vector2<double>(1.0, 0.0));
points.push_back(Vector2<double>(0.0, 1.0));
Delaunay<double> triangulation;
const std::vector<Triangle<double> > triangles = triangulation.triangulate(points);
EXPECT_EQ(1, triangles.size());
// const std::vector<Edge<double> > edges = triangulation.getEdges();
}
TEST_F(DelaunayTest, DelaunayDoubleDegenerated) {
std::vector<Vector2<double> > points;
points.push_back(Vector2<double>(0.0, 0.0));
points.push_back(Vector2<double>(0.0, 0.0));
points.push_back(Vector2<double>(1.0, 0.0));
points.push_back(Vector2<double>(0.0, 1.0));
Delaunay<double> triangulation;
const std::vector<Triangle<double> > triangles = triangulation.triangulate(points);
EXPECT_EQ(1, triangles.size());
// const std::vector<Edge<double> > edges = triangulation.getEdges();
}
TEST_F(DelaunayTest, DelaunayFloat10000) {
std::vector<Vector2<float> > points(1e4);
srand(666);
for (size_t i=0; i < 1e4; ++i)
{
double x = (double)rand() / (double)RAND_MAX;
double y = (double)rand() / (double)RAND_MAX;
points.at(i) = Vector2<double>(x, y);
}
EXPECT_EQ(10000, points.size());
Delaunay<double> triangulation;
const std::vector<Triangle<double> > triangles = triangulation.triangulate(points);
}
TEST_F(DelaunayTest, DelaunayDouble10000) {
std::vector<Vector2<double> > points(1e4);
srand(666);
for (size_t i=0; i < 1e4; ++i)
{
double x = (double)rand() / (double)RAND_MAX;
double y = (double)rand() / (double)RAND_MAX;
points.at(i) = Vector2<double>(x, y);
}
EXPECT_EQ(10000, points.size());
Delaunay<double> triangulation;
const std::vector<Triangle<double> > triangles = triangulation.triangulate(points);
}
} // namespace
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}<|endoftext|>
|
<commit_before>/*
This file is part of VROOM.
Copyright (c) 2015-2018, Julien Coupey.
All rights reserved (see LICENSE).
*/
#include <set>
#include "problems/vrptw/heuristics/solomon.h"
#include "utils/helpers.h"
tw_solution solomon(const input& input, INIT_T init, float lambda) {
tw_solution routes;
for (index_t i = 0; i < input._vehicles.size(); ++i) {
routes.emplace_back(input, i);
}
std::set<index_t> unassigned;
for (index_t j = 0; j < input._jobs.size(); ++j) {
unassigned.insert(j);
}
const auto& m = input.get_matrix();
// costs[j][v] is the cost of fetching job j in an empty route from
// vehicle v. regrets[j][v] is the minimum cost of fetching job j in
// an empty route from any vehicle after v.
std::vector<std::vector<cost_t>> costs(input._jobs.size(),
std::vector<cost_t>(
input._vehicles.size()));
std::vector<std::vector<cost_t>> regrets(input._jobs.size(),
std::vector<cost_t>(
input._vehicles.size()));
for (std::size_t j = 0; j < input._jobs.size(); ++j) {
index_t j_index = input._jobs[j].index();
regrets[j].back() = INFINITE_COST;
for (std::size_t v = input._vehicles.size() - 1; v > 0; --v) {
const auto& vehicle = input._vehicles[v];
cost_t current_cost = 0;
if (vehicle.has_start()) {
current_cost += m[vehicle.start.get().index()][j_index];
}
if (vehicle.has_end()) {
current_cost += m[j_index][vehicle.end.get().index()];
}
costs[j][v] = current_cost;
regrets[j][v - 1] = std::min(regrets[j][v], current_cost);
}
const auto& vehicle = input._vehicles[0];
cost_t current_cost = 0;
if (vehicle.has_start()) {
current_cost += m[vehicle.start.get().index()][j_index];
}
if (vehicle.has_end()) {
current_cost += m[j_index][vehicle.end.get().index()];
}
costs[j][0] = current_cost;
}
for (index_t v = 0; v < input._vehicles.size(); ++v) {
auto& tw_r = routes[v];
const auto& vehicle = input._vehicles[v];
amount_t route_amount(input.amount_size());
if (init != INIT_T::NONE) {
// Initialize current route with the "best" valid job that is
// closest for current vehicle than to any other remaining
// vehicle.
amount_t higher_amount(input.amount_size());
cost_t furthest_cost = 0;
duration_t earliest_deadline = std::numeric_limits<duration_t>::max();
index_t best_job_rank = 0;
for (const auto& job_rank : unassigned) {
if (!input.vehicle_ok_with_job(v, job_rank) or
!(input._jobs[job_rank].amount <= vehicle.capacity)) {
continue;
}
auto current_cost =
addition_cost(input, m, job_rank, vehicle, tw_r.route, 0);
if (regrets[job_rank][v] < current_cost) {
continue;
}
if (init == INIT_T::HIGHER_AMOUNT and
higher_amount << input._jobs[job_rank].amount and
tw_r.is_valid_addition_for_tw(job_rank, 0)) {
higher_amount = input._jobs[job_rank].amount;
best_job_rank = job_rank;
}
if (init == INIT_T::EARLIEST_DEADLINE) {
duration_t current_deadline = input._jobs[job_rank].tws.back().end;
if (current_deadline < earliest_deadline and
tw_r.is_valid_addition_for_tw(job_rank, 0)) {
earliest_deadline = current_deadline;
best_job_rank = job_rank;
}
}
if (init == INIT_T::FURTHEST and furthest_cost < current_cost and
tw_r.is_valid_addition_for_tw(job_rank, 0)) {
furthest_cost = current_cost;
best_job_rank = job_rank;
}
}
if ((init == INIT_T::HIGHER_AMOUNT and route_amount << higher_amount) or
(init == INIT_T::EARLIEST_DEADLINE and
earliest_deadline < std::numeric_limits<duration_t>::max()) or
(init == INIT_T::FURTHEST and furthest_cost > 0)) {
tw_r.add(best_job_rank, 0);
route_amount += input._jobs[best_job_rank].amount;
unassigned.erase(best_job_rank);
}
}
bool keep_going = true;
while (keep_going) {
keep_going = false;
float best_cost = std::numeric_limits<float>::max();
index_t best_job_rank = 0;
index_t best_r = 0;
for (const auto& job_rank : unassigned) {
if (!input.vehicle_ok_with_job(v, job_rank) or
!(route_amount + input._jobs[job_rank].amount <=
vehicle.capacity)) {
continue;
}
for (index_t r = 0; r <= tw_r.route.size(); ++r) {
float current_add =
addition_cost(input, m, job_rank, vehicle, tw_r.route, r);
float current_cost =
current_add - lambda * static_cast<float>(regrets[job_rank][v]);
if (current_cost < best_cost and
tw_r.is_valid_addition_for_tw(job_rank, r)) {
best_cost = current_cost;
best_job_rank = job_rank;
best_r = r;
}
}
}
if (best_cost < std::numeric_limits<float>::max()) {
tw_r.add(best_job_rank, best_r);
route_amount += input._jobs[best_job_rank].amount;
unassigned.erase(best_job_rank);
keep_going = true;
}
}
}
return routes;
}
<commit_msg>Advance TW check in Solomon job seeding.<commit_after>/*
This file is part of VROOM.
Copyright (c) 2015-2018, Julien Coupey.
All rights reserved (see LICENSE).
*/
#include <set>
#include "problems/vrptw/heuristics/solomon.h"
#include "utils/helpers.h"
tw_solution solomon(const input& input, INIT_T init, float lambda) {
tw_solution routes;
for (index_t i = 0; i < input._vehicles.size(); ++i) {
routes.emplace_back(input, i);
}
std::set<index_t> unassigned;
for (index_t j = 0; j < input._jobs.size(); ++j) {
unassigned.insert(j);
}
const auto& m = input.get_matrix();
// costs[j][v] is the cost of fetching job j in an empty route from
// vehicle v. regrets[j][v] is the minimum cost of fetching job j in
// an empty route from any vehicle after v.
std::vector<std::vector<cost_t>> costs(input._jobs.size(),
std::vector<cost_t>(
input._vehicles.size()));
std::vector<std::vector<cost_t>> regrets(input._jobs.size(),
std::vector<cost_t>(
input._vehicles.size()));
for (std::size_t j = 0; j < input._jobs.size(); ++j) {
index_t j_index = input._jobs[j].index();
regrets[j].back() = INFINITE_COST;
for (std::size_t v = input._vehicles.size() - 1; v > 0; --v) {
const auto& vehicle = input._vehicles[v];
cost_t current_cost = 0;
if (vehicle.has_start()) {
current_cost += m[vehicle.start.get().index()][j_index];
}
if (vehicle.has_end()) {
current_cost += m[j_index][vehicle.end.get().index()];
}
costs[j][v] = current_cost;
regrets[j][v - 1] = std::min(regrets[j][v], current_cost);
}
const auto& vehicle = input._vehicles[0];
cost_t current_cost = 0;
if (vehicle.has_start()) {
current_cost += m[vehicle.start.get().index()][j_index];
}
if (vehicle.has_end()) {
current_cost += m[j_index][vehicle.end.get().index()];
}
costs[j][0] = current_cost;
}
for (index_t v = 0; v < input._vehicles.size(); ++v) {
auto& tw_r = routes[v];
const auto& vehicle = input._vehicles[v];
amount_t route_amount(input.amount_size());
if (init != INIT_T::NONE) {
// Initialize current route with the "best" valid job that is
// closest for current vehicle than to any other remaining
// vehicle.
amount_t higher_amount(input.amount_size());
cost_t furthest_cost = 0;
duration_t earliest_deadline = std::numeric_limits<duration_t>::max();
index_t best_job_rank = 0;
for (const auto& job_rank : unassigned) {
if (!input.vehicle_ok_with_job(v, job_rank) or
!(input._jobs[job_rank].amount <= vehicle.capacity) or
!tw_r.is_valid_addition_for_tw(job_rank, 0)) {
continue;
}
auto current_cost =
addition_cost(input, m, job_rank, vehicle, tw_r.route, 0);
if (regrets[job_rank][v] < current_cost) {
continue;
}
if (init == INIT_T::HIGHER_AMOUNT and
higher_amount << input._jobs[job_rank].amount) {
higher_amount = input._jobs[job_rank].amount;
best_job_rank = job_rank;
}
if (init == INIT_T::EARLIEST_DEADLINE) {
duration_t current_deadline = input._jobs[job_rank].tws.back().end;
if (current_deadline < earliest_deadline) {
earliest_deadline = current_deadline;
best_job_rank = job_rank;
}
}
if (init == INIT_T::FURTHEST and furthest_cost < current_cost) {
furthest_cost = current_cost;
best_job_rank = job_rank;
}
}
if ((init == INIT_T::HIGHER_AMOUNT and route_amount << higher_amount) or
(init == INIT_T::EARLIEST_DEADLINE and
earliest_deadline < std::numeric_limits<duration_t>::max()) or
(init == INIT_T::FURTHEST and furthest_cost > 0)) {
tw_r.add(best_job_rank, 0);
route_amount += input._jobs[best_job_rank].amount;
unassigned.erase(best_job_rank);
}
}
bool keep_going = true;
while (keep_going) {
keep_going = false;
float best_cost = std::numeric_limits<float>::max();
index_t best_job_rank = 0;
index_t best_r = 0;
for (const auto& job_rank : unassigned) {
if (!input.vehicle_ok_with_job(v, job_rank) or
!(route_amount + input._jobs[job_rank].amount <=
vehicle.capacity)) {
continue;
}
for (index_t r = 0; r <= tw_r.route.size(); ++r) {
float current_add =
addition_cost(input, m, job_rank, vehicle, tw_r.route, r);
float current_cost =
current_add - lambda * static_cast<float>(regrets[job_rank][v]);
if (current_cost < best_cost and
tw_r.is_valid_addition_for_tw(job_rank, r)) {
best_cost = current_cost;
best_job_rank = job_rank;
best_r = r;
}
}
}
if (best_cost < std::numeric_limits<float>::max()) {
tw_r.add(best_job_rank, best_r);
route_amount += input._jobs[best_job_rank].amount;
unassigned.erase(best_job_rank);
keep_going = true;
}
}
}
return routes;
}
<|endoftext|>
|
<commit_before>/*
* item grouping implementation
*/
#include <string>
#include <sys/uio.h>
#include "node.h"
#include "config.h"
#include "message.h"
#include "convert.h"
#include "array.h"
#include "layout.h"
#include "object.h"
__MPT_NAMESPACE_BEGIN
template <> int typeinfo<Group *>::id()
{
static int id = 0;
if (!id && (id = mpt_valtype_interface_new("group")) < 0) {
id = mpt_valtype_interface_new(0);
}
return id;
}
// object interface for group
int Group::property(struct property *pr) const
{
if (!pr) {
return typeinfo<Group *>::id();
}
if (!pr->name || *pr->name) {
return BadArgument;
}
pr->name = "group";
pr->desc = "mpt item group";
pr->val.fmt = 0;
pr->val.ptr = 0;
return 0;
}
int Group::setProperty(const char *, const metatype *)
{
return BadOperation;
}
// generic item group
size_t Group::clear(const reference *)
{ return 0; }
Item<metatype> *Group::append(metatype *)
{ return 0; }
const Item<metatype> *Group::item(size_t) const
{ return 0; }
bool Group::bind(const Relation &, logger *)
{ return true; }
bool Group::addItems(node *head, const Relation *relation, logger *out)
{
const char _func[] = "mpt::Group::addItems";
for (; head; head = head->next) {
metatype *from = head->_meta;
if (from && from->addref()) {
Reference<metatype> m;
m.setPointer(from);
Item<metatype> *it;
if ((it = append(from))) {
m.detach();
it->setName(head->ident.name());
}
else if (out) {
out->message(_func, out->Warning, "%s %p: %s",
MPT_tr("group"), this, MPT_tr("failed to add object"));
}
continue;
}
// name is property
const char *name;
if (!(name = mpt_node_ident(head))) {
if (out) {
out->message(_func, out->Error, "%s %p: %s",
MPT_tr("node"), head, MPT_tr("bad element name"));
}
return false;
}
// set property
value val;
if (from && (val.ptr = mpt_meta_data(from))) {
if (set(name, val, out)) {
continue;
}
continue;
}
// get item type
const char *start, *pos;
size_t len;
start = pos = name;
name = mpt_convert_key(&pos, 0, &len);
if (!name || name != start || !*name) {
if (out) {
out->message(_func, out->Warning, "%s: %s",
MPT_tr("bad element name"), start);
}
continue;
}
// create item
if (!(from = create(name, len))) {
if (out) {
out->message(_func, out->Warning, "%s: %s",
MPT_tr("invalid item type"), std::string(name, len).c_str());
}
continue;
}
// get item name
name = mpt_convert_key(&pos, ":", &len);
if (!name || !len) {
if (out) {
out->message(_func, out->Warning, "%s",
MPT_tr("empty item name"));
}
from->unref();
continue;
}
// name conflict on same level
if (GroupRelation(*this).find(from->type(), name, len)) {
if (out) {
out->message(_func, out->Warning, "%s: %s",
MPT_tr("conflicting item name"), std::string(name, len).c_str());
}
from->unref();
continue;
}
const char *ident = name;
int ilen = len;
// find dependant items
while ((name = mpt_convert_key(&pos, 0, &len))) {
metatype *curr;
if (relation) curr = relation->find(from->type(), name, len);
else curr = GroupRelation(*this).find(from->type(), name, len);
object *obj, *src;
if ((src = curr->cast<object>()) && (obj = from->cast<object>())) {
obj->setProperties(*src, out);
continue;
}
from->unref();
if (out) {
out->message(_func, out->Error, "%s: %s: %s",
MPT_tr("unable to get inheritance"), head->ident.name(), std::string(name, len).c_str());
}
return false;
}
// add item to group
Item<metatype> *ni = append(from);
if (!ni) {
from->unref();
if (out) {
out->message(_func, out->Error, "%s: %s",
MPT_tr("unable add item"), std::string(ident, ilen).c_str());
}
continue;
}
ni->setName(ident, ilen);
// set properties and subitems
if (!head->children) continue;
// process child items
Group *ig;
if ((ig = from->cast<Group>())) {
if (!relation) {
if (!(ig->addItems(head->children, relation, out))) {
return false;
}
continue;
}
GroupRelation rel(*ig, relation);
if (!(ig->addItems(head->children, &rel, out))) {
return false;
}
continue;
}
object *obj;
if (!(obj = from->cast<object>())) {
if (out && head->children) {
out->message(_func, out->Warning, "%s (%p): %s",
name, from, MPT_tr("element not an object"));
}
continue;
}
// load item properties
for (node *sub = head->children; sub; sub = sub->next) {
metatype *mt;
const char *data;
if (!(mt = sub->_meta)) {
continue;
}
// skip invalid name
if (!(name = mpt_node_ident(sub)) || !*name) {
continue;
}
// try value conversion
value val;
if (mt->conv(value::Type, &val) >= 0) {
if (obj->set(name, val, out)) {
continue;
}
}
if (mt->conv('s', &data) >= 0) {
if (obj->set(name, data, out)) {
continue;
}
}
if (out) {
out->message(_func, out->Warning, "%s: %s: %s",
MPT_tr("bad value type"), ni->name(), name);
}
}
}
return true;
}
metatype *Group::create(const char *type, int nl)
{
if (!type || !nl) {
return 0;
}
if (nl < 0) {
nl = strlen(type);
}
if (nl == 4 && !memcmp("line", type, nl)) {
return new Reference<Line>::instance;
}
if (nl == 4 && !memcmp("text", type, nl)) {
return new Reference<Text>::instance;
}
if (nl == 5 && !memcmp("world", type, nl)) {
return new Reference<World>::instance;
}
if (nl == 5 && !memcmp("graph", type, nl)) {
return new Reference<Graph>::instance;
}
if (nl == 4 && !memcmp("axis", type, nl)) {
return new Reference<Axis>::instance;
}
class TypedAxis : public Reference<Axis>::instance
{
public:
TypedAxis(int type)
{ format = type & 0x3; }
};
if (nl == 5 && !memcmp("xaxis", type, nl)) {
return new TypedAxis(AxisStyleX);
}
if (nl == 5 && !memcmp("yaxis", type, nl)) {
return new TypedAxis(AxisStyleY);
}
if (nl == 5 && !memcmp("zaxis", type, nl)) {
return new TypedAxis(AxisStyleZ);
}
return 0;
}
// group storing elements in RefArray
Collection::~Collection()
{ }
void Collection::unref()
{
delete this;
}
int Collection::conv(int type, void *ptr) const
{
int me = typeinfo<Group *>::id();
if (me < 0) {
me = object::Type;
}
if (!type) {
static const char fmt[] = { array::Type };
if (ptr) *static_cast<const char **>(ptr) = fmt;
return me;
}
if (type == metatype::Type) {
if (ptr) *static_cast<const metatype **>(ptr) = this;
return me;
}
if (type == object::Type) {
if (ptr) *static_cast<const object **>(ptr) = this;
return me;
}
if (type == me) {
if (ptr) *static_cast<const Group **>(ptr) = this;
return array::Type;
}
return BadType;
}
Collection *Collection::clone() const
{
Collection *copy = new Collection;
copy->_items = _items;
return copy;
}
const Item<metatype> *Collection::item(size_t pos) const
{
return _items.get(pos);
}
Item<metatype> *Collection::append(metatype *mt)
{
return _items.append(mt, 0);
}
size_t Collection::clear(const reference *ref)
{
long remove = 0;
if (!ref) {
remove = _items.length();
_items = ItemArray<metatype>();
return remove ? true : false;
}
long empty = 0;
for (auto &it : _items) {
reference *curr = it.pointer();
if (!curr) { ++empty; continue; }
if (curr != ref) continue;
it.setPointer(nullptr);
++remove;
}
if ((remove + empty) > _items.length()/2) {
_items.compact();
}
return remove;
}
bool Collection::bind(const Relation &from, logger *out)
{
for (auto &it : _items) {
metatype *curr;
Group *g;
if (!(curr = it.pointer()) || !(g = curr->cast<Group>())) {
continue;
}
if (!g->bind(GroupRelation(*g, &from), out)) {
return false;
}
}
return true;
}
// Relation search operations
metatype *GroupRelation::find(int type, const char *name, int nlen) const
{
const Item<metatype> *c;
const char *sep;
if (nlen < 0) nlen = name ? strlen(name) : 0;
if (_sep && (sep = (char *) memchr(name, _sep, nlen))) {
size_t plen = sep - name;
for (int i = 0; (c = _curr.item(i)); ++i) {
metatype *m = c->pointer();
if (!m || !c->equal(name, plen)) continue;
const Group *g;
if (!(g = m->cast<Group>())) continue;
if ((m = GroupRelation(*g, this).find(type, sep+1, nlen-plen-1))) {
return m;
}
}
}
else {
for (int i = 0; (c = _curr.item(i)); ++i) {
metatype *m = c->pointer();
if (!m || (type && m->type() != type)) continue;
if (!c->equal(name, nlen)) continue;
return m;
}
}
return _parent ? _parent->find(type, name, nlen) : 0;
}
metatype *NodeRelation::find(int type, const char *name, int nlen) const
{
if (!_curr) return 0;
if (nlen < 0) nlen = name ? strlen(name) : 0;
for (const node *c = _curr->children; c; c = c->next) {
metatype *m;
if (!(m = c->_meta) || !c->ident.equal(name, nlen)) continue;
if (type && m->type() != type) continue;
return m;
}
return _parent ? _parent->find(type, name, nlen) : 0;
}
__MPT_NAMESPACE_END
<commit_msg>extend matching for metatype lookup<commit_after>/*
* item grouping implementation
*/
#include <string>
#include <sys/uio.h>
#include "node.h"
#include "config.h"
#include "message.h"
#include "convert.h"
#include "array.h"
#include "layout.h"
#include "object.h"
__MPT_NAMESPACE_BEGIN
template <> int typeinfo<Group *>::id()
{
static int id = 0;
if (!id && (id = mpt_valtype_interface_new("group")) < 0) {
id = mpt_valtype_interface_new(0);
}
return id;
}
// object interface for group
int Group::property(struct property *pr) const
{
if (!pr) {
return typeinfo<Group *>::id();
}
if (!pr->name || *pr->name) {
return BadArgument;
}
pr->name = "group";
pr->desc = "mpt item group";
pr->val.fmt = 0;
pr->val.ptr = 0;
return 0;
}
int Group::setProperty(const char *, const metatype *)
{
return BadOperation;
}
// generic item group
size_t Group::clear(const reference *)
{ return 0; }
Item<metatype> *Group::append(metatype *)
{ return 0; }
const Item<metatype> *Group::item(size_t) const
{ return 0; }
bool Group::bind(const Relation &, logger *)
{ return true; }
bool Group::addItems(node *head, const Relation *relation, logger *out)
{
const char _func[] = "mpt::Group::addItems";
for (; head; head = head->next) {
metatype *from = head->_meta;
if (from && from->addref()) {
Reference<metatype> m;
m.setPointer(from);
Item<metatype> *it;
if ((it = append(from))) {
m.detach();
it->setName(head->ident.name());
}
else if (out) {
out->message(_func, out->Warning, "%s %p: %s",
MPT_tr("group"), this, MPT_tr("failed to add object"));
}
continue;
}
// name is property
const char *name;
if (!(name = mpt_node_ident(head))) {
if (out) {
out->message(_func, out->Error, "%s %p: %s",
MPT_tr("node"), head, MPT_tr("bad element name"));
}
return false;
}
// set property
value val;
if (from && (val.ptr = mpt_meta_data(from))) {
if (set(name, val, out)) {
continue;
}
continue;
}
// get item type
const char *start, *pos;
size_t len;
start = pos = name;
name = mpt_convert_key(&pos, 0, &len);
if (!name || name != start || !*name) {
if (out) {
out->message(_func, out->Warning, "%s: %s",
MPT_tr("bad element name"), start);
}
continue;
}
// create item
if (!(from = create(name, len))) {
if (out) {
out->message(_func, out->Warning, "%s: %s",
MPT_tr("invalid item type"), std::string(name, len).c_str());
}
continue;
}
// get item name
name = mpt_convert_key(&pos, ":", &len);
if (!name || !len) {
if (out) {
out->message(_func, out->Warning, "%s",
MPT_tr("empty item name"));
}
from->unref();
continue;
}
// name conflict on same level
if (GroupRelation(*this).find(from->type(), name, len)) {
if (out) {
out->message(_func, out->Warning, "%s: %s",
MPT_tr("conflicting item name"), std::string(name, len).c_str());
}
from->unref();
continue;
}
const char *ident = name;
int ilen = len;
// find dependant items
while ((name = mpt_convert_key(&pos, 0, &len))) {
metatype *curr;
if (relation) curr = relation->find(from->type(), name, len);
else curr = GroupRelation(*this).find(from->type(), name, len);
if (!curr) {
if (out) {
out->message(_func, out->Error, "%s: '%s': %s",
MPT_tr("unable to get parent"), head->ident.name(), std::string(name, len).c_str());
}
from->unref();
return false;
}
object *obj, *src;
if ((src = curr->cast<object>()) && (obj = from->cast<object>())) {
obj->setProperties(*src, out);
continue;
}
from->unref();
if (out) {
out->message(_func, out->Error, "%s: '%s': %s",
MPT_tr("unable to get inheritance"), head->ident.name(), std::string(name, len).c_str());
}
return false;
}
// add item to group
Item<metatype> *ni = append(from);
if (!ni) {
from->unref();
if (out) {
out->message(_func, out->Error, "%s: %s",
MPT_tr("unable add item"), std::string(ident, ilen).c_str());
}
continue;
}
ni->setName(ident, ilen);
// set properties and subitems
if (!head->children) continue;
// process child items
Group *ig;
if ((ig = from->cast<Group>())) {
if (!relation) {
if (!(ig->addItems(head->children, relation, out))) {
return false;
}
continue;
}
GroupRelation rel(*ig, relation);
if (!(ig->addItems(head->children, &rel, out))) {
return false;
}
continue;
}
object *obj;
if (!(obj = from->cast<object>())) {
if (out && head->children) {
out->message(_func, out->Warning, "%s (%p): %s",
name, from, MPT_tr("element not an object"));
}
continue;
}
// load item properties
for (node *sub = head->children; sub; sub = sub->next) {
metatype *mt;
const char *data;
if (!(mt = sub->_meta)) {
continue;
}
// skip invalid name
if (!(name = mpt_node_ident(sub)) || !*name) {
continue;
}
// try value conversion
value val;
if (mt->conv(value::Type, &val) >= 0) {
if (obj->set(name, val, out)) {
continue;
}
}
if (mt->conv('s', &data) >= 0) {
if (obj->set(name, data, out)) {
continue;
}
}
if (out) {
out->message(_func, out->Warning, "%s: %s: %s",
MPT_tr("bad value type"), ni->name(), name);
}
}
}
return true;
}
metatype *Group::create(const char *type, int nl)
{
if (!type || !nl) {
return 0;
}
if (nl < 0) {
nl = strlen(type);
}
if (nl == 4 && !memcmp("line", type, nl)) {
return new Reference<Line>::instance;
}
if (nl == 4 && !memcmp("text", type, nl)) {
return new Reference<Text>::instance;
}
if (nl == 5 && !memcmp("world", type, nl)) {
return new Reference<World>::instance;
}
if (nl == 5 && !memcmp("graph", type, nl)) {
return new Reference<Graph>::instance;
}
if (nl == 4 && !memcmp("axis", type, nl)) {
return new Reference<Axis>::instance;
}
class TypedAxis : public Reference<Axis>::instance
{
public:
TypedAxis(int type)
{ format = type & 0x3; }
};
if (nl == 5 && !memcmp("xaxis", type, nl)) {
return new TypedAxis(AxisStyleX);
}
if (nl == 5 && !memcmp("yaxis", type, nl)) {
return new TypedAxis(AxisStyleY);
}
if (nl == 5 && !memcmp("zaxis", type, nl)) {
return new TypedAxis(AxisStyleZ);
}
return 0;
}
// group storing elements in RefArray
Collection::~Collection()
{ }
void Collection::unref()
{
delete this;
}
int Collection::conv(int type, void *ptr) const
{
int me = typeinfo<Group *>::id();
if (me < 0) {
me = object::Type;
}
if (!type) {
static const char fmt[] = { array::Type };
if (ptr) *static_cast<const char **>(ptr) = fmt;
return me;
}
if (type == metatype::Type) {
if (ptr) *static_cast<const metatype **>(ptr) = this;
return me;
}
if (type == object::Type) {
if (ptr) *static_cast<const object **>(ptr) = this;
return me;
}
if (type == me) {
if (ptr) *static_cast<const Group **>(ptr) = this;
return array::Type;
}
return BadType;
}
Collection *Collection::clone() const
{
Collection *copy = new Collection;
copy->_items = _items;
return copy;
}
const Item<metatype> *Collection::item(size_t pos) const
{
return _items.get(pos);
}
Item<metatype> *Collection::append(metatype *mt)
{
return _items.append(mt, 0);
}
size_t Collection::clear(const reference *ref)
{
long remove = 0;
if (!ref) {
remove = _items.length();
_items = ItemArray<metatype>();
return remove ? true : false;
}
long empty = 0;
for (auto &it : _items) {
reference *curr = it.pointer();
if (!curr) { ++empty; continue; }
if (curr != ref) continue;
it.setPointer(nullptr);
++remove;
}
if ((remove + empty) > _items.length()/2) {
_items.compact();
}
return remove;
}
bool Collection::bind(const Relation &from, logger *out)
{
for (auto &it : _items) {
metatype *curr;
Group *g;
if (!(curr = it.pointer()) || !(g = curr->cast<Group>())) {
continue;
}
if (!g->bind(GroupRelation(*g, &from), out)) {
return false;
}
}
return true;
}
// Relation search operations
metatype *GroupRelation::find(int type, const char *name, int nlen) const
{
const Item<metatype> *c;
const char *sep;
if (nlen < 0) nlen = name ? strlen(name) : 0;
if (_sep && name && (sep = (char *) memchr(name, _sep, nlen))) {
size_t plen = sep - name;
for (int i = 0; (c = _curr.item(i)); ++i) {
metatype *m = c->pointer();
if (!m || !c->equal(name, plen)) {
continue;
}
const Group *g;
if (!(g = m->cast<Group>())) {
continue;
}
if ((m = GroupRelation(*g, this).find(type, sep + 1, nlen - plen - 1))) {
return m;
}
}
}
else {
for (int i = 0; (c = _curr.item(i)); ++i) {
metatype *m;
if (!(m = c->pointer())) {
continue;
}
if (name && !c->equal(name, nlen)) {
continue;
}
if (type < 0) {
return m;
}
int val;
if ((val = m->type()) < 0) {
continue;
}
if (type) {
if (type && type != val && (val = m->conv(type, 0)) < 0) {
continue;
}
}
else if (!val) {
continue;
}
return m;
}
}
return _parent ? _parent->find(type, name, nlen) : 0;
}
metatype *NodeRelation::find(int type, const char *name, int nlen) const
{
if (!_curr) return 0;
if (nlen < 0) nlen = name ? strlen(name) : 0;
for (const node *c = _curr->children; c; c = c->next) {
metatype *m;
if (!(m = c->_meta)) {
continue;
}
if (name && !c->ident.equal(name, nlen)) {
continue;
}
if (type < 0) {
return m;
}
int val;
if ((val = m->type()) < 0) {
continue;
}
if (type) {
if (type && type != val && (val = m->conv(type, 0)) < 0) {
continue;
}
}
else if (!val) {
continue;
}
return m;
}
return _parent ? _parent->find(type, name, nlen) : 0;
}
__MPT_NAMESPACE_END
<|endoftext|>
|
<commit_before>/* This file is part of the Vc library.
Copyright (C) 2009-2012 Matthias Kretz <[email protected]>
Vc is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3 of
the License, or (at your option) any later version.
Vc 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 Vc. If not, see <http://www.gnu.org/licenses/>.
*/
#include <Vc/Vc>
#include "unittest.h"
#include <iostream>
#include "vectormemoryhelper.h"
#include "../cpuid.h"
using namespace Vc;
template<typename Vec> void testSort()
{
typedef typename Vec::EntryType EntryType;
typedef typename Vec::IndexType IndexType;
typename Vec::Memory _a;
const IndexType _ref(IndexesFromZero);
Vec ref(_ref);
Vec a;
int maxPerm = 1;
for (int x = Vec::Size; x > 0; --x) {
maxPerm *= x;
}
for (int perm = 0; perm < maxPerm; ++perm) {
int rest = perm;
for (int i = 0; i < Vec::Size; ++i) {
_a[i] = 0;
for (int j = 0; j < i; ++j) {
if (_a[i] == _a[j]) {
++_a[i];
j = -1;
}
}
_a[i] += rest % (Vec::Size - i);
rest /= (Vec::Size - i);
for (int j = 0; j < i; ++j) {
if (_a[i] == _a[j]) {
++_a[i];
j = -1;
}
}
}
a.load(_a);
//std::cout << a << a.sorted() << std::endl;
COMPARE(ref, a.sorted()) << ", a: " << a;
}
}
template<typename T, typename Mem> struct Foo
{
Foo() : i(0) {}
void reset() { i = 0; }
void operator()(T v) { d[i++] = v; }
Mem d;
int i;
};
template<typename V> void testCall()
{
typedef typename V::EntryType T;
typedef typename V::IndexType I;
typedef typename V::Mask M;
typedef typename I::Mask MI;
const I _indexes(IndexesFromZero);
const MI _odd = (_indexes & I(One)) > 0;
const M odd(_odd);
V a(_indexes);
Foo<T, typename V::Memory> f;
a.callWithValuesSorted(f);
V b(f.d);
COMPARE(b, a);
f.reset();
a(odd) -= 1;
a.callWithValuesSorted(f);
V c(f.d);
for (int i = 0; i < V::Size / 2; ++i) {
COMPARE(a[i * 2], c[i]);
}
for (int i = V::Size / 2; i < V::Size; ++i) {
COMPARE(b[i], c[i]);
}
}
template<typename V> void testForeachBit()
{
typedef typename V::EntryType T;
typedef typename V::IndexType I;
typedef typename V::Mask M;
typedef typename I::Mask MI;
const I indexes(IndexesFromZero);
for_all_masks(V, mask) {
V tmp = V::Zero();
foreach_bit(int j, mask) {
tmp[j] = T(1);
}
COMPARE(tmp == V::One(), mask);
int count = 0;
foreach_bit(int j, mask) {
++count;
if (j >= 0) {
continue;
}
}
COMPARE(count, mask.count());
count = 0;
foreach_bit(int j, mask) {
if (j >= 0) {
break;
}
++count;
}
COMPARE(count, 0);
}
}
template<typename V> void copySign()
{
typedef typename V::EntryType T;
V v(One);
V positive(One);
V negative = -positive;
COMPARE(v, v.copySign(positive));
COMPARE(-v, v.copySign(negative));
}
#ifdef VC_MSVC
void bzero(void *p, size_t n) { memset(p, 0, n); }
#else
#include <strings.h>
#endif
template<typename V> void Random()
{
typedef typename V::EntryType T;
enum {
NBits = 3,
NBins = 1 << NBits, // short int
TotalBits = sizeof(T) * 8, // 16 32
RightShift = TotalBits - NBits, // 13 29
NHistograms = TotalBits - NBits + 1, // 14 30
LeftShift = (RightShift + 1) / NHistograms,// 1 1
Mean = 135791,
MinGood = Mean - Mean/10,
MaxGood = Mean + Mean/10
};
const V mask((1 << NBits) - 1);
int histogram[NHistograms][NBins];
bzero(&histogram[0][0], sizeof(histogram));
for (size_t i = 0; i < NBins * Mean / V::Size; ++i) {
const V rand = V::Random();
for (size_t hist = 0; hist < NHistograms; ++hist) {
const V bin = ((rand << (hist * LeftShift)) >> RightShift) & mask;
for (size_t k = 0; k < V::Size; ++k) {
++histogram[hist][bin[k]];
}
}
}
//#define PRINT_RANDOM_HISTOGRAM
#ifdef PRINT_RANDOM_HISTOGRAM
for (size_t hist = 0; hist < NHistograms; ++hist) {
std::cout << "histogram[" << std::setw(2) << hist << "]: ";
for (size_t bin = 0; bin < NBins; ++bin) {
std::cout << std::setw(3) << (histogram[hist][bin] - Mean) * 1000 / Mean << "|";
}
std::cout << std::endl;
}
#endif
for (size_t hist = 0; hist < NHistograms; ++hist) {
for (size_t bin = 0; bin < NBins; ++bin) {
VERIFY(histogram[hist][bin] > MinGood)
<< " bin = " << bin << " is " << histogram[0][bin];
VERIFY(histogram[hist][bin] < MaxGood)
<< " bin = " << bin << " is " << histogram[0][bin];
}
}
}
template<typename V, typename I> void FloatRandom()
{
typedef typename V::EntryType T;
enum {
NBins = 64,
NHistograms = 1,
Mean = 135791,
MinGood = Mean - Mean/10,
MaxGood = Mean + Mean/10
};
int histogram[NHistograms][NBins];
bzero(&histogram[0][0], sizeof(histogram));
for (size_t i = 0; i < NBins * Mean / V::Size; ++i) {
const V rand = V::Random();
const I bin = static_cast<I>(rand * T(NBins));
for (size_t k = 0; k < V::Size; ++k) {
++histogram[0][bin[k]];
}
}
#ifdef PRINT_RANDOM_HISTOGRAM
for (size_t hist = 0; hist < NHistograms; ++hist) {
std::cout << "histogram[" << std::setw(2) << hist << "]: ";
for (size_t bin = 0; bin < NBins; ++bin) {
std::cout << std::setw(3) << (histogram[hist][bin] - Mean) * 1000 / Mean << "|";
}
std::cout << std::endl;
}
#endif
for (size_t hist = 0; hist < NHistograms; ++hist) {
for (size_t bin = 0; bin < NBins; ++bin) {
VERIFY(histogram[hist][bin] > MinGood)
<< " bin = " << bin << " is " << histogram[0][bin];
VERIFY(histogram[hist][bin] < MaxGood)
<< " bin = " << bin << " is " << histogram[0][bin];
}
}
}
template<> void Random<float_v>() { FloatRandom<float_v, int_v>(); }
template<> void Random<double_v>() { FloatRandom<double_v, int_v>(); }
template<> void Random<sfloat_v>() { FloatRandom<sfloat_v, short_v>(); }
template<typename T> T add2(T x) { return x + T(2); }
template<typename T, typename V>
class CallTester
{
public:
CallTester() : v(Vc::Zero), i(0) {}
void operator()(T x) {
v[i] = x;
++i;
}
void reset() { v.setZero(); i = 0; }
int callCount() const { return i; }
V callValues() const { return v; }
private:
V v;
int i;
};
#if __cplusplus >= 201103 && (!defined(VC_CLANG) || VC_CLANG > 0x30000)
#define DO_LAMBDA_TESTS 1
#endif
template<typename V>
void applyAndCall()
{
typedef typename V::EntryType T;
const V two(T(2));
for (int i = 0; i < 1000; ++i) {
const V rand = V::Random();
COMPARE(rand.apply(add2<T>), rand + two);
#ifdef DO_LAMBDA_TESTS
COMPARE(rand.apply([](T x) { return x + T(2); }), rand + two);
#endif
CallTester<T, V> callTester;
rand.call(callTester);
COMPARE(callTester.callCount(), int(V::Size));
COMPARE(callTester.callValues(), rand);
for_all_masks(V, mask) {
V copy1 = rand;
V copy2 = rand;
copy1(mask) += two;
COMPARE(copy2(mask).apply(add2<T>), copy1) << mask;
COMPARE(rand.apply(add2<T>, mask), copy1) << mask;
#ifdef DO_LAMBDA_TESTS
COMPARE(copy2(mask).apply([](T x) { return x + T(2); }), copy1) << mask;
COMPARE(rand.apply([](T x) { return x + T(2); }, mask), copy1) << mask;
#endif
callTester.reset();
copy2(mask).call(callTester);
COMPARE(callTester.callCount(), mask.count());
callTester.reset();
rand.call(callTester, mask);
COMPARE(callTester.callCount(), mask.count());
}
}
}
template<typename T, int value> T returnConstant() { return T(value); }
template<typename T, int value> T returnConstantOffset(int i) { return T(value) + T(i); }
template<typename T, int value> T returnConstantOffset2(unsigned short i) { return T(value) + T(i); }
template<typename V> void fill()
{
typedef typename V::EntryType T;
typedef typename V::IndexType I;
V test = V::Random();
test.fill(returnConstant<T, 2>);
COMPARE(test, V(T(2)));
test = V::Random();
test.fill(returnConstantOffset<T, 0>);
COMPARE(test, static_cast<V>(I::IndexesFromZero()));
test = V::Random();
test.fill(returnConstantOffset2<T, 0>);
COMPARE(test, static_cast<V>(I::IndexesFromZero()));
}
template<typename V> void shifted()
{
typedef typename V::EntryType T;
for (int shift = -2 * V::Size; shift <= 2 * V::Size; ++shift) {
const V reference = V::Random();
const V test = reference.shifted(shift);
for (int i = 0; i < V::Size; ++i) {
if (i + shift >= 0 && i + shift < V::Size) {
COMPARE(test[i], reference[i + shift]) << "shift: " << shift << ", i: " << i << ", test: " << test << ", reference: " << reference;
} else {
COMPARE(test[i], T(0)) << "shift: " << shift << ", i: " << i << ", test: " << test << ", reference: " << reference;
}
}
}
}
template<typename V> void rotated()
{
for (int shift = -2 * V::Size; shift <= 2 * V::Size; ++shift) {
//std::cout << "amount = " << shift % V::Size << std::endl;
const V reference = V::Random();
const V test = reference.rotated(shift);
for (int i = 0; i < V::Size; ++i) {
unsigned int refShift = i + shift;
COMPARE(test[i], reference[refShift % V::Size]) << "shift: " << shift << ", i: " << i << ", test: " << test << ", reference: " << reference;
}
}
}
void testMallocAlignment()
{
int_v *a = Vc::malloc<int_v, Vc::AlignOnVector>(10);
unsigned long mask = VectorAlignment - 1;
for (int i = 0; i < 10; ++i) {
VERIFY((reinterpret_cast<unsigned long>(&a[i]) & mask) == 0);
}
const char *data = reinterpret_cast<const char *>(&a[0]);
for (int i = 0; i < 10; ++i) {
VERIFY(&data[i * int_v::Size * sizeof(int_v::EntryType)] == reinterpret_cast<const char *>(&a[i]));
}
a = Vc::malloc<int_v, Vc::AlignOnCacheline>(10);
mask = CpuId::cacheLineSize() - 1;
COMPARE((reinterpret_cast<unsigned long>(&a[0]) & mask), 0ul);
// I don't know how to properly check page alignment. So we check for 4 KiB alignment as this is
// the minimum page size on x86
a = Vc::malloc<int_v, Vc::AlignOnPage>(10);
mask = 4096 - 1;
COMPARE((reinterpret_cast<unsigned long>(&a[0]) & mask), 0ul);
}
int main()
{
testAllTypes(testCall);
testAllTypes(testForeachBit);
testAllTypes(testSort);
testRealTypes(copySign);
testAllTypes(shifted);
testAllTypes(rotated);
testAllTypes(Random);
testAllTypes(applyAndCall);
testAllTypes(fill);
runTest(testMallocAlignment);
return 0;
}
<commit_msg>use correct path to cpuid.h<commit_after>/* This file is part of the Vc library.
Copyright (C) 2009-2012 Matthias Kretz <[email protected]>
Vc is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3 of
the License, or (at your option) any later version.
Vc 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 Vc. If not, see <http://www.gnu.org/licenses/>.
*/
#include <Vc/Vc>
#include "unittest.h"
#include <iostream>
#include "vectormemoryhelper.h"
#include <Vc/cpuid.h>
using namespace Vc;
template<typename Vec> void testSort()
{
typedef typename Vec::EntryType EntryType;
typedef typename Vec::IndexType IndexType;
typename Vec::Memory _a;
const IndexType _ref(IndexesFromZero);
Vec ref(_ref);
Vec a;
int maxPerm = 1;
for (int x = Vec::Size; x > 0; --x) {
maxPerm *= x;
}
for (int perm = 0; perm < maxPerm; ++perm) {
int rest = perm;
for (int i = 0; i < Vec::Size; ++i) {
_a[i] = 0;
for (int j = 0; j < i; ++j) {
if (_a[i] == _a[j]) {
++_a[i];
j = -1;
}
}
_a[i] += rest % (Vec::Size - i);
rest /= (Vec::Size - i);
for (int j = 0; j < i; ++j) {
if (_a[i] == _a[j]) {
++_a[i];
j = -1;
}
}
}
a.load(_a);
//std::cout << a << a.sorted() << std::endl;
COMPARE(ref, a.sorted()) << ", a: " << a;
}
}
template<typename T, typename Mem> struct Foo
{
Foo() : i(0) {}
void reset() { i = 0; }
void operator()(T v) { d[i++] = v; }
Mem d;
int i;
};
template<typename V> void testCall()
{
typedef typename V::EntryType T;
typedef typename V::IndexType I;
typedef typename V::Mask M;
typedef typename I::Mask MI;
const I _indexes(IndexesFromZero);
const MI _odd = (_indexes & I(One)) > 0;
const M odd(_odd);
V a(_indexes);
Foo<T, typename V::Memory> f;
a.callWithValuesSorted(f);
V b(f.d);
COMPARE(b, a);
f.reset();
a(odd) -= 1;
a.callWithValuesSorted(f);
V c(f.d);
for (int i = 0; i < V::Size / 2; ++i) {
COMPARE(a[i * 2], c[i]);
}
for (int i = V::Size / 2; i < V::Size; ++i) {
COMPARE(b[i], c[i]);
}
}
template<typename V> void testForeachBit()
{
typedef typename V::EntryType T;
typedef typename V::IndexType I;
typedef typename V::Mask M;
typedef typename I::Mask MI;
const I indexes(IndexesFromZero);
for_all_masks(V, mask) {
V tmp = V::Zero();
foreach_bit(int j, mask) {
tmp[j] = T(1);
}
COMPARE(tmp == V::One(), mask);
int count = 0;
foreach_bit(int j, mask) {
++count;
if (j >= 0) {
continue;
}
}
COMPARE(count, mask.count());
count = 0;
foreach_bit(int j, mask) {
if (j >= 0) {
break;
}
++count;
}
COMPARE(count, 0);
}
}
template<typename V> void copySign()
{
typedef typename V::EntryType T;
V v(One);
V positive(One);
V negative = -positive;
COMPARE(v, v.copySign(positive));
COMPARE(-v, v.copySign(negative));
}
#ifdef VC_MSVC
void bzero(void *p, size_t n) { memset(p, 0, n); }
#else
#include <strings.h>
#endif
template<typename V> void Random()
{
typedef typename V::EntryType T;
enum {
NBits = 3,
NBins = 1 << NBits, // short int
TotalBits = sizeof(T) * 8, // 16 32
RightShift = TotalBits - NBits, // 13 29
NHistograms = TotalBits - NBits + 1, // 14 30
LeftShift = (RightShift + 1) / NHistograms,// 1 1
Mean = 135791,
MinGood = Mean - Mean/10,
MaxGood = Mean + Mean/10
};
const V mask((1 << NBits) - 1);
int histogram[NHistograms][NBins];
bzero(&histogram[0][0], sizeof(histogram));
for (size_t i = 0; i < NBins * Mean / V::Size; ++i) {
const V rand = V::Random();
for (size_t hist = 0; hist < NHistograms; ++hist) {
const V bin = ((rand << (hist * LeftShift)) >> RightShift) & mask;
for (size_t k = 0; k < V::Size; ++k) {
++histogram[hist][bin[k]];
}
}
}
//#define PRINT_RANDOM_HISTOGRAM
#ifdef PRINT_RANDOM_HISTOGRAM
for (size_t hist = 0; hist < NHistograms; ++hist) {
std::cout << "histogram[" << std::setw(2) << hist << "]: ";
for (size_t bin = 0; bin < NBins; ++bin) {
std::cout << std::setw(3) << (histogram[hist][bin] - Mean) * 1000 / Mean << "|";
}
std::cout << std::endl;
}
#endif
for (size_t hist = 0; hist < NHistograms; ++hist) {
for (size_t bin = 0; bin < NBins; ++bin) {
VERIFY(histogram[hist][bin] > MinGood)
<< " bin = " << bin << " is " << histogram[0][bin];
VERIFY(histogram[hist][bin] < MaxGood)
<< " bin = " << bin << " is " << histogram[0][bin];
}
}
}
template<typename V, typename I> void FloatRandom()
{
typedef typename V::EntryType T;
enum {
NBins = 64,
NHistograms = 1,
Mean = 135791,
MinGood = Mean - Mean/10,
MaxGood = Mean + Mean/10
};
int histogram[NHistograms][NBins];
bzero(&histogram[0][0], sizeof(histogram));
for (size_t i = 0; i < NBins * Mean / V::Size; ++i) {
const V rand = V::Random();
const I bin = static_cast<I>(rand * T(NBins));
for (size_t k = 0; k < V::Size; ++k) {
++histogram[0][bin[k]];
}
}
#ifdef PRINT_RANDOM_HISTOGRAM
for (size_t hist = 0; hist < NHistograms; ++hist) {
std::cout << "histogram[" << std::setw(2) << hist << "]: ";
for (size_t bin = 0; bin < NBins; ++bin) {
std::cout << std::setw(3) << (histogram[hist][bin] - Mean) * 1000 / Mean << "|";
}
std::cout << std::endl;
}
#endif
for (size_t hist = 0; hist < NHistograms; ++hist) {
for (size_t bin = 0; bin < NBins; ++bin) {
VERIFY(histogram[hist][bin] > MinGood)
<< " bin = " << bin << " is " << histogram[0][bin];
VERIFY(histogram[hist][bin] < MaxGood)
<< " bin = " << bin << " is " << histogram[0][bin];
}
}
}
template<> void Random<float_v>() { FloatRandom<float_v, int_v>(); }
template<> void Random<double_v>() { FloatRandom<double_v, int_v>(); }
template<> void Random<sfloat_v>() { FloatRandom<sfloat_v, short_v>(); }
template<typename T> T add2(T x) { return x + T(2); }
template<typename T, typename V>
class CallTester
{
public:
CallTester() : v(Vc::Zero), i(0) {}
void operator()(T x) {
v[i] = x;
++i;
}
void reset() { v.setZero(); i = 0; }
int callCount() const { return i; }
V callValues() const { return v; }
private:
V v;
int i;
};
#if __cplusplus >= 201103 && (!defined(VC_CLANG) || VC_CLANG > 0x30000)
#define DO_LAMBDA_TESTS 1
#endif
template<typename V>
void applyAndCall()
{
typedef typename V::EntryType T;
const V two(T(2));
for (int i = 0; i < 1000; ++i) {
const V rand = V::Random();
COMPARE(rand.apply(add2<T>), rand + two);
#ifdef DO_LAMBDA_TESTS
COMPARE(rand.apply([](T x) { return x + T(2); }), rand + two);
#endif
CallTester<T, V> callTester;
rand.call(callTester);
COMPARE(callTester.callCount(), int(V::Size));
COMPARE(callTester.callValues(), rand);
for_all_masks(V, mask) {
V copy1 = rand;
V copy2 = rand;
copy1(mask) += two;
COMPARE(copy2(mask).apply(add2<T>), copy1) << mask;
COMPARE(rand.apply(add2<T>, mask), copy1) << mask;
#ifdef DO_LAMBDA_TESTS
COMPARE(copy2(mask).apply([](T x) { return x + T(2); }), copy1) << mask;
COMPARE(rand.apply([](T x) { return x + T(2); }, mask), copy1) << mask;
#endif
callTester.reset();
copy2(mask).call(callTester);
COMPARE(callTester.callCount(), mask.count());
callTester.reset();
rand.call(callTester, mask);
COMPARE(callTester.callCount(), mask.count());
}
}
}
template<typename T, int value> T returnConstant() { return T(value); }
template<typename T, int value> T returnConstantOffset(int i) { return T(value) + T(i); }
template<typename T, int value> T returnConstantOffset2(unsigned short i) { return T(value) + T(i); }
template<typename V> void fill()
{
typedef typename V::EntryType T;
typedef typename V::IndexType I;
V test = V::Random();
test.fill(returnConstant<T, 2>);
COMPARE(test, V(T(2)));
test = V::Random();
test.fill(returnConstantOffset<T, 0>);
COMPARE(test, static_cast<V>(I::IndexesFromZero()));
test = V::Random();
test.fill(returnConstantOffset2<T, 0>);
COMPARE(test, static_cast<V>(I::IndexesFromZero()));
}
template<typename V> void shifted()
{
typedef typename V::EntryType T;
for (int shift = -2 * V::Size; shift <= 2 * V::Size; ++shift) {
const V reference = V::Random();
const V test = reference.shifted(shift);
for (int i = 0; i < V::Size; ++i) {
if (i + shift >= 0 && i + shift < V::Size) {
COMPARE(test[i], reference[i + shift]) << "shift: " << shift << ", i: " << i << ", test: " << test << ", reference: " << reference;
} else {
COMPARE(test[i], T(0)) << "shift: " << shift << ", i: " << i << ", test: " << test << ", reference: " << reference;
}
}
}
}
template<typename V> void rotated()
{
for (int shift = -2 * V::Size; shift <= 2 * V::Size; ++shift) {
//std::cout << "amount = " << shift % V::Size << std::endl;
const V reference = V::Random();
const V test = reference.rotated(shift);
for (int i = 0; i < V::Size; ++i) {
unsigned int refShift = i + shift;
COMPARE(test[i], reference[refShift % V::Size]) << "shift: " << shift << ", i: " << i << ", test: " << test << ", reference: " << reference;
}
}
}
void testMallocAlignment()
{
int_v *a = Vc::malloc<int_v, Vc::AlignOnVector>(10);
unsigned long mask = VectorAlignment - 1;
for (int i = 0; i < 10; ++i) {
VERIFY((reinterpret_cast<unsigned long>(&a[i]) & mask) == 0);
}
const char *data = reinterpret_cast<const char *>(&a[0]);
for (int i = 0; i < 10; ++i) {
VERIFY(&data[i * int_v::Size * sizeof(int_v::EntryType)] == reinterpret_cast<const char *>(&a[i]));
}
a = Vc::malloc<int_v, Vc::AlignOnCacheline>(10);
mask = CpuId::cacheLineSize() - 1;
COMPARE((reinterpret_cast<unsigned long>(&a[0]) & mask), 0ul);
// I don't know how to properly check page alignment. So we check for 4 KiB alignment as this is
// the minimum page size on x86
a = Vc::malloc<int_v, Vc::AlignOnPage>(10);
mask = 4096 - 1;
COMPARE((reinterpret_cast<unsigned long>(&a[0]) & mask), 0ul);
}
int main()
{
testAllTypes(testCall);
testAllTypes(testForeachBit);
testAllTypes(testSort);
testRealTypes(copySign);
testAllTypes(shifted);
testAllTypes(rotated);
testAllTypes(Random);
testAllTypes(applyAndCall);
testAllTypes(fill);
runTest(testMallocAlignment);
return 0;
}
<|endoftext|>
|
<commit_before>#include <catch.hpp>
#include <fstream>
#include <iostream>
#include <kitty/constructors.hpp>
#include <kitty/dynamic_truth_table.hpp>
#include <kitty/operations.hpp>
#include <kitty/print.hpp>
#include <mockturtle/algorithms/akers_synthesis.hpp>
#include <mockturtle/networks/mig.hpp>
using namespace mockturtle;
TEST_CASE( "Check Akers for MAJ-3", "[maj_3_akers]" )
{
mig_network mig;
std::vector<kitty::dynamic_truth_table> xs{5, kitty::dynamic_truth_table( 3 )};
create_majority( xs[0] );
for ( auto i = 0u; i < unsigned( xs[0].num_bits() ); i++ )
{
set_bit( xs[1], i );
}
mig = akers_synthesis( mig, xs[0], xs[1] );
kitty::create_nth_var( xs[2], 0 );
kitty::create_nth_var( xs[3], 1 );
kitty::create_nth_var( xs[4], 2 );
CHECK( mig.compute( mig.index_to_node( mig.size() ), xs.begin() + 2, xs.end() ) == xs[0] );
CHECK( mig.size() == 5 );
}
TEST_CASE( "Check Akers for MAJ-5", "[maj_5_akers]" )
{
mig_network mig;
std::vector<kitty::dynamic_truth_table> xs{7, kitty::dynamic_truth_table( 5 )};
create_majority( xs[0] );
for ( auto i = 0u; i < unsigned( xs[0].num_bits() ); i++ )
{
set_bit( xs[1], i );
}
mig = akers_synthesis( mig, xs[0], xs[1] );
kitty::create_nth_var( xs[2], 0 );
kitty::create_nth_var( xs[3], 1 );
kitty::create_nth_var( xs[4], 2 );
kitty::create_nth_var( xs[5], 3 );
kitty::create_nth_var( xs[6], 4 );
mig.foreach_gate( [&]( auto n ) {
std::vector<kitty::dynamic_truth_table> fanin{3, kitty::dynamic_truth_table( 5 )};
mig.foreach_fanin( n, [&]( auto s, auto j ) {
fanin[j] = xs[mig.node_to_index( mig.get_node( s ) ) + 1];
} );
xs.push_back( mig.compute( n, fanin.begin(), fanin.end() ) );
} );
CHECK( xs[xs.size() - 1] == xs[0] );
}
TEST_CASE( "Check Akers for random - 4 inputs", "[maj_random4_akers]" )
{
for ( auto y = 0; y < 5; y++ )
{
mig_network mig;
std::vector<kitty::dynamic_truth_table> xs{6, kitty::dynamic_truth_table( 4 )};
kitty::create_nth_var( xs[2], 0 );
kitty::create_nth_var( xs[3], 1 );
kitty::create_nth_var( xs[4], 2 );
kitty::create_nth_var( xs[5], 3 );
create_random( xs[0] );
//kitty::print_binary(xs[0], std::cout); std::cout << std::endl;
for ( auto i = 0u; i < unsigned( xs[0].num_bits() ); i++ )
{
set_bit( xs[1], i );
}
mig = akers_synthesis( mig, xs[0], xs[1] );
if ( mig.size() > 4 )
{
mig.foreach_gate( [&]( auto n ) {
std::vector<kitty::dynamic_truth_table> fanin{3, kitty::dynamic_truth_table( 4 )};
mig.foreach_fanin( n, [&]( auto s, auto j ) {
if ( mig.node_to_index( mig.get_node( s ) ) == 0 )
{
fanin[j] = ~xs[1];
}
else
{
fanin[j] = xs[mig.node_to_index( mig.get_node( s ) ) + 1];
}
} );
xs.push_back( mig.compute( n, fanin.begin(), fanin.end() ) );
} );
mig.foreach_po( [&]( auto n ) {
if ( mig.is_complemented( n ) )
CHECK( ~xs[xs.size() - 1] == xs[0] );
else
CHECK( xs[xs.size() - 1] == xs[0] );
} );
}
}
}
TEST_CASE( "Check Akers for random - 5 inputs", "[maj_random5_akers]" )
{
for ( auto y = 0; y < 5; y++ )
{
mig_network mig;
std::vector<kitty::dynamic_truth_table> xs{7, kitty::dynamic_truth_table( 5 )};
kitty::create_nth_var( xs[2], 0 );
kitty::create_nth_var( xs[3], 1 );
kitty::create_nth_var( xs[4], 2 );
kitty::create_nth_var( xs[5], 3 );
kitty::create_nth_var( xs[6], 4 );
create_random( xs[0] );
for ( auto i = 0u; i < unsigned( xs[0].num_bits() ); i++ )
{
set_bit( xs[1], i );
}
mig = akers_synthesis( mig, xs[0], xs[1] );
if ( mig.size() > 6 )
{
mig.foreach_gate( [&]( auto n ) {
std::vector<kitty::dynamic_truth_table> fanin{3, kitty::dynamic_truth_table( 5 )};
mig.foreach_fanin( n, [&]( auto s, auto j ) {
if ( mig.node_to_index( mig.get_node( s ) ) == 0 )
{
fanin[j] = ~xs[1];
}
else
{
fanin[j] = xs[mig.node_to_index( mig.get_node( s ) ) + 1];
}
} );
xs.push_back( mig.compute( n, fanin.begin(), fanin.end() ) );
} );
mig.foreach_po( [&]( auto n ) {
if ( mig.is_complemented( n ) )
CHECK( ~xs[xs.size() - 1] == xs[0] );
else
CHECK( xs[xs.size() - 1] == xs[0] );
} );
}
}
}
TEST_CASE( "Check Akers for random - 6 inputs", "[maj_random6_akers]" )
{
for ( auto y = 0; y < 1; y++ )
{
mig_network mig;
std::vector<kitty::dynamic_truth_table> xs{8, kitty::dynamic_truth_table( 6 )};
kitty::create_nth_var( xs[2], 0 );
kitty::create_nth_var( xs[3], 1 );
kitty::create_nth_var( xs[4], 2 );
kitty::create_nth_var( xs[5], 3 );
kitty::create_nth_var( xs[6], 4 );
kitty::create_nth_var( xs[7], 5 );
//create_from_binary_string(xs[0], "1100110010001100011010011010100001111010101010110010011010000010");
create_random( xs[0] );
//kitty::print_binary( xs[0], std::cout );
//std::cout << std::endl;
for ( auto i = 0u; i < unsigned( xs[0].num_bits() ); i++ )
{
set_bit( xs[1], i );
}
mig = akers_synthesis( mig, xs[0], xs[1] );
if ( mig.size() > 6 )
{
mig.foreach_gate( [&]( auto n ) {
std::vector<kitty::dynamic_truth_table> fanin{3, kitty::dynamic_truth_table( 6 )};
mig.foreach_fanin( n, [&]( auto s, auto j ) {
if ( mig.node_to_index( mig.get_node( s ) ) == 0 )
{
fanin[j] = ~xs[1];
}
else
{
fanin[j] = xs[mig.node_to_index( mig.get_node( s ) ) + 1];
}
} );
xs.push_back( mig.compute( n, fanin.begin(), fanin.end() ) );
} );
mig.foreach_po( [&]( auto n ) {
if ( mig.is_complemented( n ) )
CHECK( ~xs[xs.size() - 1] == xs[0] );
else
CHECK( xs[xs.size() - 1] == xs[0] );
} );
}
}
}
TEST_CASE( "Check SIZE and DEPTH for Akers for random - 6 inputs", "[maj_random6_sizedepthakers]" )
{
std::ifstream infile( "mock_akers.txt" );
int size;
std::string tt;
while ( infile >> tt >> size )
{
std::cout << tt << std::endl;
std::cout << size << std::endl;
mig_network mig;
std::vector<kitty::dynamic_truth_table> xs{8, kitty::dynamic_truth_table( 6 )};
kitty::create_nth_var( xs[2], 0 );
kitty::create_nth_var( xs[3], 1 );
kitty::create_nth_var( xs[4], 2 );
kitty::create_nth_var( xs[5], 3 );
kitty::create_nth_var( xs[6], 4 );
kitty::create_nth_var( xs[7], 5 );
create_from_binary_string( xs[0], tt );
for ( auto i = 0u; i < unsigned( xs[0].num_bits() ); i++ )
{
set_bit( xs[1], i );
}
mig = akers_synthesis( mig, xs[0], xs[1] );
if ( mig.size() > 6 )
{
mig.foreach_gate( [&]( auto n ) {
std::vector<kitty::dynamic_truth_table> fanin{3, kitty::dynamic_truth_table( 6 )};
mig.foreach_fanin( n, [&]( auto s, auto j ) {
if ( mig.node_to_index( mig.get_node( s ) ) == 0 )
{
fanin[j] = ~xs[1];
}
else
{
fanin[j] = xs[mig.node_to_index( mig.get_node( s ) ) + 1];
}
} );
xs.push_back( mig.compute( n, fanin.begin(), fanin.end() ) );
} );
mig.foreach_po( [&]( auto n ) {
if ( mig.is_complemented( n ) )
CHECK( ~xs[xs.size() - 1] == xs[0] );
else
CHECK( xs[xs.size() - 1] == xs[0] );
} );
}
CHECK( mig.num_gates() == size );
}
}
TEST_CASE( "Check leaves iterator -- easy case ", "[akers_leavesiterator]" )
{
mig_network mig;
auto a = mig.create_pi();
auto b = mig.create_pi();
auto c = mig.create_pi();
auto d = mig.create_pi();
std::vector<mig_network::signal> operations;
operations.push_back( mig.create_and( a, b ) );
operations.push_back( mig.create_and( c, d ) );
std::vector<kitty::dynamic_truth_table> xs_in{2, kitty::dynamic_truth_table( 2 )};
std::vector<kitty::dynamic_truth_table> xs{5, kitty::dynamic_truth_table( 4 )};
create_from_binary_string( xs_in[0], "0110" );
for ( auto i = 0u; i < unsigned( xs_in[0].num_bits() ); i++ )
{
set_bit( xs_in[1], i );
}
auto t = akers_synthesis( mig, xs_in[0], xs_in[1], operations.begin(), operations.end() );
mig.create_po(t);
kitty::create_nth_var( xs[1], 0 );
kitty::create_nth_var( xs[2], 1 );
kitty::create_nth_var( xs[3], 2 );
kitty::create_nth_var( xs[4], 3 );
for ( auto i = 0u; i < unsigned( xs[1].num_bits() ); i++ )
{
set_bit( xs[0], i );
}
CHECK( mig.num_gates() == 5 );
if ( mig.size() > 6 )
{
mig.foreach_gate( [&]( auto n ) {
std::vector<kitty::dynamic_truth_table> fanin{3, kitty::dynamic_truth_table( 4 )};
mig.foreach_fanin( n, [&]( auto s, auto j ) {
if ( mig.node_to_index( mig.get_node( s ) ) == 0 )
{
fanin[j] = ~xs[0];
}
else
{
fanin[j] = xs[mig.get_node( s ) ];
}
} );
xs.push_back( mig.compute( n, fanin.begin(), fanin.end() ) );
} );
mig.foreach_po( [&]( auto n ) {
if ( mig.is_complemented( n ) )
CHECK( ~xs[xs.size() - 1] == binary_xor(binary_and(xs[1], xs[2]), binary_and(xs[4],xs[3])));
else
CHECK( xs[xs.size() - 1] == binary_xor(binary_and(xs[1], xs[2]), binary_and(xs[4],xs[3])));
} );
}
//CHECK( mig.num_gates() == 5 );
}<commit_msg>Test - final version<commit_after>#include <catch.hpp>
#include <fstream>
#include <iostream>
#include <kitty/constructors.hpp>
#include <kitty/dynamic_truth_table.hpp>
#include <kitty/operations.hpp>
#include <kitty/print.hpp>
#include <mockturtle/algorithms/akers_synthesis.hpp>
#include <mockturtle/networks/mig.hpp>
using namespace mockturtle;
TEST_CASE( "Check Akers for MAJ-3", "[maj_3_akers]" )
{
mig_network mig;
std::vector<kitty::dynamic_truth_table> xs{5, kitty::dynamic_truth_table( 3 )};
create_majority( xs[0] );
for ( auto i = 0u; i < unsigned( xs[0].num_bits() ); i++ )
{
set_bit( xs[1], i );
}
mig = akers_synthesis( mig, xs[0], xs[1] );
kitty::create_nth_var( xs[2], 0 );
kitty::create_nth_var( xs[3], 1 );
kitty::create_nth_var( xs[4], 2 );
CHECK( mig.compute( mig.index_to_node( mig.size() ), xs.begin() + 2, xs.end() ) == xs[0] );
CHECK( mig.size() == 5 );
}
TEST_CASE( "Check Akers for MAJ-5", "[maj_5_akers]" )
{
mig_network mig;
std::vector<kitty::dynamic_truth_table> xs{7, kitty::dynamic_truth_table( 5 )};
create_majority( xs[0] );
for ( auto i = 0u; i < unsigned( xs[0].num_bits() ); i++ )
{
set_bit( xs[1], i );
}
mig = akers_synthesis( mig, xs[0], xs[1] );
kitty::create_nth_var( xs[2], 0 );
kitty::create_nth_var( xs[3], 1 );
kitty::create_nth_var( xs[4], 2 );
kitty::create_nth_var( xs[5], 3 );
kitty::create_nth_var( xs[6], 4 );
mig.foreach_gate( [&]( auto n ) {
std::vector<kitty::dynamic_truth_table> fanin{3, kitty::dynamic_truth_table( 5 )};
mig.foreach_fanin( n, [&]( auto s, auto j ) {
fanin[j] = xs[mig.node_to_index( mig.get_node( s ) ) + 1];
} );
xs.push_back( mig.compute( n, fanin.begin(), fanin.end() ) );
} );
CHECK( xs[xs.size() - 1] == xs[0] );
}
TEST_CASE( "Check Akers for random - 4 inputs", "[maj_random4_akers]" )
{
for ( auto y = 0; y < 5; y++ )
{
mig_network mig;
std::vector<kitty::dynamic_truth_table> xs{6, kitty::dynamic_truth_table( 4 )};
kitty::create_nth_var( xs[2], 0 );
kitty::create_nth_var( xs[3], 1 );
kitty::create_nth_var( xs[4], 2 );
kitty::create_nth_var( xs[5], 3 );
create_random( xs[0] );
//kitty::print_binary(xs[0], std::cout); std::cout << std::endl;
for ( auto i = 0u; i < unsigned( xs[0].num_bits() ); i++ )
{
set_bit( xs[1], i );
}
mig = akers_synthesis( mig, xs[0], xs[1] );
if ( mig.size() > 4 )
{
mig.foreach_gate( [&]( auto n ) {
std::vector<kitty::dynamic_truth_table> fanin{3, kitty::dynamic_truth_table( 4 )};
mig.foreach_fanin( n, [&]( auto s, auto j ) {
if ( mig.node_to_index( mig.get_node( s ) ) == 0 )
{
fanin[j] = ~xs[1];
}
else
{
fanin[j] = xs[mig.node_to_index( mig.get_node( s ) ) + 1];
}
} );
xs.push_back( mig.compute( n, fanin.begin(), fanin.end() ) );
} );
mig.foreach_po( [&]( auto n ) {
if ( mig.is_complemented( n ) )
CHECK( ~xs[xs.size() - 1] == xs[0] );
else
CHECK( xs[xs.size() - 1] == xs[0] );
} );
}
}
}
TEST_CASE( "Check Akers for random - 5 inputs", "[maj_random5_akers]" )
{
for ( auto y = 0; y < 5; y++ )
{
mig_network mig;
std::vector<kitty::dynamic_truth_table> xs{7, kitty::dynamic_truth_table( 5 )};
kitty::create_nth_var( xs[2], 0 );
kitty::create_nth_var( xs[3], 1 );
kitty::create_nth_var( xs[4], 2 );
kitty::create_nth_var( xs[5], 3 );
kitty::create_nth_var( xs[6], 4 );
create_random( xs[0] );
for ( auto i = 0u; i < unsigned( xs[0].num_bits() ); i++ )
{
set_bit( xs[1], i );
}
mig = akers_synthesis( mig, xs[0], xs[1] );
if ( mig.size() > 6 )
{
mig.foreach_gate( [&]( auto n ) {
std::vector<kitty::dynamic_truth_table> fanin{3, kitty::dynamic_truth_table( 5 )};
mig.foreach_fanin( n, [&]( auto s, auto j ) {
if ( mig.node_to_index( mig.get_node( s ) ) == 0 )
{
fanin[j] = ~xs[1];
}
else
{
fanin[j] = xs[mig.node_to_index( mig.get_node( s ) ) + 1];
}
} );
xs.push_back( mig.compute( n, fanin.begin(), fanin.end() ) );
} );
mig.foreach_po( [&]( auto n ) {
if ( mig.is_complemented( n ) )
CHECK( ~xs[xs.size() - 1] == xs[0] );
else
CHECK( xs[xs.size() - 1] == xs[0] );
} );
}
}
}
TEST_CASE( "Check Akers for random - 6 inputs", "[maj_random6_akers]" )
{
for ( auto y = 0; y < 1; y++ )
{
mig_network mig;
std::vector<kitty::dynamic_truth_table> xs{8, kitty::dynamic_truth_table( 6 )};
kitty::create_nth_var( xs[2], 0 );
kitty::create_nth_var( xs[3], 1 );
kitty::create_nth_var( xs[4], 2 );
kitty::create_nth_var( xs[5], 3 );
kitty::create_nth_var( xs[6], 4 );
kitty::create_nth_var( xs[7], 5 );
//create_from_binary_string(xs[0], "1100110010001100011010011010100001111010101010110010011010000010");
create_random( xs[0] );
//kitty::print_binary( xs[0], std::cout );
//std::cout << std::endl;
for ( auto i = 0u; i < unsigned( xs[0].num_bits() ); i++ )
{
set_bit( xs[1], i );
}
mig = akers_synthesis( mig, xs[0], xs[1] );
if ( mig.size() > 6 )
{
mig.foreach_gate( [&]( auto n ) {
std::vector<kitty::dynamic_truth_table> fanin{3, kitty::dynamic_truth_table( 6 )};
mig.foreach_fanin( n, [&]( auto s, auto j ) {
if ( mig.node_to_index( mig.get_node( s ) ) == 0 )
{
fanin[j] = ~xs[1];
}
else
{
fanin[j] = xs[mig.node_to_index( mig.get_node( s ) ) + 1];
}
} );
xs.push_back( mig.compute( n, fanin.begin(), fanin.end() ) );
} );
mig.foreach_po( [&]( auto n ) {
if ( mig.is_complemented( n ) )
CHECK( ~xs[xs.size() - 1] == xs[0] );
else
CHECK( xs[xs.size() - 1] == xs[0] );
} );
}
}
}
/*
TEST_CASE( "Check SIZE and DEPTH for Akers for random - 6 inputs", "[maj_random6_sizedepthakers]" )
{
std::ifstream infile( "mock_akers.txt" );
int size;
std::string tt;
while ( infile >> tt >> size )
{
std::cout << tt << std::endl;
std::cout << size << std::endl;
mig_network mig;
std::vector<kitty::dynamic_truth_table> xs{8, kitty::dynamic_truth_table( 6 )};
kitty::create_nth_var( xs[2], 0 );
kitty::create_nth_var( xs[3], 1 );
kitty::create_nth_var( xs[4], 2 );
kitty::create_nth_var( xs[5], 3 );
kitty::create_nth_var( xs[6], 4 );
kitty::create_nth_var( xs[7], 5 );
create_from_binary_string( xs[0], tt );
for ( auto i = 0u; i < unsigned( xs[0].num_bits() ); i++ )
{
set_bit( xs[1], i );
}
mig = akers_synthesis( mig, xs[0], xs[1] );
if ( mig.size() > 6 )
{
mig.foreach_gate( [&]( auto n ) {
std::vector<kitty::dynamic_truth_table> fanin{3, kitty::dynamic_truth_table( 6 )};
mig.foreach_fanin( n, [&]( auto s, auto j ) {
if ( mig.node_to_index( mig.get_node( s ) ) == 0 )
{
fanin[j] = ~xs[1];
}
else
{
fanin[j] = xs[mig.node_to_index( mig.get_node( s ) ) + 1];
}
} );
xs.push_back( mig.compute( n, fanin.begin(), fanin.end() ) );
} );
mig.foreach_po( [&]( auto n ) {
if ( mig.is_complemented( n ) )
CHECK( ~xs[xs.size() - 1] == xs[0] );
else
CHECK( xs[xs.size() - 1] == xs[0] );
} );
}
CHECK( mig.num_gates() == size );
}
}*/
TEST_CASE( "Check leaves iterator -- easy case ", "[akers_leavesiterator]" )
{
mig_network mig;
auto a = mig.create_pi();
auto b = mig.create_pi();
auto c = mig.create_pi();
auto d = mig.create_pi();
std::vector<mig_network::signal> operations;
operations.push_back( mig.create_and( a, b ) );
operations.push_back( mig.create_and( c, d ) );
std::vector<kitty::dynamic_truth_table> xs_in{2, kitty::dynamic_truth_table( 2 )};
std::vector<kitty::dynamic_truth_table> xs{5, kitty::dynamic_truth_table( 4 )};
create_from_binary_string( xs_in[0], "0110" );
for ( auto i = 0u; i < unsigned( xs_in[0].num_bits() ); i++ )
{
set_bit( xs_in[1], i );
}
auto t = akers_synthesis( mig, xs_in[0], xs_in[1], operations.begin(), operations.end() );
mig.create_po(t);
kitty::create_nth_var( xs[1], 0 );
kitty::create_nth_var( xs[2], 1 );
kitty::create_nth_var( xs[3], 2 );
kitty::create_nth_var( xs[4], 3 );
for ( auto i = 0u; i < unsigned( xs[1].num_bits() ); i++ )
{
set_bit( xs[0], i );
}
CHECK( mig.num_gates() == 5 );
if ( mig.size() > 6 )
{
mig.foreach_gate( [&]( auto n ) {
std::vector<kitty::dynamic_truth_table> fanin{3, kitty::dynamic_truth_table( 4 )};
mig.foreach_fanin( n, [&]( auto s, auto j ) {
if ( mig.node_to_index( mig.get_node( s ) ) == 0 )
{
fanin[j] = ~xs[0];
}
else
{
fanin[j] = xs[mig.get_node( s ) ];
}
} );
xs.push_back( mig.compute( n, fanin.begin(), fanin.end() ) );
} );
mig.foreach_po( [&]( auto n ) {
if ( mig.is_complemented( n ) )
CHECK( ~xs[xs.size() - 1] == binary_xor(binary_and(xs[1], xs[2]), binary_and(xs[4],xs[3])));
else
CHECK( xs[xs.size() - 1] == binary_xor(binary_and(xs[1], xs[2]), binary_and(xs[4],xs[3])));
} );
}
//CHECK( mig.num_gates() == 5 );
}<|endoftext|>
|
<commit_before>/*
This file is part of:
NoahFrame
https://github.com/ketoo/NoahGameFrame
Copyright 2009 - 2019 NoahFrame(NoahGameFrame)
File creator: lvsheng.huang
NoahFrame is open-source software and you can redistribute it and/or modify
it under the terms of the License; besides, anyone who use this file/software must include this copyright announcement.
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 "NFComm/NFPluginModule/NFPlatform.h"
#ifdef NF_DEBUG_MODE
#if NF_PLATFORM == NF_PLATFORM_WIN
#pragma comment( lib, "ws2_32" )
#pragma comment( lib, "lua.lib" )
#pragma comment( lib, "libprotobuf.lib" )
#elif NF_PLATFORM == NF_PLATFORM_LINUX || NF_PLATFORM == NF_PLATFORM_ANDROID
#pragma comment( lib, "NFCore_d.a" )
#pragma comment( lib, "lua.a" )
#elif NF_PLATFORM == NF_PLATFORM_APPLE || NF_PLATFORM == NF_PLATFORM_APPLE_IOS
#pragma comment( lib, "NFCore.a" )
#pragma comment( lib, "lua.a" )
#endif
#else
#if NF_PLATFORM == NF_PLATFORM_WIN
#pragma comment( lib, "NFCore.lib" )
#pragma comment( lib, "lua.lib" )
#pragma comment( lib, "libprotobuf.lib" )
#elif NF_PLATFORM == NF_PLATFORM_LINUX || NF_PLATFORM == NF_PLATFORM_ANDROID
#pragma comment( lib, "NFCore.a" )
#pragma comment( lib, "lua.a" )
#elif NF_PLATFORM == NF_PLATFORM_APPLE || NF_PLATFORM == NF_PLATFORM_APPLE_IOS
#pragma comment( lib, "NFCore.a" )
#pragma comment( lib, "lua.a" )
#endif
#endif
<commit_msg>build system<commit_after>/*
This file is part of:
NoahFrame
https://github.com/ketoo/NoahGameFrame
Copyright 2009 - 2019 NoahFrame(NoahGameFrame)
File creator: lvsheng.huang
NoahFrame is open-source software and you can redistribute it and/or modify
it under the terms of the License; besides, anyone who use this file/software must include this copyright announcement.
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 "NFComm/NFPluginModule/NFPlatform.h"
#ifdef NF_DEBUG_MODE
#if NF_PLATFORM == NF_PLATFORM_WIN
#pragma comment( lib, "ws2_32" )
#pragma comment( lib, "lua.lib" )
#pragma comment( lib, "libprotobufd.lib" )
#elif NF_PLATFORM == NF_PLATFORM_LINUX || NF_PLATFORM == NF_PLATFORM_ANDROID
#pragma comment( lib, "NFCore_d.a" )
#pragma comment( lib, "lua.a" )
#elif NF_PLATFORM == NF_PLATFORM_APPLE || NF_PLATFORM == NF_PLATFORM_APPLE_IOS
#pragma comment( lib, "NFCore.a" )
#pragma comment( lib, "lua.a" )
#endif
#else
#if NF_PLATFORM == NF_PLATFORM_WIN
#pragma comment( lib, "NFCore.lib" )
#pragma comment( lib, "lua.lib" )
#pragma comment( lib, "libprotobuf.lib" )
#elif NF_PLATFORM == NF_PLATFORM_LINUX || NF_PLATFORM == NF_PLATFORM_ANDROID
#pragma comment( lib, "NFCore.a" )
#pragma comment( lib, "lua.a" )
#elif NF_PLATFORM == NF_PLATFORM_APPLE || NF_PLATFORM == NF_PLATFORM_APPLE_IOS
#pragma comment( lib, "NFCore.a" )
#pragma comment( lib, "lua.a" )
#endif
#endif
<|endoftext|>
|
<commit_before>#include <iostream>
#include <cmath>
#include <cstdlib>
#include <iomanip>
#include <string>
using namespace std;
// void rowSum(int a[][4],int nRow){
// for(int i=0;i<nRow;i++){
// for(int j=0;j<4;j++){
// a[i][0] = a[i][j];
// }
// }
// }
// void splitFloat(float x,int *intPart, float *fracPart){
// *intPart = static_cast<int>(x);
// *fracPart = x - *intPart;
// }
// int* search(int* a, int num){
// for(int i=0;i<num;i++){
// if(a[i] == 0){
// return &a[i];
// }
// }
// }
// int compute(int a, int b,int(*func)(int,int)){
// return func(a,b);
// }
// int max(int a, int b){
// return((a>b)?a:b);
// }
// int min(int a, int b){
// return((a<b)?a:b);
// }
// int sum(int a, int b){
// return a+b;
// }
// class Point {
// public:
// Point(int x = 0, int y = 0) : x(x), y(y) { }
// int getX() const { return x; }
// int getY() const { return y; }
// private:
// int x, y;
// };
int main(){
int (*fp)[9][8] = new int[7][9][8];
for (int i = 0; i < 7; i++)
for (int j = 0; j < 9; j++)
for (int k = 0; k < 8; k++)
*(*(*(fp + i) + j) + k) = (i*100+j*10+k);
for (int i = 0; i < 7; i++) {
for (int j = 0; j < 9; j++) {
for (int k = 0; k < 8; k++)
cout<<fp[i][j][k]<<' ';
cout<<endl;
}
cout<<endl;
}
delete[] fp;
// Point a(4,5);
// Point *ptr = &a;
// cout<<ptr->getX()<<endl;
// cout<<a.getX()<<endl;
// int a,b,res;
// cout<<"Please enter a: "; cin>>a;
// cout<<"Please enter b: "; cin>>b;
// res = compute(a,b,&max);
// cout<<"max of a and b is "<<res<<endl;
// res = compute(a,b,&min);
// cout<<"min of a and b is "<<res<<endl;
// res = compute(a,b,&sum);
// cout<<"sum of a and b is "<<res<<endl;
// int array[10];
// int* search(int* a, int num);
// for(int i=0;i<10;i++){
// cin>>array[i];
// }
// int* zeroptr = search(array, 10);
// cout<<"Enter 3 float point numbers: "<<endl;
// for(int i=0;i<3;i++){
// float x, f;
// int n;
// cin>>x;
// splitFloat(x, &n, &f);
// cout<<"Integer part: "<<n<<" Fraction part: "<<f<<endl;
// }
// int line1[] = {1,2,3};
// int line2[] = {4,5,6};
// int line3[] = {7,8,9};
// int *pline[] = {line1,line2,line3};
// cout<<"Matrix test: "<<endl;
// for(int i=0;i<3;i++){
// for(int j=0;j<3;j++){
// cout<<pline[i][j]<<",";
// }
// cout<<endl;
// }
// int array[3] = {1,2,3};
// for(int &e:array){
// e += 2;
// cout<<e<<endl;
// }
// int table[3][4] = {{1, 2, 3, 4}, {2, 3, 4, 5}, {3, 4, 5, 6}};
// for (int i = 0; i < 3; i++) {
// for (int j = 0; j < 4; j++)
// cout << table[i][j] << " ";
// cout << endl;
// }
// rowSum(table, 3);
// for(int i=0;i<3;i++){
// cout << "Sum of row " << i << " is " << table[i][0] << endl;
// }
// const char key[] = {'a','c','b','a','d'};
// const int ques_num = 5;
// char usr_input;
// int ques = 0, correct_num = 0;
// cout<<"Enter the "<<ques_num<<" question tests:"<<endl;
// while(cin.get(usr_input)){
// if(usr_input != '\n'){
// if(usr_input == key[ques]){
// correct_num++;
// cout<<" ";
// }
// else{
// cout<<"*";
// }
// ques++;
// }
// else{
// cout<<"Score: "<<static_cast<float>(correct_num)/ques_num*100<<"%";
// ques = 0; correct_num = 0;cout<<endl;
// }
// }
// int f[20] = {1,1};
// for (int i=2;i<20;i++){
// f[i] = f[i-1] + f[i-2];
// }
// for (int i=0;i<20;i++){
// if(i%4 == 0)cout<<endl;
// cout.width(5);
// cout<<f[i];
// }
// cout<<endl;
// int a[10], b[10];
// for(int i = 0; i < 10; i++) {
// a[i] = i * 2 - 1;
// b[10 - i - 1] = a[i];
// }
// for(int i = 0; i < 10; i++) {
// cout << "a[" << i << "] = " << a[i] << " ";
// cout << "b[" << i << "] = " << b[i] << endl;
// }
return 0;
}
<commit_msg>new practice.<commit_after>#include <iostream>
#include <cmath>
#include <cstdlib>
#include <iomanip>
#include <string>
#include <vector>
using namespace std;
// void rowSum(int a[][4],int nRow){
// for(int i=0;i<nRow;i++){
// for(int j=0;j<4;j++){
// a[i][0] = a[i][j];
// }
// }
// }
// void splitFloat(float x,int *intPart, float *fracPart){
// *intPart = static_cast<int>(x);
// *fracPart = x - *intPart;
// }
// int* search(int* a, int num){
// for(int i=0;i<num;i++){
// if(a[i] == 0){
// return &a[i];
// }
// }
// }
// int compute(int a, int b,int(*func)(int,int)){
// return func(a,b);
// }
// int max(int a, int b){
// return((a>b)?a:b);
// }
// int min(int a, int b){
// return((a<b)?a:b);
// }
// int sum(int a, int b){
// return a+b;
// }
// class Point {
// public:
// Point(int x = 0, int y = 0) : x(x), y(y) { }
// int getX() const { return x; }
// int getY() const { return y; }
// private:
// int x, y;
// };
double average(const vector<double> &arr){
double sum = 0;
for(unsigned i=0;i<arr.size();i++){
sum += arr[i];
}
return sum/arr.size();
}
int main(){
unsigned n;
cout<<"n = ";
cin>>n;
vector<double> arr(n);
cout<<"Please input "<<n<<" real numbers: "<<endl;
for(int i=0;i<n;i++)
cin>>arr[i];
cout<<"Average = "<<average(arr)<<endl;
// int (*fp)[9][8] = new int[7][9][8];
// for (int i = 0; i < 7; i++)
// for (int j = 0; j < 9; j++)
// for (int k = 0; k < 8; k++)
// *(*(*(fp + i) + j) + k) = (i*100+j*10+k);
// for (int i = 0; i < 7; i++) {
// for (int j = 0; j < 9; j++) {
// for (int k = 0; k < 8; k++)
// cout<<fp[i][j][k]<<' ';
// cout<<endl;
// }
// cout<<endl;
// }
// delete[] fp;
// Point a(4,5);
// Point *ptr = &a;
// cout<<ptr->getX()<<endl;
// cout<<a.getX()<<endl;
// int a,b,res;
// cout<<"Please enter a: "; cin>>a;
// cout<<"Please enter b: "; cin>>b;
// res = compute(a,b,&max);
// cout<<"max of a and b is "<<res<<endl;
// res = compute(a,b,&min);
// cout<<"min of a and b is "<<res<<endl;
// res = compute(a,b,&sum);
// cout<<"sum of a and b is "<<res<<endl;
// int array[10];
// int* search(int* a, int num);
// for(int i=0;i<10;i++){
// cin>>array[i];
// }
// int* zeroptr = search(array, 10);
// cout<<"Enter 3 float point numbers: "<<endl;
// for(int i=0;i<3;i++){
// float x, f;
// int n;
// cin>>x;
// splitFloat(x, &n, &f);
// cout<<"Integer part: "<<n<<" Fraction part: "<<f<<endl;
// }
// int line1[] = {1,2,3};
// int line2[] = {4,5,6};
// int line3[] = {7,8,9};
// int *pline[] = {line1,line2,line3};
// cout<<"Matrix test: "<<endl;
// for(int i=0;i<3;i++){
// for(int j=0;j<3;j++){
// cout<<pline[i][j]<<",";
// }
// cout<<endl;
// }
// int array[3] = {1,2,3};
// for(int &e:array){
// e += 2;
// cout<<e<<endl;
// }
// int table[3][4] = {{1, 2, 3, 4}, {2, 3, 4, 5}, {3, 4, 5, 6}};
// for (int i = 0; i < 3; i++) {
// for (int j = 0; j < 4; j++)
// cout << table[i][j] << " ";
// cout << endl;
// }
// rowSum(table, 3);
// for(int i=0;i<3;i++){
// cout << "Sum of row " << i << " is " << table[i][0] << endl;
// }
// const char key[] = {'a','c','b','a','d'};
// const int ques_num = 5;
// char usr_input;
// int ques = 0, correct_num = 0;
// cout<<"Enter the "<<ques_num<<" question tests:"<<endl;
// while(cin.get(usr_input)){
// if(usr_input != '\n'){
// if(usr_input == key[ques]){
// correct_num++;
// cout<<" ";
// }
// else{
// cout<<"*";
// }
// ques++;
// }
// else{
// cout<<"Score: "<<static_cast<float>(correct_num)/ques_num*100<<"%";
// ques = 0; correct_num = 0;cout<<endl;
// }
// }
// int f[20] = {1,1};
// for (int i=2;i<20;i++){
// f[i] = f[i-1] + f[i-2];
// }
// for (int i=0;i<20;i++){
// if(i%4 == 0)cout<<endl;
// cout.width(5);
// cout<<f[i];
// }
// cout<<endl;
// int a[10], b[10];
// for(int i = 0; i < 10; i++) {
// a[i] = i * 2 - 1;
// b[10 - i - 1] = a[i];
// }
// for(int i = 0; i < 10; i++) {
// cout << "a[" << i << "] = " << a[i] << " ";
// cout << "b[" << i << "] = " << b[i] << endl;
// }
return 0;
}
<|endoftext|>
|
<commit_before>// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <unistd.h>
#include <new>
#include <functional>
#include <string>
#include <process/dispatch.hpp>
#include <process/io.hpp>
#include <process/process.hpp>
#include <stout/bytes.hpp>
#include <stout/error.hpp>
#include <stout/exit.hpp>
#include <stout/nothing.hpp>
#include <stout/path.hpp>
#include <stout/stringify.hpp>
#include <stout/try.hpp>
#include <stout/os/shell.hpp>
#include <stout/os/write.hpp>
#include "slave/container_loggers/logrotate.hpp"
using namespace process;
using namespace mesos::internal::logger::rotate;
class LogrotateLoggerProcess : public Process<LogrotateLoggerProcess>
{
public:
LogrotateLoggerProcess(const Flags& _flags)
: flags(_flags),
leading(None()),
bytesWritten(0)
{
// Prepare a buffer for reading from the `incoming` pipe.
length = sysconf(_SC_PAGE_SIZE);
buffer = new char[length];
}
virtual ~LogrotateLoggerProcess()
{
if (buffer != NULL) {
delete[] buffer;
buffer = NULL;
}
if (leading.isSome()) {
os::close(leading.get());
}
}
// Prepares and starts the loop which reads from stdin, writes to the
// leading log file, and manages total log size.
Future<Nothing> run()
{
// Populate the `logrotate` configuration file.
// See `Flags::logrotate_options` for the format.
//
// NOTE: We specify a size of `--max_size - length` because `logrotate`
// has slightly different size semantics. `logrotate` will rotate when the
// max size is *exceeded*. We rotate to keep files *under* the max size.
const std::string config =
"\"" + flags.log_filename.get() + "\" {\n" +
flags.logrotate_options.getOrElse("") + "\n" +
"size " + stringify(flags.max_size.bytes() - length) + "\n" +
"}";
Try<Nothing> result = os::write(
flags.log_filename.get() + CONF_SUFFIX, config);
if (result.isError()) {
return Failure("Failed to write configuration file: " + result.error());
}
// NOTE: This is a prerequisuite for `io::read`.
Try<Nothing> nonblock = os::nonblock(STDIN_FILENO);
if (nonblock.isError()) {
return Failure("Failed to set nonblocking pipe: " + nonblock.error());
}
// NOTE: This does not block.
loop();
return promise.future();
}
// Reads from stdin and writes to the leading log file.
void loop() {
io::read(STDIN_FILENO, buffer, length)
.then([&](size_t readSize) -> Future<Nothing> {
// Check if EOF has been reached on the input stream.
// This indicates that the container (whose logs are being
// piped to this process) has exited.
if (readSize <= 0) {
promise.set(Nothing());
return Nothing();
}
// Do log rotation (if necessary) and write the bytes to the
// leading log file.
Try<Nothing> result = write(readSize);
if (result.isError()) {
promise.fail("Failed to write: " + result.error());
return Nothing();
}
// Use `dispatch` to limit the size of the call stack.
dispatch(self(), &LogrotateLoggerProcess::loop);
return Nothing();
});
}
// Writes the buffer from stdin to the leading log file.
// When the number of written bytes exceeds `--max_size`, the leading
// log file is rotated. When the number of log files exceed `--max_files`,
// the oldest log file is deleted.
Try<Nothing> write(size_t readSize)
{
// Rotate the log file if it will grow beyond the `--max_size`.
if (bytesWritten + readSize > flags.max_size.bytes()) {
rotate();
}
// If the leading log file is not open, open it.
// NOTE: We open the file in append-mode as `logrotate` may sometimes fail.
if (leading.isNone()) {
Try<int> open = os::open(
flags.log_filename.get(),
O_WRONLY | O_CREAT | O_APPEND | O_CLOEXEC,
S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
if (open.isError()) {
return Error(
"Failed to open '" + flags.log_filename.get() +
"': " + open.error());
}
leading = open.get();
}
// Write from stdin to `leading`.
// NOTE: We do not exit on error here since we are prioritizing
// clearing the STDIN pipe (which would otherwise potentially block
// the container on write) over log fidelity.
Try<Nothing> result =
os::write(leading.get(), std::string(buffer, readSize));
if (result.isError()) {
std::cerr << "Failed to write: " << result.error() << std::endl;
}
bytesWritten += readSize;
return Nothing();
}
// Calls `logrotate` on the leading log file and resets the `bytesWritten`.
void rotate()
{
if (leading.isSome()) {
os::close(leading.get());
leading = None();
}
// Call `logrotate` to move around the files.
// NOTE: If `logrotate` fails for whatever reason, we will ignore
// the error and continue logging. In case the leading log file
// is not renamed, we will continue appending to the existing
// leading log file.
os::shell(
flags.logrotate_path +
" --state \"" + flags.log_filename.get() + STATE_SUFFIX + "\" \"" +
flags.log_filename.get() + CONF_SUFFIX + "\"");
// Reset the number of bytes written.
bytesWritten = 0;
}
private:
Flags flags;
// For reading from stdin.
char* buffer;
size_t length;
// For writing and rotating the leading log file.
Option<int> leading;
size_t bytesWritten;
// Used to capture when log rotation has completed because the
// underlying process/input has terminated.
Promise<Nothing> promise;
};
int main(int argc, char** argv)
{
Flags flags;
// Load and validate flags from the environment and command line.
Try<Nothing> load = flags.load(None(), &argc, &argv);
if (load.isError()) {
EXIT(EXIT_FAILURE) << flags.usage(load.error());
}
// Make sure this process is running in its own session.
// This ensures that, if the parent process (presumably the Mesos agent)
// terminates, this logger process will continue to run.
if (::setsid() == -1) {
EXIT(EXIT_FAILURE)
<< ErrnoError("Failed to put child in a new session").message;
}
// Asynchronously control the flow and size of logs.
LogrotateLoggerProcess process(flags);
spawn(&process);
// Wait for the logging process to finish.
Future<Nothing> status = dispatch(process, &LogrotateLoggerProcess::run);
status.await();
terminate(process);
wait(process);
return status.isReady() ? EXIT_SUCCESS : EXIT_FAILURE;
}
<commit_msg>Fixed style.<commit_after>// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <unistd.h>
#include <new>
#include <functional>
#include <string>
#include <process/dispatch.hpp>
#include <process/io.hpp>
#include <process/process.hpp>
#include <stout/bytes.hpp>
#include <stout/error.hpp>
#include <stout/exit.hpp>
#include <stout/nothing.hpp>
#include <stout/path.hpp>
#include <stout/stringify.hpp>
#include <stout/try.hpp>
#include <stout/os/shell.hpp>
#include <stout/os/write.hpp>
#include "slave/container_loggers/logrotate.hpp"
using namespace process;
using namespace mesos::internal::logger::rotate;
class LogrotateLoggerProcess : public Process<LogrotateLoggerProcess>
{
public:
LogrotateLoggerProcess(const Flags& _flags)
: flags(_flags),
leading(None()),
bytesWritten(0)
{
// Prepare a buffer for reading from the `incoming` pipe.
length = sysconf(_SC_PAGE_SIZE);
buffer = new char[length];
}
virtual ~LogrotateLoggerProcess()
{
if (buffer != NULL) {
delete[] buffer;
buffer = NULL;
}
if (leading.isSome()) {
os::close(leading.get());
}
}
// Prepares and starts the loop which reads from stdin, writes to the
// leading log file, and manages total log size.
Future<Nothing> run()
{
// Populate the `logrotate` configuration file.
// See `Flags::logrotate_options` for the format.
//
// NOTE: We specify a size of `--max_size - length` because `logrotate`
// has slightly different size semantics. `logrotate` will rotate when the
// max size is *exceeded*. We rotate to keep files *under* the max size.
const std::string config =
"\"" + flags.log_filename.get() + "\" {\n" +
flags.logrotate_options.getOrElse("") + "\n" +
"size " + stringify(flags.max_size.bytes() - length) + "\n" +
"}";
Try<Nothing> result = os::write(
flags.log_filename.get() + CONF_SUFFIX, config);
if (result.isError()) {
return Failure("Failed to write configuration file: " + result.error());
}
// NOTE: This is a prerequisuite for `io::read`.
Try<Nothing> nonblock = os::nonblock(STDIN_FILENO);
if (nonblock.isError()) {
return Failure("Failed to set nonblocking pipe: " + nonblock.error());
}
// NOTE: This does not block.
loop();
return promise.future();
}
// Reads from stdin and writes to the leading log file.
void loop()
{
io::read(STDIN_FILENO, buffer, length)
.then([&](size_t readSize) -> Future<Nothing> {
// Check if EOF has been reached on the input stream.
// This indicates that the container (whose logs are being
// piped to this process) has exited.
if (readSize <= 0) {
promise.set(Nothing());
return Nothing();
}
// Do log rotation (if necessary) and write the bytes to the
// leading log file.
Try<Nothing> result = write(readSize);
if (result.isError()) {
promise.fail("Failed to write: " + result.error());
return Nothing();
}
// Use `dispatch` to limit the size of the call stack.
dispatch(self(), &LogrotateLoggerProcess::loop);
return Nothing();
});
}
// Writes the buffer from stdin to the leading log file.
// When the number of written bytes exceeds `--max_size`, the leading
// log file is rotated. When the number of log files exceed `--max_files`,
// the oldest log file is deleted.
Try<Nothing> write(size_t readSize)
{
// Rotate the log file if it will grow beyond the `--max_size`.
if (bytesWritten + readSize > flags.max_size.bytes()) {
rotate();
}
// If the leading log file is not open, open it.
// NOTE: We open the file in append-mode as `logrotate` may sometimes fail.
if (leading.isNone()) {
Try<int> open = os::open(
flags.log_filename.get(),
O_WRONLY | O_CREAT | O_APPEND | O_CLOEXEC,
S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
if (open.isError()) {
return Error(
"Failed to open '" + flags.log_filename.get() +
"': " + open.error());
}
leading = open.get();
}
// Write from stdin to `leading`.
// NOTE: We do not exit on error here since we are prioritizing
// clearing the STDIN pipe (which would otherwise potentially block
// the container on write) over log fidelity.
Try<Nothing> result =
os::write(leading.get(), std::string(buffer, readSize));
if (result.isError()) {
std::cerr << "Failed to write: " << result.error() << std::endl;
}
bytesWritten += readSize;
return Nothing();
}
// Calls `logrotate` on the leading log file and resets the `bytesWritten`.
void rotate()
{
if (leading.isSome()) {
os::close(leading.get());
leading = None();
}
// Call `logrotate` to move around the files.
// NOTE: If `logrotate` fails for whatever reason, we will ignore
// the error and continue logging. In case the leading log file
// is not renamed, we will continue appending to the existing
// leading log file.
os::shell(
flags.logrotate_path +
" --state \"" + flags.log_filename.get() + STATE_SUFFIX + "\" \"" +
flags.log_filename.get() + CONF_SUFFIX + "\"");
// Reset the number of bytes written.
bytesWritten = 0;
}
private:
Flags flags;
// For reading from stdin.
char* buffer;
size_t length;
// For writing and rotating the leading log file.
Option<int> leading;
size_t bytesWritten;
// Used to capture when log rotation has completed because the
// underlying process/input has terminated.
Promise<Nothing> promise;
};
int main(int argc, char** argv)
{
Flags flags;
// Load and validate flags from the environment and command line.
Try<Nothing> load = flags.load(None(), &argc, &argv);
if (load.isError()) {
EXIT(EXIT_FAILURE) << flags.usage(load.error());
}
// Make sure this process is running in its own session.
// This ensures that, if the parent process (presumably the Mesos agent)
// terminates, this logger process will continue to run.
if (::setsid() == -1) {
EXIT(EXIT_FAILURE)
<< ErrnoError("Failed to put child in a new session").message;
}
// Asynchronously control the flow and size of logs.
LogrotateLoggerProcess process(flags);
spawn(&process);
// Wait for the logging process to finish.
Future<Nothing> status = dispatch(process, &LogrotateLoggerProcess::run);
status.await();
terminate(process);
wait(process);
return status.isReady() ? EXIT_SUCCESS : EXIT_FAILURE;
}
<|endoftext|>
|
<commit_before>#include <camera.hpp>
Camera::Camera():
name_{"Camera_Obscura"},
eye_{ 0.0,0.0,0.0 },
direction_{ 0,-1,0 },
up_{ 0.0,0.0,0.0 },
fovX_{ 0.0 }
{}
Camera::Camera(glm::vec3 const& pos) :
name_{"Camera_Obscura"},
eye_{ pos },
direction_{0,-1,0},
up_{ 0.0,0.0,0.0 },
fovX_{0.0}
{}
Camera::Camera(std::string const& name, glm::vec3 const& pos, glm::vec3 const& dir, float& fov_x, glm::vec3 const& up) :
name_{ name },
eye_{ pos },
direction_{ dir },
up_{ up },
fovX_{ fov_x }
{}
Camera::Camera(Camera const& cam) :
name_{ cam.name },
eye_{ cam.eye },
direction_{ cam.direction },
up_{ cam.up },
fovX_{ cam.fov_x }
{}
Camera::~Camera(){}
std::string Camera::get_name() const {
return name_;
}
glm::vec3 Camera::get_position() const {
return eye_;
}
glm::vec3 Camera::get_direction() const {
return direction_;
}
glm::vec3 Camera::get_up() const {
return up_;
}
float Camera::get_fov_x() const {
return fovX_;
}
<commit_msg>member fix die zweite<commit_after>#include <camera.hpp>
Camera::Camera():
name_{"Camera_Obscura"},
eye_{ 0.0,0.0,0.0 },
direction_{ 0,-1,0 },
up_{ 0.0,0.0,0.0 },
fovX_{ 0.0 }
{}
Camera::Camera(glm::vec3 const& pos) :
name_{"Camera_Obscura"},
eye_{ pos },
direction_{0,-1,0},
up_{ 0.0,0.0,0.0 },
fovX_{0.0}
{}
Camera::Camera(std::string const& name, glm::vec3 const& pos, glm::vec3 const& dir, float& fov, glm::vec3 const& up) :
name_{ name },
eye_{ pos },
direction_{ dir },
up_{ up },
fovX_{ fov }
{}
Camera::Camera(Camera const& cam) :
name_{ cam.name_ },
eye_{ cam.eye_ },
direction_{ cam.direction_ },
up_{ cam.up_ },
fovX_{ cam.fovX_ }
{}
Camera::~Camera(){}
std::string Camera::get_name() const {
return name_;
}
glm::vec3 Camera::get_position() const {
return eye_;
}
glm::vec3 Camera::get_direction() const {
return direction_;
}
glm::vec3 Camera::get_up() const {
return up_;
}
float Camera::get_fov_x() const {
return fovX_;
}
<|endoftext|>
|
<commit_before>/*++
Copyright (c) 2012 Microsoft Corporation
Module Name:
fpa2bv_model_converter.h
Abstract:
Model conversion for fpa2bv_converter
Author:
Christoph (cwinter) 2012-02-09
Notes:
--*/
#include"ast_smt2_pp.h"
#include"fpa2bv_model_converter.h"
void fpa2bv_model_converter::display(std::ostream & out) {
out << "(fpa2bv-model-converter";
for (obj_map<func_decl, expr*>::iterator it = m_const2bv.begin();
it != m_const2bv.end();
it++) {
const symbol & n = it->m_key->get_name();
out << "\n (" << n << " ";
unsigned indent = n.size() + 4;
out << mk_ismt2_pp(it->m_value, m, indent) << ")";
}
for (obj_map<func_decl, expr*>::iterator it = m_rm_const2bv.begin();
it != m_rm_const2bv.end();
it++) {
const symbol & n = it->m_key->get_name();
out << "\n (" << n << " ";
unsigned indent = n.size() + 4;
out << mk_ismt2_pp(it->m_value, m, indent) << ")";
}
for (obj_map<func_decl, func_decl*>::iterator it = m_uf2bvuf.begin();
it != m_uf2bvuf.end();
it++) {
const symbol & n = it->m_key->get_name();
out << "\n (" << n << " ";
unsigned indent = n.size() + 4;
out << mk_ismt2_pp(it->m_value, m, indent) << ")";
}
for (obj_map<func_decl, func_decl_triple>::iterator it = m_uf23bvuf.begin();
it != m_uf23bvuf.end();
it++) {
const symbol & n = it->m_key->get_name();
out << "\n (" << n << " ";
unsigned indent = n.size() + 4;
out << mk_ismt2_pp(it->m_value.f_sgn, m, indent) << " ; " <<
mk_ismt2_pp(it->m_value.f_sig, m, indent) << " ; " <<
mk_ismt2_pp(it->m_value.f_exp, m, indent) << " ; " <<
")";
}
out << ")" << std::endl;
}
model_converter * fpa2bv_model_converter::translate(ast_translation & translator) {
fpa2bv_model_converter * res = alloc(fpa2bv_model_converter, translator.to());
for (obj_map<func_decl, expr*>::iterator it = m_const2bv.begin();
it != m_const2bv.end();
it++)
{
func_decl * k = translator(it->m_key);
expr * v = translator(it->m_value);
res->m_const2bv.insert(k, v);
translator.to().inc_ref(k);
translator.to().inc_ref(v);
}
for (obj_map<func_decl, expr*>::iterator it = m_rm_const2bv.begin();
it != m_rm_const2bv.end();
it++)
{
func_decl * k = translator(it->m_key);
expr * v = translator(it->m_value);
res->m_rm_const2bv.insert(k, v);
translator.to().inc_ref(k);
translator.to().inc_ref(v);
}
return res;
}
void fpa2bv_model_converter::convert(model * bv_mdl, model * float_mdl) {
float_util fu(m);
bv_util bu(m);
mpf fp_val;
unsynch_mpz_manager & mpzm = fu.fm().mpz_manager();
unsynch_mpq_manager & mpqm = fu.fm().mpq_manager();
TRACE("fpa2bv_mc", tout << "BV Model: " << std::endl;
for (unsigned i = 0; i < bv_mdl->get_num_constants(); i++)
tout << bv_mdl->get_constant(i)->get_name() << " --> " <<
mk_ismt2_pp(bv_mdl->get_const_interp(bv_mdl->get_constant(i)), m) << std::endl;
);
obj_hashtable<func_decl> seen;
for (obj_map<func_decl, expr*>::iterator it = m_const2bv.begin();
it != m_const2bv.end();
it++)
{
func_decl * var = it->m_key;
app * a = to_app(it->m_value);
SASSERT(fu.is_float(var->get_range()));
SASSERT(var->get_range()->get_num_parameters() == 2);
unsigned ebits = fu.get_ebits(var->get_range());
unsigned sbits = fu.get_sbits(var->get_range());
expr_ref sgn(m), sig(m), exp(m);
bv_mdl->eval(a->get_arg(0), sgn, true);
bv_mdl->eval(a->get_arg(1), sig, true);
bv_mdl->eval(a->get_arg(2), exp, true);
SASSERT(a->is_app_of(fu.get_family_id(), OP_FLOAT_TO_FP));
#ifdef Z3DEBUG
SASSERT(to_app(a->get_arg(0))->get_decl()->get_arity() == 0);
SASSERT(to_app(a->get_arg(1))->get_decl()->get_arity() == 0);
SASSERT(to_app(a->get_arg(1))->get_decl()->get_arity() == 0);
seen.insert(to_app(a->get_arg(0))->get_decl());
seen.insert(to_app(a->get_arg(1))->get_decl());
seen.insert(to_app(a->get_arg(2))->get_decl());
#else
SASSERT(a->get_arg(0)->get_kind() == OP_EXTRACT);
SASSERT(to_app(a->get_arg(0))->get_arg(0)->get_kind() == OP_EXTRACT);
seen.insert(to_app(to_app(a->get_arg(0))->get_arg(0))->get_decl());
#endif
if (!sgn && !sig && !exp)
continue;
unsigned sgn_sz = bu.get_bv_size(m.get_sort(a->get_arg(0)));
unsigned sig_sz = bu.get_bv_size(m.get_sort(a->get_arg(1))) - 1;
unsigned exp_sz = bu.get_bv_size(m.get_sort(a->get_arg(2)));
rational sgn_q(0), sig_q(0), exp_q(0);
if (sgn) bu.is_numeral(sgn, sgn_q, sgn_sz);
if (sig) bu.is_numeral(sig, sig_q, sig_sz);
if (exp) bu.is_numeral(exp, exp_q, exp_sz);
// un-bias exponent
rational exp_unbiased_q;
exp_unbiased_q = exp_q - fu.fm().m_powers2.m1(ebits - 1);
mpz sig_z; mpf_exp_t exp_z;
mpzm.set(sig_z, sig_q.to_mpq().numerator());
exp_z = mpzm.get_int64(exp_unbiased_q.to_mpq().numerator());
TRACE("fpa2bv_mc", tout << var->get_name() << " == [" << sgn_q.to_string() << " " <<
mpzm.to_string(sig_z) << " " << exp_z << "(" << exp_q.to_string() << ")]" << std::endl;);
fu.fm().set(fp_val, ebits, sbits, !mpqm.is_zero(sgn_q.to_mpq()), sig_z, exp_z);
float_mdl->register_decl(var, fu.mk_value(fp_val));
mpzm.del(sig_z);
}
for (obj_map<func_decl, expr*>::iterator it = m_rm_const2bv.begin();
it != m_rm_const2bv.end();
it++)
{
func_decl * var = it->m_key;
expr * v = it->m_value;
expr_ref eval_v(m);
SASSERT(fu.is_rm(var->get_range()));
rational bv_val(0);
unsigned sz = 0;
if (v && bv_mdl->eval(v, eval_v, true) && bu.is_numeral(eval_v, bv_val, sz)) {
TRACE("fpa2bv_mc", tout << var->get_name() << " == " << bv_val.to_string() << std::endl;);
SASSERT(bv_val.is_uint64());
switch (bv_val.get_uint64())
{
case BV_RM_TIES_TO_AWAY: float_mdl->register_decl(var, fu.mk_round_nearest_ties_to_away()); break;
case BV_RM_TIES_TO_EVEN: float_mdl->register_decl(var, fu.mk_round_nearest_ties_to_even()); break;
case BV_RM_TO_NEGATIVE: float_mdl->register_decl(var, fu.mk_round_toward_negative()); break;
case BV_RM_TO_POSITIVE: float_mdl->register_decl(var, fu.mk_round_toward_positive()); break;
case BV_RM_TO_ZERO:
default: float_mdl->register_decl(var, fu.mk_round_toward_zero());
}
SASSERT(v->get_kind() == AST_APP);
seen.insert(to_app(v)->get_decl());
}
}
for (obj_map<func_decl, func_decl*>::iterator it = m_uf2bvuf.begin();
it != m_uf2bvuf.end();
it++)
seen.insert(it->m_value);
for (obj_map<func_decl, func_decl_triple>::iterator it = m_uf23bvuf.begin();
it != m_uf23bvuf.end();
it++)
{
seen.insert(it->m_value.f_sgn);
seen.insert(it->m_value.f_sig);
seen.insert(it->m_value.f_exp);
}
fu.fm().del(fp_val);
// Keep all the non-float constants.
unsigned sz = bv_mdl->get_num_constants();
for (unsigned i = 0; i < sz; i++)
{
func_decl * c = bv_mdl->get_constant(i);
if (!seen.contains(c))
float_mdl->register_decl(c, bv_mdl->get_const_interp(c));
}
// And keep everything else
sz = bv_mdl->get_num_functions();
for (unsigned i = 0; i < sz; i++)
{
func_decl * f = bv_mdl->get_function(i);
if (!seen.contains(f))
{
TRACE("fpa2bv_mc", tout << "Keeping: " << mk_ismt2_pp(f, m) << std::endl;);
func_interp * val = bv_mdl->get_func_interp(f);
float_mdl->register_decl(f, val);
}
}
sz = bv_mdl->get_num_uninterpreted_sorts();
for (unsigned i = 0; i < sz; i++)
{
sort * s = bv_mdl->get_uninterpreted_sort(i);
ptr_vector<expr> u = bv_mdl->get_universe(s);
float_mdl->register_usort(s, u.size(), u.c_ptr());
}
}
model_converter * mk_fpa2bv_model_converter(ast_manager & m,
obj_map<func_decl, expr*> const & const2bv,
obj_map<func_decl, expr*> const & rm_const2bv,
obj_map<func_decl, func_decl*> const & uf2bvuf,
obj_map<func_decl, func_decl_triple> const & uf23bvuf) {
return alloc(fpa2bv_model_converter, m, const2bv, rm_const2bv, uf2bvuf, uf23bvuf);
}
<commit_msg>fpa2bv: adjustments for consistency<commit_after>/*++
Copyright (c) 2012 Microsoft Corporation
Module Name:
fpa2bv_model_converter.h
Abstract:
Model conversion for fpa2bv_converter
Author:
Christoph (cwinter) 2012-02-09
Notes:
--*/
#include"ast_smt2_pp.h"
#include"fpa2bv_model_converter.h"
void fpa2bv_model_converter::display(std::ostream & out) {
out << "(fpa2bv-model-converter";
for (obj_map<func_decl, expr*>::iterator it = m_const2bv.begin();
it != m_const2bv.end();
it++) {
const symbol & n = it->m_key->get_name();
out << "\n (" << n << " ";
unsigned indent = n.size() + 4;
out << mk_ismt2_pp(it->m_value, m, indent) << ")";
}
for (obj_map<func_decl, expr*>::iterator it = m_rm_const2bv.begin();
it != m_rm_const2bv.end();
it++) {
const symbol & n = it->m_key->get_name();
out << "\n (" << n << " ";
unsigned indent = n.size() + 4;
out << mk_ismt2_pp(it->m_value, m, indent) << ")";
}
for (obj_map<func_decl, func_decl*>::iterator it = m_uf2bvuf.begin();
it != m_uf2bvuf.end();
it++) {
const symbol & n = it->m_key->get_name();
out << "\n (" << n << " ";
unsigned indent = n.size() + 4;
out << mk_ismt2_pp(it->m_value, m, indent) << ")";
}
for (obj_map<func_decl, func_decl_triple>::iterator it = m_uf23bvuf.begin();
it != m_uf23bvuf.end();
it++) {
const symbol & n = it->m_key->get_name();
out << "\n (" << n << " ";
unsigned indent = n.size() + 4;
out << mk_ismt2_pp(it->m_value.f_sgn, m, indent) << " ; " <<
mk_ismt2_pp(it->m_value.f_sig, m, indent) << " ; " <<
mk_ismt2_pp(it->m_value.f_exp, m, indent) << " ; " <<
")";
}
out << ")" << std::endl;
}
model_converter * fpa2bv_model_converter::translate(ast_translation & translator) {
fpa2bv_model_converter * res = alloc(fpa2bv_model_converter, translator.to());
for (obj_map<func_decl, expr*>::iterator it = m_const2bv.begin();
it != m_const2bv.end();
it++)
{
func_decl * k = translator(it->m_key);
expr * v = translator(it->m_value);
res->m_const2bv.insert(k, v);
translator.to().inc_ref(k);
translator.to().inc_ref(v);
}
for (obj_map<func_decl, expr*>::iterator it = m_rm_const2bv.begin();
it != m_rm_const2bv.end();
it++)
{
func_decl * k = translator(it->m_key);
expr * v = translator(it->m_value);
res->m_rm_const2bv.insert(k, v);
translator.to().inc_ref(k);
translator.to().inc_ref(v);
}
return res;
}
void fpa2bv_model_converter::convert(model * bv_mdl, model * float_mdl) {
float_util fu(m);
bv_util bu(m);
mpf fp_val;
unsynch_mpz_manager & mpzm = fu.fm().mpz_manager();
unsynch_mpq_manager & mpqm = fu.fm().mpq_manager();
TRACE("fpa2bv_mc", tout << "BV Model: " << std::endl;
for (unsigned i = 0; i < bv_mdl->get_num_constants(); i++)
tout << bv_mdl->get_constant(i)->get_name() << " --> " <<
mk_ismt2_pp(bv_mdl->get_const_interp(bv_mdl->get_constant(i)), m) << std::endl;
);
obj_hashtable<func_decl> seen;
for (obj_map<func_decl, expr*>::iterator it = m_const2bv.begin();
it != m_const2bv.end();
it++)
{
func_decl * var = it->m_key;
app * a = to_app(it->m_value);
SASSERT(fu.is_float(var->get_range()));
SASSERT(var->get_range()->get_num_parameters() == 2);
unsigned ebits = fu.get_ebits(var->get_range());
unsigned sbits = fu.get_sbits(var->get_range());
expr_ref sgn(m), sig(m), exp(m);
bv_mdl->eval(a->get_arg(0), sgn, true);
bv_mdl->eval(a->get_arg(1), exp, true);
bv_mdl->eval(a->get_arg(2), sig, true);
SASSERT(a->is_app_of(fu.get_family_id(), OP_FLOAT_TO_FP));
#ifdef Z3DEBUG
SASSERT(to_app(a->get_arg(0))->get_decl()->get_arity() == 0);
SASSERT(to_app(a->get_arg(1))->get_decl()->get_arity() == 0);
SASSERT(to_app(a->get_arg(2))->get_decl()->get_arity() == 0);
seen.insert(to_app(a->get_arg(0))->get_decl());
seen.insert(to_app(a->get_arg(1))->get_decl());
seen.insert(to_app(a->get_arg(2))->get_decl());
#else
SASSERT(a->get_arg(0)->get_kind() == OP_EXTRACT);
SASSERT(to_app(a->get_arg(0))->get_arg(0)->get_kind() == OP_EXTRACT);
seen.insert(to_app(to_app(a->get_arg(0))->get_arg(0))->get_decl());
#endif
if (!sgn && !sig && !exp)
continue;
unsigned sgn_sz = bu.get_bv_size(m.get_sort(a->get_arg(0)));
unsigned exp_sz = bu.get_bv_size(m.get_sort(a->get_arg(1)));
unsigned sig_sz = bu.get_bv_size(m.get_sort(a->get_arg(2))) - 1;
rational sgn_q(0), sig_q(0), exp_q(0);
if (sgn) bu.is_numeral(sgn, sgn_q, sgn_sz);
if (sig) bu.is_numeral(sig, sig_q, sig_sz);
if (exp) bu.is_numeral(exp, exp_q, exp_sz);
// un-bias exponent
rational exp_unbiased_q;
exp_unbiased_q = exp_q - fu.fm().m_powers2.m1(ebits - 1);
mpz sig_z; mpf_exp_t exp_z;
mpzm.set(sig_z, sig_q.to_mpq().numerator());
exp_z = mpzm.get_int64(exp_unbiased_q.to_mpq().numerator());
TRACE("fpa2bv_mc", tout << var->get_name() << " == [" << sgn_q.to_string() << " " <<
mpzm.to_string(sig_z) << " " << exp_z << "(" << exp_q.to_string() << ")]" << std::endl;);
fu.fm().set(fp_val, ebits, sbits, !mpqm.is_zero(sgn_q.to_mpq()), sig_z, exp_z);
float_mdl->register_decl(var, fu.mk_value(fp_val));
mpzm.del(sig_z);
}
for (obj_map<func_decl, expr*>::iterator it = m_rm_const2bv.begin();
it != m_rm_const2bv.end();
it++)
{
func_decl * var = it->m_key;
expr * v = it->m_value;
expr_ref eval_v(m);
SASSERT(fu.is_rm(var->get_range()));
rational bv_val(0);
unsigned sz = 0;
if (v && bv_mdl->eval(v, eval_v, true) && bu.is_numeral(eval_v, bv_val, sz)) {
TRACE("fpa2bv_mc", tout << var->get_name() << " == " << bv_val.to_string() << std::endl;);
SASSERT(bv_val.is_uint64());
switch (bv_val.get_uint64())
{
case BV_RM_TIES_TO_AWAY: float_mdl->register_decl(var, fu.mk_round_nearest_ties_to_away()); break;
case BV_RM_TIES_TO_EVEN: float_mdl->register_decl(var, fu.mk_round_nearest_ties_to_even()); break;
case BV_RM_TO_NEGATIVE: float_mdl->register_decl(var, fu.mk_round_toward_negative()); break;
case BV_RM_TO_POSITIVE: float_mdl->register_decl(var, fu.mk_round_toward_positive()); break;
case BV_RM_TO_ZERO:
default: float_mdl->register_decl(var, fu.mk_round_toward_zero());
}
SASSERT(v->get_kind() == AST_APP);
seen.insert(to_app(v)->get_decl());
}
}
for (obj_map<func_decl, func_decl*>::iterator it = m_uf2bvuf.begin();
it != m_uf2bvuf.end();
it++)
seen.insert(it->m_value);
for (obj_map<func_decl, func_decl_triple>::iterator it = m_uf23bvuf.begin();
it != m_uf23bvuf.end();
it++)
{
seen.insert(it->m_value.f_sgn);
seen.insert(it->m_value.f_sig);
seen.insert(it->m_value.f_exp);
}
fu.fm().del(fp_val);
// Keep all the non-float constants.
unsigned sz = bv_mdl->get_num_constants();
for (unsigned i = 0; i < sz; i++)
{
func_decl * c = bv_mdl->get_constant(i);
if (!seen.contains(c))
float_mdl->register_decl(c, bv_mdl->get_const_interp(c));
}
// And keep everything else
sz = bv_mdl->get_num_functions();
for (unsigned i = 0; i < sz; i++)
{
func_decl * f = bv_mdl->get_function(i);
if (!seen.contains(f))
{
TRACE("fpa2bv_mc", tout << "Keeping: " << mk_ismt2_pp(f, m) << std::endl;);
func_interp * val = bv_mdl->get_func_interp(f);
float_mdl->register_decl(f, val);
}
}
sz = bv_mdl->get_num_uninterpreted_sorts();
for (unsigned i = 0; i < sz; i++)
{
sort * s = bv_mdl->get_uninterpreted_sort(i);
ptr_vector<expr> u = bv_mdl->get_universe(s);
float_mdl->register_usort(s, u.size(), u.c_ptr());
}
}
model_converter * mk_fpa2bv_model_converter(ast_manager & m,
obj_map<func_decl, expr*> const & const2bv,
obj_map<func_decl, expr*> const & rm_const2bv,
obj_map<func_decl, func_decl*> const & uf2bvuf,
obj_map<func_decl, func_decl_triple> const & uf23bvuf) {
return alloc(fpa2bv_model_converter, m, const2bv, rm_const2bv, uf2bvuf, uf23bvuf);
}
<|endoftext|>
|
<commit_before>/* ---------------------------------------------------------------------
* Numenta Platform for Intelligent Computing (NuPIC)
* Copyright (C) 2018, Numenta, Inc. Unless you have an agreement
* with Numenta, Inc., for a separate license for this software code, the
* following terms and conditions apply:
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero Public License version 3 as
* published by the Free Software Foundation.
*
* 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 Public License for more details.
*
* You should have received a copy of the GNU Affero Public License
* along with this program. If not, see http://www.gnu.org/licenses.
*
* http://numenta.org/licenses/
*
* Author: @chhenning, 2018
* ---------------------------------------------------------------------
*/
/** @file
Definition of the PyBindRegion class. The base class for all Python Region implementations.
*/
#ifndef NTA_PYBIND_REGION_HPP
#define NTA_PYBIND_REGION_HPP
// the use of 'register' keyword is removed in C++17
// Python2.7 uses 'register' in unicodeobject.h
#ifdef _WIN32
#pragma warning( disable : 5033) // MSVC
#else
#pragma GCC diagnostic ignored "-Wregister" // for GCC and CLang
#endif
#include <bindings/suppress_register.hpp> //include before pybind11.h
#include <pybind11/pybind11.h>
#include <nupic/engine/RegionImpl.hpp>
#include <nupic/engine/Spec.hpp>
#include <nupic/ntypes/Value.hpp>
#include <string>
#include <vector>
#include <set>
namespace nupic
{
class PyBindRegion : public RegionImpl
{
typedef std::map<std::string, Spec> SpecMap;
public:
// Used by RegionImplFactory via RegisterRegionImplPy to create and cache a nodespec
static void createSpec(const char * module, Spec& ns, const char* classname = "");
// called by .py code on an already instantiated instance.
const Spec & getSpec() { return nodeSpec_; }
// Used by RegisterRegionImplPy to destroy a node spec when clearing its cache
static void destroySpec(const char * nodeType, const char* className = "");
// Constructors
PyBindRegion() = delete;
PyBindRegion(const char* module, const ValueMap& nodeParams, Region *region, const char* className);
PyBindRegion(const char* module, BundleIO& bundle, Region* region, const char* className);
// no copy constructor
PyBindRegion(const Region &) = delete;
// Destructor
virtual ~PyBindRegion();
// Manual serialization methods. Current recommended method.
void serialize(BundleIO& bundle) override;
void deserialize(BundleIO& bundle) override;
////////////////////////////
// RegionImpl
////////////////////////////
size_t getNodeOutputElementCount(const std::string& outputName) override;
void getParameterFromBuffer(const std::string& name, Int64 index, IWriteBuffer& value) override;
void setParameterFromBuffer(const std::string& name, Int64 index, IReadBuffer& value) override;
void initialize() override;
void compute() override;
std::string executeCommand(const std::vector<std::string>& args, Int64 index) override;
size_t getParameterArrayCount(const std::string& name, Int64 index) override;
virtual Byte getParameterByte(const std::string& name, Int64 index);
virtual Int32 getParameterInt32(const std::string& name, Int64 index) override;
virtual UInt32 getParameterUInt32(const std::string& name, Int64 index) override;
virtual Int64 getParameterInt64(const std::string& name, Int64 index) override;
virtual UInt64 getParameterUInt64(const std::string& name, Int64 index) override;
virtual Real32 getParameterReal32(const std::string& name, Int64 index) override;
virtual Real64 getParameterReal64(const std::string& name, Int64 index) override;
virtual Handle getParameterHandle(const std::string& name, Int64 index) override;
virtual bool getParameterBool(const std::string& name, Int64 index) override;
virtual std::string getParameterString(const std::string& name, Int64 index) override;
virtual void setParameterByte(const std::string& name, Int64 index, Byte value);
virtual void setParameterInt32(const std::string& name, Int64 index, Int32 value) override;
virtual void setParameterUInt32(const std::string& name, Int64 index, UInt32 value) override;
virtual void setParameterInt64(const std::string& name, Int64 index, Int64 value) override;
virtual void setParameterUInt64(const std::string& name, Int64 index, UInt64 value) override;
virtual void setParameterReal32(const std::string& name, Int64 index, Real32 value) override;
virtual void setParameterReal64(const std::string& name, Int64 index, Real64 value) override;
virtual void setParameterHandle(const std::string& name, Int64 index, Handle value) override;
virtual void setParameterBool(const std::string& name, Int64 index, bool value) override;
virtual void setParameterString(const std::string& name, Int64 index, const std::string& value) override;
virtual void getParameterArray(const std::string& name, Int64 index, Array & array) override;
virtual void setParameterArray(const std::string& name, Int64 index, const Array & array) override;
// Helper methods
template <typename T>
T getParameterT(const std::string & name, Int64 index);
template <typename T>
void setParameterT(const std::string & name, Int64 index, T value);
private:
std::string module_;
std::string className_;
pybind11::object node_;
static std::string last_error;
Spec nodeSpec_; // locally cached version of spec.
};
} // namespace nupic
#endif //NTA_PYBIND_REGION_HPP
<commit_msg>one more fix for travis<commit_after>/* ---------------------------------------------------------------------
* Numenta Platform for Intelligent Computing (NuPIC)
* Copyright (C) 2018, Numenta, Inc. Unless you have an agreement
* with Numenta, Inc., for a separate license for this software code, the
* following terms and conditions apply:
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero Public License version 3 as
* published by the Free Software Foundation.
*
* 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 Public License for more details.
*
* You should have received a copy of the GNU Affero Public License
* along with this program. If not, see http://www.gnu.org/licenses.
*
* http://numenta.org/licenses/
*
* Author: @chhenning, 2018
* ---------------------------------------------------------------------
*/
/** @file
Definition of the PyBindRegion class. The base class for all Python Region implementations.
*/
#ifndef NTA_PYBIND_REGION_HPP
#define NTA_PYBIND_REGION_HPP
#include <bindings/suppress_register.hpp> //include before pybind11.h
#include <pybind11/pybind11.h>
#include <nupic/engine/RegionImpl.hpp>
#include <nupic/engine/Spec.hpp>
#include <nupic/ntypes/Value.hpp>
#include <string>
#include <vector>
#include <set>
namespace nupic
{
class PyBindRegion : public RegionImpl
{
typedef std::map<std::string, Spec> SpecMap;
public:
// Used by RegionImplFactory via RegisterRegionImplPy to create and cache a nodespec
static void createSpec(const char * module, Spec& ns, const char* classname = "");
// called by .py code on an already instantiated instance.
const Spec & getSpec() { return nodeSpec_; }
// Used by RegisterRegionImplPy to destroy a node spec when clearing its cache
static void destroySpec(const char * nodeType, const char* className = "");
// Constructors
PyBindRegion() = delete;
PyBindRegion(const char* module, const ValueMap& nodeParams, Region *region, const char* className);
PyBindRegion(const char* module, BundleIO& bundle, Region* region, const char* className);
// no copy constructor
PyBindRegion(const Region &) = delete;
// Destructor
virtual ~PyBindRegion();
// Manual serialization methods. Current recommended method.
void serialize(BundleIO& bundle) override;
void deserialize(BundleIO& bundle) override;
////////////////////////////
// RegionImpl
////////////////////////////
size_t getNodeOutputElementCount(const std::string& outputName) override;
void getParameterFromBuffer(const std::string& name, Int64 index, IWriteBuffer& value) override;
void setParameterFromBuffer(const std::string& name, Int64 index, IReadBuffer& value) override;
void initialize() override;
void compute() override;
std::string executeCommand(const std::vector<std::string>& args, Int64 index) override;
size_t getParameterArrayCount(const std::string& name, Int64 index) override;
virtual Byte getParameterByte(const std::string& name, Int64 index);
virtual Int32 getParameterInt32(const std::string& name, Int64 index) override;
virtual UInt32 getParameterUInt32(const std::string& name, Int64 index) override;
virtual Int64 getParameterInt64(const std::string& name, Int64 index) override;
virtual UInt64 getParameterUInt64(const std::string& name, Int64 index) override;
virtual Real32 getParameterReal32(const std::string& name, Int64 index) override;
virtual Real64 getParameterReal64(const std::string& name, Int64 index) override;
virtual Handle getParameterHandle(const std::string& name, Int64 index) override;
virtual bool getParameterBool(const std::string& name, Int64 index) override;
virtual std::string getParameterString(const std::string& name, Int64 index) override;
virtual void setParameterByte(const std::string& name, Int64 index, Byte value);
virtual void setParameterInt32(const std::string& name, Int64 index, Int32 value) override;
virtual void setParameterUInt32(const std::string& name, Int64 index, UInt32 value) override;
virtual void setParameterInt64(const std::string& name, Int64 index, Int64 value) override;
virtual void setParameterUInt64(const std::string& name, Int64 index, UInt64 value) override;
virtual void setParameterReal32(const std::string& name, Int64 index, Real32 value) override;
virtual void setParameterReal64(const std::string& name, Int64 index, Real64 value) override;
virtual void setParameterHandle(const std::string& name, Int64 index, Handle value) override;
virtual void setParameterBool(const std::string& name, Int64 index, bool value) override;
virtual void setParameterString(const std::string& name, Int64 index, const std::string& value) override;
virtual void getParameterArray(const std::string& name, Int64 index, Array & array) override;
virtual void setParameterArray(const std::string& name, Int64 index, const Array & array) override;
// Helper methods
template <typename T>
T getParameterT(const std::string & name, Int64 index);
template <typename T>
void setParameterT(const std::string & name, Int64 index, T value);
private:
std::string module_;
std::string className_;
pybind11::object node_;
static std::string last_error;
Spec nodeSpec_; // locally cached version of spec.
};
} // namespace nupic
#endif //NTA_PYBIND_REGION_HPP
<|endoftext|>
|
<commit_before>/*
This file is part of solidity.
solidity 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.
solidity 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 solidity. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @author Christian <[email protected]>
* @date 2016
* Unit tests for inline assembly.
*/
#include <string>
#include <memory>
#include <libevmasm/Assembly.h>
#include <libsolidity/parsing/Scanner.h>
#include <libsolidity/inlineasm/AsmStack.h>
#include <libsolidity/interface/Exceptions.h>
#include <libsolidity/ast/AST.h>
#include "../TestHelper.h"
using namespace std;
namespace dev
{
namespace solidity
{
namespace test
{
namespace
{
bool successParse(std::string const& _source, bool _assemble = false, bool _allowWarnings = true)
{
assembly::InlineAssemblyStack stack;
try
{
if (!stack.parse(std::make_shared<Scanner>(CharStream(_source))))
return false;
if (_assemble)
{
stack.assemble();
if (!stack.errors().empty())
if (!_allowWarnings || !Error::containsOnlyWarnings(stack.errors()))
return false;
}
}
catch (FatalError const&)
{
if (Error::containsErrorOfType(stack.errors(), Error::Type::ParserError))
return false;
}
if (Error::containsErrorOfType(stack.errors(), Error::Type::ParserError))
return false;
BOOST_CHECK(Error::containsOnlyWarnings(stack.errors()));
return true;
}
bool successAssemble(string const& _source, bool _allowWarnings = true)
{
return successParse(_source, true, _allowWarnings);
}
void parsePrintCompare(string const& _source)
{
assembly::InlineAssemblyStack stack;
BOOST_REQUIRE(stack.parse(std::make_shared<Scanner>(CharStream(_source))));
BOOST_REQUIRE(stack.errors().empty());
BOOST_CHECK_EQUAL(stack.toString(), _source);
}
}
BOOST_AUTO_TEST_SUITE(SolidityInlineAssembly)
BOOST_AUTO_TEST_SUITE(Parsing)
BOOST_AUTO_TEST_CASE(smoke_test)
{
BOOST_CHECK(successParse("{ }"));
}
BOOST_AUTO_TEST_CASE(simple_instructions)
{
BOOST_CHECK(successParse("{ dup1 dup1 mul dup1 sub }"));
}
BOOST_AUTO_TEST_CASE(suicide_selfdestruct)
{
BOOST_CHECK(successParse("{ suicide selfdestruct }"));
}
BOOST_AUTO_TEST_CASE(keywords)
{
BOOST_CHECK(successParse("{ byte return address }"));
}
BOOST_AUTO_TEST_CASE(constants)
{
BOOST_CHECK(successParse("{ 7 8 mul }"));
}
BOOST_AUTO_TEST_CASE(vardecl)
{
BOOST_CHECK(successParse("{ let x := 7 }"));
}
BOOST_AUTO_TEST_CASE(assignment)
{
BOOST_CHECK(successParse("{ 7 8 add =: x }"));
}
BOOST_AUTO_TEST_CASE(label)
{
BOOST_CHECK(successParse("{ 7 abc: 8 eq abc jump }"));
}
BOOST_AUTO_TEST_CASE(label_complex)
{
BOOST_CHECK(successParse("{ 7 abc: 8 eq jump(abc) jumpi(eq(7, 8), abc) }"));
}
BOOST_AUTO_TEST_CASE(functional)
{
BOOST_CHECK(successParse("{ add(7, mul(6, x)) add mul(7, 8) }"));
}
BOOST_AUTO_TEST_CASE(functional_assignment)
{
BOOST_CHECK(successParse("{ x := 7 }"));
}
BOOST_AUTO_TEST_CASE(functional_assignment_complex)
{
BOOST_CHECK(successParse("{ x := add(7, mul(6, x)) add mul(7, 8) }"));
}
BOOST_AUTO_TEST_CASE(vardecl_complex)
{
BOOST_CHECK(successParse("{ let x := add(7, mul(6, x)) add mul(7, 8) }"));
}
BOOST_AUTO_TEST_CASE(blocks)
{
BOOST_CHECK(successParse("{ let x := 7 { let y := 3 } { let z := 2 } }"));
}
BOOST_AUTO_TEST_CASE(function_definitions)
{
BOOST_CHECK(successParse("{ function f() { } function g(a) -> (x) { } }"));
}
BOOST_AUTO_TEST_CASE(function_definitions_multiple_args)
{
BOOST_CHECK(successParse("{ function f(a, d) { } function g(a, d) -> (x, y) { } }"));
}
BOOST_AUTO_TEST_CASE(function_calls)
{
BOOST_CHECK(successParse("{ g(1, 2, f(mul(2, 3))) x() }"));
}
BOOST_AUTO_TEST_SUITE_END()
BOOST_AUTO_TEST_SUITE(Printing)
BOOST_AUTO_TEST_CASE(print_smoke)
{
parsePrintCompare("{\n}");
}
BOOST_AUTO_TEST_CASE(print_instructions)
{
parsePrintCompare("{\n 7\n 8\n mul\n dup10\n add\n}");
}
BOOST_AUTO_TEST_CASE(print_subblock)
{
parsePrintCompare("{\n {\n dup4\n add\n }\n}");
}
BOOST_AUTO_TEST_CASE(print_functional)
{
parsePrintCompare("{\n mul(sload(0x12), 7)\n}");
}
BOOST_AUTO_TEST_CASE(print_label)
{
parsePrintCompare("{\n loop:\n jump(loop)\n}");
}
BOOST_AUTO_TEST_CASE(print_assignments)
{
parsePrintCompare("{\n let x := mul(2, 3)\n 7\n =: x\n x := add(1, 2)\n}");
}
BOOST_AUTO_TEST_CASE(print_string_literals)
{
parsePrintCompare("{\n \"\\n'\\xab\\x95\\\"\"\n}");
}
BOOST_AUTO_TEST_CASE(print_string_literal_unicode)
{
string source = "{ \"\\u1bac\" }";
string parsed = "{\n \"\\xe1\\xae\\xac\"\n}";
assembly::InlineAssemblyStack stack;
BOOST_REQUIRE(stack.parse(std::make_shared<Scanner>(CharStream(source))));
BOOST_REQUIRE(stack.errors().empty());
BOOST_CHECK_EQUAL(stack.toString(), parsed);
parsePrintCompare(parsed);
}
BOOST_AUTO_TEST_CASE(function_definitions_multiple_args)
{
parsePrintCompare("{\n function f(a, d)\n {\n mstore(a, d)\n }\n function g(a, d) -> (x, y)\n {\n }\n}");
}
BOOST_AUTO_TEST_CASE(function_calls)
{
parsePrintCompare("{\n g(1, mul(2, x), f(mul(2, 3)))\n x()\n}");
}
BOOST_AUTO_TEST_SUITE_END()
BOOST_AUTO_TEST_SUITE(Analysis)
BOOST_AUTO_TEST_CASE(string_literals)
{
BOOST_CHECK(successAssemble("{ let x := \"12345678901234567890123456789012\" }"));
}
BOOST_AUTO_TEST_CASE(oversize_string_literals)
{
BOOST_CHECK(!successAssemble("{ let x := \"123456789012345678901234567890123\" }"));
}
BOOST_AUTO_TEST_CASE(assignment_after_tag)
{
BOOST_CHECK(successParse("{ let x := 1 { tag: =: x } }"));
}
BOOST_AUTO_TEST_CASE(magic_variables)
{
BOOST_CHECK(!successAssemble("{ this }"));
BOOST_CHECK(!successAssemble("{ ecrecover }"));
BOOST_CHECK(successAssemble("{ let ecrecover := 1 ecrecover }"));
}
BOOST_AUTO_TEST_CASE(imbalanced_stack)
{
BOOST_CHECK(successAssemble("{ 1 2 mul pop }", false));
BOOST_CHECK(!successAssemble("{ 1 }", false));
BOOST_CHECK(successAssemble("{ let x := 4 7 add }", false));
}
BOOST_AUTO_TEST_CASE(error_tag)
{
BOOST_CHECK(successAssemble("{ invalidJumpLabel }"));
}
BOOST_AUTO_TEST_CASE(designated_invalid_instruction)
{
BOOST_CHECK(successAssemble("{ invalid }"));
}
BOOST_AUTO_TEST_CASE(inline_assembly_shadowed_instruction_declaration)
{
// Error message: "Cannot use instruction names for identifier names."
BOOST_CHECK(!successAssemble("{ let gas := 1 }"));
}
BOOST_AUTO_TEST_CASE(inline_assembly_shadowed_instruction_assignment)
{
// Error message: "Identifier expected, got instruction name."
BOOST_CHECK(!successAssemble("{ 2 =: gas }"));
}
BOOST_AUTO_TEST_CASE(inline_assembly_shadowed_instruction_functional_assignment)
{
// Error message: "Cannot use instruction names for identifier names."
BOOST_CHECK(!successAssemble("{ gas := 2 }"));
}
BOOST_AUTO_TEST_CASE(revert)
{
BOOST_CHECK(successAssemble("{ revert(0, 0) }"));
}
BOOST_AUTO_TEST_SUITE_END()
BOOST_AUTO_TEST_SUITE_END()
}
}
} // end namespaces
<commit_msg>Check error messages for assembly tests.<commit_after>/*
This file is part of solidity.
solidity 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.
solidity 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 solidity. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @author Christian <[email protected]>
* @date 2016
* Unit tests for inline assembly.
*/
#include "../TestHelper.h"
#include <libsolidity/inlineasm/AsmStack.h>
#include <libsolidity/parsing/Scanner.h>
#include <libsolidity/interface/Exceptions.h>
#include <libsolidity/ast/AST.h>
#include <test/libsolidity/ErrorCheck.h>
#include <libevmasm/Assembly.h>
#include <boost/optional.hpp>
#include <string>
#include <memory>
using namespace std;
namespace dev
{
namespace solidity
{
namespace test
{
namespace
{
boost::optional<Error> parseAndReturnFirstError(string const& _source, bool _assemble = false, bool _allowWarnings = true)
{
assembly::InlineAssemblyStack stack;
bool success = false;
try
{
success = stack.parse(std::make_shared<Scanner>(CharStream(_source)));
if (success && _assemble)
stack.assemble();
}
catch (FatalError const& e)
{
BOOST_FAIL("Fatal error leaked.");
success = false;
}
if (!success)
{
BOOST_CHECK_EQUAL(stack.errors().size(), 1);
return *stack.errors().front();
}
else
{
// If success is true, there might still be an error in the assembly stage.
if (_allowWarnings && Error::containsOnlyWarnings(stack.errors()))
return {};
else if (!stack.errors().empty())
{
if (!_allowWarnings)
BOOST_CHECK_EQUAL(stack.errors().size(), 1);
return *stack.errors().front();
}
}
return {};
}
bool successParse(std::string const& _source, bool _assemble = false, bool _allowWarnings = true)
{
return !parseAndReturnFirstError(_source, _assemble, _allowWarnings);
}
bool successAssemble(string const& _source, bool _allowWarnings = true)
{
return successParse(_source, true, _allowWarnings);
}
Error expectError(std::string const& _source, bool _assemble, bool _allowWarnings = false)
{
auto error = parseAndReturnFirstError(_source, _assemble, _allowWarnings);
BOOST_REQUIRE(error);
return *error;
}
void parsePrintCompare(string const& _source)
{
assembly::InlineAssemblyStack stack;
BOOST_REQUIRE(stack.parse(std::make_shared<Scanner>(CharStream(_source))));
BOOST_REQUIRE(stack.errors().empty());
BOOST_CHECK_EQUAL(stack.toString(), _source);
}
}
#define CHECK_ERROR(text, assemble, typ, substring) \
do \
{ \
Error err = expectError((text), (assemble), false); \
BOOST_CHECK(err.type() == (Error::Type::typ)); \
BOOST_CHECK(searchErrorMessage(err, (substring))); \
} while(0)
#define CHECK_PARSE_ERROR(text, type, substring) \
CHECK_ERROR(text, false, type, substring)
#define CHECK_ASSEMBLE_ERROR(text, type, substring) \
CHECK_ERROR(text, true, type, substring)
BOOST_AUTO_TEST_SUITE(SolidityInlineAssembly)
BOOST_AUTO_TEST_SUITE(Parsing)
BOOST_AUTO_TEST_CASE(smoke_test)
{
BOOST_CHECK(successParse("{ }"));
}
BOOST_AUTO_TEST_CASE(simple_instructions)
{
BOOST_CHECK(successParse("{ dup1 dup1 mul dup1 sub }"));
}
BOOST_AUTO_TEST_CASE(suicide_selfdestruct)
{
BOOST_CHECK(successParse("{ suicide selfdestruct }"));
}
BOOST_AUTO_TEST_CASE(keywords)
{
BOOST_CHECK(successParse("{ byte return address }"));
}
BOOST_AUTO_TEST_CASE(constants)
{
BOOST_CHECK(successParse("{ 7 8 mul }"));
}
BOOST_AUTO_TEST_CASE(vardecl)
{
BOOST_CHECK(successParse("{ let x := 7 }"));
}
BOOST_AUTO_TEST_CASE(assignment)
{
BOOST_CHECK(successParse("{ 7 8 add =: x }"));
}
BOOST_AUTO_TEST_CASE(label)
{
BOOST_CHECK(successParse("{ 7 abc: 8 eq abc jump }"));
}
BOOST_AUTO_TEST_CASE(label_complex)
{
BOOST_CHECK(successParse("{ 7 abc: 8 eq jump(abc) jumpi(eq(7, 8), abc) }"));
}
BOOST_AUTO_TEST_CASE(functional)
{
BOOST_CHECK(successParse("{ add(7, mul(6, x)) add mul(7, 8) }"));
}
BOOST_AUTO_TEST_CASE(functional_assignment)
{
BOOST_CHECK(successParse("{ x := 7 }"));
}
BOOST_AUTO_TEST_CASE(functional_assignment_complex)
{
BOOST_CHECK(successParse("{ x := add(7, mul(6, x)) add mul(7, 8) }"));
}
BOOST_AUTO_TEST_CASE(vardecl_complex)
{
BOOST_CHECK(successParse("{ let x := add(7, mul(6, x)) add mul(7, 8) }"));
}
BOOST_AUTO_TEST_CASE(blocks)
{
BOOST_CHECK(successParse("{ let x := 7 { let y := 3 } { let z := 2 } }"));
}
BOOST_AUTO_TEST_CASE(function_definitions)
{
BOOST_CHECK(successParse("{ function f() { } function g(a) -> (x) { } }"));
}
BOOST_AUTO_TEST_CASE(function_definitions_multiple_args)
{
BOOST_CHECK(successParse("{ function f(a, d) { } function g(a, d) -> (x, y) { } }"));
}
BOOST_AUTO_TEST_CASE(function_calls)
{
BOOST_CHECK(successParse("{ g(1, 2, f(mul(2, 3))) x() }"));
}
BOOST_AUTO_TEST_SUITE_END()
BOOST_AUTO_TEST_SUITE(Printing)
BOOST_AUTO_TEST_CASE(print_smoke)
{
parsePrintCompare("{\n}");
}
BOOST_AUTO_TEST_CASE(print_instructions)
{
parsePrintCompare("{\n 7\n 8\n mul\n dup10\n add\n}");
}
BOOST_AUTO_TEST_CASE(print_subblock)
{
parsePrintCompare("{\n {\n dup4\n add\n }\n}");
}
BOOST_AUTO_TEST_CASE(print_functional)
{
parsePrintCompare("{\n mul(sload(0x12), 7)\n}");
}
BOOST_AUTO_TEST_CASE(print_label)
{
parsePrintCompare("{\n loop:\n jump(loop)\n}");
}
BOOST_AUTO_TEST_CASE(print_assignments)
{
parsePrintCompare("{\n let x := mul(2, 3)\n 7\n =: x\n x := add(1, 2)\n}");
}
BOOST_AUTO_TEST_CASE(print_string_literals)
{
parsePrintCompare("{\n \"\\n'\\xab\\x95\\\"\"\n}");
}
BOOST_AUTO_TEST_CASE(print_string_literal_unicode)
{
string source = "{ \"\\u1bac\" }";
string parsed = "{\n \"\\xe1\\xae\\xac\"\n}";
assembly::InlineAssemblyStack stack;
BOOST_REQUIRE(stack.parse(std::make_shared<Scanner>(CharStream(source))));
BOOST_REQUIRE(stack.errors().empty());
BOOST_CHECK_EQUAL(stack.toString(), parsed);
parsePrintCompare(parsed);
}
BOOST_AUTO_TEST_CASE(function_definitions_multiple_args)
{
parsePrintCompare("{\n function f(a, d)\n {\n mstore(a, d)\n }\n function g(a, d) -> (x, y)\n {\n }\n}");
}
BOOST_AUTO_TEST_CASE(function_calls)
{
parsePrintCompare("{\n g(1, mul(2, x), f(mul(2, 3)))\n x()\n}");
}
BOOST_AUTO_TEST_SUITE_END()
BOOST_AUTO_TEST_SUITE(Analysis)
BOOST_AUTO_TEST_CASE(string_literals)
{
BOOST_CHECK(successAssemble("{ let x := \"12345678901234567890123456789012\" }"));
}
BOOST_AUTO_TEST_CASE(oversize_string_literals)
{
BOOST_CHECK(!successAssemble("{ let x := \"123456789012345678901234567890123\" }"));
}
BOOST_AUTO_TEST_CASE(assignment_after_tag)
{
BOOST_CHECK(successParse("{ let x := 1 { tag: =: x } }"));
}
BOOST_AUTO_TEST_CASE(magic_variables)
{
CHECK_ASSEMBLE_ERROR("{ this pop }", DeclarationError, "Identifier not found or not unique");
CHECK_ASSEMBLE_ERROR("{ ecrecover pop }", DeclarationError, "Identifier not found or not unique");
BOOST_CHECK(successAssemble("{ let ecrecover := 1 ecrecover }"));
}
BOOST_AUTO_TEST_CASE(imbalanced_stack)
{
BOOST_CHECK(successAssemble("{ 1 2 mul pop }", false));
BOOST_CHECK(!successAssemble("{ 1 }", false));
BOOST_CHECK(successAssemble("{ let x := 4 7 add }", false));
}
BOOST_AUTO_TEST_CASE(error_tag)
{
BOOST_CHECK(successAssemble("{ invalidJumpLabel }"));
}
BOOST_AUTO_TEST_CASE(designated_invalid_instruction)
{
BOOST_CHECK(successAssemble("{ invalid }"));
}
BOOST_AUTO_TEST_CASE(inline_assembly_shadowed_instruction_declaration)
{
CHECK_ASSEMBLE_ERROR("{ let gas := 1 }", ParserError, "Cannot use instruction names for identifier names.");
}
BOOST_AUTO_TEST_CASE(inline_assembly_shadowed_instruction_assignment)
{
CHECK_ASSEMBLE_ERROR("{ 2 =: gas }", ParserError, "Identifier expected, got instruction name.");
}
BOOST_AUTO_TEST_CASE(inline_assembly_shadowed_instruction_functional_assignment)
{
CHECK_ASSEMBLE_ERROR("{ gas := 2 }", ParserError, "Label name / variable name must precede \":\"");
}
BOOST_AUTO_TEST_CASE(revert)
{
BOOST_CHECK(successAssemble("{ revert(0, 0) }"));
}
BOOST_AUTO_TEST_SUITE_END()
BOOST_AUTO_TEST_SUITE_END()
}
}
} // end namespaces
<|endoftext|>
|
<commit_before>// Copyright 2020 The gVisor Authors.
//
// 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 <sys/syscall.h>
#include <unistd.h>
#include "gtest/gtest.h"
#include "benchmark/benchmark.h"
namespace gvisor {
namespace testing {
namespace {
void BM_Getpid(benchmark::State& state) {
for (auto _ : state) {
syscall(SYS_getpid);
}
}
BENCHMARK(BM_Getpid);
} // namespace
} // namespace testing
} // namespace gvisor
<commit_msg>perf/getpid: add a case when syscalls are executed via mov $XXX, %eax; syscall<commit_after>// Copyright 2020 The gVisor Authors.
//
// 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 <sys/syscall.h>
#include <unistd.h>
#include "gtest/gtest.h"
#include "benchmark/benchmark.h"
namespace gvisor {
namespace testing {
namespace {
void BM_Getpid(benchmark::State& state) {
for (auto _ : state) {
syscall(SYS_getpid);
}
}
BENCHMARK(BM_Getpid);
#ifdef __x86_64__
#define SYSNO_STR1(x) #x
#define SYSNO_STR(x) SYSNO_STR1(x)
// BM_GetpidOpt uses the most often pattern of calling system calls:
// mov $SYS_XXX, %eax; syscall.
void BM_GetpidOpt(benchmark::State& state) {
for (auto s : state) {
__asm__("movl $" SYSNO_STR(SYS_getpid) ", %%eax\n"
"syscall\n"
: : : "rax", "rcx", "r11");
}
}
BENCHMARK(BM_GetpidOpt);
#endif // __x86_64__
} // namespace
} // namespace testing
} // namespace gvisor
<|endoftext|>
|
<commit_before>/*
** Copyright 2012-2015 Merethis
**
** This file is part of Centreon Broker.
**
** Centreon Broker 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 Broker 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 Broker. If not, see
** <http://www.gnu.org/licenses/>.
*/
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <fstream>
#include <iostream>
#include <sstream>
#include <QSqlError>
#include <QSqlQuery>
#include <QVariant>
#include <sstream>
#include "com/centreon/broker/exceptions/msg.hh"
#include "test/cbd.hh"
#include "test/config.hh"
#include "test/engine.hh"
#include "test/external_command.hh"
#include "test/generate.hh"
#include "test/misc.hh"
#include "test/vars.hh"
using namespace com::centreon::broker;
#define DB_NAME "broker_secondary_failovers_to_file"
/**
* Check that encryption works on Broker stream.
*
* @return EXIT_SUCCESS on success.
*/
int main() {
// Return value.
int retval(EXIT_FAILURE);
// Variables that need cleaning.
std::list<host> hosts;
std::list<service> services;
std::string cbmod_config_path(tmpnam(NULL));
std::string engine_config_path(tmpnam(NULL));
std::string retention_file_path(tmpnam(NULL));
std::string retention_secondary_file_path(tmpnam(NULL));
std::string retention_secondary_file2_path(tmpnam(NULL));
external_command commander;
commander.set_file(tmpnam(NULL));
engine daemon;
test_db db;
try {
// Prepare database.
db.open(DB_NAME);
// Write cbmod configuration file.
{
std::ofstream ofs;
ofs.open(
cbmod_config_path.c_str(),
std::ios_base::out | std::ios_base::trunc);
if (ofs.fail())
throw (exceptions::msg()
<< "cannot open cbmod configuration file '"
<< cbmod_config_path.c_str() << "'");
ofs << "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"
<< "<centreonbroker>\n"
<< " <include>" PROJECT_SOURCE_DIR "/test/cfg/broker_modules.xml</include>\n"
<< " <instance>42</instance>\n"
<< " <instance_name>MyBroker</instance_name>\n"
<< " <!--\n"
<< " <logger>\n"
<< " <type>file</type>\n"
<< " <name>cbmod.log</name>\n"
<< " <config>1</config>\n"
<< " <debug>1</debug>\n"
<< " <error>1</error>\n"
<< " <info>1</info>\n"
<< " <level>3</level>\n"
<< " </logger>\n"
<< " -->\n"
<< " <output>\n"
<< " <name>EngineToTCP</name>\n"
<< " <failover>ToRetentionFile</failover>\n"
<< " <secondary_failover>SecondaryRetentionFile1</secondary_failover>\n"
<< " <secondary_failover>SecondaryRetentionFile2</secondary_failover>\n"
<< " <type>tcp</type>\n"
<< " <host>localhost</host>\n"
<< " <port>5680</port>\n"
<< " <protocol>bbdo</protocol>\n"
<< " <retry_interval>1</retry_interval>\n"
<< " </output>\n"
<< " <output>\n"
<< " <name>ToRetentionFile</name>\n"
<< " <type>file</type>\n"
<< " <path>" << retention_file_path << "</path>\n"
<< " <protocol>bbdo</protocol>\n"
<< " <compression>yes</compression>\n"
<< " </output>\n"
<< " <output>\n"
<< " <name>SecondaryRetentionFile1</name>\n"
<< " <type>file</type>\n"
<< " <path>" << retention_secondary_file_path << "</path>\n"
<< " <protocol>bbdo</protocol>\n"
<< " <compression>yes</compression>\n"
<< " </output>\n"
<< " <output>\n"
<< " <name>SecondaryRetentionFile2</name>\n"
<< " <type>file</type>\n"
<< " <path>" << retention_secondary_file2_path << "</path>\n"
<< " <protocol>bbdo</protocol>\n"
<< " <compression>yes</compression>\n"
<< " </output>\n"
<< "</centreonbroker>\n";
ofs.close();
}
// Prepare monitoring engine configuration parameters.
generate_hosts(hosts, 10);
generate_services(services, hosts, 5);
std::string additional_config;
{
std::ostringstream oss;
oss << commander.get_engine_config()
<< "broker_module=" << CBMOD_PATH << " " << cbmod_config_path;
additional_config = oss.str();
}
// Generate monitoring engine configuration files.
config_write(
engine_config_path.c_str(),
additional_config.c_str(),
&hosts,
&services);
// Start engine.
std::string engine_config_file(engine_config_path);
engine_config_file.append("/nagios.cfg");
daemon.set_config_file(engine_config_file);
daemon.start();
sleep_for(12);
// Temporary disable checks.
commander.execute("STOP_EXECUTING_SVC_CHECKS");
sleep_for(4);
// Terminate monitoring engine.
daemon.stop();
// Check the secondary failovers.
std::fstream file;
std::string primary_file;
std::string secondary_file1;
std::string secondary_file2;
std::stringstream sstream;
file.exceptions(std::ifstream::failbit | std::ifstream::badbit);
file.open(retention_file_path.c_str());
sstream << file.rdbuf();
primary_file = sstream.str();
file.close();
file.open(retention_secondary_file_path.c_str());
sstream.str("");
sstream << file.rdbuf();
secondary_file1 = sstream.str();
file.close();
file.open(retention_secondary_file2_path.c_str());
sstream.str("");
sstream << file.rdbuf();
secondary_file2 = sstream.str();
file.close();
if (primary_file.empty() || secondary_file1.empty() || secondary_file2.empty())
throw (
com::centreon::broker::exceptions::msg()
<< "a retention file was empty");
if (primary_file != secondary_file1 || primary_file != secondary_file2)
throw (
com::centreon::broker::exceptions::msg()
<< "primary retention file and secondary retention files are not the same");
retval = EXIT_SUCCESS;
}
catch (std::exception const& e) {
std::cerr << e.what() << std::endl;
}
catch (...) {
std::cerr << "unknown exception" << std::endl;
}
// Cleanup.
daemon.stop();
config_remove(engine_config_path.c_str());
::remove(cbmod_config_path.c_str());
::remove(retention_file_path.c_str());
::remove(retention_secondary_file_path.c_str());
::remove(retention_secondary_file2_path.c_str());
free_hosts(hosts);
free_services(services);
return (retval);
}
<commit_msg>test: repair running_secondary_failovers_to_file unit test.<commit_after>/*
** Copyright 2012-2015 Merethis
**
** This file is part of Centreon Broker.
**
** Centreon Broker 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 Broker 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 Broker. If not, see
** <http://www.gnu.org/licenses/>.
*/
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <fstream>
#include <iostream>
#include <sstream>
#include <QSqlError>
#include <QSqlQuery>
#include <QVariant>
#include <sstream>
#include "com/centreon/broker/exceptions/msg.hh"
#include "test/cbd.hh"
#include "test/config.hh"
#include "test/engine.hh"
#include "test/external_command.hh"
#include "test/generate.hh"
#include "test/misc.hh"
#include "test/vars.hh"
using namespace com::centreon::broker;
#define DB_NAME "broker_secondary_failovers_to_file"
/**
* Check that encryption works on Broker stream.
*
* @return EXIT_SUCCESS on success.
*/
int main() {
// Return value.
int retval(EXIT_FAILURE);
// Variables that need cleaning.
std::list<host> hosts;
std::list<service> services;
std::string cbmod_config_path(tmpnam(NULL));
std::string engine_config_path(tmpnam(NULL));
std::string retention_secondary_file_path(tmpnam(NULL));
std::string retention_secondary_file2_path(tmpnam(NULL));
external_command commander;
commander.set_file(tmpnam(NULL));
engine daemon;
test_db db;
try {
// Prepare database.
db.open(DB_NAME);
// Write cbmod configuration file.
{
std::ofstream ofs;
ofs.open(
cbmod_config_path.c_str(),
std::ios_base::out | std::ios_base::trunc);
if (ofs.fail())
throw (exceptions::msg()
<< "cannot open cbmod configuration file '"
<< cbmod_config_path.c_str() << "'");
ofs << "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"
<< "<centreonbroker>\n"
<< " <include>" PROJECT_SOURCE_DIR "/test/cfg/broker_modules.xml</include>\n"
<< " <instance>42</instance>\n"
<< " <instance_name>MyBroker</instance_name>\n"
<< " <!--\n"
<< " <logger>\n"
<< " <type>file</type>\n"
<< " <name>cbmod.log</name>\n"
<< " <config>1</config>\n"
<< " <debug>1</debug>\n"
<< " <error>1</error>\n"
<< " <info>1</info>\n"
<< " <level>3</level>\n"
<< " </logger>\n"
<< " -->\n"
<< " <output>\n"
<< " <name>SecondaryFailoversToFile-TCP</name>\n"
<< " <failover>SecondaryFailoversToFile-NodeEvents</failover>\n"
<< " <secondary_failover>SecondaryFailoversToFile-File1</secondary_failover>\n"
<< " <secondary_failover>SecondaryFailoversToFile-File2</secondary_failover>\n"
<< " <type>tcp</type>\n"
<< " <host>localhost</host>\n"
<< " <port>5680</port>\n"
<< " <protocol>bbdo</protocol>\n"
<< " <retry_interval>1</retry_interval>\n"
<< " </output>\n"
<< " <output>\n"
<< " <name>SecondaryFailoversToFile-NodeEvents</name>\n"
<< " <type>node_events</type>\n"
<< " </output>\n"
<< " <output>\n"
<< " <name>SecondaryFailoversToFile-File1</name>\n"
<< " <type>file</type>\n"
<< " <path>" << retention_secondary_file_path << "</path>\n"
<< " <protocol>bbdo</protocol>\n"
<< " <compression>yes</compression>\n"
<< " </output>\n"
<< " <output>\n"
<< " <name>SecondaryFailoversToFile-File2</name>\n"
<< " <type>file</type>\n"
<< " <path>" << retention_secondary_file2_path << "</path>\n"
<< " <protocol>bbdo</protocol>\n"
<< " <compression>yes</compression>\n"
<< " </output>\n"
<< "</centreonbroker>\n";
ofs.close();
}
// Prepare monitoring engine configuration parameters.
generate_hosts(hosts, 10);
generate_services(services, hosts, 5);
std::string additional_config;
{
std::ostringstream oss;
oss << commander.get_engine_config()
<< "broker_module=" << CBMOD_PATH << " " << cbmod_config_path;
additional_config = oss.str();
}
// Generate monitoring engine configuration files.
config_write(
engine_config_path.c_str(),
additional_config.c_str(),
&hosts,
&services);
// Start engine.
std::string engine_config_file(engine_config_path);
engine_config_file.append("/nagios.cfg");
daemon.set_config_file(engine_config_file);
daemon.start();
sleep_for(12);
// Temporary disable checks.
commander.execute("STOP_EXECUTING_SVC_CHECKS");
sleep_for(4);
// Terminate monitoring engine.
daemon.stop();
// Check the secondary failovers.
std::fstream file;
std::string secondary_file1;
std::string secondary_file2;
std::stringstream sstream;
file.exceptions(std::ifstream::failbit | std::ifstream::badbit);
file.open(retention_secondary_file_path.c_str());
sstream.str("");
sstream << file.rdbuf();
secondary_file1 = sstream.str();
file.close();
file.open(retention_secondary_file2_path.c_str());
sstream.str("");
sstream << file.rdbuf();
secondary_file2 = sstream.str();
file.close();
if (secondary_file1.empty() || secondary_file2.empty())
throw (
com::centreon::broker::exceptions::msg()
<< "a retention file was empty");
if (secondary_file1 != secondary_file2)
throw (
com::centreon::broker::exceptions::msg()
<< "secondary retention files are not the same");
retval = EXIT_SUCCESS;
}
catch (std::exception const& e) {
std::cerr << e.what() << std::endl;
}
catch (...) {
std::cerr << "unknown exception" << std::endl;
}
// Cleanup.
daemon.stop();
config_remove(engine_config_path.c_str());
::remove(cbmod_config_path.c_str());
::remove(retention_secondary_file_path.c_str());
::remove(retention_secondary_file2_path.c_str());
free_hosts(hosts);
free_services(services);
return (retval);
}
<|endoftext|>
|
<commit_before>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "mitkPlaneGeometryDataMapper2D.h"
//mitk includes
#include "mitkVtkPropRenderer.h"
#include <mitkProperties.h>
#include <mitkDataNode.h>
#include <mitkPointSet.h>
#include <mitkPlaneGeometry.h>
#include <mitkPlaneOrientationProperty.h>
#include <mitkLine.h>
#include <mitkAbstractTransformGeometry.h>
#include <mitkResliceMethodProperty.h>
#include <mitkSlicedGeometry3D.h>
//vtk includes
#include <mitkIPropertyAliases.h>
#include <vtkActor.h>
#include <vtkCellArray.h>
#include <vtkCellData.h>
#include <vtkLine.h>
#include <vtkPoints.h>
#include <vtkPolyData.h>
mitk::PlaneGeometryDataMapper2D::AllInstancesContainer mitk::PlaneGeometryDataMapper2D::s_AllInstances;
// input for this mapper ( = PlaneGeometryData)
const mitk::PlaneGeometryData* mitk::PlaneGeometryDataMapper2D::GetInput() const
{
return static_cast< PlaneGeometryData * >(GetDataNode()->GetData());
}
mitk::PlaneGeometryDataMapper2D::PlaneGeometryDataMapper2D()
: m_RenderOrientationArrows( false ),
m_ArrowOrientationPositive( true ),
m_DepthValue(1.0f)
{
s_AllInstances.insert(this);
}
mitk::PlaneGeometryDataMapper2D::~PlaneGeometryDataMapper2D()
{
s_AllInstances.erase(this);
}
vtkProp* mitk::PlaneGeometryDataMapper2D::GetVtkProp(mitk::BaseRenderer * renderer)
{
LocalStorage *ls = m_LSH.GetLocalStorage(renderer);
return ls->m_CrosshairAssembly;
}
void mitk::PlaneGeometryDataMapper2D::GenerateDataForRenderer( mitk::BaseRenderer *renderer )
{
BaseLocalStorage *ls = m_LSH.GetLocalStorage(renderer);
// The PlaneGeometryDataMapper2D mapper is special in that the rendering of
// OTHER PlaneGeometryDatas affects how we render THIS PlaneGeometryData
// (for the gap at the point where they intersect). A change in any of the
// other PlaneGeometryData nodes could mean that we render ourself
// differently, so we check for that here.
bool generateDataRequired = false;
for (AllInstancesContainer::iterator it = s_AllInstances.begin();
it != s_AllInstances.end();
++it)
{
generateDataRequired = ls->IsGenerateDataRequired(renderer, this, (*it)->GetDataNode());
if (generateDataRequired) break;
}
ls->UpdateGenerateDataTime();
// Collect all other PlaneGeometryDatas that are being mapped by this mapper
m_OtherPlaneGeometries.clear();
for (AllInstancesContainer::iterator it = s_AllInstances.begin(); it != s_AllInstances.end(); ++it)
{
Self *otherInstance = *it;
// Skip ourself
if (otherInstance == this) continue;
mitk::DataNode *otherNode = otherInstance->GetDataNode();
if (!otherNode) continue;
// Skip other PlaneGeometryData nodes that are not visible on this renderer
if (!otherNode->IsVisible(renderer)) continue;
PlaneGeometryData* otherData = dynamic_cast<PlaneGeometryData*>(otherNode->GetData());
if (!otherData) continue;
PlaneGeometry* otherGeometry = dynamic_cast<PlaneGeometry*>(otherData->GetPlaneGeometry());
if ( otherGeometry && !dynamic_cast<AbstractTransformGeometry*>(otherData->GetPlaneGeometry()) )
{
m_OtherPlaneGeometries.push_back(otherNode);
}
}
CreateVtkCrosshair(renderer);
ApplyAllProperties(renderer);
}
void mitk::PlaneGeometryDataMapper2D::CreateVtkCrosshair(mitk::BaseRenderer *renderer)
{
bool visible = true;
GetDataNode()->GetVisibility(visible, renderer, "visible");
if(!visible) return;
PlaneGeometryData::Pointer input = const_cast< PlaneGeometryData * >(this->GetInput());
mitk::DataNode* geometryDataNode = renderer->GetCurrentWorldPlaneGeometryNode();
const PlaneGeometryData* rendererWorldPlaneGeometryData = dynamic_cast< PlaneGeometryData * >(geometryDataNode->GetData());
// intersecting with ourself?
if ( input.IsNull() || input.GetPointer() == rendererWorldPlaneGeometryData)
{
return; //nothing to do in this case
}
const PlaneGeometry *inputPlaneGeometry = dynamic_cast< const PlaneGeometry * >( input->GetPlaneGeometry() );
const PlaneGeometry* worldPlaneGeometry = dynamic_cast< const PlaneGeometry* >(
rendererWorldPlaneGeometryData->GetPlaneGeometry() );
if ( worldPlaneGeometry && dynamic_cast<const AbstractTransformGeometry*>(worldPlaneGeometry)==NULL
&& inputPlaneGeometry && dynamic_cast<const AbstractTransformGeometry*>(input->GetPlaneGeometry() )==NULL
&& inputPlaneGeometry->GetReferenceGeometry() )
{
const BaseGeometry *referenceGeometry = inputPlaneGeometry->GetReferenceGeometry();
// calculate intersection of the plane data with the border of the
// world geometry rectangle
Point3D point1, point2;
Line3D crossLine;
// Calculate the intersection line of the input plane with the world plane
if ( worldPlaneGeometry->IntersectionLine( inputPlaneGeometry, crossLine ) )
{
Point3D boundingBoxMin, boundingBoxMax;
boundingBoxMin = referenceGeometry->GetCornerPoint(0);
boundingBoxMax = referenceGeometry->GetCornerPoint(7);
// Then, clip this line with the (transformed) bounding box of the
// reference geometry.
crossLine.BoxLineIntersection(
boundingBoxMin[0], boundingBoxMin[1], boundingBoxMin[2],
boundingBoxMax[0], boundingBoxMax[1], boundingBoxMax[2],
crossLine.GetPoint(), crossLine.GetDirection(),
point1, point2 );
crossLine.SetPoints(point1,point2);
vtkSmartPointer<vtkCellArray> lines = vtkSmartPointer<vtkCellArray>::New();
vtkSmartPointer<vtkPoints> points = vtkSmartPointer<vtkPoints>::New();
vtkSmartPointer<vtkPolyData> linesPolyData = vtkSmartPointer<vtkPolyData>::New();
// Now iterate through all other lines displayed in this window and
// calculate the positions of intersection with the line to be
// rendered; these positions will be stored in lineParams to form a
// gap afterwards.
NodesVectorType::iterator otherPlanesIt = m_OtherPlaneGeometries.begin();
NodesVectorType::iterator otherPlanesEnd = m_OtherPlaneGeometries.end();
std::vector<Point3D> intersections;
intersections.push_back(point1);
otherPlanesIt = m_OtherPlaneGeometries.begin();
int gapsize = 32;
this->GetDataNode()->GetPropertyValue( "Crosshair.Gap Size",gapsize, NULL );
ScalarType lineLength = point1.EuclideanDistanceTo(point2);
DisplayGeometry *displayGeometry = renderer->GetDisplayGeometry();
ScalarType gapinmm = gapsize * displayGeometry->GetScaleFactorMMPerDisplayUnit();
float gapSizeParam = gapinmm / lineLength;
while ( otherPlanesIt != otherPlanesEnd )
{
PlaneGeometry *otherPlane = static_cast< PlaneGeometry * >(
static_cast< PlaneGeometryData * >((*otherPlanesIt)->GetData() )->GetPlaneGeometry() );
if (otherPlane != inputPlaneGeometry && otherPlane != worldPlaneGeometry)
{
Point3D planeIntersection;
otherPlane->IntersectionPoint(crossLine,planeIntersection);
ScalarType sectionLength = point1.EuclideanDistanceTo(planeIntersection);
ScalarType lineValue = sectionLength/lineLength;
if(lineValue-gapSizeParam > 0.0)
intersections.push_back(crossLine.GetPoint(lineValue-gapSizeParam));
else intersections.pop_back();
if(lineValue+gapSizeParam < 1.0)
intersections.push_back(crossLine.GetPoint(lineValue+gapSizeParam));
}
++otherPlanesIt;
}
if(intersections.size()%2 == 1)
intersections.push_back(point2);
if(intersections.empty())
{
this->DrawLine(point1,point2,lines,points);
}
else
for(unsigned int i = 0 ; i< intersections.size()-1 ; i+=2)
{
this->DrawLine(intersections[i],intersections[i+1],lines,points);
}
// Add the points to the dataset
linesPolyData->SetPoints(points);
// Add the lines to the dataset
linesPolyData->SetLines(lines);
// Visualize
vtkSmartPointer<vtkPolyDataMapper> mapper = vtkSmartPointer<vtkPolyDataMapper>::New();
mapper->SetInputData(linesPolyData);
LocalStorage* ls = m_LSH.GetLocalStorage(renderer);
ls->m_CrosshairActor->SetMapper(mapper);
// Determine if we should draw the area covered by the thick slicing, default is false.
// This will also show the area of slices that do not have thick slice mode enabled
bool showAreaOfThickSlicing = false;
GetDataNode()->GetBoolProperty( "reslice.thickslices.showarea", showAreaOfThickSlicing );
// get the normal of the inputPlaneGeometry
Vector3D normal = inputPlaneGeometry->GetNormal();
// determine the pixelSpacing in that direction
double thickSliceDistance = SlicedGeometry3D::CalculateSpacing( referenceGeometry->GetSpacing(), normal );
IntProperty *intProperty=0;
if( GetDataNode()->GetProperty( intProperty, "reslice.thickslices.num" ) && intProperty )
thickSliceDistance *= intProperty->GetValue()+0.5;
else
showAreaOfThickSlicing = false;
// not the nicest place to do it, but we have the width of the visible bloc in MM here
// so we store it in this fancy property
GetDataNode()->SetFloatProperty( "reslice.thickslices.sizeinmm", thickSliceDistance*2 );
if ( showAreaOfThickSlicing )
{
vtkSmartPointer<vtkCellArray> helperlines = vtkSmartPointer<vtkCellArray>::New();
vtkSmartPointer<vtkPolyData> helperlinesPolyData = vtkSmartPointer<vtkPolyData>::New();
// vectorToHelperLine defines how to reach the helperLine from the mainLine
Vector3D vectorToHelperLine;
vectorToHelperLine = normal;
vectorToHelperLine.Normalize();
// got the right direction, so we multiply the width
vectorToHelperLine *= thickSliceDistance;
this->DrawLine(point1 - vectorToHelperLine, point2 - vectorToHelperLine,helperlines,points);
this->DrawLine(point1 + vectorToHelperLine, point2 + vectorToHelperLine,helperlines,points);
// Add the points to the dataset
helperlinesPolyData->SetPoints(points);
// Add the lines to the dataset
helperlinesPolyData->SetLines(helperlines);
// Visualize
vtkSmartPointer<vtkPolyDataMapper> helperLinesmapper = vtkSmartPointer<vtkPolyDataMapper>::New();
helperLinesmapper->SetInputData(helperlinesPolyData);
ls->m_CrosshairActor->GetProperty()->SetLineStipplePattern(0xf0f0);
ls->m_CrosshairActor->GetProperty()->SetLineStippleRepeatFactor(1);
ls->m_CrosshairHelperLineActor->SetMapper(helperLinesmapper);
ls->m_CrosshairAssembly->AddPart(ls->m_CrosshairHelperLineActor);
}
else
{
ls->m_CrosshairAssembly->RemovePart(ls->m_CrosshairHelperLineActor);
ls->m_CrosshairActor->GetProperty()->SetLineStipplePattern(0xffff);
}
}
}
}
void mitk::PlaneGeometryDataMapper2D::DrawLine( mitk::Point3D p0,mitk::Point3D p1,
vtkCellArray* lines,
vtkPoints* points
)
{
vtkIdType pidStart = points->InsertNextPoint(p0[0],p0[1], p0[2]);
vtkIdType pidEnd = points->InsertNextPoint(p1[0],p1[1], p1[2]);
vtkSmartPointer<vtkLine> lineVtk = vtkSmartPointer<vtkLine>::New();
lineVtk->GetPointIds()->SetId(0,pidStart);
lineVtk->GetPointIds()->SetId(1,pidEnd);
lines->InsertNextCell(lineVtk);
}
int mitk::PlaneGeometryDataMapper2D::DetermineThickSliceMode( DataNode * dn, int &thickSlicesNum )
{
int thickSlicesMode = 0;
// determine the state and the extend of the thick-slice mode
mitk::ResliceMethodProperty *resliceMethodEnumProperty=0;
if( dn->GetProperty( resliceMethodEnumProperty, "reslice.thickslices" ) && resliceMethodEnumProperty )
thickSlicesMode = resliceMethodEnumProperty->GetValueAsId();
IntProperty *intProperty=0;
if( dn->GetProperty( intProperty, "reslice.thickslices.num" ) && intProperty )
{
thickSlicesNum = intProperty->GetValue();
if(thickSlicesNum < 1) thickSlicesNum=0;
if(thickSlicesNum > 10) thickSlicesNum=10;
}
if ( thickSlicesMode == 0 )
thickSlicesNum = 0;
return thickSlicesMode;
}
void mitk::PlaneGeometryDataMapper2D::ApplyAllProperties( BaseRenderer *renderer )
{
LocalStorage *ls = m_LSH.GetLocalStorage(renderer);
Superclass::ApplyColorAndOpacityProperties(renderer, ls->m_CrosshairActor);
Superclass::ApplyColorAndOpacityProperties(renderer, ls->m_CrosshairHelperLineActor);
float thickness;
this->GetDataNode()->GetFloatProperty("Line width",thickness,renderer);
ls->m_CrosshairActor->GetProperty()->SetLineWidth(thickness);
ls->m_CrosshairHelperLineActor->GetProperty()->SetLineWidth(thickness);
PlaneOrientationProperty* decorationProperty;
this->GetDataNode()->GetProperty( decorationProperty, "decoration", renderer );
if ( decorationProperty != NULL )
{
if ( decorationProperty->GetPlaneDecoration() ==
PlaneOrientationProperty::PLANE_DECORATION_POSITIVE_ORIENTATION )
{
m_RenderOrientationArrows = true;
m_ArrowOrientationPositive = true;
}
else if ( decorationProperty->GetPlaneDecoration() ==
PlaneOrientationProperty::PLANE_DECORATION_NEGATIVE_ORIENTATION )
{
m_RenderOrientationArrows = true;
m_ArrowOrientationPositive = false;
}
else
{
m_RenderOrientationArrows = false;
}
}
}
void mitk::PlaneGeometryDataMapper2D::SetDefaultProperties(mitk::DataNode* node, mitk::BaseRenderer* renderer, bool overwrite)
{
mitk::IPropertyAliases* aliases = mitk::CoreServices::GetPropertyAliases();
node->AddProperty( "Line width", mitk::FloatProperty::New(1), renderer, overwrite );
aliases->AddAlias( "line width", "Crosshair.Line Width", "");
node->AddProperty( "Crosshair.Gap Size", mitk::IntProperty::New(32), renderer, overwrite );
node->AddProperty( "decoration", mitk::PlaneOrientationProperty
::New(PlaneOrientationProperty::PLANE_DECORATION_NONE), renderer, overwrite );
aliases->AddAlias( "decoration", "Crosshair.Orientation Decoration", "");
Superclass::SetDefaultProperties(node, renderer, overwrite);
}
void mitk::PlaneGeometryDataMapper2D::UpdateVtkTransform(mitk::BaseRenderer* /*renderer*/)
{
}
mitk::PlaneGeometryDataMapper2D::LocalStorage::LocalStorage()
{
m_CrosshairAssembly = vtkSmartPointer <vtkPropAssembly>::New();
m_CrosshairActor = vtkSmartPointer <vtkActor>::New();
m_CrosshairHelperLineActor = vtkSmartPointer <vtkActor>::New();
m_CrosshairAssembly->AddPart(m_CrosshairActor);
m_CrosshairAssembly->AddPart(m_CrosshairHelperLineActor);
}
mitk::PlaneGeometryDataMapper2D::LocalStorage::~LocalStorage()
{
}
<commit_msg>transform boundingbox to index coordinates before intersection<commit_after>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "mitkPlaneGeometryDataMapper2D.h"
//mitk includes
#include "mitkVtkPropRenderer.h"
#include <mitkProperties.h>
#include <mitkDataNode.h>
#include <mitkPointSet.h>
#include <mitkPlaneGeometry.h>
#include <mitkPlaneOrientationProperty.h>
#include <mitkLine.h>
#include <mitkAbstractTransformGeometry.h>
#include <mitkResliceMethodProperty.h>
#include <mitkSlicedGeometry3D.h>
//vtk includes
#include <mitkIPropertyAliases.h>
#include <vtkActor.h>
#include <vtkCellArray.h>
#include <vtkCellData.h>
#include <vtkLine.h>
#include <vtkPoints.h>
#include <vtkPolyData.h>
mitk::PlaneGeometryDataMapper2D::AllInstancesContainer mitk::PlaneGeometryDataMapper2D::s_AllInstances;
// input for this mapper ( = PlaneGeometryData)
const mitk::PlaneGeometryData* mitk::PlaneGeometryDataMapper2D::GetInput() const
{
return static_cast< PlaneGeometryData * >(GetDataNode()->GetData());
}
mitk::PlaneGeometryDataMapper2D::PlaneGeometryDataMapper2D()
: m_RenderOrientationArrows( false ),
m_ArrowOrientationPositive( true ),
m_DepthValue(1.0f)
{
s_AllInstances.insert(this);
}
mitk::PlaneGeometryDataMapper2D::~PlaneGeometryDataMapper2D()
{
s_AllInstances.erase(this);
}
vtkProp* mitk::PlaneGeometryDataMapper2D::GetVtkProp(mitk::BaseRenderer * renderer)
{
LocalStorage *ls = m_LSH.GetLocalStorage(renderer);
return ls->m_CrosshairAssembly;
}
void mitk::PlaneGeometryDataMapper2D::GenerateDataForRenderer( mitk::BaseRenderer *renderer )
{
BaseLocalStorage *ls = m_LSH.GetLocalStorage(renderer);
// The PlaneGeometryDataMapper2D mapper is special in that the rendering of
// OTHER PlaneGeometryDatas affects how we render THIS PlaneGeometryData
// (for the gap at the point where they intersect). A change in any of the
// other PlaneGeometryData nodes could mean that we render ourself
// differently, so we check for that here.
bool generateDataRequired = false;
for (AllInstancesContainer::iterator it = s_AllInstances.begin();
it != s_AllInstances.end();
++it)
{
generateDataRequired = ls->IsGenerateDataRequired(renderer, this, (*it)->GetDataNode());
if (generateDataRequired) break;
}
ls->UpdateGenerateDataTime();
// Collect all other PlaneGeometryDatas that are being mapped by this mapper
m_OtherPlaneGeometries.clear();
for (AllInstancesContainer::iterator it = s_AllInstances.begin(); it != s_AllInstances.end(); ++it)
{
Self *otherInstance = *it;
// Skip ourself
if (otherInstance == this) continue;
mitk::DataNode *otherNode = otherInstance->GetDataNode();
if (!otherNode) continue;
// Skip other PlaneGeometryData nodes that are not visible on this renderer
if (!otherNode->IsVisible(renderer)) continue;
PlaneGeometryData* otherData = dynamic_cast<PlaneGeometryData*>(otherNode->GetData());
if (!otherData) continue;
PlaneGeometry* otherGeometry = dynamic_cast<PlaneGeometry*>(otherData->GetPlaneGeometry());
if ( otherGeometry && !dynamic_cast<AbstractTransformGeometry*>(otherData->GetPlaneGeometry()) )
{
m_OtherPlaneGeometries.push_back(otherNode);
}
}
CreateVtkCrosshair(renderer);
ApplyAllProperties(renderer);
}
void mitk::PlaneGeometryDataMapper2D::CreateVtkCrosshair(mitk::BaseRenderer *renderer)
{
bool visible = true;
GetDataNode()->GetVisibility(visible, renderer, "visible");
if(!visible) return;
PlaneGeometryData::Pointer input = const_cast< PlaneGeometryData * >(this->GetInput());
mitk::DataNode* geometryDataNode = renderer->GetCurrentWorldPlaneGeometryNode();
const PlaneGeometryData* rendererWorldPlaneGeometryData = dynamic_cast< PlaneGeometryData * >(geometryDataNode->GetData());
// intersecting with ourself?
if ( input.IsNull() || input.GetPointer() == rendererWorldPlaneGeometryData)
{
return; //nothing to do in this case
}
const PlaneGeometry *inputPlaneGeometry = dynamic_cast< const PlaneGeometry * >( input->GetPlaneGeometry() );
const PlaneGeometry* worldPlaneGeometry = dynamic_cast< const PlaneGeometry* >(
rendererWorldPlaneGeometryData->GetPlaneGeometry() );
if ( worldPlaneGeometry && dynamic_cast<const AbstractTransformGeometry*>(worldPlaneGeometry)==NULL
&& inputPlaneGeometry && dynamic_cast<const AbstractTransformGeometry*>(input->GetPlaneGeometry() )==NULL
&& inputPlaneGeometry->GetReferenceGeometry() )
{
const BaseGeometry *referenceGeometry = inputPlaneGeometry->GetReferenceGeometry();
// calculate intersection of the plane data with the border of the
// world geometry rectangle
Point3D point1, point2;
Line3D crossLine;
// Calculate the intersection line of the input plane with the world plane
if ( worldPlaneGeometry->IntersectionLine( inputPlaneGeometry, crossLine ) )
{
Point3D boundingBoxMin, boundingBoxMax;
boundingBoxMin = referenceGeometry->GetCornerPoint(0);
boundingBoxMax = referenceGeometry->GetCornerPoint(7);
Point3D indexLinePoint;
Vector3D indexLineDirection;
referenceGeometry->WorldToIndex(crossLine.GetPoint(),indexLinePoint);
referenceGeometry->WorldToIndex(crossLine.GetDirection(),indexLineDirection);
referenceGeometry->WorldToIndex(boundingBoxMin,boundingBoxMin);
referenceGeometry->WorldToIndex(boundingBoxMax,boundingBoxMax);
// Then, clip this line with the (transformed) bounding box of the
// reference geometry.
Line3D::BoxLineIntersection(
boundingBoxMin[0], boundingBoxMin[1], boundingBoxMin[2],
boundingBoxMax[0], boundingBoxMax[1], boundingBoxMax[2],
indexLinePoint, indexLineDirection,
point1, point2 );
referenceGeometry->IndexToWorld(point1,point1);
referenceGeometry->IndexToWorld(point2,point2);
crossLine.SetPoints(point1,point2);
vtkSmartPointer<vtkCellArray> lines = vtkSmartPointer<vtkCellArray>::New();
vtkSmartPointer<vtkPoints> points = vtkSmartPointer<vtkPoints>::New();
vtkSmartPointer<vtkPolyData> linesPolyData = vtkSmartPointer<vtkPolyData>::New();
// Now iterate through all other lines displayed in this window and
// calculate the positions of intersection with the line to be
// rendered; these positions will be stored in lineParams to form a
// gap afterwards.
NodesVectorType::iterator otherPlanesIt = m_OtherPlaneGeometries.begin();
NodesVectorType::iterator otherPlanesEnd = m_OtherPlaneGeometries.end();
std::vector<Point3D> intersections;
intersections.push_back(point1);
otherPlanesIt = m_OtherPlaneGeometries.begin();
int gapsize = 32;
this->GetDataNode()->GetPropertyValue( "Crosshair.Gap Size",gapsize, NULL );
ScalarType lineLength = point1.EuclideanDistanceTo(point2);
DisplayGeometry *displayGeometry = renderer->GetDisplayGeometry();
ScalarType gapinmm = gapsize * displayGeometry->GetScaleFactorMMPerDisplayUnit();
float gapSizeParam = gapinmm / lineLength;
while ( otherPlanesIt != otherPlanesEnd )
{
PlaneGeometry *otherPlane = static_cast< PlaneGeometry * >(
static_cast< PlaneGeometryData * >((*otherPlanesIt)->GetData() )->GetPlaneGeometry() );
if (otherPlane != inputPlaneGeometry && otherPlane != worldPlaneGeometry)
{
Point3D planeIntersection;
otherPlane->IntersectionPoint(crossLine,planeIntersection);
ScalarType sectionLength = point1.EuclideanDistanceTo(planeIntersection);
ScalarType lineValue = sectionLength/lineLength;
if(lineValue-gapSizeParam > 0.0)
intersections.push_back(crossLine.GetPoint(lineValue-gapSizeParam));
else intersections.pop_back();
if(lineValue+gapSizeParam < 1.0)
intersections.push_back(crossLine.GetPoint(lineValue+gapSizeParam));
}
++otherPlanesIt;
}
if(intersections.size()%2 == 1)
intersections.push_back(point2);
if(intersections.empty())
{
this->DrawLine(point1,point2,lines,points);
}
else
for(unsigned int i = 0 ; i< intersections.size()-1 ; i+=2)
{
this->DrawLine(intersections[i],intersections[i+1],lines,points);
}
// Add the points to the dataset
linesPolyData->SetPoints(points);
// Add the lines to the dataset
linesPolyData->SetLines(lines);
// Visualize
vtkSmartPointer<vtkPolyDataMapper> mapper = vtkSmartPointer<vtkPolyDataMapper>::New();
mapper->SetInputData(linesPolyData);
LocalStorage* ls = m_LSH.GetLocalStorage(renderer);
ls->m_CrosshairActor->SetMapper(mapper);
// Determine if we should draw the area covered by the thick slicing, default is false.
// This will also show the area of slices that do not have thick slice mode enabled
bool showAreaOfThickSlicing = false;
GetDataNode()->GetBoolProperty( "reslice.thickslices.showarea", showAreaOfThickSlicing );
// get the normal of the inputPlaneGeometry
Vector3D normal = inputPlaneGeometry->GetNormal();
// determine the pixelSpacing in that direction
double thickSliceDistance = SlicedGeometry3D::CalculateSpacing( referenceGeometry->GetSpacing(), normal );
IntProperty *intProperty=0;
if( GetDataNode()->GetProperty( intProperty, "reslice.thickslices.num" ) && intProperty )
thickSliceDistance *= intProperty->GetValue()+0.5;
else
showAreaOfThickSlicing = false;
// not the nicest place to do it, but we have the width of the visible bloc in MM here
// so we store it in this fancy property
GetDataNode()->SetFloatProperty( "reslice.thickslices.sizeinmm", thickSliceDistance*2 );
if ( showAreaOfThickSlicing )
{
vtkSmartPointer<vtkCellArray> helperlines = vtkSmartPointer<vtkCellArray>::New();
vtkSmartPointer<vtkPolyData> helperlinesPolyData = vtkSmartPointer<vtkPolyData>::New();
// vectorToHelperLine defines how to reach the helperLine from the mainLine
Vector3D vectorToHelperLine;
vectorToHelperLine = normal;
vectorToHelperLine.Normalize();
// got the right direction, so we multiply the width
vectorToHelperLine *= thickSliceDistance;
this->DrawLine(point1 - vectorToHelperLine, point2 - vectorToHelperLine,helperlines,points);
this->DrawLine(point1 + vectorToHelperLine, point2 + vectorToHelperLine,helperlines,points);
// Add the points to the dataset
helperlinesPolyData->SetPoints(points);
// Add the lines to the dataset
helperlinesPolyData->SetLines(helperlines);
// Visualize
vtkSmartPointer<vtkPolyDataMapper> helperLinesmapper = vtkSmartPointer<vtkPolyDataMapper>::New();
helperLinesmapper->SetInputData(helperlinesPolyData);
ls->m_CrosshairActor->GetProperty()->SetLineStipplePattern(0xf0f0);
ls->m_CrosshairActor->GetProperty()->SetLineStippleRepeatFactor(1);
ls->m_CrosshairHelperLineActor->SetMapper(helperLinesmapper);
ls->m_CrosshairAssembly->AddPart(ls->m_CrosshairHelperLineActor);
}
else
{
ls->m_CrosshairAssembly->RemovePart(ls->m_CrosshairHelperLineActor);
ls->m_CrosshairActor->GetProperty()->SetLineStipplePattern(0xffff);
}
}
}
}
void mitk::PlaneGeometryDataMapper2D::DrawLine( mitk::Point3D p0,mitk::Point3D p1,
vtkCellArray* lines,
vtkPoints* points
)
{
vtkIdType pidStart = points->InsertNextPoint(p0[0],p0[1], p0[2]);
vtkIdType pidEnd = points->InsertNextPoint(p1[0],p1[1], p1[2]);
vtkSmartPointer<vtkLine> lineVtk = vtkSmartPointer<vtkLine>::New();
lineVtk->GetPointIds()->SetId(0,pidStart);
lineVtk->GetPointIds()->SetId(1,pidEnd);
lines->InsertNextCell(lineVtk);
}
int mitk::PlaneGeometryDataMapper2D::DetermineThickSliceMode( DataNode * dn, int &thickSlicesNum )
{
int thickSlicesMode = 0;
// determine the state and the extend of the thick-slice mode
mitk::ResliceMethodProperty *resliceMethodEnumProperty=0;
if( dn->GetProperty( resliceMethodEnumProperty, "reslice.thickslices" ) && resliceMethodEnumProperty )
thickSlicesMode = resliceMethodEnumProperty->GetValueAsId();
IntProperty *intProperty=0;
if( dn->GetProperty( intProperty, "reslice.thickslices.num" ) && intProperty )
{
thickSlicesNum = intProperty->GetValue();
if(thickSlicesNum < 1) thickSlicesNum=0;
if(thickSlicesNum > 10) thickSlicesNum=10;
}
if ( thickSlicesMode == 0 )
thickSlicesNum = 0;
return thickSlicesMode;
}
void mitk::PlaneGeometryDataMapper2D::ApplyAllProperties( BaseRenderer *renderer )
{
LocalStorage *ls = m_LSH.GetLocalStorage(renderer);
Superclass::ApplyColorAndOpacityProperties(renderer, ls->m_CrosshairActor);
Superclass::ApplyColorAndOpacityProperties(renderer, ls->m_CrosshairHelperLineActor);
float thickness;
this->GetDataNode()->GetFloatProperty("Line width",thickness,renderer);
ls->m_CrosshairActor->GetProperty()->SetLineWidth(thickness);
ls->m_CrosshairHelperLineActor->GetProperty()->SetLineWidth(thickness);
PlaneOrientationProperty* decorationProperty;
this->GetDataNode()->GetProperty( decorationProperty, "decoration", renderer );
if ( decorationProperty != NULL )
{
if ( decorationProperty->GetPlaneDecoration() ==
PlaneOrientationProperty::PLANE_DECORATION_POSITIVE_ORIENTATION )
{
m_RenderOrientationArrows = true;
m_ArrowOrientationPositive = true;
}
else if ( decorationProperty->GetPlaneDecoration() ==
PlaneOrientationProperty::PLANE_DECORATION_NEGATIVE_ORIENTATION )
{
m_RenderOrientationArrows = true;
m_ArrowOrientationPositive = false;
}
else
{
m_RenderOrientationArrows = false;
}
}
}
void mitk::PlaneGeometryDataMapper2D::SetDefaultProperties(mitk::DataNode* node, mitk::BaseRenderer* renderer, bool overwrite)
{
mitk::IPropertyAliases* aliases = mitk::CoreServices::GetPropertyAliases();
node->AddProperty( "Line width", mitk::FloatProperty::New(1), renderer, overwrite );
aliases->AddAlias( "line width", "Crosshair.Line Width", "");
node->AddProperty( "Crosshair.Gap Size", mitk::IntProperty::New(32), renderer, overwrite );
node->AddProperty( "decoration", mitk::PlaneOrientationProperty
::New(PlaneOrientationProperty::PLANE_DECORATION_NONE), renderer, overwrite );
aliases->AddAlias( "decoration", "Crosshair.Orientation Decoration", "");
Superclass::SetDefaultProperties(node, renderer, overwrite);
}
void mitk::PlaneGeometryDataMapper2D::UpdateVtkTransform(mitk::BaseRenderer* /*renderer*/)
{
}
mitk::PlaneGeometryDataMapper2D::LocalStorage::LocalStorage()
{
m_CrosshairAssembly = vtkSmartPointer <vtkPropAssembly>::New();
m_CrosshairActor = vtkSmartPointer <vtkActor>::New();
m_CrosshairHelperLineActor = vtkSmartPointer <vtkActor>::New();
m_CrosshairAssembly->AddPart(m_CrosshairActor);
m_CrosshairAssembly->AddPart(m_CrosshairHelperLineActor);
}
mitk::PlaneGeometryDataMapper2D::LocalStorage::~LocalStorage()
{
}
<|endoftext|>
|
<commit_before>// 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 "views/controls/tabbed_pane/native_tabbed_pane_win.h"
#include <vssym32.h>
#include "app/gfx/canvas.h"
#include "app/gfx/font.h"
#include "app/l10n_util_win.h"
#include "app/resource_bundle.h"
#include "base/gfx/native_theme.h"
#include "base/logging.h"
#include "base/stl_util-inl.h"
#include "views/controls/tabbed_pane/tabbed_pane.h"
#include "views/fill_layout.h"
#include "views/widget/root_view.h"
#include "views/widget/widget_win.h"
namespace views {
// A background object that paints the tab panel background which may be
// rendered by the system visual styles system.
class TabBackground : public Background {
public:
explicit TabBackground() {
// TMT_FILLCOLORHINT returns a color value that supposedly
// approximates the texture drawn by PaintTabPanelBackground.
SkColor tab_page_color =
gfx::NativeTheme::instance()->GetThemeColorWithDefault(
gfx::NativeTheme::TAB, TABP_BODY, 0, TMT_FILLCOLORHINT,
COLOR_3DFACE);
SetNativeControlColor(tab_page_color);
}
virtual ~TabBackground() {}
virtual void Paint(gfx::Canvas* canvas, View* view) const {
HDC dc = canvas->beginPlatformPaint();
RECT r = {0, 0, view->width(), view->height()};
gfx::NativeTheme::instance()->PaintTabPanelBackground(dc, &r);
canvas->endPlatformPaint();
}
private:
DISALLOW_COPY_AND_ASSIGN(TabBackground);
};
////////////////////////////////////////////////////////////////////////////////
// NativeTabbedPaneWin, public:
NativeTabbedPaneWin::NativeTabbedPaneWin(TabbedPane* tabbed_pane)
: NativeControlWin(),
tabbed_pane_(tabbed_pane),
content_window_(NULL),
selected_index_(-1) {
// Associates the actual HWND with the tabbed-pane so the tabbed-pane is
// the one considered as having the focus (not the wrapper) when the HWND is
// focused directly (with a click for example).
set_focus_view(tabbed_pane);
}
NativeTabbedPaneWin::~NativeTabbedPaneWin() {
// We own the tab views, let's delete them.
STLDeleteContainerPointers(tab_views_.begin(), tab_views_.end());
}
////////////////////////////////////////////////////////////////////////////////
// NativeTabbedPaneWin, NativeTabbedPaneWrapper implementation:
void NativeTabbedPaneWin::AddTab(const std::wstring& title, View* contents) {
AddTabAtIndex(static_cast<int>(tab_views_.size()), title, contents, true);
}
void NativeTabbedPaneWin::AddTabAtIndex(int index, const std::wstring& title,
View* contents,
bool select_if_first_tab) {
DCHECK(index <= static_cast<int>(tab_views_.size()));
contents->SetParentOwned(false);
tab_views_.insert(tab_views_.begin() + index, contents);
tab_titles_.insert(tab_titles_.begin() + index, title);
if (!contents->background())
contents->set_background(new TabBackground);
if (tab_views_.size() == 1 && select_if_first_tab) {
// If this is the only tab displayed, make sure the contents is set.
selected_index_ = 0;
if (content_window_)
content_window_->GetRootView()->AddChildView(contents);
}
// Add native tab only if the native control is alreay created.
if (content_window_) {
AddNativeTab(index, title, contents);
// The newly added tab may have made the contents window smaller.
ResizeContents();
}
}
void NativeTabbedPaneWin::AddNativeTab(int index,
const std::wstring &title,
views::View* contents) {
TCITEM tcitem;
tcitem.mask = TCIF_TEXT;
// If the locale is RTL, we set the TCIF_RTLREADING so that BiDi text is
// rendered properly on the tabs.
if (UILayoutIsRightToLeft()) {
tcitem.mask |= TCIF_RTLREADING;
}
tcitem.pszText = const_cast<wchar_t*>(title.c_str());
int result = TabCtrl_InsertItem(native_view(), index, &tcitem);
DCHECK(result != -1);
}
View* NativeTabbedPaneWin::RemoveTabAtIndex(int index) {
int tab_count = static_cast<int>(tab_views_.size());
DCHECK(index >= 0 && index < tab_count);
if (index < (tab_count - 1)) {
// Select the next tab.
SelectTabAt(index + 1);
} else {
// We are the last tab, select the previous one.
if (index > 0) {
SelectTabAt(index - 1);
} else if (content_window_) {
// That was the last tab. Remove the contents.
content_window_->GetRootView()->RemoveAllChildViews(false);
}
}
TabCtrl_DeleteItem(native_view(), index);
// The removed tab may have made the contents window bigger.
ResizeContents();
std::vector<View*>::iterator iter = tab_views_.begin() + index;
View* removed_tab = *iter;
tab_views_.erase(iter);
tab_titles_.erase(tab_titles_.begin() + index);
return removed_tab;
}
void NativeTabbedPaneWin::SelectTabAt(int index) {
DCHECK((index >= 0) && (index < static_cast<int>(tab_views_.size())));
if (native_view())
TabCtrl_SetCurSel(native_view(), index);
DoSelectTabAt(index, true);
}
int NativeTabbedPaneWin::GetTabCount() {
return TabCtrl_GetItemCount(native_view());
}
int NativeTabbedPaneWin::GetSelectedTabIndex() {
return TabCtrl_GetCurSel(native_view());
}
View* NativeTabbedPaneWin::GetSelectedTab() {
if (selected_index_ < 0)
return NULL;
return tab_views_[selected_index_];
}
View* NativeTabbedPaneWin::GetView() {
return this;
}
void NativeTabbedPaneWin::SetFocus() {
// Focus the associated HWND.
Focus();
}
gfx::NativeView NativeTabbedPaneWin::GetTestingHandle() const {
return native_view();
}
////////////////////////////////////////////////////////////////////////////////
// NativeTabbedPaneWin, NativeControlWin override:
void NativeTabbedPaneWin::CreateNativeControl() {
// Create the tab control.
//
// Note that we don't follow the common convention for NativeControl
// subclasses and we don't pass the value returned from
// NativeControl::GetAdditionalExStyle() as the dwExStyle parameter. Here is
// why: on RTL locales, if we pass NativeControl::GetAdditionalExStyle() when
// we basically tell Windows to create our HWND with the WS_EX_LAYOUTRTL. If
// we do that, then the HWND we create for |content_window_| below will
// inherit the WS_EX_LAYOUTRTL property and this will result in the contents
// being flipped, which is not what we want (because we handle mirroring in
// views without the use of Windows' support for mirroring). Therefore,
// we initially create our HWND without the aforementioned property and we
// explicitly set this property our child is created. This way, on RTL
// locales, our tabs will be nicely rendered from right to left (by virtue of
// Windows doing the right thing with the TabbedPane HWND) and each tab
// contents will use an RTL layout correctly (by virtue of the mirroring
// infrastructure in views doing the right thing with each View we put
// in the tab).
HWND tab_control = ::CreateWindowEx(0,
WC_TABCONTROL,
L"",
WS_CHILD | WS_CLIPSIBLINGS | WS_VISIBLE,
0, 0, width(), height(),
GetWidget()->GetNativeView(), NULL, NULL,
NULL);
HFONT font = ResourceBundle::GetSharedInstance().
GetFont(ResourceBundle::BaseFont).hfont();
SendMessage(tab_control, WM_SETFONT, reinterpret_cast<WPARAM>(font), FALSE);
// Create the view container which is a child of the TabControl.
content_window_ = new WidgetWin();
content_window_->Init(tab_control, gfx::Rect());
// Explicitly setting the WS_EX_LAYOUTRTL property for the HWND (see above
// for a thorough explanation regarding why we waited until |content_window_|
// if created before we set this property for the tabbed pane's HWND).
if (UILayoutIsRightToLeft())
l10n_util::HWNDSetRTLLayout(tab_control);
RootView* root_view = content_window_->GetRootView();
root_view->SetLayoutManager(new FillLayout());
DWORD sys_color = ::GetSysColor(COLOR_3DHILIGHT);
SkColor color = SkColorSetRGB(GetRValue(sys_color), GetGValue(sys_color),
GetBValue(sys_color));
root_view->set_background(Background::CreateSolidBackground(color));
content_window_->SetFocusTraversableParentView(this);
NativeControlCreated(tab_control);
// Add tabs that are already added if any.
if (tab_views_.size() > 0) {
InitializeTabs();
if (selected_index_ >= 0)
DoSelectTabAt(selected_index_, false);
}
ResizeContents();
}
bool NativeTabbedPaneWin::ProcessMessage(UINT message,
WPARAM w_param,
LPARAM l_param,
LRESULT* result) {
if (message == WM_NOTIFY &&
reinterpret_cast<LPNMHDR>(l_param)->code == TCN_SELCHANGE) {
int selected_tab = TabCtrl_GetCurSel(native_view());
DCHECK(selected_tab != -1);
DoSelectTabAt(selected_tab, true);
return TRUE;
}
return NativeControlWin::ProcessMessage(message, w_param, l_param, result);
}
////////////////////////////////////////////////////////////////////////////////
// View override:
void NativeTabbedPaneWin::Layout() {
NativeControlWin::Layout();
ResizeContents();
}
FocusTraversable* NativeTabbedPaneWin::GetFocusTraversable() {
return content_window_;
}
void NativeTabbedPaneWin::ViewHierarchyChanged(bool is_add,
View *parent,
View *child) {
NativeControlWin::ViewHierarchyChanged(is_add, parent, child);
if (is_add && (child == this) && content_window_) {
// We have been added to a view hierarchy, update the FocusTraversable
// parent.
content_window_->SetFocusTraversableParent(GetRootView());
}
}
////////////////////////////////////////////////////////////////////////////////
// NativeTabbedPaneWin, private:
void NativeTabbedPaneWin::InitializeTabs() {
for (size_t i = 0; i < tab_views_.size(); ++i) {
AddNativeTab(i, tab_titles_[i], tab_views_[i]);
}
}
void NativeTabbedPaneWin::DoSelectTabAt(int index, boolean invoke_listener) {
selected_index_ = index;
if (content_window_) {
RootView* content_root = content_window_->GetRootView();
// Clear the focus if the focused view was on the tab.
FocusManager* focus_manager = GetFocusManager();
DCHECK(focus_manager);
View* focused_view = focus_manager->GetFocusedView();
if (focused_view && content_root->IsParentOf(focused_view))
focus_manager->ClearFocus();
content_root->RemoveAllChildViews(false);
content_root->AddChildView(tab_views_[index]);
content_root->Layout();
}
if (invoke_listener && tabbed_pane_->listener())
tabbed_pane_->listener()->TabSelectedAt(index);
}
void NativeTabbedPaneWin::ResizeContents() {
CRect content_bounds;
if (!GetClientRect(native_view(), &content_bounds))
return;
TabCtrl_AdjustRect(native_view(), FALSE, &content_bounds);
content_window_->MoveWindow(content_bounds.left, content_bounds.top,
content_bounds.Width(), content_bounds.Height(),
TRUE);
}
////////////////////////////////////////////////////////////////////////////////
// NativeTabbedPaneWrapper, public:
// static
NativeTabbedPaneWrapper* NativeTabbedPaneWrapper::CreateNativeWrapper(
TabbedPane* tabbed_pane) {
return new NativeTabbedPaneWin(tabbed_pane);
}
} // namespace views
<commit_msg>Fix possible null pointer dereference.<commit_after>// 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 "views/controls/tabbed_pane/native_tabbed_pane_win.h"
#include <vssym32.h>
#include "app/gfx/canvas.h"
#include "app/gfx/font.h"
#include "app/l10n_util_win.h"
#include "app/resource_bundle.h"
#include "base/gfx/native_theme.h"
#include "base/logging.h"
#include "base/stl_util-inl.h"
#include "views/controls/tabbed_pane/tabbed_pane.h"
#include "views/fill_layout.h"
#include "views/widget/root_view.h"
#include "views/widget/widget_win.h"
namespace views {
// A background object that paints the tab panel background which may be
// rendered by the system visual styles system.
class TabBackground : public Background {
public:
explicit TabBackground() {
// TMT_FILLCOLORHINT returns a color value that supposedly
// approximates the texture drawn by PaintTabPanelBackground.
SkColor tab_page_color =
gfx::NativeTheme::instance()->GetThemeColorWithDefault(
gfx::NativeTheme::TAB, TABP_BODY, 0, TMT_FILLCOLORHINT,
COLOR_3DFACE);
SetNativeControlColor(tab_page_color);
}
virtual ~TabBackground() {}
virtual void Paint(gfx::Canvas* canvas, View* view) const {
HDC dc = canvas->beginPlatformPaint();
RECT r = {0, 0, view->width(), view->height()};
gfx::NativeTheme::instance()->PaintTabPanelBackground(dc, &r);
canvas->endPlatformPaint();
}
private:
DISALLOW_COPY_AND_ASSIGN(TabBackground);
};
////////////////////////////////////////////////////////////////////////////////
// NativeTabbedPaneWin, public:
NativeTabbedPaneWin::NativeTabbedPaneWin(TabbedPane* tabbed_pane)
: NativeControlWin(),
tabbed_pane_(tabbed_pane),
content_window_(NULL),
selected_index_(-1) {
// Associates the actual HWND with the tabbed-pane so the tabbed-pane is
// the one considered as having the focus (not the wrapper) when the HWND is
// focused directly (with a click for example).
set_focus_view(tabbed_pane);
}
NativeTabbedPaneWin::~NativeTabbedPaneWin() {
// We own the tab views, let's delete them.
STLDeleteContainerPointers(tab_views_.begin(), tab_views_.end());
}
////////////////////////////////////////////////////////////////////////////////
// NativeTabbedPaneWin, NativeTabbedPaneWrapper implementation:
void NativeTabbedPaneWin::AddTab(const std::wstring& title, View* contents) {
AddTabAtIndex(static_cast<int>(tab_views_.size()), title, contents, true);
}
void NativeTabbedPaneWin::AddTabAtIndex(int index, const std::wstring& title,
View* contents,
bool select_if_first_tab) {
DCHECK(index <= static_cast<int>(tab_views_.size()));
contents->SetParentOwned(false);
tab_views_.insert(tab_views_.begin() + index, contents);
tab_titles_.insert(tab_titles_.begin() + index, title);
if (!contents->background())
contents->set_background(new TabBackground);
if (tab_views_.size() == 1 && select_if_first_tab) {
// If this is the only tab displayed, make sure the contents is set.
selected_index_ = 0;
if (content_window_)
content_window_->GetRootView()->AddChildView(contents);
}
// Add native tab only if the native control is alreay created.
if (content_window_) {
AddNativeTab(index, title, contents);
// The newly added tab may have made the contents window smaller.
ResizeContents();
}
}
void NativeTabbedPaneWin::AddNativeTab(int index,
const std::wstring &title,
views::View* contents) {
TCITEM tcitem;
tcitem.mask = TCIF_TEXT;
// If the locale is RTL, we set the TCIF_RTLREADING so that BiDi text is
// rendered properly on the tabs.
if (UILayoutIsRightToLeft()) {
tcitem.mask |= TCIF_RTLREADING;
}
tcitem.pszText = const_cast<wchar_t*>(title.c_str());
int result = TabCtrl_InsertItem(native_view(), index, &tcitem);
DCHECK(result != -1);
}
View* NativeTabbedPaneWin::RemoveTabAtIndex(int index) {
int tab_count = static_cast<int>(tab_views_.size());
DCHECK(index >= 0 && index < tab_count);
if (index < (tab_count - 1)) {
// Select the next tab.
SelectTabAt(index + 1);
} else {
// We are the last tab, select the previous one.
if (index > 0) {
SelectTabAt(index - 1);
} else if (content_window_) {
// That was the last tab. Remove the contents.
content_window_->GetRootView()->RemoveAllChildViews(false);
}
}
TabCtrl_DeleteItem(native_view(), index);
// The removed tab may have made the contents window bigger.
if (content_window_)
ResizeContents();
std::vector<View*>::iterator iter = tab_views_.begin() + index;
View* removed_tab = *iter;
tab_views_.erase(iter);
tab_titles_.erase(tab_titles_.begin() + index);
return removed_tab;
}
void NativeTabbedPaneWin::SelectTabAt(int index) {
DCHECK((index >= 0) && (index < static_cast<int>(tab_views_.size())));
if (native_view())
TabCtrl_SetCurSel(native_view(), index);
DoSelectTabAt(index, true);
}
int NativeTabbedPaneWin::GetTabCount() {
return TabCtrl_GetItemCount(native_view());
}
int NativeTabbedPaneWin::GetSelectedTabIndex() {
return TabCtrl_GetCurSel(native_view());
}
View* NativeTabbedPaneWin::GetSelectedTab() {
if (selected_index_ < 0)
return NULL;
return tab_views_[selected_index_];
}
View* NativeTabbedPaneWin::GetView() {
return this;
}
void NativeTabbedPaneWin::SetFocus() {
// Focus the associated HWND.
Focus();
}
gfx::NativeView NativeTabbedPaneWin::GetTestingHandle() const {
return native_view();
}
////////////////////////////////////////////////////////////////////////////////
// NativeTabbedPaneWin, NativeControlWin override:
void NativeTabbedPaneWin::CreateNativeControl() {
// Create the tab control.
//
// Note that we don't follow the common convention for NativeControl
// subclasses and we don't pass the value returned from
// NativeControl::GetAdditionalExStyle() as the dwExStyle parameter. Here is
// why: on RTL locales, if we pass NativeControl::GetAdditionalExStyle() when
// we basically tell Windows to create our HWND with the WS_EX_LAYOUTRTL. If
// we do that, then the HWND we create for |content_window_| below will
// inherit the WS_EX_LAYOUTRTL property and this will result in the contents
// being flipped, which is not what we want (because we handle mirroring in
// views without the use of Windows' support for mirroring). Therefore,
// we initially create our HWND without the aforementioned property and we
// explicitly set this property our child is created. This way, on RTL
// locales, our tabs will be nicely rendered from right to left (by virtue of
// Windows doing the right thing with the TabbedPane HWND) and each tab
// contents will use an RTL layout correctly (by virtue of the mirroring
// infrastructure in views doing the right thing with each View we put
// in the tab).
HWND tab_control = ::CreateWindowEx(0,
WC_TABCONTROL,
L"",
WS_CHILD | WS_CLIPSIBLINGS | WS_VISIBLE,
0, 0, width(), height(),
GetWidget()->GetNativeView(), NULL, NULL,
NULL);
HFONT font = ResourceBundle::GetSharedInstance().
GetFont(ResourceBundle::BaseFont).hfont();
SendMessage(tab_control, WM_SETFONT, reinterpret_cast<WPARAM>(font), FALSE);
// Create the view container which is a child of the TabControl.
content_window_ = new WidgetWin();
content_window_->Init(tab_control, gfx::Rect());
// Explicitly setting the WS_EX_LAYOUTRTL property for the HWND (see above
// for a thorough explanation regarding why we waited until |content_window_|
// if created before we set this property for the tabbed pane's HWND).
if (UILayoutIsRightToLeft())
l10n_util::HWNDSetRTLLayout(tab_control);
RootView* root_view = content_window_->GetRootView();
root_view->SetLayoutManager(new FillLayout());
DWORD sys_color = ::GetSysColor(COLOR_3DHILIGHT);
SkColor color = SkColorSetRGB(GetRValue(sys_color), GetGValue(sys_color),
GetBValue(sys_color));
root_view->set_background(Background::CreateSolidBackground(color));
content_window_->SetFocusTraversableParentView(this);
NativeControlCreated(tab_control);
// Add tabs that are already added if any.
if (tab_views_.size() > 0) {
InitializeTabs();
if (selected_index_ >= 0)
DoSelectTabAt(selected_index_, false);
}
ResizeContents();
}
bool NativeTabbedPaneWin::ProcessMessage(UINT message,
WPARAM w_param,
LPARAM l_param,
LRESULT* result) {
if (message == WM_NOTIFY &&
reinterpret_cast<LPNMHDR>(l_param)->code == TCN_SELCHANGE) {
int selected_tab = TabCtrl_GetCurSel(native_view());
DCHECK(selected_tab != -1);
DoSelectTabAt(selected_tab, true);
return TRUE;
}
return NativeControlWin::ProcessMessage(message, w_param, l_param, result);
}
////////////////////////////////////////////////////////////////////////////////
// View override:
void NativeTabbedPaneWin::Layout() {
NativeControlWin::Layout();
ResizeContents();
}
FocusTraversable* NativeTabbedPaneWin::GetFocusTraversable() {
return content_window_;
}
void NativeTabbedPaneWin::ViewHierarchyChanged(bool is_add,
View *parent,
View *child) {
NativeControlWin::ViewHierarchyChanged(is_add, parent, child);
if (is_add && (child == this) && content_window_) {
// We have been added to a view hierarchy, update the FocusTraversable
// parent.
content_window_->SetFocusTraversableParent(GetRootView());
}
}
////////////////////////////////////////////////////////////////////////////////
// NativeTabbedPaneWin, private:
void NativeTabbedPaneWin::InitializeTabs() {
for (size_t i = 0; i < tab_views_.size(); ++i) {
AddNativeTab(i, tab_titles_[i], tab_views_[i]);
}
}
void NativeTabbedPaneWin::DoSelectTabAt(int index, boolean invoke_listener) {
selected_index_ = index;
if (content_window_) {
RootView* content_root = content_window_->GetRootView();
// Clear the focus if the focused view was on the tab.
FocusManager* focus_manager = GetFocusManager();
DCHECK(focus_manager);
View* focused_view = focus_manager->GetFocusedView();
if (focused_view && content_root->IsParentOf(focused_view))
focus_manager->ClearFocus();
content_root->RemoveAllChildViews(false);
content_root->AddChildView(tab_views_[index]);
content_root->Layout();
}
if (invoke_listener && tabbed_pane_->listener())
tabbed_pane_->listener()->TabSelectedAt(index);
}
void NativeTabbedPaneWin::ResizeContents() {
CRect content_bounds;
if (!GetClientRect(native_view(), &content_bounds))
return;
TabCtrl_AdjustRect(native_view(), FALSE, &content_bounds);
content_window_->MoveWindow(content_bounds.left, content_bounds.top,
content_bounds.Width(), content_bounds.Height(),
TRUE);
}
////////////////////////////////////////////////////////////////////////////////
// NativeTabbedPaneWrapper, public:
// static
NativeTabbedPaneWrapper* NativeTabbedPaneWrapper::CreateNativeWrapper(
TabbedPane* tabbed_pane) {
return new NativeTabbedPaneWin(tabbed_pane);
}
} // namespace views
<|endoftext|>
|
<commit_before>#include "gmock/gmock.h"
#include "tcframe/experimental/runner.hpp"
using ::testing::Test;
namespace tcframe {
class FakeProblem : public BaseProblem {
protected:
void InputFormat() {}
};
class FakeGenerator : public BaseGenerator<FakeProblem> {};
class RunnerTests : public Test {
protected:
int argc = 1;
char* argv[1] = {const_cast<char*>("./runner")};
Runner<FakeProblem> runner = Runner<FakeProblem>(argc, argv);
};
TEST_F(RunnerTests, CompilationSuccessful) {
runner.setGenerator(new FakeGenerator());
}
}
<commit_msg>Use safer cast from const char* literal to char*<commit_after>#include "gmock/gmock.h"
#include "tcframe/experimental/runner.hpp"
using ::testing::Test;
namespace tcframe {
class FakeProblem : public BaseProblem {
protected:
void InputFormat() {}
};
class FakeGenerator : public BaseGenerator<FakeProblem> {};
class RunnerTests : public Test {
protected:
int argc = 1;
char* argv[1] = {toChar("./runner")};
Runner<FakeProblem> runner = Runner<FakeProblem>(argc, argv);
private:
static char* toChar(const string& str) {
char* cstr = new char[str.length() + 1];
strcpy(cstr, str.c_str());
return cstr;
}
};
TEST_F(RunnerTests, CompilationSuccessful) {
runner.setGenerator(new FakeGenerator());
}
}
<|endoftext|>
|
<commit_before>#define BOOST_TEST_MODULE TestImpedanceSpectroscopy
#define BOOST_TEST_MAIN
#include <cap/energy_storage_device.h>
#include <boost/format.hpp>
#include <boost/foreach.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <boost/math/constants/constants.hpp>
#include <boost/test/unit_test.hpp>
#include <gsl/gsl_fft_real.h>
#include <iostream>
#include <fstream>
#include <complex>
namespace cap {
std::complex<double>
measure_impedance(std::shared_ptr<cap::EnergyStorageDevice> dev, std::shared_ptr<boost::property_tree::ptree const> database, std::ostream & os = std::cout);
void bar(std::shared_ptr<cap::EnergyStorageDevice> dev, std::shared_ptr<boost::property_tree::ptree const> database, std::ostream & os = std::cout)
{
double const frequency_lower_limit = database->get<double>("frequency_lower_limit");
double const frequency_upper_limit = database->get<double>("frequency_upper_limit");
double const ratio = database->get<double>("ratio" );
double const pi = boost::math::constants::pi<double>();
std::shared_ptr<boost::property_tree::ptree> tmp =
std::make_shared<boost::property_tree::ptree>(*database);
for (double frequency = frequency_lower_limit; frequency <= frequency_upper_limit; frequency *= ratio)
{
tmp->put("frequency", frequency);
std::complex<double> impedance =
measure_impedance(dev, tmp);
os<<boost::format( " %20.15e %20.15e %20.15e %20.15e %20.15e \n")
% frequency
% impedance.real()
% impedance.imag()
% std::abs(impedance)
% (std::arg(impedance) * 180.0 / pi)
;
}
}
std::complex<double>
measure_impedance(std::shared_ptr<cap::EnergyStorageDevice> dev, std::shared_ptr<boost::property_tree::ptree const> database, std::ostream & os)
{
double const frequency = database->get<double>("frequency" );
double const amplitude = database->get<double>("amplitude" );
int const cycles = database->get<int >("cycles" );
int const steps_per_cycle = database->get<int >("steps_per_cycle");
double const initial_voltage = 0.0;
std::vector<int> const powers_of_two =
{ 1, 2 ,4, 8, 16,
32, 64, 128, 256, 512,
1024, 2048, 4096, 8192, 16384,
32768, 65536, 131072, 262144, 524288
}; // first 20 powers of two
if (find(powers_of_two.begin(), powers_of_two.end(), (cycles-1)*steps_per_cycle) == powers_of_two.end())
throw std::runtime_error("(cycles-1)*steps_per_cycle must be a power of two");
double time = 0.0;
double const time_step = 1.0 / frequency / steps_per_cycle;
double const phase = std::asin(initial_voltage / amplitude);
double const pi = std::acos(-1.0);
dev->reset_voltage(initial_voltage);
double voltage;
double current;
std::vector<double> excitation;
std::vector<double> response;
for (int n = 0; n < cycles*steps_per_cycle; ++n)
{
time += time_step;
voltage = amplitude*std::sin(2.0*pi*frequency*time+phase);
dev->evolve_one_time_step_constant_voltage(time_step, voltage);
dev->get_current(current);
if (n >= steps_per_cycle)
{
excitation.push_back(voltage);
response .push_back(current);
}
// os<<boost::format(" %20.15e %20.15e %20.15e \n")
// % time
// % current
// % voltage
// ;
}
gsl_fft_real_radix2_transform(&(excitation[0]), 1, excitation.size());
gsl_fft_real_radix2_transform(&(response [0]), 1, response .size());
std::complex<double> const impedance =
std::complex<double>(excitation[(cycles-1)], excitation[excitation.size()-(cycles-1)])
/
std::complex<double>(response [(cycles-1)], response [response .size()-(cycles-1)]);
return impedance;
}
} // end namespace cap
BOOST_AUTO_TEST_CASE( test_measure_impedance )
{
// parse input file
std::shared_ptr<boost::property_tree::ptree> input_database =
std::make_shared<boost::property_tree::ptree>();
read_xml("input_impedance_spectroscopy", *input_database);
std::string const type = input_database->get<std::string>("device.type");
if ((type.compare("SeriesRC") != 0) && (type.compare("ParallelRC") != 0))
input_database->put("device.type", "ParallelRC");
std::string const duh = input_database->get<std::string>("device.type");
if (duh.compare("NoName") == 0)
throw std::runtime_error("duh");
// build an energy storage system
std::shared_ptr<boost::property_tree::ptree> device_database =
std::make_shared<boost::property_tree::ptree>(input_database->get_child("device"));
std::shared_ptr<cap::EnergyStorageDevice> device =
cap::buildEnergyStorageDevice(std::make_shared<cap::Parameters>(device_database));
double const frequency_lower_limit = input_database->get<double>("impedance_spectroscopy.frequency_lower_limit");
double const frequency_upper_limit = input_database->get<double>("impedance_spectroscopy.frequency_upper_limit");
double const ratio = input_database->get<double>("impedance_spectroscopy.ratio" );
double const series_resistance = input_database->get<double>("device.series_resistance" );
double const parallel_resistance = input_database->get<double>("device.parallel_resistance");
double const capacitance = input_database->get<double>("device.capacitance" );
double const pi = boost::math::constants::pi<double>();
double const percent_tolerance = 1.0e-1;
std::shared_ptr<boost::property_tree::ptree> impedance_spectroscopy_database =
std::make_shared<boost::property_tree::ptree>(input_database->get_child("impedance_spectroscopy"));
std::fstream fout("computed_vs_exact_impedance_spectroscopy_data", std::fstream::out);
for (double frequency = frequency_lower_limit; frequency < frequency_upper_limit; frequency *= ratio)
{
impedance_spectroscopy_database->put("frequency", frequency);
std::complex<double> computed_impedance = cap::measure_impedance(device, impedance_spectroscopy_database);
std::complex<double> exact_impedance =
((type.compare("SeriesRC") == 0) ?
series_resistance + 1.0 / std::complex<double>(0.0, capacitance * 2.0*pi*frequency) :
series_resistance + parallel_resistance / std::complex<double>(1.0, capacitance * parallel_resistance * 2.0*pi*frequency));
fout<<boost::format(" %22.15e %22.15e %22.15e %22.15e %22.15e %22.15e %22.15e %22.15e %22.15e \n")
% frequency
% computed_impedance.real()
% computed_impedance.imag()
% std::abs(computed_impedance)
% std::arg(computed_impedance)
% exact_impedance.real()
% exact_impedance.imag()
% std::abs(exact_impedance)
% std::arg(exact_impedance)
;
BOOST_CHECK_CLOSE(computed_impedance.real(), exact_impedance.real(), percent_tolerance);
BOOST_CHECK_CLOSE(computed_impedance.imag(), exact_impedance.imag(), percent_tolerance);
}
}
BOOST_AUTO_TEST_CASE( test_impedance_spectroscopy )
{
// parse input file
std::shared_ptr<boost::property_tree::ptree> input_database =
std::make_shared<boost::property_tree::ptree>();
read_xml("input_impedance_spectroscopy", *input_database);
// build an energy storage system
std::shared_ptr<boost::property_tree::ptree> device_database =
std::make_shared<boost::property_tree::ptree>(input_database->get_child("device"));
std::shared_ptr<cap::EnergyStorageDevice> device =
cap::buildEnergyStorageDevice(std::make_shared<cap::Parameters>(device_database));
// measure its impedance
std::fstream fout;
fout.open("impedance_spectroscopy_data", std::fstream::out);
std::shared_ptr<boost::property_tree::ptree> impedance_spectroscopy_database =
std::make_shared<boost::property_tree::ptree>(input_database->get_child("impedance_spectroscopy"));
cap::bar(device, impedance_spectroscopy_database, fout);
}
<commit_msg>print argument of the complex impedance in degrees<commit_after>#define BOOST_TEST_MODULE TestImpedanceSpectroscopy
#define BOOST_TEST_MAIN
#include <cap/energy_storage_device.h>
#include <boost/format.hpp>
#include <boost/foreach.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <boost/math/constants/constants.hpp>
#include <boost/test/unit_test.hpp>
#include <gsl/gsl_fft_real.h>
#include <iostream>
#include <fstream>
#include <complex>
namespace cap {
std::complex<double>
measure_impedance(std::shared_ptr<cap::EnergyStorageDevice> dev, std::shared_ptr<boost::property_tree::ptree const> database, std::ostream & os = std::cout);
void bar(std::shared_ptr<cap::EnergyStorageDevice> dev, std::shared_ptr<boost::property_tree::ptree const> database, std::ostream & os = std::cout)
{
double const frequency_lower_limit = database->get<double>("frequency_lower_limit");
double const frequency_upper_limit = database->get<double>("frequency_upper_limit");
double const ratio = database->get<double>("ratio" );
double const pi = boost::math::constants::pi<double>();
std::shared_ptr<boost::property_tree::ptree> tmp =
std::make_shared<boost::property_tree::ptree>(*database);
for (double frequency = frequency_lower_limit; frequency <= frequency_upper_limit; frequency *= ratio)
{
tmp->put("frequency", frequency);
std::complex<double> impedance =
measure_impedance(dev, tmp);
os<<boost::format( " %20.15e %20.15e %20.15e %20.15e %20.15e \n")
% frequency
% impedance.real()
% impedance.imag()
% std::abs(impedance)
% (std::arg(impedance) * 180.0 / pi)
;
}
}
std::complex<double>
measure_impedance(std::shared_ptr<cap::EnergyStorageDevice> dev, std::shared_ptr<boost::property_tree::ptree const> database, std::ostream & os)
{
double const frequency = database->get<double>("frequency" );
double const amplitude = database->get<double>("amplitude" );
int const cycles = database->get<int >("cycles" );
int const steps_per_cycle = database->get<int >("steps_per_cycle");
double const initial_voltage = 0.0;
std::vector<int> const powers_of_two =
{ 1, 2 ,4, 8, 16,
32, 64, 128, 256, 512,
1024, 2048, 4096, 8192, 16384,
32768, 65536, 131072, 262144, 524288
}; // first 20 powers of two
if (find(powers_of_two.begin(), powers_of_two.end(), (cycles-1)*steps_per_cycle) == powers_of_two.end())
throw std::runtime_error("(cycles-1)*steps_per_cycle must be a power of two");
double time = 0.0;
double const time_step = 1.0 / frequency / steps_per_cycle;
double const phase = std::asin(initial_voltage / amplitude);
double const pi = std::acos(-1.0);
dev->reset_voltage(initial_voltage);
double voltage;
double current;
std::vector<double> excitation;
std::vector<double> response;
for (int n = 0; n < cycles*steps_per_cycle; ++n)
{
time += time_step;
voltage = amplitude*std::sin(2.0*pi*frequency*time+phase);
dev->evolve_one_time_step_constant_voltage(time_step, voltage);
dev->get_current(current);
if (n >= steps_per_cycle)
{
excitation.push_back(voltage);
response .push_back(current);
}
// os<<boost::format(" %20.15e %20.15e %20.15e \n")
// % time
// % current
// % voltage
// ;
}
gsl_fft_real_radix2_transform(&(excitation[0]), 1, excitation.size());
gsl_fft_real_radix2_transform(&(response [0]), 1, response .size());
std::complex<double> const impedance =
std::complex<double>(excitation[(cycles-1)], excitation[excitation.size()-(cycles-1)])
/
std::complex<double>(response [(cycles-1)], response [response .size()-(cycles-1)]);
return impedance;
}
} // end namespace cap
BOOST_AUTO_TEST_CASE( test_measure_impedance )
{
// parse input file
std::shared_ptr<boost::property_tree::ptree> input_database =
std::make_shared<boost::property_tree::ptree>();
read_xml("input_impedance_spectroscopy", *input_database);
std::string const type = input_database->get<std::string>("device.type");
if ((type.compare("SeriesRC") != 0) && (type.compare("ParallelRC") != 0))
input_database->put("device.type", "ParallelRC");
std::string const duh = input_database->get<std::string>("device.type");
if (duh.compare("NoName") == 0)
throw std::runtime_error("duh");
// build an energy storage system
std::shared_ptr<boost::property_tree::ptree> device_database =
std::make_shared<boost::property_tree::ptree>(input_database->get_child("device"));
std::shared_ptr<cap::EnergyStorageDevice> device =
cap::buildEnergyStorageDevice(std::make_shared<cap::Parameters>(device_database));
double const frequency_lower_limit = input_database->get<double>("impedance_spectroscopy.frequency_lower_limit");
double const frequency_upper_limit = input_database->get<double>("impedance_spectroscopy.frequency_upper_limit");
double const ratio = input_database->get<double>("impedance_spectroscopy.ratio" );
double const series_resistance = input_database->get<double>("device.series_resistance" );
double const parallel_resistance = input_database->get<double>("device.parallel_resistance");
double const capacitance = input_database->get<double>("device.capacitance" );
double const pi = boost::math::constants::pi<double>();
double const percent_tolerance = 1.0e-1;
std::shared_ptr<boost::property_tree::ptree> impedance_spectroscopy_database =
std::make_shared<boost::property_tree::ptree>(input_database->get_child("impedance_spectroscopy"));
std::fstream fout("computed_vs_exact_impedance_spectroscopy_data", std::fstream::out);
for (double frequency = frequency_lower_limit; frequency < frequency_upper_limit; frequency *= ratio)
{
impedance_spectroscopy_database->put("frequency", frequency);
std::complex<double> computed_impedance = cap::measure_impedance(device, impedance_spectroscopy_database);
std::complex<double> exact_impedance =
((type.compare("SeriesRC") == 0) ?
series_resistance + 1.0 / std::complex<double>(0.0, capacitance * 2.0*pi*frequency) :
series_resistance + parallel_resistance / std::complex<double>(1.0, capacitance * parallel_resistance * 2.0*pi*frequency));
fout<<boost::format(" %22.15e %22.15e %22.15e %22.15e %22.15e %22.15e %22.15e %22.15e %22.15e \n")
% frequency
% computed_impedance.real()
% computed_impedance.imag()
% std::abs(computed_impedance)
% (std::arg(computed_impedance) * 180.0 / pi)
% exact_impedance.real()
% exact_impedance.imag()
% std::abs(exact_impedance)
% (std::arg(exact_impedance) * 180.0 / pi)
;
BOOST_CHECK_CLOSE(computed_impedance.real(), exact_impedance.real(), percent_tolerance);
BOOST_CHECK_CLOSE(computed_impedance.imag(), exact_impedance.imag(), percent_tolerance);
}
}
BOOST_AUTO_TEST_CASE( test_impedance_spectroscopy )
{
// parse input file
std::shared_ptr<boost::property_tree::ptree> input_database =
std::make_shared<boost::property_tree::ptree>();
read_xml("input_impedance_spectroscopy", *input_database);
// build an energy storage system
std::shared_ptr<boost::property_tree::ptree> device_database =
std::make_shared<boost::property_tree::ptree>(input_database->get_child("device"));
std::shared_ptr<cap::EnergyStorageDevice> device =
cap::buildEnergyStorageDevice(std::make_shared<cap::Parameters>(device_database));
// measure its impedance
std::fstream fout;
fout.open("impedance_spectroscopy_data", std::fstream::out);
std::shared_ptr<boost::property_tree::ptree> impedance_spectroscopy_database =
std::make_shared<boost::property_tree::ptree>(input_database->get_child("impedance_spectroscopy"));
cap::bar(device, impedance_spectroscopy_database, fout);
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <math.h>
// Functions inclusive:
#include <new-feature.h>
// End.
using namespace std;
int main() {
short int cResult = (8*2) + 7 + 1;
cout << cResult;
return 0;
}
<commit_msg>Last step: include feature<commit_after>#include <iostream>
#include <math.h>
// Functions inclusive:
#include <new-feature.h>
// End.
using namespace std;
int main() {
short int cResult = (8*2) + 7 + 1;
cout << cResult << " " << my-feature();
return 0;
}
<|endoftext|>
|
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* 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 .
*/
#include <sal/config.h>
#include <cassert>
#include <typeinfo>
#include <unordered_map>
#include <utility>
#include <vector>
#include <dlfcn.h>
#include <osl/mutex.hxx>
#include <rtl/instance.hxx>
#include <rtl/strbuf.hxx>
#include <rtl/ustring.hxx>
#include <typelib/typedescription.h>
#include <rtti.hxx>
#include <share.hxx>
namespace {
class RTTI
{
typedef std::unordered_map< OUString, std::type_info *, OUStringHash > t_rtti_map;
osl::Mutex m_mutex;
t_rtti_map m_rttis;
t_rtti_map m_generatedRttis;
void * m_hApp;
public:
RTTI();
~RTTI();
std::type_info * getRTTI(typelib_TypeDescription const &);
};
RTTI::RTTI()
#if defined(FREEBSD) && __FreeBSD_version < 702104
: m_hApp( dlopen( 0, RTLD_NOW | RTLD_GLOBAL ) )
#else
: m_hApp( dlopen( 0, RTLD_LAZY ) )
#endif
{
}
RTTI::~RTTI()
{
dlclose( m_hApp );
}
std::type_info * RTTI::getRTTI(typelib_TypeDescription const & pTypeDescr)
{
std::type_info * rtti;
OUString const & unoName = OUString::unacquired(&pTypeDescr.pTypeName);
osl::MutexGuard guard( m_mutex );
t_rtti_map::const_iterator iFind( m_rttis.find( unoName ) );
if (iFind == m_rttis.end())
{
// RTTI symbol
OStringBuffer buf( 64 );
buf.append( "_ZTIN" );
sal_Int32 index = 0;
do
{
OUString token( unoName.getToken( 0, '.', index ) );
buf.append( token.getLength() );
OString c_token( OUStringToOString( token, RTL_TEXTENCODING_ASCII_US ) );
buf.append( c_token );
}
while (index >= 0);
buf.append( 'E' );
OString symName( buf.makeStringAndClear() );
#if defined(FREEBSD) && __FreeBSD_version < 702104 /* #i22253# */
rtti = (std::type_info *)dlsym( RTLD_DEFAULT, symName.getStr() );
#else
rtti = (std::type_info *)dlsym( m_hApp, symName.getStr() );
#endif
if (rtti)
{
std::pair< t_rtti_map::iterator, bool > insertion (
m_rttis.insert( t_rtti_map::value_type( unoName, rtti ) ) );
SAL_WARN_IF( !insertion.second, "bridges", "key " << unoName << " already in rtti map" );
}
else
{
// try to lookup the symbol in the generated rtti map
t_rtti_map::const_iterator iFind2( m_generatedRttis.find( unoName ) );
if (iFind2 == m_generatedRttis.end())
{
// we must generate it !
// symbol and rtti-name is nearly identical,
// the symbol is prefixed with _ZTI
char const * rttiName = symName.getStr() +4;
#if OSL_DEBUG_LEVEL > 1
fprintf( stderr,"generated rtti for %s\n", rttiName );
#endif
switch (pTypeDescr.eTypeClass) {
case typelib_TypeClass_EXCEPTION:
{
typelib_CompoundTypeDescription const & ctd
= reinterpret_cast<
typelib_CompoundTypeDescription const &>(
pTypeDescr);
if (ctd.pBaseTypeDescription)
{
// ensure availability of base
std::type_info * base_rtti = getRTTI(
ctd.pBaseTypeDescription->aBase);
rtti = new __cxxabiv1::__si_class_type_info(
strdup( rttiName ), static_cast<__cxxabiv1::__class_type_info *>(base_rtti) );
}
else
{
// this class has no base class
rtti = new __cxxabiv1::__class_type_info( strdup( rttiName ) );
}
break;
}
case typelib_TypeClass_INTERFACE:
{
typelib_InterfaceTypeDescription const & itd
= reinterpret_cast<
typelib_InterfaceTypeDescription const &>(
pTypeDescr);
std::vector<std::type_info *> bases;
for (sal_Int32 i = 0; i != itd.nBaseTypes; ++i) {
bases.push_back(getRTTI(itd.ppBaseTypes[i]->aBase));
}
switch (itd.nBaseTypes) {
case 0:
rtti = new __cxxabiv1::__class_type_info(
strdup(rttiName));
break;
case 1:
rtti = new __cxxabiv1::__si_class_type_info(
strdup(rttiName),
static_cast<__cxxabiv1::__class_type_info *>(
bases[0]));
break;
case 2:
//TODO
break;
}
break;
}
default:
assert(false); // cannot happen
}
if (rtti != 0) {
std::pair< t_rtti_map::iterator, bool > insertion (
m_generatedRttis.insert( t_rtti_map::value_type( unoName, rtti ) ) );
SAL_WARN_IF( !insertion.second, "bridges", "key " << unoName << " already in generated rtti map" );
}
}
else // taking already generated rtti
{
rtti = iFind2->second;
}
}
}
else
{
rtti = iFind->second;
}
return rtti;
}
struct theRttiFactory: public rtl::Static<RTTI, theRttiFactory> {};
}
std::type_info * x86_64::getRtti(typelib_TypeDescription const & type) {
return theRttiFactory::get().getRTTI(type);
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Fix MI RTTI (as needed by -fsanitize=vptr)<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* 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 .
*/
#include <sal/config.h>
#include <cassert>
#include <typeinfo>
#include <unordered_map>
#include <utility>
#include <vector>
#include <dlfcn.h>
#include <osl/mutex.hxx>
#include <rtl/instance.hxx>
#include <rtl/strbuf.hxx>
#include <rtl/ustring.hxx>
#include <typelib/typedescription.h>
#include <rtti.hxx>
#include <share.hxx>
namespace {
class RTTI
{
typedef std::unordered_map< OUString, std::type_info *, OUStringHash > t_rtti_map;
osl::Mutex m_mutex;
t_rtti_map m_rttis;
t_rtti_map m_generatedRttis;
void * m_hApp;
public:
RTTI();
~RTTI();
std::type_info * getRTTI(typelib_TypeDescription const &);
};
RTTI::RTTI()
#if defined(FREEBSD) && __FreeBSD_version < 702104
: m_hApp( dlopen( 0, RTLD_NOW | RTLD_GLOBAL ) )
#else
: m_hApp( dlopen( 0, RTLD_LAZY ) )
#endif
{
}
RTTI::~RTTI()
{
dlclose( m_hApp );
}
std::type_info * RTTI::getRTTI(typelib_TypeDescription const & pTypeDescr)
{
std::type_info * rtti;
OUString const & unoName = OUString::unacquired(&pTypeDescr.pTypeName);
osl::MutexGuard guard( m_mutex );
t_rtti_map::const_iterator iFind( m_rttis.find( unoName ) );
if (iFind == m_rttis.end())
{
// RTTI symbol
OStringBuffer buf( 64 );
buf.append( "_ZTIN" );
sal_Int32 index = 0;
do
{
OUString token( unoName.getToken( 0, '.', index ) );
buf.append( token.getLength() );
OString c_token( OUStringToOString( token, RTL_TEXTENCODING_ASCII_US ) );
buf.append( c_token );
}
while (index >= 0);
buf.append( 'E' );
OString symName( buf.makeStringAndClear() );
#if defined(FREEBSD) && __FreeBSD_version < 702104 /* #i22253# */
rtti = (std::type_info *)dlsym( RTLD_DEFAULT, symName.getStr() );
#else
rtti = (std::type_info *)dlsym( m_hApp, symName.getStr() );
#endif
if (rtti)
{
std::pair< t_rtti_map::iterator, bool > insertion (
m_rttis.insert( t_rtti_map::value_type( unoName, rtti ) ) );
SAL_WARN_IF( !insertion.second, "bridges", "key " << unoName << " already in rtti map" );
}
else
{
// try to lookup the symbol in the generated rtti map
t_rtti_map::const_iterator iFind2( m_generatedRttis.find( unoName ) );
if (iFind2 == m_generatedRttis.end())
{
// we must generate it !
// symbol and rtti-name is nearly identical,
// the symbol is prefixed with _ZTI
char const * rttiName = symName.getStr() +4;
#if OSL_DEBUG_LEVEL > 1
fprintf( stderr,"generated rtti for %s\n", rttiName );
#endif
switch (pTypeDescr.eTypeClass) {
case typelib_TypeClass_EXCEPTION:
{
typelib_CompoundTypeDescription const & ctd
= reinterpret_cast<
typelib_CompoundTypeDescription const &>(
pTypeDescr);
if (ctd.pBaseTypeDescription)
{
// ensure availability of base
std::type_info * base_rtti = getRTTI(
ctd.pBaseTypeDescription->aBase);
rtti = new __cxxabiv1::__si_class_type_info(
strdup( rttiName ), static_cast<__cxxabiv1::__class_type_info *>(base_rtti) );
}
else
{
// this class has no base class
rtti = new __cxxabiv1::__class_type_info( strdup( rttiName ) );
}
break;
}
case typelib_TypeClass_INTERFACE:
{
typelib_InterfaceTypeDescription const & itd
= reinterpret_cast<
typelib_InterfaceTypeDescription const &>(
pTypeDescr);
std::vector<std::type_info *> bases;
for (sal_Int32 i = 0; i != itd.nBaseTypes; ++i) {
bases.push_back(getRTTI(itd.ppBaseTypes[i]->aBase));
}
switch (itd.nBaseTypes) {
case 0:
rtti = new __cxxabiv1::__class_type_info(
strdup(rttiName));
break;
case 1:
rtti = new __cxxabiv1::__si_class_type_info(
strdup(rttiName),
static_cast<__cxxabiv1::__class_type_info *>(
bases[0]));
break;
default:
{
char * pad = new char[
sizeof (__cxxabiv1::__vmi_class_type_info)
+ ((itd.nBaseTypes - 1)
* sizeof (
__cxxabiv1::__base_class_type_info))];
__cxxabiv1::__vmi_class_type_info * info
= new(pad)
__cxxabiv1::__vmi_class_type_info(
strdup(rttiName),
__cxxabiv1::__vmi_class_type_info::__flags_unknown_mask);
info->__base_count = itd.nBaseTypes;
for (sal_Int32 i = 0; i != itd.nBaseTypes; ++i)
{
info->__base_info[i].__base_type
= static_cast<
__cxxabiv1::__class_type_info *>(
bases[i]);
info->__base_info[i].__offset_flags
= (__cxxabiv1::__base_class_type_info::__public_mask
| ((8 * i) << __cxxabiv1::__base_class_type_info::__offset_shift));
}
rtti = info;
break;
}
}
break;
}
default:
assert(false); // cannot happen
}
if (rtti != 0) {
std::pair< t_rtti_map::iterator, bool > insertion (
m_generatedRttis.insert( t_rtti_map::value_type( unoName, rtti ) ) );
SAL_WARN_IF( !insertion.second, "bridges", "key " << unoName << " already in generated rtti map" );
}
}
else // taking already generated rtti
{
rtti = iFind2->second;
}
}
}
else
{
rtti = iFind->second;
}
return rtti;
}
struct theRttiFactory: public rtl::Static<RTTI, theRttiFactory> {};
}
std::type_info * x86_64::getRtti(typelib_TypeDescription const & type) {
return theRttiFactory::get().getRTTI(type);
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>
|
<commit_before>//
// Copyright (C) 2013 Mateusz Łoskot <[email protected]>
//
// This file is part of Qt Creator Boost.Build plugin project.
//
// This is free software; you can redistribute and/or modify it under
// the terms of the GNU Lesser General Public License, Version 2.1
// as published by the Free Software Foundation.
// See accompanying file LICENSE.txt or copy at
// http://www.gnu.org/licenses/lgpl-2.1-standalone.html.
//
#include "bboutputparser.hpp"
#include "bbutility.hpp"
#include "external/projectexplorer/gccparser.h"
#include "external/projectexplorer/ldparser.h"
#include "external/projectexplorer/clangparser.h"
// Qt Creator
#include <projectexplorer/ioutputparser.h>
#include <projectexplorer/projectexplorerconstants.h>
#include <projectexplorer/task.h>
#include <utils/qtcassert.h>
// Qt
#include <QRegExp>
#include <QString>
#include <QStringRef>
namespace BoostBuildProjectManager {
namespace Internal {
namespace {
char const* const RxToolsetFromCommand = "^([\\w-]+)(?:\\.)([\\w-]+).+$";
char const* const RxToolsetFromWarning = "^warning\\:.+toolset.+\\\"([\\w-]+)\\\".*$";
// TODO: replace filename with full path? ^\*\*passed\*\*\s(.+\.test)
char const* const RxTestPassed = "^\\*\\*passed\\*\\*\\s+(.+\\.test)\\s*$";
char const* const RxTestFailed = "^\\.\\.\\.failed\\s+testing\\.capture-output\\s+(.+\\.run)\\.\\.\\.$";
char const* const RxTestFailedAsExpected = "^\\(failed-as-expected\\)\\s+(.+\\.o)\\s*$";
char const* const RxTestFileLineN = "(\\.[ch][px]*)\\(([0-9]+)\\)"; // replace \\1:\\2
char const* const RxTestFileObj = "\\W(\\w+)(\\.o)";
}
BoostBuildParser::BoostBuildParser()
: rxToolsetNameCommand_(QLatin1String(RxToolsetFromCommand))
, rxToolsetNameWarning_(QLatin1String(RxToolsetFromWarning))
, rxTestPassed_(QLatin1String(RxTestPassed))
, rxTestFailed_(QLatin1String(RxTestFailed))
, rxTestFailedAsExpected_(QLatin1String(RxTestFailedAsExpected))
, rxTestFileLineN_(QLatin1String(RxTestFileLineN))
, rxTestFileObj_(QLatin1String(RxTestFileObj))
, lineMode_(Common)
{
rxToolsetNameCommand_.setMinimal(true);
QTC_CHECK(rxToolsetNameCommand_.isValid());
rxToolsetNameWarning_.setMinimal(true);
QTC_CHECK(rxToolsetNameWarning_.isValid());
rxTestPassed_.setMinimal(true);
QTC_CHECK(rxTestPassed_.isValid());
rxTestFailed_.setMinimal(true);
QTC_CHECK(rxTestFailed_.isValid());
rxTestFailedAsExpected_.setMinimal(true);
QTC_CHECK(rxTestFailedAsExpected_.isValid());
rxTestFileLineN_.setMinimal(true);
QTC_CHECK(rxTestFileLineN_.isValid());
}
QString BoostBuildParser::findToolset(QString const& line) const
{
QString name;
if (rxToolsetNameWarning_.indexIn(line) > -1)
name = rxToolsetNameWarning_.cap(1);
else if (rxToolsetNameCommand_.indexIn(line) > -1)
name = rxToolsetNameCommand_.cap(1);
return name;
}
void BoostBuildParser::setToolsetParser(QString const& toolsetName)
{
if (!toolsetName.isEmpty() && toolsetName_.isEmpty())
{
if (QStringRef(&toolsetName, 0, 3) == QLatin1String("gcc"))
{
appendOutputParser(new ProjectExplorer::GccParser());
toolsetName_ = toolsetName;
}
else if (QStringRef(&toolsetName, 0, 5) == QLatin1String("clang"))
{
// clang-xxx found (e.g. clang-linux)
appendOutputParser(new ProjectExplorer::ClangParser());
toolsetName_ = toolsetName;
}
else
{
// TODO: Add more toolsets (Intel, VC++, etc.)
}
}
}
void BoostBuildParser::stdOutput(QString const& rawLine)
{
setToolsetParser(findToolset(rawLine));
QString const line
= rightTrimmed(rawLine).replace(rxTestFileLineN_, QLatin1String("\\1:\\2"));
if (!toolsetName_.isEmpty() && line.startsWith(toolsetName_))
lineMode_ = Toolset;
else if (line.startsWith(QLatin1String("testing"))
|| line.startsWith(QLatin1String("(failed-as-expected)")))
lineMode_ = Testing;
else if (line.startsWith(QLatin1String("common")))
lineMode_ = Common;
// TODO: Handle (failed-as-expected) - cancel error Task
if (lineMode_ == Toolset)
{
// Boost.Build seems to send everything to stdout,
// whereas gcc and clang to use stderr.
ProjectExplorer::IOutputParser::stdError(line);
}
else if (lineMode_ == Testing)
{
if (rxTestPassed_.indexIn(line) > -1)
{
BBPM_QDEBUG(rxTestPassed_.capturedTexts());
// TODO: issue #3
ProjectExplorer::Task task(ProjectExplorer::Task::Unknown
, rxTestPassed_.cap(0)
, Utils::FileName::fromString(rxTestPassed_.cap(1))
, -1 // line
, ProjectExplorer::Constants::TASK_CATEGORY_COMPILE);
setTask(task);
lineMode_ = Common;
}
else if (rxTestFailed_.indexIn(line) > -1)
{
BBPM_QDEBUG(rxTestFailed_.capturedTexts());
// Report summary task for "...failed testing.capture-output /myfile.run"
ProjectExplorer::Task task(ProjectExplorer::Task::Error
, rxTestFailed_.cap(0)
, Utils::FileName::fromString(rxTestFailed_.cap(1))
, -1 // line
, ProjectExplorer::Constants::TASK_CATEGORY_COMPILE);
setTask(task);
lineMode_ = Common;
}
else if (rxTestFailedAsExpected_.indexIn(line) > -1)
{
BBPM_QDEBUG(rxTestFailedAsExpected_.capturedTexts());
// TODO: messages are reversed: first compile command, then testing status
// So, first compilation tasks are added, then we receive testing status
QString fileName(rxTestFailedAsExpected_.cap(1));
if (rxTestFileObj_.indexIn(fileName))
fileName = rxTestFileObj_.cap(1) + QLatin1String(".cpp");// FIXME:hardcoded ext
// ATM, we can only indicate in UI that test failed-as-expected
ProjectExplorer::Task task(ProjectExplorer::Task::Error
, rxTestFailedAsExpected_.cap(0)
, Utils::FileName::fromString(fileName)
, -1 // line
, ProjectExplorer::Constants::TASK_CATEGORY_COMPILE);
setTask(task);
lineMode_ = Common;
}
else
{
// Parses compilation errors of run-time tests, creates issue tasks
ProjectExplorer::IOutputParser::stdError(line);
}
}
else
{
doFlush();
ProjectExplorer::IOutputParser::stdOutput(line);
}
}
void BoostBuildParser::stdError(QString const& line)
{
setToolsetParser(findToolset(line));
ProjectExplorer::IOutputParser::stdError(line);
}
void BoostBuildParser::doFlush()
{
if (!lastTask_.isNull())
{
ProjectExplorer::Task t = lastTask_;
lastTask_.clear();
emit addTask(t);
}
}
void BoostBuildParser::setTask(ProjectExplorer::Task const& task)
{
doFlush();
lastTask_ = task;
}
} // namespace Internal
} // namespace BoostBuildProjectManager
<commit_msg>Clarify TODO item for issues with parsing "(failed-as-expected)" status<commit_after>//
// Copyright (C) 2013 Mateusz Łoskot <[email protected]>
//
// This file is part of Qt Creator Boost.Build plugin project.
//
// This is free software; you can redistribute and/or modify it under
// the terms of the GNU Lesser General Public License, Version 2.1
// as published by the Free Software Foundation.
// See accompanying file LICENSE.txt or copy at
// http://www.gnu.org/licenses/lgpl-2.1-standalone.html.
//
#include "bboutputparser.hpp"
#include "bbutility.hpp"
#include "external/projectexplorer/gccparser.h"
#include "external/projectexplorer/ldparser.h"
#include "external/projectexplorer/clangparser.h"
// Qt Creator
#include <projectexplorer/ioutputparser.h>
#include <projectexplorer/projectexplorerconstants.h>
#include <projectexplorer/task.h>
#include <utils/qtcassert.h>
// Qt
#include <QRegExp>
#include <QString>
#include <QStringRef>
namespace BoostBuildProjectManager {
namespace Internal {
namespace {
char const* const RxToolsetFromCommand = "^([\\w-]+)(?:\\.)([\\w-]+).+$";
char const* const RxToolsetFromWarning = "^warning\\:.+toolset.+\\\"([\\w-]+)\\\".*$";
// TODO: replace filename with full path? ^\*\*passed\*\*\s(.+\.test)
char const* const RxTestPassed = "^\\*\\*passed\\*\\*\\s+(.+\\.test)\\s*$";
char const* const RxTestFailed = "^\\.\\.\\.failed\\s+testing\\.capture-output\\s+(.+\\.run)\\.\\.\\.$";
char const* const RxTestFailedAsExpected = "^\\(failed-as-expected\\)\\s+(.+\\.o)\\s*$";
char const* const RxTestFileLineN = "(\\.[ch][px]*)\\(([0-9]+)\\)"; // replace \\1:\\2
char const* const RxTestFileObj = "\\W(\\w+)(\\.o)";
}
BoostBuildParser::BoostBuildParser()
: rxToolsetNameCommand_(QLatin1String(RxToolsetFromCommand))
, rxToolsetNameWarning_(QLatin1String(RxToolsetFromWarning))
, rxTestPassed_(QLatin1String(RxTestPassed))
, rxTestFailed_(QLatin1String(RxTestFailed))
, rxTestFailedAsExpected_(QLatin1String(RxTestFailedAsExpected))
, rxTestFileLineN_(QLatin1String(RxTestFileLineN))
, rxTestFileObj_(QLatin1String(RxTestFileObj))
, lineMode_(Common)
{
rxToolsetNameCommand_.setMinimal(true);
QTC_CHECK(rxToolsetNameCommand_.isValid());
rxToolsetNameWarning_.setMinimal(true);
QTC_CHECK(rxToolsetNameWarning_.isValid());
rxTestPassed_.setMinimal(true);
QTC_CHECK(rxTestPassed_.isValid());
rxTestFailed_.setMinimal(true);
QTC_CHECK(rxTestFailed_.isValid());
rxTestFailedAsExpected_.setMinimal(true);
QTC_CHECK(rxTestFailedAsExpected_.isValid());
rxTestFileLineN_.setMinimal(true);
QTC_CHECK(rxTestFileLineN_.isValid());
}
QString BoostBuildParser::findToolset(QString const& line) const
{
QString name;
if (rxToolsetNameWarning_.indexIn(line) > -1)
name = rxToolsetNameWarning_.cap(1);
else if (rxToolsetNameCommand_.indexIn(line) > -1)
name = rxToolsetNameCommand_.cap(1);
return name;
}
void BoostBuildParser::setToolsetParser(QString const& toolsetName)
{
if (!toolsetName.isEmpty() && toolsetName_.isEmpty())
{
if (QStringRef(&toolsetName, 0, 3) == QLatin1String("gcc"))
{
appendOutputParser(new ProjectExplorer::GccParser());
toolsetName_ = toolsetName;
}
else if (QStringRef(&toolsetName, 0, 5) == QLatin1String("clang"))
{
// clang-xxx found (e.g. clang-linux)
appendOutputParser(new ProjectExplorer::ClangParser());
toolsetName_ = toolsetName;
}
else
{
// TODO: Add more toolsets (Intel, VC++, etc.)
}
}
}
void BoostBuildParser::stdOutput(QString const& rawLine)
{
setToolsetParser(findToolset(rawLine));
QString const line
= rightTrimmed(rawLine).replace(rxTestFileLineN_, QLatin1String("\\1:\\2"));
if (!toolsetName_.isEmpty() && line.startsWith(toolsetName_))
lineMode_ = Toolset;
else if (line.startsWith(QLatin1String("testing"))
|| line.startsWith(QLatin1String("(failed-as-expected)")))
lineMode_ = Testing;
else if (line.startsWith(QLatin1String("common")))
lineMode_ = Common;
if (lineMode_ == Toolset)
{
// Boost.Build seems to send everything to stdout,
// whereas gcc and clang to use stderr.
ProjectExplorer::IOutputParser::stdError(line);
}
else if (lineMode_ == Testing)
{
if (rxTestPassed_.indexIn(line) > -1)
{
BBPM_QDEBUG(rxTestPassed_.capturedTexts());
// TODO: issue #3
ProjectExplorer::Task task(ProjectExplorer::Task::Unknown
, rxTestPassed_.cap(0)
, Utils::FileName::fromString(rxTestPassed_.cap(1))
, -1 // line
, ProjectExplorer::Constants::TASK_CATEGORY_COMPILE);
setTask(task);
lineMode_ = Common;
}
else if (rxTestFailed_.indexIn(line) > -1)
{
BBPM_QDEBUG(rxTestFailed_.capturedTexts());
// Report summary task for "...failed testing.capture-output /myfile.run"
ProjectExplorer::Task task(ProjectExplorer::Task::Error
, rxTestFailed_.cap(0)
, Utils::FileName::fromString(rxTestFailed_.cap(1))
, -1 // line
, ProjectExplorer::Constants::TASK_CATEGORY_COMPILE);
setTask(task);
lineMode_ = Common;
}
else if (rxTestFailedAsExpected_.indexIn(line) > -1)
{
BBPM_QDEBUG(rxTestFailedAsExpected_.capturedTexts());
// TODO: Handling of "(failed-as-expected)" is not great, might be confusing.
// Boost.Build spits out compile command first, so compilation errors arrive
// and are parsed immediately (issue tasks are created)
// due to lineMode_==Toolset.
// Then, "(failed-as-expected)" status arrives and there seem to be no way to
// look back and clear all the issue tasks created for compilation errors.
// TODO: Ask Volodya if b2 could announce "testing." before compile command
// for a compile-time test.
QString fileName(rxTestFailedAsExpected_.cap(1));
if (rxTestFileObj_.indexIn(fileName))
fileName = rxTestFileObj_.cap(1) + QLatin1String(".cpp");// FIXME:hardcoded ext
// ATM, we can only indicate in UI that test failed-as-expected
ProjectExplorer::Task task(ProjectExplorer::Task::Error
, rxTestFailedAsExpected_.cap(0)
, Utils::FileName::fromString(fileName)
, -1 // line
, ProjectExplorer::Constants::TASK_CATEGORY_COMPILE);
setTask(task);
lineMode_ = Common;
}
else
{
// Parses compilation errors of run-time tests, creates issue tasks
ProjectExplorer::IOutputParser::stdError(line);
}
}
else
{
doFlush();
ProjectExplorer::IOutputParser::stdOutput(line);
}
}
void BoostBuildParser::stdError(QString const& line)
{
setToolsetParser(findToolset(line));
ProjectExplorer::IOutputParser::stdError(line);
}
void BoostBuildParser::doFlush()
{
if (!lastTask_.isNull())
{
ProjectExplorer::Task t = lastTask_;
lastTask_.clear();
emit addTask(t);
}
}
void BoostBuildParser::setTask(ProjectExplorer::Task const& task)
{
doFlush();
lastTask_ = task;
}
} // namespace Internal
} // namespace BoostBuildProjectManager
<|endoftext|>
|
<commit_before>//
// Copyright 2020 Google LLC
//
// 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 "backend/query/analyzer_options.h"
#include "zetasql/public/analyzer.h"
#include "zetasql/public/options.pb.h"
#include "absl/time/time.h"
#include "common/constants.h"
#include "common/feature_flags.h"
namespace google {
namespace spanner {
namespace emulator {
namespace backend {
zetasql::AnalyzerOptions MakeGoogleSqlAnalyzerOptions() {
zetasql::AnalyzerOptions options;
absl::TimeZone time_zone;
absl::LoadTimeZone(kDefaultTimeZone, &time_zone);
options.set_default_time_zone(time_zone);
options.set_error_message_mode(
zetasql::AnalyzerOptions::ERROR_MESSAGE_MULTI_LINE_WITH_CARET);
options.set_language_options(MakeGoogleSqlLanguageOptions());
options.set_allow_undeclared_parameters(true);
// Spanner does not support positional parameters, so tell ZetaSQL to always
// use named parameter bindings.
options.set_parameter_mode(zetasql::PARAMETER_NAMED);
return options;
}
zetasql::LanguageOptions MakeGoogleSqlLanguageOptions() {
zetasql::LanguageOptions options;
options.set_name_resolution_mode(zetasql::NAME_RESOLUTION_DEFAULT);
options.set_product_mode(zetasql::PRODUCT_EXTERNAL);
options.SetEnabledLanguageFeatures({
zetasql::FEATURE_TIMESTAMP_NANOS,
// TODO: Reenable zetasql::FEATURE_TABLESAMPLE once AST
// filtering lands.
zetasql::FEATURE_V_1_1_HAVING_IN_AGGREGATE,
zetasql::FEATURE_V_1_1_NULL_HANDLING_MODIFIER_IN_AGGREGATE,
zetasql::FEATURE_V_1_2_SAFE_FUNCTION_CALL,
zetasql::FEATURE_V_1_1_ORDER_BY_COLLATE,
});
options.SetSupportedStatementKinds({
zetasql::RESOLVED_QUERY_STMT,
zetasql::RESOLVED_INSERT_STMT,
zetasql::RESOLVED_UPDATE_STMT,
zetasql::RESOLVED_DELETE_STMT,
});
if (EmulatorFeatureFlags::instance().flags().enable_numeric_type) {
options.EnableLanguageFeature(zetasql::FEATURE_NUMERIC_TYPE);
}
return options;
}
static void DisableOption(zetasql::LanguageFeature feature,
zetasql::LanguageOptions* options) {
std::set<zetasql::LanguageFeature> features(
options->GetEnabledLanguageFeatures());
features.erase(feature);
options->SetEnabledLanguageFeatures(features);
}
zetasql::LanguageOptions MakeGoogleSqlLanguageOptionsForCompliance() {
auto options = MakeGoogleSqlLanguageOptions();
DisableOption(zetasql::FEATURE_ANALYTIC_FUNCTIONS, &options);
DisableOption(zetasql::FEATURE_TABLESAMPLE, &options);
return options;
}
} // namespace backend
} // namespace emulator
} // namespace spanner
} // namespace google
<commit_msg>Internal change<commit_after>//
// Copyright 2020 Google LLC
//
// 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 "backend/query/analyzer_options.h"
#include "zetasql/public/analyzer.h"
#include "zetasql/public/options.pb.h"
#include "absl/time/time.h"
#include "common/constants.h"
#include "common/feature_flags.h"
namespace google {
namespace spanner {
namespace emulator {
namespace backend {
zetasql::AnalyzerOptions MakeGoogleSqlAnalyzerOptions() {
zetasql::AnalyzerOptions options;
absl::TimeZone time_zone;
absl::LoadTimeZone(kDefaultTimeZone, &time_zone);
options.set_default_time_zone(time_zone);
options.set_error_message_mode(
zetasql::AnalyzerOptions::ERROR_MESSAGE_MULTI_LINE_WITH_CARET);
options.set_language(MakeGoogleSqlLanguageOptions());
options.set_allow_undeclared_parameters(true);
// Spanner does not support positional parameters, so tell ZetaSQL to always
// use named parameter bindings.
options.set_parameter_mode(zetasql::PARAMETER_NAMED);
return options;
}
zetasql::LanguageOptions MakeGoogleSqlLanguageOptions() {
zetasql::LanguageOptions options;
options.set_name_resolution_mode(zetasql::NAME_RESOLUTION_DEFAULT);
options.set_product_mode(zetasql::PRODUCT_EXTERNAL);
options.SetEnabledLanguageFeatures({
zetasql::FEATURE_TIMESTAMP_NANOS,
// TODO: Reenable zetasql::FEATURE_TABLESAMPLE once AST
// filtering lands.
zetasql::FEATURE_V_1_1_HAVING_IN_AGGREGATE,
zetasql::FEATURE_V_1_1_NULL_HANDLING_MODIFIER_IN_AGGREGATE,
zetasql::FEATURE_V_1_2_SAFE_FUNCTION_CALL,
zetasql::FEATURE_V_1_1_ORDER_BY_COLLATE,
});
options.SetSupportedStatementKinds({
zetasql::RESOLVED_QUERY_STMT,
zetasql::RESOLVED_INSERT_STMT,
zetasql::RESOLVED_UPDATE_STMT,
zetasql::RESOLVED_DELETE_STMT,
});
if (EmulatorFeatureFlags::instance().flags().enable_numeric_type) {
options.EnableLanguageFeature(zetasql::FEATURE_NUMERIC_TYPE);
}
return options;
}
static void DisableOption(zetasql::LanguageFeature feature,
zetasql::LanguageOptions* options) {
std::set<zetasql::LanguageFeature> features(
options->GetEnabledLanguageFeatures());
features.erase(feature);
options->SetEnabledLanguageFeatures(features);
}
zetasql::LanguageOptions MakeGoogleSqlLanguageOptionsForCompliance() {
auto options = MakeGoogleSqlLanguageOptions();
DisableOption(zetasql::FEATURE_ANALYTIC_FUNCTIONS, &options);
DisableOption(zetasql::FEATURE_TABLESAMPLE, &options);
return options;
}
} // namespace backend
} // namespace emulator
} // namespace spanner
} // namespace google
<|endoftext|>
|
<commit_before><commit_msg>Check that chunk length is a multiple of 8<commit_after><|endoftext|>
|
<commit_before><commit_msg>Minor formatting changes and added config option for CFG tool.<commit_after><|endoftext|>
|
<commit_before>/***********************************************************************
filename: Sample_ScrollablePane.cpp
created: Wed Aug 2 2006
author: Tomas Lindquist Olsen
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team
*
* 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 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 "CEGUI/System.h"
#include "CEGUI/SchemeManager.h"
#include "CEGUI/WindowManager.h"
#include "CEGUI/FontManager.h"
#include "CEGUI/ImageManager.h"
#include "CEGUI/Font.h"
#include "CEGUI/Window.h"
#include "CEGUI/CoordConverter.h"
#include "CEGUI/GUIContext.h"
#include "CEGUI/widgets/ScrollablePane.h"
#include "CEGUI/widgets/ScrolledContainer.h"
#include "SampleBase.h"
/*
This is a demonstration of the ScrollablePane widget
*/
// ScrollablePane demo sample class
class ScrollablePaneSample : public Sample
{
public:
// method to initialse the samples windows and events.
virtual bool initialise(CEGUI::GUIContext* guiContext);
// method to perform any required cleanup operations.
virtual void deinitialise();
private:
// creates the menubar with content
void createMenu(CEGUI::Window* bar);
// quit menu item handler
bool fileQuit(const CEGUI::EventArgs&)
{
//d_sampleApp->setQuitting(true);
return true;
}
// new dialog menu item handler
bool demoNewDialog(const CEGUI::EventArgs& e);
// handler for all the global hotkeys
bool hotkeysHandler(const CEGUI::EventArgs& e);
// member data
CEGUI::WindowManager* d_wm; // we will use the window manager alot
CEGUI::System* d_system; // the gui system
CEGUI::Window* d_root; // the gui sheet
CEGUI::Font* d_font; // the font we use
CEGUI::ScrollablePane* d_pane; // the scrollable pane. center piece of the demo
CEGUI::GUIContext* d_guiContext;
};
/*************************************************************************
Sample specific initialisation goes here.
*************************************************************************/
bool ScrollablePaneSample::initialise(CEGUI::GUIContext* guiContext)
{
using namespace CEGUI;
d_guiContext = guiContext;
d_usedFiles = CEGUI::String(__FILE__);
// this sample will use WindowsLook
SchemeManager::getSingleton().createFromFile("WindowsLook.scheme");
// load the default font
d_font = &FontManager::getSingleton().createFromFile("DejaVuSans-12-NoScale.font");
d_guiContext->setDefaultFont(d_font);
// set the pointer indicator
d_system = System::getSingletonPtr();
d_guiContext->getPointerIndicator().setDefaultImage("WindowsLook/MouseArrow");
// set the default tooltip type
d_guiContext->setDefaultTooltipType("WindowsLook/Tooltip");
// We need the window manager to set up the test interface :)
d_wm = WindowManager::getSingletonPtr();
// create a root window
// this will be a static, to give a nice app'ish background
d_root = d_wm->createWindow("WindowsLook/Static");
d_root->setProperty("FrameEnabled", "false");
d_root->setSize(CEGUI::USize(cegui_reldim(1.0f), cegui_reldim(1.0f)));
d_root->setProperty("BackgroundColours", "tl:FFBFBFBF tr:FFBFBFBF bl:FFBFBFBF br:FFBFBFBF");
// root window will take care of hotkeys
//TODO: fix this
//d_root->subscribeEvent(Window::EventKeyDown, Event::Subscriber(&ScrollablePaneSample::hotkeysHandler, this));
d_guiContext->setRootWindow(d_root);
// create a menubar.
// this will fit in the top of the screen and have options for the demo
UDim bar_bottom(0,d_font->getLineSpacing(1.5f));
Window* bar = d_wm->createWindow("WindowsLook/Menubar");
bar->setArea(UDim(0,0),UDim(0,0),UDim(1,0),bar_bottom);
d_root->addChild(bar);
// fill out the menubar
createMenu(bar);
// create a scrollable pane for our demo content
d_pane = static_cast<ScrollablePane*>(d_wm->createWindow("WindowsLook/ScrollablePane"));
d_pane->setArea(URect(UDim(0,0),bar_bottom,UDim(1,0),UDim(1,0)));
// this scrollable pane will be a kind of virtual desktop in the sense that it's bigger than
// the screen. 3000 x 3000 pixels
d_pane->setContentPaneAutoSized(false);
d_pane->setContentPaneArea(CEGUI::Rectf(0, 0, 5000, 5000));
d_root->addChild(d_pane);
// add a dialog to this pane so we have something to drag around :)
Window* dlg = d_wm->createWindow("WindowsLook/FrameWindow");
dlg->setMinSize(USize(UDim(0,250),UDim(0,100)));
dlg->setSize(USize(UDim(0,250),UDim(0,100)));
dlg->setText("Drag me around");
d_pane->addChild(dlg);
return true;
}
/*************************************************************************
Creates the menu bar and fills it up :)
*************************************************************************/
void ScrollablePaneSample::createMenu(CEGUI::Window* bar)
{
using namespace CEGUI;
// file menu item
Window* file = d_wm->createWindow("WindowsLook/MenuItem");
file->setText("File");
bar->addChild(file);
// file popup
Window* popup = d_wm->createWindow("WindowsLook/PopupMenu");
file->addChild(popup);
// quit item in file menu
Window* item = d_wm->createWindow("WindowsLook/MenuItem");
item->setText("Quit");
item->subscribeEvent("Clicked", Event::Subscriber(&ScrollablePaneSample::fileQuit, this));
popup->addChild(item);
// demo menu item
Window* demo = d_wm->createWindow("WindowsLook/MenuItem");
demo->setText("Demo");
bar->addChild(demo);
// demo popup
popup = d_wm->createWindow("WindowsLook/PopupMenu");
demo->addChild(popup);
// demo -> new window
item = d_wm->createWindow("WindowsLook/MenuItem");
item->setText("New dialog");
item->setTooltipText("Hotkey: Space");
item->subscribeEvent("Clicked", Event::Subscriber(&ScrollablePaneSample::demoNewDialog, this));
popup->addChild(item);
}
/*************************************************************************
Cleans up resources allocated in the initialiseSample call.
*************************************************************************/
void ScrollablePaneSample::deinitialise()
{
// everything we did is cleaned up by CEGUI
}
/*************************************************************************
Handler for the 'Demo -> New dialog' menu item
*************************************************************************/
bool ScrollablePaneSample::demoNewDialog(const CEGUI::EventArgs&)
{
using namespace CEGUI;
// add a dialog to this pane so we have some more stuff to drag around :)
Window* dlg = d_wm->createWindow("WindowsLook/FrameWindow");
dlg->setMinSize(USize(UDim(0,200),UDim(0,100)));
dlg->setSize(USize(UDim(0,200),UDim(0,100)));
dlg->setText("Drag me around too!");
// we put this in the center of the viewport into the scrollable pane
UVector2 uni_center(UDim(0.5f,0), UDim(0.5f,0));
// URGENT FIXME!
//Vector2f center = CoordConverter::windowToScreen(*d_root, uni_center);
//Vector2f target = CoordConverter::screenToWindow(*d_pane->getContentPane(), center);
//dlg->setPosition(UVector2(UDim(0,target.d_x-100), UDim(0,target.d_y-50)));
d_pane->addChild(dlg);
return true;
}
/*************************************************************************
Handler for global hotkeys
*************************************************************************/
bool ScrollablePaneSample::hotkeysHandler(const CEGUI::EventArgs& e)
{
using namespace CEGUI;
const KeyEventArgs& k = static_cast<const KeyEventArgs&>(e);
switch (k.scancode)
{
// space is a hotkey for demo -> new dialog
case Key::Space:
// this handler does not use the event args at all so this is fine :)
// though maybe a bit hackish...
demoNewDialog(e);
break;
// no hotkey found? event not used...
default:
return false;
}
return true;
}
/*************************************************************************
Define the module function that returns an instance of the sample
*************************************************************************/
extern "C" SAMPLE_EXPORT Sample& getSampleInstance()
{
static ScrollablePaneSample sample;
return sample;
}<commit_msg>Implement a custom 'InputAggregator' in the 'ScrollablePane' sample and remove direct references to a keyboard.<commit_after>/***********************************************************************
filename: Sample_ScrollablePane.cpp
created: Wed Aug 2 2006
author: Tomas Lindquist Olsen
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team
*
* 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 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 "CEGUI/System.h"
#include "CEGUI/SchemeManager.h"
#include "CEGUI/WindowManager.h"
#include "CEGUI/FontManager.h"
#include "CEGUI/ImageManager.h"
#include "CEGUI/InputAggregator.h"
#include "CEGUI/InputEventReceiver.h"
#include "CEGUI/Font.h"
#include "CEGUI/Window.h"
#include "CEGUI/CoordConverter.h"
#include "CEGUI/GUIContext.h"
#include "CEGUI/widgets/ScrollablePane.h"
#include "CEGUI/widgets/ScrolledContainer.h"
#include "SampleBase.h"
/*
This is a demonstration of the ScrollablePane widget
*/
// ScrollablePane demo sample class
class ScrollablePaneSample : public Sample
{
public:
// method to initialse the samples windows and events.
virtual bool initialise(CEGUI::GUIContext* guiContext);
// method to perform any required cleanup operations.
virtual void deinitialise();
private:
// creates the menubar with content
void createMenu(CEGUI::Window* bar);
// quit menu item handler
bool fileQuit(const CEGUI::EventArgs&)
{
//d_sampleApp->setQuitting(true);
return true;
}
// new dialog menu item handler
bool demoNewDialog(const CEGUI::EventArgs& e);
bool semanticEventHandler(const CEGUI::EventArgs& e);
// member data
CEGUI::WindowManager* d_wm; // we will use the window manager alot
CEGUI::System* d_system; // the gui system
CEGUI::Window* d_root; // the gui sheet
CEGUI::Font* d_font; // the font we use
CEGUI::ScrollablePane* d_pane; // the scrollable pane. center piece of the demo
CEGUI::GUIContext* d_guiContext;
};
/*************************************************************************
Custom implementation of InputAggregator
*************************************************************************/
enum SampleSemanticValue
{
// we start from the user-defined value
SpawnNewDialog = CEGUI::SemanticValue::SV_UserDefinedSemanticValue
};
class SampleInputAggregator : public CEGUI::InputAggregator
{
public:
SampleInputAggregator(CEGUI::InputEventReceiver* input_receiver) :
CEGUI::InputAggregator(input_receiver)
{
}
void initialise()
{
d_keyValuesMappings[CEGUI::Key::Space] = SpawnNewDialog;
}
};
/*************************************************************************
Sample specific initialisation goes here.
*************************************************************************/
bool ScrollablePaneSample::initialise(CEGUI::GUIContext* guiContext)
{
using namespace CEGUI;
d_guiContext = guiContext;
d_usedFiles = CEGUI::String(__FILE__);
d_inputAggregator = new SampleInputAggregator(d_guiContext);
// this sample will use WindowsLook
SchemeManager::getSingleton().createFromFile("WindowsLook.scheme");
// load the default font
d_font = &FontManager::getSingleton().createFromFile("DejaVuSans-12-NoScale.font");
d_guiContext->setDefaultFont(d_font);
// set the pointer indicator
d_system = System::getSingletonPtr();
d_guiContext->getPointerIndicator().setDefaultImage("WindowsLook/MouseArrow");
// set the default tooltip type
d_guiContext->setDefaultTooltipType("WindowsLook/Tooltip");
// We need the window manager to set up the test interface :)
d_wm = WindowManager::getSingletonPtr();
// create a root window
// this will be a static, to give a nice app'ish background
d_root = d_wm->createWindow("WindowsLook/Static");
d_root->setProperty("FrameEnabled", "false");
d_root->setSize(CEGUI::USize(cegui_reldim(1.0f), cegui_reldim(1.0f)));
d_root->setProperty("BackgroundColours", "tl:FFBFBFBF tr:FFBFBFBF bl:FFBFBFBF br:FFBFBFBF");
d_root->subscribeEvent(Window::EventSemanticEvent,
Event::Subscriber(&ScrollablePaneSample::semanticEventHandler, this));
d_guiContext->setRootWindow(d_root);
// create a menubar.
// this will fit in the top of the screen and have options for the demo
UDim bar_bottom(0,d_font->getLineSpacing(1.5f));
Window* bar = d_wm->createWindow("WindowsLook/Menubar");
bar->setArea(UDim(0,0),UDim(0,0),UDim(1,0),bar_bottom);
d_root->addChild(bar);
// fill out the menubar
createMenu(bar);
// create a scrollable pane for our demo content
d_pane = static_cast<ScrollablePane*>(d_wm->createWindow("WindowsLook/ScrollablePane"));
d_pane->setArea(URect(UDim(0,0),bar_bottom,UDim(1,0),UDim(1,0)));
// this scrollable pane will be a kind of virtual desktop in the sense that it's bigger than
// the screen. 3000 x 3000 pixels
d_pane->setContentPaneAutoSized(false);
d_pane->setContentPaneArea(CEGUI::Rectf(0, 0, 5000, 5000));
d_root->addChild(d_pane);
// add a dialog to this pane so we have something to drag around :)
Window* dlg = d_wm->createWindow("WindowsLook/FrameWindow");
dlg->setMinSize(USize(UDim(0,250),UDim(0,100)));
dlg->setSize(USize(UDim(0,250),UDim(0,100)));
dlg->setText("Drag me around");
d_pane->addChild(dlg);
return true;
}
/*************************************************************************
Creates the menu bar and fills it up :)
*************************************************************************/
void ScrollablePaneSample::createMenu(CEGUI::Window* bar)
{
using namespace CEGUI;
// file menu item
Window* file = d_wm->createWindow("WindowsLook/MenuItem");
file->setText("File");
bar->addChild(file);
// file popup
Window* popup = d_wm->createWindow("WindowsLook/PopupMenu");
file->addChild(popup);
// quit item in file menu
Window* item = d_wm->createWindow("WindowsLook/MenuItem");
item->setText("Quit");
item->subscribeEvent("Clicked", Event::Subscriber(&ScrollablePaneSample::fileQuit, this));
popup->addChild(item);
// demo menu item
Window* demo = d_wm->createWindow("WindowsLook/MenuItem");
demo->setText("Demo");
bar->addChild(demo);
// demo popup
popup = d_wm->createWindow("WindowsLook/PopupMenu");
demo->addChild(popup);
// demo -> new window
item = d_wm->createWindow("WindowsLook/MenuItem");
item->setText("New dialog");
item->setTooltipText("Hotkey: Space");
item->subscribeEvent("Clicked", Event::Subscriber(&ScrollablePaneSample::demoNewDialog, this));
popup->addChild(item);
}
/*************************************************************************
Cleans up resources allocated in the initialiseSample call.
*************************************************************************/
void ScrollablePaneSample::deinitialise()
{
// everything we did is cleaned up by CEGUI
delete d_inputAggregator;
}
/*************************************************************************
Handler for the 'Demo -> New dialog' menu item
*************************************************************************/
bool ScrollablePaneSample::demoNewDialog(const CEGUI::EventArgs&)
{
using namespace CEGUI;
// add a dialog to this pane so we have some more stuff to drag around :)
Window* dlg = d_wm->createWindow("WindowsLook/FrameWindow");
dlg->setMinSize(USize(UDim(0,200),UDim(0,100)));
dlg->setSize(USize(UDim(0,200),UDim(0,100)));
dlg->setText("Drag me around too!");
// we put this in the center of the viewport into the scrollable pane
UVector2 uni_center(UDim(0.5f,0), UDim(0.5f,0));
// URGENT FIXME!
//Vector2f center = CoordConverter::windowToScreen(*d_root, uni_center);
//Vector2f target = CoordConverter::screenToWindow(*d_pane->getContentPane(), center);
//dlg->setPosition(UVector2(UDim(0,target.d_x-100), UDim(0,target.d_y-50)));
d_pane->addChild(dlg);
return true;
}
bool ScrollablePaneSample::semanticEventHandler(const CEGUI::EventArgs& e)
{
const CEGUI::SemanticEventArgs& args = static_cast<const CEGUI::SemanticEventArgs&>(e);
if (args.d_semanticValue == SpawnNewDialog)
{
// this handler does not use the event args at all so this is fine :)
// though maybe a bit hack-ish...
demoNewDialog(e);
return true;
}
return false;
}
/*************************************************************************
Define the module function that returns an instance of the sample
*************************************************************************/
extern "C" SAMPLE_EXPORT Sample& getSampleInstance()
{
static ScrollablePaneSample sample;
return sample;
}<|endoftext|>
|
<commit_before>/**
* The MIT License
*
* Copyright (C) 2017 Kiyofumi Kondoh
*
* 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 "stdafx.h"
#include "cef_scheme_handler.h"
#include "include/cef_scheme.h"
#include "include/wrapper/cef_helpers.h"
namespace {
const char kScheme[] = "local";
const char kDomain[] = "test";
} // namespace {
static
CefRefPtr<CefSchemeHandlerFactory>
createClientSchemeHandlerFactory();
static
CefRefPtr<CefResourceHandler>
createClientSchemeHandler();
void registerSchemeHandlerFactory()
{
const bool bRet = CefRegisterSchemeHandlerFactory(
kScheme
, kDomain
, createClientSchemeHandlerFactory()
);
DCHECK(bRet);
}
void addCustomScheme( CefRawPtr<CefSchemeRegistrar> registrar )
{
const bool is_standard = true;
const bool is_local = false;
const bool is_display_isolated = false;
const bool is_secure = true;
const bool is_cors_enabled = false;
const bool is_csp_bypassing = false;
const bool bRet = registrar->AddCustomScheme(
kScheme
, is_standard
, is_local
, is_display_isolated
, is_secure
, is_cors_enabled
#if CHROME_VERSION_BUILD > 2987
, is_csp_bypassing
#endif // CHROME_VERSION_BUILD > 2987
);
DCHECK( bRet );
}
class ClientSchemeHandlerFactory
: public CefSchemeHandlerFactory
{
public:
ClientSchemeHandlerFactory() {}
CefRefPtr<CefResourceHandler>
Create(
CefRefPtr<CefBrowser> browser
, CefRefPtr<CefFrame> frame
, const CefString& scheme_name
, CefRefPtr<CefRequest> request
) OVERRIDE;
private:
IMPLEMENT_REFCOUNTING(ClientSchemeHandlerFactory);
DISALLOW_COPY_AND_ASSIGN(ClientSchemeHandlerFactory);
};
CefRefPtr<CefResourceHandler>
ClientSchemeHandlerFactory::Create(
CefRefPtr<CefBrowser> browser
, CefRefPtr<CefFrame> frame
, const CefString& scheme_name
, CefRefPtr<CefRequest> request
) // OVERRIDE
{
CEF_REQUIRE_IO_THREAD();
return createClientSchemeHandler();
}
CefRefPtr<CefSchemeHandlerFactory>
createClientSchemeHandlerFactory()
{
return new ClientSchemeHandlerFactory();
}
class ClientSchemeHandler
: public CefResourceHandler
{
public:
ClientSchemeHandler()
: is_binary_(false)
, offset_(0)
{
}
bool
ProcessRequest(
CefRefPtr<CefRequest> request
, CefRefPtr<CefCallback> callback
) OVERRIDE;
void
GetResponseHeaders(
CefRefPtr<CefResponse> response
, int64& response_length
, CefString& redirectUrl
) OVERRIDE;
bool
ReadResponse(
void* data_out
, int bytes_to_read
, int& bytes_read
, CefRefPtr<CefCallback> callback
) OVERRIDE;
void
Cancel() OVERRIDE;
private:
std::string mime_type_;
std::vector<uint8_t> data_;
bool is_binary_;
size_t offset_;
private:
IMPLEMENT_REFCOUNTING(ClientSchemeHandler);
DISALLOW_COPY_AND_ASSIGN(ClientSchemeHandler);
};
static
bool
ends_with(const std::string& str, const std::string& suffix)
{
if ( str.size() < suffix.size() )
{
return false;
}
return std::equal( std::rbegin(suffix), std::rend(suffix), std::rbegin(str) );
//return ( 0 == str.compare( str.size() - suffix.size(), suffix.size(), suffix ));
}
static
bool
parseURL(std::string& scheme, std::string& domain, std::string& path, const std::string& url)
{
const size_t pos_scheme = url.find( "://" );
if ( std::string::npos == pos_scheme )
{
return false;
}
scheme = url.substr( 0, pos_scheme );
if ( url.size() <= (pos_scheme + 3/*strlen("://")*/) )
{
return false;
}
const size_t pos_domain = url.find( '/', (pos_scheme + 3/*strlen("://")*/) );
if ( std::string::npos == pos_domain )
{
return false;
}
domain = url.substr( (pos_scheme + 3/*strlen("://")*/), pos_domain - (pos_scheme + 3/*strlen("://")*/) );
if ( url.size() <= (pos_domain + 1/*strlen("/")*/) )
{
return false;
}
path = url.substr( (pos_domain + 1/*strlen("/")*/) );
return true;
}
#if defined(_MSC_VER)
#pragma warning(disable : 4996)
#endif // defined(_MSC_VER)
static
bool
readResource( const std::string& path, std::vector<uint8_t>& data )
{
std::string relPath;
relPath = "resources_scheme/";
relPath += path;
FILE* fp = fopen( relPath.c_str(), "rb" );
if ( NULL == fp )
{
return false;
}
data.reserve( 256*1024 );
char buff[16];
size_t pos = 0;
size_t len;
while ( 0 < (len = fread( buff, 1, sizeof(buff), fp ) ) )
{
if ( data.size() < ( pos + len ) )
{
data.resize( (pos + len) );
}
memcpy( &(data.at(pos)), buff, len );
pos += len;
}
fclose( fp );
fp = NULL;
#if 0 // defined(OS_WIN)
{
char buff[128];
::wsprintfA( buff, "size=%u\n", data.size() );
::OutputDebugStringA( buff );
}
{
std::string str;
str.append( (const char*)&data.at(0), data.size() );
::OutputDebugStringA( str.c_str() );
}
#endif
return true;
}
bool
ClientSchemeHandler::ProcessRequest(
CefRefPtr<CefRequest> request
, CefRefPtr<CefCallback> callback
) // OVERRIDE
{
CEF_REQUIRE_IO_THREAD();
bool handled = false;
std::string url = request->GetURL();
std::string scheme;
std::string domain;
std::string path;
{
const bool bRet = parseURL( scheme, domain, path, url );
}
if ( ends_with( url, ".html" ) )
{
const bool bRet = readResource( path, this->data_ );
}
return handled;
}
void
ClientSchemeHandler::GetResponseHeaders(
CefRefPtr<CefResponse> response
, int64& response_length
, CefString& redirectUrl
) // OVERRIDE
{
CEF_REQUIRE_IO_THREAD();
}
bool
ClientSchemeHandler::ReadResponse(
void* data_out
, int bytes_to_read
, int& bytes_read
, CefRefPtr<CefCallback> callback
) // OVERRIDE
{
CEF_REQUIRE_IO_THREAD();
return true;
}
void
ClientSchemeHandler::Cancel() // OVERRIDE
{
CEF_REQUIRE_IO_THREAD();
}
CefRefPtr<CefResourceHandler>
createClientSchemeHandler()
{
return new ClientSchemeHandler();
}
<commit_msg>add response and transfer data to cef<commit_after>/**
* The MIT License
*
* Copyright (C) 2017 Kiyofumi Kondoh
*
* 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 "stdafx.h"
#include "cef_scheme_handler.h"
#include "include/cef_scheme.h"
#include "include/wrapper/cef_helpers.h"
namespace {
const char kScheme[] = "local";
const char kDomain[] = "test";
} // namespace {
static
CefRefPtr<CefSchemeHandlerFactory>
createClientSchemeHandlerFactory();
static
CefRefPtr<CefResourceHandler>
createClientSchemeHandler();
void registerSchemeHandlerFactory()
{
const bool bRet = CefRegisterSchemeHandlerFactory(
kScheme
, kDomain
, createClientSchemeHandlerFactory()
);
DCHECK(bRet);
}
void addCustomScheme( CefRawPtr<CefSchemeRegistrar> registrar )
{
const bool is_standard = true;
const bool is_local = false;
const bool is_display_isolated = false;
const bool is_secure = true;
const bool is_cors_enabled = false;
const bool is_csp_bypassing = false;
const bool bRet = registrar->AddCustomScheme(
kScheme
, is_standard
, is_local
, is_display_isolated
, is_secure
, is_cors_enabled
#if CHROME_VERSION_BUILD > 2987
, is_csp_bypassing
#endif // CHROME_VERSION_BUILD > 2987
);
DCHECK( bRet );
}
class ClientSchemeHandlerFactory
: public CefSchemeHandlerFactory
{
public:
ClientSchemeHandlerFactory() {}
CefRefPtr<CefResourceHandler>
Create(
CefRefPtr<CefBrowser> browser
, CefRefPtr<CefFrame> frame
, const CefString& scheme_name
, CefRefPtr<CefRequest> request
) OVERRIDE;
private:
IMPLEMENT_REFCOUNTING(ClientSchemeHandlerFactory);
DISALLOW_COPY_AND_ASSIGN(ClientSchemeHandlerFactory);
};
CefRefPtr<CefResourceHandler>
ClientSchemeHandlerFactory::Create(
CefRefPtr<CefBrowser> browser
, CefRefPtr<CefFrame> frame
, const CefString& scheme_name
, CefRefPtr<CefRequest> request
) // OVERRIDE
{
CEF_REQUIRE_IO_THREAD();
return createClientSchemeHandler();
}
CefRefPtr<CefSchemeHandlerFactory>
createClientSchemeHandlerFactory()
{
return new ClientSchemeHandlerFactory();
}
class ClientSchemeHandler
: public CefResourceHandler
{
public:
ClientSchemeHandler()
: is_binary_(false)
, delay_count_(0)
, offset_(0)
{
}
bool
ProcessRequest(
CefRefPtr<CefRequest> request
, CefRefPtr<CefCallback> callback
) OVERRIDE;
void
GetResponseHeaders(
CefRefPtr<CefResponse> response
, int64& response_length
, CefString& redirectUrl
) OVERRIDE;
bool
ReadResponse(
void* data_out
, int bytes_to_read
, int& bytes_read
, CefRefPtr<CefCallback> callback
) OVERRIDE;
void
Cancel() OVERRIDE;
private:
std::string mime_type_;
std::vector<uint8_t> data_;
bool is_binary_;
size_t delay_count_;
size_t offset_;
private:
IMPLEMENT_REFCOUNTING(ClientSchemeHandler);
DISALLOW_COPY_AND_ASSIGN(ClientSchemeHandler);
};
static
bool
ends_with(const std::string& str, const std::string& suffix)
{
if ( str.size() < suffix.size() )
{
return false;
}
return std::equal( std::rbegin(suffix), std::rend(suffix), std::rbegin(str) );
//return ( 0 == str.compare( str.size() - suffix.size(), suffix.size(), suffix ));
}
static
bool
parseURL(std::string& scheme, std::string& domain, std::string& path, const std::string& url)
{
const size_t pos_scheme = url.find( "://" );
if ( std::string::npos == pos_scheme )
{
return false;
}
scheme = url.substr( 0, pos_scheme );
if ( url.size() <= (pos_scheme + 3/*strlen("://")*/) )
{
return false;
}
const size_t pos_domain = url.find( '/', (pos_scheme + 3/*strlen("://")*/) );
if ( std::string::npos == pos_domain )
{
return false;
}
domain = url.substr( (pos_scheme + 3/*strlen("://")*/), pos_domain - (pos_scheme + 3/*strlen("://")*/) );
if ( url.size() <= (pos_domain + 1/*strlen("/")*/) )
{
return false;
}
path = url.substr( (pos_domain + 1/*strlen("/")*/) );
return true;
}
#if defined(_MSC_VER)
#pragma warning(disable : 4996)
#endif // defined(_MSC_VER)
static
bool
readResource( const std::string& path, std::vector<uint8_t>& data )
{
std::string relPath;
relPath = "resources_scheme/";
relPath += path;
FILE* fp = fopen( relPath.c_str(), "rb" );
if ( NULL == fp )
{
return false;
}
data.reserve( 256*1024 );
char buff[16];
size_t pos = 0;
size_t len;
while ( 0 < (len = fread( buff, 1, sizeof(buff), fp ) ) )
{
if ( data.size() < ( pos + len ) )
{
data.resize( (pos + len) );
}
memcpy( &(data.at(pos)), buff, len );
pos += len;
}
fclose( fp );
fp = NULL;
#if 0 // defined(OS_WIN)
{
char buff[128];
::wsprintfA( buff, "size=%u\n", data.size() );
::OutputDebugStringA( buff );
}
{
std::string str;
str.append( (const char*)&data.at(0), data.size() );
::OutputDebugStringA( str.c_str() );
}
#endif
return true;
}
bool
ClientSchemeHandler::ProcessRequest(
CefRefPtr<CefRequest> request
, CefRefPtr<CefCallback> callback
) // OVERRIDE
{
CEF_REQUIRE_IO_THREAD();
bool handled = false;
std::string url = request->GetURL();
std::string scheme;
std::string domain;
std::string path;
{
const bool bRet = parseURL( scheme, domain, path, url );
}
if ( ends_with( url, ".html" ) )
{
const bool bRet = readResource( path, this->data_ );
if ( bRet )
{
handled = true;
this->mime_type_ = "text/html";
}
}
if ( handled )
{
callback->Continue();
}
return handled;
}
void
ClientSchemeHandler::GetResponseHeaders(
CefRefPtr<CefResponse> response
, int64& response_length
, CefString& redirectUrl
) // OVERRIDE
{
CEF_REQUIRE_IO_THREAD();
DCHECK( false == this->data_.empty() );
response->SetMimeType( this->mime_type_ );
response->SetStatus( 200 );
response_length = this->data_.size();
}
bool
ClientSchemeHandler::ReadResponse(
void* data_out
, int bytes_to_read
, int& bytes_read
, CefRefPtr<CefCallback> callback
) // OVERRIDE
{
CEF_REQUIRE_IO_THREAD();
bool transfer_data = false;
bytes_read = 0;
bool notready = true;
{
this->delay_count_ += 1;
if ( 3 < this->delay_count_ )
{
this->delay_count_ = 0;
notready = false;
}
}
if ( notready )
{
bytes_read = 0;
callback->Continue();
transfer_data = true;
}
else
{
if ( this->offset_ < this->data_.size() )
{
bytes_to_read = 16;
const int transfer_size =
std::min(
bytes_to_read
, static_cast<int>( this->data_.size() - this->offset_ )
);
memcpy( data_out, &(this->data_.at(this->offset_)), transfer_size );
this->offset_ += transfer_size;
bytes_read = transfer_size;
transfer_data = true;
}
}
return transfer_data;
}
void
ClientSchemeHandler::Cancel() // OVERRIDE
{
CEF_REQUIRE_IO_THREAD();
}
CefRefPtr<CefResourceHandler>
createClientSchemeHandler()
{
return new ClientSchemeHandler();
}
<|endoftext|>
|
<commit_before>#include <QString>
#include <functional>
#include <future>
#include <memory>
#include "kernel.h"
#include "coverage.h"
#include "columndefinition.h"
#include "table.h"
#include "attributerecord.h"
#include "polygon.h"
#include "geometry.h"
#include "feature.h"
#include "featurecoverage.h"
#include "symboltable.h"
#include "OperationExpression.h"
#include "operationmetadata.h"
#include "operation.h"
#include "operationhelper.h"
#include "operationhelperfeatures.h"
#include "commandhandler.h"
#include "featureiterator.h"
#include "ifoperation.h"
#include "iffeature.h"
using namespace Ilwis;
using namespace BaseOperations;
Ilwis::BaseOperations::IfFeature::IfFeature()
{
}
IfFeature::IfFeature(quint64 metaid, const Ilwis::OperationExpression &expr) : IfOperation(metaid, expr)
{
}
bool IfFeature::execute(ExecutionContext *ctx, SymbolTable &symTable)
{
if (_prepState == sNOTPREPARED)
if((_prepState = prepare(ctx, symTable)) != sPREPARED)
return false;
SubSetAsyncFunc iffunc = [&](const std::vector<quint32>& subset) -> bool {
// FeatureIterator iterOut(_outputFC);
// FeatureIterator iterIn(_inputFC,subset);
// FeatureIterator iter1, iter2;
// iter1 = iterOut;
// bool isCoverage1 = _coverages[0].isValid();
// bool isCoverage2 = _coverages[1].isValid();
// if ( isCoverage1)
// iter1 = FeatureIterator(_coverages[0].get<FeatureCoverage>(), subset);
// if ( isCoverage2)
// iter2 = FeatureIterator(_coverages[1].get<FeatureCoverage>(), subset);
// while(iterIn != iterIn.end()) {
// FeatureInterface v1,v2;
// if ( isCoverage1) {
// v1 = *iter1;
// ++iter1;
// }
// if ( isCoverage2) {
// v2 = *iter2;
// ++iter2;
// }
// if (_number[0] != rUNDEF)
// v1 = _number[0];
// if ( _number[1] != rUNDEF)
// v2 = _number[1];
// *iterOut = *iterIn ? v1 : v2;
// ++iterOut;
// ++iterIn;
// }
return true;
};
// bool res = OperationHelperRaster::execute(ctx, iffunc, _outputGC);
// if ( res && ctx != 0) {
// QVariant value;
// value.setValue<IFeatureCoverage>(_outputFC);
// ctx->addOutput(symTable,value,_outputFC->name(),itGRIDCOVERAGE,_outputGC->source());
// }
return true;
}
Ilwis::OperationImplementation *IfFeature::create(quint64 metaid, const Ilwis::OperationExpression &expr)
{
return new IfFeature(metaid, expr);
}
Ilwis::OperationImplementation::State IfFeature::prepare(ExecutionContext *ctx, const SymbolTable &)
{
QString fc = _expression.parm(0).value();
if (!_inputFC.prepare(fc)) {
ERROR2(ERR_COULD_NOT_LOAD_2,fc,"");
return sPREPAREFAILED;
}
OperationHelperFeatures helper;
IIlwisObject obj = helper.initialize(_inputFC.get<IlwisObject>(), itFEATURECOVERAGE, itENVELOPE | itCOORDSYSTEM) ;
if ( !obj.isValid()) {
ERROR2(ERR_INVALID_INIT_FOR_2,"FeatureCoverage",fc);
return sPREPAREFAILED;
}
_outputFC = obj.get<FeatureCoverage>();
DataDefinition outputDataDef = findOutputDataDef(_expression);
_outputFC->datadef() = outputDataDef;
return sPREPARED;
}
quint64 IfFeature::createMetadata()
{
QString url = QString("ilwis://operations/iff");
Resource res(QUrl(url), itOPERATIONMETADATA);
res.addProperty("namespace","ilwis");
res.addProperty("longname","iff");
res.addProperty("syntax","iffraster(featurecoverage,outputchoicetrue, outputchoicefalse)");
res.addProperty("inparameters","3");
res.addProperty("pin_1_type", itFEATURECOVERAGE);
res.addProperty("pin_1_name", TR("input featurecoverage"));
res.addProperty("pin_1_desc",TR("input featurecoverage with boolean domain"));
res.addProperty("pin_2_type", itNUMERIC | itSTRING | itBOOL | itFEATURECOVERAGE);
res.addProperty("pin_2_name", TR("true choice"));
res.addProperty("pin_2_desc",TR("value returned when the boolean input feature is true"));
res.addProperty("pin_3_type", itNUMERIC | itSTRING | itBOOL | itFEATURECOVERAGE);
res.addProperty("pin_3_name", TR("false choice"));
res.addProperty("pin_3_desc",TR("value returned when the boolean input feature is false"));
res.addProperty("outparameters",1);
res.addProperty("pout_1_type", itFEATURECOVERAGE);
res.addProperty("pout_1_name", TR("featurecoverage"));
res.addProperty("pout_1_desc",TR("featurecoverage with all features that correspond to the true value in the input having a value"));
res.prepare();
url += "=" + QString::number(res.id());
res.setUrl(url);
mastercatalog()->addItems({res});
return res.id();
}
<commit_msg>partial implementation of iff for features; completion has to wait until some oeht operations for features are finished<commit_after>#include <QString>
#include <functional>
#include <future>
#include <memory>
#include "kernel.h"
#include "coverage.h"
#include "columndefinition.h"
#include "table.h"
#include "attributerecord.h"
#include "polygon.h"
#include "geometry.h"
#include "feature.h"
#include "featurecoverage.h"
#include "symboltable.h"
#include "OperationExpression.h"
#include "operationmetadata.h"
#include "operation.h"
#include "operationhelper.h"
#include "operationhelperfeatures.h"
#include "commandhandler.h"
#include "featureiterator.h"
#include "ifoperation.h"
#include "iffeature.h"
using namespace Ilwis;
using namespace BaseOperations;
Ilwis::BaseOperations::IfFeature::IfFeature()
{
}
IfFeature::IfFeature(quint64 metaid, const Ilwis::OperationExpression &expr) : IfOperation(metaid, expr)
{
}
bool IfFeature::execute(ExecutionContext *ctx, SymbolTable &symTable)
{
if (_prepState == sNOTPREPARED)
if((_prepState = prepare(ctx, symTable)) != sPREPARED)
return false;
SubSetAsyncFunc iffunc = [&](const std::vector<quint32>& subset) -> bool {
FeatureIterator iterOut(_outputFC);
FeatureIterator iterIn(_inputFC,subset);
while(iterIn != iterIn.end()) {
_outputFC->newFeatureFrom(*iterIn);
++iterOut;
++iterIn;
}
return true;
};
bool res = OperationHelperFeatures::execute(ctx, iffunc, _outputFC);
if ( res && ctx != 0) {
QVariant value;
value.setValue<IFeatureCoverage>(_outputFC);
ctx->addOutput(symTable,value,_outputFC->name(),itFEATURECOVERAGE,_outputFC->source());
}
return true;
}
Ilwis::OperationImplementation *IfFeature::create(quint64 metaid, const Ilwis::OperationExpression &expr)
{
return new IfFeature(metaid, expr);
}
Ilwis::OperationImplementation::State IfFeature::prepare(ExecutionContext *ctx, const SymbolTable &)
{
QString fc = _expression.parm(0).value();
if (!_inputFC.prepare(fc)) {
ERROR2(ERR_COULD_NOT_LOAD_2,fc,"");
return sPREPAREFAILED;
}
OperationHelperFeatures helper;
IIlwisObject obj = helper.initialize(_inputFC.get<IlwisObject>(), itFEATURECOVERAGE, itENVELOPE | itCOORDSYSTEM) ;
if ( !obj.isValid()) {
ERROR2(ERR_INVALID_INIT_FOR_2,"FeatureCoverage",fc);
return sPREPAREFAILED;
}
_outputFC = obj.get<FeatureCoverage>();
DataDefinition outputDataDef = findOutputDataDef(_expression);
_outputFC->datadef() = outputDataDef;
return sPREPARED;
}
quint64 IfFeature::createMetadata()
{
QString url = QString("ilwis://operations/iff");
Resource res(QUrl(url), itOPERATIONMETADATA);
res.addProperty("namespace","ilwis");
res.addProperty("longname","iff");
res.addProperty("syntax","iffraster(featurecoverage,outputchoicetrue, outputchoicefalse)");
res.addProperty("inparameters","3");
res.addProperty("pin_1_type", itFEATURECOVERAGE);
res.addProperty("pin_1_name", TR("input featurecoverage"));
res.addProperty("pin_1_desc",TR("input featurecoverage with boolean domain"));
res.addProperty("pin_2_type", itNUMERIC | itSTRING | itBOOL | itFEATURECOVERAGE);
res.addProperty("pin_2_name", TR("true choice"));
res.addProperty("pin_2_desc",TR("value returned when the boolean input feature is true"));
res.addProperty("pin_3_type", itNUMERIC | itSTRING | itBOOL | itFEATURECOVERAGE);
res.addProperty("pin_3_name", TR("false choice"));
res.addProperty("pin_3_desc",TR("value returned when the boolean input feature is false"));
res.addProperty("outparameters",1);
res.addProperty("pout_1_type", itFEATURECOVERAGE);
res.addProperty("pout_1_name", TR("featurecoverage"));
res.addProperty("pout_1_desc",TR("featurecoverage with all features that correspond to the true value in the input having a value"));
res.prepare();
url += "=" + QString::number(res.id());
res.setUrl(url);
mastercatalog()->addItems({res});
return res.id();
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: sbintern.cxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: hr $ $Date: 2005-09-29 16:10:51 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* 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., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _SHL_HXX //autogen
#include <tools/shl.hxx>
#endif
#include "sbintern.hxx"
#include "sbunoobj.hxx"
#include "token.hxx" // Tokenizer
#include "symtbl.hxx" // Symbolverwaltung
#include "parser.hxx" // Parser
#include "codegen.hxx" // Code-Generator
#include "basmgr.hxx"
#pragma hdrstop
SV_IMPL_PTRARR(SbErrorStack, SbErrorStackEntry*)
SbiGlobals* GetSbData()
{
SbiGlobals** pp = (SbiGlobals**) ::GetAppData( SHL_SBC );
SbiGlobals* p = *pp;
if( !p )
p = *pp = new SbiGlobals;
return p;
}
SbiGlobals::SbiGlobals()
{
pInst = NULL;
pMod = NULL;
pSbFac= NULL;
pUnoFac = NULL;
pTypeFac = NULL;
pOLEFac = NULL;
pCompMod = NULL; // JSM
nInst = 0;
nCode = 0;
nLine = 0;
nCol1 = nCol2 = 0;
bCompiler = FALSE;
bGlobalInitErr = FALSE;
bRunInit = FALSE;
eLanguageMode = SB_LANG_BASIC;
pErrStack = NULL;
pTransliterationWrapper = NULL;
bBlockCompilerError = FALSE;
pAppBasMgr = NULL;
}
SbiGlobals::~SbiGlobals()
{
delete pErrStack;
delete pSbFac;
delete pUnoFac;
delete pTransliterationWrapper;
}
<commit_msg>INTEGRATION: CWS warnings01 (1.7.8); FILE MERGED 2005/11/07 12:02:40 ab 1.7.8.1: #i53898# Removed warnings<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: sbintern.cxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: hr $ $Date: 2006-06-19 17:40:11 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* 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., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _SHL_HXX //autogen
#include <tools/shl.hxx>
#endif
#include "sbintern.hxx"
#include "sbunoobj.hxx"
#include "token.hxx" // Tokenizer
#include "symtbl.hxx" // Symbolverwaltung
#include "parser.hxx" // Parser
#include "codegen.hxx" // Code-Generator
#include "basmgr.hxx"
SV_IMPL_PTRARR(SbErrorStack, SbErrorStackEntry*)
SbiGlobals* GetSbData()
{
SbiGlobals** pp = (SbiGlobals**) ::GetAppData( SHL_SBC );
SbiGlobals* p = *pp;
if( !p )
p = *pp = new SbiGlobals;
return p;
}
SbiGlobals::SbiGlobals()
{
pInst = NULL;
pMod = NULL;
pSbFac= NULL;
pUnoFac = NULL;
pTypeFac = NULL;
pOLEFac = NULL;
pCompMod = NULL; // JSM
nInst = 0;
nCode = 0;
nLine = 0;
nCol1 = nCol2 = 0;
bCompiler = FALSE;
bGlobalInitErr = FALSE;
bRunInit = FALSE;
eLanguageMode = SB_LANG_BASIC;
pErrStack = NULL;
pTransliterationWrapper = NULL;
bBlockCompilerError = FALSE;
pAppBasMgr = NULL;
}
SbiGlobals::~SbiGlobals()
{
delete pErrStack;
delete pSbFac;
delete pUnoFac;
delete pTransliterationWrapper;
}
<|endoftext|>
|
<commit_before><commit_msg>fixed typo<commit_after><|endoftext|>
|
<commit_before>#ifndef STRING_HPP
#define STRING_HPP
#include <string>
#include <vector>
#include <sstream>
#include <cmath>
namespace string {
using unicode_char = std::uint32_t;
using unicode = std::basic_string<unicode_char>;
template<typename T>
std::string convert(const T& t) {
std::ostringstream ss;
ss << t;
return ss.str();
}
template<typename T, typename enable = typename std::enable_if<!std::is_same<T,std::string>::value>::type>
std::string convert(const T& t, std::size_t n, char fill = '0') {
if (n <= 1) {
return convert(t);
}
if (t == 0) {
return std::string(n-1, fill)+'0';
} else {
std::ostringstream ss;
ss << t;
std::size_t nz = n-1 - floor(log10(t));
if (nz > 0 && nz < 6) {
return std::string(nz, fill) + ss.str();
} else {
return ss.str();
}
}
}
template<typename T>
bool convert(const std::string& s, T& t) {
std::istringstream ss(s);
return (ss >> t);
}
std::string trim(std::string ts, const std::string& chars = " \t");
std::string join(const std::vector<std::string>& vs, const std::string& delim = "");
std::string to_upper(std::string ts);
std::string to_lower(std::string ts);
std::string erase_begin(std::string ts, std::size_t n = 1);
std::string erase_end(std::string ts, std::size_t n = 1);
std::string replace(std::string ts, const std::string& pattern, const std::string& rep);
std::size_t distance(const std::string& t, const std::string& u);
bool start_with(const std::string& s, const std::string& pattern);
bool end_with(const std::string& s, const std::string& pattern);
std::vector<std::string> split(const std::string& ts, const std::string& pattern);
std::vector<std::string> split_any_of(const std::string& ts, const std::string& chars);
std::string collapse(const std::vector<std::string>& sv, const std::string& sep);
std::string uchar_to_hex(std::uint8_t i);
std::uint8_t hex_to_uchar(std::string s);
unicode_char to_unicode(unsigned char c);
unicode to_unicode(const std::string& s);
std::string to_utf8(unicode_char s);
std::string to_utf8(const unicode& s);
}
#endif
<commit_msg>Added string::to_string<commit_after>#ifndef STRING_HPP
#define STRING_HPP
#include <string>
#include <vector>
#include <sstream>
#include <cmath>
namespace string {
using unicode_char = std::uint32_t;
using unicode = std::basic_string<unicode_char>;
template<typename T>
std::string convert(const T& t) {
std::ostringstream ss;
ss << t;
return ss.str();
}
template<typename T, typename enable = typename std::enable_if<!std::is_same<T,std::string>::value>::type>
std::string convert(const T& t, std::size_t n, char fill = '0') {
if (n <= 1) {
return convert(t);
}
if (t == 0) {
return std::string(n-1, fill)+'0';
} else {
std::ostringstream ss;
ss << t;
std::size_t nz = n-1 - floor(log10(t));
if (nz > 0 && nz < 6) {
return std::string(nz, fill) + ss.str();
} else {
return ss.str();
}
}
}
template<typename T>
bool convert(const std::string& s, T& t) {
std::istringstream ss(s);
return (ss >> t);
}
std::string trim(std::string ts, const std::string& chars = " \t");
std::string join(const std::vector<std::string>& vs, const std::string& delim = "");
std::string to_upper(std::string ts);
std::string to_lower(std::string ts);
std::string erase_begin(std::string ts, std::size_t n = 1);
std::string erase_end(std::string ts, std::size_t n = 1);
std::string replace(std::string ts, const std::string& pattern, const std::string& rep);
std::size_t distance(const std::string& t, const std::string& u);
bool start_with(const std::string& s, const std::string& pattern);
bool end_with(const std::string& s, const std::string& pattern);
std::vector<std::string> split(const std::string& ts, const std::string& pattern);
std::vector<std::string> split_any_of(const std::string& ts, const std::string& chars);
std::string collapse(const std::vector<std::string>& sv, const std::string& sep);
std::string uchar_to_hex(std::uint8_t i);
std::uint8_t hex_to_uchar(std::string s);
unicode_char to_unicode(unsigned char c);
unicode to_unicode(const std::string& s);
std::string to_utf8(unicode_char s);
std::string to_utf8(const unicode& s);
template<typename ... Args>
std::string to_string(Args&& ... args) {
std::ostringstream ss;
(void)(int[]){0, ((void)(ss << args), 0)...};
return ss.str();
}
}
#endif
<|endoftext|>
|
<commit_before>#include <cfloat>
#include <cmath>
#include "geometry/r3_element.hpp"
#include "glog/logging.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "quantities/elementary_functions.hpp"
#include "quantities/si.hpp"
#include "testing_utilities/numerics.hpp"
namespace principia {
namespace testing_utilities {
using quantities::Dimensionless;
using quantities::Sqrt;
using geometry::R3Element;
using si::Metre;
using testing::Eq;
using testing::Ne;
namespace {
struct World;
} // namespace
class NumericsTest : public testing::Test {};
double DoubleAbs(const double x) {
return std::abs(x);
};
// The smallest positive double, a denormal.
double const SmallestPositive = DBL_MIN * DBL_EPSILON;
TEST_F(NumericsTest, ULPs) {
EXPECT_THAT(ULPDistance(1, 1), Eq(0));
EXPECT_THAT(ULPDistance(+0.0, +0.0), Eq(0));
EXPECT_THAT(ULPDistance(+0.0, -0.0), Eq(0));
// DBL_MIN is the smallest positive normalised number.
// 52 bits of mantissa stand between it and 0, in the form of denormals.
EXPECT_THAT(ULPDistance(+0.0, DBL_MIN), Eq(std::pow(2, DBL_MANT_DIG - 1)));
EXPECT_THAT(ULPDistance(-0.0, DBL_MIN), Eq(std::pow(2, DBL_MANT_DIG - 1)));
EXPECT_THAT(ULPDistance(+0.0, -SmallestPositive), Eq(1));
EXPECT_THAT(ULPDistance(-0.0, -SmallestPositive), Eq(1));
EXPECT_THAT(ULPDistance(-1, 1), Ne(0));
EXPECT_THAT(ULPDistance(-1, 1), 2 * ULPDistance(0, 1));
}
TEST_F(NumericsTest, DoubleAbsoluteError) {
EXPECT_THAT(AbsoluteError(1., 1., DoubleAbs), Eq(0.));
EXPECT_THAT(AbsoluteError(1., 2., DoubleAbs), Eq(1.));
EXPECT_THAT(AbsoluteError(1., 0., DoubleAbs), Eq(1.));
}
TEST_F(NumericsTest, DimensionlessAbsoluteError) {
EXPECT_THAT(AbsoluteError(1, 1), Eq(0));
EXPECT_THAT(AbsoluteError(1, 2), Eq(1));
EXPECT_THAT(AbsoluteError(1, 0), Eq(1));
}
TEST_F(NumericsTest, DimensionfulAbsoluteError) {
EXPECT_THAT(AbsoluteError(1 * Metre, 1 * Metre), Eq(0 * Metre));
EXPECT_THAT(AbsoluteError(1 * Metre, 2 * Metre), Eq(1 * Metre));
EXPECT_THAT(AbsoluteError(1 * Metre, 0 * Metre), Eq(1 * Metre));
}
TEST_F(NumericsTest, R3ElementAbsoluteError) {
R3Element<Dimensionless> const i = {1, 0, 0};
R3Element<Dimensionless> const j = {0, 1, 0};
R3Element<Dimensionless> const k = {0, 0, 1};
EXPECT_THAT(AbsoluteError(i + j + k, i + j + k), Eq(0));
EXPECT_THAT(AbsoluteError(i + j, i + j + k), Eq(1));
EXPECT_THAT(AbsoluteError(i, i + j + k), Eq(Sqrt(2)));
}
TEST_F(NumericsTest, DoubleRelativeError) {
auto const double_abs = [](double x) { return std::abs(x); };
EXPECT_THAT(
RelativeError(SmallestPositive, 2 * (SmallestPositive / 2), double_abs),
Eq(1));
}
} // namespace testing_utilities
} // namespace principia
<commit_msg>double<commit_after>#include <cfloat>
#include <cmath>
#include "geometry/r3_element.hpp"
#include "glog/logging.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "quantities/elementary_functions.hpp"
#include "quantities/si.hpp"
#include "testing_utilities/numerics.hpp"
namespace principia {
namespace testing_utilities {
using quantities::Dimensionless;
using quantities::Sqrt;
using geometry::R3Element;
using si::Metre;
using testing::AllOf;
using testing::Eq;
using testing::Gt;
using testing::Lt;
using testing::Ne;
namespace {
struct World;
} // namespace
class NumericsTest : public testing::Test {};
double DoubleAbs(const double x) {
return std::abs(x);
};
// The smallest positive double, a denormal.
double const SmallestPositive = DBL_MIN * DBL_EPSILON;
TEST_F(NumericsTest, ULPs) {
EXPECT_THAT(ULPDistance(1, 1), Eq(0));
EXPECT_THAT(ULPDistance(+0.0, +0.0), Eq(0));
EXPECT_THAT(ULPDistance(+0.0, -0.0), Eq(0));
// DBL_MIN is the smallest positive normalised number.
// 52 bits of mantissa stand between it and 0, in the form of denormals.
EXPECT_THAT(ULPDistance(+0.0, DBL_MIN), Eq(std::pow(2, DBL_MANT_DIG - 1)));
EXPECT_THAT(ULPDistance(-0.0, DBL_MIN), Eq(std::pow(2, DBL_MANT_DIG - 1)));
EXPECT_THAT(ULPDistance(+0.0, -SmallestPositive), Eq(1));
EXPECT_THAT(ULPDistance(-0.0, -SmallestPositive), Eq(1));
EXPECT_THAT(ULPDistance(-1, 1), Ne(0));
EXPECT_THAT(ULPDistance(-1, 1), Eq(2 * ULPDistance(0, 1)));
}
TEST_F(NumericsTest, DoubleAbsoluteError) {
EXPECT_THAT(AbsoluteError(1., 1., DoubleAbs), Eq(0.));
EXPECT_THAT(AbsoluteError(1., 2., DoubleAbs), Eq(1.));
EXPECT_THAT(AbsoluteError(1., 0., DoubleAbs), Eq(1.));
}
TEST_F(NumericsTest, DimensionlessAbsoluteError) {
EXPECT_THAT(AbsoluteError(1, 1), Eq(0));
EXPECT_THAT(AbsoluteError(1, 2), Eq(1));
EXPECT_THAT(AbsoluteError(1, 0), Eq(1));
}
TEST_F(NumericsTest, DimensionfulAbsoluteError) {
EXPECT_THAT(AbsoluteError(1 * Metre, 1 * Metre), Eq(0 * Metre));
EXPECT_THAT(AbsoluteError(1 * Metre, 2 * Metre), Eq(1 * Metre));
EXPECT_THAT(AbsoluteError(1 * Metre, 0 * Metre), Eq(1 * Metre));
}
TEST_F(NumericsTest, R3ElementAbsoluteError) {
R3Element<Dimensionless> const i = {1, 0, 0};
R3Element<Dimensionless> const j = {0, 1, 0};
R3Element<Dimensionless> const k = {0, 0, 1};
EXPECT_THAT(AbsoluteError(i + j + k, i + j + k), Eq(0));
EXPECT_THAT(AbsoluteError(i + j, i + j + k), Eq(1));
EXPECT_THAT(AbsoluteError(i, i + j + k), Eq(Sqrt(2)));
}
TEST_F(NumericsTest, DoubleRelativeError) {
EXPECT_THAT(
RelativeError(42.0, 42.0, DoubleAbs), Eq(0));
EXPECT_THAT(
RelativeError(1.0, -1.0, DoubleAbs), Eq(2));
EXPECT_THAT(
RelativeError(42.0, 6.0 * 9.0, DoubleAbs), AllOf(Gt(0.28), Lt(0.29)));
}
} // namespace testing_utilities
} // namespace principia
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2017 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include <cstring>
#include "webrtc/base/event.h"
#include "webrtc/base/logging.h"
#include "webrtc/base/scoped_ref_ptr.h"
#include "webrtc/modules/audio_device/audio_device_impl.h"
#include "webrtc/modules/audio_device/include/audio_device.h"
#include "webrtc/modules/audio_device/include/mock_audio_transport.h"
#include "webrtc/system_wrappers/include/sleep.h"
#include "webrtc/test/gmock.h"
#include "webrtc/test/gtest.h"
using ::testing::_;
using ::testing::AtLeast;
using ::testing::Ge;
using ::testing::Invoke;
using ::testing::NiceMock;
using ::testing::NotNull;
namespace webrtc {
namespace {
// Don't run these tests in combination with sanitizers.
#if !defined(ADDRESS_SANITIZER) && !defined(MEMORY_SANITIZER)
#define SKIP_TEST_IF_NOT(requirements_satisfied) \
do { \
if (!requirements_satisfied) { \
return; \
} \
} while (false)
#else
// Or if other audio-related requirements are not met.
#define SKIP_TEST_IF_NOT(requirements_satisfied) \
do { \
return; \
} while (false)
#endif
// Number of callbacks (input or output) the tests waits for before we set
// an event indicating that the test was OK.
static const size_t kNumCallbacks = 10;
// Max amount of time we wait for an event to be set while counting callbacks.
static const int kTestTimeOutInMilliseconds = 10 * 1000;
enum class TransportType {
kInvalid,
kPlay,
kRecord,
kPlayAndRecord,
};
} // namespace
// Mocks the AudioTransport object and proxies actions for the two callbacks
// (RecordedDataIsAvailable and NeedMorePlayData) to different implementations
// of AudioStreamInterface.
class MockAudioTransport : public test::MockAudioTransport {
public:
explicit MockAudioTransport(TransportType type) : type_(type) {}
~MockAudioTransport() {}
// Set default actions of the mock object. We are delegating to fake
// implementation where the number of callbacks is counted and an event
// is set after a certain number of callbacks. Audio parameters are also
// checked.
void HandleCallbacks(rtc::Event* event, int num_callbacks) {
event_ = event;
num_callbacks_ = num_callbacks;
if (play_mode()) {
ON_CALL(*this, NeedMorePlayData(_, _, _, _, _, _, _, _))
.WillByDefault(
Invoke(this, &MockAudioTransport::RealNeedMorePlayData));
}
if (rec_mode()) {
ON_CALL(*this, RecordedDataIsAvailable(_, _, _, _, _, _, _, _, _, _))
.WillByDefault(
Invoke(this, &MockAudioTransport::RealRecordedDataIsAvailable));
}
}
int32_t RealRecordedDataIsAvailable(const void* audio_buffer,
const size_t samples_per_channel,
const size_t bytes_per_frame,
const size_t channels,
const uint32_t sample_rate,
const uint32_t total_delay_ms,
const int32_t clock_drift,
const uint32_t current_mic_level,
const bool typing_status,
uint32_t& new_mic_level) {
EXPECT_TRUE(rec_mode()) << "No test is expecting these callbacks.";
LOG(INFO) << "+";
// Store audio parameters once in the first callback. For all other
// callbacks, verify that the provided audio parameters are maintained and
// that each callback corresponds to 10ms for any given sample rate.
if (!record_parameters_.is_complete()) {
record_parameters_.reset(sample_rate, channels, samples_per_channel);
} else {
EXPECT_EQ(samples_per_channel, record_parameters_.frames_per_buffer());
EXPECT_EQ(bytes_per_frame, record_parameters_.GetBytesPerFrame());
EXPECT_EQ(channels, record_parameters_.channels());
EXPECT_EQ(static_cast<int>(sample_rate),
record_parameters_.sample_rate());
EXPECT_EQ(samples_per_channel,
record_parameters_.frames_per_10ms_buffer());
}
rec_count_++;
// Signal the event after given amount of callbacks.
if (ReceivedEnoughCallbacks()) {
event_->Set();
}
return 0;
}
int32_t RealNeedMorePlayData(const size_t samples_per_channel,
const size_t bytes_per_frame,
const size_t channels,
const uint32_t sample_rate,
void* audio_buffer,
size_t& samples_per_channel_out,
int64_t* elapsed_time_ms,
int64_t* ntp_time_ms) {
EXPECT_TRUE(play_mode()) << "No test is expecting these callbacks.";
LOG(INFO) << "-";
// Store audio parameters once in the first callback. For all other
// callbacks, verify that the provided audio parameters are maintained and
// that each callback corresponds to 10ms for any given sample rate.
if (!playout_parameters_.is_complete()) {
playout_parameters_.reset(sample_rate, channels, samples_per_channel);
} else {
EXPECT_EQ(samples_per_channel, playout_parameters_.frames_per_buffer());
EXPECT_EQ(bytes_per_frame, playout_parameters_.GetBytesPerFrame());
EXPECT_EQ(channels, playout_parameters_.channels());
EXPECT_EQ(static_cast<int>(sample_rate),
playout_parameters_.sample_rate());
EXPECT_EQ(samples_per_channel,
playout_parameters_.frames_per_10ms_buffer());
}
play_count_++;
samples_per_channel_out = samples_per_channel;
// Fill the audio buffer with zeros to avoid disturbing audio.
const size_t num_bytes = samples_per_channel * bytes_per_frame;
std::memset(audio_buffer, 0, num_bytes);
// Signal the event after given amount of callbacks.
if (ReceivedEnoughCallbacks()) {
event_->Set();
}
return 0;
}
bool ReceivedEnoughCallbacks() {
bool recording_done = false;
if (rec_mode()) {
recording_done = rec_count_ >= num_callbacks_;
} else {
recording_done = true;
}
bool playout_done = false;
if (play_mode()) {
playout_done = play_count_ >= num_callbacks_;
} else {
playout_done = true;
}
return recording_done && playout_done;
}
bool play_mode() const {
return type_ == TransportType::kPlay ||
type_ == TransportType::kPlayAndRecord;
}
bool rec_mode() const {
return type_ == TransportType::kRecord ||
type_ == TransportType::kPlayAndRecord;
}
private:
TransportType type_ = TransportType::kInvalid;
rtc::Event* event_ = nullptr;
size_t num_callbacks_ = 0;
size_t play_count_ = 0;
size_t rec_count_ = 0;
AudioParameters playout_parameters_;
AudioParameters record_parameters_;
};
// AudioDeviceTest test fixture.
class AudioDeviceTest : public ::testing::Test {
protected:
AudioDeviceTest() : event_(false, false) {
#if !defined(ADDRESS_SANITIZER) && !defined(MEMORY_SANITIZER)
rtc::LogMessage::LogToDebug(rtc::LS_INFO);
// Add extra logging fields here if needed for debugging.
// rtc::LogMessage::LogTimestamps();
// rtc::LogMessage::LogThreads();
audio_device_ =
AudioDeviceModule::Create(0, AudioDeviceModule::kPlatformDefaultAudio);
EXPECT_NE(audio_device_.get(), nullptr);
AudioDeviceModule::AudioLayer audio_layer;
int got_platform_audio_layer =
audio_device_->ActiveAudioLayer(&audio_layer);
if (got_platform_audio_layer != 0 ||
audio_layer == AudioDeviceModule::kLinuxAlsaAudio) {
requirements_satisfied_ = false;
}
if (requirements_satisfied_) {
EXPECT_EQ(0, audio_device_->Init());
const int16_t num_playout_devices = audio_device_->PlayoutDevices();
const int16_t num_record_devices = audio_device_->RecordingDevices();
requirements_satisfied_ =
num_playout_devices > 0 && num_record_devices > 0;
}
#else
requirements_satisfied_ = false;
#endif
if (requirements_satisfied_) {
EXPECT_EQ(0, audio_device_->SetPlayoutDevice(0));
EXPECT_EQ(0, audio_device_->InitSpeaker());
EXPECT_EQ(0, audio_device_->SetRecordingDevice(0));
EXPECT_EQ(0, audio_device_->InitMicrophone());
EXPECT_EQ(0, audio_device_->StereoPlayoutIsAvailable(&stereo_playout_));
EXPECT_EQ(0, audio_device_->SetStereoPlayout(stereo_playout_));
EXPECT_EQ(0,
audio_device_->StereoRecordingIsAvailable(&stereo_recording_));
EXPECT_EQ(0, audio_device_->SetStereoRecording(stereo_recording_));
EXPECT_EQ(0, audio_device_->SetAGC(false));
EXPECT_FALSE(audio_device_->AGC());
}
}
virtual ~AudioDeviceTest() {
if (audio_device_) {
EXPECT_EQ(0, audio_device_->Terminate());
}
}
bool requirements_satisfied() const { return requirements_satisfied_; }
rtc::Event* event() { return &event_; }
const rtc::scoped_refptr<AudioDeviceModule>& audio_device() const {
return audio_device_;
}
void StartPlayout() {
EXPECT_FALSE(audio_device()->Playing());
EXPECT_EQ(0, audio_device()->InitPlayout());
EXPECT_TRUE(audio_device()->PlayoutIsInitialized());
EXPECT_EQ(0, audio_device()->StartPlayout());
EXPECT_TRUE(audio_device()->Playing());
}
void StopPlayout() {
EXPECT_EQ(0, audio_device()->StopPlayout());
EXPECT_FALSE(audio_device()->Playing());
EXPECT_FALSE(audio_device()->PlayoutIsInitialized());
}
void StartRecording() {
EXPECT_FALSE(audio_device()->Recording());
EXPECT_EQ(0, audio_device()->InitRecording());
EXPECT_TRUE(audio_device()->RecordingIsInitialized());
EXPECT_EQ(0, audio_device()->StartRecording());
EXPECT_TRUE(audio_device()->Recording());
}
void StopRecording() {
EXPECT_EQ(0, audio_device()->StopRecording());
EXPECT_FALSE(audio_device()->Recording());
EXPECT_FALSE(audio_device()->RecordingIsInitialized());
}
private:
bool requirements_satisfied_ = true;
rtc::Event event_;
rtc::scoped_refptr<AudioDeviceModule> audio_device_;
bool stereo_playout_ = false;
bool stereo_recording_ = false;
};
// Uses the test fixture to create, initialize and destruct the ADM.
TEST_F(AudioDeviceTest, ConstructDestruct) {}
TEST_F(AudioDeviceTest, InitTerminate) {
SKIP_TEST_IF_NOT(requirements_satisfied());
// Initialization is part of the test fixture.
EXPECT_TRUE(audio_device()->Initialized());
EXPECT_EQ(0, audio_device()->Terminate());
EXPECT_FALSE(audio_device()->Initialized());
}
// Tests Start/Stop playout without any registered audio callback.
TEST_F(AudioDeviceTest, StartStopPlayout) {
SKIP_TEST_IF_NOT(requirements_satisfied());
StartPlayout();
StopPlayout();
StartPlayout();
StopPlayout();
}
// Tests Start/Stop recording without any registered audio callback.
TEST_F(AudioDeviceTest, StartStopRecording) {
SKIP_TEST_IF_NOT(requirements_satisfied());
StartRecording();
StopRecording();
StartRecording();
StopRecording();
}
// Start playout and verify that the native audio layer starts asking for real
// audio samples to play out using the NeedMorePlayData() callback.
// Note that we can't add expectations on audio parameters in EXPECT_CALL
// since parameter are not provided in the each callback. We therefore test and
// verify the parameters in the fake audio transport implementation instead.
TEST_F(AudioDeviceTest, StartPlayoutVerifyCallbacks) {
SKIP_TEST_IF_NOT(requirements_satisfied());
MockAudioTransport mock(TransportType::kPlay);
mock.HandleCallbacks(event(), kNumCallbacks);
EXPECT_CALL(mock, NeedMorePlayData(_, _, _, _, NotNull(), _, _, _))
.Times(AtLeast(kNumCallbacks));
EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
StartPlayout();
event()->Wait(kTestTimeOutInMilliseconds);
StopPlayout();
}
// Start recording and verify that the native audio layer starts providing real
// audio samples using the RecordedDataIsAvailable() callback.
TEST_F(AudioDeviceTest, StartRecordingVerifyCallbacks) {
SKIP_TEST_IF_NOT(requirements_satisfied());
MockAudioTransport mock(TransportType::kRecord);
mock.HandleCallbacks(event(), kNumCallbacks);
EXPECT_CALL(mock, RecordedDataIsAvailable(NotNull(), _, _, _, _, Ge(0u), 0, _,
false, _))
.Times(AtLeast(kNumCallbacks));
EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
StartRecording();
event()->Wait(kTestTimeOutInMilliseconds);
StopRecording();
}
// Start playout and recording (full-duplex audio) and verify that audio is
// active in both directions.
TEST_F(AudioDeviceTest, StartPlayoutAndRecordingVerifyCallbacks) {
SKIP_TEST_IF_NOT(requirements_satisfied());
MockAudioTransport mock(TransportType::kPlayAndRecord);
mock.HandleCallbacks(event(), kNumCallbacks);
EXPECT_CALL(mock, NeedMorePlayData(_, _, _, _, NotNull(), _, _, _))
.Times(AtLeast(kNumCallbacks));
EXPECT_CALL(mock, RecordedDataIsAvailable(NotNull(), _, _, _, _, Ge(0u), 0, _,
false, _))
.Times(AtLeast(kNumCallbacks));
EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
StartPlayout();
StartRecording();
event()->Wait(kTestTimeOutInMilliseconds);
StopRecording();
StopPlayout();
}
} // namespace webrtc
<commit_msg>Ensures that audio device tests works when run through remote desktop<commit_after>/*
* Copyright (c) 2017 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include <cstring>
#include "webrtc/base/event.h"
#include "webrtc/base/logging.h"
#include "webrtc/base/scoped_ref_ptr.h"
#include "webrtc/modules/audio_device/audio_device_impl.h"
#include "webrtc/modules/audio_device/include/audio_device.h"
#include "webrtc/modules/audio_device/include/mock_audio_transport.h"
#include "webrtc/system_wrappers/include/sleep.h"
#include "webrtc/test/gmock.h"
#include "webrtc/test/gtest.h"
using ::testing::_;
using ::testing::AtLeast;
using ::testing::Ge;
using ::testing::Invoke;
using ::testing::NiceMock;
using ::testing::NotNull;
namespace webrtc {
namespace {
// Don't run these tests in combination with sanitizers.
#if !defined(ADDRESS_SANITIZER) && !defined(MEMORY_SANITIZER)
#define SKIP_TEST_IF_NOT(requirements_satisfied) \
do { \
if (!requirements_satisfied) { \
return; \
} \
} while (false)
#else
// Or if other audio-related requirements are not met.
#define SKIP_TEST_IF_NOT(requirements_satisfied) \
do { \
return; \
} while (false)
#endif
// Number of callbacks (input or output) the tests waits for before we set
// an event indicating that the test was OK.
static const size_t kNumCallbacks = 10;
// Max amount of time we wait for an event to be set while counting callbacks.
static const int kTestTimeOutInMilliseconds = 10 * 1000;
enum class TransportType {
kInvalid,
kPlay,
kRecord,
kPlayAndRecord,
};
} // namespace
// Mocks the AudioTransport object and proxies actions for the two callbacks
// (RecordedDataIsAvailable and NeedMorePlayData) to different implementations
// of AudioStreamInterface.
class MockAudioTransport : public test::MockAudioTransport {
public:
explicit MockAudioTransport(TransportType type) : type_(type) {}
~MockAudioTransport() {}
// Set default actions of the mock object. We are delegating to fake
// implementation where the number of callbacks is counted and an event
// is set after a certain number of callbacks. Audio parameters are also
// checked.
void HandleCallbacks(rtc::Event* event, int num_callbacks) {
event_ = event;
num_callbacks_ = num_callbacks;
if (play_mode()) {
ON_CALL(*this, NeedMorePlayData(_, _, _, _, _, _, _, _))
.WillByDefault(
Invoke(this, &MockAudioTransport::RealNeedMorePlayData));
}
if (rec_mode()) {
ON_CALL(*this, RecordedDataIsAvailable(_, _, _, _, _, _, _, _, _, _))
.WillByDefault(
Invoke(this, &MockAudioTransport::RealRecordedDataIsAvailable));
}
}
int32_t RealRecordedDataIsAvailable(const void* audio_buffer,
const size_t samples_per_channel,
const size_t bytes_per_frame,
const size_t channels,
const uint32_t sample_rate,
const uint32_t total_delay_ms,
const int32_t clock_drift,
const uint32_t current_mic_level,
const bool typing_status,
uint32_t& new_mic_level) {
EXPECT_TRUE(rec_mode()) << "No test is expecting these callbacks.";
LOG(INFO) << "+";
// Store audio parameters once in the first callback. For all other
// callbacks, verify that the provided audio parameters are maintained and
// that each callback corresponds to 10ms for any given sample rate.
if (!record_parameters_.is_complete()) {
record_parameters_.reset(sample_rate, channels, samples_per_channel);
} else {
EXPECT_EQ(samples_per_channel, record_parameters_.frames_per_buffer());
EXPECT_EQ(bytes_per_frame, record_parameters_.GetBytesPerFrame());
EXPECT_EQ(channels, record_parameters_.channels());
EXPECT_EQ(static_cast<int>(sample_rate),
record_parameters_.sample_rate());
EXPECT_EQ(samples_per_channel,
record_parameters_.frames_per_10ms_buffer());
}
rec_count_++;
// Signal the event after given amount of callbacks.
if (ReceivedEnoughCallbacks()) {
event_->Set();
}
return 0;
}
int32_t RealNeedMorePlayData(const size_t samples_per_channel,
const size_t bytes_per_frame,
const size_t channels,
const uint32_t sample_rate,
void* audio_buffer,
size_t& samples_per_channel_out,
int64_t* elapsed_time_ms,
int64_t* ntp_time_ms) {
EXPECT_TRUE(play_mode()) << "No test is expecting these callbacks.";
LOG(INFO) << "-";
// Store audio parameters once in the first callback. For all other
// callbacks, verify that the provided audio parameters are maintained and
// that each callback corresponds to 10ms for any given sample rate.
if (!playout_parameters_.is_complete()) {
playout_parameters_.reset(sample_rate, channels, samples_per_channel);
} else {
EXPECT_EQ(samples_per_channel, playout_parameters_.frames_per_buffer());
EXPECT_EQ(bytes_per_frame, playout_parameters_.GetBytesPerFrame());
EXPECT_EQ(channels, playout_parameters_.channels());
EXPECT_EQ(static_cast<int>(sample_rate),
playout_parameters_.sample_rate());
EXPECT_EQ(samples_per_channel,
playout_parameters_.frames_per_10ms_buffer());
}
play_count_++;
samples_per_channel_out = samples_per_channel;
// Fill the audio buffer with zeros to avoid disturbing audio.
const size_t num_bytes = samples_per_channel * bytes_per_frame;
std::memset(audio_buffer, 0, num_bytes);
// Signal the event after given amount of callbacks.
if (ReceivedEnoughCallbacks()) {
event_->Set();
}
return 0;
}
bool ReceivedEnoughCallbacks() {
bool recording_done = false;
if (rec_mode()) {
recording_done = rec_count_ >= num_callbacks_;
} else {
recording_done = true;
}
bool playout_done = false;
if (play_mode()) {
playout_done = play_count_ >= num_callbacks_;
} else {
playout_done = true;
}
return recording_done && playout_done;
}
bool play_mode() const {
return type_ == TransportType::kPlay ||
type_ == TransportType::kPlayAndRecord;
}
bool rec_mode() const {
return type_ == TransportType::kRecord ||
type_ == TransportType::kPlayAndRecord;
}
private:
TransportType type_ = TransportType::kInvalid;
rtc::Event* event_ = nullptr;
size_t num_callbacks_ = 0;
size_t play_count_ = 0;
size_t rec_count_ = 0;
AudioParameters playout_parameters_;
AudioParameters record_parameters_;
};
// AudioDeviceTest test fixture.
class AudioDeviceTest : public ::testing::Test {
protected:
AudioDeviceTest() : event_(false, false) {
#if !defined(ADDRESS_SANITIZER) && !defined(MEMORY_SANITIZER)
rtc::LogMessage::LogToDebug(rtc::LS_INFO);
// Add extra logging fields here if needed for debugging.
// rtc::LogMessage::LogTimestamps();
// rtc::LogMessage::LogThreads();
audio_device_ =
AudioDeviceModule::Create(0, AudioDeviceModule::kPlatformDefaultAudio);
EXPECT_NE(audio_device_.get(), nullptr);
AudioDeviceModule::AudioLayer audio_layer;
int got_platform_audio_layer =
audio_device_->ActiveAudioLayer(&audio_layer);
if (got_platform_audio_layer != 0 ||
audio_layer == AudioDeviceModule::kLinuxAlsaAudio) {
requirements_satisfied_ = false;
}
if (requirements_satisfied_) {
EXPECT_EQ(0, audio_device_->Init());
const int16_t num_playout_devices = audio_device_->PlayoutDevices();
const int16_t num_record_devices = audio_device_->RecordingDevices();
requirements_satisfied_ =
num_playout_devices > 0 && num_record_devices > 0;
}
#else
requirements_satisfied_ = false;
#endif
if (requirements_satisfied_) {
EXPECT_EQ(0, audio_device_->SetPlayoutDevice(0));
EXPECT_EQ(0, audio_device_->InitSpeaker());
EXPECT_EQ(0, audio_device_->SetRecordingDevice(0));
EXPECT_EQ(0, audio_device_->InitMicrophone());
EXPECT_EQ(0, audio_device_->StereoPlayoutIsAvailable(&stereo_playout_));
EXPECT_EQ(0, audio_device_->SetStereoPlayout(stereo_playout_));
// Avoid asking for input stereo support and always record in mono
// since asking can cause issues in combination with remote desktop.
// See https://bugs.chromium.org/p/webrtc/issues/detail?id=7397 for
// details.
EXPECT_EQ(0, audio_device_->SetStereoRecording(false));
EXPECT_EQ(0, audio_device_->SetAGC(false));
EXPECT_FALSE(audio_device_->AGC());
}
}
virtual ~AudioDeviceTest() {
if (audio_device_) {
EXPECT_EQ(0, audio_device_->Terminate());
}
}
bool requirements_satisfied() const { return requirements_satisfied_; }
rtc::Event* event() { return &event_; }
const rtc::scoped_refptr<AudioDeviceModule>& audio_device() const {
return audio_device_;
}
void StartPlayout() {
EXPECT_FALSE(audio_device()->Playing());
EXPECT_EQ(0, audio_device()->InitPlayout());
EXPECT_TRUE(audio_device()->PlayoutIsInitialized());
EXPECT_EQ(0, audio_device()->StartPlayout());
EXPECT_TRUE(audio_device()->Playing());
}
void StopPlayout() {
EXPECT_EQ(0, audio_device()->StopPlayout());
EXPECT_FALSE(audio_device()->Playing());
EXPECT_FALSE(audio_device()->PlayoutIsInitialized());
}
void StartRecording() {
EXPECT_FALSE(audio_device()->Recording());
EXPECT_EQ(0, audio_device()->InitRecording());
EXPECT_TRUE(audio_device()->RecordingIsInitialized());
EXPECT_EQ(0, audio_device()->StartRecording());
EXPECT_TRUE(audio_device()->Recording());
}
void StopRecording() {
EXPECT_EQ(0, audio_device()->StopRecording());
EXPECT_FALSE(audio_device()->Recording());
EXPECT_FALSE(audio_device()->RecordingIsInitialized());
}
private:
bool requirements_satisfied_ = true;
rtc::Event event_;
rtc::scoped_refptr<AudioDeviceModule> audio_device_;
bool stereo_playout_ = false;
};
// Uses the test fixture to create, initialize and destruct the ADM.
TEST_F(AudioDeviceTest, ConstructDestruct) {}
TEST_F(AudioDeviceTest, InitTerminate) {
SKIP_TEST_IF_NOT(requirements_satisfied());
// Initialization is part of the test fixture.
EXPECT_TRUE(audio_device()->Initialized());
EXPECT_EQ(0, audio_device()->Terminate());
EXPECT_FALSE(audio_device()->Initialized());
}
// Tests Start/Stop playout without any registered audio callback.
TEST_F(AudioDeviceTest, StartStopPlayout) {
SKIP_TEST_IF_NOT(requirements_satisfied());
StartPlayout();
StopPlayout();
StartPlayout();
StopPlayout();
}
// Tests Start/Stop recording without any registered audio callback.
TEST_F(AudioDeviceTest, StartStopRecording) {
SKIP_TEST_IF_NOT(requirements_satisfied());
StartRecording();
StopRecording();
StartRecording();
StopRecording();
}
// Start playout and verify that the native audio layer starts asking for real
// audio samples to play out using the NeedMorePlayData() callback.
// Note that we can't add expectations on audio parameters in EXPECT_CALL
// since parameter are not provided in the each callback. We therefore test and
// verify the parameters in the fake audio transport implementation instead.
TEST_F(AudioDeviceTest, StartPlayoutVerifyCallbacks) {
SKIP_TEST_IF_NOT(requirements_satisfied());
MockAudioTransport mock(TransportType::kPlay);
mock.HandleCallbacks(event(), kNumCallbacks);
EXPECT_CALL(mock, NeedMorePlayData(_, _, _, _, NotNull(), _, _, _))
.Times(AtLeast(kNumCallbacks));
EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
StartPlayout();
event()->Wait(kTestTimeOutInMilliseconds);
StopPlayout();
}
// Start recording and verify that the native audio layer starts providing real
// audio samples using the RecordedDataIsAvailable() callback.
TEST_F(AudioDeviceTest, StartRecordingVerifyCallbacks) {
SKIP_TEST_IF_NOT(requirements_satisfied());
MockAudioTransport mock(TransportType::kRecord);
mock.HandleCallbacks(event(), kNumCallbacks);
EXPECT_CALL(mock, RecordedDataIsAvailable(NotNull(), _, _, _, _, Ge(0u), 0, _,
false, _))
.Times(AtLeast(kNumCallbacks));
EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
StartRecording();
event()->Wait(kTestTimeOutInMilliseconds);
StopRecording();
}
// Start playout and recording (full-duplex audio) and verify that audio is
// active in both directions.
TEST_F(AudioDeviceTest, StartPlayoutAndRecordingVerifyCallbacks) {
SKIP_TEST_IF_NOT(requirements_satisfied());
MockAudioTransport mock(TransportType::kPlayAndRecord);
mock.HandleCallbacks(event(), kNumCallbacks);
EXPECT_CALL(mock, NeedMorePlayData(_, _, _, _, NotNull(), _, _, _))
.Times(AtLeast(kNumCallbacks));
EXPECT_CALL(mock, RecordedDataIsAvailable(NotNull(), _, _, _, _, Ge(0u), 0, _,
false, _))
.Times(AtLeast(kNumCallbacks));
EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
StartPlayout();
StartRecording();
event()->Wait(kTestTimeOutInMilliseconds);
StopRecording();
StopPlayout();
}
} // namespace webrtc
<|endoftext|>
|
<commit_before>
#include "CopierAstConsumer.h"
using namespace clang;
#include <fstream>
#include "FileUtils.h"
namespace typegrind {
CopierAstConsumer::CopierAstConsumer(clang::Rewriter*& rewriter, DirectoryMapper mapper,
AppConfig const& appConfig)
: AllocationASTConsumer(rewriter, appConfig), mapper(mapper) {}
void CopierAstConsumer::processRewriterData(clang::Rewriter*& rewriter) {
llvm::outs() << "processing!\n";
for (auto it = rewriter->buffer_begin(), end = rewriter->buffer_end(); it != end; ++it) {
const FileEntry* Entry = rewriter->getSourceMgr().getFileEntryForID(it->first);
if (Entry && Entry->isValid()) {
std::string originalFileName(Entry->getName());
std::string outputFileName;
if (!typegrind::file_utils::canonize_path(originalFileName, outputFileName)) {
llvm::errs() << "Error while processing entry: " << Entry->getName() << "\n";
return;
}
if (mapper.apply(outputFileName)) {
llvm::outs() << "Writing " << outputFileName << "\n";
if (!typegrind::file_utils::ensure_directory_exists(outputFileName)) {
llvm::errs() << "Error while processing entry: " << Entry->getName() << "\n";
return;
}
std::error_code ErrInfo;
llvm::raw_fd_ostream ofs(outputFileName.c_str(), ErrInfo, llvm::sys::fs::F_None);
it->second.write(ofs);
} else {
llvm::errs() << "File not found in mapping, ignoring: " << outputFileName << "\n";
}
}
}
delete rewriter;
rewriter = nullptr;
}
}
<commit_msg>removed debug comment<commit_after>
#include "CopierAstConsumer.h"
using namespace clang;
#include <fstream>
#include "FileUtils.h"
namespace typegrind {
CopierAstConsumer::CopierAstConsumer(clang::Rewriter*& rewriter, DirectoryMapper mapper,
AppConfig const& appConfig)
: AllocationASTConsumer(rewriter, appConfig), mapper(mapper) {}
void CopierAstConsumer::processRewriterData(clang::Rewriter*& rewriter) {
for (auto it = rewriter->buffer_begin(), end = rewriter->buffer_end(); it != end; ++it) {
const FileEntry* Entry = rewriter->getSourceMgr().getFileEntryForID(it->first);
if (Entry && Entry->isValid()) {
std::string originalFileName(Entry->getName());
std::string outputFileName;
if (!typegrind::file_utils::canonize_path(originalFileName, outputFileName)) {
llvm::errs() << "Error while processing entry: " << Entry->getName() << "\n";
return;
}
if (mapper.apply(outputFileName)) {
llvm::outs() << "Writing " << outputFileName << "\n";
if (!typegrind::file_utils::ensure_directory_exists(outputFileName)) {
llvm::errs() << "Error while processing entry: " << Entry->getName() << "\n";
return;
}
std::error_code ErrInfo;
llvm::raw_fd_ostream ofs(outputFileName.c_str(), ErrInfo, llvm::sys::fs::F_None);
it->second.write(ofs);
} else {
llvm::errs() << "File not found in mapping, ignoring: " << outputFileName << "\n";
}
}
}
delete rewriter;
rewriter = nullptr;
}
}
<|endoftext|>
|
<commit_before>/*
===========================================================================
Daemon GPL Source Code
Copyright (C) 1999-2010 id Software LLC, a ZeniMax Media company.
This file is part of the Daemon GPL Source Code (Daemon Source Code).
Daemon Source Code 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.
Daemon Source Code 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 Daemon Source Code. If not, see <http://www.gnu.org/licenses/>.
In addition, the Daemon Source Code is also subject to certain additional terms.
You should have received a copy of these additional terms immediately following the
terms and conditions of the GNU General Public License which accompanied the Daemon
Source Code. If not, please request a copy in writing from id Software at the address
below.
If you have questions concerning this license or the applicable additional terms, you
may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville,
Maryland 20850 USA.
===========================================================================
*/
/* Additional features that would be nice for this code:
* Only display <gamepath>/<file>, i.e., etpro/etpro-3_0_1.pk3 in the UI.
* Add server as referring URL
*/
#include "common/Common.h"
#ifdef __MINGW32__
#define CURL_STATICLIB
#endif
#include <curl/curl.h>
#include "common/FileSystem.h"
#include "qcommon/q_shared.h"
#include "qcommon/qcommon.h"
extern Log::Logger downloadLogger; // cl_download.cpp
extern Cvar::Cvar<int> cl_downloadCount; // cl_download.cpp
namespace {
class CurlDownload {
CURLM* multi_ = nullptr;
CURL* request_ = nullptr;
dlStatus_t status_ = dlStatus_t::DL_FAILED;
public:
CurlDownload(Str::StringRef url) {
multi_ = curl_multi_init();
if (!multi_) {
downloadLogger.Warn("curl_multi_init returned null");
return;
}
request_ = curl_easy_init();
if (!request_) {
downloadLogger.Warn( "curl_easy_init returned null" );
return;
}
if (!SetOptions(url)) {
return;
}
CURLMcode err = curl_multi_add_handle(multi_, request_);
if (err != CURLM_OK)
{
downloadLogger.Warn("curl_multi_add_handle error: %s", curl_multi_strerror(err));
curl_easy_cleanup(request_);
request_ = nullptr;
return;
}
status_ = dlStatus_t::DL_CONTINUE;
}
CurlDownload(CurlDownload&&) = delete; // Disallow copy construction and assignment (yes this is a move constructor)
void Advance() {
if (status_ != dlStatus_t::DL_CONTINUE) {
return;
}
int numRunningTransfers;
CURLMcode err = curl_multi_perform(multi_, &numRunningTransfers);
if (err != CURLM_OK) {
downloadLogger.Warn("curl_multi_perform error: %s", curl_multi_strerror(err));
status_ = dlStatus_t::DL_FAILED;
}
if (status_ != dlStatus_t::DL_CONTINUE) { // may be set by callback
return;
}
if (numRunningTransfers > 0) {
return;
}
CURLMsg* msg;
do {
int ignored;
msg = curl_multi_info_read(multi_, &ignored);
} while (msg && msg->msg != CURLMSG_DONE);
if (!msg) {
status_ = dlStatus_t::DL_FAILED;
downloadLogger.Warn("Unexpected lack of CURLMSG_DONE");
return;
}
if (msg->data.result != CURLE_OK) {
downloadLogger.Notice("Download request terminated with failure status '%s'", err);
status_ = dlStatus_t::DL_FAILED;
return;
}
long httpStatus = -1;
curl_easy_getinfo(request_, CURLINFO_RESPONSE_CODE, &httpStatus); // ignore return code and fail due to httpStatus = -1
if (httpStatus != 200) {
// We don't follow redirects, so report a failure if we get one
// (they're not considered an error for CURLOPT_FAILONERROR purposes).
downloadLogger.Notice("Download failed: returned HTTP %d", httpStatus);
status_ = dlStatus_t::DL_FAILED;
return;
}
status_ = dlStatus_t::DL_DONE;
}
dlStatus_t Status() {
return status_;
}
protected:
// return DL_CONTINUE to continue, DL_DONE or DL_FAILED to stop
virtual dlStatus_t WriteCallback(const char* data, size_t len) = 0;
virtual ~CurlDownload() {
if (request_) {
CURLMcode err = curl_multi_remove_handle(multi_, request_);
if (err != CURLM_OK) {
downloadLogger.Warn("curl_multi_remove_handle error: %s", curl_multi_strerror(err));
}
curl_easy_cleanup(request_);
}
if (multi_) {
CURLMcode err = curl_multi_cleanup(multi_);
if (err != CURLM_OK) {
downloadLogger.Warn("curl_multi_cleanup error: %s", curl_multi_strerror(err));
}
}
}
private:
static size_t LibcurlWriteCallback(char* data, size_t, size_t len, void* object) {
auto* download = static_cast<CurlDownload*>(object);
download->status_ = download->WriteCallback(data, len);
return download->status_ == dlStatus_t::DL_CONTINUE ? len : ~size_t(0);
}
bool SetOptions(Str::StringRef url) {
#define SETOPT(option, value) \
if (curl_easy_setopt(request_, option, value) != CURLE_OK) { \
downloadLogger.Warn("Setting " #option " failed"); \
return false; \
}
SETOPT( CURLOPT_USERAGENT, Str::Format( "%s %s", PRODUCT_NAME "/" PRODUCT_VERSION, curl_version() ).c_str() )
SETOPT( CURLOPT_REFERER, Str::Format("%s%s", URI_SCHEME, Cvar::GetValue("cl_currentServerIP")).c_str() )
SETOPT( CURLOPT_URL, url.c_str() )
SETOPT( CURLOPT_PROTOCOLS, long(CURLPROTO_HTTP) )
SETOPT( CURLOPT_WRITEFUNCTION, curl_write_callback(LibcurlWriteCallback) )
SETOPT( CURLOPT_WRITEDATA, static_cast<void*>(this) )
SETOPT( CURLOPT_FAILONERROR, 1L )
return true;
}
};
class FileDownload : public CurlDownload {
FS::File file_;
dlStatus_t WriteCallback(const char* data, size_t len) override {
try {
file_.Write(data, len);
} catch (std::system_error& e) {
downloadLogger.Notice("Error writing to download file: %s", e.what());
return dlStatus_t::DL_FAILED;
}
cl_downloadCount.Set(cl_downloadCount.Get() + len);
return dlStatus_t::DL_CONTINUE;
}
public:
FileDownload(Str::StringRef url, FS::File file) : CurlDownload(url), file_(std::move(file)) {}
};
// If servers could ask the client to download any URL, there would be a security issue: the URL
// could point to something on a private network that the server shouldn't have access to. Therefore,
// before an HTTP download commences, the client checks for a magic file named PAKSERVER in the same
// directory where the desired file is stored. If the file begins with the right magic string (we
// check only a prefix to avoid any fiddly newline issues), this is interpreted as permission
// Daemon clients to download anything from that directory.
//
// Note that this is the same issue addressed by the Same-Origin Policy in web browsers. In that
// model, CORS headers are used to give scripts permission to access resources. We couldn't really
// implement that here since there is no origin tracking of cgame binaries.
const Str::StringRef PAKSERVER_FILE_NAME = "PAKSERVER";
const Str::StringRef PAKSERVER_FILE_CONTENT_PREFIX = "ALLOW_UNRESTRICTED_DOWNLOAD";
class PakserverCheck : public CurlDownload {
Str::StringRef unmatchedPrefix_ = PAKSERVER_FILE_CONTENT_PREFIX;
dlStatus_t WriteCallback(const char* data, size_t len) override {
size_t n = std::min(len, unmatchedPrefix_.size());
if (0 != memcmp(unmatchedPrefix_.c_str(), data, n)) {
return dlStatus_t::DL_FAILED;
}
unmatchedPrefix_ = unmatchedPrefix_.suffix(n);
return unmatchedPrefix_.empty() ? dlStatus_t::DL_DONE : dlStatus_t::DL_CONTINUE;
}
public:
PakserverCheck(Str::StringRef url) : CurlDownload(url) {}
};
struct DownloadState {
Util::optional<PakserverCheck> pakserverCheck;
Util::optional<FileDownload> actualDownload;
std::string url;
std::string homepathPath; // should begin with pkg/
};
} // namespace
// initialize once
static int dl_initialized = 0;
static DownloadState download;
void DL_InitDownload()
{
if ( dl_initialized )
{
return;
}
/* Make sure curl has initialized, so the cleanup doesn't get confused */
if ( curl_global_init( CURL_GLOBAL_ALL ) == CURLE_OK )
{
downloadLogger.Debug( "Client download subsystem initialized" );
dl_initialized = 1;
}
else
{
downloadLogger.Warn( "Error initializing libcurl" );
}
}
// TODO: call this function whenever a download is cancelled
static void DL_StopDownload()
{
if (download.actualDownload)
{
download.actualDownload = Util::nullopt;
// TODO: kill temp file
}
download.~DownloadState();
new (&download) DownloadState();
}
/*
================
DL_Shutdown
================
*/
void DL_Shutdown()
{
if ( !dl_initialized )
{
return;
}
DL_StopDownload();
curl_global_cleanup();
dl_initialized = 0;
}
/*
===============
inspired from http://www.w3.org/Library/Examples/LoadToFile.c
setup the download, return once we have a connection
===============
*/
int DL_BeginDownload( const char *localName, const char *remoteName, int basePathLen )
{
DL_StopDownload();
DL_InitDownload();
if ( !dl_initialized )
{
return 0;
}
// This URL parsing code is naive as it doesn't consider the possibility of params,
// anchors, or whatever, but regardless of what comes out, it should do the job of
// preventing downloading things that shouldn't be accessed.
std::string urlDir = remoteName;
if (basePathLen < 2 || static_cast<size_t>(basePathLen) + 1 >= urlDir.size() || urlDir[basePathLen - 1] != '/') {
downloadLogger.Notice("Bad download base path specification");
return 0;
}
urlDir = urlDir.substr(0, basePathLen);
downloadLogger.Debug("Checking for PAKSERVER file in %s", urlDir);
download.pakserverCheck.emplace(urlDir + PAKSERVER_FILE_NAME);
download.url = remoteName;
download.homepathPath = localName;
Cvar_Set( "cl_downloadName", remoteName );
return 1;
}
static void StartRealDownload() {
FS::File file;
try {
file = FS::HomePath::OpenWrite(download.homepathPath);
} catch (std::system_error& e) {
downloadLogger.Notice( "DL_BeginDownload unable to open '%s' for writing: %s", download.homepathPath, e.what() );
return;
}
downloadLogger.Debug("Starting HTTP download of %s", download.url);
download.actualDownload.emplace(download.url, std::move(file));
}
// (maybe this should be CL_DL_DownloadLoop)
dlStatus_t DL_DownloadLoop()
{
if ( !download.pakserverCheck && !download.actualDownload )
{
downloadLogger.Warn( "DL_DownloadLoop: unexpected call with no active request" );
return dlStatus_t::DL_DONE;
}
if ( download.pakserverCheck )
{
download.pakserverCheck->Advance();
switch (download.pakserverCheck->Status()) {
case dlStatus_t::DL_CONTINUE:
return dlStatus_t::DL_CONTINUE;
case dlStatus_t::DL_DONE:
download.pakserverCheck = Util::nullopt;
StartRealDownload();
if (!download.actualDownload)
{
DL_StopDownload();
return dlStatus_t::DL_FAILED;
}
break;
case dlStatus_t::DL_FAILED:
DL_StopDownload();
downloadLogger.Notice("Download server failed PAKSERVER check");
return dlStatus_t::DL_FAILED;
}
}
download.actualDownload->Advance();
dlStatus_t status = download.actualDownload->Status();
if ( status != dlStatus_t::DL_CONTINUE )
{
DL_StopDownload();
}
return status;
}
<commit_msg>Fix curl error message<commit_after>/*
===========================================================================
Daemon GPL Source Code
Copyright (C) 1999-2010 id Software LLC, a ZeniMax Media company.
This file is part of the Daemon GPL Source Code (Daemon Source Code).
Daemon Source Code 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.
Daemon Source Code 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 Daemon Source Code. If not, see <http://www.gnu.org/licenses/>.
In addition, the Daemon Source Code is also subject to certain additional terms.
You should have received a copy of these additional terms immediately following the
terms and conditions of the GNU General Public License which accompanied the Daemon
Source Code. If not, please request a copy in writing from id Software at the address
below.
If you have questions concerning this license or the applicable additional terms, you
may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville,
Maryland 20850 USA.
===========================================================================
*/
/* Additional features that would be nice for this code:
* Only display <gamepath>/<file>, i.e., etpro/etpro-3_0_1.pk3 in the UI.
* Add server as referring URL
*/
#include "common/Common.h"
#ifdef __MINGW32__
#define CURL_STATICLIB
#endif
#include <curl/curl.h>
#include "common/FileSystem.h"
#include "qcommon/q_shared.h"
#include "qcommon/qcommon.h"
extern Log::Logger downloadLogger; // cl_download.cpp
extern Cvar::Cvar<int> cl_downloadCount; // cl_download.cpp
namespace {
class CurlDownload {
CURLM* multi_ = nullptr;
CURL* request_ = nullptr;
dlStatus_t status_ = dlStatus_t::DL_FAILED;
public:
CurlDownload(Str::StringRef url) {
multi_ = curl_multi_init();
if (!multi_) {
downloadLogger.Warn("curl_multi_init returned null");
return;
}
request_ = curl_easy_init();
if (!request_) {
downloadLogger.Warn( "curl_easy_init returned null" );
return;
}
if (!SetOptions(url)) {
return;
}
CURLMcode err = curl_multi_add_handle(multi_, request_);
if (err != CURLM_OK)
{
downloadLogger.Warn("curl_multi_add_handle error: %s", curl_multi_strerror(err));
curl_easy_cleanup(request_);
request_ = nullptr;
return;
}
status_ = dlStatus_t::DL_CONTINUE;
}
CurlDownload(CurlDownload&&) = delete; // Disallow copy construction and assignment (yes this is a move constructor)
void Advance() {
if (status_ != dlStatus_t::DL_CONTINUE) {
return;
}
int numRunningTransfers;
CURLMcode err = curl_multi_perform(multi_, &numRunningTransfers);
if (err != CURLM_OK) {
downloadLogger.Warn("curl_multi_perform error: %s", curl_multi_strerror(err));
status_ = dlStatus_t::DL_FAILED;
}
if (status_ != dlStatus_t::DL_CONTINUE) { // may be set by callback
return;
}
if (numRunningTransfers > 0) {
return;
}
CURLMsg* msg;
do {
int ignored;
msg = curl_multi_info_read(multi_, &ignored);
} while (msg && msg->msg != CURLMSG_DONE);
if (!msg) {
status_ = dlStatus_t::DL_FAILED;
downloadLogger.Warn("Unexpected lack of msg");
return;
}
if (msg->data.result != CURLE_OK) {
downloadLogger.Notice("Download request terminated with error: %s", curl_easy_strerror(msg->data.result));
status_ = dlStatus_t::DL_FAILED;
return;
}
long httpStatus = -1;
curl_easy_getinfo(request_, CURLINFO_RESPONSE_CODE, &httpStatus); // ignore return code and fail due to httpStatus = -1
if (httpStatus != 200) {
// We don't follow redirects, so report a failure if we get one
// (they're not considered an error for CURLOPT_FAILONERROR purposes).
downloadLogger.Notice("Download failed: returned HTTP %d", httpStatus);
status_ = dlStatus_t::DL_FAILED;
return;
}
status_ = dlStatus_t::DL_DONE;
}
dlStatus_t Status() {
return status_;
}
protected:
// return DL_CONTINUE to continue, DL_DONE or DL_FAILED to stop
virtual dlStatus_t WriteCallback(const char* data, size_t len) = 0;
virtual ~CurlDownload() {
if (request_) {
CURLMcode err = curl_multi_remove_handle(multi_, request_);
if (err != CURLM_OK) {
downloadLogger.Warn("curl_multi_remove_handle error: %s", curl_multi_strerror(err));
}
curl_easy_cleanup(request_);
}
if (multi_) {
CURLMcode err = curl_multi_cleanup(multi_);
if (err != CURLM_OK) {
downloadLogger.Warn("curl_multi_cleanup error: %s", curl_multi_strerror(err));
}
}
}
private:
static size_t LibcurlWriteCallback(char* data, size_t, size_t len, void* object) {
auto* download = static_cast<CurlDownload*>(object);
download->status_ = download->WriteCallback(data, len);
return download->status_ == dlStatus_t::DL_CONTINUE ? len : ~size_t(0);
}
bool SetOptions(Str::StringRef url) {
#define SETOPT(option, value) \
if (curl_easy_setopt(request_, option, value) != CURLE_OK) { \
downloadLogger.Warn("Setting " #option " failed"); \
return false; \
}
SETOPT( CURLOPT_USERAGENT, Str::Format( "%s %s", PRODUCT_NAME "/" PRODUCT_VERSION, curl_version() ).c_str() )
SETOPT( CURLOPT_REFERER, Str::Format("%s%s", URI_SCHEME, Cvar::GetValue("cl_currentServerIP")).c_str() )
SETOPT( CURLOPT_URL, url.c_str() )
SETOPT( CURLOPT_PROTOCOLS, long(CURLPROTO_HTTP) )
SETOPT( CURLOPT_WRITEFUNCTION, curl_write_callback(LibcurlWriteCallback) )
SETOPT( CURLOPT_WRITEDATA, static_cast<void*>(this) )
SETOPT( CURLOPT_FAILONERROR, 1L )
return true;
}
};
class FileDownload : public CurlDownload {
FS::File file_;
dlStatus_t WriteCallback(const char* data, size_t len) override {
try {
file_.Write(data, len);
} catch (std::system_error& e) {
downloadLogger.Notice("Error writing to download file: %s", e.what());
return dlStatus_t::DL_FAILED;
}
cl_downloadCount.Set(cl_downloadCount.Get() + len);
return dlStatus_t::DL_CONTINUE;
}
public:
FileDownload(Str::StringRef url, FS::File file) : CurlDownload(url), file_(std::move(file)) {}
};
// If servers could ask the client to download any URL, there would be a security issue: the URL
// could point to something on a private network that the server shouldn't have access to. Therefore,
// before an HTTP download commences, the client checks for a magic file named PAKSERVER in the same
// directory where the desired file is stored. If the file begins with the right magic string (we
// check only a prefix to avoid any fiddly newline issues), this is interpreted as permission
// Daemon clients to download anything from that directory.
//
// Note that this is the same issue addressed by the Same-Origin Policy in web browsers. In that
// model, CORS headers are used to give scripts permission to access resources. We couldn't really
// implement that here since there is no origin tracking of cgame binaries.
const Str::StringRef PAKSERVER_FILE_NAME = "PAKSERVER";
const Str::StringRef PAKSERVER_FILE_CONTENT_PREFIX = "ALLOW_UNRESTRICTED_DOWNLOAD";
class PakserverCheck : public CurlDownload {
Str::StringRef unmatchedPrefix_ = PAKSERVER_FILE_CONTENT_PREFIX;
dlStatus_t WriteCallback(const char* data, size_t len) override {
size_t n = std::min(len, unmatchedPrefix_.size());
if (0 != memcmp(unmatchedPrefix_.c_str(), data, n)) {
return dlStatus_t::DL_FAILED;
}
unmatchedPrefix_ = unmatchedPrefix_.suffix(n);
return unmatchedPrefix_.empty() ? dlStatus_t::DL_DONE : dlStatus_t::DL_CONTINUE;
}
public:
PakserverCheck(Str::StringRef url) : CurlDownload(url) {}
};
struct DownloadState {
Util::optional<PakserverCheck> pakserverCheck;
Util::optional<FileDownload> actualDownload;
std::string url;
std::string homepathPath; // should begin with pkg/
};
} // namespace
// initialize once
static int dl_initialized = 0;
static DownloadState download;
void DL_InitDownload()
{
if ( dl_initialized )
{
return;
}
/* Make sure curl has initialized, so the cleanup doesn't get confused */
if ( curl_global_init( CURL_GLOBAL_ALL ) == CURLE_OK )
{
downloadLogger.Debug( "Client download subsystem initialized" );
dl_initialized = 1;
}
else
{
downloadLogger.Warn( "Error initializing libcurl" );
}
}
// TODO: call this function whenever a download is cancelled
static void DL_StopDownload()
{
if (download.actualDownload)
{
download.actualDownload = Util::nullopt;
// TODO: kill temp file
}
download.~DownloadState();
new (&download) DownloadState();
}
/*
================
DL_Shutdown
================
*/
void DL_Shutdown()
{
if ( !dl_initialized )
{
return;
}
DL_StopDownload();
curl_global_cleanup();
dl_initialized = 0;
}
/*
===============
inspired from http://www.w3.org/Library/Examples/LoadToFile.c
setup the download, return once we have a connection
===============
*/
int DL_BeginDownload( const char *localName, const char *remoteName, int basePathLen )
{
DL_StopDownload();
DL_InitDownload();
if ( !dl_initialized )
{
return 0;
}
// This URL parsing code is naive as it doesn't consider the possibility of params,
// anchors, or whatever, but regardless of what comes out, it should do the job of
// preventing downloading things that shouldn't be accessed.
std::string urlDir = remoteName;
if (basePathLen < 2 || static_cast<size_t>(basePathLen) + 1 >= urlDir.size() || urlDir[basePathLen - 1] != '/') {
downloadLogger.Notice("Bad download base path specification");
return 0;
}
urlDir = urlDir.substr(0, basePathLen);
downloadLogger.Debug("Checking for PAKSERVER file in %s", urlDir);
download.pakserverCheck.emplace(urlDir + PAKSERVER_FILE_NAME);
download.url = remoteName;
download.homepathPath = localName;
Cvar_Set( "cl_downloadName", remoteName );
return 1;
}
static void StartRealDownload() {
FS::File file;
try {
file = FS::HomePath::OpenWrite(download.homepathPath);
} catch (std::system_error& e) {
downloadLogger.Notice( "DL_BeginDownload unable to open '%s' for writing: %s", download.homepathPath, e.what() );
return;
}
downloadLogger.Debug("Starting HTTP download of %s", download.url);
download.actualDownload.emplace(download.url, std::move(file));
}
// (maybe this should be CL_DL_DownloadLoop)
dlStatus_t DL_DownloadLoop()
{
if ( !download.pakserverCheck && !download.actualDownload )
{
downloadLogger.Warn( "DL_DownloadLoop: unexpected call with no active request" );
return dlStatus_t::DL_DONE;
}
if ( download.pakserverCheck )
{
download.pakserverCheck->Advance();
switch (download.pakserverCheck->Status()) {
case dlStatus_t::DL_CONTINUE:
return dlStatus_t::DL_CONTINUE;
case dlStatus_t::DL_DONE:
download.pakserverCheck = Util::nullopt;
StartRealDownload();
if (!download.actualDownload)
{
DL_StopDownload();
return dlStatus_t::DL_FAILED;
}
break;
case dlStatus_t::DL_FAILED:
DL_StopDownload();
downloadLogger.Notice("Download server failed PAKSERVER check");
return dlStatus_t::DL_FAILED;
}
}
download.actualDownload->Advance();
dlStatus_t status = download.actualDownload->Status();
if ( status != dlStatus_t::DL_CONTINUE )
{
DL_StopDownload();
}
return status;
}
<|endoftext|>
|
<commit_before>/* Copyright The kNet 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. */
/** @file LockFreePoolAllocatorTest.cpp
@brief Tests the thread safety and proper operation of the LockFreePoolAllocator structure. */
#include "kNet.h"
#include "kNet/LockFreePoolAllocator.h"
#include "kNet/Thread.h"
#include "tassert.h"
#include "kNet/DebugMemoryLeakCheck.h"
#include <iostream>
using namespace std;
using namespace kNet;
struct Foo : public PoolAllocatable<Foo>
{
int bar;
};
volatile bool wait = true;
const int numThreads = 20;
LockFreePoolAllocator<Foo> pool;
std::vector<Foo*> foos[numThreads];
void PoolThreadMain(Thread *me, int threadIndex)
{
while(wait)
{
if (me->ShouldQuit())
return;
}
int idx = threadIndex << 16;
while(!me->ShouldQuit())
{
if (rand()%2 || foos[threadIndex].size() == 0)
{
if (foos[threadIndex].size() < 100)
{
Foo *f = pool.New();
f->bar = ++idx;
foos[threadIndex].push_back(f);
}
}
else
{
Foo *f = foos[threadIndex].back();
f->bar = 0;
foos[threadIndex].pop_back();
pool.Free(f);
}
}
}
template<typename T>
bool VectorsIntersect(const std::vector<T> &a, const std::vector<T> &b)
{
if (a.size() == 0 || b.size() == 0)
return false;
vector<T>::const_iterator iA = a.begin();
vector<T>::const_iterator iB = b.begin();
while(iA != a.end() && iB != b.end())
{
if (*iA == *iB)
return true;
if (*iA < *iB)
++iA;
else
++iB;
}
return false;
}
void LockFreePoolAllocatorTest()
{
cout << "Starting LockFreePoolAllocatorTest.";
Thread testThreads[numThreads];
wait = true;
// Fire up all threads.
for(int i = 0; i < numThreads; ++i)
testThreads[i].RunFunc(PoolThreadMain, &testThreads[i], i);
wait = false;
Thread::Sleep(100);
for(int i = 0; i < numThreads; ++i)
testThreads[i].Stop();
for(int i = 0; i < numThreads; ++i)
std::sort(foos[i].begin(), foos[i].end());
for(int i = 0; i < numThreads; ++i)
for(int j = i+1; j < numThreads; ++j)
if (VectorsIntersect(foos[i], foos[j]))
{
cout << "!!";
i = numThreads;
j = numThreads;
break;
}
for(int i = 0; i < numThreads; ++i)
{
for(size_t j = 0; j < foos[i].size(); ++j)
delete foos[i][j];
foos[i].clear();
}
pool.UnsafeClearAll();
}
<commit_msg>Fix tests to compile on GCC.<commit_after>/* Copyright The kNet 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. */
/** @file LockFreePoolAllocatorTest.cpp
@brief Tests the thread safety and proper operation of the LockFreePoolAllocator structure. */
#include "kNet.h"
#include "kNet/LockFreePoolAllocator.h"
#include "kNet/Thread.h"
#include "tassert.h"
#include "kNet/DebugMemoryLeakCheck.h"
#include <iostream>
using namespace std;
using namespace kNet;
struct Foo : public PoolAllocatable<Foo>
{
int bar;
};
volatile bool wait = true;
const int numThreads = 20;
LockFreePoolAllocator<Foo> pool;
std::vector<Foo*> foos[numThreads];
void PoolThreadMain(Thread *me, int threadIndex)
{
while(wait)
{
if (me->ShouldQuit())
return;
}
int idx = threadIndex << 16;
while(!me->ShouldQuit())
{
if (rand()%2 || foos[threadIndex].size() == 0)
{
if (foos[threadIndex].size() < 100)
{
Foo *f = pool.New();
f->bar = ++idx;
foos[threadIndex].push_back(f);
}
}
else
{
Foo *f = foos[threadIndex].back();
f->bar = 0;
foos[threadIndex].pop_back();
pool.Free(f);
}
}
}
template<typename T>
bool VectorsIntersect(const std::vector<T> &a, const std::vector<T> &b)
{
if (a.size() == 0 || b.size() == 0)
return false;
typename vector<T>::const_iterator iA = a.begin();
typename vector<T>::const_iterator iB = b.begin();
while(iA != a.end() && iB != b.end())
{
if (*iA == *iB)
return true;
if (*iA < *iB)
++iA;
else
++iB;
}
return false;
}
void LockFreePoolAllocatorTest()
{
cout << "Starting LockFreePoolAllocatorTest.";
Thread testThreads[numThreads];
wait = true;
// Fire up all threads.
for(int i = 0; i < numThreads; ++i)
testThreads[i].RunFunc(PoolThreadMain, &testThreads[i], i);
wait = false;
Thread::Sleep(100);
for(int i = 0; i < numThreads; ++i)
testThreads[i].Stop();
for(int i = 0; i < numThreads; ++i)
std::sort(foos[i].begin(), foos[i].end());
for(int i = 0; i < numThreads; ++i)
for(int j = i+1; j < numThreads; ++j)
if (VectorsIntersect(foos[i], foos[j]))
{
cout << "!!";
i = numThreads;
j = numThreads;
break;
}
for(int i = 0; i < numThreads; ++i)
{
for(size_t j = 0; j < foos[i].size(); ++j)
delete foos[i][j];
foos[i].clear();
}
pool.UnsafeClearAll();
}
<|endoftext|>
|
<commit_before>/*
* DesktopMenuCallback.cpp
*
* Copyright (C) 2009-17 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include "DesktopMenuCallback.hpp"
#include <QDebug>
#include <QApplication>
#ifdef Q_OS_MAC
#include <ApplicationServices/ApplicationServices.h>
#endif
namespace rstudio {
namespace desktop {
MenuCallback::MenuCallback(QObject *parent) :
QObject(parent)
{
}
void MenuCallback::beginMainMenu()
{
pMainMenu_ = new QMenuBar();
}
void MenuCallback::beginMenu(QString label)
{
#ifdef Q_OS_MAC
if (label == QString::fromUtf8("&Help"))
{
pMainMenu_->addMenu(new WindowMenu(pMainMenu_));
}
#endif
auto* pMenu = new SubMenu(label, pMainMenu_);
pMenu->setSeparatorsCollapsible(true);
if (menuStack_.count() == 0)
pMainMenu_->addMenu(pMenu);
else
menuStack_.top()->addMenu(pMenu);
menuStack_.push(pMenu);
}
QAction* MenuCallback::addCustomAction(QString commandId,
QString label,
QString tooltip,
QKeySequence keySequence,
bool checkable)
{
QAction* pAction = nullptr;
#ifdef Q_OS_MAC
// On Mac, certain commands will be automatically moved to Application Menu by Qt. If we want them to also
// appear in RStudio menus, check for them here and return nullptr.
if (duplicateAppMenuAction(QString::fromUtf8("showAboutDialog"),
commandId, label, tooltip, keySequence, checkable))
{
return nullptr;
}
else if (duplicateAppMenuAction(QString::fromUtf8("quitSession"),
commandId, label, tooltip, keySequence, checkable))
{
return nullptr;
}
// If we want a command to not be automatically moved to Application Menu, include it here and return the
// created action.
pAction = duplicateAppMenuAction(QString::fromUtf8("buildToolsProjectSetup"),
commandId, label, tooltip, keySequence, checkable);
if (pAction)
return pAction;
#endif // Q_OS_MAC
if (commandId == QString::fromUtf8("zoomIn"))
{
pAction = menuStack_.top()->addAction(QIcon(),
label,
this,
SIGNAL(zoomIn()),
QKeySequence::ZoomIn);
}
else if (commandId == QString::fromUtf8("zoomOut"))
{
pAction = menuStack_.top()->addAction(QIcon(),
label,
this,
SIGNAL(zoomOut()),
QKeySequence::ZoomOut);
}
#ifdef Q_OS_LINUX
else if (commandId == QString::fromUtf8("nextTab"))
{
pAction = menuStack_.top()->addAction(QIcon(),
label,
this,
SLOT(actionInvoked()),
QKeySequence(Qt::CTRL +
Qt::Key_PageDown));
}
else if (commandId == QString::fromUtf8("previousTab"))
{
pAction = menuStack_.top()->addAction(QIcon(),
label,
this,
SLOT(actionInvoked()),
QKeySequence(Qt::CTRL +
Qt::Key_PageUp));
}
#endif
if (pAction != nullptr)
{
pAction->setData(commandId);
pAction->setToolTip(tooltip);
return pAction;
}
else
{
return nullptr;
}
}
QAction* MenuCallback::duplicateAppMenuAction(QString commandToDuplicate,
QString commandId,
QString label,
QString tooltip,
QKeySequence keySequence,
bool checkable)
{
QAction* pAction = nullptr;
if (commandId == commandToDuplicate)
{
pAction = new QAction(QIcon(), label);
pAction->setMenuRole(QAction::NoRole);
pAction->setData(commandId);
pAction->setToolTip(tooltip);
pAction->setShortcut(keySequence);
if (checkable)
pAction->setCheckable(true);
menuStack_.top()->addAction(pAction);
auto* pBinder = new MenuActionBinder(menuStack_.top(), pAction);
connect(pBinder, SIGNAL(manageCommand(QString, QAction * )), this, SIGNAL(manageCommand(QString, QAction * )));
connect(pAction, SIGNAL(triggered()), this, SLOT(actionInvoked()));
}
return pAction;
}
void MenuCallback::addCommand(QString commandId,
QString label,
QString tooltip,
QString shortcut,
bool checkable)
{
// replace instances of 'Cmd' with 'Ctrl' -- note that on macOS
// Qt automatically maps that to the Command key
shortcut.replace(QStringLiteral("Cmd"), QStringLiteral("Ctrl"));
QKeySequence keySequence(shortcut);
// some shortcuts (namely, the Edit shortcuts) don't have bindings on the client side.
// populate those here when discovered
if (commandId == QStringLiteral("cutDummy"))
{
keySequence = QKeySequence(QKeySequence::Cut);
}
else if (commandId == QStringLiteral("copyDummy"))
{
keySequence = QKeySequence(QKeySequence::Copy);
}
else if (commandId == QStringLiteral("pasteDummy"))
{
keySequence = QKeySequence(QKeySequence::Paste);
}
else if (commandId == QStringLiteral("undoDummy"))
{
keySequence = QKeySequence(QKeySequence::Undo);
}
else if (commandId == QStringLiteral("redoDummy"))
{
keySequence = QKeySequence(QKeySequence::Redo);
}
#ifndef Q_OS_MAC
if (shortcut.contains(QString::fromUtf8("\n")))
{
int value = (keySequence[0] & Qt::MODIFIER_MASK) + Qt::Key_Enter;
keySequence = QKeySequence(value);
}
#endif
// allow custom action handlers first shot
QAction* pAction = addCustomAction(commandId, label, tooltip, keySequence, checkable);
// if there was no custom handler then do stock command-id processing
if (pAction == nullptr)
{
pAction = menuStack_.top()->addAction(QIcon(),
label,
this,
SLOT(actionInvoked()),
keySequence);
pAction->setData(commandId);
pAction->setToolTip(tooltip);
if (checkable)
pAction->setCheckable(true);
auto * pBinder = new MenuActionBinder(menuStack_.top(), pAction);
connect(pBinder, SIGNAL(manageCommand(QString,QAction*)),
this, SIGNAL(manageCommand(QString,QAction*)));
}
// remember action for later
actions_[commandId] = pAction;
}
void MenuCallback::actionInvoked()
{
auto * action = qobject_cast<QAction*>(sender());
QString commandId = action->data().toString();
commandInvoked(commandId);
}
void MenuCallback::addSeparator()
{
if (menuStack_.count() > 0)
menuStack_.top()->addSeparator();
}
void MenuCallback::endMenu()
{
menuStack_.pop();
}
void MenuCallback::endMainMenu()
{
menuBarCompleted(pMainMenu_);
}
void MenuCallback::setCommandEnabled(QString commandId, bool enabled)
{
auto it = actions_.find(commandId);
if (it == actions_.end())
return;
it.value()->setEnabled(enabled);
}
void MenuCallback::setCommandVisible(QString commandId, bool visible)
{
auto it = actions_.find(commandId);
if (it == actions_.end())
return;
it.value()->setVisible(visible);
}
void MenuCallback::setCommandLabel(QString commandId, QString label)
{
auto it = actions_.find(commandId);
if (it == actions_.end())
return;
it.value()->setText(label);
}
void MenuCallback::setCommandChecked(QString commandId, bool checked)
{
auto it = actions_.find(commandId);
if (it == actions_.end())
return;
it.value()->setChecked(checked);
}
MenuActionBinder::MenuActionBinder(QMenu* pMenu, QAction* pAction) : QObject(pAction)
{
connect(pMenu, SIGNAL(aboutToShow()), this, SLOT(onShowMenu()));
connect(pMenu, SIGNAL(aboutToHide()), this, SLOT(onHideMenu()));
pAction_ = pAction;
keySequence_ = pAction->shortcut();
pAction->setShortcut(QKeySequence());
}
void MenuActionBinder::onShowMenu()
{
QString commandId = pAction_->data().toString();
pAction_->setShortcut(keySequence_);
}
void MenuActionBinder::onHideMenu()
{
pAction_->setShortcut(QKeySequence());
}
WindowMenu::WindowMenu(QWidget *parent) : QMenu(QString::fromUtf8("&Window"), parent)
{
pMinimize_ = addAction(QString::fromUtf8("Minimize"));
pMinimize_->setShortcut(QKeySequence(QString::fromUtf8("Meta+M")));
connect(pMinimize_, SIGNAL(triggered()),
this, SLOT(onMinimize()));
pZoom_ = addAction(QString::fromUtf8("Zoom"));
connect(pZoom_, SIGNAL(triggered()),
this, SLOT(onZoom()));
addSeparator();
pWindowPlaceholder_ = addAction(QString::fromUtf8("__PLACEHOLDER__"));
pWindowPlaceholder_->setVisible(false);
addSeparator();
pBringAllToFront_ = addAction(QString::fromUtf8("Bring All to Front"));
connect(pBringAllToFront_, SIGNAL(triggered()),
this, SLOT(onBringAllToFront()));
connect(this, SIGNAL(aboutToShow()),
this, SLOT(onAboutToShow()));
connect(this, SIGNAL(aboutToHide()),
this, SLOT(onAboutToHide()));
}
void WindowMenu::onMinimize()
{
QWidget* pWin = QApplication::activeWindow();
if (pWin)
{
pWin->setWindowState(Qt::WindowMinimized);
}
}
void WindowMenu::onZoom()
{
QWidget* pWin = QApplication::activeWindow();
if (pWin)
{
pWin->setWindowState(pWin->windowState() ^ Qt::WindowMaximized);
}
}
void WindowMenu::onBringAllToFront()
{
#ifdef Q_OS_MAC
CFURLRef appUrlRef = CFBundleCopyBundleURL(CFBundleGetMainBundle());
if (appUrlRef)
{
LSOpenCFURLRef(appUrlRef, nullptr);
CFRelease(appUrlRef);
}
#endif
}
void WindowMenu::onAboutToShow()
{
QWidget* win = QApplication::activeWindow();
pMinimize_->setEnabled(win);
pZoom_->setEnabled(win && win->maximumSize() != win->minimumSize());
pBringAllToFront_->setEnabled(win);
for (int i = windows_.size() - 1; i >= 0; i--)
{
QAction* pAction = windows_[i];
removeAction(pAction);
windows_.removeAt(i);
pAction->deleteLater();
}
QWidgetList topLevels = QApplication::topLevelWidgets();
for (auto pWindow : topLevels)
{
if (!pWindow->isVisible())
continue;
// construct with no parent (we free it manually)
QAction* pAction = new QAction(pWindow->windowTitle(), nullptr);
pAction->setData(QVariant::fromValue(pWindow));
pAction->setCheckable(true);
if (pWindow->isActiveWindow())
pAction->setChecked(true);
insertAction(pWindowPlaceholder_, pAction);
connect(pAction, SIGNAL(triggered()),
this, SLOT(showWindow()));
windows_.append(pAction);
}
}
void WindowMenu::onAboutToHide()
{
}
void WindowMenu::showWindow()
{
auto* pAction = qobject_cast<QAction*>(sender());
if (!pAction)
return;
auto* pWidget = pAction->data().value<QWidget*>();
if (!pWidget)
return;
if (pWidget->isMinimized())
pWidget->setWindowState(pWidget->windowState() & ~Qt::WindowMinimized);
pWidget->activateWindow();
}
} // namespace desktop
} // namespace rstudio
<commit_msg>render ctrl+based shortcuts in menus correctly on macos; fixes #2010<commit_after>/*
* DesktopMenuCallback.cpp
*
* Copyright (C) 2009-17 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include "DesktopMenuCallback.hpp"
#include <QDebug>
#include <QApplication>
#ifdef Q_OS_MAC
#include <ApplicationServices/ApplicationServices.h>
#endif
namespace rstudio {
namespace desktop {
MenuCallback::MenuCallback(QObject *parent) :
QObject(parent)
{
}
void MenuCallback::beginMainMenu()
{
pMainMenu_ = new QMenuBar();
}
void MenuCallback::beginMenu(QString label)
{
#ifdef Q_OS_MAC
if (label == QString::fromUtf8("&Help"))
{
pMainMenu_->addMenu(new WindowMenu(pMainMenu_));
}
#endif
auto* pMenu = new SubMenu(label, pMainMenu_);
pMenu->setSeparatorsCollapsible(true);
if (menuStack_.count() == 0)
pMainMenu_->addMenu(pMenu);
else
menuStack_.top()->addMenu(pMenu);
menuStack_.push(pMenu);
}
QAction* MenuCallback::addCustomAction(QString commandId,
QString label,
QString tooltip,
QKeySequence keySequence,
bool checkable)
{
QAction* pAction = nullptr;
#ifdef Q_OS_MAC
// On Mac, certain commands will be automatically moved to Application Menu by Qt. If we want them to also
// appear in RStudio menus, check for them here and return nullptr.
if (duplicateAppMenuAction(QString::fromUtf8("showAboutDialog"),
commandId, label, tooltip, keySequence, checkable))
{
return nullptr;
}
else if (duplicateAppMenuAction(QString::fromUtf8("quitSession"),
commandId, label, tooltip, keySequence, checkable))
{
return nullptr;
}
// If we want a command to not be automatically moved to Application Menu, include it here and return the
// created action.
pAction = duplicateAppMenuAction(QString::fromUtf8("buildToolsProjectSetup"),
commandId, label, tooltip, keySequence, checkable);
if (pAction)
return pAction;
#endif // Q_OS_MAC
if (commandId == QString::fromUtf8("zoomIn"))
{
pAction = menuStack_.top()->addAction(QIcon(),
label,
this,
SIGNAL(zoomIn()),
QKeySequence::ZoomIn);
}
else if (commandId == QString::fromUtf8("zoomOut"))
{
pAction = menuStack_.top()->addAction(QIcon(),
label,
this,
SIGNAL(zoomOut()),
QKeySequence::ZoomOut);
}
#ifdef Q_OS_LINUX
else if (commandId == QString::fromUtf8("nextTab"))
{
pAction = menuStack_.top()->addAction(QIcon(),
label,
this,
SLOT(actionInvoked()),
QKeySequence(Qt::CTRL +
Qt::Key_PageDown));
}
else if (commandId == QString::fromUtf8("previousTab"))
{
pAction = menuStack_.top()->addAction(QIcon(),
label,
this,
SLOT(actionInvoked()),
QKeySequence(Qt::CTRL +
Qt::Key_PageUp));
}
#endif
if (pAction != nullptr)
{
pAction->setData(commandId);
pAction->setToolTip(tooltip);
return pAction;
}
else
{
return nullptr;
}
}
QAction* MenuCallback::duplicateAppMenuAction(QString commandToDuplicate,
QString commandId,
QString label,
QString tooltip,
QKeySequence keySequence,
bool checkable)
{
QAction* pAction = nullptr;
if (commandId == commandToDuplicate)
{
pAction = new QAction(QIcon(), label);
pAction->setMenuRole(QAction::NoRole);
pAction->setData(commandId);
pAction->setToolTip(tooltip);
pAction->setShortcut(keySequence);
if (checkable)
pAction->setCheckable(true);
menuStack_.top()->addAction(pAction);
auto* pBinder = new MenuActionBinder(menuStack_.top(), pAction);
connect(pBinder, SIGNAL(manageCommand(QString, QAction * )), this, SIGNAL(manageCommand(QString, QAction * )));
connect(pAction, SIGNAL(triggered()), this, SLOT(actionInvoked()));
}
return pAction;
}
void MenuCallback::addCommand(QString commandId,
QString label,
QString tooltip,
QString shortcut,
bool checkable)
{
#ifdef Q_OS_MAC
// on macOS, replace instances of 'Ctrl' with 'Meta'; QKeySequence renders "Ctrl" using the
// macOS command symbol, but we want the menu to show the literal Ctrl symbol (^)
shortcut.replace(QStringLiteral("Ctrl"), QStringLiteral("Meta"));
#endif
// replace instances of 'Cmd' with 'Ctrl' -- note that on macOS
// Qt automatically maps that to the Command key
shortcut.replace(QStringLiteral("Cmd"), QStringLiteral("Ctrl"));
QKeySequence keySequence(shortcut);
// some shortcuts (namely, the Edit shortcuts) don't have bindings on the client side.
// populate those here when discovered
if (commandId == QStringLiteral("cutDummy"))
{
keySequence = QKeySequence(QKeySequence::Cut);
}
else if (commandId == QStringLiteral("copyDummy"))
{
keySequence = QKeySequence(QKeySequence::Copy);
}
else if (commandId == QStringLiteral("pasteDummy"))
{
keySequence = QKeySequence(QKeySequence::Paste);
}
else if (commandId == QStringLiteral("undoDummy"))
{
keySequence = QKeySequence(QKeySequence::Undo);
}
else if (commandId == QStringLiteral("redoDummy"))
{
keySequence = QKeySequence(QKeySequence::Redo);
}
#ifndef Q_OS_MAC
if (shortcut.contains(QString::fromUtf8("\n")))
{
int value = (keySequence[0] & Qt::MODIFIER_MASK) + Qt::Key_Enter;
keySequence = QKeySequence(value);
}
#endif
// allow custom action handlers first shot
QAction* pAction = addCustomAction(commandId, label, tooltip, keySequence, checkable);
// if there was no custom handler then do stock command-id processing
if (pAction == nullptr)
{
pAction = menuStack_.top()->addAction(QIcon(),
label,
this,
SLOT(actionInvoked()),
keySequence);
pAction->setData(commandId);
pAction->setToolTip(tooltip);
if (checkable)
pAction->setCheckable(true);
auto * pBinder = new MenuActionBinder(menuStack_.top(), pAction);
connect(pBinder, SIGNAL(manageCommand(QString,QAction*)),
this, SIGNAL(manageCommand(QString,QAction*)));
}
// remember action for later
actions_[commandId] = pAction;
}
void MenuCallback::actionInvoked()
{
auto * action = qobject_cast<QAction*>(sender());
QString commandId = action->data().toString();
commandInvoked(commandId);
}
void MenuCallback::addSeparator()
{
if (menuStack_.count() > 0)
menuStack_.top()->addSeparator();
}
void MenuCallback::endMenu()
{
menuStack_.pop();
}
void MenuCallback::endMainMenu()
{
menuBarCompleted(pMainMenu_);
}
void MenuCallback::setCommandEnabled(QString commandId, bool enabled)
{
auto it = actions_.find(commandId);
if (it == actions_.end())
return;
it.value()->setEnabled(enabled);
}
void MenuCallback::setCommandVisible(QString commandId, bool visible)
{
auto it = actions_.find(commandId);
if (it == actions_.end())
return;
it.value()->setVisible(visible);
}
void MenuCallback::setCommandLabel(QString commandId, QString label)
{
auto it = actions_.find(commandId);
if (it == actions_.end())
return;
it.value()->setText(label);
}
void MenuCallback::setCommandChecked(QString commandId, bool checked)
{
auto it = actions_.find(commandId);
if (it == actions_.end())
return;
it.value()->setChecked(checked);
}
MenuActionBinder::MenuActionBinder(QMenu* pMenu, QAction* pAction) : QObject(pAction)
{
connect(pMenu, SIGNAL(aboutToShow()), this, SLOT(onShowMenu()));
connect(pMenu, SIGNAL(aboutToHide()), this, SLOT(onHideMenu()));
pAction_ = pAction;
keySequence_ = pAction->shortcut();
pAction->setShortcut(QKeySequence());
}
void MenuActionBinder::onShowMenu()
{
QString commandId = pAction_->data().toString();
pAction_->setShortcut(keySequence_);
}
void MenuActionBinder::onHideMenu()
{
pAction_->setShortcut(QKeySequence());
}
WindowMenu::WindowMenu(QWidget *parent) : QMenu(QString::fromUtf8("&Window"), parent)
{
pMinimize_ = addAction(QString::fromUtf8("Minimize"));
pMinimize_->setShortcut(QKeySequence(QString::fromUtf8("Meta+M")));
connect(pMinimize_, SIGNAL(triggered()),
this, SLOT(onMinimize()));
pZoom_ = addAction(QString::fromUtf8("Zoom"));
connect(pZoom_, SIGNAL(triggered()),
this, SLOT(onZoom()));
addSeparator();
pWindowPlaceholder_ = addAction(QString::fromUtf8("__PLACEHOLDER__"));
pWindowPlaceholder_->setVisible(false);
addSeparator();
pBringAllToFront_ = addAction(QString::fromUtf8("Bring All to Front"));
connect(pBringAllToFront_, SIGNAL(triggered()),
this, SLOT(onBringAllToFront()));
connect(this, SIGNAL(aboutToShow()),
this, SLOT(onAboutToShow()));
connect(this, SIGNAL(aboutToHide()),
this, SLOT(onAboutToHide()));
}
void WindowMenu::onMinimize()
{
QWidget* pWin = QApplication::activeWindow();
if (pWin)
{
pWin->setWindowState(Qt::WindowMinimized);
}
}
void WindowMenu::onZoom()
{
QWidget* pWin = QApplication::activeWindow();
if (pWin)
{
pWin->setWindowState(pWin->windowState() ^ Qt::WindowMaximized);
}
}
void WindowMenu::onBringAllToFront()
{
#ifdef Q_OS_MAC
CFURLRef appUrlRef = CFBundleCopyBundleURL(CFBundleGetMainBundle());
if (appUrlRef)
{
LSOpenCFURLRef(appUrlRef, nullptr);
CFRelease(appUrlRef);
}
#endif
}
void WindowMenu::onAboutToShow()
{
QWidget* win = QApplication::activeWindow();
pMinimize_->setEnabled(win);
pZoom_->setEnabled(win && win->maximumSize() != win->minimumSize());
pBringAllToFront_->setEnabled(win);
for (int i = windows_.size() - 1; i >= 0; i--)
{
QAction* pAction = windows_[i];
removeAction(pAction);
windows_.removeAt(i);
pAction->deleteLater();
}
QWidgetList topLevels = QApplication::topLevelWidgets();
for (auto pWindow : topLevels)
{
if (!pWindow->isVisible())
continue;
// construct with no parent (we free it manually)
QAction* pAction = new QAction(pWindow->windowTitle(), nullptr);
pAction->setData(QVariant::fromValue(pWindow));
pAction->setCheckable(true);
if (pWindow->isActiveWindow())
pAction->setChecked(true);
insertAction(pWindowPlaceholder_, pAction);
connect(pAction, SIGNAL(triggered()),
this, SLOT(showWindow()));
windows_.append(pAction);
}
}
void WindowMenu::onAboutToHide()
{
}
void WindowMenu::showWindow()
{
auto* pAction = qobject_cast<QAction*>(sender());
if (!pAction)
return;
auto* pWidget = pAction->data().value<QWidget*>();
if (!pWidget)
return;
if (pWidget->isMinimized())
pWidget->setWindowState(pWidget->windowState() & ~Qt::WindowMinimized);
pWidget->activateWindow();
}
} // namespace desktop
} // namespace rstudio
<|endoftext|>
|
<commit_before>#ifndef ENTT_ENTITY_VIEW_PACK_HPP
#define ENTT_ENTITY_VIEW_PACK_HPP
#include <tuple>
#include <type_traits>
#include <utility>
#include "../core/type_traits.hpp"
#include "fwd.hpp"
#include "utility.hpp"
namespace entt {
/**
* @brief View pack.
*
* The view pack allows users to combine multiple views into a single iterable
* object, while also giving them full control over which view should lead the
* iteration.<br/>
* This class returns all and only the entities present in all views. Its
* intended primary use is for custom storage and views, but it can also be very
* convenient in everyday use.
*
* @tparam View Type of the leading view of the pack.
* @tparam Other Types of all other views of the pack.
*/
template<typename View, typename... Other>
class view_pack {
using common_entity_type = std::common_type_t<typename View::entity_type, typename Other::entity_type...>;
class view_pack_iterator {
friend class view_pack<View, Other...>;
using underlying_iterator = typename View::iterator;
view_pack_iterator(underlying_iterator from, underlying_iterator to, const std::tuple<View, Other...> &ref) ENTT_NOEXCEPT
: it{from},
last{to},
pack{std::get<Other>(ref)...}
{
if(it != last && !valid()) {
++(*this);
}
}
[[nodiscard]] bool valid() const {
const auto entity = *it;
return (std::get<Other>(pack).contains(entity) && ...);
}
public:
using difference_type = typename std::iterator_traits<underlying_iterator>::difference_type;
using value_type = decltype(*std::declval<underlying_iterator>());
using pointer = void;
using reference = value_type;
using iterator_category = std::input_iterator_tag;
view_pack_iterator & operator++() ENTT_NOEXCEPT {
while(++it != last && !valid());
return *this;
}
view_pack_iterator operator++(int) ENTT_NOEXCEPT {
view_pack_iterator orig = *this;
return ++(*this), orig;
}
[[nodiscard]] reference operator*() const {
return *it;
}
[[nodiscard]] bool operator==(const view_pack_iterator &other) const ENTT_NOEXCEPT {
return other.it == it;
}
[[nodiscard]] bool operator!=(const view_pack_iterator &other) const ENTT_NOEXCEPT {
return !(*this == other);
}
private:
underlying_iterator it;
const underlying_iterator last;
const std::tuple<Other...> pack;
};
class iterable_view_pack {
friend class view_pack<View, Other...>;
using iterable_view = decltype(std::declval<View>().each());
class iterable_view_pack_iterator {
friend class iterable_view_pack;
using underlying_iterator = typename iterable_view::iterator;
iterable_view_pack_iterator(underlying_iterator from, underlying_iterator to, const std::tuple<Other...> &ref) ENTT_NOEXCEPT
: it{from},
last{to},
pack{ref}
{
if(it != last && !valid()) {
++(*this);
}
}
[[nodiscard]] bool valid() const {
const auto entity = std::get<0>(*it);
return (std::get<Other>(pack).contains(entity) && ...);
}
public:
using difference_type = typename std::iterator_traits<underlying_iterator>::difference_type;
using value_type = decltype(std::tuple_cat(*std::declval<underlying_iterator>(), std::declval<Other>().get({})...));
using pointer = void;
using reference = value_type;
using iterator_category = std::input_iterator_tag;
iterable_view_pack_iterator & operator++() ENTT_NOEXCEPT {
while(++it != last && !valid());
return *this;
}
iterable_view_pack_iterator operator++(int) ENTT_NOEXCEPT {
iterable_view_pack_iterator orig = *this;
return ++(*this), orig;
}
[[nodiscard]] reference operator*() const {
const auto curr = *it;
return std::tuple_cat(curr, std::get<Other>(pack).get(std::get<0>(curr))...);
}
[[nodiscard]] bool operator==(const iterable_view_pack_iterator &other) const ENTT_NOEXCEPT {
return other.it == it;
}
[[nodiscard]] bool operator!=(const iterable_view_pack_iterator &other) const ENTT_NOEXCEPT {
return !(*this == other);
}
private:
underlying_iterator it;
const underlying_iterator last;
const std::tuple<Other...> pack;
};
iterable_view_pack(const std::tuple<View, Other...> &ref)
: iterable{std::get<View>(ref).each()},
pack{std::get<Other>(ref)...}
{}
public:
using iterator = iterable_view_pack_iterator;
[[nodiscard]] iterator begin() const ENTT_NOEXCEPT {
return { iterable.begin(), iterable.end(), pack };
}
[[nodiscard]] iterator end() const ENTT_NOEXCEPT {
return { iterable.end(), iterable.end(), pack };
}
private:
iterable_view iterable;
std::tuple<Other...> pack;
};
public:
/*! @brief Underlying entity identifier. */
using entity_type = common_entity_type;
/*! @brief Input iterator type. */
using iterator = view_pack_iterator;
/**
* @brief Constructs a pack from a bunch of views.
* @param view A reference to the leading view for the pack.
* @param other References to the other views to use to construct the pack.
*/
view_pack(const View &view, const Other &... other)
: pack{view, other...}
{}
/**
* @brief Returns an iterator to the first entity of the pack.
*
* The returned iterator points to the first entity of the pack. If the pack
* is empty, the returned iterator will be equal to `end()`.
*
* @note
* Iterators stay true to the order imposed by the first view of the pack.
*
* @return An iterator to the first entity of the pack.
*/
[[nodiscard]] iterator begin() const ENTT_NOEXCEPT {
return { std::get<View>(pack).begin(), std::get<View>(pack).end(), pack };
}
/**
* @brief Returns an iterator that is past the last entity of the pack.
*
* The returned iterator points to the entity following the last entity of
* the pack. Attempting to dereference the returned iterator results in
* undefined behavior.
*
* @note
* Iterators stay true to the order imposed by the first view of the pack.
*
* @return An iterator to the entity following the last entity of the pack.
*/
[[nodiscard]] iterator end() const ENTT_NOEXCEPT {
return { std::get<View>(pack).end(), std::get<View>(pack).end(), pack };
}
/**
* @brief Iterates entities and components and applies the given function
* object to them.
*
* The function object is invoked for each entity. It is provided with the
* entity itself and a set of references to non-empty components. The
* _constness_ of the components is as requested.<br/>
* The signature of the function must be equivalent to one of the following
* forms:
*
* @code{.cpp}
* void(const entity_type, Type &...);
* void(Type &...);
* @endcode
*
* @note
* Empty types aren't explicitly instantiated and therefore they are never
* returned during iterations.
*
* @tparam Func Type of the function object to invoke.
* @param func A valid function object.
*/
template<typename Func>
void each(Func func) const {
for(const auto value: std::get<View>(pack).each()) {
const auto entity = std::get<0>(value);
if((std::get<Other>(pack).contains(entity) && ...)) {
if constexpr(is_applicable_v<Func, decltype(std::tuple_cat(value, std::get<Other>(pack).get(entity)...))>) {
std::apply(func, std::tuple_cat(value, std::get<Other>(pack).get(entity)...));
} else {
const auto args = std::apply([](const auto, auto &&... component) { return std::forward_as_tuple(component...); }, value);
std::apply(func, std::tuple_cat(args, std::get<Other>(pack).get(entity)...));
}
}
}
}
/**
* @brief Returns an iterable object to use to _visit_ the pack.
*
* The iterable object returns tuples that contain the current entity and a
* set of references to its non-empty components. The _constness_ of the
* components is as requested.
*
* @note
* Empty types aren't explicitly instantiated and therefore they are never
* returned during iterations.
*
* @return An iterable object to use to _visit_ the pack.
*/
[[nodiscard]] iterable_view_pack each() const ENTT_NOEXCEPT {
return pack;
}
/**
* @brief Returns a copy of the requested view from a pack.
* @tparam Type Type of the view to return.
* @return A copy of the requested view from the pack.
*/
template<typename Type>
operator Type() const ENTT_NOEXCEPT {
return std::get<Type>(pack);
}
/**
* @brief Appends a view to a pack.
* @tparam Args View template arguments.
* @param view A reference to a view to append to the pack.
* @return The extended pack.
*/
template<typename... Args>
[[nodiscard]] auto operator|(const basic_view<Args...> &view) const {
return std::make_from_tuple<view_pack<View, Other..., basic_view<Args...>>>(std::tuple_cat(pack, std::make_tuple(view)));
}
/**
* @brief Appends a pack and therefore all its views to another pack.
* @tparam Pack Types of views of the pack to append.
* @param other A reference to the pack to append.
* @return The extended pack.
*/
template<typename... Pack>
[[nodiscard]] auto operator|(const view_pack<Pack...> &other) const {
return std::make_from_tuple<view_pack<View, Other..., Pack...>>(std::tuple_cat(pack, std::make_tuple(static_cast<Pack>(other)...)));
}
private:
std::tuple<View, Other...> pack;
};
/**
* @brief Combines two views in a pack.
* @tparam Args Template arguments of the first view.
* @tparam Other Template arguments of the second view.
* @param lhs A reference to the first view with which to create the pack.
* @param rhs A reference to the second view with which to create the pack.
* @return A pack that combines the two views in a single iterable object.
*/
template<typename... Args, typename... Other>
[[nodiscard]] auto operator|(const basic_view<Args...> &lhs, const basic_view<Other...> &rhs) {
return view_pack{lhs, rhs};
}
/**
* @brief Combines a view with a pack.
* @tparam Args View template arguments.
* @tparam Pack Types of views of the pack.
* @param view A reference to the view to combine with the pack.
* @param pack A reference to the pack to combine with the view.
* @return The extended pack.
*/
template<typename... Args, typename... Pack>
[[nodiscard]] auto operator|(const basic_view<Args...> &view, const view_pack<Pack...> &pack) {
return view_pack{view} | pack;
}
}
#endif
<commit_msg>view_pack: minor changes<commit_after>#ifndef ENTT_ENTITY_VIEW_PACK_HPP
#define ENTT_ENTITY_VIEW_PACK_HPP
#include <tuple>
#include <type_traits>
#include <utility>
#include "../core/type_traits.hpp"
#include "fwd.hpp"
#include "utility.hpp"
namespace entt {
/**
* @brief View pack.
*
* The view pack allows users to combine multiple views into a single iterable
* object, while also giving them full control over which view should lead the
* iteration.<br/>
* This class returns all and only the entities present in all views. Its
* intended primary use is for custom storage and views, but it can also be very
* convenient in everyday use.
*
* @tparam View Type of the leading view of the pack.
* @tparam Other Types of all other views of the pack.
*/
template<typename View, typename... Other>
class view_pack {
using common_entity_type = std::common_type_t<typename View::entity_type, typename Other::entity_type...>;
class view_pack_iterator {
friend class view_pack<View, Other...>;
using underlying_iterator = typename View::iterator;
view_pack_iterator(underlying_iterator from, underlying_iterator to, const std::tuple<View, Other...> &ref) ENTT_NOEXCEPT
: it{from},
last{to},
pack{std::get<Other>(ref)...}
{
if(it != last && !valid()) {
++(*this);
}
}
[[nodiscard]] bool valid() const {
const auto entity = *it;
return (std::get<Other>(pack).contains(entity) && ...);
}
public:
using difference_type = typename std::iterator_traits<underlying_iterator>::difference_type;
using value_type = decltype(*std::declval<underlying_iterator>());
using pointer = void;
using reference = value_type;
using iterator_category = std::input_iterator_tag;
view_pack_iterator & operator++() ENTT_NOEXCEPT {
while(++it != last && !valid());
return *this;
}
view_pack_iterator operator++(int) ENTT_NOEXCEPT {
view_pack_iterator orig = *this;
return ++(*this), orig;
}
[[nodiscard]] reference operator*() const {
return *it;
}
[[nodiscard]] bool operator==(const view_pack_iterator &other) const ENTT_NOEXCEPT {
return other.it == it;
}
[[nodiscard]] bool operator!=(const view_pack_iterator &other) const ENTT_NOEXCEPT {
return !(*this == other);
}
private:
underlying_iterator it;
const underlying_iterator last;
const std::tuple<Other...> pack;
};
class iterable_view_pack {
friend class view_pack<View, Other...>;
using iterable_view = decltype(std::declval<View>().each());
class iterable_view_pack_iterator {
friend class iterable_view_pack;
using underlying_iterator = typename iterable_view::iterator;
iterable_view_pack_iterator(underlying_iterator from, underlying_iterator to, const std::tuple<Other...> &ref) ENTT_NOEXCEPT
: it{from},
last{to},
pack{ref}
{
if(it != last && !valid()) {
++(*this);
}
}
[[nodiscard]] bool valid() const {
const auto entity = std::get<0>(*it);
return (std::get<Other>(pack).contains(entity) && ...);
}
public:
using difference_type = typename std::iterator_traits<underlying_iterator>::difference_type;
using value_type = decltype(std::tuple_cat(*std::declval<underlying_iterator>(), std::declval<Other>().get({})...));
using pointer = void;
using reference = value_type;
using iterator_category = std::input_iterator_tag;
iterable_view_pack_iterator & operator++() ENTT_NOEXCEPT {
while(++it != last && !valid());
return *this;
}
iterable_view_pack_iterator operator++(int) ENTT_NOEXCEPT {
iterable_view_pack_iterator orig = *this;
return ++(*this), orig;
}
[[nodiscard]] reference operator*() const {
const auto curr = *it;
return std::tuple_cat(curr, std::get<Other>(pack).get(std::get<0>(curr))...);
}
[[nodiscard]] bool operator==(const iterable_view_pack_iterator &other) const ENTT_NOEXCEPT {
return other.it == it;
}
[[nodiscard]] bool operator!=(const iterable_view_pack_iterator &other) const ENTT_NOEXCEPT {
return !(*this == other);
}
private:
underlying_iterator it;
const underlying_iterator last;
const std::tuple<Other...> pack;
};
iterable_view_pack(const std::tuple<View, Other...> &ref)
: iterable{std::get<View>(ref).each()},
pack{std::get<Other>(ref)...}
{}
public:
using iterator = iterable_view_pack_iterator;
[[nodiscard]] iterator begin() const ENTT_NOEXCEPT {
return { iterable.begin(), iterable.end(), pack };
}
[[nodiscard]] iterator end() const ENTT_NOEXCEPT {
return { iterable.end(), iterable.end(), pack };
}
private:
iterable_view iterable;
std::tuple<Other...> pack;
};
public:
/*! @brief Underlying entity identifier. */
using entity_type = common_entity_type;
/*! @brief Input iterator type. */
using iterator = view_pack_iterator;
/**
* @brief Constructs a pack from a bunch of views.
* @param view A reference to the leading view for the pack.
* @param other References to the other views to use to construct the pack.
*/
view_pack(const View &view, const Other &... other)
: pack{view, other...}
{}
/**
* @brief Returns an iterator to the first entity of the pack.
*
* The returned iterator points to the first entity of the pack. If the pack
* is empty, the returned iterator will be equal to `end()`.
*
* @note
* Iterators stay true to the order imposed by the first view of the pack.
*
* @return An iterator to the first entity of the pack.
*/
[[nodiscard]] iterator begin() const ENTT_NOEXCEPT {
return { std::get<View>(pack).begin(), std::get<View>(pack).end(), pack };
}
/**
* @brief Returns an iterator that is past the last entity of the pack.
*
* The returned iterator points to the entity following the last entity of
* the pack. Attempting to dereference the returned iterator results in
* undefined behavior.
*
* @note
* Iterators stay true to the order imposed by the first view of the pack.
*
* @return An iterator to the entity following the last entity of the pack.
*/
[[nodiscard]] iterator end() const ENTT_NOEXCEPT {
return { std::get<View>(pack).end(), std::get<View>(pack).end(), pack };
}
/**
* @brief Iterates entities and components and applies the given function
* object to them.
*
* The function object is invoked for each entity. It is provided with the
* entity itself and a set of references to non-empty components. The
* _constness_ of the components is as requested.<br/>
* The signature of the function must be equivalent to one of the following
* forms:
*
* @code{.cpp}
* void(const entity_type, Type &...);
* void(Type &...);
* @endcode
*
* @note
* Empty types aren't explicitly instantiated and therefore they are never
* returned during iterations.
*
* @tparam Func Type of the function object to invoke.
* @param func A valid function object.
*/
template<typename Func>
void each(Func func) const {
for(const auto value: std::get<View>(pack).each()) {
const auto entity = std::get<0>(value);
if((std::get<Other>(pack).contains(entity) && ...)) {
if constexpr(is_applicable_v<Func, decltype(std::tuple_cat(value, std::get<Other>(pack).get(entity)...))>) {
std::apply(func, std::tuple_cat(value, std::get<Other>(pack).get(entity)...));
} else {
const auto args = std::apply([](const auto, auto &&... component) { return std::forward_as_tuple(std::forward<decltype(component)>(component)...); }, value);
std::apply(func, std::tuple_cat(args, std::get<Other>(pack).get(entity)...));
}
}
}
}
/**
* @brief Returns an iterable object to use to _visit_ the pack.
*
* The iterable object returns tuples that contain the current entity and a
* set of references to its non-empty components. The _constness_ of the
* components is as requested.
*
* @note
* Empty types aren't explicitly instantiated and therefore they are never
* returned during iterations.
*
* @return An iterable object to use to _visit_ the pack.
*/
[[nodiscard]] iterable_view_pack each() const ENTT_NOEXCEPT {
return pack;
}
/**
* @brief Returns a copy of the requested view from a pack.
* @tparam Type Type of the view to return.
* @return A copy of the requested view from the pack.
*/
template<typename Type>
operator Type() const ENTT_NOEXCEPT {
return std::get<Type>(pack);
}
/**
* @brief Appends a view to a pack.
* @tparam Args View template arguments.
* @param view A reference to a view to append to the pack.
* @return The extended pack.
*/
template<typename... Args>
[[nodiscard]] auto operator|(const basic_view<Args...> &view) const {
return std::make_from_tuple<view_pack<View, Other..., basic_view<Args...>>>(std::tuple_cat(pack, std::make_tuple(view)));
}
/**
* @brief Appends a pack and therefore all its views to another pack.
* @tparam Pack Types of views of the pack to append.
* @param other A reference to the pack to append.
* @return The extended pack.
*/
template<typename... Pack>
[[nodiscard]] auto operator|(const view_pack<Pack...> &other) const {
return std::make_from_tuple<view_pack<View, Other..., Pack...>>(std::tuple_cat(pack, std::make_tuple(static_cast<Pack>(other)...)));
}
private:
std::tuple<View, Other...> pack;
};
/**
* @brief Combines two views in a pack.
* @tparam Args Template arguments of the first view.
* @tparam Other Template arguments of the second view.
* @param lhs A reference to the first view with which to create the pack.
* @param rhs A reference to the second view with which to create the pack.
* @return A pack that combines the two views in a single iterable object.
*/
template<typename... Args, typename... Other>
[[nodiscard]] auto operator|(const basic_view<Args...> &lhs, const basic_view<Other...> &rhs) {
return view_pack{lhs, rhs};
}
/**
* @brief Combines a view with a pack.
* @tparam Args View template arguments.
* @tparam Pack Types of views of the pack.
* @param view A reference to the view to combine with the pack.
* @param pack A reference to the pack to combine with the view.
* @return The extended pack.
*/
template<typename... Args, typename... Pack>
[[nodiscard]] auto operator|(const basic_view<Args...> &view, const view_pack<Pack...> &pack) {
return view_pack{view} | pack;
}
}
#endif
<|endoftext|>
|
<commit_before>#include "astutil.h"
#include "expr.h"
#include "stmt.h"
#include "iterator.h"
IteratorInfo::IteratorInfo() :
seqType(NULL),
classType(NULL),
getHeadCursor(NULL),
getNextCursor(NULL),
isValidCursor(NULL),
getValue(NULL)
{}
static FnSymbol*
buildEmptyIteratorMethod(char* name, ClassType* ct) {
FnSymbol* fn = new FnSymbol(name);
fn->copyPragmas(fn);
fn->addPragma("auto ii");
fn->global = true;
fn->insertFormalAtTail(new ArgSymbol(INTENT_BLANK, "_mt", dtMethodToken));
fn->_this = new ArgSymbol(INTENT_BLANK, "this", ct);
fn->insertFormalAtTail(fn->_this);
return fn;
}
static VarSymbol* newTemp(FnSymbol* fn, Type* type, char* name = "_tmp") {
VarSymbol* var = new VarSymbol(name, type);
var->isCompilerTemp = true;
fn->insertAtHead(new DefExpr(var));
return var;
}
void prototypeIteratorClass(FnSymbol* fn) {
currentLineno = fn->lineno;
currentFilename = fn->filename;
IteratorInfo* ii = new IteratorInfo();
fn->iteratorInfo = ii;
ii->classType = new ClassType(CLASS_CLASS);
TypeSymbol* cts = new TypeSymbol(astr("_ic_", fn->name), ii->classType);
cts->addPragma("iterator class");
fn->defPoint->insertBefore(new DefExpr(cts));
Type* cursorType = dtInt[INT_SIZE_32];
ii->getHeadCursor = buildEmptyIteratorMethod("getHeadCursor", ii->classType);
ii->getHeadCursor->retType = cursorType;
ii->getNextCursor = buildEmptyIteratorMethod("getNextCursor", ii->classType);
ii->getNextCursor->retType = cursorType;
ii->getNextCursor->insertFormalAtTail(
new ArgSymbol(INTENT_BLANK, "cursor", cursorType));
ii->isValidCursor = buildEmptyIteratorMethod("isValidCursor?", ii->classType);
ii->isValidCursor->retType = dtBool;
ii->isValidCursor->insertFormalAtTail(
new ArgSymbol(INTENT_BLANK, "cursor", cursorType));
ii->getValue = buildEmptyIteratorMethod("getValue", ii->classType);
ii->getValue->retType = fn->retType;
ii->getValue->insertFormalAtTail(
new ArgSymbol(INTENT_BLANK, "cursor", cursorType));
fn->defPoint->insertBefore(new DefExpr(ii->getHeadCursor));
fn->defPoint->insertBefore(new DefExpr(ii->getNextCursor));
fn->defPoint->insertBefore(new DefExpr(ii->isValidCursor));
fn->defPoint->insertBefore(new DefExpr(ii->getValue));
ii->classType->defaultConstructor = fn;
ii->classType->scalarPromotionType = fn->retType;
fn->retType = ii->classType;
}
static void
buildGetNextCursor(FnSymbol* fn,
Vec<BaseAST*>& asts,
Map<Symbol*,Symbol*>& local2field,
Vec<Symbol*>& locals) {
IteratorInfo* ii = fn->iteratorInfo;
Symbol *iterator, *cursor, *t1;
Vec<Symbol*> labels;
iterator = ii->getNextCursor->getFormal(1);
cursor = ii->getNextCursor->getFormal(2);
for_alist(Expr, expr, fn->body->body)
ii->getNextCursor->insertAtTail(expr->remove());
Symbol* end = new LabelSymbol("_end");
// change yields to labels and gotos
int i = 2; // 1 = not started, 0 = finished
forv_Vec(BaseAST, ast, asts) {
if (CallExpr* call = dynamic_cast<CallExpr*>(ast)) {
if (call->isPrimitive(PRIMITIVE_YIELD)) {
call->insertBefore(new CallExpr(PRIMITIVE_MOVE, cursor, new_IntSymbol(i)));
call->insertBefore(new GotoStmt(goto_normal, end));
Symbol* label = new LabelSymbol(astr("_jump_", istr(i)));
call->insertBefore(new DefExpr(label));
labels.add(label);
call->remove();
i++;
} else if (call->isPrimitive(PRIMITIVE_RETURN)) {
call->insertBefore(new CallExpr(PRIMITIVE_MOVE, cursor, new_IntSymbol(0)));
call->remove(); // remove old return
}
}
}
ii->getNextCursor->insertAtTail(new DefExpr(end));
t1 = newTemp(ii->getNextCursor, ii->getNextCursor->retType);
ii->getNextCursor->insertAtTail(new CallExpr(PRIMITIVE_MOVE, t1, cursor));
ii->getNextCursor->insertAtTail(new CallExpr(PRIMITIVE_RETURN, t1));
// insert jump table at head of getNextCursor
i = 2;
t1 = newTemp(ii->getNextCursor, dtBool);
forv_Vec(Symbol, label, labels) {
ii->getNextCursor->insertAtHead(new CondStmt(new SymExpr(t1), new GotoStmt(goto_normal, label)));
ii->getNextCursor->insertAtHead(new CallExpr(PRIMITIVE_MOVE, t1, new CallExpr(PRIMITIVE_EQUAL, cursor, new_IntSymbol(i++))));
}
// load local variables from fields at return points and update
// fields when local variables change
forv_Vec(Symbol, local, locals) {
Symbol* field = local2field.get(local);
if (dynamic_cast<ArgSymbol*>(local)) {
Symbol* newlocal = newTemp(ii->getNextCursor, local->type, local->name);
ASTMap map;
map.put(local, newlocal);
update_symbols(ii->getNextCursor, &map);
local = newlocal;
}
ii->getNextCursor->insertAtHead(new CallExpr(PRIMITIVE_MOVE, local, new CallExpr(PRIMITIVE_GET_MEMBER, iterator, field)));
forv_Vec(SymExpr, se, local->defs) {
if (CallExpr* parent = dynamic_cast<CallExpr*>(se->parentExpr)) {
SymExpr* newuse = new SymExpr(local);
parent->getStmtExpr()->insertAfter(new CallExpr(PRIMITIVE_SET_MEMBER, iterator, field, newuse));
local->uses.add(newuse);
}
}
}
}
static void
buildGetHeadCursor(FnSymbol* fn) {
IteratorInfo* ii = fn->iteratorInfo;
Symbol *iterator, *t1;
iterator = ii->getHeadCursor->getFormal(1);
t1 = newTemp(ii->getHeadCursor, ii->getHeadCursor->retType);
ii->getHeadCursor->insertAtTail(new CallExpr(PRIMITIVE_MOVE, t1, new CallExpr(ii->getNextCursor, iterator, new_IntSymbol(1))));
ii->getHeadCursor->insertAtTail(new CallExpr(PRIMITIVE_RETURN, t1));
}
static void
buildIsValidCursor(FnSymbol* fn) {
IteratorInfo* ii = fn->iteratorInfo;
Symbol *cursor, *t1;
cursor = ii->isValidCursor->getFormal(2);
t1 = newTemp(ii->isValidCursor, dtBool);
ii->isValidCursor->insertAtTail(new CallExpr(PRIMITIVE_MOVE, t1, new CallExpr(PRIMITIVE_NOTEQUAL, cursor, new_IntSymbol(0))));
ii->isValidCursor->insertAtTail(new CallExpr(PRIMITIVE_RETURN, t1));
}
static void
buildGetValue(FnSymbol* fn, Symbol* value) {
IteratorInfo* ii = fn->iteratorInfo;
Symbol *iterator, *t1;
iterator = ii->getValue->getFormal(1);
t1 = newTemp(ii->getValue, ii->getValue->retType);
ii->getValue->insertAtTail(
new CallExpr(PRIMITIVE_MOVE, t1,
new CallExpr(PRIMITIVE_GET_MEMBER, iterator, value)));
ii->getValue->insertAtTail(new CallExpr(PRIMITIVE_RETURN, t1));
}
void lowerIterator(FnSymbol* fn) {
IteratorInfo* ii = fn->iteratorInfo;
currentLineno = fn->lineno;
currentFilename = fn->filename;
Vec<BaseAST*> asts;
collect_asts_postorder(&asts, fn);
// make fields for all local variables and arguments
// optimization note: only variables live at yield points are required
Map<Symbol*,Symbol*> local2field;
Vec<Symbol*> locals;
int i = 0;
forv_Vec(BaseAST, ast, asts) {
if (DefExpr* def = dynamic_cast<DefExpr*>(ast)) {
if (dynamic_cast<ArgSymbol*>(def->sym) || dynamic_cast<VarSymbol*>(def->sym)) {
if (def->sym->isReference) // references are short-lived and
// should never need to be stored
// in an iterator class (hopefully)
continue;
Symbol* local = def->sym;
Symbol* field =
new VarSymbol(astr("_", istr(i++), "_", local->name), local->type);
local2field.put(local, field);
locals.add(local);
ii->classType->fields->insertAtTail(new DefExpr(field));
}
}
}
Symbol* value = local2field.get(fn->getReturnSymbol());
buildGetNextCursor(fn, asts, local2field, locals);
buildGetHeadCursor(fn);
buildIsValidCursor(fn);
buildGetValue(fn, value);
// rebuild iterator function
fn->defPoint->remove();
fn->retType = ii->classType;
Symbol* t1 = newTemp(fn, ii->classType);
fn->insertAtTail(new CallExpr(PRIMITIVE_MOVE, t1, new CallExpr(PRIMITIVE_CHPL_ALLOC, ii->classType->symbol, new_StringSymbol("iterator class"))));
forv_Vec(Symbol, local, locals) {
Symbol* field = local2field.get(local);
if (dynamic_cast<ArgSymbol*>(local))
fn->insertAtTail(new CallExpr(PRIMITIVE_SET_MEMBER, t1, field, local));
}
fn->addPragma("first member sets");
fn->insertAtTail(new CallExpr(PRIMITIVE_RETURN, t1));
ii->getValue->defPoint->insertAfter(new DefExpr(fn));
}
<commit_msg>Specialized the iterator interface methods for iterators that have a stylized form consisting of a single for loop with a yield statement in that loop.<commit_after>#include "astutil.h"
#include "expr.h"
#include "stmt.h"
#include "iterator.h"
IteratorInfo::IteratorInfo() :
seqType(NULL),
classType(NULL),
getHeadCursor(NULL),
getNextCursor(NULL),
isValidCursor(NULL),
getValue(NULL)
{}
static FnSymbol*
buildEmptyIteratorMethod(char* name, ClassType* ct) {
FnSymbol* fn = new FnSymbol(name);
fn->copyPragmas(fn);
fn->addPragma("auto ii");
fn->global = true;
fn->insertFormalAtTail(new ArgSymbol(INTENT_BLANK, "_mt", dtMethodToken));
fn->_this = new ArgSymbol(INTENT_BLANK, "this", ct);
fn->insertFormalAtTail(fn->_this);
return fn;
}
static VarSymbol* newTemp(FnSymbol* fn, Type* type, char* name = "_tmp") {
VarSymbol* var = new VarSymbol(name, type);
var->isCompilerTemp = true;
fn->insertAtHead(new DefExpr(var));
return var;
}
void prototypeIteratorClass(FnSymbol* fn) {
currentLineno = fn->lineno;
currentFilename = fn->filename;
IteratorInfo* ii = new IteratorInfo();
fn->iteratorInfo = ii;
ii->classType = new ClassType(CLASS_CLASS);
TypeSymbol* cts = new TypeSymbol(astr("_ic_", fn->name), ii->classType);
cts->addPragma("iterator class");
fn->defPoint->insertBefore(new DefExpr(cts));
Type* cursorType = dtInt[INT_SIZE_32];
ii->getHeadCursor = buildEmptyIteratorMethod("getHeadCursor", ii->classType);
ii->getHeadCursor->retType = cursorType;
ii->getNextCursor = buildEmptyIteratorMethod("getNextCursor", ii->classType);
ii->getNextCursor->retType = cursorType;
ii->getNextCursor->insertFormalAtTail(
new ArgSymbol(INTENT_BLANK, "cursor", cursorType));
ii->isValidCursor = buildEmptyIteratorMethod("isValidCursor?", ii->classType);
ii->isValidCursor->retType = dtBool;
ii->isValidCursor->insertFormalAtTail(
new ArgSymbol(INTENT_BLANK, "cursor", cursorType));
ii->getValue = buildEmptyIteratorMethod("getValue", ii->classType);
ii->getValue->retType = fn->retType;
ii->getValue->insertFormalAtTail(
new ArgSymbol(INTENT_BLANK, "cursor", cursorType));
fn->defPoint->insertBefore(new DefExpr(ii->getHeadCursor));
fn->defPoint->insertBefore(new DefExpr(ii->getNextCursor));
fn->defPoint->insertBefore(new DefExpr(ii->isValidCursor));
fn->defPoint->insertBefore(new DefExpr(ii->getValue));
ii->classType->defaultConstructor = fn;
ii->classType->scalarPromotionType = fn->retType;
fn->retType = ii->classType;
}
static void
buildGetNextCursor(FnSymbol* fn,
Vec<BaseAST*>& asts,
Map<Symbol*,Symbol*>& local2field,
Vec<Symbol*>& locals) {
IteratorInfo* ii = fn->iteratorInfo;
Symbol *iterator, *cursor, *t1;
Vec<Symbol*> labels;
iterator = ii->getNextCursor->getFormal(1);
cursor = ii->getNextCursor->getFormal(2);
for_alist(Expr, expr, fn->body->body)
ii->getNextCursor->insertAtTail(expr->remove());
Symbol* end = new LabelSymbol("_end");
// change yields to labels and gotos
int i = 2; // 1 = not started, 0 = finished
forv_Vec(BaseAST, ast, asts) {
if (CallExpr* call = dynamic_cast<CallExpr*>(ast)) {
if (call->isPrimitive(PRIMITIVE_YIELD)) {
call->insertBefore(new CallExpr(PRIMITIVE_MOVE, cursor, new_IntSymbol(i)));
call->insertBefore(new GotoStmt(goto_normal, end));
Symbol* label = new LabelSymbol(astr("_jump_", istr(i)));
call->insertBefore(new DefExpr(label));
labels.add(label);
call->remove();
i++;
} else if (call->isPrimitive(PRIMITIVE_RETURN)) {
call->insertBefore(new CallExpr(PRIMITIVE_MOVE, cursor, new_IntSymbol(0)));
call->remove(); // remove old return
}
}
}
ii->getNextCursor->insertAtTail(new DefExpr(end));
t1 = newTemp(ii->getNextCursor, ii->getNextCursor->retType);
ii->getNextCursor->insertAtTail(new CallExpr(PRIMITIVE_MOVE, t1, cursor));
ii->getNextCursor->insertAtTail(new CallExpr(PRIMITIVE_RETURN, t1));
// insert jump table at head of getNextCursor
i = 2;
t1 = newTemp(ii->getNextCursor, dtBool);
forv_Vec(Symbol, label, labels) {
ii->getNextCursor->insertAtHead(new CondStmt(new SymExpr(t1), new GotoStmt(goto_normal, label)));
ii->getNextCursor->insertAtHead(new CallExpr(PRIMITIVE_MOVE, t1, new CallExpr(PRIMITIVE_EQUAL, cursor, new_IntSymbol(i++))));
}
// load local variables from fields at return points and update
// fields when local variables change
forv_Vec(Symbol, local, locals) {
Symbol* field = local2field.get(local);
if (dynamic_cast<ArgSymbol*>(local)) {
Symbol* newlocal = newTemp(ii->getNextCursor, local->type, local->name);
ASTMap map;
map.put(local, newlocal);
update_symbols(ii->getNextCursor, &map);
local = newlocal;
}
ii->getNextCursor->insertAtHead(new CallExpr(PRIMITIVE_MOVE, local, new CallExpr(PRIMITIVE_GET_MEMBER, iterator, field)));
forv_Vec(SymExpr, se, local->defs) {
if (CallExpr* parent = dynamic_cast<CallExpr*>(se->parentExpr)) {
SymExpr* newuse = new SymExpr(local);
parent->getStmtExpr()->insertAfter(new CallExpr(PRIMITIVE_SET_MEMBER, iterator, field, newuse));
local->uses.add(newuse);
}
}
}
}
static void
buildGetHeadCursor(FnSymbol* fn) {
IteratorInfo* ii = fn->iteratorInfo;
Symbol *iterator, *t1;
iterator = ii->getHeadCursor->getFormal(1);
t1 = newTemp(ii->getHeadCursor, ii->getHeadCursor->retType);
ii->getHeadCursor->insertAtTail(new CallExpr(PRIMITIVE_MOVE, t1, new CallExpr(ii->getNextCursor, iterator, new_IntSymbol(1))));
ii->getHeadCursor->insertAtTail(new CallExpr(PRIMITIVE_RETURN, t1));
}
static void
buildIsValidCursor(FnSymbol* fn) {
IteratorInfo* ii = fn->iteratorInfo;
Symbol *cursor, *t1;
cursor = ii->isValidCursor->getFormal(2);
t1 = newTemp(ii->isValidCursor, dtBool);
ii->isValidCursor->insertAtTail(new CallExpr(PRIMITIVE_MOVE, t1, new CallExpr(PRIMITIVE_NOTEQUAL, cursor, new_IntSymbol(0))));
ii->isValidCursor->insertAtTail(new CallExpr(PRIMITIVE_RETURN, t1));
}
static void
buildGetValue(FnSymbol* fn, Symbol* value) {
IteratorInfo* ii = fn->iteratorInfo;
Symbol *iterator, *t1;
iterator = ii->getValue->getFormal(1);
t1 = newTemp(ii->getValue, ii->getValue->retType);
ii->getValue->insertAtTail(
new CallExpr(PRIMITIVE_MOVE, t1,
new CallExpr(PRIMITIVE_GET_MEMBER, iterator, value)));
ii->getValue->insertAtTail(new CallExpr(PRIMITIVE_RETURN, t1));
}
//
// Determines that an iterator has a single loop with a single yield
// in it by checking the following conditions:
//
// 1. There is exactly one for-loop and no other loops.
// 2. The single for-loop is top-level to the function.
// 3. There is exactly one yield.
// 4. The single yield is top-level to the for-loop.
// 5. There are no goto statements.
//
// I believe these conditions can be relaxed.
//
static CallExpr*
isSingleLoopIterator(FnSymbol* fn, Vec<BaseAST*>& asts) {
BlockStmt* singleFor = NULL;
CallExpr* singleYield = NULL;
forv_Vec(BaseAST, ast, asts) {
if (CallExpr* call = dynamic_cast<CallExpr*>(ast)) {
if (call->isPrimitive(PRIMITIVE_YIELD)) {
if (singleYield) {
return NULL;
} else if (BlockStmt* block = dynamic_cast<BlockStmt*>(call->parentExpr)) {
if (block->loopInfo && block->loopInfo->isPrimitive(PRIMITIVE_LOOP_FOR)) {
singleYield = call;
} else {
return NULL;
}
} else {
return NULL;
}
}
} else if (BlockStmt* block = dynamic_cast<BlockStmt*>(ast)) {
if (block->loopInfo) {
if (singleFor) {
return NULL;
} else if (block->loopInfo->isPrimitive(PRIMITIVE_LOOP_FOR) &&
block->parentExpr == fn->body) {
singleFor = block;
} else {
return NULL;
}
}
} else if (ast->astType == STMT_GOTO) {
return NULL;
}
}
if (singleFor && singleYield)
return singleYield;
else
return NULL;
}
//
// Builds the iterator interface methods for a single loop iterator as
// determined by isSingleLoopIterator.
//
// A single loop iterator has the form:
//
// iterator foo() {
// BLOCK I
// for loop {
// BLOCK II
// yield statement
// BLOCK III
// }
// BLOCK IV
// }
//
static void
buildSingleLoopMethods(FnSymbol* fn,
Vec<BaseAST*>& asts,
Map<Symbol*,Symbol*>& local2field,
Vec<Symbol*>& locals,
Symbol* value,
CallExpr* yield) {
IteratorInfo* ii = fn->iteratorInfo;
BlockStmt* loop = dynamic_cast<BlockStmt*>(yield->parentExpr);
Symbol* headIterator = ii->getHeadCursor->getFormal(1);
Symbol* headCursor = newTemp(ii->getHeadCursor, ii->getHeadCursor->retType);
Symbol* nextIterator = ii->getNextCursor->getFormal(1);
Symbol* nextCursor = ii->getNextCursor->getFormal(2);
ASTMap headCopyMap; // copy map of iterator to getHeadCursor; note:
// there is no map for getNextCursor since the
// asts are moved (not copied) to getNextCursor
//
// add local variable defs to getNextCursor and getHeadCursor
//
forv_Vec(BaseAST, ast, asts) {
if (DefExpr* def = dynamic_cast<DefExpr*>(ast)) {
if (dynamic_cast<ArgSymbol*>(def->sym))
continue;
ii->getHeadCursor->insertAtHead(def->copy(&headCopyMap));
ii->getNextCursor->insertAtHead(def->remove());
}
}
//
// add BLOCK I to getHeadCursor method
//
for_alist(Expr, expr, fn->body->body) {
if (expr == loop)
break;
ii->getHeadCursor->insertAtTail(expr->copy(&headCopyMap));
expr->remove();
}
//
// add BLOCK III to getNextCursor method
//
bool postYield = false;
for_alist(Expr, expr, loop->body) {
if (!postYield) {
if (expr == yield)
postYield = true;
continue;
}
ii->getNextCursor->insertAtTail(expr->remove());
}
//
// add BLOCK II to conditional then clause for both getHeadCursor and
// getNextCursor methods; set cursor to 1
//
BlockStmt* headThen = new BlockStmt();
BlockStmt* nextThen = new BlockStmt();
for_alist(Expr, expr, loop->body) {
if (expr == yield)
break;
headThen->insertAtTail(expr->copy(&headCopyMap));
nextThen->insertAtTail(expr->remove());
}
headThen->insertAtTail(new CallExpr(PRIMITIVE_MOVE, headCursor, new_IntSymbol(1)));
nextThen->insertAtTail(new CallExpr(PRIMITIVE_MOVE, nextCursor, new_IntSymbol(1)));
//
// add BLOCK IV to conditional else clause for both getHeadCursor and
// getNextCursor methods; set cursor to 0
//
BlockStmt* headElse = new BlockStmt();
BlockStmt* nextElse = new BlockStmt();
loop->remove();
for_alist(Expr, expr, fn->body->body) {
if (!expr->next) // ignore return statement
break;
headElse->insertAtTail(expr->copy(&headCopyMap));
nextElse->insertAtTail(expr->remove());
}
headElse->insertAtTail(new CallExpr(PRIMITIVE_MOVE, headCursor, new_IntSymbol(0)));
nextElse->insertAtTail(new CallExpr(PRIMITIVE_MOVE, nextCursor, new_IntSymbol(0)));
//
// add conditional to getHeadCursor and getNextCursor methods
//
Expr* headCond = loop->loopInfo->get(1)->copy(&headCopyMap);
Expr* nextCond = loop->loopInfo->get(1)->remove();
ii->getHeadCursor->insertAtTail(new CondStmt(headCond, headThen, headElse));
ii->getNextCursor->insertAtTail(new CondStmt(nextCond, nextThen, nextElse));
ii->getHeadCursor->insertAtTail(new CallExpr(PRIMITIVE_RETURN, headCursor));
ii->getNextCursor->insertAtTail(new CallExpr(PRIMITIVE_RETURN, nextCursor));
// load local variables from fields at return points and update
// fields when local variables change
forv_Vec(Symbol, local, locals) {
Symbol* field = local2field.get(local);
if (dynamic_cast<ArgSymbol*>(local)) {
Symbol* newlocal = newTemp(ii->getNextCursor, local->type, local->name);
ASTMap map;
map.put(local, newlocal);
update_symbols(ii->getNextCursor, &map);
Symbol* newlocal2 = newTemp(ii->getHeadCursor, local->type, local->name);
{
ASTMap map;
map.put(local, newlocal2);
update_symbols(ii->getHeadCursor, &map);
}
local = newlocal;
headCopyMap.put(newlocal, newlocal2);
}
ii->getHeadCursor->insertAtHead(new CallExpr(PRIMITIVE_MOVE, headCopyMap.get(local), new CallExpr(PRIMITIVE_GET_MEMBER, headIterator, field)));
ii->getNextCursor->insertAtHead(new CallExpr(PRIMITIVE_MOVE, local, new CallExpr(PRIMITIVE_GET_MEMBER, nextIterator, field)));
forv_Vec(SymExpr, se, local->defs) {
if (CallExpr* parent = dynamic_cast<CallExpr*>(se->parentExpr))
parent->getStmtExpr()->insertAfter(
new CallExpr(PRIMITIVE_SET_MEMBER, nextIterator, field,
new SymExpr(local)));
if ((se = dynamic_cast<SymExpr*>(headCopyMap.get(se))))
if (CallExpr* parent = dynamic_cast<CallExpr*>(se->parentExpr))
parent->getStmtExpr()->insertAfter(
new CallExpr(PRIMITIVE_SET_MEMBER, headIterator, field,
new SymExpr(dynamic_cast<Symbol*>(headCopyMap.get(local)))));
}
}
buildIsValidCursor(fn);
buildGetValue(fn, value);
}
void lowerIterator(FnSymbol* fn) {
IteratorInfo* ii = fn->iteratorInfo;
currentLineno = fn->lineno;
currentFilename = fn->filename;
Vec<BaseAST*> asts;
collect_asts_postorder(&asts, fn);
// make fields for all local variables and arguments
// optimization note: only variables live at yield points are required
Map<Symbol*,Symbol*> local2field;
Vec<Symbol*> locals;
int i = 0;
forv_Vec(BaseAST, ast, asts) {
if (DefExpr* def = dynamic_cast<DefExpr*>(ast)) {
if (dynamic_cast<ArgSymbol*>(def->sym) || dynamic_cast<VarSymbol*>(def->sym)) {
if (def->sym->isReference) // references are short-lived and
// should never need to be stored
// in an iterator class (hopefully)
continue;
Symbol* local = def->sym;
Symbol* field =
new VarSymbol(astr("_", istr(i++), "_", local->name), local->type);
local2field.put(local, field);
locals.add(local);
ii->classType->fields->insertAtTail(new DefExpr(field));
}
}
}
Symbol* value = local2field.get(fn->getReturnSymbol());
if (CallExpr* yield = isSingleLoopIterator(fn, asts)) {
buildSingleLoopMethods(fn, asts, local2field, locals, value, yield);
} else {
buildGetNextCursor(fn, asts, local2field, locals);
buildGetHeadCursor(fn);
buildIsValidCursor(fn);
buildGetValue(fn, value);
}
// rebuild iterator function
for_alist(Expr, expr, fn->body->body)
expr->remove();
fn->defPoint->remove();
fn->retType = ii->classType;
Symbol* t1 = newTemp(fn, ii->classType);
fn->insertAtTail(new CallExpr(PRIMITIVE_MOVE, t1, new CallExpr(PRIMITIVE_CHPL_ALLOC, ii->classType->symbol, new_StringSymbol("iterator class"))));
forv_Vec(Symbol, local, locals) {
Symbol* field = local2field.get(local);
if (dynamic_cast<ArgSymbol*>(local))
fn->insertAtTail(new CallExpr(PRIMITIVE_SET_MEMBER, t1, field, local));
}
fn->addPragma("first member sets");
fn->insertAtTail(new CallExpr(PRIMITIVE_RETURN, t1));
ii->getValue->defPoint->insertAfter(new DefExpr(fn));
}
<|endoftext|>
|
<commit_before>/*
* SessionPath.cpp
*
* Copyright (C) 2009-11 by RStudio, Inc.
*
* This program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include "SessionPath.hpp"
#include <string>
#include <vector>
#include <boost/regex.hpp>
#include <boost/bind.hpp>
#include <core/Error.hpp>
#include <core/Log.hpp>
#include <core/FilePath.hpp>
#include <core/FileSerializer.hpp>
#include <core/system/System.hpp>
#include <session/SessionModuleContext.hpp>
using namespace core ;
namespace session {
namespace modules {
namespace path {
namespace {
Error readPathsFromFile(const FilePath& filePath,
std::vector<std::string>* pPaths)
{
std::vector<std::string> paths;
Error error = core::readStringVectorFromFile(filePath, &paths);
if (error)
{
error.addProperty("path-source", filePath.absolutePath());
return error;
}
std::copy(paths.begin(), paths.end(), std::back_inserter(*pPaths));
return Success();
}
void safeReadPathsFromFile(const FilePath& filePath,
std::vector<std::string>* pPaths)
{
Error error = readPathsFromFile(filePath, pPaths);
if (error)
LOG_ERROR(error);
}
void addToPathIfNecessary(const std::string& entry, std::string* pPath)
{
if (!regex_search(*pPath, boost::regex("(^|:)" + entry + "/?($|:)")))
{
if (!pPath->empty())
pPath->push_back(':');
pPath->append(entry);
}
}
} // anonymous namespace
Error initialize()
{
#ifdef __APPLE__
if (session::options().programMode() == kSessionProgramModeDesktop)
{
// read /etc/paths
std::vector<std::string> paths;
safeReadPathsFromFile(FilePath("/etc/paths"), &paths);
// read /etc/paths.d/* (once again failure is not fatal as we
// can fall back to the previous setting)
FilePath pathsD("/etc/paths.d");
if (pathsD.exists())
{
// enumerate the children
std::vector<FilePath> pathsDChildren;
Error error = pathsD.children(&pathsDChildren);
if (error)
LOG_ERROR(error);
// collect their paths
std::for_each(pathsDChildren.begin(),
pathsDChildren.end(),
boost::bind(safeReadPathsFromFile, _1, &paths));
}
// build and set the PATH
std::string path = core::system::getenv("PATH");
std::for_each(paths.begin(),
paths.end(),
boost::bind(addToPathIfNecessary, _1, &path));
core::system::setenv("PATH", path);
}
#endif
return Success();
}
} // namespace path
} // namespace modules
} // namesapce session
<commit_msg>prepend /opt/local/bin to path on os x if it exists (for TeXLive)<commit_after>/*
* SessionPath.cpp
*
* Copyright (C) 2009-11 by RStudio, Inc.
*
* This program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include "SessionPath.hpp"
#include <string>
#include <vector>
#include <boost/regex.hpp>
#include <boost/bind.hpp>
#include <core/Error.hpp>
#include <core/Log.hpp>
#include <core/FilePath.hpp>
#include <core/FileSerializer.hpp>
#include <core/system/System.hpp>
#include <session/SessionModuleContext.hpp>
using namespace core ;
namespace session {
namespace modules {
namespace path {
namespace {
Error readPathsFromFile(const FilePath& filePath,
std::vector<std::string>* pPaths)
{
std::vector<std::string> paths;
Error error = core::readStringVectorFromFile(filePath, &paths);
if (error)
{
error.addProperty("path-source", filePath.absolutePath());
return error;
}
std::copy(paths.begin(), paths.end(), std::back_inserter(*pPaths));
return Success();
}
void safeReadPathsFromFile(const FilePath& filePath,
std::vector<std::string>* pPaths)
{
Error error = readPathsFromFile(filePath, pPaths);
if (error)
LOG_ERROR(error);
}
void addToPathIfNecessary(const std::string& entry, std::string* pPath)
{
if (!regex_search(*pPath, boost::regex("(^|:)" + entry + "/?($|:)")))
{
if (!pPath->empty())
pPath->push_back(':');
pPath->append(entry);
}
}
} // anonymous namespace
Error initialize()
{
#ifdef __APPLE__
if (session::options().programMode() == kSessionProgramModeDesktop)
{
// do we need to add /opt/local/bin?
std::string probePath = core::system::getenv("PATH");
FilePath optLocalBinPath("/opt/local/bin");
if (!regex_search(probePath, boost::regex("(^|:)/opt/local/bin/?($|:)"))
&& optLocalBinPath.exists())
{
// add opt/local/bin to path (prepend so we find macports texi2dvi
// first if it is installed there)
core::system::addToSystemPath(optLocalBinPath, true);
}
// read /etc/paths
std::vector<std::string> paths;
safeReadPathsFromFile(FilePath("/etc/paths"), &paths);
// read /etc/paths.d/* (once again failure is not fatal as we
// can fall back to the previous setting)
FilePath pathsD("/etc/paths.d");
if (pathsD.exists())
{
// enumerate the children
std::vector<FilePath> pathsDChildren;
Error error = pathsD.children(&pathsDChildren);
if (error)
LOG_ERROR(error);
// collect their paths
std::for_each(pathsDChildren.begin(),
pathsDChildren.end(),
boost::bind(safeReadPathsFromFile, _1, &paths));
}
// build and set the PATH
std::string path = core::system::getenv("PATH");
std::for_each(paths.begin(),
paths.end(),
boost::bind(addToPathIfNecessary, _1, &path));
core::system::setenv("PATH", path);
}
#endif
return Success();
}
} // namespace path
} // namespace modules
} // namesapce session
<|endoftext|>
|
<commit_before>#include "cpu/pred/control_fault_evaluator.hh"
using namespace Evaluator;
using namespace std;
ControlFaultEvaluator::ControlFaultEvaluator(string trigger,string action,
bool _isEnabled) :
isEnabled(_isEnabled)
{
if (!isEnabled)
return;
int n_nodes, n_edges;
stringstream trigger_stream(trigger);
stringstream action_stream(action);
trigger_stream >> n_nodes;
trigger_stream >> n_edges;
triggerNodes.resize(n_nodes);
for ( int i = 0; i < n_nodes; i++ ) {
int number;
trigger_stream >> number;
char type;
NodeType n_type;
trigger_stream >> type;
if ( type == 'i' )
n_type = NodeType::index;
else if ( type == 'c' )
n_type = NodeType::constant;
else
n_type = NodeType::op;
string value;
trigger_stream >> value;
triggerNodes[number].type= n_type;
triggerNodes[number].value = value;
}
for ( int i = 0; i < n_edges; i++ ) {
int father;
int child;
trigger_stream >> father;
trigger_stream >> child;
if ( triggerNodes[father].left == -1 )
triggerNodes[father].left = child;
else
triggerNodes[father].right = child;
}
action_stream >> n_nodes;
action_stream >> n_edges;
actionNodes.resize(n_nodes);
for ( int i = 0; i < n_nodes; i++ ) {
int number;
action_stream >> number;
char type;
NodeType n_type;
action_stream >> type;
if ( type == 'i' )
n_type = NodeType::index;
else if ( type == 'c' )
n_type = NodeType::constant;
else
n_type = NodeType::op;
string value;
action_stream >> value;
actionNodes[number] = Node(n_type,value);
}
for ( int i = 0; i < n_edges; i++ ) {
int father;
int child;
action_stream >> father;
action_stream >> child;
if ( actionNodes[father].left == -1 )
actionNodes[father].left = child;
else
actionNodes[father].right = child;
}
}
Addr ControlFaultEvaluator::evaluateTrigger(Addr original_address,
node_index actual_node) {
//original_address %= 128;
if ( triggerNodes[actual_node].isOp() ) {
if ( triggerNodes[actual_node].value.compare("&") == 0 ) {
return
(triggerNodes[triggerNodes[actual_node].left].isOp() ?
evaluateTrigger(original_address,triggerNodes[actual_node].left)
: triggerNodes[triggerNodes[actual_node].left]
.extractValue(original_address))
&
(triggerNodes[triggerNodes[actual_node].right].isOp() ?
evaluateTrigger(original_address,triggerNodes[actual_node].right)
: triggerNodes[triggerNodes[actual_node].right]
.extractValue(original_address));
}
else if ( triggerNodes[actual_node].value.compare("|") == 0 ) {
return
(triggerNodes[triggerNodes[actual_node].left].isOp() ?
evaluateTrigger(original_address,triggerNodes[actual_node].left)
:
triggerNodes[triggerNodes[actual_node].left]
.extractValue(original_address))
|
(triggerNodes[triggerNodes[actual_node].right].isOp() ?
evaluateTrigger(original_address,triggerNodes[actual_node].right)
: triggerNodes[triggerNodes[actual_node].right]
.extractValue(original_address));
}
else if ( triggerNodes[actual_node].value.compare(">") == 0 ) {
long int op1 = (triggerNodes[triggerNodes[actual_node].left].isOp() ?
evaluateTrigger(original_address,triggerNodes[actual_node].left)
: triggerNodes[triggerNodes[actual_node].left]
.extractValue(original_address));
long int op2 = (triggerNodes[triggerNodes[actual_node].right].isOp() ?
evaluateTrigger(original_address,triggerNodes[actual_node].right)
: triggerNodes[triggerNodes[actual_node].right]
.extractValue(original_address));
if (op1 > op2)
return 1;
else
return 0;
}
else if ( triggerNodes[actual_node].value.compare("<") == 0 ) {
long int op1 = (triggerNodes[triggerNodes[actual_node].left].isOp() ?
evaluateTrigger(original_address,triggerNodes[actual_node].left)
: triggerNodes[triggerNodes[actual_node].left]
.extractValue(original_address));
long int op2 = (triggerNodes[triggerNodes[actual_node].right].isOp() ?
evaluateTrigger(original_address,triggerNodes[actual_node].right)
: triggerNodes[triggerNodes[actual_node].right]
.extractValue(original_address));
if (op1 < op2)
return 1;
else
return 0;
}
else if ( triggerNodes[actual_node].value.compare(">=") == 0 ) {
long int op1 = (triggerNodes[triggerNodes[actual_node].left].isOp() ?
evaluateTrigger(original_address,triggerNodes[actual_node].left)
: triggerNodes[triggerNodes[actual_node].left]
.extractValue(original_address));
long int op2 = (triggerNodes[triggerNodes[actual_node].right].isOp() ?
evaluateTrigger(original_address,triggerNodes[actual_node].right)
: triggerNodes[triggerNodes[actual_node].right]
.extractValue(original_address));
if (op1 >= op2)
return 1;
else
return 0;
}
else if ( triggerNodes[actual_node].value.compare("<=") == 0 ) {
long int op1 = (triggerNodes[triggerNodes[actual_node].left].isOp() ?
evaluateTrigger(original_address,triggerNodes[actual_node].left)
: triggerNodes[triggerNodes[actual_node].left]
.extractValue(original_address));
long int op2 = (triggerNodes[triggerNodes[actual_node].right].isOp() ?
evaluateTrigger(original_address,triggerNodes[actual_node].right)
: triggerNodes[triggerNodes[actual_node].right]
.extractValue(original_address));
if (op1 <= op2)
return 1;
else
return 0;
}
else if ( triggerNodes[actual_node].value.compare("==") == 0 ) {
long int op1 = (triggerNodes[triggerNodes[actual_node].left].isOp() ?
evaluateTrigger(original_address,triggerNodes[actual_node].left)
: triggerNodes[triggerNodes[actual_node].left]
.extractValue(original_address));
long int op2 = (triggerNodes[triggerNodes[actual_node].right].isOp() ?
evaluateTrigger(original_address,triggerNodes[actual_node].right)
: triggerNodes[triggerNodes[actual_node].right]
.extractValue(original_address));
if (op1 == op2)
return 1;
else
return 0;
}
else if ( triggerNodes[actual_node].value.compare("!") == 0 ) {
return
(triggerNodes[triggerNodes[actual_node].left].isOp() ?
!evaluateTrigger(original_address,triggerNodes[actual_node].left)
: !triggerNodes[triggerNodes[actual_node].left]
.extractValue(original_address));
}
}
return false;
}
Addr ControlFaultEvaluator::evaluateAction(Addr original_address,
node_index actual_node) {
if ( actionNodes[actual_node].isOp() ) {
if ( actionNodes[actual_node].value.compare("&") == 0 ) {
return
(actionNodes[actionNodes[actual_node].left].isOp() ?
evaluateTrigger(original_address,actionNodes[actual_node].left)
: actionNodes[actionNodes[actual_node].left]
.extractValue(original_address))
&
(actionNodes[actionNodes[actual_node].right].isOp() ?
evaluateTrigger(original_address,actionNodes[actual_node].right)
: actionNodes[actionNodes[actual_node].right]
.extractValue(original_address));
}
else if ( actionNodes[actual_node].value.compare("|") == 0 ) {
return
(actionNodes[actionNodes[actual_node].left].isOp() ?
evaluateTrigger(original_address,actionNodes[actual_node].left)
:
actionNodes[actionNodes[actual_node].left]
.extractValue(original_address))
|
(actionNodes[actionNodes[actual_node].right].isOp() ?
evaluateTrigger(original_address,actionNodes[actual_node].right)
: actionNodes[actionNodes[actual_node].right]
.extractValue(original_address));
}
else if ( actionNodes[actual_node].value.compare(">>") == 0 ) {
return
(actionNodes[actionNodes[actual_node].left].isOp() ?
evaluateTrigger(original_address,actionNodes[actual_node].left)
: actionNodes[actionNodes[actual_node].left]
.extractValue(original_address))
>>
(actionNodes[actionNodes[actual_node].right].isOp() ?
evaluateTrigger(original_address,actionNodes[actual_node].right)
: actionNodes[actionNodes[actual_node].right]
.extractValue(original_address));
}
else if ( actionNodes[actual_node].value.compare("<<") == 0 ) {
return
(actionNodes[actionNodes[actual_node].left].isOp() ?
evaluateTrigger(original_address,actionNodes[actual_node].left)
: actionNodes[actionNodes[actual_node].left]
.extractValue(original_address))
<<
(actionNodes[actionNodes[actual_node].right].isOp() ?
evaluateTrigger(original_address,actionNodes[actual_node].right)
: actionNodes[actionNodes[actual_node].right]
.extractValue(original_address));
}
else if ( actionNodes[actual_node].value.compare("^") == 0 ) {
return
(actionNodes[actionNodes[actual_node].left].isOp() ?
evaluateTrigger(original_address,actionNodes[actual_node].left)
: actionNodes[actionNodes[actual_node].left]
.extractValue(original_address))
^
(actionNodes[actionNodes[actual_node].right].isOp() ?
evaluateTrigger(original_address,actionNodes[actual_node].right)
: actionNodes[actionNodes[actual_node].right]
.extractValue(original_address));
}
else if ( actionNodes[actual_node].value.compare("~") == 0 ) {
return
(actionNodes[actionNodes[actual_node].left].isOp() ?
~ evaluateTrigger(original_address,actionNodes[actual_node].left)
: ~ actionNodes[actionNodes[actual_node].left]
.extractValue(original_address));
}
}
return actionNodes[actual_node].extractValue(original_address);
}
Addr ControlFaultEvaluator::evaluate(Addr original_address) {
if (!isEnabled)
return original_address;
if (!evaluateTrigger(original_address, 0))
return original_address;
return evaluateAction(original_address, 0);
}
<commit_msg>fix logical condition evalutarion in contro_fault_evaluator<commit_after>#include "cpu/pred/control_fault_evaluator.hh"
using namespace Evaluator;
using namespace std;
ControlFaultEvaluator::ControlFaultEvaluator(string trigger,string action,
bool _isEnabled) :
isEnabled(_isEnabled)
{
if (!isEnabled)
return;
int n_nodes, n_edges;
stringstream trigger_stream(trigger);
stringstream action_stream(action);
trigger_stream >> n_nodes;
trigger_stream >> n_edges;
triggerNodes.resize(n_nodes);
for ( int i = 0; i < n_nodes; i++ ) {
int number;
trigger_stream >> number;
char type;
NodeType n_type;
trigger_stream >> type;
if ( type == 'i' )
n_type = NodeType::index;
else if ( type == 'c' )
n_type = NodeType::constant;
else
n_type = NodeType::op;
string value;
trigger_stream >> value;
triggerNodes[number].type= n_type;
triggerNodes[number].value = value;
}
for ( int i = 0; i < n_edges; i++ ) {
int father;
int child;
trigger_stream >> father;
trigger_stream >> child;
if ( triggerNodes[father].left == -1 )
triggerNodes[father].left = child;
else
triggerNodes[father].right = child;
}
action_stream >> n_nodes;
action_stream >> n_edges;
actionNodes.resize(n_nodes);
for ( int i = 0; i < n_nodes; i++ ) {
int number;
action_stream >> number;
char type;
NodeType n_type;
action_stream >> type;
if ( type == 'i' )
n_type = NodeType::index;
else if ( type == 'c' )
n_type = NodeType::constant;
else
n_type = NodeType::op;
string value;
action_stream >> value;
actionNodes[number] = Node(n_type,value);
}
for ( int i = 0; i < n_edges; i++ ) {
int father;
int child;
action_stream >> father;
action_stream >> child;
if ( actionNodes[father].left == -1 )
actionNodes[father].left = child;
else
actionNodes[father].right = child;
}
}
Addr ControlFaultEvaluator::evaluateTrigger(Addr original_address,
node_index actual_node) {
//original_address %= 128;
if ( triggerNodes[actual_node].isOp() ) {
if ( triggerNodes[actual_node].value.compare("&") == 0 ) {
return
(triggerNodes[triggerNodes[actual_node].left].isOp() ?
evaluateTrigger(original_address,triggerNodes[actual_node].left)
: triggerNodes[triggerNodes[actual_node].left]
.extractValue(original_address))
&
(triggerNodes[triggerNodes[actual_node].right].isOp() ?
evaluateTrigger(original_address,triggerNodes[actual_node].right)
: triggerNodes[triggerNodes[actual_node].right]
.extractValue(original_address));
}
else if ( triggerNodes[actual_node].value.compare("&&") == 0 ) {
long int op1 = (triggerNodes[triggerNodes[actual_node].left].isOp() ?
evaluateTrigger(original_address,triggerNodes[actual_node].left)
: triggerNodes[triggerNodes[actual_node].left]
.extractValue(original_address));
long int op2 = (triggerNodes[triggerNodes[actual_node].right].isOp() ?
evaluateTrigger(original_address,triggerNodes[actual_node].right)
: triggerNodes[triggerNodes[actual_node].right]
.extractValue(original_address));
if (op1 && op2)
return 1;
else
return 0;
}
else if ( triggerNodes[actual_node].value.compare("|") == 0 ) {
return
(triggerNodes[triggerNodes[actual_node].left].isOp() ?
evaluateTrigger(original_address,triggerNodes[actual_node].left)
:
triggerNodes[triggerNodes[actual_node].left]
.extractValue(original_address))
|
(triggerNodes[triggerNodes[actual_node].right].isOp() ?
evaluateTrigger(original_address,triggerNodes[actual_node].right)
: triggerNodes[triggerNodes[actual_node].right]
.extractValue(original_address));
}
else if ( triggerNodes[actual_node].value.compare("||") == 0 ) {
long int op1 = (triggerNodes[triggerNodes[actual_node].left].isOp() ?
evaluateTrigger(original_address,triggerNodes[actual_node].left)
: triggerNodes[triggerNodes[actual_node].left]
.extractValue(original_address));
long int op2 = (triggerNodes[triggerNodes[actual_node].right].isOp() ?
evaluateTrigger(original_address,triggerNodes[actual_node].right)
: triggerNodes[triggerNodes[actual_node].right]
.extractValue(original_address));
if (op1 || op2)
return 1;
else
return 0;
}
else if ( triggerNodes[actual_node].value.compare(">") == 0 ) {
long int op1 = (triggerNodes[triggerNodes[actual_node].left].isOp() ?
evaluateTrigger(original_address,triggerNodes[actual_node].left)
: triggerNodes[triggerNodes[actual_node].left]
.extractValue(original_address));
long int op2 = (triggerNodes[triggerNodes[actual_node].right].isOp() ?
evaluateTrigger(original_address,triggerNodes[actual_node].right)
: triggerNodes[triggerNodes[actual_node].right]
.extractValue(original_address));
if (op1 > op2)
return 1;
else
return 0;
}
else if ( triggerNodes[actual_node].value.compare("<") == 0 ) {
long int op1 = (triggerNodes[triggerNodes[actual_node].left].isOp() ?
evaluateTrigger(original_address,triggerNodes[actual_node].left)
: triggerNodes[triggerNodes[actual_node].left]
.extractValue(original_address));
long int op2 = (triggerNodes[triggerNodes[actual_node].right].isOp() ?
evaluateTrigger(original_address,triggerNodes[actual_node].right)
: triggerNodes[triggerNodes[actual_node].right]
.extractValue(original_address));
if (op1 < op2)
return 1;
else
return 0;
}
else if ( triggerNodes[actual_node].value.compare(">=") == 0 ) {
long int op1 = (triggerNodes[triggerNodes[actual_node].left].isOp() ?
evaluateTrigger(original_address,triggerNodes[actual_node].left)
: triggerNodes[triggerNodes[actual_node].left]
.extractValue(original_address));
long int op2 = (triggerNodes[triggerNodes[actual_node].right].isOp() ?
evaluateTrigger(original_address,triggerNodes[actual_node].right)
: triggerNodes[triggerNodes[actual_node].right]
.extractValue(original_address));
if (op1 >= op2)
return 1;
else
return 0;
}
else if ( triggerNodes[actual_node].value.compare("<=") == 0 ) {
long int op1 = (triggerNodes[triggerNodes[actual_node].left].isOp() ?
evaluateTrigger(original_address,triggerNodes[actual_node].left)
: triggerNodes[triggerNodes[actual_node].left]
.extractValue(original_address));
long int op2 = (triggerNodes[triggerNodes[actual_node].right].isOp() ?
evaluateTrigger(original_address,triggerNodes[actual_node].right)
: triggerNodes[triggerNodes[actual_node].right]
.extractValue(original_address));
if (op1 <= op2)
return 1;
else
return 0;
}
else if ( triggerNodes[actual_node].value.compare("==") == 0 ) {
long int op1 = (triggerNodes[triggerNodes[actual_node].left].isOp() ?
evaluateTrigger(original_address,triggerNodes[actual_node].left)
: triggerNodes[triggerNodes[actual_node].left]
.extractValue(original_address));
long int op2 = (triggerNodes[triggerNodes[actual_node].right].isOp() ?
evaluateTrigger(original_address,triggerNodes[actual_node].right)
: triggerNodes[triggerNodes[actual_node].right]
.extractValue(original_address));
if (op1 == op2)
return 1;
else
return 0;
}
else if ( triggerNodes[actual_node].value.compare("!") == 0 ) {
return
(triggerNodes[triggerNodes[actual_node].left].isOp() ?
!evaluateTrigger(original_address,triggerNodes[actual_node].left)
: !triggerNodes[triggerNodes[actual_node].left]
.extractValue(original_address));
}
}
return false;
}
Addr ControlFaultEvaluator::evaluateAction(Addr original_address,
node_index actual_node) {
if ( actionNodes[actual_node].isOp() ) {
if ( actionNodes[actual_node].value.compare("&") == 0 ) {
return
(actionNodes[actionNodes[actual_node].left].isOp() ?
evaluateTrigger(original_address,actionNodes[actual_node].left)
: actionNodes[actionNodes[actual_node].left]
.extractValue(original_address))
&
(actionNodes[actionNodes[actual_node].right].isOp() ?
evaluateTrigger(original_address,actionNodes[actual_node].right)
: actionNodes[actionNodes[actual_node].right]
.extractValue(original_address));
}
else if ( actionNodes[actual_node].value.compare("|") == 0 ) {
return
(actionNodes[actionNodes[actual_node].left].isOp() ?
evaluateTrigger(original_address,actionNodes[actual_node].left)
:
actionNodes[actionNodes[actual_node].left]
.extractValue(original_address))
|
(actionNodes[actionNodes[actual_node].right].isOp() ?
evaluateTrigger(original_address,actionNodes[actual_node].right)
: actionNodes[actionNodes[actual_node].right]
.extractValue(original_address));
}
else if ( actionNodes[actual_node].value.compare(">>") == 0 ) {
return
(actionNodes[actionNodes[actual_node].left].isOp() ?
evaluateTrigger(original_address,actionNodes[actual_node].left)
: actionNodes[actionNodes[actual_node].left]
.extractValue(original_address))
>>
(actionNodes[actionNodes[actual_node].right].isOp() ?
evaluateTrigger(original_address,actionNodes[actual_node].right)
: actionNodes[actionNodes[actual_node].right]
.extractValue(original_address));
}
else if ( actionNodes[actual_node].value.compare("<<") == 0 ) {
return
(actionNodes[actionNodes[actual_node].left].isOp() ?
evaluateTrigger(original_address,actionNodes[actual_node].left)
: actionNodes[actionNodes[actual_node].left]
.extractValue(original_address))
<<
(actionNodes[actionNodes[actual_node].right].isOp() ?
evaluateTrigger(original_address,actionNodes[actual_node].right)
: actionNodes[actionNodes[actual_node].right]
.extractValue(original_address));
}
else if ( actionNodes[actual_node].value.compare("^") == 0 ) {
return
(actionNodes[actionNodes[actual_node].left].isOp() ?
evaluateTrigger(original_address,actionNodes[actual_node].left)
: actionNodes[actionNodes[actual_node].left]
.extractValue(original_address))
^
(actionNodes[actionNodes[actual_node].right].isOp() ?
evaluateTrigger(original_address,actionNodes[actual_node].right)
: actionNodes[actionNodes[actual_node].right]
.extractValue(original_address));
}
else if ( actionNodes[actual_node].value.compare("~") == 0 ) {
return
(actionNodes[actionNodes[actual_node].left].isOp() ?
~ evaluateTrigger(original_address,actionNodes[actual_node].left)
: ~ actionNodes[actionNodes[actual_node].left]
.extractValue(original_address));
}
}
return actionNodes[actual_node].extractValue(original_address);
}
Addr ControlFaultEvaluator::evaluate(Addr original_address) {
if (!isEnabled)
return original_address;
if (!evaluateTrigger(original_address, 0))
return original_address;
return evaluateAction(original_address, 0);
}
<|endoftext|>
|
<commit_before>/*=========================================================================
*
* Copyright Marius Staring, Stefan Klein, David Doria. 2011.
*
* 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.txt
*
* 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
\brief Create a grid image.
\verbinclude creategridimage.help
*/
#include "itkCommandLineArgumentParser.h"
#include "CommandLineArgumentHelper.h"
#include "itkImage.h"
#include "itkImageRegionIteratorWithIndex.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
//-------------------------------------------------------------------------------------
/** run: A macro to call a function. */
#define run( function, dim ) \
if ( imageDimension == dim ) \
{ \
function< dim >( inputFileName, outputFileName, imageSize, imageSpacing, distance, is2DStack ); \
supported = true; \
}
//-------------------------------------------------------------------------------------
/** Declare functions. */
std::string GetHelpString( void );
template<unsigned int Dimension>
void CreateGridImage(
const std::string & inputFileName,
const std::string & outputFileName,
const std::vector<unsigned int> & imageSize,
const std::vector<float> & imageSpacing,
const std::vector<unsigned int> & distance,
const bool & is2DStack );
//-------------------------------------------------------------------------------------
int main( int argc, char *argv[] )
{
/** Create a command line argument parser. */
itk::CommandLineArgumentParser::Pointer parser = itk::CommandLineArgumentParser::New();
parser->SetCommandLineArguments( argc, argv );
parser->SetProgramHelpText( GetHelpString() );
parser->MarkArgumentAsRequired( "-out", "The output filename." );
itk::CommandLineArgumentParser::ReturnValue validateArguments = parser->CheckForRequiredArguments();
if(validateArguments == itk::CommandLineArgumentParser::FAILED)
{
return EXIT_FAILURE;
}
else if(validateArguments == itk::CommandLineArgumentParser::HELPREQUESTED)
{
return EXIT_SUCCESS;
}
/** Get arguments. */
std::string inputFileName = "";
bool retin = parser->GetCommandLineArgument( "-in", inputFileName );
std::string outputFileName = "";
parser->GetCommandLineArgument( "-out", outputFileName );
std::vector<unsigned int> imageSize;
bool retsz = parser->GetCommandLineArgument( "-sz", imageSize );
const bool is2DStack = parser->ArgumentExists( "-stack" );
/** Check if the required arguments are given. */
if ( ( !retin && !retsz ) || ( retin && retsz ) )
{
std::cerr << "ERROR: You should specify \"-in\" or \"-sz\"." << std::endl;
return 1;
}
/** Check arguments: size. */
if ( retsz )
{
for ( unsigned int i = 0; i < imageSize.size(); ++i )
{
if ( imageSize[ i ] == 0 )
{
std::cerr << "ERROR: image size[" << i << "] = 0." << std::endl;
return 1;
}
}
}
/** Get desired grid image dimension. */
unsigned int imageDimension = 3;
if ( retsz )
{
imageDimension = imageSize.size();
}
else
{
/** Determine image properties. */
std::string ComponentTypeIn = "short";
std::string PixelType; //we don't use this
unsigned int NumberOfComponents = 1;
std::vector<unsigned int> imagesize( imageDimension, 0 );
int retgip = GetImageProperties(
inputFileName,
PixelType,
ComponentTypeIn,
imageDimension,
NumberOfComponents,
imagesize );
if ( retgip != 0 ) return 1;
}
/** Check arguments: dimensionality. */
if ( imageDimension < 2 || imageDimension > 3 )
{
std::cerr << "ERROR: Only image dimensions of 2 or 3 are supported." << std::endl;
return 1;
}
/** Get more arguments. */
std::vector<float> imageSpacing( imageDimension, 1.0 );
parser->GetCommandLineArgument( "-sp", imageSpacing );
std::vector<unsigned int> distance( imageDimension, 1 );
bool retd = parser->GetCommandLineArgument( "-d", distance );
/** Check arguments: distance. */
if ( !retd )
{
std::cerr << "ERROR: You should specify \"-d\"." << std::endl;
return 1;
}
for ( unsigned int i = 0; i < distance.size(); ++i )
{
if ( distance[ i ] == 0 ) distance[ i ] = 1;
}
/** Run the program. */
bool supported = false;
try
{
run( CreateGridImage, 2 );
run( CreateGridImage, 3 );
}
catch( itk::ExceptionObject &e )
{
std::cerr << "Caught ITK exception: " << e << std::endl;
return 1;
}
if ( !supported )
{
std::cerr << "ERROR: this dimension is not supported!" << std::endl;
std::cerr <<
" ; dimension = " << imageDimension
<< std::endl;
return 1;
}
/** End program. */
return 0;
} // end main
/*
* ******************* CreateGridImage *******************
*/
template< unsigned int Dimension >
void CreateGridImage(
const std::string & inputFileName,
const std::string & outputFileName,
const std::vector<unsigned int> & imageSize,
const std::vector<float> & imageSpacing,
const std::vector<unsigned int> & distance,
const bool & is2DStack )
{
/** Typedef's. */
typedef unsigned char PixelType;
typedef itk::Image< PixelType, Dimension > ImageType;
typedef itk::ImageRegionIteratorWithIndex< ImageType > IteratorType;
typedef itk::ImageFileReader< ImageType > ReaderType;
typedef itk::ImageFileWriter< ImageType > WriterType;
typedef typename ImageType::SizeType SizeType;
typedef typename ImageType::IndexType IndexType;
typedef typename ImageType::SpacingType SpacingType;
/* Create image and writer. */
typename ImageType::Pointer image = ImageType::New();
typename ReaderType::Pointer reader = ReaderType::New();
typename WriterType::Pointer writer = WriterType::New();
/** Get and set grid image information. */
if ( inputFileName != "" )
{
reader->SetFileName( inputFileName.c_str() );
reader->GenerateOutputInformation();
SizeType size = reader->GetOutput()->GetLargestPossibleRegion().GetSize();
image->SetRegions( size );
image->SetSpacing( reader->GetOutput()->GetSpacing() );
image->SetOrigin( reader->GetOutput()->GetOrigin() );
image->SetDirection( reader->GetOutput()->GetDirection() );
}
else
{
SizeType size;
SpacingType spacing;
for ( unsigned int i = 0; i < Dimension; ++i )
{
size[ i ] = imageSize[ i ];
spacing[ i ] = imageSpacing[ i ];
}
image->SetRegions( size );
image->SetSpacing( spacing );
}
/** Allocate image. */
image->Allocate();
/* Fill the image. */
IteratorType it( image, image->GetLargestPossibleRegion() );
it.GoToBegin();
IndexType ind;
while ( !it.IsAtEnd() )
{
/** Check if on grid. */
ind = it.GetIndex();
bool onGrid = false;
onGrid |= ind[ 0 ] % distance[ 0 ] == 0;
onGrid |= ind[ 1 ] % distance[ 1 ] == 0;
if ( Dimension == 3 && !is2DStack )
{
if ( ind[ 2 ] % distance[ 2 ] != 0 )
{
onGrid = ind[ 0 ] % distance[ 0 ] == 0;
onGrid &= ind[ 1 ] % distance[ 1 ] == 0;
}
}
/** Set the value and continue. */
if ( onGrid ) it.Set( 1 );
else it.Set( 0 );
++it;
} // end while
/* Write result to file. */
writer->SetFileName( outputFileName.c_str() );
writer->SetInput( image );
writer->Update();
} // end CreateGridImage()
/**
* ******************* GetHelpString *******************
*/
std::string GetHelpString( void )
{
std::stringstream ss;
ss << "Usage:" << std::endl
<< "pxcreategridimage" << std::endl
<< "[-in] inputFilename, information about size, etc, is taken from it" << std::endl
<< "-out outputFilename" << std::endl
<< "-sz image size for each dimension" << std::endl
<< "[-sp] image spacing, default 1.0" << std::endl
<< "-d distance in pixels between two gridlines" << std::endl
<< "[-stack] for 3D images, create a stack of 2D images, default false" << std::endl
<< "Supported: 2D, 3D, short.";
return ss.str();
} // end GetHelpString()
<commit_msg>ENH: Convert CreateGridImage to template<commit_after>/*=========================================================================
*
* Copyright Marius Staring, Stefan Klein, David Doria. 2011.
*
* 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.txt
*
* 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
\brief Create a grid image.
\verbinclude creategridimage.help
*/
#include "itkCommandLineArgumentParser.h"
#include "CommandLineArgumentHelper.h"
#include "itkImage.h"
#include "itkImageRegionIteratorWithIndex.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
//-------------------------------------------------------------------------------------
std::string GetHelpString( void );
/** CreateGridImage */
class CreateGridImageBase : public itktools::ITKToolsBase
{
public:
CreateGridImageBase(){};
~CreateGridImageBase(){};
/** Input parameters */
std::string m_InputFileName;
std::string m_OutputFileName;
std::vector<unsigned int> m_ImageSize;
std::vector<float> m_ImageSpacing;
std::vector<unsigned int> m_Distance;
bool m_Is2DStack;
}; // end CreateGridImageBase
template< unsigned int VDimension >
class CreateGridImage : public CreateGridImageBase
{
public:
typedef CreateGridImage Self;
CreateGridImage(){};
~CreateGridImage(){};
static Self * New( unsigned int dim )
{
if ( VDimension == dim )
{
return new Self;
}
return 0;
}
void Run(void)
{
/** Typedef's. */
typedef unsigned char PixelType;
typedef itk::Image< PixelType, VDimension > ImageType;
typedef itk::ImageRegionIteratorWithIndex< ImageType > IteratorType;
typedef itk::ImageFileReader< ImageType > ReaderType;
typedef itk::ImageFileWriter< ImageType > WriterType;
typedef typename ImageType::SizeType SizeType;
typedef typename ImageType::IndexType IndexType;
typedef typename ImageType::SpacingType SpacingType;
/* Create image and writer. */
typename ImageType::Pointer image = ImageType::New();
typename ReaderType::Pointer reader = ReaderType::New();
typename WriterType::Pointer writer = WriterType::New();
/** Get and set grid image information. */
if ( m_InputFileName != "" )
{
reader->SetFileName( m_InputFileName.c_str() );
reader->GenerateOutputInformation();
SizeType size = reader->GetOutput()->GetLargestPossibleRegion().GetSize();
image->SetRegions( size );
image->SetSpacing( reader->GetOutput()->GetSpacing() );
image->SetOrigin( reader->GetOutput()->GetOrigin() );
image->SetDirection( reader->GetOutput()->GetDirection() );
}
else
{
SizeType size;
SpacingType spacing;
for ( unsigned int i = 0; i < VDimension; ++i )
{
size[ i ] = m_ImageSize[ i ];
spacing[ i ] = m_ImageSpacing[ i ];
}
image->SetRegions( size );
image->SetSpacing( spacing );
}
/** Allocate image. */
image->Allocate();
/* Fill the image. */
IteratorType it( image, image->GetLargestPossibleRegion() );
it.GoToBegin();
IndexType ind;
while ( !it.IsAtEnd() )
{
/** Check if on grid. */
ind = it.GetIndex();
bool onGrid = false;
onGrid |= ind[ 0 ] % m_Distance[ 0 ] == 0;
onGrid |= ind[ 1 ] % m_Distance[ 1 ] == 0;
if ( VDimension == 3 && !m_Is2DStack )
{
if ( ind[ 2 ] % m_Distance[ 2 ] != 0 )
{
onGrid = ind[ 0 ] % m_Distance[ 0 ] == 0;
onGrid &= ind[ 1 ] % m_Distance[ 1 ] == 0;
}
}
/** Set the value and continue. */
if ( onGrid ) it.Set( 1 );
else it.Set( 0 );
++it;
} // end while
/* Write result to file. */
writer->SetFileName( m_OutputFileName.c_str() );
writer->SetInput( image );
writer->Update();
}
}; // end CreateGridImage
//-------------------------------------------------------------------------------------
int main( int argc, char *argv[] )
{
/** Create a command line argument parser. */
itk::CommandLineArgumentParser::Pointer parser = itk::CommandLineArgumentParser::New();
parser->SetCommandLineArguments( argc, argv );
parser->SetProgramHelpText( GetHelpString() );
parser->MarkArgumentAsRequired( "-out", "The output filename." );
itk::CommandLineArgumentParser::ReturnValue validateArguments = parser->CheckForRequiredArguments();
if(validateArguments == itk::CommandLineArgumentParser::FAILED)
{
return EXIT_FAILURE;
}
else if(validateArguments == itk::CommandLineArgumentParser::HELPREQUESTED)
{
return EXIT_SUCCESS;
}
/** Get arguments. */
std::string inputFileName = "";
bool retin = parser->GetCommandLineArgument( "-in", inputFileName );
std::string outputFileName = "";
parser->GetCommandLineArgument( "-out", outputFileName );
std::vector<unsigned int> imageSize;
bool retsz = parser->GetCommandLineArgument( "-sz", imageSize );
const bool is2DStack = parser->ArgumentExists( "-stack" );
/** Check if the required arguments are given. */
if ( ( !retin && !retsz ) || ( retin && retsz ) )
{
std::cerr << "ERROR: You should specify \"-in\" or \"-sz\"." << std::endl;
return 1;
}
/** Check arguments: size. */
if ( retsz )
{
for ( unsigned int i = 0; i < imageSize.size(); ++i )
{
if ( imageSize[ i ] == 0 )
{
std::cerr << "ERROR: image size[" << i << "] = 0." << std::endl;
return 1;
}
}
}
/** Get desired grid image dimension. */
unsigned int imageDimension = 3;
if ( retsz )
{
imageDimension = imageSize.size();
}
else
{
/** Determine image properties. */
std::string ComponentTypeIn = "short";
std::string PixelType; //we don't use this
unsigned int NumberOfComponents = 1;
std::vector<unsigned int> imagesize( imageDimension, 0 );
int retgip = GetImageProperties(
inputFileName,
PixelType,
ComponentTypeIn,
imageDimension,
NumberOfComponents,
imagesize );
if ( retgip != 0 ) return 1;
}
/** Check arguments: dimensionality. */
if ( imageDimension < 2 || imageDimension > 3 )
{
std::cerr << "ERROR: Only image dimensions of 2 or 3 are supported." << std::endl;
return 1;
}
/** Get more arguments. */
std::vector<float> imageSpacing( imageDimension, 1.0 );
parser->GetCommandLineArgument( "-sp", imageSpacing );
std::vector<unsigned int> distance( imageDimension, 1 );
bool retd = parser->GetCommandLineArgument( "-d", distance );
/** Check arguments: distance. */
if ( !retd )
{
std::cerr << "ERROR: You should specify \"-d\"." << std::endl;
return 1;
}
for ( unsigned int i = 0; i < distance.size(); ++i )
{
if ( distance[ i ] == 0 ) distance[ i ] = 1;
}
/** Class that does the work */
CreateGridImageBase * createGridImage = NULL;
/** Short alias */
unsigned int dim = imageDimension;
try
{
// now call all possible template combinations.
if (!createGridImage) createGridImage = CreateGridImage< 2 >::New( dim );
#ifdef ITKTOOLS_3D_SUPPORT
if (!createGridImage) createGridImage = CreateGridImage< 3 >::New( dim );
#endif
if (!createGridImage)
{
std::cerr << "ERROR: this combination of pixeltype and dimension is not supported!" << std::endl;
std::cerr
<< " dimension = " << dim
<< std::endl;
return 1;
}
createGridImage->m_InputFileName = inputFileName;
createGridImage->m_OutputFileName = outputFileName;
createGridImage->m_ImageSize = imageSize;
createGridImage->m_ImageSpacing = imageSpacing;
createGridImage->m_Distance = distance;
createGridImage->m_Is2DStack = is2DStack;
createGridImage->Run();
delete createGridImage;
}
catch( itk::ExceptionObject &e )
{
std::cerr << "Caught ITK exception: " << e << std::endl;
delete createGridImage;
return 1;
}
/** End program. */
return 0;
} // end main
/**
* ******************* GetHelpString *******************
*/
std::string GetHelpString( void )
{
std::stringstream ss;
ss << "Usage:" << std::endl
<< "pxcreategridimage" << std::endl
<< "[-in] inputFilename, information about size, etc, is taken from it" << std::endl
<< "-out outputFilename" << std::endl
<< "-sz image size for each dimension" << std::endl
<< "[-sp] image spacing, default 1.0" << std::endl
<< "-d distance in pixels between two gridlines" << std::endl
<< "[-stack] for 3D images, create a stack of 2D images, default false" << std::endl
<< "Supported: 2D, 3D, short.";
return ss.str();
} // end GetHelpString()
<|endoftext|>
|
<commit_before>/*!
* Copyright (c) 2015 by Contributors
* \file im2rec.cc
* \brief convert images into image recordio format
* Image Record Format: zeropad[64bit] imid[64bit] img-binary-content
* The 64bit zero pad was reserved for future purposes
*
* Image List Format: unique-image-index label[s] path-to-image
* \sa dmlc/recordio.h
*/
#include <cctype>
#include <cstring>
#include <vector>
#include <iomanip>
#include <sstream>
#include <dmlc/base.h>
#include <dmlc/io.h>
#include <dmlc/timer.h>
#include <dmlc/logging.h>
#include <dmlc/recordio.h>
#include <opencv2/opencv.hpp>
#include "../src/io/image_recordio.h"
int main(int argc, char *argv[]) {
if (argc < 4) {
printf("Usage: <image.lst> <image_root_dir> <output.rec> [additional parameters in form key=value]\n"\
"Possible additional parameters:\n"\
"\tresize=newsize resize the shorter edge of image to the newsize, original images will be packed by default\n"\
"\tlabel_width=WIDTH[default=1] specify the label_width in the list, by default set to 1\n"\
"\tnsplit=NSPLIT[default=1] used for part generation, logically split the image.list to NSPLIT parts by position\n"\
"\tpart=PART[default=0] used for part generation, pack the images from the specific part in image.list\n");
return 0;
}
int label_width = 1;
int new_size = -1;
int nsplit = 1;
int partid = 0;
for (int i = 4; i < argc; ++i) {
char key[128], val[128];
if (sscanf(argv[i], "%[^=]=%s", key, val) == 2) {
if (!strcmp(key, "resize")) new_size = atoi(val);
if (!strcmp(key, "label_width")) label_width = atoi(val);
if (!strcmp(key, "nsplit")) nsplit = atoi(val);
if (!strcmp(key, "part")) partid = atoi(val);
}
}
if (new_size > 0) {
LOG(INFO) << "New Image Size: Short Edge " << new_size;
} else {
LOG(INFO) << "Keep origin image size";
}
using namespace dmlc;
const static size_t kBufferSize = 1 << 20UL;
std::string root = argv[2];
mxnet::io::ImageRecordIO rec;
size_t imcnt = 0;
double tstart = dmlc::GetTime();
dmlc::InputSplit *flist = dmlc::InputSplit::
Create(argv[1], partid, nsplit, "text");
std::ostringstream os;
if (nsplit == 1) {
os << argv[3];
} else {
os << argv[3] << ".part" << std::setw(3) << std::setfill('0') << partid;
}
LOG(INFO) << "Write to output: " << os.str();
dmlc::Stream *fo = dmlc::Stream::Create(os.str().c_str(), "w");
LOG(INFO) << "Output: " << argv[3];
dmlc::RecordIOWriter writer(fo);
std::string fname, path, blob;
std::vector<unsigned char> decode_buf;
std::vector<unsigned char> encode_buf;
std::vector<int> encode_params;
encode_params.push_back(CV_IMWRITE_JPEG_QUALITY);
encode_params.push_back(80);
dmlc::InputSplit::Blob line;
while (flist->NextRecord(&line)) {
std::string sline(static_cast<char*>(line.dptr), line.size);
std::istringstream is(sline);
if (!(is >> rec.header.image_id[0] >> rec.header.label)) continue;
for (int k = 1; k < label_width; ++ k) {
float tmp;
CHECK(is >> tmp)
<< "Invalid ImageList, did you provide the correct label_width?";
}
CHECK(std::getline(is, fname));
const char *p = fname.c_str();
while (isspace(*p)) ++p;
path = root + p;
// use "r" is equal to rb in dmlc::Stream
dmlc::Stream *fi = dmlc::Stream::Create(path.c_str(), "r");
rec.SaveHeader(&blob);
decode_buf.clear();
size_t imsize = 0;
while (true) {
decode_buf.resize(imsize + kBufferSize);
size_t nread = fi->Read(BeginPtr(decode_buf) + imsize, kBufferSize);
imsize += nread;
decode_buf.resize(imsize);
if (nread != kBufferSize) break;
}
delete fi;
if (new_size > 0) {
cv::Mat img = cv::imdecode(decode_buf, CV_LOAD_IMAGE_COLOR);
CHECK(img.data != NULL) << "OpenCV decode fail:" << path;
cv::Mat res;
if (img.rows > img.cols) {
cv::resize(img, res, cv::Size(new_size, img.rows * new_size / img.cols),
0, 0, CV_INTER_LINEAR);
} else {
cv::resize(img, res, cv::Size(new_size * img.cols / img.rows, new_size),
0, 0, CV_INTER_LINEAR);
}
encode_buf.clear();
CHECK(cv::imencode(".jpg", res, encode_buf, encode_params));
size_t bsize = blob.size();
blob.resize(bsize + encode_buf.size());
memcpy(BeginPtr(blob) + bsize,
BeginPtr(encode_buf), encode_buf.size());
} else {
size_t bsize = blob.size();
blob.resize(bsize + decode_buf.size());
memcpy(BeginPtr(blob) + bsize,
BeginPtr(decode_buf), decode_buf.size());
}
writer.WriteRecord(BeginPtr(blob), blob.size());
// write header
++imcnt;
if (imcnt % 1000 == 0) {
LOG(INFO) << imcnt << " images processed, " << GetTime() - tstart << " sec elapsed";
}
}
LOG(INFO) << "Total: " << imcnt << " images processed, " << GetTime() - tstart << " sec elapsed";
delete fo;
delete flist;
return 0;
}
<commit_msg>More robust im2rec<commit_after>/*!
* Copyright (c) 2015 by Contributors
* \file im2rec.cc
* \brief convert images into image recordio format
* Image Record Format: zeropad[64bit] imid[64bit] img-binary-content
* The 64bit zero pad was reserved for future purposes
*
* Image List Format: unique-image-index label[s] path-to-image
* \sa dmlc/recordio.h
*/
#include <cctype>
#include <cstring>
#include <vector>
#include <iomanip>
#include <sstream>
#include <dmlc/base.h>
#include <dmlc/io.h>
#include <dmlc/timer.h>
#include <dmlc/logging.h>
#include <dmlc/recordio.h>
#include <opencv2/opencv.hpp>
#include "../src/io/image_recordio.h"
int main(int argc, char *argv[]) {
if (argc < 4) {
printf("Usage: <image.lst> <image_root_dir> <output.rec> [additional parameters in form key=value]\n"\
"Possible additional parameters:\n"\
"\tresize=newsize resize the shorter edge of image to the newsize, original images will be packed by default\n"\
"\tlabel_width=WIDTH[default=1] specify the label_width in the list, by default set to 1\n"\
"\tnsplit=NSPLIT[default=1] used for part generation, logically split the image.list to NSPLIT parts by position\n"\
"\tpart=PART[default=0] used for part generation, pack the images from the specific part in image.list\n");
return 0;
}
int label_width = 1;
int new_size = -1;
int nsplit = 1;
int partid = 0;
for (int i = 4; i < argc; ++i) {
char key[128], val[128];
if (sscanf(argv[i], "%[^=]=%s", key, val) == 2) {
if (!strcmp(key, "resize")) new_size = atoi(val);
if (!strcmp(key, "label_width")) label_width = atoi(val);
if (!strcmp(key, "nsplit")) nsplit = atoi(val);
if (!strcmp(key, "part")) partid = atoi(val);
}
}
if (new_size > 0) {
LOG(INFO) << "New Image Size: Short Edge " << new_size;
} else {
LOG(INFO) << "Keep origin image size";
}
using namespace dmlc;
const static size_t kBufferSize = 1 << 20UL;
std::string root = argv[2];
mxnet::io::ImageRecordIO rec;
size_t imcnt = 0;
double tstart = dmlc::GetTime();
dmlc::InputSplit *flist = dmlc::InputSplit::
Create(argv[1], partid, nsplit, "text");
std::ostringstream os;
if (nsplit == 1) {
os << argv[3];
} else {
os << argv[3] << ".part" << std::setw(3) << std::setfill('0') << partid;
}
LOG(INFO) << "Write to output: " << os.str();
dmlc::Stream *fo = dmlc::Stream::Create(os.str().c_str(), "w");
LOG(INFO) << "Output: " << argv[3];
dmlc::RecordIOWriter writer(fo);
std::string fname, path, blob;
std::vector<unsigned char> decode_buf;
std::vector<unsigned char> encode_buf;
std::vector<int> encode_params;
encode_params.push_back(CV_IMWRITE_JPEG_QUALITY);
encode_params.push_back(80);
dmlc::InputSplit::Blob line;
while (flist->NextRecord(&line)) {
std::string sline(static_cast<char*>(line.dptr), line.size);
std::istringstream is(sline);
if (!(is >> rec.header.image_id[0] >> rec.header.label)) continue;
for (int k = 1; k < label_width; ++ k) {
float tmp;
CHECK(is >> tmp)
<< "Invalid ImageList, did you provide the correct label_width?";
}
CHECK(std::getline(is, fname));
// eliminate invalid chars in the end
while (fname.length() != 0 &&
(isspace(*fname.rbegin()) || !isprint(*fname.rbegin()))) {
fname.resize(fname.length() - 1);
}
// eliminate invalid chars in beginning.
const char *p = fname.c_str();
while (isspace(*p)) ++p;
path = root + p;
// use "r" is equal to rb in dmlc::Stream
dmlc::Stream *fi = dmlc::Stream::Create(path.c_str(), "r");
rec.SaveHeader(&blob);
decode_buf.clear();
size_t imsize = 0;
while (true) {
decode_buf.resize(imsize + kBufferSize);
size_t nread = fi->Read(BeginPtr(decode_buf) + imsize, kBufferSize);
imsize += nread;
decode_buf.resize(imsize);
if (nread != kBufferSize) break;
}
delete fi;
if (new_size > 0) {
cv::Mat img = cv::imdecode(decode_buf, CV_LOAD_IMAGE_COLOR);
CHECK(img.data != NULL) << "OpenCV decode fail:" << path;
cv::Mat res;
if (img.rows > img.cols) {
cv::resize(img, res, cv::Size(new_size, img.rows * new_size / img.cols),
0, 0, CV_INTER_LINEAR);
} else {
cv::resize(img, res, cv::Size(new_size * img.cols / img.rows, new_size),
0, 0, CV_INTER_LINEAR);
}
encode_buf.clear();
CHECK(cv::imencode(".jpg", res, encode_buf, encode_params));
size_t bsize = blob.size();
blob.resize(bsize + encode_buf.size());
memcpy(BeginPtr(blob) + bsize,
BeginPtr(encode_buf), encode_buf.size());
} else {
size_t bsize = blob.size();
blob.resize(bsize + decode_buf.size());
memcpy(BeginPtr(blob) + bsize,
BeginPtr(decode_buf), decode_buf.size());
}
writer.WriteRecord(BeginPtr(blob), blob.size());
// write header
++imcnt;
if (imcnt % 1000 == 0) {
LOG(INFO) << imcnt << " images processed, " << GetTime() - tstart << " sec elapsed";
}
}
LOG(INFO) << "Total: " << imcnt << " images processed, " << GetTime() - tstart << " sec elapsed";
delete fo;
delete flist;
return 0;
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: cppdep.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: mh $ $Date: 2001-02-16 14:04:14 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* 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., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (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.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#if SUPD < 356
#include <tools.hxx>
#else
#include <list.hxx>
#include <string.hxx>
#endif
#define PATH_SEP ":"
#define DIR_SEP "/"
DECLARE_LIST( ByteStringList, ByteString * );
class CppDep
{
ByteString aSourceFile;
ByteStringList *pSearchPath;
protected:
ByteStringList *pFileList;
ByteStringList *pSources;
BOOL Search( ByteString aFileName );
ByteString Exists( ByteString aFileName );
ByteString IsIncludeStatement( ByteString aLine );
public:
CppDep( ByteString aFileName );
CppDep();
~CppDep();
virtual void Execute();
ByteStringList* GetDepList(){return pFileList;}
BOOL AddSearchPath( const char* aPath );
BOOL AddSource( const char * aSource );
};
<commit_msg>INTEGRATION: CWS vclcleanup02 (1.2.194); FILE MERGED 2003/12/04 17:22:25 mt 1.2.194.1: #i23061# Removed SUPD stuff<commit_after>/*************************************************************************
*
* $RCSfile: cppdep.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: vg $ $Date: 2004-01-06 18:28:36 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* 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., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (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.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#include <list.hxx>
#include <string.hxx>
#define PATH_SEP ":"
#define DIR_SEP "/"
DECLARE_LIST( ByteStringList, ByteString * );
class CppDep
{
ByteString aSourceFile;
ByteStringList *pSearchPath;
protected:
ByteStringList *pFileList;
ByteStringList *pSources;
BOOL Search( ByteString aFileName );
ByteString Exists( ByteString aFileName );
ByteString IsIncludeStatement( ByteString aLine );
public:
CppDep( ByteString aFileName );
CppDep();
~CppDep();
virtual void Execute();
ByteStringList* GetDepList(){return pFileList;}
BOOL AddSearchPath( const char* aPath );
BOOL AddSource( const char * aSource );
};
<|endoftext|>
|
<commit_before>/* This file is part of Strigi Desktop Search
*
* Copyright (C) 2007 Jos van den Oever <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* 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
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "diranalyzer.h"
#include "indexwriter.h"
#include "indexmanager.h"
#include "indexreader.h"
#include "filelister.h"
#include "analysisresult.h"
#include "strigi_thread.h"
#include "fileinputstream.h"
#include <map>
#include <iostream>
#include <sys/stat.h>
using namespace Strigi;
using namespace std;
class DirAnalyzer::Private {
public:
//FileLister filelister;
DirLister dirlister;
IndexManager& manager;
AnalyzerConfiguration& config;
StreamAnalyzer analyzer;
STRIGI_MUTEX_DEFINE(updateMutex);
AnalysisCaller* caller;
Private(IndexManager& m, AnalyzerConfiguration& c)
:dirlister(&c), manager(m), config(c), analyzer(c) {
STRIGI_MUTEX_INIT(&updateMutex);
analyzer.setIndexWriter(*manager.indexWriter());
}
~Private() {
STRIGI_MUTEX_DESTROY(&updateMutex);
}
int analyzeDir(const string& dir, int nthreads, AnalysisCaller* caller,
const string& lastToSkip);
int updateDirs(const vector<string>& dir, int nthreads,
AnalysisCaller* caller);
void analyze(StreamAnalyzer*);
void update(StreamAnalyzer*);
int analyzeFile(const string& path, time_t mtime, bool realfile);
};
struct DA {
StreamAnalyzer* streamanalyzer;
DirAnalyzer::Private* diranalyzer;
};
extern "C" // Linkage for functions passed to pthread_create matters
{
void*
analyzeInThread(void* d) {
DA* a = static_cast<DA*>(d);
a->diranalyzer->analyze(a->streamanalyzer);
delete a;
STRIGI_THREAD_EXIT(0);
return 0; // Return bogus value
}
void*
updateInThread(void* d) {
DA* a = static_cast<DA*>(d);
a->diranalyzer->update(a->streamanalyzer);
delete a;
STRIGI_THREAD_EXIT(0);
return 0; // Return bogus value
}
}
DirAnalyzer::DirAnalyzer(IndexManager& manager, AnalyzerConfiguration& conf)
:p(new Private(manager, conf)) {
}
DirAnalyzer::~DirAnalyzer() {
delete p;
}
int
DirAnalyzer::Private::analyzeFile(const string& path, time_t mtime,
bool realfile) {
AnalysisResult analysisresult(path, mtime, *manager.indexWriter(),
analyzer);
if (realfile) {
FileInputStream file(path.c_str());
return analysisresult.index(&file);
} else {
return analysisresult.index(0);
}
}
void
DirAnalyzer::Private::analyze(StreamAnalyzer* analyzer) {
IndexWriter& indexWriter = *manager.indexWriter();
try {
string parentpath;
time_t parentmtime;
vector<pair<string, time_t> > dirfiles;
int r = dirlister.nextDir(parentpath, dirfiles);
cerr << "path:" << parentpath << " " << r << " " << dirfiles.size() <<
endl;
while (r == 0 && (caller == 0 || caller->continueAnalysis())) {
vector<pair<string, time_t> >::const_iterator end
= dirfiles.end();
for (vector<pair<string, time_t> >::const_iterator i
= dirfiles.begin(); i != end; ++i) {
const string& filepath(i->first);
cerr << "filepath:" << filepath << endl;
time_t mtime = i->second;
AnalysisResult analysisresult(filepath, mtime,
indexWriter, *analyzer, parentpath);
FileInputStream file(filepath.c_str());
if (file.status() == Ok) {
analysisresult.index(&file);
} else {
analysisresult.index(0);
}
}
r = dirlister.nextDir(parentpath, dirfiles);
}
} catch(...) {
fprintf(stderr, "Unknown error\n");
}
}
void
DirAnalyzer::Private::update(StreamAnalyzer* analyzer) {
IndexReader* reader = manager.indexReader();
vector<pair<string, time_t> > dirfiles;
map<string, time_t> dbdirfiles;
vector<string> toDelete;
vector<pair<string, time_t> > toIndex;
try {
string path;
// loop over all files that exist in the index
int r = dirlister.nextDir(path, dirfiles);
while (r >= 0 && (caller == 0 || caller->continueAnalysis())) {
cerr << "r: " << r << " " << path << " " << dirfiles.size() << endl;
if (r < 0) {
continue;
}
// get the files that are in the current database
reader->getChildren(path, dbdirfiles);
// get all files in this directory
vector<pair<string, time_t> >::const_iterator end
= dirfiles.end();
for (vector<pair<string, time_t> >::const_iterator i
= dirfiles.begin(); i != end; ++i) {
const string& filepath(i->first);
time_t mtime = i->second;
// check if this file is new or not
map<string, time_t>::iterator j = dbdirfiles.find(filepath);
bool newfile = j == dbdirfiles.end();
bool updatedfile = !newfile && j->second != mtime;
// if the file is update we delete it in this loop
// if it is new, it should not be in the list anyway
// otherwise we should _not_ delete it and remove it from the
// to be deleted list
if (updatedfile || !newfile) {
dbdirfiles.erase(j);
}
// if the file has not yet been indexed or if the mtime has
// changed, index it
if (updatedfile) {
toDelete.push_back(filepath);
}
if (newfile || updatedfile) {
toIndex.push_back(make_pair(filepath, mtime));
}
}
manager.indexWriter()->deleteEntries(toDelete);
vector<pair<string, time_t> >::const_iterator fend = toIndex.end();
for (vector<pair<string, time_t> >::const_iterator i
= toIndex.begin(); i != fend; ++i) {
AnalysisResult analysisresult(i->first, i->second,
*manager.indexWriter(), *analyzer);
FileInputStream file(path.c_str());
if (file.status() == Ok) {
analysisresult.index(&file);
} else {
analysisresult.index(0);
}
}
toDelete.clear();
toIndex.clear();
r = dirlister.nextDir(path, dirfiles);
}
} catch(...) {
fprintf(stderr, "Unknown error\n");
}
}
int
DirAnalyzer::analyzeDir(const string& dir, int nthreads, AnalysisCaller* c,
const string& lastToSkip) {
return p->analyzeDir(dir, nthreads, c, lastToSkip);
}
int
DirAnalyzer::Private::analyzeDir(const string& dir, int nthreads,
AnalysisCaller* c, const string& lastToSkip) {
caller = c;
// check if the path exists and if it is a file or a directory
struct stat s;
int retval = stat(dir.c_str(), &s);
time_t mtime = (retval == -1) ?0 :s.st_mtime;
retval = analyzeFile(dir, mtime, S_ISREG(s.st_mode));
// if the path does not point to a directory, return
if (!S_ISDIR(s.st_mode)) {
manager.indexWriter()->commit();
return retval;
}
dirlister.startListing(dir);
if (lastToSkip.length()) {
dirlister.skipTillAfter(lastToSkip);
}
if (nthreads < 1) nthreads = 1;
vector<StreamAnalyzer*> analyzers(nthreads);
analyzers[0] = &analyzer;
for (int i=1; i<nthreads; ++i) {
analyzers[i] = new StreamAnalyzer(config);
analyzers[i]->setIndexWriter(*manager.indexWriter());
}
vector<STRIGI_THREAD_TYPE> threads;
threads.resize(nthreads-1);
for (int i=1; i<nthreads; i++) {
DA* da = new DA();
da->diranalyzer = this;
da->streamanalyzer = analyzers[i];
STRIGI_THREAD_CREATE(&threads[i-1], analyzeInThread, da);
}
analyze(analyzers[0]);
for (int i=1; i<nthreads; i++) {
STRIGI_THREAD_JOIN(threads[i-1]);
delete analyzers[i];
}
manager.indexWriter()->commit();
return 0;
}
int
DirAnalyzer::updateDir(const string& dir, int nthreads, AnalysisCaller* caller){
vector<string> dirs;
dirs.push_back(dir);
return p->updateDirs(dirs, nthreads, caller);
}
int
DirAnalyzer::Private::updateDirs(const vector<string>& dirs, int nthreads,
AnalysisCaller* c) {
IndexReader* reader = manager.indexReader();
if (reader == 0) return -1;
caller = c;
// create the streamanalyzers
if (nthreads < 1) nthreads = 1;
vector<StreamAnalyzer*> analyzers(nthreads);
analyzers[0] = &analyzer;
for (int i=1; i<nthreads; ++i) {
analyzers[i] = new StreamAnalyzer(config);
analyzers[i]->setIndexWriter(*manager.indexWriter());
}
vector<STRIGI_THREAD_TYPE> threads;
threads.resize(nthreads-1);
// loop over all directories that should be updated
for (vector<string>::const_iterator d =dirs.begin(); d != dirs.end(); ++d) {
dirlister.startListing(*d);
for (int i=1; i<nthreads; i++) {
DA* da = new DA();
da->diranalyzer = this;
da->streamanalyzer = analyzers[i];
STRIGI_THREAD_CREATE(&threads[i-1], updateInThread, da);
}
update(analyzers[0]);
// wait until all threads have finished
for (int i=1; i<nthreads; i++) {
STRIGI_THREAD_JOIN(threads[i-1]);
}
dirlister.stopListing();
}
// clean up the analyzers
for (int i=1; i<nthreads; i++) {
delete analyzers[i];
}
// remove the files that were not encountered from the index
/* vector<string> todelete(1);
map<string,time_t>::iterator it = dbfiles.begin();
while (it != dbfiles.end()) {
todelete[0].assign(it->first);
manager.indexWriter()->deleteEntries(todelete);
++it;
}
dbfiles.clear();*/
return 0;
}
int
DirAnalyzer::updateDirs(const vector<string>& dirs, int nthreads,
AnalysisCaller* caller) {
return p->updateDirs(dirs, nthreads, caller);
}
<commit_msg>remove unused variable<commit_after>/* This file is part of Strigi Desktop Search
*
* Copyright (C) 2007 Jos van den Oever <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* 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
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "diranalyzer.h"
#include "indexwriter.h"
#include "indexmanager.h"
#include "indexreader.h"
#include "filelister.h"
#include "analysisresult.h"
#include "strigi_thread.h"
#include "fileinputstream.h"
#include <map>
#include <iostream>
#include <sys/stat.h>
using namespace Strigi;
using namespace std;
class DirAnalyzer::Private {
public:
//FileLister filelister;
DirLister dirlister;
IndexManager& manager;
AnalyzerConfiguration& config;
StreamAnalyzer analyzer;
STRIGI_MUTEX_DEFINE(updateMutex);
AnalysisCaller* caller;
Private(IndexManager& m, AnalyzerConfiguration& c)
:dirlister(&c), manager(m), config(c), analyzer(c) {
STRIGI_MUTEX_INIT(&updateMutex);
analyzer.setIndexWriter(*manager.indexWriter());
}
~Private() {
STRIGI_MUTEX_DESTROY(&updateMutex);
}
int analyzeDir(const string& dir, int nthreads, AnalysisCaller* caller,
const string& lastToSkip);
int updateDirs(const vector<string>& dir, int nthreads,
AnalysisCaller* caller);
void analyze(StreamAnalyzer*);
void update(StreamAnalyzer*);
int analyzeFile(const string& path, time_t mtime, bool realfile);
};
struct DA {
StreamAnalyzer* streamanalyzer;
DirAnalyzer::Private* diranalyzer;
};
extern "C" // Linkage for functions passed to pthread_create matters
{
void*
analyzeInThread(void* d) {
DA* a = static_cast<DA*>(d);
a->diranalyzer->analyze(a->streamanalyzer);
delete a;
STRIGI_THREAD_EXIT(0);
return 0; // Return bogus value
}
void*
updateInThread(void* d) {
DA* a = static_cast<DA*>(d);
a->diranalyzer->update(a->streamanalyzer);
delete a;
STRIGI_THREAD_EXIT(0);
return 0; // Return bogus value
}
}
DirAnalyzer::DirAnalyzer(IndexManager& manager, AnalyzerConfiguration& conf)
:p(new Private(manager, conf)) {
}
DirAnalyzer::~DirAnalyzer() {
delete p;
}
int
DirAnalyzer::Private::analyzeFile(const string& path, time_t mtime,
bool realfile) {
AnalysisResult analysisresult(path, mtime, *manager.indexWriter(),
analyzer);
if (realfile) {
FileInputStream file(path.c_str());
return analysisresult.index(&file);
} else {
return analysisresult.index(0);
}
}
void
DirAnalyzer::Private::analyze(StreamAnalyzer* analyzer) {
IndexWriter& indexWriter = *manager.indexWriter();
try {
string parentpath;
vector<pair<string, time_t> > dirfiles;
int r = dirlister.nextDir(parentpath, dirfiles);
cerr << "path:" << parentpath << " " << r << " " << dirfiles.size() <<
endl;
while (r == 0 && (caller == 0 || caller->continueAnalysis())) {
vector<pair<string, time_t> >::const_iterator end
= dirfiles.end();
for (vector<pair<string, time_t> >::const_iterator i
= dirfiles.begin(); i != end; ++i) {
const string& filepath(i->first);
cerr << "filepath:" << filepath << endl;
time_t mtime = i->second;
AnalysisResult analysisresult(filepath, mtime,
indexWriter, *analyzer, parentpath);
FileInputStream file(filepath.c_str());
if (file.status() == Ok) {
analysisresult.index(&file);
} else {
analysisresult.index(0);
}
}
r = dirlister.nextDir(parentpath, dirfiles);
}
} catch(...) {
fprintf(stderr, "Unknown error\n");
}
}
void
DirAnalyzer::Private::update(StreamAnalyzer* analyzer) {
IndexReader* reader = manager.indexReader();
vector<pair<string, time_t> > dirfiles;
map<string, time_t> dbdirfiles;
vector<string> toDelete;
vector<pair<string, time_t> > toIndex;
try {
string path;
// loop over all files that exist in the index
int r = dirlister.nextDir(path, dirfiles);
while (r >= 0 && (caller == 0 || caller->continueAnalysis())) {
cerr << "r: " << r << " " << path << " " << dirfiles.size() << endl;
if (r < 0) {
continue;
}
// get the files that are in the current database
reader->getChildren(path, dbdirfiles);
// get all files in this directory
vector<pair<string, time_t> >::const_iterator end
= dirfiles.end();
for (vector<pair<string, time_t> >::const_iterator i
= dirfiles.begin(); i != end; ++i) {
const string& filepath(i->first);
time_t mtime = i->second;
// check if this file is new or not
map<string, time_t>::iterator j = dbdirfiles.find(filepath);
bool newfile = j == dbdirfiles.end();
bool updatedfile = !newfile && j->second != mtime;
// if the file is update we delete it in this loop
// if it is new, it should not be in the list anyway
// otherwise we should _not_ delete it and remove it from the
// to be deleted list
if (updatedfile || !newfile) {
dbdirfiles.erase(j);
}
// if the file has not yet been indexed or if the mtime has
// changed, index it
if (updatedfile) {
toDelete.push_back(filepath);
}
if (newfile || updatedfile) {
toIndex.push_back(make_pair(filepath, mtime));
}
}
manager.indexWriter()->deleteEntries(toDelete);
vector<pair<string, time_t> >::const_iterator fend = toIndex.end();
for (vector<pair<string, time_t> >::const_iterator i
= toIndex.begin(); i != fend; ++i) {
AnalysisResult analysisresult(i->first, i->second,
*manager.indexWriter(), *analyzer);
FileInputStream file(path.c_str());
if (file.status() == Ok) {
analysisresult.index(&file);
} else {
analysisresult.index(0);
}
}
toDelete.clear();
toIndex.clear();
r = dirlister.nextDir(path, dirfiles);
}
} catch(...) {
fprintf(stderr, "Unknown error\n");
}
}
int
DirAnalyzer::analyzeDir(const string& dir, int nthreads, AnalysisCaller* c,
const string& lastToSkip) {
return p->analyzeDir(dir, nthreads, c, lastToSkip);
}
int
DirAnalyzer::Private::analyzeDir(const string& dir, int nthreads,
AnalysisCaller* c, const string& lastToSkip) {
caller = c;
// check if the path exists and if it is a file or a directory
struct stat s;
int retval = stat(dir.c_str(), &s);
time_t mtime = (retval == -1) ?0 :s.st_mtime;
retval = analyzeFile(dir, mtime, S_ISREG(s.st_mode));
// if the path does not point to a directory, return
if (!S_ISDIR(s.st_mode)) {
manager.indexWriter()->commit();
return retval;
}
dirlister.startListing(dir);
if (lastToSkip.length()) {
dirlister.skipTillAfter(lastToSkip);
}
if (nthreads < 1) nthreads = 1;
vector<StreamAnalyzer*> analyzers(nthreads);
analyzers[0] = &analyzer;
for (int i=1; i<nthreads; ++i) {
analyzers[i] = new StreamAnalyzer(config);
analyzers[i]->setIndexWriter(*manager.indexWriter());
}
vector<STRIGI_THREAD_TYPE> threads;
threads.resize(nthreads-1);
for (int i=1; i<nthreads; i++) {
DA* da = new DA();
da->diranalyzer = this;
da->streamanalyzer = analyzers[i];
STRIGI_THREAD_CREATE(&threads[i-1], analyzeInThread, da);
}
analyze(analyzers[0]);
for (int i=1; i<nthreads; i++) {
STRIGI_THREAD_JOIN(threads[i-1]);
delete analyzers[i];
}
manager.indexWriter()->commit();
return 0;
}
int
DirAnalyzer::updateDir(const string& dir, int nthreads, AnalysisCaller* caller){
vector<string> dirs;
dirs.push_back(dir);
return p->updateDirs(dirs, nthreads, caller);
}
int
DirAnalyzer::Private::updateDirs(const vector<string>& dirs, int nthreads,
AnalysisCaller* c) {
IndexReader* reader = manager.indexReader();
if (reader == 0) return -1;
caller = c;
// create the streamanalyzers
if (nthreads < 1) nthreads = 1;
vector<StreamAnalyzer*> analyzers(nthreads);
analyzers[0] = &analyzer;
for (int i=1; i<nthreads; ++i) {
analyzers[i] = new StreamAnalyzer(config);
analyzers[i]->setIndexWriter(*manager.indexWriter());
}
vector<STRIGI_THREAD_TYPE> threads;
threads.resize(nthreads-1);
// loop over all directories that should be updated
for (vector<string>::const_iterator d =dirs.begin(); d != dirs.end(); ++d) {
dirlister.startListing(*d);
for (int i=1; i<nthreads; i++) {
DA* da = new DA();
da->diranalyzer = this;
da->streamanalyzer = analyzers[i];
STRIGI_THREAD_CREATE(&threads[i-1], updateInThread, da);
}
update(analyzers[0]);
// wait until all threads have finished
for (int i=1; i<nthreads; i++) {
STRIGI_THREAD_JOIN(threads[i-1]);
}
dirlister.stopListing();
}
// clean up the analyzers
for (int i=1; i<nthreads; i++) {
delete analyzers[i];
}
// remove the files that were not encountered from the index
/* vector<string> todelete(1);
map<string,time_t>::iterator it = dbfiles.begin();
while (it != dbfiles.end()) {
todelete[0].assign(it->first);
manager.indexWriter()->deleteEntries(todelete);
++it;
}
dbfiles.clear();*/
return 0;
}
int
DirAnalyzer::updateDirs(const vector<string>& dirs, int nthreads,
AnalysisCaller* caller) {
return p->updateDirs(dirs, nthreads, caller);
}
<|endoftext|>
|
<commit_before>/////////////////////////////////////////////////////////////////////////////
//
// BSD 3-Clause License
//
// Copyright (c) 2019, The Regents of the University of California
// 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 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 "stt/SteinerTreeBuilder.h"
#include "stt/LinesRenderer.h"
#include "stt/flute.h"
#include "stt/pdrev.h"
#include <map>
#include <vector>
#include "ord/OpenRoad.hh"
#include "odb/db.h"
namespace stt {
SteinerTreeBuilder::SteinerTreeBuilder() :
alpha_(0.3),
min_fanout_alpha_({0, -1}),
min_hpwl_alpha_({0, -1}),
logger_(nullptr),
db_(nullptr)
{
}
void SteinerTreeBuilder::init(odb::dbDatabase* db, Logger* logger)
{
db_ = db;
logger_ = logger;
}
Tree SteinerTreeBuilder::makeSteinerTree(std::vector<int>& x,
std::vector<int>& y,
int drvr_index)
{
Tree tree = makeSteinerTree(x, y, drvr_index, alpha_);
return tree;
}
Tree SteinerTreeBuilder::makeSteinerTree(odb::dbNet* net,
std::vector<int>& x,
std::vector<int>& y,
int drvr_index)
{
float net_alpha = alpha_;
int min_fanout = min_fanout_alpha_.first;
int min_hpwl = min_hpwl_alpha_.first;
if (net_alpha_map_.find(net) != net_alpha_map_.end()) {
net_alpha = net_alpha_map_[net];
} else if (min_hpwl > 0) {
if (computeHPWL(net) >= min_hpwl) {
net_alpha = min_hpwl_alpha_.second;
}
} else if (min_fanout > 0) {
if (net->getTermCount()-1 >= min_fanout) {
net_alpha = min_fanout_alpha_.second;
}
}
return makeSteinerTree(x, y, drvr_index, net_alpha);
}
Tree SteinerTreeBuilder::makeSteinerTree(std::vector<int>& x,
std::vector<int>& y,
int drvr_index,
float alpha)
{
if (alpha > 0.0)
return pdr::primDijkstra(x, y, drvr_index, alpha, logger_);
else
return flt::flute(x, y, flute_accuracy);
}
Tree SteinerTreeBuilder::makeSteinerTree(const std::vector<int>& x,
const std::vector<int>& y,
const std::vector<int>& s,
int accuracy)
{
return flt::flutes(x, y, s, accuracy);
}
static bool rectAreaZero(const odb::Rect &rect)
{
return rect.xMin() == rect.xMax() && rect.yMin() == rect.yMax();
}
// This checks whether the tree has the property that no two
// non-adjacent edges have intersecting bounding boxes. If
// they do it is a failure as embedding those egdes may cause
// overlap between them.
bool SteinerTreeBuilder::checkTree(const Tree& tree) const
{
// Such high fanout nets are going to get buffered so
// we don't need to worry about them.
if (tree.deg > 100) {
return true;
}
std::vector<odb::Rect> rects;
for (int i = 0; i < tree.branchCount(); ++i) {
const Branch& branch = tree.branch[i];
const int x1 = branch.x;
const int y1 = branch.y;
const Branch& neighbor = tree.branch[branch.n];
const int x2 = neighbor.x;
const int y2 = neighbor.y;
rects.emplace_back(x1, y1, x2, y2);
}
for (auto i = 0; i < rects.size(); ++i) {
for (auto j = i + 1; j < rects.size(); ++j) {
const Branch& b1 = tree.branch[i];
const Branch& b2 = tree.branch[j];
const odb::Rect& r1 = rects[i];
const odb::Rect& r2 = rects[j];
if (!rectAreaZero(r1)
&& !rectAreaZero(r2)
&& r1.intersects(r2)
&& b1.n != j
&& b2.n != i
&& b1.n != b2.n) {
debugPrint(logger_, utl::STT, "check", 1,
"check failed ({}, {}) ({}, {}) [{}, {}] vs ({}, {}) ({}, {}) [{}, {}] degree={}",
r1.xMin(), r1.yMin(), r1.xMax(), r1.yMax(),
i, b1.n,
r2.xMin(), r2.yMin(), r2.xMax(), r2.yMax(),
j, b2.n, tree.deg);
return false;
}
}
}
return true;
}
////////////////////////////////////////////////////////////////
void SteinerTreeBuilder::setAlpha(float alpha)
{
alpha_ = alpha;
}
float SteinerTreeBuilder::getAlpha(const odb::dbNet* net) const
{
float net_alpha = net_alpha_map_.find(net) != net_alpha_map_.end() ?
net_alpha_map_.at(net) : alpha_;
return net_alpha;
}
void SteinerTreeBuilder::setNetAlpha(const odb::dbNet* net, float alpha)
{
net_alpha_map_[net] = alpha;
}
void SteinerTreeBuilder::setMinFanoutAlpha(int min_fanout, float alpha)
{
min_fanout_alpha_ = {min_fanout, alpha};
}
void SteinerTreeBuilder::setMinHPWLAlpha(int min_hpwl, float alpha)
{
min_hpwl_alpha_ = {min_hpwl, alpha};
}
int SteinerTreeBuilder::computeHPWL(odb::dbNet* net)
{
int min_x = std::numeric_limits<int>::max();
int min_y = std::numeric_limits<int>::max();
int max_x = std::numeric_limits<int>::min();
int max_y = std::numeric_limits<int>::min();
for (odb::dbITerm* iterm : net->getITerms()) {
odb::dbPlacementStatus status = iterm->getInst()->getPlacementStatus();
if (status != odb::dbPlacementStatus::NONE &&
status != odb::dbPlacementStatus::UNPLACED) {
int x, y;
iterm->getAvgXY(&x, &y);
min_x = std::min(min_x, x);
max_x = std::max(max_x, x);
min_y = std::min(min_y, y);
max_y = std::max(max_y, y);
} else {
logger_->error(utl::STT, 4, "Net {} is connected to unplaced instance {}.",
net->getName(),
iterm->getInst()->getName());
}
}
for (odb::dbBTerm* bterm : net->getBTerms()) {
if (bterm->getFirstPinPlacementStatus() != odb::dbPlacementStatus::NONE ||
bterm->getFirstPinPlacementStatus() != odb::dbPlacementStatus::UNPLACED) {
int x, y;
bterm->getFirstPinLocation(x, y);
min_x = std::min(min_x, x);
max_x = std::max(max_x, x);
min_y = std::min(min_y, y);
max_y = std::max(max_y, y);
} else {
logger_->error(utl::STT, 5, "Net {} is connected to unplaced pin {}.",
net->getName(),
bterm->getName());
}
}
int hpwl = (max_x - min_x) + (max_y - min_y);
return hpwl;
}
////////////////////////////////////////////////////////////////
typedef std::pair<int, int> PDedge;
typedef std::vector<std::set<PDedge>> PDedges;
static int findPathDepth(const Tree &tree,
int drvr_index);
static int findPathDepth(int node,
int from,
PDedges &edges,
int length);
static int findLocationIndex(const Tree &tree, int x, int y);
// Used by regressions.
void
reportSteinerTree(const stt::Tree &tree,
int drvr_x,
int drvr_y,
Logger *logger)
{
// flute mangles the x/y locations and pdrev moves the driver to 0
// so we have to find the driver location index.
int drvr_index = findLocationIndex(tree, drvr_x, drvr_y);
logger->report("Wire length = {} Path depth = {}",
tree.length,
findPathDepth(tree, drvr_index));
for (int i = 0; i < tree.branchCount(); i++) {
int x1 = tree.branch[i].x;
int y1 = tree.branch[i].y;
int parent = tree.branch[i].n;
int x2 = tree.branch[parent].x;
int y2 = tree.branch[parent].y;
int length = abs(x1-x2)+abs(y1-y2);
logger->report("{} ({} {}) neighbor {} length {}",
i, x1, y1, parent, length);
}
}
int
findLocationIndex(const Tree &tree,
int x,
int y)
{
for (int i = 0; i < tree.branchCount(); i++) {
int x1 = tree.branch[i].x;
int y1 = tree.branch[i].y;
if (x1 == x && y1 == y)
return i;
}
return -1;
}
static int findPathDepth(const Tree &tree,
int drvr_index)
{
int branch_count = tree.branchCount();
PDedges edges(branch_count);
if (branch_count > 2) {
for (int i = 0; i < branch_count; i++) {
const stt::Branch &branch = tree.branch[i];
int neighbor = branch.n;
if (neighbor != i) {
const Branch &neighbor_branch = tree.branch[neighbor];
int length = std::abs(branch.x - neighbor_branch.x)
+ std::abs(branch.y - neighbor_branch.y);
edges[neighbor].insert(PDedge(i, length));
edges[i].insert(PDedge(neighbor, length));
}
}
return findPathDepth(drvr_index, drvr_index, edges, 0);
}
else
return 0;
}
static int findPathDepth(int node,
int from,
PDedges &edges,
int length)
{
int max_length = length;
for (const PDedge &edge : edges[node]) {
int neighbor = edge.first;
int edge_length = edge.second;
if (neighbor != from)
max_length = std::max(max_length,
findPathDepth(neighbor, node, edges, length + edge_length));
}
return max_length;
}
////////////////////////////////////////////////////////////////
static LinesRenderer *LinesRenderer::lines_renderer = nullptr;
void
LinesRenderer::highlight(std::vector<std::pair<odb::Point, odb::Point>> &lines,
gui::Painter::Color color)
{
lines_ = lines;
color_ = color;
}
void
LinesRenderer::drawObjects(gui::Painter &painter)
{
if (!lines_.empty()) {
painter.setPen(color_, true);
for (int i = 0 ; i < lines_.size(); ++i) {
painter.drawLine(lines_[i].first, lines_[i].second);
}
}
}
void
highlightSteinerTree(const Tree &tree,
gui::Gui *gui)
{
if (gui) {
if (LinesRenderer::lines_renderer == nullptr) {
LinesRenderer::lines_renderer = new LinesRenderer();
gui->registerRenderer(LinesRenderer::lines_renderer);
}
std::vector<std::pair<odb::Point, odb::Point>> lines;
for (int i = 0; i < tree.branchCount(); i++) {
const stt::Branch &branch = tree.branch[i];
int x1 = branch.x;
int y1 = branch.y;
const stt::Branch &neighbor = tree.branch[branch.n];
int x2 = neighbor.x;
int y2 = neighbor.y;
lines.push_back(std::pair(odb::Point(x1, y1),
odb::Point(x2, y2)));
}
LinesRenderer::lines_renderer->highlight(lines, gui::Painter::red);
}
}
void Tree::printTree(utl::Logger* logger)
{
if (deg > 1) {
for (int i = 0; i < deg; i++)
logger->report(" {:2d}: x={:4g} y={:4g} e={}",
i, (float)branch[i].x, (float)branch[i].y, branch[i].n);
for (int i = deg; i < 2 * deg - 2; i++)
logger->report("s{:2d}: x={:4g} y={:4g} e={}",
i, (float)branch[i].x, (float)branch[i].y, branch[i].n);
logger->report("");
}
}
}
<commit_msg>stt compile error<commit_after>/////////////////////////////////////////////////////////////////////////////
//
// BSD 3-Clause License
//
// Copyright (c) 2019, The Regents of the University of California
// 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 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 "stt/SteinerTreeBuilder.h"
#include "stt/LinesRenderer.h"
#include "stt/flute.h"
#include "stt/pdrev.h"
#include <map>
#include <vector>
#include "ord/OpenRoad.hh"
#include "odb/db.h"
namespace stt {
SteinerTreeBuilder::SteinerTreeBuilder() :
alpha_(0.3),
min_fanout_alpha_({0, -1}),
min_hpwl_alpha_({0, -1}),
logger_(nullptr),
db_(nullptr)
{
}
void SteinerTreeBuilder::init(odb::dbDatabase* db, Logger* logger)
{
db_ = db;
logger_ = logger;
}
Tree SteinerTreeBuilder::makeSteinerTree(std::vector<int>& x,
std::vector<int>& y,
int drvr_index)
{
Tree tree = makeSteinerTree(x, y, drvr_index, alpha_);
return tree;
}
Tree SteinerTreeBuilder::makeSteinerTree(odb::dbNet* net,
std::vector<int>& x,
std::vector<int>& y,
int drvr_index)
{
float net_alpha = alpha_;
int min_fanout = min_fanout_alpha_.first;
int min_hpwl = min_hpwl_alpha_.first;
if (net_alpha_map_.find(net) != net_alpha_map_.end()) {
net_alpha = net_alpha_map_[net];
} else if (min_hpwl > 0) {
if (computeHPWL(net) >= min_hpwl) {
net_alpha = min_hpwl_alpha_.second;
}
} else if (min_fanout > 0) {
if (net->getTermCount()-1 >= min_fanout) {
net_alpha = min_fanout_alpha_.second;
}
}
return makeSteinerTree(x, y, drvr_index, net_alpha);
}
Tree SteinerTreeBuilder::makeSteinerTree(std::vector<int>& x,
std::vector<int>& y,
int drvr_index,
float alpha)
{
if (alpha > 0.0)
return pdr::primDijkstra(x, y, drvr_index, alpha, logger_);
else
return flt::flute(x, y, flute_accuracy);
}
Tree SteinerTreeBuilder::makeSteinerTree(const std::vector<int>& x,
const std::vector<int>& y,
const std::vector<int>& s,
int accuracy)
{
return flt::flutes(x, y, s, accuracy);
}
static bool rectAreaZero(const odb::Rect &rect)
{
return rect.xMin() == rect.xMax() && rect.yMin() == rect.yMax();
}
// This checks whether the tree has the property that no two
// non-adjacent edges have intersecting bounding boxes. If
// they do it is a failure as embedding those egdes may cause
// overlap between them.
bool SteinerTreeBuilder::checkTree(const Tree& tree) const
{
// Such high fanout nets are going to get buffered so
// we don't need to worry about them.
if (tree.deg > 100) {
return true;
}
std::vector<odb::Rect> rects;
for (int i = 0; i < tree.branchCount(); ++i) {
const Branch& branch = tree.branch[i];
const int x1 = branch.x;
const int y1 = branch.y;
const Branch& neighbor = tree.branch[branch.n];
const int x2 = neighbor.x;
const int y2 = neighbor.y;
rects.emplace_back(x1, y1, x2, y2);
}
for (auto i = 0; i < rects.size(); ++i) {
for (auto j = i + 1; j < rects.size(); ++j) {
const Branch& b1 = tree.branch[i];
const Branch& b2 = tree.branch[j];
const odb::Rect& r1 = rects[i];
const odb::Rect& r2 = rects[j];
if (!rectAreaZero(r1)
&& !rectAreaZero(r2)
&& r1.intersects(r2)
&& b1.n != j
&& b2.n != i
&& b1.n != b2.n) {
debugPrint(logger_, utl::STT, "check", 1,
"check failed ({}, {}) ({}, {}) [{}, {}] vs ({}, {}) ({}, {}) [{}, {}] degree={}",
r1.xMin(), r1.yMin(), r1.xMax(), r1.yMax(),
i, b1.n,
r2.xMin(), r2.yMin(), r2.xMax(), r2.yMax(),
j, b2.n, tree.deg);
return false;
}
}
}
return true;
}
////////////////////////////////////////////////////////////////
void SteinerTreeBuilder::setAlpha(float alpha)
{
alpha_ = alpha;
}
float SteinerTreeBuilder::getAlpha(const odb::dbNet* net) const
{
float net_alpha = net_alpha_map_.find(net) != net_alpha_map_.end() ?
net_alpha_map_.at(net) : alpha_;
return net_alpha;
}
void SteinerTreeBuilder::setNetAlpha(const odb::dbNet* net, float alpha)
{
net_alpha_map_[net] = alpha;
}
void SteinerTreeBuilder::setMinFanoutAlpha(int min_fanout, float alpha)
{
min_fanout_alpha_ = {min_fanout, alpha};
}
void SteinerTreeBuilder::setMinHPWLAlpha(int min_hpwl, float alpha)
{
min_hpwl_alpha_ = {min_hpwl, alpha};
}
int SteinerTreeBuilder::computeHPWL(odb::dbNet* net)
{
int min_x = std::numeric_limits<int>::max();
int min_y = std::numeric_limits<int>::max();
int max_x = std::numeric_limits<int>::min();
int max_y = std::numeric_limits<int>::min();
for (odb::dbITerm* iterm : net->getITerms()) {
odb::dbPlacementStatus status = iterm->getInst()->getPlacementStatus();
if (status != odb::dbPlacementStatus::NONE &&
status != odb::dbPlacementStatus::UNPLACED) {
int x, y;
iterm->getAvgXY(&x, &y);
min_x = std::min(min_x, x);
max_x = std::max(max_x, x);
min_y = std::min(min_y, y);
max_y = std::max(max_y, y);
} else {
logger_->error(utl::STT, 4, "Net {} is connected to unplaced instance {}.",
net->getName(),
iterm->getInst()->getName());
}
}
for (odb::dbBTerm* bterm : net->getBTerms()) {
if (bterm->getFirstPinPlacementStatus() != odb::dbPlacementStatus::NONE ||
bterm->getFirstPinPlacementStatus() != odb::dbPlacementStatus::UNPLACED) {
int x, y;
bterm->getFirstPinLocation(x, y);
min_x = std::min(min_x, x);
max_x = std::max(max_x, x);
min_y = std::min(min_y, y);
max_y = std::max(max_y, y);
} else {
logger_->error(utl::STT, 5, "Net {} is connected to unplaced pin {}.",
net->getName(),
bterm->getName());
}
}
int hpwl = (max_x - min_x) + (max_y - min_y);
return hpwl;
}
////////////////////////////////////////////////////////////////
typedef std::pair<int, int> PDedge;
typedef std::vector<std::set<PDedge>> PDedges;
static int findPathDepth(const Tree &tree,
int drvr_index);
static int findPathDepth(int node,
int from,
PDedges &edges,
int length);
static int findLocationIndex(const Tree &tree, int x, int y);
// Used by regressions.
void
reportSteinerTree(const stt::Tree &tree,
int drvr_x,
int drvr_y,
Logger *logger)
{
// flute mangles the x/y locations and pdrev moves the driver to 0
// so we have to find the driver location index.
int drvr_index = findLocationIndex(tree, drvr_x, drvr_y);
logger->report("Wire length = {} Path depth = {}",
tree.length,
findPathDepth(tree, drvr_index));
for (int i = 0; i < tree.branchCount(); i++) {
int x1 = tree.branch[i].x;
int y1 = tree.branch[i].y;
int parent = tree.branch[i].n;
int x2 = tree.branch[parent].x;
int y2 = tree.branch[parent].y;
int length = abs(x1-x2)+abs(y1-y2);
logger->report("{} ({} {}) neighbor {} length {}",
i, x1, y1, parent, length);
}
}
int
findLocationIndex(const Tree &tree,
int x,
int y)
{
for (int i = 0; i < tree.branchCount(); i++) {
int x1 = tree.branch[i].x;
int y1 = tree.branch[i].y;
if (x1 == x && y1 == y)
return i;
}
return -1;
}
static int findPathDepth(const Tree &tree,
int drvr_index)
{
int branch_count = tree.branchCount();
PDedges edges(branch_count);
if (branch_count > 2) {
for (int i = 0; i < branch_count; i++) {
const stt::Branch &branch = tree.branch[i];
int neighbor = branch.n;
if (neighbor != i) {
const Branch &neighbor_branch = tree.branch[neighbor];
int length = std::abs(branch.x - neighbor_branch.x)
+ std::abs(branch.y - neighbor_branch.y);
edges[neighbor].insert(PDedge(i, length));
edges[i].insert(PDedge(neighbor, length));
}
}
return findPathDepth(drvr_index, drvr_index, edges, 0);
}
else
return 0;
}
static int findPathDepth(int node,
int from,
PDedges &edges,
int length)
{
int max_length = length;
for (const PDedge &edge : edges[node]) {
int neighbor = edge.first;
int edge_length = edge.second;
if (neighbor != from)
max_length = std::max(max_length,
findPathDepth(neighbor, node, edges, length + edge_length));
}
return max_length;
}
////////////////////////////////////////////////////////////////
LinesRenderer *LinesRenderer::lines_renderer = nullptr;
void
LinesRenderer::highlight(std::vector<std::pair<odb::Point, odb::Point>> &lines,
gui::Painter::Color color)
{
lines_ = lines;
color_ = color;
}
void
LinesRenderer::drawObjects(gui::Painter &painter)
{
if (!lines_.empty()) {
painter.setPen(color_, true);
for (int i = 0 ; i < lines_.size(); ++i) {
painter.drawLine(lines_[i].first, lines_[i].second);
}
}
}
void
highlightSteinerTree(const Tree &tree,
gui::Gui *gui)
{
if (gui) {
if (LinesRenderer::lines_renderer == nullptr) {
LinesRenderer::lines_renderer = new LinesRenderer();
gui->registerRenderer(LinesRenderer::lines_renderer);
}
std::vector<std::pair<odb::Point, odb::Point>> lines;
for (int i = 0; i < tree.branchCount(); i++) {
const stt::Branch &branch = tree.branch[i];
int x1 = branch.x;
int y1 = branch.y;
const stt::Branch &neighbor = tree.branch[branch.n];
int x2 = neighbor.x;
int y2 = neighbor.y;
lines.push_back(std::pair(odb::Point(x1, y1),
odb::Point(x2, y2)));
}
LinesRenderer::lines_renderer->highlight(lines, gui::Painter::red);
}
}
void Tree::printTree(utl::Logger* logger)
{
if (deg > 1) {
for (int i = 0; i < deg; i++)
logger->report(" {:2d}: x={:4g} y={:4g} e={}",
i, (float)branch[i].x, (float)branch[i].y, branch[i].n);
for (int i = deg; i < 2 * deg - 2; i++)
logger->report("s{:2d}: x={:4g} y={:4g} e={}",
i, (float)branch[i].x, (float)branch[i].y, branch[i].n);
logger->report("");
}
}
}
<|endoftext|>
|
<commit_before>/*
* Copyright 2004-2014 Cray Inc.
* Other additional copyright holders may be indicated within.
*
* The entirety of this work is 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 <cstdio>
#include "driver.h"
#include "version.h"
#include "version_num.h"
void
get_version(char *v) {
v += sprintf(v, "%d.%s.%s", MAJOR_VERSION, MINOR_VERSION, UPDATE_VERSION);
if (strcmp(BUILD_VERSION, "") || developer)
sprintf(v, ".%s", BUILD_VERSION);
}
<commit_msg>Fix boolean expectation from strcmp.<commit_after>/*
* Copyright 2004-2014 Cray Inc.
* Other additional copyright holders may be indicated within.
*
* The entirety of this work is 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 <cstdio>
#include "driver.h"
#include "version.h"
#include "version_num.h"
void
get_version(char *v) {
v += sprintf(v, "%d.%s.%s", MAJOR_VERSION, MINOR_VERSION, UPDATE_VERSION);
if (!strcmp(BUILD_VERSION, "") || developer)
sprintf(v, ".%s", BUILD_VERSION);
}
<|endoftext|>
|
<commit_before>/*
* stdp.cpp
*
* Created on: Apr 2, 2009
* Author: Craig Rasmussen
*/
#include <assert.h>
#include <stdlib.h>
#include "LinearPostConnProbe.hpp"
#include "BiConn.hpp"
#include "Patterns.hpp"
#include <src/columns/HyPerCol.hpp>
#include <src/io/ConnectionProbe.hpp>
#include <src/io/GLDisplay.hpp>
#include <src/io/PostConnProbe.hpp>
#include <src/io/LinearActivityProbe.hpp>
#include <src/io/PointProbe.hpp>
#include <src/io/StatsProbe.hpp>
#include <src/layers/Gratings.hpp>
#include <src/layers/Movie.hpp>
#include <src/layers/Retina.hpp>
#include <src/layers/V1.hpp>
#include <src/connections/HyPerConn.hpp>
#include <src/connections/RandomConn.hpp>
#include <src/connections/KernelConn.hpp>
using namespace PV;
#undef DISPLAY
void dump_weights(PVPatch ** patches, int numPatches);
#undef INHIB
#undef L2
#undef L2INHIB
int main(int argc, char* argv[])
{
// create the managing hypercolumn
//
HyPerCol * hc = new HyPerCol("column", argc, argv);
// create the layers
//
//Image * image = new Movie("Image", hc, "input/earth-files.txt", 1.0);
//Image * image = new Patterns("Image", hc, RECTANGLES);
Image * image = new Patterns("Image", hc, BARS);
HyPerLayer * retinaOn = new Retina("RetinaOn", hc);
HyPerLayer * retinaOff = new Retina("RetinaOff", hc);
HyPerLayer * l1 = new V1("L1", hc);
#ifdef INHIB
HyPerLayer * l1Inh = new V1("L1Inh", hc);
#endif
#ifdef L2
HyPerLayer * l2 = new V1("L2", hc);
#endif
#ifdef L2INHIB
HyPerLayer * l2Inh = new V1("L2Inh", hc);
#endif
// connect the layers
//
HyPerConn * i_r1_c = new KernelConn("Image to RetinaOn Center", hc, image, retinaOn, CHANNEL_EXC);
HyPerConn * i_r1_s = new KernelConn("Image to RetinaOn Surround", hc, image, retinaOn, CHANNEL_INH);
HyPerConn * i_r0_c = new KernelConn("Image to RetinaOff Center", hc, image, retinaOff, CHANNEL_INH);
HyPerConn * i_r0_s = new KernelConn("Image to RetinaOff Surround", hc, image, retinaOff, CHANNEL_EXC);
HyPerConn * r1_l1 = new HyPerConn("RetinaOn to L1", hc, retinaOn, l1, CHANNEL_EXC);
HyPerConn * r0_l1 = new HyPerConn("RetinaOff to L1", hc, retinaOff, l1, CHANNEL_EXC);
#ifdef L2
HyPerConn * l1_l2 = new HyPerConn("L1 to L2", hc, l1, l2, CHANNEL_EXC);
#endif
#ifdef L2INHIB
HyPerConn * l2_l2Inh = new KernelConn("L2 to L2Inh", hc, l2, l2Inh, CHANNEL_EXC);
HyPerConn * l2Inh_l2 = new KernelConn("L2Inh to L2", hc, l2Inh, l2, CHANNEL_INH);
#endif
#ifdef INHIB
HyPerConn * l1_l1Inh = new KernelConn("L1 to L1Inh", hc, l1, l1Inh, CHANNEL_EXC);
HyPerConn * l1Inh_l1 = new KernelConn("L1Inh to L1", hc, l1Inh, l1, CHANNEL_INH);
#endif
#ifdef DISPLAY
GLDisplay * display = new GLDisplay(&argc, argv, hc, 2, 2);
display->setDelay(800);
display->setImage(image);
display->addLayer(retinaOn);
display->addLayer(retinaOff);
display->addLayer(l1);
#endif
// add probes
//
#undef LINEAR_PROBES
#ifdef LINEAR_PROBES
LayerProbe * rProbe0 = new LinearActivityProbe(hc, PV::DimX, 0, 0);
LayerProbe * rProbe1 = new LinearActivityProbe(hc, PV::DimX, 1, 0);
LayerProbe * rProbe2 = new LinearActivityProbe(hc, PV::DimX, 2, 0);
LayerProbe * rProbe3 = new LinearActivityProbe(hc, PV::DimX, 3, 0);
LayerProbe * rProbe4 = new LinearActivityProbe(hc, PV::DimX, 4, 0);
LayerProbe * rProbe5 = new LinearActivityProbe(hc, PV::DimX, 5, 0);
LayerProbe * rProbe6 = new LinearActivityProbe(hc, PV::DimX, 6, 0);
LayerProbe * rProbe7 = new LinearActivityProbe(hc, PV::DimX, 7, 0);
LayerProbe * rProbe8 = new LinearActivityProbe(hc, PV::DimX, 8, 0);
LayerProbe * rProbe9 = new LinearActivityProbe(hc, PV::DimX, 9, 0);
LayerProbe * rProbe10 = new LinearActivityProbe(hc, PV::DimX, 10, 0);
LayerProbe * rProbe11 = new LinearActivityProbe(hc, PV::DimX, 11, 0);
LayerProbe * rProbe12 = new LinearActivityProbe(hc, PV::DimX, 12, 0);
LayerProbe * rProbe13 = new LinearActivityProbe(hc, PV::DimX, 13, 0);
LayerProbe * rProbe14 = new LinearActivityProbe(hc, PV::DimX, 14, 0);
l2->insertProbe(rProbe0);
l2->insertProbe(rProbe1);
l2->insertProbe(rProbe2);
l2->insertProbe(rProbe3);
l2->insertProbe(rProbe4);
l2->insertProbe(rProbe5);
l2->insertProbe(rProbe6);
l2->insertProbe(rProbe7);
l2->insertProbe(rProbe8);
l2->insertProbe(rProbe9);
l2->insertProbe(rProbe10);
l2->insertProbe(rProbe11);
l2->insertProbe(rProbe12);
l2->insertProbe(rProbe13);
l2->insertProbe(rProbe14);
#endif
#define WRITE_KERNELS
#ifdef WRITE_KERNELS
const char * i_r1_s_filename = "i_r1_s_gauss.txt";
HyPerLayer * pre = i_r1_s->preSynapticLayer();
int npad = pre->clayer->loc.nPad;
int nx = pre->clayer->loc.nx;
int ny = pre->clayer->loc.ny;
int nf = pre->clayer->loc.nBands;
i_r1_s->writeTextWeights(i_r1_s_filename, nf*(nx+npad)/2 + nf*(nx+2*npad)*(ny+2*npad)/2);
const char * i_r0_s_filename = "i_r0_s_gauss.txt";
pre = i_r0_s->preSynapticLayer();
npad = pre->clayer->loc.nPad;
nx = pre->clayer->loc.nx;
ny = pre->clayer->loc.ny;
nf = pre->clayer->loc.nBands;
i_r0_s->writeTextWeights(i_r0_s_filename, nf*(nx+npad)/2 + nf*(nx+2*npad)*(ny+2*npad)/2);
#endif
//40
//LayerProbe * ptprobe1 = new PointProbe("l2_activity.txt", 9, 7, 0, "L2:");
//l2->insertProbe(ptprobe1);
//ConnectionProbe * cProbe = new ConnectionProbe(114);
//l1_l2->insertProbe(cProbe);
//ConnectionProbe * cProbe = new ConnectionProbe(277);
//i_r1_s->insertProbe(cProbe);
//PostConnProbe * pcProbe0 = new LinearPostConnProbe(PV::DimX, locY, 0);
//LayerProbe * rptprobe = new PointProbe(25, 0, 0, "R :");
//retina->insertProbe(rptprobe);
//LayerProbe * ptprobe1 = new PointProbe("l1_activity.txt", 98, 42, 0, "L1:");
//l1->insertProbe(ptprobe1);
//LayerProbe * ptprobe2 = new PointProbe("l1Inh_activity.txt", 24, 10, 0, "L1Inh:");
//l1Inh->insertProbe(ptprobe2);
//LayerProbe * ptprobe3 = new PointProbe("image_activity.txt", 17, 11, 0, "Image:");
//image->insertProbe(ptprobe3);
//int retinaplacement = 9;
//LayerProbe * ptprobe4 = new PointProbe("retinaOn_activity.txt", retinaplacement, 11, 0, "RetinaOn:");
//retinaOn->insertProbe(ptprobe4);
//LayerProbe * ptprobe5 = new PointProbe("retinaOff_activity.txt", retinaplacement, 11, 0, "RetinaOff:");
//retinaOff->insertProbe(ptprobe5);
//LayerProbe * ptprobe6 = new PointProbe("l1_activity.txt", 52, 40, 0, "L1:");
//l1->insertProbe(ptprobe6);
//LayerProbe * ptprobe7 = new PointProbe("l1Inh_activity.txt", 13, 10, 0, "L1Inh:");
//l1Inh->insertProbe(ptprobe7);
//PostConnProbe * pcOnProbe = new PostConnProbe(5474); //(245); // 8575=>127,66
//PostConnProbe * pcOffProbe = new PostConnProbe(5474); //(245); // 8575=>127,66
//PostConnProbe * pcInhProbe = new PostConnProbe(403);
//pcProbe->setImage(image);
//pcOnProbe->setOutputIndices(true);
//r0_l1->insertProbe(pcOffProbe);
//r1_l1->insertProbe(pcOnProbe);
//l1_l1Inh->insertProbe(pcInhProbe);
//StatsProbe * sProbe = new StatsProbe(PV::BufActivity, "l1");
//l1->insertProbe(sProbe);
// run the simulation
//
if (hc->columnId() == 0) {
printf("[0]: Running simulation ...\n"); fflush(stdout);
}
hc->run();
if (hc->columnId() == 0) {
printf("[0]: Finished\n");
}
/* clean up (HyPerCol owns layers and connections, don't delete them) */
delete hc;
return 0;
}
void dump_weights(PVPatch ** patches, int numPatches)
{
FILE * fp = fopen("wdump.txt", "w");
assert(fp != NULL);
int num = 0;
for (int k = 0; k < numPatches; k++) {
PVPatch * p = patches[k];
float * w = p->data;
int nkp = p->nx * p->ny * p->nf;
for (int i = 0; i < nkp; i++) {
fprintf(fp, "%d (%d,%d) %f\n", num, k, i, w[i]);
num += 1;
}
}
fclose(fp);
}
<commit_msg>Normal running version for STDP runs.<commit_after>/*
* stdp.cpp
*
* Created on: Apr 2, 2009
* Author: Craig Rasmussen
*/
#include <assert.h>
#include <stdlib.h>
#include "LinearPostConnProbe.hpp"
#include "BiConn.hpp"
#include "Patterns.hpp"
#include <src/columns/HyPerCol.hpp>
#include <src/io/ConnectionProbe.hpp>
#include <src/io/GLDisplay.hpp>
#include <src/io/PostConnProbe.hpp>
#include <src/io/LinearActivityProbe.hpp>
#include <src/io/PointProbe.hpp>
#include <src/io/StatsProbe.hpp>
#include <src/layers/Gratings.hpp>
#include <src/layers/Movie.hpp>
#include <src/layers/Retina.hpp>
#include <src/layers/V1.hpp>
#include <src/connections/HyPerConn.hpp>
#include <src/connections/RandomConn.hpp>
#include <src/connections/KernelConn.hpp>
using namespace PV;
#undef DISPLAY
void dump_weights(PVPatch ** patches, int numPatches);
#undef L2
#define INHIB
#undef L2INHIB
int main(int argc, char* argv[])
{
// create the managing hypercolumn
//
HyPerCol * hc = new HyPerCol("column", argc, argv);
// create the layers
//
//Image * image = new Movie("Image", hc, "input/earth-files.txt", 1.0);
//Image * image = new Patterns("Image", hc, RECTANGLES);
Image * image = new Patterns("Image", hc, BARS);
HyPerLayer * retinaOn = new Retina("RetinaOn", hc);
HyPerLayer * retinaOff = new Retina("RetinaOff", hc);
HyPerLayer * l1 = new V1("L1", hc);
#ifdef INHIB
HyPerLayer * l1Inh = new V1("L1Inh", hc);
#endif
#ifdef L2
HyPerLayer * l2 = new V1("L2", hc);
#endif
#ifdef L2INHIB
HyPerLayer * l2Inh = new V1("L2Inh", hc);
#endif
// connect the layers
//
HyPerConn * i_r1_c = new KernelConn("Image to RetinaOn Center", hc, image, retinaOn, CHANNEL_EXC);
HyPerConn * i_r1_s = new KernelConn("Image to RetinaOn Surround", hc, image, retinaOn, CHANNEL_INH);
HyPerConn * i_r0_c = new KernelConn("Image to RetinaOff Center", hc, image, retinaOff, CHANNEL_INH);
HyPerConn * i_r0_s = new KernelConn("Image to RetinaOff Surround", hc, image, retinaOff, CHANNEL_EXC);
HyPerConn * r1_l1 = new HyPerConn("RetinaOn to L1", hc, retinaOn, l1, CHANNEL_EXC);
HyPerConn * r0_l1 = new HyPerConn("RetinaOff to L1", hc, retinaOff, l1, CHANNEL_EXC);
#ifdef L2
HyPerConn * l1_l2 = new HyPerConn("L1 to L2", hc, l1, l2, CHANNEL_EXC);
#endif
#ifdef INHIB
HyPerConn * l1_l1Inh = new HyPerConn("L1 to L1Inh", hc, l1, l1Inh, CHANNEL_EXC);
HyPerConn * l1Inh_l1 = new KernelConn("L1Inh to L1", hc, l1Inh, l1, CHANNEL_INH);
#endif
#ifdef L2INHIB
HyPerConn * l2_l2Inh = new HyPerConn("L2 to L2Inh", hc, l2, l2Inh, CHANNEL_EXC);
HyPerConn * l2Inh_l2 = new KernelConn("L2Inh to L2", hc, l2Inh, l2, CHANNEL_INH);
#endif
#ifdef DISPLAY
GLDisplay * display = new GLDisplay(&argc, argv, hc, 2, 2);
display->setDelay(200);
display->setImage(image);
//display->addLayer(retinaOn);
//display->addLayer(retinaOff);
display->addLayer(l1);
display->addLayer(l2);
#endif
// add probes
//
#undef LINEAR_PROBES
#ifdef LINEAR_PROBES
LayerProbe * rProbe0 = new LinearActivityProbe(hc, PV::DimX, 0, 0);
LayerProbe * rProbe1 = new LinearActivityProbe(hc, PV::DimX, 1, 0);
LayerProbe * rProbe2 = new LinearActivityProbe(hc, PV::DimX, 2, 0);
LayerProbe * rProbe3 = new LinearActivityProbe(hc, PV::DimX, 3, 0);
LayerProbe * rProbe4 = new LinearActivityProbe(hc, PV::DimX, 4, 0);
LayerProbe * rProbe5 = new LinearActivityProbe(hc, PV::DimX, 5, 0);
LayerProbe * rProbe6 = new LinearActivityProbe(hc, PV::DimX, 6, 0);
LayerProbe * rProbe7 = new LinearActivityProbe(hc, PV::DimX, 7, 0);
LayerProbe * rProbe8 = new LinearActivityProbe(hc, PV::DimX, 8, 0);
LayerProbe * rProbe9 = new LinearActivityProbe(hc, PV::DimX, 9, 0);
LayerProbe * rProbe10 = new LinearActivityProbe(hc, PV::DimX, 10, 0);
LayerProbe * rProbe11 = new LinearActivityProbe(hc, PV::DimX, 11, 0);
LayerProbe * rProbe12 = new LinearActivityProbe(hc, PV::DimX, 12, 0);
LayerProbe * rProbe13 = new LinearActivityProbe(hc, PV::DimX, 13, 0);
LayerProbe * rProbe14 = new LinearActivityProbe(hc, PV::DimX, 14, 0);
l2->insertProbe(rProbe0);
l2->insertProbe(rProbe1);
l2->insertProbe(rProbe2);
l2->insertProbe(rProbe3);
l2->insertProbe(rProbe4);
l2->insertProbe(rProbe5);
l2->insertProbe(rProbe6);
l2->insertProbe(rProbe7);
l2->insertProbe(rProbe8);
l2->insertProbe(rProbe9);
l2->insertProbe(rProbe10);
l2->insertProbe(rProbe11);
l2->insertProbe(rProbe12);
l2->insertProbe(rProbe13);
l2->insertProbe(rProbe14);
#endif
#undef WRITE_KERNELS
#ifdef WRITE_KERNELS
l1_l1Inh->writeTextWeights("l1_l1inh_kernel.txt", 14);
const char * i_r1_s_filename = "i_r1_s_gauss.txt";
HyPerLayer * pre = i_r1_s->preSynapticLayer();
int npad = pre->clayer->loc.nPad;
int nx = pre->clayer->loc.nx;
int ny = pre->clayer->loc.ny;
int nf = pre->clayer->loc.nBands;
i_r1_s->writeTextWeights(i_r1_s_filename, nf*(nx+npad)/2 + nf*(nx+2*npad)*(ny+2*npad)/2);
const char * i_r0_s_filename = "i_r0_s_gauss.txt";
pre = i_r0_s->preSynapticLayer();
npad = pre->clayer->loc.nPad;
nx = pre->clayer->loc.nx;
ny = pre->clayer->loc.ny;
nf = pre->clayer->loc.nBands;
i_r0_s->writeTextWeights(i_r0_s_filename, nf*(nx+npad)/2 + nf*(nx+2*npad)*(ny+2*npad)/2);
#endif
//40
//LayerProbe * ptprobe1 = new PointProbe("l2_activity.txt", 9, 7, 0, "L2:");
//l2->insertProbe(ptprobe1);
//ConnectionProbe * cProbe = new ConnectionProbe(114);
//l1_l2->insertProbe(cProbe);
//ConnectionProbe * cProbe = new ConnectionProbe(277);
//i_r1_s->insertProbe(cProbe);
//PostConnProbe * pcProbe0 = new LinearPostConnProbe(PV::DimX, locY, 0);
//LayerProbe * rptprobe = new PointProbe(25, 0, 0, "R :");
//retina->insertProbe(rptprobe);
//LayerProbe * ptprobe1 = new PointProbe("l1_activity.txt", 56 , 76, 0, "L1:");
//l1->insertProbe(ptprobe1);
//LayerProbe * ptprobe2 = new PointProbe("l2_activity.txt", 64, 64, 0, "L2:");
//l2->insertProbe(ptprobe2);
//LayerProbe * ptprobe3 = new PointProbe("l1Inh_activity.txt", 14, 19, 0, "L1Inh:");
//l1Inh->insertProbe(ptprobe3);
//LayerProbe * ptprobe4 = new PointProbe("l2Inh_activity.txt", 16, 16, 0, "L2Inh:");
//l2Inh->insertProbe(ptprobe4);
//LayerProbe * ptprobe3 = new PointProbe("image_activity.txt", 16, 16, 0, "Image:");
//image->insertProbe(ptprobe3);
//int retinaplacement = 9;
//LayerProbe * ptprobe4 = new PointProbe("retinaOn_activity.txt", retinaplacement, 11, 0, "RetinaOn:");
//retinaOn->insertProbe(ptprobe4);
//LayerProbe * ptprobe5 = new PointProbe("retinaOff_activity.txt", retinaplacement, 11, 0, "RetinaOff:");
//retinaOff->insertProbe(ptprobe5);
//LayerProbe * ptprobe6 = new PointProbe("l1_activity.txt", 52, 40, 0, "L1:");
//l1->insertProbe(ptprobe6);
//LayerProbe * ptprobe7 = new PointProbe("l1Inh_activity.txt", 13, 10, 0, "L1Inh:");
//l1Inh->insertProbe(ptprobe7);
//PostConnProbe * pcOnProbe = new PostConnProbe(5474); //(245); // 8575=>127,66
//PostConnProbe * pcOffProbe = new PostConnProbe(5474); //(245); // 8575=>127,66
//PostConnProbe * pcInhProbe = new PostConnProbe(403);
//pcProbe->setImage(image);
//pcOnProbe->setOutputIndices(true);
//r0_l1->insertProbe(pcOffProbe);
//r1_l1->insertProbe(pcOnProbe);
//l1_l1Inh->insertProbe(pcInhProbe);
//StatsProbe * sProbe = new StatsProbe(PV::BufActivity, "l1");
//l1->insertProbe(sProbe);
// run the simulation
//
if (hc->columnId() == 0) {
printf("[0]: Running simulation ...\n"); fflush(stdout);
}
hc->run();
if (hc->columnId() == 0) {
printf("[0]: Finished\n");
}
/* clean up (HyPerCol owns layers and connections, don't delete them) */
delete hc;
return 0;
}
void dump_weights(PVPatch ** patches, int numPatches)
{
FILE * fp = fopen("wdump.txt", "w");
assert(fp != NULL);
int num = 0;
for (int k = 0; k < numPatches; k++) {
PVPatch * p = patches[k];
float * w = p->data;
int nkp = p->nx * p->ny * p->nf;
for (int i = 0; i < nkp; i++) {
fprintf(fp, "%d (%d,%d) %f\n", num, k, i, w[i]);
num += 1;
}
}
fclose(fp);
}
<|endoftext|>
|
<commit_before>/*
* Copyright 2006-2008 The FLWOR Foundation.
*
* 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 <zorba/config.h>
#ifndef ZORBA_NO_XMLSCHEMA
#include "system/globalenv.h"
#include "types/schema/EventSchemaValidator.h"
#include "types/schema/StrX.h"
#include "types/typeimpl.h"
#include <zorbatypes/xerces_xmlcharray.h>
#include "store/api/item_factory.h"
#include "types/schema/schema.h"
#include "types/root_typemanager.h"
#include "PrintSchema.h"
using namespace std;
using namespace XERCES_CPP_NAMESPACE;
namespace zorba
{
EventSchemaValidator::EventSchemaValidator(
TypeManager* typeManager,
XERCES_CPP_NAMESPACE::XMLGrammarPool* grammarPool,
bool isLax,
const QueryLoc& loc)
:
_typeManager(typeManager),
_validationEventHandler()
{
XERCES_CPP_NAMESPACE::MemoryManager* memoryManager =
XERCES_CPP_NAMESPACE::XMLPlatformUtils::fgMemoryManager;
_grammarResolver = new (memoryManager)
XERCES_CPP_NAMESPACE::GrammarResolver(grammarPool, memoryManager);
_grammarResolver->useCachedGrammarInParse(true);
#if 0 // enable this to debug registered user defined schema types
PrintSchema::printInfo(true, grammarPool);
#endif
_schemaValidatorFilter = new SchemaValidatorFilter(!isLax,
&_validationEventHandler,
_grammarResolver,
memoryManager,
loc);
}
EventSchemaValidator::~EventSchemaValidator()
{
delete _schemaValidatorFilter;
delete _grammarResolver;
}
void EventSchemaValidator::startDoc()
{
//cout << " SDoc \n";
_schemaValidatorFilter->startDocumentEvent(NULL, NULL);
}
void EventSchemaValidator::endDoc()
{
//cout << " EDoc \n";
_schemaValidatorFilter->endDocumentEvent();
}
void EventSchemaValidator::startElem(store::Item_t elemName)
{
//cout << " sv SElem: " << elemName->getLocalName()->c_str() << "\n";
XMLChArray prefix(elemName->getPrefix()->c_str());
XMLChArray uri(elemName->getNamespace()->c_str());
XMLChArray localname(elemName->getLocalName()->c_str());
_schemaValidatorFilter->startElementEvent(prefix, uri, localname);
}
void EventSchemaValidator::endElem(store::Item_t elemName)
{
//cout << " sv EElem: " << elemName->getLocalName()->c_str() << "\n";
XMLChArray prefix(elemName->getPrefix()->c_str());
XMLChArray uri(elemName->getNamespace()->c_str());
XMLChArray localname(elemName->getLocalName()->c_str());
XMLCh *typeURI = NULL;
XMLCh *typeName = NULL;
_schemaValidatorFilter->endElementEvent(prefix, uri, localname, typeURI, typeName);
}
void EventSchemaValidator::attr(store::Item_t attrName, xqpStringStore_t textValue)
{
//cout << " sv Attr: " << attrName->getPrefix()->c_str() << ":"
// << attrName->getLocalName()->c_str() << " = '" << textValue->c_str() << "'\n";
XMLChArray prefix(attrName->getPrefix()->c_str());
XMLChArray uri(attrName->getNamespace()->c_str());
XMLChArray localname(attrName->getLocalName()->c_str());
XMLChArray value(textValue->c_str());
XMLCh *typeURI = NULL;
XMLCh *typeName = NULL;
_schemaValidatorFilter->attributeEvent(prefix, uri, localname, value, typeURI, typeName);
}
void EventSchemaValidator::text(xqpStringStore_t textValue)
{
//cout << " sv Text: " << textValue->c_str() << "\n";
XMLChArray value(textValue->c_str());
_schemaValidatorFilter->textEvent(value);
//_validationEventHandler.resetAttList();
}
void EventSchemaValidator::ns(xqpStringStore_t prefix, xqpStringStore_t uri)
{
//cout << " Ns : " << prefix->c_str() << " = '" << uri->c_str() << "'\n";
XMLChArray prefixVal(prefix->c_str());
XMLChArray uriVal(uri->c_str());
_schemaValidatorFilter->namespaceEvent(prefixVal, uriVal);
}
store::Item_t EventSchemaValidator::getTypeQName()
{
StrX typeName(_schemaValidatorFilter->getTypeName());
StrX typeUri(_schemaValidatorFilter->getTypeUri());
//cout << " - getTypeQName: " << typeName << "@" << typeUri <<" ";
store::Item_t typeQName;
GENV_ITEMFACTORY->createQName(typeQName,
typeUri.localFormOrDefault (Schema::XSD_NAMESPACE),
"",
typeName.localFormOrDefault ("anyType"));
//cout << " : " << typeQName->getLocalName()->c_str() << " @ "
// << typeQName->getNamespace()->c_str() <<"\n";
return typeQName;
}
xqtref_t EventSchemaValidator::getType()
{
StrX typeName(_schemaValidatorFilter->getTypeName());
StrX typeUri(_schemaValidatorFilter->getTypeUri());
//cout << " - getType: " << typeName << "@" << typeUri <<"\n";
store::Item_t typeQName;
GENV_ITEMFACTORY->createQName(typeQName,
typeUri.localFormOrDefault (Schema::XSD_NAMESPACE),
"",
typeName.localFormOrDefault ("anyType"));
xqtref_t type = _typeManager->create_named_type(typeQName);
return type;
}
store::Item_t EventSchemaValidator::getSubstitutedElemQName()
{
if (_schemaValidatorFilter->getSubstitutedElemName())
{
StrX substElemName(_schemaValidatorFilter->getSubstitutedElemName());
StrX substElemUri (_schemaValidatorFilter->getSubstitutedElemUri ());
//cout << " - getSubstitutedElemQName: " << substElemName << "@" << substElemUri <<" ";
store::Item_t substElemQName;
GENV_ITEMFACTORY->createQName(substElemQName,
substElemUri.localForm(),
"",
substElemName.localForm());
//cout << " : " << substElemQName->getLocalName()->c_str() << " @ "
// << substElemQName->getNamespace()->c_str() <<"\n";
return substElemQName;
}
else
return NULL;
}
void EventSchemaValidator::startType(store::Item_t typeQName)
{
XMLChArray uri(typeQName->getNamespace()->c_str());
XMLChArray localname(typeQName->getLocalName()->c_str());
//cout << " SType: " << typeQName->getLocalName()->c_str() << " @ "
// << typeQName->getNamespace()->c_str() << "\n";
_schemaValidatorFilter->startTypeEvent(uri, localname);
}
void EventSchemaValidator::endType()
{
//cout << " EType \n";
_schemaValidatorFilter->endTypeEvent();
}
} // namespace zorba
#endif // ZORBA_NO_XMLSCHEMA
<commit_msg>changed the default element type from anyType to untyped<commit_after>/*
* Copyright 2006-2008 The FLWOR Foundation.
*
* 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 <zorba/config.h>
#ifndef ZORBA_NO_XMLSCHEMA
#include "system/globalenv.h"
#include "types/schema/EventSchemaValidator.h"
#include "types/schema/StrX.h"
#include "types/typeimpl.h"
#include <zorbatypes/xerces_xmlcharray.h>
#include "store/api/item_factory.h"
#include "types/schema/schema.h"
#include "types/root_typemanager.h"
#include "PrintSchema.h"
using namespace std;
using namespace XERCES_CPP_NAMESPACE;
namespace zorba
{
EventSchemaValidator::EventSchemaValidator(
TypeManager* typeManager,
XERCES_CPP_NAMESPACE::XMLGrammarPool* grammarPool,
bool isLax,
const QueryLoc& loc)
:
_typeManager(typeManager),
_validationEventHandler()
{
XERCES_CPP_NAMESPACE::MemoryManager* memoryManager =
XERCES_CPP_NAMESPACE::XMLPlatformUtils::fgMemoryManager;
_grammarResolver = new (memoryManager)
XERCES_CPP_NAMESPACE::GrammarResolver(grammarPool, memoryManager);
_grammarResolver->useCachedGrammarInParse(true);
#if 0 // enable this to debug registered user defined schema types
PrintSchema::printInfo(true, grammarPool);
#endif
_schemaValidatorFilter = new SchemaValidatorFilter(!isLax,
&_validationEventHandler,
_grammarResolver,
memoryManager,
loc);
}
EventSchemaValidator::~EventSchemaValidator()
{
delete _schemaValidatorFilter;
delete _grammarResolver;
}
void EventSchemaValidator::startDoc()
{
//cout << " SDoc \n";
_schemaValidatorFilter->startDocumentEvent(NULL, NULL);
}
void EventSchemaValidator::endDoc()
{
//cout << " EDoc \n";
_schemaValidatorFilter->endDocumentEvent();
}
void EventSchemaValidator::startElem(store::Item_t elemName)
{
//cout << " sv SElem: " << elemName->getLocalName()->c_str() << "\n";
XMLChArray prefix(elemName->getPrefix()->c_str());
XMLChArray uri(elemName->getNamespace()->c_str());
XMLChArray localname(elemName->getLocalName()->c_str());
_schemaValidatorFilter->startElementEvent(prefix, uri, localname);
}
void EventSchemaValidator::endElem(store::Item_t elemName)
{
//cout << " sv EElem: " << elemName->getLocalName()->c_str() << "\n";
XMLChArray prefix(elemName->getPrefix()->c_str());
XMLChArray uri(elemName->getNamespace()->c_str());
XMLChArray localname(elemName->getLocalName()->c_str());
XMLCh *typeURI = NULL;
XMLCh *typeName = NULL;
_schemaValidatorFilter->endElementEvent(prefix, uri, localname, typeURI, typeName);
}
void EventSchemaValidator::attr(store::Item_t attrName, xqpStringStore_t textValue)
{
//cout << " sv Attr: " << attrName->getPrefix()->c_str() << ":"
// << attrName->getLocalName()->c_str() << " = '" << textValue->c_str() << "'\n";
XMLChArray prefix(attrName->getPrefix()->c_str());
XMLChArray uri(attrName->getNamespace()->c_str());
XMLChArray localname(attrName->getLocalName()->c_str());
XMLChArray value(textValue->c_str());
XMLCh *typeURI = NULL;
XMLCh *typeName = NULL;
_schemaValidatorFilter->attributeEvent(prefix, uri, localname, value, typeURI, typeName);
}
void EventSchemaValidator::text(xqpStringStore_t textValue)
{
//cout << " sv Text: " << textValue->c_str() << "\n";
XMLChArray value(textValue->c_str());
_schemaValidatorFilter->textEvent(value);
//_validationEventHandler.resetAttList();
}
void EventSchemaValidator::ns(xqpStringStore_t prefix, xqpStringStore_t uri)
{
//cout << " Ns : " << prefix->c_str() << " = '" << uri->c_str() << "'\n";
XMLChArray prefixVal(prefix->c_str());
XMLChArray uriVal(uri->c_str());
_schemaValidatorFilter->namespaceEvent(prefixVal, uriVal);
}
store::Item_t EventSchemaValidator::getTypeQName()
{
StrX typeName(_schemaValidatorFilter->getTypeName());
StrX typeUri(_schemaValidatorFilter->getTypeUri());
//cout << " - getTypeQName: " << typeName << "@" << typeUri <<" ";
store::Item_t typeQName;
GENV_ITEMFACTORY->createQName(typeQName,
typeUri.localFormOrDefault (Schema::XSD_NAMESPACE),
"",
typeName.localFormOrDefault ("untyped"));
//cout << " : " << typeQName->getLocalName()->c_str() << " @ "
// << typeQName->getNamespace()->c_str() <<"\n";
return typeQName;
}
xqtref_t EventSchemaValidator::getType()
{
StrX typeName(_schemaValidatorFilter->getTypeName());
StrX typeUri(_schemaValidatorFilter->getTypeUri());
//cout << " - getType: " << typeName << "@" << typeUri <<"\n";
store::Item_t typeQName;
GENV_ITEMFACTORY->createQName(typeQName,
typeUri.localFormOrDefault (Schema::XSD_NAMESPACE),
"",
typeName.localFormOrDefault ("untyped"));
xqtref_t type = _typeManager->create_named_type(typeQName);
return type;
}
store::Item_t EventSchemaValidator::getSubstitutedElemQName()
{
if (_schemaValidatorFilter->getSubstitutedElemName())
{
StrX substElemName(_schemaValidatorFilter->getSubstitutedElemName());
StrX substElemUri (_schemaValidatorFilter->getSubstitutedElemUri ());
//cout << " - getSubstitutedElemQName: " << substElemName << "@" << substElemUri <<" ";
store::Item_t substElemQName;
GENV_ITEMFACTORY->createQName(substElemQName,
substElemUri.localForm(),
"",
substElemName.localForm());
//cout << " : " << substElemQName->getLocalName()->c_str() << " @ "
// << substElemQName->getNamespace()->c_str() <<"\n";
return substElemQName;
}
else
return NULL;
}
void EventSchemaValidator::startType(store::Item_t typeQName)
{
XMLChArray uri(typeQName->getNamespace()->c_str());
XMLChArray localname(typeQName->getLocalName()->c_str());
//cout << " SType: " << typeQName->getLocalName()->c_str() << " @ "
// << typeQName->getNamespace()->c_str() << "\n";
_schemaValidatorFilter->startTypeEvent(uri, localname);
}
void EventSchemaValidator::endType()
{
//cout << " EType \n";
_schemaValidatorFilter->endTypeEvent();
}
} // namespace zorba
#endif // ZORBA_NO_XMLSCHEMA
<|endoftext|>
|
<commit_before>/*
* Copyright 2012 Troels Blum <[email protected]>
*
* This file is part of cphVB <http://code.google.com/p/cphvb/>.
*
* cphVB 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.
*
* cphVB 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 cphVB. If not, see <http://www.gnu.org/licenses/>.
*/
#include <cassert>
#include <stdexcept>
#include <cphvb.h>
#include "Scalar.hpp"
Scalar::Scalar(cphvb_constant constant)
: mytype(oclType(constant.type))
{
switch (constant.type)
{
case CPHVB_BOOL:
value.uc = constant.value.bool8;
break;
case CPHVB_INT8:
value.c = constant.value.int8;
break;
case CPHVB_INT16:
value.s = constant.value.int16;
break;
case CPHVB_INT32:
value.i = constant.value.int32;
break;
case CPHVB_INT64:
value.l = constant.value.int64;
break;
case CPHVB_UINT8:
value.uc = constant.value.uint8;
break;
case CPHVB_UINT16:
value.us = constant.value.uint16;
break;
case CPHVB_UINT32:
value.ui = constant.value.uint32;
break;
case CPHVB_UINT64:
value.ul = constant.value.uint64;
break;
case CPHVB_FLOAT16:
value.h = constant.value.float16;
break;
case CPHVB_FLOAT32:
value.f = constant.value.float32;
break;
case CPHVB_FLOAT64:
value.d = constant.value.float64;
break;
default:
throw std::runtime_error("Scalar: Unknown type.");
}
}
Scalar::Scalar(cphvb_array* spec)
: mytype(oclType(spec->type))
{
assert(cphvb_is_scalar(spec));
switch (spec->type)
{
case CPHVB_BOOL:
value.uc = *(cphvb_bool*)spec->data;
break;
case CPHVB_INT8:
value.c = *(cphvb_int8*)spec->data;
break;
case CPHVB_INT16:
value.s = *(cphvb_int16*)spec->data;
break;
case CPHVB_INT32:
value.i = *(cphvb_int32*)spec->data;
break;
case CPHVB_INT64:
value.l = *(cphvb_int64*)spec->data;
break;
case CPHVB_UINT8:
value.uc = *(cphvb_uint8*)spec->data;
break;
case CPHVB_UINT16:
value.us = *(cphvb_uint16*)spec->data;
break;
case CPHVB_UINT32:
value.ui = *(cphvb_uint32*)spec->data;
break;
case CPHVB_UINT64:
value.ul = *(cphvb_uint64*)spec->data;
break;
case CPHVB_FLOAT16:
value.h = *(cphvb_float16*)spec->data;
break;
case CPHVB_FLOAT32:
value.f = *(cphvb_float32*)spec->data;
break;
case CPHVB_FLOAT64:
value.d = *(cphvb_float64*)spec->data;
break;
default:
throw std::runtime_error("Scalar: Unknown type.");
}
}
Scalar::Scalar(cl_long v)
: mytype(OCL_INT64)
{
value.l = v;
}
OCLtype Scalar::type() const
{
return mytype;
}
void Scalar::printOn(std::ostream& os) const
{
os << "const " << oclTypeStr(mytype);
}
void Scalar::addToKernel(cl::Kernel& kernel, unsigned int argIndex)
{
switch(mytype)
{
case OCL_INT8:
kernel.setArg(argIndex, value.c);
break;
case OCL_INT16:
kernel.setArg(argIndex, value.s);
break;
case OCL_INT32:
kernel.setArg(argIndex, value.i);
break;
case OCL_INT64:
kernel.setArg(argIndex, value.l);
break;
case OCL_UINT8:
kernel.setArg(argIndex, value.uc);
break;
case OCL_UINT16:
kernel.setArg(argIndex, value.us);
break;
case OCL_UINT32:
kernel.setArg(argIndex, value.ui);
break;
case OCL_UINT64:
kernel.setArg(argIndex, value.ul);
break;
case OCL_FLOAT16:
kernel.setArg(argIndex, value.h);
break;
case OCL_FLOAT32:
kernel.setArg(argIndex, value.f);
break;
case OCL_FLOAT64:
kernel.setArg(argIndex, value.d);
break;
default:
assert(false);
}
}
<commit_msg>added saaertion<commit_after>/*
* Copyright 2012 Troels Blum <[email protected]>
*
* This file is part of cphVB <http://code.google.com/p/cphvb/>.
*
* cphVB 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.
*
* cphVB 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 cphVB. If not, see <http://www.gnu.org/licenses/>.
*/
#include <cassert>
#include <stdexcept>
#include <cphvb.h>
#include "Scalar.hpp"
Scalar::Scalar(cphvb_constant constant)
: mytype(oclType(constant.type))
{
switch (constant.type)
{
case CPHVB_BOOL:
value.uc = constant.value.bool8;
break;
case CPHVB_INT8:
value.c = constant.value.int8;
break;
case CPHVB_INT16:
value.s = constant.value.int16;
break;
case CPHVB_INT32:
value.i = constant.value.int32;
break;
case CPHVB_INT64:
value.l = constant.value.int64;
break;
case CPHVB_UINT8:
value.uc = constant.value.uint8;
break;
case CPHVB_UINT16:
value.us = constant.value.uint16;
break;
case CPHVB_UINT32:
value.ui = constant.value.uint32;
break;
case CPHVB_UINT64:
value.ul = constant.value.uint64;
break;
case CPHVB_FLOAT16:
value.h = constant.value.float16;
break;
case CPHVB_FLOAT32:
value.f = constant.value.float32;
break;
case CPHVB_FLOAT64:
value.d = constant.value.float64;
break;
default:
throw std::runtime_error("Scalar: Unknown type.");
}
}
Scalar::Scalar(cphvb_array* spec)
: mytype(oclType(spec->type))
{
assert (cphvb_is_scalar(spec));
assert (spec->data != NULL);
switch (spec->type)
{
case CPHVB_BOOL:
value.uc = *(cphvb_bool*)spec->data;
break;
case CPHVB_INT8:
value.c = *(cphvb_int8*)spec->data;
break;
case CPHVB_INT16:
value.s = *(cphvb_int16*)spec->data;
break;
case CPHVB_INT32:
value.i = *(cphvb_int32*)spec->data;
break;
case CPHVB_INT64:
value.l = *(cphvb_int64*)spec->data;
break;
case CPHVB_UINT8:
value.uc = *(cphvb_uint8*)spec->data;
break;
case CPHVB_UINT16:
value.us = *(cphvb_uint16*)spec->data;
break;
case CPHVB_UINT32:
value.ui = *(cphvb_uint32*)spec->data;
break;
case CPHVB_UINT64:
value.ul = *(cphvb_uint64*)spec->data;
break;
case CPHVB_FLOAT16:
value.h = *(cphvb_float16*)spec->data;
break;
case CPHVB_FLOAT32:
value.f = *(cphvb_float32*)spec->data;
break;
case CPHVB_FLOAT64:
value.d = *(cphvb_float64*)spec->data;
break;
default:
throw std::runtime_error("Scalar: Unknown type.");
}
}
Scalar::Scalar(cl_long v)
: mytype(OCL_INT64)
{
value.l = v;
}
OCLtype Scalar::type() const
{
return mytype;
}
void Scalar::printOn(std::ostream& os) const
{
os << "const " << oclTypeStr(mytype);
}
void Scalar::addToKernel(cl::Kernel& kernel, unsigned int argIndex)
{
switch(mytype)
{
case OCL_INT8:
kernel.setArg(argIndex, value.c);
break;
case OCL_INT16:
kernel.setArg(argIndex, value.s);
break;
case OCL_INT32:
kernel.setArg(argIndex, value.i);
break;
case OCL_INT64:
kernel.setArg(argIndex, value.l);
break;
case OCL_UINT8:
kernel.setArg(argIndex, value.uc);
break;
case OCL_UINT16:
kernel.setArg(argIndex, value.us);
break;
case OCL_UINT32:
kernel.setArg(argIndex, value.ui);
break;
case OCL_UINT64:
kernel.setArg(argIndex, value.ul);
break;
case OCL_FLOAT16:
kernel.setArg(argIndex, value.h);
break;
case OCL_FLOAT32:
kernel.setArg(argIndex, value.f);
break;
case OCL_FLOAT64:
kernel.setArg(argIndex, value.d);
break;
default:
assert(false);
}
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2009-2019 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <test/fuzz/fuzz.h>
#include <util/bip32.h>
void test_one_input(const std::vector<uint8_t>& buffer)
{
const std::string keypath_str(buffer.begin(), buffer.end());
std::vector<uint32_t> keypath;
(void)ParseHDKeypath(keypath_str, keypath);
}
<commit_msg>tests: Add fuzzing coverage for FormatHDKeypath(...) and WriteHDKeypath(...)<commit_after>// Copyright (c) 2009-2019 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <test/fuzz/FuzzedDataProvider.h>
#include <test/fuzz/fuzz.h>
#include <test/fuzz/util.h>
#include <util/bip32.h>
#include <cstdint>
#include <vector>
void test_one_input(const std::vector<uint8_t>& buffer)
{
const std::string keypath_str(buffer.begin(), buffer.end());
std::vector<uint32_t> keypath;
(void)ParseHDKeypath(keypath_str, keypath);
FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size());
const std::vector<uint32_t> random_keypath = ConsumeRandomLengthIntegralVector<uint32_t>(fuzzed_data_provider);
(void)FormatHDKeypath(random_keypath);
(void)WriteHDKeypath(random_keypath);
}
<|endoftext|>
|
<commit_before>/*
Copyright (C) 2013 Andreas Hartmetz <[email protected]>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LGPL. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
Alternatively, this file is available under the Mozilla Public License
Version 1.1. You may obtain a copy of the License at
http://www.mozilla.org/MPL/
*/
#include "argumentlist.h"
#include "eventdispatcher.h"
#include "imessagereceiver.h"
#include "message.h"
#include "pendingreply.h"
//#include "platformtime.h"
//#include "timer.h"
#include "transceiver.h"
#include "../testutil.h"
#include <iostream>
#include <string>
using namespace std;
static void addressMessageToBus(Message *msg)
{
msg->setType(Message::MethodCallMessage);
msg->setDestination(string("org.freedesktop.DBus"));
msg->setInterface(string("org.freedesktop.DBus"));
msg->setPath("/org/freedesktop/DBus");
}
class ReplyCheck : public IMessageReceiver
{
public:
EventDispatcher *m_eventDispatcher;
void pendingReplyReceived(PendingReply *pr) override
{
pr->dumpState();
std::cout << "got it!\n" << pr->reply()->argumentList().prettyPrint();
TEST(pr->isFinished());
TEST(!pr->isError());
m_eventDispatcher->interrupt();
}
};
static void testBusAddress()
{
EventDispatcher eventDispatcher;
Transceiver trans(&eventDispatcher, ConnectionInfo::Bus::Session);
Message busNameRequest;
addressMessageToBus(&busNameRequest);
busNameRequest.setMethod(string("RequestName"));
ArgumentList argList;
ArgumentList::Writer writer(&argList);
writer.writeString("Bana.nana"); // requested name
writer.writeUint32(4); // TODO proper enum or so: 4 == DBUS_NAME_FLAG_DO_NOT_QUEUE
writer.finish();
busNameRequest.setArgumentList(argList);
PendingReply busNameReply = trans.send(move(busNameRequest));
ReplyCheck replyCheck;
replyCheck.m_eventDispatcher = &eventDispatcher;
busNameReply.setReceiver(&replyCheck);
while (eventDispatcher.poll()) {
}
}
int main(int argc, char *argv[])
{
testBusAddress();
std::cout << "Passed!\n";
}
<commit_msg>Remove already commented out includes.<commit_after>/*
Copyright (C) 2013 Andreas Hartmetz <[email protected]>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LGPL. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
Alternatively, this file is available under the Mozilla Public License
Version 1.1. You may obtain a copy of the License at
http://www.mozilla.org/MPL/
*/
#include "argumentlist.h"
#include "eventdispatcher.h"
#include "imessagereceiver.h"
#include "message.h"
#include "pendingreply.h"
#include "transceiver.h"
#include "../testutil.h"
#include <iostream>
#include <string>
using namespace std;
static void addressMessageToBus(Message *msg)
{
msg->setType(Message::MethodCallMessage);
msg->setDestination(string("org.freedesktop.DBus"));
msg->setInterface(string("org.freedesktop.DBus"));
msg->setPath("/org/freedesktop/DBus");
}
class ReplyCheck : public IMessageReceiver
{
public:
EventDispatcher *m_eventDispatcher;
void pendingReplyReceived(PendingReply *pr) override
{
pr->dumpState();
std::cout << "got it!\n" << pr->reply()->argumentList().prettyPrint();
TEST(pr->isFinished());
TEST(!pr->isError());
m_eventDispatcher->interrupt();
}
};
static void testBusAddress()
{
EventDispatcher eventDispatcher;
Transceiver trans(&eventDispatcher, ConnectionInfo::Bus::Session);
Message busNameRequest;
addressMessageToBus(&busNameRequest);
busNameRequest.setMethod(string("RequestName"));
ArgumentList argList;
ArgumentList::Writer writer(&argList);
writer.writeString("Bana.nana"); // requested name
writer.writeUint32(4); // TODO proper enum or so: 4 == DBUS_NAME_FLAG_DO_NOT_QUEUE
writer.finish();
busNameRequest.setArgumentList(argList);
PendingReply busNameReply = trans.send(move(busNameRequest));
ReplyCheck replyCheck;
replyCheck.m_eventDispatcher = &eventDispatcher;
busNameReply.setReceiver(&replyCheck);
while (eventDispatcher.poll()) {
}
}
int main(int argc, char *argv[])
{
testBusAddress();
std::cout << "Passed!\n";
}
<|endoftext|>
|
<commit_before>NAN_METHOD(GitPatch::ConvenientFromDiff) {
if (info.Length() == 0 || !info[0]->IsObject()) {
return Nan::ThrowError("Diff diff is required.");
}
if (info.Length() == 1 || !info[1]->IsFunction()) {
return Nan::ThrowError("Callback is required and must be a Function.");
}
ConvenientFromDiffBaton *baton = new ConvenientFromDiffBaton;
baton->error_code = GIT_OK;
baton->error = NULL;
baton->diff = Nan::ObjectWrap::Unwrap<GitDiff>(Nan::To<v8::Object>(info[0]).ToLocalChecked())->GetValue();
baton->out = new std::vector<PatchData *>;
baton->out->reserve(git_diff_num_deltas(baton->diff));
Nan::Callback *callback = new Nan::Callback(Local<Function>::Cast(info[1]));
ConvenientFromDiffWorker *worker = new ConvenientFromDiffWorker(baton, callback);
worker->SaveToPersistent("diff", info[0]);
Nan::AsyncQueueWorker(worker);
return;
}
void GitPatch::ConvenientFromDiffWorker::Execute() {
git_error_clear();
{
LockMaster lockMaster(true, baton->diff);
std::vector<git_patch *> patchesToBeFreed;
for (int i = 0; i < git_diff_num_deltas(baton->diff); ++i) {
git_patch *nextPatch;
int result = git_patch_from_diff(&nextPatch, baton->diff, i);
if (result) {
while (!patchesToBeFreed.empty())
{
git_patch_free(patchesToBeFreed.back());
patchesToBeFreed.pop_back();
}
while (!baton->out->empty()) {
PatchDataFree(baton->out->back());
baton->out->pop_back();
}
baton->error_code = result;
if (git_error_last() != NULL) {
baton->error = git_error_dup(git_error_last());
}
delete baton->out;
baton->out = NULL;
return;
}
if (nextPatch != NULL) {
baton->out->push_back(createFromRaw(nextPatch));
patchesToBeFreed.push_back(nextPatch);
}
}
while (!patchesToBeFreed.empty())
{
git_patch_free(patchesToBeFreed.back());
patchesToBeFreed.pop_back();
}
}
}
void GitPatch::ConvenientFromDiffWorker::HandleOKCallback() {
if (baton->out != NULL) {
unsigned int size = baton->out->size();
Local<Array> result = Nan::New<Array>(size);
for (unsigned int i = 0; i < size; ++i) {
Nan::Set(result, Nan::New<Number>(i), ConvenientPatch::New((void *)baton->out->at(i)));
}
delete baton->out;
Local<v8::Value> argv[2] = {
Nan::Null(),
result
};
callback->Call(2, argv, async_resource);
return;
}
if (baton->error) {
Local<v8::Object> err;
if (baton->error->message) {
err = Nan::To<v8::Object>(Nan::Error(baton->error->message)).ToLocalChecked();
} else {
err = Nan::To<v8::Object>(Nan::Error("Method convenientFromDiff has thrown an error.")).ToLocalChecked();
}
Nan::Set(err, Nan::New("errno").ToLocalChecked(), Nan::New(baton->error_code));
Nan::Set(err, Nan::New("errorFunction").ToLocalChecked(), Nan::New("Patch.convenientFromDiff").ToLocalChecked());
Local<v8::Value> argv[1] = {
err
};
callback->Call(1, argv, async_resource);
if (baton->error->message)
{
free((void *)baton->error->message);
}
free((void *)baton->error);
return;
}
if (baton->error_code < 0) {
Local<v8::Object> err = Nan::To<v8::Object>(Nan::Error("method convenientFromDiff has thrown an error.")).ToLocalChecked();
Nan::Set(err, Nan::New("errno").ToLocalChecked(), Nan::New(baton->error_code));
Nan::Set(err, Nan::New("errorFunction").ToLocalChecked(), Nan::New("Patch.convenientFromDiff").ToLocalChecked());
Local<v8::Value> argv[1] = {
err
};
callback->Call(1, argv, async_resource);
return;
}
Nan::Call(callback, 0, NULL);
}
<commit_msg>:bug: Needs the reference to callback, not the pointer<commit_after>NAN_METHOD(GitPatch::ConvenientFromDiff) {
if (info.Length() == 0 || !info[0]->IsObject()) {
return Nan::ThrowError("Diff diff is required.");
}
if (info.Length() == 1 || !info[1]->IsFunction()) {
return Nan::ThrowError("Callback is required and must be a Function.");
}
ConvenientFromDiffBaton *baton = new ConvenientFromDiffBaton;
baton->error_code = GIT_OK;
baton->error = NULL;
baton->diff = Nan::ObjectWrap::Unwrap<GitDiff>(Nan::To<v8::Object>(info[0]).ToLocalChecked())->GetValue();
baton->out = new std::vector<PatchData *>;
baton->out->reserve(git_diff_num_deltas(baton->diff));
Nan::Callback *callback = new Nan::Callback(Local<Function>::Cast(info[1]));
ConvenientFromDiffWorker *worker = new ConvenientFromDiffWorker(baton, callback);
worker->SaveToPersistent("diff", info[0]);
Nan::AsyncQueueWorker(worker);
return;
}
void GitPatch::ConvenientFromDiffWorker::Execute() {
git_error_clear();
{
LockMaster lockMaster(true, baton->diff);
std::vector<git_patch *> patchesToBeFreed;
for (int i = 0; i < git_diff_num_deltas(baton->diff); ++i) {
git_patch *nextPatch;
int result = git_patch_from_diff(&nextPatch, baton->diff, i);
if (result) {
while (!patchesToBeFreed.empty())
{
git_patch_free(patchesToBeFreed.back());
patchesToBeFreed.pop_back();
}
while (!baton->out->empty()) {
PatchDataFree(baton->out->back());
baton->out->pop_back();
}
baton->error_code = result;
if (git_error_last() != NULL) {
baton->error = git_error_dup(git_error_last());
}
delete baton->out;
baton->out = NULL;
return;
}
if (nextPatch != NULL) {
baton->out->push_back(createFromRaw(nextPatch));
patchesToBeFreed.push_back(nextPatch);
}
}
while (!patchesToBeFreed.empty())
{
git_patch_free(patchesToBeFreed.back());
patchesToBeFreed.pop_back();
}
}
}
void GitPatch::ConvenientFromDiffWorker::HandleOKCallback() {
if (baton->out != NULL) {
unsigned int size = baton->out->size();
Local<Array> result = Nan::New<Array>(size);
for (unsigned int i = 0; i < size; ++i) {
Nan::Set(result, Nan::New<Number>(i), ConvenientPatch::New((void *)baton->out->at(i)));
}
delete baton->out;
Local<v8::Value> argv[2] = {
Nan::Null(),
result
};
callback->Call(2, argv, async_resource);
return;
}
if (baton->error) {
Local<v8::Object> err;
if (baton->error->message) {
err = Nan::To<v8::Object>(Nan::Error(baton->error->message)).ToLocalChecked();
} else {
err = Nan::To<v8::Object>(Nan::Error("Method convenientFromDiff has thrown an error.")).ToLocalChecked();
}
Nan::Set(err, Nan::New("errno").ToLocalChecked(), Nan::New(baton->error_code));
Nan::Set(err, Nan::New("errorFunction").ToLocalChecked(), Nan::New("Patch.convenientFromDiff").ToLocalChecked());
Local<v8::Value> argv[1] = {
err
};
callback->Call(1, argv, async_resource);
if (baton->error->message)
{
free((void *)baton->error->message);
}
free((void *)baton->error);
return;
}
if (baton->error_code < 0) {
Local<v8::Object> err = Nan::To<v8::Object>(Nan::Error("method convenientFromDiff has thrown an error.")).ToLocalChecked();
Nan::Set(err, Nan::New("errno").ToLocalChecked(), Nan::New(baton->error_code));
Nan::Set(err, Nan::New("errorFunction").ToLocalChecked(), Nan::New("Patch.convenientFromDiff").ToLocalChecked());
Local<v8::Value> argv[1] = {
err
};
callback->Call(1, argv, async_resource);
return;
}
Nan::Call(*callback, 0, NULL);
}
<|endoftext|>
|
<commit_before>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright 2000-2002 The OGRE Team
Also see acknowledgements in Readme.html
This program 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 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 Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along with
this program; if not, write to the Free Software Foundation, Inc., 59 Temple
Place - Suite 330, Boston, MA 02111-1307, USA, or go to
http://www.gnu.org/copyleft/lesser.txt.
-----------------------------------------------------------------------------
*/
#include "Q3BSP.h"
#include <stdio.h>
#include <iostream>
#include <fstream>
float bzpScale = 0.25f;
Quake3Level::Quake3Level()
{
data = NULL;
}
Quake3Level::~Quake3Level()
{
if (data)
free (data);
}
void Quake3Level::loadFromFile ( const char* fileName)
{
if(!fileName)
return;
theFileName = fileName;
initialise();
#ifdef _DEBUG
dumpContents();
#endif
}
// byte swapping functions
void SwapFourBytes(unsigned long *dw)
{
unsigned long tmp;
tmp = (*dw & 0x000000FF);
tmp = ((*dw & 0x0000FF00) >> 0x08) | (tmp << 0x08);
tmp = ((*dw & 0x00FF0000) >> 0x10) | (tmp << 0x08);
tmp = ((*dw & 0xFF000000) >> 0x18) | (tmp << 0x08);
memcpy (dw, &tmp, sizeof(unsigned long));
}
void SwapFourBytesGrup (unsigned long *src, int size)
{
unsigned long *ptr = (unsigned long *)src;
int i;
for (i = 0; i < size/4; ++i) {
SwapFourBytes (&ptr[i]);
}
}
bool Quake3Level::dumpToModel ( CModel &model )
{
model.clear();
for ( int i = 0; i < mNumShaders; i++)
{
CMaterial material;
char temp[128];
strcpy(temp, mShaders[i].name);
if (strrchr(temp,'.'))
*(strrchr(temp,'.')) = 0;
material.texture = temp;
material.texture += ".png";
model.materials[std::string(temp)] = material;
}
for ( int i = 0; i < mNumFaces; i++ )
{
switch( mFaces[i].type )
{
case 1: // polygon face
case 3: // mesh face
{
CMesh mesh;
// add in the verts and normals and UVs
for ( int j = mFaces[i].vert_count-1; j >= 0; j-- )
{
CVertex vert;
CVertex norm;
CTexCoord coord;
int index = mFaces[i].vert_start + j;
if ( index > 0 && index < mNumVertices)
{
vert.x = mVertices[index].point[0]*bzpScale;
vert.y = mVertices[index].point[1]*bzpScale;
vert.z = mVertices[index].point[2]*bzpScale;
norm.x = mVertices[index].normal[0];
norm.y = mVertices[index].normal[1];
norm.z = mVertices[index].normal[2];
coord.u = mVertices[index].texture[0];
coord.v = mVertices[index].texture[1];
}
mesh.verts.push_back(vert);
mesh.normals.push_back(norm);
mesh.texCoords.push_back(coord);
}
// now do the face
CFace face;
if ( mFaces[i].shader > 0 && mFaces[i].shader < mNumShaders)
{
char temp[128];
if (strlen(mShaders[mFaces[i].shader].name) )
{
strcpy(temp, mShaders[mFaces[i].shader].name);
char *p = strrchr(temp,'.');
if (p)
*p = 0;
face.material = temp;
}
int iBlarg = 10;
iBlarg++;
}
int maxIndex = mFaces[i].vert_start + mFaces[i].vert_count -1;
if ( maxIndex < mNumVertices)
{
for( int j = 0; j < mFaces[i].vert_count; j++)
{
face.verts.push_back(j);
face.normals.push_back(j);
face.texCoords.push_back(j);
}
mesh.faces.push_back(face);
}
if ( mesh.faces.size())
model.meshes.push_back(mesh);
}
break;
case 2: // surface
break;
case 4: //billboard
break;
default:
// something else
break;
}
}
return model.meshes.size() > 0;
}
void Quake3Level::initialise(void)
{
int i=0;
FILE *fp = fopen(theFileName.c_str(),"rb");
if (!fp)
return;
fseek(fp,0,SEEK_END);
unsigned int size = ftell(fp);
fseek(fp,0,SEEK_SET);
if (data)
free(data);
data = (char*)malloc(size);
fread(data,size,1,fp);
fclose(fp);
mHeader = (bsp_header_t*)data;
mLumpStart = ((unsigned char*)mHeader) + sizeof(mHeader);
mEntities = (unsigned char*)getLump(BSP_ENTITIES_LUMP);
mNumEntities = getLumpSize(BSP_ENTITIES_LUMP);
mElements = (int*)getLump(BSP_ELEMENTS_LUMP);
mNumElements = getLumpSize(BSP_ELEMENTS_LUMP) / sizeof(int);
mFaces = (bsp_face_t*)getLump(BSP_FACES_LUMP);
mNumFaces = getLumpSize(BSP_FACES_LUMP) / sizeof(bsp_face_t);
mLeafFaces = (int*)getLump(BSP_LFACES_LUMP);
mNumLeafFaces = getLumpSize(BSP_LFACES_LUMP) / sizeof(int);
mLeaves = (bsp_leaf_t*)getLump(BSP_LEAVES_LUMP);
mNumLeaves = getLumpSize(BSP_LEAVES_LUMP) / sizeof(bsp_leaf_t);
mLightmaps = (unsigned char*)getLump(BSP_LIGHTMAPS_LUMP);
mNumLightmaps = getLumpSize(BSP_LIGHTMAPS_LUMP)/BSP_LIGHTMAP_BANKSIZE;
mModels = (bsp_model_t*)getLump(BSP_MODELS_LUMP);
mNumModels = getLumpSize(BSP_MODELS_LUMP) / sizeof(bsp_model_t);
mNodes = (bsp_node_t*)getLump(BSP_NODES_LUMP);
mNumNodes = getLumpSize(BSP_NODES_LUMP) / sizeof(bsp_node_t);
mPlanes = (bsp_plane_t*) getLump(BSP_PLANES_LUMP);
mNumPlanes = getLumpSize(BSP_PLANES_LUMP)/sizeof(bsp_plane_t);
mShaders = (bsp_shader_t*) getLump(BSP_SHADERS_LUMP);
mNumShaders = getLumpSize(BSP_SHADERS_LUMP)/sizeof(bsp_shader_t);
mVis = (bsp_vis_t*)getLump(BSP_VISIBILITY_LUMP);
mVertices = (bsp_vertex_t*) getLump(BSP_VERTICES_LUMP);
mNumVertices = getLumpSize(BSP_VERTICES_LUMP)/sizeof(bsp_vertex_t);
mLeafBrushes = (int*)getLump(BSP_LBRUSHES_LUMP);
mNumLeafBrushes = getLumpSize(BSP_LBRUSHES_LUMP)/sizeof(int);
mBrushes = (bsp_brush_t*) getLump(BSP_BRUSH_LUMP);
mNumBrushes = getLumpSize(BSP_BRUSH_LUMP)/sizeof(bsp_brush_t);
mBrushSides = (bsp_brushside_t*) getLump(BSP_BRUSHSIDES_LUMP);
mNumBrushSides = getLumpSize(BSP_BRUSHSIDES_LUMP)/sizeof(bsp_brushside_t);
#ifdef __APPLE___
// swap header
SwapFourBytes (&mHeader->version);
SwapFourBytesGrup ((unsigned long*)mElements, mNumElements*sizeof(int));
SwapFourBytesGrup ((unsigned long*)mFaces, mNumFaces*sizeof(bsp_face_t));
SwapFourBytesGrup ((unsigned long*)mLeafFaces, mNumLeafFaces*sizeof(int));
SwapFourBytesGrup ((unsigned long*)mLeaves, mNumLeaves*sizeof(bsp_leaf_t));
SwapFourBytesGrup ((unsigned long*)mModels, mNumModels*sizeof(bsp_model_t));
SwapFourBytesGrup ((unsigned long*)mNodes, mNumNodes*sizeof(bsp_node_t));
SwapFourBytesGrup ((unsigned long*)mPlanes, mNumPlanes*sizeof(bsp_plane_t));
for (i=0; i < mNumShaders; ++i) {
SwapFourBytes(&mShaders[i].surface_flags);
SwapFourBytes(&mShaders[i].content_flags);
}
SwapFourBytes(&mVis->cluster_count);
SwapFourBytes(&mVis->row_size);
SwapFourBytesGrup ((unsigned long*)mVertices, mNumVertices*sizeof(bsp_vertex_t));
SwapFourBytesGrup ((unsigned long*)mLeafBrushes, mNumLeafBrushes*sizeof(int));
SwapFourBytesGrup ((unsigned long*)mBrushes, mNumBrushes*sizeof(bsp_brush_t));
SwapFourBytesGrup ((unsigned long*)mBrushSides, mNumBrushSides*sizeof(bsp_brushside_t));
#endif
}
void* Quake3Level::getLump(int lumpType)
{
#ifdef __APPLE___
// swap lump offset
SwapFourBytes (&mHeader->lumps[lumpType].offset);
#endif
return (unsigned char*)mHeader + mHeader->lumps[lumpType].offset;
}
int Quake3Level::getLumpSize(int lumpType)
{
#ifdef __APPLE___
// swap lump size
SwapFourBytes (&mHeader->lumps[lumpType].size);
#endif
return mHeader->lumps[lumpType].size;
}
void Quake3Level::dumpContents(void)
{
std::ofstream of;
of.open("Quake3Level.log");
of << "Quake3 level statistics" << std::endl;
of << "-----------------------" << std::endl;
of << "Entities : " << mNumEntities << std::endl;
of << "Faces : " << mNumFaces << std::endl;
of << "Leaf Faces : " << mNumLeafFaces << std::endl;
of << "Leaves : " << mNumLeaves << std::endl;
of << "Lightmaps : " << mNumLightmaps << std::endl;
of << "Elements : " << mNumElements << std::endl;
of << "Models : " << mNumModels << std::endl;
of << "Nodes : " << mNumNodes << std::endl;
of << "Planes : " << mNumPlanes << std::endl;
of << "Shaders : " << mNumShaders << std::endl;
of << "Vertices : " << mNumVertices << std::endl;
// of << "Vis Clusters : " << mVis->cluster_count << std::endl;
of << std::endl;
of << "-= Shaders =-";
of << std::endl;
for (int i = 0; i < mNumShaders; ++i)
{
of << "Shader " << i << ": " << mShaders[i].name << std::endl;
}
of << std::endl;
of << "-= Entities =-";
of << std::endl;
char* strEnt = strtok((char*)mEntities, "\0");
while (strEnt != 0)
{
of << strEnt << std::endl;
strEnt = strtok(0, "\0");
}
of.close();
}
void Quake3Level::extractLightmaps(void) const
{
// Lightmaps are always 128x128x24 (RGB)
unsigned char* pLightmap = mLightmaps;
for (int i = 0; i < mNumLightmaps; ++i)
{
char name[32];
sprintf(name, "@lightmap%d", i);
/* // Load, no mipmaps, brighten by factor 2.5
Image img; img.loadRawData( DataChunk( pLightmap, 128 * 128 * 3 ), 128, 128, PF_R8G8B8 );
TextureManager::getSingleton().loadImage( name, img, TEX_TYPE_2D, 0, 4.0f );
pLightmap += BSP_LIGHTMAP_BANKSIZE;
*/
}
}
<commit_msg>move declaration inside #def to quiet unused warning<commit_after>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright 2000-2002 The OGRE Team
Also see acknowledgements in Readme.html
This program 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 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 Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along with
this program; if not, write to the Free Software Foundation, Inc., 59 Temple
Place - Suite 330, Boston, MA 02111-1307, USA, or go to
http://www.gnu.org/copyleft/lesser.txt.
-----------------------------------------------------------------------------
*/
#include "Q3BSP.h"
#include <stdio.h>
#include <iostream>
#include <fstream>
float bzpScale = 0.25f;
Quake3Level::Quake3Level()
{
data = NULL;
}
Quake3Level::~Quake3Level()
{
if (data)
free (data);
}
void Quake3Level::loadFromFile ( const char* fileName)
{
if(!fileName)
return;
theFileName = fileName;
initialise();
#ifdef _DEBUG
dumpContents();
#endif
}
// byte swapping functions
void SwapFourBytes(unsigned long *dw)
{
unsigned long tmp;
tmp = (*dw & 0x000000FF);
tmp = ((*dw & 0x0000FF00) >> 0x08) | (tmp << 0x08);
tmp = ((*dw & 0x00FF0000) >> 0x10) | (tmp << 0x08);
tmp = ((*dw & 0xFF000000) >> 0x18) | (tmp << 0x08);
memcpy (dw, &tmp, sizeof(unsigned long));
}
void SwapFourBytesGrup (unsigned long *src, int size)
{
unsigned long *ptr = (unsigned long *)src;
int i;
for (i = 0; i < size/4; ++i) {
SwapFourBytes (&ptr[i]);
}
}
bool Quake3Level::dumpToModel ( CModel &model )
{
model.clear();
for ( int i = 0; i < mNumShaders; i++)
{
CMaterial material;
char temp[128];
strcpy(temp, mShaders[i].name);
if (strrchr(temp,'.'))
*(strrchr(temp,'.')) = 0;
material.texture = temp;
material.texture += ".png";
model.materials[std::string(temp)] = material;
}
for ( int i = 0; i < mNumFaces; i++ )
{
switch( mFaces[i].type )
{
case 1: // polygon face
case 3: // mesh face
{
CMesh mesh;
// add in the verts and normals and UVs
for ( int j = mFaces[i].vert_count-1; j >= 0; j-- )
{
CVertex vert;
CVertex norm;
CTexCoord coord;
int index = mFaces[i].vert_start + j;
if ( index > 0 && index < mNumVertices)
{
vert.x = mVertices[index].point[0]*bzpScale;
vert.y = mVertices[index].point[1]*bzpScale;
vert.z = mVertices[index].point[2]*bzpScale;
norm.x = mVertices[index].normal[0];
norm.y = mVertices[index].normal[1];
norm.z = mVertices[index].normal[2];
coord.u = mVertices[index].texture[0];
coord.v = mVertices[index].texture[1];
}
mesh.verts.push_back(vert);
mesh.normals.push_back(norm);
mesh.texCoords.push_back(coord);
}
// now do the face
CFace face;
if ( mFaces[i].shader > 0 && mFaces[i].shader < mNumShaders)
{
char temp[128];
if (strlen(mShaders[mFaces[i].shader].name) )
{
strcpy(temp, mShaders[mFaces[i].shader].name);
char *p = strrchr(temp,'.');
if (p)
*p = 0;
face.material = temp;
}
int iBlarg = 10;
iBlarg++;
}
int maxIndex = mFaces[i].vert_start + mFaces[i].vert_count -1;
if ( maxIndex < mNumVertices)
{
for( int j = 0; j < mFaces[i].vert_count; j++)
{
face.verts.push_back(j);
face.normals.push_back(j);
face.texCoords.push_back(j);
}
mesh.faces.push_back(face);
}
if ( mesh.faces.size())
model.meshes.push_back(mesh);
}
break;
case 2: // surface
break;
case 4: //billboard
break;
default:
// something else
break;
}
}
return model.meshes.size() > 0;
}
void Quake3Level::initialise(void)
{
FILE *fp = fopen(theFileName.c_str(),"rb");
if (!fp)
return;
fseek(fp,0,SEEK_END);
unsigned int size = ftell(fp);
fseek(fp,0,SEEK_SET);
if (data)
free(data);
data = (char*)malloc(size);
fread(data,size,1,fp);
fclose(fp);
mHeader = (bsp_header_t*)data;
mLumpStart = ((unsigned char*)mHeader) + sizeof(mHeader);
mEntities = (unsigned char*)getLump(BSP_ENTITIES_LUMP);
mNumEntities = getLumpSize(BSP_ENTITIES_LUMP);
mElements = (int*)getLump(BSP_ELEMENTS_LUMP);
mNumElements = getLumpSize(BSP_ELEMENTS_LUMP) / sizeof(int);
mFaces = (bsp_face_t*)getLump(BSP_FACES_LUMP);
mNumFaces = getLumpSize(BSP_FACES_LUMP) / sizeof(bsp_face_t);
mLeafFaces = (int*)getLump(BSP_LFACES_LUMP);
mNumLeafFaces = getLumpSize(BSP_LFACES_LUMP) / sizeof(int);
mLeaves = (bsp_leaf_t*)getLump(BSP_LEAVES_LUMP);
mNumLeaves = getLumpSize(BSP_LEAVES_LUMP) / sizeof(bsp_leaf_t);
mLightmaps = (unsigned char*)getLump(BSP_LIGHTMAPS_LUMP);
mNumLightmaps = getLumpSize(BSP_LIGHTMAPS_LUMP)/BSP_LIGHTMAP_BANKSIZE;
mModels = (bsp_model_t*)getLump(BSP_MODELS_LUMP);
mNumModels = getLumpSize(BSP_MODELS_LUMP) / sizeof(bsp_model_t);
mNodes = (bsp_node_t*)getLump(BSP_NODES_LUMP);
mNumNodes = getLumpSize(BSP_NODES_LUMP) / sizeof(bsp_node_t);
mPlanes = (bsp_plane_t*) getLump(BSP_PLANES_LUMP);
mNumPlanes = getLumpSize(BSP_PLANES_LUMP)/sizeof(bsp_plane_t);
mShaders = (bsp_shader_t*) getLump(BSP_SHADERS_LUMP);
mNumShaders = getLumpSize(BSP_SHADERS_LUMP)/sizeof(bsp_shader_t);
mVis = (bsp_vis_t*)getLump(BSP_VISIBILITY_LUMP);
mVertices = (bsp_vertex_t*) getLump(BSP_VERTICES_LUMP);
mNumVertices = getLumpSize(BSP_VERTICES_LUMP)/sizeof(bsp_vertex_t);
mLeafBrushes = (int*)getLump(BSP_LBRUSHES_LUMP);
mNumLeafBrushes = getLumpSize(BSP_LBRUSHES_LUMP)/sizeof(int);
mBrushes = (bsp_brush_t*) getLump(BSP_BRUSH_LUMP);
mNumBrushes = getLumpSize(BSP_BRUSH_LUMP)/sizeof(bsp_brush_t);
mBrushSides = (bsp_brushside_t*) getLump(BSP_BRUSHSIDES_LUMP);
mNumBrushSides = getLumpSize(BSP_BRUSHSIDES_LUMP)/sizeof(bsp_brushside_t);
#ifdef __APPLE___
int i=0;
// swap header
SwapFourBytes (&mHeader->version);
SwapFourBytesGrup ((unsigned long*)mElements, mNumElements*sizeof(int));
SwapFourBytesGrup ((unsigned long*)mFaces, mNumFaces*sizeof(bsp_face_t));
SwapFourBytesGrup ((unsigned long*)mLeafFaces, mNumLeafFaces*sizeof(int));
SwapFourBytesGrup ((unsigned long*)mLeaves, mNumLeaves*sizeof(bsp_leaf_t));
SwapFourBytesGrup ((unsigned long*)mModels, mNumModels*sizeof(bsp_model_t));
SwapFourBytesGrup ((unsigned long*)mNodes, mNumNodes*sizeof(bsp_node_t));
SwapFourBytesGrup ((unsigned long*)mPlanes, mNumPlanes*sizeof(bsp_plane_t));
for (i=0; i < mNumShaders; ++i) {
SwapFourBytes(&mShaders[i].surface_flags);
SwapFourBytes(&mShaders[i].content_flags);
}
SwapFourBytes(&mVis->cluster_count);
SwapFourBytes(&mVis->row_size);
SwapFourBytesGrup ((unsigned long*)mVertices, mNumVertices*sizeof(bsp_vertex_t));
SwapFourBytesGrup ((unsigned long*)mLeafBrushes, mNumLeafBrushes*sizeof(int));
SwapFourBytesGrup ((unsigned long*)mBrushes, mNumBrushes*sizeof(bsp_brush_t));
SwapFourBytesGrup ((unsigned long*)mBrushSides, mNumBrushSides*sizeof(bsp_brushside_t));
#endif
}
void* Quake3Level::getLump(int lumpType)
{
#ifdef __APPLE___
// swap lump offset
SwapFourBytes (&mHeader->lumps[lumpType].offset);
#endif
return (unsigned char*)mHeader + mHeader->lumps[lumpType].offset;
}
int Quake3Level::getLumpSize(int lumpType)
{
#ifdef __APPLE___
// swap lump size
SwapFourBytes (&mHeader->lumps[lumpType].size);
#endif
return mHeader->lumps[lumpType].size;
}
void Quake3Level::dumpContents(void)
{
std::ofstream of;
of.open("Quake3Level.log");
of << "Quake3 level statistics" << std::endl;
of << "-----------------------" << std::endl;
of << "Entities : " << mNumEntities << std::endl;
of << "Faces : " << mNumFaces << std::endl;
of << "Leaf Faces : " << mNumLeafFaces << std::endl;
of << "Leaves : " << mNumLeaves << std::endl;
of << "Lightmaps : " << mNumLightmaps << std::endl;
of << "Elements : " << mNumElements << std::endl;
of << "Models : " << mNumModels << std::endl;
of << "Nodes : " << mNumNodes << std::endl;
of << "Planes : " << mNumPlanes << std::endl;
of << "Shaders : " << mNumShaders << std::endl;
of << "Vertices : " << mNumVertices << std::endl;
// of << "Vis Clusters : " << mVis->cluster_count << std::endl;
of << std::endl;
of << "-= Shaders =-";
of << std::endl;
for (int i = 0; i < mNumShaders; ++i)
{
of << "Shader " << i << ": " << mShaders[i].name << std::endl;
}
of << std::endl;
of << "-= Entities =-";
of << std::endl;
char* strEnt = strtok((char*)mEntities, "\0");
while (strEnt != 0)
{
of << strEnt << std::endl;
strEnt = strtok(0, "\0");
}
of.close();
}
void Quake3Level::extractLightmaps(void) const
{
// Lightmaps are always 128x128x24 (RGB)
unsigned char* pLightmap = mLightmaps;
for (int i = 0; i < mNumLightmaps; ++i)
{
char name[32];
sprintf(name, "@lightmap%d", i);
/* // Load, no mipmaps, brighten by factor 2.5
Image img; img.loadRawData( DataChunk( pLightmap, 128 * 128 * 3 ), 128, 128, PF_R8G8B8 );
TextureManager::getSingleton().loadImage( name, img, TEX_TYPE_2D, 0, 4.0f );
pLightmap += BSP_LIGHTMAP_BANKSIZE;
*/
}
}
<|endoftext|>
|
<commit_before>#include <blackhole/formatter/string.hpp>
#include <blackhole/keyword/message.hpp>
#include <blackhole/keyword/timestamp.hpp>
#include "global.hpp"
using namespace blackhole;
TEST(string_t, FormatSingleAttribute) {
record_t record;
record.insert(keyword::message() = "le message");
std::string pattern("[%(message)s]");
formatter::string_t fmt(pattern);
EXPECT_EQ("[le message]", fmt.format(record));
}
TEST(string_t, FormatMultipleAttributes) {
record_t record;
record.insert(keyword::message() = "le message");
record.insert({ "timestamp", attribute_t("le timestamp") });
std::string pattern("[%(timestamp)s]: %(message)s");
formatter::string_t fmt(pattern);
EXPECT_EQ("[le timestamp]: le message", fmt.format(record));
}
TEST(string_t, FormatMultipleAttributesMoreThanExists) {
record_t record;
record.insert(keyword::message() = "le message");
record.insert({ "timestamp", attribute_t("le timestamp") });
record.insert({ "source", attribute_t("le source") });
std::string pattern("[%(timestamp)s]: %(message)s");
formatter::string_t fmt(pattern);
EXPECT_EQ("[le timestamp]: le message", fmt.format(record));
}
TEST(string_t, ThrowsExceptionWhenAttributeNameNotProvided) {
record_t record;
record.insert(keyword::message() = "le message");
std::string pattern("[%(timestamp)s]: %(message)s");
formatter::string_t fmt(pattern);
EXPECT_THROW(fmt.format(record), blackhole::error_t);
}
TEST(string_t, FormatOtherLocalAttribute) {
record_t record;
record.insert({ "uuid", attribute_t("123-456") });
std::string pattern("[%(...L)s]");
formatter::string_t formatter(pattern);
EXPECT_EQ("['uuid': '123-456']", formatter.format(record));
}
TEST(string_t, FormatOtherLocalAttributes) {
record_t record;
record.insert({ "uuid", attribute_t("123-456") });
record.insert({ "answer to life the universe and everything", attribute_t(42) });
std::string pattern("[%(...L)s]");
formatter::string_t formatter(pattern);
std::string actual = formatter.format(record);
EXPECT_TRUE(actual.find("'answer to life the universe and everything': 42") != std::string::npos);
EXPECT_TRUE(actual.find("'uuid': '123-456'") != std::string::npos);
}
TEST(string_t, ComplexFormatWithOtherLocalAttributes) {
record_t record;
record.insert({ "timestamp", attribute_t("1960-01-01 00:00:00", attribute::scope_t::event) });
record.insert({ "level", attribute_t("INFO", attribute::scope_t::event) });
record.insert(keyword::message() = "le message");
record.insert({ "uuid", attribute_t("123-456") });
record.insert({ "answer to life the universe and everything", attribute_t(42) });
std::string pattern("[%(timestamp)s] [%(level)s]: %(message)s [%(...L)s]");
formatter::string_t formatter(pattern);
std::string actual = formatter.format(record);
EXPECT_TRUE(boost::starts_with(actual, "[1960-01-01 00:00:00] [INFO]: le message ["));
EXPECT_TRUE(actual.find("'answer to life the universe and everything': 42") != std::string::npos);
EXPECT_TRUE(actual.find("'uuid': '123-456'") != std::string::npos);
}
namespace testing {
void map_timestamp(blackhole::aux::attachable_ostringstream& stream, const timeval& tv) {
char str[64];
struct tm tm;
gmtime_r((time_t *)&tv.tv_sec, &tm);
if (std::strftime(str, sizeof(str), "%F %T", &tm)) {
char usecs[64];
snprintf(usecs, sizeof(usecs), ".%06ld", (long)tv.tv_usec);
stream << str << usecs;
} else {
stream << "UNKNOWN";
}
}
} // namespace testing
TEST(string_t, CustomMapping) {
mapping::value_t mapper;
mapper.add<timeval>("timestamp", &testing::map_timestamp);
record_t record;
record.insert(keyword::timestamp() = timeval { 100500, 0 });
record.insert(keyword::message() = "le message");
std::string pattern("[%(timestamp)s]: %(message)s");
formatter::string_t formatter(pattern);
formatter.set_mapper(std::move(mapper));
std::string actual = formatter.format(record);
EXPECT_EQ(actual, "[1970-01-02 03:55:00.000000]: le message");
}
TEST(string_t, CustomMappingWithKeyword) {
mapping::value_t mapper;
mapper.add<keyword::tag::timestamp_t>(&testing::map_timestamp);
record_t record;
record.insert(keyword::timestamp() = timeval { 100500, 0 });
record.insert(keyword::message() = "le message");
std::string pattern("[%(timestamp)s]: %(message)s");
formatter::string_t formatter(pattern);
formatter.set_mapper(std::move(mapper));
std::string actual = formatter.format(record);
EXPECT_EQ(actual, "[1970-01-02 03:55:00.000000]: le message");
}
TEST(mapping, DatetimeMapping) {
mapping::value_t mapper;
mapper.add<keyword::tag::timestamp_t>("%Y-%m-%d %H:%M:%S");
std::string result;
aux::attachable_ostringstream stream;
stream.attach(result);
timeval tv{ 100500, 0 };
mapper(stream, "timestamp", tv);
EXPECT_EQ("1970-01-02 03:55:00", result);
}
TEST(string_t, OptionalKeywordIsPresent) {
record_t record;
record.insert(attribute::make("message", "le message"));
record.insert(attribute::make("id", 42));
std::string pattern("<%([id])?s>: [%(message)s]");
formatter::string_t fmt(pattern);
EXPECT_EQ("<42>: [le message]", fmt.format(record));
}
TEST(string_t, OptionalKeywordIsNotPresent) {
record_t record;
record.insert(attribute::make("message", "le message"));
std::string pattern("<%([id])?s>: [%(message)s]");
formatter::string_t fmt(pattern);
EXPECT_EQ("<>: [le message]", fmt.format(record));
}
TEST(string_t, OptionalKeywordWithPrefixIsPresent) {
record_t record;
record.insert(attribute::make("message", "le message"));
record.insert(attribute::make("id", 42));
std::string pattern("<%(.[id])?s>: [%(message)s]");
formatter::string_t fmt(pattern);
EXPECT_EQ("<.42>: [le message]", fmt.format(record));
}
TEST(string_t, OptionalKeywordWithPrefixIsNotPresent) {
record_t record;
record.insert(attribute::make("message", "le message"));
std::string pattern("<%(.[id])?s>: [%(message)s]");
formatter::string_t fmt(pattern);
EXPECT_EQ("<>: [le message]", fmt.format(record));
}
TEST(string_t, OptionalKeywordWithSuffixIsPresent) {
record_t record;
record.insert(attribute::make("message", "le message"));
record.insert(attribute::make("id", 42));
std::string pattern("<%([id].)?s>: [%(message)s]");
formatter::string_t fmt(pattern);
EXPECT_EQ("<42.>: [le message]", fmt.format(record));
}
TEST(string_t, OptionalKeywordWithSuffixIsNotPresent) {
record_t record;
record.insert(attribute::make("message", "le message"));
std::string pattern("<%([id].)?s>: [%(message)s]");
formatter::string_t fmt(pattern);
EXPECT_EQ("<>: [le message]", fmt.format(record));
}
TEST(string_t, OptionalKeywordWithPrefixSuffixIsPresent) {
record_t record;
record.insert(attribute::make("message", "le message"));
record.insert(attribute::make("id", 42));
std::string pattern("<%(.[id].)?s>: [%(message)s]");
formatter::string_t fmt(pattern);
EXPECT_EQ("<.42.>: [le message]", fmt.format(record));
}
TEST(string_t, OptionalKeywordWithPrefixSuffixIsNotPresent) {
record_t record;
record.insert(attribute::make("message", "le message"));
std::string pattern("<%(.[id].)?s>: [%(message)s]");
formatter::string_t fmt(pattern);
EXPECT_EQ("<>: [le message]", fmt.format(record));
}
TEST(string_t, OptionalKeywordIsPresentWithPrefixSuffixParentheses) {
record_t record;
record.insert(attribute::make("message", "le message"));
record.insert(attribute::make("id", 42));
std::string pattern("<%(([id]))?s>: [%(message)s]");
formatter::string_t fmt(pattern);
EXPECT_EQ("<(42)>: [le message]", fmt.format(record));
}
TEST(string_t, OptionalKeywordIsNotPresentWithPrefixSuffixParentheses) {
record_t record;
record.insert(attribute::make("message", "le message"));
std::string pattern("<%(([id]))?s>: [%(message)s]");
formatter::string_t fmt(pattern);
EXPECT_EQ("<>: [le message]", fmt.format(record));
}
TEST(string_t, OptionalKeywordIsPresentWithPrefixSuffixReverseParentheses) {
record_t record;
record.insert(attribute::make("message", "le message"));
record.insert(attribute::make("id", 42));
std::string pattern("<%()[id]()?s>: [%(message)s]");
formatter::string_t fmt(pattern);
EXPECT_EQ("<)42(>: [le message]", fmt.format(record));
}
TEST(string_t, OptionalKeywordIsNotPresentWithPrefixSuffixReverseParentheses) {
record_t record;
record.insert(attribute::make("message", "le message"));
std::string pattern("<%()[id]()?s>: [%(message)s]");
formatter::string_t fmt(pattern);
EXPECT_EQ("<>: [le message]", fmt.format(record));
}
TEST(string_t, OptionalKeywordIsPresentWithPrefixSuffixSquareBrackets) {
record_t record;
record.insert(attribute::make("message", "le message"));
record.insert(attribute::make("id", 42));
std::string pattern("<%(\\[[id]\\])?s>: [%(message)s]");
formatter::string_t fmt(pattern);
EXPECT_EQ("<[42]>: [le message]", fmt.format(record));
}
TEST(string_t, OptionalKeywordIsNotPresentWithPrefixSuffixSquareBrackets) {
record_t record;
record.insert(attribute::make("message", "le message"));
std::string pattern("<%(\\[[id]\\])?s>: [%(message)s]");
formatter::string_t fmt(pattern);
EXPECT_EQ("<>: [le message]", fmt.format(record));
}
TEST(string_t, OptionalKeywordIsPresentWithPrefixSuffixSquareBracketsReversed) {
record_t record;
record.insert(attribute::make("message", "le message"));
record.insert(attribute::make("id", 42));
std::string pattern("<%(\\][id]\\[)?s>: [%(message)s]");
formatter::string_t fmt(pattern);
EXPECT_EQ("<]42[>: [le message]", fmt.format(record));
}
TEST(string_t, OptionalKeywordIsNotPresentWithPrefixSuffixSquareBracketsReversed) {
record_t record;
record.insert(attribute::make("message", "le message"));
std::string pattern("<%(\\][id]\\[)?s>: [%(message)s]");
formatter::string_t fmt(pattern);
EXPECT_EQ("<>: [le message]", fmt.format(record));
}
<commit_msg>[Unit Testing] Naming.<commit_after>#include <blackhole/formatter/string.hpp>
#include <blackhole/keyword/message.hpp>
#include <blackhole/keyword/timestamp.hpp>
#include "global.hpp"
using namespace blackhole;
TEST(string_t, FormatSingleAttribute) {
record_t record;
record.insert(keyword::message() = "le message");
std::string pattern("[%(message)s]");
formatter::string_t fmt(pattern);
EXPECT_EQ("[le message]", fmt.format(record));
}
TEST(string_t, FormatMultipleAttributes) {
record_t record;
record.insert(keyword::message() = "le message");
record.insert({ "timestamp", attribute_t("le timestamp") });
std::string pattern("[%(timestamp)s]: %(message)s");
formatter::string_t fmt(pattern);
EXPECT_EQ("[le timestamp]: le message", fmt.format(record));
}
TEST(string_t, FormatMultipleAttributesMoreThanExists) {
record_t record;
record.insert(keyword::message() = "le message");
record.insert({ "timestamp", attribute_t("le timestamp") });
record.insert({ "source", attribute_t("le source") });
std::string pattern("[%(timestamp)s]: %(message)s");
formatter::string_t fmt(pattern);
EXPECT_EQ("[le timestamp]: le message", fmt.format(record));
}
TEST(string_t, ThrowsExceptionWhenAttributeNameNotProvided) {
record_t record;
record.insert(keyword::message() = "le message");
std::string pattern("[%(timestamp)s]: %(message)s");
formatter::string_t fmt(pattern);
EXPECT_THROW(fmt.format(record), blackhole::error_t);
}
TEST(string_t, FormatOtherLocalAttribute) {
record_t record;
record.insert({ "uuid", attribute_t("123-456") });
std::string pattern("[%(...L)s]");
formatter::string_t formatter(pattern);
EXPECT_EQ("['uuid': '123-456']", formatter.format(record));
}
TEST(string_t, FormatOtherLocalAttributes) {
record_t record;
record.insert({ "uuid", attribute_t("123-456") });
record.insert({ "answer to life the universe and everything", attribute_t(42) });
std::string pattern("[%(...L)s]");
formatter::string_t formatter(pattern);
std::string actual = formatter.format(record);
EXPECT_TRUE(actual.find("'answer to life the universe and everything': 42") != std::string::npos);
EXPECT_TRUE(actual.find("'uuid': '123-456'") != std::string::npos);
}
TEST(string_t, ComplexFormatWithOtherLocalAttributes) {
record_t record;
record.insert({ "timestamp", attribute_t("1960-01-01 00:00:00", attribute::scope_t::event) });
record.insert({ "level", attribute_t("INFO", attribute::scope_t::event) });
record.insert(keyword::message() = "le message");
record.insert({ "uuid", attribute_t("123-456") });
record.insert({ "answer to life the universe and everything", attribute_t(42) });
std::string pattern("[%(timestamp)s] [%(level)s]: %(message)s [%(...L)s]");
formatter::string_t formatter(pattern);
std::string actual = formatter.format(record);
EXPECT_TRUE(boost::starts_with(actual, "[1960-01-01 00:00:00] [INFO]: le message ["));
EXPECT_TRUE(actual.find("'answer to life the universe and everything': 42") != std::string::npos);
EXPECT_TRUE(actual.find("'uuid': '123-456'") != std::string::npos);
}
namespace testing {
void map_timestamp(blackhole::aux::attachable_ostringstream& stream, const timeval& tv) {
char str[64];
struct tm tm;
gmtime_r((time_t *)&tv.tv_sec, &tm);
if (std::strftime(str, sizeof(str), "%F %T", &tm)) {
char usecs[64];
snprintf(usecs, sizeof(usecs), ".%06ld", (long)tv.tv_usec);
stream << str << usecs;
} else {
stream << "UNKNOWN";
}
}
} // namespace testing
TEST(string_t, CustomMapping) {
mapping::value_t mapper;
mapper.add<timeval>("timestamp", &testing::map_timestamp);
record_t record;
record.insert(keyword::timestamp() = timeval { 100500, 0 });
record.insert(keyword::message() = "le message");
std::string pattern("[%(timestamp)s]: %(message)s");
formatter::string_t formatter(pattern);
formatter.set_mapper(std::move(mapper));
std::string actual = formatter.format(record);
EXPECT_EQ(actual, "[1970-01-02 03:55:00.000000]: le message");
}
TEST(string_t, CustomMappingWithKeyword) {
mapping::value_t mapper;
mapper.add<keyword::tag::timestamp_t>(&testing::map_timestamp);
record_t record;
record.insert(keyword::timestamp() = timeval { 100500, 0 });
record.insert(keyword::message() = "le message");
std::string pattern("[%(timestamp)s]: %(message)s");
formatter::string_t formatter(pattern);
formatter.set_mapper(std::move(mapper));
std::string actual = formatter.format(record);
EXPECT_EQ(actual, "[1970-01-02 03:55:00.000000]: le message");
}
TEST(mapping, DatetimeMapping) {
mapping::value_t mapper;
mapper.add<keyword::tag::timestamp_t>("%Y-%m-%d %H:%M:%S");
std::string result;
aux::attachable_ostringstream stream;
stream.attach(result);
timeval tv{ 100500, 0 };
mapper(stream, "timestamp", tv);
EXPECT_EQ("1970-01-02 03:55:00", result);
}
#define TEST_STRING_FORMATTER(Suite, Case) \
TEST(string_t##_##Suite, Case)
TEST_STRING_FORMATTER(Optional, Keyword) {
record_t record;
record.insert(attribute::make("message", "le message"));
record.insert(attribute::make("id", 42));
std::string pattern("<%([id])?s>: [%(message)s]");
formatter::string_t fmt(pattern);
EXPECT_EQ("<42>: [le message]", fmt.format(record));
}
TEST_STRING_FORMATTER(Optional, AbsentKeyword) {
record_t record;
record.insert(attribute::make("message", "le message"));
std::string pattern("<%([id])?s>: [%(message)s]");
formatter::string_t fmt(pattern);
EXPECT_EQ("<>: [le message]", fmt.format(record));
}
TEST_STRING_FORMATTER(Optional, WithPrefix) {
record_t record;
record.insert(attribute::make("message", "le message"));
record.insert(attribute::make("id", 42));
std::string pattern("<%(.[id])?s>: [%(message)s]");
formatter::string_t fmt(pattern);
EXPECT_EQ("<.42>: [le message]", fmt.format(record));
}
TEST_STRING_FORMATTER(Optional, AbsentWithPrefix) {
record_t record;
record.insert(attribute::make("message", "le message"));
std::string pattern("<%(.[id])?s>: [%(message)s]");
formatter::string_t fmt(pattern);
EXPECT_EQ("<>: [le message]", fmt.format(record));
}
TEST_STRING_FORMATTER(Optional, WithSuffix) {
record_t record;
record.insert(attribute::make("message", "le message"));
record.insert(attribute::make("id", 42));
std::string pattern("<%([id].)?s>: [%(message)s]");
formatter::string_t fmt(pattern);
EXPECT_EQ("<42.>: [le message]", fmt.format(record));
}
TEST_STRING_FORMATTER(Optional, AbsentWithSuffix) {
record_t record;
record.insert(attribute::make("message", "le message"));
std::string pattern("<%([id].)?s>: [%(message)s]");
formatter::string_t fmt(pattern);
EXPECT_EQ("<>: [le message]", fmt.format(record));
}
TEST_STRING_FORMATTER(Optional, WithPrefixSuffix) {
record_t record;
record.insert(attribute::make("message", "le message"));
record.insert(attribute::make("id", 42));
std::string pattern("<%(.[id].)?s>: [%(message)s]");
formatter::string_t fmt(pattern);
EXPECT_EQ("<.42.>: [le message]", fmt.format(record));
}
TEST_STRING_FORMATTER(Optional, AbsentWithPrefixSuffix) {
record_t record;
record.insert(attribute::make("message", "le message"));
std::string pattern("<%(.[id].)?s>: [%(message)s]");
formatter::string_t fmt(pattern);
EXPECT_EQ("<>: [le message]", fmt.format(record));
}
TEST_STRING_FORMATTER(Optional, WithPrefixSuffixParentheses) {
record_t record;
record.insert(attribute::make("message", "le message"));
record.insert(attribute::make("id", 42));
std::string pattern("<%(([id]))?s>: [%(message)s]");
formatter::string_t fmt(pattern);
EXPECT_EQ("<(42)>: [le message]", fmt.format(record));
}
TEST_STRING_FORMATTER(Optional, AbsentWithPrefixSuffixParentheses) {
record_t record;
record.insert(attribute::make("message", "le message"));
std::string pattern("<%(([id]))?s>: [%(message)s]");
formatter::string_t fmt(pattern);
EXPECT_EQ("<>: [le message]", fmt.format(record));
}
TEST_STRING_FORMATTER(Optional, WithPrefixSuffixReverseParentheses) {
record_t record;
record.insert(attribute::make("message", "le message"));
record.insert(attribute::make("id", 42));
std::string pattern("<%()[id]()?s>: [%(message)s]");
formatter::string_t fmt(pattern);
EXPECT_EQ("<)42(>: [le message]", fmt.format(record));
}
TEST_STRING_FORMATTER(Optional, AbsentWithPrefixSuffixReverseParentheses) {
record_t record;
record.insert(attribute::make("message", "le message"));
std::string pattern("<%()[id]()?s>: [%(message)s]");
formatter::string_t fmt(pattern);
EXPECT_EQ("<>: [le message]", fmt.format(record));
}
TEST_STRING_FORMATTER(Optional, WithPrefixSuffixSquareBrackets) {
record_t record;
record.insert(attribute::make("message", "le message"));
record.insert(attribute::make("id", 42));
std::string pattern("<%(\\[[id]\\])?s>: [%(message)s]");
formatter::string_t fmt(pattern);
EXPECT_EQ("<[42]>: [le message]", fmt.format(record));
}
TEST_STRING_FORMATTER(Optional, AbsentWithPrefixSuffixSquareBrackets) {
record_t record;
record.insert(attribute::make("message", "le message"));
std::string pattern("<%(\\[[id]\\])?s>: [%(message)s]");
formatter::string_t fmt(pattern);
EXPECT_EQ("<>: [le message]", fmt.format(record));
}
TEST_STRING_FORMATTER(Optional, WithPrefixSuffixSquareBracketsReversed) {
record_t record;
record.insert(attribute::make("message", "le message"));
record.insert(attribute::make("id", 42));
std::string pattern("<%(\\][id]\\[)?s>: [%(message)s]");
formatter::string_t fmt(pattern);
EXPECT_EQ("<]42[>: [le message]", fmt.format(record));
}
TEST_STRING_FORMATTER(Optional, AbsentWithPrefixSuffixSquareBracketsReversed) {
record_t record;
record.insert(attribute::make("message", "le message"));
std::string pattern("<%(\\][id]\\[)?s>: [%(message)s]");
formatter::string_t fmt(pattern);
EXPECT_EQ("<>: [le message]", fmt.format(record));
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2009 - Mozy, Inc.
#include "timer.h"
#include <algorithm>
#include <vector>
#include "assert.h"
#include "atomic.h"
#include "exception.h"
#include "log.h"
#include "version.h"
#include "util.h"
#include "config.h"
#ifdef OSX
#include <mach/mach_time.h>
#elif defined(WINDOWS)
#include <windows.h> // for LARGE_INTEGER, QueryPerformanceFrequency()
#else
#include <sys/time.h>
#include <time.h>
#endif
namespace Mordor {
boost::function<unsigned long long ()> TimerManager::ms_clockDg;
static Logger::ptr g_log = Log::lookup("mordor:timer");
// now() doesn't roll over at 0xffff...., because underlying hardware timers
// do not count in microseconds; also, prevent clock anomalies from causing
// timers that will never expire
static ConfigVar<unsigned long long>::ptr g_clockRolloverThreshold =
Config::lookup<unsigned long long>("timer.clockrolloverthreshold", 5000000ULL,
"Expire all timers if the clock goes backward by >= this amount");
static void
stubOnTimer(boost::weak_ptr<void> weakCond, boost::function<void ()> dg);
#ifdef WINDOWS
static unsigned long long queryFrequency()
{
LARGE_INTEGER frequency;
BOOL bRet = QueryPerformanceFrequency(&frequency);
MORDOR_ASSERT(bRet);
return (unsigned long long)frequency.QuadPart;
}
unsigned long long g_frequency = queryFrequency();
#elif defined (OSX)
static mach_timebase_info_data_t queryTimebase()
{
mach_timebase_info_data_t timebase;
mach_timebase_info(&timebase);
return timebase;
}
mach_timebase_info_data_t g_timebase = queryTimebase();
#endif
unsigned long long
TimerManager::now()
{
if (ms_clockDg)
return ms_clockDg();
#ifdef WINDOWS
LARGE_INTEGER count;
if (!QueryPerformanceCounter(&count))
MORDOR_THROW_EXCEPTION_FROM_LAST_ERROR_API("QueryPerformanceCounter");
unsigned long long countUll = (unsigned long long)count.QuadPart;
if (g_frequency == 0)
g_frequency = queryFrequency();
return muldiv64(countUll, 1000000, g_frequency);
#elif defined(OSX)
unsigned long long absoluteTime = mach_absolute_time();
if (g_timebase.denom == 0)
g_timebase = queryTimebase();
return muldiv64(absoluteTime, g_timebase.numer, (uint64_t)g_timebase.denom * 1000);
#else
struct timespec ts;
if (clock_gettime(CLOCK_MONOTONIC, &ts))
MORDOR_THROW_EXCEPTION_FROM_LAST_ERROR_API("clock_gettime");
return ts.tv_sec * 1000000ull + ts.tv_nsec / 1000;
#endif
}
Timer::Timer(unsigned long long us, boost::function<void ()> dg, bool recurring,
TimerManager *manager)
: m_recurring(recurring),
m_us(us),
m_dg(dg),
m_manager(manager)
{
MORDOR_ASSERT(m_dg);
m_next = TimerManager::now() + m_us;
}
Timer::Timer(unsigned long long next)
: m_next(next)
{}
bool
Timer::cancel()
{
MORDOR_LOG_DEBUG(g_log) << this << " cancel";
boost::mutex::scoped_lock lock(m_manager->m_mutex);
if (m_dg) {
m_dg = NULL;
std::set<Timer::ptr, Timer::Comparator>::iterator it =
m_manager->m_timers.find(shared_from_this());
MORDOR_ASSERT(it != m_manager->m_timers.end());
m_manager->m_timers.erase(it);
return true;
}
return false;
}
bool
Timer::refresh()
{
boost::mutex::scoped_lock lock(m_manager->m_mutex);
if (!m_dg)
return false;
std::set<Timer::ptr, Timer::Comparator>::iterator it =
m_manager->m_timers.find(shared_from_this());
MORDOR_ASSERT(it != m_manager->m_timers.end());
m_manager->m_timers.erase(it);
m_next = TimerManager::now() + m_us;
m_manager->m_timers.insert(shared_from_this());
lock.unlock();
MORDOR_LOG_DEBUG(g_log) << this << " refresh";
return true;
}
bool
Timer::reset(unsigned long long us, bool fromNow)
{
boost::mutex::scoped_lock lock(m_manager->m_mutex);
if (!m_dg)
return false;
// No change
if (us == m_us && !fromNow)
return true;
std::set<Timer::ptr, Timer::Comparator>::iterator it =
m_manager->m_timers.find(shared_from_this());
MORDOR_ASSERT(it != m_manager->m_timers.end());
m_manager->m_timers.erase(it);
unsigned long long start;
if (fromNow)
start = TimerManager::now();
else
start = m_next - m_us;
m_us = us;
m_next = start + m_us;
it = m_manager->m_timers.insert(shared_from_this()).first;
bool atFront = (it == m_manager->m_timers.begin()) && !m_manager->m_tickled;
if (atFront)
m_manager->m_tickled = true;
lock.unlock();
MORDOR_LOG_DEBUG(g_log) << this << " reset to " << m_us;
if (atFront)
m_manager->onTimerInsertedAtFront();
return true;
}
TimerManager::TimerManager()
: m_tickled(false),
m_previousTime(0ull)
{}
TimerManager::~TimerManager()
{
#ifndef NDEBUG
boost::mutex::scoped_lock lock(m_mutex);
MORDOR_ASSERT(m_timers.empty());
#endif
}
Timer::ptr
TimerManager::registerTimer(unsigned long long us, boost::function<void ()> dg,
bool recurring)
{
MORDOR_ASSERT(dg);
Timer::ptr result(new Timer(us, dg, recurring, this));
boost::mutex::scoped_lock lock(m_mutex);
std::set<Timer::ptr, Timer::Comparator>::iterator it =
m_timers.insert(result).first;
bool atFront = (it == m_timers.begin()) && !m_tickled;
if (atFront)
m_tickled = true;
lock.unlock();
MORDOR_LOG_DEBUG(g_log) << result.get() << " registerTimer(" << us
<< ", " << recurring << "): " << atFront;
if (atFront)
onTimerInsertedAtFront();
return result;
}
Timer::ptr
TimerManager::registerConditionTimer(unsigned long long us,
boost::function<void ()> dg,
boost::weak_ptr<void> weakCond,
bool recurring)
{
return registerTimer(us,
boost::bind(stubOnTimer, weakCond, dg),
recurring);
}
static void
stubOnTimer(
boost::weak_ptr<void> weakCond, boost::function<void ()> dg)
{
if (weakCond.lock()) {
dg();
}
else {
MORDOR_LOG_DEBUG(g_log) << " Conditionally skip in stubOnTimer!";
}
}
unsigned long long
TimerManager::nextTimer()
{
boost::mutex::scoped_lock lock(m_mutex);
m_tickled = false;
if (m_timers.empty()) {
MORDOR_LOG_DEBUG(g_log) << this << " nextTimer(): ~0ull";
return ~0ull;
}
const Timer::ptr &next = *m_timers.begin();
unsigned long long nowUs = now();
unsigned long long result;
if (nowUs >= next->m_next)
result = 0;
else
result = next->m_next - nowUs;
MORDOR_LOG_DEBUG(g_log) << this << " nextTimer(): " << result;
return result;
}
bool
TimerManager::detectClockRollover(unsigned long long nowUs)
{
// If the time jumps backward, expire timers (rather than have them
// expire in the distant future or not at all).
// We check this way because now() will not roll from 0xffff... to zero
// since the underlying hardware counter doesn't count microseconds.
// Use a threshold value so we don't overreact to minor clock jitter.
bool rollover = false;
if (nowUs < m_previousTime && // check first in case the next line would underflow
nowUs < m_previousTime - g_clockRolloverThreshold->val())
{
MORDOR_LOG_ERROR(g_log) << this << " clock has rolled back from "
<< m_previousTime << " to " << nowUs << "; expiring all timers";
rollover = true;
}
m_previousTime = nowUs;
return rollover;
}
std::vector<boost::function<void ()> >
TimerManager::processTimers()
{
std::vector<Timer::ptr> expired;
std::vector<boost::function<void ()> > result;
unsigned long long nowUs = now();
{
boost::mutex::scoped_lock lock(m_mutex);
if (m_timers.empty())
return result;
bool rollover = detectClockRollover(nowUs);
if (!rollover && (*m_timers.begin())->m_next > nowUs)
return result;
Timer nowTimer(nowUs);
Timer::ptr nowTimerPtr(&nowTimer, &nop<Timer *>);
// Find all timers that are expired
std::set<Timer::ptr, Timer::Comparator>::iterator it =
rollover ? m_timers.end() : m_timers.lower_bound(nowTimerPtr);
while (it != m_timers.end() && (*it)->m_next == nowUs ) ++it;
// Copy to expired, remove from m_timers;
expired.insert(expired.begin(), m_timers.begin(), it);
m_timers.erase(m_timers.begin(), it);
result.reserve(expired.size());
// Look at expired timers and re-register recurring timers
// (while under the same lock)
for (std::vector<Timer::ptr>::iterator it2(expired.begin());
it2 != expired.end();
++it2) {
Timer::ptr &timer = *it2;
MORDOR_ASSERT(timer->m_dg);
result.push_back(timer->m_dg);
if (timer->m_recurring) {
MORDOR_LOG_TRACE(g_log) << timer << " expired and refreshed";
timer->m_next = nowUs + timer->m_us;
m_timers.insert(timer);
} else {
MORDOR_LOG_TRACE(g_log) << timer << " expired";
timer->m_dg = NULL;
}
}
}
return result;
}
void
TimerManager::executeTimers()
{
std::vector<boost::function<void ()> > expired = processTimers();
// Run the callbacks for each expired timer (not under a lock)
for (std::vector<boost::function<void ()> >::iterator it(expired.begin());
it != expired.end();
++it) {
(*it)();
}
}
void
TimerManager::setClock(boost::function<unsigned long long()> dg)
{
ms_clockDg = dg;
}
bool
Timer::Comparator::operator()(const Timer::ptr &lhs,
const Timer::ptr &rhs) const
{
// Order NULL before everything else
if (!lhs && !rhs)
return false;
if (!lhs)
return true;
if (!rhs)
return false;
// Order primarily on m_next
if (lhs->m_next < rhs->m_next)
return true;
if (rhs->m_next < lhs->m_next)
return false;
// Order by raw pointer for equivalent timeout values
return lhs.get() < rhs.get();
}
}
<commit_msg>hold the shared_ptr during timer execution<commit_after>// Copyright (c) 2009 - Mozy, Inc.
#include "timer.h"
#include <algorithm>
#include <vector>
#include "assert.h"
#include "atomic.h"
#include "exception.h"
#include "log.h"
#include "version.h"
#include "util.h"
#include "config.h"
#ifdef OSX
#include <mach/mach_time.h>
#elif defined(WINDOWS)
#include <windows.h> // for LARGE_INTEGER, QueryPerformanceFrequency()
#else
#include <sys/time.h>
#include <time.h>
#endif
namespace Mordor {
boost::function<unsigned long long ()> TimerManager::ms_clockDg;
static Logger::ptr g_log = Log::lookup("mordor:timer");
// now() doesn't roll over at 0xffff...., because underlying hardware timers
// do not count in microseconds; also, prevent clock anomalies from causing
// timers that will never expire
static ConfigVar<unsigned long long>::ptr g_clockRolloverThreshold =
Config::lookup<unsigned long long>("timer.clockrolloverthreshold", 5000000ULL,
"Expire all timers if the clock goes backward by >= this amount");
static void
stubOnTimer(boost::weak_ptr<void> weakCond, boost::function<void ()> dg);
#ifdef WINDOWS
static unsigned long long queryFrequency()
{
LARGE_INTEGER frequency;
BOOL bRet = QueryPerformanceFrequency(&frequency);
MORDOR_ASSERT(bRet);
return (unsigned long long)frequency.QuadPart;
}
unsigned long long g_frequency = queryFrequency();
#elif defined (OSX)
static mach_timebase_info_data_t queryTimebase()
{
mach_timebase_info_data_t timebase;
mach_timebase_info(&timebase);
return timebase;
}
mach_timebase_info_data_t g_timebase = queryTimebase();
#endif
unsigned long long
TimerManager::now()
{
if (ms_clockDg)
return ms_clockDg();
#ifdef WINDOWS
LARGE_INTEGER count;
if (!QueryPerformanceCounter(&count))
MORDOR_THROW_EXCEPTION_FROM_LAST_ERROR_API("QueryPerformanceCounter");
unsigned long long countUll = (unsigned long long)count.QuadPart;
if (g_frequency == 0)
g_frequency = queryFrequency();
return muldiv64(countUll, 1000000, g_frequency);
#elif defined(OSX)
unsigned long long absoluteTime = mach_absolute_time();
if (g_timebase.denom == 0)
g_timebase = queryTimebase();
return muldiv64(absoluteTime, g_timebase.numer, (uint64_t)g_timebase.denom * 1000);
#else
struct timespec ts;
if (clock_gettime(CLOCK_MONOTONIC, &ts))
MORDOR_THROW_EXCEPTION_FROM_LAST_ERROR_API("clock_gettime");
return ts.tv_sec * 1000000ull + ts.tv_nsec / 1000;
#endif
}
Timer::Timer(unsigned long long us, boost::function<void ()> dg, bool recurring,
TimerManager *manager)
: m_recurring(recurring),
m_us(us),
m_dg(dg),
m_manager(manager)
{
MORDOR_ASSERT(m_dg);
m_next = TimerManager::now() + m_us;
}
Timer::Timer(unsigned long long next)
: m_next(next)
{}
bool
Timer::cancel()
{
MORDOR_LOG_DEBUG(g_log) << this << " cancel";
boost::mutex::scoped_lock lock(m_manager->m_mutex);
if (m_dg) {
m_dg = NULL;
std::set<Timer::ptr, Timer::Comparator>::iterator it =
m_manager->m_timers.find(shared_from_this());
MORDOR_ASSERT(it != m_manager->m_timers.end());
m_manager->m_timers.erase(it);
return true;
}
return false;
}
bool
Timer::refresh()
{
boost::mutex::scoped_lock lock(m_manager->m_mutex);
if (!m_dg)
return false;
std::set<Timer::ptr, Timer::Comparator>::iterator it =
m_manager->m_timers.find(shared_from_this());
MORDOR_ASSERT(it != m_manager->m_timers.end());
m_manager->m_timers.erase(it);
m_next = TimerManager::now() + m_us;
m_manager->m_timers.insert(shared_from_this());
lock.unlock();
MORDOR_LOG_DEBUG(g_log) << this << " refresh";
return true;
}
bool
Timer::reset(unsigned long long us, bool fromNow)
{
boost::mutex::scoped_lock lock(m_manager->m_mutex);
if (!m_dg)
return false;
// No change
if (us == m_us && !fromNow)
return true;
std::set<Timer::ptr, Timer::Comparator>::iterator it =
m_manager->m_timers.find(shared_from_this());
MORDOR_ASSERT(it != m_manager->m_timers.end());
m_manager->m_timers.erase(it);
unsigned long long start;
if (fromNow)
start = TimerManager::now();
else
start = m_next - m_us;
m_us = us;
m_next = start + m_us;
it = m_manager->m_timers.insert(shared_from_this()).first;
bool atFront = (it == m_manager->m_timers.begin()) && !m_manager->m_tickled;
if (atFront)
m_manager->m_tickled = true;
lock.unlock();
MORDOR_LOG_DEBUG(g_log) << this << " reset to " << m_us;
if (atFront)
m_manager->onTimerInsertedAtFront();
return true;
}
TimerManager::TimerManager()
: m_tickled(false),
m_previousTime(0ull)
{}
TimerManager::~TimerManager()
{
#ifndef NDEBUG
boost::mutex::scoped_lock lock(m_mutex);
MORDOR_ASSERT(m_timers.empty());
#endif
}
Timer::ptr
TimerManager::registerTimer(unsigned long long us, boost::function<void ()> dg,
bool recurring)
{
MORDOR_ASSERT(dg);
Timer::ptr result(new Timer(us, dg, recurring, this));
boost::mutex::scoped_lock lock(m_mutex);
std::set<Timer::ptr, Timer::Comparator>::iterator it =
m_timers.insert(result).first;
bool atFront = (it == m_timers.begin()) && !m_tickled;
if (atFront)
m_tickled = true;
lock.unlock();
MORDOR_LOG_DEBUG(g_log) << result.get() << " registerTimer(" << us
<< ", " << recurring << "): " << atFront;
if (atFront)
onTimerInsertedAtFront();
return result;
}
Timer::ptr
TimerManager::registerConditionTimer(unsigned long long us,
boost::function<void ()> dg,
boost::weak_ptr<void> weakCond,
bool recurring)
{
return registerTimer(us,
boost::bind(stubOnTimer, weakCond, dg),
recurring);
}
static void
stubOnTimer(
boost::weak_ptr<void> weakCond, boost::function<void ()> dg)
{
boost::shared_ptr<void> temp = weakCond.lock();
if (temp) {
dg();
} else {
MORDOR_LOG_DEBUG(g_log) << " Conditionally skip in stubOnTimer!";
}
}
unsigned long long
TimerManager::nextTimer()
{
boost::mutex::scoped_lock lock(m_mutex);
m_tickled = false;
if (m_timers.empty()) {
MORDOR_LOG_DEBUG(g_log) << this << " nextTimer(): ~0ull";
return ~0ull;
}
const Timer::ptr &next = *m_timers.begin();
unsigned long long nowUs = now();
unsigned long long result;
if (nowUs >= next->m_next)
result = 0;
else
result = next->m_next - nowUs;
MORDOR_LOG_DEBUG(g_log) << this << " nextTimer(): " << result;
return result;
}
bool
TimerManager::detectClockRollover(unsigned long long nowUs)
{
// If the time jumps backward, expire timers (rather than have them
// expire in the distant future or not at all).
// We check this way because now() will not roll from 0xffff... to zero
// since the underlying hardware counter doesn't count microseconds.
// Use a threshold value so we don't overreact to minor clock jitter.
bool rollover = false;
if (nowUs < m_previousTime && // check first in case the next line would underflow
nowUs < m_previousTime - g_clockRolloverThreshold->val())
{
MORDOR_LOG_ERROR(g_log) << this << " clock has rolled back from "
<< m_previousTime << " to " << nowUs << "; expiring all timers";
rollover = true;
}
m_previousTime = nowUs;
return rollover;
}
std::vector<boost::function<void ()> >
TimerManager::processTimers()
{
std::vector<Timer::ptr> expired;
std::vector<boost::function<void ()> > result;
unsigned long long nowUs = now();
{
boost::mutex::scoped_lock lock(m_mutex);
if (m_timers.empty())
return result;
bool rollover = detectClockRollover(nowUs);
if (!rollover && (*m_timers.begin())->m_next > nowUs)
return result;
Timer nowTimer(nowUs);
Timer::ptr nowTimerPtr(&nowTimer, &nop<Timer *>);
// Find all timers that are expired
std::set<Timer::ptr, Timer::Comparator>::iterator it =
rollover ? m_timers.end() : m_timers.lower_bound(nowTimerPtr);
while (it != m_timers.end() && (*it)->m_next == nowUs ) ++it;
// Copy to expired, remove from m_timers;
expired.insert(expired.begin(), m_timers.begin(), it);
m_timers.erase(m_timers.begin(), it);
result.reserve(expired.size());
// Look at expired timers and re-register recurring timers
// (while under the same lock)
for (std::vector<Timer::ptr>::iterator it2(expired.begin());
it2 != expired.end();
++it2) {
Timer::ptr &timer = *it2;
MORDOR_ASSERT(timer->m_dg);
result.push_back(timer->m_dg);
if (timer->m_recurring) {
MORDOR_LOG_TRACE(g_log) << timer << " expired and refreshed";
timer->m_next = nowUs + timer->m_us;
m_timers.insert(timer);
} else {
MORDOR_LOG_TRACE(g_log) << timer << " expired";
timer->m_dg = NULL;
}
}
}
return result;
}
void
TimerManager::executeTimers()
{
std::vector<boost::function<void ()> > expired = processTimers();
// Run the callbacks for each expired timer (not under a lock)
for (std::vector<boost::function<void ()> >::iterator it(expired.begin());
it != expired.end();
++it) {
(*it)();
}
}
void
TimerManager::setClock(boost::function<unsigned long long()> dg)
{
ms_clockDg = dg;
}
bool
Timer::Comparator::operator()(const Timer::ptr &lhs,
const Timer::ptr &rhs) const
{
// Order NULL before everything else
if (!lhs && !rhs)
return false;
if (!lhs)
return true;
if (!rhs)
return false;
// Order primarily on m_next
if (lhs->m_next < rhs->m_next)
return true;
if (rhs->m_next < lhs->m_next)
return false;
// Order by raw pointer for equivalent timeout values
return lhs.get() < rhs.get();
}
}
<|endoftext|>
|
<commit_before>/*****************************************************************************
* Media Library
*****************************************************************************
* Copyright (C) 2018-2019 Hugo Beauzée-Luyssen, Videolabs, VideoLAN, VideoLAN
*
* Authors: Hugo Beauzée-Luyssen <[email protected]>
*
* This program 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.
*
* 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include "CoreThumbnailer.h"
#include "compat/ConditionVariable.h"
#include "compat/Mutex.h"
#include "Media.h"
#include "MediaLibrary.h"
#include "utils/VLCInstance.h"
namespace medialibrary
{
CoreThumbnailer::CoreThumbnailer( MediaLibraryPtr ml )
: m_ml( ml )
{
}
bool CoreThumbnailer::generate( const std::string& mrl, uint32_t desiredWidth,
uint32_t desiredHeight, float position,
const std::string& dest )
{
compat::ConditionVariable cond;
auto done = false;
VLC::Picture thumbnail;
{
m_vlcMedia = VLC::Media{ VLCInstance::get(), mrl, VLC::Media::FromType::FromLocation };
auto em = m_vlcMedia.eventManager();
em.onThumbnailGenerated([this, &cond, &thumbnail, &done]( const VLC::Picture* p ) {
{
std::unique_lock<compat::Mutex> l{ m_mutex };
if( p != nullptr )
thumbnail = *p;
done = true;
}
cond.notify_all();
});
m_request = m_vlcMedia.thumbnailRequestByPos( position, VLC::Media::ThumbnailSeekSpeed::Fast,
desiredWidth, desiredHeight,
desiredWidth != 0 && desiredHeight != 0,
VLC::Picture::Type::Jpg, 3000 );
if ( m_request == nullptr )
{
m_vlcMedia = VLC::Media{};
return false;
}
std::unique_lock<compat::Mutex> l{ m_mutex };
cond.wait( l, [&done]() { return done == true; } );
m_request = nullptr;
m_vlcMedia = VLC::Media{};
}
if ( thumbnail.isValid() == false )
return false;
return thumbnail.save( dest );
}
void CoreThumbnailer::stop()
{
std::lock_guard<compat::Mutex> lock{ m_mutex };
if ( m_request != nullptr )
m_vlcMedia.thumbnailCancel( m_request );
}
}
<commit_msg>CoreThumbnailer: Initialize current request<commit_after>/*****************************************************************************
* Media Library
*****************************************************************************
* Copyright (C) 2018-2019 Hugo Beauzée-Luyssen, Videolabs, VideoLAN, VideoLAN
*
* Authors: Hugo Beauzée-Luyssen <[email protected]>
*
* This program 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.
*
* 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include "CoreThumbnailer.h"
#include "compat/ConditionVariable.h"
#include "compat/Mutex.h"
#include "Media.h"
#include "MediaLibrary.h"
#include "utils/VLCInstance.h"
namespace medialibrary
{
CoreThumbnailer::CoreThumbnailer( MediaLibraryPtr ml )
: m_ml( ml )
, m_request( nullptr )
{
}
bool CoreThumbnailer::generate( const std::string& mrl, uint32_t desiredWidth,
uint32_t desiredHeight, float position,
const std::string& dest )
{
compat::ConditionVariable cond;
auto done = false;
VLC::Picture thumbnail;
{
m_vlcMedia = VLC::Media{ VLCInstance::get(), mrl, VLC::Media::FromType::FromLocation };
auto em = m_vlcMedia.eventManager();
em.onThumbnailGenerated([this, &cond, &thumbnail, &done]( const VLC::Picture* p ) {
{
std::unique_lock<compat::Mutex> l{ m_mutex };
if( p != nullptr )
thumbnail = *p;
done = true;
}
cond.notify_all();
});
m_request = m_vlcMedia.thumbnailRequestByPos( position, VLC::Media::ThumbnailSeekSpeed::Fast,
desiredWidth, desiredHeight,
desiredWidth != 0 && desiredHeight != 0,
VLC::Picture::Type::Jpg, 3000 );
if ( m_request == nullptr )
{
m_vlcMedia = VLC::Media{};
return false;
}
std::unique_lock<compat::Mutex> l{ m_mutex };
cond.wait( l, [&done]() { return done == true; } );
m_request = nullptr;
m_vlcMedia = VLC::Media{};
}
if ( thumbnail.isValid() == false )
return false;
return thumbnail.save( dest );
}
void CoreThumbnailer::stop()
{
std::lock_guard<compat::Mutex> lock{ m_mutex };
if ( m_request != nullptr )
m_vlcMedia.thumbnailCancel( m_request );
}
}
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt 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 notices for more information.
=========================================================================*/
#include "otbDEMHandler.h"
#include "otbMacro.h"
#include "ossim/elevation/ossimElevManager.h"
#include "ossim/base/ossimGeoidManager.h"
#include "ossim/base/ossimFilename.h"
#include "ossim/base/ossimDirectory.h"
#include "ossim/base/ossimGeoidEgm96.h"
#include "ossim/base/ossimRefPtr.h"
namespace otb
{
/** Initialize the singleton */
DEMHandler::Pointer DEMHandler::m_Singleton = NULL;
DEMHandler::Pointer DEMHandler::Instance()
{
if(m_Singleton.GetPointer() == NULL)
{
m_Singleton = itk::ObjectFactory<Self>::Create();
if(m_Singleton.GetPointer() == NULL)
{
m_Singleton = new DEMHandler;
}
m_Singleton->UnRegister();
}
return m_Singleton;
}
DEMHandler * DEMHandler::New()
{
return Instance();
}
DEMHandler
::DEMHandler() :
m_ElevManager(ossimElevManager::instance()),
m_GeoidFile(""),
m_DefaultHeightAboveEllipsoid(0)
{
}
void
DEMHandler
::OpenDEMDirectory(const char* DEMDirectory)
{
ossimFilename ossimDEMDir;
ossimDEMDir = ossimFilename(DEMDirectory);
if (!m_ElevManager->loadElevationPath(ossimDEMDir))
{
itkExceptionMacro("Failed to open DEM Directory: " << ossimDEMDir);
}
}
void
DEMHandler
::OpenDEMDirectory(const std::string& DEMDirectory)
{
OpenDEMDirectory(DEMDirectory.c_str());
}
bool
DEMHandler
::IsValidDEMDirectory(const char* DEMDirectory)
{
return m_ElevManager->loadElevationPath(DEMDirectory);
}
void
DEMHandler
::OpenGeoidFile(const char* geoidFile)
{
if ((ossimGeoidManager::instance()->findGeoidByShortName("geoid1996")) == 0)
{
otbMsgDevMacro(<< "Opening geoid: " << geoidFile);
ossimFilename geoid(geoidFile);
ossimRefPtr<ossimGeoid> geoidPtr = new ossimGeoidEgm96(geoid);
if (geoidPtr->getErrorStatus() == ossimErrorCodes::OSSIM_OK)
{
// Ossim does not allow to retrieve the geoid file path
// We therefore must keep it on our side
m_GeoidFile = geoidFile;
otbMsgDevMacro(<< "Geoid successfully opened");
ossimGeoidManager::instance()->addGeoid(geoidPtr);
geoidPtr.release();
}
else
{
otbMsgDevMacro(<< "Failure opening geoid");
geoidPtr.release();
}
}
}
void
DEMHandler
::OpenGeoidFile(const std::string& geoidFile)
{
OpenGeoidFile(geoidFile.c_str());
}
double
DEMHandler
::GetHeightAboveMSL(double lon, double lat) const
{
double height;
ossimGpt ossimWorldPoint;
ossimWorldPoint.lon = lon;
ossimWorldPoint.lat = lat;
height = m_ElevManager->getHeightAboveMSL(ossimWorldPoint);
return height;
}
double
DEMHandler
::GetHeightAboveMSL(const PointType& geoPoint) const
{
return GetHeightAboveMSL(geoPoint[0], geoPoint[1]);
}
double
DEMHandler
::GetHeightAboveEllipsoid(double lon, double lat) const
{
double height;
ossimGpt ossimWorldPoint;
ossimWorldPoint.lon = lon;
ossimWorldPoint.lat = lat;
otbMsgDevMacro(<< "Geoid offset: " << ossimGeoidManager::instance()->offsetFromEllipsoid(ossimWorldPoint));
height = m_ElevManager->getHeightAboveEllipsoid(ossimWorldPoint);
return height;
}
double
DEMHandler
::GetHeightAboveEllipsoid(const PointType& geoPoint) const
{
return GetHeightAboveEllipsoid(geoPoint[0], geoPoint[1]);
}
void
DEMHandler
::SetDefaultHeightAboveEllipsoid(double h)
{
// Ossim does not allow to retrieve the default height above
// ellipsoid We therefore must keep it on our side
m_DefaultHeightAboveEllipsoid = h;
m_ElevManager->setDefaultHeightAboveEllipsoid(h);
}
double
DEMHandler
::GetDefaultHeightAboveEllipsoid() const
{
// Ossim does not allow to retrieve the default height above
// ellipsoid We therefore must keep it on our side
return m_DefaultHeightAboveEllipsoid;
}
std::string DEMHandler::GetDEMDirectory(unsigned int idx) const
{
std::string demDir = "";
if(m_ElevManager->getNumberOfElevationDatabases() > 0)
{
demDir = m_ElevManager->getElevationDatabase(idx)->getConnectionString().string();
}
return demDir;
}
std::string DEMHandler::GetGeoidFile() const
{
// Ossim does not allow to retrieve the geoid file path
// We therefore must keep it on our side
return m_GeoidFile;
}
void
DEMHandler
::PrintSelf(std::ostream& os, itk::Indent indent) const
{
Superclass::PrintSelf(os, indent);
os << indent << "DEMHandler" << std::endl;
}
} // namespace otb
<commit_msg>BUG: Default height above ellipsoid in ossim class is NaN<commit_after>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt 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 notices for more information.
=========================================================================*/
#include "otbDEMHandler.h"
#include "otbMacro.h"
#include "ossim/elevation/ossimElevManager.h"
#include "ossim/base/ossimGeoidManager.h"
#include "ossim/base/ossimFilename.h"
#include "ossim/base/ossimDirectory.h"
#include "ossim/base/ossimGeoidEgm96.h"
#include "ossim/base/ossimRefPtr.h"
namespace otb
{
/** Initialize the singleton */
DEMHandler::Pointer DEMHandler::m_Singleton = NULL;
DEMHandler::Pointer DEMHandler::Instance()
{
if(m_Singleton.GetPointer() == NULL)
{
m_Singleton = itk::ObjectFactory<Self>::Create();
if(m_Singleton.GetPointer() == NULL)
{
m_Singleton = new DEMHandler;
}
m_Singleton->UnRegister();
}
return m_Singleton;
}
DEMHandler * DEMHandler::New()
{
return Instance();
}
DEMHandler
::DEMHandler() :
m_ElevManager(ossimElevManager::instance()),
m_GeoidFile(""),
m_DefaultHeightAboveEllipsoid(0)
{
m_ElevManager->setDefaultHeightAboveEllipsoid(m_DefaultHeightAboveEllipsoid);
}
void
DEMHandler
::OpenDEMDirectory(const char* DEMDirectory)
{
ossimFilename ossimDEMDir;
ossimDEMDir = ossimFilename(DEMDirectory);
if (!m_ElevManager->loadElevationPath(ossimDEMDir))
{
itkExceptionMacro("Failed to open DEM Directory: " << ossimDEMDir);
}
}
void
DEMHandler
::OpenDEMDirectory(const std::string& DEMDirectory)
{
OpenDEMDirectory(DEMDirectory.c_str());
}
bool
DEMHandler
::IsValidDEMDirectory(const char* DEMDirectory)
{
return m_ElevManager->loadElevationPath(DEMDirectory);
}
void
DEMHandler
::OpenGeoidFile(const char* geoidFile)
{
if ((ossimGeoidManager::instance()->findGeoidByShortName("geoid1996")) == 0)
{
otbMsgDevMacro(<< "Opening geoid: " << geoidFile);
ossimFilename geoid(geoidFile);
ossimRefPtr<ossimGeoid> geoidPtr = new ossimGeoidEgm96(geoid);
if (geoidPtr->getErrorStatus() == ossimErrorCodes::OSSIM_OK)
{
// Ossim does not allow to retrieve the geoid file path
// We therefore must keep it on our side
m_GeoidFile = geoidFile;
otbMsgDevMacro(<< "Geoid successfully opened");
ossimGeoidManager::instance()->addGeoid(geoidPtr);
geoidPtr.release();
}
else
{
otbMsgDevMacro(<< "Failure opening geoid");
geoidPtr.release();
}
}
}
void
DEMHandler
::OpenGeoidFile(const std::string& geoidFile)
{
OpenGeoidFile(geoidFile.c_str());
}
double
DEMHandler
::GetHeightAboveMSL(double lon, double lat) const
{
double height;
ossimGpt ossimWorldPoint;
ossimWorldPoint.lon = lon;
ossimWorldPoint.lat = lat;
height = m_ElevManager->getHeightAboveMSL(ossimWorldPoint);
return height;
}
double
DEMHandler
::GetHeightAboveMSL(const PointType& geoPoint) const
{
return GetHeightAboveMSL(geoPoint[0], geoPoint[1]);
}
double
DEMHandler
::GetHeightAboveEllipsoid(double lon, double lat) const
{
double height;
ossimGpt ossimWorldPoint;
ossimWorldPoint.lon = lon;
ossimWorldPoint.lat = lat;
height = m_ElevManager->getHeightAboveEllipsoid(ossimWorldPoint);
return height;
}
double
DEMHandler
::GetHeightAboveEllipsoid(const PointType& geoPoint) const
{
return GetHeightAboveEllipsoid(geoPoint[0], geoPoint[1]);
}
void
DEMHandler
::SetDefaultHeightAboveEllipsoid(double h)
{
// Ossim does not allow to retrieve the default height above
// ellipsoid We therefore must keep it on our side
m_DefaultHeightAboveEllipsoid = h;
m_ElevManager->setDefaultHeightAboveEllipsoid(h);
}
double
DEMHandler
::GetDefaultHeightAboveEllipsoid() const
{
// Ossim does not allow to retrieve the default height above
// ellipsoid We therefore must keep it on our side
return m_DefaultHeightAboveEllipsoid;
}
std::string DEMHandler::GetDEMDirectory(unsigned int idx) const
{
std::string demDir = "";
if(m_ElevManager->getNumberOfElevationDatabases() > 0)
{
demDir = m_ElevManager->getElevationDatabase(idx)->getConnectionString().string();
}
return demDir;
}
std::string DEMHandler::GetGeoidFile() const
{
// Ossim does not allow to retrieve the geoid file path
// We therefore must keep it on our side
return m_GeoidFile;
}
void
DEMHandler
::PrintSelf(std::ostream& os, itk::Indent indent) const
{
Superclass::PrintSelf(os, indent);
os << indent << "DEMHandler" << std::endl;
}
} // namespace otb
<|endoftext|>
|
<commit_before>/** @file
@brief Implementation
@date 2016
@author
Sensics, Inc.
<http://sensics.com/osvr>
*/
// Copyright 2016 Sensics, Inc.
// Copyright 2019 Collabora, Ltd.
//
// 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.
// Internal Includes
#include "CatchEigen.h"
#include <osvr/Util/EigenQuatExponentialMap.h>
// Library/third-party includes
#ifdef HAVE_QUATLIB
#include "quat.h"
#endif // HAVE_QUATLIB
#include <catch2/catch.hpp>
// Standard includes
#include <array>
#ifndef HAVE_QUATLIB
#define Q_X 0
#define Q_Y 1
#define Q_Z 2
#define Q_W 3
#endif // !HAVE_QUATLIB
using osvr::util::quat_exp_map;
static const double SMALL = 0.1;
static const double SMALLER = 1.0e-5;
// Make an equality comparison for quaternions, for the sake of Catch2.
namespace Eigen {
static inline bool operator==(Quaterniond const &lhs, Quaterniond const &rhs) {
return lhs.coeffs() == rhs.coeffs();
}
} // namespace Eigen
using Eigen::AngleAxisd;
using Eigen::Quaterniond;
using Eigen::Vector3d;
/// @name Quatlib interaction utilities
/// @{
/// Container for q_type that's C++-safe to pass around and such. To pass to
/// quatlib functions, use the `.data()` member function.
using QuatArray = std::array<double, 4>;
/// Convert Eigen vector to a quatlib (pure: w = 0) quaternion, wrapped in an
/// std::array.
static inline QuatArray toQuatlib(Vector3d const &vec) {
QuatArray ret;
ret[Q_W] = 0;
ret[Q_X] = vec.x();
ret[Q_Y] = vec.y();
ret[Q_Z] = vec.z();
return ret;
}
/// Convert Eigen quat to a quatlib quaternion, wrapped in an std::array.
static inline QuatArray toQuatlib(Quaterniond const &q) {
QuatArray ret;
ret[Q_W] = q.w();
ret[Q_X] = q.x();
ret[Q_Y] = q.y();
ret[Q_Z] = q.z();
return ret;
}
/// Takes a quatlib quaternion wrapped in an array and converts it to an
/// Eigen::Quaterniond, no questions asked.
static inline Quaterniond quatFromQuatlib(QuatArray const &arr) {
return Quaterniond(arr[Q_W], arr[Q_X], arr[Q_Y], arr[Q_Z]);
}
/// Takes a quatlib quaternion wrapped in an array and converts it to an
/// Eigen::Vector3d, no questions asked - assumes it's a pure quaternion (w=0)
/// or that you just want the vector part.
static inline Vector3d vecFromQuatlib(QuatArray const &arr) {
return Vector3d(arr[Q_X], arr[Q_Y], arr[Q_Z]);
}
/// @}
/// Creates a quaternion from angle+axis or identity,
/// and stores it along with a human-readable description.
class QuatCreator {
public:
explicit QuatCreator(QuatArray &&arr, std::string &&input)
: m_coeffs(std::move(arr)), m_input(std::move(input)) {}
static QuatCreator Identity() {
return QuatCreator(toQuatlib(Eigen::Quaterniond::Identity()),
"Identity");
}
static QuatCreator AngleAxis(double angle, Eigen::Vector3d const &axis) {
return QuatCreator(
toQuatlib(Eigen::Quaterniond(Eigen::AngleAxisd(angle, axis))),
formatAngleAxis(angle, axis));
}
Eigen::Quaterniond get() const { return quatFromQuatlib(m_coeffs); }
std::string const &getDescription() const { return m_input; }
private:
QuatArray m_coeffs;
std::string m_input;
static std::string formatAngleAxis(double angle,
Eigen::Vector3d const &axis) {
std::ostringstream os;
os << "Angle " << angle << ", Axis " << axis.transpose();
return os.str();
}
};
static inline ::std::ostream &operator<<(::std::ostream &os,
QuatCreator const &q) {
os << q.getDescription();
return os;
}
using QuatVecPair = std::pair<QuatCreator, Eigen::Vector3d>;
static inline QuatVecPair makePairFromAngleAxis(double angle,
Eigen::Vector3d const &axis) {
return std::make_pair(QuatCreator::AngleAxis(angle, axis),
(angle * axis * 0.5).eval());
}
static inline ::std::ostream &operator<<(::std::ostream &os,
QuatVecPair const &q) {
os << q.first << " (quat-vec pair, vec " << q.second.transpose() << ")";
return os;
}
static const Vector3d Vec3dZero = Vector3d::Zero();
/* Tests that take a unit quat as input */
static const auto BasicQuats = {
QuatCreator::Identity(),
QuatCreator::AngleAxis(EIGEN_PI / 2, Vector3d::UnitX()),
QuatCreator::AngleAxis(EIGEN_PI / 2, Vector3d::UnitY()),
QuatCreator::AngleAxis(EIGEN_PI / 2, Vector3d::UnitZ()),
QuatCreator::AngleAxis(-EIGEN_PI / 2, Vector3d::UnitX()),
QuatCreator::AngleAxis(-EIGEN_PI / 2, Vector3d::UnitY()),
QuatCreator::AngleAxis(-EIGEN_PI / 2, Vector3d::UnitZ())};
static const auto SmallQuats = {
QuatCreator::AngleAxis(SMALL, Vector3d::UnitX()),
QuatCreator::AngleAxis(SMALL, Vector3d::UnitY()),
QuatCreator::AngleAxis(SMALL, Vector3d::UnitZ()),
QuatCreator::AngleAxis(SMALLER, Vector3d::UnitX()),
QuatCreator::AngleAxis(SMALLER, Vector3d::UnitY()),
QuatCreator::AngleAxis(SMALLER, Vector3d::UnitZ())};
static const auto SmallNegativeQuats = {
QuatCreator::AngleAxis(-SMALL, Vector3d::UnitX()),
QuatCreator::AngleAxis(-SMALL, Vector3d::UnitY()),
QuatCreator::AngleAxis(-SMALL, Vector3d::UnitZ()),
QuatCreator::AngleAxis(-SMALLER, Vector3d::UnitX()),
QuatCreator::AngleAxis(-SMALLER, Vector3d::UnitY()),
QuatCreator::AngleAxis(-SMALLER, Vector3d::UnitZ())};
#if 0
QuatCreator::AngleAxis(EIGEN_PI, Vector3d::UnitX()),
QuatCreator::AngleAxis(EIGEN_PI, Vector3d::UnitY()),
QuatCreator::AngleAxis(EIGEN_PI, Vector3d::UnitZ()),
QuatCreator::AngleAxis(3 * EIGEN_PI / 2, Vector3d::UnitX()),
QuatCreator::AngleAxis(3 * EIGEN_PI / 2, Vector3d::UnitY()),
QuatCreator::AngleAxis(3 * EIGEN_PI / 2, Vector3d::UnitZ()),
#endif
TEST_CASE("UnitQuatInput") {
const auto doTests = [](QuatCreator const &qCreator) {
CAPTURE(qCreator);
Quaterniond q = qCreator.get();
CAPTURE(q);
SECTION("Basic run ln") {
REQUIRE_NOTHROW(quat_exp_map(q).ln());
const Vector3d ln_q = quat_exp_map(q).ln();
const bool isIdentityQuat = q.vec().norm() == 0;
CAPTURE(isIdentityQuat);
if (isIdentityQuat) {
REQUIRE(ln_q == Vec3dZero);
} else {
REQUIRE_FALSE(ln_q == Vec3dZero);
}
SECTION("Round trip") {
const Quaterniond exp_ln_q = quat_exp_map(ln_q).exp();
REQUIRE(q == exp_ln_q);
}
}
#ifdef HAVE_QUATLIB
SECTION("Quatlib roundtrip (exp(ln(q))) as ground truth") {
QuatArray quatlib_q = toQuatlib(q);
q_log(quatlib_q.data(), quatlib_q.data());
q_exp(quatlib_q.data(), quatlib_q.data());
REQUIRE(ApproxVec(q.coeffs()) ==
quatFromQuatlib(quatlib_q).coeffs());
}
#endif // HAVE_QUATLIB
};
SECTION("Basic quats") {
auto quatCreator = GENERATE(values(BasicQuats));
doTests(quatCreator);
}
SECTION("Small quats") {
auto quatCreator = GENERATE(values(SmallQuats));
doTests(quatCreator);
}
SECTION("Small negative quats") {
auto quatCreator = GENERATE(values(SmallNegativeQuats));
doTests(quatCreator);
}
}
/* Tests that take a rotation vector as input */
static const std::initializer_list<Vector3d> BasicVecs = {
Vector3d::Zero(),
Vector3d(EIGEN_PI / 2, 0, 0),
Vector3d(0, EIGEN_PI / 2, 0),
Vector3d(0, 0, EIGEN_PI / 2),
Vector3d(-EIGEN_PI / 2, 0, 0),
Vector3d(0, -EIGEN_PI / 2, 0),
Vector3d(0, 0, -EIGEN_PI / 2)};
static const std::initializer_list<Vector3d> SmallVecs = {
Vector3d(SMALL, 0, 0), Vector3d(0, SMALL, 0), Vector3d(0, 0, SMALL),
Vector3d(SMALLER, 0, 0), Vector3d(0, SMALLER, 0), Vector3d(0, 0, SMALLER)};
static const std::initializer_list<Vector3d> SmallNegativeVecs = {
Vector3d(-SMALL, 0, 0), Vector3d(0, -SMALL, 0),
Vector3d(0, 0, -SMALL), Vector3d(-SMALLER, 0, 0),
Vector3d(0, -SMALLER, 0), Vector3d(0, 0, -SMALLER)};
TEST_CASE("ExpMapVecInput") {
const auto doTests = [](Vector3d const &v) {
CAPTURE(v);
SECTION("BasicRunExp") {
REQUIRE_NOTHROW(quat_exp_map(v).exp());
const Quaterniond exp_v = quat_exp_map(v).exp();
const bool isNullRotation = (v == Vector3d::Zero());
CAPTURE(isNullRotation);
if (isNullRotation) {
REQUIRE(exp_v == Quaterniond::Identity());
} else {
REQUIRE_FALSE(exp_v == Quaterniond::Identity());
}
SECTION("Round-trip") {
Vector3d ln_exp_v = quat_exp_map(exp_v).ln();
REQUIRE(ln_exp_v == ApproxVec(v));
}
}
#ifdef HAVE_QUATLIB
SECTION("Quatlib roundtrip (ln(exp(v))) as ground truth") {
QuatArray quatlib_q = toQuatlib(v);
q_exp(quatlib_q.data(), quatlib_q.data());
q_log(quatlib_q.data(), quatlib_q.data());
REQUIRE(ApproxVec(v) == vecFromQuatlib(quatlib_q));
}
#endif // HAVE_QUATLIB
};
SECTION("BasicVecs") {
Vector3d v = GENERATE(values(BasicVecs));
doTests(v);
}
SECTION("SmallVecs") {
Vector3d v = GENERATE(values(SmallVecs));
doTests(v);
}
SECTION("SmallNegativeVecs") {
Vector3d v = GENERATE(values(SmallNegativeVecs));
doTests(v);
}
}
TEST_CASE("SimpleEquivalencies-Ln") {
REQUIRE(Vec3dZero == Vector3d(quat_exp_map(Quaterniond::Identity()).ln()));
}
TEST_CASE("SimpleEquivalencies-Exp") {
REQUIRE(Quaterniond::Identity() ==
Quaterniond(quat_exp_map(Vec3dZero).exp()));
}
/* Tests that take a pair of equivalent quaternion and vector as input */
static const auto HalfPiMultiples = {
makePairFromAngleAxis(EIGEN_PI / 2, Vector3d::UnitX()),
makePairFromAngleAxis(EIGEN_PI / 2, Vector3d::UnitY()),
makePairFromAngleAxis(EIGEN_PI / 2, Vector3d::UnitZ()),
makePairFromAngleAxis(-EIGEN_PI / 2, Vector3d::UnitX()),
makePairFromAngleAxis(-EIGEN_PI / 2, Vector3d::UnitY()),
makePairFromAngleAxis(-EIGEN_PI / 2, Vector3d::UnitZ())};
static const auto SmallEquivalentValues = {
makePairFromAngleAxis(SMALL, Vector3d::UnitX()),
makePairFromAngleAxis(SMALL, Vector3d::UnitY()),
makePairFromAngleAxis(SMALL, Vector3d::UnitZ()),
makePairFromAngleAxis(SMALLER, Vector3d::UnitX()),
makePairFromAngleAxis(SMALLER, Vector3d::UnitY()),
makePairFromAngleAxis(SMALLER, Vector3d::UnitZ())};
static const auto SmallNegativeEquivalentValues = {
makePairFromAngleAxis(-SMALL, Vector3d::UnitX()),
makePairFromAngleAxis(-SMALL, Vector3d::UnitY()),
makePairFromAngleAxis(-SMALL, Vector3d::UnitZ()),
makePairFromAngleAxis(-SMALLER, Vector3d::UnitX()),
makePairFromAngleAxis(-SMALLER, Vector3d::UnitY()),
makePairFromAngleAxis(-SMALLER, Vector3d::UnitZ())};
TEST_CASE("EquivalentInput") {
const auto doTests = [](QuatCreator const &qCreator, Vector3d const &v) {
CAPTURE(v);
CAPTURE(qCreator);
Quaterniond q = qCreator.get();
CAPTURE(q);
Vector3d ln_q = quat_exp_map(q).ln();
Quaterniond exp_v = quat_exp_map(v).exp();
SECTION("Ln") { REQUIRE(ln_q == ApproxVec(v)); }
SECTION("Exp") { REQUIRE(exp_v == ApproxQuat(q)); }
#ifdef HAVE_QUATLIB
SECTION("Compare ln with quatlib") {
QuatArray quatlib_q = toQuatlib(q);
q_log(quatlib_q.data(), quatlib_q.data());
REQUIRE(vecFromQuatlib(quatlib_q) == ln_q);
}
SECTION("Compare exp with quatlib") {
QuatArray quatlib_q = toQuatlib(v);
q_exp(quatlib_q.data(), quatlib_q.data());
q_normalize(quatlib_q.data(), quatlib_q.data());
REQUIRE(quatFromQuatlib(quatlib_q) == exp_v);
}
#endif // HAVE_QUATLIB
};
SECTION("HalfPiMultiples") {
QuatVecPair qvp = GENERATE(values(HalfPiMultiples));
doTests(qvp.first, qvp.second);
}
SECTION("SmallEquivalentValues") {
QuatVecPair qvp = GENERATE(values(SmallEquivalentValues));
doTests(qvp.first, qvp.second);
}
SECTION("SmallNegativeVecs") {
QuatVecPair qvp = GENERATE(values(SmallNegativeEquivalentValues));
doTests(qvp.first, qvp.second);
}
}
<commit_msg>QuatExpMap test: Move the test data into the functions.<commit_after>/** @file
@brief Implementation
@date 2016
@author
Sensics, Inc.
<http://sensics.com/osvr>
*/
// Copyright 2016 Sensics, Inc.
// Copyright 2019 Collabora, Ltd.
//
// 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.
// Internal Includes
#include "CatchEigen.h"
#include <osvr/Util/EigenQuatExponentialMap.h>
// Library/third-party includes
#ifdef HAVE_QUATLIB
#include "quat.h"
#endif // HAVE_QUATLIB
#include <catch2/catch.hpp>
// Standard includes
#include <array>
#ifndef HAVE_QUATLIB
#define Q_X 0
#define Q_Y 1
#define Q_Z 2
#define Q_W 3
#endif // !HAVE_QUATLIB
using osvr::util::quat_exp_map;
static const double SMALL = 0.1;
static const double SMALLER = 1.0e-5;
// Make an equality comparison for quaternions, for the sake of Catch2.
namespace Eigen {
static inline bool operator==(Quaterniond const &lhs, Quaterniond const &rhs) {
return lhs.coeffs() == rhs.coeffs();
}
} // namespace Eigen
using Eigen::AngleAxisd;
using Eigen::Quaterniond;
using Eigen::Vector3d;
/// @name Quatlib interaction utilities
/// @{
/// Container for q_type that's C++-safe to pass around and such. To pass to
/// quatlib functions, use the `.data()` member function.
using QuatArray = std::array<double, 4>;
/// Convert Eigen vector to a quatlib (pure: w = 0) quaternion, wrapped in an
/// std::array.
static inline QuatArray toQuatlib(Vector3d const &vec) {
QuatArray ret;
ret[Q_W] = 0;
ret[Q_X] = vec.x();
ret[Q_Y] = vec.y();
ret[Q_Z] = vec.z();
return ret;
}
/// Convert Eigen quat to a quatlib quaternion, wrapped in an std::array.
static inline QuatArray toQuatlib(Quaterniond const &q) {
QuatArray ret;
ret[Q_W] = q.w();
ret[Q_X] = q.x();
ret[Q_Y] = q.y();
ret[Q_Z] = q.z();
return ret;
}
/// Takes a quatlib quaternion wrapped in an array and converts it to an
/// Eigen::Quaterniond, no questions asked.
static inline Quaterniond quatFromQuatlib(QuatArray const &arr) {
return Quaterniond(arr[Q_W], arr[Q_X], arr[Q_Y], arr[Q_Z]);
}
/// Takes a quatlib quaternion wrapped in an array and converts it to an
/// Eigen::Vector3d, no questions asked - assumes it's a pure quaternion (w=0)
/// or that you just want the vector part.
static inline Vector3d vecFromQuatlib(QuatArray const &arr) {
return Vector3d(arr[Q_X], arr[Q_Y], arr[Q_Z]);
}
/// @}
/// Creates a quaternion from angle+axis or identity,
/// and stores it along with a human-readable description.
class QuatCreator {
public:
explicit QuatCreator(QuatArray &&arr, std::string &&input)
: m_coeffs(std::move(arr)), m_input(std::move(input)) {}
static QuatCreator Identity() {
return QuatCreator(toQuatlib(Eigen::Quaterniond::Identity()),
"Identity");
}
static QuatCreator AngleAxis(double angle, Eigen::Vector3d const &axis) {
return QuatCreator(
toQuatlib(Eigen::Quaterniond(Eigen::AngleAxisd(angle, axis))),
formatAngleAxis(angle, axis));
}
Eigen::Quaterniond get() const { return quatFromQuatlib(m_coeffs); }
std::string const &getDescription() const { return m_input; }
private:
QuatArray m_coeffs;
std::string m_input;
static std::string formatAngleAxis(double angle,
Eigen::Vector3d const &axis) {
std::ostringstream os;
os << "Angle " << angle << ", Axis " << axis.transpose();
return os.str();
}
};
static inline ::std::ostream &operator<<(::std::ostream &os,
QuatCreator const &q) {
os << q.getDescription();
return os;
}
using QuatVecPair = std::pair<QuatCreator, Eigen::Vector3d>;
static inline QuatVecPair makePairFromAngleAxis(double angle,
Eigen::Vector3d const &axis) {
return std::make_pair(QuatCreator::AngleAxis(angle, axis),
(angle * axis * 0.5).eval());
}
static inline ::std::ostream &operator<<(::std::ostream &os,
QuatVecPair const &q) {
os << q.first << " (quat-vec pair, vec " << q.second.transpose() << ")";
return os;
}
static const Vector3d Vec3dZero = Vector3d::Zero();
/* Tests that take a unit quat as input */
TEST_CASE("UnitQuatInput") {
const auto doTests = [](QuatCreator const &qCreator) {
CAPTURE(qCreator);
Quaterniond q = qCreator.get();
CAPTURE(q);
SECTION("Basic run ln") {
REQUIRE_NOTHROW(quat_exp_map(q).ln());
const Vector3d ln_q = quat_exp_map(q).ln();
const bool isIdentityQuat = q.vec().norm() == 0;
CAPTURE(isIdentityQuat);
if (isIdentityQuat) {
REQUIRE(ln_q == Vec3dZero);
} else {
REQUIRE_FALSE(ln_q == Vec3dZero);
}
SECTION("Round trip") {
const Quaterniond exp_ln_q = quat_exp_map(ln_q).exp();
REQUIRE(q == exp_ln_q);
}
}
#ifdef HAVE_QUATLIB
SECTION("Quatlib roundtrip (exp(ln(q))) as ground truth") {
QuatArray quatlib_q = toQuatlib(q);
q_log(quatlib_q.data(), quatlib_q.data());
q_exp(quatlib_q.data(), quatlib_q.data());
REQUIRE(ApproxVec(q.coeffs()) ==
quatFromQuatlib(quatlib_q).coeffs());
}
#endif // HAVE_QUATLIB
};
SECTION("Basic quats") {
auto quatCreator = GENERATE(
values({QuatCreator::Identity(),
QuatCreator::AngleAxis(EIGEN_PI / 2, Vector3d::UnitX()),
QuatCreator::AngleAxis(EIGEN_PI / 2, Vector3d::UnitY()),
QuatCreator::AngleAxis(EIGEN_PI / 2, Vector3d::UnitZ()),
QuatCreator::AngleAxis(-EIGEN_PI / 2, Vector3d::UnitX()),
QuatCreator::AngleAxis(-EIGEN_PI / 2, Vector3d::UnitY()),
QuatCreator::AngleAxis(-EIGEN_PI / 2, Vector3d::UnitZ())}));
doTests(quatCreator);
}
SECTION("Small quats") {
auto quatCreator = GENERATE(
values({QuatCreator::AngleAxis(SMALL, Vector3d::UnitX()),
QuatCreator::AngleAxis(SMALL, Vector3d::UnitY()),
QuatCreator::AngleAxis(SMALL, Vector3d::UnitZ()),
QuatCreator::AngleAxis(SMALLER, Vector3d::UnitX()),
QuatCreator::AngleAxis(SMALLER, Vector3d::UnitY()),
QuatCreator::AngleAxis(SMALLER, Vector3d::UnitZ())}));
doTests(quatCreator);
}
SECTION("Small negative quats") {
auto quatCreator = GENERATE(
values({QuatCreator::AngleAxis(-SMALL, Vector3d::UnitX()),
QuatCreator::AngleAxis(-SMALL, Vector3d::UnitY()),
QuatCreator::AngleAxis(-SMALL, Vector3d::UnitZ()),
QuatCreator::AngleAxis(-SMALLER, Vector3d::UnitX()),
QuatCreator::AngleAxis(-SMALLER, Vector3d::UnitY()),
QuatCreator::AngleAxis(-SMALLER, Vector3d::UnitZ())}));
doTests(quatCreator);
}
#if 0
QuatCreator::AngleAxis(EIGEN_PI, Vector3d::UnitX()),
QuatCreator::AngleAxis(EIGEN_PI, Vector3d::UnitY()),
QuatCreator::AngleAxis(EIGEN_PI, Vector3d::UnitZ()),
QuatCreator::AngleAxis(3 * EIGEN_PI / 2, Vector3d::UnitX()),
QuatCreator::AngleAxis(3 * EIGEN_PI / 2, Vector3d::UnitY()),
QuatCreator::AngleAxis(3 * EIGEN_PI / 2, Vector3d::UnitZ()),
#endif
}
/* Tests that take a rotation vector as input */
TEST_CASE("ExpMapVecInput") {
const auto doTests = [](Vector3d const &v) {
CAPTURE(v);
SECTION("BasicRunExp") {
REQUIRE_NOTHROW(quat_exp_map(v).exp());
const Quaterniond exp_v = quat_exp_map(v).exp();
const bool isNullRotation = (v == Vector3d::Zero());
CAPTURE(isNullRotation);
if (isNullRotation) {
REQUIRE(exp_v == Quaterniond::Identity());
} else {
REQUIRE_FALSE(exp_v == Quaterniond::Identity());
}
SECTION("Round-trip") {
Vector3d ln_exp_v = quat_exp_map(exp_v).ln();
REQUIRE(ln_exp_v == ApproxVec(v));
}
}
#ifdef HAVE_QUATLIB
SECTION("Quatlib roundtrip (ln(exp(v))) as ground truth") {
QuatArray quatlib_q = toQuatlib(v);
q_exp(quatlib_q.data(), quatlib_q.data());
q_log(quatlib_q.data(), quatlib_q.data());
REQUIRE(ApproxVec(v) == vecFromQuatlib(quatlib_q));
}
#endif // HAVE_QUATLIB
};
SECTION("BasicVecs") {
Vector3d v = GENERATE(values(
{Vector3d(Vector3d::Zero()), Vector3d(EIGEN_PI / 2, 0, 0),
Vector3d(0, EIGEN_PI / 2, 0), Vector3d(0, 0, EIGEN_PI / 2),
Vector3d(-EIGEN_PI / 2, 0, 0), Vector3d(0, -EIGEN_PI / 2, 0),
Vector3d(0, 0, -EIGEN_PI / 2)}));
doTests(v);
}
SECTION("SmallVecs") {
Vector3d v = GENERATE(
values({Vector3d(SMALL, 0, 0), Vector3d(0, SMALL, 0),
Vector3d(0, 0, SMALL), Vector3d(SMALLER, 0, 0),
Vector3d(0, SMALLER, 0), Vector3d(0, 0, SMALLER)}));
doTests(v);
}
SECTION("SmallNegativeVecs") {
Vector3d v = GENERATE(
values({Vector3d(-SMALL, 0, 0), Vector3d(0, -SMALL, 0),
Vector3d(0, 0, -SMALL), Vector3d(-SMALLER, 0, 0),
Vector3d(0, -SMALLER, 0), Vector3d(0, 0, -SMALLER)}));
doTests(v);
}
}
TEST_CASE("SimpleEquivalencies-Ln") {
REQUIRE(Vec3dZero == Vector3d(quat_exp_map(Quaterniond::Identity()).ln()));
}
TEST_CASE("SimpleEquivalencies-Exp") {
REQUIRE(Quaterniond::Identity() ==
Quaterniond(quat_exp_map(Vec3dZero).exp()));
}
/* Tests that take a pair of equivalent quaternion and vector as input */
TEST_CASE("EquivalentInput") {
const auto doTests = [](QuatCreator const &qCreator, Vector3d const &v) {
CAPTURE(v);
CAPTURE(qCreator);
Quaterniond q = qCreator.get();
CAPTURE(q);
Vector3d ln_q = quat_exp_map(q).ln();
Quaterniond exp_v = quat_exp_map(v).exp();
SECTION("Ln") { REQUIRE(ln_q == ApproxVec(v)); }
SECTION("Exp") { REQUIRE(exp_v == ApproxQuat(q)); }
#ifdef HAVE_QUATLIB
SECTION("Compare ln with quatlib") {
QuatArray quatlib_q = toQuatlib(q);
q_log(quatlib_q.data(), quatlib_q.data());
REQUIRE(vecFromQuatlib(quatlib_q) == ln_q);
}
SECTION("Compare exp with quatlib") {
QuatArray quatlib_q = toQuatlib(v);
q_exp(quatlib_q.data(), quatlib_q.data());
q_normalize(quatlib_q.data(), quatlib_q.data());
REQUIRE(quatFromQuatlib(quatlib_q) == exp_v);
}
#endif // HAVE_QUATLIB
};
SECTION("HalfPiMultiples") {
QuatVecPair qvp = GENERATE(
values({makePairFromAngleAxis(EIGEN_PI / 2, Vector3d::UnitX()),
makePairFromAngleAxis(EIGEN_PI / 2, Vector3d::UnitY()),
makePairFromAngleAxis(EIGEN_PI / 2, Vector3d::UnitZ()),
makePairFromAngleAxis(-EIGEN_PI / 2, Vector3d::UnitX()),
makePairFromAngleAxis(-EIGEN_PI / 2, Vector3d::UnitY()),
makePairFromAngleAxis(-EIGEN_PI / 2, Vector3d::UnitZ())}));
doTests(qvp.first, qvp.second);
}
SECTION("SmallEquivalentValues") {
QuatVecPair qvp = GENERATE(
values({makePairFromAngleAxis(SMALL, Vector3d::UnitX()),
makePairFromAngleAxis(SMALL, Vector3d::UnitY()),
makePairFromAngleAxis(SMALL, Vector3d::UnitZ()),
makePairFromAngleAxis(SMALLER, Vector3d::UnitX()),
makePairFromAngleAxis(SMALLER, Vector3d::UnitY()),
makePairFromAngleAxis(SMALLER, Vector3d::UnitZ())}));
doTests(qvp.first, qvp.second);
}
SECTION("SmallNegativeVecs") {
QuatVecPair qvp = GENERATE(
values({makePairFromAngleAxis(-SMALL, Vector3d::UnitX()),
makePairFromAngleAxis(-SMALL, Vector3d::UnitY()),
makePairFromAngleAxis(-SMALL, Vector3d::UnitZ()),
makePairFromAngleAxis(-SMALLER, Vector3d::UnitX()),
makePairFromAngleAxis(-SMALLER, Vector3d::UnitY()),
makePairFromAngleAxis(-SMALLER, Vector3d::UnitZ())}));
doTests(qvp.first, qvp.second);
}
}
<|endoftext|>
|
<commit_before>#include "processes_page.h"
#include "ui_processes_page.h"
#include "utilities.h"
ProcessesPage::~ProcessesPage()
{
delete ui;
}
ProcessesPage::ProcessesPage(QWidget *parent) :
QWidget(parent),
ui(new Ui::ProcessesPage),
mItemModel(new QStandardItemModel(this)),
mSortFilterModel(new QSortFilterProxyModel(this)),
im(InfoManager::ins()),
mTimer(new QTimer(this))
{
ui->setupUi(this);
init();
}
void ProcessesPage::init()
{
mHeaders = QStringList {
"PID", tr("Resident Memory"), tr("%Memory"), tr("Virtual Memory"),
tr("User"), "%CPU", tr("Start Time"), tr("State"), tr("Group"),
tr("Nice"), tr("CPU Time"), tr("Session"), tr("Process")
};
// slider settings
ui->sliderRefresh->setRange(1, 10);
ui->sliderRefresh->setPageStep(1);
ui->sliderRefresh->setSingleStep(1);
// Table settings
mSortFilterModel->setSourceModel(mItemModel);
mItemModel->setHorizontalHeaderLabels(mHeaders);
ui->tableProcess->setModel(mSortFilterModel);
mSortFilterModel->setSortRole(1);
mSortFilterModel->setDynamicSortFilter(true);
mSortFilterModel->sort(5, Qt::SortOrder::DescendingOrder);
ui->tableProcess->horizontalHeader()->setSectionsMovable(true);
ui->tableProcess->horizontalHeader()->setFixedHeight(36);
ui->tableProcess->horizontalHeader()->setDefaultAlignment(Qt::AlignLeft | Qt::AlignVCenter);
ui->tableProcess->horizontalHeader()->setCursor(Qt::PointingHandCursor);
ui->tableProcess->horizontalHeader()->resizeSection(0, 70);
loadProcesses();
connect(mTimer, &QTimer::timeout, this, &ProcessesPage::loadProcesses);
mTimer->setInterval(1000);
mTimer->start();
ui->tableProcess->horizontalHeader()->setContextMenuPolicy(Qt::CustomContextMenu);
connect(ui->tableProcess->horizontalHeader(), SIGNAL(customContextMenuRequested(const QPoint&)),
this, SLOT(on_tableProcess_customContextMenuRequested(const QPoint&)));
loadHeaderMenu();
Utilities::addDropShadow(ui->btnEndProcess, 60);
Utilities::addDropShadow(ui->tableProcess, 55);
}
void ProcessesPage::loadHeaderMenu()
{
int i = 0;
for (const QString &header : mHeaders) {
QAction *action = new QAction(header);
action->setCheckable(true);
action->setChecked(true);
action->setData(i++);
mHeaderMenu.addAction(action);
}
// exclude headers
#define ex(n) mHeaders.indexOf(n)
QList<int> hiddenHeaders = { ex("Start Time"), ex("State"), ex("Group"),
ex("Nice"), ex("CPU Time"), ex("Session"), ex("Virtual Memory") };
#undef ex
QList<QAction*> actions = mHeaderMenu.actions();
for (const int i : hiddenHeaders) {
ui->tableProcess->horizontalHeader()->setSectionHidden(i, true);
actions.at(i)->setChecked(false);
}
}
void ProcessesPage::loadProcesses()
{
QModelIndexList selecteds = ui->tableProcess->selectionModel()->selectedRows();
mItemModel->removeRows(0, mItemModel->rowCount());
im->updateProcesses();
QList<Process> processes = im->getProcesses();
QString username = im->getUserName();
if (ui->checkAllProcesses->isChecked()) {
for (const Process &proc : processes) {
mItemModel->appendRow(createRow(proc));
}
} else {
for (const Process &proc : processes) {
if (username == proc.getUname()) {
mItemModel->appendRow(createRow(proc));
}
}
}
ui->lblProcessTitle->setText(tr("Processes (%1)").arg(mItemModel->rowCount()));
// selected item
if(! selecteds.isEmpty()) {
mSeletedRowModel = selecteds.first();
for (int i = 0; i < mSortFilterModel->rowCount(); ++i) {
if (mSortFilterModel->index(i, 0).data(1).toInt() == mSeletedRowModel.data(1).toInt()) {
ui->tableProcess->selectRow(i);
}
}
} else {
mSeletedRowModel = QModelIndex();
}
}
QList<QStandardItem*> ProcessesPage::createRow(const Process &proc)
{
QList<QStandardItem*> row;
int data = 1;
QStandardItem *pid_i = new QStandardItem(QString::number(proc.getPid()));
pid_i->setData(proc.getPid(), data);
pid_i->setData(proc.getPid(), Qt::ToolTipRole);
QStandardItem *rss_i = new QStandardItem(FormatUtil::formatBytes(proc.getRss()));
rss_i->setData(proc.getRss(), data);
rss_i->setData(FormatUtil::formatBytes(proc.getRss()), Qt::ToolTipRole);
QStandardItem *pmem_i = new QStandardItem(QString::number(proc.getPmem()));
pmem_i->setData(proc.getPmem(), data);
pmem_i->setData(proc.getPmem(), Qt::ToolTipRole);
QStandardItem *vsize_i = new QStandardItem(FormatUtil::formatBytes(proc.getVsize()));
vsize_i->setData(proc.getVsize(), data);
vsize_i->setData(FormatUtil::formatBytes(proc.getVsize()), Qt::ToolTipRole);
QStandardItem *uname_i = new QStandardItem(proc.getUname());
uname_i->setData(proc.getUname(), data);
uname_i->setData(proc.getUname(), Qt::ToolTipRole);
QStandardItem *pcpu_i = new QStandardItem(QString::number(proc.getPcpu()));
pcpu_i->setData(proc.getPcpu(), data);
pcpu_i->setData(proc.getPcpu(), Qt::ToolTipRole);
QStandardItem *starttime_i = new QStandardItem(proc.getStartTime());
starttime_i->setData(proc.getStartTime(), data);
starttime_i->setData(proc.getStartTime(), Qt::ToolTipRole);
QStandardItem *state_i = new QStandardItem(proc.getState());
state_i->setData(proc.getState(), data);
state_i->setData(proc.getState(), Qt::ToolTipRole);
QStandardItem *group_i = new QStandardItem(proc.getGroup());
group_i->setData(proc.getGroup(), data);
group_i->setData(proc.getGroup(), Qt::ToolTipRole);
QStandardItem *nice_i = new QStandardItem(QString::number(proc.getNice()));
nice_i->setData(proc.getNice(), data);
nice_i->setData(proc.getNice(), Qt::ToolTipRole);
QStandardItem *cpuTime_i = new QStandardItem(proc.getCpuTime());
cpuTime_i->setData(proc.getCpuTime(), data);
cpuTime_i->setData(proc.getCpuTime(), Qt::ToolTipRole);
QStandardItem *session_i = new QStandardItem(proc.getSession());
session_i->setData(proc.getSession(), data);
session_i->setData(proc.getSession(), Qt::ToolTipRole);
QStandardItem *cmd_i = new QStandardItem(proc.getCmd());
cmd_i->setData(proc.getCmd(), data);
cmd_i->setData(QString("<p>%1</p>").arg(proc.getCmd()), Qt::ToolTipRole);
row << pid_i << rss_i << pmem_i << vsize_i << uname_i << pcpu_i
<< starttime_i << state_i << group_i << nice_i << cpuTime_i
<< session_i << cmd_i;
return row;
}
void ProcessesPage::on_txtProcessSearch_textChanged(const QString &val)
{
QRegExp query(val, Qt::CaseInsensitive, QRegExp::Wildcard);
mSortFilterModel->setFilterKeyColumn(mHeaders.count() - 1); // process name
mSortFilterModel->setFilterRegExp(query);
}
void ProcessesPage::on_sliderRefresh_valueChanged(const int &i)
{
ui->lblRefresh->setText(tr("Refresh (%1)").arg(i));
mTimer->setInterval(i * 1000);
}
void ProcessesPage::on_btnEndProcess_clicked()
{
pid_t pid = mSeletedRowModel.data(1).toInt();
if (pid) {
QString selectedUname = mSortFilterModel->index(mSeletedRowModel.row(), 4).data(1).toString();
try {
if (selectedUname == im->getUserName()) {
CommandUtil::exec("kill", { QString::number(pid) });
} else {
CommandUtil::sudoExec("kill", { QString::number(pid) });
}
} catch (QString &ex) {
qCritical() << ex;
}
}
}
void ProcessesPage::on_tableProcess_customContextMenuRequested(const QPoint &pos)
{
QPoint globalPos = ui->tableProcess->mapToGlobal(pos);
QAction *action = mHeaderMenu.exec(globalPos);
if (action) {
ui->tableProcess->horizontalHeader()->setSectionHidden(action->data().toInt(), ! action->isChecked());
}
}
<commit_msg>exclude headers update<commit_after>#include "processes_page.h"
#include "ui_processes_page.h"
#include "utilities.h"
ProcessesPage::~ProcessesPage()
{
delete ui;
}
ProcessesPage::ProcessesPage(QWidget *parent) :
QWidget(parent),
ui(new Ui::ProcessesPage),
mItemModel(new QStandardItemModel(this)),
mSortFilterModel(new QSortFilterProxyModel(this)),
im(InfoManager::ins()),
mTimer(new QTimer(this))
{
ui->setupUi(this);
init();
}
void ProcessesPage::init()
{
mHeaders = QStringList {
"PID", tr("Resident Memory"), tr("%Memory"), tr("Virtual Memory"),
tr("User"), "%CPU", tr("Start Time"), tr("State"), tr("Group"),
tr("Nice"), tr("CPU Time"), tr("Session"), tr("Process")
};
// slider settings
ui->sliderRefresh->setRange(1, 10);
ui->sliderRefresh->setPageStep(1);
ui->sliderRefresh->setSingleStep(1);
// Table settings
mSortFilterModel->setSourceModel(mItemModel);
mItemModel->setHorizontalHeaderLabels(mHeaders);
ui->tableProcess->setModel(mSortFilterModel);
mSortFilterModel->setSortRole(1);
mSortFilterModel->setDynamicSortFilter(true);
mSortFilterModel->sort(5, Qt::SortOrder::DescendingOrder);
ui->tableProcess->horizontalHeader()->setSectionsMovable(true);
ui->tableProcess->horizontalHeader()->setFixedHeight(36);
ui->tableProcess->horizontalHeader()->setDefaultAlignment(Qt::AlignLeft | Qt::AlignVCenter);
ui->tableProcess->horizontalHeader()->setCursor(Qt::PointingHandCursor);
ui->tableProcess->horizontalHeader()->resizeSection(0, 70);
loadProcesses();
connect(mTimer, &QTimer::timeout, this, &ProcessesPage::loadProcesses);
mTimer->setInterval(1000);
mTimer->start();
ui->tableProcess->horizontalHeader()->setContextMenuPolicy(Qt::CustomContextMenu);
connect(ui->tableProcess->horizontalHeader(), SIGNAL(customContextMenuRequested(const QPoint&)),
this, SLOT(on_tableProcess_customContextMenuRequested(const QPoint&)));
loadHeaderMenu();
Utilities::addDropShadow(ui->btnEndProcess, 60);
Utilities::addDropShadow(ui->tableProcess, 55);
}
void ProcessesPage::loadHeaderMenu()
{
int i = 0;
for (const QString &header : mHeaders) {
QAction *action = new QAction(header);
action->setCheckable(true);
action->setChecked(true);
action->setData(i++);
mHeaderMenu.addAction(action);
}
// exclude headers
QList<int> hiddenHeaders = { 3, 6, 7, 8, 9, 10, 11 };
QList<QAction*> actions = mHeaderMenu.actions();
for (const int i : hiddenHeaders) {
if (i < mHeaders.count()) {
ui->tableProcess->horizontalHeader()->setSectionHidden(i, true);
actions.at(i)->setChecked(false);
}
}
}
void ProcessesPage::loadProcesses()
{
QModelIndexList selecteds = ui->tableProcess->selectionModel()->selectedRows();
mItemModel->removeRows(0, mItemModel->rowCount());
im->updateProcesses();
QList<Process> processes = im->getProcesses();
QString username = im->getUserName();
if (ui->checkAllProcesses->isChecked()) {
for (const Process &proc : processes) {
mItemModel->appendRow(createRow(proc));
}
} else {
for (const Process &proc : processes) {
if (username == proc.getUname()) {
mItemModel->appendRow(createRow(proc));
}
}
}
ui->lblProcessTitle->setText(tr("Processes (%1)").arg(mItemModel->rowCount()));
// selected item
if(! selecteds.isEmpty()) {
mSeletedRowModel = selecteds.first();
for (int i = 0; i < mSortFilterModel->rowCount(); ++i) {
if (mSortFilterModel->index(i, 0).data(1).toInt() == mSeletedRowModel.data(1).toInt()) {
ui->tableProcess->selectRow(i);
}
}
} else {
mSeletedRowModel = QModelIndex();
}
}
QList<QStandardItem*> ProcessesPage::createRow(const Process &proc)
{
QList<QStandardItem*> row;
int data = 1;
QStandardItem *pid_i = new QStandardItem(QString::number(proc.getPid()));
pid_i->setData(proc.getPid(), data);
pid_i->setData(proc.getPid(), Qt::ToolTipRole);
QStandardItem *rss_i = new QStandardItem(FormatUtil::formatBytes(proc.getRss()));
rss_i->setData(proc.getRss(), data);
rss_i->setData(FormatUtil::formatBytes(proc.getRss()), Qt::ToolTipRole);
QStandardItem *pmem_i = new QStandardItem(QString::number(proc.getPmem()));
pmem_i->setData(proc.getPmem(), data);
pmem_i->setData(proc.getPmem(), Qt::ToolTipRole);
QStandardItem *vsize_i = new QStandardItem(FormatUtil::formatBytes(proc.getVsize()));
vsize_i->setData(proc.getVsize(), data);
vsize_i->setData(FormatUtil::formatBytes(proc.getVsize()), Qt::ToolTipRole);
QStandardItem *uname_i = new QStandardItem(proc.getUname());
uname_i->setData(proc.getUname(), data);
uname_i->setData(proc.getUname(), Qt::ToolTipRole);
QStandardItem *pcpu_i = new QStandardItem(QString::number(proc.getPcpu()));
pcpu_i->setData(proc.getPcpu(), data);
pcpu_i->setData(proc.getPcpu(), Qt::ToolTipRole);
QStandardItem *starttime_i = new QStandardItem(proc.getStartTime());
starttime_i->setData(proc.getStartTime(), data);
starttime_i->setData(proc.getStartTime(), Qt::ToolTipRole);
QStandardItem *state_i = new QStandardItem(proc.getState());
state_i->setData(proc.getState(), data);
state_i->setData(proc.getState(), Qt::ToolTipRole);
QStandardItem *group_i = new QStandardItem(proc.getGroup());
group_i->setData(proc.getGroup(), data);
group_i->setData(proc.getGroup(), Qt::ToolTipRole);
QStandardItem *nice_i = new QStandardItem(QString::number(proc.getNice()));
nice_i->setData(proc.getNice(), data);
nice_i->setData(proc.getNice(), Qt::ToolTipRole);
QStandardItem *cpuTime_i = new QStandardItem(proc.getCpuTime());
cpuTime_i->setData(proc.getCpuTime(), data);
cpuTime_i->setData(proc.getCpuTime(), Qt::ToolTipRole);
QStandardItem *session_i = new QStandardItem(proc.getSession());
session_i->setData(proc.getSession(), data);
session_i->setData(proc.getSession(), Qt::ToolTipRole);
QStandardItem *cmd_i = new QStandardItem(proc.getCmd());
cmd_i->setData(proc.getCmd(), data);
cmd_i->setData(QString("<p>%1</p>").arg(proc.getCmd()), Qt::ToolTipRole);
row << pid_i << rss_i << pmem_i << vsize_i << uname_i << pcpu_i
<< starttime_i << state_i << group_i << nice_i << cpuTime_i
<< session_i << cmd_i;
return row;
}
void ProcessesPage::on_txtProcessSearch_textChanged(const QString &val)
{
QRegExp query(val, Qt::CaseInsensitive, QRegExp::Wildcard);
mSortFilterModel->setFilterKeyColumn(mHeaders.count() - 1); // process name
mSortFilterModel->setFilterRegExp(query);
}
void ProcessesPage::on_sliderRefresh_valueChanged(const int &i)
{
ui->lblRefresh->setText(tr("Refresh (%1)").arg(i));
mTimer->setInterval(i * 1000);
}
void ProcessesPage::on_btnEndProcess_clicked()
{
pid_t pid = mSeletedRowModel.data(1).toInt();
if (pid) {
QString selectedUname = mSortFilterModel->index(mSeletedRowModel.row(), 4).data(1).toString();
try {
if (selectedUname == im->getUserName()) {
CommandUtil::exec("kill", { QString::number(pid) });
} else {
CommandUtil::sudoExec("kill", { QString::number(pid) });
}
} catch (QString &ex) {
qCritical() << ex;
}
}
}
void ProcessesPage::on_tableProcess_customContextMenuRequested(const QPoint &pos)
{
QPoint globalPos = ui->tableProcess->mapToGlobal(pos);
QAction *action = mHeaderMenu.exec(globalPos);
if (action) {
ui->tableProcess->horizontalHeader()->setSectionHidden(action->data().toInt(), ! action->isChecked());
}
}
<|endoftext|>
|
<commit_before>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the tools applications of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QCoreApplication>
#include <QTextStream>
#include <QStringList>
#include <QScopedPointer>
#include <QTimer>
#include "symbianutils/trkutils.h"
#include "symbianutils/trkdevice.h"
#include "symbianutils/launcher.h"
#include "trksignalhandler.h"
#include "serenum.h"
void printUsage(QTextStream& outstream)
{
outstream << "runtest [options] <program> [program arguments]" << endl
<< "-s, --sis <file> specify sis file to install" << endl
<< "-p, --portname <COMx> specify COM port to use by device name" << endl
<< "-f, --portfriendlyname <substring> specify COM port to use by friendly name" << endl
<< "-t, --timeout <milliseconds> terminate test if timeout occurs" << endl
<< "-v, --verbose show debugging output" << endl
<< "-q, --quiet hide progress messages" << endl
<< endl
<< "USB COM ports can usually be autodetected" << endl;
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QString serialPortName;
QString serialPortFriendlyName;
QString sisFile;
QString exeFile;
QStringList cmdLine;
QStringList args = QCoreApplication::arguments();
QTextStream outstream(stdout);
QTextStream errstream(stderr);
int loglevel=1;
int timeout=0;
for (int i=1;i<args.size();i++) {
QString arg = args.at(i);
if (arg.startsWith("-")) {
if (args.size() < i+2) {
errstream << "Command line missing argument parameters" << endl;
return 1;
}
QString param = args.at(i+1);
if(arg.compare("--portname", Qt::CaseSensitive) == 0
|| arg.compare("-p", Qt::CaseSensitive) == 0) {
serialPortName = param;
i++;
}
else if(arg.compare("--portfriendlyname", Qt::CaseSensitive) == 0
|| arg.compare("-f", Qt::CaseSensitive) == 0) {
serialPortFriendlyName = param;
i++;
}
else if(arg.compare("--sis", Qt::CaseSensitive) == 0
|| arg.compare("-s", Qt::CaseSensitive) == 0) {
sisFile = param;
i++;
}
else if(arg.compare("--timeout", Qt::CaseSensitive) == 0
|| arg.compare("-t", Qt::CaseSensitive) == 0) {
bool ok;
timeout = param.toInt(&ok);
if (!ok) {
errstream << "Timeout must be specified in milliseconds" << endl;
return 1;
}
i++;
}
else if(arg.compare("--verbose", Qt::CaseSensitive) == 0
|| arg.compare("-v", Qt::CaseSensitive) == 0)
loglevel=2;
else if(arg.compare("--quiet", Qt::CaseSensitive) == 0
|| arg.compare("-q", Qt::CaseSensitive) == 0)
loglevel=0;
else
errstream << "unknown command line option " << arg << endl;
} else {
exeFile = arg;
i++;
for(;i<args.size();i++) {
cmdLine.append(args.at(i));
}
}
}
if(exeFile.isEmpty()) {
printUsage(outstream);
return 1;
}
if (serialPortName.isEmpty()) {
if (loglevel > 0)
outstream << "Detecting serial ports" << endl;
foreach (const SerialPortId &id, enumerateSerialPorts()) {
if (loglevel > 0)
outstream << "Port Name: " << id.portName << ", "
<< "Friendly Name:" << id.friendlyName << endl;
if (!id.friendlyName.isEmpty()
&& serialPortFriendlyName.isEmpty()
&& (id.friendlyName.contains("symbian", Qt::CaseInsensitive)
|| id.friendlyName.contains("s60", Qt::CaseInsensitive)
|| id.friendlyName.contains("nokia", Qt::CaseInsensitive))) {
serialPortName = id.portName;
break;
} else if (!id.friendlyName.isEmpty()
&& !serialPortFriendlyName.isEmpty()
&& id.friendlyName.contains(serialPortFriendlyName)) {
serialPortName = id.portName;
break;
}
}
if (serialPortName.isEmpty()) {
errstream << "No phone found, ensure USB cable is connected or specify manually with -p" << endl;
return 1;
}
}
QScopedPointer<trk::Launcher> launcher;
if (sisFile.isEmpty()) {
launcher.reset(new trk::Launcher(trk::Launcher::ActionCopyRun));
launcher->setCopyFileName(exeFile, QString("c:\\sys\\bin\\") + exeFile);
errstream << "System TRK required to copy EXE, use --sis if using Application TRK" << endl;
} else {
launcher.reset(new trk::Launcher(trk::Launcher::ActionCopyInstallRun));
launcher->addStartupActions(trk::Launcher::ActionInstall);
launcher->setCopyFileName(sisFile, "c:\\data\\testtemp.sis");
launcher->setInstallFileName("c:\\data\\testtemp.sis");
}
if (loglevel > 0)
outstream << "Connecting to target via " << serialPortName << endl;
launcher->setTrkServerName(serialPortName);
launcher->setFileName(QString("c:\\sys\\bin\\") + exeFile);
launcher->setCommandLineArgs(cmdLine);
if (loglevel > 1)
launcher->setVerbose(1);
TrkSignalHandler handler;
handler.setLogLevel(loglevel);
QObject::connect(launcher.data(), SIGNAL(copyingStarted()), &handler, SLOT(copyingStarted()));
QObject::connect(launcher.data(), SIGNAL(canNotConnect(const QString &)), &handler, SLOT(canNotConnect(const QString &)));
QObject::connect(launcher.data(), SIGNAL(canNotCreateFile(const QString &, const QString &)), &handler, SLOT(canNotCreateFile(const QString &, const QString &)));
QObject::connect(launcher.data(), SIGNAL(canNotWriteFile(const QString &, const QString &)), &handler, SLOT(canNotWriteFile(const QString &, const QString &)));
QObject::connect(launcher.data(), SIGNAL(canNotCloseFile(const QString &, const QString &)), &handler, SLOT(canNotCloseFile(const QString &, const QString &)));
QObject::connect(launcher.data(), SIGNAL(installingStarted()), &handler, SLOT(installingStarted()));
QObject::connect(launcher.data(), SIGNAL(canNotInstall(const QString &, const QString &)), &handler, SLOT(canNotInstall(const QString &, const QString &)));
QObject::connect(launcher.data(), SIGNAL(installingFinished()), &handler, SLOT(installingFinished()));
QObject::connect(launcher.data(), SIGNAL(startingApplication()), &handler, SLOT(startingApplication()));
QObject::connect(launcher.data(), SIGNAL(applicationRunning(uint)), &handler, SLOT(applicationRunning(uint)));
QObject::connect(launcher.data(), SIGNAL(canNotRun(const QString &)), &handler, SLOT(canNotRun(const QString &)));
QObject::connect(launcher.data(), SIGNAL(applicationOutputReceived(const QString &)), &handler, SLOT(applicationOutputReceived(const QString &)));
QObject::connect(launcher.data(), SIGNAL(copyProgress(int)), &handler, SLOT(copyProgress(int)));
QObject::connect(launcher.data(), SIGNAL(stateChanged(int)), &handler, SLOT(stateChanged(int)));
QObject::connect(launcher.data(), SIGNAL(processStopped(uint,uint,uint,QString)), &handler, SLOT(stopped(uint,uint,uint,QString)));
QObject::connect(&handler, SIGNAL(resume(uint,uint)), launcher.data(), SLOT(resumeProcess(uint,uint)));
QObject::connect(&handler, SIGNAL(terminate()), launcher.data(), SLOT(terminate()));
QObject::connect(launcher.data(), SIGNAL(finished()), &handler, SLOT(finished()));
QTimer timer;
timer.setSingleShot(true);
QObject::connect(&timer, SIGNAL(timeout()), &handler, SLOT(timeout()));
if (timeout > 0) {
timer.start(timeout);
}
QString errorMessage;
if (!launcher->startServer(&errorMessage)) {
errstream << errorMessage << endl;
return 1;
}
return a.exec();
}
<commit_msg>Enable installation of a sis file without running any application<commit_after>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the tools applications of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QCoreApplication>
#include <QTextStream>
#include <QStringList>
#include <QScopedPointer>
#include <QTimer>
#include <QFileInfo>
#include "symbianutils/trkutils.h"
#include "symbianutils/trkdevice.h"
#include "symbianutils/launcher.h"
#include "trksignalhandler.h"
#include "serenum.h"
void printUsage(QTextStream& outstream, QString exeName)
{
outstream << exeName << " [options] [program] [program arguments]" << endl
<< "-s, --sis <file> specify sis file to install" << endl
<< "-p, --portname <COMx> specify COM port to use by device name" << endl
<< "-f, --portfriendlyname <substring> specify COM port to use by friendly name" << endl
<< "-t, --timeout <milliseconds> terminate test if timeout occurs" << endl
<< "-v, --verbose show debugging output" << endl
<< "-q, --quiet hide progress messages" << endl
<< endl
<< "USB COM ports can usually be autodetected, use -p or -f to force a specific port." << endl
<< "If using System TRK, it is possible to copy the program directly to sys/bin on the phone." << endl
<< "-s can be used with both System and Application TRK to install the program" << endl;
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QString serialPortName;
QString serialPortFriendlyName;
QString sisFile;
QString exeFile;
QStringList cmdLine;
QStringList args = QCoreApplication::arguments();
QTextStream outstream(stdout);
QTextStream errstream(stderr);
int loglevel=1;
int timeout=0;
for (int i=1;i<args.size();i++) {
QString arg = args.at(i);
if (arg.startsWith("-")) {
if (args.size() < i+2) {
errstream << "Command line missing argument parameters" << endl;
return 1;
}
QString param = args.at(i+1);
if (arg.compare("--portname", Qt::CaseSensitive) == 0
|| arg.compare("-p", Qt::CaseSensitive) == 0) {
serialPortName = param;
i++;
}
else if (arg.compare("--portfriendlyname", Qt::CaseSensitive) == 0
|| arg.compare("-f", Qt::CaseSensitive) == 0) {
serialPortFriendlyName = param;
i++;
}
else if (arg.compare("--sis", Qt::CaseSensitive) == 0
|| arg.compare("-s", Qt::CaseSensitive) == 0) {
sisFile = param;
i++;
}
else if (arg.compare("--timeout", Qt::CaseSensitive) == 0
|| arg.compare("-t", Qt::CaseSensitive) == 0) {
bool ok;
timeout = param.toInt(&ok);
if (!ok) {
errstream << "Timeout must be specified in milliseconds" << endl;
return 1;
}
i++;
}
else if (arg.compare("--verbose", Qt::CaseSensitive) == 0
|| arg.compare("-v", Qt::CaseSensitive) == 0)
loglevel=2;
else if (arg.compare("--quiet", Qt::CaseSensitive) == 0
|| arg.compare("-q", Qt::CaseSensitive) == 0)
loglevel=0;
else
errstream << "unknown command line option " << arg << endl;
} else {
exeFile = arg;
i++;
for(;i<args.size();i++) {
cmdLine.append(args.at(i));
}
}
}
if (exeFile.isEmpty() && sisFile.isEmpty()) {
printUsage(outstream, args[0]);
return 1;
}
if (serialPortName.isEmpty()) {
if (loglevel > 0)
outstream << "Detecting serial ports" << endl;
foreach (const SerialPortId &id, enumerateSerialPorts()) {
if (loglevel > 0)
outstream << "Port Name: " << id.portName << ", "
<< "Friendly Name:" << id.friendlyName << endl;
if (!id.friendlyName.isEmpty()
&& serialPortFriendlyName.isEmpty()
&& (id.friendlyName.contains("symbian", Qt::CaseInsensitive)
|| id.friendlyName.contains("s60", Qt::CaseInsensitive)
|| id.friendlyName.contains("nokia", Qt::CaseInsensitive))) {
serialPortName = id.portName;
break;
} else if (!id.friendlyName.isEmpty()
&& !serialPortFriendlyName.isEmpty()
&& id.friendlyName.contains(serialPortFriendlyName)) {
serialPortName = id.portName;
break;
}
}
if (serialPortName.isEmpty()) {
errstream << "No phone found, ensure USB cable is connected or specify manually with -p" << endl;
return 1;
}
}
QScopedPointer<trk::Launcher> launcher;
launcher.reset(new trk::Launcher(trk::Launcher::ActionPingOnly));
QFileInfo info(exeFile);
if (!sisFile.isEmpty()) {
launcher->addStartupActions(trk::Launcher::ActionCopyInstall);
launcher->setCopyFileName(sisFile, "c:\\data\\testtemp.sis");
launcher->setInstallFileName("c:\\data\\testtemp.sis");
}
else if (info.exists()) {
launcher->addStartupActions(trk::Launcher::ActionCopy);
launcher->setCopyFileName(exeFile, QString("c:\\sys\\bin\\") + info.fileName());
}
if (!exeFile.isEmpty()) {
launcher->addStartupActions(trk::Launcher::ActionRun);
launcher->setFileName(QString("c:\\sys\\bin\\") + info.fileName());
launcher->setCommandLineArgs(cmdLine);
}
if (loglevel > 0)
outstream << "Connecting to target via " << serialPortName << endl;
launcher->setTrkServerName(serialPortName);
if (loglevel > 1)
launcher->setVerbose(1);
TrkSignalHandler handler;
handler.setLogLevel(loglevel);
QObject::connect(launcher.data(), SIGNAL(copyingStarted()), &handler, SLOT(copyingStarted()));
QObject::connect(launcher.data(), SIGNAL(canNotConnect(const QString &)), &handler, SLOT(canNotConnect(const QString &)));
QObject::connect(launcher.data(), SIGNAL(canNotCreateFile(const QString &, const QString &)), &handler, SLOT(canNotCreateFile(const QString &, const QString &)));
QObject::connect(launcher.data(), SIGNAL(canNotWriteFile(const QString &, const QString &)), &handler, SLOT(canNotWriteFile(const QString &, const QString &)));
QObject::connect(launcher.data(), SIGNAL(canNotCloseFile(const QString &, const QString &)), &handler, SLOT(canNotCloseFile(const QString &, const QString &)));
QObject::connect(launcher.data(), SIGNAL(installingStarted()), &handler, SLOT(installingStarted()));
QObject::connect(launcher.data(), SIGNAL(canNotInstall(const QString &, const QString &)), &handler, SLOT(canNotInstall(const QString &, const QString &)));
QObject::connect(launcher.data(), SIGNAL(installingFinished()), &handler, SLOT(installingFinished()));
QObject::connect(launcher.data(), SIGNAL(startingApplication()), &handler, SLOT(startingApplication()));
QObject::connect(launcher.data(), SIGNAL(applicationRunning(uint)), &handler, SLOT(applicationRunning(uint)));
QObject::connect(launcher.data(), SIGNAL(canNotRun(const QString &)), &handler, SLOT(canNotRun(const QString &)));
QObject::connect(launcher.data(), SIGNAL(applicationOutputReceived(const QString &)), &handler, SLOT(applicationOutputReceived(const QString &)));
QObject::connect(launcher.data(), SIGNAL(copyProgress(int)), &handler, SLOT(copyProgress(int)));
QObject::connect(launcher.data(), SIGNAL(stateChanged(int)), &handler, SLOT(stateChanged(int)));
QObject::connect(launcher.data(), SIGNAL(processStopped(uint,uint,uint,QString)), &handler, SLOT(stopped(uint,uint,uint,QString)));
QObject::connect(&handler, SIGNAL(resume(uint,uint)), launcher.data(), SLOT(resumeProcess(uint,uint)));
QObject::connect(&handler, SIGNAL(terminate()), launcher.data(), SLOT(terminate()));
QObject::connect(launcher.data(), SIGNAL(finished()), &handler, SLOT(finished()));
QTimer timer;
timer.setSingleShot(true);
QObject::connect(&timer, SIGNAL(timeout()), &handler, SLOT(timeout()));
if (timeout > 0) {
timer.start(timeout);
}
QString errorMessage;
if (!launcher->startServer(&errorMessage)) {
errstream << errorMessage << endl;
return 1;
}
return a.exec();
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2016, Baldur Karlsson
//
// Licensed under BSD 2-Clause License, see LICENSE file.
//
// Obtained from https://github.com/baldurk/qprocessinfo
#include "qprocessinfo.h"
#if defined(Q_OS_WIN32)
#include <windows.h>
#include <tlhelp32.h>
typedef DWORD(WINAPI *PFN_GETWINDOWTHREADPROCESSID)(HWND hWnd, LPDWORD lpdwProcessId);
typedef HWND(WINAPI *PFN_GETWINDOW)(HWND hWnd, UINT uCmd);
typedef BOOL(WINAPI *PFN_ISWINDOWVISIBLE)(HWND hWnd);
typedef int(WINAPI *PFN_GETWINDOWTEXTLENGTHW)(HWND hWnd);
typedef int(WINAPI *PFN_GETWINDOWTEXTW)(HWND hWnd, LPWSTR lpString, int nMaxCount);
typedef BOOL(WINAPI *PFN_ENUMWINDOWS)(WNDENUMPROC lpEnumFunc, LPARAM lParam);
namespace
{
struct callbackContext
{
callbackContext(QProcessList &l) : list(l) {}
QProcessList &list;
PFN_GETWINDOWTHREADPROCESSID GetWindowThreadProcessId;
PFN_GETWINDOW GetWindow;
PFN_ISWINDOWVISIBLE IsWindowVisible;
PFN_GETWINDOWTEXTLENGTHW GetWindowTextLengthW;
PFN_GETWINDOWTEXTW GetWindowTextW;
PFN_ENUMWINDOWS EnumWindows;
};
};
static BOOL CALLBACK fillWindowTitles(HWND hwnd, LPARAM lp)
{
callbackContext *ctx = (callbackContext *)lp;
DWORD pid = 0;
ctx->GetWindowThreadProcessId(hwnd, &pid);
HWND parent = ctx->GetWindow(hwnd, GW_OWNER);
if(parent != 0)
return TRUE;
if(!ctx->IsWindowVisible(hwnd))
return TRUE;
for(QProcessInfo &info : ctx->list)
{
if(info.pid() == (uint32_t)pid)
{
int len = ctx->GetWindowTextLengthW(hwnd);
wchar_t *buf = new wchar_t[len + 1];
ctx->GetWindowTextW(hwnd, buf, len + 1);
buf[len] = 0;
info.setWindowTitle(QString::fromStdWString(std::wstring(buf)));
delete[] buf;
return TRUE;
}
}
return TRUE;
}
QProcessList QProcessInfo::enumerate()
{
QProcessList ret;
HANDLE h = NULL;
PROCESSENTRY32 pe = {0};
pe.dwSize = sizeof(PROCESSENTRY32);
h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if(Process32First(h, &pe))
{
do
{
QProcessInfo info;
info.setPid((uint32_t)pe.th32ProcessID);
info.setName(QString::fromStdWString(std::wstring(pe.szExeFile)));
ret.push_back(info);
} while(Process32Next(h, &pe));
}
CloseHandle(h);
HMODULE user32 = LoadLibraryA("user32.dll");
if(user32)
{
callbackContext ctx(ret);
ctx.GetWindowThreadProcessId =
(PFN_GETWINDOWTHREADPROCESSID)GetProcAddress(user32, "GetWindowThreadProcessId");
ctx.GetWindow = (PFN_GETWINDOW)GetProcAddress(user32, "GetWindow");
ctx.IsWindowVisible = (PFN_ISWINDOWVISIBLE)GetProcAddress(user32, "IsWindowVisible");
ctx.GetWindowTextLengthW =
(PFN_GETWINDOWTEXTLENGTHW)GetProcAddress(user32, "GetWindowTextLengthW");
ctx.GetWindowTextW = (PFN_GETWINDOWTEXTW)GetProcAddress(user32, "GetWindowTextW");
ctx.EnumWindows = (PFN_ENUMWINDOWS)GetProcAddress(user32, "EnumWindows");
if(ctx.GetWindowThreadProcessId && ctx.GetWindow && ctx.IsWindowVisible &&
ctx.GetWindowTextLengthW && ctx.GetWindowTextW && ctx.EnumWindows)
{
ctx.EnumWindows(fillWindowTitles, (LPARAM)&ctx);
}
FreeLibrary(user32);
}
return ret;
}
#elif defined(Q_OS_UNIX)
#include <QDir>
#include <QProcess>
#include <QRegExp>
#include <QTextStream>
QProcessList QProcessInfo::enumerate()
{
QProcessList ret;
QDir proc(QStringLiteral("/proc"));
QStringList files = proc.entryList();
for(const QString &f : files)
{
bool ok = false;
uint32_t pid = f.toUInt(&ok);
if(ok)
{
QProcessInfo info;
info.setPid(pid);
QDir processDir(QStringLiteral("/proc") + f);
// default to the exe symlink if valid
QFileInfo exe(processDir.absoluteFilePath(QStringLiteral("exe")));
exe = QFileInfo(exe.symLinkTarget());
info.setName(exe.completeBaseName());
// if we didn't get a name from the symlink, check in the status file
if(info.name().isEmpty())
{
QFile status(processDir.absoluteFilePath(QStringLiteral("status")));
if(status.open(QIODevice::ReadOnly))
{
QByteArray contents = status.readAll();
QTextStream in(&contents);
while(!in.atEnd())
{
QString line = in.readLine();
if(line.startsWith(QStringLiteral("Name:")))
{
line.remove(0, 5);
// if we're using this name, surround with []s to indicate it's not a file
info.setName(QStringLiteral("[%1]").arg(line.trimmed()));
break;
}
}
status.close();
}
}
// get the command line
QFile cmdline(processDir.absoluteFilePath(QStringLiteral("cmdline")));
if(cmdline.open(QIODevice::ReadOnly))
{
QByteArray contents = cmdline.readAll();
int nullIdx = contents.indexOf('\0');
if(nullIdx > 0)
{
QString firstparam = QString::fromUtf8(contents.data(), nullIdx);
// if name is a truncated form of a filename, replace it
if(firstparam.endsWith(info.name()) && QFileInfo::exists(firstparam))
info.setName(QFileInfo(firstparam).completeBaseName());
// if we don't have a name, replace it but with []s
if(info.name().isEmpty())
info.setName(QStringLiteral("[%1]").arg(firstparam));
contents.replace('\0', ' ');
}
info.setCommandLine(QString::fromUtf8(contents).trimmed());
cmdline.close();
}
ret.push_back(info);
}
}
{
// get a list of all windows. This is faster than searching with --pid
// for every PID, and usually there will be fewer windows than PIDs.
QStringList params;
params << QStringLiteral("search") << QStringLiteral("--onlyvisible") << QStringLiteral(".*");
QList<QByteArray> windowlist;
{
QProcess process;
process.start(QStringLiteral("xdotool"), params);
process.waitForFinished(100);
windowlist = process.readAll().split('\n');
}
// if xdotool isn't installed or failed to run, we'll have an empty
// list or else entries that aren't numbers, so we'll skip them
for(const QByteArray &win : windowlist)
{
// empty result, no window matches
if(win.size() == 0)
continue;
bool isUInt = false;
win.toUInt(&isUInt);
// skip invalid lines (maybe because xdotool failed)
if(!isUInt)
continue;
// get the PID of the window first. If one isn't available we won't
// be able to match it up to our entries so don't proceed further
params.clear();
params << QStringLiteral("getwindowpid") << QString::fromLatin1(win);
uint32_t pid = 0;
{
QProcess process;
process.start(QStringLiteral("xdotool"), params);
process.waitForFinished(100);
pid = process.readAll().trimmed().toUInt(&isUInt);
}
// can't find a PID, skip this window
if(!isUInt || pid == 0)
continue;
// check to see if the geometry is somewhere offscreen
params.clear();
params << QStringLiteral("getwindowgeometry") << QString::fromLatin1(win);
QList<QByteArray> winGeometry;
{
QProcess process;
process.start(QStringLiteral("xdotool"), params);
process.waitForFinished(100);
winGeometry = process.readAll().split('\n');
}
// should be three lines: Window <id> \n Position: ... \n Geometry: ...
if(winGeometry.size() >= 3)
{
QRegExp pos(QStringLiteral("Position: (-?\\d+),(-?\\d+)"));
QRegExp geometry(QStringLiteral("Geometry: (\\d+)x(\\d+)"));
QString posString = QString::fromUtf8(winGeometry[1]);
QString geometryString = QString::fromUtf8(winGeometry[2]);
int x = 0, y = 0, w = 1000, h = 1000;
if(pos.indexIn(posString) >= 0)
{
x = pos.cap(1).toInt();
y = pos.cap(2).toInt();
}
if(geometry.indexIn(geometryString) >= 0)
{
w = geometry.cap(1).toInt();
h = geometry.cap(2).toInt();
}
// some invisible windows are placed off screen, if we detect that skip it
if(x + w < 0 && y + h < 0)
continue;
}
// take the first window name
{
params.clear();
params << QStringLiteral("getwindowname") << QString::fromLatin1(win);
QProcess process;
process.start(QStringLiteral("xdotool"), params);
process.waitForFinished(100);
QString windowTitle = QString::fromUtf8(process.readAll().split('\n')[0]);
for(QProcessInfo &info : ret)
{
if(info.pid() == pid)
{
info.setWindowTitle(windowTitle);
break;
}
}
}
}
}
return ret;
}
#else
QProcessList QProcessInfo::enumerate()
{
QProcessList ret;
qWarning() << "Process enumeration not supported on this platform";
return ret;
}
#endif
uint32_t QProcessInfo::pid() const
{
return m_pid;
}
void QProcessInfo::setPid(uint32_t pid)
{
m_pid = pid;
}
const QString &QProcessInfo::name() const
{
return m_name;
}
void QProcessInfo::setName(const QString &name)
{
m_name = name;
}
const QString &QProcessInfo::windowTitle() const
{
return m_title;
}
void QProcessInfo::setWindowTitle(const QString &title)
{
m_title = title;
}
const QString &QProcessInfo::commandLine() const
{
return m_cmdLine;
}
void QProcessInfo::setCommandLine(const QString &cmd)
{
m_cmdLine = cmd;
}
<commit_msg>Update qprocessinfo to 39678d76bd9b462da9acbfea397dd56494aab73e<commit_after>// Copyright (c) 2016, Baldur Karlsson
//
// Licensed under BSD 2-Clause License, see LICENSE file.
//
// Obtained from https://github.com/baldurk/qprocessinfo
#include "qprocessinfo.h"
#if defined(Q_OS_WIN32)
#include <windows.h>
#include <tlhelp32.h>
typedef DWORD(WINAPI *PFN_GETWINDOWTHREADPROCESSID)(HWND hWnd, LPDWORD lpdwProcessId);
typedef HWND(WINAPI *PFN_GETWINDOW)(HWND hWnd, UINT uCmd);
typedef BOOL(WINAPI *PFN_ISWINDOWVISIBLE)(HWND hWnd);
typedef int(WINAPI *PFN_GETWINDOWTEXTLENGTHW)(HWND hWnd);
typedef int(WINAPI *PFN_GETWINDOWTEXTW)(HWND hWnd, LPWSTR lpString, int nMaxCount);
typedef BOOL(WINAPI *PFN_ENUMWINDOWS)(WNDENUMPROC lpEnumFunc, LPARAM lParam);
namespace
{
struct callbackContext
{
callbackContext(QProcessList &l) : list(l) {}
QProcessList &list;
PFN_GETWINDOWTHREADPROCESSID GetWindowThreadProcessId;
PFN_GETWINDOW GetWindow;
PFN_ISWINDOWVISIBLE IsWindowVisible;
PFN_GETWINDOWTEXTLENGTHW GetWindowTextLengthW;
PFN_GETWINDOWTEXTW GetWindowTextW;
PFN_ENUMWINDOWS EnumWindows;
};
};
static BOOL CALLBACK fillWindowTitles(HWND hwnd, LPARAM lp)
{
callbackContext *ctx = (callbackContext *)lp;
DWORD pid = 0;
ctx->GetWindowThreadProcessId(hwnd, &pid);
HWND parent = ctx->GetWindow(hwnd, GW_OWNER);
if(parent != 0)
return TRUE;
if(!ctx->IsWindowVisible(hwnd))
return TRUE;
for(QProcessInfo &info : ctx->list)
{
if(info.pid() == (uint32_t)pid)
{
int len = ctx->GetWindowTextLengthW(hwnd);
wchar_t *buf = new wchar_t[len + 1];
ctx->GetWindowTextW(hwnd, buf, len + 1);
buf[len] = 0;
info.setWindowTitle(QString::fromStdWString(std::wstring(buf)));
delete[] buf;
return TRUE;
}
}
return TRUE;
}
QProcessList QProcessInfo::enumerate()
{
QProcessList ret;
HANDLE h = NULL;
PROCESSENTRY32 pe = {0};
pe.dwSize = sizeof(PROCESSENTRY32);
h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if(Process32First(h, &pe))
{
do
{
QProcessInfo info;
info.setPid((uint32_t)pe.th32ProcessID);
info.setName(QString::fromStdWString(std::wstring(pe.szExeFile)));
ret.push_back(info);
} while(Process32Next(h, &pe));
}
CloseHandle(h);
HMODULE user32 = LoadLibraryA("user32.dll");
if(user32)
{
callbackContext ctx(ret);
ctx.GetWindowThreadProcessId =
(PFN_GETWINDOWTHREADPROCESSID)GetProcAddress(user32, "GetWindowThreadProcessId");
ctx.GetWindow = (PFN_GETWINDOW)GetProcAddress(user32, "GetWindow");
ctx.IsWindowVisible = (PFN_ISWINDOWVISIBLE)GetProcAddress(user32, "IsWindowVisible");
ctx.GetWindowTextLengthW =
(PFN_GETWINDOWTEXTLENGTHW)GetProcAddress(user32, "GetWindowTextLengthW");
ctx.GetWindowTextW = (PFN_GETWINDOWTEXTW)GetProcAddress(user32, "GetWindowTextW");
ctx.EnumWindows = (PFN_ENUMWINDOWS)GetProcAddress(user32, "EnumWindows");
if(ctx.GetWindowThreadProcessId && ctx.GetWindow && ctx.IsWindowVisible &&
ctx.GetWindowTextLengthW && ctx.GetWindowTextW && ctx.EnumWindows)
{
ctx.EnumWindows(fillWindowTitles, (LPARAM)&ctx);
}
FreeLibrary(user32);
}
return ret;
}
#elif defined(Q_OS_UNIX)
#include <QDir>
#include <QProcess>
#include <QRegExp>
#include <QStandardPaths>
#include <QTextStream>
QProcessList QProcessInfo::enumerate()
{
QProcessList ret;
QDir proc(QStringLiteral("/proc"));
QStringList files = proc.entryList();
for(const QString &f : files)
{
bool ok = false;
uint32_t pid = f.toUInt(&ok);
if(ok)
{
QProcessInfo info;
info.setPid(pid);
QDir processDir(QStringLiteral("/proc/") + f);
// default to the exe symlink if valid
QFileInfo exe(processDir.absoluteFilePath(QStringLiteral("exe")));
exe = QFileInfo(exe.symLinkTarget());
info.setName(exe.completeBaseName());
// if we didn't get a name from the symlink, check in the status file
if(info.name().isEmpty())
{
QFile status(processDir.absoluteFilePath(QStringLiteral("status")));
if(status.open(QIODevice::ReadOnly))
{
QByteArray contents = status.readAll();
QTextStream in(&contents);
while(!in.atEnd())
{
QString line = in.readLine();
if(line.startsWith(QStringLiteral("Name:")))
{
line.remove(0, 5);
// if we're using this name, surround with []s to indicate it's not a file
info.setName(QStringLiteral("[%1]").arg(line.trimmed()));
break;
}
}
status.close();
}
}
// get the command line
QFile cmdline(processDir.absoluteFilePath(QStringLiteral("cmdline")));
if(cmdline.open(QIODevice::ReadOnly))
{
QByteArray contents = cmdline.readAll();
int nullIdx = contents.indexOf('\0');
if(nullIdx > 0)
{
QString firstparam = QString::fromUtf8(contents.data(), nullIdx);
// if name is a truncated form of a filename, replace it
if(firstparam.endsWith(info.name()) && QFileInfo::exists(firstparam))
info.setName(QFileInfo(firstparam).completeBaseName());
// if we don't have a name, replace it but with []s
if(info.name().isEmpty())
info.setName(QStringLiteral("[%1]").arg(firstparam));
contents.replace('\0', ' ');
}
info.setCommandLine(QString::fromUtf8(contents).trimmed());
cmdline.close();
}
ret.push_back(info);
}
}
{
// get a list of all windows. This is faster than searching with --pid
// for every PID, and usually there will be fewer windows than PIDs.
QStringList params;
params << QStringLiteral("search") << QStringLiteral("--onlyvisible") << QStringLiteral(".*");
QList<QByteArray> windowlist;
QString inPath = QStandardPaths::findExecutable(QStringLiteral("xdotool"));
if(inPath.isEmpty())
{
// add a fake window title to the first process to indicate that xdotool is missing
if(!ret.isEmpty())
ret[0].setWindowTitle(QStringLiteral("Window titles not available - install `xdotool`"));
}
else
{
QProcess process;
process.start(QStringLiteral("xdotool"), params);
process.waitForFinished(100);
windowlist = process.readAll().split('\n');
}
// if xdotool isn't installed or failed to run, we'll have an empty
// list or else entries that aren't numbers, so we'll skip them
for(const QByteArray &win : windowlist)
{
// empty result, no window matches
if(win.size() == 0)
continue;
bool isUInt = false;
win.toUInt(&isUInt);
// skip invalid lines (maybe because xdotool failed)
if(!isUInt)
continue;
// get the PID of the window first. If one isn't available we won't
// be able to match it up to our entries so don't proceed further
params.clear();
params << QStringLiteral("getwindowpid") << QString::fromLatin1(win);
uint32_t pid = 0;
{
QProcess process;
process.start(QStringLiteral("xdotool"), params);
process.waitForFinished(100);
pid = process.readAll().trimmed().toUInt(&isUInt);
}
// can't find a PID, skip this window
if(!isUInt || pid == 0)
continue;
// check to see if the geometry is somewhere offscreen
params.clear();
params << QStringLiteral("getwindowgeometry") << QString::fromLatin1(win);
QList<QByteArray> winGeometry;
{
QProcess process;
process.start(QStringLiteral("xdotool"), params);
process.waitForFinished(100);
winGeometry = process.readAll().split('\n');
}
// should be three lines: Window <id> \n Position: ... \n Geometry: ...
if(winGeometry.size() >= 3)
{
QRegExp pos(QStringLiteral("Position: (-?\\d+),(-?\\d+)"));
QRegExp geometry(QStringLiteral("Geometry: (\\d+)x(\\d+)"));
QString posString = QString::fromUtf8(winGeometry[1]);
QString geometryString = QString::fromUtf8(winGeometry[2]);
int x = 0, y = 0, w = 1000, h = 1000;
if(pos.indexIn(posString) >= 0)
{
x = pos.cap(1).toInt();
y = pos.cap(2).toInt();
}
if(geometry.indexIn(geometryString) >= 0)
{
w = geometry.cap(1).toInt();
h = geometry.cap(2).toInt();
}
// some invisible windows are placed off screen, if we detect that skip it
if(x + w < 0 && y + h < 0)
continue;
}
// take the first window name
{
params.clear();
params << QStringLiteral("getwindowname") << QString::fromLatin1(win);
QProcess process;
process.start(QStringLiteral("xdotool"), params);
process.waitForFinished(100);
QString windowTitle = QString::fromUtf8(process.readAll().split('\n')[0]);
for(QProcessInfo &info : ret)
{
if(info.pid() == pid)
{
info.setWindowTitle(windowTitle);
break;
}
}
}
}
}
return ret;
}
#else
QProcessList QProcessInfo::enumerate()
{
QProcessList ret;
qWarning() << "Process enumeration not supported on this platform";
return ret;
}
#endif
uint32_t QProcessInfo::pid() const
{
return m_pid;
}
void QProcessInfo::setPid(uint32_t pid)
{
m_pid = pid;
}
const QString &QProcessInfo::name() const
{
return m_name;
}
void QProcessInfo::setName(const QString &name)
{
m_name = name;
}
const QString &QProcessInfo::windowTitle() const
{
return m_title;
}
void QProcessInfo::setWindowTitle(const QString &title)
{
m_title = title;
}
const QString &QProcessInfo::commandLine() const
{
return m_cmdLine;
}
void QProcessInfo::setCommandLine(const QString &cmd)
{
m_cmdLine = cmd;
}
<|endoftext|>
|
<commit_before>#include "profilerui.h"
#include "ui_profilerui.h"
#include <qpainter.h>
#include <qpixmap.h>
static const int MAX_FRAMES = 200;
ProfileModel::Block::Block()
{
m_frames.reserve(MAX_FRAMES);
for(int i = 0; i < MAX_FRAMES; ++i)
{
m_frames.push_back(0);
}
m_hit_counts.reserve(MAX_FRAMES);
for (int i = 0; i < MAX_FRAMES; ++i)
{
m_hit_counts.push_back(0);
}
}
ProfileModel::ProfileModel(QWidget* parent)
: QAbstractItemModel(parent)
{
Lumix::g_profiler.getFrameListeners().bind<ProfileModel, &ProfileModel::onFrame>(this);
m_root = NULL;
m_frame = -1;
}
void ProfileModel::cloneBlock(Block* my_block, Lumix::Profiler::Block* remote_block)
{
ASSERT(my_block->m_name == remote_block->m_name);
my_block->m_frames.push_back(remote_block->getLength());
my_block->m_hit_counts.push_back(remote_block->getHitCount());
if (my_block->m_frames.size() > MAX_FRAMES)
{
my_block->m_frames.pop_front();
}
if (my_block->m_hit_counts.size() > MAX_FRAMES)
{
my_block->m_hit_counts.pop_front();
}
if (!my_block->m_first_child && remote_block->m_first_child)
{
Lumix::Profiler::Block* remote_child = remote_block->m_first_child;
Block* my_child = new Block;
my_child->m_function = remote_child->m_function;
my_child->m_name = remote_child->m_name;
my_child->m_parent = my_block;
my_child->m_next = NULL;
my_child->m_first_child = NULL;
my_block->m_first_child = my_child;
cloneBlock(my_child, remote_child);
}
else if(my_block->m_first_child)
{
Lumix::Profiler::Block* remote_child = remote_block->m_first_child;
Block* my_child = my_block->m_first_child;
cloneBlock(my_child, remote_child);
}
if (!my_block->m_next && remote_block->m_next)
{
Lumix::Profiler::Block* remote_next = remote_block->m_next;
Block* my_next = new Block;
my_next->m_function = remote_next->m_function;
my_next->m_name = remote_next->m_name;
my_next->m_parent = my_block->m_parent;
my_next->m_next = NULL;
my_next->m_first_child = NULL;
my_block->m_next = my_next;
cloneBlock(my_next, remote_next);
}
else if (my_block->m_next)
{
cloneBlock(my_block->m_next, remote_block->m_next);
}
}
void ProfileModel::onFrame()
{
if(!m_root && Lumix::g_profiler.getRootBlock())
{
m_root = new Block;
m_root->m_function = Lumix::g_profiler.getRootBlock()->m_function;
m_root->m_name = Lumix::g_profiler.getRootBlock()->m_name;
m_root->m_parent = NULL;
m_root->m_next = NULL;
m_root->m_first_child = NULL;
}
if(m_root)
{
cloneBlock(m_root, Lumix::g_profiler.getRootBlock());
}
static int hit = 0;
++hit;
int count = 0;
Block* child = m_root->m_first_child;
while(child)
{
++count;
child = child->m_next;
}
if(hit % 10 == 0)
{
emit dataChanged(createIndex(0, 0, m_root), createIndex(count, 0, m_root));
}
}
QVariant ProfileModel::headerData(int section, Qt::Orientation, int role) const
{
if(role == Qt::DisplayRole)
{
switch(section)
{
case Values::FUNCTION:
return "Function";
case Values::NAME:
return "Name";
case Values::LENGTH:
return "Length (ms)";
case Values::LENGTH_EXCLUSIVE:
return "Length exclusive (ms)";
case Values::HIT_COUNT:
return "Hit count";
break;
default:
ASSERT(false);
return QVariant();
}
}
return QVariant();
}
QModelIndex ProfileModel::index(int row, int column, const QModelIndex& parent) const
{
if(!hasIndex(row, column, parent))
{
return QModelIndex();
}
Block* block = NULL;
if(parent.internalPointer() != NULL)
{
block = static_cast<Block*>(parent.internalPointer())->m_first_child;
}
else
{
block = m_root;
}
int index = row;
while (block && index > 0)
{
block = block->m_next;
--index;
}
return createIndex(row, column, block);
}
QModelIndex ProfileModel::parent(const QModelIndex& index) const
{
if (!index.isValid() || !index.internalPointer())
{
return QModelIndex();
}
Block* child = static_cast<Block*>(index.internalPointer());
Block* parent = child->m_parent;
if (parent == NULL)
{
return QModelIndex();
}
int row = 0;
Block* row_sibling = parent->m_first_child;
while(row_sibling && row_sibling != child)
{
row_sibling = row_sibling->m_next;
++row;
}
ASSERT(row_sibling);
return createIndex(row, 0, parent);
}
int ProfileModel::rowCount(const QModelIndex& parent_index) const
{
Block* parent;
if (parent_index.column() > 0 || Lumix::g_profiler.getRootBlock() == NULL)
return 0;
if (!parent_index.isValid() || !parent_index.internalPointer())
{
int count = 0;
Block* root = m_root;
while (root)
{
++count;
root = root->m_next;
}
return count;
}
else
{
parent = static_cast<Block*>(parent_index.internalPointer());
}
int count = 0;
Block* child = parent->m_first_child;
while(child)
{
++count;
child = child->m_next;
}
return count;
}
int ProfileModel::columnCount(const QModelIndex&) const
{
return (int)Values::COUNT;
}
QVariant ProfileModel::data(const QModelIndex& index, int role) const
{
if (!index.isValid() || !index.internalPointer())
{
return QVariant();
}
if (role != Qt::DisplayRole)
{
return QVariant();
}
Block* block = static_cast<Block*>(index.internalPointer());
switch(index.column())
{
case Values::FUNCTION:
return block->m_function;
case Values::NAME:
return block->m_name;
case Values::LENGTH:
return m_frame >= 0 && m_frame < block->m_frames.size() ? block->m_frames[m_frame] : (block->m_frames.isEmpty() ? 0 : block->m_frames.back());
case Values::LENGTH_EXCLUSIVE:
{
if (m_frame >= 0 && m_frame < block->m_frames.size())
{
float length = block->m_frames[m_frame];
Block* child = block->m_first_child;
while (child)
{
length -= m_frame < child->m_frames.size() ? child->m_frames[m_frame] : (child->m_frames.isEmpty() ? 0 : child->m_frames.back());
child = child->m_next;
}
return length;
}
else
{
float length = block->m_frames.isEmpty() ? 0 : block->m_frames.back();
Block* child = block->m_first_child;
while (child)
{
length -= child->m_frames.isEmpty() ? 0 : child->m_frames.back();
child = child->m_next;
}
return length;
}
}
break;
case Values::HIT_COUNT:
return m_frame >= 0 && m_frame < block->m_hit_counts.size() ? block->m_hit_counts[m_frame] : (block->m_hit_counts.isEmpty() ? 0 : block->m_hit_counts.back());
break;
default:
ASSERT(false);
return QVariant();
}
}
ProfilerUI::ProfilerUI(QWidget* parent)
: QDockWidget(parent)
, m_ui(new Ui::ProfilerUI)
{
m_sortable_model = new QSortFilterProxyModel(this);
m_model = new ProfileModel(this);
m_sortable_model->setSourceModel(m_model);
m_ui->setupUi(this);
m_ui->profileTreeView->setModel(m_sortable_model);
m_ui->profileTreeView->header()->setSectionResizeMode(0, QHeaderView::ResizeMode::Stretch);
m_ui->profileTreeView->header()->setSectionResizeMode(1, QHeaderView::ResizeMode::ResizeToContents);
m_ui->profileTreeView->header()->setSectionResizeMode(2, QHeaderView::ResizeMode::ResizeToContents);
connect(m_model, &QAbstractItemModel::dataChanged, this, &ProfilerUI::on_dataChanged);
connect(m_ui->graphView, &ProfilerGraph::frameSet, this, &ProfilerUI::on_frameSet);
m_ui->graphView->setModel(m_model);
}
void ProfilerUI::on_dataChanged()
{
m_ui->graphView->update();
}
ProfilerUI::~ProfilerUI()
{
delete m_ui;
}
void ProfilerUI::on_recordCheckBox_stateChanged(int)
{
Lumix::g_profiler.toggleRecording();
m_ui->profileTreeView->setModel(NULL);
m_sortable_model->setSourceModel(m_model);
m_ui->profileTreeView->setModel(m_sortable_model);
m_ui->profileTreeView->update();
}
void ProfilerUI::on_frameSet()
{
m_ui->recordCheckBox->setChecked(false);
m_ui->profileTreeView->update();
m_model->setFrame(m_ui->graphView->getFrame());
}
void ProfilerUI::on_profileTreeView_clicked(const QModelIndex &index)
{
if(index.internalPointer() != NULL)
{
m_ui->graphView->setBlock(static_cast<ProfileModel::Block*>(index.internalPointer()));
m_ui->graphView->update();
}
}
<commit_msg>profiler crash fixed<commit_after>#include "profilerui.h"
#include "ui_profilerui.h"
#include <qpainter.h>
#include <qpixmap.h>
static const int MAX_FRAMES = 200;
ProfileModel::Block::Block()
{
m_frames.reserve(MAX_FRAMES);
for(int i = 0; i < MAX_FRAMES; ++i)
{
m_frames.push_back(0);
}
m_hit_counts.reserve(MAX_FRAMES);
for (int i = 0; i < MAX_FRAMES; ++i)
{
m_hit_counts.push_back(0);
}
}
ProfileModel::ProfileModel(QWidget* parent)
: QAbstractItemModel(parent)
{
Lumix::g_profiler.getFrameListeners().bind<ProfileModel, &ProfileModel::onFrame>(this);
m_root = NULL;
m_frame = -1;
}
void ProfileModel::cloneBlock(Block* my_block, Lumix::Profiler::Block* remote_block)
{
ASSERT(my_block->m_name == remote_block->m_name);
my_block->m_frames.push_back(remote_block->getLength());
my_block->m_hit_counts.push_back(remote_block->getHitCount());
if (my_block->m_frames.size() > MAX_FRAMES)
{
my_block->m_frames.pop_front();
}
if (my_block->m_hit_counts.size() > MAX_FRAMES)
{
my_block->m_hit_counts.pop_front();
}
if (!my_block->m_first_child && remote_block->m_first_child)
{
Lumix::Profiler::Block* remote_child = remote_block->m_first_child;
Block* my_child = new Block;
my_child->m_function = remote_child->m_function;
my_child->m_name = remote_child->m_name;
my_child->m_parent = my_block;
my_child->m_next = NULL;
my_child->m_first_child = NULL;
my_block->m_first_child = my_child;
cloneBlock(my_child, remote_child);
}
else if(my_block->m_first_child)
{
Lumix::Profiler::Block* remote_child = remote_block->m_first_child;
Block* my_child = my_block->m_first_child;
if(my_child->m_function != remote_child->m_function || my_child->m_name != remote_child->m_name)
{
Block* my_new_child = new Block;
my_new_child->m_function = remote_child->m_function;
my_new_child->m_name = remote_child->m_name;
my_new_child->m_parent = my_block;
my_new_child->m_next = my_child;
my_new_child->m_first_child = NULL;
my_block->m_first_child = my_new_child;
my_child = my_new_child;
}
cloneBlock(my_child, remote_child);
}
if (!my_block->m_next && remote_block->m_next)
{
Lumix::Profiler::Block* remote_next = remote_block->m_next;
Block* my_next = new Block;
my_next->m_function = remote_next->m_function;
my_next->m_name = remote_next->m_name;
my_next->m_parent = my_block->m_parent;
my_next->m_next = NULL;
my_next->m_first_child = NULL;
my_block->m_next = my_next;
cloneBlock(my_next, remote_next);
}
else if (my_block->m_next)
{
if(my_block->m_next->m_function != remote_block->m_next->m_function || my_block->m_next->m_name != remote_block->m_next->m_name)
{
Block* my_next = new Block;
Lumix::Profiler::Block* remote_next = remote_block->m_next;
my_next->m_function = remote_next->m_function;
my_next->m_name = remote_next->m_name;
my_next->m_parent = my_block->m_parent;
my_next->m_next = my_block->m_next;
my_next->m_first_child = NULL;
my_block->m_next = my_next;
}
cloneBlock(my_block->m_next, remote_block->m_next);
}
}
void ProfileModel::onFrame()
{
if(!m_root && Lumix::g_profiler.getRootBlock())
{
m_root = new Block;
m_root->m_function = Lumix::g_profiler.getRootBlock()->m_function;
m_root->m_name = Lumix::g_profiler.getRootBlock()->m_name;
m_root->m_parent = NULL;
m_root->m_next = NULL;
m_root->m_first_child = NULL;
}
if(m_root)
{
cloneBlock(m_root, Lumix::g_profiler.getRootBlock());
}
static int hit = 0;
++hit;
int count = 0;
Block* child = m_root->m_first_child;
while(child)
{
++count;
child = child->m_next;
}
if(hit % 10 == 0)
{
emit dataChanged(createIndex(0, 0, m_root), createIndex(count, 0, m_root));
}
}
QVariant ProfileModel::headerData(int section, Qt::Orientation, int role) const
{
if(role == Qt::DisplayRole)
{
switch(section)
{
case Values::FUNCTION:
return "Function";
case Values::NAME:
return "Name";
case Values::LENGTH:
return "Length (ms)";
case Values::LENGTH_EXCLUSIVE:
return "Length exclusive (ms)";
case Values::HIT_COUNT:
return "Hit count";
break;
default:
ASSERT(false);
return QVariant();
}
}
return QVariant();
}
QModelIndex ProfileModel::index(int row, int column, const QModelIndex& parent) const
{
if(!hasIndex(row, column, parent))
{
return QModelIndex();
}
Block* block = NULL;
if(parent.internalPointer() != NULL)
{
block = static_cast<Block*>(parent.internalPointer())->m_first_child;
}
else
{
block = m_root;
}
int index = row;
while (block && index > 0)
{
block = block->m_next;
--index;
}
return createIndex(row, column, block);
}
QModelIndex ProfileModel::parent(const QModelIndex& index) const
{
if (!index.isValid() || !index.internalPointer())
{
return QModelIndex();
}
Block* child = static_cast<Block*>(index.internalPointer());
Block* parent = child->m_parent;
if (parent == NULL)
{
return QModelIndex();
}
int row = 0;
Block* row_sibling = parent->m_first_child;
while(row_sibling && row_sibling != child)
{
row_sibling = row_sibling->m_next;
++row;
}
ASSERT(row_sibling);
return createIndex(row, 0, parent);
}
int ProfileModel::rowCount(const QModelIndex& parent_index) const
{
Block* parent;
if (parent_index.column() > 0 || Lumix::g_profiler.getRootBlock() == NULL)
return 0;
if (!parent_index.isValid() || !parent_index.internalPointer())
{
int count = 0;
Block* root = m_root;
while (root)
{
++count;
root = root->m_next;
}
return count;
}
else
{
parent = static_cast<Block*>(parent_index.internalPointer());
}
int count = 0;
Block* child = parent->m_first_child;
while(child)
{
++count;
child = child->m_next;
}
return count;
}
int ProfileModel::columnCount(const QModelIndex&) const
{
return (int)Values::COUNT;
}
QVariant ProfileModel::data(const QModelIndex& index, int role) const
{
if (!index.isValid() || !index.internalPointer())
{
return QVariant();
}
if (role != Qt::DisplayRole)
{
return QVariant();
}
Block* block = static_cast<Block*>(index.internalPointer());
switch(index.column())
{
case Values::FUNCTION:
return block->m_function;
case Values::NAME:
return block->m_name;
case Values::LENGTH:
return m_frame >= 0 && m_frame < block->m_frames.size() ? block->m_frames[m_frame] : (block->m_frames.isEmpty() ? 0 : block->m_frames.back());
case Values::LENGTH_EXCLUSIVE:
{
if (m_frame >= 0 && m_frame < block->m_frames.size())
{
float length = block->m_frames[m_frame];
Block* child = block->m_first_child;
while (child)
{
length -= m_frame < child->m_frames.size() ? child->m_frames[m_frame] : (child->m_frames.isEmpty() ? 0 : child->m_frames.back());
child = child->m_next;
}
return length;
}
else
{
float length = block->m_frames.isEmpty() ? 0 : block->m_frames.back();
Block* child = block->m_first_child;
while (child)
{
length -= child->m_frames.isEmpty() ? 0 : child->m_frames.back();
child = child->m_next;
}
return length;
}
}
break;
case Values::HIT_COUNT:
return m_frame >= 0 && m_frame < block->m_hit_counts.size() ? block->m_hit_counts[m_frame] : (block->m_hit_counts.isEmpty() ? 0 : block->m_hit_counts.back());
break;
default:
ASSERT(false);
return QVariant();
}
}
ProfilerUI::ProfilerUI(QWidget* parent)
: QDockWidget(parent)
, m_ui(new Ui::ProfilerUI)
{
m_sortable_model = new QSortFilterProxyModel(this);
m_model = new ProfileModel(this);
m_sortable_model->setSourceModel(m_model);
m_ui->setupUi(this);
m_ui->profileTreeView->setModel(m_sortable_model);
m_ui->profileTreeView->header()->setSectionResizeMode(0, QHeaderView::ResizeMode::Stretch);
m_ui->profileTreeView->header()->setSectionResizeMode(1, QHeaderView::ResizeMode::ResizeToContents);
m_ui->profileTreeView->header()->setSectionResizeMode(2, QHeaderView::ResizeMode::ResizeToContents);
connect(m_model, &QAbstractItemModel::dataChanged, this, &ProfilerUI::on_dataChanged);
connect(m_ui->graphView, &ProfilerGraph::frameSet, this, &ProfilerUI::on_frameSet);
m_ui->graphView->setModel(m_model);
}
void ProfilerUI::on_dataChanged()
{
m_ui->graphView->update();
}
ProfilerUI::~ProfilerUI()
{
delete m_ui;
}
void ProfilerUI::on_recordCheckBox_stateChanged(int)
{
Lumix::g_profiler.toggleRecording();
m_ui->profileTreeView->setModel(NULL);
m_sortable_model->setSourceModel(m_model);
m_ui->profileTreeView->setModel(m_sortable_model);
m_ui->profileTreeView->update();
}
void ProfilerUI::on_frameSet()
{
m_ui->recordCheckBox->setChecked(false);
m_ui->profileTreeView->update();
m_model->setFrame(m_ui->graphView->getFrame());
}
void ProfilerUI::on_profileTreeView_clicked(const QModelIndex &index)
{
if(index.internalPointer() != NULL)
{
m_ui->graphView->setBlock(static_cast<ProfileModel::Block*>(index.internalPointer()));
m_ui->graphView->update();
}
}
<|endoftext|>
|
<commit_before>#ifndef STAN_MATH_REV_FUN_HMM_MARGINAL_LPDF_HPP
#define STAN_MATH_REV_FUN_HMM_MARGINAL_LPDF_HPP
#include <stan/math/prim/meta.hpp>
#include <stan/math/prim/err.hpp>
#include <stan/math/prim/fun/row.hpp>
#include <stan/math/prim/fun/col.hpp>
#include <stan/math/prim/fun/transpose.hpp>
#include <stan/math/prim/fun/exp.hpp>
#include <stan/math/prim/fun/value_of.hpp>
#include <stan/math/prim/core.hpp>
#include <vector>
namespace stan {
namespace math {
template <typename T_omega, typename T_Gamma, typename T_rho, typename T_alpha>
inline auto hmm_marginal_lpdf_val(
const Eigen::Matrix<T_omega, Eigen::Dynamic, Eigen::Dynamic>& omegas,
const Eigen::Matrix<T_Gamma, Eigen::Dynamic, Eigen::Dynamic>& Gamma_val,
const Eigen::Matrix<T_rho, Eigen::Dynamic, 1>& rho_val,
Eigen::Matrix<T_alpha, Eigen::Dynamic, Eigen::Dynamic>& alphas,
Eigen::Matrix<T_alpha, Eigen::Dynamic, 1>& alpha_log_norms) {
const int n_states = omegas.rows();
const int n_transitions = omegas.cols() - 1;
alphas.col(0) = omegas.col(0).cwiseProduct(rho_val);
const auto norm = alphas.col(0).maxCoeff();
alphas.col(0) /= norm;
alpha_log_norms(0) = log(norm);
for (int n = 1; n <= n_transitions; ++n) {
alphas.col(n)
= omegas.col(n).cwiseProduct(Gamma_val.transpose() * alphas.col(n - 1));
const auto col_norm = alphas.col(n).maxCoeff();
alphas.col(n) /= col_norm;
alpha_log_norms(n) = log(col_norm) + alpha_log_norms(n - 1);
}
return log(alphas.col(n_transitions).sum()) + alpha_log_norms(n_transitions);
}
/**
* For a Hidden Markov Model with observation y, hidden state x,
* and parameters theta, return the log marginal density, log
* p(y | theta). In this setting, the hidden states are discrete
* and take values over the finite space {1, ..., K}.
* The marginal lpdf is obtained via a forward pass, and
* the derivative is calculated with an adjoint method,
* e.g (Betancourt, Margossian, & Leos-Barajas, 2020).
* log_omegas is a matrix of observational densities, where
* the (i, j)th entry corresponds to the density of the ith observation, y_i,
* given x_i = j.
* The transition matrix Gamma is such that the (i, j)th entry is the
* probability that x_n = j given x_{n - 1} = i. The rows of Gamma are
* simplexes.
* The Gamma argument is only checked if there is at least one transition.
*
* @tparam T_omega type of the log likelihood matrix
* @tparam T_Gamma type of the transition matrix
* @tparam T_rho type of the initial guess vector
* @param[in] log_omegas log matrix of observational densities.
* @param[in] Gamma transition density between hidden states.
* @param[in] rho initial state
* @return log marginal density.
* @throw `std::invalid_argument` if Gamma is not square, when we have
* at least one transition.
* @throw `std::invalid_argument` if the size of rho is not
* the number of rows of log_omegas.
* @throw `std::domain_error` if rho is not a simplex and of the rows
* of Gamma are not a simplex (when there is at least one transition).
*/
template <typename T_omega, typename T_Gamma, typename T_rho>
inline auto hmm_marginal_lpdf(
const Eigen::Matrix<T_omega, Eigen::Dynamic, Eigen::Dynamic>& log_omegas,
const Eigen::Matrix<T_Gamma, Eigen::Dynamic, Eigen::Dynamic>& Gamma,
const Eigen::Matrix<T_rho, Eigen::Dynamic, 1>& rho) {
using T_partial_type = partials_return_t<T_omega, T_Gamma, T_rho>;
using eig_matrix_partial
= Eigen::Matrix<T_partial_type, Eigen::Dynamic, Eigen::Dynamic>;
using eig_vector_partial = Eigen::Matrix<T_partial_type, Eigen::Dynamic, 1>;
int n_states = log_omegas.rows();
int n_transitions = log_omegas.cols() - 1;
check_consistent_size("hmm_marginal_lpdf", "rho", rho, n_states);
check_simplex("hmm_marginal_lpdf", "rho", rho);
if (n_transitions != 0) {
check_square("hmm_marginal_lpdf", "Gamma", Gamma);
check_nonzero_size("hmm_marginal_lpdf", "Gamma", Gamma);
check_matching_sizes("hmm_marginal_lpdf", "Gamma (row and column)",
Gamma.row(0), "log_omegas (row)", log_omegas.col(0));
for (int i = 0; i < Gamma.rows(); ++i) {
check_simplex("hmm_marginal_lpdf", "Gamma[i, ]", row(Gamma, i + 1));
}
}
operands_and_partials<Eigen::Matrix<T_omega, Eigen::Dynamic, Eigen::Dynamic>,
Eigen::Matrix<T_Gamma, Eigen::Dynamic, Eigen::Dynamic>,
Eigen::Matrix<T_rho, Eigen::Dynamic, 1> >
ops_partials(log_omegas, Gamma, rho);
eig_matrix_partial alphas(n_states, n_transitions + 1);
eig_vector_partial alpha_log_norms(n_transitions + 1);
auto Gamma_val = value_of(Gamma);
// compute the density using the forward algorithm.
auto rho_val = value_of(rho);
eig_matrix_partial omegas = value_of(log_omegas).array().exp();
auto log_marginal_density = hmm_marginal_lpdf_val(omegas, Gamma_val, rho_val,
alphas, alpha_log_norms);
// Variables required for all three Jacobian-adjoint products.
auto norm_norm = alpha_log_norms(n_transitions);
auto unnormed_marginal = alphas.col(n_transitions).sum();
std::vector<eig_vector_partial> kappa(n_transitions);
eig_vector_partial kappa_log_norms(n_transitions);
std::vector<T_partial_type> grad_corr(n_transitions, 0);
if (n_transitions > 0) {
kappa[n_transitions - 1] = Eigen::VectorXd::Ones(n_states);
kappa_log_norms(n_transitions - 1) = 0;
grad_corr[n_transitions - 1]
= exp(alpha_log_norms(n_transitions - 1) - norm_norm);
}
for (int n = n_transitions - 1; n-- > 0;) {
kappa[n] = Gamma_val * (omegas.col(n + 2).cwiseProduct(kappa[n + 1]));
auto norm = kappa[n].maxCoeff();
kappa[n] /= norm;
kappa_log_norms[n] = log(norm) + kappa_log_norms[n + 1];
grad_corr[n] = exp(alpha_log_norms[n] + kappa_log_norms[n] - norm_norm);
}
if (!is_constant_all<T_Gamma>::value) {
eig_matrix_partial Gamma_jacad = Eigen::MatrixXd::Zero(n_states, n_states);
for (int n = n_transitions - 1; n >= 0; --n) {
Gamma_jacad += grad_corr[n] * alphas.col(n)
* kappa[n].cwiseProduct(omegas.col(n + 1)).transpose()
/ unnormed_marginal;
}
ops_partials.edge2_.partials_ = Gamma_jacad;
}
if (!is_constant_all<T_omega, T_rho>::value) {
eig_matrix_partial log_omega_jacad
= Eigen::MatrixXd::Zero(n_states, n_transitions + 1);
if (!is_constant_all<T_omega>::value) {
// auto Gamma_alpha = Gamma_val.transpose() * alphas;
for (int n = n_transitions - 1; n >= 0; --n)
log_omega_jacad.col(n + 1)
= grad_corr[n]
// * kappa[n].cwiseProduct(Gamma_alpha.col(n)).eval();
// * kappa[n].cwiseProduct(Gamma_alpha.col(n));
* kappa[n].cwiseProduct(Gamma_val.transpose() * alphas.col(n));
}
// Boundary terms
if (n_transitions == 0) {
if (!is_constant_all<T_omega>::value) {
log_omega_jacad
= omegas.cwiseProduct(value_of(rho)) / exp(log_marginal_density);
ops_partials.edge1_.partials_ = log_omega_jacad;
}
if (!is_constant_all<T_rho>::value) {
ops_partials.edge3_.partials_
= omegas.col(0) / exp(log_marginal_density);
}
return ops_partials.build(log_marginal_density);
} else {
auto grad_corr_boundary = exp(kappa_log_norms(0) - norm_norm);
eig_vector_partial C = Gamma_val * omegas.col(1).cwiseProduct(kappa[0]);
if (!is_constant_all<T_omega>::value) {
log_omega_jacad.col(0)
= grad_corr_boundary * C.cwiseProduct(value_of(rho));
ops_partials.edge1_.partials_
= log_omega_jacad.cwiseProduct(omegas / unnormed_marginal);
}
if (!is_constant_all<T_rho>::value) {
ops_partials.edge3_.partials_ = grad_corr_boundary
* C.cwiseProduct(omegas.col(0))
/ unnormed_marginal;
}
}
}
return ops_partials.build(log_marginal_density);
}
} // namespace math
} // namespace stan
#endif
<commit_msg>update doc on throw<commit_after>#ifndef STAN_MATH_REV_FUN_HMM_MARGINAL_LPDF_HPP
#define STAN_MATH_REV_FUN_HMM_MARGINAL_LPDF_HPP
#include <stan/math/prim/meta.hpp>
#include <stan/math/prim/err.hpp>
#include <stan/math/prim/fun/row.hpp>
#include <stan/math/prim/fun/col.hpp>
#include <stan/math/prim/fun/transpose.hpp>
#include <stan/math/prim/fun/exp.hpp>
#include <stan/math/prim/fun/value_of.hpp>
#include <stan/math/prim/core.hpp>
#include <vector>
namespace stan {
namespace math {
template <typename T_omega, typename T_Gamma, typename T_rho, typename T_alpha>
inline auto hmm_marginal_lpdf_val(
const Eigen::Matrix<T_omega, Eigen::Dynamic, Eigen::Dynamic>& omegas,
const Eigen::Matrix<T_Gamma, Eigen::Dynamic, Eigen::Dynamic>& Gamma_val,
const Eigen::Matrix<T_rho, Eigen::Dynamic, 1>& rho_val,
Eigen::Matrix<T_alpha, Eigen::Dynamic, Eigen::Dynamic>& alphas,
Eigen::Matrix<T_alpha, Eigen::Dynamic, 1>& alpha_log_norms) {
const int n_states = omegas.rows();
const int n_transitions = omegas.cols() - 1;
alphas.col(0) = omegas.col(0).cwiseProduct(rho_val);
const auto norm = alphas.col(0).maxCoeff();
alphas.col(0) /= norm;
alpha_log_norms(0) = log(norm);
for (int n = 1; n <= n_transitions; ++n) {
alphas.col(n)
= omegas.col(n).cwiseProduct(Gamma_val.transpose() * alphas.col(n - 1));
const auto col_norm = alphas.col(n).maxCoeff();
alphas.col(n) /= col_norm;
alpha_log_norms(n) = log(col_norm) + alpha_log_norms(n - 1);
}
return log(alphas.col(n_transitions).sum()) + alpha_log_norms(n_transitions);
}
/**
* For a Hidden Markov Model with observation y, hidden state x,
* and parameters theta, return the log marginal density, log
* p(y | theta). In this setting, the hidden states are discrete
* and take values over the finite space {1, ..., K}.
* The marginal lpdf is obtained via a forward pass, and
* the derivative is calculated with an adjoint method,
* e.g (Betancourt, Margossian, & Leos-Barajas, 2020).
* log_omegas is a matrix of observational densities, where
* the (i, j)th entry corresponds to the density of the ith observation, y_i,
* given x_i = j.
* The transition matrix Gamma is such that the (i, j)th entry is the
* probability that x_n = j given x_{n - 1} = i. The rows of Gamma are
* simplexes.
* The Gamma argument is only checked if there is at least one transition.
*
* @tparam T_omega type of the log likelihood matrix
* @tparam T_Gamma type of the transition matrix
* @tparam T_rho type of the initial guess vector
* @param[in] log_omegas log matrix of observational densities.
* @param[in] Gamma transition density between hidden states.
* @param[in] rho initial state
* @return log marginal density.
* @throw `std::invalid_argument` if Gamma is not square, when we have
* at least one transition, or if the size of rho is not the
* number of rows of log_omegas.
* @throw `std::domain_error` if rho is not a simplex and of the rows
* of Gamma are not a simplex (when there is at least one transition).
*/
template <typename T_omega, typename T_Gamma, typename T_rho>
inline auto hmm_marginal_lpdf(
const Eigen::Matrix<T_omega, Eigen::Dynamic, Eigen::Dynamic>& log_omegas,
const Eigen::Matrix<T_Gamma, Eigen::Dynamic, Eigen::Dynamic>& Gamma,
const Eigen::Matrix<T_rho, Eigen::Dynamic, 1>& rho) {
using T_partial_type = partials_return_t<T_omega, T_Gamma, T_rho>;
using eig_matrix_partial
= Eigen::Matrix<T_partial_type, Eigen::Dynamic, Eigen::Dynamic>;
using eig_vector_partial = Eigen::Matrix<T_partial_type, Eigen::Dynamic, 1>;
int n_states = log_omegas.rows();
int n_transitions = log_omegas.cols() - 1;
check_consistent_size("hmm_marginal_lpdf", "rho", rho, n_states);
check_simplex("hmm_marginal_lpdf", "rho", rho);
if (n_transitions != 0) {
check_square("hmm_marginal_lpdf", "Gamma", Gamma);
check_nonzero_size("hmm_marginal_lpdf", "Gamma", Gamma);
check_matching_sizes("hmm_marginal_lpdf", "Gamma (row and column)",
Gamma.row(0), "log_omegas (row)", log_omegas.col(0));
for (int i = 0; i < Gamma.rows(); ++i) {
check_simplex("hmm_marginal_lpdf", "Gamma[i, ]", row(Gamma, i + 1));
}
}
operands_and_partials<Eigen::Matrix<T_omega, Eigen::Dynamic, Eigen::Dynamic>,
Eigen::Matrix<T_Gamma, Eigen::Dynamic, Eigen::Dynamic>,
Eigen::Matrix<T_rho, Eigen::Dynamic, 1> >
ops_partials(log_omegas, Gamma, rho);
eig_matrix_partial alphas(n_states, n_transitions + 1);
eig_vector_partial alpha_log_norms(n_transitions + 1);
auto Gamma_val = value_of(Gamma);
// compute the density using the forward algorithm.
auto rho_val = value_of(rho);
eig_matrix_partial omegas = value_of(log_omegas).array().exp();
auto log_marginal_density = hmm_marginal_lpdf_val(omegas, Gamma_val, rho_val,
alphas, alpha_log_norms);
// Variables required for all three Jacobian-adjoint products.
auto norm_norm = alpha_log_norms(n_transitions);
auto unnormed_marginal = alphas.col(n_transitions).sum();
std::vector<eig_vector_partial> kappa(n_transitions);
eig_vector_partial kappa_log_norms(n_transitions);
std::vector<T_partial_type> grad_corr(n_transitions, 0);
if (n_transitions > 0) {
kappa[n_transitions - 1] = Eigen::VectorXd::Ones(n_states);
kappa_log_norms(n_transitions - 1) = 0;
grad_corr[n_transitions - 1]
= exp(alpha_log_norms(n_transitions - 1) - norm_norm);
}
for (int n = n_transitions - 1; n-- > 0;) {
kappa[n] = Gamma_val * (omegas.col(n + 2).cwiseProduct(kappa[n + 1]));
auto norm = kappa[n].maxCoeff();
kappa[n] /= norm;
kappa_log_norms[n] = log(norm) + kappa_log_norms[n + 1];
grad_corr[n] = exp(alpha_log_norms[n] + kappa_log_norms[n] - norm_norm);
}
if (!is_constant_all<T_Gamma>::value) {
eig_matrix_partial Gamma_jacad = Eigen::MatrixXd::Zero(n_states, n_states);
for (int n = n_transitions - 1; n >= 0; --n) {
Gamma_jacad += grad_corr[n] * alphas.col(n)
* kappa[n].cwiseProduct(omegas.col(n + 1)).transpose()
/ unnormed_marginal;
}
ops_partials.edge2_.partials_ = Gamma_jacad;
}
if (!is_constant_all<T_omega, T_rho>::value) {
eig_matrix_partial log_omega_jacad
= Eigen::MatrixXd::Zero(n_states, n_transitions + 1);
if (!is_constant_all<T_omega>::value) {
// auto Gamma_alpha = Gamma_val.transpose() * alphas;
for (int n = n_transitions - 1; n >= 0; --n)
log_omega_jacad.col(n + 1)
= grad_corr[n]
// * kappa[n].cwiseProduct(Gamma_alpha.col(n)).eval();
// * kappa[n].cwiseProduct(Gamma_alpha.col(n));
* kappa[n].cwiseProduct(Gamma_val.transpose() * alphas.col(n));
}
// Boundary terms
if (n_transitions == 0) {
if (!is_constant_all<T_omega>::value) {
log_omega_jacad
= omegas.cwiseProduct(value_of(rho)) / exp(log_marginal_density);
ops_partials.edge1_.partials_ = log_omega_jacad;
}
if (!is_constant_all<T_rho>::value) {
ops_partials.edge3_.partials_
= omegas.col(0) / exp(log_marginal_density);
}
return ops_partials.build(log_marginal_density);
} else {
auto grad_corr_boundary = exp(kappa_log_norms(0) - norm_norm);
eig_vector_partial C = Gamma_val * omegas.col(1).cwiseProduct(kappa[0]);
if (!is_constant_all<T_omega>::value) {
log_omega_jacad.col(0)
= grad_corr_boundary * C.cwiseProduct(value_of(rho));
ops_partials.edge1_.partials_
= log_omega_jacad.cwiseProduct(omegas / unnormed_marginal);
}
if (!is_constant_all<T_rho>::value) {
ops_partials.edge3_.partials_ = grad_corr_boundary
* C.cwiseProduct(omegas.col(0))
/ unnormed_marginal;
}
}
}
return ops_partials.build(log_marginal_density);
}
} // namespace math
} // namespace stan
#endif
<|endoftext|>
|
<commit_before>#ifndef STAN_MATH_REV_FUN_LOG_DETERMINANT_SPD_HPP
#define STAN_MATH_REV_FUN_LOG_DETERMINANT_SPD_HPP
#include <stan/math/rev/meta.hpp>
#include <stan/math/rev/core.hpp>
#include <stan/math/rev/core/typedefs.hpp>
#include <stan/math/prim/err.hpp>
#include <stan/math/prim/fun/Eigen.hpp>
#include <stan/math/prim/fun/log.hpp>
#include <stan/math/prim/fun/sum.hpp>
#include <stan/math/prim/fun/typedefs.hpp>
namespace stan {
namespace math {
/**
* Returns the log det of a symmetric, positive-definite matrix
*
* @tparam T Type is an Eigen Matrix
* @param m a symmetric, positive-definite matrix
* @return The log determinant of the specified matrix
*/
template <typename T, require_rev_matrix_t<T>* = nullptr>
inline var log_determinant_spd(const T& m) {
if (m.size() == 0) {
return var(0.0);
}
check_symmetric("log_determinant", "m", m);
matrix_d m_d = m.val();
arena_t<T> arena_m = m;
auto m_ldlt = arena_m.val().ldlt();
if (m_ldlt.info() != Eigen::Success) {
double y = 0;
throw_domain_error("log_determinant_spd", "matrix argument", y,
"failed LDLT factorization");
}
// compute the inverse of A (needed for the derivative)
m_d.setIdentity(m.rows(), m.cols());
auto arena_m_inv_transpose = to_arena(m_ldlt.solve(m_d).transpose());
if (m_ldlt.isNegative() || (m_ldlt.vectorD().array() <= 1e-16).any()) {
double y = 0;
throw_domain_error("log_determinant_spd", "matrix argument", y,
"matrix is negative definite");
}
var log_det = sum(log(m_ldlt.vectorD()));
reverse_pass_callback([arena_m, log_det, arena_m_inv_transpose]() mutable {
arena_m.adj() += log_det.adj() * arena_m_inv_transpose;
});
return log_det;
}
} // namespace math
} // namespace stan
#endif
<commit_msg>[Jenkins] auto-formatting by clang-format version 10.0.0-4ubuntu1<commit_after>#ifndef STAN_MATH_REV_FUN_LOG_DETERMINANT_SPD_HPP
#define STAN_MATH_REV_FUN_LOG_DETERMINANT_SPD_HPP
#include <stan/math/rev/meta.hpp>
#include <stan/math/rev/core.hpp>
#include <stan/math/rev/core/typedefs.hpp>
#include <stan/math/prim/err.hpp>
#include <stan/math/prim/fun/Eigen.hpp>
#include <stan/math/prim/fun/log.hpp>
#include <stan/math/prim/fun/sum.hpp>
#include <stan/math/prim/fun/typedefs.hpp>
namespace stan {
namespace math {
/**
* Returns the log det of a symmetric, positive-definite matrix
*
* @tparam T Type is an Eigen Matrix
* @param m a symmetric, positive-definite matrix
* @return The log determinant of the specified matrix
*/
template <typename T, require_rev_matrix_t<T>* = nullptr>
inline var log_determinant_spd(const T& m) {
if (m.size() == 0) {
return var(0.0);
}
check_symmetric("log_determinant", "m", m);
matrix_d m_d = m.val();
arena_t<T> arena_m = m;
auto m_ldlt = arena_m.val().ldlt();
if (m_ldlt.info() != Eigen::Success) {
double y = 0;
throw_domain_error("log_determinant_spd", "matrix argument", y,
"failed LDLT factorization");
}
// compute the inverse of A (needed for the derivative)
m_d.setIdentity(m.rows(), m.cols());
auto arena_m_inv_transpose = to_arena(m_ldlt.solve(m_d).transpose());
if (m_ldlt.isNegative() || (m_ldlt.vectorD().array() <= 1e-16).any()) {
double y = 0;
throw_domain_error("log_determinant_spd", "matrix argument", y,
"matrix is negative definite");
}
var log_det = sum(log(m_ldlt.vectorD()));
reverse_pass_callback([arena_m, log_det, arena_m_inv_transpose]() mutable {
arena_m.adj() += log_det.adj() * arena_m_inv_transpose;
});
return log_det;
}
} // namespace math
} // namespace stan
#endif
<|endoftext|>
|
<commit_before>// Copyright 2018 Google LLC
//
// 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 "stratum/hal/lib/common/yang_parse_tree.h"
#include <grpcpp/grpcpp.h>
#include <list>
#include <string>
#include "absl/container/flat_hash_map.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_format.h"
#include "absl/synchronization/mutex.h"
#include "stratum/glue/status/status_macros.h"
#include "stratum/hal/lib/common/gnmi_publisher.h"
#include "stratum/hal/lib/common/yang_parse_tree_paths.h"
namespace stratum {
namespace hal {
TreeNode::TreeNode(const TreeNode& src) {
name_ = src.name_;
// Deep-copy children.
this->CopySubtree(src);
}
void TreeNode::CopySubtree(const TreeNode& src) {
// Copy the handlers.
on_timer_handler_ = src.on_timer_handler_;
on_poll_handler_ = src.on_poll_handler_;
on_change_handler_ = src.on_change_handler_;
on_update_handler_ = src.on_update_handler_;
on_replace_handler_ = src.on_replace_handler_;
on_delete_handler_ = src.on_delete_handler_;
// Set the parent.
parent_ = src.parent_;
// Copy the supported_* flags.
supports_on_timer_ = src.supports_on_timer_;
supports_on_poll_ = src.supports_on_poll_;
supports_on_change_ = src.supports_on_change_;
supports_on_update_ = src.supports_on_update_;
supports_on_replace_ = src.supports_on_replace_;
supports_on_delete_ = src.supports_on_delete_;
// Copy flags.
is_name_a_key_ = src.is_name_a_key_;
// Deep-copy children.
for (const auto& entry : src.children_) {
children_.emplace(entry.first, TreeNode(*this, entry.first));
children_[entry.first].CopySubtree(entry.second);
}
}
::util::Status TreeNode::VisitThisNodeAndItsChildren(
const TreeNodeEventHandlerPtr& handler, const GnmiEvent& event,
const ::gnmi::Path& path, GnmiSubscribeStream* stream) const {
RETURN_IF_ERROR((this->*handler)(event, path, stream));
for (const auto& child : children_) {
RETURN_IF_ERROR(child.second.VisitThisNodeAndItsChildren(
handler, event, child.second.GetPath(), stream));
}
return ::util::OkStatus();
}
::util::Status TreeNode::RegisterThisNodeAndItsChildren(
const EventHandlerRecordPtr& record) const {
RETURN_IF_ERROR(this->on_change_registration_(record));
for (const auto& child : children_) {
RETURN_IF_ERROR(child.second.RegisterThisNodeAndItsChildren(record));
}
return ::util::OkStatus();
}
::gnmi::Path TreeNode::GetPath() const {
std::list<const TreeNode*> elements;
for (const TreeNode* node = this; node != nullptr; node = node->parent_) {
elements.push_front(node);
}
// Remove the first element as it is a fake root and should never apear in the
// path.
if (!elements.empty()) elements.pop_front();
::gnmi::Path path;
::gnmi::PathElem* elem = nullptr;
for (const auto& element : elements) {
if (element->is_name_a_key_) {
if (elem != nullptr) {
(*elem->mutable_key())["name"] = element->name_;
} else {
LOG(ERROR) << "Found a key element without a parent!";
}
} else {
elem = path.add_elem();
elem->set_name(element->name_);
}
}
return path;
}
const TreeNode* TreeNode::FindNodeOrNull(const ::gnmi::Path& path) const {
// Map the input path to the supported one - walk the tree of known elements
// element by element starting from this node and if the element is found the
// move to the next one. If not found, return an error (nullptr).
int element = 0;
const TreeNode* node = this;
for (; node != nullptr && !node->children_.empty() &&
element < path.elem_size();) {
node = gtl::FindOrNull(node->children_, path.elem(element).name());
auto* search = gtl::FindOrNull(path.elem(element).key(), "name");
if (search != nullptr) {
node = gtl::FindOrNull(node->children_, *search);
}
++element;
}
return node;
}
void YangParseTree::SendNotification(const GnmiEventPtr& event) {
absl::WriterMutexLock r(&root_access_lock_);
if (!gnmi_event_writer_) return;
// Pass the event to the gNMI publisher using the gNMI event notification
// channel.
// The GnmiEventPtr is a smart pointer (shared_ptr<>) and it takes care of
// the memory allocated to this event object once the event is handled by
// the GnmiPublisher.
if (!gnmi_event_writer_->Write(event)) {
// Remove WriterInterface if it is no longer operational.
gnmi_event_writer_.reset();
}
}
void YangParseTree::ProcessPushedConfig(
const ConfigHasBeenPushedEvent& change) {
absl::WriterMutexLock r(&root_access_lock_);
// Translation from node ID to an object describing the node.
absl::flat_hash_map<uint64, const Node*> node_id_to_node;
for (const auto& node : change.new_config_.nodes()) {
node_id_to_node[node.id()] = &node;
}
// An empty config to be used when node ID is not defined.
const NodeConfigParams empty_node_config;
// Translation from port ID to node ID.
absl::flat_hash_map<uint32, uint64> port_id_to_node_id;
for (const auto& singleton : change.new_config_.singleton_ports()) {
const NodeConfigParams& node_config =
node_id_to_node[singleton.node()]
? node_id_to_node[singleton.node()]->config_params()
: empty_node_config;
AddSubtreeInterfaceFromSingleton(singleton, node_config);
port_id_to_node_id[singleton.id()] = singleton.node();
}
for (const auto& trunk : change.new_config_.trunk_ports()) {
// Find out on which node the trunk is created.
// TODO(b/70300190): Once TrunkPort message in hal.proto is extended to
// include node_id remove 3 following lines.
constexpr uint64 kNodeIdUnknown = 0xFFFF;
uint64 node_id = trunk.members_size() ? port_id_to_node_id[trunk.members(0)]
: kNodeIdUnknown;
const NodeConfigParams& node_config =
node_id != kNodeIdUnknown ? node_id_to_node[node_id]->config_params()
: empty_node_config;
AddSubtreeInterfaceFromTrunk(trunk.name(), node_id, trunk.id(),
node_config);
}
// Add all chassis-related gNMI paths.
AddSubtreeChassis(change.new_config_.chassis());
// Add all node-related gNMI paths.
for (const auto& node : change.new_config_.nodes()) {
AddSubtreeNode(node);
}
AddRoot();
}
bool YangParseTree::IsWildcard(const std::string& name) const {
if (name.compare("*") == 0) return true;
if (name.compare("...") == 0) return true;
return false;
}
::util::Status YangParseTree::PerformActionForAllNonWildcardNodes(
const gnmi::Path& path, const gnmi::Path& subpath,
const std::function<::util::Status(const TreeNode& leaf)>& action) const {
const auto* root = root_.FindNodeOrNull(path);
::util::Status ret = ::util::OkStatus();
for (const auto& entry : root->children_) {
if (IsWildcard(entry.first)) {
// Skip this one!
continue;
}
auto* leaf = subpath.elem_size() ? entry.second.FindNodeOrNull(subpath)
: &entry.second;
if (leaf == nullptr) {
// Should not happen!
::util::Status status = MAKE_ERROR(ERR_INTERNAL)
<< "Found node without "
<< subpath.ShortDebugString() << " leaf!";
APPEND_STATUS_IF_ERROR(ret, status);
continue;
}
APPEND_STATUS_IF_ERROR(ret, action(*leaf));
}
return ret;
}
YangParseTree::YangParseTree(SwitchInterface* switch_interface)
: switch_interface_(ABSL_DIE_IF_NULL(switch_interface)) {
// Add the minimum nodes:
// /interfaces/interface[name=*]/state/ifindex
// /interfaces/interface[name=*]/state/name
// /interfaces/interface/...
// /
// The rest of nodes will be added once the config is pushed.
absl::WriterMutexLock l(&root_access_lock_);
AddSubtreeAllInterfaces();
AddRoot();
}
TreeNode* YangParseTree::AddNode(const ::gnmi::Path& path) {
// No need to lock the mutex - it is locked by method calling this one.
TreeNode* node = &root_;
for (const auto& element : path.elem()) {
TreeNode* child = gtl::FindOrNull(node->children_, element.name());
if (child == nullptr) {
// This path is not supported yet. Let's add a node with default
// processing.
node->children_.emplace(element.name(), TreeNode(*node, element.name()));
child = gtl::FindOrNull(node->children_, element.name());
}
node = child;
auto* search = gtl::FindOrNull(element.key(), "name");
if (search == nullptr) {
continue;
}
// A filtering pattern has been found!
child = gtl::FindOrNull(node->children_, *search);
if (child == nullptr) {
// This path is not supported yet. Let's add a node with default
// processing.
node->children_.emplace(
*search, TreeNode(*node, *search, true /* mark as a key */));
child = gtl::FindOrNull(node->children_, *search);
}
node = child;
}
return node;
}
::util::Status YangParseTree::CopySubtree(const ::gnmi::Path& from,
const ::gnmi::Path& to) {
// No need to lock the mutex - it is locked by method calling this one.
// Find the source subtree root.
const TreeNode* source = root_.FindNodeOrNull(from);
if (source == nullptr) {
// This path is not defined!
return MAKE_ERROR(ERR_INVALID_PARAM) << "Source path does not exist";
}
// Now 'source' points to the root of the source subtree.
// Set 'dest' to the insertion point of the new subtree.
TreeNode* node = AddNode(to);
// Now 'node' points to the insertion point of the new subtree.
// Deep-copy the source subtree.
node->CopySubtree(*source);
return ::util::OkStatus();
}
const TreeNode* YangParseTree::FindNodeOrNull(const ::gnmi::Path& path) const {
absl::WriterMutexLock l(&root_access_lock_);
// Map the input path to the supported one - walk the tree of known elements
// element by element starting from the root and if the element is found the
// move to the next one. If not found, return an error (nullptr).
return root_.FindNodeOrNull(path);
}
const TreeNode* YangParseTree::GetRoot() const {
absl::WriterMutexLock l(&root_access_lock_);
return &root_;
}
void YangParseTree::AddSubtreeInterfaceFromTrunk(
const std::string& name, uint64 node_id, uint32 port_id,
const NodeConfigParams& node_config) {
YangParseTreePaths::AddSubtreeInterfaceFromTrunk(name, node_id, port_id,
node_config, this);
}
void YangParseTree::AddSubtreeInterfaceFromSingleton(
const SingletonPort& singleton, const NodeConfigParams& node_config) {
YangParseTreePaths::AddSubtreeInterfaceFromSingleton(singleton, node_config,
this);
}
void YangParseTree::AddSubtreeNode(const Node& node) {
YangParseTreePaths::AddSubtreeNode(node, this);
}
void YangParseTree::AddSubtreeChassis(const Chassis& chassis) {
YangParseTreePaths::AddSubtreeChassis(chassis, this);
}
void YangParseTree::AddSubtreeAllInterfaces() {
// No need to lock the mutex - it is locked by method calling this one.
// Add all nodes defined in YangParseTreePaths class.
YangParseTreePaths::AddSubtreeAllInterfaces(this);
}
void YangParseTree::AddRoot() {
// No need to lock the mutex - it is locked by method calling this one.
// Add root element
YangParseTreePaths::AddRoot(this);
}
} // namespace hal
} // namespace stratum
<commit_msg>Fix null pointer exception<commit_after>// Copyright 2018 Google LLC
//
// 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 "stratum/hal/lib/common/yang_parse_tree.h"
#include <grpcpp/grpcpp.h>
#include <list>
#include <string>
#include "absl/container/flat_hash_map.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_format.h"
#include "absl/synchronization/mutex.h"
#include "stratum/glue/status/status_macros.h"
#include "stratum/hal/lib/common/gnmi_publisher.h"
#include "stratum/hal/lib/common/yang_parse_tree_paths.h"
namespace stratum {
namespace hal {
TreeNode::TreeNode(const TreeNode& src) {
name_ = src.name_;
// Deep-copy children.
this->CopySubtree(src);
}
void TreeNode::CopySubtree(const TreeNode& src) {
// Copy the handlers.
on_timer_handler_ = src.on_timer_handler_;
on_poll_handler_ = src.on_poll_handler_;
on_change_handler_ = src.on_change_handler_;
on_update_handler_ = src.on_update_handler_;
on_replace_handler_ = src.on_replace_handler_;
on_delete_handler_ = src.on_delete_handler_;
// Set the parent.
parent_ = src.parent_;
// Copy the supported_* flags.
supports_on_timer_ = src.supports_on_timer_;
supports_on_poll_ = src.supports_on_poll_;
supports_on_change_ = src.supports_on_change_;
supports_on_update_ = src.supports_on_update_;
supports_on_replace_ = src.supports_on_replace_;
supports_on_delete_ = src.supports_on_delete_;
// Copy flags.
is_name_a_key_ = src.is_name_a_key_;
// Deep-copy children.
for (const auto& entry : src.children_) {
children_.emplace(entry.first, TreeNode(*this, entry.first));
children_[entry.first].CopySubtree(entry.second);
}
}
::util::Status TreeNode::VisitThisNodeAndItsChildren(
const TreeNodeEventHandlerPtr& handler, const GnmiEvent& event,
const ::gnmi::Path& path, GnmiSubscribeStream* stream) const {
RETURN_IF_ERROR((this->*handler)(event, path, stream));
for (const auto& child : children_) {
RETURN_IF_ERROR(child.second.VisitThisNodeAndItsChildren(
handler, event, child.second.GetPath(), stream));
}
return ::util::OkStatus();
}
::util::Status TreeNode::RegisterThisNodeAndItsChildren(
const EventHandlerRecordPtr& record) const {
RETURN_IF_ERROR(this->on_change_registration_(record));
for (const auto& child : children_) {
RETURN_IF_ERROR(child.second.RegisterThisNodeAndItsChildren(record));
}
return ::util::OkStatus();
}
::gnmi::Path TreeNode::GetPath() const {
std::list<const TreeNode*> elements;
for (const TreeNode* node = this; node != nullptr; node = node->parent_) {
elements.push_front(node);
}
// Remove the first element as it is a fake root and should never apear in the
// path.
if (!elements.empty()) elements.pop_front();
::gnmi::Path path;
::gnmi::PathElem* elem = nullptr;
for (const auto& element : elements) {
if (element->is_name_a_key_) {
if (elem != nullptr) {
(*elem->mutable_key())["name"] = element->name_;
} else {
LOG(ERROR) << "Found a key element without a parent!";
}
} else {
elem = path.add_elem();
elem->set_name(element->name_);
}
}
return path;
}
const TreeNode* TreeNode::FindNodeOrNull(const ::gnmi::Path& path) const {
// Map the input path to the supported one - walk the tree of known elements
// element by element starting from this node and if the element is found the
// move to the next one. If not found, return an error (nullptr).
int element = 0;
const TreeNode* node = this;
for (; node != nullptr && !node->children_.empty() &&
element < path.elem_size();) {
node = gtl::FindOrNull(node->children_, path.elem(element).name());
auto* search = gtl::FindOrNull(path.elem(element).key(), "name");
if (search != nullptr && node != nullptr) {
node = gtl::FindOrNull(node->children_, *search);
}
++element;
}
return node;
}
void YangParseTree::SendNotification(const GnmiEventPtr& event) {
absl::WriterMutexLock r(&root_access_lock_);
if (!gnmi_event_writer_) return;
// Pass the event to the gNMI publisher using the gNMI event notification
// channel.
// The GnmiEventPtr is a smart pointer (shared_ptr<>) and it takes care of
// the memory allocated to this event object once the event is handled by
// the GnmiPublisher.
if (!gnmi_event_writer_->Write(event)) {
// Remove WriterInterface if it is no longer operational.
gnmi_event_writer_.reset();
}
}
void YangParseTree::ProcessPushedConfig(
const ConfigHasBeenPushedEvent& change) {
absl::WriterMutexLock r(&root_access_lock_);
// Translation from node ID to an object describing the node.
absl::flat_hash_map<uint64, const Node*> node_id_to_node;
for (const auto& node : change.new_config_.nodes()) {
node_id_to_node[node.id()] = &node;
}
// An empty config to be used when node ID is not defined.
const NodeConfigParams empty_node_config;
// Translation from port ID to node ID.
absl::flat_hash_map<uint32, uint64> port_id_to_node_id;
for (const auto& singleton : change.new_config_.singleton_ports()) {
const NodeConfigParams& node_config =
node_id_to_node[singleton.node()]
? node_id_to_node[singleton.node()]->config_params()
: empty_node_config;
AddSubtreeInterfaceFromSingleton(singleton, node_config);
port_id_to_node_id[singleton.id()] = singleton.node();
}
for (const auto& trunk : change.new_config_.trunk_ports()) {
// Find out on which node the trunk is created.
// TODO(b/70300190): Once TrunkPort message in hal.proto is extended to
// include node_id remove 3 following lines.
constexpr uint64 kNodeIdUnknown = 0xFFFF;
uint64 node_id = trunk.members_size() ? port_id_to_node_id[trunk.members(0)]
: kNodeIdUnknown;
const NodeConfigParams& node_config =
node_id != kNodeIdUnknown ? node_id_to_node[node_id]->config_params()
: empty_node_config;
AddSubtreeInterfaceFromTrunk(trunk.name(), node_id, trunk.id(),
node_config);
}
// Add all chassis-related gNMI paths.
AddSubtreeChassis(change.new_config_.chassis());
// Add all node-related gNMI paths.
for (const auto& node : change.new_config_.nodes()) {
AddSubtreeNode(node);
}
AddRoot();
}
bool YangParseTree::IsWildcard(const std::string& name) const {
if (name.compare("*") == 0) return true;
if (name.compare("...") == 0) return true;
return false;
}
::util::Status YangParseTree::PerformActionForAllNonWildcardNodes(
const gnmi::Path& path, const gnmi::Path& subpath,
const std::function<::util::Status(const TreeNode& leaf)>& action) const {
const auto* root = root_.FindNodeOrNull(path);
::util::Status ret = ::util::OkStatus();
for (const auto& entry : root->children_) {
if (IsWildcard(entry.first)) {
// Skip this one!
continue;
}
auto* leaf = subpath.elem_size() ? entry.second.FindNodeOrNull(subpath)
: &entry.second;
if (leaf == nullptr) {
// Should not happen!
::util::Status status = MAKE_ERROR(ERR_INTERNAL)
<< "Found node without "
<< subpath.ShortDebugString() << " leaf!";
APPEND_STATUS_IF_ERROR(ret, status);
continue;
}
APPEND_STATUS_IF_ERROR(ret, action(*leaf));
}
return ret;
}
YangParseTree::YangParseTree(SwitchInterface* switch_interface)
: switch_interface_(ABSL_DIE_IF_NULL(switch_interface)) {
// Add the minimum nodes:
// /interfaces/interface[name=*]/state/ifindex
// /interfaces/interface[name=*]/state/name
// /interfaces/interface/...
// /
// The rest of nodes will be added once the config is pushed.
absl::WriterMutexLock l(&root_access_lock_);
AddSubtreeAllInterfaces();
AddRoot();
}
TreeNode* YangParseTree::AddNode(const ::gnmi::Path& path) {
// No need to lock the mutex - it is locked by method calling this one.
TreeNode* node = &root_;
for (const auto& element : path.elem()) {
TreeNode* child = gtl::FindOrNull(node->children_, element.name());
if (child == nullptr) {
// This path is not supported yet. Let's add a node with default
// processing.
node->children_.emplace(element.name(), TreeNode(*node, element.name()));
child = gtl::FindOrNull(node->children_, element.name());
}
node = child;
auto* search = gtl::FindOrNull(element.key(), "name");
if (search == nullptr) {
continue;
}
// A filtering pattern has been found!
child = gtl::FindOrNull(node->children_, *search);
if (child == nullptr) {
// This path is not supported yet. Let's add a node with default
// processing.
node->children_.emplace(
*search, TreeNode(*node, *search, true /* mark as a key */));
child = gtl::FindOrNull(node->children_, *search);
}
node = child;
}
return node;
}
::util::Status YangParseTree::CopySubtree(const ::gnmi::Path& from,
const ::gnmi::Path& to) {
// No need to lock the mutex - it is locked by method calling this one.
// Find the source subtree root.
const TreeNode* source = root_.FindNodeOrNull(from);
if (source == nullptr) {
// This path is not defined!
return MAKE_ERROR(ERR_INVALID_PARAM) << "Source path does not exist";
}
// Now 'source' points to the root of the source subtree.
// Set 'dest' to the insertion point of the new subtree.
TreeNode* node = AddNode(to);
// Now 'node' points to the insertion point of the new subtree.
// Deep-copy the source subtree.
node->CopySubtree(*source);
return ::util::OkStatus();
}
const TreeNode* YangParseTree::FindNodeOrNull(const ::gnmi::Path& path) const {
absl::WriterMutexLock l(&root_access_lock_);
// Map the input path to the supported one - walk the tree of known elements
// element by element starting from the root and if the element is found the
// move to the next one. If not found, return an error (nullptr).
return root_.FindNodeOrNull(path);
}
const TreeNode* YangParseTree::GetRoot() const {
absl::WriterMutexLock l(&root_access_lock_);
return &root_;
}
void YangParseTree::AddSubtreeInterfaceFromTrunk(
const std::string& name, uint64 node_id, uint32 port_id,
const NodeConfigParams& node_config) {
YangParseTreePaths::AddSubtreeInterfaceFromTrunk(name, node_id, port_id,
node_config, this);
}
void YangParseTree::AddSubtreeInterfaceFromSingleton(
const SingletonPort& singleton, const NodeConfigParams& node_config) {
YangParseTreePaths::AddSubtreeInterfaceFromSingleton(singleton, node_config,
this);
}
void YangParseTree::AddSubtreeNode(const Node& node) {
YangParseTreePaths::AddSubtreeNode(node, this);
}
void YangParseTree::AddSubtreeChassis(const Chassis& chassis) {
YangParseTreePaths::AddSubtreeChassis(chassis, this);
}
void YangParseTree::AddSubtreeAllInterfaces() {
// No need to lock the mutex - it is locked by method calling this one.
// Add all nodes defined in YangParseTreePaths class.
YangParseTreePaths::AddSubtreeAllInterfaces(this);
}
void YangParseTree::AddRoot() {
// No need to lock the mutex - it is locked by method calling this one.
// Add root element
YangParseTreePaths::AddRoot(this);
}
} // namespace hal
} // namespace stratum
<|endoftext|>
|
<commit_before>/*
The MIT License (MIT)
Copyright (c) [2016] [BTC.COM]
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 "StratumServerGrin.h"
#include "StratumSessionGrin.h"
#include "CommonGrin.h"
#include <boost/make_unique.hpp>
#include <algorithm>
unique_ptr<StratumSession> StratumServerGrin::createConnection(
struct bufferevent *bev,
struct sockaddr *saddr,
uint32_t sessionID) {
return boost::make_unique<StratumSessionGrin>(*this, bev, saddr, sessionID);
}
void StratumServerGrin::checkAndUpdateShare(
size_t chainId,
ShareGrin &share,
shared_ptr<StratumJobEx> exjob,
const vector<uint64_t > &proofs,
const std::set<uint64_t> &jobDiffs,
const string &workFullName,
uint256 &blockHash) {
auto sjob = dynamic_cast<StratumJobGrin *>(exjob->sjob_);
DLOG(INFO) << "checking share nonce: " << std::hex << share.nonce()
<< ", pre_pow: " << sjob->prePowStr_
<< ", edge_bits: " << share.edgebits();
if (exjob->isStale()) {
share.set_status(StratumStatus::JOB_NOT_FOUND);
return;
}
PreProofGrin preProof;
preProof.prePow = sjob->prePow_;
preProof.nonce = share.nonce();
if (!VerifyPowGrin(preProof, share.edgebits(), proofs)) {
share.set_status(StratumStatus::INVALID_SOLUTION);
return;
}
blockHash = PowHashGrin(share.height(), share.edgebits(), preProof.prePow.secondaryScaling.value(), proofs);
share.set_hashprefix(blockHash.GetCheapHash());
uint64_t scaledShareDiff = PowDifficultyGrin(share.height(), share.edgebits(), preProof.prePow.secondaryScaling.value(), proofs);
DLOG(INFO) << "compare share difficulty: " << scaledShareDiff << ", network difficulty: " << sjob->difficulty_;
// print out high diff share
if (scaledShareDiff / sjob->difficulty_ >= 1024) {
LOG(INFO) << "high diff share, share difficulty: " << scaledShareDiff << ", network difficulty: " << sjob->difficulty_
<< ", worker: " << workFullName;
}
if (isSubmitInvalidBlock_ || scaledShareDiff >= sjob->difficulty_) {
LOG(INFO) << "solution found, share difficulty: " << scaledShareDiff << ", network difficulty: " << sjob->difficulty_
<< ", worker: " << workFullName;
share.set_status(StratumStatus::SOLVED);
LOG(INFO) << "solved share: " << share.toString();
return;
}
// higher difficulty is prior
for (auto itr = jobDiffs.rbegin(); itr != jobDiffs.rend(); itr++) {
uint64_t jobDiff = *itr;
uint64_t scaledJobDiff = jobDiff * share.scaling();
DLOG(INFO) << "compare share difficulty: " << scaledShareDiff << ", job difficulty: " << scaledJobDiff;
if (isEnableSimulator_ || scaledShareDiff >= scaledJobDiff) {
share.set_sharediff(jobDiff);
share.set_status(StratumStatus::ACCEPT);
return;
}
}
share.set_status(StratumStatus::LOW_DIFFICULTY);
return;
}
void StratumServerGrin::sendSolvedShare2Kafka(
size_t chainId,
const ShareGrin &share,
shared_ptr<StratumJobEx> exjob,
const vector<uint64_t> &proofs,
const StratumWorker &worker,
const uint256 &blockHash) {
string proofArray;
if (!proofs.empty()) {
proofArray = std::accumulate(
std::next(proofs.begin()),
proofs.end(),
std::to_string(proofs.front()),
[](string a, int b) { return std::move(a) + "," + std::to_string(b); });
}
auto sjob = dynamic_cast<StratumJobGrin *>(exjob->sjob_);
string msg = Strings::Format(
"{\"prePow\":\"%s\""
",\"height\":%" PRIu64
",\"edgeBits\":%" PRIu32
",\"nonce\":%" PRIu64
",\"proofs\":[%s]"
",\"userId\":%" PRId32
",\"workerId\":%" PRId64
",\"workerFullName\":\"%s\""
",\"blockHash\":\"%s\""
"}",
sjob->prePowStr_.c_str(),
sjob->height_,
share.edgebits(),
share.nonce(),
proofArray.c_str(),
worker.userId_,
worker.workerHashId_,
filterWorkerName(worker.fullName_).c_str(),
blockHash.GetHex().c_str());
ServerBase::sendSolvedShare2Kafka(chainId, msg.c_str(), msg.length());
}
JobRepository* StratumServerGrin::createJobRepository(
size_t chainId,
const char *kafkaBrokers,
const char *consumerTopic,
const string &fileLastNotifyTime) {
return new JobRepositoryGrin{chainId, this, kafkaBrokers, consumerTopic, fileLastNotifyTime};
}
JobRepositoryGrin::JobRepositoryGrin(
size_t chainId,
StratumServerGrin *server,
const char *kafkaBrokers,
const char *consumerTopic,
const string &fileLastNotifyTime)
: JobRepositoryBase{chainId, server, kafkaBrokers, consumerTopic, fileLastNotifyTime}
, lastHeight_{0} {
}
StratumJob* JobRepositoryGrin::createStratumJob() {
return new StratumJobGrin;
}
void JobRepositoryGrin::broadcastStratumJob(StratumJob *sjob) {
auto sjobGrin = dynamic_cast<StratumJobGrin*>(sjob);
LOG(INFO) << "broadcast stratum job " << std::hex << sjobGrin->jobId_;
bool isClean = false;
if (sjobGrin->height_ != lastHeight_) {
isClean = true;
lastHeight_ = sjobGrin->height_;
LOG(INFO) << "received new height stratum job, height: " << sjobGrin->height_
<< ", prePow: " << sjobGrin->prePowStr_;
}
shared_ptr<StratumJobEx> exJob{createStratumJobEx(sjobGrin, isClean)};
{
ScopeLock sl(lock_);
if (isClean) {
// mark all jobs as stale, should do this before insert new job
// stale shares will not be rejected, they will be marked as ACCEPT_STALE and have lower rewards.
for (auto it : exJobs_) {
it.second->markStale();
}
}
// insert new job
exJobs_[sjobGrin->jobId_] = exJob;
}
//send job
sendMiningNotify(exJob);
}
<commit_msg>Grin fix block hash order in found blocks<commit_after>/*
The MIT License (MIT)
Copyright (c) [2016] [BTC.COM]
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 "StratumServerGrin.h"
#include "StratumSessionGrin.h"
#include "CommonGrin.h"
#include <boost/make_unique.hpp>
#include <algorithm>
unique_ptr<StratumSession> StratumServerGrin::createConnection(
struct bufferevent *bev,
struct sockaddr *saddr,
uint32_t sessionID) {
return boost::make_unique<StratumSessionGrin>(*this, bev, saddr, sessionID);
}
void StratumServerGrin::checkAndUpdateShare(
size_t chainId,
ShareGrin &share,
shared_ptr<StratumJobEx> exjob,
const vector<uint64_t > &proofs,
const std::set<uint64_t> &jobDiffs,
const string &workFullName,
uint256 &blockHash) {
auto sjob = dynamic_cast<StratumJobGrin *>(exjob->sjob_);
DLOG(INFO) << "checking share nonce: " << std::hex << share.nonce()
<< ", pre_pow: " << sjob->prePowStr_
<< ", edge_bits: " << share.edgebits();
if (exjob->isStale()) {
share.set_status(StratumStatus::JOB_NOT_FOUND);
return;
}
PreProofGrin preProof;
preProof.prePow = sjob->prePow_;
preProof.nonce = share.nonce();
if (!VerifyPowGrin(preProof, share.edgebits(), proofs)) {
share.set_status(StratumStatus::INVALID_SOLUTION);
return;
}
blockHash = PowHashGrin(share.height(), share.edgebits(), preProof.prePow.secondaryScaling.value(), proofs);
share.set_hashprefix(blockHash.GetCheapHash());
uint64_t scaledShareDiff = PowDifficultyGrin(share.height(), share.edgebits(), preProof.prePow.secondaryScaling.value(), proofs);
DLOG(INFO) << "compare share difficulty: " << scaledShareDiff << ", network difficulty: " << sjob->difficulty_;
// print out high diff share
if (scaledShareDiff / sjob->difficulty_ >= 1024) {
LOG(INFO) << "high diff share, share difficulty: " << scaledShareDiff << ", network difficulty: " << sjob->difficulty_
<< ", worker: " << workFullName;
}
if (isSubmitInvalidBlock_ || scaledShareDiff >= sjob->difficulty_) {
LOG(INFO) << "solution found, share difficulty: " << scaledShareDiff << ", network difficulty: " << sjob->difficulty_
<< ", worker: " << workFullName;
share.set_status(StratumStatus::SOLVED);
LOG(INFO) << "solved share: " << share.toString();
return;
}
// higher difficulty is prior
for (auto itr = jobDiffs.rbegin(); itr != jobDiffs.rend(); itr++) {
uint64_t jobDiff = *itr;
uint64_t scaledJobDiff = jobDiff * share.scaling();
DLOG(INFO) << "compare share difficulty: " << scaledShareDiff << ", job difficulty: " << scaledJobDiff;
if (isEnableSimulator_ || scaledShareDiff >= scaledJobDiff) {
share.set_sharediff(jobDiff);
share.set_status(StratumStatus::ACCEPT);
return;
}
}
share.set_status(StratumStatus::LOW_DIFFICULTY);
return;
}
void StratumServerGrin::sendSolvedShare2Kafka(
size_t chainId,
const ShareGrin &share,
shared_ptr<StratumJobEx> exjob,
const vector<uint64_t> &proofs,
const StratumWorker &worker,
const uint256 &blockHash) {
string proofArray;
if (!proofs.empty()) {
proofArray = std::accumulate(
std::next(proofs.begin()),
proofs.end(),
std::to_string(proofs.front()),
[](string a, int b) { return std::move(a) + "," + std::to_string(b); });
}
auto sjob = dynamic_cast<StratumJobGrin *>(exjob->sjob_);
string blockHashStr;
Bin2Hex(blockHash.begin(), blockHash.size(), blockHashStr);
string msg = Strings::Format(
"{\"prePow\":\"%s\""
",\"height\":%" PRIu64
",\"edgeBits\":%" PRIu32
",\"nonce\":%" PRIu64
",\"proofs\":[%s]"
",\"userId\":%" PRId32
",\"workerId\":%" PRId64
",\"workerFullName\":\"%s\""
",\"blockHash\":\"%s\""
"}",
sjob->prePowStr_.c_str(),
sjob->height_,
share.edgebits(),
share.nonce(),
proofArray.c_str(),
worker.userId_,
worker.workerHashId_,
filterWorkerName(worker.fullName_).c_str(),
blockHashStr.c_str());
ServerBase::sendSolvedShare2Kafka(chainId, msg.c_str(), msg.length());
}
JobRepository* StratumServerGrin::createJobRepository(
size_t chainId,
const char *kafkaBrokers,
const char *consumerTopic,
const string &fileLastNotifyTime) {
return new JobRepositoryGrin{chainId, this, kafkaBrokers, consumerTopic, fileLastNotifyTime};
}
JobRepositoryGrin::JobRepositoryGrin(
size_t chainId,
StratumServerGrin *server,
const char *kafkaBrokers,
const char *consumerTopic,
const string &fileLastNotifyTime)
: JobRepositoryBase{chainId, server, kafkaBrokers, consumerTopic, fileLastNotifyTime}
, lastHeight_{0} {
}
StratumJob* JobRepositoryGrin::createStratumJob() {
return new StratumJobGrin;
}
void JobRepositoryGrin::broadcastStratumJob(StratumJob *sjob) {
auto sjobGrin = dynamic_cast<StratumJobGrin*>(sjob);
LOG(INFO) << "broadcast stratum job " << std::hex << sjobGrin->jobId_;
bool isClean = false;
if (sjobGrin->height_ != lastHeight_) {
isClean = true;
lastHeight_ = sjobGrin->height_;
LOG(INFO) << "received new height stratum job, height: " << sjobGrin->height_
<< ", prePow: " << sjobGrin->prePowStr_;
}
shared_ptr<StratumJobEx> exJob{createStratumJobEx(sjobGrin, isClean)};
{
ScopeLock sl(lock_);
if (isClean) {
// mark all jobs as stale, should do this before insert new job
// stale shares will not be rejected, they will be marked as ACCEPT_STALE and have lower rewards.
for (auto it : exJobs_) {
it.second->markStale();
}
}
// insert new job
exJobs_[sjobGrin->jobId_] = exJob;
}
//send job
sendMiningNotify(exJob);
}
<|endoftext|>
|
<commit_before>// Copyright 2009 The RE2 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 "util/test.h"
#include "re2/filtered_re2.h"
#include "re2/re2.h"
DECLARE_int32(filtered_re2_min_atom_len); // From prefilter_tree.cc
namespace re2 {
struct FilterTestVars {
vector<string> atoms;
vector<int> atom_indices;
vector<int> matches;
RE2::Options opts;
FilteredRE2 f;
};
TEST(FilteredRE2Test, EmptyTest) {
FilterTestVars v;
v.f.AllMatches("foo", v.atom_indices, &v.matches);
EXPECT_EQ(0, v.matches.size());
}
TEST(FilteredRE2Test, SmallOrTest) {
FLAGS_filtered_re2_min_atom_len = 4;
FilterTestVars v;
int id;
v.f.Add("(foo|bar)", v.opts, &id);
v.f.Compile(&v.atoms);
EXPECT_EQ(0, v.atoms.size());
v.f.AllMatches("lemurs bar", v.atom_indices, &v.matches);
EXPECT_EQ(1, v.matches.size());
EXPECT_EQ(id, v.matches[0]);
}
TEST(FilteredRE2Test, SmallLatinTest) {
FLAGS_filtered_re2_min_atom_len = 3;
FilterTestVars v;
int id;
v.opts.set_utf8(false);
v.f.Add("\xde\xadQ\xbe\xef", v.opts, &id);
v.f.Compile(&v.atoms);
EXPECT_EQ(1, v.atoms.size());
EXPECT_EQ(v.atoms[0], "\xde\xadq\xbe\xef");
v.atom_indices.push_back(0);
v.f.AllMatches("foo\xde\xadQ\xbe\xeflemur", v.atom_indices, &v.matches);
EXPECT_EQ(1, v.matches.size());
EXPECT_EQ(id, v.matches[0]);
}
struct AtomTest {
const char* testname;
// If any test needs more than this many regexps or atoms, increase
// the size of the corresponding array.
const char* regexps[20];
const char* atoms[20];
};
AtomTest atom_tests[] = {
{
// This test checks to make sure empty patterns are allowed.
"CheckEmptyPattern",
{""},
{}
}, {
// This test checks that all atoms of length greater than min length
// are found, and no atoms that are of smaller length are found.
"AllAtomsGtMinLengthFound", {
"(abc123|def456|ghi789).*mnop[x-z]+",
"abc..yyy..zz",
"mnmnpp[a-z]+PPP"
}, {
"abc123",
"def456",
"ghi789",
"mnop",
"abc",
"yyy",
"mnmnpp",
"ppp"
}
}, {
// Test to make sure that any atoms that have another atom as a
// substring in an OR are removed; that is, only the shortest
// substring is kept.
"SubstrAtomRemovesSuperStrInOr", {
"(abc123|abc|ghi789|abc1234).*[x-z]+",
"abcd..yyy..yyyzzz",
"mnmnpp[a-z]+PPP"
}, {
"abc",
"ghi789",
"abcd",
"yyy",
"yyyzzz",
"mnmnpp",
"ppp"
}
}, {
// Test character class expansion.
"CharClassExpansion", {
"m[a-c][d-f]n.*[x-z]+",
"[x-y]bcde[ab]"
}, {
"madn", "maen", "mafn",
"mbdn", "mben", "mbfn",
"mcdn", "mcen", "mcfn",
"xbcdea", "xbcdeb",
"ybcdea", "ybcdeb"
}
}, {
// Test upper/lower of non-ASCII.
"UnicodeLower", {
"(?i)ΔδΠϖπΣςσ",
"ΛΜΝΟΠ",
"ψρστυ",
}, {
"δδπππσσσ",
"λμνοπ",
"ψρστυ",
},
},
};
void AddRegexpsAndCompile(const char* regexps[],
int n,
struct FilterTestVars* v) {
for (int i = 0; i < n; i++) {
int id;
v->f.Add(regexps[i], v->opts, &id);
}
v->f.Compile(&v->atoms);
}
bool CheckExpectedAtoms(const char* atoms[],
int n,
const char* testname,
struct FilterTestVars* v) {
vector<string> expected;
for (int i = 0; i < n; i++)
expected.push_back(atoms[i]);
bool pass = expected.size() == v->atoms.size();
sort(v->atoms.begin(), v->atoms.end());
sort(expected.begin(), expected.end());
for (int i = 0; pass && i < n; i++)
pass = pass && expected[i] == v->atoms[i];
if (!pass) {
LOG(WARNING) << "Failed " << testname;
LOG(WARNING) << "Expected #atoms = " << expected.size();
for (size_t i = 0; i < expected.size(); i++)
LOG(WARNING) << expected[i];
LOG(WARNING) << "Found #atoms = " << v->atoms.size();
for (size_t i = 0; i < v->atoms.size(); i++)
LOG(WARNING) << v->atoms[i];
}
return pass;
}
TEST(FilteredRE2Test, AtomTests) {
FLAGS_filtered_re2_min_atom_len = 3;
int nfail = 0;
for (int i = 0; i < arraysize(atom_tests); i++) {
FilterTestVars v;
AtomTest* t = &atom_tests[i];
int natom, nregexp;
for (nregexp = 0; nregexp < arraysize(t->regexps); nregexp++)
if (t->regexps[nregexp] == NULL)
break;
for (natom = 0; natom < arraysize(t->atoms); natom++)
if (t->atoms[natom] == NULL)
break;
AddRegexpsAndCompile(t->regexps, nregexp, &v);
if (!CheckExpectedAtoms(t->atoms, natom, t->testname, &v))
nfail++;
}
EXPECT_EQ(0, nfail);
}
void FindAtomIndices(const vector<string> atoms,
const vector<string> matched_atoms,
vector<int>* atom_indices) {
atom_indices->clear();
for (size_t i = 0; i < matched_atoms.size(); i++) {
size_t j = 0;
for (; j < atoms.size(); j++) {
if (matched_atoms[i] == atoms[j]) {
atom_indices->push_back(j);
break;
}
EXPECT_LT(j, atoms.size());
}
}
}
TEST(FilteredRE2Test, MatchEmptyPattern) {
FLAGS_filtered_re2_min_atom_len = 3;
FilterTestVars v;
AtomTest* t = &atom_tests[0];
// We are using the regexps used in one of the atom tests
// for this test. Adding the EXPECT here to make sure
// the index we use for the test is for the correct test.
EXPECT_EQ("CheckEmptyPattern", string(t->testname));
int nregexp;
for (nregexp = 0; nregexp < arraysize(t->regexps); nregexp++)
if (t->regexps[nregexp] == NULL)
break;
AddRegexpsAndCompile(t->regexps, nregexp, &v);
string text = "0123";
vector<int> atom_ids;
vector<int> matching_regexps;
EXPECT_EQ(0, v.f.FirstMatch(text, atom_ids));
}
TEST(FilteredRE2Test, MatchTests) {
FLAGS_filtered_re2_min_atom_len = 3;
FilterTestVars v;
AtomTest* t = &atom_tests[2];
// We are using the regexps used in one of the atom tests
// for this test.
EXPECT_EQ("SubstrAtomRemovesSuperStrInOr", string(t->testname));
int nregexp;
for (nregexp = 0; nregexp < arraysize(t->regexps); nregexp++)
if (t->regexps[nregexp] == NULL)
break;
AddRegexpsAndCompile(t->regexps, nregexp, &v);
string text = "abc121212xyz";
// atoms = abc
vector<int> atom_ids;
vector<string> atoms;
atoms.push_back("abc");
FindAtomIndices(v.atoms, atoms, &atom_ids);
vector<int> matching_regexps;
v.f.AllMatches(text, atom_ids, &matching_regexps);
EXPECT_EQ(1, matching_regexps.size());
text = "abc12312yyyzzz";
atoms.clear();
atoms.push_back("abc");
atoms.push_back("yyy");
atoms.push_back("yyyzzz");
FindAtomIndices(v.atoms, atoms, &atom_ids);
v.f.AllMatches(text, atom_ids, &matching_regexps);
EXPECT_EQ(1, matching_regexps.size());
text = "abcd12yyy32yyyzzz";
atoms.clear();
atoms.push_back("abc");
atoms.push_back("abcd");
atoms.push_back("yyy");
atoms.push_back("yyyzzz");
FindAtomIndices(v.atoms, atoms, &atom_ids);
LOG(INFO) << "S: " << atom_ids.size();
for (size_t i = 0; i < atom_ids.size(); i++)
LOG(INFO) << "i: " << i << " : " << atom_ids[i];
v.f.AllMatches(text, atom_ids, &matching_regexps);
EXPECT_EQ(2, matching_regexps.size());
}
} // namespace re2
<commit_msg>Cleanup: Call set_encoding() instead of set_utf8() in filtered_re2 test.<commit_after>// Copyright 2009 The RE2 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 "util/test.h"
#include "re2/filtered_re2.h"
#include "re2/re2.h"
DECLARE_int32(filtered_re2_min_atom_len); // From prefilter_tree.cc
namespace re2 {
struct FilterTestVars {
vector<string> atoms;
vector<int> atom_indices;
vector<int> matches;
RE2::Options opts;
FilteredRE2 f;
};
TEST(FilteredRE2Test, EmptyTest) {
FilterTestVars v;
v.f.AllMatches("foo", v.atom_indices, &v.matches);
EXPECT_EQ(0, v.matches.size());
}
TEST(FilteredRE2Test, SmallOrTest) {
FLAGS_filtered_re2_min_atom_len = 4;
FilterTestVars v;
int id;
v.f.Add("(foo|bar)", v.opts, &id);
v.f.Compile(&v.atoms);
EXPECT_EQ(0, v.atoms.size());
v.f.AllMatches("lemurs bar", v.atom_indices, &v.matches);
EXPECT_EQ(1, v.matches.size());
EXPECT_EQ(id, v.matches[0]);
}
TEST(FilteredRE2Test, SmallLatinTest) {
FLAGS_filtered_re2_min_atom_len = 3;
FilterTestVars v;
int id;
v.opts.set_encoding(RE2::Options::EncodingLatin1);
v.f.Add("\xde\xadQ\xbe\xef", v.opts, &id);
v.f.Compile(&v.atoms);
EXPECT_EQ(1, v.atoms.size());
EXPECT_EQ(v.atoms[0], "\xde\xadq\xbe\xef");
v.atom_indices.push_back(0);
v.f.AllMatches("foo\xde\xadQ\xbe\xeflemur", v.atom_indices, &v.matches);
EXPECT_EQ(1, v.matches.size());
EXPECT_EQ(id, v.matches[0]);
}
struct AtomTest {
const char* testname;
// If any test needs more than this many regexps or atoms, increase
// the size of the corresponding array.
const char* regexps[20];
const char* atoms[20];
};
AtomTest atom_tests[] = {
{
// This test checks to make sure empty patterns are allowed.
"CheckEmptyPattern",
{""},
{}
}, {
// This test checks that all atoms of length greater than min length
// are found, and no atoms that are of smaller length are found.
"AllAtomsGtMinLengthFound", {
"(abc123|def456|ghi789).*mnop[x-z]+",
"abc..yyy..zz",
"mnmnpp[a-z]+PPP"
}, {
"abc123",
"def456",
"ghi789",
"mnop",
"abc",
"yyy",
"mnmnpp",
"ppp"
}
}, {
// Test to make sure that any atoms that have another atom as a
// substring in an OR are removed; that is, only the shortest
// substring is kept.
"SubstrAtomRemovesSuperStrInOr", {
"(abc123|abc|ghi789|abc1234).*[x-z]+",
"abcd..yyy..yyyzzz",
"mnmnpp[a-z]+PPP"
}, {
"abc",
"ghi789",
"abcd",
"yyy",
"yyyzzz",
"mnmnpp",
"ppp"
}
}, {
// Test character class expansion.
"CharClassExpansion", {
"m[a-c][d-f]n.*[x-z]+",
"[x-y]bcde[ab]"
}, {
"madn", "maen", "mafn",
"mbdn", "mben", "mbfn",
"mcdn", "mcen", "mcfn",
"xbcdea", "xbcdeb",
"ybcdea", "ybcdeb"
}
}, {
// Test upper/lower of non-ASCII.
"UnicodeLower", {
"(?i)ΔδΠϖπΣςσ",
"ΛΜΝΟΠ",
"ψρστυ",
}, {
"δδπππσσσ",
"λμνοπ",
"ψρστυ",
},
},
};
void AddRegexpsAndCompile(const char* regexps[],
int n,
struct FilterTestVars* v) {
for (int i = 0; i < n; i++) {
int id;
v->f.Add(regexps[i], v->opts, &id);
}
v->f.Compile(&v->atoms);
}
bool CheckExpectedAtoms(const char* atoms[],
int n,
const char* testname,
struct FilterTestVars* v) {
vector<string> expected;
for (int i = 0; i < n; i++)
expected.push_back(atoms[i]);
bool pass = expected.size() == v->atoms.size();
sort(v->atoms.begin(), v->atoms.end());
sort(expected.begin(), expected.end());
for (int i = 0; pass && i < n; i++)
pass = pass && expected[i] == v->atoms[i];
if (!pass) {
LOG(WARNING) << "Failed " << testname;
LOG(WARNING) << "Expected #atoms = " << expected.size();
for (size_t i = 0; i < expected.size(); i++)
LOG(WARNING) << expected[i];
LOG(WARNING) << "Found #atoms = " << v->atoms.size();
for (size_t i = 0; i < v->atoms.size(); i++)
LOG(WARNING) << v->atoms[i];
}
return pass;
}
TEST(FilteredRE2Test, AtomTests) {
FLAGS_filtered_re2_min_atom_len = 3;
int nfail = 0;
for (int i = 0; i < arraysize(atom_tests); i++) {
FilterTestVars v;
AtomTest* t = &atom_tests[i];
int natom, nregexp;
for (nregexp = 0; nregexp < arraysize(t->regexps); nregexp++)
if (t->regexps[nregexp] == NULL)
break;
for (natom = 0; natom < arraysize(t->atoms); natom++)
if (t->atoms[natom] == NULL)
break;
AddRegexpsAndCompile(t->regexps, nregexp, &v);
if (!CheckExpectedAtoms(t->atoms, natom, t->testname, &v))
nfail++;
}
EXPECT_EQ(0, nfail);
}
void FindAtomIndices(const vector<string> atoms,
const vector<string> matched_atoms,
vector<int>* atom_indices) {
atom_indices->clear();
for (size_t i = 0; i < matched_atoms.size(); i++) {
size_t j = 0;
for (; j < atoms.size(); j++) {
if (matched_atoms[i] == atoms[j]) {
atom_indices->push_back(j);
break;
}
EXPECT_LT(j, atoms.size());
}
}
}
TEST(FilteredRE2Test, MatchEmptyPattern) {
FLAGS_filtered_re2_min_atom_len = 3;
FilterTestVars v;
AtomTest* t = &atom_tests[0];
// We are using the regexps used in one of the atom tests
// for this test. Adding the EXPECT here to make sure
// the index we use for the test is for the correct test.
EXPECT_EQ("CheckEmptyPattern", string(t->testname));
int nregexp;
for (nregexp = 0; nregexp < arraysize(t->regexps); nregexp++)
if (t->regexps[nregexp] == NULL)
break;
AddRegexpsAndCompile(t->regexps, nregexp, &v);
string text = "0123";
vector<int> atom_ids;
vector<int> matching_regexps;
EXPECT_EQ(0, v.f.FirstMatch(text, atom_ids));
}
TEST(FilteredRE2Test, MatchTests) {
FLAGS_filtered_re2_min_atom_len = 3;
FilterTestVars v;
AtomTest* t = &atom_tests[2];
// We are using the regexps used in one of the atom tests
// for this test.
EXPECT_EQ("SubstrAtomRemovesSuperStrInOr", string(t->testname));
int nregexp;
for (nregexp = 0; nregexp < arraysize(t->regexps); nregexp++)
if (t->regexps[nregexp] == NULL)
break;
AddRegexpsAndCompile(t->regexps, nregexp, &v);
string text = "abc121212xyz";
// atoms = abc
vector<int> atom_ids;
vector<string> atoms;
atoms.push_back("abc");
FindAtomIndices(v.atoms, atoms, &atom_ids);
vector<int> matching_regexps;
v.f.AllMatches(text, atom_ids, &matching_regexps);
EXPECT_EQ(1, matching_regexps.size());
text = "abc12312yyyzzz";
atoms.clear();
atoms.push_back("abc");
atoms.push_back("yyy");
atoms.push_back("yyyzzz");
FindAtomIndices(v.atoms, atoms, &atom_ids);
v.f.AllMatches(text, atom_ids, &matching_regexps);
EXPECT_EQ(1, matching_regexps.size());
text = "abcd12yyy32yyyzzz";
atoms.clear();
atoms.push_back("abc");
atoms.push_back("abcd");
atoms.push_back("yyy");
atoms.push_back("yyyzzz");
FindAtomIndices(v.atoms, atoms, &atom_ids);
LOG(INFO) << "S: " << atom_ids.size();
for (size_t i = 0; i < atom_ids.size(); i++)
LOG(INFO) << "i: " << i << " : " << atom_ids[i];
v.f.AllMatches(text, atom_ids, &matching_regexps);
EXPECT_EQ(2, matching_regexps.size());
}
} // namespace re2
<|endoftext|>
|
<commit_before>// Scintilla source code edit control
/** @file LexCSS.cxx
** Lexer for Cascade Style Sheets
** Written by Jakub Vrna
**/
// Copyright 1998-2002 by Neil Hodgson <[email protected]>
// The License.txt file describes the conditions under which this software may be distributed.
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdio.h>
#include <stdarg.h>
#include "Platform.h"
#include "PropSet.h"
#include "Accessor.h"
#include "StyleContext.h"
#include "KeyWords.h"
#include "Scintilla.h"
#include "SciLexer.h"
static inline bool IsAWordChar(const unsigned int ch) {
return (isalnum(ch) || ch == '-' || ch == '_' || ch >= 161); // _ is not in fact correct CSS word-character
}
inline bool IsCssOperator(const char ch) {
if (!isalnum(ch) && (ch == '{' || ch == '}' || ch == ':' || ch == ',' || ch == ';' || ch == '.' || ch == '#' || ch == '!' || ch == '@'))
return true;
return false;
}
static void ColouriseCssDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[], Accessor &styler) {
WordList &keywords = *keywordlists[0];
WordList &pseudoClasses = *keywordlists[1];
StyleContext sc(startPos, length, initStyle, styler);
int lastState = -1; // before operator
int lastStateC = -1; // before comment
int op = ' '; // last operator
for (; sc.More(); sc.Forward()) {
if (sc.state == SCE_CSS_COMMENT && sc.Match('*', '/')) {
if (lastStateC == -1) {
// backtrack to get last state
unsigned int i = startPos;
for (; i > 0; i--) {
if ((lastStateC = styler.StyleAt(i-1)) != SCE_CSS_COMMENT) {
if (lastStateC == SCE_CSS_OPERATOR) {
op = styler.SafeGetCharAt(i-1);
while (--i) {
lastState = styler.StyleAt(i-1);
if (lastState != SCE_CSS_OPERATOR && lastState != SCE_CSS_COMMENT)
break;
}
if (i == 0)
lastState = SCE_CSS_DEFAULT;
}
break;
}
}
if (i == 0)
lastStateC = SCE_CSS_DEFAULT;
}
sc.Forward();
sc.ForwardSetState(lastStateC);
}
if (sc.state == SCE_CSS_COMMENT)
continue;
if (sc.state == SCE_CSS_DOUBLESTRING || sc.state == SCE_CSS_SINGLESTRING) {
if (sc.ch != (sc.state == SCE_CSS_DOUBLESTRING ? '\"' : '\''))
continue;
unsigned int i = sc.currentPos;
while (i && styler[i-1] == '\\')
i--;
if ((sc.currentPos - i) % 2 == 1)
continue;
sc.ForwardSetState(SCE_CSS_VALUE);
}
if (sc.state == SCE_CSS_OPERATOR) {
if (op == ' ') {
unsigned int i = startPos;
op = styler.SafeGetCharAt(i-1);
while (--i) {
lastState = styler.StyleAt(i-1);
if (lastState != SCE_CSS_OPERATOR && lastState != SCE_CSS_COMMENT)
break;
}
}
switch (op) {
case '@':
if (lastState == SCE_CSS_DEFAULT)
sc.SetState(SCE_CSS_DIRECTIVE);
break;
case '{':
if (lastState == SCE_CSS_DIRECTIVE)
sc.SetState(SCE_CSS_DEFAULT);
else if (lastState == SCE_CSS_TAG)
sc.SetState(SCE_CSS_IDENTIFIER);
break;
case '}':
if (lastState == SCE_CSS_DEFAULT || lastState == SCE_CSS_VALUE || lastState == SCE_CSS_IMPORTANT || lastState == SCE_CSS_IDENTIFIER)
sc.SetState(SCE_CSS_DEFAULT);
break;
case ':':
if (lastState == SCE_CSS_TAG || lastState == SCE_CSS_PSEUDOCLASS || lastState == SCE_CSS_DEFAULT ||
lastState == SCE_CSS_CLASS || lastState == SCE_CSS_ID || lastState == SCE_CSS_UNKNOWN_PSEUDOCLASS)
sc.SetState(SCE_CSS_PSEUDOCLASS);
else if (lastState == SCE_CSS_IDENTIFIER || lastState == SCE_CSS_UNKNOWN_IDENTIFIER)
sc.SetState(SCE_CSS_VALUE);
break;
case '.':
if (lastState == SCE_CSS_TAG || lastState == SCE_CSS_DEFAULT)
sc.SetState(SCE_CSS_CLASS);
break;
case '#':
if (lastState == SCE_CSS_TAG || lastState == SCE_CSS_DEFAULT)
sc.SetState(SCE_CSS_ID);
break;
case ',':
if (lastState == SCE_CSS_TAG)
sc.SetState(SCE_CSS_DEFAULT);
break;
case ';':
if (lastState == SCE_CSS_DIRECTIVE)
sc.SetState(SCE_CSS_DEFAULT);
else if (lastState == SCE_CSS_VALUE || lastState == SCE_CSS_IMPORTANT)
sc.SetState(SCE_CSS_IDENTIFIER);
break;
case '!':
if (lastState == SCE_CSS_VALUE)
sc.SetState(SCE_CSS_IMPORTANT);
break;
}
}
if (IsAWordChar(sc.ch)) {
if (sc.state == SCE_CSS_DEFAULT)
sc.SetState(SCE_CSS_TAG);
continue;
}
if (IsAWordChar(sc.chPrev) && (
sc.state == SCE_CSS_IDENTIFIER || sc.state == SCE_CSS_UNKNOWN_IDENTIFIER
|| sc.state == SCE_CSS_PSEUDOCLASS || sc.state == SCE_CSS_UNKNOWN_PSEUDOCLASS
|| sc.state == SCE_CSS_IMPORTANT
)) {
char s[100];
sc.GetCurrentLowered(s, sizeof(s));
char *s2 = s;
while (*s2 && !IsAWordChar(*s2))
s2++;
switch (sc.state) {
case SCE_CSS_IDENTIFIER:
if (!keywords.InList(s2))
sc.ChangeState(SCE_CSS_UNKNOWN_IDENTIFIER);
break;
case SCE_CSS_UNKNOWN_IDENTIFIER:
if (keywords.InList(s2))
sc.ChangeState(SCE_CSS_IDENTIFIER);
break;
case SCE_CSS_PSEUDOCLASS:
if (!pseudoClasses.InList(s2))
sc.ChangeState(SCE_CSS_UNKNOWN_PSEUDOCLASS);
break;
case SCE_CSS_UNKNOWN_PSEUDOCLASS:
if (pseudoClasses.InList(s2))
sc.ChangeState(SCE_CSS_PSEUDOCLASS);
break;
case SCE_CSS_IMPORTANT:
if (strcmp(s2, "important") != 0)
sc.ChangeState(SCE_CSS_VALUE);
break;
}
}
if (sc.ch != '.' && sc.ch != ':' && sc.ch != '#' && (sc.state == SCE_CSS_CLASS || sc.state == SCE_CSS_PSEUDOCLASS || sc.state == SCE_CSS_UNKNOWN_PSEUDOCLASS || sc.state == SCE_CSS_ID))
sc.SetState(SCE_CSS_TAG);
if (sc.Match('/', '*')) {
lastStateC = sc.state;
sc.SetState(SCE_CSS_COMMENT);
sc.Forward();
} else if (sc.state == SCE_CSS_VALUE && (sc.ch == '\"' || sc.ch == '\'')) {
sc.SetState((sc.ch == '\"' ? SCE_CSS_DOUBLESTRING : SCE_CSS_SINGLESTRING));
} else if (IsCssOperator(static_cast<char>(sc.ch))
&& (sc.state != SCE_CSS_VALUE || sc.ch == ';' || sc.ch == '}' || sc.ch == '!')
&& (sc.state != SCE_CSS_DIRECTIVE || sc.ch == ';' || sc.ch == '{')
) {
if (sc.state != SCE_CSS_OPERATOR)
lastState = sc.state;
sc.SetState(SCE_CSS_OPERATOR);
op = sc.ch;
}
}
sc.Complete();
}
static void FoldCSSDoc(unsigned int startPos, int length, int, WordList *[], Accessor &styler) {
bool foldComment = styler.GetPropertyInt("fold.comment") != 0;
bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0;
unsigned int endPos = startPos + length;
int visibleChars = 0;
int lineCurrent = styler.GetLine(startPos);
int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK;
int levelCurrent = levelPrev;
char chNext = styler[startPos];
bool inComment = (styler.StyleAt(startPos-1) == SCE_CSS_COMMENT);
for (unsigned int i = startPos; i < endPos; i++) {
char ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
int style = styler.StyleAt(i);
bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n');
if (foldComment) {
if (!inComment && (style == SCE_CSS_COMMENT))
levelCurrent++;
else if (inComment && (style != SCE_CSS_COMMENT))
levelCurrent--;
inComment = (style == SCE_CSS_COMMENT);
}
if (style == SCE_CSS_OPERATOR) {
if (ch == '{') {
levelCurrent++;
} else if (ch == '}') {
levelCurrent--;
}
}
if (atEOL) {
int lev = levelPrev;
if (visibleChars == 0 && foldCompact)
lev |= SC_FOLDLEVELWHITEFLAG;
if ((levelCurrent > levelPrev) && (visibleChars > 0))
lev |= SC_FOLDLEVELHEADERFLAG;
if (lev != styler.LevelAt(lineCurrent)) {
styler.SetLevel(lineCurrent, lev);
}
lineCurrent++;
levelPrev = levelCurrent;
visibleChars = 0;
}
if (!isspacechar(ch))
visibleChars++;
}
// Fill in the real level of the next line, keeping the current flags as they will be filled in later
int flagsNext = styler.LevelAt(lineCurrent) & ~SC_FOLDLEVELNUMBERMASK;
styler.SetLevel(lineCurrent, levelPrev | flagsNext);
}
static const char * const cssWordListDesc[] = {
"Keywords",
"Pseudo classes",
0
};
LexerModule lmCss(SCLEX_CSS, ColouriseCssDoc, "css", FoldCSSDoc, cssWordListDesc);
<commit_msg>Update from Philippe with some support for CSS 2.<commit_after>// Scintilla source code edit control
/** @file LexCSS.cxx
** Lexer for Cascading Style Sheets
** Written by Jakub Vrna
**/
// Copyright 1998-2002 by Neil Hodgson <[email protected]>
// The License.txt file describes the conditions under which this software may be distributed.
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdio.h>
#include <stdarg.h>
#include "Platform.h"
#include "PropSet.h"
#include "Accessor.h"
#include "StyleContext.h"
#include "KeyWords.h"
#include "Scintilla.h"
#include "SciLexer.h"
static inline bool IsAWordChar(const unsigned int ch) {
return (isalnum(ch) || ch == '-' || ch == '_' || ch >= 161); // _ is not in fact correct CSS word-character
}
inline bool IsCssOperator(const char ch) {
if (!isalnum(ch) &&
(ch == '{' || ch == '}' || ch == ':' || ch == ',' || ch == ';' ||
ch == '.' || ch == '#' || ch == '!' || ch == '@' ||
/* CSS2 */
ch == '*' || ch == '>' || ch == '+' || ch == '=' || ch == '~' || ch == '|' ||
ch == '[' || ch == ']' || ch == '(' || ch == ')')) {
return true;
}
return false;
}
static void ColouriseCssDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[], Accessor &styler) {
WordList &keywords = *keywordlists[0];
WordList &pseudoClasses = *keywordlists[1];
WordList &keywords2 = *keywordlists[2];
StyleContext sc(startPos, length, initStyle, styler);
int lastState = -1; // before operator
int lastStateC = -1; // before comment
int op = ' '; // last operator
for (; sc.More(); sc.Forward()) {
if (sc.state == SCE_CSS_COMMENT && sc.Match('*', '/')) {
if (lastStateC == -1) {
// backtrack to get last state:
// comments are like whitespace, so we must return to the previous state
unsigned int i = startPos;
for (; i > 0; i--) {
if ((lastStateC = styler.StyleAt(i-1)) != SCE_CSS_COMMENT) {
if (lastStateC == SCE_CSS_OPERATOR) {
op = styler.SafeGetCharAt(i-1);
while (--i) {
lastState = styler.StyleAt(i-1);
if (lastState != SCE_CSS_OPERATOR && lastState != SCE_CSS_COMMENT)
break;
}
if (i == 0)
lastState = SCE_CSS_DEFAULT;
}
break;
}
}
if (i == 0)
lastStateC = SCE_CSS_DEFAULT;
}
sc.Forward();
sc.ForwardSetState(lastStateC);
}
if (sc.state == SCE_CSS_COMMENT)
continue;
if (sc.state == SCE_CSS_DOUBLESTRING || sc.state == SCE_CSS_SINGLESTRING) {
if (sc.ch != (sc.state == SCE_CSS_DOUBLESTRING ? '\"' : '\''))
continue;
unsigned int i = sc.currentPos;
while (i && styler[i-1] == '\\')
i--;
if ((sc.currentPos - i) % 2 == 1)
continue;
sc.ForwardSetState(SCE_CSS_VALUE);
}
if (sc.state == SCE_CSS_OPERATOR) {
if (op == ' ') {
unsigned int i = startPos;
op = styler.SafeGetCharAt(i-1);
while (--i) {
lastState = styler.StyleAt(i-1);
if (lastState != SCE_CSS_OPERATOR && lastState != SCE_CSS_COMMENT)
break;
}
}
switch (op) {
case '@':
if (lastState == SCE_CSS_DEFAULT)
sc.SetState(SCE_CSS_DIRECTIVE);
break;
case '{':
if (lastState == SCE_CSS_DIRECTIVE)
sc.SetState(SCE_CSS_DEFAULT);
else if (lastState == SCE_CSS_TAG)
sc.SetState(SCE_CSS_IDENTIFIER);
break;
case '}':
if (lastState == SCE_CSS_DEFAULT || lastState == SCE_CSS_VALUE || lastState == SCE_CSS_IMPORTANT || lastState == SCE_CSS_IDENTIFIER)
sc.SetState(SCE_CSS_DEFAULT);
break;
case ':':
if (lastState == SCE_CSS_TAG || lastState == SCE_CSS_PSEUDOCLASS || lastState == SCE_CSS_DEFAULT ||
lastState == SCE_CSS_CLASS || lastState == SCE_CSS_ID || lastState == SCE_CSS_UNKNOWN_PSEUDOCLASS)
sc.SetState(SCE_CSS_PSEUDOCLASS);
else if (lastState == SCE_CSS_IDENTIFIER || lastState == SCE_CSS_UNKNOWN_IDENTIFIER)
sc.SetState(SCE_CSS_VALUE);
break;
case '.':
if (lastState == SCE_CSS_TAG || lastState == SCE_CSS_DEFAULT)
sc.SetState(SCE_CSS_CLASS);
break;
case '#':
if (lastState == SCE_CSS_TAG || lastState == SCE_CSS_DEFAULT)
sc.SetState(SCE_CSS_ID);
break;
case ',':
if (lastState == SCE_CSS_TAG)
sc.SetState(SCE_CSS_DEFAULT);
break;
case ';':
if (lastState == SCE_CSS_DIRECTIVE)
sc.SetState(SCE_CSS_DEFAULT);
else if (lastState == SCE_CSS_VALUE || lastState == SCE_CSS_IMPORTANT)
sc.SetState(SCE_CSS_IDENTIFIER);
break;
case '!':
if (lastState == SCE_CSS_VALUE)
sc.SetState(SCE_CSS_IMPORTANT);
break;
}
}
if (IsAWordChar(sc.ch)) {
if (sc.state == SCE_CSS_DEFAULT)
sc.SetState(SCE_CSS_TAG);
continue;
}
if (IsAWordChar(sc.chPrev) && (
sc.state == SCE_CSS_IDENTIFIER || sc.state == SCE_CSS_UNKNOWN_IDENTIFIER
|| sc.state == SCE_CSS_PSEUDOCLASS || sc.state == SCE_CSS_UNKNOWN_PSEUDOCLASS
|| sc.state == SCE_CSS_IMPORTANT
)) {
char s[100];
sc.GetCurrentLowered(s, sizeof(s));
char *s2 = s;
while (*s2 && !IsAWordChar(*s2))
s2++;
switch (sc.state) {
case SCE_CSS_IDENTIFIER:
if (!keywords.InList(s2) && !keywords2.InList(s2))
sc.ChangeState(SCE_CSS_UNKNOWN_IDENTIFIER);
break;
case SCE_CSS_UNKNOWN_IDENTIFIER:
if (keywords.InList(s2))
sc.ChangeState(SCE_CSS_IDENTIFIER);
break;
case SCE_CSS_PSEUDOCLASS:
if (!pseudoClasses.InList(s2))
sc.ChangeState(SCE_CSS_UNKNOWN_PSEUDOCLASS);
break;
case SCE_CSS_UNKNOWN_PSEUDOCLASS:
if (pseudoClasses.InList(s2))
sc.ChangeState(SCE_CSS_PSEUDOCLASS);
break;
case SCE_CSS_IMPORTANT:
if (strcmp(s2, "important") != 0)
sc.ChangeState(SCE_CSS_VALUE);
break;
}
}
if (sc.ch != '.' && sc.ch != ':' && sc.ch != '#' && (sc.state == SCE_CSS_CLASS || sc.state == SCE_CSS_PSEUDOCLASS || sc.state == SCE_CSS_UNKNOWN_PSEUDOCLASS || sc.state == SCE_CSS_ID))
sc.SetState(SCE_CSS_TAG);
if (sc.Match('/', '*')) {
lastStateC = sc.state;
sc.SetState(SCE_CSS_COMMENT);
sc.Forward();
} else if (sc.state == SCE_CSS_VALUE && (sc.ch == '\"' || sc.ch == '\'')) {
sc.SetState((sc.ch == '\"' ? SCE_CSS_DOUBLESTRING : SCE_CSS_SINGLESTRING));
} else if (IsCssOperator(static_cast<char>(sc.ch))
&& (sc.state != SCE_CSS_VALUE || sc.ch == ';' || sc.ch == '}' || sc.ch == '!')
&& (sc.state != SCE_CSS_DIRECTIVE || sc.ch == ';' || sc.ch == '{')
) {
if (sc.state != SCE_CSS_OPERATOR)
lastState = sc.state;
sc.SetState(SCE_CSS_OPERATOR);
op = sc.ch;
}
}
sc.Complete();
}
static void FoldCSSDoc(unsigned int startPos, int length, int, WordList *[], Accessor &styler) {
bool foldComment = styler.GetPropertyInt("fold.comment") != 0;
bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0;
unsigned int endPos = startPos + length;
int visibleChars = 0;
int lineCurrent = styler.GetLine(startPos);
int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK;
int levelCurrent = levelPrev;
char chNext = styler[startPos];
bool inComment = (styler.StyleAt(startPos-1) == SCE_CSS_COMMENT);
for (unsigned int i = startPos; i < endPos; i++) {
char ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
int style = styler.StyleAt(i);
bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n');
if (foldComment) {
if (!inComment && (style == SCE_CSS_COMMENT))
levelCurrent++;
else if (inComment && (style != SCE_CSS_COMMENT))
levelCurrent--;
inComment = (style == SCE_CSS_COMMENT);
}
if (style == SCE_CSS_OPERATOR) {
if (ch == '{') {
levelCurrent++;
} else if (ch == '}') {
levelCurrent--;
}
}
if (atEOL) {
int lev = levelPrev;
if (visibleChars == 0 && foldCompact)
lev |= SC_FOLDLEVELWHITEFLAG;
if ((levelCurrent > levelPrev) && (visibleChars > 0))
lev |= SC_FOLDLEVELHEADERFLAG;
if (lev != styler.LevelAt(lineCurrent)) {
styler.SetLevel(lineCurrent, lev);
}
lineCurrent++;
levelPrev = levelCurrent;
visibleChars = 0;
}
if (!isspacechar(ch))
visibleChars++;
}
// Fill in the real level of the next line, keeping the current flags as they will be filled in later
int flagsNext = styler.LevelAt(lineCurrent) & ~SC_FOLDLEVELNUMBERMASK;
styler.SetLevel(lineCurrent, levelPrev | flagsNext);
}
static const char * const cssWordListDesc[] = {
"Keywords",
"Pseudo classes",
0
};
LexerModule lmCss(SCLEX_CSS, ColouriseCssDoc, "css", FoldCSSDoc, cssWordListDesc);
<|endoftext|>
|
<commit_before>#include <jni.h>
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <locale.h>
#include <mpv/client.h>
#include <mpv/opengl_cb.h>
#include <EGL/egl.h>
#include "main.h"
#define ARRAYLEN(a) (sizeof(a)/sizeof(a[0]))
#define jfunc(name, type) JNIEXPORT type JNICALL Java_is_xyz_mpv_MPVLib_##name
#define jvoidfunc(name) jfunc(name, void)
extern "C" {
jvoidfunc(init) (JNIEnv* env, jobject obj);
jvoidfunc(command) (JNIEnv* env, jobject obj, jobjectArray jarray);
jvoidfunc(resize) (JNIEnv* env, jobject obj, jint width, jint height);
jvoidfunc(step) (JNIEnv* env, jobject obj);
jvoidfunc(play) (JNIEnv *env, jobject obj);
jvoidfunc(pause) (JNIEnv *env, jobject obj);
jvoidfunc(touch_1down) (JNIEnv* env, jobject obj, jint x, jint y);
jvoidfunc(touch_1move) (JNIEnv* env, jobject obj, jint x, jint y);
jvoidfunc(touch_1up) (JNIEnv* env, jobject obj, jint x, jint y);
jvoidfunc(setconfigdir) (JNIEnv* env, jobject obj, jstring path);
jfunc(getpropertyint, jint) (JNIEnv *env, jobject obj, jstring property);
jvoidfunc(setpropertyint) (JNIEnv *env, jobject obj, jstring property, jint value);
};
mpv_handle *mpv;
mpv_opengl_cb_context *mpv_gl;
int g_width, g_height;
char g_config_dir[2048];
char **g_command_queue[16] = {NULL};
static void die(const char *msg)
{
ALOGE("%s", msg);
exit(1);
}
static void *get_proc_address_mpv(void *fn_ctx, const char *name)
{
return (void*)eglGetProcAddress(name);
}
static int cq_push(char **e)
{
for (int i = 0; i < ARRAYLEN(g_command_queue); i++) {
if (g_command_queue[i] != NULL)
continue;
g_command_queue[i] = e;
return 0;
}
return -1;
}
static void cq_free(char **e)
{
for (int i = 0; e[i] != NULL; i++)
free(e[i]);
free(e);
}
jvoidfunc(init) (JNIEnv* env, jobject obj) {
if (mpv)
return;
setlocale(LC_NUMERIC, "C");
mpv = mpv_create();
if (!mpv)
die("context init failed");
int osc = 1;
mpv_set_option(mpv, "osc", MPV_FORMAT_FLAG, &osc);
mpv_set_option_string(mpv, "script-opts", "osc-scalewindowed=1.5");
mpv_set_option_string(mpv, "config", "yes");
mpv_set_option_string(mpv, "config-dir", g_config_dir);
mpv_request_log_messages(mpv, "v");
if (mpv_initialize(mpv) < 0)
die("mpv init failed");
mpv_gl = (mpv_opengl_cb_context*)mpv_get_sub_api(mpv, MPV_SUB_API_OPENGL_CB);
if (!mpv_gl)
die("failed to create mpv GL API handle");
if (mpv_opengl_cb_init_gl(mpv_gl, NULL, get_proc_address_mpv, NULL) < 0)
die("failed to initialize mpv GL context");
if (mpv_set_option_string(mpv, "vo", "opengl-cb") < 0)
die("failed to set VO");
if (mpv_set_option_string(mpv, "ao", "openal") < 0)
die("failed to set AO");
for (int i = 0; i < ARRAYLEN(g_command_queue); i++) {
if (g_command_queue[i] == NULL)
break;
char **cmd = g_command_queue[i];
mpv_command(mpv, (const char**) cmd);
cq_free(cmd);
}
}
#define CHKVALID() if (!mpv) return;
jvoidfunc(command) (JNIEnv* env, jobject obj, jobjectArray jarray) {
char **command;
int jarray_l = env->GetArrayLength(jarray);
command = (char**) malloc(sizeof(char*) * (jarray_l+1));
if (!command)
return;
for (int i = 0; i < jarray_l; i++) {
jstring jstr = (jstring) env->GetObjectArrayElement(jarray, i);
const char *str = env->GetStringUTFChars(jstr, NULL);
command[i] = strdup(str);
env->ReleaseStringUTFChars(jstr, str);
}
command[jarray_l] = NULL;
if (mpv) {
mpv_command(mpv, (const char**) command);
cq_free(command);
return;
}
if(cq_push(command) < 0) {
ALOGE("command queue full");
cq_free(command);
}
}
static void mouse_pos(int x, int y) {
char sx[5], sy[5];
const char *cmd[] = {"mouse", sx, sy, NULL};
snprintf(sx, sizeof(sx), "%d", x);
snprintf(sy, sizeof(sy), "%d", y);
mpv_command(mpv, cmd);
}
static void mouse_trigger(int down, int btn) {
// "mouse" doesn't actually send keydown events so we need to do it manually
char k[16];
const char *cmd[] = {down?"keydown":"keyup", k, NULL};
snprintf(k, sizeof(k), "MOUSE_BTN%d", btn);
mpv_command(mpv, cmd);
}
jvoidfunc(touch_1down) (JNIEnv* env, jobject obj, jint x, jint y) {
CHKVALID();
mouse_pos(x, y);
mouse_trigger(1, 0);
}
jvoidfunc(touch_1move) (JNIEnv* env, jobject obj, jint x, jint y) {
CHKVALID();
mouse_pos(x, y);
}
jvoidfunc(touch_1up) (JNIEnv* env, jobject obj, jint x, jint y) {
CHKVALID();
mouse_trigger(0, 0);
// move the cursor to the top left corner where it doesn't trigger the OSC
// FIXME: this causes the OSC to receive a mouse_btn0 up event with x and y == 0
// but sometimes it gets the correct coords (threading/async?)
//mouse_pos(0, 0);
}
jvoidfunc(resize) (JNIEnv* env, jobject obj, jint width, jint height) {
g_width = width;
g_height = height;
}
jvoidfunc(step) (JNIEnv* env, jobject obj) {
mpv_opengl_cb_draw(mpv_gl, 0, g_width, -g_height);
while (1) {
mpv_event *mp_event = mpv_wait_event(mpv, 0);
mpv_event_log_message *msg;
if (mp_event->event_id == MPV_EVENT_NONE)
break;
switch (mp_event->event_id) {
case MPV_EVENT_LOG_MESSAGE:
msg = (mpv_event_log_message*)mp_event->data;
ALOGV("[%s:%s] %s", msg->prefix, msg->level, msg->text);
break;
default:
ALOGV("event: %s\n", mpv_event_name(mp_event->event_id));
break;
}
}
}
jvoidfunc(play) (JNIEnv* env, jobject obj) {
CHKVALID();
int paused = 0;
mpv_set_property(mpv, "pause", MPV_FORMAT_FLAG, &paused);
}
jvoidfunc(pause) (JNIEnv* env, jobject obj) {
CHKVALID();
int paused = 1;
mpv_set_property(mpv, "pause", MPV_FORMAT_FLAG, &paused);
}
jvoidfunc(setconfigdir) (JNIEnv* env, jobject obj, jstring jpath) {
const char *path = env->GetStringUTFChars(jpath, NULL);
strncpy(g_config_dir, path, sizeof(g_config_dir) - 1);
env->ReleaseStringUTFChars(jpath, path);
}
jfunc(getpropertyint, jint) (JNIEnv *env, jobject obj, jstring jproperty) {
if (!mpv)
return 0;
const char *prop = env->GetStringUTFChars(jproperty, NULL);
int64_t value = 0;
int result = mpv_get_property(mpv, prop, MPV_FORMAT_INT64, &value);
if (!result)
ALOGE("mpv_get_property(%s) returned error %s", prop, mpv_error_string(result));
env->ReleaseStringUTFChars(jproperty, prop);
return value;
}
jvoidfunc(setpropertyint) (JNIEnv *env, jobject obj, jstring jproperty, jint value) {
if (!mpv)
return;
const char *prop = env->GetStringUTFChars(jproperty, NULL);
int64_t value64 = value;
int result = mpv_set_property(mpv, prop, MPV_FORMAT_INT64, &value64);
if (!result)
ALOGE("mpv_set_property(%s, %d) returned error %s", prop, value, mpv_error_string(result));
env->ReleaseStringUTFChars(jproperty, prop);
}
<commit_msg>Fix mpv_*_property return value check.<commit_after>#include <jni.h>
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <locale.h>
#include <mpv/client.h>
#include <mpv/opengl_cb.h>
#include <EGL/egl.h>
#include "main.h"
#define ARRAYLEN(a) (sizeof(a)/sizeof(a[0]))
#define jfunc(name, type) JNIEXPORT type JNICALL Java_is_xyz_mpv_MPVLib_##name
#define jvoidfunc(name) jfunc(name, void)
extern "C" {
jvoidfunc(init) (JNIEnv* env, jobject obj);
jvoidfunc(command) (JNIEnv* env, jobject obj, jobjectArray jarray);
jvoidfunc(resize) (JNIEnv* env, jobject obj, jint width, jint height);
jvoidfunc(step) (JNIEnv* env, jobject obj);
jvoidfunc(play) (JNIEnv *env, jobject obj);
jvoidfunc(pause) (JNIEnv *env, jobject obj);
jvoidfunc(touch_1down) (JNIEnv* env, jobject obj, jint x, jint y);
jvoidfunc(touch_1move) (JNIEnv* env, jobject obj, jint x, jint y);
jvoidfunc(touch_1up) (JNIEnv* env, jobject obj, jint x, jint y);
jvoidfunc(setconfigdir) (JNIEnv* env, jobject obj, jstring path);
jfunc(getpropertyint, jint) (JNIEnv *env, jobject obj, jstring property);
jvoidfunc(setpropertyint) (JNIEnv *env, jobject obj, jstring property, jint value);
};
mpv_handle *mpv;
mpv_opengl_cb_context *mpv_gl;
int g_width, g_height;
char g_config_dir[2048];
char **g_command_queue[16] = {NULL};
static void die(const char *msg)
{
ALOGE("%s", msg);
exit(1);
}
static void *get_proc_address_mpv(void *fn_ctx, const char *name)
{
return (void*)eglGetProcAddress(name);
}
static int cq_push(char **e)
{
for (int i = 0; i < ARRAYLEN(g_command_queue); i++) {
if (g_command_queue[i] != NULL)
continue;
g_command_queue[i] = e;
return 0;
}
return -1;
}
static void cq_free(char **e)
{
for (int i = 0; e[i] != NULL; i++)
free(e[i]);
free(e);
}
jvoidfunc(init) (JNIEnv* env, jobject obj) {
if (mpv)
return;
setlocale(LC_NUMERIC, "C");
mpv = mpv_create();
if (!mpv)
die("context init failed");
int osc = 1;
mpv_set_option(mpv, "osc", MPV_FORMAT_FLAG, &osc);
mpv_set_option_string(mpv, "script-opts", "osc-scalewindowed=1.5");
mpv_set_option_string(mpv, "config", "yes");
mpv_set_option_string(mpv, "config-dir", g_config_dir);
mpv_request_log_messages(mpv, "v");
if (mpv_initialize(mpv) < 0)
die("mpv init failed");
mpv_gl = (mpv_opengl_cb_context*)mpv_get_sub_api(mpv, MPV_SUB_API_OPENGL_CB);
if (!mpv_gl)
die("failed to create mpv GL API handle");
if (mpv_opengl_cb_init_gl(mpv_gl, NULL, get_proc_address_mpv, NULL) < 0)
die("failed to initialize mpv GL context");
if (mpv_set_option_string(mpv, "vo", "opengl-cb") < 0)
die("failed to set VO");
if (mpv_set_option_string(mpv, "ao", "openal") < 0)
die("failed to set AO");
for (int i = 0; i < ARRAYLEN(g_command_queue); i++) {
if (g_command_queue[i] == NULL)
break;
char **cmd = g_command_queue[i];
mpv_command(mpv, (const char**) cmd);
cq_free(cmd);
}
}
#define CHKVALID() if (!mpv) return;
jvoidfunc(command) (JNIEnv* env, jobject obj, jobjectArray jarray) {
char **command;
int jarray_l = env->GetArrayLength(jarray);
command = (char**) malloc(sizeof(char*) * (jarray_l+1));
if (!command)
return;
for (int i = 0; i < jarray_l; i++) {
jstring jstr = (jstring) env->GetObjectArrayElement(jarray, i);
const char *str = env->GetStringUTFChars(jstr, NULL);
command[i] = strdup(str);
env->ReleaseStringUTFChars(jstr, str);
}
command[jarray_l] = NULL;
if (mpv) {
mpv_command(mpv, (const char**) command);
cq_free(command);
return;
}
if(cq_push(command) < 0) {
ALOGE("command queue full");
cq_free(command);
}
}
static void mouse_pos(int x, int y) {
char sx[5], sy[5];
const char *cmd[] = {"mouse", sx, sy, NULL};
snprintf(sx, sizeof(sx), "%d", x);
snprintf(sy, sizeof(sy), "%d", y);
mpv_command(mpv, cmd);
}
static void mouse_trigger(int down, int btn) {
// "mouse" doesn't actually send keydown events so we need to do it manually
char k[16];
const char *cmd[] = {down?"keydown":"keyup", k, NULL};
snprintf(k, sizeof(k), "MOUSE_BTN%d", btn);
mpv_command(mpv, cmd);
}
jvoidfunc(touch_1down) (JNIEnv* env, jobject obj, jint x, jint y) {
CHKVALID();
mouse_pos(x, y);
mouse_trigger(1, 0);
}
jvoidfunc(touch_1move) (JNIEnv* env, jobject obj, jint x, jint y) {
CHKVALID();
mouse_pos(x, y);
}
jvoidfunc(touch_1up) (JNIEnv* env, jobject obj, jint x, jint y) {
CHKVALID();
mouse_trigger(0, 0);
// move the cursor to the top left corner where it doesn't trigger the OSC
// FIXME: this causes the OSC to receive a mouse_btn0 up event with x and y == 0
// but sometimes it gets the correct coords (threading/async?)
//mouse_pos(0, 0);
}
jvoidfunc(resize) (JNIEnv* env, jobject obj, jint width, jint height) {
g_width = width;
g_height = height;
}
jvoidfunc(step) (JNIEnv* env, jobject obj) {
mpv_opengl_cb_draw(mpv_gl, 0, g_width, -g_height);
while (1) {
mpv_event *mp_event = mpv_wait_event(mpv, 0);
mpv_event_log_message *msg;
if (mp_event->event_id == MPV_EVENT_NONE)
break;
switch (mp_event->event_id) {
case MPV_EVENT_LOG_MESSAGE:
msg = (mpv_event_log_message*)mp_event->data;
ALOGV("[%s:%s] %s", msg->prefix, msg->level, msg->text);
break;
default:
ALOGV("event: %s\n", mpv_event_name(mp_event->event_id));
break;
}
}
}
jvoidfunc(play) (JNIEnv* env, jobject obj) {
CHKVALID();
int paused = 0;
mpv_set_property(mpv, "pause", MPV_FORMAT_FLAG, &paused);
}
jvoidfunc(pause) (JNIEnv* env, jobject obj) {
CHKVALID();
int paused = 1;
mpv_set_property(mpv, "pause", MPV_FORMAT_FLAG, &paused);
}
jvoidfunc(setconfigdir) (JNIEnv* env, jobject obj, jstring jpath) {
const char *path = env->GetStringUTFChars(jpath, NULL);
strncpy(g_config_dir, path, sizeof(g_config_dir) - 1);
env->ReleaseStringUTFChars(jpath, path);
}
jfunc(getpropertyint, jint) (JNIEnv *env, jobject obj, jstring jproperty) {
if (!mpv)
return 0;
const char *prop = env->GetStringUTFChars(jproperty, NULL);
int64_t value = 0;
int result = mpv_get_property(mpv, prop, MPV_FORMAT_INT64, &value);
if (result)
ALOGE("mpv_get_property(%s) returned error %s", prop, mpv_error_string(result));
env->ReleaseStringUTFChars(jproperty, prop);
return value;
}
jvoidfunc(setpropertyint) (JNIEnv *env, jobject obj, jstring jproperty, jint value) {
if (!mpv)
return;
const char *prop = env->GetStringUTFChars(jproperty, NULL);
int64_t value64 = value;
int result = mpv_set_property(mpv, prop, MPV_FORMAT_INT64, &value64);
if (result)
ALOGE("mpv_set_property(%s, %d) returned error %s", prop, value, mpv_error_string(result));
env->ReleaseStringUTFChars(jproperty, prop);
}
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.