text
stringlengths 54
60.6k
|
---|
<commit_before>// ======================================================================== //
// Copyright 2009-2016 Intel Corporation //
// //
// Licensed under the Apache License, Version 2.0 (the "License"); //
// you may not use this file except in compliance with the License. //
// You may obtain a copy of the License at //
// //
// http://www.apache.org/licenses/LICENSE-2.0 //
// //
// Unless required by applicable law or agreed to in writing, software //
// distributed under the License is distributed on an "AS IS" BASIS, //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and //
// limitations under the License. //
// ======================================================================== //
#include "TriangleMeshSceneParser.h"
#include <ospray_cpp/Data.h>
#include <common/miniSG/miniSG.h>
using namespace ospray;
using namespace ospcommon;
#include <string>
#include <iostream>
using std::cerr;
using std::endl;
// Static local helper functions //////////////////////////////////////////////
static void warnMaterial(const std::string &type)
{
static std::map<std::string,int> numOccurances;
if (numOccurances[type] == 0)
{
cerr << "could not create material type '"<< type <<
"'. Replacing with default material." << endl;
}
numOccurances[type]++;
}
// SceneParser definitions ////////////////////////////////////////////////////
TriangleMeshSceneParser::TriangleMeshSceneParser(cpp::Renderer renderer,
std::string geometryType) :
m_renderer(renderer),
m_geometryType(geometryType),
m_alpha(false),
m_createDefaultMaterial(true),
m_maxObjectsToConsider((uint32_t)-1),
m_forceInstancing(false),
m_msgModel(new miniSG::Model)
{
}
bool TriangleMeshSceneParser::parse(int ac, const char **&av)
{
bool loadedScene = false;
for (int i = 1; i < ac; i++) {
const std::string arg = av[i];
if (arg == "--max-objects") {
m_maxObjectsToConsider = atoi(av[++i]);
} else if (arg == "--force-instancing") {
m_forceInstancing = true;
} else if (arg == "--alpha") {
m_alpha = true;
} else if (arg == "--no-default-material") {
m_createDefaultMaterial = false;
} else {
FileName fn = arg;
if (fn.ext() == "stl") {
miniSG::importSTL(*m_msgModel,fn);
loadedScene = true;
} else if (fn.ext() == "msg") {
miniSG::importMSG(*m_msgModel,fn);
loadedScene = true;
} else if (fn.ext() == "tri") {
miniSG::importTRI(*m_msgModel,fn);
loadedScene = true;
} else if (fn.ext() == "xml") {
miniSG::importRIVL(*m_msgModel,fn);
loadedScene = true;
} else if (fn.ext() == "obj") {
miniSG::importOBJ(*m_msgModel,fn);
loadedScene = true;
} else if (fn.ext() == "hbp") {
miniSG::importHBP(*m_msgModel,fn);
loadedScene = true;
} else if (fn.ext() == "x3d") {
miniSG::importX3D(*m_msgModel,fn);
loadedScene = true;
} else if (fn.ext() == "astl") {
miniSG::importSTL(m_msgAnimation,fn);
loadedScene = true;
}
}
}
if (loadedScene) finalize();
return loadedScene;
}
cpp::Model TriangleMeshSceneParser::model() const
{
return m_model;
}
ospcommon::box3f TriangleMeshSceneParser::bbox() const
{
return m_msgModel.ptr->getBBox();
}
cpp::Material
TriangleMeshSceneParser::createDefaultMaterial(cpp::Renderer renderer)
{
if(!m_createDefaultMaterial) return nullptr;
static auto ospMat = cpp::Material(nullptr);
if (ospMat.handle()) return ospMat;
ospMat = renderer.newMaterial("OBJMaterial");
ospMat.set("Kd", .8f, 0.f, 0.f);
ospMat.commit();
return ospMat;
}
cpp::Material TriangleMeshSceneParser::createMaterial(cpp::Renderer renderer,
miniSG::Material *mat)
{
if (mat == nullptr) return createDefaultMaterial(renderer);
static std::map<miniSG::Material *, cpp::Material> alreadyCreatedMaterials;
if (alreadyCreatedMaterials.find(mat) != alreadyCreatedMaterials.end()) {
return alreadyCreatedMaterials[mat];
}
const char *type = mat->getParam("type", "OBJMaterial");
assert(type);
cpp::Material ospMat;
try {
ospMat = alreadyCreatedMaterials[mat] = renderer.newMaterial(type);
} catch (const std::runtime_error &/*e*/) {
warnMaterial(type);
return createDefaultMaterial(renderer);
}
const bool isOBJMaterial = !strcmp(type, "OBJMaterial");
for (auto it = mat->params.begin(); it != mat->params.end(); ++it) {
const char *name = it->first.c_str();
const miniSG::Material::Param *p = it->second.ptr;
switch(p->type) {
case miniSG::Material::Param::INT:
ospMat.set(name, p->i[0]);
break;
case miniSG::Material::Param::FLOAT: {
float f = p->f[0];
/* many mtl materials of obj models wrongly store the phong exponent
'Ns' in range [0..1], whereas OSPRay's material implementations
correctly interpret it to be in [0..inf), thus we map ranges here */
if (isOBJMaterial &&
(!strcmp(name, "Ns") || !strcmp(name, "ns")) &&
f < 1.f) {
f = 1.f/(1.f - f) - 1.f;
}
ospMat.set(name, f);
} break;
case miniSG::Material::Param::FLOAT_3:
ospMat.set(name, p->f[0], p->f[1], p->f[2]);
break;
case miniSG::Material::Param::STRING:
ospMat.set(name, p->s);
break;
case miniSG::Material::Param::TEXTURE:
{
miniSG::Texture2D *tex = (miniSG::Texture2D*)p->ptr;
if (tex) {
OSPTexture2D ospTex = miniSG::createTexture2D(tex);
assert(ospTex);
ospCommit(ospTex);
ospMat.set(name, ospTex);
}
break;
}
default:
throw std::runtime_error("unknown material parameter type");
};
}
ospMat.commit();
return ospMat;
}
void TriangleMeshSceneParser::finalize()
{
// code does not yet do instancing ... check that the model doesn't
// contain instances
bool doesInstancing = 0;
if (m_forceInstancing) {
doesInstancing = true;
} else if (m_msgModel->instance.size() > m_msgModel->mesh.size()) {
doesInstancing = true;
} else {
doesInstancing = false;
}
if (m_msgModel->instance.size() > m_maxObjectsToConsider) {
m_msgModel->instance.resize(m_maxObjectsToConsider);
if (!doesInstancing) {
m_msgModel->mesh.resize(m_maxObjectsToConsider);
}
}
std::vector<OSPModel> instanceModels;
for (size_t i=0;i<m_msgModel->mesh.size();i++) {
Ref<miniSG::Mesh> msgMesh = m_msgModel->mesh[i];
// create ospray mesh
auto ospMesh = m_alpha ? cpp::Geometry("alpha_aware_triangle_mesh") :
cpp::Geometry(m_geometryType);
// check if we have to transform the vertices:
if (doesInstancing == false &&
m_msgModel->instance[i] != miniSG::Instance(i)) {
for (size_t vID = 0; vID < msgMesh->position.size(); vID++) {
msgMesh->position[vID] = xfmPoint(m_msgModel->instance[i].xfm,
msgMesh->position[vID]);
}
}
// add position array to mesh
OSPData position = ospNewData(msgMesh->position.size(),
OSP_FLOAT3A,
&msgMesh->position[0]);
ospMesh.set("position", position);
// add triangle index array to mesh
if (!msgMesh->triangleMaterialId.empty()) {
OSPData primMatID = ospNewData(msgMesh->triangleMaterialId.size(),
OSP_INT,
&msgMesh->triangleMaterialId[0]);
ospMesh.set("prim.materialID", primMatID);
}
// add triangle index array to mesh
OSPData index = ospNewData(msgMesh->triangle.size(),
OSP_INT3,
&msgMesh->triangle[0]);
assert(msgMesh->triangle.size() > 0);
ospMesh.set("index", index);
// add normal array to mesh
if (!msgMesh->normal.empty()) {
OSPData normal = ospNewData(msgMesh->normal.size(),
OSP_FLOAT3A,
&msgMesh->normal[0]);
assert(msgMesh->normal.size() > 0);
ospMesh.set("vertex.normal", normal);
}
// add color array to mesh
if (!msgMesh->color.empty()) {
OSPData color = ospNewData(msgMesh->color.size(),
OSP_FLOAT3A,
&msgMesh->color[0]);
assert(msgMesh->color.size() > 0);
ospMesh.set("vertex.color", color);
}
// add texcoord array to mesh
if (!msgMesh->texcoord.empty()) {
OSPData texcoord = ospNewData(msgMesh->texcoord.size(),
OSP_FLOAT2,
&msgMesh->texcoord[0]);
assert(msgMesh->texcoord.size() > 0);
ospMesh.set("vertex.texcoord", texcoord);
}
ospMesh.set("alpha_type", 0);
ospMesh.set("alpha_component", 4);
// add triangle material id array to mesh
if (msgMesh->materialList.empty()) {
// we have a single material for this mesh...
auto singleMaterial = createMaterial(m_renderer, msgMesh->material.ptr);
ospMesh.setMaterial(singleMaterial);
} else {
// we have an entire material list, assign that list
std::vector<OSPMaterial> materialList;
std::vector<OSPTexture2D> alphaMaps;
std::vector<float> alphas;
for (size_t i = 0; i < msgMesh->materialList.size(); i++) {
auto m = createMaterial(m_renderer, msgMesh->materialList[i].ptr);
auto handle = m.handle();
materialList.push_back(handle);
for (miniSG::Material::ParamMap::const_iterator it =
msgMesh->materialList[i]->params.begin();
it != msgMesh->materialList[i]->params.end(); it++) {
const char *name = it->first.c_str();
const miniSG::Material::Param *p = it->second.ptr;
if(p->type == miniSG::Material::Param::TEXTURE) {
if(!strcmp(name, "map_kd") || !strcmp(name, "map_Kd")) {
miniSG::Texture2D *tex = (miniSG::Texture2D*)p->ptr;
OSPTexture2D ospTex = createTexture2D(tex);
ospCommit(ospTex);
alphaMaps.push_back(ospTex);
}
} else if(p->type == miniSG::Material::Param::FLOAT) {
if(!strcmp(name, "d")) alphas.push_back(p->f[0]);
}
}
while(materialList.size() > alphaMaps.size()) {
alphaMaps.push_back(nullptr);
}
while(materialList.size() > alphas.size()) {
alphas.push_back(0.f);
}
}
auto ospMaterialList = cpp::Data(materialList.size(),
OSP_OBJECT,
&materialList[0]);
ospMesh.set("materialList", ospMaterialList);
// only set these if alpha aware mode enabled
// this currently doesn't work on the MICs!
if(m_alpha) {
auto ospAlphaMapList = cpp::Data(alphaMaps.size(),
OSP_OBJECT,
&alphaMaps[0]);
ospMesh.set("alpha_maps", ospAlphaMapList);
auto ospAlphaList = cpp::Data(alphas.size(),
OSP_OBJECT,
&alphas[0]);
ospMesh.set("alphas", ospAlphaList);
}
}
ospMesh.commit();
if (doesInstancing) {
cpp::Model model_i;
model_i.addGeometry(ospMesh);
model_i.commit();
instanceModels.push_back(model_i.handle());
} else {
m_model.addGeometry(ospMesh);
}
}
if (doesInstancing) {
for (size_t i = 0; i < m_msgModel->instance.size(); i++) {
OSPGeometry inst =
ospNewInstance(instanceModels[m_msgModel->instance[i].meshID],
reinterpret_cast<osp::affine3f&>(m_msgModel->instance[i].xfm));
m_model.addGeometry(inst);
}
}
m_model.commit();
}
<commit_msg>add ability to configure triangle mesh string type on the command line<commit_after>// ======================================================================== //
// Copyright 2009-2016 Intel Corporation //
// //
// Licensed under the Apache License, Version 2.0 (the "License"); //
// you may not use this file except in compliance with the License. //
// You may obtain a copy of the License at //
// //
// http://www.apache.org/licenses/LICENSE-2.0 //
// //
// Unless required by applicable law or agreed to in writing, software //
// distributed under the License is distributed on an "AS IS" BASIS, //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and //
// limitations under the License. //
// ======================================================================== //
#include "TriangleMeshSceneParser.h"
#include <ospray_cpp/Data.h>
#include <common/miniSG/miniSG.h>
using namespace ospray;
using namespace ospcommon;
#include <string>
#include <iostream>
using std::cerr;
using std::endl;
// Static local helper functions //////////////////////////////////////////////
static void warnMaterial(const std::string &type)
{
static std::map<std::string,int> numOccurances;
if (numOccurances[type] == 0)
{
cerr << "could not create material type '"<< type <<
"'. Replacing with default material." << endl;
}
numOccurances[type]++;
}
// SceneParser definitions ////////////////////////////////////////////////////
TriangleMeshSceneParser::TriangleMeshSceneParser(cpp::Renderer renderer,
std::string geometryType) :
m_renderer(renderer),
m_geometryType(geometryType),
m_alpha(false),
m_createDefaultMaterial(true),
m_maxObjectsToConsider((uint32_t)-1),
m_forceInstancing(false),
m_msgModel(new miniSG::Model)
{
}
bool TriangleMeshSceneParser::parse(int ac, const char **&av)
{
bool loadedScene = false;
for (int i = 1; i < ac; i++) {
const std::string arg = av[i];
if (arg == "--max-objects") {
m_maxObjectsToConsider = atoi(av[++i]);
} else if (arg == "--force-instancing") {
m_forceInstancing = true;
} else if (arg == "--alpha") {
m_alpha = true;
} else if (arg == "--no-default-material") {
m_createDefaultMaterial = false;
} else if (arg == "--trianglemesh-type") {
m_geometryType = av[++i];
} else {
FileName fn = arg;
if (fn.ext() == "stl") {
miniSG::importSTL(*m_msgModel,fn);
loadedScene = true;
} else if (fn.ext() == "msg") {
miniSG::importMSG(*m_msgModel,fn);
loadedScene = true;
} else if (fn.ext() == "tri") {
miniSG::importTRI(*m_msgModel,fn);
loadedScene = true;
} else if (fn.ext() == "xml") {
miniSG::importRIVL(*m_msgModel,fn);
loadedScene = true;
} else if (fn.ext() == "obj") {
miniSG::importOBJ(*m_msgModel,fn);
loadedScene = true;
} else if (fn.ext() == "hbp") {
miniSG::importHBP(*m_msgModel,fn);
loadedScene = true;
} else if (fn.ext() == "x3d") {
miniSG::importX3D(*m_msgModel,fn);
loadedScene = true;
} else if (fn.ext() == "astl") {
miniSG::importSTL(m_msgAnimation,fn);
loadedScene = true;
}
}
}
if (loadedScene) finalize();
return loadedScene;
}
cpp::Model TriangleMeshSceneParser::model() const
{
return m_model;
}
ospcommon::box3f TriangleMeshSceneParser::bbox() const
{
return m_msgModel.ptr->getBBox();
}
cpp::Material
TriangleMeshSceneParser::createDefaultMaterial(cpp::Renderer renderer)
{
if(!m_createDefaultMaterial) return nullptr;
static auto ospMat = cpp::Material(nullptr);
if (ospMat.handle()) return ospMat;
ospMat = renderer.newMaterial("OBJMaterial");
ospMat.set("Kd", .8f, 0.f, 0.f);
ospMat.commit();
return ospMat;
}
cpp::Material TriangleMeshSceneParser::createMaterial(cpp::Renderer renderer,
miniSG::Material *mat)
{
if (mat == nullptr) return createDefaultMaterial(renderer);
static std::map<miniSG::Material *, cpp::Material> alreadyCreatedMaterials;
if (alreadyCreatedMaterials.find(mat) != alreadyCreatedMaterials.end()) {
return alreadyCreatedMaterials[mat];
}
const char *type = mat->getParam("type", "OBJMaterial");
assert(type);
cpp::Material ospMat;
try {
ospMat = alreadyCreatedMaterials[mat] = renderer.newMaterial(type);
} catch (const std::runtime_error &/*e*/) {
warnMaterial(type);
return createDefaultMaterial(renderer);
}
const bool isOBJMaterial = !strcmp(type, "OBJMaterial");
for (auto it = mat->params.begin(); it != mat->params.end(); ++it) {
const char *name = it->first.c_str();
const miniSG::Material::Param *p = it->second.ptr;
switch(p->type) {
case miniSG::Material::Param::INT:
ospMat.set(name, p->i[0]);
break;
case miniSG::Material::Param::FLOAT: {
float f = p->f[0];
/* many mtl materials of obj models wrongly store the phong exponent
'Ns' in range [0..1], whereas OSPRay's material implementations
correctly interpret it to be in [0..inf), thus we map ranges here */
if (isOBJMaterial &&
(!strcmp(name, "Ns") || !strcmp(name, "ns")) &&
f < 1.f) {
f = 1.f/(1.f - f) - 1.f;
}
ospMat.set(name, f);
} break;
case miniSG::Material::Param::FLOAT_3:
ospMat.set(name, p->f[0], p->f[1], p->f[2]);
break;
case miniSG::Material::Param::STRING:
ospMat.set(name, p->s);
break;
case miniSG::Material::Param::TEXTURE:
{
miniSG::Texture2D *tex = (miniSG::Texture2D*)p->ptr;
if (tex) {
OSPTexture2D ospTex = miniSG::createTexture2D(tex);
assert(ospTex);
ospCommit(ospTex);
ospMat.set(name, ospTex);
}
break;
}
default:
throw std::runtime_error("unknown material parameter type");
};
}
ospMat.commit();
return ospMat;
}
void TriangleMeshSceneParser::finalize()
{
// code does not yet do instancing ... check that the model doesn't
// contain instances
bool doesInstancing = 0;
if (m_forceInstancing) {
doesInstancing = true;
} else if (m_msgModel->instance.size() > m_msgModel->mesh.size()) {
doesInstancing = true;
} else {
doesInstancing = false;
}
if (m_msgModel->instance.size() > m_maxObjectsToConsider) {
m_msgModel->instance.resize(m_maxObjectsToConsider);
if (!doesInstancing) {
m_msgModel->mesh.resize(m_maxObjectsToConsider);
}
}
std::vector<OSPModel> instanceModels;
for (size_t i=0;i<m_msgModel->mesh.size();i++) {
Ref<miniSG::Mesh> msgMesh = m_msgModel->mesh[i];
// create ospray mesh
auto ospMesh = m_alpha ? cpp::Geometry("alpha_aware_triangle_mesh") :
cpp::Geometry(m_geometryType);
// check if we have to transform the vertices:
if (doesInstancing == false &&
m_msgModel->instance[i] != miniSG::Instance(i)) {
for (size_t vID = 0; vID < msgMesh->position.size(); vID++) {
msgMesh->position[vID] = xfmPoint(m_msgModel->instance[i].xfm,
msgMesh->position[vID]);
}
}
// add position array to mesh
OSPData position = ospNewData(msgMesh->position.size(),
OSP_FLOAT3A,
&msgMesh->position[0]);
ospMesh.set("position", position);
// add triangle index array to mesh
if (!msgMesh->triangleMaterialId.empty()) {
OSPData primMatID = ospNewData(msgMesh->triangleMaterialId.size(),
OSP_INT,
&msgMesh->triangleMaterialId[0]);
ospMesh.set("prim.materialID", primMatID);
}
// add triangle index array to mesh
OSPData index = ospNewData(msgMesh->triangle.size(),
OSP_INT3,
&msgMesh->triangle[0]);
assert(msgMesh->triangle.size() > 0);
ospMesh.set("index", index);
// add normal array to mesh
if (!msgMesh->normal.empty()) {
OSPData normal = ospNewData(msgMesh->normal.size(),
OSP_FLOAT3A,
&msgMesh->normal[0]);
assert(msgMesh->normal.size() > 0);
ospMesh.set("vertex.normal", normal);
}
// add color array to mesh
if (!msgMesh->color.empty()) {
OSPData color = ospNewData(msgMesh->color.size(),
OSP_FLOAT3A,
&msgMesh->color[0]);
assert(msgMesh->color.size() > 0);
ospMesh.set("vertex.color", color);
}
// add texcoord array to mesh
if (!msgMesh->texcoord.empty()) {
OSPData texcoord = ospNewData(msgMesh->texcoord.size(),
OSP_FLOAT2,
&msgMesh->texcoord[0]);
assert(msgMesh->texcoord.size() > 0);
ospMesh.set("vertex.texcoord", texcoord);
}
ospMesh.set("alpha_type", 0);
ospMesh.set("alpha_component", 4);
// add triangle material id array to mesh
if (msgMesh->materialList.empty()) {
// we have a single material for this mesh...
auto singleMaterial = createMaterial(m_renderer, msgMesh->material.ptr);
ospMesh.setMaterial(singleMaterial);
} else {
// we have an entire material list, assign that list
std::vector<OSPMaterial> materialList;
std::vector<OSPTexture2D> alphaMaps;
std::vector<float> alphas;
for (size_t i = 0; i < msgMesh->materialList.size(); i++) {
auto m = createMaterial(m_renderer, msgMesh->materialList[i].ptr);
auto handle = m.handle();
materialList.push_back(handle);
for (miniSG::Material::ParamMap::const_iterator it =
msgMesh->materialList[i]->params.begin();
it != msgMesh->materialList[i]->params.end(); it++) {
const char *name = it->first.c_str();
const miniSG::Material::Param *p = it->second.ptr;
if(p->type == miniSG::Material::Param::TEXTURE) {
if(!strcmp(name, "map_kd") || !strcmp(name, "map_Kd")) {
miniSG::Texture2D *tex = (miniSG::Texture2D*)p->ptr;
OSPTexture2D ospTex = createTexture2D(tex);
ospCommit(ospTex);
alphaMaps.push_back(ospTex);
}
} else if(p->type == miniSG::Material::Param::FLOAT) {
if(!strcmp(name, "d")) alphas.push_back(p->f[0]);
}
}
while(materialList.size() > alphaMaps.size()) {
alphaMaps.push_back(nullptr);
}
while(materialList.size() > alphas.size()) {
alphas.push_back(0.f);
}
}
auto ospMaterialList = cpp::Data(materialList.size(),
OSP_OBJECT,
&materialList[0]);
ospMesh.set("materialList", ospMaterialList);
// only set these if alpha aware mode enabled
// this currently doesn't work on the MICs!
if(m_alpha) {
auto ospAlphaMapList = cpp::Data(alphaMaps.size(),
OSP_OBJECT,
&alphaMaps[0]);
ospMesh.set("alpha_maps", ospAlphaMapList);
auto ospAlphaList = cpp::Data(alphas.size(),
OSP_OBJECT,
&alphas[0]);
ospMesh.set("alphas", ospAlphaList);
}
}
ospMesh.commit();
if (doesInstancing) {
cpp::Model model_i;
model_i.addGeometry(ospMesh);
model_i.commit();
instanceModels.push_back(model_i.handle());
} else {
m_model.addGeometry(ospMesh);
}
}
if (doesInstancing) {
for (size_t i = 0; i < m_msgModel->instance.size(); i++) {
OSPGeometry inst =
ospNewInstance(instanceModels[m_msgModel->instance[i].meshID],
reinterpret_cast<osp::affine3f&>(m_msgModel->instance[i].xfm));
m_model.addGeometry(inst);
}
}
m_model.commit();
}
<|endoftext|> |
<commit_before>/* Copyright 2009-2016 Francesco Biscani (bluescarni@gmail.com)
This file is part of the mp++ library.
The mp++ library is free software; you can redistribute it and/or modify
it under the terms of either:
* 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.
or
* 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.
or both in parallel, as here.
The mp++ 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 General Public License
for more details.
You should have received copies of the GNU General Public License and the
GNU Lesser General Public License along with the mp++ library. If not,
see https://www.gnu.org/licenses/. */
// std::index_sequence and std::make_index_sequence implementation, from:
// http://stackoverflow.com/questions/17424477/implementation-c14-make-integer-sequence
#ifndef MPPP_TEST_UTILS_HPP
#define MPPP_TEST_UTILS_HPP
#include <cassert>
#include <cstddef>
#include <gmp.h>
#include <initializer_list>
#include <limits>
#include <locale>
#include <mp++.hpp>
#include <random>
#include <sstream>
#include <string>
#include <tuple>
#include <type_traits>
#include <utility>
namespace mppp_test
{
// std::index_sequence and std::make_index_sequence implementation for C++11. These are available
// in the std library in C++14. Implementation taken from:
// http://stackoverflow.com/questions/17424477/implementation-c14-make-integer-sequence
template <std::size_t... Ints>
struct index_sequence {
using type = index_sequence;
using value_type = std::size_t;
static constexpr std::size_t size() noexcept
{
return sizeof...(Ints);
}
};
inline namespace impl
{
template <class Sequence1, class Sequence2>
struct merge_and_renumber;
template <std::size_t... I1, std::size_t... I2>
struct merge_and_renumber<index_sequence<I1...>, index_sequence<I2...>>
: index_sequence<I1..., (sizeof...(I1) + I2)...> {
};
}
template <std::size_t N>
struct make_index_sequence
: merge_and_renumber<typename make_index_sequence<N / 2>::type, typename make_index_sequence<N - N / 2>::type> {
};
template <>
struct make_index_sequence<0> : index_sequence<> {
};
template <>
struct make_index_sequence<1> : index_sequence<0> {
};
inline namespace impl
{
template <typename T, typename F, std::size_t... Is>
void apply_to_each_item(T &&t, const F &f, index_sequence<Is...>)
{
(void)std::initializer_list<int>{0, (void(f(std::get<Is>(std::forward<T>(t)))), 0)...};
}
}
// Tuple for_each(). Execute the functor f on each element of the input Tuple.
// https://isocpp.org/blog/2015/01/for-each-arg-eric-niebler
// https://www.reddit.com/r/cpp/comments/2tffv3/for_each_argumentsean_parent/
// https://www.reddit.com/r/cpp/comments/33b06v/for_each_in_tuple/
template <class Tuple, class F>
void tuple_for_each(Tuple &&t, const F &f)
{
apply_to_each_item(std::forward<Tuple>(t), f,
make_index_sequence<std::tuple_size<typename std::decay<Tuple>::type>::value>{});
}
inline namespace impl
{
template <typename T>
struct is_mp_integer {
static const bool value = false;
};
template <std::size_t SSize>
struct is_mp_integer<mppp::mp_integer<SSize>> {
static const bool value = true;
};
template <typename T, typename std::enable_if<std::is_integral<T>::value && std::is_signed<T>::value, int>::type = 0>
inline long long lex_cast_tr(T n)
{
return static_cast<long long>(n);
}
template <typename T, typename std::enable_if<std::is_integral<T>::value && std::is_unsigned<T>::value, int>::type = 0>
inline unsigned long long lex_cast_tr(T n)
{
return static_cast<unsigned long long>(n);
}
template <typename T, typename std::enable_if<is_mp_integer<T>::value, int>::type = 0>
inline std::string lex_cast_tr(const T &x)
{
return x.to_string();
}
template <typename T, typename std::enable_if<std::is_floating_point<T>::value, int>::type = 0>
inline T lex_cast_tr(const T &x)
{
return x;
}
}
// Lexical cast: retrieve the string representation of input object x.
template <typename T>
inline std::string lex_cast(const T &x)
{
std::ostringstream oss;
oss.imbue(std::locale::classic());
oss << lex_cast_tr(x);
return oss.str();
}
inline std::string lex_cast(const mppp::mppp_impl::mpz_raii &m)
{
return mppp::mppp_impl::mpz_to_str(&m.m_mpz);
}
// Set mpz to random value with n limbs. Top limb is divided by div.
inline void random_integer(mppp::mppp_impl::mpz_raii &m, unsigned n, std::mt19937 &rng, ::mp_limb_t div = 1u)
{
if (!n) {
::mpz_set_ui(&m.m_mpz, 0);
return;
}
static thread_local mppp::mppp_impl::mpz_raii tmp;
std::uniform_int_distribution<::mp_limb_t> dist(0u, std::numeric_limits<::mp_limb_t>::max());
// Set the first limb.
::mpz_set_str(&m.m_mpz, lex_cast((dist(rng) & GMP_NUMB_MASK) / div).c_str(), 10);
for (unsigned i = 1u; i < n; ++i) {
::mpz_set_str(&tmp.m_mpz, lex_cast(dist(rng) & GMP_NUMB_MASK).c_str(), 10);
::mpz_mul_2exp(&m.m_mpz, &m.m_mpz, GMP_NUMB_BITS);
::mpz_add(&m.m_mpz, &m.m_mpz, &tmp.m_mpz);
}
}
// Set mpz to the max value with n limbs.
inline void max_integer(mppp::mppp_impl::mpz_raii &m, unsigned n)
{
if (!n) {
::mpz_set_ui(&m.m_mpz, 0);
return;
}
static thread_local mppp::mppp_impl::mpz_raii tmp;
// Set the first limb.
::mpz_set_str(&m.m_mpz, lex_cast(::mp_limb_t(-1) & GMP_NUMB_MASK).c_str(), 10);
for (unsigned i = 1u; i < n; ++i) {
::mpz_set_str(&tmp.m_mpz, lex_cast(::mp_limb_t(-1) & GMP_NUMB_MASK).c_str(), 10);
::mpz_mul_2exp(&m.m_mpz, &m.m_mpz, GMP_NUMB_BITS);
::mpz_add(&m.m_mpz, &m.m_mpz, &tmp.m_mpz);
}
}
}
// A macro for checking that an expression throws a specific exception object satisfying a predicate.
#define REQUIRE_THROWS_PREDICATE(expr, exc, pred) \
{ \
bool thrown_checked = false; \
try { \
(void)expr; \
} catch (const exc &e) { \
if (pred(e)) { \
thrown_checked = true; \
} \
} \
REQUIRE(thrown_checked); \
}
#endif
<commit_msg>Fix the fix.<commit_after>/* Copyright 2009-2016 Francesco Biscani (bluescarni@gmail.com)
This file is part of the mp++ library.
The mp++ library is free software; you can redistribute it and/or modify
it under the terms of either:
* 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.
or
* 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.
or both in parallel, as here.
The mp++ 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 General Public License
for more details.
You should have received copies of the GNU General Public License and the
GNU Lesser General Public License along with the mp++ library. If not,
see https://www.gnu.org/licenses/. */
// std::index_sequence and std::make_index_sequence implementation, from:
// http://stackoverflow.com/questions/17424477/implementation-c14-make-integer-sequence
#ifndef MPPP_TEST_UTILS_HPP
#define MPPP_TEST_UTILS_HPP
#include <cassert>
#include <cstddef>
#include <gmp.h>
#include <initializer_list>
#include <limits>
#include <locale>
#include <mp++.hpp>
#include <random>
#include <sstream>
#include <string>
#include <tuple>
#include <type_traits>
#include <utility>
namespace mppp_test
{
// std::index_sequence and std::make_index_sequence implementation for C++11. These are available
// in the std library in C++14. Implementation taken from:
// http://stackoverflow.com/questions/17424477/implementation-c14-make-integer-sequence
template <std::size_t... Ints>
struct index_sequence {
using type = index_sequence;
using value_type = std::size_t;
static constexpr std::size_t size() noexcept
{
return sizeof...(Ints);
}
};
inline namespace impl
{
template <class Sequence1, class Sequence2>
struct merge_and_renumber;
template <std::size_t... I1, std::size_t... I2>
struct merge_and_renumber<index_sequence<I1...>, index_sequence<I2...>>
: index_sequence<I1..., (sizeof...(I1) + I2)...> {
};
}
template <std::size_t N>
struct make_index_sequence
: merge_and_renumber<typename make_index_sequence<N / 2>::type, typename make_index_sequence<N - N / 2>::type> {
};
template <>
struct make_index_sequence<0> : index_sequence<> {
};
template <>
struct make_index_sequence<1> : index_sequence<0> {
};
inline namespace impl
{
template <typename T, typename F, std::size_t... Is>
void apply_to_each_item(T &&t, const F &f, index_sequence<Is...>)
{
(void)std::initializer_list<int>{0, (void(f(std::get<Is>(std::forward<T>(t)))), 0)...};
}
}
// Tuple for_each(). Execute the functor f on each element of the input Tuple.
// https://isocpp.org/blog/2015/01/for-each-arg-eric-niebler
// https://www.reddit.com/r/cpp/comments/2tffv3/for_each_argumentsean_parent/
// https://www.reddit.com/r/cpp/comments/33b06v/for_each_in_tuple/
template <class Tuple, class F>
void tuple_for_each(Tuple &&t, const F &f)
{
apply_to_each_item(std::forward<Tuple>(t), f,
make_index_sequence<std::tuple_size<typename std::decay<Tuple>::type>::value>{});
}
inline namespace impl
{
template <typename T>
struct is_mp_integer {
static const bool value = false;
};
template <std::size_t SSize>
struct is_mp_integer<mppp::mp_integer<SSize>> {
static const bool value = true;
};
template <typename T, typename std::enable_if<std::is_integral<T>::value && std::is_signed<T>::value, int>::type = 0>
inline long long lex_cast_tr(T n)
{
return static_cast<long long>(n);
}
template <typename T, typename std::enable_if<std::is_integral<T>::value && std::is_unsigned<T>::value, int>::type = 0>
inline unsigned long long lex_cast_tr(T n)
{
return static_cast<unsigned long long>(n);
}
template <typename T, typename std::enable_if<is_mp_integer<T>::value, int>::type = 0>
inline std::string lex_cast_tr(const T &x)
{
return x.to_string();
}
template <typename T, typename std::enable_if<std::is_floating_point<T>::value, int>::type = 0>
inline T lex_cast_tr(const T &x)
{
return x;
}
}
// Lexical cast: retrieve the string representation of input object x.
template <typename T>
inline std::string lex_cast(const T &x)
{
std::ostringstream oss;
oss.imbue(std::locale::classic());
oss << lex_cast_tr(x);
return oss.str();
}
inline std::string lex_cast(const mppp::mppp_impl::mpz_raii &m)
{
return mppp::mppp_impl::mpz_to_str(&m.m_mpz);
}
// Set mpz to random value with n limbs. Top limb is divided by div.
inline void random_integer(mppp::mppp_impl::mpz_raii &m, unsigned n, std::mt19937 &rng, ::mp_limb_t div = 1u)
{
if (!n) {
::mpz_set_ui(&m.m_mpz, 0);
return;
}
static thread_local mppp::mppp_impl::mpz_raii tmp;
std::uniform_int_distribution<::mp_limb_t> dist(0u, std::numeric_limits<::mp_limb_t>::max());
// Set the first limb.
::mpz_set_str(&m.m_mpz, lex_cast((dist(rng) & GMP_NUMB_MASK) / div).c_str(), 10);
for (unsigned i = 1u; i < n; ++i) {
::mpz_set_str(&tmp.m_mpz, lex_cast(dist(rng) & GMP_NUMB_MASK).c_str(), 10);
::mpz_mul_2exp(&m.m_mpz, &m.m_mpz, GMP_NUMB_BITS);
::mpz_add(&m.m_mpz, &m.m_mpz, &tmp.m_mpz);
}
}
// Set mpz to the max value with n limbs.
inline void max_integer(mppp::mppp_impl::mpz_raii &m, unsigned n)
{
if (!n) {
::mpz_set_ui(&m.m_mpz, 0);
return;
}
static thread_local mppp::mppp_impl::mpz_raii tmp;
// Set the first limb.
::mpz_set_str(&m.m_mpz, lex_cast(::mp_limb_t(-1) & GMP_NUMB_MASK).c_str(), 10);
for (unsigned i = 1u; i < n; ++i) {
::mpz_set_str(&tmp.m_mpz, lex_cast(::mp_limb_t(-1) & GMP_NUMB_MASK).c_str(), 10);
::mpz_mul_2exp(&m.m_mpz, &m.m_mpz, GMP_NUMB_BITS);
::mpz_add(&m.m_mpz, &m.m_mpz, &tmp.m_mpz);
}
}
}
// A macro for checking that an expression throws a specific exception object satisfying a predicate.
#define REQUIRE_THROWS_PREDICATE(expr, exc, pred) \
{ \
bool thrown_checked = false; \
try { \
(void)(expr); \
} catch (const exc &e) { \
if (pred(e)) { \
thrown_checked = true; \
} \
} \
REQUIRE(thrown_checked); \
}
#endif
<|endoftext|> |
<commit_before>// Copyright (c) 2012 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 "chrome/browser/extensions/api/declarative/rules_registry_storage_delegate.h"
#include "base/bind.h"
#include "base/metrics/histogram.h"
#include "base/time.h"
#include "chrome/browser/extensions/extension_info_map.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/extension_system.h"
#include "chrome/browser/extensions/state_store.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/chrome_notification_types.h"
#include "chrome/common/extensions/extension.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/notification_details.h"
#include "content/public/browser/notification_source.h"
namespace extensions {
namespace {
scoped_ptr<base::Value> RulesToValue(
const std::vector<linked_ptr<RulesRegistry::Rule> >& rules) {
scoped_ptr<base::ListValue> list(new base::ListValue());
for (size_t i = 0; i < rules.size(); ++i)
list->Append(rules[i]->ToValue().release());
return list.PassAs<base::Value>();
}
std::vector<linked_ptr<RulesRegistry::Rule> > RulesFromValue(
base::Value* value) {
std::vector<linked_ptr<RulesRegistry::Rule> > rules;
base::ListValue* list = NULL;
if (!value || !value->GetAsList(&list))
return rules;
for (size_t i = 0; i < list->GetSize(); ++i) {
base::DictionaryValue* dict = NULL;
if (!list->GetDictionary(i, &dict))
continue;
linked_ptr<RulesRegistry::Rule> rule(new RulesRegistry::Rule());
if (RulesRegistry::Rule::Populate(*dict, rule.get()))
rules.push_back(rule);
}
return rules;
}
} // namespace
// This class coordinates information between the UI and RulesRegistry threads.
// It may outlive the RulesRegistry, which owns the delegate. Methods/variables
// should be used on the UI thread unless otherwise noted.
class RulesRegistryStorageDelegate::Inner
: public content::NotificationObserver,
public base::RefCountedThreadSafe<Inner> {
public:
Inner(Profile* profile,
RulesRegistryWithCache* rules_registry,
const std::string& storage_key);
private:
friend class base::RefCountedThreadSafe<Inner>;
friend class RulesRegistryStorageDelegate;
virtual ~Inner();
// Initialization of the storage delegate if it is used in the context of
// an incognito profile.
void InitForOTRProfile();
// NotificationObserver
virtual void Observe(
int type,
const content::NotificationSource& source,
const content::NotificationDetails& details) OVERRIDE;
// Read/write a list of rules serialized to Values.
void ReadFromStorage(const std::string& extension_id);
void ReadFromStorageCallback(const std::string& extension_id,
scoped_ptr<base::Value> value);
void WriteToStorage(const std::string& extension_id,
scoped_ptr<base::Value> value);
// Check if we are done reading all data from storage on startup, and notify
// the RulesRegistry on its thread if so. The notification is delivered
// exactly once.
void CheckIfReady();
// Deserialize the rules from the given Value object and add them to the
// RulesRegistry.
void ReadFromStorageOnRegistryThread(const std::string& extension_id,
scoped_ptr<base::Value> value);
// Notify the RulesRegistry that we are now ready.
void NotifyReadyOnRegistryThread();
scoped_ptr<content::NotificationRegistrar> registrar_;
Profile* profile_;
// The key under which rules are stored.
const std::string storage_key_;
// A set of extension IDs that have rules we are reading from storage.
std::set<std::string> waiting_for_extensions_;
// The thread that our RulesRegistry lives on.
content::BrowserThread::ID rules_registry_thread_;
// The following are only accessible on rules_registry_thread_.
// The RulesRegistry whose delegate we are.
RulesRegistryWithCache* rules_registry_;
// True when we have finished reading from storage for all extensions that
// are loaded on startup.
bool ready_;
// We measure the time spent on loading rules on init. The result is logged
// with UMA once per the delegate instance, unless in Incognito.
base::Time storage_init_time_;
bool log_storage_init_delay_;
// TODO(vabr): Could |ready_| be used instead of |log_storage_init_delay_|?
// http://crbug.com/176926
};
RulesRegistryStorageDelegate::RulesRegistryStorageDelegate() {
}
RulesRegistryStorageDelegate::~RulesRegistryStorageDelegate() {
// RulesRegistry owns us, which means it has been deleted.
inner_->rules_registry_ = NULL;
}
void RulesRegistryStorageDelegate::InitOnUIThread(
Profile* profile,
RulesRegistryWithCache* rules_registry,
const std::string& storage_key) {
DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
extensions::StateStore* store = ExtensionSystem::Get(profile)->rules_store();
if (store)
store->RegisterKey(storage_key);
inner_ = new Inner(profile, rules_registry, storage_key);
}
void RulesRegistryStorageDelegate::CleanupOnUIThread() {
// The registrar must be deleted on the UI thread.
inner_->registrar_.reset();
inner_->profile_ = NULL; // no longer safe to use.
}
bool RulesRegistryStorageDelegate::IsReady() {
DCHECK(content::BrowserThread::CurrentlyOn(inner_->rules_registry_thread_));
return inner_->ready_;
}
void RulesRegistryStorageDelegate::OnRulesChanged(
RulesRegistryWithCache* rules_registry,
const std::string& extension_id) {
DCHECK(content::BrowserThread::CurrentlyOn(inner_->rules_registry_thread_));
std::vector<linked_ptr<RulesRegistry::Rule> > new_rules;
std::string error = rules_registry->GetAllRules(extension_id, &new_rules);
DCHECK_EQ("", error);
content::BrowserThread::PostTask(
content::BrowserThread::UI, FROM_HERE,
base::Bind(&Inner::WriteToStorage, inner_.get(), extension_id,
base::Passed(RulesToValue(new_rules))));
}
RulesRegistryStorageDelegate::Inner::Inner(
Profile* profile,
RulesRegistryWithCache* rules_registry,
const std::string& storage_key)
: registrar_(new content::NotificationRegistrar()),
profile_(profile),
storage_key_(storage_key),
rules_registry_thread_(rules_registry->GetOwnerThread()),
rules_registry_(rules_registry),
ready_(false),
log_storage_init_delay_(true) {
if (!profile_->IsOffTheRecord()) {
registrar_->Add(this, chrome::NOTIFICATION_EXTENSION_LOADED,
content::Source<Profile>(profile));
registrar_->Add(this, chrome::NOTIFICATION_EXTENSIONS_READY,
content::Source<Profile>(profile));
} else {
log_storage_init_delay_ = false;
registrar_->Add(this, chrome::NOTIFICATION_EXTENSION_LOADED,
content::Source<Profile>(profile->GetOriginalProfile()));
InitForOTRProfile();
}
}
RulesRegistryStorageDelegate::Inner::~Inner() {
DCHECK(!registrar_.get());
}
void RulesRegistryStorageDelegate::Inner::InitForOTRProfile() {
ExtensionService* extension_service =
extensions::ExtensionSystem::Get(profile_)->extension_service();
const ExtensionSet* extensions = extension_service->extensions();
for (ExtensionSet::const_iterator i = extensions->begin();
i != extensions->end(); ++i) {
if (((*i)->HasAPIPermission(APIPermission::kDeclarativeContent) ||
(*i)->HasAPIPermission(APIPermission::kDeclarativeWebRequest)) &&
extension_service->IsIncognitoEnabled((*i)->id()))
ReadFromStorage((*i)->id());
}
ready_ = true;
}
void RulesRegistryStorageDelegate::Inner::Observe(
int type,
const content::NotificationSource& source,
const content::NotificationDetails& details) {
DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
if (type == chrome::NOTIFICATION_EXTENSION_LOADED) {
const extensions::Extension* extension =
content::Details<const extensions::Extension>(details).ptr();
// TODO(mpcomplete): This API check should generalize to any use of
// declarative rules, not just webRequest.
if (extension->HasAPIPermission(APIPermission::kDeclarativeContent) ||
extension->HasAPIPermission(APIPermission::kDeclarativeWebRequest)) {
ExtensionInfoMap* extension_info_map =
ExtensionSystem::Get(profile_)->info_map();
if (profile_->IsOffTheRecord() &&
!extension_info_map->IsIncognitoEnabled(extension->id())) {
// Ignore this extension.
} else {
ReadFromStorage(extension->id());
}
}
} else if (type == chrome::NOTIFICATION_EXTENSIONS_READY) {
CheckIfReady();
}
}
void RulesRegistryStorageDelegate::Inner::ReadFromStorage(
const std::string& extension_id) {
DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
if (!profile_)
return;
if (storage_init_time_.is_null())
storage_init_time_ = base::Time::Now();
extensions::StateStore* store = ExtensionSystem::Get(profile_)->rules_store();
if (store) {
waiting_for_extensions_.insert(extension_id);
store->GetExtensionValue(extension_id, storage_key_,
base::Bind(&Inner::ReadFromStorageCallback, this, extension_id));
}
// TODO(mpcomplete): Migration code. Remove when declarativeWebRequest goes
// to stable.
// http://crbug.com/166474
store = ExtensionSystem::Get(profile_)->state_store();
if (store) {
waiting_for_extensions_.insert(extension_id);
store->GetExtensionValue(extension_id, storage_key_,
base::Bind(&Inner::ReadFromStorageCallback, this, extension_id));
store->RemoveExtensionValue(extension_id, storage_key_);
}
}
void RulesRegistryStorageDelegate::Inner::ReadFromStorageCallback(
const std::string& extension_id, scoped_ptr<base::Value> value) {
DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
content::BrowserThread::PostTask(
rules_registry_thread_, FROM_HERE,
base::Bind(&Inner::ReadFromStorageOnRegistryThread, this, extension_id,
base::Passed(&value)));
waiting_for_extensions_.erase(extension_id);
CheckIfReady();
if (log_storage_init_delay_ && waiting_for_extensions_.empty()) {
UMA_HISTOGRAM_TIMES("Extensions.DeclarativeRulesStorageInitialization",
base::Time::Now() - storage_init_time_);
log_storage_init_delay_ = false;
}
}
void RulesRegistryStorageDelegate::Inner::WriteToStorage(
const std::string& extension_id, scoped_ptr<base::Value> value) {
DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
if (!profile_)
return;
StateStore* store = ExtensionSystem::Get(profile_)->rules_store();
if (store)
store->SetExtensionValue(extension_id, storage_key_, value.Pass());
}
void RulesRegistryStorageDelegate::Inner::CheckIfReady() {
DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
if (!waiting_for_extensions_.empty())
return;
content::BrowserThread::PostTask(
rules_registry_thread_, FROM_HERE,
base::Bind(&Inner::NotifyReadyOnRegistryThread, this));
}
void RulesRegistryStorageDelegate::Inner::ReadFromStorageOnRegistryThread(
const std::string& extension_id, scoped_ptr<base::Value> value) {
DCHECK(content::BrowserThread::CurrentlyOn(rules_registry_thread_));
if (!rules_registry_)
return; // registry went away
rules_registry_->AddRules(extension_id, RulesFromValue(value.get()));
}
void RulesRegistryStorageDelegate::Inner::NotifyReadyOnRegistryThread() {
DCHECK(content::BrowserThread::CurrentlyOn(rules_registry_thread_));
if (ready_)
return; // we've already notified our readiness
ready_ = true;
rules_registry_->OnReady();
}
} // namespace extensions
<commit_msg>Hold RulesRegistryStorageDelegate::Inner in scoped_refptr when posting tasks<commit_after>// Copyright (c) 2012 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 "chrome/browser/extensions/api/declarative/rules_registry_storage_delegate.h"
#include "base/bind.h"
#include "base/metrics/histogram.h"
#include "base/time.h"
#include "chrome/browser/extensions/extension_info_map.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/extension_system.h"
#include "chrome/browser/extensions/state_store.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/chrome_notification_types.h"
#include "chrome/common/extensions/extension.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/notification_details.h"
#include "content/public/browser/notification_source.h"
namespace extensions {
namespace {
scoped_ptr<base::Value> RulesToValue(
const std::vector<linked_ptr<RulesRegistry::Rule> >& rules) {
scoped_ptr<base::ListValue> list(new base::ListValue());
for (size_t i = 0; i < rules.size(); ++i)
list->Append(rules[i]->ToValue().release());
return list.PassAs<base::Value>();
}
std::vector<linked_ptr<RulesRegistry::Rule> > RulesFromValue(
base::Value* value) {
std::vector<linked_ptr<RulesRegistry::Rule> > rules;
base::ListValue* list = NULL;
if (!value || !value->GetAsList(&list))
return rules;
for (size_t i = 0; i < list->GetSize(); ++i) {
base::DictionaryValue* dict = NULL;
if (!list->GetDictionary(i, &dict))
continue;
linked_ptr<RulesRegistry::Rule> rule(new RulesRegistry::Rule());
if (RulesRegistry::Rule::Populate(*dict, rule.get()))
rules.push_back(rule);
}
return rules;
}
} // namespace
// This class coordinates information between the UI and RulesRegistry threads.
// It may outlive the RulesRegistry, which owns the delegate. Methods/variables
// should be used on the UI thread unless otherwise noted.
class RulesRegistryStorageDelegate::Inner
: public content::NotificationObserver,
public base::RefCountedThreadSafe<Inner> {
public:
Inner(Profile* profile,
RulesRegistryWithCache* rules_registry,
const std::string& storage_key);
private:
friend class base::RefCountedThreadSafe<Inner>;
friend class RulesRegistryStorageDelegate;
virtual ~Inner();
// Initialization of the storage delegate if it is used in the context of
// an incognito profile.
void InitForOTRProfile();
// NotificationObserver
virtual void Observe(
int type,
const content::NotificationSource& source,
const content::NotificationDetails& details) OVERRIDE;
// Read/write a list of rules serialized to Values.
void ReadFromStorage(const std::string& extension_id);
void ReadFromStorageCallback(const std::string& extension_id,
scoped_ptr<base::Value> value);
void WriteToStorage(const std::string& extension_id,
scoped_ptr<base::Value> value);
// Check if we are done reading all data from storage on startup, and notify
// the RulesRegistry on its thread if so. The notification is delivered
// exactly once.
void CheckIfReady();
// Deserialize the rules from the given Value object and add them to the
// RulesRegistry.
void ReadFromStorageOnRegistryThread(const std::string& extension_id,
scoped_ptr<base::Value> value);
// Notify the RulesRegistry that we are now ready.
void NotifyReadyOnRegistryThread();
scoped_ptr<content::NotificationRegistrar> registrar_;
Profile* profile_;
// The key under which rules are stored.
const std::string storage_key_;
// A set of extension IDs that have rules we are reading from storage.
std::set<std::string> waiting_for_extensions_;
// The thread that our RulesRegistry lives on.
content::BrowserThread::ID rules_registry_thread_;
// The following are only accessible on rules_registry_thread_.
// The RulesRegistry whose delegate we are.
RulesRegistryWithCache* rules_registry_;
// True when we have finished reading from storage for all extensions that
// are loaded on startup.
bool ready_;
// We measure the time spent on loading rules on init. The result is logged
// with UMA once per the delegate instance, unless in Incognito.
base::Time storage_init_time_;
bool log_storage_init_delay_;
// TODO(vabr): Could |ready_| be used instead of |log_storage_init_delay_|?
// http://crbug.com/176926
};
RulesRegistryStorageDelegate::RulesRegistryStorageDelegate() {
}
RulesRegistryStorageDelegate::~RulesRegistryStorageDelegate() {
// RulesRegistry owns us, which means it has been deleted.
inner_->rules_registry_ = NULL;
}
void RulesRegistryStorageDelegate::InitOnUIThread(
Profile* profile,
RulesRegistryWithCache* rules_registry,
const std::string& storage_key) {
DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
extensions::StateStore* store = ExtensionSystem::Get(profile)->rules_store();
if (store)
store->RegisterKey(storage_key);
inner_ = new Inner(profile, rules_registry, storage_key);
}
void RulesRegistryStorageDelegate::CleanupOnUIThread() {
// The registrar must be deleted on the UI thread.
inner_->registrar_.reset();
inner_->profile_ = NULL; // no longer safe to use.
}
bool RulesRegistryStorageDelegate::IsReady() {
DCHECK(content::BrowserThread::CurrentlyOn(inner_->rules_registry_thread_));
return inner_->ready_;
}
void RulesRegistryStorageDelegate::OnRulesChanged(
RulesRegistryWithCache* rules_registry,
const std::string& extension_id) {
DCHECK(content::BrowserThread::CurrentlyOn(inner_->rules_registry_thread_));
std::vector<linked_ptr<RulesRegistry::Rule> > new_rules;
std::string error = rules_registry->GetAllRules(extension_id, &new_rules);
DCHECK_EQ("", error);
content::BrowserThread::PostTask(
content::BrowserThread::UI, FROM_HERE,
base::Bind(&Inner::WriteToStorage, inner_, extension_id,
base::Passed(RulesToValue(new_rules))));
}
RulesRegistryStorageDelegate::Inner::Inner(
Profile* profile,
RulesRegistryWithCache* rules_registry,
const std::string& storage_key)
: registrar_(new content::NotificationRegistrar()),
profile_(profile),
storage_key_(storage_key),
rules_registry_thread_(rules_registry->GetOwnerThread()),
rules_registry_(rules_registry),
ready_(false),
log_storage_init_delay_(true) {
if (!profile_->IsOffTheRecord()) {
registrar_->Add(this, chrome::NOTIFICATION_EXTENSION_LOADED,
content::Source<Profile>(profile));
registrar_->Add(this, chrome::NOTIFICATION_EXTENSIONS_READY,
content::Source<Profile>(profile));
} else {
log_storage_init_delay_ = false;
registrar_->Add(this, chrome::NOTIFICATION_EXTENSION_LOADED,
content::Source<Profile>(profile->GetOriginalProfile()));
InitForOTRProfile();
}
}
RulesRegistryStorageDelegate::Inner::~Inner() {
DCHECK(!registrar_.get());
}
void RulesRegistryStorageDelegate::Inner::InitForOTRProfile() {
ExtensionService* extension_service =
extensions::ExtensionSystem::Get(profile_)->extension_service();
const ExtensionSet* extensions = extension_service->extensions();
for (ExtensionSet::const_iterator i = extensions->begin();
i != extensions->end(); ++i) {
if (((*i)->HasAPIPermission(APIPermission::kDeclarativeContent) ||
(*i)->HasAPIPermission(APIPermission::kDeclarativeWebRequest)) &&
extension_service->IsIncognitoEnabled((*i)->id()))
ReadFromStorage((*i)->id());
}
ready_ = true;
}
void RulesRegistryStorageDelegate::Inner::Observe(
int type,
const content::NotificationSource& source,
const content::NotificationDetails& details) {
DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
if (type == chrome::NOTIFICATION_EXTENSION_LOADED) {
const extensions::Extension* extension =
content::Details<const extensions::Extension>(details).ptr();
// TODO(mpcomplete): This API check should generalize to any use of
// declarative rules, not just webRequest.
if (extension->HasAPIPermission(APIPermission::kDeclarativeContent) ||
extension->HasAPIPermission(APIPermission::kDeclarativeWebRequest)) {
ExtensionInfoMap* extension_info_map =
ExtensionSystem::Get(profile_)->info_map();
if (profile_->IsOffTheRecord() &&
!extension_info_map->IsIncognitoEnabled(extension->id())) {
// Ignore this extension.
} else {
ReadFromStorage(extension->id());
}
}
} else if (type == chrome::NOTIFICATION_EXTENSIONS_READY) {
CheckIfReady();
}
}
void RulesRegistryStorageDelegate::Inner::ReadFromStorage(
const std::string& extension_id) {
DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
if (!profile_)
return;
if (storage_init_time_.is_null())
storage_init_time_ = base::Time::Now();
extensions::StateStore* store = ExtensionSystem::Get(profile_)->rules_store();
if (store) {
waiting_for_extensions_.insert(extension_id);
store->GetExtensionValue(extension_id,
storage_key_,
base::Bind(&Inner::ReadFromStorageCallback,
make_scoped_refptr(this),
extension_id));
}
// TODO(mpcomplete): Migration code. Remove when declarativeWebRequest goes
// to stable.
// http://crbug.com/166474
store = ExtensionSystem::Get(profile_)->state_store();
if (store) {
waiting_for_extensions_.insert(extension_id);
store->GetExtensionValue(extension_id,
storage_key_,
base::Bind(&Inner::ReadFromStorageCallback,
make_scoped_refptr(this),
extension_id));
store->RemoveExtensionValue(extension_id, storage_key_);
}
}
void RulesRegistryStorageDelegate::Inner::ReadFromStorageCallback(
const std::string& extension_id, scoped_ptr<base::Value> value) {
DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
content::BrowserThread::PostTask(
rules_registry_thread_,
FROM_HERE,
base::Bind(&Inner::ReadFromStorageOnRegistryThread,
make_scoped_refptr(this),
extension_id,
base::Passed(&value)));
waiting_for_extensions_.erase(extension_id);
CheckIfReady();
if (log_storage_init_delay_ && waiting_for_extensions_.empty()) {
UMA_HISTOGRAM_TIMES("Extensions.DeclarativeRulesStorageInitialization",
base::Time::Now() - storage_init_time_);
log_storage_init_delay_ = false;
}
}
void RulesRegistryStorageDelegate::Inner::WriteToStorage(
const std::string& extension_id, scoped_ptr<base::Value> value) {
DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
if (!profile_)
return;
StateStore* store = ExtensionSystem::Get(profile_)->rules_store();
if (store)
store->SetExtensionValue(extension_id, storage_key_, value.Pass());
}
void RulesRegistryStorageDelegate::Inner::CheckIfReady() {
DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
if (!waiting_for_extensions_.empty())
return;
content::BrowserThread::PostTask(
rules_registry_thread_,
FROM_HERE,
base::Bind(&Inner::NotifyReadyOnRegistryThread,
make_scoped_refptr(this)));
}
void RulesRegistryStorageDelegate::Inner::ReadFromStorageOnRegistryThread(
const std::string& extension_id, scoped_ptr<base::Value> value) {
DCHECK(content::BrowserThread::CurrentlyOn(rules_registry_thread_));
if (!rules_registry_)
return; // registry went away
rules_registry_->AddRules(extension_id, RulesFromValue(value.get()));
}
void RulesRegistryStorageDelegate::Inner::NotifyReadyOnRegistryThread() {
DCHECK(content::BrowserThread::CurrentlyOn(rules_registry_thread_));
if (ready_)
return; // we've already notified our readiness
ready_ = true;
if (!rules_registry_)
return; // registry went away
rules_registry_->OnReady();
}
} // namespace extensions
<|endoftext|> |
<commit_before>/*
* Copyright 2014 CyberVision, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "kaa/configuration/ConfigurationTransport.hpp"
#include <utility>
#include "kaa/configuration/IConfigurationProcessor.hpp"
#include "kaa/configuration/IConfigurationHashContainer.hpp"
#ifdef KAA_USE_CONFIGURATION
#include "kaa/logging/Log.hpp"
namespace kaa {
ConfigurationTransport::ConfigurationTransport(IKaaChannelManager& channelManager, IKaaClientStateStoragePtr status)
: AbstractKaaTransport(channelManager)
, configurationProcessor_(nullptr)
, hashContainer_(nullptr)
{
setClientState(status);
}
void ConfigurationTransport::sync()
{
syncByType();
}
std::shared_ptr<ConfigurationSyncRequest> ConfigurationTransport::createConfigurationRequest()
{
if (!clientStatus_ || !hashContainer_) {
throw KaaException("Can not generate ConfigurationSyncRequest: configuration transport is not initialized");
}
std::shared_ptr<ConfigurationSyncRequest> request(new ConfigurationSyncRequest);
request->appStateSeqNumber = clientStatus_->getConfigurationSequenceNumber();
request->configurationHash.set_bytes(hashContainer_->getConfigurationHash());
request->resyncOnly.set_bool(true); // Only full resyncs are currently supported
return request;
}
void ConfigurationTransport::onConfigurationResponse(const ConfigurationSyncResponse &response)
{
if (response.responseStatus != SyncResponseStatus::NO_DELTA) {
clientStatus_->setConfigurationSequenceNumber(response.appStateSeqNumber);
if (configurationProcessor_ && !response.confDeltaBody.is_null()) {
configurationProcessor_->processConfigurationData(response.confDeltaBody.get_bytes()
, response.responseStatus == SyncResponseStatus::RESYNC);
}
syncAck();
}
}
} // namespace kaa
#endif
<commit_msg>KAA-753: Update an application sequence number disregarding of configuration sync response status.<commit_after>/*
* Copyright 2014 CyberVision, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "kaa/configuration/ConfigurationTransport.hpp"
#include <utility>
#include "kaa/configuration/IConfigurationProcessor.hpp"
#include "kaa/configuration/IConfigurationHashContainer.hpp"
#ifdef KAA_USE_CONFIGURATION
#include "kaa/logging/Log.hpp"
namespace kaa {
ConfigurationTransport::ConfigurationTransport(IKaaChannelManager& channelManager, IKaaClientStateStoragePtr status)
: AbstractKaaTransport(channelManager)
, configurationProcessor_(nullptr)
, hashContainer_(nullptr)
{
setClientState(status);
}
void ConfigurationTransport::sync()
{
syncByType();
}
std::shared_ptr<ConfigurationSyncRequest> ConfigurationTransport::createConfigurationRequest()
{
if (!clientStatus_ || !hashContainer_) {
throw KaaException("Can not generate ConfigurationSyncRequest: configuration transport is not initialized");
}
std::shared_ptr<ConfigurationSyncRequest> request(new ConfigurationSyncRequest);
request->appStateSeqNumber = clientStatus_->getConfigurationSequenceNumber();
request->configurationHash.set_bytes(hashContainer_->getConfigurationHash());
request->resyncOnly.set_bool(true); // Only full resyncs are currently supported
return request;
}
void ConfigurationTransport::onConfigurationResponse(const ConfigurationSyncResponse &response)
{
clientStatus_->setConfigurationSequenceNumber(response.appStateSeqNumber);
if (configurationProcessor_ && !response.confDeltaBody.is_null()) {
configurationProcessor_->processConfigurationData(response.confDeltaBody.get_bytes()
, response.responseStatus == SyncResponseStatus::RESYNC);
}
syncAck();
}
} // namespace kaa
#endif
<|endoftext|> |
<commit_before>/******************************************************************
*
* Round for C
*
* Copyright (C) Satoshi Konno 2015
*
* This is licensed under BSD-style license, see file COPYING.
*
******************************************************************/
#include <boost/test/unit_test.hpp>
#include <string>
#include <round/script/python.h>
#include "ScriptTestController.h"
#if defined(ROUND_SUPPORT_PYTHON)
BOOST_AUTO_TEST_SUITE(script)
BOOST_AUTO_TEST_CASE(PythonEngineEcho)
{
#define SCRIPT_ECHO_LOOP 1
#define PY_ECHO_FUNC "echo"
#define PY_ECHO_PARAM "hello"
const std::string PY_ECHO_CODE = "def " PY_ECHO_FUNC "(params):\n"
" return params\n";
RoundPythonEngine* pyEngine = round_python_engine_new();
RoundMethod* method = round_method_new();
round_method_setname(method, PY_ECHO_FUNC);
round_method_setcode(method, (byte*)PY_ECHO_CODE.c_str(), PY_ECHO_CODE.size());
RoundString* result = round_string_new();
RoundError* err = round_error_new();
BOOST_CHECK(pyEngine);
for (int n = 0; n < SCRIPT_ECHO_LOOP; n++) {
BOOST_CHECK(round_python_engine_lock(pyEngine));
BOOST_CHECK(round_python_engine_run(pyEngine, method, PY_ECHO_PARAM, result, err));
BOOST_CHECK(round_streq(PY_ECHO_PARAM, round_string_getvalue(result)));
BOOST_CHECK(round_python_engine_unlock(pyEngine));
}
BOOST_CHECK(round_method_delete(method));
BOOST_CHECK(round_string_delete(result));
BOOST_CHECK(round_error_delete(err));
BOOST_CHECK(round_python_engine_delete(pyEngine));
}
BOOST_AUTO_TEST_CASE(PythonRegistryMethods)
{
static const char* SETKEY_CODE = "function " SET_KEY_NAME "(params) {return " ROUND_SYSTEM_METHOD_SET_REGISTRY "(params);}";
static const char* GETKEY_CODE = "function " GET_KEY_NAME "(params) {return " ROUND_SYSTEM_METHOD_GET_REGISTRY "(params);}";
static const char* REMOVEKEY_CODE = "function " REMOVE_KEY_NAME "(params) {return " ROUND_SYSTEM_METHOD_REMOVE_REGISTRY "(params);}";
RoundLocalNode* node = round_local_node_new();
BOOST_CHECK(round_local_node_start(node));
RoundError* err = round_error_new();
// Post Node Message (Set '*_key' method)
BOOST_CHECK(round_node_setmethod((RoundNode*)node, ROUND_SCRIPT_LANGUAGE_PYTHON, SET_KEY_NAME, SETKEY_CODE, err));
BOOST_CHECK(round_node_setmethod((RoundNode*)node, ROUND_SCRIPT_LANGUAGE_PYTHON, GET_KEY_NAME, GETKEY_CODE, err));
BOOST_CHECK(round_node_setmethod((RoundNode*)node, ROUND_SCRIPT_LANGUAGE_PYTHON, REMOVE_KEY_NAME, REMOVEKEY_CODE, err));
// Post Node Message (Run 'set_key' method)
Round::Test::ScriptTestController scriptTestCtrl;
scriptTestCtrl.runScriptRegistryMethodTest(node);
// Clean up
BOOST_CHECK(round_error_delete(err));
BOOST_CHECK(round_local_node_stop(node));
BOOST_CHECK(round_local_node_delete(node));
}
BOOST_AUTO_TEST_SUITE_END()
#endif
<commit_msg>* Updated pyton functions.<commit_after>/******************************************************************
*
* Round for C
*
* Copyright (C) Satoshi Konno 2015
*
* This is licensed under BSD-style license, see file COPYING.
*
******************************************************************/
#include <boost/test/unit_test.hpp>
#include <string>
#include <round/script/python.h>
#include "ScriptTestController.h"
#if defined(ROUND_SUPPORT_PYTHON)
BOOST_AUTO_TEST_SUITE(script)
BOOST_AUTO_TEST_SUITE(python)
BOOST_AUTO_TEST_CASE(PythonEngineEcho)
{
#define SCRIPT_ECHO_LOOP 1
#define PY_ECHO_FUNC "echo"
#define PY_ECHO_PARAM "hello"
const std::string PY_ECHO_CODE = "def " PY_ECHO_FUNC "(params):\n"
" return params\n";
RoundPythonEngine* pyEngine = round_python_engine_new();
RoundMethod* method = round_method_new();
round_method_setname(method, PY_ECHO_FUNC);
round_method_setcode(method, (byte*)PY_ECHO_CODE.c_str(), PY_ECHO_CODE.size());
RoundString* result = round_string_new();
RoundError* err = round_error_new();
BOOST_CHECK(pyEngine);
for (int n = 0; n < SCRIPT_ECHO_LOOP; n++) {
BOOST_CHECK(round_python_engine_lock(pyEngine));
BOOST_CHECK(round_python_engine_run(pyEngine, method, PY_ECHO_PARAM, result, err));
BOOST_CHECK(round_streq(PY_ECHO_PARAM, round_string_getvalue(result)));
BOOST_CHECK(round_python_engine_unlock(pyEngine));
}
BOOST_CHECK(round_method_delete(method));
BOOST_CHECK(round_string_delete(result));
BOOST_CHECK(round_error_delete(err));
BOOST_CHECK(round_python_engine_delete(pyEngine));
}
#define ROUND_SYSTEM_METHOD_PARAM_KEY "key"
#define ROUND_SYSTEM_METHOD_PARAM_VALUE "val"
BOOST_AUTO_TEST_CASE(PythonRegistryMethods)
{
static const char* SETKEY_CODE = \
"import json\n" \
"def " SET_KEY_NAME "(jsonParams):\n" \
" params = json.loads(jsonParams)\n" \
" return " ROUND_SYSTEM_METHOD_SET_REGISTRY "(params[\"" ROUND_SYSTEM_METHOD_PARAM_KEY "\"], params[\"" ROUND_SYSTEM_METHOD_PARAM_VALUE "\"])";
static const char* GETKEY_CODE = \
"import json\n" \
"def " SET_KEY_NAME "(jsonParams):\n" \
" params = json.loads(jsonParams)\n" \
" return " ROUND_SYSTEM_METHOD_GET_REGISTRY "(params[\"" ROUND_SYSTEM_METHOD_PARAM_KEY "\"])";
static const char* REMOVEKEY_CODE = \
"import json\n" \
"def " SET_KEY_NAME "(jsonParams):\n" \
" params = json.loads(jsonParams)\n" \
" return " ROUND_SYSTEM_METHOD_REMOVE_REGISTRY "(params[\"" ROUND_SYSTEM_METHOD_PARAM_KEY "\"])";
RoundLocalNode* node = round_local_node_new();
BOOST_CHECK(round_local_node_start(node));
RoundError* err = round_error_new();
// Post Node Message (Set '*_key' method)
BOOST_CHECK(round_node_setmethod((RoundNode*)node, ROUND_SCRIPT_LANGUAGE_PYTHON, SET_KEY_NAME, SETKEY_CODE, err));
BOOST_CHECK(round_node_setmethod((RoundNode*)node, ROUND_SCRIPT_LANGUAGE_PYTHON, GET_KEY_NAME, GETKEY_CODE, err));
BOOST_CHECK(round_node_setmethod((RoundNode*)node, ROUND_SCRIPT_LANGUAGE_PYTHON, REMOVE_KEY_NAME, REMOVEKEY_CODE, err));
// Post Node Message (Run 'set_key' method)
Round::Test::ScriptTestController scriptTestCtrl;
scriptTestCtrl.runScriptRegistryMethodTest(node);
// Clean up
BOOST_CHECK(round_error_delete(err));
BOOST_CHECK(round_local_node_stop(node));
BOOST_CHECK(round_local_node_delete(node));
}
BOOST_AUTO_TEST_SUITE_END()
BOOST_AUTO_TEST_SUITE_END()
#endif
<|endoftext|> |
<commit_before>// Copyright (c) 2010-2020, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-806117.
//
// This file is part of the MFEM library. For more information and source code
// availability visit https://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.
#include "mfem.hpp"
#include "unit_tests.hpp"
namespace mfem
{
static void TestSolve(FiniteElementSpace &fespace);
// Check basic functioning of variable order spaces, hp interpolation and
// some corner cases.
//
TEST_CASE("Variable Order FiniteElementSpace",
"[FiniteElementCollection]"
"[FiniteElementSpace]"
"[NCMesh]")
{
SECTION("Quad mesh")
{
// 2-element quad mesh
Mesh mesh(2, 1, Element::QUADRILATERAL);
mesh.EnsureNCMesh();
// standard H1 space with order 1 elements
H1_FECollection fec(1, mesh.Dimension());
FiniteElementSpace fespace(&mesh, &fec);
REQUIRE(fespace.GetNDofs() == 6);
REQUIRE(fespace.GetNConformingDofs() == 6);
// convert to variable order space: p-refine second element
fespace.SetElementOrder(1, 2);
fespace.Update(false);
REQUIRE(fespace.GetNDofs() == 11);
REQUIRE(fespace.GetNConformingDofs() == 10);
// h-refine first element in the y axis
Array<Refinement> refs;
refs.Append(Refinement(0, 2));
mesh.GeneralRefinement(refs);
fespace.Update();
REQUIRE(fespace.GetNDofs() == 13);
REQUIRE(fespace.GetNConformingDofs() == 11);
// relax the master edge to be quadratic
fespace.SetRelaxedHpConformity(true);
REQUIRE(fespace.GetNDofs() == 13);
REQUIRE(fespace.GetNConformingDofs() == 12);
// increase order
for (int i = 0; i < mesh.GetNE(); i++)
{
fespace.SetElementOrder(i, fespace.GetElementOrder(i) + 1);
}
fespace.Update(false);
// 15 quadratic + 16 cubic DOFs - 2 shared vertices:
REQUIRE(fespace.GetNDofs() == 29);
// 3 constrained DOFs on slave side, inexact interpolation
REQUIRE(fespace.GetNConformingDofs() == 26);
// relaxed off
fespace.SetRelaxedHpConformity(false);
// new quadratic DOF on master edge:
REQUIRE(fespace.GetNDofs() == 30);
// 3 constrained DOFs on slave side, 2 on master side:
REQUIRE(fespace.GetNConformingDofs() == 25);
TestSolve(fespace);
// refine
mesh.UniformRefinement();
fespace.Update();
REQUIRE(fespace.GetNDofs() == 93);
REQUIRE(fespace.GetNConformingDofs() == 83);
TestSolve(fespace);
}
SECTION("Hex mesh")
{
// 2-element hex mesh
Mesh mesh(2, 1, 1, Element::HEXAHEDRON);
mesh.EnsureNCMesh();
// standard H1 space with order 1 elements
H1_FECollection fec(1, mesh.Dimension());
FiniteElementSpace fespace(&mesh, &fec);
REQUIRE(fespace.GetNDofs() == 12);
REQUIRE(fespace.GetNConformingDofs() == 12);
// convert to variable order space: p-refine second element
fespace.SetElementOrder(1, 2);
fespace.Update(false);
REQUIRE(fespace.GetNDofs() == 31);
REQUIRE(fespace.GetNConformingDofs() == 26);
// h-refine first element in the z axis
Array<Refinement> refs;
refs.Append(Refinement(0, 4));
mesh.GeneralRefinement(refs);
fespace.Update();
REQUIRE(fespace.GetNDofs() == 35);
REQUIRE(fespace.GetNConformingDofs() == 28);
// relax the master face to be quadratic
fespace.SetRelaxedHpConformity(true);
REQUIRE(fespace.GetNDofs() == 35);
REQUIRE(fespace.GetNConformingDofs() == 31);
// increase order
for (int i = 0; i < mesh.GetNE(); i++)
{
fespace.SetElementOrder(i, fespace.GetElementOrder(i) + 1);
}
fespace.Update(false);
REQUIRE(fespace.GetNDofs() == 105);
REQUIRE(fespace.GetNConformingDofs() == 92);
// relaxed off
fespace.SetRelaxedHpConformity(false);
REQUIRE(fespace.GetNDofs() == 108);
REQUIRE(fespace.GetNConformingDofs() == 87);
// refine one of the small elements into four
refs[0].ref_type = 3;
mesh.GeneralRefinement(refs);
fespace.Update();
REQUIRE(fespace.GetNDofs() == 162);
REQUIRE(fespace.GetNConformingDofs() == 115);
TestSolve(fespace);
// lower the order of one of the four new elements to 1 - this minimum
// order will propagate through two master faces and severely constrain
// the space (since relaxed hp is off)
fespace.SetElementOrder(0, 1);
fespace.Update(false);
REQUIRE(fespace.GetNDofs() == 152);
REQUIRE(fespace.GetNConformingDofs() == 92);
}
SECTION("Prism mesh")
{
// 2-element prism mesh
Mesh mesh(1, 1, 1, Element::WEDGE);
mesh.EnsureNCMesh();
// standard H1 space with order 2 elements
H1_FECollection fec(2, mesh.Dimension());
FiniteElementSpace fespace(&mesh, &fec);
REQUIRE(fespace.GetNDofs() == 27);
REQUIRE(fespace.GetNConformingDofs() == 27);
// convert to variable order space: p-refine first element
fespace.SetElementOrder(0, 3);
fespace.Update(false);
REQUIRE(fespace.GetNDofs() == 54);
REQUIRE(fespace.GetNConformingDofs() == 42);
// refine to form an edge-face constraint similar to
// https://github.com/mfem/mfem/pull/713#issuecomment-495786362
Array<Refinement> refs;
refs.Append(Refinement(1, 3));
mesh.GeneralRefinement(refs);
fespace.Update(false);
refs[0].ref_type = 4;
refs.Append(Refinement(2, 4));
mesh.GeneralRefinement(refs);
fespace.Update(false);
REQUIRE(fespace.GetNDofs() == 113);
REQUIRE(fespace.GetNConformingDofs() == 67);
TestSolve(fespace);
}
}
// Exact solution: x^2 + y^2 + z^2
static double exact_sln(const Vector &p)
{
double x = p(0), y = p(1);
if (p.Size() == 3)
{
double z = p(2);
return x*x + y*y + z*z;
}
else
{
return x*x + y*y;
}
}
static double exact_rhs(const Vector &p)
{
return (p.Size() == 3) ? -6.0 : -4.0;
}
static void TestSolve(FiniteElementSpace &fespace)
{
Mesh *mesh = fespace.GetMesh();
// exact solution and RHS for the problem -\Delta u = 1
FunctionCoefficient exsol(exact_sln);
FunctionCoefficient rhs(exact_rhs);
// set up Dirichlet BC on the boundary
Array<int> ess_attr(mesh->bdr_attributes.Max());
ess_attr = 1;
Array<int> ess_tdof_list;
fespace.GetEssentialTrueDofs(ess_attr, ess_tdof_list);
GridFunction x(&fespace);
x = 0.0;
x.ProjectBdrCoefficient(exsol, ess_attr);
// assemble the linear form
LinearForm lf(&fespace);
lf.AddDomainIntegrator(new DomainLFIntegrator(rhs));
lf.Assemble();
// assemble the bilinear form.
BilinearForm bf(&fespace);
bf.AddDomainIntegrator(new DiffusionIntegrator());
bf.Assemble();
OperatorPtr A;
Vector B, X;
bf.FormLinearSystem(ess_tdof_list, x, lf, A, X, B);
// solve
GSSmoother M((SparseMatrix&)(*A));
PCG(*A, M, B, X, 0, 500, 1e-30, 0.0);
bf.RecoverFEMSolution(X, lf, x);
// compute L2 error from the exact solution
double error = x.ComputeL2Error(exsol);
REQUIRE(error == MFEM_Approx(0.0));
// visualize
#ifdef MFEM_UNIT_DEBUG_VISUALIZE
const char vishost[] = "localhost";
const int visport = 19916;
GridFunction *vis_x = ProlongToMaxOrder(&x);
socketstream sol_sock(vishost, visport);
sol_sock.precision(8);
sol_sock << "solution\n" << *mesh << *vis_x;
delete vis_x;
#endif
}
}
<commit_msg>Fix deprecations in unit tests<commit_after>// Copyright (c) 2010-2020, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-806117.
//
// This file is part of the MFEM library. For more information and source code
// availability visit https://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.
#include "mfem.hpp"
#include "unit_tests.hpp"
namespace mfem
{
static void TestSolve(FiniteElementSpace &fespace);
// Check basic functioning of variable order spaces, hp interpolation and
// some corner cases.
//
TEST_CASE("Variable Order FiniteElementSpace",
"[FiniteElementCollection]"
"[FiniteElementSpace]"
"[NCMesh]")
{
SECTION("Quad mesh")
{
// 2-element quad mesh
Mesh mesh = Mesh::MakeCartesian2D(2, 1, Element::QUADRILATERAL);
mesh.EnsureNCMesh();
// standard H1 space with order 1 elements
H1_FECollection fec(1, mesh.Dimension());
FiniteElementSpace fespace(&mesh, &fec);
REQUIRE(fespace.GetNDofs() == 6);
REQUIRE(fespace.GetNConformingDofs() == 6);
// convert to variable order space: p-refine second element
fespace.SetElementOrder(1, 2);
fespace.Update(false);
REQUIRE(fespace.GetNDofs() == 11);
REQUIRE(fespace.GetNConformingDofs() == 10);
// h-refine first element in the y axis
Array<Refinement> refs;
refs.Append(Refinement(0, 2));
mesh.GeneralRefinement(refs);
fespace.Update();
REQUIRE(fespace.GetNDofs() == 13);
REQUIRE(fespace.GetNConformingDofs() == 11);
// relax the master edge to be quadratic
fespace.SetRelaxedHpConformity(true);
REQUIRE(fespace.GetNDofs() == 13);
REQUIRE(fespace.GetNConformingDofs() == 12);
// increase order
for (int i = 0; i < mesh.GetNE(); i++)
{
fespace.SetElementOrder(i, fespace.GetElementOrder(i) + 1);
}
fespace.Update(false);
// 15 quadratic + 16 cubic DOFs - 2 shared vertices:
REQUIRE(fespace.GetNDofs() == 29);
// 3 constrained DOFs on slave side, inexact interpolation
REQUIRE(fespace.GetNConformingDofs() == 26);
// relaxed off
fespace.SetRelaxedHpConformity(false);
// new quadratic DOF on master edge:
REQUIRE(fespace.GetNDofs() == 30);
// 3 constrained DOFs on slave side, 2 on master side:
REQUIRE(fespace.GetNConformingDofs() == 25);
TestSolve(fespace);
// refine
mesh.UniformRefinement();
fespace.Update();
REQUIRE(fespace.GetNDofs() == 93);
REQUIRE(fespace.GetNConformingDofs() == 83);
TestSolve(fespace);
}
SECTION("Hex mesh")
{
// 2-element hex mesh
Mesh mesh = Mesh::MakeCartesian3D(2, 1, 1, Element::HEXAHEDRON);
mesh.EnsureNCMesh();
// standard H1 space with order 1 elements
H1_FECollection fec(1, mesh.Dimension());
FiniteElementSpace fespace(&mesh, &fec);
REQUIRE(fespace.GetNDofs() == 12);
REQUIRE(fespace.GetNConformingDofs() == 12);
// convert to variable order space: p-refine second element
fespace.SetElementOrder(1, 2);
fespace.Update(false);
REQUIRE(fespace.GetNDofs() == 31);
REQUIRE(fespace.GetNConformingDofs() == 26);
// h-refine first element in the z axis
Array<Refinement> refs;
refs.Append(Refinement(0, 4));
mesh.GeneralRefinement(refs);
fespace.Update();
REQUIRE(fespace.GetNDofs() == 35);
REQUIRE(fespace.GetNConformingDofs() == 28);
// relax the master face to be quadratic
fespace.SetRelaxedHpConformity(true);
REQUIRE(fespace.GetNDofs() == 35);
REQUIRE(fespace.GetNConformingDofs() == 31);
// increase order
for (int i = 0; i < mesh.GetNE(); i++)
{
fespace.SetElementOrder(i, fespace.GetElementOrder(i) + 1);
}
fespace.Update(false);
REQUIRE(fespace.GetNDofs() == 105);
REQUIRE(fespace.GetNConformingDofs() == 92);
// relaxed off
fespace.SetRelaxedHpConformity(false);
REQUIRE(fespace.GetNDofs() == 108);
REQUIRE(fespace.GetNConformingDofs() == 87);
// refine one of the small elements into four
refs[0].ref_type = 3;
mesh.GeneralRefinement(refs);
fespace.Update();
REQUIRE(fespace.GetNDofs() == 162);
REQUIRE(fespace.GetNConformingDofs() == 115);
TestSolve(fespace);
// lower the order of one of the four new elements to 1 - this minimum
// order will propagate through two master faces and severely constrain
// the space (since relaxed hp is off)
fespace.SetElementOrder(0, 1);
fespace.Update(false);
REQUIRE(fespace.GetNDofs() == 152);
REQUIRE(fespace.GetNConformingDofs() == 92);
}
SECTION("Prism mesh")
{
// 2-element prism mesh
Mesh mesh = Mesh::MakeCartesian3D(1, 1, 1, Element::WEDGE);
mesh.EnsureNCMesh();
// standard H1 space with order 2 elements
H1_FECollection fec(2, mesh.Dimension());
FiniteElementSpace fespace(&mesh, &fec);
REQUIRE(fespace.GetNDofs() == 27);
REQUIRE(fespace.GetNConformingDofs() == 27);
// convert to variable order space: p-refine first element
fespace.SetElementOrder(0, 3);
fespace.Update(false);
REQUIRE(fespace.GetNDofs() == 54);
REQUIRE(fespace.GetNConformingDofs() == 42);
// refine to form an edge-face constraint similar to
// https://github.com/mfem/mfem/pull/713#issuecomment-495786362
Array<Refinement> refs;
refs.Append(Refinement(1, 3));
mesh.GeneralRefinement(refs);
fespace.Update(false);
refs[0].ref_type = 4;
refs.Append(Refinement(2, 4));
mesh.GeneralRefinement(refs);
fespace.Update(false);
REQUIRE(fespace.GetNDofs() == 113);
REQUIRE(fespace.GetNConformingDofs() == 67);
TestSolve(fespace);
}
}
// Exact solution: x^2 + y^2 + z^2
static double exact_sln(const Vector &p)
{
double x = p(0), y = p(1);
if (p.Size() == 3)
{
double z = p(2);
return x*x + y*y + z*z;
}
else
{
return x*x + y*y;
}
}
static double exact_rhs(const Vector &p)
{
return (p.Size() == 3) ? -6.0 : -4.0;
}
static void TestSolve(FiniteElementSpace &fespace)
{
Mesh *mesh = fespace.GetMesh();
// exact solution and RHS for the problem -\Delta u = 1
FunctionCoefficient exsol(exact_sln);
FunctionCoefficient rhs(exact_rhs);
// set up Dirichlet BC on the boundary
Array<int> ess_attr(mesh->bdr_attributes.Max());
ess_attr = 1;
Array<int> ess_tdof_list;
fespace.GetEssentialTrueDofs(ess_attr, ess_tdof_list);
GridFunction x(&fespace);
x = 0.0;
x.ProjectBdrCoefficient(exsol, ess_attr);
// assemble the linear form
LinearForm lf(&fespace);
lf.AddDomainIntegrator(new DomainLFIntegrator(rhs));
lf.Assemble();
// assemble the bilinear form.
BilinearForm bf(&fespace);
bf.AddDomainIntegrator(new DiffusionIntegrator());
bf.Assemble();
OperatorPtr A;
Vector B, X;
bf.FormLinearSystem(ess_tdof_list, x, lf, A, X, B);
// solve
GSSmoother M((SparseMatrix&)(*A));
PCG(*A, M, B, X, 0, 500, 1e-30, 0.0);
bf.RecoverFEMSolution(X, lf, x);
// compute L2 error from the exact solution
double error = x.ComputeL2Error(exsol);
REQUIRE(error == MFEM_Approx(0.0));
// visualize
#ifdef MFEM_UNIT_DEBUG_VISUALIZE
const char vishost[] = "localhost";
const int visport = 19916;
GridFunction *vis_x = ProlongToMaxOrder(&x);
socketstream sol_sock(vishost, visport);
sol_sock.precision(8);
sol_sock << "solution\n" << *mesh << *vis_x;
delete vis_x;
#endif
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: colrowba.hxx,v $
*
* $Revision: 1.1.1.1 $
*
* last change: $Author: hr $ $Date: 2000-09-18 16:44:57 $
*
* 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 SC_COLROWBAR_HXX
#define SC_COLROWBAR_HXX
#ifndef SC_HDRCONT_HXX
#include "hdrcont.hxx"
#endif
#ifndef SC_VIEWDATA_HXX
#include "viewdata.hxx"
#endif
class ScHeaderFunctionSet;
class ScHeaderSelectionEngine;
// ---------------------------------------------------------------------------
class ScColBar : public ScHeaderControl
{
ScViewData* pViewData;
ScHSplitPos eWhich;
ScHeaderFunctionSet* pFuncSet;
ScHeaderSelectionEngine* pSelEngine;
public:
ScColBar( Window* pParent, ScViewData* pData, ScHSplitPos eWhichPos,
ScHeaderFunctionSet* pFunc, ScHeaderSelectionEngine* pEng );
~ScColBar();
virtual USHORT GetPos();
virtual USHORT GetEntrySize( USHORT nEntryNo );
virtual String GetEntryText( USHORT nEntryNo );
virtual void SetEntrySize( USHORT nPos, USHORT nNewSize );
virtual void HideEntries( USHORT nStart, USHORT nEnd );
virtual void SetMarking( BOOL bSet );
virtual void SelectWindow();
virtual BOOL IsDisabled();
virtual BOOL ResizeAllowed();
virtual void DrawInvert( long nDragPos );
virtual String GetDragHelp( long nVal );
};
class ScRowBar : public ScHeaderControl
{
ScViewData* pViewData;
ScVSplitPos eWhich;
ScHeaderFunctionSet* pFuncSet;
ScHeaderSelectionEngine* pSelEngine;
public:
ScRowBar( Window* pParent, ScViewData* pData, ScVSplitPos eWhichPos,
ScHeaderFunctionSet* pFunc, ScHeaderSelectionEngine* pEng );
~ScRowBar();
virtual USHORT GetPos();
virtual USHORT GetEntrySize( USHORT nEntryNo );
virtual String GetEntryText( USHORT nEntryNo );
virtual USHORT GetHiddenCount( USHORT nEntryNo ); // nur fuer Zeilen
virtual void SetEntrySize( USHORT nPos, USHORT nNewSize );
virtual void HideEntries( USHORT nStart, USHORT nEnd );
virtual void SetMarking( BOOL bSet );
virtual void SelectWindow();
virtual BOOL IsDisabled();
virtual BOOL ResizeAllowed();
virtual void DrawInvert( long nDragPos );
virtual String GetDragHelp( long nVal );
};
#endif
<commit_msg>INTEGRATION: CWS calcrtl (1.1.1.1.126); FILE MERGED 2003/07/11 10:31:22 nn 1.1.1.1.126.2: #106948# RTL ordering of view elements 2003/06/30 17:18:24 nn 1.1.1.1.126.1: #106948# RTL layout, continued implementation<commit_after>/*************************************************************************
*
* $RCSfile: colrowba.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: hr $ $Date: 2004-02-03 12:37:08 $
*
* 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 SC_COLROWBAR_HXX
#define SC_COLROWBAR_HXX
#ifndef SC_HDRCONT_HXX
#include "hdrcont.hxx"
#endif
#ifndef SC_VIEWDATA_HXX
#include "viewdata.hxx"
#endif
class ScHeaderFunctionSet;
class ScHeaderSelectionEngine;
// ---------------------------------------------------------------------------
class ScColBar : public ScHeaderControl
{
ScViewData* pViewData;
ScHSplitPos eWhich;
ScHeaderFunctionSet* pFuncSet;
ScHeaderSelectionEngine* pSelEngine;
public:
ScColBar( Window* pParent, ScViewData* pData, ScHSplitPos eWhichPos,
ScHeaderFunctionSet* pFunc, ScHeaderSelectionEngine* pEng );
~ScColBar();
virtual USHORT GetPos();
virtual USHORT GetEntrySize( USHORT nEntryNo );
virtual String GetEntryText( USHORT nEntryNo );
virtual BOOL IsLayoutRTL(); // only for columns
virtual void SetEntrySize( USHORT nPos, USHORT nNewSize );
virtual void HideEntries( USHORT nStart, USHORT nEnd );
virtual void SetMarking( BOOL bSet );
virtual void SelectWindow();
virtual BOOL IsDisabled();
virtual BOOL ResizeAllowed();
virtual void DrawInvert( long nDragPos );
virtual String GetDragHelp( long nVal );
};
class ScRowBar : public ScHeaderControl
{
ScViewData* pViewData;
ScVSplitPos eWhich;
ScHeaderFunctionSet* pFuncSet;
ScHeaderSelectionEngine* pSelEngine;
public:
ScRowBar( Window* pParent, ScViewData* pData, ScVSplitPos eWhichPos,
ScHeaderFunctionSet* pFunc, ScHeaderSelectionEngine* pEng );
~ScRowBar();
virtual USHORT GetPos();
virtual USHORT GetEntrySize( USHORT nEntryNo );
virtual String GetEntryText( USHORT nEntryNo );
virtual BOOL IsMirrored(); // only for columns
virtual USHORT GetHiddenCount( USHORT nEntryNo ); // only for columns
virtual void SetEntrySize( USHORT nPos, USHORT nNewSize );
virtual void HideEntries( USHORT nStart, USHORT nEnd );
virtual void SetMarking( BOOL bSet );
virtual void SelectWindow();
virtual BOOL IsDisabled();
virtual BOOL ResizeAllowed();
virtual void DrawInvert( long nDragPos );
virtual String GetDragHelp( long nVal );
};
#endif
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: expftext.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-08 21:24:30 $
*
* 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 _SC_EXPFTEXT_HXX
#define _SC_EXPFTEXT_HXX
#ifndef _SV_FIXED_HXX //autogen
#include <vcl/fixed.hxx>
#endif
#ifndef INCLUDED_SCDLLAPI_H
#include "scdllapi.h"
#endif
class SC_DLLPUBLIC ScExpandedFixedText: public FixedText
{
protected:
void RequestHelp( const HelpEvent& rHEvt );
public:
ScExpandedFixedText( Window* pParent,WinBits nWinStyle = 0);
ScExpandedFixedText( Window* pWindow, const ResId& rResId);
};
#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.3.700); FILE MERGED 2008/04/01 15:30:53 thb 1.3.700.3: #i85898# Stripping all external header guards 2008/04/01 12:36:45 thb 1.3.700.2: #i85898# Stripping all external header guards 2008/03/31 17:15:41 rt 1.3.700.1: #i87441# Change license header to LPGL v3.<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: expftext.hxx,v $
* $Revision: 1.4 $
*
* 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 _SC_EXPFTEXT_HXX
#define _SC_EXPFTEXT_HXX
#include <vcl/fixed.hxx>
#include "scdllapi.h"
class SC_DLLPUBLIC ScExpandedFixedText: public FixedText
{
protected:
void RequestHelp( const HelpEvent& rHEvt );
public:
ScExpandedFixedText( Window* pParent,WinBits nWinStyle = 0);
ScExpandedFixedText( Window* pWindow, const ResId& rResId);
};
#endif
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: hintwin.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-08 22:59:44 $
*
* 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
*
************************************************************************/
// System - Includes -----------------------------------------------------
#ifdef PCH
#include "ui_pch.hxx"
#endif
// INCLUDE ---------------------------------------------------------------
#include "hintwin.hxx"
#include "global.hxx"
#define HINT_LINESPACE 2
#define HINT_INDENT 3
#define HINT_MARGIN 4
//==================================================================
ScHintWindow::ScHintWindow( Window* pParent, const String& rTit, const String& rMsg ) :
Window( pParent, WinBits( WB_BORDER ) ),
aTitle( rTit ),
aMessage( rMsg )
{
aMessage.ConvertLineEnd( LINEEND_CR );
// Hellgelb, wie Notizen in detfunc.cxx
Color aYellow( 255,255,192 ); // hellgelb
SetBackground( aYellow );
aTextFont = GetFont();
aTextFont.SetTransparent( TRUE );
aTextFont.SetWeight( WEIGHT_NORMAL );
aHeadFont = aTextFont;
aHeadFont.SetWeight( WEIGHT_BOLD );
SetFont( aHeadFont );
Size aHeadSize( GetTextWidth( aTitle ), GetTextHeight() );
SetFont( aTextFont );
Size aTextSize;
xub_StrLen nIndex = 0;
while ( nIndex != STRING_NOTFOUND )
{
String aLine = aMessage.GetToken( 0, CHAR_CR, nIndex );
Size aLineSize( GetTextWidth( aLine ), GetTextHeight() );
nTextHeight = aLineSize.Height();
aTextSize.Height() += nTextHeight;
if ( aLineSize.Width() > aTextSize.Width() )
aTextSize.Width() = aLineSize.Width();
}
aTextSize.Width() += HINT_INDENT;
aTextStart = Point( HINT_MARGIN + HINT_INDENT,
aHeadSize.Height() + HINT_MARGIN + HINT_LINESPACE );
Size aWinSize( Max( aHeadSize.Width(), aTextSize.Width() ) + 2 * HINT_MARGIN + 1,
aHeadSize.Height() + aTextSize.Height() + HINT_LINESPACE + 2 * HINT_MARGIN + 1 );
SetOutputSizePixel( aWinSize );
}
ScHintWindow::~ScHintWindow()
{
}
void __EXPORT ScHintWindow::Paint( const Rectangle& rRect )
{
SetFont( aHeadFont );
DrawText( Point(HINT_MARGIN,HINT_MARGIN), aTitle );
SetFont( aTextFont );
xub_StrLen nIndex = 0;
Point aLineStart = aTextStart;
while ( nIndex != STRING_NOTFOUND )
{
String aLine = aMessage.GetToken( 0, CHAR_CR, nIndex );
DrawText( aLineStart, aLine );
aLineStart.Y() += nTextHeight;
}
}
<commit_msg>INTEGRATION: CWS pchfix01 (1.3.216); FILE MERGED 2006/07/12 10:03:05 kaib 1.3.216.1: #i67080# Converted cxx files in sc, added initial project level pch and stripped old PCH definitions.<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: hintwin.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: kz $ $Date: 2006-07-21 15:02:02 $
*
* 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
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sc.hxx"
// System - Includes -----------------------------------------------------
// INCLUDE ---------------------------------------------------------------
#include "hintwin.hxx"
#include "global.hxx"
#define HINT_LINESPACE 2
#define HINT_INDENT 3
#define HINT_MARGIN 4
//==================================================================
ScHintWindow::ScHintWindow( Window* pParent, const String& rTit, const String& rMsg ) :
Window( pParent, WinBits( WB_BORDER ) ),
aTitle( rTit ),
aMessage( rMsg )
{
aMessage.ConvertLineEnd( LINEEND_CR );
// Hellgelb, wie Notizen in detfunc.cxx
Color aYellow( 255,255,192 ); // hellgelb
SetBackground( aYellow );
aTextFont = GetFont();
aTextFont.SetTransparent( TRUE );
aTextFont.SetWeight( WEIGHT_NORMAL );
aHeadFont = aTextFont;
aHeadFont.SetWeight( WEIGHT_BOLD );
SetFont( aHeadFont );
Size aHeadSize( GetTextWidth( aTitle ), GetTextHeight() );
SetFont( aTextFont );
Size aTextSize;
xub_StrLen nIndex = 0;
while ( nIndex != STRING_NOTFOUND )
{
String aLine = aMessage.GetToken( 0, CHAR_CR, nIndex );
Size aLineSize( GetTextWidth( aLine ), GetTextHeight() );
nTextHeight = aLineSize.Height();
aTextSize.Height() += nTextHeight;
if ( aLineSize.Width() > aTextSize.Width() )
aTextSize.Width() = aLineSize.Width();
}
aTextSize.Width() += HINT_INDENT;
aTextStart = Point( HINT_MARGIN + HINT_INDENT,
aHeadSize.Height() + HINT_MARGIN + HINT_LINESPACE );
Size aWinSize( Max( aHeadSize.Width(), aTextSize.Width() ) + 2 * HINT_MARGIN + 1,
aHeadSize.Height() + aTextSize.Height() + HINT_LINESPACE + 2 * HINT_MARGIN + 1 );
SetOutputSizePixel( aWinSize );
}
ScHintWindow::~ScHintWindow()
{
}
void __EXPORT ScHintWindow::Paint( const Rectangle& rRect )
{
SetFont( aHeadFont );
DrawText( Point(HINT_MARGIN,HINT_MARGIN), aTitle );
SetFont( aTextFont );
xub_StrLen nIndex = 0;
Point aLineStart = aTextStart;
while ( nIndex != STRING_NOTFOUND )
{
String aLine = aMessage.GetToken( 0, CHAR_CR, nIndex );
DrawText( aLineStart, aLine );
aLineStart.Y() += nTextHeight;
}
}
<|endoftext|> |
<commit_before>#include "parse.hh"
#include <nail/size.hh>
/* template<typename siz_t> struct NailCoroFragmentStream {
private:
typedef std::map<siz_t, NailMemStream> inner_t;
std::map<siz_t, NailMemStream> streams;
public:
typedef class {
inner_t::iterator iter;
NailMemStream::pos_t pos;
}
};*/
template <typename str> struct ip_checksum_parse {
};
template <> struct ip_checksum_parse<NailMemStream> {
typedef NailMemStream out_1_t;
typedef NailMemStream out_2_t;
typedef NailMemStream out_3_t;
static int f(NailArena *tmp,NailMemStream *in_current,uint16_t *ptr_checksum){
uint32_t checksum = 0;
uint16_t *field = (uint16_t *)in_current->getBuf();
for(size_t l = in_current->getSize()/2; l>0;l--){
checksum += *field;
field++;
}
while(checksum >> 16){
checksum = (checksum & 0xFFFF)+ (checksum>>16);
}
if(checksum != 0xFFFF) return -1;
return 0;
}
};
int ip_checksum_generate(NailArena *tmp, NailOutStream *current, uint16_t *ptr_checksum){
uint32_t checksum=0;
const uint16_t *field = (uint16_t *)current->data;
for(size_t ihl = current->pos/2; ihl>0;ihl--){
checksum += *field;
field++;
}
while(checksum >> 16){
checksum = (checksum & 0xFFFF)+ (checksum>>16);
}
*ptr_checksum = ~((uint16_t)checksum);
return 0;
}
template <typename str> struct ip_header_parse {
};
template <> struct ip_header_parse<NailMemStream> {
typedef NailMemStream out_1_t;
typedef NailMemStream out_2_t;
typedef NailMemStream out_3_t;
static int f(NailArena *tmp, NailMemStream **out_options,NailMemStream **out_body,NailMemStream *in_current, uint8_t *ihl, uint16_t *ptr_checksum,uint16_t *total_length){
if(n_fail(in_current->repositionOffset(*ihl * 4, 0))) return -1;
if(in_current->getSize() != *total_length) return -1;
*out_options = (NailMemStream *)n_malloc(tmp,sizeof(NailMemStream));
new((void *)*out_options) NailMemStream(in_current->getBuf() + 20, *ihl * 4 - 20);
NailMemStream total_header(in_current->getBuf(), *ihl*4);
if(n_fail(ip_checksum_parse<NailMemStream>::f(tmp,&total_header, ptr_checksum))) return -1;
*out_body = (NailMemStream *)n_malloc(tmp,sizeof(NailMemStream));
new((void *)*out_body) NailMemStream(in_current->getBuf() + *ihl * 4, in_current->getSize()- (*ihl * 4));
return 0;
}
};
int ip_header_generate(NailArena *tmp, const NailOutStream* in_options, const NailOutStream *in_body, NailOutStream *current, uint8_t *ihl, uint16_t *out_checksum,uint16_t *total_length)
{
if(in_options->pos % 4 != 0) return -1; // XXX:: HEADER PADDING!
if(in_options->pos + 20 >= 64) return -1; // XXX: option length
if(n_fail(size_generate(tmp, in_options, current, ihl))) return -1;
*ihl /= 4;
*ihl += 5;
ip_checksum_generate(tmp, current, out_checksum);
if(n_fail(tail_generate(tmp, in_body, current))) return -1;
*total_length = *ihl * 4 + in_body->pos;
return 0;
}
#include "proto/net.nail.cc"
struct ethernet *p_ethernet(NailArena *arena, const uint8_t *buf, size_t nread)
{
NailMemStream packetstream(buf, nread);
return parse_ethernet(arena,&packetstream);
}
<commit_msg>parse<commit_after>#include "parse.hh"
#include <nail/size.hh>
/* template<typename siz_t> struct NailCoroFragmentStream {
private:
typedef std::map<siz_t, NailMemStream> inner_t;
std::map<siz_t, NailMemStream> streams;
public:
typedef class {
inner_t::iterator iter;
NailMemStream::pos_t pos;
}
};*/
template <typename str> struct ip_checksum_parse {
};
template <> struct ip_checksum_parse<NailMemStream> {
typedef NailMemStream out_1_t;
typedef NailMemStream out_2_t;
typedef NailMemStream out_3_t;
static int f(NailArena *tmp,NailMemStream *in_current,uint16_t *ptr_checksum){
uint32_t checksum = 0;
uint16_t *field = (uint16_t *)in_current->getBuf();
for(size_t l = in_current->getSize()/2; l>0;l--){
checksum += *field;
field++;
}
while(checksum >> 16){
checksum = (checksum & 0xFFFF)+ (checksum>>16);
}
if(checksum != 0xFFFF) return -1;
return 0;
}
};
int ip_checksum_generate(NailArena *tmp, NailOutStream *current, uint16_t *ptr_checksum, uint16_t extra_1=0, uint16_t extra_2 =0){
uint32_t checksum=extra_1+extra_2;
const uint16_t *field = (uint16_t *)current->data;
for(size_t ihl = current->pos/2; ihl>0;ihl--){
checksum += *field;
field++;
}
while(checksum >> 16){
checksum = (checksum & 0xFFFF)+ (checksum>>16);
}
*ptr_checksum = ~((uint16_t)checksum);
return 0;
}
template <typename str> struct ip_header_parse {
};
template <> struct ip_header_parse<NailMemStream> {
typedef NailMemStream out_1_t;
typedef NailMemStream out_2_t;
typedef NailMemStream out_3_t;
static int f(NailArena *tmp, NailMemStream **out_options,NailMemStream **out_body,NailMemStream *in_current, uint8_t *ihl, uint16_t *ptr_checksum,uint16_t *total_length){
if(n_fail(in_current->repositionOffset(*ihl * 4, 0))) return -1;
if(in_current->getSize() != *total_length) return -1;
*out_options = (NailMemStream *)n_malloc(tmp,sizeof(NailMemStream));
new((void *)*out_options) NailMemStream(in_current->getBuf() + 20, *ihl * 4 - 20);
NailMemStream total_header(in_current->getBuf(), *ihl*4);
if(n_fail(ip_checksum_parse<NailMemStream>::f(tmp,&total_header, ptr_checksum))) return -1;
*out_body = (NailMemStream *)n_malloc(tmp,sizeof(NailMemStream));
new((void *)*out_body) NailMemStream(in_current->getBuf() + *ihl * 4, in_current->getSize()- (*ihl * 4));
return 0;
}
};
int ip_header_generate(NailArena *tmp, const NailOutStream* in_options, const NailOutStream *in_body, NailOutStream *current, uint8_t *ihl, uint16_t *out_checksum,uint16_t *total_length)
{
if(in_options->pos % 4 != 0) return -1; // XXX:: HEADER PADDING!
if(in_options->pos + 20 >= 64) return -1; // XXX: option length
if(n_fail(size_generate(tmp, in_options, current, ihl))) return -1;
*ihl /= 4;
*ihl += 5;
if(n_fail(tail_generate(tmp, in_body, current))) return -1;
*total_length = *ihl * 4 + in_body->pos;
ip_checksum_generate(tmp, current, out_checksum, *ihl, *total_length);
return 0;
}
#include "proto/net.nail.cc"
struct ethernet *p_ethernet(NailArena *arena, const uint8_t *buf, size_t nread)
{
NailMemStream packetstream(buf, nread);
return parse_ethernet(arena,&packetstream);
}
<|endoftext|> |
<commit_before>
/*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "Test.h"
#include "SkDeque.h"
static void assert_count(skiatest::Reporter* reporter, const SkDeque& deq, int count) {
if (0 == count) {
REPORTER_ASSERT(reporter, deq.empty());
REPORTER_ASSERT(reporter, 0 == deq.count());
REPORTER_ASSERT(reporter, sizeof(int) == deq.elemSize());
REPORTER_ASSERT(reporter, NULL == deq.front());
REPORTER_ASSERT(reporter, NULL == deq.back());
} else {
REPORTER_ASSERT(reporter, !deq.empty());
REPORTER_ASSERT(reporter, count == deq.count());
REPORTER_ASSERT(reporter, sizeof(int) == deq.elemSize());
REPORTER_ASSERT(reporter, NULL != deq.front());
REPORTER_ASSERT(reporter, NULL != deq.back());
if (1 == count) {
REPORTER_ASSERT(reporter, deq.back() == deq.front());
} else {
REPORTER_ASSERT(reporter, deq.back() != deq.front());
}
}
}
static void assert_iter(skiatest::Reporter* reporter, const SkDeque& deq,
int max, int min) {
// test forward iteration
SkDeque::Iter iter(deq, SkDeque::Iter::kFront_IterStart);
void* ptr;
int value = max;
while (NULL != (ptr = iter.next())) {
REPORTER_ASSERT(reporter, value == *(int*)ptr);
value -= 1;
}
REPORTER_ASSERT(reporter, value+1 == min);
// test reverse iteration
iter.reset(deq, SkDeque::Iter::kBack_IterStart);
value = min;
while (NULL != (ptr = iter.prev())) {
REPORTER_ASSERT(reporter, value == *(int*)ptr);
value += 1;
}
REPORTER_ASSERT(reporter, value-1 == max);
// test mixed iteration
iter.reset(deq, SkDeque::Iter::kFront_IterStart);
value = max;
// forward iteration half-way
for (int i = 0; i < deq.count()/2 && NULL != (ptr = iter.next()); i++) {
REPORTER_ASSERT(reporter, value == *(int*)ptr);
value -= 1;
}
// then back down w/ reverse iteration
while (NULL != (ptr = iter.prev())) {
REPORTER_ASSERT(reporter, value == *(int*)ptr);
value += 1;
}
REPORTER_ASSERT(reporter, value-1 == max);
}
// This helper is intended to only give the unit test access to SkDeque's
// private numBlocksAllocated method
class DequeUnitTestHelper {
public:
int fNumBlocksAllocated;
DequeUnitTestHelper(const SkDeque& deq) {
fNumBlocksAllocated = deq.numBlocksAllocated();
}
};
static void assert_blocks(skiatest::Reporter* reporter,
const SkDeque& deq,
int allocCount) {
DequeUnitTestHelper helper(deq);
if (0 == deq.count()) {
REPORTER_ASSERT(reporter, 1 == helper.fNumBlocksAllocated);
} else {
int expected = (deq.count() + allocCount - 1) / allocCount;
// A block isn't freed in the deque when it first becomes empty so
// sometimes an extra block lingers around
REPORTER_ASSERT(reporter,
expected == helper.fNumBlocksAllocated ||
expected+1 == helper.fNumBlocksAllocated);
}
}
static void Test(skiatest::Reporter* reporter, int allocCount) {
SkDeque deq(sizeof(int), allocCount);
int i;
// test pushing on the front
assert_count(reporter, deq, 0);
for (i = 1; i <= 10; i++) {
*(int*)deq.push_front() = i;
}
assert_count(reporter, deq, 10);
assert_iter(reporter, deq, 10, 1);
assert_blocks(reporter, deq, allocCount);
for (i = 0; i < 5; i++) {
deq.pop_front();
}
assert_count(reporter, deq, 5);
assert_iter(reporter, deq, 5, 1);
assert_blocks(reporter, deq, allocCount);
for (i = 0; i < 5; i++) {
deq.pop_front();
}
assert_count(reporter, deq, 0);
assert_blocks(reporter, deq, allocCount);
// now test pushing on the back
for (i = 10; i >= 1; --i) {
*(int*)deq.push_back() = i;
}
assert_count(reporter, deq, 10);
assert_iter(reporter, deq, 10, 1);
assert_blocks(reporter, deq, allocCount);
for (i = 0; i < 5; i++) {
deq.pop_back();
}
assert_count(reporter, deq, 5);
assert_iter(reporter, deq, 10, 6);
assert_blocks(reporter, deq, allocCount);
for (i = 0; i < 5; i++) {
deq.pop_back();
}
assert_count(reporter, deq, 0);
assert_blocks(reporter, deq, allocCount);
// now test pushing/popping on both ends
*(int*)deq.push_front() = 5;
*(int*)deq.push_back() = 4;
*(int*)deq.push_front() = 6;
*(int*)deq.push_back() = 3;
*(int*)deq.push_front() = 7;
*(int*)deq.push_back() = 2;
*(int*)deq.push_front() = 8;
*(int*)deq.push_back() = 1;
assert_count(reporter, deq, 8);
assert_iter(reporter, deq, 8, 1);
assert_blocks(reporter, deq, allocCount);
}
static void TestDeque(skiatest::Reporter* reporter) {
// test it once with the default allocation count
Test(reporter, 1);
// test it again with a generous allocation count
Test(reporter, 10);
}
#include "TestClassDef.h"
DEFINE_TESTCLASS("Deque", TestDequeClass, TestDeque)
<commit_msg>fix for non-Windows-specific compiler error in r4624<commit_after>
/*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "Test.h"
#include "SkDeque.h"
static void assert_count(skiatest::Reporter* reporter, const SkDeque& deq, int count) {
if (0 == count) {
REPORTER_ASSERT(reporter, deq.empty());
REPORTER_ASSERT(reporter, 0 == deq.count());
REPORTER_ASSERT(reporter, sizeof(int) == deq.elemSize());
REPORTER_ASSERT(reporter, NULL == deq.front());
REPORTER_ASSERT(reporter, NULL == deq.back());
} else {
REPORTER_ASSERT(reporter, !deq.empty());
REPORTER_ASSERT(reporter, count == deq.count());
REPORTER_ASSERT(reporter, sizeof(int) == deq.elemSize());
REPORTER_ASSERT(reporter, NULL != deq.front());
REPORTER_ASSERT(reporter, NULL != deq.back());
if (1 == count) {
REPORTER_ASSERT(reporter, deq.back() == deq.front());
} else {
REPORTER_ASSERT(reporter, deq.back() != deq.front());
}
}
}
static void assert_iter(skiatest::Reporter* reporter, const SkDeque& deq,
int max, int min) {
// test forward iteration
SkDeque::Iter iter(deq, SkDeque::Iter::kFront_IterStart);
void* ptr;
int value = max;
while (NULL != (ptr = iter.next())) {
REPORTER_ASSERT(reporter, value == *(int*)ptr);
value -= 1;
}
REPORTER_ASSERT(reporter, value+1 == min);
// test reverse iteration
iter.reset(deq, SkDeque::Iter::kBack_IterStart);
value = min;
while (NULL != (ptr = iter.prev())) {
REPORTER_ASSERT(reporter, value == *(int*)ptr);
value += 1;
}
REPORTER_ASSERT(reporter, value-1 == max);
// test mixed iteration
iter.reset(deq, SkDeque::Iter::kFront_IterStart);
value = max;
// forward iteration half-way
for (int i = 0; i < deq.count()/2 && NULL != (ptr = iter.next()); i++) {
REPORTER_ASSERT(reporter, value == *(int*)ptr);
value -= 1;
}
// then back down w/ reverse iteration
while (NULL != (ptr = iter.prev())) {
REPORTER_ASSERT(reporter, value == *(int*)ptr);
value += 1;
}
REPORTER_ASSERT(reporter, value-1 == max);
}
// This helper is intended to only give the unit test access to SkDeque's
// private numBlocksAllocated method
class DequeUnitTestHelper {
public:
int fNumBlocksAllocated;
DequeUnitTestHelper(const SkDeque& deq) {
fNumBlocksAllocated = deq.numBlocksAllocated();
}
};
static void assert_blocks(skiatest::Reporter* reporter,
const SkDeque& deq,
int allocCount) {
DequeUnitTestHelper helper(deq);
if (0 == deq.count()) {
REPORTER_ASSERT(reporter, 1 == helper.fNumBlocksAllocated);
} else {
int expected = (deq.count() + allocCount - 1) / allocCount;
// A block isn't freed in the deque when it first becomes empty so
// sometimes an extra block lingers around
REPORTER_ASSERT(reporter,
expected == helper.fNumBlocksAllocated ||
expected+1 == helper.fNumBlocksAllocated);
}
}
static void TestSub(skiatest::Reporter* reporter, int allocCount) {
SkDeque deq(sizeof(int), allocCount);
int i;
// test pushing on the front
assert_count(reporter, deq, 0);
for (i = 1; i <= 10; i++) {
*(int*)deq.push_front() = i;
}
assert_count(reporter, deq, 10);
assert_iter(reporter, deq, 10, 1);
assert_blocks(reporter, deq, allocCount);
for (i = 0; i < 5; i++) {
deq.pop_front();
}
assert_count(reporter, deq, 5);
assert_iter(reporter, deq, 5, 1);
assert_blocks(reporter, deq, allocCount);
for (i = 0; i < 5; i++) {
deq.pop_front();
}
assert_count(reporter, deq, 0);
assert_blocks(reporter, deq, allocCount);
// now test pushing on the back
for (i = 10; i >= 1; --i) {
*(int*)deq.push_back() = i;
}
assert_count(reporter, deq, 10);
assert_iter(reporter, deq, 10, 1);
assert_blocks(reporter, deq, allocCount);
for (i = 0; i < 5; i++) {
deq.pop_back();
}
assert_count(reporter, deq, 5);
assert_iter(reporter, deq, 10, 6);
assert_blocks(reporter, deq, allocCount);
for (i = 0; i < 5; i++) {
deq.pop_back();
}
assert_count(reporter, deq, 0);
assert_blocks(reporter, deq, allocCount);
// now test pushing/popping on both ends
*(int*)deq.push_front() = 5;
*(int*)deq.push_back() = 4;
*(int*)deq.push_front() = 6;
*(int*)deq.push_back() = 3;
*(int*)deq.push_front() = 7;
*(int*)deq.push_back() = 2;
*(int*)deq.push_front() = 8;
*(int*)deq.push_back() = 1;
assert_count(reporter, deq, 8);
assert_iter(reporter, deq, 8, 1);
assert_blocks(reporter, deq, allocCount);
}
static void TestDeque(skiatest::Reporter* reporter) {
// test it once with the default allocation count
TestSub(reporter, 1);
// test it again with a generous allocation count
TestSub(reporter, 10);
}
#include "TestClassDef.h"
DEFINE_TESTCLASS("Deque", TestDequeClass, TestDeque)
<|endoftext|> |
<commit_before>// Copyright 2015-2019 Elviss Strazdins. All rights reserved.
#include <iterator>
#include <stdexcept>
#include <string>
#include "MtlLoader.hpp"
#include "Bundle.hpp"
#include "Cache.hpp"
#include "core/Engine.hpp"
namespace ouzel
{
namespace assets
{
namespace
{
constexpr auto isWhitespace(uint8_t c)
{
return c == ' ' || c == '\t';
}
constexpr auto isNewline(uint8_t c)
{
return c == '\r' || c == '\n';
}
constexpr auto isControlChar(uint8_t c)
{
return c <= 0x1F;
}
void skipWhitespaces(std::vector<uint8_t>::const_iterator& iterator,
std::vector<uint8_t>::const_iterator end)
{
while (iterator != end)
if (isWhitespace(*iterator))
++iterator;
else
break;
}
void skipLine(std::vector<uint8_t>::const_iterator& iterator,
std::vector<uint8_t>::const_iterator end)
{
while (iterator != end)
{
if (isNewline(*iterator))
{
++iterator;
break;
}
++iterator;
}
}
std::string parseString(std::vector<uint8_t>::const_iterator& iterator,
std::vector<uint8_t>::const_iterator end)
{
std::string result;
while (iterator != end && !isControlChar(*iterator) && !isWhitespace(*iterator))
{
result.push_back(static_cast<char>(*iterator));
++iterator;
}
if (result.empty())
throw std::runtime_error("Invalid string");
return result;
}
float parseFloat(std::vector<uint8_t>::const_iterator& iterator,
std::vector<uint8_t>::const_iterator end)
{
std::string value;
uint32_t length = 1;
if (iterator != end && *iterator == '-')
{
value.push_back(static_cast<char>(*iterator));
++length;
++iterator;
}
while (iterator != end && *iterator >= '0' && *iterator <= '9')
{
value.push_back(static_cast<char>(*iterator));
++iterator;
}
if (iterator != end && *iterator == '.')
{
value.push_back(static_cast<char>(*iterator));
++length;
++iterator;
while (iterator != end && *iterator >= '0' && *iterator <= '9')
{
value.push_back(static_cast<char>(*iterator));
++iterator;
}
}
if (value.length() < length) return false;
return std::stof(value);
}
}
MtlLoader::MtlLoader(Cache& initCache):
Loader(initCache, Loader::Material)
{
}
bool MtlLoader::loadAsset(Bundle& bundle,
const std::string& name,
const std::vector<uint8_t>& data,
bool mipmaps)
{
std::string materialName = name;
std::shared_ptr<graphics::Texture> diffuseTexture;
std::shared_ptr<graphics::Texture> ambientTexture;
Color diffuseColor = Color::white();
float opacity = 1.0F;
uint32_t materialCount = 0;
auto iterator = data.cbegin();
std::string keyword;
std::string value;
while (iterator != data.end())
{
if (isNewline(*iterator))
{
// skip empty lines
++iterator;
}
else if (*iterator == '#')
{
// skip the comment
skipLine(iterator, data.end());
}
else
{
skipWhitespaces(iterator, data.end());
keyword = parseString(iterator, data.end());
if (keyword == "newmtl")
{
if (materialCount)
{
auto material = std::make_unique<graphics::Material>();
material->blendState = cache.getBlendState(BLEND_ALPHA);
material->shader = cache.getShader(SHADER_TEXTURE);
material->textures[0] = diffuseTexture;
material->textures[1] = ambientTexture;
material->diffuseColor = diffuseColor;
material->opacity = opacity;
material->cullMode = graphics::CullMode::Back;
bundle.setMaterial(materialName, std::move(material));
}
skipWhitespaces(iterator, data.end());
materialName = parseString(iterator, data.end());
skipLine(iterator, data.end());
diffuseTexture.reset();
ambientTexture.reset();
diffuseColor = Color::white();
opacity = 1.0F;
}
else if (keyword == "map_Ka") // ambient texture map
{
skipWhitespaces(iterator, data.end());
value = parseString(iterator, data.end());
skipLine(iterator, data.end());
ambientTexture = cache.getTexture(value);
}
else if (keyword == "map_Kd") // diffuse texture map
{
skipWhitespaces(iterator, data.end());
value = parseString(iterator, data.end());
skipLine(iterator, data.end());
diffuseTexture = cache.getTexture(value);
if (!diffuseTexture)
{
bundle.loadAsset(Loader::Image, value, value, mipmaps);
diffuseTexture = cache.getTexture(value);
}
}
else if (keyword == "Ka") // ambient color
skipLine(iterator, data.end());
else if (keyword == "Kd") // diffuse color
{
float color[4];
skipWhitespaces(iterator, data.end());
color[0] = parseFloat(iterator, data.end());
skipWhitespaces(iterator, data.end());
color[1] = parseFloat(iterator, data.end());
skipWhitespaces(iterator, data.end());
color[2] = parseFloat(iterator, data.end());
skipLine(iterator, data.end());
color[3] = 1.0F;
diffuseColor = Color(color);
}
else if (keyword == "Ks") // specular color
skipLine(iterator, data.end());
else if (keyword == "Ke") // emissive color
skipLine(iterator, data.end());
else if (keyword == "d") // opacity
{
skipWhitespaces(iterator, data.end());
opacity = parseFloat(iterator, data.end());
skipLine(iterator, data.end());
}
else if (keyword == "Tr") // transparency
{
float transparency;
skipWhitespaces(iterator, data.end());
transparency = parseFloat(iterator, data.end());
skipLine(iterator, data.end());
// d = 1 - Tr
opacity = 1.0F - transparency;
}
else
{
// skip all unknown commands
skipLine(iterator, data.end());
}
if (!materialCount) ++materialCount; // if we got at least one attribute, we have an material
}
}
if (materialCount)
{
auto material = std::make_unique<graphics::Material>();
material->blendState = cache.getBlendState(BLEND_ALPHA);
material->shader = cache.getShader(SHADER_TEXTURE);
material->textures[0] = diffuseTexture;
material->textures[1] = ambientTexture;
material->diffuseColor = diffuseColor;
material->opacity = opacity;
material->cullMode = graphics::CullMode::Back;
bundle.setMaterial(materialName, std::move(material));
}
return true;
}
} // namespace assets
} // namespace ouzel
<commit_msg>Use color shader if material has no texture in MtlLoader<commit_after>// Copyright 2015-2019 Elviss Strazdins. All rights reserved.
#include <iterator>
#include <stdexcept>
#include <string>
#include "MtlLoader.hpp"
#include "Bundle.hpp"
#include "Cache.hpp"
#include "core/Engine.hpp"
namespace ouzel
{
namespace assets
{
namespace
{
constexpr auto isWhitespace(uint8_t c)
{
return c == ' ' || c == '\t';
}
constexpr auto isNewline(uint8_t c)
{
return c == '\r' || c == '\n';
}
constexpr auto isControlChar(uint8_t c)
{
return c <= 0x1F;
}
void skipWhitespaces(std::vector<uint8_t>::const_iterator& iterator,
std::vector<uint8_t>::const_iterator end)
{
while (iterator != end)
if (isWhitespace(*iterator))
++iterator;
else
break;
}
void skipLine(std::vector<uint8_t>::const_iterator& iterator,
std::vector<uint8_t>::const_iterator end)
{
while (iterator != end)
{
if (isNewline(*iterator))
{
++iterator;
break;
}
++iterator;
}
}
std::string parseString(std::vector<uint8_t>::const_iterator& iterator,
std::vector<uint8_t>::const_iterator end)
{
std::string result;
while (iterator != end && !isControlChar(*iterator) && !isWhitespace(*iterator))
{
result.push_back(static_cast<char>(*iterator));
++iterator;
}
if (result.empty())
throw std::runtime_error("Invalid string");
return result;
}
float parseFloat(std::vector<uint8_t>::const_iterator& iterator,
std::vector<uint8_t>::const_iterator end)
{
std::string value;
uint32_t length = 1;
if (iterator != end && *iterator == '-')
{
value.push_back(static_cast<char>(*iterator));
++length;
++iterator;
}
while (iterator != end && *iterator >= '0' && *iterator <= '9')
{
value.push_back(static_cast<char>(*iterator));
++iterator;
}
if (iterator != end && *iterator == '.')
{
value.push_back(static_cast<char>(*iterator));
++length;
++iterator;
while (iterator != end && *iterator >= '0' && *iterator <= '9')
{
value.push_back(static_cast<char>(*iterator));
++iterator;
}
}
if (value.length() < length) return false;
return std::stof(value);
}
}
MtlLoader::MtlLoader(Cache& initCache):
Loader(initCache, Loader::Material)
{
}
bool MtlLoader::loadAsset(Bundle& bundle,
const std::string& name,
const std::vector<uint8_t>& data,
bool mipmaps)
{
std::string materialName = name;
std::shared_ptr<graphics::Texture> diffuseTexture;
std::shared_ptr<graphics::Texture> ambientTexture;
Color diffuseColor = Color::white();
float opacity = 1.0F;
uint32_t materialCount = 0;
auto iterator = data.cbegin();
std::string keyword;
std::string value;
while (iterator != data.end())
{
if (isNewline(*iterator))
{
// skip empty lines
++iterator;
}
else if (*iterator == '#')
{
// skip the comment
skipLine(iterator, data.end());
}
else
{
skipWhitespaces(iterator, data.end());
keyword = parseString(iterator, data.end());
if (keyword == "newmtl")
{
if (materialCount)
{
auto material = std::make_unique<graphics::Material>();
material->blendState = cache.getBlendState(BLEND_ALPHA);
material->shader = diffuseTexture ? cache.getShader(SHADER_TEXTURE) : cache.getShader(SHADER_COLOR);
material->textures[0] = diffuseTexture;
material->textures[1] = ambientTexture;
material->diffuseColor = diffuseColor;
material->opacity = opacity;
material->cullMode = graphics::CullMode::Back;
bundle.setMaterial(materialName, std::move(material));
}
skipWhitespaces(iterator, data.end());
materialName = parseString(iterator, data.end());
skipLine(iterator, data.end());
diffuseTexture.reset();
ambientTexture.reset();
diffuseColor = Color::white();
opacity = 1.0F;
}
else if (keyword == "map_Ka") // ambient texture map
{
skipWhitespaces(iterator, data.end());
value = parseString(iterator, data.end());
skipLine(iterator, data.end());
ambientTexture = cache.getTexture(value);
}
else if (keyword == "map_Kd") // diffuse texture map
{
skipWhitespaces(iterator, data.end());
value = parseString(iterator, data.end());
skipLine(iterator, data.end());
diffuseTexture = cache.getTexture(value);
if (!diffuseTexture)
{
bundle.loadAsset(Loader::Image, value, value, mipmaps);
diffuseTexture = cache.getTexture(value);
}
}
else if (keyword == "Ka") // ambient color
skipLine(iterator, data.end());
else if (keyword == "Kd") // diffuse color
{
float color[4];
skipWhitespaces(iterator, data.end());
color[0] = parseFloat(iterator, data.end());
skipWhitespaces(iterator, data.end());
color[1] = parseFloat(iterator, data.end());
skipWhitespaces(iterator, data.end());
color[2] = parseFloat(iterator, data.end());
skipLine(iterator, data.end());
color[3] = 1.0F;
diffuseColor = Color(color);
}
else if (keyword == "Ks") // specular color
skipLine(iterator, data.end());
else if (keyword == "Ke") // emissive color
skipLine(iterator, data.end());
else if (keyword == "d") // opacity
{
skipWhitespaces(iterator, data.end());
opacity = parseFloat(iterator, data.end());
skipLine(iterator, data.end());
}
else if (keyword == "Tr") // transparency
{
float transparency;
skipWhitespaces(iterator, data.end());
transparency = parseFloat(iterator, data.end());
skipLine(iterator, data.end());
// d = 1 - Tr
opacity = 1.0F - transparency;
}
else
{
// skip all unknown commands
skipLine(iterator, data.end());
}
if (!materialCount) ++materialCount; // if we got at least one attribute, we have an material
}
}
if (materialCount)
{
auto material = std::make_unique<graphics::Material>();
material->blendState = cache.getBlendState(BLEND_ALPHA);
material->shader = cache.getShader(SHADER_TEXTURE);
material->textures[0] = diffuseTexture;
material->textures[1] = ambientTexture;
material->diffuseColor = diffuseColor;
material->opacity = opacity;
material->cullMode = graphics::CullMode::Back;
bundle.setMaterial(materialName, std::move(material));
}
return true;
}
} // namespace assets
} // namespace ouzel
<|endoftext|> |
<commit_before>/*
* DefineLink.cc
*
* Copyright (C) 2015 Linas Vepstas
*
* Author: Linas Vepstas <linasvepstas@gmail.com> May 2015
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License v3 as
* published by the Free Software Foundation and including the
* exceptions at http://opencog.org/wiki/Licenses
*
* 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 Affero General Public
* License along with this program; if not, write to:
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <opencog/atoms/base/ClassServer.h>
#include "DefineLink.h"
using namespace opencog;
void DefineLink::init()
{
// Must have name and body
if (2 != _outgoing.size())
throw SyntaxException(TRACE_INFO,
"Expecting name and definition, got size %d", _outgoing.size());
// Perform some additional checks in the UniqueLink init method
UniqueLink::init(false);
#if ALREADY_BROKEN
// Type-check. Probably not needed, probably too strict, but what
// the heck, since we are here... Heh. There's already code that
// defines shit more loosely than this. Bummer.
Type dtype = _outgoing[0]->getType();
if (DEFINED_SCHEMA_NODE != dtype and
DEFINED_PREDICATE_NODE != dtype and
DEFINED_TYPE_NODE != dtype)
throw SyntaxException(TRACE_INFO,
"Expecting Defined-X-Node, got %s",
classserver().getTypeName(dtype).c_str());
#endif
}
DefineLink::DefineLink(const HandleSeq& oset,
TruthValuePtr tv, AttentionValuePtr av)
: UniqueLink(DEFINE_LINK, oset, tv, av)
{
init();
}
DefineLink::DefineLink(const Handle& name, const Handle& defn,
TruthValuePtr tv, AttentionValuePtr av)
: UniqueLink(DEFINE_LINK, HandleSeq({name, defn}), tv, av)
{
init();
}
DefineLink::DefineLink(Link &l)
: UniqueLink(l)
{
init();
}
/**
* Get the definition associated with the alias.
* This will be the second atom of some DefineLink, where
* `alias` is the first.
*/
Handle DefineLink::get_definition(const Handle& alias)
{
Handle uniq(get_unique(alias, DEFINE_LINK, false));
LinkPtr luniq(LinkCast(uniq));
return luniq->getOutgoingAtom(1);
}
/* ===================== END OF FILE ===================== */
<commit_msg>Add type-check for defintions.<commit_after>/*
* DefineLink.cc
*
* Copyright (C) 2015 Linas Vepstas
*
* Author: Linas Vepstas <linasvepstas@gmail.com> May 2015
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License v3 as
* published by the Free Software Foundation and including the
* exceptions at http://opencog.org/wiki/Licenses
*
* 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 Affero General Public
* License along with this program; if not, write to:
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <opencog/atoms/base/ClassServer.h>
#include "DefineLink.h"
using namespace opencog;
void DefineLink::init()
{
// Must have name and body
if (2 != _outgoing.size())
throw SyntaxException(TRACE_INFO,
"Expecting name and definition, got size %d", _outgoing.size());
// Perform some additional checks in the UniqueLink init method
UniqueLink::init(false);
// Type-check. The execution and FunctionLink's only expand
// definitions anchored with these type; other definitions won't
// work during execution.
Type dtype = _outgoing[0]->getType();
if (DEFINED_SCHEMA_NODE != dtype and
DEFINED_PREDICATE_NODE != dtype and
DEFINED_TYPE_NODE != dtype)
throw SyntaxException(TRACE_INFO,
"Expecting Defined(Schema/Predicate/Type)Node, got %s",
classserver().getTypeName(dtype).c_str());
}
DefineLink::DefineLink(const HandleSeq& oset,
TruthValuePtr tv, AttentionValuePtr av)
: UniqueLink(DEFINE_LINK, oset, tv, av)
{
init();
}
DefineLink::DefineLink(const Handle& name, const Handle& defn,
TruthValuePtr tv, AttentionValuePtr av)
: UniqueLink(DEFINE_LINK, HandleSeq({name, defn}), tv, av)
{
init();
}
DefineLink::DefineLink(Link &l)
: UniqueLink(l)
{
init();
}
/**
* Get the definition associated with the alias.
* This will be the second atom of some DefineLink, where
* `alias` is the first.
*/
Handle DefineLink::get_definition(const Handle& alias)
{
Handle uniq(get_unique(alias, DEFINE_LINK, false));
LinkPtr luniq(LinkCast(uniq));
return luniq->getOutgoingAtom(1);
}
/* ===================== END OF FILE ===================== */
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: writer.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: pjunck $ $Date: 2004-11-03 09:18: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): _______________________________________
*
*
************************************************************************/
#ifndef INCLUDED_registry_writer_hxx
#define INCLUDED_registry_writer_hxx
#include "registry/writer.h"
#include "registry/refltype.hxx"
#include "registry/types.h"
#include "registry/version.h"
#include "rtl/ustring.hxx"
#include "sal/types.h"
#include <new>
namespace typereg {
/// @HTML
/**
A type writer working on a binary blob that represents a UNOIDL type.
<p>Instances of this class are not multi-thread–safe.</p>
@since UDK 3.2.0
*/
class Writer {
public:
/**
Creates a type writer.
@param version the version of the created type writer; must not be
negative
@param documentation the documentation
@param fileName the file name
@param typeClass the type class of the created type writer
@param published whether the created type writer is published; for a type
class that cannot be published, this should be false
@param typeName the type name of the created type writer
@param superTypeCount the number of super types of the created type
writer
@param fieldCount the number of fields of the created type writer
@param methodCount the number of methods of the created type writer
@param referenceCount the number of references of the created type writer
@exception std::bad_alloc is raised if an out-of-memory condition occurs
*/
Writer(
typereg_Version version, rtl::OUString const & documentation,
rtl::OUString const & fileName, RTTypeClass typeClass, bool published,
rtl::OUString const & typeName, sal_uInt16 superTypeCount,
sal_uInt16 fieldCount, sal_uInt16 methodCount,
sal_uInt16 referenceCount):
m_handle(
typereg_writer_create(
version, documentation.pData, fileName.pData, typeClass,
published, typeName.pData, superTypeCount, fieldCount,
methodCount, referenceCount))
{
if (m_handle == 0) {
throw std::bad_alloc();
}
}
/**
Destroys this <code>Writer</code> instance.
*/
~Writer() {
typereg_writer_destroy(m_handle);
}
/**
Sets the type name of a super type of this type writer.
@param index a valid index into the range of super types of this type
writer
@param typeName the super type name
@exception std::bad_alloc is raised if an out-of-memory condition occurs
*/
void setSuperTypeName(sal_uInt16 index, rtl::OUString const & typeName) {
if (!typereg_writer_setSuperTypeName(m_handle, index, typeName.pData)) {
throw std::bad_alloc();
}
}
/**
Sets the data of a field of this type writer.
@param index a valid index into the range of fields of this type writer
@param documentation the documentation of the field
@param fileName the file name of the field
@param flags the flags of the field
@param name the name of the field
@param typeName the type name of the field
@param valueType the type of the value of the field
@param valueValue the value of the value of the field
@exception std::bad_alloc is raised if an out-of-memory condition occurs
*/
void setFieldData(
sal_uInt16 index, rtl::OUString const & documentation,
rtl::OUString const & fileName, RTFieldAccess flags,
rtl::OUString const & name, rtl::OUString const & typeName,
RTConstValue const & value)
{
if (!typereg_writer_setFieldData(
m_handle, index, documentation.pData, fileName.pData, flags,
name.pData, typeName.pData, value.m_type, value.m_value))
{
throw std::bad_alloc();
}
}
/**
Sets the data of a method of this type writer.
@param index a valid index into the range of methods of this type writer
@param documentation the documentation of the method
@param flags the flags of the method
@param name the name of the method
@param returnTypeName the return type name of the method
@param parameterCount the number of parameters of the method
@param exceptionCount the number of exceptions of the method
@exception std::bad_alloc is raised if an out-of-memory condition occurs
*/
void setMethodData(
sal_uInt16 index, rtl::OUString const & documentation,
RTMethodMode flags, rtl::OUString const & name,
rtl::OUString const & returnTypeName, sal_uInt16 parameterCount,
sal_uInt16 exceptionCount)
{
if (!typereg_writer_setMethodData(
m_handle, index, documentation.pData, flags, name.pData,
returnTypeName.pData, parameterCount, exceptionCount))
{
throw std::bad_alloc();
}
}
/**
Sets the data of a parameter of a method of this type writer.
@param methodIndex a valid index into the range of methods of this type
writer
@param parameterIndex a valid index into the range of parameters of the
given method
@param flags the flags of the parameter
@param name the name of the parameter
@param typeName the type name of the parameter
@exception std::bad_alloc is raised if an out-of-memory condition occurs
*/
void setMethodParameterData(
sal_uInt16 methodIndex, sal_uInt16 parameterIndex,
RTParamMode flags, rtl::OUString const & name,
rtl::OUString const & typeName)
{
if (!typereg_writer_setMethodParameterData(
m_handle, methodIndex, parameterIndex, flags, name.pData,
typeName.pData))
{
throw std::bad_alloc();
}
}
/**
Sets an exception type name of a method of this type writer.
@param methodIndex a valid index into the range of methods of this type
writer
@param exceptionIndex a valid index into the range of exceptions of the
given method
@param typeName the exception type name
@exception std::bad_alloc is raised if an out-of-memory condition occurs
*/
void setMethodExceptionTypeName(
sal_uInt16 methodIndex, sal_uInt16 exceptionIndex,
rtl::OUString const & typeName)
{
if (!typereg_writer_setMethodExceptionTypeName(
m_handle, methodIndex, exceptionIndex, typeName.pData))
{
throw std::bad_alloc();
}
}
/**
Sets the data of a reference of this type writer.
@param handle a handle on a type writer
@param index a valid index into the range of references of this type
writer
@param documentation the documentation of the reference
@param sort the sort of the reference
@param flags the flags of the reference
@param typeName the type name of the reference
@exception std::bad_alloc is raised if an out-of-memory condition occurs
*/
void setReferenceData(
sal_uInt16 index, rtl::OUString const & documentation,
RTReferenceType sort, RTFieldAccess flags,
rtl::OUString const & typeName)
{
if (!typereg_writer_setReferenceData(
m_handle, index, documentation.pData, sort, flags,
typeName.pData))
{
throw std::bad_alloc();
}
}
/**
Returns the blob of this type writer.
@param size an out-parameter obtaining the size of the blob
@return a (byte-aligned) pointer to the blob; the returned pointer and
the returned <code>size</code> remain valid until the next function is
called on this type writer
@exception std::bad_alloc is raised if an out-of-memory condition occurs
(in which case <code>siez</code> is not modified
*/
void const * getBlob(sal_uInt32 * size) {
void const * p = typereg_writer_getBlob(m_handle, size);
if (p == 0) {
throw std::bad_alloc();
}
return p;
}
private:
Writer(Writer &); // not implemented
void operator =(Writer); // not implemented
void * m_handle;
};
}
#endif
<commit_msg>INTEGRATION: CWS sdksample (1.3.18); FILE MERGED 2004/11/26 16:14:19 jsc 1.3.18.3: #i29966# remove to optimistic API change 2004/11/16 09:04:16 jsc 1.3.18.2: RESYNC: (1.3-1.4); FILE MERGED 2004/10/27 15:58:25 jsc 1.3.18.1: #i29966# remove filename related APIs<commit_after>/*************************************************************************
*
* $RCSfile: writer.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: rt $ $Date: 2005-01-31 15:47:48 $
*
* 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 INCLUDED_registry_writer_hxx
#define INCLUDED_registry_writer_hxx
#include "registry/writer.h"
#include "registry/refltype.hxx"
#include "registry/types.h"
#include "registry/version.h"
#include "rtl/ustring.hxx"
#include "sal/types.h"
#include <new>
namespace typereg {
/// @HTML
/**
A type writer working on a binary blob that represents a UNOIDL type.
<p>Instances of this class are not multi-thread–safe.</p>
@since UDK 3.2.0
*/
class Writer {
public:
/**
Creates a type writer.
@param version the version of the created type writer; must not be
negative
@param documentation the documentation
@param fileName the file name (deprecated, use an empty string)
@param typeClass the type class of the created type writer
@param published whether the created type writer is published; for a type
class that cannot be published, this should be false
@param typeName the type name of the created type writer
@param superTypeCount the number of super types of the created type
writer
@param fieldCount the number of fields of the created type writer
@param methodCount the number of methods of the created type writer
@param referenceCount the number of references of the created type writer
@exception std::bad_alloc is raised if an out-of-memory condition occurs
*/
Writer(
typereg_Version version, rtl::OUString const & documentation,
rtl::OUString const & fileName, RTTypeClass typeClass, bool published,
rtl::OUString const & typeName, sal_uInt16 superTypeCount,
sal_uInt16 fieldCount, sal_uInt16 methodCount,
sal_uInt16 referenceCount):
m_handle(
typereg_writer_create(
version, documentation.pData, fileName.pData, typeClass,
published, typeName.pData, superTypeCount, fieldCount,
methodCount, referenceCount))
{
if (m_handle == 0) {
throw std::bad_alloc();
}
}
/**
Destroys this <code>Writer</code> instance.
*/
~Writer() {
typereg_writer_destroy(m_handle);
}
/**
Sets the type name of a super type of this type writer.
@param index a valid index into the range of super types of this type
writer
@param typeName the super type name
@exception std::bad_alloc is raised if an out-of-memory condition occurs
*/
void setSuperTypeName(sal_uInt16 index, rtl::OUString const & typeName) {
if (!typereg_writer_setSuperTypeName(m_handle, index, typeName.pData)) {
throw std::bad_alloc();
}
}
/**
Sets the data of a field of this type writer.
@param index a valid index into the range of fields of this type writer
@param documentation the documentation of the field
@param fileName the file name of the field (deprecated, use an empty string)
@param flags the flags of the field
@param name the name of the field
@param typeName the type name of the field
@param valueType the type of the value of the field
@param valueValue the value of the value of the field
@exception std::bad_alloc is raised if an out-of-memory condition occurs
*/
void setFieldData(
sal_uInt16 index, rtl::OUString const & documentation,
rtl::OUString const & fileName, RTFieldAccess flags, rtl::OUString const & name,
rtl::OUString const & typeName, RTConstValue const & value)
{
if (!typereg_writer_setFieldData(
m_handle, index, documentation.pData, fileName.pData, flags,
name.pData, typeName.pData, value.m_type, value.m_value))
{
throw std::bad_alloc();
}
}
/**
Sets the data of a method of this type writer.
@param index a valid index into the range of methods of this type writer
@param documentation the documentation of the method
@param flags the flags of the method
@param name the name of the method
@param returnTypeName the return type name of the method
@param parameterCount the number of parameters of the method
@param exceptionCount the number of exceptions of the method
@exception std::bad_alloc is raised if an out-of-memory condition occurs
*/
void setMethodData(
sal_uInt16 index, rtl::OUString const & documentation,
RTMethodMode flags, rtl::OUString const & name,
rtl::OUString const & returnTypeName, sal_uInt16 parameterCount,
sal_uInt16 exceptionCount)
{
if (!typereg_writer_setMethodData(
m_handle, index, documentation.pData, flags, name.pData,
returnTypeName.pData, parameterCount, exceptionCount))
{
throw std::bad_alloc();
}
}
/**
Sets the data of a parameter of a method of this type writer.
@param methodIndex a valid index into the range of methods of this type
writer
@param parameterIndex a valid index into the range of parameters of the
given method
@param flags the flags of the parameter
@param name the name of the parameter
@param typeName the type name of the parameter
@exception std::bad_alloc is raised if an out-of-memory condition occurs
*/
void setMethodParameterData(
sal_uInt16 methodIndex, sal_uInt16 parameterIndex,
RTParamMode flags, rtl::OUString const & name,
rtl::OUString const & typeName)
{
if (!typereg_writer_setMethodParameterData(
m_handle, methodIndex, parameterIndex, flags, name.pData,
typeName.pData))
{
throw std::bad_alloc();
}
}
/**
Sets an exception type name of a method of this type writer.
@param methodIndex a valid index into the range of methods of this type
writer
@param exceptionIndex a valid index into the range of exceptions of the
given method
@param typeName the exception type name
@exception std::bad_alloc is raised if an out-of-memory condition occurs
*/
void setMethodExceptionTypeName(
sal_uInt16 methodIndex, sal_uInt16 exceptionIndex,
rtl::OUString const & typeName)
{
if (!typereg_writer_setMethodExceptionTypeName(
m_handle, methodIndex, exceptionIndex, typeName.pData))
{
throw std::bad_alloc();
}
}
/**
Sets the data of a reference of this type writer.
@param handle a handle on a type writer
@param index a valid index into the range of references of this type
writer
@param documentation the documentation of the reference
@param sort the sort of the reference
@param flags the flags of the reference
@param typeName the type name of the reference
@exception std::bad_alloc is raised if an out-of-memory condition occurs
*/
void setReferenceData(
sal_uInt16 index, rtl::OUString const & documentation,
RTReferenceType sort, RTFieldAccess flags,
rtl::OUString const & typeName)
{
if (!typereg_writer_setReferenceData(
m_handle, index, documentation.pData, sort, flags,
typeName.pData))
{
throw std::bad_alloc();
}
}
/**
Returns the blob of this type writer.
@param size an out-parameter obtaining the size of the blob
@return a (byte-aligned) pointer to the blob; the returned pointer and
the returned <code>size</code> remain valid until the next function is
called on this type writer
@exception std::bad_alloc is raised if an out-of-memory condition occurs
(in which case <code>siez</code> is not modified
*/
void const * getBlob(sal_uInt32 * size) {
void const * p = typereg_writer_getBlob(m_handle, size);
if (p == 0) {
throw std::bad_alloc();
}
return p;
}
private:
Writer(Writer &); // not implemented
void operator =(Writer); // not implemented
void * m_handle;
};
}
#endif
<|endoftext|> |
<commit_before>/******************************************************************************
* _ _____ __________ *
* | | / / _ | / __/_ __/ Visibility *
* | |/ / __ |_\ \ / / Across *
* |___/_/ |_/___/ /_/ Space and Time *
* *
* This file is part of VAST. It is subject to the license terms in the *
* LICENSE file found in the top-level directory of this distribution and at *
* http://vast.io/license. No part of VAST, including this file, may be *
* copied, modified, propagated, or distributed except according to the terms *
* contained in the LICENSE file. *
******************************************************************************/
#include <atomic>
#include <csignal>
#include <cstdint>
#include <cstdlib>
#include <iostream>
#include <string>
#include <caf/config_option_adder.hpp>
#include <broker/bro.hh>
#include <broker/broker.hh>
#include <vast/data.hpp>
#include <vast/defaults.hpp>
#include <vast/error.hpp>
#include <vast/event.hpp>
#include <vast/expression.hpp>
#include <vast/logger.hpp>
#include <vast/uuid.hpp>
#include <vast/concept/parseable/parse.hpp>
#include <vast/concept/parseable/vast/expression.hpp>
#include <vast/concept/parseable/vast/uuid.hpp>
#include <vast/format/writer.hpp>
#include <vast/system/sink.hpp>
#include <vast/system/sink_command.hpp>
#include <vast/detail/add_error_categories.hpp>
#include <vast/detail/add_message_types.hpp>
#include <vast/detail/overload.hpp>
using namespace std::chrono_literals;
namespace {
constexpr char control_topic[] = "/vast/control";
constexpr char data_topic[] = "/vast/data";
/// The address where the Broker endpoint listens at.
constexpr char default_address[] = "127.0.0.1";
/// The port where the Broker endpoint binds to.
constexpr uint16_t default_port = 43000;
// The timeout after which a blocking call to retrieve a message from a
// subscriber should return.
broker::duration get_timeout = broker::duration{500ms};
// Global flag that indicates that the application is shutting down due to a
// signal.
std::atomic<bool> terminating = false;
// Double-check the signal handler requirement.
static_assert(decltype(terminating)::is_always_lock_free);
extern "C" void signal_handler(int sig) {
// Catch termination signals only once to allow forced termination by the OS
// upon sending the signal a second time.
if (sig == SIGINT || sig == SIGTERM)
std::signal(sig, SIG_DFL);
terminating = true;
}
// Our custom configuration with extra command line options for this tool.
class config : public broker::configuration {
public:
config() {
// Print a reasonable amount of logging output to the console.
set("logger.console", caf::atom("COLORED"));
set("logger.verbosity", caf::atom("INFO"));
// As a stand-alone application, we reuse the global option group from CAF
// to avoid unnecessary prefixing.
opt_group{custom_options_, "global"}
.add<std::string>("address,a", "the address where the endpoints listens")
.add<uint16_t>("port,p", "the port where the endpoint binds to")
.add<bool>("show-progress,s", "print one '.' for each proccessed event");
}
};
/// Converts VAST data to the corresponding Broker type.
broker::data to_broker(const vast::data& data) {
return caf::visit(vast::detail::overload(
[](const auto& x) -> broker::data {
return x;
},
[](caf::none_t) -> broker::data {
return {};
},
[](const vast::pattern& x) -> broker::data {
return x.string();
},
[](const vast::address& x) -> broker::data {
auto bytes = reinterpret_cast<const uint32_t*>(x.data().data());
return broker::address{bytes, broker::address::family::ipv6,
broker::address::byte_order::network};
},
[](const vast::subnet& x) -> broker::data {
auto bytes = reinterpret_cast<const uint32_t*>(x.network().data().data());
auto addr = broker::address{bytes, broker::address::family::ipv6,
broker::address::byte_order::network};
return broker::subnet(addr, x.length());
},
[](vast::port x) -> broker::data {
// We rely on the fact that port types don't change...ever.
auto protocol = static_cast<broker::port::protocol>(x.type());
return broker::port{x.number(), protocol};
},
[](vast::enumeration x) -> broker::data {
// FIXME: here we face two different implementation approaches for enums.
// To represent the actual enum value, Broker uses a string whereas VAST
// uses a 32-bit unsigned integer. We currently lose the type information
// by converting the VAST enum into a Broker count. A wholistic approach
// would include the type information for this data instance and perform
// the string conversion.
return broker::count{x};
},
[](const vast::vector& xs) -> broker::data {
broker::vector result;
result.reserve(xs.size());
std::transform(xs.begin(), xs.end(), std::back_inserter(result),
[](const auto& x) { return to_broker(x); });
return result;
},
[](const vast::set& xs) -> broker::data {
broker::set result;
std::transform(xs.begin(), xs.end(), std::inserter(result, result.end()),
[](const auto& x) { return to_broker(x); });
return result;
},
[](const vast::map& xs) -> broker::data {
broker::table result;
auto f = [](const auto& x) { return std::pair{to_broker(x.first),
to_broker(x.second)}; };
std::transform(xs.begin(), xs.end(), std::inserter(result, result.end()),
f);
return result;
}
), data);
}
// Constructs a result event for Bro from Broker data.
broker::bro::Event make_result_event(std::string name, broker::data x) {
broker::vector args(2);
args[0] = std::move(name);
args[1] = std::move(x);
return {"VAST::result", std::move(args)};
}
// Constructs a result event for Bro from a VAST event.
broker::bro::Event make_result_event(const vast::event& x) {
return make_result_event(x.type().name(), to_broker(x.data()));
}
// A VAST writer that publishes the event it gets to a Bro endpoint.
class bro_writer : public vast::format::writer {
public:
bro_writer() = default;
bro_writer(broker::endpoint& endpoint, std::string query_id)
: endpoint_{&endpoint},
query_id_{std::move(query_id)} {
auto& cfg = endpoint.system().config();
show_progress_ = caf::get_or(cfg, "show-progress", false);
}
~bro_writer() {
if (show_progress_ && num_results_ > 0)
std::cerr << std::endl;
VAST_INFO_ANON("query", query_id_, "had", num_results_, "result(s)");
}
caf::expected<void> write(const vast::event& x) override {
++num_results_;
if (show_progress_)
std::cerr << '.';
endpoint_->publish(data_topic, make_result_event(x));
return caf::no_error;
}
const char* name() const override {
return "bro-writer";
}
private:
broker::endpoint* endpoint_;
std::string query_id_;
bool show_progress_ = false;
size_t num_results_ = 0;
};
// A custom command that allows us to re-use VAST command dispatching logic in
// order to issue a query that writes into a sink with a custom format.
class bro_command : public vast::system::sink_command {
public:
bro_command(broker::endpoint& endpoint)
: sink_command{nullptr, "bro"},
endpoint_{endpoint} {
// nop
}
// Sets the query ID to the UUID provided by Bro.
void query_id(std::string id) {
query_id_ = std::move(id);
}
/// Retrieves the current sink actor, which terminates when the exporter
/// corresponding to the issued query terminates.
caf::actor sink() const {
return sink_;
}
protected:
caf::expected<caf::actor> make_sink(caf::scoped_actor& self,
const caf::config_value_map& options,
argument_iterator begin,
argument_iterator end) override {
VAST_UNUSED(options, begin, end);
bro_writer writer{endpoint_, query_id_};
sink_ = self->spawn(vast::system::sink<bro_writer>, std::move(writer),
vast::defaults::command::max_events);
return sink_;
}
private:
broker::endpoint& endpoint_;
std::string query_id_;
caf::actor sink_;
};
// Parses Broker data as Bro event.
caf::expected<std::pair<std::string, std::string>>
parse_query_event(const broker::data& x) {
std::pair<std::string, std::string> result;
auto event = broker::bro::Event(x);
if (event.name() != "VAST::query")
return make_error(vast::ec::parse_error, "invalid event name", event.name());
if (event.args().size() != 2)
return make_error(vast::ec::parse_error, "invalid number of arguments");
auto query_id = caf::get_if<std::string>(&event.args()[0]);
if (!query_id)
return make_error(vast::ec::parse_error, "invalid type of 1st argument");
result.first = *query_id;
if (!vast::parsers::uuid(*query_id))
return make_error(vast::ec::parse_error, "invalid query UUID", *query_id);
auto expression = caf::get_if<std::string>(&event.args()[1]);
if (!expression)
return make_error(vast::ec::parse_error, "invalid type of 2nd argument");
if (!vast::parsers::expr(*expression))
return make_error(vast::ec::parse_error, "invalid query expression",
*expression);
result.second = *expression;
return result;
}
} // namespace <anonymous>
int main(int argc, char** argv) {
// Parse the command line.
config cfg;
vast::detail::add_message_types(cfg);
vast::detail::add_error_categories(cfg);
cfg.parse(argc, argv);
std::string address = caf::get_or(cfg, "address", default_address);
uint16_t port = caf::get_or(cfg, "port", default_port);
// Create a Broker endpoint.
auto endpoint = broker::endpoint{std::move(cfg)};
endpoint.listen(address, port);
// Subscribe to the control channel.
auto subscriber = endpoint.make_subscriber({control_topic});
// Connect to VAST via a custom command.
bro_command cmd{endpoint};
auto& sys = endpoint.system();
caf::scoped_actor self{sys};
caf::config_value_map opts;
auto node = cmd.connect_to_node(self, opts);
if (!node) {
VAST_ERROR_ANON("failed to connect to VAST: " << sys.render(node.error()));
return 1;
}
VAST_INFO_ANON("connected to VAST successfully" );
// Block until Bro peers with us.
auto receive_statuses = true;
auto status_subscriber = endpoint.make_status_subscriber(receive_statuses);
auto peered = false;
while (!peered) {
auto msg = status_subscriber.get(get_timeout);
if (terminating)
return -1;
if (!msg)
continue; // timeout
caf::visit(vast::detail::overload(
[&](broker::none) {
// timeout
},
[&](broker::error error) {
VAST_ERROR_ANON(sys.render(error));
},
[&](broker::status status) {
if (status == broker::sc::peer_added)
peered = true;
else
VAST_ERROR_ANON(to_string(status));
}
), *msg);
};
VAST_INFO_ANON("peered with Bro successfully, waiting for commands");
// Process queries from Bro.
auto done = false;
while (!done) {
auto msg = subscriber.get(get_timeout);
if (terminating)
return -1;
if (!msg)
continue; // timeout
auto& [topic, data] = *msg;
// Parse the Bro query event.
auto result = parse_query_event(data);
if (!result) {
VAST_ERROR_ANON(sys.render(result.error()));
continue;
}
auto& [query_id, expression] = *result;
// Relay the query expression to VAST.
cmd.query_id(query_id);
auto args = std::vector<std::string>{expression};
VAST_INFO_ANON("dispatching query", query_id, expression);
auto rc = cmd.run(sys, args.begin(), args.end());
if (rc != 0) {
VAST_ERROR_ANON("failed to dispatch query to VAST");
return rc;
}
// Our Bro command contains a sink, which terminates automatically when the
// exporter for the corresponding query has finished. We use this signal to
// send the final terminator event to Bro.
self->monitor(cmd.sink());
self->receive(
[&, query_id=query_id](const caf::down_msg&) {
endpoint.publish(data_topic, make_result_event(query_id, broker::nil));
}
);
}
}
<commit_msg>Do not execute when usage is requested<commit_after>/******************************************************************************
* _ _____ __________ *
* | | / / _ | / __/_ __/ Visibility *
* | |/ / __ |_\ \ / / Across *
* |___/_/ |_/___/ /_/ Space and Time *
* *
* This file is part of VAST. It is subject to the license terms in the *
* LICENSE file found in the top-level directory of this distribution and at *
* http://vast.io/license. No part of VAST, including this file, may be *
* copied, modified, propagated, or distributed except according to the terms *
* contained in the LICENSE file. *
******************************************************************************/
#include <atomic>
#include <csignal>
#include <cstdint>
#include <cstdlib>
#include <iostream>
#include <string>
#include <caf/config_option_adder.hpp>
#include <broker/bro.hh>
#include <broker/broker.hh>
#include <vast/data.hpp>
#include <vast/defaults.hpp>
#include <vast/error.hpp>
#include <vast/event.hpp>
#include <vast/expression.hpp>
#include <vast/logger.hpp>
#include <vast/uuid.hpp>
#include <vast/concept/parseable/parse.hpp>
#include <vast/concept/parseable/vast/expression.hpp>
#include <vast/concept/parseable/vast/uuid.hpp>
#include <vast/format/writer.hpp>
#include <vast/system/sink.hpp>
#include <vast/system/sink_command.hpp>
#include <vast/detail/add_error_categories.hpp>
#include <vast/detail/add_message_types.hpp>
#include <vast/detail/overload.hpp>
using namespace std::chrono_literals;
namespace {
constexpr char control_topic[] = "/vast/control";
constexpr char data_topic[] = "/vast/data";
/// The address where the Broker endpoint listens at.
constexpr char default_address[] = "127.0.0.1";
/// The port where the Broker endpoint binds to.
constexpr uint16_t default_port = 43000;
// The timeout after which a blocking call to retrieve a message from a
// subscriber should return.
broker::duration get_timeout = broker::duration{500ms};
// Global flag that indicates that the application is shutting down due to a
// signal.
std::atomic<bool> terminating = false;
// Double-check the signal handler requirement.
static_assert(decltype(terminating)::is_always_lock_free);
extern "C" void signal_handler(int sig) {
// Catch termination signals only once to allow forced termination by the OS
// upon sending the signal a second time.
if (sig == SIGINT || sig == SIGTERM)
std::signal(sig, SIG_DFL);
terminating = true;
}
// Our custom configuration with extra command line options for this tool.
class config : public broker::configuration {
public:
config() {
// Print a reasonable amount of logging output to the console.
set("logger.console", caf::atom("COLORED"));
set("logger.verbosity", caf::atom("INFO"));
// As a stand-alone application, we reuse the global option group from CAF
// to avoid unnecessary prefixing.
opt_group{custom_options_, "global"}
.add<std::string>("address,a", "the address where the endpoints listens")
.add<uint16_t>("port,p", "the port where the endpoint binds to")
.add<bool>("show-progress,s", "print one '.' for each proccessed event");
}
};
/// Converts VAST data to the corresponding Broker type.
broker::data to_broker(const vast::data& data) {
return caf::visit(vast::detail::overload(
[](const auto& x) -> broker::data {
return x;
},
[](caf::none_t) -> broker::data {
return {};
},
[](const vast::pattern& x) -> broker::data {
return x.string();
},
[](const vast::address& x) -> broker::data {
auto bytes = reinterpret_cast<const uint32_t*>(x.data().data());
return broker::address{bytes, broker::address::family::ipv6,
broker::address::byte_order::network};
},
[](const vast::subnet& x) -> broker::data {
auto bytes = reinterpret_cast<const uint32_t*>(x.network().data().data());
auto addr = broker::address{bytes, broker::address::family::ipv6,
broker::address::byte_order::network};
return broker::subnet(addr, x.length());
},
[](vast::port x) -> broker::data {
// We rely on the fact that port types don't change...ever.
auto protocol = static_cast<broker::port::protocol>(x.type());
return broker::port{x.number(), protocol};
},
[](vast::enumeration x) -> broker::data {
// FIXME: here we face two different implementation approaches for enums.
// To represent the actual enum value, Broker uses a string whereas VAST
// uses a 32-bit unsigned integer. We currently lose the type information
// by converting the VAST enum into a Broker count. A wholistic approach
// would include the type information for this data instance and perform
// the string conversion.
return broker::count{x};
},
[](const vast::vector& xs) -> broker::data {
broker::vector result;
result.reserve(xs.size());
std::transform(xs.begin(), xs.end(), std::back_inserter(result),
[](const auto& x) { return to_broker(x); });
return result;
},
[](const vast::set& xs) -> broker::data {
broker::set result;
std::transform(xs.begin(), xs.end(), std::inserter(result, result.end()),
[](const auto& x) { return to_broker(x); });
return result;
},
[](const vast::map& xs) -> broker::data {
broker::table result;
auto f = [](const auto& x) { return std::pair{to_broker(x.first),
to_broker(x.second)}; };
std::transform(xs.begin(), xs.end(), std::inserter(result, result.end()),
f);
return result;
}
), data);
}
// Constructs a result event for Bro from Broker data.
broker::bro::Event make_result_event(std::string name, broker::data x) {
broker::vector args(2);
args[0] = std::move(name);
args[1] = std::move(x);
return {"VAST::result", std::move(args)};
}
// Constructs a result event for Bro from a VAST event.
broker::bro::Event make_result_event(const vast::event& x) {
return make_result_event(x.type().name(), to_broker(x.data()));
}
// A VAST writer that publishes the event it gets to a Bro endpoint.
class bro_writer : public vast::format::writer {
public:
bro_writer() = default;
bro_writer(broker::endpoint& endpoint, std::string query_id)
: endpoint_{&endpoint},
query_id_{std::move(query_id)} {
auto& cfg = endpoint.system().config();
show_progress_ = caf::get_or(cfg, "show-progress", false);
}
~bro_writer() {
if (show_progress_ && num_results_ > 0)
std::cerr << std::endl;
VAST_INFO_ANON("query", query_id_, "had", num_results_, "result(s)");
}
caf::expected<void> write(const vast::event& x) override {
++num_results_;
if (show_progress_)
std::cerr << '.';
endpoint_->publish(data_topic, make_result_event(x));
return caf::no_error;
}
const char* name() const override {
return "bro-writer";
}
private:
broker::endpoint* endpoint_;
std::string query_id_;
bool show_progress_ = false;
size_t num_results_ = 0;
};
// A custom command that allows us to re-use VAST command dispatching logic in
// order to issue a query that writes into a sink with a custom format.
class bro_command : public vast::system::sink_command {
public:
bro_command(broker::endpoint& endpoint)
: sink_command{nullptr, "bro"},
endpoint_{endpoint} {
// nop
}
// Sets the query ID to the UUID provided by Bro.
void query_id(std::string id) {
query_id_ = std::move(id);
}
/// Retrieves the current sink actor, which terminates when the exporter
/// corresponding to the issued query terminates.
caf::actor sink() const {
return sink_;
}
protected:
caf::expected<caf::actor> make_sink(caf::scoped_actor& self,
const caf::config_value_map& options,
argument_iterator begin,
argument_iterator end) override {
VAST_UNUSED(options, begin, end);
bro_writer writer{endpoint_, query_id_};
sink_ = self->spawn(vast::system::sink<bro_writer>, std::move(writer),
vast::defaults::command::max_events);
return sink_;
}
private:
broker::endpoint& endpoint_;
std::string query_id_;
caf::actor sink_;
};
// Parses Broker data as Bro event.
caf::expected<std::pair<std::string, std::string>>
parse_query_event(const broker::data& x) {
std::pair<std::string, std::string> result;
auto event = broker::bro::Event(x);
if (event.name() != "VAST::query")
return make_error(vast::ec::parse_error, "invalid event name", event.name());
if (event.args().size() != 2)
return make_error(vast::ec::parse_error, "invalid number of arguments");
auto query_id = caf::get_if<std::string>(&event.args()[0]);
if (!query_id)
return make_error(vast::ec::parse_error, "invalid type of 1st argument");
result.first = *query_id;
if (!vast::parsers::uuid(*query_id))
return make_error(vast::ec::parse_error, "invalid query UUID", *query_id);
auto expression = caf::get_if<std::string>(&event.args()[1]);
if (!expression)
return make_error(vast::ec::parse_error, "invalid type of 2nd argument");
if (!vast::parsers::expr(*expression))
return make_error(vast::ec::parse_error, "invalid query expression",
*expression);
result.second = *expression;
return result;
}
} // namespace <anonymous>
int main(int argc, char** argv) {
// Parse the command line.
config cfg;
vast::detail::add_message_types(cfg);
vast::detail::add_error_categories(cfg);
cfg.parse(argc, argv);
if (caf::get_or(cfg, "help", false))
return 0;
std::string address = caf::get_or(cfg, "address", default_address);
uint16_t port = caf::get_or(cfg, "port", default_port);
// Create a Broker endpoint.
auto endpoint = broker::endpoint{std::move(cfg)};
endpoint.listen(address, port);
// Subscribe to the control channel.
auto subscriber = endpoint.make_subscriber({control_topic});
// Connect to VAST via a custom command.
bro_command cmd{endpoint};
auto& sys = endpoint.system();
caf::scoped_actor self{sys};
caf::config_value_map opts;
auto node = cmd.connect_to_node(self, opts);
if (!node) {
VAST_ERROR_ANON("failed to connect to VAST: " << sys.render(node.error()));
return 1;
}
VAST_INFO_ANON("connected to VAST successfully" );
// Block until Bro peers with us.
auto receive_statuses = true;
auto status_subscriber = endpoint.make_status_subscriber(receive_statuses);
auto peered = false;
while (!peered) {
auto msg = status_subscriber.get(get_timeout);
if (terminating)
return -1;
if (!msg)
continue; // timeout
caf::visit(vast::detail::overload(
[&](broker::none) {
// timeout
},
[&](broker::error error) {
VAST_ERROR_ANON(sys.render(error));
},
[&](broker::status status) {
if (status == broker::sc::peer_added)
peered = true;
else
VAST_ERROR_ANON(to_string(status));
}
), *msg);
};
VAST_INFO_ANON("peered with Bro successfully, waiting for commands");
// Process queries from Bro.
auto done = false;
while (!done) {
auto msg = subscriber.get(get_timeout);
if (terminating)
return -1;
if (!msg)
continue; // timeout
auto& [topic, data] = *msg;
// Parse the Bro query event.
auto result = parse_query_event(data);
if (!result) {
VAST_ERROR_ANON(sys.render(result.error()));
continue;
}
auto& [query_id, expression] = *result;
// Relay the query expression to VAST.
cmd.query_id(query_id);
auto args = std::vector<std::string>{expression};
VAST_INFO_ANON("dispatching query", query_id, expression);
auto rc = cmd.run(sys, args.begin(), args.end());
if (rc != 0) {
VAST_ERROR_ANON("failed to dispatch query to VAST");
return rc;
}
// Our Bro command contains a sink, which terminates automatically when the
// exporter for the corresponding query has finished. We use this signal to
// send the final terminator event to Bro.
self->monitor(cmd.sink());
self->receive(
[&, query_id=query_id](const caf::down_msg&) {
endpoint.publish(data_topic, make_result_event(query_id, broker::nil));
}
);
}
}
<|endoftext|> |
<commit_before>/******************************************************************************
* _ _____ __________ *
* | | / / _ | / __/_ __/ Visibility *
* | |/ / __ |_\ \ / / Across *
* |___/_/ |_/___/ /_/ Space and Time *
* *
* This file is part of VAST. It is subject to the license terms in the *
* LICENSE file found in the top-level directory of this distribution and at *
* http://vast.io/license. No part of VAST, including this file, may be *
* copied, modified, propagated, or distributed except according to the terms *
* contained in the LICENSE file. *
******************************************************************************/
#include <cstdint>
#include <iostream>
#include <string>
#include <caf/config_option_adder.hpp>
#include <broker/bro.hh>
#include <broker/broker.hh>
#include <vast/defaults.hpp>
#include <vast/error.hpp>
#include <vast/event.hpp>
#include <vast/expression.hpp>
#include <vast/uuid.hpp>
#include <vast/concept/parseable/parse.hpp>
#include <vast/concept/parseable/vast/expression.hpp>
#include <vast/concept/parseable/vast/uuid.hpp>
#include <vast/system/writer_command_base.hpp>
#include <vast/system/sink.hpp>
#include <vast/detail/assert.hpp>
#include <vast/detail/overload.hpp>
namespace {
constexpr char control_topic[] = "/vast/control";
constexpr char data_topic[] = "/vast/data";
constexpr char default_address[] = "localhost";
constexpr uint16_t default_port = 43000;
// Our custom configuration with extra command line options for this tool.
class config : public broker::configuration {
public:
config() {
// As a stand-alone application, we reuse the global option group from CAF
// to avoid unnecessary prefixing.
opt_group{custom_options_, "global"}
.add<uint16_t>("port,p", "the port to listen at or connect to");
}
};
// Constructs a result event for Bro.
broker::bro::Event make_bro_event(std::string id, broker::data x) {
broker::vector args(2);
args[0] = std::move(id);
args[1] = std::move(x);
return {"VAST::result", std::move(args)};
}
// A VAST writer that publishes the event it gets to a Bro endpoint.
class bro_writer {
public:
bro_writer() = default;
bro_writer(broker::endpoint& endpoint, std::string query_id)
: endpoint_{&endpoint},
query_id_{std::move(query_id)} {
// nop
}
caf::expected<void> write(const vast::event& x) {
// TODO: publish to Broker endpoint.
std::cout << x.type().name() << std::endl;
return caf::no_error;
}
caf::expected<void> flush() {
return caf::no_error;
}
auto name() const {
return "bro-writer";
}
private:
broker::endpoint* endpoint_;
std::string query_id_;
};
// A custom command that allows us to re-use VAST command dispatching logic in
// order to issue a query that writes into a sink with a custom format.
class bro_command : public vast::system::writer_command_base {
public:
bro_command(broker::endpoint& endpoint)
: writer_command_base{nullptr, "bro"},
endpoint_{endpoint} {
// nop
}
// Sets the query ID to the UUID provided by Bro.
void query_id(std::string id) {
query_id_ = std::move(id);
}
protected:
caf::expected<caf::actor> make_sink(caf::scoped_actor& self,
const caf::config_value_map& options,
argument_iterator begin,
argument_iterator end) override {
VAST_UNUSED(options, begin, end);
bro_writer writer{endpoint_, query_id_};
return self->spawn(vast::system::sink<bro_writer>, std::move(writer),
vast::defaults::command::max_events);
}
private:
broker::endpoint& endpoint_;
std::string query_id_;
};
// Parses Broker data as Bro event.
caf::expected<std::pair<std::string, std::string>>
parse_query_event(const broker::data& x) {
std::pair<std::string, std::string> result;
auto event = broker::bro::Event(x);
if (event.name() != "VAST::query")
return make_error(vast::ec::parse_error, "invalid event name", event.name());
if (event.args().size() != 2)
return make_error(vast::ec::parse_error, "invalid number of arguments");
auto query_id = caf::get_if<std::string>(&event.args()[0]);
if (!query_id)
return make_error(vast::ec::parse_error, "invalid type of 1st argument");
result.first = *query_id;
if (!vast::parsers::uuid(*query_id))
return make_error(vast::ec::parse_error, "invalid query UUID", *query_id);
auto expression = caf::get_if<std::string>(&event.args()[1]);
if (!expression)
return make_error(vast::ec::parse_error, "invalid type of 2nd argument");
if (!vast::parsers::expr(*expression))
return make_error(vast::ec::parse_error, "invalid query expression",
*expression);
result.second = *expression;
return result;
}
} // namespace <anonymous>
int main(int argc, char** argv) {
// Parse the command line.
config cfg;
cfg.parse(argc, argv);
std::string address = caf::get_or(cfg, "address", default_address);
uint16_t port = caf::get_or(cfg, "port", default_port);
// Create a Broker endpoint.
auto endpoint = broker::endpoint{std::move(cfg)};
endpoint.listen(address, port);
// Subscribe to the control channel.
auto subscriber = endpoint.make_subscriber({control_topic});
// Connect to VAST via a custom command.
bro_command cmd{endpoint};
auto& sys = endpoint.system();
caf::scoped_actor self{sys};
caf::config_value_map opts;
auto node = cmd.connect_to_node(self, opts);
if (!node) {
std::cerr << "failed to connect to VAST: " << sys.render(node.error())
<< std::endl;
return 1;
}
std::cerr << "connected to VAST successfully" << std::endl;
// Block until Bro peers with us.
auto receive_statuses = true;
auto status_subscriber = endpoint.make_status_subscriber(receive_statuses);
auto peered = false;
while (!peered) {
auto msg = status_subscriber.get();
caf::visit(vast::detail::overload(
[&](broker::none) {
// timeout
},
[&](broker::error error) {
std::cerr << sys.render(error) << std::endl;
},
[&](broker::status status) {
if (status == broker::sc::peer_added)
peered = true;
else
std::cerr << to_string(status) << std::endl;
}
), msg);
};
std::cerr << "peered with Bro successfully" << std::endl;
// Process queries from Bro.
auto done = false;
while (!done) {
std::cerr << "waiting for commands" << std::endl;
auto [topic, data] = subscriber.get();
// Parse the Bro query event.
auto result = parse_query_event(data);
if (!result) {
std::cerr << sys.render(result.error()) << std::endl;
return 1;
}
auto& [query_id, expression] = *result;
// Relay the query expression to VAST.
cmd.query_id(query_id);
auto args = std::vector<std::string>{expression};
auto rc = cmd.run(sys, args.begin(), args.end());
if (rc != 0) {
std::cerr << "failed to dispatch query to VAST" << std::endl;
return rc;
}
// A none value signals that the query has completed.
endpoint.publish(data_topic, make_bro_event(query_id, broker::nil));
}
}
<commit_msg>Add VAST types to Broker actor system config<commit_after>/******************************************************************************
* _ _____ __________ *
* | | / / _ | / __/_ __/ Visibility *
* | |/ / __ |_\ \ / / Across *
* |___/_/ |_/___/ /_/ Space and Time *
* *
* This file is part of VAST. It is subject to the license terms in the *
* LICENSE file found in the top-level directory of this distribution and at *
* http://vast.io/license. No part of VAST, including this file, may be *
* copied, modified, propagated, or distributed except according to the terms *
* contained in the LICENSE file. *
******************************************************************************/
#include <cstdint>
#include <iostream>
#include <string>
#include <caf/config_option_adder.hpp>
#include <broker/bro.hh>
#include <broker/broker.hh>
#include <vast/defaults.hpp>
#include <vast/error.hpp>
#include <vast/event.hpp>
#include <vast/expression.hpp>
#include <vast/uuid.hpp>
#include <vast/concept/parseable/parse.hpp>
#include <vast/concept/parseable/vast/expression.hpp>
#include <vast/concept/parseable/vast/uuid.hpp>
#include <vast/system/writer_command_base.hpp>
#include <vast/system/sink.hpp>
#include <vast/detail/add_message_types.hpp>
#include <vast/detail/assert.hpp>
#include <vast/detail/overload.hpp>
namespace {
constexpr char control_topic[] = "/vast/control";
constexpr char data_topic[] = "/vast/data";
constexpr char default_address[] = "localhost";
constexpr uint16_t default_port = 43000;
// Our custom configuration with extra command line options for this tool.
class config : public broker::configuration {
public:
config() {
// As a stand-alone application, we reuse the global option group from CAF
// to avoid unnecessary prefixing.
opt_group{custom_options_, "global"}
.add<uint16_t>("port,p", "the port to listen at or connect to");
}
};
// Constructs a result event for Bro.
broker::bro::Event make_bro_event(std::string id, broker::data x) {
broker::vector args(2);
args[0] = std::move(id);
args[1] = std::move(x);
return {"VAST::result", std::move(args)};
}
// A VAST writer that publishes the event it gets to a Bro endpoint.
class bro_writer {
public:
bro_writer() = default;
bro_writer(broker::endpoint& endpoint, std::string query_id)
: endpoint_{&endpoint},
query_id_{std::move(query_id)} {
// nop
}
caf::expected<void> write(const vast::event& x) {
// TODO: publish to Broker endpoint.
std::cout << x.type().name() << std::endl;
return caf::no_error;
}
caf::expected<void> flush() {
return caf::no_error;
}
auto name() const {
return "bro-writer";
}
private:
broker::endpoint* endpoint_;
std::string query_id_;
};
// A custom command that allows us to re-use VAST command dispatching logic in
// order to issue a query that writes into a sink with a custom format.
class bro_command : public vast::system::writer_command_base {
public:
bro_command(broker::endpoint& endpoint)
: writer_command_base{nullptr, "bro"},
endpoint_{endpoint} {
// nop
}
// Sets the query ID to the UUID provided by Bro.
void query_id(std::string id) {
query_id_ = std::move(id);
}
protected:
caf::expected<caf::actor> make_sink(caf::scoped_actor& self,
const caf::config_value_map& options,
argument_iterator begin,
argument_iterator end) override {
VAST_UNUSED(options, begin, end);
bro_writer writer{endpoint_, query_id_};
return self->spawn(vast::system::sink<bro_writer>, std::move(writer),
vast::defaults::command::max_events);
}
private:
broker::endpoint& endpoint_;
std::string query_id_;
};
// Parses Broker data as Bro event.
caf::expected<std::pair<std::string, std::string>>
parse_query_event(const broker::data& x) {
std::pair<std::string, std::string> result;
auto event = broker::bro::Event(x);
if (event.name() != "VAST::query")
return make_error(vast::ec::parse_error, "invalid event name", event.name());
if (event.args().size() != 2)
return make_error(vast::ec::parse_error, "invalid number of arguments");
auto query_id = caf::get_if<std::string>(&event.args()[0]);
if (!query_id)
return make_error(vast::ec::parse_error, "invalid type of 1st argument");
result.first = *query_id;
if (!vast::parsers::uuid(*query_id))
return make_error(vast::ec::parse_error, "invalid query UUID", *query_id);
auto expression = caf::get_if<std::string>(&event.args()[1]);
if (!expression)
return make_error(vast::ec::parse_error, "invalid type of 2nd argument");
if (!vast::parsers::expr(*expression))
return make_error(vast::ec::parse_error, "invalid query expression",
*expression);
result.second = *expression;
return result;
}
} // namespace <anonymous>
int main(int argc, char** argv) {
// Parse the command line.
config cfg;
vast::detail::add_message_types(cfg);
cfg.parse(argc, argv);
std::string address = caf::get_or(cfg, "address", default_address);
uint16_t port = caf::get_or(cfg, "port", default_port);
// Create a Broker endpoint.
auto endpoint = broker::endpoint{std::move(cfg)};
endpoint.listen(address, port);
// Subscribe to the control channel.
auto subscriber = endpoint.make_subscriber({control_topic});
// Connect to VAST via a custom command.
bro_command cmd{endpoint};
auto& sys = endpoint.system();
caf::scoped_actor self{sys};
caf::config_value_map opts;
auto node = cmd.connect_to_node(self, opts);
if (!node) {
std::cerr << "failed to connect to VAST: " << sys.render(node.error())
<< std::endl;
return 1;
}
std::cerr << "connected to VAST successfully" << std::endl;
// Block until Bro peers with us.
auto receive_statuses = true;
auto status_subscriber = endpoint.make_status_subscriber(receive_statuses);
auto peered = false;
while (!peered) {
auto msg = status_subscriber.get();
caf::visit(vast::detail::overload(
[&](broker::none) {
// timeout
},
[&](broker::error error) {
std::cerr << sys.render(error) << std::endl;
},
[&](broker::status status) {
if (status == broker::sc::peer_added)
peered = true;
else
std::cerr << to_string(status) << std::endl;
}
), msg);
};
std::cerr << "peered with Bro successfully" << std::endl;
// Process queries from Bro.
auto done = false;
while (!done) {
std::cerr << "waiting for commands" << std::endl;
auto [topic, data] = subscriber.get();
// Parse the Bro query event.
auto result = parse_query_event(data);
if (!result) {
std::cerr << sys.render(result.error()) << std::endl;
return 1;
}
auto& [query_id, expression] = *result;
// Relay the query expression to VAST.
cmd.query_id(query_id);
auto args = std::vector<std::string>{expression};
auto rc = cmd.run(sys, args.begin(), args.end());
if (rc != 0) {
std::cerr << "failed to dispatch query to VAST" << std::endl;
return rc;
}
// A none value signals that the query has completed.
endpoint.publish(data_topic, make_bro_event(query_id, broker::nil));
}
}
<|endoftext|> |
<commit_before>/******************************************************************************
* _ _____ __________ *
* | | / / _ | / __/_ __/ Visibility *
* | |/ / __ |_\ \ / / Across *
* |___/_/ |_/___/ /_/ Space and Time *
* *
* This file is part of VAST. It is subject to the license terms in the *
* LICENSE file found in the top-level directory of this distribution and at *
* http://vast.io/license. No part of VAST, including this file, may be *
* copied, modified, propagated, or distributed except according to the terms *
* contained in the LICENSE file. *
******************************************************************************/
#include <atomic>
#include <csignal>
#include <cstdint>
#include <cstdlib>
#include <iostream>
#include <string>
#include <caf/config_option_adder.hpp>
#include <broker/bro.hh>
#include <broker/broker.hh>
#include <vast/data.hpp>
#include <vast/defaults.hpp>
#include <vast/error.hpp>
#include <vast/event.hpp>
#include <vast/expression.hpp>
#include <vast/uuid.hpp>
#include <vast/concept/parseable/parse.hpp>
#include <vast/concept/parseable/vast/expression.hpp>
#include <vast/concept/parseable/vast/uuid.hpp>
#include <vast/system/writer_command_base.hpp>
#include <vast/system/sink.hpp>
#include <vast/detail/add_error_categories.hpp>
#include <vast/detail/add_message_types.hpp>
#include <vast/detail/assert.hpp>
#include <vast/detail/overload.hpp>
using namespace std::chrono_literals;
namespace {
constexpr char control_topic[] = "/vast/control";
constexpr char data_topic[] = "/vast/data";
constexpr char default_address[] = "localhost";
constexpr uint16_t default_port = 43000;
// The timeout after which a blocking call to retrieve a message from a
// subscriber should return.
broker::duration get_timeout = broker::duration{500ms};
// Global flag that indicates that the application is shutting down due to a
// signal.
std::atomic<bool> terminating = false;
extern "C" void signal_handler(int sig) {
// Catch termination signals only once to allow forced termination by the OS
// upon sending the signal a second time.
if (sig == SIGINT || sig == SIGTERM)
std::signal(sig, SIG_DFL);
terminating = true;
}
// Our custom configuration with extra command line options for this tool.
class config : public broker::configuration {
public:
config() {
// As a stand-alone application, we reuse the global option group from CAF
// to avoid unnecessary prefixing.
opt_group{custom_options_, "global"}
.add<uint16_t>("port,p", "the port to listen at or connect to");
}
};
/// Converts VAST data to the corresponding Broker type.
broker::data to_broker(const vast::data& data) {
return caf::visit(vast::detail::overload(
[](const auto& x) -> broker::data {
return x;
},
[](caf::none_t) -> broker::data {
return {};
},
[](const vast::pattern& x) -> broker::data {
return x.string();
},
[](const vast::address& x) -> broker::data {
auto bytes = reinterpret_cast<const uint32_t*>(x.data().data());
return broker::address{bytes, broker::address::family::ipv6,
broker::address::byte_order::network};
},
[](const vast::subnet& x) -> broker::data {
auto bytes = reinterpret_cast<const uint32_t*>(x.network().data().data());
auto addr = broker::address{bytes, broker::address::family::ipv6,
broker::address::byte_order::network};
return broker::subnet(addr, x.length());
},
[](vast::port x) -> broker::data {
// We rely on the fact that port types don't change...ever.
auto protocol = static_cast<broker::port::protocol>(x.type());
return broker::port{x.number(), protocol};
},
[](vast::enumeration x) -> broker::data {
// FIXME: here we face two different implementation approaches for enums.
// To represent the actual enum value, Broker uses a string whereas VAST
// uses a 32-bit unsigned integer. We currently lose the type information
// by converting the VAST enum into a Broker count. A wholistic approach
// would include the type information for this data instance and perform
// the string conversion.
return broker::count{x};
},
[](const vast::vector& xs) -> broker::data {
broker::vector result;
result.reserve(xs.size());
std::transform(xs.begin(), xs.end(), std::back_inserter(result),
[](const auto& x) { return to_broker(x); });
return result;
},
[](const vast::set& xs) -> broker::data {
broker::set result;
std::transform(xs.begin(), xs.end(), std::inserter(result, result.end()),
[](const auto& x) { return to_broker(x); });
return result;
},
[](const vast::map& xs) -> broker::data {
broker::table result;
auto f = [](const auto& x) { return std::pair{to_broker(x.first),
to_broker(x.second)}; };
std::transform(xs.begin(), xs.end(), std::inserter(result, result.end()),
f);
return result;
}
), data);
}
// Constructs a result event for Bro from Broker data.
broker::bro::Event make_bro_event(std::string name, broker::data x) {
broker::vector args(2);
args[0] = std::move(name);
args[1] = std::move(x);
return {"VAST::result", std::move(args)};
}
// Constructs a result event for Bro from a VAST event.
broker::bro::Event make_bro_event(const vast::event& x) {
return make_bro_event(x.type().name(), to_broker(x.data()));
}
// A VAST writer that publishes the event it gets to a Bro endpoint.
class bro_writer {
public:
bro_writer() = default;
bro_writer(broker::endpoint& endpoint, std::string query_id)
: endpoint_{&endpoint},
query_id_{std::move(query_id)} {
// nop
}
caf::expected<void> write(const vast::event& x) {
std::cerr << '.';
endpoint_->publish(data_topic, make_bro_event(x));
return caf::no_error;
}
caf::expected<void> flush() {
return caf::no_error;
}
auto name() const {
return "bro-writer";
}
private:
broker::endpoint* endpoint_;
std::string query_id_;
};
// A custom command that allows us to re-use VAST command dispatching logic in
// order to issue a query that writes into a sink with a custom format.
class bro_command : public vast::system::writer_command_base {
public:
bro_command(broker::endpoint& endpoint)
: writer_command_base{nullptr, "bro"},
endpoint_{endpoint} {
// nop
}
// Sets the query ID to the UUID provided by Bro.
void query_id(std::string id) {
query_id_ = std::move(id);
}
/// Retrieves the current sink actor, which terminates when the exporter
/// corresponding to the issued query terminates.
caf::actor sink() const {
return sink_;
}
protected:
caf::expected<caf::actor> make_sink(caf::scoped_actor& self,
const caf::config_value_map& options,
argument_iterator begin,
argument_iterator end) override {
VAST_UNUSED(options, begin, end);
bro_writer writer{endpoint_, query_id_};
sink_ = self->spawn(vast::system::sink<bro_writer>, std::move(writer),
vast::defaults::command::max_events);
return sink_;
}
private:
broker::endpoint& endpoint_;
std::string query_id_;
caf::actor sink_;
};
// Parses Broker data as Bro event.
caf::expected<std::pair<std::string, std::string>>
parse_query_event(const broker::data& x) {
std::pair<std::string, std::string> result;
auto event = broker::bro::Event(x);
if (event.name() != "VAST::query")
return make_error(vast::ec::parse_error, "invalid event name", event.name());
if (event.args().size() != 2)
return make_error(vast::ec::parse_error, "invalid number of arguments");
auto query_id = caf::get_if<std::string>(&event.args()[0]);
if (!query_id)
return make_error(vast::ec::parse_error, "invalid type of 1st argument");
result.first = *query_id;
if (!vast::parsers::uuid(*query_id))
return make_error(vast::ec::parse_error, "invalid query UUID", *query_id);
auto expression = caf::get_if<std::string>(&event.args()[1]);
if (!expression)
return make_error(vast::ec::parse_error, "invalid type of 2nd argument");
if (!vast::parsers::expr(*expression))
return make_error(vast::ec::parse_error, "invalid query expression",
*expression);
result.second = *expression;
return result;
}
} // namespace <anonymous>
int main(int argc, char** argv) {
VAST_ASSERT(terminating.is_lock_free());
// Parse the command line.
config cfg;
vast::detail::add_message_types(cfg);
vast::detail::add_error_categories(cfg);
cfg.parse(argc, argv);
std::string address = caf::get_or(cfg, "address", default_address);
uint16_t port = caf::get_or(cfg, "port", default_port);
// Create a Broker endpoint.
auto endpoint = broker::endpoint{std::move(cfg)};
endpoint.listen(address, port);
// Subscribe to the control channel.
auto subscriber = endpoint.make_subscriber({control_topic});
// Connect to VAST via a custom command.
bro_command cmd{endpoint};
auto& sys = endpoint.system();
caf::scoped_actor self{sys};
caf::config_value_map opts;
auto node = cmd.connect_to_node(self, opts);
if (!node) {
std::cerr << "failed to connect to VAST: " << sys.render(node.error())
<< std::endl;
return 1;
}
std::cerr << "connected to VAST successfully" << std::endl;
// Block until Bro peers with us.
auto receive_statuses = true;
auto status_subscriber = endpoint.make_status_subscriber(receive_statuses);
auto peered = false;
while (!peered) {
auto msg = status_subscriber.get(get_timeout);
if (terminating)
return -1;
if (!msg)
continue; // timeout
caf::visit(vast::detail::overload(
[&](broker::none) {
// timeout
},
[&](broker::error error) {
std::cerr << sys.render(error) << std::endl;
},
[&](broker::status status) {
if (status == broker::sc::peer_added)
peered = true;
else
std::cerr << to_string(status) << std::endl;
}
), *msg);
};
std::cerr << "peered with Bro successfully" << std::endl;
// Process queries from Bro.
auto done = false;
while (!done) {
std::cerr << "waiting for commands" << std::endl;
auto msg = subscriber.get(get_timeout);
if (terminating)
return -1;
if (!msg)
continue; // timeout
auto& [topic, data] = *msg;
// Parse the Bro query event.
auto result = parse_query_event(data);
if (!result) {
std::cerr << sys.render(result.error()) << std::endl;
continue;
}
auto& [query_id, expression] = *result;
// Relay the query expression to VAST.
cmd.query_id(query_id);
auto args = std::vector<std::string>{expression};
std::cerr << "dispatching query to VAST: " << expression << std::endl;
auto rc = cmd.run(sys, args.begin(), args.end());
if (rc != 0) {
std::cerr << "failed to dispatch query to VAST" << std::endl;
return rc;
}
// Our Bro command contains a sink, which terminates automatically when the
// exporter for the corresponding query has finished. We use this signal to
// send the final terminator event to Bro.
self->monitor(cmd.sink());
self->receive(
[&, query_id=query_id](const caf::down_msg&) {
std::cerr << "\ncompleted processing of query results" << std::endl;
endpoint.publish(data_topic, make_bro_event(query_id, broker::nil));
}
);
}
}
<commit_msg>Give result event factory a clearer name<commit_after>/******************************************************************************
* _ _____ __________ *
* | | / / _ | / __/_ __/ Visibility *
* | |/ / __ |_\ \ / / Across *
* |___/_/ |_/___/ /_/ Space and Time *
* *
* This file is part of VAST. It is subject to the license terms in the *
* LICENSE file found in the top-level directory of this distribution and at *
* http://vast.io/license. No part of VAST, including this file, may be *
* copied, modified, propagated, or distributed except according to the terms *
* contained in the LICENSE file. *
******************************************************************************/
#include <atomic>
#include <csignal>
#include <cstdint>
#include <cstdlib>
#include <iostream>
#include <string>
#include <caf/config_option_adder.hpp>
#include <broker/bro.hh>
#include <broker/broker.hh>
#include <vast/data.hpp>
#include <vast/defaults.hpp>
#include <vast/error.hpp>
#include <vast/event.hpp>
#include <vast/expression.hpp>
#include <vast/uuid.hpp>
#include <vast/concept/parseable/parse.hpp>
#include <vast/concept/parseable/vast/expression.hpp>
#include <vast/concept/parseable/vast/uuid.hpp>
#include <vast/system/writer_command_base.hpp>
#include <vast/system/sink.hpp>
#include <vast/detail/add_error_categories.hpp>
#include <vast/detail/add_message_types.hpp>
#include <vast/detail/assert.hpp>
#include <vast/detail/overload.hpp>
using namespace std::chrono_literals;
namespace {
constexpr char control_topic[] = "/vast/control";
constexpr char data_topic[] = "/vast/data";
constexpr char default_address[] = "localhost";
constexpr uint16_t default_port = 43000;
// The timeout after which a blocking call to retrieve a message from a
// subscriber should return.
broker::duration get_timeout = broker::duration{500ms};
// Global flag that indicates that the application is shutting down due to a
// signal.
std::atomic<bool> terminating = false;
extern "C" void signal_handler(int sig) {
// Catch termination signals only once to allow forced termination by the OS
// upon sending the signal a second time.
if (sig == SIGINT || sig == SIGTERM)
std::signal(sig, SIG_DFL);
terminating = true;
}
// Our custom configuration with extra command line options for this tool.
class config : public broker::configuration {
public:
config() {
// As a stand-alone application, we reuse the global option group from CAF
// to avoid unnecessary prefixing.
opt_group{custom_options_, "global"}
.add<uint16_t>("port,p", "the port to listen at or connect to");
}
};
/// Converts VAST data to the corresponding Broker type.
broker::data to_broker(const vast::data& data) {
return caf::visit(vast::detail::overload(
[](const auto& x) -> broker::data {
return x;
},
[](caf::none_t) -> broker::data {
return {};
},
[](const vast::pattern& x) -> broker::data {
return x.string();
},
[](const vast::address& x) -> broker::data {
auto bytes = reinterpret_cast<const uint32_t*>(x.data().data());
return broker::address{bytes, broker::address::family::ipv6,
broker::address::byte_order::network};
},
[](const vast::subnet& x) -> broker::data {
auto bytes = reinterpret_cast<const uint32_t*>(x.network().data().data());
auto addr = broker::address{bytes, broker::address::family::ipv6,
broker::address::byte_order::network};
return broker::subnet(addr, x.length());
},
[](vast::port x) -> broker::data {
// We rely on the fact that port types don't change...ever.
auto protocol = static_cast<broker::port::protocol>(x.type());
return broker::port{x.number(), protocol};
},
[](vast::enumeration x) -> broker::data {
// FIXME: here we face two different implementation approaches for enums.
// To represent the actual enum value, Broker uses a string whereas VAST
// uses a 32-bit unsigned integer. We currently lose the type information
// by converting the VAST enum into a Broker count. A wholistic approach
// would include the type information for this data instance and perform
// the string conversion.
return broker::count{x};
},
[](const vast::vector& xs) -> broker::data {
broker::vector result;
result.reserve(xs.size());
std::transform(xs.begin(), xs.end(), std::back_inserter(result),
[](const auto& x) { return to_broker(x); });
return result;
},
[](const vast::set& xs) -> broker::data {
broker::set result;
std::transform(xs.begin(), xs.end(), std::inserter(result, result.end()),
[](const auto& x) { return to_broker(x); });
return result;
},
[](const vast::map& xs) -> broker::data {
broker::table result;
auto f = [](const auto& x) { return std::pair{to_broker(x.first),
to_broker(x.second)}; };
std::transform(xs.begin(), xs.end(), std::inserter(result, result.end()),
f);
return result;
}
), data);
}
// Constructs a result event for Bro from Broker data.
broker::bro::Event make_result_event(std::string name, broker::data x) {
broker::vector args(2);
args[0] = std::move(name);
args[1] = std::move(x);
return {"VAST::result", std::move(args)};
}
// Constructs a result event for Bro from a VAST event.
broker::bro::Event make_result_event(const vast::event& x) {
return make_result_event(x.type().name(), to_broker(x.data()));
}
// A VAST writer that publishes the event it gets to a Bro endpoint.
class bro_writer {
public:
bro_writer() = default;
bro_writer(broker::endpoint& endpoint, std::string query_id)
: endpoint_{&endpoint},
query_id_{std::move(query_id)} {
// nop
}
caf::expected<void> write(const vast::event& x) {
std::cerr << '.';
endpoint_->publish(data_topic, make_result_event(x));
return caf::no_error;
}
caf::expected<void> flush() {
return caf::no_error;
}
auto name() const {
return "bro-writer";
}
private:
broker::endpoint* endpoint_;
std::string query_id_;
};
// A custom command that allows us to re-use VAST command dispatching logic in
// order to issue a query that writes into a sink with a custom format.
class bro_command : public vast::system::writer_command_base {
public:
bro_command(broker::endpoint& endpoint)
: writer_command_base{nullptr, "bro"},
endpoint_{endpoint} {
// nop
}
// Sets the query ID to the UUID provided by Bro.
void query_id(std::string id) {
query_id_ = std::move(id);
}
/// Retrieves the current sink actor, which terminates when the exporter
/// corresponding to the issued query terminates.
caf::actor sink() const {
return sink_;
}
protected:
caf::expected<caf::actor> make_sink(caf::scoped_actor& self,
const caf::config_value_map& options,
argument_iterator begin,
argument_iterator end) override {
VAST_UNUSED(options, begin, end);
bro_writer writer{endpoint_, query_id_};
sink_ = self->spawn(vast::system::sink<bro_writer>, std::move(writer),
vast::defaults::command::max_events);
return sink_;
}
private:
broker::endpoint& endpoint_;
std::string query_id_;
caf::actor sink_;
};
// Parses Broker data as Bro event.
caf::expected<std::pair<std::string, std::string>>
parse_query_event(const broker::data& x) {
std::pair<std::string, std::string> result;
auto event = broker::bro::Event(x);
if (event.name() != "VAST::query")
return make_error(vast::ec::parse_error, "invalid event name", event.name());
if (event.args().size() != 2)
return make_error(vast::ec::parse_error, "invalid number of arguments");
auto query_id = caf::get_if<std::string>(&event.args()[0]);
if (!query_id)
return make_error(vast::ec::parse_error, "invalid type of 1st argument");
result.first = *query_id;
if (!vast::parsers::uuid(*query_id))
return make_error(vast::ec::parse_error, "invalid query UUID", *query_id);
auto expression = caf::get_if<std::string>(&event.args()[1]);
if (!expression)
return make_error(vast::ec::parse_error, "invalid type of 2nd argument");
if (!vast::parsers::expr(*expression))
return make_error(vast::ec::parse_error, "invalid query expression",
*expression);
result.second = *expression;
return result;
}
} // namespace <anonymous>
int main(int argc, char** argv) {
VAST_ASSERT(terminating.is_lock_free());
// Parse the command line.
config cfg;
vast::detail::add_message_types(cfg);
vast::detail::add_error_categories(cfg);
cfg.parse(argc, argv);
std::string address = caf::get_or(cfg, "address", default_address);
uint16_t port = caf::get_or(cfg, "port", default_port);
// Create a Broker endpoint.
auto endpoint = broker::endpoint{std::move(cfg)};
endpoint.listen(address, port);
// Subscribe to the control channel.
auto subscriber = endpoint.make_subscriber({control_topic});
// Connect to VAST via a custom command.
bro_command cmd{endpoint};
auto& sys = endpoint.system();
caf::scoped_actor self{sys};
caf::config_value_map opts;
auto node = cmd.connect_to_node(self, opts);
if (!node) {
std::cerr << "failed to connect to VAST: " << sys.render(node.error())
<< std::endl;
return 1;
}
std::cerr << "connected to VAST successfully" << std::endl;
// Block until Bro peers with us.
auto receive_statuses = true;
auto status_subscriber = endpoint.make_status_subscriber(receive_statuses);
auto peered = false;
while (!peered) {
auto msg = status_subscriber.get(get_timeout);
if (terminating)
return -1;
if (!msg)
continue; // timeout
caf::visit(vast::detail::overload(
[&](broker::none) {
// timeout
},
[&](broker::error error) {
std::cerr << sys.render(error) << std::endl;
},
[&](broker::status status) {
if (status == broker::sc::peer_added)
peered = true;
else
std::cerr << to_string(status) << std::endl;
}
), *msg);
};
std::cerr << "peered with Bro successfully" << std::endl;
// Process queries from Bro.
auto done = false;
while (!done) {
std::cerr << "waiting for commands" << std::endl;
auto msg = subscriber.get(get_timeout);
if (terminating)
return -1;
if (!msg)
continue; // timeout
auto& [topic, data] = *msg;
// Parse the Bro query event.
auto result = parse_query_event(data);
if (!result) {
std::cerr << sys.render(result.error()) << std::endl;
continue;
}
auto& [query_id, expression] = *result;
// Relay the query expression to VAST.
cmd.query_id(query_id);
auto args = std::vector<std::string>{expression};
std::cerr << "dispatching query to VAST: " << expression << std::endl;
auto rc = cmd.run(sys, args.begin(), args.end());
if (rc != 0) {
std::cerr << "failed to dispatch query to VAST" << std::endl;
return rc;
}
// Our Bro command contains a sink, which terminates automatically when the
// exporter for the corresponding query has finished. We use this signal to
// send the final terminator event to Bro.
self->monitor(cmd.sink());
self->receive(
[&, query_id=query_id](const caf::down_msg&) {
std::cerr << "\ncompleted processing of query results" << std::endl;
endpoint.publish(data_topic, make_result_event(query_id, broker::nil));
}
);
}
}
<|endoftext|> |
<commit_before>/******************************************************************************
* _ _____ __________ *
* | | / / _ | / __/_ __/ Visibility *
* | |/ / __ |_\ \ / / Across *
* |___/_/ |_/___/ /_/ Space and Time *
* *
* This file is part of VAST. It is subject to the license terms in the *
* LICENSE file found in the top-level directory of this distribution and at *
* http://vast.io/license. No part of VAST, including this file, may be *
* copied, modified, propagated, or distributed except according to the terms *
* contained in the LICENSE file. *
******************************************************************************/
#include <cstdint>
#include <iostream>
#include <string>
#include <caf/config_option_adder.hpp>
#include <broker/bro.hh>
#include <broker/broker.hh>
#include <vast/data.hpp>
#include <vast/defaults.hpp>
#include <vast/error.hpp>
#include <vast/event.hpp>
#include <vast/expression.hpp>
#include <vast/uuid.hpp>
#include <vast/concept/parseable/parse.hpp>
#include <vast/concept/parseable/vast/expression.hpp>
#include <vast/concept/parseable/vast/uuid.hpp>
#include <vast/system/writer_command_base.hpp>
#include <vast/system/sink.hpp>
#include <vast/detail/add_error_categories.hpp>
#include <vast/detail/add_message_types.hpp>
#include <vast/detail/assert.hpp>
#include <vast/detail/overload.hpp>
namespace {
constexpr char control_topic[] = "/vast/control";
constexpr char data_topic[] = "/vast/data";
constexpr char default_address[] = "localhost";
constexpr uint16_t default_port = 43000;
// Our custom configuration with extra command line options for this tool.
class config : public broker::configuration {
public:
config() {
// As a stand-alone application, we reuse the global option group from CAF
// to avoid unnecessary prefixing.
opt_group{custom_options_, "global"}
.add<uint16_t>("port,p", "the port to listen at or connect to");
}
};
/// Converts VAST data to the corresponding Broker type.
broker::data to_broker(const vast::data& data) {
return caf::visit(vast::detail::overload(
[](const auto& x) -> broker::data {
return x;
},
[](caf::none_t) -> broker::data {
return {};
},
[](const vast::pattern& x) -> broker::data {
return x.string();
},
[](const vast::address& x) -> broker::data {
auto bytes = reinterpret_cast<const uint32_t*>(x.data().data());
return broker::address{bytes, broker::address::family::ipv6,
broker::address::byte_order::network};
},
[](const vast::subnet& x) -> broker::data {
auto bytes = reinterpret_cast<const uint32_t*>(x.network().data().data());
auto addr = broker::address{bytes, broker::address::family::ipv6,
broker::address::byte_order::network};
return broker::subnet(addr, x.length());
},
[](vast::port x) -> broker::data {
// We rely on the fact that port types don't change...ever.
auto protocol = static_cast<broker::port::protocol>(x.type());
return broker::port{x.number(), protocol};
},
[](vast::enumeration x) -> broker::data {
// FIXME: here we face two different implementation approaches for enums.
// To represent the actual enum value, Broker uses a string whereas VAST
// uses a 32-bit unsigned integer. We currently lose the type information
// by converting the VAST enum into a Broker count. A wholistic approach
// would include the type information for this data instance and perform
// the string conversion.
return broker::count{x};
},
[](const vast::vector& xs) -> broker::data {
broker::vector result;
result.reserve(xs.size());
std::transform(xs.begin(), xs.end(), std::back_inserter(result),
[](const auto& x) { return to_broker(x); });
return result;
},
[](const vast::set& xs) -> broker::data {
broker::set result;
std::transform(xs.begin(), xs.end(), std::inserter(result, result.end()),
[](const auto& x) { return to_broker(x); });
return result;
},
[](const vast::map& xs) -> broker::data {
broker::table result;
auto f = [](const auto& x) { return std::pair{to_broker(x.first),
to_broker(x.second)}; };
std::transform(xs.begin(), xs.end(), std::inserter(result, result.end()),
f);
return result;
}
), data);
}
// Constructs a result event for Bro from Broker data.
broker::bro::Event make_bro_event(std::string name, broker::data x) {
broker::vector args(2);
args[0] = std::move(name);
args[1] = std::move(x);
return {"VAST::result", std::move(args)};
}
// Constructs a result event for Bro from a VAST event.
broker::bro::Event make_bro_event(const vast::event& x) {
return make_bro_event(x.type().name(), to_broker(x.data()));
}
// A VAST writer that publishes the event it gets to a Bro endpoint.
class bro_writer {
public:
bro_writer() = default;
bro_writer(broker::endpoint& endpoint, std::string query_id)
: endpoint_{&endpoint},
query_id_{std::move(query_id)} {
// nop
}
caf::expected<void> write(const vast::event& x) {
std::cerr << '.';
endpoint_->publish(data_topic, make_bro_event(x));
return caf::no_error;
}
caf::expected<void> flush() {
return caf::no_error;
}
auto name() const {
return "bro-writer";
}
private:
broker::endpoint* endpoint_;
std::string query_id_;
};
// A custom command that allows us to re-use VAST command dispatching logic in
// order to issue a query that writes into a sink with a custom format.
class bro_command : public vast::system::writer_command_base {
public:
bro_command(broker::endpoint& endpoint)
: writer_command_base{nullptr, "bro"},
endpoint_{endpoint} {
// nop
}
// Sets the query ID to the UUID provided by Bro.
void query_id(std::string id) {
query_id_ = std::move(id);
}
/// Retrieves the current sink actor, which terminates when the exporter
/// corresponding to the issued query terminates.
caf::actor sink() const {
return sink_;
}
protected:
caf::expected<caf::actor> make_sink(caf::scoped_actor& self,
const caf::config_value_map& options,
argument_iterator begin,
argument_iterator end) override {
VAST_UNUSED(options, begin, end);
bro_writer writer{endpoint_, query_id_};
sink_ = self->spawn(vast::system::sink<bro_writer>, std::move(writer),
vast::defaults::command::max_events);
return sink_;
}
private:
broker::endpoint& endpoint_;
std::string query_id_;
caf::actor sink_;
};
// Parses Broker data as Bro event.
caf::expected<std::pair<std::string, std::string>>
parse_query_event(const broker::data& x) {
std::pair<std::string, std::string> result;
auto event = broker::bro::Event(x);
if (event.name() != "VAST::query")
return make_error(vast::ec::parse_error, "invalid event name", event.name());
if (event.args().size() != 2)
return make_error(vast::ec::parse_error, "invalid number of arguments");
auto query_id = caf::get_if<std::string>(&event.args()[0]);
if (!query_id)
return make_error(vast::ec::parse_error, "invalid type of 1st argument");
result.first = *query_id;
if (!vast::parsers::uuid(*query_id))
return make_error(vast::ec::parse_error, "invalid query UUID", *query_id);
auto expression = caf::get_if<std::string>(&event.args()[1]);
if (!expression)
return make_error(vast::ec::parse_error, "invalid type of 2nd argument");
if (!vast::parsers::expr(*expression))
return make_error(vast::ec::parse_error, "invalid query expression",
*expression);
result.second = *expression;
return result;
}
} // namespace <anonymous>
int main(int argc, char** argv) {
// Parse the command line.
config cfg;
vast::detail::add_message_types(cfg);
vast::detail::add_error_categories(cfg);
cfg.parse(argc, argv);
std::string address = caf::get_or(cfg, "address", default_address);
uint16_t port = caf::get_or(cfg, "port", default_port);
// Create a Broker endpoint.
auto endpoint = broker::endpoint{std::move(cfg)};
endpoint.listen(address, port);
// Subscribe to the control channel.
auto subscriber = endpoint.make_subscriber({control_topic});
// Connect to VAST via a custom command.
bro_command cmd{endpoint};
auto& sys = endpoint.system();
caf::scoped_actor self{sys};
caf::config_value_map opts;
auto node = cmd.connect_to_node(self, opts);
if (!node) {
std::cerr << "failed to connect to VAST: " << sys.render(node.error())
<< std::endl;
return 1;
}
std::cerr << "connected to VAST successfully" << std::endl;
// Block until Bro peers with us.
auto receive_statuses = true;
auto status_subscriber = endpoint.make_status_subscriber(receive_statuses);
auto peered = false;
while (!peered) {
auto msg = status_subscriber.get();
caf::visit(vast::detail::overload(
[&](broker::none) {
// timeout
},
[&](broker::error error) {
std::cerr << sys.render(error) << std::endl;
},
[&](broker::status status) {
if (status == broker::sc::peer_added)
peered = true;
else
std::cerr << to_string(status) << std::endl;
}
), msg);
};
std::cerr << "peered with Bro successfully" << std::endl;
// Process queries from Bro.
auto done = false;
while (!done) {
std::cerr << "waiting for commands" << std::endl;
auto [topic, data] = subscriber.get();
// Parse the Bro query event.
auto result = parse_query_event(data);
if (!result) {
std::cerr << sys.render(result.error()) << std::endl;
continue;
}
auto& [query_id, expression] = *result;
// Relay the query expression to VAST.
cmd.query_id(query_id);
auto args = std::vector<std::string>{expression};
std::cerr << "dispatching query to VAST: " << expression << std::endl;
auto rc = cmd.run(sys, args.begin(), args.end());
if (rc != 0) {
std::cerr << "failed to dispatch query to VAST" << std::endl;
return rc;
}
// Our Bro command contains a sink, which terminates automatically when the
// exporter for the corresponding query has finished. We use this signal to
// send the final terminator event to Bro.
self->monitor(cmd.sink());
self->receive(
[&, query_id=query_id](const caf::down_msg&) {
std::cerr << "\ncompleted processing of query results" << std::endl;
endpoint.publish(data_topic, make_bro_event(query_id, broker::nil));
}
);
}
}
<commit_msg>Handle SIGINT and SIGTERM more graceful<commit_after>/******************************************************************************
* _ _____ __________ *
* | | / / _ | / __/_ __/ Visibility *
* | |/ / __ |_\ \ / / Across *
* |___/_/ |_/___/ /_/ Space and Time *
* *
* This file is part of VAST. It is subject to the license terms in the *
* LICENSE file found in the top-level directory of this distribution and at *
* http://vast.io/license. No part of VAST, including this file, may be *
* copied, modified, propagated, or distributed except according to the terms *
* contained in the LICENSE file. *
******************************************************************************/
#include <atomic>
#include <csignal>
#include <cstdint>
#include <cstdlib>
#include <iostream>
#include <string>
#include <caf/config_option_adder.hpp>
#include <broker/bro.hh>
#include <broker/broker.hh>
#include <vast/data.hpp>
#include <vast/defaults.hpp>
#include <vast/error.hpp>
#include <vast/event.hpp>
#include <vast/expression.hpp>
#include <vast/uuid.hpp>
#include <vast/concept/parseable/parse.hpp>
#include <vast/concept/parseable/vast/expression.hpp>
#include <vast/concept/parseable/vast/uuid.hpp>
#include <vast/system/writer_command_base.hpp>
#include <vast/system/sink.hpp>
#include <vast/detail/add_error_categories.hpp>
#include <vast/detail/add_message_types.hpp>
#include <vast/detail/assert.hpp>
#include <vast/detail/overload.hpp>
using namespace std::chrono_literals;
namespace {
constexpr char control_topic[] = "/vast/control";
constexpr char data_topic[] = "/vast/data";
constexpr char default_address[] = "localhost";
constexpr uint16_t default_port = 43000;
// The timeout after which a blocking call to retrieve a message from a
// subscriber should return.
broker::duration get_timeout = broker::duration{500ms};
// Global flag that indicates that the application is shutting down due to a
// signal.
std::atomic<bool> terminating = false;
extern "C" void signal_handler(int sig) {
// Catch termination signals only once to allow forced termination by the OS
// upon sending the signal a second time.
if (sig == SIGINT || sig == SIGTERM)
std::signal(sig, SIG_DFL);
terminating = true;
}
// Our custom configuration with extra command line options for this tool.
class config : public broker::configuration {
public:
config() {
// As a stand-alone application, we reuse the global option group from CAF
// to avoid unnecessary prefixing.
opt_group{custom_options_, "global"}
.add<uint16_t>("port,p", "the port to listen at or connect to");
}
};
/// Converts VAST data to the corresponding Broker type.
broker::data to_broker(const vast::data& data) {
return caf::visit(vast::detail::overload(
[](const auto& x) -> broker::data {
return x;
},
[](caf::none_t) -> broker::data {
return {};
},
[](const vast::pattern& x) -> broker::data {
return x.string();
},
[](const vast::address& x) -> broker::data {
auto bytes = reinterpret_cast<const uint32_t*>(x.data().data());
return broker::address{bytes, broker::address::family::ipv6,
broker::address::byte_order::network};
},
[](const vast::subnet& x) -> broker::data {
auto bytes = reinterpret_cast<const uint32_t*>(x.network().data().data());
auto addr = broker::address{bytes, broker::address::family::ipv6,
broker::address::byte_order::network};
return broker::subnet(addr, x.length());
},
[](vast::port x) -> broker::data {
// We rely on the fact that port types don't change...ever.
auto protocol = static_cast<broker::port::protocol>(x.type());
return broker::port{x.number(), protocol};
},
[](vast::enumeration x) -> broker::data {
// FIXME: here we face two different implementation approaches for enums.
// To represent the actual enum value, Broker uses a string whereas VAST
// uses a 32-bit unsigned integer. We currently lose the type information
// by converting the VAST enum into a Broker count. A wholistic approach
// would include the type information for this data instance and perform
// the string conversion.
return broker::count{x};
},
[](const vast::vector& xs) -> broker::data {
broker::vector result;
result.reserve(xs.size());
std::transform(xs.begin(), xs.end(), std::back_inserter(result),
[](const auto& x) { return to_broker(x); });
return result;
},
[](const vast::set& xs) -> broker::data {
broker::set result;
std::transform(xs.begin(), xs.end(), std::inserter(result, result.end()),
[](const auto& x) { return to_broker(x); });
return result;
},
[](const vast::map& xs) -> broker::data {
broker::table result;
auto f = [](const auto& x) { return std::pair{to_broker(x.first),
to_broker(x.second)}; };
std::transform(xs.begin(), xs.end(), std::inserter(result, result.end()),
f);
return result;
}
), data);
}
// Constructs a result event for Bro from Broker data.
broker::bro::Event make_bro_event(std::string name, broker::data x) {
broker::vector args(2);
args[0] = std::move(name);
args[1] = std::move(x);
return {"VAST::result", std::move(args)};
}
// Constructs a result event for Bro from a VAST event.
broker::bro::Event make_bro_event(const vast::event& x) {
return make_bro_event(x.type().name(), to_broker(x.data()));
}
// A VAST writer that publishes the event it gets to a Bro endpoint.
class bro_writer {
public:
bro_writer() = default;
bro_writer(broker::endpoint& endpoint, std::string query_id)
: endpoint_{&endpoint},
query_id_{std::move(query_id)} {
// nop
}
caf::expected<void> write(const vast::event& x) {
std::cerr << '.';
endpoint_->publish(data_topic, make_bro_event(x));
return caf::no_error;
}
caf::expected<void> flush() {
return caf::no_error;
}
auto name() const {
return "bro-writer";
}
private:
broker::endpoint* endpoint_;
std::string query_id_;
};
// A custom command that allows us to re-use VAST command dispatching logic in
// order to issue a query that writes into a sink with a custom format.
class bro_command : public vast::system::writer_command_base {
public:
bro_command(broker::endpoint& endpoint)
: writer_command_base{nullptr, "bro"},
endpoint_{endpoint} {
// nop
}
// Sets the query ID to the UUID provided by Bro.
void query_id(std::string id) {
query_id_ = std::move(id);
}
/// Retrieves the current sink actor, which terminates when the exporter
/// corresponding to the issued query terminates.
caf::actor sink() const {
return sink_;
}
protected:
caf::expected<caf::actor> make_sink(caf::scoped_actor& self,
const caf::config_value_map& options,
argument_iterator begin,
argument_iterator end) override {
VAST_UNUSED(options, begin, end);
bro_writer writer{endpoint_, query_id_};
sink_ = self->spawn(vast::system::sink<bro_writer>, std::move(writer),
vast::defaults::command::max_events);
return sink_;
}
private:
broker::endpoint& endpoint_;
std::string query_id_;
caf::actor sink_;
};
// Parses Broker data as Bro event.
caf::expected<std::pair<std::string, std::string>>
parse_query_event(const broker::data& x) {
std::pair<std::string, std::string> result;
auto event = broker::bro::Event(x);
if (event.name() != "VAST::query")
return make_error(vast::ec::parse_error, "invalid event name", event.name());
if (event.args().size() != 2)
return make_error(vast::ec::parse_error, "invalid number of arguments");
auto query_id = caf::get_if<std::string>(&event.args()[0]);
if (!query_id)
return make_error(vast::ec::parse_error, "invalid type of 1st argument");
result.first = *query_id;
if (!vast::parsers::uuid(*query_id))
return make_error(vast::ec::parse_error, "invalid query UUID", *query_id);
auto expression = caf::get_if<std::string>(&event.args()[1]);
if (!expression)
return make_error(vast::ec::parse_error, "invalid type of 2nd argument");
if (!vast::parsers::expr(*expression))
return make_error(vast::ec::parse_error, "invalid query expression",
*expression);
result.second = *expression;
return result;
}
} // namespace <anonymous>
int main(int argc, char** argv) {
VAST_ASSERT(terminating.is_lock_free());
// Parse the command line.
config cfg;
vast::detail::add_message_types(cfg);
vast::detail::add_error_categories(cfg);
cfg.parse(argc, argv);
std::string address = caf::get_or(cfg, "address", default_address);
uint16_t port = caf::get_or(cfg, "port", default_port);
// Create a Broker endpoint.
auto endpoint = broker::endpoint{std::move(cfg)};
endpoint.listen(address, port);
// Subscribe to the control channel.
auto subscriber = endpoint.make_subscriber({control_topic});
// Connect to VAST via a custom command.
bro_command cmd{endpoint};
auto& sys = endpoint.system();
caf::scoped_actor self{sys};
caf::config_value_map opts;
auto node = cmd.connect_to_node(self, opts);
if (!node) {
std::cerr << "failed to connect to VAST: " << sys.render(node.error())
<< std::endl;
return 1;
}
std::cerr << "connected to VAST successfully" << std::endl;
// Block until Bro peers with us.
auto receive_statuses = true;
auto status_subscriber = endpoint.make_status_subscriber(receive_statuses);
auto peered = false;
while (!peered) {
auto msg = status_subscriber.get(get_timeout);
if (terminating)
return -1;
if (!msg)
continue; // timeout
caf::visit(vast::detail::overload(
[&](broker::none) {
// timeout
},
[&](broker::error error) {
std::cerr << sys.render(error) << std::endl;
},
[&](broker::status status) {
if (status == broker::sc::peer_added)
peered = true;
else
std::cerr << to_string(status) << std::endl;
}
), *msg);
};
std::cerr << "peered with Bro successfully" << std::endl;
// Process queries from Bro.
auto done = false;
while (!done) {
std::cerr << "waiting for commands" << std::endl;
auto msg = subscriber.get(get_timeout);
if (terminating)
return -1;
if (!msg)
continue; // timeout
auto& [topic, data] = *msg;
// Parse the Bro query event.
auto result = parse_query_event(data);
if (!result) {
std::cerr << sys.render(result.error()) << std::endl;
continue;
}
auto& [query_id, expression] = *result;
// Relay the query expression to VAST.
cmd.query_id(query_id);
auto args = std::vector<std::string>{expression};
std::cerr << "dispatching query to VAST: " << expression << std::endl;
auto rc = cmd.run(sys, args.begin(), args.end());
if (rc != 0) {
std::cerr << "failed to dispatch query to VAST" << std::endl;
return rc;
}
// Our Bro command contains a sink, which terminates automatically when the
// exporter for the corresponding query has finished. We use this signal to
// send the final terminator event to Bro.
self->monitor(cmd.sink());
self->receive(
[&, query_id=query_id](const caf::down_msg&) {
std::cerr << "\ncompleted processing of query results" << std::endl;
endpoint.publish(data_topic, make_bro_event(query_id, broker::nil));
}
);
}
}
<|endoftext|> |
<commit_before>#include <stdio.h>
#include <stdlib.h>
#include <mpi.h>
// neighbours convention
#define UP 0
#define DOWN 1
#define LEFT 2
#define RIGHT 3
// hallo radius
#define R 1 // for the time been this is a fixed param.
// domain decompostion
#define Sx 1 // size in x
#define Sy 4 // size in y
// root processor
#define ROOT 0
void print(int *data, int nx, int ny) {
printf("-- output --\n");
for (int i=0; i<ny; i++) {
for (int j=0; j<nx; j++) {
printf("%3d ", data[i*nx+j]);
}
printf("\n");
}
}
int main(int argc, char **argv) {
int rank, size;
MPI_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &size);
// if number of np != Sx*Sy then terminate.
if (size != Sx*Sy){
if (rank==ROOT)
fprintf(stderr,"%s: Needs at least %d processors.\n", argv[0], Sx*Sy);
MPI_Finalize();
return 1;
}
// Testing :
// A 1x4 grid of subgrid
/*
+-----+-----+-----+-----+
| 0 | 1 | 2 | 3 |
|(0,0)|(0,1)|(0,2)|(0,3)|
+-----+-----+-----+-----+
*/
// A 1x4 grid of subgrid
/*
+-----+
| 0 |
|(0,0)|
+-----+
| 1 |
|(1,0)|
+-----+
| 2 |
|(2,0)|
+-----+
| 3 |
|(3,0)|
+-----+
*/
// A 2x2 grid of subgrid
/*
+-----+-----+
| 0 | 1 |
|(0,0)|(0,1)|
+-----+-----+
| 3 | 4 |
|(1,0)|(1,1)|
+-----+-----+
*/
MPI_Comm Comm2d;
int ndim = 2;
int dim[2] = {Sy,Sx};
int period[2] = {false,false}; // for periodic boundary conditions
int reorder = {true};
// Setup and build cartesian grid
MPI_Cart_create(MPI_COMM_WORLD,ndim,dim,period,reorder,&Comm2d);
MPI_Comm_rank(Comm2d, &rank);
// Every processor prints it rank and coordinates
int coord[2];
MPI_Cart_coords(Comm2d,rank,2,coord);
printf("P:%2d My coordinates are %d %d\n",rank,coord[0],coord[1]);
MPI_Barrier(Comm2d);
// Every processor build his neighbour map
int nbrs[4];
MPI_Cart_shift(Comm2d,0,1,&nbrs[DOWN],&nbrs[UP]);
MPI_Cart_shift(Comm2d,1,1,&nbrs[LEFT],&nbrs[RIGHT]);
MPI_Barrier(Comm2d);
// prints its neighbours
if (rank==3) {
printf("P:%2d has neighbours (u,d,l,r): %2d %2d %2d %2d\n",
rank,nbrs[UP],nbrs[DOWN],nbrs[LEFT],nbrs[RIGHT]);
}
/* array sizes */
const int NX =20;
const int NY =20;
const int nx =NX/Sx;
const int ny =NY/Sy;
// subsizes verification
// build a MPI data type for a subarray in Root processor
MPI_Datatype global, myGlobal;
int bigsizes[2] = {NY,NX};
int subsizes[2] = {ny,nx};
int starts[2] = {0,0};
MPI_Type_create_subarray(2, bigsizes, subsizes, starts, MPI_ORDER_C, MPI_INT, &global);
MPI_Type_create_resized(global, 0, nx*sizeof(int), &myGlobal); // resize extend
MPI_Type_commit(&myGlobal);
// build a MPI data type for a subarray in workers
MPI_Datatype myLocal;
int bigsizes2[2] = {R+ny+R,R+nx+R};
int subsizes2[2] = {ny,nx};
int starts2[2] = {R,R};
MPI_Type_create_subarray(2, bigsizes2, subsizes2, starts2, MPI_ORDER_C, MPI_INT, &myLocal);
MPI_Type_commit(&myLocal); // now we can use this MPI costum data type
// halo data types
MPI_Datatype xSlice, ySlice;
MPI_Type_vector(nx, 1, 1 , MPI_INT, &xSlice);
MPI_Type_vector(ny, 1, nx+2*R, MPI_INT, &ySlice);
MPI_Type_commit(&xSlice);
MPI_Type_commit(&ySlice);
// Allocate 2d big-array in root processor
int i, j;
int *bigarray; // to be allocated only in root
if (rank==ROOT) {
bigarray = (int*)malloc(NX*NY*sizeof(int));
for (i=0; i<NY; i++) {
for (j=0; j<NX; j++) {
bigarray[i*NX+j] = i*NX+j;
}
}
// print the big array
print(bigarray, NX, NY);
}
// Allocte sub-array in every np
int *subarray;
subarray = (int*)malloc((R+nx+R)*(R+ny+R)*sizeof(int));
for (i=0; i<ny+2*R; i++) {
for (j=0; j<nx+2*R; j++) {
subarray[i*(nx+2*R)+j] = 0;
}
}
// build sendcounts and displacements in root processor
int sendcounts[size];
int displs[size];
if (rank==ROOT) {
for (i=0; i<size; i++) sendcounts[i]=1;
int disp = 0; // displacement counter
for (i=0; i<Sy; i++) {
for (j=0; j<Sx; j++) {
displs[i*Sx+j]=disp; disp+=1; // x-displacements
}
disp += Sx*(ny-1); // y-displacements
}
printf("\n");
for (i=0; i<size; i++) printf("%d ",displs[i]);
printf("end \n");
}
// scatter pieces of the big data array
MPI_Scatterv(bigarray, sendcounts, displs, myGlobal,
subarray, 1, myLocal, ROOT, Comm2d);
// Exchange x - slices with top and bottom neighbors
MPI_Sendrecv(&(subarray[ ny *(nx+2*R)+1]), 1, xSlice, nbrs[UP] , 1,
&(subarray[ 0 *(nx+2*R)+1]), 1, xSlice, nbrs[DOWN], 1,
Comm2d, MPI_STATUS_IGNORE);
MPI_Sendrecv(&(subarray[ 1 *(nx+2*R)+1]), 1, xSlice, nbrs[DOWN], 2,
&(subarray[(ny+1)*(nx+2*R)+1]), 1, xSlice, nbrs[UP] , 2,
Comm2d, MPI_STATUS_IGNORE);
// Exchange y - slices with left and right neighbors
MPI_Sendrecv(&(subarray[1*(nx+2*R)+ nx ]), 1, ySlice, nbrs[RIGHT],3,
&(subarray[1*(nx+2*R)+ 0 ]), 1, ySlice, nbrs[LEFT] ,3,
Comm2d, MPI_STATUS_IGNORE);
MPI_Sendrecv(&(subarray[1*(nx+2*R)+ 1 ]), 1, ySlice, nbrs[LEFT] ,4,
&(subarray[1*(nx+2*R)+(nx+1)]), 1, ySlice, nbrs[RIGHT],4,
Comm2d, MPI_STATUS_IGNORE);
// selected reciver processor prints the subarray
if (rank==3) print(subarray, nx+2*R, ny+2*R);
MPI_Barrier(Comm2d);
// gather all pieces into the big data array
MPI_Gatherv(subarray, 1, myLocal,
bigarray, sendcounts, displs, myGlobal, ROOT, Comm2d);
// print the bigarray and free array in root
if (rank==ROOT) print(bigarray, NX, NY);
// MPI types
MPI_Type_free(&xSlice);
MPI_Type_free(&ySlice);
MPI_Type_free(&myLocal);
MPI_Type_free(&myGlobal);
// free arrays in workers
if (rank==ROOT) free(bigarray);
free(subarray);
// finalize MPI
MPI_Finalize();
return 0;
}
<commit_msg>Perfect!<commit_after>#include <stdio.h>
#include <stdlib.h>
#include <mpi.h>
// neighbours convention
#define UP 0
#define DOWN 1
#define LEFT 2
#define RIGHT 3
// hallo radius
#define R 1 // for the time been this is a fixed param.
// domain decompostion
#define Sx 2 // size in x
#define Sy 2 // size in y
// root processor
#define ROOT 0
void print(int *data, int nx, int ny) {
printf("-- Global Memory --\n");
for (int i=0; i<ny; i++) {
for (int j=0; j<nx; j++) {
printf("%3d ", data[i*nx+j]);
}
printf("\n");
}
}
int main(int argc, char **argv) {
int rank, size;
MPI_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &size);
// if number of np != Sx*Sy then terminate.
if (size != Sx*Sy){
if (rank==ROOT)
fprintf(stderr,"%s: Needs at least %d processors.\n", argv[0], Sx*Sy);
MPI_Finalize();
return 1;
}
// Testing :
// A 1x4 grid of subgrid
/*
+-----+-----+-----+-----+
| 0 | 1 | 2 | 3 |
|(0,0)|(0,1)|(0,2)|(0,3)|
+-----+-----+-----+-----+
*/
// A 1x4 grid of subgrid
/*
+-----+
| 0 |
|(0,0)|
+-----+
| 1 |
|(1,0)|
+-----+
| 2 |
|(2,0)|
+-----+
| 3 |
|(3,0)|
+-----+
*/
// A 2x2 grid of subgrid
/*
+-----+-----+
| 0 | 1 |
|(0,0)|(0,1)|
+-----+-----+
| 3 | 4 |
|(1,0)|(1,1)|
+-----+-----+
*/
MPI_Comm Comm2d;
int ndim = 2;
int dim[2] = {Sy,Sx};
int period[2] = {false,false}; // for periodic boundary conditions
int reorder = {true};
// Setup and build cartesian grid
MPI_Cart_create(MPI_COMM_WORLD,ndim,dim,period,reorder,&Comm2d);
MPI_Comm_rank(Comm2d, &rank);
// Every processor prints it rank and coordinates
int coord[2];
MPI_Cart_coords(Comm2d,rank,2,coord);
printf("P:%2d My coordinates are %d %d\n",rank,coord[0],coord[1]);
MPI_Barrier(Comm2d);
// Every processor build his neighbour map
int nbrs[4];
MPI_Cart_shift(Comm2d,0,1,&nbrs[DOWN],&nbrs[UP]);
MPI_Cart_shift(Comm2d,1,1,&nbrs[LEFT],&nbrs[RIGHT]);
MPI_Barrier(Comm2d);
// prints its neighbours
printf("P:%2d has neighbours (u,d,l,r): %2d %2d %2d %2d\n",
rank,nbrs[UP],nbrs[DOWN],nbrs[LEFT],nbrs[RIGHT]);
/* array sizes */
const int NX =8;
const int NY =8;
const int nx =NX/Sx;
const int ny =NY/Sy;
// subsizes verification
if (NX%Sx!=0 || NY%Sy!=0) {
if (rank==ROOT)
fprintf(stderr,"%s: Subdomain sizes not an integer value.\n", argv[0]);
MPI_Finalize();
return 1;
}
// build a MPI data type for a subarray in Root processor
MPI_Datatype global, myGlobal;
int bigsizes[2] = {NY,NX};
int subsizes[2] = {ny,nx};
int starts[2] = {0,0};
MPI_Type_create_subarray(2, bigsizes, subsizes, starts, MPI_ORDER_C, MPI_INT, &global);
MPI_Type_create_resized(global, 0, nx*sizeof(int), &myGlobal); // resize extend
MPI_Type_commit(&myGlobal);
// build a MPI data type for a subarray in workers
MPI_Datatype myLocal;
int bigsizes2[2] = {R+ny+R,R+nx+R};
int subsizes2[2] = {ny,nx};
int starts2[2] = {R,R};
MPI_Type_create_subarray(2, bigsizes2, subsizes2, starts2, MPI_ORDER_C, MPI_INT, &myLocal);
MPI_Type_commit(&myLocal); // now we can use this MPI costum data type
// halo data types
MPI_Datatype xSlice, ySlice;
MPI_Type_vector(nx, 1, 1 , MPI_INT, &xSlice);
MPI_Type_vector(ny, 1, nx+2*R, MPI_INT, &ySlice);
MPI_Type_commit(&xSlice);
MPI_Type_commit(&ySlice);
// Allocate 2d big-array in root processor
int i, j;
int *bigarray; // to be allocated only in root
if (rank==ROOT) {
bigarray = (int*)malloc(NX*NY*sizeof(int));
for (i=0; i<NY; i++) {
for (j=0; j<NX; j++) {
bigarray[i*NX+j] = i*NX+j;
}
}
// print the big array
print(bigarray, NX, NY);
}
// Allocte sub-array in every np
int *subarray;
subarray = (int*)malloc((R+nx+R)*(R+ny+R)*sizeof(int));
for (i=0; i<ny+2*R; i++) {
for (j=0; j<nx+2*R; j++) {
subarray[i*(nx+2*R)+j] = 0;
}
}
// build sendcounts and displacements in root processor
int sendcounts[size];
int displs[size];
if (rank==ROOT) {
for (i=0; i<size; i++) sendcounts[i]=1;
int disp = 0; // displacement counter
for (i=0; i<Sy; i++) {
for (j=0; j<Sx; j++) {
displs[i*Sx+j]=disp; disp+=1; // x-displacements
}
disp += Sx*(ny-1); // y-displacements
}
}
// scatter pieces of the big data array
MPI_Scatterv(bigarray, sendcounts, displs, myGlobal,
subarray, 1, myLocal, ROOT, Comm2d);
// Exchange x - slices with top and bottom neighbors
MPI_Sendrecv(&(subarray[ ny *(nx+2*R)+1]), 1, xSlice, nbrs[UP] , 1,
&(subarray[ 0 *(nx+2*R)+1]), 1, xSlice, nbrs[DOWN], 1,
Comm2d, MPI_STATUS_IGNORE);
MPI_Sendrecv(&(subarray[ 1 *(nx+2*R)+1]), 1, xSlice, nbrs[DOWN], 2,
&(subarray[(ny+1)*(nx+2*R)+1]), 1, xSlice, nbrs[UP] , 2,
Comm2d, MPI_STATUS_IGNORE);
// Exchange y - slices with left and right neighbors
MPI_Sendrecv(&(subarray[1*(nx+2*R)+ nx ]), 1, ySlice, nbrs[RIGHT],3,
&(subarray[1*(nx+2*R)+ 0 ]), 1, ySlice, nbrs[LEFT] ,3,
Comm2d, MPI_STATUS_IGNORE);
MPI_Sendrecv(&(subarray[1*(nx+2*R)+ 1 ]), 1, ySlice, nbrs[LEFT] ,4,
&(subarray[1*(nx+2*R)+(nx+1)]), 1, ySlice, nbrs[RIGHT],4,
Comm2d, MPI_STATUS_IGNORE);
// every processor prints the subarray
for (int p=0; p<size; p++) {
if (rank == p) {
printf("Local process on rank %d is:\n", rank);
for (i=0; i<ny+2*R; i++) {
putchar('|');
for (j=0; j<nx+2*R; j++) {
printf("%3d ", subarray[i*(nx+2*R)+j]);
}
printf("|\n");
}
}
MPI_Barrier(Comm2d);
}
// gather all pieces into the big data array
MPI_Gatherv(subarray, 1, myLocal,
bigarray, sendcounts, displs, myGlobal, ROOT, Comm2d);
// print the bigarray and free array in root
if (rank==ROOT) print(bigarray, NX, NY);
// MPI types
MPI_Type_free(&xSlice);
MPI_Type_free(&ySlice);
MPI_Type_free(&myLocal);
MPI_Type_free(&myGlobal);
// free arrays in workers
if (rank==ROOT) free(bigarray);
free(subarray);
// finalize MPI
MPI_Finalize();
return 0;
}
<|endoftext|> |
<commit_before>/* The MIT License
Copyright (c) 2011 Sahab Yazdani
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 "stippler_impl.h"
#include <fstream>
#include <limits>
#include <boost/random.hpp>
#include "VoronoiDiagramGenerator.h"
Stippler::Stippler( const StipplingParameters ¶meters )
: IStippler(),
parameters(parameters),
displacement(std::numeric_limits<float>::max()),
vertsX(new float[parameters.points]), vertsY(new float[parameters.points]), radii(new float[parameters.points]),
image(parameters.inputFile) {
createInitialDistribution();
}
Stippler::~Stippler() {
delete[] radii;
delete[] vertsX;
delete[] vertsY;
}
void Stippler::distribute() {
createVoronoiDiagram();
redistributeStipples();
}
float Stippler::getAverageDisplacement() {
return displacement;
}
void Stippler::createInitialDistribution() {
using std::ceil;
// find initial distribution
boost::mt19937 rng;
boost::uniform_01<boost::mt19937, float> generator( rng );
float w = (float)image.getWidth(), h = (float)image.getHeight();
float xC, yC;
for ( unsigned int i = 0; i < parameters.points; ) {
xC = generator() * w;
yC = generator() * h;
// do a nearest neighbour search on the vertices
if ( ceil(generator() * 255.0f) <= image.getIntensity( xC, yC ) ) {
vertsX[i] = xC;
vertsY[i] = yC;
radii[i] = 0.0f;
i++;
}
}
}
void Stippler::getStipples( StipplePoint *dst ) {
StipplePoint *workingPtr;
for (unsigned int i = 0; i < parameters.points; i++ ) {
workingPtr = &(dst[i]);
workingPtr->x = vertsX[i];
workingPtr->y = vertsY[i];
workingPtr->radius = radii[i];
image.getColour(vertsX[i], vertsY[i], workingPtr->r, workingPtr->g, workingPtr->b);
}
}
void Stippler::createVoronoiDiagram() {
VoronoiDiagramGenerator generator;
generator.generateVoronoi( vertsX, vertsY, parameters.points,
0.0f, (float)image.getWidth(), 0.0f, (float)image.getHeight(), 0.0f/*::sqrt(8.0f) + 0.1f*/ );
edges.clear();
Point< float > p1, p2;
Edge< float > edge;
generator.resetIterator();
while ( generator.getNext(
edge.begin.x, edge.begin.y, edge.end.x, edge.end.y,
p1.x, p1.y, p2.x, p2.y ) ) {
if ( edge.begin == edge.end ) {
continue;
}
if ( edges.find( p1 ) == edges.end() ) {
edges[p1] = EdgeList();
}
if ( edges.find( p2 ) == edges.end() ) {
edges[p2] = EdgeList();
}
edges[p1].push_back( edge );
edges[p2].push_back( edge );
}
}
void Stippler::redistributeStipples() {
using std::pow;
using std::sqrt;
using std::pair;
using std::make_pair;
using std::vector;
unsigned int j = 0;
float distance;
vector< pair< Point< float >, EdgeList > > vectorized;
for ( EdgeMap::iterator key_iter = edges.begin(); key_iter != edges.end(); ++key_iter ) {
vectorized.push_back(make_pair(key_iter->first, key_iter->second));
}
displacement = 0.0f;
#pragma omp parallel for private(distance)
for (int i = 0; i < (int)vectorized.size(); i++) {
pair< Point< float >, EdgeList > item = vectorized[i];
pair< Point<float>, float > centroid = calculateCellCentroid( item.first, item.second );
distance = sqrt( pow( item.first.x - centroid.first.x, 2.0f ) + pow( item.first.y - centroid.first.y, 2.0f ) );
radii[i] = centroid.second;
vertsX[i] = centroid.first.x;
vertsY[i] = centroid.first.y;
#pragma omp atomic
displacement += distance;
}
displacement /= vectorized.size(); // average out the displacement
}
inline Stippler::line Stippler::createClipLine( float insideX, float insideY, float x1, float y1, float x2, float y2 ) {
using std::abs;
using std::numeric_limits;
Stippler::line l;
// if the floating point version of the line collapsed down to one
// point, then just ignore it all
if (abs(x1 - x2) < numeric_limits<float>::epsilon() && abs(y1 - y2) < numeric_limits<float>::epsilon()) {
l.a = .0f;
l.b = .0f;
l.c = .0f;
return l;
}
l.a = -(y1 - y2);
l.b = x1 - x2;
l.c = (y1 - y2) * x1 - (x1 - x2) * y1;
// make sure the known inside point falls on the correct side of the clipping plane
if ( insideX * l.a + insideY * l.b + l.c > 0.0f ) {
l.a *= -1;
l.b *= -1;
l.c *= -1;
}
return l;
}
std::pair< Point<float>, float > Stippler::calculateCellCentroid( Point<float> &inside, EdgeList &edgeList ) {
using std::make_pair;
using std::numeric_limits;
using std::vector;
using std::floor;
using std::ceil;
using std::abs;
using std::sqrt;
using std::pow;
vector<line> clipLines;
extents extent = getCellExtents(edgeList);
unsigned int x, y;
float xDiff = ( extent.maxX - extent.minX );
float yDiff = ( extent.maxY - extent.minY );
unsigned int tileWidth = (unsigned int)ceil(xDiff) * parameters.subpixels;
unsigned int tileHeight = (unsigned int)ceil(yDiff) * parameters.subpixels;
float xStep = xDiff / (float)tileWidth;
float yStep = yDiff / (float)tileHeight;
float spotDensity, areaDensity = 0.0f, maxAreaDensity = 0.0f;
float xSum = 0.0f;
float ySum = 0.0f;
float xCurrent;
float yCurrent;
// compute the clip lines
for ( EdgeList::iterator value_iter = edgeList.begin(); value_iter != edgeList.end(); ++value_iter ) {
line l = createClipLine( inside.x, inside.y,
value_iter->begin.x, value_iter->begin.y,
value_iter->end.x, value_iter->end.y );
if (l.a < numeric_limits<float>::epsilon() && abs(l.b) < numeric_limits<float>::epsilon()) {
continue;
}
clipLines.push_back(l);
}
for ( y = 0, yCurrent = extent.minY; y < tileHeight; ++y, yCurrent += yStep ) {
for ( x = 0, xCurrent = extent.minX; x < tileWidth; ++x, xCurrent += xStep ) {
// a point is outside of the polygon if it is outside of all clipping planes
bool outside = false;
for ( vector<line>::iterator iter = clipLines.begin(); iter != clipLines.end(); iter++ ) {
if ( xCurrent * iter->a + yCurrent * iter->b + iter->c >= 0.0f ) {
outside = true;
break;
}
}
if (!outside) {
spotDensity = image.getIntensity(xCurrent, yCurrent);
areaDensity += spotDensity;
maxAreaDensity += 255.0f;
xSum += spotDensity * xCurrent;
ySum += spotDensity * yCurrent;
}
}
}
float area = areaDensity * xStep * yStep / 255.0f;
float maxArea = maxAreaDensity * xStep * yStep / 255.0f;
Point<float> pt;
if (areaDensity > numeric_limits<float>::epsilon()) {
pt.x = xSum / areaDensity;
pt.y = ySum / areaDensity;
} else {
// if for some reason, the cell is completely white, then the centroid does not move
pt.x = inside.x;
pt.y = inside.y;
}
float closest = numeric_limits<float>::max(),
farthest = numeric_limits<float>::min(),
distance;
float x0 = pt.x, y0 = pt.y,
x1, x2, y1, y2;
for ( EdgeList::iterator value_iter = edgeList.begin(); value_iter != edgeList.end(); ++value_iter ) {
x1 = value_iter->begin.x; x2 = value_iter->end.x;
y1 = value_iter->begin.y; y2 = value_iter->end.y;
distance = abs( ( x2 - x1 ) * ( y1 - y0 ) - ( x1 - x0 ) * ( y2 - y1 ) ) / sqrt( pow( x2 - x1, 2.0f ) + pow( y2 - y1, 2.0f ) );
if ( closest > distance ) {
closest = distance;
}
if ( farthest < distance ) {
farthest = distance;
}
}
float radius;
if ( parameters.noOverlap ) {
radius = closest;
} else {
radius = farthest;
}
radius *= area / maxArea;
return make_pair( pt, radius );
}
Stippler::extents Stippler::getCellExtents( Stippler::EdgeList &edgeList ) {
using std::numeric_limits;
extents extent;
extent.minX = extent.minY = numeric_limits<float>::max();
extent.maxX = extent.maxY = numeric_limits<float>::min();
for ( EdgeList::iterator value_iter = edgeList.begin(); value_iter != edgeList.end(); ++value_iter ) {
if ( value_iter->begin.x < extent.minX ) extent.minX = value_iter->begin.x;
if ( value_iter->end.x < extent.minX ) extent.minX = value_iter->end.x;
if ( value_iter->begin.y < extent.minY ) extent.minY = value_iter->begin.y;
if ( value_iter->end.y < extent.minY ) extent.minY = value_iter->end.y;
if ( value_iter->begin.x > extent.maxX ) extent.maxX = value_iter->begin.x;
if ( value_iter->end.x > extent.maxX ) extent.maxX = value_iter->end.x;
if ( value_iter->begin.y > extent.maxY ) extent.maxY = value_iter->begin.y;
if ( value_iter->end.y > extent.maxY ) extent.maxY = value_iter->end.y;
}
return extent;
}
bool operator==(Point<float> const& p1, Point<float> const& p2)
{
using std::abs;
using std::numeric_limits;
return abs( p1.x - p2.x ) < numeric_limits<float>::epsilon() &&
abs( p1.y - p2.y ) < numeric_limits<float>::epsilon();
}
std::size_t hash_value(Point<float> const& p) {
using std::size_t;
using boost::hash_combine;
size_t seed = 0;
hash_combine(seed, p.x);
hash_combine(seed, p.y);
return seed;
}
<commit_msg>Better OpenMP usage According to http://bisqwit.iki.fi/story/howto/openmp/#ReductionClause reduction is better than atomic<commit_after>/* The MIT License
Copyright (c) 2011 Sahab Yazdani
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 "stippler_impl.h"
#include <fstream>
#include <limits>
#include <boost/random.hpp>
#include "VoronoiDiagramGenerator.h"
Stippler::Stippler( const StipplingParameters ¶meters )
: IStippler(),
parameters(parameters),
displacement(std::numeric_limits<float>::max()),
vertsX(new float[parameters.points]), vertsY(new float[parameters.points]), radii(new float[parameters.points]),
image(parameters.inputFile) {
createInitialDistribution();
}
Stippler::~Stippler() {
delete[] radii;
delete[] vertsX;
delete[] vertsY;
}
void Stippler::distribute() {
createVoronoiDiagram();
redistributeStipples();
}
float Stippler::getAverageDisplacement() {
return displacement;
}
void Stippler::createInitialDistribution() {
using std::ceil;
// find initial distribution
boost::mt19937 rng;
boost::uniform_01<boost::mt19937, float> generator( rng );
float w = (float)image.getWidth(), h = (float)image.getHeight();
float xC, yC;
for ( unsigned int i = 0; i < parameters.points; ) {
xC = generator() * w;
yC = generator() * h;
// do a nearest neighbour search on the vertices
if ( ceil(generator() * 255.0f) <= image.getIntensity( xC, yC ) ) {
vertsX[i] = xC;
vertsY[i] = yC;
radii[i] = 0.0f;
i++;
}
}
}
void Stippler::getStipples( StipplePoint *dst ) {
StipplePoint *workingPtr;
for (unsigned int i = 0; i < parameters.points; i++ ) {
workingPtr = &(dst[i]);
workingPtr->x = vertsX[i];
workingPtr->y = vertsY[i];
workingPtr->radius = radii[i];
image.getColour(vertsX[i], vertsY[i], workingPtr->r, workingPtr->g, workingPtr->b);
}
}
void Stippler::createVoronoiDiagram() {
VoronoiDiagramGenerator generator;
generator.generateVoronoi( vertsX, vertsY, parameters.points,
0.0f, (float)image.getWidth(), 0.0f, (float)image.getHeight(), 0.0f/*::sqrt(8.0f) + 0.1f*/ );
edges.clear();
Point< float > p1, p2;
Edge< float > edge;
generator.resetIterator();
while ( generator.getNext(
edge.begin.x, edge.begin.y, edge.end.x, edge.end.y,
p1.x, p1.y, p2.x, p2.y ) ) {
if ( edge.begin == edge.end ) {
continue;
}
if ( edges.find( p1 ) == edges.end() ) {
edges[p1] = EdgeList();
}
if ( edges.find( p2 ) == edges.end() ) {
edges[p2] = EdgeList();
}
edges[p1].push_back( edge );
edges[p2].push_back( edge );
}
}
void Stippler::redistributeStipples() {
using std::pow;
using std::sqrt;
using std::pair;
using std::make_pair;
using std::vector;
unsigned int j = 0;
float distance, local_displacement;
vector< pair< Point< float >, EdgeList > > vectorized;
for ( EdgeMap::iterator key_iter = edges.begin(); key_iter != edges.end(); ++key_iter ) {
vectorized.push_back(make_pair(key_iter->first, key_iter->second));
}
local_displacement = displacement = 0.0f;
#pragma omp parallel for private(distance) reduction(+:local_displacement)
for (int i = 0; i < (int)vectorized.size(); i++) {
pair< Point< float >, EdgeList > item = vectorized[i];
pair< Point<float>, float > centroid = calculateCellCentroid( item.first, item.second );
distance = sqrt( pow( item.first.x - centroid.first.x, 2.0f ) + pow( item.first.y - centroid.first.y, 2.0f ) );
radii[i] = centroid.second;
vertsX[i] = centroid.first.x;
vertsY[i] = centroid.first.y;
local_displacement += distance;
}
displacement = local_displacement / vectorized.size(); // average out the displacement
}
inline Stippler::line Stippler::createClipLine( float insideX, float insideY, float x1, float y1, float x2, float y2 ) {
using std::abs;
using std::numeric_limits;
Stippler::line l;
// if the floating point version of the line collapsed down to one
// point, then just ignore it all
if (abs(x1 - x2) < numeric_limits<float>::epsilon() && abs(y1 - y2) < numeric_limits<float>::epsilon()) {
l.a = .0f;
l.b = .0f;
l.c = .0f;
return l;
}
l.a = -(y1 - y2);
l.b = x1 - x2;
l.c = (y1 - y2) * x1 - (x1 - x2) * y1;
// make sure the known inside point falls on the correct side of the clipping plane
if ( insideX * l.a + insideY * l.b + l.c > 0.0f ) {
l.a *= -1;
l.b *= -1;
l.c *= -1;
}
return l;
}
std::pair< Point<float>, float > Stippler::calculateCellCentroid( Point<float> &inside, EdgeList &edgeList ) {
using std::make_pair;
using std::numeric_limits;
using std::vector;
using std::floor;
using std::ceil;
using std::abs;
using std::sqrt;
using std::pow;
vector<line> clipLines;
extents extent = getCellExtents(edgeList);
unsigned int x, y;
float xDiff = ( extent.maxX - extent.minX );
float yDiff = ( extent.maxY - extent.minY );
unsigned int tileWidth = (unsigned int)ceil(xDiff) * parameters.subpixels;
unsigned int tileHeight = (unsigned int)ceil(yDiff) * parameters.subpixels;
float xStep = xDiff / (float)tileWidth;
float yStep = yDiff / (float)tileHeight;
float spotDensity, areaDensity = 0.0f, maxAreaDensity = 0.0f;
float xSum = 0.0f;
float ySum = 0.0f;
float xCurrent;
float yCurrent;
// compute the clip lines
for ( EdgeList::iterator value_iter = edgeList.begin(); value_iter != edgeList.end(); ++value_iter ) {
line l = createClipLine( inside.x, inside.y,
value_iter->begin.x, value_iter->begin.y,
value_iter->end.x, value_iter->end.y );
if (l.a < numeric_limits<float>::epsilon() && abs(l.b) < numeric_limits<float>::epsilon()) {
continue;
}
clipLines.push_back(l);
}
for ( y = 0, yCurrent = extent.minY; y < tileHeight; ++y, yCurrent += yStep ) {
for ( x = 0, xCurrent = extent.minX; x < tileWidth; ++x, xCurrent += xStep ) {
// a point is outside of the polygon if it is outside of all clipping planes
bool outside = false;
for ( vector<line>::iterator iter = clipLines.begin(); iter != clipLines.end(); iter++ ) {
if ( xCurrent * iter->a + yCurrent * iter->b + iter->c >= 0.0f ) {
outside = true;
break;
}
}
if (!outside) {
spotDensity = image.getIntensity(xCurrent, yCurrent);
areaDensity += spotDensity;
maxAreaDensity += 255.0f;
xSum += spotDensity * xCurrent;
ySum += spotDensity * yCurrent;
}
}
}
float area = areaDensity * xStep * yStep / 255.0f;
float maxArea = maxAreaDensity * xStep * yStep / 255.0f;
Point<float> pt;
if (areaDensity > numeric_limits<float>::epsilon()) {
pt.x = xSum / areaDensity;
pt.y = ySum / areaDensity;
} else {
// if for some reason, the cell is completely white, then the centroid does not move
pt.x = inside.x;
pt.y = inside.y;
}
float closest = numeric_limits<float>::max(),
farthest = numeric_limits<float>::min(),
distance;
float x0 = pt.x, y0 = pt.y,
x1, x2, y1, y2;
for ( EdgeList::iterator value_iter = edgeList.begin(); value_iter != edgeList.end(); ++value_iter ) {
x1 = value_iter->begin.x; x2 = value_iter->end.x;
y1 = value_iter->begin.y; y2 = value_iter->end.y;
distance = abs( ( x2 - x1 ) * ( y1 - y0 ) - ( x1 - x0 ) * ( y2 - y1 ) ) / sqrt( pow( x2 - x1, 2.0f ) + pow( y2 - y1, 2.0f ) );
if ( closest > distance ) {
closest = distance;
}
if ( farthest < distance ) {
farthest = distance;
}
}
float radius;
if ( parameters.noOverlap ) {
radius = closest;
} else {
radius = farthest;
}
radius *= area / maxArea;
return make_pair( pt, radius );
}
Stippler::extents Stippler::getCellExtents( Stippler::EdgeList &edgeList ) {
using std::numeric_limits;
extents extent;
extent.minX = extent.minY = numeric_limits<float>::max();
extent.maxX = extent.maxY = numeric_limits<float>::min();
for ( EdgeList::iterator value_iter = edgeList.begin(); value_iter != edgeList.end(); ++value_iter ) {
if ( value_iter->begin.x < extent.minX ) extent.minX = value_iter->begin.x;
if ( value_iter->end.x < extent.minX ) extent.minX = value_iter->end.x;
if ( value_iter->begin.y < extent.minY ) extent.minY = value_iter->begin.y;
if ( value_iter->end.y < extent.minY ) extent.minY = value_iter->end.y;
if ( value_iter->begin.x > extent.maxX ) extent.maxX = value_iter->begin.x;
if ( value_iter->end.x > extent.maxX ) extent.maxX = value_iter->end.x;
if ( value_iter->begin.y > extent.maxY ) extent.maxY = value_iter->begin.y;
if ( value_iter->end.y > extent.maxY ) extent.maxY = value_iter->end.y;
}
return extent;
}
bool operator==(Point<float> const& p1, Point<float> const& p2)
{
using std::abs;
using std::numeric_limits;
return abs( p1.x - p2.x ) < numeric_limits<float>::epsilon() &&
abs( p1.y - p2.y ) < numeric_limits<float>::epsilon();
}
std::size_t hash_value(Point<float> const& p) {
using std::size_t;
using boost::hash_combine;
size_t seed = 0;
hash_combine(seed, p.x);
hash_combine(seed, p.y);
return seed;
}
<|endoftext|> |
<commit_before><commit_msg>Update HttpServerRequestHandler.cpp<commit_after><|endoftext|> |
<commit_before>#include <Halide.h>
#include <stdio.h>
#include "clock.h"
#include <memory>
using namespace Halide;
enum {
scalar_trans,
vec_y_trans,
vec_x_trans
};
void test_transpose(int mode) {
Func input, block, block_transpose, output;
Var x, y;
input(x, y) = cast<uint16_t>(x + y);
input.compute_root();
block(x, y) = input(x, y);
block_transpose(x, y) = block(y, x);
output(x, y) = block_transpose(x, y);
Var xi, yi;
output.tile(x, y, xi, yi, 8, 8).vectorize(xi).unroll(yi);
// Do 8 vectorized loads from the input.
block.compute_at(output, x).vectorize(x).unroll(y);
std::string algorithm;
switch(mode) {
case scalar_trans:
block_transpose.compute_at(output, x).unroll(x).unroll(y);
algorithm = "Scalar transpose";
break;
case vec_y_trans:
block_transpose.compute_at(output, x).vectorize(y).unroll(x);
algorithm = "Transpose vectorized in y";
break;
case vec_x_trans:
block_transpose.compute_at(output, x).vectorize(x).unroll(y);
algorithm = "Transpose vectorized in x";
break;
}
output.compile_to_lowered_stmt("fast_transpose.stmt");
output.compile_to_assembly("fast_transpose.s", std::vector<Argument>());
Image<uint16_t> result(1024, 1024);
output.compile_jit();
output.realize(result);
double t1 = current_time();
for (int i = 0; i < 10; i++) {
output.realize(result);
}
double t2 = current_time();
std::cout << algorithm << " bandwidth " << ((1024*1024 / (t2 - t1)) * 1000 * 10) << " byte/s.\n";
}
int main(int argc, char **argv) {
test_transpose(scalar_trans);
test_transpose(vec_y_trans);
test_transpose(vec_x_trans);
printf("Success!\n");
return 0;
}
<commit_msg>Modified block_transpose performance test to ouput assembly code for each different algorithm.<commit_after>#include <Halide.h>
#include <stdio.h>
#include "clock.h"
#include <memory>
using namespace Halide;
enum {
scalar_trans,
vec_y_trans,
vec_x_trans
};
void test_transpose(int mode) {
Func input, block, block_transpose, output;
Var x, y;
input(x, y) = cast<uint16_t>(x + y);
input.compute_root();
block(x, y) = input(x, y);
block_transpose(x, y) = block(y, x);
output(x, y) = block_transpose(x, y);
Var xi, yi;
output.tile(x, y, xi, yi, 8, 8).vectorize(xi).unroll(yi);
// Do 8 vectorized loads from the input.
block.compute_at(output, x).vectorize(x).unroll(y);
std::string algorithm;
switch(mode) {
case scalar_trans:
block_transpose.compute_at(output, x).unroll(x).unroll(y);
algorithm = "Scalar transpose";
output.compile_to_assembly("scalar_transpose.s", std::vector<Argument>());
break;
case vec_y_trans:
block_transpose.compute_at(output, x).vectorize(y).unroll(x);
algorithm = "Transpose vectorized in y";
output.compile_to_assembly("fast_transpose_y.s", std::vector<Argument>());
break;
case vec_x_trans:
block_transpose.compute_at(output, x).vectorize(x).unroll(y);
algorithm = "Transpose vectorized in x";
output.compile_to_assembly("fast_transpose_x.s", std::vector<Argument>());
break;
}
Image<uint16_t> result(1024, 1024);
output.compile_jit();
output.realize(result);
double t1 = current_time();
for (int i = 0; i < 10; i++) {
output.realize(result);
}
double t2 = current_time();
std::cout << algorithm << " bandwidth " << ((1024*1024 / (t2 - t1)) * 1000 * 10) << " byte/s.\n";
}
int main(int argc, char **argv) {
test_transpose(scalar_trans);
test_transpose(vec_y_trans);
test_transpose(vec_x_trans);
printf("Success!\n");
return 0;
}
<|endoftext|> |
<commit_before><commit_msg>Remove file<commit_after><|endoftext|> |
<commit_before><commit_msg>Use a std::map instead of a linear search to look up files for line records.<commit_after><|endoftext|> |
<commit_before><commit_msg>GeographyValue.hpp: Add const to methods which should be const<commit_after><|endoftext|> |
<commit_before><commit_msg>Omit shader swizzle if it is rgba.<commit_after><|endoftext|> |
<commit_before><commit_msg>INTEGRATION: CWS vgbugs07 (1.36.132); FILE MERGED 2007/06/04 13:27:07 vg 1.36.132.1: #i76605# Remove -I .../inc/module hack introduced by hedaburemove01<commit_after><|endoftext|> |
<commit_before>#include <turbo/threading/shared_mutex.hpp>
#include <turbo/threading/shared_lock.hpp>
#include <turbo/threading/shared_lock.hxx>
#include <gtest/gtest.h>
#include <asio/io_service.hpp>
#include <algorithm>
#include <functional>
#include <memory>
#include <string>
#include <thread>
#include <utility>
namespace tth = turbo::threading;
class write_task
{
public:
write_task(tth::shared_mutex& mutex, std::string& shared_value);
~write_task();
bool is_running() const { return thread_ != nullptr; }
void start();
void stop();
template <typename then_f>
void write(const std::string& value, then_f&& then_func);
private:
void run();
void exec_stop();
template <typename then_f>
void exec_write(const std::string& value, then_f&& then_func);
tth::shared_mutex& mutex_;
std::string& shared_value_;
std::thread* thread_;
asio::io_service service_;
};
write_task::write_task(tth::shared_mutex& mutex, std::string& shared_value)
:
mutex_(mutex),
shared_value_(shared_value),
thread_(nullptr),
service_()
{ }
write_task::~write_task()
{
stop();
if (is_running())
{
thread_->join();
delete thread_;
}
}
void write_task::start()
{
if (!is_running())
{
thread_ = new std::thread(std::bind(&write_task::run, this));
}
}
void write_task::stop()
{
service_.post(std::bind(&write_task::exec_stop, this));
}
void write_task::run()
{
EXPECT_TRUE(1U <= service_.run());
service_.reset();
}
template <typename then_f>
void write_task::write(const std::string& value, then_f&& then_func)
{
service_.post([this, value, &then_func]() -> void
{
this->exec_write<then_f>(value, std::forward<then_f&&>(then_func));
});
}
void write_task::exec_stop()
{
service_.stop();
}
template <typename then_f>
void write_task::exec_write(const std::string& value, then_f&& then_func)
{
{
std::unique_lock<tth::shared_mutex> lock(mutex_);
shared_value_ = value;
}
then_func();
}
class read_task
{
public:
read_task(tth::shared_mutex& mutex, std::string& shared_value, const std::string& expected_value);
~read_task();
bool is_running() const { return thread_ != nullptr; }
void start();
void stop();
void read();
private:
void run();
void exec_stop();
void exec_read();
tth::shared_mutex& mutex_;
std::string& shared_value_;
std::thread* thread_;
asio::io_service service_;
std::string expected_;
};
read_task::read_task(tth::shared_mutex& mutex, std::string& shared_value, const std::string& expected_value)
:
mutex_(mutex),
shared_value_(shared_value),
thread_(nullptr),
service_(),
expected_(expected_value)
{ }
read_task::~read_task()
{
stop();
if (is_running())
{
thread_->join();
delete thread_;
}
}
void read_task::start()
{
if (!is_running())
{
thread_ = new std::thread(std::bind(&read_task::run, this));
}
}
void read_task::stop()
{
service_.post(std::bind(&read_task::exec_stop, this));
}
void read_task::run()
{
EXPECT_TRUE(1U <= service_.run());
service_.reset();
}
void read_task::read()
{
service_.post([&]() -> void
{
this->exec_read();
});
}
void read_task::exec_stop()
{
service_.stop();
}
void read_task::exec_read()
{
std::string value;
{
tth::shared_lock<tth::shared_mutex> lock(mutex_);
value = shared_value_;
}
auto result = std::search(value.cbegin(), value.cend(), expected_.cbegin(), expected_.cend());
if (result == value.cend())
{
this->read();
}
else
{
EXPECT_EQ(value.cbegin(), result) << "read failed";
}
}
TEST(shared_mutex_test, basic_read)
{
tth::shared_mutex mutex1;
std::string value1("foo");
{
read_task reader1(mutex1, value1, "foo");
read_task reader2(mutex1, value1, "foo");
read_task reader3(mutex1, value1, "foo");
reader1.read();
reader2.read();
reader3.read();
reader1.start();
reader2.start();
reader3.start();
}
}
TEST(shared_mutex_test, basic_write)
{
tth::shared_mutex mutex1;
std::string value1("foo");
{
read_task reader1(mutex1, value1, "bar");
read_task reader2(mutex1, value1, "bar");
read_task reader3(mutex1, value1, "bar");
write_task writer1(mutex1, value1);
write_task writer2(mutex1, value1);
reader1.read();
reader2.read();
reader3.read();
writer1.write("bar1", [&]() -> void { });
writer2.write("bar2", [&]() -> void { });
reader1.start();
reader2.start();
reader3.start();
writer1.start();
writer2.start();
}
}
<commit_msg>adding mixed lock usage test case<commit_after>#include <turbo/threading/shared_mutex.hpp>
#include <turbo/threading/shared_lock.hpp>
#include <turbo/threading/shared_lock.hxx>
#include <gtest/gtest.h>
#include <asio/io_service.hpp>
#include <algorithm>
#include <functional>
#include <memory>
#include <string>
#include <thread>
#include <utility>
namespace tth = turbo::threading;
class write_task
{
public:
write_task(tth::shared_mutex& mutex, std::string& shared_value);
~write_task();
bool is_running() const { return thread_ != nullptr; }
void start();
void stop();
template <typename then_f>
void write(const std::string& value, then_f&& then_func);
private:
void run();
void exec_stop();
template <typename then_f>
void exec_write(const std::string& value, then_f&& then_func);
tth::shared_mutex& mutex_;
std::string& shared_value_;
std::thread* thread_;
asio::io_service service_;
};
write_task::write_task(tth::shared_mutex& mutex, std::string& shared_value)
:
mutex_(mutex),
shared_value_(shared_value),
thread_(nullptr),
service_()
{ }
write_task::~write_task()
{
stop();
if (is_running())
{
thread_->join();
delete thread_;
}
}
void write_task::start()
{
if (!is_running())
{
thread_ = new std::thread(std::bind(&write_task::run, this));
}
}
void write_task::stop()
{
service_.post(std::bind(&write_task::exec_stop, this));
}
void write_task::run()
{
EXPECT_TRUE(1U <= service_.run());
service_.reset();
}
template <typename then_f>
void write_task::write(const std::string& value, then_f&& then_func)
{
service_.post([this, value, &then_func]() -> void
{
this->exec_write<then_f>(value, std::forward<then_f&&>(then_func));
});
}
void write_task::exec_stop()
{
service_.stop();
}
template <typename then_f>
void write_task::exec_write(const std::string& value, then_f&& then_func)
{
{
std::unique_lock<tth::shared_mutex> lock(mutex_);
shared_value_ = value;
}
then_func();
}
class read_task
{
public:
read_task(tth::shared_mutex& mutex, std::string& shared_value, const std::string& expected_value);
~read_task();
bool is_running() const { return thread_ != nullptr; }
void start();
void stop();
void read();
private:
void run();
void exec_stop();
void exec_read();
tth::shared_mutex& mutex_;
std::string& shared_value_;
std::thread* thread_;
asio::io_service service_;
std::string expected_;
};
read_task::read_task(tth::shared_mutex& mutex, std::string& shared_value, const std::string& expected_value)
:
mutex_(mutex),
shared_value_(shared_value),
thread_(nullptr),
service_(),
expected_(expected_value)
{ }
read_task::~read_task()
{
stop();
if (is_running())
{
thread_->join();
delete thread_;
}
}
void read_task::start()
{
if (!is_running())
{
thread_ = new std::thread(std::bind(&read_task::run, this));
}
}
void read_task::stop()
{
service_.post(std::bind(&read_task::exec_stop, this));
}
void read_task::run()
{
EXPECT_TRUE(1U <= service_.run());
service_.reset();
}
void read_task::read()
{
service_.post([&]() -> void
{
this->exec_read();
});
}
void read_task::exec_stop()
{
service_.stop();
}
void read_task::exec_read()
{
std::string value;
{
tth::shared_lock<tth::shared_mutex> lock(mutex_);
value = shared_value_;
}
auto result = std::search(value.cbegin(), value.cend(), expected_.cbegin(), expected_.cend());
if (result == value.cend())
{
this->read();
}
else
{
EXPECT_EQ(value.cbegin(), result) << "read failed";
}
}
TEST(shared_mutex_test, basic_read)
{
tth::shared_mutex mutex1;
std::string value1("foo");
{
read_task reader1(mutex1, value1, "foo");
read_task reader2(mutex1, value1, "foo");
read_task reader3(mutex1, value1, "foo");
reader1.read();
reader2.read();
reader3.read();
reader1.start();
reader2.start();
reader3.start();
}
}
TEST(shared_mutex_test, basic_write)
{
tth::shared_mutex mutex1;
std::string value1("foo");
{
read_task reader1(mutex1, value1, "bar");
read_task reader2(mutex1, value1, "bar");
read_task reader3(mutex1, value1, "bar");
write_task writer1(mutex1, value1);
write_task writer2(mutex1, value1);
reader1.read();
reader2.read();
reader3.read();
writer1.write("bar1", [&]() -> void { });
writer2.write("bar2", [&]() -> void { });
reader1.start();
reader2.start();
reader3.start();
writer1.start();
writer2.start();
}
}
TEST(shared_mutex_test, mixed_locks)
{
tth::shared_mutex mutex1;
{
std::unique_lock<tth::shared_mutex> lock1a(mutex1, std::defer_lock);
EXPECT_TRUE(lock1a.try_lock()) << "1st lock (unique) failed";
}
{
tth::shared_lock<tth::shared_mutex> lock1b(mutex1, std::defer_lock);
EXPECT_TRUE(lock1b.try_lock()) << "2nd lock (shared) failed";
}
{
std::unique_lock<tth::shared_mutex> lock1c(mutex1, std::defer_lock);
EXPECT_TRUE(lock1c.try_lock()) << "3rd lock (unique) failed";
}
{
tth::shared_lock<tth::shared_mutex> lock1d(mutex1, std::defer_lock);
EXPECT_TRUE(lock1d.try_lock()) << "4th lock (shared) failed";
}
tth::shared_mutex mutex2;
{
tth::shared_lock<tth::shared_mutex> lock2a(mutex2, std::defer_lock);
EXPECT_TRUE(lock2a.try_lock()) << "2nd lock (shared) failed";
}
{
std::unique_lock<tth::shared_mutex> lock2b(mutex2, std::defer_lock);
EXPECT_TRUE(lock2b.try_lock()) << "1st lock (unique) failed";
}
{
tth::shared_lock<tth::shared_mutex> lock2c(mutex2, std::defer_lock);
EXPECT_TRUE(lock2c.try_lock()) << "4th lock (shared) failed";
}
{
std::unique_lock<tth::shared_mutex> lock2d(mutex2, std::defer_lock);
EXPECT_TRUE(lock2d.try_lock()) << "3rd lock (unique) failed";
}
}
<|endoftext|> |
<commit_before>#include <dublintraceroute/udpv4probe.h>
#include <gtest/gtest.h>
#include <tins/tins.h>
using namespace Tins;
namespace {
class UDPv4Test: public ::testing::Test {
};
TEST_F(UDPv4Test, TestUDPv4Constructor) {
UDPv4Probe p = UDPv4Probe(IPv4Address("8.8.8.8"), 33434, 12345, 64, IPv4Address("127.0.0.2"));
ASSERT_EQ(p.local_port(), 12345);
ASSERT_EQ(p.remote_port(), 33434);
ASSERT_EQ(p.ttl(), 64);
ASSERT_EQ(p.remote_addr().to_string(), std::string("8.8.8.8"));
ASSERT_EQ(p.local_addr().to_string(), std::string("127.0.0.2"));
}
TEST_F(UDPv4Test, TestUDPv4ConstructorDefaultLocalAddr) {
UDPv4Probe p = UDPv4Probe(IPv4Address("8.8.8.8"), 33434, 12345, 64);
ASSERT_EQ(p.local_port(), 12345);
ASSERT_EQ(p.remote_port(), 33434);
ASSERT_EQ(p.ttl(), 64);
ASSERT_EQ(p.remote_addr().to_string(), std::string("8.8.8.8"));
ASSERT_EQ(p.local_addr().to_string(), std::string("0.0.0.0"));
}
TEST_F(UDPv4Test, TestUDPv4PacketForging) {
UDPv4Probe p = UDPv4Probe(IPv4Address("127.0.0.3"), 33434, 12345, 64, IPv4Address("127.0.0.2"));
IP* ip = p.forge();
ASSERT_EQ(ip->tos(), 0);
ASSERT_EQ(ip->id(), 60794);
ASSERT_EQ(ip->flags(), Tins::IP::Flags::DONT_FRAGMENT);
ASSERT_EQ(ip->ttl(), 64);
ASSERT_EQ(ip->dst_addr().to_string(), std::string("127.0.0.3"));
ASSERT_EQ(ip->src_addr().to_string(), std::string("127.0.0.2"));
delete ip;
}
TEST_F(UDPv4Test, TestUDPv4PacketForgingDefaultLocalAddr) {
UDPv4Probe p = UDPv4Probe(IPv4Address("8.8.8.8"), 33434, 12345, 64);
IP* ip = p.forge();
ASSERT_EQ(ip->tos(), 0);
ASSERT_EQ(ip->id(), 36162);
ASSERT_EQ(ip->flags(), Tins::IP::Flags::DONT_FRAGMENT);
ASSERT_EQ(ip->ttl(), 64);
ASSERT_EQ(ip->dst_addr().to_string(), std::string("8.8.8.8"));
// not testing src_addr because in this test it depends on the actual
// network interface's outgoing address for the destination
delete ip;
}
}
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
std::exit(RUN_ALL_TESTS());
}
<commit_msg>Removed IP ID check for default addr test<commit_after>#include <dublintraceroute/udpv4probe.h>
#include <gtest/gtest.h>
#include <tins/tins.h>
using namespace Tins;
namespace {
class UDPv4Test: public ::testing::Test {
};
TEST_F(UDPv4Test, TestUDPv4Constructor) {
UDPv4Probe p = UDPv4Probe(IPv4Address("8.8.8.8"), 33434, 12345, 64, IPv4Address("127.0.0.2"));
ASSERT_EQ(p.local_port(), 12345);
ASSERT_EQ(p.remote_port(), 33434);
ASSERT_EQ(p.ttl(), 64);
ASSERT_EQ(p.remote_addr().to_string(), std::string("8.8.8.8"));
ASSERT_EQ(p.local_addr().to_string(), std::string("127.0.0.2"));
}
TEST_F(UDPv4Test, TestUDPv4ConstructorDefaultLocalAddr) {
UDPv4Probe p = UDPv4Probe(IPv4Address("8.8.8.8"), 33434, 12345, 64);
ASSERT_EQ(p.local_port(), 12345);
ASSERT_EQ(p.remote_port(), 33434);
ASSERT_EQ(p.ttl(), 64);
ASSERT_EQ(p.remote_addr().to_string(), std::string("8.8.8.8"));
ASSERT_EQ(p.local_addr().to_string(), std::string("0.0.0.0"));
}
TEST_F(UDPv4Test, TestUDPv4PacketForging) {
UDPv4Probe p = UDPv4Probe(IPv4Address("127.0.0.3"), 33434, 12345, 64, IPv4Address("127.0.0.2"));
IP* ip = p.forge();
ASSERT_EQ(ip->tos(), 0);
ASSERT_EQ(ip->id(), 60794);
ASSERT_EQ(ip->flags(), Tins::IP::Flags::DONT_FRAGMENT);
ASSERT_EQ(ip->ttl(), 64);
ASSERT_EQ(ip->dst_addr().to_string(), std::string("127.0.0.3"));
ASSERT_EQ(ip->src_addr().to_string(), std::string("127.0.0.2"));
delete ip;
}
TEST_F(UDPv4Test, TestUDPv4PacketForgingDefaultLocalAddr) {
UDPv4Probe p = UDPv4Probe(IPv4Address("8.8.8.8"), 33434, 12345, 64);
IP* ip = p.forge();
ASSERT_EQ(ip->tos(), 0);
ASSERT_EQ(ip->flags(), Tins::IP::Flags::DONT_FRAGMENT);
ASSERT_EQ(ip->ttl(), 64);
ASSERT_EQ(ip->dst_addr().to_string(), std::string("8.8.8.8"));
// not testing src_addr and IP ID because the default addr depends on
// the actual network interface's configuration
delete ip;
}
}
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
std::exit(RUN_ALL_TESTS());
}
<|endoftext|> |
<commit_before>/* -*- mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- */
// vim:sts=4:sw=4:ts=4:noet:sr:cino=>s,f0,{0,g0,(0,\:0,t0,+0,=s
/*
* Copyright (C) FFLAS-FFPACK
* Written by Clément Pernet <clement.pernet@imag.fr>
* Philippe LEDENT <philippe.ledent@etu.univ.grenoble-alpes
* This file is Free Software and part of FFLAS-FFPACK.
*
* ========LICENCE========
* This file is part of the library FFLAS-FFPACK.
*
* FFLAS-FFPACK 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 library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
* ========LICENCE========
*.
*/
#define __FFLASFFPACK_SEQUENTIAL
#define ENABLE_ALL_CHECKINGS 1
#include "fflas-ffpack/fflas-ffpack-config.h"
#include <iomanip>
#include <iostream>
#include "fflas-ffpack/utils/timer.h"
#include "fflas-ffpack/fflas/fflas.h"
#include "fflas-ffpack/utils/args-parser.h"
#include "test-utils.h"
#include <givaro/modular.h>
#include "fflas-ffpack/utils/fflas_io.h"
#include "fflas-ffpack/ffpack/ffpack.h"
using namespace std;
using namespace FFPACK;
using namespace FFLAS;
using Givaro::Modular;
using Givaro::ModularBalanced;
template<typename Field, class RandIter>
bool check_ftrtri (const Field &F, size_t n, FFLAS_UPLO uplo, FFLAS_DIAG diag, RandIter& Rand){
typedef typename Field::Element Element;
Element * A, * B, * C;
size_t lda = n + (rand() % n );
A = fflas_new(F,n,lda);
B = fflas_new(F,n,lda);
C = fflas_new(F,n,lda);
RandomTriangularMatrix (F, n, n, uplo, diag, true, A, lda, Rand);
fassign (F, n, n, A, lda, B, lda); // copy of A
fassign (F, n, n, A, lda, C, lda); // copy of A
string ss=string((uplo == FflasLower)?"Lower_":"Upper_")+string((diag == FflasUnit)?"Unit":"NonUnit");
cout<<std::left<<"Checking FTRTRI_";
cout.fill('.');
cout.width(30);
cout<<ss;
// << endl;
Timer t; t.clear();
double time=0.0;
t.clear();
t.start();
ftrtri (F, uplo, diag, n, A, lda);
t.stop();
time+=t.usertime();
// B <- A times B
ftrmm(F, FFLAS::FflasRight, uplo, FFLAS::FflasNoTrans, diag, n, n, F.one, A, lda, B, lda);
// Is B the identity matrix ?
bool ok = true;
for(size_t li = 0; (li < n) && ok; li++){
for(size_t co = 0; (co < n) && ok; co++){
ok = ((li == co) && (F.areEqual(B[li*lda+co],F.one))) || (F.areEqual(B[li*lda+co],F.zero));
}
}
if (ok){
cout << "PASSED ("<<time<<")"<<endl;
} else{
//string file = "./mat.sage";
//WriteMatrix(file,F,n,n,C,lda,FFLAS::FflasSageMath);
cout << "FAILED ("<<time<<")"<<endl;
WriteMatrix(std::cout << "\nA" << std::endl, F,n,n,C,lda);
WriteMatrix(std::cout << "\nA^-1" << std::endl, F,n,n,A,lda);
}
fflas_delete(A);
fflas_delete(B);
return ok;
}
template <class Field>
bool run_with_field (Givaro::Integer q, size_t b, size_t n, size_t iters, uint64_t seed){
bool ok = true ;
int nbit=(int)iters;
while (ok && nbit){
//typedef typename Field::Element Element ;
// choose Field
Field* F= chooseField<Field>(q,b);
typename Field::RandIter G(*F,0,seed);
if (F==nullptr)
return true;
cout<<"Checking with ";F->write(cout)<<endl;
ok = ok && check_ftrtri(*F,n,FflasLower,FflasUnit,G);
ok = ok && check_ftrtri(*F,n,FflasUpper,FflasUnit,G);
ok = ok && check_ftrtri(*F,n,FflasLower,FflasNonUnit,G);
ok = ok && check_ftrtri(*F,n,FflasUpper,FflasNonUnit,G);
nbit--;
delete F;
}
if (!ok)
std::cout << "with seed = "<< seed << std::endl;
return ok;
}
int main(int argc, char** argv)
{
cerr<<setprecision(10);
Givaro::Integer q=-1;
size_t b=0;
size_t n=207;
size_t iters=3;
bool loop=false;
uint64_t seed = time(NULL);
Argument as[] = {
{ 'q', "-q Q", "Set the field characteristic (-1 for random).", TYPE_INTEGER , &q },
{ 'b', "-b B", "Set the bitsize of the field characteristic.", TYPE_INT , &b },
{ 'n', "-n N", "Set the dimension of the system.", TYPE_INT , &n },
{ 'i', "-i R", "Set number of repetitions.", TYPE_INT , &iters },
{ 'l', "-loop Y/N", "run the test in an infinite loop.", TYPE_BOOL , &loop },
{ 's', "-s seed", "Set seed for the random generator", TYPE_INT, &seed },
END_OF_ARGUMENTS
};
parseArguments(argc,argv,as);
bool ok = true;
do{
ok &= run_with_field<Modular<double> >(q,b,n,iters,seed);
ok &= run_with_field<ModularBalanced<double> >(q,b,n,iters,seed);
ok &= run_with_field<Modular<float> >(q,b,n,iters,seed);
ok &= run_with_field<ModularBalanced<float> >(q,b,n,iters,seed);
ok &= run_with_field<Modular<int32_t> >(q,b,n,iters,seed);
ok &= run_with_field<ModularBalanced<int32_t> >(q,b,n,iters,seed);
ok &= run_with_field<Modular<int64_t> >(q,b,n,iters,seed);
ok &= run_with_field<ModularBalanced<int64_t> >(q,b,n,iters,seed);
ok &= run_with_field<Modular<Givaro::Integer> >(q,5,n/4+1,iters,seed);
ok &= run_with_field<Modular<Givaro::Integer> >(q,(b?b:512),n/4+1,iters,seed);
} while (loop && ok);
return !ok ;
}
<commit_msg>test-ftrtri.C : Corrected typo<commit_after>/* -*- mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- */
// vim:sts=4:sw=4:ts=4:noet:sr:cino=>s,f0,{0,g0,(0,\:0,t0,+0,=s
/*
* Copyright (C) FFLAS-FFPACK
* Written by Clément Pernet <clement.pernet@imag.fr>
* Philippe LEDENT <philippe.ledent@etu.univ-grenoble-alpes
* This file is Free Software and part of FFLAS-FFPACK.
*
* ========LICENCE========
* This file is part of the library FFLAS-FFPACK.
*
* FFLAS-FFPACK 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 library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
* ========LICENCE========
*.
*/
#define __FFLASFFPACK_SEQUENTIAL
#define ENABLE_ALL_CHECKINGS 1
#include "fflas-ffpack/fflas-ffpack-config.h"
#include <iomanip>
#include <iostream>
#include "fflas-ffpack/utils/timer.h"
#include "fflas-ffpack/fflas/fflas.h"
#include "fflas-ffpack/utils/args-parser.h"
#include "test-utils.h"
#include <givaro/modular.h>
#include "fflas-ffpack/utils/fflas_io.h"
#include "fflas-ffpack/ffpack/ffpack.h"
using namespace std;
using namespace FFPACK;
using namespace FFLAS;
using Givaro::Modular;
using Givaro::ModularBalanced;
template<typename Field, class RandIter>
bool check_ftrtri (const Field &F, size_t n, FFLAS_UPLO uplo, FFLAS_DIAG diag, RandIter& Rand){
typedef typename Field::Element Element;
Element * A, * B, * C;
size_t lda = n + (rand() % n );
A = fflas_new(F,n,lda);
B = fflas_new(F,n,lda);
C = fflas_new(F,n,lda);
RandomTriangularMatrix (F, n, n, uplo, diag, true, A, lda, Rand);
fassign (F, n, n, A, lda, B, lda); // copy of A
fassign (F, n, n, A, lda, C, lda); // copy of A
string ss=string((uplo == FflasLower)?"Lower_":"Upper_")+string((diag == FflasUnit)?"Unit":"NonUnit");
cout<<std::left<<"Checking FTRTRI_";
cout.fill('.');
cout.width(30);
cout<<ss;
// << endl;
Timer t; t.clear();
double time=0.0;
t.clear();
t.start();
ftrtri (F, uplo, diag, n, A, lda);
t.stop();
time+=t.usertime();
// B <- A times B
ftrmm(F, FFLAS::FflasRight, uplo, FFLAS::FflasNoTrans, diag, n, n, F.one, A, lda, B, lda);
// Is B the identity matrix ?
bool ok = true;
for(size_t li = 0; (li < n) && ok; li++){
for(size_t co = 0; (co < n) && ok; co++){
ok = ((li == co) && (F.areEqual(B[li*lda+co],F.one))) || (F.areEqual(B[li*lda+co],F.zero));
}
}
if (ok){
cout << "PASSED ("<<time<<")"<<endl;
} else{
//string file = "./mat.sage";
//WriteMatrix(file,F,n,n,C,lda,FFLAS::FflasSageMath);
cout << "FAILED ("<<time<<")"<<endl;
WriteMatrix(std::cout << "\nA" << std::endl, F,n,n,C,lda);
WriteMatrix(std::cout << "\nA^-1" << std::endl, F,n,n,A,lda);
}
fflas_delete(A);
fflas_delete(B);
return ok;
}
template <class Field>
bool run_with_field (Givaro::Integer q, size_t b, size_t n, size_t iters, uint64_t seed){
bool ok = true ;
int nbit=(int)iters;
while (ok && nbit){
//typedef typename Field::Element Element ;
// choose Field
Field* F= chooseField<Field>(q,b);
typename Field::RandIter G(*F,0,seed);
if (F==nullptr)
return true;
cout<<"Checking with ";F->write(cout)<<endl;
ok = ok && check_ftrtri(*F,n,FflasLower,FflasUnit,G);
ok = ok && check_ftrtri(*F,n,FflasUpper,FflasUnit,G);
ok = ok && check_ftrtri(*F,n,FflasLower,FflasNonUnit,G);
ok = ok && check_ftrtri(*F,n,FflasUpper,FflasNonUnit,G);
nbit--;
delete F;
}
if (!ok)
std::cout << "with seed = "<< seed << std::endl;
return ok;
}
int main(int argc, char** argv)
{
cerr<<setprecision(10);
Givaro::Integer q=-1;
size_t b=0;
size_t n=207;
size_t iters=3;
bool loop=false;
uint64_t seed = time(NULL);
Argument as[] = {
{ 'q', "-q Q", "Set the field characteristic (-1 for random).", TYPE_INTEGER , &q },
{ 'b', "-b B", "Set the bitsize of the field characteristic.", TYPE_INT , &b },
{ 'n', "-n N", "Set the dimension of the system.", TYPE_INT , &n },
{ 'i', "-i R", "Set number of repetitions.", TYPE_INT , &iters },
{ 'l', "-loop Y/N", "run the test in an infinite loop.", TYPE_BOOL , &loop },
{ 's', "-s seed", "Set seed for the random generator", TYPE_INT, &seed },
END_OF_ARGUMENTS
};
parseArguments(argc,argv,as);
bool ok = true;
do{
ok &= run_with_field<Modular<double> >(q,b,n,iters,seed);
ok &= run_with_field<ModularBalanced<double> >(q,b,n,iters,seed);
ok &= run_with_field<Modular<float> >(q,b,n,iters,seed);
ok &= run_with_field<ModularBalanced<float> >(q,b,n,iters,seed);
ok &= run_with_field<Modular<int32_t> >(q,b,n,iters,seed);
ok &= run_with_field<ModularBalanced<int32_t> >(q,b,n,iters,seed);
ok &= run_with_field<Modular<int64_t> >(q,b,n,iters,seed);
ok &= run_with_field<ModularBalanced<int64_t> >(q,b,n,iters,seed);
ok &= run_with_field<Modular<Givaro::Integer> >(q,5,n/4+1,iters,seed);
ok &= run_with_field<Modular<Givaro::Integer> >(q,(b?b:512),n/4+1,iters,seed);
} while (loop && ok);
return !ok ;
}
<|endoftext|> |
<commit_before>/*
* This file is open source software, licensed to you under the terms
* of the Apache License, Version 2.0 (the "License"). See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. You may not use this file except in compliance with the License.
*
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*
* Copyright (C) 2014 Cloudius Systems, Ltd.
*/
#pragma once
#include <boost/test/unit_test.hpp>
#include "core/future.hh"
#include "test_runner.hh"
namespace seastar {
class seastar_test {
public:
seastar_test();
virtual ~seastar_test() {}
virtual const char* get_test_file() = 0;
virtual const char* get_name() = 0;
virtual future<> run_test_case() = 0;
void run();
};
#define SEASTAR_TEST_CASE(name) \
struct name : public seastar_test { \
const char* get_test_file() override { return __FILE__; } \
const char* get_name() override { return #name; } \
future<> run_test_case() override; \
}; \
static name name ## _instance; \
future<> name::run_test_case()
#define SEASTAR_THREAD_TEST_CASE(name) \
struct name : public seastar_test { \
const char* get_test_file() override { return __FILE__; } \
const char* get_name() override { return #name; } \
future<> run_test_case() override { \
return async([this] { \
do_run_test_case(); \
}); \
} \
void do_run_test_case(); \
}; \
static name name ## _instance; \
void name::do_run_test_case() \
}
<commit_msg>tests: test-utils: Add missing include<commit_after>/*
* This file is open source software, licensed to you under the terms
* of the Apache License, Version 2.0 (the "License"). See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. You may not use this file except in compliance with the License.
*
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*
* Copyright (C) 2014 Cloudius Systems, Ltd.
*/
#pragma once
#include <boost/test/unit_test.hpp>
#include "core/future.hh"
#include "core/thread.hh"
#include "test_runner.hh"
namespace seastar {
class seastar_test {
public:
seastar_test();
virtual ~seastar_test() {}
virtual const char* get_test_file() = 0;
virtual const char* get_name() = 0;
virtual future<> run_test_case() = 0;
void run();
};
#define SEASTAR_TEST_CASE(name) \
struct name : public seastar_test { \
const char* get_test_file() override { return __FILE__; } \
const char* get_name() override { return #name; } \
future<> run_test_case() override; \
}; \
static name name ## _instance; \
future<> name::run_test_case()
#define SEASTAR_THREAD_TEST_CASE(name) \
struct name : public seastar_test { \
const char* get_test_file() override { return __FILE__; } \
const char* get_name() override { return #name; } \
future<> run_test_case() override { \
return async([this] { \
do_run_test_case(); \
}); \
} \
void do_run_test_case(); \
}; \
static name name ## _instance; \
void name::do_run_test_case() \
}
<|endoftext|> |
<commit_before>/***********************************************************************************************************************
**
** Copyright (c) 2011, 2014 ETH Zurich
** 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 ETH Zurich 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 "JavaDebugger.h"
#include "../run_support/java/JavaRunner.h"
#include "jdwp/messages/EventSet.h"
#include "jdwp/Location.h"
#include "ModelBase/src/nodes/Node.h"
#include "OOModel/src/declarations/Method.h"
#include "OOModel/src/declarations/Class.h"
#include "OOModel/src/declarations/Module.h"
#include "VisualizationBase/src/items/Item.h"
#include "VisualizationBase/src/overlays/OverlayAccessor.h"
#include "VisualizationBase/src/overlays/MessageOverlay.h"
namespace OODebug {
JavaDebugger& JavaDebugger::instance()
{
static JavaDebugger instance;
return instance;
}
void JavaDebugger::debugTree(Model::TreeManager* manager, const QString& pathToProjectContainerDirectory)
{
Model::Node* mainContainer = JavaRunner::runTree(manager, pathToProjectContainerDirectory, true);
// Find the class name where the main method is in.
auto mainClass = mainContainer->firstAncestorOfType<OOModel::Class>();
Q_ASSERT(mainClass);
QString mainClassName = fullNameFor(mainClass, '.');
debugConnector_.connect(mainClassName);
}
bool JavaDebugger::addBreakpoint(Visualization::Item* target, QKeyEvent* event)
{
if (event->modifiers() == Qt::NoModifier && (event->key() == Qt::Key_F8))
{
auto it = breakpoints_.find(target);
if (it != breakpoints_.end())
{
target->scene()->removeOverlay(it->overlay_);
if (debugConnector_.vmRunning() && it->requestId_ > 0)
debugConnector_.clearBreakpoint(it->requestId_);
breakpoints_.erase(it);
}
else
{
auto breakpoint = Breakpoint(addBreakpointOverlay(target));
if (debugConnector_.vmRunning())
breakpoint.requestId_ = debugConnector_.sendBreakpoint(nodeToLocation(target->node()));
breakpoints_[target] = breakpoint;
}
return true;
}
return false;
}
bool JavaDebugger::resume(Visualization::Item*, QKeyEvent* event)
{
if (event->modifiers() == Qt::NoModifier && (event->key() == Qt::Key_F6))
{
debugConnector_.resume();
return true;
}
return false;
}
JavaDebugger::JavaDebugger()
{
debugConnector_.addEventListener(Protocol::EventKind::CLASS_PREPARE, [this] (Event e) { handleClassPrepare(e);});
}
Visualization::MessageOverlay* JavaDebugger::addBreakpointOverlay(Visualization::Item* target)
{
// TODO: Use a custom overlay for breakpoints.
static const QString overlayGroupName("Breakpoint overlay");
auto scene = target->scene();
// TODO: QUESTION: overlayGroup could just create a group if there is none?
auto overlayGroup = scene->overlayGroup(overlayGroupName);
if (!overlayGroup) overlayGroup = scene->addOverlayGroup(overlayGroupName);
auto overlay = new Visualization::MessageOverlay(target,
[](Visualization::MessageOverlay *){
return QString("BP");
});
overlayGroup->addOverlay(makeOverlay(overlay));
return overlay;
}
QString JavaDebugger::jvmSignatureFor(OOModel::Class* theClass)
{
// from JNI spec fully qualified class: http://docs.oracle.com/javase/1.5.0/docs/guide/jni/spec/types.html#wp16432
QString signature = fullNameFor(theClass, '/');
signature.prepend("L").append(";");
return signature;
}
QString JavaDebugger::fullNameFor(OOModel::Class* theClass, QChar delimiter)
{
QString fullName = theClass->name();
auto module = theClass->firstAncestorOfType<OOModel::Module>();
while (module)
{
fullName.prepend(module->name() + delimiter);
module = module->firstAncestorOfType<OOModel::Module>();
}
return fullName;
}
Location JavaDebugger::nodeToLocation(Model::Node* node)
{
auto method = node->firstAncestorOfType<OOModel::Method>();
auto containerClass = method->firstAncestorOfType<OOModel::Class>();
qint64 classId = debugConnector_.getClassId(jvmSignatureFor(containerClass));
// TODO: function to get signature of a method: for Java classes we would need the full java library.
// Once fixed also fix the implementation of getMethodId().
qint64 methodId = debugConnector_.getMethodId(classId, method->name());
Q_ASSERT(methodId != -1);
auto tagKind = Protocol::TypeTagKind::CLASS;
if (containerClass->constructKind() == OOModel::Class::ConstructKind::Interface)
tagKind = Protocol::TypeTagKind::INTERFACE;
else if (containerClass->constructKind() != OOModel::Class::ConstructKind::Class)
Q_ASSERT(0); // This should not happen for a Java project!
// TODO: fix method index
return Location(tagKind, classId, methodId, 0);
}
void JavaDebugger::handleClassPrepare(Event)
{
for (auto it = breakpoints_.begin(); it != breakpoints_.end(); ++it)
{
auto target = it.key();
auto targetNode = target->node();
it.value().requestId_ = debugConnector_.sendBreakpoint(nodeToLocation(targetNode));
}
debugConnector_.resume();
}
} /* namespace OODebug */
<commit_msg>Remove a question<commit_after>/***********************************************************************************************************************
**
** Copyright (c) 2011, 2014 ETH Zurich
** 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 ETH Zurich 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 "JavaDebugger.h"
#include "../run_support/java/JavaRunner.h"
#include "jdwp/messages/EventSet.h"
#include "jdwp/Location.h"
#include "ModelBase/src/nodes/Node.h"
#include "OOModel/src/declarations/Method.h"
#include "OOModel/src/declarations/Class.h"
#include "OOModel/src/declarations/Module.h"
#include "VisualizationBase/src/items/Item.h"
#include "VisualizationBase/src/overlays/OverlayAccessor.h"
#include "VisualizationBase/src/overlays/MessageOverlay.h"
namespace OODebug {
JavaDebugger& JavaDebugger::instance()
{
static JavaDebugger instance;
return instance;
}
void JavaDebugger::debugTree(Model::TreeManager* manager, const QString& pathToProjectContainerDirectory)
{
Model::Node* mainContainer = JavaRunner::runTree(manager, pathToProjectContainerDirectory, true);
// Find the class name where the main method is in.
auto mainClass = mainContainer->firstAncestorOfType<OOModel::Class>();
Q_ASSERT(mainClass);
QString mainClassName = fullNameFor(mainClass, '.');
debugConnector_.connect(mainClassName);
}
bool JavaDebugger::addBreakpoint(Visualization::Item* target, QKeyEvent* event)
{
if (event->modifiers() == Qt::NoModifier && (event->key() == Qt::Key_F8))
{
auto it = breakpoints_.find(target);
if (it != breakpoints_.end())
{
target->scene()->removeOverlay(it->overlay_);
if (debugConnector_.vmRunning() && it->requestId_ > 0)
debugConnector_.clearBreakpoint(it->requestId_);
breakpoints_.erase(it);
}
else
{
auto breakpoint = Breakpoint(addBreakpointOverlay(target));
if (debugConnector_.vmRunning())
breakpoint.requestId_ = debugConnector_.sendBreakpoint(nodeToLocation(target->node()));
breakpoints_[target] = breakpoint;
}
return true;
}
return false;
}
bool JavaDebugger::resume(Visualization::Item*, QKeyEvent* event)
{
if (event->modifiers() == Qt::NoModifier && (event->key() == Qt::Key_F6))
{
debugConnector_.resume();
return true;
}
return false;
}
JavaDebugger::JavaDebugger()
{
debugConnector_.addEventListener(Protocol::EventKind::CLASS_PREPARE, [this] (Event e) { handleClassPrepare(e);});
}
Visualization::MessageOverlay* JavaDebugger::addBreakpointOverlay(Visualization::Item* target)
{
// TODO: Use a custom overlay for breakpoints.
static const QString overlayGroupName("Breakpoint overlay");
auto scene = target->scene();
auto overlayGroup = scene->overlayGroup(overlayGroupName);
if (!overlayGroup) overlayGroup = scene->addOverlayGroup(overlayGroupName);
auto overlay = new Visualization::MessageOverlay(target,
[](Visualization::MessageOverlay *){
return QString("BP");
});
overlayGroup->addOverlay(makeOverlay(overlay));
return overlay;
}
QString JavaDebugger::jvmSignatureFor(OOModel::Class* theClass)
{
// from JNI spec fully qualified class: http://docs.oracle.com/javase/1.5.0/docs/guide/jni/spec/types.html#wp16432
QString signature = fullNameFor(theClass, '/');
signature.prepend("L").append(";");
return signature;
}
QString JavaDebugger::fullNameFor(OOModel::Class* theClass, QChar delimiter)
{
QString fullName = theClass->name();
auto module = theClass->firstAncestorOfType<OOModel::Module>();
while (module)
{
fullName.prepend(module->name() + delimiter);
module = module->firstAncestorOfType<OOModel::Module>();
}
return fullName;
}
Location JavaDebugger::nodeToLocation(Model::Node* node)
{
auto method = node->firstAncestorOfType<OOModel::Method>();
auto containerClass = method->firstAncestorOfType<OOModel::Class>();
qint64 classId = debugConnector_.getClassId(jvmSignatureFor(containerClass));
// TODO: function to get signature of a method: for Java classes we would need the full java library.
// Once fixed also fix the implementation of getMethodId().
qint64 methodId = debugConnector_.getMethodId(classId, method->name());
Q_ASSERT(methodId != -1);
auto tagKind = Protocol::TypeTagKind::CLASS;
if (containerClass->constructKind() == OOModel::Class::ConstructKind::Interface)
tagKind = Protocol::TypeTagKind::INTERFACE;
else if (containerClass->constructKind() != OOModel::Class::ConstructKind::Class)
Q_ASSERT(0); // This should not happen for a Java project!
// TODO: fix method index
return Location(tagKind, classId, methodId, 0);
}
void JavaDebugger::handleClassPrepare(Event)
{
for (auto it = breakpoints_.begin(); it != breakpoints_.end(); ++it)
{
auto target = it.key();
auto targetNode = target->node();
it.value().requestId_ = debugConnector_.sendBreakpoint(nodeToLocation(targetNode));
}
debugConnector_.resume();
}
} /* namespace OODebug */
<|endoftext|> |
<commit_before><commit_msg>Cleaned up TODO list.<commit_after><|endoftext|> |
<commit_before>/* Copyright (C) 2019 Martin Albrecht
This file is part of fplll. fplll 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.
fplll 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 fplll. If not, see <http://www.gnu.org/licenses/>. */
#include <cstring>
#include <fplll/fplll.h>
using namespace fplll;
template <class FT> int test_enum(size_t d)
{
RandGen::init_with_seed(0x1337);
ZZ_mat<mpz_t> A = ZZ_mat<mpz_t>(100, 100);
A.gen_qary_withq(50, 7681);
lll_reduction(A);
ZZ_mat<mpz_t> U;
MatGSO<Z_NR<mpz_t>, FP_NR<FT>> M(A, U, U, 0);
M.update_gso();
FastEvaluator<FP_NR<FT>> evaluator;
Enumeration<Z_NR<mpz_t>, FP_NR<FT>> enum_obj(M, evaluator);
FP_NR<FT> max_dist;
M.get_r(max_dist, 0, 0);
max_dist *= 0.99;
enum_obj.enumerate(0, d, max_dist, 0);
if (evaluator.empty())
{
return 1;
}
else
{
return 0;
}
}
/**
@brief Test if list_CVP via enumeration function returns the correct amount of vectors
@return
*/
template <class FT>
int test_list_cvp()
{
ZZ_mat<mpz_t> u;
status |= read_file(A, "tests/lattices/example_list_cvp_in_lattice");
int status = lll_reduction(A);
if (status != RED_SUCCESS)
{
cerr << "LLL reduction failed: " << get_red_status_str(status) << endl;
return status;
}
// Search for up to 999999 vectors, up to radius 32.5 around the origin
// the right answer is 196561
FT rad = 32.5;
int right_answer = 196561;
// Tests with two targets: 0, and something very close to 0.
// HOLE: Not sure how to set that up
target = 0 ...
FastEvaluator<FP_NR<FT>> evaluator(999999);
Enumeration<Z_NR<mpz_t>, FP_NR<FT>> enum_obj(A.M, evaluator);
enum_obj.enumerate(0, d, max_dist, 0, target);
// HOLE: Not sure how to really count solutions
if (enum_obj.count_solution() != right_answer)
{
cerr << "list CVP failed, expected 196561 solutions, got : " << get_red_status_str(enum_obj.count_solution()) << endl;
return 1;
}
// HOLE: Not sure how to set that up
target = 0.001 ...
enum_obj.enumerate(0, d, max_dist, 0, target);
// HOLE: Not sure how to really count solutions
if (enum_obj.count_solution() != right_answer)
{
cerr << "list CVP failed, expected 196561 solutions, got : " << get_red_status_str(enum_obj.count_solution()) << endl;
return 1;
}
}
bool callback_firstf(size_t n, enumf *new_sol_coord, void *ctx)
{
if (new_sol_coord[0] == static_cast<double *>(ctx)[0])
{
return true;
}
return false;
}
template <class FT> int test_callback_enum(size_t d)
{
RandGen::init_with_seed(0x1337);
ZZ_mat<mpz_t> A = ZZ_mat<mpz_t>(100, 100);
A.gen_qary_withq(50, 7681);
lll_reduction(A);
ZZ_mat<mpz_t> U;
MatGSO<Z_NR<mpz_t>, FP_NR<FT>> M(A, U, U, 0);
M.update_gso();
enumf ctx = 2;
CallbackEvaluator<FP_NR<FT>> evaluator(callback_firstf, &ctx);
Enumeration<Z_NR<mpz_t>, FP_NR<FT>> enum_obj(M, evaluator);
FP_NR<FT> max_dist;
M.get_r(max_dist, 0, 0);
max_dist *= 0.99;
enum_obj.enumerate(0, d, max_dist, 0);
if (evaluator.empty())
{
return 1;
}
else
{
if (evaluator.begin()->second[0].get_si() == 2)
{
return 0;
}
else
{
return 1;
}
}
}
int main(int argc, char *argv[])
{
int status = 0;
status |= test_enum<double>(30);
status |= test_callback_enum<double>(40);
if (status == 0)
{
std::cerr << "All tests passed." << std::endl;
return 0;
}
else
{
return -1;
}
}
<commit_msg>test_enum.cpp work<commit_after>/* Copyright (C) 2019 Martin Albrecht
This file is part of fplll. fplll 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.
fplll 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 fplll. If not, see <http://www.gnu.org/licenses/>. */
#include <cstring>
#include <fplll/fplll.h>
#include <test_utils.h>
using namespace fplll;
template <class FT> int test_enum(size_t d)
{
RandGen::init_with_seed(0x1337);
ZZ_mat<mpz_t> A = ZZ_mat<mpz_t>(100, 100);
A.gen_qary_withq(50, 7681);
lll_reduction(A);
ZZ_mat<mpz_t> U;
MatGSO<Z_NR<mpz_t>, FP_NR<FT>> M(A, U, U, 0);
M.update_gso();
FastEvaluator<FP_NR<FT>> evaluator;
Enumeration<Z_NR<mpz_t>, FP_NR<FT>> enum_obj(M, evaluator);
FP_NR<FT> max_dist;
M.get_r(max_dist, 0, 0);
max_dist *= 0.99;
enum_obj.enumerate(0, d, max_dist, 0);
if (evaluator.empty())
{
return 1;
}
else
{
return 0;
}
}
/**
@brief Test if list_CVP via enumeration function returns the correct amount of vectors
@return
*/
template <class FT> int test_list_cvp()
{
ZZ_mat<mpz_t> u;
int status = 0;
ZZ_mat<mpz_t> A;
status |= read_file(A, "tests/lattices/example_list_cvp_in_lattice");
status |= lll_reduction(A);
if (status != RED_SUCCESS)
{
cerr << "LLL reduction failed: " << get_red_status_str(status) << endl;
return status;
}
// Search for up to 999999 vectors, up to radius 32.5 around the origin
// the right answer is 196561
FT rad = 32.5;
int right_answer = 196561;
// Tests with two targets: 0, and something very close to 0.
// HOLE: Not sure how to set that up
size_t d = A.get_rows();
std::vector<FP_NR<FT>> target(d);
ZZ_mat<mpz_t> empty_mat;
MatGSO<Z_NR<mpz_t>, FP_NR<mpfr_t>> gso(A, empty_mat, empty_mat, GSO_INT_GRAM);
FastEvaluator<FP_NR<FT>> evaluator(d, gso.get_mu_matrix(), gso.get_r_matrix(), EVALMODE_CV,
999999);
Enumeration<Z_NR<mpz_t>, FP_NR<FT>> enum_obj(gso, evaluator);
enum_obj.enumerate(0, d, rad, 0, target);
// HOLE: Not sure how to really count solutions
if (enum_obj.count_solution() != right_answer)
{
cerr << "list CVP failed, expected 196561 solutions, got : "
<< get_red_status_str(enum_obj.count_solution()) << endl;
return 1;
}
// HOLE: Not sure how to set that up
target.clear();
target.resize(d, 0.0001);
enum_obj.enumerate(0, d, rad, 0, target);
// HOLE: Not sure how to really count solutions
if (enum_obj.count_solution() != right_answer)
{
cerr << "list CVP failed, expected 196561 solutions, got : "
<< get_red_status_str(enum_obj.count_solution()) << endl;
return 1;
}
}
bool callback_firstf(size_t n, enumf *new_sol_coord, void *ctx)
{
if (new_sol_coord[0] == static_cast<double *>(ctx)[0])
{
return true;
}
return false;
}
template <class FT> int test_callback_enum(size_t d)
{
RandGen::init_with_seed(0x1337);
ZZ_mat<mpz_t> A = ZZ_mat<mpz_t>(100, 100);
A.gen_qary_withq(50, 7681);
lll_reduction(A);
ZZ_mat<mpz_t> U;
MatGSO<Z_NR<mpz_t>, FP_NR<FT>> M(A, U, U, 0);
M.update_gso();
enumf ctx = 2;
CallbackEvaluator<FP_NR<FT>> evaluator(callback_firstf, &ctx);
Enumeration<Z_NR<mpz_t>, FP_NR<FT>> enum_obj(M, evaluator);
FP_NR<FT> max_dist;
M.get_r(max_dist, 0, 0);
max_dist *= 0.99;
enum_obj.enumerate(0, d, max_dist, 0);
if (evaluator.empty())
{
return 1;
}
else
{
if (evaluator.begin()->second[0].get_si() == 2)
{
return 0;
}
else
{
return 1;
}
}
}
int main(int argc, char *argv[])
{
int status = 0;
status |= test_enum<double>(30);
status |= test_callback_enum<double>(40);
if (status == 0)
{
std::cerr << "All tests passed." << std::endl;
return 0;
}
else
{
return -1;
}
}
<|endoftext|> |
<commit_before>// REQUIRES: shell
// MSYS doesn't emulate umask.
// FIXME: Could we introduce another feature for it?
// REQUIRES: shell-preserves-root'
// RUN: umask 000
// RUN: %clang_cc1 -emit-llvm-bc %s -o %t
// RUN: ls -l %t | FileCheck --check-prefix=CHECK000 %s
// CHECK000: rw-rw-rw-
// RUN: umask 002
// RUN: %clang_cc1 -emit-llvm-bc %s -o %t
// RUN: ls -l %t | FileCheck --check-prefix=CHECK002 %s
// CHECK002: rw-rw-r--
<commit_msg>Fix typo in test's REQUIRES line<commit_after>// REQUIRES: shell
// MSYS doesn't emulate umask.
// FIXME: Could we introduce another feature for it?
// REQUIRES: shell-preserves-root
// RUN: umask 000
// RUN: %clang_cc1 -emit-llvm-bc %s -o %t
// RUN: ls -l %t | FileCheck --check-prefix=CHECK000 %s
// CHECK000: rw-rw-rw-
// RUN: umask 002
// RUN: %clang_cc1 -emit-llvm-bc %s -o %t
// RUN: ls -l %t | FileCheck --check-prefix=CHECK002 %s
// CHECK002: rw-rw-r--
<|endoftext|> |
<commit_before>// Copyright 2013 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Author: jdtang@google.com (Jonathan Tang)
#include "test_utils.h"
#include "error.h"
#include "util.h"
int GetChildCount(GumboNode* node) {
if (node->type == GUMBO_NODE_DOCUMENT) {
return node->v.document.children.length;
} else {
return node->v.element.children.length;
}
}
GumboTag GetTag(GumboNode* node) {
return node->v.element.tag;
}
GumboNode* GetChild(GumboNode* parent, int index) {
if (parent->type == GUMBO_NODE_DOCUMENT) {
return static_cast<GumboNode*>(parent->v.document.children.data[index]);
} else {
return static_cast<GumboNode*>(parent->v.element.children.data[index]);
}
}
int GetAttributeCount(GumboNode* node) {
return node->v.element.attributes.length;
}
GumboAttribute* GetAttribute(GumboNode* node, int index) {
return static_cast<GumboAttribute*>(node->v.element.attributes.data[index]);
}
// Convenience function to do some basic assertions on the structure of the
// document (nodes are elements, nodes have the right tags) and then return
// the body node.
void GetAndAssertBody(GumboNode* root, GumboNode** body) {
GumboNode* html = NULL;
for (int i = 0; i < GetChildCount(root); ++i) {
GumboNode* child = GetChild(root, i);
if (child->type != GUMBO_NODE_ELEMENT) {
ASSERT_EQ(GUMBO_NODE_COMMENT, child->type);
continue;
}
ASSERT_TRUE(html == NULL);
html = child;
}
ASSERT_TRUE(html != NULL);
ASSERT_EQ(GUMBO_NODE_ELEMENT, html->type);
EXPECT_EQ(GUMBO_TAG_HTML, GetTag(html));
// There may be comment/whitespace nodes; this walks through the children of
// <html> and assigns head/body based on them, or assert-fails if there are
// fewer/more than 2 such nodes.
GumboNode* head = NULL;
*body = NULL;
for (int i = 0; i < GetChildCount(html); ++i) {
GumboNode* child = GetChild(html, i);
if (child->type != GUMBO_NODE_ELEMENT) {
continue;
}
if (!head) {
head = child;
EXPECT_EQ(GUMBO_TAG_HEAD, GetTag(head));
} else if (!(*body)) {
*body = child;
EXPECT_EQ(GUMBO_TAG_BODY, GetTag(*body));
} else {
ASSERT_TRUE("More than two elements found inside <html>" != NULL);
}
}
EXPECT_TRUE(head != NULL);
ASSERT_TRUE(*body != NULL);
}
void SanityCheckPointers(const char* input, size_t input_length,
const GumboNode* node, int depth) {
ASSERT_GE(input_length, (size_t) 0);
ASSERT_TRUE(node != NULL);
// There are some truly pathological HTML documents out there - the
// integration tests for this include one where the DOM "tree" is actually a
// linked list 27,500 nodes deep - and so we need a limit on the recursion
// depth here to avoid blowing the stack. Alternatively, we could externalize
// the stack and use an iterative algorithm, but that gets us very little for
// the additional programming complexity.
if (node->type == GUMBO_NODE_DOCUMENT || depth > 500) {
// Don't sanity-check the document as well...we start with the root.
return;
}
if (node->type == GUMBO_NODE_ELEMENT) {
const GumboElement* element = &node->v.element;
// Sanity checks on original* pointers, making sure they fall within the
// original input.
if (element->original_tag.data && element->original_tag.length) {
EXPECT_GE(element->original_tag.data, input);
EXPECT_LT(element->original_tag.data, input + input_length);
EXPECT_LE(element->original_tag.length, input_length);
}
if (element->original_end_tag.data && element->original_tag.length) {
EXPECT_GE(element->original_end_tag.data, input);
EXPECT_LT(element->original_end_tag.data, input + input_length);
EXPECT_LE(element->original_end_tag.length, input_length);
}
EXPECT_GE(element->start_pos.offset, 0);
EXPECT_LE(element->start_pos.offset, input_length);
EXPECT_GE(element->end_pos.offset, 0);
EXPECT_LE(element->end_pos.offset, input_length);
const GumboVector* children = &element->children;
for (int i = 0; i < children->length; ++i) {
const GumboNode* child = static_cast<const GumboNode*>(children->data[i]);
// Checks on parent/child links.
ASSERT_TRUE(child != NULL);
EXPECT_EQ(node, child->parent);
EXPECT_EQ(i, child->index_within_parent);
SanityCheckPointers(input, input_length, child, depth + 1);
}
} else {
const GumboText* text = &node->v.text;
EXPECT_GE(text->original_text.data, input);
EXPECT_LT(text->original_text.data, input + input_length);
EXPECT_LE(text->original_text.length, input_length);
EXPECT_GE(text->start_pos.offset, 0);
EXPECT_LT(text->start_pos.offset, input_length);
}
}
// Custom allocator machinery to sanity check for memory leaks. Normally we can
// use heapcheck/valgrind/ASAN for this, but they only give the
// results when the program terminates. This means that if the parser is run in
// a loop (say, a MapReduce) and there's a leak, it may end up exhausting memory
// before it can catch the particular document responsible for the leak. These
// allocators let us check each document individually for leaks.
static void* LeakDetectingMalloc(void* userdata, size_t size) {
MallocStats* stats = static_cast<MallocStats*>(userdata);
stats->bytes_allocated += size;
++stats->objects_allocated;
// Arbitrary limit of 2G on allocation; parsing any reasonable document
// shouldn't take more than that.
assert(stats->bytes_allocated < (1 << 31));
void* obj = malloc(size);
// gumbo_debug("Allocated %u bytes at %x.\n", size, obj);
return obj;
}
static void LeakDetectingFree(void* userdata, void* ptr) {
MallocStats* stats = static_cast<MallocStats*>(userdata);
if (ptr) {
++stats->objects_freed;
// gumbo_debug("Freed %x.\n");
free(ptr);
}
}
void InitLeakDetection(GumboOptions* options, MallocStats* stats) {
stats->bytes_allocated = 0;
stats->objects_allocated = 0;
stats->objects_freed = 0;
options->allocator = LeakDetectingMalloc;
options->deallocator = LeakDetectingFree;
options->userdata = stats;
}
GumboTest::GumboTest() :
options_(kGumboDefaultOptions),
errors_are_expected_(false),
text_("") {
InitLeakDetection(&options_, &malloc_stats_);
options_.max_errors = 100;
parser_._options = &options_;
parser_._output = static_cast<GumboOutput*>(
gumbo_parser_allocate(&parser_, sizeof(GumboOutput)));
gumbo_init_errors(&parser_);
}
GumboTest::~GumboTest() {
if (!errors_are_expected_) {
// TODO(jdtang): A googlemock matcher may be a more appropriate solution for
// this; we only want to pretty-print errors that are not an expected
// output of the test.
for (int i = 0; i < parser_._output->errors.length && i < 1; ++i) {
gumbo_print_caret_diagnostic(
&parser_, static_cast<GumboError*>(
parser_._output->errors.data[i]), text_);
}
}
gumbo_destroy_errors(&parser_);
gumbo_parser_deallocate(&parser_, parser_._output);
EXPECT_EQ(malloc_stats_.objects_allocated, malloc_stats_.objects_freed);
}
<commit_msg>Drop down the recursion limit on SanityCheckParentPointers.<commit_after>// Copyright 2013 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Author: jdtang@google.com (Jonathan Tang)
#include "test_utils.h"
#include "error.h"
#include "util.h"
int GetChildCount(GumboNode* node) {
if (node->type == GUMBO_NODE_DOCUMENT) {
return node->v.document.children.length;
} else {
return node->v.element.children.length;
}
}
GumboTag GetTag(GumboNode* node) {
return node->v.element.tag;
}
GumboNode* GetChild(GumboNode* parent, int index) {
if (parent->type == GUMBO_NODE_DOCUMENT) {
return static_cast<GumboNode*>(parent->v.document.children.data[index]);
} else {
return static_cast<GumboNode*>(parent->v.element.children.data[index]);
}
}
int GetAttributeCount(GumboNode* node) {
return node->v.element.attributes.length;
}
GumboAttribute* GetAttribute(GumboNode* node, int index) {
return static_cast<GumboAttribute*>(node->v.element.attributes.data[index]);
}
// Convenience function to do some basic assertions on the structure of the
// document (nodes are elements, nodes have the right tags) and then return
// the body node.
void GetAndAssertBody(GumboNode* root, GumboNode** body) {
GumboNode* html = NULL;
for (int i = 0; i < GetChildCount(root); ++i) {
GumboNode* child = GetChild(root, i);
if (child->type != GUMBO_NODE_ELEMENT) {
ASSERT_EQ(GUMBO_NODE_COMMENT, child->type);
continue;
}
ASSERT_TRUE(html == NULL);
html = child;
}
ASSERT_TRUE(html != NULL);
ASSERT_EQ(GUMBO_NODE_ELEMENT, html->type);
EXPECT_EQ(GUMBO_TAG_HTML, GetTag(html));
// There may be comment/whitespace nodes; this walks through the children of
// <html> and assigns head/body based on them, or assert-fails if there are
// fewer/more than 2 such nodes.
GumboNode* head = NULL;
*body = NULL;
for (int i = 0; i < GetChildCount(html); ++i) {
GumboNode* child = GetChild(html, i);
if (child->type != GUMBO_NODE_ELEMENT) {
continue;
}
if (!head) {
head = child;
EXPECT_EQ(GUMBO_TAG_HEAD, GetTag(head));
} else if (!(*body)) {
*body = child;
EXPECT_EQ(GUMBO_TAG_BODY, GetTag(*body));
} else {
ASSERT_TRUE("More than two elements found inside <html>" != NULL);
}
}
EXPECT_TRUE(head != NULL);
ASSERT_TRUE(*body != NULL);
}
void SanityCheckPointers(const char* input, size_t input_length,
const GumboNode* node, int depth) {
ASSERT_GE(input_length, (size_t) 0);
ASSERT_TRUE(node != NULL);
// There are some truly pathological HTML documents out there - the
// integration tests for this include one where the DOM "tree" is actually a
// linked list 27,500 nodes deep - and so we need a limit on the recursion
// depth here to avoid blowing the stack. Alternatively, we could externalize
// the stack and use an iterative algorithm, but that gets us very little for
// the additional programming complexity.
if (node->type == GUMBO_NODE_DOCUMENT || depth > 400) {
// Don't sanity-check the document as well...we start with the root.
return;
}
if (node->type == GUMBO_NODE_ELEMENT) {
const GumboElement* element = &node->v.element;
// Sanity checks on original* pointers, making sure they fall within the
// original input.
if (element->original_tag.data && element->original_tag.length) {
EXPECT_GE(element->original_tag.data, input);
EXPECT_LT(element->original_tag.data, input + input_length);
EXPECT_LE(element->original_tag.length, input_length);
}
if (element->original_end_tag.data && element->original_tag.length) {
EXPECT_GE(element->original_end_tag.data, input);
EXPECT_LT(element->original_end_tag.data, input + input_length);
EXPECT_LE(element->original_end_tag.length, input_length);
}
EXPECT_GE(element->start_pos.offset, 0);
EXPECT_LE(element->start_pos.offset, input_length);
EXPECT_GE(element->end_pos.offset, 0);
EXPECT_LE(element->end_pos.offset, input_length);
const GumboVector* children = &element->children;
for (int i = 0; i < children->length; ++i) {
const GumboNode* child = static_cast<const GumboNode*>(children->data[i]);
// Checks on parent/child links.
ASSERT_TRUE(child != NULL);
EXPECT_EQ(node, child->parent);
EXPECT_EQ(i, child->index_within_parent);
SanityCheckPointers(input, input_length, child, depth + 1);
}
} else {
const GumboText* text = &node->v.text;
EXPECT_GE(text->original_text.data, input);
EXPECT_LT(text->original_text.data, input + input_length);
EXPECT_LE(text->original_text.length, input_length);
EXPECT_GE(text->start_pos.offset, 0);
EXPECT_LT(text->start_pos.offset, input_length);
}
}
// Custom allocator machinery to sanity check for memory leaks. Normally we can
// use heapcheck/valgrind/ASAN for this, but they only give the
// results when the program terminates. This means that if the parser is run in
// a loop (say, a MapReduce) and there's a leak, it may end up exhausting memory
// before it can catch the particular document responsible for the leak. These
// allocators let us check each document individually for leaks.
static void* LeakDetectingMalloc(void* userdata, size_t size) {
MallocStats* stats = static_cast<MallocStats*>(userdata);
stats->bytes_allocated += size;
++stats->objects_allocated;
// Arbitrary limit of 2G on allocation; parsing any reasonable document
// shouldn't take more than that.
assert(stats->bytes_allocated < (1 << 31));
void* obj = malloc(size);
// gumbo_debug("Allocated %u bytes at %x.\n", size, obj);
return obj;
}
static void LeakDetectingFree(void* userdata, void* ptr) {
MallocStats* stats = static_cast<MallocStats*>(userdata);
if (ptr) {
++stats->objects_freed;
// gumbo_debug("Freed %x.\n");
free(ptr);
}
}
void InitLeakDetection(GumboOptions* options, MallocStats* stats) {
stats->bytes_allocated = 0;
stats->objects_allocated = 0;
stats->objects_freed = 0;
options->allocator = LeakDetectingMalloc;
options->deallocator = LeakDetectingFree;
options->userdata = stats;
}
GumboTest::GumboTest() :
options_(kGumboDefaultOptions),
errors_are_expected_(false),
text_("") {
InitLeakDetection(&options_, &malloc_stats_);
options_.max_errors = 100;
parser_._options = &options_;
parser_._output = static_cast<GumboOutput*>(
gumbo_parser_allocate(&parser_, sizeof(GumboOutput)));
gumbo_init_errors(&parser_);
}
GumboTest::~GumboTest() {
if (!errors_are_expected_) {
// TODO(jdtang): A googlemock matcher may be a more appropriate solution for
// this; we only want to pretty-print errors that are not an expected
// output of the test.
for (int i = 0; i < parser_._output->errors.length && i < 1; ++i) {
gumbo_print_caret_diagnostic(
&parser_, static_cast<GumboError*>(
parser_._output->errors.data[i]), text_);
}
}
gumbo_destroy_errors(&parser_);
gumbo_parser_deallocate(&parser_, parser_._output);
EXPECT_EQ(malloc_stats_.objects_allocated, malloc_stats_.objects_freed);
}
<|endoftext|> |
<commit_before>#include "parsertests.h"
#include "handlermacros.h"
#include "yaml-cpp/yaml.h"
#include <iostream>
namespace Test
{
namespace Parser {
TEST NoEndOfMapFlow()
{
try {
HANDLE("---{header: {id: 1");
} catch(const YAML::ParserException& e) {
YAML_ASSERT(e.msg == std::string(YAML::ErrorMsg::END_OF_MAP_FLOW));
return true;
}
return " no exception caught";
}
}
namespace {
void RunParserTest(TEST (*test)(), const std::string& name, int& passed, int& total) {
TEST ret;
try {
ret = test();
} catch(const YAML::Exception& e) {
ret.ok = false;
ret.error = std::string(" Exception caught: ") + e.what();
}
if(!ret.ok) {
std::cout << "Parser test failed: " << name << "\n";
std::cout << ret.error << "\n";
}
if(ret.ok)
passed++;
total++;
}
}
bool RunParserTests()
{
int passed = 0;
int total = 0;
RunParserTest(&Parser::NoEndOfMapFlow, "No end of map flow", passed, total);
std::cout << "Parser tests: " << passed << "/" << total << " passed\n";
return passed == total;
}
}
<commit_msg>Added failing test for parsing a ? at the start of a value<commit_after>#include "parsertests.h"
#include "handlermacros.h"
#include "yaml-cpp/yaml.h"
#include <iostream>
namespace Test
{
namespace Parser {
TEST NoEndOfMapFlow()
{
try {
HANDLE("---{header: {id: 1");
} catch(const YAML::ParserException& e) {
YAML_ASSERT(e.msg == std::string(YAML::ErrorMsg::END_OF_MAP_FLOW));
return true;
}
return " no exception caught";
}
TEST PlainScalarStartingWithQuestionMark()
{
HANDLE("foo: ?bar");
EXPECT_DOC_START();
EXPECT_MAP_START("?", 0);
EXPECT_SCALAR("?", 0, "foo");
EXPECT_SCALAR("?", 0, "?bar");
EXPECT_MAP_END();
EXPECT_DOC_END();
DONE();
}
}
namespace {
void RunParserTest(TEST (*test)(), const std::string& name, int& passed, int& total) {
TEST ret;
try {
ret = test();
} catch(const YAML::Exception& e) {
ret.ok = false;
ret.error = std::string(" Exception caught: ") + e.what();
}
if(!ret.ok) {
std::cout << "Parser test failed: " << name << "\n";
std::cout << ret.error << "\n";
}
if(ret.ok)
passed++;
total++;
}
}
bool RunParserTests()
{
int passed = 0;
int total = 0;
RunParserTest(&Parser::NoEndOfMapFlow, "No end of map flow", passed, total);
RunParserTest(&Parser::PlainScalarStartingWithQuestionMark, "Plain scalar starting with question mark", passed, total);
std::cout << "Parser tests: " << passed << "/" << total << " passed\n";
return passed == total;
}
}
<|endoftext|> |
<commit_before>#include <se306Project/sheepdog.h>
const static double MIN_SCAN_ANGLE_RAD = -10.0/180*M_PI;
const static double MAX_SCAN_ANGLE_RAD = +10.0/180*M_PI;
const static float PROXIMITY_RANGE_M = 5;
const static double FORWARD_SPEED_MPS = 1;
const static double ROTATE_SPEED_RADPS = M_PI;
float prevclosestRange = 0;
double linear_x;
double angular_z;
//pose of the robot
double px;
double py;
double tz;
double theta;
double prevpx;
double prevpy;
bool isRotate;
int sheepNum = 0;
int checkcount = 0;
enum FSM {FSM_MOVE_FORWARD, FSM_ROTATE};
ros::Publisher commandPub; // Publisher to the simulated robot's velocity command topic
ros::Publisher sheepdogPosPub;
ros::Subscriber laserSub; // Subscriber to the simulated robot's laser scan topic
enum FSM fsm; // Finite state machine for the random walk algorithm
ros::Time rotateStartTime; // Start time of the rotation
ros::Time rotateEndTime;
ros::Duration rotateDuration; // Duration of the rotation
ros::Subscriber StageOdo_sub;
laser_geometry::LaserProjection projector_;
ros::Publisher point_cloud_publisher_;
sheepdogNode::sheepdogNode(int number) {
sheepNum = number;
}
void sheepdogNode::StageOdom_callback(nav_msgs::Odometry msg)
{
//This is the call back function to process odometry messages coming from Stage.
px = 5 + msg.pose.pose.position.x;
py = 5 + msg.pose.pose.position.y;
tz = tz + msg.twist.twist.angular.z;
//printf("%f",px);
// If the current position is the same the previous position, then the robot is stuck and needs to move around
if ((px == prevpx) && (py == prevpy)) {
//msg.pose.pose.position.x = 5;
//ROS_INFO("Prevpx: %f",prevpx);
// Note the negative linear_x
//linear_x=-0.2;
//angular_z=1;
//theta=10;
//px = 5;
//py= 5;
//printf("Robot stuck");
if (!isRotate) {
ROS_INFO("Sheepdog stuck");
double r2 = (double)rand()/((double)RAND_MAX/(M_PI/2));
double m2 = (double)rand()/((double)RAND_MAX/0.5);
move(-m2, r2);
}
} else {
// One the robot becomes unstuck, then it moves around again normally
//linear_x = 0.2;
//angular_z = 0.2;
//ROS_INFO("Robot unstuck");
//checkcount=0;
}
ROS_INFO("Sheepdog -- Current x position is: %f", px);
ROS_INFO("Sheepdog -- Current y position is: %f", py);
ROS_INFO("Sheepdog -- Current z position is: %f", tz);
ROS_INFO("Sheepdog -- Current sheepNum is: %d", sheepNum);
prevpx = px;
prevpy = py;
}
// Send a velocity command
void sheepdogNode::move(double linearVelMPS, double angularVelRadPS) {
geometry_msgs::Twist msg; // The default constructor will set all commands to 0
msg.linear.x = linearVelMPS;
msg.angular.z = angularVelRadPS;
commandPub.publish(msg);
}
// Process the incoming laser scan message
void sheepdogNode::commandCallback(const sensor_msgs::LaserScan::ConstPtr& msg) {
sensor_msgs::PointCloud cloud;
projector_.transformLaserScanToPointCloud("robot_1/base_link", *msg, cloud, tfListener_);
point_cloud_publisher_.publish(cloud);
if (fsm == FSM_MOVE_FORWARD) {
// Compute the average range value between MIN_SCAN_ANGLE and MAX_SCAN_ANGLE
//
// NOTE: ideally, the following loop should have additional checks to ensure
// that indices are not out of bounds, by computing:
//
//- currAngle = msg->angle_min + msg->angle_increment*currIndex
//
// and then ensuring that currAngle <= msg->angle_max
unsigned int minIndex = ceil((MIN_SCAN_ANGLE_RAD - msg->angle_min) / msg->angle_increment);
unsigned int maxIndex = ceil((MAX_SCAN_ANGLE_RAD - msg->angle_min) / msg->angle_increment);
float closestRange = msg->ranges[minIndex];
for (unsigned int currIndex = minIndex + 1; currIndex < maxIndex; currIndex++) {
if (msg->ranges[currIndex] < closestRange) {
closestRange = msg->ranges[currIndex];
}
}
//if (closestRange == prevclosestRange) {
// ROS_INFO_STREAM("STUCK");
// move(-FORWARD_SPEED_MPS, ROTATE_SPEED_RADPS);
// //move(0, ROTATE_SPEED_RADPS);
//} else {
//ROS_INFO_STREAM("Range: " << closestRange);
prevclosestRange = closestRange;
if (closestRange > 20) {
fsm=FSM_ROTATE;
rotateStartTime=ros::Time::now();
rotateDuration=ros::Duration(0.001);
//fsm= FSM_MOVE_FORWARD;
}
//}
}
}
// Process the incoming sheep position messages
void sheepdogNode::chaseSheepCallback(geometry_msgs::Pose2D msg) {
if (fsm == FSM_MOVE_FORWARD) {
}
}
// Main FSM loop for ensuring that ROS messages are
// processed in a timely manner, and also for sending
// velocity controls to the simulated robot based on the FSM state
void sheepdogNode::spin() {
ros::Rate rate(10); // Specify the FSM loop rate in Hz
while (ros::ok()) { // Keep spinning loop until user presses Ctrl+C
geometry_msgs::Pose2D msg;
msg.x = px;
msg.y = py;
msg.theta = tz;
//ROS_INFO("%s", msg.data.c_str());
if (fsm == FSM_MOVE_FORWARD) {
//ROS_INFO_STREAM("Start forward");
move(FORWARD_SPEED_MPS, 0);
checkcount++;
if (checkcount > 3) {
isRotate=false;
}
}
if (fsm == FSM_ROTATE) {
//ROS_INFO_STREAM("Start rotate");
move(0, ROTATE_SPEED_RADPS);
rotateEndTime=ros::Time::now();
isRotate=true;
//ROS_INFO_STREAM("Time: " << rotateEndTime);
if ((rotateEndTime - rotateStartTime) > rotateDuration) {
fsm=FSM_MOVE_FORWARD;
//ROS_INFO_STREAM("End rotate");
checkcount=0;
}
}
sheepdogPosPub.publish(msg);
ros::spinOnce(); // Need to call this function often to allow ROS to process incoming messages
rate.sleep(); // Sleep for the rest of the cycle, to enforce the FSM loop rate
}
}
void sheepdogNode::rosSetup(int argc, char **argv) {
ros::init(argc, argv, "Sheepdog"); // Initiate new ROS node named "Sheepdog"
ros::NodeHandle nh;
tf::TransformListener tfListener_;
ROS_INFO("This node is: Sheepdog");
fsm = FSM(FSM_MOVE_FORWARD);
// Initialize random time generator
srand(time(NULL));
// Advertise a new publisher for the simulated robot's velocity command topic
// (the second argument indicates that if multiple command messages are in
// the queue to be sent, only the last command will be sent)
std::string sheepPosSubs [sheepNum];
std::ostringstream buffer;
for(int i = 0; i < sheepNum; i++){
buffer << i;
nh.subscribe<geometry_msgs::Pose2D>("sheep_" + buffer.str() + "/pose", 1000, &sheepdogNode::chaseSheepCallback, this);
}
commandPub = nh.advertise<geometry_msgs::Twist>("robot_1/cmd_vel",1000);
sheepdogPosPub = nh.advertise<geometry_msgs::Pose2D>("sheepdog_position",1000);
// Subscribe to the simulated robot's laser scan topic and tell ROS to call
// this->commandCallback() whenever a new message is published on that topic
laserSub = nh.subscribe<sensor_msgs::LaserScan>("robot_1/base_scan", 1000, &sheepdogNode::commandCallback, this);
StageOdo_sub = nh.subscribe<nav_msgs::Odometry>("robot_1/odom",1000, &sheepdogNode::StageOdom_callback,this);
point_cloud_publisher_ = nh.advertise<sensor_msgs::PointCloud> ("/camera", 1000, false);
tfListener_.setExtrapolationLimit(ros::Duration(0.1));
prevpx = 5;
prevpx= 5;
this->spin();
}
<commit_msg>Sorry. THIS is the fixed sheepdog. Should fix up stage issues.<commit_after>#include <se306Project/sheepdog.h>
const static double MIN_SCAN_ANGLE_RAD = -10.0/180*M_PI;
const static double MAX_SCAN_ANGLE_RAD = +10.0/180*M_PI;
const static float PROXIMITY_RANGE_M = 5;
const static double FORWARD_SPEED_MPS = 1;
const static double ROTATE_SPEED_RADPS = M_PI;
float prevclosestRange = 0;
double linear_x;
double angular_z;
//pose of the robot
double px;
double py;
double tz;
double theta;
double prevpx;
double prevpy;
bool isRotate;
int sheepNum = 0;
int checkcount = 0;
enum FSM {FSM_MOVE_FORWARD, FSM_ROTATE};
ros::Publisher commandPub; // Publisher to the simulated robot's velocity command topic
ros::Publisher sheepdogPosPub;
ros::Subscriber laserSub; // Subscriber to the simulated robot's laser scan topic
enum FSM fsm; // Finite state machine for the random walk algorithm
ros::Time rotateStartTime; // Start time of the rotation
ros::Time rotateEndTime;
ros::Duration rotateDuration; // Duration of the rotation
ros::Subscriber StageOdo_sub;
laser_geometry::LaserProjection projector_;
ros::Publisher point_cloud_publisher_;
sheepdogNode::sheepdogNode(int number) {
sheepNum = number;
}
void sheepdogNode::StageOdom_callback(nav_msgs::Odometry msg)
{
//This is the call back function to process odometry messages coming from Stage.
px = 5 + msg.pose.pose.position.x;
py = 5 + msg.pose.pose.position.y;
tz = tz + msg.twist.twist.angular.z;
//printf("%f",px);
// If the current position is the same the previous position, then the robot is stuck and needs to move around
if ((px == prevpx) && (py == prevpy)) {
//msg.pose.pose.position.x = 5;
//ROS_INFO("Prevpx: %f",prevpx);
// Note the negative linear_x
//linear_x=-0.2;
//angular_z=1;
//theta=10;
//px = 5;
//py= 5;
//printf("Robot stuck");
if (!isRotate) {
ROS_INFO("Sheepdog stuck");
double r2 = (double)rand()/((double)RAND_MAX/(M_PI/2));
double m2 = (double)rand()/((double)RAND_MAX/0.5);
move(-m2, r2);
}
} else {
// One the robot becomes unstuck, then it moves around again normally
//linear_x = 0.2;
//angular_z = 0.2;
//ROS_INFO("Robot unstuck");
//checkcount=0;
}
ROS_INFO("Sheepdog -- Current x position is: %f", px);
ROS_INFO("Sheepdog -- Current y position is: %f", py);
ROS_INFO("Sheepdog -- Current z position is: %f", tz);
ROS_INFO("Sheepdog -- Current sheepNum is: %d", sheepNum);
prevpx = px;
prevpy = py;
}
// Send a velocity command
void sheepdogNode::move(double linearVelMPS, double angularVelRadPS) {
geometry_msgs::Twist msg; // The default constructor will set all commands to 0
msg.linear.x = linearVelMPS;
msg.angular.z = angularVelRadPS;
commandPub.publish(msg);
}
// Process the incoming laser scan message
void sheepdogNode::commandCallback(const sensor_msgs::LaserScan::ConstPtr& msg) {
sensor_msgs::PointCloud cloud;
//projector_.transformLaserScanToPointCloud("robot_1/base_link", *msg, cloud, tfListener_);
point_cloud_publisher_.publish(cloud);
if (fsm == FSM_MOVE_FORWARD) {
// Compute the average range value between MIN_SCAN_ANGLE and MAX_SCAN_ANGLE
//
// NOTE: ideally, the following loop should have additional checks to ensure
// that indices are not out of bounds, by computing:
//
//- currAngle = msg->angle_min + msg->angle_increment*currIndex
//
// and then ensuring that currAngle <= msg->angle_max
unsigned int minIndex = ceil((MIN_SCAN_ANGLE_RAD - msg->angle_min) / msg->angle_increment);
unsigned int maxIndex = ceil((MAX_SCAN_ANGLE_RAD - msg->angle_min) / msg->angle_increment);
float closestRange = msg->ranges[minIndex];
for (unsigned int currIndex = minIndex + 1; currIndex < maxIndex; currIndex++) {
if (msg->ranges[currIndex] < closestRange) {
closestRange = msg->ranges[currIndex];
}
}
//if (closestRange == prevclosestRange) {
// ROS_INFO_STREAM("STUCK");
// move(-FORWARD_SPEED_MPS, ROTATE_SPEED_RADPS);
// //move(0, ROTATE_SPEED_RADPS);
//} else {
//ROS_INFO_STREAM("Range: " << closestRange);
prevclosestRange = closestRange;
if (closestRange > 20) {
fsm=FSM_ROTATE;
rotateStartTime=ros::Time::now();
rotateDuration=ros::Duration(0.001);
//fsm= FSM_MOVE_FORWARD;
}
//}
}
}
// Process the incoming sheep position messages
void sheepdogNode::chaseSheepCallback(geometry_msgs::Pose2D msg) {
if (fsm == FSM_MOVE_FORWARD) {
}
}
// Main FSM loop for ensuring that ROS messages are
// processed in a timely manner, and also for sending
// velocity controls to the simulated robot based on the FSM state
void sheepdogNode::spin() {
ros::Rate rate(10); // Specify the FSM loop rate in Hz
while (ros::ok()) { // Keep spinning loop until user presses Ctrl+C
geometry_msgs::Pose2D msg;
msg.x = px;
msg.y = py;
msg.theta = tz;
//ROS_INFO("%s", msg.data.c_str());
if (fsm == FSM_MOVE_FORWARD) {
//ROS_INFO_STREAM("Start forward");
move(FORWARD_SPEED_MPS, 0);
checkcount++;
if (checkcount > 3) {
isRotate=false;
}
}
if (fsm == FSM_ROTATE) {
//ROS_INFO_STREAM("Start rotate");
move(0, ROTATE_SPEED_RADPS);
rotateEndTime=ros::Time::now();
isRotate=true;
//ROS_INFO_STREAM("Time: " << rotateEndTime);
if ((rotateEndTime - rotateStartTime) > rotateDuration) {
fsm=FSM_MOVE_FORWARD;
//ROS_INFO_STREAM("End rotate");
checkcount=0;
}
}
sheepdogPosPub.publish(msg);
ros::spinOnce(); // Need to call this function often to allow ROS to process incoming messages
rate.sleep(); // Sleep for the rest of the cycle, to enforce the FSM loop rate
}
}
void sheepdogNode::rosSetup(int argc, char **argv) {
ros::init(argc, argv, "Sheepdog"); // Initiate new ROS node named "Sheepdog"
ros::NodeHandle nh;
tf::TransformListener tfListener_;
ROS_INFO("This node is: Sheepdog");
fsm = FSM(FSM_MOVE_FORWARD);
// Initialize random time generator
srand(time(NULL));
// Advertise a new publisher for the simulated robot's velocity command topic
// (the second argument indicates that if multiple command messages are in
// the queue to be sent, only the last command will be sent)
std::string sheepPosSubs [sheepNum];
std::ostringstream buffer;
for(int i = 0; i < sheepNum; i++){
buffer << i;
nh.subscribe<geometry_msgs::Pose2D>("sheep_" + buffer.str() + "/pose", 1000, &sheepdogNode::chaseSheepCallback, this);
}
commandPub = nh.advertise<geometry_msgs::Twist>("robot_1/cmd_vel",1000);
sheepdogPosPub = nh.advertise<geometry_msgs::Pose2D>("sheepdog_position",1000);
// Subscribe to the simulated robot's laser scan topic and tell ROS to call
// this->commandCallback() whenever a new message is published on that topic
laserSub = nh.subscribe<sensor_msgs::LaserScan>("robot_1/base_scan", 1000, &sheepdogNode::commandCallback, this);
StageOdo_sub = nh.subscribe<nav_msgs::Odometry>("robot_1/odom",1000, &sheepdogNode::StageOdom_callback,this);
point_cloud_publisher_ = nh.advertise<sensor_msgs::PointCloud> ("/camera", 1000, false);
tfListener_.setExtrapolationLimit(ros::Duration(0.1));
prevpx = 5;
prevpx= 5;
this->spin();
}
<|endoftext|> |
<commit_before>//===--- Job.cpp - Command to Execute -------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#include "swift/Basic/STLExtras.h"
#include "swift/Driver/Job.h"
#include "swift/Driver/PrettyStackTrace.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/Option/Arg.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/Program.h"
#include "llvm/Support/raw_ostream.h"
using namespace swift;
using namespace swift::driver;
StringRef CommandOutput::getOutputForInputAndType(StringRef PrimaryInputFile,
file_types::ID Type) const {
if (Type == file_types::TY_Nothing)
return StringRef();
auto const *M = DerivedOutputMap.getOutputMapForInput(PrimaryInputFile);
if (!M)
return StringRef();
auto const Out = M->find(Type);
if (Out == M->end())
return StringRef();
assert(!Out->second.empty());
return StringRef(Out->second);
}
struct CommandOutputInvariantChecker {
CommandOutput const &Out;
CommandOutputInvariantChecker(CommandOutput const &CO) : Out(CO) {
#ifndef NDEBUG
Out.checkInvariants();
#endif
}
~CommandOutputInvariantChecker() {
#ifndef NDEBUG
Out.checkInvariants();
#endif
}
};
void CommandOutput::ensureEntry(StringRef PrimaryInputFile,
file_types::ID Type,
StringRef OutputFile,
bool Overwrite) {
assert(!PrimaryInputFile.empty());
assert(!OutputFile.empty());
assert(Type != file_types::TY_Nothing);
auto &M = DerivedOutputMap.getOrCreateOutputMapForInput(PrimaryInputFile);
if (Overwrite) {
M[Type] = OutputFile;
} else {
auto res = M.insert(std::make_pair(Type, OutputFile));
if (res.second) {
// New entry, no need to compare.
} else {
// Existing entry, check equality with request.
assert(res.first->getSecond() == OutputFile);
}
}
}
void CommandOutput::checkInvariants() const {
file_types::forAllTypes([&](file_types::ID Type) {
size_t numOutputsOfType = 0;
for (auto const &I : Inputs) {
// FIXME: At the moment, empty primary input names correspond to
// corner cases in the driver where it is doing TY_Nothing work
// and isn't even given a primary input; but at some point we
// ought to enable storing derived OFM entries under the empty
// name in general, for "whole build" additional outputs. They
// are presently (arbitrarily and wrongly) stored in entries
// associated with the first primary input of the CommandOutput
// that they were derived from.
assert(PrimaryOutputType == file_types::TY_Nothing || !I.Primary.empty());
auto const *M = DerivedOutputMap.getOutputMapForInput(I.Primary);
if (!M)
continue;
auto const Out = M->find(Type);
if (Out == M->end())
continue;
assert(!Out->second.empty());
++numOutputsOfType;
}
assert(numOutputsOfType == 0 ||
numOutputsOfType == 1 ||
numOutputsOfType == Inputs.size());
});
assert(AdditionalOutputTypes.count(PrimaryOutputType) == 0);
}
bool CommandOutput::hasSameAdditionalOutputTypes(
CommandOutput const &other) const {
bool sameAdditionalOutputTypes = true;
file_types::forAllTypes([&](file_types::ID Type) {
bool a = AdditionalOutputTypes.count(Type) == 0;
bool b = other.AdditionalOutputTypes.count(Type) == 0;
if (a != b)
sameAdditionalOutputTypes = false;
});
return sameAdditionalOutputTypes;
}
void CommandOutput::addOutputs(CommandOutput const &other) {
CommandOutputInvariantChecker Check(*this);
assert(PrimaryOutputType == other.PrimaryOutputType);
assert(&DerivedOutputMap == &other.DerivedOutputMap);
Inputs.append(other.Inputs.begin(),
other.Inputs.end());
// Should only be called with an empty AdditionalOutputTypes
// or one populated with the same types as other.
if (AdditionalOutputTypes.empty()) {
AdditionalOutputTypes = other.AdditionalOutputTypes;
} else {
assert(hasSameAdditionalOutputTypes(other));
}
}
CommandOutput::CommandOutput(file_types::ID PrimaryOutputType,
OutputFileMap &Derived)
: PrimaryOutputType(PrimaryOutputType), DerivedOutputMap(Derived) {
CommandOutputInvariantChecker Check(*this);
}
file_types::ID CommandOutput::getPrimaryOutputType() const {
return PrimaryOutputType;
}
void CommandOutput::addPrimaryOutput(CommandInputPair Input,
StringRef PrimaryOutputFile) {
PrettyStackTraceDriverCommandOutputAddition CrashInfo(
"primary", this, Input.Primary, PrimaryOutputType, PrimaryOutputFile);
if (PrimaryOutputType == file_types::TY_Nothing) {
// For TY_Nothing, we accumulate the inputs but do not add any outputs.
// The invariant holds on either side of this action because all primary
// outputs for this command will be absent (so the length == 0 case in the
// invariant holds).
CommandOutputInvariantChecker Check(*this);
Inputs.push_back(Input);
return;
}
// The invariant holds in the non-TY_Nothing case before an input is added and
// _after the corresponding output is added_, but not inbetween. Don't try to
// merge these two cases, they're different.
CommandOutputInvariantChecker Check(*this);
Inputs.push_back(Input);
assert(!PrimaryOutputFile.empty());
assert(AdditionalOutputTypes.count(PrimaryOutputType) == 0);
ensureEntry(Input.Primary, PrimaryOutputType, PrimaryOutputFile, false);
}
StringRef CommandOutput::getPrimaryOutputFilename() const {
// FIXME: ideally this shouldn't exist, or should at least assert size() == 1,
// and callers should handle cases with multiple primaries explicitly.
assert(Inputs.size() >= 1);
return getOutputForInputAndType(Inputs[0].Primary, PrimaryOutputType);
}
SmallVector<StringRef, 16> CommandOutput::getPrimaryOutputFilenames() const {
SmallVector<StringRef, 16> V;
size_t NonEmpty = 0;
for (auto const &I : Inputs) {
auto Out = getOutputForInputAndType(I.Primary, PrimaryOutputType);
V.push_back(Out);
if (!Out.empty())
++NonEmpty;
assert(!Out.empty() || PrimaryOutputType == file_types::TY_Nothing);
}
assert(NonEmpty == 0 || NonEmpty == Inputs.size());
return V;
}
void CommandOutput::setAdditionalOutputForType(file_types::ID Type,
StringRef OutputFilename) {
PrettyStackTraceDriverCommandOutputAddition CrashInfo(
"additional", this, Inputs[0].Primary, Type, OutputFilename);
CommandOutputInvariantChecker Check(*this);
assert(Inputs.size() >= 1);
assert(!OutputFilename.empty());
assert(Type != file_types::TY_Nothing);
// If we're given an "additional" output with the same type as the primary,
// and we've not yet had such an additional type added, we treat it as a
// request to overwrite the primary choice (which happens early and is
// sometimes just inferred) with a refined value (eg. -emit-module-path).
bool Overwrite = Type == PrimaryOutputType;
if (Overwrite) {
assert(AdditionalOutputTypes.count(Type) == 0);
} else {
AdditionalOutputTypes.insert(Type);
}
ensureEntry(Inputs[0].Primary, Type, OutputFilename, Overwrite);
}
StringRef CommandOutput::getAdditionalOutputForType(file_types::ID Type) const {
if (AdditionalOutputTypes.count(Type) == 0)
return StringRef();
assert(Inputs.size() >= 1);
// FIXME: ideally this shouldn't associate the additional output with the
// first primary, but with a specific primary (and/or possibly the primary "",
// for build-wide outputs) specified by the caller.
assert(Inputs.size() >= 1);
return getOutputForInputAndType(Inputs[0].Primary, Type);
}
SmallVector<StringRef, 16>
CommandOutput::getAdditionalOutputsForType(file_types::ID Type) const {
SmallVector<StringRef, 16> V;
if (AdditionalOutputTypes.count(Type) != 0) {
for (auto const &I : Inputs) {
auto Out = getOutputForInputAndType(I.Primary, Type);
// FIXME: In theory this should always be non-empty -- and V.size() would
// always be either 0 or N like with primary outputs -- but in practice
// WMO currently associates additional outputs with the _first primary_ in
// a multi-primary job, which means that the 2nd..Nth primaries will have
// an empty result from getOutputForInputAndType, and V.size() will be 1.
if (!Out.empty())
V.push_back(Out);
}
}
assert(V.empty() || V.size() == 1 || V.size() == Inputs.size());
return V;
}
StringRef CommandOutput::getAnyOutputForType(file_types::ID Type) const {
if (PrimaryOutputType == Type)
return getPrimaryOutputFilename();
return getAdditionalOutputForType(Type);
}
const OutputFileMap &CommandOutput::getDerivedOutputMap() const {
return DerivedOutputMap;
}
StringRef CommandOutput::getBaseInput(size_t Index) const {
assert(Index < Inputs.size());
return Inputs[Index].Base;
}
static void escapeAndPrintString(llvm::raw_ostream &os, StringRef Str) {
if (Str.empty()) {
// Special-case the empty string.
os << "\"\"";
return;
}
bool NeedsEscape = Str.find_first_of(" \"\\$") != StringRef::npos;
if (!NeedsEscape) {
// This string doesn't have anything we need to escape, so print it directly
os << Str;
return;
}
// Quote and escape. This isn't really complete, but is good enough, and
// matches how Clang's Command handles escaping arguments.
os << '"';
for (const char c : Str) {
switch (c) {
case '"':
case '\\':
case '$':
// These characters need to be escaped.
os << '\\';
// Fall-through to the default case, since we still need to print the
// character.
LLVM_FALLTHROUGH;
default:
os << c;
}
}
os << '"';
}
void
CommandOutput::print(raw_ostream &out) const {
out
<< "{\n"
<< " PrimaryOutputType = " << file_types::getTypeName(PrimaryOutputType)
<< ";\n"
<< " Inputs = [\n";
interleave(Inputs,
[&](CommandInputPair const &P) {
out << " CommandInputPair {\n"
<< " Base = ";
escapeAndPrintString(out, P.Base);
out << ", \n"
<< " Primary = ";
escapeAndPrintString(out, P.Primary);
out << "\n }";
},
[&] { out << ",\n"; });
out << "];\n"
<< " DerivedOutputFileMap = {\n";
DerivedOutputMap.dump(out, true);
out << "\n };\n}";
}
void
CommandOutput::dump() const {
print(llvm::errs());
llvm::errs() << '\n';
}
void CommandOutput::writeOutputFileMap(llvm::raw_ostream &out) const {
SmallVector<StringRef, 4> inputs;
for (const CommandInputPair IP : Inputs) {
assert(IP.Base == IP.Primary && !IP.Base.empty() &&
"output file maps won't work if these differ");
inputs.push_back(IP.Primary);
}
getDerivedOutputMap().write(out, inputs);
}
Job::~Job() = default;
void Job::printArguments(raw_ostream &os,
const llvm::opt::ArgStringList &Args) {
interleave(Args,
[&](const char *Arg) { escapeAndPrintString(os, Arg); },
[&] { os << ' '; });
}
void Job::dump() const {
printCommandLineAndEnvironment(llvm::errs());
}
ArrayRef<const char *> Job::getArgumentsForTaskExecution() const {
if (hasResponseFile()) {
writeArgsToResponseFile();
return ArrayRef<const char *>(ResponseFileArg);
} else {
return Arguments;
}
}
void Job::printCommandLineAndEnvironment(raw_ostream &Stream,
StringRef Terminator) const {
printCommandLine(Stream, /*Terminator=*/"");
if (!ExtraEnvironment.empty()) {
Stream << " #";
for (auto &pair : ExtraEnvironment) {
Stream << " " << pair.first << "=" << pair.second;
}
}
Stream << "\n";
}
void Job::printCommandLine(raw_ostream &os, StringRef Terminator) const {
escapeAndPrintString(os, Executable);
os << ' ';
if (hasResponseFile()) {
printArguments(os, {ResponseFileArg});
os << " # ";
}
printArguments(os, Arguments);
os << Terminator;
}
void Job::printSummary(raw_ostream &os) const {
// Deciding how to describe our inputs is a bit subtle; if we are a Job built
// from a JobAction that itself has InputActions sources, then we collect
// those up. Otherwise it's more correct to talk about our inputs as the
// outputs of our input-jobs.
SmallVector<StringRef, 4> Inputs;
SmallVector<StringRef, 4> Outputs = getOutput().getPrimaryOutputFilenames();
for (const Action *A : getSource().getInputs())
if (const auto *IA = dyn_cast<InputAction>(A))
Inputs.push_back(IA->getInputArg().getValue());
for (const Job *J : getInputs())
for (StringRef f : J->getOutput().getPrimaryOutputFilenames())
Inputs.push_back(f);
size_t limit = 3;
size_t actual_in = Inputs.size();
size_t actual_out = Outputs.size();
if (actual_in > limit) {
Inputs.erase(Inputs.begin() + limit, Inputs.end());
}
if (actual_out > limit) {
Outputs.erase(Outputs.begin() + limit, Outputs.end());
}
os << "{" << getSource().getClassName() << ": ";
interleave(Outputs,
[&](const std::string &Arg) {
os << llvm::sys::path::filename(Arg);
},
[&] { os << ' '; });
if (actual_out > limit) {
os << " ... " << (actual_out-limit) << " more";
}
os << " <= ";
interleave(Inputs,
[&](const std::string &Arg) {
os << llvm::sys::path::filename(Arg);
},
[&] { os << ' '; });
if (actual_in > limit) {
os << " ... " << (actual_in-limit) << " more";
}
os << "}";
}
bool Job::writeArgsToResponseFile() const {
std::error_code EC;
llvm::raw_fd_ostream OS(ResponseFilePath, EC, llvm::sys::fs::F_None);
if (EC) {
return true;
}
for (const char *arg : Arguments) {
OS << "\"";
escapeAndPrintString(OS, arg);
OS << "\" ";
}
OS.flush();
return false;
}
BatchJob::BatchJob(const JobAction &Source,
SmallVectorImpl<const Job *> &&Inputs,
std::unique_ptr<CommandOutput> Output,
const char *Executable, llvm::opt::ArgStringList Arguments,
EnvironmentVector ExtraEnvironment,
std::vector<FilelistInfo> Infos,
ArrayRef<const Job *> Combined, int64_t &NextQuasiPID)
: Job(Source, std::move(Inputs), std::move(Output), Executable, Arguments,
ExtraEnvironment, Infos),
CombinedJobs(Combined.begin(), Combined.end()),
QuasiPIDBase(NextQuasiPID) {
assert(QuasiPIDBase < 0);
NextQuasiPID -= CombinedJobs.size();
assert(NextQuasiPID < 0);
}
<commit_msg>Replace accessor methods in getArgumentsForTaskExecution.<commit_after>//===--- Job.cpp - Command to Execute -------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#include "swift/Basic/STLExtras.h"
#include "swift/Driver/Job.h"
#include "swift/Driver/PrettyStackTrace.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/Option/Arg.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/Program.h"
#include "llvm/Support/raw_ostream.h"
using namespace swift;
using namespace swift::driver;
StringRef CommandOutput::getOutputForInputAndType(StringRef PrimaryInputFile,
file_types::ID Type) const {
if (Type == file_types::TY_Nothing)
return StringRef();
auto const *M = DerivedOutputMap.getOutputMapForInput(PrimaryInputFile);
if (!M)
return StringRef();
auto const Out = M->find(Type);
if (Out == M->end())
return StringRef();
assert(!Out->second.empty());
return StringRef(Out->second);
}
struct CommandOutputInvariantChecker {
CommandOutput const &Out;
CommandOutputInvariantChecker(CommandOutput const &CO) : Out(CO) {
#ifndef NDEBUG
Out.checkInvariants();
#endif
}
~CommandOutputInvariantChecker() {
#ifndef NDEBUG
Out.checkInvariants();
#endif
}
};
void CommandOutput::ensureEntry(StringRef PrimaryInputFile,
file_types::ID Type,
StringRef OutputFile,
bool Overwrite) {
assert(!PrimaryInputFile.empty());
assert(!OutputFile.empty());
assert(Type != file_types::TY_Nothing);
auto &M = DerivedOutputMap.getOrCreateOutputMapForInput(PrimaryInputFile);
if (Overwrite) {
M[Type] = OutputFile;
} else {
auto res = M.insert(std::make_pair(Type, OutputFile));
if (res.second) {
// New entry, no need to compare.
} else {
// Existing entry, check equality with request.
assert(res.first->getSecond() == OutputFile);
}
}
}
void CommandOutput::checkInvariants() const {
file_types::forAllTypes([&](file_types::ID Type) {
size_t numOutputsOfType = 0;
for (auto const &I : Inputs) {
// FIXME: At the moment, empty primary input names correspond to
// corner cases in the driver where it is doing TY_Nothing work
// and isn't even given a primary input; but at some point we
// ought to enable storing derived OFM entries under the empty
// name in general, for "whole build" additional outputs. They
// are presently (arbitrarily and wrongly) stored in entries
// associated with the first primary input of the CommandOutput
// that they were derived from.
assert(PrimaryOutputType == file_types::TY_Nothing || !I.Primary.empty());
auto const *M = DerivedOutputMap.getOutputMapForInput(I.Primary);
if (!M)
continue;
auto const Out = M->find(Type);
if (Out == M->end())
continue;
assert(!Out->second.empty());
++numOutputsOfType;
}
assert(numOutputsOfType == 0 ||
numOutputsOfType == 1 ||
numOutputsOfType == Inputs.size());
});
assert(AdditionalOutputTypes.count(PrimaryOutputType) == 0);
}
bool CommandOutput::hasSameAdditionalOutputTypes(
CommandOutput const &other) const {
bool sameAdditionalOutputTypes = true;
file_types::forAllTypes([&](file_types::ID Type) {
bool a = AdditionalOutputTypes.count(Type) == 0;
bool b = other.AdditionalOutputTypes.count(Type) == 0;
if (a != b)
sameAdditionalOutputTypes = false;
});
return sameAdditionalOutputTypes;
}
void CommandOutput::addOutputs(CommandOutput const &other) {
CommandOutputInvariantChecker Check(*this);
assert(PrimaryOutputType == other.PrimaryOutputType);
assert(&DerivedOutputMap == &other.DerivedOutputMap);
Inputs.append(other.Inputs.begin(),
other.Inputs.end());
// Should only be called with an empty AdditionalOutputTypes
// or one populated with the same types as other.
if (AdditionalOutputTypes.empty()) {
AdditionalOutputTypes = other.AdditionalOutputTypes;
} else {
assert(hasSameAdditionalOutputTypes(other));
}
}
CommandOutput::CommandOutput(file_types::ID PrimaryOutputType,
OutputFileMap &Derived)
: PrimaryOutputType(PrimaryOutputType), DerivedOutputMap(Derived) {
CommandOutputInvariantChecker Check(*this);
}
file_types::ID CommandOutput::getPrimaryOutputType() const {
return PrimaryOutputType;
}
void CommandOutput::addPrimaryOutput(CommandInputPair Input,
StringRef PrimaryOutputFile) {
PrettyStackTraceDriverCommandOutputAddition CrashInfo(
"primary", this, Input.Primary, PrimaryOutputType, PrimaryOutputFile);
if (PrimaryOutputType == file_types::TY_Nothing) {
// For TY_Nothing, we accumulate the inputs but do not add any outputs.
// The invariant holds on either side of this action because all primary
// outputs for this command will be absent (so the length == 0 case in the
// invariant holds).
CommandOutputInvariantChecker Check(*this);
Inputs.push_back(Input);
return;
}
// The invariant holds in the non-TY_Nothing case before an input is added and
// _after the corresponding output is added_, but not inbetween. Don't try to
// merge these two cases, they're different.
CommandOutputInvariantChecker Check(*this);
Inputs.push_back(Input);
assert(!PrimaryOutputFile.empty());
assert(AdditionalOutputTypes.count(PrimaryOutputType) == 0);
ensureEntry(Input.Primary, PrimaryOutputType, PrimaryOutputFile, false);
}
StringRef CommandOutput::getPrimaryOutputFilename() const {
// FIXME: ideally this shouldn't exist, or should at least assert size() == 1,
// and callers should handle cases with multiple primaries explicitly.
assert(Inputs.size() >= 1);
return getOutputForInputAndType(Inputs[0].Primary, PrimaryOutputType);
}
SmallVector<StringRef, 16> CommandOutput::getPrimaryOutputFilenames() const {
SmallVector<StringRef, 16> V;
size_t NonEmpty = 0;
for (auto const &I : Inputs) {
auto Out = getOutputForInputAndType(I.Primary, PrimaryOutputType);
V.push_back(Out);
if (!Out.empty())
++NonEmpty;
assert(!Out.empty() || PrimaryOutputType == file_types::TY_Nothing);
}
assert(NonEmpty == 0 || NonEmpty == Inputs.size());
return V;
}
void CommandOutput::setAdditionalOutputForType(file_types::ID Type,
StringRef OutputFilename) {
PrettyStackTraceDriverCommandOutputAddition CrashInfo(
"additional", this, Inputs[0].Primary, Type, OutputFilename);
CommandOutputInvariantChecker Check(*this);
assert(Inputs.size() >= 1);
assert(!OutputFilename.empty());
assert(Type != file_types::TY_Nothing);
// If we're given an "additional" output with the same type as the primary,
// and we've not yet had such an additional type added, we treat it as a
// request to overwrite the primary choice (which happens early and is
// sometimes just inferred) with a refined value (eg. -emit-module-path).
bool Overwrite = Type == PrimaryOutputType;
if (Overwrite) {
assert(AdditionalOutputTypes.count(Type) == 0);
} else {
AdditionalOutputTypes.insert(Type);
}
ensureEntry(Inputs[0].Primary, Type, OutputFilename, Overwrite);
}
StringRef CommandOutput::getAdditionalOutputForType(file_types::ID Type) const {
if (AdditionalOutputTypes.count(Type) == 0)
return StringRef();
assert(Inputs.size() >= 1);
// FIXME: ideally this shouldn't associate the additional output with the
// first primary, but with a specific primary (and/or possibly the primary "",
// for build-wide outputs) specified by the caller.
assert(Inputs.size() >= 1);
return getOutputForInputAndType(Inputs[0].Primary, Type);
}
SmallVector<StringRef, 16>
CommandOutput::getAdditionalOutputsForType(file_types::ID Type) const {
SmallVector<StringRef, 16> V;
if (AdditionalOutputTypes.count(Type) != 0) {
for (auto const &I : Inputs) {
auto Out = getOutputForInputAndType(I.Primary, Type);
// FIXME: In theory this should always be non-empty -- and V.size() would
// always be either 0 or N like with primary outputs -- but in practice
// WMO currently associates additional outputs with the _first primary_ in
// a multi-primary job, which means that the 2nd..Nth primaries will have
// an empty result from getOutputForInputAndType, and V.size() will be 1.
if (!Out.empty())
V.push_back(Out);
}
}
assert(V.empty() || V.size() == 1 || V.size() == Inputs.size());
return V;
}
StringRef CommandOutput::getAnyOutputForType(file_types::ID Type) const {
if (PrimaryOutputType == Type)
return getPrimaryOutputFilename();
return getAdditionalOutputForType(Type);
}
const OutputFileMap &CommandOutput::getDerivedOutputMap() const {
return DerivedOutputMap;
}
StringRef CommandOutput::getBaseInput(size_t Index) const {
assert(Index < Inputs.size());
return Inputs[Index].Base;
}
static void escapeAndPrintString(llvm::raw_ostream &os, StringRef Str) {
if (Str.empty()) {
// Special-case the empty string.
os << "\"\"";
return;
}
bool NeedsEscape = Str.find_first_of(" \"\\$") != StringRef::npos;
if (!NeedsEscape) {
// This string doesn't have anything we need to escape, so print it directly
os << Str;
return;
}
// Quote and escape. This isn't really complete, but is good enough, and
// matches how Clang's Command handles escaping arguments.
os << '"';
for (const char c : Str) {
switch (c) {
case '"':
case '\\':
case '$':
// These characters need to be escaped.
os << '\\';
// Fall-through to the default case, since we still need to print the
// character.
LLVM_FALLTHROUGH;
default:
os << c;
}
}
os << '"';
}
void
CommandOutput::print(raw_ostream &out) const {
out
<< "{\n"
<< " PrimaryOutputType = " << file_types::getTypeName(PrimaryOutputType)
<< ";\n"
<< " Inputs = [\n";
interleave(Inputs,
[&](CommandInputPair const &P) {
out << " CommandInputPair {\n"
<< " Base = ";
escapeAndPrintString(out, P.Base);
out << ", \n"
<< " Primary = ";
escapeAndPrintString(out, P.Primary);
out << "\n }";
},
[&] { out << ",\n"; });
out << "];\n"
<< " DerivedOutputFileMap = {\n";
DerivedOutputMap.dump(out, true);
out << "\n };\n}";
}
void
CommandOutput::dump() const {
print(llvm::errs());
llvm::errs() << '\n';
}
void CommandOutput::writeOutputFileMap(llvm::raw_ostream &out) const {
SmallVector<StringRef, 4> inputs;
for (const CommandInputPair IP : Inputs) {
assert(IP.Base == IP.Primary && !IP.Base.empty() &&
"output file maps won't work if these differ");
inputs.push_back(IP.Primary);
}
getDerivedOutputMap().write(out, inputs);
}
Job::~Job() = default;
void Job::printArguments(raw_ostream &os,
const llvm::opt::ArgStringList &Args) {
interleave(Args,
[&](const char *Arg) { escapeAndPrintString(os, Arg); },
[&] { os << ' '; });
}
void Job::dump() const {
printCommandLineAndEnvironment(llvm::errs());
}
ArrayRef<const char *> Job::getArgumentsForTaskExecution() const {
if (hasResponseFile()) {
writeArgsToResponseFile();
return getResponseFileArg();
} else {
return getArguments();
}
}
void Job::printCommandLineAndEnvironment(raw_ostream &Stream,
StringRef Terminator) const {
printCommandLine(Stream, /*Terminator=*/"");
if (!ExtraEnvironment.empty()) {
Stream << " #";
for (auto &pair : ExtraEnvironment) {
Stream << " " << pair.first << "=" << pair.second;
}
}
Stream << "\n";
}
void Job::printCommandLine(raw_ostream &os, StringRef Terminator) const {
escapeAndPrintString(os, Executable);
os << ' ';
if (hasResponseFile()) {
printArguments(os, {ResponseFileArg});
os << " # ";
}
printArguments(os, Arguments);
os << Terminator;
}
void Job::printSummary(raw_ostream &os) const {
// Deciding how to describe our inputs is a bit subtle; if we are a Job built
// from a JobAction that itself has InputActions sources, then we collect
// those up. Otherwise it's more correct to talk about our inputs as the
// outputs of our input-jobs.
SmallVector<StringRef, 4> Inputs;
SmallVector<StringRef, 4> Outputs = getOutput().getPrimaryOutputFilenames();
for (const Action *A : getSource().getInputs())
if (const auto *IA = dyn_cast<InputAction>(A))
Inputs.push_back(IA->getInputArg().getValue());
for (const Job *J : getInputs())
for (StringRef f : J->getOutput().getPrimaryOutputFilenames())
Inputs.push_back(f);
size_t limit = 3;
size_t actual_in = Inputs.size();
size_t actual_out = Outputs.size();
if (actual_in > limit) {
Inputs.erase(Inputs.begin() + limit, Inputs.end());
}
if (actual_out > limit) {
Outputs.erase(Outputs.begin() + limit, Outputs.end());
}
os << "{" << getSource().getClassName() << ": ";
interleave(Outputs,
[&](const std::string &Arg) {
os << llvm::sys::path::filename(Arg);
},
[&] { os << ' '; });
if (actual_out > limit) {
os << " ... " << (actual_out-limit) << " more";
}
os << " <= ";
interleave(Inputs,
[&](const std::string &Arg) {
os << llvm::sys::path::filename(Arg);
},
[&] { os << ' '; });
if (actual_in > limit) {
os << " ... " << (actual_in-limit) << " more";
}
os << "}";
}
bool Job::writeArgsToResponseFile() const {
std::error_code EC;
llvm::raw_fd_ostream OS(ResponseFilePath, EC, llvm::sys::fs::F_None);
if (EC) {
return true;
}
for (const char *arg : Arguments) {
OS << "\"";
escapeAndPrintString(OS, arg);
OS << "\" ";
}
OS.flush();
return false;
}
BatchJob::BatchJob(const JobAction &Source,
SmallVectorImpl<const Job *> &&Inputs,
std::unique_ptr<CommandOutput> Output,
const char *Executable, llvm::opt::ArgStringList Arguments,
EnvironmentVector ExtraEnvironment,
std::vector<FilelistInfo> Infos,
ArrayRef<const Job *> Combined, int64_t &NextQuasiPID)
: Job(Source, std::move(Inputs), std::move(Output), Executable, Arguments,
ExtraEnvironment, Infos),
CombinedJobs(Combined.begin(), Combined.end()),
QuasiPIDBase(NextQuasiPID) {
assert(QuasiPIDBase < 0);
NextQuasiPID -= CombinedJobs.size();
assert(NextQuasiPID < 0);
}
<|endoftext|> |
<commit_before>//=======================================================================
// Copyright (c) 2014-2017 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#ifdef ETL_VECTORIZE_IMPL
#ifdef __AVX__
#define TEST_VEC
#elif defined(__SSE3__)
#define TEST_VEC
#endif
#endif
#define SUM_FUNCTOR(name, ...) \
struct name { \
template <typename A, typename C> \
static void apply(A&& a, C&& c) { \
__VA_ARGS__; \
} \
};
SUM_FUNCTOR(default_sum, c = etl::sum(a))
SUM_FUNCTOR(std_sum, SELECTED_SECTION(etl::sum_impl::STD) { c = etl::sum(a); })
SUM_FUNCTOR(default_asum, c = etl::asum(a))
SUM_FUNCTOR(std_asum, SELECTED_SECTION(etl::sum_impl::STD) { c = etl::asum(a); })
#define SUM_TEST_CASE_SECTION_DEFAULT SUM_TEST_CASE_SECTIONS(default_sum)
#define SUM_TEST_CASE_SECTION_STD SUM_TEST_CASE_SECTIONS(std_sum)
#define ASUM_TEST_CASE_SECTION_DEFAULT SUM_TEST_CASE_SECTIONS(default_asum)
#define ASUM_TEST_CASE_SECTION_STD SUM_TEST_CASE_SECTIONS(std_asum)
#ifdef TEST_VEC
SUM_FUNCTOR(vec_sum, SELECTED_SECTION(etl::sum_impl::VEC) { c = etl::sum(a); })
SUM_FUNCTOR(vec_asum, SELECTED_SECTION(etl::sum_impl::VEC) { c = etl::asum(a); })
#define SUM_TEST_CASE_SECTION_VEC SUM_TEST_CASE_SECTIONS(vec_sum)
#define ASUM_TEST_CASE_SECTION_VEC SUM_TEST_CASE_SECTIONS(vec_asum)
#else
#define SUM_TEST_CASE_SECTION_VEC
#define ASUM_TEST_CASE_SECTION_VEC
#endif
#ifdef ETL_BLAS_MODE
SUM_FUNCTOR(blas_sum, SELECTED_SECTION(etl::sum_impl::BLAS) { c = etl::sum(a); })
SUM_FUNCTOR(blas_asum, SELECTED_SECTION(etl::sum_impl::BLAS) { c = etl::asum(a); })
#define SUM_TEST_CASE_SECTION_BLAS SUM_TEST_CASE_SECTIONS(blas_sum)
#define ASUM_TEST_CASE_SECTION_BLAS SUM_TEST_CASE_SECTIONS(blas_asum)
#else
#define SUM_TEST_CASE_SECTION_BLAS
#define ASUM_TEST_CASE_SECTION_BLAS
#endif
#ifdef ETL_CUBLAS_MODE
SUM_FUNCTOR(cublas_sum, SELECTED_SECTION(etl::sum_impl::CUBLAS) { c = etl::sum(a); })
SUM_FUNCTOR(cublas_asum, SELECTED_SECTION(etl::sum_impl::CUBLAS) { c = etl::asum(a); })
#define SUM_TEST_CASE_SECTION_CUBLAS SUM_TEST_CASE_SECTIONS(cublas_sum)
#define ASUM_TEST_CASE_SECTION_CUBLAS ASUM_TEST_CASE_SECTIONS(cublas_asum)
#else
#define SUM_TEST_CASE_SECTION_CUBLAS
#define ASUM_TEST_CASE_SECTION_CUBLAS
#endif
#define SUM_TEST_CASE_DECL(name, description) \
template <typename T, typename Impl> \
static void UNIQUE_NAME(____C_A_T_C_H____T_E_M_P_L_A_TE____T_E_S_T____)(); \
ETL_TEST_CASE(name, description)
#define SUM_TEST_CASE_SECTION(Tn, Impln) \
ETL_SECTION(#Tn "_" #Impln) { \
UNIQUE_NAME(____C_A_T_C_H____T_E_M_P_L_A_TE____T_E_S_T____)<Tn, Impln>(); \
}
#define SUM_TEST_CASE_DEFN \
template <typename T, typename Impl> \
static void UNIQUE_NAME(____C_A_T_C_H____T_E_M_P_L_A_TE____T_E_S_T____)()
#define SUM_TEST_CASE_SECTIONS(S1) \
SUM_TEST_CASE_SECTION(float, S1) \
SUM_TEST_CASE_SECTION(double, S1)
#define SUM_TEST_CASE(name, description) \
SUM_TEST_CASE_DECL(name, description) { \
SUM_TEST_CASE_SECTION_DEFAULT \
SUM_TEST_CASE_SECTION_STD \
SUM_TEST_CASE_SECTION_VEC \
SUM_TEST_CASE_SECTION_BLAS \
SUM_TEST_CASE_SECTION_CUBLAS \
} \
SUM_TEST_CASE_DEFN
#define ASUM_TEST_CASE(name, description) \
SUM_TEST_CASE_DECL(name, description) { \
ASUM_TEST_CASE_SECTION_DEFAULT \
ASUM_TEST_CASE_SECTION_STD \
ASUM_TEST_CASE_SECTION_VEC \
ASUM_TEST_CASE_SECTION_BLAS \
ASUM_TEST_CASE_SECTION_CUBLAS \
} \
SUM_TEST_CASE_DEFN
<commit_msg>Fix the sum tests<commit_after>//=======================================================================
// Copyright (c) 2014-2017 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#ifdef ETL_VECTORIZE_IMPL
#ifdef __AVX__
#define TEST_VEC
#elif defined(__SSE3__)
#define TEST_VEC
#endif
#endif
#define SUM_FUNCTOR(name, ...) \
struct name { \
template <typename A, typename C> \
static void apply(A&& a, C&& c) { \
__VA_ARGS__; \
} \
};
SUM_FUNCTOR(default_sum, c = etl::sum(a))
SUM_FUNCTOR(std_sum, SELECTED_SECTION(etl::sum_impl::STD) { c = etl::sum(a); })
SUM_FUNCTOR(default_asum, c = etl::asum(a))
SUM_FUNCTOR(std_asum, SELECTED_SECTION(etl::sum_impl::STD) { c = etl::asum(a); })
#define SUM_TEST_CASE_SECTION_DEFAULT SUM_TEST_CASE_SECTIONS(default_sum)
#define SUM_TEST_CASE_SECTION_STD SUM_TEST_CASE_SECTIONS(std_sum)
#define ASUM_TEST_CASE_SECTION_DEFAULT SUM_TEST_CASE_SECTIONS(default_asum)
#define ASUM_TEST_CASE_SECTION_STD SUM_TEST_CASE_SECTIONS(std_asum)
#ifdef TEST_VEC
SUM_FUNCTOR(vec_sum, SELECTED_SECTION(etl::sum_impl::VEC) { c = etl::sum(a); })
SUM_FUNCTOR(vec_asum, SELECTED_SECTION(etl::sum_impl::VEC) { c = etl::asum(a); })
#define SUM_TEST_CASE_SECTION_VEC SUM_TEST_CASE_SECTIONS(vec_sum)
#define ASUM_TEST_CASE_SECTION_VEC SUM_TEST_CASE_SECTIONS(vec_asum)
#else
#define SUM_TEST_CASE_SECTION_VEC
#define ASUM_TEST_CASE_SECTION_VEC
#endif
#ifdef ETL_BLAS_MODE
SUM_FUNCTOR(blas_sum, SELECTED_SECTION(etl::sum_impl::BLAS) { c = etl::sum(a); })
SUM_FUNCTOR(blas_asum, SELECTED_SECTION(etl::sum_impl::BLAS) { c = etl::asum(a); })
#define SUM_TEST_CASE_SECTION_BLAS SUM_TEST_CASE_SECTIONS(blas_sum)
#define ASUM_TEST_CASE_SECTION_BLAS SUM_TEST_CASE_SECTIONS(blas_asum)
#else
#define SUM_TEST_CASE_SECTION_BLAS
#define ASUM_TEST_CASE_SECTION_BLAS
#endif
#ifdef ETL_CUBLAS_MODE
SUM_FUNCTOR(cublas_sum, SELECTED_SECTION(etl::sum_impl::CUBLAS) { c = etl::sum(a); })
SUM_FUNCTOR(cublas_asum, SELECTED_SECTION(etl::sum_impl::CUBLAS) { c = etl::asum(a); })
#define SUM_TEST_CASE_SECTION_CUBLAS SUM_TEST_CASE_SECTIONS(cublas_sum)
#define ASUM_TEST_CASE_SECTION_CUBLAS SUM_TEST_CASE_SECTIONS(cublas_asum)
#else
#define SUM_TEST_CASE_SECTION_CUBLAS
#define ASUM_TEST_CASE_SECTION_CUBLAS
#endif
#define SUM_TEST_CASE_DECL(name, description) \
template <typename T, typename Impl> \
static void UNIQUE_NAME(____C_A_T_C_H____T_E_M_P_L_A_TE____T_E_S_T____)(); \
ETL_TEST_CASE(name, description)
#define SUM_TEST_CASE_SECTION(Tn, Impln) \
ETL_SECTION(#Tn "_" #Impln) { \
UNIQUE_NAME(____C_A_T_C_H____T_E_M_P_L_A_TE____T_E_S_T____)<Tn, Impln>(); \
}
#define SUM_TEST_CASE_DEFN \
template <typename T, typename Impl> \
static void UNIQUE_NAME(____C_A_T_C_H____T_E_M_P_L_A_TE____T_E_S_T____)()
#define SUM_TEST_CASE_SECTIONS(S1) \
SUM_TEST_CASE_SECTION(float, S1) \
SUM_TEST_CASE_SECTION(double, S1)
#define SUM_TEST_CASE(name, description) \
SUM_TEST_CASE_DECL(name, description) { \
SUM_TEST_CASE_SECTION_DEFAULT \
SUM_TEST_CASE_SECTION_STD \
SUM_TEST_CASE_SECTION_VEC \
SUM_TEST_CASE_SECTION_BLAS \
SUM_TEST_CASE_SECTION_CUBLAS \
} \
SUM_TEST_CASE_DEFN
#define ASUM_TEST_CASE(name, description) \
SUM_TEST_CASE_DECL(name, description) { \
ASUM_TEST_CASE_SECTION_DEFAULT \
ASUM_TEST_CASE_SECTION_STD \
ASUM_TEST_CASE_SECTION_VEC \
ASUM_TEST_CASE_SECTION_BLAS \
ASUM_TEST_CASE_SECTION_CUBLAS \
} \
SUM_TEST_CASE_DEFN
<|endoftext|> |
<commit_before>#ifndef FX_SEGMENT_TREE_HPP
#define FX_SEGMENT_TREE_HPP
#include <vector>
#include <utility>
namespace fx {
template <typename T, typename Specification, typename Container=std::vector<T> >
class segment_tree
{
// Types
public:
typedef T value_type;
typedef Container container;
typedef Specification specification;
protected:
typedef typename Container::size_type size_type;
typedef std::pair<size_type, size_type> size_type_pair;
public:
// Constructors
segment_tree() :
cont_(),
tree_cont_(),
identity_(specification::get_identity())
{
}
segment_tree(size_type n, const value_type& val = value_type()) :
cont_(n, val),
tree_cont_(),
identity_(specification::get_identity())
{
build();
}
template<typename InputIterator>
segment_tree(InputIterator first, InputIterator last) :
cont_(first, last),
tree_cont_(),
identity_(specification::get_identity())
{
build();
}
segment_tree(const container& cont) :
cont_(cont),
tree_cont_(),
identity_(specification::get_identity())
{
build();
}
// Public methods
void build()
{
size_type_pair tree_size_height = tree_size(cont_.size());
size_ = tree_size_height.first+1;
height_ = tree_size_height.second;
tree_cont_.resize(size_-1);
if (!height_) return;
size_type_pair range = range_for_depth(height_-1);
size_type& start = range.first;
size_type& end = range.second;
// tree base level
for (size_type k = 0; start+k < end; ++k)
tree_cont_[start+k] = specification::fn(get_element(k<<1), get_element((k<<1)+1));
// other levels
for (size_type h = 1, depth = height_-2; h < height_; ++h, --depth)
{
range = range_for_depth(depth);
size_type& start = range.first;
size_type& end = range.second;
for (size_type k = start; k < end; ++k)
tree_cont_[k] = specification::fn(tree_cont_[(k<<1)+1], tree_cont_[(k<<1)+2]);
}
}
const T& query(size_type start, size_type last) const
{
// check start < last <= cont_.size()
return query_recursive(0, size_type_pair(0, size_), size_type_pair(start, last));
}
void update(size_type index, const value_type& val)
{
// check index < cont_.size()
update_recursive(0, size_type_pair(0, size_), index, val);
}
protected:
// Data members
container cont_;
container tree_cont_;
size_type height_;
size_type size_;
value_type identity_;
// Query and update methods
const T& query_recursive(size_type node, size_type_pair node_range, size_type_pair query_range) const
{
if (node_range.first >= query_range.first && node_range.second <= query_range.second)
if (node_range.first + 1 == node_range.second)
return get_element(node_range.first);
else
return tree_cont_[node];
if (node_range.second <= query_range.first || query_range.second <= node_range.first)
return identity_;
size_type mid = mid_point(node_range.first, node_range.second);
const T * left_val = & query_recursive((node<<1)+1, size_type_pair(node_range.first, mid),
query_range);
const T * right_val = & query_recursive((node<<1)+2, size_type_pair(mid, node_range.second),
query_range);
return specification::fn(*left_val, *right_val);
}
const T& update_recursive(size_type node, size_type_pair node_range, size_type index, const T& val)
{
if (node_range.first + 1 == node_range.second && index == node_range.first)
return cont_[index] = val; // index must always be less than cont_.size()
if (index < node_range.first || node_range.second <= index)
if (node_range.first + 1 == node_range.second)
return get_element(node_range.first);
else
return tree_cont_[node];
size_type mid = mid_point(node_range.first, node_range.second);
const T * left_val = & update_recursive((node<<1)+1, size_type_pair(node_range.first, mid),
index, val);
const T * right_val = & update_recursive((node<<1)+2, size_type_pair(mid, node_range.second),
index, val);
return tree_cont_[node] = specification::fn(*left_val, *right_val);
}
// Util functions
size_type_pair tree_size(size_type n) const
{
size_type height = 0;
size_type size = 1;
while (size < n) ++height, size <<= 1;
return size_type_pair(size - 1, height);
}
inline size_type_pair range_for_depth(size_type depth) const
{
return size_type_pair((1<<depth)-1, (1<<(depth+1))-1);
}
inline const value_type& get_element(size_type index) const
{
return index < cont_.size() ? cont_[index] : identity_;
}
inline size_type mid_point(size_type a, size_type b) const
{
// check b > a
return a + ((b - a) >> 1);
}
}; // class segment_tree
} // namespace fx
#endif // FX_SEGMENT_TREE_HPP
<commit_msg>Added const_iterator<commit_after>#ifndef FX_SEGMENT_TREE_HPP
#define FX_SEGMENT_TREE_HPP
#include <vector>
#include <utility>
namespace fx {
template <typename T, typename Specification, typename Container=std::vector<T> >
class segment_tree
{
// Types
public:
typedef T value_type;
typedef Container container;
typedef Specification specification;
typedef typename container::const_iterator const_iterator;
protected:
typedef typename Container::size_type size_type;
typedef std::pair<size_type, size_type> size_type_pair;
public:
// Constructors
segment_tree() :
cont_(),
tree_cont_(),
identity_(specification::get_identity())
{
}
segment_tree(size_type n, const value_type& val = value_type()) :
cont_(n, val),
tree_cont_(),
identity_(specification::get_identity())
{
build();
}
template<typename InputIterator>
segment_tree(InputIterator first, InputIterator last) :
cont_(first, last),
tree_cont_(),
identity_(specification::get_identity())
{
build();
}
segment_tree(const container& cont) :
cont_(cont),
tree_cont_(),
identity_(specification::get_identity())
{
build();
}
// Public methods
void build()
{
size_type_pair tree_size_height = tree_size(cont_.size());
size_ = tree_size_height.first+1;
height_ = tree_size_height.second;
tree_cont_.resize(size_-1);
if (!height_) return;
size_type_pair range = range_for_depth(height_-1);
size_type& start = range.first;
size_type& end = range.second;
// tree base level
for (size_type k = 0; start+k < end; ++k)
tree_cont_[start+k] = specification::fn(get_element(k<<1), get_element((k<<1)+1));
// other levels
for (size_type h = 1, depth = height_-2; h < height_; ++h, --depth)
{
range = range_for_depth(depth);
size_type& start = range.first;
size_type& end = range.second;
for (size_type k = start; k < end; ++k)
tree_cont_[k] = specification::fn(tree_cont_[(k<<1)+1], tree_cont_[(k<<1)+2]);
}
}
const T& query(size_type start, size_type last) const
{
// check start < last <= cont_.size()
return query_recursive(0, size_type_pair(0, size_), size_type_pair(start, last));
}
void update(size_type index, const value_type& val)
{
// check index < cont_.size()
update_recursive(0, size_type_pair(0, size_), index, val);
}
inline const_iterator begin() const
{
return cont_.begin();
}
inline const_iterator end() const
{
return cont_.end();
}
protected:
// Data members
container cont_;
container tree_cont_; // change to a vector of size_type so it store the position of the element instead of a copy
size_type height_;
size_type size_;
value_type identity_;
// Query and update methods
const T& query_recursive(size_type node, size_type_pair node_range, size_type_pair query_range) const
{
if (node_range.first >= query_range.first && node_range.second <= query_range.second)
if (node_range.first + 1 == node_range.second)
return get_element(node_range.first);
else
return tree_cont_[node];
if (node_range.second <= query_range.first || query_range.second <= node_range.first)
return identity_;
size_type mid = mid_point(node_range.first, node_range.second);
const T * left_val = & query_recursive((node<<1)+1, size_type_pair(node_range.first, mid),
query_range);
const T * right_val = & query_recursive((node<<1)+2, size_type_pair(mid, node_range.second),
query_range);
return specification::fn(*left_val, *right_val);
}
const T& update_recursive(size_type node, size_type_pair node_range, size_type index, const T& val)
{
if (node_range.first + 1 == node_range.second && index == node_range.first)
return cont_[index] = val; // index must always be less than cont_.size()
if (index < node_range.first || node_range.second <= index)
if (node_range.first + 1 == node_range.second)
return get_element(node_range.first);
else
return tree_cont_[node];
size_type mid = mid_point(node_range.first, node_range.second);
const T * left_val = & update_recursive((node<<1)+1, size_type_pair(node_range.first, mid),
index, val);
const T * right_val = & update_recursive((node<<1)+2, size_type_pair(mid, node_range.second),
index, val);
return tree_cont_[node] = specification::fn(*left_val, *right_val);
}
// Util functions
size_type_pair tree_size(size_type n) const
{
size_type height = 0;
size_type size = 1;
while (size < n) ++height, size <<= 1;
return size_type_pair(size - 1, height);
}
inline size_type_pair range_for_depth(size_type depth) const
{
return size_type_pair((1<<depth)-1, (1<<(depth+1))-1);
}
inline const value_type& get_element(size_type index) const
{
return index < cont_.size() ? cont_[index] : identity_;
}
inline size_type mid_point(size_type a, size_type b) const
{
// check b > a
return a + ((b - a) >> 1);
}
}; // class segment_tree
} // namespace fx
#endif // FX_SEGMENT_TREE_HPP
<|endoftext|> |
<commit_before><commit_msg>tests: Add LayoutFromPresentWithoutSrcAccess test<commit_after><|endoftext|> |
<commit_before><commit_msg>tests: Fix CreateBufferView error in DSUsageBitsErrors<commit_after><|endoftext|> |
<commit_before>/*
Author: Araf Al-Jami
Last Edited: 21/05/16
*/
#include <iostream>
#include <cstring>
using namespace std;
int board[10];
int win_combos[][3] = {
{ 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 },
{ 1, 4, 7 }, { 2, 5, 8 }, { 3, 6, 9 },
{ 1, 5, 9 }, { 3, 5, 7 }
};
int mv_cnt;
void init();
void draw();
void single_player( int player );
void two_player();
bool running();
int minimax( int player );
void player_move( int player );
void computer_move( int player );
int main( int argc, char **argv ) {
int inp;
bool invalid = false;
do {
if( invalid ) {
cout << "Please Enter A Valid Input\n";
}
cout << "Enter 1 for single player or 2 for Two Player: ";
cin >> inp;
invalid = true;
cout << "\n";
} while( inp < 1 or inp > 2 );
if( inp == 1 ) {
invalid = false;
do {
if( invalid ) {
cout << "Please Enter A Valid Input\n";
}
cout << "Enter 1 If You Want To Be The First Player\n";
cout << "Else Enter 2: ";
cin >> inp;
cout << "\n";
} while( inp < 1 or inp > 2 );
single_player( inp );
} else {
two_player();
}
return 0;
}
void init() {
memset( board, 0, sizeof board );
mv_cnt = 9;
}
void draw() {
for( int i=1; i<=9; i++ ) {
if( board[i] ) {
cout << "XO"[ board[i]-1 ] << "\n|"[ i % 3 != 0 ];
} else {
cout << i << "\n|"[ i % 3 != 0 ];
}
if( i == 3 or i == 6 ) {
cout << string( 5, '-' ) << "\n";
}
}
cout << "\n";
}
bool running() {
if( !mv_cnt ) {
return false;
}
for( int i=0; i<8; i++ ) {
if( board[ win_combos[i][0] ] == board[ win_combos[i][1] ]
and
board[ win_combos[i][1] ] == board[ win_combos[i][2] ]
and board[ win_combos[i][2] ] != 0 ) {
return false;
}
}
return true;
}
string determine( int game_type, int player ) {
if( !mv_cnt ) {
return "Tie!";
}
for( int i=0; i<8; i++ ) {
if( board[ win_combos[i][0] ] == board[ win_combos[i][1] ]
and
board[ win_combos[i][1] ] == board[ win_combos[i][2] ]
and board[ win_combos[i][2] ] != 0 ) {
if( board[ win_combos[i][2] ] == 1 ) {
if( game_type == 1 ) {
return player == 1 ? "You Win!" : "You lose!";
} else {
return "Player 1 Wins!";
}
} else {
if( game_type == 1 ) {
return player == 2 ? "You Win!" : "You lose!";
} else {
return "Player 2 Wins!";
}
}
}
}
return "Not Complete!";
}
void two_player() {
int inp = 0;
int player = 1;
bool invalid = false;
init();
draw();
while( running() ) {
do {
if( invalid ) {
cout << "Please Enter A Valid Input\n";
}
cout << "Player " << player << " input: ";
cin >> inp;
invalid = true;
cout << "\n";
} while( inp < 1 or inp > 9 or board[inp] );
invalid = false;
board[inp] = player;
--mv_cnt;
draw();
player = player == 1 ? 2 : 1 ;
}
cout << determine( 2, 0 ) << "\n";
}
void single_player( int player ) {
init();
draw();
while( running() ) {
if( mv_cnt & 1 ) {
player == 1 ? player_move( player ) : computer_move( player );
} else {
player == 2 ? player_move( player ) : computer_move( player );
}
--mv_cnt;
draw();
}
cout << determine( 1, player ) << "\n";
}
void player_move( int player ) {
int inp = 0;
bool invalid = false;
do {
if( invalid ) {
cout << "Please Enter A Valid Input\n";
}
cout << "Player " << player << " input: ";
cin >> inp;
invalid = true;
cout << "\n";
} while( inp < 1 or inp > 9 or board[inp] );
board[inp] = player;
}
void computer_move( int player ) {
int cmp = player == 1 ? 2 : 1;
int move = -1;
int best = -11;
int temp;
for( int i=1; i<=9; i++ ) {
if( board[i] == 0 ) {
board[i] = cmp;
--mv_cnt;
temp = -minimax( player );
board[i] = 0;
++mv_cnt;
if( temp > best ) {
best = temp;
move = i;
}
}
}
board[move] = cmp;
}
int score( int player ) {
int enemy = player == 1 ? 2 : 1;
for( int i=0; i<8; i++ ) {
if( board[ win_combos[i][0] ] == board[ win_combos[i][1] ]
and
board[ win_combos[i][1] ] == board[ win_combos[i][2] ] ) {
if( board[ win_combos[i][2] ] == player ) {
return 10;
} else if( board[ win_combos[i][2] ] == enemy ) {
return -10;
}
}
}
return 0;
}
int minimax( int player ) {
if( !running() ) {
return score( player );
}
int enemy = player == 1 ? 2 : 1;
int move = -1;
int best = -11;
int temp;
for( int i=1; i<=9; i++ ) {
if( board[i] == 0 ) {
board[i] = player;
--mv_cnt;
temp = -minimax( enemy );
board[i] = 0;
++mv_cnt;
if( temp > best ) {
best = temp;
move = i;
}
}
}
if( move == -1 ) {
return 0;
}
return best;
}<commit_msg>Difficulty level added.<commit_after>/*
Author: Araf Al-Jami
Diff_Update: Mohammed Raihan Hussain
Last Edited: 21/05/16
*/
#include <iostream>
#include <cstring>
#include <stdlib.h>
using namespace std;
int board[10];
int win_combos[][3] = {
{ 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 },
{ 1, 4, 7 }, { 2, 5, 8 }, { 3, 6, 9 },
{ 1, 5, 9 }, { 3, 5, 7 }
};
int mv_cnt;
void init();
void draw();
void single_player( int player , int diff_level);
void two_player();
bool running();
int minimax( int player );
void player_move( int player );
void computer_move( int player , int diff_level);
int main( int argc, char **argv ) {
int inp;
bool invalid = false;
do {
if( invalid ) {
cout << "Please Enter A Valid Input\n";
}
cout << "Enter 1 for single player or 2 for Two Player: ";
cin >> inp;
invalid = true;
cout << "\n";
} while( inp < 1 or inp > 2 );
if( inp == 1 ) {
invalid = false;
do {
if( invalid ) {
cout << "Please Enter A Valid Input\n";
}
cout << "Enter 1 If You Want To Be The First Player\n";
cout << "Else Enter 2: ";
cin >> inp;
cout << "\n";
} while( inp < 1 or inp > 2 );
int cns = inp;
invalid = false;
do {
if( invalid ) {
cout << "Please Enter A Valid Input\n";
}
cout << "Enter 1 for Easy Difficulty\n";
cout << "Else Enter 2 for Hard Difficulty: ";
cin >> inp;
cout << "\n";
} while( inp < 1 or inp > 2 );
single_player(cns, inp );
} else {
two_player();
}
return 0;
}
void init() {
memset( board, 0, sizeof board );
mv_cnt = 9;
}
void draw() {
for( int i=1; i<=9; i++ ) {
if( board[i] ) {
cout << "XO"[ board[i]-1 ] << "\n|"[ i % 3 != 0 ];
} else {
cout << i << "\n|"[ i % 3 != 0 ];
}
if( i == 3 or i == 6 ) {
cout << string( 5, '-' ) << "\n";
}
}
cout << "\n";
}
bool running() {
if( !mv_cnt ) {
return false;
}
for( int i=0; i<8; i++ ) {
if( board[ win_combos[i][0] ] == board[ win_combos[i][1] ]
and
board[ win_combos[i][1] ] == board[ win_combos[i][2] ]
and board[ win_combos[i][2] ] != 0 ) {
return false;
}
}
return true;
}
string determine( int game_type, int player ) {
if( !mv_cnt ) {
return "Tie!";
}
for( int i=0; i<8; i++ ) {
if( board[ win_combos[i][0] ] == board[ win_combos[i][1] ]
and
board[ win_combos[i][1] ] == board[ win_combos[i][2] ]
and board[ win_combos[i][2] ] != 0 ) {
if( board[ win_combos[i][2] ] == 1 ) {
if( game_type == 1 ) {
return player == 1 ? "You Win!" : "You lose!";
} else {
return "Player 1 Wins!";
}
} else {
if( game_type == 1 ) {
return player == 2 ? "You Win!" : "You lose!";
} else {
return "Player 2 Wins!";
}
}
}
}
return "Not Complete!";
}
void two_player() {
int inp = 0;
int player = 1;
bool invalid = false;
init();
draw();
while( running() ) {
do {
if( invalid ) {
cout << "Please Enter A Valid Input\n";
}
cout << "Player " << player << " input: ";
cin >> inp;
invalid = true;
cout << "\n";
} while( inp < 1 or inp > 9 or board[inp] );
invalid = false;
board[inp] = player;
--mv_cnt;
draw();
player = player == 1 ? 2 : 1 ;
}
cout << determine( 2, 0 ) << "\n";
}
void single_player( int player , int diff_level) {
init();
draw();
while( running() ) {
if( mv_cnt & 1 ) {
player == 1 ? player_move( player ) : computer_move( player, diff_level );
} else {
player == 2 ? player_move( player ) : computer_move( player, diff_level );
}
--mv_cnt;
draw();
}
cout << determine( 1, player ) << "\n";
}
void player_move( int player ) {
int inp = 0;
bool invalid = false;
do {
if( invalid ) {
cout << "Please Enter A Valid Input\n";
}
cout << "Player " << player << " input: ";
cin >> inp;
invalid = true;
cout << "\n";
} while( inp < 1 or inp > 9 or board[inp] );
board[inp] = player;
}
void computer_move( int player , int diff_level ) {
int move = -1;
int cmp = player == 1 ? 2 : 1;
if (diff_level == 2){
int best = -11;
int temp;
for( int i=1; i<=9; i++ ) {
if( board[i] == 0 ) {
board[i] = cmp;
--mv_cnt;
temp = -minimax( player );
board[i] = 0;
++mv_cnt;
if( temp > best ) {
best = temp;
move = i;
}
}
}
}
else{
int pos;
while (1){
pos = rand()%9 + 1;
if (board[pos] != player){
move = pos;
break;
}
}
}
board[move] = cmp;
}
int score( int player ) {
int enemy = player == 1 ? 2 : 1;
for( int i=0; i<8; i++ ) {
if( board[ win_combos[i][0] ] == board[ win_combos[i][1] ]
and
board[ win_combos[i][1] ] == board[ win_combos[i][2] ] ) {
if( board[ win_combos[i][2] ] == player ) {
return 10;
} else if( board[ win_combos[i][2] ] == enemy ) {
return -10;
}
}
}
return 0;
}
int minimax( int player ) {
if( !running() ) {
return score( player );
}
int enemy = player == 1 ? 2 : 1;
int move = -1;
int best = -11;
int temp;
for( int i=1; i<=9; i++ ) {
if( board[i] == 0 ) {
board[i] = player;
--mv_cnt;
temp = -minimax( enemy );
board[i] = 0;
++mv_cnt;
if( temp > best ) {
best = temp;
move = i;
}
}
}
if( move == -1 ) {
return 0;
}
return best;
}
<|endoftext|> |
<commit_before>// Copyright 2019 The SwiftShader Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// This file contains LLVM stub functions - these are functions that are never
// called and are declared to satisfy the linker.
#include <assert.h>
#define STUB() assert(!"Stub function. Should not be called");
#include "llvm/Transforms/IPO/PassManagerBuilder.h"
namespace llvm
{
void PassManagerBuilder::addExtension(ExtensionPointTy Ty, ExtensionFn Fn) { STUB(); }
} // namespace llvm
<commit_msg>Fix warning treated as error<commit_after>// Copyright 2019 The SwiftShader Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// This file contains LLVM stub functions - these are functions that are never
// called and are declared to satisfy the linker.
#include <assert.h>
#define STUB() assert(false); // Stub function. Should not be called
#include "llvm/Transforms/IPO/PassManagerBuilder.h"
namespace llvm
{
void PassManagerBuilder::addExtension(ExtensionPointTy Ty, ExtensionFn Fn) { STUB(); }
} // namespace llvm
<|endoftext|> |
<commit_before>#include "specter/ViewResources.hpp"
namespace specter {
static logvisor::Module Log("specter::ViewResources");
void ViewResources::init(boo::IGraphicsDataFactory* factory, FontCache* fcache, const IThemeData* theme, float pf) {
if (!factory || !fcache || !theme)
Log.report(logvisor::Fatal, "all arguments of ViewResources::init() must be non-null");
m_pixelFactor = pf;
m_factory = factory;
m_theme = theme;
m_fcache = fcache;
unsigned dpi = 72.f * m_pixelFactor;
m_curveFont = fcache->prepCurvesFont(AllCharFilter, false, 8.f, dpi);
factory->commitTransaction([&](boo::IGraphicsDataFactory::Context& ctx) {
init(ctx, *theme, fcache);
return true;
} BooTrace);
}
void ViewResources::destroyResData() {
m_viewRes.destroy();
m_textRes.destroy();
m_splitRes.destroy();
m_toolbarRes.destroy();
m_buttonRes.destroy();
}
void ViewResources::prepFontCacheSync() {
unsigned dpi = 72.f * m_pixelFactor;
if (m_fcacheInterrupt.load())
return;
m_mainFont = m_fcache->prepMainFont(AllCharFilter, false, 10.f, dpi);
if (m_fcacheInterrupt.load())
return;
m_monoFont10 = m_fcache->prepMonoFont(AllCharFilter, false, 10.f, dpi);
if (m_fcacheInterrupt.load())
return;
m_monoFont18 = m_fcache->prepMonoFont(AllCharFilter, false, 18.f, dpi);
if (m_fcacheInterrupt.load())
return;
m_heading14 = m_fcache->prepMainFont(LatinAndJapaneseCharFilter, false, 14.f, dpi);
if (m_fcacheInterrupt.load())
return;
m_heading18 = m_fcache->prepMainFont(LatinAndJapaneseCharFilter, false, 18.f, dpi);
if (m_fcacheInterrupt.load())
return;
m_titleFont = m_fcache->prepMainFont(LatinCharFilter, false, 36.f, dpi);
if (m_fcacheInterrupt.load())
return;
m_fcache->closeBuiltinFonts();
m_fcacheReady.store(true);
}
void ViewResources::prepFontCacheAsync(boo::IWindow* window) {
m_fcacheReady.store(false);
m_fcacheThread = std::thread([this]() { prepFontCacheSync(); });
}
void ViewResources::resetPixelFactor(float pf) {
m_pixelFactor = pf;
unsigned dpi = 72.f * m_pixelFactor;
m_curveFont = m_fcache->prepCurvesFont(AllCharFilter, false, 8.f, dpi);
prepFontCacheSync();
}
void ViewResources::resetTheme(const IThemeData* theme) { m_theme = theme; }
} // namespace specter
<commit_msg>Asynchronous shader compilation<commit_after>#include "specter/ViewResources.hpp"
namespace specter {
static logvisor::Module Log("specter::ViewResources");
void ViewResources::init(boo::IGraphicsDataFactory* factory, FontCache* fcache, const IThemeData* theme, float pf) {
if (!factory || !fcache || !theme)
Log.report(logvisor::Fatal, "all arguments of ViewResources::init() must be non-null");
m_pixelFactor = pf;
m_factory = factory;
m_theme = theme;
m_fcache = fcache;
unsigned dpi = 72.f * m_pixelFactor;
m_curveFont = fcache->prepCurvesFont(AllCharFilter, false, 8.f, dpi);
factory->commitTransaction([&](boo::IGraphicsDataFactory::Context& ctx) {
init(ctx, *theme, fcache);
return true;
} BooTrace);
factory->waitUntilShadersReady();
}
void ViewResources::destroyResData() {
m_viewRes.destroy();
m_textRes.destroy();
m_splitRes.destroy();
m_toolbarRes.destroy();
m_buttonRes.destroy();
}
void ViewResources::prepFontCacheSync() {
unsigned dpi = 72.f * m_pixelFactor;
if (m_fcacheInterrupt.load())
return;
m_mainFont = m_fcache->prepMainFont(AllCharFilter, false, 10.f, dpi);
if (m_fcacheInterrupt.load())
return;
m_monoFont10 = m_fcache->prepMonoFont(AllCharFilter, false, 10.f, dpi);
if (m_fcacheInterrupt.load())
return;
m_monoFont18 = m_fcache->prepMonoFont(AllCharFilter, false, 18.f, dpi);
if (m_fcacheInterrupt.load())
return;
m_heading14 = m_fcache->prepMainFont(LatinAndJapaneseCharFilter, false, 14.f, dpi);
if (m_fcacheInterrupt.load())
return;
m_heading18 = m_fcache->prepMainFont(LatinAndJapaneseCharFilter, false, 18.f, dpi);
if (m_fcacheInterrupt.load())
return;
m_titleFont = m_fcache->prepMainFont(LatinCharFilter, false, 36.f, dpi);
if (m_fcacheInterrupt.load())
return;
m_fcache->closeBuiltinFonts();
m_fcacheReady.store(true);
}
void ViewResources::prepFontCacheAsync(boo::IWindow* window) {
m_fcacheReady.store(false);
m_fcacheThread = std::thread([this]() { prepFontCacheSync(); });
}
void ViewResources::resetPixelFactor(float pf) {
m_pixelFactor = pf;
unsigned dpi = 72.f * m_pixelFactor;
m_curveFont = m_fcache->prepCurvesFont(AllCharFilter, false, 8.f, dpi);
prepFontCacheSync();
}
void ViewResources::resetTheme(const IThemeData* theme) { m_theme = theme; }
} // namespace specter
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: printopt.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-08 18:47:23 $
*
* 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
*
************************************************************************/
#ifdef PCH
#include "core_pch.hxx"
#endif
#pragma hdrstop
#include <com/sun/star/uno/Any.hxx>
#include <com/sun/star/uno/Sequence.hxx>
#include "printopt.hxx"
#include "miscuno.hxx"
using namespace utl;
using namespace rtl;
using namespace com::sun::star::uno;
// -----------------------------------------------------------------------
TYPEINIT1(ScTpPrintItem, SfxPoolItem);
// -----------------------------------------------------------------------
ScPrintOptions::ScPrintOptions()
{
SetDefaults();
}
ScPrintOptions::ScPrintOptions( const ScPrintOptions& rCpy ) :
bSkipEmpty( rCpy.bSkipEmpty ),
bAllSheets( rCpy.bAllSheets )
{
}
ScPrintOptions::~ScPrintOptions()
{
}
void ScPrintOptions::SetDefaults()
{
bSkipEmpty = FALSE;
bAllSheets = TRUE;
}
const ScPrintOptions& ScPrintOptions::operator=( const ScPrintOptions& rCpy )
{
bSkipEmpty = rCpy.bSkipEmpty;
bAllSheets = rCpy.bAllSheets;
return *this;
}
inline int ScPrintOptions::operator==( const ScPrintOptions& rOpt ) const
{
return bSkipEmpty == rOpt.bSkipEmpty
&& bAllSheets == rOpt.bAllSheets;
}
inline int ScPrintOptions::operator!=( const ScPrintOptions& rOpt ) const
{
return !(operator==(rOpt));
}
// -----------------------------------------------------------------------
ScTpPrintItem::ScTpPrintItem( USHORT nWhich ) : SfxPoolItem( nWhich )
{
}
ScTpPrintItem::ScTpPrintItem( USHORT nWhich, const ScPrintOptions& rOpt ) :
SfxPoolItem ( nWhich ),
theOptions ( rOpt )
{
}
ScTpPrintItem::ScTpPrintItem( const ScTpPrintItem& rItem ) :
SfxPoolItem ( rItem ),
theOptions ( rItem.theOptions )
{
}
ScTpPrintItem::~ScTpPrintItem()
{
}
String ScTpPrintItem::GetValueText() const
{
return String::CreateFromAscii( "ScTpPrintItem" );
}
int ScTpPrintItem::operator==( const SfxPoolItem& rItem ) const
{
DBG_ASSERT( SfxPoolItem::operator==( rItem ), "unequal Which or Type" );
const ScTpPrintItem& rPItem = (const ScTpPrintItem&)rItem;
return ( theOptions == rPItem.theOptions );
}
SfxPoolItem* ScTpPrintItem::Clone( SfxItemPool * ) const
{
return new ScTpPrintItem( *this );
}
// -----------------------------------------------------------------------
#define CFGPATH_PRINT "Office.Calc/Print"
#define SCPRINTOPT_EMPTYPAGES 0
#define SCPRINTOPT_ALLSHEETS 1
#define SCPRINTOPT_COUNT 2
Sequence<OUString> ScPrintCfg::GetPropertyNames()
{
static const char* aPropNames[] =
{
"Page/EmptyPages", // SCPRINTOPT_EMPTYPAGES
"Other/AllSheets" // SCPRINTOPT_ALLSHEETS
};
Sequence<OUString> aNames(SCPRINTOPT_COUNT);
OUString* pNames = aNames.getArray();
for(int i = 0; i < SCPRINTOPT_COUNT; i++)
pNames[i] = OUString::createFromAscii(aPropNames[i]);
return aNames;
}
ScPrintCfg::ScPrintCfg() :
ConfigItem( OUString::createFromAscii( CFGPATH_PRINT ) )
{
Sequence<OUString> aNames = GetPropertyNames();
Sequence<Any> aValues = GetProperties(aNames);
// EnableNotification(aNames);
const Any* pValues = aValues.getConstArray();
DBG_ASSERT(aValues.getLength() == aNames.getLength(), "GetProperties failed")
if(aValues.getLength() == aNames.getLength())
{
for(int nProp = 0; nProp < aNames.getLength(); nProp++)
{
DBG_ASSERT(pValues[nProp].hasValue(), "property value missing")
if(pValues[nProp].hasValue())
{
switch(nProp)
{
case SCPRINTOPT_EMPTYPAGES:
// reversed
SetSkipEmpty( !ScUnoHelpFunctions::GetBoolFromAny( pValues[nProp] ) );
break;
case SCPRINTOPT_ALLSHEETS:
SetAllSheets( ScUnoHelpFunctions::GetBoolFromAny( pValues[nProp] ) );
break;
}
}
}
}
}
void ScPrintCfg::Commit()
{
Sequence<OUString> aNames = GetPropertyNames();
OUString* pNames = aNames.getArray();
Sequence<Any> aValues(aNames.getLength());
Any* pValues = aValues.getArray();
const Type& rType = ::getBooleanCppuType();
for(int nProp = 0; nProp < aNames.getLength(); nProp++)
{
switch(nProp)
{
case SCPRINTOPT_EMPTYPAGES:
// reversed
ScUnoHelpFunctions::SetBoolInAny( pValues[nProp], !GetSkipEmpty() );
break;
case SCPRINTOPT_ALLSHEETS:
ScUnoHelpFunctions::SetBoolInAny( pValues[nProp], GetAllSheets() );
break;
}
}
PutProperties(aNames, aValues);
}
void ScPrintCfg::SetOptions( const ScPrintOptions& rNew )
{
*(ScPrintOptions*)this = rNew;
SetModified();
}
void ScPrintCfg::OptionsChanged()
{
SetModified();
}
<commit_msg>INTEGRATION: CWS pchfix01 (1.3.214); FILE MERGED 2006/07/12 10:01:44 kaib 1.3.214.1: #i67080# Converted cxx files in sc, added initial project level pch and stripped old PCH definitions.<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: printopt.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: kz $ $Date: 2006-07-21 11:38:55 $
*
* 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
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sc.hxx"
#include <com/sun/star/uno/Any.hxx>
#include <com/sun/star/uno/Sequence.hxx>
#include "printopt.hxx"
#include "miscuno.hxx"
using namespace utl;
using namespace rtl;
using namespace com::sun::star::uno;
// -----------------------------------------------------------------------
TYPEINIT1(ScTpPrintItem, SfxPoolItem);
// -----------------------------------------------------------------------
ScPrintOptions::ScPrintOptions()
{
SetDefaults();
}
ScPrintOptions::ScPrintOptions( const ScPrintOptions& rCpy ) :
bSkipEmpty( rCpy.bSkipEmpty ),
bAllSheets( rCpy.bAllSheets )
{
}
ScPrintOptions::~ScPrintOptions()
{
}
void ScPrintOptions::SetDefaults()
{
bSkipEmpty = FALSE;
bAllSheets = TRUE;
}
const ScPrintOptions& ScPrintOptions::operator=( const ScPrintOptions& rCpy )
{
bSkipEmpty = rCpy.bSkipEmpty;
bAllSheets = rCpy.bAllSheets;
return *this;
}
inline int ScPrintOptions::operator==( const ScPrintOptions& rOpt ) const
{
return bSkipEmpty == rOpt.bSkipEmpty
&& bAllSheets == rOpt.bAllSheets;
}
inline int ScPrintOptions::operator!=( const ScPrintOptions& rOpt ) const
{
return !(operator==(rOpt));
}
// -----------------------------------------------------------------------
ScTpPrintItem::ScTpPrintItem( USHORT nWhich ) : SfxPoolItem( nWhich )
{
}
ScTpPrintItem::ScTpPrintItem( USHORT nWhich, const ScPrintOptions& rOpt ) :
SfxPoolItem ( nWhich ),
theOptions ( rOpt )
{
}
ScTpPrintItem::ScTpPrintItem( const ScTpPrintItem& rItem ) :
SfxPoolItem ( rItem ),
theOptions ( rItem.theOptions )
{
}
ScTpPrintItem::~ScTpPrintItem()
{
}
String ScTpPrintItem::GetValueText() const
{
return String::CreateFromAscii( "ScTpPrintItem" );
}
int ScTpPrintItem::operator==( const SfxPoolItem& rItem ) const
{
DBG_ASSERT( SfxPoolItem::operator==( rItem ), "unequal Which or Type" );
const ScTpPrintItem& rPItem = (const ScTpPrintItem&)rItem;
return ( theOptions == rPItem.theOptions );
}
SfxPoolItem* ScTpPrintItem::Clone( SfxItemPool * ) const
{
return new ScTpPrintItem( *this );
}
// -----------------------------------------------------------------------
#define CFGPATH_PRINT "Office.Calc/Print"
#define SCPRINTOPT_EMPTYPAGES 0
#define SCPRINTOPT_ALLSHEETS 1
#define SCPRINTOPT_COUNT 2
Sequence<OUString> ScPrintCfg::GetPropertyNames()
{
static const char* aPropNames[] =
{
"Page/EmptyPages", // SCPRINTOPT_EMPTYPAGES
"Other/AllSheets" // SCPRINTOPT_ALLSHEETS
};
Sequence<OUString> aNames(SCPRINTOPT_COUNT);
OUString* pNames = aNames.getArray();
for(int i = 0; i < SCPRINTOPT_COUNT; i++)
pNames[i] = OUString::createFromAscii(aPropNames[i]);
return aNames;
}
ScPrintCfg::ScPrintCfg() :
ConfigItem( OUString::createFromAscii( CFGPATH_PRINT ) )
{
Sequence<OUString> aNames = GetPropertyNames();
Sequence<Any> aValues = GetProperties(aNames);
// EnableNotification(aNames);
const Any* pValues = aValues.getConstArray();
DBG_ASSERT(aValues.getLength() == aNames.getLength(), "GetProperties failed")
if(aValues.getLength() == aNames.getLength())
{
for(int nProp = 0; nProp < aNames.getLength(); nProp++)
{
DBG_ASSERT(pValues[nProp].hasValue(), "property value missing")
if(pValues[nProp].hasValue())
{
switch(nProp)
{
case SCPRINTOPT_EMPTYPAGES:
// reversed
SetSkipEmpty( !ScUnoHelpFunctions::GetBoolFromAny( pValues[nProp] ) );
break;
case SCPRINTOPT_ALLSHEETS:
SetAllSheets( ScUnoHelpFunctions::GetBoolFromAny( pValues[nProp] ) );
break;
}
}
}
}
}
void ScPrintCfg::Commit()
{
Sequence<OUString> aNames = GetPropertyNames();
OUString* pNames = aNames.getArray();
Sequence<Any> aValues(aNames.getLength());
Any* pValues = aValues.getArray();
const Type& rType = ::getBooleanCppuType();
for(int nProp = 0; nProp < aNames.getLength(); nProp++)
{
switch(nProp)
{
case SCPRINTOPT_EMPTYPAGES:
// reversed
ScUnoHelpFunctions::SetBoolInAny( pValues[nProp], !GetSkipEmpty() );
break;
case SCPRINTOPT_ALLSHEETS:
ScUnoHelpFunctions::SetBoolInAny( pValues[nProp], GetAllSheets() );
break;
}
}
PutProperties(aNames, aValues);
}
void ScPrintCfg::SetOptions( const ScPrintOptions& rNew )
{
*(ScPrintOptions*)this = rNew;
SetModified();
}
void ScPrintCfg::OptionsChanged()
{
SetModified();
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: excdefs.hxx,v $
*
* $Revision: 1.44 $
*
* last change: $Author: obo $ $Date: 2004-08-11 09:04:12 $
*
* 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 _EXCDEFS_HXX
#define _EXCDEFS_HXX
#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif
// (0x001C) NOTE ==============================================================
#define EXC_NOTE5_MAXTEXT 2048
// (0x0031) FONT ==============================================================
// color
#define EXC_FONTCOL_IGNORE 0x7FFF
// height
#define EXC_FONTHGHT_COEFF 20.0
// (0x0092) PALETTE ===========================================================
// special color indices
#define EXC_COLIND_AUTOTEXT 77
#define EXC_COLIND_AUTOLINE 77
#define EXC_COLIND_AUTOFILLBG 77
#define EXC_COLIND_AUTOFILLFG 78
// (0x009B, 0x009D, 0x009E) AUTOFILTER ========================================
// flags
#define EXC_AFFLAG_AND 0x0000
#define EXC_AFFLAG_OR 0x0001
#define EXC_AFFLAG_ANDORMASK 0x0003
#define EXC_AFFLAG_SIMPLE1 0x0004
#define EXC_AFFLAG_SIMPLE2 0x0008
#define EXC_AFFLAG_TOP10 0x0010
#define EXC_AFFLAG_TOP10TOP 0x0020
#define EXC_AFFLAG_TOP10PERC 0x0040
// data types
#define EXC_AFTYPE_NOTUSED 0x00
#define EXC_AFTYPE_RK 0x02
#define EXC_AFTYPE_DOUBLE 0x04
#define EXC_AFTYPE_STRING 0x06
#define EXC_AFTYPE_BOOLERR 0x08
#define EXC_AFTYPE_INVALID 0x0A
#define EXC_AFTYPE_EMPTY 0x0C
#define EXC_AFTYPE_NOTEMPTY 0x0E
// comparison operands
#define EXC_AFOPER_NONE 0x00
#define EXC_AFOPER_LESS 0x01
#define EXC_AFOPER_EQUAL 0x02
#define EXC_AFOPER_LESSEQUAL 0x03
#define EXC_AFOPER_GREATER 0x04
#define EXC_AFOPER_NOTEQUAL 0x05
#define EXC_AFOPER_GREATEREQUAL 0x06
// (0x00AE, 0x00AF) SCENARIO, SCENMAN =========================================
#define EXC_SCEN_MAXCELL 32
// (0x00E5) CELLMERGING =======================================================
#define EXC_MERGE_MAXCOUNT 1024
// (0x0208) ROW ===============================================================
// flags
#define EXC_ROW_COLLAPSED 0x0010
#define EXC_ROW_ZEROHEIGHT 0x0020
#define EXC_ROW_UNSYNCED 0x0040
#define EXC_ROW_GHOSTDIRTY 0x0080
#define EXC_ROW_XFMASK 0x0FFF
// outline
#define EXC_ROW_LEVELFLAGS(nOL) (nOL & 0x0007)
#define EXC_ROW_GETLEVEL(nFlag) (nFlag & 0x0007)
// unknown, always save
#define EXC_ROW_FLAGCOMMON 0x0100
// row height
#define EXC_ROW_VALZEROHEIGHT 0x00FF
#define EXC_ROW_FLAGDEFHEIGHT 0x8000
// (0x0236) TABLE =============================================================
#define EXC_TABOP_CALCULATE 0x0003
#define EXC_TABOP_ROW 0x0004
#define EXC_TABOP_BOTH 0x0008
// (0x023E) WINDOW2 ===========================================================
#define EXC_WIN2_SHOWFORMULAS 0x0001
#define EXC_WIN2_SHOWGRID 0x0002
#define EXC_WIN2_SHOWHEADINGS 0x0004
#define EXC_WIN2_FROZEN 0x0008
#define EXC_WIN2_SHOWZEROS 0x0010
#define EXC_WIN2_DEFAULTCOLOR 0x0020
const sal_uInt16 EXC_WIN2_MIRRORED = 0x0040;
#define EXC_WIN2_OUTLINE 0x0080
#define EXC_WIN2_FROZENNOSPLIT 0x0100
#define EXC_WIN2_SELECTED 0x0200
#define EXC_WIN2_DISPLAYED 0x0400
// Specials for outlines ======================================================
#define EXC_OUTLINE_MAX 7
#define EXC_OUTLINE_COUNT (EXC_OUTLINE_MAX + 1)
// defines for change tracking ================================================
#define EXC_STREAM_USERNAMES CREATE_STRING( "User Names" )
#define EXC_STREAM_REVLOG CREATE_STRING( "Revision Log" )
// opcodes
#define EXC_CHTR_OP_COLFLAG 0x0001
#define EXC_CHTR_OP_DELFLAG 0x0002
#define EXC_CHTR_OP_INSROW 0x0000
#define EXC_CHTR_OP_INSCOL EXC_CHTR_OP_COLFLAG
#define EXC_CHTR_OP_DELROW EXC_CHTR_OP_DELFLAG
#define EXC_CHTR_OP_DELCOL (EXC_CHTR_OP_COLFLAG|EXC_CHTR_OP_DELFLAG)
#define EXC_CHTR_OP_MOVE 0x0004
#define EXC_CHTR_OP_INSTAB 0x0005
#define EXC_CHTR_OP_CELL 0x0008
#define EXC_CHTR_OP_RENAME 0x0009
#define EXC_CHTR_OP_NAME 0x000A
#define EXC_CHTR_OP_FORMAT 0x000B
#define EXC_CHTR_OP_UNKNOWN 0xFFFF
// data types
#define EXC_CHTR_TYPE_MASK 0x0007
#define EXC_CHTR_TYPE_FORMATMASK 0xFF00
#define EXC_CHTR_TYPE_EMPTY 0x0000
#define EXC_CHTR_TYPE_RK 0x0001
#define EXC_CHTR_TYPE_DOUBLE 0x0002
#define EXC_CHTR_TYPE_STRING 0x0003
#define EXC_CHTR_TYPE_BOOL 0x0004
#define EXC_CHTR_TYPE_FORMULA 0x0005
// accept flags
#define EXC_CHTR_NOTHING 0x0000
#define EXC_CHTR_ACCEPT 0x0001
#define EXC_CHTR_REJECT 0x0003
// ============================================================================
#endif // _EXCDEFS_HXX
<commit_msg>INTEGRATION: CWS dr20 (1.43.12); FILE MERGED 2004/08/18 11:35:33 dr 1.43.12.3: RESYNC: (1.43-1.44); FILE MERGED 2004/08/11 10:43:49 dr 1.43.12.2: #i12577# #i16277# #i24129# #i31482# #i24672# #i27407# #i30411# rework of cell table export - default row/column formats and shared formulas 2004/07/09 14:32:55 dr 1.43.12.1: #i30411# #i27407# export of def row format, step 1<commit_after>/*************************************************************************
*
* $RCSfile: excdefs.hxx,v $
*
* $Revision: 1.45 $
*
* last change: $Author: hr $ $Date: 2004-09-08 15:42:08 $
*
* 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 _EXCDEFS_HXX
#define _EXCDEFS_HXX
#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif
// (0x0031) FONT ==============================================================
// color
#define EXC_FONTCOL_IGNORE 0x7FFF
// height
#define EXC_FONTHGHT_COEFF 20.0
// (0x0092) PALETTE ===========================================================
// special color indices
#define EXC_COLIND_AUTOTEXT 77
#define EXC_COLIND_AUTOLINE 77
#define EXC_COLIND_AUTOFILLBG 77
#define EXC_COLIND_AUTOFILLFG 78
// (0x009B, 0x009D, 0x009E) AUTOFILTER ========================================
// flags
#define EXC_AFFLAG_AND 0x0000
#define EXC_AFFLAG_OR 0x0001
#define EXC_AFFLAG_ANDORMASK 0x0003
#define EXC_AFFLAG_SIMPLE1 0x0004
#define EXC_AFFLAG_SIMPLE2 0x0008
#define EXC_AFFLAG_TOP10 0x0010
#define EXC_AFFLAG_TOP10TOP 0x0020
#define EXC_AFFLAG_TOP10PERC 0x0040
// data types
#define EXC_AFTYPE_NOTUSED 0x00
#define EXC_AFTYPE_RK 0x02
#define EXC_AFTYPE_DOUBLE 0x04
#define EXC_AFTYPE_STRING 0x06
#define EXC_AFTYPE_BOOLERR 0x08
#define EXC_AFTYPE_INVALID 0x0A
#define EXC_AFTYPE_EMPTY 0x0C
#define EXC_AFTYPE_NOTEMPTY 0x0E
// comparison operands
#define EXC_AFOPER_NONE 0x00
#define EXC_AFOPER_LESS 0x01
#define EXC_AFOPER_EQUAL 0x02
#define EXC_AFOPER_LESSEQUAL 0x03
#define EXC_AFOPER_GREATER 0x04
#define EXC_AFOPER_NOTEQUAL 0x05
#define EXC_AFOPER_GREATEREQUAL 0x06
// (0x00AE, 0x00AF) SCENARIO, SCENMAN =========================================
#define EXC_SCEN_MAXCELL 32
// (0x023E) WINDOW2 ===========================================================
#define EXC_WIN2_SHOWFORMULAS 0x0001
#define EXC_WIN2_SHOWGRID 0x0002
#define EXC_WIN2_SHOWHEADINGS 0x0004
#define EXC_WIN2_FROZEN 0x0008
#define EXC_WIN2_SHOWZEROS 0x0010
#define EXC_WIN2_DEFAULTCOLOR 0x0020
const sal_uInt16 EXC_WIN2_MIRRORED = 0x0040;
#define EXC_WIN2_OUTLINE 0x0080
#define EXC_WIN2_FROZENNOSPLIT 0x0100
#define EXC_WIN2_SELECTED 0x0200
#define EXC_WIN2_DISPLAYED 0x0400
// defines for change tracking ================================================
#define EXC_STREAM_USERNAMES CREATE_STRING( "User Names" )
#define EXC_STREAM_REVLOG CREATE_STRING( "Revision Log" )
// opcodes
#define EXC_CHTR_OP_COLFLAG 0x0001
#define EXC_CHTR_OP_DELFLAG 0x0002
#define EXC_CHTR_OP_INSROW 0x0000
#define EXC_CHTR_OP_INSCOL EXC_CHTR_OP_COLFLAG
#define EXC_CHTR_OP_DELROW EXC_CHTR_OP_DELFLAG
#define EXC_CHTR_OP_DELCOL (EXC_CHTR_OP_COLFLAG|EXC_CHTR_OP_DELFLAG)
#define EXC_CHTR_OP_MOVE 0x0004
#define EXC_CHTR_OP_INSTAB 0x0005
#define EXC_CHTR_OP_CELL 0x0008
#define EXC_CHTR_OP_RENAME 0x0009
#define EXC_CHTR_OP_NAME 0x000A
#define EXC_CHTR_OP_FORMAT 0x000B
#define EXC_CHTR_OP_UNKNOWN 0xFFFF
// data types
#define EXC_CHTR_TYPE_MASK 0x0007
#define EXC_CHTR_TYPE_FORMATMASK 0xFF00
#define EXC_CHTR_TYPE_EMPTY 0x0000
#define EXC_CHTR_TYPE_RK 0x0001
#define EXC_CHTR_TYPE_DOUBLE 0x0002
#define EXC_CHTR_TYPE_STRING 0x0003
#define EXC_CHTR_TYPE_BOOL 0x0004
#define EXC_CHTR_TYPE_FORMULA 0x0005
// accept flags
#define EXC_CHTR_NOTHING 0x0000
#define EXC_CHTR_ACCEPT 0x0001
#define EXC_CHTR_REJECT 0x0003
// ============================================================================
#endif // _EXCDEFS_HXX
<|endoftext|> |
<commit_before><commit_msg>Fix on the protection against zero in MUON conversion<commit_after><|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: scuiexp.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: hr $ $Date: 2004-05-10 15:56:24 $
*
* 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 "scdlgfact.hxx"
namespace scui
{
static ScAbstractDialogFactory_Impl* pFactory=NULL;
ScAbstractDialogFactory_Impl* GetFactory()
{
if ( !pFactory )
pFactory = new ScAbstractDialogFactory_Impl;
//if ( !pSwResMgr)
// ScDialogsResMgr::GetResMgr();
return pFactory;
}
};
extern "C"
{
ScAbstractDialogFactory* CreateDialogFactory()
{
return ::scui::GetFactory();
}
}
<commit_msg>INTEGRATION: CWS tune03 (1.2.72); FILE MERGED 2004/07/08 16:45:04 mhu 1.2.72.1: #i29979# Added SC_DLLPUBLIC/PRIVATE (see scdllapi.h) to exported symbols/classes.<commit_after>/*************************************************************************
*
* $RCSfile: scuiexp.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2004-08-23 09:28:25 $
*
* 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): _______________________________________
*
*
************************************************************************/
#undef SC_DLLIMPLEMENTATION
#include "scdlgfact.hxx"
#ifndef _SAL_TYPES_H_
#include "sal/types.h"
#endif
namespace scui
{
static ScAbstractDialogFactory_Impl* pFactory=NULL;
ScAbstractDialogFactory_Impl* GetFactory()
{
if ( !pFactory )
pFactory = new ScAbstractDialogFactory_Impl;
//if ( !pSwResMgr)
// ScDialogsResMgr::GetResMgr();
return pFactory;
}
};
extern "C"
{
SAL_DLLPUBLIC_EXPORT ScAbstractDialogFactory* CreateDialogFactory()
{
return ::scui::GetFactory();
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: docsh2.cxx,v $
*
* $Revision: 1.19 $
*
* last change: $Author: kz $ $Date: 2006-07-21 13:37:44 $
*
* 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
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sc.hxx"
#ifndef _SVDPAGE_HXX //autogen
#include <svx/svdpage.hxx>
#endif
#include <svx/xtable.hxx>
#include "scitems.hxx"
#include <tools/gen.hxx>
#include <svtools/ctrltool.hxx>
#include <svx/flstitem.hxx>
#include <svx/drawitem.hxx>
#include <sfx2/printer.hxx>
#include <svtools/smplhint.hxx>
#include <svx/svditer.hxx>
#include <svx/svdobj.hxx>
#include <svx/svdoole2.hxx>
#include <vcl/svapp.hxx>
#include <svx/asiancfg.hxx>
#include <svx/forbiddencharacterstable.hxx>
#include <svx/unolingu.hxx>
#include <rtl/logfile.hxx>
// INCLUDE ---------------------------------------------------------------
/*
#include <svdrwetc.hxx>
#include <svdrwobx.hxx>
#include <sostor.hxx>
*/
#include "drwlayer.hxx"
#include "stlpool.hxx"
#include "docsh.hxx"
#include "docfunc.hxx"
#include "sc.hrc"
using namespace com::sun::star;
//------------------------------------------------------------------
BOOL __EXPORT ScDocShell::InitNew( const uno::Reference < embed::XStorage >& xStor )
{
RTL_LOGFILE_CONTEXT_AUTHOR ( aLog, "sc", "nn93723", "ScDocShell::InitNew" );
BOOL bRet = SfxObjectShell::InitNew( xStor );
aDocument.MakeTable(0);
// zusaetzliche Tabellen werden von der ersten View angelegt,
// wenn bIsEmpty dann noch TRUE ist
if( bRet )
{
Size aSize( (long) ( STD_COL_WIDTH * HMM_PER_TWIPS * OLE_STD_CELLS_X ),
(long) ( ScGlobal::nStdRowHeight * HMM_PER_TWIPS * OLE_STD_CELLS_Y ) );
// hier muss auch der Start angepasst werden
SetVisAreaOrSize( Rectangle( Point(), aSize ), TRUE );
}
// InitOptions sets the document languages, must be called before CreateStandardStyles
InitOptions();
aDocument.GetStyleSheetPool()->CreateStandardStyles();
aDocument.UpdStlShtPtrsFrmNms();
// SetDocumentModified ist in Load/InitNew nicht mehr erlaubt!
InitItems();
CalcOutputFactor();
return bRet;
}
//------------------------------------------------------------------
BOOL ScDocShell::IsEmpty() const
{
return bIsEmpty;
}
void ScDocShell::ResetEmpty()
{
bIsEmpty = FALSE;
}
//------------------------------------------------------------------
void ScDocShell::InitItems()
{
// AllItemSet fuer Controller mit benoetigten Items fuellen:
// if ( pFontList )
// delete pFontList;
// Druck-Optionen werden beim Drucken und evtl. in GetPrinter gesetzt
// pFontList = new FontList( GetPrinter(), Application::GetDefaultDevice() );
//PutItem( SvxFontListItem( pFontList, SID_ATTR_CHAR_FONTLIST ) );
UpdateFontList();
ScDrawLayer* pDrawLayer = aDocument.GetDrawLayer();
if (pDrawLayer)
{
PutItem( SvxColorTableItem ( pDrawLayer->GetColorTable() ) );
PutItem( SvxGradientListItem( pDrawLayer->GetGradientList() ) );
PutItem( SvxHatchListItem ( pDrawLayer->GetHatchList() ) );
PutItem( SvxBitmapListItem ( pDrawLayer->GetBitmapList() ) );
PutItem( SvxDashListItem ( pDrawLayer->GetDashList() ) );
PutItem( SvxLineEndListItem ( pDrawLayer->GetLineEndList() ) );
// andere Anpassungen nach dem Anlegen des DrawLayers
pDrawLayer->SetNotifyUndoActionHdl( LINK( pDocFunc, ScDocFunc, NotifyDrawUndo ) );
//if (SfxObjectShell::HasSbxObject())
pDrawLayer->UpdateBasic(); // DocShell-Basic in DrawPages setzen
}
else
{
// always use global color table instead of local copy
PutItem( SvxColorTableItem( XColorTable::GetStdColorTable() ) );
}
if ( !aDocument.GetForbiddenCharacters().isValid() ||
!aDocument.IsValidAsianCompression() || !aDocument.IsValidAsianKerning() )
{
// get settings from SvxAsianConfig
SvxAsianConfig aAsian( sal_False );
if ( !aDocument.GetForbiddenCharacters().isValid() )
{
// set forbidden characters if necessary
uno::Sequence<lang::Locale> aLocales = aAsian.GetStartEndCharLocales();
if (aLocales.getLength())
{
vos::ORef<SvxForbiddenCharactersTable> xForbiddenTable =
new SvxForbiddenCharactersTable( aDocument.GetServiceManager() );
const lang::Locale* pLocales = aLocales.getConstArray();
for (sal_Int32 i = 0; i < aLocales.getLength(); i++)
{
i18n::ForbiddenCharacters aForbidden;
aAsian.GetStartEndChars( pLocales[i], aForbidden.beginLine, aForbidden.endLine );
LanguageType eLang = SvxLocaleToLanguage(pLocales[i]);
//pDoc->SetForbiddenCharacters( eLang, aForbidden );
xForbiddenTable->SetForbiddenCharacters( eLang, aForbidden );
}
aDocument.SetForbiddenCharacters( xForbiddenTable );
}
}
if ( !aDocument.IsValidAsianCompression() )
{
// set compression mode from configuration if not already set (e.g. XML import)
aDocument.SetAsianCompression( aAsian.GetCharDistanceCompression() );
}
if ( !aDocument.IsValidAsianKerning() )
{
// set asian punctuation kerning from configuration if not already set (e.g. XML import)
aDocument.SetAsianKerning( !aAsian.IsKerningWesternTextOnly() ); // reversed
}
}
}
//------------------------------------------------------------------
void ScDocShell::ResetDrawObjectShell()
{
ScDrawLayer* pDrawLayer = aDocument.GetDrawLayer();
if (pDrawLayer)
pDrawLayer->SetObjectShell( NULL );
}
//------------------------------------------------------------------
void __EXPORT ScDocShell::Activate()
{
}
void __EXPORT ScDocShell::Deactivate()
{
}
//------------------------------------------------------------------
ScDrawLayer* ScDocShell::MakeDrawLayer()
{
ScDrawLayer* pDrawLayer = aDocument.GetDrawLayer();
if (!pDrawLayer)
{
RTL_LOGFILE_CONTEXT_AUTHOR ( aLog, "sc", "nn93723", "ScDocShell::MakeDrawLayer" );
aDocument.InitDrawLayer(this);
pDrawLayer = aDocument.GetDrawLayer();
InitItems(); // incl. Undo und Basic
Broadcast( SfxSimpleHint( SC_HINT_DRWLAYER_NEW ) );
if (nDocumentLock)
pDrawLayer->setLock(TRUE);
}
return pDrawLayer;
}
//------------------------------------------------------------------
void ScDocShell::RemoveUnknownObjects()
{
// OLE-Objekte loeschen, wenn kein Drawing-Objekt dazu existiert
// Loeschen wie in SvPersist::CleanUp
ScDrawLayer* pDrawLayer = aDocument.GetDrawLayer();
uno::Sequence < rtl::OUString > aNames = GetEmbeddedObjectContainer().GetObjectNames();
for( sal_Int32 i=0; i<aNames.getLength(); i++ )
{
String aObjName = aNames[i];
BOOL bFound = FALSE;
if ( pDrawLayer )
{
SCTAB nTabCount = static_cast<sal_Int16>(pDrawLayer->GetPageCount());
for (SCTAB nTab=0; nTab<nTabCount && !bFound; nTab++)
{
SdrPage* pPage = pDrawLayer->GetPage(static_cast<sal_uInt16>(nTab));
DBG_ASSERT(pPage,"Page ?");
if (pPage)
{
SdrObjListIter aIter( *pPage, IM_DEEPNOGROUPS );
SdrObject* pObject = aIter.Next();
while (pObject && !bFound)
{
// name from InfoObject is PersistName
if ( pObject->ISA(SdrOle2Obj) &&
static_cast<SdrOle2Obj*>(pObject)->GetPersistName() == aObjName )
bFound = TRUE;
pObject = aIter.Next();
}
}
}
}
if (!bFound)
{
//TODO/LATER: hacks not supported anymore
//DBG_ASSERT(pEle->GetRefCount()==2, "Loeschen von referenziertem Storage");
GetEmbeddedObjectContainer().RemoveEmbeddedObject( aObjName );
}
else
i++;
}
}
<commit_msg>INTEGRATION: CWS asyncdialogs (1.17.122); FILE MERGED 2006/08/30 15:40:22 pb 1.17.122.4: RESYNC: (1.18-1.19); FILE MERGED 2006/06/01 05:24:11 pb 1.17.122.3: fix: #i57125# pFontList moved to pImpl 2006/05/31 13:56:52 pb 1.17.122.2: RESYNC: (1.17-1.18); FILE MERGED 2006/03/01 09:47:41 pb 1.17.122.1: fix: #i57125# use DocShell_Impl*<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: docsh2.cxx,v $
*
* $Revision: 1.20 $
*
* last change: $Author: vg $ $Date: 2006-11-22 10:45:32 $
*
* 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
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sc.hxx"
#ifndef _SVDPAGE_HXX //autogen
#include <svx/svdpage.hxx>
#endif
#include <svx/xtable.hxx>
#include "scitems.hxx"
#include <tools/gen.hxx>
#include <svtools/ctrltool.hxx>
#include <svx/flstitem.hxx>
#include <svx/drawitem.hxx>
#include <sfx2/printer.hxx>
#include <svtools/smplhint.hxx>
#include <svx/svditer.hxx>
#include <svx/svdobj.hxx>
#include <svx/svdoole2.hxx>
#include <vcl/svapp.hxx>
#include <svx/asiancfg.hxx>
#include <svx/forbiddencharacterstable.hxx>
#include <svx/unolingu.hxx>
#include <rtl/logfile.hxx>
// INCLUDE ---------------------------------------------------------------
/*
#include <svdrwetc.hxx>
#include <svdrwobx.hxx>
#include <sostor.hxx>
*/
#include "drwlayer.hxx"
#include "stlpool.hxx"
#include "docsh.hxx"
#include "docshimp.hxx"
#include "docfunc.hxx"
#include "sc.hrc"
using namespace com::sun::star;
//------------------------------------------------------------------
BOOL __EXPORT ScDocShell::InitNew( const uno::Reference < embed::XStorage >& xStor )
{
RTL_LOGFILE_CONTEXT_AUTHOR ( aLog, "sc", "nn93723", "ScDocShell::InitNew" );
BOOL bRet = SfxObjectShell::InitNew( xStor );
aDocument.MakeTable(0);
// zusaetzliche Tabellen werden von der ersten View angelegt,
// wenn bIsEmpty dann noch TRUE ist
if( bRet )
{
Size aSize( (long) ( STD_COL_WIDTH * HMM_PER_TWIPS * OLE_STD_CELLS_X ),
(long) ( ScGlobal::nStdRowHeight * HMM_PER_TWIPS * OLE_STD_CELLS_Y ) );
// hier muss auch der Start angepasst werden
SetVisAreaOrSize( Rectangle( Point(), aSize ), TRUE );
}
// InitOptions sets the document languages, must be called before CreateStandardStyles
InitOptions();
aDocument.GetStyleSheetPool()->CreateStandardStyles();
aDocument.UpdStlShtPtrsFrmNms();
// SetDocumentModified ist in Load/InitNew nicht mehr erlaubt!
InitItems();
CalcOutputFactor();
return bRet;
}
//------------------------------------------------------------------
BOOL ScDocShell::IsEmpty() const
{
return bIsEmpty;
}
void ScDocShell::ResetEmpty()
{
bIsEmpty = FALSE;
}
//------------------------------------------------------------------
void ScDocShell::InitItems()
{
// AllItemSet fuer Controller mit benoetigten Items fuellen:
// if ( pImpl->pFontList )
// delete pImpl->pFontList;
// Druck-Optionen werden beim Drucken und evtl. in GetPrinter gesetzt
// pImpl->pFontList = new FontList( GetPrinter(), Application::GetDefaultDevice() );
//PutItem( SvxFontListItem( pImpl->pFontList, SID_ATTR_CHAR_FONTLIST ) );
UpdateFontList();
ScDrawLayer* pDrawLayer = aDocument.GetDrawLayer();
if (pDrawLayer)
{
PutItem( SvxColorTableItem ( pDrawLayer->GetColorTable() ) );
PutItem( SvxGradientListItem( pDrawLayer->GetGradientList() ) );
PutItem( SvxHatchListItem ( pDrawLayer->GetHatchList() ) );
PutItem( SvxBitmapListItem ( pDrawLayer->GetBitmapList() ) );
PutItem( SvxDashListItem ( pDrawLayer->GetDashList() ) );
PutItem( SvxLineEndListItem ( pDrawLayer->GetLineEndList() ) );
// andere Anpassungen nach dem Anlegen des DrawLayers
pDrawLayer->SetNotifyUndoActionHdl( LINK( pDocFunc, ScDocFunc, NotifyDrawUndo ) );
//if (SfxObjectShell::HasSbxObject())
pDrawLayer->UpdateBasic(); // DocShell-Basic in DrawPages setzen
}
else
{
// always use global color table instead of local copy
PutItem( SvxColorTableItem( XColorTable::GetStdColorTable() ) );
}
if ( !aDocument.GetForbiddenCharacters().isValid() ||
!aDocument.IsValidAsianCompression() || !aDocument.IsValidAsianKerning() )
{
// get settings from SvxAsianConfig
SvxAsianConfig aAsian( sal_False );
if ( !aDocument.GetForbiddenCharacters().isValid() )
{
// set forbidden characters if necessary
uno::Sequence<lang::Locale> aLocales = aAsian.GetStartEndCharLocales();
if (aLocales.getLength())
{
vos::ORef<SvxForbiddenCharactersTable> xForbiddenTable =
new SvxForbiddenCharactersTable( aDocument.GetServiceManager() );
const lang::Locale* pLocales = aLocales.getConstArray();
for (sal_Int32 i = 0; i < aLocales.getLength(); i++)
{
i18n::ForbiddenCharacters aForbidden;
aAsian.GetStartEndChars( pLocales[i], aForbidden.beginLine, aForbidden.endLine );
LanguageType eLang = SvxLocaleToLanguage(pLocales[i]);
//pDoc->SetForbiddenCharacters( eLang, aForbidden );
xForbiddenTable->SetForbiddenCharacters( eLang, aForbidden );
}
aDocument.SetForbiddenCharacters( xForbiddenTable );
}
}
if ( !aDocument.IsValidAsianCompression() )
{
// set compression mode from configuration if not already set (e.g. XML import)
aDocument.SetAsianCompression( aAsian.GetCharDistanceCompression() );
}
if ( !aDocument.IsValidAsianKerning() )
{
// set asian punctuation kerning from configuration if not already set (e.g. XML import)
aDocument.SetAsianKerning( !aAsian.IsKerningWesternTextOnly() ); // reversed
}
}
}
//------------------------------------------------------------------
void ScDocShell::ResetDrawObjectShell()
{
ScDrawLayer* pDrawLayer = aDocument.GetDrawLayer();
if (pDrawLayer)
pDrawLayer->SetObjectShell( NULL );
}
//------------------------------------------------------------------
void __EXPORT ScDocShell::Activate()
{
}
void __EXPORT ScDocShell::Deactivate()
{
}
//------------------------------------------------------------------
ScDrawLayer* ScDocShell::MakeDrawLayer()
{
ScDrawLayer* pDrawLayer = aDocument.GetDrawLayer();
if (!pDrawLayer)
{
RTL_LOGFILE_CONTEXT_AUTHOR ( aLog, "sc", "nn93723", "ScDocShell::MakeDrawLayer" );
aDocument.InitDrawLayer(this);
pDrawLayer = aDocument.GetDrawLayer();
InitItems(); // incl. Undo und Basic
Broadcast( SfxSimpleHint( SC_HINT_DRWLAYER_NEW ) );
if (nDocumentLock)
pDrawLayer->setLock(TRUE);
}
return pDrawLayer;
}
//------------------------------------------------------------------
void ScDocShell::RemoveUnknownObjects()
{
// OLE-Objekte loeschen, wenn kein Drawing-Objekt dazu existiert
// Loeschen wie in SvPersist::CleanUp
ScDrawLayer* pDrawLayer = aDocument.GetDrawLayer();
uno::Sequence < rtl::OUString > aNames = GetEmbeddedObjectContainer().GetObjectNames();
for( sal_Int32 i=0; i<aNames.getLength(); i++ )
{
String aObjName = aNames[i];
BOOL bFound = FALSE;
if ( pDrawLayer )
{
SCTAB nTabCount = static_cast<sal_Int16>(pDrawLayer->GetPageCount());
for (SCTAB nTab=0; nTab<nTabCount && !bFound; nTab++)
{
SdrPage* pPage = pDrawLayer->GetPage(static_cast<sal_uInt16>(nTab));
DBG_ASSERT(pPage,"Page ?");
if (pPage)
{
SdrObjListIter aIter( *pPage, IM_DEEPNOGROUPS );
SdrObject* pObject = aIter.Next();
while (pObject && !bFound)
{
// name from InfoObject is PersistName
if ( pObject->ISA(SdrOle2Obj) &&
static_cast<SdrOle2Obj*>(pObject)->GetPersistName() == aObjName )
bFound = TRUE;
pObject = aIter.Next();
}
}
}
}
if (!bFound)
{
//TODO/LATER: hacks not supported anymore
//DBG_ASSERT(pEle->GetRefCount()==2, "Loeschen von referenziertem Storage");
GetEmbeddedObjectContainer().RemoveEmbeddedObject( aObjName );
}
else
i++;
}
}
<|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/.
*/
#define USE_CPPUNIT 1
#include "test/xmldiff.hxx"
#include <libxml/xpath.h>
#include <libxml/parser.h>
#include <libxml/tree.h>
#include <libxml/xmlmemory.h>
#include <set>
#include <cstring>
#include <sstream>
#include <cmath>
#include <cassert>
#if USE_CPPUNIT
#include <cppunit/extensions/HelperMacros.h>
#endif
#include <rtl/math.hxx>
struct tolerance
{
~tolerance()
{
xmlFree(elementName);
xmlFree(attribName);
}
tolerance()
: elementName(NULL)
, attribName(NULL)
, relative(false)
, value(0.0)
{
}
tolerance(const tolerance& tol)
{
elementName = xmlStrdup(tol.elementName);
attribName = xmlStrdup(tol.attribName);
relative = tol.relative;
value = tol.value;
}
xmlChar* elementName;
xmlChar* attribName;
bool relative;
double value;
bool operator==(const tolerance& rTol) const { return xmlStrEqual(elementName, rTol.elementName) && xmlStrEqual(attribName, rTol.attribName); }
bool operator<(const tolerance& rTol) const
{
int cmp = xmlStrcmp(elementName, rTol.elementName);
if(cmp == 0)
{
cmp = xmlStrcmp(attribName, rTol.attribName);
}
if(cmp>=0)
return false;
else
return true;
}
};
class XMLDiff
{
public:
XMLDiff(const char* pFileName, const char* pContent, int size, const char* pToleranceFileName);
~XMLDiff();
bool compare();
private:
typedef std::set<tolerance> ToleranceContainer;
void loadToleranceFile(xmlDocPtr xmlTolerance);
bool compareAttributes(xmlNodePtr node1, xmlNodePtr node2);
bool compareElements(xmlNodePtr node1, xmlNodePtr node2);
/// Error message for cppunit that prints out when expected and found are not equal.
void cppunitAssertEqual(const xmlChar *expected, const xmlChar *found);
/// Error message for cppunit that prints out when expected and found are not equal - for doubles.
void cppunitAssertEqualDouble(const xmlChar *node, double expected, double found, double delta);
ToleranceContainer toleranceContainer;
xmlDocPtr xmlFile1;
xmlDocPtr xmlFile2;
std::string fileName;
};
XMLDiff::XMLDiff( const char* pFileName, const char* pContent, int size, const char* pToleranceFile)
: fileName(pFileName)
{
xmlFile1 = xmlParseFile(pFileName);
xmlFile2 = xmlParseMemory(pContent, size);
if(pToleranceFile)
{
xmlDocPtr xmlToleranceFile = xmlParseFile(pToleranceFile);
loadToleranceFile(xmlToleranceFile);
xmlFreeDoc(xmlToleranceFile);
}
}
XMLDiff::~XMLDiff()
{
xmlFreeDoc(xmlFile1);
xmlFreeDoc(xmlFile2);
}
namespace {
void readAttributesForTolerance(xmlNodePtr node, tolerance& tol)
{
xmlChar* elementName = xmlGetProp(node, BAD_CAST("elementName"));
tol.elementName = elementName;
xmlChar* attribName = xmlGetProp(node, BAD_CAST("attribName"));
tol.attribName = attribName;
xmlChar* value = xmlGetProp(node, BAD_CAST("value"));
double val = xmlXPathCastStringToNumber(value);
xmlFree(value);
tol.value = val;
xmlChar* relative = xmlGetProp(node, BAD_CAST("relative"));
bool rel = false;
if(xmlStrEqual(relative, BAD_CAST("true")))
rel = true;
xmlFree(relative);
tol.relative = rel;
}
}
void XMLDiff::loadToleranceFile(xmlDocPtr xmlToleranceFile)
{
xmlNodePtr root = xmlDocGetRootElement(xmlToleranceFile);
#if USE_CPPUNIT
CPPUNIT_ASSERT_MESSAGE("did not find correct tolerance file", xmlStrEqual( root->name, BAD_CAST("tolerances") ));
#else
if(!xmlStrEqual( root->name, BAD_CAST("tolerances") ))
{
assert(false);
return;
}
#endif
xmlNodePtr child = NULL;
for (child = root->children; child != NULL; child = child->next)
{
// assume a valid xml file
if(child->type != XML_ELEMENT_NODE)
continue;
assert(xmlStrEqual(child->name, BAD_CAST("tolerance")));
tolerance tol;
readAttributesForTolerance(child, tol);
toleranceContainer.insert(tol);
}
}
bool XMLDiff::compare()
{
xmlNode* root1 = xmlDocGetRootElement(xmlFile1);
xmlNode* root2 = xmlDocGetRootElement(xmlFile2);
#if USE_CPPUNIT
CPPUNIT_ASSERT(root1);
CPPUNIT_ASSERT(root2);
cppunitAssertEqual(root1->name, root2->name);
#else
if (!root1 || !root2)
return false;
if(!xmlStrEqual(root1->name, root2->name))
return false;
#endif
return compareElements(root1, root2);
}
namespace {
bool checkForEmptyChildren(xmlNodePtr node)
{
if(!node)
return true;
for(; node != NULL; node = node->next)
{
if (node->type == XML_ELEMENT_NODE)
return false;
}
return true;
}
}
bool XMLDiff::compareElements(xmlNode* node1, xmlNode* node2)
{
#if USE_CPPUNIT
cppunitAssertEqual(node1->name, node2->name);
#else
if (!xmlStrEqual( node1->name, node2->name ))
return false;
#endif
//compare attributes
bool sameAttribs = compareAttributes(node1, node2);
#if USE_CPPUNIT
CPPUNIT_ASSERT(sameAttribs);
#else
if (!sameAttribs)
return false;
#endif
// compare children
xmlNode* child2 = NULL;
xmlNode* child1 = NULL;
for(child1 = node1->children, child2 = node2->children; child1 != NULL && child2 != NULL; child1 = child1->next, child2 = child2->next)
{
if (child1->type == XML_ELEMENT_NODE)
{
bool bCompare = compareElements(child1, child2);
if(!bCompare)
{
return false;
}
}
}
#if USE_CPPUNIT
CPPUNIT_ASSERT(checkForEmptyChildren(child1));
CPPUNIT_ASSERT(checkForEmptyChildren(child2));
#else
if(!checkForEmptyChildren(child1) || !checkForEmptyChildren(child2))
return false;
#endif
return true;
}
void XMLDiff::cppunitAssertEqual(const xmlChar *expected, const xmlChar *found)
{
#if USE_CPPUNIT
std::stringstream stringStream;
stringStream << "Reference: " << fileName << "\n- Expected: " << (const char*) expected << "\n- Found: " << (const char*) found;
CPPUNIT_ASSERT_MESSAGE(stringStream.str(), xmlStrEqual(expected, found));
#endif
}
void XMLDiff::cppunitAssertEqualDouble(const xmlChar *node, double expected, double found, double delta)
{
#if USE_CPPUNIT
std::stringstream stringStream;
stringStream << "Reference: " << fileName << "\n- Node: " << (const char*) node;
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(stringStream.str(), expected, found, delta);
#endif
}
namespace {
bool compareValuesWithTolerance(double val1, double val2, double tolerance, bool relative)
{
if(relative)
{
return (val1/tolerance) <= val2 && val2 <= (val1*tolerance);
}
else
{
return (val1 - tolerance) <= val2 && val2 <= (val1 + tolerance);
}
}
}
bool XMLDiff::compareAttributes(xmlNodePtr node1, xmlNodePtr node2)
{
xmlAttrPtr attr1 = NULL;
xmlAttrPtr attr2 = NULL;
for(attr1 = node1->properties, attr2 = node2->properties; attr1 != NULL && attr2 != NULL; attr1 = attr1->next, attr2 = attr2->next)
{
#if USE_CPPUNIT
cppunitAssertEqual(attr1->name, attr2->name);
#else
if (!xmlStrEqual( attr1->name, attr2->name ))
return false;
#endif
xmlChar* val1 = xmlGetProp(node1, attr1->name);
xmlChar* val2 = xmlGetProp(node2, attr2->name);
double dVal1 = xmlXPathCastStringToNumber(val1);
double dVal2 = xmlXPathCastStringToNumber(val2);
if(!rtl::math::isNan(dVal1) || !rtl::math::isNan(dVal2))
{
//compare by value and respect tolerance
tolerance tol;
tol.elementName = xmlStrdup(node1->name);
tol.attribName = xmlStrdup(attr1->name);
ToleranceContainer::iterator itr = toleranceContainer.find( tol );
bool useTolerance = false;
if (itr != toleranceContainer.end())
{
useTolerance = true;
}
if (useTolerance)
{
bool valInTolerance = compareValuesWithTolerance(dVal1, dVal2, itr->value, itr->relative);
#if USE_CPPUNIT
std::stringstream stringStream("Expected Value: ");
stringStream << dVal1 << "; Found Value: " << dVal2 << "; Tolerance: " << itr->value;
stringStream << "; Relative: " << itr->relative;
CPPUNIT_ASSERT_MESSAGE(stringStream.str(), valInTolerance);
#else
if (!valInTolerance)
return false;
#endif
}
else
{
#if USE_CPPUNIT
cppunitAssertEqualDouble(attr1->name, dVal1, dVal2, 1e-08);
#else
if (dVal1 != dVal2)
return false;
#endif
}
}
else
{
#if USE_CPPUNIT
cppunitAssertEqual(val1, val2);
#else
if(!xmlStrEqual( val1, val2 ))
return false;
#endif
}
xmlFree(val1);
xmlFree(val2);
}
// unequal number of attributes
#ifdef CPPUNIT_ASSERT
CPPUNIT_ASSERT(!attr1);
CPPUNIT_ASSERT(!attr2);
#else
if (attr1 || attr2)
return false;
#endif
return true;
}
bool
doXMLDiff(char const*const pFileName, char const*const pContent, int const size,
char const*const pToleranceFileName)
{
XMLDiff aDiff(pFileName, pContent, size, pToleranceFileName);
return aDiff.compare();
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Remove unused function<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/.
*/
#define USE_CPPUNIT 1
#include "test/xmldiff.hxx"
#include <libxml/xpath.h>
#include <libxml/parser.h>
#include <libxml/tree.h>
#include <libxml/xmlmemory.h>
#include <set>
#include <cstring>
#include <sstream>
#include <cmath>
#include <cassert>
#if USE_CPPUNIT
#include <cppunit/extensions/HelperMacros.h>
#endif
#include <rtl/math.hxx>
struct tolerance
{
~tolerance()
{
xmlFree(elementName);
xmlFree(attribName);
}
tolerance()
: elementName(NULL)
, attribName(NULL)
, relative(false)
, value(0.0)
{
}
tolerance(const tolerance& tol)
{
elementName = xmlStrdup(tol.elementName);
attribName = xmlStrdup(tol.attribName);
relative = tol.relative;
value = tol.value;
}
xmlChar* elementName;
xmlChar* attribName;
bool relative;
double value;
bool operator<(const tolerance& rTol) const
{
int cmp = xmlStrcmp(elementName, rTol.elementName);
if(cmp == 0)
{
cmp = xmlStrcmp(attribName, rTol.attribName);
}
if(cmp>=0)
return false;
else
return true;
}
};
class XMLDiff
{
public:
XMLDiff(const char* pFileName, const char* pContent, int size, const char* pToleranceFileName);
~XMLDiff();
bool compare();
private:
typedef std::set<tolerance> ToleranceContainer;
void loadToleranceFile(xmlDocPtr xmlTolerance);
bool compareAttributes(xmlNodePtr node1, xmlNodePtr node2);
bool compareElements(xmlNodePtr node1, xmlNodePtr node2);
/// Error message for cppunit that prints out when expected and found are not equal.
void cppunitAssertEqual(const xmlChar *expected, const xmlChar *found);
/// Error message for cppunit that prints out when expected and found are not equal - for doubles.
void cppunitAssertEqualDouble(const xmlChar *node, double expected, double found, double delta);
ToleranceContainer toleranceContainer;
xmlDocPtr xmlFile1;
xmlDocPtr xmlFile2;
std::string fileName;
};
XMLDiff::XMLDiff( const char* pFileName, const char* pContent, int size, const char* pToleranceFile)
: fileName(pFileName)
{
xmlFile1 = xmlParseFile(pFileName);
xmlFile2 = xmlParseMemory(pContent, size);
if(pToleranceFile)
{
xmlDocPtr xmlToleranceFile = xmlParseFile(pToleranceFile);
loadToleranceFile(xmlToleranceFile);
xmlFreeDoc(xmlToleranceFile);
}
}
XMLDiff::~XMLDiff()
{
xmlFreeDoc(xmlFile1);
xmlFreeDoc(xmlFile2);
}
namespace {
void readAttributesForTolerance(xmlNodePtr node, tolerance& tol)
{
xmlChar* elementName = xmlGetProp(node, BAD_CAST("elementName"));
tol.elementName = elementName;
xmlChar* attribName = xmlGetProp(node, BAD_CAST("attribName"));
tol.attribName = attribName;
xmlChar* value = xmlGetProp(node, BAD_CAST("value"));
double val = xmlXPathCastStringToNumber(value);
xmlFree(value);
tol.value = val;
xmlChar* relative = xmlGetProp(node, BAD_CAST("relative"));
bool rel = false;
if(xmlStrEqual(relative, BAD_CAST("true")))
rel = true;
xmlFree(relative);
tol.relative = rel;
}
}
void XMLDiff::loadToleranceFile(xmlDocPtr xmlToleranceFile)
{
xmlNodePtr root = xmlDocGetRootElement(xmlToleranceFile);
#if USE_CPPUNIT
CPPUNIT_ASSERT_MESSAGE("did not find correct tolerance file", xmlStrEqual( root->name, BAD_CAST("tolerances") ));
#else
if(!xmlStrEqual( root->name, BAD_CAST("tolerances") ))
{
assert(false);
return;
}
#endif
xmlNodePtr child = NULL;
for (child = root->children; child != NULL; child = child->next)
{
// assume a valid xml file
if(child->type != XML_ELEMENT_NODE)
continue;
assert(xmlStrEqual(child->name, BAD_CAST("tolerance")));
tolerance tol;
readAttributesForTolerance(child, tol);
toleranceContainer.insert(tol);
}
}
bool XMLDiff::compare()
{
xmlNode* root1 = xmlDocGetRootElement(xmlFile1);
xmlNode* root2 = xmlDocGetRootElement(xmlFile2);
#if USE_CPPUNIT
CPPUNIT_ASSERT(root1);
CPPUNIT_ASSERT(root2);
cppunitAssertEqual(root1->name, root2->name);
#else
if (!root1 || !root2)
return false;
if(!xmlStrEqual(root1->name, root2->name))
return false;
#endif
return compareElements(root1, root2);
}
namespace {
bool checkForEmptyChildren(xmlNodePtr node)
{
if(!node)
return true;
for(; node != NULL; node = node->next)
{
if (node->type == XML_ELEMENT_NODE)
return false;
}
return true;
}
}
bool XMLDiff::compareElements(xmlNode* node1, xmlNode* node2)
{
#if USE_CPPUNIT
cppunitAssertEqual(node1->name, node2->name);
#else
if (!xmlStrEqual( node1->name, node2->name ))
return false;
#endif
//compare attributes
bool sameAttribs = compareAttributes(node1, node2);
#if USE_CPPUNIT
CPPUNIT_ASSERT(sameAttribs);
#else
if (!sameAttribs)
return false;
#endif
// compare children
xmlNode* child2 = NULL;
xmlNode* child1 = NULL;
for(child1 = node1->children, child2 = node2->children; child1 != NULL && child2 != NULL; child1 = child1->next, child2 = child2->next)
{
if (child1->type == XML_ELEMENT_NODE)
{
bool bCompare = compareElements(child1, child2);
if(!bCompare)
{
return false;
}
}
}
#if USE_CPPUNIT
CPPUNIT_ASSERT(checkForEmptyChildren(child1));
CPPUNIT_ASSERT(checkForEmptyChildren(child2));
#else
if(!checkForEmptyChildren(child1) || !checkForEmptyChildren(child2))
return false;
#endif
return true;
}
void XMLDiff::cppunitAssertEqual(const xmlChar *expected, const xmlChar *found)
{
#if USE_CPPUNIT
std::stringstream stringStream;
stringStream << "Reference: " << fileName << "\n- Expected: " << (const char*) expected << "\n- Found: " << (const char*) found;
CPPUNIT_ASSERT_MESSAGE(stringStream.str(), xmlStrEqual(expected, found));
#endif
}
void XMLDiff::cppunitAssertEqualDouble(const xmlChar *node, double expected, double found, double delta)
{
#if USE_CPPUNIT
std::stringstream stringStream;
stringStream << "Reference: " << fileName << "\n- Node: " << (const char*) node;
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(stringStream.str(), expected, found, delta);
#endif
}
namespace {
bool compareValuesWithTolerance(double val1, double val2, double tolerance, bool relative)
{
if(relative)
{
return (val1/tolerance) <= val2 && val2 <= (val1*tolerance);
}
else
{
return (val1 - tolerance) <= val2 && val2 <= (val1 + tolerance);
}
}
}
bool XMLDiff::compareAttributes(xmlNodePtr node1, xmlNodePtr node2)
{
xmlAttrPtr attr1 = NULL;
xmlAttrPtr attr2 = NULL;
for(attr1 = node1->properties, attr2 = node2->properties; attr1 != NULL && attr2 != NULL; attr1 = attr1->next, attr2 = attr2->next)
{
#if USE_CPPUNIT
cppunitAssertEqual(attr1->name, attr2->name);
#else
if (!xmlStrEqual( attr1->name, attr2->name ))
return false;
#endif
xmlChar* val1 = xmlGetProp(node1, attr1->name);
xmlChar* val2 = xmlGetProp(node2, attr2->name);
double dVal1 = xmlXPathCastStringToNumber(val1);
double dVal2 = xmlXPathCastStringToNumber(val2);
if(!rtl::math::isNan(dVal1) || !rtl::math::isNan(dVal2))
{
//compare by value and respect tolerance
tolerance tol;
tol.elementName = xmlStrdup(node1->name);
tol.attribName = xmlStrdup(attr1->name);
ToleranceContainer::iterator itr = toleranceContainer.find( tol );
bool useTolerance = false;
if (itr != toleranceContainer.end())
{
useTolerance = true;
}
if (useTolerance)
{
bool valInTolerance = compareValuesWithTolerance(dVal1, dVal2, itr->value, itr->relative);
#if USE_CPPUNIT
std::stringstream stringStream("Expected Value: ");
stringStream << dVal1 << "; Found Value: " << dVal2 << "; Tolerance: " << itr->value;
stringStream << "; Relative: " << itr->relative;
CPPUNIT_ASSERT_MESSAGE(stringStream.str(), valInTolerance);
#else
if (!valInTolerance)
return false;
#endif
}
else
{
#if USE_CPPUNIT
cppunitAssertEqualDouble(attr1->name, dVal1, dVal2, 1e-08);
#else
if (dVal1 != dVal2)
return false;
#endif
}
}
else
{
#if USE_CPPUNIT
cppunitAssertEqual(val1, val2);
#else
if(!xmlStrEqual( val1, val2 ))
return false;
#endif
}
xmlFree(val1);
xmlFree(val2);
}
// unequal number of attributes
#ifdef CPPUNIT_ASSERT
CPPUNIT_ASSERT(!attr1);
CPPUNIT_ASSERT(!attr2);
#else
if (attr1 || attr2)
return false;
#endif
return true;
}
bool
doXMLDiff(char const*const pFileName, char const*const pContent, int const size,
char const*const pToleranceFileName)
{
XMLDiff aDiff(pFileName, pContent, size, pToleranceFileName);
return aDiff.compare();
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before><commit_msg>disable mouse aiming when app has no focus<commit_after><|endoftext|> |
<commit_before>/***************************************************************
*
* Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,
* University of Wisconsin-Madison, WI.
*
* 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 "condor_common.h"
#include "script.h"
#include "util.h"
#include "job.h"
#include "dag.h"
ScriptQ::ScriptQ( Dag* dag ) :
_scriptDeferredCount (0)
{
_dag = dag;
_numScriptsRunning = 0;
_scriptPidTable = new HashTable<int,Script*>( 127, &hashFuncInt );
_waitingQueue = new Queue<std::pair<Script*, int> *>();
if( _scriptPidTable == NULL || _waitingQueue == NULL ) {
EXCEPT( "ERROR: out of memory!");
}
// register daemonCore reaper for PRE/POST script completion
_scriptReaperId =
daemonCore->Register_Reaper( "PRE/POST Script Reaper",
(ReaperHandlercpp)&ScriptQ::ScriptReaper,
"ScriptQ::ScriptReaper", this );
}
ScriptQ::~ScriptQ()
{
// should we un-register the daemonCore reaper here?
delete _scriptPidTable;
delete _waitingQueue;
};
int
ScriptQ::CheckDeferredScripts()
{
std::pair<Script *, int> *scriptInfo = NULL;
std::pair<Script *, int> *firstScriptInfo = NULL;
int now = time(NULL);
unsigned startedThisRound = 0;
while (!_waitingQueue->IsEmpty()) {
_waitingQueue->dequeue( scriptInfo );
ASSERT( (scriptInfo != NULL) && (scriptInfo->first != NULL) );
if ( !firstScriptInfo ) {
firstScriptInfo = scriptInfo;
} else if ( firstScriptInfo == scriptInfo) {
_waitingQueue->enqueue( scriptInfo );
break;
}
if (scriptInfo->second <= now) {
Script *script = scriptInfo->first;
int maxScripts = script->_post ? _dag->_maxPostScripts : _dag->_maxPreScripts;
if ( maxScripts != 0 && (_numScriptsRunning >= maxScripts) ) {
_waitingQueue->enqueue( scriptInfo );
}
delete scriptInfo;
startedThisRound += Run(script);
firstScriptInfo = NULL;
} else {
_waitingQueue->enqueue( scriptInfo );
}
}
debug_printf( DEBUG_NORMAL, "Started %d deferred scripts\n", startedThisRound );
return startedThisRound;
}
// run script if possible, otherwise insert it into the waiting queue
int
ScriptQ::Run( Script *script )
{
const char *prefix = script->_post ? "POST" : "PRE";
bool deferScript = false;
// Defer PRE scripts if the DAG is halted (we need to go ahead
// and run POST scripts so we don't "waste" the fact that the
// job completed). (Allow PRE script for final node, though.)
if ( _dag->IsHalted() && !script->_post &&
!script->GetNode()->GetFinal() ) {
debug_printf( DEBUG_DEBUG_1,
"Deferring %s script of node %s because DAG is halted\n",
prefix, script->GetNodeName() );
deferScript = true;
}
// Defer the script if we've hit the max PRE/POST scripts
// running limit.
int maxScripts =
script->_post ? _dag->_maxPostScripts : _dag->_maxPreScripts;
if ( maxScripts != 0 && _numScriptsRunning >= maxScripts ) {
// max scripts already running
debug_printf( DEBUG_DEBUG_1, "Max %s scripts (%d) already running; "
"deferring %s script of Job %s\n", prefix, maxScripts,
prefix, script->GetNodeName() );
deferScript = true;
}
if ( deferScript ) {
_scriptDeferredCount++;
_waitingQueue->enqueue( new std::pair<Script*, int>(script, 0) );
return 0;
}
debug_printf( DEBUG_NORMAL, "Running %s script of Node %s...\n",
prefix, script->GetNodeName() );
_dag->GetJobstateLog().WriteScriptStarted( script->GetNode(),
script->_post );
if( int pid = script->BackgroundRun( _scriptReaperId,
_dag->_dagStatus, _dag->NumNodesFailed() ) ) {
_numScriptsRunning++;
_scriptPidTable->insert( pid, script );
debug_printf( DEBUG_DEBUG_1, "\tspawned pid %d: %s\n", pid,
script->_cmd );
return 1;
}
// BackgroundRun() returned pid 0
debug_printf( DEBUG_NORMAL, " error: daemonCore->Create_Process() "
"failed; %s script of Job %s failed\n", prefix,
script->GetNodeName() );
// Putting this code here fixes PR 906 (Missing PRE or POST script
// causes DAGMan to hang); also, without this code a node for which
// the script spawning fails will permanently add to the running
// script count, which will throw off the maxpre/maxpost throttles.
// wenger 2007-11-08
const int returnVal = 1<<8;
if( ! script->_post ) {
_dag->PreScriptReaper( script->GetNode(), returnVal );
} else {
_dag->PostScriptReaper( script->GetNode(), returnVal );
}
return 0;
}
int
ScriptQ::RunWaitingScript()
{
std::pair<Script *, int> *firstScriptInfo = NULL;
std::pair<Script *, int> *scriptInfo = NULL;
time_t now = time(NULL);
while( !_waitingQueue->IsEmpty() ) {
_waitingQueue->dequeue( scriptInfo );
if ( !firstScriptInfo ) {
firstScriptInfo = scriptInfo;
} else if ( scriptInfo == firstScriptInfo ) {
_waitingQueue->enqueue( scriptInfo );
break;
}
ASSERT( (scriptInfo != NULL) && (scriptInfo->first != NULL) );
if ( now >= scriptInfo->second ) {
Script *script = scriptInfo->first;
delete scriptInfo;
return Run( script );
} else {
_waitingQueue->enqueue( scriptInfo );
}
}
return 0;
}
int
ScriptQ::RunAllWaitingScripts()
{
int scriptsRun = 0;
while ( RunWaitingScript() > 0 ) {
scriptsRun++;
}
debug_printf( DEBUG_DEBUG_1, "Ran %d scripts\n", scriptsRun );
return scriptsRun;
}
int
ScriptQ::NumScriptsRunning()
{
return _numScriptsRunning;
}
int
ScriptQ::ScriptReaper( int pid, int status )
{
Script* script = NULL;
// get the Script* that corresponds to this pid
_scriptPidTable->lookup( pid, script );
ASSERT( script != NULL );
_scriptPidTable->remove( pid );
_numScriptsRunning--;
if ( pid != script->_pid ) {
EXCEPT( "Reaper pid (%d) does not match expected script pid (%d)!",
pid, script->_pid );
}
// Check to see if we should re-run this later.
if ( status == script->_defer_status ) {
std::pair<Script *, int> *scriptInfo = new std::pair<Script *, int>(script, time(NULL)+script->_defer_time);
_waitingQueue->enqueue( scriptInfo );
const char *prefix = script->_post ? "POST" : "PRE";
debug_printf( DEBUG_NORMAL, "Deferring %s script of Node %s for %ld seconds (exit status was %d)...\n",
prefix, script->GetNodeName(), script->_defer_time, script->_defer_status );
}
else
{
script->_done = TRUE;
// call appropriate DAG reaper
if( ! script->_post ) {
_dag->PreScriptReaper( script->GetNode(), status );
} else {
_dag->PostScriptReaper( script->GetNode(), status );
}
}
// if there's another script waiting to run, run it now
RunWaitingScript();
return 1;
}
<commit_msg>Gittrac #4488: Noted problems found so far...<commit_after>/***************************************************************
*
* Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,
* University of Wisconsin-Madison, WI.
*
* 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 "condor_common.h"
#include "script.h"
#include "util.h"
#include "job.h"
#include "dag.h"
ScriptQ::ScriptQ( Dag* dag ) :
_scriptDeferredCount (0)
{
_dag = dag;
_numScriptsRunning = 0;
_scriptPidTable = new HashTable<int,Script*>( 127, &hashFuncInt );
_waitingQueue = new Queue<std::pair<Script*, int> *>();
if( _scriptPidTable == NULL || _waitingQueue == NULL ) {
EXCEPT( "ERROR: out of memory!");
}
// register daemonCore reaper for PRE/POST script completion
_scriptReaperId =
daemonCore->Register_Reaper( "PRE/POST Script Reaper",
(ReaperHandlercpp)&ScriptQ::ScriptReaper,
"ScriptQ::ScriptReaper", this );
}
ScriptQ::~ScriptQ()
{
// should we un-register the daemonCore reaper here?
delete _scriptPidTable;
delete _waitingQueue;
};
//TEMPTEMP -- merge this into RunAllWaitingScripts/RunWaitingScript
int
ScriptQ::CheckDeferredScripts()
{
std::pair<Script *, int> *scriptInfo = NULL;
std::pair<Script *, int> *firstScriptInfo = NULL;
int now = time(NULL);
unsigned startedThisRound = 0;
while (!_waitingQueue->IsEmpty()) {
_waitingQueue->dequeue( scriptInfo );
ASSERT( (scriptInfo != NULL) && (scriptInfo->first != NULL) );//TEMPTEMP -- valgrind says invalid read here! (reading freed memory)
if ( !firstScriptInfo ) {
firstScriptInfo = scriptInfo;
//TEMPTEMP -- is this a dummy node or something?
} else if ( firstScriptInfo == scriptInfo) {
_waitingQueue->enqueue( scriptInfo );
break;
}
if (scriptInfo->second <= now) {//TEMPTEMP -- valgrind says invalid read here! (reading freed memory)
Script *script = scriptInfo->first;
int maxScripts = script->_post ? _dag->_maxPostScripts : _dag->_maxPreScripts;
if ( maxScripts != 0 && (_numScriptsRunning >= maxScripts) ) {
_waitingQueue->enqueue( scriptInfo );
}
delete scriptInfo; //TEMPTEMP -- valgrind says invalid free here (already freed)
startedThisRound += Run(script);
firstScriptInfo = NULL;
} else {
_waitingQueue->enqueue( scriptInfo );
}
}
debug_printf( DEBUG_NORMAL, "Started %d deferred scripts\n", startedThisRound );
return startedThisRound;
}
// run script if possible, otherwise insert it into the waiting queue
int
ScriptQ::Run( Script *script )
{
//TEMP -- should ScriptQ object know whether it's pre or post?
const char *prefix = script->_post ? "POST" : "PRE";
bool deferScript = false;
// Defer PRE scripts if the DAG is halted (we need to go ahead
// and run POST scripts so we don't "waste" the fact that the
// job completed). (Allow PRE script for final node, though.)
if ( _dag->IsHalted() && !script->_post &&
!script->GetNode()->GetFinal() ) {
debug_printf( DEBUG_DEBUG_1,
"Deferring %s script of node %s because DAG is halted\n",
prefix, script->GetNodeName() );
deferScript = true;
}
// Defer the script if we've hit the max PRE/POST scripts
// running limit.
//TEMP -- the scriptQ object should really know the max scripts
// limit, instead of getting it from the Dag object. wenger 2015-03-18
int maxScripts =
script->_post ? _dag->_maxPostScripts : _dag->_maxPreScripts;
if ( maxScripts != 0 && _numScriptsRunning >= maxScripts ) {
// max scripts already running
debug_printf( DEBUG_DEBUG_1, "Max %s scripts (%d) already running; "
"deferring %s script of Job %s\n", prefix, maxScripts,
prefix, script->GetNodeName() );
deferScript = true;
}
if ( deferScript ) {
_scriptDeferredCount++;
_waitingQueue->enqueue( new std::pair<Script*, int>(script, 0) );
return 0;
}
debug_printf( DEBUG_NORMAL, "Running %s script of Node %s...\n",
prefix, script->GetNodeName() );
_dag->GetJobstateLog().WriteScriptStarted( script->GetNode(),
script->_post );
if( int pid = script->BackgroundRun( _scriptReaperId,
_dag->_dagStatus, _dag->NumNodesFailed() ) ) {
_numScriptsRunning++;
_scriptPidTable->insert( pid, script );
debug_printf( DEBUG_DEBUG_1, "\tspawned pid %d: %s\n", pid,
script->_cmd );
return 1;
}
// BackgroundRun() returned pid 0
debug_printf( DEBUG_NORMAL, " error: daemonCore->Create_Process() "
"failed; %s script of Job %s failed\n", prefix,
script->GetNodeName() );
// Putting this code here fixes PR 906 (Missing PRE or POST script
// causes DAGMan to hang); also, without this code a node for which
// the script spawning fails will permanently add to the running
// script count, which will throw off the maxpre/maxpost throttles.
// wenger 2007-11-08
const int returnVal = 1<<8;
if( ! script->_post ) {
_dag->PreScriptReaper( script->GetNode(), returnVal );
} else {
_dag->PostScriptReaper( script->GetNode(), returnVal );
}
return 0;
}
int
ScriptQ::RunWaitingScript()
{
std::pair<Script *, int> *firstScriptInfo = NULL;
std::pair<Script *, int> *scriptInfo = NULL;
time_t now = time(NULL);
while( !_waitingQueue->IsEmpty() ) {
_waitingQueue->dequeue( scriptInfo );
if ( !firstScriptInfo ) {
firstScriptInfo = scriptInfo;
} else if ( scriptInfo == firstScriptInfo ) {
_waitingQueue->enqueue( scriptInfo );
break;
}
ASSERT( (scriptInfo != NULL) && (scriptInfo->first != NULL) );
if ( now >= scriptInfo->second ) {
Script *script = scriptInfo->first;
delete scriptInfo;
return Run( script );
} else {
_waitingQueue->enqueue( scriptInfo );
}
}
return 0;
}
int
ScriptQ::RunAllWaitingScripts()
{
int scriptsRun = 0;
while ( RunWaitingScript() > 0 ) {
scriptsRun++;
}
debug_printf( DEBUG_DEBUG_1, "Ran %d scripts\n", scriptsRun );
return scriptsRun;
}
int
ScriptQ::NumScriptsRunning()
{
return _numScriptsRunning;
}
int
ScriptQ::ScriptReaper( int pid, int status )
{
Script* script = NULL;
// get the Script* that corresponds to this pid
_scriptPidTable->lookup( pid, script );
ASSERT( script != NULL );
_scriptPidTable->remove( pid );
_numScriptsRunning--;
if ( pid != script->_pid ) {
EXCEPT( "Reaper pid (%d) does not match expected script pid (%d)!",
pid, script->_pid );
}
// Check to see if we should re-run this later.
if ( status == script->_defer_status ) {
std::pair<Script *, int> *scriptInfo = new std::pair<Script *, int>(script, time(NULL)+script->_defer_time);
_waitingQueue->enqueue( scriptInfo );
const char *prefix = script->_post ? "POST" : "PRE";
debug_printf( DEBUG_NORMAL, "Deferring %s script of Node %s for %ld seconds (exit status was %d)...\n",
prefix, script->GetNodeName(), script->_defer_time, script->_defer_status );
}
else
{
script->_done = TRUE;
// call appropriate DAG reaper
if( ! script->_post ) {
_dag->PreScriptReaper( script->GetNode(), status );
} else {
_dag->PostScriptReaper( script->GetNode(), status );
}
}
// if there's another script waiting to run, run it now
RunWaitingScript();
return 1;
}
<|endoftext|> |
<commit_before>/******************************************************************************
The MIT License(MIT)
Embedded Template Library.
https://github.com/ETLCPP/etl
https://www.etlcpp.com
Documentation:
Copyright(c) 2022 John Wellbelove
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 "unit_test_framework.h"
#include "etl/char_traits.h"
namespace
{
template <typename T>
size_t length(const T* text)
{
size_t count = 0U;
while (*text != 0U)
{
++text;
++count;
}
return count;
}
SUITE(test_char_traits)
{
//*************************************************************************
TEST(test_strlen)
{
char data1[etl::strlen("qwerty")];
char data2[etl::strlen(L"qwerty")];
char data3[etl::strlen(u"qwerty")];
char data4[etl::strlen(U"qwerty")];
CHECK_EQUAL(6U, sizeof(data1));
CHECK_EQUAL(6U, sizeof(data2));
CHECK_EQUAL(6U, sizeof(data3));
CHECK_EQUAL(6U, sizeof(data4));
}
//*************************************************************************
TEST(test_char_traits_char_template)
{
using char_traits = etl::char_traits<char>;
using char_type = char_traits::char_type;
using int_type = char_traits::int_type;
char_type r = 'A';
char_type c = 'B';
char_type src[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
char_type dst[etl::size(src)];
char_type filled[] = { 9, 9, 9, 9, 9, 9, 9, 9, 9, 9 };
const char_type* p_src;
char_type* p_dst;
char_traits::assign(r, c);
CHECK_EQUAL(r, 'B');
CHECK(char_traits::eq(1, 1));
CHECK(!char_traits::eq(1, 2));
CHECK(!char_traits::eq(2, 1));
CHECK(!char_traits::lt(1, 1));
CHECK(char_traits::lt(1, 2));
CHECK(!char_traits::lt(2, 1));
CHECK_EQUAL(length<char_type>("ABCDEF"), char_traits::length("ABCDEF"));
CHECK_EQUAL(0, char_traits::compare("ABCDEF", "ABCDEF", 6U));
CHECK_EQUAL(-1, char_traits::compare("ABCDEE", "ABCDEF", 6U));
CHECK_EQUAL(1, char_traits::compare("ABCDEF", "ABCDEE", 6U));
p_dst = char_traits::assign(dst, etl::size(dst), 9);
CHECK_ARRAY_EQUAL(filled, p_dst, etl::size(filled));
std::fill_n(dst, etl::size(dst), 0);
p_dst = char_traits::copy(dst, src, etl::size(src));
CHECK_ARRAY_EQUAL(src, p_dst, etl::size(src));
std::fill_n(dst, etl::size(dst), 0);
p_dst = char_traits::move(dst, src, etl::size(src));
CHECK_ARRAY_EQUAL(src, p_dst, etl::size(src));
p_src = char_traits::find(src, etl::size(src), 4);
CHECK_EQUAL(src[4], *p_src);
CHECK_EQUAL(127, char_traits::to_char_type(int_type(127)));
CHECK_EQUAL(127, char_traits::to_int_type(char_type(127)));
CHECK(!char_traits::eq_int_type(0, 1));
CHECK(char_traits::eq_int_type(1, 1));
CHECK(int_type(char_traits::eof()) != char_traits::not_eof(char_traits::eof()));
CHECK(int_type(char_traits::eof() + 1) == char_traits::not_eof(char_traits::eof() + 1));
}
//*************************************************************************
TEST(test_char_traits_wchar_t_template)
{
using char_traits = etl::char_traits<wchar_t>;
using char_type = char_traits::char_type;
using int_type = char_traits::int_type;
char_type r = L'A';
char_type c = L'B';
char_type src[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
char_type dst[etl::size(src)];
char_type filled[] = { 9, 9, 9, 9, 9, 9, 9, 9, 9, 9 };
const char_type* p_src;
char_type* p_dst;
char_traits::assign(r, c);
CHECK_EQUAL(r, 'B');
CHECK(char_traits::eq(1, 1));
CHECK(!char_traits::eq(1, 2));
CHECK(!char_traits::eq(2, 1));
CHECK(!char_traits::lt(1, 1));
CHECK(char_traits::lt(1, 2));
CHECK(!char_traits::lt(2, 1));
CHECK_EQUAL(length<char_type>(L"ABCDEF"), char_traits::length(L"ABCDEF"));
CHECK_EQUAL(0, char_traits::compare(L"ABCDEF", L"ABCDEF", 6U));
CHECK_EQUAL(-1, char_traits::compare(L"ABCDEE", L"ABCDEF", 6U));
CHECK_EQUAL(1, char_traits::compare(L"ABCDEF", L"ABCDEE", 6U));
p_dst = char_traits::assign(dst, etl::size(dst), 9);
CHECK_ARRAY_EQUAL(filled, p_dst, etl::size(filled));
std::fill_n(dst, etl::size(dst), 0);
p_dst = char_traits::copy(dst, src, etl::size(src));
CHECK_ARRAY_EQUAL(src, p_dst, etl::size(src));
std::fill_n(dst, etl::size(dst), 0);
p_dst = char_traits::move(dst, src, etl::size(src));
CHECK_ARRAY_EQUAL(src, p_dst, etl::size(src));
p_src = char_traits::find(src, etl::size(src), 4);
CHECK_EQUAL(src[4], *p_src);
CHECK_EQUAL(127, char_traits::to_char_type(int_type(127)));
CHECK_EQUAL(127, char_traits::to_int_type(char_type(127)));
CHECK(!char_traits::eq_int_type(0, 1));
CHECK(char_traits::eq_int_type(1, 1));
CHECK(int_type(char_traits::eof()) != char_traits::not_eof(char_traits::eof()));
CHECK(int_type(char_traits::eof() + 1) == char_traits::not_eof(char_traits::eof() + 1));
}
//*************************************************************************
TEST(test_char_traits_char16_t_template)
{
using char_traits = etl::char_traits<char16_t>;
using char_type = char_traits::char_type;
using int_type = char_traits::int_type;
char_type r = u'A';
char_type c = u'B';
char_type src[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
char_type dst[etl::size(src)];
char_type filled[] = { 9, 9, 9, 9, 9, 9, 9, 9, 9, 9 };
const char_type* p_src;
char_type* p_dst;
char_traits::assign(r, c);
CHECK_EQUAL(r, 'B');
CHECK(char_traits::eq(1, 1));
CHECK(!char_traits::eq(1, 2));
CHECK(!char_traits::eq(2, 1));
CHECK(!char_traits::lt(1, 1));
CHECK(char_traits::lt(1, 2));
CHECK(!char_traits::lt(2, 1));
CHECK_EQUAL(length<char_type>(u"ABCDEF"), char_traits::length(u"ABCDEF"));
CHECK_EQUAL(0, char_traits::compare(u"ABCDEF", u"ABCDEF", 6U));
CHECK_EQUAL(-1, char_traits::compare(u"ABCDEE", u"ABCDEF", 6U));
CHECK_EQUAL(1, char_traits::compare(u"ABCDEF", u"ABCDEE", 6U));
p_dst = char_traits::assign(dst, etl::size(dst), 9);
CHECK_ARRAY_EQUAL(filled, p_dst, etl::size(filled));
std::fill_n(dst, etl::size(dst), 0);
p_dst = char_traits::copy(dst, src, etl::size(src));
CHECK_ARRAY_EQUAL(src, p_dst, etl::size(src));
std::fill_n(dst, etl::size(dst), 0);
p_dst = char_traits::move(dst, src, etl::size(src));
CHECK_ARRAY_EQUAL(src, p_dst, etl::size(src));
p_src = char_traits::find(src, etl::size(src), 4);
CHECK_EQUAL(src[4], *p_src);
CHECK_EQUAL(127, char_traits::to_char_type(int_type(127)));
CHECK_EQUAL(127, char_traits::to_int_type(char_type(127)));
CHECK(!char_traits::eq_int_type(0, 1));
CHECK(char_traits::eq_int_type(1, 1));
CHECK(int_type(char_traits::eof()) != char_traits::not_eof(char_traits::eof()));
CHECK(int_type(char_traits::eof() + 1) == char_traits::not_eof(char_traits::eof() + 1));
}
//*************************************************************************
TEST(test_char_traits_char32_t_template)
{
using char_traits = etl::char_traits<char32_t>;
using char_type = char_traits::char_type;
using int_type = char_traits::int_type;
char_type r = U'A';
char_type c = U'B';
char_type src[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
char_type dst[etl::size(src)];
char_type filled[] = { 9, 9, 9, 9, 9, 9, 9, 9, 9, 9 };
const char_type* p_src;
char_type* p_dst;
char_traits::assign(r, c);
CHECK_EQUAL(r, 'B');
CHECK(char_traits::eq(1, 1));
CHECK(!char_traits::eq(1, 2));
CHECK(!char_traits::eq(2, 1));
CHECK(!char_traits::lt(1, 1));
CHECK(char_traits::lt(1, 2));
CHECK(!char_traits::lt(2, 1));
CHECK_EQUAL(length<char_type>(U"ABCDEF"), char_traits::length(U"ABCDEF"));
CHECK_EQUAL(0, char_traits::compare(U"ABCDEF", U"ABCDEF", 6U));
CHECK_EQUAL(-1, char_traits::compare(U"ABCDEE", U"ABCDEF", 6U));
CHECK_EQUAL(1, char_traits::compare(U"ABCDEF", U"ABCDEE", 6U));
p_dst = char_traits::assign(dst, etl::size(dst), 9);
CHECK_ARRAY_EQUAL(filled, p_dst, etl::size(filled));
std::fill_n(dst, etl::size(dst), 0);
p_dst = char_traits::copy(dst, src, etl::size(src));
CHECK_ARRAY_EQUAL(src, p_dst, etl::size(src));
std::fill_n(dst, etl::size(dst), 0);
p_dst = char_traits::move(dst, src, etl::size(src));
CHECK_ARRAY_EQUAL(src, p_dst, etl::size(src));
p_src = char_traits::find(src, etl::size(src), 4);
CHECK_EQUAL(src[4], *p_src);
CHECK_EQUAL(127, char_traits::to_char_type(int_type(127)));
CHECK_EQUAL(127, char_traits::to_int_type(char_type(127)));
CHECK(!char_traits::eq_int_type(0, 1));
CHECK(char_traits::eq_int_type(1, 1));
CHECK(int_type(char_traits::eof()) != char_traits::not_eof(char_traits::eof()));
CHECK(int_type(char_traits::eof() + 1) == char_traits::not_eof(char_traits::eof() + 1));
}
};
}
<commit_msg>Changed etl::size to std::size in the tests<commit_after>/******************************************************************************
The MIT License(MIT)
Embedded Template Library.
https://github.com/ETLCPP/etl
https://www.etlcpp.com
Documentation:
Copyright(c) 2022 John Wellbelove
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 "unit_test_framework.h"
#include "etl/char_traits.h"
namespace
{
template <typename T>
size_t length(const T* text)
{
size_t count = 0U;
while (*text != 0U)
{
++text;
++count;
}
return count;
}
SUITE(test_char_traits)
{
//*************************************************************************
TEST(test_strlen)
{
char data1[etl::strlen("qwerty")];
char data2[etl::strlen(L"qwerty")];
char data3[etl::strlen(u"qwerty")];
char data4[etl::strlen(U"qwerty")];
CHECK_EQUAL(6U, sizeof(data1));
CHECK_EQUAL(6U, sizeof(data2));
CHECK_EQUAL(6U, sizeof(data3));
CHECK_EQUAL(6U, sizeof(data4));
}
//*************************************************************************
TEST(test_char_traits_char_template)
{
using char_traits = etl::char_traits<char>;
using char_type = char_traits::char_type;
using int_type = char_traits::int_type;
char_type r = 'A';
char_type c = 'B';
char_type src[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
char_type dst[std::size(src)];
char_type filled[] = { 9, 9, 9, 9, 9, 9, 9, 9, 9, 9 };
const char_type* p_src;
char_type* p_dst;
char_traits::assign(r, c);
CHECK_EQUAL(r, 'B');
CHECK(char_traits::eq(1, 1));
CHECK(!char_traits::eq(1, 2));
CHECK(!char_traits::eq(2, 1));
CHECK(!char_traits::lt(1, 1));
CHECK(char_traits::lt(1, 2));
CHECK(!char_traits::lt(2, 1));
CHECK_EQUAL(length<char_type>("ABCDEF"), char_traits::length("ABCDEF"));
CHECK_EQUAL(0, char_traits::compare("ABCDEF", "ABCDEF", 6U));
CHECK_EQUAL(-1, char_traits::compare("ABCDEE", "ABCDEF", 6U));
CHECK_EQUAL(1, char_traits::compare("ABCDEF", "ABCDEE", 6U));
p_dst = char_traits::assign(dst, std::size(dst), 9);
CHECK_ARRAY_EQUAL(filled, p_dst, std::size(filled));
std::fill_n(dst, std::size(dst), 0);
p_dst = char_traits::copy(dst, src, std::size(src));
CHECK_ARRAY_EQUAL(src, p_dst, std::size(src));
std::fill_n(dst, std::size(dst), 0);
p_dst = char_traits::move(dst, src, std::size(src));
CHECK_ARRAY_EQUAL(src, p_dst, std::size(src));
p_src = char_traits::find(src, std::size(src), 4);
CHECK_EQUAL(src[4], *p_src);
CHECK_EQUAL(127, char_traits::to_char_type(int_type(127)));
CHECK_EQUAL(127, char_traits::to_int_type(char_type(127)));
CHECK(!char_traits::eq_int_type(0, 1));
CHECK(char_traits::eq_int_type(1, 1));
CHECK(int_type(char_traits::eof()) != char_traits::not_eof(char_traits::eof()));
CHECK(int_type(char_traits::eof() + 1) == char_traits::not_eof(char_traits::eof() + 1));
}
//*************************************************************************
TEST(test_char_traits_wchar_t_template)
{
using char_traits = etl::char_traits<wchar_t>;
using char_type = char_traits::char_type;
using int_type = char_traits::int_type;
char_type r = L'A';
char_type c = L'B';
char_type src[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
char_type dst[std::size(src)];
char_type filled[] = { 9, 9, 9, 9, 9, 9, 9, 9, 9, 9 };
const char_type* p_src;
char_type* p_dst;
char_traits::assign(r, c);
CHECK_EQUAL(r, 'B');
CHECK(char_traits::eq(1, 1));
CHECK(!char_traits::eq(1, 2));
CHECK(!char_traits::eq(2, 1));
CHECK(!char_traits::lt(1, 1));
CHECK(char_traits::lt(1, 2));
CHECK(!char_traits::lt(2, 1));
CHECK_EQUAL(length<char_type>(L"ABCDEF"), char_traits::length(L"ABCDEF"));
CHECK_EQUAL(0, char_traits::compare(L"ABCDEF", L"ABCDEF", 6U));
CHECK_EQUAL(-1, char_traits::compare(L"ABCDEE", L"ABCDEF", 6U));
CHECK_EQUAL(1, char_traits::compare(L"ABCDEF", L"ABCDEE", 6U));
p_dst = char_traits::assign(dst, std::size(dst), 9);
CHECK_ARRAY_EQUAL(filled, p_dst, std::size(filled));
std::fill_n(dst, std::size(dst), 0);
p_dst = char_traits::copy(dst, src, std::size(src));
CHECK_ARRAY_EQUAL(src, p_dst, std::size(src));
std::fill_n(dst, std::size(dst), 0);
p_dst = char_traits::move(dst, src, std::size(src));
CHECK_ARRAY_EQUAL(src, p_dst, std::size(src));
p_src = char_traits::find(src, std::size(src), 4);
CHECK_EQUAL(src[4], *p_src);
CHECK_EQUAL(127, char_traits::to_char_type(int_type(127)));
CHECK_EQUAL(127, char_traits::to_int_type(char_type(127)));
CHECK(!char_traits::eq_int_type(0, 1));
CHECK(char_traits::eq_int_type(1, 1));
CHECK(int_type(char_traits::eof()) != char_traits::not_eof(char_traits::eof()));
CHECK(int_type(char_traits::eof() + 1) == char_traits::not_eof(char_traits::eof() + 1));
}
//*************************************************************************
TEST(test_char_traits_char16_t_template)
{
using char_traits = etl::char_traits<char16_t>;
using char_type = char_traits::char_type;
using int_type = char_traits::int_type;
char_type r = u'A';
char_type c = u'B';
char_type src[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
char_type dst[std::size(src)];
char_type filled[] = { 9, 9, 9, 9, 9, 9, 9, 9, 9, 9 };
const char_type* p_src;
char_type* p_dst;
char_traits::assign(r, c);
CHECK_EQUAL(r, 'B');
CHECK(char_traits::eq(1, 1));
CHECK(!char_traits::eq(1, 2));
CHECK(!char_traits::eq(2, 1));
CHECK(!char_traits::lt(1, 1));
CHECK(char_traits::lt(1, 2));
CHECK(!char_traits::lt(2, 1));
CHECK_EQUAL(length<char_type>(u"ABCDEF"), char_traits::length(u"ABCDEF"));
CHECK_EQUAL(0, char_traits::compare(u"ABCDEF", u"ABCDEF", 6U));
CHECK_EQUAL(-1, char_traits::compare(u"ABCDEE", u"ABCDEF", 6U));
CHECK_EQUAL(1, char_traits::compare(u"ABCDEF", u"ABCDEE", 6U));
p_dst = char_traits::assign(dst, std::size(dst), 9);
CHECK_ARRAY_EQUAL(filled, p_dst, std::size(filled));
std::fill_n(dst, std::size(dst), 0);
p_dst = char_traits::copy(dst, src, std::size(src));
CHECK_ARRAY_EQUAL(src, p_dst, std::size(src));
std::fill_n(dst, std::size(dst), 0);
p_dst = char_traits::move(dst, src, std::size(src));
CHECK_ARRAY_EQUAL(src, p_dst, std::size(src));
p_src = char_traits::find(src, std::size(src), 4);
CHECK_EQUAL(src[4], *p_src);
CHECK_EQUAL(127, char_traits::to_char_type(int_type(127)));
CHECK_EQUAL(127, char_traits::to_int_type(char_type(127)));
CHECK(!char_traits::eq_int_type(0, 1));
CHECK(char_traits::eq_int_type(1, 1));
CHECK(int_type(char_traits::eof()) != char_traits::not_eof(char_traits::eof()));
CHECK(int_type(char_traits::eof() + 1) == char_traits::not_eof(char_traits::eof() + 1));
}
//*************************************************************************
TEST(test_char_traits_char32_t_template)
{
using char_traits = etl::char_traits<char32_t>;
using char_type = char_traits::char_type;
using int_type = char_traits::int_type;
char_type r = U'A';
char_type c = U'B';
char_type src[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
char_type dst[std::size(src)];
char_type filled[] = { 9, 9, 9, 9, 9, 9, 9, 9, 9, 9 };
const char_type* p_src;
char_type* p_dst;
char_traits::assign(r, c);
CHECK_EQUAL(r, 'B');
CHECK(char_traits::eq(1, 1));
CHECK(!char_traits::eq(1, 2));
CHECK(!char_traits::eq(2, 1));
CHECK(!char_traits::lt(1, 1));
CHECK(char_traits::lt(1, 2));
CHECK(!char_traits::lt(2, 1));
CHECK_EQUAL(length<char_type>(U"ABCDEF"), char_traits::length(U"ABCDEF"));
CHECK_EQUAL(0, char_traits::compare(U"ABCDEF", U"ABCDEF", 6U));
CHECK_EQUAL(-1, char_traits::compare(U"ABCDEE", U"ABCDEF", 6U));
CHECK_EQUAL(1, char_traits::compare(U"ABCDEF", U"ABCDEE", 6U));
p_dst = char_traits::assign(dst, std::size(dst), 9);
CHECK_ARRAY_EQUAL(filled, p_dst, std::size(filled));
std::fill_n(dst, std::size(dst), 0);
p_dst = char_traits::copy(dst, src, std::size(src));
CHECK_ARRAY_EQUAL(src, p_dst, std::size(src));
std::fill_n(dst, std::size(dst), 0);
p_dst = char_traits::move(dst, src, std::size(src));
CHECK_ARRAY_EQUAL(src, p_dst, std::size(src));
p_src = char_traits::find(src, std::size(src), 4);
CHECK_EQUAL(src[4], *p_src);
CHECK_EQUAL(127, char_traits::to_char_type(int_type(127)));
CHECK_EQUAL(127, char_traits::to_int_type(char_type(127)));
CHECK(!char_traits::eq_int_type(0, 1));
CHECK(char_traits::eq_int_type(1, 1));
CHECK(int_type(char_traits::eof()) != char_traits::not_eof(char_traits::eof()));
CHECK(int_type(char_traits::eof() + 1) == char_traits::not_eof(char_traits::eof() + 1));
}
};
}
<|endoftext|> |
<commit_before>#include <string>
#include <Python.h>
/*
* basically doing this:
*
* PyRun_SimpleString("from Bio import SeqIO\n"
* "SeqIO.parse('filename.extnsn', 'filetype'");
*/
PyObject* getFileData(int argc, char *argv[])
{
PyObject *BioModule = PyImport_ImportModule("Bio");
const char *filename, *filetype;
filename = PyUnicode_DecodeFSDefault(argv[1]);
filetype = PyUnicode_DecodeFSDefault(argv[2]);
std::string cmdToRun = "import Bio\nBio.SeqIO.parse(";
cmdToRun = cmdToRun + filename + std::string(",") + filetype;
cmdToRun = (const char*)cmdToRun;
wchar_t *program = Py_DecodeLocale(argv[0], NULL);
if (program == NULL) {
fprintf(stderr, "Fatal error: cannot decode argv[0]\n");
exit(1);
}
Py_SetProgramName(program); /* optional but recommended */
Py_Initialize();
PyObject* filedata;
filedata = PyRun_String(cmdToRun, 0, NULL, NULL);
Py_DECREF(filename);
Py_DECREF(filetype);
Py_Finalize();
PyMem_RawFree(program);
return filedata;
}
<commit_msg>fix type cast to const char*<commit_after>#include <string>
#include <Python.h>
/*
* basically doing this:
*
* PyRun_SimpleString("from Bio import SeqIO\n"
* "SeqIO.parse('filename.extnsn', 'filetype'");
*/
PyObject* getFileData(int argc, char *argv[])
{
PyObject *BioModule = PyImport_ImportModule("Bio");
const char *filename, *filetype, *pycmdToRun;
filename = (const char *)PyUnicode_DecodeFSDefault(argv[1]);
filetype = (const char *)PyUnicode_DecodeFSDefault(argv[2]);
std::string cmdToRun = "import Bio\nBio.SeqIO.parse(";
cmdToRun = cmdToRun + filename + std::string(",") + filetype;
pycmdToRun = cmdToRun.c_str();
wchar_t *program = Py_DecodeLocale(argv[0], NULL);
if (program == NULL) {
fprintf(stderr, "Fatal error: cannot decode argv[0]\n");
exit(1);
}
Py_SetProgramName(program); /* optional but recommended */
Py_Initialize();
PyObject* filedata;
filedata = PyRun_String(pycmdToRun, 0, NULL, NULL);
Py_DECREF(filename);
Py_DECREF(filetype);
Py_Finalize();
PyMem_RawFree(program);
return filedata;
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkInteractorStyleImage.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkInteractorStyleImage.h"
#include "vtkAbstractPropPicker.h"
#include "vtkAssemblyPath.h"
#include "vtkCommand.h"
#include "vtkMath.h"
#include "vtkObjectFactory.h"
#include "vtkRenderWindowInteractor.h"
vtkCxxRevisionMacro(vtkInteractorStyleImage, "1.23");
vtkStandardNewMacro(vtkInteractorStyleImage);
//----------------------------------------------------------------------------
vtkInteractorStyleImage::vtkInteractorStyleImage()
{
this->WindowLevelStartPosition[0] = 0;
this->WindowLevelStartPosition[1] = 0;
this->WindowLevelCurrentPosition[0] = 0;
this->WindowLevelCurrentPosition[1] = 0;
}
//----------------------------------------------------------------------------
vtkInteractorStyleImage::~vtkInteractorStyleImage()
{
}
//----------------------------------------------------------------------------
void vtkInteractorStyleImage::StartWindowLevel()
{
if (this->State != VTKIS_NONE)
{
return;
}
this->StartState(VTKIS_WINDOW_LEVEL);
this->InvokeEvent(vtkCommand::StartWindowLevelEvent,this);
}
//----------------------------------------------------------------------------
void vtkInteractorStyleImage::EndWindowLevel()
{
if (this->State != VTKIS_WINDOW_LEVEL)
{
return;
}
this->InvokeEvent(vtkCommand::EndWindowLevelEvent, this);
this->StopState();
}
//----------------------------------------------------------------------------
void vtkInteractorStyleImage::StartPick()
{
if (this->State != VTKIS_NONE)
{
return;
}
this->StartState(VTKIS_PICK);
this->InvokeEvent(vtkCommand::StartPickEvent, this);
}
//----------------------------------------------------------------------------
void vtkInteractorStyleImage::EndPick()
{
if (this->State != VTKIS_PICK)
{
return;
}
this->InvokeEvent(vtkCommand::EndPickEvent, this);
this->StopState();
}
//----------------------------------------------------------------------------
void vtkInteractorStyleImage::OnMouseMove()
{
int x = this->Interactor->GetEventPosition()[0];
int y = this->Interactor->GetEventPosition()[1];
switch (this->State)
{
case VTKIS_WINDOW_LEVEL:
this->FindPokedRenderer(x, y);
this->WindowLevel();
this->InvokeEvent(vtkCommand::InteractionEvent, NULL);
break;
case VTKIS_PICK:
this->FindPokedRenderer(x, y);
this->Pick();
this->InvokeEvent(vtkCommand::InteractionEvent, NULL);
break;
}
// Call parent to handle all other states and perform additional work
this->Superclass::OnMouseMove();
}
//----------------------------------------------------------------------------
void vtkInteractorStyleImage::OnLeftButtonDown()
{
int x = this->Interactor->GetEventPosition()[0];
int y = this->Interactor->GetEventPosition()[1];
this->FindPokedRenderer(x, y);
if (this->CurrentRenderer == NULL)
{
return;
}
// Redefine this button to handle window/level
if (!this->Interactor->GetShiftKey() && !this->Interactor->GetControlKey())
{
this->WindowLevelStartPosition[0] = x;
this->WindowLevelStartPosition[1] = y;
this->StartWindowLevel();
}
// The rest of the button + key combinations remain the same
else
{
this->Superclass::OnLeftButtonDown();
}
}
//----------------------------------------------------------------------------
void vtkInteractorStyleImage::OnLeftButtonUp()
{
switch (this->State)
{
case VTKIS_WINDOW_LEVEL:
this->EndWindowLevel();
break;
}
// Call parent to handle all other states and perform additional work
this->Superclass::OnLeftButtonUp();
}
//----------------------------------------------------------------------------
void vtkInteractorStyleImage::OnRightButtonDown()
{
int x = this->Interactor->GetEventPosition()[0];
int y = this->Interactor->GetEventPosition()[1];
this->FindPokedRenderer(x, y);
if (this->CurrentRenderer == NULL)
{
return;
}
// Redefine this button + shift to handle pick
if (this->Interactor->GetShiftKey())
{
this->StartPick();
}
// The rest of the button + key combinations remain the same
else
{
this->Superclass::OnRightButtonDown();
}
}
//----------------------------------------------------------------------------
void vtkInteractorStyleImage::OnRightButtonUp()
{
switch (this->State)
{
case VTKIS_PICK:
this->EndPick();
break;
}
// Call parent to handle all other states and perform additional work
this->Superclass::OnRightButtonUp();
}
//----------------------------------------------------------------------------
void vtkInteractorStyleImage::OnChar()
{
vtkRenderWindowInteractor *rwi = this->Interactor;
switch (rwi->GetKeyCode())
{
case 'f' :
case 'F' :
{
this->AnimState = VTKIS_ANIM_ON;
vtkAssemblyPath *path=NULL;
this->FindPokedRenderer(rwi->GetEventPosition()[0],
rwi->GetEventPosition()[1]);
rwi->GetPicker()->Pick(rwi->GetEventPosition()[0],
rwi->GetEventPosition()[1], 0.0,
this->CurrentRenderer);
vtkAbstractPropPicker *picker;
if ( (picker=vtkAbstractPropPicker::SafeDownCast(rwi->GetPicker())) )
{
path = picker->GetPath();
}
if ( path != NULL )
{
rwi->FlyToImage(this->CurrentRenderer,picker->GetPickPosition());
}
this->AnimState = VTKIS_ANIM_OFF;
break;
}
case 'r' :
case 'R' :
// Allow either shift/ctrl to trigger the usual 'r' binding
// otherwise trigger reset window level event
if (rwi->GetShiftKey() || rwi->GetControlKey())
{
this->Superclass::OnChar();
}
else
{
this->InvokeEvent(vtkCommand::ResetWindowLevelEvent, this);
}
break;
default:
this->Superclass::OnChar();
break;
}
}
//----------------------------------------------------------------------------
void vtkInteractorStyleImage::WindowLevel()
{
vtkRenderWindowInteractor *rwi = this->Interactor;
this->WindowLevelCurrentPosition[0] = rwi->GetEventPosition()[0];
this->WindowLevelCurrentPosition[1] = rwi->GetEventPosition()[1];
this->InvokeEvent(vtkCommand::WindowLevelEvent, this);
}
//----------------------------------------------------------------------------
void vtkInteractorStyleImage::Pick()
{
this->InvokeEvent(vtkCommand::PickEvent, this);
}
//----------------------------------------------------------------------------
void vtkInteractorStyleImage::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
os << indent << "Window Level Current Position: " <<
this->WindowLevelCurrentPosition << endl;
os << indent << "Window Level Start Position: " <<
this->WindowLevelStartPosition << endl;
}
<commit_msg>BUG: Printing WindowLevelCurrentPosition and WindowLevelStartPosition should print the two integer components, not the address of the array.<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkInteractorStyleImage.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkInteractorStyleImage.h"
#include "vtkAbstractPropPicker.h"
#include "vtkAssemblyPath.h"
#include "vtkCommand.h"
#include "vtkMath.h"
#include "vtkObjectFactory.h"
#include "vtkRenderWindowInteractor.h"
vtkCxxRevisionMacro(vtkInteractorStyleImage, "1.24");
vtkStandardNewMacro(vtkInteractorStyleImage);
//----------------------------------------------------------------------------
vtkInteractorStyleImage::vtkInteractorStyleImage()
{
this->WindowLevelStartPosition[0] = 0;
this->WindowLevelStartPosition[1] = 0;
this->WindowLevelCurrentPosition[0] = 0;
this->WindowLevelCurrentPosition[1] = 0;
}
//----------------------------------------------------------------------------
vtkInteractorStyleImage::~vtkInteractorStyleImage()
{
}
//----------------------------------------------------------------------------
void vtkInteractorStyleImage::StartWindowLevel()
{
if (this->State != VTKIS_NONE)
{
return;
}
this->StartState(VTKIS_WINDOW_LEVEL);
this->InvokeEvent(vtkCommand::StartWindowLevelEvent,this);
}
//----------------------------------------------------------------------------
void vtkInteractorStyleImage::EndWindowLevel()
{
if (this->State != VTKIS_WINDOW_LEVEL)
{
return;
}
this->InvokeEvent(vtkCommand::EndWindowLevelEvent, this);
this->StopState();
}
//----------------------------------------------------------------------------
void vtkInteractorStyleImage::StartPick()
{
if (this->State != VTKIS_NONE)
{
return;
}
this->StartState(VTKIS_PICK);
this->InvokeEvent(vtkCommand::StartPickEvent, this);
}
//----------------------------------------------------------------------------
void vtkInteractorStyleImage::EndPick()
{
if (this->State != VTKIS_PICK)
{
return;
}
this->InvokeEvent(vtkCommand::EndPickEvent, this);
this->StopState();
}
//----------------------------------------------------------------------------
void vtkInteractorStyleImage::OnMouseMove()
{
int x = this->Interactor->GetEventPosition()[0];
int y = this->Interactor->GetEventPosition()[1];
switch (this->State)
{
case VTKIS_WINDOW_LEVEL:
this->FindPokedRenderer(x, y);
this->WindowLevel();
this->InvokeEvent(vtkCommand::InteractionEvent, NULL);
break;
case VTKIS_PICK:
this->FindPokedRenderer(x, y);
this->Pick();
this->InvokeEvent(vtkCommand::InteractionEvent, NULL);
break;
}
// Call parent to handle all other states and perform additional work
this->Superclass::OnMouseMove();
}
//----------------------------------------------------------------------------
void vtkInteractorStyleImage::OnLeftButtonDown()
{
int x = this->Interactor->GetEventPosition()[0];
int y = this->Interactor->GetEventPosition()[1];
this->FindPokedRenderer(x, y);
if (this->CurrentRenderer == NULL)
{
return;
}
// Redefine this button to handle window/level
if (!this->Interactor->GetShiftKey() && !this->Interactor->GetControlKey())
{
this->WindowLevelStartPosition[0] = x;
this->WindowLevelStartPosition[1] = y;
this->StartWindowLevel();
}
// The rest of the button + key combinations remain the same
else
{
this->Superclass::OnLeftButtonDown();
}
}
//----------------------------------------------------------------------------
void vtkInteractorStyleImage::OnLeftButtonUp()
{
switch (this->State)
{
case VTKIS_WINDOW_LEVEL:
this->EndWindowLevel();
break;
}
// Call parent to handle all other states and perform additional work
this->Superclass::OnLeftButtonUp();
}
//----------------------------------------------------------------------------
void vtkInteractorStyleImage::OnRightButtonDown()
{
int x = this->Interactor->GetEventPosition()[0];
int y = this->Interactor->GetEventPosition()[1];
this->FindPokedRenderer(x, y);
if (this->CurrentRenderer == NULL)
{
return;
}
// Redefine this button + shift to handle pick
if (this->Interactor->GetShiftKey())
{
this->StartPick();
}
// The rest of the button + key combinations remain the same
else
{
this->Superclass::OnRightButtonDown();
}
}
//----------------------------------------------------------------------------
void vtkInteractorStyleImage::OnRightButtonUp()
{
switch (this->State)
{
case VTKIS_PICK:
this->EndPick();
break;
}
// Call parent to handle all other states and perform additional work
this->Superclass::OnRightButtonUp();
}
//----------------------------------------------------------------------------
void vtkInteractorStyleImage::OnChar()
{
vtkRenderWindowInteractor *rwi = this->Interactor;
switch (rwi->GetKeyCode())
{
case 'f' :
case 'F' :
{
this->AnimState = VTKIS_ANIM_ON;
vtkAssemblyPath *path=NULL;
this->FindPokedRenderer(rwi->GetEventPosition()[0],
rwi->GetEventPosition()[1]);
rwi->GetPicker()->Pick(rwi->GetEventPosition()[0],
rwi->GetEventPosition()[1], 0.0,
this->CurrentRenderer);
vtkAbstractPropPicker *picker;
if ( (picker=vtkAbstractPropPicker::SafeDownCast(rwi->GetPicker())) )
{
path = picker->GetPath();
}
if ( path != NULL )
{
rwi->FlyToImage(this->CurrentRenderer,picker->GetPickPosition());
}
this->AnimState = VTKIS_ANIM_OFF;
break;
}
case 'r' :
case 'R' :
// Allow either shift/ctrl to trigger the usual 'r' binding
// otherwise trigger reset window level event
if (rwi->GetShiftKey() || rwi->GetControlKey())
{
this->Superclass::OnChar();
}
else
{
this->InvokeEvent(vtkCommand::ResetWindowLevelEvent, this);
}
break;
default:
this->Superclass::OnChar();
break;
}
}
//----------------------------------------------------------------------------
void vtkInteractorStyleImage::WindowLevel()
{
vtkRenderWindowInteractor *rwi = this->Interactor;
this->WindowLevelCurrentPosition[0] = rwi->GetEventPosition()[0];
this->WindowLevelCurrentPosition[1] = rwi->GetEventPosition()[1];
this->InvokeEvent(vtkCommand::WindowLevelEvent, this);
}
//----------------------------------------------------------------------------
void vtkInteractorStyleImage::Pick()
{
this->InvokeEvent(vtkCommand::PickEvent, this);
}
//----------------------------------------------------------------------------
void vtkInteractorStyleImage::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
os << indent << "Window Level Current Position: ("
<< this->WindowLevelCurrentPosition[0] << ", "
<< this->WindowLevelCurrentPosition[1] << ")" << endl;
os << indent << "Window Level Start Position: ("
<< this->WindowLevelStartPosition[0] << ", "
<< this->WindowLevelStartPosition[1] << ")" << endl;
}
<|endoftext|> |
<commit_before>/*
* yosys -- Yosys Open SYnthesis Suite
*
* Copyright (C) 2012 Clifford Wolf <clifford@clifford.at>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*/
#include "kernel/yosys.h"
#include "kernel/sigtools.h"
USING_YOSYS_NAMESPACE
PRIVATE_NAMESPACE_BEGIN
struct ShregmapOptions
{
std::string clkpol;
int minlen, maxlen;
int keep_before, keep_after;
ShregmapOptions()
{
clkpol = "any";
minlen = 2;
maxlen = 0;
keep_before = 0;
keep_after = 0;
}
};
struct ShregmapWorker
{
Module *module;
SigMap sigmap;
const ShregmapOptions &opts;
int dff_count, shreg_count;
// next is set to NULL for sigbits that drive non-DFFs
dict<SigBit, Cell*> sigbit_chain_next;
dict<SigBit, Cell*> sigbit_chain_prev;
pool<Cell*> chain_start_cells;
void make_sigbit_chain_next_prev()
{
for (auto wire : module->wires()) {
if (!wire->port_output)
continue;
for (auto bit : sigmap(wire))
sigbit_chain_next[bit] = nullptr;
}
for (auto cell : module->cells())
{
if ((opts.clkpol != "pos" && cell->type == "$_DFF_N_") ||
(opts.clkpol != "neg" && cell->type == "$_DFF_P_"))
{
SigBit d_bit = sigmap(cell->getPort("\\D").as_bit());
if (sigbit_chain_next.count(d_bit))
sigbit_chain_next[d_bit] = nullptr;
else
sigbit_chain_next[d_bit] = cell;
SigBit q_bit = sigmap(cell->getPort("\\Q").as_bit());
sigbit_chain_prev[q_bit] = cell;
continue;
}
for (auto conn : cell->connections())
if (cell->input(conn.first))
for (auto bit : sigmap(conn.second))
sigbit_chain_next[bit] = nullptr;
}
}
void find_chain_start_cells()
{
for (auto it : sigbit_chain_next)
{
if (it.second == nullptr)
continue;
if (sigbit_chain_prev.count(it.first) != 0)
{
Cell *c1 = sigbit_chain_prev.at(it.first);
Cell *c2 = it.second;
if (c1->type != c2->type)
goto start_cell;
if (sigmap(c1->getPort("\\C")) != c2->getPort("\\C"))
goto start_cell;
continue;
}
start_cell:
chain_start_cells.insert(it.second);
}
}
vector<Cell*> create_chain(Cell *start_cell)
{
vector<Cell*> chain;
Cell *c = start_cell;
while (c != nullptr)
{
chain.push_back(c);
SigBit q_bit = sigmap(c->getPort("\\Q").as_bit());
if (sigbit_chain_next.count(q_bit) == 0)
break;
c = sigbit_chain_next.at(q_bit);
if (chain_start_cells.count(c) != 0)
break;
}
return chain;
}
void process_chain(vector<Cell*> &chain)
{
if (GetSize(chain) < opts.keep_before + opts.minlen + opts.keep_after)
return;
int cursor = opts.keep_before;
while (cursor < GetSize(chain) - opts.keep_after)
{
int depth = GetSize(chain) - opts.keep_after - cursor;
if (opts.maxlen > 0)
depth = std::min(opts.maxlen, depth);
Cell *first_cell = chain[cursor], *last_cell = chain[cursor+depth-1];
if (depth < 2)
return;
log("Converting %s.%s ... %s.%s to a shift register with depth %d.\n",
log_id(module), log_id(first_cell), log_id(module), log_id(last_cell), depth);
first_cell->type = "$__DFF_SHREG_" + first_cell->type.substr(6);
first_cell->setPort("\\Q", last_cell->getPort("\\Q"));
first_cell->setParam("\\DEPTH", depth);
for (int i = 1; i < depth; i++)
module->remove(chain[cursor+i]);
cursor += depth;
}
}
ShregmapWorker(Module *module, const ShregmapOptions &opts) :
module(module), sigmap(module), opts(opts), dff_count(0), shreg_count(0)
{
make_sigbit_chain_next_prev();
find_chain_start_cells();
for (auto c : chain_start_cells) {
vector<Cell*> chain = create_chain(c);
process_chain(chain);
}
}
};
struct ShregmapPass : public Pass {
ShregmapPass() : Pass("shregmap", "map shift registers") { }
virtual void help()
{
// |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
log("\n");
log(" shregmap [options] [selection]\n");
log("\n");
log("This pass converts chains of $_DFF_[NP]_ gates to target specific shift register.\n");
log("primitives. The generated shift register will be of type $__DFF_SHREG_[NP]_ and\n");
log("will use the same interface as the original $_DFF_*_ cells. The cell parameter\n");
log("'DEPTH' will contain the depth of the shift register. Use a target-specific\n");
log("'techmap' map file to convert those cells to the actual target cells.\n");
log("\n");
log(" -minlen N\n");
log(" minimum length of shift register (default = 2)\n");
log(" (this is the length after -keep_before and -keep_after)\n");
log("\n");
log(" -maxlen N\n");
log(" maximum length of shift register (default = no limit)\n");
log(" larger chains will be mapped to multiple shift register instances\n");
log("\n");
log(" -keep_before N\n");
log(" number of DFFs to keep before the shift register (default = 0)\n");
log("\n");
log(" -keep_after N\n");
log(" number of DFFs to keep after the shift register (default = 0)\n");
log("\n");
log(" -clkpol pos|neg|any\n");
log(" limit match to only positive or negative edge clocks. (default = any)\n");
log("\n");
}
virtual void execute(std::vector<std::string> args, RTLIL::Design *design)
{
ShregmapOptions opts;
log_header("Executing SHREGMAP pass (map shift registers).\n");
size_t argidx;
for (argidx = 1; argidx < args.size(); argidx++)
{
if (args[argidx] == "-clkpol" && argidx+1 < args.size()) {
opts.clkpol = args[++argidx];
continue;
}
if (args[argidx] == "-minlen" && argidx+1 < args.size()) {
opts.minlen = atoi(args[++argidx].c_str());
continue;
}
if (args[argidx] == "-maxlen" && argidx+1 < args.size()) {
opts.maxlen = atoi(args[++argidx].c_str());
continue;
}
if (args[argidx] == "-keep_before" && argidx+1 < args.size()) {
opts.keep_before = atoi(args[++argidx].c_str());
continue;
}
if (args[argidx] == "-keep_after" && argidx+1 < args.size()) {
opts.keep_after = atoi(args[++argidx].c_str());
continue;
}
break;
}
extra_args(args, argidx, design);
if (opts.clkpol != "pos" && opts.clkpol != "neg" && opts.clkpol != "any")
log_cmd_error("Invalid value for -clkpol: %s\n", opts.clkpol.c_str());
int dff_count = 0;
int shreg_count = 0;
for (auto module : design->selected_modules()) {
ShregmapWorker worker(module, opts);
dff_count += worker.dff_count;
shreg_count += worker.shreg_count;
}
log("Converted %d dff cells into %d shift registers.\n", dff_count, shreg_count);
}
} ShregmapPass;
PRIVATE_NAMESPACE_END
<commit_msg>Improvements in "shregmap"<commit_after>/*
* yosys -- Yosys Open SYnthesis Suite
*
* Copyright (C) 2012 Clifford Wolf <clifford@clifford.at>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*/
#include "kernel/yosys.h"
#include "kernel/sigtools.h"
USING_YOSYS_NAMESPACE
PRIVATE_NAMESPACE_BEGIN
struct ShregmapOptions
{
int minlen, maxlen;
int keep_before, keep_after;
dict<IdString, pair<IdString, IdString>> ffcells;
ShregmapOptions()
{
minlen = 2;
maxlen = 0;
keep_before = 0;
keep_after = 0;
}
};
struct ShregmapWorker
{
Module *module;
SigMap sigmap;
const ShregmapOptions &opts;
int dff_count, shreg_count;
pool<Cell*> remove_cells;
dict<SigBit, bool> sigbit_init;
dict<SigBit, Cell*> sigbit_chain_next;
dict<SigBit, Cell*> sigbit_chain_prev;
pool<SigBit> sigbit_with_non_chain_users;
pool<Cell*> chain_start_cells;
void make_sigbit_chain_next_prev()
{
for (auto wire : module->wires())
{
if (wire->port_output) {
for (auto bit : sigmap(wire))
sigbit_with_non_chain_users.insert(bit);
}
if (wire->attributes.count("\\init")) {
SigSpec initsig = sigmap(wire);
Const initval = wire->attributes.at("\\init");
for (int i = 0; i < GetSize(initsig) && i < GetSize(initval); i++)
if (initval[i] == State::S0)
sigbit_init[initsig[i]] = false;
else if (initval[i] == State::S1)
sigbit_init[initsig[i]] = true;
}
}
for (auto cell : module->cells())
{
if (opts.ffcells.count(cell->type))
{
IdString d_port = opts.ffcells.at(cell->type).first;
IdString q_port = opts.ffcells.at(cell->type).second;
SigBit d_bit = sigmap(cell->getPort(d_port).as_bit());
SigBit q_bit = sigmap(cell->getPort(q_port).as_bit());
if (sigbit_init.count(q_bit) == 0) {
if (sigbit_chain_next.count(d_bit)) {
sigbit_with_non_chain_users.insert(d_bit);
} else
sigbit_chain_next[d_bit] = cell;
sigbit_chain_prev[q_bit] = cell;
continue;
}
}
for (auto conn : cell->connections())
if (cell->input(conn.first))
for (auto bit : sigmap(conn.second))
sigbit_with_non_chain_users.insert(bit);
}
}
void find_chain_start_cells()
{
for (auto it : sigbit_chain_next)
{
if (sigbit_with_non_chain_users.count(it.first))
continue;
if (sigbit_chain_prev.count(it.first) != 0)
{
Cell *c1 = sigbit_chain_prev.at(it.first);
Cell *c2 = it.second;
if (c1->type != c2->type)
goto start_cell;
if (c1->parameters != c2->parameters)
goto start_cell;
IdString d_port = opts.ffcells.at(c1->type).first;
IdString q_port = opts.ffcells.at(c1->type).second;
auto c1_conn = c1->connections();
auto c2_conn = c1->connections();
c1_conn.erase(d_port);
c1_conn.erase(q_port);
c2_conn.erase(d_port);
c2_conn.erase(q_port);
if (c1_conn != c2_conn)
goto start_cell;
continue;
}
start_cell:
chain_start_cells.insert(it.second);
}
}
vector<Cell*> create_chain(Cell *start_cell)
{
vector<Cell*> chain;
Cell *c = start_cell;
while (c != nullptr)
{
chain.push_back(c);
IdString q_port = opts.ffcells.at(c->type).second;
SigBit q_bit = sigmap(c->getPort(q_port).as_bit());
if (sigbit_chain_next.count(q_bit) == 0)
break;
c = sigbit_chain_next.at(q_bit);
if (chain_start_cells.count(c) != 0)
break;
}
return chain;
}
void process_chain(vector<Cell*> &chain)
{
if (GetSize(chain) < opts.keep_before + opts.minlen + opts.keep_after)
return;
int cursor = opts.keep_before;
while (cursor < GetSize(chain) - opts.keep_after)
{
int depth = GetSize(chain) - opts.keep_after - cursor;
if (opts.maxlen > 0)
depth = std::min(opts.maxlen, depth);
Cell *first_cell = chain[cursor], *last_cell = chain[cursor+depth-1];
if (depth < 2)
return;
log("Converting %s.%s ... %s.%s to a shift register with depth %d.\n",
log_id(module), log_id(first_cell), log_id(module), log_id(last_cell), depth);
dff_count += depth;
shreg_count += 1;
string shreg_cell_type_str = "$__SHREG";
if (first_cell->type[1] != '_')
shreg_cell_type_str += "_";
shreg_cell_type_str += first_cell->type.substr(1);
IdString q_port = opts.ffcells.at(first_cell->type).second;
first_cell->type = shreg_cell_type_str;
first_cell->setPort(q_port, last_cell->getPort(q_port));
first_cell->setParam("\\DEPTH", depth);
for (int i = 1; i < depth; i++)
remove_cells.insert(chain[cursor+i]);
cursor += depth;
}
}
void cleanup()
{
for (auto cell : remove_cells)
module->remove(cell);
remove_cells.clear();
sigbit_chain_next.clear();
sigbit_chain_prev.clear();
chain_start_cells.clear();
}
ShregmapWorker(Module *module, const ShregmapOptions &opts) :
module(module), sigmap(module), opts(opts), dff_count(0), shreg_count(0)
{
make_sigbit_chain_next_prev();
find_chain_start_cells();
for (auto c : chain_start_cells) {
vector<Cell*> chain = create_chain(c);
process_chain(chain);
}
cleanup();
}
};
struct ShregmapPass : public Pass {
ShregmapPass() : Pass("shregmap", "map shift registers") { }
virtual void help()
{
// |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
log("\n");
log(" shregmap [options] [selection]\n");
log("\n");
log("This pass converts chains of $_DFF_[NP]_ gates to target specific shift register.\n");
log("primitives. The generated shift register will be of type $__SHREG_DFF_[NP]_ and\n");
log("will use the same interface as the original $_DFF_*_ cells. The cell parameter\n");
log("'DEPTH' will contain the depth of the shift register. Use a target-specific\n");
log("'techmap' map file to convert those cells to the actual target cells.\n");
log("\n");
log(" -minlen N\n");
log(" minimum length of shift register (default = 2)\n");
log(" (this is the length after -keep_before and -keep_after)\n");
log("\n");
log(" -maxlen N\n");
log(" maximum length of shift register (default = no limit)\n");
log(" larger chains will be mapped to multiple shift register instances\n");
log("\n");
log(" -keep_before N\n");
log(" number of DFFs to keep before the shift register (default = 0)\n");
log("\n");
log(" -keep_after N\n");
log(" number of DFFs to keep after the shift register (default = 0)\n");
log("\n");
log(" -clkpol pos|neg|any\n");
log(" limit match to only positive or negative edge clocks. (default = any)\n");
log("\n");
log(" -enpol pos|neg|none|any_or_none|any\n");
log(" limit match to FFs with the specified enable polarity. (default = none)\n");
log("\n");
log(" -match <cell_type>[:<d_port_name>:<q_port_name>]\n");
log(" match the specified cells instead of $_DFF_N_ and $_DFF_P_. If\n");
log(" ':<d_port_name>:<q_port_name>' is omitted then 'D' and 'Q' is used\n");
log(" by default. E.g. the option '-clkpol pos' is just an alias for\n");
log(" '-match $_DFF_P_', which is an alias for '-match $_DFF_P_:D:Q'.\n");
log("\n");
}
virtual void execute(std::vector<std::string> args, RTLIL::Design *design)
{
ShregmapOptions opts;
string clkpol, enpol;
log_header("Executing SHREGMAP pass (map shift registers).\n");
size_t argidx;
for (argidx = 1; argidx < args.size(); argidx++)
{
if (args[argidx] == "-clkpol" && argidx+1 < args.size()) {
clkpol = args[++argidx];
continue;
}
if (args[argidx] == "-enpol" && argidx+1 < args.size()) {
enpol = args[++argidx];
continue;
}
if (args[argidx] == "-match" && argidx+1 < args.size()) {
vector<string> match_args = split_tokens(args[++argidx], ":");
if (GetSize(match_args) < 2)
match_args.push_back("D");
if (GetSize(match_args) < 3)
match_args.push_back("Q");
IdString id_cell_type(RTLIL::escape_id(match_args[0]));
IdString id_d_port_name(RTLIL::escape_id(match_args[1]));
IdString id_q_port_name(RTLIL::escape_id(match_args[2]));
opts.ffcells[id_cell_type] = make_pair(id_d_port_name, id_q_port_name);
continue;
}
if (args[argidx] == "-minlen" && argidx+1 < args.size()) {
opts.minlen = atoi(args[++argidx].c_str());
continue;
}
if (args[argidx] == "-maxlen" && argidx+1 < args.size()) {
opts.maxlen = atoi(args[++argidx].c_str());
continue;
}
if (args[argidx] == "-keep_before" && argidx+1 < args.size()) {
opts.keep_before = atoi(args[++argidx].c_str());
continue;
}
if (args[argidx] == "-keep_after" && argidx+1 < args.size()) {
opts.keep_after = atoi(args[++argidx].c_str());
continue;
}
break;
}
extra_args(args, argidx, design);
if (opts.ffcells.empty())
{
bool clk_pos = clkpol == "" || clkpol == "pos" || clkpol == "any";
bool clk_neg = clkpol == "" || clkpol == "neg" || clkpol == "any";
bool en_none = enpol == "" || enpol == "none" || enpol == "any_or_none";
bool en_pos = enpol == "pos" || enpol == "any" || enpol == "any_or_none";
bool en_neg = enpol == "neg" || enpol == "any" || enpol == "any_or_none";
if (clk_pos && en_none)
opts.ffcells["$_DFF_P_"] = make_pair(IdString("\\D"), IdString("\\Q"));
if (clk_neg && en_none)
opts.ffcells["$_DFF_N_"] = make_pair(IdString("\\D"), IdString("\\Q"));
if (clk_pos && en_pos)
opts.ffcells["$_DFFE_PP_"] = make_pair(IdString("\\D"), IdString("\\Q"));
if (clk_pos && en_neg)
opts.ffcells["$_DFFE_PN_"] = make_pair(IdString("\\D"), IdString("\\Q"));
if (clk_neg && en_pos)
opts.ffcells["$_DFFE_NP_"] = make_pair(IdString("\\D"), IdString("\\Q"));
if (clk_neg && en_neg)
opts.ffcells["$_DFFE_NN_"] = make_pair(IdString("\\D"), IdString("\\Q"));
}
else
{
if (!clkpol.empty())
log_cmd_error("Options -clkpol and -match are exclusive!\n");
if (!enpol.empty())
log_cmd_error("Options -enpol and -match are exclusive!\n");
}
int dff_count = 0;
int shreg_count = 0;
for (auto module : design->selected_modules()) {
ShregmapWorker worker(module, opts);
dff_count += worker.dff_count;
shreg_count += worker.shreg_count;
}
log("Converted %d dff cells into %d shift registers.\n", dff_count, shreg_count);
}
} ShregmapPass;
PRIVATE_NAMESPACE_END
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2014 Pelagicore AB
* All rights reserved.
*/
#include "CommandLineParser.h"
#include "debug.h"
#include "paminterface.h"
#include "pelagicontain.h"
#include "pelagicontaintodbusadapter.h"
#include "dbusmainloop.h"
#include "generators.h" /* used for gen_ct_name */
#include "pulsegateway.h"
#include "networkgateway.h"
#include "dbusgateway.h"
#include <sys/stat.h>
LOG_DEFINE_APP_IDS("PCON", "Pelagicontain");
LOG_DECLARE_CONTEXT(Pelagicontain_DefaultLogContext, "PCON", "Main context");
#ifndef CONFIG
#error Must define CONFIG; path to configuration file (/etc/pelagicontain?)
#endif
int main(int argc, char **argv)
{
const char *summary = "Pelagicore container utility. "
"Requires an absolute path to the container root, "
"the command to run inside the container and "
"an alphanumerical cookie string as first, second and third "
"argument respectively";
const char *paramsDescription = "[container root directory (abs path)] "
"[command] [cookie]";
pelagicore::CommandLineParser commandLineParser(summary,
paramsDescription,
PACKAGE_VERSION,
"");
std::string containerRoot;
std::string containedCommand;
std::string cookie;
const char* configFilePath = CONFIG;
commandLineParser.addOption(configFilePath, "with-config-file", 'c', "Config file");
if (commandLineParser.parse(argc, argv))
return -1;
if (argc < 4) {
log_error("Invalid arguments");
commandLineParser.printHelp();
return -1;
} else {
containerRoot = std::string(argv[1]);
containedCommand = std::string(argv[2]);
cookie = std::string(argv[3]);
}
if (containerRoot.c_str()[0] != '/') {
log_error("Path to container root must be absolute");
commandLineParser.printHelp();
return -1;
}
std::string containerName = gen_ct_name();
std::string containerConfig(configFilePath);
// Create gateway directory for container in containerRoot/gateways.
// This dir will contain various sockets etc acting as gateways
// in/out of the container.
std::string containerDir = containerRoot + "/" + containerName;
std::string gatewayDir = containerDir + "/gateways";
if (mkdir(containerDir.c_str(), S_IRWXU) == -1)
{
log_error("Could not create gateway directory %s, %s.",
containerDir.c_str(),
strerror(errno));
exit(-1);
}
if (mkdir(gatewayDir.c_str(), S_IRWXU) == -1)
{
log_error("Could not create gateway directory %s, %s.",
gatewayDir.c_str(),
strerror(errno));
exit(-1);
}
{ // Create a new scope so that we can du clean up after dtors
DBus::BusDispatcher dispatcher;
DBus::default_dispatcher = &dispatcher;
DBus::Connection bus = DBus::Connection::SessionBus();
/* Pelagicontain needs an interface to the mainloop so it can
* exit it when we are to clean up and shut down
*/
DBusMainloop dbusmainloop(&dispatcher);
/* The request_name call does not return anything but raises an
* exception if the name cannot be requested.
*/
bus.request_name("com.pelagicore.Pelagicontain");
PAMInterface pamInterface(bus);
ControllerInterface controllerInterface(gatewayDir);
Pelagicontain pelagicontain(&pamInterface, &dbusmainloop, &controllerInterface, cookie);
std::string baseObjPath("/com/pelagicore/Pelagicontain/");
std::string fullObjPath = baseObjPath + cookie;
PelagicontainToDBusAdapter pcAdapter(bus, fullObjPath, pelagicontain);
pelagicontain.addGateway(new NetworkGateway(&controllerInterface));
pelagicontain.addGateway(new PulseGateway(gatewayDir, containerName));
pelagicontain.addGateway(new DBusGateway(&controllerInterface,
DBusGateway::SessionProxy, gatewayDir, containerName,
containerConfig));
pelagicontain.addGateway(new DBusGateway(&controllerInterface,
DBusGateway::SystemProxy, gatewayDir, containerName,
containerConfig));
//pelagicontain.initialize(containerName, containerConfig, containerRoot);
//pid_t pcPid = pelagicontain.preload(containerRoot, containedCommand, cookie);
pid_t pcPid = pelagicontain.preload(containerName, containerConfig, containerRoot, containedCommand);
log_debug("Started Pelagicontain with PID: %d", pcPid);
dbusmainloop.enter();
}
// remove instance specific dirs again
if (rmdir(gatewayDir.c_str()) == -1)
{
log_error("Cannot delete dir %s, %s", gatewayDir.c_str(), strerror(errno));
}
if (rmdir(containerDir.c_str()) == -1)
{
log_error("Cannot delete dir %s, %s", gatewayDir.c_str(), strerror(errno));
}
}
<commit_msg>pelagicontain: Added log message after dbus mainloop ends<commit_after>/*
* Copyright (C) 2014 Pelagicore AB
* All rights reserved.
*/
#include "CommandLineParser.h"
#include "debug.h"
#include "paminterface.h"
#include "pelagicontain.h"
#include "pelagicontaintodbusadapter.h"
#include "dbusmainloop.h"
#include "generators.h" /* used for gen_ct_name */
#include "pulsegateway.h"
#include "networkgateway.h"
#include "dbusgateway.h"
#include <sys/stat.h>
LOG_DEFINE_APP_IDS("PCON", "Pelagicontain");
LOG_DECLARE_CONTEXT(Pelagicontain_DefaultLogContext, "PCON", "Main context");
#ifndef CONFIG
#error Must define CONFIG; path to configuration file (/etc/pelagicontain?)
#endif
int main(int argc, char **argv)
{
const char *summary = "Pelagicore container utility. "
"Requires an absolute path to the container root, "
"the command to run inside the container and "
"an alphanumerical cookie string as first, second and third "
"argument respectively";
const char *paramsDescription = "[container root directory (abs path)] "
"[command] [cookie]";
pelagicore::CommandLineParser commandLineParser(summary,
paramsDescription,
PACKAGE_VERSION,
"");
std::string containerRoot;
std::string containedCommand;
std::string cookie;
const char* configFilePath = CONFIG;
commandLineParser.addOption(configFilePath, "with-config-file", 'c', "Config file");
if (commandLineParser.parse(argc, argv))
return -1;
if (argc < 4) {
log_error("Invalid arguments");
commandLineParser.printHelp();
return -1;
} else {
containerRoot = std::string(argv[1]);
containedCommand = std::string(argv[2]);
cookie = std::string(argv[3]);
}
if (containerRoot.c_str()[0] != '/') {
log_error("Path to container root must be absolute");
commandLineParser.printHelp();
return -1;
}
std::string containerName = gen_ct_name();
std::string containerConfig(configFilePath);
// Create gateway directory for container in containerRoot/gateways.
// This dir will contain various sockets etc acting as gateways
// in/out of the container.
std::string containerDir = containerRoot + "/" + containerName;
std::string gatewayDir = containerDir + "/gateways";
if (mkdir(containerDir.c_str(), S_IRWXU) == -1)
{
log_error("Could not create gateway directory %s, %s.",
containerDir.c_str(),
strerror(errno));
exit(-1);
}
if (mkdir(gatewayDir.c_str(), S_IRWXU) == -1)
{
log_error("Could not create gateway directory %s, %s.",
gatewayDir.c_str(),
strerror(errno));
exit(-1);
}
{ // Create a new scope so that we can du clean up after dtors
DBus::BusDispatcher dispatcher;
DBus::default_dispatcher = &dispatcher;
DBus::Connection bus = DBus::Connection::SessionBus();
/* Pelagicontain needs an interface to the mainloop so it can
* exit it when we are to clean up and shut down
*/
DBusMainloop dbusmainloop(&dispatcher);
/* The request_name call does not return anything but raises an
* exception if the name cannot be requested.
*/
bus.request_name("com.pelagicore.Pelagicontain");
PAMInterface pamInterface(bus);
ControllerInterface controllerInterface(gatewayDir);
Pelagicontain pelagicontain(&pamInterface, &dbusmainloop, &controllerInterface, cookie);
std::string baseObjPath("/com/pelagicore/Pelagicontain/");
std::string fullObjPath = baseObjPath + cookie;
PelagicontainToDBusAdapter pcAdapter(bus, fullObjPath, pelagicontain);
pelagicontain.addGateway(new NetworkGateway(&controllerInterface));
pelagicontain.addGateway(new PulseGateway(gatewayDir, containerName));
pelagicontain.addGateway(new DBusGateway(&controllerInterface,
DBusGateway::SessionProxy, gatewayDir, containerName,
containerConfig));
pelagicontain.addGateway(new DBusGateway(&controllerInterface,
DBusGateway::SystemProxy, gatewayDir, containerName,
containerConfig));
//pelagicontain.initialize(containerName, containerConfig, containerRoot);
//pid_t pcPid = pelagicontain.preload(containerRoot, containedCommand, cookie);
pid_t pcPid = pelagicontain.preload(containerName, containerConfig, containerRoot, containedCommand);
log_debug("Started Pelagicontain with PID: %d", pcPid);
dbusmainloop.enter();
log_debug("Exited dbusmainloop.");
}
// remove instance specific dirs again
if (rmdir(gatewayDir.c_str()) == -1)
{
log_error("Cannot delete dir %s, %s", gatewayDir.c_str(), strerror(errno));
}
if (rmdir(containerDir.c_str()) == -1)
{
log_error("Cannot delete dir %s, %s", gatewayDir.c_str(), strerror(errno));
}
}
<|endoftext|> |
<commit_before>#include "CCharLayoutInfo.hpp"
#include "CToken.hpp"
namespace urde {
zeus::CVector3f CCharLayoutInfo::GetFromParentUnrotated(const CSegId& id) const {
const CCharLayoutNode::Bone& bone = x0_node->GetBoneMap()[id];
if (!x0_node->GetBoneMap().HasElement(bone.x0_parentId))
return bone.x4_origin;
else {
const CCharLayoutNode::Bone& pBone = x0_node->GetBoneMap()[bone.x0_parentId];
return bone.x4_origin - pBone.x4_origin;
}
}
zeus::CVector3f CCharLayoutInfo::GetFromRootUnrotated(const CSegId& id) const {
const CCharLayoutNode::Bone& bone = x0_node->GetBoneMap()[id];
return bone.x4_origin;
}
CSegId CCharLayoutInfo::GetSegIdFromString(std::string_view name) const {
const auto it = x18_segIdMap.find(name);
if (it == x18_segIdMap.cend()) {
return {};
}
return it->second;
}
void CCharLayoutNode::Bone::read(CInputStream& in) {
x0_parentId = CSegId(in);
x4_origin.readBig(in);
const u32 chCount = in.readUint32Big();
x10_children.reserve(chCount);
for (u32 i = 0; i < chCount; ++i) {
x10_children.emplace_back(in);
}
}
CCharLayoutNode::CCharLayoutNode(CInputStream& in) : x0_boneMap(in.readUint32Big()) {
const u32 cap = x0_boneMap.GetCapacity();
for (u32 i = 0; i < cap; ++i) {
const u32 thisId = in.readUint32Big();
Bone& bone = x0_boneMap[thisId];
bone.read(in);
}
}
CCharLayoutInfo::CCharLayoutInfo(CInputStream& in) : x0_node(std::make_shared<CCharLayoutNode>(in)), x8_segIdList(in) {
const atUint32 mapCount = in.readUint32Big();
for (atUint32 i = 0; i < mapCount; ++i) {
std::string key = in.readString();
x18_segIdMap.emplace(std::move(key), in);
}
}
CFactoryFnReturn FCharLayoutInfo(const SObjectTag&, CInputStream& in, const CVParamTransfer&,
CObjectReference* selfRef) {
return TToken<CCharLayoutInfo>::GetIObjObjectFor(std::make_unique<CCharLayoutInfo>(in));
}
} // namespace urde
<commit_msg>CCharLayoutInfo: Invert conditional within GetFromParentUnrotated()<commit_after>#include "CCharLayoutInfo.hpp"
#include "CToken.hpp"
namespace urde {
zeus::CVector3f CCharLayoutInfo::GetFromParentUnrotated(const CSegId& id) const {
const CCharLayoutNode::Bone& bone = x0_node->GetBoneMap()[id];
if (x0_node->GetBoneMap().HasElement(bone.x0_parentId)) {
const CCharLayoutNode::Bone& parent = x0_node->GetBoneMap()[bone.x0_parentId];
return bone.x4_origin - parent.x4_origin;
} else {
return bone.x4_origin;
}
}
zeus::CVector3f CCharLayoutInfo::GetFromRootUnrotated(const CSegId& id) const {
const CCharLayoutNode::Bone& bone = x0_node->GetBoneMap()[id];
return bone.x4_origin;
}
CSegId CCharLayoutInfo::GetSegIdFromString(std::string_view name) const {
const auto it = x18_segIdMap.find(name);
if (it == x18_segIdMap.cend()) {
return {};
}
return it->second;
}
void CCharLayoutNode::Bone::read(CInputStream& in) {
x0_parentId = CSegId(in);
x4_origin.readBig(in);
const u32 chCount = in.readUint32Big();
x10_children.reserve(chCount);
for (u32 i = 0; i < chCount; ++i) {
x10_children.emplace_back(in);
}
}
CCharLayoutNode::CCharLayoutNode(CInputStream& in) : x0_boneMap(in.readUint32Big()) {
const u32 cap = x0_boneMap.GetCapacity();
for (u32 i = 0; i < cap; ++i) {
const u32 thisId = in.readUint32Big();
Bone& bone = x0_boneMap[thisId];
bone.read(in);
}
}
CCharLayoutInfo::CCharLayoutInfo(CInputStream& in) : x0_node(std::make_shared<CCharLayoutNode>(in)), x8_segIdList(in) {
const atUint32 mapCount = in.readUint32Big();
for (atUint32 i = 0; i < mapCount; ++i) {
std::string key = in.readString();
x18_segIdMap.emplace(std::move(key), in);
}
}
CFactoryFnReturn FCharLayoutInfo(const SObjectTag&, CInputStream& in, const CVParamTransfer&,
CObjectReference* selfRef) {
return TToken<CCharLayoutInfo>::GetIObjObjectFor(std::make_unique<CCharLayoutInfo>(in));
}
} // namespace urde
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2015 The WebM 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 "third_party/googletest/src/include/gtest/gtest.h"
#include "test/codec_factory.h"
#include "test/encode_test_driver.h"
#include "test/util.h"
#include "test/y4m_video_source.h"
#include "test/yuv_video_source.h"
#include "vp9/encoder/vp9_ratectrl.h"
namespace {
const unsigned int kFrames = 100;
const int kBitrate = 500;
#define ARF_NOT_SEEN 1000001
#define ARF_SEEN_ONCE 1000000
typedef struct {
const char *filename;
unsigned int width;
unsigned int height;
unsigned int framerate_num;
unsigned int framerate_den;
unsigned int input_bit_depth;
vpx_img_fmt fmt;
vpx_bit_depth_t bit_depth;
unsigned int profile;
} TestVideoParam;
typedef struct {
libvpx_test::TestMode mode;
int cpu_used;
} TestEncodeParam;
const TestVideoParam kTestVectors[] = {
// artificially increase framerate to trigger default check
{"hantro_collage_w352h288.yuv", 352, 288, 5000, 1,
8, VPX_IMG_FMT_I420, VPX_BITS_8, 0},
{"hantro_collage_w352h288.yuv", 352, 288, 30, 1,
8, VPX_IMG_FMT_I420, VPX_BITS_8, 0},
{"rush_hour_444.y4m", 352, 288, 30, 1,
8, VPX_IMG_FMT_I444, VPX_BITS_8, 1},
#if CONFIG_VP9_HIGHBITDEPTH
// Add list of profile 2/3 test videos here ...
#endif // CONFIG_VP9_HIGHBITDEPTH
};
const TestEncodeParam kEncodeVectors[] = {
{::libvpx_test::kOnePassGood, 2},
{::libvpx_test::kOnePassGood, 5},
{::libvpx_test::kTwoPassGood, 1},
{::libvpx_test::kTwoPassGood, 2},
{::libvpx_test::kTwoPassGood, 5},
{::libvpx_test::kRealTime, 5},
};
const int kMinArfVectors[] = {
// NOTE: 0 refers to the default built-in logic in:
// vp9_rc_get_default_min_gf_interval(...)
0, 4, 8, 12, 15
};
int is_extension_y4m(const char *filename) {
const char *dot = strrchr(filename, '.');
if (!dot || dot == filename)
return 0;
else
return !strcmp(dot, ".y4m");
}
class ArfFreqTestLarge
: public ::libvpx_test::EncoderTest,
public ::libvpx_test::CodecTestWith3Params<TestVideoParam, \
TestEncodeParam, int> {
protected:
ArfFreqTestLarge()
: EncoderTest(GET_PARAM(0)),
test_video_param_(GET_PARAM(1)),
test_encode_param_(GET_PARAM(2)),
min_arf_requested_(GET_PARAM(3)) {
}
virtual ~ArfFreqTestLarge() {}
virtual void SetUp() {
InitializeConfig();
SetMode(test_encode_param_.mode);
if (test_encode_param_.mode != ::libvpx_test::kRealTime) {
cfg_.g_lag_in_frames = 25;
cfg_.rc_end_usage = VPX_VBR;
} else {
cfg_.g_lag_in_frames = 0;
cfg_.rc_end_usage = VPX_CBR;
cfg_.rc_buf_sz = 1000;
cfg_.rc_buf_initial_sz = 500;
cfg_.rc_buf_optimal_sz = 600;
}
dec_cfg_.threads = 4;
}
virtual void BeginPassHook(unsigned int) {
min_run_ = ARF_NOT_SEEN;
run_of_visible_frames_ = 0;
}
int GetNumFramesInPkt(const vpx_codec_cx_pkt_t *pkt) {
const uint8_t *buffer = reinterpret_cast<uint8_t*>(pkt->data.frame.buf);
const uint8_t marker = buffer[pkt->data.frame.sz - 1];
const int mag = ((marker >> 3) & 3) + 1;
int frames = (marker & 0x7) + 1;
const unsigned int index_sz = 2 + mag * frames;
// Check for superframe or not.
// Assume superframe has only one visible frame, the rest being
// invisible. If superframe index is not found, then there is only
// one frame.
if (!((marker & 0xe0) == 0xc0 &&
pkt->data.frame.sz >= index_sz &&
buffer[pkt->data.frame.sz - index_sz] == marker)) {
frames = 1;
}
return frames;
}
virtual void FramePktHook(const vpx_codec_cx_pkt_t *pkt) {
if (pkt->kind != VPX_CODEC_CX_FRAME_PKT)
return;
const int frames = GetNumFramesInPkt(pkt);
if (frames == 1) {
run_of_visible_frames_++;
} else if (frames == 2) {
if (min_run_ == ARF_NOT_SEEN) {
min_run_ = ARF_SEEN_ONCE;
} else if (min_run_ == ARF_SEEN_ONCE ||
run_of_visible_frames_ < min_run_) {
min_run_ = run_of_visible_frames_;
}
run_of_visible_frames_ = 1;
} else {
min_run_ = 0;
run_of_visible_frames_ = 1;
}
}
virtual void PreEncodeFrameHook(::libvpx_test::VideoSource *video,
::libvpx_test::Encoder *encoder) {
if (video->frame() == 0) {
encoder->Control(VP9E_SET_FRAME_PARALLEL_DECODING, 1);
encoder->Control(VP9E_SET_TILE_COLUMNS, 4);
encoder->Control(VP8E_SET_CPUUSED, test_encode_param_.cpu_used);
encoder->Control(VP9E_SET_MIN_GF_INTERVAL, min_arf_requested_);
if (test_encode_param_.mode != ::libvpx_test::kRealTime) {
encoder->Control(VP8E_SET_ENABLEAUTOALTREF, 1);
encoder->Control(VP8E_SET_ARNR_MAXFRAMES, 7);
encoder->Control(VP8E_SET_ARNR_STRENGTH, 5);
encoder->Control(VP8E_SET_ARNR_TYPE, 3);
}
}
}
int GetMinVisibleRun() const {
return min_run_;
}
int GetMinArfDistanceRequested() const {
if (min_arf_requested_)
return min_arf_requested_;
else
return vp9_rc_get_default_min_gf_interval(
test_video_param_.width, test_video_param_.height,
(double)test_video_param_.framerate_num /
test_video_param_.framerate_den);
}
TestVideoParam test_video_param_;
TestEncodeParam test_encode_param_;
private:
int min_arf_requested_;
int min_run_;
int run_of_visible_frames_;
};
TEST_P(ArfFreqTestLarge, MinArfFreqTest) {
cfg_.rc_target_bitrate = kBitrate;
cfg_.g_error_resilient = 0;
cfg_.g_profile = test_video_param_.profile;
cfg_.g_input_bit_depth = test_video_param_.input_bit_depth;
cfg_.g_bit_depth = test_video_param_.bit_depth;
init_flags_ = VPX_CODEC_USE_PSNR;
if (cfg_.g_bit_depth > 8)
init_flags_ |= VPX_CODEC_USE_HIGHBITDEPTH;
libvpx_test::VideoSource *video;
if (is_extension_y4m(test_video_param_.filename)) {
video = new libvpx_test::Y4mVideoSource(test_video_param_.filename,
0, kFrames);
} else {
video = new libvpx_test::YUVVideoSource(test_video_param_.filename,
test_video_param_.fmt,
test_video_param_.width,
test_video_param_.height,
test_video_param_.framerate_num,
test_video_param_.framerate_den,
0, kFrames);
}
ASSERT_NO_FATAL_FAILURE(RunLoop(video));
const int min_run = GetMinVisibleRun();
const int min_arf_dist_requested = GetMinArfDistanceRequested();
if (min_run != ARF_NOT_SEEN && min_run != ARF_SEEN_ONCE) {
const int min_arf_dist = min_run + 1;
EXPECT_GE(min_arf_dist, min_arf_dist_requested);
}
delete(video);
}
VP9_INSTANTIATE_TEST_CASE(
ArfFreqTestLarge,
::testing::ValuesIn(kTestVectors),
::testing::ValuesIn(kEncodeVectors),
::testing::ValuesIn(kMinArfVectors));
#if CONFIG_VP9_HIGHBITDEPTH
#if CONFIG_VP10_ENCODER
// TODO(angiebird): 25-29 fail in high bitdepth mode.
INSTANTIATE_TEST_CASE_P(
DISABLED_VP10, ArfFreqTestLarge,
::testing::Combine(
::testing::Values(static_cast<const libvpx_test::CodecFactory *>(
&libvpx_test::kVP10)),
::testing::ValuesIn(kTestVectors),
::testing::ValuesIn(kEncodeVectors),
::testing::ValuesIn(kMinArfVectors)));
#endif // CONFIG_VP10_ENCODER
#else
VP10_INSTANTIATE_TEST_CASE(
ArfFreqTestLarge,
::testing::ValuesIn(kTestVectors),
::testing::ValuesIn(kEncodeVectors),
::testing::ValuesIn(kMinArfVectors));
#endif // CONFIG_VP9_HIGHBITDEPTH
} // namespace
<commit_msg>Disable the unit test of ArfFreq for BIDIR_PRED<commit_after>/*
* Copyright (c) 2015 The WebM 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 "third_party/googletest/src/include/gtest/gtest.h"
#include "test/codec_factory.h"
#include "test/encode_test_driver.h"
#include "test/util.h"
#include "test/y4m_video_source.h"
#include "test/yuv_video_source.h"
#include "vp9/encoder/vp9_ratectrl.h"
namespace {
const unsigned int kFrames = 100;
const int kBitrate = 500;
#define ARF_NOT_SEEN 1000001
#define ARF_SEEN_ONCE 1000000
typedef struct {
const char *filename;
unsigned int width;
unsigned int height;
unsigned int framerate_num;
unsigned int framerate_den;
unsigned int input_bit_depth;
vpx_img_fmt fmt;
vpx_bit_depth_t bit_depth;
unsigned int profile;
} TestVideoParam;
typedef struct {
libvpx_test::TestMode mode;
int cpu_used;
} TestEncodeParam;
const TestVideoParam kTestVectors[] = {
// artificially increase framerate to trigger default check
{"hantro_collage_w352h288.yuv", 352, 288, 5000, 1,
8, VPX_IMG_FMT_I420, VPX_BITS_8, 0},
{"hantro_collage_w352h288.yuv", 352, 288, 30, 1,
8, VPX_IMG_FMT_I420, VPX_BITS_8, 0},
{"rush_hour_444.y4m", 352, 288, 30, 1,
8, VPX_IMG_FMT_I444, VPX_BITS_8, 1},
#if CONFIG_VP9_HIGHBITDEPTH
// Add list of profile 2/3 test videos here ...
#endif // CONFIG_VP9_HIGHBITDEPTH
};
const TestEncodeParam kEncodeVectors[] = {
{::libvpx_test::kOnePassGood, 2},
{::libvpx_test::kOnePassGood, 5},
{::libvpx_test::kTwoPassGood, 1},
{::libvpx_test::kTwoPassGood, 2},
{::libvpx_test::kTwoPassGood, 5},
{::libvpx_test::kRealTime, 5},
};
const int kMinArfVectors[] = {
// NOTE: 0 refers to the default built-in logic in:
// vp9_rc_get_default_min_gf_interval(...)
0, 4, 8, 12, 15
};
int is_extension_y4m(const char *filename) {
const char *dot = strrchr(filename, '.');
if (!dot || dot == filename)
return 0;
else
return !strcmp(dot, ".y4m");
}
class ArfFreqTestLarge
: public ::libvpx_test::EncoderTest,
public ::libvpx_test::CodecTestWith3Params<TestVideoParam, \
TestEncodeParam, int> {
protected:
ArfFreqTestLarge()
: EncoderTest(GET_PARAM(0)),
test_video_param_(GET_PARAM(1)),
test_encode_param_(GET_PARAM(2)),
min_arf_requested_(GET_PARAM(3)) {
}
virtual ~ArfFreqTestLarge() {}
virtual void SetUp() {
InitializeConfig();
SetMode(test_encode_param_.mode);
if (test_encode_param_.mode != ::libvpx_test::kRealTime) {
cfg_.g_lag_in_frames = 25;
cfg_.rc_end_usage = VPX_VBR;
} else {
cfg_.g_lag_in_frames = 0;
cfg_.rc_end_usage = VPX_CBR;
cfg_.rc_buf_sz = 1000;
cfg_.rc_buf_initial_sz = 500;
cfg_.rc_buf_optimal_sz = 600;
}
dec_cfg_.threads = 4;
}
virtual void BeginPassHook(unsigned int) {
min_run_ = ARF_NOT_SEEN;
run_of_visible_frames_ = 0;
}
int GetNumFramesInPkt(const vpx_codec_cx_pkt_t *pkt) {
const uint8_t *buffer = reinterpret_cast<uint8_t*>(pkt->data.frame.buf);
const uint8_t marker = buffer[pkt->data.frame.sz - 1];
const int mag = ((marker >> 3) & 3) + 1;
int frames = (marker & 0x7) + 1;
const unsigned int index_sz = 2 + mag * frames;
// Check for superframe or not.
// Assume superframe has only one visible frame, the rest being
// invisible. If superframe index is not found, then there is only
// one frame.
if (!((marker & 0xe0) == 0xc0 &&
pkt->data.frame.sz >= index_sz &&
buffer[pkt->data.frame.sz - index_sz] == marker)) {
frames = 1;
}
return frames;
}
virtual void FramePktHook(const vpx_codec_cx_pkt_t *pkt) {
if (pkt->kind != VPX_CODEC_CX_FRAME_PKT)
return;
const int frames = GetNumFramesInPkt(pkt);
if (frames == 1) {
run_of_visible_frames_++;
} else if (frames == 2) {
if (min_run_ == ARF_NOT_SEEN) {
min_run_ = ARF_SEEN_ONCE;
} else if (min_run_ == ARF_SEEN_ONCE ||
run_of_visible_frames_ < min_run_) {
min_run_ = run_of_visible_frames_;
}
run_of_visible_frames_ = 1;
} else {
min_run_ = 0;
run_of_visible_frames_ = 1;
}
}
virtual void PreEncodeFrameHook(::libvpx_test::VideoSource *video,
::libvpx_test::Encoder *encoder) {
if (video->frame() == 0) {
encoder->Control(VP9E_SET_FRAME_PARALLEL_DECODING, 1);
encoder->Control(VP9E_SET_TILE_COLUMNS, 4);
encoder->Control(VP8E_SET_CPUUSED, test_encode_param_.cpu_used);
encoder->Control(VP9E_SET_MIN_GF_INTERVAL, min_arf_requested_);
if (test_encode_param_.mode != ::libvpx_test::kRealTime) {
encoder->Control(VP8E_SET_ENABLEAUTOALTREF, 1);
encoder->Control(VP8E_SET_ARNR_MAXFRAMES, 7);
encoder->Control(VP8E_SET_ARNR_STRENGTH, 5);
encoder->Control(VP8E_SET_ARNR_TYPE, 3);
}
}
}
int GetMinVisibleRun() const {
return min_run_;
}
int GetMinArfDistanceRequested() const {
if (min_arf_requested_)
return min_arf_requested_;
else
return vp9_rc_get_default_min_gf_interval(
test_video_param_.width, test_video_param_.height,
(double)test_video_param_.framerate_num /
test_video_param_.framerate_den);
}
TestVideoParam test_video_param_;
TestEncodeParam test_encode_param_;
private:
int min_arf_requested_;
int min_run_;
int run_of_visible_frames_;
};
TEST_P(ArfFreqTestLarge, MinArfFreqTest) {
cfg_.rc_target_bitrate = kBitrate;
cfg_.g_error_resilient = 0;
cfg_.g_profile = test_video_param_.profile;
cfg_.g_input_bit_depth = test_video_param_.input_bit_depth;
cfg_.g_bit_depth = test_video_param_.bit_depth;
init_flags_ = VPX_CODEC_USE_PSNR;
if (cfg_.g_bit_depth > 8)
init_flags_ |= VPX_CODEC_USE_HIGHBITDEPTH;
libvpx_test::VideoSource *video;
if (is_extension_y4m(test_video_param_.filename)) {
video = new libvpx_test::Y4mVideoSource(test_video_param_.filename,
0, kFrames);
} else {
video = new libvpx_test::YUVVideoSource(test_video_param_.filename,
test_video_param_.fmt,
test_video_param_.width,
test_video_param_.height,
test_video_param_.framerate_num,
test_video_param_.framerate_den,
0, kFrames);
}
ASSERT_NO_FATAL_FAILURE(RunLoop(video));
const int min_run = GetMinVisibleRun();
const int min_arf_dist_requested = GetMinArfDistanceRequested();
if (min_run != ARF_NOT_SEEN && min_run != ARF_SEEN_ONCE) {
const int min_arf_dist = min_run + 1;
EXPECT_GE(min_arf_dist, min_arf_dist_requested);
}
delete(video);
}
VP9_INSTANTIATE_TEST_CASE(
ArfFreqTestLarge,
::testing::ValuesIn(kTestVectors),
::testing::ValuesIn(kEncodeVectors),
::testing::ValuesIn(kMinArfVectors));
#if CONFIG_VP9_HIGHBITDEPTH || CONFIG_BIDIR_PRED
#if CONFIG_VP10_ENCODER
// TODO(angiebird): 25-29 fail in high bitdepth mode.
// TODO(zoeliu): This ArfFreqTest does not work with BWDREF_FRAME, as
// BWDREF_FRAME is also a non-show frame, and the minimum run between two
// consecutive BWDREF_FRAME's may vary between 1 and any arbitrary positive
// number as long as it does not exceed the gf_group interval.
INSTANTIATE_TEST_CASE_P(
DISABLED_VP10, ArfFreqTestLarge,
::testing::Combine(
::testing::Values(static_cast<const libvpx_test::CodecFactory *>(
&libvpx_test::kVP10)),
::testing::ValuesIn(kTestVectors),
::testing::ValuesIn(kEncodeVectors),
::testing::ValuesIn(kMinArfVectors)));
#endif // CONFIG_VP10_ENCODER
#else
VP10_INSTANTIATE_TEST_CASE(
ArfFreqTestLarge,
::testing::ValuesIn(kTestVectors),
::testing::ValuesIn(kEncodeVectors),
::testing::ValuesIn(kMinArfVectors));
#endif // CONFIG_VP9_HIGHBITDEPTH || CONFIG_BIDIR_PRED
} // namespace
<|endoftext|> |
<commit_before>#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable : 4100 4701 4127 4706 4267 4324)
#endif
<commit_msg>beast seems to produce fewer warnings now<commit_after>#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable : 4100 4267)
#endif
<|endoftext|> |
<commit_before>#include "photoeffects.hpp"
#include <vector>
#include <iostream>
using namespace cv;
using namespace std;
Point topleftFind(Point firstPoint, Point secondPoint, int &Xsize, int &Ysize)
{
Point topleft(0, 0);
if(Xsize < 0)
{
topleft.x = firstPoint.x;
Xsize-=(2*Xsize);
}
else
{
topleft.x = secondPoint.x;
}
if(Ysize < 0)
{
topleft.y = secondPoint.y;
Ysize-=(2*Ysize);
}
else
{
topleft.y = firstPoint.y;
}
return topleft;
}
int matte(InputArray src, OutputArray dst, Point firstPoint, Point secondPoint, float sigma)
{
CV_Assert(src.type() == CV_8UC3);
Mat srcImg = src.getMat();
srcImg.convertTo(srcImg, CV_32FC3, 1.0f/255.0f);
Mat bg=Mat(srcImg.size(),CV_32FC3);
bg=Scalar(1.0f,1.0f,1.0f);
int Xsize = firstPoint.x - secondPoint.x;
int Ysize = firstPoint.y - secondPoint.y;
Point topLeft = topleftFind(firstPoint, secondPoint, Xsize, Ysize);
Mat meaningPart(srcImg.rows, srcImg.cols, CV_32FC1, Scalar(0.0f,0.0f,0.0f));
ellipse(meaningPart, Point((topLeft.x+Xsize/2),(topLeft.y-Ysize/2)),
Size(Xsize/2,Ysize/2),0, 0, 360, Scalar(1.0f,1.0f,1.0f), -1, 8);
Mat mask;
meaningPart.convertTo(mask,CV_32FC1);
threshold(1.0f-mask, mask, 0.9f, 1.0f, THRESH_BINARY_INV);
GaussianBlur(mask, mask, Size(127, 127), sigma);
vector<Mat> ch_img;
vector<Mat> ch_bg;
split(srcImg,ch_img);
split(bg, ch_bg);
ch_img[0]=ch_img[0].mul(mask)+ch_bg[0].mul(1.0f-mask);
ch_img[1]=ch_img[1].mul(mask)+ch_bg[1].mul(1.0f-mask);
ch_img[2]=ch_img[2].mul(mask)+ch_bg[2].mul(1.0f-mask);
merge(ch_img,dst);
merge(ch_bg,bg);
return 0;
}
<commit_msg>Fixed code and make it a bit clear.<commit_after>#include "photoeffects.hpp"
#include <vector>
using namespace cv;
using namespace std;
Point topleftFind(Point firstPoint, Point secondPoint, int &Xsize, int &Ysize)
{
Point topleft(0, 0);
if(Xsize < 0)
{
topleft.x = firstPoint.x;
Xsize-=(2*Xsize);
}
else
{
topleft.x = secondPoint.x;
}
if(Ysize < 0)
{
topleft.y = secondPoint.y;
Ysize-=(2*Ysize);
}
else
{
topleft.y = firstPoint.y;
}
return topleft;
}
int matte(InputArray src, OutputArray dst, Point firstPoint, Point secondPoint, float sigma)
{
CV_Assert(src.type() == CV_8UC3);
Mat srcImg = src.getMat();
srcImg.convertTo(srcImg, CV_32FC3, 1.0f/255.0f);
Mat bg=Mat(srcImg.size(),CV_32FC3);
bg=Scalar(1.0f,1.0f,1.0f);
int Xsize = firstPoint.x - secondPoint.x;
int Ysize = firstPoint.y - secondPoint.y;
Point topLeft = topleftFind(firstPoint, secondPoint, Xsize, Ysize);
Mat meaningPart(srcImg.rows, srcImg.cols, CV_32FC1, Scalar(0.0f,0.0f,0.0f));
ellipse(meaningPart, Point((topLeft.x+Xsize/2),(topLeft.y-Ysize/2)),
Size(Xsize/2,Ysize/2),0, 0, 360, Scalar(1.0f,1.0f,1.0f), -1, 8);
Mat mask;
meaningPart.convertTo(mask,CV_32FC1);
threshold(1.0f-mask, mask, 0.9f, 1.0f, THRESH_BINARY_INV);
GaussianBlur(mask, mask, Size(127, 127), sigma);
vector<Mat> ch_img;
vector<Mat> ch_bg;
split(srcImg,ch_img);
split(bg, ch_bg);
ch_img[0]=ch_img[0].mul(mask)+ch_bg[0].mul(1.0f-mask);
ch_img[1]=ch_img[1].mul(mask)+ch_bg[1].mul(1.0f-mask);
ch_img[2]=ch_img[2].mul(mask)+ch_bg[2].mul(1.0f-mask);
merge(ch_img,dst);
merge(ch_bg,bg);
return 0;
}
<|endoftext|> |
<commit_before>
/*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "Test.h"
#include "SkColor.h"
#include "SkColorFilter.h"
#include "SkRandom.h"
#include "SkXfermode.h"
static SkFlattenable* reincarnate_flattenable(SkFlattenable* obj) {
SkFlattenable::Factory fact = obj->getFactory();
if (NULL == fact) {
return NULL;
}
SkFlattenableWriteBuffer wb(1024);
obj->flatten(wb);
size_t size = wb.size();
SkAutoSMalloc<1024> storage(size);
// make a copy into storage
wb.flatten(storage.get());
SkFlattenableReadBuffer rb(storage.get(), size);
return fact(rb);
}
template <typename T> T* reincarnate(T* obj) {
return (T*)reincarnate_flattenable(obj);
}
///////////////////////////////////////////////////////////////////////////////
#define ILLEGAL_MODE ((SkXfermode::Mode)-1)
static void test_asColorMode(skiatest::Reporter* reporter) {
SkRandom rand;
for (int mode = 0; mode <= SkXfermode::kLastMode; mode++) {
SkColor color = rand.nextU();
// ensure we always get a filter, by avoiding the possibility of a
// special case that would return NULL (if color's alpha is 0 or 0xFF)
color = SkColorSetA(color, 0x7F);
SkColorFilter* cf = SkColorFilter::CreateModeFilter(color,
(SkXfermode::Mode)mode);
// allow for no filter if we're in Dst mode (its a no op)
if (SkXfermode::kDst_Mode == mode && NULL == cf) {
continue;
}
SkAutoUnref aur(cf);
REPORTER_ASSERT(reporter, cf);
SkColor c = ~color;
SkXfermode::Mode m = ILLEGAL_MODE;
SkColor expectedColor = color;
SkXfermode::Mode expectedMode = (SkXfermode::Mode)mode;
// SkDebugf("--- mc [%d %x] ", mode, color);
REPORTER_ASSERT(reporter, cf->asColorMode(&c, &m));
// handle special-case folding by the factory
if (SkXfermode::kClear_Mode == mode) {
if (c != expectedColor) {
expectedColor = 0;
}
if (m != expectedMode) {
expectedMode = SkXfermode::kSrc_Mode;
}
}
// SkDebugf("--- got [%d %x] expected [%d %x]\n", m, c, expectedMode, expectedColor);
REPORTER_ASSERT(reporter, c == expectedColor);
REPORTER_ASSERT(reporter, m == expectedMode);
{
SkColorFilter* cf2 = reincarnate(cf);
SkAutoUnref aur2(cf2);
REPORTER_ASSERT(reporter, cf2);
SkColor c2 = ~color;
SkXfermode::Mode m2 = ILLEGAL_MODE;
REPORTER_ASSERT(reporter, cf2->asColorMode(&c2, &m2));
REPORTER_ASSERT(reporter, c2 == expectedColor);
REPORTER_ASSERT(reporter, m2 == expectedMode);
}
}
}
#include "TestClassDef.h"
DEFINE_TESTCLASS("ColorFilter", ColorFilterTestClass, test_asColorMode)
<commit_msg>Fix test to use the flattenable writer class instead of flattening the object directly. Review URL: https://codereview.appspot.com/5901059<commit_after>
/*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "Test.h"
#include "SkColor.h"
#include "SkColorFilter.h"
#include "SkRandom.h"
#include "SkXfermode.h"
static SkFlattenable* reincarnate_flattenable(SkFlattenable* obj) {
SkFlattenableWriteBuffer wb(1024);
wb.writeFlattenable(obj);
size_t size = wb.size();
SkAutoSMalloc<1024> storage(size);
// make a copy into storage
wb.flatten(storage.get());
SkFlattenableReadBuffer rb(storage.get(), size);
return rb.readFlattenable();
}
template <typename T> T* reincarnate(T* obj) {
return (T*)reincarnate_flattenable(obj);
}
///////////////////////////////////////////////////////////////////////////////
#define ILLEGAL_MODE ((SkXfermode::Mode)-1)
static void test_asColorMode(skiatest::Reporter* reporter) {
SkRandom rand;
for (int mode = 0; mode <= SkXfermode::kLastMode; mode++) {
SkColor color = rand.nextU();
// ensure we always get a filter, by avoiding the possibility of a
// special case that would return NULL (if color's alpha is 0 or 0xFF)
color = SkColorSetA(color, 0x7F);
SkColorFilter* cf = SkColorFilter::CreateModeFilter(color,
(SkXfermode::Mode)mode);
// allow for no filter if we're in Dst mode (its a no op)
if (SkXfermode::kDst_Mode == mode && NULL == cf) {
continue;
}
SkAutoUnref aur(cf);
REPORTER_ASSERT(reporter, cf);
SkColor c = ~color;
SkXfermode::Mode m = ILLEGAL_MODE;
SkColor expectedColor = color;
SkXfermode::Mode expectedMode = (SkXfermode::Mode)mode;
// SkDebugf("--- mc [%d %x] ", mode, color);
REPORTER_ASSERT(reporter, cf->asColorMode(&c, &m));
// handle special-case folding by the factory
if (SkXfermode::kClear_Mode == mode) {
if (c != expectedColor) {
expectedColor = 0;
}
if (m != expectedMode) {
expectedMode = SkXfermode::kSrc_Mode;
}
}
// SkDebugf("--- got [%d %x] expected [%d %x]\n", m, c, expectedMode, expectedColor);
REPORTER_ASSERT(reporter, c == expectedColor);
REPORTER_ASSERT(reporter, m == expectedMode);
{
SkColorFilter* cf2 = reincarnate(cf);
SkAutoUnref aur2(cf2);
REPORTER_ASSERT(reporter, cf2);
SkColor c2 = ~color;
SkXfermode::Mode m2 = ILLEGAL_MODE;
REPORTER_ASSERT(reporter, cf2->asColorMode(&c2, &m2));
REPORTER_ASSERT(reporter, c2 == expectedColor);
REPORTER_ASSERT(reporter, m2 == expectedMode);
}
}
}
#include "TestClassDef.h"
DEFINE_TESTCLASS("ColorFilter", ColorFilterTestClass, test_asColorMode)
<|endoftext|> |
<commit_before>// Copyright (c) 2012 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 "webkit/glue/webcursor.h"
#include <X11/Xcursor/Xcursor.h>
#include <X11/Xlib.h>
#include <X11/cursorfont.h>
#include "base/logging.h"
#include "skia/ext/image_operations.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebCursorInfo.h"
#include "ui/base/cursor/cursor.h"
#include "ui/base/x/x11_util.h"
#include "ui/gfx/point_conversions.h"
#include "ui/gfx/size_conversions.h"
const ui::PlatformCursor WebCursor::GetPlatformCursor() {
if (platform_cursor_)
return platform_cursor_;
SkBitmap bitmap;
bitmap.setConfig(SkBitmap::kARGB_8888_Config,
custom_size_.width(), custom_size_.height());
bitmap.allocPixels();
memcpy(bitmap.getAddr32(0, 0), custom_data_.data(), custom_data_.size());
gfx::Point hotspot = hotspot_;
if (device_scale_factor_ != custom_scale_) {
float scale = device_scale_factor_ / custom_scale_;
gfx::Size scaled_size =
gfx::ToFlooredSize(gfx::ScaleSize(custom_size_, scale));
bitmap = skia::ImageOperations::Resize(bitmap,
skia::ImageOperations::RESIZE_BETTER,
scaled_size.width(),
scaled_size.height());
hotspot = gfx::ToFlooredPoint(gfx::ScalePoint(hotspot, scale));
}
XcursorImage* image = ui::SkBitmapToXcursorImage(&bitmap, hotspot);
platform_cursor_ = ui::CreateReffedCustomXCursor(image);
return platform_cursor_;
}
void WebCursor::SetDeviceScaleFactor(float scale_factor) {
if (device_scale_factor_ == scale_factor)
return;
device_scale_factor_ = scale_factor;
if (platform_cursor_)
ui::UnrefCustomXCursor(platform_cursor_);
platform_cursor_ = 0;
// It is not necessary to recreate platform_cursor_ yet, since it will be
// recreated on demand when GetPlatformCursor is called.
}
void WebCursor::InitPlatformData() {
platform_cursor_ = 0;
device_scale_factor_ = 1.f;
}
bool WebCursor::SerializePlatformData(Pickle* pickle) const {
return true;
}
bool WebCursor::DeserializePlatformData(PickleIterator* iter) {
return true;
}
bool WebCursor::IsPlatformDataEqual(const WebCursor& other) const {
return true;
}
void WebCursor::CleanupPlatformData() {
if (platform_cursor_) {
ui::UnrefCustomXCursor(platform_cursor_);
platform_cursor_ = 0;
}
}
void WebCursor::CopyPlatformData(const WebCursor& other) {
if (platform_cursor_)
ui::UnrefCustomXCursor(platform_cursor_);
platform_cursor_ = other.platform_cursor_;
if (platform_cursor_)
ui::RefCustomXCursor(platform_cursor_);
device_scale_factor_ = other.device_scale_factor_;
}
<commit_msg>webcursor-x11: Do not attempt to create a custom cursor when there's no data.<commit_after>// Copyright (c) 2012 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 "webkit/glue/webcursor.h"
#include <X11/Xcursor/Xcursor.h>
#include <X11/Xlib.h>
#include <X11/cursorfont.h>
#include "base/logging.h"
#include "skia/ext/image_operations.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebCursorInfo.h"
#include "ui/base/cursor/cursor.h"
#include "ui/base/x/x11_util.h"
#include "ui/gfx/point_conversions.h"
#include "ui/gfx/size_conversions.h"
const ui::PlatformCursor WebCursor::GetPlatformCursor() {
if (platform_cursor_)
return platform_cursor_;
if (custom_data_.size() == 0)
return 0;
SkBitmap bitmap;
bitmap.setConfig(SkBitmap::kARGB_8888_Config,
custom_size_.width(), custom_size_.height());
bitmap.allocPixels();
memcpy(bitmap.getAddr32(0, 0), custom_data_.data(), custom_data_.size());
gfx::Point hotspot = hotspot_;
if (device_scale_factor_ != custom_scale_) {
float scale = device_scale_factor_ / custom_scale_;
gfx::Size scaled_size =
gfx::ToFlooredSize(gfx::ScaleSize(custom_size_, scale));
bitmap = skia::ImageOperations::Resize(bitmap,
skia::ImageOperations::RESIZE_BETTER,
scaled_size.width(),
scaled_size.height());
hotspot = gfx::ToFlooredPoint(gfx::ScalePoint(hotspot, scale));
}
XcursorImage* image = ui::SkBitmapToXcursorImage(&bitmap, hotspot);
platform_cursor_ = ui::CreateReffedCustomXCursor(image);
return platform_cursor_;
}
void WebCursor::SetDeviceScaleFactor(float scale_factor) {
if (device_scale_factor_ == scale_factor)
return;
device_scale_factor_ = scale_factor;
if (platform_cursor_)
ui::UnrefCustomXCursor(platform_cursor_);
platform_cursor_ = 0;
// It is not necessary to recreate platform_cursor_ yet, since it will be
// recreated on demand when GetPlatformCursor is called.
}
void WebCursor::InitPlatformData() {
platform_cursor_ = 0;
device_scale_factor_ = 1.f;
}
bool WebCursor::SerializePlatformData(Pickle* pickle) const {
return true;
}
bool WebCursor::DeserializePlatformData(PickleIterator* iter) {
return true;
}
bool WebCursor::IsPlatformDataEqual(const WebCursor& other) const {
return true;
}
void WebCursor::CleanupPlatformData() {
if (platform_cursor_) {
ui::UnrefCustomXCursor(platform_cursor_);
platform_cursor_ = 0;
}
}
void WebCursor::CopyPlatformData(const WebCursor& other) {
if (platform_cursor_)
ui::UnrefCustomXCursor(platform_cursor_);
platform_cursor_ = other.platform_cursor_;
if (platform_cursor_)
ui::RefCustomXCursor(platform_cursor_);
device_scale_factor_ = other.device_scale_factor_;
}
<|endoftext|> |
<commit_before><commit_msg>minor fix<commit_after><|endoftext|> |
<commit_before>#include <QApplication>
#include <QQmlApplicationEngine>
#include <QQuickStyle>
#include <QQuickView>
#include <QQmlContext>
#include <QFontDatabase>
#include "opencv2/core/core.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "headers/qml_models/fileitemmodel.h"
#include "headers/qml_models/generaloptionsmodel.h"
#include "headers/qml_models/fpsoptionsmodel.h"
#include "headers/qml_models/tearoptionsmodel.h"
#include "headers/qml_models/resolutionsmodel.h"
#include "headers/qml_models/imageformatmodel.h"
#include "headers/qml_models/videoformatmodel.h"
#include "headers/qml_models/exportoptionsmodel.h"
#include "headers/qml_interface/videocapturelist_qml.h"
#include "headers/qml_interface/imageconverter_qml.h"
#include "headers/qml_interface/imagecomposer_qml.h"
#include "headers/qml_interface/framerateprocessing_qml.h"
#include "headers/qml_interface/deltaprocessing_qml.h"
#include "headers/qml_interface/renderer_qml.h"
#include "headers/qml_interface/viewer_qml.h"
#include "headers/qml_interface/exporter_qml.h"
#include "headers/cpp_interface/frameratemodel.h"
int main(int argc, char *argv[])
{
// general application stuff
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QApplication app(argc, argv);
QQmlApplicationEngine engine;
QQuickStyle::setStyle("Material");
QFontDatabase::addApplicationFont("qrc:/fonts/materialdesignicons-webfont.ttf");
// c++ models
FramerateModel framerate_model;
std::shared_ptr<FramerateModel> shared_framerate_model(&framerate_model);
//
QList<FPSOptions> fps_option_list;
std::shared_ptr<QList<FPSOptions>> shared_fps_options_list(&fps_option_list);
// qml models
// prepare the FileItemModel
qmlRegisterType<FileItemModel>();
constexpr quint8 default_file_items_count = 3;
FileItemModel file_item_model(default_file_items_count);
engine.rootContext()->setContextProperty("fileItemModel", &file_item_model);
// prepare the Tear Options Model
qmlRegisterType<TearOptionsModel>();
TearOptionsModel tear_options_model;
engine.rootContext()->setContextProperty("tearOptionsModel", &tear_options_model);
// prepare the FPS Options Model
qmlRegisterType<FPSOptionsModel>();
FPSOptionsModel fps_options_model(shared_framerate_model, shared_fps_options_list);
engine.rootContext()->setContextProperty("fpsOptionsModel", &fps_options_model);
// prepare the OptionsModel
qmlRegisterType<GeneralOptionsModel>();
GeneralOptionsModel general_options_model;
engine.rootContext()->setContextProperty("generalOptionsModel", &general_options_model);
std::shared_ptr<GeneralOptionsModel> shared_general_options_model(&general_options_model);
// prepare ResolutionsModel (Exporter)
qmlRegisterType<ResolutionsModel>();
ResolutionsModel resolutions_model;
engine.rootContext()->setContextProperty("resolutionsModel", &resolutions_model);
std::shared_ptr<ResolutionsModel> shared_resolution_model(&resolutions_model);
// prepare ImagFormatModel (Exporter)
qmlRegisterType<ImageFormatModel>();
ImageFormatModel imageformat_model;
engine.rootContext()->setContextProperty("imageFormatModel", &imageformat_model);
std::shared_ptr<ImageFormatModel> shared_imageformat_model(&imageformat_model);
// prepare VideoFormatModel (Exporter)
qmlRegisterType<VideoFormatModel>();
VideoFormatModel videoformat_model;
engine.rootContext()->setContextProperty("videoFormatModel", &videoformat_model);
// prepare ExportOptionsModel (Exporter)
qmlRegisterType<ExportOptionsModel>();
ExportOptionsModel export_options_model;
engine.rootContext()->setContextProperty("exportOptionsModel", &export_options_model);
std::shared_ptr<ExportOptionsModel> shared_export_options_model(&export_options_model);
// allow cv::Mat in signals
qRegisterMetaType<cv::Mat>("cv::Mat");
// allow const QList<FPSOptions> in signals
qRegisterMetaType<QList<FPSOptions>>("const QList<FPSOptions>");
// register the viewer as qml type
qmlRegisterType<ViewerQML>("Trdrop", 1, 0, "ViewerQML");
VideoCaptureListQML videocapturelist_qml(default_file_items_count);
engine.rootContext()->setContextProperty("videocapturelist", &videocapturelist_qml);
FramerateProcessingQML framerate_processing_qml(shared_framerate_model, shared_fps_options_list);
engine.rootContext()->setContextProperty("framerateprocessing", &framerate_processing_qml);
DeltaProcessingQML delta_processing_qml(shared_fps_options_list, shared_general_options_model);
engine.rootContext()->setContextProperty("deltaprocessing", &delta_processing_qml);
ImageConverterQML imageconverter_qml;
engine.rootContext()->setContextProperty("imageconverter", &imageconverter_qml);
ImageComposerQML imagecomposer_qml(shared_resolution_model);
engine.rootContext()->setContextProperty("imagecomposer", &imagecomposer_qml);
RendererQML renderer_qml(shared_fps_options_list);
engine.rootContext()->setContextProperty("renderer", &renderer_qml);
ExporterQML exporter_qml(shared_export_options_model
, shared_imageformat_model);
engine.rootContext()->setContextProperty("exporter", &exporter_qml);
// sigals in c++ (main processing pipeline)
// pass the QList<cv::Mat> to the converter
QObject::connect(&videocapturelist_qml, &VideoCaptureListQML::framesReady, &framerate_processing_qml, &FramerateProcessingQML::processFrames);
// tearprocessing
QObject::connect(&framerate_processing_qml, &FramerateProcessingQML::framesReady, &delta_processing_qml, &DeltaProcessingQML::processFrames);
// frametime processing
QObject::connect(&delta_processing_qml, &DeltaProcessingQML::framesReady, &imageconverter_qml, &ImageConverterQML::processFrames);
// pass the QList<QImage> to the composer to mux them together
QObject::connect(&imageconverter_qml, &ImageConverterQML::imagesReady, &imagecomposer_qml, &ImageComposerQML::processImages);
// pass the QImage to the renderer to render the meta information onto the image
QObject::connect(&imagecomposer_qml, &ImageComposerQML::imageReady, &renderer_qml, &RendererQML::processImage);
// pass the rendered QImage to the exporter
QObject::connect(&renderer_qml, &RendererQML::imageReady, &exporter_qml, &ExporterQML::processImage);
// if VCL finishes processing, finish exporting (may be needed if it's a video)
QObject::connect(&videocapturelist_qml, &VideoCaptureListQML::finishedProcessing, &exporter_qml, &ExporterQML::finishExporting);
// the exporter may trigger a request for new frames from VCL
QObject::connect(&exporter_qml, &ExporterQML::requestNextImages, &videocapturelist_qml, &VideoCaptureListQML::readNextFrames);
// meta data pipeline
// link the fps options with the renderer
QObject::connect(&fps_options_model, &FPSOptionsModel::dataChanged, &renderer_qml, &RendererQML::redraw);
// TODO tear options
// TODO frametime options
// TODO tear values
// TODO fps values
// TODO frametime values
// TODO general option values
// load application
engine.load(QUrl(QStringLiteral("qrc:/qml/main.qml")));
return app.exec();
}
<commit_msg>removed invalid free warning<commit_after>#include <QApplication>
#include <QQmlApplicationEngine>
#include <QQuickStyle>
#include <QQuickView>
#include <QQmlContext>
#include <QFontDatabase>
#include "opencv2/core/core.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "headers/qml_models/fileitemmodel.h"
#include "headers/qml_models/generaloptionsmodel.h"
#include "headers/qml_models/fpsoptionsmodel.h"
#include "headers/qml_models/tearoptionsmodel.h"
#include "headers/qml_models/resolutionsmodel.h"
#include "headers/qml_models/imageformatmodel.h"
#include "headers/qml_models/videoformatmodel.h"
#include "headers/qml_models/exportoptionsmodel.h"
#include "headers/qml_interface/videocapturelist_qml.h"
#include "headers/qml_interface/imageconverter_qml.h"
#include "headers/qml_interface/imagecomposer_qml.h"
#include "headers/qml_interface/framerateprocessing_qml.h"
#include "headers/qml_interface/deltaprocessing_qml.h"
#include "headers/qml_interface/renderer_qml.h"
#include "headers/qml_interface/viewer_qml.h"
#include "headers/qml_interface/exporter_qml.h"
#include "headers/cpp_interface/frameratemodel.h"
int main(int argc, char *argv[])
{
// general application stuff
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QApplication app(argc, argv);
QQmlApplicationEngine engine;
QQuickStyle::setStyle("Material");
QFontDatabase::addApplicationFont("qrc:/fonts/materialdesignicons-webfont.ttf");
// c++ models
std::shared_ptr<FramerateModel> shared_framerate_model(new FramerateModel());
//
std::shared_ptr<QList<FPSOptions>> shared_fps_options_list(new QList<FPSOptions>());
// qml models
// prepare the FileItemModel
qmlRegisterType<FileItemModel>();
constexpr quint8 default_file_items_count = 3;
FileItemModel file_item_model(default_file_items_count);
engine.rootContext()->setContextProperty("fileItemModel", &file_item_model);
// prepare the Tear Options Model
qmlRegisterType<TearOptionsModel>();
TearOptionsModel tear_options_model;
engine.rootContext()->setContextProperty("tearOptionsModel", &tear_options_model);
// prepare the FPS Options Model
qmlRegisterType<FPSOptionsModel>();
FPSOptionsModel fps_options_model(shared_framerate_model, shared_fps_options_list);
engine.rootContext()->setContextProperty("fpsOptionsModel", &fps_options_model);
// prepare the OptionsModel
qmlRegisterType<GeneralOptionsModel>();
GeneralOptionsModel general_options_model;
engine.rootContext()->setContextProperty("generalOptionsModel", &general_options_model);
std::shared_ptr<GeneralOptionsModel> shared_general_options_model(&general_options_model);
// prepare ResolutionsModel (Exporter)
qmlRegisterType<ResolutionsModel>();
ResolutionsModel resolutions_model;
std::shared_ptr<ResolutionsModel> shared_resolution_model(&resolutions_model);
engine.rootContext()->setContextProperty("resolutionsModel", &resolutions_model);
// prepare ImagFormatModel (Exporter)
qmlRegisterType<ImageFormatModel>();
ImageFormatModel imageformat_model;
engine.rootContext()->setContextProperty("imageFormatModel", &imageformat_model);
std::shared_ptr<ImageFormatModel> shared_imageformat_model(&imageformat_model);
// prepare VideoFormatModel (Exporter)
qmlRegisterType<VideoFormatModel>();
VideoFormatModel videoformat_model;
engine.rootContext()->setContextProperty("videoFormatModel", &videoformat_model);
// prepare ExportOptionsModel (Exporter)
qmlRegisterType<ExportOptionsModel>();
ExportOptionsModel export_options_model;
engine.rootContext()->setContextProperty("exportOptionsModel", &export_options_model);
std::shared_ptr<ExportOptionsModel> shared_export_options_model(&export_options_model);
// allow cv::Mat in signals
qRegisterMetaType<cv::Mat>("cv::Mat");
// allow const QList<FPSOptions> in signals
qRegisterMetaType<QList<FPSOptions>>("const QList<FPSOptions>");
// register the viewer as qml type
qmlRegisterType<ViewerQML>("Trdrop", 1, 0, "ViewerQML");
VideoCaptureListQML videocapturelist_qml(default_file_items_count);
engine.rootContext()->setContextProperty("videocapturelist", &videocapturelist_qml);
FramerateProcessingQML framerate_processing_qml(shared_framerate_model, shared_fps_options_list);
engine.rootContext()->setContextProperty("framerateprocessing", &framerate_processing_qml);
DeltaProcessingQML delta_processing_qml(shared_fps_options_list, shared_general_options_model);
engine.rootContext()->setContextProperty("deltaprocessing", &delta_processing_qml);
ImageConverterQML imageconverter_qml;
engine.rootContext()->setContextProperty("imageconverter", &imageconverter_qml);
ImageComposerQML imagecomposer_qml(shared_resolution_model);
engine.rootContext()->setContextProperty("imagecomposer", &imagecomposer_qml);
RendererQML renderer_qml(shared_fps_options_list);
engine.rootContext()->setContextProperty("renderer", &renderer_qml);
ExporterQML exporter_qml(shared_export_options_model
, shared_imageformat_model);
engine.rootContext()->setContextProperty("exporter", &exporter_qml);
// sigals in c++ (main processing pipeline)
// pass the QList<cv::Mat> to the converter
QObject::connect(&videocapturelist_qml, &VideoCaptureListQML::framesReady, &framerate_processing_qml, &FramerateProcessingQML::processFrames);
// tearprocessing
QObject::connect(&framerate_processing_qml, &FramerateProcessingQML::framesReady, &delta_processing_qml, &DeltaProcessingQML::processFrames);
// frametime processing
QObject::connect(&delta_processing_qml, &DeltaProcessingQML::framesReady, &imageconverter_qml, &ImageConverterQML::processFrames);
// pass the QList<QImage> to the composer to mux them together
QObject::connect(&imageconverter_qml, &ImageConverterQML::imagesReady, &imagecomposer_qml, &ImageComposerQML::processImages);
// pass the QImage to the renderer to render the meta information onto the image
QObject::connect(&imagecomposer_qml, &ImageComposerQML::imageReady, &renderer_qml, &RendererQML::processImage);
// pass the rendered QImage to the exporter
QObject::connect(&renderer_qml, &RendererQML::imageReady, &exporter_qml, &ExporterQML::processImage);
// if VCL finishes processing, finish exporting (may be needed if it's a video)
QObject::connect(&videocapturelist_qml, &VideoCaptureListQML::finishedProcessing, &exporter_qml, &ExporterQML::finishExporting);
// the exporter may trigger a request for new frames from VCL
QObject::connect(&exporter_qml, &ExporterQML::requestNextImages, &videocapturelist_qml, &VideoCaptureListQML::readNextFrames);
// meta data pipeline
// link the fps options with the renderer
QObject::connect(&fps_options_model, &FPSOptionsModel::dataChanged, &renderer_qml, &RendererQML::redraw);
// TODO tear options
// TODO frametime options
// TODO tear values
// TODO fps values
// TODO frametime values
// TODO general option values
// load application
engine.load(QUrl(QStringLiteral("qrc:/qml/main.qml")));
return app.exec();
}
<|endoftext|> |
<commit_before><commit_msg>minor fix<commit_after><|endoftext|> |
<commit_before>#include <algorithm>
#include <chrono>
#include "control.h"
#include "bvs/archutils.h"
BVS::Control::Control(ModuleDataMap& modules, BVS& bvs, Info& info)
: modules(modules),
bvs(bvs),
info(info),
logger{"Control"},
runningThreads{0},
masterModules{},
pools{},
flag{SystemFlag::PAUSE},
mutex{},
masterLock{mutex},
monitor{},
controlThread{},
round{0}
{ }
BVS::Control& BVS::Control::masterController(const bool forkMasterController)
{
if (forkMasterController)
{
LOG(3, "master -> FORKED!");
controlThread = std::thread{&Control::masterController, this, false};
return *this;
}
else
{
nameThisThread("masterControl");
// startup sync
monitor.notify_all();
monitor.wait(masterLock, [&](){ return runningThreads.load()==0; });
runningThreads.store(0);
}
std::chrono::time_point<std::chrono::high_resolution_clock> timer =
std::chrono::high_resolution_clock::now();
while (flag!=SystemFlag::QUIT)
{
// round sync
monitor.wait(masterLock, [&](){ return runningThreads.load()==0; });
info.lastRoundDuration =
std::chrono::duration_cast<std::chrono::milliseconds>
(std::chrono::high_resolution_clock::now() - timer);
timer = std::chrono::high_resolution_clock::now();
switch (flag)
{
case SystemFlag::QUIT:
break;
case SystemFlag::PAUSE:
if (!controlThread.joinable()) return *this;
LOG(3, "PAUSE...");
monitor.wait(masterLock, [&](){ return flag!=SystemFlag::PAUSE; });
timer = std::chrono::high_resolution_clock::now();
break;
case SystemFlag::RUN:
case SystemFlag::STEP:
LOG(3, "ROUND: " << round);
info.round = round++;
for (auto& module: modules)
{
if (module.second->status!=Status::OK)
checkModuleStatus(module.second);
module.second->flag = ControlFlag::RUN;
if (module.second->asThread) runningThreads.fetch_add(1);
}
for (auto& pool: pools) pool.second->flag = ControlFlag::RUN;
runningThreads.fetch_add(pools.size());
monitor.notify_all();
for (auto& it: masterModules) moduleController(*(it.get()));
if (flag==SystemFlag::STEP) flag = SystemFlag::PAUSE;
LOG(3, "WAIT FOR THREADS AND POOLS!");
break;
case SystemFlag::STEP_BACK:
break;
}
if (!controlThread.joinable() && flag!=SystemFlag::RUN) return *this;
}
for (auto& pool: pools) pool.second->flag = ControlFlag::QUIT;
masterLock.unlock();
return *this;
}
BVS::Control& BVS::Control::sendCommand(const SystemFlag controlFlag)
{
LOG(3, "FLAG: " << (int)controlFlag);
flag = controlFlag;
if (controlThread.joinable()) monitor.notify_all();
else masterController(false);
if (controlFlag==SystemFlag::QUIT)
{
if (controlThread.joinable())
{
LOG(3, "JOIN MASTER CONTROLLER!");
controlThread.join();
}
}
return *this;
}
BVS::SystemFlag BVS::Control::queryActiveFlag()
{
return flag;
}
BVS::Control& BVS::Control::startModule(std::string id)
{
std::shared_ptr<ModuleData> data = modules[id];
if (!data->poolName.empty())
{
LOG(3, id << " -> POOL(" << data->poolName << ")");
if (pools.find(data->poolName)==pools.end())
{
pools[data->poolName] = std::make_shared<PoolData>
(data->poolName, ControlFlag::WAIT);
pools[data->poolName]->modules.push_back(modules[id]);
pools[data->poolName]->thread = std::thread
{&Control::poolController, this, pools[data->poolName]};
runningThreads.fetch_add(1);
}
else
{
pools[data->poolName]->modules.push_back(modules[id]);
}
}
else if (data->asThread)
{
LOG(3, id << " -> THREAD");
runningThreads.fetch_add(1);
data->thread = std::thread{&Control::threadController, this, data};
}
else
{
LOG(3, id << " -> MASTER");
masterModules.push_back(modules[id]);
}
return *this;
}
BVS::Control& BVS::Control::quitModule(std::string id)
{
if (modules[id]->asThread==true)
{
if (modules[id]->thread.joinable())
{
modules[id]->flag = ControlFlag::QUIT;
monitor.notify_all();
LOG(3, "Waiting for '" << id << "' to join!");
modules[id]->thread.join();
}
}
return *this;
}
BVS::Control& BVS::Control::purgeData(const std::string& id)
{
if (!pools.empty())
{
std::string pool = modules[id]->poolName;
if (!pool.empty())
{
ModuleDataVector& poolModules = pools[pool]->modules;
if (!poolModules.empty())
poolModules.erase(std::remove_if
(poolModules.begin(), poolModules.end(),
[&](std::shared_ptr<ModuleData> data)
{ return data->id==id; }));
}
}
if (!masterModules.empty())
masterModules.erase(std::remove_if
(masterModules.begin(), masterModules.end(),
[&](std::shared_ptr<ModuleData> data)
{ return data->id==id; }));
modules[id]->connectors.clear();
return *this;
}
BVS::Control& BVS::Control::waitUntilInactive(const std::string& id)
{
while (isActive(id)) monitor.wait_for(masterLock,
std::chrono::milliseconds{100}, [&](){ return !isActive(id); });
return *this;
}
bool BVS::Control::isActive(const std::string& id)
{
if (modules[id]->asThread)
{
if (modules[id]->flag==ControlFlag::WAIT) return false;
else return true;
}
if (!modules[id]->poolName.empty())
{
if (pools[modules[id]->poolName]->flag==ControlFlag::WAIT) return false;
else return true;
}
return false;
}
BVS::Control& BVS::Control::moduleController(ModuleData& data)
{
std::chrono::time_point<std::chrono::high_resolution_clock> modTimer =
std::chrono::high_resolution_clock::now();
switch (data.flag)
{
case ControlFlag::QUIT:
break;
case ControlFlag::WAIT:
break;
case ControlFlag::RUN:
data.status = data.module->execute();
data.flag = ControlFlag::WAIT;
break;
}
info.moduleDurations[data.id] =
std::chrono::duration_cast<std::chrono::milliseconds>
(std::chrono::high_resolution_clock::now() - modTimer);
return *this;
}
BVS::Control& BVS::Control::threadController(std::shared_ptr<ModuleData> data)
{
nameThisThread(("[M]"+data->id).c_str());
std::unique_lock<std::mutex> threadLock{mutex};
while (bool(data->flag))
{
runningThreads.fetch_sub(1);
LOG(3, data->id << " -> WAIT!");
monitor.notify_all();
monitor.wait(threadLock, [&](){ return data->flag!=ControlFlag::WAIT; });
moduleController(*(data.get()));
}
return *this;
}
BVS::Control& BVS::Control::poolController(std::shared_ptr<PoolData> data)
{
nameThisThread(("[P]"+data->poolName).c_str());
LOG(3, "POOL(" << data->poolName << ") STARTED!");
std::unique_lock<std::mutex> threadLock{mutex};
while (bool(data->flag) && !data->modules.empty())
{
for (auto& module: data->modules) moduleController(*(module.get()));
data->flag = ControlFlag::WAIT;
runningThreads.fetch_sub(1);
LOG(3, "POOL(" << data->poolName << ") WAIT!");
monitor.notify_all();
monitor.wait(threadLock, [&](){ return data->flag!=ControlFlag::WAIT; });
}
pools.erase(pools.find(data->poolName));
LOG(3, "POOL(" << data->poolName << ") QUITTING!");
return *this;
}
BVS::Control& BVS::Control::checkModuleStatus(std::shared_ptr<ModuleData> data)
{
switch (data->status)
{
case Status::OK:
break;
case Status::NOINPUT:
break;
case Status::FAIL:
break;
case Status::WAIT:
break;
case Status::DONE:
bvs.unloadModule(data->id);
break;
case Status::SHUTDOWN:
break;
}
return *this;
}
<commit_msg>control: small syntax fixes<commit_after>#include <algorithm>
#include <chrono>
#include "control.h"
#include "bvs/archutils.h"
BVS::Control::Control(ModuleDataMap& modules, BVS& bvs, Info& info)
: modules(modules),
bvs(bvs),
info(info),
logger{"Control"},
runningThreads{0},
masterModules{},
pools{},
flag{SystemFlag::PAUSE},
mutex{},
masterLock{mutex},
monitor{},
controlThread{},
round{0}
{ }
BVS::Control& BVS::Control::masterController(const bool forkMasterController)
{
if (forkMasterController)
{
LOG(3, "master -> FORKED!");
controlThread = std::thread{&Control::masterController, this, false};
return *this;
}
else
{
nameThisThread("masterControl");
// startup sync
monitor.notify_all();
monitor.wait(masterLock, [&](){ return runningThreads.load()==0; });
runningThreads.store(0);
}
std::chrono::time_point<std::chrono::high_resolution_clock> timer =
std::chrono::high_resolution_clock::now();
while (flag!=SystemFlag::QUIT)
{
// round sync
monitor.wait(masterLock, [&](){ return runningThreads.load()==0; });
info.lastRoundDuration =
std::chrono::duration_cast<std::chrono::milliseconds>
(std::chrono::high_resolution_clock::now() - timer);
timer = std::chrono::high_resolution_clock::now();
switch (flag)
{
case SystemFlag::QUIT: break;
case SystemFlag::PAUSE:
if (!controlThread.joinable()) return *this;
LOG(3, "PAUSE...");
monitor.wait(masterLock, [&](){ return flag!=SystemFlag::PAUSE; });
timer = std::chrono::high_resolution_clock::now();
break;
case SystemFlag::RUN:
case SystemFlag::STEP:
LOG(3, "ROUND: " << round);
info.round = round++;
for (auto& module: modules)
{
if (module.second->status!=Status::OK)
checkModuleStatus(module.second);
module.second->flag = ControlFlag::RUN;
if (module.second->asThread) runningThreads.fetch_add(1);
}
for (auto& pool: pools) pool.second->flag = ControlFlag::RUN;
runningThreads.fetch_add(pools.size());
monitor.notify_all();
for (auto& it: masterModules) moduleController(*(it.get()));
if (flag==SystemFlag::STEP) flag = SystemFlag::PAUSE;
LOG(3, "WAIT FOR THREADS AND POOLS!");
break;
case SystemFlag::STEP_BACK: break;
}
if (!controlThread.joinable() && flag!=SystemFlag::RUN) return *this;
}
for (auto& pool: pools) pool.second->flag = ControlFlag::QUIT;
masterLock.unlock();
return *this;
}
BVS::Control& BVS::Control::sendCommand(const SystemFlag controlFlag)
{
LOG(3, "FLAG: " << (int)controlFlag);
flag = controlFlag;
if (controlThread.joinable()) monitor.notify_all();
else masterController(false);
if (controlFlag==SystemFlag::QUIT)
{
if (controlThread.joinable())
{
LOG(3, "JOIN MASTER CONTROLLER!");
controlThread.join();
}
}
return *this;
}
BVS::SystemFlag BVS::Control::queryActiveFlag()
{
return flag;
}
BVS::Control& BVS::Control::startModule(std::string id)
{
std::shared_ptr<ModuleData> data = modules[id];
if (!data->poolName.empty())
{
LOG(3, id << " -> POOL(" << data->poolName << ")");
if (pools.find(data->poolName)==pools.end())
{
pools[data->poolName] = std::make_shared<PoolData>
(data->poolName, ControlFlag::WAIT);
pools[data->poolName]->modules.push_back(modules[id]);
pools[data->poolName]->thread = std::thread
{&Control::poolController, this, pools[data->poolName]};
runningThreads.fetch_add(1);
}
else
{
pools[data->poolName]->modules.push_back(modules[id]);
}
}
else if (data->asThread)
{
LOG(3, id << " -> THREAD");
runningThreads.fetch_add(1);
data->thread = std::thread{&Control::threadController, this, data};
}
else
{
LOG(3, id << " -> MASTER");
masterModules.push_back(modules[id]);
}
return *this;
}
BVS::Control& BVS::Control::quitModule(std::string id)
{
if (modules[id]->asThread==true)
{
if (modules[id]->thread.joinable())
{
modules[id]->flag = ControlFlag::QUIT;
monitor.notify_all();
LOG(3, "Waiting for '" << id << "' to join!");
modules[id]->thread.join();
}
}
return *this;
}
BVS::Control& BVS::Control::purgeData(const std::string& id)
{
if (!pools.empty())
{
std::string pool = modules[id]->poolName;
if (!pool.empty())
{
ModuleDataVector& poolModules = pools[pool]->modules;
if (!poolModules.empty())
poolModules.erase(std::remove_if
(poolModules.begin(), poolModules.end(),
[&](std::shared_ptr<ModuleData> data)
{ return data->id==id; }));
}
}
if (!masterModules.empty())
masterModules.erase(std::remove_if
(masterModules.begin(), masterModules.end(),
[&](std::shared_ptr<ModuleData> data)
{ return data->id==id; }));
modules[id]->connectors.clear();
return *this;
}
BVS::Control& BVS::Control::waitUntilInactive(const std::string& id)
{
while (isActive(id)) monitor.wait_for(masterLock,
std::chrono::milliseconds{100}, [&](){ return !isActive(id); });
return *this;
}
bool BVS::Control::isActive(const std::string& id)
{
if (modules[id]->asThread)
{
if (modules[id]->flag==ControlFlag::WAIT) return false;
else return true;
}
if (!modules[id]->poolName.empty())
{
if (pools[modules[id]->poolName]->flag==ControlFlag::WAIT) return false;
else return true;
}
return false;
}
BVS::Control& BVS::Control::moduleController(ModuleData& data)
{
std::chrono::time_point<std::chrono::high_resolution_clock> modTimer =
std::chrono::high_resolution_clock::now();
switch (data.flag)
{
case ControlFlag::QUIT: break;
case ControlFlag::WAIT: break;
case ControlFlag::RUN:
data.status = data.module->execute();
data.flag = ControlFlag::WAIT;
break;
}
info.moduleDurations[data.id] =
std::chrono::duration_cast<std::chrono::milliseconds>
(std::chrono::high_resolution_clock::now() - modTimer);
return *this;
}
BVS::Control& BVS::Control::threadController(std::shared_ptr<ModuleData> data)
{
nameThisThread(("[M]"+data->id).c_str());
std::unique_lock<std::mutex> threadLock{mutex};
while (bool(data->flag))
{
runningThreads.fetch_sub(1);
LOG(3, data->id << " -> WAIT!");
monitor.notify_all();
monitor.wait(threadLock, [&](){ return data->flag!=ControlFlag::WAIT; });
moduleController(*(data.get()));
}
return *this;
}
BVS::Control& BVS::Control::poolController(std::shared_ptr<PoolData> data)
{
nameThisThread(("[P]"+data->poolName).c_str());
LOG(3, "POOL(" << data->poolName << ") STARTED!");
std::unique_lock<std::mutex> threadLock{mutex};
while (bool(data->flag) && !data->modules.empty())
{
for (auto& module: data->modules) moduleController(*(module.get()));
data->flag = ControlFlag::WAIT;
runningThreads.fetch_sub(1);
LOG(3, "POOL(" << data->poolName << ") WAIT!");
monitor.notify_all();
monitor.wait(threadLock, [&](){ return data->flag!=ControlFlag::WAIT; });
}
pools.erase(pools.find(data->poolName));
LOG(3, "POOL(" << data->poolName << ") QUITTING!");
return *this;
}
BVS::Control& BVS::Control::checkModuleStatus(std::shared_ptr<ModuleData> data)
{
switch (data->status)
{
case Status::OK: break;
case Status::NOINPUT: break;
case Status::FAIL: break;
case Status::WAIT: break;
case Status::DONE:
bvs.unloadModule(data->id);
break;
case Status::SHUTDOWN:
break;
}
return *this;
}
<|endoftext|> |
<commit_before>/* Copyright (C) 2016 INRA
*
* 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 "lpformat-consistency.hpp"
#include "lpformat-io.hpp"
#include "mitm.hpp"
#include <fstream>
#include <lpcore>
namespace lp {
problem
make_problem(const std::string& filename)
{
std::ifstream ifs;
ifs.exceptions(std::ifstream::badbit);
ifs.open(filename);
return details::read_problem(ifs);
}
problem
make_problem(std::istream& is)
{
is.exceptions(std::ifstream::badbit);
return details::read_problem(is);
}
std::ostream&
operator<<(std::ostream& os, const problem& p)
{
details::problem_writer pw(p, os);
return os;
}
result
solve(problem& pb)
{
check(pb);
std::map<std::string, parameter> params;
return mitm_solve(pb, params);
}
result
solve(problem& pb, const std::map<std::string, parameter>& params)
{
check(pb);
return mitm_solve(pb, params);
}
result
optimize(problem& pb, const std::map<std::string, parameter>& params)
{
check(pb);
return mitm_optimize(pb, params);
}
result
optimize(problem& pb)
{
check(pb);
std::map<std::string, parameter> params;
return mitm_optimize(pb, params);
}
template <typename functionT, typename variablesT>
int
compute_function(const functionT& fct, const variablesT& vars) noexcept
{
int v{ 0 };
for (auto& f : fct)
v += f.factor * vars[f.variable_index];
return v;
}
bool
is_valid_solution(const problem& pb,
const std::vector<int>& variable_value) noexcept
{
for (auto& cst : pb.equal_constraints) {
if (compute_function(cst.elements, variable_value) != cst.value) {
printf("constraint %s (=) fails\n", cst.label.c_str());
return false;
}
}
for (auto& cst : pb.greater_constraints) {
if (compute_function(cst.elements, variable_value) <= cst.value) {
printf("constraint %s (>) fails\n", cst.label.c_str());
return false;
}
}
for (auto& cst : pb.greater_equal_constraints) {
if (compute_function(cst.elements, variable_value) < cst.value) {
printf("constraint %s (>=) fails\n", cst.label.c_str());
return false;
}
}
for (auto& cst : pb.less_constraints) {
if (compute_function(cst.elements, variable_value) >= cst.value) {
printf("constraint %s (<) fails\n", cst.label.c_str());
return false;
}
}
for (auto& cst : pb.greater_constraints) {
if (compute_function(cst.elements, variable_value) > cst.value) {
printf("constraint %s (<=) fails\n", cst.label.c_str());
return false;
}
}
return true;
}
double
compute_solution(const problem& pb,
const std::vector<int>& variable_value) noexcept
{
double ret = pb.objective.constant;
for (auto& elem : pb.objective.elements)
ret += elem.factor * variable_value[elem.variable_index];
return ret;
}
}
<commit_msg>lib: fix is_valid_solution and empty variable<commit_after>/* Copyright (C) 2016 INRA
*
* 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 "lpformat-consistency.hpp"
#include "lpformat-io.hpp"
#include "mitm.hpp"
#include <fstream>
#include <lpcore>
namespace lp {
problem
make_problem(const std::string& filename)
{
std::ifstream ifs;
ifs.exceptions(std::ifstream::badbit);
ifs.open(filename);
return details::read_problem(ifs);
}
problem
make_problem(std::istream& is)
{
is.exceptions(std::ifstream::badbit);
return details::read_problem(is);
}
std::ostream&
operator<<(std::ostream& os, const problem& p)
{
details::problem_writer pw(p, os);
return os;
}
result
solve(problem& pb)
{
check(pb);
std::map<std::string, parameter> params;
return mitm_solve(pb, params);
}
result
solve(problem& pb, const std::map<std::string, parameter>& params)
{
check(pb);
return mitm_solve(pb, params);
}
result
optimize(problem& pb, const std::map<std::string, parameter>& params)
{
check(pb);
return mitm_optimize(pb, params);
}
result
optimize(problem& pb)
{
check(pb);
std::map<std::string, parameter> params;
return mitm_optimize(pb, params);
}
template <typename functionT, typename variablesT>
int
compute_function(const functionT& fct, const variablesT& vars) noexcept
{
int v{ 0 };
for (auto& f : fct)
v += f.factor * vars[f.variable_index];
return v;
}
bool
is_valid_solution(const problem& pb,
const std::vector<int>& variable_value) noexcept
{
if (variable_value.empty())
return false;
for (auto& cst : pb.equal_constraints) {
if (compute_function(cst.elements, variable_value) != cst.value) {
printf("constraint %s (=) fails\n", cst.label.c_str());
return false;
}
}
for (auto& cst : pb.greater_constraints) {
if (compute_function(cst.elements, variable_value) <= cst.value) {
printf("constraint %s (>) fails\n", cst.label.c_str());
return false;
}
}
for (auto& cst : pb.greater_equal_constraints) {
if (compute_function(cst.elements, variable_value) < cst.value) {
printf("constraint %s (>=) fails\n", cst.label.c_str());
return false;
}
}
for (auto& cst : pb.less_constraints) {
if (compute_function(cst.elements, variable_value) >= cst.value) {
printf("constraint %s (<) fails\n", cst.label.c_str());
return false;
}
}
for (auto& cst : pb.greater_constraints) {
if (compute_function(cst.elements, variable_value) > cst.value) {
printf("constraint %s (<=) fails\n", cst.label.c_str());
return false;
}
}
return true;
}
double
compute_solution(const problem& pb,
const std::vector<int>& variable_value) noexcept
{
double ret = pb.objective.constant;
for (auto& elem : pb.objective.elements)
ret += elem.factor * variable_value[elem.variable_index];
return ret;
}
}
<|endoftext|> |
<commit_before>/*
* Copyright 2021 Google LLC.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "include/private/SkTArray.h"
#include "include/private/SkTOptional.h"
#include "tests/Test.h"
DEF_TEST(SkTOptionalEmpty, r) {
skstd::optional<int> o;
REPORTER_ASSERT(r, !o);
REPORTER_ASSERT(r, !o.has_value());
}
DEF_TEST(SkTOptionalNulloptCtor, r) {
skstd::optional<int> o(skstd::nullopt);
REPORTER_ASSERT(r, !o);
REPORTER_ASSERT(r, !o.has_value());
}
DEF_TEST(SkTOptionalValueOr, r) {
{
skstd::optional<const char*> o;
REPORTER_ASSERT(r, !strcmp(o.value_or("Hello"), "Hello"));
}
{
skstd::optional<const char*> o("Bye");
REPORTER_ASSERT(r, !strcmp(o.value_or("Hello"), "Bye"));
}
{
skstd::optional<std::unique_ptr<int>> o;
std::unique_ptr<int> a = std::move(o).value_or(std::make_unique<int>(5));
REPORTER_ASSERT(r, *a == 5);
}
{
skstd::optional<std::unique_ptr<int>> o(std::make_unique<int>(3));
std::unique_ptr<int> a = std::move(o).value_or(std::make_unique<int>(5));
REPORTER_ASSERT(r, *a == 3);
}
}
DEF_TEST(SkTOptionalValue, r) {
skstd::optional<const char*> o("test");
REPORTER_ASSERT(r, o);
REPORTER_ASSERT(r, o.has_value());
REPORTER_ASSERT(r, !strcmp(*o, "test"));
REPORTER_ASSERT(r, !strcmp(o.value(), "test"));
o.reset();
REPORTER_ASSERT(r, !o);
REPORTER_ASSERT(r, !o.has_value());
}
DEF_TEST(SkTOptionalNulloptAssignment, r) {
skstd::optional<const char*> o("test");
REPORTER_ASSERT(r, o);
REPORTER_ASSERT(r, o.has_value());
o = skstd::nullopt;
REPORTER_ASSERT(r, !o);
REPORTER_ASSERT(r, !o.has_value());
}
DEF_TEST(SkTOptionalNulloptReturn, r) {
auto fn = []() -> skstd::optional<float> { return skstd::nullopt; };
skstd::optional<float> o = fn();
REPORTER_ASSERT(r, !o);
REPORTER_ASSERT(r, !o.has_value());
}
DEF_TEST(SkTOptionalComparisons, r) {
int v[] = { 1, 2, 3, 4, 5 };
skstd::optional<int> o[] = {1, 2, skstd::nullopt, 4, 5};
skstd::optional<int> five = 5;
skstd::optional<int> six = 6;
for (int index = 0; index < (int)SK_ARRAY_COUNT(v); ++index) {
REPORTER_ASSERT(r, v[index] < six);
REPORTER_ASSERT(r, o[index] < six);
REPORTER_ASSERT(r, six > v[index]);
REPORTER_ASSERT(r, six > o[index]);
REPORTER_ASSERT(r, v[index] < 6);
REPORTER_ASSERT(r, o[index] < 6);
REPORTER_ASSERT(r, 6 > v[index]);
REPORTER_ASSERT(r, 6 > o[index]);
REPORTER_ASSERT(r, !(six < v[index]));
REPORTER_ASSERT(r, !(six < o[index]));
REPORTER_ASSERT(r, !(v[index] > six));
REPORTER_ASSERT(r, !(o[index] > six));
REPORTER_ASSERT(r, !(6 < v[index]));
REPORTER_ASSERT(r, !(6 < o[index]));
REPORTER_ASSERT(r, !(v[index] > 6));
REPORTER_ASSERT(r, !(o[index] > 6));
REPORTER_ASSERT(r, v[index] <= five);
REPORTER_ASSERT(r, o[index] <= five);
REPORTER_ASSERT(r, five >= v[index]);
REPORTER_ASSERT(r, five >= o[index]);
REPORTER_ASSERT(r, v[index] <= 5);
REPORTER_ASSERT(r, o[index] <= 5);
REPORTER_ASSERT(r, 5 >= v[index]);
REPORTER_ASSERT(r, 5 >= o[index]);
REPORTER_ASSERT(r, skstd::nullopt <= o[index]);
REPORTER_ASSERT(r, !(skstd::nullopt > o[index]));
REPORTER_ASSERT(r, o[index] >= skstd::nullopt);
REPORTER_ASSERT(r, !(o[index] < skstd::nullopt));
if (o[index].has_value()) {
REPORTER_ASSERT(r, o[index] != skstd::nullopt);
REPORTER_ASSERT(r, skstd::nullopt != o[index]);
REPORTER_ASSERT(r, o[index] == o[index]);
REPORTER_ASSERT(r, o[index] != six);
REPORTER_ASSERT(r, o[index] == v[index]);
REPORTER_ASSERT(r, v[index] == o[index]);
REPORTER_ASSERT(r, o[index] > 0);
REPORTER_ASSERT(r, o[index] >= 1);
REPORTER_ASSERT(r, o[index] <= 5);
REPORTER_ASSERT(r, o[index] < 6);
REPORTER_ASSERT(r, 0 < o[index]);
REPORTER_ASSERT(r, 1 <= o[index]);
REPORTER_ASSERT(r, 5 >= o[index]);
REPORTER_ASSERT(r, 6 > o[index]);
} else {
REPORTER_ASSERT(r, o[index] == skstd::nullopt);
REPORTER_ASSERT(r, skstd::nullopt == o[index]);
REPORTER_ASSERT(r, o[index] == o[index]);
REPORTER_ASSERT(r, o[index] != five);
REPORTER_ASSERT(r, o[index] != v[index]);
REPORTER_ASSERT(r, v[index] != o[index]);
REPORTER_ASSERT(r, o[index] < 0);
REPORTER_ASSERT(r, o[index] <= 0);
REPORTER_ASSERT(r, 0 > o[index]);
REPORTER_ASSERT(r, 0 >= o[index]);
REPORTER_ASSERT(r, !(o[index] > 0));
REPORTER_ASSERT(r, !(o[index] >= 0));
REPORTER_ASSERT(r, !(0 < o[index]));
REPORTER_ASSERT(r, !(0 <= o[index]));
}
}
}
class SkTOptionalTestPayload {
public:
enum State {
kConstructed,
kCopyConstructed,
kCopyAssigned,
kMoveConstructed,
kMoveAssigned,
kMovedFrom
};
SkTOptionalTestPayload(int payload)
: fState(kConstructed)
, fPayload(payload) {}
SkTOptionalTestPayload(const SkTOptionalTestPayload& other)
: fState(kCopyConstructed)
, fPayload(other.fPayload) {}
SkTOptionalTestPayload(SkTOptionalTestPayload&& other)
: fState(kMoveConstructed)
, fPayload(other.fPayload) {
other.fState = kMovedFrom;
}
SkTOptionalTestPayload& operator=(const SkTOptionalTestPayload& other) {
fState = kCopyAssigned;
fPayload = other.fPayload;
return *this;
}
SkTOptionalTestPayload& operator=(SkTOptionalTestPayload&& other) {
fState = kMoveAssigned;
fPayload = other.fPayload;
other.fState = kMovedFrom;
return *this;
}
State fState;
int fPayload;
};
DEF_TEST(SkTOptionalConstruction, r) {
skstd::optional<SkTOptionalTestPayload> o(1);
REPORTER_ASSERT(r, o);
REPORTER_ASSERT(r, o->fState == SkTOptionalTestPayload::kConstructed);
REPORTER_ASSERT(r, o->fPayload == 1);
skstd::optional<SkTOptionalTestPayload> copy(o);
REPORTER_ASSERT(r, copy);
REPORTER_ASSERT(r, copy->fState == SkTOptionalTestPayload::kCopyConstructed);
REPORTER_ASSERT(r, copy->fPayload == 1);
REPORTER_ASSERT(r, o->fState == SkTOptionalTestPayload::kConstructed);
skstd::optional<SkTOptionalTestPayload> move(std::move(o));
REPORTER_ASSERT(r, move);
REPORTER_ASSERT(r, move->fState == SkTOptionalTestPayload::kMoveConstructed);
REPORTER_ASSERT(r, move->fPayload == 1);
// NOLINTNEXTLINE(bugprone-use-after-move)
REPORTER_ASSERT(r, o->fState == SkTOptionalTestPayload::kMovedFrom);
}
DEF_TEST(SkTOptionalMoveAssignment, r) {
skstd::optional<SkTOptionalTestPayload> o;
REPORTER_ASSERT(r, !o);
// assign to an empty optional from an empty optional
o = skstd::optional<SkTOptionalTestPayload>();
REPORTER_ASSERT(r, !o);
// assign to an empty optional from a full optional
skstd::optional<SkTOptionalTestPayload> full(1);
o = std::move(full);
REPORTER_ASSERT(r, o);
REPORTER_ASSERT(r, o->fState == SkTOptionalTestPayload::kMoveConstructed);
REPORTER_ASSERT(r, o->fPayload == 1);
// NOLINTNEXTLINE(bugprone-use-after-move)
REPORTER_ASSERT(r, full->fState == SkTOptionalTestPayload::kMovedFrom);
// assign to a full optional from a full optional
full = skstd::optional<SkTOptionalTestPayload>(2);
o = std::move(full);
REPORTER_ASSERT(r, o);
REPORTER_ASSERT(r, o->fState == SkTOptionalTestPayload::kMoveAssigned);
REPORTER_ASSERT(r, o->fPayload == 2);
// NOLINTNEXTLINE(bugprone-use-after-move)
REPORTER_ASSERT(r, full->fState == SkTOptionalTestPayload::kMovedFrom);
// assign to a full optional from an empty optional
o = skstd::optional<SkTOptionalTestPayload>();
REPORTER_ASSERT(r, !o);
}
DEF_TEST(SkTOptionalCopyAssignment, r) {
skstd::optional<SkTOptionalTestPayload> o;
REPORTER_ASSERT(r, !o);
skstd::optional<SkTOptionalTestPayload> empty;
skstd::optional<SkTOptionalTestPayload> full(1);
// assign to an empty optional from an empty optional
o = empty;
REPORTER_ASSERT(r, !o);
// assign to an empty optional from a full optional
o = full;
REPORTER_ASSERT(r, o);
REPORTER_ASSERT(r, o->fState == SkTOptionalTestPayload::kCopyConstructed);
REPORTER_ASSERT(r, o->fPayload == 1);
// assign to a full optional from a full optional
o = full;
REPORTER_ASSERT(r, o);
REPORTER_ASSERT(r, o->fState == SkTOptionalTestPayload::kCopyAssigned);
REPORTER_ASSERT(r, o->fPayload == 1);
// assign to a full optional from an empty optional
o = empty;
REPORTER_ASSERT(r, !o);
}
DEF_TEST(SkTOptionalEmplace, r) {
skstd::optional<std::vector<int>> o;
REPORTER_ASSERT(r, !o);
// Emplace with the no-argument constructor
o.emplace();
REPORTER_ASSERT(r, o.has_value());
REPORTER_ASSERT(r, o->empty());
// Emplace with the initializer-list constructor
o.emplace({1, 2, 3});
REPORTER_ASSERT(r, o.has_value());
REPORTER_ASSERT(r, (*o == std::vector<int>{1, 2, 3}));
// Emplace with a normal constructor
std::vector<int> otherVec = {4, 5, 6};
o.emplace(otherVec.begin(), otherVec.end());
REPORTER_ASSERT(r, o.has_value());
REPORTER_ASSERT(r, (*o == std::vector<int>{4, 5, 6}));
}
DEF_TEST(SkTOptionalNoDefaultConstructor, r) {
class NoDefaultConstructor {
public:
NoDefaultConstructor(int value)
: fValue(value) {}
int fValue;
};
skstd::optional<NoDefaultConstructor> o1;
REPORTER_ASSERT(r, !o1);
skstd::optional<NoDefaultConstructor> o2(5);
REPORTER_ASSERT(r, o2);
REPORTER_ASSERT(r, o2->fValue == 5);
o1 = std::move(o2);
REPORTER_ASSERT(r, o1);
REPORTER_ASSERT(r, o1->fValue == 5);
}
DEF_TEST(SkTOptionalSelfAssignment, r) {
skstd::optional<SkString> empty;
skstd::optional<SkString>& emptyRef = empty;
empty = emptyRef;
REPORTER_ASSERT(r, !empty);
empty = std::move(emptyRef);
REPORTER_ASSERT(r, !empty);
skstd::optional<SkString> full("full");
skstd::optional<SkString>& fullRef = full;
full = fullRef;
REPORTER_ASSERT(r, full);
REPORTER_ASSERT(r, *full == SkString("full"));
full = std::move(fullRef);
REPORTER_ASSERT(r, full);
REPORTER_ASSERT(r, *full == SkString("full"));
}
<commit_msg>Test skstd::optional calls emplaced T's destructor<commit_after>/*
* Copyright 2021 Google LLC.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "include/private/SkTArray.h"
#include "include/private/SkTOptional.h"
#include "tests/Test.h"
DEF_TEST(SkTOptionalEmpty, r) {
skstd::optional<int> o;
REPORTER_ASSERT(r, !o);
REPORTER_ASSERT(r, !o.has_value());
}
DEF_TEST(SkTOptionalNulloptCtor, r) {
skstd::optional<int> o(skstd::nullopt);
REPORTER_ASSERT(r, !o);
REPORTER_ASSERT(r, !o.has_value());
}
DEF_TEST(SkTOptionalValueOr, r) {
{
skstd::optional<const char*> o;
REPORTER_ASSERT(r, !strcmp(o.value_or("Hello"), "Hello"));
}
{
skstd::optional<const char*> o("Bye");
REPORTER_ASSERT(r, !strcmp(o.value_or("Hello"), "Bye"));
}
{
skstd::optional<std::unique_ptr<int>> o;
std::unique_ptr<int> a = std::move(o).value_or(std::make_unique<int>(5));
REPORTER_ASSERT(r, *a == 5);
}
{
skstd::optional<std::unique_ptr<int>> o(std::make_unique<int>(3));
std::unique_ptr<int> a = std::move(o).value_or(std::make_unique<int>(5));
REPORTER_ASSERT(r, *a == 3);
}
}
DEF_TEST(SkTOptionalValue, r) {
skstd::optional<const char*> o("test");
REPORTER_ASSERT(r, o);
REPORTER_ASSERT(r, o.has_value());
REPORTER_ASSERT(r, !strcmp(*o, "test"));
REPORTER_ASSERT(r, !strcmp(o.value(), "test"));
o.reset();
REPORTER_ASSERT(r, !o);
REPORTER_ASSERT(r, !o.has_value());
}
DEF_TEST(SkTOptionalNulloptAssignment, r) {
skstd::optional<const char*> o("test");
REPORTER_ASSERT(r, o);
REPORTER_ASSERT(r, o.has_value());
o = skstd::nullopt;
REPORTER_ASSERT(r, !o);
REPORTER_ASSERT(r, !o.has_value());
}
DEF_TEST(SkTOptionalNulloptReturn, r) {
auto fn = []() -> skstd::optional<float> { return skstd::nullopt; };
skstd::optional<float> o = fn();
REPORTER_ASSERT(r, !o);
REPORTER_ASSERT(r, !o.has_value());
}
DEF_TEST(SkTOptionalComparisons, r) {
int v[] = { 1, 2, 3, 4, 5 };
skstd::optional<int> o[] = {1, 2, skstd::nullopt, 4, 5};
skstd::optional<int> five = 5;
skstd::optional<int> six = 6;
for (int index = 0; index < (int)SK_ARRAY_COUNT(v); ++index) {
REPORTER_ASSERT(r, v[index] < six);
REPORTER_ASSERT(r, o[index] < six);
REPORTER_ASSERT(r, six > v[index]);
REPORTER_ASSERT(r, six > o[index]);
REPORTER_ASSERT(r, v[index] < 6);
REPORTER_ASSERT(r, o[index] < 6);
REPORTER_ASSERT(r, 6 > v[index]);
REPORTER_ASSERT(r, 6 > o[index]);
REPORTER_ASSERT(r, !(six < v[index]));
REPORTER_ASSERT(r, !(six < o[index]));
REPORTER_ASSERT(r, !(v[index] > six));
REPORTER_ASSERT(r, !(o[index] > six));
REPORTER_ASSERT(r, !(6 < v[index]));
REPORTER_ASSERT(r, !(6 < o[index]));
REPORTER_ASSERT(r, !(v[index] > 6));
REPORTER_ASSERT(r, !(o[index] > 6));
REPORTER_ASSERT(r, v[index] <= five);
REPORTER_ASSERT(r, o[index] <= five);
REPORTER_ASSERT(r, five >= v[index]);
REPORTER_ASSERT(r, five >= o[index]);
REPORTER_ASSERT(r, v[index] <= 5);
REPORTER_ASSERT(r, o[index] <= 5);
REPORTER_ASSERT(r, 5 >= v[index]);
REPORTER_ASSERT(r, 5 >= o[index]);
REPORTER_ASSERT(r, skstd::nullopt <= o[index]);
REPORTER_ASSERT(r, !(skstd::nullopt > o[index]));
REPORTER_ASSERT(r, o[index] >= skstd::nullopt);
REPORTER_ASSERT(r, !(o[index] < skstd::nullopt));
if (o[index].has_value()) {
REPORTER_ASSERT(r, o[index] != skstd::nullopt);
REPORTER_ASSERT(r, skstd::nullopt != o[index]);
REPORTER_ASSERT(r, o[index] == o[index]);
REPORTER_ASSERT(r, o[index] != six);
REPORTER_ASSERT(r, o[index] == v[index]);
REPORTER_ASSERT(r, v[index] == o[index]);
REPORTER_ASSERT(r, o[index] > 0);
REPORTER_ASSERT(r, o[index] >= 1);
REPORTER_ASSERT(r, o[index] <= 5);
REPORTER_ASSERT(r, o[index] < 6);
REPORTER_ASSERT(r, 0 < o[index]);
REPORTER_ASSERT(r, 1 <= o[index]);
REPORTER_ASSERT(r, 5 >= o[index]);
REPORTER_ASSERT(r, 6 > o[index]);
} else {
REPORTER_ASSERT(r, o[index] == skstd::nullopt);
REPORTER_ASSERT(r, skstd::nullopt == o[index]);
REPORTER_ASSERT(r, o[index] == o[index]);
REPORTER_ASSERT(r, o[index] != five);
REPORTER_ASSERT(r, o[index] != v[index]);
REPORTER_ASSERT(r, v[index] != o[index]);
REPORTER_ASSERT(r, o[index] < 0);
REPORTER_ASSERT(r, o[index] <= 0);
REPORTER_ASSERT(r, 0 > o[index]);
REPORTER_ASSERT(r, 0 >= o[index]);
REPORTER_ASSERT(r, !(o[index] > 0));
REPORTER_ASSERT(r, !(o[index] >= 0));
REPORTER_ASSERT(r, !(0 < o[index]));
REPORTER_ASSERT(r, !(0 <= o[index]));
}
}
}
class SkTOptionalTestPayload {
public:
enum State {
kConstructed,
kCopyConstructed,
kCopyAssigned,
kMoveConstructed,
kMoveAssigned,
kMovedFrom
};
SkTOptionalTestPayload(int payload)
: fState(kConstructed)
, fPayload(payload) {}
SkTOptionalTestPayload(const SkTOptionalTestPayload& other)
: fState(kCopyConstructed)
, fPayload(other.fPayload) {}
SkTOptionalTestPayload(SkTOptionalTestPayload&& other)
: fState(kMoveConstructed)
, fPayload(other.fPayload) {
other.fState = kMovedFrom;
}
SkTOptionalTestPayload& operator=(const SkTOptionalTestPayload& other) {
fState = kCopyAssigned;
fPayload = other.fPayload;
return *this;
}
SkTOptionalTestPayload& operator=(SkTOptionalTestPayload&& other) {
fState = kMoveAssigned;
fPayload = other.fPayload;
other.fState = kMovedFrom;
return *this;
}
State fState;
int fPayload;
};
DEF_TEST(SkTOptionalConstruction, r) {
skstd::optional<SkTOptionalTestPayload> o(1);
REPORTER_ASSERT(r, o);
REPORTER_ASSERT(r, o->fState == SkTOptionalTestPayload::kConstructed);
REPORTER_ASSERT(r, o->fPayload == 1);
skstd::optional<SkTOptionalTestPayload> copy(o);
REPORTER_ASSERT(r, copy);
REPORTER_ASSERT(r, copy->fState == SkTOptionalTestPayload::kCopyConstructed);
REPORTER_ASSERT(r, copy->fPayload == 1);
REPORTER_ASSERT(r, o->fState == SkTOptionalTestPayload::kConstructed);
skstd::optional<SkTOptionalTestPayload> move(std::move(o));
REPORTER_ASSERT(r, move);
REPORTER_ASSERT(r, move->fState == SkTOptionalTestPayload::kMoveConstructed);
REPORTER_ASSERT(r, move->fPayload == 1);
// NOLINTNEXTLINE(bugprone-use-after-move)
REPORTER_ASSERT(r, o->fState == SkTOptionalTestPayload::kMovedFrom);
}
DEF_TEST(SkTOptionalMoveAssignment, r) {
skstd::optional<SkTOptionalTestPayload> o;
REPORTER_ASSERT(r, !o);
// assign to an empty optional from an empty optional
o = skstd::optional<SkTOptionalTestPayload>();
REPORTER_ASSERT(r, !o);
// assign to an empty optional from a full optional
skstd::optional<SkTOptionalTestPayload> full(1);
o = std::move(full);
REPORTER_ASSERT(r, o);
REPORTER_ASSERT(r, o->fState == SkTOptionalTestPayload::kMoveConstructed);
REPORTER_ASSERT(r, o->fPayload == 1);
// NOLINTNEXTLINE(bugprone-use-after-move)
REPORTER_ASSERT(r, full->fState == SkTOptionalTestPayload::kMovedFrom);
// assign to a full optional from a full optional
full = skstd::optional<SkTOptionalTestPayload>(2);
o = std::move(full);
REPORTER_ASSERT(r, o);
REPORTER_ASSERT(r, o->fState == SkTOptionalTestPayload::kMoveAssigned);
REPORTER_ASSERT(r, o->fPayload == 2);
// NOLINTNEXTLINE(bugprone-use-after-move)
REPORTER_ASSERT(r, full->fState == SkTOptionalTestPayload::kMovedFrom);
// assign to a full optional from an empty optional
o = skstd::optional<SkTOptionalTestPayload>();
REPORTER_ASSERT(r, !o);
}
DEF_TEST(SkTOptionalCopyAssignment, r) {
skstd::optional<SkTOptionalTestPayload> o;
REPORTER_ASSERT(r, !o);
skstd::optional<SkTOptionalTestPayload> empty;
skstd::optional<SkTOptionalTestPayload> full(1);
// assign to an empty optional from an empty optional
o = empty;
REPORTER_ASSERT(r, !o);
// assign to an empty optional from a full optional
o = full;
REPORTER_ASSERT(r, o);
REPORTER_ASSERT(r, o->fState == SkTOptionalTestPayload::kCopyConstructed);
REPORTER_ASSERT(r, o->fPayload == 1);
// assign to a full optional from a full optional
o = full;
REPORTER_ASSERT(r, o);
REPORTER_ASSERT(r, o->fState == SkTOptionalTestPayload::kCopyAssigned);
REPORTER_ASSERT(r, o->fPayload == 1);
// assign to a full optional from an empty optional
o = empty;
REPORTER_ASSERT(r, !o);
}
DEF_TEST(SkTOptionalEmplace, r) {
skstd::optional<std::vector<int>> o;
REPORTER_ASSERT(r, !o);
// Emplace with the no-argument constructor
o.emplace();
REPORTER_ASSERT(r, o.has_value());
REPORTER_ASSERT(r, o->empty());
// Emplace with the initializer-list constructor
o.emplace({1, 2, 3});
REPORTER_ASSERT(r, o.has_value());
REPORTER_ASSERT(r, (*o == std::vector<int>{1, 2, 3}));
// Emplace with a normal constructor
std::vector<int> otherVec = {4, 5, 6};
o.emplace(otherVec.begin(), otherVec.end());
REPORTER_ASSERT(r, o.has_value());
REPORTER_ASSERT(r, (*o == std::vector<int>{4, 5, 6}));
}
DEF_TEST(SkTOptionalNoDefaultConstructor, r) {
class NoDefaultConstructor {
public:
NoDefaultConstructor(int value)
: fValue(value) {}
int fValue;
};
skstd::optional<NoDefaultConstructor> o1;
REPORTER_ASSERT(r, !o1);
skstd::optional<NoDefaultConstructor> o2(5);
REPORTER_ASSERT(r, o2);
REPORTER_ASSERT(r, o2->fValue == 5);
o1 = std::move(o2);
REPORTER_ASSERT(r, o1);
REPORTER_ASSERT(r, o1->fValue == 5);
}
DEF_TEST(SkTOptionalDestroyed, r) {
bool destroyed = false;
struct NotifyWhenDestroyed {
NotifyWhenDestroyed(bool* e) : fE(e) {}
~NotifyWhenDestroyed() { *fE = true; }
bool* fE;
};
{
skstd::optional<NotifyWhenDestroyed> notify(&destroyed);
}
REPORTER_ASSERT(r, destroyed);
}
DEF_TEST(SkTOptionalSelfAssignment, r) {
skstd::optional<SkString> empty;
skstd::optional<SkString>& emptyRef = empty;
empty = emptyRef;
REPORTER_ASSERT(r, !empty);
empty = std::move(emptyRef);
REPORTER_ASSERT(r, !empty);
skstd::optional<SkString> full("full");
skstd::optional<SkString>& fullRef = full;
full = fullRef;
REPORTER_ASSERT(r, full);
REPORTER_ASSERT(r, *full == SkString("full"));
full = std::move(fullRef);
REPORTER_ASSERT(r, full);
REPORTER_ASSERT(r, *full == SkString("full"));
}
<|endoftext|> |
<commit_before>#include <iomanip>
#include <Castro.H>
#include <Castro_F.H>
#include <Geometry.H>
void
Castro::sum_integrated_quantities ()
{
int finest_level = parent->finestLevel();
Real time = state[State_Type].curTime();
Real mass = 0.0;
Real momentum[3] = {0.0, 0.0, 0.0};
Real rho_E = 0.0;
Real rho_e = 0.0;
Real rho_phi = 0.0;
Real gravitational_energy = 0.0;
Real kinetic_energy = 0.0;
Real internal_energy = 0.0;
Real total_energy = 0.0;
Real angular_momentum[3] = {0.0, 0.0, 0.0};
Real moment_of_inertia[3] = {0.0, 0.0, 0.0};
Real m_r_squared[3] = {0.0, 0.0, 0.0};
Real omega[3] = {0.0, 0.0, 2.0*3.1415926*rotational_frequency};
Real delta_L[3] = {0.0, 0.0, 0.0};
Real mass_left = 0.0;
Real mass_right = 0.0;
Real com[3] = {0.0, 0.0, 0.0};
Real com_l[3] = {0.0, 0.0, 0.0};
Real com_r[3] = {0.0, 0.0, 0.0};
Real delta_com[3] = {0.0, 0.0, 0.0};
Real com_vel[3] = {0.0, 0.0, 0.0};
Real com_vel_l[3] = {0.0, 0.0, 0.0};
Real com_vel_r[3] = {0.0, 0.0, 0.0};
std::string name1;
std::string name2;
int datawidth = 14;
int dataprecision = 6;
for (int lev = 0; lev <= finest_level; lev++)
{
// Get the current level from Castro
Castro& ca_lev = getLevel(lev);
// Calculate center of mass quantities.
mass_left += ca_lev.volWgtSumOneSide("density", time, 0, 0);
mass_right += ca_lev.volWgtSumOneSide("density", time, 1, 0);
for ( int i = 0; i <= 2; i++ ) {
switch ( i ) {
case 0 :
name1 = "xmom"; break;
case 1 :
name1 = "ymom"; break;
case 2 :
name1 = "zmom"; break;
}
delta_com[i] = ca_lev.locWgtSum("density", time, i);
com[i] += delta_com[i];
com_l[i] += ca_lev.locWgtSumOneSide("density", time, i, 0, 0);
com_r[i] += ca_lev.locWgtSumOneSide("density", time, i, 1, 0);
com_vel_l[i] += ca_lev.volWgtSumOneSide(name1, time, 0, 0);
com_vel_r[i] += ca_lev.volWgtSumOneSide(name1, time, 1, 0);
}
// Calculate total mass, momentum and energy of system.
mass += ca_lev.volWgtSum("density", time);
momentum[0] += ca_lev.volWgtSum("xmom", time);
momentum[1] += ca_lev.volWgtSum("ymom", time);
momentum[2] += ca_lev.volWgtSum("zmom", time);
rho_E += ca_lev.volWgtSum("rho_E", time);
rho_e += ca_lev.volWgtSum("rho_e", time);
if ( do_grav )
rho_phi += ca_lev.volProductSum("density", "phi", time);
// Calculate total angular momentum of system using L = r x p
for ( int i = 0; i <= 2; i++ )
m_r_squared[i] = ca_lev.locSquaredSum("density", time, i);
for ( int i = 0; i <= 2; i++ ) {
int index1 = (i+1) % 3;
int index2 = (i+2) % 3;
switch (i) {
case 0 :
name1 = "ymom"; name2 = "zmom"; break;
case 1 :
name1 = "zmom"; name2 = "xmom"; break;
case 2 :
name1 = "xmom"; name2 = "ymom"; break;
}
moment_of_inertia[i] = m_r_squared[index1] + m_r_squared[index2];
delta_L[i] = ca_lev.locWgtSum(name2, time, index1) - ca_lev.locWgtSum(name1, time, index2);
angular_momentum[i] += delta_L[i];
}
// Add rotation source terms
if ( do_rotation ) {
for ( int i = 0; i <= 2; i++ ) {
// Rotational energy == omega dot L + 0.5 * I * omega**2
kinetic_energy += omega[i] * delta_L[i] + (1.0/2.0) * moment_of_inertia[i] * omega[i] * omega[i];
// Angular momentum == (I * omega); missing a cross term which is irrelevant
// since omega has only one non-zero entry.
angular_momentum[i] += moment_of_inertia[i] * omega[i];
// Momentum == omega x (rho * r)
int index1 = (i+1) % 3;
int index2 = (i+2) % 3;
momentum[i] += omega[index1]*delta_com[index2] - omega[index2]*delta_com[index1];
}
}
}
// Complete calculations for COM quantities
Real center = 0.0;
for ( int i = 0; i <= 2; i++ ) {
center = 0.5*(Geometry::ProbLo(i) + Geometry::ProbHi(i));
com[i] = com[0] / mass;
com_l[i] = com_l[0] / mass_left + center;
com_r[i] = com_r[0] / mass_right + center;
com_vel_l[i] = com_vel_l[0] / mass_left;
com_vel_r[i] = com_vel_r[0] / mass_right;
com_vel[i] = momentum[i] / mass;
}
const Real* ml = &mass_left;
const Real* mr = &mass_right;
const Real* cxl = &com_l[0];
const Real* cxr = &com_r[0];
const Real* cyl = &com_l[1];
const Real* cyr = &com_r[1];
const Real* czl = &com_l[2];
const Real* czr = &com_r[2];
BL_FORT_PROC_CALL(COM_SAVE,com_save)
(ml, mr, cxl, cxr, cyl, cyr, czl, czr);
// Complete calculations for energy
gravitational_energy = (-1.0/2.0) * rho_phi; // avoids double counting; CASTRO uses positive phi
internal_energy = rho_e;
kinetic_energy += rho_E - rho_e;
total_energy = gravitational_energy + internal_energy + kinetic_energy;
// Write data out to the log.
std::ostream& data_log1 = parent->DataLog(0);
if ( ParallelDescriptor::IOProcessor() && data_log1.good() )
{
// Write header row
if (time == 0.0) {
data_log1 << std::setw(datawidth) << "# TIME ";
data_log1 << std::setw(datawidth) << " MASS ";
data_log1 << std::setw(datawidth) << " XMOM ";
data_log1 << std::setw(datawidth) << " YMOM ";
data_log1 << std::setw(datawidth) << " ZMOM ";
data_log1 << std::setw(datawidth) << " KIN. ENERGY ";
data_log1 << std::setw(datawidth) << " GRAV. ENERGY";
data_log1 << std::setw(datawidth) << " INT. ENERGY ";
data_log1 << std::setw(datawidth) << " TOTAL ENERGY";
data_log1 << std::setw(datawidth) << " ANG. MOM. X ";
data_log1 << std::setw(datawidth) << " ANG. MOM. Y ";
data_log1 << std::setw(datawidth) << " ANG. MOM. Z ";
data_log1 << std::setw(datawidth) << " X COM ";
data_log1 << std::setw(datawidth) << " Y COM ";
data_log1 << std::setw(datawidth) << " Z COM ";
data_log1 << std::setw(datawidth) << " LEFT MASS ";
data_log1 << std::setw(datawidth) << " RIGHT MASS ";
data_log1 << std::setw(datawidth) << " LEFT X COM ";
data_log1 << std::setw(datawidth) << " RIGHT X COM ";
data_log1 << std::setw(datawidth) << " LEFT Y COM ";
data_log1 << std::setw(datawidth) << " RIGHT Y COM ";
data_log1 << std::setw(datawidth) << " LEFT Z COM ";
data_log1 << std::setw(datawidth) << " RIGHT Z COM ";
data_log1 << std::setw(datawidth) << " X VEL ";
data_log1 << std::setw(datawidth) << " Y VEL ";
data_log1 << std::setw(datawidth) << " Z VEL ";
data_log1 << std::setw(datawidth) << " LEFT X VEL ";
data_log1 << std::setw(datawidth) << " RIGHT X VEL ";
data_log1 << std::setw(datawidth) << " LEFT Y VEL ";
data_log1 << std::setw(datawidth) << " RIGHT Y VEL ";
data_log1 << std::setw(datawidth) << " LEFT Z VEL ";
data_log1 << std::setw(datawidth) << " RIGHT Z VEL ";
data_log1 << std::endl;
}
// Write data for the present time
data_log1 << std::fixed;
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << time;
data_log1 << std::scientific;
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << mass;
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << momentum[0];
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << momentum[1];
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << momentum[2];
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << kinetic_energy;
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << gravitational_energy;
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << internal_energy;
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << total_energy;
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << angular_momentum[0];
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << angular_momentum[1];
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << angular_momentum[2];
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com[0];
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com[1];
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com[2];
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << mass_left;
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << mass_right;
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com_l[0];
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com_r[0];
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com_l[1];
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com_r[1];
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com_l[2];
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com_r[2];
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com_vel[0];
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com_vel[1];
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com_vel[2];
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com_vel_l[0];
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com_vel_r[0];
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com_vel_l[1];
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com_vel_r[1];
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com_vel_l[2];
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com_vel_r[2];
data_log1 << std::endl;
}
}
<commit_msg>Updated sum_integrated_quantities to get angular momentum correct in directions other than the rotation axis.<commit_after>#include <iomanip>
#include <Castro.H>
#include <Castro_F.H>
#include <Geometry.H>
void
Castro::sum_integrated_quantities ()
{
int finest_level = parent->finestLevel();
Real time = state[State_Type].curTime();
Real mass = 0.0;
Real momentum[3] = { 0.0 };
Real rho_E = 0.0;
Real rho_e = 0.0;
Real rho_phi = 0.0;
Real gravitational_energy = 0.0;
Real kinetic_energy = 0.0;
Real internal_energy = 0.0;
Real total_energy = 0.0;
Real angular_momentum[3] = { 0.0 };
Real moment_of_inertia[3][3] = { 0.0 };
Real m_r_squared[3] = { 0.0 };
Real omega[3] = { 0.0, 0.0, 2.0*3.14159265358979*rotational_frequency };
Real L_grid[3] = { 0.0 };
Real mass_left = 0.0;
Real mass_right = 0.0;
Real com[3] = { 0.0 };
Real com_l[3] = { 0.0 };
Real com_r[3] = { 0.0 };
Real delta_com[3] = { 0.0 };
Real com_vel[3] = { 0.0 };
Real com_vel_l[3] = { 0.0 };
Real com_vel_r[3] = { 0.0 };
std::string name1;
std::string name2;
int index1;
int index2;
int datawidth = 14;
int dataprecision = 6;
for (int lev = 0; lev <= finest_level; lev++)
{
// Get the current level from Castro
Castro& ca_lev = getLevel(lev);
// Calculate center of mass quantities.
mass_left += ca_lev.volWgtSumOneSide("density", time, 0, 0);
mass_right += ca_lev.volWgtSumOneSide("density", time, 1, 0);
for ( int i = 0; i <= 2; i++ ) {
switch ( i ) {
case 0 :
name1 = "xmom"; break;
case 1 :
name1 = "ymom"; break;
case 2 :
name1 = "zmom"; break;
}
delta_com[i] = ca_lev.locWgtSum("density", time, i);
com[i] += delta_com[i];
com_l[i] += ca_lev.locWgtSumOneSide("density", time, i, 0, 0);
com_r[i] += ca_lev.locWgtSumOneSide("density", time, i, 1, 0);
com_vel_l[i] += ca_lev.volWgtSumOneSide(name1, time, 0, 0);
com_vel_r[i] += ca_lev.volWgtSumOneSide(name1, time, 1, 0);
}
// Calculate total mass, momentum and energy of system.
mass += ca_lev.volWgtSum("density", time);
momentum[0] += ca_lev.volWgtSum("xmom", time);
momentum[1] += ca_lev.volWgtSum("ymom", time);
momentum[2] += ca_lev.volWgtSum("zmom", time);
rho_E += ca_lev.volWgtSum("rho_E", time);
rho_e += ca_lev.volWgtSum("rho_e", time);
if ( do_grav ) {
rho_phi += ca_lev.volProductSum("density", "phi", time);
}
// Calculate total angular momentum on the grid using L = r x p
for ( int i = 0; i <= 2; i++ ) {
index1 = (i+1) % 3;
index2 = (i+2) % 3;
switch (i) {
case 0 :
name1 = "ymom"; name2 = "zmom"; break;
case 1 :
name1 = "zmom"; name2 = "xmom"; break;
case 2 :
name1 = "xmom"; name2 = "ymom"; break;
}
L_grid[i] = ca_lev.locWgtSum(name2, time, index1) - ca_lev.locWgtSum(name1, time, index2);
angular_momentum[i] += L_grid[i];
}
// Add rotation source terms
if ( do_rotation ) {
// Construct (symmetric) moment of inertia tensor
for ( int i = 0; i <= 2; i++ ) {
m_r_squared[i] = ca_lev.locWgtSum2D("density", time, i, i);
}
for ( int i = 0; i <= 2; i++ ) {
for ( int j = 0; j <= 2; j++ ) {
if ( i <= j ) {
if ( i != j )
moment_of_inertia[i][j] = -ca_lev.locWgtSum2D("density", time, i, j);
else
moment_of_inertia[i][j] = m_r_squared[(i+1)%3] + m_r_squared[(i+2)%3];
}
else
moment_of_inertia[i][j] = moment_of_inertia[j][i];
}
}
for ( int i = 0; i <= 2; i++ ) {
// Momentum source from motion IN rotating frame == omega x (rho * r)
momentum[i] += omega[(i+1)%3]*delta_com[(i+2)%3] - omega[(i+2)%3]*delta_com[(i+1)%3];
// Rotational energy from motion IN rotating frame == omega dot L_grid
kinetic_energy += omega[i] * L_grid[i];
// Now add quantities due to motion OF rotating frame
for ( int j = 0; j <=2; j++ ) {
angular_momentum[i] += moment_of_inertia[i][j] * omega[j];
kinetic_energy += (1.0/2.0) * omega[i] * moment_of_inertia[i][j] * omega[j];
}
}
}
}
// Complete calculations for COM quantities
Real center = 0.0;
for ( int i = 0; i <= 2; i++ ) {
center = 0.5*(Geometry::ProbLo(i) + Geometry::ProbHi(i));
com[i] = com[i] / mass + center;
com_l[i] = com_l[i] / mass_left + center;
com_r[i] = com_r[i] / mass_right + center;
com_vel_l[i] = com_vel_l[i] / mass_left;
com_vel_r[i] = com_vel_r[i] / mass_right;
com_vel[i] = momentum[i] / mass;
}
const Real* ml = &mass_left;
const Real* mr = &mass_right;
const Real* cxl = &com_l[0];
const Real* cxr = &com_r[0];
const Real* cyl = &com_l[1];
const Real* cyr = &com_r[1];
const Real* czl = &com_l[2];
const Real* czr = &com_r[2];
BL_FORT_PROC_CALL(COM_SAVE,com_save)
(ml, mr, cxl, cxr, cyl, cyr, czl, czr);
// Complete calculations for energy
gravitational_energy = (-1.0/2.0) * rho_phi; // avoids double counting; CASTRO uses positive phi
internal_energy = rho_e;
kinetic_energy += rho_E - rho_e;
total_energy = gravitational_energy + internal_energy + kinetic_energy;
// Write data out to the log.
std::ostream& data_log1 = parent->DataLog(0);
if ( ParallelDescriptor::IOProcessor() && data_log1.good() )
{
// Write header row
if (time == 0.0) {
data_log1 << std::setw(datawidth) << "# TIME ";
data_log1 << std::setw(datawidth) << " MASS ";
data_log1 << std::setw(datawidth) << " XMOM ";
data_log1 << std::setw(datawidth) << " YMOM ";
data_log1 << std::setw(datawidth) << " ZMOM ";
data_log1 << std::setw(datawidth) << " KIN. ENERGY ";
data_log1 << std::setw(datawidth) << " GRAV. ENERGY";
data_log1 << std::setw(datawidth) << " INT. ENERGY ";
data_log1 << std::setw(datawidth) << " TOTAL ENERGY";
data_log1 << std::setw(datawidth) << " ANG. MOM. X ";
data_log1 << std::setw(datawidth) << " ANG. MOM. Y ";
data_log1 << std::setw(datawidth) << " ANG. MOM. Z ";
data_log1 << std::setw(datawidth) << " X COM ";
data_log1 << std::setw(datawidth) << " Y COM ";
data_log1 << std::setw(datawidth) << " Z COM ";
data_log1 << std::setw(datawidth) << " LEFT MASS ";
data_log1 << std::setw(datawidth) << " RIGHT MASS ";
data_log1 << std::setw(datawidth) << " LEFT X COM ";
data_log1 << std::setw(datawidth) << " RIGHT X COM ";
data_log1 << std::setw(datawidth) << " LEFT Y COM ";
data_log1 << std::setw(datawidth) << " RIGHT Y COM ";
data_log1 << std::setw(datawidth) << " LEFT Z COM ";
data_log1 << std::setw(datawidth) << " RIGHT Z COM ";
data_log1 << std::setw(datawidth) << " X VEL ";
data_log1 << std::setw(datawidth) << " Y VEL ";
data_log1 << std::setw(datawidth) << " Z VEL ";
data_log1 << std::setw(datawidth) << " LEFT X VEL ";
data_log1 << std::setw(datawidth) << " RIGHT X VEL ";
data_log1 << std::setw(datawidth) << " LEFT Y VEL ";
data_log1 << std::setw(datawidth) << " RIGHT Y VEL ";
data_log1 << std::setw(datawidth) << " LEFT Z VEL ";
data_log1 << std::setw(datawidth) << " RIGHT Z VEL ";
data_log1 << std::endl;
}
// Write data for the present time
data_log1 << std::fixed;
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << time;
data_log1 << std::scientific;
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << mass;
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << momentum[0];
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << momentum[1];
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << momentum[2];
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << kinetic_energy;
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << gravitational_energy;
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << internal_energy;
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << total_energy;
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << angular_momentum[0];
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << angular_momentum[1];
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << angular_momentum[2];
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com[0];
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com[1];
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com[2];
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << mass_left;
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << mass_right;
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com_l[0];
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com_r[0];
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com_l[1];
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com_r[1];
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com_l[2];
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com_r[2];
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com_vel[0];
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com_vel[1];
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com_vel[2];
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com_vel_l[0];
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com_vel_r[0];
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com_vel_l[1];
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com_vel_r[1];
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com_vel_l[2];
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com_vel_r[2];
data_log1 << std::endl;
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: optfltr.hxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: hr $ $Date: 2007-06-27 17:26:39 $
*
* 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 _OFA_OPTFLTR_HXX
#define _OFA_OPTFLTR_HXX
#ifndef _BUTTON_HXX //autogen
#include <vcl/button.hxx>
#endif
#ifndef _GROUP_HXX //autogen
#include <vcl/group.hxx>
#endif
#ifndef _SV_FIXED_HXX
#include <vcl/fixed.hxx>
#endif
#ifndef _SFXTABDLG_HXX //autogen
#include <sfx2/tabdlg.hxx>
#endif
#ifndef _SVX_SIMPTABL_HXX //autogen
#include <svx/simptabl.hxx>
#endif
class OfaMSFilterTabPage : public SfxTabPage
{
FixedLine aMSWordGB;
CheckBox aWBasicCodeCB;
CheckBox aWBasicStgCB;
FixedLine aMSExcelGB;
CheckBox aEBasicCodeCB;
CheckBox aEBasicStgCB;
FixedLine aMSPPointGB;
CheckBox aPBasicCodeCB;
CheckBox aPBasicStgCB;
OfaMSFilterTabPage( Window* pParent, const SfxItemSet& rSet );
virtual ~OfaMSFilterTabPage();
public:
static SfxTabPage* Create( Window* pParent,
const SfxItemSet& rAttrSet );
virtual BOOL FillItemSet( SfxItemSet& rSet );
virtual void Reset( const SfxItemSet& rSet );
};
class OfaMSFilterTabPage2 : public SfxTabPage
{
class MSFltrSimpleTable : public SvxSimpleTable
{
using SvTreeListBox::GetCheckButtonState;
using SvTreeListBox::SetCheckButtonState;
using SvxSimpleTable::SetTabs;
void CheckEntryPos(ULONG nPos, USHORT nCol, BOOL bChecked);
SvButtonState GetCheckButtonState( SvLBoxEntry*, USHORT nCol ) const;
void SetCheckButtonState( SvLBoxEntry*, USHORT nCol, SvButtonState );
protected:
virtual void SetTabs();
virtual void HBarClick();
virtual void KeyInput( const KeyEvent& rKEvt );
public:
MSFltrSimpleTable(Window* pParent, const ResId& rResId ) :
SvxSimpleTable( pParent, rResId ){}
};
MSFltrSimpleTable aCheckLB;
FixedText aHeader1FT, aHeader2FT;
Bitmap aChkunBmp, aChkchBmp, aChkchhiBmp,
aChkunhiBmp, aChktriBmp, aChktrihiBmp;
String sHeader1, sHeader2;
String sChgToFromMath,
sChgToFromWriter,
sChgToFromCalc,
sChgToFromImpress;
SvLBoxButtonData* pCheckButtonData;
OfaMSFilterTabPage2( Window* pParent, const SfxItemSet& rSet );
virtual ~OfaMSFilterTabPage2();
void InsertEntry( const String& _rTxt, sal_IntPtr _nType );
SvLBoxEntry* GetEntry4Type( sal_IntPtr _nType ) const;
public:
static SfxTabPage* Create( Window* pParent, const SfxItemSet& rAttrSet );
virtual BOOL FillItemSet( SfxItemSet& rSet );
virtual void Reset( const SfxItemSet& rSet );
};
#endif //
<commit_msg>INTEGRATION: CWS iconupdate03 (1.6.360); FILE MERGED 2007/06/26 07:27:09 pb 1.6.360.1: fix: #i61420# old CheckListBox bitmaps removed<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: optfltr.hxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: rt $ $Date: 2007-07-03 14:27:49 $
*
* 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 _OFA_OPTFLTR_HXX
#define _OFA_OPTFLTR_HXX
#ifndef _BUTTON_HXX //autogen
#include <vcl/button.hxx>
#endif
#ifndef _GROUP_HXX //autogen
#include <vcl/group.hxx>
#endif
#ifndef _SV_FIXED_HXX
#include <vcl/fixed.hxx>
#endif
#ifndef _SFXTABDLG_HXX //autogen
#include <sfx2/tabdlg.hxx>
#endif
#ifndef _SVX_SIMPTABL_HXX //autogen
#include <svx/simptabl.hxx>
#endif
class OfaMSFilterTabPage : public SfxTabPage
{
FixedLine aMSWordGB;
CheckBox aWBasicCodeCB;
CheckBox aWBasicStgCB;
FixedLine aMSExcelGB;
CheckBox aEBasicCodeCB;
CheckBox aEBasicStgCB;
FixedLine aMSPPointGB;
CheckBox aPBasicCodeCB;
CheckBox aPBasicStgCB;
OfaMSFilterTabPage( Window* pParent, const SfxItemSet& rSet );
virtual ~OfaMSFilterTabPage();
public:
static SfxTabPage* Create( Window* pParent,
const SfxItemSet& rAttrSet );
virtual BOOL FillItemSet( SfxItemSet& rSet );
virtual void Reset( const SfxItemSet& rSet );
};
class OfaMSFilterTabPage2 : public SfxTabPage
{
class MSFltrSimpleTable : public SvxSimpleTable
{
using SvTreeListBox::GetCheckButtonState;
using SvTreeListBox::SetCheckButtonState;
using SvxSimpleTable::SetTabs;
void CheckEntryPos(ULONG nPos, USHORT nCol, BOOL bChecked);
SvButtonState GetCheckButtonState( SvLBoxEntry*, USHORT nCol ) const;
void SetCheckButtonState( SvLBoxEntry*, USHORT nCol, SvButtonState );
protected:
virtual void SetTabs();
virtual void HBarClick();
virtual void KeyInput( const KeyEvent& rKEvt );
public:
MSFltrSimpleTable(Window* pParent, const ResId& rResId ) :
SvxSimpleTable( pParent, rResId ){}
};
MSFltrSimpleTable aCheckLB;
FixedText aHeader1FT, aHeader2FT;
String sHeader1, sHeader2;
String sChgToFromMath,
sChgToFromWriter,
sChgToFromCalc,
sChgToFromImpress;
SvLBoxButtonData* pCheckButtonData;
OfaMSFilterTabPage2( Window* pParent, const SfxItemSet& rSet );
virtual ~OfaMSFilterTabPage2();
void InsertEntry( const String& _rTxt, sal_IntPtr _nType );
SvLBoxEntry* GetEntry4Type( sal_IntPtr _nType ) const;
public:
static SfxTabPage* Create( Window* pParent, const SfxItemSet& rAttrSet );
virtual BOOL FillItemSet( SfxItemSet& rSet );
virtual void Reset( const SfxItemSet& rSet );
};
#endif //
<|endoftext|> |
<commit_before>#include <libmesh/equation_systems.h>
#include <libmesh/mesh.h>
#include <libmesh/mesh_generation.h>
#include <libmesh/elem.h>
#include <libmesh/dof_map.h>
#include "test_comm.h"
#include "libmesh_cppunit.h"
using namespace libMesh;
#ifdef LIBMESH_ENABLE_CONSTRAINTS
// This class is used by testConstraintLoopDetection
class MyConstraint : public System::Constraint
{
private:
System & _sys;
public:
MyConstraint( System & sys ) : Constraint(), _sys(sys) {}
virtual ~MyConstraint() {}
void constrain()
{
{
const dof_id_type constrained_dof_index = 0;
DofConstraintRow constraint_row;
constraint_row[1] = 1.0;
_sys.get_dof_map().add_constraint_row( constrained_dof_index, constraint_row, 0., true);
}
{
const dof_id_type constrained_dof_index = 1;
DofConstraintRow constraint_row;
constraint_row[0] = 1.0;
_sys.get_dof_map().add_constraint_row( constrained_dof_index, constraint_row, 0., true);
}
}
};
#endif
class DofMapTest : public CppUnit::TestCase {
public:
LIBMESH_CPPUNIT_TEST_SUITE( DofMapTest );
CPPUNIT_TEST( testDofOwnerOnEdge3 );
#if LIBMESH_DIM > 1
CPPUNIT_TEST( testDofOwnerOnQuad9 );
CPPUNIT_TEST( testDofOwnerOnTri6 );
#endif
#if LIBMESH_DIM > 2
CPPUNIT_TEST( testDofOwnerOnHex27 );
#endif
#if defined(LIBMESH_ENABLE_CONSTRAINTS) && defined(LIBMESH_ENABLE_EXCEPTIONS) && LIBMESH_DIM > 1
CPPUNIT_TEST( testConstraintLoopDetection );
#endif
CPPUNIT_TEST_SUITE_END();
private:
public:
void setUp()
{}
void tearDown()
{}
void testDofOwner(const ElemType elem_type)
{
Mesh mesh(*TestCommWorld);
EquationSystems es(mesh);
System &sys = es.add_system<System> ("SimpleSystem");
sys.add_variable("u", THIRD, HIERARCHIC);
const unsigned int n_elem_per_side = 3;
const std::unique_ptr<Elem> test_elem = Elem::build(elem_type);
const unsigned int ymax = test_elem->dim() > 1;
const unsigned int zmax = test_elem->dim() > 2;
const unsigned int ny = ymax * n_elem_per_side;
const unsigned int nz = zmax * n_elem_per_side;
MeshTools::Generation::build_cube (mesh,
n_elem_per_side,
ny,
nz,
0., 1.,
0., ymax,
0., zmax,
elem_type);
es.init();
DofMap & dof_map = sys.get_dof_map();
for (dof_id_type id = 0; id != dof_map.n_dofs(); ++id)
{
const processor_id_type pid = dof_map.dof_owner(id);
CPPUNIT_ASSERT(dof_map.first_dof(pid) <= id);
CPPUNIT_ASSERT(id < dof_map.end_dof(pid));
}
}
void testDofOwnerOnEdge3() { LOG_UNIT_TEST; testDofOwner(EDGE3); }
void testDofOwnerOnQuad9() { LOG_UNIT_TEST; testDofOwner(QUAD9); }
void testDofOwnerOnTri6() { LOG_UNIT_TEST; testDofOwner(TRI6); }
void testDofOwnerOnHex27() { LOG_UNIT_TEST; testDofOwner(HEX27); }
#if defined(LIBMESH_ENABLE_CONSTRAINTS) && defined(LIBMESH_ENABLE_EXCEPTIONS)
void testConstraintLoopDetection()
{
LOG_UNIT_TEST;
Mesh mesh(*TestCommWorld);
EquationSystems es(mesh);
System & sys = es.add_system<System> ("SimpleSystem");
sys.add_variable("u", FIRST);
MyConstraint my_constraint(sys);
sys.attach_constraint_object(my_constraint);
MeshTools::Generation::build_square (mesh,4,4,-1., 1.,-1., 1., QUAD4);
// Tell the dof_map to check for constraint loops
DofMap & dof_map = sys.get_dof_map();
dof_map.set_error_on_constraint_loop(true);
CPPUNIT_ASSERT_THROW_MESSAGE("Constraint loop not detected", es.init(), libMesh::LogicError);
}
#endif
};
CPPUNIT_TEST_SUITE_REGISTRATION( DofMapTest );
<commit_msg>Add testBadElemFECombo unit test<commit_after>#include <libmesh/equation_systems.h>
#include <libmesh/mesh.h>
#include <libmesh/mesh_generation.h>
#include <libmesh/elem.h>
#include <libmesh/dof_map.h>
#include "test_comm.h"
#include "libmesh_cppunit.h"
#include <regex>
#include <string>
using namespace libMesh;
#ifdef LIBMESH_ENABLE_CONSTRAINTS
// This class is used by testConstraintLoopDetection
class MyConstraint : public System::Constraint
{
private:
System & _sys;
public:
MyConstraint( System & sys ) : Constraint(), _sys(sys) {}
virtual ~MyConstraint() {}
void constrain()
{
{
const dof_id_type constrained_dof_index = 0;
DofConstraintRow constraint_row;
constraint_row[1] = 1.0;
_sys.get_dof_map().add_constraint_row( constrained_dof_index, constraint_row, 0., true);
}
{
const dof_id_type constrained_dof_index = 1;
DofConstraintRow constraint_row;
constraint_row[0] = 1.0;
_sys.get_dof_map().add_constraint_row( constrained_dof_index, constraint_row, 0., true);
}
}
};
#endif
class DofMapTest : public CppUnit::TestCase {
public:
LIBMESH_CPPUNIT_TEST_SUITE( DofMapTest );
CPPUNIT_TEST( testDofOwnerOnEdge3 );
#if LIBMESH_DIM > 1
CPPUNIT_TEST( testDofOwnerOnQuad9 );
CPPUNIT_TEST( testDofOwnerOnTri6 );
#endif
#if LIBMESH_DIM > 2
CPPUNIT_TEST( testDofOwnerOnHex27 );
#endif
CPPUNIT_TEST( testBadElemFECombo );
#if defined(LIBMESH_ENABLE_CONSTRAINTS) && defined(LIBMESH_ENABLE_EXCEPTIONS) && LIBMESH_DIM > 1
CPPUNIT_TEST( testConstraintLoopDetection );
#endif
CPPUNIT_TEST_SUITE_END();
private:
public:
void setUp()
{}
void tearDown()
{}
void testDofOwner(const ElemType elem_type)
{
Mesh mesh(*TestCommWorld);
EquationSystems es(mesh);
System &sys = es.add_system<System> ("SimpleSystem");
sys.add_variable("u", THIRD, HIERARCHIC);
const unsigned int n_elem_per_side = 3;
const std::unique_ptr<Elem> test_elem = Elem::build(elem_type);
const unsigned int ymax = test_elem->dim() > 1;
const unsigned int zmax = test_elem->dim() > 2;
const unsigned int ny = ymax * n_elem_per_side;
const unsigned int nz = zmax * n_elem_per_side;
MeshTools::Generation::build_cube (mesh,
n_elem_per_side,
ny,
nz,
0., 1.,
0., ymax,
0., zmax,
elem_type);
es.init();
DofMap & dof_map = sys.get_dof_map();
for (dof_id_type id = 0; id != dof_map.n_dofs(); ++id)
{
const processor_id_type pid = dof_map.dof_owner(id);
CPPUNIT_ASSERT(dof_map.first_dof(pid) <= id);
CPPUNIT_ASSERT(id < dof_map.end_dof(pid));
}
}
void testDofOwnerOnEdge3() { LOG_UNIT_TEST; testDofOwner(EDGE3); }
void testDofOwnerOnQuad9() { LOG_UNIT_TEST; testDofOwner(QUAD9); }
void testDofOwnerOnTri6() { LOG_UNIT_TEST; testDofOwner(TRI6); }
void testDofOwnerOnHex27() { LOG_UNIT_TEST; testDofOwner(HEX27); }
void testBadElemFECombo()
{
LOG_UNIT_TEST;
Mesh mesh(*TestCommWorld);
EquationSystems es(mesh);
System & sys = es.add_system<System> ("SimpleSystem");
sys.add_variable("u", SECOND);
MeshTools::Generation::build_square (mesh,4,4,-1., 1.,-1., 1., QUAD4);
// We can't just CPPUNIT_ASSERT_THROW, because we want to make
// sure we were thrown from the right place with the right error
// message!
bool threw_desired_exception = false;
try {
es.init();
}
catch (libMesh::LogicError & e) {
std::regex msg_regex("only supports FEInterface::max_order");
CPPUNIT_ASSERT(std::regex_search(e.what(), msg_regex));
threw_desired_exception = true;
}
catch (...) {
CPPUNIT_ASSERT(false);
}
CPPUNIT_ASSERT(threw_desired_exception);
CPPUNIT_ASSERT_THROW_MESSAGE("Incompatible Elem/FE combo not detected", es.init(), libMesh::LogicError);
}
#if defined(LIBMESH_ENABLE_CONSTRAINTS) && defined(LIBMESH_ENABLE_EXCEPTIONS)
void testConstraintLoopDetection()
{
LOG_UNIT_TEST;
Mesh mesh(*TestCommWorld);
EquationSystems es(mesh);
System & sys = es.add_system<System> ("SimpleSystem");
sys.add_variable("u", FIRST);
MyConstraint my_constraint(sys);
sys.attach_constraint_object(my_constraint);
MeshTools::Generation::build_square (mesh,4,4,-1., 1.,-1., 1., QUAD4);
// Tell the dof_map to check for constraint loops
DofMap & dof_map = sys.get_dof_map();
dof_map.set_error_on_constraint_loop(true);
CPPUNIT_ASSERT_THROW_MESSAGE("Constraint loop not detected", es.init(), libMesh::LogicError);
}
#endif
};
CPPUNIT_TEST_SUITE_REGISTRATION( DofMapTest );
<|endoftext|> |
<commit_before><commit_msg>INTEGRATION: CWS vgbugs07 (1.10.320); FILE MERGED 2007/06/04 13:27:25 vg 1.10.320.1: #i76605# Remove -I .../inc/module hack introduced by hedaburemove01<commit_after><|endoftext|> |
<commit_before>//------------------------------------------------------------------------------
// cpp-compile-test.cc
// Just check whether (most of) the sokol headers also comppile as C++.
//------------------------------------------------------------------------------
#if defined(__APPLE__)
#error "This is for non-apple platforms only"
#elif defined(__EMSCRIPTEN__)
#define SOKOL_GLES2
#elif defined(_WIN32)
#define SOKOL_D3D11
#else
#define SOKOL_GLCORE33
#endif
#define SOKOL_IMPL
#define SOKOL_WIN32_FORCE_MAIN
#include "sokol_app.h"
#include "sokol_args.h"
#include "sokol_audio.h"
#include "sokol_gfx.h"
#include "sokol_time.h"
static sapp_desc desc;
sapp_desc sokol_main(int argc, char* argv[]) {
/* just interested whether the compilation worked, so force-exit here */
exit(0);
return desc;
}
<commit_msg>cpp-compile-test: Android fix<commit_after>//------------------------------------------------------------------------------
// cpp-compile-test.cc
// Just check whether (most of) the sokol headers also comppile as C++.
//------------------------------------------------------------------------------
#if defined(__APPLE__)
#error "This is for non-apple platforms only"
#elif defined(__EMSCRIPTEN__)
#define SOKOL_GLES2
#elif defined(_WIN32)
#define SOKOL_D3D11
#elif defined(__ANDROID__)
#define SOKOL_GLES3
#else
#define SOKOL_GLCORE33
#endif
#define SOKOL_IMPL
#define SOKOL_WIN32_FORCE_MAIN
#include "sokol_app.h"
#include "sokol_args.h"
#include "sokol_audio.h"
#include "sokol_gfx.h"
#include "sokol_time.h"
static sapp_desc desc;
sapp_desc sokol_main(int argc, char* argv[]) {
/* just interested whether the compilation worked, so force-exit here */
exit(0);
return desc;
}
<|endoftext|> |
<commit_before>/* Copyright (C) 2016 INRA
*
* 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 "unit-test.hpp"
#include <fstream>
#include <iostream>
#include <lpcore-compare>
#include <lpcore-out>
#include <lpcore>
#include <map>
#include <numeric>
#include <random>
#include <sstream>
void
test_assignment_problem()
{
auto pb = lp::make_problem(EXAMPLES_DIR "/assignment_problem_1.lp");
std::map<std::string, lp::parameter> params;
params["limit"] = 50l;
auto result = lp::solve(pb, params);
Ensures(result.solution_found == true);
}
void
test_assignment_problem_random_coast()
{
auto pb = lp::make_problem(EXAMPLES_DIR "/assignment_problem_1.lp");
std::map<std::string, lp::parameter> params;
params["limit"] = 50l;
for (int i{ 0 }, e{ 10 }; i != e; ++i) {
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> dis(1, 100);
for (auto& elem : pb.objective.elements)
elem.factor = dis(gen);
auto result = lp::solve(pb, params);
Ensures(result.solution_found == true);
}
}
void
test_negative_coeff()
{
auto pb = lp::make_problem(EXAMPLES_DIR "/negative-coeff.lp");
std::map<std::string, lp::parameter> params;
params["limit"] = 50l;
auto result = lp::solve(pb, params);
Ensures(result.solution_found == true);
}
void
test_negative_coeff2()
{
auto pb = lp::make_problem(EXAMPLES_DIR "/negative-coeff2.lp");
std::map<std::string, lp::parameter> params;
params["limit"] = 50l;
auto result = lp::solve(pb, params);
Ensures(result.solution_found == true);
Ensures(result.variable_value[0] == 1);
Ensures(result.variable_value[1] == 0);
Ensures(result.variable_value[2] == 0);
Ensures(result.variable_value[3] == 1);
}
void
test_negative_coeff3()
{
auto pb = lp::make_problem(EXAMPLES_DIR "/negative-coeff3.lp");
std::map<std::string, lp::parameter> params;
params["limit"] = 50l;
auto result = lp::solve(pb, params);
Ensures(result.solution_found == true);
}
void
test_flat30_7()
{
auto pb = lp::make_problem(EXAMPLES_DIR "/flat30-7.lp");
std::map<std::string, lp::parameter> params;
params["limit"] = 10'000'000l;
params["theta"] = 0.5;
params["delta"] = 0.2;
params["kappa-step"] = 10e-4;
params["kappa-max"] = 10.0;
params["alpha"] = 1.0;
params["w"] = 20l;
auto result = lp::solve(pb, params);
Ensures(result.solution_found == true);
}
void
test_uf50_0448()
{
auto pb = lp::make_problem(EXAMPLES_DIR "/uf50-0448.lp");
std::map<std::string, lp::parameter> params;
params["limit"] = 10'000'000l;
params["theta"] = 0.5;
params["delta"] = 0.2;
params["kappa-step"] = 10e-4;
params["kappa-max"] = 10.0;
params["alpha"] = 1.0;
params["w"] = 20l;
auto result = lp::solve(pb, params);
Ensures(result.solution_found == true);
}
void
aim_50_1_6_yes1_2()
{
auto pb = lp::make_problem(EXAMPLES_DIR "/uf50-0448.lp");
std::map<std::string, lp::parameter> params;
params["limit"] = 10'000'000l;
params["theta"] = 0.5;
params["delta"] = 0.1;
params["kappa-step"] = 10e-5;
params["kappa-max"] = 10.0;
params["alpha"] = 2.0;
params["w"] = 20l;
auto result = lp::solve(pb, params);
Ensures(result.solution_found == true);
}
void
test_bibd1n()
{
auto pb = lp::make_problem(EXAMPLES_DIR "/uf50-0448.lp");
std::map<std::string, lp::parameter> params;
params["limit"] = 10'000'000'000l;
params["theta"] = 0.5;
params["delta"] = 0.2;
params["kappa-step"] = 10e-8;
params["kappa-max"] = 60.0;
params["alpha"] = 1.0;
params["w"] = 10l;
auto result = lp::solve(pb, params);
Ensures(result.solution_found == true);
}
void
test_8_queens_puzzle_fixed_cost()
{
auto pb = lp::make_problem(EXAMPLES_DIR "/8_queens_puzzle.lp");
std::map<std::string, lp::parameter> params;
params["kappa"] = 0.1;
params["theta"] = 0.5;
params["delta"] = 0.5;
params["limit"] = 100l;
std::vector<int> cost{ 25, 89, 12, 22, 84, 3, 61, 14, 93, 97, 68, 5, 51,
72, 96, 80, 13, 38, 81, 48, 70, 50, 66, 68, 30, 97,
79, 4, 41, 44, 47, 62, 60, 11, 18, 44, 57, 24, 7,
11, 66, 87, 9, 17, 27, 60, 95, 45, 94, 47, 60, 87,
79, 53, 81, 52, 91, 53, 57, 8, 63, 78, 1, 8 };
std::size_t i{ 0 };
for (auto& elem : pb.objective.elements)
elem.factor = cost[i++];
auto result = lp::solve(pb, params);
for (int i = 0; i != 8; ++i) {
for (int j = 0; j != 8; ++j) {
std::cout << result.variable_value[j * 8 + i] << ' ';
}
std::cout << '\n';
}
Ensures(result.solution_found == true);
}
void
test_8_queens_puzzle_random_cost()
{
auto pb = lp::make_problem(EXAMPLES_DIR "/8_queens_puzzle.lp");
std::map<std::string, lp::parameter> params;
params["limit"] = 1'000l;
for (int i{ 0 }, e{ 10 }; i != e; ++i) {
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> dis(1, 100);
for (auto& elem : pb.objective.elements)
elem.factor = dis(gen);
auto result = lp::solve(pb, params);
Ensures(result.solution_found == true);
}
}
void
test_qap()
{
auto pb = lp::make_problem(EXAMPLES_DIR "/small4.lp");
std::map<std::string, lp::parameter> params;
params["limit"] = 10'000'000l;
params["theta"] = 0.5;
params["delta"] = 0.2;
params["kappa-step"] = 10e-4;
params["kappa-max"] = 10.0;
params["alpha"] = 1.0;
params["w"] = 20l;
auto result = lp::solve(pb, params);
}
void
test_verger_5_5()
{
auto pb = lp::make_problem(EXAMPLES_DIR "/verger_5_5.lp");
std::map<std::string, lp::parameter> params;
params["limit"] = 10'000'000l;
params["theta"] = 0.5;
params["delta"] = 0.2;
params["kappa-step"] = 10e-4;
params["kappa-max"] = 10.0;
params["alpha"] = 1.0;
params["w"] = 20l;
auto result = lp::solve(pb, params);
}
int
main(int /* argc */, char* /* argv */ [])
{
// test_assignment_problem();
// test_assignment_problem_random_coast();
// test_negative_coeff();
// test_negative_coeff2();
// test_negative_coeff3();
// test_8_queens_puzzle_fixed_cost();
// test_8_queens_puzzle_random_cost();
// test_flat30_7();
// test_qap();
// test_uf50_0448();
// aim_50_1_6_yes1_2();
test_bibd1n();
// test_verger_5_5();
return unit_test::report_errors();
}
<commit_msg>test: try to change some parameters<commit_after>/* Copyright (C) 2016 INRA
*
* 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 "unit-test.hpp"
#include <fstream>
#include <iostream>
#include <lpcore-compare>
#include <lpcore-out>
#include <lpcore>
#include <map>
#include <numeric>
#include <random>
#include <sstream>
void
test_assignment_problem()
{
auto pb = lp::make_problem(EXAMPLES_DIR "/assignment_problem_1.lp");
std::map<std::string, lp::parameter> params;
params["limit"] = 50l;
auto result = lp::solve(pb, params);
Ensures(result.solution_found == true);
}
void
test_assignment_problem_random_coast()
{
auto pb = lp::make_problem(EXAMPLES_DIR "/assignment_problem_1.lp");
std::map<std::string, lp::parameter> params;
params["limit"] = 50l;
for (int i{ 0 }, e{ 10 }; i != e; ++i) {
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> dis(1, 100);
for (auto& elem : pb.objective.elements)
elem.factor = dis(gen);
auto result = lp::solve(pb, params);
Ensures(result.solution_found == true);
}
}
void
test_negative_coeff()
{
auto pb = lp::make_problem(EXAMPLES_DIR "/negative-coeff.lp");
std::map<std::string, lp::parameter> params;
params["limit"] = 50l;
auto result = lp::solve(pb, params);
Ensures(result.solution_found == true);
}
void
test_negative_coeff2()
{
auto pb = lp::make_problem(EXAMPLES_DIR "/negative-coeff2.lp");
std::map<std::string, lp::parameter> params;
params["limit"] = 50l;
auto result = lp::solve(pb, params);
Ensures(result.solution_found == true);
Ensures(result.variable_value[0] == 1);
Ensures(result.variable_value[1] == 0);
Ensures(result.variable_value[2] == 0);
Ensures(result.variable_value[3] == 1);
}
void
test_negative_coeff3()
{
auto pb = lp::make_problem(EXAMPLES_DIR "/negative-coeff3.lp");
std::map<std::string, lp::parameter> params;
params["limit"] = 50l;
auto result = lp::solve(pb, params);
Ensures(result.solution_found == true);
}
void
test_flat30_7()
{
auto pb = lp::make_problem(EXAMPLES_DIR "/flat30-7.lp");
std::map<std::string, lp::parameter> params;
params["limit"] = 10'000'000l;
params["theta"] = 0.5;
params["delta"] = 0.2;
params["kappa-step"] = 10e-4;
params["kappa-max"] = 10.0;
params["alpha"] = 1.0;
params["w"] = 20l;
auto result = lp::solve(pb, params);
Ensures(result.solution_found == true);
}
void
test_uf50_0448()
{
auto pb = lp::make_problem(EXAMPLES_DIR "/uf50-0448.lp");
std::map<std::string, lp::parameter> params;
params["limit"] = 10'000'000'000l;
params["theta"] = 0.5;
params["delta"] = 0.001;
params["kappa-min"] = 0.3;
params["kappa-step"] = 1e-4;
params["kappa-max"] = 100.0;
params["alpha"] = 1.0;
params["w"] = 20l;
auto result = lp::solve(pb, params);
Ensures(result.solution_found == true);
}
void
aim_50_1_6_yes1_2()
{
auto pb = lp::make_problem(EXAMPLES_DIR "/aim-50-1_6-yes1-2.lp.lp");
std::map<std::string, lp::parameter> params;
params["limit"] = 10'000'000'000l;
params["theta"] = 0.6;
params["delta"] = 0.01;
params["kappa-step"] = 2 * 10e-4;
params["kappa-max"] = 100.0;
params["alpha"] = 1.0;
params["w"] = 20l;
auto result = lp::solve(pb, params);
Ensures(result.solution_found == true);
}
void
test_bibd1n()
{
auto pb = lp::make_problem(EXAMPLES_DIR "/bibd1n.lp");
std::map<std::string, lp::parameter> params;
params["limit"] = 10'000'000'000l;
params["theta"] = 0.6;
params["delta"] = 0.01;
params["kappa-step"] = 2e-4;
params["kappa-min"] = 0.3;
params["kappa-max"] = 100.0;
params["alpha"] = 2.0;
params["w"] = 20l;
auto result = lp::solve(pb, params);
Ensures(result.solution_found == true);
}
void
test_8_queens_puzzle_fixed_cost()
{
auto pb = lp::make_problem(EXAMPLES_DIR "/8_queens_puzzle.lp");
std::map<std::string, lp::parameter> params;
params["kappa"] = 0.1;
params["theta"] = 0.5;
params["delta"] = 0.5;
params["limit"] = 100l;
std::vector<int> cost{ 25, 89, 12, 22, 84, 3, 61, 14, 93, 97, 68, 5, 51,
72, 96, 80, 13, 38, 81, 48, 70, 50, 66, 68, 30, 97,
79, 4, 41, 44, 47, 62, 60, 11, 18, 44, 57, 24, 7,
11, 66, 87, 9, 17, 27, 60, 95, 45, 94, 47, 60, 87,
79, 53, 81, 52, 91, 53, 57, 8, 63, 78, 1, 8 };
std::size_t i{ 0 };
for (auto& elem : pb.objective.elements)
elem.factor = cost[i++];
auto result = lp::solve(pb, params);
for (int i = 0; i != 8; ++i) {
for (int j = 0; j != 8; ++j) {
std::cout << result.variable_value[j * 8 + i] << ' ';
}
std::cout << '\n';
}
Ensures(result.solution_found == true);
}
void
test_8_queens_puzzle_random_cost()
{
auto pb = lp::make_problem(EXAMPLES_DIR "/8_queens_puzzle.lp");
std::map<std::string, lp::parameter> params;
params["limit"] = 1'000l;
for (int i{ 0 }, e{ 10 }; i != e; ++i) {
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> dis(1, 100);
for (auto& elem : pb.objective.elements)
elem.factor = dis(gen);
auto result = lp::solve(pb, params);
Ensures(result.solution_found == true);
}
}
void
test_qap()
{
auto pb = lp::make_problem(EXAMPLES_DIR "/small4.lp");
std::map<std::string, lp::parameter> params;
params["limit"] = 10'000'000l;
params["theta"] = 0.5;
params["delta"] = 0.2;
params["kappa-step"] = 10e-4;
params["kappa-max"] = 10.0;
params["alpha"] = 1.0;
params["w"] = 20l;
auto result = lp::solve(pb, params);
}
void
test_verger_5_5()
{
auto pb = lp::make_problem(EXAMPLES_DIR "/verger_5_5.lp");
std::map<std::string, lp::parameter> params;
params["limit"] = 10'000'000l;
params["theta"] = 0.5;
params["delta"] = 0.01;
params["kappa-step"] = 2 * 10e-4;
params["kappa-max"] = 60.0;
params["alpha"] = 1.0;
params["w"] = 20l;
// params["limit"] = 10'000'000l;
// params["theta"] = 0.5;
// params["delta"] = 0.2;
// params["kappa-step"] = 10e-7;
// params["kappa-max"] = 60.0;
// params["alpha"] = 1.0;
// params["w"] = 20l;
auto result = lp::solve(pb, params);
}
int
main(int /* argc */, char* /* argv */ [])
{
// test_assignment_problem();
// test_assignment_problem_random_coast();
// test_negative_coeff();
// test_negative_coeff2();
// test_negative_coeff3();
// test_8_queens_puzzle_fixed_cost();
// test_8_queens_puzzle_random_cost();
// test_flat30_7();
// test_qap();
// test_uf50_0448();
// aim_50_1_6_yes1_2();
test_bibd1n();
// test_verger_5_5();
return unit_test::report_errors();
}
<|endoftext|> |
<commit_before><commit_msg>dead assign (clang)<commit_after><|endoftext|> |
<commit_before>#include "THttpServer.h"
#include "THttpWSHandler.h"
#include "THttpCallArg.h"
#include "TString.h"
#include "TSystem.h"
#include "TDatime.h"
#include "TTimer.h"
#include <cstdio>
class TUserHandler : public THttpWSHandler {
public:
UInt_t fWSId;
Int_t fServCnt;
TUserHandler(const char *name = nullptr, const char *title = nullptr) : THttpWSHandler(name, title), fWSId(0), fServCnt(0) {}
// load custom HTML page when open correspondent address
TString GetDefaultPageContent() { return "file:ws.htm"; }
virtual Bool_t ProcessWS(THttpCallArg *arg)
{
if (!arg || (arg->GetWSId()==0)) return kTRUE;
// printf("Method %s\n", arg->GetMethod());
if (arg->IsMethod("WS_CONNECT")) {
// accept only if connection not established
return fWSId == 0;
}
if (arg->IsMethod("WS_READY")) {
fWSId = arg->GetWSId();
printf("Client connected %d\n", fWSId);
return kTRUE;
}
if (arg->IsMethod("WS_CLOSE")) {
fWSId = 0;
printf("Client disconnected\n");
return kTRUE;
}
if (arg->IsMethod("WS_DATA")) {
TString str;
str.Append((const char *)arg->GetPostData(), arg->GetPostDataLength());
printf("Client msg: %s\n", str.Data());
TDatime now;
SendCharStarWS(arg->GetWSId(), Form("Server replies:%s server counter:%d", now.AsString(), fServCnt++));
return kTRUE;
}
return kFALSE;
}
/// per timeout sends data portion to the client
virtual Bool_t HandleTimer(TTimer *)
{
TDatime now;
if (fWSId) SendCharStarWS(fWSId, Form("Server sends data:%s server counter:%d", now.AsString(), fServCnt++));
return kTRUE;
}
};
void ws()
{
THttpServer *serv = new THttpServer("http:8090");
TUserHandler *handler = new TUserHandler("name1", "title1");
serv->Register("/folder1", handler);
const char *addr = "http://localhost:8090/folder1/name1/";
printf("Starting browser with URL address %s\n", addr);
printf("In browser content of ws.htm file should be loaded\n");
printf("Please be sure that ws.htm is provided in current directory\n");
if (gSystem->InheritsFrom("TMacOSXSystem"))
gSystem->Exec(Form("open %s", addr));
else if (gSystem->InheritsFrom("TWinNTSystem")) {
gSystem->Exec(Form("start %s", addr));
else
gSystem->Exec(Form("xdg-open %s &", addr));
// when connection will be established, data will be send to the client
TTimer *tm = new TTimer(handler, 3700);
tm->Start();
}
<commit_msg>[http] fix typo in ws.C<commit_after>#include "THttpServer.h"
#include "THttpWSHandler.h"
#include "THttpCallArg.h"
#include "TString.h"
#include "TSystem.h"
#include "TDatime.h"
#include "TTimer.h"
#include <cstdio>
class TUserHandler : public THttpWSHandler {
public:
UInt_t fWSId;
Int_t fServCnt;
TUserHandler(const char *name = nullptr, const char *title = nullptr) : THttpWSHandler(name, title), fWSId(0), fServCnt(0) {}
// load custom HTML page when open correspondent address
TString GetDefaultPageContent() { return "file:ws.htm"; }
virtual Bool_t ProcessWS(THttpCallArg *arg)
{
if (!arg || (arg->GetWSId()==0)) return kTRUE;
// printf("Method %s\n", arg->GetMethod());
if (arg->IsMethod("WS_CONNECT")) {
// accept only if connection not established
return fWSId == 0;
}
if (arg->IsMethod("WS_READY")) {
fWSId = arg->GetWSId();
printf("Client connected %d\n", fWSId);
return kTRUE;
}
if (arg->IsMethod("WS_CLOSE")) {
fWSId = 0;
printf("Client disconnected\n");
return kTRUE;
}
if (arg->IsMethod("WS_DATA")) {
TString str;
str.Append((const char *)arg->GetPostData(), arg->GetPostDataLength());
printf("Client msg: %s\n", str.Data());
TDatime now;
SendCharStarWS(arg->GetWSId(), Form("Server replies:%s server counter:%d", now.AsString(), fServCnt++));
return kTRUE;
}
return kFALSE;
}
/// per timeout sends data portion to the client
virtual Bool_t HandleTimer(TTimer *)
{
TDatime now;
if (fWSId) SendCharStarWS(fWSId, Form("Server sends data:%s server counter:%d", now.AsString(), fServCnt++));
return kTRUE;
}
};
void ws()
{
THttpServer *serv = new THttpServer("http:8090");
TUserHandler *handler = new TUserHandler("name1", "title1");
serv->Register("/folder1", handler);
const char *addr = "http://localhost:8090/folder1/name1/";
printf("Starting browser with URL address %s\n", addr);
printf("In browser content of ws.htm file should be loaded\n");
printf("Please be sure that ws.htm is provided in current directory\n");
if (gSystem->InheritsFrom("TMacOSXSystem"))
gSystem->Exec(Form("open %s", addr));
else if (gSystem->InheritsFrom("TWinNTSystem"))
gSystem->Exec(Form("start %s", addr));
else
gSystem->Exec(Form("xdg-open %s &", addr));
// when connection will be established, data will be send to the client
TTimer *tm = new TTimer(handler, 3700);
tm->Start();
}
<|endoftext|> |
<commit_before>#include <Halide.h>
#include <math.h>
#include <sys/time.h>
using namespace Halide;
template<typename A>
const char *string_of_type();
#define DECL_SOT(name) \
template<> \
const char *string_of_type<name>() {return #name;}
DECL_SOT(uint8_t);
DECL_SOT(int8_t);
DECL_SOT(uint16_t);
DECL_SOT(int16_t);
DECL_SOT(uint32_t);
DECL_SOT(int32_t);
DECL_SOT(float);
DECL_SOT(double);
double currentTime() {
timeval t;
gettimeofday(&t, NULL);
return t.tv_sec * 1000.0 + t.tv_usec / 1000.0f;
}
template<typename A>
A mod(A x, A y);
template<>
float mod(float x, float y) {
return fmod(x, y);
}
template<>
double mod(double x, double y) {
return fmod(x, y);
}
template<typename A>
A mod(A x, A y) {
return x % y;
}
template<typename A>
bool test(int vec_width) {
const int W = 6400;
const int H = 16;
Image<A> input(W+16, H+16);
for (int y = 0; y < H+16; y++) {
for (int x = 0; x < W+16; x++) {
input(x, y) = (A)(rand()*0.125 + 1.0);
}
}
Var x, y;
// Add
Func f1;
f1(x, y) = input(x, y) + input(x+1, y);
f1.vectorize(x, vec_width);
Image<A> im1 = f1.realize(W, H);
for (int y = 0; y < H; y++) {
for (int x = 0; x < W; x++) {
A correct = input(x, y) + input(x+1, y);
if (im1(x, y) != correct) {
printf("im1(%d, %d) = %f instead of %f\n", x, y, (double)(im1(x, y)), (double)(correct));
return false;
}
}
}
// Sub
Func f2;
f2(x, y) = input(x, y) - input(x+1, y);
f2.vectorize(x, vec_width);
Image<A> im2 = f2.realize(W, H);
for (int y = 0; y < H; y++) {
for (int x = 0; x < W; x++) {
A correct = input(x, y) - input(x+1, y);
if (im2(x, y) != correct) {
printf("im2(%d, %d) = %f instead of %f\n", x, y, (double)(im2(x, y)), (double)(correct));
return false;
}
}
}
// Mul
Func f3;
f3(x, y) = input(x, y) * input(x+1, y);
f3.vectorize(x, vec_width);
Image<A> im3 = f3.realize(W, H);
for (int y = 0; y < H; y++) {
for (int x = 0; x < W; x++) {
A correct = input(x, y) * input(x+1, y);
if (im3(x, y) != correct) {
printf("im3(%d, %d) = %f instead of %f\n", x, y, (double)(im3(x, y)), (double)(correct));
return false;
}
}
}
// select
Func f4;
f4(x, y) = select(input(x, y) > input(x+1, y), input(x+2, y), input(x+3, y));
f4.vectorize(x, vec_width);
Image<A> im4 = f4.realize(W, H);
for (int y = 0; y < H; y++) {
for (int x = 0; x < W; x++) {
A correct = input(x, y) > input(x+1, y) ? input(x+2, y) : input(x+3, y);
if (im4(x, y) != correct) {
printf("im4(%d, %d) = %f instead of %f\n", x, y, (double)(im4(x, y)), (double)(correct));
return false;
}
}
}
// Gather
Func f5;
Expr xCoord = clamp(cast<int>(input(x, y)), 0, W-1);
Expr yCoord = clamp(cast<int>(input(x+1, y)), 0, H-1);
f5(x, y) = input(xCoord, yCoord);
f5.vectorize(x, vec_width);
Image<A> im5 = f5.realize(W, H);
for (int y = 0; y < H; y++) {
for (int x = 0; x < W; x++) {
int xCoord = (int)(input(x, y));
if (xCoord >= W) xCoord = W-1;
if (xCoord < 0) xCoord = 0;
int yCoord = (int)(input(x+1, y));
if (yCoord >= H) yCoord = H-1;
if (yCoord < 0) yCoord = 0;
A correct = input(xCoord, yCoord);
if (im5(x, y) != correct) {
printf("im5(%d, %d) = %f instead of %f\n", x, y, (double)(im5(x, y)), (double)(correct));
return false;
}
}
}
// Scatter
Func f6;
RDom i(0, H);
// Set one entry in each row high
xCoord = clamp(cast<int>(input(2*i, i)), 0, W-1);
f6(x, y) = 0;
f6(xCoord, i) = 1;
f6.vectorize(x, vec_width);
Image<int> im6 = f6.realize(W, H);
for (int y = 0; y < H; y++) {
int xCoord = (int)(input(2*y, y));
if (xCoord >= W) xCoord = W-1;
if (xCoord < 0) xCoord = 0;
for (int x = 0; x < W; x++) {
int correct = x == xCoord ? 1 : 0;
if (im6(x, y) != correct) {
printf("im6(%d, %d) = %d instead of %d\n", x, y, im6(x, y), correct);
return false;
}
}
}
// Min/max
Func f7;
f7(x, y) = clamp(input(x, y), cast<A>(10), cast<A>(20));
f7.vectorize(x, vec_width);
Image<A> im7 = f7.realize(W, H);
for (int y = 0; y < H; y++) {
for (int x = 0; x < W; x++) {
if (im7(x, y) < (A)10 || im7(x, y) > (A)20) {
printf("im7(%d, %d) = %f instead of %f\n", x, y, (double)(im7(x, y)));
return false;
}
}
}
// Extern function call
Func f8;
f8(x, y) = pow(2.0f, cast<float>(input(x, y)));
f8.vectorize(x, vec_width);
Image<float> im8 = f8.realize(W, H);
for (int y = 0; y < H; y++) {
for (int x = 0; x < W; x++) {
float correct = powf(2.0f, (float)input(x, y));
if (im8(x, y) != correct) {
printf("im8(%d, %d) = %f instead of %f\n", x, y, im8(x, y));
return false;
}
}
}
// Div
Func f9;
f9(x, y) = input(x, y) / clamp(input(x+1, y), cast<A>(1), cast<A>(3));
f9.vectorize(x, vec_width);
Image<A> im9 = f9.realize(W, H);
for (int y = 0; y < H; y++) {
for (int x = 0; x < W; x++) {
A clamped = input(x+1, y);
if (clamped < (A)1) clamped = (A)1;
if (clamped > (A)3) clamped = (A)3;
A correct = input(x, y) / clamped;
if (im9(x, y) != correct) {
printf("im9(%d, %d) = %f instead of %f\n", x, y, (double)(im9(x, y)), (double)(correct));
return false;
}
}
}
// Interleave
Func f11;
f11(x, y) = select((x%2)==0, input(x/2, y), input(x/2, y+1));
f11.vectorize(x, vec_width);
Image<A> im11 = f11.realize(W, H);
for (int y = 0; y < H; y++) {
for (int x = 0; x < W; x++) {
A correct = ((x%2)==0) ? input(x/2, y) : input(x/2, y+1);
if (im11(x, y) != correct) {
printf("im11(%d, %d) = %f instead of %f\n", x, y, (double)(im11(x, y)), (double)(correct));
return false;
}
}
}
return true;
}
int main(int argc, char **argv) {
bool ok = true;
// Only native vector widths - llvm doesn't handle others well
ok = ok && test<float>(4);
ok = ok && test<double>(2);
ok = ok && test<uint8_t>(16);
ok = ok && test<int8_t>(16);
ok = ok && test<uint16_t>(8);
ok = ok && test<int16_t>(8);
ok = ok && test<uint32_t>(4);
ok = ok && test<int32_t>(4);
if (!ok) return -1;
printf("Success!\n");
return 0;
}
<commit_msg>Added float_8 to vector math test. Should theoretically use avx.<commit_after>#include <Halide.h>
#include <math.h>
#include <sys/time.h>
using namespace Halide;
// Make some functions for turning types into strings
template<typename A>
const char *string_of_type();
#define DECL_SOT(name) \
template<> \
const char *string_of_type<name>() {return #name;}
DECL_SOT(uint8_t);
DECL_SOT(int8_t);
DECL_SOT(uint16_t);
DECL_SOT(int16_t);
DECL_SOT(uint32_t);
DECL_SOT(int32_t);
DECL_SOT(float);
DECL_SOT(double);
double currentTime() {
timeval t;
gettimeofday(&t, NULL);
return t.tv_sec * 1000.0 + t.tv_usec / 1000.0f;
}
template<typename A>
A mod(A x, A y);
template<>
float mod(float x, float y) {
return fmod(x, y);
}
template<>
double mod(double x, double y) {
return fmod(x, y);
}
template<typename A>
A mod(A x, A y) {
return x % y;
}
template<typename A>
bool test(int vec_width) {
const int W = 6400;
const int H = 16;
Image<A> input(W+16, H+16);
for (int y = 0; y < H+16; y++) {
for (int x = 0; x < W+16; x++) {
input(x, y) = (A)(rand()*0.125 + 1.0);
}
}
Var x, y;
// Add
Func f1;
f1(x, y) = input(x, y) + input(x+1, y);
f1.vectorize(x, vec_width);
Image<A> im1 = f1.realize(W, H);
for (int y = 0; y < H; y++) {
for (int x = 0; x < W; x++) {
A correct = input(x, y) + input(x+1, y);
if (im1(x, y) != correct) {
printf("im1(%d, %d) = %f instead of %f\n", x, y, (double)(im1(x, y)), (double)(correct));
return false;
}
}
}
// Sub
Func f2;
f2(x, y) = input(x, y) - input(x+1, y);
f2.vectorize(x, vec_width);
Image<A> im2 = f2.realize(W, H);
for (int y = 0; y < H; y++) {
for (int x = 0; x < W; x++) {
A correct = input(x, y) - input(x+1, y);
if (im2(x, y) != correct) {
printf("im2(%d, %d) = %f instead of %f\n", x, y, (double)(im2(x, y)), (double)(correct));
return false;
}
}
}
// Mul
Func f3;
f3(x, y) = input(x, y) * input(x+1, y);
f3.vectorize(x, vec_width);
Image<A> im3 = f3.realize(W, H);
for (int y = 0; y < H; y++) {
for (int x = 0; x < W; x++) {
A correct = input(x, y) * input(x+1, y);
if (im3(x, y) != correct) {
printf("im3(%d, %d) = %f instead of %f\n", x, y, (double)(im3(x, y)), (double)(correct));
return false;
}
}
}
// select
Func f4;
f4(x, y) = select(input(x, y) > input(x+1, y), input(x+2, y), input(x+3, y));
f4.vectorize(x, vec_width);
Image<A> im4 = f4.realize(W, H);
for (int y = 0; y < H; y++) {
for (int x = 0; x < W; x++) {
A correct = input(x, y) > input(x+1, y) ? input(x+2, y) : input(x+3, y);
if (im4(x, y) != correct) {
printf("im4(%d, %d) = %f instead of %f\n", x, y, (double)(im4(x, y)), (double)(correct));
return false;
}
}
}
// Gather
Func f5;
Expr xCoord = clamp(cast<int>(input(x, y)), 0, W-1);
Expr yCoord = clamp(cast<int>(input(x+1, y)), 0, H-1);
f5(x, y) = input(xCoord, yCoord);
f5.vectorize(x, vec_width);
Image<A> im5 = f5.realize(W, H);
for (int y = 0; y < H; y++) {
for (int x = 0; x < W; x++) {
int xCoord = (int)(input(x, y));
if (xCoord >= W) xCoord = W-1;
if (xCoord < 0) xCoord = 0;
int yCoord = (int)(input(x+1, y));
if (yCoord >= H) yCoord = H-1;
if (yCoord < 0) yCoord = 0;
A correct = input(xCoord, yCoord);
if (im5(x, y) != correct) {
printf("im5(%d, %d) = %f instead of %f\n", x, y, (double)(im5(x, y)), (double)(correct));
return false;
}
}
}
// Scatter
Func f6;
RDom i(0, H);
// Set one entry in each row high
xCoord = clamp(cast<int>(input(2*i, i)), 0, W-1);
f6(x, y) = 0;
f6(xCoord, i) = 1;
f6.vectorize(x, vec_width);
Image<int> im6 = f6.realize(W, H);
for (int y = 0; y < H; y++) {
int xCoord = (int)(input(2*y, y));
if (xCoord >= W) xCoord = W-1;
if (xCoord < 0) xCoord = 0;
for (int x = 0; x < W; x++) {
int correct = x == xCoord ? 1 : 0;
if (im6(x, y) != correct) {
printf("im6(%d, %d) = %d instead of %d\n", x, y, im6(x, y), correct);
return false;
}
}
}
// Min/max
Func f7;
f7(x, y) = clamp(input(x, y), cast<A>(10), cast<A>(20));
f7.vectorize(x, vec_width);
Image<A> im7 = f7.realize(W, H);
for (int y = 0; y < H; y++) {
for (int x = 0; x < W; x++) {
if (im7(x, y) < (A)10 || im7(x, y) > (A)20) {
printf("im7(%d, %d) = %f instead of %f\n", x, y, (double)(im7(x, y)));
return false;
}
}
}
// Extern function call
Func f8;
f8(x, y) = pow(2.0f, cast<float>(input(x, y)));
f8.vectorize(x, vec_width);
Image<float> im8 = f8.realize(W, H);
for (int y = 0; y < H; y++) {
for (int x = 0; x < W; x++) {
float correct = powf(2.0f, (float)input(x, y));
if (im8(x, y) != correct) {
printf("im8(%d, %d) = %f instead of %f\n", x, y, im8(x, y));
return false;
}
}
}
// Div
Func f9;
f9(x, y) = input(x, y) / clamp(input(x+1, y), cast<A>(1), cast<A>(3));
f9.vectorize(x, vec_width);
Image<A> im9 = f9.realize(W, H);
for (int y = 0; y < H; y++) {
for (int x = 0; x < W; x++) {
A clamped = input(x+1, y);
if (clamped < (A)1) clamped = (A)1;
if (clamped > (A)3) clamped = (A)3;
A correct = input(x, y) / clamped;
if (im9(x, y) != correct) {
printf("im9(%d, %d) = %f instead of %f\n", x, y, (double)(im9(x, y)), (double)(correct));
return false;
}
}
}
// Interleave
Func f11;
f11(x, y) = select((x%2)==0, input(x/2, y), input(x/2, y+1));
f11.vectorize(x, vec_width);
Image<A> im11 = f11.realize(W, H);
for (int y = 0; y < H; y++) {
for (int x = 0; x < W; x++) {
A correct = ((x%2)==0) ? input(x/2, y) : input(x/2, y+1);
if (im11(x, y) != correct) {
printf("im11(%d, %d) = %f instead of %f\n", x, y, (double)(im11(x, y)), (double)(correct));
return false;
}
}
}
return true;
}
int main(int argc, char **argv) {
bool ok = true;
// Only native vector widths - llvm doesn't handle others well
ok = ok && test<float>(4);
ok = ok && test<float>(8);
ok = ok && test<double>(2);
ok = ok && test<uint8_t>(16);
ok = ok && test<int8_t>(16);
ok = ok && test<uint16_t>(8);
ok = ok && test<int16_t>(8);
ok = ok && test<uint32_t>(4);
ok = ok && test<int32_t>(4);
if (!ok) return -1;
printf("Success!\n");
return 0;
}
<|endoftext|> |
<commit_before>/**
* @file server.cc
* tests/kiwi/http
*
* Copyright (c) 2013 Hugo Peixoto.
* Distributed under the MIT License.
*/
#include "gtest/gtest.h"
#include "kiwi/http/server.h"
#include "kiwi/http/response.h"
#include <unistd.h>
#include <stdlib.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/select.h>
#include <netinet/in.h>
#include <netinet/ip.h> /* superset of previous */
#include <netinet/tcp.h>
#include <assert.h>
#include <thread>
using kiwi::http::Server;
int connect (uint16_t a_port)
{
struct sockaddr_in sin;
int sock = socket(AF_INET, SOCK_STREAM, 0);
sin.sin_addr.s_addr = inet_addr("127.0.0.1");
sin.sin_port = htons(a_port);
sin.sin_family = AF_INET;
connect(sock, (struct sockaddr*) &sin, sizeof(sin));
return sock;
}
void send (int sock, const std::string& a_text)
{
send(sock, a_text.c_str(), a_text.size(), 0);
}
std::string receive (int sock, int bytes)
{
char* buffer = new char[bytes];
int r = recv(sock, buffer, bytes, 0);
std::string ret(buffer, r);
delete[] buffer;
return ret;
}
TEST(KiwiHttpServer, ShouldConstruct)
{
Server s;
EXPECT_TRUE(s.construct(10001));
}
TEST(KiwiHttpServer, ShouldConstructTwoServersInDifferentPorts)
{
Server s1;
Server s2;
EXPECT_TRUE(s1.construct(10002));
EXPECT_TRUE(s2.construct(10003));
}
TEST(KiwiHttpServer, ShouldNotConstructTwoServersInSamePorts)
{
Server s1;
Server s2;
EXPECT_TRUE(s1.construct(10004));
EXPECT_FALSE(s2.construct(10004));
}
TEST(KiwiHttpServer, ShouldReturnTrueWhenItReceivesData)
{
kiwi::http::Request* request;
kiwi::http::Response* response;
Server server;
server.construct(10005);
std::thread sender([](){
int sock = connect(10005);
send(sock, "X");
close(sock);
});
EXPECT_TRUE(server.begin(request, response));
sender.join();
}
TEST(KiwiHttpServer, ShouldHaveNullRequestAndResponseWhenReceivingNonHTTPRequest)
{
kiwi::http::Request* request;
kiwi::http::Response* response;
Server server;
server.construct(10006);
std::thread sender([](){
int sock = connect(10006);
send(sock, "X");
close(sock);
});
server.begin(request, response);
EXPECT_TRUE(nullptr == request);
EXPECT_TRUE(nullptr == response);
sender.join();
}
TEST(KiwiHttpServer, ShouldHaveRequestAndResponseWhenReceivingFullHTTPRequest)
{
kiwi::http::Request* request;
kiwi::http::Response* response;
Server server;
server.construct(10007);
std::thread sender([](){
int sock = connect(10007);
send(sock, "GET / HTTP/1.1\r\nHost: example.com\r\n\r\n\r\n");
close(sock);
});
server.begin(request, response); // accept connection
server.begin(request, response); // read string
server.begin(request, response); // pop it
EXPECT_TRUE(nullptr != request);
EXPECT_TRUE(nullptr != response);
sender.join();
}
TEST(KiwiHttpServer, ShouldSendHTTPResponse)
{
kiwi::http::Request* request;
kiwi::http::Response* response;
Server server;
server.construct(10008);
std::string body;
std::thread sender([&body](){
int sock = connect(10008);
send(sock, "GET / HTTP/1.1\r\nHost: example.com\r\n\r\n");
body = receive(sock, 1024);
close(sock);
});
while (server.begin(request, response)) {
if (request && response) {
response->start_body();
response->body_chunk("Hello", 5);
response->finish_body();
server.end(request, response);
break;
}
}
sender.join();
EXPECT_EQ(
"HTTP/1.1 200 OK\r\n"
"Content-Type: text/html; charset=UTF-8\r\n"
"Transfer-Encoding: chunked\r\n"
"\r\n"
"5\r\n"
"Hello\r\n"
"0\r\n\r\n",
body);
}
TEST(KiwiHttpServer, ShouldHandleMoreThanOneClient)
{
kiwi::http::Request* request;
kiwi::http::Response* response;
Server server;
server.construct(10009);
std::string body1;
std::string body2;
std::thread sender1([&body1](){
int sock = connect(10009);
send(sock, "GET / HTTP/1.1\r\nHost: example.com\r\n\r\n");
body1 = receive(sock, 1024);
close(sock);
});
std::thread sender2([&body2](){
int sock = connect(10009);
send(sock, "GET / HTTP/1.1\r\nHost: example.com\r\n\r\n");
body2 = receive(sock, 1024);
close(sock);
});
for (int i = 0; server.begin(request, response);) {
if (request && response) {
response->start_body();
response->body_chunk("Hello", 5);
response->finish_body();
server.end(request, response);
++i;
if (i == 2) break;
}
}
sender1.join();
sender2.join();
EXPECT_EQ(
"HTTP/1.1 200 OK\r\n"
"Content-Type: text/html; charset=UTF-8\r\n"
"Transfer-Encoding: chunked\r\n"
"\r\n"
"5\r\n"
"Hello\r\n"
"0\r\n\r\n",
body1);
EXPECT_EQ(body1, body2);
}
<commit_msg>Fixes the server tests<commit_after>/**
* @file server.cc
* tests/kiwi/http
*
* Copyright (c) 2013 Hugo Peixoto.
* Distributed under the MIT License.
*/
#include "gtest/gtest.h"
#include "kiwi/http/server.h"
#include "kiwi/http/response.h"
#include <unistd.h>
#include <stdlib.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/select.h>
#include <netinet/in.h>
#include <netinet/ip.h> /* superset of previous */
#include <netinet/tcp.h>
#include <assert.h>
#include <thread>
using kiwi::http::Server;
int connect (uint16_t a_port)
{
struct sockaddr_in sin;
int sock = socket(AF_INET, SOCK_STREAM, 0);
sin.sin_addr.s_addr = inet_addr("127.0.0.1");
sin.sin_port = htons(a_port);
sin.sin_family = AF_INET;
connect(sock, (struct sockaddr*) &sin, sizeof(sin));
return sock;
}
void send (int sock, const std::string& a_text)
{
send(sock, a_text.c_str(), a_text.size(), 0);
}
std::string receive (int sock)
{
std::string body;
char buffer[1024];
for (int r = 0; (r = recv(sock, buffer, 1024, 0)); body += std::string(buffer, r));
return body;
}
TEST(KiwiHttpServer, ShouldConstruct)
{
Server s;
EXPECT_TRUE(s.construct(10001));
}
TEST(KiwiHttpServer, ShouldConstructTwoServersInDifferentPorts)
{
Server s1;
Server s2;
EXPECT_TRUE(s1.construct(10002));
EXPECT_TRUE(s2.construct(10003));
}
TEST(KiwiHttpServer, ShouldNotConstructTwoServersInSamePorts)
{
Server s1;
Server s2;
EXPECT_TRUE(s1.construct(10004));
EXPECT_FALSE(s2.construct(10004));
}
TEST(KiwiHttpServer, ShouldReturnTrueWhenItReceivesData)
{
kiwi::http::Request* request;
kiwi::http::Response* response;
Server server;
server.construct(10005);
std::thread sender([](){
int sock = connect(10005);
send(sock, "X");
close(sock);
});
EXPECT_TRUE(server.begin(request, response));
sender.join();
}
TEST(KiwiHttpServer, ShouldHaveNullRequestAndResponseWhenReceivingNonHTTPRequest)
{
kiwi::http::Request* request;
kiwi::http::Response* response;
Server server;
server.construct(10006);
std::thread sender([](){
int sock = connect(10006);
send(sock, "X");
close(sock);
});
server.begin(request, response);
EXPECT_TRUE(nullptr == request);
EXPECT_TRUE(nullptr == response);
sender.join();
}
TEST(KiwiHttpServer, ShouldHaveRequestAndResponseWhenReceivingFullHTTPRequest)
{
kiwi::http::Request* request;
kiwi::http::Response* response;
Server server;
server.construct(10007);
std::thread sender([](){
int sock = connect(10007);
send(sock, "GET / HTTP/1.1\r\nHost: example.com\r\n\r\n\r\n");
close(sock);
});
server.begin(request, response); // accept connection
server.begin(request, response); // read string
server.begin(request, response); // pop it
EXPECT_TRUE(nullptr != request);
EXPECT_TRUE(nullptr != response);
sender.join();
}
TEST(KiwiHttpServer, ShouldSendHTTPResponse)
{
kiwi::http::Request* request;
kiwi::http::Response* response;
Server server;
server.construct(10008);
std::string body;
std::thread sender([&body](){
int sock = connect(10008);
send(sock, "GET / HTTP/1.1\r\nHost: example.com\r\n\r\n");
body = receive(sock);
close(sock);
});
while (server.begin(request, response)) {
if (request && response) {
response->start_body();
response->body_chunk("Hello", 5);
response->finish_body();
server.end(request, response);
break;
}
}
sender.join();
EXPECT_EQ(
"HTTP/1.1 200 OK\r\n"
"Content-Type: text/html; charset=UTF-8\r\n"
"Transfer-Encoding: chunked\r\n"
"\r\n"
"5\r\n"
"Hello\r\n"
"0\r\n\r\n",
body);
}
TEST(KiwiHttpServer, ShouldHandleMoreThanOneClient)
{
kiwi::http::Request* request;
kiwi::http::Response* response;
Server server;
server.construct(10009);
std::string body1;
std::string body2;
std::thread sender1([&body1](){
int sock = connect(10009);
send(sock, "GET / HTTP/1.1\r\nHost: example.com\r\n\r\n");
body1 = receive(sock);
close(sock);
});
std::thread sender2([&body2](){
int sock = connect(10009);
send(sock, "GET / HTTP/1.1\r\nHost: example.com\r\n\r\n");
body2 = receive(sock);
close(sock);
});
for (int i = 0; server.begin(request, response);) {
if (request && response) {
response->start_body();
response->body_chunk("Hello", 5);
response->finish_body();
server.end(request, response);
++i;
if (i == 2) break;
}
}
sender1.join();
sender2.join();
EXPECT_EQ(
"HTTP/1.1 200 OK\r\n"
"Content-Type: text/html; charset=UTF-8\r\n"
"Transfer-Encoding: chunked\r\n"
"\r\n"
"5\r\n"
"Hello\r\n"
"0\r\n\r\n",
body1);
EXPECT_EQ(body1, body2);
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2013-2016 Alexander Saprykin <xelfium@gmail.com>
*
* 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.
*/
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE psemaphore_test
#include "plib.h"
#include <boost/test/unit_test.hpp>
static pint semaphore_test_val = 10;
static void * semaphore_test_thread (void *)
{
PSemaphore *sem;
pint i;
sem = p_semaphore_new ("p_semaphore_test_object", 1, P_SEM_ACCESS_OPEN);
if (sem == NULL)
p_uthread_exit (1);
for (i = 0; i < 1000; ++i) {
if (!p_semaphore_acquire (sem))
p_uthread_exit (1);
if (semaphore_test_val == 10)
--semaphore_test_val;
else {
p_uthread_sleep (1);
++semaphore_test_val;
}
if (!p_semaphore_release (sem))
p_uthread_exit (1);
}
p_semaphore_free (sem);
p_uthread_exit (0);
}
BOOST_AUTO_TEST_SUITE (BOOST_TEST_MODULE)
BOOST_AUTO_TEST_CASE (psemaphore_general_test)
{
PSemaphore *sem = NULL;
pint i;
p_lib_init ();
BOOST_REQUIRE (p_semaphore_acquire (sem) == FALSE);
BOOST_REQUIRE (p_semaphore_acquire (sem) == FALSE);
p_semaphore_take_ownership (sem);
sem = p_semaphore_new ("p_semaphore_test_object", 10, P_SEM_ACCESS_CREATE);
BOOST_REQUIRE (sem != NULL);
p_semaphore_take_ownership (sem);
p_semaphore_free (sem);
sem = p_semaphore_new ("p_semaphore_test_object", 10, P_SEM_ACCESS_CREATE);
BOOST_REQUIRE (sem != NULL);
for (i = 0; i < 10; ++i)
BOOST_CHECK (p_semaphore_acquire (sem));
for (i = 0; i < 10; ++i)
BOOST_CHECK (p_semaphore_release (sem));
for (i = 0; i < 1000; ++i) {
BOOST_CHECK (p_semaphore_acquire (sem));
BOOST_CHECK (p_semaphore_release (sem));
}
p_semaphore_free (sem);
p_lib_shutdown ();
}
BOOST_AUTO_TEST_CASE (psemaphore_thread_test)
{
PUThread *thr1, *thr2;
PSemaphore *sem = NULL;
p_lib_init ();
sem = p_semaphore_new ("p_semaphore_test_object", 10, P_SEM_ACCESS_CREATE);
BOOST_REQUIRE (sem != NULL);
p_semaphore_take_ownership (sem);
p_semaphore_free (sem);
thr1 = p_uthread_create ((PUThreadFunc) semaphore_test_thread, NULL, true);
BOOST_REQUIRE (thr1 != NULL);
thr2 = p_uthread_create ((PUThreadFunc) semaphore_test_thread, NULL, true);
BOOST_REQUIRE (thr2 != NULL);
BOOST_CHECK (p_uthread_join (thr1) == 0);
BOOST_CHECK (p_uthread_join (thr2) == 0);
BOOST_REQUIRE (semaphore_test_val == 10);
BOOST_REQUIRE (p_semaphore_acquire (sem) == FALSE);
BOOST_REQUIRE (p_semaphore_release (sem) == FALSE);
p_semaphore_free (sem);
p_semaphore_take_ownership (sem);
sem = p_semaphore_new ("p_semaphore_test_object", 1, P_SEM_ACCESS_OPEN);
BOOST_REQUIRE (sem != NULL);
p_semaphore_take_ownership (sem);
p_semaphore_free (sem);
p_uthread_free (thr1);
p_uthread_free (thr2);
p_lib_shutdown ();
}
BOOST_AUTO_TEST_SUITE_END()
<commit_msg>tests: Fix PSemaphore test<commit_after>/*
* Copyright (C) 2013-2016 Alexander Saprykin <xelfium@gmail.com>
*
* 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.
*/
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE psemaphore_test
#include "plib.h"
#include <boost/test/unit_test.hpp>
static pint semaphore_test_val = 10;
static void * semaphore_test_thread (void *)
{
PSemaphore *sem;
pint i;
sem = p_semaphore_new ("p_semaphore_test_object", 1, P_SEM_ACCESS_OPEN);
if (sem == NULL)
p_uthread_exit (1);
for (i = 0; i < 1000; ++i) {
if (!p_semaphore_acquire (sem))
p_uthread_exit (1);
if (semaphore_test_val == 10)
--semaphore_test_val;
else {
p_uthread_sleep (1);
++semaphore_test_val;
}
if (!p_semaphore_release (sem))
p_uthread_exit (1);
}
p_semaphore_free (sem);
p_uthread_exit (0);
}
BOOST_AUTO_TEST_SUITE (BOOST_TEST_MODULE)
BOOST_AUTO_TEST_CASE (psemaphore_general_test)
{
PSemaphore *sem = NULL;
pint i;
p_lib_init ();
BOOST_REQUIRE (p_semaphore_acquire (sem) == FALSE);
BOOST_REQUIRE (p_semaphore_acquire (sem) == FALSE);
p_semaphore_take_ownership (sem);
sem = p_semaphore_new ("p_semaphore_test_object", 10, P_SEM_ACCESS_CREATE);
BOOST_REQUIRE (sem != NULL);
p_semaphore_take_ownership (sem);
p_semaphore_free (sem);
sem = p_semaphore_new ("p_semaphore_test_object", 10, P_SEM_ACCESS_CREATE);
BOOST_REQUIRE (sem != NULL);
for (i = 0; i < 10; ++i)
BOOST_CHECK (p_semaphore_acquire (sem));
for (i = 0; i < 10; ++i)
BOOST_CHECK (p_semaphore_release (sem));
for (i = 0; i < 1000; ++i) {
BOOST_CHECK (p_semaphore_acquire (sem));
BOOST_CHECK (p_semaphore_release (sem));
}
p_semaphore_free (sem);
p_lib_shutdown ();
}
BOOST_AUTO_TEST_CASE (psemaphore_thread_test)
{
PUThread *thr1, *thr2;
PSemaphore *sem = NULL;
p_lib_init ();
sem = p_semaphore_new ("p_semaphore_test_object", 10, P_SEM_ACCESS_CREATE);
BOOST_REQUIRE (sem != NULL);
p_semaphore_take_ownership (sem);
p_semaphore_free (sem);
sem = NULL;
thr1 = p_uthread_create ((PUThreadFunc) semaphore_test_thread, NULL, true);
BOOST_REQUIRE (thr1 != NULL);
thr2 = p_uthread_create ((PUThreadFunc) semaphore_test_thread, NULL, true);
BOOST_REQUIRE (thr2 != NULL);
BOOST_CHECK (p_uthread_join (thr1) == 0);
BOOST_CHECK (p_uthread_join (thr2) == 0);
BOOST_REQUIRE (semaphore_test_val == 10);
BOOST_REQUIRE (p_semaphore_acquire (sem) == FALSE);
BOOST_REQUIRE (p_semaphore_release (sem) == FALSE);
p_semaphore_free (sem);
p_semaphore_take_ownership (sem);
sem = p_semaphore_new ("p_semaphore_test_object", 1, P_SEM_ACCESS_OPEN);
BOOST_REQUIRE (sem != NULL);
p_semaphore_take_ownership (sem);
p_semaphore_free (sem);
p_uthread_free (thr1);
p_uthread_free (thr2);
p_lib_shutdown ();
}
BOOST_AUTO_TEST_SUITE_END()
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: wrapfield.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2005-09-08 19:33:40 $
*
* 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 SVX_WRAPFIELD_HXX
#define SVX_WRAPFIELD_HXX
#ifndef _SV_FIELD_HXX
#include <vcl/field.hxx>
#endif
#ifndef INCLUDED_SVXDLLAPI_H
#include "svx/svxdllapi.h"
#endif
namespace svx {
// ============================================================================
/** A numeric spin field that wraps around the value on limits.
@descr Note: Use type "NumericField" in resources. */
class SVX_DLLPUBLIC WrapField : public NumericField
{
public:
explicit WrapField( Window* pParent, WinBits nWinStyle );
explicit WrapField( Window* pParent, const ResId& rResId );
protected:
/** Up event with wrap-around functionality. */
virtual void Up();
/** Down event with wrap-around functionality. */
virtual void Down();
};
// ============================================================================
} // namespace svx
#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.4.1256); FILE MERGED 2008/04/01 15:49:26 thb 1.4.1256.3: #i85898# Stripping all external header guards 2008/04/01 12:46:29 thb 1.4.1256.2: #i85898# Stripping all external header guards 2008/03/31 14:18:01 rt 1.4.1256.1: #i87441# Change license header to LPGL v3.<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: wrapfield.hxx,v $
* $Revision: 1.5 $
*
* 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 SVX_WRAPFIELD_HXX
#define SVX_WRAPFIELD_HXX
#include <vcl/field.hxx>
#include "svx/svxdllapi.h"
namespace svx {
// ============================================================================
/** A numeric spin field that wraps around the value on limits.
@descr Note: Use type "NumericField" in resources. */
class SVX_DLLPUBLIC WrapField : public NumericField
{
public:
explicit WrapField( Window* pParent, WinBits nWinStyle );
explicit WrapField( Window* pParent, const ResId& rResId );
protected:
/** Up event with wrap-around functionality. */
virtual void Up();
/** Down event with wrap-around functionality. */
virtual void Down();
};
// ============================================================================
} // namespace svx
#endif
<|endoftext|> |
<commit_before>#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <fcntl.h>
bool socketError = false;
bool socketBlocking = false;
int DDV_OpenUnix(std::string adres, bool nonblock = false){
int s = socket(PF_UNIX, SOCK_STREAM, 0);
sockaddr_un addr;
addr.sun_family = AF_UNIX;
strncpy(addr.sun_path, adres.c_str(), adres.size()+1);
int r = connect(s, (sockaddr*)&addr, sizeof(addr));
if (r == 0){
if (nonblock){
int flags = fcntl(s, F_GETFL, 0);
flags |= O_NONBLOCK;
fcntl(s, F_SETFL, flags);
}
return s;
}else{
close(s);
return 0;
}
}
int DDV_Listen(int port){
int s = socket(AF_INET, SOCK_STREAM, 0);
int on = 1;
setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(port);//port 8888
inet_pton(AF_INET, "0.0.0.0", &addr.sin_addr);//listen on all interfaces
int ret = bind(s, (sockaddr*)&addr, sizeof(addr));//bind to all interfaces, chosen port
if (ret == 0){
ret = listen(s, 100);//start listening, backlog of 100 allowed
if (ret == 0){
return s;
}else{
printf("Listen failed! Error: %s\n", strerror(errno));
close(s);
return 0;
}
}else{
printf("Binding failed! Error: %s\n", strerror(errno));
close(s);
return 0;
}
}
int DDV_Accept(int sock, bool nonblock = false){
int r = accept(sock, 0, 0);
if ((r > 0) && nonblock){
int flags = fcntl(r, F_GETFL, 0);
flags |= O_NONBLOCK;
fcntl(r, F_SETFL, flags);
}
return r;
}
bool DDV_write(void * buffer, int todo, int sock){
int sofar = 0;
socketBlocking = false;
while (sofar != todo){
int r = send(sock, (char*)buffer + sofar, todo-sofar, 0);
if (r <= 0){
switch (errno){
case EWOULDBLOCK: socketBlocking = true; break;
default:
socketError = true;
printf("Could not write! %s\n", strerror(errno));
return false;
break;
}
}
sofar += r;
}
return true;
}
bool DDV_ready(int sock){
char tmp;
int preflags = fcntl(sock, F_GETFL, 0);
int postflags = preflags | O_NONBLOCK;
fcntl(sock, F_SETFL, postflags);
int r = recv(sock, &tmp, 1, MSG_PEEK);
fcntl(sock, F_SETFL, preflags);
return (r == 1);
}
int DDV_readycount(int sock){
static tmp[1048576];
int preflags = fcntl(sock, F_GETFL, 0);
int postflags = preflags | O_NONBLOCK;
fcntl(sock, F_SETFL, postflags);
int r = recv(sock, tmp, 1048576, MSG_PEEK);
fcntl(sock, F_SETFL, preflags);
if (r > 0){
return r;
}else{
return 0;
}
}
bool DDV_read(void * buffer, int todo, int sock){
int sofar = 0;
socketBlocking = false;
while (sofar != todo){
int r = recv(sock, (char*)buffer + sofar, todo-sofar, 0);
if (r <= 0){
switch (errno){
case EWOULDBLOCK: socketBlocking = true; break;
default:
socketError = true;
printf("Could not read! %s\n", strerror(errno));
return false;
break;
}
}
sofar += r;
}
return true;
}
bool DDV_read(void * buffer, int width, int count, int sock){return DDV_read(buffer, width*count, sock);}
bool DDV_write(void * buffer, int width, int count, int sock){return DDV_write(buffer, width*count, sock);}
int DDV_iwrite(void * buffer, int todo, int sock){
int r = send(sock, buffer, todo, 0);
if (r < 0){
switch (errno){
case EWOULDBLOCK: break;
default:
socketError = true;
printf("Could not write! %s\n", strerror(errno));
return false;
break;
}
}
return r;
}
int DDV_iread(void * buffer, int todo, int sock){
int r = recv(sock, buffer, todo, 0);
if (r < 0){
switch (errno){
case EWOULDBLOCK: break;
default:
socketError = true;
printf("Could not read! %s\n", strerror(errno));
return false;
break;
}
}
return r;
}
<commit_msg>Gadver<commit_after>#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <fcntl.h>
bool socketError = false;
bool socketBlocking = false;
int DDV_OpenUnix(std::string adres, bool nonblock = false){
int s = socket(PF_UNIX, SOCK_STREAM, 0);
sockaddr_un addr;
addr.sun_family = AF_UNIX;
strncpy(addr.sun_path, adres.c_str(), adres.size()+1);
int r = connect(s, (sockaddr*)&addr, sizeof(addr));
if (r == 0){
if (nonblock){
int flags = fcntl(s, F_GETFL, 0);
flags |= O_NONBLOCK;
fcntl(s, F_SETFL, flags);
}
return s;
}else{
close(s);
return 0;
}
}
int DDV_Listen(int port){
int s = socket(AF_INET, SOCK_STREAM, 0);
int on = 1;
setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(port);//port 8888
inet_pton(AF_INET, "0.0.0.0", &addr.sin_addr);//listen on all interfaces
int ret = bind(s, (sockaddr*)&addr, sizeof(addr));//bind to all interfaces, chosen port
if (ret == 0){
ret = listen(s, 100);//start listening, backlog of 100 allowed
if (ret == 0){
return s;
}else{
printf("Listen failed! Error: %s\n", strerror(errno));
close(s);
return 0;
}
}else{
printf("Binding failed! Error: %s\n", strerror(errno));
close(s);
return 0;
}
}
int DDV_Accept(int sock, bool nonblock = false){
int r = accept(sock, 0, 0);
if ((r > 0) && nonblock){
int flags = fcntl(r, F_GETFL, 0);
flags |= O_NONBLOCK;
fcntl(r, F_SETFL, flags);
}
return r;
}
bool DDV_write(void * buffer, int todo, int sock){
int sofar = 0;
socketBlocking = false;
while (sofar != todo){
int r = send(sock, (char*)buffer + sofar, todo-sofar, 0);
if (r <= 0){
switch (errno){
case EWOULDBLOCK: socketBlocking = true; break;
default:
socketError = true;
printf("Could not write! %s\n", strerror(errno));
return false;
break;
}
}
sofar += r;
}
return true;
}
bool DDV_ready(int sock){
char tmp;
int preflags = fcntl(sock, F_GETFL, 0);
int postflags = preflags | O_NONBLOCK;
fcntl(sock, F_SETFL, postflags);
int r = recv(sock, &tmp, 1, MSG_PEEK);
fcntl(sock, F_SETFL, preflags);
return (r == 1);
}
int DDV_readycount(int sock){
static char tmp[1048576];
int preflags = fcntl(sock, F_GETFL, 0);
int postflags = preflags | O_NONBLOCK;
fcntl(sock, F_SETFL, postflags);
int r = recv(sock, tmp, 1048576, MSG_PEEK);
fcntl(sock, F_SETFL, preflags);
if (r > 0){
return r;
}else{
return 0;
}
}
bool DDV_read(void * buffer, int todo, int sock){
int sofar = 0;
socketBlocking = false;
while (sofar != todo){
int r = recv(sock, (char*)buffer + sofar, todo-sofar, 0);
if (r <= 0){
switch (errno){
case EWOULDBLOCK: socketBlocking = true; break;
default:
socketError = true;
printf("Could not read! %s\n", strerror(errno));
return false;
break;
}
}
sofar += r;
}
return true;
}
bool DDV_read(void * buffer, int width, int count, int sock){return DDV_read(buffer, width*count, sock);}
bool DDV_write(void * buffer, int width, int count, int sock){return DDV_write(buffer, width*count, sock);}
int DDV_iwrite(void * buffer, int todo, int sock){
int r = send(sock, buffer, todo, 0);
if (r < 0){
switch (errno){
case EWOULDBLOCK: break;
default:
socketError = true;
printf("Could not write! %s\n", strerror(errno));
return false;
break;
}
}
return r;
}
int DDV_iread(void * buffer, int todo, int sock){
int r = recv(sock, buffer, todo, 0);
if (r < 0){
switch (errno){
case EWOULDBLOCK: break;
default:
socketError = true;
printf("Could not read! %s\n", strerror(errno));
return false;
break;
}
}
return r;
}
<|endoftext|> |
<commit_before>/*
* Copyright 2018 NXP.
*
* 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 NXP Semiconductor 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 <array>
#include <string>
#include "sdps.h"
#include "config.h"
#include "hidreport.h"
#include "liberror.h"
#include "libcomm.h"
#include "buffer.h"
#include "sdp.h"
#include "rominfo.h"
static constexpr std::array<ROM_INFO, 15> g_RomInfo
{
ROM_INFO{ "MX6Q", 0x00910000, ROM_INFO_HID | ROM_INFO_HID_MX6 },
ROM_INFO{ "MX6D", 0x00910000, ROM_INFO_HID | ROM_INFO_HID_MX6 },
ROM_INFO{ "MX6SL", 0x00910000, ROM_INFO_HID | ROM_INFO_HID_MX6 },
ROM_INFO{ "MX7D", 0x00911000, ROM_INFO_HID | ROM_INFO_HID_MX6 | ROM_INFO_HID_SKIP_DCD },
ROM_INFO{ "MX6UL", 0x00910000, ROM_INFO_HID | ROM_INFO_HID_MX6 | ROM_INFO_HID_SKIP_DCD },
ROM_INFO{ "MX6ULL", 0x00910000, ROM_INFO_HID | ROM_INFO_HID_MX6 | ROM_INFO_HID_SKIP_DCD },
ROM_INFO{ "MX6SLL", 0x00910000, ROM_INFO_HID | ROM_INFO_HID_MX6 | ROM_INFO_HID_SKIP_DCD },
ROM_INFO{ "MX8MQ", 0x00910000, ROM_INFO_HID | ROM_INFO_HID_MX6 | ROM_INFO_HID_SKIP_DCD },
ROM_INFO{ "MX7ULP", 0x2f018000, ROM_INFO_HID | ROM_INFO_HID_MX6 | ROM_INFO_HID_SKIP_DCD },
ROM_INFO{ "MXRT106X", 0x1000, ROM_INFO_HID | ROM_INFO_HID_MX6 | ROM_INFO_HID_SKIP_DCD },
ROM_INFO{ "MX8QXP", 0x0, ROM_INFO_HID | ROM_INFO_HID_NO_CMD | ROM_INFO_HID_UID_STRING },
ROM_INFO{ "MX28", 0x0, ROM_INFO_HID},
ROM_INFO{ "MX815", 0x0, ROM_INFO_HID | ROM_INFO_HID_NO_CMD | ROM_INFO_HID_UID_STRING | ROM_INFO_HID_EP1 | ROM_INFO_HID_PACK_SIZE_1020 },
ROM_INFO{ "SPL", 0x0, ROM_INFO_HID | ROM_INFO_HID_MX6 | ROM_INFO_SPL_JUMP | ROM_INFO_HID_SDP_NO_MAX_PER_TRANS},
ROM_INFO{ "SPL1", 0x0, ROM_INFO_HID | ROM_INFO_HID_MX6 | ROM_INFO_SPL_JUMP | ROM_INFO_HID_SDP_NO_MAX_PER_TRANS | ROM_INFO_AUTO_SCAN_UBOOT_POS},
};
const ROM_INFO * search_rom_info(const char *s)
{
string s1 = s;
for (size_t i = 0; i < sizeof(g_RomInfo) / sizeof(ROM_INFO); i++)
{
string s2;
s2 = g_RomInfo[i].m_name;
if (s1 == s2)
return &g_RomInfo[i];
}
return 0;
}
const ROM_INFO * search_rom_info(const ConfigItem *item)
{
if (item == nullptr)
return nullptr;
const ROM_INFO *p = search_rom_info(item->m_chip.c_str());
if (p)
return p;
return search_rom_info(item->m_compatible.c_str());
}
#define IV_MAX_LEN 32
#define HASH_MAX_LEN 64
#define CONTAINER_HDR_ALIGNMENT 0x400
#define CONTAINER_TAG 0x87
#pragma pack (1)
struct rom_container {
uint8_t version;
uint8_t length_l;
uint8_t length_m;
uint8_t tag;
uint32_t flags;
uint16_t sw_version;
uint8_t fuse_version;
uint8_t num_images;
uint16_t sig_blk_offset;
uint16_t reserved;
};
struct rom_bootimg {
uint32_t offset;
uint32_t size;
uint64_t destination;
uint64_t entry;
uint32_t flags;
uint32_t meta;
uint8_t hash[HASH_MAX_LEN];
uint8_t iv[IV_MAX_LEN];
};
#define IMG_V2X 0x0B
#pragma pack ()
size_t GetContainerActualSize(shared_ptr<FileBuffer> p, size_t offset)
{
struct rom_container *hdr;
int cindex = 1;
hdr = (struct rom_container *)(p->data() + offset + CONTAINER_HDR_ALIGNMENT);
if (hdr->tag != CONTAINER_TAG)
return p->size() - offset;
struct rom_bootimg *image;
/* Check if include V2X container*/
image = (struct rom_bootimg *)(p->data() + offset + CONTAINER_HDR_ALIGNMENT
+ sizeof(struct rom_container));
if ((image->flags & 0xF) == IMG_V2X)
{
cindex = 2;
hdr = (struct rom_container *)(p->data() + offset + cindex * CONTAINER_HDR_ALIGNMENT);
if (hdr->tag != CONTAINER_TAG)
return p->size() - offset;
}
image = (struct rom_bootimg *)(p->data() + offset + cindex * CONTAINER_HDR_ALIGNMENT
+ sizeof(struct rom_container)
+ sizeof(struct rom_bootimg) * (hdr->num_images - 1));
uint32_t sz = image->size + image->offset + cindex * CONTAINER_HDR_ALIGNMENT;
sz = round_up(sz, (uint32_t)CONTAINER_HDR_ALIGNMENT);
if (sz > (p->size() - offset))
return p->size() - offset;
hdr = (struct rom_container *)(p->data() + offset + sz);
return sz;
}
static uint32_t FlashHeaderMagic[] =
{
0xc0ffee01,
0x42464346,
0
};
bool CheckHeader(uint32_t *p)
{
int i = 0;
while(FlashHeaderMagic[i])
{
if (*p == FlashHeaderMagic[i])
return true;
i++;
}
return false;
}
size_t GetFlashHeaderSize(shared_ptr<FileBuffer> p, size_t offset)
{
if (p->size() < offset)
return 0;
if (CheckHeader((uint32_t*)(p->data() + offset)))
return 0x1000;
if (p->size() < offset + 0x400)
return 0;
if (CheckHeader((uint32_t*)(p->data() + offset + 0x400)))
return 0x1000;
if (p->size() < offset + 0x1fc)
return 0;
if (CheckHeader((uint32_t*)(p->data() + offset + 0x1fc)))
return 0x1000;
if (p->size() < offset + 0x5fc)
return 0;
if (CheckHeader((uint32_t*)(p->data() + offset + 0x5fc)))
return 0x1000;
return 0;
}
<commit_msg>Modernize search_rom_info(const char *s)<commit_after>/*
* Copyright 2018 NXP.
*
* 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 NXP Semiconductor 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 <array>
#include <string>
#include "sdps.h"
#include "config.h"
#include "hidreport.h"
#include "liberror.h"
#include "libcomm.h"
#include "buffer.h"
#include "sdp.h"
#include "rominfo.h"
static constexpr std::array<ROM_INFO, 15> g_RomInfo
{
ROM_INFO{ "MX6Q", 0x00910000, ROM_INFO_HID | ROM_INFO_HID_MX6 },
ROM_INFO{ "MX6D", 0x00910000, ROM_INFO_HID | ROM_INFO_HID_MX6 },
ROM_INFO{ "MX6SL", 0x00910000, ROM_INFO_HID | ROM_INFO_HID_MX6 },
ROM_INFO{ "MX7D", 0x00911000, ROM_INFO_HID | ROM_INFO_HID_MX6 | ROM_INFO_HID_SKIP_DCD },
ROM_INFO{ "MX6UL", 0x00910000, ROM_INFO_HID | ROM_INFO_HID_MX6 | ROM_INFO_HID_SKIP_DCD },
ROM_INFO{ "MX6ULL", 0x00910000, ROM_INFO_HID | ROM_INFO_HID_MX6 | ROM_INFO_HID_SKIP_DCD },
ROM_INFO{ "MX6SLL", 0x00910000, ROM_INFO_HID | ROM_INFO_HID_MX6 | ROM_INFO_HID_SKIP_DCD },
ROM_INFO{ "MX8MQ", 0x00910000, ROM_INFO_HID | ROM_INFO_HID_MX6 | ROM_INFO_HID_SKIP_DCD },
ROM_INFO{ "MX7ULP", 0x2f018000, ROM_INFO_HID | ROM_INFO_HID_MX6 | ROM_INFO_HID_SKIP_DCD },
ROM_INFO{ "MXRT106X", 0x1000, ROM_INFO_HID | ROM_INFO_HID_MX6 | ROM_INFO_HID_SKIP_DCD },
ROM_INFO{ "MX8QXP", 0x0, ROM_INFO_HID | ROM_INFO_HID_NO_CMD | ROM_INFO_HID_UID_STRING },
ROM_INFO{ "MX28", 0x0, ROM_INFO_HID},
ROM_INFO{ "MX815", 0x0, ROM_INFO_HID | ROM_INFO_HID_NO_CMD | ROM_INFO_HID_UID_STRING | ROM_INFO_HID_EP1 | ROM_INFO_HID_PACK_SIZE_1020 },
ROM_INFO{ "SPL", 0x0, ROM_INFO_HID | ROM_INFO_HID_MX6 | ROM_INFO_SPL_JUMP | ROM_INFO_HID_SDP_NO_MAX_PER_TRANS},
ROM_INFO{ "SPL1", 0x0, ROM_INFO_HID | ROM_INFO_HID_MX6 | ROM_INFO_SPL_JUMP | ROM_INFO_HID_SDP_NO_MAX_PER_TRANS | ROM_INFO_AUTO_SCAN_UBOOT_POS},
};
const ROM_INFO * search_rom_info(const char *s)
{
if (s == nullptr) {
return nullptr;
}
const string s1{s};
for (const auto &rom_info : g_RomInfo) {
if (s1 == rom_info.m_name)
{
return &rom_info;
}
}
return nullptr;
}
const ROM_INFO * search_rom_info(const ConfigItem *item)
{
if (item == nullptr)
return nullptr;
const ROM_INFO *p = search_rom_info(item->m_chip.c_str());
if (p)
return p;
return search_rom_info(item->m_compatible.c_str());
}
#define IV_MAX_LEN 32
#define HASH_MAX_LEN 64
#define CONTAINER_HDR_ALIGNMENT 0x400
#define CONTAINER_TAG 0x87
#pragma pack (1)
struct rom_container {
uint8_t version;
uint8_t length_l;
uint8_t length_m;
uint8_t tag;
uint32_t flags;
uint16_t sw_version;
uint8_t fuse_version;
uint8_t num_images;
uint16_t sig_blk_offset;
uint16_t reserved;
};
struct rom_bootimg {
uint32_t offset;
uint32_t size;
uint64_t destination;
uint64_t entry;
uint32_t flags;
uint32_t meta;
uint8_t hash[HASH_MAX_LEN];
uint8_t iv[IV_MAX_LEN];
};
#define IMG_V2X 0x0B
#pragma pack ()
size_t GetContainerActualSize(shared_ptr<FileBuffer> p, size_t offset)
{
struct rom_container *hdr;
int cindex = 1;
hdr = (struct rom_container *)(p->data() + offset + CONTAINER_HDR_ALIGNMENT);
if (hdr->tag != CONTAINER_TAG)
return p->size() - offset;
struct rom_bootimg *image;
/* Check if include V2X container*/
image = (struct rom_bootimg *)(p->data() + offset + CONTAINER_HDR_ALIGNMENT
+ sizeof(struct rom_container));
if ((image->flags & 0xF) == IMG_V2X)
{
cindex = 2;
hdr = (struct rom_container *)(p->data() + offset + cindex * CONTAINER_HDR_ALIGNMENT);
if (hdr->tag != CONTAINER_TAG)
return p->size() - offset;
}
image = (struct rom_bootimg *)(p->data() + offset + cindex * CONTAINER_HDR_ALIGNMENT
+ sizeof(struct rom_container)
+ sizeof(struct rom_bootimg) * (hdr->num_images - 1));
uint32_t sz = image->size + image->offset + cindex * CONTAINER_HDR_ALIGNMENT;
sz = round_up(sz, (uint32_t)CONTAINER_HDR_ALIGNMENT);
if (sz > (p->size() - offset))
return p->size() - offset;
hdr = (struct rom_container *)(p->data() + offset + sz);
return sz;
}
static uint32_t FlashHeaderMagic[] =
{
0xc0ffee01,
0x42464346,
0
};
bool CheckHeader(uint32_t *p)
{
int i = 0;
while(FlashHeaderMagic[i])
{
if (*p == FlashHeaderMagic[i])
return true;
i++;
}
return false;
}
size_t GetFlashHeaderSize(shared_ptr<FileBuffer> p, size_t offset)
{
if (p->size() < offset)
return 0;
if (CheckHeader((uint32_t*)(p->data() + offset)))
return 0x1000;
if (p->size() < offset + 0x400)
return 0;
if (CheckHeader((uint32_t*)(p->data() + offset + 0x400)))
return 0x1000;
if (p->size() < offset + 0x1fc)
return 0;
if (CheckHeader((uint32_t*)(p->data() + offset + 0x1fc)))
return 0x1000;
if (p->size() < offset + 0x5fc)
return 0;
if (CheckHeader((uint32_t*)(p->data() + offset + 0x5fc)))
return 0x1000;
return 0;
}
<|endoftext|> |
<commit_before>////////////////////////////////////////////////////////////////////////////////
// Name: app.cpp
// Purpose: Implementation of classes for syncodbcquery
// Author: Anton van Wezenbeek
// Copyright: (c) 2014 Anton van Wezenbeek
////////////////////////////////////////////////////////////////////////////////
#include <wx/wxprec.h>
#ifndef WX_PRECOMP
#include <wx/wx.h>
#endif
#include <wx/aboutdlg.h>
#include <wx/config.h>
#include <wx/regex.h>
#include <wx/stockitem.h>
#include <wx/tokenzr.h>
#include <wx/extension/filedlg.h>
#include <wx/extension/grid.h>
#include <wx/extension/lexers.h>
#include <wx/extension/shell.h>
#include <wx/extension/toolbar.h>
#include <wx/extension/util.h>
#include <wx/extension/version.h>
#include <wx/extension/report/defs.h>
#include <wx/extension/report/stc.h>
#include <wx/extension/report/util.h>
#include "app.h"
#ifndef __WXMSW__
#include "app.xpm"
#endif
wxIMPLEMENT_APP(App);
bool App::OnInit()
{
SetAppName("syncodbcquery");
if (!wxExApp::OnInit())
{
return false;
}
Frame *frame = new Frame();
frame->Show(true);
return true;
}
BEGIN_EVENT_TABLE(Frame, wxExFrameWithHistory)
EVT_CLOSE(Frame::OnClose)
EVT_MENU(wxID_ABOUT, Frame::OnCommand)
EVT_MENU(wxID_EXECUTE, Frame::OnCommand)
EVT_MENU(wxID_EXIT, Frame::OnCommand)
EVT_MENU(wxID_NEW, Frame::OnCommand)
EVT_MENU(wxID_OPEN, Frame::OnCommand)
EVT_MENU(wxID_SAVE, Frame::OnCommand)
EVT_MENU(wxID_SAVEAS, Frame::OnCommand)
EVT_MENU(wxID_STOP, Frame::OnCommand)
EVT_MENU(ID_SHELL_COMMAND, Frame::OnCommand)
EVT_MENU(ID_SHELL_COMMAND_STOP, Frame::OnCommand)
EVT_MENU_RANGE(wxID_CUT, wxID_CLEAR, Frame::OnCommand)
EVT_MENU_RANGE(ID_FIRST, ID_LAST, Frame::OnCommand)
EVT_UPDATE_UI(wxID_SAVE, Frame::OnUpdateUI)
EVT_UPDATE_UI(wxID_SAVEAS, Frame::OnUpdateUI)
EVT_UPDATE_UI(wxID_STOP, Frame::OnUpdateUI)
EVT_UPDATE_UI(ID_DATABASE_CLOSE, Frame::OnUpdateUI)
EVT_UPDATE_UI(ID_DATABASE_OPEN, Frame::OnUpdateUI)
EVT_UPDATE_UI(wxID_EXECUTE, Frame::OnUpdateUI)
EVT_UPDATE_UI(ID_RECENTFILE_MENU, Frame::OnUpdateUI)
EVT_UPDATE_UI(ID_VIEW_QUERY, Frame::OnUpdateUI)
EVT_UPDATE_UI(ID_VIEW_RESULTS, Frame::OnUpdateUI)
EVT_UPDATE_UI(ID_VIEW_STATISTICS, Frame::OnUpdateUI)
END_EVENT_TABLE()
Frame::Frame()
: wxExFrameWithHistory(NULL, wxID_ANY, wxTheApp->GetAppDisplayName())
, m_Running(false)
, m_Stopped(false)
, m_Query( new wxExSTCWithFrame(this, this))
, m_Shell( new wxExSTCShell(this, ">", ";", true, 50))
, m_Results( new wxExGrid(this))
{
SetIcon(wxICON(app));
wxExMenu* menuFile = new wxExMenu;
menuFile->Append(wxID_NEW);
menuFile->Append(wxID_OPEN);
UseFileHistory(ID_RECENTFILE_MENU, menuFile);
menuFile->AppendSeparator();
menuFile->Append(wxID_SAVE);
menuFile->Append(wxID_SAVEAS);
menuFile->AppendSeparator();
menuFile->Append(wxID_EXIT);
wxExMenu* menuDatabase = new wxExMenu;
menuDatabase->Append(ID_DATABASE_OPEN, wxExEllipsed(_("&Open")));
menuDatabase->Append(ID_DATABASE_CLOSE, _("&Close"));
wxExMenu* menuQuery = new wxExMenu;
menuQuery->Append(wxID_EXECUTE);
menuQuery->Append(wxID_STOP);
wxMenu* menuOptions = new wxMenu();
menuOptions->Append(wxID_PREFERENCES);
wxExMenu* menuView = new wxExMenu();
menuView->AppendBars();
menuView->AppendSeparator();
menuView->AppendCheckItem(ID_VIEW_QUERY, _("Query"));
menuView->AppendCheckItem(ID_VIEW_RESULTS, _("Results"));
menuView->AppendCheckItem(ID_VIEW_STATISTICS, _("Statistics"));
wxMenu* menuHelp = new wxMenu();
menuHelp->Append(wxID_ABOUT);
wxMenuBar *menubar = new wxMenuBar;
menubar->Append(menuFile, wxGetStockLabel(wxID_FILE));
menubar->Append(menuView, _("&View"));
menubar->Append(menuDatabase, _("&Connection"));
menubar->Append(menuQuery, _("&Query"));
menubar->Append(menuOptions, _("&Options"));
menubar->Append(menuHelp, wxGetStockLabel(wxID_HELP));
SetMenuBar(menubar);
m_Results->CreateGrid(0, 0);
m_Results->EnableEditing(false); // this is a read-only grid
if (wxExLexers::Get()->GetCount() > 0)
{
m_Query->SetLexer("sql");
m_Shell->SetLexer("sql");
}
m_Shell->SetFocus();
#if wxUSE_STATUSBAR
std::vector<wxExStatusBarPane> panes;
panes.push_back(wxExStatusBarPane());
panes.push_back(wxExStatusBarPane("PaneInfo", 100, _("Lines")));
SetupStatusBar(panes);
#endif
GetManager().AddPane(m_Shell,
wxAuiPaneInfo().
Name("CONSOLE").
CenterPane());
GetManager().AddPane(m_Results,
wxAuiPaneInfo().
Name("RESULTS").
Caption(_("Results")).
CloseButton(true).
MaximizeButton(true));
GetManager().AddPane(m_Query,
wxAuiPaneInfo().
Name("QUERY").
Caption(_("Query")).
CloseButton(true).
MaximizeButton(true));
GetManager().AddPane(m_Statistics.Show(this),
wxAuiPaneInfo().Left().
MaximizeButton(true).
Caption(_("Statistics")).
Name("STATISTICS"));
GetManager().LoadPerspective(wxConfigBase::Get()->Read("Perspective"));
GetManager().GetPane("QUERY").Show(false);
GetManager().Update();
}
void Frame::OnClose(wxCloseEvent& event)
{
wxExFileDialog dlg(this, &m_Query->GetFile());
if (dlg.ShowModalIfChanged() == wxID_CANCEL)
{
return;
}
wxConfigBase::Get()->Write("Perspective", GetManager().SavePerspective());
event.Skip();
}
void Frame::OnCommand(wxCommandEvent& event)
{
switch (event.GetId())
{
case wxID_ABOUT:
{
wxAboutDialogInfo info;
info.SetIcon(GetIcon());
info.SetDescription(_("This program offers a general ODBC query."));
info.SetVersion(wxExGetVersionInfo().GetVersionOnlyString());
info.SetCopyright(wxExGetVersionInfo().GetCopyright());
info.AddDeveloper(wxExOTL::VersionInfo().GetVersionString());
wxAboutBox(info);
}
break;
case wxID_EXECUTE:
m_Stopped = false;
RunQueries(m_Query->GetText());
break;
case wxID_EXIT:
Close(true);
break;
case wxID_NEW:
m_Query->GetFile().FileNew(wxExFileName());
if (wxExLexers::Get()->GetCount() > 0)
{
m_Query->SetLexer("sql");
}
m_Query->SetFocus();
GetManager().GetPane("QUERY").Show();
GetManager().Update();
break;
case wxID_OPEN:
wxExOpenFilesDialog(
this,
wxFD_OPEN | wxFD_CHANGE_DIR,
"sql files (*.sql)|*.sql",
true);
break;
case wxID_SAVE:
m_Query->GetFile().FileSave();
break;
case wxID_SAVEAS:
{
wxExFileDialog dlg(
this,
&m_Query->GetFile(),
wxGetStockLabel(wxID_SAVEAS),
wxFileSelectorDefaultWildcardStr,
wxFD_SAVE);
if (dlg.ShowModal() == wxID_OK)
{
m_Query->GetFile().FileSave(dlg.GetPath());
}
}
break;
case wxID_STOP:
m_Running = false;
m_Stopped = true;
break;
case ID_DATABASE_CLOSE:
if (m_otl.Logoff())
{
m_Shell->SetPrompt(">");
}
break;
case ID_DATABASE_OPEN:
if (m_otl.Logon(this))
{
m_Shell->SetPrompt(m_otl.Datasource() + ">");
}
break;
case ID_SHELL_COMMAND:
if (m_otl.IsConnected())
{
try
{
const wxString input(event.GetString());
if (!input.empty())
{
const wxString query = input.substr(
0,
input.length() - 1);
m_Stopped = false;
RunQuery(query, true);
}
}
catch (otl_exception& p)
{
if (m_Results->IsShown())
{
m_Results->EndBatch();
}
m_Shell->AppendText(_("\nerror: ") + wxExQuoted(p.msg));
}
}
else
{
m_Shell->AppendText(_("\nnot connected"));
}
m_Shell->Prompt();
break;
case ID_SHELL_COMMAND_STOP:
m_Stopped = true;
m_Shell->Prompt(_("cancelled"));
break;
case ID_VIEW_QUERY: TogglePane("QUERY"); break;
case ID_VIEW_RESULTS: TogglePane("RESULTS"); break;
case ID_VIEW_STATISTICS: TogglePane("STATISTICS"); break;
default:
wxFAIL;
}
}
void Frame::OnCommandConfigDialog(
wxWindowID dialogid,
int commandid)
{
if (dialogid == wxID_PREFERENCES)
{
m_Query->ConfigGet();
m_Shell->ConfigGet();
}
else
{
wxExFrameWithHistory::OnCommandConfigDialog(dialogid, commandid);
}
}
void Frame::OnUpdateUI(wxUpdateUIEvent& event)
{
switch (event.GetId())
{
case wxID_EXECUTE:
// If we have a query, you can hide it, but still run it.
event.Enable(m_Query->GetLength() > 0 && m_otl.IsConnected());
break;
case wxID_SAVE:
event.Enable(m_Query->GetModify());
break;
case wxID_SAVEAS:
event.Enable(m_Query->GetLength() > 0);
break;
case wxID_STOP:
event.Enable(m_Running);
break;
case ID_DATABASE_CLOSE:
event.Enable(m_otl.IsConnected());
break;
case ID_DATABASE_OPEN:
event.Enable(!m_otl.IsConnected());
break;
case ID_RECENTFILE_MENU:
event.Enable(!GetRecentFile().empty());
break;
case ID_VIEW_QUERY:
event.Check(GetManager().GetPane("QUERY").IsShown());
break;
case ID_VIEW_RESULTS:
event.Check(GetManager().GetPane("RESULTS").IsShown());
break;
case ID_VIEW_STATISTICS:
event.Check(GetManager().GetPane("STATISTICS").IsShown());
break;
default:
wxFAIL;
}
}
bool Frame::OpenFile(
const wxExFileName& filename,
int line_number,
const wxString& match,
int col_number,
long flags)
{
if (m_Query->Open(filename, line_number, match, col_number, flags))
{
GetManager().GetPane("QUERY").Show(true);
GetManager().Update();
SetRecentFile(filename.GetFullPath());
}
else
{
return false;
}
}
void Frame::RunQuery(const wxString& query, bool empty_results)
{
wxStopWatch sw;
const wxString query_lower = query.Lower();
// Query functions supported by ODBC
// $SQLTables, $SQLColumns, etc.
// $SQLTables $1:'%'
// allow you to get database schema.
if (query_lower.StartsWith("select") ||
query_lower.StartsWith("describe") ||
query_lower.StartsWith("show") ||
query_lower.StartsWith("explain") ||
query_lower.StartsWith("$sql"))
{
long rpc;
if (m_Results->IsShown())
{
rpc = m_otl.Query(query, m_Results, m_Stopped, empty_results);
}
else
{
rpc = m_otl.Query(query, m_Shell, m_Stopped);
}
sw.Pause();
UpdateStatistics(sw.Time(), rpc);
}
else
{
const auto rpc = m_otl.Query(query);
sw.Pause();
UpdateStatistics(sw.Time(), rpc);
}
m_Shell->DocumentEnd();
}
void Frame::RunQueries(const wxString& text)
{
if (text.empty())
{
return;
}
if (m_Results->IsShown())
{
m_Results->ClearGrid();
}
// Skip sql comments.
wxString output = text;
wxRegEx("--.*$", wxRE_NEWLINE).ReplaceAll(&output, "");
// Queries are seperated by ; character.
wxStringTokenizer tkz(output, ";");
int no_queries = 0;
wxStopWatch sw;
m_Running = true;
// Run all queries.
while (tkz.HasMoreTokens() && !m_Stopped)
{
wxString query = tkz.GetNextToken();
query.Trim(true);
query.Trim(false);
if (!query.empty())
{
try
{
RunQuery(query, no_queries == 0);
no_queries++;
}
catch (otl_exception& p)
{
m_Statistics.Inc(_("Number of query errors"));
m_Shell->AppendText(
_("\nerror: ") + wxExQuoted(p.msg) +
_(" in: ") + wxExQuoted(query));
}
}
}
m_Shell->Prompt(wxString::Format(_("\n%d queries (%.3f seconds)"),
no_queries,
(float)sw.Time() / (float)1000));
m_Running = false;
}
void Frame::UpdateStatistics(long time, long rpc)
{
m_Shell->AppendText(wxString::Format(_("\n%ld rows processed (%.3f seconds)"),
rpc,
(float)time / (float)1000));
m_Statistics.Set(_("Rows processed"), rpc);
m_Statistics.Set(_("Query runtime"), time);
m_Statistics.Inc(_("Total number of queries run"));
m_Statistics.Inc(_("Total query runtime"), time);
m_Statistics.Inc(_("Total rows processed"), rpc);
}
<commit_msg>added toolbar bitmap for wxID_EXECUTE<commit_after>////////////////////////////////////////////////////////////////////////////////
// Name: app.cpp
// Purpose: Implementation of classes for syncodbcquery
// Author: Anton van Wezenbeek
// Copyright: (c) 2014 Anton van Wezenbeek
////////////////////////////////////////////////////////////////////////////////
#include <wx/wxprec.h>
#ifndef WX_PRECOMP
#include <wx/wx.h>
#endif
#include <wx/aboutdlg.h>
#include <wx/config.h>
#include <wx/regex.h>
#include <wx/stockitem.h>
#include <wx/tokenzr.h>
#include <wx/extension/filedlg.h>
#include <wx/extension/grid.h>
#include <wx/extension/lexers.h>
#include <wx/extension/shell.h>
#include <wx/extension/toolbar.h>
#include <wx/extension/util.h>
#include <wx/extension/version.h>
#include <wx/extension/report/defs.h>
#include <wx/extension/report/stc.h>
#include <wx/extension/report/util.h>
#include "app.h"
#ifndef __WXMSW__
#include "app.xpm"
#endif
wxIMPLEMENT_APP(App);
bool App::OnInit()
{
SetAppName("syncodbcquery");
if (!wxExApp::OnInit())
{
return false;
}
Frame *frame = new Frame();
frame->Show(true);
return true;
}
BEGIN_EVENT_TABLE(Frame, wxExFrameWithHistory)
EVT_CLOSE(Frame::OnClose)
EVT_MENU(wxID_ABOUT, Frame::OnCommand)
EVT_MENU(wxID_EXECUTE, Frame::OnCommand)
EVT_MENU(wxID_EXIT, Frame::OnCommand)
EVT_MENU(wxID_NEW, Frame::OnCommand)
EVT_MENU(wxID_OPEN, Frame::OnCommand)
EVT_MENU(wxID_SAVE, Frame::OnCommand)
EVT_MENU(wxID_SAVEAS, Frame::OnCommand)
EVT_MENU(wxID_STOP, Frame::OnCommand)
EVT_MENU(ID_SHELL_COMMAND, Frame::OnCommand)
EVT_MENU(ID_SHELL_COMMAND_STOP, Frame::OnCommand)
EVT_MENU_RANGE(wxID_CUT, wxID_CLEAR, Frame::OnCommand)
EVT_MENU_RANGE(ID_FIRST, ID_LAST, Frame::OnCommand)
EVT_UPDATE_UI(wxID_SAVE, Frame::OnUpdateUI)
EVT_UPDATE_UI(wxID_SAVEAS, Frame::OnUpdateUI)
EVT_UPDATE_UI(wxID_STOP, Frame::OnUpdateUI)
EVT_UPDATE_UI(ID_DATABASE_CLOSE, Frame::OnUpdateUI)
EVT_UPDATE_UI(ID_DATABASE_OPEN, Frame::OnUpdateUI)
EVT_UPDATE_UI(wxID_EXECUTE, Frame::OnUpdateUI)
EVT_UPDATE_UI(ID_RECENTFILE_MENU, Frame::OnUpdateUI)
EVT_UPDATE_UI(ID_VIEW_QUERY, Frame::OnUpdateUI)
EVT_UPDATE_UI(ID_VIEW_RESULTS, Frame::OnUpdateUI)
EVT_UPDATE_UI(ID_VIEW_STATISTICS, Frame::OnUpdateUI)
END_EVENT_TABLE()
Frame::Frame()
: wxExFrameWithHistory(NULL, wxID_ANY, wxTheApp->GetAppDisplayName())
, m_Running(false)
, m_Stopped(false)
, m_Query( new wxExSTCWithFrame(this, this))
, m_Shell( new wxExSTCShell(this, ">", ";", true, 50))
, m_Results( new wxExGrid(this))
{
SetIcon(wxICON(app));
wxExMenu* menuFile = new wxExMenu;
menuFile->Append(wxID_NEW);
menuFile->Append(wxID_OPEN);
UseFileHistory(ID_RECENTFILE_MENU, menuFile);
menuFile->AppendSeparator();
menuFile->Append(wxID_SAVE);
menuFile->Append(wxID_SAVEAS);
menuFile->AppendSeparator();
menuFile->Append(wxID_EXIT);
wxExMenu* menuDatabase = new wxExMenu;
menuDatabase->Append(ID_DATABASE_OPEN, wxExEllipsed(_("&Open")));
menuDatabase->Append(ID_DATABASE_CLOSE, _("&Close"));
wxExMenu* menuQuery = new wxExMenu;
menuQuery->Append(wxID_EXECUTE);
menuQuery->Append(wxID_STOP);
wxMenu* menuOptions = new wxMenu();
menuOptions->Append(wxID_PREFERENCES);
wxExMenu* menuView = new wxExMenu();
menuView->AppendBars();
menuView->AppendSeparator();
menuView->AppendCheckItem(ID_VIEW_QUERY, _("Query"));
menuView->AppendCheckItem(ID_VIEW_RESULTS, _("Results"));
menuView->AppendCheckItem(ID_VIEW_STATISTICS, _("Statistics"));
wxMenu* menuHelp = new wxMenu();
menuHelp->Append(wxID_ABOUT);
wxMenuBar *menubar = new wxMenuBar;
menubar->Append(menuFile, wxGetStockLabel(wxID_FILE));
menubar->Append(menuView, _("&View"));
menubar->Append(menuDatabase, _("&Connection"));
menubar->Append(menuQuery, _("&Query"));
menubar->Append(menuOptions, _("&Options"));
menubar->Append(menuHelp, wxGetStockLabel(wxID_HELP));
SetMenuBar(menubar);
m_Results->CreateGrid(0, 0);
m_Results->EnableEditing(false); // this is a read-only grid
if (wxExLexers::Get()->GetCount() > 0)
{
m_Query->SetLexer("sql");
m_Shell->SetLexer("sql");
}
m_Shell->SetFocus();
#if wxUSE_STATUSBAR
std::vector<wxExStatusBarPane> panes;
panes.push_back(wxExStatusBarPane());
panes.push_back(wxExStatusBarPane("PaneInfo", 100, _("Lines")));
SetupStatusBar(panes);
#endif
GetToolBar()->AddTool(wxID_EXECUTE,
wxEmptyString,
wxArtProvider::GetBitmap(
wxART_GO_FORWARD, wxART_TOOLBAR, GetToolBar()->GetToolBitmapSize()),
wxGetStockLabel(wxID_EXECUTE, wxSTOCK_NOFLAGS));
GetToolBar()->Realize();
GetManager().AddPane(m_Shell,
wxAuiPaneInfo().
Name("CONSOLE").
CenterPane());
GetManager().AddPane(m_Results,
wxAuiPaneInfo().
Name("RESULTS").
Caption(_("Results")).
CloseButton(true).
MaximizeButton(true));
GetManager().AddPane(m_Query,
wxAuiPaneInfo().
Name("QUERY").
Caption(_("Query")).
CloseButton(true).
MaximizeButton(true));
GetManager().AddPane(m_Statistics.Show(this),
wxAuiPaneInfo().Left().
MaximizeButton(true).
Caption(_("Statistics")).
Name("STATISTICS"));
GetManager().LoadPerspective(wxConfigBase::Get()->Read("Perspective"));
GetManager().GetPane("QUERY").Show(false);
GetManager().Update();
}
void Frame::OnClose(wxCloseEvent& event)
{
wxExFileDialog dlg(this, &m_Query->GetFile());
if (dlg.ShowModalIfChanged() == wxID_CANCEL)
{
return;
}
wxConfigBase::Get()->Write("Perspective", GetManager().SavePerspective());
event.Skip();
}
void Frame::OnCommand(wxCommandEvent& event)
{
switch (event.GetId())
{
case wxID_ABOUT:
{
wxAboutDialogInfo info;
info.SetIcon(GetIcon());
info.SetDescription(_("This program offers a general ODBC query."));
info.SetVersion(wxExGetVersionInfo().GetVersionOnlyString());
info.SetCopyright(wxExGetVersionInfo().GetCopyright());
info.AddDeveloper(wxExOTL::VersionInfo().GetVersionString());
wxAboutBox(info);
}
break;
case wxID_EXECUTE:
m_Stopped = false;
RunQueries(m_Query->GetText());
break;
case wxID_EXIT:
Close(true);
break;
case wxID_NEW:
m_Query->GetFile().FileNew(wxExFileName());
if (wxExLexers::Get()->GetCount() > 0)
{
m_Query->SetLexer("sql");
}
m_Query->SetFocus();
GetManager().GetPane("QUERY").Show();
GetManager().Update();
break;
case wxID_OPEN:
wxExOpenFilesDialog(
this,
wxFD_OPEN | wxFD_CHANGE_DIR,
"sql files (*.sql)|*.sql",
true);
break;
case wxID_SAVE:
m_Query->GetFile().FileSave();
break;
case wxID_SAVEAS:
{
wxExFileDialog dlg(
this,
&m_Query->GetFile(),
wxGetStockLabel(wxID_SAVEAS),
wxFileSelectorDefaultWildcardStr,
wxFD_SAVE);
if (dlg.ShowModal() == wxID_OK)
{
m_Query->GetFile().FileSave(dlg.GetPath());
}
}
break;
case wxID_STOP:
m_Running = false;
m_Stopped = true;
break;
case ID_DATABASE_CLOSE:
if (m_otl.Logoff())
{
m_Shell->SetPrompt(">");
}
break;
case ID_DATABASE_OPEN:
if (m_otl.Logon(this))
{
m_Shell->SetPrompt(m_otl.Datasource() + ">");
}
break;
case ID_SHELL_COMMAND:
if (m_otl.IsConnected())
{
try
{
const wxString input(event.GetString());
if (!input.empty())
{
const wxString query = input.substr(
0,
input.length() - 1);
m_Stopped = false;
RunQuery(query, true);
}
}
catch (otl_exception& p)
{
if (m_Results->IsShown())
{
m_Results->EndBatch();
}
m_Shell->AppendText(_("\nerror: ") + wxExQuoted(p.msg));
}
}
else
{
m_Shell->AppendText(_("\nnot connected"));
}
m_Shell->Prompt();
break;
case ID_SHELL_COMMAND_STOP:
m_Stopped = true;
m_Shell->Prompt(_("cancelled"));
break;
case ID_VIEW_QUERY: TogglePane("QUERY"); break;
case ID_VIEW_RESULTS: TogglePane("RESULTS"); break;
case ID_VIEW_STATISTICS: TogglePane("STATISTICS"); break;
default:
wxFAIL;
}
}
void Frame::OnCommandConfigDialog(
wxWindowID dialogid,
int commandid)
{
if (dialogid == wxID_PREFERENCES)
{
m_Query->ConfigGet();
m_Shell->ConfigGet();
}
else
{
wxExFrameWithHistory::OnCommandConfigDialog(dialogid, commandid);
}
}
void Frame::OnUpdateUI(wxUpdateUIEvent& event)
{
switch (event.GetId())
{
case wxID_EXECUTE:
// If we have a query, you can hide it, but still run it.
event.Enable(m_Query->GetLength() > 0 && m_otl.IsConnected());
break;
case wxID_SAVE:
event.Enable(m_Query->GetModify());
break;
case wxID_SAVEAS:
event.Enable(m_Query->GetLength() > 0);
break;
case wxID_STOP:
event.Enable(m_Running);
break;
case ID_DATABASE_CLOSE:
event.Enable(m_otl.IsConnected());
break;
case ID_DATABASE_OPEN:
event.Enable(!m_otl.IsConnected());
break;
case ID_RECENTFILE_MENU:
event.Enable(!GetRecentFile().empty());
break;
case ID_VIEW_QUERY:
event.Check(GetManager().GetPane("QUERY").IsShown());
break;
case ID_VIEW_RESULTS:
event.Check(GetManager().GetPane("RESULTS").IsShown());
break;
case ID_VIEW_STATISTICS:
event.Check(GetManager().GetPane("STATISTICS").IsShown());
break;
default:
wxFAIL;
}
}
bool Frame::OpenFile(
const wxExFileName& filename,
int line_number,
const wxString& match,
int col_number,
long flags)
{
if (m_Query->Open(filename, line_number, match, col_number, flags))
{
GetManager().GetPane("QUERY").Show(true);
GetManager().Update();
SetRecentFile(filename.GetFullPath());
return true;
}
else
{
return false;
}
}
void Frame::RunQuery(const wxString& query, bool empty_results)
{
wxStopWatch sw;
const wxString query_lower = query.Lower();
// Query functions supported by ODBC
// $SQLTables, $SQLColumns, etc.
// $SQLTables $1:'%'
// allow you to get database schema.
if (query_lower.StartsWith("select") ||
query_lower.StartsWith("describe") ||
query_lower.StartsWith("show") ||
query_lower.StartsWith("explain") ||
query_lower.StartsWith("$sql"))
{
long rpc;
if (m_Results->IsShown())
{
rpc = m_otl.Query(query, m_Results, m_Stopped, empty_results);
}
else
{
rpc = m_otl.Query(query, m_Shell, m_Stopped);
}
sw.Pause();
UpdateStatistics(sw.Time(), rpc);
}
else
{
const auto rpc = m_otl.Query(query);
sw.Pause();
UpdateStatistics(sw.Time(), rpc);
}
m_Shell->DocumentEnd();
}
void Frame::RunQueries(const wxString& text)
{
if (text.empty())
{
return;
}
if (m_Results->IsShown())
{
m_Results->ClearGrid();
}
// Skip sql comments.
wxString output = text;
wxRegEx("--.*$", wxRE_NEWLINE).ReplaceAll(&output, "");
// Queries are seperated by ; character.
wxStringTokenizer tkz(output, ";");
int no_queries = 0;
wxStopWatch sw;
m_Running = true;
// Run all queries.
while (tkz.HasMoreTokens() && !m_Stopped)
{
wxString query = tkz.GetNextToken();
query.Trim(true);
query.Trim(false);
if (!query.empty())
{
try
{
RunQuery(query, no_queries == 0);
no_queries++;
}
catch (otl_exception& p)
{
m_Statistics.Inc(_("Number of query errors"));
m_Shell->AppendText(
_("\nerror: ") + wxExQuoted(p.msg) +
_(" in: ") + wxExQuoted(query));
}
}
}
m_Shell->Prompt(wxString::Format(_("\n%d queries (%.3f seconds)"),
no_queries,
(float)sw.Time() / (float)1000));
m_Running = false;
}
void Frame::UpdateStatistics(long time, long rpc)
{
m_Shell->AppendText(wxString::Format(_("\n%ld rows processed (%.3f seconds)"),
rpc,
(float)time / (float)1000));
m_Statistics.Set(_("Rows processed"), rpc);
m_Statistics.Set(_("Query runtime"), time);
m_Statistics.Inc(_("Total number of queries run"));
m_Statistics.Inc(_("Total query runtime"), time);
m_Statistics.Inc(_("Total rows processed"), rpc);
}
<|endoftext|> |
<commit_before>/*************************************************************************
> File Name: Draw.cpp
> Project Name: Hearthstonepp
> Author: Young-Joong Kim
> Purpose: Implement DrawTask
> Created Time: 2018/07/21
> Copyright (c) 2018, Young-Joong Kim
*************************************************************************/
#include <Tasks/BasicTasks/DrawTask.h>
#include <Cards/Entity.h>
namespace Hearthstonepp::BasicTasks
{
DrawTask::DrawTask(size_t num, TaskAgent& agent) : m_num(num), m_agent(agent)
{
// Do Nothing
}
TaskID DrawTask::GetTaskID() const
{
return TaskID::DRAW;
}
MetaData DrawTask::Impl(Player& user, Player&)
{
size_t num = m_num;
MetaData result = MetaData::DRAW_SUCCESS;
std::vector<Entity*>& deck = user.cards;
std::vector<Entity*>& hand = user.hand;
// after reaching fatigue
if (deck.size() < num)
{
size_t numDrawAfterFatigue = num - deck.size();
// sigma (i = 1 to numDrawAfterFatigue) { current.exhausted + i }
int fatigueDamage = static_cast<int>(
user.exhausted * numDrawAfterFatigue +
numDrawAfterFatigue * (numDrawAfterFatigue + 1) / 2);
int remainHealth = static_cast<int>(user.hero->health) - fatigueDamage;
user.hero->health =
remainHealth > 0 ? static_cast<size_t>(remainHealth) : 0;
user.exhausted += static_cast<BYTE>(numDrawAfterFatigue);
result = MetaData::DRAW_EXHAUST;
}
// when hand size over 10, over draw
if (hand.size() + num > 10)
{
// number of over draw
size_t over = hand.size() + num - 10;
std::vector<Entity*> burnt;
burnt.reserve(over);
// draw burnt card
for (size_t i = 0; i < over; ++i)
{
burnt.emplace_back(deck.back());
deck.pop_back();
}
num = 10 - hand.size();
if (result == MetaData::DRAW_EXHAUST)
{
result = MetaData::DRAW_EXHAUST_OVERDRAW;
}
else
{
result = MetaData::DRAW_OVERDRAW;
}
// Send Burnt Cards to GameInterface
TaskMetaTrait trait(TaskID::OVER_DRAW, result, user.id);
m_agent.Notify(Serializer::CreateEntityVector(trait, burnt));
}
// successful draw
for (size_t i = 0; i < num; ++i)
{
hand.push_back(deck.back());
deck.pop_back();
}
return result;
}
DrawCardTask::DrawCardTask(Card* card)
{
switch (card->cardType)
{
case +CardType::MINION:
m_entity = new Minion(card);
break;
case +CardType::WEAPON:
m_entity = new Weapon(card);
break;
default:
m_entity = new Entity(card);
}
}
TaskID DrawCardTask::GetTaskID() const
{
return TaskID::DRAW;
}
MetaData DrawCardTask::Impl(Player& user, Player&)
{
std::vector<Entity*>& deck = user.cards;
std::vector<Entity*>& hand = user.hand;
hand.emplace_back(m_entity);
if (!deck.empty())
{
deck.pop_back();
}
return MetaData::DRAW_SUCCESS;
}
} // namespace Hearthstonepp::BasicTasks<commit_msg>Update DrawTask - Fix error : draw over the deck<commit_after>/*************************************************************************
> File Name: Draw.cpp
> Project Name: Hearthstonepp
> Author: Young-Joong Kim
> Purpose: Implement DrawTask
> Created Time: 2018/07/21
> Copyright (c) 2018, Young-Joong Kim
*************************************************************************/
#include <Tasks/BasicTasks/DrawTask.h>
#include <Cards/Entity.h>
namespace Hearthstonepp::BasicTasks
{
DrawTask::DrawTask(size_t num, TaskAgent& agent) : m_num(num), m_agent(agent)
{
// Do Nothing
}
TaskID DrawTask::GetTaskID() const
{
return TaskID::DRAW;
}
MetaData DrawTask::Impl(Player& user, Player&)
{
size_t num = m_num;
MetaData result = MetaData::DRAW_SUCCESS;
std::vector<Entity*>& deck = user.cards;
std::vector<Entity*>& hand = user.hand;
// after reaching fatigue
if (deck.size() < num)
{
size_t numDrawAfterFatigue = num - deck.size();
// sigma (i = 1 to numDrawAfterFatigue) { current.exhausted + i }
int fatigueDamage = static_cast<int>(
user.exhausted * numDrawAfterFatigue +
numDrawAfterFatigue * (numDrawAfterFatigue + 1) / 2);
int remainHealth = static_cast<int>(user.hero->health) - fatigueDamage;
user.hero->health =
remainHealth > 0 ? static_cast<size_t>(remainHealth) : 0;
user.exhausted += static_cast<BYTE>(numDrawAfterFatigue);
num = deck.size();
result = MetaData::DRAW_EXHAUST;
}
// when hand size over 10, over draw
if (hand.size() + num > 10)
{
// number of over draw
size_t over = hand.size() + num - 10;
std::vector<Entity*> burnt;
burnt.reserve(over);
// draw burnt card
for (size_t i = 0; i < over; ++i)
{
burnt.emplace_back(deck.back());
deck.pop_back();
}
num = 10 - hand.size();
if (result == MetaData::DRAW_EXHAUST)
{
result = MetaData::DRAW_EXHAUST_OVERDRAW;
}
else
{
result = MetaData::DRAW_OVERDRAW;
}
// Send Burnt Cards to GameInterface
TaskMetaTrait trait(TaskID::OVER_DRAW, result, user.id);
m_agent.Notify(Serializer::CreateEntityVector(trait, burnt));
}
// successful draw
for (size_t i = 0; i < num; ++i)
{
hand.push_back(deck.back());
deck.pop_back();
}
return result;
}
DrawCardTask::DrawCardTask(Card* card)
{
switch (card->cardType)
{
case +CardType::MINION:
m_entity = new Minion(card);
break;
case +CardType::WEAPON:
m_entity = new Weapon(card);
break;
default:
m_entity = new Entity(card);
}
}
TaskID DrawCardTask::GetTaskID() const
{
return TaskID::DRAW;
}
MetaData DrawCardTask::Impl(Player& user, Player&)
{
std::vector<Entity*>& deck = user.cards;
std::vector<Entity*>& hand = user.hand;
hand.emplace_back(m_entity);
if (!deck.empty())
{
deck.pop_back();
}
return MetaData::DRAW_SUCCESS;
}
} // namespace Hearthstonepp::BasicTasks<|endoftext|> |
<commit_before>/** @package TBTKtemp
* @file main.cpp
* @brief Basic Chebyshev example
*
* Basic example of using the Chebyshev method to solve a 2D tight-binding
* model with t = 1 and mu = -1. Lattice with edges and a size of 20x20 sites.
* Using 5000 Chebyshev coefficients and evaluating the Green's function with
* an energy resolution of 10000. Calculates LDOS at SIZE_X = 20 sites along
* the line y = SIZE_Y/2 = 10.
*
* @author Kristofer Björnson
*/
#include <complex>
#include "Model.h"
#include "ChebyshevSolver.h"
#include "CPropertyExtractor.h"
#include "FileWriter.h"
using namespace std;
using namespace TBTK;
const complex<double> i(0, 1);
int main(int argc, char **argv){
//Chebyshev expansion parameters.
const int NUM_COEFFICIENTS = 5000;
const int ENERGY_RESOLUTION = 10000;
const double SCALE_FACTOR = 5.;
//Lattice size
const int SIZE_X = 20;
const int SIZE_Y = 20;
//Model parameters.
complex<double> mu = -1.0;
complex<double> t = 1.0;
//Create model and set up hopping parameters
Model model;
for(int x = 0; x < SIZE_X; x++){
for(int y = 0; y < SIZE_Y; y++){
for(int s = 0; s < 2; s++){
//Add hopping amplitudes corresponding to chemical potential
model.addHA(HoppingAmplitude(-mu, {x, y, s}, {x, y, s}));
//Add hopping parameters corresponding to t
if(x+1 < SIZE_X)
model.addHAAndHC(HoppingAmplitude(-t, {(x+1)%SIZE_X, y, s}, {x, y, s}));
if(y+1 < SIZE_Y)
model.addHAAndHC(HoppingAmplitude(-t, {x, (y+1)%SIZE_Y, s}, {x, y, s}));
}
}
}
//Construct model
model.construct();
//Set filename and remove any file already in the folder
FileWriter::setFileName("TBTKResults.h5");
FileWriter::clear();
//Setup ChebyshevSolver
ChebyshevSolver cSolver;
cSolver.setModel(&model);
cSolver.setScaleFactor(SCALE_FACTOR);
//Create PropertyExtractor. The parameter are in order: The
//ChebyshevSolver, number of expansion coefficients used in the
//Cebyshev expansion, energy resolution with which the Green's function
// is evaluated, whether calculate expansion functions using a GPU or
//not, whether to evaluate the Green's function using a GPU or not,
//whether to use a lookup table for the Green's function or not
//(required if the Green's function is evaluated on a GPU), and the
//lower and upper bound between which the Green's function is evaluated
//(has to be inside the interval [-SCALE_FACTOR, SCALE_FACTOR]).
CPropertyExtractor pe(&cSolver,
NUM_COEFFICIENTS,
ENERGY_RESOLUTION,
false,
false,
true,
-SCALE_FACTOR,
SCALE_FACTOR);
//Extract local density of states and write to file
double *ldos = pe.calculateLDOS({IDX_X, SIZE_Y/2, IDX_SUM_ALL}, {SIZE_Y, 1, 2});
const int RANK = 1;
int dims[RANK] = {SIZE_X};
FileWriter::writeLDOS(ldos,
RANK,
dims,
-SCALE_FACTOR,
SCALE_FACTOR,
ENERGY_RESOLUTION);
delete [] ldos;
return 0;
}
<commit_msg>Changed parameters in Template/BasicChebyshev<commit_after>/** @package TBTKtemp
* @file main.cpp
* @brief Basic Chebyshev example
*
* Basic example of using the Chebyshev method to solve a 2D tight-binding
* model with t = 1 and mu = -1. Lattice with edges and a size of 40x40 sites.
* Using 5000 Chebyshev coefficients and evaluating the Green's function with
* an energy resolution of 10000. Calculates LDOS at SIZE_X = 40 sites along
* the line y = SIZE_Y/2 = 20.
*
* @author Kristofer Björnson
*/
#include <complex>
#include "Model.h"
#include "ChebyshevSolver.h"
#include "CPropertyExtractor.h"
#include "FileWriter.h"
using namespace std;
using namespace TBTK;
const complex<double> i(0, 1);
int main(int argc, char **argv){
//Chebyshev expansion parameters.
const int NUM_COEFFICIENTS = 5000;
const int ENERGY_RESOLUTION = 10000;
const double SCALE_FACTOR = 5.;
//Lattice size
const int SIZE_X = 40;
const int SIZE_Y = 40;
//Model parameters.
complex<double> mu = -1.0;
complex<double> t = 1.0;
//Create model and set up hopping parameters
Model model;
for(int x = 0; x < SIZE_X; x++){
for(int y = 0; y < SIZE_Y; y++){
for(int s = 0; s < 2; s++){
//Add hopping amplitudes corresponding to chemical potential
model.addHA(HoppingAmplitude(-mu, {x, y, s}, {x, y, s}));
//Add hopping parameters corresponding to t
if(x+1 < SIZE_X)
model.addHAAndHC(HoppingAmplitude(-t, {(x+1)%SIZE_X, y, s}, {x, y, s}));
if(y+1 < SIZE_Y)
model.addHAAndHC(HoppingAmplitude(-t, {x, (y+1)%SIZE_Y, s}, {x, y, s}));
}
}
}
//Construct model
model.construct();
//Set filename and remove any file already in the folder
FileWriter::setFileName("TBTKResults.h5");
FileWriter::clear();
//Setup ChebyshevSolver
ChebyshevSolver cSolver;
cSolver.setModel(&model);
cSolver.setScaleFactor(SCALE_FACTOR);
//Create PropertyExtractor. The parameter are in order: The
//ChebyshevSolver, number of expansion coefficients used in the
//Cebyshev expansion, energy resolution with which the Green's function
// is evaluated, whether calculate expansion functions using a GPU or
//not, whether to evaluate the Green's function using a GPU or not,
//whether to use a lookup table for the Green's function or not
//(required if the Green's function is evaluated on a GPU), and the
//lower and upper bound between which the Green's function is evaluated
//(has to be inside the interval [-SCALE_FACTOR, SCALE_FACTOR]).
CPropertyExtractor pe(&cSolver,
NUM_COEFFICIENTS,
ENERGY_RESOLUTION,
false,
false,
true,
-SCALE_FACTOR,
SCALE_FACTOR);
//Extract local density of states and write to file
double *ldos = pe.calculateLDOS({IDX_X, SIZE_Y/2, IDX_SUM_ALL}, {SIZE_Y, 1, 2});
const int RANK = 1;
int dims[RANK] = {SIZE_X};
FileWriter::writeLDOS(ldos,
RANK,
dims,
-SCALE_FACTOR,
SCALE_FACTOR,
ENERGY_RESOLUTION);
delete [] ldos;
return 0;
}
<|endoftext|> |
<commit_before>
// Copyright 2010-2012 University of Washington. All Rights Reserved.
// LICENSE_PLACEHOLDER
// This software was created with Government support under DE
// AC05-76RL01830 awarded by the United States Department of
// Energy. The Government has certain rights in the software.
/// One implementation of GUPS. This does no load-balancing, and may
/// suffer from some load imbalance.
#include <Grappa.hpp>
#include "ForkJoin.hpp"
#include "GlobalAllocator.hpp"
#include <boost/test/unit_test.hpp>
DEFINE_int64( iterations, 1 << 30, "Iterations" );
DEFINE_int64( sizeA, 1000, "Size of array that gups increments" );
double wall_clock_time() {
const double nano = 1.0e-9;
timespec t;
clock_gettime( CLOCK_MONOTONIC, &t );
return nano * t.tv_nsec + t.tv_sec;
}
BOOST_AUTO_TEST_SUITE( Gups_tests );
LOOP_FUNCTION( func_start_profiling, index ) {
Grappa_start_profiling();
}
LOOP_FUNCTION( func_stop_profiling, index ) {
Grappa_stop_profiling();
}
/// Functor to execute one GUP.
LOOP_FUNCTOR( func_gups, index, ((GlobalAddress<int64_t>, Array)) ) {
const uint64_t LARGE_PRIME = 18446744073709551557UL;
uint64_t b = (index*LARGE_PRIME) % FLAGS_sizeA;
Grappa_delegate_fetch_and_add_word( Array + b, 1 );
}
void user_main( int * args ) {
func_start_profiling start_profiling;
func_stop_profiling stop_profiling;
GlobalAddress<int64_t> A = Grappa_typed_malloc<int64_t>(FLAGS_sizeA);
func_gups gups( A );
double runtime = 0.0;
double throughput = 0.0;
int nnodes = atoi(getenv("SLURM_NNODES"));
double throughput_per_node = 0.0;
Grappa_add_profiling_value( &runtime, "runtime", "s", false, 0.0 );
Grappa_add_profiling_integer( &FLAGS_iterations, "iterations", "it", false, 0 );
Grappa_add_profiling_integer( &FLAGS_sizeA, "sizeA", "entries", false, 0 );
Grappa_add_profiling_value( &throughput, "updates_per_s", "up/s", false, 0.0 );
Grappa_add_profiling_value( &throughput_per_node, "updates_per_s_per_node", "up/s", false, 0.0 );
fork_join_custom( &start_profiling );
double start = wall_clock_time();
fork_join( &gups, 1, FLAGS_iterations );
double end = wall_clock_time();
fork_join_custom( &stop_profiling );
runtime = end - start;
throughput = FLAGS_iterations / runtime;
throughput_per_node = throughput/nnodes;
Grappa_merge_and_dump_stats();
LOG(INFO) << "GUPS: "
<< FLAGS_iterations << " updates at "
<< throughput << "updates/s ("
<< throughput/nnodes << " updates/s/node).";
}
BOOST_AUTO_TEST_CASE( test1 ) {
Grappa_init( &(boost::unit_test::framework::master_test_suite().argc),
&(boost::unit_test::framework::master_test_suite().argv) );
Grappa_activate();
Grappa_run_user_main( &user_main, (int*)NULL );
Grappa_finish( 0 );
}
BOOST_AUTO_TEST_SUITE_END();
<commit_msg>hasty checkin of gups using ff delegates & outputs stats as a means of validation<commit_after>
// Copyright 2010-2012 University of Washington. All Rights Reserved.
// LICENSE_PLACEHOLDER
// This software was created with Government support under DE
// AC05-76RL01830 awarded by the United States Department of
// Energy. The Government has certain rights in the software.
/// One implementation of GUPS. This does no load-balancing, and may
/// suffer from some load imbalance.
#include <Grappa.hpp>
#include "ForkJoin.hpp"
#include "GlobalAllocator.hpp"
#include "GlobalTaskJoiner.hpp"
#include "Array.hpp"
#include <boost/test/unit_test.hpp>
DEFINE_int64( repeats, 1, "Repeats" );
DEFINE_int64( iterations, 1 << 30, "Iterations" );
DEFINE_int64( sizeA, 1000, "Size of array that gups increments" );
double wall_clock_time() {
const double nano = 1.0e-9;
timespec t;
clock_gettime( CLOCK_MONOTONIC, &t );
return nano * t.tv_nsec + t.tv_sec;
}
BOOST_AUTO_TEST_SUITE( Gups_tests );
LOOP_FUNCTION( func_start_profiling, index ) {
Grappa_start_profiling();
}
LOOP_FUNCTION( func_stop_profiling, index ) {
Grappa_stop_profiling();
}
/// Functor to execute one GUP.
static GlobalAddress<int64_t> Array;
static int64_t * base;
LOOP_FUNCTOR( func_gups, index, ((GlobalAddress<int64_t>, _Array)) ) {
Array = _Array;
base = Array.localize();
}
void func_gups_x(int64_t * p) {
const uint64_t LARGE_PRIME = 18446744073709551557UL;
/* across all nodes and all calls, each instance of index in [0.. iterations)
** must be encounted exactly once */
//uint64_t index = random() + Grappa_mynode();//(p - base) * Grappa_nodes() + Grappa_mynode();
//uint64_t b = (index*LARGE_PRIME) % FLAGS_sizeA;
static uint64_t index = 1;
uint64_t b = ((Grappa_mynode() + index++) *LARGE_PRIME) & 1023;
//fprintf(stderr, "%d ", b);
ff_delegate_add( Array + b, (const int64_t &) 1 );
}
void validate(GlobalAddress<uint64_t> A, size_t n) {
int total = 0, max = 0, min = INT_MAX;
double sum_sqr = 0.0;
for (int i = 0; i < n; i++) {
int tmp = Grappa_delegate_read_word(A+i);
total += tmp;
sum_sqr += tmp*tmp;
max = tmp > max ? tmp : max;
min = tmp < min ? tmp : min;
}
fprintf(stderr, "Validation: total updates %d; min %d; max %d; avg value %g; std dev %g\n",
total, min, max, total/((double)n), sqrt(sum_sqr/n - ((total/n)*total/n)));
}
void user_main( int * args ) {
fprintf(stderr, "Entering user_main\n");
func_start_profiling start_profiling;
func_stop_profiling stop_profiling;
GlobalAddress<int64_t> A = Grappa_typed_malloc<int64_t>(FLAGS_sizeA);
fprintf(stderr, "user_main: Allocated global array of %d integers\n", FLAGS_sizeA);
fprintf(stderr, "user_main: Will run %d iterations\n", FLAGS_iterations);
func_gups gups( A );
double runtime = 0.0;
double throughput = 0.0;
int nnodes = atoi(getenv("SLURM_NNODES"));
double throughput_per_node = 0.0;
Grappa_add_profiling_value( &runtime, "runtime", "s", false, 0.0 );
Grappa_add_profiling_integer( &FLAGS_iterations, "iterations", "it", false, 0 );
Grappa_add_profiling_integer( &FLAGS_sizeA, "sizeA", "entries", false, 0 );
Grappa_add_profiling_value( &throughput, "updates_per_s", "up/s", false, 0.0 );
Grappa_add_profiling_value( &throughput_per_node, "updates_per_s_per_node", "up/s", false, 0.0 );
do {
Grappa_memset_local(A, 0, FLAGS_sizeA);
fork_join_custom( &start_profiling );
double start = wall_clock_time();
fork_join_custom( &gups );
printf ("Yeahoow!\n");
forall_local <int64_t, func_gups_x> (A, FLAGS_iterations);
double end = wall_clock_time();
fork_join_custom( &stop_profiling );
runtime = end - start;
throughput = FLAGS_iterations / runtime;
throughput_per_node = throughput/nnodes;
validate(A, FLAGS_sizeA);
Grappa_merge_and_dump_stats();
LOG(INFO) << "GUPS: "
<< FLAGS_iterations << " updates at "
<< throughput << "updates/s ("
<< throughput/nnodes << " updates/s/node).";
} while (FLAGS_repeats-- > 1);
}
BOOST_AUTO_TEST_CASE( test1 ) {
Grappa_init( &(boost::unit_test::framework::master_test_suite().argc),
&(boost::unit_test::framework::master_test_suite().argv) );
Grappa_activate();
Grappa_run_user_main( &user_main, (int*)NULL );
Grappa_finish( 0 );
}
BOOST_AUTO_TEST_SUITE_END();
<|endoftext|> |
<commit_before>//===- InstrInfoEmitter.cpp - Generate a Instruction Set Desc. ------------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This tablegen backend is responsible for emitting a description of the target
// instruction set for the code generator.
//
//===----------------------------------------------------------------------===//
#include "InstrInfoEmitter.h"
#include "CodeGenTarget.h"
#include "llvm/Target/TargetInstrInfo.h"
#include "Record.h"
#include <algorithm>
using namespace llvm;
// runEnums - Print out enum values for all of the instructions.
void InstrInfoEmitter::runEnums(std::ostream &OS) {
EmitSourceFileHeader("Target Instruction Enum Values", OS);
OS << "namespace llvm {\n\n";
CodeGenTarget Target;
// We must emit the PHI opcode first...
std::string Namespace;
for (CodeGenTarget::inst_iterator II = Target.inst_begin(),
E = Target.inst_end(); II != E; ++II) {
if (II->second.Namespace != "TargetInstrInfo") {
Namespace = II->second.Namespace;
break;
}
}
if (Namespace.empty()) {
std::cerr << "No instructions defined!\n";
exit(1);
}
std::vector<const CodeGenInstruction*> NumberedInstructions;
Target.getInstructionsByEnumValue(NumberedInstructions);
OS << "namespace " << Namespace << " {\n";
OS << " enum {\n";
for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
OS << " " << NumberedInstructions[i]->TheDef->getName()
<< "\t= " << i << ",\n";
}
OS << " INSTRUCTION_LIST_END = " << NumberedInstructions.size() << "\n";
OS << " };\n}\n";
OS << "} // End llvm namespace \n";
}
void InstrInfoEmitter::printDefList(const std::vector<Record*> &Uses,
unsigned Num, std::ostream &OS) const {
OS << "static const unsigned ImplicitList" << Num << "[] = { ";
for (unsigned i = 0, e = Uses.size(); i != e; ++i)
OS << getQualifiedName(Uses[i]) << ", ";
OS << "0 };\n";
}
std::vector<std::string>
InstrInfoEmitter::GetOperandInfo(const CodeGenInstruction &Inst) {
std::vector<std::string> Result;
for (unsigned i = 0, e = Inst.OperandList.size(); i != e; ++i) {
// Handle aggregate operands and normal operands the same way by expanding
// either case into a list of operands for this op.
std::vector<CodeGenInstruction::OperandInfo> OperandList;
// This might be a multiple operand thing. Targets like X86 have
// registers in their multi-operand operands. It may also be an anonymous
// operand, which has a single operand, but no declared class for the
// operand.
DagInit *MIOI = Inst.OperandList[i].MIOperandInfo;
if (!MIOI || MIOI->getNumArgs() == 0) {
// Single, anonymous, operand.
OperandList.push_back(Inst.OperandList[i]);
} else {
for (unsigned j = 0, e = Inst.OperandList[i].MINumOperands; j != e; ++j) {
OperandList.push_back(Inst.OperandList[i]);
Record *OpR = dynamic_cast<DefInit*>(MIOI->getArg(j))->getDef();
OperandList.back().Rec = OpR;
}
}
for (unsigned j = 0, e = OperandList.size(); j != e; ++j) {
Record *OpR = OperandList[j].Rec;
std::string Res;
if (OpR->isSubClassOf("RegisterClass"))
Res += getQualifiedName(OpR) + "RegClassID, ";
else
Res += "0, ";
// Fill in applicable flags.
Res += "0";
// Ptr value whose register class is resolved via callback.
if (OpR->getName() == "ptr_rc")
Res += "|M_LOOK_UP_PTR_REG_CLASS";
// Predicate operands. Check to see if the original unexpanded operand
// was of type PredicateOperand.
if (j == 0 && Inst.OperandList[i].Rec->isSubClassOf("PredicateOperand"))
Res += "|M_PREDICATE_OPERAND";
// Fill in constraint info.
Res += ", " + Inst.OperandList[i].Constraints[j];
Result.push_back(Res);
}
}
return Result;
}
// run - Emit the main instruction description records for the target...
void InstrInfoEmitter::run(std::ostream &OS) {
GatherItinClasses();
EmitSourceFileHeader("Target Instruction Descriptors", OS);
OS << "namespace llvm {\n\n";
CodeGenTarget Target;
const std::string &TargetName = Target.getName();
Record *InstrInfo = Target.getInstructionSet();
// Keep track of all of the def lists we have emitted already.
std::map<std::vector<Record*>, unsigned> EmittedLists;
unsigned ListNumber = 0;
// Emit all of the instruction's implicit uses and defs.
for (CodeGenTarget::inst_iterator II = Target.inst_begin(),
E = Target.inst_end(); II != E; ++II) {
Record *Inst = II->second.TheDef;
std::vector<Record*> Uses = Inst->getValueAsListOfDefs("Uses");
if (!Uses.empty()) {
unsigned &IL = EmittedLists[Uses];
if (!IL) printDefList(Uses, IL = ++ListNumber, OS);
}
std::vector<Record*> Defs = Inst->getValueAsListOfDefs("Defs");
if (!Defs.empty()) {
unsigned &IL = EmittedLists[Defs];
if (!IL) printDefList(Defs, IL = ++ListNumber, OS);
}
}
std::map<std::vector<std::string>, unsigned> OperandInfosEmitted;
unsigned OperandListNum = 0;
OperandInfosEmitted[std::vector<std::string>()] = ++OperandListNum;
// Emit all of the operand info records.
OS << "\n";
for (CodeGenTarget::inst_iterator II = Target.inst_begin(),
E = Target.inst_end(); II != E; ++II) {
std::vector<std::string> OperandInfo = GetOperandInfo(II->second);
unsigned &N = OperandInfosEmitted[OperandInfo];
if (N == 0) {
N = ++OperandListNum;
OS << "static const TargetOperandInfo OperandInfo" << N << "[] = { ";
for (unsigned i = 0, e = OperandInfo.size(); i != e; ++i)
OS << "{ " << OperandInfo[i] << " }, ";
OS << "};\n";
}
}
// Emit all of the TargetInstrDescriptor records in their ENUM ordering.
//
OS << "\nstatic const TargetInstrDescriptor " << TargetName
<< "Insts[] = {\n";
std::vector<const CodeGenInstruction*> NumberedInstructions;
Target.getInstructionsByEnumValue(NumberedInstructions);
for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i)
emitRecord(*NumberedInstructions[i], i, InstrInfo, EmittedLists,
OperandInfosEmitted, OS);
OS << "};\n";
OS << "} // End llvm namespace \n";
}
void InstrInfoEmitter::emitRecord(const CodeGenInstruction &Inst, unsigned Num,
Record *InstrInfo,
std::map<std::vector<Record*>, unsigned> &EmittedLists,
std::map<std::vector<std::string>, unsigned> &OpInfo,
std::ostream &OS) {
int MinOperands;
if (!Inst.OperandList.empty())
// Each logical operand can be multiple MI operands.
MinOperands = Inst.OperandList.back().MIOperandNo +
Inst.OperandList.back().MINumOperands;
else
MinOperands = 0;
OS << " { \"";
if (Inst.Name.empty())
OS << Inst.TheDef->getName();
else
OS << Inst.Name;
unsigned ItinClass = !IsItineraries ? 0 :
ItinClassNumber(Inst.TheDef->getValueAsDef("Itinerary")->getName());
OS << "\",\t" << MinOperands << ", " << ItinClass
<< ", 0";
// Try to determine (from the pattern), if the instruction is a store.
bool isStore = false;
if (dynamic_cast<ListInit*>(Inst.TheDef->getValueInit("Pattern"))) {
ListInit *LI = Inst.TheDef->getValueAsListInit("Pattern");
if (LI && LI->getSize() > 0) {
DagInit *Dag = (DagInit *)LI->getElement(0);
DefInit *OpDef = dynamic_cast<DefInit*>(Dag->getOperator());
if (OpDef) {
Record *Operator = OpDef->getDef();
if (Operator->isSubClassOf("SDNode")) {
const std::string Opcode = Operator->getValueAsString("Opcode");
if (Opcode == "ISD::STORE" || Opcode == "ISD::TRUNCSTORE")
isStore = true;
}
}
}
}
// Emit all of the target indepedent flags...
if (Inst.isReturn) OS << "|M_RET_FLAG";
if (Inst.isBranch) OS << "|M_BRANCH_FLAG";
if (Inst.isBarrier) OS << "|M_BARRIER_FLAG";
if (Inst.hasDelaySlot) OS << "|M_DELAY_SLOT_FLAG";
if (Inst.isCall) OS << "|M_CALL_FLAG";
if (Inst.isLoad) OS << "|M_LOAD_FLAG";
if (Inst.isStore || isStore) OS << "|M_STORE_FLAG";
if (Inst.isPredicated) OS << "|M_PREDICATED";
if (Inst.isConvertibleToThreeAddress) OS << "|M_CONVERTIBLE_TO_3_ADDR";
if (Inst.isCommutable) OS << "|M_COMMUTABLE";
if (Inst.isTerminator) OS << "|M_TERMINATOR_FLAG";
if (Inst.usesCustomDAGSchedInserter)
OS << "|M_USES_CUSTOM_DAG_SCHED_INSERTION";
if (Inst.hasVariableNumberOfOperands)
OS << "|M_VARIABLE_OPS";
OS << ", 0";
// Emit all of the target-specific flags...
ListInit *LI = InstrInfo->getValueAsListInit("TSFlagsFields");
ListInit *Shift = InstrInfo->getValueAsListInit("TSFlagsShifts");
if (LI->getSize() != Shift->getSize())
throw "Lengths of " + InstrInfo->getName() +
":(TargetInfoFields, TargetInfoPositions) must be equal!";
for (unsigned i = 0, e = LI->getSize(); i != e; ++i)
emitShiftedValue(Inst.TheDef, dynamic_cast<StringInit*>(LI->getElement(i)),
dynamic_cast<IntInit*>(Shift->getElement(i)), OS);
OS << ", ";
// Emit the implicit uses and defs lists...
std::vector<Record*> UseList = Inst.TheDef->getValueAsListOfDefs("Uses");
if (UseList.empty())
OS << "NULL, ";
else
OS << "ImplicitList" << EmittedLists[UseList] << ", ";
std::vector<Record*> DefList = Inst.TheDef->getValueAsListOfDefs("Defs");
if (DefList.empty())
OS << "NULL, ";
else
OS << "ImplicitList" << EmittedLists[DefList] << ", ";
// Emit the operand info.
std::vector<std::string> OperandInfo = GetOperandInfo(Inst);
if (OperandInfo.empty())
OS << "0";
else
OS << "OperandInfo" << OpInfo[OperandInfo];
OS << " }, // Inst #" << Num << " = " << Inst.TheDef->getName() << "\n";
}
struct LessRecord {
bool operator()(const Record *Rec1, const Record *Rec2) const {
return Rec1->getName() < Rec2->getName();
}
};
void InstrInfoEmitter::GatherItinClasses() {
std::vector<Record*> DefList =
Records.getAllDerivedDefinitions("InstrItinClass");
IsItineraries = !DefList.empty();
if (!IsItineraries) return;
std::sort(DefList.begin(), DefList.end(), LessRecord());
for (unsigned i = 0, N = DefList.size(); i < N; i++) {
Record *Def = DefList[i];
ItinClassMap[Def->getName()] = i;
}
}
unsigned InstrInfoEmitter::ItinClassNumber(std::string ItinName) {
return ItinClassMap[ItinName];
}
void InstrInfoEmitter::emitShiftedValue(Record *R, StringInit *Val,
IntInit *ShiftInt, std::ostream &OS) {
if (Val == 0 || ShiftInt == 0)
throw std::string("Illegal value or shift amount in TargetInfo*!");
RecordVal *RV = R->getValue(Val->getValue());
int Shift = ShiftInt->getValue();
if (RV == 0 || RV->getValue() == 0) {
// This isn't an error if this is a builtin instruction.
if (R->getName() != "PHI" && R->getName() != "INLINEASM")
throw R->getName() + " doesn't have a field named '" +
Val->getValue() + "'!";
return;
}
Init *Value = RV->getValue();
if (BitInit *BI = dynamic_cast<BitInit*>(Value)) {
if (BI->getValue()) OS << "|(1<<" << Shift << ")";
return;
} else if (BitsInit *BI = dynamic_cast<BitsInit*>(Value)) {
// Convert the Bits to an integer to print...
Init *I = BI->convertInitializerTo(new IntRecTy());
if (I)
if (IntInit *II = dynamic_cast<IntInit*>(I)) {
if (II->getValue()) {
if (Shift)
OS << "|(" << II->getValue() << "<<" << Shift << ")";
else
OS << "|" << II->getValue();
}
return;
}
} else if (IntInit *II = dynamic_cast<IntInit*>(Value)) {
if (II->getValue()) {
if (Shift)
OS << "|(" << II->getValue() << "<<" << Shift << ")";
else
OS << II->getValue();
}
return;
}
std::cerr << "Unhandled initializer: " << *Val << "\n";
throw "In record '" + R->getName() + "' for TSFlag emission.";
}
<commit_msg>Add opcode to TargetInstrDescriptor.<commit_after>//===- InstrInfoEmitter.cpp - Generate a Instruction Set Desc. ------------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This tablegen backend is responsible for emitting a description of the target
// instruction set for the code generator.
//
//===----------------------------------------------------------------------===//
#include "InstrInfoEmitter.h"
#include "CodeGenTarget.h"
#include "llvm/Target/TargetInstrInfo.h"
#include "Record.h"
#include <algorithm>
using namespace llvm;
// runEnums - Print out enum values for all of the instructions.
void InstrInfoEmitter::runEnums(std::ostream &OS) {
EmitSourceFileHeader("Target Instruction Enum Values", OS);
OS << "namespace llvm {\n\n";
CodeGenTarget Target;
// We must emit the PHI opcode first...
std::string Namespace;
for (CodeGenTarget::inst_iterator II = Target.inst_begin(),
E = Target.inst_end(); II != E; ++II) {
if (II->second.Namespace != "TargetInstrInfo") {
Namespace = II->second.Namespace;
break;
}
}
if (Namespace.empty()) {
std::cerr << "No instructions defined!\n";
exit(1);
}
std::vector<const CodeGenInstruction*> NumberedInstructions;
Target.getInstructionsByEnumValue(NumberedInstructions);
OS << "namespace " << Namespace << " {\n";
OS << " enum {\n";
for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
OS << " " << NumberedInstructions[i]->TheDef->getName()
<< "\t= " << i << ",\n";
}
OS << " INSTRUCTION_LIST_END = " << NumberedInstructions.size() << "\n";
OS << " };\n}\n";
OS << "} // End llvm namespace \n";
}
void InstrInfoEmitter::printDefList(const std::vector<Record*> &Uses,
unsigned Num, std::ostream &OS) const {
OS << "static const unsigned ImplicitList" << Num << "[] = { ";
for (unsigned i = 0, e = Uses.size(); i != e; ++i)
OS << getQualifiedName(Uses[i]) << ", ";
OS << "0 };\n";
}
std::vector<std::string>
InstrInfoEmitter::GetOperandInfo(const CodeGenInstruction &Inst) {
std::vector<std::string> Result;
for (unsigned i = 0, e = Inst.OperandList.size(); i != e; ++i) {
// Handle aggregate operands and normal operands the same way by expanding
// either case into a list of operands for this op.
std::vector<CodeGenInstruction::OperandInfo> OperandList;
// This might be a multiple operand thing. Targets like X86 have
// registers in their multi-operand operands. It may also be an anonymous
// operand, which has a single operand, but no declared class for the
// operand.
DagInit *MIOI = Inst.OperandList[i].MIOperandInfo;
if (!MIOI || MIOI->getNumArgs() == 0) {
// Single, anonymous, operand.
OperandList.push_back(Inst.OperandList[i]);
} else {
for (unsigned j = 0, e = Inst.OperandList[i].MINumOperands; j != e; ++j) {
OperandList.push_back(Inst.OperandList[i]);
Record *OpR = dynamic_cast<DefInit*>(MIOI->getArg(j))->getDef();
OperandList.back().Rec = OpR;
}
}
for (unsigned j = 0, e = OperandList.size(); j != e; ++j) {
Record *OpR = OperandList[j].Rec;
std::string Res;
if (OpR->isSubClassOf("RegisterClass"))
Res += getQualifiedName(OpR) + "RegClassID, ";
else
Res += "0, ";
// Fill in applicable flags.
Res += "0";
// Ptr value whose register class is resolved via callback.
if (OpR->getName() == "ptr_rc")
Res += "|M_LOOK_UP_PTR_REG_CLASS";
// Predicate operands. Check to see if the original unexpanded operand
// was of type PredicateOperand.
if (j == 0 && Inst.OperandList[i].Rec->isSubClassOf("PredicateOperand"))
Res += "|M_PREDICATE_OPERAND";
// Fill in constraint info.
Res += ", " + Inst.OperandList[i].Constraints[j];
Result.push_back(Res);
}
}
return Result;
}
// run - Emit the main instruction description records for the target...
void InstrInfoEmitter::run(std::ostream &OS) {
GatherItinClasses();
EmitSourceFileHeader("Target Instruction Descriptors", OS);
OS << "namespace llvm {\n\n";
CodeGenTarget Target;
const std::string &TargetName = Target.getName();
Record *InstrInfo = Target.getInstructionSet();
// Keep track of all of the def lists we have emitted already.
std::map<std::vector<Record*>, unsigned> EmittedLists;
unsigned ListNumber = 0;
// Emit all of the instruction's implicit uses and defs.
for (CodeGenTarget::inst_iterator II = Target.inst_begin(),
E = Target.inst_end(); II != E; ++II) {
Record *Inst = II->second.TheDef;
std::vector<Record*> Uses = Inst->getValueAsListOfDefs("Uses");
if (!Uses.empty()) {
unsigned &IL = EmittedLists[Uses];
if (!IL) printDefList(Uses, IL = ++ListNumber, OS);
}
std::vector<Record*> Defs = Inst->getValueAsListOfDefs("Defs");
if (!Defs.empty()) {
unsigned &IL = EmittedLists[Defs];
if (!IL) printDefList(Defs, IL = ++ListNumber, OS);
}
}
std::map<std::vector<std::string>, unsigned> OperandInfosEmitted;
unsigned OperandListNum = 0;
OperandInfosEmitted[std::vector<std::string>()] = ++OperandListNum;
// Emit all of the operand info records.
OS << "\n";
for (CodeGenTarget::inst_iterator II = Target.inst_begin(),
E = Target.inst_end(); II != E; ++II) {
std::vector<std::string> OperandInfo = GetOperandInfo(II->second);
unsigned &N = OperandInfosEmitted[OperandInfo];
if (N == 0) {
N = ++OperandListNum;
OS << "static const TargetOperandInfo OperandInfo" << N << "[] = { ";
for (unsigned i = 0, e = OperandInfo.size(); i != e; ++i)
OS << "{ " << OperandInfo[i] << " }, ";
OS << "};\n";
}
}
// Emit all of the TargetInstrDescriptor records in their ENUM ordering.
//
OS << "\nstatic const TargetInstrDescriptor " << TargetName
<< "Insts[] = {\n";
std::vector<const CodeGenInstruction*> NumberedInstructions;
Target.getInstructionsByEnumValue(NumberedInstructions);
for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i)
emitRecord(*NumberedInstructions[i], i, InstrInfo, EmittedLists,
OperandInfosEmitted, OS);
OS << "};\n";
OS << "} // End llvm namespace \n";
}
void InstrInfoEmitter::emitRecord(const CodeGenInstruction &Inst, unsigned Num,
Record *InstrInfo,
std::map<std::vector<Record*>, unsigned> &EmittedLists,
std::map<std::vector<std::string>, unsigned> &OpInfo,
std::ostream &OS) {
int MinOperands;
if (!Inst.OperandList.empty())
// Each logical operand can be multiple MI operands.
MinOperands = Inst.OperandList.back().MIOperandNo +
Inst.OperandList.back().MINumOperands;
else
MinOperands = 0;
OS << " { ";
OS << Num << ",\t" << MinOperands << ",\t\"";
if (Inst.Name.empty())
OS << Inst.TheDef->getName();
else
OS << Inst.Name;
unsigned ItinClass = !IsItineraries ? 0 :
ItinClassNumber(Inst.TheDef->getValueAsDef("Itinerary")->getName());
OS << "\",\t" << ItinClass << ", 0";
// Try to determine (from the pattern), if the instruction is a store.
bool isStore = false;
if (dynamic_cast<ListInit*>(Inst.TheDef->getValueInit("Pattern"))) {
ListInit *LI = Inst.TheDef->getValueAsListInit("Pattern");
if (LI && LI->getSize() > 0) {
DagInit *Dag = (DagInit *)LI->getElement(0);
DefInit *OpDef = dynamic_cast<DefInit*>(Dag->getOperator());
if (OpDef) {
Record *Operator = OpDef->getDef();
if (Operator->isSubClassOf("SDNode")) {
const std::string Opcode = Operator->getValueAsString("Opcode");
if (Opcode == "ISD::STORE" || Opcode == "ISD::TRUNCSTORE")
isStore = true;
}
}
}
}
// Emit all of the target indepedent flags...
if (Inst.isReturn) OS << "|M_RET_FLAG";
if (Inst.isBranch) OS << "|M_BRANCH_FLAG";
if (Inst.isBarrier) OS << "|M_BARRIER_FLAG";
if (Inst.hasDelaySlot) OS << "|M_DELAY_SLOT_FLAG";
if (Inst.isCall) OS << "|M_CALL_FLAG";
if (Inst.isLoad) OS << "|M_LOAD_FLAG";
if (Inst.isStore || isStore) OS << "|M_STORE_FLAG";
if (Inst.isPredicated) OS << "|M_PREDICATED";
if (Inst.isConvertibleToThreeAddress) OS << "|M_CONVERTIBLE_TO_3_ADDR";
if (Inst.isCommutable) OS << "|M_COMMUTABLE";
if (Inst.isTerminator) OS << "|M_TERMINATOR_FLAG";
if (Inst.usesCustomDAGSchedInserter)
OS << "|M_USES_CUSTOM_DAG_SCHED_INSERTION";
if (Inst.hasVariableNumberOfOperands)
OS << "|M_VARIABLE_OPS";
OS << ", 0";
// Emit all of the target-specific flags...
ListInit *LI = InstrInfo->getValueAsListInit("TSFlagsFields");
ListInit *Shift = InstrInfo->getValueAsListInit("TSFlagsShifts");
if (LI->getSize() != Shift->getSize())
throw "Lengths of " + InstrInfo->getName() +
":(TargetInfoFields, TargetInfoPositions) must be equal!";
for (unsigned i = 0, e = LI->getSize(); i != e; ++i)
emitShiftedValue(Inst.TheDef, dynamic_cast<StringInit*>(LI->getElement(i)),
dynamic_cast<IntInit*>(Shift->getElement(i)), OS);
OS << ", ";
// Emit the implicit uses and defs lists...
std::vector<Record*> UseList = Inst.TheDef->getValueAsListOfDefs("Uses");
if (UseList.empty())
OS << "NULL, ";
else
OS << "ImplicitList" << EmittedLists[UseList] << ", ";
std::vector<Record*> DefList = Inst.TheDef->getValueAsListOfDefs("Defs");
if (DefList.empty())
OS << "NULL, ";
else
OS << "ImplicitList" << EmittedLists[DefList] << ", ";
// Emit the operand info.
std::vector<std::string> OperandInfo = GetOperandInfo(Inst);
if (OperandInfo.empty())
OS << "0";
else
OS << "OperandInfo" << OpInfo[OperandInfo];
OS << " }, // Inst #" << Num << " = " << Inst.TheDef->getName() << "\n";
}
struct LessRecord {
bool operator()(const Record *Rec1, const Record *Rec2) const {
return Rec1->getName() < Rec2->getName();
}
};
void InstrInfoEmitter::GatherItinClasses() {
std::vector<Record*> DefList =
Records.getAllDerivedDefinitions("InstrItinClass");
IsItineraries = !DefList.empty();
if (!IsItineraries) return;
std::sort(DefList.begin(), DefList.end(), LessRecord());
for (unsigned i = 0, N = DefList.size(); i < N; i++) {
Record *Def = DefList[i];
ItinClassMap[Def->getName()] = i;
}
}
unsigned InstrInfoEmitter::ItinClassNumber(std::string ItinName) {
return ItinClassMap[ItinName];
}
void InstrInfoEmitter::emitShiftedValue(Record *R, StringInit *Val,
IntInit *ShiftInt, std::ostream &OS) {
if (Val == 0 || ShiftInt == 0)
throw std::string("Illegal value or shift amount in TargetInfo*!");
RecordVal *RV = R->getValue(Val->getValue());
int Shift = ShiftInt->getValue();
if (RV == 0 || RV->getValue() == 0) {
// This isn't an error if this is a builtin instruction.
if (R->getName() != "PHI" && R->getName() != "INLINEASM")
throw R->getName() + " doesn't have a field named '" +
Val->getValue() + "'!";
return;
}
Init *Value = RV->getValue();
if (BitInit *BI = dynamic_cast<BitInit*>(Value)) {
if (BI->getValue()) OS << "|(1<<" << Shift << ")";
return;
} else if (BitsInit *BI = dynamic_cast<BitsInit*>(Value)) {
// Convert the Bits to an integer to print...
Init *I = BI->convertInitializerTo(new IntRecTy());
if (I)
if (IntInit *II = dynamic_cast<IntInit*>(I)) {
if (II->getValue()) {
if (Shift)
OS << "|(" << II->getValue() << "<<" << Shift << ")";
else
OS << "|" << II->getValue();
}
return;
}
} else if (IntInit *II = dynamic_cast<IntInit*>(Value)) {
if (II->getValue()) {
if (Shift)
OS << "|(" << II->getValue() << "<<" << Shift << ")";
else
OS << II->getValue();
}
return;
}
std::cerr << "Unhandled initializer: " << *Val << "\n";
throw "In record '" + R->getName() + "' for TSFlag emission.";
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: salframe.cxx,v $
*
* $Revision: 1.43 $
*
* last change: $Author: pluby $ $Date: 2001-03-07 04:39:53 $
*
* 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 <string.h>
#define _SV_SALFRAME_CXX
#ifndef _SV_SALDATA_HXX
#include <saldata.hxx>
#endif
#ifndef _SV_SALGDI_HXX
#include <salgdi.hxx>
#endif
#ifndef _SV_SALFRAME_HXX
#include <salframe.hxx>
#endif
#ifndef _SV_VCLWINDOW_H
#include <VCLWindow.h>
#endif
#ifndef _SV_VCLGRAPHICS_H
#include <VCLGraphics.h>
#endif
// =======================================================================
static long ImplSalFrameCallbackDummy( void*, SalFrame*, USHORT, const void* )
{
return 0;
}
// =======================================================================
SalFrame::SalFrame()
{
SalData* pSalData = GetSalData();
maFrameData.mhWnd = NULL;
maFrameData.mpGraphics = NULL;
maFrameData.mpInst = NULL;
maFrameData.mpProc = ImplSalFrameCallbackDummy;
maFrameData.mnWidth = 0;
maFrameData.mnHeight = 0;
maFrameData.mbGraphics = FALSE;
// insert frame in framelist
maFrameData.mpNextFrame = pSalData->mpFirstFrame;
pSalData->mpFirstFrame = this;
}
// -----------------------------------------------------------------------
SalFrame::~SalFrame()
{
SalData* pSalData = GetSalData();
if ( maFrameData.mpGraphics )
delete maFrameData.mpGraphics;
if ( maFrameData.mhWnd )
VCLWindow_Release( maFrameData.mhWnd );
// remove frame from framelist
if ( this == pSalData->mpFirstFrame )
pSalData->mpFirstFrame = maFrameData.mpNextFrame;
else
{
SalFrame* pTempFrame = pSalData->mpFirstFrame;
while ( pTempFrame->maFrameData.mpNextFrame != this )
pTempFrame = pTempFrame->maFrameData.mpNextFrame;
pTempFrame->maFrameData.mpNextFrame = maFrameData.mpNextFrame;
}
}
// -----------------------------------------------------------------------
SalGraphics* SalFrame::GetGraphics()
{
if ( maFrameData.mbGraphics )
return NULL;
if ( !maFrameData.mpGraphics )
{
VCLVIEW hView = NULL;
SalFrame *pFrame = this;
// Search for the parent SalFrame that has a native window and
// use that window to get an NSView
while ( !pFrame->maFrameData.mhWnd ) {
pFrame = pFrame->maFrameData.mpParent;
if ( !pFrame )
break;
}
hView = VCLWindow_ContentView( pFrame->maFrameData.mhWnd );
if ( hView )
{
maFrameData.mpGraphics = new SalGraphics;
maFrameData.mpGraphics->maGraphicsData.mhDC = hView;
maFrameData.mpGraphics->maGraphicsData.mbPrinter = FALSE;
maFrameData.mpGraphics->maGraphicsData.mbVirDev = FALSE;
maFrameData.mpGraphics->maGraphicsData.mbWindow = TRUE;
maFrameData.mpGraphics->maGraphicsData.mbScreen = TRUE;
}
}
maFrameData.mbGraphics = TRUE;
return maFrameData.mpGraphics;
}
// -----------------------------------------------------------------------
void SalFrame::ReleaseGraphics( SalGraphics *pGraphics )
{
maFrameData.mbGraphics = FALSE;
}
// -----------------------------------------------------------------------
BOOL SalFrame::PostEvent( void *pData )
{
return VCLWindow_PostEvent( maFrameData.mhWnd, pData );
}
// -----------------------------------------------------------------------
void SalFrame::SetTitle( const XubString& rTitle )
{
ByteString aByteTitle( rTitle, gsl_getSystemTextEncoding() );
char *pTitle = (char *)aByteTitle.GetBuffer();
if ( maFrameData.mhWnd )
VCLWindow_SetTitle( maFrameData.mhWnd, pTitle );
}
// -----------------------------------------------------------------------
void SalFrame::SetIcon( USHORT nIcon )
{
}
// -----------------------------------------------------------------------
void SalFrame::Show( BOOL bVisible )
{
if ( bVisible )
{
if ( maFrameData.mhWnd )
VCLWindow_Show( maFrameData.mhWnd );
} // if
else
{
if ( maFrameData.mhWnd )
{
VCLWindow_Close( maFrameData.mhWnd );
if ( maFrameData.mpParent )
maFrameData.mpParent->Show( TRUE );
}
} // else
} // SalFrame::Show
// -----------------------------------------------------------------------
void SalFrame::Enable( BOOL bEnable )
{
}
// -----------------------------------------------------------------------
void SalFrame::SetMinClientSize( long nWidth, long nHeight )
{
}
// -----------------------------------------------------------------------
void SalFrame::SetClientSize( long nWidth, long nHeight )
{
maFrameData.mnWidth = nWidth;
maFrameData.mnHeight = nHeight;
// If this is a native window, resize it
if ( maFrameData.mhWnd )
VCLWindow_SetSize( maFrameData.mhWnd, nWidth, nHeight );
}
// -----------------------------------------------------------------------
void SalFrame::GetClientSize( long& rWidth, long& rHeight )
{
rWidth = maFrameData.mnWidth;
rHeight = maFrameData.mnHeight;
}
// -----------------------------------------------------------------------
void SalFrame::SetWindowState( const SalFrameState* pState )
{
}
// -----------------------------------------------------------------------
BOOL SalFrame::GetWindowState( SalFrameState* pState )
{
return FALSE;
}
// -----------------------------------------------------------------------
void SalFrame::ShowFullScreen( BOOL bFullScreen )
{
}
// -----------------------------------------------------------------------
void SalFrame::StartPresentation( BOOL bStart )
{
}
// -----------------------------------------------------------------------
void SalFrame::SetAlwaysOnTop( BOOL bOnTop )
{
}
// -----------------------------------------------------------------------
void SalFrame::ToTop( USHORT nFlags )
{
if ( maFrameData.mhWnd )
VCLWindow_Show( maFrameData.mhWnd );
}
// -----------------------------------------------------------------------
void SalFrame::SetPointer( PointerStyle ePointerStyle )
{
}
// -----------------------------------------------------------------------
void SalFrame::CaptureMouse( BOOL bCapture )
{
}
// -----------------------------------------------------------------------
void SalFrame::SetPointerPos( long nX, long nY )
{
}
// -----------------------------------------------------------------------
void SalFrame::Flush()
{
}
// -----------------------------------------------------------------------
void SalFrame::Sync()
{
}
// -----------------------------------------------------------------------
void SalFrame::SetInputContext( SalInputContext* pContext )
{
}
// -----------------------------------------------------------------------
void SalFrame::EndExtTextInput( USHORT nFlags )
{
}
// -----------------------------------------------------------------------
XubString SalFrame::GetKeyName( USHORT nKeyCode )
{
return XubString();
}
// -----------------------------------------------------------------------
XubString SalFrame::GetSymbolKeyName( const XubString&, USHORT nKeyCode )
{
return GetKeyName( nKeyCode );
}
// -----------------------------------------------------------------------
void SalFrame::UpdateSettings( AllSettings& rSettings )
{
}
// -----------------------------------------------------------------------
const SystemEnvData* SalFrame::GetSystemData() const
{
return NULL;
}
// -----------------------------------------------------------------------
void SalFrame::Beep( SoundType eSoundType )
{
VCLWindow_Beep();
}
// -----------------------------------------------------------------------
void SalFrame::SetCallback( void* pInst, SALFRAMEPROC pProc )
{
maFrameData.mpInst = pInst;
if ( pProc )
maFrameData.mpProc = pProc;
else
maFrameData.mpProc = ImplSalFrameCallbackDummy;
}
<commit_msg>Added more comprehensive posting of user events<commit_after>/*************************************************************************
*
* $RCSfile: salframe.cxx,v $
*
* $Revision: 1.44 $
*
* last change: $Author: pluby $ $Date: 2001-03-19 16:31: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): _______________________________________
*
*
************************************************************************/
#include <string.h>
#define _SV_SALFRAME_CXX
#ifndef _SV_SALDATA_HXX
#include <saldata.hxx>
#endif
#ifndef _SV_SALGDI_HXX
#include <salgdi.hxx>
#endif
#ifndef _SV_SALFRAME_HXX
#include <salframe.hxx>
#endif
#ifndef _SV_VCLWINDOW_H
#include <VCLWindow.h>
#endif
#ifndef _SV_VCLGRAPHICS_H
#include <VCLGraphics.h>
#endif
// =======================================================================
static long ImplSalFrameCallbackDummy( void*, SalFrame*, USHORT, const void* )
{
return 0;
}
// =======================================================================
SalFrame::SalFrame()
{
SalData* pSalData = GetSalData();
maFrameData.mhWnd = NULL;
maFrameData.mpGraphics = NULL;
maFrameData.mpInst = NULL;
maFrameData.mpProc = ImplSalFrameCallbackDummy;
maFrameData.mnWidth = 0;
maFrameData.mnHeight = 0;
maFrameData.mbGraphics = FALSE;
// insert frame in framelist
maFrameData.mpNextFrame = pSalData->mpFirstFrame;
pSalData->mpFirstFrame = this;
}
// -----------------------------------------------------------------------
SalFrame::~SalFrame()
{
SalData* pSalData = GetSalData();
if ( maFrameData.mpGraphics )
delete maFrameData.mpGraphics;
if ( maFrameData.mhWnd )
VCLWindow_Release( maFrameData.mhWnd );
// remove frame from framelist
if ( this == pSalData->mpFirstFrame )
pSalData->mpFirstFrame = maFrameData.mpNextFrame;
else
{
SalFrame* pTempFrame = pSalData->mpFirstFrame;
while ( pTempFrame->maFrameData.mpNextFrame != this )
pTempFrame = pTempFrame->maFrameData.mpNextFrame;
pTempFrame->maFrameData.mpNextFrame = maFrameData.mpNextFrame;
}
}
// -----------------------------------------------------------------------
SalGraphics* SalFrame::GetGraphics()
{
if ( maFrameData.mbGraphics )
return NULL;
if ( !maFrameData.mpGraphics )
{
VCLVIEW hView = NULL;
SalFrame *pFrame = this;
// Search for the parent SalFrame that has a native window and
// use that window to get an NSView
while ( !pFrame->maFrameData.mhWnd ) {
pFrame = pFrame->maFrameData.mpParent;
if ( !pFrame )
break;
}
hView = VCLWindow_ContentView( pFrame->maFrameData.mhWnd );
if ( hView )
{
maFrameData.mpGraphics = new SalGraphics;
maFrameData.mpGraphics->maGraphicsData.mhDC = hView;
maFrameData.mpGraphics->maGraphicsData.mbPrinter = FALSE;
maFrameData.mpGraphics->maGraphicsData.mbVirDev = FALSE;
maFrameData.mpGraphics->maGraphicsData.mbWindow = TRUE;
maFrameData.mpGraphics->maGraphicsData.mbScreen = TRUE;
}
}
maFrameData.mbGraphics = TRUE;
return maFrameData.mpGraphics;
}
// -----------------------------------------------------------------------
void SalFrame::ReleaseGraphics( SalGraphics *pGraphics )
{
maFrameData.mbGraphics = FALSE;
}
// -----------------------------------------------------------------------
BOOL SalFrame::PostEvent( void *pData )
{
VCLWINDOW hWindow = NULL;
SalFrame *pFrame = this;
// Search for the parent SalFrame that has a native window and
// use that window to post the event to
while ( !pFrame->maFrameData.mhWnd ) {
pFrame = pFrame->maFrameData.mpParent;
if ( !pFrame )
break;
}
return VCLWindow_PostEvent( pFrame->maFrameData.mhWnd, pData );
}
// -----------------------------------------------------------------------
void SalFrame::SetTitle( const XubString& rTitle )
{
ByteString aByteTitle( rTitle, gsl_getSystemTextEncoding() );
char *pTitle = (char *)aByteTitle.GetBuffer();
if ( maFrameData.mhWnd )
VCLWindow_SetTitle( maFrameData.mhWnd, pTitle );
}
// -----------------------------------------------------------------------
void SalFrame::SetIcon( USHORT nIcon )
{
}
// -----------------------------------------------------------------------
void SalFrame::Show( BOOL bVisible )
{
if ( bVisible )
{
if ( maFrameData.mhWnd )
VCLWindow_Show( maFrameData.mhWnd );
} // if
else
{
if ( maFrameData.mhWnd )
{
VCLWindow_Close( maFrameData.mhWnd );
if ( maFrameData.mpParent )
maFrameData.mpParent->Show( TRUE );
}
} // else
} // SalFrame::Show
// -----------------------------------------------------------------------
void SalFrame::Enable( BOOL bEnable )
{
}
// -----------------------------------------------------------------------
void SalFrame::SetMinClientSize( long nWidth, long nHeight )
{
}
// -----------------------------------------------------------------------
void SalFrame::SetClientSize( long nWidth, long nHeight )
{
maFrameData.mnWidth = nWidth;
maFrameData.mnHeight = nHeight;
// If this is a native window, resize it
if ( maFrameData.mhWnd )
VCLWindow_SetSize( maFrameData.mhWnd, nWidth, nHeight );
}
// -----------------------------------------------------------------------
void SalFrame::GetClientSize( long& rWidth, long& rHeight )
{
rWidth = maFrameData.mnWidth;
rHeight = maFrameData.mnHeight;
}
// -----------------------------------------------------------------------
void SalFrame::SetWindowState( const SalFrameState* pState )
{
}
// -----------------------------------------------------------------------
BOOL SalFrame::GetWindowState( SalFrameState* pState )
{
return FALSE;
}
// -----------------------------------------------------------------------
void SalFrame::ShowFullScreen( BOOL bFullScreen )
{
}
// -----------------------------------------------------------------------
void SalFrame::StartPresentation( BOOL bStart )
{
}
// -----------------------------------------------------------------------
void SalFrame::SetAlwaysOnTop( BOOL bOnTop )
{
}
// -----------------------------------------------------------------------
void SalFrame::ToTop( USHORT nFlags )
{
if ( maFrameData.mhWnd )
VCLWindow_Show( maFrameData.mhWnd );
}
// -----------------------------------------------------------------------
void SalFrame::SetPointer( PointerStyle ePointerStyle )
{
}
// -----------------------------------------------------------------------
void SalFrame::CaptureMouse( BOOL bCapture )
{
}
// -----------------------------------------------------------------------
void SalFrame::SetPointerPos( long nX, long nY )
{
}
// -----------------------------------------------------------------------
void SalFrame::Flush()
{
}
// -----------------------------------------------------------------------
void SalFrame::Sync()
{
}
// -----------------------------------------------------------------------
void SalFrame::SetInputContext( SalInputContext* pContext )
{
}
// -----------------------------------------------------------------------
void SalFrame::EndExtTextInput( USHORT nFlags )
{
}
// -----------------------------------------------------------------------
XubString SalFrame::GetKeyName( USHORT nKeyCode )
{
return XubString();
}
// -----------------------------------------------------------------------
XubString SalFrame::GetSymbolKeyName( const XubString&, USHORT nKeyCode )
{
return GetKeyName( nKeyCode );
}
// -----------------------------------------------------------------------
void SalFrame::UpdateSettings( AllSettings& rSettings )
{
}
// -----------------------------------------------------------------------
const SystemEnvData* SalFrame::GetSystemData() const
{
return NULL;
}
// -----------------------------------------------------------------------
void SalFrame::Beep( SoundType eSoundType )
{
VCLWindow_Beep();
}
// -----------------------------------------------------------------------
void SalFrame::SetCallback( void* pInst, SALFRAMEPROC pProc )
{
maFrameData.mpInst = pInst;
if ( pProc )
maFrameData.mpProc = pProc;
else
maFrameData.mpProc = ImplSalFrameCallbackDummy;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2011 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/widget/native_widget_views.h"
#include "ui/gfx/compositor/compositor.h"
#include "views/desktop/desktop_window_view.h"
#include "views/view.h"
#include "views/views_delegate.h"
#include "views/widget/native_widget_view.h"
#include "views/widget/root_view.h"
#if defined(HAVE_IBUS)
#include "views/ime/input_methodc_ibus.h"
#else
#include "views/ime/mock_input_method.h"
#endif
namespace views {
////////////////////////////////////////////////////////////////////////////////
// NativeWidgetViews, public:
NativeWidgetViews::NativeWidgetViews(internal::NativeWidgetDelegate* delegate)
: delegate_(delegate),
view_(NULL),
active_(false),
minimized_(false),
ALLOW_THIS_IN_INITIALIZER_LIST(close_widget_factory_(this)),
hosting_widget_(NULL),
ownership_(Widget::InitParams::NATIVE_WIDGET_OWNS_WIDGET) {
}
NativeWidgetViews::~NativeWidgetViews() {
delegate_->OnNativeWidgetDestroying();
delegate_->OnNativeWidgetDestroyed();
if (ownership_ == Widget::InitParams::NATIVE_WIDGET_OWNS_WIDGET)
delete delegate_;
view_.reset();
}
View* NativeWidgetViews::GetView() {
return view_.get();
}
const View* NativeWidgetViews::GetView() const {
return view_.get();
}
void NativeWidgetViews::OnActivate(bool active) {
if (active_ == active)
return;
active_ = active;
delegate_->OnNativeWidgetActivationChanged(active);
InputMethod* input_method = GetInputMethodNative();
// TODO(oshima): Focus change should be separated from window activation.
// This will be fixed when we have WM API.
if (active) {
input_method->OnFocus();
// See description of got_initial_focus_in_ for details on this.
GetWidget()->GetFocusManager()->RestoreFocusedView();
} else {
input_method->OnBlur();
GetWidget()->GetFocusManager()->StoreFocusedView();
}
view_->SchedulePaint();
}
bool NativeWidgetViews::OnKeyEvent(const KeyEvent& key_event) {
GetInputMethodNative()->DispatchKeyEvent(key_event);
return true;
}
void NativeWidgetViews::DispatchKeyEventPostIME(const KeyEvent& key) {
// TODO(oshima): GTK impl handles menu_key in special way. This may be
// necessary when running under NativeWidgetX.
delegate_->OnKeyEvent(key);
}
////////////////////////////////////////////////////////////////////////////////
// NativeWidgetViews, NativeWidget implementation:
void NativeWidgetViews::InitNativeWidget(const Widget::InitParams& params) {
ownership_ = params.ownership;
view_.reset(new internal::NativeWidgetView(this));
view_->SetBoundsRect(params.bounds);
view_->SetPaintToLayer(true);
View* parent_view = NULL;
if (params.parent_widget) {
hosting_widget_ = params.parent_widget;
parent_view = hosting_widget_->GetChildViewParent();
} else {
parent_view = ViewsDelegate::views_delegate->GetDefaultParentView();
hosting_widget_ = parent_view->GetWidget();
}
parent_view->AddChildView(view_.get());
// TODO(beng): SetInitParams().
}
NonClientFrameView* NativeWidgetViews::CreateNonClientFrameView() {
return NULL;
}
void NativeWidgetViews::UpdateFrameAfterFrameChange() {
}
bool NativeWidgetViews::ShouldUseNativeFrame() const {
// NOTIMPLEMENTED();
return false;
}
void NativeWidgetViews::FrameTypeChanged() {
}
Widget* NativeWidgetViews::GetWidget() {
return delegate_->AsWidget();
}
const Widget* NativeWidgetViews::GetWidget() const {
return delegate_->AsWidget();
}
gfx::NativeView NativeWidgetViews::GetNativeView() const {
return GetParentNativeWidget()->GetNativeView();
}
gfx::NativeWindow NativeWidgetViews::GetNativeWindow() const {
return GetParentNativeWidget()->GetNativeWindow();
}
Widget* NativeWidgetViews::GetTopLevelWidget() {
if (view_->parent() == ViewsDelegate::views_delegate->GetDefaultParentView())
return GetWidget();
// During Widget destruction, this function may be called after |view_| is
// detached from a Widget, at which point this NativeWidget's Widget becomes
// the effective toplevel.
Widget* containing_widget = view_->GetWidget();
return containing_widget ? containing_widget->GetTopLevelWidget()
: GetWidget();
}
const ui::Compositor* NativeWidgetViews::GetCompositor() const {
return hosting_widget_->GetCompositor();
}
ui::Compositor* NativeWidgetViews::GetCompositor() {
return hosting_widget_->GetCompositor();
}
void NativeWidgetViews::MarkLayerDirty() {
view_->MarkLayerDirty();
}
void NativeWidgetViews::CalculateOffsetToAncestorWithLayer(gfx::Point* offset,
View** ancestor) {
view_->CalculateOffsetToAncestorWithLayer(offset, ancestor);
}
void NativeWidgetViews::ViewRemoved(View* view) {
internal::NativeWidgetPrivate* parent = GetParentNativeWidget();
if (parent)
parent->ViewRemoved(view);
}
void NativeWidgetViews::SetNativeWindowProperty(const char* name, void* value) {
NOTIMPLEMENTED();
}
void* NativeWidgetViews::GetNativeWindowProperty(const char* name) const {
NOTIMPLEMENTED();
return NULL;
}
TooltipManager* NativeWidgetViews::GetTooltipManager() const {
const internal::NativeWidgetPrivate* parent = GetParentNativeWidget();
return parent ? parent->GetTooltipManager() : NULL;
}
bool NativeWidgetViews::IsScreenReaderActive() const {
return GetParentNativeWidget()->IsScreenReaderActive();
}
void NativeWidgetViews::SendNativeAccessibilityEvent(
View* view,
ui::AccessibilityTypes::Event event_type) {
return GetParentNativeWidget()->SendNativeAccessibilityEvent(view,
event_type);
}
void NativeWidgetViews::SetMouseCapture() {
View* parent_root_view = GetParentNativeWidget()->GetWidget()->GetRootView();
static_cast<internal::RootView*>(parent_root_view)->set_capture_view(
view_.get());
GetParentNativeWidget()->SetMouseCapture();
}
void NativeWidgetViews::ReleaseMouseCapture() {
View* parent_root_view = GetParentNativeWidget()->GetWidget()->GetRootView();
static_cast<internal::RootView*>(parent_root_view)->set_capture_view(NULL);
GetParentNativeWidget()->ReleaseMouseCapture();
}
bool NativeWidgetViews::HasMouseCapture() const {
// NOTE: we may need to tweak this to only return true if the parent native
// widget's RootView has us as the capture view.
return GetParentNativeWidget()->HasMouseCapture();
}
void NativeWidgetViews::SetKeyboardCapture() {
GetParentNativeWidget()->SetKeyboardCapture();
}
void NativeWidgetViews::ReleaseKeyboardCapture() {
GetParentNativeWidget()->ReleaseKeyboardCapture();
}
bool NativeWidgetViews::HasKeyboardCapture() {
return GetParentNativeWidget()->HasKeyboardCapture();
}
InputMethod* NativeWidgetViews::GetInputMethodNative() {
if (!input_method_.get()) {
#if defined(HAVE_IBUS)
input_method_.reset(static_cast<InputMethod*>(new InputMethodIBus(this)));
#else
// TODO(suzhe|oshima): Figure out what to do on windows.
input_method_.reset(new MockInputMethod(this));
#endif
input_method_->Init(GetWidget());
}
return input_method_.get();
}
void NativeWidgetViews::ReplaceInputMethod(InputMethod* input_method) {
CHECK(input_method);
input_method_.reset(input_method);
input_method->set_delegate(this);
input_method->Init(GetWidget());
}
void NativeWidgetViews::CenterWindow(const gfx::Size& size) {
// TODO(beng): actually center.
GetView()->SetBounds(0, 0, size.width(), size.height());
}
void NativeWidgetViews::GetWindowBoundsAndMaximizedState(
gfx::Rect* bounds,
bool* maximized) const {
*bounds = GetView()->bounds();
*maximized = false;
}
void NativeWidgetViews::SetWindowTitle(const std::wstring& title) {
}
void NativeWidgetViews::SetWindowIcons(const SkBitmap& window_icon,
const SkBitmap& app_icon) {
}
void NativeWidgetViews::SetAccessibleName(const std::wstring& name) {
}
void NativeWidgetViews::SetAccessibleRole(ui::AccessibilityTypes::Role role) {
}
void NativeWidgetViews::SetAccessibleState(
ui::AccessibilityTypes::State state) {
}
void NativeWidgetViews::BecomeModal() {
NOTIMPLEMENTED();
}
gfx::Rect NativeWidgetViews::GetWindowScreenBounds() const {
if (GetWidget() == GetWidget()->GetTopLevelWidget())
return view_->bounds();
gfx::Point origin = view_->bounds().origin();
View::ConvertPointToScreen(view_->parent(), &origin);
return gfx::Rect(origin.x(), origin.y(), view_->width(), view_->height());
}
gfx::Rect NativeWidgetViews::GetClientAreaScreenBounds() const {
return GetWindowScreenBounds();
}
gfx::Rect NativeWidgetViews::GetRestoredBounds() const {
return GetWindowScreenBounds();
}
void NativeWidgetViews::SetBounds(const gfx::Rect& bounds) {
// |bounds| are supplied in the coordinates of the parent.
view_->SetBoundsRect(bounds);
}
void NativeWidgetViews::SetSize(const gfx::Size& size) {
view_->SetSize(size);
}
void NativeWidgetViews::SetBoundsConstrained(const gfx::Rect& bounds,
Widget* other_widget) {
// TODO(beng): honor other_widget.
SetBounds(bounds);
}
void NativeWidgetViews::MoveAbove(gfx::NativeView native_view) {
NOTIMPLEMENTED();
}
void NativeWidgetViews::MoveToTop() {
view_->parent()->ReorderChildView(view_.get(), -1);
}
void NativeWidgetViews::SetShape(gfx::NativeRegion region) {
NOTIMPLEMENTED();
}
void NativeWidgetViews::Close() {
Hide();
if (close_widget_factory_.empty()) {
MessageLoop::current()->PostTask(FROM_HERE,
close_widget_factory_.NewRunnableMethod(&NativeWidgetViews::CloseNow));
}
}
void NativeWidgetViews::CloseNow() {
// reset input_method before destroying widget.
input_method_.reset();
// TODO(beng): what about the other case??
if (ownership_ == Widget::InitParams::NATIVE_WIDGET_OWNS_WIDGET)
delete this;
}
void NativeWidgetViews::EnableClose(bool enable) {
}
void NativeWidgetViews::Show() {
view_->SetVisible(true);
GetWidget()->SetInitialFocus();
}
void NativeWidgetViews::Hide() {
view_->SetVisible(false);
}
void NativeWidgetViews::ShowNativeWidget(ShowState state) {
}
bool NativeWidgetViews::IsVisible() const {
return view_->IsVisible();
}
void NativeWidgetViews::Activate() {
// Enable WidgetObserverTest.ActivationChange when this is implemented.
NOTIMPLEMENTED();
}
void NativeWidgetViews::Deactivate() {
NOTIMPLEMENTED();
}
bool NativeWidgetViews::IsActive() const {
return active_;
}
void NativeWidgetViews::SetAlwaysOnTop(bool on_top) {
NOTIMPLEMENTED();
}
void NativeWidgetViews::Maximize() {
NOTIMPLEMENTED();
}
void NativeWidgetViews::Minimize() {
gfx::Rect view_bounds = view_->bounds();
gfx::Rect parent_bounds = view_->parent()->bounds();
restored_bounds_ = view_bounds;
restored_transform_ = view_->GetTransform();
float aspect_ratio = static_cast<float>(view_bounds.width()) /
static_cast<float>(view_bounds.height());
int target_size = 100;
int target_height = target_size;
int target_width = static_cast<int>(aspect_ratio * target_height);
if (target_width > target_size) {
target_width = target_size;
target_height = static_cast<int>(target_width / aspect_ratio);
}
int target_x = 20;
int target_y = parent_bounds.height() - target_size - 20;
view_->SetBounds(
target_x, target_y, view_bounds.width(), view_bounds.height());
ui::Transform transform;
transform.SetScale((float)target_width / (float)view_bounds.width(),
(float)target_height / (float)view_bounds.height());
view_->SetTransform(transform);
minimized_ = true;
}
bool NativeWidgetViews::IsMaximized() const {
// NOTIMPLEMENTED();
return false;
}
bool NativeWidgetViews::IsMinimized() const {
return minimized_;
}
void NativeWidgetViews::Restore() {
minimized_ = false;
view_->SetBoundsRect(restored_bounds_);
view_->SetTransform(restored_transform_);
}
void NativeWidgetViews::SetFullscreen(bool fullscreen) {
NOTIMPLEMENTED();
}
bool NativeWidgetViews::IsFullscreen() const {
// NOTIMPLEMENTED();
return false;
}
void NativeWidgetViews::SetOpacity(unsigned char opacity) {
NOTIMPLEMENTED();
}
void NativeWidgetViews::SetUseDragFrame(bool use_drag_frame) {
NOTIMPLEMENTED();
}
bool NativeWidgetViews::IsAccessibleWidget() const {
NOTIMPLEMENTED();
return false;
}
void NativeWidgetViews::RunShellDrag(View* view,
const ui::OSExchangeData& data,
int operation) {
GetParentNativeWidget()->RunShellDrag(view, data, operation);
}
void NativeWidgetViews::SchedulePaintInRect(const gfx::Rect& rect) {
view_->SchedulePaintInternal(rect);
}
void NativeWidgetViews::SetCursor(gfx::NativeCursor cursor) {
GetParentNativeWidget()->SetCursor(cursor);
}
void NativeWidgetViews::ClearNativeFocus() {
GetParentNativeWidget()->ClearNativeFocus();
}
void NativeWidgetViews::FocusNativeView(gfx::NativeView native_view) {
GetParentNativeWidget()->FocusNativeView(native_view);
}
////////////////////////////////////////////////////////////////////////////////
// NativeWidgetViews, private:
internal::NativeWidgetPrivate* NativeWidgetViews::GetParentNativeWidget() {
Widget* containing_widget = view_->GetWidget();
return containing_widget ? static_cast<internal::NativeWidgetPrivate*>(
containing_widget->native_widget()) :
NULL;
}
const internal::NativeWidgetPrivate*
NativeWidgetViews::GetParentNativeWidget() const {
const Widget* containing_widget = view_->GetWidget();
return containing_widget ? static_cast<const internal::NativeWidgetPrivate*>(
containing_widget->native_widget()) :
NULL;
}
} // namespace views
<commit_msg>Fix typo in header file name.<commit_after>// Copyright (c) 2011 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/widget/native_widget_views.h"
#include "ui/gfx/compositor/compositor.h"
#include "views/desktop/desktop_window_view.h"
#include "views/view.h"
#include "views/views_delegate.h"
#include "views/widget/native_widget_view.h"
#include "views/widget/root_view.h"
#if defined(HAVE_IBUS)
#include "views/ime/input_method_ibus.h"
#else
#include "views/ime/mock_input_method.h"
#endif
namespace views {
////////////////////////////////////////////////////////////////////////////////
// NativeWidgetViews, public:
NativeWidgetViews::NativeWidgetViews(internal::NativeWidgetDelegate* delegate)
: delegate_(delegate),
view_(NULL),
active_(false),
minimized_(false),
ALLOW_THIS_IN_INITIALIZER_LIST(close_widget_factory_(this)),
hosting_widget_(NULL),
ownership_(Widget::InitParams::NATIVE_WIDGET_OWNS_WIDGET) {
}
NativeWidgetViews::~NativeWidgetViews() {
delegate_->OnNativeWidgetDestroying();
delegate_->OnNativeWidgetDestroyed();
if (ownership_ == Widget::InitParams::NATIVE_WIDGET_OWNS_WIDGET)
delete delegate_;
view_.reset();
}
View* NativeWidgetViews::GetView() {
return view_.get();
}
const View* NativeWidgetViews::GetView() const {
return view_.get();
}
void NativeWidgetViews::OnActivate(bool active) {
if (active_ == active)
return;
active_ = active;
delegate_->OnNativeWidgetActivationChanged(active);
InputMethod* input_method = GetInputMethodNative();
// TODO(oshima): Focus change should be separated from window activation.
// This will be fixed when we have WM API.
if (active) {
input_method->OnFocus();
// See description of got_initial_focus_in_ for details on this.
GetWidget()->GetFocusManager()->RestoreFocusedView();
} else {
input_method->OnBlur();
GetWidget()->GetFocusManager()->StoreFocusedView();
}
view_->SchedulePaint();
}
bool NativeWidgetViews::OnKeyEvent(const KeyEvent& key_event) {
GetInputMethodNative()->DispatchKeyEvent(key_event);
return true;
}
void NativeWidgetViews::DispatchKeyEventPostIME(const KeyEvent& key) {
// TODO(oshima): GTK impl handles menu_key in special way. This may be
// necessary when running under NativeWidgetX.
delegate_->OnKeyEvent(key);
}
////////////////////////////////////////////////////////////////////////////////
// NativeWidgetViews, NativeWidget implementation:
void NativeWidgetViews::InitNativeWidget(const Widget::InitParams& params) {
ownership_ = params.ownership;
view_.reset(new internal::NativeWidgetView(this));
view_->SetBoundsRect(params.bounds);
view_->SetPaintToLayer(true);
View* parent_view = NULL;
if (params.parent_widget) {
hosting_widget_ = params.parent_widget;
parent_view = hosting_widget_->GetChildViewParent();
} else {
parent_view = ViewsDelegate::views_delegate->GetDefaultParentView();
hosting_widget_ = parent_view->GetWidget();
}
parent_view->AddChildView(view_.get());
// TODO(beng): SetInitParams().
}
NonClientFrameView* NativeWidgetViews::CreateNonClientFrameView() {
return NULL;
}
void NativeWidgetViews::UpdateFrameAfterFrameChange() {
}
bool NativeWidgetViews::ShouldUseNativeFrame() const {
// NOTIMPLEMENTED();
return false;
}
void NativeWidgetViews::FrameTypeChanged() {
}
Widget* NativeWidgetViews::GetWidget() {
return delegate_->AsWidget();
}
const Widget* NativeWidgetViews::GetWidget() const {
return delegate_->AsWidget();
}
gfx::NativeView NativeWidgetViews::GetNativeView() const {
return GetParentNativeWidget()->GetNativeView();
}
gfx::NativeWindow NativeWidgetViews::GetNativeWindow() const {
return GetParentNativeWidget()->GetNativeWindow();
}
Widget* NativeWidgetViews::GetTopLevelWidget() {
if (view_->parent() == ViewsDelegate::views_delegate->GetDefaultParentView())
return GetWidget();
// During Widget destruction, this function may be called after |view_| is
// detached from a Widget, at which point this NativeWidget's Widget becomes
// the effective toplevel.
Widget* containing_widget = view_->GetWidget();
return containing_widget ? containing_widget->GetTopLevelWidget()
: GetWidget();
}
const ui::Compositor* NativeWidgetViews::GetCompositor() const {
return hosting_widget_->GetCompositor();
}
ui::Compositor* NativeWidgetViews::GetCompositor() {
return hosting_widget_->GetCompositor();
}
void NativeWidgetViews::MarkLayerDirty() {
view_->MarkLayerDirty();
}
void NativeWidgetViews::CalculateOffsetToAncestorWithLayer(gfx::Point* offset,
View** ancestor) {
view_->CalculateOffsetToAncestorWithLayer(offset, ancestor);
}
void NativeWidgetViews::ViewRemoved(View* view) {
internal::NativeWidgetPrivate* parent = GetParentNativeWidget();
if (parent)
parent->ViewRemoved(view);
}
void NativeWidgetViews::SetNativeWindowProperty(const char* name, void* value) {
NOTIMPLEMENTED();
}
void* NativeWidgetViews::GetNativeWindowProperty(const char* name) const {
NOTIMPLEMENTED();
return NULL;
}
TooltipManager* NativeWidgetViews::GetTooltipManager() const {
const internal::NativeWidgetPrivate* parent = GetParentNativeWidget();
return parent ? parent->GetTooltipManager() : NULL;
}
bool NativeWidgetViews::IsScreenReaderActive() const {
return GetParentNativeWidget()->IsScreenReaderActive();
}
void NativeWidgetViews::SendNativeAccessibilityEvent(
View* view,
ui::AccessibilityTypes::Event event_type) {
return GetParentNativeWidget()->SendNativeAccessibilityEvent(view,
event_type);
}
void NativeWidgetViews::SetMouseCapture() {
View* parent_root_view = GetParentNativeWidget()->GetWidget()->GetRootView();
static_cast<internal::RootView*>(parent_root_view)->set_capture_view(
view_.get());
GetParentNativeWidget()->SetMouseCapture();
}
void NativeWidgetViews::ReleaseMouseCapture() {
View* parent_root_view = GetParentNativeWidget()->GetWidget()->GetRootView();
static_cast<internal::RootView*>(parent_root_view)->set_capture_view(NULL);
GetParentNativeWidget()->ReleaseMouseCapture();
}
bool NativeWidgetViews::HasMouseCapture() const {
// NOTE: we may need to tweak this to only return true if the parent native
// widget's RootView has us as the capture view.
return GetParentNativeWidget()->HasMouseCapture();
}
void NativeWidgetViews::SetKeyboardCapture() {
GetParentNativeWidget()->SetKeyboardCapture();
}
void NativeWidgetViews::ReleaseKeyboardCapture() {
GetParentNativeWidget()->ReleaseKeyboardCapture();
}
bool NativeWidgetViews::HasKeyboardCapture() {
return GetParentNativeWidget()->HasKeyboardCapture();
}
InputMethod* NativeWidgetViews::GetInputMethodNative() {
if (!input_method_.get()) {
#if defined(HAVE_IBUS)
input_method_.reset(static_cast<InputMethod*>(new InputMethodIBus(this)));
#else
// TODO(suzhe|oshima): Figure out what to do on windows.
input_method_.reset(new MockInputMethod(this));
#endif
input_method_->Init(GetWidget());
}
return input_method_.get();
}
void NativeWidgetViews::ReplaceInputMethod(InputMethod* input_method) {
CHECK(input_method);
input_method_.reset(input_method);
input_method->set_delegate(this);
input_method->Init(GetWidget());
}
void NativeWidgetViews::CenterWindow(const gfx::Size& size) {
// TODO(beng): actually center.
GetView()->SetBounds(0, 0, size.width(), size.height());
}
void NativeWidgetViews::GetWindowBoundsAndMaximizedState(
gfx::Rect* bounds,
bool* maximized) const {
*bounds = GetView()->bounds();
*maximized = false;
}
void NativeWidgetViews::SetWindowTitle(const std::wstring& title) {
}
void NativeWidgetViews::SetWindowIcons(const SkBitmap& window_icon,
const SkBitmap& app_icon) {
}
void NativeWidgetViews::SetAccessibleName(const std::wstring& name) {
}
void NativeWidgetViews::SetAccessibleRole(ui::AccessibilityTypes::Role role) {
}
void NativeWidgetViews::SetAccessibleState(
ui::AccessibilityTypes::State state) {
}
void NativeWidgetViews::BecomeModal() {
NOTIMPLEMENTED();
}
gfx::Rect NativeWidgetViews::GetWindowScreenBounds() const {
if (GetWidget() == GetWidget()->GetTopLevelWidget())
return view_->bounds();
gfx::Point origin = view_->bounds().origin();
View::ConvertPointToScreen(view_->parent(), &origin);
return gfx::Rect(origin.x(), origin.y(), view_->width(), view_->height());
}
gfx::Rect NativeWidgetViews::GetClientAreaScreenBounds() const {
return GetWindowScreenBounds();
}
gfx::Rect NativeWidgetViews::GetRestoredBounds() const {
return GetWindowScreenBounds();
}
void NativeWidgetViews::SetBounds(const gfx::Rect& bounds) {
// |bounds| are supplied in the coordinates of the parent.
view_->SetBoundsRect(bounds);
}
void NativeWidgetViews::SetSize(const gfx::Size& size) {
view_->SetSize(size);
}
void NativeWidgetViews::SetBoundsConstrained(const gfx::Rect& bounds,
Widget* other_widget) {
// TODO(beng): honor other_widget.
SetBounds(bounds);
}
void NativeWidgetViews::MoveAbove(gfx::NativeView native_view) {
NOTIMPLEMENTED();
}
void NativeWidgetViews::MoveToTop() {
view_->parent()->ReorderChildView(view_.get(), -1);
}
void NativeWidgetViews::SetShape(gfx::NativeRegion region) {
NOTIMPLEMENTED();
}
void NativeWidgetViews::Close() {
Hide();
if (close_widget_factory_.empty()) {
MessageLoop::current()->PostTask(FROM_HERE,
close_widget_factory_.NewRunnableMethod(&NativeWidgetViews::CloseNow));
}
}
void NativeWidgetViews::CloseNow() {
// reset input_method before destroying widget.
input_method_.reset();
// TODO(beng): what about the other case??
if (ownership_ == Widget::InitParams::NATIVE_WIDGET_OWNS_WIDGET)
delete this;
}
void NativeWidgetViews::EnableClose(bool enable) {
}
void NativeWidgetViews::Show() {
view_->SetVisible(true);
GetWidget()->SetInitialFocus();
}
void NativeWidgetViews::Hide() {
view_->SetVisible(false);
}
void NativeWidgetViews::ShowNativeWidget(ShowState state) {
}
bool NativeWidgetViews::IsVisible() const {
return view_->IsVisible();
}
void NativeWidgetViews::Activate() {
// Enable WidgetObserverTest.ActivationChange when this is implemented.
NOTIMPLEMENTED();
}
void NativeWidgetViews::Deactivate() {
NOTIMPLEMENTED();
}
bool NativeWidgetViews::IsActive() const {
return active_;
}
void NativeWidgetViews::SetAlwaysOnTop(bool on_top) {
NOTIMPLEMENTED();
}
void NativeWidgetViews::Maximize() {
NOTIMPLEMENTED();
}
void NativeWidgetViews::Minimize() {
gfx::Rect view_bounds = view_->bounds();
gfx::Rect parent_bounds = view_->parent()->bounds();
restored_bounds_ = view_bounds;
restored_transform_ = view_->GetTransform();
float aspect_ratio = static_cast<float>(view_bounds.width()) /
static_cast<float>(view_bounds.height());
int target_size = 100;
int target_height = target_size;
int target_width = static_cast<int>(aspect_ratio * target_height);
if (target_width > target_size) {
target_width = target_size;
target_height = static_cast<int>(target_width / aspect_ratio);
}
int target_x = 20;
int target_y = parent_bounds.height() - target_size - 20;
view_->SetBounds(
target_x, target_y, view_bounds.width(), view_bounds.height());
ui::Transform transform;
transform.SetScale((float)target_width / (float)view_bounds.width(),
(float)target_height / (float)view_bounds.height());
view_->SetTransform(transform);
minimized_ = true;
}
bool NativeWidgetViews::IsMaximized() const {
// NOTIMPLEMENTED();
return false;
}
bool NativeWidgetViews::IsMinimized() const {
return minimized_;
}
void NativeWidgetViews::Restore() {
minimized_ = false;
view_->SetBoundsRect(restored_bounds_);
view_->SetTransform(restored_transform_);
}
void NativeWidgetViews::SetFullscreen(bool fullscreen) {
NOTIMPLEMENTED();
}
bool NativeWidgetViews::IsFullscreen() const {
// NOTIMPLEMENTED();
return false;
}
void NativeWidgetViews::SetOpacity(unsigned char opacity) {
NOTIMPLEMENTED();
}
void NativeWidgetViews::SetUseDragFrame(bool use_drag_frame) {
NOTIMPLEMENTED();
}
bool NativeWidgetViews::IsAccessibleWidget() const {
NOTIMPLEMENTED();
return false;
}
void NativeWidgetViews::RunShellDrag(View* view,
const ui::OSExchangeData& data,
int operation) {
GetParentNativeWidget()->RunShellDrag(view, data, operation);
}
void NativeWidgetViews::SchedulePaintInRect(const gfx::Rect& rect) {
view_->SchedulePaintInternal(rect);
}
void NativeWidgetViews::SetCursor(gfx::NativeCursor cursor) {
GetParentNativeWidget()->SetCursor(cursor);
}
void NativeWidgetViews::ClearNativeFocus() {
GetParentNativeWidget()->ClearNativeFocus();
}
void NativeWidgetViews::FocusNativeView(gfx::NativeView native_view) {
GetParentNativeWidget()->FocusNativeView(native_view);
}
////////////////////////////////////////////////////////////////////////////////
// NativeWidgetViews, private:
internal::NativeWidgetPrivate* NativeWidgetViews::GetParentNativeWidget() {
Widget* containing_widget = view_->GetWidget();
return containing_widget ? static_cast<internal::NativeWidgetPrivate*>(
containing_widget->native_widget()) :
NULL;
}
const internal::NativeWidgetPrivate*
NativeWidgetViews::GetParentNativeWidget() const {
const Widget* containing_widget = view_->GetWidget();
return containing_widget ? static_cast<const internal::NativeWidgetPrivate*>(
containing_widget->native_widget()) :
NULL;
}
} // namespace views
<|endoftext|> |
<commit_before>#include <iostream>
#include <vector>
using namespace std;
class ModInt {
public:
ModInt(int n) : num(n) {};
operator int() const { return num; }
ModInt operator=(const ModInt& other);
ModInt operator+(const ModInt& other);
ModInt operator-(const ModInt& other);
ModInt operator*(const ModInt& other);
ModInt operator%(const ModInt& other);
ModInt operator/(const ModInt& other);
ModInt operator/=(const ModInt& other);
friend ostream& operator<<(ostream& os, const ModInt& out);
protected:
int num;
};
class BaseInt {
public:
BaseInt(int b) : base(b) {};
int to10(vector<int> &numB);
int from10(vector<int> &numB, int num10);
protected:
int base;
};
ModInt ModInt::operator=(const ModInt& other)
{
num = other.num;
return *this;
}
ModInt ModInt::operator+(const ModInt& other)
{
return ModInt(num + other.num);
}
ModInt ModInt::operator-(const ModInt& other)
{
return ModInt(num - other.num);
}
ModInt ModInt::operator*(const ModInt& other)
{
return ModInt(num * other.num);
}
ModInt ModInt::operator%(const ModInt& other)
{
int n = num;
int m = other.num;
if(m < 0) {
m = -m;
}
n %= m;
while(n < 0) {
n += m;
}
return ModInt(n);
}
ModInt ModInt::operator/(const ModInt& other)
{
ModInt mod = *this % other;
int n = num - mod.num;
return ModInt(n / other.num);
}
ModInt ModInt::operator/=(const ModInt& other)
{
*this = *this / other;
return *this;
}
ostream& operator<<(ostream& os, const ModInt& out)
{
os << out.num;
return os;
}
int BaseInt::to10(vector<int> &a) {
int n = 0;
vector<int>::iterator i;
for(i = a.begin(); i != a.end(); i++)
{
int d = *i;
n *= base;
n += d;
}
return n;
}
int BaseInt::from10(vector<int> &a, int n) {
ModInt m(n);
ModInt b(base);
while(m) {
ModInt d = m % b;
m /= b;
vector<int>::iterator it = a.begin();
a.insert(it, (int)d);
}
}
<commit_msg>adding comments and demo for extension class<commit_after>#include <iostream>
#include <vector>
using namespace std;
/*
* class ModInt
* Extention of integers to support division and modulo operations for negative integers
*/
class ModInt {
public:
ModInt(int n) : num(n) {};
operator int() const { return num; }
ModInt operator=(const ModInt& other);
ModInt operator+(const ModInt& other);
ModInt operator-(const ModInt& other);
ModInt operator*(const ModInt& other);
ModInt operator%(const ModInt& other);
ModInt operator/(const ModInt& other);
ModInt operator/=(const ModInt& other);
friend ostream& operator<<(ostream& os, const ModInt& out);
protected:
int num;
};
/*
* class BaseInt
* Convert from decimal to other base and vice versa. Works for negative base.
*/
class BaseInt {
public:
BaseInt(int b) : base(b) {};
int to10(vector<int> &numB);
int from10(vector<int> &numB, int num10);
protected:
int base;
};
// standard assignment oprator
ModInt ModInt::operator=(const ModInt& other)
{
num = other.num;
return *this;
}
// support for integer +
ModInt ModInt::operator+(const ModInt& other)
{
return ModInt(num + other.num);
}
// support for integer - (binary)
ModInt ModInt::operator-(const ModInt& other)
{
return ModInt(num - other.num);
}
// support for integer *
ModInt ModInt::operator*(const ModInt& other)
{
return ModInt(num * other.num);
}
// support for integer modulo operator, works for negative
ModInt ModInt::operator%(const ModInt& other)
{
int n = num;
int m = other.num;
if(m < 0) {
m = -m;
}
n %= m;
while(n < 0) {
n += m;
}
return ModInt(n);
}
// support for integer division operator, works for negative
ModInt ModInt::operator/(const ModInt& other)
{
ModInt mod = *this % other;
int n = num - mod.num;
return ModInt(n / other.num);
}
// support for integer /= operator, works for negative
ModInt ModInt::operator/=(const ModInt& other)
{
*this = *this / other;
return *this;
}
// stream output for ModInt objects
ostream& operator<<(ostream& os, const ModInt& out)
{
os << out.num;
return os;
}
// convert to decimal, works for both positive and negative radix
int BaseInt::to10(vector<int> &a) {
int n = 0;
vector<int>::iterator i;
for(i = a.begin(); i != a.end(); i++)
{
int d = *i;
n *= base;
n += d;
}
return n;
}
// convert from decimal, works for both positive and negative radix
int BaseInt::from10(vector<int> &a, int n) {
ModInt m(n);
ModInt b(base);
while(m) {
ModInt d = m % b;
m /= b;
vector<int>::iterator it = a.begin();
a.insert(it, (int)d);
}
}
// demo for ModInt class and its differences from standard integers
int demoModInt(int a, int b) {
cout << "Demo for pair (" << a << "," << b << "):" << endl;
int c = a / b;
int d = a % b;
ModInt ma(a);
ModInt mb(b);
ModInt mc = ma / mb;
ModInt md = ma % mb;
cout << "Standard integer division: " << a << " / " << b << " = " << c << endl;
cout << "Fixed integer division: " << ma << " / " << mb << " = " << mc << endl;
cout << "Standard integer modulo: " << a << " % " << b << " = " << d << endl;
cout << "Fixed integer modulo: " << ma << " mod " << mb << " = " << md << endl << endl;
}
int main() {
demoModInt(17, 5);
demoModInt(17, -5);
demoModInt(-17, 5);
demoModInt(-17, -5);
return 0;
}
<|endoftext|> |
<commit_before>#include <CL/sycl.hpp>
#include <array>
#include <iostream>
// dpcpp simple2.cpp -o simple2
using namespace sycl;
int main() {
constexpr unsigned N = 256;
constexpr unsigned M = 16;
// Create queue on implementation-chosen default device
queue Q;
unsigned* data = malloc_shared<unsigned>(N, Q);
std::fill(data, data + N, 0);
// Launch exactly one work-group
// Number of work-groups = global / local
range<1> global{N};
range<1> local{N};
Q.parallel_for(nd_range<1>{global, local}, [=](nd_item<1> it) {
int i = it.get_global_id(0);
int j = i % M;
for (int round = 0; round < N; ++round) {
// Allow exactly one work-item update per round
if (i == round) {
data[j] += 1;
}
it.barrier();
}
}).wait();
for (int i = 0; i < N; ++i) {
std::cout << "data [" << i << "] = " << data[i] << "\n";
}
return 0;
}
<commit_msg>modify DPC++ sample<commit_after>#include <CL/sycl.hpp>
#include <array>
#include <iostream>
// dpcpp simple2.cpp -o simple2
using namespace sycl;
using namespace sycl::ONEAPI;
int main() {
constexpr unsigned N = 256;
constexpr unsigned M = 16;
// Create queue on implementation-chosen default device
queue Q;
unsigned* data = malloc_shared<unsigned>(N, Q);
std::fill(data, data + N, 0);
// Launch exactly one work-group
// Number of work-groups = global / local
range<1> global{N};
range<1> local{N};
Q.parallel_for(nd_range<1>{global, local}, [=](nd_item<1> it) {
int i = it.get_global_id(0);
int j = i % M;
for (int round = 0; round < N; ++round) {
// Allow exactly one work-item update per round
if (i == round) {
data[j] += 1;
}
it.barrier();
}
}).wait();
std::array<unsigned, N> data2;
buffer buf{ data2 };
Q.submit([&](handler& h) {
atomic_accessor acc(buf, h, relaxed_order, system_scope);
h.parallel_for(N, [=](id<1> i) {
int j = i % M;
acc[j] += 1;
});
});
for (int i = 0; i < N; ++i) {
std::cout << "data [" << i << "] = " << data[i] << " data2 [" << i << "] = " << data2[i] << "\n";
}
return 0;
}
<|endoftext|> |
<commit_before>#include "optical_flow.h"
using namespace cv;
using namespace std;
namespace nba_vision {
OpticalFlow::OpticalFlow(bool debug){
debug_ = debug;
if (debug_){
namedWindow(windowName, CV_WINDOW_AUTOSIZE);
}
}
void OpticalFlow::computeOpticalFlow(Mat current_frame){
cvtColor(current_frame, current_frame, COLOR_BGR2GRAY);
goodFeaturesToTrack(current_frame, points[0], MAX_COUNT, .01, 10, Mat(), 3, 0, .04);
cornerSubPix(current_frame, points[0], subPixWinSize, Size(-1,-1), termcrit);
if(!previous_frame.empty()){
vector<uchar> status;
vector<float> err;
calcOpticalFlowPyrLK(previous_frame, current_frame, points[0],
points[1], status, err, winSize, 3, termcrit, 0, 0.001);
for( int i = 0; i < points[1].size(); i++ ){
if( !status[i] )
continue;
else
drawFlow(points[0][i], points[1][i]);
}
//debug
if (debug_){
imshow(windowName, previous_frame);
}
}
// update for next frame
//swap(points[1], points[0]); // new points become old points
previous_frame = current_frame; // current frame becomes previous frame.
}
void OpticalFlow::drawFlow(Point2f point_a, Point2f point_b){
Point p0( ceil( point_a.x ), ceil( point_a.y ) );
Point p1( ceil( point_b.x ), ceil( point_b.y ) );
line( previous_frame, p0, p1, CV_RGB(255,255,255), 2 );
}
}
<commit_msg>commiting b4 branch<commit_after>#include "optical_flow.h"
using namespace cv;
using namespace std;
namespace nba_vision {
OpticalFlow::OpticalFlow(bool debug){
debug_ = debug;
if (debug_){
namedWindow(windowName, CV_WINDOW_AUTOSIZE);
}
}
void OpticalFlow::computeOpticalFlow(Mat current_frame){
cvtColor(current_frame, current_frame, COLOR_BGR2GRAY);
goodFeaturesToTrack(current_frame, points[0], MAX_COUNT, .01, 11, Mat(), 3, 0, .04);
cornerSubPix(current_frame, points[0], subPixWinSize, Size(-1,-1), termcrit);
if(!previous_frame.empty()){
vector<uchar> status;
vector<float> err;
calcOpticalFlowPyrLK(previous_frame, current_frame, points[0],
points[1], status, err, winSize, 3, termcrit, 0, 0.001);
for( int i = 0; i < points[1].size(); i++ ){
if( !status[i] )
continue;
else
drawFlow(points[0][i], points[1][i]);
}
//debug
if (debug_){
imshow(windowName, previous_frame);
}
}
// update for next frame
//swap(points[1], points[0]); // new points become old points
previous_frame = current_frame; // current frame becomes previous frame.
}
void OpticalFlow::drawFlow(Point2f point_a, Point2f point_b){
Point p0( ceil( point_a.x ), ceil( point_a.y ) );
Point p1( ceil( point_b.x ), ceil( point_b.y ) );
line( previous_frame, p0, p1, CV_RGB(255,255,255), 2 );
}
}
<|endoftext|> |
<commit_before>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2013. All rights reserved
*/
#ifndef _Stroika_Foundation_DataExchangeFormat_ObjectVariantMapper_inl_
#define _Stroika_Foundation_DataExchangeFormat_ObjectVariantMapper_inl_ 1
/*
********************************************************************************
***************************** Implementation Details ***************************
********************************************************************************
*/
#include "../Execution/Exceptions.h"
#include "BadFormatException.h"
namespace Stroika {
namespace Foundation {
namespace DataExchangeFormat {
/*
********************************************************************************
******************* ObjectVariantMapper::StructureFieldInfo ********************
********************************************************************************
*/
inline ObjectVariantMapper::StructureFieldInfo::StructureFieldInfo (size_t fieldOffset, type_index typeInfo, const String& serializedFieldName)
: fOffset (fieldOffset)
, fTypeInfo (typeInfo)
, fSerializedFieldName (serializedFieldName)
{
}
/*
********************************************************************************
******************************** ObjectVariantMapper ***************************
********************************************************************************
*/
inline Set<ObjectVariantMapper::TypeMappingDetails> ObjectVariantMapper::GetTypeMappingRegistry () const
{
return fSerializers_;
}
inline void ObjectVariantMapper::SetTypeMappingRegistry (const Set<TypeMappingDetails>& s)
{
fSerializers_ = s;
}
template <typename CLASS>
inline void ObjectVariantMapper::RegisterClass (const Sequence<StructureFieldInfo>& fieldDescriptions)
{
RegisterTypeMapper (TypeMappingDetails (typeid (CLASS), sizeof (CLASS), fieldDescriptions));
}
template <typename CLASS>
inline void ObjectVariantMapper::ToObject (const Memory::VariantValue& v, CLASS* into) const
{
ToObject (typeid (CLASS), v, reinterpret_cast<Byte*> (into));
}
template <typename CLASS>
inline CLASS ObjectVariantMapper::ToObject (const Memory::VariantValue& v) const
{
CLASS tmp;
ToObject (v, &tmp);
return tmp;
}
template <typename CLASS>
inline VariantValue ObjectVariantMapper::FromObject (const CLASS& from) const
{
return FromObject (typeid (CLASS), reinterpret_cast<const Byte*> (&from));
}
template <typename T, size_t SZ>
ObjectVariantMapper::TypeMappingDetails ObjectVariantMapper::MakeCommonSerializer_Array ()
{
auto toVariantMapper = [] (ObjectVariantMapper * mapper, const Byte * fromObjOfTypeT) -> VariantValue {
Sequence<VariantValue> s;
const T* actualMember = reinterpret_cast<const T*> (fromObjOfTypeT);
for (auto i = actualMember; i < actualMember + SZ; ++i) {
s.Append (mapper->FromObject<T> (*i));
}
return VariantValue (s);
};
auto fromVariantMapper = [] (ObjectVariantMapper * mapper, const VariantValue & d, Byte * intoObjOfTypeT) -> void {
Sequence<VariantValue> s = d.As<Sequence<T>> ();
T* actualMember = reinterpret_cast<T*> (intoObjOfTypeT);
if (s.size () > SZ) {
Execution::DoThrow<BadFormatException> (BadFormatException ());
}
size_t idx = 0;
for (auto i : s) {
actualMember[idx++] = mapper->ToObject<T> (i);
}
while (idx < SZ) {
actualMember[idx++] = T ();
}
};
return ObjectVariantMapper::TypeMappingDetails (typeid (Sequence<T>), toVariantMapper, fromVariantMapper);
}
template <typename T>
ObjectVariantMapper::TypeMappingDetails ObjectVariantMapper::MakeCommonSerializer_Sequence ()
{
auto toVariantMapper = [] (ObjectVariantMapper * mapper, const Byte * fromObjOfTypeT) -> VariantValue {
Sequence<VariantValue> s;
const Sequence<T>* actualMember = reinterpret_cast<const Sequence<T>*> (fromObjOfTypeT);
for (auto i : *actualMember) {
s.Append (mapper->FromObject<T> (i));
}
return VariantValue (s);
};
auto fromVariantMapper = [] (ObjectVariantMapper * mapper, const VariantValue & d, Byte * intoObjOfTypeT) -> void {
Sequence<VariantValue> s = d.As<Sequence<T>> ();
Sequence<T>* actualInto = reinterpret_cast<Sequence<T>*> (intoObjOfTypeT);
actualInto->clear ();
for (auto i : s) {
actualInto->Append (mapper->ToObject<T> (i));
}
};
return ObjectVariantMapper::TypeMappingDetails (typeid (Sequence<T>), toVariantMapper, fromVariantMapper);
}
template <typename KEY_TYPE, typename VALUE_TYPE>
ObjectVariantMapper::TypeMappingDetails ObjectVariantMapper::MakeCommonSerializer_Mapping ()
{
auto toVariantMapper = [] (ObjectVariantMapper * mapper, const Byte * fromObjOfTypeT) -> VariantValue {
Sequence<VariantValue> s;
const Mapping<KEY_TYPE, VALUE_TYPE>* actualMember = reinterpret_cast<const Mapping<KEY_TYPE, VALUE_TYPE>*> (fromObjOfTypeT);
for (auto i : *actualMember) {
Sequence<VariantValue> encodedPair;
encodedPair.Append (mapper->FromObject<KEY_TYPE> (i.first));
encodedPair.Append (mapper->FromObject<VALUE_TYPE> (i.second));
s.Append (VariantValue (encodedPair));
}
return VariantValue (s);
};
auto fromVariantMapper = [] (ObjectVariantMapper * mapper, const VariantValue & d, Byte * intoObjOfTypeT) -> void {
Sequence<VariantValue> s = d.As<Sequence<VariantValue>> ();
Mapping<KEY_TYPE, VALUE_TYPE>* actualInto = reinterpret_cast<Mapping<KEY_TYPE, VALUE_TYPE>*> (intoObjOfTypeT);
actualInto->clear ();
for (VariantValue encodedPair : s) {
Sequence<VariantValue> p = p.As<Sequence<VariantValue>> ();
if (p.size () != 2) {
Execution::DoThrow<BadFormatException> (BadFormatException ());
}
actualInto->Add (mapper->ToObject<KEY_TYPE> (p[0]), mapper->ToObject<VALUE_TYPE> (p[1]));
}
};
return ObjectVariantMapper::TypeMappingDetails (typeid (Mapping<KEY_TYPE, VALUE_TYPE>), toVariantMapper, fromVariantMapper);
}
template <typename RANGE_TYPE>
ObjectVariantMapper::TypeMappingDetails ObjectVariantMapper::MakeCommonSerializer_Range ()
{
auto toVariantMapper = [] (ObjectVariantMapper * mapper, const Byte * fromObjOfTypeT) -> VariantValue {
typedef typename RANGE_TYPE::ElementType ElementType;
Sequence<VariantValue> s;
const RANGE_TYPE* actualMember = reinterpret_cast<const RANGE_TYPE*> (fromObjOfTypeT);
s.Append (mapper->FromObject<ElementType> (actualMember->begin ()));
s.Append (mapper->FromObject<ElementType> (actualMember->end ()));
return VariantValue (s);
};
auto fromVariantMapper = [] (ObjectVariantMapper * mapper, const VariantValue & d, Byte * intoObjOfTypeT) -> void {
typedef typename RANGE_TYPE::ElementType ElementType;
Sequence<VariantValue> s = d.As<Sequence<VariantValue>> ();
RANGE_TYPE* actualInto = reinterpret_cast<RANGE_TYPE*> (intoObjOfTypeT);
actualInto->clear ();
if (p.size () != 2) {
Execution::DoThrow<BadFormatException> (BadFormatException ());
}
ElementType from = mapper->ToObject<ElementType> (p[0]);
ElementType to = mapper->ToObject<ElementType> (p[1]);
if (not (RANGE_TYPE::kMin <= from and from <= RANGE_TYPE::kMax)) {
Execution::DoThrow<BadFormatException> (BadFormatException ());
}
if (not (RANGE_TYPE::kMin <= to and to <= RANGE_TYPE::kMax)) {
Execution::DoThrow<BadFormatException> (BadFormatException ());
}
* actualInto = RANGE_TYPE (from, to);
};
return ObjectVariantMapper::TypeMappingDetails (typeid (RANGE_TYPE), toVariantMapper, fromVariantMapper);
}
#if 0
template <typename T>
inline ObjectVariantMapper::TypeMappingDetails ObjectVariantMapper::MakeCommonSerializer<Sequence<T>> ()
{
return mkSerializerInfoFor_Sequence_<T> ();
}
#endif
}
}
}
#endif /*_Stroika_Foundation_DataExchangeFormat_ObjectVariantMapper_inl_*/
<commit_msg>fixed small bug in recent objectvariantmapper helper/addition<commit_after>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2013. All rights reserved
*/
#ifndef _Stroika_Foundation_DataExchangeFormat_ObjectVariantMapper_inl_
#define _Stroika_Foundation_DataExchangeFormat_ObjectVariantMapper_inl_ 1
/*
********************************************************************************
***************************** Implementation Details ***************************
********************************************************************************
*/
#include "../Execution/Exceptions.h"
#include "BadFormatException.h"
namespace Stroika {
namespace Foundation {
namespace DataExchangeFormat {
/*
********************************************************************************
******************* ObjectVariantMapper::StructureFieldInfo ********************
********************************************************************************
*/
inline ObjectVariantMapper::StructureFieldInfo::StructureFieldInfo (size_t fieldOffset, type_index typeInfo, const String& serializedFieldName)
: fOffset (fieldOffset)
, fTypeInfo (typeInfo)
, fSerializedFieldName (serializedFieldName)
{
}
/*
********************************************************************************
******************************** ObjectVariantMapper ***************************
********************************************************************************
*/
inline Set<ObjectVariantMapper::TypeMappingDetails> ObjectVariantMapper::GetTypeMappingRegistry () const
{
return fSerializers_;
}
inline void ObjectVariantMapper::SetTypeMappingRegistry (const Set<TypeMappingDetails>& s)
{
fSerializers_ = s;
}
template <typename CLASS>
inline void ObjectVariantMapper::RegisterClass (const Sequence<StructureFieldInfo>& fieldDescriptions)
{
RegisterTypeMapper (TypeMappingDetails (typeid (CLASS), sizeof (CLASS), fieldDescriptions));
}
template <typename CLASS>
inline void ObjectVariantMapper::ToObject (const Memory::VariantValue& v, CLASS* into) const
{
ToObject (typeid (CLASS), v, reinterpret_cast<Byte*> (into));
}
template <typename CLASS>
inline CLASS ObjectVariantMapper::ToObject (const Memory::VariantValue& v) const
{
CLASS tmp;
ToObject (v, &tmp);
return tmp;
}
template <typename CLASS>
inline VariantValue ObjectVariantMapper::FromObject (const CLASS& from) const
{
return FromObject (typeid (CLASS), reinterpret_cast<const Byte*> (&from));
}
template <typename T, size_t SZ>
ObjectVariantMapper::TypeMappingDetails ObjectVariantMapper::MakeCommonSerializer_Array ()
{
auto toVariantMapper = [] (ObjectVariantMapper * mapper, const Byte * fromObjOfTypeT) -> VariantValue {
Sequence<VariantValue> s;
const T* actualMember = reinterpret_cast<const T*> (fromObjOfTypeT);
for (auto i = actualMember; i < actualMember + SZ; ++i) {
s.Append (mapper->FromObject<T> (*i));
}
return VariantValue (s);
};
auto fromVariantMapper = [] (ObjectVariantMapper * mapper, const VariantValue & d, Byte * intoObjOfTypeT) -> void {
Sequence<VariantValue> s = d.As<Sequence<T>> ();
T* actualMember = reinterpret_cast<T*> (intoObjOfTypeT);
if (s.size () > SZ) {
Execution::DoThrow<BadFormatException> (BadFormatException ());
}
size_t idx = 0;
for (auto i : s) {
actualMember[idx++] = mapper->ToObject<T> (i);
}
while (idx < SZ) {
actualMember[idx++] = T ();
}
};
return ObjectVariantMapper::TypeMappingDetails (typeid (Sequence<T>), toVariantMapper, fromVariantMapper);
}
template <typename T>
ObjectVariantMapper::TypeMappingDetails ObjectVariantMapper::MakeCommonSerializer_Sequence ()
{
auto toVariantMapper = [] (ObjectVariantMapper * mapper, const Byte * fromObjOfTypeT) -> VariantValue {
Sequence<VariantValue> s;
const Sequence<T>* actualMember = reinterpret_cast<const Sequence<T>*> (fromObjOfTypeT);
for (auto i : *actualMember) {
s.Append (mapper->FromObject<T> (i));
}
return VariantValue (s);
};
auto fromVariantMapper = [] (ObjectVariantMapper * mapper, const VariantValue & d, Byte * intoObjOfTypeT) -> void {
Sequence<VariantValue> s = d.As<Sequence<T>> ();
Sequence<T>* actualInto = reinterpret_cast<Sequence<T>*> (intoObjOfTypeT);
actualInto->clear ();
for (auto i : s) {
actualInto->Append (mapper->ToObject<T> (i));
}
};
return ObjectVariantMapper::TypeMappingDetails (typeid (Sequence<T>), toVariantMapper, fromVariantMapper);
}
template <typename KEY_TYPE, typename VALUE_TYPE>
ObjectVariantMapper::TypeMappingDetails ObjectVariantMapper::MakeCommonSerializer_Mapping ()
{
auto toVariantMapper = [] (ObjectVariantMapper * mapper, const Byte * fromObjOfTypeT) -> VariantValue {
Sequence<VariantValue> s;
const Mapping<KEY_TYPE, VALUE_TYPE>* actualMember = reinterpret_cast<const Mapping<KEY_TYPE, VALUE_TYPE>*> (fromObjOfTypeT);
for (auto i : *actualMember) {
Sequence<VariantValue> encodedPair;
encodedPair.Append (mapper->FromObject<KEY_TYPE> (i.first));
encodedPair.Append (mapper->FromObject<VALUE_TYPE> (i.second));
s.Append (VariantValue (encodedPair));
}
return VariantValue (s);
};
auto fromVariantMapper = [] (ObjectVariantMapper * mapper, const VariantValue & d, Byte * intoObjOfTypeT) -> void {
Sequence<VariantValue> s = d.As<Sequence<VariantValue>> ();
Mapping<KEY_TYPE, VALUE_TYPE>* actualInto = reinterpret_cast<Mapping<KEY_TYPE, VALUE_TYPE>*> (intoObjOfTypeT);
actualInto->clear ();
for (VariantValue encodedPair : s) {
Sequence<VariantValue> p = p.As<Sequence<VariantValue>> ();
if (p.size () != 2) {
Execution::DoThrow<BadFormatException> (BadFormatException ());
}
actualInto->Add (mapper->ToObject<KEY_TYPE> (p[0]), mapper->ToObject<VALUE_TYPE> (p[1]));
}
};
return ObjectVariantMapper::TypeMappingDetails (typeid (Mapping<KEY_TYPE, VALUE_TYPE>), toVariantMapper, fromVariantMapper);
}
template <typename RANGE_TYPE>
ObjectVariantMapper::TypeMappingDetails ObjectVariantMapper::MakeCommonSerializer_Range ()
{
auto toVariantMapper = [] (ObjectVariantMapper * mapper, const Byte * fromObjOfTypeT) -> VariantValue {
typedef typename RANGE_TYPE::ElementType ElementType;
Sequence<VariantValue> s;
const RANGE_TYPE* actualMember = reinterpret_cast<const RANGE_TYPE*> (fromObjOfTypeT);
s.Append (mapper->FromObject<ElementType> (actualMember->begin ()));
s.Append (mapper->FromObject<ElementType> (actualMember->end ()));
return VariantValue (s);
};
auto fromVariantMapper = [] (ObjectVariantMapper * mapper, const VariantValue & d, Byte * intoObjOfTypeT) -> void {
typedef typename RANGE_TYPE::ElementType ElementType;
Sequence<VariantValue> p = d.As<Sequence<VariantValue>> ();
RANGE_TYPE* actualInto = reinterpret_cast<RANGE_TYPE*> (intoObjOfTypeT);
actualInto->clear ();
if (p.size () != 2) {
Execution::DoThrow<BadFormatException> (BadFormatException ());
}
ElementType from = mapper->ToObject<ElementType> (p[0]);
ElementType to = mapper->ToObject<ElementType> (p[1]);
if (not (RANGE_TYPE::kMin <= from and from <= RANGE_TYPE::kMax)) {
Execution::DoThrow<BadFormatException> (BadFormatException ());
}
if (not (RANGE_TYPE::kMin <= to and to <= RANGE_TYPE::kMax)) {
Execution::DoThrow<BadFormatException> (BadFormatException ());
}
* actualInto = RANGE_TYPE (from, to);
};
return ObjectVariantMapper::TypeMappingDetails (typeid (RANGE_TYPE), toVariantMapper, fromVariantMapper);
}
#if 0
template <typename T>
inline ObjectVariantMapper::TypeMappingDetails ObjectVariantMapper::MakeCommonSerializer<Sequence<T>> ()
{
return mkSerializerInfoFor_Sequence_<T> ();
}
#endif
}
}
}
#endif /*_Stroika_Foundation_DataExchangeFormat_ObjectVariantMapper_inl_*/
<|endoftext|> |
<commit_before>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2013. All rights reserved
*/
#ifndef _Stroika_Foundation_DataExchangeFormat_XML_SAXObjectReader_inl_
#define _Stroika_Foundation_DataExchangeFormat_XML_SAXObjectReader_inl_ 1
/*
********************************************************************************
***************************** Implementation Details ***************************
********************************************************************************
*/
#include "../../Containers/Common.h"
namespace Stroika {
namespace Foundation {
namespace DataExchangeFormat {
namespace XML {
// class SAXObjectReader
inline SAXObjectReader::SAXObjectReader ()
#if qDefaultTracingOn
: fTraceThisReader (false)
#endif
{
}
inline void SAXObjectReader::Push (const shared_ptr<ObjectBase>& elt)
{
#if qDefaultTracingOn
if (fTraceThisReader) {
DbgTrace ("%sSAXObjectReader::Push", TraceLeader_ ().c_str ());
}
#endif
Containers::ReserveSpeedTweekAdd1 (fStack_);
fStack_.push_back (elt);
}
inline void SAXObjectReader::Pop ()
{
fStack_.pop_back ();
#if qDefaultTracingOn
if (fTraceThisReader) {
DbgTrace ("%sSAXObjectReader::Popped", TraceLeader_ ().c_str ());
}
#endif
}
inline shared_ptr<SAXObjectReader::ObjectBase> SAXObjectReader::GetTop () const
{
Require (not fStack_.empty ());
return fStack_.back ();
}
template <>
class BuiltinReader<String> : public SAXObjectReader::ObjectBase {
public:
BuiltinReader (String* intoVal, const map<String, Memory::VariantValue>& attrs = map<String, Memory::VariantValue> ());
private:
String* value_;
public:
virtual void HandleChildStart (SAXObjectReader& r, const String& uri, const String& localName, const String& qname, const map<String, Memory::VariantValue>& attrs) override;
virtual void HandleTextInside (SAXObjectReader& r, const String& text) override;
virtual void HandleEndTag (SAXObjectReader& r) override;
};
template <>
class BuiltinReader<int> : public SAXObjectReader::ObjectBase {
public:
BuiltinReader (int* intoVal, const map<String, Memory::VariantValue>& attrs = map<String, Memory::VariantValue> ());
private:
String tmpVal_;
int* value_;
public:
virtual void HandleChildStart (SAXObjectReader& r, const String& uri, const String& localName, const String& qname, const map<String, Memory::VariantValue>& attrs) override;
virtual void HandleTextInside (SAXObjectReader& r, const String& text) override;
virtual void HandleEndTag (SAXObjectReader& r) override;
};
template <>
class BuiltinReader<unsigned int> : public SAXObjectReader::ObjectBase {
public:
BuiltinReader (unsigned int* intoVal, const map<String, Memory::VariantValue>& attrs = map<String, Memory::VariantValue> ());
private:
String tmpVal_;
unsigned int* value_;
public:
virtual void HandleChildStart (SAXObjectReader& r, const String& uri, const String& localName, const String& qname, const map<String, Memory::VariantValue>& attrs) override;
virtual void HandleTextInside (SAXObjectReader& r, const String& text) override;
virtual void HandleEndTag (SAXObjectReader& r) override;
};
template <>
class BuiltinReader<float> : public SAXObjectReader::ObjectBase {
public:
BuiltinReader (float* intoVal, const map<String, Memory::VariantValue>& attrs = map<String, Memory::VariantValue> ());
private:
String tmpVal_;
float* value_;
public:
virtual void HandleChildStart (SAXObjectReader& r, const String& uri, const String& localName, const String& qname, const map<String, Memory::VariantValue>& attrs) override;
virtual void HandleTextInside (SAXObjectReader& r, const String& text) override;
virtual void HandleEndTag (SAXObjectReader& r) override;
};
template <>
class BuiltinReader<double> : public SAXObjectReader::ObjectBase {
public:
BuiltinReader (double* intoVal, const map<String, Memory::VariantValue>& attrs = map<String, Memory::VariantValue> ());
private:
String tmpVal_;
double* value_;
public:
virtual void HandleChildStart (SAXObjectReader& r, const String& uri, const String& localName, const String& qname, const map<String, Memory::VariantValue>& attrs) override;
virtual void HandleTextInside (SAXObjectReader& r, const String& text) override;
virtual void HandleEndTag (SAXObjectReader& r) override;
};
template <>
class BuiltinReader<bool> : public SAXObjectReader::ObjectBase {
public:
BuiltinReader (bool* intoVal, const map<String, Memory::VariantValue>& attrs = map<String, Memory::VariantValue> ());
private:
String tmpVal_;
bool* value_;
public:
virtual void HandleChildStart (SAXObjectReader& r, const String& uri, const String& localName, const String& qname, const map<String, Memory::VariantValue>& attrs) override;
virtual void HandleTextInside (SAXObjectReader& r, const String& text) override;
virtual void HandleEndTag (SAXObjectReader& r) override;
};
template <>
class BuiltinReader<Time::DateTime> : public SAXObjectReader::ObjectBase {
public:
BuiltinReader (Time::DateTime* intoVal, const map<String, Memory::VariantValue>& attrs = map<String, Memory::VariantValue> ());
private:
String tmpVal_;
Time::DateTime* value_;
public:
virtual void HandleChildStart (SAXObjectReader& r, const String& uri, const String& localName, const String& qname, const map<String, Memory::VariantValue>& attrs) override;
virtual void HandleTextInside (SAXObjectReader& r, const String& text) override;
virtual void HandleEndTag (SAXObjectReader& r) override;
};
template <typename T, typename ACTUAL_READER>
OptionalTypesReader<T, ACTUAL_READER>::OptionalTypesReader (Memory::Optional<T>* intoVal, const map<String, Memory::VariantValue>& attrs)
: value_ (intoVal)
, proxyValue_ ()
, actualReader_ (&proxyValue_)
{
}
template <typename T, typename ACTUAL_READER>
void OptionalTypesReader<T, ACTUAL_READER>::HandleChildStart (SAXObjectReader& r, const String& uri, const String& localName, const String& qname, const map<String, Memory::VariantValue>& attrs)
{
actualReader_.HandleChildStart (r, uri, localName, qname, attrs);
}
template <typename T, typename ACTUAL_READER>
void OptionalTypesReader<T, ACTUAL_READER>::HandleTextInside (SAXObjectReader& r, const String& text)
{
actualReader_.HandleTextInside (r, text);
}
template <typename T, typename ACTUAL_READER>
void OptionalTypesReader<T, ACTUAL_READER>::HandleEndTag (SAXObjectReader& r)
{
shared_ptr<ObjectBase> saveCopyOfUs = r.GetTop (); // bump our reference count til the end of the procedure
// because the HandleEndTag will typically cause a POP on the reader that destroys us!
// However, we cannot do the copy back to value beofre the base POP, because
// it also might do some additioanl processing on its value
actualReader_.HandleEndTag (r);
*value_ = proxyValue_;
}
template <typename T>
inline ComplexObjectReader<T>::ComplexObjectReader (T* vp, const map<String, Memory::VariantValue>& attrs)
: fValuePtr (vp)
{
RequireNotNull (vp);
}
template <typename T>
void ComplexObjectReader<T>::HandleTextInside (SAXObjectReader& r, const String& text)
{
// OK so long as text is whitespace - or comment. Probably should check/assert, but KISS..., and count on validation to
// assure input is valid
Assert (text.IsWhitespace ());
}
template <typename T>
void ComplexObjectReader<T>::HandleEndTag (SAXObjectReader& r)
{
r.Pop ();
}
template <typename T>
void ComplexObjectReader<T>::_PushNewObjPtr (SAXObjectReader& r, ObjectBase* newlyAllocatedObject2Push)
{
RequireNotNull (newlyAllocatedObject2Push);
r.Push (shared_ptr<ObjectBase> (newlyAllocatedObject2Push));
}
template <typename TRAITS>
ListOfObjectReader<TRAITS>::ListOfObjectReader (vector<typename TRAITS::ElementType>* v, const map<String, Memory::VariantValue>& attrs)
: ComplexObjectReader<vector<typename TRAITS::ElementType>> (v)
, readingAT_ (false)
{
}
template <typename TRAITS>
void ListOfObjectReader<TRAITS>::HandleChildStart (SAXObjectReader& r, const String& uri, const String& localName, const String& qname, const map<String, Memory::VariantValue>& attrs)
{
if (localName == TRAITS::ElementName) {
if (readingAT_) {
Containers::ReserveSpeedTweekAdd1 (*this->fValuePtr);
this->fValuePtr->push_back (curTReading_);
readingAT_ = false;
}
readingAT_ = true;
curTReading_ = typename TRAITS::ElementType (); // clear because dont' want to keep values from previous elements
_PushNewObjPtr (r, DEBUG_NEW typename TRAITS::ReaderType (&curTReading_, attrs));
}
else {
ThrowUnRecognizedStartElt (uri, localName);
}
}
template <typename TRAITS>
void ListOfObjectReader<TRAITS>::HandleEndTag (SAXObjectReader& r)
{
if (readingAT_) {
Containers::ReserveSpeedTweekAdd1 (*this->fValuePtr);
this->fValuePtr->push_back (curTReading_);
readingAT_ = false;
}
ComplexObjectReader<vector<typename TRAITS::ElementType>>::HandleEndTag (r);
}
}
}
}
}
#endif /*_Stroika_Foundation_DataExchangeFormat_XML_SAXObjectReader_inl_*/
<commit_msg>use this->MEHTOD() in template - as required by gcc (correctly)<commit_after>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2013. All rights reserved
*/
#ifndef _Stroika_Foundation_DataExchangeFormat_XML_SAXObjectReader_inl_
#define _Stroika_Foundation_DataExchangeFormat_XML_SAXObjectReader_inl_ 1
/*
********************************************************************************
***************************** Implementation Details ***************************
********************************************************************************
*/
#include "../../Containers/Common.h"
namespace Stroika {
namespace Foundation {
namespace DataExchangeFormat {
namespace XML {
// class SAXObjectReader
inline SAXObjectReader::SAXObjectReader ()
#if qDefaultTracingOn
: fTraceThisReader (false)
#endif
{
}
inline void SAXObjectReader::Push (const shared_ptr<ObjectBase>& elt)
{
#if qDefaultTracingOn
if (fTraceThisReader) {
DbgTrace ("%sSAXObjectReader::Push", TraceLeader_ ().c_str ());
}
#endif
Containers::ReserveSpeedTweekAdd1 (fStack_);
fStack_.push_back (elt);
}
inline void SAXObjectReader::Pop ()
{
fStack_.pop_back ();
#if qDefaultTracingOn
if (fTraceThisReader) {
DbgTrace ("%sSAXObjectReader::Popped", TraceLeader_ ().c_str ());
}
#endif
}
inline shared_ptr<SAXObjectReader::ObjectBase> SAXObjectReader::GetTop () const
{
Require (not fStack_.empty ());
return fStack_.back ();
}
template <>
class BuiltinReader<String> : public SAXObjectReader::ObjectBase {
public:
BuiltinReader (String* intoVal, const map<String, Memory::VariantValue>& attrs = map<String, Memory::VariantValue> ());
private:
String* value_;
public:
virtual void HandleChildStart (SAXObjectReader& r, const String& uri, const String& localName, const String& qname, const map<String, Memory::VariantValue>& attrs) override;
virtual void HandleTextInside (SAXObjectReader& r, const String& text) override;
virtual void HandleEndTag (SAXObjectReader& r) override;
};
template <>
class BuiltinReader<int> : public SAXObjectReader::ObjectBase {
public:
BuiltinReader (int* intoVal, const map<String, Memory::VariantValue>& attrs = map<String, Memory::VariantValue> ());
private:
String tmpVal_;
int* value_;
public:
virtual void HandleChildStart (SAXObjectReader& r, const String& uri, const String& localName, const String& qname, const map<String, Memory::VariantValue>& attrs) override;
virtual void HandleTextInside (SAXObjectReader& r, const String& text) override;
virtual void HandleEndTag (SAXObjectReader& r) override;
};
template <>
class BuiltinReader<unsigned int> : public SAXObjectReader::ObjectBase {
public:
BuiltinReader (unsigned int* intoVal, const map<String, Memory::VariantValue>& attrs = map<String, Memory::VariantValue> ());
private:
String tmpVal_;
unsigned int* value_;
public:
virtual void HandleChildStart (SAXObjectReader& r, const String& uri, const String& localName, const String& qname, const map<String, Memory::VariantValue>& attrs) override;
virtual void HandleTextInside (SAXObjectReader& r, const String& text) override;
virtual void HandleEndTag (SAXObjectReader& r) override;
};
template <>
class BuiltinReader<float> : public SAXObjectReader::ObjectBase {
public:
BuiltinReader (float* intoVal, const map<String, Memory::VariantValue>& attrs = map<String, Memory::VariantValue> ());
private:
String tmpVal_;
float* value_;
public:
virtual void HandleChildStart (SAXObjectReader& r, const String& uri, const String& localName, const String& qname, const map<String, Memory::VariantValue>& attrs) override;
virtual void HandleTextInside (SAXObjectReader& r, const String& text) override;
virtual void HandleEndTag (SAXObjectReader& r) override;
};
template <>
class BuiltinReader<double> : public SAXObjectReader::ObjectBase {
public:
BuiltinReader (double* intoVal, const map<String, Memory::VariantValue>& attrs = map<String, Memory::VariantValue> ());
private:
String tmpVal_;
double* value_;
public:
virtual void HandleChildStart (SAXObjectReader& r, const String& uri, const String& localName, const String& qname, const map<String, Memory::VariantValue>& attrs) override;
virtual void HandleTextInside (SAXObjectReader& r, const String& text) override;
virtual void HandleEndTag (SAXObjectReader& r) override;
};
template <>
class BuiltinReader<bool> : public SAXObjectReader::ObjectBase {
public:
BuiltinReader (bool* intoVal, const map<String, Memory::VariantValue>& attrs = map<String, Memory::VariantValue> ());
private:
String tmpVal_;
bool* value_;
public:
virtual void HandleChildStart (SAXObjectReader& r, const String& uri, const String& localName, const String& qname, const map<String, Memory::VariantValue>& attrs) override;
virtual void HandleTextInside (SAXObjectReader& r, const String& text) override;
virtual void HandleEndTag (SAXObjectReader& r) override;
};
template <>
class BuiltinReader<Time::DateTime> : public SAXObjectReader::ObjectBase {
public:
BuiltinReader (Time::DateTime* intoVal, const map<String, Memory::VariantValue>& attrs = map<String, Memory::VariantValue> ());
private:
String tmpVal_;
Time::DateTime* value_;
public:
virtual void HandleChildStart (SAXObjectReader& r, const String& uri, const String& localName, const String& qname, const map<String, Memory::VariantValue>& attrs) override;
virtual void HandleTextInside (SAXObjectReader& r, const String& text) override;
virtual void HandleEndTag (SAXObjectReader& r) override;
};
template <typename T, typename ACTUAL_READER>
OptionalTypesReader<T, ACTUAL_READER>::OptionalTypesReader (Memory::Optional<T>* intoVal, const map<String, Memory::VariantValue>& attrs)
: value_ (intoVal)
, proxyValue_ ()
, actualReader_ (&proxyValue_)
{
}
template <typename T, typename ACTUAL_READER>
void OptionalTypesReader<T, ACTUAL_READER>::HandleChildStart (SAXObjectReader& r, const String& uri, const String& localName, const String& qname, const map<String, Memory::VariantValue>& attrs)
{
actualReader_.HandleChildStart (r, uri, localName, qname, attrs);
}
template <typename T, typename ACTUAL_READER>
void OptionalTypesReader<T, ACTUAL_READER>::HandleTextInside (SAXObjectReader& r, const String& text)
{
actualReader_.HandleTextInside (r, text);
}
template <typename T, typename ACTUAL_READER>
void OptionalTypesReader<T, ACTUAL_READER>::HandleEndTag (SAXObjectReader& r)
{
shared_ptr<ObjectBase> saveCopyOfUs = r.GetTop (); // bump our reference count til the end of the procedure
// because the HandleEndTag will typically cause a POP on the reader that destroys us!
// However, we cannot do the copy back to value beofre the base POP, because
// it also might do some additioanl processing on its value
actualReader_.HandleEndTag (r);
*value_ = proxyValue_;
}
template <typename T>
inline ComplexObjectReader<T>::ComplexObjectReader (T* vp, const map<String, Memory::VariantValue>& attrs)
: fValuePtr (vp)
{
RequireNotNull (vp);
}
template <typename T>
void ComplexObjectReader<T>::HandleTextInside (SAXObjectReader& r, const String& text)
{
// OK so long as text is whitespace - or comment. Probably should check/assert, but KISS..., and count on validation to
// assure input is valid
Assert (text.IsWhitespace ());
}
template <typename T>
void ComplexObjectReader<T>::HandleEndTag (SAXObjectReader& r)
{
r.Pop ();
}
template <typename T>
void ComplexObjectReader<T>::_PushNewObjPtr (SAXObjectReader& r, ObjectBase* newlyAllocatedObject2Push)
{
RequireNotNull (newlyAllocatedObject2Push);
r.Push (shared_ptr<ObjectBase> (newlyAllocatedObject2Push));
}
template <typename TRAITS>
ListOfObjectReader<TRAITS>::ListOfObjectReader (vector<typename TRAITS::ElementType>* v, const map<String, Memory::VariantValue>& attrs)
: ComplexObjectReader<vector<typename TRAITS::ElementType>> (v)
, readingAT_ (false)
{
}
template <typename TRAITS>
void ListOfObjectReader<TRAITS>::HandleChildStart (SAXObjectReader& r, const String& uri, const String& localName, const String& qname, const map<String, Memory::VariantValue>& attrs)
{
if (localName == TRAITS::ElementName) {
if (readingAT_) {
Containers::ReserveSpeedTweekAdd1 (*this->fValuePtr);
this->fValuePtr->push_back (curTReading_);
readingAT_ = false;
}
readingAT_ = true;
curTReading_ = typename TRAITS::ElementType (); // clear because dont' want to keep values from previous elements
_this->PushNewObjPtr (r, DEBUG_NEW typename TRAITS::ReaderType (&curTReading_, attrs));
}
else {
ThrowUnRecognizedStartElt (uri, localName);
}
}
template <typename TRAITS>
void ListOfObjectReader<TRAITS>::HandleEndTag (SAXObjectReader& r)
{
if (readingAT_) {
Containers::ReserveSpeedTweekAdd1 (*this->fValuePtr);
this->fValuePtr->push_back (curTReading_);
readingAT_ = false;
}
ComplexObjectReader<vector<typename TRAITS::ElementType>>::HandleEndTag (r);
}
}
}
}
}
#endif /*_Stroika_Foundation_DataExchangeFormat_XML_SAXObjectReader_inl_*/
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkGradientAnisotropicDiffusionImageFilterTest2.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include <fstream>
#include "itkCastImageFilter.h"
#include "itkGradientAnisotropicDiffusionImageFilter.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkChangeInformationImageFilter.h"
#include "itkDifferenceImageFilter.h"
typedef float PixelType;
typedef itk::Image<PixelType, 2> myFloatImage;
typedef itk::Image<PixelType, 2> ImageType;
typedef ImageType::Pointer ImagePointer;
namespace {
// compare two images with an intensity tolerance
bool SameImage(ImagePointer testImage, ImagePointer baselineImage)
{
PixelType intensityTolerance = 1;
int radiusTolerance = 0;
unsigned long numberOfPixelTolerance = 0;
typedef itk::DifferenceImageFilter<ImageType,ImageType> DiffType;
DiffType::Pointer diff = DiffType::New();
diff->SetValidInput(baselineImage);
diff->SetTestInput(testImage);
diff->SetDifferenceThreshold( intensityTolerance );
diff->SetToleranceRadius( radiusTolerance );
diff->UpdateLargestPossibleRegion();
unsigned long status = diff->GetNumberOfPixelsWithDifferences();
if (status > numberOfPixelTolerance)
{
std::cout << "Number of Different Pixels: " << status << std::endl;
return false;
}
return true;
}
}
int itkGradientAnisotropicDiffusionImageFilterTest2(int ac, char* av[] )
{
if(ac < 3)
{
std::cerr << "Usage: " << av[0] << " InputImage OutputImage\n";
return -1;
}
itk::ImageFileReader<myFloatImage>::Pointer input
= itk::ImageFileReader<myFloatImage>::New();
input->SetFileName(av[1]);
// Create a filter
itk::GradientAnisotropicDiffusionImageFilter<myFloatImage, myFloatImage>
::Pointer filter
= itk::GradientAnisotropicDiffusionImageFilter<myFloatImage, myFloatImage>
::New();
filter->SetNumberOfIterations(10);
filter->SetConductanceParameter(1.0f);
filter->SetTimeStep(0.125f);
filter->SetInput(input->GetOutput());
typedef itk::Image<unsigned char, 2> myUCharImage;
itk::CastImageFilter<myFloatImage, myUCharImage>::Pointer caster
= itk::CastImageFilter<myFloatImage, myUCharImage>::New();
caster->SetInput(filter->GetOutput());
try
{
caster->Update();
}
catch (itk::ExceptionObject& e)
{
std::cerr << "Exception detected: " << e.GetDescription();
return -1;
}
// Generate test image
itk::ImageFileWriter<myUCharImage>::Pointer writer;
writer = itk::ImageFileWriter<myUCharImage>::New();
writer->SetInput( caster->GetOutput() );
std::cout << "Writing " << av[2] << std::endl;
writer->SetFileName( av[2] );
writer->Update();
myFloatImage::Pointer normalImage = filter->GetOutput();
normalImage->DisconnectPipeline();
// We now set up testing when the image spacing is not trivial 1 and
// perform diffusion with spacing on
typedef itk::ChangeInformationImageFilter<myFloatImage> ChangeInformationType;
ChangeInformationType::Pointer changeInfo = ChangeInformationType::New();
changeInfo->SetInput( input->GetOutput() );
myFloatImage::SpacingType spacing;
spacing[0] = input->GetOutput()->GetSpacing()[0]*100.0;
spacing[1] = input->GetOutput()->GetSpacing()[1]*100.0;
changeInfo->SetOutputSpacing( spacing );
changeInfo->ChangeSpacingOn();
filter->SetInput( changeInfo->GetOutput() );
filter->UseImageSpacingOn();
// need to adjust the time step to the number of iterations equates
// to the same operation
filter->SetTimeStep( 100.0 * filter->GetTimeStep() );
try
{
filter->Update();
}
catch (itk::ExceptionObject& e)
{
std::cerr << "Exception detected: " << e.GetDescription();
return EXIT_FAILURE;
}
// the results with spacing should be about the same as without spacing
if ( !SameImage( filter->GetOutput(), normalImage ) )
{
std::cout << "Results varied with spacing enabled!" << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
<commit_msg>ENH: Tightening the pixel tolerance for comparing UseImageSpacing processed image<commit_after>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkGradientAnisotropicDiffusionImageFilterTest2.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include <fstream>
#include "itkCastImageFilter.h"
#include "itkGradientAnisotropicDiffusionImageFilter.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkChangeInformationImageFilter.h"
#include "itkDifferenceImageFilter.h"
typedef float PixelType;
typedef itk::Image<PixelType, 2> myFloatImage;
typedef itk::Image<PixelType, 2> ImageType;
typedef ImageType::Pointer ImagePointer;
namespace {
// compare two images with an intensity tolerance
bool SameImage(ImagePointer testImage, ImagePointer baselineImage)
{
PixelType intensityTolerance = .001;
int radiusTolerance = 0;
unsigned long numberOfPixelTolerance = 0;
typedef itk::DifferenceImageFilter<ImageType,ImageType> DiffType;
DiffType::Pointer diff = DiffType::New();
diff->SetValidInput(baselineImage);
diff->SetTestInput(testImage);
diff->SetDifferenceThreshold( intensityTolerance );
diff->SetToleranceRadius( radiusTolerance );
diff->UpdateLargestPossibleRegion();
unsigned long status = diff->GetNumberOfPixelsWithDifferences();
if (status > numberOfPixelTolerance)
{
std::cout << "Number of Different Pixels: " << status << std::endl;
return false;
}
return true;
}
}
int itkGradientAnisotropicDiffusionImageFilterTest2(int ac, char* av[] )
{
if(ac < 3)
{
std::cerr << "Usage: " << av[0] << " InputImage OutputImage\n";
return -1;
}
itk::ImageFileReader<myFloatImage>::Pointer input
= itk::ImageFileReader<myFloatImage>::New();
input->SetFileName(av[1]);
// Create a filter
itk::GradientAnisotropicDiffusionImageFilter<myFloatImage, myFloatImage>
::Pointer filter
= itk::GradientAnisotropicDiffusionImageFilter<myFloatImage, myFloatImage>
::New();
filter->SetNumberOfIterations(10);
filter->SetConductanceParameter(1.0f);
filter->SetTimeStep(0.125f);
filter->SetInput(input->GetOutput());
typedef itk::Image<unsigned char, 2> myUCharImage;
itk::CastImageFilter<myFloatImage, myUCharImage>::Pointer caster
= itk::CastImageFilter<myFloatImage, myUCharImage>::New();
caster->SetInput(filter->GetOutput());
try
{
caster->Update();
}
catch (itk::ExceptionObject& e)
{
std::cerr << "Exception detected: " << e.GetDescription();
return -1;
}
// Generate test image
itk::ImageFileWriter<myUCharImage>::Pointer writer;
writer = itk::ImageFileWriter<myUCharImage>::New();
writer->SetInput( caster->GetOutput() );
std::cout << "Writing " << av[2] << std::endl;
writer->SetFileName( av[2] );
writer->Update();
myFloatImage::Pointer normalImage = filter->GetOutput();
normalImage->DisconnectPipeline();
// We now set up testing when the image spacing is not trivial 1 and
// perform diffusion with spacing on
typedef itk::ChangeInformationImageFilter<myFloatImage> ChangeInformationType;
ChangeInformationType::Pointer changeInfo = ChangeInformationType::New();
changeInfo->SetInput( input->GetOutput() );
myFloatImage::SpacingType spacing;
spacing[0] = input->GetOutput()->GetSpacing()[0]*100.0;
spacing[1] = input->GetOutput()->GetSpacing()[1]*100.0;
changeInfo->SetOutputSpacing( spacing );
changeInfo->ChangeSpacingOn();
filter->SetInput( changeInfo->GetOutput() );
filter->UseImageSpacingOn();
// need to adjust the time step to the number of iterations equates
// to the same operation
filter->SetTimeStep( 100.0 * filter->GetTimeStep() );
try
{
filter->Update();
}
catch (itk::ExceptionObject& e)
{
std::cerr << "Exception detected: " << e.GetDescription();
return EXIT_FAILURE;
}
// the results with spacing should be about the same as without spacing
if ( !SameImage( filter->GetOutput(), normalImage ) )
{
std::cout << "Results varied with spacing enabled!" << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkSpatialObjectToImageStatisticsCalculatorTest.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 2002 Insight Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include <iostream>
#include "itkImage.h"
#include "itkSpatialObjectToImageStatisticsCalculator.h"
#include "itkSpatialObjectToImageFilter.h"
#include "itkFloodFilledSpatialFunctionConditionalIterator.h"
#include "itkEllipseSpatialObject.h"
#include "itkImageSliceIteratorWithIndex.h"
int itkSpatialObjectToImageStatisticsCalculatorTest(int, char * [] )
{
typedef unsigned char PixelType;
typedef itk::Image<PixelType,2> ImageType;
typedef itk::EllipseSpatialObject<2> EllipseType;
typedef itk::FloodFilledSpatialFunctionConditionalIterator<ImageType,
EllipseType> IteratorType;
// Image Definition
ImageType::RegionType region;
ImageType::SizeType size;
size.Fill(50);
// Circle definition
EllipseType::Pointer ellipse = EllipseType::New();
ellipse->SetRadius(10);
EllipseType::VectorType offset;
offset.Fill(25);
ellipse->GetIndexToObjectTransform()->SetOffset(offset);
ellipse->ComputeObjectToParentTransform();
// Create a test image
typedef itk::SpatialObjectToImageFilter<EllipseType,ImageType> ImageFilterType;
ImageFilterType::Pointer filter = ImageFilterType::New();
filter->SetInput(ellipse);
filter->SetSize(size);
filter->SetInsideValue(255);
filter->Update();
ImageType::Pointer image = filter->GetOutput();
offset.Fill(25);
ellipse->GetIndexToObjectTransform()->SetOffset(offset);
ellipse->ComputeObjectToParentTransform();
typedef itk::SpatialObjectToImageStatisticsCalculator<ImageType,EllipseType> CalculatorType;
CalculatorType::Pointer calculator = CalculatorType::New();
calculator->SetImage(image);
calculator->SetSpatialObject(ellipse);
calculator->Update();
std::cout << " --- Ellipse and Image perfectly aligned --- " << std::endl;
std::cout << "Sample mean = " << calculator->GetMean() << std::endl ;
std::cout << "Sample covariance = " << calculator->GetCovarianceMatrix();
if(calculator->GetMean() != 255
|| calculator->GetCovarianceMatrix()[0][0] != 0
)
{
std::cout << "[FAILED]" << std::endl;
return EXIT_FAILURE;
}
std::cout << "[PASSED]" << std::endl;
offset.Fill(20);
ellipse->GetIndexToObjectTransform()->SetOffset(offset);
ellipse->ComputeObjectToParentTransform();
ellipse->Update();
calculator->Update();
std::cout << " --- Ellipse and Image mismatched left --- " << std::endl;
std::cout << "Sample mean = " << calculator->GetMean() << std::endl ;
std::cout << "Sample covariance = " << calculator->GetCovarianceMatrix();
if( (fabs(calculator->GetMean()[0]-140.0)>1.0)
|| (fabs(calculator->GetCovarianceMatrix()[0][0]-16141.0)>1.0)
)
{
std::cout << "[FAILED]" << std::endl;
return EXIT_FAILURE;
}
std::cout << "[PASSED]" << std::endl;
std::cout << " --- Ellipse and Image mismatched right --- " << std::endl;
offset.Fill(30);
ellipse->GetIndexToObjectTransform()->SetOffset(offset);
ellipse->ComputeObjectToParentTransform();
ellipse->Update();
calculator->Update();
std::cout << "Sample mean = " << calculator->GetMean() << std::endl ;
std::cout << "Sample covariance = " << calculator->GetCovarianceMatrix();
if( (fabs(calculator->GetMean()[0]-140.0)>1.0)
|| (fabs(calculator->GetCovarianceMatrix()[0][0]-16141.0)>1.0)
)
{
std::cout << "[FAILED]" << std::endl;
return EXIT_FAILURE;
}
std::cout << "[PASSED]" << std::endl;
std::cout << " --- Testing higher dimensionality --- " << std::endl;
// Create a new 3D image
typedef itk::Image<PixelType,3> Image3DType;
Image3DType::Pointer image3D = Image3DType::New();
typedef Image3DType::RegionType RegionType;
typedef Image3DType::SizeType SizeType;
typedef Image3DType::IndexType IndexType;
SizeType size3D;
size3D[0]=50;
size3D[1]=50;
size3D[2]=3;
IndexType start;
start.Fill( 0 );
RegionType region3D;
region3D.SetIndex( start );
region3D.SetSize( size3D );
image3D->SetRegions( region3D );
image3D->Allocate();
image3D->FillBuffer(255);
// Fill the image
typedef itk::ImageSliceIteratorWithIndex< Image3DType > SliceIteratorType;
SliceIteratorType it( image3D, region3D );
it.GoToBegin();
it.SetFirstDirection( 0 ); // 0=x, 1=y, 2=z
it.SetSecondDirection( 1 ); // 0=x, 1=y, 2=z
unsigned int value = 0;
while( !it.IsAtEnd() )
{
while( !it.IsAtEndOfSlice() )
{
while( !it.IsAtEndOfLine() )
{
it.Set( value );
++it;
}
it.NextLine();
}
it.NextSlice();
value++;
}
typedef itk::EllipseSpatialObject<3> Ellipse3DType;
Ellipse3DType::Pointer ellipse3D = Ellipse3DType::New();
double radius[3];
radius[0] = 10;
radius[1] = 10;
radius[2] = 0;
ellipse3D->SetRadius(radius);
Ellipse3DType::VectorType offset3D;
offset3D.Fill(25);
offset3D[2]=0; // first slice
ellipse3D->GetIndexToObjectTransform()->SetOffset(offset3D);
ellipse3D->ComputeObjectToParentTransform();
// Create a new calculator with a sample size of 3
typedef itk::SpatialObjectToImageStatisticsCalculator<Image3DType,Ellipse3DType,3> Calculator3DType;
Calculator3DType::Pointer calculator3D = Calculator3DType::New();
calculator3D->SetImage(image3D);
calculator3D->SetSpatialObject(ellipse3D);
calculator3D->Update();
std::cout << "Sample mean = " << calculator3D->GetMean() << std::endl ;
std::cout << "Sample covariance = " << calculator3D->GetCovarianceMatrix();
if( (calculator3D->GetMean()[0] != 0)
|| (calculator3D->GetMean()[1] != 1)
|| (calculator3D->GetMean()[2] != 2)
)
{
std::cout << "[FAILED]" << std::endl;
return EXIT_FAILURE;
}
std::cout << "[PASSED]" << std::endl;
return EXIT_SUCCESS;
}
<commit_msg>ENH: Added debug info<commit_after>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkSpatialObjectToImageStatisticsCalculatorTest.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 2002 Insight Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include <iostream>
#include "itkImage.h"
#include "itkSpatialObjectToImageStatisticsCalculator.h"
#include "itkSpatialObjectToImageFilter.h"
#include "itkFloodFilledSpatialFunctionConditionalIterator.h"
#include "itkEllipseSpatialObject.h"
#include "itkImageSliceIteratorWithIndex.h"
int itkSpatialObjectToImageStatisticsCalculatorTest(int, char * [] )
{
typedef unsigned char PixelType;
typedef itk::Image<PixelType,2> ImageType;
typedef itk::EllipseSpatialObject<2> EllipseType;
typedef itk::FloodFilledSpatialFunctionConditionalIterator<ImageType,
EllipseType> IteratorType;
// Image Definition
ImageType::RegionType region;
ImageType::SizeType size;
size.Fill(50);
// Circle definition
EllipseType::Pointer ellipse = EllipseType::New();
ellipse->SetRadius(10);
EllipseType::VectorType offset;
offset.Fill(25);
ellipse->GetIndexToObjectTransform()->SetOffset(offset);
ellipse->ComputeObjectToParentTransform();
// Create a test image
typedef itk::SpatialObjectToImageFilter<EllipseType,ImageType> ImageFilterType;
ImageFilterType::Pointer filter = ImageFilterType::New();
filter->SetInput(ellipse);
filter->SetSize(size);
filter->SetInsideValue(255);
filter->Update();
ImageType::Pointer image = filter->GetOutput();
offset.Fill(25);
ellipse->GetIndexToObjectTransform()->SetOffset(offset);
ellipse->ComputeObjectToParentTransform();
typedef itk::SpatialObjectToImageStatisticsCalculator<ImageType,EllipseType> CalculatorType;
CalculatorType::Pointer calculator = CalculatorType::New();
calculator->SetImage(image);
calculator->SetSpatialObject(ellipse);
calculator->Update();
std::cout << " --- Ellipse and Image perfectly aligned --- " << std::endl;
std::cout << "Sample mean = " << calculator->GetMean() << std::endl ;
std::cout << "Sample covariance = " << calculator->GetCovarianceMatrix();
if(calculator->GetMean() != 255
|| calculator->GetCovarianceMatrix()[0][0] != 0
)
{
std::cout << "[FAILED]" << std::endl;
return EXIT_FAILURE;
}
std::cout << "[PASSED]" << std::endl;
offset.Fill(20);
ellipse->GetIndexToObjectTransform()->SetOffset(offset);
ellipse->ComputeObjectToParentTransform();
ellipse->Update();
calculator->Update();
std::cout << " --- Ellipse and Image mismatched left --- " << std::endl;
std::cout << "Sample mean = " << calculator->GetMean() << std::endl ;
std::cout << "Sample covariance = " << calculator->GetCovarianceMatrix();
if( (fabs(calculator->GetMean()[0]-140.0)>1.0)
|| (fabs(calculator->GetCovarianceMatrix()[0][0]-16141.0)>1.0)
)
{
std::cout << "[FAILED]" << std::endl;
return EXIT_FAILURE;
}
std::cout << "[PASSED]" << std::endl;
std::cout << " --- Ellipse and Image mismatched right --- " << std::endl;
offset.Fill(30);
ellipse->GetIndexToObjectTransform()->SetOffset(offset);
ellipse->ComputeObjectToParentTransform();
ellipse->Update();
calculator->Update();
std::cout << "Sample mean = " << calculator->GetMean() << std::endl ;
std::cout << "Sample covariance = " << calculator->GetCovarianceMatrix();
if( (fabs(calculator->GetMean()[0]-140.0)>1.0)
|| (fabs(calculator->GetCovarianceMatrix()[0][0]-16141.0)>1.0)
)
{
std::cout << "[FAILED]" << std::endl;
return EXIT_FAILURE;
}
std::cout << "[PASSED]" << std::endl;
std::cout << " --- Testing higher dimensionality --- " << std::endl;
// Create a new 3D image
typedef itk::Image<PixelType,3> Image3DType;
Image3DType::Pointer image3D = Image3DType::New();
typedef Image3DType::RegionType RegionType;
typedef Image3DType::SizeType SizeType;
typedef Image3DType::IndexType IndexType;
SizeType size3D;
size3D[0]=50;
size3D[1]=50;
size3D[2]=3;
IndexType start;
start.Fill( 0 );
RegionType region3D;
region3D.SetIndex( start );
region3D.SetSize( size3D );
image3D->SetRegions( region3D );
image3D->Allocate();
image3D->FillBuffer(255);
// Fill the image
std::cout << "Allocating image." << std::endl;
typedef itk::ImageSliceIteratorWithIndex< Image3DType > SliceIteratorType;
SliceIteratorType it( image3D, region3D );
it.GoToBegin();
it.SetFirstDirection( 0 ); // 0=x, 1=y, 2=z
it.SetSecondDirection( 1 ); // 0=x, 1=y, 2=z
unsigned int value = 0;
while( !it.IsAtEnd() )
{
while( !it.IsAtEndOfSlice() )
{
while( !it.IsAtEndOfLine() )
{
it.Set( value );
++it;
}
it.NextLine();
}
it.NextSlice();
value++;
}
std::cout << "Allocating spatial object." << std::endl;
typedef itk::EllipseSpatialObject<3> Ellipse3DType;
Ellipse3DType::Pointer ellipse3D = Ellipse3DType::New();
double radius[3];
radius[0] = 10;
radius[1] = 10;
radius[2] = 0;
ellipse3D->SetRadius(radius);
Ellipse3DType::VectorType offset3D;
offset3D.Fill(25);
offset3D[2]=0; // first slice
ellipse3D->GetIndexToObjectTransform()->SetOffset(offset3D);
ellipse3D->ComputeObjectToParentTransform();
// Create a new calculator with a sample size of 3
std::cout << "Updating calculator." << std::endl;
typedef itk::SpatialObjectToImageStatisticsCalculator<Image3DType,Ellipse3DType,3> Calculator3DType;
Calculator3DType::Pointer calculator3D = Calculator3DType::New();
calculator3D->SetImage(image3D);
calculator3D->SetSpatialObject(ellipse3D);
calculator3D->Update();
std::cout << "Sample mean = " << calculator3D->GetMean() << std::endl ;
std::cout << "Sample covariance = " << calculator3D->GetCovarianceMatrix();
if( (calculator3D->GetMean()[0] != 0)
|| (calculator3D->GetMean()[1] != 1)
|| (calculator3D->GetMean()[2] != 2)
)
{
std::cout << "[FAILED]" << std::endl;
return EXIT_FAILURE;
}
std::cout << "[PASSED]" << std::endl;
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2012 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 "android_webview/browser/renderer_host/aw_resource_dispatcher_host_delegate.h"
#include <string>
#include "android_webview/browser/aw_contents_io_thread_client.h"
#include "android_webview/browser/aw_login_delegate.h"
#include "android_webview/common/url_constants.h"
#include "base/memory/scoped_ptr.h"
#include "base/memory/scoped_vector.h"
#include "components/auto_login_parser/auto_login_parser.h"
#include "components/navigation_interception/intercept_navigation_delegate.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/resource_controller.h"
#include "content/public/browser/resource_dispatcher_host.h"
#include "content/public/browser/resource_dispatcher_host_login_delegate.h"
#include "content/public/browser/resource_request_info.h"
#include "content/public/browser/resource_throttle.h"
#include "content/public/common/url_constants.h"
#include "net/base/load_flags.h"
#include "net/http/http_response_headers.h"
#include "net/url_request/url_request.h"
using android_webview::AwContentsIoThreadClient;
using content::BrowserThread;
using navigation_interception::InterceptNavigationDelegate;
namespace {
base::LazyInstance<android_webview::AwResourceDispatcherHostDelegate>
g_webview_resource_dispatcher_host_delegate = LAZY_INSTANCE_INITIALIZER;
void SetCacheControlFlag(
net::URLRequest* request, int flag) {
const int all_cache_control_flags = net::LOAD_BYPASS_CACHE |
net::LOAD_VALIDATE_CACHE |
net::LOAD_PREFERRING_CACHE |
net::LOAD_ONLY_FROM_CACHE;
DCHECK((flag & all_cache_control_flags) == flag);
int load_flags = request->load_flags();
load_flags &= ~all_cache_control_flags;
load_flags |= flag;
request->set_load_flags(load_flags);
}
} // namespace
namespace android_webview {
// Calls through the IoThreadClient to check the embedders settings to determine
// if the request should be cancelled. There may not always be an IoThreadClient
// available for the |child_id|, |route_id| pair (in the case of newly created
// pop up windows, for example) and in that case the request and the client
// callbacks will be deferred the request until a client is ready.
class IoThreadClientThrottle : public content::ResourceThrottle {
public:
IoThreadClientThrottle(int child_id,
int route_id,
net::URLRequest* request);
virtual ~IoThreadClientThrottle();
// From content::ResourceThrottle
virtual void WillStartRequest(bool* defer) OVERRIDE;
virtual void WillRedirectRequest(const GURL& new_url, bool* defer) OVERRIDE;
bool MaybeDeferRequest(bool* defer);
void OnIoThreadClientReady(int new_child_id, int new_route_id);
bool MaybeBlockRequest();
bool ShouldBlockRequest();
int get_child_id() const { return child_id_; }
int get_route_id() const { return route_id_; }
private:
int child_id_;
int route_id_;
net::URLRequest* request_;
};
IoThreadClientThrottle::IoThreadClientThrottle(int child_id,
int route_id,
net::URLRequest* request)
: child_id_(child_id),
route_id_(route_id),
request_(request) { }
IoThreadClientThrottle::~IoThreadClientThrottle() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
g_webview_resource_dispatcher_host_delegate.Get().
RemovePendingThrottleOnIoThread(this);
}
void IoThreadClientThrottle::WillStartRequest(bool* defer) {
// TODO(sgurun): This block can be removed when crbug.com/277937 is fixed.
if (route_id_ < 1) {
// OPTIONS is used for preflighted requests which are generated internally.
DCHECK_EQ("OPTIONS", request_->method());
return;
}
DCHECK(child_id_);
if (!MaybeDeferRequest(defer)) {
MaybeBlockRequest();
}
}
void IoThreadClientThrottle::WillRedirectRequest(const GURL& new_url,
bool* defer) {
WillStartRequest(defer);
}
bool IoThreadClientThrottle::MaybeDeferRequest(bool* defer) {
*defer = false;
// Defer all requests of a pop up that is still not associated with Java
// client so that the client will get a chance to override requests.
scoped_ptr<AwContentsIoThreadClient> io_client =
AwContentsIoThreadClient::FromID(child_id_, route_id_);
if (io_client && io_client->PendingAssociation()) {
*defer = true;
AwResourceDispatcherHostDelegate::AddPendingThrottle(
child_id_, route_id_, this);
}
return *defer;
}
void IoThreadClientThrottle::OnIoThreadClientReady(int new_child_id,
int new_route_id) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
if (!MaybeBlockRequest()) {
controller()->Resume();
}
}
bool IoThreadClientThrottle::MaybeBlockRequest() {
if (ShouldBlockRequest()) {
controller()->CancelWithError(net::ERR_ACCESS_DENIED);
return true;
}
return false;
}
bool IoThreadClientThrottle::ShouldBlockRequest() {
scoped_ptr<AwContentsIoThreadClient> io_client =
AwContentsIoThreadClient::FromID(child_id_, route_id_);
DCHECK(io_client.get());
// Part of implementation of WebSettings.allowContentAccess.
if (request_->url().SchemeIs(android_webview::kContentScheme) &&
io_client->ShouldBlockContentUrls()) {
return true;
}
// Part of implementation of WebSettings.allowFileAccess.
if (request_->url().SchemeIsFile() &&
io_client->ShouldBlockFileUrls()) {
const GURL& url = request_->url();
if (!url.has_path() ||
// Application's assets and resources are always available.
(url.path().find(android_webview::kAndroidResourcePath) != 0 &&
url.path().find(android_webview::kAndroidAssetPath) != 0)) {
return true;
}
}
if (io_client->ShouldBlockNetworkLoads()) {
if (request_->url().SchemeIs(chrome::kFtpScheme)) {
return true;
}
SetCacheControlFlag(request_, net::LOAD_ONLY_FROM_CACHE);
} else {
AwContentsIoThreadClient::CacheMode cache_mode = io_client->GetCacheMode();
switch(cache_mode) {
case AwContentsIoThreadClient::LOAD_CACHE_ELSE_NETWORK:
SetCacheControlFlag(request_, net::LOAD_PREFERRING_CACHE);
break;
case AwContentsIoThreadClient::LOAD_NO_CACHE:
SetCacheControlFlag(request_, net::LOAD_BYPASS_CACHE);
break;
case AwContentsIoThreadClient::LOAD_CACHE_ONLY:
SetCacheControlFlag(request_, net::LOAD_ONLY_FROM_CACHE);
break;
default:
break;
}
}
return false;
}
// static
void AwResourceDispatcherHostDelegate::ResourceDispatcherHostCreated() {
content::ResourceDispatcherHost::Get()->SetDelegate(
&g_webview_resource_dispatcher_host_delegate.Get());
}
AwResourceDispatcherHostDelegate::AwResourceDispatcherHostDelegate()
: content::ResourceDispatcherHostDelegate() {
}
AwResourceDispatcherHostDelegate::~AwResourceDispatcherHostDelegate() {
}
void AwResourceDispatcherHostDelegate::RequestBeginning(
net::URLRequest* request,
content::ResourceContext* resource_context,
appcache::AppCacheService* appcache_service,
ResourceType::Type resource_type,
int child_id,
int route_id,
ScopedVector<content::ResourceThrottle>* throttles) {
// If io_client is NULL, then the browser side objects have already been
// destroyed, so do not do anything to the request. Conversely if the
// request relates to a not-yet-created popup window, then the client will
// be non-NULL but PopupPendingAssociation() will be set.
scoped_ptr<AwContentsIoThreadClient> io_client =
AwContentsIoThreadClient::FromID(child_id, route_id);
if (!io_client)
return;
throttles->push_back(new IoThreadClientThrottle(
child_id, route_id, request));
bool allow_intercepting =
// We allow intercepting navigations within subframes, but only if the
// scheme other than http or https. This is because the embedder
// can't distinguish main frame and subframe callbacks (which could lead
// to broken content if the embedder decides to not ignore the main frame
// navigation, but ignores the subframe navigation).
// The reason this is supported at all is that certain JavaScript-based
// frameworks use iframe navigation as a form of communication with the
// embedder.
(resource_type == ResourceType::MAIN_FRAME ||
(resource_type == ResourceType::SUB_FRAME &&
!request->url().SchemeIs(content::kHttpScheme) &&
!request->url().SchemeIs(content::kHttpsScheme)));
if (allow_intercepting) {
throttles->push_back(InterceptNavigationDelegate::CreateThrottleFor(
request));
}
}
void AwResourceDispatcherHostDelegate::DownloadStarting(
net::URLRequest* request,
content::ResourceContext* resource_context,
int child_id,
int route_id,
int request_id,
bool is_content_initiated,
bool must_download,
ScopedVector<content::ResourceThrottle>* throttles) {
GURL url(request->url());
std::string user_agent;
std::string content_disposition;
std::string mime_type;
int64 content_length = request->GetExpectedContentSize();
request->extra_request_headers().GetHeader(
net::HttpRequestHeaders::kUserAgent, &user_agent);
net::HttpResponseHeaders* response_headers = request->response_headers();
if (response_headers) {
response_headers->GetNormalizedHeader("content-disposition",
&content_disposition);
response_headers->GetMimeType(&mime_type);
}
request->Cancel();
scoped_ptr<AwContentsIoThreadClient> io_client =
AwContentsIoThreadClient::FromID(child_id, route_id);
// POST request cannot be repeated in general, so prevent client from
// retrying the same request, even if it is with a GET.
if ("GET" == request->method() && io_client) {
io_client->NewDownload(url,
user_agent,
content_disposition,
mime_type,
content_length);
}
}
bool AwResourceDispatcherHostDelegate::AcceptAuthRequest(
net::URLRequest* request,
net::AuthChallengeInfo* auth_info) {
return true;
}
content::ResourceDispatcherHostLoginDelegate*
AwResourceDispatcherHostDelegate::CreateLoginDelegate(
net::AuthChallengeInfo* auth_info,
net::URLRequest* request) {
return new AwLoginDelegate(auth_info, request);
}
bool AwResourceDispatcherHostDelegate::HandleExternalProtocol(const GURL& url,
int child_id,
int route_id) {
// The AwURLRequestJobFactory implementation should ensure this method never
// gets called.
NOTREACHED();
return false;
}
void AwResourceDispatcherHostDelegate::OnResponseStarted(
net::URLRequest* request,
content::ResourceContext* resource_context,
content::ResourceResponse* response,
IPC::Sender* sender) {
const content::ResourceRequestInfo* request_info =
content::ResourceRequestInfo::ForRequest(request);
if (!request_info) {
DLOG(FATAL) << "Started request without associated info: " <<
request->url();
return;
}
if (request_info->GetResourceType() == ResourceType::MAIN_FRAME) {
// Check for x-auto-login header.
auto_login_parser::HeaderData header_data;
if (auto_login_parser::ParserHeaderInResponse(
request, auto_login_parser::ALLOW_ANY_REALM, &header_data)) {
scoped_ptr<AwContentsIoThreadClient> io_client =
AwContentsIoThreadClient::FromID(request_info->GetChildID(),
request_info->GetRouteID());
io_client->NewLoginRequest(
header_data.realm, header_data.account, header_data.args);
}
}
}
void AwResourceDispatcherHostDelegate::RemovePendingThrottleOnIoThread(
IoThreadClientThrottle* throttle) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
PendingThrottleMap::iterator it = pending_throttles_.find(
ChildRouteIDPair(throttle->get_child_id(), throttle->get_route_id()));
if (it != pending_throttles_.end()) {
pending_throttles_.erase(it);
}
}
// static
void AwResourceDispatcherHostDelegate::OnIoThreadClientReady(
int new_child_id,
int new_route_id) {
BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
base::Bind(
&AwResourceDispatcherHostDelegate::OnIoThreadClientReadyInternal,
base::Unretained(
g_webview_resource_dispatcher_host_delegate.Pointer()),
new_child_id, new_route_id));
}
// static
void AwResourceDispatcherHostDelegate::AddPendingThrottle(
int child_id,
int route_id,
IoThreadClientThrottle* pending_throttle) {
BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
base::Bind(
&AwResourceDispatcherHostDelegate::AddPendingThrottleOnIoThread,
base::Unretained(
g_webview_resource_dispatcher_host_delegate.Pointer()),
child_id, route_id, pending_throttle));
}
void AwResourceDispatcherHostDelegate::AddPendingThrottleOnIoThread(
int child_id,
int route_id,
IoThreadClientThrottle* pending_throttle) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
pending_throttles_.insert(
std::pair<ChildRouteIDPair, IoThreadClientThrottle*>(
ChildRouteIDPair(child_id, route_id), pending_throttle));
}
void AwResourceDispatcherHostDelegate::OnIoThreadClientReadyInternal(
int new_child_id,
int new_route_id) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
PendingThrottleMap::iterator it = pending_throttles_.find(
ChildRouteIDPair(new_child_id, new_route_id));
if (it != pending_throttles_.end()) {
IoThreadClientThrottle* throttle = it->second;
throttle->OnIoThreadClientReady(new_child_id, new_route_id);
pending_throttles_.erase(it);
}
}
} // namespace android_webview
<commit_msg>[Android WebView] Check AwContentsIoThreadClient usage<commit_after>// Copyright (c) 2012 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 "android_webview/browser/renderer_host/aw_resource_dispatcher_host_delegate.h"
#include <string>
#include "android_webview/browser/aw_contents_io_thread_client.h"
#include "android_webview/browser/aw_login_delegate.h"
#include "android_webview/common/url_constants.h"
#include "base/memory/scoped_ptr.h"
#include "base/memory/scoped_vector.h"
#include "components/auto_login_parser/auto_login_parser.h"
#include "components/navigation_interception/intercept_navigation_delegate.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/resource_controller.h"
#include "content/public/browser/resource_dispatcher_host.h"
#include "content/public/browser/resource_dispatcher_host_login_delegate.h"
#include "content/public/browser/resource_request_info.h"
#include "content/public/browser/resource_throttle.h"
#include "content/public/common/url_constants.h"
#include "net/base/load_flags.h"
#include "net/http/http_response_headers.h"
#include "net/url_request/url_request.h"
using android_webview::AwContentsIoThreadClient;
using content::BrowserThread;
using navigation_interception::InterceptNavigationDelegate;
namespace {
base::LazyInstance<android_webview::AwResourceDispatcherHostDelegate>
g_webview_resource_dispatcher_host_delegate = LAZY_INSTANCE_INITIALIZER;
void SetCacheControlFlag(
net::URLRequest* request, int flag) {
const int all_cache_control_flags = net::LOAD_BYPASS_CACHE |
net::LOAD_VALIDATE_CACHE |
net::LOAD_PREFERRING_CACHE |
net::LOAD_ONLY_FROM_CACHE;
DCHECK((flag & all_cache_control_flags) == flag);
int load_flags = request->load_flags();
load_flags &= ~all_cache_control_flags;
load_flags |= flag;
request->set_load_flags(load_flags);
}
} // namespace
namespace android_webview {
// Calls through the IoThreadClient to check the embedders settings to determine
// if the request should be cancelled. There may not always be an IoThreadClient
// available for the |child_id|, |route_id| pair (in the case of newly created
// pop up windows, for example) and in that case the request and the client
// callbacks will be deferred the request until a client is ready.
class IoThreadClientThrottle : public content::ResourceThrottle {
public:
IoThreadClientThrottle(int child_id,
int route_id,
net::URLRequest* request);
virtual ~IoThreadClientThrottle();
// From content::ResourceThrottle
virtual void WillStartRequest(bool* defer) OVERRIDE;
virtual void WillRedirectRequest(const GURL& new_url, bool* defer) OVERRIDE;
bool MaybeDeferRequest(bool* defer);
void OnIoThreadClientReady(int new_child_id, int new_route_id);
bool MaybeBlockRequest();
bool ShouldBlockRequest();
int get_child_id() const { return child_id_; }
int get_route_id() const { return route_id_; }
private:
int child_id_;
int route_id_;
net::URLRequest* request_;
};
IoThreadClientThrottle::IoThreadClientThrottle(int child_id,
int route_id,
net::URLRequest* request)
: child_id_(child_id),
route_id_(route_id),
request_(request) { }
IoThreadClientThrottle::~IoThreadClientThrottle() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
g_webview_resource_dispatcher_host_delegate.Get().
RemovePendingThrottleOnIoThread(this);
}
void IoThreadClientThrottle::WillStartRequest(bool* defer) {
// TODO(sgurun): This block can be removed when crbug.com/277937 is fixed.
if (route_id_ < 1) {
// OPTIONS is used for preflighted requests which are generated internally.
DCHECK_EQ("OPTIONS", request_->method());
return;
}
DCHECK(child_id_);
if (!MaybeDeferRequest(defer)) {
MaybeBlockRequest();
}
}
void IoThreadClientThrottle::WillRedirectRequest(const GURL& new_url,
bool* defer) {
WillStartRequest(defer);
}
bool IoThreadClientThrottle::MaybeDeferRequest(bool* defer) {
*defer = false;
// Defer all requests of a pop up that is still not associated with Java
// client so that the client will get a chance to override requests.
scoped_ptr<AwContentsIoThreadClient> io_client =
AwContentsIoThreadClient::FromID(child_id_, route_id_);
if (io_client && io_client->PendingAssociation()) {
*defer = true;
AwResourceDispatcherHostDelegate::AddPendingThrottle(
child_id_, route_id_, this);
}
return *defer;
}
void IoThreadClientThrottle::OnIoThreadClientReady(int new_child_id,
int new_route_id) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
if (!MaybeBlockRequest()) {
controller()->Resume();
}
}
bool IoThreadClientThrottle::MaybeBlockRequest() {
if (ShouldBlockRequest()) {
controller()->CancelWithError(net::ERR_ACCESS_DENIED);
return true;
}
return false;
}
bool IoThreadClientThrottle::ShouldBlockRequest() {
scoped_ptr<AwContentsIoThreadClient> io_client =
AwContentsIoThreadClient::FromID(child_id_, route_id_);
if (!io_client)
return false;
// Part of implementation of WebSettings.allowContentAccess.
if (request_->url().SchemeIs(android_webview::kContentScheme) &&
io_client->ShouldBlockContentUrls()) {
return true;
}
// Part of implementation of WebSettings.allowFileAccess.
if (request_->url().SchemeIsFile() &&
io_client->ShouldBlockFileUrls()) {
const GURL& url = request_->url();
if (!url.has_path() ||
// Application's assets and resources are always available.
(url.path().find(android_webview::kAndroidResourcePath) != 0 &&
url.path().find(android_webview::kAndroidAssetPath) != 0)) {
return true;
}
}
if (io_client->ShouldBlockNetworkLoads()) {
if (request_->url().SchemeIs(chrome::kFtpScheme)) {
return true;
}
SetCacheControlFlag(request_, net::LOAD_ONLY_FROM_CACHE);
} else {
AwContentsIoThreadClient::CacheMode cache_mode = io_client->GetCacheMode();
switch(cache_mode) {
case AwContentsIoThreadClient::LOAD_CACHE_ELSE_NETWORK:
SetCacheControlFlag(request_, net::LOAD_PREFERRING_CACHE);
break;
case AwContentsIoThreadClient::LOAD_NO_CACHE:
SetCacheControlFlag(request_, net::LOAD_BYPASS_CACHE);
break;
case AwContentsIoThreadClient::LOAD_CACHE_ONLY:
SetCacheControlFlag(request_, net::LOAD_ONLY_FROM_CACHE);
break;
default:
break;
}
}
return false;
}
// static
void AwResourceDispatcherHostDelegate::ResourceDispatcherHostCreated() {
content::ResourceDispatcherHost::Get()->SetDelegate(
&g_webview_resource_dispatcher_host_delegate.Get());
}
AwResourceDispatcherHostDelegate::AwResourceDispatcherHostDelegate()
: content::ResourceDispatcherHostDelegate() {
}
AwResourceDispatcherHostDelegate::~AwResourceDispatcherHostDelegate() {
}
void AwResourceDispatcherHostDelegate::RequestBeginning(
net::URLRequest* request,
content::ResourceContext* resource_context,
appcache::AppCacheService* appcache_service,
ResourceType::Type resource_type,
int child_id,
int route_id,
ScopedVector<content::ResourceThrottle>* throttles) {
// If io_client is NULL, then the browser side objects have already been
// destroyed, so do not do anything to the request. Conversely if the
// request relates to a not-yet-created popup window, then the client will
// be non-NULL but PopupPendingAssociation() will be set.
scoped_ptr<AwContentsIoThreadClient> io_client =
AwContentsIoThreadClient::FromID(child_id, route_id);
if (!io_client)
return;
throttles->push_back(new IoThreadClientThrottle(
child_id, route_id, request));
bool allow_intercepting =
// We allow intercepting navigations within subframes, but only if the
// scheme other than http or https. This is because the embedder
// can't distinguish main frame and subframe callbacks (which could lead
// to broken content if the embedder decides to not ignore the main frame
// navigation, but ignores the subframe navigation).
// The reason this is supported at all is that certain JavaScript-based
// frameworks use iframe navigation as a form of communication with the
// embedder.
(resource_type == ResourceType::MAIN_FRAME ||
(resource_type == ResourceType::SUB_FRAME &&
!request->url().SchemeIs(content::kHttpScheme) &&
!request->url().SchemeIs(content::kHttpsScheme)));
if (allow_intercepting) {
throttles->push_back(InterceptNavigationDelegate::CreateThrottleFor(
request));
}
}
void AwResourceDispatcherHostDelegate::DownloadStarting(
net::URLRequest* request,
content::ResourceContext* resource_context,
int child_id,
int route_id,
int request_id,
bool is_content_initiated,
bool must_download,
ScopedVector<content::ResourceThrottle>* throttles) {
GURL url(request->url());
std::string user_agent;
std::string content_disposition;
std::string mime_type;
int64 content_length = request->GetExpectedContentSize();
request->extra_request_headers().GetHeader(
net::HttpRequestHeaders::kUserAgent, &user_agent);
net::HttpResponseHeaders* response_headers = request->response_headers();
if (response_headers) {
response_headers->GetNormalizedHeader("content-disposition",
&content_disposition);
response_headers->GetMimeType(&mime_type);
}
request->Cancel();
scoped_ptr<AwContentsIoThreadClient> io_client =
AwContentsIoThreadClient::FromID(child_id, route_id);
// POST request cannot be repeated in general, so prevent client from
// retrying the same request, even if it is with a GET.
if ("GET" == request->method() && io_client) {
io_client->NewDownload(url,
user_agent,
content_disposition,
mime_type,
content_length);
}
}
bool AwResourceDispatcherHostDelegate::AcceptAuthRequest(
net::URLRequest* request,
net::AuthChallengeInfo* auth_info) {
return true;
}
content::ResourceDispatcherHostLoginDelegate*
AwResourceDispatcherHostDelegate::CreateLoginDelegate(
net::AuthChallengeInfo* auth_info,
net::URLRequest* request) {
return new AwLoginDelegate(auth_info, request);
}
bool AwResourceDispatcherHostDelegate::HandleExternalProtocol(const GURL& url,
int child_id,
int route_id) {
// The AwURLRequestJobFactory implementation should ensure this method never
// gets called.
NOTREACHED();
return false;
}
void AwResourceDispatcherHostDelegate::OnResponseStarted(
net::URLRequest* request,
content::ResourceContext* resource_context,
content::ResourceResponse* response,
IPC::Sender* sender) {
const content::ResourceRequestInfo* request_info =
content::ResourceRequestInfo::ForRequest(request);
if (!request_info) {
DLOG(FATAL) << "Started request without associated info: " <<
request->url();
return;
}
if (request_info->GetResourceType() == ResourceType::MAIN_FRAME) {
// Check for x-auto-login header.
auto_login_parser::HeaderData header_data;
if (auto_login_parser::ParserHeaderInResponse(
request, auto_login_parser::ALLOW_ANY_REALM, &header_data)) {
scoped_ptr<AwContentsIoThreadClient> io_client =
AwContentsIoThreadClient::FromID(request_info->GetChildID(),
request_info->GetRouteID());
if (io_client) {
io_client->NewLoginRequest(
header_data.realm, header_data.account, header_data.args);
}
}
}
}
void AwResourceDispatcherHostDelegate::RemovePendingThrottleOnIoThread(
IoThreadClientThrottle* throttle) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
PendingThrottleMap::iterator it = pending_throttles_.find(
ChildRouteIDPair(throttle->get_child_id(), throttle->get_route_id()));
if (it != pending_throttles_.end()) {
pending_throttles_.erase(it);
}
}
// static
void AwResourceDispatcherHostDelegate::OnIoThreadClientReady(
int new_child_id,
int new_route_id) {
BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
base::Bind(
&AwResourceDispatcherHostDelegate::OnIoThreadClientReadyInternal,
base::Unretained(
g_webview_resource_dispatcher_host_delegate.Pointer()),
new_child_id, new_route_id));
}
// static
void AwResourceDispatcherHostDelegate::AddPendingThrottle(
int child_id,
int route_id,
IoThreadClientThrottle* pending_throttle) {
BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
base::Bind(
&AwResourceDispatcherHostDelegate::AddPendingThrottleOnIoThread,
base::Unretained(
g_webview_resource_dispatcher_host_delegate.Pointer()),
child_id, route_id, pending_throttle));
}
void AwResourceDispatcherHostDelegate::AddPendingThrottleOnIoThread(
int child_id,
int route_id,
IoThreadClientThrottle* pending_throttle) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
pending_throttles_.insert(
std::pair<ChildRouteIDPair, IoThreadClientThrottle*>(
ChildRouteIDPair(child_id, route_id), pending_throttle));
}
void AwResourceDispatcherHostDelegate::OnIoThreadClientReadyInternal(
int new_child_id,
int new_route_id) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
PendingThrottleMap::iterator it = pending_throttles_.find(
ChildRouteIDPair(new_child_id, new_route_id));
if (it != pending_throttles_.end()) {
IoThreadClientThrottle* throttle = it->second;
throttle->OnIoThreadClientReady(new_child_id, new_route_id);
pending_throttles_.erase(it);
}
}
} // namespace android_webview
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.