text
stringlengths 54
60.6k
|
---|
<commit_before>// This file is part of The New Aspell
// Copyright (C) 2002 by Christoph Hintermller under the GNU LGPL license
// version 2.0 or 2.1. You should have received a copy of the LGPL
// license along with this library if you did not you can find
// it at http://www.gnu.org/.
//
// Example for a filter implementation usable via extended filter library
// interface.
// This was added to Aspell by Christoph Hintermller
#include "settings.h"
#include "can_have_error.hpp"
#include "config.hpp"
#include "filter_char.hpp"
#include "indiv_filter.hpp"
#include "iostream.hpp"
#include "posib_err.hpp"
#include "string.hpp"
#include "string_enumeration.hpp"
#include "string_list.hpp"
#include "vector.hpp"
using namespace acommon;
namespace {
enum filterstate {hidden=0, visible=1};
class ContextFilter : public IndividualFilter {
filterstate state;
Vector<String> opening;
Vector<String> closing;
int correspond;
String filterversion;
PosibErr<bool> hidecode(FilterChar * begin,FilterChar * end);
public:
ContextFilter(void);
virtual void reset(void);
void process(FilterChar *& start,FilterChar *& stop);
virtual PosibErr<bool> setup(Config * config);
virtual ~ContextFilter();
};
ContextFilter::ContextFilter(void)
: opening(),
closing()
{
state=hidden;
correspond=-1;
opening.resize(3);
opening[0]="\"";
opening[1]="/*";
opening[2]="//";
closing.resize(3);
closing[0]="\"";
closing[1]="*/";
closing[2]="";
filterversion=VERSION;
}
PosibErr<bool> ContextFilter::setup(Config * config){
name_ = "context-filter";
StringList delimiters;
StringEnumeration * delimiterpairs;
const char * delimiterpair=NULL;
char * repair=NULL;
char * begin=NULL;
char * end=NULL;
String delimiter;
unsigned int countdelim=0;
if (config == NULL) {
fprintf(stderr,"Nothing to be configured\n");
return true;
}
if (config->retrieve_bool("f-context-visible-first")) {
state=visible;
}
config->retrieve_list("f-context-delimiters", &delimiters);
delimiterpairs=delimiters.elements();
opening.resize(0);
closing.resize(0);
while ((delimiterpair=delimiterpairs->next())) {
if ((begin=repair=strdup(delimiterpair)) == NULL) {
//fprintf(stderr,"ifailed to initialise %s filter\n",filter_name());
return false;
}
end=repair+strlen(repair);
while ((*begin != ' ') && (*begin != '\t') && (begin != end)) {
begin++;
}
if (begin == repair) {
fprintf(stderr,"no delimiter pair: `%s'\n",repair);
free(repair);
//FIXME replace someday by make_err
//fprintf(stderr,"ifailed to initialise %s filter\n",filter_name());
return false;
}
if (((*begin == ' ') || (*begin == '\t')) && (begin != end)) {
*begin='\0';
opening.resize(opening.size()+1);
opening[opening.size()-1]=repair;
begin++;
}
while (((*begin == ' ') || (*begin == '\t')) && (begin != end)) {
begin++;
}
if ((*begin != ' ') && (*begin != '\t') && (begin != end)) {
closing.resize(closing.size()+1);
if (strcmp(begin,"\\0") != 0) {
closing[closing.size()-1]=begin;
}
else {
closing[closing.size()-1]="";
}
}
else {
closing.resize(closing.size()+1);
closing[closing.size()-1]="";
}
free(repair);
}
if (state == visible) {
for (countdelim=0;(countdelim < opening.size()) &&
(countdelim < closing.size());countdelim++) {
delimiter=opening[countdelim];
opening[countdelim]=closing[countdelim];
closing[countdelim]=delimiter;
}
}
//fprintf(stderr,"%s filter initialised\n",filter_name());
return true;
}
void ContextFilter::process(FilterChar *& start,FilterChar *& stop) {
FilterChar * current=start-1;
FilterChar * beginblind=start;
FilterChar * endblind=stop;
FilterChar * localstop=stop;
int countmasking=0;
int countdelimit=0;
int matchdelim=0;
if ((localstop > start+1) && (*(localstop-1) == '\0')) {
localstop--;
endblind=localstop;
}
if (state == visible) {
beginblind=endblind;
}
while (( ++current < localstop) && (*current != '\0')) {
if (*current == '\\') {
countmasking++;
continue;
}
if (state == visible) {
if ((countmasking % 2 == 0) && (correspond < 0)) {
for (countdelimit=0;
countdelimit < (signed)closing.size();countdelimit++) {
for (matchdelim=0;
(current+closing[countdelimit].size() < localstop) &&
(matchdelim < (signed)closing[countdelimit].size());
matchdelim++){
//FIXME Warning about comparison of signed and unsigned in following line
if (current[matchdelim] != closing[countdelimit][matchdelim]) {
break;
}
}
if ((matchdelim == (signed) closing[countdelimit].size()) &&
closing[countdelimit].size()) {
correspond=countdelimit;
break;
}
}
}
if ((countmasking % 2 == 0) && (correspond >= 0) &&
(correspond < (signed)closing.size()) &&
(closing[correspond].size() > 0) &&
(current+closing[correspond].size() < localstop)) {
for (matchdelim=0;matchdelim < (signed)closing[correspond].size();
matchdelim++) {
//FIXME Warning about comparison of signed and unsigned in following line
if (current[matchdelim] != closing[correspond][matchdelim]) {
break;
}
}
if ((matchdelim == (signed) closing[correspond].size()) &&
closing[correspond].size()) {
beginblind=current;
endblind=localstop;
state=hidden;
correspond=-1;
}
}
countmasking=0;
continue;
}
if (countmasking % 2) {
countmasking=0;
continue;
}
countmasking=0;
for (countdelimit=0;countdelimit < (signed)opening.size();countdelimit++) {
for (matchdelim=0;(current+opening[countdelimit].size() < localstop) &&
(matchdelim < (signed)opening[countdelimit].size());
matchdelim++) {
//FIXME Warning about comparison of signed and unsigned in following line
if (current[matchdelim] != opening[countdelimit][matchdelim]) {
break;
}
}
if ((matchdelim == (signed) opening[countdelimit].size()) &&
opening[countdelimit].size()) {
endblind=current+opening[countdelimit].size();
state=visible;
hidecode(beginblind,endblind);
current=endblind-1;
beginblind=endblind=localstop;
correspond=countdelimit;
break;
}
}
}
if ((state == visible) &&
(correspond >= 0) && (correspond < (signed)closing.size()) &&
(closing[correspond] == "") && (countmasking % 2 == 0)) {
state=hidden;
correspond=-1;
}
if (beginblind < endblind) {
hidecode(beginblind,endblind);
}
}
PosibErr<bool> ContextFilter::hidecode(FilterChar * begin,FilterChar * end) {
//FIXME here we go, a more efficient context hiding blinding might be used :)
FilterChar * current=begin;
while (current < end) {
if ((*current != '\t') && (*current != '\n') && (*current != '\r')) {
*current=' ';
}
current++;
}
return true;
}
void ContextFilter::reset(void) {
opening.resize(0);
closing.resize(0);
state=hidden;
}
ContextFilter::~ContextFilter() {
reset();
}
}
C_EXPORT
IndividualFilter * new_aspell_context_filter() {
return new ContextFilter;
}
<commit_msg>context filter: fix memory leak<commit_after>// This file is part of The New Aspell
// Copyright (C) 2002 by Christoph Hintermller under the GNU LGPL license
// version 2.0 or 2.1. You should have received a copy of the LGPL
// license along with this library if you did not you can find
// it at http://www.gnu.org/.
//
// Example for a filter implementation usable via extended filter library
// interface.
// This was added to Aspell by Christoph Hintermller
#include "settings.h"
#include "can_have_error.hpp"
#include "config.hpp"
#include "filter_char.hpp"
#include "indiv_filter.hpp"
#include "iostream.hpp"
#include "posib_err.hpp"
#include "stack_ptr.hpp"
#include "string.hpp"
#include "string_enumeration.hpp"
#include "string_list.hpp"
#include "vector.hpp"
using namespace acommon;
namespace {
enum filterstate {hidden=0, visible=1};
class ContextFilter : public IndividualFilter {
filterstate state;
Vector<String> opening;
Vector<String> closing;
int correspond;
String filterversion;
PosibErr<bool> hidecode(FilterChar * begin,FilterChar * end);
public:
ContextFilter(void);
virtual void reset(void);
void process(FilterChar *& start,FilterChar *& stop);
virtual PosibErr<bool> setup(Config * config);
virtual ~ContextFilter();
};
ContextFilter::ContextFilter(void)
: opening(),
closing()
{
state=hidden;
correspond=-1;
opening.resize(3);
opening[0]="\"";
opening[1]="/*";
opening[2]="//";
closing.resize(3);
closing[0]="\"";
closing[1]="*/";
closing[2]="";
filterversion=VERSION;
}
PosibErr<bool> ContextFilter::setup(Config * config){
name_ = "context-filter";
StringList delimiters;
StackPtr<StringEnumeration> delimiterpairs;
const char * delimiterpair=NULL;
char * repair=NULL;
char * begin=NULL;
char * end=NULL;
String delimiter;
unsigned int countdelim=0;
if (config == NULL) {
fprintf(stderr,"Nothing to be configured\n");
return true;
}
if (config->retrieve_bool("f-context-visible-first")) {
state=visible;
}
config->retrieve_list("f-context-delimiters", &delimiters);
delimiterpairs.reset(delimiters.elements());
opening.resize(0);
closing.resize(0);
while ((delimiterpair=delimiterpairs->next())) {
if ((begin=repair=strdup(delimiterpair)) == NULL) {
//fprintf(stderr,"ifailed to initialise %s filter\n",filter_name());
return false;
}
end=repair+strlen(repair);
while ((*begin != ' ') && (*begin != '\t') && (begin != end)) {
begin++;
}
if (begin == repair) {
fprintf(stderr,"no delimiter pair: `%s'\n",repair);
free(repair);
//FIXME replace someday by make_err
//fprintf(stderr,"ifailed to initialise %s filter\n",filter_name());
return false;
}
if (((*begin == ' ') || (*begin == '\t')) && (begin != end)) {
*begin='\0';
opening.resize(opening.size()+1);
opening[opening.size()-1]=repair;
begin++;
}
while (((*begin == ' ') || (*begin == '\t')) && (begin != end)) {
begin++;
}
if ((*begin != ' ') && (*begin != '\t') && (begin != end)) {
closing.resize(closing.size()+1);
if (strcmp(begin,"\\0") != 0) {
closing[closing.size()-1]=begin;
}
else {
closing[closing.size()-1]="";
}
}
else {
closing.resize(closing.size()+1);
closing[closing.size()-1]="";
}
free(repair);
}
if (state == visible) {
for (countdelim=0;(countdelim < opening.size()) &&
(countdelim < closing.size());countdelim++) {
delimiter=opening[countdelim];
opening[countdelim]=closing[countdelim];
closing[countdelim]=delimiter;
}
}
//fprintf(stderr,"%s filter initialised\n",filter_name());
return true;
}
void ContextFilter::process(FilterChar *& start,FilterChar *& stop) {
FilterChar * current=start-1;
FilterChar * beginblind=start;
FilterChar * endblind=stop;
FilterChar * localstop=stop;
int countmasking=0;
int countdelimit=0;
int matchdelim=0;
if ((localstop > start+1) && (*(localstop-1) == '\0')) {
localstop--;
endblind=localstop;
}
if (state == visible) {
beginblind=endblind;
}
while (( ++current < localstop) && (*current != '\0')) {
if (*current == '\\') {
countmasking++;
continue;
}
if (state == visible) {
if ((countmasking % 2 == 0) && (correspond < 0)) {
for (countdelimit=0;
countdelimit < (signed)closing.size();countdelimit++) {
for (matchdelim=0;
(current+closing[countdelimit].size() < localstop) &&
(matchdelim < (signed)closing[countdelimit].size());
matchdelim++){
//FIXME Warning about comparison of signed and unsigned in following line
if (current[matchdelim] != closing[countdelimit][matchdelim]) {
break;
}
}
if ((matchdelim == (signed) closing[countdelimit].size()) &&
closing[countdelimit].size()) {
correspond=countdelimit;
break;
}
}
}
if ((countmasking % 2 == 0) && (correspond >= 0) &&
(correspond < (signed)closing.size()) &&
(closing[correspond].size() > 0) &&
(current+closing[correspond].size() < localstop)) {
for (matchdelim=0;matchdelim < (signed)closing[correspond].size();
matchdelim++) {
//FIXME Warning about comparison of signed and unsigned in following line
if (current[matchdelim] != closing[correspond][matchdelim]) {
break;
}
}
if ((matchdelim == (signed) closing[correspond].size()) &&
closing[correspond].size()) {
beginblind=current;
endblind=localstop;
state=hidden;
correspond=-1;
}
}
countmasking=0;
continue;
}
if (countmasking % 2) {
countmasking=0;
continue;
}
countmasking=0;
for (countdelimit=0;countdelimit < (signed)opening.size();countdelimit++) {
for (matchdelim=0;(current+opening[countdelimit].size() < localstop) &&
(matchdelim < (signed)opening[countdelimit].size());
matchdelim++) {
//FIXME Warning about comparison of signed and unsigned in following line
if (current[matchdelim] != opening[countdelimit][matchdelim]) {
break;
}
}
if ((matchdelim == (signed) opening[countdelimit].size()) &&
opening[countdelimit].size()) {
endblind=current+opening[countdelimit].size();
state=visible;
hidecode(beginblind,endblind);
current=endblind-1;
beginblind=endblind=localstop;
correspond=countdelimit;
break;
}
}
}
if ((state == visible) &&
(correspond >= 0) && (correspond < (signed)closing.size()) &&
(closing[correspond] == "") && (countmasking % 2 == 0)) {
state=hidden;
correspond=-1;
}
if (beginblind < endblind) {
hidecode(beginblind,endblind);
}
}
PosibErr<bool> ContextFilter::hidecode(FilterChar * begin,FilterChar * end) {
//FIXME here we go, a more efficient context hiding blinding might be used :)
FilterChar * current=begin;
while (current < end) {
if ((*current != '\t') && (*current != '\n') && (*current != '\r')) {
*current=' ';
}
current++;
}
return true;
}
void ContextFilter::reset(void) {
opening.resize(0);
closing.resize(0);
state=hidden;
}
ContextFilter::~ContextFilter() {
reset();
}
}
C_EXPORT
IndividualFilter * new_aspell_context_filter() {
return new ContextFilter;
}
<|endoftext|> |
<commit_before>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2014 Robert Osfield
*
* This library is open source and may be redistributed and/or modified under
* the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
* (at your option) any later version. The full license is in LICENSE file
* included with this distribution, and on the openscenegraph.org website.
*
* 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
* OpenSceneGraph Public License for more details.
*/
#include <osgUI/Style>
#include <osg/Geode>
#include <osg/Depth>
#include <osg/TexGen>
#include <osg/AlphaFunc>
#include <osgText/Text>
#include <osgDB/ReadFile>
using namespace osgUI;
osg::ref_ptr<Style>& Style::instance()
{
static osg::ref_ptr<Style> s_style = new Style;
return s_style;
}
OSG_INIT_SINGLETON_PROXY(StyleSingletonProxy, Style::instance())
Style::Style()
{
osg::ref_ptr<osg::Image> image = new osg::Image;
image->allocateImage(1,1,1,GL_RGBA, GL_FLOAT);
*(reinterpret_cast<osg::Vec4f*>(image->data(0,0,0))) = osg::Vec4f(1.0f, 1.0f, 1.0f, 1.0f);
_clipTexture = new osg::Texture2D;
_clipTexture->setImage(image.get());
_clipTexture->setBorderColor(osg::Vec4f(1.0f,1.0f,1.0f,0.0f));
_clipTexture->setWrap(osg::Texture::WRAP_S, osg::Texture::CLAMP_TO_BORDER);
_clipTexture->setWrap(osg::Texture::WRAP_T, osg::Texture::CLAMP_TO_BORDER);
_clipTexture->setFilter(osg::Texture::MIN_FILTER, osg::Texture::NEAREST);
_clipTexture->setFilter(osg::Texture::MAG_FILTER, osg::Texture::NEAREST);
//image = osgDB::readImageFile("Images/lz.rgb");
//_clipTexture->setImage(image.get());
_disabledDepthWrite = new osg::Depth(osg::Depth::LESS,0.0, 1.0,false);
_enabledDepthWrite = new osg::Depth(osg::Depth::LESS,0.0, 1.0,true);
_disableColorWriteMask = new osg::ColorMask(false, false, false, false);
}
Style::Style(const Style& style, const osg::CopyOp& copyop):
osg::Object(style, copyop),
_clipTexture(style._clipTexture)
{
}
osg::Node* Style::createPanel(const osg::BoundingBox& extents, const osg::Vec4& colour)
{
OSG_NOTICE<<"Creating Panel"<<std::endl;
osg::ref_ptr<osg::Geometry> geometry = new osg::Geometry;
geometry->setName("Panel");
osg::ref_ptr<osg::Vec3Array> vertices = new osg::Vec3Array;
geometry->setVertexArray(vertices.get());
vertices->push_back( osg::Vec3(extents.xMin(), extents.yMin(), extents.zMin()) );
vertices->push_back( osg::Vec3(extents.xMin(), extents.yMax(), extents.zMin()) );
vertices->push_back( osg::Vec3(extents.xMax(), extents.yMin(), extents.zMin()) );
vertices->push_back( osg::Vec3(extents.xMax(), extents.yMax(), extents.zMin()) );
osg::ref_ptr<osg::Vec4Array> colours = new osg::Vec4Array;
geometry->setColorArray(colours, osg::Array::BIND_OVERALL);
colours->push_back( colour );
geometry->addPrimitiveSet( new osg::DrawArrays(GL_TRIANGLE_STRIP, 0, 4) );
return geometry.release();
}
osg::Node* Style::createDepthSetPanel(const osg::BoundingBox& extents)
{
osg::ref_ptr<osg::Geometry> geometry = new osg::Geometry;
geometry->setName("DepthSetPanel");
osg::ref_ptr<osg::Vec3Array> vertices = new osg::Vec3Array;
geometry->setVertexArray(vertices.get());
vertices->push_back( osg::Vec3(extents.xMin(), extents.yMin(), extents.zMin()) );
vertices->push_back( osg::Vec3(extents.xMin(), extents.yMax(), extents.zMin()) );
vertices->push_back( osg::Vec3(extents.xMax(), extents.yMin(), extents.zMin()) );
vertices->push_back( osg::Vec3(extents.xMax(), extents.yMax(), extents.zMin()) );
geometry->addPrimitiveSet( new osg::DrawArrays(GL_TRIANGLE_STRIP, 0, 4) );
osg::ref_ptr<osg::StateSet> stateset = geometry->getOrCreateStateSet();
stateset->setAttributeAndModes( _enabledDepthWrite.get(), osg::StateAttribute::ON);
stateset->setAttributeAndModes( _disableColorWriteMask.get() );
return geometry.release();
}
osg::Node* Style::createFrame(const osg::BoundingBox& extents, const FrameSettings* frameSettings, const osg::Vec4& color)
{
osg::ref_ptr<osg::Geometry> geometry = new osg::Geometry;
geometry->setName("Frame");
float topScale = 1.0f;
float bottomScale = 1.0f;
float leftScale = 1.0f;
float rightScale = 1.0f;
if (frameSettings)
{
switch(frameSettings->getShadow())
{
case(FrameSettings::PLAIN):
// default settings are appropriate for PLAIN
break;
case(FrameSettings::SUNKEN):
topScale = 0.6f;
bottomScale = 1.2f;
leftScale = 0.8f;
rightScale = 0.8f;
break;
case(FrameSettings::RAISED):
topScale = 1.2f;
bottomScale = 0.6f;
leftScale = 0.8f;
rightScale = 0.8f;
break;
}
}
osg::Vec4 topColor(osg::minimum(color.r()*topScale,1.0f), osg::minimum(color.g()*topScale,1.0f), osg::minimum(color.b()*topScale,1.0f), color.a());
osg::Vec4 bottomColor(osg::minimum(color.r()*bottomScale,1.0f), osg::minimum(color.g()*bottomScale,1.0f), osg::minimum(color.b()*bottomScale,1.0f), color.a());
osg::Vec4 leftColor(osg::minimum(color.r()*leftScale,1.0f), osg::minimum(color.g()*leftScale,1.0f), osg::minimum(color.b()*leftScale,1.0f), color.a());
osg::Vec4 rightColor(osg::minimum(color.r()*rightScale,1.0f), osg::minimum(color.g()*rightScale,1.0f), osg::minimum(color.b()*rightScale,1.0f), color.a());
float lineWidth = frameSettings ? frameSettings->getLineWidth() : 1.0f;
osg::Vec3 outerBottomLeft(extents.xMin(), extents.yMin(), extents.zMin());
osg::Vec3 outerBottomRight(extents.xMax(), extents.yMin(), extents.zMin());
osg::Vec3 outerTopLeft(extents.xMin(), extents.yMax(), extents.zMin());
osg::Vec3 outerTopRight(extents.xMax(), extents.yMax(), extents.zMin());
osg::Vec3 innerBottomLeft(extents.xMin()+lineWidth, extents.yMin()+lineWidth, extents.zMin());
osg::Vec3 innerBottomRight(extents.xMax()-lineWidth, extents.yMin()+lineWidth, extents.zMin());
osg::Vec3 innerTopLeft(extents.xMin()+lineWidth, extents.yMax()-lineWidth, extents.zMin());
osg::Vec3 innerTopRight(extents.xMax()-lineWidth, extents.yMax()-lineWidth, extents.zMin());
osg::ref_ptr<osg::Vec3Array> vertices = new osg::Vec3Array;
geometry->setVertexArray(vertices.get());
vertices->push_back( outerBottomLeft ); // 0
vertices->push_back( outerBottomRight ); // 1
vertices->push_back( outerTopLeft ); // 2
vertices->push_back( outerTopRight ); // 3
vertices->push_back( innerBottomLeft ); // 4
vertices->push_back( innerBottomRight ); // 5
vertices->push_back( innerTopLeft ); // 6
vertices->push_back( innerTopRight ); // 7
osg::ref_ptr<osg::Vec4Array> colours = new osg::Vec4Array;
geometry->setColorArray(colours.get(), osg::Array::BIND_PER_PRIMITIVE_SET);
// bottom
{
colours->push_back(bottomColor);
osg::ref_ptr<osg::DrawElementsUShort> primitives = new osg::DrawElementsUShort(GL_TRIANGLE_STRIP);
geometry->addPrimitiveSet(primitives.get());
primitives->push_back(4);
primitives->push_back(0);
primitives->push_back(5);
primitives->push_back(1);
}
// top
{
colours->push_back(topColor);
osg::ref_ptr<osg::DrawElementsUShort> primitives = new osg::DrawElementsUShort(GL_TRIANGLE_STRIP);
geometry->addPrimitiveSet(primitives.get());
primitives->push_back(2);
primitives->push_back(6);
primitives->push_back(3);
primitives->push_back(7);
}
// left
{
colours->push_back(leftColor);
osg::ref_ptr<osg::DrawElementsUShort> primitives = new osg::DrawElementsUShort(GL_TRIANGLE_STRIP);
geometry->addPrimitiveSet(primitives.get());
primitives->push_back(2);
primitives->push_back(0);
primitives->push_back(6);
primitives->push_back(4);
}
// right
{
colours->push_back(rightColor);
osg::ref_ptr<osg::DrawElementsUShort> primitives = new osg::DrawElementsUShort(GL_TRIANGLE_STRIP);
geometry->addPrimitiveSet(primitives.get());
primitives->push_back(7);
primitives->push_back(5);
primitives->push_back(3);
primitives->push_back(1);
}
return geometry.release();
}
osg::Node* Style::createText(const osg::BoundingBox& extents, const AlignmentSettings* as, const TextSettings* ts, const std::string& text)
{
osg::ref_ptr<osgText::Text> textDrawable = new osgText::Text;
textDrawable->setName("Text");
textDrawable->setText(text);
textDrawable->setPosition( osg::Vec3(extents.xMin(), extents.yMin(), extents.zMin()) );
textDrawable->setEnableDepthWrites(false);
if (ts)
{
textDrawable->setFont(ts->getFont());
textDrawable->setCharacterSize(ts->getCharacterSize());
}
if (as)
{
osgText::TextBase::AlignmentType alignmentType = static_cast<osgText::TextBase::AlignmentType>(as->getAlignment());
textDrawable->setAlignment(alignmentType);
}
return textDrawable.release();
}
osg::Node* Style::createIcon(const osg::BoundingBox& extents, const std::string& filename)
{
return 0;
}
void Style::setupDialogStateSet(osg::StateSet* stateset)
{
stateset->setRenderBinDetails(5, "TraversalOrderBin", osg::StateSet::OVERRIDE_RENDERBIN_DETAILS);
stateset->setMode( GL_LIGHTING, osg::StateAttribute::OFF );
stateset->setAttributeAndModes( _disabledDepthWrite.get(), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE );
}
void Style::setupClipStateSet(const osg::BoundingBox& extents, osg::StateSet* stateset)
{
unsigned int clipTextureUnit = 1;
stateset->setAttributeAndModes( new osg::AlphaFunc(osg::AlphaFunc::GREATER, 0.0f), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE);
stateset->setTextureAttributeAndModes( clipTextureUnit, _clipTexture.get(), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE);
osg::Matrixd matrix = osg::Matrixd::translate(osg::Vec3(-extents.xMin(), -extents.yMin(), -extents.zMin()))*
osg::Matrixd::scale(osg::Vec3(1.0f/(extents.xMax()-extents.xMin()), 1.0f/(extents.yMax()-extents.yMin()), 1.0f));
osg::ref_ptr<osg::TexGen> texgen = new osg::TexGen;
texgen->setPlanesFromMatrix(matrix);
texgen->setMode(osg::TexGen::OBJECT_LINEAR);
stateset->setTextureAttributeAndModes( clipTextureUnit, texgen.get(), osg::StateAttribute::ON);
}
<commit_msg>Added handling of AligmentSettings of Text layout<commit_after>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2014 Robert Osfield
*
* This library is open source and may be redistributed and/or modified under
* the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
* (at your option) any later version. The full license is in LICENSE file
* included with this distribution, and on the openscenegraph.org website.
*
* 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
* OpenSceneGraph Public License for more details.
*/
#include <osgUI/Style>
#include <osg/Geode>
#include <osg/Depth>
#include <osg/TexGen>
#include <osg/AlphaFunc>
#include <osgText/Text>
#include <osgDB/ReadFile>
using namespace osgUI;
osg::ref_ptr<Style>& Style::instance()
{
static osg::ref_ptr<Style> s_style = new Style;
return s_style;
}
OSG_INIT_SINGLETON_PROXY(StyleSingletonProxy, Style::instance())
Style::Style()
{
osg::ref_ptr<osg::Image> image = new osg::Image;
image->allocateImage(1,1,1,GL_RGBA, GL_FLOAT);
*(reinterpret_cast<osg::Vec4f*>(image->data(0,0,0))) = osg::Vec4f(1.0f, 1.0f, 1.0f, 1.0f);
_clipTexture = new osg::Texture2D;
_clipTexture->setImage(image.get());
_clipTexture->setBorderColor(osg::Vec4f(1.0f,1.0f,1.0f,0.0f));
_clipTexture->setWrap(osg::Texture::WRAP_S, osg::Texture::CLAMP_TO_BORDER);
_clipTexture->setWrap(osg::Texture::WRAP_T, osg::Texture::CLAMP_TO_BORDER);
_clipTexture->setFilter(osg::Texture::MIN_FILTER, osg::Texture::NEAREST);
_clipTexture->setFilter(osg::Texture::MAG_FILTER, osg::Texture::NEAREST);
//image = osgDB::readImageFile("Images/lz.rgb");
//_clipTexture->setImage(image.get());
_disabledDepthWrite = new osg::Depth(osg::Depth::LESS,0.0, 1.0,false);
_enabledDepthWrite = new osg::Depth(osg::Depth::LESS,0.0, 1.0,true);
_disableColorWriteMask = new osg::ColorMask(false, false, false, false);
}
Style::Style(const Style& style, const osg::CopyOp& copyop):
osg::Object(style, copyop),
_clipTexture(style._clipTexture)
{
}
osg::Node* Style::createPanel(const osg::BoundingBox& extents, const osg::Vec4& colour)
{
OSG_NOTICE<<"Creating Panel"<<std::endl;
osg::ref_ptr<osg::Geometry> geometry = new osg::Geometry;
geometry->setName("Panel");
osg::ref_ptr<osg::Vec3Array> vertices = new osg::Vec3Array;
geometry->setVertexArray(vertices.get());
vertices->push_back( osg::Vec3(extents.xMin(), extents.yMin(), extents.zMin()) );
vertices->push_back( osg::Vec3(extents.xMin(), extents.yMax(), extents.zMin()) );
vertices->push_back( osg::Vec3(extents.xMax(), extents.yMin(), extents.zMin()) );
vertices->push_back( osg::Vec3(extents.xMax(), extents.yMax(), extents.zMin()) );
osg::ref_ptr<osg::Vec4Array> colours = new osg::Vec4Array;
geometry->setColorArray(colours, osg::Array::BIND_OVERALL);
colours->push_back( colour );
geometry->addPrimitiveSet( new osg::DrawArrays(GL_TRIANGLE_STRIP, 0, 4) );
return geometry.release();
}
osg::Node* Style::createDepthSetPanel(const osg::BoundingBox& extents)
{
osg::ref_ptr<osg::Geometry> geometry = new osg::Geometry;
geometry->setName("DepthSetPanel");
osg::ref_ptr<osg::Vec3Array> vertices = new osg::Vec3Array;
geometry->setVertexArray(vertices.get());
vertices->push_back( osg::Vec3(extents.xMin(), extents.yMin(), extents.zMin()) );
vertices->push_back( osg::Vec3(extents.xMin(), extents.yMax(), extents.zMin()) );
vertices->push_back( osg::Vec3(extents.xMax(), extents.yMin(), extents.zMin()) );
vertices->push_back( osg::Vec3(extents.xMax(), extents.yMax(), extents.zMin()) );
geometry->addPrimitiveSet( new osg::DrawArrays(GL_TRIANGLE_STRIP, 0, 4) );
osg::ref_ptr<osg::StateSet> stateset = geometry->getOrCreateStateSet();
stateset->setAttributeAndModes( _enabledDepthWrite.get(), osg::StateAttribute::ON);
stateset->setAttributeAndModes( _disableColorWriteMask.get() );
return geometry.release();
}
osg::Node* Style::createFrame(const osg::BoundingBox& extents, const FrameSettings* frameSettings, const osg::Vec4& color)
{
osg::ref_ptr<osg::Geometry> geometry = new osg::Geometry;
geometry->setName("Frame");
float topScale = 1.0f;
float bottomScale = 1.0f;
float leftScale = 1.0f;
float rightScale = 1.0f;
if (frameSettings)
{
switch(frameSettings->getShadow())
{
case(FrameSettings::PLAIN):
// default settings are appropriate for PLAIN
break;
case(FrameSettings::SUNKEN):
topScale = 0.6f;
bottomScale = 1.2f;
leftScale = 0.8f;
rightScale = 0.8f;
break;
case(FrameSettings::RAISED):
topScale = 1.2f;
bottomScale = 0.6f;
leftScale = 0.8f;
rightScale = 0.8f;
break;
}
}
osg::Vec4 topColor(osg::minimum(color.r()*topScale,1.0f), osg::minimum(color.g()*topScale,1.0f), osg::minimum(color.b()*topScale,1.0f), color.a());
osg::Vec4 bottomColor(osg::minimum(color.r()*bottomScale,1.0f), osg::minimum(color.g()*bottomScale,1.0f), osg::minimum(color.b()*bottomScale,1.0f), color.a());
osg::Vec4 leftColor(osg::minimum(color.r()*leftScale,1.0f), osg::minimum(color.g()*leftScale,1.0f), osg::minimum(color.b()*leftScale,1.0f), color.a());
osg::Vec4 rightColor(osg::minimum(color.r()*rightScale,1.0f), osg::minimum(color.g()*rightScale,1.0f), osg::minimum(color.b()*rightScale,1.0f), color.a());
float lineWidth = frameSettings ? frameSettings->getLineWidth() : 1.0f;
osg::Vec3 outerBottomLeft(extents.xMin(), extents.yMin(), extents.zMin());
osg::Vec3 outerBottomRight(extents.xMax(), extents.yMin(), extents.zMin());
osg::Vec3 outerTopLeft(extents.xMin(), extents.yMax(), extents.zMin());
osg::Vec3 outerTopRight(extents.xMax(), extents.yMax(), extents.zMin());
osg::Vec3 innerBottomLeft(extents.xMin()+lineWidth, extents.yMin()+lineWidth, extents.zMin());
osg::Vec3 innerBottomRight(extents.xMax()-lineWidth, extents.yMin()+lineWidth, extents.zMin());
osg::Vec3 innerTopLeft(extents.xMin()+lineWidth, extents.yMax()-lineWidth, extents.zMin());
osg::Vec3 innerTopRight(extents.xMax()-lineWidth, extents.yMax()-lineWidth, extents.zMin());
osg::ref_ptr<osg::Vec3Array> vertices = new osg::Vec3Array;
geometry->setVertexArray(vertices.get());
vertices->push_back( outerBottomLeft ); // 0
vertices->push_back( outerBottomRight ); // 1
vertices->push_back( outerTopLeft ); // 2
vertices->push_back( outerTopRight ); // 3
vertices->push_back( innerBottomLeft ); // 4
vertices->push_back( innerBottomRight ); // 5
vertices->push_back( innerTopLeft ); // 6
vertices->push_back( innerTopRight ); // 7
osg::ref_ptr<osg::Vec4Array> colours = new osg::Vec4Array;
geometry->setColorArray(colours.get(), osg::Array::BIND_PER_PRIMITIVE_SET);
// bottom
{
colours->push_back(bottomColor);
osg::ref_ptr<osg::DrawElementsUShort> primitives = new osg::DrawElementsUShort(GL_TRIANGLE_STRIP);
geometry->addPrimitiveSet(primitives.get());
primitives->push_back(4);
primitives->push_back(0);
primitives->push_back(5);
primitives->push_back(1);
}
// top
{
colours->push_back(topColor);
osg::ref_ptr<osg::DrawElementsUShort> primitives = new osg::DrawElementsUShort(GL_TRIANGLE_STRIP);
geometry->addPrimitiveSet(primitives.get());
primitives->push_back(2);
primitives->push_back(6);
primitives->push_back(3);
primitives->push_back(7);
}
// left
{
colours->push_back(leftColor);
osg::ref_ptr<osg::DrawElementsUShort> primitives = new osg::DrawElementsUShort(GL_TRIANGLE_STRIP);
geometry->addPrimitiveSet(primitives.get());
primitives->push_back(2);
primitives->push_back(0);
primitives->push_back(6);
primitives->push_back(4);
}
// right
{
colours->push_back(rightColor);
osg::ref_ptr<osg::DrawElementsUShort> primitives = new osg::DrawElementsUShort(GL_TRIANGLE_STRIP);
geometry->addPrimitiveSet(primitives.get());
primitives->push_back(7);
primitives->push_back(5);
primitives->push_back(3);
primitives->push_back(1);
}
return geometry.release();
}
osg::Node* Style::createText(const osg::BoundingBox& extents, const AlignmentSettings* as, const TextSettings* ts, const std::string& text)
{
osg::ref_ptr<osgText::Text> textDrawable = new osgText::Text;
textDrawable->setName("Text");
textDrawable->setText(text);
textDrawable->setEnableDepthWrites(false);
if (ts)
{
textDrawable->setFont(ts->getFont());
textDrawable->setCharacterSize(ts->getCharacterSize());
}
AlignmentSettings::Alignment alignment = as ? as->getAlignment() : AlignmentSettings::CENTER_CENTER;
textDrawable->setAlignment(static_cast<osgText::TextBase::AlignmentType>(alignment));
switch(alignment)
{
case(AlignmentSettings::LEFT_TOP):
textDrawable->setPosition( osg::Vec3(extents.xMin(), extents.yMax(), extents.zMin()) );
break;
case(AlignmentSettings::LEFT_CENTER):
textDrawable->setPosition( osg::Vec3(extents.xMin(), (extents.yMin()+extents.yMax())*0.5f, extents.zMin()) );
break;
case(AlignmentSettings::LEFT_BOTTOM):
textDrawable->setPosition( osg::Vec3(extents.xMin(), extents.yMin(), extents.zMin()) );
break;
case(AlignmentSettings::CENTER_TOP):
textDrawable->setPosition( osg::Vec3((extents.xMin()+extents.xMin())*0.5f, extents.yMax(), extents.zMin()) );
break;
case(AlignmentSettings::CENTER_CENTER):
textDrawable->setPosition( osg::Vec3((extents.xMin()+extents.xMin())*0.5f, (extents.yMin()+extents.yMax())*0.5f, extents.zMin()) );
break;
case(AlignmentSettings::CENTER_BOTTOM):
textDrawable->setPosition( osg::Vec3((extents.xMin()+extents.xMin())*0.5f, extents.yMin(), extents.zMin()) );
break;
case(AlignmentSettings::RIGHT_TOP):
textDrawable->setPosition( osg::Vec3(extents.xMax(), extents.yMax(), extents.zMin()) );
break;
case(AlignmentSettings::RIGHT_CENTER):
textDrawable->setPosition( osg::Vec3(extents.xMax(), (extents.yMin()+extents.yMax())*0.5f, extents.zMin()) );
break;
case(AlignmentSettings::RIGHT_BOTTOM):
textDrawable->setPosition( osg::Vec3(extents.xMax(), extents.yMin(), extents.zMin()) );
break;
case(AlignmentSettings::LEFT_BASE_LINE):
OSG_NOTICE<<"Text : LEFT_BASE_LINE"<<std::endl;
textDrawable->setPosition( osg::Vec3(extents.xMin(), (extents.yMin()+extents.yMax())*0.5f-textDrawable->getCharacterHeight()*0.5f, extents.zMin()) );
break;
case(AlignmentSettings::CENTER_BASE_LINE):
textDrawable->setPosition( osg::Vec3((extents.xMin()+extents.xMin())*0.5f, (extents.yMin()+extents.yMax())*0.5f-textDrawable->getCharacterHeight()*0.5, extents.zMin()) );
break;
case(AlignmentSettings::RIGHT_BASE_LINE):
textDrawable->setPosition( osg::Vec3(extents.xMax(), (extents.yMin()+extents.yMax())*0.5f-textDrawable->getCharacterHeight()*0.5, extents.zMin()) );
break;
case(AlignmentSettings::LEFT_BOTTOM_BASE_LINE):
case(AlignmentSettings::CENTER_BOTTOM_BASE_LINE):
case(AlignmentSettings::RIGHT_BOTTOM_BASE_LINE):
default:
textDrawable->setPosition( osg::Vec3(extents.xMin(), extents.yMin(), extents.zMin()) );
break;
}
return textDrawable.release();
}
osg::Node* Style::createIcon(const osg::BoundingBox& extents, const std::string& filename)
{
return 0;
}
void Style::setupDialogStateSet(osg::StateSet* stateset)
{
stateset->setRenderBinDetails(5, "TraversalOrderBin", osg::StateSet::OVERRIDE_RENDERBIN_DETAILS);
stateset->setMode( GL_LIGHTING, osg::StateAttribute::OFF );
stateset->setAttributeAndModes( _disabledDepthWrite.get(), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE );
}
void Style::setupClipStateSet(const osg::BoundingBox& extents, osg::StateSet* stateset)
{
unsigned int clipTextureUnit = 1;
stateset->setAttributeAndModes( new osg::AlphaFunc(osg::AlphaFunc::GREATER, 0.0f), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE);
stateset->setTextureAttributeAndModes( clipTextureUnit, _clipTexture.get(), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE);
osg::Matrixd matrix = osg::Matrixd::translate(osg::Vec3(-extents.xMin(), -extents.yMin(), -extents.zMin()))*
osg::Matrixd::scale(osg::Vec3(1.0f/(extents.xMax()-extents.xMin()), 1.0f/(extents.yMax()-extents.yMin()), 1.0f));
osg::ref_ptr<osg::TexGen> texgen = new osg::TexGen;
texgen->setPlanesFromMatrix(matrix);
texgen->setMode(osg::TexGen::OBJECT_LINEAR);
stateset->setTextureAttributeAndModes( clipTextureUnit, texgen.get(), osg::StateAttribute::ON);
}
<|endoftext|> |
<commit_before>#include <algorithm>
#include <stdexcept>
#include <chrono>
#include <vector>
#include <memory>
#include <cmath>
#include <thread>
#include <signal.h>
#include <sched.h>
#include <sys/mman.h>
#include <eeros/core/Executor.hpp>
#include <eeros/task/Async.hpp>
#include <eeros/task/Lambda.hpp>
#include <eeros/task/HarmonicTaskList.hpp>
#include <eeros/control/TimeDomain.hpp>
#include <eeros/safety/SafetySystem.hpp>
#include <ros/callback_queue_interface.h>
#include <ros/callback_queue.h>
volatile bool running = true;
using namespace eeros;
namespace {
using Logger = logger::Logger;
struct TaskThread {
TaskThread(double period, task::Periodic &task, task::HarmonicTaskList tasks) :
taskList(tasks), async(taskList, task.getRealtime(), task.getNice())
{
async.counter.setPeriod(period);
async.counter.monitors = task.monitors;
}
task::HarmonicTaskList taskList;
task::Async async;
};
template < typename F >
void traverse(std::vector<task::Periodic> &tasks, F func) {
for (auto &t: tasks) {
func(&t);
traverse(t.before, func);
traverse(t.after, func);
}
}
void createThread(Logger &log, task::Periodic &task, task::Periodic &baseTask, std::vector<std::shared_ptr<TaskThread>> &threads, std::vector<task::Harmonic> &output);
void createThreads(Logger &log, std::vector<task::Periodic> &tasks, task::Periodic &baseTask, std::vector<std::shared_ptr<TaskThread>> &threads, task::HarmonicTaskList &output) {
for (task::Periodic &t: tasks) {
createThread(log, t, baseTask, threads, output.tasks);
}
}
void createThread(Logger &log, task::Periodic &task, task::Periodic &baseTask, std::vector<std::shared_ptr<TaskThread>> &threads, std::vector<task::Harmonic> &output) {
int k = static_cast<int>(task.getPeriod() / baseTask.getPeriod());
double actualPeriod = k * baseTask.getPeriod();
double deviation = std::abs(task.getPeriod() - actualPeriod) / task.getPeriod();
task::HarmonicTaskList taskList;
if (task.before.size() > 0) {
createThreads(log, task.before, task, threads, taskList);
}
taskList.add(task.getTask());
if (task.after.size() > 0) {
createThreads(log, task.after, task, threads, taskList);
}
if (task.getRealtime())
log.trace() << "creating harmonic realtime task '" << task.getName()
<< "' with period " << actualPeriod << " sec (k = "
<< k << ") and priority " << (Executor::basePriority - task.getNice())
<< " based on '" << baseTask.getName() << "'";
else
log.trace() << "creating harmonic task '" << task.getName() << "' with period "
<< actualPeriod << " sec (k = " << k << ")"
<< " based on '" << baseTask.getName() << "'";
if (deviation > 0.01) throw std::runtime_error("period deviation too high");
if (task.getRealtime() && task.getNice() <= 0)
throw std::runtime_error("priority not set");
if (taskList.tasks.size() == 0)
throw std::runtime_error("no task to execute");
threads.push_back(std::make_shared<TaskThread>(actualPeriod, task, taskList));
output.emplace_back(threads.back()->async, k);
}
}
Executor::Executor() :
log('E'), period(0), mainTask(nullptr), syncWithEtherCatStackIsSet(false), syncWithRosTimeIsSet(false), syncWithRosTopicIsSet(false) { }
Executor::~Executor() {
}
Executor& Executor::instance() {
static Executor executor;
return executor;
}
#ifdef ECMASTERLIB_FOUND
void Executor::syncWithEtherCATSTack(ethercat::EtherCATMain* etherCATStack) {
syncWithEtherCatStackIsSet = true;
this->etherCATStack = etherCATStack;
cv = etherCATStack->getConditionalVariable();
m = etherCATStack->getMutex();
}
#endif
void Executor::setMainTask(task::Periodic &mainTask) {
if (this->mainTask != nullptr)
throw std::runtime_error("you can only define one main task per executor");
period = mainTask.getPeriod();
counter.setPeriod(period);
this->mainTask = &mainTask;
}
void Executor::setMainTask(safety::SafetySystem &ss) {
task::Periodic *task = new task::Periodic("safety system", ss.getPeriod(), ss, true);
setMainTask(*task);
}
void Executor::add(task::Periodic &task) {
tasks.push_back(task);
}
void Executor::add(control::TimeDomain &timedomain) {
task::Periodic task(timedomain.getName().c_str(), timedomain.getPeriod(), timedomain, timedomain.getRealtime());
tasks.push_back(task);
}
void Executor::prefault_stack() {
unsigned char dummy[8*1024] = {};
}
bool Executor::lock_memory() {
return (mlockall(MCL_CURRENT | MCL_FUTURE) != -1);
}
bool Executor::set_priority(int nice) {
struct sched_param schedulingParam;
schedulingParam.sched_priority = (Executor::basePriority - nice);
return (sched_setscheduler(0, SCHED_FIFO, &schedulingParam) != -1);
}
void Executor::stop() {
running = false;
auto &instance = Executor::instance();
#ifdef ECMASTERLIB_FOUND
if(instance.etherCATStack) instance.cv->notify_one();
#endif
}
void Executor::syncWithRosTime() {
syncWithRosTimeIsSet = true;
}
void Executor::syncWithRosTopic(ros::CallbackQueue* syncRosCallbackQueue)
{
std::cout << "sync executor with gazebo" << std::endl;
syncWithRosTopicIsSet = true;
this->syncRosCallbackQueue = syncRosCallbackQueue;
}
void Executor::assignPriorities() {
std::vector<task::Periodic*> priorityAssignments;
// add task to list of priority assignments
traverse(tasks, [&priorityAssignments] (task::Periodic *task) {
priorityAssignments.push_back(task);
});
// sort list of priority assignments
std::sort(priorityAssignments.begin(), priorityAssignments.end(), [] (task::Periodic *a, task::Periodic *b) -> bool {
if (a->getRealtime() == b->getRealtime())
return (a->getPeriod() < b->getPeriod());
else
return a->getRealtime();
});
// assign priorities
int nice = 1;
for (auto t: priorityAssignments) {
if (t->getRealtime()) {
t->setNice(nice++);
}
}
}
void Executor::run() {
log.trace() << "starting executor with base period " << period << " sec and priority " << basePriority;
if (period == 0.0)
throw std::runtime_error("period of executor not set");
log.trace() << "assigning priorities";
assignPriorities();
Runnable *mainTask = nullptr;
if (this->mainTask != nullptr) {
mainTask = &this->mainTask->getTask();
log.trace() << "setting '" << this->mainTask->getName() << "' as main task";
}
std::vector<std::shared_ptr<TaskThread>> threads; // smart pointer used because async objects must not be copied
task::HarmonicTaskList taskList;
task::Periodic executorTask("executor", period, this, true);
counter.monitors = this->mainTask->monitors;
createThreads(log, tasks, executorTask, threads, taskList);
using seconds = std::chrono::duration<double, std::chrono::seconds::period>;
// TODO: implement this with ready-flag (wait for all threads to be ready instead of blind sleep)
std::this_thread::sleep_for(seconds(1)); // wait 1 sec to allow threads to be created
if (!set_priority(0))
log.error() << "could not set realtime priority";
prefault_stack();
if (!lock_memory())
log.error() << "could not lock memory in RAM";
bool useDefaultExecutor = true;
#ifdef ECMASTERLIB_FOUND
if (etherCATStack) {
log.trace() << "starting execution synced to etcherCAT stack";
if (syncWithRosTimeIsSet) log.error() << "Can't use both etherCAT and RosTime to sync executor";
if (syncWithRosTopicIsSet) log.error() << "Can't use both etherCAT and RosTopic to sync executor";
useDefaultExecutor = false;
while (running) {
std::unique_lock<std::mutex> lk(*m);
cv->wait(lk);
lk.unlock();
counter.tick();
taskList.run();
if (mainTask != nullptr)
mainTask->run();
counter.tock();
}
}
#endif
#ifdef ROS_FOUND
if (syncWithRosTimeIsSet) {
log.trace() << "starting execution synced to rosTime";
if (syncWithEtherCatStackIsSet) log.error() << "Can't use both RosTime and etherCAT to sync executor";
if (syncWithRosTopicIsSet) log.error() << "Can't use both RosTime and RosTopic to sync executor";
useDefaultExecutor = false;
long periodNsec = static_cast<long>(period * 1.0e9);
long next_cycle = ros::Time::now().toNSec()+periodNsec;
// auto next_cycle = std::chrono::steady_clock::now() + seconds(period);
while (running) {
while (ros::Time::now().toNSec() < next_cycle && running) usleep(10);
counter.tick();
taskList.run();
if (mainTask != nullptr)
mainTask->run();
counter.tock();
next_cycle += periodNsec;
}
}
else if (syncWithRosTopicIsSet) {
log.trace() << "starting execution synced to gazebo";
if (syncWithRosTimeIsSet) log.error() << "Can't use both RosTopic and RosTime to sync executor";
if (syncWithEtherCatStackIsSet) log.error() << "Can't use both RosTopic and etherCAT to sync executor";
useDefaultExecutor = false;
auto timeOld = ros::Time::now();
auto timeNew = ros::Time::now();
static bool first = true;
while (running) {
if (first) {
while (timeOld == timeNew && running) { // waits for new rosTime beeing published
usleep(10);
timeNew = ros::Time::now();
}
first = false;
timeOld = timeNew;
}
while (syncRosCallbackQueue->isEmpty() && running) usleep(10); //waits for new message;
while (timeOld == timeNew && running) { // waits for new rosTime beeing published
usleep(10);
timeNew = ros::Time::now();
}
timeOld = timeNew;
syncRosCallbackQueue->callAvailable();
// ros::getGlobalCallbackQueue()->callAvailable();
counter.tick();
taskList.run();
if (mainTask != nullptr)
mainTask->run();
counter.tock();
}
}
#endif
if (useDefaultExecutor) {
log.trace() << "starting periodic execution";
auto next_cycle = std::chrono::steady_clock::now() + seconds(period);
while (running) {
std::this_thread::sleep_until(next_cycle);
counter.tick();
taskList.run();
if (mainTask != nullptr)
mainTask->run();
counter.tock();
next_cycle += seconds(period);
}
}
log.trace() << "stopping all threads";
for (auto &t: threads)
t->async.stop();
log.trace() << "joining all threads";
for (auto &t: threads)
t->async.join();
log.trace() << "exiting executor";
}
<commit_msg>hotfix. #ifdef ROS_FOUND 2 times<commit_after>#include <algorithm>
#include <stdexcept>
#include <chrono>
#include <vector>
#include <memory>
#include <cmath>
#include <thread>
#include <signal.h>
#include <sched.h>
#include <sys/mman.h>
#include <eeros/core/Executor.hpp>
#include <eeros/task/Async.hpp>
#include <eeros/task/Lambda.hpp>
#include <eeros/task/HarmonicTaskList.hpp>
#include <eeros/control/TimeDomain.hpp>
#include <eeros/safety/SafetySystem.hpp>
#ifdef ROS_FOUND
#include <ros/callback_queue_interface.h>
#include <ros/callback_queue.h>
#endif
volatile bool running = true;
using namespace eeros;
namespace {
using Logger = logger::Logger;
struct TaskThread {
TaskThread(double period, task::Periodic &task, task::HarmonicTaskList tasks) :
taskList(tasks), async(taskList, task.getRealtime(), task.getNice())
{
async.counter.setPeriod(period);
async.counter.monitors = task.monitors;
}
task::HarmonicTaskList taskList;
task::Async async;
};
template < typename F >
void traverse(std::vector<task::Periodic> &tasks, F func) {
for (auto &t: tasks) {
func(&t);
traverse(t.before, func);
traverse(t.after, func);
}
}
void createThread(Logger &log, task::Periodic &task, task::Periodic &baseTask, std::vector<std::shared_ptr<TaskThread>> &threads, std::vector<task::Harmonic> &output);
void createThreads(Logger &log, std::vector<task::Periodic> &tasks, task::Periodic &baseTask, std::vector<std::shared_ptr<TaskThread>> &threads, task::HarmonicTaskList &output) {
for (task::Periodic &t: tasks) {
createThread(log, t, baseTask, threads, output.tasks);
}
}
void createThread(Logger &log, task::Periodic &task, task::Periodic &baseTask, std::vector<std::shared_ptr<TaskThread>> &threads, std::vector<task::Harmonic> &output) {
int k = static_cast<int>(task.getPeriod() / baseTask.getPeriod());
double actualPeriod = k * baseTask.getPeriod();
double deviation = std::abs(task.getPeriod() - actualPeriod) / task.getPeriod();
task::HarmonicTaskList taskList;
if (task.before.size() > 0) {
createThreads(log, task.before, task, threads, taskList);
}
taskList.add(task.getTask());
if (task.after.size() > 0) {
createThreads(log, task.after, task, threads, taskList);
}
if (task.getRealtime())
log.trace() << "creating harmonic realtime task '" << task.getName()
<< "' with period " << actualPeriod << " sec (k = "
<< k << ") and priority " << (Executor::basePriority - task.getNice())
<< " based on '" << baseTask.getName() << "'";
else
log.trace() << "creating harmonic task '" << task.getName() << "' with period "
<< actualPeriod << " sec (k = " << k << ")"
<< " based on '" << baseTask.getName() << "'";
if (deviation > 0.01) throw std::runtime_error("period deviation too high");
if (task.getRealtime() && task.getNice() <= 0)
throw std::runtime_error("priority not set");
if (taskList.tasks.size() == 0)
throw std::runtime_error("no task to execute");
threads.push_back(std::make_shared<TaskThread>(actualPeriod, task, taskList));
output.emplace_back(threads.back()->async, k);
}
}
Executor::Executor() :
log('E'), period(0), mainTask(nullptr), syncWithEtherCatStackIsSet(false), syncWithRosTimeIsSet(false), syncWithRosTopicIsSet(false) { }
Executor::~Executor() {
}
Executor& Executor::instance() {
static Executor executor;
return executor;
}
#ifdef ECMASTERLIB_FOUND
void Executor::syncWithEtherCATSTack(ethercat::EtherCATMain* etherCATStack) {
syncWithEtherCatStackIsSet = true;
this->etherCATStack = etherCATStack;
cv = etherCATStack->getConditionalVariable();
m = etherCATStack->getMutex();
}
#endif
void Executor::setMainTask(task::Periodic &mainTask) {
if (this->mainTask != nullptr)
throw std::runtime_error("you can only define one main task per executor");
period = mainTask.getPeriod();
counter.setPeriod(period);
this->mainTask = &mainTask;
}
void Executor::setMainTask(safety::SafetySystem &ss) {
task::Periodic *task = new task::Periodic("safety system", ss.getPeriod(), ss, true);
setMainTask(*task);
}
void Executor::add(task::Periodic &task) {
tasks.push_back(task);
}
void Executor::add(control::TimeDomain &timedomain) {
task::Periodic task(timedomain.getName().c_str(), timedomain.getPeriod(), timedomain, timedomain.getRealtime());
tasks.push_back(task);
}
void Executor::prefault_stack() {
unsigned char dummy[8*1024] = {};
}
bool Executor::lock_memory() {
return (mlockall(MCL_CURRENT | MCL_FUTURE) != -1);
}
bool Executor::set_priority(int nice) {
struct sched_param schedulingParam;
schedulingParam.sched_priority = (Executor::basePriority - nice);
return (sched_setscheduler(0, SCHED_FIFO, &schedulingParam) != -1);
}
void Executor::stop() {
running = false;
auto &instance = Executor::instance();
#ifdef ECMASTERLIB_FOUND
if(instance.etherCATStack) instance.cv->notify_one();
#endif
}
#ifdef ROS_FOUND
void Executor::syncWithRosTime() {
syncWithRosTimeIsSet = true;
}
void Executor::syncWithRosTopic(ros::CallbackQueue* syncRosCallbackQueue)
{
std::cout << "sync executor with gazebo" << std::endl;
syncWithRosTopicIsSet = true;
this->syncRosCallbackQueue = syncRosCallbackQueue;
}
#endif
void Executor::assignPriorities() {
std::vector<task::Periodic*> priorityAssignments;
// add task to list of priority assignments
traverse(tasks, [&priorityAssignments] (task::Periodic *task) {
priorityAssignments.push_back(task);
});
// sort list of priority assignments
std::sort(priorityAssignments.begin(), priorityAssignments.end(), [] (task::Periodic *a, task::Periodic *b) -> bool {
if (a->getRealtime() == b->getRealtime())
return (a->getPeriod() < b->getPeriod());
else
return a->getRealtime();
});
// assign priorities
int nice = 1;
for (auto t: priorityAssignments) {
if (t->getRealtime()) {
t->setNice(nice++);
}
}
}
void Executor::run() {
log.trace() << "starting executor with base period " << period << " sec and priority " << basePriority;
if (period == 0.0)
throw std::runtime_error("period of executor not set");
log.trace() << "assigning priorities";
assignPriorities();
Runnable *mainTask = nullptr;
if (this->mainTask != nullptr) {
mainTask = &this->mainTask->getTask();
log.trace() << "setting '" << this->mainTask->getName() << "' as main task";
}
std::vector<std::shared_ptr<TaskThread>> threads; // smart pointer used because async objects must not be copied
task::HarmonicTaskList taskList;
task::Periodic executorTask("executor", period, this, true);
counter.monitors = this->mainTask->monitors;
createThreads(log, tasks, executorTask, threads, taskList);
using seconds = std::chrono::duration<double, std::chrono::seconds::period>;
// TODO: implement this with ready-flag (wait for all threads to be ready instead of blind sleep)
std::this_thread::sleep_for(seconds(1)); // wait 1 sec to allow threads to be created
if (!set_priority(0))
log.error() << "could not set realtime priority";
prefault_stack();
if (!lock_memory())
log.error() << "could not lock memory in RAM";
bool useDefaultExecutor = true;
#ifdef ECMASTERLIB_FOUND
if (etherCATStack) {
log.trace() << "starting execution synced to etcherCAT stack";
if (syncWithRosTimeIsSet) log.error() << "Can't use both etherCAT and RosTime to sync executor";
if (syncWithRosTopicIsSet) log.error() << "Can't use both etherCAT and RosTopic to sync executor";
useDefaultExecutor = false;
while (running) {
std::unique_lock<std::mutex> lk(*m);
cv->wait(lk);
lk.unlock();
counter.tick();
taskList.run();
if (mainTask != nullptr)
mainTask->run();
counter.tock();
}
}
#endif
#ifdef ROS_FOUND
if (syncWithRosTimeIsSet) {
log.trace() << "starting execution synced to rosTime";
if (syncWithEtherCatStackIsSet) log.error() << "Can't use both RosTime and etherCAT to sync executor";
if (syncWithRosTopicIsSet) log.error() << "Can't use both RosTime and RosTopic to sync executor";
useDefaultExecutor = false;
long periodNsec = static_cast<long>(period * 1.0e9);
long next_cycle = ros::Time::now().toNSec()+periodNsec;
// auto next_cycle = std::chrono::steady_clock::now() + seconds(period);
while (running) {
while (ros::Time::now().toNSec() < next_cycle && running) usleep(10);
counter.tick();
taskList.run();
if (mainTask != nullptr)
mainTask->run();
counter.tock();
next_cycle += periodNsec;
}
}
else if (syncWithRosTopicIsSet) {
log.trace() << "starting execution synced to gazebo";
if (syncWithRosTimeIsSet) log.error() << "Can't use both RosTopic and RosTime to sync executor";
if (syncWithEtherCatStackIsSet) log.error() << "Can't use both RosTopic and etherCAT to sync executor";
useDefaultExecutor = false;
auto timeOld = ros::Time::now();
auto timeNew = ros::Time::now();
static bool first = true;
while (running) {
if (first) {
while (timeOld == timeNew && running) { // waits for new rosTime beeing published
usleep(10);
timeNew = ros::Time::now();
}
first = false;
timeOld = timeNew;
}
while (syncRosCallbackQueue->isEmpty() && running) usleep(10); //waits for new message;
while (timeOld == timeNew && running) { // waits for new rosTime beeing published
usleep(10);
timeNew = ros::Time::now();
}
timeOld = timeNew;
syncRosCallbackQueue->callAvailable();
// ros::getGlobalCallbackQueue()->callAvailable();
counter.tick();
taskList.run();
if (mainTask != nullptr)
mainTask->run();
counter.tock();
}
}
#endif
if (useDefaultExecutor) {
log.trace() << "starting periodic execution";
auto next_cycle = std::chrono::steady_clock::now() + seconds(period);
while (running) {
std::this_thread::sleep_until(next_cycle);
counter.tick();
taskList.run();
if (mainTask != nullptr)
mainTask->run();
counter.tock();
next_cycle += seconds(period);
}
}
log.trace() << "stopping all threads";
for (auto &t: threads)
t->async.stop();
log.trace() << "joining all threads";
for (auto &t: threads)
t->async.join();
log.trace() << "exiting executor";
}
<|endoftext|> |
<commit_before>#include "chunk.h"
#include "../utils/crc.h"
#include "bloom_filter.h"
#include <algorithm>
#include <cassert>
#include <cstring>
using namespace dariadb;
using namespace dariadb::utils;
using namespace dariadb::storage;
using namespace dariadb::compression::v2;
// std::unique_ptr<ChunkCache> ChunkCache::_instance = nullptr;
std::ostream &dariadb::storage::operator<<(std::ostream &stream, const CHUNK_KIND &b) {
switch (b) {
case CHUNK_KIND::Simple:
stream << "CHUNK_KIND::Simple";
break;
case CHUNK_KIND::Compressed:
stream << "CHUNK_KIND::Compressed";
break;
}
return stream;
}
Chunk::Chunk(ChunkHeader *hdr, uint8_t *buffer) {
should_free = false;
header = hdr;
_buffer_t = buffer;
}
Chunk::Chunk(ChunkHeader *hdr, uint8_t *buffer, size_t _size, Meas first_m) {
should_free = false;
hdr->is_init = true;
_buffer_t = buffer;
header = hdr;
header->size = _size;
header->is_readonly = false;
header->count = 0;
header->first = first_m;
header->last = first_m;
header->minTime = first_m.time;
header->maxTime = first_m.time;
header->minId = first_m.id;
header->maxId = first_m.id;
header->flag_bloom = dariadb::storage::bloom_empty<dariadb::Flag>();
header->id_bloom = dariadb::storage::bloom_empty<dariadb::Id>();
std::fill(_buffer_t, _buffer_t + header->size, 0);
}
Chunk::~Chunk() {
if (should_free) {
delete header;
delete[] _buffer_t;
}
this->bw = nullptr;
}
bool Chunk::check_id(const Id &id) {
if (!dariadb::storage::bloom_check(header->id_bloom, id)) {
return false;
}
return inInterval(header->minId, header->maxId, id);
}
bool Chunk::check_flag(const Flag &f) {
if (f != 0) {
if (!dariadb::storage::bloom_check(header->flag_bloom, f)) {
return false;
}
}
return true;
}
bool Chunk::check_checksum() {
auto exists = get_checksum();
auto calculated = calc_checksum();
return exists == calculated;
}
//TODO rm std::make_shared<ByteBuffer>. use stack veriable.
ZippedChunk::ZippedChunk(ChunkHeader *index, uint8_t *buffer, size_t _size, Meas first_m)
: Chunk(index, buffer, _size, first_m),
c_writer(std::make_shared<ByteBuffer>(Range{ _buffer_t, _buffer_t + index->size }))
{
header->kind = CHUNK_KIND::Compressed;
bw = c_writer.get_bb();
bw->reset_pos();
header->bw_pos = uint32_t(bw->pos());
c_writer.append(header->first);
header->id_bloom = dariadb::storage::bloom_add(header->id_bloom, first_m.id);
header->flag_bloom = dariadb::storage::bloom_add(header->flag_bloom, first_m.flag);
}
ZippedChunk::ZippedChunk(ChunkHeader *index, uint8_t *buffer)
: Chunk(index, buffer),
c_writer(std::make_shared<ByteBuffer>(Range{ _buffer_t, _buffer_t + index->size }))
{
assert(index->kind == CHUNK_KIND::Compressed);
assert(size_t(range.end - range.begin) == index->size);
bw = c_writer.get_bb();
bw->set_pos(header->bw_pos);
}
ZippedChunk::~ZippedChunk() {}
void ZippedChunk::close() {
header->is_readonly = true;
header->crc = this->calc_checksum();
assert(header->crc != 0);
}
uint32_t ZippedChunk::calc_checksum() {
return utils::crc32(this->_buffer_t, this->header->size);
}
uint32_t ZippedChunk::get_checksum() {
return header->crc;
}
bool ZippedChunk::append(const Meas &m) {
if (!header->is_init || header->is_readonly) {
throw MAKE_EXCEPTION("(!is_not_free || is_readonly)");
}
auto t_f = this->c_writer.append(m);
if (!t_f) {
this->close();
assert(c_writer.is_full());
return false;
} else {
header->bw_pos = uint32_t(bw->pos());
header->count++;
header->minTime = std::min(header->minTime, m.time);
header->maxTime = std::max(header->maxTime, m.time);
header->minId = std::min(header->minId, m.id);
header->maxId = std::max(header->maxId, m.id);
header->flag_bloom = dariadb::storage::bloom_add(header->flag_bloom, m.flag);
header->id_bloom = dariadb::storage::bloom_add(header->id_bloom, m.id);
header->last = m;
return true;
}
}
class ZippedChunkReader : public Chunk::IChunkReader {
public:
virtual Meas readNext() override {
assert(!is_end());
if (_is_first) {
_is_first = false;
return _chunk->header->first;
}
--count;
return _reader->read();
}
bool is_end() const override { return count == 0 && !_is_first; }
size_t count;
bool _is_first = true;
Chunk_Ptr _chunk;
std::shared_ptr<ByteBuffer> bw;
std::shared_ptr<CopmressedReader> _reader;
};
Chunk::ChunkReader_Ptr ZippedChunk::get_reader() {
auto raw_res = new ZippedChunkReader;
raw_res->count = this->header->count;
raw_res->_chunk = this->shared_from_this();
raw_res->_is_first = true;
raw_res->bw = std::make_shared<compression::v2::ByteBuffer>(this->bw->get_range());
raw_res->bw->reset_pos();
raw_res->_reader = std::make_shared<CopmressedReader>(raw_res->bw, this->header->first);
Chunk::ChunkReader_Ptr result{raw_res};
return result;
}
<commit_msg>mingw build.<commit_after>#include "chunk.h"
#include "../utils/crc.h"
#include "bloom_filter.h"
#include <algorithm>
#include <cassert>
#include <cstring>
using namespace dariadb;
using namespace dariadb::utils;
using namespace dariadb::storage;
using namespace dariadb::compression::v2;
// std::unique_ptr<ChunkCache> ChunkCache::_instance = nullptr;
std::ostream &dariadb::storage::operator<<(std::ostream &stream, const CHUNK_KIND &b) {
switch (b) {
case CHUNK_KIND::Simple:
stream << "CHUNK_KIND::Simple";
break;
case CHUNK_KIND::Compressed:
stream << "CHUNK_KIND::Compressed";
break;
}
return stream;
}
Chunk::Chunk(ChunkHeader *hdr, uint8_t *buffer) {
should_free = false;
header = hdr;
_buffer_t = buffer;
}
Chunk::Chunk(ChunkHeader *hdr, uint8_t *buffer, size_t _size, Meas first_m) {
should_free = false;
hdr->is_init = true;
_buffer_t = buffer;
header = hdr;
header->size = _size;
header->is_readonly = false;
header->count = 0;
header->first = first_m;
header->last = first_m;
header->minTime = first_m.time;
header->maxTime = first_m.time;
header->minId = first_m.id;
header->maxId = first_m.id;
header->flag_bloom = dariadb::storage::bloom_empty<dariadb::Flag>();
header->id_bloom = dariadb::storage::bloom_empty<dariadb::Id>();
std::fill(_buffer_t, _buffer_t + header->size, 0);
}
Chunk::~Chunk() {
if (should_free) {
delete header;
delete[] _buffer_t;
}
this->bw = nullptr;
}
bool Chunk::check_id(const Id &id) {
if (!dariadb::storage::bloom_check(header->id_bloom, id)) {
return false;
}
return inInterval(header->minId, header->maxId, id);
}
bool Chunk::check_flag(const Flag &f) {
if (f != 0) {
if (!dariadb::storage::bloom_check(header->flag_bloom, f)) {
return false;
}
}
return true;
}
bool Chunk::check_checksum() {
auto exists = get_checksum();
auto calculated = calc_checksum();
return exists == calculated;
}
//TODO rm std::make_shared<ByteBuffer>. use stack veriable.
ZippedChunk::ZippedChunk(ChunkHeader *index, uint8_t *buffer, size_t _size, Meas first_m)
: Chunk(index, buffer, _size, first_m),
c_writer(std::make_shared<ByteBuffer>(Range{ _buffer_t, _buffer_t + index->size }))
{
header->kind = CHUNK_KIND::Compressed;
bw = c_writer.get_bb();
bw->reset_pos();
header->bw_pos = uint32_t(bw->pos());
c_writer.append(header->first);
header->id_bloom = dariadb::storage::bloom_add(header->id_bloom, first_m.id);
header->flag_bloom = dariadb::storage::bloom_add(header->flag_bloom, first_m.flag);
}
ZippedChunk::ZippedChunk(ChunkHeader *index, uint8_t *buffer)
: Chunk(index, buffer),
c_writer(std::make_shared<ByteBuffer>(Range{ _buffer_t, _buffer_t + index->size }))
{
assert(index->kind == CHUNK_KIND::Compressed);
bw = c_writer.get_bb();
bw->set_pos(header->bw_pos);
}
ZippedChunk::~ZippedChunk() {}
void ZippedChunk::close() {
header->is_readonly = true;
header->crc = this->calc_checksum();
assert(header->crc != 0);
}
uint32_t ZippedChunk::calc_checksum() {
return utils::crc32(this->_buffer_t, this->header->size);
}
uint32_t ZippedChunk::get_checksum() {
return header->crc;
}
bool ZippedChunk::append(const Meas &m) {
if (!header->is_init || header->is_readonly) {
throw MAKE_EXCEPTION("(!is_not_free || is_readonly)");
}
auto t_f = this->c_writer.append(m);
if (!t_f) {
this->close();
assert(c_writer.is_full());
return false;
} else {
header->bw_pos = uint32_t(bw->pos());
header->count++;
header->minTime = std::min(header->minTime, m.time);
header->maxTime = std::max(header->maxTime, m.time);
header->minId = std::min(header->minId, m.id);
header->maxId = std::max(header->maxId, m.id);
header->flag_bloom = dariadb::storage::bloom_add(header->flag_bloom, m.flag);
header->id_bloom = dariadb::storage::bloom_add(header->id_bloom, m.id);
header->last = m;
return true;
}
}
class ZippedChunkReader : public Chunk::IChunkReader {
public:
virtual Meas readNext() override {
assert(!is_end());
if (_is_first) {
_is_first = false;
return _chunk->header->first;
}
--count;
return _reader->read();
}
bool is_end() const override { return count == 0 && !_is_first; }
size_t count;
bool _is_first = true;
Chunk_Ptr _chunk;
std::shared_ptr<ByteBuffer> bw;
std::shared_ptr<CopmressedReader> _reader;
};
Chunk::ChunkReader_Ptr ZippedChunk::get_reader() {
auto raw_res = new ZippedChunkReader;
raw_res->count = this->header->count;
raw_res->_chunk = this->shared_from_this();
raw_res->_is_first = true;
raw_res->bw = std::make_shared<compression::v2::ByteBuffer>(this->bw->get_range());
raw_res->bw->reset_pos();
raw_res->_reader = std::make_shared<CopmressedReader>(raw_res->bw, this->header->first);
Chunk::ChunkReader_Ptr result{raw_res};
return result;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: fmtextcontroldialogs.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: rt $ $Date: 2005-09-08 22:57:33 $
*
* 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_SOURCE_FORM_FMTEXTCONTROLDIALOGS_HXX
#include "fmtextcontroldialogs.hxx"
#endif
#ifndef _SVX_DIALMGR_HXX
#include "dialmgr.hxx"
#endif
#ifndef _SVX_DIALOGS_HRC
#include "dialogs.hrc"
#endif
#ifndef _SVX_CHARDLG_HXX
//#include "chardlg.hxx"
#endif
#ifndef _SVX_PARAGRPH_HXX
//#include "paragrph.hxx"
#endif
#ifndef _EEITEM_HXX
#include "eeitem.hxx"
#endif
#define ITEMID_TABSTOP EE_PARA_TABS
#ifndef _SVX_TABSTPGE_HXX
//#include "tabstpge.hxx"
#endif
#include "flagsdef.hxx"
#include <svtools/intitem.hxx>
#include <com/sun/star/uno/Sequence.hxx>
#ifndef _SVTOOLS_CJKOPTIONS_HXX
#include <svtools/cjkoptions.hxx>
#endif
//........................................................................
namespace svx
{
//........................................................................
//====================================================================
//= TextControlCharAttribDialog
//====================================================================
//--------------------------------------------------------------------
TextControlCharAttribDialog::TextControlCharAttribDialog( Window* pParent, const SfxItemSet& _rCoreSet, const SvxFontListItem& _rFontList )
:SfxTabDialog( pParent, SVX_RES( RID_SVXDLG_TEXTCONTROL_CHARATTR ), &_rCoreSet )
,m_aFontList( _rFontList )
{
FreeResource();
AddTabPage( RID_SVXPAGE_CHAR_NAME);
AddTabPage( RID_SVXPAGE_CHAR_EFFECTS);
AddTabPage( RID_SVXPAGE_CHAR_POSITION);
}
//--------------------------------------------------------------------
TextControlCharAttribDialog::~TextControlCharAttribDialog()
{
}
//--------------------------------------------------------------------
void TextControlCharAttribDialog::PageCreated( USHORT _nId, SfxTabPage& _rPage )
{
SfxAllItemSet aSet(*(GetInputSetImpl()->GetPool()));
switch( _nId )
{
case RID_SVXPAGE_CHAR_NAME:
aSet.Put (m_aFontList);
_rPage.PageCreated(aSet);
break;
case RID_SVXPAGE_CHAR_EFFECTS:
aSet.Put (SfxUInt16Item(SID_DISABLE_CTL,DISABLE_CASEMAP));
_rPage.PageCreated(aSet);
break;
case RID_SVXPAGE_CHAR_POSITION:
aSet.Put( SfxUInt32Item(SID_FLAG_TYPE, SVX_PREVIEW_CHARACTER) );
_rPage.PageCreated(aSet);
break;
}
}
//====================================================================
//= TextControlParaAttribDialog
//====================================================================
//--------------------------------------------------------------------
TextControlParaAttribDialog::TextControlParaAttribDialog( Window* _pParent, const SfxItemSet& _rCoreSet )
:SfxTabDialog( _pParent, SVX_RES( RID_SVXDLG_TEXTCONTROL_PARAATTR ), &_rCoreSet )
{
FreeResource();
AddTabPage( RID_SVXPAGE_STD_PARAGRAPH );
AddTabPage( RID_SVXPAGE_ALIGN_PARAGRAPH );
SvtCJKOptions aCJKOptions;
if( aCJKOptions.IsAsianTypographyEnabled() )
AddTabPage( RID_SVXPAGE_PARA_ASIAN );
else
RemoveTabPage( RID_SVXPAGE_PARA_ASIAN );
AddTabPage( RID_SVXPAGE_TABULATOR );
}
//--------------------------------------------------------------------
TextControlParaAttribDialog::~TextControlParaAttribDialog()
{
}
//--------------------------------------------------------------------
void TextControlParaAttribDialog::PageCreated( USHORT _nId, SfxTabPage& _rPage )
{
}
//........................................................................
} // namespace svx
//........................................................................
<commit_msg>INTEGRATION: CWS warnings01 (1.6.222); FILE MERGED 2006/02/15 13:28:11 fs 1.6.222.1: #i55991# warning-free code<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: fmtextcontroldialogs.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: hr $ $Date: 2006-06-19 15:58:11 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef SVX_SOURCE_FORM_FMTEXTCONTROLDIALOGS_HXX
#include "fmtextcontroldialogs.hxx"
#endif
#ifndef _SVX_DIALMGR_HXX
#include "dialmgr.hxx"
#endif
#ifndef _SVX_DIALOGS_HRC
#include "dialogs.hrc"
#endif
#ifndef _SVX_CHARDLG_HXX
//#include "chardlg.hxx"
#endif
#ifndef _SVX_PARAGRPH_HXX
//#include "paragrph.hxx"
#endif
#ifndef _EEITEM_HXX
#include "eeitem.hxx"
#endif
#define ITEMID_TABSTOP EE_PARA_TABS
#ifndef _SVX_TABSTPGE_HXX
//#include "tabstpge.hxx"
#endif
#include "flagsdef.hxx"
#include <svtools/intitem.hxx>
#include <com/sun/star/uno/Sequence.hxx>
#ifndef _SVTOOLS_CJKOPTIONS_HXX
#include <svtools/cjkoptions.hxx>
#endif
//........................................................................
namespace svx
{
//........................................................................
//====================================================================
//= TextControlCharAttribDialog
//====================================================================
//--------------------------------------------------------------------
TextControlCharAttribDialog::TextControlCharAttribDialog( Window* pParent, const SfxItemSet& _rCoreSet, const SvxFontListItem& _rFontList )
:SfxTabDialog( pParent, SVX_RES( RID_SVXDLG_TEXTCONTROL_CHARATTR ), &_rCoreSet )
,m_aFontList( _rFontList )
{
FreeResource();
AddTabPage( RID_SVXPAGE_CHAR_NAME);
AddTabPage( RID_SVXPAGE_CHAR_EFFECTS);
AddTabPage( RID_SVXPAGE_CHAR_POSITION);
}
//--------------------------------------------------------------------
TextControlCharAttribDialog::~TextControlCharAttribDialog()
{
}
//--------------------------------------------------------------------
void TextControlCharAttribDialog::PageCreated( USHORT _nId, SfxTabPage& _rPage )
{
SfxAllItemSet aSet(*(GetInputSetImpl()->GetPool()));
switch( _nId )
{
case RID_SVXPAGE_CHAR_NAME:
aSet.Put (m_aFontList);
_rPage.PageCreated(aSet);
break;
case RID_SVXPAGE_CHAR_EFFECTS:
aSet.Put (SfxUInt16Item(SID_DISABLE_CTL,DISABLE_CASEMAP));
_rPage.PageCreated(aSet);
break;
case RID_SVXPAGE_CHAR_POSITION:
aSet.Put( SfxUInt32Item(SID_FLAG_TYPE, SVX_PREVIEW_CHARACTER) );
_rPage.PageCreated(aSet);
break;
}
}
//====================================================================
//= TextControlParaAttribDialog
//====================================================================
//--------------------------------------------------------------------
TextControlParaAttribDialog::TextControlParaAttribDialog( Window* _pParent, const SfxItemSet& _rCoreSet )
:SfxTabDialog( _pParent, SVX_RES( RID_SVXDLG_TEXTCONTROL_PARAATTR ), &_rCoreSet )
{
FreeResource();
AddTabPage( RID_SVXPAGE_STD_PARAGRAPH );
AddTabPage( RID_SVXPAGE_ALIGN_PARAGRAPH );
SvtCJKOptions aCJKOptions;
if( aCJKOptions.IsAsianTypographyEnabled() )
AddTabPage( RID_SVXPAGE_PARA_ASIAN );
else
RemoveTabPage( RID_SVXPAGE_PARA_ASIAN );
AddTabPage( RID_SVXPAGE_TABULATOR );
}
//--------------------------------------------------------------------
TextControlParaAttribDialog::~TextControlParaAttribDialog()
{
}
//........................................................................
} // namespace svx
//........................................................................
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#include <osl/mutex.hxx>
#include <vcl/svapp.hxx>
#include <com/sun/star/accessibility/AccessibleRole.hpp>
#include <com/sun/star/accessibility/AccessibleStateType.hpp>
#include <com/sun/star/accessibility/AccessibleEventId.hpp>
#include <unotools/accessiblestatesethelper.hxx>
#include <frmfmt.hxx>
#include <ndnotxt.hxx>
#include <flyfrm.hxx>
#include <cntfrm.hxx>
#include <hints.hxx>
#include "accnotextframe.hxx"
#include <fmturl.hxx>
#include <accnotexthyperlink.hxx>
#include <svtools/imap.hxx>
#include <unotools/accessiblerelationsethelper.hxx>
#include <com/sun/star/accessibility/AccessibleRelationType.hpp>
#include <com/sun/star/accessibility/XAccessibleRelationSet.hpp>
#include <doc.hxx>
using namespace ::com::sun::star;
using namespace ::com::sun::star::accessibility;
using utl::AccessibleRelationSetHelper;
const SwNoTxtNode *SwAccessibleNoTextFrame::GetNoTxtNode() const
{
const SwNoTxtNode *pNd = 0;
const SwFlyFrm *pFlyFrm = static_cast< const SwFlyFrm *>( GetFrm() );
if( pFlyFrm->Lower() && pFlyFrm->Lower()->IsNoTxtFrm() )
{
const SwCntntFrm *pCntFrm =
static_cast<const SwCntntFrm *>( pFlyFrm->Lower() );
const SwCntntNode* pSwCntntNode = pCntFrm->GetNode();
if(pSwCntntNode != NULL)
{
pNd = pSwCntntNode->GetNoTxtNode();
}
}
return pNd;
}
SwAccessibleNoTextFrame::SwAccessibleNoTextFrame(
SwAccessibleMap* pInitMap,
sal_Int16 nInitRole,
const SwFlyFrm* pFlyFrm ) :
SwAccessibleFrameBase( pInitMap, nInitRole, pFlyFrm ),
aDepend( this, const_cast < SwNoTxtNode * >( GetNoTxtNode() ) ),
msTitle(),
msDesc()
{
const SwNoTxtNode* pNd = GetNoTxtNode();
// #i73249#
// consider new attributes Title and Description
if( pNd )
{
msTitle = pNd->GetTitle();
msDesc = pNd->GetDescription();
if ( msDesc.isEmpty() &&
msTitle != GetName() )
{
msDesc = msTitle;
}
}
}
SwAccessibleNoTextFrame::~SwAccessibleNoTextFrame()
{
}
void SwAccessibleNoTextFrame::Modify( const SfxPoolItem* pOld, const SfxPoolItem *pNew)
{
const sal_uInt16 nWhich = pOld ? pOld->Which() : pNew ? pNew->Which() : 0 ;
// #i73249#
// suppress handling of RES_NAME_CHANGED in case that attribute Title is
// used as the accessible name.
if ( nWhich != RES_NAME_CHANGED ||
msTitle.isEmpty() )
{
SwAccessibleFrameBase::Modify( pOld, pNew );
if (!GetRegisteredIn())
return; // probably was deleted - avoid doing anything
}
const SwNoTxtNode *pNd = GetNoTxtNode();
OSL_ENSURE( pNd == aDepend.GetRegisteredIn(), "invalid frame" );
switch( nWhich )
{
// #i73249#
case RES_TITLE_CHANGED:
{
OUString sOldTitle;
const SwStringMsgPoolItem* pOldItem = dynamic_cast<const SwStringMsgPoolItem*>(pOld);
if (pOldItem)
sOldTitle = pOldItem->GetString();
const OUString& sNewTitle(
dynamic_cast<const SwStringMsgPoolItem*>(pNew)->GetString() );
if ( sOldTitle == sNewTitle )
{
break;
}
msTitle = sNewTitle;
AccessibleEventObject aEvent;
aEvent.EventId = AccessibleEventId::NAME_CHANGED;
aEvent.OldValue <<= sOldTitle;
aEvent.NewValue <<= msTitle;
FireAccessibleEvent( aEvent );
if ( !pNd->GetDescription().isEmpty() )
{
break;
}
}
// intentional no break here
case RES_DESCRIPTION_CHANGED:
{
if ( pNd && GetFrm() )
{
const OUString sOldDesc( msDesc );
const OUString& rDesc = pNd->GetDescription();
msDesc = rDesc;
if ( msDesc.isEmpty() &&
msTitle != GetName() )
{
msDesc = msTitle;
}
if ( msDesc != sOldDesc )
{
AccessibleEventObject aEvent;
aEvent.EventId = AccessibleEventId::DESCRIPTION_CHANGED;
aEvent.OldValue <<= sOldDesc;
aEvent.NewValue <<= msDesc;
FireAccessibleEvent( aEvent );
}
}
}
break;
}
}
void SwAccessibleNoTextFrame::Dispose( bool bRecursive )
{
SolarMutexGuard aGuard;
if( aDepend.GetRegisteredIn() )
const_cast < SwModify *>( aDepend.GetRegisteredIn() )->Remove( &aDepend );
SwAccessibleFrameBase::Dispose( bRecursive );
}
// #i73249#
OUString SAL_CALL SwAccessibleNoTextFrame::getAccessibleName (void)
throw (uno::RuntimeException, std::exception)
{
SolarMutexGuard aGuard;
CHECK_FOR_DEFUNC( XAccessibleContext )
if ( !msTitle.isEmpty() )
{
return msTitle;
}
return SwAccessibleFrameBase::getAccessibleName();
}
OUString SAL_CALL SwAccessibleNoTextFrame::getAccessibleDescription (void)
throw (uno::RuntimeException, std::exception)
{
SolarMutexGuard aGuard;
CHECK_FOR_DEFUNC( XAccessibleContext )
return msDesc;
}
// XInterface
uno::Any SAL_CALL SwAccessibleNoTextFrame::queryInterface( const uno::Type& aType )
throw (uno::RuntimeException, std::exception)
{
if( aType ==
::cppu::UnoType<XAccessibleImage>::get() )
{
uno::Reference<XAccessibleImage> xImage = this;
uno::Any aAny;
aAny <<= xImage;
return aAny;
}
else if ( aType == cppu::UnoType<XAccessibleHypertext>::get())
{
uno::Reference<XAccessibleHypertext> aAccHypertext = this;
uno::Any aAny;
aAny <<= aAccHypertext;
return aAny;
}
else
return SwAccessibleContext::queryInterface( aType );
}
// XTypeProvider
uno::Sequence< uno::Type > SAL_CALL SwAccessibleNoTextFrame::getTypes() throw(uno::RuntimeException, std::exception)
{
uno::Sequence< uno::Type > aTypes( SwAccessibleFrameBase::getTypes() );
sal_Int32 nIndex = aTypes.getLength();
aTypes.realloc( nIndex + 1 );
uno::Type* pTypes = aTypes.getArray();
pTypes[nIndex] = ::cppu::UnoType<XAccessibleImage>::get();
return aTypes;
}
/// XAccessibleImage
/** implementation of the XAccessibleImage methods is a no-brainer, as
all relevant information is already accessible through other
methods. So we just delegate to those. */
OUString SAL_CALL SwAccessibleNoTextFrame::getAccessibleImageDescription()
throw ( uno::RuntimeException, std::exception )
{
return getAccessibleDescription();
}
sal_Int32 SAL_CALL SwAccessibleNoTextFrame::getAccessibleImageHeight( )
throw ( uno::RuntimeException, std::exception )
{
return getSize().Height;
}
sal_Int32 SAL_CALL SwAccessibleNoTextFrame::getAccessibleImageWidth( )
throw ( uno::RuntimeException, std::exception )
{
return getSize().Width;
}
// XAccesibleText
sal_Int32 SAL_CALL SwAccessibleNoTextFrame::getCaretPosition( ) throw (::com::sun::star::uno::RuntimeException, std::exception){return 0;}
sal_Bool SAL_CALL SwAccessibleNoTextFrame::setCaretPosition( sal_Int32 ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException, std::exception){return 0;}
sal_Unicode SAL_CALL SwAccessibleNoTextFrame::getCharacter( sal_Int32 ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException, std::exception){return 0;}
::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue > SAL_CALL SwAccessibleNoTextFrame::getCharacterAttributes( sal_Int32 , const ::com::sun::star::uno::Sequence< OUString >& ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException, std::exception)
{
uno::Sequence<beans::PropertyValue> aValues(0);
return aValues;
}
::com::sun::star::awt::Rectangle SAL_CALL SwAccessibleNoTextFrame::getCharacterBounds( sal_Int32 ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException, std::exception)
{
return com::sun::star::awt::Rectangle(0, 0, 0, 0 );
}
sal_Int32 SAL_CALL SwAccessibleNoTextFrame::getCharacterCount( ) throw (::com::sun::star::uno::RuntimeException, std::exception){return 0;}
sal_Int32 SAL_CALL SwAccessibleNoTextFrame::getIndexAtPoint( const ::com::sun::star::awt::Point& ) throw (::com::sun::star::uno::RuntimeException, std::exception){return 0;}
OUString SAL_CALL SwAccessibleNoTextFrame::getSelectedText( ) throw (::com::sun::star::uno::RuntimeException, std::exception){return OUString();}
sal_Int32 SAL_CALL SwAccessibleNoTextFrame::getSelectionStart( ) throw (::com::sun::star::uno::RuntimeException, std::exception){return 0;}
sal_Int32 SAL_CALL SwAccessibleNoTextFrame::getSelectionEnd( ) throw (::com::sun::star::uno::RuntimeException, std::exception){return 0;}
sal_Bool SAL_CALL SwAccessibleNoTextFrame::setSelection( sal_Int32 , sal_Int32 ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException, std::exception){return sal_True;}
OUString SAL_CALL SwAccessibleNoTextFrame::getText( ) throw (::com::sun::star::uno::RuntimeException, std::exception){return OUString();}
OUString SAL_CALL SwAccessibleNoTextFrame::getTextRange( sal_Int32 , sal_Int32 ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException, std::exception){return OUString();}
::com::sun::star::accessibility::TextSegment SAL_CALL SwAccessibleNoTextFrame::getTextAtIndex( sal_Int32 , sal_Int16 ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException, std::exception)
{
::com::sun::star::accessibility::TextSegment aResult;
return aResult;
}
::com::sun::star::accessibility::TextSegment SAL_CALL SwAccessibleNoTextFrame::getTextBeforeIndex( sal_Int32, sal_Int16 ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException, std::exception)
{
::com::sun::star::accessibility::TextSegment aResult;
return aResult;
}
::com::sun::star::accessibility::TextSegment SAL_CALL SwAccessibleNoTextFrame::getTextBehindIndex( sal_Int32 , sal_Int16 ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException, std::exception)
{
::com::sun::star::accessibility::TextSegment aResult;
return aResult;
}
sal_Bool SAL_CALL SwAccessibleNoTextFrame::copyText( sal_Int32, sal_Int32 ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException, std::exception){return sal_True;}
// XAccessibleHyperText
sal_Int32 SAL_CALL SwAccessibleNoTextFrame::getHyperLinkCount()
throw (uno::RuntimeException, std::exception)
{
SolarMutexGuard aGuard;
CHECK_FOR_DEFUNC( XAccessibleHypertext );
sal_Int32 nCount = 0;
SwFmtURL aURL( ((SwLayoutFrm*)GetFrm())->GetFmt()->GetURL() );
if(aURL.GetMap() || !aURL.GetURL().isEmpty())
nCount = 1;
return nCount;
}
uno::Reference< XAccessibleHyperlink > SAL_CALL
SwAccessibleNoTextFrame::getHyperLink( sal_Int32 nLinkIndex )
throw (lang::IndexOutOfBoundsException, uno::RuntimeException, std::exception)
{
SolarMutexGuard aGuard;
CHECK_FOR_DEFUNC( XAccessibleHypertext );
uno::Reference< XAccessibleHyperlink > xRet;
SwFmtURL aURL( ((SwLayoutFrm*)GetFrm())->GetFmt()->GetURL() );
if( nLinkIndex > 0 )
throw lang::IndexOutOfBoundsException();
if( aURL.GetMap() || !aURL.GetURL().isEmpty() )
{
if ( !alink.is() )
{
alink = new SwAccessibleNoTextHyperlink( this, GetFrm() );
}
return alink;
}
return NULL;
}
sal_Int32 SAL_CALL SwAccessibleNoTextFrame::getHyperLinkIndex( sal_Int32 )
throw (lang::IndexOutOfBoundsException, uno::RuntimeException, std::exception)
{
SolarMutexGuard aGuard;
return 0;
}
uno::Reference<XAccessibleRelationSet> SAL_CALL SwAccessibleNoTextFrame::getAccessibleRelationSet( )
throw ( uno::RuntimeException, std::exception )
{
SolarMutexGuard aGuard;
return new AccessibleRelationSetHelper();
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>coverity#1078575 Unchecked dynamic_cast<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#include <osl/mutex.hxx>
#include <vcl/svapp.hxx>
#include <com/sun/star/accessibility/AccessibleRole.hpp>
#include <com/sun/star/accessibility/AccessibleStateType.hpp>
#include <com/sun/star/accessibility/AccessibleEventId.hpp>
#include <unotools/accessiblestatesethelper.hxx>
#include <frmfmt.hxx>
#include <ndnotxt.hxx>
#include <flyfrm.hxx>
#include <cntfrm.hxx>
#include <hints.hxx>
#include "accnotextframe.hxx"
#include <fmturl.hxx>
#include <accnotexthyperlink.hxx>
#include <svtools/imap.hxx>
#include <unotools/accessiblerelationsethelper.hxx>
#include <com/sun/star/accessibility/AccessibleRelationType.hpp>
#include <com/sun/star/accessibility/XAccessibleRelationSet.hpp>
#include <doc.hxx>
using namespace ::com::sun::star;
using namespace ::com::sun::star::accessibility;
using utl::AccessibleRelationSetHelper;
const SwNoTxtNode *SwAccessibleNoTextFrame::GetNoTxtNode() const
{
const SwNoTxtNode *pNd = 0;
const SwFlyFrm *pFlyFrm = static_cast< const SwFlyFrm *>( GetFrm() );
if( pFlyFrm->Lower() && pFlyFrm->Lower()->IsNoTxtFrm() )
{
const SwCntntFrm *pCntFrm =
static_cast<const SwCntntFrm *>( pFlyFrm->Lower() );
const SwCntntNode* pSwCntntNode = pCntFrm->GetNode();
if(pSwCntntNode != NULL)
{
pNd = pSwCntntNode->GetNoTxtNode();
}
}
return pNd;
}
SwAccessibleNoTextFrame::SwAccessibleNoTextFrame(
SwAccessibleMap* pInitMap,
sal_Int16 nInitRole,
const SwFlyFrm* pFlyFrm ) :
SwAccessibleFrameBase( pInitMap, nInitRole, pFlyFrm ),
aDepend( this, const_cast < SwNoTxtNode * >( GetNoTxtNode() ) ),
msTitle(),
msDesc()
{
const SwNoTxtNode* pNd = GetNoTxtNode();
// #i73249#
// consider new attributes Title and Description
if( pNd )
{
msTitle = pNd->GetTitle();
msDesc = pNd->GetDescription();
if ( msDesc.isEmpty() &&
msTitle != GetName() )
{
msDesc = msTitle;
}
}
}
SwAccessibleNoTextFrame::~SwAccessibleNoTextFrame()
{
}
void SwAccessibleNoTextFrame::Modify( const SfxPoolItem* pOld, const SfxPoolItem *pNew)
{
const sal_uInt16 nWhich = pOld ? pOld->Which() : pNew ? pNew->Which() : 0 ;
// #i73249#
// suppress handling of RES_NAME_CHANGED in case that attribute Title is
// used as the accessible name.
if ( nWhich != RES_NAME_CHANGED ||
msTitle.isEmpty() )
{
SwAccessibleFrameBase::Modify( pOld, pNew );
if (!GetRegisteredIn())
return; // probably was deleted - avoid doing anything
}
const SwNoTxtNode *pNd = GetNoTxtNode();
OSL_ENSURE( pNd == aDepend.GetRegisteredIn(), "invalid frame" );
switch( nWhich )
{
// #i73249#
case RES_TITLE_CHANGED:
{
OUString sOldTitle, sNewTitle;
const SwStringMsgPoolItem* pOldItem = dynamic_cast<const SwStringMsgPoolItem*>(pOld);
if (pOldItem)
sOldTitle = pOldItem->GetString();
const SwStringMsgPoolItem* pNewItem = dynamic_cast<const SwStringMsgPoolItem*>(pNew);
if (pNewItem)
sNewTitle = pNewItem->GetString();
if ( sOldTitle == sNewTitle )
{
break;
}
msTitle = sNewTitle;
AccessibleEventObject aEvent;
aEvent.EventId = AccessibleEventId::NAME_CHANGED;
aEvent.OldValue <<= sOldTitle;
aEvent.NewValue <<= msTitle;
FireAccessibleEvent( aEvent );
if ( !pNd->GetDescription().isEmpty() )
{
break;
}
}
// intentional no break here
case RES_DESCRIPTION_CHANGED:
{
if ( pNd && GetFrm() )
{
const OUString sOldDesc( msDesc );
const OUString& rDesc = pNd->GetDescription();
msDesc = rDesc;
if ( msDesc.isEmpty() &&
msTitle != GetName() )
{
msDesc = msTitle;
}
if ( msDesc != sOldDesc )
{
AccessibleEventObject aEvent;
aEvent.EventId = AccessibleEventId::DESCRIPTION_CHANGED;
aEvent.OldValue <<= sOldDesc;
aEvent.NewValue <<= msDesc;
FireAccessibleEvent( aEvent );
}
}
}
break;
}
}
void SwAccessibleNoTextFrame::Dispose( bool bRecursive )
{
SolarMutexGuard aGuard;
if( aDepend.GetRegisteredIn() )
const_cast < SwModify *>( aDepend.GetRegisteredIn() )->Remove( &aDepend );
SwAccessibleFrameBase::Dispose( bRecursive );
}
// #i73249#
OUString SAL_CALL SwAccessibleNoTextFrame::getAccessibleName (void)
throw (uno::RuntimeException, std::exception)
{
SolarMutexGuard aGuard;
CHECK_FOR_DEFUNC( XAccessibleContext )
if ( !msTitle.isEmpty() )
{
return msTitle;
}
return SwAccessibleFrameBase::getAccessibleName();
}
OUString SAL_CALL SwAccessibleNoTextFrame::getAccessibleDescription (void)
throw (uno::RuntimeException, std::exception)
{
SolarMutexGuard aGuard;
CHECK_FOR_DEFUNC( XAccessibleContext )
return msDesc;
}
// XInterface
uno::Any SAL_CALL SwAccessibleNoTextFrame::queryInterface( const uno::Type& aType )
throw (uno::RuntimeException, std::exception)
{
if( aType ==
::cppu::UnoType<XAccessibleImage>::get() )
{
uno::Reference<XAccessibleImage> xImage = this;
uno::Any aAny;
aAny <<= xImage;
return aAny;
}
else if ( aType == cppu::UnoType<XAccessibleHypertext>::get())
{
uno::Reference<XAccessibleHypertext> aAccHypertext = this;
uno::Any aAny;
aAny <<= aAccHypertext;
return aAny;
}
else
return SwAccessibleContext::queryInterface( aType );
}
// XTypeProvider
uno::Sequence< uno::Type > SAL_CALL SwAccessibleNoTextFrame::getTypes() throw(uno::RuntimeException, std::exception)
{
uno::Sequence< uno::Type > aTypes( SwAccessibleFrameBase::getTypes() );
sal_Int32 nIndex = aTypes.getLength();
aTypes.realloc( nIndex + 1 );
uno::Type* pTypes = aTypes.getArray();
pTypes[nIndex] = ::cppu::UnoType<XAccessibleImage>::get();
return aTypes;
}
/// XAccessibleImage
/** implementation of the XAccessibleImage methods is a no-brainer, as
all relevant information is already accessible through other
methods. So we just delegate to those. */
OUString SAL_CALL SwAccessibleNoTextFrame::getAccessibleImageDescription()
throw ( uno::RuntimeException, std::exception )
{
return getAccessibleDescription();
}
sal_Int32 SAL_CALL SwAccessibleNoTextFrame::getAccessibleImageHeight( )
throw ( uno::RuntimeException, std::exception )
{
return getSize().Height;
}
sal_Int32 SAL_CALL SwAccessibleNoTextFrame::getAccessibleImageWidth( )
throw ( uno::RuntimeException, std::exception )
{
return getSize().Width;
}
// XAccesibleText
sal_Int32 SAL_CALL SwAccessibleNoTextFrame::getCaretPosition( ) throw (::com::sun::star::uno::RuntimeException, std::exception){return 0;}
sal_Bool SAL_CALL SwAccessibleNoTextFrame::setCaretPosition( sal_Int32 ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException, std::exception){return 0;}
sal_Unicode SAL_CALL SwAccessibleNoTextFrame::getCharacter( sal_Int32 ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException, std::exception){return 0;}
::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue > SAL_CALL SwAccessibleNoTextFrame::getCharacterAttributes( sal_Int32 , const ::com::sun::star::uno::Sequence< OUString >& ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException, std::exception)
{
uno::Sequence<beans::PropertyValue> aValues(0);
return aValues;
}
::com::sun::star::awt::Rectangle SAL_CALL SwAccessibleNoTextFrame::getCharacterBounds( sal_Int32 ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException, std::exception)
{
return com::sun::star::awt::Rectangle(0, 0, 0, 0 );
}
sal_Int32 SAL_CALL SwAccessibleNoTextFrame::getCharacterCount( ) throw (::com::sun::star::uno::RuntimeException, std::exception){return 0;}
sal_Int32 SAL_CALL SwAccessibleNoTextFrame::getIndexAtPoint( const ::com::sun::star::awt::Point& ) throw (::com::sun::star::uno::RuntimeException, std::exception){return 0;}
OUString SAL_CALL SwAccessibleNoTextFrame::getSelectedText( ) throw (::com::sun::star::uno::RuntimeException, std::exception){return OUString();}
sal_Int32 SAL_CALL SwAccessibleNoTextFrame::getSelectionStart( ) throw (::com::sun::star::uno::RuntimeException, std::exception){return 0;}
sal_Int32 SAL_CALL SwAccessibleNoTextFrame::getSelectionEnd( ) throw (::com::sun::star::uno::RuntimeException, std::exception){return 0;}
sal_Bool SAL_CALL SwAccessibleNoTextFrame::setSelection( sal_Int32 , sal_Int32 ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException, std::exception){return sal_True;}
OUString SAL_CALL SwAccessibleNoTextFrame::getText( ) throw (::com::sun::star::uno::RuntimeException, std::exception){return OUString();}
OUString SAL_CALL SwAccessibleNoTextFrame::getTextRange( sal_Int32 , sal_Int32 ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException, std::exception){return OUString();}
::com::sun::star::accessibility::TextSegment SAL_CALL SwAccessibleNoTextFrame::getTextAtIndex( sal_Int32 , sal_Int16 ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException, std::exception)
{
::com::sun::star::accessibility::TextSegment aResult;
return aResult;
}
::com::sun::star::accessibility::TextSegment SAL_CALL SwAccessibleNoTextFrame::getTextBeforeIndex( sal_Int32, sal_Int16 ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException, std::exception)
{
::com::sun::star::accessibility::TextSegment aResult;
return aResult;
}
::com::sun::star::accessibility::TextSegment SAL_CALL SwAccessibleNoTextFrame::getTextBehindIndex( sal_Int32 , sal_Int16 ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException, std::exception)
{
::com::sun::star::accessibility::TextSegment aResult;
return aResult;
}
sal_Bool SAL_CALL SwAccessibleNoTextFrame::copyText( sal_Int32, sal_Int32 ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException, std::exception){return sal_True;}
// XAccessibleHyperText
sal_Int32 SAL_CALL SwAccessibleNoTextFrame::getHyperLinkCount()
throw (uno::RuntimeException, std::exception)
{
SolarMutexGuard aGuard;
CHECK_FOR_DEFUNC( XAccessibleHypertext );
sal_Int32 nCount = 0;
SwFmtURL aURL( ((SwLayoutFrm*)GetFrm())->GetFmt()->GetURL() );
if(aURL.GetMap() || !aURL.GetURL().isEmpty())
nCount = 1;
return nCount;
}
uno::Reference< XAccessibleHyperlink > SAL_CALL
SwAccessibleNoTextFrame::getHyperLink( sal_Int32 nLinkIndex )
throw (lang::IndexOutOfBoundsException, uno::RuntimeException, std::exception)
{
SolarMutexGuard aGuard;
CHECK_FOR_DEFUNC( XAccessibleHypertext );
uno::Reference< XAccessibleHyperlink > xRet;
SwFmtURL aURL( ((SwLayoutFrm*)GetFrm())->GetFmt()->GetURL() );
if( nLinkIndex > 0 )
throw lang::IndexOutOfBoundsException();
if( aURL.GetMap() || !aURL.GetURL().isEmpty() )
{
if ( !alink.is() )
{
alink = new SwAccessibleNoTextHyperlink( this, GetFrm() );
}
return alink;
}
return NULL;
}
sal_Int32 SAL_CALL SwAccessibleNoTextFrame::getHyperLinkIndex( sal_Int32 )
throw (lang::IndexOutOfBoundsException, uno::RuntimeException, std::exception)
{
SolarMutexGuard aGuard;
return 0;
}
uno::Reference<XAccessibleRelationSet> SAL_CALL SwAccessibleNoTextFrame::getAccessibleRelationSet( )
throw ( uno::RuntimeException, std::exception )
{
SolarMutexGuard aGuard;
return new AccessibleRelationSetHelper();
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: FldRefTreeListBox.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: obo $ $Date: 2008-02-26 10:46:37 $
*
* 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 _FLDREFTREELISTBOX_HXX
#define _FLDREFTREELISTBOX_HXX
#ifndef _SVTREEBOX_HXX
#include <svtools/svtreebx.hxx>
#endif
class SwFldRefTreeListBox : public SvTreeListBox
{
protected:
virtual void RequestHelp( const HelpEvent& rHEvt );
public:
SwFldRefTreeListBox(Window* pParent, const ResId& rResId);
virtual ~SwFldRefTreeListBox();
// virtual long GetTabPos( SvLBoxEntry*, SvLBoxTab* );
};
#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.2.58); FILE MERGED 2008/04/01 15:58:59 thb 1.2.58.2: #i85898# Stripping all external header guards 2008/03/31 16:58:00 rt 1.2.58.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: FldRefTreeListBox.hxx,v $
* $Revision: 1.3 $
*
* 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 _FLDREFTREELISTBOX_HXX
#define _FLDREFTREELISTBOX_HXX
#include <svtools/svtreebx.hxx>
class SwFldRefTreeListBox : public SvTreeListBox
{
protected:
virtual void RequestHelp( const HelpEvent& rHEvt );
public:
SwFldRefTreeListBox(Window* pParent, const ResId& rResId);
virtual ~SwFldRefTreeListBox();
// virtual long GetTabPos( SvLBoxEntry*, SvLBoxTab* );
};
#endif
<|endoftext|> |
<commit_before>/*
kopeteidentity.cpp - Kopete Identity
Copyright (c) 2007 by Gustavo Pichorim Boiko <[email protected]>
Kopete (c) 2002-2007 by the Kopete developers <[email protected]>
*************************************************************************
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Lesser General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
*************************************************************************
*/
#include "kopetepropertycontainer.h"
#include "kopeteidentity.h"
#include "kopeteaccount.h"
#include "kopetecontact.h"
#include <QStringList>
#include <KDebug>
#include <KConfigGroup>
#include <KGlobal>
#include <KSharedConfigPtr>
#include <kdeversion.h>
namespace Kopete
{
class Identity::Private
{
public:
QList<Kopete::Account*> accounts;
QString id;
KConfigGroup *configGroup;
OnlineStatus onlineStatus;
};
Identity::Identity(const QString &id)
{
d = new Private;
d->id = id;
d->configGroup = new KConfigGroup(KGlobal::config(), QString::fromLatin1( "Identity_%1" ).arg( id ));
}
Identity::~Identity()
{
emit identityDestroyed(this);
delete d->configGroup;
delete d;
}
QString Identity::identityId() const
{
return d->id;
}
Kopete::UI::InfoPage::List Identity::customInfoPages() const
{
// TODO implement
Kopete::UI::InfoPage::List list;
return list;
}
bool Identity::excludeConnect() const
{
//TODO implement
return false;
}
void Identity::setOnlineStatus( uint category, const QString &awayMessage )
{
OnlineStatusManager::Categories katgor=(OnlineStatusManager::Categories)category;
foreach( Account *account , d->accounts )
{
Kopete::OnlineStatus status = OnlineStatusManager::self()->onlineStatus(account->protocol() , katgor);
if ( !account->excludeConnect() )
account->setOnlineStatus( status , awayMessage );
}
}
OnlineStatus Identity::onlineStatus() const
{
//TODO implement
return d->onlineStatus;
}
QString Identity::toolTip() const
{
//TODO implement
return QString("Identity %1").arg(d->id);
}
QString Identity::customIcon() const
{
//TODO implement
return "identity";
}
KActionMenu* Identity::actionMenu()
{
//TODO implement
return new KActionMenu(d->id, this);
}
void Identity::addAccount( Kopete::Account *account )
{
// check if we already have this account
if ( d->accounts.indexOf( account ) != -1 )
return;
d->accounts.append( account );
//TODO implement the signals for status changes and so
}
void Identity::removeAccount( Kopete::Account *account )
{
//TODO disconnect signals and so on
d->accounts.removeAll( account );
}
KConfigGroup *Identity::configGroup() const
{
return d->configGroup;
}
void Identity::load()
{
QStringList properties = d->configGroup->readEntry("Properties", QStringList());
QMap<QString,QString> props;
foreach(QString prop, properties)
{
props[ prop ] = d->configGroup->readEntry( prop, QString() );
}
}
void Identity::save()
{
// FIXME: using kconfig for now, but I guess this is going to change
d->configGroup->writeEntry("Properties", properties());
QMap<QString,QString> props;
serializeProperties(props);
QMap<QString,QString>::iterator it;
for (it = props.begin(); it != props.end(); ++it)
{
d->configGroup->writeEntry(it.key(), *it);
}
}
void Identity::updateOnlineStatus()
{
Kopete::OnlineStatus mostSignificantStatus;
foreach(Account *account, d->accounts)
{
// find most significant status
if ( account->myself()->onlineStatus() > mostSignificantStatus )
mostSignificantStatus = account->myself()->onlineStatus();
}
if( mostSignificantStatus != d->onlineStatus )
{
emit onlineStatusChanged( this, d->onlineStatus, mostSignificantStatus );
d->onlineStatus = mostSignificantStatus;
}
}
} //END namespace Kopete
#include "kopeteidentity.moc"
// vim: set noet ts=4 sts=4 sw=4:
<commit_msg>Add something in the tooltip and in the context menu<commit_after>/*
kopeteidentity.cpp - Kopete Identity
Copyright (c) 2007 by Gustavo Pichorim Boiko <[email protected]>
Kopete (c) 2002-2007 by the Kopete developers <[email protected]>
*************************************************************************
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Lesser General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
*************************************************************************
*/
#include "kopetepropertycontainer.h"
#include "kopeteidentity.h"
#include "kopeteaccount.h"
#include "kopetecontact.h"
#include "kopeteprotocol.h"
#include <QStringList>
#include <KDebug>
#include <KConfigGroup>
#include <KGlobal>
#include <KSharedConfigPtr>
#include <KLocale>
#include <kdeversion.h>
namespace Kopete
{
class Identity::Private
{
public:
QList<Kopete::Account*> accounts;
QString id;
KConfigGroup *configGroup;
OnlineStatus onlineStatus;
};
Identity::Identity(const QString &id)
{
d = new Private;
d->id = id;
d->configGroup = new KConfigGroup(KGlobal::config(), QString::fromLatin1( "Identity_%1" ).arg( id ));
}
Identity::~Identity()
{
emit identityDestroyed(this);
delete d->configGroup;
delete d;
}
QString Identity::identityId() const
{
return d->id;
}
Kopete::UI::InfoPage::List Identity::customInfoPages() const
{
// TODO implement
Kopete::UI::InfoPage::List list;
return list;
}
bool Identity::excludeConnect() const
{
//TODO implement
return false;
}
void Identity::setOnlineStatus( uint category, const QString &awayMessage )
{
OnlineStatusManager::Categories katgor=(OnlineStatusManager::Categories)category;
foreach( Account *account , d->accounts )
{
Kopete::OnlineStatus status = OnlineStatusManager::self()->onlineStatus(account->protocol() , katgor);
if ( !account->excludeConnect() )
account->setOnlineStatus( status , awayMessage );
}
}
OnlineStatus Identity::onlineStatus() const
{
//TODO implement
return d->onlineStatus;
}
QString Identity::toolTip() const
{
QString tt = QLatin1String("<qt>");
QString nick;
if ( hasProperty(Kopete::Global::Properties::self()->nickName().key()) )
nick = getProperty(Kopete::Global::Properties::self()->nickName()).value().toString();
else
nick = d->id;
tt+= i18nc( "Identity tooltip information: <nobr>ICON <b>NAME</b><br/></br>",
"<nobr><img src=\"kopete-identity-icon:%1\"> <b>%2</b><br/<br/>",
QString(QUrl::toPercentEncoding( d->id )), nick );
foreach(Account *a, d->accounts)
{
Kopete::Contact *self = a->myself();
tt += i18nc( "Account tooltip information: <nobr>ICON <b>PROTOCOL:</b> NAME (<i>STATUS</i>)<br/>",
"<nobr><img src=\"kopete-account-icon:%3:%4\"> <b>%1:</b> %2 (<i>%5</i>)<br/>",
a->protocol()->displayName(), a->accountLabel(), QString(QUrl::toPercentEncoding( a->protocol()->pluginId() )),
QString(QUrl::toPercentEncoding( a->accountId() )), self->onlineStatus().description() );
}
tt += QLatin1String("</qt>");
return tt;
}
QString Identity::customIcon() const
{
//TODO implement
return "identity";
}
KActionMenu* Identity::actionMenu()
{
//TODO check what layout we want to have for this menu
// for now if there is only on account, return the account menu
if (d->accounts.count() == 1)
return d->accounts.first()->actionMenu();
// if there is more than one account, add them as submenus of this identity menu
KActionMenu *menu = new KActionMenu(d->id, this);
foreach(Account *account, d->accounts)
{
KActionMenu *accountMenu = account->actionMenu();
accountMenu->setIcon( account->myself()->onlineStatus().iconFor(account->myself()) );
menu->addAction( accountMenu );
}
return menu;
}
void Identity::addAccount( Kopete::Account *account )
{
// check if we already have this account
if ( d->accounts.indexOf( account ) != -1 )
return;
d->accounts.append( account );
//TODO implement the signals for status changes and so
}
void Identity::removeAccount( Kopete::Account *account )
{
//TODO disconnect signals and so on
d->accounts.removeAll( account );
}
KConfigGroup *Identity::configGroup() const
{
return d->configGroup;
}
void Identity::load()
{
QStringList properties = d->configGroup->readEntry("Properties", QStringList());
QMap<QString,QString> props;
foreach(QString prop, properties)
{
props[ prop ] = d->configGroup->readEntry( prop, QString() );
}
}
void Identity::save()
{
// FIXME: using kconfig for now, but I guess this is going to change
d->configGroup->writeEntry("Properties", properties());
QMap<QString,QString> props;
serializeProperties(props);
QMap<QString,QString>::iterator it;
for (it = props.begin(); it != props.end(); ++it)
{
d->configGroup->writeEntry(it.key(), *it);
}
}
void Identity::updateOnlineStatus()
{
Kopete::OnlineStatus mostSignificantStatus;
foreach(Account *account, d->accounts)
{
// find most significant status
if ( account->myself()->onlineStatus() > mostSignificantStatus )
mostSignificantStatus = account->myself()->onlineStatus();
}
if( mostSignificantStatus != d->onlineStatus )
{
emit onlineStatusChanged( this, d->onlineStatus, mostSignificantStatus );
d->onlineStatus = mostSignificantStatus;
}
}
} //END namespace Kopete
#include "kopeteidentity.moc"
// vim: set noet ts=4 sts=4 sw=4:
<|endoftext|> |
<commit_before>/* Copyright 2021 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/data/service/py_utils.h"
#include "tensorflow/core/data/service/credentials_factory.h"
namespace tensorflow {
namespace data {
std::string DefaultProtocol() {
#if defined(PLATFORM_GOOGLE)
if (CredentialsFactory::Exists("grpc+loas")) {
return "grpc+loas";
}
LOG(WARNING) << "loas credentials factory is not available, falling back to "
"using insecure credentials.";
#endif // PLATFORM_GOOGLE
return "grpc";
}
} // namespace data
} // namespace tensorflow
<commit_msg>[tf.data service] Reduce frequency of insecure credentials warning.<commit_after>/* Copyright 2021 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/data/service/py_utils.h"
#include "tensorflow/core/data/service/credentials_factory.h"
namespace tensorflow {
namespace data {
std::string DefaultProtocol() {
#if defined(PLATFORM_GOOGLE)
if (CredentialsFactory::Exists("grpc+loas")) {
return "grpc+loas";
}
static absl::once_flag log_once;
absl::call_once(log_once, [] {
LOG(WARNING)
<< "loas credentials factory is not available, falling back to "
"using insecure credentials.";
});
#endif // PLATFORM_GOOGLE
return "grpc";
}
} // namespace data
} // namespace tensorflow
<|endoftext|> |
<commit_before>#include "gbgpu.h"
gbgpu::gbgpu(z80mmu *mmu) {
this->mmu = mmu;
reset();
}
void gbgpu::reset() {
mode = 2;
modeclock = 0;
line = 0;
for (int i = 0; i < 4; ++i) {
pallete_bg[i] = pallete_obj0[i] = pallete_obj1[i] = 255;
}
for (int y = 0; y < _GBGPU_H; ++y) {
for (int x = 0; x < _GBGPU_W; ++x) {
for (int c = 0; c < 4; ++c) {
screen_buffer[y][x][c] = 255;
}
}
}
}
void gbgpu::step(int z80m) {
preprocessram();
modeclock += z80m;
updated = false;
switch (mode) {
case 2:
if (modeclock >= 20) {
modeclock = 0;
mode = 3;
}
break;
case 3:
if (modeclock >= 43) {
modeclock = 0;
mode = 0;
renderscan();
}
break;
case 0:
if (modeclock >= 51) {
modeclock = 0;
++line;
if (line == 144) {
mode = 1;
updated = true;
} else {
mode = 2;
}
}
break;
case 1:
if (modeclock >= 114) {
modeclock = 0;
++line;
if (line > 153) {
mode = 2;
line = 0;
}
}
break;
}
postprocessram();
}
quint8 *gbgpu::getLCD() {
return &screen_buffer[0][0][0];
}
bool gbgpu::is_updated() {
return updated;
}
bool gbgpu::lcd_on() {
return mmu->readbyte(_GBGPU_VREGBASE) & 0x80;
}
bool gbgpu::bg_on() {
return mmu->readbyte(_GBGPU_VREGBASE) & 0x01;
}
bool gbgpu::win_on() {
return mmu->readbyte(_GBGPU_VREGBASE) & 0x20;
}
bool gbgpu::sprite_large() {
return mmu->readbyte(_GBGPU_VREGBASE) & 0x04;
}
quint16 gbgpu::bg_mapbase() {
if (mmu->readbyte(_GBGPU_VREGBASE) & 0x08) {
return _GBGPU_VRAMBASE + 0x1C00;
} else {
return _GBGPU_VRAMBASE + 0x1800;
}
}
quint16 gbgpu::win_mapbase() {
if (mmu->readbyte(_GBGPU_VREGBASE) & 0x40) {
return _GBGPU_VRAMBASE + 0x1C00;
} else {
return _GBGPU_VRAMBASE + 0x1800;
}
}
bool gbgpu::tileset1() {
return mmu->readbyte(_GBGPU_VREGBASE) & 0x10;
}
bool gbgpu::sprite_on() {
return mmu->readbyte(_GBGPU_VREGBASE) & 0x02;
}
quint8 gbgpu::yscroll() {
return mmu->readbyte(_GBGPU_VREGBASE + 2);
}
quint8 gbgpu::xscroll() {
return mmu->readbyte(_GBGPU_VREGBASE + 3);
}
quint8 gbgpu::winypos() {
return mmu->readbyte(_GBGPU_VREGBASE + 10);
}
quint8 gbgpu::winxpos() {
return mmu->readbyte(_GBGPU_VREGBASE + 11);
}
quint8 gbgpu::linecmp() {
return mmu->readbyte(_GBGPU_VREGBASE + 5);
}
void gbgpu::preprocessram() {
quint8 oamdma = mmu->readbyte(_GBGPU_VREGBASE + 6);
if (oamdma != 0) {
quint16 baseaddr = oamdma;
baseaddr <<= 8;
for(quint8 i = 0; i < 0xA0; ++i) {
mmu->writebyte(_GBGPU_VOAMBASE + i, mmu->readbyte(baseaddr + i));
}
mmu->writebyte(_GBGPU_VREGBASE + 6, 0);
}
quint8 val = mmu->readbyte(_GBGPU_VREGBASE + 7);
for(int i = 0; i < 4; ++i) {
switch((val >> (2*i)) & 3) {
case 0: pallete_bg[i] = 255; break;
case 1: pallete_bg[i] = 192; break;
case 2: pallete_bg[i] = 96; break;
case 3: pallete_bg[i] = 0; break;
}
}
val = mmu->readbyte(_GBGPU_VREGBASE + 8);
for(int i = 0; i < 4; ++i) {
switch((val >> (2*i)) & 3) {
case 0: pallete_obj0[i] = 255; break;
case 1: pallete_obj0[i] = 192; break;
case 2: pallete_obj0[i] = 96; break;
case 3: pallete_obj0[i] = 0; break;
}
}
val = mmu->readbyte(_GBGPU_VREGBASE + 9);
for (int i = 0; i < 4; ++i) {
switch((val >> (2*i)) & 3) {
case 0: pallete_obj1[i] = 255; break;
case 1: pallete_obj1[i] = 192; break;
case 2: pallete_obj1[i] = 96; break;
case 3: pallete_obj1[i] = 0; break;
}
}
}
void gbgpu::postprocessram() {
mmu->writebyte(_GBGPU_VREGBASE + 4, line);
quint8 vreg1 = mmu->readbyte(_GBGPU_VREGBASE + 1);
vreg1 &= 0xF8;
vreg1 |= (line == linecmp() ? 4 : 0) | (mode & 0x3);
mmu->writebyte(_GBGPU_VREGBASE + 1, vreg1);
bool lcdstat = false;
if ((vreg1 & 0x40) && line == linecmp()) lcdstat = true;
if ((vreg1 & 0x20) && mode == 2) lcdstat = true;
if ((vreg1 & 0x10) && mode == 1) lcdstat = true;
if ((vreg1 & 0x08) && mode == 0) lcdstat = true;
if (lcdstat || updated) {
quint8 int_flags = mmu->readbyte(0xFF0F);
int_flags |= (lcdstat ? 0x2 : 0) | (updated ? 0x1 : 0);
mmu->writebyte(0xFF0F, int_flags);
}
}
void gbgpu::renderscan() {
if (!lcd_on()) return;
int winx, winy = line - winypos();
int bgx, bgy = yscroll() + line;
quint16 mapbase;
int posx, posy;
for (int x = 0; x < 160; ++x) {
quint8 colour = 0;
quint16 tileaddress;
if (win_on() && winypos() <= line && x >= winxpos() - 7) {
// select tile from window
winx = x - (winxpos() - 7);
posx = winx;
posy = winy;
mapbase = win_mapbase();
} else if (bg_on()) {
// select regular bg tile
bgx = xscroll() + x;
posx = bgx;
posy = bgy;
mapbase = bg_mapbase();
} else {
screen_buffer[line][x][0] = screen_buffer[line][x][1] = screen_buffer[line][x][2] = 255;
continue;
}
int tiley = (posy >> 3) & 31;
int tilex = (posx >> 3) & 31;
if (tileset1()) {
quint8 tilenr;
tilenr = mmu->readbyte(mapbase + tiley * 32 + tilex);
tileaddress = 0x8000 + tilenr * 16;
} else {
qint8 tilenr; // signed!
tilenr = mmu->readbyte(mapbase + tiley * 32 + tilex);
tileaddress = 0x9000 + tilenr * 16;
}
quint8 byte1 = mmu->readbyte(tileaddress + ((posy & 0x7) * 2));
quint8 byte2 = mmu->readbyte(tileaddress + ((posy & 0x7) * 2) + 1);
quint8 xbit = posx % 8;
quint8 colnr = (byte1 & (0x80 >> xbit)) ? 1 : 0;
colnr |= (byte2 & (0x80 >> xbit)) ? 2 : 0;
colour = pallete_bg[colnr];
screen_buffer[line][x][0] = screen_buffer[line][x][1] = screen_buffer[line][x][2] = colour;
}
if (sprite_on()) {
int spritenum = 0;
int spriteheight = sprite_large() ? 16 : 8;
for (int i = 0; i < 40; ++i) {
quint16 spriteaddr = _GBGPU_VOAMBASE + i*4;
int spritey = mmu->readbyte(spriteaddr + 0) - 16;
int spritex = mmu->readbyte(spriteaddr + 1) - 8;
quint8 spritetile = mmu->readbyte(spriteaddr + 2);
quint8 spriteflags = mmu->readbyte(spriteaddr + 3);
if (line < spritey || line >= spritey + spriteheight)
continue;
spritenum++;
if (spritenum > 10) break;
int tiley = line - spritey;
if (spriteflags & 0x40) tiley = spriteheight - 1 - tiley;
if (spriteheight == 16) {
spritetile &= 0xFE;
}
quint16 tileaddress = 0x8000 + spritetile * 16 + tiley * 2;
quint8 byte1 = mmu->readbyte(tileaddress);
quint8 byte2 = mmu->readbyte(tileaddress + 1);
for (int x = 0; x < 8; ++x) {
int tilex = x;
if (spriteflags & 0x20) tilex = 7 - tilex;
if (spritex + x < 0 || spritex + x >= 160) continue;
int colnr = ((byte1 & (0x80 >> tilex)) ? 1 : 0)
| ((byte2 & (0x80 >> tilex)) ? 2 : 0);
int colour = (spriteflags & 0x10) ? pallete_obj1[colnr] : pallete_obj0[colnr];
// colnr 0 is always transparant, and only draw on white if belowbg
if (colnr == 0 || ((spriteflags & 0x80) && screen_buffer[line][spritex + x][0] != 255)) continue;
screen_buffer[line][spritex + x][0] = screen_buffer[line][spritex + x][1] = screen_buffer[line][spritex + x][2] = colour;
}
}
}
}
<commit_msg>DE FIX!!! HEHE gevonden<commit_after>#include "gbgpu.h"
gbgpu::gbgpu(z80mmu *mmu) {
this->mmu = mmu;
reset();
}
void gbgpu::reset() {
mode = 2;
modeclock = 0;
line = 0;
for (int i = 0; i < 4; ++i) {
pallete_bg[i] = pallete_obj0[i] = pallete_obj1[i] = 255;
}
for (int y = 0; y < _GBGPU_H; ++y) {
for (int x = 0; x < _GBGPU_W; ++x) {
for (int c = 0; c < 4; ++c) {
screen_buffer[y][x][c] = 255;
}
}
}
}
void gbgpu::step(int z80m) {
preprocessram();
updated = false;
if (!lcd_on()) return;
modeclock += z80m;
switch (mode) {
case 2:
if (modeclock >= 20) {
modeclock = 0;
mode = 3;
}
break;
case 3:
if (modeclock >= 43) {
modeclock = 0;
mode = 0;
renderscan();
}
break;
case 0:
if (modeclock >= 51) {
modeclock = 0;
++line;
if (line == 144) {
mode = 1;
updated = true;
} else {
mode = 2;
}
}
break;
case 1:
if (modeclock >= 114) {
modeclock = 0;
++line;
if (line > 153) {
mode = 2;
line = 0;
}
}
break;
}
postprocessram();
}
quint8 *gbgpu::getLCD() {
return &screen_buffer[0][0][0];
}
bool gbgpu::is_updated() {
return updated;
}
bool gbgpu::lcd_on() {
return mmu->readbyte(_GBGPU_VREGBASE) & 0x80;
}
bool gbgpu::bg_on() {
return mmu->readbyte(_GBGPU_VREGBASE) & 0x01;
}
bool gbgpu::win_on() {
return mmu->readbyte(_GBGPU_VREGBASE) & 0x20;
}
bool gbgpu::sprite_large() {
return mmu->readbyte(_GBGPU_VREGBASE) & 0x04;
}
quint16 gbgpu::bg_mapbase() {
if (mmu->readbyte(_GBGPU_VREGBASE) & 0x08) {
return _GBGPU_VRAMBASE + 0x1C00;
} else {
return _GBGPU_VRAMBASE + 0x1800;
}
}
quint16 gbgpu::win_mapbase() {
if (mmu->readbyte(_GBGPU_VREGBASE) & 0x40) {
return _GBGPU_VRAMBASE + 0x1C00;
} else {
return _GBGPU_VRAMBASE + 0x1800;
}
}
bool gbgpu::tileset1() {
return mmu->readbyte(_GBGPU_VREGBASE) & 0x10;
}
bool gbgpu::sprite_on() {
return mmu->readbyte(_GBGPU_VREGBASE) & 0x02;
}
quint8 gbgpu::yscroll() {
return mmu->readbyte(_GBGPU_VREGBASE + 2);
}
quint8 gbgpu::xscroll() {
return mmu->readbyte(_GBGPU_VREGBASE + 3);
}
quint8 gbgpu::winypos() {
return mmu->readbyte(_GBGPU_VREGBASE + 10);
}
quint8 gbgpu::winxpos() {
return mmu->readbyte(_GBGPU_VREGBASE + 11);
}
quint8 gbgpu::linecmp() {
return mmu->readbyte(_GBGPU_VREGBASE + 5);
}
void gbgpu::preprocessram() {
quint8 oamdma = mmu->readbyte(_GBGPU_VREGBASE + 6);
if (oamdma != 0) {
quint16 baseaddr = oamdma;
baseaddr <<= 8;
for(quint8 i = 0; i < 0xA0; ++i) {
mmu->writebyte(_GBGPU_VOAMBASE + i, mmu->readbyte(baseaddr + i));
}
mmu->writebyte(_GBGPU_VREGBASE + 6, 0);
}
quint8 val = mmu->readbyte(_GBGPU_VREGBASE + 7);
for(int i = 0; i < 4; ++i) {
switch((val >> (2*i)) & 3) {
case 0: pallete_bg[i] = 255; break;
case 1: pallete_bg[i] = 192; break;
case 2: pallete_bg[i] = 96; break;
case 3: pallete_bg[i] = 0; break;
}
}
val = mmu->readbyte(_GBGPU_VREGBASE + 8);
for(int i = 0; i < 4; ++i) {
switch((val >> (2*i)) & 3) {
case 0: pallete_obj0[i] = 255; break;
case 1: pallete_obj0[i] = 192; break;
case 2: pallete_obj0[i] = 96; break;
case 3: pallete_obj0[i] = 0; break;
}
}
val = mmu->readbyte(_GBGPU_VREGBASE + 9);
for (int i = 0; i < 4; ++i) {
switch((val >> (2*i)) & 3) {
case 0: pallete_obj1[i] = 255; break;
case 1: pallete_obj1[i] = 192; break;
case 2: pallete_obj1[i] = 96; break;
case 3: pallete_obj1[i] = 0; break;
}
}
}
void gbgpu::postprocessram() {
mmu->writebyte(_GBGPU_VREGBASE + 4, line);
quint8 vreg1 = mmu->readbyte(_GBGPU_VREGBASE + 1);
vreg1 &= 0xF8;
vreg1 |= (line == linecmp() ? 4 : 0) | (mode & 0x3);
mmu->writebyte(_GBGPU_VREGBASE + 1, vreg1);
bool lcdstat = false;
if ((vreg1 & 0x40) && line == linecmp()) lcdstat = true;
if ((vreg1 & 0x20) && mode == 2) lcdstat = true;
if ((vreg1 & 0x10) && mode == 1) lcdstat = true;
if ((vreg1 & 0x08) && mode == 0) lcdstat = true;
if (lcdstat || updated) {
quint8 int_flags = mmu->readbyte(0xFF0F);
int_flags |= (lcdstat ? 0x2 : 0) | (updated ? 0x1 : 0);
mmu->writebyte(0xFF0F, int_flags);
}
}
void gbgpu::renderscan() {
if (!lcd_on()) return;
int winx, winy = line - winypos();
int bgx, bgy = yscroll() + line;
quint16 mapbase;
int posx, posy;
for (int x = 0; x < 160; ++x) {
quint8 colour = 0;
quint16 tileaddress;
if (win_on() && winypos() <= line && x >= winxpos() - 7) {
// select tile from window
winx = x - (winxpos() - 7);
posx = winx;
posy = winy;
mapbase = win_mapbase();
} else if (bg_on()) {
// select regular bg tile
bgx = xscroll() + x;
posx = bgx;
posy = bgy;
mapbase = bg_mapbase();
} else {
screen_buffer[line][x][0] = screen_buffer[line][x][1] = screen_buffer[line][x][2] = 255;
continue;
}
int tiley = (posy >> 3) & 31;
int tilex = (posx >> 3) & 31;
if (tileset1()) {
quint8 tilenr;
tilenr = mmu->readbyte(mapbase + tiley * 32 + tilex);
tileaddress = 0x8000 + tilenr * 16;
} else {
qint8 tilenr; // signed!
tilenr = mmu->readbyte(mapbase + tiley * 32 + tilex);
tileaddress = 0x9000 + tilenr * 16;
}
quint8 byte1 = mmu->readbyte(tileaddress + ((posy & 0x7) * 2));
quint8 byte2 = mmu->readbyte(tileaddress + ((posy & 0x7) * 2) + 1);
quint8 xbit = posx % 8;
quint8 colnr = (byte1 & (0x80 >> xbit)) ? 1 : 0;
colnr |= (byte2 & (0x80 >> xbit)) ? 2 : 0;
colour = pallete_bg[colnr];
screen_buffer[line][x][0] = screen_buffer[line][x][1] = screen_buffer[line][x][2] = colour;
}
if (sprite_on()) {
int spritenum = 0;
int spriteheight = sprite_large() ? 16 : 8;
for (int i = 0; i < 40; ++i) {
quint16 spriteaddr = _GBGPU_VOAMBASE + i*4;
int spritey = mmu->readbyte(spriteaddr + 0) - 16;
int spritex = mmu->readbyte(spriteaddr + 1) - 8;
quint8 spritetile = mmu->readbyte(spriteaddr + 2);
quint8 spriteflags = mmu->readbyte(spriteaddr + 3);
if (line < spritey || line >= spritey + spriteheight)
continue;
spritenum++;
if (spritenum > 10) break;
int tiley = line - spritey;
if (spriteflags & 0x40) tiley = spriteheight - 1 - tiley;
if (spriteheight == 16) {
spritetile &= 0xFE;
}
quint16 tileaddress = 0x8000 + spritetile * 16 + tiley * 2;
quint8 byte1 = mmu->readbyte(tileaddress);
quint8 byte2 = mmu->readbyte(tileaddress + 1);
for (int x = 0; x < 8; ++x) {
int tilex = x;
if (spriteflags & 0x20) tilex = 7 - tilex;
if (spritex + x < 0 || spritex + x >= 160) continue;
int colnr = ((byte1 & (0x80 >> tilex)) ? 1 : 0)
| ((byte2 & (0x80 >> tilex)) ? 2 : 0);
int colour = (spriteflags & 0x10) ? pallete_obj1[colnr] : pallete_obj0[colnr];
// colnr 0 is always transparant, and only draw on white if belowbg
if (colnr == 0 || ((spriteflags & 0x80) && screen_buffer[line][spritex + x][0] != 255)) continue;
screen_buffer[line][spritex + x][0] = screen_buffer[line][spritex + x][1] = screen_buffer[line][spritex + x][2] = colour;
}
}
}
}
<|endoftext|> |
<commit_before>// RUN: %clang_analyze_cc1 -analyzer-checker=debug.DumpCFG %s > %t 2>&1
// RUN: FileCheck --input-file=%t %s
// RUN: %clang_analyze_cc1 -analyzer-checker=core,debug.ExprInspection -std=c++14 -verify %s
void clang_analyzer_eval(bool);
int global;
namespace variant_0 {
// This variant of the code works correctly. Function foo() is not a template
// function. Note that there are two destructors within foo().
class A {
public:
~A() { ++global; }
};
class B {
A a;
};
// CHECK: void foo(int)
// CHECK: [B1]
// CHECK-NEXT: 1: (CXXConstructExpr, [B1.2], class variant_0::B)
// CHECK-NEXT: 2: variant_0::B i;
// CHECK-NEXT: 3: operator=
// CHECK-NEXT: 4: [B1.3] (ImplicitCastExpr, FunctionToPointerDecay, class variant_0::B &(*)(class variant_0::B &&) noexcept)
// CHECK-NEXT: 5: i
// CHECK-NEXT: 6: {} (CXXConstructExpr, [B1.7], [B1.8], class variant_0::B)
// CHECK-NEXT: 7: [B1.6] (BindTemporary)
// CHECK-NEXT: 8: [B1.7]
// CHECK-NEXT: 9: [B1.5] = [B1.8] (OperatorCall)
// CHECK-NEXT: 10: ~variant_0::B() (Temporary object destructor)
// CHECK-NEXT: 11: [B1.2].~B() (Implicit destructor)
void foo(int) {
B i;
i = {};
}
void bar() {
global = 0;
foo(1);
clang_analyzer_eval(global == 2); // expected-warning{{TRUE}}
}
} // end namespace variant_0
namespace variant_1 {
// Suddenly, if we turn foo() into a template, we are missing a
// CXXBindTemporaryExpr in the AST, and therefore we're missing a
// temporary destructor in the CFG.
class A {
public:
~A() { ++global; }
};
class B {
A a;
};
// FIXME: Find the construction context for {} and enforce the temporary
// destructor.
// CHECK: template<> void foo<int>(int)
// CHECK: [B1]
// CHECK-NEXT: 1: (CXXConstructExpr, [B1.2], class variant_1::B)
// CHECK-NEXT: 2: variant_1::B i;
// CHECK-NEXT: 3: operator=
// CHECK-NEXT: 4: [B1.3] (ImplicitCastExpr, FunctionToPointerDecay, class variant_1::B &(*)(class variant_1::B &&) noexcept)
// CHECK-NEXT: 5: i
// CHECK-NEXT: 6: {} (CXXConstructExpr, class variant_1::B)
// CHECK-NEXT: 7: [B1.6]
// CHECK-NEXT: 8: [B1.5] = [B1.7] (OperatorCall)
// CHECK-NEXT: 9: [B1.2].~B() (Implicit destructor)
template <typename T> void foo(T) {
B i;
i = {};
}
void bar() {
global = 0;
foo(1);
// FIXME: Should be TRUE, i.e. we should call (and inline) two destructors.
clang_analyzer_eval(global == 2); // expected-warning{{UNKNOWN}}
}
} // end namespace variant_1
namespace variant_2 {
// Making field 'a' in class 'B' public turns the class into an aggregate.
// In this case there is no constructor at {} - only an aggregate
// initialization. Aggregate initialization is unsupported for now.
class A {
public:
~A() { ++global; }
};
class B {
public:
A a;
};
// CHECK: template<> void foo<int>(int)
// CHECK: [B1]
// CHECK-NEXT: 1: (CXXConstructExpr, [B1.2], class variant_2::B)
// CHECK-NEXT: 2: variant_2::B i;
// CHECK-NEXT: 3: operator=
// CHECK-NEXT: 4: [B1.3] (ImplicitCastExpr, FunctionToPointerDecay, class variant_2::B &(*)(class variant_2::B &&) noexcept)
// CHECK-NEXT: 5: i
// CHECK-NEXT: 6: {}
// CHECK-NEXT: 7: {}
// CHECK-NEXT: 8: [B1.7] (BindTemporary)
// CHECK-NEXT: 9: [B1.8]
// CHECK-NEXT: 10: [B1.5] = [B1.9] (OperatorCall)
// CHECK-NEXT: 11: ~variant_2::B() (Temporary object destructor)
// CHECK-NEXT: 12: [B1.2].~B() (Implicit destructor)
template <typename T> void foo(T) {
B i;
i = {};
}
void bar() {
global = 0;
foo(1);
// FIXME: Should be TRUE, i.e. we should call (and inline) two destructors.
clang_analyzer_eval(global == 2); // expected-warning{{UNKNOWN}}
}
} // end namespace variant_2
<commit_msg>[analyzer] Fix test triple in missing-bind-temporary.cpp.<commit_after>// RUN: %clang_analyze_cc1 -triple x86_64-unknown-linux -analyzer-checker=debug.DumpCFG %s > %t 2>&1
// RUN: FileCheck --input-file=%t %s
// RUN: %clang_analyze_cc1 -triple x86_64-unknown-linux -analyzer-checker=core,debug.ExprInspection -std=c++14 -verify %s
void clang_analyzer_eval(bool);
int global;
namespace variant_0 {
// This variant of the code works correctly. Function foo() is not a template
// function. Note that there are two destructors within foo().
class A {
public:
~A() { ++global; }
};
class B {
A a;
};
// CHECK: void foo(int)
// CHECK: [B1]
// CHECK-NEXT: 1: (CXXConstructExpr, [B1.2], class variant_0::B)
// CHECK-NEXT: 2: variant_0::B i;
// CHECK-NEXT: 3: operator=
// CHECK-NEXT: 4: [B1.3] (ImplicitCastExpr, FunctionToPointerDecay, class variant_0::B &(*)(class variant_0::B &&) noexcept)
// CHECK-NEXT: 5: i
// CHECK-NEXT: 6: {} (CXXConstructExpr, [B1.7], [B1.8], class variant_0::B)
// CHECK-NEXT: 7: [B1.6] (BindTemporary)
// CHECK-NEXT: 8: [B1.7]
// CHECK-NEXT: 9: [B1.5] = [B1.8] (OperatorCall)
// CHECK-NEXT: 10: ~variant_0::B() (Temporary object destructor)
// CHECK-NEXT: 11: [B1.2].~B() (Implicit destructor)
void foo(int) {
B i;
i = {};
}
void bar() {
global = 0;
foo(1);
clang_analyzer_eval(global == 2); // expected-warning{{TRUE}}
}
} // end namespace variant_0
namespace variant_1 {
// Suddenly, if we turn foo() into a template, we are missing a
// CXXBindTemporaryExpr in the AST, and therefore we're missing a
// temporary destructor in the CFG.
class A {
public:
~A() { ++global; }
};
class B {
A a;
};
// FIXME: Find the construction context for {} and enforce the temporary
// destructor.
// CHECK: template<> void foo<int>(int)
// CHECK: [B1]
// CHECK-NEXT: 1: (CXXConstructExpr, [B1.2], class variant_1::B)
// CHECK-NEXT: 2: variant_1::B i;
// CHECK-NEXT: 3: operator=
// CHECK-NEXT: 4: [B1.3] (ImplicitCastExpr, FunctionToPointerDecay, class variant_1::B &(*)(class variant_1::B &&) noexcept)
// CHECK-NEXT: 5: i
// CHECK-NEXT: 6: {} (CXXConstructExpr, class variant_1::B)
// CHECK-NEXT: 7: [B1.6]
// CHECK-NEXT: 8: [B1.5] = [B1.7] (OperatorCall)
// CHECK-NEXT: 9: [B1.2].~B() (Implicit destructor)
template <typename T> void foo(T) {
B i;
i = {};
}
void bar() {
global = 0;
foo(1);
// FIXME: Should be TRUE, i.e. we should call (and inline) two destructors.
clang_analyzer_eval(global == 2); // expected-warning{{UNKNOWN}}
}
} // end namespace variant_1
namespace variant_2 {
// Making field 'a' in class 'B' public turns the class into an aggregate.
// In this case there is no constructor at {} - only an aggregate
// initialization. Aggregate initialization is unsupported for now.
class A {
public:
~A() { ++global; }
};
class B {
public:
A a;
};
// CHECK: template<> void foo<int>(int)
// CHECK: [B1]
// CHECK-NEXT: 1: (CXXConstructExpr, [B1.2], class variant_2::B)
// CHECK-NEXT: 2: variant_2::B i;
// CHECK-NEXT: 3: operator=
// CHECK-NEXT: 4: [B1.3] (ImplicitCastExpr, FunctionToPointerDecay, class variant_2::B &(*)(class variant_2::B &&) noexcept)
// CHECK-NEXT: 5: i
// CHECK-NEXT: 6: {}
// CHECK-NEXT: 7: {}
// CHECK-NEXT: 8: [B1.7] (BindTemporary)
// CHECK-NEXT: 9: [B1.8]
// CHECK-NEXT: 10: [B1.5] = [B1.9] (OperatorCall)
// CHECK-NEXT: 11: ~variant_2::B() (Temporary object destructor)
// CHECK-NEXT: 12: [B1.2].~B() (Implicit destructor)
template <typename T> void foo(T) {
B i;
i = {};
}
void bar() {
global = 0;
foo(1);
// FIXME: Should be TRUE, i.e. we should call (and inline) two destructors.
clang_analyzer_eval(global == 2); // expected-warning{{UNKNOWN}}
}
} // end namespace variant_2
<|endoftext|> |
<commit_before>/* libs/graphics/sgl/SkShader.cpp
**
** Copyright 2006, The Android Open Source Project
**
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
#include "SkShader.h"
#include "SkPaint.h"
SkShader::SkShader() : fLocalMatrix(NULL) {
SkDEBUGCODE(fInSession = false;)
}
SkShader::SkShader(SkFlattenableReadBuffer& buffer)
: INHERITED(buffer), fLocalMatrix(NULL) {
if (buffer.readBool()) {
SkMatrix matrix;
buffer.read(&matrix, sizeof(matrix));
setLocalMatrix(matrix);
}
SkDEBUGCODE(fInSession = false;)
}
SkShader::~SkShader() {
SkASSERT(!fInSession);
sk_free(fLocalMatrix);
}
void SkShader::beginSession() {
SkASSERT(!fInSession);
SkDEBUGCODE(fInSession = true;)
}
void SkShader::endSession() {
SkASSERT(fInSession);
SkDEBUGCODE(fInSession = false;)
}
void SkShader::flatten(SkFlattenableWriteBuffer& buffer) {
this->INHERITED::flatten(buffer);
buffer.writeBool(fLocalMatrix != NULL);
if (fLocalMatrix) {
buffer.writeMul4(fLocalMatrix, sizeof(SkMatrix));
}
}
bool SkShader::getLocalMatrix(SkMatrix* localM) const {
if (fLocalMatrix) {
if (localM) {
*localM = *fLocalMatrix;
}
return true;
} else {
if (localM) {
localM->reset();
}
return false;
}
}
void SkShader::setLocalMatrix(const SkMatrix& localM) {
if (localM.isIdentity()) {
this->resetLocalMatrix();
} else {
if (fLocalMatrix == NULL) {
fLocalMatrix = (SkMatrix*)sk_malloc_throw(sizeof(SkMatrix));
}
*fLocalMatrix = localM;
}
}
void SkShader::resetLocalMatrix() {
if (fLocalMatrix) {
sk_free(fLocalMatrix);
fLocalMatrix = NULL;
}
}
bool SkShader::setContext(const SkBitmap& device,
const SkPaint& paint,
const SkMatrix& matrix) {
const SkMatrix* m = &matrix;
SkMatrix total;
fDeviceConfig = SkToU8(device.getConfig());
fPaintAlpha = paint.getAlpha();
if (fLocalMatrix) {
total.setConcat(matrix, *fLocalMatrix);
m = &total;
}
if (m->invert(&fTotalInverse)) {
fTotalInverseClass = (uint8_t)ComputeMatrixClass(fTotalInverse);
return true;
}
return false;
}
#include "SkColorPriv.h"
void SkShader::shadeSpan16(int x, int y, uint16_t span16[], int count) {
SkASSERT(span16);
SkASSERT(count > 0);
SkASSERT(this->canCallShadeSpan16());
// basically, if we get here, the subclass screwed up
SkASSERT(!"kHasSpan16 flag is set, but shadeSpan16() not implemented");
}
#define kTempColorQuadCount 6 // balance between speed (larger) and saving stack-space
#define kTempColorCount (kTempColorQuadCount << 2)
#ifdef SK_CPU_BENDIAN
#define SkU32BitShiftToByteOffset(shift) (3 - ((shift) >> 3))
#else
#define SkU32BitShiftToByteOffset(shift) ((shift) >> 3)
#endif
void SkShader::shadeSpanAlpha(int x, int y, uint8_t alpha[], int count) {
SkASSERT(count > 0);
SkPMColor colors[kTempColorCount];
while ((count -= kTempColorCount) >= 0) {
this->shadeSpan(x, y, colors, kTempColorCount);
x += kTempColorCount;
const uint8_t* srcA = (const uint8_t*)colors + SkU32BitShiftToByteOffset(SK_A32_SHIFT);
int quads = kTempColorQuadCount;
do {
U8CPU a0 = srcA[0];
U8CPU a1 = srcA[4];
U8CPU a2 = srcA[8];
U8CPU a3 = srcA[12];
srcA += 4*4;
*alpha++ = SkToU8(a0);
*alpha++ = SkToU8(a1);
*alpha++ = SkToU8(a2);
*alpha++ = SkToU8(a3);
} while (--quads != 0);
}
SkASSERT(count < 0);
SkASSERT(count + kTempColorCount >= 0);
if (count += kTempColorCount) {
this->shadeSpan(x, y, colors, count);
const uint8_t* srcA = (const uint8_t*)colors + SkU32BitShiftToByteOffset(SK_A32_SHIFT);
do {
*alpha++ = *srcA;
srcA += 4;
} while (--count != 0);
}
#if 0
do {
int n = count;
if (n > kTempColorCount)
n = kTempColorCount;
SkASSERT(n > 0);
this->shadeSpan(x, y, colors, n);
x += n;
count -= n;
const uint8_t* srcA = (const uint8_t*)colors + SkU32BitShiftToByteOffset(SK_A32_SHIFT);
do {
*alpha++ = *srcA;
srcA += 4;
} while (--n != 0);
} while (count > 0);
#endif
}
SkShader::MatrixClass SkShader::ComputeMatrixClass(const SkMatrix& mat) {
MatrixClass mc = kLinear_MatrixClass;
if (mat.getType() & SkMatrix::kPerspective_Mask) {
if (mat.fixedStepInX(0, NULL, NULL)) {
mc = kFixedStepInX_MatrixClass;
} else {
mc = kPerspective_MatrixClass;
}
}
return mc;
}
//////////////////////////////////////////////////////////////////////////////
bool SkShader::asABitmap(SkBitmap*, SkMatrix*, TileMode*) {
return false;
}
SkShader* SkShader::CreateBitmapShader(const SkBitmap& src,
TileMode tmx, TileMode tmy) {
return SkShader::CreateBitmapShader(src, tmx, tmy, NULL, 0);
}
//////////////////////////////////////////////////////////////////////////////
#include "SkColorShader.h"
#include "SkUtils.h"
SkColorShader::SkColorShader(SkFlattenableReadBuffer& b) : INHERITED(b) {
fFlags = 0; // computed in setContext
fInheritColor = b.readU8();
if (fInheritColor) {
return;
}
fColor = b.readU32();
}
void SkColorShader::flatten(SkFlattenableWriteBuffer& buffer) {
this->INHERITED::flatten(buffer);
buffer.write8(fInheritColor);
if (fInheritColor) {
return;
}
buffer.write32(fColor);
}
uint8_t SkColorShader::getSpan16Alpha() const {
return SkGetPackedA32(fPMColor);
}
bool SkColorShader::setContext(const SkBitmap& device, const SkPaint& paint,
const SkMatrix& matrix) {
if (!this->INHERITED::setContext(device, paint, matrix)) {
return false;
}
SkColor c;
unsigned a;
if (fInheritColor) {
c = paint.getColor();
a = SkColorGetA(c);
} else {
c = fColor;
a = SkAlphaMul(SkColorGetA(c), SkAlpha255To256(paint.getAlpha()));
}
unsigned r = SkColorGetR(c);
unsigned g = SkColorGetG(c);
unsigned b = SkColorGetB(c);
// we want this before we apply any alpha
fColor16 = SkPack888ToRGB16(r, g, b);
if (a != 255) {
r = SkMulDiv255Round(r, a);
g = SkMulDiv255Round(g, a);
b = SkMulDiv255Round(b, a);
}
fPMColor = SkPackARGB32(a, r, g, b);
fFlags = kConstInY32_Flag;
if (paint.isDither() == false) {
fFlags |= kHasSpan16_Flag;
}
if (SkGetPackedA32(fPMColor) == 255) {
fFlags |= kOpaqueAlpha_Flag;
}
return true;
}
void SkColorShader::shadeSpan(int x, int y, SkPMColor span[], int count) {
sk_memset32(span, fPMColor, count);
}
void SkColorShader::shadeSpan16(int x, int y, uint16_t span[], int count) {
sk_memset16(span, fColor16, count);
}
void SkColorShader::shadeSpanAlpha(int x, int y, uint8_t alpha[], int count) {
memset(alpha, SkGetPackedA32(fPMColor), count);
}
<commit_msg>only report hasspan16 if we're opaque, otherwise we get a different blend via 565 than the 8888 case<commit_after>/* libs/graphics/sgl/SkShader.cpp
**
** Copyright 2006, The Android Open Source Project
**
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
#include "SkShader.h"
#include "SkPaint.h"
SkShader::SkShader() : fLocalMatrix(NULL) {
SkDEBUGCODE(fInSession = false;)
}
SkShader::SkShader(SkFlattenableReadBuffer& buffer)
: INHERITED(buffer), fLocalMatrix(NULL) {
if (buffer.readBool()) {
SkMatrix matrix;
buffer.read(&matrix, sizeof(matrix));
setLocalMatrix(matrix);
}
SkDEBUGCODE(fInSession = false;)
}
SkShader::~SkShader() {
SkASSERT(!fInSession);
sk_free(fLocalMatrix);
}
void SkShader::beginSession() {
SkASSERT(!fInSession);
SkDEBUGCODE(fInSession = true;)
}
void SkShader::endSession() {
SkASSERT(fInSession);
SkDEBUGCODE(fInSession = false;)
}
void SkShader::flatten(SkFlattenableWriteBuffer& buffer) {
this->INHERITED::flatten(buffer);
buffer.writeBool(fLocalMatrix != NULL);
if (fLocalMatrix) {
buffer.writeMul4(fLocalMatrix, sizeof(SkMatrix));
}
}
bool SkShader::getLocalMatrix(SkMatrix* localM) const {
if (fLocalMatrix) {
if (localM) {
*localM = *fLocalMatrix;
}
return true;
} else {
if (localM) {
localM->reset();
}
return false;
}
}
void SkShader::setLocalMatrix(const SkMatrix& localM) {
if (localM.isIdentity()) {
this->resetLocalMatrix();
} else {
if (fLocalMatrix == NULL) {
fLocalMatrix = (SkMatrix*)sk_malloc_throw(sizeof(SkMatrix));
}
*fLocalMatrix = localM;
}
}
void SkShader::resetLocalMatrix() {
if (fLocalMatrix) {
sk_free(fLocalMatrix);
fLocalMatrix = NULL;
}
}
bool SkShader::setContext(const SkBitmap& device,
const SkPaint& paint,
const SkMatrix& matrix) {
const SkMatrix* m = &matrix;
SkMatrix total;
fDeviceConfig = SkToU8(device.getConfig());
fPaintAlpha = paint.getAlpha();
if (fLocalMatrix) {
total.setConcat(matrix, *fLocalMatrix);
m = &total;
}
if (m->invert(&fTotalInverse)) {
fTotalInverseClass = (uint8_t)ComputeMatrixClass(fTotalInverse);
return true;
}
return false;
}
#include "SkColorPriv.h"
void SkShader::shadeSpan16(int x, int y, uint16_t span16[], int count) {
SkASSERT(span16);
SkASSERT(count > 0);
SkASSERT(this->canCallShadeSpan16());
// basically, if we get here, the subclass screwed up
SkASSERT(!"kHasSpan16 flag is set, but shadeSpan16() not implemented");
}
#define kTempColorQuadCount 6 // balance between speed (larger) and saving stack-space
#define kTempColorCount (kTempColorQuadCount << 2)
#ifdef SK_CPU_BENDIAN
#define SkU32BitShiftToByteOffset(shift) (3 - ((shift) >> 3))
#else
#define SkU32BitShiftToByteOffset(shift) ((shift) >> 3)
#endif
void SkShader::shadeSpanAlpha(int x, int y, uint8_t alpha[], int count) {
SkASSERT(count > 0);
SkPMColor colors[kTempColorCount];
while ((count -= kTempColorCount) >= 0) {
this->shadeSpan(x, y, colors, kTempColorCount);
x += kTempColorCount;
const uint8_t* srcA = (const uint8_t*)colors + SkU32BitShiftToByteOffset(SK_A32_SHIFT);
int quads = kTempColorQuadCount;
do {
U8CPU a0 = srcA[0];
U8CPU a1 = srcA[4];
U8CPU a2 = srcA[8];
U8CPU a3 = srcA[12];
srcA += 4*4;
*alpha++ = SkToU8(a0);
*alpha++ = SkToU8(a1);
*alpha++ = SkToU8(a2);
*alpha++ = SkToU8(a3);
} while (--quads != 0);
}
SkASSERT(count < 0);
SkASSERT(count + kTempColorCount >= 0);
if (count += kTempColorCount) {
this->shadeSpan(x, y, colors, count);
const uint8_t* srcA = (const uint8_t*)colors + SkU32BitShiftToByteOffset(SK_A32_SHIFT);
do {
*alpha++ = *srcA;
srcA += 4;
} while (--count != 0);
}
#if 0
do {
int n = count;
if (n > kTempColorCount)
n = kTempColorCount;
SkASSERT(n > 0);
this->shadeSpan(x, y, colors, n);
x += n;
count -= n;
const uint8_t* srcA = (const uint8_t*)colors + SkU32BitShiftToByteOffset(SK_A32_SHIFT);
do {
*alpha++ = *srcA;
srcA += 4;
} while (--n != 0);
} while (count > 0);
#endif
}
SkShader::MatrixClass SkShader::ComputeMatrixClass(const SkMatrix& mat) {
MatrixClass mc = kLinear_MatrixClass;
if (mat.getType() & SkMatrix::kPerspective_Mask) {
if (mat.fixedStepInX(0, NULL, NULL)) {
mc = kFixedStepInX_MatrixClass;
} else {
mc = kPerspective_MatrixClass;
}
}
return mc;
}
//////////////////////////////////////////////////////////////////////////////
bool SkShader::asABitmap(SkBitmap*, SkMatrix*, TileMode*) {
return false;
}
SkShader* SkShader::CreateBitmapShader(const SkBitmap& src,
TileMode tmx, TileMode tmy) {
return SkShader::CreateBitmapShader(src, tmx, tmy, NULL, 0);
}
//////////////////////////////////////////////////////////////////////////////
#include "SkColorShader.h"
#include "SkUtils.h"
SkColorShader::SkColorShader(SkFlattenableReadBuffer& b) : INHERITED(b) {
fFlags = 0; // computed in setContext
fInheritColor = b.readU8();
if (fInheritColor) {
return;
}
fColor = b.readU32();
}
void SkColorShader::flatten(SkFlattenableWriteBuffer& buffer) {
this->INHERITED::flatten(buffer);
buffer.write8(fInheritColor);
if (fInheritColor) {
return;
}
buffer.write32(fColor);
}
uint8_t SkColorShader::getSpan16Alpha() const {
return SkGetPackedA32(fPMColor);
}
bool SkColorShader::setContext(const SkBitmap& device, const SkPaint& paint,
const SkMatrix& matrix) {
if (!this->INHERITED::setContext(device, paint, matrix)) {
return false;
}
SkColor c;
unsigned a;
if (fInheritColor) {
c = paint.getColor();
a = SkColorGetA(c);
} else {
c = fColor;
a = SkAlphaMul(SkColorGetA(c), SkAlpha255To256(paint.getAlpha()));
}
unsigned r = SkColorGetR(c);
unsigned g = SkColorGetG(c);
unsigned b = SkColorGetB(c);
// we want this before we apply any alpha
fColor16 = SkPack888ToRGB16(r, g, b);
if (a != 255) {
r = SkMulDiv255Round(r, a);
g = SkMulDiv255Round(g, a);
b = SkMulDiv255Round(b, a);
}
fPMColor = SkPackARGB32(a, r, g, b);
fFlags = kConstInY32_Flag;
if (255 == a) {
fFlags |= kOpaqueAlpha_Flag;
if (paint.isDither() == false) {
fFlags |= kHasSpan16_Flag;
}
}
return true;
}
void SkColorShader::shadeSpan(int x, int y, SkPMColor span[], int count) {
sk_memset32(span, fPMColor, count);
}
void SkColorShader::shadeSpan16(int x, int y, uint16_t span[], int count) {
sk_memset16(span, fColor16, count);
}
void SkColorShader::shadeSpanAlpha(int x, int y, uint8_t alpha[], int count) {
memset(alpha, SkGetPackedA32(fPMColor), count);
}
<|endoftext|> |
<commit_before>#ifndef TOML_PARSE_VALUE
#define TOML_PARSE_VALUE
#include "definitions.hpp"
#include "toml_values.hpp"
namespace toml
{
// to test
template<typename charT, typename traits, typename alloc>
std::shared_ptr<value_base>
parse_value(const std::basic_string<charT, traits, alloc>& str)
{
return std::make_shared<typed_value<String>>(str);
}
}//toml
#endif /* TOML_PARSE_VALUE */
<commit_msg>enable parse_value to parse values except inline table<commit_after>#ifndef TOML_PARSE_VALUE
#define TOML_PARSE_VALUE
#include "definitions.hpp"
#include "toml_values.hpp"
#include "is.hpp"
#include <algorithm>
namespace toml
{
template<typename T, typename charT, typename traits, typename alloc>
struct parse_value_impl;
template<typename charT, typename traits, typename alloc>
std::shared_ptr<value_base>
parse_value(const std::basic_string<charT, traits, alloc>& str)
{
if(is<Boolean>(str))
return parse_value_impl<Boolean, charT, traits, alloc>::apply(str);
else if(is<Integer>(str))
return parse_value_impl<Integer, charT, traits, alloc>::apply(str);
else if(is<Float>(str))
return parse_value_impl<Float, charT, traits, alloc>::apply(str);
else if(is<String>(str))
return parse_value_impl<String, charT, traits, alloc>::apply(str);
else if(is<Datetime>(str))
return parse_value_impl<Datetime, charT, traits, alloc>::apply(str);
else if(is<array_type>(str))
return parse_value_impl<array_type, charT, traits, alloc>::apply(str);
else if(is<table_type>(str))
return parse_value_impl<table_type, charT, traits, alloc>::apply(str);
else
throw syntax_error<charT, traits, alloc>("unknown type " + str);
}
// ---------------------------- utility functions -----------------------------
// read string that length is s and return the string
template<typename charT, typename traits, typename alloc>
std::basic_string<charT, traits, alloc>
get_word(std::basic_istringstream<charT, traits, alloc>& iss, std::streamsize s)
{
std::basic_string<charT, traits, alloc> retval;
for(std::streamsize i=0; i<s; ++i)
retval += iss.get();
return retval;
}
// read continuous numbers from iss and return the string
template<typename charT, typename traits, typename alloc>
std::basic_string<charT, traits, alloc>
get_number(std::basic_istringstream<charT, traits, alloc>& iss)
{
std::basic_string<charT, traits, alloc> retval;
while(iss.eof())
{
char tmp = iss.peek();
if(tmp < '0' || '9' < tmp) retval += iss.get();
else break;
}
return retval;
}
// return iterator that points the brace that enclose the block.
// iter-> '['[1,2], [3,4], [5,6]']' <- retval
template<typename charT, typename traits, typename alloc>
typename std::basic_string<charT, traits, alloc>::const_iterator
next_close(typename std::basic_string<charT, traits, alloc>::const_iterator iter,
const typename std::basic_string<charT, traits, alloc>::const_iterator end,
const charT close)
{
const charT open = *iter;
int counter = 0;
while(iter != end)
{
if(*iter == open) ++counter;
else if(*iter == close) --counter;
if(counter == 0) break;
}
return iter;
}
// for """ and ''' case.
template<typename charT, typename traits, typename alloc>
typename std::basic_string<charT, traits, alloc>::const_iterator
next_close(typename std::basic_string<charT, traits, alloc>::const_iterator iter,
const typename std::basic_string<charT, traits, alloc>::const_iterator end,
const typename std::basic_string<charT, traits, alloc> close)
{
if(std::distance(iter, end) < close.size())
throw internal_error<charT, traits, alloc>("never close");
std::size_t len = close.size()-1;
while(iter + len != end)
{
if(std::basic_string<charT, traits, alloc>(iter, iter+len) == close)
return iter+len;
++iter;
}
return end;
}
// split array string into vector of element strings.
template<typename charT, typename traits, typename alloc>
std::vector<std::basic_string<charT, traits, alloc>>
split_array(const std::basic_string<charT, traits, alloc>& str)
{
using syntax_exception = syntax_error<charT, traits, alloc>;
auto iter = str.cbegin();
if(*iter != '[') throw syntax_exception(str);
++iter;
std::vector<std::basic_string<charT, traits, alloc>> splitted;
while(iter != str.cend())
{
if(*iter == '[')
{
auto close = next_close<charT, traits, alloc>(iter, str.cend(), ']');
if(close == str.cend()) throw syntax_exception(str);
splitted.emplace_back(iter, close+1);
iter = close + 1;
while(*iter == ' ' || *iter == '\t'){++iter;}
if(*iter != ',' && *iter != ']') throw syntax_exception(str);
++iter;
}
else if(*iter == '{')
{
auto close = next_close<charT, traits, alloc>(iter, str.cend(), '}');
if(close == str.cend()) throw syntax_exception(str);
splitted.emplace_back(iter, close+1);
iter = close + 1;
while(*iter == ' ' || *iter == '\t'){++iter;}
if(*iter != ',' && *iter != ']') throw syntax_exception(str);
++iter;
}
else if(*iter == '\'')
{
if(*(iter+1) == '\'' && *(iter+2) == '\'')
{
auto close = next_close<charT, traits, alloc>(iter+3, str.cend(),
std::basic_string<charT, traits, alloc>("\'\'\'"));
if(close == str.cend()) throw syntax_exception(str);
splitted.emplace_back(iter, close+1);
iter = close + 1;
while(*iter == ' ' || *iter == '\t'){++iter;}
if(*iter != ',' && *iter != ']') throw syntax_exception(str);
++iter;
}
else
{
auto close = std::find(iter+1, str.cend(), '\'');
if(close == str.cend()) throw syntax_exception(str);
splitted.emplace_back(iter, close+1);
iter = close + 1;
while(*iter == ' ' || *iter == '\t'){++iter;}
if(*iter != ',' && *iter != ']') throw syntax_exception(str);
++iter;
}
}
else if(*iter == '\"')
{
if(*(iter+1) == '\"' && *(iter+2) == '\"')
{
auto close = next_close<charT, traits, alloc>(iter+3, str.cend(),
std::basic_string<charT, traits, alloc>("\"\"\""));
if(close == str.cend()) throw syntax_exception(str);
splitted.emplace_back(iter, close+1);
iter = close + 1;
while(*iter == ' ' || *iter == '\t'){++iter;}
if(*iter != ',' && *iter != ']') throw syntax_exception(str);
++iter;
}
else
{
auto close = std::find(iter+1, str.cend(), '\"');
if(close == str.cend()) throw syntax_exception(str);
splitted.emplace_back(iter, close+1);
iter = close + 1;
while(*iter == ' ' || *iter == '\t'){++iter;}
if(*iter != ',' && *iter != ']') throw syntax_exception(str);
++iter;
}
}
else if(*iter == ']')
{
break;// other part passes only valid(closed) array string
}
else if(*iter == ' ')
{
++iter;
}
else
{
auto delim = std::find(iter, str.cend(), ',');
if(delim == str.cend())// [... , last-value]
splitted.emplace_back(iter, std::find(iter, str.cend(), ']'));
else
splitted.emplace_back(iter, delim);
splitted.back() = // remove needless whitespace
remove_extraneous_whitespace(remove_indent(splitted.back()));
iter = delim;
if(iter != str.cend()) ++iter;
}
}
return splitted;
}
// ---------------------------- implementation ---------------------------------
template<typename charT, typename traits, typename alloc>
struct parse_value_impl<Boolean, charT, traits, alloc>
{
static std::shared_ptr<value_base>
apply(const std::basic_string<charT, traits, alloc>& str)
{
std::shared_ptr<typed_value<Boolean>> val =
std::make_shared<typed_value<Boolean>>();
if(str == "true") val->value = true;
else if(str == "false") val->value = false;
else throw internal_error<charT, traits, alloc>("not boolean type" + str);
return val;
}
};
template<typename charT, typename traits, typename alloc>
struct parse_value_impl<Integer, charT, traits, alloc>
{
static std::shared_ptr<value_base>
apply(const std::basic_string<charT, traits, alloc>& str)
{
std::shared_ptr<typed_value<Integer>> val =
std::make_shared<typed_value<Integer>>();
try{val->value = std::stoll(remove(str, '_'));}
catch(std::exception& excpt)
{throw internal_error<charT, traits, alloc>("not Integer type" + str);}
return val;
}
};
template<typename charT, typename traits, typename alloc>
struct parse_value_impl<Float, charT, traits, alloc>
{
static std::shared_ptr<value_base>
apply(const std::basic_string<charT, traits, alloc>& str)
{
std::shared_ptr<typed_value<Float>> val =
std::make_shared<typed_value<Float>>();
try{val->value = std::stod(remove(str, '_'));}
catch(std::exception& excpt)
{throw internal_error<charT, traits, alloc>("not Float type" + str);}
return val;
}
};
template<typename charT, typename traits, typename alloc>
struct parse_value_impl<String, charT, traits, alloc>
{
static std::shared_ptr<value_base>
apply(const std::basic_string<charT, traits, alloc>& str)
{
std::shared_ptr<typed_value<String>> val =
std::make_shared<typed_value<String>>();
if(str.substr(0,3) == "\'\'\'" || str.substr(0,3) == "\"\"\"")
val->value = str.substr(3, str.size() - 6);
else if(str.front() == '\'' || str.front() == '\"')
val->value = str.substr(1, str.size() - 2);
else throw internal_error<charT, traits, alloc>("not String type" + str);
return val;
}
};
// this implementation is extremely complecated...
template<typename charT, typename traits, typename alloc>
struct parse_value_impl<Datetime, charT, traits, alloc>
{
static std::shared_ptr<value_base>
apply(const std::basic_string<charT, traits, alloc>& str)
{
typedef internal_error<charT, traits, alloc> internal_exception;
try{
// 1 2
// 012345678901234567890123
// patterns
// yyyy-mm-dd
// yyyy-mm-ddThh:mm:ss
// yyyy-mm-ddThh:mm:ssZ
// yyyy-mm-ddThh:mm:ss+09:00
// yyyy-mm-ddThh:mm:ss.sss
// yyyy-mm-ddThh:mm:ss.sssZ
// yyyy-mm-ddThh:mm:ss.sss+09:00
std::shared_ptr<typed_value<Datetime>> val =
std::make_shared<typed_value<Datetime>>();
std::basic_istringstream<charT, traits, alloc> iss(str);
std::tm t;
t.tm_year = std::stoi(get_word(iss, 4)) - 1900;// yyyy
if(iss.get() != '-') throw internal_exception("-");// -
t.tm_mon = std::stoi(get_word(iss, 2)) - 1; // mm
if(iss.get() != '-') throw internal_exception("-");// -
t.tm_mday = std::stoi(get_word(iss, 2)); // dd
if(iss.eof())
{
t.tm_sec = 0; t.tm_min = 0; t.tm_hour = 0;
val->value = std::chrono::system_clock::from_time_t(make_local(t));
return val;
}
if(iss.get() != 'T') throw internal_exception("T");// T
t.tm_hour = std::stoi(get_word(iss, 2)); // hh
if(iss.get() != ':') throw internal_exception(":");// :
t.tm_min = std::stoi(get_word(iss, 2)); // mm
if(iss.get() != ':') throw internal_exception(":");// :
t.tm_sec = std::stoi(get_word(iss, 2)); // ss
bool secfrac = false;
std::chrono::microseconds sfrac;
if(iss.peek() == '.')
{
secfrac = true;
std::basic_string<charT, traits, alloc> numf("0.");
numf += get_number(iss);
const double subsecond = std::stod(numf);
sfrac = std::chrono::microseconds(static_cast<int>(subsecond * 1000000));
}
if(iss.eof()) // LOCAL
{
val->value = std::chrono::system_clock::from_time_t(make_local(t));
if(secfrac) val->value += sfrac;
return val;
}
else if(iss.peek() == 'Z') //GMT
{
val->value = std::chrono::system_clock::from_time_t(make_global(t));
if(secfrac) val->value += sfrac;
return val;
}
else if(iss.peek() == '+' || iss.peek() == '-') //GMT + offset
{
val->value = std::chrono::system_clock::from_time_t(make_global(t));
if(secfrac) val->value += sfrac;
apply_offset(val, iss);
return val;
}
else
{
throw internal_error<charT, traits, alloc>("not datetime");
}
}//try
catch(std::exception& excpt)
{
throw internal_error<charT, traits, alloc>("cannot parse as Datetime " + str);
}
}
static std::time_t make_global(std::tm t)
{
return std::mktime(&t);
}
static std::time_t make_local(std::tm t)
{
const std::time_t gtime = std::mktime(&t);
return std::mktime(std::localtime(>ime));
}
static void apply_offset(std::shared_ptr<typed_value<Datetime>>& val,
std::basic_istringstream<charT, traits, alloc>& iss)
{
if(iss.get() == '+')
{
val->value += std::chrono::hours(std::stoi(get_word(iss, 2)));
if(iss.get() != ':') throw internal_error<charT, traits, alloc>(":");
val->value += std::chrono::minutes(std::stoi(get_word(iss, 2)));
}
else
{
val->value -= std::chrono::hours(std::stoi(get_word(iss, 2)));
if(iss.get() != ':') throw internal_error<charT, traits, alloc>(":");
val->value -= std::chrono::minutes(std::stoi(get_word(iss, 2)));
}
return;
}
};
template<typename charT, typename traits, typename alloc>
struct parse_value_impl<array_type, charT, traits, alloc>
{
static std::shared_ptr<value_base>
apply(const std::basic_string<charT, traits, alloc>& str)
{
std::shared_ptr<array_type> val = std::make_shared<array_type>();
std::vector<std::basic_string<charT, traits, alloc>> splitted =
split_array(str);
for(auto iter = splitted.cbegin(); iter != splitted.cend(); ++iter)
val->value.push_back(parse_value(*iter));
return val;
}
};
// TODO: parse inline table
template<typename charT, typename traits, typename alloc>
struct parse_value_impl<table_type, charT, traits, alloc>
{
static std::shared_ptr<value_base>
apply(const std::basic_string<charT, traits, alloc>& str)
{
std::shared_ptr<table_type> val = std::make_shared<table_type>();
// std::vector<std::basic_string<charT, traits, alloc>> splitted =
// split_array(str);
// for(auto iter = splitted.cbegin(); iter != splitted.cend(); ++iter)
// val->value.push_back(parse_value(*iter));
return val;
}
};
}//toml
#endif /* TOML_PARSE_VALUE */
<|endoftext|> |
<commit_before>/* Copyright © 2001-2014, Canal TP and/or its affiliates. All rights reserved.
This file is part of Navitia,
the software to build cool stuff with public transport.
Hope you'll enjoy and contribute to this project,
powered by Canal TP (www.canaltp.fr).
Help us simplify mobility and open public transport:
a non ending quest to the responsive locomotion way of traveling!
LICENCE: This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Stay tuned using
twitter @navitia
channel `#navitia` on riot https://riot.im/app/#/room/#navitia:matrix.org
https://groups.google.com/d/forum/navitia
www.navitia.io
*/
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE data_test
// Boost
#include <boost/test/unit_test.hpp>
#include <boost/filesystem.hpp>
// Std
#include <string>
#include "utils/functions.h" // absolute_path function
// Data to test
#include "type/data.h"
using namespace navitia;
static const std::string fake_data_file = "fake_data.nav.lz4";
static const std::string fake_disruption_path = "fake_disruption_path";
BOOST_AUTO_TEST_CASE(load_data) {
navitia::type::Data data(0);
data.save(fake_data_file);
// load .nav
std::string fake_data_path = navitia::absolute_path() + fake_data_file;
bool failed = false;
BOOST_CHECK_EQUAL(data.last_load_succeeded, false);
try {
data.load_nav(fake_data_path);
} catch (const navitia::data::data_loading_error&) {
failed = true;
}
BOOST_CHECK_EQUAL(failed, false);
BOOST_CHECK_EQUAL(data.last_load_succeeded, true);
try {
data.load_nav("wrong_path");
} catch (const navitia::data::data_loading_error&) {
failed = true;
}
BOOST_CHECK_EQUAL(failed, true);
BOOST_CHECK_EQUAL(data.last_load_succeeded, true);
// Clean fake file
boost::filesystem::remove(fake_data_path);
}
BOOST_AUTO_TEST_CASE(load_disruptions_fail) {
navitia::type::Data data(0);
// load disruptions
bool failed = false;
try {
data.load_disruptions(fake_disruption_path);
} catch (const navitia::data::disruptions_broken_connection&) {
failed = true;
}
BOOST_CHECK_EQUAL(failed, true);
}
<commit_msg>fix test<commit_after>/* Copyright © 2001-2014, Canal TP and/or its affiliates. All rights reserved.
This file is part of Navitia,
the software to build cool stuff with public transport.
Hope you'll enjoy and contribute to this project,
powered by Canal TP (www.canaltp.fr).
Help us simplify mobility and open public transport:
a non ending quest to the responsive locomotion way of traveling!
LICENCE: This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Stay tuned using
twitter @navitia
channel `#navitia` on riot https://riot.im/app/#/room/#navitia:matrix.org
https://groups.google.com/d/forum/navitia
www.navitia.io
*/
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE data_test
// Boost
#include <boost/test/unit_test.hpp>
#include <boost/filesystem.hpp>
// Std
#include <string>
#include "utils/functions.h" // absolute_path function
// Data to test
#include "type/data.h"
using namespace navitia;
static const std::string fake_data_file = "fake_data.nav.lz4";
static const std::string fake_disruption_path = "fake_disruption_path";
BOOST_AUTO_TEST_CASE(load_data) {
navitia::type::Data data(0);
data.save(fake_data_file);
// load .nav
std::string fake_data_path = navitia::absolute_path() + fake_data_file;
bool failed = false;
BOOST_CHECK_EQUAL(data.last_load_succeeded, false);
try {
data.load_nav(fake_data_path);
} catch (const navitia::data::data_loading_error&) {
failed = true;
}
BOOST_CHECK_EQUAL(failed, false);
BOOST_CHECK_EQUAL(data.last_load_succeeded, true);
try {
data.load_nav("wrong_path");
} catch (const navitia::data::data_loading_error&) {
failed = true;
}
BOOST_CHECK_EQUAL(failed, true);
BOOST_CHECK_EQUAL(data.last_load_succeeded, true);
// Clean fake file
boost::filesystem::remove(fake_data_path);
}
BOOST_AUTO_TEST_CASE(load_disruptions_fail) {
navitia::type::Data data(0);
// load disruptions
bool failed = false;
try {
data.load_disruptions(fake_disruption_path, 1000);
} catch (const navitia::data::disruptions_broken_connection&) {
failed = true;
}
BOOST_CHECK_EQUAL(failed, true);
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <fstream>
#include <memory>
#include <boost/algorithm/string.hpp>
using namespace std;
/* Becasue I want to use OpenMP,
* So I must use vector as the container for paras, because openmp require random access iterator.
* And must use list as the container for results, because vector need to relocate, and therefore not thread-safe.
*/
// type define
typedef array<double, 3> Row;
typedef shared_ptr< list<Row> > RowList;
typedef array<double, 3> Para;
typedef shared_ptr< vector<Para> > ParaList;
typedef pair<Para, int> Score;
// function defines
RowList readFile(const string& fileName);
int sign(const Row& row, const Para& para);
int errors(const Para& para);
int predictErrors(const Para& para);
Para patch(const Para& para, const Row& row);
ParaList analysys(const Para& para);
Score deepin(const int now, const Para& para, const int limit);
// overloading define
ostream &operator<<(ostream& out, const Para& para) {
out << "[" << para[0] << ", " << para[1] << ", " << para[2] << "]";
return out;
}
ostream &operator<<(ostream& out, const Score& score) {
out << "<" << score.first << ", " << score.second << ">";
return out;
}
// preset data defines
Para initPara = {0, 0, 0};
auto trainFileContent = readFile("train_1_5.csv");
auto testFileContent = readFile("test_1_5.csv");
// main
int main(void) {
Score trainResult = deepin(0, initPara, 2);
int predictionError = predictErrors(trainResult.first);
cout << "Train Result: " << trainResult << endl;
cout << "Prediction Error: " << predictionError << endl;
}
// function implementation
RowList readFile(const string& fileName) {
ifstream inFile(fileName);
string line;
vector<string> words;
Row nums;
RowList fileContent = static_cast<RowList>(new list<Row>);
while(getline(inFile, line)){
boost::split(words, line, boost::is_any_of(","));
nums = {
stod(words[0]),
stod(words[1]),
stod(words[2])
};
fileContent->push_back(nums);
}
return fileContent;
}
inline int sign(const Row& row, const Para& para) {
double result = para[0] * row[0] + para[1] * row[1] + para[2];
if(result >= 0){
return 1;
} else{
return -1;
}
}
int errors(const Para& para) {
int sum = 0;
for(auto it = trainFileContent->begin(); it != trainFileContent->end(); it++){
Row& row = *it;
if(sign(row, para) != row[2]){
sum++;
}
}
return sum;
}
int predictErrors(const Para& para) {
int sum = 0;
for(auto it = testFileContent->begin(); it != testFileContent->end(); it++){
Row& row = *it;
if(sign(row, para) != row[2]){
sum++;
}
}
return sum;
}
Para patch(const Para& para, const Row& row) {
Para tryPara = {
para[0] + row[2] * row[0],
para[1] + row[2] * row[1],
para[2] + row[2]
};
return tryPara;
}
ParaList analysys(const Para& para) {
ParaList candidatePara = static_cast<ParaList>(new vector<Para>);
for(auto it = trainFileContent->begin(); it != trainFileContent->end(); it++){
Row& row = *it;
if(sign(row, para) != row[2]){
candidatePara->push_back(patch(para, row));
}
}
return candidatePara;
}
/* @parameter: init para
* @return: the best para among the child and sub-child para created by this para.
*/
Score deepin(const int now, const Para& para, const int limit) {
list<Score> thisResult;
thisResult.push_back(Score(para, errors(para)));
if(now < limit){
auto tryParas = *analysys(para);
const unsigned int size = tryParas.size();
#pragma omp parallel for
for(unsigned int i = 0; i < size; i++){
Para& childPara = tryParas[i];
thisResult.push_back(deepin(now+1, childPara, limit));
if(now == 0){
cout << "No: " << i << ", Score: " << *thisResult.rbegin() << endl;
}
}
} else{
auto tryParas = *analysys(para);
const unsigned int size = tryParas.size();
#pragma omp parallel for
for(unsigned int i = 0; i < size; i++){
Para& subPara = tryParas[i];
thisResult.push_back(Score(subPara, errors(subPara)));
}
}
Para bestPara = thisResult.begin()->first;
int bestError = thisResult.begin()->second;
for(auto it = thisResult.begin(); it != thisResult.end(); it++){
if(it->second < bestError){
bestPara = it->first;
bestError = it->second;
}
}
return(Score(bestPara, bestError));
}<commit_msg>OMP_NESTED is disable by default, internal parallel regin won't work and shouldn't work<commit_after>#include <iostream>
#include <fstream>
#include <memory>
#include <boost/algorithm/string.hpp>
using namespace std;
/* Becasue I want to use OpenMP,
* So I must use vector as the container for paras, because openmp require random access iterator.
* And must use list as the container for results, because vector need to relocate, and therefore not thread-safe.
*/
// type define
typedef array<double, 3> Row;
typedef shared_ptr< list<Row> > RowList;
typedef array<double, 3> Para;
typedef shared_ptr< vector<Para> > ParaList;
typedef pair<Para, int> Score;
// function defines
RowList readFile(const string& fileName);
int sign(const Row& row, const Para& para);
int errors(const Para& para);
int predictErrors(const Para& para);
Para patch(const Para& para, const Row& row);
ParaList analysys(const Para& para);
Score deepin(const int now, const Para& para, const int limit);
// overloading define
ostream &operator<<(ostream& out, const Para& para) {
out << "[" << para[0] << ", " << para[1] << ", " << para[2] << "]";
return out;
}
ostream &operator<<(ostream& out, const Score& score) {
out << "<" << score.first << ", " << score.second << ">";
return out;
}
// preset data defines
Para initPara = {0, 0, 0};
auto trainFileContent = readFile("train_1_5.csv");
auto testFileContent = readFile("test_1_5.csv");
// main
int main(void) {
Score trainResult = deepin(0, initPara, 2);
int predictionError = predictErrors(trainResult.first);
cout << "Train Result: " << trainResult << endl;
cout << "Prediction Error: " << predictionError << endl;
}
// function implementation
RowList readFile(const string& fileName) {
ifstream inFile(fileName);
string line;
vector<string> words;
Row nums;
RowList fileContent = static_cast<RowList>(new list<Row>);
while(getline(inFile, line)){
boost::split(words, line, boost::is_any_of(","));
nums = {
stod(words[0]),
stod(words[1]),
stod(words[2])
};
fileContent->push_back(nums);
}
return fileContent;
}
inline int sign(const Row& row, const Para& para) {
double result = para[0] * row[0] + para[1] * row[1] + para[2];
if(result >= 0){
return 1;
} else{
return -1;
}
}
int errors(const Para& para) {
int sum = 0;
for(auto it = trainFileContent->begin(); it != trainFileContent->end(); it++){
Row& row = *it;
if(sign(row, para) != row[2]){
sum++;
}
}
return sum;
}
int predictErrors(const Para& para) {
int sum = 0;
for(auto it = testFileContent->begin(); it != testFileContent->end(); it++){
Row& row = *it;
if(sign(row, para) != row[2]){
sum++;
}
}
return sum;
}
Para patch(const Para& para, const Row& row) {
Para tryPara = {
para[0] + row[2] * row[0],
para[1] + row[2] * row[1],
para[2] + row[2]
};
return tryPara;
}
ParaList analysys(const Para& para) {
ParaList candidatePara = static_cast<ParaList>(new vector<Para>);
for(auto it = trainFileContent->begin(); it != trainFileContent->end(); it++){
Row& row = *it;
if(sign(row, para) != row[2]){
candidatePara->push_back(patch(para, row));
}
}
return candidatePara;
}
/* @parameter: init para
* @return: the best para among the child and sub-child para created by this para.
*/
Score deepin(const int now, const Para& para, const int limit) {
list<Score> thisResult;
thisResult.push_back(Score(para, errors(para)));
if(now < limit){
auto tryParas = *analysys(para);
const unsigned int size = tryParas.size();
#pragma omp parallel for
for(unsigned int i = 0; i < size; i++){
Para& childPara = tryParas[i];
thisResult.push_back(deepin(now+1, childPara, limit));
if(now == 0){
cout << "No: " << i << ", Score: " << *thisResult.rbegin() << endl;
}
}
} else{
auto tryParas = *analysys(para);
const unsigned int size = tryParas.size();
for(unsigned int i = 0; i < size; i++){
Para& subPara = tryParas[i];
thisResult.push_back(Score(subPara, errors(subPara)));
}
}
Para bestPara = thisResult.begin()->first;
int bestError = thisResult.begin()->second;
for(auto it = thisResult.begin(); it != thisResult.end(); it++){
if(it->second < bestError){
bestPara = it->first;
bestError = it->second;
}
}
return(Score(bestPara, bestError));
}<|endoftext|> |
<commit_before>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
// Includes
#include "otbVectorImage.h"
#include "otbImageFileReader.h"
#include "otbImageFileWriter.h"
#include "otbMultiToMonoChannelExtractROI.h"
#include "otbGenericRSResampleImageFilter.h"
#include "otbGridResampleImageFilter.h"
#include "otbImportGeoInformationImageFilter.h"
#include "otbBCOInterpolateImageFunction.h"
#include "otbSimpleRcsPanSharpeningFusionImageFilter.h"
#include "itkFixedArray.h"
// Elevation handler
//#include "otbWrapperElevationParametersHandler.h"
#include "otbPleiadesPToXSAffineTransformCalculator.h"
#include "otbMPIConfig.h"
#include <cstdlib>
#include <iostream>
#include <boost/chrono/thread_clock.hpp>
// Test
int otbMPIBundleToPerfectSensorTest(int argc, char* argv[])
{
// Mono-thread execution
itk::MultiThreader::SetGlobalMaximumNumberOfThreads(1);
itk::MultiThreader::SetGlobalDefaultNumberOfThreads(1);
// Start chrono
boost::chrono::thread_clock::time_point startTimer = boost::chrono::thread_clock::now();
// MPI Initialization
typedef otb::mpi::MPIConfig MPIConfigType;
MPIConfigType::Pointer config = MPIConfigType::New();
config->Init(argc,argv,true);
// Verify the number of parameters in the command line
if (argc != 4)
{
std::stringstream message;
message << "Usage: " << std::endl;
message << argv[0] << " PANInputImageFile XSInputImageFile OutputImageFile " << std::endl;
config->logError(message.str());
config->abort(EXIT_FAILURE);
}
// Image types
typedef float FloatPixelType;
const unsigned int Dimension = 2;
typedef otb::VectorImage<FloatPixelType,Dimension> FloatVectorImageType;
// Reader
typedef otb::ImageFileReader<FloatVectorImageType> ReaderType;
// PAN Reader
ReaderType::Pointer panReader = ReaderType::New();
// PAN Reader configuration
std::string panInputFilename = std::string(argv[1]);
panReader->SetFileName(panInputFilename);
FloatVectorImageType* panchroV = panReader->GetOutput();
panReader->UpdateOutputInformation();
if ( panchroV->GetNumberOfComponentsPerPixel() != 1 )
{
config->logError("The panchromatic image must be a single channel image");
config->abort(EXIT_FAILURE);
}
// XS Reader
ReaderType::Pointer xsReader = ReaderType::New();
// XS Reader configuration
std::string xsInputFilename = std::string(argv[2]);
xsReader->SetFileName(xsInputFilename);
FloatVectorImageType* xs = xsReader->GetOutput();
xsReader->UpdateOutputInformation();
// Transform the PAN image to otb::Image
typedef otb::Image<FloatVectorImageType::InternalPixelType> InternalImageType;
typedef otb::MultiToMonoChannelExtractROI<float,float> ExtractFilterType;
ExtractFilterType::Pointer channelSelect = ExtractFilterType::New();
channelSelect->SetChannel(1);
channelSelect->SetInput(panchroV);
channelSelect->UpdateOutputInformation();
InternalImageType::Pointer panchro = channelSelect->GetOutput();
typedef otb::BCOInterpolateImageFunction<FloatVectorImageType> InterpolatorType;
typedef otb::GenericRSResampleImageFilter<FloatVectorImageType, FloatVectorImageType> ResamplerType;
typedef otb::GridResampleImageFilter<FloatVectorImageType, FloatVectorImageType> BasicResamplerType;
typedef otb::ImportGeoInformationImageFilter<FloatVectorImageType,InternalImageType> ImportGeoInformationFilterType;
typedef otb::SimpleRcsPanSharpeningFusionImageFilter<InternalImageType, FloatVectorImageType, FloatVectorImageType> FusionFilterType;
// Resample filter
ResamplerType::Pointer resampler = ResamplerType::New();
BasicResamplerType::Pointer basicResampler = BasicResamplerType::New();
ImportGeoInformationFilterType::Pointer geoImport = ImportGeoInformationFilterType::New();
InterpolatorType::Pointer interpolator = InterpolatorType::New();
resampler->SetInterpolator(interpolator);
basicResampler->SetInterpolator(interpolator);
// Fusion filter
FusionFilterType::Pointer fusionFilter = FusionFilterType::New();
fusionFilter->SetPanInput(panchro);
// Setup the DEM Handler
//otb::Wrapper::ElevationParametersHandler::SetupDEMHandlerFromElevationParameters(this,"elev");
// Set up output image information
FloatVectorImageType::SpacingType spacing = panchro->GetSpacing();
FloatVectorImageType::IndexType start = panchro->GetLargestPossibleRegion().GetIndex();
FloatVectorImageType::SizeType size = panchro->GetLargestPossibleRegion().GetSize();
FloatVectorImageType::PointType origin = panchro->GetOrigin();
FloatVectorImageType::PixelType defaultValue;
itk::NumericTraits<FloatVectorImageType::PixelType>::SetLength(defaultValue, xs->GetNumberOfComponentsPerPixel());
otb::PleiadesPToXSAffineTransformCalculator::TransformType::OffsetType offset
= otb::PleiadesPToXSAffineTransformCalculator::ComputeOffset(panchroV,xs);
origin+=offset;
origin[0]=origin[0]/4;
origin[1]=origin[1]/4;
basicResampler->SetOutputOrigin(origin);
basicResampler->SetInput(xs);
basicResampler->SetOutputOrigin(origin);
FloatVectorImageType::SpacingType xsSpacing = xs->GetSpacing();
xsSpacing*=0.25;
basicResampler->SetOutputSpacing(xsSpacing);
basicResampler->SetOutputSize(size);
basicResampler->SetOutputStartIndex(start);
basicResampler->SetEdgePaddingValue(defaultValue);
geoImport->SetInput(basicResampler->GetOutput());
geoImport->SetSource(panchro);
fusionFilter->SetXsInput(geoImport->GetOutput());
// Update MPI Pipeline
std::string outputFilename = std::string(argv[3]);
config->UpdateMPI(fusionFilter->GetOutput(),outputFilename, false, true);
// End chrono
boost::chrono::thread_clock::time_point stopTimer = boost::chrono::thread_clock::now();
std::stringstream message;
message << "Duration = " << boost::chrono::duration_cast<boost::chrono::milliseconds>(stopTimer-startTimer).count() <<" ms\n";
config->logInfo(message.str());
return EXIT_SUCCESS;
}
<commit_msg>Add try/catch to compute offset<commit_after>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
// Includes
#include "otbVectorImage.h"
#include "otbImageFileReader.h"
#include "otbImageFileWriter.h"
#include "otbMultiToMonoChannelExtractROI.h"
#include "otbGenericRSResampleImageFilter.h"
#include "otbGridResampleImageFilter.h"
#include "otbImportGeoInformationImageFilter.h"
#include "otbBCOInterpolateImageFunction.h"
#include "otbSimpleRcsPanSharpeningFusionImageFilter.h"
#include "itkFixedArray.h"
// Elevation handler
//#include "otbWrapperElevationParametersHandler.h"
#include "otbPleiadesPToXSAffineTransformCalculator.h"
#include "otbMPIConfig.h"
#include <cstdlib>
#include <iostream>
#include <boost/chrono/thread_clock.hpp>
// Test
int otbMPIBundleToPerfectSensorTest(int argc, char* argv[])
{
// Mono-thread execution
itk::MultiThreader::SetGlobalMaximumNumberOfThreads(1);
itk::MultiThreader::SetGlobalDefaultNumberOfThreads(1);
// Start chrono
boost::chrono::thread_clock::time_point startTimer = boost::chrono::thread_clock::now();
// MPI Initialization
typedef otb::mpi::MPIConfig MPIConfigType;
MPIConfigType::Pointer config = MPIConfigType::New();
config->Init(argc,argv,true);
// Verify the number of parameters in the command line
if (argc != 4)
{
std::stringstream message;
message << "Usage: " << std::endl;
message << argv[0] << " PANInputImageFile XSInputImageFile OutputImageFile " << std::endl;
config->logError(message.str());
config->abort(EXIT_FAILURE);
}
// Image types
typedef float FloatPixelType;
const unsigned int Dimension = 2;
typedef otb::VectorImage<FloatPixelType,Dimension> FloatVectorImageType;
// Reader
typedef otb::ImageFileReader<FloatVectorImageType> ReaderType;
// PAN Reader
ReaderType::Pointer panReader = ReaderType::New();
// PAN Reader configuration
std::string panInputFilename = std::string(argv[1]);
panReader->SetFileName(panInputFilename);
FloatVectorImageType* panchroV = panReader->GetOutput();
panReader->UpdateOutputInformation();
if ( panchroV->GetNumberOfComponentsPerPixel() != 1 )
{
config->logError("The panchromatic image must be a single channel image");
config->abort(EXIT_FAILURE);
}
// XS Reader
ReaderType::Pointer xsReader = ReaderType::New();
// XS Reader configuration
std::string xsInputFilename = std::string(argv[2]);
xsReader->SetFileName(xsInputFilename);
FloatVectorImageType* xs = xsReader->GetOutput();
xsReader->UpdateOutputInformation();
// Transform the PAN image to otb::Image
typedef otb::Image<FloatVectorImageType::InternalPixelType> InternalImageType;
typedef otb::MultiToMonoChannelExtractROI<float,float> ExtractFilterType;
ExtractFilterType::Pointer channelSelect = ExtractFilterType::New();
channelSelect->SetChannel(1);
channelSelect->SetInput(panchroV);
InternalImageType::Pointer panchro = channelSelect->GetOutput();
channelSelect->UpdateOutputInformation();
typedef otb::BCOInterpolateImageFunction<FloatVectorImageType> InterpolatorType;
typedef otb::GenericRSResampleImageFilter<FloatVectorImageType, FloatVectorImageType> ResamplerType;
typedef otb::GridResampleImageFilter<FloatVectorImageType, FloatVectorImageType> BasicResamplerType;
typedef otb::ImportGeoInformationImageFilter<FloatVectorImageType,InternalImageType> ImportGeoInformationFilterType;
typedef otb::SimpleRcsPanSharpeningFusionImageFilter<InternalImageType, FloatVectorImageType, FloatVectorImageType> FusionFilterType;
// Resample filter
ResamplerType::Pointer resampler = ResamplerType::New();
BasicResamplerType::Pointer basicResampler = BasicResamplerType::New();
ImportGeoInformationFilterType::Pointer geoImport = ImportGeoInformationFilterType::New();
InterpolatorType::Pointer interpolator = InterpolatorType::New();
resampler->SetInterpolator(interpolator);
basicResampler->SetInterpolator(interpolator);
// Fusion filter
FusionFilterType::Pointer fusionFilter = FusionFilterType::New();
fusionFilter->SetPanInput(panchro);
// Setup the DEM Handler
//otb::Wrapper::ElevationParametersHandler::SetupDEMHandlerFromElevationParameters(this,"elev");
// Set up output image information
FloatVectorImageType::SpacingType spacing = panchro->GetSpacing();
FloatVectorImageType::IndexType start = panchro->GetLargestPossibleRegion().GetIndex();
FloatVectorImageType::SizeType size = panchro->GetLargestPossibleRegion().GetSize();
FloatVectorImageType::PointType origin = panchro->GetOrigin();
FloatVectorImageType::PixelType defaultValue;
itk::NumericTraits<FloatVectorImageType::PixelType>::SetLength(defaultValue, xs->GetNumberOfComponentsPerPixel());
otb::PleiadesPToXSAffineTransformCalculator::TransformType::OffsetType offset;
try
{
offset = otb::PleiadesPToXSAffineTransformCalculator::ComputeOffset(panchroV,xs);
}
catch (itk::ExceptionObject& err)
{
std::stringstream message;
message << "ExceptionObject caught: " << err << std::endl;
config->logError(message.str());
config->abort(EXIT_FAILURE);
}
origin+=offset;
origin[0]=origin[0]/4;
origin[1]=origin[1]/4;
basicResampler->SetOutputOrigin(origin);
basicResampler->SetInput(xs);
basicResampler->SetOutputOrigin(origin);
FloatVectorImageType::SpacingType xsSpacing = xs->GetSpacing();
xsSpacing*=0.25;
basicResampler->SetOutputSpacing(xsSpacing);
basicResampler->SetOutputSize(size);
basicResampler->SetOutputStartIndex(start);
basicResampler->SetEdgePaddingValue(defaultValue);
geoImport->SetInput(basicResampler->GetOutput());
geoImport->SetSource(panchro);
fusionFilter->SetXsInput(geoImport->GetOutput());
// Update MPI Pipeline
std::string outputFilename = std::string(argv[3]);
config->UpdateMPI(fusionFilter->GetOutput(),outputFilename, false, true);
// End chrono
boost::chrono::thread_clock::time_point stopTimer = boost::chrono::thread_clock::now();
std::stringstream message;
message << "Duration = " << boost::chrono::duration_cast<boost::chrono::milliseconds>(stopTimer-startTimer).count() <<" ms\n";
config->logInfo(message.str());
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>/*************************************************
* PBE Retrieval Source File *
* (C) 1999-2007 Jack Lloyd *
*************************************************/
#include <botan/get_pbe.h>
#include <botan/oids.h>
#include <botan/parsing.h>
#if defined(BOTAN_HAS_PBE_PKCS_V15)
#include <botan/pbes1.h>
#endif
#if defined(BOTAN_HAS_PBE_PKCS_V20)
#include <botan/pbes2.h>
#endif
namespace Botan {
/*************************************************
* Get an encryption PBE, set new parameters *
*************************************************/
PBE* get_pbe(const std::string& pbe_name)
{
std::vector<std::string> algo_name;
algo_name = parse_algorithm_name(pbe_name);
if(algo_name.size() != 3)
throw Invalid_Algorithm_Name(pbe_name);
const std::string pbe = algo_name[0];
const std::string digest = algo_name[1];
const std::string cipher = algo_name[2];
PBE* pbe_obj = 0;
#if defined(BOTAN_HAS_PBE_PKCS_V15)
if(!pbe_obj && pbe == "PBE-PKCS5v15")
pbe_obj = new PBE_PKCS5v15(digest, cipher, ENCRYPTION);
#endif
#if defined(BOTAN_HAS_PBE_PKCS_V20)
if(!pbe_obj && pbe == "PBE-PKCS5v20")
pbe_obj = new PBE_PKCS5v20(digest, cipher);
#endif
if(!pbe_obj)
throw Algorithm_Not_Found(pbe_name);
return pbe_obj;
}
/*************************************************
* Get a decryption PBE, decode parameters *
*************************************************/
PBE* get_pbe(const OID& pbe_oid, DataSource& params)
{
std::vector<std::string> algo_name;
algo_name = parse_algorithm_name(OIDS::lookup(pbe_oid));
if(algo_name.size() < 1)
throw Invalid_Algorithm_Name(pbe_oid.as_string());
const std::string pbe_algo = algo_name[0];
if(pbe_algo == "PBE-PKCS5v15")
{
#if defined(BOTAN_HAS_PBE_PKCS_V15)
if(algo_name.size() != 3)
throw Invalid_Algorithm_Name(pbe_oid.as_string());
const std::string digest = algo_name[1];
const std::string cipher = algo_name[2];
PBE* pbe = new PBE_PKCS5v15(digest, cipher, DECRYPTION);
pbe->decode_params(params);
return pbe;
#endif
}
else if(pbe_algo == "PBE-PKCS5v20")
{
#if defined(BOTAN_HAS_PBE_PKCS_V20)
return new PBE_PKCS5v20(params);
#endif
}
throw Algorithm_Not_Found(pbe_oid.as_string());
}
}
<commit_msg>Make two variants of get_pbe more consistent<commit_after>/*************************************************
* PBE Retrieval Source File *
* (C) 1999-2007 Jack Lloyd *
*************************************************/
#include <botan/get_pbe.h>
#include <botan/oids.h>
#include <botan/parsing.h>
#if defined(BOTAN_HAS_PBE_PKCS_V15)
#include <botan/pbes1.h>
#endif
#if defined(BOTAN_HAS_PBE_PKCS_V20)
#include <botan/pbes2.h>
#endif
namespace Botan {
/*************************************************
* Get an encryption PBE, set new parameters *
*************************************************/
PBE* get_pbe(const std::string& pbe_name)
{
std::vector<std::string> algo_name;
algo_name = parse_algorithm_name(pbe_name);
if(algo_name.size() != 3)
throw Invalid_Algorithm_Name(pbe_name);
const std::string pbe = algo_name[0];
const std::string digest = algo_name[1];
const std::string cipher = algo_name[2];
PBE* pbe_obj = 0;
#if defined(BOTAN_HAS_PBE_PKCS_V15)
if(pbe == "PBE-PKCS5v15")
return new PBE_PKCS5v15(digest, cipher, ENCRYPTION);
#endif
#if defined(BOTAN_HAS_PBE_PKCS_V20)
if(pbe == "PBE-PKCS5v20")
return new PBE_PKCS5v20(digest, cipher);
#endif
throw Algorithm_Not_Found(pbe_name);
}
/*************************************************
* Get a decryption PBE, decode parameters *
*************************************************/
PBE* get_pbe(const OID& pbe_oid, DataSource& params)
{
std::vector<std::string> algo_name;
algo_name = parse_algorithm_name(OIDS::lookup(pbe_oid));
if(algo_name.size() < 1)
throw Invalid_Algorithm_Name(pbe_oid.as_string());
const std::string pbe_algo = algo_name[0];
#if defined(BOTAN_HAS_PBE_PKCS_V15)
if(pbe_algo == "PBE-PKCS5v15")
{
if(algo_name.size() != 3)
throw Invalid_Algorithm_Name(pbe_oid.as_string());
const std::string digest = algo_name[1];
const std::string cipher = algo_name[2];
PBE* pbe = new PBE_PKCS5v15(digest, cipher, DECRYPTION);
pbe->decode_params(params);
return pbe;
}
#endif
#if defined(BOTAN_HAS_PBE_PKCS_V20)
if(pbe_algo == "PBE-PKCS5v20")
return new PBE_PKCS5v20(params);
#endif
throw Algorithm_Not_Found(pbe_oid.as_string());
}
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <fstream>
#include <sstream>
#include "phonemeDict.h"
/*
* Assembles the map<word,phoneme> dictionary by reading one line at a time,
* separating the word from the pronunciation, encoding the phoneme, and
* putting the pair in the map
*/
PhonemeDict::PhonemeDict() {
dict = new std::map<std::string, std::string>;
std::ifstream file(DICTIONARY_FILE);
if (file) {
std::string line;
while (std::getline(file,line)) {
if (line.substr(0,3) == COMMENT_HEAD) {
continue;
}
else {
addWord(line);
}
}
}
else {
std::cerr << "Unable to load dictionary" << std::endl;
}
}
PhonemeDict::~PhonemeDict() {
dict->erase(dict->begin(), dict->end());
delete dict;
}
/*
* Given a string, return a pointer to the associated phoneme string
* or the phoneme of "gravy" if the string is not found.
*/
std::string* PhonemeDict::lookUp(std::string word) {
try {
return &(dict->at(allCaps(word)));
}
catch (const std::out_of_range& oor) {
return &(dict->at("GRAVY"));
}
}
/*
* Add an entry from the dictionary to the map
*/
void PhonemeDict::addWord(std::string line) {
std::istringstream ss(line);
std::string word;
std::string phonemes;
std::string phoneme;
std::pair<std::string, std::string> word_phonemes;
ss >> word;
while (ss >> phoneme) {
encoded_phoneme = encode(phoneme);
phonemes.push_back(encoded_phoneme);
}
dict->insert(word_phoneme(word,phonemes));
}
/*
* Capitalize a string
*/
std::string PhonemeDict::allCaps(std::string string) {
std::locale loc;
for (std::string::size_type i = 0; i < string.length(); ++i) {
string[i] = std::toupper(string[i],loc);
}
return string;
}
char PhonemeDict::encode(std::string phoneme) {
char code = '\0';
if (phoneme.substr(0,2) == "AA") code = 'A';
else if (phoneme.substr(0,2) == "AE") code = 'B';
else if (phoneme.substr(0,2) == "AH") code = 'C';
else if (phoneme.substr(0,2) == "AO") code = 'D';
else if (phoneme.substr(0,2) == "AW") code = 'E';
else if (phoneme.substr(0,2) == "AY") code = 'F';
else if (phoneme == "B") code = 'G';
else if (phoneme == "CH") code = 'H';
else if (phoneme == "D") code = 'I';
else if (phoneme == "DH") code = 'J';
else if (phoneme.substr(0,2) == "EH") code = 'K';
else if (phoneme.substr(0,2) == "ER") code = 'L';
else if (phoneme.substr(0,2) == "EY") code = 'M';
else if (phoneme == "F") code = 'N';
else if (phoneme == "G") code = 'O';
else if (phoneme == "HH") code = 'P';
else if (phoneme.substr(0,2) == "IH") code = 'Q';
else if (phoneme.substr(0,2) == "IY") code = 'R';
else if (phoneme == "JH") code = 'S';
else if (phoneme == "K") code = 'T';
else if (phoneme == "L") code = 'U';
else if (phoneme == "M") code = 'V';
else if (phoneme == "N") code = 'W';
else if (phoneme == "NG") code = 'X';
else if (phoneme.substr(0,2) == "OW") code = 'Y';
else if (phoneme.substr(0,2) == "OY") code = 'Z';
else if (phoneme == "P") code = 'a';
else if (phoneme == "R") code = 'b';
else if (phoneme == "S") code = 'c';
else if (phoneme == "SH") code = 'd';
else if (phoneme == "T") code = 'e';
else if (phoneme == "TH") code = 'f';
else if (phoneme.substr(0,2) == "UH") code = 'g';
else if (phoneme.substr(0,2) == "UW") code = 'h';
else if (phoneme == "V") code = 'i';
else if (phoneme == "W") code = 'j';
else if (phoneme == "Y") code = 'k';
else if (phoneme == "Z") code = 'l';
else if (phoneme == "ZH") code = 'm';
else
std::cerr << "Could not identify phoneme " << phoneme << std::endl;
return code;
}
int PhonemeDict::getSize(){
return dict->size();
}
<commit_msg>resolve std::pair call operator error<commit_after>#include <iostream>
#include <fstream>
#include <sstream>
#include "phonemeDict.h"
/*
* Assembles the map<word,phoneme> dictionary by reading one line at a time,
* separating the word from the pronunciation, encoding the phoneme, and
* putting the pair in the map
*/
PhonemeDict::PhonemeDict() {
dict = new std::map<std::string, std::string>;
std::ifstream file(DICTIONARY_FILE);
if (file) {
std::string line;
while (std::getline(file,line)) {
if (line.substr(0,3) == COMMENT_HEAD) {
continue;
}
else {
addWord(line);
}
}
}
else {
std::cerr << "Unable to load dictionary" << std::endl;
}
}
PhonemeDict::~PhonemeDict() {
dict->erase(dict->begin(), dict->end());
delete dict;
}
/*
* Given a string, return a pointer to the associated phoneme string
* or the phoneme of "gravy" if the string is not found.
*/
std::string* PhonemeDict::lookUp(std::string word) {
try {
return &(dict->at(allCaps(word)));
}
catch (const std::out_of_range& oor) {
return &(dict->at("GRAVY"));
}
}
/*
* Add an entry from the dictionary to the map
*/
void PhonemeDict::addWord(std::string line) {
std::istringstream ss(line);
std::string word;
std::string phonemes;
std::string phoneme;
ss >> word;
while (ss >> phoneme) {
char encoded_phoneme = encode(phoneme);
phonemes.push_back(encoded_phoneme);
}
std::pair<std::string, std::string> word_phonemes(word, phonemes);
dict->insert(word_phonemes);
}
/*
* Capitalize a string
*/
std::string PhonemeDict::allCaps(std::string string) {
std::locale loc;
for (std::string::size_type i = 0; i < string.length(); ++i) {
string[i] = std::toupper(string[i],loc);
}
return string;
}
char PhonemeDict::encode(std::string phoneme) {
char code = '\0';
if (phoneme.substr(0,2) == "AA") code = 'A';
else if (phoneme.substr(0,2) == "AE") code = 'B';
else if (phoneme.substr(0,2) == "AH") code = 'C';
else if (phoneme.substr(0,2) == "AO") code = 'D';
else if (phoneme.substr(0,2) == "AW") code = 'E';
else if (phoneme.substr(0,2) == "AY") code = 'F';
else if (phoneme == "B") code = 'G';
else if (phoneme == "CH") code = 'H';
else if (phoneme == "D") code = 'I';
else if (phoneme == "DH") code = 'J';
else if (phoneme.substr(0,2) == "EH") code = 'K';
else if (phoneme.substr(0,2) == "ER") code = 'L';
else if (phoneme.substr(0,2) == "EY") code = 'M';
else if (phoneme == "F") code = 'N';
else if (phoneme == "G") code = 'O';
else if (phoneme == "HH") code = 'P';
else if (phoneme.substr(0,2) == "IH") code = 'Q';
else if (phoneme.substr(0,2) == "IY") code = 'R';
else if (phoneme == "JH") code = 'S';
else if (phoneme == "K") code = 'T';
else if (phoneme == "L") code = 'U';
else if (phoneme == "M") code = 'V';
else if (phoneme == "N") code = 'W';
else if (phoneme == "NG") code = 'X';
else if (phoneme.substr(0,2) == "OW") code = 'Y';
else if (phoneme.substr(0,2) == "OY") code = 'Z';
else if (phoneme == "P") code = 'a';
else if (phoneme == "R") code = 'b';
else if (phoneme == "S") code = 'c';
else if (phoneme == "SH") code = 'd';
else if (phoneme == "T") code = 'e';
else if (phoneme == "TH") code = 'f';
else if (phoneme.substr(0,2) == "UH") code = 'g';
else if (phoneme.substr(0,2) == "UW") code = 'h';
else if (phoneme == "V") code = 'i';
else if (phoneme == "W") code = 'j';
else if (phoneme == "Y") code = 'k';
else if (phoneme == "Z") code = 'l';
else if (phoneme == "ZH") code = 'm';
else
std::cerr << "Could not identify phoneme " << phoneme << std::endl;
return code;
}
int PhonemeDict::getSize(){
return dict->size();
}
<|endoftext|> |
<commit_before>/*
* MIT License
*
* Copyright (c) 2009-2018 Jingwood, unvell.com. All right reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "stdafx.h"
#include "Simple.h"
#include "Pen.h"
void DrawLine(HANDLE ctx, D2D1_POINT_2F start, D2D1_POINT_2F end, D2D1_COLOR_F color,
FLOAT width, D2D1_DASH_STYLE dashStyle)
{
RetrieveContext(ctx);
ID2D1SolidColorBrush* brush;
(context->renderTarget)->CreateSolidColorBrush(color, &brush);
ID2D1StrokeStyle* strokeStyle = NULL;
if (dashStyle != D2D1_DASH_STYLE_SOLID)
{
context->factory->CreateStrokeStyle(D2D1::StrokeStyleProperties(
D2D1_CAP_STYLE_FLAT,
D2D1_CAP_STYLE_FLAT,
D2D1_CAP_STYLE_ROUND,
D2D1_LINE_JOIN_MITER,
10.0f,
dashStyle,
0.0f), NULL, 0, &strokeStyle);
}
context->renderTarget->DrawLine(start, end, brush, width, strokeStyle);
SafeRelease(&strokeStyle);
SafeRelease(&brush);
}
void DrawArrowLine(HANDLE ctx, D2D1_POINT_2F start, D2D1_POINT_2F end, D2D1_COLOR_F color,
FLOAT width, D2D1_DASH_STYLE dashStyle)
{
RetrieveContext(ctx);
ID2D1SolidColorBrush* brush = NULL;
(context->renderTarget)->CreateSolidColorBrush(color, &brush);
ID2D1StrokeStyle* strokeStyle = NULL;
if (dashStyle != D2D1_DASH_STYLE_SOLID)
{
context->factory->CreateStrokeStyle(D2D1::StrokeStyleProperties(
D2D1_CAP_STYLE_FLAT,
D2D1_CAP_STYLE_FLAT,
D2D1_CAP_STYLE_ROUND,
D2D1_LINE_JOIN_MITER,
10.0f,
dashStyle,
0.0f), NULL, 0, &strokeStyle);
}
if (brush != NULL) {
context->renderTarget->DrawLine(start, end, brush, width, strokeStyle);
}
SafeRelease(&strokeStyle);
SafeRelease(&brush);
}
D2DLIB_API void DrawLineWithPen(HANDLE ctx, D2D1_POINT_2F start, D2D1_POINT_2F end, HANDLE penHandle, FLOAT width)
{
RetrieveContext(ctx);
D2DPen* pen = (D2DPen*)penHandle;
context->renderTarget->DrawLine(start, end, pen->brush, width, pen->strokeStyle);
}
void DrawLines(HANDLE ctx, D2D1_POINT_2F* points, UINT count, D2D1_COLOR_F color,
FLOAT width, D2D1_DASH_STYLE dashStyle)
{
if (count <= 1) return;
RetrieveContext(ctx);
ID2D1SolidColorBrush* brush = NULL;
ID2D1StrokeStyle* strokeStyle = NULL;
context->renderTarget->CreateSolidColorBrush(color, &brush);
if (brush != NULL) {
if (dashStyle != D2D1_DASH_STYLE_SOLID)
{
context->factory->CreateStrokeStyle(D2D1::StrokeStyleProperties(
D2D1_CAP_STYLE_FLAT,
D2D1_CAP_STYLE_FLAT,
D2D1_CAP_STYLE_ROUND,
D2D1_LINE_JOIN_MITER,
10.0f,
dashStyle,
0.0f), NULL, 0, &strokeStyle);
ID2D1PathGeometry* pathGeo = NULL;
ID2D1GeometrySink* sink = NULL;
context->factory->CreatePathGeometry(&pathGeo);
if (pathGeo != NULL) {
pathGeo->Open(&sink);
sink->BeginFigure(points[0], D2D1_FIGURE_BEGIN::D2D1_FIGURE_BEGIN_FILLED);
sink->AddLines(points + 1, count - 1);
//sink->EndFigure(D2D1_FIGURE_END_CLOSED);
sink->Close();
context->renderTarget->DrawGeometry(pathGeo, brush, width, strokeStyle);
}
SafeRelease(&sink);
SafeRelease(&pathGeo);
}
else
{
for (UINT i = 0; i < count - 1; i++)
{
context->renderTarget->DrawLine(points[i], points[i + 1], brush, width, strokeStyle);
}
//context->renderTarget->DrawLine(points[count - 1], points[0], brush, weight, strokeStyle);
}
}
SafeRelease(&strokeStyle);
SafeRelease(&brush);
}
void DrawRectangle(HANDLE handle, D2D1_RECT_F* rect, D2D1_COLOR_F color,
FLOAT width, D2D1_DASH_STYLE dashStyle)
{
D2DContext* context = reinterpret_cast<D2DContext*>(handle);
ID2D1SolidColorBrush* brush = NULL;
ID2D1StrokeStyle* strokeStyle = NULL;
if (brush != NULL) {
context->renderTarget->CreateSolidColorBrush(color, &brush);
if (dashStyle != D2D1_DASH_STYLE_SOLID)
{
context->factory->CreateStrokeStyle(D2D1::StrokeStyleProperties(
D2D1_CAP_STYLE_FLAT,
D2D1_CAP_STYLE_FLAT,
D2D1_CAP_STYLE_ROUND,
D2D1_LINE_JOIN_MITER,
10.0f,
dashStyle,
0.0f), NULL, 0, &strokeStyle);
}
context->renderTarget->DrawRectangle(rect, brush, width, strokeStyle);
}
SafeRelease(&strokeStyle);
SafeRelease(&brush);
}
void FillRectangle(HANDLE ctx, D2D1_RECT_F* rect, D2D1_COLOR_F color)
{
RetrieveContext(ctx);
ID2D1SolidColorBrush* brush = NULL;
context->renderTarget->CreateSolidColorBrush(color, &brush);
if (brush != NULL) {
context->renderTarget->FillRectangle(rect, brush);
}
SafeRelease(&brush);
}
void FillRectangleWithBrush(HANDLE ctx, D2D1_RECT_F* rect, HANDLE brushHandle)
{
RetrieveContext(ctx);
ID2D1Brush* brush = reinterpret_cast<ID2D1Brush*>(brushHandle);
if (brush != NULL) {
context->renderTarget->FillRectangle(rect, brush);
}
}
void DrawEllipse(HANDLE handle, D2D1_ELLIPSE* ellipse, D2D1_COLOR_F color,
FLOAT width, D2D1_DASH_STYLE dashStyle)
{
D2DContext* context = reinterpret_cast<D2DContext*>(handle);
ID2D1SolidColorBrush* brush = NULL;
ID2D1StrokeStyle* strokeStyle = NULL;
(context->renderTarget)->CreateSolidColorBrush(color, &brush);
if (brush != NULL) {
if (dashStyle != D2D1_DASH_STYLE_SOLID)
{
context->factory->CreateStrokeStyle(D2D1::StrokeStyleProperties(
D2D1_CAP_STYLE_FLAT,
D2D1_CAP_STYLE_FLAT,
D2D1_CAP_STYLE_ROUND,
D2D1_LINE_JOIN_MITER,
10.0f,
dashStyle,
0.0f), NULL, 0, &strokeStyle);
}
context->renderTarget->DrawEllipse(ellipse, brush, width, strokeStyle);
}
SafeRelease(&strokeStyle);
SafeRelease(&brush);
}
void FillEllipse(HANDLE handle, D2D1_ELLIPSE* ellipse, D2D1_COLOR_F color)
{
D2DContext* context = reinterpret_cast<D2DContext*>(handle);
// Create a black brush.
ID2D1SolidColorBrush* brush;
context->renderTarget->CreateSolidColorBrush(color, &brush);
if (brush != NULL) {
context->renderTarget->FillEllipse(ellipse, brush);
}
SafeRelease(&brush);
}
void FillEllipseWithBrush(HANDLE ctx, D2D1_ELLIPSE* ellipse, HANDLE brush_handle)
{
RetrieveContext(ctx);
ID2D1Brush* brush = reinterpret_cast<ID2D1Brush*>(brush_handle);
context->renderTarget->FillEllipse(ellipse, brush);
}<commit_msg>fix #12<commit_after>/*
* MIT License
*
* Copyright (c) 2009-2018 Jingwood, unvell.com. All right reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "stdafx.h"
#include "Simple.h"
#include "Pen.h"
void DrawLine(HANDLE ctx, D2D1_POINT_2F start, D2D1_POINT_2F end, D2D1_COLOR_F color,
FLOAT width, D2D1_DASH_STYLE dashStyle)
{
RetrieveContext(ctx);
ID2D1SolidColorBrush* brush = NULL;
ID2D1StrokeStyle* strokeStyle = NULL;
context->renderTarget->CreateSolidColorBrush(color, &brush);
if (brush != NULL) {
if (dashStyle != D2D1_DASH_STYLE_SOLID)
{
context->factory->CreateStrokeStyle(D2D1::StrokeStyleProperties(
D2D1_CAP_STYLE_FLAT,
D2D1_CAP_STYLE_FLAT,
D2D1_CAP_STYLE_ROUND,
D2D1_LINE_JOIN_MITER,
10.0f,
dashStyle,
0.0f), NULL, 0, &strokeStyle);
}
context->renderTarget->DrawLine(start, end, brush, width, strokeStyle);
}
SafeRelease(&strokeStyle);
SafeRelease(&brush);
}
void DrawArrowLine(HANDLE ctx, D2D1_POINT_2F start, D2D1_POINT_2F end, D2D1_COLOR_F color,
FLOAT width, D2D1_DASH_STYLE dashStyle)
{
RetrieveContext(ctx);
ID2D1SolidColorBrush* brush = NULL;
(context->renderTarget)->CreateSolidColorBrush(color, &brush);
ID2D1StrokeStyle* strokeStyle = NULL;
if (dashStyle != D2D1_DASH_STYLE_SOLID)
{
context->factory->CreateStrokeStyle(D2D1::StrokeStyleProperties(
D2D1_CAP_STYLE_FLAT,
D2D1_CAP_STYLE_FLAT,
D2D1_CAP_STYLE_ROUND,
D2D1_LINE_JOIN_MITER,
10.0f,
dashStyle,
0.0f), NULL, 0, &strokeStyle);
}
if (brush != NULL) {
context->renderTarget->DrawLine(start, end, brush, width, strokeStyle);
}
SafeRelease(&strokeStyle);
SafeRelease(&brush);
}
D2DLIB_API void DrawLineWithPen(HANDLE ctx, D2D1_POINT_2F start, D2D1_POINT_2F end, HANDLE penHandle, FLOAT width)
{
RetrieveContext(ctx);
D2DPen* pen = (D2DPen*)penHandle;
context->renderTarget->DrawLine(start, end, pen->brush, width, pen->strokeStyle);
}
void DrawLines(HANDLE ctx, D2D1_POINT_2F* points, UINT count, D2D1_COLOR_F color,
FLOAT width, D2D1_DASH_STYLE dashStyle)
{
if (count <= 1) return;
RetrieveContext(ctx);
ID2D1SolidColorBrush* brush = NULL;
ID2D1StrokeStyle* strokeStyle = NULL;
context->renderTarget->CreateSolidColorBrush(color, &brush);
if (brush != NULL) {
if (dashStyle != D2D1_DASH_STYLE_SOLID)
{
context->factory->CreateStrokeStyle(D2D1::StrokeStyleProperties(
D2D1_CAP_STYLE_FLAT,
D2D1_CAP_STYLE_FLAT,
D2D1_CAP_STYLE_ROUND,
D2D1_LINE_JOIN_MITER,
10.0f,
dashStyle,
0.0f), NULL, 0, &strokeStyle);
ID2D1PathGeometry* pathGeo = NULL;
ID2D1GeometrySink* sink = NULL;
context->factory->CreatePathGeometry(&pathGeo);
if (pathGeo != NULL) {
pathGeo->Open(&sink);
sink->BeginFigure(points[0], D2D1_FIGURE_BEGIN::D2D1_FIGURE_BEGIN_FILLED);
sink->AddLines(points + 1, count - 1);
//sink->EndFigure(D2D1_FIGURE_END_CLOSED);
sink->Close();
context->renderTarget->DrawGeometry(pathGeo, brush, width, strokeStyle);
}
SafeRelease(&sink);
SafeRelease(&pathGeo);
}
else
{
for (UINT i = 0; i < count - 1; i++)
{
context->renderTarget->DrawLine(points[i], points[i + 1], brush, width, strokeStyle);
}
//context->renderTarget->DrawLine(points[count - 1], points[0], brush, weight, strokeStyle);
}
}
SafeRelease(&strokeStyle);
SafeRelease(&brush);
}
void DrawRectangle(HANDLE handle, D2D1_RECT_F* rect, D2D1_COLOR_F color,
FLOAT width, D2D1_DASH_STYLE dashStyle)
{
D2DContext* context = reinterpret_cast<D2DContext*>(handle);
ID2D1SolidColorBrush* brush = NULL;
ID2D1StrokeStyle* strokeStyle = NULL;
context->renderTarget->CreateSolidColorBrush(color, &brush);
if (brush != NULL) {
if (dashStyle != D2D1_DASH_STYLE_SOLID) {
context->factory->CreateStrokeStyle(D2D1::StrokeStyleProperties(
D2D1_CAP_STYLE_FLAT,
D2D1_CAP_STYLE_FLAT,
D2D1_CAP_STYLE_ROUND,
D2D1_LINE_JOIN_MITER,
10.0f,
dashStyle,
0.0f), NULL, 0, &strokeStyle);
}
context->renderTarget->DrawRectangle(rect, brush, width, strokeStyle);
}
SafeRelease(&brush);
SafeRelease(&strokeStyle);
}
void FillRectangle(HANDLE ctx, D2D1_RECT_F* rect, D2D1_COLOR_F color)
{
RetrieveContext(ctx);
ID2D1SolidColorBrush* brush = NULL;
context->renderTarget->CreateSolidColorBrush(color, &brush);
if (brush != NULL) {
context->renderTarget->FillRectangle(rect, brush);
}
SafeRelease(&brush);
}
void FillRectangleWithBrush(HANDLE ctx, D2D1_RECT_F* rect, HANDLE brushHandle)
{
RetrieveContext(ctx);
ID2D1Brush* brush = reinterpret_cast<ID2D1Brush*>(brushHandle);
if (brush != NULL) {
context->renderTarget->FillRectangle(rect, brush);
}
}
void DrawEllipse(HANDLE handle, D2D1_ELLIPSE* ellipse, D2D1_COLOR_F color,
FLOAT width, D2D1_DASH_STYLE dashStyle)
{
D2DContext* context = reinterpret_cast<D2DContext*>(handle);
ID2D1SolidColorBrush* brush = NULL;
ID2D1StrokeStyle* strokeStyle = NULL;
(context->renderTarget)->CreateSolidColorBrush(color, &brush);
if (brush != NULL) {
if (dashStyle != D2D1_DASH_STYLE_SOLID)
{
context->factory->CreateStrokeStyle(D2D1::StrokeStyleProperties(
D2D1_CAP_STYLE_FLAT,
D2D1_CAP_STYLE_FLAT,
D2D1_CAP_STYLE_ROUND,
D2D1_LINE_JOIN_MITER,
10.0f,
dashStyle,
0.0f), NULL, 0, &strokeStyle);
}
context->renderTarget->DrawEllipse(ellipse, brush, width, strokeStyle);
}
SafeRelease(&strokeStyle);
SafeRelease(&brush);
}
void FillEllipse(HANDLE handle, D2D1_ELLIPSE* ellipse, D2D1_COLOR_F color)
{
D2DContext* context = reinterpret_cast<D2DContext*>(handle);
// Create a black brush.
ID2D1SolidColorBrush* brush;
context->renderTarget->CreateSolidColorBrush(color, &brush);
if (brush != NULL) {
context->renderTarget->FillEllipse(ellipse, brush);
}
SafeRelease(&brush);
}
void FillEllipseWithBrush(HANDLE ctx, D2D1_ELLIPSE* ellipse, HANDLE brush_handle)
{
RetrieveContext(ctx);
ID2D1Brush* brush = reinterpret_cast<ID2D1Brush*>(brush_handle);
context->renderTarget->FillEllipse(ellipse, brush);
}<|endoftext|> |
<commit_before>/*
* Copyright (c) 2014 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 "vp9/decoder/vp9_decoder.h"
#include "vp9/vp9_dx_iface.c"
static vpx_codec_alg_priv_t *get_alg_priv(vpx_codec_ctx_t *ctx) {
return (vpx_codec_alg_priv_t *)ctx->priv;
}
namespace {
const int kCpuUsed = 2;
struct EncodePerfTestVideo {
const char *name;
uint32_t width;
uint32_t height;
uint32_t bitrate;
int frames;
};
const EncodePerfTestVideo kVP9EncodePerfTestVectors[] = {
{"niklas_1280_720_30.y4m", 1280, 720, 600, 10},
};
struct EncodeParameters {
int32_t tile_rows;
int32_t tile_cols;
int32_t lossless;
int32_t error_resilient;
int32_t frame_parallel;
vpx_color_space_t cs;
// TODO(JBB): quantizers / bitrate
};
const EncodeParameters kVP9EncodeParameterSet[] = {
{0, 0, 0, 1, 0, VPX_CS_BT_601},
{0, 0, 0, 0, 0, VPX_CS_BT_709},
{0, 0, 1, 0, 0, VPX_CS_BT_2020},
{0, 2, 0, 0, 1, VPX_CS_UNKNOWN},
// TODO(JBB): Test profiles (requires more work).
};
class VpxEncoderParmsGetToDecoder
: public ::libvpx_test::EncoderTest,
public ::libvpx_test::CodecTestWith2Params<EncodeParameters, \
EncodePerfTestVideo> {
protected:
VpxEncoderParmsGetToDecoder()
: EncoderTest(GET_PARAM(0)),
encode_parms(GET_PARAM(1)) {
}
virtual ~VpxEncoderParmsGetToDecoder() {}
virtual void SetUp() {
InitializeConfig();
SetMode(::libvpx_test::kTwoPassGood);
cfg_.g_lag_in_frames = 25;
cfg_.g_error_resilient = encode_parms.error_resilient;
dec_cfg_.threads = 4;
test_video_ = GET_PARAM(2);
cfg_.rc_target_bitrate = test_video_.bitrate;
}
virtual void PreEncodeFrameHook(::libvpx_test::VideoSource *video,
::libvpx_test::Encoder *encoder) {
if (video->frame() == 1) {
encoder->Control(VP9E_SET_COLOR_SPACE, encode_parms.cs);
encoder->Control(VP9E_SET_LOSSLESS, encode_parms.lossless);
encoder->Control(VP9E_SET_FRAME_PARALLEL_DECODING,
encode_parms.frame_parallel);
encoder->Control(VP9E_SET_TILE_ROWS, encode_parms.tile_rows);
encoder->Control(VP9E_SET_TILE_COLUMNS, encode_parms.tile_cols);
encoder->Control(VP8E_SET_CPUUSED, kCpuUsed);
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);
}
}
virtual bool HandleDecodeResult(const vpx_codec_err_t res_dec,
const libvpx_test::VideoSource& video,
libvpx_test::Decoder *decoder) {
vpx_codec_ctx_t* vp9_decoder = decoder->GetDecoder();
vpx_codec_alg_priv_t* priv =
(vpx_codec_alg_priv_t*) get_alg_priv(vp9_decoder);
FrameWorkerData *const worker_data =
reinterpret_cast<FrameWorkerData *>(priv->frame_workers[0].data1);
VP9_COMMON *const common = &worker_data->pbi->common;
if (encode_parms.lossless) {
EXPECT_EQ(0, common->base_qindex);
EXPECT_EQ(0, common->y_dc_delta_q);
EXPECT_EQ(0, common->uv_dc_delta_q);
EXPECT_EQ(0, common->uv_ac_delta_q);
EXPECT_EQ(ONLY_4X4, common->tx_mode);
}
EXPECT_EQ(encode_parms.error_resilient, common->error_resilient_mode);
if (encode_parms.error_resilient) {
EXPECT_EQ(1, common->frame_parallel_decoding_mode);
EXPECT_EQ(0, common->use_prev_frame_mvs);
} else {
EXPECT_EQ(encode_parms.frame_parallel,
common->frame_parallel_decoding_mode);
}
EXPECT_EQ(encode_parms.cs, common->color_space);
EXPECT_EQ(encode_parms.tile_cols, common->log2_tile_cols);
EXPECT_EQ(encode_parms.tile_rows, common->log2_tile_rows);
EXPECT_EQ(VPX_CODEC_OK, res_dec) << decoder->DecodeError();
return VPX_CODEC_OK == res_dec;
}
EncodePerfTestVideo test_video_;
private:
EncodeParameters encode_parms;
};
TEST_P(VpxEncoderParmsGetToDecoder, BitstreamParms) {
init_flags_ = VPX_CODEC_USE_PSNR;
libvpx_test::VideoSource *const video =
new libvpx_test::Y4mVideoSource(test_video_.name, 0, test_video_.frames);
ASSERT_TRUE(video != NULL);
ASSERT_NO_FATAL_FAILURE(RunLoop(video));
delete(video);
}
VP9_INSTANTIATE_TEST_CASE(
VpxEncoderParmsGetToDecoder,
::testing::ValuesIn(kVP9EncodeParameterSet),
::testing::ValuesIn(kVP9EncodePerfTestVectors));
} // namespace
<commit_msg>vp9...parms_get_to_decoder: remove unneeded func<commit_after>/*
* Copyright (c) 2014 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 "vp9/decoder/vp9_decoder.h"
#include "vp9/vp9_dx_iface.c"
namespace {
const int kCpuUsed = 2;
struct EncodePerfTestVideo {
const char *name;
uint32_t width;
uint32_t height;
uint32_t bitrate;
int frames;
};
const EncodePerfTestVideo kVP9EncodePerfTestVectors[] = {
{"niklas_1280_720_30.y4m", 1280, 720, 600, 10},
};
struct EncodeParameters {
int32_t tile_rows;
int32_t tile_cols;
int32_t lossless;
int32_t error_resilient;
int32_t frame_parallel;
vpx_color_space_t cs;
// TODO(JBB): quantizers / bitrate
};
const EncodeParameters kVP9EncodeParameterSet[] = {
{0, 0, 0, 1, 0, VPX_CS_BT_601},
{0, 0, 0, 0, 0, VPX_CS_BT_709},
{0, 0, 1, 0, 0, VPX_CS_BT_2020},
{0, 2, 0, 0, 1, VPX_CS_UNKNOWN},
// TODO(JBB): Test profiles (requires more work).
};
class VpxEncoderParmsGetToDecoder
: public ::libvpx_test::EncoderTest,
public ::libvpx_test::CodecTestWith2Params<EncodeParameters, \
EncodePerfTestVideo> {
protected:
VpxEncoderParmsGetToDecoder()
: EncoderTest(GET_PARAM(0)),
encode_parms(GET_PARAM(1)) {
}
virtual ~VpxEncoderParmsGetToDecoder() {}
virtual void SetUp() {
InitializeConfig();
SetMode(::libvpx_test::kTwoPassGood);
cfg_.g_lag_in_frames = 25;
cfg_.g_error_resilient = encode_parms.error_resilient;
dec_cfg_.threads = 4;
test_video_ = GET_PARAM(2);
cfg_.rc_target_bitrate = test_video_.bitrate;
}
virtual void PreEncodeFrameHook(::libvpx_test::VideoSource *video,
::libvpx_test::Encoder *encoder) {
if (video->frame() == 1) {
encoder->Control(VP9E_SET_COLOR_SPACE, encode_parms.cs);
encoder->Control(VP9E_SET_LOSSLESS, encode_parms.lossless);
encoder->Control(VP9E_SET_FRAME_PARALLEL_DECODING,
encode_parms.frame_parallel);
encoder->Control(VP9E_SET_TILE_ROWS, encode_parms.tile_rows);
encoder->Control(VP9E_SET_TILE_COLUMNS, encode_parms.tile_cols);
encoder->Control(VP8E_SET_CPUUSED, kCpuUsed);
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);
}
}
virtual bool HandleDecodeResult(const vpx_codec_err_t res_dec,
const libvpx_test::VideoSource& video,
libvpx_test::Decoder *decoder) {
vpx_codec_ctx_t* vp9_decoder = decoder->GetDecoder();
vpx_codec_alg_priv_t* priv =
reinterpret_cast<vpx_codec_alg_priv_t *>(vp9_decoder->priv);
FrameWorkerData *const worker_data =
reinterpret_cast<FrameWorkerData *>(priv->frame_workers[0].data1);
VP9_COMMON *const common = &worker_data->pbi->common;
if (encode_parms.lossless) {
EXPECT_EQ(0, common->base_qindex);
EXPECT_EQ(0, common->y_dc_delta_q);
EXPECT_EQ(0, common->uv_dc_delta_q);
EXPECT_EQ(0, common->uv_ac_delta_q);
EXPECT_EQ(ONLY_4X4, common->tx_mode);
}
EXPECT_EQ(encode_parms.error_resilient, common->error_resilient_mode);
if (encode_parms.error_resilient) {
EXPECT_EQ(1, common->frame_parallel_decoding_mode);
EXPECT_EQ(0, common->use_prev_frame_mvs);
} else {
EXPECT_EQ(encode_parms.frame_parallel,
common->frame_parallel_decoding_mode);
}
EXPECT_EQ(encode_parms.cs, common->color_space);
EXPECT_EQ(encode_parms.tile_cols, common->log2_tile_cols);
EXPECT_EQ(encode_parms.tile_rows, common->log2_tile_rows);
EXPECT_EQ(VPX_CODEC_OK, res_dec) << decoder->DecodeError();
return VPX_CODEC_OK == res_dec;
}
EncodePerfTestVideo test_video_;
private:
EncodeParameters encode_parms;
};
TEST_P(VpxEncoderParmsGetToDecoder, BitstreamParms) {
init_flags_ = VPX_CODEC_USE_PSNR;
libvpx_test::VideoSource *const video =
new libvpx_test::Y4mVideoSource(test_video_.name, 0, test_video_.frames);
ASSERT_TRUE(video != NULL);
ASSERT_NO_FATAL_FAILURE(RunLoop(video));
delete(video);
}
VP9_INSTANTIATE_TEST_CASE(
VpxEncoderParmsGetToDecoder,
::testing::ValuesIn(kVP9EncodeParameterSet),
::testing::ValuesIn(kVP9EncodePerfTestVectors));
} // namespace
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2017 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <boost/test/unit_test.hpp>
#include <seastar/util/backtrace.hh>
#include "flat_mutation_reader.hh"
#include "mutation_assertions.hh"
// Intended to be called in a seastar thread
class flat_reader_assertions {
flat_mutation_reader _reader;
dht::partition_range _pr;
private:
mutation_fragment_opt read_next() {
return _reader().get0();
}
public:
flat_reader_assertions(flat_mutation_reader reader)
: _reader(std::move(reader))
{ }
flat_reader_assertions& produces_partition_start(const dht::decorated_key& dk,
stdx::optional<tombstone> tomb = stdx::nullopt) {
BOOST_TEST_MESSAGE(sprint("Expecting partition start with key %s", dk));
auto mfopt = read_next();
if (!mfopt) {
BOOST_FAIL(sprint("Expected: partition start with key %s, got end of stream", dk));
}
if (!mfopt->is_partition_start()) {
BOOST_FAIL(sprint("Expected: partition start with key %s, got: %s", dk, *mfopt));
}
if (!mfopt->as_partition_start().key().equal(*_reader.schema(), dk)) {
BOOST_FAIL(sprint("Expected: partition start with key %s, got: %s", dk, *mfopt));
}
if (tomb && mfopt->as_partition_start().partition_tombstone() != *tomb) {
BOOST_FAIL(sprint("Expected: partition start with tombstone %s, got: %s", *tomb, *mfopt));
}
return *this;
}
flat_reader_assertions& produces_static_row() {
BOOST_TEST_MESSAGE(sprint("Expecting static row"));
auto mfopt = read_next();
if (!mfopt) {
BOOST_FAIL("Expected static row, got end of stream");
}
if (!mfopt->is_static_row()) {
BOOST_FAIL(sprint("Expected static row, got: %s", *mfopt));
}
return *this;
}
flat_reader_assertions& produces_row_with_key(const clustering_key& ck) {
BOOST_TEST_MESSAGE(sprint("Expect %s", ck));
auto mfopt = read_next();
if (!mfopt) {
BOOST_FAIL(sprint("Expected row with key %s, but got end of stream", ck));
}
if (!mfopt->is_clustering_row()) {
BOOST_FAIL(sprint("Expected row with key %s, but got %s", ck, *mfopt));
}
auto& actual = mfopt->as_clustering_row().key();
if (!actual.equal(*_reader.schema(), ck)) {
BOOST_FAIL(sprint("Expected row with key %s, but key is %s", ck, actual));
}
return *this;
}
// If ck_ranges is passed, verifies only that information relevant for ck_ranges matches.
flat_reader_assertions& produces_range_tombstone(const range_tombstone& rt, const query::clustering_row_ranges& ck_ranges = {}) {
BOOST_TEST_MESSAGE(sprint("Expect %s", rt));
auto mfo = read_next();
if (!mfo) {
BOOST_FAIL(sprint("Expected range tombstone %s, but got end of stream", rt));
}
if (!mfo->is_range_tombstone()) {
BOOST_FAIL(sprint("Expected range tombstone %s, but got %s", rt, *mfo));
}
const schema& s = *_reader.schema();
range_tombstone_list actual_list(s);
position_in_partition::equal_compare eq(s);
while (mutation_fragment* next = _reader.peek().get0()) {
if (!next->is_range_tombstone() || !eq(next->position(), mfo->position())) {
break;
}
actual_list.apply(s, _reader().get0()->as_range_tombstone());
}
actual_list.apply(s, mfo->as_range_tombstone());
{
range_tombstone_list expected_list(s);
expected_list.apply(s, rt);
actual_list.trim(s, ck_ranges);
expected_list.trim(s, ck_ranges);
if (!actual_list.equal(s, expected_list)) {
BOOST_FAIL(sprint("Expected %s, but got %s", expected_list, actual_list));
}
}
return *this;
}
flat_reader_assertions& produces_partition_end() {
BOOST_TEST_MESSAGE("Expecting partition end");
auto mfopt = read_next();
if (!mfopt) {
BOOST_FAIL(sprint("Expected partition end but got end of stream"));
}
if (!mfopt->is_end_of_partition()) {
BOOST_FAIL(sprint("Expected partition end but got %s", *mfopt));
}
return *this;
}
flat_reader_assertions& produces_end_of_stream() {
BOOST_TEST_MESSAGE("Expecting end of stream");
auto mfopt = read_next();
if (bool(mfopt)) {
BOOST_FAIL(sprint("Expected end of stream, got %s", *mfopt));
}
return *this;
}
flat_reader_assertions& produces(mutation_fragment::kind k, std::vector<int> ck_elements) {
std::vector<bytes> ck_bytes;
for (auto&& e : ck_elements) {
ck_bytes.emplace_back(int32_type->decompose(e));
}
auto ck = clustering_key_prefix::from_exploded(*_reader.schema(), std::move(ck_bytes));
auto mfopt = read_next();
if (!mfopt) {
BOOST_FAIL(sprint("Expected mutation fragment %s, got end of stream", ck));
}
if (mfopt->mutation_fragment_kind() != k) {
BOOST_FAIL(sprint("Expected mutation fragment kind %s, got: %s", k, mfopt->mutation_fragment_kind()));
}
clustering_key::equality ck_eq(*_reader.schema());
if (!ck_eq(mfopt->key(), ck)) {
BOOST_FAIL(sprint("Expected key %s, got: %s", ck, mfopt->key()));
}
return *this;
}
flat_reader_assertions& produces_partition(const mutation& m) {
return produces(m);
}
flat_reader_assertions& produces(const mutation& m, const stdx::optional<query::clustering_row_ranges>& ck_ranges = {}) {
auto mo = read_mutation_from_flat_mutation_reader(_reader).get0();
if (!mo) {
BOOST_FAIL(sprint("Expected %s, but got end of stream, at: %s", m, seastar::current_backtrace()));
}
memory::disable_failure_guard dfg;
assert_that(*mo).is_equal_to(m, ck_ranges);
return *this;
}
flat_reader_assertions& produces(const dht::decorated_key& dk) {
produces_partition_start(dk);
next_partition();
return *this;
}
template<typename Range>
flat_reader_assertions& produces(const Range& range) {
for (auto&& m : range) {
produces(m);
}
return *this;
}
flat_reader_assertions& produces_eos_or_empty_mutation() {
BOOST_TEST_MESSAGE("Expecting eos or empty mutation");
auto mo = read_mutation_from_flat_mutation_reader(_reader).get0();
if (mo) {
if (!mo->partition().empty()) {
BOOST_FAIL(sprint("Mutation is not empty: %s", *mo));
}
}
return *this;
}
void has_monotonic_positions() {
position_in_partition::less_compare less(*_reader.schema());
mutation_fragment_opt previous_fragment;
mutation_fragment_opt previous_partition;
bool inside_partition = false;
for (;;) {
auto mfo = read_next();
if (!mfo) {
break;
}
if (mfo->is_partition_start()) {
BOOST_REQUIRE(!inside_partition);
auto& dk = mfo->as_partition_start().key();
if (previous_partition && !previous_partition->as_partition_start().key().less_compare(*_reader.schema(), dk)) {
BOOST_FAIL(sprint("previous partition had greater key: prev=%s, current=%s", *previous_partition, *mfo));
}
previous_partition = std::move(mfo);
previous_fragment = stdx::nullopt;
inside_partition = true;
} else if (mfo->is_end_of_partition()) {
BOOST_REQUIRE(inside_partition);
inside_partition = false;
} else {
BOOST_REQUIRE(inside_partition);
if (previous_fragment) {
if (!less(previous_fragment->position(), mfo->position())) {
BOOST_FAIL(sprint("previous fragment has greater position: prev=%s, current=%s", *previous_fragment, *mfo));
}
}
previous_fragment = std::move(mfo);
}
}
BOOST_REQUIRE(!inside_partition);
}
flat_reader_assertions& fast_forward_to(const dht::partition_range& pr) {
_pr = pr;
_reader.fast_forward_to(_pr).get();
return *this;
}
flat_reader_assertions& next_partition() {
_reader.next_partition();
return *this;
}
flat_reader_assertions& fast_forward_to(position_range pr) {
_reader.fast_forward_to(std::move(pr)).get();
return *this;
}
flat_reader_assertions& fast_forward_to(const clustering_key& ck1, const clustering_key& ck2) {
return fast_forward_to(position_range{
position_in_partition(position_in_partition::clustering_row_tag_t(), ck1),
position_in_partition(position_in_partition::clustering_row_tag_t(), ck2)
});
}
flat_reader_assertions& produces_compacted(const mutation& m, const stdx::optional<query::clustering_row_ranges>& ck_ranges = {}) {
auto mo = read_mutation_from_flat_mutation_reader(_reader).get0();
BOOST_REQUIRE(bool(mo));
memory::disable_failure_guard dfg;
mutation got = *mo;
got.partition().compact_for_compaction(*m.schema(), always_gc, gc_clock::now());
assert_that(got).is_equal_to(m, ck_ranges);
return *this;
}
mutation_assertion next_mutation() {
auto mo = read_mutation_from_flat_mutation_reader(_reader).get0();
BOOST_REQUIRE(bool(mo));
return mutation_assertion(std::move(*mo));
}
future<> fill_buffer() {
return _reader.fill_buffer();
}
bool is_buffer_full() const {
return _reader.is_buffer_full();
}
void set_max_buffer_size(size_t size) {
_reader.set_max_buffer_size(size);
}
};
inline
flat_reader_assertions assert_that(flat_mutation_reader r) {
return { std::move(r) };
}
<commit_msg>flat_reader_assertions: Add produces_row taking column values<commit_after>/*
* Copyright (C) 2017 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <boost/test/unit_test.hpp>
#include <seastar/util/backtrace.hh>
#include "flat_mutation_reader.hh"
#include "mutation_assertions.hh"
// Intended to be called in a seastar thread
class flat_reader_assertions {
flat_mutation_reader _reader;
dht::partition_range _pr;
private:
mutation_fragment_opt read_next() {
return _reader().get0();
}
public:
flat_reader_assertions(flat_mutation_reader reader)
: _reader(std::move(reader))
{ }
flat_reader_assertions& produces_partition_start(const dht::decorated_key& dk,
stdx::optional<tombstone> tomb = stdx::nullopt) {
BOOST_TEST_MESSAGE(sprint("Expecting partition start with key %s", dk));
auto mfopt = read_next();
if (!mfopt) {
BOOST_FAIL(sprint("Expected: partition start with key %s, got end of stream", dk));
}
if (!mfopt->is_partition_start()) {
BOOST_FAIL(sprint("Expected: partition start with key %s, got: %s", dk, *mfopt));
}
if (!mfopt->as_partition_start().key().equal(*_reader.schema(), dk)) {
BOOST_FAIL(sprint("Expected: partition start with key %s, got: %s", dk, *mfopt));
}
if (tomb && mfopt->as_partition_start().partition_tombstone() != *tomb) {
BOOST_FAIL(sprint("Expected: partition start with tombstone %s, got: %s", *tomb, *mfopt));
}
return *this;
}
flat_reader_assertions& produces_static_row() {
BOOST_TEST_MESSAGE(sprint("Expecting static row"));
auto mfopt = read_next();
if (!mfopt) {
BOOST_FAIL("Expected static row, got end of stream");
}
if (!mfopt->is_static_row()) {
BOOST_FAIL(sprint("Expected static row, got: %s", *mfopt));
}
return *this;
}
flat_reader_assertions& produces_row_with_key(const clustering_key& ck) {
BOOST_TEST_MESSAGE(sprint("Expect %s", ck));
auto mfopt = read_next();
if (!mfopt) {
BOOST_FAIL(sprint("Expected row with key %s, but got end of stream", ck));
}
if (!mfopt->is_clustering_row()) {
BOOST_FAIL(sprint("Expected row with key %s, but got %s", ck, *mfopt));
}
auto& actual = mfopt->as_clustering_row().key();
if (!actual.equal(*_reader.schema(), ck)) {
BOOST_FAIL(sprint("Expected row with key %s, but key is %s", ck, actual));
}
return *this;
}
struct expected_column {
column_id id;
const sstring& name;
bytes value;
expected_column(const column_definition* cdef, bytes value)
: id(cdef->id)
, name(cdef->name_as_text())
, value(std::move(value))
{ }
};
flat_reader_assertions& produces_row(const clustering_key& ck, const std::vector<expected_column>& columns) {
BOOST_TEST_MESSAGE(sprint("Expect %s", ck));
auto mfopt = read_next();
if (!mfopt) {
BOOST_FAIL(sprint("Expected row with key %s, but got end of stream", ck));
}
if (!mfopt->is_clustering_row()) {
BOOST_FAIL(sprint("Expected row with key %s, but got %s", ck, *mfopt));
}
auto& actual = mfopt->as_clustering_row().key();
if (!actual.equal(*_reader.schema(), ck)) {
BOOST_FAIL(sprint("Expected row with key %s, but key is %s", ck, actual));
}
auto& cells = mfopt->as_clustering_row().cells();
if (cells.size() != columns.size()) {
BOOST_FAIL(sprint("Expected row with %s columns, but has %s", columns.size(), cells.size()));
}
for (size_t i = 0; i < columns.size(); ++i) {
const atomic_cell_or_collection* cell = cells.find_cell(columns[i].id);
if (!cell) {
BOOST_FAIL(sprint("Expected row with column %s, but it is not present", columns[i].name));
}
auto cmp = compare_unsigned(columns[i].value, cell->as_atomic_cell().value());
if (cmp != 0) {
BOOST_FAIL(sprint("Expected row with column %s having value %s, but it has value %s",
columns[i].name,
columns[i].value,
cell->as_atomic_cell().value()));
}
}
return *this;
}
// If ck_ranges is passed, verifies only that information relevant for ck_ranges matches.
flat_reader_assertions& produces_range_tombstone(const range_tombstone& rt, const query::clustering_row_ranges& ck_ranges = {}) {
BOOST_TEST_MESSAGE(sprint("Expect %s", rt));
auto mfo = read_next();
if (!mfo) {
BOOST_FAIL(sprint("Expected range tombstone %s, but got end of stream", rt));
}
if (!mfo->is_range_tombstone()) {
BOOST_FAIL(sprint("Expected range tombstone %s, but got %s", rt, *mfo));
}
const schema& s = *_reader.schema();
range_tombstone_list actual_list(s);
position_in_partition::equal_compare eq(s);
while (mutation_fragment* next = _reader.peek().get0()) {
if (!next->is_range_tombstone() || !eq(next->position(), mfo->position())) {
break;
}
actual_list.apply(s, _reader().get0()->as_range_tombstone());
}
actual_list.apply(s, mfo->as_range_tombstone());
{
range_tombstone_list expected_list(s);
expected_list.apply(s, rt);
actual_list.trim(s, ck_ranges);
expected_list.trim(s, ck_ranges);
if (!actual_list.equal(s, expected_list)) {
BOOST_FAIL(sprint("Expected %s, but got %s", expected_list, actual_list));
}
}
return *this;
}
flat_reader_assertions& produces_partition_end() {
BOOST_TEST_MESSAGE("Expecting partition end");
auto mfopt = read_next();
if (!mfopt) {
BOOST_FAIL(sprint("Expected partition end but got end of stream"));
}
if (!mfopt->is_end_of_partition()) {
BOOST_FAIL(sprint("Expected partition end but got %s", *mfopt));
}
return *this;
}
flat_reader_assertions& produces_end_of_stream() {
BOOST_TEST_MESSAGE("Expecting end of stream");
auto mfopt = read_next();
if (bool(mfopt)) {
BOOST_FAIL(sprint("Expected end of stream, got %s", *mfopt));
}
return *this;
}
flat_reader_assertions& produces(mutation_fragment::kind k, std::vector<int> ck_elements) {
std::vector<bytes> ck_bytes;
for (auto&& e : ck_elements) {
ck_bytes.emplace_back(int32_type->decompose(e));
}
auto ck = clustering_key_prefix::from_exploded(*_reader.schema(), std::move(ck_bytes));
auto mfopt = read_next();
if (!mfopt) {
BOOST_FAIL(sprint("Expected mutation fragment %s, got end of stream", ck));
}
if (mfopt->mutation_fragment_kind() != k) {
BOOST_FAIL(sprint("Expected mutation fragment kind %s, got: %s", k, mfopt->mutation_fragment_kind()));
}
clustering_key::equality ck_eq(*_reader.schema());
if (!ck_eq(mfopt->key(), ck)) {
BOOST_FAIL(sprint("Expected key %s, got: %s", ck, mfopt->key()));
}
return *this;
}
flat_reader_assertions& produces_partition(const mutation& m) {
return produces(m);
}
flat_reader_assertions& produces(const mutation& m, const stdx::optional<query::clustering_row_ranges>& ck_ranges = {}) {
auto mo = read_mutation_from_flat_mutation_reader(_reader).get0();
if (!mo) {
BOOST_FAIL(sprint("Expected %s, but got end of stream, at: %s", m, seastar::current_backtrace()));
}
memory::disable_failure_guard dfg;
assert_that(*mo).is_equal_to(m, ck_ranges);
return *this;
}
flat_reader_assertions& produces(const dht::decorated_key& dk) {
produces_partition_start(dk);
next_partition();
return *this;
}
template<typename Range>
flat_reader_assertions& produces(const Range& range) {
for (auto&& m : range) {
produces(m);
}
return *this;
}
flat_reader_assertions& produces_eos_or_empty_mutation() {
BOOST_TEST_MESSAGE("Expecting eos or empty mutation");
auto mo = read_mutation_from_flat_mutation_reader(_reader).get0();
if (mo) {
if (!mo->partition().empty()) {
BOOST_FAIL(sprint("Mutation is not empty: %s", *mo));
}
}
return *this;
}
void has_monotonic_positions() {
position_in_partition::less_compare less(*_reader.schema());
mutation_fragment_opt previous_fragment;
mutation_fragment_opt previous_partition;
bool inside_partition = false;
for (;;) {
auto mfo = read_next();
if (!mfo) {
break;
}
if (mfo->is_partition_start()) {
BOOST_REQUIRE(!inside_partition);
auto& dk = mfo->as_partition_start().key();
if (previous_partition && !previous_partition->as_partition_start().key().less_compare(*_reader.schema(), dk)) {
BOOST_FAIL(sprint("previous partition had greater key: prev=%s, current=%s", *previous_partition, *mfo));
}
previous_partition = std::move(mfo);
previous_fragment = stdx::nullopt;
inside_partition = true;
} else if (mfo->is_end_of_partition()) {
BOOST_REQUIRE(inside_partition);
inside_partition = false;
} else {
BOOST_REQUIRE(inside_partition);
if (previous_fragment) {
if (!less(previous_fragment->position(), mfo->position())) {
BOOST_FAIL(sprint("previous fragment has greater position: prev=%s, current=%s", *previous_fragment, *mfo));
}
}
previous_fragment = std::move(mfo);
}
}
BOOST_REQUIRE(!inside_partition);
}
flat_reader_assertions& fast_forward_to(const dht::partition_range& pr) {
_pr = pr;
_reader.fast_forward_to(_pr).get();
return *this;
}
flat_reader_assertions& next_partition() {
_reader.next_partition();
return *this;
}
flat_reader_assertions& fast_forward_to(position_range pr) {
_reader.fast_forward_to(std::move(pr)).get();
return *this;
}
flat_reader_assertions& fast_forward_to(const clustering_key& ck1, const clustering_key& ck2) {
return fast_forward_to(position_range{
position_in_partition(position_in_partition::clustering_row_tag_t(), ck1),
position_in_partition(position_in_partition::clustering_row_tag_t(), ck2)
});
}
flat_reader_assertions& produces_compacted(const mutation& m, const stdx::optional<query::clustering_row_ranges>& ck_ranges = {}) {
auto mo = read_mutation_from_flat_mutation_reader(_reader).get0();
BOOST_REQUIRE(bool(mo));
memory::disable_failure_guard dfg;
mutation got = *mo;
got.partition().compact_for_compaction(*m.schema(), always_gc, gc_clock::now());
assert_that(got).is_equal_to(m, ck_ranges);
return *this;
}
mutation_assertion next_mutation() {
auto mo = read_mutation_from_flat_mutation_reader(_reader).get0();
BOOST_REQUIRE(bool(mo));
return mutation_assertion(std::move(*mo));
}
future<> fill_buffer() {
return _reader.fill_buffer();
}
bool is_buffer_full() const {
return _reader.is_buffer_full();
}
void set_max_buffer_size(size_t size) {
_reader.set_max_buffer_size(size);
}
};
inline
flat_reader_assertions assert_that(flat_mutation_reader r) {
return { std::move(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 "config.h"
#include "cmd.h"
#include "libcomm.h"
#include "liberror.h"
#include "libuuu.h"
using namespace std;
static Config g_config;
constexpr uint16_t FSL_VID = 0x15A2;
constexpr uint16_t NXP_VID = 0x1FC9;
constexpr uint16_t BD_VID = 0x3016;
Config::Config()
{
emplace_back(ConfigItem{"SDPS:", "MX8QXP", nullptr, NXP_VID, 0x012F, 0x0002});
emplace_back(ConfigItem{"SDPS:", "MX8QM", "MX8QXP", NXP_VID, 0x0129, 0x0002});
emplace_back(ConfigItem{"SDPS:", "MX8DXL", "MX8QXP", NXP_VID, 0x0147});
emplace_back(ConfigItem{"SDPS:", "MX28", nullptr, FSL_VID, 0x004f});
emplace_back(ConfigItem{"SDPS:", "MX815", nullptr, NXP_VID, 0x013E});
emplace_back(ConfigItem{"SDPS:", "MX865", "MX815", NXP_VID, 0x0146});
emplace_back(ConfigItem{"SDPS:", "MX8ULP", "MX815", NXP_VID, 0x014A});
emplace_back(ConfigItem{"SDPS:", "MX8ULP", "MX815", NXP_VID, 0x014B});
emplace_back(ConfigItem{"SDPS:", "MX93", "MX815", NXP_VID, 0x014E});
emplace_back(ConfigItem{"SDP:", "MX7D", nullptr, FSL_VID, 0x0076});
emplace_back(ConfigItem{"SDP:", "MX6Q", nullptr, FSL_VID, 0x0054});
emplace_back(ConfigItem{"SDP:", "MX6D", "MX6Q", FSL_VID, 0x0061});
emplace_back(ConfigItem{"SDP:", "MX6SL", "MX6Q", FSL_VID, 0x0063});
emplace_back(ConfigItem{"SDP:", "MX6SX", "MX6Q", FSL_VID, 0x0071});
emplace_back(ConfigItem{"SDP:", "MX6UL", "MX7D", FSL_VID, 0x007D});
emplace_back(ConfigItem{"SDP:", "MX6ULL", "MX7D", FSL_VID, 0x0080});
emplace_back(ConfigItem{"SDP:", "MX6SLL", "MX7D", NXP_VID, 0x0128});
emplace_back(ConfigItem{"SDP:", "MX7ULP", nullptr, NXP_VID, 0x0126});
emplace_back(ConfigItem{"SDP:", "MXRT106X", nullptr, NXP_VID, 0x0135});
emplace_back(ConfigItem{"SDP:", "MX8MM", "MX8MQ", NXP_VID, 0x0134});
emplace_back(ConfigItem{"SDP:", "MX8MQ", "MX8MQ", NXP_VID, 0x012B});
emplace_back(ConfigItem{"SDPU:", "SPL", "SPL", 0x0525, 0xB4A4, 0, 0x04FF});
emplace_back(ConfigItem{"SDPV:", "SPL1", "SPL", 0x0525, 0xB4A4, 0x0500, 0x9998});
emplace_back(ConfigItem{"SDPV:", "SPL1", "SPL", NXP_VID, 0x0151, 0x0500, 0x9998});
emplace_back(ConfigItem{"SDPU:", "SPL", "SPL", 0x0525, 0xB4A4, 0x9999, 0x9999}); /*old i.MX8 MQEVk use bcd 9999*/
emplace_back(ConfigItem{"SDPU:", "SPL", "SPL", BD_VID, 0x1001, 0, 0x04FF});
emplace_back(ConfigItem{"SDPV:", "SPL1", "SPL", BD_VID, 0x1001, 0x0500, 0x9998});
emplace_back(ConfigItem{"FBK:", nullptr, nullptr, 0x066F, 0x9AFE});
emplace_back(ConfigItem{"FBK:", nullptr, nullptr, 0x066F, 0x9BFF});
emplace_back(ConfigItem{"FBK:", nullptr, nullptr, NXP_VID, 0x0153});
emplace_back(ConfigItem{"FB:", nullptr, nullptr, 0x0525, 0xA4A5});
emplace_back(ConfigItem{"FB:", nullptr, nullptr, 0x18D1, 0x0D02});
emplace_back(ConfigItem{"FB:", nullptr, nullptr, BD_VID, 0x0001});
emplace_back(ConfigItem{"FB:", nullptr, nullptr, NXP_VID, 0x0152});
}
int uuu_for_each_cfg(uuu_show_cfg fn, void *p)
{
for (const auto &configItem : g_config)
{
if (fn(configItem.m_protocol.c_str(),
configItem.m_chip.c_str(),
configItem.m_compatible.c_str(),
configItem.m_vid,
configItem.m_pid,
configItem.m_bcdVerMin,
configItem.m_bcdVerMax,
p))
return -1;
}
return 0;
}
Config * get_config() noexcept
{
return &g_config;
}
ConfigItem * Config::find(uint16_t vid, uint16_t pid, uint16_t ver)
{
for (auto it = begin(); it != end(); it++)
{
if (vid == it->m_vid && pid == it->m_pid)
{
if (ver >= it->m_bcdVerMin && ver <= it->m_bcdVerMax)
return &(*it);
}
}
return nullptr;
}
Config Config::find(const string &pro)
{
Config items;
for (auto it = begin(); it != end(); it++)
{
if (it->m_protocol == pro)
items.emplace_back(*it);
}
return items;
}
int CfgCmd::run(CmdCtx *)
{
size_t pos = 0;
string param;
ConfigItem item;
param = get_next_param(m_cmd, pos);
if (str_to_upper(param) == "CFG:")
param = get_next_param(m_cmd, pos);
if (param.empty())
{
set_last_err_string("Wrong param");
return -1;
}
item.m_protocol = str_to_upper(param);
bool conversion_succeeded = false;
while (pos < m_cmd.size())
{
param = get_next_param(m_cmd, pos);
if (param == "-pid")
{
param = get_next_param(m_cmd, pos);
item.m_pid = str_to_uint16(param, &conversion_succeeded);
if (!conversion_succeeded) return -1;
continue;
}
if (param == "-vid")
{
param = get_next_param(m_cmd, pos);
item.m_vid = str_to_uint16(param, &conversion_succeeded);
if (!conversion_succeeded) return -1;
continue;
}
if (param == "-bcdversion")
{
param = get_next_param(m_cmd, pos);
item.m_bcdVerMin = item.m_bcdVerMax = str_to_uint16(param, &conversion_succeeded);
if (!conversion_succeeded) return -1;
continue;
}
if (param == "-bcdmin")
{
param = get_next_param(m_cmd, pos);
item.m_bcdVerMin = str_to_uint16(param, &conversion_succeeded);
if (!conversion_succeeded) return -1;
continue;
}
if (param == "-bcdmax")
{
param = get_next_param(m_cmd, pos);
item.m_bcdVerMax = str_to_uint16(param, &conversion_succeeded);
if (!conversion_succeeded) return -1;
continue;
}
if (param == "-chip")
{
param = get_next_param(m_cmd, pos);
item.m_chip = param;
continue;
}
if (param == "-compatible")
{
param = get_next_param(m_cmd, pos);
item.m_compatible = param;
continue;
}
}
ConfigItem *pItem= g_config.find(item.m_vid, item.m_pid, item.m_bcdVerMax);
if (pItem)
*pItem = item;
else
g_config.emplace_back(item);
return 0;
}
<commit_msg>add support for stm vendor fastboot<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 "config.h"
#include "cmd.h"
#include "libcomm.h"
#include "liberror.h"
#include "libuuu.h"
using namespace std;
static Config g_config;
constexpr uint16_t FSL_VID = 0x15A2;
constexpr uint16_t NXP_VID = 0x1FC9;
constexpr uint16_t BD_VID = 0x3016;
Config::Config()
{
emplace_back(ConfigItem{"SDPS:", "MX8QXP", nullptr, NXP_VID, 0x012F, 0x0002});
emplace_back(ConfigItem{"SDPS:", "MX8QM", "MX8QXP", NXP_VID, 0x0129, 0x0002});
emplace_back(ConfigItem{"SDPS:", "MX8DXL", "MX8QXP", NXP_VID, 0x0147});
emplace_back(ConfigItem{"SDPS:", "MX28", nullptr, FSL_VID, 0x004f});
emplace_back(ConfigItem{"SDPS:", "MX815", nullptr, NXP_VID, 0x013E});
emplace_back(ConfigItem{"SDPS:", "MX865", "MX815", NXP_VID, 0x0146});
emplace_back(ConfigItem{"SDPS:", "MX8ULP", "MX815", NXP_VID, 0x014A});
emplace_back(ConfigItem{"SDPS:", "MX8ULP", "MX815", NXP_VID, 0x014B});
emplace_back(ConfigItem{"SDPS:", "MX93", "MX815", NXP_VID, 0x014E});
emplace_back(ConfigItem{"SDP:", "MX7D", nullptr, FSL_VID, 0x0076});
emplace_back(ConfigItem{"SDP:", "MX6Q", nullptr, FSL_VID, 0x0054});
emplace_back(ConfigItem{"SDP:", "MX6D", "MX6Q", FSL_VID, 0x0061});
emplace_back(ConfigItem{"SDP:", "MX6SL", "MX6Q", FSL_VID, 0x0063});
emplace_back(ConfigItem{"SDP:", "MX6SX", "MX6Q", FSL_VID, 0x0071});
emplace_back(ConfigItem{"SDP:", "MX6UL", "MX7D", FSL_VID, 0x007D});
emplace_back(ConfigItem{"SDP:", "MX6ULL", "MX7D", FSL_VID, 0x0080});
emplace_back(ConfigItem{"SDP:", "MX6SLL", "MX7D", NXP_VID, 0x0128});
emplace_back(ConfigItem{"SDP:", "MX7ULP", nullptr, NXP_VID, 0x0126});
emplace_back(ConfigItem{"SDP:", "MXRT106X", nullptr, NXP_VID, 0x0135});
emplace_back(ConfigItem{"SDP:", "MX8MM", "MX8MQ", NXP_VID, 0x0134});
emplace_back(ConfigItem{"SDP:", "MX8MQ", "MX8MQ", NXP_VID, 0x012B});
emplace_back(ConfigItem{"SDPU:", "SPL", "SPL", 0x0525, 0xB4A4, 0, 0x04FF});
emplace_back(ConfigItem{"SDPV:", "SPL1", "SPL", 0x0525, 0xB4A4, 0x0500, 0x9998});
emplace_back(ConfigItem{"SDPV:", "SPL1", "SPL", NXP_VID, 0x0151, 0x0500, 0x9998});
emplace_back(ConfigItem{"SDPU:", "SPL", "SPL", 0x0525, 0xB4A4, 0x9999, 0x9999}); /*old i.MX8 MQEVk use bcd 9999*/
emplace_back(ConfigItem{"SDPU:", "SPL", "SPL", BD_VID, 0x1001, 0, 0x04FF});
emplace_back(ConfigItem{"SDPV:", "SPL1", "SPL", BD_VID, 0x1001, 0x0500, 0x9998});
emplace_back(ConfigItem{"FBK:", nullptr, nullptr, 0x066F, 0x9AFE});
emplace_back(ConfigItem{"FBK:", nullptr, nullptr, 0x066F, 0x9BFF});
emplace_back(ConfigItem{"FBK:", nullptr, nullptr, NXP_VID, 0x0153});
emplace_back(ConfigItem{"FB:", nullptr, nullptr, 0x0525, 0xA4A5});
emplace_back(ConfigItem{"FB:", nullptr, nullptr, 0x18D1, 0x0D02});
emplace_back(ConfigItem{"FB:", nullptr, nullptr, BD_VID, 0x0001});
emplace_back(ConfigItem{"FB:", nullptr, nullptr, NXP_VID, 0x0152});
emplace_back(ConfigItem{"FB:", nullptr, nullptr, 0x0483, 0x0afb});
}
int uuu_for_each_cfg(uuu_show_cfg fn, void *p)
{
for (const auto &configItem : g_config)
{
if (fn(configItem.m_protocol.c_str(),
configItem.m_chip.c_str(),
configItem.m_compatible.c_str(),
configItem.m_vid,
configItem.m_pid,
configItem.m_bcdVerMin,
configItem.m_bcdVerMax,
p))
return -1;
}
return 0;
}
Config * get_config() noexcept
{
return &g_config;
}
ConfigItem * Config::find(uint16_t vid, uint16_t pid, uint16_t ver)
{
for (auto it = begin(); it != end(); it++)
{
if (vid == it->m_vid && pid == it->m_pid)
{
if (ver >= it->m_bcdVerMin && ver <= it->m_bcdVerMax)
return &(*it);
}
}
return nullptr;
}
Config Config::find(const string &pro)
{
Config items;
for (auto it = begin(); it != end(); it++)
{
if (it->m_protocol == pro)
items.emplace_back(*it);
}
return items;
}
int CfgCmd::run(CmdCtx *)
{
size_t pos = 0;
string param;
ConfigItem item;
param = get_next_param(m_cmd, pos);
if (str_to_upper(param) == "CFG:")
param = get_next_param(m_cmd, pos);
if (param.empty())
{
set_last_err_string("Wrong param");
return -1;
}
item.m_protocol = str_to_upper(param);
bool conversion_succeeded = false;
while (pos < m_cmd.size())
{
param = get_next_param(m_cmd, pos);
if (param == "-pid")
{
param = get_next_param(m_cmd, pos);
item.m_pid = str_to_uint16(param, &conversion_succeeded);
if (!conversion_succeeded) return -1;
continue;
}
if (param == "-vid")
{
param = get_next_param(m_cmd, pos);
item.m_vid = str_to_uint16(param, &conversion_succeeded);
if (!conversion_succeeded) return -1;
continue;
}
if (param == "-bcdversion")
{
param = get_next_param(m_cmd, pos);
item.m_bcdVerMin = item.m_bcdVerMax = str_to_uint16(param, &conversion_succeeded);
if (!conversion_succeeded) return -1;
continue;
}
if (param == "-bcdmin")
{
param = get_next_param(m_cmd, pos);
item.m_bcdVerMin = str_to_uint16(param, &conversion_succeeded);
if (!conversion_succeeded) return -1;
continue;
}
if (param == "-bcdmax")
{
param = get_next_param(m_cmd, pos);
item.m_bcdVerMax = str_to_uint16(param, &conversion_succeeded);
if (!conversion_succeeded) return -1;
continue;
}
if (param == "-chip")
{
param = get_next_param(m_cmd, pos);
item.m_chip = param;
continue;
}
if (param == "-compatible")
{
param = get_next_param(m_cmd, pos);
item.m_compatible = param;
continue;
}
}
ConfigItem *pItem= g_config.find(item.m_vid, item.m_pid, item.m_bcdVerMax);
if (pItem)
*pItem = item;
else
g_config.emplace_back(item);
return 0;
}
<|endoftext|> |
<commit_before>#include <QMessageBox>
#include <QCloseEvent>
#include <QMenu>
#include <QTreeWidget>
#include "about.h"
#include "settings.h"
#include "messagedialog.h"
#include "qommunicate.h"
Qommunicate::Qommunicate(QWidget *parent)
: QMainWindow(parent)
{
ui.setupUi(this);
createTrayIcon();
}
void Qommunicate::on_searchEdit_textChanged(const QString &text)
{
QMessageBox::information(this, tr("Text Changed"), text);
}
void Qommunicate::on_action_About_triggered()
{
AboutDialog(this).exec();
}
void Qommunicate::on_action_Settings_triggered()
{
SettingsDialog(this).exec();
}
void Qommunicate::on_actionBroadcast_triggered()
{
MessageDialog dlg(tr("Broadcast"));
dlg.setModal(false);
dlg.exec();
}
void Qommunicate::on_actionQuit_triggered()
{
qApp->quit();
}
void Qommunicate::closeEvent(QCloseEvent * event)
{
setVisible(false);
event->ignore();
}
void Qommunicate::iconActivated(QSystemTrayIcon::ActivationReason reason)
{
if( reason == QSystemTrayIcon::Trigger )
setVisible(!isVisible());
}
void Qommunicate::createTrayIcon()
{
trayIcon = new QSystemTrayIcon(this);
trayIcon->setIcon(windowIcon());
connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(iconActivated(QSystemTrayIcon::ActivationReason)));
QMenu *menu = new QMenu;
menu->addAction(ui.actionBroadcast);
menu->addAction(ui.actionQuit);
trayIcon->setContextMenu(menu);
trayIcon->show();
}
void Qommunicate::on_memberTree_itemDoubleClicked(QTreeWidgetItem * item, int col)
{
// TODO: subclass item and set custom types for groups and users
MessageDialog dlg(tr("Chat with %1").arg(item->data(0, Qt::DisplayRole).toString()));
dlg.setModal(false);
dlg.exec();
}<commit_msg>Member tree is now expanded by default<commit_after>#include <QMessageBox>
#include <QCloseEvent>
#include <QMenu>
#include <QTreeWidget>
#include "about.h"
#include "settings.h"
#include "messagedialog.h"
#include "qommunicate.h"
Qommunicate::Qommunicate(QWidget *parent)
: QMainWindow(parent)
{
ui.setupUi(this);
ui.memberTree->expandAll();
createTrayIcon();
}
void Qommunicate::on_searchEdit_textChanged(const QString &text)
{
QMessageBox::information(this, tr("Text Changed"), text);
}
void Qommunicate::on_action_About_triggered()
{
AboutDialog(this).exec();
}
void Qommunicate::on_action_Settings_triggered()
{
SettingsDialog(this).exec();
}
void Qommunicate::on_actionBroadcast_triggered()
{
MessageDialog dlg(tr("Broadcast"));
dlg.setModal(false);
dlg.exec();
}
void Qommunicate::on_actionQuit_triggered()
{
qApp->quit();
}
void Qommunicate::closeEvent(QCloseEvent * event)
{
setVisible(false);
event->ignore();
}
void Qommunicate::iconActivated(QSystemTrayIcon::ActivationReason reason)
{
if( reason == QSystemTrayIcon::Trigger )
setVisible(!isVisible());
}
void Qommunicate::createTrayIcon()
{
trayIcon = new QSystemTrayIcon(this);
trayIcon->setIcon(windowIcon());
connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(iconActivated(QSystemTrayIcon::ActivationReason)));
QMenu *menu = new QMenu;
menu->addAction(ui.actionBroadcast);
menu->addAction(ui.actionQuit);
trayIcon->setContextMenu(menu);
trayIcon->show();
}
void Qommunicate::on_memberTree_itemDoubleClicked(QTreeWidgetItem * item, int col)
{
// TODO: subclass item and set custom types for groups and users
MessageDialog dlg(tr("Chat with %1").arg(item->data(0, Qt::DisplayRole).toString()));
dlg.setModal(false);
dlg.exec();
}<|endoftext|> |
<commit_before>/*
* 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 Library 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Universe.cpp
* Represents a universe of DMX data
* Copyright (C) 2005-2008 Simon Newton
*
*/
#include <lla/Logging.h>
#include <llad/Port.h>
#include <llad/Universe.h>
#include "UniverseStore.h"
#include "Client.h"
#include <arpa/inet.h>
#include <iterator>
#include <algorithm>
#include <string.h>
#include <stdio.h>
namespace lla {
const string Universe::K_UNIVERSE_NAME_VAR = "universe_name";
const string Universe::K_UNIVERSE_MODE_VAR = "universe_mode";
const string Universe::K_UNIVERSE_PORT_VAR = "universe_ports";
const string Universe::K_UNIVERSE_CLIENTS_VAR = "universe_clients";
const string Universe::K_MERGE_HTP_STR = "htp";
const string Universe::K_MERGE_LTP_STR = "ltp";
/*
* Create a new universe
*
* @param uid the universe id of this universe
*/
Universe::Universe(unsigned int universe_id, UniverseStore *store,
ExportMap *export_map):
m_universe_name(""),
m_universe_id(universe_id),
m_merge_mode(Universe::MERGE_LTP),
m_universe_store(store),
m_export_map(export_map) {
stringstream universe_id_str;
universe_id_str << universe_id;
m_universe_id_str = universe_id_str.str();
UpdateName();
UpdateMode();
if (m_export_map) {
m_export_map->GetIntMapVar(K_UNIVERSE_PORT_VAR)->Set(m_universe_id_str, 0);
m_export_map->GetIntMapVar(K_UNIVERSE_CLIENTS_VAR)->Set(m_universe_id_str, 0);
}
}
/*
* Delete this universe
*/
Universe::~Universe() {
if (m_export_map) {
m_export_map->GetStringMapVar(K_UNIVERSE_NAME_VAR)->Remove(m_universe_id_str);
m_export_map->GetStringMapVar(K_UNIVERSE_MODE_VAR)->Remove(m_universe_id_str);
m_export_map->GetIntMapVar(K_UNIVERSE_PORT_VAR)->Remove(m_universe_id_str);
m_export_map->GetIntMapVar(K_UNIVERSE_CLIENTS_VAR)->Remove(m_universe_id_str);
}
}
/*
* Set the universe name
*/
void Universe::SetName(const string &name) {
m_universe_name = name;
UpdateName();
}
/*
* Set the universe merge mode
*/
void Universe::SetMergeMode(merge_mode merge_mode) {
m_merge_mode = merge_mode;
UpdateMode();
}
/*
* Add a port to this universe
* @param port the port to add
*/
bool Universe::AddPort(AbstractPort *port) {
vector<AbstractPort*>::iterator iter;
Universe *universe = port->GetUniverse();
if (universe == this)
return true;
// unpatch if required
if (universe) {
LLA_DEBUG << "Port " << port->PortId() << " is bound to universe " <<
universe->UniverseId();
universe->RemovePort(port);
}
// patch to this universe
LLA_INFO << "Patched " << port->PortId() << " to universe " << m_universe_id;
m_ports.push_back(port);
port->SetUniverse(this);
if (m_export_map) {
IntMap *map = m_export_map->GetIntMapVar(K_UNIVERSE_PORT_VAR);
map->Set(m_universe_id_str, map->Get(m_universe_id_str) + 1);
}
return true;
}
/*
* Remove a port from this universe.
* @param port the port to remove
* @return true if the port was removed, false if it didn't exist
*/
bool Universe::RemovePort(AbstractPort *port) {
vector<AbstractPort*>::iterator iter;
iter = find(m_ports.begin(), m_ports.end(), port);
if (iter != m_ports.end()) {
m_ports.erase(iter);
port->SetUniverse(NULL);
if (m_export_map) {
IntMap *map = m_export_map->GetIntMapVar(K_UNIVERSE_PORT_VAR);
map->Set(m_universe_id_str, map->Get(m_universe_id_str) - 1);
}
LLA_DEBUG << "Port " << port << " has been removed from uni " <<
m_universe_id;
} else {
LLA_DEBUG << "Could not find port in universe";
return false;
}
if (!IsActive())
m_universe_store->AddUniverseGarbageCollection(this);
return true;
}
/*
* Add this client to this universe
* @param client the client to add
*/
bool Universe::AddClient(Client *client) {
vector<Client*>::const_iterator iter = find(m_clients.begin(),
m_clients.end(),
client);
if (iter != m_clients.end())
return true;
LLA_INFO << "Added client " << client << " to universe " << m_universe_id;
m_clients.push_back(client);
if (m_export_map) {
IntMap *map = m_export_map->GetIntMapVar(K_UNIVERSE_CLIENTS_VAR);
map->Set(m_universe_id_str, map->Get(m_universe_id_str) + 1);
}
return true;
}
/*
* Remove this client from the universe. After calling this method you need to
* check if this universe is still in use, and if not delete it
* @param client the client to remove
*/
bool Universe::RemoveClient(Client *client) {
vector<Client*>::iterator iter = find(m_clients.begin(),
m_clients.end(),
client);
if (iter != m_clients.end()) {
m_clients.erase(iter);
if (m_export_map) {
IntMap *map = m_export_map->GetIntMapVar(K_UNIVERSE_CLIENTS_VAR);
map->Set(m_universe_id_str, map->Get(m_universe_id_str) - 1);
}
LLA_INFO << "Client " << client << " has been removed from uni " <<
m_universe_id;
}
if (!IsActive())
m_universe_store->AddUniverseGarbageCollection(this);
return true;
}
/*
* Returns true if the client is bound to this universe
* @param client the client to check for
*/
bool Universe::ContainsClient(class Client *client) const {
vector<Client*>::const_iterator iter = find(m_clients.begin(),
m_clients.end(),
client);
return iter != m_clients.end();
}
/*
* Set the dmx data for this universe
* @param buffer the dmx buffer with the data
* @return true is we updated all ports/clients, false otherwise
*/
bool Universe::SetDMX(const DmxBuffer &buffer) {
if (!buffer.Size()) {
LLA_INFO << "Trying to SetDMX with a 0 length dmx buffer, universe " <<
UniverseId();
return true;
}
if (m_merge_mode == Universe::MERGE_LTP) {
m_buffer = buffer;
} else {
HTPMergeAllSources();
m_buffer.HTPMerge(buffer);
}
return this->UpdateDependants();
}
/*
* Call this when the dmx in a port that is part of this universe changes
* @param port the port that has changed
*/
bool Universe::PortDataChanged(AbstractPort *port) {
vector<AbstractPort*>::const_iterator iter;
if (m_merge_mode == Universe::MERGE_LTP) {
// LTP merge mode
for (iter = m_ports.begin(); iter != m_ports.end(); ++iter) {
if (*iter == port && (*iter)->CanRead()) {
const DmxBuffer &new_buffer = (*iter)->ReadDMX();
if (new_buffer.Size())
m_buffer = new_buffer;
} else {
LLA_INFO << "Trying to update a port which isn't bound to universe: "
<< UniverseId();
}
}
} else {
// htp merge mode
HTPMergeAllSources();
}
UpdateDependants();
return true;
}
/*
* Called to indicate that data from a client has changed
*/
bool Universe::ClientDataChanged(Client *client) {
vector<Client*>::const_iterator iter;
if (m_merge_mode == Universe::MERGE_LTP) {
if (client) {
const DmxBuffer &new_buffer = client->GetDMX(m_universe_id);
if (new_buffer.Size())
m_buffer = new_buffer;
}
} else {
HTPMergeAllSources();
}
UpdateDependants();
return true;
}
/*
* Return true if this universe is in use
*/
bool Universe::IsActive() const {
return m_ports.size() > 0 || m_clients.size() > 0;
}
// Private Methods
//-----------------------------------------------------------------------------
/*
* Called when the dmx data for this universe changes,
* updates everyone who needs to know (patched ports and network clients)
*
*/
bool Universe::UpdateDependants() {
vector<AbstractPort*>::const_iterator iter;
vector<Client*>::const_iterator client_iter;
// write to all ports assigned to this unviverse
for (iter = m_ports.begin(); iter != m_ports.end(); ++iter) {
(*iter)->WriteDMX(m_buffer);
}
// write to all clients
for (client_iter = m_clients.begin(); client_iter != m_clients.end();
++client_iter) {
LLA_DEBUG << "Sending dmx data msg to client";
(*client_iter)->SendDMX(m_universe_id, m_buffer);
}
return true;
}
/*
* Update the name in the export map.
*/
void Universe::UpdateName() {
if (!m_export_map)
return;
StringMap *name_map = m_export_map->GetStringMapVar(K_UNIVERSE_NAME_VAR);
name_map->Set(m_universe_id_str, m_universe_name);
}
/*
* Update the mode in the export map.
*/
void Universe::UpdateMode() {
if (!m_export_map)
return;
StringMap *mode_map = m_export_map->GetStringMapVar(K_UNIVERSE_MODE_VAR);
mode_map->Set(m_universe_id_str,
m_merge_mode == Universe::MERGE_LTP ?
K_MERGE_LTP_STR : K_MERGE_HTP_STR);
}
/*
* HTP Merge all sources (clients/ports)
*/
bool Universe::HTPMergeAllSources() {
vector<AbstractPort*>::const_iterator iter;
vector<Client*>::const_iterator client_iter;
bool first = true;
for (iter = m_ports.begin(); iter != m_ports.end(); ++iter) {
if ((*iter)->CanRead()) {
if (first) {
m_buffer = (*iter)->ReadDMX();
first = false;
} else {
m_buffer.HTPMerge((*iter)->ReadDMX());
}
}
}
// THIS IS WRONG
// WRONG WRONG WRONG
// clients are ones we send to - not recv from
for (client_iter = m_clients.begin(); client_iter != m_clients.end();
++client_iter) {
if (first) {
m_buffer = (*client_iter)->GetDMX(m_universe_id);
first = false;
} else {
m_buffer.HTPMerge((*client_iter)->GetDMX(m_universe_id));
}
}
return true;
}
} //lla
<commit_msg> * fix the HTP merge case when we have no new data<commit_after>/*
* 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 Library 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Universe.cpp
* Represents a universe of DMX data
* Copyright (C) 2005-2008 Simon Newton
*
*/
#include <lla/Logging.h>
#include <llad/Port.h>
#include <llad/Universe.h>
#include "UniverseStore.h"
#include "Client.h"
#include <arpa/inet.h>
#include <iterator>
#include <algorithm>
#include <string.h>
#include <stdio.h>
namespace lla {
const string Universe::K_UNIVERSE_NAME_VAR = "universe_name";
const string Universe::K_UNIVERSE_MODE_VAR = "universe_mode";
const string Universe::K_UNIVERSE_PORT_VAR = "universe_ports";
const string Universe::K_UNIVERSE_CLIENTS_VAR = "universe_clients";
const string Universe::K_MERGE_HTP_STR = "htp";
const string Universe::K_MERGE_LTP_STR = "ltp";
/*
* Create a new universe
*
* @param uid the universe id of this universe
*/
Universe::Universe(unsigned int universe_id, UniverseStore *store,
ExportMap *export_map):
m_universe_name(""),
m_universe_id(universe_id),
m_merge_mode(Universe::MERGE_LTP),
m_universe_store(store),
m_export_map(export_map) {
stringstream universe_id_str;
universe_id_str << universe_id;
m_universe_id_str = universe_id_str.str();
UpdateName();
UpdateMode();
if (m_export_map) {
m_export_map->GetIntMapVar(K_UNIVERSE_PORT_VAR)->Set(m_universe_id_str, 0);
m_export_map->GetIntMapVar(K_UNIVERSE_CLIENTS_VAR)->Set(m_universe_id_str, 0);
}
}
/*
* Delete this universe
*/
Universe::~Universe() {
if (m_export_map) {
m_export_map->GetStringMapVar(K_UNIVERSE_NAME_VAR)->Remove(m_universe_id_str);
m_export_map->GetStringMapVar(K_UNIVERSE_MODE_VAR)->Remove(m_universe_id_str);
m_export_map->GetIntMapVar(K_UNIVERSE_PORT_VAR)->Remove(m_universe_id_str);
m_export_map->GetIntMapVar(K_UNIVERSE_CLIENTS_VAR)->Remove(m_universe_id_str);
}
}
/*
* Set the universe name
*/
void Universe::SetName(const string &name) {
m_universe_name = name;
UpdateName();
}
/*
* Set the universe merge mode
*/
void Universe::SetMergeMode(merge_mode merge_mode) {
m_merge_mode = merge_mode;
UpdateMode();
}
/*
* Add a port to this universe
* @param port the port to add
*/
bool Universe::AddPort(AbstractPort *port) {
vector<AbstractPort*>::iterator iter;
Universe *universe = port->GetUniverse();
if (universe == this)
return true;
// unpatch if required
if (universe) {
LLA_DEBUG << "Port " << port->PortId() << " is bound to universe " <<
universe->UniverseId();
universe->RemovePort(port);
}
// patch to this universe
LLA_INFO << "Patched " << port->PortId() << " to universe " << m_universe_id;
m_ports.push_back(port);
port->SetUniverse(this);
if (m_export_map) {
IntMap *map = m_export_map->GetIntMapVar(K_UNIVERSE_PORT_VAR);
map->Set(m_universe_id_str, map->Get(m_universe_id_str) + 1);
}
return true;
}
/*
* Remove a port from this universe.
* @param port the port to remove
* @return true if the port was removed, false if it didn't exist
*/
bool Universe::RemovePort(AbstractPort *port) {
vector<AbstractPort*>::iterator iter;
iter = find(m_ports.begin(), m_ports.end(), port);
if (iter != m_ports.end()) {
m_ports.erase(iter);
port->SetUniverse(NULL);
if (m_export_map) {
IntMap *map = m_export_map->GetIntMapVar(K_UNIVERSE_PORT_VAR);
map->Set(m_universe_id_str, map->Get(m_universe_id_str) - 1);
}
LLA_DEBUG << "Port " << port << " has been removed from uni " <<
m_universe_id;
} else {
LLA_DEBUG << "Could not find port in universe";
return false;
}
if (!IsActive())
m_universe_store->AddUniverseGarbageCollection(this);
return true;
}
/*
* Add this client to this universe
* @param client the client to add
*/
bool Universe::AddClient(Client *client) {
vector<Client*>::const_iterator iter = find(m_clients.begin(),
m_clients.end(),
client);
if (iter != m_clients.end())
return true;
LLA_INFO << "Added client " << client << " to universe " << m_universe_id;
m_clients.push_back(client);
if (m_export_map) {
IntMap *map = m_export_map->GetIntMapVar(K_UNIVERSE_CLIENTS_VAR);
map->Set(m_universe_id_str, map->Get(m_universe_id_str) + 1);
}
return true;
}
/*
* Remove this client from the universe. After calling this method you need to
* check if this universe is still in use, and if not delete it
* @param client the client to remove
*/
bool Universe::RemoveClient(Client *client) {
vector<Client*>::iterator iter = find(m_clients.begin(),
m_clients.end(),
client);
if (iter != m_clients.end()) {
m_clients.erase(iter);
if (m_export_map) {
IntMap *map = m_export_map->GetIntMapVar(K_UNIVERSE_CLIENTS_VAR);
map->Set(m_universe_id_str, map->Get(m_universe_id_str) - 1);
}
LLA_INFO << "Client " << client << " has been removed from uni " <<
m_universe_id;
}
if (!IsActive())
m_universe_store->AddUniverseGarbageCollection(this);
return true;
}
/*
* Returns true if the client is bound to this universe
* @param client the client to check for
*/
bool Universe::ContainsClient(class Client *client) const {
vector<Client*>::const_iterator iter = find(m_clients.begin(),
m_clients.end(),
client);
return iter != m_clients.end();
}
/*
* Set the dmx data for this universe
* @param buffer the dmx buffer with the data
* @return true is we updated all ports/clients, false otherwise
*/
bool Universe::SetDMX(const DmxBuffer &buffer) {
if (!buffer.Size()) {
LLA_INFO << "Trying to SetDMX with a 0 length dmx buffer, universe " <<
UniverseId();
return true;
}
if (m_merge_mode == Universe::MERGE_LTP) {
m_buffer = buffer;
} else {
HTPMergeAllSources();
m_buffer.HTPMerge(buffer);
}
return this->UpdateDependants();
}
/*
* Call this when the dmx in a port that is part of this universe changes
* @param port the port that has changed
*/
bool Universe::PortDataChanged(AbstractPort *port) {
vector<AbstractPort*>::const_iterator iter;
if (m_merge_mode == Universe::MERGE_LTP) {
// LTP merge mode
for (iter = m_ports.begin(); iter != m_ports.end(); ++iter) {
if (*iter == port && (*iter)->CanRead()) {
const DmxBuffer &new_buffer = (*iter)->ReadDMX();
if (new_buffer.Size())
m_buffer = new_buffer;
} else {
LLA_INFO << "Trying to update a port which isn't bound to universe: "
<< UniverseId();
}
}
} else {
// htp merge mode
HTPMergeAllSources();
}
UpdateDependants();
return true;
}
/*
* Called to indicate that data from a client has changed
*/
bool Universe::ClientDataChanged(Client *client) {
vector<Client*>::const_iterator iter;
if (m_merge_mode == Universe::MERGE_LTP) {
if (client) {
const DmxBuffer &new_buffer = client->GetDMX(m_universe_id);
if (new_buffer.Size())
m_buffer = new_buffer;
}
} else {
HTPMergeAllSources();
}
UpdateDependants();
return true;
}
/*
* Return true if this universe is in use
*/
bool Universe::IsActive() const {
return m_ports.size() > 0 || m_clients.size() > 0;
}
// Private Methods
//-----------------------------------------------------------------------------
/*
* Called when the dmx data for this universe changes,
* updates everyone who needs to know (patched ports and network clients)
*
*/
bool Universe::UpdateDependants() {
vector<AbstractPort*>::const_iterator iter;
vector<Client*>::const_iterator client_iter;
// write to all ports assigned to this unviverse
for (iter = m_ports.begin(); iter != m_ports.end(); ++iter) {
(*iter)->WriteDMX(m_buffer);
}
// write to all clients
for (client_iter = m_clients.begin(); client_iter != m_clients.end();
++client_iter) {
LLA_DEBUG << "Sending dmx data msg to client";
(*client_iter)->SendDMX(m_universe_id, m_buffer);
}
return true;
}
/*
* Update the name in the export map.
*/
void Universe::UpdateName() {
if (!m_export_map)
return;
StringMap *name_map = m_export_map->GetStringMapVar(K_UNIVERSE_NAME_VAR);
name_map->Set(m_universe_id_str, m_universe_name);
}
/*
* Update the mode in the export map.
*/
void Universe::UpdateMode() {
if (!m_export_map)
return;
StringMap *mode_map = m_export_map->GetStringMapVar(K_UNIVERSE_MODE_VAR);
mode_map->Set(m_universe_id_str,
m_merge_mode == Universe::MERGE_LTP ?
K_MERGE_LTP_STR : K_MERGE_HTP_STR);
}
/*
* HTP Merge all sources (clients/ports)
*/
bool Universe::HTPMergeAllSources() {
vector<AbstractPort*>::const_iterator iter;
vector<Client*>::const_iterator client_iter;
bool first = true;
for (iter = m_ports.begin(); iter != m_ports.end(); ++iter) {
if ((*iter)->CanRead()) {
if (first) {
m_buffer = (*iter)->ReadDMX();
first = false;
} else {
m_buffer.HTPMerge((*iter)->ReadDMX());
}
}
}
// THIS IS WRONG
// WRONG WRONG WRONG
// clients are ones we send to - not recv from
for (client_iter = m_clients.begin(); client_iter != m_clients.end();
++client_iter) {
if (first) {
m_buffer = (*client_iter)->GetDMX(m_universe_id);
first = false;
} else {
m_buffer.HTPMerge((*client_iter)->GetDMX(m_universe_id));
}
}
// we have no data yet, just reset the buffer
if (first) {
m_buffer.Reset();
}
return true;
}
} //lla
<|endoftext|> |
<commit_before>/*
+----------------------------------------------------------------------+
| Swoole |
+----------------------------------------------------------------------+
| This source file is subject to version 2.0 of the Apache license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.apache.org/licenses/LICENSE-2.0.html |
| If you did not receive a copy of the Apache2.0 license and are unable|
| to obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: Tianfeng Han <[email protected]> |
+----------------------------------------------------------------------+
*/
#include "swoole.h"
#include "swoole_socket.h"
#include "swoole_signal.h"
#include "swoole_reactor.h"
#include <system_error>
using swoole::CallbackManager;
using swoole::Reactor;
#ifdef SW_USE_MALLOC_TRIM
#ifdef __APPLE__
#include <sys/malloc.h>
#else
#include <malloc.h>
#endif
#endif
static void reactor_begin(swReactor *reactor);
Reactor::Reactor(int max_event) {
int ret;
#ifdef HAVE_EPOLL
ret = swReactorEpoll_create(this, max_event);
#elif defined(HAVE_KQUEUE)
ret = swReactorKqueue_create(this, max_event);
#elif defined(HAVE_POLL)
ret = swReactorPoll_create(this, max_event);
#else
ret = swReactorSelect_create(this);
#endif
if (ret < 0) {
throw std::system_error(std::error_code(errno, std::system_category()));
}
running = true;
write = swReactor_write;
close = swReactor_close;
default_write_handler = swReactor_onWrite;
if (SwooleG.hooks[SW_GLOBAL_HOOK_ON_REACTOR_CREATE]) {
swoole_call_hook(SW_GLOBAL_HOOK_ON_REACTOR_CREATE, this);
}
set_end_callback(SW_REACTOR_PRIORITY_DEFER_TASK, [](swReactor *reactor) {
CallbackManager *cm = reactor->defer_tasks;
if (cm) {
reactor->defer_tasks = nullptr;
cm->execute();
delete cm;
}
});
set_exit_condition(SW_REACTOR_EXIT_CONDITION_DEFER_TASK,
[](swReactor *reactor, int &event_num) -> bool { return reactor->defer_tasks == nullptr; });
set_end_callback(SW_REACTOR_PRIORITY_IDLE_TASK, [](swReactor *reactor) {
if (reactor->idle_task.callback) {
reactor->idle_task.callback(reactor->idle_task.data);
}
});
set_end_callback(SW_REACTOR_PRIORITY_SIGNAL_CALLBACK, [](swReactor *reactor) {
if (sw_unlikely(reactor->singal_no)) {
swSignal_callback(reactor->singal_no);
reactor->singal_no = 0;
}
});
set_end_callback(SW_REACTOR_PRIORITY_TRY_EXIT, [](swReactor *reactor) {
if (reactor->wait_exit && reactor->if_exit()) {
reactor->running = false;
}
});
#ifdef SW_USE_MALLOC_TRIM
set_end_callback(SW_REACTOR_PRIORITY_MALLOC_TRIM, [](swReactor *reactor) {
time_t now = ::time(nullptr);
if (reactor->last_malloc_trim_time < now - SW_MALLOC_TRIM_INTERVAL) {
malloc_trim(SW_MALLOC_TRIM_PAD);
reactor->last_malloc_trim_time = now;
}
});
#endif
set_exit_condition(SW_REACTOR_EXIT_CONDITION_DEFAULT,
[](swReactor *reactor, int &event_num) -> bool { return event_num == 0; });
}
bool Reactor::set_handler(int _fdtype, swReactor_handler handler) {
int fdtype = swReactor_fdtype(_fdtype);
if (fdtype >= SW_MAX_FDTYPE) {
swWarn("fdtype > SW_MAX_FDTYPE[%d]", SW_MAX_FDTYPE);
return false;
}
if (swReactor_event_read(_fdtype)) {
read_handler[fdtype] = handler;
} else if (swReactor_event_write(_fdtype)) {
write_handler[fdtype] = handler;
} else if (swReactor_event_error(_fdtype)) {
error_handler[fdtype] = handler;
} else {
swWarn("unknow fdtype");
return false;
}
return true;
}
bool Reactor::if_exit() {
int _event_num = event_num;
for (auto &kv : exit_conditions) {
if (kv.second(this, _event_num) == false) {
return false;
}
}
return true;
}
void swReactor_activate_future_task(swReactor *reactor) {
reactor->onBegin = reactor_begin;
}
static void reactor_begin(swReactor *reactor) {
if (reactor->future_task.callback) {
reactor->future_task.callback(reactor->future_task.data);
}
}
int swReactor_close(swReactor *reactor, swSocket *socket) {
if (socket->out_buffer) {
swBuffer_free(socket->out_buffer);
socket->out_buffer = nullptr;
}
if (socket->in_buffer) {
swBuffer_free(socket->in_buffer);
socket->in_buffer = nullptr;
}
swTraceLog(SW_TRACE_CLOSE, "fd=%d", socket->fd);
socket->free();
return SW_OK;
}
int swReactor_write(swReactor *reactor, swSocket *socket, const void *buf, int n) {
int ret;
swBuffer *buffer = socket->out_buffer;
const char *ptr = (const char *) buf;
int fd = socket->fd;
if (socket->buffer_size == 0) {
socket->buffer_size = swoole::network::Socket::default_buffer_size;;
}
if (socket->nonblock == 0) {
swoole_fcntl_set_option(socket->fd, 1, -1);
socket->nonblock = 1;
}
if ((uint32_t) n > socket->buffer_size) {
swoole_error_log(
SW_LOG_WARNING, SW_ERROR_PACKAGE_LENGTH_TOO_LARGE, "data is too large, cannot exceed buffer size");
return SW_ERR;
}
if (swBuffer_empty(buffer)) {
#ifdef SW_USE_OPENSSL
if (socket->ssl_send) {
goto _do_buffer;
}
#endif
_do_send:
ret = socket->send(ptr, n, 0);
if (ret > 0) {
if (n == ret) {
return ret;
} else {
ptr += ret;
n -= ret;
goto _do_buffer;
}
} else if (socket->catch_error(errno) == SW_WAIT) {
_do_buffer:
if (!socket->out_buffer) {
buffer = swBuffer_new(socket->chunk_size);
if (!buffer) {
swWarn("create worker buffer failed");
return SW_ERR;
}
socket->out_buffer = buffer;
}
reactor->add_write_event(socket);
goto _append_buffer;
} else if (errno == EINTR) {
goto _do_send;
} else {
swoole_set_last_error(errno);
return SW_ERR;
}
} else {
_append_buffer:
if (buffer->length > socket->buffer_size) {
if (socket->dontwait) {
swoole_set_last_error(SW_ERROR_OUTPUT_BUFFER_OVERFLOW);
return SW_ERR;
} else {
swoole_error_log(
SW_LOG_WARNING, SW_ERROR_OUTPUT_BUFFER_OVERFLOW, "socket#%d output buffer overflow", fd);
swYield();
socket->wait_event(SW_SOCKET_OVERFLOW_WAIT, SW_EVENT_WRITE);
}
}
if (swBuffer_append(buffer, ptr, n) < 0) {
return SW_ERR;
}
}
return SW_OK;
}
int swReactor_onWrite(swReactor *reactor, swEvent *ev) {
int ret;
swSocket *socket = ev->socket;
swBuffer_chunk *chunk = nullptr;
swBuffer *buffer = socket->out_buffer;
// send to socket
while (!swBuffer_empty(buffer)) {
chunk = swBuffer_get_chunk(buffer);
if (chunk->type == SW_CHUNK_CLOSE) {
_close_fd:
reactor->close(reactor, ev->socket);
return SW_OK;
} else if (chunk->type == SW_CHUNK_SENDFILE) {
ret = socket->handle_sendfile(chunk);
} else {
ret = socket->handle_send();
}
if (ret < 0) {
if (socket->close_wait) {
goto _close_fd;
} else if (socket->send_wait) {
return SW_OK;
}
}
}
// remove EPOLLOUT event
if (swBuffer_empty(buffer)) {
reactor->remove_write_event(ev->socket);
}
return SW_OK;
}
void Reactor::drain_write_buffer(swSocket *socket) {
swEvent event = { };
event.socket = socket;
event.fd = socket->fd;
while (!swBuffer_empty(socket->out_buffer)) {
if (socket->wait_event(network::Socket::default_write_timeout, SW_EVENT_WRITE) == SW_ERR) {
break;
}
swReactor_onWrite(this, &event);
if (socket->close_wait || socket->removed) {
break;
}
}
}
void Reactor::add_destroy_callback(swCallback cb, void *data) {
destroy_callbacks.append(cb, data);
}
void Reactor::set_end_callback(enum swReactor_end_callback id, const std::function<void(Reactor *)> &fn) {
end_callbacks[id] = fn;
}
void Reactor::set_exit_condition(enum swReactor_exit_condition id, const std::function<bool(Reactor *, int &)> &fn) {
exit_conditions[id] = fn;
}
void Reactor::defer(swCallback cb, void *data) {
if (defer_tasks == nullptr) {
defer_tasks = new CallbackManager;
}
defer_tasks->append(cb, data);
}
void Reactor::execute_end_callbacks(bool timedout) {
for (auto &kv : end_callbacks) {
kv.second(this);
}
}
Reactor::~Reactor() {
destroyed = true;
destroy_callbacks.execute();
free(this);
}
<commit_msg>Fix undefined symbol (#3538)<commit_after>/*
+----------------------------------------------------------------------+
| Swoole |
+----------------------------------------------------------------------+
| This source file is subject to version 2.0 of the Apache license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.apache.org/licenses/LICENSE-2.0.html |
| If you did not receive a copy of the Apache2.0 license and are unable|
| to obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: Tianfeng Han <[email protected]> |
+----------------------------------------------------------------------+
*/
#include "swoole.h"
#include "swoole_socket.h"
#include "swoole_signal.h"
#include "swoole_reactor.h"
#include <system_error>
using swoole::CallbackManager;
using swoole::Reactor;
#ifdef SW_USE_MALLOC_TRIM
#ifdef __APPLE__
#include <sys/malloc.h>
#else
#include <malloc.h>
#endif
#endif
static void reactor_begin(swReactor *reactor);
Reactor::Reactor(int max_event) {
int ret;
#ifdef HAVE_EPOLL
ret = swReactorEpoll_create(this, max_event);
#elif defined(HAVE_KQUEUE)
ret = swReactorKqueue_create(this, max_event);
#elif defined(HAVE_POLL)
ret = swReactorPoll_create(this, max_event);
#else
ret = swReactorSelect_create(this);
#endif
if (ret < 0) {
throw std::system_error(std::error_code(errno, std::system_category()));
}
running = true;
write = swReactor_write;
close = swReactor_close;
default_write_handler = swReactor_onWrite;
if (SwooleG.hooks[SW_GLOBAL_HOOK_ON_REACTOR_CREATE]) {
swoole_call_hook(SW_GLOBAL_HOOK_ON_REACTOR_CREATE, this);
}
set_end_callback(SW_REACTOR_PRIORITY_DEFER_TASK, [](swReactor *reactor) {
CallbackManager *cm = reactor->defer_tasks;
if (cm) {
reactor->defer_tasks = nullptr;
cm->execute();
delete cm;
}
});
set_exit_condition(SW_REACTOR_EXIT_CONDITION_DEFER_TASK,
[](swReactor *reactor, int &event_num) -> bool { return reactor->defer_tasks == nullptr; });
set_end_callback(SW_REACTOR_PRIORITY_IDLE_TASK, [](swReactor *reactor) {
if (reactor->idle_task.callback) {
reactor->idle_task.callback(reactor->idle_task.data);
}
});
set_end_callback(SW_REACTOR_PRIORITY_SIGNAL_CALLBACK, [](swReactor *reactor) {
if (sw_unlikely(reactor->singal_no)) {
swSignal_callback(reactor->singal_no);
reactor->singal_no = 0;
}
});
set_end_callback(SW_REACTOR_PRIORITY_TRY_EXIT, [](swReactor *reactor) {
if (reactor->wait_exit && reactor->if_exit()) {
reactor->running = false;
}
});
#ifdef SW_USE_MALLOC_TRIM
set_end_callback(SW_REACTOR_PRIORITY_MALLOC_TRIM, [](swReactor *reactor) {
time_t now = ::time(nullptr);
if (reactor->last_malloc_trim_time < now - SW_MALLOC_TRIM_INTERVAL) {
malloc_trim(SW_MALLOC_TRIM_PAD);
reactor->last_malloc_trim_time = now;
}
});
#endif
set_exit_condition(SW_REACTOR_EXIT_CONDITION_DEFAULT,
[](swReactor *reactor, int &event_num) -> bool { return event_num == 0; });
}
bool Reactor::set_handler(int _fdtype, swReactor_handler handler) {
int fdtype = swReactor_fdtype(_fdtype);
if (fdtype >= SW_MAX_FDTYPE) {
swWarn("fdtype > SW_MAX_FDTYPE[%d]", SW_MAX_FDTYPE);
return false;
}
if (swReactor_event_read(_fdtype)) {
read_handler[fdtype] = handler;
} else if (swReactor_event_write(_fdtype)) {
write_handler[fdtype] = handler;
} else if (swReactor_event_error(_fdtype)) {
error_handler[fdtype] = handler;
} else {
swWarn("unknow fdtype");
return false;
}
return true;
}
bool Reactor::if_exit() {
int _event_num = event_num;
for (auto &kv : exit_conditions) {
if (kv.second(this, _event_num) == false) {
return false;
}
}
return true;
}
void Reactor::activate_future_task() {
onBegin = reactor_begin;
}
static void reactor_begin(swReactor *reactor) {
if (reactor->future_task.callback) {
reactor->future_task.callback(reactor->future_task.data);
}
}
int swReactor_close(swReactor *reactor, swSocket *socket) {
if (socket->out_buffer) {
swBuffer_free(socket->out_buffer);
socket->out_buffer = nullptr;
}
if (socket->in_buffer) {
swBuffer_free(socket->in_buffer);
socket->in_buffer = nullptr;
}
swTraceLog(SW_TRACE_CLOSE, "fd=%d", socket->fd);
socket->free();
return SW_OK;
}
int swReactor_write(swReactor *reactor, swSocket *socket, const void *buf, int n) {
int ret;
swBuffer *buffer = socket->out_buffer;
const char *ptr = (const char *) buf;
int fd = socket->fd;
if (socket->buffer_size == 0) {
socket->buffer_size = swoole::network::Socket::default_buffer_size;;
}
if (socket->nonblock == 0) {
swoole_fcntl_set_option(socket->fd, 1, -1);
socket->nonblock = 1;
}
if ((uint32_t) n > socket->buffer_size) {
swoole_error_log(
SW_LOG_WARNING, SW_ERROR_PACKAGE_LENGTH_TOO_LARGE, "data is too large, cannot exceed buffer size");
return SW_ERR;
}
if (swBuffer_empty(buffer)) {
#ifdef SW_USE_OPENSSL
if (socket->ssl_send) {
goto _do_buffer;
}
#endif
_do_send:
ret = socket->send(ptr, n, 0);
if (ret > 0) {
if (n == ret) {
return ret;
} else {
ptr += ret;
n -= ret;
goto _do_buffer;
}
} else if (socket->catch_error(errno) == SW_WAIT) {
_do_buffer:
if (!socket->out_buffer) {
buffer = swBuffer_new(socket->chunk_size);
if (!buffer) {
swWarn("create worker buffer failed");
return SW_ERR;
}
socket->out_buffer = buffer;
}
reactor->add_write_event(socket);
goto _append_buffer;
} else if (errno == EINTR) {
goto _do_send;
} else {
swoole_set_last_error(errno);
return SW_ERR;
}
} else {
_append_buffer:
if (buffer->length > socket->buffer_size) {
if (socket->dontwait) {
swoole_set_last_error(SW_ERROR_OUTPUT_BUFFER_OVERFLOW);
return SW_ERR;
} else {
swoole_error_log(
SW_LOG_WARNING, SW_ERROR_OUTPUT_BUFFER_OVERFLOW, "socket#%d output buffer overflow", fd);
swYield();
socket->wait_event(SW_SOCKET_OVERFLOW_WAIT, SW_EVENT_WRITE);
}
}
if (swBuffer_append(buffer, ptr, n) < 0) {
return SW_ERR;
}
}
return SW_OK;
}
int swReactor_onWrite(swReactor *reactor, swEvent *ev) {
int ret;
swSocket *socket = ev->socket;
swBuffer_chunk *chunk = nullptr;
swBuffer *buffer = socket->out_buffer;
// send to socket
while (!swBuffer_empty(buffer)) {
chunk = swBuffer_get_chunk(buffer);
if (chunk->type == SW_CHUNK_CLOSE) {
_close_fd:
reactor->close(reactor, ev->socket);
return SW_OK;
} else if (chunk->type == SW_CHUNK_SENDFILE) {
ret = socket->handle_sendfile(chunk);
} else {
ret = socket->handle_send();
}
if (ret < 0) {
if (socket->close_wait) {
goto _close_fd;
} else if (socket->send_wait) {
return SW_OK;
}
}
}
// remove EPOLLOUT event
if (swBuffer_empty(buffer)) {
reactor->remove_write_event(ev->socket);
}
return SW_OK;
}
void Reactor::drain_write_buffer(swSocket *socket) {
swEvent event = { };
event.socket = socket;
event.fd = socket->fd;
while (!swBuffer_empty(socket->out_buffer)) {
if (socket->wait_event(network::Socket::default_write_timeout, SW_EVENT_WRITE) == SW_ERR) {
break;
}
swReactor_onWrite(this, &event);
if (socket->close_wait || socket->removed) {
break;
}
}
}
void Reactor::add_destroy_callback(swCallback cb, void *data) {
destroy_callbacks.append(cb, data);
}
void Reactor::set_end_callback(enum swReactor_end_callback id, const std::function<void(Reactor *)> &fn) {
end_callbacks[id] = fn;
}
void Reactor::set_exit_condition(enum swReactor_exit_condition id, const std::function<bool(Reactor *, int &)> &fn) {
exit_conditions[id] = fn;
}
void Reactor::defer(swCallback cb, void *data) {
if (defer_tasks == nullptr) {
defer_tasks = new CallbackManager;
}
defer_tasks->append(cb, data);
}
void Reactor::execute_end_callbacks(bool timedout) {
for (auto &kv : end_callbacks) {
kv.second(this);
}
}
Reactor::~Reactor() {
destroyed = true;
destroy_callbacks.execute();
free(this);
}
<|endoftext|> |
<commit_before>/*
This file is part of the kblog library.
Copyright (c) 2007 Christian Weilbach <[email protected]>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include <gdata_p.h>
#include <syndication/loader.h>
#include <syndication/item.h>
#include <kdebug.h>
#include <kio/netaccess.h>
#include <kio/http.h>
#include <klocale.h>
#include <kdatetime.h>
#include <kurl.h>
#include <QtCore/QByteArray>
#include <QtCore/QRegExp>
#include <QtGui/QWidget>
#define TIMEOUT 600
using namespace KBlog;
APIGData::APIGDataPrivate::APIGDataPrivate():
mAuthenticationTime(),mAuthenticationString(),mFetchPostingId(){
}
APIGData::APIGDataPrivate::~APIGDataPrivate(){
}
QString APIGData::APIGDataPrivate::authenticate(){
QByteArray data;
KUrl authGateway( "https://www.google.com/accounts/ClientLogin" );
authGateway.addQueryItem( "Email", parent->username() );
authGateway.addQueryItem( "Passwd", parent->password() );
authGateway.addQueryItem( "source" , "KBlog" );
authGateway.addQueryItem( "service", "blogger" );
if( !mAuthenticationTime.isValid() ||
QDateTime::currentDateTime().toTime_t() - mAuthenticationTime.toTime_t() > TIMEOUT ||
mAuthenticationString.isEmpty() ){
KIO::Job *job = KIO::http_post( authGateway, QByteArray(), false );
job->addMetaData( "content-length", "0" );
if ( KIO::NetAccess::synchronousRun( job, (QWidget*)0, &data, &authGateway ) ) {
kDebug(5323) << "Fetched authentication result for " << authGateway.prettyUrl() << ". " << endl;
kDebug(5323) << "Authentication response " << data << endl;
QRegExp rx( "Auth=(.+)" );
if( rx.indexIn( data )!=-1 ){
kDebug(5323)<<"RegExp got authentication string: " << rx.cap(1) << endl;
mAuthenticationString = rx.cap(1);
mAuthenticationTime = QDateTime::currentDateTime();
return mAuthenticationString;
}
}
return QString();
}
return mAuthenticationString;
}
void APIGData::APIGDataPrivate::slotLoadingBlogsComplete( Syndication::Loader* loader,
Syndication::FeedPtr feed, Syndication::ErrorCode status ){
if (status != Syndication::Success){
emit parent->error( AtomAPI, i18n( "Could not get blogs." ) );
return;
}
QList<Syndication::ItemPtr> items = feed->items();
QList<Syndication::ItemPtr>::ConstIterator it = items.begin();
QList<Syndication::ItemPtr>::ConstIterator end = items.end();
for( ; it!=end; ++it ){
QRegExp rx( "blog-(\\d+)" );
QString id, name;
if( rx.indexIn( ( *it )->id() )!=-1 ){
kDebug(5323)<<"QRegExp rx( 'blog-(\\d+)' matches "<< rx.cap(1) << endl;
id = rx.cap(1);
name = ( *it )->title();
}
else{
emit parent->error( Other, i18n( "Could not regexp the blog id path." ) );
kDebug(5323)<<"QRegExp rx( 'blog-(\\d+)' does not match anything in: "<< ( *it )->id() << endl;
}
if ( !id.isEmpty() && !name.isEmpty() ) {
emit parent->blogInfoRetrieved( id, name );
kDebug(5323) << "Emitting blogInfoRetrieved( id=" << id
<< ", name=" << name << "); " << endl;
}
}
}
void APIGData::APIGDataPrivate::slotLoadingPostingsComplete( Syndication::Loader* loader,
Syndication::FeedPtr feed, Syndication::ErrorCode status ){
if (status != Syndication::Success){
emit parent->error( AtomAPI, i18n( "Could not get postings." ) );
return;
}
QList<Syndication::ItemPtr> items = feed->items();
QList<Syndication::ItemPtr>::ConstIterator it = items.begin();
QList<Syndication::ItemPtr>::ConstIterator end = items.end();
for( ; it!=end; ++it ){
BlogPosting posting;
QRegExp rx( "post-(\\d+)" );
if( rx.indexIn( ( *it )->id() )==-1 ){
kDebug(5323)<<"QRegExp rx( 'post-(\\d+)' does not match "<< rx.cap(1) << endl;
emit parent->error( Other, i18n( "Could not regexp the posting id path." ) );
return;
}
kDebug(5323)<<"QRegExp rx( 'post-(\\d+)' matches "<< rx.cap(1) << endl;
posting.setPostingId( rx.cap(1) );
posting.setTitle( ( *it )->title() );
posting.setContent( ( *it )->content() );
// FIXME: assuming UTC for now
posting.setCreationDateTime( KDateTime( QDateTime::fromTime_t( ( *it )->datePublished() ), KDateTime::Spec::UTC() ) );
posting.setModificationDateTime( KDateTime( QDateTime::fromTime_t( ( *it )->dateUpdated() ), KDateTime::Spec::UTC() ) );
emit parent->listedPosting( posting );
kDebug(5323) << "Emitting listedPosting( postingId=" << posting.postingId() << " ); " << endl;
}
kDebug(5323) << "Emitting listPostingsFinished()" << endl;
emit parent->listPostingsFinished();
}
void APIGData::APIGDataPrivate::slotFetchingPostingComplete( Syndication::Loader* loader,
Syndication::FeedPtr feed, Syndication::ErrorCode status ){
bool success = false;
if (status != Syndication::Success){
emit parent->error( AtomAPI, i18n( "Could not get postings." ) );
return;
}
QList<Syndication::ItemPtr> items = feed->items();
QList<Syndication::ItemPtr>::ConstIterator it = items.begin();
QList<Syndication::ItemPtr>::ConstIterator end = items.end();
for( ; it!=end; ++it ){
BlogPosting posting;
QRegExp rx( "post-(\\d+)" );
if( rx.indexIn( ( *it )->id() )!=-1 && rx.cap(1)==getFetchPostingId() ){
kDebug(5323)<<"QRegExp rx( 'post-(\\d+)' matches "<< rx.cap(1) << endl;
posting.setPostingId( rx.cap(1) );
posting.setTitle( ( *it )->title() );
posting.setContent( ( *it )->content() );
// FIXME: assuming UTC for now
posting.setCreationDateTime( KDateTime( QDateTime::fromTime_t( ( *it )->datePublished() ),
KDateTime::Spec::UTC() ) );
posting.setModificationDateTime( KDateTime( QDateTime::fromTime_t( ( *it )->dateUpdated() ),
KDateTime::Spec::UTC() ) );
emit parent->fetchedPosting( posting );
success = true;
kDebug(5323) << "Emitting fetchedPosting( postingId=" << posting.postingId() << " ); " << endl;
}
}
if(!success){
emit parent->error( Other, i18n( "Could not regexp the blog id path." ) );
kDebug(5323) << "QRegExp rx( 'post-(\\d+)' does not match " << mFetchPostingId << ". " << endl;
}
setFetchPostingId( "" );
}
#include "gdata_p.moc"<commit_msg>fix initialization order<commit_after>/*
This file is part of the kblog library.
Copyright (c) 2007 Christian Weilbach <[email protected]>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include <gdata_p.h>
#include <syndication/loader.h>
#include <syndication/item.h>
#include <kdebug.h>
#include <kio/netaccess.h>
#include <kio/http.h>
#include <klocale.h>
#include <kdatetime.h>
#include <kurl.h>
#include <QtCore/QByteArray>
#include <QtCore/QRegExp>
#include <QtGui/QWidget>
#define TIMEOUT 600
using namespace KBlog;
APIGData::APIGDataPrivate::APIGDataPrivate():
mFetchPostingId(),mAuthenticationString(),mAuthenticationTime(){
}
APIGData::APIGDataPrivate::~APIGDataPrivate(){
}
QString APIGData::APIGDataPrivate::authenticate(){
QByteArray data;
KUrl authGateway( "https://www.google.com/accounts/ClientLogin" );
authGateway.addQueryItem( "Email", parent->username() );
authGateway.addQueryItem( "Passwd", parent->password() );
authGateway.addQueryItem( "source" , "KBlog" );
authGateway.addQueryItem( "service", "blogger" );
if( !mAuthenticationTime.isValid() ||
QDateTime::currentDateTime().toTime_t() - mAuthenticationTime.toTime_t() > TIMEOUT ||
mAuthenticationString.isEmpty() ){
KIO::Job *job = KIO::http_post( authGateway, QByteArray(), false );
job->addMetaData( "content-length", "0" );
if ( KIO::NetAccess::synchronousRun( job, (QWidget*)0, &data, &authGateway ) ) {
kDebug(5323) << "Fetched authentication result for " << authGateway.prettyUrl() << ". " << endl;
kDebug(5323) << "Authentication response " << data << endl;
QRegExp rx( "Auth=(.+)" );
if( rx.indexIn( data )!=-1 ){
kDebug(5323)<<"RegExp got authentication string: " << rx.cap(1) << endl;
mAuthenticationString = rx.cap(1);
mAuthenticationTime = QDateTime::currentDateTime();
return mAuthenticationString;
}
}
return QString();
}
return mAuthenticationString;
}
void APIGData::APIGDataPrivate::slotLoadingBlogsComplete( Syndication::Loader* loader,
Syndication::FeedPtr feed, Syndication::ErrorCode status ){
if (status != Syndication::Success){
emit parent->error( AtomAPI, i18n( "Could not get blogs." ) );
return;
}
QList<Syndication::ItemPtr> items = feed->items();
QList<Syndication::ItemPtr>::ConstIterator it = items.begin();
QList<Syndication::ItemPtr>::ConstIterator end = items.end();
for( ; it!=end; ++it ){
QRegExp rx( "blog-(\\d+)" );
QString id, name;
if( rx.indexIn( ( *it )->id() )!=-1 ){
kDebug(5323)<<"QRegExp rx( 'blog-(\\d+)' matches "<< rx.cap(1) << endl;
id = rx.cap(1);
name = ( *it )->title();
}
else{
emit parent->error( Other, i18n( "Could not regexp the blog id path." ) );
kDebug(5323)<<"QRegExp rx( 'blog-(\\d+)' does not match anything in: "<< ( *it )->id() << endl;
}
if ( !id.isEmpty() && !name.isEmpty() ) {
emit parent->blogInfoRetrieved( id, name );
kDebug(5323) << "Emitting blogInfoRetrieved( id=" << id
<< ", name=" << name << "); " << endl;
}
}
}
void APIGData::APIGDataPrivate::slotLoadingPostingsComplete( Syndication::Loader* loader,
Syndication::FeedPtr feed, Syndication::ErrorCode status ){
if (status != Syndication::Success){
emit parent->error( AtomAPI, i18n( "Could not get postings." ) );
return;
}
QList<Syndication::ItemPtr> items = feed->items();
QList<Syndication::ItemPtr>::ConstIterator it = items.begin();
QList<Syndication::ItemPtr>::ConstIterator end = items.end();
for( ; it!=end; ++it ){
BlogPosting posting;
QRegExp rx( "post-(\\d+)" );
if( rx.indexIn( ( *it )->id() )==-1 ){
kDebug(5323)<<"QRegExp rx( 'post-(\\d+)' does not match "<< rx.cap(1) << endl;
emit parent->error( Other, i18n( "Could not regexp the posting id path." ) );
return;
}
kDebug(5323)<<"QRegExp rx( 'post-(\\d+)' matches "<< rx.cap(1) << endl;
posting.setPostingId( rx.cap(1) );
posting.setTitle( ( *it )->title() );
posting.setContent( ( *it )->content() );
// FIXME: assuming UTC for now
posting.setCreationDateTime( KDateTime( QDateTime::fromTime_t( ( *it )->datePublished() ), KDateTime::Spec::UTC() ) );
posting.setModificationDateTime( KDateTime( QDateTime::fromTime_t( ( *it )->dateUpdated() ), KDateTime::Spec::UTC() ) );
emit parent->listedPosting( posting );
kDebug(5323) << "Emitting listedPosting( postingId=" << posting.postingId() << " ); " << endl;
}
kDebug(5323) << "Emitting listPostingsFinished()" << endl;
emit parent->listPostingsFinished();
}
void APIGData::APIGDataPrivate::slotFetchingPostingComplete( Syndication::Loader* loader,
Syndication::FeedPtr feed, Syndication::ErrorCode status ){
bool success = false;
if (status != Syndication::Success){
emit parent->error( AtomAPI, i18n( "Could not get postings." ) );
return;
}
QList<Syndication::ItemPtr> items = feed->items();
QList<Syndication::ItemPtr>::ConstIterator it = items.begin();
QList<Syndication::ItemPtr>::ConstIterator end = items.end();
for( ; it!=end; ++it ){
BlogPosting posting;
QRegExp rx( "post-(\\d+)" );
if( rx.indexIn( ( *it )->id() )!=-1 && rx.cap(1)==getFetchPostingId() ){
kDebug(5323)<<"QRegExp rx( 'post-(\\d+)' matches "<< rx.cap(1) << endl;
posting.setPostingId( rx.cap(1) );
posting.setTitle( ( *it )->title() );
posting.setContent( ( *it )->content() );
// FIXME: assuming UTC for now
posting.setCreationDateTime( KDateTime( QDateTime::fromTime_t( ( *it )->datePublished() ),
KDateTime::Spec::UTC() ) );
posting.setModificationDateTime( KDateTime( QDateTime::fromTime_t( ( *it )->dateUpdated() ),
KDateTime::Spec::UTC() ) );
emit parent->fetchedPosting( posting );
success = true;
kDebug(5323) << "Emitting fetchedPosting( postingId=" << posting.postingId() << " ); " << endl;
}
}
if(!success){
emit parent->error( Other, i18n( "Could not regexp the blog id path." ) );
kDebug(5323) << "QRegExp rx( 'post-(\\d+)' does not match " << mFetchPostingId << ". " << endl;
}
setFetchPostingId( "" );
}
#include "gdata_p.moc"
<|endoftext|> |
<commit_before>//
// Copyright (c) 2009, Markus Rickert
// 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.
//
// 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 "Rrt.h"
#include "Sampler.h"
#include "SimpleModel.h"
#include "Viewer.h"
namespace rl
{
namespace plan
{
Rrt::Rrt(const ::std::size_t& trees) :
Planner(),
delta(1.0f),
epsilon(1.0e-3f),
sampler(nullptr),
begin(trees, nullptr),
end(trees, nullptr),
tree(trees)
{
}
Rrt::~Rrt()
{
}
Rrt::Edge
Rrt::addEdge(const Vertex& u, const Vertex& v, Tree& tree)
{
Edge e = ::boost::add_edge(u, v, tree).first;
if (nullptr != this->viewer)
{
this->viewer->drawConfigurationEdge(*get(tree, u)->q, *get(tree, v)->q);
}
return e;
}
Rrt::Vertex
Rrt::addVertex(Tree& tree, const VectorPtr& q)
{
::std::shared_ptr<VertexBundle> bundle = ::std::make_shared<VertexBundle>();
bundle->index = ::boost::num_vertices(tree) - 1;
bundle->q = q;
Vertex v = ::boost::add_vertex(tree);
tree[v] = bundle;
tree[::boost::graph_bundle].nn->push(Metric::Value(q.get(), v));
if (nullptr != this->viewer)
{
this->viewer->drawConfigurationVertex(*get(tree, v)->q);
}
return v;
}
bool
Rrt::areEqual(const ::rl::math::Vector& lhs, const ::rl::math::Vector& rhs) const
{
if (this->model->distance(lhs, rhs) > this->epsilon)
{
return false;
}
else
{
return true;
}
}
::rl::math::Vector
Rrt::choose()
{
return this->sampler->generate();
}
Rrt::Vertex
Rrt::connect(Tree& tree, const Neighbor& nearest, const ::rl::math::Vector& chosen)
{
::rl::math::Real distance = nearest.first;
::rl::math::Real step = distance;
bool reached = false;
if (step <= this->delta)
{
reached = true;
}
else
{
step = this->delta;
}
VectorPtr last = ::std::make_shared< ::rl::math::Vector>(this->model->getDofPosition());
this->model->interpolate(*get(tree, nearest.second)->q, chosen, step / distance, *last);
if (nullptr != this->viewer)
{
// this->viewer->drawConfiguration(*last);
}
this->model->setPosition(*last);
this->model->updateFrames();
if (this->model->isColliding())
{
return nullptr;
}
::rl::math::Vector next(this->model->getDofPosition());
while (!reached)
{
distance = this->model->distance(*last, chosen);
step = distance;
if (step <= this->delta)
{
reached = true;
}
else
{
step = this->delta;
}
this->model->interpolate(*last, chosen, step / distance, next);
if (nullptr != this->viewer)
{
// this->viewer->drawConfiguration(next);
}
this->model->setPosition(next);
this->model->updateFrames();
if (this->model->isColliding())
{
break;
}
*last = next;
}
Vertex connected = this->addVertex(tree, last);
this->addEdge(nearest.second, connected, tree);
return connected;
}
Rrt::Vertex
Rrt::extend(Tree& tree, const Neighbor& nearest, const ::rl::math::Vector& chosen)
{
::rl::math::Real distance = nearest.first;
::rl::math::Real step = ::std::min(distance, this->delta);
VectorPtr next = ::std::make_shared< ::rl::math::Vector>(this->model->getDofPosition());
this->model->interpolate(*get(tree, nearest.second)->q, chosen, step / distance, *next);
this->model->setPosition(*next);
this->model->updateFrames();
if (!this->model->isColliding())
{
Vertex extended = this->addVertex(tree, next);
this->addEdge(nearest.second, extended, tree);
return extended;
}
return nullptr;
}
Rrt::VertexBundle*
Rrt::get(const Tree& tree, const Vertex& v)
{
return tree[v].get();
}
::std::string
Rrt::getName() const
{
return "RRT";
}
NearestNeighbors*
Rrt::getNearestNeighbors(const ::std::size_t& i) const
{
return this->tree[i][::boost::graph_bundle].nn;
}
::std::size_t
Rrt::getNumEdges() const
{
::std::size_t edges = 0;
for (::std::size_t i = 0; i < this->tree.size(); ++i)
{
edges += ::boost::num_edges(this->tree[i]);
}
return edges;
}
::std::size_t
Rrt::getNumVertices() const
{
::std::size_t vertices = 0;
for (::std::size_t i = 0; i < this->tree.size(); ++i)
{
vertices += ::boost::num_vertices(this->tree[i]);
}
return vertices;
}
VectorList
Rrt::getPath()
{
VectorList path;
Vertex i = this->end[0];
while (i != this->begin[0])
{
path.push_front(*get(this->tree[0], i)->q);
i = ::boost::source(*::boost::in_edges(i, this->tree[0]).first, this->tree[0]);
}
path.push_front(*get(this->tree[0], i)->q);
return path;
}
Rrt::Neighbor
Rrt::nearest(const Tree& tree, const ::rl::math::Vector& chosen)
{
::std::vector<NearestNeighbors::Neighbor> neighbors = tree[::boost::graph_bundle].nn->nearest(Metric::Value(&chosen, Vertex()), 1);
return Neighbor(
tree[::boost::graph_bundle].nn->isTransformedDistance() ? this->model->inverseOfTransformedDistance(neighbors.front().first) : neighbors.front().first,
neighbors.front().second.second
);
}
void
Rrt::reset()
{
for (::std::size_t i = 0; i < this->tree.size(); ++i)
{
this->tree[i].clear();
this->tree[i][::boost::graph_bundle].nn->clear();
this->begin[i] = nullptr;
this->end[i] = nullptr;
}
}
void
Rrt::setNearestNeighbors(NearestNeighbors* nearestNeighbors, const ::std::size_t& i)
{
this->tree[i][::boost::graph_bundle].nn = nearestNeighbors;
}
bool
Rrt::solve()
{
this->time = ::std::chrono::steady_clock::now();
this->begin[0] = this->addVertex(this->tree[0], ::std::make_shared< ::rl::math::Vector>(*this->start));
while ((::std::chrono::steady_clock::now() - this->time) < this->duration)
{
::rl::math::Vector chosen = this->choose();
Neighbor nearest = this->nearest(this->tree[0], chosen);
Vertex extended = this->extend(this->tree[0], nearest, chosen);
if (nullptr != extended)
{
if (this->areEqual(*get(this->tree[0], extended)->q, *this->goal))
{
this->end[0] = extended;
return true;
}
}
}
return false;
}
}
}
<commit_msg>Remove extra distance call in RRT connect<commit_after>//
// Copyright (c) 2009, Markus Rickert
// 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.
//
// 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 "Rrt.h"
#include "Sampler.h"
#include "SimpleModel.h"
#include "Viewer.h"
namespace rl
{
namespace plan
{
Rrt::Rrt(const ::std::size_t& trees) :
Planner(),
delta(1.0f),
epsilon(1.0e-3f),
sampler(nullptr),
begin(trees, nullptr),
end(trees, nullptr),
tree(trees)
{
}
Rrt::~Rrt()
{
}
Rrt::Edge
Rrt::addEdge(const Vertex& u, const Vertex& v, Tree& tree)
{
Edge e = ::boost::add_edge(u, v, tree).first;
if (nullptr != this->viewer)
{
this->viewer->drawConfigurationEdge(*get(tree, u)->q, *get(tree, v)->q);
}
return e;
}
Rrt::Vertex
Rrt::addVertex(Tree& tree, const VectorPtr& q)
{
::std::shared_ptr<VertexBundle> bundle = ::std::make_shared<VertexBundle>();
bundle->index = ::boost::num_vertices(tree) - 1;
bundle->q = q;
Vertex v = ::boost::add_vertex(tree);
tree[v] = bundle;
tree[::boost::graph_bundle].nn->push(Metric::Value(q.get(), v));
if (nullptr != this->viewer)
{
this->viewer->drawConfigurationVertex(*get(tree, v)->q);
}
return v;
}
bool
Rrt::areEqual(const ::rl::math::Vector& lhs, const ::rl::math::Vector& rhs) const
{
if (this->model->distance(lhs, rhs) > this->epsilon)
{
return false;
}
else
{
return true;
}
}
::rl::math::Vector
Rrt::choose()
{
return this->sampler->generate();
}
Rrt::Vertex
Rrt::connect(Tree& tree, const Neighbor& nearest, const ::rl::math::Vector& chosen)
{
::rl::math::Real distance = nearest.first;
::rl::math::Real step = distance;
bool reached = false;
if (step <= this->delta)
{
reached = true;
}
else
{
step = this->delta;
}
VectorPtr last = ::std::make_shared< ::rl::math::Vector>(this->model->getDofPosition());
this->model->interpolate(*get(tree, nearest.second)->q, chosen, step / distance, *last);
if (nullptr != this->viewer)
{
// this->viewer->drawConfiguration(*last);
}
this->model->setPosition(*last);
this->model->updateFrames();
if (this->model->isColliding())
{
return nullptr;
}
::rl::math::Vector next(this->model->getDofPosition());
while (!reached)
{
step += this->delta;
if (step >= distance)
{
reached = true;
step = distance;
}
this->model->interpolate(*get(tree, nearest.second)->q, chosen, step / distance, next);
if (nullptr != this->viewer)
{
// this->viewer->drawConfiguration(next);
}
this->model->setPosition(next);
this->model->updateFrames();
if (this->model->isColliding())
{
break;
}
*last = next;
}
Vertex connected = this->addVertex(tree, last);
this->addEdge(nearest.second, connected, tree);
return connected;
}
Rrt::Vertex
Rrt::extend(Tree& tree, const Neighbor& nearest, const ::rl::math::Vector& chosen)
{
::rl::math::Real distance = nearest.first;
::rl::math::Real step = ::std::min(distance, this->delta);
VectorPtr next = ::std::make_shared< ::rl::math::Vector>(this->model->getDofPosition());
this->model->interpolate(*get(tree, nearest.second)->q, chosen, step / distance, *next);
this->model->setPosition(*next);
this->model->updateFrames();
if (!this->model->isColliding())
{
Vertex extended = this->addVertex(tree, next);
this->addEdge(nearest.second, extended, tree);
return extended;
}
return nullptr;
}
Rrt::VertexBundle*
Rrt::get(const Tree& tree, const Vertex& v)
{
return tree[v].get();
}
::std::string
Rrt::getName() const
{
return "RRT";
}
NearestNeighbors*
Rrt::getNearestNeighbors(const ::std::size_t& i) const
{
return this->tree[i][::boost::graph_bundle].nn;
}
::std::size_t
Rrt::getNumEdges() const
{
::std::size_t edges = 0;
for (::std::size_t i = 0; i < this->tree.size(); ++i)
{
edges += ::boost::num_edges(this->tree[i]);
}
return edges;
}
::std::size_t
Rrt::getNumVertices() const
{
::std::size_t vertices = 0;
for (::std::size_t i = 0; i < this->tree.size(); ++i)
{
vertices += ::boost::num_vertices(this->tree[i]);
}
return vertices;
}
VectorList
Rrt::getPath()
{
VectorList path;
Vertex i = this->end[0];
while (i != this->begin[0])
{
path.push_front(*get(this->tree[0], i)->q);
i = ::boost::source(*::boost::in_edges(i, this->tree[0]).first, this->tree[0]);
}
path.push_front(*get(this->tree[0], i)->q);
return path;
}
Rrt::Neighbor
Rrt::nearest(const Tree& tree, const ::rl::math::Vector& chosen)
{
::std::vector<NearestNeighbors::Neighbor> neighbors = tree[::boost::graph_bundle].nn->nearest(Metric::Value(&chosen, Vertex()), 1);
return Neighbor(
tree[::boost::graph_bundle].nn->isTransformedDistance() ? this->model->inverseOfTransformedDistance(neighbors.front().first) : neighbors.front().first,
neighbors.front().second.second
);
}
void
Rrt::reset()
{
for (::std::size_t i = 0; i < this->tree.size(); ++i)
{
this->tree[i].clear();
this->tree[i][::boost::graph_bundle].nn->clear();
this->begin[i] = nullptr;
this->end[i] = nullptr;
}
}
void
Rrt::setNearestNeighbors(NearestNeighbors* nearestNeighbors, const ::std::size_t& i)
{
this->tree[i][::boost::graph_bundle].nn = nearestNeighbors;
}
bool
Rrt::solve()
{
this->time = ::std::chrono::steady_clock::now();
this->begin[0] = this->addVertex(this->tree[0], ::std::make_shared< ::rl::math::Vector>(*this->start));
while ((::std::chrono::steady_clock::now() - this->time) < this->duration)
{
::rl::math::Vector chosen = this->choose();
Neighbor nearest = this->nearest(this->tree[0], chosen);
Vertex extended = this->extend(this->tree[0], nearest, chosen);
if (nullptr != extended)
{
if (this->areEqual(*get(this->tree[0], extended)->q, *this->goal))
{
this->end[0] = extended;
return true;
}
}
}
return false;
}
}
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2014, webvariants GmbH, http://www.webvariants.de
*
* This file is released under the terms of the MIT license. You can find the
* complete text in the attached LICENSE file or online at:
*
* http://www.opensource.org/licenses/mit-license.php
*
* @author: Thomas Krause ([email protected])
*/
#include <iostream>
#include <string>
#include <mutex>
#include <vector>
#include <condition_variable>
#include <csignal>
#include <iostream>
#include "config/Config.h"
#include "world/ComponentManager.h"
std::condition_variable waitCond;
std::shared_ptr<Susi::System::ComponentManager> componentManager;
void waitForEver()
{
std::mutex mutex;
std::unique_lock<std::mutex> lk(mutex);
waitCond.wait(lk,[](){return false;});
}
void signalHandler( int signum )
{
std::cout << "Interrupt signal (" << signum << ") received.\n";
// cleanup and close up stuff here
// terminate program
componentManager->stopAll();
exit(0);
}
int main(int argc, char** argv){
std::vector<std::string> argv_vec;
for (int i=0; i<argc; i++) {
argv_vec[i] = argv[i];
}
Susi::Config cfg{"config.json"};
cfg.parseCommandLine(argv_vec);
componentManager = std::make_shared<Susi::System::ComponentManager>(cfg.getConfig());
componentManager->startAll();
// register signal SIGINT and signal handler
signal(SIGINT, signalHandler);
waitForEver();
componentManager->stopAll();
exit(0);
}<commit_msg>[Main]<commit_after>/*
* Copyright (c) 2014, webvariants GmbH, http://www.webvariants.de
*
* This file is released under the terms of the MIT license. You can find the
* complete text in the attached LICENSE file or online at:
*
* http://www.opensource.org/licenses/mit-license.php
*
* @author: Thomas Krause ([email protected])
*/
#include <iostream>
#include <string>
#include <mutex>
#include <vector>
#include <condition_variable>
#include <csignal>
#include <iostream>
#include "config/Config.h"
#include "world/ComponentManager.h"
#include "world/system_setup.h"
std::condition_variable waitCond;
std::shared_ptr<Susi::System::ComponentManager> componentManager;
void waitForEver()
{
std::mutex mutex;
std::unique_lock<std::mutex> lk(mutex);
waitCond.wait(lk,[](){return false;});
}
void signalHandler( int signum )
{
std::cout << "Interrupt signal (" << signum << ") received.\n";
// cleanup and close up stuff here
// terminate program
componentManager->stopAll();
exit(0);
}
int main(int argc, char** argv){
std::vector<std::string> argv_vec;
for (int i=0; i<argc; i++) {
argv_vec[i] = argv[i];
}
Susi::Config cfg{"config.json"};
cfg.parseCommandLine(argv_vec);
componentManager = Susi::System::createSusiComponentManager(cfg.getConfig());
//componentManager = std::make_shared<Susi::System::ComponentManager>(cfg.getConfig());
componentManager->startAll();
// register signal SIGINT and signal handler
signal(SIGINT, signalHandler);
waitForEver();
componentManager->stopAll();
exit(0);
}<|endoftext|> |
<commit_before>#include "stft_client.h"
#include "app_globals.h"
#include "audio_nodes.h"
#include "recorder_node.h"
#include "stft_request.h"
#include "stft_client_storage.h"
#include <cinder/audio/dsp/Fft.h>
#include <cinder/audio/Buffer.h>
#include <mutex>
#include <thread>
#include <tuple>
namespace cieq {
namespace stft {
namespace {
/*!
* \struct ClientResources
* \brief internal storage for a thread, therefore multiple
* threads running at the same time do not share an FFT session.
*/
thread_local static struct ClientResources
{
ClientStorage* mPrivateStorage;
} _resources;
static class ClientResourcesAllocator
{
public:
void allocate( const Client::Format& fmt,
ClientResources& local_rsc)
{
std::lock_guard<std::mutex> _lock(mResourceLock);
mPrivateMemory.push_back(std::make_unique<ClientStorage>(fmt));
local_rsc.mPrivateStorage = mPrivateMemory.back().get();
}
private:
std::mutex mResourceLock;
/* mind: blown. */
std::vector < std::unique_ptr < ClientStorage > >
mPrivateMemory;
} _resources_allocator;
} //!namespace
Client::Client(work::Manager& m, AppGlobals* g /*= nullptr*/, Format fmt /*= Format()*/)
: work::Client(m)
, mFormat(fmt)
, mGlobals(g)
{}
void Client::handle(work::RequestRef req)
{
// Allocate once per thread.
thread_local static bool _ready = false;
if (!_ready)
{
// pass thread's local storage to the allocator function
_resources_allocator.allocate( mFormat, _resources );
_ready = true;
}
auto request_ptr = static_cast<stft::Request*>(req.get());
mGlobals
->getAudioNodes()
.getBufferRecorderNode()
->popBufferWindow(_resources.mPrivateStorage->mFftBuffer, request_ptr->getQueryPos());
}
Client::Format& Client::Format::windowSize(std::size_t size)
{
mWindowSize = size; return *this;
}
Client::Format& Client::Format::fftSize(std::size_t size)
{
mFftSize = size; return *this;
}
std::size_t Client::Format::getWindowSize() const
{
return mWindowSize;
}
std::size_t Client::Format::getFftSize() const
{
return mFftSize;
}
Client::Format& Client::Format::channels(std::size_t size)
{
mChannels = size;
return *this;
}
std::size_t Client::Format::getChannelSize() const
{
return mChannels;
}
Client::Format& Client::Format::windowType(ci::audio::dsp::WindowType type)
{
mWindowType = type; return *this;
}
ci::audio::dsp::WindowType Client::Format::getWindowType() const
{
return mWindowType;
}
}
} //!cieq::stft<commit_msg>Implemented the actual FFT computation<commit_after>#include "stft_client.h"
#include "app_globals.h"
#include "audio_nodes.h"
#include "recorder_node.h"
#include "stft_request.h"
#include "stft_client_storage.h"
#include <cinder/audio/dsp/Fft.h>
#include <cinder/audio/Buffer.h>
#include <cinder/CinderMath.h>
#include <mutex>
#include <thread>
#include <tuple>
namespace cieq {
namespace stft {
namespace {
/*!
* \struct ClientResources
* \brief internal storage for a thread, therefore multiple
* threads running at the same time do not share an FFT session.
*/
thread_local static struct ClientResources
{
ClientStorage* mPrivateStorage;
} _resources;
static class ClientResourcesAllocator
{
public:
void allocate( const Client::Format& fmt,
ClientResources& local_rsc)
{
std::lock_guard<std::mutex> _lock(mResourceLock);
mPrivateMemory.push_back(std::make_unique<ClientStorage>(fmt));
local_rsc.mPrivateStorage = mPrivateMemory.back().get();
}
private:
std::mutex mResourceLock;
/* mind: blown. */
std::vector < std::unique_ptr < ClientStorage > >
mPrivateMemory;
} _resources_allocator;
} //!namespace
Client::Client(work::Manager& m, AppGlobals* g /*= nullptr*/, Format fmt /*= Format()*/)
: work::Client(m)
, mFormat(fmt)
, mGlobals(g)
{}
void Client::handle(work::RequestRef req)
{
// Allocate once per thread.
thread_local static bool _ready = false;
if (!_ready)
{
// pass thread's local storage to the allocator function
_resources_allocator.allocate( mFormat, _resources );
_ready = true;
}
auto request_ptr = static_cast<stft::Request*>(req.get());
mGlobals
->getAudioNodes()
.getBufferRecorderNode()
->popBufferWindow(_resources.mPrivateStorage->mCopiedBuffer, request_ptr->getQueryPos());
// window the copied buffer and compute forward FFT transform
if (_resources.mPrivateStorage->mChannelSize > 1) {
// naive average of all channels
_resources.mPrivateStorage->mFftBuffer.zero();
float scale = 1.0f / _resources.mPrivateStorage->mChannelSize;
for (size_t ch = 0; ch < _resources.mPrivateStorage->mChannelSize; ch++) {
for (size_t i = 0; i < _resources.mPrivateStorage->mWindowSize; i++)
_resources.mPrivateStorage->mFftBuffer[i] += _resources.mPrivateStorage->mCopiedBuffer.getChannel(ch)[i] * scale;
}
ci::audio::dsp::mul( _resources.mPrivateStorage->mFftBuffer.getData(),
_resources.mPrivateStorage->mWindowingTable.get(),
_resources.mPrivateStorage->mFftBuffer.getData(),
_resources.mPrivateStorage->mWindowSize);
}
else
ci::audio::dsp::mul( _resources.mPrivateStorage->mCopiedBuffer.getData(),
_resources.mPrivateStorage->mWindowingTable.get(),
_resources.mPrivateStorage->mFftBuffer.getData(),
_resources.mPrivateStorage->mWindowSize);
_resources.mPrivateStorage->mFft->forward(&_resources.mPrivateStorage->mFftBuffer, &_resources.mPrivateStorage->mBufferSpectral);
float *real = _resources.mPrivateStorage->mBufferSpectral.getReal();
float *imag = _resources.mPrivateStorage->mBufferSpectral.getImag();
// remove Nyquist component
imag[0] = 0.0f;
// compute normalized magnitude spectrum
// TODO: break this into vector Cartesian -> polar and then vector lowpass. skip lowpass if smoothing factor is very small
const float magScale = 1.0f / _resources.mPrivateStorage->mFft->getSize();
for (size_t i = 0; i < _resources.mPrivateStorage->mMagSpectrum.size(); i++) {
float re = real[i];
float im = imag[i];
_resources.mPrivateStorage->mMagSpectrum[i] =
_resources.mPrivateStorage->mMagSpectrum[i] *
_resources.mPrivateStorage->mSmoothingFactor +
ci::math<float>::sqrt(re * re + im * im) *
magScale * (1 - _resources.mPrivateStorage->mSmoothingFactor);
}
}
Client::Format& Client::Format::windowSize(std::size_t size)
{
mWindowSize = size; return *this;
}
Client::Format& Client::Format::fftSize(std::size_t size)
{
mFftSize = size; return *this;
}
std::size_t Client::Format::getWindowSize() const
{
return mWindowSize;
}
std::size_t Client::Format::getFftSize() const
{
return mFftSize;
}
Client::Format& Client::Format::channels(std::size_t size)
{
mChannels = size;
return *this;
}
std::size_t Client::Format::getChannelSize() const
{
return mChannels;
}
Client::Format& Client::Format::windowType(ci::audio::dsp::WindowType type)
{
mWindowType = type; return *this;
}
ci::audio::dsp::WindowType Client::Format::getWindowType() const
{
return mWindowType;
}
}
} //!cieq::stft<|endoftext|> |
<commit_before>#include <iostream>
#include <string>
#include <assert.h>
#include <cstdlib>
#include <log4cxx/logger.h>
#include <log4cxx/xml/domconfigurator.h>
using namespace log4cxx;
using namespace log4cxx::xml;
#include "hdf5.h"
#include "swmr-testdata.h"
#include "timestamp.h"
#include "progressbar.h"
#include "swmr-writer.h"
using namespace std;
SWMRWriter::SWMRWriter(const string& fname)
{
this->log = Logger::getLogger("SWMRWriter");
LOG4CXX_TRACE(log, "SWMRWriter constructor. Filename: " << fname);
this->filename = fname;
this->fid = -1;
}
void SWMRWriter::create_file()
{
hid_t fapl; /* File access property list */
hid_t fcpl;
/* Create file access property list */
fapl = H5Pcreate(H5P_FILE_ACCESS);
assert(fapl >= 0);
/* Set to use the latest library format */
assert(H5Pset_libver_bounds(fapl, H5F_LIBVER_LATEST, H5F_LIBVER_LATEST) >= 0);
/* Create file creation property list */
if ((fcpl = H5Pcreate(H5P_FILE_CREATE)) < 0)
assert(fcpl >= 0);
/* Creating the file with SWMR write access*/
LOG4CXX_INFO(log, "Creating file: " << filename);
unsigned int flags = H5F_ACC_TRUNC;
this->fid = H5Fcreate(this->filename.c_str(), flags, fcpl, fapl);
assert(this->fid >= 0);
/* Close file access property list */
assert(H5Pclose(fapl) >= 0);
}
void SWMRWriter::get_test_data()
{
LOG4CXX_DEBUG(log, "Getting test data from swmr_testdata");
vector<hsize_t> dims(2);
dims[0] = swmr_testdata_cols;
dims[1] = swmr_testdata_rows;
this->img = Frame(dims, (const uint32_t*)(swmr_testdata[0]));
}
void SWMRWriter::get_test_data(const string& fname, const string& dsetname)
{
LOG4CXX_DEBUG(log, "Getting test data from file/dset: "
<< fname << "/" << dsetname);
this->img = Frame(fname, dsetname);
}
void SWMRWriter::write_test_data(unsigned int niter,
unsigned int nframes_cache,
double period)
{
hid_t dataspace, dataset;
hid_t filespace, memspace;
hid_t prop;
herr_t status;
hsize_t chunk_dims[3];
hsize_t max_dims[3];
hsize_t img_dims[3];
hsize_t offset[3] = { 0, 0, 0 };
hsize_t size[3];
assert(this->img.dimensions().size() == 2);
chunk_dims[0] = nframes_cache;
chunk_dims[1] = this->img.dimensions()[0];
chunk_dims[2] = this->img.dimensions()[1];
max_dims[0] = H5S_UNLIMITED;
max_dims[1] = this->img.dimensions()[0];
max_dims[2] = this->img.dimensions()[1];
img_dims[0] = 1;
img_dims[1] = this->img.dimensions()[0];
img_dims[2] = this->img.dimensions()[1];
size[0] = 1;
size[1] = this->img.dimensions()[0];
size[2] = this->img.dimensions()[1];
/* Create the dataspace with the given dimensions - and max dimensions */
dataspace = H5Screate_simple(3, img_dims, max_dims);
assert(dataspace >= 0);
/* Enable chunking */
prop = H5Pcreate(H5P_DATASET_CREATE);
status = H5Pset_chunk(prop, 3, chunk_dims);
assert(status >= 0);
/* Create dataset */
LOG4CXX_DEBUG(log, "Creating dataset");
dataset = H5Dcreate2(this->fid, "data", H5T_NATIVE_INT, dataspace,
H5P_DEFAULT, prop, H5P_DEFAULT);
/* Enable SWMR writing mode */
assert(H5Fstart_swmr_write(this->fid) >= 0);
LOG4CXX_INFO(log, "##### SWMR mode ######");
LOG4CXX_INFO(log, "Clients can start reading");
if (!log->isInfoEnabled()) cout << "##### SWMR mode ######" << endl;
TimeStamp ts;
ts.reset();
LOG4CXX_DEBUG(log, "Starting write loop. Iterations: " << niter);
bool show_pbar = not log->isDebugEnabled();
if (show_pbar) progressbar(0, niter);
for (int i = 0; i < niter; i++) {
/* Extend the dataset */
LOG4CXX_TRACE(log, "Extending. Size: " << size[2]
<< ", " << size[1] << ", " << size[0]);
status = H5Dset_extent(dataset, size);
assert(status >= 0);
/* Select a hyperslab */
filespace = H5Dget_space(dataset);
status = H5Sselect_hyperslab(filespace, H5S_SELECT_SET, offset, NULL,
img_dims, NULL);
assert(status >= 0);
/* Write the data to the hyperslab */
LOG4CXX_DEBUG(log, "Writing. Offset: " << offset[0] << ", "
<< offset[1] << ", " << offset[2]);
status = H5Dwrite(dataset, H5T_NATIVE_UINT32, dataspace, filespace,
H5P_DEFAULT, this->img.pdata());
assert(status >= 0);
/* Increment offsets and dimensions as appropriate */
offset[0]++;
size[0]++;
LOG4CXX_TRACE(log, "Flushing");
assert(H5Dflush(dataset) >= 0);
if (show_pbar) progressbar(i+1, niter);
if (period > 0.0) {
double sleeptime = period - ts.seconds_until_now();
if (sleeptime > 0.0) {
LOG4CXX_TRACE(log, "Sleeping " << sleeptime << "sec (period: "
<< period << "sec" );
usleep((unsigned int) (sleeptime * 1000000));
}
ts.reset();
}
}
LOG4CXX_DEBUG(log, "Closing intermediate open HDF objects");
H5Dclose(dataset);
H5Pclose(prop);
H5Sclose(dataspace);
H5Sclose(filespace);
}
SWMRWriter::~SWMRWriter()
{
LOG4CXX_TRACE(log, "SWMRWriter destructor");
if (this->fid >= 0) {
assert(H5Fclose(this->fid) >= 0);
this->fid = -1;
}
}
<commit_msg>Added HDF5 optimisation<commit_after>#include <iostream>
#include <string>
#include <cmath>
#include <assert.h>
#include <cstdlib>
#include <log4cxx/logger.h>
#include <log4cxx/xml/domconfigurator.h>
using namespace log4cxx;
using namespace log4cxx::xml;
#include "hdf5.h"
#include "swmr-testdata.h"
#include "timestamp.h"
#include "progressbar.h"
#include "swmr-writer.h"
using namespace std;
SWMRWriter::SWMRWriter(const string& fname)
{
this->log = Logger::getLogger("SWMRWriter");
LOG4CXX_TRACE(log, "SWMRWriter constructor. Filename: " << fname);
this->filename = fname;
this->fid = -1;
}
void SWMRWriter::create_file()
{
hid_t fapl; /* File access property list */
hid_t fcpl;
/* Create file access property list */
fapl = H5Pcreate(H5P_FILE_ACCESS);
assert(fapl >= 0);
assert(H5Pset_fclose_degree(fapl, H5F_CLOSE_STRONG) >= 0);
/* Set chunk boundary alignment */
assert( H5Pset_alignment( fapl, 65536, 4*1024*1024 ) >= 0);
/* Set to use the latest library format */
assert(H5Pset_libver_bounds(fapl, H5F_LIBVER_LATEST, H5F_LIBVER_LATEST) >= 0);
/* Create file creation property list */
if ((fcpl = H5Pcreate(H5P_FILE_CREATE)) < 0)
assert(fcpl >= 0);
/* Creating the file with SWMR write access*/
LOG4CXX_INFO(log, "Creating file: " << filename);
unsigned int flags = H5F_ACC_TRUNC;
this->fid = H5Fcreate(this->filename.c_str(), flags, fcpl, fapl);
assert(this->fid >= 0);
/* Close file access property list */
assert(H5Pclose(fapl) >= 0);
}
void SWMRWriter::get_test_data()
{
LOG4CXX_DEBUG(log, "Getting test data from swmr_testdata");
vector<hsize_t> dims(2);
dims[0] = swmr_testdata_cols;
dims[1] = swmr_testdata_rows;
this->img = Frame(dims, (const uint32_t*)(swmr_testdata[0]));
}
void SWMRWriter::get_test_data(const string& fname, const string& dsetname)
{
LOG4CXX_DEBUG(log, "Getting test data from file/dset: "
<< fname << "/" << dsetname);
this->img = Frame(fname, dsetname);
}
void SWMRWriter::write_test_data(unsigned int niter,
unsigned int nframes_cache,
double period)
{
hid_t dataspace, dataset;
hid_t filespace, memspace;
hid_t prop;
herr_t status;
hsize_t chunk_dims[3];
hsize_t max_dims[3];
hsize_t img_dims[3];
hsize_t offset[3] = { 0, 0, 0 };
hsize_t size[3];
assert(this->img.dimensions().size() == 2);
chunk_dims[0] = nframes_cache;
chunk_dims[1] = this->img.dimensions()[0];
chunk_dims[2] = this->img.dimensions()[1];
max_dims[0] = H5S_UNLIMITED;
max_dims[1] = this->img.dimensions()[0];
max_dims[2] = this->img.dimensions()[1];
img_dims[0] = 1;
img_dims[1] = this->img.dimensions()[0];
img_dims[2] = this->img.dimensions()[1];
size[0] = 1;
size[1] = this->img.dimensions()[0];
size[2] = this->img.dimensions()[1];
/* Create the dataspace with the given dimensions - and max dimensions */
dataspace = H5Screate_simple(3, img_dims, max_dims);
assert(dataspace >= 0);
/* Enable chunking */
prop = H5Pcreate(H5P_DATASET_CREATE);
status = H5Pset_chunk(prop, 3, chunk_dims);
assert(status >= 0);
/* dataset access property list */
hid_t dapl = H5Pcreate(H5P_DATASET_ACCESS);
size_t nbytes = img_dims[1] * img_dims[2] * sizeof(uint32_t) * chunk_dims[0];
size_t nslots = static_cast<size_t>(ceil((double)max_dims[1] / chunk_dims[1]) * niter);
nslots *= 13;
LOG4CXX_DEBUG(log, "Chunk cache nslots=" << nslots << " nbytes=" << nbytes);
assert( H5Pset_chunk_cache( dapl, nslots, nbytes, 1.0) >= 0);
/* Create dataset */
LOG4CXX_DEBUG(log, "Creating dataset");
dataset = H5Dcreate2(this->fid, "data", H5T_NATIVE_INT, dataspace,
H5P_DEFAULT, prop, dapl);
/* Enable SWMR writing mode */
assert(H5Fstart_swmr_write(this->fid) >= 0);
LOG4CXX_INFO(log, "##### SWMR mode ######");
LOG4CXX_INFO(log, "Clients can start reading");
if (!log->isInfoEnabled()) cout << "##### SWMR mode ######" << endl;
TimeStamp ts;
ts.reset();
LOG4CXX_DEBUG(log, "Starting write loop. Iterations: " << niter);
bool show_pbar = not log->isDebugEnabled();
if (show_pbar) progressbar(0, niter);
for (int i = 0; i < niter; i++) {
/* Extend the dataset */
LOG4CXX_TRACE(log, "Extending. Size: " << size[2]
<< ", " << size[1] << ", " << size[0]);
status = H5Dset_extent(dataset, size);
assert(status >= 0);
/* Select a hyperslab */
filespace = H5Dget_space(dataset);
status = H5Sselect_hyperslab(filespace, H5S_SELECT_SET, offset, NULL,
img_dims, NULL);
assert(status >= 0);
/* Write the data to the hyperslab */
LOG4CXX_DEBUG(log, "Writing. Offset: " << offset[0] << ", "
<< offset[1] << ", " << offset[2]);
status = H5Dwrite(dataset, H5T_NATIVE_UINT32, dataspace, filespace,
H5P_DEFAULT, this->img.pdata());
assert(status >= 0);
/* Increment offsets and dimensions as appropriate */
offset[0]++;
size[0]++;
if ((i+1) % nframes_cache == 0)
{
LOG4CXX_TRACE(log, "Flushing");
assert(H5Dflush(dataset) >= 0);
}
if (show_pbar) progressbar(i+1, niter);
if (period > 0.0) {
double sleeptime = period - ts.seconds_until_now();
if (sleeptime > 0.0) {
LOG4CXX_TRACE(log, "Sleeping " << sleeptime << "sec (period: "
<< period << "sec" );
usleep((unsigned int) (sleeptime * 1000000));
}
ts.reset();
}
}
LOG4CXX_DEBUG(log, "Closing intermediate open HDF objects");
H5Dclose(dataset);
H5Pclose(prop);
H5Pclose(dapl);
H5Sclose(dataspace);
H5Sclose(filespace);
}
SWMRWriter::~SWMRWriter()
{
LOG4CXX_TRACE(log, "SWMRWriter destructor");
if (this->fid >= 0) {
assert(H5Fclose(this->fid) >= 0);
this->fid = -1;
}
}
<|endoftext|> |
<commit_before>/* Copyright (c) 2011-2012, AOYAMA Kazuharu
* All rights reserved.
*
* This software may be used and distributed according to the terms of
* the New BSD License, which is incorporated herein by reference.
*/
#include <THttpHeader>
/*!
\class THttpHeader
\brief The THttpHeader class is the abstract base class of request or response header information for HTTP.
*/
THttpHeader::THttpHeader(const QByteArray &str)
{
parse(str);
}
QByteArray THttpHeader::toByteArray() const
{
return TInternetMessageHeader::toByteArray();
}
/*!
\class THttpRequestHeader
\brief The THttpRequestHeader class contains request header information
for HTTP.
*/
THttpRequestHeader::THttpRequestHeader()
: majVer(0), minVer(0)
{ }
THttpRequestHeader::THttpRequestHeader(const QByteArray &str)
{
int i = str.indexOf('\n');
if (i > 0) {
parse(str.mid(i + 1));
QByteArray line = str.left(i).trimmed();
i = line.indexOf(' ');
if (i > 0) {
reqMethod = line.left(i);
++i;
int j = line.indexOf(' ', i);
if (j > 0) {
reqUri = line.mid(i, j - i);
i = j;
j = line.indexOf("HTTP/", i);
if (j > 0 && j + 7 < line.length()) {
majVer = line.mid(j + 5, 1).toInt();
minVer = line.mid(j + 7, 1).toInt();
}
}
}
}
}
void THttpRequestHeader::setRequest(const QByteArray &method, const QByteArray &path, int majorVer, int minorVer)
{
reqMethod = method;
reqUri = path;
majVer = majorVer;
minVer = minorVer;
}
QByteArray THttpRequestHeader::toByteArray() const
{
QByteArray ba;
ba += reqMethod + ' ' + reqUri + " HTTP/";
ba += QByteArray::number(majVer);
ba += '.';
ba += QByteArray::number(minVer);
ba += "\r\n";
ba += THttpHeader::toByteArray();
return ba;
}
/*!
\class THttpResponseHeader
\brief The THttpResponseHeader class contains response header information
for HTTP.
*/
THttpResponseHeader::THttpResponseHeader()
: statCode(0), majVer(1), minVer(1)
{ }
THttpResponseHeader::THttpResponseHeader(const QByteArray &str)
: statCode(0), majVer(1), minVer(1)
{
int i = str.indexOf('\n');
if (i > 0) {
parse(str.mid(i + 1));
QByteArray line = str.left(i).trimmed();
i = line.indexOf("HTTP/");
if (i == 0 && line.length() >= 12) {
majVer = line.mid(5, 1).toInt();
minVer = line.mid(7, 1).toInt();
if (line[8] == ' ' || line[8] == '\t') {
statCode = line.mid(9, 3).toInt();
}
if (line.length() > 13 &&
(line[12] == ' ' || line[12] == '\t')) {
reasonPhr = line.mid(13).trimmed();
}
}
}
}
void THttpResponseHeader::setStatusLine(int code, const QByteArray &text, int majorVer, int minorVer)
{
statCode = code;
reasonPhr = text;
majVer = majorVer;
minVer = minorVer;
}
QByteArray THttpResponseHeader::toByteArray() const
{
QByteArray ba;
ba += "HTTP/";
ba += QByteArray::number(majVer);
ba += '.';
ba += QByteArray::number(minVer);
ba += ' ';
ba += QByteArray::number(statCode);
ba += ' ';
ba += reasonPhr;
ba += "\r\n";
ba += THttpHeader::toByteArray();
return ba;
}
<commit_msg>added doxygen comments<commit_after>/* Copyright (c) 2011-2012, AOYAMA Kazuharu
* All rights reserved.
*
* This software may be used and distributed according to the terms of
* the New BSD License, which is incorporated herein by reference.
*/
#include <THttpHeader>
/*!
\class THttpHeader
\brief The THttpHeader class is the abstract base class of request or response header information for HTTP.
*/
/*!
Constructor an HTTP header by parsing \a str.
*/
THttpHeader::THttpHeader(const QByteArray &str)
{
parse(str);
}
/*!
Returns a byte array representation of the HTTP header.
*/
QByteArray THttpHeader::toByteArray() const
{
return TInternetMessageHeader::toByteArray();
}
/*!
\fn THttpHeader::THttpHeader()
Constructor.
*/
/*!
\fn int THttpHeader::majorVersion() const
Returns the major protocol-version of the HTTP header.
*/
/*!
\fn int THttpHeader::minorVersion() const
Returns the minor protocol-version of the HTTP header.
*/
/*!
\class THttpRequestHeader
\brief The THttpRequestHeader class contains request header information
for HTTP.
*/
/*!
Constructor.
*/
THttpRequestHeader::THttpRequestHeader()
: majVer(0), minVer(0)
{ }
/*!
Constructor an HTTP request header by parsing \a str.
*/
THttpRequestHeader::THttpRequestHeader(const QByteArray &str)
{
int i = str.indexOf('\n');
if (i > 0) {
parse(str.mid(i + 1));
QByteArray line = str.left(i).trimmed();
i = line.indexOf(' ');
if (i > 0) {
reqMethod = line.left(i);
++i;
int j = line.indexOf(' ', i);
if (j > 0) {
reqUri = line.mid(i, j - i);
i = j;
j = line.indexOf("HTTP/", i);
if (j > 0 && j + 7 < line.length()) {
majVer = line.mid(j + 5, 1).toInt();
minVer = line.mid(j + 7, 1).toInt();
}
}
}
}
}
/*!
Sets the request method to \a method, the request-URI to \a path and
the protocol-version to \a majorVer and \a minorVer.
*/
void THttpRequestHeader::setRequest(const QByteArray &method, const QByteArray &path, int majorVer, int minorVer)
{
reqMethod = method;
reqUri = path;
majVer = majorVer;
minVer = minorVer;
}
/*!
Returns a byte array representation of the HTTP request header.
*/
QByteArray THttpRequestHeader::toByteArray() const
{
QByteArray ba;
ba += reqMethod + ' ' + reqUri + " HTTP/";
ba += QByteArray::number(majVer);
ba += '.';
ba += QByteArray::number(minVer);
ba += "\r\n";
ba += THttpHeader::toByteArray();
return ba;
}
/*!
\fn const QByteArray &THttpRequestHeader::method() const
Returns the method of the HTTP request header.
*/
/*!
\fn const QByteArray &THttpRequestHeader::path() const
Returns the request-URI of the HTTP request header.
*/
/*!
\class THttpResponseHeader
\brief The THttpResponseHeader class contains response header information
for HTTP.
*/
/*!
Constructor.
*/
THttpResponseHeader::THttpResponseHeader()
: statCode(0), majVer(1), minVer(1)
{ }
/*!
Constructor an HTTP response header by parsing \a str.
*/
THttpResponseHeader::THttpResponseHeader(const QByteArray &str)
: statCode(0), majVer(1), minVer(1)
{
int i = str.indexOf('\n');
if (i > 0) {
parse(str.mid(i + 1));
QByteArray line = str.left(i).trimmed();
i = line.indexOf("HTTP/");
if (i == 0 && line.length() >= 12) {
majVer = line.mid(5, 1).toInt();
minVer = line.mid(7, 1).toInt();
if (line[8] == ' ' || line[8] == '\t') {
statCode = line.mid(9, 3).toInt();
}
if (line.length() > 13 &&
(line[12] == ' ' || line[12] == '\t')) {
reasonPhr = line.mid(13).trimmed();
}
}
}
}
/*!
Sets the status code to \a code, the reason phrase to \a text and
the protocol-version to \a majorVer and \a minorVer.
*/
void THttpResponseHeader::setStatusLine(int code, const QByteArray &text, int majorVer, int minorVer)
{
statCode = code;
reasonPhr = text;
majVer = majorVer;
minVer = minorVer;
}
/*!
Returns a byte array representation of the HTTP response header.
*/
QByteArray THttpResponseHeader::toByteArray() const
{
QByteArray ba;
ba += "HTTP/";
ba += QByteArray::number(majVer);
ba += '.';
ba += QByteArray::number(minVer);
ba += ' ';
ba += QByteArray::number(statCode);
ba += ' ';
ba += reasonPhr;
ba += "\r\n";
ba += THttpHeader::toByteArray();
return ba;
}
/*!
\fn int THttpResponseHeader::statusCode() const
Returns the status code of the HTTP response header.
*/
<|endoftext|> |
<commit_before>/*
* Copyright 2007-2017 Content Management AG
* All rights reserved.
*
* author: Max Kellermann <[email protected]>
*
* 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.
*
* 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
* FOUNDATION 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.
*/
#ifndef BENG_PROXY_WAS_CONTROL_HXX
#define BENG_PROXY_WAS_CONTROL_HXX
#include "event/net/BufferedSocket.hxx"
#include "SliceFifoBuffer.hxx"
#include <was/protocol.h>
class StringMap;
template<typename T> struct ConstBuffer;
class WasControlHandler {
public:
/**
* A packet was received.
*
* @return false if the object was closed
*/
virtual bool OnWasControlPacket(enum was_command cmd,
ConstBuffer<void> payload) noexcept = 0;
/**
* Called after a group of control packets have been handled, and
* the input buffer is drained.
*
* @return false if the #WasControl object has been destructed
*/
virtual bool OnWasControlDrained() noexcept {
return true;
}
virtual void OnWasControlDone() noexcept = 0;
virtual void OnWasControlError(std::exception_ptr ep) noexcept = 0;
};
/**
* Web Application Socket protocol, control channel library.
*/
class WasControl final : BufferedSocketHandler {
BufferedSocket socket;
bool done = false;
WasControlHandler &handler;
struct {
unsigned bulk = 0;
} output;
SliceFifoBuffer output_buffer;
public:
WasControl(EventLoop &event_loop, int _fd,
WasControlHandler &_handler) noexcept;
EventLoop &GetEventLoop() noexcept {
return socket.GetEventLoop();
}
bool IsDefined() const noexcept {
return socket.IsValid();
}
bool Send(enum was_command cmd,
const void *payload, size_t payload_length) noexcept;
bool SendEmpty(enum was_command cmd) noexcept {
return Send(cmd, nullptr, 0);
}
bool SendString(enum was_command cmd, const char *payload) noexcept;
bool SendUint64(enum was_command cmd, uint64_t payload) noexcept {
return Send(cmd, &payload, sizeof(payload));
}
bool SendArray(enum was_command cmd,
ConstBuffer<const char *> values) noexcept;
bool SendStrmap(enum was_command cmd, const StringMap &map) noexcept;
/**
* Enables bulk mode.
*/
void BulkOn() noexcept {
++output.bulk;
}
/**
* Disables bulk mode and flushes the output buffer.
*/
bool BulkOff() noexcept;
void Done() noexcept;
bool empty() const {
return socket.IsEmpty() && output_buffer.empty();
}
private:
void *Start(enum was_command cmd, size_t payload_length) noexcept;
bool Finish(size_t payload_length) noexcept;
void ScheduleRead() noexcept;
void ScheduleWrite() noexcept;
public:
/**
* Release the socket held by this object.
*/
void ReleaseSocket() noexcept;
private:
void InvokeDone() noexcept {
ReleaseSocket();
handler.OnWasControlDone();
}
void InvokeError(std::exception_ptr ep) noexcept {
ReleaseSocket();
handler.OnWasControlError(ep);
}
void InvokeError(const char *msg) noexcept;
bool InvokeDrained() noexcept {
return handler.OnWasControlDrained();
}
bool TryWrite() noexcept;
/* virtual methods from class BufferedSocketHandler */
BufferedResult OnBufferedData() override;
bool OnBufferedClosed() noexcept override;
bool OnBufferedWrite() override;
bool OnBufferedDrained() noexcept;
void OnBufferedError(std::exception_ptr e) noexcept override;
};
#endif
<commit_msg>was/control: add missing "override"<commit_after>/*
* Copyright 2007-2017 Content Management AG
* All rights reserved.
*
* author: Max Kellermann <[email protected]>
*
* 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.
*
* 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
* FOUNDATION 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.
*/
#ifndef BENG_PROXY_WAS_CONTROL_HXX
#define BENG_PROXY_WAS_CONTROL_HXX
#include "event/net/BufferedSocket.hxx"
#include "SliceFifoBuffer.hxx"
#include <was/protocol.h>
class StringMap;
template<typename T> struct ConstBuffer;
class WasControlHandler {
public:
/**
* A packet was received.
*
* @return false if the object was closed
*/
virtual bool OnWasControlPacket(enum was_command cmd,
ConstBuffer<void> payload) noexcept = 0;
/**
* Called after a group of control packets have been handled, and
* the input buffer is drained.
*
* @return false if the #WasControl object has been destructed
*/
virtual bool OnWasControlDrained() noexcept {
return true;
}
virtual void OnWasControlDone() noexcept = 0;
virtual void OnWasControlError(std::exception_ptr ep) noexcept = 0;
};
/**
* Web Application Socket protocol, control channel library.
*/
class WasControl final : BufferedSocketHandler {
BufferedSocket socket;
bool done = false;
WasControlHandler &handler;
struct {
unsigned bulk = 0;
} output;
SliceFifoBuffer output_buffer;
public:
WasControl(EventLoop &event_loop, int _fd,
WasControlHandler &_handler) noexcept;
EventLoop &GetEventLoop() noexcept {
return socket.GetEventLoop();
}
bool IsDefined() const noexcept {
return socket.IsValid();
}
bool Send(enum was_command cmd,
const void *payload, size_t payload_length) noexcept;
bool SendEmpty(enum was_command cmd) noexcept {
return Send(cmd, nullptr, 0);
}
bool SendString(enum was_command cmd, const char *payload) noexcept;
bool SendUint64(enum was_command cmd, uint64_t payload) noexcept {
return Send(cmd, &payload, sizeof(payload));
}
bool SendArray(enum was_command cmd,
ConstBuffer<const char *> values) noexcept;
bool SendStrmap(enum was_command cmd, const StringMap &map) noexcept;
/**
* Enables bulk mode.
*/
void BulkOn() noexcept {
++output.bulk;
}
/**
* Disables bulk mode and flushes the output buffer.
*/
bool BulkOff() noexcept;
void Done() noexcept;
bool empty() const {
return socket.IsEmpty() && output_buffer.empty();
}
private:
void *Start(enum was_command cmd, size_t payload_length) noexcept;
bool Finish(size_t payload_length) noexcept;
void ScheduleRead() noexcept;
void ScheduleWrite() noexcept;
public:
/**
* Release the socket held by this object.
*/
void ReleaseSocket() noexcept;
private:
void InvokeDone() noexcept {
ReleaseSocket();
handler.OnWasControlDone();
}
void InvokeError(std::exception_ptr ep) noexcept {
ReleaseSocket();
handler.OnWasControlError(ep);
}
void InvokeError(const char *msg) noexcept;
bool InvokeDrained() noexcept {
return handler.OnWasControlDrained();
}
bool TryWrite() noexcept;
/* virtual methods from class BufferedSocketHandler */
BufferedResult OnBufferedData() override;
bool OnBufferedClosed() noexcept override;
bool OnBufferedWrite() override;
bool OnBufferedDrained() noexcept override;
void OnBufferedError(std::exception_ptr e) noexcept override;
};
#endif
<|endoftext|> |
<commit_before>/*
Copyright (c) 2016 Xavier Leclercq
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.
*/
/*
Part of this file were copied from the Chart.js project (http://chartjs.org/)
and translated into C++.
The files of the Chart.js project have the following copyright and license.
Copyright (c) 2013-2016 Nick Downie
Released under the MIT license
https://github.com/nnnick/Chart.js/blob/master/LICENSE.md
*/
#include "wxchartgrid.h"
#include "wxchartutilities.h"
wxChartGrid::wxChartGrid(const wxSize &size,
const wxVector<wxString> &labels,
wxDouble minValue,
wxDouble maxValue,
const wxChartGridOptions& options)
: m_options(options), m_mapping(size, labels.size()),
m_XAxis(labels), m_needsFit(true)
{
wxDouble graphMinValue;
wxDouble graphMaxValue;
wxDouble valueRange = 0;
wxChartUtilities::CalculateGridRange(minValue, maxValue,
graphMinValue, graphMaxValue, valueRange, m_steps, m_stepValue);
m_mapping.SetMinValue(graphMinValue);
m_mapping.SetMaxValue(graphMaxValue);
m_YAxis.BuildYLabels(m_mapping.GetMinValue(), m_steps, m_stepValue);
}
bool wxChartGrid::HitTest(const wxPoint &point) const
{
return false;
}
void wxChartGrid::Draw(wxGraphicsContext &gc)
{
Fit(m_steps, gc);
wxDouble yLabelGap = (m_mapping.GetEndPoint() - m_mapping.GetStartPoint()) / m_steps;
wxDouble xStart = m_mapping.GetLeftPadding();
m_XAxis.UpdateLabelPositions2();
m_YAxis.UpdateLabelPositions1();
for (size_t i = 1; i < m_YAxis.GetLabels().size(); ++i)
{
wxDouble yLabelCenter = m_mapping.GetEndPoint() - (yLabelGap * i);
wxDouble linePositionY = yLabelCenter;
if (m_options.ShowHorizontalLines())
{
wxGraphicsPath path = gc.CreatePath();
path.MoveToPoint(xStart, linePositionY);
path.AddLineToPoint(m_mapping.GetSize().GetWidth(), linePositionY);
path.CloseSubpath();
wxPen pen1(m_options.GetGridLineColor(), m_options.GetGridLineWidth());
gc.SetPen(pen1);
gc.StrokePath(path);
wxGraphicsPath path2 = gc.CreatePath();
path2.MoveToPoint(xStart - 5, linePositionY);
path2.AddLineToPoint(xStart, linePositionY);
path2.CloseSubpath();
wxPen pen(m_options.GetXAxisOptions().GetLineColor(),
m_options.GetXAxisOptions().GetLineWidth());
gc.SetPen(pen);
gc.StrokePath(path2);
}
}
for (size_t i = 1; i < m_XAxis.GetLabels().size(); ++i)
{
wxDouble labelPosition = m_XAxis.CalculateLabelPosition(i);
wxPoint2DDouble s;
wxPoint2DDouble t;
m_mapping.GetVerticalLinePositions(i, s, t);
wxDouble linePosition = s.m_x;
if (m_options.ShowVerticalLines())
{
wxGraphicsPath path = gc.CreatePath();
path.MoveToPoint(linePosition, m_mapping.GetEndPoint());
path.AddLineToPoint(linePosition, m_mapping.GetStartPoint() - 3);
path.CloseSubpath();
wxPen pen1(m_options.GetGridLineColor(), m_options.GetGridLineWidth());
gc.SetPen(pen1);
gc.StrokePath(path);
// Small lines at the bottom of the base grid line
wxGraphicsPath path2 = gc.CreatePath();
path2.MoveToPoint(linePosition, m_mapping.GetEndPoint());
path2.AddLineToPoint(linePosition, m_mapping.GetEndPoint() + 5);
path2.CloseSubpath();
wxPen pen(m_options.GetYAxisOptions().GetLineColor(),
m_options.GetYAxisOptions().GetLineWidth());
gc.SetPen(pen);
gc.StrokePath(path2);
}
}
m_XAxis.Draw(gc);
// Draw the Y-axis
if (m_XAxis.GetLabels().size() > 0)
{
wxDouble labelPosition = m_XAxis.CalculateLabelPosition(0);
wxPoint2DDouble s;
wxPoint2DDouble t;
m_mapping.GetVerticalLinePositions(0, s, t);
wxDouble linePosition = s.m_x;
wxGraphicsPath path = gc.CreatePath();
path.MoveToPoint(linePosition, m_mapping.GetEndPoint());
path.AddLineToPoint(linePosition, m_mapping.GetStartPoint() - 3);
path.CloseSubpath();
wxPen pen(m_options.GetYAxisOptions().GetLineColor(),
m_options.GetYAxisOptions().GetLineWidth());
gc.SetPen(pen);
gc.StrokePath(path);
// Small lines at the bottom of the base grid line
wxGraphicsPath path2 = gc.CreatePath();
path2.MoveToPoint(linePosition, m_mapping.GetEndPoint());
path2.AddLineToPoint(linePosition, m_mapping.GetEndPoint() + 5);
path2.CloseSubpath();
gc.SetPen(pen);
gc.StrokePath(path2);
}
m_YAxis.Draw(gc);
// Draw the X-axis
if (m_YAxis.GetLabels().size() > 0)
{
wxDouble yLabelCenter = m_mapping.GetEndPoint();
wxDouble linePositionY = yLabelCenter;
wxGraphicsPath path = gc.CreatePath();
path.MoveToPoint(xStart, linePositionY);
path.AddLineToPoint(m_mapping.GetSize().GetWidth(), linePositionY);
path.CloseSubpath();
wxPen pen(m_options.GetXAxisOptions().GetLineColor(),
m_options.GetXAxisOptions().GetLineWidth());
gc.SetPen(pen);
gc.StrokePath(path);
wxGraphicsPath path2 = gc.CreatePath();
path2.MoveToPoint(xStart - 5, linePositionY);
path2.AddLineToPoint(xStart, linePositionY);
path2.CloseSubpath();
gc.SetPen(pen);
gc.StrokePath(path2);
}
}
void wxChartGrid::Resize(const wxSize &size)
{
m_mapping.SetSize(size);
m_needsFit = true;
}
const wxChartGridMapping& wxChartGrid::GetMapping() const
{
return m_mapping;
}
void wxChartGrid::Fit(size_t steps,
wxGraphicsContext &gc)
{
if (!m_needsFit)
{
return;
}
wxDouble startPoint = m_options.GetYAxisOptions().GetFontSize();
wxDouble endPoint = m_mapping.GetSize().GetHeight() - (m_options.GetYAxisOptions().GetFontSize() + 15) - 5; // -5 to pad labels
// Apply padding settings to the start and end point.
//this.startPoint += this.padding;
//this.endPoint -= this.padding;
m_YAxis.UpdateLabelSizes(gc);
m_XAxis.UpdateLabelSizes(gc);
wxDouble leftPadding = CalculateLeftPadding(m_XAxis.GetLabels(), m_YAxis.GetLabelMaxWidth());
m_XAxis.Fit(leftPadding, 0, endPoint, m_mapping.GetSize().GetWidth() - leftPadding);
m_YAxis.Fit(leftPadding, startPoint, endPoint, 0);
m_mapping.Fit(leftPadding, startPoint, endPoint);
m_needsFit = false;
}
wxDouble wxChartGrid::CalculateLeftPadding(const wxVector<wxChartLabel> &xLabels,
wxDouble yLabelMaxWidth)
{
// Either the first x label or any of the y labels can be the widest
// so they are all taken into account to compute the left padding
wxDouble leftPadding = yLabelMaxWidth;
if ((xLabels.size() > 0) && ((xLabels[0].GetSize().GetWidth() / 2) > leftPadding))
{
leftPadding = (xLabels[0].GetSize().GetWidth() / 2);
}
return leftPadding;
}
<commit_msg>Refactoring<commit_after>/*
Copyright (c) 2016 Xavier Leclercq
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.
*/
/*
Part of this file were copied from the Chart.js project (http://chartjs.org/)
and translated into C++.
The files of the Chart.js project have the following copyright and license.
Copyright (c) 2013-2016 Nick Downie
Released under the MIT license
https://github.com/nnnick/Chart.js/blob/master/LICENSE.md
*/
#include "wxchartgrid.h"
#include "wxchartutilities.h"
wxChartGrid::wxChartGrid(const wxSize &size,
const wxVector<wxString> &labels,
wxDouble minValue,
wxDouble maxValue,
const wxChartGridOptions& options)
: m_options(options), m_mapping(size, labels.size()),
m_XAxis(labels), m_needsFit(true)
{
wxDouble graphMinValue;
wxDouble graphMaxValue;
wxDouble valueRange = 0;
wxChartUtilities::CalculateGridRange(minValue, maxValue,
graphMinValue, graphMaxValue, valueRange, m_steps, m_stepValue);
m_mapping.SetMinValue(graphMinValue);
m_mapping.SetMaxValue(graphMaxValue);
m_YAxis.BuildYLabels(m_mapping.GetMinValue(), m_steps, m_stepValue);
}
bool wxChartGrid::HitTest(const wxPoint &point) const
{
return false;
}
void wxChartGrid::Draw(wxGraphicsContext &gc)
{
Fit(m_steps, gc);
wxDouble yLabelGap = (m_mapping.GetEndPoint() - m_mapping.GetStartPoint()) / m_steps;
wxDouble xStart = m_mapping.GetLeftPadding();
m_XAxis.UpdateLabelPositions2();
m_YAxis.UpdateLabelPositions1();
if (m_options.ShowHorizontalLines())
{
for (size_t i = 1; i < m_YAxis.GetLabels().size(); ++i)
{
wxDouble yLabelCenter = m_mapping.GetEndPoint() - (yLabelGap * i);
wxDouble linePositionY = yLabelCenter;
wxGraphicsPath path = gc.CreatePath();
path.MoveToPoint(xStart, linePositionY);
path.AddLineToPoint(m_mapping.GetSize().GetWidth(), linePositionY);
path.CloseSubpath();
wxPen pen1(m_options.GetGridLineColor(), m_options.GetGridLineWidth());
gc.SetPen(pen1);
gc.StrokePath(path);
wxGraphicsPath path2 = gc.CreatePath();
path2.MoveToPoint(xStart - 5, linePositionY);
path2.AddLineToPoint(xStart, linePositionY);
path2.CloseSubpath();
wxPen pen(m_options.GetXAxisOptions().GetLineColor(),
m_options.GetXAxisOptions().GetLineWidth());
gc.SetPen(pen);
gc.StrokePath(path2);
}
}
if (m_options.ShowVerticalLines())
{
for (size_t i = 1; i < m_XAxis.GetLabels().size(); ++i)
{
wxDouble labelPosition = m_XAxis.CalculateLabelPosition(i);
wxPoint2DDouble s;
wxPoint2DDouble t;
m_mapping.GetVerticalLinePositions(i, s, t);
wxDouble linePosition = s.m_x;
wxGraphicsPath path = gc.CreatePath();
path.MoveToPoint(linePosition, m_mapping.GetEndPoint());
path.AddLineToPoint(linePosition, m_mapping.GetStartPoint() - 3);
path.CloseSubpath();
wxPen pen1(m_options.GetGridLineColor(), m_options.GetGridLineWidth());
gc.SetPen(pen1);
gc.StrokePath(path);
// Small lines at the bottom of the base grid line
wxGraphicsPath path2 = gc.CreatePath();
path2.MoveToPoint(linePosition, m_mapping.GetEndPoint());
path2.AddLineToPoint(linePosition, m_mapping.GetEndPoint() + 5);
path2.CloseSubpath();
wxPen pen(m_options.GetYAxisOptions().GetLineColor(),
m_options.GetYAxisOptions().GetLineWidth());
gc.SetPen(pen);
gc.StrokePath(path2);
}
}
m_XAxis.Draw(gc);
// Draw the Y-axis
if (m_XAxis.GetLabels().size() > 0)
{
wxDouble labelPosition = m_XAxis.CalculateLabelPosition(0);
wxPoint2DDouble s;
wxPoint2DDouble t;
m_mapping.GetVerticalLinePositions(0, s, t);
wxDouble linePosition = s.m_x;
wxGraphicsPath path = gc.CreatePath();
path.MoveToPoint(linePosition, m_mapping.GetEndPoint());
path.AddLineToPoint(linePosition, m_mapping.GetStartPoint() - 3);
path.CloseSubpath();
wxPen pen(m_options.GetYAxisOptions().GetLineColor(),
m_options.GetYAxisOptions().GetLineWidth());
gc.SetPen(pen);
gc.StrokePath(path);
// Small lines at the bottom of the base grid line
wxGraphicsPath path2 = gc.CreatePath();
path2.MoveToPoint(linePosition, m_mapping.GetEndPoint());
path2.AddLineToPoint(linePosition, m_mapping.GetEndPoint() + 5);
path2.CloseSubpath();
gc.SetPen(pen);
gc.StrokePath(path2);
}
m_YAxis.Draw(gc);
// Draw the X-axis
if (m_YAxis.GetLabels().size() > 0)
{
wxDouble yLabelCenter = m_mapping.GetEndPoint();
wxDouble linePositionY = yLabelCenter;
wxGraphicsPath path = gc.CreatePath();
path.MoveToPoint(xStart, linePositionY);
path.AddLineToPoint(m_mapping.GetSize().GetWidth(), linePositionY);
path.CloseSubpath();
wxPen pen(m_options.GetXAxisOptions().GetLineColor(),
m_options.GetXAxisOptions().GetLineWidth());
gc.SetPen(pen);
gc.StrokePath(path);
wxGraphicsPath path2 = gc.CreatePath();
path2.MoveToPoint(xStart - 5, linePositionY);
path2.AddLineToPoint(xStart, linePositionY);
path2.CloseSubpath();
gc.SetPen(pen);
gc.StrokePath(path2);
}
}
void wxChartGrid::Resize(const wxSize &size)
{
m_mapping.SetSize(size);
m_needsFit = true;
}
const wxChartGridMapping& wxChartGrid::GetMapping() const
{
return m_mapping;
}
void wxChartGrid::Fit(size_t steps,
wxGraphicsContext &gc)
{
if (!m_needsFit)
{
return;
}
wxDouble startPoint = m_options.GetYAxisOptions().GetFontSize();
wxDouble endPoint = m_mapping.GetSize().GetHeight() - (m_options.GetYAxisOptions().GetFontSize() + 15) - 5; // -5 to pad labels
// Apply padding settings to the start and end point.
//this.startPoint += this.padding;
//this.endPoint -= this.padding;
m_YAxis.UpdateLabelSizes(gc);
m_XAxis.UpdateLabelSizes(gc);
wxDouble leftPadding = CalculateLeftPadding(m_XAxis.GetLabels(), m_YAxis.GetLabelMaxWidth());
m_XAxis.Fit(leftPadding, 0, endPoint, m_mapping.GetSize().GetWidth() - leftPadding);
m_YAxis.Fit(leftPadding, startPoint, endPoint, 0);
m_mapping.Fit(leftPadding, startPoint, endPoint);
m_needsFit = false;
}
wxDouble wxChartGrid::CalculateLeftPadding(const wxVector<wxChartLabel> &xLabels,
wxDouble yLabelMaxWidth)
{
// Either the first x label or any of the y labels can be the widest
// so they are all taken into account to compute the left padding
wxDouble leftPadding = yLabelMaxWidth;
if ((xLabels.size() > 0) && ((xLabels[0].GetSize().GetWidth() / 2) > leftPadding))
{
leftPadding = (xLabels[0].GetSize().GetWidth() / 2);
}
return leftPadding;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: galmisc.hxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: rt $ $Date: 2005-09-08 17:49:41 $
*
* 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_GALMISC_HXX_
#define _SVX_GALMISC_HXX_
#include <sot/storage.hxx>
#include <tools/urlobj.hxx>
#include <svtools/imap.hxx>
#include <svtools/hint.hxx>
#include <svtools/transfer.hxx>
#include "svdio.hxx"
#include "svdobj.hxx"
#include "galobj.hxx"
#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_
#include <com/sun/star/uno/Reference.h>
#endif
#ifndef _COM_SUN_STAR_AWT_XPROGRESSMONITOR_HPP
#include <com/sun/star/awt/XProgressMonitor.hpp>
#endif
#ifndef INCLUDED_SVXDLLAPI_H
#include "svx/svxdllapi.h"
#endif
// -----------
// - Defines -
// -----------
#define IV_IMAPINFO (UINT32('S')*0x00000001+UINT32('D')*0x00000100+UINT32('U')*0x00010000+UINT32('D')*0x01000000)
#define ID_IMAPINFO 2
#define USERDATA_HDL() (LINK(this,SgaUserDataFactory,MakeUserData))
#define GAL_RESID( nId ) ResId( nId, GetGalleryResMgr() )
#define STREAMBUF_SIZE 16384L
#define SGA_IMPORT_NONE 0x0000
#define SGA_IMPORT_FILE 0x0001
#define SGA_IMPORT_INET 0x0002
#define GALLERY_PROGRESS_RANGE 10000
#define GALLERY_FG_COLOR Application::GetSettings().GetStyleSettings().GetWindowTextColor()
#define GALLERY_BG_COLOR Application::GetSettings().GetStyleSettings().GetWindowColor()
#define GALLERY_DLG_COLOR Application::GetSettings().GetStyleSettings().GetDialogColor()
// -------------
// - Functions -
// -------------
class ResMgr;
class String;
class SvStream;
class Graphic;
class FmFormModel;
class ImageMap;
class Gallery;
SVX_DLLPUBLIC ResMgr* GetGalleryResMgr();
USHORT GalleryGraphicImport( const INetURLObject& rURL, Graphic& rGraphic, String& rFilterName, BOOL bShowProgress = FALSE );
BOOL GallerySvDrawImport( SvStream& rIStm, FmFormModel& rModel );
BOOL CreateIMapGraphic( const FmFormModel& rModel, Graphic& rGraphic, ImageMap& rImageMap );
SVX_DLLPUBLIC String GetReducedString( const INetURLObject& rURL, ULONG nMaxLen );
String GetSvDrawStreamNameFromURL( const INetURLObject& rSvDrawObjURL );
BOOL FileExists( const INetURLObject& rURL );
BOOL CreateDir( const INetURLObject& rURL );
BOOL CopyFile( const INetURLObject& rSrcURL, const INetURLObject& rDstURL );
BOOL KillFile( const INetURLObject& rURL );
BitmapEx GalleryResGetBitmapEx( ULONG nId );
// ---------------
// - SgaIMapInfo -
// ---------------
class SgaIMapInfo : public SdrObjUserData, public SfxListener
{
ImageMap aImageMap;
public:
SgaIMapInfo() : SdrObjUserData( IV_IMAPINFO, ID_IMAPINFO, 0 ) {};
SgaIMapInfo( const ImageMap& rImageMap) :
SdrObjUserData( IV_IMAPINFO, ID_IMAPINFO, 0 ),
aImageMap( rImageMap ) {};
virtual ~SgaIMapInfo() {};
virtual SdrObjUserData* Clone( SdrObject* pObj ) const
{
SgaIMapInfo* pInfo = new SgaIMapInfo;
pInfo->aImageMap = aImageMap;
return pInfo;
}
const ImageMap& GetImageMap() const { return aImageMap; }
};
// ----------------------
// - SgaUserDataFactory -
// ----------------------
class SgaUserDataFactory
{
public:
SgaUserDataFactory() { SdrObjFactory::InsertMakeUserDataHdl( USERDATA_HDL() ); }
~SgaUserDataFactory() { SdrObjFactory::RemoveMakeUserDataHdl( USERDATA_HDL() ); }
DECL_LINK( MakeUserData, SdrObjFactory* );
};
// -------------------
// - GalleryProgress -
// -------------------
class GraphicFilter;
class SVX_DLLPUBLIC GalleryProgress
{
::com::sun::star::uno::Reference< ::com::sun::star::awt::XProgressBar > mxProgressBar;
GraphicFilter* mpFilter;
DECL_LINK( Update, GraphicFilter * );
public:
GalleryProgress( GraphicFilter* pFilter = NULL );
~GalleryProgress();
void Update( ULONG nVal, ULONG nMaxVal );
};
// -----------------------
// - GalleryTransferable -
// -----------------------
class Gallery;
class GalleryTheme;
class GraphicObject;
class GalleryTransferable : public TransferableHelper
{
friend class GalleryTheme;
private:
GalleryTheme* mpTheme;
SgaObjKind meObjectKind;
sal_uInt32 mnObjectPos;
SotStorageStreamRef mxModelStream;
GraphicObject* mpGraphicObject;
ImageMap* mpImageMap;
INetURLObject* mpURL;
sal_Bool mbInitialized;
protected:
GalleryTransferable( GalleryTheme* pTheme, ULONG nObjectPos );
~GalleryTransferable();
void InitData();
// TransferableHelper
virtual void AddSupportedFormats();
virtual sal_Bool GetData( const ::com::sun::star::datatransfer::DataFlavor& rFlavor );
virtual sal_Bool WriteObject( SotStorageStreamRef& rxOStm, void* pUserObject, sal_uInt32 nUserObjectId, const ::com::sun::star::datatransfer::DataFlavor& rFlavor );
virtual void DragFinished( sal_Int8 nDropAction );
virtual void ObjectReleased();
void CopyToClipboard( Window* pWindow );
void StartDrag( Window* pWindow, sal_Int8 nDragSourceActions,
sal_Int32 nDragPointer = DND_POINTER_NONE,
sal_Int32 nDragImage = DND_IMAGE_NONE );
};
// ---------------
// - GalleryHint -
// ---------------
#define GALLERY_HINT_NONE 0x00000000
#define GALLERY_HINT_CLOSE_THEME 0x00000001
#define GALLERY_HINT_THEME_REMOVED 0x00000002
#define GALLERY_HINT_THEME_RENAMED 0x00000004
#define GALLERY_HINT_THEME_CREATED 0x00000008
#define GALLERY_HINT_THEME_UPDATEVIEW 0x00000010
#define GALLERY_HINT_CLOSE_OBJECT 0x00000020
#define GALLERY_HINT_OBJECT_REMOVED 0x00000040
// -----------------------------------------------------------------------------
class GalleryHint : public SfxHint
{
private:
ULONG mnType;
String maThemeName;
String maStringData;
ULONG mnData1;
ULONG mnData2;
public:
GalleryHint( ULONG nType, const String& rThemeName, ULONG nData1 = 0UL, ULONG nData2 = 0UL ) :
mnType( nType ), maThemeName( rThemeName ), mnData1( nData1 ), mnData2( nData2 ) {}
GalleryHint( ULONG nType, const String& rThemeName, const String& rStringData, ULONG nData1 = 0UL, ULONG nData2 = 0UL ) :
mnType( nType ), maThemeName( rThemeName ), maStringData( rStringData ), mnData1( nData1 ), mnData2( nData2 ) {}
ULONG GetType() const { return mnType; }
const String& GetThemeName() const { return maThemeName; }
const String& GetStringData() const { return maStringData; }
ULONG GetData1() const { return mnData1; }
ULONG GetData2() const { return mnData2; }
};
#endif
<commit_msg>INTEGRATION: CWS pj43 (1.9.166); FILE MERGED 2005/12/06 12:26:35 pjanik 1.9.166.1: #i58947#: ResID are always 32bit, use sal_uInt32 instead of ULONG.<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: galmisc.hxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: hr $ $Date: 2005-12-28 17:35:22 $
*
* 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_GALMISC_HXX_
#define _SVX_GALMISC_HXX_
#include <sot/storage.hxx>
#include <tools/urlobj.hxx>
#include <svtools/imap.hxx>
#include <svtools/hint.hxx>
#include <svtools/transfer.hxx>
#include "svdio.hxx"
#include "svdobj.hxx"
#include "galobj.hxx"
#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_
#include <com/sun/star/uno/Reference.h>
#endif
#ifndef _COM_SUN_STAR_AWT_XPROGRESSMONITOR_HPP
#include <com/sun/star/awt/XProgressMonitor.hpp>
#endif
#ifndef INCLUDED_SVXDLLAPI_H
#include "svx/svxdllapi.h"
#endif
// -----------
// - Defines -
// -----------
#define IV_IMAPINFO (UINT32('S')*0x00000001+UINT32('D')*0x00000100+UINT32('U')*0x00010000+UINT32('D')*0x01000000)
#define ID_IMAPINFO 2
#define USERDATA_HDL() (LINK(this,SgaUserDataFactory,MakeUserData))
#define GAL_RESID( nId ) ResId( nId, GetGalleryResMgr() )
#define STREAMBUF_SIZE 16384L
#define SGA_IMPORT_NONE 0x0000
#define SGA_IMPORT_FILE 0x0001
#define SGA_IMPORT_INET 0x0002
#define GALLERY_PROGRESS_RANGE 10000
#define GALLERY_FG_COLOR Application::GetSettings().GetStyleSettings().GetWindowTextColor()
#define GALLERY_BG_COLOR Application::GetSettings().GetStyleSettings().GetWindowColor()
#define GALLERY_DLG_COLOR Application::GetSettings().GetStyleSettings().GetDialogColor()
// -------------
// - Functions -
// -------------
class ResMgr;
class String;
class SvStream;
class Graphic;
class FmFormModel;
class ImageMap;
class Gallery;
SVX_DLLPUBLIC ResMgr* GetGalleryResMgr();
USHORT GalleryGraphicImport( const INetURLObject& rURL, Graphic& rGraphic, String& rFilterName, BOOL bShowProgress = FALSE );
BOOL GallerySvDrawImport( SvStream& rIStm, FmFormModel& rModel );
BOOL CreateIMapGraphic( const FmFormModel& rModel, Graphic& rGraphic, ImageMap& rImageMap );
SVX_DLLPUBLIC String GetReducedString( const INetURLObject& rURL, ULONG nMaxLen );
String GetSvDrawStreamNameFromURL( const INetURLObject& rSvDrawObjURL );
BOOL FileExists( const INetURLObject& rURL );
BOOL CreateDir( const INetURLObject& rURL );
BOOL CopyFile( const INetURLObject& rSrcURL, const INetURLObject& rDstURL );
BOOL KillFile( const INetURLObject& rURL );
BitmapEx GalleryResGetBitmapEx( sal_uInt32 nId );
// ---------------
// - SgaIMapInfo -
// ---------------
class SgaIMapInfo : public SdrObjUserData, public SfxListener
{
ImageMap aImageMap;
public:
SgaIMapInfo() : SdrObjUserData( IV_IMAPINFO, ID_IMAPINFO, 0 ) {};
SgaIMapInfo( const ImageMap& rImageMap) :
SdrObjUserData( IV_IMAPINFO, ID_IMAPINFO, 0 ),
aImageMap( rImageMap ) {};
virtual ~SgaIMapInfo() {};
virtual SdrObjUserData* Clone( SdrObject* pObj ) const
{
SgaIMapInfo* pInfo = new SgaIMapInfo;
pInfo->aImageMap = aImageMap;
return pInfo;
}
const ImageMap& GetImageMap() const { return aImageMap; }
};
// ----------------------
// - SgaUserDataFactory -
// ----------------------
class SgaUserDataFactory
{
public:
SgaUserDataFactory() { SdrObjFactory::InsertMakeUserDataHdl( USERDATA_HDL() ); }
~SgaUserDataFactory() { SdrObjFactory::RemoveMakeUserDataHdl( USERDATA_HDL() ); }
DECL_LINK( MakeUserData, SdrObjFactory* );
};
// -------------------
// - GalleryProgress -
// -------------------
class GraphicFilter;
class SVX_DLLPUBLIC GalleryProgress
{
::com::sun::star::uno::Reference< ::com::sun::star::awt::XProgressBar > mxProgressBar;
GraphicFilter* mpFilter;
DECL_LINK( Update, GraphicFilter * );
public:
GalleryProgress( GraphicFilter* pFilter = NULL );
~GalleryProgress();
void Update( ULONG nVal, ULONG nMaxVal );
};
// -----------------------
// - GalleryTransferable -
// -----------------------
class Gallery;
class GalleryTheme;
class GraphicObject;
class GalleryTransferable : public TransferableHelper
{
friend class GalleryTheme;
private:
GalleryTheme* mpTheme;
SgaObjKind meObjectKind;
sal_uInt32 mnObjectPos;
SotStorageStreamRef mxModelStream;
GraphicObject* mpGraphicObject;
ImageMap* mpImageMap;
INetURLObject* mpURL;
sal_Bool mbInitialized;
protected:
GalleryTransferable( GalleryTheme* pTheme, ULONG nObjectPos );
~GalleryTransferable();
void InitData();
// TransferableHelper
virtual void AddSupportedFormats();
virtual sal_Bool GetData( const ::com::sun::star::datatransfer::DataFlavor& rFlavor );
virtual sal_Bool WriteObject( SotStorageStreamRef& rxOStm, void* pUserObject, sal_uInt32 nUserObjectId, const ::com::sun::star::datatransfer::DataFlavor& rFlavor );
virtual void DragFinished( sal_Int8 nDropAction );
virtual void ObjectReleased();
void CopyToClipboard( Window* pWindow );
void StartDrag( Window* pWindow, sal_Int8 nDragSourceActions,
sal_Int32 nDragPointer = DND_POINTER_NONE,
sal_Int32 nDragImage = DND_IMAGE_NONE );
};
// ---------------
// - GalleryHint -
// ---------------
#define GALLERY_HINT_NONE 0x00000000
#define GALLERY_HINT_CLOSE_THEME 0x00000001
#define GALLERY_HINT_THEME_REMOVED 0x00000002
#define GALLERY_HINT_THEME_RENAMED 0x00000004
#define GALLERY_HINT_THEME_CREATED 0x00000008
#define GALLERY_HINT_THEME_UPDATEVIEW 0x00000010
#define GALLERY_HINT_CLOSE_OBJECT 0x00000020
#define GALLERY_HINT_OBJECT_REMOVED 0x00000040
// -----------------------------------------------------------------------------
class GalleryHint : public SfxHint
{
private:
ULONG mnType;
String maThemeName;
String maStringData;
ULONG mnData1;
ULONG mnData2;
public:
GalleryHint( ULONG nType, const String& rThemeName, ULONG nData1 = 0UL, ULONG nData2 = 0UL ) :
mnType( nType ), maThemeName( rThemeName ), mnData1( nData1 ), mnData2( nData2 ) {}
GalleryHint( ULONG nType, const String& rThemeName, const String& rStringData, ULONG nData1 = 0UL, ULONG nData2 = 0UL ) :
mnType( nType ), maThemeName( rThemeName ), maStringData( rStringData ), mnData1( nData1 ), mnData2( nData2 ) {}
ULONG GetType() const { return mnType; }
const String& GetThemeName() const { return maThemeName; }
const String& GetStringData() const { return maStringData; }
ULONG GetData1() const { return mnData1; }
ULONG GetData2() const { return mnData2; }
};
#endif
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: svxpch.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-09 01:24:41 $
*
* 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
*
************************************************************************/
#include <thread.hxx>
#include <sysdep.hxx>
#if defined(WNT) || defined (WIN)
#include <svwin.h>
#endif
#include <tlintl.hxx>
#include <tlfsys.hxx>
#include <tlbigint.hxx>
#include <sysdep.hxx>
#include <sv.hxx>
#include <svtool.hxx>
#define _ANIMATION
#include <svgraph.hxx>
#include <svsystem.hxx>
#include <svcontnr.hxx>
#include <sfx.hxx>
#include <sfxitems.hxx>
#include <sfxipool.hxx>
#include <sfxiiter.hxx>
#include <sfxdoc.hxx>
#include <sfxview.hxx>
#include <sfxdlg.hxx>
#include <sfxstyle.hxx>
#include <svxenum.hxx>
#include <sbx.hxx>
#include <hmwrap.hxx>
#include <mail.hxx>
#include <urlobj.hxx>
#include <inet.hxx>
#include <inetui.hxx>
#include <svtruler.hxx>
#include <limits.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <sfx.hrc>
#include "segmentc.hxx"
<commit_msg>INTEGRATION: CWS rt15 (1.3.452); FILE MERGED 2006/06/29 11:25:41 rt 1.3.452.1: #i66824# segmentc.hxx is obsolete.<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: svxpch.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2006-07-25 09:30:22 $
*
* 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
*
************************************************************************/
#include <thread.hxx>
#include <sysdep.hxx>
#if defined(WNT) || defined (WIN)
#include <svwin.h>
#endif
#include <tlintl.hxx>
#include <tlfsys.hxx>
#include <tlbigint.hxx>
#include <sysdep.hxx>
#include <sv.hxx>
#include <svtool.hxx>
#define _ANIMATION
#include <svgraph.hxx>
#include <svsystem.hxx>
#include <svcontnr.hxx>
#include <sfx.hxx>
#include <sfxitems.hxx>
#include <sfxipool.hxx>
#include <sfxiiter.hxx>
#include <sfxdoc.hxx>
#include <sfxview.hxx>
#include <sfxdlg.hxx>
#include <sfxstyle.hxx>
#include <svxenum.hxx>
#include <sbx.hxx>
#include <hmwrap.hxx>
#include <mail.hxx>
#include <urlobj.hxx>
#include <inet.hxx>
#include <inetui.hxx>
#include <svtruler.hxx>
#include <limits.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <sfx.hrc>
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: txatritr.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: kz $ $Date: 2005-10-05 13:19:21 $
*
* 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 _TXATRITR_HXX
#define _TXATRITR_HXX
#ifndef _SOLAR_H
#include <tools/solar.h>
#endif
#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif
#ifndef _SVARRAY_HXX
#include <svtools/svarray.hxx>
#endif
class String;
class SwTxtNode;
class SwTxtAttr;
class SfxPoolItem;
class SwScriptIterator
{
const String& rText;
xub_StrLen nChgPos;
sal_uInt16 nCurScript;
sal_Bool bForward;
public:
SwScriptIterator( const String& rStr, xub_StrLen nStart = 0,
sal_Bool bFrwrd = sal_True );
sal_Bool Next();
sal_uInt16 GetCurrScript() const { return nCurScript; }
xub_StrLen GetScriptChgPos() const { return nChgPos; }
const String& GetText() const { return rText; }
};
class SwTxtAttrIterator
{
SwScriptIterator aSIter;
SvPtrarr aStack;
const SwTxtNode& rTxtNd;
const SfxPoolItem *pParaItem, *pCurItem;
xub_StrLen nChgPos;
sal_uInt16 nAttrPos, nWhichId;
sal_Bool bIsUseGetWhichOfScript;
void AddToStack( const SwTxtAttr& rAttr );
void SearchNextChg();
public:
SwTxtAttrIterator( const SwTxtNode& rTxtNd, USHORT nWhichId,
xub_StrLen nStart = 0, sal_Bool bUseGetWhichOfScript = sal_True );
sal_Bool Next();
const SfxPoolItem& GetAttr() const { return *pCurItem; }
xub_StrLen GetChgPos() const { return nChgPos; }
};
#ifdef ITEMID_LANGUAGE
class SwLanguageIterator : public SwTxtAttrIterator
{
public:
SwLanguageIterator( const SwTxtNode& rTxtNd, xub_StrLen nStart = 0,
USHORT nWhichId = RES_CHRATR_LANGUAGE,
sal_Bool bUseGetWhichOfScript = sal_True )
: SwTxtAttrIterator( rTxtNd, nWhichId, nStart, bUseGetWhichOfScript )
{}
sal_uInt16 GetLanguage() const
{ return ((SvxLanguageItem&)GetAttr()).GetValue(); }
};
#endif
#endif
<commit_msg>INTEGRATION: CWS pchfix04 (1.5.560); FILE MERGED 2007/02/05 08:27:16 os 1.5.560.1: #i73604# usage of ITEMID_* removed<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: txatritr.hxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: kz $ $Date: 2007-05-10 15:54:05 $
*
* 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 _TXATRITR_HXX
#define _TXATRITR_HXX
#ifndef _SOLAR_H
#include <tools/solar.h>
#endif
#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif
#ifndef _SVARRAY_HXX
#include <svtools/svarray.hxx>
#endif
#include <svx/langitem.hxx>
#include <hintids.hxx>
class String;
class SwTxtNode;
class SwTxtAttr;
class SfxPoolItem;
class SwScriptIterator
{
const String& rText;
xub_StrLen nChgPos;
sal_uInt16 nCurScript;
sal_Bool bForward;
public:
SwScriptIterator( const String& rStr, xub_StrLen nStart = 0,
sal_Bool bFrwrd = sal_True );
sal_Bool Next();
sal_uInt16 GetCurrScript() const { return nCurScript; }
xub_StrLen GetScriptChgPos() const { return nChgPos; }
const String& GetText() const { return rText; }
};
class SwTxtAttrIterator
{
SwScriptIterator aSIter;
SvPtrarr aStack;
const SwTxtNode& rTxtNd;
const SfxPoolItem *pParaItem, *pCurItem;
xub_StrLen nChgPos;
sal_uInt16 nAttrPos, nWhichId;
sal_Bool bIsUseGetWhichOfScript;
void AddToStack( const SwTxtAttr& rAttr );
void SearchNextChg();
public:
SwTxtAttrIterator( const SwTxtNode& rTxtNd, USHORT nWhichId,
xub_StrLen nStart = 0, sal_Bool bUseGetWhichOfScript = sal_True );
sal_Bool Next();
const SfxPoolItem& GetAttr() const { return *pCurItem; }
xub_StrLen GetChgPos() const { return nChgPos; }
};
class SwLanguageIterator : public SwTxtAttrIterator
{
public:
SwLanguageIterator( const SwTxtNode& rTxtNd, xub_StrLen nStart = 0,
USHORT nWhichId = RES_CHRATR_LANGUAGE,
sal_Bool bUseGetWhichOfScript = sal_True )
: SwTxtAttrIterator( rTxtNd, nWhichId, nStart, bUseGetWhichOfScript )
{}
sal_uInt16 GetLanguage() const
{ return ((SvxLanguageItem&)GetAttr()).GetValue(); }
};
#endif
<|endoftext|> |
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/message_pump_glib_x.h"
#include <gdk/gdkx.h>
#if defined(HAVE_XINPUT2)
#include <X11/extensions/XInput2.h>
#else
#include <X11/Xlib.h>
#endif
#include "base/message_pump_glib_x_dispatch.h"
namespace {
gboolean PlaceholderDispatch(GSource* source,
GSourceFunc cb,
gpointer data) {
return TRUE;
}
#if defined(HAVE_XINPUT2)
// Setup XInput2 select for the GtkWidget.
gboolean GtkWidgetRealizeCallback(GSignalInvocationHint* hint, guint nparams,
const GValue* pvalues, gpointer data) {
GtkWidget* widget = GTK_WIDGET(g_value_get_object(pvalues));
GdkWindow* window = widget->window;
base::MessagePumpGlibX* msgpump = static_cast<base::MessagePumpGlibX*>(data);
DCHECK(window); // TODO(sad): Remove once determined if necessary.
// TODO(sad): Do we need to set a flag on |window| to make sure we don't
// select for the same GdkWindow multiple times? Does it matter?
msgpump->SetupXInput2ForXWindow(GDK_WINDOW_XID(window));
return true;
}
// We need to capture all the GDK windows that get created, and start
// listening for XInput2 events. So we setup a callback to the 'realize'
// signal for GTK+ widgets, so that whenever the signal triggers for any
// GtkWidget, which means the GtkWidget should now have a GdkWindow, we can
// setup XInput2 events for the GdkWindow.
void SetupGtkWidgetRealizeNotifier(base::MessagePumpGlibX* msgpump) {
guint signal_id;
gpointer klass = g_type_class_ref(GTK_TYPE_WIDGET);
g_signal_parse_name("realize", GTK_TYPE_WIDGET, &signal_id, NULL, FALSE);
g_signal_add_emission_hook(signal_id, 0, GtkWidgetRealizeCallback,
static_cast<gpointer>(msgpump), NULL);
g_type_class_unref(klass);
}
#endif // HAVE_XINPUT2
} // namespace
namespace base {
MessagePumpGlibX::MessagePumpGlibX() : base::MessagePumpForUI(),
#if defined(HAVE_XINPUT2)
xiopcode_(-1),
masters_(),
slaves_(),
#endif
gdksource_(NULL),
dispatching_event_(false),
capture_x_events_(0),
capture_gdk_events_(0) {
gdk_event_handler_set(&EventDispatcherX, this, NULL);
#if defined(HAVE_XINPUT2)
InitializeXInput2();
#endif
InitializeEventsToCapture();
}
MessagePumpGlibX::~MessagePumpGlibX() {
}
#if defined(HAVE_XINPUT2)
void MessagePumpGlibX::SetupXInput2ForXWindow(Window xwindow) {
Display* xdisplay = GDK_DISPLAY_XDISPLAY(gdk_display_get_default());
// Setup mask for mouse events.
unsigned char mask[(XI_LASTEVENT + 7)/8];
memset(mask, 0, sizeof(mask));
XISetMask(mask, XI_ButtonPress);
XISetMask(mask, XI_ButtonRelease);
XISetMask(mask, XI_Motion);
// It is necessary to select only for the master devices. XInput2 provides
// enough information to the event callback to decide which slave device
// triggered the event, thus decide whether the 'pointer event' is a 'mouse
// event' or a 'touch event'. So it is not necessary to select for the slave
// devices here.
XIEventMask evmasks[masters_.size()];
int count = 0;
for (std::set<int>::const_iterator iter = masters_.begin();
iter != masters_.end();
++iter, ++count) {
evmasks[count].deviceid = *iter;
evmasks[count].mask_len = sizeof(mask);
evmasks[count].mask = mask;
}
XISelectEvents(xdisplay, xwindow, evmasks, masters_.size());
// TODO(sad): Setup masks for keyboard events.
XFlush(xdisplay);
}
#endif // HAVE_XINPUT2
bool MessagePumpGlibX::RunOnce(GMainContext* context, bool block) {
GdkDisplay* gdisp = gdk_display_get_default();
if (!gdisp)
return MessagePumpForUI::RunOnce(context, block);
Display* display = GDK_DISPLAY_XDISPLAY(gdisp);
bool should_quit = false;
if (XPending(display)) {
XEvent xev;
XPeekEvent(display, &xev);
if (capture_x_events_[xev.type]
#if defined(HAVE_XINPUT2)
&& (xev.type != GenericEvent || xev.xcookie.extension == xiopcode_)
#endif
) {
XNextEvent(display, &xev);
#if defined(HAVE_XINPUT2)
bool have_cookie = false;
if (xev.type == GenericEvent &&
XGetEventData(xev.xgeneric.display, &xev.xcookie)) {
have_cookie = true;
}
#endif
MessagePumpGlibXDispatcher::DispatchStatus status =
static_cast<MessagePumpGlibXDispatcher*>
(GetDispatcher())->DispatchX(&xev);
if (status == MessagePumpGlibXDispatcher::EVENT_QUIT) {
should_quit = true;
Quit();
} else if (status == MessagePumpGlibXDispatcher::EVENT_IGNORED) {
DLOG(WARNING) << "Event (" << xev.type << ") not handled.";
// TODO(sad): It is necessary to put back the event so that the default
// GDK events handler can take care of it. Without this, it is
// impossible to use the omnibox at the moment. However, this will
// eventually be removed once the omnibox code is updated for touchui.
XPutBackEvent(display, &xev);
if (gdksource_)
gdksource_->source_funcs->dispatch = gdkdispatcher_;
g_main_context_iteration(context, FALSE);
}
#if defined(HAVE_XINPUT2)
if (have_cookie) {
XFreeEventData(xev.xgeneric.display, &xev.xcookie);
}
#endif
} else {
// TODO(sad): A couple of extra events can still sneak in during this.
// Those should be sent back to the X queue from the dispatcher
// EventDispatcherX.
if (gdksource_)
gdksource_->source_funcs->dispatch = gdkdispatcher_;
g_main_context_iteration(context, FALSE);
}
}
if (should_quit)
return true;
bool retvalue;
if (gdksource_) {
// Replace the dispatch callback of the GDK event source temporarily so that
// it doesn't read events from X.
gboolean (*cb)(GSource*, GSourceFunc, void*) =
gdksource_->source_funcs->dispatch;
gdksource_->source_funcs->dispatch = PlaceholderDispatch;
dispatching_event_ = true;
retvalue = g_main_context_iteration(context, block);
dispatching_event_ = false;
gdksource_->source_funcs->dispatch = cb;
} else {
retvalue = g_main_context_iteration(context, block);
}
return retvalue;
}
void MessagePumpGlibX::EventDispatcherX(GdkEvent* event, gpointer data) {
MessagePumpGlibX* pump_x = reinterpret_cast<MessagePumpGlibX*>(data);
if (!pump_x->gdksource_) {
pump_x->gdksource_ = g_main_current_source();
pump_x->gdkdispatcher_ = pump_x->gdksource_->source_funcs->dispatch;
} else if (!pump_x->IsDispatchingEvent()) {
if (event->type != GDK_NOTHING &&
pump_x->capture_gdk_events_[event->type]) {
// TODO(sad): An X event is caught by the GDK handler. Put it back in the
// X queue so that we catch it in the next iteration. When done, the
// following DLOG statement will be removed.
DLOG(WARNING) << "GDK received an event it shouldn't have";
}
}
pump_x->DispatchEvents(event);
}
void MessagePumpGlibX::InitializeEventsToCapture(void) {
// TODO(sad): Decide which events we want to capture and update the tables
// accordingly.
capture_x_events_[KeyPress] = true;
capture_gdk_events_[GDK_KEY_PRESS] = true;
capture_x_events_[KeyRelease] = true;
capture_gdk_events_[GDK_KEY_RELEASE] = true;
capture_x_events_[ButtonPress] = true;
capture_gdk_events_[GDK_BUTTON_PRESS] = true;
capture_x_events_[ButtonRelease] = true;
capture_gdk_events_[GDK_BUTTON_RELEASE] = true;
capture_x_events_[MotionNotify] = true;
capture_gdk_events_[GDK_MOTION_NOTIFY] = true;
#if defined(HAVE_XINPUT2)
capture_x_events_[GenericEvent] = true;
#endif
}
#if defined(HAVE_XINPUT2)
void MessagePumpGlibX::InitializeXInput2(void) {
GdkDisplay* display = gdk_display_get_default();
if (!display)
return;
Display* xdisplay = GDK_DISPLAY_XDISPLAY(display);
int event, err;
if (!XQueryExtension(xdisplay, "XInputExtension", &xiopcode_, &event, &err)) {
DLOG(WARNING) << "X Input extension not available.";
xiopcode_ = -1;
return;
}
int major = 2, minor = 0;
if (XIQueryVersion(xdisplay, &major, &minor) == BadRequest) {
DLOG(WARNING) << "XInput2 not supported in the server.";
xiopcode_ = -1;
return;
}
// TODO(sad): Here, we only setup so that the X windows created by GTK+ are
// setup for XInput2 events. We need a way to listen for XInput2 events for X
// windows created by other means (e.g. for context menus).
SetupGtkWidgetRealizeNotifier(this);
// Instead of asking X for the list of devices all the time, let's maintain a
// list of slave (physical) and master (virtual) pointer devices.
int count = 0;
XIDeviceInfo* devices = XIQueryDevice(xdisplay, XIAllDevices, &count);
for (int i = 0; i < count; i++) {
XIDeviceInfo* devinfo = devices + i;
if (devinfo->use == XISlavePointer) {
slaves_.insert(devinfo->deviceid);
} else if (devinfo->use == XIMasterPointer) {
masters_.insert(devinfo->deviceid);
}
// We do not need to care about XIFloatingSlave, because the callback for
// XI_HierarchyChanged event will take care of it.
}
XIFreeDeviceInfo(devices);
// TODO(sad): Select on root for XI_HierarchyChanged so that slaves_ and
// masters_ can be kept up-to-date. This is a relatively rare event, so we can
// put it off for a later time.
// Note: It is not necessary to listen for XI_DeviceChanged events.
}
#endif // HAVE_XINPUT2
} // namespace base
<commit_msg>touch: Fix unit_tests crash.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/message_pump_glib_x.h"
#include <gdk/gdkx.h>
#if defined(HAVE_XINPUT2)
#include <X11/extensions/XInput2.h>
#else
#include <X11/Xlib.h>
#endif
#include "base/message_pump_glib_x_dispatch.h"
namespace {
gboolean PlaceholderDispatch(GSource* source,
GSourceFunc cb,
gpointer data) {
return TRUE;
}
#if defined(HAVE_XINPUT2)
// Setup XInput2 select for the GtkWidget.
gboolean GtkWidgetRealizeCallback(GSignalInvocationHint* hint, guint nparams,
const GValue* pvalues, gpointer data) {
GtkWidget* widget = GTK_WIDGET(g_value_get_object(pvalues));
GdkWindow* window = widget->window;
base::MessagePumpGlibX* msgpump = static_cast<base::MessagePumpGlibX*>(data);
DCHECK(window); // TODO(sad): Remove once determined if necessary.
if (GDK_WINDOW_TYPE(window) != GDK_WINDOW_TOPLEVEL &&
GDK_WINDOW_TYPE(window) != GDK_WINDOW_CHILD &&
GDK_WINDOW_TYPE(window) != GDK_WINDOW_DIALOG)
return true;
// TODO(sad): Do we need to set a flag on |window| to make sure we don't
// select for the same GdkWindow multiple times? Does it matter?
msgpump->SetupXInput2ForXWindow(GDK_WINDOW_XID(window));
return true;
}
// We need to capture all the GDK windows that get created, and start
// listening for XInput2 events. So we setup a callback to the 'realize'
// signal for GTK+ widgets, so that whenever the signal triggers for any
// GtkWidget, which means the GtkWidget should now have a GdkWindow, we can
// setup XInput2 events for the GdkWindow.
void SetupGtkWidgetRealizeNotifier(base::MessagePumpGlibX* msgpump) {
guint signal_id;
gpointer klass = g_type_class_ref(GTK_TYPE_WIDGET);
g_signal_parse_name("realize", GTK_TYPE_WIDGET, &signal_id, NULL, FALSE);
g_signal_add_emission_hook(signal_id, 0, GtkWidgetRealizeCallback,
static_cast<gpointer>(msgpump), NULL);
g_type_class_unref(klass);
}
#endif // HAVE_XINPUT2
} // namespace
namespace base {
MessagePumpGlibX::MessagePumpGlibX() : base::MessagePumpForUI(),
#if defined(HAVE_XINPUT2)
xiopcode_(-1),
masters_(),
slaves_(),
#endif
gdksource_(NULL),
dispatching_event_(false),
capture_x_events_(0),
capture_gdk_events_(0) {
gdk_event_handler_set(&EventDispatcherX, this, NULL);
#if defined(HAVE_XINPUT2)
InitializeXInput2();
#endif
InitializeEventsToCapture();
}
MessagePumpGlibX::~MessagePumpGlibX() {
}
#if defined(HAVE_XINPUT2)
void MessagePumpGlibX::SetupXInput2ForXWindow(Window xwindow) {
Display* xdisplay = GDK_DISPLAY_XDISPLAY(gdk_display_get_default());
// Setup mask for mouse events.
unsigned char mask[(XI_LASTEVENT + 7)/8];
memset(mask, 0, sizeof(mask));
XISetMask(mask, XI_ButtonPress);
XISetMask(mask, XI_ButtonRelease);
XISetMask(mask, XI_Motion);
// It is necessary to select only for the master devices. XInput2 provides
// enough information to the event callback to decide which slave device
// triggered the event, thus decide whether the 'pointer event' is a 'mouse
// event' or a 'touch event'. So it is not necessary to select for the slave
// devices here.
XIEventMask evmasks[masters_.size()];
int count = 0;
for (std::set<int>::const_iterator iter = masters_.begin();
iter != masters_.end();
++iter, ++count) {
evmasks[count].deviceid = *iter;
evmasks[count].mask_len = sizeof(mask);
evmasks[count].mask = mask;
}
XISelectEvents(xdisplay, xwindow, evmasks, masters_.size());
// TODO(sad): Setup masks for keyboard events.
XFlush(xdisplay);
}
#endif // HAVE_XINPUT2
bool MessagePumpGlibX::RunOnce(GMainContext* context, bool block) {
GdkDisplay* gdisp = gdk_display_get_default();
if (!gdisp)
return MessagePumpForUI::RunOnce(context, block);
Display* display = GDK_DISPLAY_XDISPLAY(gdisp);
bool should_quit = false;
if (XPending(display)) {
XEvent xev;
XPeekEvent(display, &xev);
if (capture_x_events_[xev.type]
#if defined(HAVE_XINPUT2)
&& (xev.type != GenericEvent || xev.xcookie.extension == xiopcode_)
#endif
) {
XNextEvent(display, &xev);
#if defined(HAVE_XINPUT2)
bool have_cookie = false;
if (xev.type == GenericEvent &&
XGetEventData(xev.xgeneric.display, &xev.xcookie)) {
have_cookie = true;
}
#endif
MessagePumpGlibXDispatcher::DispatchStatus status =
static_cast<MessagePumpGlibXDispatcher*>
(GetDispatcher())->DispatchX(&xev);
if (status == MessagePumpGlibXDispatcher::EVENT_QUIT) {
should_quit = true;
Quit();
} else if (status == MessagePumpGlibXDispatcher::EVENT_IGNORED) {
DLOG(WARNING) << "Event (" << xev.type << ") not handled.";
// TODO(sad): It is necessary to put back the event so that the default
// GDK events handler can take care of it. Without this, it is
// impossible to use the omnibox at the moment. However, this will
// eventually be removed once the omnibox code is updated for touchui.
XPutBackEvent(display, &xev);
if (gdksource_)
gdksource_->source_funcs->dispatch = gdkdispatcher_;
g_main_context_iteration(context, FALSE);
}
#if defined(HAVE_XINPUT2)
if (have_cookie) {
XFreeEventData(xev.xgeneric.display, &xev.xcookie);
}
#endif
} else {
// TODO(sad): A couple of extra events can still sneak in during this.
// Those should be sent back to the X queue from the dispatcher
// EventDispatcherX.
if (gdksource_)
gdksource_->source_funcs->dispatch = gdkdispatcher_;
g_main_context_iteration(context, FALSE);
}
}
if (should_quit)
return true;
bool retvalue;
if (gdksource_) {
// Replace the dispatch callback of the GDK event source temporarily so that
// it doesn't read events from X.
gboolean (*cb)(GSource*, GSourceFunc, void*) =
gdksource_->source_funcs->dispatch;
gdksource_->source_funcs->dispatch = PlaceholderDispatch;
dispatching_event_ = true;
retvalue = g_main_context_iteration(context, block);
dispatching_event_ = false;
gdksource_->source_funcs->dispatch = cb;
} else {
retvalue = g_main_context_iteration(context, block);
}
return retvalue;
}
void MessagePumpGlibX::EventDispatcherX(GdkEvent* event, gpointer data) {
MessagePumpGlibX* pump_x = reinterpret_cast<MessagePumpGlibX*>(data);
if (!pump_x->gdksource_) {
pump_x->gdksource_ = g_main_current_source();
pump_x->gdkdispatcher_ = pump_x->gdksource_->source_funcs->dispatch;
} else if (!pump_x->IsDispatchingEvent()) {
if (event->type != GDK_NOTHING &&
pump_x->capture_gdk_events_[event->type]) {
// TODO(sad): An X event is caught by the GDK handler. Put it back in the
// X queue so that we catch it in the next iteration. When done, the
// following DLOG statement will be removed.
DLOG(WARNING) << "GDK received an event it shouldn't have";
}
}
pump_x->DispatchEvents(event);
}
void MessagePumpGlibX::InitializeEventsToCapture(void) {
// TODO(sad): Decide which events we want to capture and update the tables
// accordingly.
capture_x_events_[KeyPress] = true;
capture_gdk_events_[GDK_KEY_PRESS] = true;
capture_x_events_[KeyRelease] = true;
capture_gdk_events_[GDK_KEY_RELEASE] = true;
capture_x_events_[ButtonPress] = true;
capture_gdk_events_[GDK_BUTTON_PRESS] = true;
capture_x_events_[ButtonRelease] = true;
capture_gdk_events_[GDK_BUTTON_RELEASE] = true;
capture_x_events_[MotionNotify] = true;
capture_gdk_events_[GDK_MOTION_NOTIFY] = true;
#if defined(HAVE_XINPUT2)
capture_x_events_[GenericEvent] = true;
#endif
}
#if defined(HAVE_XINPUT2)
void MessagePumpGlibX::InitializeXInput2(void) {
GdkDisplay* display = gdk_display_get_default();
if (!display)
return;
Display* xdisplay = GDK_DISPLAY_XDISPLAY(display);
int event, err;
if (!XQueryExtension(xdisplay, "XInputExtension", &xiopcode_, &event, &err)) {
DLOG(WARNING) << "X Input extension not available.";
xiopcode_ = -1;
return;
}
int major = 2, minor = 0;
if (XIQueryVersion(xdisplay, &major, &minor) == BadRequest) {
DLOG(WARNING) << "XInput2 not supported in the server.";
xiopcode_ = -1;
return;
}
// TODO(sad): Here, we only setup so that the X windows created by GTK+ are
// setup for XInput2 events. We need a way to listen for XInput2 events for X
// windows created by other means (e.g. for context menus).
SetupGtkWidgetRealizeNotifier(this);
// Instead of asking X for the list of devices all the time, let's maintain a
// list of slave (physical) and master (virtual) pointer devices.
int count = 0;
XIDeviceInfo* devices = XIQueryDevice(xdisplay, XIAllDevices, &count);
for (int i = 0; i < count; i++) {
XIDeviceInfo* devinfo = devices + i;
if (devinfo->use == XISlavePointer) {
slaves_.insert(devinfo->deviceid);
} else if (devinfo->use == XIMasterPointer) {
masters_.insert(devinfo->deviceid);
}
// We do not need to care about XIFloatingSlave, because the callback for
// XI_HierarchyChanged event will take care of it.
}
XIFreeDeviceInfo(devices);
// TODO(sad): Select on root for XI_HierarchyChanged so that slaves_ and
// masters_ can be kept up-to-date. This is a relatively rare event, so we can
// put it off for a later time.
// Note: It is not necessary to listen for XI_DeviceChanged events.
}
#endif // HAVE_XINPUT2
} // namespace base
<|endoftext|> |
<commit_before>#include <PrecompiledHeader.h>
#include "Micro/Units/ProtossGround/ZealotUnit.h"
#include "Micro/UnitsGroup.h"
#include "Regions/MapManager.h"
using namespace std;
using namespace BWAPI;
ProbTables ZealotUnit::_sProbTables = ProbTables(UnitTypes::Protoss_Zealot.getID());
std::set<UnitType> ZealotUnit::setPrio;
ZealotUnit::ZealotUnit(Unit* u)
: GroundUnit(u, &_sProbTables)
{
if (setPrio.empty())
{
setPrio.insert(UnitTypes::Protoss_Reaver);
setPrio.insert(UnitTypes::Protoss_High_Templar);
setPrio.insert(UnitTypes::Terran_Siege_Tank_Siege_Mode);
setPrio.insert(UnitTypes::Terran_Siege_Tank_Tank_Mode);
setPrio.insert(UnitTypes::Zerg_Hydralisk);
setPrio.insert(UnitTypes::Zerg_Lurker);
setPrio.insert(UnitTypes::Zerg_Defiler);
}
_fleeingDmg = 36; // one round of storm = 14
}
ZealotUnit::~ZealotUnit()
{
}
#ifdef __LEARNING_PROB_TABLES__
void ZealotUnit::initProbTables()
{
_sProbTables = ProbTables(UnitTypes::Protoss_Zealot.getID());
}
#endif
int ZealotUnit::fightMove()
{
if (Broodwar->getFrameCount() - _lastClickFrame <= Broodwar->getLatencyFrames())
return 0;
/// approach our target enemy if not in range and in our priority targets
if (targetEnemy != NULL && targetEnemy->exists() && targetEnemy->isVisible() && targetEnemy->isDetected()
&& setPrio.count(targetEnemy->getType())
&& (targetEnemy->getDistance(_unitPos) > 45.0 || !inRange(targetEnemy)))
{
unit->move(targetEnemy->getPosition());
_lastClickFrame = Broodwar->getFrameCount();
_lastMoveFrame = Broodwar->getFrameCount();
_fightMoving = true;
return 1;
}
double dist = target.getDistance(_unitPos);
/// approach out of range target
if (oorTargetEnemy != NULL && oorTargetEnemy->exists() && oorTargetEnemy->isVisible() && targetEnemy->isDetected()
&& !inRange(oorTargetEnemy))
{
unit->move(oorTargetEnemy->getPosition());
_lastClickFrame = Broodwar->getFrameCount();
_lastMoveFrame = Broodwar->getFrameCount();
_fightMoving = true;
return 2;
}
return 0;
}
bool ZealotUnit::decideToFlee()
{
_fleeing = false;
if (unit->getShields() < 5 && unit->isUnderAttack()
&& !(targetEnemy && targetEnemy->exists() && targetEnemy->isVisible() && targetEnemy->isDetected()
&& setPrio.count(targetEnemy->getType())))
_fleeing = true;
return _fleeing;
}
void ZealotUnit::updateTargetEnemy()
{
/// oorTarget = closest in the setPrio
oorTargetEnemy = NULL;
double closest = DBL_MAX;
for (map<Unit*, Position>::const_iterator it = _unitsGroup->enemies.begin();
it != _unitsGroup->enemies.end(); ++it)
{
if (!it->first->exists() || !it->first->isVisible() || !it->first->isDetected() || it->first->getType().isFlyer())
continue;
if (it->first->isDefenseMatrixed()
|| it->first->isHallucination()
|| it->first->isInvincible())
continue;
if (!it->first->getType().isFlyer()
&& setPrio.count(it->first->getType())
&& it->first->getDistance(_unitPos) < closest)
{
closest = it->first->getDistance(_unitPos);
oorTargetEnemy = it->first;
}
}
/// targetEnemy = in range, the ones in setPrio have the priority
/// otherwise the closest
targetEnemy = NULL;
Unit* closestEnemy = NULL;
closest = DBL_MAX;
for (map<Unit*, Position>::const_iterator it = _unitsGroup->enemies.begin();
it != _unitsGroup->enemies.end(); ++it)
{
/// Rule out what we don't want to attack
if (!it->first->exists() || !it->first->isVisible() || !it->first->isDetected() || it->first->getType().isFlyer())
continue;
if (it->first->isDefenseMatrixed()
|| it->first->isHallucination()
|| it->first->isInvincible())
continue;
UnitType testType = it->first->getType();
if (testType.isBuilding()
&& testType != UnitTypes::Protoss_Photon_Cannon
&& (testType != UnitTypes::Terran_Bunker || !it->first->isAttacking())
&& testType != UnitTypes::Terran_Missile_Turret
&& testType != UnitTypes::Zerg_Sunken_Colony
&& testType != UnitTypes::Zerg_Spore_Colony)
continue;
/// Take one in the setPrio and in range or one in range or the closest
if (inRange(it->first))
{
targetEnemy = it->first;
if (setPrio.count(it->first->getType()))
break;
} else
{
if (it->first->getDistance(_unitPos) < closest)
{
closest = it->first->getDistance(_unitPos);
closestEnemy = it->first;
}
}
}
if (targetEnemy == NULL)
targetEnemy = closestEnemy;
}
void ZealotUnit::flee()
{
//if (_lastTotalHP < 60)
{
for each (Unit* u in _targetingMe)
{
if (isOutrangingMe(u))
return;
}
}
_fightMoving = false;
if (!this->mapManager->groundDamages[_unitPos.x()/32 + _unitPos.y()/32*Broodwar->mapWidth()])
{
_fleeing = false;
return;
}
_fleeing = true;
updateDir();
clickDir();
}
void ZealotUnit::micro()
{
int currentFrame = Broodwar->getFrameCount();
if (unit->isStartingAttack())
_lastAttackFrame = currentFrame;
updateTargetingMe();
/// Dodge storm, drag mine, drag scarab
if (dodgeStorm() || dragMine() || dragScarab())
return;
decideToFlee();
updateTargetEnemy();
if (currentFrame - _lastClickFrame <= Broodwar->getLatencyFrames())
return;
if (currentFrame - _lastAttackFrame <= getAttackDuration()) // not interrupting attacks
return;
if (unit->getGroundWeaponCooldown() <= Broodwar->getLatencyFrames() + 2)
{
if (targetEnemy != NULL && targetEnemy->exists() && targetEnemy->isVisible() && targetEnemy->isDetected())
{
// attack enemy unit
unit->rightClick(targetEnemy);
_lastClickFrame = Broodwar->getFrameCount();
_lastAttackFrame = Broodwar->getFrameCount();
}
else
unit->attack(_unitsGroup->enemiesCenter);
}
else if (unit->getGroundWeaponCooldown() > Broodwar->getLatencyFrames() + 2) // (Broodwar->getLatencyFrames()+1)*2, safety
{
if (_fleeing)
{
#ifdef __SIMPLE_FLEE__
simpleFlee();
#else
//if (unit->isStuck()) // TODO do something with it
// simpleFlee();
//else
flee();
#endif
}
else
{
fightMove();
}
}
}
void ZealotUnit::check()
{
if (unit->getUpgradeLevel(UpgradeTypes::Leg_Enhancements) && !setPrio.count(UnitTypes::Terran_Siege_Tank_Siege_Mode))
{
setPrio.insert(UnitTypes::Protoss_High_Templar);
}
}
int ZealotUnit::getAttackDuration()
{
return 1;
}
std::set<UnitType> ZealotUnit::getSetPrio()
{
return ZealotUnit::setPrio;
}<commit_msg>lessen the APM of Zealot micro while retaining efficiency<commit_after>#include <PrecompiledHeader.h>
#include "Micro/Units/ProtossGround/ZealotUnit.h"
#include "Micro/UnitsGroup.h"
#include "Regions/MapManager.h"
using namespace std;
using namespace BWAPI;
ProbTables ZealotUnit::_sProbTables = ProbTables(UnitTypes::Protoss_Zealot.getID());
std::set<UnitType> ZealotUnit::setPrio;
ZealotUnit::ZealotUnit(Unit* u)
: GroundUnit(u, &_sProbTables)
{
if (setPrio.empty())
{
setPrio.insert(UnitTypes::Protoss_Reaver);
setPrio.insert(UnitTypes::Protoss_High_Templar);
setPrio.insert(UnitTypes::Terran_Siege_Tank_Siege_Mode);
setPrio.insert(UnitTypes::Terran_Siege_Tank_Tank_Mode);
setPrio.insert(UnitTypes::Zerg_Hydralisk);
setPrio.insert(UnitTypes::Zerg_Lurker);
setPrio.insert(UnitTypes::Zerg_Defiler);
}
_fleeingDmg = 36; // one round of storm = 14
}
ZealotUnit::~ZealotUnit()
{
}
#ifdef __LEARNING_PROB_TABLES__
void ZealotUnit::initProbTables()
{
_sProbTables = ProbTables(UnitTypes::Protoss_Zealot.getID());
}
#endif
int ZealotUnit::fightMove()
{
if (Broodwar->getFrameCount() - _lastClickFrame <= Broodwar->getLatencyFrames())
return 0;
/// approach our target enemy if not in range and in our priority targets
if (targetEnemy != NULL && targetEnemy->exists() && targetEnemy->isVisible() && targetEnemy->isDetected()
&& setPrio.count(targetEnemy->getType())
&& (targetEnemy->getDistance(_unitPos) > 45.0 || !inRange(targetEnemy)))
{
if (unit->getTarget() != targetEnemy)
unit->rightClick(targetEnemy);
_lastClickFrame = Broodwar->getFrameCount();
_lastMoveFrame = Broodwar->getFrameCount();
_lastAttackFrame = Broodwar->getFrameCount();
_fightMoving = true;
return 1;
}
double dist = target.getDistance(_unitPos);
/// approach out of range target
if (oorTargetEnemy != NULL && oorTargetEnemy->exists() && oorTargetEnemy->isVisible() && targetEnemy->isDetected()
&& !inRange(oorTargetEnemy))
{
if (unit->getTarget() != oorTargetEnemy)
unit->rightClick(oorTargetEnemy);
_lastClickFrame = Broodwar->getFrameCount();
_lastMoveFrame = Broodwar->getFrameCount();
_lastAttackFrame = Broodwar->getFrameCount();
_fightMoving = true;
return 2;
}
return 0;
}
bool ZealotUnit::decideToFlee()
{
_fleeing = false;
if (unit->getShields() < 5 && unit->isUnderAttack()
&& !(targetEnemy && targetEnemy->exists() && targetEnemy->isVisible() && targetEnemy->isDetected()
&& setPrio.count(targetEnemy->getType())))
_fleeing = true;
return _fleeing;
}
void ZealotUnit::updateTargetEnemy()
{
/// oorTarget = closest in the setPrio
oorTargetEnemy = NULL;
double closest = DBL_MAX;
for (map<Unit*, Position>::const_iterator it = _unitsGroup->enemies.begin();
it != _unitsGroup->enemies.end(); ++it)
{
if (!it->first->exists() || !it->first->isVisible() || !it->first->isDetected() || it->first->getType().isFlyer())
continue;
if (it->first->isDefenseMatrixed()
|| it->first->isHallucination()
|| it->first->isInvincible())
continue;
if (!it->first->getType().isFlyer()
&& setPrio.count(it->first->getType())
&& it->first->getDistance(_unitPos) < closest)
{
closest = it->first->getDistance(_unitPos);
oorTargetEnemy = it->first;
}
}
/// targetEnemy = in range, the ones in setPrio have the priority
/// otherwise the closest
targetEnemy = NULL;
Unit* closestEnemy = NULL;
closest = DBL_MAX;
for (map<Unit*, Position>::const_iterator it = _unitsGroup->enemies.begin();
it != _unitsGroup->enemies.end(); ++it)
{
/// Rule out what we don't want to attack
if (!it->first->exists() || !it->first->isVisible() || !it->first->isDetected() || it->first->getType().isFlyer())
continue;
if (it->first->isDefenseMatrixed()
|| it->first->isHallucination()
|| it->first->isInvincible())
continue;
UnitType testType = it->first->getType();
if (testType.isBuilding()
&& testType != UnitTypes::Protoss_Photon_Cannon
&& (testType != UnitTypes::Terran_Bunker || !it->first->isAttacking())
&& testType != UnitTypes::Terran_Missile_Turret
&& testType != UnitTypes::Zerg_Sunken_Colony
&& testType != UnitTypes::Zerg_Spore_Colony)
continue;
/// Take one in the setPrio and in range or one in range or the closest
if (inRange(it->first))
{
targetEnemy = it->first;
if (setPrio.count(it->first->getType()))
break;
} else
{
if (it->first->getDistance(_unitPos) < closest)
{
closest = it->first->getDistance(_unitPos);
closestEnemy = it->first;
}
}
}
if (targetEnemy == NULL)
targetEnemy = closestEnemy;
}
void ZealotUnit::flee()
{
//if (_lastTotalHP < 60)
{
for each (Unit* u in _targetingMe)
{
if (isOutrangingMe(u))
return;
}
}
_fightMoving = false;
if (!this->mapManager->groundDamages[_unitPos.x()/32 + _unitPos.y()/32*Broodwar->mapWidth()])
{
_fleeing = false;
return;
}
_fleeing = true;
updateDir();
clickDir();
}
void ZealotUnit::micro()
{
int currentFrame = Broodwar->getFrameCount();
if (unit->isStartingAttack())
_lastAttackFrame = currentFrame;
updateTargetingMe();
/// Dodge storm, drag mine, drag scarab
if (dodgeStorm() || dragMine() || dragScarab())
return;
decideToFlee();
updateTargetEnemy();
if (currentFrame - _lastClickFrame <= Broodwar->getLatencyFrames())
return;
if (currentFrame - _lastAttackFrame <= getAttackDuration()) // not interrupting attacks
return;
if (unit->getGroundWeaponCooldown() <= Broodwar->getLatencyFrames() + 2)
{
if (targetEnemy != NULL && targetEnemy->exists() && targetEnemy->isVisible() && targetEnemy->isDetected())
{
_lastClickFrame = Broodwar->getFrameCount();
_lastAttackFrame = Broodwar->getFrameCount();
if (unit->getTarget() == targetEnemy)
return;
// attack enemy unit
unit->rightClick(targetEnemy);
}
else
{
if (unit->getOrder() != Orders::AttackMove || unit->getOrderTargetPosition().getApproxDistance(_unitsGroup->enemiesCenter) > 3*TILE_SIZE)
unit->attack(_unitsGroup->enemiesCenter);
}
}
else if (unit->getGroundWeaponCooldown() > Broodwar->getLatencyFrames() + 2) // (Broodwar->getLatencyFrames()+1)*2, safety
{
if (_fleeing)
{
#ifdef __SIMPLE_FLEE__
simpleFlee();
#else
//if (unit->isStuck()) // TODO do something with it
// simpleFlee();
//else
flee();
#endif
}
else
{
fightMove();
}
}
}
void ZealotUnit::check()
{
if (unit->getUpgradeLevel(UpgradeTypes::Leg_Enhancements) && !setPrio.count(UnitTypes::Terran_Siege_Tank_Siege_Mode))
{
setPrio.insert(UnitTypes::Protoss_High_Templar);
}
}
int ZealotUnit::getAttackDuration()
{
return 1;
}
std::set<UnitType> ZealotUnit::getSetPrio()
{
return ZealotUnit::setPrio;
}<|endoftext|> |
<commit_before>#pragma once
#include "But/Format/Parsed.hpp"
#include "argumentsCountWithChecks.hpp"
namespace But
{
namespace Format
{
namespace detail
{
template<size_t ArgumentsCount>
struct CompiletimeCheckedFormatProxy final
{
static auto make(char const* fmt) { return Parsed{fmt}; }
};
#define BUT_FORMAT_DETAIL_FORMAT_COMPILETIME_IMPL(fmt, N) \
::But::Format::detail::CompiletimeChckedFormatProxy< ::But::Format::detail::argumentsCountWithChecks<N>(fmt) >::make(fmt)
#define BUT_FORMAT_DETAIL_FORMAT_RUNTIME_IMPL(fmt) \
::But::Format::Parsed{fmt}
}
}
}
<commit_msg>interface aligned to new Parsed* classes<commit_after>#pragma once
#include "But/Format/Parsed.hpp"
#include "argumentsCountWithChecks.hpp"
namespace But
{
namespace Format
{
namespace detail
{
#define BUT_FORMAT_DETAIL_FORMAT_COMPILETIME_IMPL(fmt, N) \
::But::Format::ParsedCompiletime< ::But::Format::detail::argumentsCountWithChecks<N>(fmt), N >::make(fmt)
#define BUT_FORMAT_DETAIL_FORMAT_RUNTIME_IMPL(fmt) \
::But::Format::ParsedRuntime{fmt}
}
}
}
<|endoftext|> |
<commit_before>#include "MUSI8903Config.h"
#ifdef WITH_TESTS
#include <cassert>
#include <cstdio>
#include <fstream>
#include "UnitTest++.h"
#include <vector>
#include "FastConv.h"
#include "Synthesis.h"
extern std::string cTestDataDir;
SUITE(FastConv)
{
struct FastConvData
{
FastConvData()
{
CFastConv::create( m_pCFastConv );
}
~FastConvData()
{
CFastConv::destroy( m_pCFastConv );
}
CFastConv *m_pCFastConv;
float m_fImpulseResponse,
m_fInputSignal;
};
// only for testing the basic convolution equation works
// TEST_FIXTURE(FastConvData, convTest) {
// float impulse[6] = { 1, 2, 3, 4, 5, 6},
// input[3] = { 7, 8, 9},
// output[8] = { 7, 22, 46, 70, 94, 118, 93, 54};
// float *procOut = new float[8];
//
// m_pCFastConv->init( impulse, 6, 5, CFastConv::kTimeDomain );
// m_pCFastConv->process( input, procOut, 3 );
//
// CHECK_ARRAY_EQUAL( output, procOut, 8 );
// }
// TEST_FIXTURE(FastConvData, inputBufferStorageTest) {
// float input[18],
// impulse[4] = { 1, 1, 1, 1};
// float *procOut = new float[21];
// int blockLen = 3;
//
// for( int sample =0; sample<18; sample++) {
// input[sample] = sample*1.0f;
// }
//
// m_pCFastConv->init( impulse, 4, blockLen, CFastConv::kTimeDomain );
// for( int block = 0; block<6; block++ ) {
// m_pCFastConv->process( &input[block*blockLen], &procOut[block*blockLen], blockLen );
// }
// }
// TEST_FIXTURE
// //Question3.1
// TEST_FIXTURE(FastConvData, IrTest)
// {
// //create a impulse response of 51 seconds with random index of 1
// int iSampleRate = 44100;
// int iIRLengthInSec = 30;
// int iIRLengthInSample = iSampleRate * iIRLengthInSec;
// float* pfRandomIR = new float[iIRLengthInSample];
// float decEnv = 1;
//
// for (int sample = 0; sample < iIRLengthInSample; sample++) {
// pfRandomIR[sample] = decEnv - 0.1f * (static_cast <float> (rand()) / static_cast <float> (RAND_MAX));
// if (sample % 10000 == 0) {
// // std::cout<<pfRandomIR[sample]<<" "<<decEnv<<std::endl;
// }
// // decEnv = decEnv-1/iIRLengthInSample;
// }
//
// // create a input signal: delayed impulse (5 samples)
// int iInputLength = 10000;
// float* pfInputSignal = new float[iInputLength];
// float* pfOutputSignal = new float[iIRLengthInSample + iInputLength - 1];
//
// for( int sample = 0; sample<iInputLength; sample++) {
// pfInputSignal[sample] = 0.0f;
// }
// pfInputSignal[5] = 1.f;
//
// // create the reference signal: shifted IR (5 samples)
// float* pfReference = new float[iIRLengthInSample];
// for (int sample = 0; sample < 5; sample++) {
// pfReference[sample] = 0.f;
// }
// for (int sample = 5; sample < iIRLengthInSample; sample++) {
// pfReference[sample] = pfRandomIR[sample - 5];
// }
//
// // identity test using process function
// m_pCFastConv->init(pfRandomIR, iIRLengthInSample, 4096, CFastConv::kTimeDomain);
// m_pCFastConv->process(pfInputSignal, pfOutputSignal, iInputLength);
//
// CHECK_ARRAY_EQUAL( pfReference, pfOutputSignal, iIRLengthInSample );
//
// delete pfRandomIR; pfRandomIR = 0;
// delete pfInputSignal; pfInputSignal = 0;
// delete pfOutputSignal; pfOutputSignal = 0;
// delete pfReference; pfReference = 0;
// }
//Question3.2
TEST_FIXTURE(FastConvData, InputBlockLengthTest)
{
m_pCFastConv->reset();
//generate a 1 second sawtooth wave of 50 Hz for test (sample rate 10000)
int iInputSampleRate = 10000;
int iInputLengthInSec = 1;
int iInputLengthInSample = iInputLengthInSec * iInputSampleRate;
float* pfInputSignal = new float[iInputLengthInSample];
// CSynthesis::generateSaw(pfInputSignal, 50, iInputSampleRate, iInputLengthInSample);
CSynthesis::generateSine(pfInputSignal, 50, iInputSampleRate, iInputLengthInSample);
//generate a impulse response: decayed sine wave
int iIRSampleRate = iInputSampleRate;
int iIRLengthInSec = iInputLengthInSec;
int iIRLengthInSample = iIRSampleRate * iIRLengthInSec;
float* pfImpulseResponse = new float[iIRLengthInSample];
CSynthesis::generateSine(pfImpulseResponse, 100, iIRSampleRate, iIRLengthInSample);
float param = 0.f;
for (int sample = 0; sample < iIRLengthInSample; sample++) {
pfImpulseResponse[sample] = expf(-param) * pfImpulseResponse[sample];
param = param + 1.f/iIRSampleRate;
}
//creat a output buffer
int iOutputLengthInSample = iInputLengthInSample + iIRLengthInSample - 1;
float* pfOutputSignal = new float[iOutputLengthInSample];
// create a array of block size
int iaBlockSize[8] = {1, 13, 1023, 2048, 1, 17, 5000, 1897};
//Read Reference Output
std::ifstream inputFile;
inputFile.open(cTestDataDir + "testOutput.txt");
std::ofstream outputFile(cTestDataDir + "myOut1.txt");
std::istream_iterator<float> start( inputFile ), end;
std::vector<float> outputRef( start, end );
// std::ostream_iterator<float> outputStream(std::cout," , ");
// std::copy(outputRef.begin(),outputRef.end(),outputStream);
for (int nthBlockSize = 0; nthBlockSize < 8; nthBlockSize++) {
// for each block size, run the corresponding test process
m_pCFastConv->init( pfImpulseResponse, iIRLengthInSample, iaBlockSize[nthBlockSize], CFastConv::kTimeDomain );
m_pCFastConv->process( pfInputSignal, pfOutputSignal, iInputLengthInSample);
for(int sample=0; sample<iOutputLengthInSample; sample++ ) {
outputFile<<pfOutputSignal[sample]<<"\n";
}
CHECK_ARRAY_CLOSE(outputRef, pfOutputSignal,iOutputLengthInSample, 4e-3);
}
inputFile.close();
outputFile.close();
delete pfInputSignal; pfInputSignal = 0;
delete pfOutputSignal; pfOutputSignal = 0;
delete pfImpulseResponse; pfImpulseResponse = 0;
}
}
#endif //WITH_TESTS
<commit_msg>Run test for fast convolution<commit_after>#include "MUSI8903Config.h"
#ifdef WITH_TESTS
#include <cassert>
#include <cstdio>
#include <fstream>
#include "UnitTest++.h"
#include <vector>
#include "FastConv.h"
#include "Synthesis.h"
extern std::string cTestDataDir;
SUITE(FastConv)
{
struct FastConvData
{
FastConvData()
{
CFastConv::create( m_pCFastConv );
}
~FastConvData()
{
CFastConv::destroy( m_pCFastConv );
}
CFastConv *m_pCFastConv;
float m_fImpulseResponse,
m_fInputSignal;
};
// only for testing the basic convolution equation works
TEST_FIXTURE(FastConvData, convTest) {
float impulse[6] = { 1, 2, 3, 4, 5, 6},
input[3] = { 7, 8, 9},
output[8] = { 7, 22, 46, 70, 94, 118, 93, 54};
float *procOut = new float[8];
m_pCFastConv->init( impulse, 6, 5, CFastConv::kTimeDomain );
m_pCFastConv->process( input, procOut, 3 );
CHECK_ARRAY_EQUAL( output, procOut, 8 );
}
TEST_FIXTURE(FastConvData, inputBufferStorageTest) {
float input[18],
impulse[4] = { 1, 1, 1, 1};
float *procOut = new float[21];
int blockLen = 3;
for( int sample =0; sample<18; sample++) {
input[sample] = sample*1.0f;
}
m_pCFastConv->init( impulse, 4, blockLen, CFastConv::kTimeDomain );
for( int block = 0; block<6; block++ ) {
m_pCFastConv->process( &input[block*blockLen], &procOut[block*blockLen], blockLen );
}
delete procOut; procOut = 0;
}
//Question3.1
TEST_FIXTURE(FastConvData, IrTest)
{
//create a impulse response of 51 seconds with random index of 1
int iSampleRate = 44100;
int iIRLengthInSec = 30;
int iIRLengthInSample = iSampleRate * iIRLengthInSec;
float* pfRandomIR = new float[iIRLengthInSample];
float decEnv = 1;
for (int sample = 0; sample < iIRLengthInSample; sample++) {
pfRandomIR[sample] = decEnv - 0.1f * (static_cast <float> (rand()) / static_cast <float> (RAND_MAX));
if (sample % 10000 == 0) {
// std::cout<<pfRandomIR[sample]<<" "<<decEnv<<std::endl;
}
// decEnv = decEnv-1/iIRLengthInSample;
}
// create a input signal: delayed impulse (5 samples)
int iInputLength = 10000;
float* pfInputSignal = new float[iInputLength];
float* pfOutputSignal = new float[iIRLengthInSample + iInputLength - 1];
for( int sample = 0; sample<iInputLength; sample++) {
pfInputSignal[sample] = 0.0f;
}
pfInputSignal[5] = 1.f;
// create the reference signal: shifted IR (5 samples)
float* pfReference = new float[iIRLengthInSample];
for (int sample = 0; sample < 5; sample++) {
pfReference[sample] = 0.f;
}
for (int sample = 5; sample < iIRLengthInSample; sample++) {
pfReference[sample] = pfRandomIR[sample - 5];
}
// identity test using process function
m_pCFastConv->init(pfRandomIR, iIRLengthInSample, 4096, CFastConv::kTimeDomain);
m_pCFastConv->process(pfInputSignal, pfOutputSignal, iInputLength);
CHECK_ARRAY_EQUAL( pfReference, pfOutputSignal, iIRLengthInSample );
delete pfRandomIR; pfRandomIR = 0;
delete pfInputSignal; pfInputSignal = 0;
delete pfOutputSignal; pfOutputSignal = 0;
delete pfReference; pfReference = 0;
}
//Question3.2
TEST_FIXTURE(FastConvData, InputBlockLengthTest)
{
m_pCFastConv->reset();
//generate a 1 second sawtooth wave of 50 Hz for test (sample rate 10000)
int iInputSampleRate = 10000;
int iInputLengthInSec = 1;
int iInputLengthInSample = iInputLengthInSec * iInputSampleRate;
float* pfInputSignal = new float[iInputLengthInSample];
// CSynthesis::generateSaw(pfInputSignal, 50, iInputSampleRate, iInputLengthInSample);
CSynthesis::generateSine(pfInputSignal, 50, iInputSampleRate, iInputLengthInSample);
//generate a impulse response: decayed sine wave
int iIRSampleRate = iInputSampleRate;
int iIRLengthInSec = iInputLengthInSec;
int iIRLengthInSample = iIRSampleRate * iIRLengthInSec;
float* pfImpulseResponse = new float[iIRLengthInSample];
CSynthesis::generateSine(pfImpulseResponse, 100, iIRSampleRate, iIRLengthInSample);
float param = 0.f;
for (int sample = 0; sample < iIRLengthInSample; sample++) {
pfImpulseResponse[sample] = expf(-param) * pfImpulseResponse[sample];
param = param + 1.f/iIRSampleRate;
}
//creat a output buffer
int iOutputLengthInSample = iInputLengthInSample + iIRLengthInSample - 1;
float* pfOutputSignal = new float[iOutputLengthInSample];
// create a array of block size
int iaBlockSize[8] = {1, 13, 1023, 2048, 1, 17, 5000, 1897};
//Read Reference Output
std::ifstream inputFile;
inputFile.open(cTestDataDir + "testOutput.txt");
std::ofstream outputFile(cTestDataDir + "myOut1.txt");
std::istream_iterator<float> start( inputFile ), end;
std::vector<float> outputRef( start, end );
// std::ostream_iterator<float> outputStream(std::cout," , ");
// std::copy(outputRef.begin(),outputRef.end(),outputStream);
for (int nthBlockSize = 0; nthBlockSize < 8; nthBlockSize++) {
// for each block size, run the corresponding test process
m_pCFastConv->init( pfImpulseResponse, iIRLengthInSample, iaBlockSize[nthBlockSize], CFastConv::kTimeDomain );
m_pCFastConv->process( pfInputSignal, pfOutputSignal, iInputLengthInSample);
for(int sample=0; sample<iOutputLengthInSample; sample++ ) {
outputFile<<pfOutputSignal[sample]<<"\n";
}
CHECK_ARRAY_CLOSE(outputRef, pfOutputSignal,iOutputLengthInSample, 4e-3);
}
inputFile.close();
outputFile.close();
delete pfInputSignal; pfInputSignal = 0;
delete pfOutputSignal; pfOutputSignal = 0;
delete pfImpulseResponse; pfImpulseResponse = 0;
}
}
#endif //WITH_TESTS
<|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.
//
// --------------------------------------------------------------
// Radial NC: radial non-conforming mesh generator
// --------------------------------------------------------------
//
// This miniapp TODO
//
// Compile with: make radial-nc
//
// Sample runs: radial-nc
// radial-nc TODO
#include "mfem.hpp"
#include <fstream>
#include <iostream>
using namespace mfem;
using namespace std;
struct Params
{
double r, dr;
double a, da;
Params() = default;
Params(double r0, double r1, double a0, double a1)
: r(r0), dr(r1 - r0), a(a0), da(a1 - a0) {}
};
Mesh* Make2D(int nsteps, double rstep, double phi, double aspect, int order)
{
Mesh *mesh = new Mesh(2, 0, 0);
int origin = mesh->AddVertex(0.0, 0.0);
// n is the number of steps in the polar direction
int n = 1;
while (phi * rstep / n * aspect > rstep) { n++; }
double r = rstep;
int first = mesh->AddVertex(r, 0.0);
Array<Params> params;
// create triangles around the origin
double prev_alpha = 0.0;
for (int i = 0; i < n; i++)
{
double alpha = phi * (i+1) / n;
mesh->AddVertex(r*cos(alpha), r*sin(alpha));
mesh->AddTriangle(origin, first+i, first+i+1);
params.Append(Params(0, r, prev_alpha, alpha));
prev_alpha = alpha;
}
mesh->AddBdrSegment(origin, first, 1);
mesh->AddBdrSegment(first+n, origin, 2);
for (int k = 1; k < nsteps; k++)
{
// m is the number of polar steps of the previous row
int m = n;
int prev_first = first;
double prev_r = r;
r += rstep;
if (phi * (r + prev_r)/2 / n * aspect <= rstep)
{
first = mesh->AddVertex(r, 0.0);
mesh->AddBdrSegment(prev_first, first, 1);
// create a row of quads, same number as in previous row
prev_alpha = 0.0;
for (int i = 0; i < n; i++)
{
double alpha = phi * (i+1) / n;
mesh->AddVertex(r*cos(alpha), r*sin(alpha));
mesh->AddQuad(prev_first+i, first+i, first+i+1, prev_first+i+1);
params.Append(Params(prev_r, r, prev_alpha, alpha));
prev_alpha = alpha;
}
mesh->AddBdrSegment(first+n, prev_first+n, 2);
}
else // we need to double the number of elements per row
{
n *= 2;
// first create hanging vertices
int hang;
for (int i = 0; i < m; i++)
{
double alpha = phi * (2*i+1) / n;
int index = mesh->AddVertex(prev_r*cos(alpha), prev_r*sin(alpha));
mesh->AddVertexParents(index, prev_first+i, prev_first+i+1);
if (!i) { hang = index; }
}
first = mesh->AddVertex(r, 0.0);
int a = prev_first, b = first;
mesh->AddBdrSegment(a, b, 1);
// create a row of quad pairs
prev_alpha = 0.0;
for (int i = 0; i < m; i++)
{
int c = hang+i, e = a+1;
double alpha_half = phi * (2*i+1) / n;
int d = mesh->AddVertex(r*cos(alpha_half), r*sin(alpha_half));
double alpha = phi * (2*i+2) / n;
int f = mesh->AddVertex(r*cos(alpha), r*sin(alpha));
mesh->AddQuad(a, b, d, c);
mesh->AddQuad(c, d, f, e);
a = e, b = f;
params.Append(Params(prev_r, r, prev_alpha, alpha_half));
params.Append(Params(prev_r, r, alpha_half, alpha));
prev_alpha = alpha;
}
mesh->AddBdrSegment(b, a, 2);
}
}
for (int i = 0; i < n; i++)
{
mesh->AddBdrSegment(first+i, first+i+1, 3);
}
mesh->FinalizeMesh();
// create high-order curvature
if (order > 1)
{
mesh->SetCurvature(order);
GridFunction *nodes = mesh->GetNodes();
const FiniteElementSpace *fes = mesh->GetNodalFESpace();
Array<int> dofs;
MFEM_ASSERT(params.Size() == mesh->GetNE(), "");
for (int i = 0; i < mesh->GetNE(); i++)
{
const Params &par = params[i];
const IntegrationRule &ir = fes->GetFE(i)->GetNodes();
Geometry::Type geom = mesh->GetElementBaseGeometry(i);
fes->GetElementDofs(i, dofs);
for (int j = 0; j < dofs.Size(); j++)
{
double r, a;
if (geom == Geometry::SQUARE)
{
r = par.r + ir[j].x * par.dr;
a = par.a + ir[j].y * par.da;
}
else
{
double rr = ir[j].x + ir[j].y;
if (std::abs(rr) < 1e-12) { continue; }
r = par.r + rr * par.dr;
a = par.a + ir[j].y/rr * par.da;
}
(*nodes)(fes->DofToVDof(dofs[j], 0)) = r*cos(a);
(*nodes)(fes->DofToVDof(dofs[j], 1)) = r*sin(a);
}
}
nodes->RestrictConforming();
}
return mesh;
}
int main(int argc, char *argv[])
{
int dim = 2;
double radius = 1.0;
int nsteps = 10;
double angle = 90;
double aspect = 1.0;
int order = 2;
// Parse command line
OptionsParser args(argc, argv);
args.AddOption(&dim, "-d", "--dim", "Mesh dimension (2 or 3).");
args.AddOption(&radius, "-r", "--radius", "Radius of the domain.");
args.AddOption(&nsteps, "-n", "--nsteps",
"Number of elements along the radial direction");
args.AddOption(&aspect, "-a", "--aspect",
"Target aspect ratio of the elements.");
args.AddOption(&angle, "-phi", "--phi", "Angular range.");
args.AddOption(&order, "-o", "--order",
"Polynomial degree of mesh curvature.");
args.Parse();
if (!args.Good())
{
args.PrintUsage(cout);
return EXIT_FAILURE;
}
args.PrintOptions(cout);
MFEM_VERIFY(angle < 360, "");
double phi = angle * M_PI / 180;
// Generate
Mesh *mesh;
if (dim == 2)
{
mesh = Make2D(nsteps, radius/nsteps, phi, aspect, order);
}
else
{
MFEM_ABORT("TODO");
}
// Save the final mesh
ofstream ofs("radial.mesh");
ofs.precision(8);
mesh->Print(ofs);
delete mesh;
return EXIT_SUCCESS;
}
<commit_msg>radial-nc: added SFC ordering option.<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.
//
// --------------------------------------------------------------
// Radial NC: radial non-conforming mesh generator
// --------------------------------------------------------------
//
// This miniapp TODO
//
// Compile with: make radial-nc
//
// Sample runs: radial-nc
// radial-nc TODO
#include "mfem.hpp"
#include <fstream>
#include <iostream>
using namespace mfem;
using namespace std;
struct Params
{
double r, dr;
double a, da;
Params() = default;
Params(double r0, double r1, double a0, double a1)
: r(r0), dr(r1 - r0), a(a0), da(a1 - a0) {}
};
Mesh* Make2D(int nsteps, double rstep, double phi, double aspect, int order,
bool sfc)
{
Mesh *mesh = new Mesh(2, 0, 0);
int origin = mesh->AddVertex(0.0, 0.0);
// n is the number of steps in the polar direction
int n = 1;
while (phi * rstep / n * aspect > rstep) { n++; }
double r = rstep;
int first = mesh->AddVertex(r, 0.0);
Array<Params> params;
Array<Pair<int, int>> blocks;
// create triangles around the origin
double prev_alpha = 0.0;
for (int i = 0; i < n; i++)
{
double alpha = phi * (i+1) / n;
mesh->AddVertex(r*cos(alpha), r*sin(alpha));
mesh->AddTriangle(origin, first+i, first+i+1);
params.Append(Params(0, r, prev_alpha, alpha));
prev_alpha = alpha;
}
mesh->AddBdrSegment(origin, first, 1);
mesh->AddBdrSegment(first+n, origin, 2);
for (int k = 1; k < nsteps; k++)
{
// m is the number of polar steps of the previous row
int m = n;
int prev_first = first;
double prev_r = r;
r += rstep;
if (phi * (r + prev_r)/2 / n * aspect <= rstep)
{
if (k == 1) { blocks.Append(Pair<int, int>(mesh->GetNE(), n)); }
first = mesh->AddVertex(r, 0.0);
mesh->AddBdrSegment(prev_first, first, 1);
// create a row of quads, same number as in previous row
prev_alpha = 0.0;
for (int i = 0; i < n; i++)
{
double alpha = phi * (i+1) / n;
mesh->AddVertex(r*cos(alpha), r*sin(alpha));
mesh->AddQuad(prev_first+i, first+i, first+i+1, prev_first+i+1);
params.Append(Params(prev_r, r, prev_alpha, alpha));
prev_alpha = alpha;
}
mesh->AddBdrSegment(first+n, prev_first+n, 2);
}
else // we need to double the number of elements per row
{
n *= 2;
blocks.Append(Pair<int, int>(mesh->GetNE(), n));
// first create hanging vertices
int hang;
for (int i = 0; i < m; i++)
{
double alpha = phi * (2*i+1) / n;
int index = mesh->AddVertex(prev_r*cos(alpha), prev_r*sin(alpha));
mesh->AddVertexParents(index, prev_first+i, prev_first+i+1);
if (!i) { hang = index; }
}
first = mesh->AddVertex(r, 0.0);
int a = prev_first, b = first;
mesh->AddBdrSegment(a, b, 1);
// create a row of quad pairs
prev_alpha = 0.0;
for (int i = 0; i < m; i++)
{
int c = hang+i, e = a+1;
double alpha_half = phi * (2*i+1) / n;
int d = mesh->AddVertex(r*cos(alpha_half), r*sin(alpha_half));
double alpha = phi * (2*i+2) / n;
int f = mesh->AddVertex(r*cos(alpha), r*sin(alpha));
mesh->AddQuad(a, b, d, c);
mesh->AddQuad(c, d, f, e);
a = e, b = f;
params.Append(Params(prev_r, r, prev_alpha, alpha_half));
params.Append(Params(prev_r, r, alpha_half, alpha));
prev_alpha = alpha;
}
mesh->AddBdrSegment(b, a, 2);
}
}
for (int i = 0; i < n; i++)
{
mesh->AddBdrSegment(first+i, first+i+1, 3);
}
// reorder blocks of elements with Grid SFC ordering
if (sfc)
{
blocks.Append(Pair<int, int>(mesh->GetNE(), 0));
Array<Params> new_params(params.Size());
Array<int> ordering(mesh->GetNE());
for (int i = 0; i < blocks[0].one; i++)
{
ordering[i] = i;
new_params[i] = params[i];
}
Array<int> coords;
for (int i = 0; i < blocks.Size()-1; i++)
{
int beg = blocks[i].one;
int width = blocks[i].two;
int height = (blocks[i+1].one - blocks[i].one) / width;
NCMesh::GridSfcOrdering2D(width, height, coords);
for (int j = 0, k = 0; j < coords.Size(); k++, j += 2)
{
int sfc = ((i & 1) ? coords[j] : width-1 - coords[j]) + coords[j+1]*width;
int old_index = beg + sfc;
ordering[old_index] = beg + k;
new_params[beg + k] = params[old_index];
}
}
mesh->ReorderElements(ordering, false);
mfem::Swap(params, new_params);
}
mesh->FinalizeMesh();
// create high-order curvature
if (order > 1)
{
mesh->SetCurvature(order);
GridFunction *nodes = mesh->GetNodes();
const FiniteElementSpace *fes = mesh->GetNodalFESpace();
Array<int> dofs;
MFEM_ASSERT(params.Size() == mesh->GetNE(), "");
for (int i = 0; i < mesh->GetNE(); i++)
{
const Params &par = params[i];
const IntegrationRule &ir = fes->GetFE(i)->GetNodes();
Geometry::Type geom = mesh->GetElementBaseGeometry(i);
fes->GetElementDofs(i, dofs);
for (int j = 0; j < dofs.Size(); j++)
{
double r, a;
if (geom == Geometry::SQUARE)
{
r = par.r + ir[j].x * par.dr;
a = par.a + ir[j].y * par.da;
}
else
{
double rr = ir[j].x + ir[j].y;
if (std::abs(rr) < 1e-12) { continue; }
r = par.r + rr * par.dr;
a = par.a + ir[j].y/rr * par.da;
}
(*nodes)(fes->DofToVDof(dofs[j], 0)) = r*cos(a);
(*nodes)(fes->DofToVDof(dofs[j], 1)) = r*sin(a);
}
}
nodes->RestrictConforming();
}
return mesh;
}
int main(int argc, char *argv[])
{
int dim = 2;
double radius = 1.0;
int nsteps = 10;
double angle = 90;
double aspect = 1.0;
int order = 2;
bool sfc = true;
// Parse command line
OptionsParser args(argc, argv);
args.AddOption(&dim, "-d", "--dim", "Mesh dimension (2 or 3).");
args.AddOption(&radius, "-r", "--radius", "Radius of the domain.");
args.AddOption(&nsteps, "-n", "--nsteps",
"Number of elements along the radial direction");
args.AddOption(&aspect, "-a", "--aspect",
"Target aspect ratio of the elements.");
args.AddOption(&angle, "-phi", "--phi", "Angular range.");
args.AddOption(&order, "-o", "--order",
"Polynomial degree of mesh curvature.");
args.AddOption(&sfc, "-sfc", "--sfc", "-no-sfc", "--no-sfc",
"Try to order elements along a space-filling curve.");
args.Parse();
if (!args.Good())
{
args.PrintUsage(cout);
return EXIT_FAILURE;
}
args.PrintOptions(cout);
// validate options
MFEM_VERIFY(dim >= 2 && dim <= 3, "");
MFEM_VERIFY(angle > 0 && angle < 360, "");
MFEM_VERIFY(nsteps > 0, "");
double phi = angle * M_PI / 180;
// Generate
Mesh *mesh;
if (dim == 2)
{
mesh = Make2D(nsteps, radius/nsteps, phi, aspect, order, sfc);
}
else
{
MFEM_ABORT("TODO");
}
// Save the final mesh
ofstream ofs("radial.mesh");
ofs.precision(8);
mesh->Print(ofs);
delete mesh;
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>/*
The OpenTRV project licenses this file to you
under the Apache Licence, Version 2.0 (the "Licence");
you may not use this file except in compliance
with the Licence. You may obtain a copy of the Licence at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the Licence is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the Licence for the
specific language governing permissions and limitations
under the Licence.
Author(s) / Copyright (s): Damon Hart-Davis 2013--2016
*/
/*
Schedule support for TRV.
*/
#include <avr/eeprom.h>
#include <util/atomic.h>
#include "Schedule.h"
#include "Control.h"
#if defined(UNIT_TESTS)
// Support for unit tests to force particular apparent schedule state.
// Current override state; 0 (default) means no override.
static _TEST_schedule_override _soUT_override;
// Set the override value (or remove the override).
void _TEST_set_schedule_override(const _TEST_schedule_override override)
{ _soUT_override = override; }
#endif
// All EEPROM activity is made atomic by locking out interrupts where necessary.
// Maximum mins-after-midnight compacted value in one byte.
static const uint8_t MAX_COMPRESSED_MINS_AFTER_MIDNIGHT = ((OTV0P2BASE::MINS_PER_DAY / SIMPLE_SCHEDULE_GRANULARITY_MINS) - 1);
// If LEARN_BUTTON_AVAILABLE then what is the schedule on time?
//#ifdef LEARN_BUTTON_AVAILABLE
// Number of minutes of schedule on time to use.
// Will depend on eco bias.
// TODO: make gradual.
static uint8_t onTime()
{
#if LEARNED_ON_PERIOD_M == LEARNED_ON_PERIOD_COMFORT_M
// Simplify the logic where no variation in on time is required.
return(LEARNED_ON_PERIOD_M);
#else
// Variable 'on' time depending on how 'eco' the settings are.
// // Simple and fast binary choice.
// return(hasEcoBias() ? LEARNED_ON_PERIOD_M : LEARNED_ON_PERIOD_COMFORT_M);
// Three-way split based on current WARM target temperature,
// for a relatively gentle change in behaviour along the valve dial for example.
const uint8_t wt = getWARMTargetC();
if(isEcoTemperature(wt)) { return(LEARNED_ON_PERIOD_M); }
else if(isComfortTemperature(wt)) { return(LEARNED_ON_PERIOD_COMFORT_M); }
else { return((LEARNED_ON_PERIOD_M + LEARNED_ON_PERIOD_COMFORT_M) / 2); }
#endif
}
// #endif // LEARN_BUTTON_AVAILABLE
// Pre-warm time before learned/scheduled WARM period,
// based on basic scheduled on time and allowing for some wobble in the timing resolution.
// DHD20151122: even half an hour may not be enough if very cold and heating system not good.
const uint8_t PREWARM_MINS = max(30, (SIMPLE_SCHEDULE_GRANULARITY_MINS + (LEARNED_ON_PERIOD_M/2)));
// Setback period before WARM period to help ensure that the WARM target can be reached on time.
// Important for slow-to-heat rooms that have become very cold.
// Similar to or a little longer than PREWARM_MINS
// so that we can safely use this without causing distress, eg waking people up.
const uint8_t PREPREWARM_MINS = (3*(PREWARM_MINS/2));
// Get the simple/primary schedule on time, as minutes after midnight [0,1439]; invalid (eg ~0) if none set.
// Will usually include a pre-warm time before the actual time set.
// Note that unprogrammed EEPROM value will result in invalid time, ie schedule not set.
// * which schedule number, counting from 0
uint_least16_t getSimpleScheduleOn(const uint8_t which)
{
if(which >= MAX_SIMPLE_SCHEDULES) { return(~0); } // Invalid schedule number.
uint8_t startMM;
ATOMIC_BLOCK (ATOMIC_RESTORESTATE)
{ startMM = eeprom_read_byte((uint8_t*)(V0P2BASE_EE_START_SIMPLE_SCHEDULE0_ON + which)); }
if(startMM > MAX_COMPRESSED_MINS_AFTER_MIDNIGHT) { return(~0); } // No schedule set.
// Compute start time from stored schedule value.
uint_least16_t startTime = SIMPLE_SCHEDULE_GRANULARITY_MINS * startMM;
// If LEARN_BUTTON_AVAILABLE then in the absence of anything better SUPPORT_SINGLETON_SCHEDULE should be supported.
#ifdef LEARN_BUTTON_AVAILABLE
const uint8_t windBackM = PREWARM_MINS; // Wind back start time by about 25% of full interval.
if(windBackM > startTime) { startTime += OTV0P2BASE::MINS_PER_DAY; } // Allow for wrap-around at midnight.
startTime -= windBackM;
#endif
return(startTime);
}
// Get the simple/primary schedule off time, as minutes after midnight [0,1439]; invalid (eg ~0) if none set.
// This is based on specified start time and some element of the current eco/comfort bias.
// * which schedule number, counting from 0
uint_least16_t getSimpleScheduleOff(const uint8_t which)
{
const uint_least16_t startMins = getSimpleScheduleOn(which);
if(startMins == (uint_least16_t)~0) { return(~0); }
// Compute end from start, allowing for wrap-around at midnight.
uint_least16_t endTime = startMins + PREWARM_MINS + onTime();
if(endTime >= OTV0P2BASE::MINS_PER_DAY) { endTime -= OTV0P2BASE::MINS_PER_DAY; } // Allow for wrap-around at midnight.
return(endTime);
}
// Set the simple/primary simple on time.
// * startMinutesSinceMidnightLT is start/on time in minutes after midnight [0,1439]
// * which schedule number, counting from 0
// Invalid parameters will be ignored and false returned,
// else this will return true and isSimpleScheduleSet() will return true after this.
// NOTE: over-use of this routine can prematurely wear out the EEPROM.
bool setSimpleSchedule(const uint_least16_t startMinutesSinceMidnightLT, const uint8_t which)
{
if(which >= MAX_SIMPLE_SCHEDULES) { return(false); } // Invalid schedule number.
if(startMinutesSinceMidnightLT >= OTV0P2BASE::MINS_PER_DAY) { return(false); } // Invalid time.
// Set the schedule, minimising wear.
const uint8_t startMM = startMinutesSinceMidnightLT / SIMPLE_SCHEDULE_GRANULARITY_MINS; // Round down...
ATOMIC_BLOCK (ATOMIC_RESTORESTATE)
{ OTV0P2BASE::eeprom_smart_update_byte((uint8_t*)(V0P2BASE_EE_START_SIMPLE_SCHEDULE0_ON + which), startMM); }
return(true); // Assume EEPROM programmed OK...
}
// Clear a simple schedule.
// There will be neither on nor off events from the selected simple schedule once this is called.
// * which schedule number, counting from 0
void clearSimpleSchedule(const uint8_t which)
{
if(which >= MAX_SIMPLE_SCHEDULES) { return; } // Invalid schedule number.
// Clear the schedule back to 'unprogrammed' values, minimising wear.
ATOMIC_BLOCK (ATOMIC_RESTORESTATE)
{ OTV0P2BASE::eeprom_smart_erase_byte((uint8_t*)(V0P2BASE_EE_START_SIMPLE_SCHEDULE0_ON + which)); }
}
// Returns true if any simple schedule is set, false otherwise.
// This implementation just checks for any valid schedule 'on' time.
// In unit-test override mode is true for soon/now, false for off.
bool isAnySimpleScheduleSet()
{
#if defined(UNIT_TESTS)
// Special behaviour for unit tests.
switch(_soUT_override)
{
case _soUT_off: return(false);
case _soUT_soon: return(true);
case _soUT_now: return(true);
}
#endif
ATOMIC_BLOCK (ATOMIC_RESTORESTATE)
{
for(uint8_t which = 0; which < MAX_SIMPLE_SCHEDULES; ++which)
{
if(eeprom_read_byte((uint8_t*)(V0P2BASE_EE_START_SIMPLE_SCHEDULE0_ON + which)) <= MAX_COMPRESSED_MINS_AFTER_MIDNIGHT)
{ return(true); }
}
}
return(false);
}
// True iff any schedule is currently 'on'/'WARM' even when schedules overlap.
// May be relatively slow/expensive.
// Can be used to suppress all 'off' activity except for the final one.
// Can be used to suppress set-backs during on times.
// In unit-test override mode is true for now, false for soon/off.
bool isAnyScheduleOnWARMNow()
{
#if defined(UNIT_TESTS)
// Special behaviour for unit tests.
switch(_soUT_override)
{
case _soUT_off: return(false);
case _soUT_soon: return(false);
case _soUT_now: return(true);
}
#endif
const uint_least16_t mm = OTV0P2BASE::getMinutesSinceMidnightLT();
for(uint8_t which = 0; which < MAX_SIMPLE_SCHEDULES; ++which)
{
const uint_least16_t s = getSimpleScheduleOn(which);
if(mm < s) { continue; } // Also deals with case where this schedule is not set at all (s == ~0);
uint_least16_t e = getSimpleScheduleOff(which);
if(e < s) { e += OTV0P2BASE::MINS_PER_DAY; } // Cope with schedule wrap around midnight.
if(mm < e) { return(true); }
}
return(false);
}
// True iff any schedule is due 'on'/'WARM' soon even when schedules overlap.
// May be relatively slow/expensive.
// Can be used to allow room to be brought up to at least a set-back temperature
// if very cold when a WARM period is due soon (to help ensure that WARM target is met on time).
// In unit-test override mode is true for soon, false for now/off.
bool isAnyScheduleOnWARMSoon()
{
#if defined(UNIT_TESTS)
// Special behaviour for unit tests.
switch(_soUT_override)
{
case _soUT_off: return(false);
case _soUT_soon: return(true);
case _soUT_now: return(false);
}
#endif
const uint_least16_t mm0 = OTV0P2BASE::getMinutesSinceMidnightLT() + PREPREWARM_MINS; // Look forward...
const uint_least16_t mm = (mm0 >= OTV0P2BASE::MINS_PER_DAY) ? (mm0 - OTV0P2BASE::MINS_PER_DAY) : mm0;
for(uint8_t which = 0; which < MAX_SIMPLE_SCHEDULES; ++which)
{
const uint_least16_t s = getSimpleScheduleOn(which);
if(mm < s) { continue; } // Also deals with case where this schedule is not set at all (s == ~0);
uint_least16_t e = getSimpleScheduleOff(which);
if(e < s) { e += OTV0P2BASE::MINS_PER_DAY; } // Cope with schedule wrap around midnight.
if(mm < e) { return(true); }
}
return(false);
}
<commit_msg>Increasing total pre-warm time to 90m for scheduled on.<commit_after>/*
The OpenTRV project licenses this file to you
under the Apache Licence, Version 2.0 (the "Licence");
you may not use this file except in compliance
with the Licence. You may obtain a copy of the Licence at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the Licence is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the Licence for the
specific language governing permissions and limitations
under the Licence.
Author(s) / Copyright (s): Damon Hart-Davis 2013--2016
*/
/*
Schedule support for TRV.
*/
#include <avr/eeprom.h>
#include <util/atomic.h>
#include "Schedule.h"
#include "Control.h"
#if defined(UNIT_TESTS)
// Support for unit tests to force particular apparent schedule state.
// Current override state; 0 (default) means no override.
static _TEST_schedule_override _soUT_override;
// Set the override value (or remove the override).
void _TEST_set_schedule_override(const _TEST_schedule_override override)
{ _soUT_override = override; }
#endif
// All EEPROM activity is made atomic by locking out interrupts where necessary.
// Maximum mins-after-midnight compacted value in one byte.
static const uint8_t MAX_COMPRESSED_MINS_AFTER_MIDNIGHT = ((OTV0P2BASE::MINS_PER_DAY / SIMPLE_SCHEDULE_GRANULARITY_MINS) - 1);
// If LEARN_BUTTON_AVAILABLE then what is the schedule on time?
//#ifdef LEARN_BUTTON_AVAILABLE
// Number of minutes of schedule on time to use.
// Will depend on eco bias.
// TODO: make gradual.
static uint8_t onTime()
{
#if LEARNED_ON_PERIOD_M == LEARNED_ON_PERIOD_COMFORT_M
// Simplify the logic where no variation in on time is required.
return(LEARNED_ON_PERIOD_M);
#else
// Variable 'on' time depending on how 'eco' the settings are.
// // Simple and fast binary choice.
// return(hasEcoBias() ? LEARNED_ON_PERIOD_M : LEARNED_ON_PERIOD_COMFORT_M);
// Three-way split based on current WARM target temperature,
// for a relatively gentle change in behaviour along the valve dial for example.
const uint8_t wt = getWARMTargetC();
if(isEcoTemperature(wt)) { return(LEARNED_ON_PERIOD_M); }
else if(isComfortTemperature(wt)) { return(LEARNED_ON_PERIOD_COMFORT_M); }
else { return((LEARNED_ON_PERIOD_M + LEARNED_ON_PERIOD_COMFORT_M) / 2); }
#endif
}
// #endif // LEARN_BUTTON_AVAILABLE
// Pre-warm time before learned/scheduled WARM period,
// based on basic scheduled on time and allowing for some wobble in the timing resolution.
// DHD20151122: even half an hour may not be enough if very cold and heating system not good.
// DHD20160112: with 60m LEARNED_ON_PERIOD_M this should yield ~36m.
const uint8_t PREWARM_MINS = max(30, (SIMPLE_SCHEDULE_GRANULARITY_MINS + (LEARNED_ON_PERIOD_M/2)));
// Setback period before WARM period to help ensure that the WARM target can be reached on time.
// Important for slow-to-heat rooms that have become very cold.
// Similar to or a little longer than PREWARM_MINS
// so that we can safely use this without causing distress, eg waking people up.
// DHD20160112: with 60m LEARNED_ON_PERIOD_M this should yield ~54m for a total run-up of 90m.
const uint8_t PREPREWARM_MINS = (3*(PREWARM_MINS/2));
// Get the simple/primary schedule on time, as minutes after midnight [0,1439]; invalid (eg ~0) if none set.
// Will usually include a pre-warm time before the actual time set.
// Note that unprogrammed EEPROM value will result in invalid time, ie schedule not set.
// * which schedule number, counting from 0
uint_least16_t getSimpleScheduleOn(const uint8_t which)
{
if(which >= MAX_SIMPLE_SCHEDULES) { return(~0); } // Invalid schedule number.
uint8_t startMM;
ATOMIC_BLOCK (ATOMIC_RESTORESTATE)
{ startMM = eeprom_read_byte((uint8_t*)(V0P2BASE_EE_START_SIMPLE_SCHEDULE0_ON + which)); }
if(startMM > MAX_COMPRESSED_MINS_AFTER_MIDNIGHT) { return(~0); } // No schedule set.
// Compute start time from stored schedule value.
uint_least16_t startTime = SIMPLE_SCHEDULE_GRANULARITY_MINS * startMM;
// If LEARN_BUTTON_AVAILABLE then in the absence of anything better SUPPORT_SINGLETON_SCHEDULE should be supported.
#ifdef LEARN_BUTTON_AVAILABLE
const uint8_t windBackM = PREWARM_MINS; // Wind back start time by about 25% of full interval.
if(windBackM > startTime) { startTime += OTV0P2BASE::MINS_PER_DAY; } // Allow for wrap-around at midnight.
startTime -= windBackM;
#endif
return(startTime);
}
// Get the simple/primary schedule off time, as minutes after midnight [0,1439]; invalid (eg ~0) if none set.
// This is based on specified start time and some element of the current eco/comfort bias.
// * which schedule number, counting from 0
uint_least16_t getSimpleScheduleOff(const uint8_t which)
{
const uint_least16_t startMins = getSimpleScheduleOn(which);
if(startMins == (uint_least16_t)~0) { return(~0); }
// Compute end from start, allowing for wrap-around at midnight.
uint_least16_t endTime = startMins + PREWARM_MINS + onTime();
if(endTime >= OTV0P2BASE::MINS_PER_DAY) { endTime -= OTV0P2BASE::MINS_PER_DAY; } // Allow for wrap-around at midnight.
return(endTime);
}
// Set the simple/primary simple on time.
// * startMinutesSinceMidnightLT is start/on time in minutes after midnight [0,1439]
// * which schedule number, counting from 0
// Invalid parameters will be ignored and false returned,
// else this will return true and isSimpleScheduleSet() will return true after this.
// NOTE: over-use of this routine can prematurely wear out the EEPROM.
bool setSimpleSchedule(const uint_least16_t startMinutesSinceMidnightLT, const uint8_t which)
{
if(which >= MAX_SIMPLE_SCHEDULES) { return(false); } // Invalid schedule number.
if(startMinutesSinceMidnightLT >= OTV0P2BASE::MINS_PER_DAY) { return(false); } // Invalid time.
// Set the schedule, minimising wear.
const uint8_t startMM = startMinutesSinceMidnightLT / SIMPLE_SCHEDULE_GRANULARITY_MINS; // Round down...
ATOMIC_BLOCK (ATOMIC_RESTORESTATE)
{ OTV0P2BASE::eeprom_smart_update_byte((uint8_t*)(V0P2BASE_EE_START_SIMPLE_SCHEDULE0_ON + which), startMM); }
return(true); // Assume EEPROM programmed OK...
}
// Clear a simple schedule.
// There will be neither on nor off events from the selected simple schedule once this is called.
// * which schedule number, counting from 0
void clearSimpleSchedule(const uint8_t which)
{
if(which >= MAX_SIMPLE_SCHEDULES) { return; } // Invalid schedule number.
// Clear the schedule back to 'unprogrammed' values, minimising wear.
ATOMIC_BLOCK (ATOMIC_RESTORESTATE)
{ OTV0P2BASE::eeprom_smart_erase_byte((uint8_t*)(V0P2BASE_EE_START_SIMPLE_SCHEDULE0_ON + which)); }
}
// Returns true if any simple schedule is set, false otherwise.
// This implementation just checks for any valid schedule 'on' time.
// In unit-test override mode is true for soon/now, false for off.
bool isAnySimpleScheduleSet()
{
#if defined(UNIT_TESTS)
// Special behaviour for unit tests.
switch(_soUT_override)
{
case _soUT_off: return(false);
case _soUT_soon: return(true);
case _soUT_now: return(true);
}
#endif
ATOMIC_BLOCK (ATOMIC_RESTORESTATE)
{
for(uint8_t which = 0; which < MAX_SIMPLE_SCHEDULES; ++which)
{
if(eeprom_read_byte((uint8_t*)(V0P2BASE_EE_START_SIMPLE_SCHEDULE0_ON + which)) <= MAX_COMPRESSED_MINS_AFTER_MIDNIGHT)
{ return(true); }
}
}
return(false);
}
// True iff any schedule is currently 'on'/'WARM' even when schedules overlap.
// May be relatively slow/expensive.
// Can be used to suppress all 'off' activity except for the final one.
// Can be used to suppress set-backs during on times.
// In unit-test override mode is true for now, false for soon/off.
bool isAnyScheduleOnWARMNow()
{
#if defined(UNIT_TESTS)
// Special behaviour for unit tests.
switch(_soUT_override)
{
case _soUT_off: return(false);
case _soUT_soon: return(false);
case _soUT_now: return(true);
}
#endif
const uint_least16_t mm = OTV0P2BASE::getMinutesSinceMidnightLT();
for(uint8_t which = 0; which < MAX_SIMPLE_SCHEDULES; ++which)
{
const uint_least16_t s = getSimpleScheduleOn(which);
if(mm < s) { continue; } // Also deals with case where this schedule is not set at all (s == ~0);
uint_least16_t e = getSimpleScheduleOff(which);
if(e < s) { e += OTV0P2BASE::MINS_PER_DAY; } // Cope with schedule wrap around midnight.
if(mm < e) { return(true); }
}
return(false);
}
// True iff any schedule is due 'on'/'WARM' soon even when schedules overlap.
// May be relatively slow/expensive.
// Can be used to allow room to be brought up to at least a set-back temperature
// if very cold when a WARM period is due soon (to help ensure that WARM target is met on time).
// In unit-test override mode is true for soon, false for now/off.
bool isAnyScheduleOnWARMSoon()
{
#if defined(UNIT_TESTS)
// Special behaviour for unit tests.
switch(_soUT_override)
{
case _soUT_off: return(false);
case _soUT_soon: return(true);
case _soUT_now: return(false);
}
#endif
const uint_least16_t mm0 = OTV0P2BASE::getMinutesSinceMidnightLT() + PREPREWARM_MINS; // Look forward...
const uint_least16_t mm = (mm0 >= OTV0P2BASE::MINS_PER_DAY) ? (mm0 - OTV0P2BASE::MINS_PER_DAY) : mm0;
for(uint8_t which = 0; which < MAX_SIMPLE_SCHEDULES; ++which)
{
const uint_least16_t s = getSimpleScheduleOn(which);
if(mm < s) { continue; } // Also deals with case where this schedule is not set at all (s == ~0);
uint_least16_t e = getSimpleScheduleOff(which);
if(e < s) { e += OTV0P2BASE::MINS_PER_DAY; } // Cope with schedule wrap around midnight.
if(mm < e) { return(true); }
}
return(false);
}
<|endoftext|> |
<commit_before>/**
* @file dual_tree_kmeans_rules_impl.hpp
* @author Ryan Curtin
*
* A set of tree traversal rules for dual-tree k-means clustering.
*/
#ifndef __MLPACK_METHODS_KMEANS_DUAL_TREE_KMEANS_RULES_IMPL_HPP
#define __MLPACK_METHODS_KMEANS_DUAL_TREE_KMEANS_RULES_IMPL_HPP
// In case it hasn't been included yet.
#include "dual_tree_kmeans_rules.hpp"
namespace mlpack {
namespace kmeans {
template<typename MetricType, typename TreeType>
DualTreeKMeansRules<MetricType, TreeType>::DualTreeKMeansRules(
const typename TreeType::Mat& dataset,
const arma::mat& centroids,
arma::mat& newCentroids,
arma::Col<size_t>& counts,
const std::vector<size_t>& mappings,
const size_t iteration,
const arma::vec& clusterDistances,
arma::vec& distances,
arma::Col<size_t>& assignments,
arma::Col<size_t>& distanceIteration,
const arma::mat& interclusterDistances,
MetricType& metric) :
dataset(dataset),
centroids(centroids),
newCentroids(newCentroids),
counts(counts),
mappings(mappings),
iteration(iteration),
clusterDistances(clusterDistances),
distances(distances),
assignments(assignments),
distanceIteration(distanceIteration),
interclusterDistances(interclusterDistances),
metric(metric),
distanceCalculations(0)
{
// Nothing has been visited yet.
visited.zeros(dataset.n_cols);
}
template<typename MetricType, typename TreeType>
inline force_inline double DualTreeKMeansRules<MetricType, TreeType>::BaseCase(
const size_t queryIndex,
const size_t referenceIndex)
{
// Collect the number of clusters that have been pruned during the traversal.
// The ternary operator may not be necessary.
const size_t traversalPruned = (traversalInfo.LastReferenceNode() != NULL) ?
traversalInfo.LastReferenceNode()->Stat().ClustersPruned() : 0;
// It's possible that the reference node has been pruned before we got to the
// base case. In that case, don't do the base case, and just return.
if (traversalInfo.LastReferenceNode()->Stat().ClustersPruned() +
visited[referenceIndex] == centroids.n_cols)
return 0.0;
++distanceCalculations;
const double distance = metric.Evaluate(centroids.col(queryIndex),
dataset.col(referenceIndex));
// Iteration change check.
if (distanceIteration[referenceIndex] < iteration)
{
distanceIteration[referenceIndex] = iteration;
distances[referenceIndex] = distance;
assignments[referenceIndex] = mappings[queryIndex];
}
else if (distance < distances[referenceIndex])
{
distances[referenceIndex] = distance;
assignments[referenceIndex] = mappings[queryIndex];
}
++visited[referenceIndex];
if (visited[referenceIndex] + traversalPruned == centroids.n_cols)
{
newCentroids.col(assignments[referenceIndex]) +=
dataset.col(referenceIndex);
++counts(assignments[referenceIndex]);
}
return distance;
}
template<typename MetricType, typename TreeType>
double DualTreeKMeansRules<MetricType, TreeType>::Score(
const size_t queryIndex,
TreeType& referenceNode)
{
// No pruning here, for now.
return 0.0;
}
template<typename MetricType, typename TreeType>
double DualTreeKMeansRules<MetricType, TreeType>::Score(
TreeType& queryNode,
TreeType& referenceNode)
{
// This won't happen with the root since it is explicitly set to 0.
if (referenceNode.Stat().ClustersPruned() == size_t(-1))
referenceNode.Stat().ClustersPruned() =
referenceNode.Parent()->Stat().ClustersPruned();
traversalInfo.LastReferenceNode() = &referenceNode;
double score = ElkanTypeScore(queryNode, referenceNode);
// If there's no closest query node assigned, but the parent has one, take
// that one.
if (referenceNode.Stat().ClosestQueryNode() == NULL &&
referenceNode.Parent() != NULL &&
referenceNode.Parent()->Stat().ClosestQueryNode() != NULL)
{
referenceNode.Stat().ClosestQueryNode() =
referenceNode.Parent()->Stat().ClosestQueryNode();
referenceNode.Stat().MaxQueryNodeDistance() = std::min(
referenceNode.Parent()->Stat().MaxQueryNodeDistance(),
referenceNode.Stat().MaxQueryNodeDistance());
}
if (score != DBL_MAX)
{
// We also have to update things if the closest query node is null. This
// can probably be improved.
const double minDistance = referenceNode.MinDistance(&queryNode);
const double maxDistance = referenceNode.MaxDistance(&queryNode);
distanceCalculations += 2;
score = PellegMooreScore(queryNode, referenceNode, minDistance);
if (maxDistance < referenceNode.Stat().MaxQueryNodeDistance() ||
referenceNode.Stat().ClosestQueryNode() == NULL)
{
referenceNode.Stat().ClosestQueryNode() = (void*) &queryNode;
referenceNode.Stat().MinQueryNodeDistance() = minDistance;
referenceNode.Stat().MaxQueryNodeDistance() = maxDistance;
}
else if (IsDescendantOf(*((TreeType*)
referenceNode.Stat().ClosestQueryNode()), queryNode))
{
referenceNode.Stat().ClosestQueryNode() == (void*) &queryNode;
referenceNode.Stat().MinQueryNodeDistance() = minDistance;
referenceNode.Stat().MaxQueryNodeDistance() = maxDistance;
}
}
if (score == DBL_MAX)
{
referenceNode.Stat().ClustersPruned() += queryNode.NumDescendants();
// Have we pruned everything?
if (referenceNode.Stat().ClustersPruned() +
visited[referenceNode.Descendant(0)] == centroids.n_cols)
{
for (size_t i = 0; i < referenceNode.NumDescendants(); ++i)
{
const size_t cluster = assignments[referenceNode.Descendant(i)];
newCentroids.col(cluster) += dataset.col(referenceNode.Descendant(i));
counts(cluster)++;
}
}
}
return score;
}
template<typename MetricType, typename TreeType>
double DualTreeKMeansRules<MetricType, TreeType>::Rescore(
const size_t /* queryIndex */,
TreeType& /* referenceNode */,
const double oldScore) const
{
return oldScore;
}
template<typename MetricType, typename TreeType>
double DualTreeKMeansRules<MetricType, TreeType>::Rescore(
TreeType& /* queryNode */,
TreeType& /* referenceNode */,
const double oldScore) const
{
return oldScore;
}
template<typename MetricType, typename TreeType>
bool DualTreeKMeansRules<MetricType, TreeType>::IsDescendantOf(
const TreeType& potentialParent,
const TreeType& potentialChild) const
{
if (potentialChild.Parent() == &potentialParent)
return true;
else if (potentialChild.Parent() == NULL)
return false;
else
return IsDescendantOf(potentialParent, *potentialChild.Parent());
}
template<typename MetricType, typename TreeType>
double DualTreeKMeansRules<MetricType, TreeType>::ElkanTypeScore(
TreeType& queryNode,
TreeType& referenceNode)
{
// We have to calculate the minimum distance between the query node and the
// reference node's best query node. First, try to use the cached distance.
// const double minQueryDistance = queryNode.Stat().FirstBound();
if (queryNode.NumDescendants() == 1)
{
const double score = ElkanTypeScore(queryNode, referenceNode,
interclusterDistances[queryNode.Descendant(0)]);
return score;
}
else
return 0.0;
}
template<typename MetricType, typename TreeType>
double DualTreeKMeansRules<MetricType, TreeType>::ElkanTypeScore(
TreeType& /* queryNode */,
TreeType& referenceNode,
const double minQueryDistance) const
{
// See if we can do an Elkan-type prune on between-centroid distances.
const double maxDistance = referenceNode.Stat().MaxQueryNodeDistance();
if (maxDistance == DBL_MAX)
return minQueryDistance;
if (minQueryDistance > 2.0 * maxDistance)
{
// Then we can conclude d_max(best(N_r), N_r) <= d_min(N_q, N_r) which
// means that N_q cannot possibly hold any clusters that own any points in
// N_r.
return DBL_MAX;
}
return minQueryDistance;
}
template<typename MetricType, typename TreeType>
double DualTreeKMeansRules<MetricType, TreeType>::PellegMooreScore(
TreeType& queryNode,
TreeType& referenceNode,
const double minDistance) const
{
// If the minimum distance to the node is greater than the bound, then every
// cluster in the query node cannot possibly be the nearest neighbor of any of
// the points in the reference node.
if (minDistance > referenceNode.Stat().MaxQueryNodeDistance())
return DBL_MAX;
return minDistance;
}
} // namespace kmeans
} // namespace mlpack
#endif
<commit_msg>Don't calculate MaxDistance() unless we have to. Fairly significant time savings on this one.<commit_after>/**
* @file dual_tree_kmeans_rules_impl.hpp
* @author Ryan Curtin
*
* A set of tree traversal rules for dual-tree k-means clustering.
*/
#ifndef __MLPACK_METHODS_KMEANS_DUAL_TREE_KMEANS_RULES_IMPL_HPP
#define __MLPACK_METHODS_KMEANS_DUAL_TREE_KMEANS_RULES_IMPL_HPP
// In case it hasn't been included yet.
#include "dual_tree_kmeans_rules.hpp"
namespace mlpack {
namespace kmeans {
template<typename MetricType, typename TreeType>
DualTreeKMeansRules<MetricType, TreeType>::DualTreeKMeansRules(
const typename TreeType::Mat& dataset,
const arma::mat& centroids,
arma::mat& newCentroids,
arma::Col<size_t>& counts,
const std::vector<size_t>& mappings,
const size_t iteration,
const arma::vec& clusterDistances,
arma::vec& distances,
arma::Col<size_t>& assignments,
arma::Col<size_t>& distanceIteration,
const arma::mat& interclusterDistances,
MetricType& metric) :
dataset(dataset),
centroids(centroids),
newCentroids(newCentroids),
counts(counts),
mappings(mappings),
iteration(iteration),
clusterDistances(clusterDistances),
distances(distances),
assignments(assignments),
distanceIteration(distanceIteration),
interclusterDistances(interclusterDistances),
metric(metric),
distanceCalculations(0)
{
// Nothing has been visited yet.
visited.zeros(dataset.n_cols);
}
template<typename MetricType, typename TreeType>
inline force_inline double DualTreeKMeansRules<MetricType, TreeType>::BaseCase(
const size_t queryIndex,
const size_t referenceIndex)
{
// Collect the number of clusters that have been pruned during the traversal.
// The ternary operator may not be necessary.
const size_t traversalPruned = (traversalInfo.LastReferenceNode() != NULL) ?
traversalInfo.LastReferenceNode()->Stat().ClustersPruned() : 0;
// It's possible that the reference node has been pruned before we got to the
// base case. In that case, don't do the base case, and just return.
if (traversalInfo.LastReferenceNode()->Stat().ClustersPruned() +
visited[referenceIndex] == centroids.n_cols)
return 0.0;
++distanceCalculations;
const double distance = metric.Evaluate(centroids.col(queryIndex),
dataset.col(referenceIndex));
// Iteration change check.
if (distanceIteration[referenceIndex] < iteration)
{
distanceIteration[referenceIndex] = iteration;
distances[referenceIndex] = distance;
assignments[referenceIndex] = mappings[queryIndex];
}
else if (distance < distances[referenceIndex])
{
distances[referenceIndex] = distance;
assignments[referenceIndex] = mappings[queryIndex];
}
++visited[referenceIndex];
if (visited[referenceIndex] + traversalPruned == centroids.n_cols)
{
newCentroids.col(assignments[referenceIndex]) +=
dataset.col(referenceIndex);
++counts(assignments[referenceIndex]);
}
return distance;
}
template<typename MetricType, typename TreeType>
double DualTreeKMeansRules<MetricType, TreeType>::Score(
const size_t queryIndex,
TreeType& referenceNode)
{
// No pruning here, for now.
return 0.0;
}
template<typename MetricType, typename TreeType>
double DualTreeKMeansRules<MetricType, TreeType>::Score(
TreeType& queryNode,
TreeType& referenceNode)
{
// This won't happen with the root since it is explicitly set to 0.
if (referenceNode.Stat().ClustersPruned() == size_t(-1))
referenceNode.Stat().ClustersPruned() =
referenceNode.Parent()->Stat().ClustersPruned();
traversalInfo.LastReferenceNode() = &referenceNode;
double score = ElkanTypeScore(queryNode, referenceNode);
// If there's no closest query node assigned, but the parent has one, take
// that one.
if (referenceNode.Stat().ClosestQueryNode() == NULL &&
referenceNode.Parent() != NULL &&
referenceNode.Parent()->Stat().ClosestQueryNode() != NULL)
{
referenceNode.Stat().ClosestQueryNode() =
referenceNode.Parent()->Stat().ClosestQueryNode();
referenceNode.Stat().MaxQueryNodeDistance() = std::min(
referenceNode.Parent()->Stat().MaxQueryNodeDistance(),
referenceNode.Stat().MaxQueryNodeDistance());
}
if (score != DBL_MAX)
{
// We also have to update things if the closest query node is null. This
// can probably be improved.
const double minDistance = referenceNode.MinDistance(&queryNode);
++distanceCalculations;
score = PellegMooreScore(queryNode, referenceNode, minDistance);
if (minDistance < referenceNode.Stat().MinQueryNodeDistance() ||
referenceNode.Stat().ClosestQueryNode() == NULL)
{
const double maxDistance = referenceNode.MaxDistance(&queryNode);
++distanceCalculations;
referenceNode.Stat().ClosestQueryNode() = (void*) &queryNode;
referenceNode.Stat().MinQueryNodeDistance() = minDistance;
referenceNode.Stat().MaxQueryNodeDistance() = maxDistance;
}
else if (IsDescendantOf(*((TreeType*)
referenceNode.Stat().ClosestQueryNode()), queryNode))
{
const double maxDistance = referenceNode.MaxDistance(&queryNode);
++distanceCalculations;
referenceNode.Stat().ClosestQueryNode() == (void*) &queryNode;
referenceNode.Stat().MinQueryNodeDistance() = minDistance;
referenceNode.Stat().MaxQueryNodeDistance() = maxDistance;
}
}
if (score == DBL_MAX)
{
referenceNode.Stat().ClustersPruned() += queryNode.NumDescendants();
// Have we pruned everything?
if (referenceNode.Stat().ClustersPruned() +
visited[referenceNode.Descendant(0)] == centroids.n_cols)
{
for (size_t i = 0; i < referenceNode.NumDescendants(); ++i)
{
const size_t cluster = assignments[referenceNode.Descendant(i)];
newCentroids.col(cluster) += dataset.col(referenceNode.Descendant(i));
counts(cluster)++;
}
}
}
return score;
}
template<typename MetricType, typename TreeType>
double DualTreeKMeansRules<MetricType, TreeType>::Rescore(
const size_t /* queryIndex */,
TreeType& /* referenceNode */,
const double oldScore) const
{
return oldScore;
}
template<typename MetricType, typename TreeType>
double DualTreeKMeansRules<MetricType, TreeType>::Rescore(
TreeType& /* queryNode */,
TreeType& /* referenceNode */,
const double oldScore) const
{
return oldScore;
}
template<typename MetricType, typename TreeType>
bool DualTreeKMeansRules<MetricType, TreeType>::IsDescendantOf(
const TreeType& potentialParent,
const TreeType& potentialChild) const
{
if (potentialChild.Parent() == &potentialParent)
return true;
else if (potentialChild.Parent() == NULL)
return false;
else
return IsDescendantOf(potentialParent, *potentialChild.Parent());
}
template<typename MetricType, typename TreeType>
double DualTreeKMeansRules<MetricType, TreeType>::ElkanTypeScore(
TreeType& queryNode,
TreeType& referenceNode)
{
// We have to calculate the minimum distance between the query node and the
// reference node's best query node. First, try to use the cached distance.
// const double minQueryDistance = queryNode.Stat().FirstBound();
if (queryNode.NumDescendants() == 1)
{
const double score = ElkanTypeScore(queryNode, referenceNode,
interclusterDistances[queryNode.Descendant(0)]);
return score;
}
else
return 0.0;
}
template<typename MetricType, typename TreeType>
double DualTreeKMeansRules<MetricType, TreeType>::ElkanTypeScore(
TreeType& /* queryNode */,
TreeType& referenceNode,
const double minQueryDistance) const
{
// See if we can do an Elkan-type prune on between-centroid distances.
const double maxDistance = referenceNode.Stat().MaxQueryNodeDistance();
if (maxDistance == DBL_MAX)
return minQueryDistance;
if (minQueryDistance > 2.0 * maxDistance)
{
// Then we can conclude d_max(best(N_r), N_r) <= d_min(N_q, N_r) which
// means that N_q cannot possibly hold any clusters that own any points in
// N_r.
return DBL_MAX;
}
return minQueryDistance;
}
template<typename MetricType, typename TreeType>
double DualTreeKMeansRules<MetricType, TreeType>::PellegMooreScore(
TreeType& queryNode,
TreeType& referenceNode,
const double minDistance) const
{
// If the minimum distance to the node is greater than the bound, then every
// cluster in the query node cannot possibly be the nearest neighbor of any of
// the points in the reference node.
if (minDistance > referenceNode.Stat().MaxQueryNodeDistance())
return DBL_MAX;
return minDistance;
}
} // namespace kmeans
} // namespace mlpack
#endif
<|endoftext|> |
<commit_before>/****************************************************************************
**
** QtMEL is a Qt Media Encoding Library that allows to encode video and audio streams
** Copyright (C) 2013 Kirill Bukaev(aka KIBSOFT).
** Contact: Kirill Bukaev ([email protected])
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License as published by the Free Software Foundation; either
** version 2.1 of the License, or (at your option) any later version.
**
** This library is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
** Lesser General Public License for more details.
**
** You should have received a copy of the GNU Lesser General Public
** License along with this library; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
**
****************************************************************************/
#include "cameragrabber.h"
#include <QEventLoop>
#include <QTimer>
#include <QElapsedTimer>
#include <QDateTime>
#include <QPainter>
#include <QCamera>
#include <opencv/cv.h>
#include <opencv/highgui.h>
CameraGrabber::CameraGrabber(QObject *parent)
: AbstractImageGrabber(parent)
, m_deviceIndex(-1)
{
setInitializationTime(1000);
connect(this, SIGNAL(stateChanged(AbstractGrabber::State)), this, SLOT(onStateChanged(AbstractGrabber::State)));
}
CameraGrabber::~CameraGrabber()
{
}
void CameraGrabber::setDeviceIndex(int index)
{
if (m_deviceIndex != index) {
m_deviceIndex = index;
}
}
int CameraGrabber::deviceIndex() const
{
return m_deviceIndex;
}
void CameraGrabber::setSize(const QSize &size)
{
if (m_size != size) {
m_size = size;
}
}
QSize CameraGrabber::size() const
{
return m_size;
}
QStringList CameraGrabber::availableDeviceNames()
{
QByteArray device;
QList<QByteArray> devices = QCamera::availableDevices();
QStringList names;
Q_FOREACH (device, devices) {
names.append(QCamera::deviceDescription(device));
}
return names;
}
QSize CameraGrabber::maximumFrameSize(int deviceIndex)
{
if (deviceIndex < 0 || deviceIndex > CameraGrabber::availableDeviceNames().count())
return QSize();
CvCapture *capture = cvCreateCameraCapture(deviceIndex);
QSize size;
size.setWidth(cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH));
size.setHeight(cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT));
cvReleaseCapture(&capture);
return size;
}
bool CameraGrabber::start()
{
if (!createCamera())
return false;
return AbstractImageGrabber::start();
}
void CameraGrabber::onStateChanged(AbstractGrabber::State state)
{
if (state == AbstractGrabber::StoppedState) {
releaseCamera();
}
}
bool CameraGrabber::createCamera()
{
if (m_deviceIndex < 0 || m_deviceIndex > CameraGrabber::availableDeviceNames().count()) {
setError(AbstractGrabber::DeviceNotFoundError, tr("Device to be grabbed was not found."));
return false;
}
m_camera = cvCreateCameraCapture(m_deviceIndex);
//init size
if (!size().isValid()) {
QSize size;
size.setWidth(cvGetCaptureProperty(m_camera, CV_CAP_PROP_FRAME_WIDTH));
size.setHeight(cvGetCaptureProperty(m_camera, CV_CAP_PROP_FRAME_HEIGHT));
setSize(size);
}
return true;
}
void CameraGrabber::releaseCamera()
{
cvReleaseCapture(&m_camera);
m_camera = 0;
}
QImage CameraGrabber::captureFrame()
{
IplImage *iplImage = cvQueryFrame(m_camera);
int height = iplImage->height;
int width = iplImage->width;
QImage frame;
if (iplImage->depth == IPL_DEPTH_8U && iplImage->nChannels == 3) {
uchar *data = (uchar*)iplImage->imageData;
frame = QImage(data, width, height, QImage::Format_RGB888).rgbSwapped();
//resize the frame to a given size
if (frame.size() != size()) {
QImage scaledFrame = frame.scaled(size(), Qt::KeepAspectRatio);
if (scaledFrame.size() != size()) {
QImage newFrame(size(), QImage::Format_RGB888);
newFrame.fill(Qt::black);
QPainter painter(&newFrame);
painter.drawImage(scaledFrame.width() < size().width() ? (newFrame.width() - scaledFrame.width()) / 2 : 0,
scaledFrame.height() < size().height() ? (newFrame.height() - scaledFrame.height()) / 2 : 0, scaledFrame);
scaledFrame = newFrame;
}
frame = scaledFrame;
}
}
return frame;
}
<commit_msg>Set correct size in OpenCV when changing grabber resolution<commit_after>/****************************************************************************
**
** QtMEL is a Qt Media Encoding Library that allows to encode video and audio streams
** Copyright (C) 2013 Kirill Bukaev(aka KIBSOFT).
** Contact: Kirill Bukaev ([email protected])
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License as published by the Free Software Foundation; either
** version 2.1 of the License, or (at your option) any later version.
**
** This library is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
** Lesser General Public License for more details.
**
** You should have received a copy of the GNU Lesser General Public
** License along with this library; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
**
****************************************************************************/
#include "cameragrabber.h"
#include <QEventLoop>
#include <QTimer>
#include <QElapsedTimer>
#include <QDateTime>
#include <QPainter>
#include <QCamera>
#include <opencv/cv.h>
#include <opencv/highgui.h>
CameraGrabber::CameraGrabber(QObject *parent)
: AbstractImageGrabber(parent)
, m_deviceIndex(-1)
{
setInitializationTime(1000);
connect(this, SIGNAL(stateChanged(AbstractGrabber::State)), this, SLOT(onStateChanged(AbstractGrabber::State)));
}
CameraGrabber::~CameraGrabber()
{
}
void CameraGrabber::setDeviceIndex(int index)
{
if (m_deviceIndex != index) {
m_deviceIndex = index;
}
}
int CameraGrabber::deviceIndex() const
{
return m_deviceIndex;
}
void CameraGrabber::setSize(const QSize &size)
{
if (m_size != size) {
m_size = size;
}
}
QSize CameraGrabber::size() const
{
return m_size;
}
QStringList CameraGrabber::availableDeviceNames()
{
QByteArray device;
QList<QByteArray> devices = QCamera::availableDevices();
QStringList names;
Q_FOREACH (device, devices) {
names.append(QCamera::deviceDescription(device));
}
return names;
}
QSize CameraGrabber::maximumFrameSize(int deviceIndex)
{
if (deviceIndex < 0 || deviceIndex > CameraGrabber::availableDeviceNames().count())
return QSize();
CvCapture *capture = cvCreateCameraCapture(deviceIndex);
QSize size;
size.setWidth(cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH));
size.setHeight(cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT));
cvReleaseCapture(&capture);
return size;
}
bool CameraGrabber::start()
{
if (!createCamera())
return false;
return AbstractImageGrabber::start();
}
void CameraGrabber::onStateChanged(AbstractGrabber::State state)
{
if (state == AbstractGrabber::StoppedState) {
releaseCamera();
}
}
bool CameraGrabber::createCamera()
{
if (m_deviceIndex < 0 || m_deviceIndex > CameraGrabber::availableDeviceNames().count()) {
setError(AbstractGrabber::DeviceNotFoundError, tr("Device to be grabbed was not found."));
return false;
}
m_camera = cvCreateCameraCapture(m_deviceIndex);
//init size
if (!size().isValid()) {
QSize size;
size.setWidth(cvGetCaptureProperty(m_camera, CV_CAP_PROP_FRAME_WIDTH));
size.setHeight(cvGetCaptureProperty(m_camera, CV_CAP_PROP_FRAME_HEIGHT));
setSize(size);
}
cvSetCaptureProperty( m_camera, CV_CAP_PROP_FRAME_WIDTH, m_size.width());
cvSetCaptureProperty( m_camera, CV_CAP_PROP_FRAME_HEIGHT, m_size.height());
return true;
}
void CameraGrabber::releaseCamera()
{
cvReleaseCapture(&m_camera);
m_camera = 0;
}
QImage CameraGrabber::captureFrame()
{
IplImage *iplImage = cvQueryFrame(m_camera);
int height = iplImage->height;
int width = iplImage->width;
QImage frame;
if (iplImage->depth == IPL_DEPTH_8U && iplImage->nChannels == 3) {
uchar *data = (uchar*)iplImage->imageData;
frame = QImage(data, width, height, QImage::Format_RGB888).rgbSwapped();
//resize the frame to a given size
if (frame.size() != size()) {
QImage scaledFrame = frame.scaled(size(), Qt::KeepAspectRatio);
if (scaledFrame.size() != size()) {
QImage newFrame(size(), QImage::Format_RGB888);
newFrame.fill(Qt::black);
QPainter painter(&newFrame);
painter.drawImage(scaledFrame.width() < size().width() ? (newFrame.width() - scaledFrame.width()) / 2 : 0,
scaledFrame.height() < size().height() ? (newFrame.height() - scaledFrame.height()) / 2 : 0, scaledFrame);
scaledFrame = newFrame;
}
frame = scaledFrame;
}
}
return frame;
}
<|endoftext|> |
<commit_before>/*=========================================================================
*
* Copyright UMC Utrecht and contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#ifndef elxParameterObject_cxx
#define elxParameterObject_cxx
#include "itkFileTools.h"
#include "elxParameterObject.h"
namespace elastix {
void
ParameterObject
::SetParameterMap( const ParameterMapType parameterMap )
{
ParameterMapVectorType parameterMapVector;
parameterMapVector.push_back( parameterMap );
this->SetParameterMap( parameterMapVector );
}
void
ParameterObject
::SetParameterMap( const ParameterMapVectorType parameterMapVector )
{
this->Modified();
this->m_ParameterMapVector = parameterMapVector;
}
void
ParameterObject
::AddParameterMap( const ParameterMapType parameterMap )
{
this->Modified();
this->m_ParameterMapVector.push_back( parameterMap );
}
ParameterObject::ParameterMapType&
ParameterObject
::GetParameterMap( unsigned int index )
{
this->Modified();
return this->m_ParameterMapVector[ index ];
}
ParameterObject::ParameterMapVectorType&
ParameterObject
::GetParameterMap( void )
{
this->Modified();
return this->m_ParameterMapVector;
}
const ParameterObject::ParameterMapVectorType&
ParameterObject
::GetParameterMap( void ) const
{
return this->m_ParameterMapVector;
}
void
ParameterObject
::ReadParameterFile( const ParameterFileNameType parameterFileName )
{
ParameterFileParserPointer parameterFileParser = ParameterFileParserType::New();
parameterFileParser->SetParameterFileName( parameterFileName );
parameterFileParser->ReadParameterFile();
this->SetParameterMap( ParameterMapVectorType( 1, parameterFileParser->GetParameterMap() ) );
}
void
ParameterObject
::ReadParameterFile( const ParameterFileNameVectorType parameterFileNameVector )
{
if( parameterFileNameVector.size() == 0 )
{
itkExceptionMacro( "Parameter filename container is empty." );
}
this->m_ParameterMapVector.clear();
for( unsigned int i = 0; i < parameterFileNameVector.size(); ++i )
{
if( !itksys::SystemTools::FileExists( parameterFileNameVector[ i ] ) )
{
itkExceptionMacro( "Parameter file \"" << parameterFileNameVector[ i ] << "\" does not exist." )
}
this->AddParameterFile( parameterFileNameVector[ i ] );
}
}
void
ParameterObject
::WriteParameterFile( const ParameterMapType parameterMap, const ParameterFileNameType parameterFileName )
{
std::ofstream parameterFile;
parameterFile << std::fixed;
parameterFile.open( parameterFileName.c_str(), std::ofstream::out );
ParameterMapConstIterator parameterMapIterator = parameterMap.begin();
ParameterMapConstIterator parameterMapIteratorEnd = parameterMap.end();
while( parameterMapIterator != parameterMapIteratorEnd )
{
parameterFile << "(" << parameterMapIterator->first;
ParameterValueVectorType parameterMapValueVector = parameterMapIterator->second;
for( unsigned int i = 0; i < parameterMapValueVector.size(); ++i )
{
std::stringstream stream( parameterMapValueVector[ i ] );
float number;
stream >> number;
if( stream.fail() || stream.bad() ) {
parameterFile << " \"" << parameterMapValueVector[ i ] << "\"";
}
else
{
parameterFile << " " << number;
}
}
parameterFile << ")" << std::endl;
parameterMapIterator++;
}
parameterFile.close();
}
void
ParameterObject
::WriteParameterFile( const ParameterFileNameType parameterFileName )
{
if( this->m_ParameterMapVector.size() == 0 )
{
itkExceptionMacro( "Error writing parameter map to disk: The parameter object is empty." );
}
if( this->m_ParameterMapVector.size() > 1 )
{
itkExceptionMacro( "Error writing to disk: The number of parameter maps (" << this->m_ParameterMapVector.size() << ")"
<< " does not match the number of provided filenames (1). Please provide a vector of filenames." );
}
this->WriteParameterFile( this->m_ParameterMapVector[ 0 ], parameterFileName );
}
void
ParameterObject
::WriteParameterFile( const ParameterFileNameVectorType parameterFileNameVector )
{
if( this->m_ParameterMapVector.size() != parameterFileNameVector.size() )
{
itkExceptionMacro( "Error writing to disk: The number of parameter maps (" << this->m_ParameterMapVector.size() << ")"
<< " does not match the number of provided filenames (" << parameterFileNameVector.size() << ")." );
}
for( unsigned int i = 0; i < this->m_ParameterMapVector.size(); ++i )
{
this->WriteParameterFile( this->m_ParameterMapVector[ i ], parameterFileNameVector[ i ] );
}
}
void
ParameterObject
::SetParameterMap( const std::string transformName, const unsigned int numberOfResolutions, const double finalGridSpacingInPhysicalUnits )
{
this->m_ParameterMapVector = ParameterMapVectorType( 1, this->GetParameterMap( transformName, numberOfResolutions, finalGridSpacingInPhysicalUnits ) );
}
void
ParameterObject
::AddParameterMap( const std::string transformName, const unsigned int numberOfResolutions, const double finalGridSpacingInPhysicalUnits )
{
this->m_ParameterMapVector.push_back( this->GetParameterMap( transformName, numberOfResolutions, finalGridSpacingInPhysicalUnits ) );
}
ParameterObject::ParameterMapType
ParameterObject
::GetParameterMap( const std::string transformName, const unsigned int numberOfResolutions, const double finalGridSpacingInPhysicalUnits )
{
// Parameters that depend on size and number of resolutions
ParameterMapType parameterMap = ParameterMapType();
// Common Components
parameterMap[ "FixedImagePyramid" ] = ParameterValueVectorType( 1, "FixedSmoothingImagePyramid" );
parameterMap[ "MovingImagePyramid" ] = ParameterValueVectorType( 1, "MovingSmoothingImagePyramid" );
parameterMap[ "Interpolator"] = ParameterValueVectorType( 1, "LinearInterpolator");
parameterMap[ "Optimizer" ] = ParameterValueVectorType( 1, "AdaptiveStochasticGradientDescent" );
parameterMap[ "Resampler"] = ParameterValueVectorType( 1, "DefaultResampler" );
parameterMap[ "ResampleInterpolator"] = ParameterValueVectorType( 1, "FinalBSplineInterpolator" );
parameterMap[ "FinalBSplineInterpolationOrder" ] = ParameterValueVectorType( 1, "3" );
parameterMap[ "NumberOfResolutions" ] = ParameterValueVectorType( 1, ToString( numberOfResolutions ) );
// Image Sampler
parameterMap[ "ImageSampler" ] = ParameterValueVectorType( 1, "RandomCoordinate" );
parameterMap[ "NumberOfSpatialSamples"] = ParameterValueVectorType( 1, "2048" );
parameterMap[ "CheckNumberOfSamples" ] = ParameterValueVectorType( 1, "true" );
parameterMap[ "MaximumNumberOfSamplingAttempts" ] = ParameterValueVectorType( 1, "8" );
parameterMap[ "NewSamplesEveryIteration" ] = ParameterValueVectorType( 1, "true");
// Optimizer
parameterMap[ "NumberOfSamplesForExactGradient" ] = ParameterValueVectorType( 1, "4096" );
parameterMap[ "DefaultPixelValue" ] = ParameterValueVectorType( 1, "0.0" );
parameterMap[ "AutomaticParameterEstimation" ] = ParameterValueVectorType( 1, "true" );
// Output
parameterMap[ "WriteResultImage" ] = ParameterValueVectorType( 1, "true" );
parameterMap[ "ResultImageFormat" ] = ParameterValueVectorType( 1, "nii" );
// transformNames
if( transformName == "translation" )
{
parameterMap[ "Registration" ] = ParameterValueVectorType( 1, "MultiResolutionRegistration" );
parameterMap[ "Transform" ] = ParameterValueVectorType( 1, "TranslationTransform" );
parameterMap[ "Metric" ] = ParameterValueVectorType( 1, "AdvancedMattesMutualInformation" );
parameterMap[ "MaximumNumberOfIterations" ] = ParameterValueVectorType( 1, "256" );
parameterMap[ "AutomaticTransformInitialization" ] = ParameterValueVectorType( 1, "true" );
parameterMap[ "AutomaticTransformInitializationMethod" ] = ParameterValueVectorType( 1, "CenterOfGravity" );
}
else if( transformName == "rigid" )
{
parameterMap[ "Registration" ] = ParameterValueVectorType( 1, "MultiResolutionRegistration" );
parameterMap[ "Transform" ] = ParameterValueVectorType( 1, "EulerTransform" );
parameterMap[ "Metric" ] = ParameterValueVectorType( 1, "AdvancedMattesMutualInformation" );
parameterMap[ "MaximumNumberOfIterations" ] = ParameterValueVectorType( 1, "256" );
}
else if( transformName == "affine" )
{
parameterMap[ "Registration" ] = ParameterValueVectorType( 1, "MultiResolutionRegistration" );
parameterMap[ "Transform" ] = ParameterValueVectorType( 1, "AffineTransform" );
parameterMap[ "Metric" ] = ParameterValueVectorType( 1, "AdvancedMattesMutualInformation" );
parameterMap[ "MaximumNumberOfIterations" ] = ParameterValueVectorType( 1, "512" );
}
else if( transformName == "nonrigid" )
{
parameterMap[ "Registration" ] = ParameterValueVectorType( 1, "MultiMetricMultiResolutionRegistration" );
parameterMap[ "Transform" ] = ParameterValueVectorType( 1, "BSplineTransform" );
parameterMap[ "Metric" ] = ParameterValueVectorType( 1, "AdvancedMattesMutualInformation" );
parameterMap[ "Metric" ].push_back( "TransformBendingEnergyPenalty" );
parameterMap[ "Metric0Weight" ] = ParameterValueVectorType( 1, "0.0001" );
parameterMap[ "Metric1Weight" ] = ParameterValueVectorType( 1, "0.9999" );
parameterMap[ "MaximumNumberOfIterations" ] = ParameterValueVectorType( 1, "512" );
}
else if( transformName == "groupwise" )
{
parameterMap[ "Registration" ] = ParameterValueVectorType( 1, "MultiResolutionRegistration" );
parameterMap[ "Transform" ] = ParameterValueVectorType( 1, "BSplineStackTransform" );
parameterMap[ "Metric" ] = ParameterValueVectorType( 1, "VarianceOverLastDimensionMetric" );
parameterMap[ "MaximumNumberOfIterations" ] = ParameterValueVectorType( 1, "512" );
parameterMap[ "Interpolator"] = ParameterValueVectorType( 1, "ReducedDimensionBSplineInterpolator" );
parameterMap[ "ResampleInterpolator" ] = ParameterValueVectorType( 1, "FinalReducedDimensionBSplineInterpolator" );
}
else
{
itkExceptionMacro( "No default parameter map \"" << transformName << "\"." );
}
// B-spline transform settings
if( transformName == "nonrigid" || transformName == "groupwise" )
{
ParameterValueVectorType gridSpacingSchedule = ParameterValueVectorType();
for( unsigned int resolution = 0; resolution < numberOfResolutions; ++resolution )
{
gridSpacingSchedule.insert( gridSpacingSchedule.begin(), ToString( pow( 2, resolution ) ) );
}
parameterMap[ "GridSpacingSchedule" ] = gridSpacingSchedule;
parameterMap[ "FinalGridSpacingInPhysicalUnits" ] = ParameterValueVectorType( 1, ToString( finalGridSpacingInPhysicalUnits ) );
}
return parameterMap;
}
} // namespace elastix
#endif // elxParameterObject_cxx
// http://stackoverflow.com/questions/9670396/exception-handling-and-opening-a-file
// TODO: Implement exception handling for parameter file reader/writer, rethrow itk exception
// int main () {
// ifstream file;
// file.exceptions ( ifstream::failbit | ifstream::badbit );
// try {
// file.open ("test.txt");
// while (!file.eof()) file.get();
// }
// catch ( ifstream::failure e ) {
// cout << "Exception opening/reading file";
// }
// file.close();
// return 0;
// }
// int main () {
// ofstream file;
// file.exceptions ( ofstream::failbit | ofstream::badbit | ofstream::failure );
// try {
// file.open ("test.txt");
// while (!file.eof()) file.get();
// }
// catch (ifstream::failure e) {
// cout << "Exception opening/reading file";
// }
// file.close();
// return 0;
// }
<commit_msg>BUG: Add missing function AddParameterFile<commit_after>/*=========================================================================
*
* Copyright UMC Utrecht and contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#ifndef elxParameterObject_cxx
#define elxParameterObject_cxx
#include "itkFileTools.h"
#include "elxParameterObject.h"
namespace elastix {
void
ParameterObject
::SetParameterMap( const ParameterMapType parameterMap )
{
ParameterMapVectorType parameterMapVector;
parameterMapVector.push_back( parameterMap );
this->SetParameterMap( parameterMapVector );
}
void
ParameterObject
::SetParameterMap( const ParameterMapVectorType parameterMapVector )
{
this->Modified();
this->m_ParameterMapVector = parameterMapVector;
}
void
ParameterObject
::AddParameterMap( const ParameterMapType parameterMap )
{
this->Modified();
this->m_ParameterMapVector.push_back( parameterMap );
}
ParameterObject::ParameterMapType&
ParameterObject
::GetParameterMap( unsigned int index )
{
this->Modified();
return this->m_ParameterMapVector[ index ];
}
ParameterObject::ParameterMapVectorType&
ParameterObject
::GetParameterMap( void )
{
this->Modified();
return this->m_ParameterMapVector;
}
const ParameterObject::ParameterMapVectorType&
ParameterObject
::GetParameterMap( void ) const
{
return this->m_ParameterMapVector;
}
void
ParameterObject
::ReadParameterFile( const ParameterFileNameType parameterFileName )
{
ParameterFileParserPointer parameterFileParser = ParameterFileParserType::New();
parameterFileParser->SetParameterFileName( parameterFileName );
parameterFileParser->ReadParameterFile();
this->SetParameterMap( ParameterMapVectorType( 1, parameterFileParser->GetParameterMap() ) );
}
void
ParameterObject
::ReadParameterFile( const ParameterFileNameVectorType parameterFileNameVector )
{
if( parameterFileNameVector.size() == 0 )
{
itkExceptionMacro( "Parameter filename container is empty." );
}
this->m_ParameterMapVector.clear();
for( unsigned int i = 0; i < parameterFileNameVector.size(); ++i )
{
if( !itksys::SystemTools::FileExists( parameterFileNameVector[ i ] ) )
{
itkExceptionMacro( "Parameter file \"" << parameterFileNameVector[ i ] << "\" does not exist." )
}
this->AddParameterFile( parameterFileNameVector[ i ] );
}
}
void
ParameterObject
::AddParameterFile( const ParameterFileNameType parameterFileName )
{
ParameterFileParserPointer parameterFileParser = ParameterFileParserType::New();
parameterFileParser->SetParameterFileName( parameterFileName );
parameterFileParser->ReadParameterFile();
this->m_ParameterMapVector.push_back( parameterFileParser->GetParameterMap() );
}
void
ParameterObject
::WriteParameterFile( const ParameterMapType parameterMap, const ParameterFileNameType parameterFileName )
{
std::ofstream parameterFile;
parameterFile << std::fixed;
parameterFile.open( parameterFileName.c_str(), std::ofstream::out );
ParameterMapConstIterator parameterMapIterator = parameterMap.begin();
ParameterMapConstIterator parameterMapIteratorEnd = parameterMap.end();
while( parameterMapIterator != parameterMapIteratorEnd )
{
parameterFile << "(" << parameterMapIterator->first;
ParameterValueVectorType parameterMapValueVector = parameterMapIterator->second;
for( unsigned int i = 0; i < parameterMapValueVector.size(); ++i )
{
std::stringstream stream( parameterMapValueVector[ i ] );
float number;
stream >> number;
if( stream.fail() || stream.bad() ) {
parameterFile << " \"" << parameterMapValueVector[ i ] << "\"";
}
else
{
parameterFile << " " << number;
}
}
parameterFile << ")" << std::endl;
parameterMapIterator++;
}
parameterFile.close();
}
void
ParameterObject
::WriteParameterFile( const ParameterFileNameType parameterFileName )
{
if( this->m_ParameterMapVector.size() == 0 )
{
itkExceptionMacro( "Error writing parameter map to disk: The parameter object is empty." );
}
if( this->m_ParameterMapVector.size() > 1 )
{
itkExceptionMacro( "Error writing to disk: The number of parameter maps (" << this->m_ParameterMapVector.size() << ")"
<< " does not match the number of provided filenames (1). Please provide a vector of filenames." );
}
this->WriteParameterFile( this->m_ParameterMapVector[ 0 ], parameterFileName );
}
void
ParameterObject
::WriteParameterFile( const ParameterFileNameVectorType parameterFileNameVector )
{
if( this->m_ParameterMapVector.size() != parameterFileNameVector.size() )
{
itkExceptionMacro( "Error writing to disk: The number of parameter maps (" << this->m_ParameterMapVector.size() << ")"
<< " does not match the number of provided filenames (" << parameterFileNameVector.size() << ")." );
}
for( unsigned int i = 0; i < this->m_ParameterMapVector.size(); ++i )
{
this->WriteParameterFile( this->m_ParameterMapVector[ i ], parameterFileNameVector[ i ] );
}
}
void
ParameterObject
::SetParameterMap( const std::string transformName, const unsigned int numberOfResolutions, const double finalGridSpacingInPhysicalUnits )
{
this->m_ParameterMapVector = ParameterMapVectorType( 1, this->GetParameterMap( transformName, numberOfResolutions, finalGridSpacingInPhysicalUnits ) );
}
void
ParameterObject
::AddParameterMap( const std::string transformName, const unsigned int numberOfResolutions, const double finalGridSpacingInPhysicalUnits )
{
this->m_ParameterMapVector.push_back( this->GetParameterMap( transformName, numberOfResolutions, finalGridSpacingInPhysicalUnits ) );
}
ParameterObject::ParameterMapType
ParameterObject
::GetParameterMap( const std::string transformName, const unsigned int numberOfResolutions, const double finalGridSpacingInPhysicalUnits )
{
// Parameters that depend on size and number of resolutions
ParameterMapType parameterMap = ParameterMapType();
// Common Components
parameterMap[ "FixedImagePyramid" ] = ParameterValueVectorType( 1, "FixedSmoothingImagePyramid" );
parameterMap[ "MovingImagePyramid" ] = ParameterValueVectorType( 1, "MovingSmoothingImagePyramid" );
parameterMap[ "Interpolator"] = ParameterValueVectorType( 1, "LinearInterpolator");
parameterMap[ "Optimizer" ] = ParameterValueVectorType( 1, "AdaptiveStochasticGradientDescent" );
parameterMap[ "Resampler"] = ParameterValueVectorType( 1, "DefaultResampler" );
parameterMap[ "ResampleInterpolator"] = ParameterValueVectorType( 1, "FinalBSplineInterpolator" );
parameterMap[ "FinalBSplineInterpolationOrder" ] = ParameterValueVectorType( 1, "3" );
parameterMap[ "NumberOfResolutions" ] = ParameterValueVectorType( 1, ToString( numberOfResolutions ) );
// Image Sampler
parameterMap[ "ImageSampler" ] = ParameterValueVectorType( 1, "RandomCoordinate" );
parameterMap[ "NumberOfSpatialSamples"] = ParameterValueVectorType( 1, "2048" );
parameterMap[ "CheckNumberOfSamples" ] = ParameterValueVectorType( 1, "true" );
parameterMap[ "MaximumNumberOfSamplingAttempts" ] = ParameterValueVectorType( 1, "8" );
parameterMap[ "NewSamplesEveryIteration" ] = ParameterValueVectorType( 1, "true");
// Optimizer
parameterMap[ "NumberOfSamplesForExactGradient" ] = ParameterValueVectorType( 1, "4096" );
parameterMap[ "DefaultPixelValue" ] = ParameterValueVectorType( 1, "0.0" );
parameterMap[ "AutomaticParameterEstimation" ] = ParameterValueVectorType( 1, "true" );
// Output
parameterMap[ "WriteResultImage" ] = ParameterValueVectorType( 1, "true" );
parameterMap[ "ResultImageFormat" ] = ParameterValueVectorType( 1, "nii" );
// transformNames
if( transformName == "translation" )
{
parameterMap[ "Registration" ] = ParameterValueVectorType( 1, "MultiResolutionRegistration" );
parameterMap[ "Transform" ] = ParameterValueVectorType( 1, "TranslationTransform" );
parameterMap[ "Metric" ] = ParameterValueVectorType( 1, "AdvancedMattesMutualInformation" );
parameterMap[ "MaximumNumberOfIterations" ] = ParameterValueVectorType( 1, "256" );
parameterMap[ "AutomaticTransformInitialization" ] = ParameterValueVectorType( 1, "true" );
parameterMap[ "AutomaticTransformInitializationMethod" ] = ParameterValueVectorType( 1, "CenterOfGravity" );
}
else if( transformName == "rigid" )
{
parameterMap[ "Registration" ] = ParameterValueVectorType( 1, "MultiResolutionRegistration" );
parameterMap[ "Transform" ] = ParameterValueVectorType( 1, "EulerTransform" );
parameterMap[ "Metric" ] = ParameterValueVectorType( 1, "AdvancedMattesMutualInformation" );
parameterMap[ "MaximumNumberOfIterations" ] = ParameterValueVectorType( 1, "256" );
}
else if( transformName == "affine" )
{
parameterMap[ "Registration" ] = ParameterValueVectorType( 1, "MultiResolutionRegistration" );
parameterMap[ "Transform" ] = ParameterValueVectorType( 1, "AffineTransform" );
parameterMap[ "Metric" ] = ParameterValueVectorType( 1, "AdvancedMattesMutualInformation" );
parameterMap[ "MaximumNumberOfIterations" ] = ParameterValueVectorType( 1, "512" );
}
else if( transformName == "nonrigid" )
{
parameterMap[ "Registration" ] = ParameterValueVectorType( 1, "MultiMetricMultiResolutionRegistration" );
parameterMap[ "Transform" ] = ParameterValueVectorType( 1, "BSplineTransform" );
parameterMap[ "Metric" ] = ParameterValueVectorType( 1, "AdvancedMattesMutualInformation" );
parameterMap[ "Metric" ].push_back( "TransformBendingEnergyPenalty" );
parameterMap[ "Metric0Weight" ] = ParameterValueVectorType( 1, "0.0001" );
parameterMap[ "Metric1Weight" ] = ParameterValueVectorType( 1, "0.9999" );
parameterMap[ "MaximumNumberOfIterations" ] = ParameterValueVectorType( 1, "512" );
}
else if( transformName == "groupwise" )
{
parameterMap[ "Registration" ] = ParameterValueVectorType( 1, "MultiResolutionRegistration" );
parameterMap[ "Transform" ] = ParameterValueVectorType( 1, "BSplineStackTransform" );
parameterMap[ "Metric" ] = ParameterValueVectorType( 1, "VarianceOverLastDimensionMetric" );
parameterMap[ "MaximumNumberOfIterations" ] = ParameterValueVectorType( 1, "512" );
parameterMap[ "Interpolator"] = ParameterValueVectorType( 1, "ReducedDimensionBSplineInterpolator" );
parameterMap[ "ResampleInterpolator" ] = ParameterValueVectorType( 1, "FinalReducedDimensionBSplineInterpolator" );
}
else
{
itkExceptionMacro( "No default parameter map \"" << transformName << "\"." );
}
// B-spline transform settings
if( transformName == "nonrigid" || transformName == "groupwise" )
{
ParameterValueVectorType gridSpacingSchedule = ParameterValueVectorType();
for( unsigned int resolution = 0; resolution < numberOfResolutions; ++resolution )
{
gridSpacingSchedule.insert( gridSpacingSchedule.begin(), ToString( pow( 2, resolution ) ) );
}
parameterMap[ "GridSpacingSchedule" ] = gridSpacingSchedule;
parameterMap[ "FinalGridSpacingInPhysicalUnits" ] = ParameterValueVectorType( 1, ToString( finalGridSpacingInPhysicalUnits ) );
}
return parameterMap;
}
} // namespace elastix
#endif // elxParameterObject_cxx
// http://stackoverflow.com/questions/9670396/exception-handling-and-opening-a-file
// TODO: Implement exception handling for parameter file reader/writer, rethrow itk exception
// int main () {
// ifstream file;
// file.exceptions ( ifstream::failbit | ifstream::badbit );
// try {
// file.open ("test.txt");
// while (!file.eof()) file.get();
// }
// catch ( ifstream::failure e ) {
// cout << "Exception opening/reading file";
// }
// file.close();
// return 0;
// }
// int main () {
// ofstream file;
// file.exceptions ( ofstream::failbit | ofstream::badbit | ofstream::failure );
// try {
// file.open ("test.txt");
// while (!file.eof()) file.get();
// }
// catch (ifstream::failure e) {
// cout << "Exception opening/reading file";
// }
// file.close();
// return 0;
// }
<|endoftext|> |
<commit_before>// License: Apache 2.0. See LICENSE file in root directory.
// Copyright(c) 2016 Intel Corporation. All Rights Reserved
#include "PersonTrackingServer.h"
#include "PersonTracking2RosHelper.h"
namespace realsense_ros_person
{
PersonTrackingServer::PersonTrackingServer()
{}
void PersonTrackingServer::onInit(ros::NodeHandle &nodeHandle,
rs::person_tracking::person_tracking_video_module_interface *personTracking,
PersonTrackingConfig &config)
{
mPersonTracking = personTracking;
mConfig = config;
mTrackingConfigService = nodeHandle.advertiseService("person_tracking/tracking_config",
&PersonTrackingServer::trackingConfigRequestCallback,
this);
mRecognitionRequestService = nodeHandle.advertiseService("person_tracking/recognition_request",
&PersonTrackingServer::recognitionRequestCallback,
this);
mRecognitionRegisterRequestService = nodeHandle.advertiseService("person_tracking/register_request",
&PersonTrackingServer::recognitionRegisterRequestCallback,
this);
mStartTrackingService = nodeHandle.advertiseService("person_tracking/start_tracking_request",
&PersonTrackingServer::startTrackingRequestCallback, this);
mStopTrackingService = nodeHandle.advertiseService("person_tracking/stop_tracking_request",
&PersonTrackingServer::stopTrackingRequestCallback, this);
mSaveRecognitionDbService = nodeHandle.advertiseService("person_tracking/save_recognition",
&PersonTrackingServer::saveRecognitionDbCallback, this);
mLoadRecognitionDbService = nodeHandle.advertiseService("person_tracking/load_recognition",
&PersonTrackingServer::loadRecognitionDbCallback, this);
}
bool PersonTrackingServer::trackingConfigRequestCallback(realsense_ros_person::TrackingConfig::Request &request,
realsense_ros_person::TrackingConfig::Response &response)
{
mConfig.recognitionEnabled = request.enableRecognition;
mConfig.pointingGestureEnabled = request.enablePointingGesture;
mConfig.waveGestureEnabled = request.enableWaveGesture;
mConfig.skeletonEnabled = request.enableSkeleton;
mConfig.headBoundingBoxEnabled = request.enableHeadBoundingBox;
mConfig.landmarksEnabled = request.enableLandmarks;
mConfig.headPoseEnabled = request.enableHeadPose;
mConfig.trackingEnabled = true;
ConfigurePersonTracking(mConfig, mPersonTracking->QueryConfiguration());
response.status = true;
return true;
}
bool PersonTrackingServer::recognitionRequestCallback(realsense_ros_person::Recognition::Request &request,
realsense_ros_person::Recognition::Response &response)
{
if (!mPersonTracking->QueryConfiguration()->QueryRecognition()->IsEnabled())
{
ROS_ERROR("Recognition is not enabled");
response.status = -1;
return true;
}
ROS_INFO_STREAM("Received recognition request for person: " << request.personId);
PXCPersonTrackingData *trackingData = mPersonTracking->QueryOutput();
PXCPersonTrackingData::Person *personData = trackingData->QueryPersonDataById(request.personId);
if (!personData)
{
ROS_ERROR_STREAM("Couldn't find recognition request target");
response.status = -1;
return true;
}
ROS_INFO_STREAM("Found recognition request target");
PXCPersonTrackingData::PersonRecognition *recognition = personData->QueryRecognition();
ROS_INFO("User recognition");
PXCPersonTrackingData::PersonRecognition::RecognizerData result;
auto status = recognition->RecognizeUser(&result);
response.status = m_pt2rosHelper.RecognitionStatus2RosRecognitionStatus(status);
response.recognitionId = -1;
response.similarityScore = 0;
switch (status)
{
case PXCPersonTrackingData::PersonRecognition::RecognitionStatus::RecognitionPassedPersonRecognized:
ROS_INFO_STREAM("Recognized person: " << result.recognitionId << " TrackingId: " << result.trackingId);
response.recognitionId = result.recognitionId;
response.similarityScore = result.similarityScore;
break;
case PXCPersonTrackingData::PersonRecognition::RecognitionStatus::RecognitionPassedPersonNotRecognized:
ROS_INFO_STREAM("Recognition passed. person not recognized");
break;
case PXCPersonTrackingData::PersonRecognition::RecognitionStatus::RecognitionFailed:
ROS_INFO_STREAM("Recognition failed.");
break;
case PXCPersonTrackingData::PersonRecognition::RecognitionStatus::RecognitionFailedFaceNotDetected:
ROS_INFO_STREAM("Recognition failed. Face not detected");
break;
case PXCPersonTrackingData::PersonRecognition::RecognitionStatus::RecognitionFailedFaceNotClear:
ROS_INFO_STREAM("Recognition failed. Face not clear");
break;
case PXCPersonTrackingData::PersonRecognition::RecognitionStatus::RecognitionFailedPersonTooFar:
ROS_INFO_STREAM("Recognition failed. Person too far");
break;
case PXCPersonTrackingData::PersonRecognition::RecognitionStatus::RecognitionFailedPersonTooClose:
ROS_INFO_STREAM("Recognition failed. Person too close");
break;
case PXCPersonTrackingData::PersonRecognition::RecognitionStatus::RecognitionFailedFaceAmbiguity:
ROS_INFO_STREAM("Recognition failed. Face ambiguity");
break;
}
return true;
}
bool
PersonTrackingServer::recognitionRegisterRequestCallback(realsense_ros_person::RecognitionRegister::Request &request,
realsense_ros_person::RecognitionRegister::Response &response)
{
if (!mPersonTracking->QueryConfiguration()->QueryRecognition()->IsEnabled())
{
ROS_INFO("Recognition is not enabled");
response.status = false;
return true;
}
ROS_INFO_STREAM("Received register request for person: " << request.personId);
PXCPersonTrackingData *trackingData = mPersonTracking->QueryOutput();
PXCPersonTrackingData::Person *personData = trackingData->QueryPersonDataById(request.personId);
if (!personData)
{
ROS_ERROR_STREAM("Couldn't find recognition request target");
response.status = false;
return true;
}
ROS_INFO_STREAM("Found register request target");
PXCPersonTrackingData::PersonRecognition *recognition = personData->QueryRecognition();
int32_t outputRecognitionId;
int32_t outputTrackingId;
int32_t outDescriptorId;
ROS_INFO("User registration");
auto status = recognition->RegisterUser(&outputRecognitionId, &outputTrackingId, &outDescriptorId);
response.status = m_pt2rosHelper.RegistrationStatus2RosRecognitionStatus(status);
switch (status)
{
case PXCPersonTrackingData::PersonRecognition::RegistrationStatus::RegistrationSuccessful:
ROS_INFO_STREAM("Registered person: " << outputRecognitionId << " TrackingId: " << outputTrackingId);
response.recognitionId = outputRecognitionId;
break;
case PXCPersonTrackingData::PersonRecognition::RegistrationStatus::RegistrationFailedAlreadyRegistered:
ROS_INFO_STREAM(
"Person already registered: " << outputRecognitionId << " TrackingId: " << outputTrackingId);
break;
case PXCPersonTrackingData::PersonRecognition::RegistrationStatus::RegistrationFailed:
ROS_INFO_STREAM(
"Registration failed: person: " << outputRecognitionId << " TrackingId: " << outputTrackingId);
break;
case PXCPersonTrackingData::PersonRecognition::RegistrationStatus::RegistrationFailedFaceNotDetected:
ROS_INFO_STREAM(
"Registration failed: face not detected, person: " << outputRecognitionId << " TrackingId: "
<< outputTrackingId);
break;
case PXCPersonTrackingData::PersonRecognition::RegistrationStatus::RegistrationFailedFaceNotClear:
ROS_INFO_STREAM(
"Registration failed: face not clear, person: " << outputRecognitionId << " TrackingId: "
<< outputTrackingId);
break;
case PXCPersonTrackingData::PersonRecognition::RegistrationStatus::RegistrationFailedPersonTooFar:
ROS_INFO_STREAM(
"Registration failed: person too far, person: " << outputRecognitionId << " TrackingId: "
<< outputTrackingId);
break;
case PXCPersonTrackingData::PersonRecognition::RegistrationStatus::RegistrationFailedPersonTooClose:
ROS_INFO_STREAM(
"Registration failed: person to close, person: " << outputRecognitionId << " TrackingId: "
<< outputTrackingId);
break;
}
return true;
}
bool PersonTrackingServer::startStopTracking(bool isStart, int personId)
{
PXCPersonTrackingData *trackingData = mPersonTracking->QueryOutput();
PXCPersonTrackingData::Person *personData = trackingData->QueryPersonDataById(personId);
if (!personData)
{
ROS_ERROR_STREAM("Couldn't find tracking request target");
return false;
}
ROS_INFO_STREAM("Found tracking request target");
if (isStart)
{
ROS_INFO_STREAM("start tracking on person: " << personId);
trackingData->StartTracking(personId);
}
else
{
ROS_INFO_STREAM("stop tracking on person: " << personId);
trackingData->StopTracking(personId);
}
return true;
}
bool PersonTrackingServer::startTrackingRequestCallback(realsense_ros_person::StartTracking::Request &request,
realsense_ros_person::StartTracking::Response &response)
{
ROS_INFO_STREAM("Received start tracking request for person: " << request.personId);
response.status = startStopTracking(true, request.personId);
return true;
}
bool PersonTrackingServer::stopTrackingRequestCallback(realsense_ros_person::StopTracking::Request &request,
realsense_ros_person::StopTracking::Response &response)
{
ROS_INFO_STREAM("Received stop tracking request for person: " << request.personId);
response.status = startStopTracking(false, request.personId);
return true;
}
bool PersonTrackingServer::saveRecognitionDbCallback(realsense_ros_person::SaveRecognitionDB::Request &request,
realsense_ros_person::SaveRecognitionDB::Response &response)
{
std::string dbPath = request.saveToPath;
ROS_INFO_STREAM("Save database to: " << dbPath);
try
{
response.status = SaveDatabase(dbPath, mPersonTracking->QueryConfiguration());
}
catch (const std::runtime_error &error)
{
ROS_ERROR_STREAM("Failed to save database to: " << dbPath);
response.status = false;
}
return true;
}
bool PersonTrackingServer::loadRecognitionDbCallback(realsense_ros_person::LoadRecognitionDB::Request &request,
realsense_ros_person::LoadRecognitionDB::Response &response)
{
std::string dbPath = request.loadFromPath;
ROS_INFO_STREAM("Loading database from: " << dbPath);
try
{
response.status = LoadDatabase(dbPath, mPersonTracking->QueryConfiguration());;
}
catch (const std::runtime_error &error)
{
ROS_ERROR_STREAM("Failed to load database from: " << dbPath);
response.status = false;
}
return true;
}
}<commit_msg>person tracking: fix at recognition response<commit_after>// License: Apache 2.0. See LICENSE file in root directory.
// Copyright(c) 2016 Intel Corporation. All Rights Reserved
#include "PersonTrackingServer.h"
#include "PersonTracking2RosHelper.h"
namespace realsense_ros_person
{
PersonTrackingServer::PersonTrackingServer()
{}
void PersonTrackingServer::onInit(ros::NodeHandle &nodeHandle,
rs::person_tracking::person_tracking_video_module_interface *personTracking,
PersonTrackingConfig &config)
{
mPersonTracking = personTracking;
mConfig = config;
mTrackingConfigService = nodeHandle.advertiseService("person_tracking/tracking_config",
&PersonTrackingServer::trackingConfigRequestCallback,
this);
mRecognitionRequestService = nodeHandle.advertiseService("person_tracking/recognition_request",
&PersonTrackingServer::recognitionRequestCallback,
this);
mRecognitionRegisterRequestService = nodeHandle.advertiseService("person_tracking/register_request",
&PersonTrackingServer::recognitionRegisterRequestCallback,
this);
mStartTrackingService = nodeHandle.advertiseService("person_tracking/start_tracking_request",
&PersonTrackingServer::startTrackingRequestCallback, this);
mStopTrackingService = nodeHandle.advertiseService("person_tracking/stop_tracking_request",
&PersonTrackingServer::stopTrackingRequestCallback, this);
mSaveRecognitionDbService = nodeHandle.advertiseService("person_tracking/save_recognition",
&PersonTrackingServer::saveRecognitionDbCallback, this);
mLoadRecognitionDbService = nodeHandle.advertiseService("person_tracking/load_recognition",
&PersonTrackingServer::loadRecognitionDbCallback, this);
}
bool PersonTrackingServer::trackingConfigRequestCallback(realsense_ros_person::TrackingConfig::Request &request,
realsense_ros_person::TrackingConfig::Response &response)
{
mConfig.recognitionEnabled = request.enableRecognition;
mConfig.pointingGestureEnabled = request.enablePointingGesture;
mConfig.waveGestureEnabled = request.enableWaveGesture;
mConfig.skeletonEnabled = request.enableSkeleton;
mConfig.headBoundingBoxEnabled = request.enableHeadBoundingBox;
mConfig.landmarksEnabled = request.enableLandmarks;
mConfig.headPoseEnabled = request.enableHeadPose;
mConfig.trackingEnabled = true;
ConfigurePersonTracking(mConfig, mPersonTracking->QueryConfiguration());
response.status = true;
return true;
}
bool PersonTrackingServer::recognitionRequestCallback(realsense_ros_person::Recognition::Request &request,
realsense_ros_person::Recognition::Response &response)
{
if (!mPersonTracking->QueryConfiguration()->QueryRecognition()->IsEnabled())
{
ROS_ERROR("Recognition is not enabled");
response.status = realsense_ros_person::RecognitionResponse::RECOGNITION_FAILED;
return true;
}
ROS_INFO_STREAM("Received recognition request for person: " << request.personId);
PXCPersonTrackingData *trackingData = mPersonTracking->QueryOutput();
PXCPersonTrackingData::Person *personData = trackingData->QueryPersonDataById(request.personId);
if (!personData)
{
ROS_ERROR_STREAM("Couldn't find recognition request target");
response.status = realsense_ros_person::RecognitionResponse::RECOGNITION_FAILED;
return true;
}
ROS_INFO_STREAM("Found recognition request target");
PXCPersonTrackingData::PersonRecognition *recognition = personData->QueryRecognition();
ROS_INFO("User recognition");
PXCPersonTrackingData::PersonRecognition::RecognizerData result;
auto status = recognition->RecognizeUser(&result);
response.status = m_pt2rosHelper.RecognitionStatus2RosRecognitionStatus(status);
response.recognitionId = -1;
response.similarityScore = 0;
switch (status)
{
case PXCPersonTrackingData::PersonRecognition::RecognitionStatus::RecognitionPassedPersonRecognized:
ROS_INFO_STREAM("Recognized person: " << result.recognitionId << " TrackingId: " << result.trackingId);
response.recognitionId = result.recognitionId;
response.similarityScore = result.similarityScore;
break;
case PXCPersonTrackingData::PersonRecognition::RecognitionStatus::RecognitionPassedPersonNotRecognized:
ROS_INFO_STREAM("Recognition passed. person not recognized");
break;
case PXCPersonTrackingData::PersonRecognition::RecognitionStatus::RecognitionFailed:
ROS_INFO_STREAM("Recognition failed.");
break;
case PXCPersonTrackingData::PersonRecognition::RecognitionStatus::RecognitionFailedFaceNotDetected:
ROS_INFO_STREAM("Recognition failed. Face not detected");
break;
case PXCPersonTrackingData::PersonRecognition::RecognitionStatus::RecognitionFailedFaceNotClear:
ROS_INFO_STREAM("Recognition failed. Face not clear");
break;
case PXCPersonTrackingData::PersonRecognition::RecognitionStatus::RecognitionFailedPersonTooFar:
ROS_INFO_STREAM("Recognition failed. Person too far");
break;
case PXCPersonTrackingData::PersonRecognition::RecognitionStatus::RecognitionFailedPersonTooClose:
ROS_INFO_STREAM("Recognition failed. Person too close");
break;
case PXCPersonTrackingData::PersonRecognition::RecognitionStatus::RecognitionFailedFaceAmbiguity:
ROS_INFO_STREAM("Recognition failed. Face ambiguity");
break;
}
return true;
}
bool
PersonTrackingServer::recognitionRegisterRequestCallback(realsense_ros_person::RecognitionRegister::Request &request,
realsense_ros_person::RecognitionRegister::Response &response)
{
if (!mPersonTracking->QueryConfiguration()->QueryRecognition()->IsEnabled())
{
ROS_INFO("Recognition is not enabled");
response.status = realsense_ros_person::RecognitionRegisterResponse::REGISTRATION_FAILED;
return true;
}
ROS_INFO_STREAM("Received register request for person: " << request.personId);
PXCPersonTrackingData *trackingData = mPersonTracking->QueryOutput();
PXCPersonTrackingData::Person *personData = trackingData->QueryPersonDataById(request.personId);
if (!personData)
{
ROS_ERROR_STREAM("Couldn't find recognition request target");
response.status = realsense_ros_person::RecognitionRegisterResponse::REGISTRATION_FAILED;
return true;
}
ROS_INFO_STREAM("Found register request target");
PXCPersonTrackingData::PersonRecognition *recognition = personData->QueryRecognition();
int32_t outputRecognitionId;
int32_t outputTrackingId;
int32_t outDescriptorId;
ROS_INFO("User registration");
auto status = recognition->RegisterUser(&outputRecognitionId, &outputTrackingId, &outDescriptorId);
response.status = m_pt2rosHelper.RegistrationStatus2RosRecognitionStatus(status);
switch (status)
{
case PXCPersonTrackingData::PersonRecognition::RegistrationStatus::RegistrationSuccessful:
ROS_INFO_STREAM("Registered person: " << outputRecognitionId << " TrackingId: " << outputTrackingId);
response.recognitionId = outputRecognitionId;
break;
case PXCPersonTrackingData::PersonRecognition::RegistrationStatus::RegistrationFailedAlreadyRegistered:
ROS_INFO_STREAM(
"Person already registered: " << outputRecognitionId << " TrackingId: " << outputTrackingId);
break;
case PXCPersonTrackingData::PersonRecognition::RegistrationStatus::RegistrationFailed:
ROS_INFO_STREAM(
"Registration failed: person: " << outputRecognitionId << " TrackingId: " << outputTrackingId);
break;
case PXCPersonTrackingData::PersonRecognition::RegistrationStatus::RegistrationFailedFaceNotDetected:
ROS_INFO_STREAM(
"Registration failed: face not detected, person: " << outputRecognitionId << " TrackingId: "
<< outputTrackingId);
break;
case PXCPersonTrackingData::PersonRecognition::RegistrationStatus::RegistrationFailedFaceNotClear:
ROS_INFO_STREAM(
"Registration failed: face not clear, person: " << outputRecognitionId << " TrackingId: "
<< outputTrackingId);
break;
case PXCPersonTrackingData::PersonRecognition::RegistrationStatus::RegistrationFailedPersonTooFar:
ROS_INFO_STREAM(
"Registration failed: person too far, person: " << outputRecognitionId << " TrackingId: "
<< outputTrackingId);
break;
case PXCPersonTrackingData::PersonRecognition::RegistrationStatus::RegistrationFailedPersonTooClose:
ROS_INFO_STREAM(
"Registration failed: person to close, person: " << outputRecognitionId << " TrackingId: "
<< outputTrackingId);
break;
}
return true;
}
bool PersonTrackingServer::startStopTracking(bool isStart, int personId)
{
PXCPersonTrackingData *trackingData = mPersonTracking->QueryOutput();
PXCPersonTrackingData::Person *personData = trackingData->QueryPersonDataById(personId);
if (!personData)
{
ROS_ERROR_STREAM("Couldn't find tracking request target");
return false;
}
ROS_INFO_STREAM("Found tracking request target");
if (isStart)
{
ROS_INFO_STREAM("start tracking on person: " << personId);
trackingData->StartTracking(personId);
}
else
{
ROS_INFO_STREAM("stop tracking on person: " << personId);
trackingData->StopTracking(personId);
}
return true;
}
bool PersonTrackingServer::startTrackingRequestCallback(realsense_ros_person::StartTracking::Request &request,
realsense_ros_person::StartTracking::Response &response)
{
ROS_INFO_STREAM("Received start tracking request for person: " << request.personId);
response.status = startStopTracking(true, request.personId);
return true;
}
bool PersonTrackingServer::stopTrackingRequestCallback(realsense_ros_person::StopTracking::Request &request,
realsense_ros_person::StopTracking::Response &response)
{
ROS_INFO_STREAM("Received stop tracking request for person: " << request.personId);
response.status = startStopTracking(false, request.personId);
return true;
}
bool PersonTrackingServer::saveRecognitionDbCallback(realsense_ros_person::SaveRecognitionDB::Request &request,
realsense_ros_person::SaveRecognitionDB::Response &response)
{
std::string dbPath = request.saveToPath;
ROS_INFO_STREAM("Save database to: " << dbPath);
try
{
response.status = SaveDatabase(dbPath, mPersonTracking->QueryConfiguration());
}
catch (const std::runtime_error &error)
{
ROS_ERROR_STREAM("Failed to save database to: " << dbPath);
response.status = false;
}
return true;
}
bool PersonTrackingServer::loadRecognitionDbCallback(realsense_ros_person::LoadRecognitionDB::Request &request,
realsense_ros_person::LoadRecognitionDB::Response &response)
{
std::string dbPath = request.loadFromPath;
ROS_INFO_STREAM("Loading database from: " << dbPath);
try
{
response.status = LoadDatabase(dbPath, mPersonTracking->QueryConfiguration());;
}
catch (const std::runtime_error &error)
{
ROS_ERROR_STREAM("Failed to load database from: " << dbPath);
response.status = false;
}
return true;
}
}<|endoftext|> |
<commit_before>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: $RCSfile: itkTopHatImageFilterTest.cxx,v $
Language: C++
Date: $Date: 2005-09-01 13:41:14 $
Version: $Revision: 1.1 $
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 <itkImage.h>
#include "itkFilterWatcher.h"
#include <itkExceptionObject.h>
#include <itkImageFileReader.h>
#include <itkImageFileWriter.h>
#include <itkVesselEnhancingDiffusion2DImageFilter.h>
int itkVesselEnhancingDiffusion2DImageFilterTest(int argc, char* argv [] )
{
if( argc != 3 )
{
std::cerr << "Missing arguments." << std::endl;
std::cerr << "Usage: " << std::endl;
std::cerr << argv[0] << " inputImage outputImage" << std::endl;
return EXIT_FAILURE;
}
// Define the dimension of the images
const unsigned int Dimension = 2;
// Define the pixel type
typedef short PixelType;
// Declare the types of the images
typedef itk::Image<PixelType, Dimension> ImageType;
// Declare the reader and writer
typedef itk::ImageFileReader< ImageType > ReaderType;
typedef itk::ImageFileWriter< ImageType > WriterType;
// Declare the type for the Filter
typedef itk::VesselEnhancingDiffusion2DImageFilter<
PixelType, Dimension > FilterType;
// Create the reader and writer
ReaderType::Pointer reader = ReaderType::New();
WriterType::Pointer writer = WriterType::New();
reader->SetFileName( argv[1] );
writer->SetFileName( argv[2] );
FilterType::Pointer filter = FilterType::New();
FilterWatcher watcher(filter, "filter");
// Connect the pipeline
filter->SetInput( reader->GetOutput() );
filter->SetDefaultPars( ); // duplicates assignments given below
filter->SetTimeStep( 0.25 );
filter->SetIterations( 100 );
filter->SetRecalculateVesselness( 50 ); // Default is 100
filter->SetBeta( 0.5 );
filter->SetGamma( 5.0 );
filter->SetEpsilon( 0.01 );
filter->SetOmega( 25.0 );
filter->SetSensitivity( 20.0 );
std::vector< float > scales;
scales.resize(2);
scales[0] = 2;
scales[1] = 4;
filter->SetScales( scales );
filter->SetDarkObjectLightBackground( true );
filter->SetVerbose( true );
filter->Update();
writer->SetInput( filter->GetOutput() );
// Execute the filter
try
{
writer->Update();
}
catch (itk::ExceptionObject& e)
{
std::cerr << "Exception caught during pipeline Update\n" << e;
return EXIT_FAILURE;
}
// All objects should be automatically destroyed at this point
return EXIT_SUCCESS;
}
<commit_msg>ENH: Changed parameters used for running the itkVesselEnhancing test so that it doesn't timeout during memory check<commit_after>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: $RCSfile: itkTopHatImageFilterTest.cxx,v $
Language: C++
Date: $Date: 2005-09-01 13:41:14 $
Version: $Revision: 1.1 $
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 <itkImage.h>
#include "itkFilterWatcher.h"
#include <itkExceptionObject.h>
#include <itkImageFileReader.h>
#include <itkImageFileWriter.h>
#include <itkVesselEnhancingDiffusion2DImageFilter.h>
int itkVesselEnhancingDiffusion2DImageFilterTest(int argc, char* argv [] )
{
if( argc != 3 )
{
std::cerr << "Missing arguments." << std::endl;
std::cerr << "Usage: " << std::endl;
std::cerr << argv[0] << " inputImage outputImage" << std::endl;
return EXIT_FAILURE;
}
// Define the dimension of the images
const unsigned int Dimension = 2;
// Define the pixel type
typedef short PixelType;
// Declare the types of the images
typedef itk::Image<PixelType, Dimension> ImageType;
// Declare the reader and writer
typedef itk::ImageFileReader< ImageType > ReaderType;
typedef itk::ImageFileWriter< ImageType > WriterType;
// Declare the type for the Filter
typedef itk::VesselEnhancingDiffusion2DImageFilter<
PixelType, Dimension > FilterType;
// Create the reader and writer
ReaderType::Pointer reader = ReaderType::New();
WriterType::Pointer writer = WriterType::New();
reader->SetFileName( argv[1] );
writer->SetFileName( argv[2] );
FilterType::Pointer filter = FilterType::New();
FilterWatcher watcher(filter, "filter");
// Connect the pipeline
filter->SetInput( reader->GetOutput() );
filter->SetDefaultPars( ); // duplicates assignments given below
filter->SetTimeStep( 0.25 );
filter->SetIterations( 20 ); // Default is 200
filter->SetRecalculateVesselness( 10 ); // Default is 100
filter->SetBeta( 0.5 );
filter->SetGamma( 5.0 );
filter->SetEpsilon( 0.01 );
filter->SetOmega( 25.0 );
filter->SetSensitivity( 20.0 );
std::vector< float > scales;
scales.resize(2);
scales[0] = 1;
scales[1] = 3;
filter->SetScales( scales );
filter->SetDarkObjectLightBackground( true );
filter->SetVerbose( true );
filter->Update();
writer->SetInput( filter->GetOutput() );
// Execute the filter
try
{
writer->Update();
}
catch (itk::ExceptionObject& e)
{
std::cerr << "Exception caught during pipeline Update\n" << e;
return EXIT_FAILURE;
}
// All objects should be automatically destroyed at this point
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>/* dtkPluginGeneratorCMakeLists.cpp ---
*
* Author: Julien Wintz
* Copyright (C) 2008 - Julien Wintz, Inria.
* Created: Tue Mar 10 10:18:39 2009 (+0100)
* Version: $Id$
* Last-Updated: Tue Sep 29 08:33:35 2009 (+0200)
* By: Julien Wintz
* Update #: 22
*/
/* Commentary:
*
*/
/* Change log:
*
*/
#include "dtkPluginGenerator.h"
bool dtkPluginGenerator::generateCMakeLists(void)
{
QFile cmakeFile(d->target.absoluteFilePath("CMakeLists.txt"));
if(!cmakeFile.open(QIODevice::WriteOnly | QIODevice::Text)) {
qWarning() << "dtkPluginGenerator: unable to open CMakeLists.txt for writing";
return false;
}
QTextStream stream(&cmakeFile);
stream << QString(
"## #################################################################\n"
"## Generated by dtkPluginGenerator\n"
"## #################################################################\n"
"\n"
"cmake_minimum_required(VERSION 2.6)\n"
"\n"
"project(%1Plugin)\n"
"\n"
"## #################################################################\n"
"## Setup version numbering\n"
"## #################################################################\n"
"\n"
"set(${PROJECT_NAME}_VERSION_MAJOR 0 CACHE STRING \"${PROJECT_NAME} major version number.\")\n"
"set(${PROJECT_NAME}_VERSION_MINOR 1 CACHE STRING \"${PROJECT_NAME} minor version number.\")\n"
"set(${PROJECT_NAME}_VERSION_BUILD 0 CACHE STRING \"${PROJECT_NAME} build version number.\")\n"
"set(${PROJECT_NAME}_VERSION\n"
" \"${${PROJECT_NAME}_VERSION_MAJOR}.${${PROJECT_NAME}_VERSION_MINOR}.${${PROJECT_NAME}_VERSION_BUILD}\")\n"
"\n"
"mark_as_advanced(${PROJECT_NAME}_VERSION_MAJOR)\n"
"mark_as_advanced(${PROJECT_NAME}_VERSION_MINOR)\n"
"mark_as_advanced(${PROJECT_NAME}_VERSION_BUILD)\n"
"\n"
"set(CMAKE_COLOR_MAKEFILE ON)\n"
"set(CMAKE_VERBOSE_MAKEFILE OFF)\n"
"set(CMAKE_INCLUDE_CURRENT_DIR TRUE)\n"
"\n"
"## #################################################################\n"
"## Setup output paths\n"
"## #################################################################\n"
"\n"
"if(WIN32)\n"
" set(${PROJECT_NAME}_ARCHIVE_OUTPUT_DIRECTORY lib)\n"
" set(${PROJECT_NAME}_RUNTIME_OUTPUT_DIRECTORY bin)\n"
" set(${PROJECT_NAME}_LIBRARY_OUTPUT_DIRECTORY bin)\n"
"else(WIN32)\n"
" set(${PROJECT_NAME}_ARCHIVE_OUTPUT_DIRECTORY lib)\n"
" set(${PROJECT_NAME}_RUNTIME_OUTPUT_DIRECTORY bin)\n"
" set(${PROJECT_NAME}_LIBRARY_OUTPUT_DIRECTORY lib)\n"
"endif(WIN32)\n"
"\n"
"set(CMAKE_DEBUG_POSTFIX \"d\")\n"
"\n"
"set(LIBRARY_OUTPUT_PATH ${CMAKE_BINARY_DIR}/${${PROJECT_NAME}_LIBRARY_OUTPUT_DIRECTORY})\n"
"set(ARCHIVE_OUTPUT_PATH ${CMAKE_BINARY_DIR}/${${PROJECT_NAME}_ARCHIVE_OUTPUT_DIRECTORY})\n"
"set(RUNTIME_OUTPUT_PATH ${CMAKE_BINARY_DIR}/${${PROJECT_NAME}_RUNTIME_OUTPUT_DIRECTORY})\n"
"set(EXECUTABLE_OUTPUT_PATH ${CMAKE_BINARY_DIR}/${${PROJECT_NAME}_RUNTIME_OUTPUT_DIRECTORY})\n"
"\n"
"set(${PROJECT_NAME}_INCLUDE_PATH ${CMAKE_SOURCE_DIR}/src)\n"
"\n"
"set(${PROJECT_NAME}_LIBRARY_DIRS ${LIBRARY_OUTPUT_PATH})\n"
"set(${PROJECT_NAME}_RUNTIME_DIRS ${RUNTIME_OUTPUT_PATH})\n"
"\n"
"## #################################################################\n"
"## Resolve dependencies\n"
"## #################################################################\n"
"\n"
"mark_as_advanced(CMAKE_BACKWARDS_COMPATIBILITY)\n"
"mark_as_advanced(CMAKE_BUILD_TYPE)\n"
"mark_as_advanced(CMAKE_INSTALL_PREFIX)\n"
"if(APPLE)\n"
"mark_as_advanced(CMAKE_OSX_ARCHITECTURES)\n"
"mark_as_advanced(CMAKE_OSX_SYSROOT)\n"
"endif(APPLE)\n"
"\n"
"set(QT_USE_QTOPENGL TRUE)\n"
"set(QT_USE_QTXML TRUE)\n"
"set(QT_USE_QTSQL TRUE)\n"
"set(QT_USE_QTHELP TRUE)\n"
"set(QT_USE_QTNETWORK TRUE)\n"
"set(QT_USE_QTWEBKIT TRUE)\n"
"\n"
"find_package(Qt4 REQUIRED)\n"
"include(${QT_USE_FILE})\n"
"\n"
"mark_as_advanced(QT_QMAKE_EXECUTABLE)\n"
"\n"
"find_package(dtk REQUIRED)\n"
"include(${dtk_USE_FILE})\n"
"\n"
"## #################################################################\n"
"## Input\n"
"## #################################################################\n"
"\n"
"set(${PROJECT_NAME}_HEADERS_MOC\n"
" %1Plugin.h\n"
" %1.h\n"
")\n"
"\n"
"set(${PROJECT_NAME}_SOURCES\n"
" %1Plugin.cpp\n"
" %1.cpp\n"
")\n"
"\n"
"## #################################################################\n"
"## Build rules\n"
"## #################################################################\n"
"\n"
"add_definitions(${QT_DEFINITIONS})\n"
"add_definitions(-DQT_PLUGIN)\n"
"add_definitions(-DQT_SHARED)\n"
"add_definitions(-DQT_NO_DEBUG)\n"
"\n"
"qt4_wrap_cpp(${PROJECT_NAME}_SOURCES_MOC ${${PROJECT_NAME}_HEADERS_MOC})\n"
"\n"
"add_library(${PROJECT_NAME} SHARED\n"
" ${${PROJECT_NAME}_SOURCES_MOC} \n"
" ${${PROJECT_NAME}_SOURCES}\n"
")\n"
"\n"
"target_link_libraries(${PROJECT_NAME}\n"
" ${QT_LIBRARIES}\n"
" dtkCore\n"
")\n"
"\n"
"if(APPLE)\n"
" set(CMAKE_SHARED_LINKER_FLAGS \"-undefined dynamic_lookup\")\n"
"elseif(UNIX)\n"
" string(REPLACE \"-Wl,--no-undefined\" \"\" CMAKE_SHARED_LINKER_FLAGS \"${CMAKE_SHARED_LINKER_FLAGS}\")\n"
"endif()\n"
)
.arg(QString(d->plugin));
cmakeFile.close();
return true;
}
<commit_msg>Updating plugin generator to remove unuseful linker flags.<commit_after>/* dtkPluginGeneratorCMakeLists.cpp ---
*
* Author: Julien Wintz
* Copyright (C) 2008 - Julien Wintz, Inria.
* Created: Tue Mar 10 10:18:39 2009 (+0100)
* Version: $Id$
* Last-Updated: Tue Sep 29 23:16:14 2009 (+0200)
* By: Julien Wintz
* Update #: 23
*/
/* Commentary:
*
*/
/* Change log:
*
*/
#include "dtkPluginGenerator.h"
bool dtkPluginGenerator::generateCMakeLists(void)
{
QFile cmakeFile(d->target.absoluteFilePath("CMakeLists.txt"));
if(!cmakeFile.open(QIODevice::WriteOnly | QIODevice::Text)) {
qWarning() << "dtkPluginGenerator: unable to open CMakeLists.txt for writing";
return false;
}
QTextStream stream(&cmakeFile);
stream << QString(
"## #################################################################\n"
"## Generated by dtkPluginGenerator\n"
"## #################################################################\n"
"\n"
"cmake_minimum_required(VERSION 2.6)\n"
"\n"
"project(%1Plugin)\n"
"\n"
"## #################################################################\n"
"## Setup version numbering\n"
"## #################################################################\n"
"\n"
"set(${PROJECT_NAME}_VERSION_MAJOR 0 CACHE STRING \"${PROJECT_NAME} major version number.\")\n"
"set(${PROJECT_NAME}_VERSION_MINOR 1 CACHE STRING \"${PROJECT_NAME} minor version number.\")\n"
"set(${PROJECT_NAME}_VERSION_BUILD 0 CACHE STRING \"${PROJECT_NAME} build version number.\")\n"
"set(${PROJECT_NAME}_VERSION\n"
" \"${${PROJECT_NAME}_VERSION_MAJOR}.${${PROJECT_NAME}_VERSION_MINOR}.${${PROJECT_NAME}_VERSION_BUILD}\")\n"
"\n"
"mark_as_advanced(${PROJECT_NAME}_VERSION_MAJOR)\n"
"mark_as_advanced(${PROJECT_NAME}_VERSION_MINOR)\n"
"mark_as_advanced(${PROJECT_NAME}_VERSION_BUILD)\n"
"\n"
"set(CMAKE_COLOR_MAKEFILE ON)\n"
"set(CMAKE_VERBOSE_MAKEFILE OFF)\n"
"set(CMAKE_INCLUDE_CURRENT_DIR TRUE)\n"
"\n"
"## #################################################################\n"
"## Setup output paths\n"
"## #################################################################\n"
"\n"
"if(WIN32)\n"
" set(${PROJECT_NAME}_ARCHIVE_OUTPUT_DIRECTORY lib)\n"
" set(${PROJECT_NAME}_RUNTIME_OUTPUT_DIRECTORY bin)\n"
" set(${PROJECT_NAME}_LIBRARY_OUTPUT_DIRECTORY bin)\n"
"else(WIN32)\n"
" set(${PROJECT_NAME}_ARCHIVE_OUTPUT_DIRECTORY lib)\n"
" set(${PROJECT_NAME}_RUNTIME_OUTPUT_DIRECTORY bin)\n"
" set(${PROJECT_NAME}_LIBRARY_OUTPUT_DIRECTORY lib)\n"
"endif(WIN32)\n"
"\n"
"set(CMAKE_DEBUG_POSTFIX \"d\")\n"
"\n"
"set(LIBRARY_OUTPUT_PATH ${CMAKE_BINARY_DIR}/${${PROJECT_NAME}_LIBRARY_OUTPUT_DIRECTORY})\n"
"set(ARCHIVE_OUTPUT_PATH ${CMAKE_BINARY_DIR}/${${PROJECT_NAME}_ARCHIVE_OUTPUT_DIRECTORY})\n"
"set(RUNTIME_OUTPUT_PATH ${CMAKE_BINARY_DIR}/${${PROJECT_NAME}_RUNTIME_OUTPUT_DIRECTORY})\n"
"set(EXECUTABLE_OUTPUT_PATH ${CMAKE_BINARY_DIR}/${${PROJECT_NAME}_RUNTIME_OUTPUT_DIRECTORY})\n"
"\n"
"set(${PROJECT_NAME}_INCLUDE_PATH ${CMAKE_SOURCE_DIR}/src)\n"
"\n"
"set(${PROJECT_NAME}_LIBRARY_DIRS ${LIBRARY_OUTPUT_PATH})\n"
"set(${PROJECT_NAME}_RUNTIME_DIRS ${RUNTIME_OUTPUT_PATH})\n"
"\n"
"## #################################################################\n"
"## Resolve dependencies\n"
"## #################################################################\n"
"\n"
"mark_as_advanced(CMAKE_BACKWARDS_COMPATIBILITY)\n"
"mark_as_advanced(CMAKE_BUILD_TYPE)\n"
"mark_as_advanced(CMAKE_INSTALL_PREFIX)\n"
"if(APPLE)\n"
"mark_as_advanced(CMAKE_OSX_ARCHITECTURES)\n"
"mark_as_advanced(CMAKE_OSX_SYSROOT)\n"
"endif(APPLE)\n"
"\n"
"set(QT_USE_QTOPENGL TRUE)\n"
"set(QT_USE_QTXML TRUE)\n"
"set(QT_USE_QTSQL TRUE)\n"
"set(QT_USE_QTHELP TRUE)\n"
"set(QT_USE_QTNETWORK TRUE)\n"
"set(QT_USE_QTWEBKIT TRUE)\n"
"\n"
"find_package(Qt4 REQUIRED)\n"
"include(${QT_USE_FILE})\n"
"\n"
"mark_as_advanced(QT_QMAKE_EXECUTABLE)\n"
"\n"
"find_package(dtk REQUIRED)\n"
"include(${dtk_USE_FILE})\n"
"\n"
"## #################################################################\n"
"## Input\n"
"## #################################################################\n"
"\n"
"set(${PROJECT_NAME}_HEADERS_MOC\n"
" %1Plugin.h\n"
" %1.h\n"
")\n"
"\n"
"set(${PROJECT_NAME}_SOURCES\n"
" %1Plugin.cpp\n"
" %1.cpp\n"
")\n"
"\n"
"## #################################################################\n"
"## Build rules\n"
"## #################################################################\n"
"\n"
"add_definitions(${QT_DEFINITIONS})\n"
"add_definitions(-DQT_PLUGIN)\n"
"add_definitions(-DQT_SHARED)\n"
"add_definitions(-DQT_NO_DEBUG)\n"
"\n"
"qt4_wrap_cpp(${PROJECT_NAME}_SOURCES_MOC ${${PROJECT_NAME}_HEADERS_MOC})\n"
"\n"
"add_library(${PROJECT_NAME} SHARED\n"
" ${${PROJECT_NAME}_SOURCES_MOC} \n"
" ${${PROJECT_NAME}_SOURCES}\n"
")\n"
"\n"
"target_link_libraries(${PROJECT_NAME}\n"
" ${QT_LIBRARIES}\n"
" dtkCore\n"
")\n"
"\n"
)
.arg(QString(d->plugin));
cmakeFile.close();
return true;
}
<|endoftext|> |
<commit_before>/*************************************************************************/
/* native_extension_manager.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "native_extension_manager.h"
#include "core/io/file_access.h"
NativeExtensionManager::LoadStatus NativeExtensionManager::load_extension(const String &p_path) {
if (native_extension_map.has(p_path)) {
return LOAD_STATUS_ALREADY_LOADED;
}
Ref<NativeExtension> extension = ResourceLoader::load(p_path);
if (extension.is_null()) {
return LOAD_STATUS_FAILED;
}
if (level >= 0) { //already initialized up to some level
int32_t minimum_level = extension->get_minimum_library_initialization_level();
if (minimum_level < MIN(level, NativeExtension::INITIALIZATION_LEVEL_SCENE)) {
return LOAD_STATUS_NEEDS_RESTART;
}
//initialize up to current level
for (int32_t i = minimum_level; i < level; i++) {
extension->initialize_library(NativeExtension::InitializationLevel(level));
}
}
native_extension_map[p_path] = extension;
return LOAD_STATUS_OK;
}
NativeExtensionManager::LoadStatus NativeExtensionManager::reload_extension(const String &p_path) {
return LOAD_STATUS_OK; //TODO
}
NativeExtensionManager::LoadStatus NativeExtensionManager::unload_extension(const String &p_path) {
if (!native_extension_map.has(p_path)) {
return LOAD_STATUS_NOT_LOADED;
}
Ref<NativeExtension> extension = native_extension_map[p_path];
if (level >= 0) { //already initialized up to some level
int32_t minimum_level = extension->get_minimum_library_initialization_level();
if (minimum_level < MIN(level, NativeExtension::INITIALIZATION_LEVEL_SCENE)) {
return LOAD_STATUS_NEEDS_RESTART;
}
//initialize up to current level
for (int32_t i = level; i >= minimum_level; i--) {
extension->deinitialize_library(NativeExtension::InitializationLevel(level));
}
}
native_extension_map.erase(p_path);
return LOAD_STATUS_OK;
}
bool NativeExtensionManager::is_extension_loaded(const String &p_path) const {
return native_extension_map.has(p_path);
}
Vector<String> NativeExtensionManager::get_loaded_extensions() const {
Vector<String> ret;
for (const KeyValue<String, Ref<NativeExtension>> &E : native_extension_map) {
ret.push_back(E.key);
}
return ret;
}
Ref<NativeExtension> NativeExtensionManager::get_extension(const String &p_path) {
Map<String, Ref<NativeExtension>>::Element *E = native_extension_map.find(p_path);
ERR_FAIL_COND_V(!E, Ref<NativeExtension>());
return E->get();
}
void NativeExtensionManager::initialize_extensions(NativeExtension::InitializationLevel p_level) {
ERR_FAIL_COND(int32_t(p_level) - 1 != level);
for (KeyValue<String, Ref<NativeExtension>> &E : native_extension_map) {
E.value->initialize_library(p_level);
}
level = p_level;
}
void NativeExtensionManager::deinitialize_extensions(NativeExtension::InitializationLevel p_level) {
ERR_FAIL_COND(int32_t(p_level) != level);
for (KeyValue<String, Ref<NativeExtension>> &E : native_extension_map) {
E.value->deinitialize_library(p_level);
}
level = int32_t(p_level) - 1;
}
void NativeExtensionManager::load_extensions() {
FileAccessRef f = FileAccess::open(NativeExtension::get_extension_list_config_file(), FileAccess::READ);
while (f && !f->eof_reached()) {
String s = f->get_line().strip_edges();
if (!s.is_empty()) {
LoadStatus err = load_extension(s);
ERR_CONTINUE_MSG(err == LOAD_STATUS_FAILED, "Error loading extension: " + s);
}
}
}
NativeExtensionManager *NativeExtensionManager::get_singleton() {
return singleton;
}
void NativeExtensionManager::_bind_methods() {
ClassDB::bind_method(D_METHOD("load_extension", "path"), &NativeExtensionManager::load_extension);
ClassDB::bind_method(D_METHOD("reload_extension", "path"), &NativeExtensionManager::reload_extension);
ClassDB::bind_method(D_METHOD("unload_extension", "path"), &NativeExtensionManager::unload_extension);
ClassDB::bind_method(D_METHOD("is_extension_loaded", "path"), &NativeExtensionManager::is_extension_loaded);
ClassDB::bind_method(D_METHOD("get_loaded_extensions"), &NativeExtensionManager::get_loaded_extensions);
ClassDB::bind_method(D_METHOD("get_extension", "path"), &NativeExtensionManager::get_extension);
BIND_ENUM_CONSTANT(LOAD_STATUS_OK);
BIND_ENUM_CONSTANT(LOAD_STATUS_FAILED);
BIND_ENUM_CONSTANT(LOAD_STATUS_ALREADY_LOADED);
BIND_ENUM_CONSTANT(LOAD_STATUS_NOT_LOADED);
BIND_ENUM_CONSTANT(LOAD_STATUS_NEEDS_RESTART);
}
NativeExtensionManager *NativeExtensionManager::singleton = nullptr;
NativeExtensionManager::NativeExtensionManager() {
ERR_FAIL_COND(singleton != nullptr);
singleton = this;
}
<commit_msg>Fixing iteration for extension level loading.<commit_after>/*************************************************************************/
/* native_extension_manager.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "native_extension_manager.h"
#include "core/io/file_access.h"
NativeExtensionManager::LoadStatus NativeExtensionManager::load_extension(const String &p_path) {
if (native_extension_map.has(p_path)) {
return LOAD_STATUS_ALREADY_LOADED;
}
Ref<NativeExtension> extension = ResourceLoader::load(p_path);
if (extension.is_null()) {
return LOAD_STATUS_FAILED;
}
if (level >= 0) { //already initialized up to some level
int32_t minimum_level = extension->get_minimum_library_initialization_level();
if (minimum_level < MIN(level, NativeExtension::INITIALIZATION_LEVEL_SCENE)) {
return LOAD_STATUS_NEEDS_RESTART;
}
//initialize up to current level
for (int32_t i = minimum_level; i <= level; i++) {
extension->initialize_library(NativeExtension::InitializationLevel(i));
}
}
native_extension_map[p_path] = extension;
return LOAD_STATUS_OK;
}
NativeExtensionManager::LoadStatus NativeExtensionManager::reload_extension(const String &p_path) {
return LOAD_STATUS_OK; //TODO
}
NativeExtensionManager::LoadStatus NativeExtensionManager::unload_extension(const String &p_path) {
if (!native_extension_map.has(p_path)) {
return LOAD_STATUS_NOT_LOADED;
}
Ref<NativeExtension> extension = native_extension_map[p_path];
if (level >= 0) { //already initialized up to some level
int32_t minimum_level = extension->get_minimum_library_initialization_level();
if (minimum_level < MIN(level, NativeExtension::INITIALIZATION_LEVEL_SCENE)) {
return LOAD_STATUS_NEEDS_RESTART;
}
// deinitialize down to current level
for (int32_t i = level; i >= minimum_level; i--) {
extension->deinitialize_library(NativeExtension::InitializationLevel(i));
}
}
native_extension_map.erase(p_path);
return LOAD_STATUS_OK;
}
bool NativeExtensionManager::is_extension_loaded(const String &p_path) const {
return native_extension_map.has(p_path);
}
Vector<String> NativeExtensionManager::get_loaded_extensions() const {
Vector<String> ret;
for (const KeyValue<String, Ref<NativeExtension>> &E : native_extension_map) {
ret.push_back(E.key);
}
return ret;
}
Ref<NativeExtension> NativeExtensionManager::get_extension(const String &p_path) {
Map<String, Ref<NativeExtension>>::Element *E = native_extension_map.find(p_path);
ERR_FAIL_COND_V(!E, Ref<NativeExtension>());
return E->get();
}
void NativeExtensionManager::initialize_extensions(NativeExtension::InitializationLevel p_level) {
ERR_FAIL_COND(int32_t(p_level) - 1 != level);
for (KeyValue<String, Ref<NativeExtension>> &E : native_extension_map) {
E.value->initialize_library(p_level);
}
level = p_level;
}
void NativeExtensionManager::deinitialize_extensions(NativeExtension::InitializationLevel p_level) {
ERR_FAIL_COND(int32_t(p_level) != level);
for (KeyValue<String, Ref<NativeExtension>> &E : native_extension_map) {
E.value->deinitialize_library(p_level);
}
level = int32_t(p_level) - 1;
}
void NativeExtensionManager::load_extensions() {
FileAccessRef f = FileAccess::open(NativeExtension::get_extension_list_config_file(), FileAccess::READ);
while (f && !f->eof_reached()) {
String s = f->get_line().strip_edges();
if (!s.is_empty()) {
LoadStatus err = load_extension(s);
ERR_CONTINUE_MSG(err == LOAD_STATUS_FAILED, "Error loading extension: " + s);
}
}
}
NativeExtensionManager *NativeExtensionManager::get_singleton() {
return singleton;
}
void NativeExtensionManager::_bind_methods() {
ClassDB::bind_method(D_METHOD("load_extension", "path"), &NativeExtensionManager::load_extension);
ClassDB::bind_method(D_METHOD("reload_extension", "path"), &NativeExtensionManager::reload_extension);
ClassDB::bind_method(D_METHOD("unload_extension", "path"), &NativeExtensionManager::unload_extension);
ClassDB::bind_method(D_METHOD("is_extension_loaded", "path"), &NativeExtensionManager::is_extension_loaded);
ClassDB::bind_method(D_METHOD("get_loaded_extensions"), &NativeExtensionManager::get_loaded_extensions);
ClassDB::bind_method(D_METHOD("get_extension", "path"), &NativeExtensionManager::get_extension);
BIND_ENUM_CONSTANT(LOAD_STATUS_OK);
BIND_ENUM_CONSTANT(LOAD_STATUS_FAILED);
BIND_ENUM_CONSTANT(LOAD_STATUS_ALREADY_LOADED);
BIND_ENUM_CONSTANT(LOAD_STATUS_NOT_LOADED);
BIND_ENUM_CONSTANT(LOAD_STATUS_NEEDS_RESTART);
}
NativeExtensionManager *NativeExtensionManager::singleton = nullptr;
NativeExtensionManager::NativeExtensionManager() {
ERR_FAIL_COND(singleton != nullptr);
singleton = this;
}
<|endoftext|> |
<commit_before>/// Class copied from the Urho3D project. Modified for Tundra use.
//
// Copyright (c) 2008-2014 the Urho3D project.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
#include "StableHeaders.h"
#include "DebugHud.h"
#include "CoreDebugHuds.h"
#include "Framework.h"
#include "FrameAPI.h"
#include "CoreStringUtils.h"
#include "LoggingFunctions.h"
#include <CoreEvents.h>
#include <ResourceCache.h>
#include <GraphicsEvents.h>
#include <UIEvents.h>
#include <Context.h>
#include <Engine.h>
#include <Font.h>
#include <Graphics.h>
#include <Profiler.h>
#include <Renderer.h>
#include <Text.h>
#include <BorderImage.h>
#include <UI.h>
#include <Button.h>
#include <ScrollView.h>
#include <DebugNew.h>
using namespace Urho3D;
namespace Tundra
{
static const char* qualityTexts[] =
{
"Low",
"Med",
"High"
};
static const char* shadowQualityTexts[] =
{
"16bit Low",
"24bit Low",
"16bit High",
"24bit High"
};
DebugHud::DebugHud(Framework *framework) :
Object(framework->GetContext()),
framework_(framework),
useRendererStats_(false),
mode_(DEBUGHUD_SHOW_NONE),
currentTab_(0)
{
profilerHudPanel_ = new ProfilerHudPanel(framework_);
sceneHudPanel_ = new SceneHudPanel(framework_);
assetHudPanel_ = new AssetHudPanel(framework_);
XMLFile *style = context_->GetSubsystem<ResourceCache>()->GetResource<XMLFile>("UI/DefaultStyle.xml");
SharedPtr<BorderImage> container = CreateContainer(HA_LEFT, VA_TOP, 100);
statsText_ = new Text(context_);
statsText_->SetStyle("TextMonospaceShadowed", style);
container->AddChild(statsText_);
container = CreateContainer(HA_LEFT, VA_BOTTOM, 100);
modeText_ = new Text(context_);
modeText_->SetStyle("TextMonospaceShadowed", style);
container->AddChild(modeText_);
// Add core debug panels
AddTab("Profiler", StaticCast<DebugHudPanel>(profilerHudPanel_));
AddTab("Scene", sceneHudPanel_);
AddTab("Assets", assetHudPanel_);
framework_->Frame()->PostFrameUpdate.Connect(this, &DebugHud::OnUpdate);
SubscribeToEvent(E_SCREENMODE, HANDLER(DebugHud, HandleWindowChange));
}
DebugHud::~DebugHud()
{
profilerHudPanel_.Reset();
for(auto iter = tabs_.Begin(); iter != tabs_.End(); ++iter)
delete (*iter);
tabs_.Clear();
currentTab_ = 0;
foreach(SharedPtr<BorderImage> c, containers_)
c->Remove();
containers_.Clear();
}
bool DebugHud::AddTab(const String &name, DebugHudPanelWeakPtr updater)
{
foreach(auto tab, tabs_)
{
if (tab->name.Compare(name, true) == 0)
{
LogErrorF("DebugHud::AddTab: Tab '%s' already exists.", name.CString());
return false;
}
}
// Create widget and tab
updater->Create();
UIElementPtr widget = updater->Widget();
if (!widget)
{
LogErrorF("DebugHud::AddTab: Tab '%s' failed to create a widget for embedding.", name.CString());
return false;
}
HudTab *tab = new HudTab();
tab->name = name;
tab->updater = updater;
tabs_.Push(tab);
// Get default style
XMLFile *style = context_->GetSubsystem<ResourceCache>()->GetResource<XMLFile>("UI/DefaultStyle.xml");
// Initialize container
if (!tabContainer_)
{
tabContainer_ = CreateContainer(HA_RIGHT, VA_TOP, 100);
Graphics *graphics = GetSubsystem<Graphics>();
if (graphics)
{
tabContainer_->SetFixedHeight(graphics->GetHeight());
tabContainer_->SetFixedWidth(Urho3D::Clamp(static_cast<int>(graphics->GetWidth() * 0.4), 500, 900));
}
}
// Initialize button layout
if (!tabButtonLayout_)
{
tabButtonLayout_ = new UIElement(context_);
tabButtonLayout_->SetLayout(LM_HORIZONTAL, 15);
tabButtonLayout_->SetFixedHeight(35);
auto border = tabButtonLayout_->GetLayoutBorder();
border.top_ = 8; border.bottom_ = 8;
tabButtonLayout_->SetLayoutBorder(border);
tabContainer_->AddChild(tabButtonLayout_);
}
// Create button to invoke the panel
Button *button = tabButtonLayout_->CreateChild<Button>("button" + name, M_MAX_UNSIGNED);
Text *text = button->CreateChild<Text>("buttonText" + name, 0);
text->SetInternal(true);
text->SetText(name);
button->SetName(name);
button->SetStyle("Button", style);
// Sub to click release event
SubscribeToEvent(button, E_RELEASED, HANDLER(DebugHud, HandleTabChange));
bool isFirstChild = (tabContainer_->GetNumChildren() == 1);
ScrollView *panel = tabContainer_->CreateChild<ScrollView>("scrollView" + name, Urho3D::M_MAX_UNSIGNED);
/// Auto set style if a text widget to keep things looking consistent.
Text *textWidget = dynamic_cast<Text*>(widget.Get());
if (textWidget)
textWidget->SetStyle("TextMonospaceShadowed", style);
widget->SetVisible(isFirstChild);
// Embed widget to tab panel
panel->SetContentElement(widget);
panel->SetVisible(isFirstChild);
panel->SetStyle("OverlayScrollView", style);
tabContainer_->AddChild(panel);
// If first tab panel set it as current
if (isFirstChild && !currentTab_)
{
button->SetStyle("ButtonSelected");
currentTab_ = tab;
}
return true;
}
BorderImagePtr DebugHud::CreateContainer(int ha, int va, int priority)
{
XMLFile *style = context_->GetSubsystem<ResourceCache>()->GetResource<XMLFile>("UI/DefaultStyle.xml");
SharedPtr<BorderImage> container(new BorderImage(context_));
container->SetAlignment((HorizontalAlignment)ha, (VerticalAlignment)va);
container->SetPriority(priority);
container->SetVisible(false);
container->SetStyle("VOverlayTransparent", style);
GetSubsystem<UI>()->GetRoot()->AddChild(container);
containers_.Push(container);
return container;
}
void DebugHud::OnUpdate(float frametime)
{
if (mode_ == DEBUGHUD_SHOW_NONE)
return;
Graphics* graphics = GetSubsystem<Graphics>();
Renderer* renderer = GetSubsystem<Renderer>();
if (!renderer || !graphics)
return;
if (statsText_->IsVisible())
{
unsigned primitives, batches;
if (!useRendererStats_)
{
primitives = graphics->GetNumPrimitives();
batches = graphics->GetNumBatches();
}
else
{
primitives = renderer->GetNumPrimitives();
batches = renderer->GetNumBatches();
}
String stats;
stats.AppendWithFormat("Triangles %s\nBatches %u\nViews %u\nLights %u\nShadowmaps %u\nOccluders %u",
FormatDigitGrouping(primitives).CString(),
batches,
renderer->GetNumViews(),
renderer->GetNumLights(true),
renderer->GetNumShadowMaps(true),
renderer->GetNumOccluders(true));
if (!appStats_.Empty())
{
stats.Append("\n");
for (HashMap<String, String>::ConstIterator i = appStats_.Begin(); i != appStats_.End(); ++i)
stats.AppendWithFormat("\n%s %s", i->first_.CString(), i->second_.CString());
}
statsText_->SetText(stats);
}
if (modeText_->IsVisible())
{
String mode;
mode.AppendWithFormat("Tex:%s Mat:%s Spec:%s Shadows:%s Size:%i Quality:%s Occlusion:%s Instancing:%s Mode:%s",
qualityTexts[renderer->GetTextureQuality()],
qualityTexts[renderer->GetMaterialQuality()],
renderer->GetSpecularLighting() ? "On" : "Off",
renderer->GetDrawShadows() ? "On" : "Off",
renderer->GetShadowMapSize(),
shadowQualityTexts[renderer->GetShadowQuality()],
renderer->GetMaxOccluderTriangles() > 0 ? "On" : "Off",
renderer->GetDynamicInstancing() ? "On" : "Off",
#ifdef URHO3D_OPENGL
"OGL");
#else
graphics->GetSM3Support() ? "SM3" : "SM2");
#endif
modeText_->SetText(mode);
}
if (tabContainer_->IsVisible() && currentTab_)
{
SharedPtr<DebugHudPanel> panel = currentTab_->updater.Lock();
UIElementPtr widget = (panel.Get() ? panel->Widget() : UIElementPtr());
if (panel && widget)
panel->UpdatePanel(frametime, widget);
}
}
void DebugHud::SetMode(unsigned mode)
{
statsText_->GetParent()->SetVisible((mode & DEBUGHUD_SHOW_STATS) != 0);
modeText_->GetParent()->SetVisible((mode & DEBUGHUD_SHOW_MODE) != 0);
tabContainer_->SetVisible((mode & DEBUGHUD_SHOW_PANEL) != 0);
mode_ = mode;
}
void DebugHud::SetProfilerMaxDepth(unsigned depth)
{
profilerHudPanel_->profilerMaxDepth = depth;
}
void DebugHud::SetProfilerInterval(float interval)
{
profilerHudPanel_->profilerInterval = Max((int)(interval * 1000.0f), 0);
}
void DebugHud::SetUseRendererStats(bool enable)
{
useRendererStats_ = enable;
}
void DebugHud::Toggle(unsigned mode)
{
SetMode(GetMode() ^ mode);
}
void DebugHud::ToggleVisibility()
{
Toggle(DEBUGHUD_SHOW_ALL);
}
void DebugHud::SetVisible(bool visible)
{
SetMode(visible ? DEBUGHUD_SHOW_ALL : DEBUGHUD_SHOW_NONE);
}
unsigned DebugHud::GetProfilerMaxDepth() const
{
return profilerHudPanel_->profilerMaxDepth;
}
float DebugHud::GetProfilerInterval() const
{
return (float)profilerHudPanel_->profilerInterval / 1000.0f;
}
void DebugHud::SetAppStats(const String& label, const Variant& stats)
{
SetAppStats(label, stats.ToString());
}
void DebugHud::SetAppStats(const String& label, const String& stats)
{
bool newLabel = !appStats_.Contains(label);
appStats_[label] = stats;
if (newLabel)
appStats_.Sort();
}
bool DebugHud::ResetAppStats(const String& label)
{
return appStats_.Erase(label);
}
void DebugHud::ClearAppStats()
{
appStats_.Clear();
}
void DebugHud::HandleWindowChange(StringHash /*eventType*/, VariantMap& eventData)
{
using namespace ScreenMode;
if (tabContainer_)
{
tabContainer_->SetFixedHeight(eventData[P_HEIGHT].GetInt());
tabContainer_->SetFixedWidth(Urho3D::Clamp(static_cast<int>(eventData[P_WIDTH].GetInt() * 0.4), 500, 900));
}
}
void DebugHud::HandleTabChange(StringHash /*eventType*/, VariantMap& eventData)
{
using namespace Released;
Button *button = dynamic_cast<Button*>(eventData[P_ELEMENT].GetPtr());
if (!button)
return;
if (!ShowTab(button->GetName()))
return;
Vector<SharedPtr<UIElement> > children = tabButtonLayout_->GetChildren();
foreach(auto child, children)
{
Button *b = dynamic_cast<Button*>(child.Get());
if (b)
b->SetStyle(b == button ? "ButtonSelected" : "Button");
}
}
bool DebugHud::RemoveTab(const String &name)
{
for (auto iter = tabs_.Begin(); iter != tabs_.End(); ++iter)
{
HudTab *tab = (*iter);
if (tab->name.Compare(name, true))
{
tabs_.Erase(iter);
if (currentTab_ == tab)
{
currentTab_ = 0;
if (tabs_.Begin() != tabs_.End())
ShowTab(tabs_.Front()->name);
}
if (tab->updater.Get())
tab->updater->Destroy();
tab->updater.Reset();
delete tab;
return true;
}
}
LogErrorF("DebugHud::ShowTab: Tab '%s' does not exit.", name.CString());
return false;
}
bool DebugHud::ShowTab(const String &name)
{
if (name.Empty())
{
LogError("DebugHud::ShowTab: Provided tab name is empty");
return false;
}
UIElementPtr widget;
foreach(auto tab, tabs_)
{
if (tab->name.Compare(name, true) == 0 && tab->updater->Widget())
{
widget = tab->updater->Widget();
currentTab_ = tab;
break;
}
}
if (!widget)
{
LogErrorF("DebugHud::ShowTab: Tab '%s' does not exit.", name.CString());
return false;
}
foreach(auto tab, tabs_)
{
// Tab widgets are always parented to a ScrollView. Toggle its visibility.
UIElementPtr currentWidget = tab->updater->Widget();
bool visible = (currentWidget.Get() == widget.Get());
UIElement *parent = currentWidget->GetParent();
if (parent)
{
ScrollView *view = dynamic_cast<ScrollView*>(parent->GetParent() ? parent->GetParent() : parent);
if (view)
view->SetVisible(visible);
else
parent->SetVisible(visible);
}
currentWidget->SetVisible(visible);
}
return true;
}
StringVector DebugHud::TabNames() const
{
StringVector names;
foreach(auto tab, tabs_)
names.Push(tab->name);
return names;
}
}
<commit_msg>DebugHud: Show current FPS in the top left corner summary.<commit_after>/// Class copied from the Urho3D project. Modified for Tundra use.
//
// Copyright (c) 2008-2014 the Urho3D project.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
#include "StableHeaders.h"
#include "DebugHud.h"
#include "CoreDebugHuds.h"
#include "Framework.h"
#include "FrameAPI.h"
#include "CoreStringUtils.h"
#include "LoggingFunctions.h"
#include <CoreEvents.h>
#include <ResourceCache.h>
#include <GraphicsEvents.h>
#include <UIEvents.h>
#include <Context.h>
#include <Engine.h>
#include <Font.h>
#include <Graphics.h>
#include <Profiler.h>
#include <Renderer.h>
#include <Text.h>
#include <BorderImage.h>
#include <UI.h>
#include <Button.h>
#include <ScrollView.h>
#include <DebugNew.h>
using namespace Urho3D;
namespace Tundra
{
static const char* qualityTexts[] =
{
"Low",
"Med",
"High"
};
static const char* shadowQualityTexts[] =
{
"16bit Low",
"24bit Low",
"16bit High",
"24bit High"
};
DebugHud::DebugHud(Framework *framework) :
Object(framework->GetContext()),
framework_(framework),
useRendererStats_(false),
mode_(DEBUGHUD_SHOW_NONE),
currentTab_(0)
{
profilerHudPanel_ = new ProfilerHudPanel(framework_);
sceneHudPanel_ = new SceneHudPanel(framework_);
assetHudPanel_ = new AssetHudPanel(framework_);
XMLFile *style = context_->GetSubsystem<ResourceCache>()->GetResource<XMLFile>("UI/DefaultStyle.xml");
SharedPtr<BorderImage> container = CreateContainer(HA_LEFT, VA_TOP, 100);
statsText_ = new Text(context_);
statsText_->SetStyle("TextMonospaceShadowed", style);
container->AddChild(statsText_);
container = CreateContainer(HA_LEFT, VA_BOTTOM, 100);
modeText_ = new Text(context_);
modeText_->SetStyle("TextMonospaceShadowed", style);
container->AddChild(modeText_);
// Add core debug panels
AddTab("Profiler", StaticCast<DebugHudPanel>(profilerHudPanel_));
AddTab("Scene", sceneHudPanel_);
AddTab("Assets", assetHudPanel_);
framework_->Frame()->PostFrameUpdate.Connect(this, &DebugHud::OnUpdate);
SubscribeToEvent(E_SCREENMODE, HANDLER(DebugHud, HandleWindowChange));
}
DebugHud::~DebugHud()
{
profilerHudPanel_.Reset();
for(auto iter = tabs_.Begin(); iter != tabs_.End(); ++iter)
delete (*iter);
tabs_.Clear();
currentTab_ = 0;
foreach(SharedPtr<BorderImage> c, containers_)
c->Remove();
containers_.Clear();
}
bool DebugHud::AddTab(const String &name, DebugHudPanelWeakPtr updater)
{
foreach(auto tab, tabs_)
{
if (tab->name.Compare(name, true) == 0)
{
LogErrorF("DebugHud::AddTab: Tab '%s' already exists.", name.CString());
return false;
}
}
// Create widget and tab
updater->Create();
UIElementPtr widget = updater->Widget();
if (!widget)
{
LogErrorF("DebugHud::AddTab: Tab '%s' failed to create a widget for embedding.", name.CString());
return false;
}
HudTab *tab = new HudTab();
tab->name = name;
tab->updater = updater;
tabs_.Push(tab);
// Get default style
XMLFile *style = context_->GetSubsystem<ResourceCache>()->GetResource<XMLFile>("UI/DefaultStyle.xml");
// Initialize container
if (!tabContainer_)
{
tabContainer_ = CreateContainer(HA_RIGHT, VA_TOP, 100);
Graphics *graphics = GetSubsystem<Graphics>();
if (graphics)
{
tabContainer_->SetFixedHeight(graphics->GetHeight());
tabContainer_->SetFixedWidth(Urho3D::Clamp(static_cast<int>(graphics->GetWidth() * 0.4), 500, 900));
}
}
// Initialize button layout
if (!tabButtonLayout_)
{
tabButtonLayout_ = new UIElement(context_);
tabButtonLayout_->SetLayout(LM_HORIZONTAL, 15);
tabButtonLayout_->SetFixedHeight(35);
auto border = tabButtonLayout_->GetLayoutBorder();
border.top_ = 8; border.bottom_ = 8;
tabButtonLayout_->SetLayoutBorder(border);
tabContainer_->AddChild(tabButtonLayout_);
}
// Create button to invoke the panel
Button *button = tabButtonLayout_->CreateChild<Button>("button" + name, M_MAX_UNSIGNED);
Text *text = button->CreateChild<Text>("buttonText" + name, 0);
text->SetInternal(true);
text->SetText(name);
button->SetName(name);
button->SetStyle("Button", style);
// Sub to click release event
SubscribeToEvent(button, E_RELEASED, HANDLER(DebugHud, HandleTabChange));
bool isFirstChild = (tabContainer_->GetNumChildren() == 1);
ScrollView *panel = tabContainer_->CreateChild<ScrollView>("scrollView" + name, Urho3D::M_MAX_UNSIGNED);
/// Auto set style if a text widget to keep things looking consistent.
Text *textWidget = dynamic_cast<Text*>(widget.Get());
if (textWidget)
textWidget->SetStyle("TextMonospaceShadowed", style);
widget->SetVisible(isFirstChild);
// Embed widget to tab panel
panel->SetContentElement(widget);
panel->SetVisible(isFirstChild);
panel->SetStyle("OverlayScrollView", style);
tabContainer_->AddChild(panel);
// If first tab panel set it as current
if (isFirstChild && !currentTab_)
{
button->SetStyle("ButtonSelected");
currentTab_ = tab;
}
return true;
}
BorderImagePtr DebugHud::CreateContainer(int ha, int va, int priority)
{
XMLFile *style = context_->GetSubsystem<ResourceCache>()->GetResource<XMLFile>("UI/DefaultStyle.xml");
SharedPtr<BorderImage> container(new BorderImage(context_));
container->SetAlignment((HorizontalAlignment)ha, (VerticalAlignment)va);
container->SetPriority(priority);
container->SetVisible(false);
container->SetStyle("VOverlayTransparent", style);
GetSubsystem<UI>()->GetRoot()->AddChild(container);
containers_.Push(container);
return container;
}
void DebugHud::OnUpdate(float frametime)
{
if (mode_ == DEBUGHUD_SHOW_NONE)
return;
Graphics* graphics = GetSubsystem<Graphics>();
Renderer* renderer = GetSubsystem<Renderer>();
if (!renderer || !graphics)
return;
if (statsText_->IsVisible())
{
unsigned primitives, batches;
if (!useRendererStats_)
{
primitives = graphics->GetNumPrimitives();
batches = graphics->GetNumBatches();
}
else
{
primitives = renderer->GetNumPrimitives();
batches = renderer->GetNumBatches();
}
String stats;
stats.AppendWithFormat("FPS %d\nTriangles %s\nBatches %u\nViews %u\nLights %u\nShadowmaps %u\nOccluders %u",
static_cast<int>(1.f / GetSubsystem<Time>()->GetTimeStep()),
FormatDigitGrouping(primitives).CString(),
batches,
renderer->GetNumViews(),
renderer->GetNumLights(true),
renderer->GetNumShadowMaps(true),
renderer->GetNumOccluders(true));
if (!appStats_.Empty())
{
stats.Append("\n");
for (HashMap<String, String>::ConstIterator i = appStats_.Begin(); i != appStats_.End(); ++i)
stats.AppendWithFormat("\n%s %s", i->first_.CString(), i->second_.CString());
}
statsText_->SetText(stats);
}
if (modeText_->IsVisible())
{
String mode;
mode.AppendWithFormat("Tex:%s Mat:%s Spec:%s Shadows:%s Size:%i Quality:%s Occlusion:%s Instancing:%s Mode:%s",
qualityTexts[renderer->GetTextureQuality()],
qualityTexts[renderer->GetMaterialQuality()],
renderer->GetSpecularLighting() ? "On" : "Off",
renderer->GetDrawShadows() ? "On" : "Off",
renderer->GetShadowMapSize(),
shadowQualityTexts[renderer->GetShadowQuality()],
renderer->GetMaxOccluderTriangles() > 0 ? "On" : "Off",
renderer->GetDynamicInstancing() ? "On" : "Off",
#ifdef URHO3D_OPENGL
"OGL");
#else
graphics->GetSM3Support() ? "SM3" : "SM2");
#endif
modeText_->SetText(mode);
}
if (tabContainer_->IsVisible() && currentTab_)
{
SharedPtr<DebugHudPanel> panel = currentTab_->updater.Lock();
UIElementPtr widget = (panel.Get() ? panel->Widget() : UIElementPtr());
if (panel && widget)
panel->UpdatePanel(frametime, widget);
}
}
void DebugHud::SetMode(unsigned mode)
{
statsText_->GetParent()->SetVisible((mode & DEBUGHUD_SHOW_STATS) != 0);
modeText_->GetParent()->SetVisible((mode & DEBUGHUD_SHOW_MODE) != 0);
tabContainer_->SetVisible((mode & DEBUGHUD_SHOW_PANEL) != 0);
mode_ = mode;
}
void DebugHud::SetProfilerMaxDepth(unsigned depth)
{
profilerHudPanel_->profilerMaxDepth = depth;
}
void DebugHud::SetProfilerInterval(float interval)
{
profilerHudPanel_->profilerInterval = Max((int)(interval * 1000.0f), 0);
}
void DebugHud::SetUseRendererStats(bool enable)
{
useRendererStats_ = enable;
}
void DebugHud::Toggle(unsigned mode)
{
SetMode(GetMode() ^ mode);
}
void DebugHud::ToggleVisibility()
{
Toggle(DEBUGHUD_SHOW_ALL);
}
void DebugHud::SetVisible(bool visible)
{
SetMode(visible ? DEBUGHUD_SHOW_ALL : DEBUGHUD_SHOW_NONE);
}
unsigned DebugHud::GetProfilerMaxDepth() const
{
return profilerHudPanel_->profilerMaxDepth;
}
float DebugHud::GetProfilerInterval() const
{
return (float)profilerHudPanel_->profilerInterval / 1000.0f;
}
void DebugHud::SetAppStats(const String& label, const Variant& stats)
{
SetAppStats(label, stats.ToString());
}
void DebugHud::SetAppStats(const String& label, const String& stats)
{
bool newLabel = !appStats_.Contains(label);
appStats_[label] = stats;
if (newLabel)
appStats_.Sort();
}
bool DebugHud::ResetAppStats(const String& label)
{
return appStats_.Erase(label);
}
void DebugHud::ClearAppStats()
{
appStats_.Clear();
}
void DebugHud::HandleWindowChange(StringHash /*eventType*/, VariantMap& eventData)
{
using namespace ScreenMode;
if (tabContainer_)
{
tabContainer_->SetFixedHeight(eventData[P_HEIGHT].GetInt());
tabContainer_->SetFixedWidth(Urho3D::Clamp(static_cast<int>(eventData[P_WIDTH].GetInt() * 0.4), 500, 900));
}
}
void DebugHud::HandleTabChange(StringHash /*eventType*/, VariantMap& eventData)
{
using namespace Released;
Button *button = dynamic_cast<Button*>(eventData[P_ELEMENT].GetPtr());
if (!button)
return;
if (!ShowTab(button->GetName()))
return;
Vector<SharedPtr<UIElement> > children = tabButtonLayout_->GetChildren();
foreach(auto child, children)
{
Button *b = dynamic_cast<Button*>(child.Get());
if (b)
b->SetStyle(b == button ? "ButtonSelected" : "Button");
}
}
bool DebugHud::RemoveTab(const String &name)
{
for (auto iter = tabs_.Begin(); iter != tabs_.End(); ++iter)
{
HudTab *tab = (*iter);
if (tab->name.Compare(name, true))
{
tabs_.Erase(iter);
if (currentTab_ == tab)
{
currentTab_ = 0;
if (tabs_.Begin() != tabs_.End())
ShowTab(tabs_.Front()->name);
}
if (tab->updater.Get())
tab->updater->Destroy();
tab->updater.Reset();
delete tab;
return true;
}
}
LogErrorF("DebugHud::ShowTab: Tab '%s' does not exit.", name.CString());
return false;
}
bool DebugHud::ShowTab(const String &name)
{
if (name.Empty())
{
LogError("DebugHud::ShowTab: Provided tab name is empty");
return false;
}
UIElementPtr widget;
foreach(auto tab, tabs_)
{
if (tab->name.Compare(name, true) == 0 && tab->updater->Widget())
{
widget = tab->updater->Widget();
currentTab_ = tab;
break;
}
}
if (!widget)
{
LogErrorF("DebugHud::ShowTab: Tab '%s' does not exit.", name.CString());
return false;
}
foreach(auto tab, tabs_)
{
// Tab widgets are always parented to a ScrollView. Toggle its visibility.
UIElementPtr currentWidget = tab->updater->Widget();
bool visible = (currentWidget.Get() == widget.Get());
UIElement *parent = currentWidget->GetParent();
if (parent)
{
ScrollView *view = dynamic_cast<ScrollView*>(parent->GetParent() ? parent->GetParent() : parent);
if (view)
view->SetVisible(visible);
else
parent->SetVisible(visible);
}
currentWidget->SetVisible(visible);
}
return true;
}
StringVector DebugHud::TabNames() const
{
StringVector names;
foreach(auto tab, tabs_)
names.Push(tab->name);
return names;
}
}
<|endoftext|> |
<commit_before>// ======================================================================== //
// Copyright 2009-2017 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. //
// ======================================================================== //
#ifdef _WIN32
# define WIN32_LEAN_AND_MEAN
# include <windows.h> // for Sleep
#else
# include <time.h>
#endif
#include <chrono>
#include <atomic>
#include <thread>
#include "BatchedIsendIrecvMessaging.h"
namespace ospray {
namespace mpi {
namespace async {
enum { SEND_WINDOW_SIZE = 48 };
enum { RECV_WINDOW_SIZE = 48 };
enum { PROC_WINDOW_SIZE = 20 };
BatchedIsendIrecvImpl::Group::Group(MPI_Comm comm,
Consumer *consumer,
int32 tag)
: async::Group(comm,consumer,tag),
sendThread(this),
procThread(this),
recvThread(this),
shouldExit(false)
{
sendThread.handle = std::thread([this](){this->sendThread.run();});
procThread.handle = std::thread([this](){this->procThread.run();});
recvThread.handle = std::thread([this](){this->recvThread.run();});
}
void BatchedIsendIrecvImpl::SendThread::run()
{
Group *g = this->group;
Action *actions[SEND_WINDOW_SIZE];
MPI_Request request[SEND_WINDOW_SIZE];
while (1) {
size_t numActions = 0;
while (numActions == 0){
numActions = g->sendQueue.getSomeFor(actions,SEND_WINDOW_SIZE,
std::chrono::milliseconds(1));
if (g->shouldExit.load()){
return;
}
}
for (uint32_t i = 0; i < numActions; i++) {
Action *action = actions[i];
lockMPI("async-isend");
MPI_CALL(Isend(action->data,action->size,MPI_BYTE,
action->addr.rank,g->tag,g->comm,&request[i]));
unlockMPI();
}
// TODO: Is it ok to wait even if we're exiting? Maybe we'd just get send
// failed statuses back?
lockMPI("async-send-waitall");
MPI_CALL(Waitall(numActions,request,MPI_STATUSES_IGNORE));
unlockMPI();
for (uint32_t i = 0; i < numActions; i++) {
Action *action = actions[i];
free(action->data);
delete action;
{ std::lock_guard<std::mutex> lock(g->flushMutex);
g->numMessagesDoneSending++;
if (g->numMessagesDoneSending == g->numMessagesAskedToSend)
g->isFlushedCondition.notify_one();
}
}
}
}
void BatchedIsendIrecvImpl::RecvThread::run()
{
// note this thread not only _probes_ for new receives, it
// also immediately starts the receive operation using Irecv()
Group *g = (Group *)this->group;
MPI_Request request[RECV_WINDOW_SIZE];
Action *actions[RECV_WINDOW_SIZE];
MPI_Status status;
int numRequests = 0;
#ifdef _WIN32
const DWORD sleep_time = 1; // ms --> much longer than 150us
#else
const timespec sleep_time = timespec{0, 150000};
#endif
while (1) {
numRequests = 0;
// wait for first message
{
// usleep(280);
int msgAvail = 0;
while (!msgAvail) {
lockMPI("async-iprobe");
MPI_CALL(Iprobe(MPI_ANY_SOURCE,g->tag,g->comm,&msgAvail,&status));
unlockMPI();
if (g->shouldExit.load()){
return;
}
if (msgAvail){
break;
}
#ifdef _WIN32
Sleep(sleep_time);
#else
// TODO: Can we do a CMake feature test for this_thread::sleep_for and
// conditionally use nanosleep?
nanosleep(&sleep_time, NULL);
#endif
}
Action *action = new Action;
action->addr = Address(g,status.MPI_SOURCE);
lockMPI("async-iprobe-getcount");
MPI_CALL(Get_count(&status,MPI_BYTE,&action->size));
unlockMPI();
action->data = malloc(action->size);
lockMPI("async-iprobe-irecv");
MPI_CALL(Irecv(action->data,action->size,MPI_BYTE,
status.MPI_SOURCE,status.MPI_TAG,
g->comm,&request[numRequests]));
unlockMPI();
actions[numRequests++] = action;
}
// ... and add all the other ones that are outstanding, up
// to max window size
while (numRequests < RECV_WINDOW_SIZE) {
int msgAvail;
lockMPI("async-iprobe-recv");
MPI_CALL(Iprobe(MPI_ANY_SOURCE,g->tag,g->comm,&msgAvail,&status));
unlockMPI();
if (!msgAvail)
break;
Action *action = new Action;
action->addr = Address(g,status.MPI_SOURCE);
lockMPI("async-batched-getcount");
MPI_CALL(Get_count(&status,MPI_BYTE,&action->size));
unlockMPI();
action->data = malloc(action->size);
lockMPI("async-batched-irecv");
MPI_CALL(Irecv(action->data,action->size,MPI_BYTE,
status.MPI_SOURCE,status.MPI_TAG,
g->comm,&request[numRequests]));
unlockMPI();
actions[numRequests++] = action;
}
// TODO: Is it ok to wait even if we're exiting? Maybe we'd just get send
// failed statuses back?
// now, have certain number of messages available...
lockMPI("async-waitall");
MPI_CALL(Waitall(numRequests,request,MPI_STATUSES_IGNORE));
unlockMPI();
// OK, all actions are valid now
g->recvQueue.putSome(&actions[0],numRequests);
}
}
void BatchedIsendIrecvImpl::ProcThread::run()
{
Group *g = (Group *)this->group;
while (1) {
Action *actions[PROC_WINDOW_SIZE];
size_t numActions = 0;
while (numActions == 0){
numActions = g->recvQueue.getSomeFor(actions,PROC_WINDOW_SIZE,
std::chrono::milliseconds(1));
if (g->shouldExit.load()){
return;
}
}
for (uint32_t i = 0; i < numActions; i++) {
Action *action = actions[i];
g->consumer->process(action->addr,action->data,action->size);
delete action;
}
}
}
void BatchedIsendIrecvImpl::Group::shutdown()
{
if (logMPI) {
std::cout << "#osp:mpi:BatchIsendIrecvMessaging:Group shutting down"
<< std::endl;
}
shouldExit.store(true);
sendThread.handle.join();
recvThread.handle.join();
procThread.handle.join();
}
void BatchedIsendIrecvImpl::init()
{
mpi::world.barrier();
if (logMPI) {
printf("#osp:mpi:BatchedIsendIrecvMessaging started up %i/%i\n",
mpi::world.rank,mpi::world.size);
fflush(0);
}
mpi::world.barrier();
}
void BatchedIsendIrecvImpl::shutdown()
{
mpi::world.barrier();
if (logMPI) {
printf("#osp:mpi:BatchedIsendIrecvMessaging shutting down %i/%i\n",
mpi::world.rank,mpi::world.size);
fflush(0);
}
mpi::world.barrier();
for (uint32_t i = 0; i < myGroups.size(); i++)
myGroups[i]->shutdown();
if (logMPI) {
printf("#osp:mpi:BatchedIsendIrecvMessaging finalizing %i/%i\n",
mpi::world.rank,mpi::world.size);
}
MPI_CALL(Finalize());
}
async::Group *BatchedIsendIrecvImpl::createGroup(MPI_Comm comm,
Consumer *consumer,
int32 tag)
{
assert(consumer);
Group *g = new Group(comm,consumer,tag);
assert(g);
myGroups.push_back(g);
return g;
}
void BatchedIsendIrecvImpl::send(const Address &dest,
void *msgPtr,
int32 msgSize)
{
Action *action = new Action;
action->addr = dest;
action->data = msgPtr;
action->size = msgSize;
Group *g = (Group *)dest.group;
{ std::lock_guard<std::mutex> lock(g->flushMutex);
g->numMessagesAskedToSend++;
}
g->sendQueue.put(action);
}
/*! flushes all outgoing messages. note this currently does NOT
check if there's message incomgin during the flushign ... */
void BatchedIsendIrecvImpl::flush()
{
for (auto g : myGroups) {
assert(g);
g->flush();
}
}
void BatchedIsendIrecvImpl::Group::flush()
{
std::unique_lock<std::mutex> lock(flushMutex);
isFlushedCondition.wait(lock,[&]{
return (numMessagesDoneSending == numMessagesAskedToSend);
});
}
} // ::ospray::mpi::async
} // ::ospray::mpi
} // ::ospray
<commit_msg>working on async recv to not deadlock<commit_after>// ======================================================================== //
// Copyright 2009-2017 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. //
// ======================================================================== //
#ifdef _WIN32
# define WIN32_LEAN_AND_MEAN
# include <windows.h> // for Sleep
#else
# include <time.h>
#endif
#include <chrono>
#include <atomic>
#include <thread>
#include "BatchedIsendIrecvMessaging.h"
namespace ospray {
namespace mpi {
namespace async {
enum { SEND_WINDOW_SIZE = 48 };
enum { RECV_WINDOW_SIZE = 48 };
enum { PROC_WINDOW_SIZE = 20 };
BatchedIsendIrecvImpl::Group::Group(MPI_Comm comm,
Consumer *consumer,
int32 tag)
: async::Group(comm,consumer,tag),
sendThread(this),
procThread(this),
recvThread(this),
shouldExit(false)
{
sendThread.handle = std::thread([this](){this->sendThread.run();});
procThread.handle = std::thread([this](){this->procThread.run();});
recvThread.handle = std::thread([this](){this->recvThread.run();});
}
//using ActiveAction = std::pair<Action*, MPI_Request>;
void BatchedIsendIrecvImpl::SendThread::run()
{
Group *g = this->group;
Action *actions[SEND_WINDOW_SIZE];
MPI_Request request[SEND_WINDOW_SIZE];
int finishedSends[SEND_WINDOW_SIZE];
// Number of outstanding sends in the actions list
int numSends = 0;
while (1) {
// Each iteration try to get some new stuff to send if we have room, and repeatedly try
// if we have no data to send.
if (numSends < SEND_WINDOW_SIZE) {
do {
int numGot = g->sendQueue.getSomeFor(actions + numSends, SEND_WINDOW_SIZE - numSends,
std::chrono::milliseconds(1));
if (g->shouldExit.load()){
return;
}
// New sends are placed at the end of the buffer
for (uint32_t i = numSends; i < numSends + numGot; i++) {
Action *action = actions[i];
lockMPI("async-isend");
MPI_CALL(Isend(action->data,action->size,MPI_BYTE,
action->addr.rank,g->tag,g->comm, &request[i]));
unlockMPI();
}
numSends += numGot;
} while (numSends == 0);
}
// TODO: Is it ok to wait even if we're exiting? Maybe we'd just get send
// failed statuses back?
lockMPI("async-send-testsome");
int numFinished = 0;
MPI_CALL(Testsome(numSends, request, &numFinished, finishedSends, MPI_STATUSES_IGNORE));
unlockMPI();
if (numFinished > 0) {
for (int i = 0; i < numFinished; ++i) {
Action *a = actions[finishedSends[i]];
free(a->data);
delete a;
// Mark the entry as finished so we can partition the arrays
actions[finishedSends[i]] = nullptr;
request[finishedSends[i]] = MPI_REQUEST_NULL;
{ std::lock_guard<std::mutex> lock(g->flushMutex);
g->numMessagesDoneSending++;
if (g->numMessagesDoneSending == g->numMessagesAskedToSend)
g->isFlushedCondition.notify_one();
}
}
// Move finished sends to the end of the respective buffers
std::stable_partition(actions, actions + SEND_WINDOW_SIZE,
[](const Action *a) { return a != nullptr; });
std::stable_partition(request, request + SEND_WINDOW_SIZE,
[](const MPI_Request &r) { return r != MPI_REQUEST_NULL; });
numSends -= numFinished;
}
}
}
void BatchedIsendIrecvImpl::RecvThread::run()
{
// note this thread not only _probes_ for new receives, it
// also immediately starts the receive operation using Irecv()
Group *g = (Group *)this->group;
MPI_Request request[RECV_WINDOW_SIZE];
Action *actions[RECV_WINDOW_SIZE];
MPI_Status status;
int numRequests = 0;
#ifdef _WIN32
const DWORD sleep_time = 1; // ms --> much longer than 150us
#else
const timespec sleep_time = timespec{0, 150000};
#endif
while (1) {
numRequests = 0;
// wait for first message
{
// usleep(280);
int msgAvail = 0;
while (!msgAvail) {
lockMPI("async-iprobe");
MPI_CALL(Iprobe(MPI_ANY_SOURCE,g->tag,g->comm,&msgAvail,&status));
unlockMPI();
if (g->shouldExit.load()){
return;
}
if (msgAvail){
break;
}
#ifdef _WIN32
Sleep(sleep_time);
#else
// TODO: Can we do a CMake feature test for this_thread::sleep_for and
// conditionally use nanosleep?
nanosleep(&sleep_time, NULL);
#endif
}
Action *action = new Action;
action->addr = Address(g,status.MPI_SOURCE);
lockMPI("async-iprobe-getcount");
MPI_CALL(Get_count(&status,MPI_BYTE,&action->size));
unlockMPI();
action->data = malloc(action->size);
lockMPI("async-iprobe-irecv");
MPI_CALL(Irecv(action->data,action->size,MPI_BYTE,
status.MPI_SOURCE,status.MPI_TAG,
g->comm,&request[numRequests]));
unlockMPI();
actions[numRequests++] = action;
}
// ... and add all the other ones that are outstanding, up
// to max window size
while (numRequests < RECV_WINDOW_SIZE) {
int msgAvail;
lockMPI("async-iprobe-recv");
MPI_CALL(Iprobe(MPI_ANY_SOURCE,g->tag,g->comm,&msgAvail,&status));
unlockMPI();
if (!msgAvail)
break;
Action *action = new Action;
action->addr = Address(g,status.MPI_SOURCE);
lockMPI("async-batched-getcount");
MPI_CALL(Get_count(&status,MPI_BYTE,&action->size));
unlockMPI();
action->data = malloc(action->size);
lockMPI("async-batched-irecv");
MPI_CALL(Irecv(action->data,action->size,MPI_BYTE,
status.MPI_SOURCE,status.MPI_TAG,
g->comm,&request[numRequests]));
unlockMPI();
actions[numRequests++] = action;
}
// TODO: Is it ok to wait even if we're exiting? Maybe we'd just get send
// failed statuses back?
// now, have certain number of messages available...
lockMPI("async-waitall");
// TODO: We should be using testsome like the sending code
MPI_CALL(Waitall(numRequests,request,MPI_STATUSES_IGNORE));
unlockMPI();
// OK, all actions are valid now
g->recvQueue.putSome(&actions[0],numRequests);
}
}
void BatchedIsendIrecvImpl::ProcThread::run()
{
Group *g = (Group *)this->group;
while (1) {
Action *actions[PROC_WINDOW_SIZE];
size_t numActions = 0;
while (numActions == 0){
numActions = g->recvQueue.getSomeFor(actions,PROC_WINDOW_SIZE,
std::chrono::milliseconds(1));
if (g->shouldExit.load()){
return;
}
}
for (uint32_t i = 0; i < numActions; i++) {
Action *action = actions[i];
g->consumer->process(action->addr,action->data,action->size);
delete action;
}
}
}
void BatchedIsendIrecvImpl::Group::shutdown()
{
if (logMPI) {
std::cout << "#osp:mpi:BatchIsendIrecvMessaging:Group shutting down"
<< std::endl;
}
shouldExit.store(true);
sendThread.handle.join();
recvThread.handle.join();
procThread.handle.join();
}
void BatchedIsendIrecvImpl::init()
{
mpi::world.barrier();
if (logMPI) {
printf("#osp:mpi:BatchedIsendIrecvMessaging started up %i/%i\n",
mpi::world.rank,mpi::world.size);
fflush(0);
}
mpi::world.barrier();
}
void BatchedIsendIrecvImpl::shutdown()
{
mpi::world.barrier();
if (logMPI) {
printf("#osp:mpi:BatchedIsendIrecvMessaging shutting down %i/%i\n",
mpi::world.rank,mpi::world.size);
fflush(0);
}
mpi::world.barrier();
for (uint32_t i = 0; i < myGroups.size(); i++)
myGroups[i]->shutdown();
if (logMPI) {
printf("#osp:mpi:BatchedIsendIrecvMessaging finalizing %i/%i\n",
mpi::world.rank,mpi::world.size);
}
MPI_CALL(Finalize());
}
async::Group *BatchedIsendIrecvImpl::createGroup(MPI_Comm comm,
Consumer *consumer,
int32 tag)
{
assert(consumer);
Group *g = new Group(comm,consumer,tag);
assert(g);
myGroups.push_back(g);
return g;
}
void BatchedIsendIrecvImpl::send(const Address &dest,
void *msgPtr,
int32 msgSize)
{
Action *action = new Action;
action->addr = dest;
action->data = msgPtr;
action->size = msgSize;
Group *g = (Group *)dest.group;
{ std::lock_guard<std::mutex> lock(g->flushMutex);
g->numMessagesAskedToSend++;
}
g->sendQueue.put(action);
}
/*! flushes all outgoing messages. note this currently does NOT
check if there's message incomgin during the flushign ... */
void BatchedIsendIrecvImpl::flush()
{
for (auto g : myGroups) {
assert(g);
g->flush();
}
}
void BatchedIsendIrecvImpl::Group::flush()
{
std::unique_lock<std::mutex> lock(flushMutex);
isFlushedCondition.wait(lock,[&]{
return (numMessagesDoneSending == numMessagesAskedToSend);
});
}
} // ::ospray::mpi::async
} // ::ospray::mpi
} // ::ospray
<|endoftext|> |
<commit_before>//
// Test Suite for C-API GEOSMinimumWidth
#include <tut.hpp>
// geos
#include <geos_c.h>
// std
#include <cstdarg>
#include <cstdio>
#include <cstdlib>
namespace tut
{
//
// Test Group
//
// Common data used in test cases.
struct test_capigeosminimumwidth_data
{
GEOSGeometry* input_;
GEOSWKTWriter* wktw_;
char* wkt_;
static void notice(const char *fmt, ...)
{
std::fprintf( stdout, "NOTICE: ");
va_list ap;
va_start(ap, fmt);
std::vfprintf(stdout, fmt, ap);
va_end(ap);
std::fprintf(stdout, "\n");
}
test_capigeosminimumwidth_data()
: input_(0), wkt_(0)
{
initGEOS(notice, notice);
wktw_ = GEOSWKTWriter_create();
GEOSWKTWriter_setTrim(wktw_, 1);
GEOSWKTWriter_setRoundingPrecision(wktw_, 8);
}
~test_capigeosminimumwidth_data()
{
GEOSGeom_destroy(input_);
input_ = 0;
GEOSWKTWriter_destroy(wktw_);
GEOSFree(wkt_);
wkt_ = 0;
finishGEOS();
}
};
typedef test_group<test_capigeosminimumwidth_data> group;
typedef group::object object;
group test_capigeosminimumwidth_group("capi::GEOSMinimumWidth");
//
// Test Cases
//
template<>
template<>
void object::test<1>()
{
input_ = GEOSGeomFromWKT("POLYGON ((0 0, 0 15, 5 10, 5 0, 0 0))");
ensure( 0 != input_ );
GEOSGeometry* output = GEOSMinimumWidth(input_);
ensure( 0 != output );
ensure( 0 == GEOSisEmpty(output) );
wkt_ = GEOSWKTWriter_write(wktw_, output);
ensure_equals(std::string(wkt_), std::string( "LINESTRING (0 0, 5 0)"));
GEOSGeom_destroy(output);
}
} // namespace tut
<commit_msg>Add another test for GEOSMinimumWidth<commit_after>//
// Test Suite for C-API GEOSMinimumWidth
#include <tut.hpp>
// geos
#include <geos_c.h>
// std
#include <cstdarg>
#include <cstdio>
#include <cstdlib>
namespace tut
{
//
// Test Group
//
// Common data used in test cases.
struct test_capigeosminimumwidth_data
{
GEOSGeometry* input_;
GEOSWKTWriter* wktw_;
char* wkt_;
static void notice(const char *fmt, ...)
{
std::fprintf( stdout, "NOTICE: ");
va_list ap;
va_start(ap, fmt);
std::vfprintf(stdout, fmt, ap);
va_end(ap);
std::fprintf(stdout, "\n");
}
test_capigeosminimumwidth_data()
: input_(0), wkt_(0)
{
initGEOS(notice, notice);
wktw_ = GEOSWKTWriter_create();
GEOSWKTWriter_setTrim(wktw_, 1);
GEOSWKTWriter_setRoundingPrecision(wktw_, 8);
}
~test_capigeosminimumwidth_data()
{
GEOSGeom_destroy(input_);
input_ = 0;
GEOSWKTWriter_destroy(wktw_);
GEOSFree(wkt_);
wkt_ = 0;
finishGEOS();
}
};
typedef test_group<test_capigeosminimumwidth_data> group;
typedef group::object object;
group test_capigeosminimumwidth_group("capi::GEOSMinimumWidth");
//
// Test Cases
//
template<>
template<>
void object::test<1>()
{
input_ = GEOSGeomFromWKT("POLYGON ((0 0, 0 15, 5 10, 5 0, 0 0))");
ensure( 0 != input_ );
GEOSGeometry* output = GEOSMinimumWidth(input_);
ensure( 0 != output );
ensure( 0 == GEOSisEmpty(output) );
wkt_ = GEOSWKTWriter_write(wktw_, output);
ensure_equals(std::string(wkt_), std::string( "LINESTRING (0 0, 5 0)"));
GEOSGeom_destroy(output);
}
template<>
template<>
void object::test<2>()
{
input_ = GEOSGeomFromWKT("LINESTRING (0 0,0 10, 10 10)");
ensure( 0 != input_ );
GEOSGeometry* output = GEOSMinimumWidth(input_);
ensure( 0 != output );
ensure( 0 == GEOSisEmpty(output) );
wkt_ = GEOSWKTWriter_write(wktw_, output);
ensure_equals(std::string(wkt_), std::string( "LINESTRING (5 5, 0 10)"));
GEOSGeom_destroy(output);
}
} // namespace tut
<|endoftext|> |
<commit_before>/*===========================================================================*\
* *
* OpenMesh *
* Copyright (C) 2001-2011 by Computer Graphics Group, RWTH Aachen *
* www.openmesh.org *
* *
*---------------------------------------------------------------------------*
* This file is part of OpenMesh. *
* *
* OpenMesh is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Lesser General Public License as *
* published by the Free Software Foundation, either version 3 of *
* the License, or (at your option) any later version with the *
* following exceptions: *
* *
* If other files instantiate templates or use macros *
* or inline functions from this file, or you compile this file and *
* link it with other files to produce an executable, this file does *
* not by itself cause the resulting executable to be covered by the *
* GNU Lesser General Public License. This exception does not however *
* invalidate any other reasons why the executable file might be *
* covered by the GNU Lesser General Public License. *
* *
* OpenMesh 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 LesserGeneral Public *
* License along with OpenMesh. If not, *
* see <http://www.gnu.org/licenses/>. *
* *
\*===========================================================================*/
/*===========================================================================*\
* *
* $Revision: 460 $ *
* $Date: 2011-11-16 10:45:08 +0100 (Mi, 16 Nov 2011) $ *
* *
\*===========================================================================*/
/** \file McDecimaterT.cc
*/
//=============================================================================
//
// CLASS McDecimaterT - IMPLEMENTATION
//
//=============================================================================
#define OPENMESH_MULTIPLE_CHOICE_DECIMATER_DECIMATERT_CC
//== INCLUDES =================================================================
#include <OpenMesh/Tools/Decimater/McDecimaterT.hh>
#include <vector>
#if defined(OM_CC_MIPS)
# include <float.h>
#else
# include <cfloat>
#endif
//== NAMESPACE ===============================================================
namespace OpenMesh {
namespace Decimater {
//== IMPLEMENTATION ==========================================================
template<class Mesh>
McDecimaterT<Mesh>::McDecimaterT(Mesh& _mesh) :
BaseDecimaterT<Mesh>(_mesh),
mesh_(_mesh), randomSamples_(10) {
// default properties
mesh_.request_vertex_status();
mesh_.request_halfedge_status();
mesh_.request_edge_status();
mesh_.request_face_status();
mesh_.request_face_normals();
}
//-----------------------------------------------------------------------------
template<class Mesh>
McDecimaterT<Mesh>::~McDecimaterT() {
// default properties
mesh_.release_vertex_status();
mesh_.release_edge_status();
mesh_.release_halfedge_status();
mesh_.release_face_status();
mesh_.release_face_normals();
}
//-----------------------------------------------------------------------------
template<class Mesh>
size_t McDecimaterT<Mesh>::decimate(size_t _n_collapses) {
if (!this->is_initialized())
return 0;
unsigned int n_collapses(0);
while ( n_collapses < _n_collapses) {
// Optimal id and value will be collected during the random sampling
typename Mesh::HalfedgeHandle bestHandle(-1);
double bestEnergy = FLT_MAX;
// Generate random samples for collapses
for ( unsigned int i = 0; i < randomSamples_; ++i) {
// Random halfedge handle
typename Mesh::HalfedgeHandle tmpHandle = typename Mesh::HalfedgeHandle((static_cast<double>(rand()) / RAND_MAX) * (mesh_.n_halfedges()-1) );
// if it is not deleted, we analyse it
if ( ! mesh_.status(tmpHandle).deleted() ) {
CollapseInfo ci(mesh_, tmpHandle);
// Check if legal we analyze the priority of this collapse operation
if (this->is_collapse_legal(ci)) {
double energy = this->collapse_priority(ci);
// Check if the current samples energy is better than any energy before
if ( energy < bestEnergy ) {
bestEnergy = energy;
bestHandle = tmpHandle;
}
} else {
continue;
}
}
}
// Found the best energy?
if ( bestEnergy != FLT_MAX ) {
// setup collapse info
CollapseInfo ci(mesh_, bestHandle);
// check topological correctness AGAIN !
if (!this->is_collapse_legal(ci))
continue;
// pre-processing
this->preprocess_collapse(ci);
// perform collapse
mesh_.collapse(bestHandle);
++n_collapses;
// update triangle normals
typename Mesh::VertexFaceIter vf_it = mesh_.vf_iter(ci.v1);
for (; vf_it; ++vf_it)
if (!mesh_.status(vf_it).deleted())
mesh_.set_normal(vf_it, mesh_.calc_face_normal(vf_it.handle()));
// post-process collapse
this->postprocess_collapse(ci);
}
}
// DON'T do garbage collection here! It's up to the application.
return n_collapses;
}
//-----------------------------------------------------------------------------
template<class Mesh>
size_t McDecimaterT<Mesh>::decimate_to_faces(size_t _nv, size_t _nf) {
if (!this->is_initialized())
return 0;
unsigned int nv = mesh_.n_vertices();
unsigned int nf = mesh_.n_faces();
unsigned int n_collapses(0);
// check if no vertex or face contraints were set
bool contraintsOnly = (_nv == 0) && (_nf == 1);
// check if no legal collapses were found three times in a row
// for the sampled halfedges
bool foundNoLegalCollapsesThrice = false;
// store the last two amount of legal collapses found
int lastLegalCollapses = -1;
int beforeLastLegalCollapses = -1;
while ( !foundNoLegalCollapsesThrice && (_nv < nv) && (_nf < nf) ) {
// Optimal id and value will be collected during the random sampling
typename Mesh::HalfedgeHandle bestHandle(-1);
double bestEnergy = FLT_MAX;
// Generate random samples for collapses
unsigned int legalCollapses = 0;
for ( unsigned int i = 0; i < randomSamples_; ++i) {
// Random halfedge handle
typename Mesh::HalfedgeHandle tmpHandle = typename Mesh::HalfedgeHandle((static_cast<double>(rand()) / RAND_MAX) * (mesh_.n_halfedges()-1) );
// if it is not deleted, we analyse it
if ( ! mesh_.status(tmpHandle).deleted() ) {
CollapseInfo ci(mesh_, tmpHandle);
// Check if legal we analyze the priority of this collapse operation
if (this->is_collapse_legal(ci)) {
++legalCollapses;
double energy = this->collapse_priority(ci);
// Check if the current samples energy is better than any energy before
if ( energy < bestEnergy ) {
bestEnergy = energy;
bestHandle = tmpHandle;
}
} else {
continue;
}
}
}
if (contraintsOnly) {
// check if no legal collapses were found three times in a row
foundNoLegalCollapsesThrice = (beforeLastLegalCollapses == 0) && (lastLegalCollapses == 0) && (legalCollapses == 0);
// store amount of last legal collapses found
beforeLastLegalCollapses = lastLegalCollapses;
lastLegalCollapses = legalCollapses;
}
// Found the best energy?
if ( bestEnergy != FLT_MAX ) {
// setup collapse info
CollapseInfo ci(mesh_, bestHandle);
// check topological correctness AGAIN !
if (!this->is_collapse_legal(ci))
continue;
// adjust complexity in advance (need boundary status)
// One vertex is killed by the collapse
--nv;
// If we are at a boundary, one face is lost,
// otherwise two
if (mesh_.is_boundary(ci.v0v1) || mesh_.is_boundary(ci.v1v0))
--nf;
else
nf -= 2;
// pre-processing
this->preprocess_collapse(ci);
// perform collapse
mesh_.collapse(bestHandle);
++n_collapses;
// update triangle normals
typename Mesh::VertexFaceIter vf_it = mesh_.vf_iter(ci.v1);
for (; vf_it; ++vf_it)
if (!mesh_.status(vf_it).deleted())
mesh_.set_normal(vf_it, mesh_.calc_face_normal(vf_it.handle()));
// post-process collapse
this->postprocess_collapse(ci);
}
}
// DON'T do garbage collection here! It's up to the application.
return n_collapses;
}
//=============================================================================
}// END_NS_MC_DECIMATER
} // END_NS_OPENMESH
//=============================================================================
<commit_msg>added some OpenMP for loops for the generation of samples<commit_after>/*===========================================================================*\
* *
* OpenMesh *
* Copyright (C) 2001-2011 by Computer Graphics Group, RWTH Aachen *
* www.openmesh.org *
* *
*---------------------------------------------------------------------------*
* This file is part of OpenMesh. *
* *
* OpenMesh is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Lesser General Public License as *
* published by the Free Software Foundation, either version 3 of *
* the License, or (at your option) any later version with the *
* following exceptions: *
* *
* If other files instantiate templates or use macros *
* or inline functions from this file, or you compile this file and *
* link it with other files to produce an executable, this file does *
* not by itself cause the resulting executable to be covered by the *
* GNU Lesser General Public License. This exception does not however *
* invalidate any other reasons why the executable file might be *
* covered by the GNU Lesser General Public License. *
* *
* OpenMesh 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 LesserGeneral Public *
* License along with OpenMesh. If not, *
* see <http://www.gnu.org/licenses/>. *
* *
\*===========================================================================*/
/*===========================================================================*\
* *
* $Revision: 460 $ *
* $Date: 2011-11-16 10:45:08 +0100 (Mi, 16 Nov 2011) $ *
* *
\*===========================================================================*/
/** \file McDecimaterT.cc
*/
//=============================================================================
//
// CLASS McDecimaterT - IMPLEMENTATION
//
//=============================================================================
#define OPENMESH_MULTIPLE_CHOICE_DECIMATER_DECIMATERT_CC
//== INCLUDES =================================================================
#include <OpenMesh/Tools/Decimater/McDecimaterT.hh>
#include <vector>
#if defined(OM_CC_MIPS)
# include <float.h>
#else
# include <cfloat>
#endif
#ifdef USE_OPENMP
#include <omp.h>
#endif
//== NAMESPACE ===============================================================
namespace OpenMesh {
namespace Decimater {
//== IMPLEMENTATION ==========================================================
template<class Mesh>
McDecimaterT<Mesh>::McDecimaterT(Mesh& _mesh) :
BaseDecimaterT<Mesh>(_mesh),
mesh_(_mesh), randomSamples_(10) {
// default properties
mesh_.request_vertex_status();
mesh_.request_halfedge_status();
mesh_.request_edge_status();
mesh_.request_face_status();
mesh_.request_face_normals();
}
//-----------------------------------------------------------------------------
template<class Mesh>
McDecimaterT<Mesh>::~McDecimaterT() {
// default properties
mesh_.release_vertex_status();
mesh_.release_edge_status();
mesh_.release_halfedge_status();
mesh_.release_face_status();
mesh_.release_face_normals();
}
//-----------------------------------------------------------------------------
template<class Mesh>
size_t McDecimaterT<Mesh>::decimate(size_t _n_collapses) {
if (!this->is_initialized())
return 0;
unsigned int n_collapses(0);
while ( n_collapses < _n_collapses) {
// Optimal id and value will be collected during the random sampling
typename Mesh::HalfedgeHandle bestHandle(-1);
double bestEnergy = FLT_MAX;
// Generate random samples for collapses
#ifdef USE_OPENMP
#pragma omp parallel for shared(bestEnergy, bestHandle)
#endif
for ( unsigned int i = 0; i < randomSamples_; ++i) {
// Random halfedge handle
typename Mesh::HalfedgeHandle tmpHandle = typename Mesh::HalfedgeHandle((static_cast<double>(rand()) / RAND_MAX) * (mesh_.n_halfedges()-1) );
// if it is not deleted, we analyse it
if ( ! mesh_.status(tmpHandle).deleted() ) {
CollapseInfo ci(mesh_, tmpHandle);
// Check if legal we analyze the priority of this collapse operation
if (this->is_collapse_legal(ci)) {
double energy = this->collapse_priority(ci);
// Check if the current samples energy is better than any energy before
if ( energy < bestEnergy ) {
bestEnergy = energy;
bestHandle = tmpHandle;
}
} else {
continue;
}
}
}
// Found the best energy?
if ( bestEnergy != FLT_MAX ) {
// setup collapse info
CollapseInfo ci(mesh_, bestHandle);
// check topological correctness AGAIN !
if (!this->is_collapse_legal(ci))
continue;
// pre-processing
this->preprocess_collapse(ci);
// perform collapse
mesh_.collapse(bestHandle);
++n_collapses;
// update triangle normals
typename Mesh::VertexFaceIter vf_it = mesh_.vf_iter(ci.v1);
for (; vf_it; ++vf_it)
if (!mesh_.status(vf_it).deleted())
mesh_.set_normal(vf_it, mesh_.calc_face_normal(vf_it.handle()));
// post-process collapse
this->postprocess_collapse(ci);
}
}
// DON'T do garbage collection here! It's up to the application.
return n_collapses;
}
//-----------------------------------------------------------------------------
template<class Mesh>
size_t McDecimaterT<Mesh>::decimate_to_faces(size_t _nv, size_t _nf) {
if (!this->is_initialized())
return 0;
unsigned int nv = mesh_.n_vertices();
unsigned int nf = mesh_.n_faces();
unsigned int n_collapses(0);
// check if no vertex or face contraints were set
bool contraintsOnly = (_nv == 0) && (_nf == 1);
// check if no legal collapses were found three times in a row
// for the sampled halfedges
bool foundNoLegalCollapsesThrice = false;
// store the last two amount of legal collapses found
int lastLegalCollapses = -1;
int beforeLastLegalCollapses = -1;
while ( !foundNoLegalCollapsesThrice && (_nv < nv) && (_nf < nf) ) {
// Optimal id and value will be collected during the random sampling
typename Mesh::HalfedgeHandle bestHandle(-1);
double bestEnergy = FLT_MAX;
// Generate random samples for collapses
unsigned int legalCollapses = 0;
#ifdef USE_OPENMP
#pragma omp parallel for shared(bestEnergy, bestHandle, legalCollapses)
#endif
for ( unsigned int i = 0; i < randomSamples_; ++i) {
// Random halfedge handle
typename Mesh::HalfedgeHandle tmpHandle = typename Mesh::HalfedgeHandle((static_cast<double>(rand()) / RAND_MAX) * (mesh_.n_halfedges()-1) );
// if it is not deleted, we analyse it
if ( ! mesh_.status(tmpHandle).deleted() ) {
CollapseInfo ci(mesh_, tmpHandle);
// Check if legal we analyze the priority of this collapse operation
if (this->is_collapse_legal(ci)) {
++legalCollapses;
double energy = this->collapse_priority(ci);
// Check if the current samples energy is better than any energy before
if ( energy < bestEnergy ) {
bestEnergy = energy;
bestHandle = tmpHandle;
}
} else {
continue;
}
}
}
if (contraintsOnly) {
// check if no legal collapses were found three times in a row
foundNoLegalCollapsesThrice = (beforeLastLegalCollapses == 0) && (lastLegalCollapses == 0) && (legalCollapses == 0);
// store amount of last legal collapses found
beforeLastLegalCollapses = lastLegalCollapses;
lastLegalCollapses = legalCollapses;
}
// Found the best energy?
if ( bestEnergy != FLT_MAX ) {
// setup collapse info
CollapseInfo ci(mesh_, bestHandle);
// check topological correctness AGAIN !
if (!this->is_collapse_legal(ci))
continue;
// adjust complexity in advance (need boundary status)
// One vertex is killed by the collapse
--nv;
// If we are at a boundary, one face is lost,
// otherwise two
if (mesh_.is_boundary(ci.v0v1) || mesh_.is_boundary(ci.v1v0))
--nf;
else
nf -= 2;
// pre-processing
this->preprocess_collapse(ci);
// perform collapse
mesh_.collapse(bestHandle);
++n_collapses;
// update triangle normals
typename Mesh::VertexFaceIter vf_it = mesh_.vf_iter(ci.v1);
for (; vf_it; ++vf_it)
if (!mesh_.status(vf_it).deleted())
mesh_.set_normal(vf_it, mesh_.calc_face_normal(vf_it.handle()));
// post-process collapse
this->postprocess_collapse(ci);
}
}
// DON'T do garbage collection here! It's up to the application.
return n_collapses;
}
//=============================================================================
}// END_NS_MC_DECIMATER
} // END_NS_OPENMESH
//=============================================================================
<|endoftext|> |
<commit_before>#include "sendcoinsentry.h"
#include "ui_sendcoinsentry.h"
#include "guiutil.h"
#include "bitcoinunits.h"
#include "addressbookpage.h"
#include "walletmodel.h"
#include "optionsmodel.h"
#include "addresstablemodel.h"
#include <QApplication>
#include <QClipboard>
SendCoinsEntry::SendCoinsEntry(QWidget *parent) :
QFrame(parent),
ui(new Ui::SendCoinsEntry),
model(0)
{
ui->setupUi(this);
#ifdef Q_WS_MAC
ui->payToLayout->setSpacing(4);
#endif
#if QT_VERSION >= 0x040700
ui->payTo->setPlaceholderText(tr("Enter a Bitcoin address (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)"));
ui->addAsLabel->setPlaceholderText(tr("Enter a label for this address to add it to your address book"));
#endif
setFocusPolicy(Qt::TabFocus);
setFocusProxy(ui->payTo);
GUIUtil::setupAddressWidget(ui->payTo, this);
}
SendCoinsEntry::~SendCoinsEntry()
{
delete ui;
}
void SendCoinsEntry::on_pasteButton_clicked()
{
// Paste text from clipboard into recipient field
ui->payTo->setText(QApplication::clipboard()->text());
}
void SendCoinsEntry::on_addressBookButton_clicked()
{
if(!model)
return;
AddressBookPage dlg(AddressBookPage::ForSending, AddressBookPage::SendingTab, this);
dlg.setModel(model->getAddressTableModel());
if(dlg.exec())
{
ui->payTo->setText(dlg.getReturnValue());
ui->payAmount->setFocus();
}
}
void SendCoinsEntry::on_payTo_textChanged(const QString &address)
{
if(!model)
return;
// Fill in label from address book, if no label is filled in yet
if(ui->addAsLabel->text().isEmpty())
ui->addAsLabel->setText(model->getAddressTableModel()->labelForAddress(address));}
void SendCoinsEntry::setModel(WalletModel *model)
{
this->model = model;
clear();
}
void SendCoinsEntry::setRemoveEnabled(bool enabled)
{
ui->deleteButton->setEnabled(enabled);
}
void SendCoinsEntry::clear()
{
ui->payTo->clear();
ui->addAsLabel->clear();
ui->payAmount->clear();
ui->payTo->setFocus();
if(model && model->getOptionsModel())
{
ui->payAmount->setDisplayUnit(model->getOptionsModel()->getDisplayUnit());
}
}
void SendCoinsEntry::on_deleteButton_clicked()
{
emit removeEntry(this);
}
bool SendCoinsEntry::validate()
{
// Check input validity
bool retval = true;
if(!ui->payAmount->validate())
{
retval = false;
}
else
{
if(ui->payAmount->value() <= 0)
{
// Cannot send 0 coins or less
ui->payAmount->setValid(false);
retval = false;
}
}
if(!ui->payTo->hasAcceptableInput() ||
(model && !model->validateAddress(ui->payTo->text())))
{
ui->payTo->setValid(false);
retval = false;
}
return retval;
}
SendCoinsRecipient SendCoinsEntry::getValue()
{
SendCoinsRecipient rv;
rv.address = ui->payTo->text();
rv.label = ui->addAsLabel->text();
rv.amount = ui->payAmount->value();
return rv;
}
QWidget *SendCoinsEntry::setupTabChain(QWidget *prev)
{
QWidget::setTabOrder(prev, ui->payTo);
QWidget::setTabOrder(ui->payTo, ui->addressBookButton);
QWidget::setTabOrder(ui->addressBookButton, ui->pasteButton);
QWidget::setTabOrder(ui->pasteButton, ui->deleteButton);
QWidget::setTabOrder(ui->deleteButton, ui->addAsLabel);
return ui->payAmount->setupTabChain(ui->addAsLabel);
}
void SendCoinsEntry::setValue(const SendCoinsRecipient &value)
{
ui->payTo->setText(value.address);
ui->addAsLabel->setText(value.label);
ui->payAmount->setValue(value.amount);
}
bool SendCoinsEntry::isClear()
{
return ui->payTo->text().isEmpty();
}
void SendCoinsEntry::setFocus()
{
ui->payTo->setFocus();
}
<commit_msg>Set label when selecting an address that already has a label. Fixes #1080.<commit_after>#include "sendcoinsentry.h"
#include "ui_sendcoinsentry.h"
#include "guiutil.h"
#include "bitcoinunits.h"
#include "addressbookpage.h"
#include "walletmodel.h"
#include "optionsmodel.h"
#include "addresstablemodel.h"
#include <QApplication>
#include <QClipboard>
SendCoinsEntry::SendCoinsEntry(QWidget *parent) :
QFrame(parent),
ui(new Ui::SendCoinsEntry),
model(0)
{
ui->setupUi(this);
#ifdef Q_WS_MAC
ui->payToLayout->setSpacing(4);
#endif
#if QT_VERSION >= 0x040700
ui->payTo->setPlaceholderText(tr("Enter a Bitcoin address (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)"));
ui->addAsLabel->setPlaceholderText(tr("Enter a label for this address to add it to your address book"));
#endif
setFocusPolicy(Qt::TabFocus);
setFocusProxy(ui->payTo);
GUIUtil::setupAddressWidget(ui->payTo, this);
}
SendCoinsEntry::~SendCoinsEntry()
{
delete ui;
}
void SendCoinsEntry::on_pasteButton_clicked()
{
// Paste text from clipboard into recipient field
ui->payTo->setText(QApplication::clipboard()->text());
}
void SendCoinsEntry::on_addressBookButton_clicked()
{
if(!model)
return;
AddressBookPage dlg(AddressBookPage::ForSending, AddressBookPage::SendingTab, this);
dlg.setModel(model->getAddressTableModel());
if(dlg.exec())
{
ui->payTo->setText(dlg.getReturnValue());
ui->payAmount->setFocus();
}
}
void SendCoinsEntry::on_payTo_textChanged(const QString &address)
{
if(!model)
return;
// Fill in label from address book, if address has an associated label
QString associatedLabel = model->getAddressTableModel()->labelForAddress(address);
if(!associatedLabel.isEmpty())
ui->addAsLabel->setText(associatedLabel);
}
void SendCoinsEntry::setModel(WalletModel *model)
{
this->model = model;
clear();
}
void SendCoinsEntry::setRemoveEnabled(bool enabled)
{
ui->deleteButton->setEnabled(enabled);
}
void SendCoinsEntry::clear()
{
ui->payTo->clear();
ui->addAsLabel->clear();
ui->payAmount->clear();
ui->payTo->setFocus();
if(model && model->getOptionsModel())
{
ui->payAmount->setDisplayUnit(model->getOptionsModel()->getDisplayUnit());
}
}
void SendCoinsEntry::on_deleteButton_clicked()
{
emit removeEntry(this);
}
bool SendCoinsEntry::validate()
{
// Check input validity
bool retval = true;
if(!ui->payAmount->validate())
{
retval = false;
}
else
{
if(ui->payAmount->value() <= 0)
{
// Cannot send 0 coins or less
ui->payAmount->setValid(false);
retval = false;
}
}
if(!ui->payTo->hasAcceptableInput() ||
(model && !model->validateAddress(ui->payTo->text())))
{
ui->payTo->setValid(false);
retval = false;
}
return retval;
}
SendCoinsRecipient SendCoinsEntry::getValue()
{
SendCoinsRecipient rv;
rv.address = ui->payTo->text();
rv.label = ui->addAsLabel->text();
rv.amount = ui->payAmount->value();
return rv;
}
QWidget *SendCoinsEntry::setupTabChain(QWidget *prev)
{
QWidget::setTabOrder(prev, ui->payTo);
QWidget::setTabOrder(ui->payTo, ui->addressBookButton);
QWidget::setTabOrder(ui->addressBookButton, ui->pasteButton);
QWidget::setTabOrder(ui->pasteButton, ui->deleteButton);
QWidget::setTabOrder(ui->deleteButton, ui->addAsLabel);
return ui->payAmount->setupTabChain(ui->addAsLabel);
}
void SendCoinsEntry::setValue(const SendCoinsRecipient &value)
{
ui->payTo->setText(value.address);
ui->addAsLabel->setText(value.label);
ui->payAmount->setValue(value.amount);
}
bool SendCoinsEntry::isClear()
{
return ui->payTo->text().isEmpty();
}
void SendCoinsEntry::setFocus()
{
ui->payTo->setFocus();
}
<|endoftext|> |
<commit_before>/* ========================================================================= *
* *
* OpenMesh *
* Copyright (c) 2001-2015, RWTH-Aachen University *
* Department of Computer Graphics and Multimedia *
* All rights reserved. *
* www.openmesh.org *
* *
*---------------------------------------------------------------------------*
* This file is part of OpenMesh. *
*---------------------------------------------------------------------------*
* *
* Redistribution and use in source and binary forms, with or without *
* modification, are permitted provided that the following conditions *
* are met: *
* *
* 1. Redistributions of source code must retain the above copyright notice, *
* this list of conditions and the following disclaimer. *
* *
* 2. Redistributions in binary form must reproduce the above copyright *
* notice, this list of conditions and the following disclaimer in the *
* documentation and/or other materials provided with the distribution. *
* *
* 3. Neither the name of the copyright holder nor the names of its *
* contributors may be used to endorse or promote products derived from *
* this software without specific prior written permission. *
* *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS *
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED *
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A *
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER *
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, *
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, *
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR *
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF *
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING *
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS *
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *
* *
* ========================================================================= */
/*===========================================================================*\
* *
* $Revision$ *
* $Date$ *
* *
\*===========================================================================*/
//=============================================================================
//
// CLASS newClass - IMPLEMENTATION
//
//=============================================================================
//== INCLUDES =================================================================
#include <OpenMesh/Tools/VDPM/ViewingParameters.hh>
#include <iostream>
//== NAMESPACES ===============================================================
namespace OpenMesh {
namespace VDPM {
//== IMPLEMENTATION ==========================================================
ViewingParameters::
ViewingParameters()
{
fovy_ = 45.0f;
aspect_ = 1.0f;
tolerance_square_ = 0.001f;
}
void
ViewingParameters::
update_viewing_configurations()
{
// |a11 a12 a13|-1 | a33a22-a32a23 -(a33a12-a32a13) a23a12-a22a13 |
// |a21 a22 a23| = 1/DET*|-(a33a21-a31a23) a33a11-a31a13 -(a23a11-a21a13)|
// |a31 a32 a33| | a32a21-a31a22 -(a32a11-a31a12) a22a11-a21a12 |
// DET = a11(a33a22-a32a23)-a21(a33a12-a32a13)+a31(a23a12-a22a13)
float invdet;
float a11, a12, a13, a21, a22, a23, a31, a32, a33;
Vec3f inv_rot[3], trans;
a11 = (float) modelview_matrix_[0];
a12 = (float) modelview_matrix_[4];
a13 = (float) modelview_matrix_[8];
trans[0] = (float) modelview_matrix_[12];
a21 = (float) modelview_matrix_[1];
a22 = (float) modelview_matrix_[5];
a23 = (float) modelview_matrix_[9];
trans[1] = (float) modelview_matrix_[13];
a31 = (float) modelview_matrix_[2];
a32 = (float) modelview_matrix_[6];
a33 = (float) modelview_matrix_[10];
trans[2] = (float) modelview_matrix_[14];
invdet=a11*(a33*a22-a32*a23) - a21*(a33*a12-a32*a13) + a31*(a23*a12-a22*a13);
invdet= (float) 1.0/invdet;
(inv_rot[0])[0] = (a33*a22-a32*a23) * invdet;
(inv_rot[0])[1] = -(a33*a12-a32*a13) * invdet;
(inv_rot[0])[2] = (a23*a12-a22*a13) * invdet;
(inv_rot[1])[0] = -(a33*a21-a31*a23) * invdet;
(inv_rot[1])[1] = (a33*a11-a31*a13) * invdet;
(inv_rot[1])[2] = -(a23*a11-a21*a13) * invdet;
(inv_rot[2])[0] = (a32*a21-a31*a22) * invdet;
(inv_rot[2])[1] = -(a32*a11-a31*a12) * invdet;
(inv_rot[2])[2] = (a22*a11-a21*a12) * invdet;
eye_pos_ = - Vec3f(dot(inv_rot[0], trans),
dot(inv_rot[1], trans),
dot(inv_rot[2], trans));
right_dir_ = Vec3f(a11, a12, a13);
up_dir_ = Vec3f(a21, a22, a23);
view_dir_ = - Vec3f(a31, a32, a33);
Vec3f normal[4];
//float aspect = width() / height();
float half_theta = fovy() * 0.5f;
float half_phi = atanf(aspect() * tanf(half_theta));
float sin1 = sinf(half_theta);
float cos1 = cosf(half_theta);
float sin2 = sinf(half_phi);
float cos2 = cosf(half_phi);
normal[0] = cos2 * right_dir_ + sin2 * view_dir_;
normal[1] = -cos1 * up_dir_ - sin1 * view_dir_;
normal[2] = -cos2 * right_dir_ + sin2 * view_dir_;
normal[3] = cos1 * up_dir_ - sin1 * view_dir_;
for (int i=0; i<4; i++)
frustum_plane_[i] = Plane3d(normal[i], eye_pos_);
}
void
ViewingParameters::
PrintOut()
{
std::cout << " ModelView matrix: " << std::endl;
std::cout << " |" << modelview_matrix_[0] << " " << modelview_matrix_[4] << " " << modelview_matrix_[8] << " " << modelview_matrix_[12] << "|" << std::endl;
std::cout << " |" << modelview_matrix_[1] << " " << modelview_matrix_[5] << " " << modelview_matrix_[9] << " " << modelview_matrix_[13] << "|" << std::endl;
std::cout << " |" << modelview_matrix_[2] << " " << modelview_matrix_[6] << " " << modelview_matrix_[10] << " " << modelview_matrix_[14] << "|" << std::endl;
std::cout << " |" << modelview_matrix_[3] << " " << modelview_matrix_[7] << " " << modelview_matrix_[11] << " " << modelview_matrix_[15] << "|" << std::endl;
std::cout << " Fovy: " << fovy_ << std::endl;
std::cout << " Aspect: " << aspect_ << std::endl;
std::cout << " Tolerance^2: " << tolerance_square_ << std::endl;
std::cout << " Eye Pos: " << eye_pos_ << std::endl;
std::cout << " Right dir: " << right_dir_ << std::endl;
std::cout << " Up dir: " << up_dir_ << std::endl;
std::cout << " View dir: " << view_dir_ << std::endl;
}
//=============================================================================
} // namespace VDPM
} // namespace OpenMesh
//=============================================================================
<commit_msg>Workaround for strange compiler error on VS2015 Update 1<commit_after>/* ========================================================================= *
* *
* OpenMesh *
* Copyright (c) 2001-2015, RWTH-Aachen University *
* Department of Computer Graphics and Multimedia *
* All rights reserved. *
* www.openmesh.org *
* *
*---------------------------------------------------------------------------*
* This file is part of OpenMesh. *
*---------------------------------------------------------------------------*
* *
* Redistribution and use in source and binary forms, with or without *
* modification, are permitted provided that the following conditions *
* are met: *
* *
* 1. Redistributions of source code must retain the above copyright notice, *
* this list of conditions and the following disclaimer. *
* *
* 2. Redistributions in binary form must reproduce the above copyright *
* notice, this list of conditions and the following disclaimer in the *
* documentation and/or other materials provided with the distribution. *
* *
* 3. Neither the name of the copyright holder nor the names of its *
* contributors may be used to endorse or promote products derived from *
* this software without specific prior written permission. *
* *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS *
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED *
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A *
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER *
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, *
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, *
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR *
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF *
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING *
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS *
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *
* *
* ========================================================================= */
/*===========================================================================*\
* *
* $Revision$ *
* $Date$ *
* *
\*===========================================================================*/
//=============================================================================
//
// CLASS newClass - IMPLEMENTATION
//
//=============================================================================
//== INCLUDES =================================================================
#include <OpenMesh/Tools/VDPM/ViewingParameters.hh>
#include <iostream>
//== NAMESPACES ===============================================================
namespace OpenMesh {
namespace VDPM {
//== IMPLEMENTATION ==========================================================
ViewingParameters::
ViewingParameters()
{
fovy_ = 45.0f;
aspect_ = 1.0f;
tolerance_square_ = 0.001f;
}
void
ViewingParameters::
update_viewing_configurations()
{
// |a11 a12 a13|-1 | a33a22-a32a23 -(a33a12-a32a13) a23a12-a22a13 |
// |a21 a22 a23| = 1/DET*|-(a33a21-a31a23) a33a11-a31a13 -(a23a11-a21a13)|
// |a31 a32 a33| | a32a21-a31a22 -(a32a11-a31a12) a22a11-a21a12 |
// DET = a11(a33a22-a32a23)-a21(a33a12-a32a13)+a31(a23a12-a22a13)
float invdet;
float a11, a12, a13, a21, a22, a23, a31, a32, a33;
Vec3f trans;
// Workaround for internal compiler error on Visual Studio 2015 Update 1
#if (_MSC_VER >= 1900 )
Vec3f inv_rot[3]{ {},{},{} };
Vec3f normal[4]{ {},{},{},{} };
#else
Vec3f inv_rot[3];
Vec3f normal[4];
#endif
a11 = (float) modelview_matrix_[0];
a12 = (float) modelview_matrix_[4];
a13 = (float) modelview_matrix_[8];
trans[0] = (float) modelview_matrix_[12];
a21 = (float) modelview_matrix_[1];
a22 = (float) modelview_matrix_[5];
a23 = (float) modelview_matrix_[9];
trans[1] = (float) modelview_matrix_[13];
a31 = (float) modelview_matrix_[2];
a32 = (float) modelview_matrix_[6];
a33 = (float) modelview_matrix_[10];
trans[2] = (float) modelview_matrix_[14];
invdet = a11*(a33*a22-a32*a23) - a21*(a33*a12-a32*a13) + a31*(a23*a12-a22*a13);
invdet= (float) 1.0/invdet;
(inv_rot[0])[0] = (a33*a22-a32*a23) * invdet;
(inv_rot[0])[1] = -(a33*a12-a32*a13) * invdet;
(inv_rot[0])[2] = (a23*a12-a22*a13) * invdet;
(inv_rot[1])[0] = -(a33*a21-a31*a23) * invdet;
(inv_rot[1])[1] = (a33*a11-a31*a13) * invdet;
(inv_rot[1])[2] = -(a23*a11-a21*a13) * invdet;
(inv_rot[2])[0] = (a32*a21-a31*a22) * invdet;
(inv_rot[2])[1] = -(a32*a11-a31*a12) * invdet;
(inv_rot[2])[2] = (a22*a11-a21*a12) * invdet;
eye_pos_ = - Vec3f(dot(inv_rot[0], trans),
dot(inv_rot[1], trans),
dot(inv_rot[2], trans));
right_dir_ = Vec3f(a11, a12, a13);
up_dir_ = Vec3f(a21, a22, a23);
view_dir_ = - Vec3f(a31, a32, a33);
//float aspect = width() / height();
const float half_theta = fovy() * 0.5f;
const float half_phi = atanf(aspect() * tanf(half_theta));
const float sin1 = sinf(half_theta);
const float cos1 = cosf(half_theta);
const float sin2 = sinf(half_phi);
const float cos2 = cosf(half_phi);
normal[0] = cos2 * right_dir_ + sin2 * view_dir_;
normal[1] = -cos1 * up_dir_ - sin1 * view_dir_;
normal[2] = -cos2 * right_dir_ + sin2 * view_dir_;
normal[3] = cos1 * up_dir_ - sin1 * view_dir_;
for (int i=0; i<4; i++)
frustum_plane_[i] = Plane3d(normal[i], eye_pos_);
}
void
ViewingParameters::
PrintOut()
{
std::cout << " ModelView matrix: " << std::endl;
std::cout << " |" << modelview_matrix_[0] << " " << modelview_matrix_[4] << " " << modelview_matrix_[8] << " " << modelview_matrix_[12] << "|" << std::endl;
std::cout << " |" << modelview_matrix_[1] << " " << modelview_matrix_[5] << " " << modelview_matrix_[9] << " " << modelview_matrix_[13] << "|" << std::endl;
std::cout << " |" << modelview_matrix_[2] << " " << modelview_matrix_[6] << " " << modelview_matrix_[10] << " " << modelview_matrix_[14] << "|" << std::endl;
std::cout << " |" << modelview_matrix_[3] << " " << modelview_matrix_[7] << " " << modelview_matrix_[11] << " " << modelview_matrix_[15] << "|" << std::endl;
std::cout << " Fovy: " << fovy_ << std::endl;
std::cout << " Aspect: " << aspect_ << std::endl;
std::cout << " Tolerance^2: " << tolerance_square_ << std::endl;
std::cout << " Eye Pos: " << eye_pos_ << std::endl;
std::cout << " Right dir: " << right_dir_ << std::endl;
std::cout << " Up dir: " << up_dir_ << std::endl;
std::cout << " View dir: " << view_dir_ << std::endl;
}
//=============================================================================
} // namespace VDPM
} // namespace OpenMesh
//=============================================================================
<|endoftext|> |
<commit_before>/*
Now playing... presence plugin
Copyright (C) 2011 Martin Klapetek <[email protected]>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "telepathy-mpris.h"
#include <QDBusConnectionInterface>
#include <QDBusInterface>
#include <QDBusReply>
#include <QVariant>
#include <KDebug>
#include <TelepathyQt4/AccountSet>
#include <KSharedConfig>
#include <KConfigGroup>
#include "global-presence.h"
TelepathyMPRIS::TelepathyMPRIS(GlobalPresence* globalPresence, QObject* parent)
: TelepathyKDEDModulePlugin(globalPresence, parent)
{
setPluginPriority(50);
//read settings and detect players if plugin is enabled
onSettingsChanged();
//watch for new mpris-enabled players
connect(QDBusConnection::sessionBus().interface(), SIGNAL(serviceOwnerChanged(QString,QString,QString)),
this, SLOT(serviceOwnerChanged(QString,QString,QString)));
}
TelepathyMPRIS::~TelepathyMPRIS()
{
}
void TelepathyMPRIS::onPlayerSignalReceived(const QString &interface, const QVariantMap &changedProperties, const QStringList &invalidatedProperties)
{
Q_UNUSED(interface)
Q_UNUSED(invalidatedProperties)
//if the plugin is disabled, no point in parsing the received signal
if (!isEnabled()) {
return;
}
QString artist;
QString title;
QString album;
//FIXME We can do less lame parsing...maybe.
Q_FOREACH (const QVariant &property, changedProperties.values()) {
if (property.canConvert<QDBusArgument>()) {
QDBusArgument g = property.value<QDBusArgument>();
QMap<QString, QVariant> k = qdbus_cast<QMap<QString, QVariant> >(g);
title = k.value(QLatin1String("xesam:title")).toString();
artist = k.value(QLatin1String("xesam:artist")).toString();
album = k.value(QLatin1String("xesam:album")).toString();
//we got what we need, bail out
break;
}
if (property.canConvert<QString>()) {
if (property.toString() == QLatin1String("Paused") || property.toString() == QLatin1String("Stopped")) {
setActive(false);
return;
}
if (property.toString() == QLatin1String("Playing")) {
QStringList mprisServices = QDBusConnection::sessionBus().interface()->registeredServiceNames().value().filter(QLatin1String("org.mpris.MediaPlayer2"));
Q_FOREACH (const QString &service, mprisServices) {
QDBusInterface mprisInterface(service, QLatin1String("/org/mpris/MediaPlayer2"), QLatin1String("org.mpris.MediaPlayer2.Player"));
if (mprisInterface.property("PlaybackStatus") == QLatin1String("Playing")) {
QMap<QString, QVariant> metadata = mprisInterface.property("Metadata").toMap();
artist = metadata.value(QLatin1String("xesam:artist")).toString();
title = metadata.value(QLatin1String("xesam:title")).toString();
album = metadata.value(QLatin1String("xesam:album")).toString();
break;
}
}
}
}
}
Tp::Presence currentPresence = m_globalPresence->currentPresence();
Tp::SimplePresence presence;
presence.type = currentPresence.type();
presence.status = currentPresence.status();
presence.statusMessage = QString(QLatin1String("Now listening to %1 by %2 from album %3")).arg(title, artist, album);
setRequestedPresence(Tp::Presence(presence));
setActive(true);
}
void TelepathyMPRIS::detectPlayers()
{
QDBusConnectionInterface *i = QDBusConnection::sessionBus().interface();
QStringList mprisServices = i->registeredServiceNames().value().filter(QLatin1String("org.mpris.MediaPlayer2"));
QStringList players;
Q_FOREACH (const QString &service, mprisServices) {
kDebug() << "Found mpris service:" << service;
QDBusInterface mprisInterface(service, QLatin1String("/org/mpris/MediaPlayer2"), QLatin1String("org.mpris.MediaPlayer2.Player"));
if (mprisInterface.property("PlaybackStatus") == QLatin1String("Playing")) {
QVariantMap m;
m.insert(QLatin1String("PlaybackStatus"), QVariant(QLatin1String("Playing")));
onPlayerSignalReceived(QString(), m, QStringList());
}
//check if we are already watching this service
if (!m_knownPlayers.contains(service)) {
QDBusConnection::sessionBus().connect(
service,
QLatin1String("/org/mpris/MediaPlayer2"),
QLatin1String("org.freedesktop.DBus.Properties"),
QLatin1String("PropertiesChanged"),
this,
SLOT(onPlayerSignalReceived(const QString&, const QVariantMap&, const QStringList& )) );
}
players.append(service);
}
//this gets rid of removed services and stores only those currently present
m_knownPlayers = players;
}
void TelepathyMPRIS::onSettingsChanged()
{
KSharedConfigPtr config = KSharedConfig::openConfig(QLatin1String("ktelepathyrc"));
KConfigGroup kdedConfig = config->group("KDED");
bool pluginEnabled = kdedConfig.readEntry("nowPlayingEnabled", true);
//if the plugin was enabled and is now disabled
if (isEnabled() && !pluginEnabled) {
setEnabled(false);
return;
}
//if the plugin was disabled and is now enabled
if (!isEnabled() && pluginEnabled) {
setEnabled(true);
detectPlayers();
}
}
void TelepathyMPRIS::serviceOwnerChanged(const QString& a, const QString& b, const QString& c)
{
if (a.contains(QLatin1String("org.mpris.MediaPlayer2"))) {
kDebug() << "Found new mpris interface, running detection...";
detectPlayers();
}
}
<commit_msg>Add a check for empty metadata being sent by the media player after the playlist finishes (read: Amarok now works with 'Now playing..' plugin)<commit_after>/*
Now playing... presence plugin
Copyright (C) 2011 Martin Klapetek <[email protected]>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "telepathy-mpris.h"
#include <QDBusConnectionInterface>
#include <QDBusInterface>
#include <QDBusReply>
#include <QVariant>
#include <KDebug>
#include <TelepathyQt4/AccountSet>
#include <KSharedConfig>
#include <KConfigGroup>
#include "global-presence.h"
TelepathyMPRIS::TelepathyMPRIS(GlobalPresence* globalPresence, QObject* parent)
: TelepathyKDEDModulePlugin(globalPresence, parent)
{
setPluginPriority(50);
//read settings and detect players if plugin is enabled
onSettingsChanged();
//watch for new mpris-enabled players
connect(QDBusConnection::sessionBus().interface(), SIGNAL(serviceOwnerChanged(QString,QString,QString)),
this, SLOT(serviceOwnerChanged(QString,QString,QString)));
}
TelepathyMPRIS::~TelepathyMPRIS()
{
}
void TelepathyMPRIS::onPlayerSignalReceived(const QString &interface, const QVariantMap &changedProperties, const QStringList &invalidatedProperties)
{
Q_UNUSED(interface)
Q_UNUSED(invalidatedProperties)
//if the plugin is disabled, no point in parsing the received signal
if (!isEnabled()) {
return;
}
bool trackInfoFound = false;
QString artist;
QString title;
QString album;
//FIXME We can do less lame parsing...maybe.
Q_FOREACH (const QVariant &property, changedProperties.values()) {
//if we're dealing with track's metadata
if (property.canConvert<QDBusArgument>() && changedProperties.key(property) == QLatin1String("Metadata")) {
QDBusArgument g = property.value<QDBusArgument>();
QMap<QString, QVariant> k = qdbus_cast<QMap<QString, QVariant> >(g);
//amarok sends empty metadata after the playlist has finished, so let's make sure we won't use them
if (k.isEmpty()) {
break;
}
title = k.value(QLatin1String("xesam:title")).toString();
artist = k.value(QLatin1String("xesam:artist")).toString();
album = k.value(QLatin1String("xesam:album")).toString();
trackInfoFound = true;
//we got what we need, bail out
break;
}
if (property.canConvert<QString>()) {
if (property.toString() == QLatin1String("Paused") || property.toString() == QLatin1String("Stopped")) {
setActive(false);
return;
}
if (property.toString() == QLatin1String("Playing")) {
QStringList mprisServices = QDBusConnection::sessionBus().interface()->registeredServiceNames().value().filter(QLatin1String("org.mpris.MediaPlayer2"));
Q_FOREACH (const QString &service, mprisServices) {
QDBusInterface mprisInterface(service, QLatin1String("/org/mpris/MediaPlayer2"), QLatin1String("org.mpris.MediaPlayer2.Player"));
if (mprisInterface.property("PlaybackStatus") == QLatin1String("Playing")) {
QMap<QString, QVariant> metadata = mprisInterface.property("Metadata").toMap();
if (metadata.isEmpty()) {
break;
}
artist = metadata.value(QLatin1String("xesam:artist")).toString();
title = metadata.value(QLatin1String("xesam:title")).toString();
album = metadata.value(QLatin1String("xesam:album")).toString();
trackInfoFound = true;
break;
}
}
}
}
}
if (trackInfoFound) {
Tp::Presence currentPresence = m_globalPresence->currentPresence();
Tp::SimplePresence presence;
presence.type = currentPresence.type();
presence.status = currentPresence.status();
presence.statusMessage = QString(QLatin1String("Now listening to %1 by %2 from album %3")).arg(title, artist, album);
setRequestedPresence(Tp::Presence(presence));
setActive(true);
} else {
setActive(false);
}
}
void TelepathyMPRIS::detectPlayers()
{
QDBusConnectionInterface *i = QDBusConnection::sessionBus().interface();
QStringList mprisServices = i->registeredServiceNames().value().filter(QLatin1String("org.mpris.MediaPlayer2"));
QStringList players;
Q_FOREACH (const QString &service, mprisServices) {
kDebug() << "Found mpris service:" << service;
QDBusInterface mprisInterface(service, QLatin1String("/org/mpris/MediaPlayer2"), QLatin1String("org.mpris.MediaPlayer2.Player"));
if (mprisInterface.property("PlaybackStatus") == QLatin1String("Playing")) {
QVariantMap m;
m.insert(QLatin1String("PlaybackStatus"), QVariant(QLatin1String("Playing")));
onPlayerSignalReceived(QString(), m, QStringList());
}
//check if we are already watching this service
if (!m_knownPlayers.contains(service)) {
QDBusConnection::sessionBus().connect(
service,
QLatin1String("/org/mpris/MediaPlayer2"),
QLatin1String("org.freedesktop.DBus.Properties"),
QLatin1String("PropertiesChanged"),
this,
SLOT(onPlayerSignalReceived(const QString&, const QVariantMap&, const QStringList& )) );
}
players.append(service);
}
//this gets rid of removed services and stores only those currently present
m_knownPlayers = players;
}
void TelepathyMPRIS::onSettingsChanged()
{
KSharedConfigPtr config = KSharedConfig::openConfig(QLatin1String("ktelepathyrc"));
KConfigGroup kdedConfig = config->group("KDED");
bool pluginEnabled = kdedConfig.readEntry("nowPlayingEnabled", true);
//if the plugin was enabled and is now disabled
if (isEnabled() && !pluginEnabled) {
setEnabled(false);
return;
}
//if the plugin was disabled and is now enabled
if (!isEnabled() && pluginEnabled) {
setEnabled(true);
detectPlayers();
}
}
void TelepathyMPRIS::serviceOwnerChanged(const QString& a, const QString& b, const QString& c)
{
if (a.contains(QLatin1String("org.mpris.MediaPlayer2"))) {
kDebug() << "Found new mpris interface, running detection...";
detectPlayers();
}
}
<|endoftext|> |
<commit_before><commit_msg>clear redraw needed flag<commit_after><|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: BResultSetMetaData.cxx,v $
*
* $Revision: 1.1.1.1 $
*
* last change: $Author: hr $ $Date: 2000-09-18 16:14:20 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _CONNECTIVITY_ADABAS_BRESULTSETMETADATA_HXX_
#include "adabas/BResultSetMetaData.hxx"
#endif
#ifndef _CONNECTIVITY_OTOOLS_HXX_
#include "adabas/BTools.hxx"
#endif
using namespace connectivity::adabas;
// -------------------------------------------------------------------------
OResultSetMetaData::~OResultSetMetaData()
{
}
// -------------------------------------------------------------------------
::rtl::OUString OResultSetMetaData::getCharColAttrib(sal_Int32 _column,sal_Int32 ident) throw(starsdbc::SQLException, staruno::RuntimeException)
{
sal_Int32 column = _column;
if(_column < m_vMapping.size()) // use mapping
column = m_vMapping[_column];
sal_Int32 BUFFER_LEN = 128;
char *pName = new char[BUFFER_LEN];
SQLSMALLINT nRealLen=0;
OTools::ThrowException(N3SQLColAttribute(m_aStatementHandle,
column,
ident,
(SQLPOINTER)pName,
BUFFER_LEN,
&nRealLen,
NULL
),m_aStatementHandle,SQL_HANDLE_STMT,*this);
if(nRealLen > BUFFER_LEN)
{
delete pName;
pName = new char[nRealLen];
OTools::ThrowException(N3SQLColAttribute(m_aStatementHandle,
column,
ident,
(SQLPOINTER)pName,
nRealLen,
&nRealLen,
NULL
),m_aStatementHandle,SQL_HANDLE_STMT,*this);
}
return ::rtl::OUString::createFromAscii(pName);
}
// -------------------------------------------------------------------------
sal_Int32 OResultSetMetaData::getNumColAttrib(sal_Int32 _column,sal_Int32 ident) throw(starsdbc::SQLException, staruno::RuntimeException)
{
sal_Int32 column = _column;
if(_column < m_vMapping.size()) // use mapping
column = m_vMapping[_column];
sal_Int32 nValue;
OTools::ThrowException(N3SQLColAttribute(m_aStatementHandle,
column,
ident,
NULL,
0,
NULL,
&nValue),m_aStatementHandle,SQL_HANDLE_STMT,*this);
return nValue;
}
// -------------------------------------------------------------------------
sal_Int32 SAL_CALL OResultSetMetaData::getColumnDisplaySize( sal_Int32 column ) throw(starsdbc::SQLException, staruno::RuntimeException)
{
return getNumColAttrib(column,SQL_DESC_DISPLAY_SIZE);
}
// -------------------------------------------------------------------------
sal_Int32 SAL_CALL OResultSetMetaData::getColumnType( sal_Int32 column ) throw(starsdbc::SQLException, staruno::RuntimeException)
{
return OTools::MapOdbcType2Jdbc(getNumColAttrib(column,SQL_DESC_TYPE));
}
// -------------------------------------------------------------------------
sal_Int32 SAL_CALL OResultSetMetaData::getColumnCount( ) throw(starsdbc::SQLException, staruno::RuntimeException)
{
if(m_nColCount != -1)
return m_nColCount;
sal_Int16 nNumResultCols=0;
OTools::ThrowException(N3SQLNumResultCols(m_aStatementHandle,&nNumResultCols),m_aStatementHandle,SQL_HANDLE_STMT,*this);
return m_nColCount = nNumResultCols;
}
// -------------------------------------------------------------------------
sal_Bool SAL_CALL OResultSetMetaData::isCaseSensitive( sal_Int32 column ) throw(starsdbc::SQLException, staruno::RuntimeException)
{
return getNumColAttrib(column,SQL_DESC_CASE_SENSITIVE) == SQL_TRUE;
}
// -------------------------------------------------------------------------
::rtl::OUString SAL_CALL OResultSetMetaData::getSchemaName( sal_Int32 column ) throw(starsdbc::SQLException, staruno::RuntimeException)
{
return getCharColAttrib(column,SQL_DESC_SCHEMA_NAME);
}
// -------------------------------------------------------------------------
::rtl::OUString SAL_CALL OResultSetMetaData::getColumnName( sal_Int32 column ) throw(starsdbc::SQLException, staruno::RuntimeException)
{
return getCharColAttrib(column,SQL_DESC_NAME);
}
// -------------------------------------------------------------------------
::rtl::OUString SAL_CALL OResultSetMetaData::getTableName( sal_Int32 column ) throw(starsdbc::SQLException, staruno::RuntimeException)
{
return getCharColAttrib(column,SQL_DESC_TABLE_NAME);
}
// -------------------------------------------------------------------------
::rtl::OUString SAL_CALL OResultSetMetaData::getCatalogName( sal_Int32 column ) throw(starsdbc::SQLException, staruno::RuntimeException)
{
return getCharColAttrib(column,SQL_DESC_CATALOG_NAME);
}
// -------------------------------------------------------------------------
::rtl::OUString SAL_CALL OResultSetMetaData::getColumnTypeName( sal_Int32 column ) throw(starsdbc::SQLException, staruno::RuntimeException)
{
return getCharColAttrib(column,SQL_DESC_TYPE_NAME
);
}
// -------------------------------------------------------------------------
::rtl::OUString SAL_CALL OResultSetMetaData::getColumnLabel( sal_Int32 column ) throw(starsdbc::SQLException, staruno::RuntimeException)
{
return getCharColAttrib(column,SQL_DESC_LABEL);
}
// -------------------------------------------------------------------------
::rtl::OUString SAL_CALL OResultSetMetaData::getColumnServiceName( sal_Int32 column ) throw(starsdbc::SQLException, staruno::RuntimeException)
{
return ::rtl::OUString();
}
// -------------------------------------------------------------------------
sal_Bool SAL_CALL OResultSetMetaData::isCurrency( sal_Int32 column ) throw(starsdbc::SQLException, staruno::RuntimeException)
{
return getNumColAttrib(column,SQL_DESC_FIXED_PREC_SCALE) == SQL_TRUE;
}
// -------------------------------------------------------------------------
sal_Bool SAL_CALL OResultSetMetaData::isAutoIncrement( sal_Int32 column ) throw(starsdbc::SQLException, staruno::RuntimeException)
{
return getNumColAttrib(column,SQL_DESC_AUTO_UNIQUE_VALUE) == SQL_TRUE;
}
// -------------------------------------------------------------------------
sal_Bool SAL_CALL OResultSetMetaData::isSigned( sal_Int32 column ) throw(starsdbc::SQLException, staruno::RuntimeException)
{
return getNumColAttrib(column,SQL_DESC_UNSIGNED) == SQL_FALSE;
}
// -------------------------------------------------------------------------
sal_Int32 SAL_CALL OResultSetMetaData::getPrecision( sal_Int32 column ) throw(starsdbc::SQLException, staruno::RuntimeException)
{
return getNumColAttrib(column,SQL_DESC_PRECISION);
}
sal_Int32 SAL_CALL OResultSetMetaData::getScale( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException)
{
return getNumColAttrib(column,SQL_DESC_SCALE);
}
// -------------------------------------------------------------------------
sal_Int32 SAL_CALL OResultSetMetaData::isNullable( sal_Int32 column ) throw(starsdbc::SQLException, staruno::RuntimeException)
{
return getNumColAttrib(column,SQL_DESC_NULLABLE) == SQL_NULLABLE;
}
// -------------------------------------------------------------------------
sal_Bool SAL_CALL OResultSetMetaData::isSearchable( sal_Int32 column ) throw(starsdbc::SQLException, staruno::RuntimeException)
{
return getNumColAttrib(column,SQL_DESC_SEARCHABLE) != SQL_PRED_NONE;
}
// -------------------------------------------------------------------------
sal_Bool SAL_CALL OResultSetMetaData::isReadOnly( sal_Int32 column ) throw(starsdbc::SQLException, staruno::RuntimeException)
{
return getNumColAttrib(column,SQL_DESC_UPDATABLE) == SQL_ATTR_READONLY;
}
// -------------------------------------------------------------------------
sal_Bool SAL_CALL OResultSetMetaData::isDefinitelyWritable( sal_Int32 column ) throw(starsdbc::SQLException, staruno::RuntimeException)
{
return getNumColAttrib(column,SQL_DESC_UPDATABLE) == SQL_ATTR_WRITE;
;
}
// -------------------------------------------------------------------------
sal_Bool SAL_CALL OResultSetMetaData::isWritable( sal_Int32 column ) throw(starsdbc::SQLException, staruno::RuntimeException)
{
return getNumColAttrib(column,SQL_DESC_UPDATABLE) == SQL_ATTR_WRITE;
}
// -------------------------------------------------------------------------
<commit_msg>typing<commit_after>/*************************************************************************
*
* $RCSfile: BResultSetMetaData.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: oj $ $Date: 2001-04-25 06:07: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 _CONNECTIVITY_ADABAS_BRESULTSETMETADATA_HXX_
#include "adabas/BResultSetMetaData.hxx"
#endif
#ifndef _CONNECTIVITY_OTOOLS_HXX_
#include "adabas/BTools.hxx"
#endif
using namespace connectivity::adabas;
// -------------------------------------------------------------------------
OResultSetMetaData::~OResultSetMetaData()
{
}
// -------------------------------------------------------------------------
::rtl::OUString OResultSetMetaData::getCharColAttrib(sal_Int32 _column,sal_Int32 ident) throw(starsdbc::SQLException, staruno::RuntimeException)
{
sal_Int32 column = _column;
if(_column < m_vMapping.size()) // use mapping
column = m_vMapping[_column];
sal_Int32 BUFFER_LEN = 128;
char *pName = new char[BUFFER_LEN];
SQLSMALLINT nRealLen=0;
OTools::ThrowException(N3SQLColAttribute(m_aStatementHandle,
column,
ident,
(SQLPOINTER)pName,
BUFFER_LEN,
&nRealLen,
NULL
),m_aStatementHandle,SQL_HANDLE_STMT,*this);
if(nRealLen > BUFFER_LEN)
{
delete pName;
pName = new char[nRealLen];
OTools::ThrowException(N3SQLColAttribute(m_aStatementHandle,
column,
ident,
(SQLPOINTER)pName,
nRealLen,
&nRealLen,
NULL
),m_aStatementHandle,SQL_HANDLE_STMT,*this);
}
return ::rtl::OUString::createFromAscii(pName);
}
// -------------------------------------------------------------------------
sal_Int32 OResultSetMetaData::getNumColAttrib(sal_Int32 _column,sal_Int32 ident) throw(starsdbc::SQLException, staruno::RuntimeException)
{
sal_Int32 column = _column;
if(_column < m_vMapping.size()) // use mapping
column = m_vMapping[_column];
sal_Int32 nValue;
OTools::ThrowException(N3SQLColAttribute(m_aStatementHandle,
column,
ident,
NULL,
0,
NULL,
&nValue),m_aStatementHandle,SQL_HANDLE_STMT,*this);
return nValue;
}
// -------------------------------------------------------------------------
sal_Int32 SAL_CALL OResultSetMetaData::getColumnDisplaySize( sal_Int32 column ) throw(starsdbc::SQLException, staruno::RuntimeException)
{
return getNumColAttrib(column,SQL_DESC_DISPLAY_SIZE);
}
// -------------------------------------------------------------------------
sal_Int32 SAL_CALL OResultSetMetaData::getColumnType( sal_Int32 column ) throw(starsdbc::SQLException, staruno::RuntimeException)
{
return OTools::MapOdbcType2Jdbc(getNumColAttrib(column,SQL_DESC_TYPE));
}
// -------------------------------------------------------------------------
sal_Int32 SAL_CALL OResultSetMetaData::getColumnCount( ) throw(starsdbc::SQLException, staruno::RuntimeException)
{
if(m_nColCount != -1)
return m_nColCount;
sal_Int16 nNumResultCols=0;
OTools::ThrowException(N3SQLNumResultCols(m_aStatementHandle,&nNumResultCols),m_aStatementHandle,SQL_HANDLE_STMT,*this);
return m_nColCount = nNumResultCols;
}
// -------------------------------------------------------------------------
sal_Bool SAL_CALL OResultSetMetaData::isCaseSensitive( sal_Int32 column ) throw(starsdbc::SQLException, staruno::RuntimeException)
{
return getNumColAttrib(column,SQL_DESC_CASE_SENSITIVE) == SQL_TRUE;
}
// -------------------------------------------------------------------------
::rtl::OUString SAL_CALL OResultSetMetaData::getSchemaName( sal_Int32 column ) throw(starsdbc::SQLException, staruno::RuntimeException)
{
return getCharColAttrib(column,SQL_DESC_SCHEMA_NAME);
}
// -------------------------------------------------------------------------
::rtl::OUString SAL_CALL OResultSetMetaData::getColumnName( sal_Int32 column ) throw(starsdbc::SQLException, staruno::RuntimeException)
{
return getCharColAttrib(column,SQL_DESC_NAME);
}
// -------------------------------------------------------------------------
::rtl::OUString SAL_CALL OResultSetMetaData::getTableName( sal_Int32 column ) throw(starsdbc::SQLException, staruno::RuntimeException)
{
return getCharColAttrib(column,SQL_DESC_TABLE_NAME);
}
// -------------------------------------------------------------------------
::rtl::OUString SAL_CALL OResultSetMetaData::getCatalogName( sal_Int32 column ) throw(starsdbc::SQLException, staruno::RuntimeException)
{
return getCharColAttrib(column,SQL_DESC_CATALOG_NAME);
}
// -------------------------------------------------------------------------
::rtl::OUString SAL_CALL OResultSetMetaData::getColumnTypeName( sal_Int32 column ) throw(starsdbc::SQLException, staruno::RuntimeException)
{
return getCharColAttrib(column,SQL_DESC_TYPE_NAME);
}
// -------------------------------------------------------------------------
::rtl::OUString SAL_CALL OResultSetMetaData::getColumnLabel( sal_Int32 column ) throw(starsdbc::SQLException, staruno::RuntimeException)
{
return getCharColAttrib(column,SQL_DESC_LABEL);
}
// -------------------------------------------------------------------------
::rtl::OUString SAL_CALL OResultSetMetaData::getColumnServiceName( sal_Int32 column ) throw(starsdbc::SQLException, staruno::RuntimeException)
{
return ::rtl::OUString();
}
// -------------------------------------------------------------------------
sal_Bool SAL_CALL OResultSetMetaData::isCurrency( sal_Int32 column ) throw(starsdbc::SQLException, staruno::RuntimeException)
{
return getNumColAttrib(column,SQL_DESC_FIXED_PREC_SCALE) == SQL_TRUE;
}
// -------------------------------------------------------------------------
sal_Bool SAL_CALL OResultSetMetaData::isAutoIncrement( sal_Int32 column ) throw(starsdbc::SQLException, staruno::RuntimeException)
{
return getNumColAttrib(column,SQL_DESC_AUTO_UNIQUE_VALUE) == SQL_TRUE;
}
// -------------------------------------------------------------------------
sal_Bool SAL_CALL OResultSetMetaData::isSigned( sal_Int32 column ) throw(starsdbc::SQLException, staruno::RuntimeException)
{
return getNumColAttrib(column,SQL_DESC_UNSIGNED) == SQL_FALSE;
}
// -------------------------------------------------------------------------
sal_Int32 SAL_CALL OResultSetMetaData::getPrecision( sal_Int32 column ) throw(starsdbc::SQLException, staruno::RuntimeException)
{
return getNumColAttrib(column,SQL_DESC_PRECISION);
}
sal_Int32 SAL_CALL OResultSetMetaData::getScale( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException)
{
return getNumColAttrib(column,SQL_DESC_SCALE);
}
// -------------------------------------------------------------------------
sal_Int32 SAL_CALL OResultSetMetaData::isNullable( sal_Int32 column ) throw(starsdbc::SQLException, staruno::RuntimeException)
{
return getNumColAttrib(column,SQL_DESC_NULLABLE) == SQL_NULLABLE;
}
// -------------------------------------------------------------------------
sal_Bool SAL_CALL OResultSetMetaData::isSearchable( sal_Int32 column ) throw(starsdbc::SQLException, staruno::RuntimeException)
{
return getNumColAttrib(column,SQL_DESC_SEARCHABLE) != SQL_PRED_NONE;
}
// -------------------------------------------------------------------------
sal_Bool SAL_CALL OResultSetMetaData::isReadOnly( sal_Int32 column ) throw(starsdbc::SQLException, staruno::RuntimeException)
{
return getNumColAttrib(column,SQL_DESC_UPDATABLE) == SQL_ATTR_READONLY;
}
// -------------------------------------------------------------------------
sal_Bool SAL_CALL OResultSetMetaData::isDefinitelyWritable( sal_Int32 column ) throw(starsdbc::SQLException, staruno::RuntimeException)
{
return getNumColAttrib(column,SQL_DESC_UPDATABLE) == SQL_ATTR_WRITE;
;
}
// -------------------------------------------------------------------------
sal_Bool SAL_CALL OResultSetMetaData::isWritable( sal_Int32 column ) throw(starsdbc::SQLException, staruno::RuntimeException)
{
return getNumColAttrib(column,SQL_DESC_UPDATABLE) == SQL_ATTR_WRITE;
}
// -------------------------------------------------------------------------
<|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 "SkImageRef_GlobalPool.h"
#include "SkImageRefPool.h"
#include "SkThread.h"
extern SkBaseMutex gImageRefMutex;
static SkImageRefPool gGlobalImageRefPool;
SkImageRef_GlobalPool::SkImageRef_GlobalPool(SkStream* stream,
SkBitmap::Config config,
int sampleSize)
: SkImageRef(stream, config, sampleSize) {
this->mutex()->acquire();
gGlobalImageRefPool.addToHead(this);
this->mutex()->release();
}
SkImageRef_GlobalPool::~SkImageRef_GlobalPool() {
this->mutex()->acquire();
gGlobalImageRefPool.detach(this);
this->mutex()->release();
}
bool SkImageRef_GlobalPool::onDecode(SkImageDecoder* codec, SkStream* stream,
SkBitmap* bitmap, SkBitmap::Config config,
SkImageDecoder::Mode mode) {
if (!this->INHERITED::onDecode(codec, stream, bitmap, config, mode)) {
return false;
}
if (mode == SkImageDecoder::kDecodePixels_Mode) {
gGlobalImageRefPool.justAddedPixels(this);
}
return true;
}
void SkImageRef_GlobalPool::onUnlockPixels() {
this->INHERITED::onUnlockPixels();
gGlobalImageRefPool.canLosePixels(this);
}
SkImageRef_GlobalPool::SkImageRef_GlobalPool(SkFlattenableReadBuffer& buffer)
: INHERITED(buffer) {
this->mutex()->acquire();
gGlobalImageRefPool.addToHead(this);
this->mutex()->release();
}
SkPixelRef* SkImageRef_GlobalPool::Create(SkFlattenableReadBuffer& buffer) {
return SkNEW_ARGS(SkImageRef_GlobalPool, (buffer));
}
SK_DEFINE_PIXEL_REF_REGISTRAR(SkImageRef_GlobalPool)
///////////////////////////////////////////////////////////////////////////////
// global imagerefpool wrappers
size_t SkImageRef_GlobalPool::GetRAMBudget() {
SkAutoMutexAcquire ac(gImageRefMutex);
return gGlobalImageRefPool.getRAMBudget();
}
void SkImageRef_GlobalPool::SetRAMBudget(size_t size) {
SkAutoMutexAcquire ac(gImageRefMutex);
gGlobalImageRefPool.setRAMBudget(size);
}
size_t SkImageRef_GlobalPool::GetRAMUsed() {
SkAutoMutexAcquire ac(gImageRefMutex);
return gGlobalImageRefPool.getRAMUsed();
}
void SkImageRef_GlobalPool::SetRAMUsed(size_t usage) {
SkAutoMutexAcquire ac(gImageRefMutex);
gGlobalImageRefPool.setRAMUsed(usage);
}
void SkImageRef_GlobalPool::DumpPool() {
SkAutoMutexAcquire ac(gImageRefMutex);
gGlobalImageRefPool.dump();
}
<commit_msg>Lazily allocate our global pool for imagerefs Review URL: https://codereview.appspot.com/5677055<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 "SkImageRef_GlobalPool.h"
#include "SkImageRefPool.h"
#include "SkThread.h"
extern SkBaseMutex gImageRefMutex;
/*
* This returns the lazily-allocated global pool. It must be called
* from inside the guard mutex, so we safely only ever allocate 1.
*/
static SkImageRefPool* GetGlobalPool() {
static SkImageRefPool* gPool;
if (NULL == gPool) {
gPool = SkNEW(SkImageRefPool);
// call sk_atexit(...) when we have that, to free the global pool
}
return gPool;
}
SkImageRef_GlobalPool::SkImageRef_GlobalPool(SkStream* stream,
SkBitmap::Config config,
int sampleSize)
: SkImageRef(stream, config, sampleSize) {
this->mutex()->acquire();
GetGlobalPool()->addToHead(this);
this->mutex()->release();
}
SkImageRef_GlobalPool::~SkImageRef_GlobalPool() {
this->mutex()->acquire();
GetGlobalPool()->detach(this);
this->mutex()->release();
}
/* By design, onUnlockPixels() already is inside the mutex-lock,
* and it is the (indirect) caller of onDecode(), therefore we can assume
* that we also are already inside the mutex. Hence, we can reference
* the global-pool directly.
*/
bool SkImageRef_GlobalPool::onDecode(SkImageDecoder* codec, SkStream* stream,
SkBitmap* bitmap, SkBitmap::Config config,
SkImageDecoder::Mode mode) {
if (!this->INHERITED::onDecode(codec, stream, bitmap, config, mode)) {
return false;
}
if (mode == SkImageDecoder::kDecodePixels_Mode) {
// no need to grab the mutex here, it has already been acquired.
GetGlobalPool()->justAddedPixels(this);
}
return true;
}
void SkImageRef_GlobalPool::onUnlockPixels() {
this->INHERITED::onUnlockPixels();
// by design, onUnlockPixels() already is inside the mutex-lock
GetGlobalPool()->canLosePixels(this);
}
SkImageRef_GlobalPool::SkImageRef_GlobalPool(SkFlattenableReadBuffer& buffer)
: INHERITED(buffer) {
this->mutex()->acquire();
GetGlobalPool()->addToHead(this);
this->mutex()->release();
}
SkPixelRef* SkImageRef_GlobalPool::Create(SkFlattenableReadBuffer& buffer) {
return SkNEW_ARGS(SkImageRef_GlobalPool, (buffer));
}
SK_DEFINE_PIXEL_REF_REGISTRAR(SkImageRef_GlobalPool)
///////////////////////////////////////////////////////////////////////////////
// global imagerefpool wrappers
size_t SkImageRef_GlobalPool::GetRAMBudget() {
SkAutoMutexAcquire ac(gImageRefMutex);
return GetGlobalPool()->getRAMBudget();
}
void SkImageRef_GlobalPool::SetRAMBudget(size_t size) {
SkAutoMutexAcquire ac(gImageRefMutex);
GetGlobalPool()->setRAMBudget(size);
}
size_t SkImageRef_GlobalPool::GetRAMUsed() {
SkAutoMutexAcquire ac(gImageRefMutex);
return GetGlobalPool()->getRAMUsed();
}
void SkImageRef_GlobalPool::SetRAMUsed(size_t usage) {
SkAutoMutexAcquire ac(gImageRefMutex);
GetGlobalPool()->setRAMUsed(usage);
}
void SkImageRef_GlobalPool::DumpPool() {
SkAutoMutexAcquire ac(gImageRefMutex);
GetGlobalPool()->dump();
}
<|endoftext|> |
<commit_before>// For conditions of distribution and use, see copyright notice in license.txt
#include "StableHeaders.h"
#include "DebugOperatorNew.h"
#include "Provider.h"
#include "Session.h"
#include "MumbleVoipModule.h"
#include "ServerInfoProvider.h"
#include "MicrophoneAdjustmentWidget.h"
#include "EC_VoiceChannel.h"
#include "EventManager.h"
#include "NetworkEvents.h"
#include "UiServiceInterface.h"
#include "UiProxyWidget.h"
#include "SceneManager.h"
#include "TundraLogicModule.h"
#include "Client.h"
#include "Entity.h"
#include <QSignalMapper>
#include "MemoryLeakCheck.h"
namespace MumbleVoip
{
Provider::Provider(Foundation::Framework* framework, Settings* settings) :
framework_(framework),
description_("Mumble in-world voice"),
session_(0),
server_info_provider_(0),
settings_(settings),
microphone_adjustment_widget_(0),
signal_mapper_(new QSignalMapper(this))
{
connect(signal_mapper_, SIGNAL(mapped(const QString &)),this, SLOT(ECVoiceChannelChanged(const QString &)));
server_info_provider_ = new ServerInfoProvider(framework);
connect(server_info_provider_, SIGNAL(MumbleServerInfoReceived(ServerInfo)), this, SLOT(OnMumbleServerInfoReceived(ServerInfo)) );
networkstate_event_category_ = framework_->GetEventManager()->QueryEventCategory("NetworkState");
framework_event_category_ = framework_->GetEventManager()->QueryEventCategory("Framework");
if (framework_ && framework_->GetServiceManager())
{
boost::shared_ptr<Communications::ServiceInterface> communication_service = framework_->GetServiceManager()->GetService<Communications::ServiceInterface>(Service::ST_Communications).lock();
if (communication_service)
communication_service->Register(*this);
}
connect(framework_, SIGNAL(SceneAdded(const QString &)), this, SLOT(OnSceneAdded(const QString &)));
}
Provider::~Provider()
{
SAFE_DELETE(session_);
SAFE_DELETE(server_info_provider_);
}
void Provider::Update(f64 frametime)
{
if (session_)
session_->Update(frametime);
CheckChannelQueue();
}
bool Provider::HandleEvent(event_category_id_t category_id, event_id_t event_id, IEventData* data)
{
if (server_info_provider_)
server_info_provider_->HandleEvent(category_id, event_id, data);
if (category_id == networkstate_event_category_)
{
switch (event_id)
{
case ProtocolUtilities::Events::EVENT_SERVER_DISCONNECTED:
case ProtocolUtilities::Events::EVENT_CONNECTION_FAILED:
CloseSession();
SAFE_DELETE(session_);
break;
}
}
if (category_id == framework_event_category_)
{
switch (event_id)
{
case Foundation::WORLD_STREAM_READY:
ProtocolUtilities::WorldStreamReadyEvent *event_data = dynamic_cast<ProtocolUtilities::WorldStreamReadyEvent *>(data);
if (event_data)
world_stream_ = event_data->WorldStream;
break;
}
}
return false;
}
void Provider::CheckChannelQueue()
{
if (channel_queue_.isEmpty())
return;
if (GetUsername().length() == 0)
return;
EC_VoiceChannel* channel = channel_queue_.takeFirst();
if (channel)
AddECVoiceChannel(channel);
}
Communications::InWorldVoice::SessionInterface* Provider::Session()
{
return session_;
}
QString& Provider::Description()
{
return description_;
}
void Provider::OnMumbleServerInfoReceived(ServerInfo info)
{
ComponentPtr component = framework_->GetComponentManager()->CreateComponent("EC_VoiceChannel", "Public");
EC_VoiceChannel* channel = dynamic_cast<EC_VoiceChannel*>(component.get());
if (!channel)
return;
channel->setprotocol("mumble");
channel->setserveraddress(info.server);
channel->setversion(info.version);
channel->setusername(info.user_name);
channel->setserverpassword(info.password);
channel->setchannelid(info.channel_id);
channel->setchannelname("Public");
channel->setenabled(true);
Scene::EntityPtr e = framework_->GetDefaultWorldScene()->CreateEntity(framework_->GetDefaultWorldScene()->GetNextFreeId());
e->AddComponent(component, AttributeChange::LocalOnly);
}
void Provider::CloseSession()
{
if (session_)
session_->Close();
emit SessionUnavailable();
}
void Provider::CreateSession()
{
if (session_ && session_->GetState() == Session::STATE_CLOSED)
SAFE_DELETE(session_) //! \todo USE SHARED PTR, SOMEONE MIGHT HAVE POINTER TO SESSION OBJECT !!!!
if (!session_)
{
session_ = new MumbleVoip::Session(framework_, settings_);
emit SessionAvailable();
}
}
QList<QString> Provider::Statistics()
{
if (!session_)
{
QList<QString> lines;
return lines;
}
else
return session_->Statistics();
}
void Provider::ShowMicrophoneAdjustmentDialog()
{
UiServiceInterface *ui_service = framework_->GetService<UiServiceInterface>();
if (!ui_service)
return;
if (microphone_adjustment_widget_)
return;
bool audio_sending_was_enabled = false;
bool audio_receiving_was_enabled = false;
if (session_)
{
audio_sending_was_enabled = session_->IsAudioSendingEnabled();
audio_receiving_was_enabled = session_->IsAudioReceivingEnabled();
session_->DisableAudioSending();
session_->DisableAudioReceiving();
}
microphone_adjustment_widget_ = new MicrophoneAdjustmentWidget(framework_, settings_);
microphone_adjustment_widget_->setWindowTitle("Local Test Mode");
microphone_adjustment_widget_->setAttribute(Qt::WA_DeleteOnClose, true);
microphone_adjustment_widget_->show();
connect(microphone_adjustment_widget_, SIGNAL(destroyed()), this, SLOT(OnMicrophoneAdjustmentWidgetDestroyed()));
if (audio_sending_was_enabled)
connect(microphone_adjustment_widget_, SIGNAL(destroyed()), session_, SLOT(EnableAudioSending()));
if (audio_receiving_was_enabled)
connect(microphone_adjustment_widget_, SIGNAL(destroyed()), session_, SLOT(EnableAudioReceiving()));
}
void Provider::OnMicrophoneAdjustmentWidgetDestroyed()
{
microphone_adjustment_widget_ = 0;
}
void Provider::OnECAdded(Scene::Entity* entity, IComponent* comp, AttributeChange::Type change)
{
if (comp->TypeName() != "EC_VoiceChannel")
return;
EC_VoiceChannel* channel = dynamic_cast<EC_VoiceChannel*>(comp);
if (!channel)
return;
if (ec_voice_channels_.contains(channel))
return;
QString user_name = GetUsername();
if (user_name.length() == 0)
{
channel_queue_.append(channel);
return;
}
else
AddECVoiceChannel(channel);
}
void Provider::AddECVoiceChannel(EC_VoiceChannel* channel)
{
ec_voice_channels_.append(channel);
channel_names_[channel] = channel->getchannelname();
if (!session_ || session_->GetState() != Communications::InWorldVoice::SessionInterface::STATE_OPEN)
CreateSession();
connect(channel, SIGNAL(destroyed(QObject*)), this, SLOT(OnECVoiceChannelDestroyed(QObject*)),Qt::UniqueConnection);
connect(channel, SIGNAL(OnChanged()), signal_mapper_, SLOT(map()));
signal_mapper_->setMapping(channel,QString::number(reinterpret_cast<unsigned int>(channel)));
if (session_->GetChannels().contains(channel->getchannelname()))
channel->setenabled(false); // We do not want to create multiple channels with a same name
ServerInfo server_info;
server_info.server = channel->getserveraddress();
server_info.version = channel->getversion();
server_info.password = channel->getserverpassword();
server_info.channel_id = channel->getchannelid();
server_info.channel_name = channel->getchannelname();
server_info.user_name = GetUsername();
server_info.avatar_id = GetAvatarUuid();
if (channel->getenabled())
session_->AddChannel(channel->getchannelname(), server_info);
if (session_->GetActiveChannel() == "")
session_->SetActiveChannel(channel->Name());
}
void Provider::OnECVoiceChannelDestroyed(QObject* obj)
{
foreach(EC_VoiceChannel* channel, ec_voice_channels_)
{
if (channel == obj)
{
QString channel_name = channel_names_[channel];
if (session_)
session_->RemoveChannel(channel_name);
ec_voice_channels_.removeAll(channel);
channel_names_.remove(channel);
return;
}
}
}
void Provider::OnSceneAdded(const QString &name)
{
Scene::SceneManager* scene = framework_->GetScene(name).get();
if (!scene)
return;
connect(scene, SIGNAL(ComponentAdded(Scene::Entity*, IComponent*, AttributeChange::Type)), SLOT(OnECAdded(Scene::Entity*, IComponent*, AttributeChange::Type)));
}
void Provider::ECVoiceChannelChanged(const QString &pointer)
{
if (!session_)
return;
/// @todo If user have edited the active channel -> close, reopen
foreach(EC_VoiceChannel* channel, ec_voice_channels_)
{
if (QString::number(reinterpret_cast<unsigned int>(channel)) != pointer)
continue;
if (channel->getenabled() && !session_->GetChannels().contains(channel->getchannelname()))
{
ServerInfo server_info;
server_info.server = channel->getserveraddress();
server_info.version = channel->getversion();
server_info.password = channel->getserverpassword();
server_info.channel_id = channel->getchannelid();
server_info.channel_name = channel->getchannelname();
server_info.user_name = GetUsername();
server_info.avatar_id = GetAvatarUuid();
channel_names_[channel] = channel->getchannelname();
session_->AddChannel(channel->getchannelname(), server_info);
}
if (!channel->getenabled())
{
session_->RemoveChannel(channel->getchannelname());
}
}
}
QString Provider::GetUsername()
{
if (!tundra_logic_->IsServer())
return tundra_logic_->GetClient()->GetLoginProperty("username");;
return "";
}
QString Provider::GetAvatarUuid()
{
/// @todo: Get user's avatar entity uuid
return "";
}
void Provider::PostInitialize()
{
tundra_logic_ = framework_->GetModuleManager()->GetModule<TundraLogic::TundraLogicModule>().lock();
if (!tundra_logic_)
{
throw Exception("Fatal: could not get TundraLogicModule");
}
}
} // MumbleVoip
<commit_msg>MumbeVoip::Provider: *Do not throw if cannot retrieve TundraLogicModer, print error instead *Use IComponent::AttributeChanged() signal instead of to-be-deprecated OnChanged()<commit_after>// For conditions of distribution and use, see copyright notice in license.txt
#include "StableHeaders.h"
#include "DebugOperatorNew.h"
#include "Provider.h"
#include "Session.h"
#include "MumbleVoipModule.h"
#include "ServerInfoProvider.h"
#include "MicrophoneAdjustmentWidget.h"
#include "EC_VoiceChannel.h"
#include "EventManager.h"
#include "NetworkEvents.h"
#include "UiServiceInterface.h"
#include "UiProxyWidget.h"
#include "SceneManager.h"
#include "TundraLogicModule.h"
#include "Client.h"
#include "Entity.h"
#include <QSignalMapper>
#include "MemoryLeakCheck.h"
namespace MumbleVoip
{
Provider::Provider(Foundation::Framework* framework, Settings* settings) :
framework_(framework),
description_("Mumble in-world voice"),
session_(0),
server_info_provider_(0),
settings_(settings),
microphone_adjustment_widget_(0),
signal_mapper_(new QSignalMapper(this))
{
connect(signal_mapper_, SIGNAL(mapped(const QString &)),this, SLOT(ECVoiceChannelChanged(const QString &)));
server_info_provider_ = new ServerInfoProvider(framework);
connect(server_info_provider_, SIGNAL(MumbleServerInfoReceived(ServerInfo)), this, SLOT(OnMumbleServerInfoReceived(ServerInfo)) );
networkstate_event_category_ = framework_->GetEventManager()->QueryEventCategory("NetworkState");
framework_event_category_ = framework_->GetEventManager()->QueryEventCategory("Framework");
if (framework_ && framework_->GetServiceManager())
{
boost::shared_ptr<Communications::ServiceInterface> communication_service = framework_->GetServiceManager()->GetService<Communications::ServiceInterface>(Service::ST_Communications).lock();
if (communication_service)
communication_service->Register(*this);
}
connect(framework_, SIGNAL(SceneAdded(const QString &)), this, SLOT(OnSceneAdded(const QString &)));
}
Provider::~Provider()
{
SAFE_DELETE(session_);
SAFE_DELETE(server_info_provider_);
}
void Provider::Update(f64 frametime)
{
if (session_)
session_->Update(frametime);
CheckChannelQueue();
}
bool Provider::HandleEvent(event_category_id_t category_id, event_id_t event_id, IEventData* data)
{
if (server_info_provider_)
server_info_provider_->HandleEvent(category_id, event_id, data);
if (category_id == networkstate_event_category_)
{
switch (event_id)
{
case ProtocolUtilities::Events::EVENT_SERVER_DISCONNECTED:
case ProtocolUtilities::Events::EVENT_CONNECTION_FAILED:
CloseSession();
SAFE_DELETE(session_);
break;
}
}
if (category_id == framework_event_category_)
{
switch (event_id)
{
case Foundation::WORLD_STREAM_READY:
ProtocolUtilities::WorldStreamReadyEvent *event_data = dynamic_cast<ProtocolUtilities::WorldStreamReadyEvent *>(data);
if (event_data)
world_stream_ = event_data->WorldStream;
break;
}
}
return false;
}
void Provider::CheckChannelQueue()
{
if (channel_queue_.isEmpty())
return;
if (GetUsername().length() == 0)
return;
EC_VoiceChannel* channel = channel_queue_.takeFirst();
if (channel)
AddECVoiceChannel(channel);
}
Communications::InWorldVoice::SessionInterface* Provider::Session()
{
return session_;
}
QString& Provider::Description()
{
return description_;
}
void Provider::OnMumbleServerInfoReceived(ServerInfo info)
{
ComponentPtr component = framework_->GetComponentManager()->CreateComponent("EC_VoiceChannel", "Public");
EC_VoiceChannel* channel = dynamic_cast<EC_VoiceChannel*>(component.get());
if (!channel)
return;
channel->setprotocol("mumble");
channel->setserveraddress(info.server);
channel->setversion(info.version);
channel->setusername(info.user_name);
channel->setserverpassword(info.password);
channel->setchannelid(info.channel_id);
channel->setchannelname("Public");
channel->setenabled(true);
Scene::EntityPtr e = framework_->GetDefaultWorldScene()->CreateEntity(framework_->GetDefaultWorldScene()->GetNextFreeId());
e->AddComponent(component, AttributeChange::LocalOnly);
}
void Provider::CloseSession()
{
if (session_)
session_->Close();
emit SessionUnavailable();
}
void Provider::CreateSession()
{
if (session_ && session_->GetState() == Session::STATE_CLOSED)
SAFE_DELETE(session_) //! \todo USE SHARED PTR, SOMEONE MIGHT HAVE POINTER TO SESSION OBJECT !!!!
if (!session_)
{
session_ = new MumbleVoip::Session(framework_, settings_);
emit SessionAvailable();
}
}
QList<QString> Provider::Statistics()
{
if (!session_)
{
QList<QString> lines;
return lines;
}
else
return session_->Statistics();
}
void Provider::ShowMicrophoneAdjustmentDialog()
{
UiServiceInterface *ui_service = framework_->GetService<UiServiceInterface>();
if (!ui_service)
return;
if (microphone_adjustment_widget_)
return;
bool audio_sending_was_enabled = false;
bool audio_receiving_was_enabled = false;
if (session_)
{
audio_sending_was_enabled = session_->IsAudioSendingEnabled();
audio_receiving_was_enabled = session_->IsAudioReceivingEnabled();
session_->DisableAudioSending();
session_->DisableAudioReceiving();
}
microphone_adjustment_widget_ = new MicrophoneAdjustmentWidget(framework_, settings_);
microphone_adjustment_widget_->setWindowTitle("Local Test Mode");
microphone_adjustment_widget_->setAttribute(Qt::WA_DeleteOnClose, true);
microphone_adjustment_widget_->show();
connect(microphone_adjustment_widget_, SIGNAL(destroyed()), this, SLOT(OnMicrophoneAdjustmentWidgetDestroyed()));
if (audio_sending_was_enabled)
connect(microphone_adjustment_widget_, SIGNAL(destroyed()), session_, SLOT(EnableAudioSending()));
if (audio_receiving_was_enabled)
connect(microphone_adjustment_widget_, SIGNAL(destroyed()), session_, SLOT(EnableAudioReceiving()));
}
void Provider::OnMicrophoneAdjustmentWidgetDestroyed()
{
microphone_adjustment_widget_ = 0;
}
void Provider::OnECAdded(Scene::Entity* entity, IComponent* comp, AttributeChange::Type change)
{
if (comp->TypeName() != "EC_VoiceChannel")
return;
EC_VoiceChannel* channel = dynamic_cast<EC_VoiceChannel*>(comp);
if (!channel)
return;
if (ec_voice_channels_.contains(channel))
return;
QString user_name = GetUsername();
if (user_name.length() == 0)
{
channel_queue_.append(channel);
return;
}
else
AddECVoiceChannel(channel);
}
void Provider::AddECVoiceChannel(EC_VoiceChannel* channel)
{
ec_voice_channels_.append(channel);
channel_names_[channel] = channel->getchannelname();
if (!session_ || session_->GetState() != Communications::InWorldVoice::SessionInterface::STATE_OPEN)
CreateSession();
connect(channel, SIGNAL(destroyed(QObject*)), this, SLOT(OnECVoiceChannelDestroyed(QObject*)),Qt::UniqueConnection);
connect(channel, SIGNAL(AttributeChanged(IAttribute *, AttributeChange::Type)), signal_mapper_, SLOT(map()));
signal_mapper_->setMapping(channel,QString::number(reinterpret_cast<unsigned int>(channel)));
if (session_->GetChannels().contains(channel->getchannelname()))
channel->setenabled(false); // We do not want to create multiple channels with a same name
ServerInfo server_info;
server_info.server = channel->getserveraddress();
server_info.version = channel->getversion();
server_info.password = channel->getserverpassword();
server_info.channel_id = channel->getchannelid();
server_info.channel_name = channel->getchannelname();
server_info.user_name = GetUsername();
server_info.avatar_id = GetAvatarUuid();
if (channel->getenabled())
session_->AddChannel(channel->getchannelname(), server_info);
if (session_->GetActiveChannel() == "")
session_->SetActiveChannel(channel->Name());
}
void Provider::OnECVoiceChannelDestroyed(QObject* obj)
{
foreach(EC_VoiceChannel* channel, ec_voice_channels_)
{
if (channel == obj)
{
QString channel_name = channel_names_[channel];
if (session_)
session_->RemoveChannel(channel_name);
ec_voice_channels_.removeAll(channel);
channel_names_.remove(channel);
return;
}
}
}
void Provider::OnSceneAdded(const QString &name)
{
Scene::SceneManager* scene = framework_->GetScene(name).get();
if (!scene)
return;
connect(scene, SIGNAL(ComponentAdded(Scene::Entity*, IComponent*, AttributeChange::Type)),
SLOT(OnECAdded(Scene::Entity*, IComponent*, AttributeChange::Type)));
}
void Provider::ECVoiceChannelChanged(const QString &pointer)
{
if (!session_)
return;
/// @todo If user have edited the active channel -> close, reopen
foreach(EC_VoiceChannel* channel, ec_voice_channels_)
{
if (QString::number(reinterpret_cast<unsigned int>(channel)) != pointer)
continue;
if (channel->getenabled() && !session_->GetChannels().contains(channel->getchannelname()))
{
ServerInfo server_info;
server_info.server = channel->getserveraddress();
server_info.version = channel->getversion();
server_info.password = channel->getserverpassword();
server_info.channel_id = channel->getchannelid();
server_info.channel_name = channel->getchannelname();
server_info.user_name = GetUsername();
server_info.avatar_id = GetAvatarUuid();
channel_names_[channel] = channel->getchannelname();
session_->AddChannel(channel->getchannelname(), server_info);
}
if (!channel->getenabled())
{
session_->RemoveChannel(channel->getchannelname());
}
}
}
QString Provider::GetUsername()
{
if (tundra_logic_ && !tundra_logic_->IsServer())
return tundra_logic_->GetClient()->GetLoginProperty("username");;
return "";
}
QString Provider::GetAvatarUuid()
{
/// @todo: Get user's avatar entity uuid
return "";
}
void Provider::PostInitialize()
{
tundra_logic_ = framework_->GetModuleManager()->GetModule<TundraLogic::TundraLogicModule>().lock();
if (!tundra_logic_)
RootLogError("MumbleVoip::Proviver: Could not get TundraLogicModule");
}
} // MumbleVoip
<|endoftext|> |
<commit_before>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "imported_search_context.h"
#include "imported_attribute_vector.h"
#include <vespa/searchlib/common/bitvectoriterator.h>
#include <vespa/searchlib/queryeval/emptysearch.h>
#include "attributeiterators.hpp"
using search::datastore::EntryRef;
using search::queryeval::EmptySearch;
using search::queryeval::SearchIterator;
using search::attribute::ReferenceAttribute;
using search::AttributeVector;
using ReverseMappingRefs = ReferenceAttribute::ReverseMappingRefs;
using ReverseMapping = ReferenceAttribute::ReverseMapping;
using SearchContext = AttributeVector::SearchContext;
namespace search::attribute {
ImportedSearchContext::ImportedSearchContext(
std::unique_ptr<QueryTermSimple> term,
const SearchContextParams& params,
const ImportedAttributeVector& imported_attribute)
: _imported_attribute(imported_attribute),
_reference_attribute(*_imported_attribute.getReferenceAttribute()),
_target_attribute(*_imported_attribute.getTargetAttribute()),
_target_search_context(_target_attribute.getSearch(std::move(term), params)),
_referencedLids(_reference_attribute.getReferencedLids()),
_referencedLidLimit(_target_attribute.getCommittedDocIdLimit()),
_merger(_reference_attribute.getCommittedDocIdLimit()),
_fetchPostingsDone(false)
{
}
ImportedSearchContext::~ImportedSearchContext() {
}
unsigned int ImportedSearchContext::approximateHits() const {
return _reference_attribute.getNumDocs();
}
std::unique_ptr<queryeval::SearchIterator>
ImportedSearchContext::createIterator(fef::TermFieldMatchData* matchData, bool strict) {
if (_merger.hasArray()) {
if (_merger.emptyArray()) {
return SearchIterator::UP(new EmptySearch());
} else {
using Posting = btree::BTreeKeyData<uint32_t, int32_t>;
using DocIt = DocIdIterator<Posting>;
DocIt postings;
auto array = _merger.getArray();
postings.set(&array[0], &array[array.size()]);
return std::make_unique<AttributePostingListIteratorT<DocIt>>(true, matchData, postings);
}
} else if (_merger.hasBitVector()) {
return BitVectorIterator::create(_merger.getBitVector(), _merger.getDocIdLimit(), *matchData, strict);
}
if (!strict) {
return std::make_unique<AttributeIteratorT<ImportedSearchContext>>(*this, matchData);
} else {
return std::make_unique<AttributeIteratorStrict<ImportedSearchContext>>(*this, matchData);
}
}
namespace {
struct WeightedRef {
EntryRef revMapIdx;
int32_t weight;
WeightedRef(EntryRef revMapIdx_, int32_t weight_)
: revMapIdx(revMapIdx_),
weight(weight_)
{
}
};
struct TargetResult {
std::vector<WeightedRef> weightedRefs;
size_t sizeSum;
TargetResult()
: weightedRefs(),
sizeSum(0)
{
}
};
TargetResult
getTargetResult(ReverseMappingRefs reverseMappingRefs,
const ReverseMapping &reverseMapping,
SearchContext &target_search_context,
uint32_t committedDocIdLimit)
{
TargetResult targetResult;
fef::TermFieldMatchData matchData;
auto targetItr = target_search_context.createIterator(&matchData, true);
uint32_t docIdLimit = reverseMappingRefs.size();
if (docIdLimit > committedDocIdLimit) {
docIdLimit = committedDocIdLimit;
}
uint32_t lid = 1;
targetItr->initRange(1, docIdLimit);
while (lid < docIdLimit) {
if (targetItr->seek(lid)) {
EntryRef revMapIdx = reverseMappingRefs[lid];
if (revMapIdx.valid()) {
uint32_t size = reverseMapping.frozenSize(revMapIdx);
targetResult.sizeSum += size;
targetItr->unpack(lid);
int32_t weight = matchData.getWeight();
targetResult.weightedRefs.emplace_back(revMapIdx, weight);
}
++lid;
} else {
++lid;
uint32_t nextLid = targetItr->getDocId();
if (nextLid > lid) {
lid = nextLid;
}
}
}
return targetResult;
}
class ReverseMappingPostingList
{
const ReverseMapping &_reverseMapping;
EntryRef _revMapIdx;
int32_t _weight;
public:
ReverseMappingPostingList(const ReverseMapping &reverseMapping, EntryRef revMapIdx, int32_t weight)
: _reverseMapping(reverseMapping),
_revMapIdx(revMapIdx),
_weight(weight)
{
}
~ReverseMappingPostingList() { }
template <typename Func>
void foreach(Func func) const {
int32_t weight = _weight;
_reverseMapping.foreach_frozen_key(_revMapIdx, [func, weight](uint32_t lid) { func(lid, weight); });
}
template <typename Func>
void foreach_key(Func func) const {
_reverseMapping.foreach_frozen_key(_revMapIdx, [func](uint32_t lid) { func(lid); });
}
};
}
void ImportedSearchContext::makeMergedPostings(bool isFilter)
{
uint32_t committedTargetDocIdLimit = _target_attribute.getCommittedDocIdLimit();
std::atomic_thread_fence(std::memory_order_acquire);
TargetResult targetResult(getTargetResult(_reference_attribute.getReverseMappingRefs(),
_reference_attribute.getReverseMapping(),
*_target_search_context,
committedTargetDocIdLimit));
_merger.reserveArray(targetResult.weightedRefs.size(), targetResult.sizeSum);
const auto &reverseMapping = _reference_attribute.getReverseMapping();
if (isFilter) {
_merger.allocBitVector();
}
for (const auto &weightedRef : targetResult.weightedRefs) {
ReverseMappingPostingList rmp(reverseMapping, weightedRef.revMapIdx, weightedRef.weight);
if (isFilter) {
_merger.addToBitVector(rmp);
} else {
_merger.addToArray(rmp);
}
}
_merger.merge();
}
void ImportedSearchContext::fetchPostings(bool strict) {
assert(!_fetchPostingsDone);
_fetchPostingsDone = true;
_target_search_context->fetchPostings(strict);
if (strict || _target_attribute.getConfig().fastSearch()) {
makeMergedPostings(_target_attribute.getConfig().getIsFilter());
}
}
bool ImportedSearchContext::valid() const {
return _target_search_context->valid();
}
Int64Range ImportedSearchContext::getAsIntegerTerm() const {
return _target_search_context->getAsIntegerTerm();
}
const QueryTermBase& ImportedSearchContext::queryTerm() const {
return _target_search_context->queryTerm();
}
const vespalib::string& ImportedSearchContext::attributeName() const {
return _imported_attribute.getName();
}
}
<commit_msg>Ensure large method is not inlined.<commit_after>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "imported_search_context.h"
#include "imported_attribute_vector.h"
#include <vespa/searchlib/common/bitvectoriterator.h>
#include <vespa/searchlib/queryeval/emptysearch.h>
#include "attributeiterators.hpp"
using search::datastore::EntryRef;
using search::queryeval::EmptySearch;
using search::queryeval::SearchIterator;
using search::attribute::ReferenceAttribute;
using search::AttributeVector;
using ReverseMappingRefs = ReferenceAttribute::ReverseMappingRefs;
using ReverseMapping = ReferenceAttribute::ReverseMapping;
using SearchContext = AttributeVector::SearchContext;
namespace search::attribute {
ImportedSearchContext::ImportedSearchContext(
std::unique_ptr<QueryTermSimple> term,
const SearchContextParams& params,
const ImportedAttributeVector& imported_attribute)
: _imported_attribute(imported_attribute),
_reference_attribute(*_imported_attribute.getReferenceAttribute()),
_target_attribute(*_imported_attribute.getTargetAttribute()),
_target_search_context(_target_attribute.getSearch(std::move(term), params)),
_referencedLids(_reference_attribute.getReferencedLids()),
_referencedLidLimit(_target_attribute.getCommittedDocIdLimit()),
_merger(_reference_attribute.getCommittedDocIdLimit()),
_fetchPostingsDone(false)
{
}
ImportedSearchContext::~ImportedSearchContext() {
}
unsigned int ImportedSearchContext::approximateHits() const {
return _reference_attribute.getNumDocs();
}
std::unique_ptr<queryeval::SearchIterator>
ImportedSearchContext::createIterator(fef::TermFieldMatchData* matchData, bool strict) {
if (_merger.hasArray()) {
if (_merger.emptyArray()) {
return SearchIterator::UP(new EmptySearch());
} else {
using Posting = btree::BTreeKeyData<uint32_t, int32_t>;
using DocIt = DocIdIterator<Posting>;
DocIt postings;
auto array = _merger.getArray();
postings.set(&array[0], &array[array.size()]);
return std::make_unique<AttributePostingListIteratorT<DocIt>>(true, matchData, postings);
}
} else if (_merger.hasBitVector()) {
return BitVectorIterator::create(_merger.getBitVector(), _merger.getDocIdLimit(), *matchData, strict);
}
if (!strict) {
return std::make_unique<AttributeIteratorT<ImportedSearchContext>>(*this, matchData);
} else {
return std::make_unique<AttributeIteratorStrict<ImportedSearchContext>>(*this, matchData);
}
}
namespace {
struct WeightedRef {
EntryRef revMapIdx;
int32_t weight;
WeightedRef(EntryRef revMapIdx_, int32_t weight_)
: revMapIdx(revMapIdx_),
weight(weight_)
{
}
};
struct TargetResult {
std::vector<WeightedRef> weightedRefs;
size_t sizeSum;
TargetResult()
: weightedRefs(),
sizeSum(0)
{
}
};
TargetResult
getTargetResult(ReverseMappingRefs reverseMappingRefs,
const ReverseMapping &reverseMapping,
SearchContext &target_search_context,
uint32_t committedDocIdLimit) __attribute__((noinline));
TargetResult
getTargetResult(ReverseMappingRefs reverseMappingRefs,
const ReverseMapping &reverseMapping,
SearchContext &target_search_context,
uint32_t committedDocIdLimit)
{
TargetResult targetResult;
fef::TermFieldMatchData matchData;
auto targetItr = target_search_context.createIterator(&matchData, true);
uint32_t docIdLimit = reverseMappingRefs.size();
if (docIdLimit > committedDocIdLimit) {
docIdLimit = committedDocIdLimit;
}
uint32_t lid = 1;
targetItr->initRange(1, docIdLimit);
while (lid < docIdLimit) {
if (targetItr->seek(lid)) {
EntryRef revMapIdx = reverseMappingRefs[lid];
if (revMapIdx.valid()) {
uint32_t size = reverseMapping.frozenSize(revMapIdx);
targetResult.sizeSum += size;
targetItr->unpack(lid);
int32_t weight = matchData.getWeight();
targetResult.weightedRefs.emplace_back(revMapIdx, weight);
}
++lid;
} else {
++lid;
uint32_t nextLid = targetItr->getDocId();
if (nextLid > lid) {
lid = nextLid;
}
}
}
return targetResult;
}
class ReverseMappingPostingList
{
const ReverseMapping &_reverseMapping;
EntryRef _revMapIdx;
int32_t _weight;
public:
ReverseMappingPostingList(const ReverseMapping &reverseMapping, EntryRef revMapIdx, int32_t weight)
: _reverseMapping(reverseMapping),
_revMapIdx(revMapIdx),
_weight(weight)
{
}
~ReverseMappingPostingList() { }
template <typename Func>
void foreach(Func func) const {
int32_t weight = _weight;
_reverseMapping.foreach_frozen_key(_revMapIdx, [func, weight](uint32_t lid) { func(lid, weight); });
}
template <typename Func>
void foreach_key(Func func) const {
_reverseMapping.foreach_frozen_key(_revMapIdx, [func](uint32_t lid) { func(lid); });
}
};
}
void ImportedSearchContext::makeMergedPostings(bool isFilter)
{
uint32_t committedTargetDocIdLimit = _target_attribute.getCommittedDocIdLimit();
std::atomic_thread_fence(std::memory_order_acquire);
TargetResult targetResult(getTargetResult(_reference_attribute.getReverseMappingRefs(),
_reference_attribute.getReverseMapping(),
*_target_search_context,
committedTargetDocIdLimit));
_merger.reserveArray(targetResult.weightedRefs.size(), targetResult.sizeSum);
const auto &reverseMapping = _reference_attribute.getReverseMapping();
if (isFilter) {
_merger.allocBitVector();
}
for (const auto &weightedRef : targetResult.weightedRefs) {
ReverseMappingPostingList rmp(reverseMapping, weightedRef.revMapIdx, weightedRef.weight);
if (isFilter) {
_merger.addToBitVector(rmp);
} else {
_merger.addToArray(rmp);
}
}
_merger.merge();
}
void ImportedSearchContext::fetchPostings(bool strict) {
assert(!_fetchPostingsDone);
_fetchPostingsDone = true;
_target_search_context->fetchPostings(strict);
if (strict || _target_attribute.getConfig().fastSearch()) {
makeMergedPostings(_target_attribute.getConfig().getIsFilter());
}
}
bool ImportedSearchContext::valid() const {
return _target_search_context->valid();
}
Int64Range ImportedSearchContext::getAsIntegerTerm() const {
return _target_search_context->getAsIntegerTerm();
}
const QueryTermBase& ImportedSearchContext::queryTerm() const {
return _target_search_context->queryTerm();
}
const vespalib::string& ImportedSearchContext::attributeName() const {
return _imported_attribute.getName();
}
}
<|endoftext|> |
<commit_before>/**
* @file TaskManager.cpp
* @brief TaskManager class implementation.
* @author zer0
* @date 2019-12-19
*/
#include <libtbag/task/TaskManager.hpp>
#include <libtbag/signal/SignalHandler.hpp>
#include <libtbag/thread/ThreadKill.hpp>
#include <libtbag/thread/ThreadLocalStorage.hpp>
#include <libtbag/container/Global.hpp>
#include <libtbag/lock/UvLock.hpp>
#include <libtbag/lock/UvCondition.hpp>
#include <libtbag/log/Log.hpp>
#include <cassert>
#include <memory>
// -------------------
NAMESPACE_LIBTBAG_OPEN
// -------------------
namespace task {
using TaskId = TaskManager::TaskId;
using ErrTaskId = TaskManager::ErrTaskId;
using ErrTaskInfo = TaskManager::ErrTaskInfo;
TBAG_CONSTEXPR static char const * const GLOBAL_MANAGER_REGISTER_KEY =
"libtbag::task::_manager_register";
TBAG_CONSTEXPR static int const THREAD_TASK_KILL_SIGNAL =
libtbag::signal::TBAG_SIGNAL_INTERRUPT;
struct _manager_register TBAG_FINAL : private Noncopyable
{
using Tls = libtbag::thread::ThreadLocalStorage;
Tls mgr;
Tls id;
_manager_register() { /* EMPTY. */ }
~_manager_register() { /* EMPTY. */ }
};
static std::shared_ptr<_manager_register> __get_global_manager_register()
{
using namespace libtbag::container;
auto weak = findGlobalObject<_manager_register>(GLOBAL_MANAGER_REGISTER_KEY);
if (auto shared = weak.lock()) {
return shared;
} else {
return newGlobalObject<_manager_register>(GLOBAL_MANAGER_REGISTER_KEY);
}
}
void __task_int_signal(int signum)
{
auto const shared = __get_global_manager_register();
TaskManager * mgr = shared->mgr.cast<TaskManager>();
TaskId id = (TaskId)(std::intptr_t)shared->id.get();
mgr->_on_thread_exit(id, EXIT_FAILURE, signum);
libtbag::thread::exitThread(EXIT_FAILURE);
}
static void __init_task_thread(TaskManager * mgr, TaskId id)
{
#if !defined(TBAG_PLATFORM_WINDOWS)
auto const shared = __get_global_manager_register();
assert(static_cast<bool>(shared));
shared->mgr.set(mgr);
shared->id.set((void*)(std::intptr_t)id);
std::signal(THREAD_TASK_KILL_SIGNAL, &__task_int_signal);
#endif
}
// --------------------------
// TaskManager implementation
// --------------------------
TaskManager::TaskManager(Callback * cb)
: TASK_CALLBACK(cb), _task_number(BEGIN_TASK_ID)
{
auto const shared = __get_global_manager_register();
assert(static_cast<bool>(shared));
using namespace std::placeholders;
_processes.out_read_cb = std::bind(&TaskManager::_on_process_out, this, _1, _2, _3);
_processes.err_read_cb = std::bind(&TaskManager::_on_process_err, this, _1, _2, _3);
_processes.exit_cb = std::bind(&TaskManager::_on_process_exit, this, _1, _2, _3);
}
TaskManager::~TaskManager()
{
// EMPTY.
}
TaskId TaskManager::nextTaskId()
{
while (true) {
auto const id = _task_number++;
if (!exists(id)) {
return id;
}
}
}
std::size_t TaskManager::size() const
{
ReadLockGuard const G(_tasks_lock);
return _tasks.size();
}
bool TaskManager::empty() const
{
ReadLockGuard const G(_tasks_lock);
return _tasks.empty();
}
std::vector<TaskId> TaskManager::list() const
{
std::vector<TaskId> result;
ReadLockGuard const G(_tasks_lock);
for (auto const & task : _tasks) {
result.push_back(task.first);
}
return result;
}
TaskManager::TaskMap TaskManager::map() const
{
ReadLockGuard const G(_tasks_lock);
return _tasks;
}
bool TaskManager::exists(TaskId id) const
{
ReadLockGuard const G(_tasks_lock);
return _tasks.find(id) != _tasks.end();
}
ErrTaskInfo TaskManager::getTaskInfo(TaskId id) const
{
ReadLockGuard const G(_tasks_lock);
auto const itr = _tasks.find(id);
if (itr == _tasks.end()) {
return E_NFOUND;
}
return { E_SUCCESS, itr->second };
}
void TaskManager::_on_thread_exit(TaskId id, int64_t exit_status, int term_signal)
{
tDLogN("TaskManager::_on_thread_exit(task_id={},exit={},signum={}) function was called.",
id, exit_status, term_signal);
COMMENT("Tasks lock") {
WriteLockGuard const G(_tasks_lock);
auto itr = _tasks.find(id);
assert(itr != _tasks.end());
itr->second.done = true;
itr->second.exit_status = exit_status;
itr->second.term_signal = term_signal;
}
if (TASK_CALLBACK) {
TASK_CALLBACK->onThreadExit(id, exit_status, term_signal);
}
}
void TaskManager::_on_process_out(int pid, char const * buffer, std::size_t size)
{
TaskId task_id;
COMMENT("Tasks lock") {
ReadLockGuard const G(_tasks_lock);
auto itr0 = _pid2task.find(pid);
assert(itr0 != _pid2task.end());
task_id = itr0->second;
auto itr = _tasks.find(task_id);
assert(itr != _tasks.end());
}
if (TASK_CALLBACK) {
TASK_CALLBACK->onProcessOut(task_id, buffer, size);
}
}
void TaskManager::_on_process_err(int pid, char const * buffer, std::size_t size)
{
TaskId task_id;
COMMENT("Tasks lock") {
ReadLockGuard const G(_tasks_lock);
auto itr0 = _pid2task.find(pid);
assert(itr0 != _pid2task.end());
task_id = itr0->second;
auto itr = _tasks.find(task_id);
assert(itr != _tasks.end());
}
if (TASK_CALLBACK) {
TASK_CALLBACK->onProcessErr(task_id, buffer, size);
}
}
void TaskManager::_on_process_exit(int pid, int64_t exit_status, int term_signal)
{
TaskId task_id;
COMMENT("Tasks lock") {
WriteLockGuard const G(_tasks_lock);
auto itr0 = _pid2task.find(pid);
assert(itr0 != _pid2task.end());
task_id = itr0->second;
auto itr = _tasks.find(task_id);
assert(itr != _tasks.end());
itr->second.done = true;
itr->second.exit_status = exit_status;
itr->second.term_signal = term_signal;
}
tDLogN("TaskManager::_on_process_exit(task_id={},pid={},exit={},signum={}) function was called.",
task_id, pid, exit_status, term_signal);
if (TASK_CALLBACK) {
TASK_CALLBACK->onProcessExit(task_id, exit_status, term_signal);
}
}
ErrTaskId TaskManager::runThread(ThreadParams const & params, void * opaque)
{
auto const task_id = nextTaskId();
libtbag::lock::UvLock lock;
libtbag::lock::UvCondition signal;
bool init_task_end = false;
// [IMPORTANT] Before adding a task, to prevent access from a new thread.
WriteLockGuard const G(_tasks_lock);
_threads_lock.writeLock();
auto const thread_id = _threads.createThread([this, params, opaque, task_id, &lock, &signal, &init_task_end](){
__init_task_thread(this, task_id);
lock.lock();
init_task_end = true;
signal.signal();
lock.unlock();
if (params.runner) {
params.runner();
}
_on_thread_exit(task_id, EXIT_SUCCESS, 0);
});
_threads_lock.writeUnlock();
if (thread_id == uthread()) {
return E_CREATE;
}
TaskInfo info = {};
info.type = TaskType::TT_THREAD;
info.internal_id = createThreadTaskId(thread_id);
info.done = false;
info.exit_status = 0;
info.term_signal = 0;
info.opaque = opaque;
auto const task_insert_result = _tasks.emplace(task_id, info).second;
assert(task_insert_result);
// Do not unlock until the signal is registered.
lock.lock();
while (!init_task_end) {
signal.wait(lock);
}
lock.unlock();
return { E_SUCCESS, task_id };
}
ErrTaskId TaskManager::runProcess(ProcessParams const & params, void * opaque)
{
auto const task_id = nextTaskId();
// [IMPORTANT] Before adding a task, to prevent access from a new thread.
WriteLockGuard const G(_tasks_lock);
_processes_lock.writeLock();
auto const pid = _processes.exec(params.file, params.args, params.envs, params.cwd, params.input);
_processes_lock.writeUnlock();
if (pid == 0) {
return E_CREATE;
}
TaskInfo info = {};
info.type = TaskType::TT_PROCESS;
info.internal_id = createProcessTaskId(pid);
info.done = false;
info.exit_status = 0;
info.term_signal = 0;
info.opaque = opaque;
auto const task_insert_result = _tasks.emplace(task_id, info).second;
assert(task_insert_result);
auto const pid_insert_result = _pid2task.emplace(pid, task_id).second;
assert(pid_insert_result);
return { E_SUCCESS, task_id };
}
Err TaskManager::join(TaskId id)
{
auto const err_task_info = getTaskInfo(id);
if (!err_task_info) {
return err_task_info.code;
}
auto const & task_info = err_task_info.value;
// [IMPORTANT] Do not change the calling order.
if (task_info.type == TaskType::TT_PROCESS) {
auto const pid = task_info.internal_id.process;
tDLogN("TaskManager::join(task_id={}) Process ID: {}", id, pid);
WriteLockGuard const G2(_processes_lock);
return _processes.join(pid);
} else {
assert(task_info.type == TaskType::TT_THREAD);
auto const thread_id = task_info.internal_id.thread;
tDLogN("TaskManager::join(task_id={}) Thread ID: {}", id, (void*)thread_id);
WriteLockGuard const G2(_threads_lock);
return _threads.join(thread_id, true);
}
}
Err TaskManager::erase(TaskId id)
{
auto const err_task_info = getTaskInfo(id);
if (!err_task_info) {
return err_task_info.code;
}
auto const & task_info = err_task_info.value;
// [IMPORTANT] Do not change the calling order.
if (task_info.type == TaskType::TT_PROCESS) {
WriteLockGuard const G2(_processes_lock);
auto const erase_result = _processes.erase(task_info.internal_id.process);
assert(erase_result);
} else {
assert(task_info.type == TaskType::TT_THREAD);
WriteLockGuard const G2(_threads_lock);
auto const erase_result = _threads.erase(task_info.internal_id.thread);
assert(erase_result);
}
// [IMPORTANT] Do not change the calling order.
WriteLockGuard const G2(_tasks_lock);
if (task_info.type == TaskType::TT_PROCESS) {
auto const pid2task_erase_result = _pid2task.erase(task_info.internal_id.process);
assert(pid2task_erase_result == 1u);
}
return _tasks.erase(id) == 1u ? E_SUCCESS : E_ERASE;
}
Err TaskManager::kill(TaskId id)
{
auto const err_task_info = getTaskInfo(id);
if (!err_task_info) {
return err_task_info.code;
}
auto const & task_info = err_task_info.value;
// [IMPORTANT] Do not change the calling order.
if (task_info.type == TaskType::TT_PROCESS) {
auto const pid = task_info.internal_id.process;
tDLogN("TaskManager::kill(task_id={}) Process ID: {}", id, pid);
WriteLockGuard const G2(_processes_lock);
return _processes.kill(pid, libtbag::signal::TBAG_SIGNAL_KILL);
} else {
assert(task_info.type == TaskType::TT_THREAD);
auto const thread_id = task_info.internal_id.thread;
tDLogN("TaskManager::kill(task_id={}) Thread ID: {}", id, (void*)thread_id);
if (isWindowsPlatform()) {
// [IMPORTANT]
// On Windows platforms, the thread terminates immediately.
// Therefore, you must manipulate the attribute yourself.
WriteLockGuard const G2(_tasks_lock);
auto const itr = _tasks.find(id);
if (itr == _tasks.end()) {
return E_NFOUND;
}
if (itr->second.done) {
return E_ALREADY;
}
WriteLockGuard const G3(_threads_lock);
auto const cancel_result = _threads.cancel(thread_id);
if (isSuccess(cancel_result)) {
itr->second.done = true;
itr->second.exit_status = EXIT_FAILURE;
itr->second.term_signal = THREAD_TASK_KILL_SIGNAL;
}
if (TASK_CALLBACK) {
TASK_CALLBACK->onThreadExit(id, EXIT_FAILURE, THREAD_TASK_KILL_SIGNAL);
}
return cancel_result;
} else {
WriteLockGuard const G3(_threads_lock);
return _threads.kill(thread_id, THREAD_TASK_KILL_SIGNAL);
}
}
}
} // namespace task
// --------------------
NAMESPACE_LIBTBAG_CLOSE
// --------------------
<commit_msg>Implement TaskManager::~TaskManager() method.<commit_after>/**
* @file TaskManager.cpp
* @brief TaskManager class implementation.
* @author zer0
* @date 2019-12-19
*/
#include <libtbag/task/TaskManager.hpp>
#include <libtbag/signal/SignalHandler.hpp>
#include <libtbag/thread/ThreadKill.hpp>
#include <libtbag/thread/ThreadLocalStorage.hpp>
#include <libtbag/container/Global.hpp>
#include <libtbag/lock/UvLock.hpp>
#include <libtbag/lock/UvCondition.hpp>
#include <libtbag/log/Log.hpp>
#include <cassert>
#include <memory>
// -------------------
NAMESPACE_LIBTBAG_OPEN
// -------------------
namespace task {
using TaskId = TaskManager::TaskId;
using ErrTaskId = TaskManager::ErrTaskId;
using ErrTaskInfo = TaskManager::ErrTaskInfo;
TBAG_CONSTEXPR static char const * const GLOBAL_MANAGER_REGISTER_KEY =
"libtbag::task::_manager_register";
TBAG_CONSTEXPR static int const THREAD_TASK_KILL_SIGNAL =
libtbag::signal::TBAG_SIGNAL_INTERRUPT;
struct _manager_register TBAG_FINAL : private Noncopyable
{
using Tls = libtbag::thread::ThreadLocalStorage;
Tls mgr;
Tls id;
_manager_register() { /* EMPTY. */ }
~_manager_register() { /* EMPTY. */ }
};
static std::shared_ptr<_manager_register> __get_global_manager_register()
{
using namespace libtbag::container;
auto weak = findGlobalObject<_manager_register>(GLOBAL_MANAGER_REGISTER_KEY);
if (auto shared = weak.lock()) {
return shared;
} else {
return newGlobalObject<_manager_register>(GLOBAL_MANAGER_REGISTER_KEY);
}
}
void __task_int_signal(int signum)
{
auto const shared = __get_global_manager_register();
TaskManager * mgr = shared->mgr.cast<TaskManager>();
TaskId id = (TaskId)(std::intptr_t)shared->id.get();
mgr->_on_thread_exit(id, EXIT_FAILURE, signum);
libtbag::thread::exitThread(EXIT_FAILURE);
}
static void __init_task_thread(TaskManager * mgr, TaskId id)
{
#if !defined(TBAG_PLATFORM_WINDOWS)
auto const shared = __get_global_manager_register();
assert(static_cast<bool>(shared));
shared->mgr.set(mgr);
shared->id.set((void*)(std::intptr_t)id);
std::signal(THREAD_TASK_KILL_SIGNAL, &__task_int_signal);
#endif
}
// --------------------------
// TaskManager implementation
// --------------------------
TaskManager::TaskManager(Callback * cb)
: TASK_CALLBACK(cb), _task_number(BEGIN_TASK_ID)
{
auto const shared = __get_global_manager_register();
assert(static_cast<bool>(shared));
using namespace std::placeholders;
_processes.out_read_cb = std::bind(&TaskManager::_on_process_out, this, _1, _2, _3);
_processes.err_read_cb = std::bind(&TaskManager::_on_process_err, this, _1, _2, _3);
_processes.exit_cb = std::bind(&TaskManager::_on_process_exit, this, _1, _2, _3);
}
TaskManager::~TaskManager()
{
WriteLockGuard const G(_tasks_lock);
_tasks.clear();
_pid2task.clear();
_threads_lock.writeLock();
_threads.clear();
_threads_lock.writeUnlock();
_processes_lock.writeLock();
_processes.clear();
_processes_lock.writeUnlock();
}
TaskId TaskManager::nextTaskId()
{
while (true) {
auto const id = _task_number++;
if (!exists(id)) {
return id;
}
}
}
std::size_t TaskManager::size() const
{
ReadLockGuard const G(_tasks_lock);
return _tasks.size();
}
bool TaskManager::empty() const
{
ReadLockGuard const G(_tasks_lock);
return _tasks.empty();
}
std::vector<TaskId> TaskManager::list() const
{
std::vector<TaskId> result;
ReadLockGuard const G(_tasks_lock);
for (auto const & task : _tasks) {
result.push_back(task.first);
}
return result;
}
TaskManager::TaskMap TaskManager::map() const
{
ReadLockGuard const G(_tasks_lock);
return _tasks;
}
bool TaskManager::exists(TaskId id) const
{
ReadLockGuard const G(_tasks_lock);
return _tasks.find(id) != _tasks.end();
}
ErrTaskInfo TaskManager::getTaskInfo(TaskId id) const
{
ReadLockGuard const G(_tasks_lock);
auto const itr = _tasks.find(id);
if (itr == _tasks.end()) {
return E_NFOUND;
}
return { E_SUCCESS, itr->second };
}
void TaskManager::_on_thread_exit(TaskId id, int64_t exit_status, int term_signal)
{
tDLogN("TaskManager::_on_thread_exit(task_id={},exit={},signum={}) function was called.",
id, exit_status, term_signal);
COMMENT("Tasks lock") {
WriteLockGuard const G(_tasks_lock);
auto itr = _tasks.find(id);
assert(itr != _tasks.end());
itr->second.done = true;
itr->second.exit_status = exit_status;
itr->second.term_signal = term_signal;
}
if (TASK_CALLBACK) {
TASK_CALLBACK->onThreadExit(id, exit_status, term_signal);
}
}
void TaskManager::_on_process_out(int pid, char const * buffer, std::size_t size)
{
TaskId task_id;
COMMENT("Tasks lock") {
ReadLockGuard const G(_tasks_lock);
auto itr0 = _pid2task.find(pid);
assert(itr0 != _pid2task.end());
task_id = itr0->second;
auto itr = _tasks.find(task_id);
assert(itr != _tasks.end());
}
if (TASK_CALLBACK) {
TASK_CALLBACK->onProcessOut(task_id, buffer, size);
}
}
void TaskManager::_on_process_err(int pid, char const * buffer, std::size_t size)
{
TaskId task_id;
COMMENT("Tasks lock") {
ReadLockGuard const G(_tasks_lock);
auto itr0 = _pid2task.find(pid);
assert(itr0 != _pid2task.end());
task_id = itr0->second;
auto itr = _tasks.find(task_id);
assert(itr != _tasks.end());
}
if (TASK_CALLBACK) {
TASK_CALLBACK->onProcessErr(task_id, buffer, size);
}
}
void TaskManager::_on_process_exit(int pid, int64_t exit_status, int term_signal)
{
TaskId task_id;
COMMENT("Tasks lock") {
WriteLockGuard const G(_tasks_lock);
auto itr0 = _pid2task.find(pid);
assert(itr0 != _pid2task.end());
task_id = itr0->second;
auto itr = _tasks.find(task_id);
assert(itr != _tasks.end());
itr->second.done = true;
itr->second.exit_status = exit_status;
itr->second.term_signal = term_signal;
}
tDLogN("TaskManager::_on_process_exit(task_id={},pid={},exit={},signum={}) function was called.",
task_id, pid, exit_status, term_signal);
if (TASK_CALLBACK) {
TASK_CALLBACK->onProcessExit(task_id, exit_status, term_signal);
}
}
ErrTaskId TaskManager::runThread(ThreadParams const & params, void * opaque)
{
auto const task_id = nextTaskId();
libtbag::lock::UvLock lock;
libtbag::lock::UvCondition signal;
bool init_task_end = false;
// [IMPORTANT] Before adding a task, to prevent access from a new thread.
WriteLockGuard const G(_tasks_lock);
_threads_lock.writeLock();
auto const thread_id = _threads.createThread([this, params, opaque, task_id, &lock, &signal, &init_task_end](){
__init_task_thread(this, task_id);
lock.lock();
init_task_end = true;
signal.signal();
lock.unlock();
if (params.runner) {
params.runner();
}
_on_thread_exit(task_id, EXIT_SUCCESS, 0);
});
_threads_lock.writeUnlock();
if (thread_id == uthread()) {
return E_CREATE;
}
TaskInfo info = {};
info.type = TaskType::TT_THREAD;
info.internal_id = createThreadTaskId(thread_id);
info.done = false;
info.exit_status = 0;
info.term_signal = 0;
info.opaque = opaque;
auto const task_insert_result = _tasks.emplace(task_id, info).second;
assert(task_insert_result);
// Do not unlock until the signal is registered.
lock.lock();
while (!init_task_end) {
signal.wait(lock);
}
lock.unlock();
return { E_SUCCESS, task_id };
}
ErrTaskId TaskManager::runProcess(ProcessParams const & params, void * opaque)
{
auto const task_id = nextTaskId();
// [IMPORTANT] Before adding a task, to prevent access from a new thread.
WriteLockGuard const G(_tasks_lock);
_processes_lock.writeLock();
auto const pid = _processes.exec(params.file, params.args, params.envs, params.cwd, params.input);
_processes_lock.writeUnlock();
if (pid == 0) {
return E_CREATE;
}
TaskInfo info = {};
info.type = TaskType::TT_PROCESS;
info.internal_id = createProcessTaskId(pid);
info.done = false;
info.exit_status = 0;
info.term_signal = 0;
info.opaque = opaque;
auto const task_insert_result = _tasks.emplace(task_id, info).second;
assert(task_insert_result);
auto const pid_insert_result = _pid2task.emplace(pid, task_id).second;
assert(pid_insert_result);
return { E_SUCCESS, task_id };
}
Err TaskManager::join(TaskId id)
{
auto const err_task_info = getTaskInfo(id);
if (!err_task_info) {
return err_task_info.code;
}
auto const & task_info = err_task_info.value;
// [IMPORTANT] Do not change the calling order.
if (task_info.type == TaskType::TT_PROCESS) {
auto const pid = task_info.internal_id.process;
tDLogN("TaskManager::join(task_id={}) Process ID: {}", id, pid);
WriteLockGuard const G2(_processes_lock);
return _processes.join(pid);
} else {
assert(task_info.type == TaskType::TT_THREAD);
auto const thread_id = task_info.internal_id.thread;
tDLogN("TaskManager::join(task_id={}) Thread ID: {}", id, (void*)thread_id);
WriteLockGuard const G2(_threads_lock);
return _threads.join(thread_id, true);
}
}
Err TaskManager::erase(TaskId id)
{
auto const err_task_info = getTaskInfo(id);
if (!err_task_info) {
return err_task_info.code;
}
auto const & task_info = err_task_info.value;
// [IMPORTANT] Do not change the calling order.
if (task_info.type == TaskType::TT_PROCESS) {
WriteLockGuard const G2(_processes_lock);
auto const erase_result = _processes.erase(task_info.internal_id.process);
assert(erase_result);
} else {
assert(task_info.type == TaskType::TT_THREAD);
WriteLockGuard const G2(_threads_lock);
auto const erase_result = _threads.erase(task_info.internal_id.thread);
assert(erase_result);
}
// [IMPORTANT] Do not change the calling order.
WriteLockGuard const G2(_tasks_lock);
if (task_info.type == TaskType::TT_PROCESS) {
auto const pid2task_erase_result = _pid2task.erase(task_info.internal_id.process);
assert(pid2task_erase_result == 1u);
}
return _tasks.erase(id) == 1u ? E_SUCCESS : E_ERASE;
}
Err TaskManager::kill(TaskId id)
{
auto const err_task_info = getTaskInfo(id);
if (!err_task_info) {
return err_task_info.code;
}
auto const & task_info = err_task_info.value;
// [IMPORTANT] Do not change the calling order.
if (task_info.type == TaskType::TT_PROCESS) {
auto const pid = task_info.internal_id.process;
tDLogN("TaskManager::kill(task_id={}) Process ID: {}", id, pid);
WriteLockGuard const G2(_processes_lock);
return _processes.kill(pid, libtbag::signal::TBAG_SIGNAL_KILL);
} else {
assert(task_info.type == TaskType::TT_THREAD);
auto const thread_id = task_info.internal_id.thread;
tDLogN("TaskManager::kill(task_id={}) Thread ID: {}", id, (void*)thread_id);
if (isWindowsPlatform()) {
// [IMPORTANT]
// On Windows platforms, the thread terminates immediately.
// Therefore, you must manipulate the attribute yourself.
WriteLockGuard const G2(_tasks_lock);
auto const itr = _tasks.find(id);
if (itr == _tasks.end()) {
return E_NFOUND;
}
if (itr->second.done) {
return E_ALREADY;
}
WriteLockGuard const G3(_threads_lock);
auto const cancel_result = _threads.cancel(thread_id);
if (isSuccess(cancel_result)) {
itr->second.done = true;
itr->second.exit_status = EXIT_FAILURE;
itr->second.term_signal = THREAD_TASK_KILL_SIGNAL;
}
if (TASK_CALLBACK) {
TASK_CALLBACK->onThreadExit(id, EXIT_FAILURE, THREAD_TASK_KILL_SIGNAL);
}
return cancel_result;
} else {
WriteLockGuard const G3(_threads_lock);
return _threads.kill(thread_id, THREAD_TASK_KILL_SIGNAL);
}
}
}
} // namespace task
// --------------------
NAMESPACE_LIBTBAG_CLOSE
// --------------------
<|endoftext|> |
<commit_before>// Copyright (c) 2011-2015 The Bitcoin Core developers
// Copyright (c) 2014-2019 The Dash Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <qt/sendcoinsentry.h>
#include <qt/forms/ui_sendcoinsentry.h>
#include <qt/addressbookpage.h>
#include <qt/addresstablemodel.h>
#include <qt/guiutil.h>
#include <qt/optionsmodel.h>
#include <qt/platformstyle.h>
#include <QApplication>
#include <QClipboard>
SendCoinsEntry::SendCoinsEntry(const PlatformStyle *_platformStyle, QWidget *parent) :
QStackedWidget(parent),
ui(new Ui::SendCoinsEntry),
model(0),
platformStyle(_platformStyle)
{
ui->setupUi(this);
setCurrentWidget(ui->SendCoins);
if (platformStyle->getUseExtraSpacing())
ui->payToLayout->setSpacing(4);
ui->addAsLabel->setPlaceholderText(tr("Enter a label for this address to add it to your address book"));
// These icons are needed on Mac also!
ui->addressBookButton->setIcon(QIcon(":/icons/address-book"));
ui->pasteButton->setIcon(QIcon(":/icons/editpaste"));
ui->deleteButton->setIcon(QIcon(":/icons/remove"));
ui->deleteButton_is->setIcon(QIcon(":/icons/remove"));
ui->deleteButton_s->setIcon(QIcon(":/icons/remove"));
// normal dash address field
GUIUtil::setupAddressWidget(ui->payTo, this, true);
// just a label for displaying dash address(es)
ui->payTo_is->setFont(GUIUtil::fixedPitchFont());
// Connect signals
connect(ui->payAmount, SIGNAL(valueChanged()), this, SIGNAL(payAmountChanged()));
connect(ui->checkboxSubtractFeeFromAmount, SIGNAL(toggled(bool)), this, SIGNAL(subtractFeeFromAmountChanged()));
connect(ui->deleteButton, SIGNAL(clicked()), this, SLOT(deleteClicked()));
connect(ui->deleteButton_is, SIGNAL(clicked()), this, SLOT(deleteClicked()));
connect(ui->deleteButton_s, SIGNAL(clicked()), this, SLOT(deleteClicked()));
connect(ui->useAvailableBalanceButton, SIGNAL(clicked()), this, SLOT(useAvailableBalanceClicked()));
}
SendCoinsEntry::~SendCoinsEntry()
{
delete ui;
}
void SendCoinsEntry::on_pasteButton_clicked()
{
// Paste text from clipboard into recipient field
ui->payTo->setText(QApplication::clipboard()->text());
}
void SendCoinsEntry::on_addressBookButton_clicked()
{
if(!model)
return;
AddressBookPage dlg(platformStyle, AddressBookPage::ForSelection, AddressBookPage::SendingTab, this);
dlg.setModel(model->getAddressTableModel());
if(dlg.exec())
{
ui->payTo->setText(dlg.getReturnValue());
ui->payAmount->setFocus();
}
}
void SendCoinsEntry::on_payTo_textChanged(const QString &address)
{
SendCoinsRecipient rcp;
if (GUIUtil::parseBitcoinURI(address, &rcp)) {
ui->payTo->blockSignals(true);
setValue(rcp);
ui->payTo->blockSignals(false);
} else {
updateLabel(rcp.address);
}
}
void SendCoinsEntry::setModel(WalletModel *_model)
{
this->model = _model;
if (_model && _model->getOptionsModel())
connect(_model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));
clear();
}
void SendCoinsEntry::clear()
{
// clear UI elements for normal payment
ui->payTo->clear();
ui->addAsLabel->clear();
ui->payAmount->clear();
ui->checkboxSubtractFeeFromAmount->setCheckState(Qt::Unchecked);
ui->messageTextLabel->clear();
ui->messageTextLabel->hide();
ui->messageLabel->hide();
// clear UI elements for unauthenticated payment request
ui->payTo_is->clear();
ui->memoTextLabel_is->clear();
ui->payAmount_is->clear();
// clear UI elements for authenticated payment request
ui->payTo_s->clear();
ui->memoTextLabel_s->clear();
ui->payAmount_s->clear();
// update the display unit, to not use the default ("BTC")
updateDisplayUnit();
}
void SendCoinsEntry::checkSubtractFeeFromAmount()
{
ui->checkboxSubtractFeeFromAmount->setChecked(true);
}
void SendCoinsEntry::deleteClicked()
{
Q_EMIT removeEntry(this);
}
void SendCoinsEntry::useAvailableBalanceClicked()
{
Q_EMIT useAvailableBalance(this);
}
bool SendCoinsEntry::validate()
{
if (!model)
return false;
// Check input validity
bool retval = true;
// Skip checks for payment request
if (recipient.paymentRequest.IsInitialized())
return retval;
if (!model->validateAddress(ui->payTo->text()))
{
ui->payTo->setValid(false);
retval = false;
}
if (!ui->payAmount->validate())
{
retval = false;
}
// Sending a zero amount is invalid
if (ui->payAmount->value(0) <= 0)
{
ui->payAmount->setValid(false);
retval = false;
}
// Reject dust outputs:
if (retval && GUIUtil::isDust(ui->payTo->text(), ui->payAmount->value())) {
ui->payAmount->setValid(false);
retval = false;
}
return retval;
}
SendCoinsRecipient SendCoinsEntry::getValue()
{
// Payment request
if (recipient.paymentRequest.IsInitialized())
return recipient;
// Normal payment
recipient.address = ui->payTo->text();
recipient.label = ui->addAsLabel->text();
recipient.amount = ui->payAmount->value();
recipient.message = ui->messageTextLabel->text();
recipient.fSubtractFeeFromAmount = (ui->checkboxSubtractFeeFromAmount->checkState() == Qt::Checked);
return recipient;
}
QWidget *SendCoinsEntry::setupTabChain(QWidget *prev)
{
QWidget::setTabOrder(prev, ui->payTo);
QWidget::setTabOrder(ui->payTo, ui->addAsLabel);
QWidget *w = ui->payAmount->setupTabChain(ui->addAsLabel);
QWidget::setTabOrder(w, ui->checkboxSubtractFeeFromAmount);
QWidget::setTabOrder(ui->checkboxSubtractFeeFromAmount, ui->addressBookButton);
QWidget::setTabOrder(ui->addressBookButton, ui->pasteButton);
QWidget::setTabOrder(ui->pasteButton, ui->deleteButton);
return ui->deleteButton;
}
void SendCoinsEntry::setValue(const SendCoinsRecipient &value)
{
recipient = value;
if (recipient.paymentRequest.IsInitialized()) // payment request
{
if (recipient.authenticatedMerchant.isEmpty()) // unauthenticated
{
ui->payTo_is->setText(recipient.address);
ui->memoTextLabel_is->setText(recipient.message);
ui->payAmount_is->setValue(recipient.amount);
ui->payAmount_is->setReadOnly(true);
setCurrentWidget(ui->SendCoins_UnauthenticatedPaymentRequest);
}
else // authenticated
{
ui->payTo_s->setText(recipient.authenticatedMerchant);
ui->memoTextLabel_s->setText(recipient.message);
ui->payAmount_s->setValue(recipient.amount);
ui->payAmount_s->setReadOnly(true);
setCurrentWidget(ui->SendCoins_AuthenticatedPaymentRequest);
}
}
else // normal payment
{
// message
ui->messageTextLabel->setText(recipient.message);
ui->messageTextLabel->setVisible(!recipient.message.isEmpty());
ui->messageLabel->setVisible(!recipient.message.isEmpty());
ui->payTo->setText(recipient.address);
ui->addAsLabel->setText(recipient.label);
ui->payAmount->setValue(recipient.amount);
}
updateLabel(recipient.address);
}
void SendCoinsEntry::setAddress(const QString &address)
{
ui->payTo->setText(address);
ui->payAmount->setFocus();
}
void SendCoinsEntry::setAmount(const CAmount &amount)
{
ui->payAmount->setValue(amount);
}
bool SendCoinsEntry::isClear()
{
return ui->payTo->text().isEmpty() && ui->payTo_is->text().isEmpty() && ui->payTo_s->text().isEmpty();
}
void SendCoinsEntry::setFocus()
{
ui->payTo->setFocus();
}
void SendCoinsEntry::updateDisplayUnit()
{
if(model && model->getOptionsModel())
{
// Update payAmount with the current unit
ui->payAmount->setDisplayUnit(model->getOptionsModel()->getDisplayUnit());
ui->payAmount_is->setDisplayUnit(model->getOptionsModel()->getDisplayUnit());
ui->payAmount_s->setDisplayUnit(model->getOptionsModel()->getDisplayUnit());
}
}
bool SendCoinsEntry::updateLabel(const QString &address)
{
if(!model)
return false;
// Fill in label from address book, if address has an associated label
QString associatedLabel = model->getAddressTableModel()->labelForAddress(address);
if(!associatedLabel.isEmpty())
{
ui->addAsLabel->setText(associatedLabel);
return true;
}
return false;
}
<commit_msg>qt: Fix label updates in SendCoinsEntry (#3523)<commit_after>// Copyright (c) 2011-2015 The Bitcoin Core developers
// Copyright (c) 2014-2019 The Dash Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <qt/sendcoinsentry.h>
#include <qt/forms/ui_sendcoinsentry.h>
#include <qt/addressbookpage.h>
#include <qt/addresstablemodel.h>
#include <qt/guiutil.h>
#include <qt/optionsmodel.h>
#include <qt/platformstyle.h>
#include <QApplication>
#include <QClipboard>
SendCoinsEntry::SendCoinsEntry(const PlatformStyle *_platformStyle, QWidget *parent) :
QStackedWidget(parent),
ui(new Ui::SendCoinsEntry),
model(0),
platformStyle(_platformStyle)
{
ui->setupUi(this);
setCurrentWidget(ui->SendCoins);
if (platformStyle->getUseExtraSpacing())
ui->payToLayout->setSpacing(4);
ui->addAsLabel->setPlaceholderText(tr("Enter a label for this address to add it to your address book"));
// These icons are needed on Mac also!
ui->addressBookButton->setIcon(QIcon(":/icons/address-book"));
ui->pasteButton->setIcon(QIcon(":/icons/editpaste"));
ui->deleteButton->setIcon(QIcon(":/icons/remove"));
ui->deleteButton_is->setIcon(QIcon(":/icons/remove"));
ui->deleteButton_s->setIcon(QIcon(":/icons/remove"));
// normal dash address field
GUIUtil::setupAddressWidget(ui->payTo, this, true);
// just a label for displaying dash address(es)
ui->payTo_is->setFont(GUIUtil::fixedPitchFont());
// Connect signals
connect(ui->payAmount, SIGNAL(valueChanged()), this, SIGNAL(payAmountChanged()));
connect(ui->checkboxSubtractFeeFromAmount, SIGNAL(toggled(bool)), this, SIGNAL(subtractFeeFromAmountChanged()));
connect(ui->deleteButton, SIGNAL(clicked()), this, SLOT(deleteClicked()));
connect(ui->deleteButton_is, SIGNAL(clicked()), this, SLOT(deleteClicked()));
connect(ui->deleteButton_s, SIGNAL(clicked()), this, SLOT(deleteClicked()));
connect(ui->useAvailableBalanceButton, SIGNAL(clicked()), this, SLOT(useAvailableBalanceClicked()));
}
SendCoinsEntry::~SendCoinsEntry()
{
delete ui;
}
void SendCoinsEntry::on_pasteButton_clicked()
{
// Paste text from clipboard into recipient field
ui->payTo->setText(QApplication::clipboard()->text());
}
void SendCoinsEntry::on_addressBookButton_clicked()
{
if(!model)
return;
AddressBookPage dlg(platformStyle, AddressBookPage::ForSelection, AddressBookPage::SendingTab, this);
dlg.setModel(model->getAddressTableModel());
if(dlg.exec())
{
ui->payTo->setText(dlg.getReturnValue());
ui->payAmount->setFocus();
}
}
void SendCoinsEntry::on_payTo_textChanged(const QString &address)
{
SendCoinsRecipient rcp;
if (GUIUtil::parseBitcoinURI(address, &rcp)) {
ui->payTo->blockSignals(true);
setValue(rcp);
ui->payTo->blockSignals(false);
} else {
updateLabel(address);
}
}
void SendCoinsEntry::setModel(WalletModel *_model)
{
this->model = _model;
if (_model && _model->getOptionsModel())
connect(_model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));
clear();
}
void SendCoinsEntry::clear()
{
// clear UI elements for normal payment
ui->payTo->clear();
ui->addAsLabel->clear();
ui->payAmount->clear();
ui->checkboxSubtractFeeFromAmount->setCheckState(Qt::Unchecked);
ui->messageTextLabel->clear();
ui->messageTextLabel->hide();
ui->messageLabel->hide();
// clear UI elements for unauthenticated payment request
ui->payTo_is->clear();
ui->memoTextLabel_is->clear();
ui->payAmount_is->clear();
// clear UI elements for authenticated payment request
ui->payTo_s->clear();
ui->memoTextLabel_s->clear();
ui->payAmount_s->clear();
// update the display unit, to not use the default ("BTC")
updateDisplayUnit();
}
void SendCoinsEntry::checkSubtractFeeFromAmount()
{
ui->checkboxSubtractFeeFromAmount->setChecked(true);
}
void SendCoinsEntry::deleteClicked()
{
Q_EMIT removeEntry(this);
}
void SendCoinsEntry::useAvailableBalanceClicked()
{
Q_EMIT useAvailableBalance(this);
}
bool SendCoinsEntry::validate()
{
if (!model)
return false;
// Check input validity
bool retval = true;
// Skip checks for payment request
if (recipient.paymentRequest.IsInitialized())
return retval;
if (!model->validateAddress(ui->payTo->text()))
{
ui->payTo->setValid(false);
retval = false;
}
if (!ui->payAmount->validate())
{
retval = false;
}
// Sending a zero amount is invalid
if (ui->payAmount->value(0) <= 0)
{
ui->payAmount->setValid(false);
retval = false;
}
// Reject dust outputs:
if (retval && GUIUtil::isDust(ui->payTo->text(), ui->payAmount->value())) {
ui->payAmount->setValid(false);
retval = false;
}
return retval;
}
SendCoinsRecipient SendCoinsEntry::getValue()
{
// Payment request
if (recipient.paymentRequest.IsInitialized())
return recipient;
// Normal payment
recipient.address = ui->payTo->text();
recipient.label = ui->addAsLabel->text();
recipient.amount = ui->payAmount->value();
recipient.message = ui->messageTextLabel->text();
recipient.fSubtractFeeFromAmount = (ui->checkboxSubtractFeeFromAmount->checkState() == Qt::Checked);
return recipient;
}
QWidget *SendCoinsEntry::setupTabChain(QWidget *prev)
{
QWidget::setTabOrder(prev, ui->payTo);
QWidget::setTabOrder(ui->payTo, ui->addAsLabel);
QWidget *w = ui->payAmount->setupTabChain(ui->addAsLabel);
QWidget::setTabOrder(w, ui->checkboxSubtractFeeFromAmount);
QWidget::setTabOrder(ui->checkboxSubtractFeeFromAmount, ui->addressBookButton);
QWidget::setTabOrder(ui->addressBookButton, ui->pasteButton);
QWidget::setTabOrder(ui->pasteButton, ui->deleteButton);
return ui->deleteButton;
}
void SendCoinsEntry::setValue(const SendCoinsRecipient &value)
{
recipient = value;
if (recipient.paymentRequest.IsInitialized()) // payment request
{
if (recipient.authenticatedMerchant.isEmpty()) // unauthenticated
{
ui->payTo_is->setText(recipient.address);
ui->memoTextLabel_is->setText(recipient.message);
ui->payAmount_is->setValue(recipient.amount);
ui->payAmount_is->setReadOnly(true);
setCurrentWidget(ui->SendCoins_UnauthenticatedPaymentRequest);
}
else // authenticated
{
ui->payTo_s->setText(recipient.authenticatedMerchant);
ui->memoTextLabel_s->setText(recipient.message);
ui->payAmount_s->setValue(recipient.amount);
ui->payAmount_s->setReadOnly(true);
setCurrentWidget(ui->SendCoins_AuthenticatedPaymentRequest);
}
}
else // normal payment
{
// message
ui->messageTextLabel->setText(recipient.message);
ui->messageTextLabel->setVisible(!recipient.message.isEmpty());
ui->messageLabel->setVisible(!recipient.message.isEmpty());
ui->payTo->setText(recipient.address);
ui->addAsLabel->setText(recipient.label);
ui->payAmount->setValue(recipient.amount);
}
updateLabel(recipient.address);
}
void SendCoinsEntry::setAddress(const QString &address)
{
ui->payTo->setText(address);
ui->payAmount->setFocus();
}
void SendCoinsEntry::setAmount(const CAmount &amount)
{
ui->payAmount->setValue(amount);
}
bool SendCoinsEntry::isClear()
{
return ui->payTo->text().isEmpty() && ui->payTo_is->text().isEmpty() && ui->payTo_s->text().isEmpty();
}
void SendCoinsEntry::setFocus()
{
ui->payTo->setFocus();
}
void SendCoinsEntry::updateDisplayUnit()
{
if(model && model->getOptionsModel())
{
// Update payAmount with the current unit
ui->payAmount->setDisplayUnit(model->getOptionsModel()->getDisplayUnit());
ui->payAmount_is->setDisplayUnit(model->getOptionsModel()->getDisplayUnit());
ui->payAmount_s->setDisplayUnit(model->getOptionsModel()->getDisplayUnit());
}
}
bool SendCoinsEntry::updateLabel(const QString &address)
{
if(!model)
return false;
// Fill in label from address book, if address has an associated label
QString associatedLabel = model->getAddressTableModel()->labelForAddress(address);
if(!associatedLabel.isEmpty())
{
ui->addAsLabel->setText(associatedLabel);
return true;
}
return false;
}
<|endoftext|> |
<commit_before><commit_msg>Calculate shadow far plane<commit_after><|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: MABQueryHelper.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: dkenny $ $Date: 2001-05-28 22:02:59 $
*
* 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 _CONNECTIVITY_MAB_QUERYHELPER_HXX_
#define _CONNECTIVITY_MAB_QUERYHELPER_HXX_
#include <MABNSInclude.hxx>
#include <sal/types.h>
#include <map>
#include <vector>
#include <rtl/ustring.hxx>
#include <osl/mutex.hxx>
#include <osl/conditn.hxx>
namespace connectivity
{
namespace mozaddressbook
{
class OMozabQueryHelperResultEntry
{
private:
mutable ::osl::Mutex m_aMutex;
struct ltstr
{
sal_Bool operator()( const ::rtl::OUString &s1, const ::rtl::OUString &s2) const;
};
typedef std::map< rtl::OUString, rtl::OUString, ltstr > fieldMap;
fieldMap m_Fields;
public:
OMozabQueryHelperResultEntry();
~OMozabQueryHelperResultEntry();
void insert( rtl::OUString &key, rtl::OUString &value );
rtl::OUString getValue( const rtl::OUString &key ) const;
};
class OMozabQueryHelper : public nsIAbDirectoryQueryResultListener
{
private:
typedef std::vector< OMozabQueryHelperResultEntry* > resultsArray;
mutable ::osl::Mutex m_aMutex;
::osl::Condition m_aCondition;
resultsArray m_aResults;
sal_Int32 m_nIndex;
sal_Bool m_bHasMore;
sal_Bool m_bAtEnd;
sal_Bool m_bQueryComplete;
void append(OMozabQueryHelperResultEntry* resEnt );
void clear_results();
void clearResultOrComplete();
void notifyResultOrComplete();
void waitForResultOrComplete();
public:
NS_DECL_ISUPPORTS
NS_DECL_NSIABDIRECTORYQUERYRESULTLISTENER
OMozabQueryHelper();
~OMozabQueryHelper();
void reset();
void rewind();
OMozabQueryHelperResultEntry* next();
OMozabQueryHelperResultEntry* getByIndex( sal_Int32 nRow );
sal_Bool hasMore() const;
sal_Bool atEnd() const;
sal_Bool queryComplete() const;
void waitForRow( sal_Int32 rowNum );
sal_Int32 getResultCount() const;
sal_Int32 getRealCount() const;
};
}
}
#endif // _CONNECTIVITY_MAB_QUERYHELPER_HXX_
<commit_msg>Fix for bug #88135 - Endless loop when the ldap connection fails<commit_after>/*************************************************************************
*
* $RCSfile: MABQueryHelper.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: mmaher $ $Date: 2001-07-20 15:34:17 $
*
* 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 _CONNECTIVITY_MAB_QUERYHELPER_HXX_
#define _CONNECTIVITY_MAB_QUERYHELPER_HXX_
#include <MABNSInclude.hxx>
#include <sal/types.h>
#include <map>
#include <vector>
#include <rtl/ustring.hxx>
#include <osl/mutex.hxx>
#include <osl/conditn.hxx>
namespace connectivity
{
namespace mozaddressbook
{
class OMozabQueryHelperResultEntry
{
private:
mutable ::osl::Mutex m_aMutex;
struct ltstr
{
sal_Bool operator()( const ::rtl::OUString &s1, const ::rtl::OUString &s2) const;
};
typedef std::map< rtl::OUString, rtl::OUString, ltstr > fieldMap;
fieldMap m_Fields;
public:
OMozabQueryHelperResultEntry();
~OMozabQueryHelperResultEntry();
void insert( rtl::OUString &key, rtl::OUString &value );
rtl::OUString getValue( const rtl::OUString &key ) const;
};
class OMozabQueryHelper : public nsIAbDirectoryQueryResultListener
{
private:
typedef std::vector< OMozabQueryHelperResultEntry* > resultsArray;
mutable ::osl::Mutex m_aMutex;
::osl::Condition m_aCondition;
resultsArray m_aResults;
sal_Int32 m_nIndex;
sal_Bool m_bHasMore;
sal_Bool m_bAtEnd;
sal_Bool m_bQueryComplete;
void append(OMozabQueryHelperResultEntry* resEnt );
void clear_results();
void clearResultOrComplete();
void notifyResultOrComplete();
void waitForResultOrComplete();
public:
NS_DECL_ISUPPORTS
NS_DECL_NSIABDIRECTORYQUERYRESULTLISTENER
OMozabQueryHelper();
~OMozabQueryHelper();
void reset();
void rewind();
OMozabQueryHelperResultEntry* next();
OMozabQueryHelperResultEntry* getByIndex( sal_Int32 nRow );
sal_Bool hasMore() const;
sal_Bool atEnd() const;
sal_Bool queryComplete() const;
void waitForRow( sal_Int32 rowNum );
sal_Int32 getResultCount() const;
sal_Int32 getRealCount() const;
void notifyQueryError() ;
};
}
}
#endif // _CONNECTIVITY_MAB_QUERYHELPER_HXX_
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: parser.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: obo $ $Date: 2004-03-17 13:34:18 $
*
* 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 _PARSER_HXX
#define _PARSER_HXX
#ifndef _EXPR_HXX
#include "expr.hxx"
#endif
#ifndef _CODEGEN_HXX
#include "codegen.hxx"
#endif
#ifndef _SYMTBL_HXX
#include "symtbl.hxx"
#endif
struct SbiParseStack;
class SbiParser : public SbiTokenizer
{
SbiParseStack* pStack; // Block-Stack
SbiProcDef* pProc; // aktuelle Prozedur
SbiExprNode* pWithVar; // aktuelle With-Variable
SbiToken eEndTok; // das Ende-Token
USHORT nGblChain; // Chainkette fuer globale DIMs
BOOL bGblDefs; // TRUE globale Definitionen allgemein
BOOL bNewGblDefs; // TRUE globale Definitionen vor Sub
BOOL bSingleLineIf; // TRUE einzeiliges if-Statement
SbiSymDef* VarDecl( SbiDimList**,BOOL,BOOL );// Variablen-Deklaration
SbiProcDef* ProcDecl(BOOL bDecl);// Prozedur-Deklaration
void DefStatic( BOOL bPrivate );
void DefProc( BOOL bStatic, BOOL bPrivate ); // Prozedur einlesen
void DefVar( SbiOpcode eOp, BOOL bStatic ); // DIM/REDIM einlesen
void TypeDecl( SbiSymDef&, BOOL bAsNewAlreadyParsed=FALSE ); // AS-Deklaration
void OpenBlock( SbiToken, SbiExprNode* = NULL ); // Block oeffnen
void CloseBlock(); // Block aufloesen
BOOL Channel( BOOL=FALSE ); // Kanalnummer parsen
void StmntBlock( SbiToken ); // Statement-Block abarbeiten
public:
SbxArrayRef rTypeArray; // das Type-Array
SbiStringPool aGblStrings; // der String-Pool
SbiStringPool aLclStrings; // der String-Pool
SbiSymPool aGlobals; // globale Variable
SbiSymPool aPublics; // modulglobale Variable
SbiSymPool aRtlSyms; // Runtime-Library
SbiCodeGen aGen; // Code-Generator
StarBASIC* pBasic; // StarBASIC-Instanz
SbiSymPool* pPool; // aktueller Pool
SbiExprType eCurExpr; // aktueller Expr-Typ
short nBase; // OPTION BASE-Wert
BOOL bText; // OPTION COMPARE TEXT
BOOL bExplicit; // TRUE: OPTION EXPLICIT
SbxDataType eDefTypes[26]; // DEFxxx-Datentypen
SbiParser( StarBASIC*, SbModule* );
BOOL Parse(); // die Aktion
SbiExprNode* GetWithVar(); // Innerste With-Variable liefern
// AB 31.3.1996, Symbol in Runtime-Library suchen
SbiSymDef* CheckRTLForSym( const String& rSym, SbxDataType eType );
void AddConstants( void );
BOOL HasGlobalCode(); // Globaler Code definiert?
BOOL TestToken( SbiToken ); // bestimmtes TOken?
BOOL TestSymbol( BOOL=FALSE ); // Symbol?
BOOL TestComma(); // Komma oder EOLN?
void TestEoln(); // EOLN?
void Symbol(); // Let oder Call
void ErrorStmnt(); // ERROR n
void NotImp(); // nicht implementiert
void BadBlock(); // LOOP/WEND/NEXT
void BadSyntax(); // Falsches SbiToken
void NoIf(); // ELSE/ELSE IF ohne IF
void Assign(); // LET
void Call(); // CALL
void Close(); // CLOSE
void Declare(); // DECLARE
void DefXXX(); // DEFxxx
void Dim(); // DIM
void ReDim(); // ReDim();
void Erase(); // ERASE
void Exit(); // EXIT
void For(); // FOR...NEXT
void Goto(); // GOTO / GOSUB
void If(); // IF
void Input(); // INPUT, INPUT #
void LineInput(); // LINE INPUT, LINE INPUT #
void LSet(); // LSET
void Name(); // NAME .. AS ..
void On(); // ON ERROR/variable
void OnGoto(); // ON...GOTO / GOSUB
void Open(); // OPEN
void Option(); // OPTION
void Print(); // PRINT, PRINT #
void SubFunc(); // SUB / FUNCTION
void Resume(); // RESUME
void Return(); // RETURN
void RSet(); // RSET
void DoLoop(); // DO...LOOP
void Select(); // SELECT ... CASE
void Set(); // SET
void Static(); // STATIC
void Stop(); // STOP/SYSTEM
void Type(); // TYPE...AS...END TYPE
void While(); // WHILE/WEND
void With(); // WITH
void Write(); // WRITE
// JavaScript-Parsing
void OpenJavaBlock( SbiToken, SbiExprNode* = NULL ); // Block oeffnen
void CloseJavaBlock(); // Block aufloesen
void JavaStmntBlock( SbiToken ); // Statement-Block abarbeiten
void JavaBreak();
void JavaContinue();
void JavaFor();
void JavaFunction();
void JavaIf();
void JavaNew();
void JavaReturn();
void JavaThis();
void JavaVar();
void JavaWhile();
void JavaWith();
};
#endif
<commit_msg>INTEGRATION: CWS ab11clonepp4 (1.2.62); FILE MERGED 2004/10/15 08:39:08 ab 1.2.62.1: #118083# #118084# Class support PP4 -> SO 8<commit_after>/*************************************************************************
*
* $RCSfile: parser.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: pjunck $ $Date: 2004-11-02 11:56:01 $
*
* 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 _PARSER_HXX
#define _PARSER_HXX
#ifndef _EXPR_HXX
#include "expr.hxx"
#endif
#ifndef _CODEGEN_HXX
#include "codegen.hxx"
#endif
#ifndef _SYMTBL_HXX
#include "symtbl.hxx"
#endif
struct SbiParseStack;
class SbiParser : public SbiTokenizer
{
SbiParseStack* pStack; // Block-Stack
SbiProcDef* pProc; // aktuelle Prozedur
SbiExprNode* pWithVar; // aktuelle With-Variable
SbiToken eEndTok; // das Ende-Token
USHORT nGblChain; // Chainkette fuer globale DIMs
BOOL bGblDefs; // TRUE globale Definitionen allgemein
BOOL bNewGblDefs; // TRUE globale Definitionen vor Sub
BOOL bSingleLineIf; // TRUE einzeiliges if-Statement
SbiSymDef* VarDecl( SbiDimList**,BOOL,BOOL );// Variablen-Deklaration
SbiProcDef* ProcDecl(BOOL bDecl);// Prozedur-Deklaration
void DefStatic( BOOL bPrivate );
void DefProc( BOOL bStatic, BOOL bPrivate ); // Prozedur einlesen
void DefVar( SbiOpcode eOp, BOOL bStatic ); // DIM/REDIM einlesen
void TypeDecl( SbiSymDef&, BOOL bAsNewAlreadyParsed=FALSE ); // AS-Deklaration
void OpenBlock( SbiToken, SbiExprNode* = NULL ); // Block oeffnen
void CloseBlock(); // Block aufloesen
BOOL Channel( BOOL=FALSE ); // Kanalnummer parsen
void StmntBlock( SbiToken ); // Statement-Block abarbeiten
public:
SbxArrayRef rTypeArray; // das Type-Array
SbiStringPool aGblStrings; // der String-Pool
SbiStringPool aLclStrings; // der String-Pool
SbiSymPool aGlobals; // globale Variable
SbiSymPool aPublics; // modulglobale Variable
SbiSymPool aRtlSyms; // Runtime-Library
SbiCodeGen aGen; // Code-Generator
StarBASIC* pBasic; // StarBASIC-Instanz
SbiSymPool* pPool; // aktueller Pool
SbiExprType eCurExpr; // aktueller Expr-Typ
short nBase; // OPTION BASE-Wert
BOOL bText; // OPTION COMPARE TEXT
BOOL bExplicit; // TRUE: OPTION EXPLICIT
BOOL bClassModule; // TRUE: OPTION ClassModule
SbxDataType eDefTypes[26]; // DEFxxx-Datentypen
SbiParser( StarBASIC*, SbModule* );
BOOL Parse(); // die Aktion
SbiExprNode* GetWithVar(); // Innerste With-Variable liefern
// AB 31.3.1996, Symbol in Runtime-Library suchen
SbiSymDef* CheckRTLForSym( const String& rSym, SbxDataType eType );
void AddConstants( void );
BOOL HasGlobalCode(); // Globaler Code definiert?
BOOL TestToken( SbiToken ); // bestimmtes TOken?
BOOL TestSymbol( BOOL=FALSE ); // Symbol?
BOOL TestComma(); // Komma oder EOLN?
void TestEoln(); // EOLN?
void Symbol(); // Let oder Call
void ErrorStmnt(); // ERROR n
void NotImp(); // nicht implementiert
void BadBlock(); // LOOP/WEND/NEXT
void BadSyntax(); // Falsches SbiToken
void NoIf(); // ELSE/ELSE IF ohne IF
void Assign(); // LET
void Call(); // CALL
void Close(); // CLOSE
void Declare(); // DECLARE
void DefXXX(); // DEFxxx
void Dim(); // DIM
void ReDim(); // ReDim();
void Erase(); // ERASE
void Exit(); // EXIT
void For(); // FOR...NEXT
void Goto(); // GOTO / GOSUB
void If(); // IF
void Input(); // INPUT, INPUT #
void LineInput(); // LINE INPUT, LINE INPUT #
void LSet(); // LSET
void Name(); // NAME .. AS ..
void On(); // ON ERROR/variable
void OnGoto(); // ON...GOTO / GOSUB
void Open(); // OPEN
void Option(); // OPTION
void Print(); // PRINT, PRINT #
void SubFunc(); // SUB / FUNCTION
void Resume(); // RESUME
void Return(); // RETURN
void RSet(); // RSET
void DoLoop(); // DO...LOOP
void Select(); // SELECT ... CASE
void Set(); // SET
void Static(); // STATIC
void Stop(); // STOP/SYSTEM
void Type(); // TYPE...AS...END TYPE
void While(); // WHILE/WEND
void With(); // WITH
void Write(); // WRITE
// JavaScript-Parsing
void OpenJavaBlock( SbiToken, SbiExprNode* = NULL ); // Block oeffnen
void CloseJavaBlock(); // Block aufloesen
void JavaStmntBlock( SbiToken ); // Statement-Block abarbeiten
void JavaBreak();
void JavaContinue();
void JavaFor();
void JavaFunction();
void JavaIf();
void JavaNew();
void JavaReturn();
void JavaThis();
void JavaVar();
void JavaWhile();
void JavaWith();
};
#endif
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: sbxsng.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: obo $ $Date: 2006-10-12 14:33:50 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_basic.hxx"
#ifndef _ERRCODE_HXX //autogen
#include <tools/errcode.hxx>
#endif
#include "sbx.hxx"
#include "sbxconv.hxx"
float ImpGetSingle( const SbxValues* p )
{
SbxValues aTmp;
float nRes;
start:
switch( p->eType )
{
case SbxNULL:
SbxBase::SetError( SbxERR_CONVERSION );
case SbxEMPTY:
nRes = 0; break;
case SbxCHAR:
nRes = p->nChar; break;
case SbxBYTE:
nRes = p->nByte; break;
case SbxINTEGER:
case SbxBOOL:
nRes = p->nInteger; break;
case SbxERROR:
case SbxUSHORT:
nRes = p->nUShort; break;
case SbxLONG:
nRes = (float) p->nLong; break;
case SbxULONG:
nRes = (float) p->nULong; break;
case SbxSINGLE:
nRes = p->nSingle; break;
case SbxSALINT64:
nRes = (float) p->nInt64; break;
case SbxSALUINT64:
nRes = (float) ImpSalUInt64ToDouble( p->uInt64 ); break;
case SbxDECIMAL:
case SbxBYREF | SbxDECIMAL:
if( p->pDecimal )
p->pDecimal->getSingle( nRes );
else
nRes = 0.0;
break;
case SbxDATE:
case SbxDOUBLE:
case SbxLONG64:
case SbxULONG64:
case SbxCURRENCY:
{
double dVal;
if( p->eType == SbxCURRENCY )
dVal = ImpCurrencyToDouble( p->nLong64 );
else if( p->eType == SbxLONG64 )
dVal = ImpINT64ToDouble( p->nLong64 );
else if( p->eType == SbxULONG64 )
dVal = ImpUINT64ToDouble( p->nULong64 );
else
dVal = p->nDouble;
if( dVal > SbxMAXSNG )
{
SbxBase::SetError( SbxERR_OVERFLOW );
nRes = static_cast< float >(SbxMAXSNG);
}
else if( dVal < SbxMINSNG )
{
SbxBase::SetError( SbxERR_OVERFLOW );
nRes = static_cast< float >(SbxMINSNG);
}
else if( dVal > 0 && dVal < SbxMAXSNG2 )
{
SbxBase::SetError( SbxERR_OVERFLOW );
nRes = static_cast< float >(SbxMAXSNG2);
}
else if( dVal < 0 && dVal > SbxMINSNG2 )
{
SbxBase::SetError( SbxERR_OVERFLOW );
nRes = static_cast< float >(SbxMINSNG2);
}
else
nRes = (float) dVal;
break;
}
case SbxBYREF | SbxSTRING:
case SbxSTRING:
case SbxLPSTR:
if( !p->pString )
nRes = 0;
else
{
double d;
SbxDataType t;
if( ImpScan( *p->pString, d, t, NULL ) != SbxERR_OK )
nRes = 0;
else if( d > SbxMAXSNG )
{
SbxBase::SetError( SbxERR_OVERFLOW );
nRes = static_cast< float >(SbxMAXSNG);
}
else if( d < SbxMINSNG )
{
SbxBase::SetError( SbxERR_OVERFLOW );
nRes = static_cast< float >(SbxMINSNG);
}
else
nRes = (float) d;
}
break;
case SbxOBJECT:
{
SbxValue* pVal = PTR_CAST(SbxValue,p->pObj);
if( pVal )
nRes = pVal->GetSingle();
else
{
SbxBase::SetError( SbxERR_NO_OBJECT ); nRes = 0;
}
break;
}
case SbxBYREF | SbxCHAR:
nRes = *p->pChar; break;
case SbxBYREF | SbxBYTE:
nRes = *p->pByte; break;
case SbxBYREF | SbxINTEGER:
case SbxBYREF | SbxBOOL:
nRes = *p->pInteger; break;
case SbxBYREF | SbxLONG:
nRes = (float) *p->pLong; break;
case SbxBYREF | SbxULONG:
nRes = (float) *p->pULong; break;
case SbxBYREF | SbxERROR:
case SbxBYREF | SbxUSHORT:
nRes = *p->pUShort; break;
case SbxBYREF | SbxSINGLE:
nRes = *p->pSingle; break;
// ab hier muss getestet werden
case SbxBYREF | SbxDATE:
case SbxBYREF | SbxDOUBLE:
aTmp.nDouble = *p->pDouble; goto ref;
case SbxBYREF | SbxULONG64:
aTmp.nULong64 = *p->pULong64; goto ref;
case SbxBYREF | SbxLONG64:
case SbxBYREF | SbxSALINT64:
nRes = (float) *p->pnInt64; break;
case SbxBYREF | SbxSALUINT64:
nRes = (float) ImpSalUInt64ToDouble( *p->puInt64 ); break;
case SbxBYREF | SbxCURRENCY:
aTmp.nLong64 = *p->pLong64; goto ref;
ref:
aTmp.eType = SbxDataType( p->eType & 0x0FFF );
p = &aTmp; goto start;
default:
SbxBase::SetError( SbxERR_CONVERSION ); nRes = 0;
}
return nRes;
}
void ImpPutSingle( SbxValues* p, float n )
{
SbxValues aTmp;
start:
switch( p->eType )
{
case SbxCHAR:
aTmp.pChar = &p->nChar; goto direct;
case SbxBYTE:
aTmp.pByte = &p->nByte; goto direct;
case SbxINTEGER:
case SbxBOOL:
aTmp.pInteger = &p->nInteger; goto direct;
case SbxLONG:
aTmp.pLong = &p->nLong; goto direct;
case SbxULONG:
aTmp.pULong = &p->nULong; goto direct;
case SbxERROR:
case SbxUSHORT:
aTmp.pUShort = &p->nUShort; goto direct;
case SbxULONG64:
aTmp.pULong64 = &p->nULong64; goto direct;
case SbxLONG64:
case SbxCURRENCY:
aTmp.pLong64 = &p->nLong64; goto direct;
case SbxSALINT64:
aTmp.pnInt64 = &p->nInt64; goto direct;
case SbxSALUINT64:
aTmp.puInt64 = &p->uInt64; goto direct;
case SbxDECIMAL:
case SbxBYREF | SbxDECIMAL:
{
SbxDecimal* pDec = ImpCreateDecimal( p );
if( !pDec->setSingle( n ) )
SbxBase::SetError( SbxERR_OVERFLOW );
break;
}
direct:
aTmp.eType = SbxDataType( p->eType | SbxBYREF );
p = &aTmp; goto start;
// keine Tests ab hier
case SbxSINGLE:
p->nSingle = n; break;
case SbxDATE:
case SbxDOUBLE:
p->nDouble = n; break;
case SbxBYREF | SbxSTRING:
case SbxSTRING:
case SbxLPSTR:
{
if( !p->pString )
p->pString = new XubString;
ImpCvtNum( (double) n, 6, *p->pString );
break;
}
case SbxOBJECT:
{
SbxValue* pVal = PTR_CAST(SbxValue,p->pObj);
if( pVal )
pVal->PutSingle( n );
else
SbxBase::SetError( SbxERR_NO_OBJECT );
break;
}
case SbxBYREF | SbxCHAR:
if( n > SbxMAXCHAR )
{
SbxBase::SetError( SbxERR_OVERFLOW ); n = SbxMAXCHAR;
}
else if( n < SbxMINCHAR )
{
SbxBase::SetError( SbxERR_OVERFLOW ); n = SbxMINCHAR;
}
*p->pChar = (xub_Unicode) n; break;
case SbxBYREF | SbxBYTE:
if( n > SbxMAXBYTE )
{
SbxBase::SetError( SbxERR_OVERFLOW ); n = SbxMAXBYTE;
}
else if( n < 0 )
{
SbxBase::SetError( SbxERR_OVERFLOW ); n = 0;
}
*p->pByte = (BYTE) n; break;
case SbxBYREF | SbxINTEGER:
case SbxBYREF | SbxBOOL:
if( n > SbxMAXINT )
{
SbxBase::SetError( SbxERR_OVERFLOW ); n = SbxMAXINT;
}
else if( n < SbxMININT )
{
SbxBase::SetError( SbxERR_OVERFLOW ); n = SbxMININT;
}
*p->pInteger = (INT16) n; break;
case SbxBYREF | SbxERROR:
case SbxBYREF | SbxUSHORT:
if( n > SbxMAXUINT )
{
SbxBase::SetError( SbxERR_OVERFLOW ); n = SbxMAXUINT;
}
else if( n < 0 )
{
SbxBase::SetError( SbxERR_OVERFLOW ); n = 0;
}
*p->pUShort = (UINT16) n; break;
case SbxBYREF | SbxLONG:
{
INT32 i;
if( n > SbxMAXLNG )
{
SbxBase::SetError( SbxERR_OVERFLOW ); i = SbxMAXLNG;
}
else if( n < SbxMINLNG )
{
SbxBase::SetError( SbxERR_OVERFLOW ); i = SbxMINLNG;
}
else
{
i = sal::static_int_cast< INT32 >(n);
}
*p->pLong = i; break;
}
case SbxBYREF | SbxULONG:
{
UINT32 i;
if( n > SbxMAXULNG )
{
SbxBase::SetError( SbxERR_OVERFLOW ); i = SbxMAXULNG;
}
else if( n < 0 )
{
SbxBase::SetError( SbxERR_OVERFLOW ); i = 0;
}
else
{
i = sal::static_int_cast< UINT32 >(n);
}
*p->pULong = i; break;
}
case SbxBYREF | SbxSINGLE:
*p->pSingle = n; break;
case SbxBYREF | SbxDATE:
case SbxBYREF | SbxDOUBLE:
*p->pDouble = (double) n; break;
case SbxBYREF | SbxSALINT64:
*p->pnInt64 = ImpDoubleToSalInt64( (double) n ); break;
case SbxBYREF | SbxSALUINT64:
*p->puInt64 = ImpDoubleToSalUInt64( (double) n ); break;
case SbxBYREF | SbxCURRENCY:
double d;
if( n > SbxMAXCURR )
{
SbxBase::SetError( SbxERR_OVERFLOW ); d = SbxMAXCURR;
}
else if( n < SbxMINCURR )
{
SbxBase::SetError( SbxERR_OVERFLOW ); d = SbxMINCURR;
}
else
{
d = n;
}
*p->pLong64 = ImpDoubleToCurrency( n ); break;
default:
SbxBase::SetError( SbxERR_CONVERSION );
}
}
<commit_msg>INTEGRATION: CWS vgbugs07 (1.5.70); FILE MERGED 2007/06/04 13:22:18 vg 1.5.70.1: #i76605# Remove -I .../inc/module hack introduced by hedaburemove01<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: sbxsng.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: hr $ $Date: 2007-06-27 14:32:01 $
*
* 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_basic.hxx"
#ifndef _ERRCODE_HXX //autogen
#include <tools/errcode.hxx>
#endif
#include <basic/sbx.hxx>
#include "sbxconv.hxx"
float ImpGetSingle( const SbxValues* p )
{
SbxValues aTmp;
float nRes;
start:
switch( p->eType )
{
case SbxNULL:
SbxBase::SetError( SbxERR_CONVERSION );
case SbxEMPTY:
nRes = 0; break;
case SbxCHAR:
nRes = p->nChar; break;
case SbxBYTE:
nRes = p->nByte; break;
case SbxINTEGER:
case SbxBOOL:
nRes = p->nInteger; break;
case SbxERROR:
case SbxUSHORT:
nRes = p->nUShort; break;
case SbxLONG:
nRes = (float) p->nLong; break;
case SbxULONG:
nRes = (float) p->nULong; break;
case SbxSINGLE:
nRes = p->nSingle; break;
case SbxSALINT64:
nRes = (float) p->nInt64; break;
case SbxSALUINT64:
nRes = (float) ImpSalUInt64ToDouble( p->uInt64 ); break;
case SbxDECIMAL:
case SbxBYREF | SbxDECIMAL:
if( p->pDecimal )
p->pDecimal->getSingle( nRes );
else
nRes = 0.0;
break;
case SbxDATE:
case SbxDOUBLE:
case SbxLONG64:
case SbxULONG64:
case SbxCURRENCY:
{
double dVal;
if( p->eType == SbxCURRENCY )
dVal = ImpCurrencyToDouble( p->nLong64 );
else if( p->eType == SbxLONG64 )
dVal = ImpINT64ToDouble( p->nLong64 );
else if( p->eType == SbxULONG64 )
dVal = ImpUINT64ToDouble( p->nULong64 );
else
dVal = p->nDouble;
if( dVal > SbxMAXSNG )
{
SbxBase::SetError( SbxERR_OVERFLOW );
nRes = static_cast< float >(SbxMAXSNG);
}
else if( dVal < SbxMINSNG )
{
SbxBase::SetError( SbxERR_OVERFLOW );
nRes = static_cast< float >(SbxMINSNG);
}
else if( dVal > 0 && dVal < SbxMAXSNG2 )
{
SbxBase::SetError( SbxERR_OVERFLOW );
nRes = static_cast< float >(SbxMAXSNG2);
}
else if( dVal < 0 && dVal > SbxMINSNG2 )
{
SbxBase::SetError( SbxERR_OVERFLOW );
nRes = static_cast< float >(SbxMINSNG2);
}
else
nRes = (float) dVal;
break;
}
case SbxBYREF | SbxSTRING:
case SbxSTRING:
case SbxLPSTR:
if( !p->pString )
nRes = 0;
else
{
double d;
SbxDataType t;
if( ImpScan( *p->pString, d, t, NULL ) != SbxERR_OK )
nRes = 0;
else if( d > SbxMAXSNG )
{
SbxBase::SetError( SbxERR_OVERFLOW );
nRes = static_cast< float >(SbxMAXSNG);
}
else if( d < SbxMINSNG )
{
SbxBase::SetError( SbxERR_OVERFLOW );
nRes = static_cast< float >(SbxMINSNG);
}
else
nRes = (float) d;
}
break;
case SbxOBJECT:
{
SbxValue* pVal = PTR_CAST(SbxValue,p->pObj);
if( pVal )
nRes = pVal->GetSingle();
else
{
SbxBase::SetError( SbxERR_NO_OBJECT ); nRes = 0;
}
break;
}
case SbxBYREF | SbxCHAR:
nRes = *p->pChar; break;
case SbxBYREF | SbxBYTE:
nRes = *p->pByte; break;
case SbxBYREF | SbxINTEGER:
case SbxBYREF | SbxBOOL:
nRes = *p->pInteger; break;
case SbxBYREF | SbxLONG:
nRes = (float) *p->pLong; break;
case SbxBYREF | SbxULONG:
nRes = (float) *p->pULong; break;
case SbxBYREF | SbxERROR:
case SbxBYREF | SbxUSHORT:
nRes = *p->pUShort; break;
case SbxBYREF | SbxSINGLE:
nRes = *p->pSingle; break;
// ab hier muss getestet werden
case SbxBYREF | SbxDATE:
case SbxBYREF | SbxDOUBLE:
aTmp.nDouble = *p->pDouble; goto ref;
case SbxBYREF | SbxULONG64:
aTmp.nULong64 = *p->pULong64; goto ref;
case SbxBYREF | SbxLONG64:
case SbxBYREF | SbxSALINT64:
nRes = (float) *p->pnInt64; break;
case SbxBYREF | SbxSALUINT64:
nRes = (float) ImpSalUInt64ToDouble( *p->puInt64 ); break;
case SbxBYREF | SbxCURRENCY:
aTmp.nLong64 = *p->pLong64; goto ref;
ref:
aTmp.eType = SbxDataType( p->eType & 0x0FFF );
p = &aTmp; goto start;
default:
SbxBase::SetError( SbxERR_CONVERSION ); nRes = 0;
}
return nRes;
}
void ImpPutSingle( SbxValues* p, float n )
{
SbxValues aTmp;
start:
switch( p->eType )
{
case SbxCHAR:
aTmp.pChar = &p->nChar; goto direct;
case SbxBYTE:
aTmp.pByte = &p->nByte; goto direct;
case SbxINTEGER:
case SbxBOOL:
aTmp.pInteger = &p->nInteger; goto direct;
case SbxLONG:
aTmp.pLong = &p->nLong; goto direct;
case SbxULONG:
aTmp.pULong = &p->nULong; goto direct;
case SbxERROR:
case SbxUSHORT:
aTmp.pUShort = &p->nUShort; goto direct;
case SbxULONG64:
aTmp.pULong64 = &p->nULong64; goto direct;
case SbxLONG64:
case SbxCURRENCY:
aTmp.pLong64 = &p->nLong64; goto direct;
case SbxSALINT64:
aTmp.pnInt64 = &p->nInt64; goto direct;
case SbxSALUINT64:
aTmp.puInt64 = &p->uInt64; goto direct;
case SbxDECIMAL:
case SbxBYREF | SbxDECIMAL:
{
SbxDecimal* pDec = ImpCreateDecimal( p );
if( !pDec->setSingle( n ) )
SbxBase::SetError( SbxERR_OVERFLOW );
break;
}
direct:
aTmp.eType = SbxDataType( p->eType | SbxBYREF );
p = &aTmp; goto start;
// keine Tests ab hier
case SbxSINGLE:
p->nSingle = n; break;
case SbxDATE:
case SbxDOUBLE:
p->nDouble = n; break;
case SbxBYREF | SbxSTRING:
case SbxSTRING:
case SbxLPSTR:
{
if( !p->pString )
p->pString = new XubString;
ImpCvtNum( (double) n, 6, *p->pString );
break;
}
case SbxOBJECT:
{
SbxValue* pVal = PTR_CAST(SbxValue,p->pObj);
if( pVal )
pVal->PutSingle( n );
else
SbxBase::SetError( SbxERR_NO_OBJECT );
break;
}
case SbxBYREF | SbxCHAR:
if( n > SbxMAXCHAR )
{
SbxBase::SetError( SbxERR_OVERFLOW ); n = SbxMAXCHAR;
}
else if( n < SbxMINCHAR )
{
SbxBase::SetError( SbxERR_OVERFLOW ); n = SbxMINCHAR;
}
*p->pChar = (xub_Unicode) n; break;
case SbxBYREF | SbxBYTE:
if( n > SbxMAXBYTE )
{
SbxBase::SetError( SbxERR_OVERFLOW ); n = SbxMAXBYTE;
}
else if( n < 0 )
{
SbxBase::SetError( SbxERR_OVERFLOW ); n = 0;
}
*p->pByte = (BYTE) n; break;
case SbxBYREF | SbxINTEGER:
case SbxBYREF | SbxBOOL:
if( n > SbxMAXINT )
{
SbxBase::SetError( SbxERR_OVERFLOW ); n = SbxMAXINT;
}
else if( n < SbxMININT )
{
SbxBase::SetError( SbxERR_OVERFLOW ); n = SbxMININT;
}
*p->pInteger = (INT16) n; break;
case SbxBYREF | SbxERROR:
case SbxBYREF | SbxUSHORT:
if( n > SbxMAXUINT )
{
SbxBase::SetError( SbxERR_OVERFLOW ); n = SbxMAXUINT;
}
else if( n < 0 )
{
SbxBase::SetError( SbxERR_OVERFLOW ); n = 0;
}
*p->pUShort = (UINT16) n; break;
case SbxBYREF | SbxLONG:
{
INT32 i;
if( n > SbxMAXLNG )
{
SbxBase::SetError( SbxERR_OVERFLOW ); i = SbxMAXLNG;
}
else if( n < SbxMINLNG )
{
SbxBase::SetError( SbxERR_OVERFLOW ); i = SbxMINLNG;
}
else
{
i = sal::static_int_cast< INT32 >(n);
}
*p->pLong = i; break;
}
case SbxBYREF | SbxULONG:
{
UINT32 i;
if( n > SbxMAXULNG )
{
SbxBase::SetError( SbxERR_OVERFLOW ); i = SbxMAXULNG;
}
else if( n < 0 )
{
SbxBase::SetError( SbxERR_OVERFLOW ); i = 0;
}
else
{
i = sal::static_int_cast< UINT32 >(n);
}
*p->pULong = i; break;
}
case SbxBYREF | SbxSINGLE:
*p->pSingle = n; break;
case SbxBYREF | SbxDATE:
case SbxBYREF | SbxDOUBLE:
*p->pDouble = (double) n; break;
case SbxBYREF | SbxSALINT64:
*p->pnInt64 = ImpDoubleToSalInt64( (double) n ); break;
case SbxBYREF | SbxSALUINT64:
*p->puInt64 = ImpDoubleToSalUInt64( (double) n ); break;
case SbxBYREF | SbxCURRENCY:
double d;
if( n > SbxMAXCURR )
{
SbxBase::SetError( SbxERR_OVERFLOW ); d = SbxMAXCURR;
}
else if( n < SbxMINCURR )
{
SbxBase::SetError( SbxERR_OVERFLOW ); d = SbxMINCURR;
}
else
{
d = n;
}
*p->pLong64 = ImpDoubleToCurrency( n ); break;
default:
SbxBase::SetError( SbxERR_CONVERSION );
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "paddle/fluid/imperative/layer.h"
#include <deque>
#include <limits>
#include <map>
#include <random>
#include <utility>
#include "paddle/fluid/framework/lod_tensor.h"
#include "paddle/fluid/framework/op_registry.h"
#include "paddle/fluid/string/printf.h"
namespace paddle {
namespace imperative {
using framework::Variable;
void AddTo(Variable* src, Variable* dst) {
framework::LoDTensor* dst_tensor = dst->GetMutable<framework::LoDTensor>();
framework::LoDTensor* src_tensor = src->GetMutable<framework::LoDTensor>();
PADDLE_ENFORCE(dst_tensor->numel() == src_tensor->numel(), "%lld vs %lld",
dst_tensor->numel(), src_tensor->numel());
float* dst_data = dst_tensor->mutable_data<float>(platform::CPUPlace());
const float* src_data = src_tensor->data<float>();
for (size_t i = 0; i < src_tensor->numel(); ++i) {
dst_data[i] += src_data[i];
}
}
class Autograd {
public:
explicit Autograd(framework::Scope* scope) : scope_(scope) {}
void RunBackward(VarBase* var, framework::Variable* grad) {
if (!var->pre_op_) {
var->ApplyGrad(scope_, grad);
return;
}
PADDLE_ENFORCE(var->pre_op_->op_desc_);
// TODO(panyx0718): Only create vars that "require_grad"
std::vector<Variable*> op_grads =
CreateOpGrads(var->pre_op_->output_vars_->size());
op_grads[var->pre_op_out_idx_] = grad;
std::deque<std::pair<OpBase*, std::vector<Variable*>>> ready;
ready.push_back(std::make_pair(var->pre_op_, op_grads));
std::map<OpBase*, int> dep_counts = ComputeDepCounts(var->pre_op_);
std::map<OpBase*, std::vector<Variable*>> visited;
while (!ready.empty()) {
OpBase* ready_op = ready.front().first;
std::vector<Variable*> ready_op_grads = ready.front().second;
ready.pop_front();
std::vector<Variable*> input_grads = ready_op->ApplyGrad(scope_);
for (size_t i = 0; i < input_grads.size(); ++i) {
if (!input_grads[i]) continue;
OpBase* pre_op = ready_op->pre_ops_->at(i);
if (!pre_op) continue;
int pre_op_out_idx = ready_op->pre_ops_out_idx_->at(i);
dep_counts[pre_op] -= 1;
PADDLE_ENFORCE(dep_counts[pre_op] >= 0);
bool pre_op_ready = dep_counts[pre_op] == 0;
if (pre_op_ready) {
if (visited.find(pre_op) == visited.end()) {
PADDLE_ENFORCE(pre_op->output_vars_->size() == 1);
visited[pre_op] = {input_grads[i]};
} else {
std::vector<Variable*>& pre_op_grads = visited[pre_op];
AccumGrads(pre_op_out_idx, input_grads[i], &pre_op_grads);
}
ready.push_back(std::make_pair(pre_op, visited[pre_op]));
} else {
if (visited.find(pre_op) == visited.end()) {
// TODO(panyx0718): Only create vars that "require_grad"
visited[pre_op] = CreateOpGrads(var->pre_op_->output_vars_->size());
} else {
}
std::vector<Variable*>& pre_op_grads = visited[pre_op];
AccumGrads(pre_op_out_idx, input_grads[i], &pre_op_grads);
}
}
}
}
private:
void AccumGrads(int grad_idx, Variable* grad,
std::vector<Variable*>* op_grads) {
if (!(*op_grads)[grad_idx]) {
// FIXME(panyx0718): This should be a deep copy.
(*op_grads)[grad_idx] = grad;
return;
}
AddTo(grad, (*op_grads)[grad_idx]);
}
std::map<OpBase*, int> ComputeDepCounts(OpBase* op) {
std::map<OpBase*, int> ret;
std::deque<OpBase*> queue;
queue.push_back(op);
std::unordered_set<OpBase*> visited;
visited.insert(op);
while (!queue.empty()) {
OpBase* candidate = queue.front();
queue.pop_front();
for (OpBase* pre_op : *(candidate->pre_ops_)) {
if (!pre_op) continue;
if (visited.find(pre_op) == visited.end()) {
visited.insert(pre_op);
queue.push_back(pre_op);
}
ret[pre_op] += 1;
}
}
return ret;
}
std::vector<Variable*> CreateOpGrads(size_t count) {
std::vector<Variable*> op_grads;
for (size_t i = 0; i < count; ++i) {
op_grads.push_back(nullptr);
}
return op_grads;
}
framework::Scope* scope_;
};
framework::Variable* CreateVariable(const std::string& name,
const framework::DDim& dim, float val,
framework::Scope* scope,
bool random_name = true) {
std::string varname = name;
if (random_name) {
std::mt19937 rng;
rng.seed(std::random_device()());
std::uniform_int_distribution<std::mt19937::result_type> dist6(
1, std::numeric_limits<int>::max());
int id = dist6(rng);
varname = string::Sprintf("%s@%d", varname, id);
}
LOG(ERROR) << "creating var " << varname;
framework::Variable* var = scope->Var(varname);
framework::LoDTensor* tensor = var->GetMutable<framework::LoDTensor>();
float* data = tensor->mutable_data<float>(dim, platform::CPUPlace());
std::fill(data, data + tensor->numel(), val);
return var;
}
framework::LoDTensor& VarBase::Grad() {
VLOG(3) << "get var grad " << var_desc_->Name();
return *grads_->GetMutable<framework::LoDTensor>();
}
void VarBase::ApplyGrad(framework::Scope* scope, Variable* grad) {
VLOG(3) << "apply var grad " << var_desc_->Name() << " "
<< grad->Get<framework::LoDTensor>().data<float>()[0];
if (!grads_) {
grads_ =
CreateVariable(string::Sprintf("%s@IGrad", var_desc_->Name()),
var_->Get<framework::LoDTensor>().dims(), 0.0, scope);
}
AddTo(grad, grads_);
VLOG(3) << "grad_ after apply var grad " << var_desc_->Name() << " "
<< grads_->Get<framework::LoDTensor>().data<float>()[0];
}
std::vector<Variable*> OpBase::ApplyGrad(framework::Scope* scope) {
VLOG(3) << "op grad " << grad_op_desc_->Type();
for (const std::string& invar : grad_op_desc_->InputArgumentNames()) {
block_->FindRecursiveOrCreateVar(invar);
framework::Variable* var = scope->Var(invar);
LOG(ERROR) << "op grad in var " << invar;
if (!var->IsInitialized()) {
framework::VarDesc* var_desc = block_->FindVar(invar);
if (var_desc->GetType() == framework::proto::VarType::LOD_TENSOR) {
LOG(ERROR) << "grad op invar init " << invar;
var->GetMutable<framework::LoDTensor>();
} else {
LOG(ERROR) << "tracer doesn't support yet";
}
} else {
var->GetMutable<framework::LoDTensor>()->type();
}
}
std::vector<Variable*> ret;
for (size_t i = 0; i < input_vars_->size(); ++i) {
ret.push_back(nullptr);
}
for (const std::string& outvar : grad_op_desc_->OutputArgumentNames()) {
LOG(ERROR) << "grad outvar " << outvar;
block_->FindRecursiveOrCreateVar(outvar);
framework::Variable* var = scope->Var(outvar);
if (!var->IsInitialized()) {
framework::VarDesc* var_desc = block_->FindVar(outvar);
if (var_desc->GetType() == framework::proto::VarType::LOD_TENSOR) {
var->GetMutable<framework::LoDTensor>();
} else {
LOG(ERROR) << "tracer doesn't support yet";
}
}
}
grad_op_desc_->InferShape(*block_);
grad_op_desc_->InferVarType(block_);
std::unique_ptr<framework::OperatorBase> opbase =
framework::OpRegistry::CreateOp(*grad_op_desc_);
opbase->Run(*scope, platform::CPUPlace());
for (const std::string& outvar : grad_op_desc_->OutputArgumentNames()) {
if (grad_to_var_->find(outvar) != grad_to_var_->end()) {
std::string origin_var = (*grad_to_var_)[outvar];
for (size_t i = 0; i < input_vars_->size(); ++i) {
VarBase* origin_in_var = (*input_vars_)[i];
if (origin_in_var->var_desc_->Name() == origin_var) {
framework::Variable* var = scope->FindVar(outvar);
LOG(ERROR) << "apply grad " << outvar << " with origin "
<< origin_var;
// TODO(panyx0718): Accumulate.
// origin_in_var->grads_ = var;
origin_in_var->ApplyGrad(scope, var);
ret[i] = var;
// TODO(panyx0718): There might be 2 var with the same name. We
// currently assume the are the same Variable*. So it doesn't matter
// which one is used.
break;
}
}
}
}
return ret;
}
void VarBase::RunBackward(framework::Scope* scope) {
// TODO(panyx0718): Might not be 0th, need to detect.
grads_ = CreateVariable(pre_op_->grad_op_desc_->InputArgumentNames()[0],
var_->Get<framework::LoDTensor>().dims(), 1.0, scope,
false);
framework::Variable* grad =
CreateVariable("init@imperative_grad",
var_->Get<framework::LoDTensor>().dims(), 1.0, scope);
Autograd(scope).RunBackward(this, grad);
}
} // namespace imperative
} // namespace paddle
<commit_msg>polish<commit_after>// Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "paddle/fluid/imperative/layer.h"
#include <deque>
#include <limits>
#include <map>
#include <random>
#include <utility>
#include "paddle/fluid/framework/lod_tensor.h"
#include "paddle/fluid/framework/op_registry.h"
#include "paddle/fluid/string/printf.h"
namespace paddle {
namespace imperative {
using framework::Variable;
void AddTo(Variable* src, Variable* dst) {
framework::LoDTensor* dst_tensor = dst->GetMutable<framework::LoDTensor>();
framework::LoDTensor* src_tensor = src->GetMutable<framework::LoDTensor>();
PADDLE_ENFORCE(dst_tensor->numel() == src_tensor->numel(), "%lld vs %lld",
dst_tensor->numel(), src_tensor->numel());
float* dst_data = dst_tensor->mutable_data<float>(platform::CPUPlace());
const float* src_data = src_tensor->data<float>();
for (size_t i = 0; i < src_tensor->numel(); ++i) {
dst_data[i] += src_data[i];
}
}
class Autograd {
public:
explicit Autograd(framework::Scope* scope) : scope_(scope) {}
void RunBackward(VarBase* var) {
PADDLE_ENFORCE(var->pre_op_->op_desc_);
// TODO(panyx0718): Only create vars that "require_grad"
std::vector<Variable*> op_grads =
CreateOpGrads(var->pre_op_->output_vars_->size());
op_grads[var->pre_op_out_idx_] = var->grads_;
std::deque<std::pair<OpBase*, std::vector<Variable*>>> ready;
ready.push_back(std::make_pair(var->pre_op_, op_grads));
std::map<OpBase*, int> dep_counts = ComputeDepCounts(var->pre_op_);
std::map<OpBase*, std::vector<Variable*>> visited;
while (!ready.empty()) {
OpBase* ready_op = ready.front().first;
std::vector<Variable*> ready_op_grads = ready.front().second;
ready.pop_front();
std::vector<Variable*> input_grads = ready_op->ApplyGrad(scope_);
for (size_t i = 0; i < input_grads.size(); ++i) {
if (!input_grads[i]) continue;
OpBase* pre_op = ready_op->pre_ops_->at(i);
if (!pre_op) continue;
int pre_op_out_idx = ready_op->pre_ops_out_idx_->at(i);
dep_counts[pre_op] -= 1;
PADDLE_ENFORCE(dep_counts[pre_op] >= 0);
bool pre_op_ready = dep_counts[pre_op] == 0;
if (pre_op_ready) {
if (visited.find(pre_op) == visited.end()) {
PADDLE_ENFORCE(pre_op->output_vars_->size() == 1);
visited[pre_op] = {input_grads[i]};
} else {
std::vector<Variable*>& pre_op_grads = visited[pre_op];
AccumGrads(pre_op_out_idx, input_grads[i], &pre_op_grads);
}
ready.push_back(std::make_pair(pre_op, visited[pre_op]));
} else {
if (visited.find(pre_op) == visited.end()) {
// TODO(panyx0718): Only create vars that "require_grad"
visited[pre_op] = CreateOpGrads(var->pre_op_->output_vars_->size());
} else {
}
std::vector<Variable*>& pre_op_grads = visited[pre_op];
AccumGrads(pre_op_out_idx, input_grads[i], &pre_op_grads);
}
}
}
}
private:
void AccumGrads(int grad_idx, Variable* grad,
std::vector<Variable*>* op_grads) {
if (!(*op_grads)[grad_idx]) {
// FIXME(panyx0718): This should be a deep copy.
(*op_grads)[grad_idx] = grad;
return;
}
AddTo(grad, (*op_grads)[grad_idx]);
}
std::map<OpBase*, int> ComputeDepCounts(OpBase* op) {
std::map<OpBase*, int> ret;
std::deque<OpBase*> queue;
queue.push_back(op);
std::unordered_set<OpBase*> visited;
visited.insert(op);
while (!queue.empty()) {
OpBase* candidate = queue.front();
queue.pop_front();
for (OpBase* pre_op : *(candidate->pre_ops_)) {
if (!pre_op) continue;
if (visited.find(pre_op) == visited.end()) {
visited.insert(pre_op);
queue.push_back(pre_op);
}
ret[pre_op] += 1;
}
}
return ret;
}
std::vector<Variable*> CreateOpGrads(size_t count) {
std::vector<Variable*> op_grads;
for (size_t i = 0; i < count; ++i) {
op_grads.push_back(nullptr);
}
return op_grads;
}
framework::Scope* scope_;
};
framework::Variable* CreateVariable(const std::string& name,
const framework::DDim& dim, float val,
framework::Scope* scope,
bool random_name = true) {
std::string varname = name;
if (random_name) {
std::mt19937 rng;
rng.seed(std::random_device()());
std::uniform_int_distribution<std::mt19937::result_type> dist6(
1, std::numeric_limits<int>::max());
int id = dist6(rng);
varname = string::Sprintf("%s@%d", varname, id);
}
LOG(ERROR) << "creating var " << varname;
framework::Variable* var = scope->Var(varname);
framework::LoDTensor* tensor = var->GetMutable<framework::LoDTensor>();
float* data = tensor->mutable_data<float>(dim, platform::CPUPlace());
std::fill(data, data + tensor->numel(), val);
return var;
}
framework::LoDTensor& VarBase::Grad() {
VLOG(3) << "get var grad " << var_desc_->Name();
return *grads_->GetMutable<framework::LoDTensor>();
}
void VarBase::ApplyGrad(framework::Scope* scope, Variable* grad) {
VLOG(3) << "apply var grad " << var_desc_->Name() << " "
<< grad->Get<framework::LoDTensor>().data<float>()[0];
if (!grads_) {
grads_ =
CreateVariable(string::Sprintf("%s@IGrad", var_desc_->Name()),
var_->Get<framework::LoDTensor>().dims(), 0.0, scope);
}
AddTo(grad, grads_);
VLOG(3) << "grad_ after apply var grad " << var_desc_->Name() << " "
<< grads_->Get<framework::LoDTensor>().data<float>()[0];
}
std::vector<Variable*> OpBase::ApplyGrad(framework::Scope* scope) {
VLOG(3) << "op grad " << grad_op_desc_->Type();
for (const std::string& invar : grad_op_desc_->InputArgumentNames()) {
block_->FindRecursiveOrCreateVar(invar);
framework::Variable* var = scope->Var(invar);
LOG(ERROR) << "op grad in var " << invar;
if (!var->IsInitialized()) {
framework::VarDesc* var_desc = block_->FindVar(invar);
if (var_desc->GetType() == framework::proto::VarType::LOD_TENSOR) {
LOG(ERROR) << "grad op invar init " << invar;
var->GetMutable<framework::LoDTensor>();
} else {
LOG(ERROR) << "tracer doesn't support yet";
}
} else {
var->GetMutable<framework::LoDTensor>()->type();
}
}
std::vector<Variable*> ret;
for (size_t i = 0; i < input_vars_->size(); ++i) {
ret.push_back(nullptr);
}
for (const std::string& outvar : grad_op_desc_->OutputArgumentNames()) {
LOG(ERROR) << "grad outvar " << outvar;
block_->FindRecursiveOrCreateVar(outvar);
framework::Variable* var = scope->Var(outvar);
if (!var->IsInitialized()) {
framework::VarDesc* var_desc = block_->FindVar(outvar);
if (var_desc->GetType() == framework::proto::VarType::LOD_TENSOR) {
var->GetMutable<framework::LoDTensor>();
} else {
LOG(ERROR) << "tracer doesn't support yet";
}
}
}
grad_op_desc_->InferShape(*block_);
grad_op_desc_->InferVarType(block_);
std::unique_ptr<framework::OperatorBase> opbase =
framework::OpRegistry::CreateOp(*grad_op_desc_);
opbase->Run(*scope, platform::CPUPlace());
for (const std::string& outvar : grad_op_desc_->OutputArgumentNames()) {
if (grad_to_var_->find(outvar) != grad_to_var_->end()) {
std::string origin_var = (*grad_to_var_)[outvar];
for (size_t i = 0; i < input_vars_->size(); ++i) {
VarBase* origin_in_var = (*input_vars_)[i];
if (origin_in_var->var_desc_->Name() == origin_var) {
framework::Variable* var = scope->FindVar(outvar);
LOG(ERROR) << "apply grad " << outvar << " with origin "
<< origin_var;
origin_in_var->ApplyGrad(scope, var);
ret[i] = var;
// TODO(panyx0718): There might be 2 var with the same name. We
// currently assume the are the same Variable*. So it doesn't matter
// which one is used.
break;
}
}
}
}
return ret;
}
void VarBase::RunBackward(framework::Scope* scope) {
grads_ = CreateVariable(framework::GradVarName(var_desc_->Name()),
var_->Get<framework::LoDTensor>().dims(), 1.0, scope,
false);
if (!pre_op_) return;
Autograd(scope).RunBackward(this);
}
} // namespace imperative
} // namespace paddle
<|endoftext|> |
<commit_before>
#include "LingHun.h"
enum CAUSE{
LING_HUN_ZHEN_BAO =2201,
LING_HUN_CI_YU =2202,
LING_HUN_ZENG_FU=2203,
LING_HUN_TUN_SHI=2204,
LING_HUN_ZHAO_HUAN=2205,
LING_HUN_ZHUAN_HUAN=2206,
LING_HUN_JING_XIANG=2207,
LING_HUN_LIAN_JIE=2208,
LING_HUN_LIAN_JIE_REACT=2209
};
LingHun::LingHun()
{
makeConnection();
setMyRole(this);
lianJieUsed=false;
Button *linghunzhaohuan;
linghunzhaohuan=new Button(3,QStringLiteral("灵魂召还"));
buttonArea->addButton(linghunzhaohuan);
connect(linghunzhaohuan,SIGNAL(buttonSelected(int)),this,SLOT(LingHunZhaoHuan()));
Button *linghunjingxiang;
linghunjingxiang=new Button(4,QStringLiteral("灵魂镜像"));
buttonArea->addButton(linghunjingxiang);
connect(linghunjingxiang,SIGNAL(buttonSelected(int)),this,SLOT(LingHunJingXiang()));
Button *linghunzhenbao;
linghunzhenbao=new Button(5,QStringLiteral("灵魂震爆"));
buttonArea->addButton(linghunzhenbao);
connect(linghunzhenbao,SIGNAL(buttonSelected(int)),this,SLOT(LingHunZhenBao()));
Button *linghunciyu;
linghunciyu=new Button(6,QStringLiteral("灵魂赐予"));
buttonArea->addButton(linghunciyu);
connect(linghunciyu,SIGNAL(buttonSelected(int)),this,SLOT(LingHunCiYu()));
}
void LingHun::normal()
{
Role::normal();
Player *myself=dataInterface->getMyself();
if (handArea->checkType("magic"))
buttonArea->enable(3);
if(myself->getToken(0)>=2)
buttonArea->enable(4);
if (handArea->checkSpecility(QStringLiteral("灵魂震爆")) && myself->getToken(0)>=3)
buttonArea->enable(5);
if (handArea->checkSpecility(QStringLiteral("灵魂赐予")) && myself->getToken(1)>=3)
buttonArea->enable(6);
unactionalCheck();
}
void LingHun::LingHunZhaoHuan()
{
state= LING_HUN_ZHAO_HUAN;
playerArea->reset();
handArea->reset();
tipArea->reset();
handArea->enableMagic();
handArea->setQuota(1,7);
decisionArea->enable(1);
decisionArea->disable(0);
}
void LingHun::LingHunJingXiang()
{
state=LING_HUN_JING_XIANG;
playerArea->reset();
handArea->reset();
tipArea->reset();
decisionArea->enable(1);
decisionArea->disable(0);
if(handArea->getHandCardItems().size()>3)
{
handArea->setQuota(3);
}
else
handArea->setQuota(1,7);
handArea->enableAll();
playerArea->setQuota(1);
}
void LingHun::LingHunZhenBao()
{
state=LING_HUN_ZHEN_BAO;
playerArea->reset();
handArea->reset();
tipArea->reset();
playerArea->setQuota(1);
handArea->enableSpecility(QStringLiteral("灵魂震爆"));
handArea->setQuota(1);
decisionArea->enable(1);
decisionArea->disable(0);
}
//
void LingHun::LingHunCiYu()
{
state=LING_HUN_CI_YU;
playerArea->reset();
handArea->reset();
tipArea->reset();
playerArea->setQuota(1);
handArea->enableSpecility(QStringLiteral("灵魂赐予"));
handArea->setQuota(1);
decisionArea->enable(1);
decisionArea->disable(0);
}
void LingHun::LingHunZhuanHuan()
{
state=LING_HUN_ZHUAN_HUAN;
Player *myself=dataInterface->getMyself();
tipArea->setMsg(QStringLiteral("请选择要转换的灵魂:"));
decisionArea->enable(0);
decisionArea->enable(1);
if(myself->getToken(0)>0)
tipArea->addBoxItem(QStringLiteral("1.将黄魂转化为蓝魂"));
if(myself->getToken(1)>0)
tipArea->addBoxItem(QStringLiteral("2.将蓝魂转化为黄魂"));
tipArea->showBox();
}
//[灵魂链接]
void LingHun::LingHunLianJie()
{
state=LING_HUN_LIAN_JIE;
gui->reset();
Player *myself=dataInterface->getMyself();
decisionArea->enable(1);
tipArea->setMsg(QStringLiteral("是否发动灵魂连接?如是请选择目标"));
playerArea->enableMate();
playerArea->setQuota(1);
}
//[灵魂链接] 转移伤害
void LingHun::LingHunLianJieReact(int harmPoint)
{
state=LING_HUN_LIAN_JIE_REACT;
gui->reset();
Player *myself=dataInterface->getMyself();
tipArea->reset();
handArea->reset();
playerArea->reset();
decisionArea->enable(0);
decisionArea->enable(1);
tipArea->setMsg(QStringLiteral("请选择要转移的伤害:"));
int min=myself->getToken(1)<harmPoint?myself->getToken(1):harmPoint;
for(;min>0;min--) //转移伤害数>0
tipArea->addBoxItem(QString::number(min));
tipArea->showBox();
}
// 【灵魂增幅】
void LingHun::LingHunZengFu()
{
state=LING_HUN_ZENG_FU;
gui->reset();
tipArea->setMsg(QStringLiteral("是否发动灵魂增幅?"));
decisionArea->enable(1);
decisionArea->enable(0);
}
void LingHun::cardAnalyse()
{
Role::cardAnalyse();
switch(state)
{
case LING_HUN_ZHAO_HUAN:
decisionArea->enable(0);
break;
case LING_HUN_ZHEN_BAO:
case LING_HUN_CI_YU:
case LING_HUN_JING_XIANG:
playerArea->enableAll();
break;
}
}
void LingHun::onOkClicked()
{
Role::onOkClicked();
QList<Card*>selectedCards;
QList<Player*>selectedPlayers;
QString text;
selectedCards=handArea->getSelectedCards();
selectedPlayers=playerArea->getSelectedPlayers();
network::Action* action;
network::Respond* respond;
switch(state)
{
case LING_HUN_ZHAO_HUAN:
action = newAction(ACTION_MAGIC_SKILL,LING_HUN_ZHAO_HUAN);
for(int i=0;i<selectedCards.size();i++)
action->add_card_ids(selectedCards[i]->getID());
emit sendCommand(network::MSG_ACTION, action);
gui->reset();
break;
case LING_HUN_JING_XIANG:
action = newAction(ACTION_MAGIC_SKILL,LING_HUN_JING_XIANG);
foreach(Card*ptr,selectedCards){
action->add_card_ids(ptr->getID());
}
action->add_dst_ids(selectedPlayers[0]->getID());
emit sendCommand(network::MSG_ACTION, action);
gui->reset();
break;
case LING_HUN_ZHEN_BAO:
action = newAction(ACTION_MAGIC_SKILL,LING_HUN_ZHEN_BAO);
action->add_card_ids(selectedCards[0]->getID());
action->add_dst_ids(selectedPlayers[0]->getID());
emit sendCommand(network::MSG_ACTION, action);
gui->reset();
break;
case LING_HUN_CI_YU:
action = newAction(ACTION_MAGIC_SKILL,LING_HUN_CI_YU);
action->add_card_ids(selectedCards[0]->getID());
action->add_dst_ids(selectedPlayers[0]->getID());
emit sendCommand(network::MSG_ACTION, action);
gui->reset();
break;
case LING_HUN_ZHUAN_HUAN:
respond = new Respond();
respond->set_src_id(myID);
respond->set_respond_id(LING_HUN_ZHUAN_HUAN);
text=tipArea->getBoxCurrentText();
if(text[0].digitValue()==1)
respond->add_args(0);
else
respond->add_args(1);
emit sendCommand(network::MSG_RESPOND, respond);
gui->reset();
break;
case LING_HUN_LIAN_JIE:
respond = new Respond();
respond->set_respond_id(LING_HUN_LIAN_JIE);
respond->set_src_id(myID);
respond->add_dst_ids(selectedPlayers[0]->getID());
respond->add_args(1);
emit sendCommand(network::MSG_RESPOND, respond);
gui->reset();
break;
case LING_HUN_LIAN_JIE_REACT:
respond = new Respond();
respond->set_respond_id(LING_HUN_LIAN_JIE_REACT);
respond->set_src_id(myID);
respond->add_args(tipArea->getBoxCurrentText().toInt());
emit sendCommand(network::MSG_RESPOND, respond);
gui->reset();
break;
case LING_HUN_ZENG_FU:
respond = new Respond();
respond->set_respond_id(LING_HUN_ZENG_FU);
respond->set_src_id(myID);
// respond->set_respond_id(skillCmd.respond_id());
respond->add_args(1);
emit sendCommand(network::MSG_RESPOND, respond);
gui->reset();
break;
}
}
void LingHun::onCancelClicked()
{
Role::onCancelClicked();
network::Respond* respond;
switch(state)
{
case LING_HUN_ZHEN_BAO:
case LING_HUN_JING_XIANG:
case LING_HUN_ZHAO_HUAN:
case LING_HUN_CI_YU:
normal();
break;
case LING_HUN_ZHUAN_HUAN:
respond = new Respond();
respond->set_src_id(myID);
respond ->set_respond_id(LING_HUN_ZHUAN_HUAN);
respond->add_args(2);
emit sendCommand(network::MSG_RESPOND, respond);
gui->reset();
break;
case LING_HUN_LIAN_JIE:
respond = new Respond();
respond->set_respond_id(LING_HUN_LIAN_JIE);
respond->set_src_id(myID);
respond->add_args(0);
emit sendCommand(network::MSG_RESPOND, respond);
gui->reset();
break;
case LING_HUN_LIAN_JIE_REACT:
respond = new Respond();
respond->set_respond_id(LING_HUN_LIAN_JIE_REACT);
respond->set_src_id(myID);
respond->add_args(0);
emit sendCommand(network::MSG_RESPOND, respond);
gui->reset();
break;
case LING_HUN_ZENG_FU:
respond = new Respond();
respond->set_src_id(myID);
respond ->set_respond_id(LING_HUN_ZENG_FU);
respond->add_args(0);
emit sendCommand(network::MSG_RESPOND, respond);
gui->reset();
break;
}
}
void LingHun::askForSkill(network::Command* cmd)
{
//灵魂链接稍后补上
if(cmd->respond_id() == LING_HUN_ZHUAN_HUAN)
LingHunZhuanHuan();
else if(cmd->respond_id() == LING_HUN_ZENG_FU)
LingHunZengFu();
else if(cmd->respond_id() == LING_HUN_LIAN_JIE)
LingHunLianJie();
else if(cmd->respond_id() == LING_HUN_LIAN_JIE_REACT)
LingHunLianJieReact(cmd->args(0));
else
Role::askForSkill(cmd);
}
<commit_msg>灵魂启动之后提炼fix<commit_after>
#include "LingHun.h"
enum CAUSE{
LING_HUN_ZHEN_BAO =2201,
LING_HUN_CI_YU =2202,
LING_HUN_ZENG_FU=2203,
LING_HUN_TUN_SHI=2204,
LING_HUN_ZHAO_HUAN=2205,
LING_HUN_ZHUAN_HUAN=2206,
LING_HUN_JING_XIANG=2207,
LING_HUN_LIAN_JIE=2208,
LING_HUN_LIAN_JIE_REACT=2209
};
LingHun::LingHun()
{
makeConnection();
setMyRole(this);
lianJieUsed=false;
Button *linghunzhaohuan;
linghunzhaohuan=new Button(3,QStringLiteral("灵魂召还"));
buttonArea->addButton(linghunzhaohuan);
connect(linghunzhaohuan,SIGNAL(buttonSelected(int)),this,SLOT(LingHunZhaoHuan()));
Button *linghunjingxiang;
linghunjingxiang=new Button(4,QStringLiteral("灵魂镜像"));
buttonArea->addButton(linghunjingxiang);
connect(linghunjingxiang,SIGNAL(buttonSelected(int)),this,SLOT(LingHunJingXiang()));
Button *linghunzhenbao;
linghunzhenbao=new Button(5,QStringLiteral("灵魂震爆"));
buttonArea->addButton(linghunzhenbao);
connect(linghunzhenbao,SIGNAL(buttonSelected(int)),this,SLOT(LingHunZhenBao()));
Button *linghunciyu;
linghunciyu=new Button(6,QStringLiteral("灵魂赐予"));
buttonArea->addButton(linghunciyu);
connect(linghunciyu,SIGNAL(buttonSelected(int)),this,SLOT(LingHunCiYu()));
}
void LingHun::normal()
{
Role::normal();
Player *myself=dataInterface->getMyself();
if (handArea->checkType("magic"))
buttonArea->enable(3);
if(myself->getToken(0)>=2)
buttonArea->enable(4);
if (handArea->checkSpecility(QStringLiteral("灵魂震爆")) && myself->getToken(0)>=3)
buttonArea->enable(5);
if (handArea->checkSpecility(QStringLiteral("灵魂赐予")) && myself->getToken(1)>=3)
buttonArea->enable(6);
unactionalCheck();
}
void LingHun::LingHunZhaoHuan()
{
state= LING_HUN_ZHAO_HUAN;
playerArea->reset();
handArea->reset();
tipArea->reset();
handArea->enableMagic();
handArea->setQuota(1,7);
decisionArea->enable(1);
decisionArea->disable(0);
}
void LingHun::LingHunJingXiang()
{
state=LING_HUN_JING_XIANG;
playerArea->reset();
handArea->reset();
tipArea->reset();
decisionArea->enable(1);
decisionArea->disable(0);
if(handArea->getHandCardItems().size()>3)
{
handArea->setQuota(3);
}
else
handArea->setQuota(1,7);
handArea->enableAll();
playerArea->setQuota(1);
}
void LingHun::LingHunZhenBao()
{
state=LING_HUN_ZHEN_BAO;
playerArea->reset();
handArea->reset();
tipArea->reset();
playerArea->setQuota(1);
handArea->enableSpecility(QStringLiteral("灵魂震爆"));
handArea->setQuota(1);
decisionArea->enable(1);
decisionArea->disable(0);
}
//
void LingHun::LingHunCiYu()
{
state=LING_HUN_CI_YU;
playerArea->reset();
handArea->reset();
tipArea->reset();
playerArea->setQuota(1);
handArea->enableSpecility(QStringLiteral("灵魂赐予"));
handArea->setQuota(1);
decisionArea->enable(1);
decisionArea->disable(0);
}
void LingHun::LingHunZhuanHuan()
{
state=LING_HUN_ZHUAN_HUAN;
Player *myself=dataInterface->getMyself();
tipArea->setMsg(QStringLiteral("请选择要转换的灵魂:"));
decisionArea->enable(0);
decisionArea->enable(1);
if(myself->getToken(0)>0)
tipArea->addBoxItem(QStringLiteral("1.将黄魂转化为蓝魂"));
if(myself->getToken(1)>0)
tipArea->addBoxItem(QStringLiteral("2.将蓝魂转化为黄魂"));
tipArea->showBox();
}
//[灵魂链接]
void LingHun::LingHunLianJie()
{
state=LING_HUN_LIAN_JIE;
gui->reset();
Player *myself=dataInterface->getMyself();
decisionArea->enable(1);
tipArea->setMsg(QStringLiteral("是否发动灵魂连接?如是请选择目标"));
playerArea->enableMate();
playerArea->setQuota(1);
}
//[灵魂链接] 转移伤害
void LingHun::LingHunLianJieReact(int harmPoint)
{
state=LING_HUN_LIAN_JIE_REACT;
gui->reset();
Player *myself=dataInterface->getMyself();
tipArea->reset();
handArea->reset();
playerArea->reset();
decisionArea->enable(0);
decisionArea->enable(1);
tipArea->setMsg(QStringLiteral("请选择要转移的伤害:"));
int min=myself->getToken(1)<harmPoint?myself->getToken(1):harmPoint;
for(;min>0;min--) //转移伤害数>0
tipArea->addBoxItem(QString::number(min));
tipArea->showBox();
}
// 【灵魂增幅】
void LingHun::LingHunZengFu()
{
state=LING_HUN_ZENG_FU;
gui->reset();
tipArea->setMsg(QStringLiteral("是否发动灵魂增幅?"));
decisionArea->enable(1);
decisionArea->enable(0);
}
void LingHun::cardAnalyse()
{
Role::cardAnalyse();
switch(state)
{
case LING_HUN_ZHAO_HUAN:
decisionArea->enable(0);
break;
case LING_HUN_ZHEN_BAO:
case LING_HUN_CI_YU:
case LING_HUN_JING_XIANG:
playerArea->enableAll();
break;
}
}
void LingHun::onOkClicked()
{
Role::onOkClicked();
QList<Card*>selectedCards;
QList<Player*>selectedPlayers;
QString text;
selectedCards=handArea->getSelectedCards();
selectedPlayers=playerArea->getSelectedPlayers();
network::Action* action;
network::Respond* respond;
switch(state)
{
case LING_HUN_ZHAO_HUAN:
action = newAction(ACTION_MAGIC_SKILL,LING_HUN_ZHAO_HUAN);
for(int i=0;i<selectedCards.size();i++)
action->add_card_ids(selectedCards[i]->getID());
emit sendCommand(network::MSG_ACTION, action);
gui->reset();
break;
case LING_HUN_JING_XIANG:
action = newAction(ACTION_MAGIC_SKILL,LING_HUN_JING_XIANG);
foreach(Card*ptr,selectedCards){
action->add_card_ids(ptr->getID());
}
action->add_dst_ids(selectedPlayers[0]->getID());
emit sendCommand(network::MSG_ACTION, action);
gui->reset();
break;
case LING_HUN_ZHEN_BAO:
action = newAction(ACTION_MAGIC_SKILL,LING_HUN_ZHEN_BAO);
action->add_card_ids(selectedCards[0]->getID());
action->add_dst_ids(selectedPlayers[0]->getID());
emit sendCommand(network::MSG_ACTION, action);
gui->reset();
break;
case LING_HUN_CI_YU:
action = newAction(ACTION_MAGIC_SKILL,LING_HUN_CI_YU);
action->add_card_ids(selectedCards[0]->getID());
action->add_dst_ids(selectedPlayers[0]->getID());
emit sendCommand(network::MSG_ACTION, action);
gui->reset();
break;
case LING_HUN_ZHUAN_HUAN:
respond = new Respond();
respond->set_src_id(myID);
respond->set_respond_id(LING_HUN_ZHUAN_HUAN);
text=tipArea->getBoxCurrentText();
if(text[0].digitValue()==1)
respond->add_args(0);
else
respond->add_args(1);
emit sendCommand(network::MSG_RESPOND, respond);
gui->reset();
break;
case LING_HUN_LIAN_JIE:
respond = new Respond();
respond->set_respond_id(LING_HUN_LIAN_JIE);
respond->set_src_id(myID);
respond->add_dst_ids(selectedPlayers[0]->getID());
respond->add_args(1);
start=true;
emit sendCommand(network::MSG_RESPOND, respond);
gui->reset();
break;
case LING_HUN_LIAN_JIE_REACT:
respond = new Respond();
respond->set_respond_id(LING_HUN_LIAN_JIE_REACT);
respond->set_src_id(myID);
respond->add_args(tipArea->getBoxCurrentText().toInt());
emit sendCommand(network::MSG_RESPOND, respond);
gui->reset();
break;
case LING_HUN_ZENG_FU:
respond = new Respond();
respond->set_respond_id(LING_HUN_ZENG_FU);
respond->set_src_id(myID);
// respond->set_respond_id(skillCmd.respond_id());
respond->add_args(1);
start=true;
emit sendCommand(network::MSG_RESPOND, respond);
gui->reset();
break;
}
}
void LingHun::onCancelClicked()
{
Role::onCancelClicked();
network::Respond* respond;
switch(state)
{
case LING_HUN_ZHEN_BAO:
case LING_HUN_JING_XIANG:
case LING_HUN_ZHAO_HUAN:
case LING_HUN_CI_YU:
normal();
break;
case LING_HUN_ZHUAN_HUAN:
respond = new Respond();
respond->set_src_id(myID);
respond ->set_respond_id(LING_HUN_ZHUAN_HUAN);
respond->add_args(2);
emit sendCommand(network::MSG_RESPOND, respond);
gui->reset();
break;
case LING_HUN_LIAN_JIE:
respond = new Respond();
respond->set_respond_id(LING_HUN_LIAN_JIE);
respond->set_src_id(myID);
respond->add_args(0);
emit sendCommand(network::MSG_RESPOND, respond);
gui->reset();
break;
case LING_HUN_LIAN_JIE_REACT:
respond = new Respond();
respond->set_respond_id(LING_HUN_LIAN_JIE_REACT);
respond->set_src_id(myID);
respond->add_args(0);
emit sendCommand(network::MSG_RESPOND, respond);
gui->reset();
break;
case LING_HUN_ZENG_FU:
respond = new Respond();
respond->set_src_id(myID);
respond ->set_respond_id(LING_HUN_ZENG_FU);
respond->add_args(0);
emit sendCommand(network::MSG_RESPOND, respond);
gui->reset();
break;
}
}
void LingHun::askForSkill(network::Command* cmd)
{
//灵魂链接稍后补上
if(cmd->respond_id() == LING_HUN_ZHUAN_HUAN)
LingHunZhuanHuan();
else if(cmd->respond_id() == LING_HUN_ZENG_FU)
LingHunZengFu();
else if(cmd->respond_id() == LING_HUN_LIAN_JIE)
LingHunLianJie();
else if(cmd->respond_id() == LING_HUN_LIAN_JIE_REACT)
LingHunLianJieReact(cmd->args(0));
else
Role::askForSkill(cmd);
}
<|endoftext|> |
<commit_before>////////////////////////////////////////////////////////////////////////////////
/// Reaper
///
/// Copyright (c) 2015-2019 Thibault Schueller
/// This file is distributed under the MIT License
////////////////////////////////////////////////////////////////////////////////
#include "Renderer.h"
#include "renderer/vulkan/SwapchainRendererBase.h"
#include "renderer/vulkan/VulkanRenderer.h"
#include "renderer/renderdoc/RenderDoc.h"
namespace Reaper
{
bool create_renderer(ReaperRoot& root)
{
#if defined(REAPER_USE_RENDERDOC)
RenderDoc::start_integration(root);
#endif
Assert(root.renderer == nullptr);
root.renderer = new Renderer();
root.renderer->backend = new VulkanBackend();
create_vulkan_renderer_backend(root, *root.renderer->backend);
return true;
}
void destroy_renderer(ReaperRoot& root)
{
Assert(root.renderer != nullptr);
Assert(root.renderer->backend != nullptr);
destroy_vulkan_renderer_backend(root, *root.renderer->backend);
delete root.renderer->backend;
delete root.renderer;
root.renderer = nullptr;
#if defined(REAPER_USE_RENDERDOC)
RenderDoc::stop_integration(root);
#endif
}
void run_renderer(ReaperRoot& root)
{
Assert(root.renderer != nullptr);
Assert(root.renderer->backend != nullptr);
test_vulkan_renderer(root, *root.renderer->backend);
}
} // namespace Reaper
<commit_msg>renderdoc: slightly change integration enabling<commit_after>////////////////////////////////////////////////////////////////////////////////
/// Reaper
///
/// Copyright (c) 2015-2019 Thibault Schueller
/// This file is distributed under the MIT License
////////////////////////////////////////////////////////////////////////////////
#include "Renderer.h"
#include "renderer/vulkan/SwapchainRendererBase.h"
#include "renderer/vulkan/VulkanRenderer.h"
#include "renderer/renderdoc/RenderDoc.h"
namespace Reaper
{
#if defined(REAPER_USE_RENDERDOC)
// FIXME add this to flags at app startup when proper support is added.
constexpr bool enable_renderdoc_integration = true;
#else
constexpr bool enable_renderdoc_integration = false;
#endif
bool create_renderer(ReaperRoot& root)
{
if (enable_renderdoc_integration)
RenderDoc::start_integration(root);
Assert(root.renderer == nullptr);
root.renderer = new Renderer();
root.renderer->backend = new VulkanBackend();
create_vulkan_renderer_backend(root, *root.renderer->backend);
return true;
}
void destroy_renderer(ReaperRoot& root)
{
Assert(root.renderer != nullptr);
Assert(root.renderer->backend != nullptr);
destroy_vulkan_renderer_backend(root, *root.renderer->backend);
delete root.renderer->backend;
delete root.renderer;
root.renderer = nullptr;
if (enable_renderdoc_integration)
RenderDoc::stop_integration(root);
}
void run_renderer(ReaperRoot& root)
{
Assert(root.renderer != nullptr);
Assert(root.renderer->backend != nullptr);
test_vulkan_renderer(root, *root.renderer->backend);
}
} // namespace Reaper
<|endoftext|> |
<commit_before>/*
* RandomSplitter.cpp
* Splits dataset into training and control datasets.
*
Copyright 2017 Grzegorz Mrukwa, Wojciech Wilgierz
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 <random>
#include "RandomSplitter.h"
#include "Spectre.libPlatform/Filter.h"
#include "Spectre.libPlatform/Math.h"
#include "Spectre.libGenetic/DataTypes.h"
namespace Spectre::libClassifier {
using namespace libPlatform::Functional;
using namespace libPlatform::Math;
RandomSplitter::RandomSplitter(double trainingRate, libGenetic::Seed rngSeed)
: m_trainingRate(trainingRate),
m_randomNumberGenerator(rngSeed) {}
SplittedOpenCvDataset RandomSplitter::split(const Spectre::libClassifier::OpenCvDataset& data)
{
std::vector<int> indexes = range(0, int(data.size()));
libGenetic::RandomDevice randomDevice;
libGenetic::RandomNumberGenerator g(randomDevice());
std::shuffle(indexes.begin(), indexes.end(), g);
std::vector<DataType> trainingData{};
std::vector<DataType> validationData{};
std::vector<Label> trainingLabels{};
std::vector<Label> validationLabels{};
trainingData.reserve(data.size() * data[0].size());
validationData.reserve(data.size() * data[0].size());
trainingLabels.reserve(data.size());
validationLabels.reserve(data.size());
int trainingLimit = int(data.size() * m_trainingRate);
for (auto i = 0; i < trainingLimit; i++)
{
Observation observation(data[i]);
trainingData.insert(trainingData.end(), observation.begin(), observation.end());
trainingLabels.push_back(data.GetSampleMetadata(i));
}
for (auto i = trainingLimit; i < data.size(); i++)
{
Observation observation(data[i]);
validationData.insert(validationData.end(), observation.begin(), observation.end());
validationLabels.push_back(data.GetSampleMetadata(i));
}
OpenCvDataset dataset1(trainingData, trainingLabels);
OpenCvDataset dataset2(validationData, validationLabels);
auto result = SplittedOpenCvDataset(std::move(dataset1), std::move(dataset2));
return result;
}
}
<commit_msg>added static_cast<int><commit_after>/*
* RandomSplitter.cpp
* Splits dataset into training and control datasets.
*
Copyright 2017 Grzegorz Mrukwa, Wojciech Wilgierz
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 <random>
#include "RandomSplitter.h"
#include "Spectre.libPlatform/Filter.h"
#include "Spectre.libPlatform/Math.h"
#include "Spectre.libGenetic/DataTypes.h"
namespace Spectre::libClassifier {
using namespace libPlatform::Functional;
using namespace libPlatform::Math;
RandomSplitter::RandomSplitter(double trainingRate, libGenetic::Seed rngSeed)
: m_trainingRate(trainingRate),
m_randomNumberGenerator(rngSeed) {}
SplittedOpenCvDataset RandomSplitter::split(const Spectre::libClassifier::OpenCvDataset& data)
{
std::vector<int> indexes = range(0, int(data.size()));
libGenetic::RandomDevice randomDevice;
libGenetic::RandomNumberGenerator g(randomDevice());
std::shuffle(indexes.begin(), indexes.end(), g);
std::vector<DataType> trainingData{};
std::vector<DataType> validationData{};
std::vector<Label> trainingLabels{};
std::vector<Label> validationLabels{};
trainingData.reserve(data.size() * data[0].size());
validationData.reserve(data.size() * data[0].size());
trainingLabels.reserve(data.size());
validationLabels.reserve(data.size());
int trainingLimit = static_cast<int>(data.size() * m_trainingRate);
for (auto i = 0; i < trainingLimit; i++)
{
Observation observation(data[i]);
trainingData.insert(trainingData.end(), observation.begin(), observation.end());
trainingLabels.push_back(data.GetSampleMetadata(i));
}
for (auto i = trainingLimit; i < data.size(); i++)
{
Observation observation(data[i]);
validationData.insert(validationData.end(), observation.begin(), observation.end());
validationLabels.push_back(data.GetSampleMetadata(i));
}
OpenCvDataset dataset1(trainingData, trainingLabels);
OpenCvDataset dataset2(validationData, validationLabels);
auto result = SplittedOpenCvDataset(std::move(dataset1), std::move(dataset2));
return result;
}
}
<|endoftext|> |
<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation ([email protected])
**
** No Commercial Usage
**
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
**************************************************************************/
#include "maemotoolchain.h"
#include "maemoglobal.h"
#include "maemomanager.h"
#include "qt4projectmanagerconstants.h"
#include "qtversionmanager.h"
#include <projectexplorer/gccparser.h>
#include <projectexplorer/headerpath.h>
#include <projectexplorer/toolchainmanager.h>
#include <utils/environment.h>
#include <QtCore/QDir>
#include <QtCore/QFileInfo>
#include <QtGui/QLabel>
#include <QtGui/QVBoxLayout>
namespace Qt4ProjectManager {
namespace Internal {
static const char *const MAEMO_QT_VERSION_KEY = "Qt4ProjectManager.Maemo.QtVersion";
// --------------------------------------------------------------------------
// MaemoToolChain
// --------------------------------------------------------------------------
MaemoToolChain::MaemoToolChain(bool autodetected) :
ProjectExplorer::GccToolChain(QLatin1String(Constants::MAEMO_TOOLCHAIN_ID), autodetected),
m_qtVersionId(-1)
{
updateId();
}
MaemoToolChain::MaemoToolChain(const MaemoToolChain &tc) :
ProjectExplorer::GccToolChain(tc),
m_qtVersionId(tc.m_qtVersionId)
{ }
MaemoToolChain::~MaemoToolChain()
{ }
QString MaemoToolChain::typeName() const
{
return MaemoToolChainFactory::tr("Maemo GCC");
}
ProjectExplorer::Abi MaemoToolChain::targetAbi() const
{
return m_targetAbi;
}
bool MaemoToolChain::isValid() const
{
return GccToolChain::isValid() && m_qtVersionId >= 0 && m_targetAbi.isValid();
}
bool MaemoToolChain::canClone() const
{
return false;
}
void MaemoToolChain::addToEnvironment(Utils::Environment &env) const
{
QtVersion *v = QtVersionManager::instance()->version(m_qtVersionId);
const QString maddeRoot = MaemoGlobal::maddeRoot(v);
env.prependOrSetPath(QDir::toNativeSeparators(QString("%1/bin").arg(maddeRoot)));
env.prependOrSetPath(QDir::toNativeSeparators(QString("%1/bin")
.arg(MaemoGlobal::targetRoot(v))));
// put this into environment to make pkg-config stuff work
env.prependOrSet(QLatin1String("SYSROOT_DIR"), QDir::toNativeSeparators(sysroot()));
env.prependOrSetPath(QDir::toNativeSeparators(QString("%1/madbin")
.arg(maddeRoot)));
env.prependOrSetPath(QDir::toNativeSeparators(QString("%1/madlib")
.arg(maddeRoot)));
env.prependOrSet(QLatin1String("PERL5LIB"),
QDir::toNativeSeparators(QString("%1/madlib/perl5").arg(maddeRoot)));
const QString manglePathsKey = QLatin1String("GCCWRAPPER_PATHMANGLE");
if (!env.hasKey(manglePathsKey)) {
const QStringList pathsToMangle = QStringList() << QLatin1String("/lib")
<< QLatin1String("/opt") << QLatin1String("/usr");
env.set(manglePathsKey, QString());
foreach (const QString &path, pathsToMangle)
env.appendOrSet(manglePathsKey, path, QLatin1String(":"));
}
}
QString MaemoToolChain::sysroot() const
{
QtVersion *v = QtVersionManager::instance()->version(m_qtVersionId);
if (!v)
return QString();
if (m_sysroot.isEmpty()) {
QFile file(QDir::cleanPath(MaemoGlobal::targetRoot(v)) + QLatin1String("/information"));
if (file.exists() && file.open(QIODevice::ReadOnly | QIODevice::Text)) {
QTextStream stream(&file);
while (!stream.atEnd()) {
const QString &line = stream.readLine().trimmed();
const QStringList &list = line.split(QLatin1Char(' '));
if (list.count() > 1 && list.at(0) == QLatin1String("sysroot"))
m_sysroot = MaemoGlobal::maddeRoot(v) + QLatin1String("/sysroots/") + list.at(1);
}
}
}
return m_sysroot;
}
bool MaemoToolChain::operator ==(const ProjectExplorer::ToolChain &tc) const
{
if (!ToolChain::operator ==(tc))
return false;
const MaemoToolChain *tcPtr = static_cast<const MaemoToolChain *>(&tc);
return m_qtVersionId == tcPtr->m_qtVersionId;
}
ProjectExplorer::ToolChainConfigWidget *MaemoToolChain::configurationWidget()
{
return new MaemoToolChainConfigWidget(this);
}
QVariantMap MaemoToolChain::toMap() const
{
QVariantMap result = GccToolChain::toMap();
result.insert(QLatin1String(MAEMO_QT_VERSION_KEY), m_qtVersionId);
return result;
}
bool MaemoToolChain::fromMap(const QVariantMap &data)
{
if (!GccToolChain::fromMap(data))
return false;
m_qtVersionId = data.value(QLatin1String(MAEMO_QT_VERSION_KEY), -1).toInt();
return isValid();
}
void MaemoToolChain::setQtVersionId(int id)
{
if (id < 0) {
m_targetAbi = ProjectExplorer::Abi();
m_qtVersionId = -1;
updateId(); // Will trigger toolChainUpdated()!
return;
}
QtVersion *version = QtVersionManager::instance()->version(id);
Q_ASSERT(version);
ProjectExplorer::Abi::OSFlavor flavour = ProjectExplorer::Abi::HarmattanLinuxFlavor;
if (MaemoGlobal::isValidMaemo5QtVersion(version))
flavour = ProjectExplorer::Abi::MaemoLinuxFlavor;
else if (MaemoGlobal::isValidHarmattanQtVersion(version))
flavour = ProjectExplorer::Abi::HarmattanLinuxFlavor;
else if (MaemoGlobal::isValidMeegoQtVersion(version))
flavour = ProjectExplorer::Abi::MeegoLinuxFlavor;
else
return;
m_qtVersionId = id;
Q_ASSERT(version->qtAbis().count() == 1);
m_targetAbi = version->qtAbis().at(0);
updateId(); // Will trigger toolChainUpdated()!
setDisplayName(MaemoToolChainFactory::tr("Maemo GCC for %1").arg(version->displayName()));
}
int MaemoToolChain::qtVersionId() const
{
return m_qtVersionId;
}
void MaemoToolChain::updateId()
{
setId(QString::fromLatin1("%1:%2").arg(Constants::MAEMO_TOOLCHAIN_ID).arg(m_qtVersionId));
}
// --------------------------------------------------------------------------
// ToolChainConfigWidget
// --------------------------------------------------------------------------
MaemoToolChainConfigWidget::MaemoToolChainConfigWidget(MaemoToolChain *tc) :
ProjectExplorer::ToolChainConfigWidget(tc)
{
QVBoxLayout *layout = new QVBoxLayout(this);
QLabel *label = new QLabel;
QtVersion *v = QtVersionManager::instance()->version(tc->qtVersionId());
Q_ASSERT(v);
label->setText(tr("MADDE Root: %1<br>Target Root: %2")
.arg(MaemoGlobal::maddeRoot(v))
.arg(MaemoGlobal::targetRoot(v)));
layout->addWidget(label);
}
void MaemoToolChainConfigWidget::apply()
{
// nothing to do!
}
void MaemoToolChainConfigWidget::discard()
{
// nothing to do!
}
bool MaemoToolChainConfigWidget::isDirty() const
{
return false;
}
// --------------------------------------------------------------------------
// ToolChainFactory
// --------------------------------------------------------------------------
MaemoToolChainFactory::MaemoToolChainFactory() :
ProjectExplorer::ToolChainFactory()
{ }
QString MaemoToolChainFactory::displayName() const
{
return tr("Maemo GCC");
}
QString MaemoToolChainFactory::id() const
{
return QLatin1String(Constants::MAEMO_TOOLCHAIN_ID);
}
QList<ProjectExplorer::ToolChain *> MaemoToolChainFactory::autoDetect()
{
QList<ProjectExplorer::ToolChain *> result;
QtVersionManager *vm = QtVersionManager::instance();
connect(vm, SIGNAL(qtVersionsChanged(QList<int>)),
this, SLOT(handleQtVersionChanges(QList<int>)));
QList<int> versionList;
foreach (QtVersion *v, vm->versions())
versionList.append(v->uniqueId());
return createToolChainList(versionList);
}
void MaemoToolChainFactory::handleQtVersionChanges(const QList<int> &changes)
{
ProjectExplorer::ToolChainManager *tcm = ProjectExplorer::ToolChainManager::instance();
QList<ProjectExplorer::ToolChain *> tcList = createToolChainList(changes);
foreach (ProjectExplorer::ToolChain *tc, tcList)
tcm->registerToolChain(tc);
}
QList<ProjectExplorer::ToolChain *> MaemoToolChainFactory::createToolChainList(const QList<int> &changes)
{
ProjectExplorer::ToolChainManager *tcm = ProjectExplorer::ToolChainManager::instance();
QtVersionManager *vm = QtVersionManager::instance();
QList<ProjectExplorer::ToolChain *> result;
foreach (int i, changes) {
QtVersion *v = vm->version(i);
if (!v) {
// remove tool chain:
QList<ProjectExplorer::ToolChain *> toRemove;
foreach (ProjectExplorer::ToolChain *tc, tcm->toolChains()) {
if (!tc->id().startsWith(QLatin1String(Constants::MAEMO_TOOLCHAIN_ID)))
continue;
MaemoToolChain *mTc = static_cast<MaemoToolChain *>(tc);
if (mTc->qtVersionId() == i)
toRemove.append(mTc);
}
foreach (ProjectExplorer::ToolChain *tc, toRemove)
tcm->deregisterToolChain(tc);
} else if (v->supportsTargetId(Constants::MAEMO5_DEVICE_TARGET_ID)
|| v->supportsTargetId(Constants::HARMATTAN_DEVICE_TARGET_ID)
|| v->supportsTargetId(Constants::MEEGO_DEVICE_TARGET_ID)) {
// add tool chain:
MaemoToolChain *mTc = new MaemoToolChain(true);
mTc->setQtVersionId(i);
QString target = "Maemo 5";
if (v->supportsTargetId(Constants::HARMATTAN_DEVICE_TARGET_ID))
target = "Maemo 6";
else if (v->supportsTargetId(Constants::MEEGO_DEVICE_TARGET_ID))
target = "Meego";
mTc->setDisplayName(tr("%1 GCC (%2)").arg(target).arg(MaemoGlobal::maddeRoot(v)));
mTc->setCompilerPath(MaemoGlobal::targetRoot(v) + QLatin1String("/bin/gcc"));
result.append(mTc);
}
}
return result;
}
} // namespace Internal
} // namespace Qt4ProjectManager
<commit_msg>Maemo: Print debugger path in tool chain information<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation ([email protected])
**
** No Commercial Usage
**
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
**************************************************************************/
#include "maemotoolchain.h"
#include "maemoglobal.h"
#include "maemomanager.h"
#include "qt4projectmanagerconstants.h"
#include "qtversionmanager.h"
#include <projectexplorer/gccparser.h>
#include <projectexplorer/headerpath.h>
#include <projectexplorer/toolchainmanager.h>
#include <utils/environment.h>
#include <QtCore/QDir>
#include <QtCore/QFileInfo>
#include <QtGui/QLabel>
#include <QtGui/QVBoxLayout>
namespace Qt4ProjectManager {
namespace Internal {
static const char *const MAEMO_QT_VERSION_KEY = "Qt4ProjectManager.Maemo.QtVersion";
// --------------------------------------------------------------------------
// MaemoToolChain
// --------------------------------------------------------------------------
MaemoToolChain::MaemoToolChain(bool autodetected) :
ProjectExplorer::GccToolChain(QLatin1String(Constants::MAEMO_TOOLCHAIN_ID), autodetected),
m_qtVersionId(-1)
{
updateId();
}
MaemoToolChain::MaemoToolChain(const MaemoToolChain &tc) :
ProjectExplorer::GccToolChain(tc),
m_qtVersionId(tc.m_qtVersionId)
{ }
MaemoToolChain::~MaemoToolChain()
{ }
QString MaemoToolChain::typeName() const
{
return MaemoToolChainFactory::tr("Maemo GCC");
}
ProjectExplorer::Abi MaemoToolChain::targetAbi() const
{
return m_targetAbi;
}
bool MaemoToolChain::isValid() const
{
return GccToolChain::isValid() && m_qtVersionId >= 0 && m_targetAbi.isValid();
}
bool MaemoToolChain::canClone() const
{
return false;
}
void MaemoToolChain::addToEnvironment(Utils::Environment &env) const
{
QtVersion *v = QtVersionManager::instance()->version(m_qtVersionId);
const QString maddeRoot = MaemoGlobal::maddeRoot(v);
env.prependOrSetPath(QDir::toNativeSeparators(QString("%1/bin").arg(maddeRoot)));
env.prependOrSetPath(QDir::toNativeSeparators(QString("%1/bin")
.arg(MaemoGlobal::targetRoot(v))));
// put this into environment to make pkg-config stuff work
env.prependOrSet(QLatin1String("SYSROOT_DIR"), QDir::toNativeSeparators(sysroot()));
env.prependOrSetPath(QDir::toNativeSeparators(QString("%1/madbin")
.arg(maddeRoot)));
env.prependOrSetPath(QDir::toNativeSeparators(QString("%1/madlib")
.arg(maddeRoot)));
env.prependOrSet(QLatin1String("PERL5LIB"),
QDir::toNativeSeparators(QString("%1/madlib/perl5").arg(maddeRoot)));
const QString manglePathsKey = QLatin1String("GCCWRAPPER_PATHMANGLE");
if (!env.hasKey(manglePathsKey)) {
const QStringList pathsToMangle = QStringList() << QLatin1String("/lib")
<< QLatin1String("/opt") << QLatin1String("/usr");
env.set(manglePathsKey, QString());
foreach (const QString &path, pathsToMangle)
env.appendOrSet(manglePathsKey, path, QLatin1String(":"));
}
}
QString MaemoToolChain::sysroot() const
{
QtVersion *v = QtVersionManager::instance()->version(m_qtVersionId);
if (!v)
return QString();
if (m_sysroot.isEmpty()) {
QFile file(QDir::cleanPath(MaemoGlobal::targetRoot(v)) + QLatin1String("/information"));
if (file.exists() && file.open(QIODevice::ReadOnly | QIODevice::Text)) {
QTextStream stream(&file);
while (!stream.atEnd()) {
const QString &line = stream.readLine().trimmed();
const QStringList &list = line.split(QLatin1Char(' '));
if (list.count() > 1 && list.at(0) == QLatin1String("sysroot"))
m_sysroot = MaemoGlobal::maddeRoot(v) + QLatin1String("/sysroots/") + list.at(1);
}
}
}
return m_sysroot;
}
bool MaemoToolChain::operator ==(const ProjectExplorer::ToolChain &tc) const
{
if (!ToolChain::operator ==(tc))
return false;
const MaemoToolChain *tcPtr = static_cast<const MaemoToolChain *>(&tc);
return m_qtVersionId == tcPtr->m_qtVersionId;
}
ProjectExplorer::ToolChainConfigWidget *MaemoToolChain::configurationWidget()
{
return new MaemoToolChainConfigWidget(this);
}
QVariantMap MaemoToolChain::toMap() const
{
QVariantMap result = GccToolChain::toMap();
result.insert(QLatin1String(MAEMO_QT_VERSION_KEY), m_qtVersionId);
return result;
}
bool MaemoToolChain::fromMap(const QVariantMap &data)
{
if (!GccToolChain::fromMap(data))
return false;
m_qtVersionId = data.value(QLatin1String(MAEMO_QT_VERSION_KEY), -1).toInt();
return isValid();
}
void MaemoToolChain::setQtVersionId(int id)
{
if (id < 0) {
m_targetAbi = ProjectExplorer::Abi();
m_qtVersionId = -1;
updateId(); // Will trigger toolChainUpdated()!
return;
}
QtVersion *version = QtVersionManager::instance()->version(id);
Q_ASSERT(version);
ProjectExplorer::Abi::OSFlavor flavour = ProjectExplorer::Abi::HarmattanLinuxFlavor;
if (MaemoGlobal::isValidMaemo5QtVersion(version))
flavour = ProjectExplorer::Abi::MaemoLinuxFlavor;
else if (MaemoGlobal::isValidHarmattanQtVersion(version))
flavour = ProjectExplorer::Abi::HarmattanLinuxFlavor;
else if (MaemoGlobal::isValidMeegoQtVersion(version))
flavour = ProjectExplorer::Abi::MeegoLinuxFlavor;
else
return;
m_qtVersionId = id;
Q_ASSERT(version->qtAbis().count() == 1);
m_targetAbi = version->qtAbis().at(0);
updateId(); // Will trigger toolChainUpdated()!
setDisplayName(MaemoToolChainFactory::tr("Maemo GCC for %1").arg(version->displayName()));
}
int MaemoToolChain::qtVersionId() const
{
return m_qtVersionId;
}
void MaemoToolChain::updateId()
{
setId(QString::fromLatin1("%1:%2").arg(Constants::MAEMO_TOOLCHAIN_ID).arg(m_qtVersionId));
}
// --------------------------------------------------------------------------
// ToolChainConfigWidget
// --------------------------------------------------------------------------
MaemoToolChainConfigWidget::MaemoToolChainConfigWidget(MaemoToolChain *tc) :
ProjectExplorer::ToolChainConfigWidget(tc)
{
QVBoxLayout *layout = new QVBoxLayout(this);
QLabel *label = new QLabel;
QtVersion *v = QtVersionManager::instance()->version(tc->qtVersionId());
Q_ASSERT(v);
label->setText(tr("<html><head/><body><table>"
"<tr><td>Path to MADDE:</td><td>%1</td></tr>"
"<tr><td>Path to MADDE target:</td><td>%2</td></tr>"
"<tr><td>Debugger:</td/><td>%3</td></tr></body></html>")
.arg(QDir::toNativeSeparators(MaemoGlobal::maddeRoot(v)),
QDir::toNativeSeparators(MaemoGlobal::targetRoot(v)),
QDir::toNativeSeparators(tc->debuggerCommand())));
layout->addWidget(label);
}
void MaemoToolChainConfigWidget::apply()
{
// nothing to do!
}
void MaemoToolChainConfigWidget::discard()
{
// nothing to do!
}
bool MaemoToolChainConfigWidget::isDirty() const
{
return false;
}
// --------------------------------------------------------------------------
// ToolChainFactory
// --------------------------------------------------------------------------
MaemoToolChainFactory::MaemoToolChainFactory() :
ProjectExplorer::ToolChainFactory()
{ }
QString MaemoToolChainFactory::displayName() const
{
return tr("Maemo GCC");
}
QString MaemoToolChainFactory::id() const
{
return QLatin1String(Constants::MAEMO_TOOLCHAIN_ID);
}
QList<ProjectExplorer::ToolChain *> MaemoToolChainFactory::autoDetect()
{
QList<ProjectExplorer::ToolChain *> result;
QtVersionManager *vm = QtVersionManager::instance();
connect(vm, SIGNAL(qtVersionsChanged(QList<int>)),
this, SLOT(handleQtVersionChanges(QList<int>)));
QList<int> versionList;
foreach (QtVersion *v, vm->versions())
versionList.append(v->uniqueId());
return createToolChainList(versionList);
}
void MaemoToolChainFactory::handleQtVersionChanges(const QList<int> &changes)
{
ProjectExplorer::ToolChainManager *tcm = ProjectExplorer::ToolChainManager::instance();
QList<ProjectExplorer::ToolChain *> tcList = createToolChainList(changes);
foreach (ProjectExplorer::ToolChain *tc, tcList)
tcm->registerToolChain(tc);
}
QList<ProjectExplorer::ToolChain *> MaemoToolChainFactory::createToolChainList(const QList<int> &changes)
{
ProjectExplorer::ToolChainManager *tcm = ProjectExplorer::ToolChainManager::instance();
QtVersionManager *vm = QtVersionManager::instance();
QList<ProjectExplorer::ToolChain *> result;
foreach (int i, changes) {
QtVersion *v = vm->version(i);
if (!v) {
// remove tool chain:
QList<ProjectExplorer::ToolChain *> toRemove;
foreach (ProjectExplorer::ToolChain *tc, tcm->toolChains()) {
if (!tc->id().startsWith(QLatin1String(Constants::MAEMO_TOOLCHAIN_ID)))
continue;
MaemoToolChain *mTc = static_cast<MaemoToolChain *>(tc);
if (mTc->qtVersionId() == i)
toRemove.append(mTc);
}
foreach (ProjectExplorer::ToolChain *tc, toRemove)
tcm->deregisterToolChain(tc);
} else if (v->supportsTargetId(Constants::MAEMO5_DEVICE_TARGET_ID)
|| v->supportsTargetId(Constants::HARMATTAN_DEVICE_TARGET_ID)
|| v->supportsTargetId(Constants::MEEGO_DEVICE_TARGET_ID)) {
// add tool chain:
MaemoToolChain *mTc = new MaemoToolChain(true);
mTc->setQtVersionId(i);
QString target = "Maemo 5";
if (v->supportsTargetId(Constants::HARMATTAN_DEVICE_TARGET_ID))
target = "Maemo 6";
else if (v->supportsTargetId(Constants::MEEGO_DEVICE_TARGET_ID))
target = "Meego";
mTc->setDisplayName(tr("%1 GCC (%2)").arg(target).arg(MaemoGlobal::maddeRoot(v)));
mTc->setCompilerPath(MaemoGlobal::targetRoot(v) + QLatin1String("/bin/gcc"));
result.append(mTc);
}
}
return result;
}
} // namespace Internal
} // namespace Qt4ProjectManager
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2008-2016 the MRtrix3 contributors
*
* 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/
*
* MRtrix 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.
*
* For more details, see www.mrtrix.org
*
*/
#include "command.h"
#include "progressbar.h"
#include "algo/loop.h"
#include "image.h"
#include "sparse/fixel_metric.h"
#include "sparse/keys.h"
#include "sparse/image.h"
using namespace MR;
using namespace App;
using Sparse::FixelMetric;
const char* operation[] = { "add", "sub", "mult", "div", NULL };
void usage ()
{
AUTHOR = "David Raffelt ([email protected])";
DESCRIPTION
+ "Perform basic calculations (add, subtract, multiply, divide) between two fixel images";
ARGUMENTS
+ Argument ("input1", "the input fixel image.").type_image_in ()
+ Argument ("operation", "the type of operation to be applied (either add, sub, mult or divide)").type_choice (operation)
+ Argument ("input2", "the input fixel image.").type_image_in ()
+ Argument ("output", "the output fixel image.").type_image_out ();
}
float add (float a, float b) { return a + b; }
float subtract (float a, float b) { return a - b; }
float multiply (float a, float b) { return a * b; }
float divide (float a, float b) { return a / b; }
void run ()
{
auto header = Header::open (argument[0]);
Sparse::Image<FixelMetric> input1 (argument[0]);
Sparse::Image<FixelMetric> input2 (argument[2]);
check_dimensions (input1, input2);
Sparse::Image<FixelMetric> output (argument[3], header);
const size_t operation = argument[1];
std::string message;
float (*op)(float, float) = NULL;
switch (operation) {
case 0:
message = "adding fixel images";
op = &add;
break;
case 1:
message = "subtracting fixel images";
op = &subtract;
break;
case 2:
message = "multiplying fixel images";
op = &multiply;
break;
case 3:
message = "dividing fixel images";
op = ÷
break;
default:
break;
}
for (auto i = Loop (message, input1) (input1, input2, output); i; ++i) {
if (input1.value().size() != input2.value().size())
throw Exception ("the fixel images do not have corresponding fixels in all voxels");
output.value().set_size (input1.value().size());
for (size_t fixel = 0; fixel != input1.value().size(); ++fixel) {
output.value()[fixel] = input1.value()[fixel];
output.value()[fixel].value = (*op)(input1.value()[fixel].value, input2.value()[fixel].value);
}
}
}
<commit_msg>remove fixelcalc<commit_after><|endoftext|> |
<commit_before>/************************************************************************
filename: CEGUIDragContainer.cpp
created: 14/2/2005
author: Paul D Turner
*************************************************************************/
/*************************************************************************
Crazy Eddie's GUI System (http://www.cegui.org.uk)
Copyright (C)2004 - 2005 Paul D Turner ([email protected])
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
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
*************************************************************************/
#include "elements/CEGUIDragContainer.h"
#include "CEGUIImageset.h"
#include <cmath>
// Start of CEGUI namespace section
namespace CEGUI
{
//////////////////////////////////////////////////////////////////////////
// Window type string
const String DragContainer::WidgetTypeName("DragContainer");
// Event Strings
const String DragContainer::EventNamespace("DragContainer");
const String DragContainer::EventDragStarted("DragStarted");
const String DragContainer::EventDragEnded("DragEnded");
const String DragContainer::EventDragPositionChanged("DragPositionChanged");
const String DragContainer::EventDragEnabledChanged("DragEnabledChanged");
const String DragContainer::EventDragAlphaChanged("DragAlphaChanged");
const String DragContainer::EventDragMouseCursorChanged("DragMouseCursorChanged");
const String DragContainer::EventDragThresholdChanged("DragThresholdChanged");
const String DragContainer::EventDragDropTargetChanged("DragDropTargetChanged");
// Properties
DragContainerProperties::DragAlpha DragContainer::d_dragAlphaProperty;
DragContainerProperties::DragCursorImage DragContainer::d_dragCursorImageProperty;
DragContainerProperties::DraggingEnabled DragContainer::d_dragEnabledProperty;
DragContainerProperties::DragThreshold DragContainer::d_dragThresholdProperty;
//////////////////////////////////////////////////////////////////////////
DragContainer::DragContainer(const String& type, const String& name) :
Window(type, name),
d_draggingEnabled(true),
d_leftMouseDown(false),
d_dragging(false),
d_dragThreshold(8.0f),
d_dragAlpha(0.5f),
d_dropTarget(0),
d_dragCursorImage((const Image*)DefaultMouseCursor)
{
addDragContainerEvents();
addDragContainerProperties();
}
DragContainer::~DragContainer(void)
{
}
bool DragContainer::isDraggingEnabled(void) const
{
return d_draggingEnabled;
}
void DragContainer::setDraggingEnabled(bool setting)
{
if (d_draggingEnabled != setting)
{
d_draggingEnabled = setting;
WindowEventArgs args(this);
onDragEnabledChanged(args);
}
}
bool DragContainer::isBeingDragged(void) const
{
return d_dragging;
}
float DragContainer::getPixelDragThreshold(void) const
{
return d_dragThreshold;
}
void DragContainer::setPixelDragThreshold(float pixels)
{
if (d_dragThreshold != pixels)
{
d_dragThreshold = pixels;
WindowEventArgs args(this);
onDragThresholdChanged(args);
}
}
float DragContainer::getDragAlpha(void) const
{
return d_dragAlpha;
}
void DragContainer::setDragAlpha(float alpha)
{
if (d_dragAlpha != alpha)
{
d_dragAlpha = alpha;
WindowEventArgs args(this);
onDragAlphaChanged(args);
}
}
const Image* DragContainer::getDragCursorImage(void) const
{
if (d_dragCursorImage == (const Image*)DefaultMouseCursor)
{
return System::getSingleton().getDefaultMouseCursor();
}
else
{
return d_dragCursorImage;
}
}
void DragContainer::setDragCursorImage(const Image* image)
{
if (d_dragCursorImage != image)
{
d_dragCursorImage = image;
WindowEventArgs args(this);
onDragMouseCursorChanged(args);
}
}
void DragContainer::setDragCursorImage(MouseCursorImage image)
{
setDragCursorImage((const Image*)image);
}
void DragContainer::setDragCursorImage(const String& imageset, const String& image)
{
setDragCursorImage(&ImagesetManager::getSingleton().getImageset(imageset)->getImage(image));
}
Window* DragContainer::getCurrentDropTarget(void) const
{
return d_dropTarget;
}
void DragContainer::addDragContainerEvents(void)
{
addEvent(EventDragStarted);
addEvent(EventDragEnded);
addEvent(EventDragPositionChanged);
addEvent(EventDragEnabledChanged);
addEvent(EventDragAlphaChanged);
addEvent(EventDragMouseCursorChanged);
addEvent(EventDragThresholdChanged);
addEvent(EventDragDropTargetChanged);
}
void DragContainer::addDragContainerProperties(void)
{
addProperty(&d_dragEnabledProperty);
addProperty(&d_dragAlphaProperty);
addProperty(&d_dragThresholdProperty);
addProperty(&d_dragCursorImageProperty);
}
bool DragContainer::isDraggingThresholdExceeded(const Point& local_mouse)
{
// calculate amount mouse has moved.
float deltaX = std::fabs(local_mouse.d_x - d_dragPoint.d_x);
float deltaY = std::fabs(local_mouse.d_y - d_dragPoint.d_y);
// see if mouse has moved far enough to start dragging operation
return (deltaX > d_dragThreshold || deltaY > d_dragThreshold) ? true : false;
}
void DragContainer::initialiseDragging(void)
{
// only proceed if dragging is actually enabled
if (d_draggingEnabled)
{
// initialise drag moving state
d_storedClipState = d_clippedByParent;
setClippedByParent(false);
d_storedAlpha = d_alpha;
setAlpha(d_dragAlpha);
d_startPosition = getPosition(Absolute);
d_dragging = true;
// Now drag mode is set, change cursor as required
updateActiveMouseCursor();
}
}
void DragContainer::doDragging(const Point& local_mouse)
{
setPosition(Absolute, getPosition(Absolute) + (local_mouse - d_dragPoint));
WindowEventArgs args(this);
onDragPositionChanged(args);
}
void DragContainer::updateActiveMouseCursor(void) const
{
MouseCursor::getSingleton().setImage(d_dragging ? getDragCursorImage() : getMouseCursor());
}
void DragContainer::drawSelf(float z)
{
// No rendering for this window
}
void DragContainer::onMouseButtonDown(MouseEventArgs& e)
{
Window::onMouseButtonDown(e);
if (e.button == LeftButton)
{
// ensure all inputs come to us for now
if (captureInput())
{
// get position of mouse as co-ordinates local to this window.
Point localPos = (getMetricsMode() == Relative) ?
relativeToAbsolute(screenToWindow(e.position)) :
screenToWindow(e.position);
// store drag point for possible sizing or moving operation.
d_dragPoint = localPos;
d_leftMouseDown = true;
}
e.handled = true;
}
}
void DragContainer::onMouseButtonUp(MouseEventArgs& e)
{
Window::onMouseButtonUp(e);
if (e.button == LeftButton)
{
if (d_dragging)
{
// fire off event
WindowEventArgs args(this);
onDragEnded(args);
}
// release our capture on the input data
releaseInput();
e.handled = true;
}
}
void DragContainer::onMouseMove(MouseEventArgs& e)
{
Window::onMouseMove(e);
// get position of mouse as co-ordinates local to this window.
Point localMousePos = (getMetricsMode() == Relative) ?
relativeToAbsolute(screenToWindow(e.position)) :
screenToWindow(e.position);
// handle dragging
if (d_dragging)
{
doDragging(localMousePos);
}
// not dragging
else
{
// if mouse button is down (but we're not yet being dragged)
if (d_leftMouseDown)
{
if (isDraggingThresholdExceeded(localMousePos))
{
// Trigger the event
WindowEventArgs args(this);
onDragStarted(args);
}
}
}
}
void DragContainer::onCaptureLost(WindowEventArgs& e)
{
Window::onCaptureLost(e);
// reset state
if (d_dragging)
{
// restore windows 'normal' state.
d_dragging = false;
setPosition(Absolute, d_startPosition);
setClippedByParent(d_storedClipState);
setAlpha(d_storedAlpha);
// restore normal mouse cursor
updateActiveMouseCursor();
}
d_leftMouseDown = false;
d_dropTarget = 0;
e.handled = true;
}
void DragContainer::onAlphaChanged(WindowEventArgs& e)
{
// store new value and re-set dragging alpha as required.
if (d_dragging)
{
d_storedAlpha = d_alpha;
d_alpha = d_dragAlpha;
}
Window::onAlphaChanged(e);
}
void DragContainer::onClippingChanged(WindowEventArgs& e)
{
// store new value and re-set clipping for drag as required.
if (d_dragging)
{
d_storedClipState = d_clippedByParent;
d_clippedByParent = false;
}
Window::onClippingChanged(e);
}
void DragContainer::onDragStarted(WindowEventArgs& e)
{
initialiseDragging();
fireEvent(EventDragStarted, e, EventNamespace);
}
void DragContainer::onDragEnded(WindowEventArgs& e)
{
fireEvent(EventDragEnded, e, EventNamespace);
// did we drop over a window?
if (d_dropTarget)
{
// Notify that item was dropped in the target window
d_dropTarget->notifyDragDropItemDropped(this);
}
}
void DragContainer::onDragPositionChanged(WindowEventArgs& e)
{
fireEvent(EventDragPositionChanged, e, EventNamespace);
Window* root;
if (0 != (root = System::getSingleton().getGUISheet()))
{
// this hack with the 'enabled' state is so that getChildAtPosition
// returns something useful instead of a pointer back to 'this'.
// This hack is only acceptable because I am CrazyEddie!
bool wasEnabled = d_enabled;
d_enabled = false;
// find out which child of root window has the mouse in it
Window* eventWindow = root->getChildAtPosition(MouseCursor::getSingleton().getPosition());
d_enabled = wasEnabled;
// use root itself if no child was hit
if (!eventWindow)
{
eventWindow = root;
}
// if the window with the mouse is different to current drop target
if (eventWindow != d_dropTarget)
{
DragDropEventArgs args(eventWindow);
args.dragDropItem = this;
onDragDropTargetChanged(args);
}
}
}
void DragContainer::onDragEnabledChanged(WindowEventArgs& e)
{
fireEvent(EventDragEnabledChanged, e, EventNamespace);
// abort current drag operation if dragging gets disabled part way through
if (!d_draggingEnabled && d_dragging)
{
releaseInput();
}
}
void DragContainer::onDragAlphaChanged(WindowEventArgs& e)
{
fireEvent(EventDragAlphaChanged, e, EventNamespace);
if (d_dragging)
{
d_alpha = d_storedAlpha;
onAlphaChanged(e);
}
}
void DragContainer::onDragMouseCursorChanged(WindowEventArgs& e)
{
fireEvent(EventDragMouseCursorChanged, e, EventNamespace);
updateActiveMouseCursor();
}
void DragContainer::onDragThresholdChanged(WindowEventArgs& e)
{
fireEvent(EventDragThresholdChanged, e, EventNamespace);
}
void DragContainer::onDragDropTargetChanged(DragDropEventArgs& e)
{
fireEvent(EventDragDropTargetChanged, e, EventNamespace);
// Notify old target that drop item has left
if (d_dropTarget)
{
d_dropTarget->notifyDragDropItemLeaves(this);
}
// update to new target
d_dropTarget = e.window;
// Notify new target window that someone has dragged a DragContainer over it
d_dropTarget->notifyDragDropItemEnters(this);
}
} // End of CEGUI namespace section
<commit_msg>Fixes to work around possible STLport issues where it does not put some C funcs into std (_STL) namespace.<commit_after>/************************************************************************
filename: CEGUIDragContainer.cpp
created: 14/2/2005
author: Paul D Turner
*************************************************************************/
/*************************************************************************
Crazy Eddie's GUI System (http://www.cegui.org.uk)
Copyright (C)2004 - 2005 Paul D Turner ([email protected])
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
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
*************************************************************************/
#include "elements/CEGUIDragContainer.h"
#include "CEGUIImageset.h"
#include <math.h>
// Start of CEGUI namespace section
namespace CEGUI
{
//////////////////////////////////////////////////////////////////////////
// Window type string
const String DragContainer::WidgetTypeName("DragContainer");
// Event Strings
const String DragContainer::EventNamespace("DragContainer");
const String DragContainer::EventDragStarted("DragStarted");
const String DragContainer::EventDragEnded("DragEnded");
const String DragContainer::EventDragPositionChanged("DragPositionChanged");
const String DragContainer::EventDragEnabledChanged("DragEnabledChanged");
const String DragContainer::EventDragAlphaChanged("DragAlphaChanged");
const String DragContainer::EventDragMouseCursorChanged("DragMouseCursorChanged");
const String DragContainer::EventDragThresholdChanged("DragThresholdChanged");
const String DragContainer::EventDragDropTargetChanged("DragDropTargetChanged");
// Properties
DragContainerProperties::DragAlpha DragContainer::d_dragAlphaProperty;
DragContainerProperties::DragCursorImage DragContainer::d_dragCursorImageProperty;
DragContainerProperties::DraggingEnabled DragContainer::d_dragEnabledProperty;
DragContainerProperties::DragThreshold DragContainer::d_dragThresholdProperty;
//////////////////////////////////////////////////////////////////////////
DragContainer::DragContainer(const String& type, const String& name) :
Window(type, name),
d_draggingEnabled(true),
d_leftMouseDown(false),
d_dragging(false),
d_dragThreshold(8.0f),
d_dragAlpha(0.5f),
d_dropTarget(0),
d_dragCursorImage((const Image*)DefaultMouseCursor)
{
addDragContainerEvents();
addDragContainerProperties();
}
DragContainer::~DragContainer(void)
{
}
bool DragContainer::isDraggingEnabled(void) const
{
return d_draggingEnabled;
}
void DragContainer::setDraggingEnabled(bool setting)
{
if (d_draggingEnabled != setting)
{
d_draggingEnabled = setting;
WindowEventArgs args(this);
onDragEnabledChanged(args);
}
}
bool DragContainer::isBeingDragged(void) const
{
return d_dragging;
}
float DragContainer::getPixelDragThreshold(void) const
{
return d_dragThreshold;
}
void DragContainer::setPixelDragThreshold(float pixels)
{
if (d_dragThreshold != pixels)
{
d_dragThreshold = pixels;
WindowEventArgs args(this);
onDragThresholdChanged(args);
}
}
float DragContainer::getDragAlpha(void) const
{
return d_dragAlpha;
}
void DragContainer::setDragAlpha(float alpha)
{
if (d_dragAlpha != alpha)
{
d_dragAlpha = alpha;
WindowEventArgs args(this);
onDragAlphaChanged(args);
}
}
const Image* DragContainer::getDragCursorImage(void) const
{
if (d_dragCursorImage == (const Image*)DefaultMouseCursor)
{
return System::getSingleton().getDefaultMouseCursor();
}
else
{
return d_dragCursorImage;
}
}
void DragContainer::setDragCursorImage(const Image* image)
{
if (d_dragCursorImage != image)
{
d_dragCursorImage = image;
WindowEventArgs args(this);
onDragMouseCursorChanged(args);
}
}
void DragContainer::setDragCursorImage(MouseCursorImage image)
{
setDragCursorImage((const Image*)image);
}
void DragContainer::setDragCursorImage(const String& imageset, const String& image)
{
setDragCursorImage(&ImagesetManager::getSingleton().getImageset(imageset)->getImage(image));
}
Window* DragContainer::getCurrentDropTarget(void) const
{
return d_dropTarget;
}
void DragContainer::addDragContainerEvents(void)
{
addEvent(EventDragStarted);
addEvent(EventDragEnded);
addEvent(EventDragPositionChanged);
addEvent(EventDragEnabledChanged);
addEvent(EventDragAlphaChanged);
addEvent(EventDragMouseCursorChanged);
addEvent(EventDragThresholdChanged);
addEvent(EventDragDropTargetChanged);
}
void DragContainer::addDragContainerProperties(void)
{
addProperty(&d_dragEnabledProperty);
addProperty(&d_dragAlphaProperty);
addProperty(&d_dragThresholdProperty);
addProperty(&d_dragCursorImageProperty);
}
bool DragContainer::isDraggingThresholdExceeded(const Point& local_mouse)
{
// calculate amount mouse has moved.
float deltaX = fabs(local_mouse.d_x - d_dragPoint.d_x);
float deltaY = fabs(local_mouse.d_y - d_dragPoint.d_y);
// see if mouse has moved far enough to start dragging operation
return (deltaX > d_dragThreshold || deltaY > d_dragThreshold) ? true : false;
}
void DragContainer::initialiseDragging(void)
{
// only proceed if dragging is actually enabled
if (d_draggingEnabled)
{
// initialise drag moving state
d_storedClipState = d_clippedByParent;
setClippedByParent(false);
d_storedAlpha = d_alpha;
setAlpha(d_dragAlpha);
d_startPosition = getPosition(Absolute);
d_dragging = true;
// Now drag mode is set, change cursor as required
updateActiveMouseCursor();
}
}
void DragContainer::doDragging(const Point& local_mouse)
{
setPosition(Absolute, getPosition(Absolute) + (local_mouse - d_dragPoint));
WindowEventArgs args(this);
onDragPositionChanged(args);
}
void DragContainer::updateActiveMouseCursor(void) const
{
MouseCursor::getSingleton().setImage(d_dragging ? getDragCursorImage() : getMouseCursor());
}
void DragContainer::drawSelf(float z)
{
// No rendering for this window
}
void DragContainer::onMouseButtonDown(MouseEventArgs& e)
{
Window::onMouseButtonDown(e);
if (e.button == LeftButton)
{
// ensure all inputs come to us for now
if (captureInput())
{
// get position of mouse as co-ordinates local to this window.
Point localPos = (getMetricsMode() == Relative) ?
relativeToAbsolute(screenToWindow(e.position)) :
screenToWindow(e.position);
// store drag point for possible sizing or moving operation.
d_dragPoint = localPos;
d_leftMouseDown = true;
}
e.handled = true;
}
}
void DragContainer::onMouseButtonUp(MouseEventArgs& e)
{
Window::onMouseButtonUp(e);
if (e.button == LeftButton)
{
if (d_dragging)
{
// fire off event
WindowEventArgs args(this);
onDragEnded(args);
}
// release our capture on the input data
releaseInput();
e.handled = true;
}
}
void DragContainer::onMouseMove(MouseEventArgs& e)
{
Window::onMouseMove(e);
// get position of mouse as co-ordinates local to this window.
Point localMousePos = (getMetricsMode() == Relative) ?
relativeToAbsolute(screenToWindow(e.position)) :
screenToWindow(e.position);
// handle dragging
if (d_dragging)
{
doDragging(localMousePos);
}
// not dragging
else
{
// if mouse button is down (but we're not yet being dragged)
if (d_leftMouseDown)
{
if (isDraggingThresholdExceeded(localMousePos))
{
// Trigger the event
WindowEventArgs args(this);
onDragStarted(args);
}
}
}
}
void DragContainer::onCaptureLost(WindowEventArgs& e)
{
Window::onCaptureLost(e);
// reset state
if (d_dragging)
{
// restore windows 'normal' state.
d_dragging = false;
setPosition(Absolute, d_startPosition);
setClippedByParent(d_storedClipState);
setAlpha(d_storedAlpha);
// restore normal mouse cursor
updateActiveMouseCursor();
}
d_leftMouseDown = false;
d_dropTarget = 0;
e.handled = true;
}
void DragContainer::onAlphaChanged(WindowEventArgs& e)
{
// store new value and re-set dragging alpha as required.
if (d_dragging)
{
d_storedAlpha = d_alpha;
d_alpha = d_dragAlpha;
}
Window::onAlphaChanged(e);
}
void DragContainer::onClippingChanged(WindowEventArgs& e)
{
// store new value and re-set clipping for drag as required.
if (d_dragging)
{
d_storedClipState = d_clippedByParent;
d_clippedByParent = false;
}
Window::onClippingChanged(e);
}
void DragContainer::onDragStarted(WindowEventArgs& e)
{
initialiseDragging();
fireEvent(EventDragStarted, e, EventNamespace);
}
void DragContainer::onDragEnded(WindowEventArgs& e)
{
fireEvent(EventDragEnded, e, EventNamespace);
// did we drop over a window?
if (d_dropTarget)
{
// Notify that item was dropped in the target window
d_dropTarget->notifyDragDropItemDropped(this);
}
}
void DragContainer::onDragPositionChanged(WindowEventArgs& e)
{
fireEvent(EventDragPositionChanged, e, EventNamespace);
Window* root;
if (0 != (root = System::getSingleton().getGUISheet()))
{
// this hack with the 'enabled' state is so that getChildAtPosition
// returns something useful instead of a pointer back to 'this'.
// This hack is only acceptable because I am CrazyEddie!
bool wasEnabled = d_enabled;
d_enabled = false;
// find out which child of root window has the mouse in it
Window* eventWindow = root->getChildAtPosition(MouseCursor::getSingleton().getPosition());
d_enabled = wasEnabled;
// use root itself if no child was hit
if (!eventWindow)
{
eventWindow = root;
}
// if the window with the mouse is different to current drop target
if (eventWindow != d_dropTarget)
{
DragDropEventArgs args(eventWindow);
args.dragDropItem = this;
onDragDropTargetChanged(args);
}
}
}
void DragContainer::onDragEnabledChanged(WindowEventArgs& e)
{
fireEvent(EventDragEnabledChanged, e, EventNamespace);
// abort current drag operation if dragging gets disabled part way through
if (!d_draggingEnabled && d_dragging)
{
releaseInput();
}
}
void DragContainer::onDragAlphaChanged(WindowEventArgs& e)
{
fireEvent(EventDragAlphaChanged, e, EventNamespace);
if (d_dragging)
{
d_alpha = d_storedAlpha;
onAlphaChanged(e);
}
}
void DragContainer::onDragMouseCursorChanged(WindowEventArgs& e)
{
fireEvent(EventDragMouseCursorChanged, e, EventNamespace);
updateActiveMouseCursor();
}
void DragContainer::onDragThresholdChanged(WindowEventArgs& e)
{
fireEvent(EventDragThresholdChanged, e, EventNamespace);
}
void DragContainer::onDragDropTargetChanged(DragDropEventArgs& e)
{
fireEvent(EventDragDropTargetChanged, e, EventNamespace);
// Notify old target that drop item has left
if (d_dropTarget)
{
d_dropTarget->notifyDragDropItemLeaves(this);
}
// update to new target
d_dropTarget = e.window;
// Notify new target window that someone has dragged a DragContainer over it
d_dropTarget->notifyDragDropItemEnters(this);
}
} // End of CEGUI namespace section
<|endoftext|> |
<commit_before>/*
* Copyright © 2013 Intel Corporation
*
* 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 (including the next
* paragraph) 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 "brw_vs.h"
#include "main/context.h"
namespace brw {
void
vec4_vs_visitor::emit_prolog()
{
dst_reg sign_recovery_shift;
dst_reg normalize_factor;
dst_reg es3_normalize_factor;
for (int i = 0; i < VERT_ATTRIB_MAX; i++) {
if (vs_prog_data->inputs_read & BITFIELD64_BIT(i)) {
uint8_t wa_flags = vs_compile->key.gl_attrib_wa_flags[i];
dst_reg reg(ATTR, i);
dst_reg reg_d = reg;
reg_d.type = BRW_REGISTER_TYPE_D;
dst_reg reg_ud = reg;
reg_ud.type = BRW_REGISTER_TYPE_UD;
/* Do GL_FIXED rescaling for GLES2.0. Our GL_FIXED attributes
* come in as floating point conversions of the integer values.
*/
if (wa_flags & BRW_ATTRIB_WA_COMPONENT_MASK) {
dst_reg dst = reg;
dst.type = brw_type_for_base_type(glsl_type::vec4_type);
dst.writemask = (1 << (wa_flags & BRW_ATTRIB_WA_COMPONENT_MASK)) - 1;
emit(MUL(dst, src_reg(dst), src_reg(1.0f / 65536.0f)));
}
/* Do sign recovery for 2101010 formats if required. */
if (wa_flags & BRW_ATTRIB_WA_SIGN) {
if (sign_recovery_shift.file == BAD_FILE) {
/* shift constant: <22,22,22,30> */
sign_recovery_shift = dst_reg(this, glsl_type::uvec4_type);
emit(MOV(writemask(sign_recovery_shift, WRITEMASK_XYZ), src_reg(22u)));
emit(MOV(writemask(sign_recovery_shift, WRITEMASK_W), src_reg(30u)));
}
emit(SHL(reg_ud, src_reg(reg_ud), src_reg(sign_recovery_shift)));
emit(ASR(reg_d, src_reg(reg_d), src_reg(sign_recovery_shift)));
}
/* Apply BGRA swizzle if required. */
if (wa_flags & BRW_ATTRIB_WA_BGRA) {
src_reg temp = src_reg(reg);
temp.swizzle = BRW_SWIZZLE4(2,1,0,3);
emit(MOV(reg, temp));
}
if (wa_flags & BRW_ATTRIB_WA_NORMALIZE) {
/* ES 3.0 has different rules for converting signed normalized
* fixed-point numbers than desktop GL.
*/
if (_mesa_is_gles3(ctx) && (wa_flags & BRW_ATTRIB_WA_SIGN)) {
/* According to equation 2.2 of the ES 3.0 specification,
* signed normalization conversion is done by:
*
* f = c / (2^(b-1)-1)
*/
if (es3_normalize_factor.file == BAD_FILE) {
/* mul constant: 1 / (2^(b-1) - 1) */
es3_normalize_factor = dst_reg(this, glsl_type::vec4_type);
emit(MOV(writemask(es3_normalize_factor, WRITEMASK_XYZ),
src_reg(1.0f / ((1<<9) - 1))));
emit(MOV(writemask(es3_normalize_factor, WRITEMASK_W),
src_reg(1.0f / ((1<<1) - 1))));
}
dst_reg dst = reg;
dst.type = brw_type_for_base_type(glsl_type::vec4_type);
emit(MOV(dst, src_reg(reg_d)));
emit(MUL(dst, src_reg(dst), src_reg(es3_normalize_factor)));
emit_minmax(BRW_CONDITIONAL_G, dst, src_reg(dst), src_reg(-1.0f));
} else {
/* The following equations are from the OpenGL 3.2 specification:
*
* 2.1 unsigned normalization
* f = c/(2^n-1)
*
* 2.2 signed normalization
* f = (2c+1)/(2^n-1)
*
* Both of these share a common divisor, which is represented by
* "normalize_factor" in the code below.
*/
if (normalize_factor.file == BAD_FILE) {
/* 1 / (2^b - 1) for b=<10,10,10,2> */
normalize_factor = dst_reg(this, glsl_type::vec4_type);
emit(MOV(writemask(normalize_factor, WRITEMASK_XYZ),
src_reg(1.0f / ((1<<10) - 1))));
emit(MOV(writemask(normalize_factor, WRITEMASK_W),
src_reg(1.0f / ((1<<2) - 1))));
}
dst_reg dst = reg;
dst.type = brw_type_for_base_type(glsl_type::vec4_type);
emit(MOV(dst, src_reg((wa_flags & BRW_ATTRIB_WA_SIGN) ? reg_d : reg_ud)));
/* For signed normalization, we want the numerator to be 2c+1. */
if (wa_flags & BRW_ATTRIB_WA_SIGN) {
emit(MUL(dst, src_reg(dst), src_reg(2.0f)));
emit(ADD(dst, src_reg(dst), src_reg(1.0f)));
}
emit(MUL(dst, src_reg(dst), src_reg(normalize_factor)));
}
}
if (wa_flags & BRW_ATTRIB_WA_SCALE) {
dst_reg dst = reg;
dst.type = brw_type_for_base_type(glsl_type::vec4_type);
emit(MOV(dst, src_reg((wa_flags & BRW_ATTRIB_WA_SIGN) ? reg_d : reg_ud)));
}
}
}
}
dst_reg *
vec4_vs_visitor::make_reg_for_system_value(ir_variable *ir)
{
/* VertexID is stored by the VF as the last vertex element, but
* we don't represent it with a flag in inputs_read, so we call
* it VERT_ATTRIB_MAX, which setup_attributes() picks up on.
*/
dst_reg *reg = new(mem_ctx) dst_reg(ATTR, VERT_ATTRIB_MAX);
vs_prog_data->uses_vertexid = true;
switch (ir->data.location) {
case SYSTEM_VALUE_VERTEX_ID:
reg->writemask = WRITEMASK_X;
break;
case SYSTEM_VALUE_INSTANCE_ID:
reg->writemask = WRITEMASK_Y;
break;
default:
unreachable("not reached");
}
return reg;
}
void
vec4_vs_visitor::emit_urb_write_header(int mrf)
{
/* No need to do anything for VS; an implied write to this MRF will be
* performed by VS_OPCODE_URB_WRITE.
*/
(void) mrf;
}
vec4_instruction *
vec4_vs_visitor::emit_urb_write_opcode(bool complete)
{
/* For VS, the URB writes end the thread. */
if (complete) {
if (INTEL_DEBUG & DEBUG_SHADER_TIME)
emit_shader_time_end();
}
vec4_instruction *inst = emit(VS_OPCODE_URB_WRITE);
inst->urb_write_flags = complete ?
BRW_URB_WRITE_EOT_COMPLETE : BRW_URB_WRITE_NO_FLAGS;
return inst;
}
void
vec4_vs_visitor::emit_thread_end()
{
/* For VS, we always end the thread by emitting a single vertex.
* emit_urb_write_opcode() will take care of setting the eot flag on the
* SEND instruction.
*/
emit_vertex();
}
vec4_vs_visitor::vec4_vs_visitor(struct brw_context *brw,
struct brw_vs_compile *vs_compile,
struct brw_vs_prog_data *vs_prog_data,
struct gl_shader_program *prog,
void *mem_ctx)
: vec4_visitor(brw, &vs_compile->base, &vs_compile->vp->program.Base,
&vs_compile->key.base, &vs_prog_data->base, prog,
MESA_SHADER_VERTEX,
mem_ctx, INTEL_DEBUG & DEBUG_VS, false /* no_spills */,
ST_VS, ST_VS_WRITTEN, ST_VS_RESET),
vs_compile(vs_compile),
vs_prog_data(vs_prog_data)
{
}
} /* namespace brw */
<commit_msg>i965: Handle SYSTEM_VALUE_VERTEX_ID_ZERO_BASE<commit_after>/*
* Copyright © 2013 Intel Corporation
*
* 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 (including the next
* paragraph) 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 "brw_vs.h"
#include "main/context.h"
namespace brw {
void
vec4_vs_visitor::emit_prolog()
{
dst_reg sign_recovery_shift;
dst_reg normalize_factor;
dst_reg es3_normalize_factor;
for (int i = 0; i < VERT_ATTRIB_MAX; i++) {
if (vs_prog_data->inputs_read & BITFIELD64_BIT(i)) {
uint8_t wa_flags = vs_compile->key.gl_attrib_wa_flags[i];
dst_reg reg(ATTR, i);
dst_reg reg_d = reg;
reg_d.type = BRW_REGISTER_TYPE_D;
dst_reg reg_ud = reg;
reg_ud.type = BRW_REGISTER_TYPE_UD;
/* Do GL_FIXED rescaling for GLES2.0. Our GL_FIXED attributes
* come in as floating point conversions of the integer values.
*/
if (wa_flags & BRW_ATTRIB_WA_COMPONENT_MASK) {
dst_reg dst = reg;
dst.type = brw_type_for_base_type(glsl_type::vec4_type);
dst.writemask = (1 << (wa_flags & BRW_ATTRIB_WA_COMPONENT_MASK)) - 1;
emit(MUL(dst, src_reg(dst), src_reg(1.0f / 65536.0f)));
}
/* Do sign recovery for 2101010 formats if required. */
if (wa_flags & BRW_ATTRIB_WA_SIGN) {
if (sign_recovery_shift.file == BAD_FILE) {
/* shift constant: <22,22,22,30> */
sign_recovery_shift = dst_reg(this, glsl_type::uvec4_type);
emit(MOV(writemask(sign_recovery_shift, WRITEMASK_XYZ), src_reg(22u)));
emit(MOV(writemask(sign_recovery_shift, WRITEMASK_W), src_reg(30u)));
}
emit(SHL(reg_ud, src_reg(reg_ud), src_reg(sign_recovery_shift)));
emit(ASR(reg_d, src_reg(reg_d), src_reg(sign_recovery_shift)));
}
/* Apply BGRA swizzle if required. */
if (wa_flags & BRW_ATTRIB_WA_BGRA) {
src_reg temp = src_reg(reg);
temp.swizzle = BRW_SWIZZLE4(2,1,0,3);
emit(MOV(reg, temp));
}
if (wa_flags & BRW_ATTRIB_WA_NORMALIZE) {
/* ES 3.0 has different rules for converting signed normalized
* fixed-point numbers than desktop GL.
*/
if (_mesa_is_gles3(ctx) && (wa_flags & BRW_ATTRIB_WA_SIGN)) {
/* According to equation 2.2 of the ES 3.0 specification,
* signed normalization conversion is done by:
*
* f = c / (2^(b-1)-1)
*/
if (es3_normalize_factor.file == BAD_FILE) {
/* mul constant: 1 / (2^(b-1) - 1) */
es3_normalize_factor = dst_reg(this, glsl_type::vec4_type);
emit(MOV(writemask(es3_normalize_factor, WRITEMASK_XYZ),
src_reg(1.0f / ((1<<9) - 1))));
emit(MOV(writemask(es3_normalize_factor, WRITEMASK_W),
src_reg(1.0f / ((1<<1) - 1))));
}
dst_reg dst = reg;
dst.type = brw_type_for_base_type(glsl_type::vec4_type);
emit(MOV(dst, src_reg(reg_d)));
emit(MUL(dst, src_reg(dst), src_reg(es3_normalize_factor)));
emit_minmax(BRW_CONDITIONAL_G, dst, src_reg(dst), src_reg(-1.0f));
} else {
/* The following equations are from the OpenGL 3.2 specification:
*
* 2.1 unsigned normalization
* f = c/(2^n-1)
*
* 2.2 signed normalization
* f = (2c+1)/(2^n-1)
*
* Both of these share a common divisor, which is represented by
* "normalize_factor" in the code below.
*/
if (normalize_factor.file == BAD_FILE) {
/* 1 / (2^b - 1) for b=<10,10,10,2> */
normalize_factor = dst_reg(this, glsl_type::vec4_type);
emit(MOV(writemask(normalize_factor, WRITEMASK_XYZ),
src_reg(1.0f / ((1<<10) - 1))));
emit(MOV(writemask(normalize_factor, WRITEMASK_W),
src_reg(1.0f / ((1<<2) - 1))));
}
dst_reg dst = reg;
dst.type = brw_type_for_base_type(glsl_type::vec4_type);
emit(MOV(dst, src_reg((wa_flags & BRW_ATTRIB_WA_SIGN) ? reg_d : reg_ud)));
/* For signed normalization, we want the numerator to be 2c+1. */
if (wa_flags & BRW_ATTRIB_WA_SIGN) {
emit(MUL(dst, src_reg(dst), src_reg(2.0f)));
emit(ADD(dst, src_reg(dst), src_reg(1.0f)));
}
emit(MUL(dst, src_reg(dst), src_reg(normalize_factor)));
}
}
if (wa_flags & BRW_ATTRIB_WA_SCALE) {
dst_reg dst = reg;
dst.type = brw_type_for_base_type(glsl_type::vec4_type);
emit(MOV(dst, src_reg((wa_flags & BRW_ATTRIB_WA_SIGN) ? reg_d : reg_ud)));
}
}
}
}
dst_reg *
vec4_vs_visitor::make_reg_for_system_value(ir_variable *ir)
{
/* VertexID is stored by the VF as the last vertex element, but
* we don't represent it with a flag in inputs_read, so we call
* it VERT_ATTRIB_MAX, which setup_attributes() picks up on.
*/
dst_reg *reg = new(mem_ctx) dst_reg(ATTR, VERT_ATTRIB_MAX);
vs_prog_data->uses_vertexid = true;
switch (ir->data.location) {
case SYSTEM_VALUE_VERTEX_ID:
case SYSTEM_VALUE_VERTEX_ID_ZERO_BASE:
reg->writemask = WRITEMASK_X;
break;
case SYSTEM_VALUE_INSTANCE_ID:
reg->writemask = WRITEMASK_Y;
break;
default:
unreachable("not reached");
}
return reg;
}
void
vec4_vs_visitor::emit_urb_write_header(int mrf)
{
/* No need to do anything for VS; an implied write to this MRF will be
* performed by VS_OPCODE_URB_WRITE.
*/
(void) mrf;
}
vec4_instruction *
vec4_vs_visitor::emit_urb_write_opcode(bool complete)
{
/* For VS, the URB writes end the thread. */
if (complete) {
if (INTEL_DEBUG & DEBUG_SHADER_TIME)
emit_shader_time_end();
}
vec4_instruction *inst = emit(VS_OPCODE_URB_WRITE);
inst->urb_write_flags = complete ?
BRW_URB_WRITE_EOT_COMPLETE : BRW_URB_WRITE_NO_FLAGS;
return inst;
}
void
vec4_vs_visitor::emit_thread_end()
{
/* For VS, we always end the thread by emitting a single vertex.
* emit_urb_write_opcode() will take care of setting the eot flag on the
* SEND instruction.
*/
emit_vertex();
}
vec4_vs_visitor::vec4_vs_visitor(struct brw_context *brw,
struct brw_vs_compile *vs_compile,
struct brw_vs_prog_data *vs_prog_data,
struct gl_shader_program *prog,
void *mem_ctx)
: vec4_visitor(brw, &vs_compile->base, &vs_compile->vp->program.Base,
&vs_compile->key.base, &vs_prog_data->base, prog,
MESA_SHADER_VERTEX,
mem_ctx, INTEL_DEBUG & DEBUG_VS, false /* no_spills */,
ST_VS, ST_VS_WRITTEN, ST_VS_RESET),
vs_compile(vs_compile),
vs_prog_data(vs_prog_data)
{
}
} /* namespace brw */
<|endoftext|> |
<commit_before>// Copyright (C) 2007-2015 CEA/DEN, EDF R&D, OPEN CASCADE
//
// Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
// CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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
//
// See http://www.salome-platform.org/ or email : [email protected]
//
// SALOME TestContainer : test of container creation and its life cycle
// File : SALOME_TestComponent_i.cxx
// Author : Paul RASCLE, EDF - MARC TAJCHMAN, CEA
// Module : SALOME
// $Header$
//
#ifndef WIN32
# define private protected
#endif
#include "utilities.h"
#include "SALOME_TestComponent_i.hxx"
#include <stdio.h>
#include <cstdlib>
#include <map>
Engines_TestComponent_i::Engines_TestComponent_i(CORBA::ORB_ptr orb,
PortableServer::POA_ptr poa,
PortableServer::ObjectId * contId,
const char *instanceName,
const char *interfaceName) :
Engines_Component_i(orb, poa, contId, instanceName, interfaceName)
{
MESSAGE("activate object");
_thisObj = this ;
_id = _poa->activate_object(_thisObj);
//does not work with 4.0.6 (too bad)
//SCRUTE(_pd_refCount);
//SCRUTE(_refcount_value());
}
Engines_TestComponent_i::Engines_TestComponent_i()
{
}
Engines_TestComponent_i::~Engines_TestComponent_i()
{
MESSAGE("~Engines_TestComponent_i()");
}
char* Engines_TestComponent_i::Coucou(CORBA::Long L)
{
char s[100];
sprintf(s, "TestComponent_i : L = %ld", (long) L);
//does not work with 4.0.6 (too bad)
//SCRUTE(_pd_refCount);
//SCRUTE(_refcount_value());
return CORBA::string_dup(s);
}
void Engines_TestComponent_i::Setenv()
{
// bool overwrite = true;
std::map<std::string,CORBA::Any>::iterator it;
MESSAGE("set environment associated with keys in map _fieldsDict");
for (it = _fieldsDict.begin(); it != _fieldsDict.end(); it++)
{
std::string cle((*it).first);
if ((*it).second.type()->kind() == CORBA::tk_string)
{
const char* value;
(*it).second >>= value;
//CCRT porting : setenv not defined in stdlib.h
std::string s(cle);
s+='=';
s+=value;
//char* cast because 1st arg of linux putenv function is not a const char* !!!
putenv((char *)s.c_str());
//End of CCRT porting
//int ret = setenv(cle.c_str(), value, overwrite);
MESSAGE("--- setenv: "<<cle<<" = "<< value);
}
}
MESSAGE("read environment associated with keys in map _fieldsDict");
for (it = _fieldsDict.begin(); it != _fieldsDict.end(); it++)
{
std::string cle((*it).first);
char* valenv= getenv(cle.c_str());
if (valenv)
MESSAGE("--- getenv: "<<cle<<" = "<< valenv);
}
}
extern "C"
{
PortableServer::ObjectId * SalomeTestComponentEngine_factory(
CORBA::ORB_ptr orb,
PortableServer::POA_ptr poa,
PortableServer::ObjectId * contId,
const char *instanceName,
const char *interfaceName)
{
MESSAGE("PortableServer::ObjectId * TestComponent_factory()");
SCRUTE(interfaceName);
Engines_TestComponent_i * myTestComponent
= new Engines_TestComponent_i(orb, poa, contId, instanceName, interfaceName);
return myTestComponent->getId() ;
}
}
<commit_msg>Fix compilation problem in GCC5.2 with C++11 activated.<commit_after>// Copyright (C) 2007-2015 CEA/DEN, EDF R&D, OPEN CASCADE
//
// Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
// CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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
//
// See http://www.salome-platform.org/ or email : [email protected]
//
// SALOME TestContainer : test of container creation and its life cycle
// File : SALOME_TestComponent_i.cxx
// Author : Paul RASCLE, EDF - MARC TAJCHMAN, CEA
// Module : SALOME
// $Header$
//
#include "utilities.h"
#include "SALOME_TestComponent_i.hxx"
#include <stdio.h>
#include <cstdlib>
#include <map>
Engines_TestComponent_i::Engines_TestComponent_i(CORBA::ORB_ptr orb,
PortableServer::POA_ptr poa,
PortableServer::ObjectId * contId,
const char *instanceName,
const char *interfaceName) :
Engines_Component_i(orb, poa, contId, instanceName, interfaceName)
{
MESSAGE("activate object");
_thisObj = this ;
_id = _poa->activate_object(_thisObj);
//does not work with 4.0.6 (too bad)
//SCRUTE(_pd_refCount);
//SCRUTE(_refcount_value());
}
Engines_TestComponent_i::Engines_TestComponent_i()
{
}
Engines_TestComponent_i::~Engines_TestComponent_i()
{
MESSAGE("~Engines_TestComponent_i()");
}
char* Engines_TestComponent_i::Coucou(CORBA::Long L)
{
char s[100];
sprintf(s, "TestComponent_i : L = %ld", (long) L);
//does not work with 4.0.6 (too bad)
//SCRUTE(_pd_refCount);
//SCRUTE(_refcount_value());
return CORBA::string_dup(s);
}
void Engines_TestComponent_i::Setenv()
{
// bool overwrite = true;
std::map<std::string,CORBA::Any>::iterator it;
MESSAGE("set environment associated with keys in map _fieldsDict");
for (it = _fieldsDict.begin(); it != _fieldsDict.end(); it++)
{
std::string cle((*it).first);
if ((*it).second.type()->kind() == CORBA::tk_string)
{
const char* value;
(*it).second >>= value;
//CCRT porting : setenv not defined in stdlib.h
std::string s(cle);
s+='=';
s+=value;
//char* cast because 1st arg of linux putenv function is not a const char* !!!
putenv((char *)s.c_str());
//End of CCRT porting
//int ret = setenv(cle.c_str(), value, overwrite);
MESSAGE("--- setenv: "<<cle<<" = "<< value);
}
}
MESSAGE("read environment associated with keys in map _fieldsDict");
for (it = _fieldsDict.begin(); it != _fieldsDict.end(); it++)
{
std::string cle((*it).first);
char* valenv= getenv(cle.c_str());
if (valenv)
MESSAGE("--- getenv: "<<cle<<" = "<< valenv);
}
}
extern "C"
{
PortableServer::ObjectId * SalomeTestComponentEngine_factory(
CORBA::ORB_ptr orb,
PortableServer::POA_ptr poa,
PortableServer::ObjectId * contId,
const char *instanceName,
const char *interfaceName)
{
MESSAGE("PortableServer::ObjectId * TestComponent_factory()");
SCRUTE(interfaceName);
Engines_TestComponent_i * myTestComponent
= new Engines_TestComponent_i(orb, poa, contId, instanceName, interfaceName);
return myTestComponent->getId() ;
}
}
<|endoftext|> |
<commit_before>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2013. All rights reserved
*/
#ifndef _Stroika_Foundation_Containers_Collection_inl_
#define _Stroika_Foundation_Containers_Collection_inl_
/*
********************************************************************************
***************************** Implementation Details ***************************
********************************************************************************
*/
#include "../Debug/Assertions.h"
#include "Concrete/Collection_Factory.h"
namespace Stroika {
namespace Foundation {
namespace Containers {
/*
********************************************************************************
******************************** Collection<T> *********************************
********************************************************************************
*/
template <typename T>
inline Collection<T>::Collection ()
: inherited (Concrete::Collection_Factory<T>::mk ())
{
EnsureMember (&inherited::_GetRep (), _IRep);
}
template <typename T>
inline Collection<T>::Collection (const Collection<T>& src)
: inherited (static_cast<const inherited&> (src))
{
EnsureMember (&inherited::_GetRep (), _IRep);
}
template <typename T>
inline Collection<T>::Collection (const _SharedPtrIRep& rep)
: inherited (typename inherited::_SharedPtrIRep (rep))
{
RequireNotNull (rep);
EnsureMember (&inherited::_GetRep (), _IRep);
}
template <typename T>
inline Collection<T>::Collection (const std::initializer_list<T>& src)
: inherited (Concrete::Collection_Factory<T, TRAITS>::mk ())
{
AssertMember (&inherited::_GetRep (), _IRep);
AddAll (src);
}
template <typename T>
template <typename CONTAINER_OF_T>
inline Collection<T>::Collection (const CONTAINER_OF_T& src)
: inherited (Concrete::Collection_Factory<T>::mk ())
{
AssertMember (&inherited::_GetRep (), _IRep);
AddAll (src);
}
template <typename T>
inline Collection<T>& Collection<T>::operator= (const Collection<T>& rhs)
{
inherited::operator= (rhs);
return *this;
}
template <typename T>
inline const typename Collection<T>::_IRep& Collection<T>::_GetRep () const
{
EnsureMember (&inherited::_GetRep (), _IRep); // static_cast<> should perform better, but assert to verify safe
return *static_cast<const _IRep*> (&inherited::_GetRep ());
}
template <typename T>
inline typename Collection<T>::_IRep& Collection<T>::_GetRep ()
{
EnsureMember (&inherited::_GetRep (), _IRep); // static_cast<> should perform better, but assert to verify safe
return *static_cast<_IRep*> (&inherited::_GetRep ());
}
template <typename T>
template <typename EQUALS_COMPARER>
bool Collection<T>::Contains (T item) const
{
for (auto i : *this) {
if (EQUALS_COMPARER::Equals (i, item)) {
return true;
}
}
return false;
}
template <typename T>
inline void Collection<T>::clear ()
{
RemoveAll ();
}
template <typename T>
template <typename COPY_FROM_ITERATOR_OF_T>
void Collection<T>::AddAll (COPY_FROM_ITERATOR_OF_T start, COPY_FROM_ITERATOR_OF_T end)
{
for (auto i = start; i != end; ++i) {
Add (*i);
}
}
template <typename T>
template <typename CONTAINER_OF_T>
inline void Collection<T>::AddAll (const CONTAINER_OF_T& c)
{
/*
* Because adding items to a Collection COULD result in those items appearing in a running iterator,
* for the corner case of s.AddAll(s) - we want to assure we don't infinite loop.
*/
if (static_cast<const void*> (this) == static_cast<const void*> (std::addressof (c))) {
CONTAINER_OF_T tmp = c;
AddAll (std::begin (tmp), std::end (tmp));
}
else {
AddAll (std::begin (c), std::end (c));
}
}
template <typename T>
inline void Collection<T>::Add (T item)
{
_GetRep ().Add (item);
Ensure (not this->IsEmpty ());
}
template <typename T>
inline void Collection<T>::Update (const Iterator<T>& i, T newValue)
{
_GetRep ().Update (i, newValue);
}
template <typename T>
template <typename EQUALS_COMPARER>
inline void Collection<T>::Remove (T item)
{
for (Iterator<T> i = begin (); i != end (); ++i) {
if (EQUALS_COMPARER::Equals (*i, item)) {
_GetRep ().Remove (i);
return;
}
}
}
template <typename T>
inline void Collection<T>::RemoveAll ()
{
_GetRep ().RemoveAll ();
}
template <typename T>
template <typename COPY_FROM_ITERATOR_OF_T, typename EQUALS_COMPARER>
void Collection<T>::RemoveAll (COPY_FROM_ITERATOR_OF_T start, COPY_FROM_ITERATOR_OF_T end)
{
for (auto i = start; i != end; ++i) {
Remove<EQUALS_COMPARER> (*i);
}
}
template <typename T>
template <typename CONTAINER_OF_T, typename EQUALS_COMPARER>
inline void Collection<T>::RemoveAll (const CONTAINER_OF_T& c)
{
if (static_cast<const void*> (this) == static_cast<const void*> (std::addressof (c))) {
RemoveAll ();
}
else {
RemoveAll (std::begin (c), std::end (c));
}
}
template <typename T>
inline void Collection<T>::Remove (const Iterator<T>& i)
{
_GetRep ().Remove (i);
}
template <typename T>
inline Collection<T>& Collection<T>::operator+= (T item)
{
Add (item);
return *this;
}
template <typename T>
inline Collection<T>& Collection<T>::operator+= (const Collection<T>& items)
{
AddAll (items);
return *this;
}
/*
********************************************************************************
****************************** Collection<T>::_IRep ****************************
********************************************************************************
*/
template <typename T>
inline Collection<T>::_IRep::_IRep ()
{
}
template <typename T>
inline Collection<T>::_IRep::~_IRep ()
{
}
}
}
}
#endif /* _Stroika_Foundation_Containers_Collection_inl_ */
<commit_msg>minor tweaks to Collection<T><commit_after>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2013. All rights reserved
*/
#ifndef _Stroika_Foundation_Containers_Collection_inl_
#define _Stroika_Foundation_Containers_Collection_inl_
/*
********************************************************************************
***************************** Implementation Details ***************************
********************************************************************************
*/
#include "../Debug/Assertions.h"
#include "Concrete/Collection_Factory.h"
namespace Stroika {
namespace Foundation {
namespace Containers {
/*
********************************************************************************
******************************** Collection<T> *********************************
********************************************************************************
*/
template <typename T>
inline Collection<T>::Collection ()
: inherited (Concrete::Collection_Factory<T>::mk ())
{
EnsureMember (&inherited::_GetRep (), _IRep);
}
template <typename T>
inline Collection<T>::Collection (const Collection<T>& src)
: inherited (static_cast<const inherited&> (src))
{
EnsureMember (&inherited::_GetRep (), _IRep);
}
template <typename T>
inline Collection<T>::Collection (const _SharedPtrIRep& rep)
: inherited (typename inherited::_SharedPtrIRep (rep))
{
RequireNotNull (rep);
EnsureMember (&inherited::_GetRep (), _IRep);
}
template <typename T>
inline Collection<T>::Collection (const std::initializer_list<T>& src)
: inherited (Concrete::Collection_Factory<T, TRAITS>::mk ())
{
AssertMember (&inherited::_GetRep (), _IRep);
AddAll (src);
}
template <typename T>
template <typename CONTAINER_OF_T>
inline Collection<T>::Collection (const CONTAINER_OF_T& src)
: inherited (Concrete::Collection_Factory<T>::mk ())
{
AssertMember (&inherited::_GetRep (), _IRep);
AddAll (src);
}
template <typename T>
inline Collection<T>& Collection<T>::operator= (const Collection<T>& rhs)
{
inherited::operator= (rhs);
return *this;
}
template <typename T>
inline const typename Collection<T>::_IRep& Collection<T>::_GetRep () const
{
EnsureMember (&inherited::_GetRep (), _IRep); // static_cast<> should perform better, but assert to verify safe
return *static_cast<const _IRep*> (&inherited::_GetRep ());
}
template <typename T>
inline typename Collection<T>::_IRep& Collection<T>::_GetRep ()
{
EnsureMember (&inherited::_GetRep (), _IRep); // static_cast<> should perform better, but assert to verify safe
return *static_cast<_IRep*> (&inherited::_GetRep ());
}
template <typename T>
template <typename EQUALS_COMPARER>
bool Collection<T>::Contains (T item) const
{
for (auto i : *this) {
if (EQUALS_COMPARER::Equals (i, item)) {
return true;
}
}
return false;
}
template <typename T>
inline void Collection<T>::clear ()
{
RemoveAll ();
}
template <typename T>
template <typename COPY_FROM_ITERATOR_OF_T>
void Collection<T>::AddAll (COPY_FROM_ITERATOR_OF_T start, COPY_FROM_ITERATOR_OF_T end)
{
for (auto i = start; i != end; ++i) {
Add (*i);
}
}
template <typename T>
template <typename CONTAINER_OF_T>
inline void Collection<T>::AddAll (const CONTAINER_OF_T& c)
{
/*
* Because adding items to a Collection COULD result in those items appearing in a running iterator,
* for the corner case of s.AddAll(s) - we want to assure we don't infinite loop.
*/
if (static_cast<const void*> (this) == static_cast<const void*> (std::addressof (c))) {
CONTAINER_OF_T tmp = c;
AddAll (std::begin (tmp), std::end (tmp));
}
else {
AddAll (std::begin (c), std::end (c));
}
}
template <typename T>
inline void Collection<T>::Add (T item)
{
_GetRep ().Add (item);
Ensure (not this->IsEmpty ());
}
template <typename T>
inline void Collection<T>::Update (const Iterator<T>& i, T newValue)
{
_GetRep ().Update (i, newValue);
}
template <typename T>
template <typename EQUALS_COMPARER>
inline void Collection<T>::Remove (T item)
{
for (Iterator<T> i = this->begin (); i != this->end (); ++i) {
if (EQUALS_COMPARER::Equals (*i, item)) {
_GetRep ().Remove (i);
return;
}
}
}
template <typename T>
inline void Collection<T>::RemoveAll ()
{
_GetRep ().RemoveAll ();
}
template <typename T>
template <typename COPY_FROM_ITERATOR_OF_T, typename EQUALS_COMPARER>
void Collection<T>::RemoveAll (COPY_FROM_ITERATOR_OF_T start, COPY_FROM_ITERATOR_OF_T end)
{
for (auto i = start; i != end; ++i) {
Remove<EQUALS_COMPARER> (*i);
}
}
template <typename T>
template <typename CONTAINER_OF_T, typename EQUALS_COMPARER>
inline void Collection<T>::RemoveAll (const CONTAINER_OF_T& c)
{
if (static_cast<const void*> (this) == static_cast<const void*> (std::addressof (c))) {
RemoveAll ();
}
else {
RemoveAll (std::begin (c), std::end (c));
}
}
template <typename T>
inline void Collection<T>::Remove (const Iterator<T>& i)
{
_GetRep ().Remove (i);
}
template <typename T>
inline Collection<T>& Collection<T>::operator+= (T item)
{
Add (item);
return *this;
}
template <typename T>
inline Collection<T>& Collection<T>::operator+= (const Collection<T>& items)
{
AddAll (items);
return *this;
}
/*
********************************************************************************
****************************** Collection<T>::_IRep ****************************
********************************************************************************
*/
template <typename T>
inline Collection<T>::_IRep::_IRep ()
{
}
template <typename T>
inline Collection<T>::_IRep::~_IRep ()
{
}
}
}
}
#endif /* _Stroika_Foundation_Containers_Collection_inl_ */
<|endoftext|> |
<commit_before>// Regression test for http://llvm.org/bugs/show_bug.cgi?id=21621
// This test relies on timing between threads, so any failures will be flaky.
// RUN: LSAN_BASE="use_stacks=0:use_registers=0"
// RUN: %clangxx_lsan %s -o %t
// RUN: %run %t
#include <assert.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
void *func(void *arg) {
sleep(1);
free(arg);
return 0;
}
void create_detached_thread() {
pthread_t thread_id;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
void *arg = malloc(1337);
assert(arg);
int res = pthread_create(&thread_id, &attr, func, arg);
assert(res == 0);
}
int main() {
create_detached_thread();
}
<commit_msg>[lsan] Add debug output to leak_check_before_thread_started.cc.<commit_after>// Regression test for http://llvm.org/bugs/show_bug.cgi?id=21621
// This test relies on timing between threads, so any failures will be flaky.
// RUN: %clangxx_lsan %s -o %t
// RUN: LSAN_OPTIONS="log_pointers=1:log_threads=1" %run %t
#include <assert.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
void *func(void *arg) {
sleep(1);
free(arg);
return 0;
}
void create_detached_thread() {
pthread_t thread_id;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
void *arg = malloc(1337);
assert(arg);
int res = pthread_create(&thread_id, &attr, func, arg);
assert(res == 0);
}
int main() {
create_detached_thread();
}
<|endoftext|> |
<commit_before>/*******************************************************************************
This file is part of FeCl.
Copyright (c) 2015, Etienne Pierre-Doray, INRS
Copyright (c) 2015, Leszek Szczecinski, INRS
All rights reserved.
FeCl is free software: you can redistribute it and/or modify
it under the terms of the Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
FeCl 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 Lesser General Public License
along with FeCl. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
#include "BpDecoderImpl.h"
using namespace fec;
template <class LlrMetrics, template <class> class BoxSumAlg>
BpDecoderImpl<LlrMetrics, BoxSumAlg>::BpDecoderImpl(const Ldpc::detail::Structure& structure) :
BpDecoder(structure)
{
hardParity_.resize(this->structure().checks().cols());
parity_.resize(this->structure().checks().cols());
checkMetrics_.resize(this->structure().checks().size());
checkMetricsBuffer_.resize(this->structure().checks().size());
bitMetrics_.resize(this->structure().checks().cols());
}
template <class LlrMetrics, template <class> class BoxSumAlg>
void BpDecoderImpl<LlrMetrics, BoxSumAlg>::decodeBlock(std::vector<LlrType>::const_iterator parity, std::vector<BitField<size_t>>::iterator msg)
{
std::copy(parity, parity+structure().checks().cols(), parity_.begin());
if (structure().iterations() > 0) {
for (size_t i = 0; i < structure().checks().size(); ++i) {
checkMetrics_[i] = parity_[structure().checks().at(i)];
}
}
bool success = false;
for (int64_t i = 0; i < structure().iterations() - 1; ++i) {
checkUpdate(i);
bitUpdate();
for (size_t j = 0; j < structure().checks().cols(); ++j) {
hardParity_[j] = (bitMetrics_[j] >= 0.0);
}
if (structure().check(hardParity_.begin())) {
success = true;
break;
}
}
checkUpdate(structure().iterations()-1);
std::copy(parity_.begin(), parity_.end(), bitMetrics_.begin());
for (size_t i = 0; i < structure().checks().size(); ++i) {
bitMetrics_[structure().checks().at(i)] += checkMetrics_[i];
}
for (size_t i = 0; i < structure().innerMsgSize(); ++i) {
msg[i] = bitMetrics_[i] >= 0;
}
}
template <class LlrMetrics, template <class> class BoxSumAlg>
void BpDecoderImpl<LlrMetrics, BoxSumAlg>::soDecodeBlock(Codec::detail::InputIterator input, Codec::detail::OutputIterator output)
{
std::copy(input.parity(), input.parity()+structure().checks().cols(), parity_.begin());
if (input.hasSyst()) {
for (size_t i = 0; i < structure().innerSystSize(); ++i) {
parity_[i] += input.syst()[i];
}
}
if (input.hasState()) {
std::copy(input.state(), input.state()+structure().innerStateSize(), checkMetrics_.begin());
}
if (structure().iterations() > 0) {
if (input.hasState()) {
bitUpdate();
}
else {
for (size_t i = 0; i < structure().checks().size(); ++i) {
checkMetrics_[i] = parity_[structure().checks().at(i)];
}
}
}
bool success = false;
for (int64_t i = 0; i < structure().iterations() - 1; ++i) {
checkUpdate(i);
bitUpdate();
for (size_t j = 0; j < structure().checks().cols(); ++j) {
hardParity_[j] = (bitMetrics_[j] >= 0.0);
}
if (structure().check(hardParity_.begin())) {
success = true;
break;
}
}
checkUpdate(structure().iterations()-1);
std::fill(bitMetrics_.begin(), bitMetrics_.end(), 0);
for (size_t i = 0; i < structure().checks().size(); ++i) {
bitMetrics_[structure().checks().at(i)] += checkMetrics_[i];
}
if (output.hasSyst()) {
std::copy(bitMetrics_.begin(), bitMetrics_.begin()+structure().innerSystSize(), output.syst());
}
if (output.hasParity()) {
std::copy(bitMetrics_.begin(), bitMetrics_.begin()+structure().checks().cols(), output.parity());
}
if (output.hasState()) {
std::copy(checkMetrics_.begin(), checkMetrics_.end(), output.state());
}
if (output.hasMsg()) {
for (size_t i = 0; i < structure().innerMsgSize(); ++i) {
output.msg()[i] = parity_[i] + bitMetrics_[i];
}
}
}
template <class LlrMetrics, template <class> class BoxSumAlg>
void BpDecoderImpl<LlrMetrics, BoxSumAlg>::checkUpdate(size_t i)
{
auto checkMetric = checkMetrics_.begin();
auto checkMetricTmp = checkMetricsBuffer_.begin();
for (auto check = structure().checks().begin(); check < structure().checks().end(); ++check) {
auto first = checkMetric;
size_t size = check->size();
fec::LlrType sf = structure().scalingFactor(i, size-2);
LlrType prod = boxSum_.prior(*first);
for (size_t j = 1; j < size-1; ++j) {
checkMetricTmp[j] = boxSum_.prior(first[j]);
first[j] = prod;
prod = boxSum_.sum(prod, checkMetricTmp[j]);
}
checkMetricTmp[size-1] = boxSum_.prior(first[size-1]);
first[size-1] = sf * (boxSum_.post(prod));
prod = checkMetricTmp[size-1];
for (size_t j = size-2; j > 0; --j) {
first[j] = sf * (boxSum_.post( boxSum_.sum(first[j], prod) ));
prod = boxSum_.sum(prod, checkMetricTmp[j]);
}
*first = sf * (boxSum_.post(prod));
checkMetric += size;
}
}
template <class LlrMetrics, template <class> class BoxSumAlg>
void BpDecoderImpl<LlrMetrics, BoxSumAlg>::bitUpdate()
{
std::fill(bitMetrics_.begin(), bitMetrics_.end(), 0);
for (size_t i = 0; i < structure().checks().size(); ++i) {
checkMetricsBuffer_[i] = checkMetrics_[i];
auto& ref = bitMetrics_[structure().checks().at(i)];
checkMetrics_[i] = ref;
ref += checkMetricsBuffer_[i];
}
std::copy(parity_.begin(), parity_.begin() + bitMetrics_.size(), bitMetrics_.begin());
for (int64_t i = structure().checks().size() - 1; i >= 0; --i) {
auto& ref = bitMetrics_[structure().checks().at(i)];
checkMetrics_[i] += ref;
ref += checkMetricsBuffer_[i];
}
}
template class fec::BpDecoderImpl<FloatLlrMetrics, BoxSum>;
template class fec::BpDecoderImpl<FloatLlrMetrics, MinBoxSum>;
template class fec::BpDecoderImpl<FloatLlrMetrics, LinearBoxSum>;
<commit_msg>fix ldpc scaling<commit_after>/*******************************************************************************
This file is part of FeCl.
Copyright (c) 2015, Etienne Pierre-Doray, INRS
Copyright (c) 2015, Leszek Szczecinski, INRS
All rights reserved.
FeCl is free software: you can redistribute it and/or modify
it under the terms of the Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
FeCl 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 Lesser General Public License
along with FeCl. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
#include "BpDecoderImpl.h"
using namespace fec;
template <class LlrMetrics, template <class> class BoxSumAlg>
BpDecoderImpl<LlrMetrics, BoxSumAlg>::BpDecoderImpl(const Ldpc::detail::Structure& structure) :
BpDecoder(structure)
{
hardParity_.resize(this->structure().checks().cols());
parity_.resize(this->structure().checks().cols());
checkMetrics_.resize(this->structure().checks().size());
checkMetricsBuffer_.resize(this->structure().checks().size());
bitMetrics_.resize(this->structure().checks().cols());
}
template <class LlrMetrics, template <class> class BoxSumAlg>
void BpDecoderImpl<LlrMetrics, BoxSumAlg>::decodeBlock(std::vector<LlrType>::const_iterator parity, std::vector<BitField<size_t>>::iterator msg)
{
std::copy(parity, parity+structure().checks().cols(), parity_.begin());
if (structure().iterations() > 0) {
for (size_t i = 0; i < structure().checks().size(); ++i) {
checkMetrics_[i] = parity_[structure().checks().at(i)];
}
}
bool success = false;
for (int64_t i = 0; i < structure().iterations() - 1; ++i) {
checkUpdate(i);
bitUpdate();
for (size_t j = 0; j < structure().checks().cols(); ++j) {
hardParity_[j] = (bitMetrics_[j] >= 0.0);
}
if (structure().check(hardParity_.begin())) {
success = true;
break;
}
}
checkUpdate(structure().iterations()-1);
std::copy(parity_.begin(), parity_.end(), bitMetrics_.begin());
for (size_t i = 0; i < structure().checks().size(); ++i) {
bitMetrics_[structure().checks().at(i)] += checkMetrics_[i];
}
for (size_t i = 0; i < structure().innerMsgSize(); ++i) {
msg[i] = bitMetrics_[i] >= 0;
}
}
template <class LlrMetrics, template <class> class BoxSumAlg>
void BpDecoderImpl<LlrMetrics, BoxSumAlg>::soDecodeBlock(Codec::detail::InputIterator input, Codec::detail::OutputIterator output)
{
std::copy(input.parity(), input.parity()+structure().checks().cols(), parity_.begin());
if (input.hasSyst()) {
for (size_t i = 0; i < structure().innerSystSize(); ++i) {
parity_[i] += input.syst()[i];
}
}
if (input.hasState()) {
std::copy(input.state(), input.state()+structure().innerStateSize(), checkMetrics_.begin());
}
if (structure().iterations() > 0) {
if (input.hasState()) {
bitUpdate();
}
else {
for (size_t i = 0; i < structure().checks().size(); ++i) {
checkMetrics_[i] = parity_[structure().checks().at(i)];
}
}
}
bool success = false;
for (int64_t i = 0; i < structure().iterations() - 1; ++i) {
checkUpdate(i);
bitUpdate();
for (size_t j = 0; j < structure().checks().cols(); ++j) {
hardParity_[j] = (bitMetrics_[j] >= 0.0);
}
if (structure().check(hardParity_.begin())) {
success = true;
break;
}
}
checkUpdate(structure().iterations()-1);
std::fill(bitMetrics_.begin(), bitMetrics_.end(), 0);
for (size_t i = 0; i < structure().checks().size(); ++i) {
bitMetrics_[structure().checks().at(i)] += checkMetrics_[i];
}
if (output.hasSyst()) {
std::copy(bitMetrics_.begin(), bitMetrics_.begin()+structure().innerSystSize(), output.syst());
}
if (output.hasParity()) {
std::copy(bitMetrics_.begin(), bitMetrics_.begin()+structure().checks().cols(), output.parity());
}
if (output.hasState()) {
std::copy(checkMetrics_.begin(), checkMetrics_.end(), output.state());
}
if (output.hasMsg()) {
for (size_t i = 0; i < structure().innerMsgSize(); ++i) {
output.msg()[i] = parity_[i] + bitMetrics_[i];
}
}
}
template <class LlrMetrics, template <class> class BoxSumAlg>
void BpDecoderImpl<LlrMetrics, BoxSumAlg>::checkUpdate(size_t i)
{
auto checkMetric = checkMetrics_.begin();
auto checkMetricTmp = checkMetricsBuffer_.begin();
for (auto check = structure().checks().begin(); check < structure().checks().end(); ++check) {
auto first = checkMetric;
size_t size = check->size();
fec::LlrType sf = structure().scalingFactor(i, size);
LlrType prod = boxSum_.prior(*first);
for (size_t j = 1; j < size-1; ++j) {
checkMetricTmp[j] = boxSum_.prior(first[j]);
first[j] = prod;
prod = boxSum_.sum(prod, checkMetricTmp[j]);
}
checkMetricTmp[size-1] = boxSum_.prior(first[size-1]);
first[size-1] = sf * (boxSum_.post(prod));
prod = checkMetricTmp[size-1];
for (size_t j = size-2; j > 0; --j) {
first[j] = sf * (boxSum_.post( boxSum_.sum(first[j], prod) ));
prod = boxSum_.sum(prod, checkMetricTmp[j]);
}
*first = sf * (boxSum_.post(prod));
checkMetric += size;
}
}
template <class LlrMetrics, template <class> class BoxSumAlg>
void BpDecoderImpl<LlrMetrics, BoxSumAlg>::bitUpdate()
{
std::fill(bitMetrics_.begin(), bitMetrics_.end(), 0);
for (size_t i = 0; i < structure().checks().size(); ++i) {
checkMetricsBuffer_[i] = checkMetrics_[i];
auto& ref = bitMetrics_[structure().checks().at(i)];
checkMetrics_[i] = ref;
ref += checkMetricsBuffer_[i];
}
std::copy(parity_.begin(), parity_.begin() + bitMetrics_.size(), bitMetrics_.begin());
for (int64_t i = structure().checks().size() - 1; i >= 0; --i) {
auto& ref = bitMetrics_[structure().checks().at(i)];
checkMetrics_[i] += ref;
ref += checkMetricsBuffer_[i];
}
}
template class fec::BpDecoderImpl<FloatLlrMetrics, BoxSum>;
template class fec::BpDecoderImpl<FloatLlrMetrics, MinBoxSum>;
template class fec::BpDecoderImpl<FloatLlrMetrics, LinearBoxSum>;
<|endoftext|> |
<commit_before>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2022. All rights reserved
*/
#include "../StroikaPreComp.h"
#include "../Characters/SDKString.h"
#include "../Characters/StringBuilder.h"
#include "CommandLine.h"
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Execution;
/*
********************************************************************************
******************* Execution::InvalidCommandLineArgument **********************
********************************************************************************
*/
Execution::InvalidCommandLineArgument::InvalidCommandLineArgument ()
: Execution::RuntimeErrorException<>{L"Invalid Command Argument"sv}
{
}
Execution::InvalidCommandLineArgument::InvalidCommandLineArgument (const String& message)
: Execution::RuntimeErrorException<>{message.As<wstring> ()}
, fMessage{message}
{
}
Execution::InvalidCommandLineArgument::InvalidCommandLineArgument (const String& message, const String& argument)
: Execution::RuntimeErrorException<> (message.As<wstring> ())
, fMessage{message}
, fArgument{argument}
{
}
/*
********************************************************************************
************************* Execution::ParseCommandLine **************************
********************************************************************************
*/
Sequence<String> Execution::ParseCommandLine (const String& cmdLine)
{
using namespace Characters;
Sequence<String> result;
size_t e = cmdLine.length ();
StringBuilder curToken;
Character endQuoteChar = '\0';
for (size_t i = 0; i < e; ++i) {
Character c = cmdLine[i];
if (endQuoteChar != '\0' and c == endQuoteChar) {
result.Append (curToken.str ());
endQuoteChar = '\0';
curToken.clear ();
}
else if (c == '\'' or c == '\"') {
endQuoteChar = c;
}
else if (endQuoteChar != '\0') {
// in middle of quoted string
curToken += c;
}
else {
bool isTokenChar = not c.IsWhitespace ();
if (isTokenChar) {
curToken += c;
}
else {
if (curToken.size () != 0) {
result.Append (curToken.str ());
curToken.clear ();
}
}
}
}
if (curToken.size () != 0) {
result.Append (curToken.str ());
}
return result;
}
Sequence<String> Execution::ParseCommandLine (int argc, const char* argv[])
{
Require (argc >= 0);
Sequence<String> results;
for (int i = 0; i < argc; ++i) {
results.push_back (String::FromNarrowSDKString (argv[i]));
}
return results;
}
Sequence<String> Execution::ParseCommandLine (int argc, const wchar_t* argv[])
{
Require (argc >= 0);
Sequence<String> results;
for (int i = 0; i < argc; ++i) {
results.push_back (argv[i]);
}
return results;
}
/*
********************************************************************************
****************** Execution::MatchesCommandLineArgument ***********************
********************************************************************************
*/
namespace {
String Simplify2Compare_ (const String& actualArg)
{
return actualArg.StripAll ([] (Characters::Character c) -> bool { return c == '-' or c == '/'; }).ToLowerCase ();
}
}
bool Execution::MatchesCommandLineArgument (const String& actualArg, const String& matchesArgPattern)
{
// Command-line arguments must start with - or / (windows only)
if (actualArg.empty ()) {
return false;
}
#if qPlatform_Windows
if (actualArg[0] != '-' and actualArg[0] != '/') {
return false;
}
#else
if (actualArg[0] != '-') {
return false;
}
#endif
return Simplify2Compare_ (actualArg) == Simplify2Compare_ (matchesArgPattern);
}
bool Execution::MatchesCommandLineArgument (const Iterable<String>& argList, const String& matchesArgPattern)
{
return static_cast<bool> (argList.Find ([matchesArgPattern] (String i) -> bool { return Execution::MatchesCommandLineArgument (i, matchesArgPattern); }));
}
optional<String> Execution::MatchesCommandLineArgumentWithValue ([[maybe_unused]] const String& actualArg, [[maybe_unused]] const String& matchesArgPattern)
{
Require (matchesArgPattern.size () > 0 and matchesArgPattern[matchesArgPattern.size () - 1] == '=');
AssertNotImplemented ();
// must first strip everything after the '=' in the actualarg, and then similar to first overload...
return nullopt;
}
optional<String> Execution::MatchesCommandLineArgumentWithValue (const Iterable<String>& argList, const String& matchesArgPattern)
{
auto i = argList.Find ([matchesArgPattern] (String i) -> bool { return Execution::MatchesCommandLineArgument (i, matchesArgPattern); });
if (i != argList.end ()) {
++i;
if (i == argList.end ()) [[UNLIKELY_ATTR]] {
Execution::Throw (InvalidCommandLineArgument{});
}
else {
return optional<String> (*i);
}
}
return nullopt;
}
<commit_msg>cosmetic cleanup<commit_after>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2022. All rights reserved
*/
#include "../StroikaPreComp.h"
#include "../Characters/SDKString.h"
#include "../Characters/StringBuilder.h"
#include "CommandLine.h"
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Execution;
/*
********************************************************************************
******************* Execution::InvalidCommandLineArgument **********************
********************************************************************************
*/
Execution::InvalidCommandLineArgument::InvalidCommandLineArgument ()
: Execution::RuntimeErrorException<>{L"Invalid Command Argument"sv}
{
}
Execution::InvalidCommandLineArgument::InvalidCommandLineArgument (const String& message)
: Execution::RuntimeErrorException<>{message.As<wstring> ()}
, fMessage{message}
{
}
Execution::InvalidCommandLineArgument::InvalidCommandLineArgument (const String& message, const String& argument)
: Execution::RuntimeErrorException<> (message.As<wstring> ())
, fMessage{message}
, fArgument{argument}
{
}
/*
********************************************************************************
************************* Execution::ParseCommandLine **************************
********************************************************************************
*/
Sequence<String> Execution::ParseCommandLine (const String& cmdLine)
{
using namespace Characters;
Sequence<String> result;
size_t e = cmdLine.length ();
StringBuilder curToken;
Character endQuoteChar = '\0';
for (size_t i = 0; i < e; ++i) {
Character c = cmdLine[i];
if (endQuoteChar != '\0' and c == endQuoteChar) {
result.Append (curToken.str ());
endQuoteChar = '\0';
curToken.clear ();
}
else if (c == '\'' or c == '\"') {
endQuoteChar = c;
}
else if (endQuoteChar != '\0') {
// in middle of quoted string
curToken += c;
}
else {
bool isTokenChar = not c.IsWhitespace ();
if (isTokenChar) {
curToken += c;
}
else {
if (curToken.size () != 0) {
result.Append (curToken.str ());
curToken.clear ();
}
}
}
}
if (curToken.size () != 0) {
result.Append (curToken.str ());
}
return result;
}
Sequence<String> Execution::ParseCommandLine (int argc, const char* argv[])
{
Require (argc >= 0);
Sequence<String> results;
for (int i = 0; i < argc; ++i) {
results.push_back (String::FromNarrowSDKString (argv[i]));
}
return results;
}
Sequence<String> Execution::ParseCommandLine (int argc, const wchar_t* argv[])
{
Require (argc >= 0);
Sequence<String> results;
for (int i = 0; i < argc; ++i) {
results.push_back (argv[i]);
}
return results;
}
/*
********************************************************************************
****************** Execution::MatchesCommandLineArgument ***********************
********************************************************************************
*/
namespace {
String Simplify2Compare_ (const String& actualArg)
{
return actualArg.StripAll ([] (Characters::Character c) -> bool { return c == '-' or c == '/'; }).ToLowerCase ();
}
}
bool Execution::MatchesCommandLineArgument (const String& actualArg, const String& matchesArgPattern)
{
// Command-line arguments must start with - or / (windows only)
if (actualArg.empty ()) {
return false;
}
#if qPlatform_Windows
if (actualArg[0] != '-' and actualArg[0] != '/') {
return false;
}
#else
if (actualArg[0] != '-') {
return false;
}
#endif
return Simplify2Compare_ (actualArg) == Simplify2Compare_ (matchesArgPattern);
}
bool Execution::MatchesCommandLineArgument (const Iterable<String>& argList, const String& matchesArgPattern)
{
return static_cast<bool> (argList.Find ([matchesArgPattern] (String i) -> bool { return Execution::MatchesCommandLineArgument (i, matchesArgPattern); }));
}
optional<String> Execution::MatchesCommandLineArgumentWithValue ([[maybe_unused]] const String& actualArg, [[maybe_unused]] const String& matchesArgPattern)
{
Require (matchesArgPattern.size () > 0 and matchesArgPattern[matchesArgPattern.size () - 1] == '=');
AssertNotImplemented ();
// must first strip everything after the '=' in the actualarg, and then similar to first overload...
return nullopt;
}
optional<String> Execution::MatchesCommandLineArgumentWithValue (const Iterable<String>& argList, const String& matchesArgPattern)
{
auto i = argList.Find ([matchesArgPattern] (const String& i) -> bool { return Execution::MatchesCommandLineArgument (i, matchesArgPattern); });
if (i != argList.end ()) {
++i;
if (i == argList.end ()) [[UNLIKELY_ATTR]] {
Execution::Throw (InvalidCommandLineArgument{});
}
else {
return optional<String>{*i};
}
}
return nullopt;
}
<|endoftext|> |
<commit_before>// Copyright 2012 Cloudera 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 "runtime/row-batch.h"
#include <stdint.h> // for intptr_t
#include <boost/scoped_ptr.hpp>
#include "runtime/string-value.h"
#include "runtime/tuple-row.h"
#include "runtime/mem-tracker.h"
#include "util/compress.h"
#include "util/decompress.h"
#include "gen-cpp/Data_types.h"
using namespace boost;
using namespace std;
namespace impala {
RowBatch::RowBatch(const RowDescriptor& row_desc, int capacity,
MemTracker* mem_tracker)
: mem_tracker_(mem_tracker),
has_in_flight_row_(false),
num_rows_(0),
capacity_(capacity),
num_tuples_per_row_(row_desc.tuple_descriptors().size()),
row_desc_(row_desc),
auxiliary_mem_usage_(0),
tuple_data_pool_(new MemPool(mem_tracker_)) {
DCHECK(mem_tracker_ != NULL);
tuple_ptrs_size_ = capacity_ * num_tuples_per_row_ * sizeof(Tuple*);
tuple_ptrs_ = new Tuple*[capacity_ * num_tuples_per_row_];
mem_tracker_->Consume(tuple_ptrs_size_);
DCHECK_GT(capacity, 0);
}
// TODO: we want our input_batch's tuple_data to come from our (not yet implemented)
// global runtime memory segment; how do we get thrift to allocate it from there?
// maybe change line (in Data_types.cc generated from Data.thrift)
// xfer += iprot->readString(this->tuple_data[_i9]);
// to allocated string data in special mempool
// (change via python script that runs over Data_types.cc)
RowBatch::RowBatch(const RowDescriptor& row_desc, const TRowBatch& input_batch,
MemTracker* mem_tracker)
: mem_tracker_(mem_tracker),
has_in_flight_row_(false),
num_rows_(input_batch.num_rows),
capacity_(num_rows_),
num_tuples_per_row_(input_batch.row_tuples.size()),
row_desc_(row_desc),
tuple_ptrs_(new Tuple*[num_rows_ * input_batch.row_tuples.size()]),
auxiliary_mem_usage_(0),
tuple_data_pool_(new MemPool(mem_tracker)) {
DCHECK(mem_tracker_ != NULL);
tuple_ptrs_size_ = num_rows_ * input_batch.row_tuples.size() * sizeof(Tuple*);
mem_tracker_->Consume(tuple_ptrs_size_);
if (input_batch.is_compressed) {
// Decompress tuple data into data pool
uint8_t* compressed_data = (uint8_t*)input_batch.tuple_data.c_str();
size_t compressed_size = input_batch.tuple_data.size();
scoped_ptr<Codec> decompressor;
Status status =
Codec::CreateDecompressor(NULL, false, THdfsCompression::SNAPPY, &decompressor);
DCHECK(status.ok()) << status.GetErrorMsg();
int uncompressed_size = decompressor->MaxOutputLen(compressed_size, compressed_data);
DCHECK_NE(uncompressed_size, -1) << "RowBatch decompression failed";
uint8_t* data = tuple_data_pool_->Allocate(uncompressed_size);
status = decompressor->ProcessBlock(true, compressed_size, compressed_data,
&uncompressed_size, &data);
DCHECK(status.ok()) << "RowBatch decompression failed.";
decompressor->Close();
} else {
// Tuple data uncompressed, copy directly into data pool
uint8_t* data = tuple_data_pool_->Allocate(input_batch.tuple_data.size());
memcpy(data, input_batch.tuple_data.c_str(), input_batch.tuple_data.size());
}
// convert input_batch.tuple_offsets into pointers
int tuple_idx = 0;
for (vector<int32_t>::const_iterator offset = input_batch.tuple_offsets.begin();
offset != input_batch.tuple_offsets.end(); ++offset) {
if (*offset == -1) {
tuple_ptrs_[tuple_idx++] = NULL;
} else {
tuple_ptrs_[tuple_idx++] =
reinterpret_cast<Tuple*>(tuple_data_pool_->GetDataPtr(*offset));
}
}
// check whether we have string slots
// TODO: do that during setup (part of RowDescriptor c'tor?)
bool has_string_slots = false;
const vector<TupleDescriptor*>& tuple_descs = row_desc_.tuple_descriptors();
for (int i = 0; i < tuple_descs.size(); ++i) {
if (!tuple_descs[i]->string_slots().empty()) {
has_string_slots = true;
break;
}
}
if (!has_string_slots) return;
// convert string offsets contained in tuple data into pointers
for (int i = 0; i < num_rows_; ++i) {
TupleRow* row = GetRow(i);
vector<TupleDescriptor*>::const_iterator desc = tuple_descs.begin();
for (int j = 0; desc != tuple_descs.end(); ++desc, ++j) {
if ((*desc)->string_slots().empty()) continue;
Tuple* t = row->GetTuple(j);
if (t == NULL) continue;
vector<SlotDescriptor*>::const_iterator slot = (*desc)->string_slots().begin();
for (; slot != (*desc)->string_slots().end(); ++slot) {
DCHECK_EQ((*slot)->type(), TYPE_STRING);
StringValue* string_val = t->GetStringSlot((*slot)->tuple_offset());
string_val->ptr = reinterpret_cast<char*>(
tuple_data_pool_->GetDataPtr(reinterpret_cast<intptr_t>(string_val->ptr)));
}
}
}
}
RowBatch::~RowBatch() {
tuple_data_pool_->FreeAll();
mem_tracker_->Release(tuple_ptrs_size_);
delete [] tuple_ptrs_;
for (int i = 0; i < io_buffers_.size(); ++i) {
io_buffers_[i]->Return();
}
}
int RowBatch::Serialize(TRowBatch* output_batch) {
// why does Thrift not generate a Clear() function?
output_batch->row_tuples.clear();
output_batch->tuple_offsets.clear();
output_batch->is_compressed = false;
output_batch->num_rows = num_rows_;
row_desc_.ToThrift(&output_batch->row_tuples);
output_batch->tuple_offsets.reserve(num_rows_ * num_tuples_per_row_);
int size = TotalByteSize();
output_batch->tuple_data.resize(size);
// Copy tuple data, including strings, into output_batch (converting string
// pointers into offsets in the process)
int offset = 0; // current offset into output_batch->tuple_data
char* tuple_data = const_cast<char*>(output_batch->tuple_data.c_str());
for (int i = 0; i < num_rows_; ++i) {
TupleRow* row = GetRow(i);
const vector<TupleDescriptor*>& tuple_descs = row_desc_.tuple_descriptors();
vector<TupleDescriptor*>::const_iterator desc = tuple_descs.begin();
for (int j = 0; desc != tuple_descs.end(); ++desc, ++j) {
if (row->GetTuple(j) == NULL) {
// NULLs are encoded as -1
output_batch->tuple_offsets.push_back(-1);
continue;
}
// Record offset before creating copy (which increments offset and tuple_data)
output_batch->tuple_offsets.push_back(offset);
row->GetTuple(j)->DeepCopy(**desc, &tuple_data, &offset, /* convert_ptrs */ true);
DCHECK_LE(offset, size);
}
}
DCHECK_EQ(offset, size);
if (size > 0) {
// Try compressing tuple_data to compression_scratch_, swap if compressed data is
// smaller
scoped_ptr<Codec> compressor;
Status status =
Codec::CreateCompressor(NULL, false, THdfsCompression::SNAPPY, &compressor);
DCHECK(status.ok()) << status.GetErrorMsg();
int compressed_size = compressor->MaxOutputLen(size);
if (compression_scratch_.size() < compressed_size) {
compression_scratch_.resize(compressed_size);
}
uint8_t* input = (uint8_t*)output_batch->tuple_data.c_str();
uint8_t* compressed_output = (uint8_t*)compression_scratch_.c_str();
compressor->ProcessBlock(true, size, input, &compressed_size, &compressed_output);
if (LIKELY(compressed_size < size)) {
compression_scratch_.resize(compressed_size);
output_batch->tuple_data.swap(compression_scratch_);
output_batch->is_compressed = true;
}
VLOG_ROW << "uncompressed size: " << size << ", compressed size: " << compressed_size;
}
// The size output_batch would be if we didn't compress tuple_data (will be equal to
// actual batch size if tuple_data isn't compressed)
return GetBatchSize(*output_batch) - output_batch->tuple_data.size() + size;
}
void RowBatch::AddIoBuffer(DiskIoMgr::BufferDescriptor* buffer) {
DCHECK(buffer != NULL);
io_buffers_.push_back(buffer);
auxiliary_mem_usage_ += buffer->buffer_len();
buffer->SetMemTracker(mem_tracker_);
}
void RowBatch::Reset() {
DCHECK(tuple_data_pool_.get() != NULL);
num_rows_ = 0;
has_in_flight_row_ = false;
tuple_data_pool_->FreeAll();
tuple_data_pool_.reset(new MemPool(mem_tracker_));
for (int i = 0; i < io_buffers_.size(); ++i) {
io_buffers_[i]->Return();
}
io_buffers_.clear();
auxiliary_mem_usage_ = 0;
}
void RowBatch::TransferResourceOwnership(RowBatch* dest) {
dest->tuple_data_pool_->AcquireData(tuple_data_pool_.get(), false);
dest->auxiliary_mem_usage_ += tuple_data_pool_->total_allocated_bytes();
for (int i = 0; i < io_buffers_.size(); ++i) {
DiskIoMgr::BufferDescriptor* buffer = io_buffers_[i];
dest->io_buffers_.push_back(buffer);
dest->auxiliary_mem_usage_ += buffer->buffer_len();
buffer->SetMemTracker(dest->mem_tracker_);
}
io_buffers_.clear();
auxiliary_mem_usage_ = 0;
// make sure we can't access our tuples after we gave up the pools holding the
// tuple data
Reset();
}
int RowBatch::GetBatchSize(const TRowBatch& batch) {
int result = batch.tuple_data.size();
result += batch.row_tuples.size() * sizeof(TTupleId);
result += batch.tuple_offsets.size() * sizeof(int32_t);
return result;
}
void RowBatch::AcquireState(RowBatch* src) {
DCHECK(row_desc_.Equals(src->row_desc_));
DCHECK_EQ(num_tuples_per_row_, src->num_tuples_per_row_);
DCHECK_EQ(tuple_ptrs_size_, src->tuple_ptrs_size_);
DCHECK_EQ(capacity_, src->capacity_);
DCHECK_EQ(auxiliary_mem_usage_, 0);
// The destination row batch should be empty.
DCHECK(!has_in_flight_row_);
DCHECK_EQ(num_rows_, 0);
for (int i = 0; i < src->io_buffers_.size(); ++i) {
DiskIoMgr::BufferDescriptor* buffer = src->io_buffers_[i];
io_buffers_.push_back(buffer);
auxiliary_mem_usage_ += buffer->buffer_len();
buffer->SetMemTracker(mem_tracker_);
}
src->io_buffers_.clear();
src->auxiliary_mem_usage_ = 0;
has_in_flight_row_ = src->has_in_flight_row_;
num_rows_ = src->num_rows_;
capacity_ = src->capacity_;
std::swap(tuple_ptrs_, src->tuple_ptrs_);
tuple_data_pool_->AcquireData(src->tuple_data_pool_.get(), false);
auxiliary_mem_usage_ += src->tuple_data_pool_->total_allocated_bytes();
}
// TODO: consider computing size of batches as they are built up
int RowBatch::TotalByteSize() {
int result = 0;
for (int i = 0; i < num_rows_; ++i) {
TupleRow* row = GetRow(i);
const vector<TupleDescriptor*>& tuple_descs = row_desc_.tuple_descriptors();
vector<TupleDescriptor*>::const_iterator desc = tuple_descs.begin();
for (int j = 0; desc != tuple_descs.end(); ++desc, ++j) {
Tuple* tuple = row->GetTuple(j);
if (tuple == NULL) continue;
result += (*desc)->byte_size();
vector<SlotDescriptor*>::const_iterator slot = (*desc)->string_slots().begin();
for (; slot != (*desc)->string_slots().end(); ++slot) {
DCHECK_EQ((*slot)->type(), TYPE_STRING);
if (tuple->IsNull((*slot)->null_indicator_offset())) continue;
StringValue* string_val = tuple->GetStringSlot((*slot)->tuple_offset());
result += string_val->len;
}
}
}
return result;
}
}
<commit_msg>IMPALA-906: Fix bug in tracking of row batch auxiliary memory.<commit_after>// Copyright 2012 Cloudera 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 "runtime/row-batch.h"
#include <stdint.h> // for intptr_t
#include <boost/scoped_ptr.hpp>
#include "runtime/string-value.h"
#include "runtime/tuple-row.h"
#include "runtime/mem-tracker.h"
#include "util/compress.h"
#include "util/decompress.h"
#include "gen-cpp/Data_types.h"
using namespace boost;
using namespace std;
namespace impala {
RowBatch::RowBatch(const RowDescriptor& row_desc, int capacity,
MemTracker* mem_tracker)
: mem_tracker_(mem_tracker),
has_in_flight_row_(false),
num_rows_(0),
capacity_(capacity),
num_tuples_per_row_(row_desc.tuple_descriptors().size()),
row_desc_(row_desc),
auxiliary_mem_usage_(0),
tuple_data_pool_(new MemPool(mem_tracker_)) {
DCHECK(mem_tracker_ != NULL);
tuple_ptrs_size_ = capacity_ * num_tuples_per_row_ * sizeof(Tuple*);
tuple_ptrs_ = new Tuple*[capacity_ * num_tuples_per_row_];
mem_tracker_->Consume(tuple_ptrs_size_);
DCHECK_GT(capacity, 0);
}
// TODO: we want our input_batch's tuple_data to come from our (not yet implemented)
// global runtime memory segment; how do we get thrift to allocate it from there?
// maybe change line (in Data_types.cc generated from Data.thrift)
// xfer += iprot->readString(this->tuple_data[_i9]);
// to allocated string data in special mempool
// (change via python script that runs over Data_types.cc)
RowBatch::RowBatch(const RowDescriptor& row_desc, const TRowBatch& input_batch,
MemTracker* mem_tracker)
: mem_tracker_(mem_tracker),
has_in_flight_row_(false),
num_rows_(input_batch.num_rows),
capacity_(num_rows_),
num_tuples_per_row_(input_batch.row_tuples.size()),
row_desc_(row_desc),
tuple_ptrs_(new Tuple*[num_rows_ * input_batch.row_tuples.size()]),
auxiliary_mem_usage_(0),
tuple_data_pool_(new MemPool(mem_tracker)) {
DCHECK(mem_tracker_ != NULL);
tuple_ptrs_size_ = num_rows_ * input_batch.row_tuples.size() * sizeof(Tuple*);
mem_tracker_->Consume(tuple_ptrs_size_);
if (input_batch.is_compressed) {
// Decompress tuple data into data pool
uint8_t* compressed_data = (uint8_t*)input_batch.tuple_data.c_str();
size_t compressed_size = input_batch.tuple_data.size();
scoped_ptr<Codec> decompressor;
Status status =
Codec::CreateDecompressor(NULL, false, THdfsCompression::SNAPPY, &decompressor);
DCHECK(status.ok()) << status.GetErrorMsg();
int uncompressed_size = decompressor->MaxOutputLen(compressed_size, compressed_data);
DCHECK_NE(uncompressed_size, -1) << "RowBatch decompression failed";
uint8_t* data = tuple_data_pool_->Allocate(uncompressed_size);
status = decompressor->ProcessBlock(true, compressed_size, compressed_data,
&uncompressed_size, &data);
DCHECK(status.ok()) << "RowBatch decompression failed.";
decompressor->Close();
} else {
// Tuple data uncompressed, copy directly into data pool
uint8_t* data = tuple_data_pool_->Allocate(input_batch.tuple_data.size());
memcpy(data, input_batch.tuple_data.c_str(), input_batch.tuple_data.size());
}
// convert input_batch.tuple_offsets into pointers
int tuple_idx = 0;
for (vector<int32_t>::const_iterator offset = input_batch.tuple_offsets.begin();
offset != input_batch.tuple_offsets.end(); ++offset) {
if (*offset == -1) {
tuple_ptrs_[tuple_idx++] = NULL;
} else {
tuple_ptrs_[tuple_idx++] =
reinterpret_cast<Tuple*>(tuple_data_pool_->GetDataPtr(*offset));
}
}
// check whether we have string slots
// TODO: do that during setup (part of RowDescriptor c'tor?)
bool has_string_slots = false;
const vector<TupleDescriptor*>& tuple_descs = row_desc_.tuple_descriptors();
for (int i = 0; i < tuple_descs.size(); ++i) {
if (!tuple_descs[i]->string_slots().empty()) {
has_string_slots = true;
break;
}
}
if (!has_string_slots) return;
// convert string offsets contained in tuple data into pointers
for (int i = 0; i < num_rows_; ++i) {
TupleRow* row = GetRow(i);
vector<TupleDescriptor*>::const_iterator desc = tuple_descs.begin();
for (int j = 0; desc != tuple_descs.end(); ++desc, ++j) {
if ((*desc)->string_slots().empty()) continue;
Tuple* t = row->GetTuple(j);
if (t == NULL) continue;
vector<SlotDescriptor*>::const_iterator slot = (*desc)->string_slots().begin();
for (; slot != (*desc)->string_slots().end(); ++slot) {
DCHECK_EQ((*slot)->type(), TYPE_STRING);
StringValue* string_val = t->GetStringSlot((*slot)->tuple_offset());
string_val->ptr = reinterpret_cast<char*>(
tuple_data_pool_->GetDataPtr(reinterpret_cast<intptr_t>(string_val->ptr)));
}
}
}
}
RowBatch::~RowBatch() {
tuple_data_pool_->FreeAll();
mem_tracker_->Release(tuple_ptrs_size_);
delete [] tuple_ptrs_;
for (int i = 0; i < io_buffers_.size(); ++i) {
io_buffers_[i]->Return();
}
}
int RowBatch::Serialize(TRowBatch* output_batch) {
// why does Thrift not generate a Clear() function?
output_batch->row_tuples.clear();
output_batch->tuple_offsets.clear();
output_batch->is_compressed = false;
output_batch->num_rows = num_rows_;
row_desc_.ToThrift(&output_batch->row_tuples);
output_batch->tuple_offsets.reserve(num_rows_ * num_tuples_per_row_);
int size = TotalByteSize();
output_batch->tuple_data.resize(size);
// Copy tuple data, including strings, into output_batch (converting string
// pointers into offsets in the process)
int offset = 0; // current offset into output_batch->tuple_data
char* tuple_data = const_cast<char*>(output_batch->tuple_data.c_str());
for (int i = 0; i < num_rows_; ++i) {
TupleRow* row = GetRow(i);
const vector<TupleDescriptor*>& tuple_descs = row_desc_.tuple_descriptors();
vector<TupleDescriptor*>::const_iterator desc = tuple_descs.begin();
for (int j = 0; desc != tuple_descs.end(); ++desc, ++j) {
if (row->GetTuple(j) == NULL) {
// NULLs are encoded as -1
output_batch->tuple_offsets.push_back(-1);
continue;
}
// Record offset before creating copy (which increments offset and tuple_data)
output_batch->tuple_offsets.push_back(offset);
row->GetTuple(j)->DeepCopy(**desc, &tuple_data, &offset, /* convert_ptrs */ true);
DCHECK_LE(offset, size);
}
}
DCHECK_EQ(offset, size);
if (size > 0) {
// Try compressing tuple_data to compression_scratch_, swap if compressed data is
// smaller
scoped_ptr<Codec> compressor;
Status status =
Codec::CreateCompressor(NULL, false, THdfsCompression::SNAPPY, &compressor);
DCHECK(status.ok()) << status.GetErrorMsg();
int compressed_size = compressor->MaxOutputLen(size);
if (compression_scratch_.size() < compressed_size) {
compression_scratch_.resize(compressed_size);
}
uint8_t* input = (uint8_t*)output_batch->tuple_data.c_str();
uint8_t* compressed_output = (uint8_t*)compression_scratch_.c_str();
compressor->ProcessBlock(true, size, input, &compressed_size, &compressed_output);
if (LIKELY(compressed_size < size)) {
compression_scratch_.resize(compressed_size);
output_batch->tuple_data.swap(compression_scratch_);
output_batch->is_compressed = true;
}
VLOG_ROW << "uncompressed size: " << size << ", compressed size: " << compressed_size;
}
// The size output_batch would be if we didn't compress tuple_data (will be equal to
// actual batch size if tuple_data isn't compressed)
return GetBatchSize(*output_batch) - output_batch->tuple_data.size() + size;
}
void RowBatch::AddIoBuffer(DiskIoMgr::BufferDescriptor* buffer) {
DCHECK(buffer != NULL);
io_buffers_.push_back(buffer);
auxiliary_mem_usage_ += buffer->buffer_len();
buffer->SetMemTracker(mem_tracker_);
}
void RowBatch::Reset() {
DCHECK(tuple_data_pool_.get() != NULL);
num_rows_ = 0;
has_in_flight_row_ = false;
tuple_data_pool_->FreeAll();
tuple_data_pool_.reset(new MemPool(mem_tracker_));
for (int i = 0; i < io_buffers_.size(); ++i) {
io_buffers_[i]->Return();
}
io_buffers_.clear();
auxiliary_mem_usage_ = 0;
}
void RowBatch::TransferResourceOwnership(RowBatch* dest) {
dest->auxiliary_mem_usage_ += tuple_data_pool_->total_allocated_bytes();
dest->tuple_data_pool_->AcquireData(tuple_data_pool_.get(), false);
for (int i = 0; i < io_buffers_.size(); ++i) {
DiskIoMgr::BufferDescriptor* buffer = io_buffers_[i];
dest->io_buffers_.push_back(buffer);
dest->auxiliary_mem_usage_ += buffer->buffer_len();
buffer->SetMemTracker(dest->mem_tracker_);
}
io_buffers_.clear();
auxiliary_mem_usage_ = 0;
// make sure we can't access our tuples after we gave up the pools holding the
// tuple data
Reset();
}
int RowBatch::GetBatchSize(const TRowBatch& batch) {
int result = batch.tuple_data.size();
result += batch.row_tuples.size() * sizeof(TTupleId);
result += batch.tuple_offsets.size() * sizeof(int32_t);
return result;
}
void RowBatch::AcquireState(RowBatch* src) {
DCHECK(row_desc_.Equals(src->row_desc_));
DCHECK_EQ(num_tuples_per_row_, src->num_tuples_per_row_);
DCHECK_EQ(tuple_ptrs_size_, src->tuple_ptrs_size_);
DCHECK_EQ(capacity_, src->capacity_);
DCHECK_EQ(auxiliary_mem_usage_, 0);
// The destination row batch should be empty.
DCHECK(!has_in_flight_row_);
DCHECK_EQ(num_rows_, 0);
for (int i = 0; i < src->io_buffers_.size(); ++i) {
DiskIoMgr::BufferDescriptor* buffer = src->io_buffers_[i];
io_buffers_.push_back(buffer);
auxiliary_mem_usage_ += buffer->buffer_len();
buffer->SetMemTracker(mem_tracker_);
}
src->io_buffers_.clear();
src->auxiliary_mem_usage_ = 0;
has_in_flight_row_ = src->has_in_flight_row_;
num_rows_ = src->num_rows_;
capacity_ = src->capacity_;
std::swap(tuple_ptrs_, src->tuple_ptrs_);
tuple_data_pool_->AcquireData(src->tuple_data_pool_.get(), false);
auxiliary_mem_usage_ += src->tuple_data_pool_->total_allocated_bytes();
}
// TODO: consider computing size of batches as they are built up
int RowBatch::TotalByteSize() {
int result = 0;
for (int i = 0; i < num_rows_; ++i) {
TupleRow* row = GetRow(i);
const vector<TupleDescriptor*>& tuple_descs = row_desc_.tuple_descriptors();
vector<TupleDescriptor*>::const_iterator desc = tuple_descs.begin();
for (int j = 0; desc != tuple_descs.end(); ++desc, ++j) {
Tuple* tuple = row->GetTuple(j);
if (tuple == NULL) continue;
result += (*desc)->byte_size();
vector<SlotDescriptor*>::const_iterator slot = (*desc)->string_slots().begin();
for (; slot != (*desc)->string_slots().end(); ++slot) {
DCHECK_EQ((*slot)->type(), TYPE_STRING);
if (tuple->IsNull((*slot)->null_indicator_offset())) continue;
StringValue* string_val = tuple->GetStringSlot((*slot)->tuple_offset());
result += string_val->len;
}
}
}
return result;
}
}
<|endoftext|> |
<commit_before>#include "display_buffer.hh"
#include "assert.hh"
#include "buffer.hh"
#include "buffer_utils.hh"
#include "face_registry.hh"
#include "utf8.hh"
#include "face_registry.hh"
namespace Kakoune
{
BufferIterator get_iterator(const Buffer& buffer, BufferCoord coord)
{
// Correct one past the end of line as next line
if (not buffer.is_end(coord) and coord.column == buffer[coord.line].length())
coord = coord.line+1;
return buffer.iterator_at(coord);
}
StringView DisplayAtom::content() const
{
switch (m_type)
{
case Range:
{
auto line = (*m_buffer)[m_range.begin.line];
if (m_range.begin.line == m_range.end.line)
return line.substr(m_range.begin.column, m_range.end.column - m_range.begin.column);
else if (m_range.begin.line+1 == m_range.end.line and m_range.end.column == 0)
return line.substr(m_range.begin.column);
break;
}
case Text:
case ReplacedRange:
return m_text;
}
kak_assert(false);
return {};
}
ColumnCount DisplayAtom::length() const
{
switch (m_type)
{
case Range:
return utf8::column_distance(get_iterator(*m_buffer, m_range.begin),
get_iterator(*m_buffer, m_range.end));
case Text:
case ReplacedRange:
return m_text.column_length();
}
kak_assert(false);
return 0;
}
void DisplayAtom::trim_begin(ColumnCount count)
{
if (m_type == Range)
m_range.begin = utf8::advance(get_iterator(*m_buffer, m_range.begin),
get_iterator(*m_buffer, m_range.end),
count).coord();
else
m_text = m_text.substr(count).str();
}
void DisplayAtom::trim_end(ColumnCount count)
{
if (m_type == Range)
m_range.end = utf8::advance(get_iterator(*m_buffer, m_range.end),
get_iterator(*m_buffer, m_range.begin),
-count).coord();
else
m_text = m_text.substr(0, m_text.column_length() - count).str();
}
DisplayLine::DisplayLine(AtomList atoms)
: m_atoms(std::move(atoms))
{
compute_range();
}
DisplayLine::iterator DisplayLine::split(iterator it, BufferCoord pos)
{
kak_assert(it->type() == DisplayAtom::Range);
kak_assert(it->begin() < pos);
kak_assert(it->end() > pos);
DisplayAtom atom = *it;
atom.m_range.end = pos;
it->m_range.begin = pos;
return m_atoms.insert(it, std::move(atom));
}
DisplayLine::iterator DisplayLine::split(iterator it, ColumnCount count)
{
kak_assert(count > 0);
kak_assert(count < it->length());
if (it->type() == DisplayAtom::Text or it->type() == DisplayAtom::ReplacedRange)
{
DisplayAtom atom = *it;
atom.m_text = atom.m_text.substr(0, count).str();
it->m_text = it->m_text.substr(count).str();
return m_atoms.insert(it, std::move(atom));
}
auto pos = utf8::advance(get_iterator(it->buffer(), it->begin()),
get_iterator(it->buffer(), it->end()),
count).coord();
return split(it, pos);
}
DisplayLine::iterator DisplayLine::insert(iterator it, DisplayAtom atom)
{
if (atom.has_buffer_range())
{
m_range.begin = std::min(m_range.begin, atom.begin());
m_range.end = std::max(m_range.end, atom.end());
}
return m_atoms.insert(it, std::move(atom));
}
void DisplayLine::push_back(DisplayAtom atom)
{
if (atom.has_buffer_range())
{
m_range.begin = std::min(m_range.begin, atom.begin());
m_range.end = std::max(m_range.end, atom.end());
}
m_atoms.push_back(std::move(atom));
}
DisplayLine::iterator DisplayLine::erase(iterator beg, iterator end)
{
auto res = m_atoms.erase(beg, end);
compute_range();
return res;
}
void DisplayLine::optimize()
{
if (m_atoms.empty())
return;
auto atom_it = m_atoms.begin();
for (auto next_it = atom_it + 1; next_it != m_atoms.end(); ++next_it)
{
auto& atom = *atom_it;
auto& next = *next_it;
const auto type = atom.type();
if (type == next.type() and atom.face == next.face)
{
if (type == DisplayAtom::Text)
atom.m_text += next.m_text;
else if ((type == DisplayAtom::Range or
type == DisplayAtom::ReplacedRange) and
next.begin() == atom.end())
{
atom.m_range.end = next.end();
if (type == DisplayAtom::ReplacedRange)
atom.m_text += next.m_text;
}
else
*++atom_it = std::move(*next_it);
}
else
*++atom_it = std::move(*next_it);
}
m_atoms.erase(atom_it+1, m_atoms.end());
}
ColumnCount DisplayLine::length() const
{
ColumnCount len = 0;
for (auto& atom : m_atoms)
len += atom.length();
return len;
}
bool DisplayLine::trim(ColumnCount first_col, ColumnCount col_count)
{
for (auto it = begin(); first_col > 0 and it != end(); )
{
auto len = it->length();
if (len <= first_col)
{
m_atoms.erase(it);
first_col -= len;
}
else
{
it->trim_begin(first_col);
first_col = 0;
}
}
auto it = begin();
for (; it != end() and col_count > 0; ++it)
col_count -= it->length();
bool did_trim = it != end() || col_count < 0;
if (col_count < 0)
(it-1)->trim_end(-col_count);
m_atoms.erase(it, end());
compute_range();
return did_trim;
}
const BufferRange init_range{ {INT_MAX, INT_MAX}, {INT_MIN, INT_MIN} };
void DisplayLine::compute_range()
{
m_range = init_range;
for (auto& atom : m_atoms)
{
if (not atom.has_buffer_range())
continue;
m_range.begin = std::min(m_range.begin, atom.begin());
m_range.end = std::max(m_range.end, atom.end());
}
if (m_range == init_range)
m_range = { { 0, 0 }, { 0, 0 } };
kak_assert(m_range.begin <= m_range.end);
}
void DisplayBuffer::compute_range()
{
m_range = init_range;
for (auto& line : m_lines)
{
m_range.begin = std::min(line.range().begin, m_range.begin);
m_range.end = std::max(line.range().end, m_range.end);
}
if (m_range == init_range)
m_range = { { 0, 0 }, { 0, 0 } };
kak_assert(m_range.begin <= m_range.end);
}
void DisplayBuffer::optimize()
{
for (auto& line : m_lines)
line.optimize();
}
DisplayLine parse_display_line(StringView line, const FaceRegistry& faces, const HashMap<String, DisplayLine>& builtins)
{
DisplayLine res;
bool was_antislash = false;
auto pos = line.begin();
String content;
Face face;
for (auto it = line.begin(), end = line.end(); it != end; ++it)
{
const char c = *it;
if (c == '{')
{
if (was_antislash)
{
content += StringView{pos, it};
content.back() = '{';
pos = it + 1;
}
else
{
content += StringView{pos, it};
res.push_back({std::move(content), face});
content.clear();
auto closing = std::find(it+1, end, '}');
if (closing == end)
throw runtime_error("unclosed face definition");
if (*(it+1) == '{' and closing+1 != end and *(closing+1) == '}')
{
auto builtin_it = builtins.find(StringView{it+2, closing});
if (builtin_it == builtins.end())
throw runtime_error(format("undefined atom {}", StringView{it+2, closing}));
for (auto& atom : builtin_it->value)
res.push_back(atom);
// closing is now at the first char of "}}", advance it to the second
++closing;
}
else if (closing == it+2 and *(it+1) == '\\')
{
pos = closing + 1;
break;
}
else
face = faces[{it+1, closing}];
it = closing;
pos = closing + 1;
}
}
if (c == '\n' or c == '\t') // line breaks and tabs are forbidden, replace with space
{
content += StringView{pos, it+1};
content.back() = ' ';
pos = it + 1;
}
if (c == '\\')
{
if (was_antislash)
{
content += StringView{pos, it};
pos = it + 1;
was_antislash = false;
}
else
was_antislash = true;
}
else
was_antislash = false;
}
content += StringView{pos, line.end()};
if (not content.empty())
res.push_back({std::move(content), face});
return res;
}
String fix_atom_text(StringView str)
{
String res;
auto pos = str.begin();
for (auto it = str.begin(), end = str.end(); it != end; ++it)
{
char c = *it;
if (c == '\n' or c == '\r')
{
res += StringView{pos, it};
res += c == '\n' ? "" : "␍";
pos = it+1;
}
}
res += StringView{pos, str.end()};
return res;
}
}
<commit_msg>Use Control Picture codepoints in prompt for all codepoints < 0x22<commit_after>#include "display_buffer.hh"
#include "assert.hh"
#include "buffer.hh"
#include "buffer_utils.hh"
#include "face_registry.hh"
#include "utf8.hh"
#include "face_registry.hh"
namespace Kakoune
{
BufferIterator get_iterator(const Buffer& buffer, BufferCoord coord)
{
// Correct one past the end of line as next line
if (not buffer.is_end(coord) and coord.column == buffer[coord.line].length())
coord = coord.line+1;
return buffer.iterator_at(coord);
}
StringView DisplayAtom::content() const
{
switch (m_type)
{
case Range:
{
auto line = (*m_buffer)[m_range.begin.line];
if (m_range.begin.line == m_range.end.line)
return line.substr(m_range.begin.column, m_range.end.column - m_range.begin.column);
else if (m_range.begin.line+1 == m_range.end.line and m_range.end.column == 0)
return line.substr(m_range.begin.column);
break;
}
case Text:
case ReplacedRange:
return m_text;
}
kak_assert(false);
return {};
}
ColumnCount DisplayAtom::length() const
{
switch (m_type)
{
case Range:
return utf8::column_distance(get_iterator(*m_buffer, m_range.begin),
get_iterator(*m_buffer, m_range.end));
case Text:
case ReplacedRange:
return m_text.column_length();
}
kak_assert(false);
return 0;
}
void DisplayAtom::trim_begin(ColumnCount count)
{
if (m_type == Range)
m_range.begin = utf8::advance(get_iterator(*m_buffer, m_range.begin),
get_iterator(*m_buffer, m_range.end),
count).coord();
else
m_text = m_text.substr(count).str();
}
void DisplayAtom::trim_end(ColumnCount count)
{
if (m_type == Range)
m_range.end = utf8::advance(get_iterator(*m_buffer, m_range.end),
get_iterator(*m_buffer, m_range.begin),
-count).coord();
else
m_text = m_text.substr(0, m_text.column_length() - count).str();
}
DisplayLine::DisplayLine(AtomList atoms)
: m_atoms(std::move(atoms))
{
compute_range();
}
DisplayLine::iterator DisplayLine::split(iterator it, BufferCoord pos)
{
kak_assert(it->type() == DisplayAtom::Range);
kak_assert(it->begin() < pos);
kak_assert(it->end() > pos);
DisplayAtom atom = *it;
atom.m_range.end = pos;
it->m_range.begin = pos;
return m_atoms.insert(it, std::move(atom));
}
DisplayLine::iterator DisplayLine::split(iterator it, ColumnCount count)
{
kak_assert(count > 0);
kak_assert(count < it->length());
if (it->type() == DisplayAtom::Text or it->type() == DisplayAtom::ReplacedRange)
{
DisplayAtom atom = *it;
atom.m_text = atom.m_text.substr(0, count).str();
it->m_text = it->m_text.substr(count).str();
return m_atoms.insert(it, std::move(atom));
}
auto pos = utf8::advance(get_iterator(it->buffer(), it->begin()),
get_iterator(it->buffer(), it->end()),
count).coord();
return split(it, pos);
}
DisplayLine::iterator DisplayLine::insert(iterator it, DisplayAtom atom)
{
if (atom.has_buffer_range())
{
m_range.begin = std::min(m_range.begin, atom.begin());
m_range.end = std::max(m_range.end, atom.end());
}
return m_atoms.insert(it, std::move(atom));
}
void DisplayLine::push_back(DisplayAtom atom)
{
if (atom.has_buffer_range())
{
m_range.begin = std::min(m_range.begin, atom.begin());
m_range.end = std::max(m_range.end, atom.end());
}
m_atoms.push_back(std::move(atom));
}
DisplayLine::iterator DisplayLine::erase(iterator beg, iterator end)
{
auto res = m_atoms.erase(beg, end);
compute_range();
return res;
}
void DisplayLine::optimize()
{
if (m_atoms.empty())
return;
auto atom_it = m_atoms.begin();
for (auto next_it = atom_it + 1; next_it != m_atoms.end(); ++next_it)
{
auto& atom = *atom_it;
auto& next = *next_it;
const auto type = atom.type();
if (type == next.type() and atom.face == next.face)
{
if (type == DisplayAtom::Text)
atom.m_text += next.m_text;
else if ((type == DisplayAtom::Range or
type == DisplayAtom::ReplacedRange) and
next.begin() == atom.end())
{
atom.m_range.end = next.end();
if (type == DisplayAtom::ReplacedRange)
atom.m_text += next.m_text;
}
else
*++atom_it = std::move(*next_it);
}
else
*++atom_it = std::move(*next_it);
}
m_atoms.erase(atom_it+1, m_atoms.end());
}
ColumnCount DisplayLine::length() const
{
ColumnCount len = 0;
for (auto& atom : m_atoms)
len += atom.length();
return len;
}
bool DisplayLine::trim(ColumnCount first_col, ColumnCount col_count)
{
for (auto it = begin(); first_col > 0 and it != end(); )
{
auto len = it->length();
if (len <= first_col)
{
m_atoms.erase(it);
first_col -= len;
}
else
{
it->trim_begin(first_col);
first_col = 0;
}
}
auto it = begin();
for (; it != end() and col_count > 0; ++it)
col_count -= it->length();
bool did_trim = it != end() || col_count < 0;
if (col_count < 0)
(it-1)->trim_end(-col_count);
m_atoms.erase(it, end());
compute_range();
return did_trim;
}
const BufferRange init_range{ {INT_MAX, INT_MAX}, {INT_MIN, INT_MIN} };
void DisplayLine::compute_range()
{
m_range = init_range;
for (auto& atom : m_atoms)
{
if (not atom.has_buffer_range())
continue;
m_range.begin = std::min(m_range.begin, atom.begin());
m_range.end = std::max(m_range.end, atom.end());
}
if (m_range == init_range)
m_range = { { 0, 0 }, { 0, 0 } };
kak_assert(m_range.begin <= m_range.end);
}
void DisplayBuffer::compute_range()
{
m_range = init_range;
for (auto& line : m_lines)
{
m_range.begin = std::min(line.range().begin, m_range.begin);
m_range.end = std::max(line.range().end, m_range.end);
}
if (m_range == init_range)
m_range = { { 0, 0 }, { 0, 0 } };
kak_assert(m_range.begin <= m_range.end);
}
void DisplayBuffer::optimize()
{
for (auto& line : m_lines)
line.optimize();
}
DisplayLine parse_display_line(StringView line, const FaceRegistry& faces, const HashMap<String, DisplayLine>& builtins)
{
DisplayLine res;
bool was_antislash = false;
auto pos = line.begin();
String content;
Face face;
for (auto it = line.begin(), end = line.end(); it != end; ++it)
{
const char c = *it;
if (c == '{')
{
if (was_antislash)
{
content += StringView{pos, it};
content.back() = '{';
pos = it + 1;
}
else
{
content += StringView{pos, it};
res.push_back({std::move(content), face});
content.clear();
auto closing = std::find(it+1, end, '}');
if (closing == end)
throw runtime_error("unclosed face definition");
if (*(it+1) == '{' and closing+1 != end and *(closing+1) == '}')
{
auto builtin_it = builtins.find(StringView{it+2, closing});
if (builtin_it == builtins.end())
throw runtime_error(format("undefined atom {}", StringView{it+2, closing}));
for (auto& atom : builtin_it->value)
res.push_back(atom);
// closing is now at the first char of "}}", advance it to the second
++closing;
}
else if (closing == it+2 and *(it+1) == '\\')
{
pos = closing + 1;
break;
}
else
face = faces[{it+1, closing}];
it = closing;
pos = closing + 1;
}
}
if (c == '\n' or c == '\t') // line breaks and tabs are forbidden, replace with space
{
content += StringView{pos, it+1};
content.back() = ' ';
pos = it + 1;
}
if (c == '\\')
{
if (was_antislash)
{
content += StringView{pos, it};
pos = it + 1;
was_antislash = false;
}
else
was_antislash = true;
}
else
was_antislash = false;
}
content += StringView{pos, line.end()};
if (not content.empty())
res.push_back({std::move(content), face});
return res;
}
String fix_atom_text(StringView str)
{
String res;
auto pos = str.begin();
for (auto it = str.begin(), end = str.end(); it != end; ++it)
{
char c = *it;
if (c <= 0x21)
{
res += StringView{pos, it};
res += String{Codepoint{(uint32_t)(0x2400 + c)}};
pos = it+1;
}
}
res += StringView{pos, str.end()};
return res;
}
}
<|endoftext|> |
<commit_before>#include "dlangindenter.h"
#include <texteditor/tabsettings.h>
#include <texteditor/textdocumentlayout.h>
#include <QTextDocument>
#include <QTextBlock>
#include <QTextCursor>
using namespace DlangEditor;
enum {
INDENTER_USER_FORMAT_ID = QTextFormat::UserFormat + 1
};
DlangIndenter::DlangIndenter()
{
}
bool DlangIndenter::isElectricCharacter(const QChar &ch) const
{
if (ch == QLatin1Char('{')
|| ch == QLatin1Char('}')) {
return true;
}
return false;
}
class IndenterUserFormat
{
public:
int indent;
int padding;
IndenterUserFormat() : indent(0), padding(0) {}
};
Q_DECLARE_METATYPE(IndenterUserFormat)
IndenterUserFormat calculateIndent(const QTextBlock &origBlock, int tabSize)
{
QTextBlock block = origBlock;
QTextBlock prev = block;
do {
prev = prev.previous();
if (!prev.isValid()) {
return IndenterUserFormat();
}
} while (prev.text().trimmed().isEmpty());
IndenterUserFormat prevData = prev.blockFormat().property(INDENTER_USER_FORMAT_ID).value<IndenterUserFormat>();
int indent = 0;
int padding = 0;
QString text = prev.text();
const int prevLen = text.length();
int prevIndent = 0;
for (int i = 0; i < prevLen; ++i) {
const char c = text.at(i).toLatin1();
if (!text.at(i).isSpace() && prevIndent == 0) {
prevIndent = i;
}
switch (c) {
case '{': indent += tabSize; padding = 0; break;
case '}': indent -= tabSize; padding = 0; break;
case ')':
case ':':
case ';': padding = 0; break;
default: padding = tabSize; break;
}
}
if (prevIndent >= 0 && text.at(prevIndent) == QChar('}')) {
indent += tabSize;
}
text = block.text().trimmed();
if (text.startsWith('}')) {
indent -= tabSize;
}
auto setBlockIndenterData = [](QTextBlock& block, IndenterUserFormat d) {
QTextCursor c(block);
auto f = c.blockFormat();
f.setProperty(INDENTER_USER_FORMAT_ID, QVariant::fromValue(d));
c.setBlockFormat(f);
};
if (prevData.indent != prevIndent) {
prevData.indent = prevIndent;
setBlockIndenterData(prev, prevData);
}
IndenterUserFormat blockData;
blockData.indent = indent + prevIndent - prevData.padding + padding;
blockData.padding = padding;
if (padding) {
if (prevData.padding) {
indent = prevData.indent;
padding = prevData.padding;
}
}
setBlockIndenterData(block, blockData);
return blockData;
}
void DlangIndenter::indentBlock(QTextDocument *doc,
const QTextBlock &block,
const QChar &/*typedChar*/,
const TextEditor::TabSettings &tabSettings)
{
// At beginning: Leave as is.
if (block == doc->begin())
return;
const auto align = calculateIndent(block, tabSettings.m_indentSize);
tabSettings.indentLine(block, align.indent, align.padding);
}
<commit_msg>Indention fix<commit_after>#include "dlangindenter.h"
#include <texteditor/tabsettings.h>
#include <texteditor/textdocumentlayout.h>
#include <QTextDocument>
#include <QTextBlock>
#include <QTextCursor>
using namespace DlangEditor;
enum {
INDENTER_USER_FORMAT_ID = QTextFormat::UserFormat + 1
};
DlangIndenter::DlangIndenter()
{
}
bool DlangIndenter::isElectricCharacter(const QChar &ch) const
{
if (ch == QLatin1Char('{')
|| ch == QLatin1Char('}')) {
return true;
}
return false;
}
class IndenterUserFormat
{
public:
int indent;
int padding;
IndenterUserFormat() : indent(0), padding(0) {}
};
Q_DECLARE_METATYPE(IndenterUserFormat)
IndenterUserFormat calculateIndent(const QTextBlock &origBlock, int tabSize)
{
QTextBlock block = origBlock;
QTextBlock prev = block;
do {
prev = prev.previous();
if (!prev.isValid()) {
return IndenterUserFormat();
}
} while (prev.text().trimmed().isEmpty());
IndenterUserFormat prevData = prev.blockFormat().property(INDENTER_USER_FORMAT_ID).value<IndenterUserFormat>();
int indent = 0;
int padding = 0;
QString text = prev.text();
const int prevLen = text.length();
int prevIndent = -1;
QChar lastChar;
for (int i = 0; i < prevLen; ++i) {
const QChar qc = text.at(i);
if (!qc.isSpace()) {
if (prevIndent == -1) {
prevIndent = i;
}
lastChar = qc;
} else {
continue;
}
const char c = qc.toLatin1();
switch (c) {
case '{': indent += tabSize; padding = 0; break;
case '}': indent -= tabSize; padding = 0; break;
case ')':
case ':':
case ';': padding = 0; break;
default: padding = tabSize; break;
}
}
if (prevIndent >= 0) {
if (text.at(prevIndent) == QChar('}')) {
indent += tabSize;
}
} else {
prevIndent = 0;
}
text = block.text().trimmed();
if (text.startsWith('}')) {
indent -= tabSize;
} else if (text.startsWith('{')) {
padding = 0;
}
auto setBlockIndenterData = [](QTextBlock& block, IndenterUserFormat d) {
QTextCursor c(block);
auto f = c.blockFormat();
f.setProperty(INDENTER_USER_FORMAT_ID, QVariant::fromValue(d));
c.setBlockFormat(f);
};
if (prevData.indent != prevIndent) {
prevData.indent = prevIndent;
setBlockIndenterData(prev, prevData);
}
IndenterUserFormat blockData;
blockData.indent = indent + prevIndent - prevData.padding + padding;
blockData.padding = padding;
if (padding) {
if (prevData.padding) {
indent = prevData.indent;
padding = prevData.padding;
}
}
setBlockIndenterData(block, blockData);
return blockData;
}
void DlangIndenter::indentBlock(QTextDocument *doc,
const QTextBlock &block,
const QChar &/*typedChar*/,
const TextEditor::TabSettings &tabSettings)
{
// At beginning: Leave as is.
if (block == doc->begin())
return;
const auto align = calculateIndent(block, tabSettings.m_indentSize);
tabSettings.indentLine(block, align.indent, align.padding);
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2006-2013 Music Technology Group - Universitat Pompeu Fabra
*
* This file is part of Essentia
*
* Essentia is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License as published by the Free
* Software Foundation (FSF), either version 3 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the Affero GNU General Public License
* version 3 along with this program. If not, see http://www.gnu.org/licenses/
*/
#include "centroid.h"
using namespace essentia;
using namespace standard;
const char* Centroid::name = "Centroid";
const char* Centroid::description = DOC("This algorithm extracts the centroid (first order central moment), normalized to a specified range, of the input array.\n"
"Note:\n"
" - For a spectral centroid [hz], frequency range should be equal to samplerate/2\n"
" - For an audio centroid [s], range should be equal to (audio_size_in_samples-1) / samplerate\n"
"Exceptions are thrown when input array contains less than 2 elements.\n"
"\n"
"References:\n"
" [1] Function Centroid -- from Wolfram MathWorld,\n"
" http://mathworld.wolfram.com/FunctionCentroid.html");
void Centroid::configure() {
// get the range parameter as a Real (its native type) in the configure()
// method instead of the compute() one, so we just need to do this once when
// the object is configured, and not each time we call the compute() method.
_range = parameter("range").toReal();
}
void Centroid::compute() {
const std::vector<Real>& array = _array.get();
Real& centroid = _centroid.get();
if (array.empty()) {
throw EssentiaException("Centroid: cannot compute the centroid of an empty array");
}
if (array.size() == 1) {
throw EssentiaException("Centroid: cannot compute the centroid of an array of size 1");
}
centroid = 0.0;
Real weights = 0.0;
for (int i=0; i<int(array.size()); ++i) {
centroid += i * array[i];
weights += array[i];
}
if (weights != 0.0) {
centroid /= weights;
}
else {
centroid = 0.0;
}
centroid *= _range / (array.size() - 1);
}
<commit_msg>Add link to spectral centroid wiki article to docs<commit_after>/*
* Copyright (C) 2006-2013 Music Technology Group - Universitat Pompeu Fabra
*
* This file is part of Essentia
*
* Essentia is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License as published by the Free
* Software Foundation (FSF), either version 3 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the Affero GNU General Public License
* version 3 along with this program. If not, see http://www.gnu.org/licenses/
*/
#include "centroid.h"
using namespace essentia;
using namespace standard;
const char* Centroid::name = "Centroid";
const char* Centroid::description = DOC("This algorithm extracts the centroid (first order central moment), normalized to a specified range, of the input array.\n"
"Note:\n"
" - For a spectral centroid [hz], frequency range should be equal to samplerate/2\n"
" - For an audio centroid [s], range should be equal to (audio_size_in_samples-1) / samplerate\n"
"Exceptions are thrown when input array contains less than 2 elements.\n"
"\n"
"References:\n"
" [1] Function Centroid -- from Wolfram MathWorld,\n"
" http://mathworld.wolfram.com/FunctionCentroid.html\n"
" [2] Spectral centroid - Wikipedia, the free encyclopedia,\n"
" https://en.wikipedia.org/wiki/Spectral_centroid");
void Centroid::configure() {
// get the range parameter as a Real (its native type) in the configure()
// method instead of the compute() one, so we just need to do this once when
// the object is configured, and not each time we call the compute() method.
_range = parameter("range").toReal();
}
void Centroid::compute() {
const std::vector<Real>& array = _array.get();
Real& centroid = _centroid.get();
if (array.empty()) {
throw EssentiaException("Centroid: cannot compute the centroid of an empty array");
}
if (array.size() == 1) {
throw EssentiaException("Centroid: cannot compute the centroid of an array of size 1");
}
centroid = 0.0;
Real weights = 0.0;
for (int i=0; i<int(array.size()); ++i) {
centroid += i * array[i];
weights += array[i];
}
if (weights != 0.0) {
centroid /= weights;
}
else {
centroid = 0.0;
}
centroid *= _range / (array.size() - 1);
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2015 Samsung Electronics Co., Ltd All Rights Reserved
*
* 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
* @file
* @author Lukasz Pawelczyk ([email protected])
* @brief LXCPP guard process implementation
*/
#include "config.hpp"
#include "lxcpp/utils.hpp"
#include "lxcpp/guard/guard.hpp"
#include "lxcpp/process.hpp"
#include "lxcpp/credentials.hpp"
#include "lxcpp/hostname.hpp"
#include "lxcpp/rlimit.hpp"
#include "lxcpp/sysctl.hpp"
#include "lxcpp/capability.hpp"
#include "lxcpp/environment.hpp"
#include "lxcpp/commands/prep-guest-terminal.hpp"
#include "lxcpp/commands/provision.hpp"
#include "lxcpp/commands/setup-userns.hpp"
#include "lxcpp/commands/cgroups.hpp"
#include "lxcpp/commands/netcreate.hpp"
#include "logger/logger.hpp"
#include "utils/signal.hpp"
#include <unistd.h>
#include <sys/wait.h>
namespace lxcpp {
int Guard::startContainer(void* data)
{
ContainerConfig& config = static_cast<ContainerData*>(data)->mConfig;
utils::Channel& channel = static_cast<ContainerData*>(data)->mChannel;
// wait for continue sync from guard
channel.setRight();
channel.read<bool>();
channel.shutdown();
// TODO: container preparation part 3: things to do in the container process
lxcpp::setHostName(config.mHostName);
Provisions provisions(config);
provisions.execute();
PrepGuestTerminal terminals(config.mTerminals);
terminals.execute();
if (!config.mUserNSConfig.mUIDMaps.empty()) {
lxcpp::setreuid(0, 0);
}
if (!config.mUserNSConfig.mGIDMaps.empty()) {
lxcpp::setregid(0, 0);
}
NetConfigureAll network(config.mNetwork);
network.execute();
if (!config.mRlimits.empty()) {
for (const auto& limit : config.mRlimits) {
lxcpp::setRlimit(std::get<0>(limit), std::get<1>(limit),std::get<2>(limit));
}
}
if (!config.mKernelParameters.empty()) {
for (const auto& sysctl : config.mKernelParameters) {
lxcpp::writeKernelParameter(sysctl.first, sysctl.second);
}
}
lxcpp::dropCapsFromBoundingExcept(config.mCapsToKeep);
lxcpp::clearenv();
lxcpp::setenv(config.mEnvToSet);
utils::CArgsBuilder args;
lxcpp::execv(args.add(config.mInit));
return EXIT_FAILURE;
}
Guard::Guard(const std::string& socketPath)
: mSignalFD(mEventPoll)
{
using namespace std::placeholders;
mSignalFD.setHandler(SIGCHLD, std::bind(&Guard::onInitExit, this, _1));
// Setup socket communication
mService.reset(new cargo::ipc::Service(mEventPoll, socketPath));
mService->setRemovedPeerCallback(std::bind(&Guard::onDisconnection, this, _1, _2));
mService->setNewPeerCallback(std::bind(&Guard::onConnection, this, _1, _2));
mService->setMethodHandler<api::Pid, api::Void>(api::METHOD_START,
std::bind(&Guard::onStart, this, _1, _2, _3));
mService->setMethodHandler<api::Void, api::Void>(api::METHOD_STOP,
std::bind(&Guard::onStop, this, _1, _2, _3));
mService->setMethodHandler<api::Void, ContainerConfig>(api::METHOD_SET_CONFIG,
std::bind(&Guard::onSetConfig, this, _1, _2, _3));
mService->setMethodHandler<ContainerConfig, api::Void>(api::METHOD_GET_CONFIG,
std::bind(&Guard::onGetConfig, this, _1, _2, _3));
mService->start();
}
Guard::~Guard()
{
}
void Guard::onConnection(const cargo::ipc::PeerID& peerID, const cargo::ipc::FileDescriptor)
{
LOGT("onConnection");
if (!mPeerID.empty()) {
// FIXME: Refuse connection
LOGW("New Peer connected, but previous not disconnected");
}
mPeerID = peerID;
if (!mConfig) {
// Host is connecting to a STOPPED container,
// it needs to s setup and start it
mService->callAsyncFromCallback<api::Void, api::Void>(api::METHOD_GUARD_READY, mPeerID, std::shared_ptr<api::Void>());
} else {
// Host is connecting to a RUNNING container
// Guard passes info about the started Init
mService->callAsyncFromCallback<ContainerConfig, api::Void>(api::METHOD_GUARD_CONNECTED, mPeerID, mConfig);
}
}
void Guard::onDisconnection(const cargo::ipc::PeerID& peerID, const cargo::ipc::FileDescriptor)
{
LOGT("onDisconnection");
if(mPeerID != peerID) {
LOGE("Unknown peerID: " << peerID);
}
mPeerID.clear();
}
void Guard::onInitExit(struct ::signalfd_siginfo& sigInfo)
{
LOGT("onInitExit");
if(mConfig->mInitPid != static_cast<int>(sigInfo.ssi_pid)) {
return;
}
LOGD("Init died");
mConfig->mState = Container::State::STOPPED;
auto data = std::make_shared<api::ExitStatus>(sigInfo.ssi_status);
mService->callAsync<api::ExitStatus, api::Void>(api::METHOD_INIT_STOPPED, mPeerID, data);
mService->stop(false);
}
cargo::ipc::HandlerExitCode Guard::onSetConfig(const cargo::ipc::PeerID,
std::shared_ptr<ContainerConfig>& data,
cargo::ipc::MethodResult::Pointer result)
{
LOGT("onSetConfig");
mConfig = data;
try {
logger::setupLogger(mConfig->mLogger.mType,
mConfig->mLogger.mLevel,
mConfig->mLogger.mArg);
LOGD("Config & logging restored");
}
catch(const std::exception& e) {
result->setError(api::GUARD_SET_CONFIG_ERROR, e.what());
return cargo::ipc::HandlerExitCode::SUCCESS;
}
result->setVoid();
return cargo::ipc::HandlerExitCode::SUCCESS;
}
cargo::ipc::HandlerExitCode Guard::onGetConfig(const cargo::ipc::PeerID,
std::shared_ptr<api::Void>&,
cargo::ipc::MethodResult::Pointer result)
{
LOGT("onGetConfig");
result->set(mConfig);
return cargo::ipc::HandlerExitCode::SUCCESS;
}
cargo::ipc::HandlerExitCode Guard::onStart(const cargo::ipc::PeerID,
std::shared_ptr<api::Void>&,
cargo::ipc::MethodResult::Pointer result)
{
LOGT("onStart");
mConfig->mState = Container::State::STARTING;
try {
LOGD("Setting the guard process title");
const std::string title = "[LXCPP] " + mConfig->mName + " " + mConfig->mRootPath;
setProcTitle(title);
} catch (std::exception &e) {
// Ignore, this is optional
LOGW("Failed to set the guard configuration: " << e.what());
}
// TODO: container preparation part 1: things to do before clone
CGroupMakeAll cgroups(mConfig->mCgroups);
cgroups.execute();
utils::Channel channel;
ContainerData data(*mConfig, channel);
mConfig->mInitPid = lxcpp::clone(startContainer,
&data,
mConfig->mNamespaces);
// TODO: container preparation part 2: things to do immediately after clone
NetCreateAll network(mConfig->mNetwork, mConfig->mInitPid);
network.execute();
SetupUserNS userNS(mConfig->mUserNSConfig, mConfig->mInitPid);
userNS.execute();
CGroupAssignPidAll cgroupAssignPid(mConfig->mCgroups, mConfig->mInitPid);
cgroupAssignPid.execute();
// send continue sync to container once userns, netns, cgroups, etc, are configured
channel.setLeft();
channel.write(true);
channel.shutdown();
// Init started, change state
mConfig->mState = Container::State::RUNNING;
// Configuration succeed, return the init's PID
auto ret = std::make_shared<api::Pid>(mConfig->mInitPid);
result->set(ret);
return cargo::ipc::HandlerExitCode::SUCCESS;
}
cargo::ipc::HandlerExitCode Guard::onStop(const cargo::ipc::PeerID,
std::shared_ptr<api::Void>&,
cargo::ipc::MethodResult::Pointer result)
{
LOGT("onStop");
LOGI("Stopping...");
mConfig->mState = Container::State::STOPPING;
// TODO: Use initctl/systemd-initctl if available in container
// TODO: Use SIGTERM instead of SIGKILL.
utils::sendSignal(mConfig->mInitPid, SIGKILL);
result->setVoid();
return cargo::ipc::HandlerExitCode::SUCCESS;
}
int Guard::execute()
{
// Polling loop
while (mService->isStarted()) {
mEventPoll.dispatchIteration(-1);
}
if (!mConfig) {
// Config wasn't set, nothing started, fail
return EXIT_FAILURE;
}
int status = lxcpp::waitpid(mConfig->mInitPid);
LOGD("Init exited with status: " << status);
// TODO: container (de)preparation part 4: cleanup after container quits
Provisions provisions(*mConfig);
provisions.revert();
return status;
}
} // namespace lxcpp
<commit_msg>lxcpp: Added a synchronization step in Guard<commit_after>/*
* Copyright (C) 2015 Samsung Electronics Co., Ltd All Rights Reserved
*
* 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
* @file
* @author Lukasz Pawelczyk ([email protected])
* @brief LXCPP guard process implementation
*/
#include "config.hpp"
#include "lxcpp/utils.hpp"
#include "lxcpp/guard/guard.hpp"
#include "lxcpp/process.hpp"
#include "lxcpp/credentials.hpp"
#include "lxcpp/hostname.hpp"
#include "lxcpp/rlimit.hpp"
#include "lxcpp/sysctl.hpp"
#include "lxcpp/capability.hpp"
#include "lxcpp/environment.hpp"
#include "lxcpp/commands/prep-guest-terminal.hpp"
#include "lxcpp/commands/provision.hpp"
#include "lxcpp/commands/setup-userns.hpp"
#include "lxcpp/commands/cgroups.hpp"
#include "lxcpp/commands/netcreate.hpp"
#include "logger/logger.hpp"
#include "utils/signal.hpp"
#include <unistd.h>
#include <sys/wait.h>
namespace lxcpp {
int Guard::startContainer(void* data)
{
ContainerConfig& config = static_cast<ContainerData*>(data)->mConfig;
utils::Channel& channel = static_cast<ContainerData*>(data)->mChannel;
// Brackets are here to call destructors before execv.
{
// Wait for continue sync from guard
channel.setRight();
channel.read<bool>();
// TODO: container preparation part 3: things to do in the container process
lxcpp::setHostName(config.mHostName);
Provisions provisions(config);
provisions.execute();
PrepGuestTerminal terminals(config.mTerminals);
terminals.execute();
if (!config.mUserNSConfig.mUIDMaps.empty()) {
lxcpp::setreuid(0, 0);
}
if (!config.mUserNSConfig.mGIDMaps.empty()) {
lxcpp::setregid(0, 0);
}
NetConfigureAll network(config.mNetwork);
network.execute();
if (!config.mRlimits.empty()) {
for (const auto& limit : config.mRlimits) {
lxcpp::setRlimit(std::get<0>(limit), std::get<1>(limit),std::get<2>(limit));
}
}
if (!config.mKernelParameters.empty()) {
for (const auto& sysctl : config.mKernelParameters) {
lxcpp::writeKernelParameter(sysctl.first, sysctl.second);
}
}
lxcpp::dropCapsFromBoundingExcept(config.mCapsToKeep);
lxcpp::clearenv();
lxcpp::setenv(config.mEnvToSet);
// Notify that Init's preparation is done
channel.write(true);
channel.shutdown();
}
// Execute Init
utils::CArgsBuilder args;
lxcpp::execv(args.add(config.mInit));
return EXIT_FAILURE;
}
Guard::Guard(const std::string& socketPath)
: mSignalFD(mEventPoll)
{
using namespace std::placeholders;
mSignalFD.setHandler(SIGCHLD, std::bind(&Guard::onInitExit, this, _1));
// Setup socket communication
mService.reset(new cargo::ipc::Service(mEventPoll, socketPath));
mService->setRemovedPeerCallback(std::bind(&Guard::onDisconnection, this, _1, _2));
mService->setNewPeerCallback(std::bind(&Guard::onConnection, this, _1, _2));
mService->setMethodHandler<api::Pid, api::Void>(api::METHOD_START,
std::bind(&Guard::onStart, this, _1, _2, _3));
mService->setMethodHandler<api::Void, api::Void>(api::METHOD_STOP,
std::bind(&Guard::onStop, this, _1, _2, _3));
mService->setMethodHandler<api::Void, ContainerConfig>(api::METHOD_SET_CONFIG,
std::bind(&Guard::onSetConfig, this, _1, _2, _3));
mService->setMethodHandler<ContainerConfig, api::Void>(api::METHOD_GET_CONFIG,
std::bind(&Guard::onGetConfig, this, _1, _2, _3));
mService->start();
}
Guard::~Guard()
{
}
void Guard::onConnection(const cargo::ipc::PeerID& peerID, const cargo::ipc::FileDescriptor)
{
LOGT("onConnection");
if (!mPeerID.empty()) {
// FIXME: Refuse connection
LOGW("New Peer connected, but previous not disconnected");
}
mPeerID = peerID;
if (!mConfig) {
// Host is connecting to a STOPPED container,
// it needs to s setup and start it
mService->callAsyncFromCallback<api::Void, api::Void>(api::METHOD_GUARD_READY, mPeerID, std::shared_ptr<api::Void>());
} else {
// Host is connecting to a RUNNING container
// Guard passes info about the started Init
mService->callAsyncFromCallback<ContainerConfig, api::Void>(api::METHOD_GUARD_CONNECTED, mPeerID, mConfig);
}
}
void Guard::onDisconnection(const cargo::ipc::PeerID& peerID, const cargo::ipc::FileDescriptor)
{
LOGT("onDisconnection");
if(mPeerID != peerID) {
LOGE("Unknown peerID: " << peerID);
}
mPeerID.clear();
}
void Guard::onInitExit(struct ::signalfd_siginfo& sigInfo)
{
LOGT("onInitExit");
if(mConfig->mInitPid != static_cast<int>(sigInfo.ssi_pid)) {
return;
}
LOGD("Init died");
mConfig->mState = Container::State::STOPPED;
auto data = std::make_shared<api::ExitStatus>(sigInfo.ssi_status);
mService->callAsync<api::ExitStatus, api::Void>(api::METHOD_INIT_STOPPED, mPeerID, data);
mService->stop(false);
}
cargo::ipc::HandlerExitCode Guard::onSetConfig(const cargo::ipc::PeerID,
std::shared_ptr<ContainerConfig>& data,
cargo::ipc::MethodResult::Pointer result)
{
LOGT("onSetConfig");
mConfig = data;
try {
logger::setupLogger(mConfig->mLogger.mType,
mConfig->mLogger.mLevel,
mConfig->mLogger.mArg);
LOGD("Config & logging restored");
}
catch(const std::exception& e) {
result->setError(api::GUARD_SET_CONFIG_ERROR, e.what());
return cargo::ipc::HandlerExitCode::SUCCESS;
}
result->setVoid();
return cargo::ipc::HandlerExitCode::SUCCESS;
}
cargo::ipc::HandlerExitCode Guard::onGetConfig(const cargo::ipc::PeerID,
std::shared_ptr<api::Void>&,
cargo::ipc::MethodResult::Pointer result)
{
LOGT("onGetConfig");
result->set(mConfig);
return cargo::ipc::HandlerExitCode::SUCCESS;
}
cargo::ipc::HandlerExitCode Guard::onStart(const cargo::ipc::PeerID,
std::shared_ptr<api::Void>&,
cargo::ipc::MethodResult::Pointer result)
{
LOGT("onStart");
mConfig->mState = Container::State::STARTING;
try {
LOGD("Setting the guard process title");
const std::string title = "[LXCPP] " + mConfig->mName + " " + mConfig->mRootPath;
setProcTitle(title);
} catch (std::exception &e) {
// Ignore, this is optional
LOGW("Failed to set the guard configuration: " << e.what());
}
// TODO: container preparation part 1: things to do before clone
CGroupMakeAll cgroups(mConfig->mCgroups);
cgroups.execute();
utils::Channel channel;
ContainerData data(*mConfig, channel);
mConfig->mInitPid = lxcpp::clone(startContainer,
&data,
mConfig->mNamespaces);
// TODO: container preparation part 2: things to do immediately after clone
NetCreateAll network(mConfig->mNetwork, mConfig->mInitPid);
network.execute();
SetupUserNS userNS(mConfig->mUserNSConfig, mConfig->mInitPid);
userNS.execute();
CGroupAssignPidAll cgroupAssignPid(mConfig->mCgroups, mConfig->mInitPid);
cgroupAssignPid.execute();
// send continue sync to container once userns, netns, cgroups, etc, are configured
channel.setLeft();
channel.write(true);
// Wait till Init is executed
channel.read<bool>();
channel.shutdown();
// Init started, change state
mConfig->mState = Container::State::RUNNING;
// Configuration succeed, return the init's PID
auto ret = std::make_shared<api::Pid>(mConfig->mInitPid);
result->set(ret);
return cargo::ipc::HandlerExitCode::SUCCESS;
}
cargo::ipc::HandlerExitCode Guard::onStop(const cargo::ipc::PeerID,
std::shared_ptr<api::Void>&,
cargo::ipc::MethodResult::Pointer result)
{
LOGT("onStop");
LOGI("Stopping...");
mConfig->mState = Container::State::STOPPING;
// TODO: Use initctl/systemd-initctl if available in container
// TODO: Use SIGTERM instead of SIGKILL.
utils::sendSignal(mConfig->mInitPid, SIGKILL);
result->setVoid();
return cargo::ipc::HandlerExitCode::SUCCESS;
}
int Guard::execute()
{
// Polling loop
while (mService->isStarted()) {
mEventPoll.dispatchIteration(-1);
}
if (!mConfig) {
// Config wasn't set, nothing started, fail
return EXIT_FAILURE;
}
int status = lxcpp::waitpid(mConfig->mInitPid);
LOGD("Init exited with status: " << status);
// TODO: container (de)preparation part 4: cleanup after container quits
Provisions provisions(*mConfig);
provisions.revert();
return status;
}
} // namespace lxcpp
<|endoftext|> |
<commit_before>/**
* @file TypeTable.hpp
* @brief TypeTable class prototype.
* @author zer0
* @date 2017-12-17
*/
#ifndef __INCLUDE_LIBTBAG__LIBTBAG_TYPE_TYPETABLE_HPP__
#define __INCLUDE_LIBTBAG__LIBTBAG_TYPE_TYPETABLE_HPP__
// MS compatible compilers support #pragma once
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
#pragma once
#endif
#include <libtbag/config.h>
#include <libtbag/predef.hpp>
#include <cstdint>
#include <limits>
#include <type_traits>
// -------------------
NAMESPACE_LIBTBAG_OPEN
// -------------------
namespace type {
// It's by design, C++ standard says 'char', 'signed char' and 'unsigned char' are different types.
// see also: http://cpp14.centaur.ath.cx/basic.fundamental.html
#ifndef TBAG_TYPE_TABLE_MAP
#define TBAG_TYPE_TABLE_MAP(_TBAG_XX) \
_TBAG_XX( BOOL, b, bool) \
_TBAG_XX( CHAR, c, char) \
_TBAG_XX( SCHAR, sc, signed char) \
_TBAG_XX( UCHAR, uc, unsigned char) \
_TBAG_XX( WCHAR, wc, wchar_t) \
_TBAG_XX( CHAR16, c16, char16_t) \
_TBAG_XX( CHAR32, c32, char32_t) \
_TBAG_XX( SHORT, s, signed short int) \
_TBAG_XX( USHORT, us, unsigned short int) \
_TBAG_XX( INT, i, signed int) \
_TBAG_XX( UINT, ui, unsigned int) \
_TBAG_XX( LONG, l, signed long int) \
_TBAG_XX( ULONG, ul, unsigned long int) \
_TBAG_XX( LLONG, ll, signed long long int) \
_TBAG_XX( ULLONG, ull, unsigned long long int) \
_TBAG_XX( FLOAT, f, float) \
_TBAG_XX( DOUBLE, d, double) \
_TBAG_XX(LDOUBLE, ld, long double) \
/* -- END -- */
#endif
/**
* TypeTable class prototype.
*
* @author zer0
* @date 2017-12-17
*/
enum class TypeTable : int
{
TT_UNKNOWN = 0,
#define _TBAG_XX(name, symbol, type) TT_##name,
TBAG_TYPE_TABLE_MAP(_TBAG_XX)
#undef _TBAG_XX
};
#if defined(TBAG_COMP_MSVC)
# if defined(min)
TBAG_PUSH_MACRO(min);
# undef min
# define __RESTORE_MIN__
# endif // defined(min)
# if defined(max)
TBAG_PUSH_MACRO(max);
# undef max
# define __RESTORE_MAX__
# endif // defined(max)
#endif // defined(TBAG_COMP_MSVC)
template <typename T> struct TypeInfo;
template <typename T>
struct BaseTypeInfo : public std::false_type
{
TBAG_CONSTEXPR static char const * name() TBAG_NOEXCEPT { return "UNKNOWN"; }
TBAG_CONSTEXPR static TypeTable table() TBAG_NOEXCEPT { return TypeTable::TT_UNKNOWN; }
};
#define _TBAG_XX(n, s, t) \
template <> struct BaseTypeInfo<t> : public std::true_type { \
TBAG_CONSTEXPR static char const * name() TBAG_NOEXCEPT { return #n; } \
TBAG_CONSTEXPR static TypeTable table() TBAG_NOEXCEPT { return TypeTable::TT_##n; } \
};
TBAG_TYPE_TABLE_MAP(_TBAG_XX)
#undef _TBAG_XX
#ifndef _STATIC_ASSERT_CHECK_PRIMARY_TYPE
#define _STATIC_ASSERT_CHECK_PRIMARY_TYPE(type_name) \
static_assert(BaseTypeInfo<type_name>::value, "The " #type_name " type is not a primary type.")
#endif
_STATIC_ASSERT_CHECK_PRIMARY_TYPE( int8_t);
_STATIC_ASSERT_CHECK_PRIMARY_TYPE( uint8_t);
_STATIC_ASSERT_CHECK_PRIMARY_TYPE( int16_t);
_STATIC_ASSERT_CHECK_PRIMARY_TYPE(uint16_t);
_STATIC_ASSERT_CHECK_PRIMARY_TYPE( int32_t);
_STATIC_ASSERT_CHECK_PRIMARY_TYPE(uint32_t);
_STATIC_ASSERT_CHECK_PRIMARY_TYPE( int64_t);
_STATIC_ASSERT_CHECK_PRIMARY_TYPE(uint64_t);
template <typename T>
struct TypeInfo : public BaseTypeInfo<typename std::remove_cv<T>::type>
{
using Base = BaseTypeInfo<typename std::remove_cv<T>::type>;
using Type = typename std::remove_cv<T>::type;
TBAG_CONSTEXPR static bool const is_arithmetic = std::is_arithmetic<Type>::value;
using Number = typename std::conditional<is_arithmetic, Type, int>::type;
TBAG_CONSTEXPR static bool const is_pointer = std::is_pointer<Type>::value;
TBAG_CONSTEXPR static bool const is_reference = std::is_reference<Type>::value;
TBAG_CONSTEXPR static bool const is_floating_point = std::is_floating_point<Type>::value;
TBAG_CONSTEXPR static bool const is_integral = std::is_integral<Type>::value;
TBAG_CONSTEXPR static bool const is_unsigned = std::is_unsigned<Type>::value;
TBAG_CONSTEXPR static bool const is_signed = std::is_signed<Type>::value;
TBAG_CONSTEXPR static int size() TBAG_NOEXCEPT { return sizeof(Type); }
TBAG_CONSTEXPR static bool isArithmetic() TBAG_NOEXCEPT { return is_arithmetic; }
TBAG_CONSTEXPR static bool isSpecialized() TBAG_NOEXCEPT { return Base::value; }
TBAG_CONSTEXPR static bool isPointer() TBAG_NOEXCEPT { return is_pointer; }
TBAG_CONSTEXPR static bool isReference() TBAG_NOEXCEPT { return is_reference; }
TBAG_CONSTEXPR static bool isFloating() TBAG_NOEXCEPT { return is_floating_point; }
TBAG_CONSTEXPR static bool isIntegral() TBAG_NOEXCEPT { return is_integral; }
TBAG_CONSTEXPR static bool isUnsigned() TBAG_NOEXCEPT { return is_unsigned; }
TBAG_CONSTEXPR static bool isSigned() TBAG_NOEXCEPT { return is_signed; }
using Limits = std::numeric_limits<Number>;
/** returns the largest finite value of the given type */
TBAG_CONSTEXPR static Number maximum() TBAG_NOEXCEPT { return Limits::max(); }
/** returns the smallest finite value of the given type */
TBAG_CONSTEXPR static Number minimum() TBAG_NOEXCEPT { return Limits::min(); }
/** returns the lowest finite value of the given type */
TBAG_CONSTEXPR static Number lowest() TBAG_NOEXCEPT { return Limits::lowest(); }
/** returns the difference between 1.0 and the next representable value of the given floating-point type */
TBAG_CONSTEXPR static Number epsilon() TBAG_NOEXCEPT { return Limits::epsilon(); }
/** returns the maximum rounding error of the given floating-point type */
TBAG_CONSTEXPR static Number round_error() TBAG_NOEXCEPT { return Limits::round_error(); }
/** returns the positive infinity value of the given floating-point type */
TBAG_CONSTEXPR static Number infinity() TBAG_NOEXCEPT { return Limits::infinity(); }
/** returns a quiet NaN value of the given floating-point type */
TBAG_CONSTEXPR static Number quiet_NaN() TBAG_NOEXCEPT { return Limits::quiet_NaN(); }
/** returns a signaling NaN value of the given floating-point type */
TBAG_CONSTEXPR static Number signaling_NaN() TBAG_NOEXCEPT { return Limits::signaling_NaN(); }
/** returns the smallest positive subnormal value of the given floating-point type */
TBAG_CONSTEXPR static Number denorm_min() TBAG_NOEXCEPT { return Limits::denorm_min(); }
TBAG_CONSTEXPR static int index() TBAG_NOEXCEPT { return static_cast<int>(Base::table()); }
};
#if defined(TBAG_COMP_MSVC)
# if defined(__RESTORE_MIN__)
TBAG_POP_MACRO(min);
# undef __RESTORE_MIN__
# endif // defined(__RESTORE_MIN__)
# if defined(__RESTORE_MAX__)
TBAG_POP_MACRO(max);
# undef __RESTORE_MAX__
# endif // defined(__RESTORE_MAX__)
#endif // defined(TBAG_COMP_MSVC)
template <typename T>
inline TypeTable getTypeTable() TBAG_NOEXCEPT
{
return TypeInfo<T>::table();
}
inline char const * getTypeName(TypeTable t) TBAG_NOEXCEPT
{
switch (t) {
#define _TBAG_XX(name, symbol, type) case TypeTable::TT_##name: return #name;
TBAG_TYPE_TABLE_MAP(_TBAG_XX)
#undef _TBAG_XX
case TypeTable::TT_UNKNOWN:
default: return "UNKNOWN";
}
}
inline std::size_t getTypeSize(TypeTable t) TBAG_NOEXCEPT
{
switch (t) {
#define _TBAG_XX(name, symbol, type) case TypeTable::TT_##name: return sizeof(type);
TBAG_TYPE_TABLE_MAP(_TBAG_XX)
#undef _TBAG_XX
case TypeTable::TT_UNKNOWN:
default: return 0;
}
}
} // namespace type
// --------------------
NAMESPACE_LIBTBAG_CLOSE
// --------------------
#endif // __INCLUDE_LIBTBAG__LIBTBAG_TYPE_TYPETABLE_HPP__
<commit_msg>Create TypeTable for cstdint package.<commit_after>/**
* @file TypeTable.hpp
* @brief TypeTable class prototype.
* @author zer0
* @date 2017-12-17
*/
#ifndef __INCLUDE_LIBTBAG__LIBTBAG_TYPE_TYPETABLE_HPP__
#define __INCLUDE_LIBTBAG__LIBTBAG_TYPE_TYPETABLE_HPP__
// MS compatible compilers support #pragma once
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
#pragma once
#endif
#include <libtbag/config.h>
#include <libtbag/predef.hpp>
#include <cstdint>
#include <limits>
#include <type_traits>
// -------------------
NAMESPACE_LIBTBAG_OPEN
// -------------------
namespace type {
// It's by design, C++ standard says 'char', 'signed char' and 'unsigned char' are different types.
// see also: http://cpp14.centaur.ath.cx/basic.fundamental.html
#ifndef TBAG_TYPE_TABLE_MAP
#define TBAG_TYPE_TABLE_MAP(_TBAG_XX) \
_TBAG_XX( BOOL, b, bool) \
_TBAG_XX( CHAR, c, char) \
_TBAG_XX( SCHAR, sc, signed char) \
_TBAG_XX( UCHAR, uc, unsigned char) \
_TBAG_XX( WCHAR, wc, wchar_t) \
_TBAG_XX( CHAR16, c16, char16_t) \
_TBAG_XX( CHAR32, c32, char32_t) \
_TBAG_XX( SHORT, s, signed short int) \
_TBAG_XX( USHORT, us, unsigned short int) \
_TBAG_XX( INT, i, signed int) \
_TBAG_XX( UINT, ui, unsigned int) \
_TBAG_XX( LONG, l, signed long int) \
_TBAG_XX( ULONG, ul, unsigned long int) \
_TBAG_XX( LLONG, ll, signed long long int) \
_TBAG_XX( ULLONG, ull, unsigned long long int) \
_TBAG_XX( FLOAT, f, float) \
_TBAG_XX( DOUBLE, d, double) \
_TBAG_XX(LDOUBLE, ld, long double) \
/* -- END -- */
#endif
/**
* TypeTable class prototype.
*
* @author zer0
* @date 2017-12-17
*/
enum class TypeTable : int
{
TT_UNKNOWN = 0,
#define _TBAG_XX(name, symbol, type) TT_##name,
TBAG_TYPE_TABLE_MAP(_TBAG_XX)
#undef _TBAG_XX
};
#if defined(TBAG_COMP_MSVC)
# if defined(min)
TBAG_PUSH_MACRO(min);
# undef min
# define __RESTORE_MIN__
# endif // defined(min)
# if defined(max)
TBAG_PUSH_MACRO(max);
# undef max
# define __RESTORE_MAX__
# endif // defined(max)
#endif // defined(TBAG_COMP_MSVC)
template <typename T> struct TypeInfo;
template <typename T>
struct BaseTypeInfo : public std::false_type
{
TBAG_CONSTEXPR static char const * name() TBAG_NOEXCEPT { return "UNKNOWN"; }
TBAG_CONSTEXPR static TypeTable table() TBAG_NOEXCEPT { return TypeTable::TT_UNKNOWN; }
};
#define _TBAG_XX(n, s, t) \
template <> struct BaseTypeInfo<t> : public std::true_type { \
TBAG_CONSTEXPR static char const * name() TBAG_NOEXCEPT { return #n; } \
TBAG_CONSTEXPR static TypeTable table() TBAG_NOEXCEPT { return TypeTable::TT_##n; } \
};
TBAG_TYPE_TABLE_MAP(_TBAG_XX)
#undef _TBAG_XX
template <typename T>
struct TypeInfo : public BaseTypeInfo<typename std::remove_cv<T>::type>
{
using Base = BaseTypeInfo<typename std::remove_cv<T>::type>;
using Type = typename std::remove_cv<T>::type;
TBAG_CONSTEXPR static bool const is_arithmetic = std::is_arithmetic<Type>::value;
using Number = typename std::conditional<is_arithmetic, Type, int>::type;
TBAG_CONSTEXPR static bool const is_pointer = std::is_pointer<Type>::value;
TBAG_CONSTEXPR static bool const is_reference = std::is_reference<Type>::value;
TBAG_CONSTEXPR static bool const is_floating_point = std::is_floating_point<Type>::value;
TBAG_CONSTEXPR static bool const is_integral = std::is_integral<Type>::value;
TBAG_CONSTEXPR static bool const is_unsigned = std::is_unsigned<Type>::value;
TBAG_CONSTEXPR static bool const is_signed = std::is_signed<Type>::value;
TBAG_CONSTEXPR static int size() TBAG_NOEXCEPT { return sizeof(Type); }
TBAG_CONSTEXPR static bool isArithmetic() TBAG_NOEXCEPT { return is_arithmetic; }
TBAG_CONSTEXPR static bool isSpecialized() TBAG_NOEXCEPT { return Base::value; }
TBAG_CONSTEXPR static bool isPointer() TBAG_NOEXCEPT { return is_pointer; }
TBAG_CONSTEXPR static bool isReference() TBAG_NOEXCEPT { return is_reference; }
TBAG_CONSTEXPR static bool isFloating() TBAG_NOEXCEPT { return is_floating_point; }
TBAG_CONSTEXPR static bool isIntegral() TBAG_NOEXCEPT { return is_integral; }
TBAG_CONSTEXPR static bool isUnsigned() TBAG_NOEXCEPT { return is_unsigned; }
TBAG_CONSTEXPR static bool isSigned() TBAG_NOEXCEPT { return is_signed; }
using Limits = std::numeric_limits<Number>;
/** returns the largest finite value of the given type */
TBAG_CONSTEXPR static Number maximum() TBAG_NOEXCEPT { return Limits::max(); }
/** returns the smallest finite value of the given type */
TBAG_CONSTEXPR static Number minimum() TBAG_NOEXCEPT { return Limits::min(); }
/** returns the lowest finite value of the given type */
TBAG_CONSTEXPR static Number lowest() TBAG_NOEXCEPT { return Limits::lowest(); }
/** returns the difference between 1.0 and the next representable value of the given floating-point type */
TBAG_CONSTEXPR static Number epsilon() TBAG_NOEXCEPT { return Limits::epsilon(); }
/** returns the maximum rounding error of the given floating-point type */
TBAG_CONSTEXPR static Number round_error() TBAG_NOEXCEPT { return Limits::round_error(); }
/** returns the positive infinity value of the given floating-point type */
TBAG_CONSTEXPR static Number infinity() TBAG_NOEXCEPT { return Limits::infinity(); }
/** returns a quiet NaN value of the given floating-point type */
TBAG_CONSTEXPR static Number quiet_NaN() TBAG_NOEXCEPT { return Limits::quiet_NaN(); }
/** returns a signaling NaN value of the given floating-point type */
TBAG_CONSTEXPR static Number signaling_NaN() TBAG_NOEXCEPT { return Limits::signaling_NaN(); }
/** returns the smallest positive subnormal value of the given floating-point type */
TBAG_CONSTEXPR static Number denorm_min() TBAG_NOEXCEPT { return Limits::denorm_min(); }
TBAG_CONSTEXPR static int index() TBAG_NOEXCEPT { return static_cast<int>(Base::table()); }
};
#if defined(TBAG_COMP_MSVC)
# if defined(__RESTORE_MIN__)
TBAG_POP_MACRO(min);
# undef __RESTORE_MIN__
# endif // defined(__RESTORE_MIN__)
# if defined(__RESTORE_MAX__)
TBAG_POP_MACRO(max);
# undef __RESTORE_MAX__
# endif // defined(__RESTORE_MAX__)
#endif // defined(TBAG_COMP_MSVC)
template <typename T>
TBAG_CONSTEXPR inline TypeTable getTypeTable() TBAG_NOEXCEPT
{
return TypeInfo<T>::table();
}
#ifndef _STATIC_ASSERT_CHECK_PRIMARY_TYPE
#define _STATIC_ASSERT_CHECK_PRIMARY_TYPE(type_name) \
static_assert(BaseTypeInfo<type_name>::value, "The " #type_name " type is not a primary type.")
#endif
_STATIC_ASSERT_CHECK_PRIMARY_TYPE( int8_t);
_STATIC_ASSERT_CHECK_PRIMARY_TYPE( uint8_t);
_STATIC_ASSERT_CHECK_PRIMARY_TYPE( int16_t);
_STATIC_ASSERT_CHECK_PRIMARY_TYPE(uint16_t);
_STATIC_ASSERT_CHECK_PRIMARY_TYPE( int32_t);
_STATIC_ASSERT_CHECK_PRIMARY_TYPE(uint32_t);
_STATIC_ASSERT_CHECK_PRIMARY_TYPE( int64_t);
_STATIC_ASSERT_CHECK_PRIMARY_TYPE(uint64_t);
TBAG_CONSTEXPR TypeTable const TT_INT8 = getTypeTable< int8_t>();
TBAG_CONSTEXPR TypeTable const TT_UINT8 = getTypeTable< uint8_t>();
TBAG_CONSTEXPR TypeTable const TT_INT16 = getTypeTable< int16_t>();
TBAG_CONSTEXPR TypeTable const TT_UINT16 = getTypeTable<uint16_t>();
TBAG_CONSTEXPR TypeTable const TT_INT32 = getTypeTable< int32_t>();
TBAG_CONSTEXPR TypeTable const TT_UINT32 = getTypeTable<uint32_t>();
TBAG_CONSTEXPR TypeTable const TT_INT64 = getTypeTable< int64_t>();
TBAG_CONSTEXPR TypeTable const TT_UINT64 = getTypeTable<uint64_t>();
inline char const * getTypeName(TypeTable t) TBAG_NOEXCEPT
{
switch (t) {
#define _TBAG_XX(name, symbol, type) case TypeTable::TT_##name: return #name;
TBAG_TYPE_TABLE_MAP(_TBAG_XX)
#undef _TBAG_XX
case TypeTable::TT_UNKNOWN:
default: return "UNKNOWN";
}
}
inline std::size_t getTypeSize(TypeTable t) TBAG_NOEXCEPT
{
switch (t) {
#define _TBAG_XX(name, symbol, type) case TypeTable::TT_##name: return sizeof(type);
TBAG_TYPE_TABLE_MAP(_TBAG_XX)
#undef _TBAG_XX
case TypeTable::TT_UNKNOWN:
default: return 0;
}
}
} // namespace type
// --------------------
NAMESPACE_LIBTBAG_CLOSE
// --------------------
#endif // __INCLUDE_LIBTBAG__LIBTBAG_TYPE_TYPETABLE_HPP__
<|endoftext|> |
<commit_before>// Copyright 2008, Google Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// 3. Neither the name of Google Inc. nor the names of its contributors may be
// used to endorse or promote products derived from this software without
// specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// This file contains the unit tests for the location utility functions.
#include "kml/engine/location_util.h"
#include "kml/base/file.h"
#include "kml/dom.h"
#include "kml/engine/bbox.h"
#include "kml/engine/kml_file.h"
#include "gtest/gtest.h"
using kmlbase::File;
using kmldom::CoordinatesPtr;
using kmldom::KmlFactory;
using kmldom::LatLonBoxPtr;
using kmldom::LatLonAltBoxPtr;
using kmldom::LocationPtr;
using kmldom::ModelPtr;
using kmldom::PhotoOverlayPtr;
using kmldom::PlacemarkPtr;
using kmldom::PointPtr;
#ifndef DATADIR
#error *** DATADIR must be defined! ***
#endif
namespace kmlengine {
// Avoid linking in kmlconvenience...
static PointPtr CreatePointCoordinates(double lat, double lon) {
KmlFactory* kml_factory = KmlFactory::GetFactory();
PointPtr point = kml_factory->CreatePoint();
CoordinatesPtr coordinates = KmlFactory::GetFactory()->CreateCoordinates();
coordinates->add_latlng(lat, lon);
point->set_coordinates(coordinates);
return point;
}
// This tests the GetCenter() function.
TEST(LocationUtilTest, TestGetCenter) {
KmlFactory* factory = KmlFactory::GetFactory();
// NULL output pointer(s) should not crash.
LatLonBoxPtr llb = factory->CreateLatLonBox();
GetCenter(llb, NULL, NULL);
double lat, lon;
GetCenter(llb, &lat, NULL);
// Missing lon pointer still saves a result for lat.
ASSERT_EQ(0.0, lat);
GetCenter(llb, NULL, &lon);
// Missing lat pointer still saves a result for lon.
ASSERT_EQ(0.0, lat);
// A default LatLonBox is well defined thus so is its center.
GetCenter(llb, &lat, &lon);
ASSERT_EQ(0.0, lat);
ASSERT_EQ(0.0, lon);
// A default LatLonAltBox is well defined thus so is its center.
LatLonAltBoxPtr llab = factory->CreateLatLonAltBox();
GetCenter(llab, &lat, &lon);
ASSERT_EQ(0.0, lat);
ASSERT_EQ(0.0, lon);
}
TEST(LocationUtilTest, TestGetFeatureLatLon) {
KmlFactory* factory = KmlFactory::GetFactory();
const double kLat(-22.22);
const double kLon(42.123);
PlacemarkPtr placemark = factory->CreatePlacemark();
placemark->set_geometry(CreatePointCoordinates(kLat, kLon));
double lat, lon;
ASSERT_TRUE(GetFeatureLatLon(placemark, &lat, &lon));
ASSERT_EQ(kLat, lat);
ASSERT_EQ(kLon, lon);
}
TEST(LocationUtilTest, TestGetModelLatLon) {
KmlFactory* factory = KmlFactory::GetFactory();
const double kLat(-22.22);
const double kLon(42.123);
ModelPtr model = factory->CreateModel();
LocationPtr location = factory->CreateLocation();
location->set_latitude(kLat);
location->set_longitude(kLon);
model->set_location(location);
double lat, lon;
ASSERT_TRUE(GetModelLatLon(model, &lat, &lon));
ASSERT_EQ(kLat, lat);
ASSERT_EQ(kLon, lon);
}
TEST(LocationUtilTest, TestGetPlacemarkLatLon) {
KmlFactory* factory = KmlFactory::GetFactory();
const double kLat(-22.22);
const double kLon(42.123);
PlacemarkPtr placemark = factory->CreatePlacemark();
placemark->set_geometry(CreatePointCoordinates(kLat, kLon));
double lat, lon;
ASSERT_TRUE(GetPlacemarkLatLon(placemark, &lat, &lon));
ASSERT_EQ(kLat, lat);
ASSERT_EQ(kLon, lon);
}
TEST(LocationUtilTest, TestGetPointLatLon) {
const double kLat(-22.22);
const double kLon(42.123);
double lat, lon;
ASSERT_TRUE(GetPointLatLon(CreatePointCoordinates(kLat, kLon), &lat, &lon));
ASSERT_EQ(kLat, lat);
ASSERT_EQ(kLon, lon);
}
// This internal utility function parses the testcase file to a KmlFile.
static KmlFilePtr ParseFromDataDirFile(const std::string& filename) {
std::string kml_data;
const std::string kml_file =
File::JoinPaths(File::JoinPaths(std::string(DATADIR), "kml"), filename);
return File::ReadFileToString(kml_file, &kml_data) ?
KmlFile::CreateFromParse(kml_data, NULL) : NULL;
}
// This is a table of test cases.
static const struct {
const char* kml_filename; // Path relative to testdata/kml.
const char* feature_id; // id= of Feature within file.
bool has_bounds; // Expected return value of GetFeatureBounds.
double north; // Expected values of Bbox fields iff has_bounds == true.
double south;
double east;
double west;
bool has_loc; // Expected return value of GetFeatureLatLon.
double lat; // Expected values of GetFeatureLatLon iff has_loc == true.
double lon;
} kTestCases[] = {
{ // A 2d Placemark.
"kmlsamples.kml", "simple-placemark",
true, 37.4222899014025, 37.4222899014025, -122.082203542568,
-122.082203542568,
true, 37.4222899014025, -122.082203542568 },
{ // A 3d Placemark.
"kmlsamples.kml", "floating-placemark",
true, 37.4220033612141, 37.4220033612141, -122.084075, -122.084075,
true, 37.4220033612141, -122.084075 },
{ // A Placemark with no Geometry.
"kmlsamples.kml", "descriptive-html-placemark",
false, 0, 0, 0, 0,
false, 0, 0 },
{ // A 2d LineString Placemark.
"kmlsamples.kml", "tessellated-linestring-placemark",
true, 36.1067787047714, 36.0905099328766, -112.081423783034,
-112.087026775269,
true, 36.098644318824, -112.0842252791515 },
{ // A 3d LineString Placemark (altitudeMode=absolute, and alt != 0).
"kmlsamples.kml", "purple-line-placemark", true, 36.0944767260255,
36.086463123013, -112.265654928602, -112.269526855561,
true, 36.09046992451925, -112.2675908920815 },
#if 0 // TODO
{ // A Polygon with only an outerBoundaryIs.
"kmlsamples.kml", "b41", true, 37.4228181532365, 37.4220817196725,
-122.08509907149, -122.086016227378,
true, 37.4224499364545, -122.085557649434 },
#endif
{ // A Polygon with holes.
"kmlsamples.kml", "pentagon", true, 38.872910162817, 38.868757801256,
-77.0531553685479, -77.0584405629039,
true, 38.8708339820365, -77.0557979657259 },
{ // A Folder with multiple Features, but none with any location info.
"kmlsamples.kml", "screen-overlays-folder",
false, 0, 0, 0, 0,
false, 0, 0 },
{ // Model
"model-macky.kml", "model-macky",
true, 40.009993372683, 40.009993372683, -105.272774533734,
-105.272774533734,
true, 40.009993372683, -105.272774533734
},
{ // PhotoOverlay
"photooverlay-zermatt.kml", "photooverlay-zermatt",
true, 45.968226693, 45.968226693, 7.71792711000002, 7.71792711000002,
true, 45.968226693, 7.71792711000002
},
#if 0 // TODO
{ // GroundOverlay
},
{ // A Folder with multiple Point Placemarks.
},
{ // A Folder with multiple LineString Placemarks.
},
{ // A Folder with multiple Polygon Placemarks.
},
{ // A Document with multiple Folders each with multiple Features.
}
#endif
};
TEST(LocationUtilTest, RunTestCases) {
size_t size = sizeof(kTestCases)/sizeof(kTestCases[0]);
for (size_t i = 0; i < size; ++i) {
KmlFilePtr kml_file =
ParseFromDataDirFile(kTestCases[i].kml_filename);
// Assert basic sanity of KmlFile.
ASSERT_TRUE(kml_file) << kTestCases[i].kml_filename;
ASSERT_TRUE(kml_file->get_root());
kmldom::FeaturePtr feature = kmldom::AsFeature(
kml_file->GetObjectById(kTestCases[i].feature_id));
// Asserts both that this id is found and is a Feature.
ASSERT_TRUE(feature);
Bbox bbox;
ASSERT_EQ(kTestCases[i].has_bounds, GetFeatureBounds(feature, &bbox))
<< kTestCases[i].kml_filename << " " << kTestCases[i].feature_id;
// GetFeatureBounds returns the same no matter the state of the bbox arg.
ASSERT_EQ(kTestCases[i].has_bounds, GetFeatureBounds(feature, NULL));
if (kTestCases[i].has_bounds) {
// If has_bounds then the test case n,s,e,w are valid to test.
ASSERT_EQ(kTestCases[i].north, bbox.get_north());
ASSERT_EQ(kTestCases[i].south, bbox.get_south());
ASSERT_EQ(kTestCases[i].east, bbox.get_east());
ASSERT_EQ(kTestCases[i].west, bbox.get_west());
}
double lat, lon;
ASSERT_EQ(kTestCases[i].has_loc, GetFeatureLatLon(feature, &lat, &lon));
// GetFeatureBounds returns same no matter the state of the lat/lon args.
ASSERT_EQ(kTestCases[i].has_loc, GetFeatureLatLon(feature, &lat, NULL));
ASSERT_EQ(kTestCases[i].has_loc, GetFeatureLatLon(feature, NULL, &lon));
ASSERT_EQ(kTestCases[i].has_loc, GetFeatureLatLon(feature, NULL, NULL));
if (kTestCases[i].has_loc) {
// If has_loc then the test case lat,lon are valid to test.
ASSERT_EQ(kTestCases[i].lat, lat);
ASSERT_EQ(kTestCases[i].lon, lon);
}
}
}
} // end namespace kmlengine
int main(int argc, char** argv) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
<commit_msg>permit subdirs<commit_after>// Copyright 2008, Google Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// 3. Neither the name of Google Inc. nor the names of its contributors may be
// used to endorse or promote products derived from this software without
// specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// This file contains the unit tests for the location utility functions.
#include "kml/engine/location_util.h"
#include "kml/base/file.h"
#include "kml/dom.h"
#include "kml/engine/bbox.h"
#include "kml/engine/kml_file.h"
#include "gtest/gtest.h"
using kmlbase::File;
using kmldom::CoordinatesPtr;
using kmldom::KmlFactory;
using kmldom::LatLonBoxPtr;
using kmldom::LatLonAltBoxPtr;
using kmldom::LocationPtr;
using kmldom::ModelPtr;
using kmldom::PhotoOverlayPtr;
using kmldom::PlacemarkPtr;
using kmldom::PointPtr;
#ifndef DATADIR
#error *** DATADIR must be defined! ***
#endif
namespace kmlengine {
// Avoid linking in kmlconvenience...
static PointPtr CreatePointCoordinates(double lat, double lon) {
KmlFactory* kml_factory = KmlFactory::GetFactory();
PointPtr point = kml_factory->CreatePoint();
CoordinatesPtr coordinates = KmlFactory::GetFactory()->CreateCoordinates();
coordinates->add_latlng(lat, lon);
point->set_coordinates(coordinates);
return point;
}
// This tests the GetCenter() function.
TEST(LocationUtilTest, TestGetCenter) {
KmlFactory* factory = KmlFactory::GetFactory();
// NULL output pointer(s) should not crash.
LatLonBoxPtr llb = factory->CreateLatLonBox();
GetCenter(llb, NULL, NULL);
double lat, lon;
GetCenter(llb, &lat, NULL);
// Missing lon pointer still saves a result for lat.
ASSERT_EQ(0.0, lat);
GetCenter(llb, NULL, &lon);
// Missing lat pointer still saves a result for lon.
ASSERT_EQ(0.0, lat);
// A default LatLonBox is well defined thus so is its center.
GetCenter(llb, &lat, &lon);
ASSERT_EQ(0.0, lat);
ASSERT_EQ(0.0, lon);
// A default LatLonAltBox is well defined thus so is its center.
LatLonAltBoxPtr llab = factory->CreateLatLonAltBox();
GetCenter(llab, &lat, &lon);
ASSERT_EQ(0.0, lat);
ASSERT_EQ(0.0, lon);
}
TEST(LocationUtilTest, TestGetFeatureLatLon) {
KmlFactory* factory = KmlFactory::GetFactory();
const double kLat(-22.22);
const double kLon(42.123);
PlacemarkPtr placemark = factory->CreatePlacemark();
placemark->set_geometry(CreatePointCoordinates(kLat, kLon));
double lat, lon;
ASSERT_TRUE(GetFeatureLatLon(placemark, &lat, &lon));
ASSERT_EQ(kLat, lat);
ASSERT_EQ(kLon, lon);
}
TEST(LocationUtilTest, TestGetModelLatLon) {
KmlFactory* factory = KmlFactory::GetFactory();
const double kLat(-22.22);
const double kLon(42.123);
ModelPtr model = factory->CreateModel();
LocationPtr location = factory->CreateLocation();
location->set_latitude(kLat);
location->set_longitude(kLon);
model->set_location(location);
double lat, lon;
ASSERT_TRUE(GetModelLatLon(model, &lat, &lon));
ASSERT_EQ(kLat, lat);
ASSERT_EQ(kLon, lon);
}
TEST(LocationUtilTest, TestGetPlacemarkLatLon) {
KmlFactory* factory = KmlFactory::GetFactory();
const double kLat(-22.22);
const double kLon(42.123);
PlacemarkPtr placemark = factory->CreatePlacemark();
placemark->set_geometry(CreatePointCoordinates(kLat, kLon));
double lat, lon;
ASSERT_TRUE(GetPlacemarkLatLon(placemark, &lat, &lon));
ASSERT_EQ(kLat, lat);
ASSERT_EQ(kLon, lon);
}
TEST(LocationUtilTest, TestGetPointLatLon) {
const double kLat(-22.22);
const double kLon(42.123);
double lat, lon;
ASSERT_TRUE(GetPointLatLon(CreatePointCoordinates(kLat, kLon), &lat, &lon));
ASSERT_EQ(kLat, lat);
ASSERT_EQ(kLon, lon);
}
// This internal utility function parses the testcase file to a KmlFile.
static KmlFilePtr ParseFromDataDirFile(const std::string& subdir,
const std::string& filename) {
std::string kml_data;
const std::string kml_file =
File::JoinPaths(File::JoinPaths(std::string(DATADIR), subdir), filename);
return File::ReadFileToString(kml_file, &kml_data) ?
KmlFile::CreateFromParse(kml_data, NULL) : NULL;
}
// This is a table of test cases.
static const struct {
const char* subdir; // Subdirectory of testdata.
const char* kml_filename; // Path relative to subdir.
const char* feature_id; // id= of Feature within file.
bool has_bounds; // Expected return value of GetFeatureBounds.
double north; // Expected values of Bbox fields iff has_bounds == true.
double south;
double east;
double west;
bool has_loc; // Expected return value of GetFeatureLatLon.
double lat; // Expected values of GetFeatureLatLon iff has_loc == true.
double lon;
} kTestCases[] = {
{ // A 2d Placemark.
"kml", "kmlsamples.kml", "simple-placemark",
true, 37.4222899014025, 37.4222899014025, -122.082203542568,
-122.082203542568,
true, 37.4222899014025, -122.082203542568 },
{ // A 3d Placemark.
"kml", "kmlsamples.kml", "floating-placemark",
true, 37.4220033612141, 37.4220033612141, -122.084075, -122.084075,
true, 37.4220033612141, -122.084075 },
{ // A Placemark with no Geometry.
"kml", "kmlsamples.kml", "descriptive-html-placemark",
false, 0, 0, 0, 0,
false, 0, 0 },
{ // A 2d LineString Placemark.
"kml", "kmlsamples.kml", "tessellated-linestring-placemark",
true, 36.1067787047714, 36.0905099328766, -112.081423783034,
-112.087026775269,
true, 36.098644318824, -112.0842252791515 },
{ // A 3d LineString Placemark (altitudeMode=absolute, and alt != 0).
"kml", "kmlsamples.kml", "purple-line-placemark", true, 36.0944767260255,
36.086463123013, -112.265654928602, -112.269526855561,
true, 36.09046992451925, -112.2675908920815 },
#if 0 // TODO
{ // A Polygon with only an outerBoundaryIs.
"kml", "kmlsamples.kml", "b41", true, 37.4228181532365, 37.4220817196725,
-122.08509907149, -122.086016227378,
true, 37.4224499364545, -122.085557649434 },
#endif
{ // A Polygon with holes.
"kml", "kmlsamples.kml", "pentagon", true, 38.872910162817, 38.868757801256,
-77.0531553685479, -77.0584405629039,
true, 38.8708339820365, -77.0557979657259 },
{ // A Folder with multiple Features, but none with any location info.
"kml", "kmlsamples.kml", "screen-overlays-folder",
false, 0, 0, 0, 0,
false, 0, 0 },
{ // Model
"kml", "model-macky.kml", "model-macky",
true, 40.009993372683, 40.009993372683, -105.272774533734,
-105.272774533734,
true, 40.009993372683, -105.272774533734
},
{ // PhotoOverlay
"kml", "photooverlay-zermatt.kml", "photooverlay-zermatt",
true, 45.968226693, 45.968226693, 7.71792711000002, 7.71792711000002,
true, 45.968226693, 7.71792711000002
},
#if 0 // TODO
{ // GroundOverlay
},
{ // A Folder with multiple Point Placemarks.
},
{ // A Folder with multiple LineString Placemarks.
},
{ // A Folder with multiple Polygon Placemarks.
},
{ // A Document with multiple Folders each with multiple Features.
}
#endif
};
TEST(LocationUtilTest, RunTestCases) {
size_t size = sizeof(kTestCases)/sizeof(kTestCases[0]);
for (size_t i = 0; i < size; ++i) {
KmlFilePtr kml_file =
ParseFromDataDirFile(kTestCases[i].subdir, kTestCases[i].kml_filename);
// Assert basic sanity of KmlFile.
ASSERT_TRUE(kml_file) << kTestCases[i].kml_filename;
ASSERT_TRUE(kml_file->get_root());
kmldom::FeaturePtr feature = kmldom::AsFeature(
kml_file->GetObjectById(kTestCases[i].feature_id));
// Asserts both that this id is found and is a Feature.
ASSERT_TRUE(feature);
Bbox bbox;
ASSERT_EQ(kTestCases[i].has_bounds, GetFeatureBounds(feature, &bbox))
<< kTestCases[i].kml_filename << " " << kTestCases[i].feature_id;
// GetFeatureBounds returns the same no matter the state of the bbox arg.
ASSERT_EQ(kTestCases[i].has_bounds, GetFeatureBounds(feature, NULL));
if (kTestCases[i].has_bounds) {
// If has_bounds then the test case n,s,e,w are valid to test.
ASSERT_EQ(kTestCases[i].north, bbox.get_north());
ASSERT_EQ(kTestCases[i].south, bbox.get_south());
ASSERT_EQ(kTestCases[i].east, bbox.get_east());
ASSERT_EQ(kTestCases[i].west, bbox.get_west());
}
double lat, lon;
ASSERT_EQ(kTestCases[i].has_loc, GetFeatureLatLon(feature, &lat, &lon));
// GetFeatureBounds returns same no matter the state of the lat/lon args.
ASSERT_EQ(kTestCases[i].has_loc, GetFeatureLatLon(feature, &lat, NULL));
ASSERT_EQ(kTestCases[i].has_loc, GetFeatureLatLon(feature, NULL, &lon));
ASSERT_EQ(kTestCases[i].has_loc, GetFeatureLatLon(feature, NULL, NULL));
if (kTestCases[i].has_loc) {
// If has_loc then the test case lat,lon are valid to test.
ASSERT_EQ(kTestCases[i].lat, lat);
ASSERT_EQ(kTestCases[i].lon, lon);
}
}
}
} // end namespace kmlengine
int main(int argc, char** argv) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
<|endoftext|> |
<commit_before>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2007, Image Engine Design Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the name of Image Engine Design nor the names of any
// other contributors to this software may be used to endorse or
// promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////
#include <cassert>
#include "maya/MPointArray.h"
#include "maya/MVectorArray.h"
#include "maya/MIntArray.h"
#include "maya/MFloatPointArray.h"
#include "maya/MFloatVectorArray.h"
#include "maya/MFnMesh.h"
#include "maya/MFnMeshData.h"
#include "IECoreMaya/StatusException.h"
namespace IECoreMaya
{
template<>
struct MayaMeshBuilder<double>::Data
{
MPointArray m_P;
MVectorArray m_N;
MIntArray m_verticesPerFace;
MIntArray m_vertexIds;
};
template<>
struct MayaMeshBuilder<float>::Data
{
MFloatPointArray m_P;
MVectorArray m_N;
MIntArray m_verticesPerFace;
MIntArray m_vertexIds;
};
template<typename T>
MayaMeshBuilder<T>::MayaMeshBuilder( MObject parentOrOwner ) : m_parentOrOwner( parentOrOwner )
{
m_data = new Data();
}
template<typename T>
MayaMeshBuilder<T>::~MayaMeshBuilder()
{
delete m_data;
}
template<>
void MayaMeshBuilder<float>::addVertex( const Imath::V3f &p, const Imath::V3f &n )
{
m_data->m_P.append( MFloatPoint( p.x, p.y, p.z ) );
m_data->m_N.append( MFloatVector( n.x, n.y, n.z ) );
}
template<>
void MayaMeshBuilder<double>::addVertex( const Imath::V3d &p, const Imath::V3d &n )
{
m_data->m_P.append( MPoint( p.x, p.y, p.z ) );
m_data->m_N.append( MVector( n.x, n.y, n.z ) );
}
template<typename T>
void MayaMeshBuilder<T>::addTriangle( int v0, int v1, int v2 )
{
m_data->m_verticesPerFace.append( 3 );
m_data->m_vertexIds.append( v0 );
m_data->m_vertexIds.append( v1 );
m_data->m_vertexIds.append( v2 );
}
template<typename T>
MObject MayaMeshBuilder<T>::mesh() const
{
MStatus s;
MFnMesh fnMesh;
MObject result = fnMesh.create(
m_data->m_P.length(),
m_data->m_verticesPerFace.length(),
m_data->m_P,
m_data->m_verticesPerFace,
m_data->m_vertexIds,
m_parentOrOwner,
&s
);
if (!s)
{
throw StatusException( s );
}
assert( result != MObject::kNullObj );
MIntArray vertexList;
for (unsigned i = 0; i < m_data->m_N.length(); ++i)
{
vertexList.append( i );
}
fnMesh.setVertexNormals(
m_data->m_N,
vertexList
);
return m_parentOrOwner;
}
}
<commit_msg>Made template member functions inline<commit_after>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2007, Image Engine Design Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the name of Image Engine Design nor the names of any
// other contributors to this software may be used to endorse or
// promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////
#include <cassert>
#include "maya/MPointArray.h"
#include "maya/MVectorArray.h"
#include "maya/MIntArray.h"
#include "maya/MFloatPointArray.h"
#include "maya/MFloatVectorArray.h"
#include "maya/MFnMesh.h"
#include "maya/MFnMeshData.h"
#include "IECoreMaya/StatusException.h"
namespace IECoreMaya
{
template<>
struct MayaMeshBuilder<double>::Data
{
MPointArray m_P;
MVectorArray m_N;
MIntArray m_verticesPerFace;
MIntArray m_vertexIds;
};
template<>
struct MayaMeshBuilder<float>::Data
{
MFloatPointArray m_P;
MVectorArray m_N;
MIntArray m_verticesPerFace;
MIntArray m_vertexIds;
};
template<typename T>
MayaMeshBuilder<T>::MayaMeshBuilder( MObject parentOrOwner ) : m_parentOrOwner( parentOrOwner )
{
m_data = new Data();
}
template<typename T>
MayaMeshBuilder<T>::~MayaMeshBuilder()
{
delete m_data;
}
template<>
inline void MayaMeshBuilder<float>::addVertex( const Imath::V3f &p, const Imath::V3f &n )
{
m_data->m_P.append( MFloatPoint( p.x, p.y, p.z ) );
m_data->m_N.append( MFloatVector( n.x, n.y, n.z ) );
}
template<>
inline void MayaMeshBuilder<double>::addVertex( const Imath::V3d &p, const Imath::V3d &n )
{
m_data->m_P.append( MPoint( p.x, p.y, p.z ) );
m_data->m_N.append( MVector( n.x, n.y, n.z ) );
}
template<typename T>
inline void MayaMeshBuilder<T>::addTriangle( int v0, int v1, int v2 )
{
m_data->m_verticesPerFace.append( 3 );
m_data->m_vertexIds.append( v0 );
m_data->m_vertexIds.append( v1 );
m_data->m_vertexIds.append( v2 );
}
template<typename T>
inline MObject MayaMeshBuilder<T>::mesh() const
{
MStatus s;
MFnMesh fnMesh;
MObject result = fnMesh.create(
m_data->m_P.length(),
m_data->m_verticesPerFace.length(),
m_data->m_P,
m_data->m_verticesPerFace,
m_data->m_vertexIds,
m_parentOrOwner,
&s
);
if (!s)
{
throw StatusException( s );
}
assert( result != MObject::kNullObj );
MIntArray vertexList;
for (unsigned i = 0; i < m_data->m_N.length(); ++i)
{
vertexList.append( i );
}
fnMesh.setVertexNormals(
m_data->m_N,
vertexList
);
return m_parentOrOwner;
}
}
<|endoftext|> |
<commit_before>/**
* Copyright (c) 2011-2015 libbitcoin developers (see AUTHORS)
* Copyright (c) 2016-2018 metaverse core developers (see MVS-AUTHORS)
*
* This file is part of metaverse.
*
* metaverse is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License with
* additional permissions to the one published by the Free Software
* Foundation, either version 3 of the License, or (at your option)
* any later version. For more information see LICENSE.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <metaverse/blockchain/block_fetcher.hpp>
#include <atomic>
#include <cstdint>
#include <memory>
#include <system_error>
#include <metaverse/blockchain/block_chain.hpp>
namespace libbitcoin {
namespace blockchain {
using namespace chain;
using namespace std::placeholders;
// TODO: split into header.
// This class is used only locally.
class block_fetcher
: public std::enable_shared_from_this<block_fetcher>
{
public:
block_fetcher(block_chain& chain)
: blockchain_(chain)
{
}
template <typename BlockIndex>
void start(const BlockIndex& index,
block_chain::block_fetch_handler handler)
{
// Create the block.
const auto block = std::make_shared<chain::block>();
blockchain_.fetch_block_header(index,
std::bind(&block_fetcher::handle_fetch_header,
shared_from_this(), _1, _2, block, handler));
}
private:
void handle_fetch_header(const code& ec, const header& header,
block::ptr block, block_chain::block_fetch_handler handler)
{
if (ec)
{
handler(ec, nullptr);
return;
}
// Set the block header.
block->header = header;
const auto hash = header.hash();
blockchain_.fetch_block_transaction_hashes(hash,
std::bind(&block_fetcher::fetch_transactions,
shared_from_this(), _1, _2, block, handler));
}
void fetch_transactions(const code& ec, const hash_list& hashes,
block::ptr block, block_chain::block_fetch_handler handler)
{
if (ec)
{
handler(ec, nullptr);
return;
}
// Set the block transaction size.
const auto count = hashes.size();
block->header.transaction_count = count;
block->transactions.resize(count);
// This will be called exactly once by the synchronizer.
const auto completion_handler =
std::bind(&block_fetcher::handle_complete,
shared_from_this(), _1, _2, handler);
// Synchronize transaction fetch calls to one completion call.
const auto complete = synchronize(completion_handler, count,
"block_fetcher");
// blockchain::fetch_transaction is thread safe.
size_t index = 0;
for (const auto& hash: hashes)
blockchain_.fetch_transaction(hash,
std::bind(&block_fetcher::handle_fetch_transaction,
shared_from_this(), _1, _2, index++, block, complete));
}
void handle_fetch_transaction(const code& ec,
const transaction& transaction, size_t index, block::ptr block,
block_chain::block_fetch_handler handler)
{
if (ec)
{
handler(ec, nullptr);
return;
}
// Critical Section
///////////////////////////////////////////////////////////////////////
mutex_.lock();
// TRANSACTION COPY
block->transactions[index] = transaction;
mutex_.unlock();
///////////////////////////////////////////////////////////////////////
handler(error::success, block);
}
// If ec success then there is no possibility that block is being written.
void handle_complete(const code& ec, block::ptr block,
block_chain::block_fetch_handler handler)
{
if (ec)
handler(ec, nullptr);
else
handler(error::success, block);
}
block_chain& blockchain_;
mutable shared_mutex mutex_;
};
void fetch_block(block_chain& chain, uint64_t height,
block_chain::block_fetch_handler handle_fetch)
{
const auto fetcher = std::make_shared<block_fetcher>(chain);
fetcher->start(height, handle_fetch);
}
void fetch_block(block_chain& chain, const hash_digest& hash,
block_chain::block_fetch_handler handle_fetch)
{
const auto fetcher = std::make_shared<block_fetcher>(chain);
fetcher->start(hash, handle_fetch);
}
} // namespace blockchain
} // namespace libbitcoin
<commit_msg>block message serialize<commit_after>/**
* Copyright (c) 2011-2015 libbitcoin developers (see AUTHORS)
* Copyright (c) 2016-2018 metaverse core developers (see MVS-AUTHORS)
*
* This file is part of metaverse.
*
* metaverse is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License with
* additional permissions to the one published by the Free Software
* Foundation, either version 3 of the License, or (at your option)
* any later version. For more information see LICENSE.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <metaverse/blockchain/block_fetcher.hpp>
#include <atomic>
#include <cstdint>
#include <memory>
#include <system_error>
#include <metaverse/blockchain/block_chain.hpp>
namespace libbitcoin {
namespace blockchain {
using namespace chain;
using namespace std::placeholders;
// TODO: split into header.
// This class is used only locally.
class block_fetcher
: public std::enable_shared_from_this<block_fetcher>
{
public:
block_fetcher(block_chain& chain)
: blockchain_(chain)
{
}
template <typename BlockIndex>
void start(const BlockIndex& index,
block_chain::block_fetch_handler handler)
{
// Create the block.
const auto block = std::make_shared<chain::block>();
blockchain_.fetch_block_header(index,
std::bind(&block_fetcher::handle_fetch_header,
shared_from_this(), _1, _2, block, handler));
}
private:
void handle_fetch_header(const code& ec, const header& header,
block::ptr block, block_chain::block_fetch_handler handler) {
if (ec) {
handler(ec, nullptr);
return;
}
// Set the block header.
block->header = header;
const auto& hash = block->header.hash();
if (block->header.is_proof_of_stake())
{
blockchain_.fetch_block_signature(hash,
std::bind(&block_fetcher::handle_fetch_signature,
shared_from_this(), _1, _2, block, handler));
} else {
blockchain_.fetch_block_transaction_hashes(hash,
std::bind(&block_fetcher::fetch_transactions,
shared_from_this(), _1, _2, block, handler));
}
}
void handle_fetch_signature(const code& ec, const ec_signature& sig,
block::ptr block, block_chain::block_fetch_handler handler){
if (ec) {
handler(ec, nullptr);
return;
}
// Set the block header.
block->blocksig = sig;
const auto& hash = block->header.hash();
blockchain_.fetch_block_transaction_hashes(hash,
std::bind(&block_fetcher::fetch_transactions,
shared_from_this(), _1, _2, block, handler));
}
void fetch_transactions(const code& ec, const hash_list& hashes,
block::ptr block, block_chain::block_fetch_handler handler)
{
if (ec)
{
handler(ec, nullptr);
return;
}
// Set the block transaction size.
const auto count = hashes.size();
block->header.transaction_count = count;
block->transactions.resize(count);
// This will be called exactly once by the synchronizer.
const auto completion_handler =
std::bind(&block_fetcher::handle_complete,
shared_from_this(), _1, _2, handler);
// Synchronize transaction fetch calls to one completion call.
const auto complete = synchronize(completion_handler, count,
"block_fetcher");
// blockchain::fetch_transaction is thread safe.
size_t index = 0;
for (const auto& hash: hashes)
blockchain_.fetch_transaction(hash,
std::bind(&block_fetcher::handle_fetch_transaction,
shared_from_this(), _1, _2, index++, block, complete));
}
void handle_fetch_transaction(const code& ec,
const transaction& transaction, size_t index, block::ptr block,
block_chain::block_fetch_handler handler)
{
if (ec)
{
handler(ec, nullptr);
return;
}
// Critical Section
///////////////////////////////////////////////////////////////////////
mutex_.lock();
// TRANSACTION COPY
block->transactions[index] = transaction;
mutex_.unlock();
///////////////////////////////////////////////////////////////////////
handler(error::success, block);
}
// If ec success then there is no possibility that block is being written.
void handle_complete(const code& ec, block::ptr block,
block_chain::block_fetch_handler handler)
{
if (ec)
handler(ec, nullptr);
else
handler(error::success, block);
}
block_chain& blockchain_;
mutable shared_mutex mutex_;
};
void fetch_block(block_chain& chain, uint64_t height,
block_chain::block_fetch_handler handle_fetch)
{
const auto fetcher = std::make_shared<block_fetcher>(chain);
fetcher->start(height, handle_fetch);
}
void fetch_block(block_chain& chain, const hash_digest& hash,
block_chain::block_fetch_handler handle_fetch)
{
const auto fetcher = std::make_shared<block_fetcher>(chain);
fetcher->start(hash, handle_fetch);
}
} // namespace blockchain
} // namespace libbitcoin
<|endoftext|> |
<commit_before>#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <windows.h>
#include "refalrts-platform-specific.h"
bool refalrts::api::get_main_module_name(
char (&module_name)[refalrts::api::cModuleNameBufferLen]
) {
DWORD length = GetModuleFileName(NULL, module_name, cModuleNameBufferLen);
return (length != 0)
&& (
length < cModuleNameBufferLen
|| (
// На ОС > Windows XP функция при недостаточном размере буфера
// возвращает этот код ошибки.
GetLastError() != ERROR_INSUFFICIENT_BUFFER
// Windows XP не устанавливает кода ошибки, но при этом заполняет
// буфер без добавления концевого нуля
&& module_name[cModuleNameBufferLen - 1] == '\0'
)
);
}
int refalrts::api::system(const char *command) {
return ::system(command);
}
bool refalrts::api::get_current_directory(char buffer[], size_t size) {
DWORD result = GetCurrentDirectory(static_cast<DWORD>(size), buffer);
return (0 != result && result < size);
}
refalrts::RefalNumber refalrts::api::get_pid() {
return static_cast<refalrts::RefalNumber>(GetCurrentProcessId());
}
refalrts::RefalNumber refalrts::api::get_ppid() {
return static_cast<refalrts::RefalNumber>(GetCurrentProcessId());
}
struct refalrts::api::stat {
BY_HANDLE_FILE_INFORMATION info;
};
const refalrts::api::stat *
refalrts::api::stat_create(const char *filename) {
HANDLE h = CreateFile(
filename,
GENERIC_READ,
FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL
);
if (h == INVALID_HANDLE_VALUE) {
return 0;
}
refalrts::api::stat *api_stat = new ::refalrts::api::stat();
BOOL res = GetFileInformationByHandle(h, &api_stat->info);
CloseHandle(h);
if (res) {
return api_stat;
} else {
delete api_stat;
return 0;
}
}
signed refalrts::api::stat_compare(
const refalrts::api::stat *left, const refalrts::api::stat *right
) {
if (left->info.dwVolumeSerialNumber < right->info.dwVolumeSerialNumber) {
return -1;
} else if (left->info.dwVolumeSerialNumber > right->info.dwVolumeSerialNumber) {
return +1;
} else if (left->info.nFileIndexHigh < right->info.nFileIndexHigh) {
return -1;
} else if (left->info.nFileIndexHigh > right->info.nFileIndexHigh) {
return +1;
} else if (left->info.nFileIndexLow < right->info.nFileIndexLow) {
return -1;
} else if (left->info.nFileIndexLow > right->info.nFileIndexLow) {
return +1;
} else {
return 0;
}
}
void refalrts::api::stat_destroy(const refalrts::api::stat *stat) {
delete stat;
}
const char refalrts::api::path_env_separator = ';';
const char *const refalrts::api::directory_separators = "\\/";
bool refalrts::api::is_directory_ended_to_separator(const char *directory) {
size_t len = strlen(directory);
return (len == 0) || directory[len - 1] == '/' || directory[len - 1] == '\\'
|| (len == 2 && directory[1] == ':');
}
bool refalrts::api::is_single_file_name(const char *name) {
size_t len = strlen(name);
return
// путь не содержит разделителей каталогов
strchr(name, '/') == 0 && strchr(name, '\\') == 0
// и не начинается с буквы диска (c:filename.ext)
&& ! (len >= 2 && isalpha(name[0]) && name[1] == ':');
}
const char *refalrts::api::default_lib_extension = ".dll";
#if defined(REFAL_5_LAMBDA_USE_WINDOWS_9X)
refalrts::api::ClockNs *refalrts::api::init_clock_ns() {
return 0;
}
double refalrts::api::clock_ns(refalrts::api::ClockNs *) {
return clock() * 1e9 / CLOCKS_PER_SEC;
}
void refalrts::api::free_clock_ns(refalrts::api::ClockNs *) {
/* ничего не делаем */
}
#else /* defined(REFAL_5_LAMBDA_USE_WINDOWS_9X) */
struct refalrts::api::ClockNs {
ULARGE_INTEGER start_of_program;
};
refalrts::api::ClockNs *refalrts::api::init_clock_ns() {
ClockNs *res = new ClockNs;
GetSystemTimeAsFileTime((LPFILETIME) &res->start_of_program);
return res;
}
double refalrts::api::clock_ns(refalrts::api::ClockNs *clk) {
ULARGE_INTEGER now;
ULARGE_INTEGER start = clk->start_of_program;
GetSystemTimeAsFileTime((LPFILETIME) &now);
#if defined(REFAL_5_LAMBDA_COMPILER_DONT_SUPPORT_64)
double hi_diff =
(now.u.LowPart >= start.u.LowPart)
? (now.u.HighPart - start.u.HighPart)
: (now.u.HighPart - start.u.HighPart - 1);
double low_diff = now.u.LowPart - start.u.LowPart;
return (hi_diff * 4294967296 + low_diff) * 100;
#else /* defined(REFAL_5_LAMBDA_COMPILER_DONT_SUPPORT_64) */
return (now.QuadPart - start.QuadPart) * 100.0;
#endif /* defined(REFAL_5_LAMBDA_COMPILER_DONT_SUPPORT_64) */
}
void refalrts::api::free_clock_ns(refalrts::api::ClockNs *clk) {
delete clk;
}
#endif /* defined(REFAL_5_LAMBDA_USE_WINDOWS_9X) */
<commit_msg>Попытка использовать QueryPerformanceCounter() в Windows (#206)<commit_after>#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <windows.h>
#include "refalrts-platform-specific.h"
bool refalrts::api::get_main_module_name(
char (&module_name)[refalrts::api::cModuleNameBufferLen]
) {
DWORD length = GetModuleFileName(NULL, module_name, cModuleNameBufferLen);
return (length != 0)
&& (
length < cModuleNameBufferLen
|| (
// На ОС > Windows XP функция при недостаточном размере буфера
// возвращает этот код ошибки.
GetLastError() != ERROR_INSUFFICIENT_BUFFER
// Windows XP не устанавливает кода ошибки, но при этом заполняет
// буфер без добавления концевого нуля
&& module_name[cModuleNameBufferLen - 1] == '\0'
)
);
}
int refalrts::api::system(const char *command) {
return ::system(command);
}
bool refalrts::api::get_current_directory(char buffer[], size_t size) {
DWORD result = GetCurrentDirectory(static_cast<DWORD>(size), buffer);
return (0 != result && result < size);
}
refalrts::RefalNumber refalrts::api::get_pid() {
return static_cast<refalrts::RefalNumber>(GetCurrentProcessId());
}
refalrts::RefalNumber refalrts::api::get_ppid() {
return static_cast<refalrts::RefalNumber>(GetCurrentProcessId());
}
struct refalrts::api::stat {
BY_HANDLE_FILE_INFORMATION info;
};
const refalrts::api::stat *
refalrts::api::stat_create(const char *filename) {
HANDLE h = CreateFile(
filename,
GENERIC_READ,
FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL
);
if (h == INVALID_HANDLE_VALUE) {
return 0;
}
refalrts::api::stat *api_stat = new ::refalrts::api::stat();
BOOL res = GetFileInformationByHandle(h, &api_stat->info);
CloseHandle(h);
if (res) {
return api_stat;
} else {
delete api_stat;
return 0;
}
}
signed refalrts::api::stat_compare(
const refalrts::api::stat *left, const refalrts::api::stat *right
) {
if (left->info.dwVolumeSerialNumber < right->info.dwVolumeSerialNumber) {
return -1;
} else if (left->info.dwVolumeSerialNumber > right->info.dwVolumeSerialNumber) {
return +1;
} else if (left->info.nFileIndexHigh < right->info.nFileIndexHigh) {
return -1;
} else if (left->info.nFileIndexHigh > right->info.nFileIndexHigh) {
return +1;
} else if (left->info.nFileIndexLow < right->info.nFileIndexLow) {
return -1;
} else if (left->info.nFileIndexLow > right->info.nFileIndexLow) {
return +1;
} else {
return 0;
}
}
void refalrts::api::stat_destroy(const refalrts::api::stat *stat) {
delete stat;
}
const char refalrts::api::path_env_separator = ';';
const char *const refalrts::api::directory_separators = "\\/";
bool refalrts::api::is_directory_ended_to_separator(const char *directory) {
size_t len = strlen(directory);
return (len == 0) || directory[len - 1] == '/' || directory[len - 1] == '\\'
|| (len == 2 && directory[1] == ':');
}
bool refalrts::api::is_single_file_name(const char *name) {
size_t len = strlen(name);
return
// путь не содержит разделителей каталогов
strchr(name, '/') == 0 && strchr(name, '\\') == 0
// и не начинается с буквы диска (c:filename.ext)
&& ! (len >= 2 && isalpha(name[0]) && name[1] == ':');
}
const char *refalrts::api::default_lib_extension = ".dll";
#if defined(REFAL_5_LAMBDA_USE_WINDOWS_9X)
refalrts::api::ClockNs *refalrts::api::init_clock_ns() {
return 0;
}
double refalrts::api::clock_ns(refalrts::api::ClockNs *) {
return clock() * 1e9 / CLOCKS_PER_SEC;
}
void refalrts::api::free_clock_ns(refalrts::api::ClockNs *) {
/* ничего не делаем */
}
#else /* defined(REFAL_5_LAMBDA_USE_WINDOWS_9X) */
struct refalrts::api::ClockNs {
LARGE_INTEGER start_of_program;
double frequency_in_ns;
};
refalrts::api::ClockNs *refalrts::api::init_clock_ns() {
LARGE_INTEGER frequency;
QueryPerformanceFrequency(&frequency);
ClockNs *res = new ClockNs;
QueryPerformanceCounter(&res->start_of_program);
res->frequency_in_ns = 1.0e9 / frequency.QuadPart;
return res;
}
double refalrts::api::clock_ns(refalrts::api::ClockNs *clk) {
LARGE_INTEGER now;
LARGE_INTEGER start = clk->start_of_program;
QueryPerformanceCounter(&now);
#if defined(REFAL_5_LAMBDA_COMPILER_DONT_SUPPORT_64)
double hi_diff =
(now.u.LowPart >= start.u.LowPart)
? (now.u.HighPart - start.u.HighPart)
: (now.u.HighPart - start.u.HighPart - 1);
double low_diff = now.u.LowPart - start.u.LowPart;
return (hi_diff * 4294967296 + low_diff) * clk->frequency_in_ns;
#else /* defined(REFAL_5_LAMBDA_COMPILER_DONT_SUPPORT_64) */
return (now.QuadPart - start.QuadPart) * clk->frequency_in_ns;
#endif /* defined(REFAL_5_LAMBDA_COMPILER_DONT_SUPPORT_64) */
}
void refalrts::api::free_clock_ns(refalrts::api::ClockNs *clk) {
delete clk;
}
#endif /* defined(REFAL_5_LAMBDA_USE_WINDOWS_9X) */
<|endoftext|> |
<commit_before>/* SequenceBuilderWaveletTreeNoptrsS.cpp
* Copyright (C) 2012, Francisco Claude, all rights reserved.
*
* Francisco Claude <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include <SequenceBuilderWaveletTreeNoptrsS.h>
namespace cds_static {
SequenceBuilderWaveletTreeNoptrsS::SequenceBuilderWaveletTreeNoptrsS(BitSequenceBuilder * bsb, Mapper * am) {
this->bsb = bsb;
this->am = am;
bsb->use();
am->use();
}
SequenceBuilderWaveletTreeNoptrsS::~SequenceBuilderWaveletTreeNoptrsS() {
bsb->unuse();
am->unuse();
}
Sequence * SequenceBuilderWaveletTreeNoptrsS::build(uint * sequence, size_t len) {
return new WaveletTreeNoptrsS(sequence, len, bsb, am);
}
Sequence * SequenceBuilderWaveletTreeNoptrs::build(const Array & seq) {
return new WaveletTreeNoptrsS(seq, bsb, am);
}
};
<commit_msg>Fix commited by Eduardo Escobar<commit_after>/* SequenceBuilderWaveletTreeNoptrsS.cpp
* Copyright (C) 2012, Francisco Claude, all rights reserved.
*
* Francisco Claude <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include <SequenceBuilderWaveletTreeNoptrsS.h>
namespace cds_static {
SequenceBuilderWaveletTreeNoptrsS::SequenceBuilderWaveletTreeNoptrsS(BitSequenceBuilder * bsb, Mapper * am) {
this->bsb = bsb;
this->am = am;
bsb->use();
am->use();
}
SequenceBuilderWaveletTreeNoptrsS::~SequenceBuilderWaveletTreeNoptrsS() {
bsb->unuse();
am->unuse();
}
Sequence * SequenceBuilderWaveletTreeNoptrsS::build(uint * sequence, size_t len) {
return new WaveletTreeNoptrsS(sequence, len, bsb, am);
}
Sequence * SequenceBuilderWaveletTreeNoptrsS::build(const Array & seq) {
return new WaveletTreeNoptrsS(seq, bsb, am);
}
};
<|endoftext|> |
<commit_before>// DXGL
// Copyright (C) 2013 William Feely
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#include "common.h"
#include "glDirect3DExecuteBuffer.h"
glDirect3DExecuteBuffer::glDirect3DExecuteBuffer(LPD3DEXECUTEBUFFERDESC lpDesc)
{
locked = false;
inuse = false;
data = NULL;
desc = *lpDesc;
if(!(desc.dwFlags & D3DDEB_CAPS))
{
desc.dwFlags |= D3DDEB_CAPS;
desc.dwCaps = D3DDEBCAPS_MEM;
}
ZeroMemory(&datadesc,sizeof(D3DEXECUTEDATA));
datadesc.dwSize = sizeof(D3DEXECUTEDATA);
}
glDirect3DExecuteBuffer::~glDirect3DExecuteBuffer()
{
if(data) free(data);
}
HRESULT WINAPI glDirect3DExecuteBuffer::QueryInterface(REFIID riid, void** ppvObj)
{
if(!this) return DDERR_INVALIDOBJECT;
if((riid == IID_IUnknown) || (riid == IID_IDirect3DExecuteBuffer))
{
this->AddRef();
*ppvObj = this;
return D3D_OK;
}
return E_NOINTERFACE;
}
ULONG WINAPI glDirect3DExecuteBuffer::AddRef()
{
if(!this) return 0;
refcount++;
return refcount;
}
ULONG WINAPI glDirect3DExecuteBuffer::Release()
{
if(!this) return 0;
ULONG ret;
refcount--;
ret = refcount;
if(refcount == 0) delete this;
return ret;
}
HRESULT WINAPI glDirect3DExecuteBuffer::GetExecuteData(LPD3DEXECUTEDATA lpData)
{
if(!this) return DDERR_INVALIDOBJECT;
if(!lpData) return DDERR_INVALIDPARAMS;
if(locked) return D3DERR_EXECUTE_LOCKED;
if(lpData->dwSize < sizeof(D3DEXECUTEDATA)) return DDERR_INVALIDPARAMS;
memcpy(lpData,&datadesc,sizeof(D3DEXECUTEDATA));
return D3D_OK;
}
HRESULT WINAPI glDirect3DExecuteBuffer::Initialize(LPDIRECT3DDEVICE lpDirect3DDevice,
LPD3DEXECUTEBUFFERDESC lpDesc)
{
if(!this) return DDERR_INVALIDOBJECT;
return DDERR_ALREADYINITIALIZED;
}
HRESULT WINAPI glDirect3DExecuteBuffer::Lock(LPD3DEXECUTEBUFFERDESC lpDesc)
{
if(!this) return DDERR_INVALIDOBJECT;
if(!lpDesc) return DDERR_INVALIDPARAMS;
if(lpDesc->dwSize < sizeof(D3DEXECUTEBUFFERDESC)) return DDERR_INVALIDPARAMS;
if(inuse) return DDERR_WASSTILLDRAWING;
if(locked) return D3DERR_EXECUTE_LOCKED;
desc.dwCaps = lpDesc->dwCaps;
desc.dwFlags |= D3DDEB_LPDATA;
if(!data)
{
data = (unsigned char *)malloc(desc.dwBufferSize);
if(!data) return DDERR_OUTOFMEMORY;
}
desc.lpData = data;
memcpy(lpDesc,&desc,sizeof(D3DEXECUTEBUFFERDESC));
locked = true;
return D3D_OK;
}
HRESULT WINAPI glDirect3DExecuteBuffer::Optimize(DWORD dwDummy)
{
if(!this) return DDERR_INVALIDOBJECT;
return DDERR_UNSUPPORTED;
}
HRESULT WINAPI glDirect3DExecuteBuffer::SetExecuteData(LPD3DEXECUTEDATA lpData)
{
if(!this) return DDERR_INVALIDOBJECT;
if(!lpData) return DDERR_INVALIDPARAMS;
if(lpData->dwSize != sizeof(D3DEXECUTEDATA)) return DDERR_INVALIDPARAMS;
memcpy(&datadesc,lpData,sizeof(D3DEXECUTEDATA));
return D3D_OK;
}
HRESULT WINAPI glDirect3DExecuteBuffer::Unlock()
{
if(!this) return DDERR_INVALIDOBJECT;
if(inuse) return D3DERR_EXECUTE_NOT_LOCKED;
if(!locked) return D3DERR_EXECUTE_NOT_LOCKED;
locked = false;
return D3D_OK;
}
HRESULT WINAPI glDirect3DExecuteBuffer::Validate(LPDWORD lpdwOffset, LPD3DVALIDATECALLBACK lpFunc, LPVOID lpUserArg, DWORD dwReserved)
{
if(!this) return DDERR_INVALIDOBJECT;
return DDERR_UNSUPPORTED;
}
HRESULT glDirect3DExecuteBuffer::ExecuteLock(LPD3DEXECUTEBUFFERDESC lpDesc,LPD3DEXECUTEDATA lpData)
{
if(!this) return DDERR_INVALIDOBJECT;
if(inuse) return DDERR_WASSTILLDRAWING;
if(locked) return D3DERR_EXECUTE_LOCKED;
if(!lpDesc) return DDERR_INVALIDPARAMS;
if(!lpData) return DDERR_INVALIDPARAMS;
desc.dwFlags |= D3DDEB_LPDATA;
if(!data)
{
data = (unsigned char *)malloc(desc.dwBufferSize);
if(!data) return DDERR_OUTOFMEMORY;
}
desc.lpData = data;
memcpy(lpDesc,&desc,sizeof(D3DEXECUTEBUFFERDESC));
memcpy(lpData,&datadesc,sizeof(D3DEXECUTEDATA));
locked = true;
inuse = true;
return D3D_OK;
}
HRESULT glDirect3DExecuteBuffer::ExecuteUnlock(LPD3DEXECUTEDATA lpData)
{
if(!this) return DDERR_INVALIDOBJECT;
if(!lpData) return DDERR_INVALIDPARAMS;
if(!inuse) return D3DERR_EXECUTE_NOT_LOCKED;
inuse = false;
locked = false;
memcpy(&datadesc,lpData,sizeof(D3DEXECUTEDATA));
return D3D_OK;
}<commit_msg>Trace glDirect3DExecuteBuffer.cpp<commit_after>// DXGL
// Copyright (C) 2013 William Feely
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#include "common.h"
#include "glDirect3DExecuteBuffer.h"
glDirect3DExecuteBuffer::glDirect3DExecuteBuffer(LPD3DEXECUTEBUFFERDESC lpDesc)
{
TRACE_ENTER(2,14,this,14,lpDesc);
locked = false;
inuse = false;
data = NULL;
desc = *lpDesc;
if(!(desc.dwFlags & D3DDEB_CAPS))
{
desc.dwFlags |= D3DDEB_CAPS;
desc.dwCaps = D3DDEBCAPS_MEM;
}
ZeroMemory(&datadesc,sizeof(D3DEXECUTEDATA));
datadesc.dwSize = sizeof(D3DEXECUTEDATA);
TRACE_EXIT(-1,0);
}
glDirect3DExecuteBuffer::~glDirect3DExecuteBuffer()
{
TRACE_ENTER(1,14,this);
if(data) free(data);
TRACE_EXIT(-1,0);
}
HRESULT WINAPI glDirect3DExecuteBuffer::QueryInterface(REFIID riid, void** ppvObj)
{
TRACE_ENTER(3,14,this,24,&riid,14,ppvObj);
if(!this) TRACE_RET(23,DDERR_INVALIDOBJECT);
if((riid == IID_IUnknown) || (riid == IID_IDirect3DExecuteBuffer))
{
this->AddRef();
*ppvObj = this;
TRACE_EXIT(23,D3D_OK);
return D3D_OK;
}
TRACE_EXIT(23,E_NOINTERFACE);
return E_NOINTERFACE;
}
ULONG WINAPI glDirect3DExecuteBuffer::AddRef()
{
TRACE_ENTER(1,14,this);
if(!this) TRACE_RET(8,0);
refcount++;
TRACE_EXIT(8,refcount);
return refcount;
}
ULONG WINAPI glDirect3DExecuteBuffer::Release()
{
TRACE_ENTER(1,14,this);
if(!this) TRACE_RET(8,0);
ULONG ret;
refcount--;
ret = refcount;
if(refcount == 0) delete this;
TRACE_EXIT(8,ret);
return ret;
}
HRESULT WINAPI glDirect3DExecuteBuffer::GetExecuteData(LPD3DEXECUTEDATA lpData)
{
TRACE_ENTER(2,14,this,14,lpData);
if(!this) TRACE_RET(23,DDERR_INVALIDOBJECT);
if(!lpData) TRACE_RET(23,DDERR_INVALIDPARAMS);
if(locked) TRACE_RET(23,D3DERR_EXECUTE_LOCKED);
if(lpData->dwSize < sizeof(D3DEXECUTEDATA)) TRACE_RET(23,DDERR_INVALIDPARAMS);
memcpy(lpData,&datadesc,sizeof(D3DEXECUTEDATA));
TRACE_EXIT(23,D3D_OK);
return D3D_OK;
}
HRESULT WINAPI glDirect3DExecuteBuffer::Initialize(LPDIRECT3DDEVICE lpDirect3DDevice,
LPD3DEXECUTEBUFFERDESC lpDesc)
{
TRACE_ENTER(3,14,this,14,lpDirect3DDevice,14,lpDesc);
if(!this) TRACE_RET(23,DDERR_INVALIDOBJECT);
TRACE_EXIT(23,DDERR_ALREADYINITIALIZED);
return DDERR_ALREADYINITIALIZED;
}
HRESULT WINAPI glDirect3DExecuteBuffer::Lock(LPD3DEXECUTEBUFFERDESC lpDesc)
{
TRACE_ENTER(2,14,this,14,lpDesc);
if(!this) TRACE_RET(23,DDERR_INVALIDOBJECT);
if(!lpDesc) TRACE_RET(23,DDERR_INVALIDPARAMS);
if(lpDesc->dwSize < sizeof(D3DEXECUTEBUFFERDESC)) TRACE_RET(23,DDERR_INVALIDPARAMS);
if(inuse) TRACE_RET(23,DDERR_WASSTILLDRAWING);
if(locked) TRACE_RET(23,D3DERR_EXECUTE_LOCKED);
desc.dwCaps = lpDesc->dwCaps;
desc.dwFlags |= D3DDEB_LPDATA;
if(!data)
{
data = (unsigned char *)malloc(desc.dwBufferSize);
if(!data) return DDERR_OUTOFMEMORY;
}
desc.lpData = data;
memcpy(lpDesc,&desc,sizeof(D3DEXECUTEBUFFERDESC));
locked = true;
TRACE_EXIT(23,D3D_OK);
return D3D_OK;
}
HRESULT WINAPI glDirect3DExecuteBuffer::Optimize(DWORD dwDummy)
{
TRACE_ENTER(2,14,this,9,dwDummy);
if(!this) TRACE_RET(23,DDERR_INVALIDOBJECT);
TRACE_EXIT(23,DDERR_UNSUPPORTED);
return DDERR_UNSUPPORTED;
}
HRESULT WINAPI glDirect3DExecuteBuffer::SetExecuteData(LPD3DEXECUTEDATA lpData)
{
TRACE_ENTER(2,14,this,14,lpData);
if(!this) TRACE_RET(23,DDERR_INVALIDOBJECT);
if(!lpData) TRACE_RET(23,DDERR_INVALIDPARAMS);
if(lpData->dwSize != sizeof(D3DEXECUTEDATA)) TRACE_RET(23,DDERR_INVALIDPARAMS);
memcpy(&datadesc,lpData,sizeof(D3DEXECUTEDATA));
TRACE_EXIT(23,D3D_OK);
return D3D_OK;
}
HRESULT WINAPI glDirect3DExecuteBuffer::Unlock()
{
TRACE_ENTER(1,14,this);
if(!this) TRACE_RET(23,DDERR_INVALIDOBJECT);
if(inuse) TRACE_RET(23,D3DERR_EXECUTE_NOT_LOCKED);
if(!locked) TRACE_RET(23,D3DERR_EXECUTE_NOT_LOCKED);
locked = false;
TRACE_RET(23,D3D_OK);
return D3D_OK;
}
HRESULT WINAPI glDirect3DExecuteBuffer::Validate(LPDWORD lpdwOffset, LPD3DVALIDATECALLBACK lpFunc, LPVOID lpUserArg, DWORD dwReserved)
{
TRACE_ENTER(5,14,this,14,lpdwOffset,14,lpFunc,14,lpUserArg,9,dwReserved);
if(!this) TRACE_RET(23,DDERR_INVALIDOBJECT);
TRACE_EXIT(23,DDERR_UNSUPPORTED);
return DDERR_UNSUPPORTED;
}
HRESULT glDirect3DExecuteBuffer::ExecuteLock(LPD3DEXECUTEBUFFERDESC lpDesc,LPD3DEXECUTEDATA lpData)
{
TRACE_ENTER(3,14,this,14,lpDesc,14,lpData);
if(!this) TRACE_RET(23,DDERR_INVALIDOBJECT);
if(inuse) TRACE_RET(23,DDERR_WASSTILLDRAWING);
if(locked) TRACE_RET(23,D3DERR_EXECUTE_LOCKED);
if(!lpDesc) TRACE_RET(23,DDERR_INVALIDPARAMS);
if(!lpData) TRACE_RET(23,DDERR_INVALIDPARAMS);
desc.dwFlags |= D3DDEB_LPDATA;
if(!data)
{
data = (unsigned char *)malloc(desc.dwBufferSize);
if(!data) TRACE_RET(23,DDERR_OUTOFMEMORY);
}
desc.lpData = data;
memcpy(lpDesc,&desc,sizeof(D3DEXECUTEBUFFERDESC));
memcpy(lpData,&datadesc,sizeof(D3DEXECUTEDATA));
locked = true;
inuse = true;
TRACE_EXIT(23,D3D_OK);
return D3D_OK;
}
HRESULT glDirect3DExecuteBuffer::ExecuteUnlock(LPD3DEXECUTEDATA lpData)
{
TRACE_ENTER(2,14,this,14,lpData);
if(!this) TRACE_RET(23,DDERR_INVALIDOBJECT);
if(!lpData) TRACE_RET(23,DDERR_INVALIDPARAMS);
if(!inuse) TRACE_RET(23,D3DERR_EXECUTE_NOT_LOCKED);
inuse = false;
locked = false;
memcpy(&datadesc,lpData,sizeof(D3DEXECUTEDATA));
TRACE_RET(23,D3D_OK);
return D3D_OK;
}<|endoftext|> |
<commit_before>//---------------------------------------------------------------------------
// $Id$
// Version: $Name$
//
// Copyright (C) 1998, 2000, 2001, 2002, 2003, 2005 by the deal.II authors
//
// This file is subject to QPL and may not be distributed
// without copyright and license information. Please refer
// to the file deal.II/doc/license.html for the text and
// further information on this license.
//
//---------------------------------------------------------------------------
#include <base/exceptions.h>
#include <string>
#include <cstdlib>
#include <iostream>
#ifdef HAVE_STD_STRINGSTREAM
# include <sstream>
#else
# include <strstream>
#endif
#ifdef HAVE_GLIBC_STACKTRACE
# include <execinfo.h>
#endif
ExceptionBase::ExceptionBase ()
:
file(""), line(0), function(""), cond(""), exc("")
{}
ExceptionBase::ExceptionBase (const char* f, const int l, const char *func,
const char* c, const char *e)
:
file(f), line(l), function(func), cond(c), exc(e)
{}
ExceptionBase::~ExceptionBase () throw ()
{}
void ExceptionBase::set_fields (const char* f,
const int l,
const char *func,
const char *c,
const char *e)
{
file = f;
line = l;
function = func;
cond = c;
exc = e;
}
void ExceptionBase::print_exc_data (std::ostream &out) const
{
out << "An error occurred in line <" << line
<< "> of file <" << file
<< "> in function" << std::endl
<< " " << function << std::endl
<< "The violated condition was: "<< std::endl
<< " " << cond << std::endl
<< "The name and call sequence of the exception was:" << std::endl
<< " " << exc << std::endl
<< "Additional Information: " << std::endl;
}
void ExceptionBase::print_stack_trace (std::ostream &out) const
{
#ifdef HAVE_GLIBC_STACKTRACE
out << "Stacktrace:" << std::endl;
void * array[25];
const int n_frames = backtrace(array, 25);
char ** symbols = backtrace_symbols(array, n_frames);
// print the stacktraces. first
// omit all those frames that have
// ExceptionBase or
// deal_II_exceptions in their
// names, as these correspond to
// the exception raising mechanism
// themselves, rather than the
// place where the exception was
// triggered
int frame = 0;
while ((frame < n_frames)
&&
((std::string(symbols[frame]).find ("ExceptionBase") != std::string::npos)
||
(std::string(symbols[frame]).find ("deal_II_exceptions") != std::string::npos)))
++frame;
// output the rest
for (; frame < n_frames; ++frame)
out << symbols[frame]
<< std::endl;
free(symbols);
#endif
}
void ExceptionBase::print_info (std::ostream &out) const
{
out << "(none)" << std::endl;
}
const char * ExceptionBase::what () const throw ()
{
// if we say that this function
// does not throw exceptions, we
// better make sure it does not
try
{
// have a place where to store the
// description of the exception as
// a char *
//
// this thing obviously is not
// multi-threading safe, but we
// don't care about that for now
//
// we need to make this object
// static, since we want to return
// the data stored in it and
// therefore need a lifetime which
// is longer than the execution
// time of this function
static std::string description;
// convert the messages printed by
// the exceptions into a
// std::string
#ifdef HAVE_STD_STRINGSTREAM
std::ostringstream converter;
#else
std::ostrstream converter;
#endif
converter << "--------------------------------------------------------"
<< std::endl;
// put general info into the std::string
print_exc_data (converter);
// put in exception specific data
print_info (converter);
print_stack_trace (converter); // put in stacktrace (if available)
converter << "--------------------------------------------------------"
<< std::endl;
#ifndef HAVE_STD_STRINGSTREAM
converter << std::ends;
#endif
description = converter.str();
return description.c_str();
}
catch (std::exception &exc)
{
std::cerr << "*** Exception encountered in exception handling routines ***"
<< std::endl
<< "*** Message is " << std::endl
<< exc.what () << std::endl
<< "*** Aborting! ***" << std::endl;
std::abort ();
return 0;
}
catch (...)
{
std::cerr << "*** Exception encountered in exception handling routines ***"
<< std::endl
<< "*** Aborting! ***" << std::endl;
std::abort ();
return 0;
}
}
namespace deal_II_exceptions
{
std::string additional_assert_output;
void set_additional_assert_output (const char * const p)
{
additional_assert_output = p;
}
namespace internals
{
/**
* Number of exceptions dealt
* with so far. Zero at program
* start. Messages are only
* displayed if the value is
* zero.
*/
unsigned int n_treated_exceptions;
void issue_error_assert (const char *file,
int line,
const char *function,
const char *cond,
const char *exc_name,
ExceptionBase &e)
{
// fill the fields of the
// exception object
e.set_fields (file, line, function, cond, exc_name);
// if no other exception has
// been displayed before, show
// this one
if (n_treated_exceptions == 0)
{
std::cerr << "--------------------------------------------------------"
<< std::endl;
// print out general data
e.print_exc_data (std::cerr);
// print out exception
// specific data
e.print_info (std::cerr);
e.print_stack_trace (std::cerr);
std::cerr << "--------------------------------------------------------"
<< std::endl;
// if there is more to say,
// do so
if (!additional_assert_output.empty())
std::cerr << additional_assert_output << std::endl;
}
else
{
// if this is the first
// follow-up message,
// display a message that
// further exceptions are
// suppressed
if (n_treated_exceptions == 1)
std::cerr << "******** More assertions fail but messages are suppressed! ********"
<< std::endl;
};
// increase number of treated
// exceptions by one
n_treated_exceptions++;
// abort the program now since
// something has gone horribly
// wrong. however, there is one
// case where we do not want to
// do that, namely when another
// exception, possibly thrown
// by AssertThrow is active,
// since in that case we will
// not come to see the original
// exception. in that case
// indicate that the program is
// not aborted due to this
// reason.
if (std::uncaught_exception() == true)
{
// only display message once
if (n_treated_exceptions <= 1)
std::cerr << "******** Program is not aborted since another exception is active! ********"
<< std::endl;
}
else
std::abort ();
}
void abort ()
{
std::abort ();
}
}
}
// from the aclocal file:
// Newer versions of gcc have a very nice feature: you can set
// a verbose terminate handler, that not only aborts a program
// when an exception is thrown and not caught somewhere, but
// before aborting it prints that an exception has been thrown,
// and possibly what the std::exception::what() function has to
// say. Since many people run into the trap of not having a
// catch clause in main(), they wonder where that abort may be
// coming from. The terminate handler then at least says what is
// missing in their program.
#ifdef HAVE_VERBOSE_TERMINATE
namespace __gnu_cxx
{
extern void __verbose_terminate_handler ();
}
namespace
{
struct preload_terminate_dummy
{
preload_terminate_dummy()
{ std::set_terminate (__gnu_cxx::__verbose_terminate_handler); }
};
static preload_terminate_dummy dummy;
}
#endif
<commit_msg>There's no point to print a stacktrace in what() -- this function is usually called at the place where an exception is caught, not where it is triggered...<commit_after>//---------------------------------------------------------------------------
// $Id$
// Version: $Name$
//
// Copyright (C) 1998, 2000, 2001, 2002, 2003, 2005 by the deal.II authors
//
// This file is subject to QPL and may not be distributed
// without copyright and license information. Please refer
// to the file deal.II/doc/license.html for the text and
// further information on this license.
//
//---------------------------------------------------------------------------
#include <base/exceptions.h>
#include <string>
#include <cstdlib>
#include <iostream>
#ifdef HAVE_STD_STRINGSTREAM
# include <sstream>
#else
# include <strstream>
#endif
#ifdef HAVE_GLIBC_STACKTRACE
# include <execinfo.h>
#endif
ExceptionBase::ExceptionBase ()
:
file(""), line(0), function(""), cond(""), exc("")
{}
ExceptionBase::ExceptionBase (const char* f, const int l, const char *func,
const char* c, const char *e)
:
file(f), line(l), function(func), cond(c), exc(e)
{}
ExceptionBase::~ExceptionBase () throw ()
{}
void ExceptionBase::set_fields (const char* f,
const int l,
const char *func,
const char *c,
const char *e)
{
file = f;
line = l;
function = func;
cond = c;
exc = e;
}
void ExceptionBase::print_exc_data (std::ostream &out) const
{
out << "An error occurred in line <" << line
<< "> of file <" << file
<< "> in function" << std::endl
<< " " << function << std::endl
<< "The violated condition was: "<< std::endl
<< " " << cond << std::endl
<< "The name and call sequence of the exception was:" << std::endl
<< " " << exc << std::endl
<< "Additional Information: " << std::endl;
}
void ExceptionBase::print_stack_trace (std::ostream &out) const
{
#ifdef HAVE_GLIBC_STACKTRACE
out << "Stacktrace:" << std::endl;
void * array[25];
const int n_frames = backtrace(array, 25);
char ** symbols = backtrace_symbols(array, n_frames);
// print the stacktraces. first
// omit all those frames that have
// ExceptionBase or
// deal_II_exceptions in their
// names, as these correspond to
// the exception raising mechanism
// themselves, rather than the
// place where the exception was
// triggered
int frame = 0;
while ((frame < n_frames)
&&
((std::string(symbols[frame]).find ("ExceptionBase") != std::string::npos)
||
(std::string(symbols[frame]).find ("deal_II_exceptions") != std::string::npos)))
++frame;
// output the rest
for (; frame < n_frames; ++frame)
out << symbols[frame]
<< std::endl;
free(symbols);
#endif
}
void ExceptionBase::print_info (std::ostream &out) const
{
out << "(none)" << std::endl;
}
const char * ExceptionBase::what () const throw ()
{
// if we say that this function
// does not throw exceptions, we
// better make sure it does not
try
{
// have a place where to store the
// description of the exception as
// a char *
//
// this thing obviously is not
// multi-threading safe, but we
// don't care about that for now
//
// we need to make this object
// static, since we want to return
// the data stored in it and
// therefore need a lifetime which
// is longer than the execution
// time of this function
static std::string description;
// convert the messages printed by
// the exceptions into a
// std::string
#ifdef HAVE_STD_STRINGSTREAM
std::ostringstream converter;
#else
std::ostrstream converter;
#endif
converter << "--------------------------------------------------------"
<< std::endl;
// put general info into the std::string
print_exc_data (converter);
// put in exception specific data
print_info (converter);
converter << "--------------------------------------------------------"
<< std::endl;
#ifndef HAVE_STD_STRINGSTREAM
converter << std::ends;
#endif
description = converter.str();
return description.c_str();
}
catch (std::exception &exc)
{
std::cerr << "*** Exception encountered in exception handling routines ***"
<< std::endl
<< "*** Message is " << std::endl
<< exc.what () << std::endl
<< "*** Aborting! ***" << std::endl;
std::abort ();
return 0;
}
catch (...)
{
std::cerr << "*** Exception encountered in exception handling routines ***"
<< std::endl
<< "*** Aborting! ***" << std::endl;
std::abort ();
return 0;
}
}
namespace deal_II_exceptions
{
std::string additional_assert_output;
void set_additional_assert_output (const char * const p)
{
additional_assert_output = p;
}
namespace internals
{
/**
* Number of exceptions dealt
* with so far. Zero at program
* start. Messages are only
* displayed if the value is
* zero.
*/
unsigned int n_treated_exceptions;
void issue_error_assert (const char *file,
int line,
const char *function,
const char *cond,
const char *exc_name,
ExceptionBase &e)
{
// fill the fields of the
// exception object
e.set_fields (file, line, function, cond, exc_name);
// if no other exception has
// been displayed before, show
// this one
if (n_treated_exceptions == 0)
{
std::cerr << "--------------------------------------------------------"
<< std::endl;
// print out general data
e.print_exc_data (std::cerr);
// print out exception
// specific data
e.print_info (std::cerr);
e.print_stack_trace (std::cerr);
std::cerr << "--------------------------------------------------------"
<< std::endl;
// if there is more to say,
// do so
if (!additional_assert_output.empty())
std::cerr << additional_assert_output << std::endl;
}
else
{
// if this is the first
// follow-up message,
// display a message that
// further exceptions are
// suppressed
if (n_treated_exceptions == 1)
std::cerr << "******** More assertions fail but messages are suppressed! ********"
<< std::endl;
};
// increase number of treated
// exceptions by one
n_treated_exceptions++;
// abort the program now since
// something has gone horribly
// wrong. however, there is one
// case where we do not want to
// do that, namely when another
// exception, possibly thrown
// by AssertThrow is active,
// since in that case we will
// not come to see the original
// exception. in that case
// indicate that the program is
// not aborted due to this
// reason.
if (std::uncaught_exception() == true)
{
// only display message once
if (n_treated_exceptions <= 1)
std::cerr << "******** Program is not aborted since another exception is active! ********"
<< std::endl;
}
else
std::abort ();
}
void abort ()
{
std::abort ();
}
}
}
// from the aclocal file:
// Newer versions of gcc have a very nice feature: you can set
// a verbose terminate handler, that not only aborts a program
// when an exception is thrown and not caught somewhere, but
// before aborting it prints that an exception has been thrown,
// and possibly what the std::exception::what() function has to
// say. Since many people run into the trap of not having a
// catch clause in main(), they wonder where that abort may be
// coming from. The terminate handler then at least says what is
// missing in their program.
#ifdef HAVE_VERBOSE_TERMINATE
namespace __gnu_cxx
{
extern void __verbose_terminate_handler ();
}
namespace
{
struct preload_terminate_dummy
{
preload_terminate_dummy()
{ std::set_terminate (__gnu_cxx::__verbose_terminate_handler); }
};
static preload_terminate_dummy dummy;
}
#endif
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2008-2011, Gostai S.A.S.
*
* This software is provided "as is" without warranty of any kind,
* either expressed or implied, including but not limited to the
* implied warranties of fitness for a particular purpose.
*
* See the LICENSE file for more information.
*/
#include <iostream>
#include <boost/thread/tss.hpp>
#include <libport/cassert>
#include <libport/compiler.hh>
#include <libport/containers.hh>
#include <libport/cstdio>
#include <libport/debug.hh>
#include <libport/escape.hh>
#include <libport/fnmatch.h>
#include <libport/foreach.hh>
#include <libport/format.hh>
#include <libport/ip-semaphore.hh>
#include <libport/lockable.hh>
#include <libport/pthread.h>
#include <libport/thread-data.hh>
#include <libport/tokenizer.hh>
#include <libport/unistd.h>
#include <libport/utime.hh>
#include <libport/windows.hh>
#ifndef WIN32
# include <syslog.h>
#endif
#ifndef LIBPORT_DEBUG_DISABLE
GD_CATEGORY(Libport.Debug);
namespace libport
{
LIBPORT_API boost::function0<local_data&> debugger_data;
LIBPORT_API Debug* debugger = 0;
LIBPORT_API Debug::levels::Level Debug::filter_(levels::log);
local_data&
debugger_data_thread_local()
{
static boost::thread_specific_ptr<local_data> storage;
if (!storage.get())
storage.reset(new local_data);
return *storage;
}
local_data::local_data()
: indent(0)
{}
namespace debug
{
// Whether categories are enabled by default.
static bool default_category_state = true;
LIBPORT_API void
uninitialized_msg(const std::string& msg)
{
static bool dump =
getenv("GD_LEVEL") && libport::streq(getenv("GD_LEVEL"), "DUMP");
if (dump)
{
static bool first = true;
if (first)
{
std::cerr << "[Libport.Debug] "
<< "Uninitialized debug, fallback to stderr." << std::endl;
first = false;
}
std::cerr << "[Libport.Debug] " << msg;
if (msg.empty() || msg[msg.size() - 1] != '\n')
std::cerr << std::endl;
}
}
// Categories added so far.
ATTRIBUTE_PURE
categories_type&
categories()
{
static categories_type categories;
return categories;
}
typedef std::pair<bool, unsigned> pattern_infos_type;
typedef boost::unordered_map<category_type, pattern_infos_type>
patterns_type;
namespace
{
ATTRIBUTE_PURE
static unsigned
current_pattern()
{
static unsigned current = 0;
return current++;
}
// Patterns added so far.
ATTRIBUTE_PURE
patterns_type&
patterns()
{
static patterns_type patterns;
return patterns;
}
// Maximum category width.
ATTRIBUTE_PURE
size_t&
categories_largest()
{
static size_t res = 0;
return res;
}
inline
bool
match(category_type globbing, category_type string)
{
return fnmatch(globbing.name_get(), string.name_get()) == 0;
}
}
/// Given a category name, see whether it should be enabled or disabled.
/// Do not store it in the list of declared categories.
static
bool
category_name_enabled(category_type name)
{
int order = -1;
bool res = default_category_state;
foreach (patterns_type::value_type& s, patterns())
if (order < int(s.second.second)
&& match(s.first, name))
{
res = s.second.first;
order = s.second.second;
}
return res;
}
// New category.
category_type
add_category(category_type name)
{
categories()[name] = category_name_enabled(name);
categories_largest() =
std::max(categories_largest(), name.name_get().size());
return name;
}
int
enable_category(category_type pattern, bool enabled)
{
patterns()[pattern] = std::make_pair(enabled, current_pattern());
foreach (categories_type::value_type& s, categories())
if (match(pattern, s.first))
s.second = enabled;
return 42;
}
int
disable_category(category_type pattern)
{
return enable_category(pattern, false);
}
// Enable/Disable a new category pattern with modifier.
static int
auto_category(category_type pattern)
{
std::string p = pattern.name_get();
char modifier = p[0];
if (modifier == '+' || modifier == '-')
p = p.substr(1);
else
modifier = '+';
return enable_category(category_type(p), modifier == '+');
}
bool test_category(category_type name)
{
return
libport::has(categories(), name)
? categories()[name]
: category_name_enabled(name);
}
void
set_categories_state(const std::string& specs,
const category_modifier_type state)
{
// If the mode is "AUTO", then if the first specs is to enable
// ("-...") then the default is to enable, otherwise disable.
// If the mode if not AUTO, then the default is the converse of
// the mode: ENABLE -> false, and DISABLE => true.
default_category_state =
state == AUTO
? (!specs.empty() && specs[0] == '-')
: (state != ENABLE);
// Set all the existing categories to the default behavior
// before running the per-pattern tests.
foreach (categories_type::value_type& v, categories())
v.second = default_category_state;
foreach (const std::string& elem, make_tokenizer(specs, ","))
switch (state)
{
case ENABLE:
case DISABLE:
enable_category(category_type(elem), state == ENABLE);
break;
case AUTO:
auto_category(category_type(elem));
break;
}
}
}
Debug::Debug()
: locations_(getenv("GD_LOC"))
, timestamps_(getenv("GD_TIME") || getenv("GD_TIMESTAMP_US"))
{
// Process enabled/disabled/auto categories in environment.
if (const char* cp = getenv("GD_CATEGORY"))
debug::set_categories_state(cp, debug::AUTO);
else
{
if (const char* cp = getenv("GD_ENABLE_CATEGORY"))
debug::set_categories_state(cp, debug::ENABLE);
if (const char* cp = getenv("GD_DISABLE_CATEGORY"))
debug::set_categories_state(cp, debug::DISABLE);
}
if (const char* lvl_c = getenv("GD_LEVEL"))
filter(lvl_c);
}
Debug::~Debug()
{}
void
Debug::filter(levels::Level lvl)
{
filter_ = lvl;
}
void
Debug::filter(const std::string& lvl)
{
if (lvl == "NONE" || lvl == "0")
filter(Debug::levels::none);
else if (lvl == "LOG" || lvl == "1")
filter(Debug::levels::log);
else if (lvl == "TRACE" || lvl == "2")
filter(Debug::levels::trace);
else if (lvl == "DEBUG" || lvl == "3")
filter(Debug::levels::debug);
else if (lvl == "DUMP" || lvl == "4")
filter(Debug::levels::dump);
else
// Don't use GD_ABORT here, we can be in the debugger constructor!
pabort("invalid debug level (NONE, LOG, TRACE, DEBUG, DUMP or [0-4])");
}
unsigned
Debug::indentation() const
{
return debugger_data().indent;
}
Debug::levels::Level
Debug::level()
{
return filter_;
}
# ifdef LIBPORT_HAVE_IP_SEMAPHORE
static IPSemaphore& sem()
{
static IPSemaphore res(1);
return res;
}
# endif
void
Debug::debug(const std::string& msg,
types::Type type,
debug::category_type category,
const std::string& fun,
const std::string& file,
unsigned line)
{
# ifdef LIBPORT_HAVE_IP_SEMAPHORE
static bool useLock = getenv("GD_USE_LOCK") || getenv("GD_PID");
libport::Finally f;
if (useLock)
{
--sem();
f << boost::bind(&IPSemaphore::operator++, boost::ref(sem()));
}
# endif
message(category, msg, type, fun, file, line);
}
Debug*
Debug::push(debug::category_type category,
const std::string& msg,
const std::string& fun,
const std::string& file,
unsigned line)
{
message_push(category, msg, fun, file, line);
return this;
}
std::string
Debug::category_format(debug::category_type cat) const
{
std::string res = cat;
size_t size = res.size();
size_t largest = debug::categories_largest();
if (size < largest)
{
size_t diff = largest - size;
res = std::string(diff / 2, ' ')
+ res
+ std::string(diff / 2 + diff % 2, ' ');
}
return res;
}
namespace opts
{
void cb_debug_fun(const std::string& lvl)
{
GD_DEBUGGER->filter(lvl);
}
OptionValued::callback_type cb_debug(cb_debug_fun);
OptionValue
debug("set log verbosity (NONE, LOG, TRACE, DEBUG, DUMP) [LOG]",
"debug", 'd', "LEVEL", cb_debug);
}
ConsoleDebug::ConsoleDebug()
{}
namespace
{
inline
std::string
time()
{
static bool us = getenv("GD_TIMESTAMP_US");
if (us)
return string_cast(utime());
time_t now = std::time(0);
struct tm* ts = std::localtime(&now);
char buf[80];
strftime(buf, sizeof buf, "%a %Y-%m-%d %H:%M:%S %Z", ts);
return buf;
}
inline
std::string
color(int color, bool bold = true)
{
static bool tty = isatty(STDERR_FILENO);
static bool force = getenv("GD_COLOR");
static bool force_disable = getenv("GD_NO_COLOR");
return (((tty || force) && !force_disable)
? format("[33;0%s;%sm", bold ? 1 : 0, color)
: "");
}
}
static Debug::colors::Color
msg_color(Debug::types::Type type)
{
switch (type)
{
case Debug::types::info:
return Debug::colors::white;
case Debug::types::warn:
return Debug::colors::yellow;
case Debug::types::error:
return Debug::colors::red;
};
GD_UNREACHABLE();
}
void
ConsoleDebug::message(debug::category_type category,
const std::string& msg,
types::Type type,
const std::string& fun,
const std::string& file,
unsigned line)
{
std::ostringstream ostr;
Debug::colors::Color c = msg_color(type);
if (timestamps())
ostr << color(c) << time() << " ";
ostr << color(colors::purple)
<< "[" << category_format(category) << "] ";
{
static bool pid = getenv("GD_PID");
if (pid)
ostr << "[" << getpid() << "] ";
}
#ifndef WIN32
{
static bool thread = getenv("GD_THREAD");
if (thread)
ostr << "[" << pthread_self() << "] ";
}
#endif
ostr << color(c);
for (unsigned i = 0; i < debugger_data().indent; ++i)
ostr << " ";
// As syslog would do, don't issue the users' \n.
if (!msg.empty() && msg[msg.size() - 1] == '\n')
ostr.write(msg.c_str(), msg.size() - 1);
else
ostr << msg;
if (locations())
ostr << color(colors::blue)
<< " (" << fun << ", " << file << ":" << line << ")";
ostr << color(colors::white);
std::cerr << ostr.str() << std::endl;
}
void
ConsoleDebug::message_push(debug::category_type category,
const std::string& msg,
const std::string& fun,
const std::string& file,
unsigned line)
{
debug(msg, types::info, category, fun, file, line);
GD_INDENTATION_INC();
}
void
ConsoleDebug::pop()
{
assert_gt(debugger_data().indent, 0u);
GD_INDENTATION_DEC();
}
std::string gd_ihexdump(const unsigned char* data, unsigned size)
{
std::string res =
format("\"%s\"",
libport::escape(std::string((const char*)data, (size_t)(size))));
bool first = true;
for (unsigned i = 0; i < size; ++i)
{
if (first)
first = false;
else
res += " ";
// Cast to int, or boost::format will print the character.
res += format("0x%x", static_cast<unsigned int>(data[i]));
}
return res;
}
#ifndef WIN32
/*-------------.
| Syslog debug |
`-------------*/
SyslogDebug::SyslogDebug(const std::string& program)
{
openlog(strdup(program.c_str()), LOG_PID, LOG_DAEMON);
syslog(LOG_INFO | LOG_DAEMON, "%s",
format("Opening syslog session for '%s'", program).c_str());
}
SyslogDebug::~SyslogDebug()
{
syslog(LOG_INFO | LOG_DAEMON, "Closing syslog session.");
closelog();
}
static
int type_to_prio(Debug::types::Type t)
{
switch (t)
{
#define CASE(In, Out) \
case Debug::types::In: return Out; break
CASE(info, LOG_INFO);
CASE(warn, LOG_WARNING);
CASE(error, LOG_ERR);
#undef CASE
}
// Pacify Gcc.
libport::abort();
}
void
SyslogDebug::message(debug::category_type category,
const std::string& msg,
types::Type type,
const std::string& fun,
const std::string& file,
unsigned line)
{
std::stringstream s;
s << "[" << category_format(category) << "] ";
for (unsigned i = 0; i < debugger_data().indent; ++i)
s << " ";
// As syslog would do, don't issue the users' \n.
if (!msg.empty() && msg[msg.size() - 1] == '\n')
s.write(msg.c_str(), msg.size() - 1);
else
s << msg;
if (locations())
s << " (" << fun << ", " << file << ":" << line << ")";
int prio = type_to_prio(type) | LOG_DAEMON;
syslog(prio, "%s", s.str().c_str());
}
void
SyslogDebug::message_push(debug::category_type category,
const std::string& msg,
const std::string& fun,
const std::string& file,
unsigned line)
{
debug(msg, types::info, category, fun, file, line);
GD_INDENTATION_INC();
}
void
SyslogDebug::pop()
{
assert_gt(debugger_data().indent, 0u);
GD_INDENTATION_DEC();
}
#endif
boost::function0<Debug*> make_debugger;
namespace debug
{
void clear()
{
#if FIXME
delete debugger();
#endif
}
}
}
#endif
<commit_msg>Fix static initialization glitch.<commit_after>/*
* Copyright (C) 2008-2011, Gostai S.A.S.
*
* This software is provided "as is" without warranty of any kind,
* either expressed or implied, including but not limited to the
* implied warranties of fitness for a particular purpose.
*
* See the LICENSE file for more information.
*/
#include <iostream>
#include <boost/thread/tss.hpp>
#include <libport/cassert>
#include <libport/compiler.hh>
#include <libport/containers.hh>
#include <libport/cstdio>
#include <libport/debug.hh>
#include <libport/escape.hh>
#include <libport/fnmatch.h>
#include <libport/foreach.hh>
#include <libport/format.hh>
#include <libport/ip-semaphore.hh>
#include <libport/lockable.hh>
#include <libport/pthread.h>
#include <libport/thread-data.hh>
#include <libport/tokenizer.hh>
#include <libport/unistd.h>
#include <libport/utime.hh>
#include <libport/windows.hh>
#ifndef WIN32
# include <syslog.h>
#endif
#ifndef LIBPORT_DEBUG_DISABLE
GD_CATEGORY(Libport.Debug);
namespace libport
{
LIBPORT_API boost::function0<local_data&> debugger_data;
LIBPORT_API Debug* debugger = 0;
LIBPORT_API Debug::levels::Level Debug::filter_(levels::log);
local_data&
debugger_data_thread_local()
{
static boost::thread_specific_ptr<local_data> storage;
if (!storage.get())
storage.reset(new local_data);
return *storage;
}
local_data::local_data()
: indent(0)
{}
namespace debug
{
// Whether categories are enabled by default.
static bool default_category_state = true;
LIBPORT_API void
uninitialized_msg(const std::string& msg)
{
static bool dump =
getenv("GD_LEVEL") && libport::streq(getenv("GD_LEVEL"), "DUMP");
if (dump)
{
static bool first = true;
if (first)
{
std::cerr << "[Libport.Debug] "
<< "Uninitialized debug, fallback to stderr." << std::endl;
first = false;
}
std::cerr << "[Libport.Debug] " << msg;
if (msg.empty() || msg[msg.size() - 1] != '\n')
std::cerr << std::endl;
}
}
// Categories added so far.
ATTRIBUTE_PURE
categories_type&
categories()
{
static categories_type categories;
return categories;
}
typedef std::pair<bool, unsigned> pattern_infos_type;
typedef boost::unordered_map<category_type, pattern_infos_type>
patterns_type;
namespace
{
ATTRIBUTE_PURE
static unsigned
current_pattern()
{
static unsigned current = 0;
return current++;
}
// Patterns added so far.
ATTRIBUTE_PURE
patterns_type&
patterns()
{
static patterns_type* patterns = 0;
if (!patterns)
patterns = new patterns_type();
return *patterns;
}
// Maximum category width.
ATTRIBUTE_PURE
size_t&
categories_largest()
{
static size_t res = 0;
return res;
}
inline
bool
match(category_type globbing, category_type string)
{
return fnmatch(globbing.name_get(), string.name_get()) == 0;
}
}
/// Given a category name, see whether it should be enabled or disabled.
/// Do not store it in the list of declared categories.
static
bool
category_name_enabled(category_type name)
{
int order = -1;
bool res = default_category_state;
foreach (patterns_type::value_type& s, patterns())
if (order < int(s.second.second)
&& match(s.first, name))
{
res = s.second.first;
order = s.second.second;
}
return res;
}
// New category.
category_type
add_category(category_type name)
{
categories()[name] = category_name_enabled(name);
categories_largest() =
std::max(categories_largest(), name.name_get().size());
return name;
}
int
enable_category(category_type pattern, bool enabled)
{
patterns()[pattern] = std::make_pair(enabled, current_pattern());
foreach (categories_type::value_type& s, categories())
if (match(pattern, s.first))
s.second = enabled;
return 42;
}
int
disable_category(category_type pattern)
{
return enable_category(pattern, false);
}
// Enable/Disable a new category pattern with modifier.
static int
auto_category(category_type pattern)
{
std::string p = pattern.name_get();
char modifier = p[0];
if (modifier == '+' || modifier == '-')
p = p.substr(1);
else
modifier = '+';
return enable_category(category_type(p), modifier == '+');
}
bool test_category(category_type name)
{
return
libport::has(categories(), name)
? categories()[name]
: category_name_enabled(name);
}
void
set_categories_state(const std::string& specs,
const category_modifier_type state)
{
// If the mode is "AUTO", then if the first specs is to enable
// ("-...") then the default is to enable, otherwise disable.
// If the mode if not AUTO, then the default is the converse of
// the mode: ENABLE -> false, and DISABLE => true.
default_category_state =
state == AUTO
? (!specs.empty() && specs[0] == '-')
: (state != ENABLE);
// Set all the existing categories to the default behavior
// before running the per-pattern tests.
foreach (categories_type::value_type& v, categories())
v.second = default_category_state;
foreach (const std::string& elem, make_tokenizer(specs, ","))
switch (state)
{
case ENABLE:
case DISABLE:
enable_category(category_type(elem), state == ENABLE);
break;
case AUTO:
auto_category(category_type(elem));
break;
}
}
}
Debug::Debug()
: locations_(getenv("GD_LOC"))
, timestamps_(getenv("GD_TIME") || getenv("GD_TIMESTAMP_US"))
{
// Process enabled/disabled/auto categories in environment.
if (const char* cp = getenv("GD_CATEGORY"))
debug::set_categories_state(cp, debug::AUTO);
else
{
if (const char* cp = getenv("GD_ENABLE_CATEGORY"))
debug::set_categories_state(cp, debug::ENABLE);
if (const char* cp = getenv("GD_DISABLE_CATEGORY"))
debug::set_categories_state(cp, debug::DISABLE);
}
if (const char* lvl_c = getenv("GD_LEVEL"))
filter(lvl_c);
}
Debug::~Debug()
{}
void
Debug::filter(levels::Level lvl)
{
filter_ = lvl;
}
void
Debug::filter(const std::string& lvl)
{
if (lvl == "NONE" || lvl == "0")
filter(Debug::levels::none);
else if (lvl == "LOG" || lvl == "1")
filter(Debug::levels::log);
else if (lvl == "TRACE" || lvl == "2")
filter(Debug::levels::trace);
else if (lvl == "DEBUG" || lvl == "3")
filter(Debug::levels::debug);
else if (lvl == "DUMP" || lvl == "4")
filter(Debug::levels::dump);
else
// Don't use GD_ABORT here, we can be in the debugger constructor!
pabort("invalid debug level (NONE, LOG, TRACE, DEBUG, DUMP or [0-4])");
}
unsigned
Debug::indentation() const
{
return debugger_data().indent;
}
Debug::levels::Level
Debug::level()
{
return filter_;
}
# ifdef LIBPORT_HAVE_IP_SEMAPHORE
static IPSemaphore& sem()
{
static IPSemaphore res(1);
return res;
}
# endif
void
Debug::debug(const std::string& msg,
types::Type type,
debug::category_type category,
const std::string& fun,
const std::string& file,
unsigned line)
{
# ifdef LIBPORT_HAVE_IP_SEMAPHORE
static bool useLock = getenv("GD_USE_LOCK") || getenv("GD_PID");
libport::Finally f;
if (useLock)
{
--sem();
f << boost::bind(&IPSemaphore::operator++, boost::ref(sem()));
}
# endif
message(category, msg, type, fun, file, line);
}
Debug*
Debug::push(debug::category_type category,
const std::string& msg,
const std::string& fun,
const std::string& file,
unsigned line)
{
message_push(category, msg, fun, file, line);
return this;
}
std::string
Debug::category_format(debug::category_type cat) const
{
std::string res = cat;
size_t size = res.size();
size_t largest = debug::categories_largest();
if (size < largest)
{
size_t diff = largest - size;
res = std::string(diff / 2, ' ')
+ res
+ std::string(diff / 2 + diff % 2, ' ');
}
return res;
}
namespace opts
{
void cb_debug_fun(const std::string& lvl)
{
GD_DEBUGGER->filter(lvl);
}
OptionValued::callback_type cb_debug(cb_debug_fun);
OptionValue
debug("set log verbosity (NONE, LOG, TRACE, DEBUG, DUMP) [LOG]",
"debug", 'd', "LEVEL", cb_debug);
}
ConsoleDebug::ConsoleDebug()
{}
namespace
{
inline
std::string
time()
{
static bool us = getenv("GD_TIMESTAMP_US");
if (us)
return string_cast(utime());
time_t now = std::time(0);
struct tm* ts = std::localtime(&now);
char buf[80];
strftime(buf, sizeof buf, "%a %Y-%m-%d %H:%M:%S %Z", ts);
return buf;
}
inline
std::string
color(int color, bool bold = true)
{
static bool tty = isatty(STDERR_FILENO);
static bool force = getenv("GD_COLOR");
static bool force_disable = getenv("GD_NO_COLOR");
return (((tty || force) && !force_disable)
? format("[33;0%s;%sm", bold ? 1 : 0, color)
: "");
}
}
static Debug::colors::Color
msg_color(Debug::types::Type type)
{
switch (type)
{
case Debug::types::info:
return Debug::colors::white;
case Debug::types::warn:
return Debug::colors::yellow;
case Debug::types::error:
return Debug::colors::red;
};
GD_UNREACHABLE();
}
void
ConsoleDebug::message(debug::category_type category,
const std::string& msg,
types::Type type,
const std::string& fun,
const std::string& file,
unsigned line)
{
std::ostringstream ostr;
Debug::colors::Color c = msg_color(type);
if (timestamps())
ostr << color(c) << time() << " ";
ostr << color(colors::purple)
<< "[" << category_format(category) << "] ";
{
static bool pid = getenv("GD_PID");
if (pid)
ostr << "[" << getpid() << "] ";
}
#ifndef WIN32
{
static bool thread = getenv("GD_THREAD");
if (thread)
ostr << "[" << pthread_self() << "] ";
}
#endif
ostr << color(c);
for (unsigned i = 0; i < debugger_data().indent; ++i)
ostr << " ";
// As syslog would do, don't issue the users' \n.
if (!msg.empty() && msg[msg.size() - 1] == '\n')
ostr.write(msg.c_str(), msg.size() - 1);
else
ostr << msg;
if (locations())
ostr << color(colors::blue)
<< " (" << fun << ", " << file << ":" << line << ")";
ostr << color(colors::white);
std::cerr << ostr.str() << std::endl;
}
void
ConsoleDebug::message_push(debug::category_type category,
const std::string& msg,
const std::string& fun,
const std::string& file,
unsigned line)
{
debug(msg, types::info, category, fun, file, line);
GD_INDENTATION_INC();
}
void
ConsoleDebug::pop()
{
assert_gt(debugger_data().indent, 0u);
GD_INDENTATION_DEC();
}
std::string gd_ihexdump(const unsigned char* data, unsigned size)
{
std::string res =
format("\"%s\"",
libport::escape(std::string((const char*)data, (size_t)(size))));
bool first = true;
for (unsigned i = 0; i < size; ++i)
{
if (first)
first = false;
else
res += " ";
// Cast to int, or boost::format will print the character.
res += format("0x%x", static_cast<unsigned int>(data[i]));
}
return res;
}
#ifndef WIN32
/*-------------.
| Syslog debug |
`-------------*/
SyslogDebug::SyslogDebug(const std::string& program)
{
openlog(strdup(program.c_str()), LOG_PID, LOG_DAEMON);
syslog(LOG_INFO | LOG_DAEMON, "%s",
format("Opening syslog session for '%s'", program).c_str());
}
SyslogDebug::~SyslogDebug()
{
syslog(LOG_INFO | LOG_DAEMON, "Closing syslog session.");
closelog();
}
static
int type_to_prio(Debug::types::Type t)
{
switch (t)
{
#define CASE(In, Out) \
case Debug::types::In: return Out; break
CASE(info, LOG_INFO);
CASE(warn, LOG_WARNING);
CASE(error, LOG_ERR);
#undef CASE
}
// Pacify Gcc.
libport::abort();
}
void
SyslogDebug::message(debug::category_type category,
const std::string& msg,
types::Type type,
const std::string& fun,
const std::string& file,
unsigned line)
{
std::stringstream s;
s << "[" << category_format(category) << "] ";
for (unsigned i = 0; i < debugger_data().indent; ++i)
s << " ";
// As syslog would do, don't issue the users' \n.
if (!msg.empty() && msg[msg.size() - 1] == '\n')
s.write(msg.c_str(), msg.size() - 1);
else
s << msg;
if (locations())
s << " (" << fun << ", " << file << ":" << line << ")";
int prio = type_to_prio(type) | LOG_DAEMON;
syslog(prio, "%s", s.str().c_str());
}
void
SyslogDebug::message_push(debug::category_type category,
const std::string& msg,
const std::string& fun,
const std::string& file,
unsigned line)
{
debug(msg, types::info, category, fun, file, line);
GD_INDENTATION_INC();
}
void
SyslogDebug::pop()
{
assert_gt(debugger_data().indent, 0u);
GD_INDENTATION_DEC();
}
#endif
boost::function0<Debug*> make_debugger;
namespace debug
{
void clear()
{
#if FIXME
delete debugger();
#endif
}
}
}
#endif
<|endoftext|> |
<commit_before>#include "../include/rice.hpp"
namespace rice {
RiceDecoder::RiceDecoder(const data::RiceEncodedData& encodedData)
: input(encodedData.encodedData)
, dataCount(encodedData.dataCount)
, optimumRiceParam(encodedData.optimumRiceParam)
{
}
inline void RiceDecoder::generateEncodedBits()
{
bitInput.reserve(input.size() * 32);
for (uint64_t x : input) {
for (uint64_t j = 0; j < 32; j++) {
bitInput.push_back((bool)(x >> j & 0x1));
}
}
}
inline void RiceDecoder::generateDecodedUnsignedInts()
{
uint32_t count = 0;
uint32_t temp = 0;
uint32_t i = 0;
uint32_t bitReadCounter = 0;
unsignedOutput.reserve(dataCount);
while (count < dataCount) {
// Count 1s until a zero is encountered
temp = 0;
while (bitInput[bitReadCounter] == 1) {
temp++;
bitReadCounter++;
}
bitReadCounter++;
unsignedOutput.push_back(temp << optimumRiceParam);
// Read the last 'optimumRiceParam' number of bits and add them to output
for (i = 1; i < (optimumRiceParam + 1); i++) {
unsignedOutput[count] = unsignedOutput[count] | ((long)bitInput[bitReadCounter] << (optimumRiceParam - i));
bitReadCounter++;
}
count++;
}
}
inline void RiceDecoder::convertUnsignedToSigned(std::vector<int32_t>& output)
{
output.reserve(dataCount);
for (uint64_t x : unsignedOutput) {
output.push_back(
(int32_t)(((x & 0x01) == 0x01) ? -(int64_t)((x + 1) >> 1) : (x >> 1)));
}
}
data::RiceDecodedData RiceDecoder::process()
{
std::vector<int32_t> output;
generateEncodedBits();
generateDecodedUnsignedInts();
convertUnsignedToSigned(output);
return data::RiceDecodedData(std::move(output));
}
}
<commit_msg>Lint fixes<commit_after>#include "../include/rice.hpp"
namespace rice {
RiceDecoder::RiceDecoder(const data::RiceEncodedData& encodedData)
: input(encodedData.encodedData)
, dataCount(encodedData.dataCount)
, optimumRiceParam(encodedData.optimumRiceParam)
{
}
inline void RiceDecoder::generateEncodedBits()
{
bitInput.reserve(input.size() * 32);
for (uint64_t x : input) {
for (uint64_t j = 0; j < 32; j++) {
bitInput.push_back((bool)(x >> j & 0x1));
}
}
}
inline void RiceDecoder::generateDecodedUnsignedInts()
{
uint32_t count = 0;
uint32_t temp = 0;
uint32_t i = 0;
uint32_t bitReadCounter = 0;
unsignedOutput.reserve(dataCount);
while (count < dataCount) {
// Count 1s until a zero is encountered
temp = 0;
while (bitInput[bitReadCounter] == 1) {
temp++;
bitReadCounter++;
}
bitReadCounter++;
unsignedOutput.push_back(temp << optimumRiceParam);
// Read the last 'optimumRiceParam' number of bits and add them to output
for (i = 1; i < (optimumRiceParam + 1); i++) {
unsignedOutput[count] = unsignedOutput[count] | ((long)bitInput[bitReadCounter] << (optimumRiceParam - i));
bitReadCounter++;
}
count++;
}
}
inline void RiceDecoder::convertUnsignedToSigned(std::vector<int32_t>& output)
{
output.reserve(dataCount);
for (uint64_t x : unsignedOutput) {
output.push_back((int32_t)(((x & 0x01) == 0x01) ? -(int64_t)((x + 1) >> 1) : (x >> 1)));
}
}
data::RiceDecodedData RiceDecoder::process()
{
std::vector<int32_t> output;
generateEncodedBits();
generateDecodedUnsignedInts();
convertUnsignedToSigned(output);
return data::RiceDecodedData(std::move(output));
}
}
<|endoftext|> |
<commit_before><commit_msg>[TD]multiple faces in GeomHatch<commit_after><|endoftext|> |
<commit_before>/*
* Copyright 2014-present Facebook, 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 <thrift/lib/cpp2/async/RequestChannel.h>
#include <folly/fibers/Baton.h>
#include <folly/fibers/Fiber.h>
namespace apache {
namespace thrift {
void RequestChannel::sendRequestAsync(
apache::thrift::RpcOptions& rpcOptions,
std::unique_ptr<apache::thrift::RequestCallback> callback,
std::unique_ptr<apache::thrift::ContextStack> ctx,
std::unique_ptr<folly::IOBuf> buf,
std::shared_ptr<apache::thrift::transport::THeader> header,
RpcKind kind) {
auto eb = getEventBase();
if (!eb || eb->isInEventBaseThread()) {
switch (kind) {
case RpcKind::SINGLE_REQUEST_NO_RESPONSE:
// Calling asyncComplete before sending because
// sendOnewayRequest moves from ctx and clears it.
ctx->asyncComplete();
sendOnewayRequest(
rpcOptions,
std::move(callback),
std::move(ctx),
std::move(buf),
std::move(header));
break;
case RpcKind::SINGLE_REQUEST_SINGLE_RESPONSE:
sendRequest(
rpcOptions,
std::move(callback),
std::move(ctx),
std::move(buf),
std::move(header));
break;
case RpcKind::SINGLE_REQUEST_STREAMING_RESPONSE:
sendStreamRequest(
rpcOptions,
std::move(callback),
std::move(ctx),
std::move(buf),
std::move(header));
break;
default:
folly::assume_unreachable();
break;
}
} else {
switch (kind) {
case RpcKind::SINGLE_REQUEST_NO_RESPONSE:
eb->runInEventBaseThread([this,
rpcOptions,
callback = std::move(callback),
ctx = std::move(ctx),
buf = std::move(buf),
header = std::move(header)]() mutable {
// Calling asyncComplete before sending because
// sendOnewayRequest moves from ctx and clears it.
ctx->asyncComplete();
sendOnewayRequest(
rpcOptions,
std::move(callback),
std::move(ctx),
std::move(buf),
std::move(header));
});
break;
case RpcKind::SINGLE_REQUEST_SINGLE_RESPONSE:
eb->runInEventBaseThread([this,
rpcOptions,
callback = std::move(callback),
ctx = std::move(ctx),
buf = std::move(buf),
header = std::move(header)]() mutable {
sendRequest(
rpcOptions,
std::move(callback),
std::move(ctx),
std::move(buf),
std::move(header));
});
break;
case RpcKind::SINGLE_REQUEST_STREAMING_RESPONSE:
eb->runInEventBaseThread([this,
rpcOptions,
callback = std::move(callback),
ctx = std::move(ctx),
buf = std::move(buf),
header = std::move(header)]() mutable {
sendStreamRequest(
rpcOptions,
std::move(callback),
std::move(ctx),
std::move(buf),
std::move(header));
});
break;
default:
folly::assume_unreachable();
break;
}
}
}
namespace {
class ClientSyncBatonCallback final : public RequestCallback {
public:
ClientSyncBatonCallback(
std::unique_ptr<RequestCallback> cb,
folly::fibers::Baton& doneBaton,
RpcKind kind)
: cb_(std::move(cb)), doneBaton_(doneBaton), kind_(kind) {}
void requestSent() override {
cb_->requestSent();
if (kind_ == RpcKind::SINGLE_REQUEST_NO_RESPONSE) {
doneBaton_.post();
}
}
void replyReceived(ClientReceiveState&& rs) override {
cb_->replyReceived(std::move(rs));
doneBaton_.post();
}
void requestError(ClientReceiveState&& rs) override {
assert(rs.isException());
cb_->requestError(std::move(rs));
doneBaton_.post();
}
private:
std::unique_ptr<RequestCallback> cb_;
folly::fibers::Baton& doneBaton_;
RpcKind kind_;
};
} // namespace
void RequestChannel::sendRequestSync(
RpcOptions& options,
std::unique_ptr<RequestCallback> cb,
std::unique_ptr<apache::thrift::ContextStack> ctx,
std::unique_ptr<folly::IOBuf> buf,
std::shared_ptr<apache::thrift::transport::THeader> header,
RpcKind kind) {
auto eb = getEventBase();
// We intentionally only support sync_* calls from the EventBase thread.
eb->checkIsInEventBaseThread();
folly::fibers::Baton baton;
auto scb =
std::make_unique<ClientSyncBatonCallback>(std::move(cb), baton, kind);
folly::exception_wrapper ew;
baton.wait([&, onFiber = folly::fibers::onFiber()]() {
try {
switch (kind) {
case RpcKind::SINGLE_REQUEST_NO_RESPONSE:
sendOnewayRequest(
options,
std::move(scb),
std::move(ctx),
std::move(buf),
std::move(header));
break;
case RpcKind::SINGLE_REQUEST_SINGLE_RESPONSE:
sendRequest(
options,
std::move(scb),
std::move(ctx),
std::move(buf),
std::move(header));
break;
case RpcKind::SINGLE_REQUEST_STREAMING_RESPONSE:
sendStreamRequest(
options,
std::move(scb),
std::move(ctx),
std::move(buf),
std::move(header));
break;
default:
folly::assume_unreachable();
}
} catch (const std::exception& e) {
ew = folly::exception_wrapper(std::current_exception(), e);
baton.post();
} catch (...) {
ew = folly::exception_wrapper(std::current_exception());
baton.post();
}
if (!onFiber) {
while (!baton.ready()) {
eb->drive();
}
}
});
if (ew) {
ew.throw_exception();
}
}
uint32_t RequestChannel::sendStreamRequest(
RpcOptions&,
std::unique_ptr<RequestCallback> cb,
std::unique_ptr<apache::thrift::ContextStack> ctx,
std::unique_ptr<folly::IOBuf>,
std::shared_ptr<apache::thrift::transport::THeader>) {
cb->requestError(ClientReceiveState(
folly::make_exception_wrapper<transport::TTransportException>(
"Current channel doesn't support stream RPC"),
std::move(ctx)));
return 0;
}
} // namespace thrift
} // namespace apache
<commit_msg>Make RequestChannel::sendRequestSync work when not in running event base thread<commit_after>/*
* Copyright 2014-present Facebook, 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 <thrift/lib/cpp2/async/RequestChannel.h>
#include <folly/fibers/Baton.h>
#include <folly/fibers/Fiber.h>
namespace apache {
namespace thrift {
void RequestChannel::sendRequestAsync(
apache::thrift::RpcOptions& rpcOptions,
std::unique_ptr<apache::thrift::RequestCallback> callback,
std::unique_ptr<apache::thrift::ContextStack> ctx,
std::unique_ptr<folly::IOBuf> buf,
std::shared_ptr<apache::thrift::transport::THeader> header,
RpcKind kind) {
auto eb = getEventBase();
if (!eb || eb->isInEventBaseThread()) {
switch (kind) {
case RpcKind::SINGLE_REQUEST_NO_RESPONSE:
// Calling asyncComplete before sending because
// sendOnewayRequest moves from ctx and clears it.
ctx->asyncComplete();
sendOnewayRequest(
rpcOptions,
std::move(callback),
std::move(ctx),
std::move(buf),
std::move(header));
break;
case RpcKind::SINGLE_REQUEST_SINGLE_RESPONSE:
sendRequest(
rpcOptions,
std::move(callback),
std::move(ctx),
std::move(buf),
std::move(header));
break;
case RpcKind::SINGLE_REQUEST_STREAMING_RESPONSE:
sendStreamRequest(
rpcOptions,
std::move(callback),
std::move(ctx),
std::move(buf),
std::move(header));
break;
default:
folly::assume_unreachable();
break;
}
} else {
switch (kind) {
case RpcKind::SINGLE_REQUEST_NO_RESPONSE:
eb->runInEventBaseThread([this,
rpcOptions,
callback = std::move(callback),
ctx = std::move(ctx),
buf = std::move(buf),
header = std::move(header)]() mutable {
// Calling asyncComplete before sending because
// sendOnewayRequest moves from ctx and clears it.
ctx->asyncComplete();
sendOnewayRequest(
rpcOptions,
std::move(callback),
std::move(ctx),
std::move(buf),
std::move(header));
});
break;
case RpcKind::SINGLE_REQUEST_SINGLE_RESPONSE:
eb->runInEventBaseThread([this,
rpcOptions,
callback = std::move(callback),
ctx = std::move(ctx),
buf = std::move(buf),
header = std::move(header)]() mutable {
sendRequest(
rpcOptions,
std::move(callback),
std::move(ctx),
std::move(buf),
std::move(header));
});
break;
case RpcKind::SINGLE_REQUEST_STREAMING_RESPONSE:
eb->runInEventBaseThread([this,
rpcOptions,
callback = std::move(callback),
ctx = std::move(ctx),
buf = std::move(buf),
header = std::move(header)]() mutable {
sendStreamRequest(
rpcOptions,
std::move(callback),
std::move(ctx),
std::move(buf),
std::move(header));
});
break;
default:
folly::assume_unreachable();
break;
}
}
}
namespace {
class ClientSyncBatonCallback final : public RequestCallback {
public:
ClientSyncBatonCallback(
std::unique_ptr<RequestCallback> cb,
folly::fibers::Baton& doneBaton,
RpcKind kind)
: cb_(std::move(cb)), doneBaton_(doneBaton), kind_(kind) {}
void requestSent() override {
cb_->requestSent();
if (kind_ == RpcKind::SINGLE_REQUEST_NO_RESPONSE) {
doneBaton_.post();
}
}
void replyReceived(ClientReceiveState&& rs) override {
cb_->replyReceived(std::move(rs));
doneBaton_.post();
}
void requestError(ClientReceiveState&& rs) override {
assert(rs.isException());
cb_->requestError(std::move(rs));
doneBaton_.post();
}
private:
std::unique_ptr<RequestCallback> cb_;
folly::fibers::Baton& doneBaton_;
RpcKind kind_;
};
} // namespace
void RequestChannel::sendRequestSync(
RpcOptions& options,
std::unique_ptr<RequestCallback> cb,
std::unique_ptr<apache::thrift::ContextStack> ctx,
std::unique_ptr<folly::IOBuf> buf,
std::shared_ptr<apache::thrift::transport::THeader> header,
RpcKind kind) {
auto eb = getEventBase();
// We intentionally only support sync_* calls from the EventBase thread.
eb->checkIsInEventBaseThread();
folly::fibers::Baton baton;
auto scb =
std::make_unique<ClientSyncBatonCallback>(std::move(cb), baton, kind);
folly::exception_wrapper ew;
auto const onFiber = folly::fibers::onFiber();
auto const inEventBase = eb->inRunningEventBaseThread();
baton.wait([&, onFiber, inEventBase] {
try {
switch (kind) {
case RpcKind::SINGLE_REQUEST_NO_RESPONSE:
sendOnewayRequest(
options,
std::move(scb),
std::move(ctx),
std::move(buf),
std::move(header));
break;
case RpcKind::SINGLE_REQUEST_SINGLE_RESPONSE:
sendRequest(
options,
std::move(scb),
std::move(ctx),
std::move(buf),
std::move(header));
break;
case RpcKind::SINGLE_REQUEST_STREAMING_RESPONSE:
sendStreamRequest(
options,
std::move(scb),
std::move(ctx),
std::move(buf),
std::move(header));
break;
default:
folly::assume_unreachable();
}
} catch (const std::exception& e) {
ew = folly::exception_wrapper(std::current_exception(), e);
baton.post();
} catch (...) {
ew = folly::exception_wrapper(std::current_exception());
baton.post();
}
if (!onFiber || !inEventBase) {
while (!baton.ready()) {
eb->drive();
}
}
});
if (ew) {
ew.throw_exception();
}
}
uint32_t RequestChannel::sendStreamRequest(
RpcOptions&,
std::unique_ptr<RequestCallback> cb,
std::unique_ptr<apache::thrift::ContextStack> ctx,
std::unique_ptr<folly::IOBuf>,
std::shared_ptr<apache::thrift::transport::THeader>) {
cb->requestError(ClientReceiveState(
folly::make_exception_wrapper<transport::TTransportException>(
"Current channel doesn't support stream RPC"),
std::move(ctx)));
return 0;
}
} // namespace thrift
} // namespace apache
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <fstream>
#include <set>
#include <sstream>
#include <string>
#include "perfetto/ext/base/file_utils.h"
#include "src/traced/probes/ftrace/ftrace_controller.h"
#include "src/traced/probes/ftrace/ftrace_procfs.h"
#include "test/gtest_and_gmock.h"
using testing::Contains;
using testing::HasSubstr;
using testing::IsEmpty;
using testing::Not;
using testing::UnorderedElementsAre;
namespace perfetto {
namespace {
std::string GetFtracePath() {
size_t i = 0;
while (!FtraceProcfs::Create(FtraceController::kTracingPaths[i])) {
i++;
}
return std::string(FtraceController::kTracingPaths[i]);
}
void ResetFtrace(FtraceProcfs* ftrace) {
ftrace->DisableAllEvents();
ftrace->ClearTrace();
ftrace->EnableTracing();
}
std::string ReadFile(const std::string& name) {
std::string result;
PERFETTO_CHECK(base::ReadFile(GetFtracePath() + name, &result));
return result;
}
std::string GetTraceOutput() {
std::string output = ReadFile("trace");
if (output.empty()) {
ADD_FAILURE() << "Could not read trace output";
}
return output;
}
} // namespace
// TODO(lalitm): reenable these tests (see b/72306171).
#if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
#define MAYBE_CreateWithGoodPath CreateWithGoodPath
#else
#define MAYBE_CreateWithGoodPath DISABLED_CreateWithGoodPath
#endif
TEST(FtraceProcfsIntegrationTest, MAYBE_CreateWithGoodPath) {
EXPECT_TRUE(FtraceProcfs::Create(GetFtracePath()));
}
#if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
#define MAYBE_CreateWithBadPath CreateWithBadPath
#else
#define MAYBE_CreateWithBadPath DISABLED_CreateWithBadath
#endif
TEST(FtraceProcfsIntegrationTest, MAYBE_CreateWithBadPath) {
EXPECT_FALSE(FtraceProcfs::Create(GetFtracePath() + std::string("bad_path")));
}
#if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
#define MAYBE_ClearTrace ClearTrace
#else
#define MAYBE_ClearTrace DISABLED_ClearTrace
#endif
TEST(FtraceProcfsIntegrationTest, MAYBE_ClearTrace) {
FtraceProcfs ftrace(GetFtracePath());
ResetFtrace(&ftrace);
ftrace.WriteTraceMarker("Hello, World!");
ftrace.ClearTrace();
EXPECT_THAT(GetTraceOutput(), Not(HasSubstr("Hello, World!")));
}
#if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
#define MAYBE_TraceMarker TraceMarker
#else
#define MAYBE_TraceMarker DISABLED_TraceMarker
#endif
TEST(FtraceProcfsIntegrationTest, MAYBE_TraceMarker) {
FtraceProcfs ftrace(GetFtracePath());
ResetFtrace(&ftrace);
ftrace.WriteTraceMarker("Hello, World!");
EXPECT_THAT(GetTraceOutput(), HasSubstr("Hello, World!"));
}
#if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
#define MAYBE_EnableDisableEvent EnableDisableEvent
#else
#define MAYBE_EnableDisableEvent DISABLED_EnableDisableEvent
#endif
TEST(FtraceProcfsIntegrationTest, MAYBE_EnableDisableEvent) {
FtraceProcfs ftrace(GetFtracePath());
ResetFtrace(&ftrace);
ftrace.EnableEvent("sched", "sched_switch");
sleep(1);
EXPECT_THAT(GetTraceOutput(), HasSubstr("sched_switch"));
ftrace.DisableEvent("sched", "sched_switch");
ftrace.ClearTrace();
sleep(1);
EXPECT_THAT(GetTraceOutput(), Not(HasSubstr("sched_switch")));
}
#if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
#define MAYBE_EnableDisableTracing EnableDisableTracing
#else
#define MAYBE_EnableDisableTracing DISABLED_EnableDisableTracing
#endif
TEST(FtraceProcfsIntegrationTest, MAYBE_EnableDisableTracing) {
FtraceProcfs ftrace(GetFtracePath());
ResetFtrace(&ftrace);
EXPECT_TRUE(ftrace.IsTracingEnabled());
ftrace.WriteTraceMarker("Before");
ftrace.DisableTracing();
EXPECT_FALSE(ftrace.IsTracingEnabled());
ftrace.WriteTraceMarker("During");
ftrace.EnableTracing();
EXPECT_TRUE(ftrace.IsTracingEnabled());
ftrace.WriteTraceMarker("After");
EXPECT_THAT(GetTraceOutput(), HasSubstr("Before"));
EXPECT_THAT(GetTraceOutput(), Not(HasSubstr("During")));
EXPECT_THAT(GetTraceOutput(), HasSubstr("After"));
}
#if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
#define MAYBE_ReadFormatFile ReadFormatFile
#else
#define MAYBE_ReadFormatFile DISABLED_ReadFormatFile
#endif
TEST(FtraceProcfsIntegrationTest, MAYBE_ReadFormatFile) {
FtraceProcfs ftrace(GetFtracePath());
std::string format = ftrace.ReadEventFormat("ftrace", "print");
EXPECT_THAT(format, HasSubstr("name: print"));
EXPECT_THAT(format, HasSubstr("field:char buf"));
}
#if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
#define MAYBE_CanOpenTracePipeRaw CanOpenTracePipeRaw
#else
#define MAYBE_CanOpenTracePipeRaw DISABLED_CanOpenTracePipeRaw
#endif
TEST(FtraceProcfsIntegrationTest, MAYBE_CanOpenTracePipeRaw) {
FtraceProcfs ftrace(GetFtracePath());
EXPECT_TRUE(ftrace.OpenPipeForCpu(0));
}
#if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
#define MAYBE_Clock Clock
#else
#define MAYBE_Clock DISABLED_Clock
#endif
TEST(FtraceProcfsIntegrationTest, MAYBE_Clock) {
FtraceProcfs ftrace(GetFtracePath());
std::set<std::string> clocks = ftrace.AvailableClocks();
EXPECT_THAT(clocks, Contains("local"));
EXPECT_THAT(clocks, Contains("global"));
EXPECT_TRUE(ftrace.SetClock("global"));
EXPECT_EQ(ftrace.GetClock(), "global");
EXPECT_TRUE(ftrace.SetClock("local"));
EXPECT_EQ(ftrace.GetClock(), "local");
}
#if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
#define MAYBE_CanSetBufferSize CanSetBufferSize
#else
#define MAYBE_CanSetBufferSize DISABLED_CanSetBufferSize
#endif
TEST(FtraceProcfsIntegrationTest, MAYBE_CanSetBufferSize) {
FtraceProcfs ftrace(GetFtracePath());
EXPECT_TRUE(ftrace.SetCpuBufferSizeInPages(4ul));
EXPECT_EQ(ReadFile("buffer_size_kb"), "16\n"); // (4096 * 4) / 1024
EXPECT_TRUE(ftrace.SetCpuBufferSizeInPages(5ul));
EXPECT_EQ(ReadFile("buffer_size_kb"), "20\n"); // (4096 * 5) / 1024
}
#if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
#define MAYBE_FtraceControllerHardReset FtraceControllerHardReset
#else
#define MAYBE_FtraceControllerHardReset DISABLED_FtraceControllerHardReset
#endif
TEST(FtraceProcfsIntegrationTest, MAYBE_FtraceControllerHardReset) {
FtraceProcfs ftrace(GetFtracePath());
ResetFtrace(&ftrace);
ftrace.SetCpuBufferSizeInPages(4ul);
ftrace.EnableTracing();
ftrace.EnableEvent("sched", "sched_switch");
ftrace.WriteTraceMarker("Hello, World!");
EXPECT_EQ(ReadFile("buffer_size_kb"), "16\n");
EXPECT_EQ(ReadFile("tracing_on"), "1\n");
EXPECT_EQ(ReadFile("events/enable"), "X\n");
EXPECT_THAT(GetTraceOutput(), HasSubstr("Hello"));
HardResetFtraceState();
EXPECT_EQ(ReadFile("buffer_size_kb"), "4\n");
EXPECT_EQ(ReadFile("tracing_on"), "0\n");
EXPECT_EQ(ReadFile("events/enable"), "0\n");
EXPECT_THAT(GetTraceOutput(), Not(HasSubstr("Hello")));
}
#if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
#define MAYBE_ReadEnabledEvents ReadEnabledEvents
#else
#define MAYBE_ReadEnabledEvents DISABLED_ReadEnabledEvents
#endif
TEST(FtraceProcfsIntegrationTest, MAYBE_ReadEnabledEvents) {
FtraceProcfs ftrace(GetFtracePath());
ResetFtrace(&ftrace);
EXPECT_THAT(ftrace.ReadEnabledEvents(), IsEmpty());
ftrace.EnableEvent("sched", "sched_switch");
ftrace.EnableEvent("kmem", "kmalloc");
EXPECT_THAT(ftrace.ReadEnabledEvents(),
UnorderedElementsAre("sched/sched_switch", "kmem/kmalloc"));
ftrace.DisableEvent("sched", "sched_switch");
ftrace.DisableEvent("kmem", "kmalloc");
EXPECT_THAT(ftrace.ReadEnabledEvents(), IsEmpty());
}
} // namespace perfetto
<commit_msg>Test: Improve FtraceProcfsIntegrationTest, skip if systrace is on am: 16b67309ba am: f9e65127ad<commit_after>/*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <fstream>
#include <set>
#include <sstream>
#include <string>
#include "perfetto/ext/base/file_utils.h"
#include "src/traced/probes/ftrace/ftrace_controller.h"
#include "src/traced/probes/ftrace/ftrace_procfs.h"
#include "test/gtest_and_gmock.h"
using testing::Contains;
using testing::HasSubstr;
using testing::IsEmpty;
using testing::Not;
using testing::UnorderedElementsAre;
// These tests run only on Android because on linux they require access to
// ftrace, which would be problematic in the CI when multiple tests run
// concurrently on the same machine. Android instead uses one emulator instance
// for each worker.
#if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
#define ANDROID_ONLY_TEST(x) x
#else
#define ANDROID_ONLY_TEST(x) DISABLED_##x
#endif
namespace perfetto {
namespace {
std::string GetFtracePath() {
size_t i = 0;
while (!FtraceProcfs::Create(FtraceController::kTracingPaths[i])) {
i++;
}
return std::string(FtraceController::kTracingPaths[i]);
}
std::string ReadFile(const std::string& name) {
std::string result;
PERFETTO_CHECK(base::ReadFile(GetFtracePath() + name, &result));
return result;
}
std::string GetTraceOutput() {
std::string output = ReadFile("trace");
if (output.empty()) {
ADD_FAILURE() << "Could not read trace output";
}
return output;
}
class FtraceProcfsIntegrationTest : public testing::Test {
public:
void SetUp() override;
void TearDown() override;
std::unique_ptr<FtraceProcfs> ftrace_;
};
void FtraceProcfsIntegrationTest::SetUp() {
ftrace_ = FtraceProcfs::Create(GetFtracePath());
ASSERT_TRUE(ftrace_);
if (ftrace_->IsTracingEnabled()) {
GTEST_SKIP() << "Something else is using ftrace, skipping";
}
ftrace_->DisableAllEvents();
ftrace_->ClearTrace();
ftrace_->EnableTracing();
}
void FtraceProcfsIntegrationTest::TearDown() {
ftrace_->DisableAllEvents();
ftrace_->ClearTrace();
ftrace_->DisableTracing();
}
TEST_F(FtraceProcfsIntegrationTest, ANDROID_ONLY_TEST(CreateWithBadPath)) {
EXPECT_FALSE(FtraceProcfs::Create(GetFtracePath() + std::string("bad_path")));
}
TEST_F(FtraceProcfsIntegrationTest, ANDROID_ONLY_TEST(ClearTrace)) {
ftrace_->WriteTraceMarker("Hello, World!");
ftrace_->ClearTrace();
EXPECT_THAT(GetTraceOutput(), Not(HasSubstr("Hello, World!")));
}
TEST_F(FtraceProcfsIntegrationTest, ANDROID_ONLY_TEST(TraceMarker)) {
ftrace_->WriteTraceMarker("Hello, World!");
EXPECT_THAT(GetTraceOutput(), HasSubstr("Hello, World!"));
}
TEST_F(FtraceProcfsIntegrationTest, ANDROID_ONLY_TEST(EnableDisableEvent)) {
ftrace_->EnableEvent("sched", "sched_switch");
sleep(1);
EXPECT_THAT(GetTraceOutput(), HasSubstr("sched_switch"));
ftrace_->DisableEvent("sched", "sched_switch");
ftrace_->ClearTrace();
sleep(1);
EXPECT_THAT(GetTraceOutput(), Not(HasSubstr("sched_switch")));
}
TEST_F(FtraceProcfsIntegrationTest, ANDROID_ONLY_TEST(EnableDisableTracing)) {
EXPECT_TRUE(ftrace_->IsTracingEnabled());
ftrace_->WriteTraceMarker("Before");
ftrace_->DisableTracing();
EXPECT_FALSE(ftrace_->IsTracingEnabled());
ftrace_->WriteTraceMarker("During");
ftrace_->EnableTracing();
EXPECT_TRUE(ftrace_->IsTracingEnabled());
ftrace_->WriteTraceMarker("After");
EXPECT_THAT(GetTraceOutput(), HasSubstr("Before"));
EXPECT_THAT(GetTraceOutput(), Not(HasSubstr("During")));
EXPECT_THAT(GetTraceOutput(), HasSubstr("After"));
}
TEST_F(FtraceProcfsIntegrationTest, ANDROID_ONLY_TEST(ReadFormatFile)) {
std::string format = ftrace_->ReadEventFormat("ftrace", "print");
EXPECT_THAT(format, HasSubstr("name: print"));
EXPECT_THAT(format, HasSubstr("field:char buf"));
}
TEST_F(FtraceProcfsIntegrationTest, ANDROID_ONLY_TEST(CanOpenTracePipeRaw)) {
EXPECT_TRUE(ftrace_->OpenPipeForCpu(0));
}
TEST_F(FtraceProcfsIntegrationTest, ANDROID_ONLY_TEST(Clock)) {
std::set<std::string> clocks = ftrace_->AvailableClocks();
EXPECT_THAT(clocks, Contains("local"));
EXPECT_THAT(clocks, Contains("global"));
EXPECT_TRUE(ftrace_->SetClock("global"));
EXPECT_EQ(ftrace_->GetClock(), "global");
EXPECT_TRUE(ftrace_->SetClock("local"));
EXPECT_EQ(ftrace_->GetClock(), "local");
}
TEST_F(FtraceProcfsIntegrationTest, ANDROID_ONLY_TEST(CanSetBufferSize)) {
EXPECT_TRUE(ftrace_->SetCpuBufferSizeInPages(4ul));
EXPECT_EQ(ReadFile("buffer_size_kb"), "16\n"); // (4096 * 4) / 1024
EXPECT_TRUE(ftrace_->SetCpuBufferSizeInPages(5ul));
EXPECT_EQ(ReadFile("buffer_size_kb"), "20\n"); // (4096 * 5) / 1024
}
TEST_F(FtraceProcfsIntegrationTest,
ANDROID_ONLY_TEST(FtraceControllerHardReset)) {
ftrace_->SetCpuBufferSizeInPages(4ul);
ftrace_->EnableTracing();
ftrace_->EnableEvent("sched", "sched_switch");
ftrace_->WriteTraceMarker("Hello, World!");
EXPECT_EQ(ReadFile("buffer_size_kb"), "16\n");
EXPECT_EQ(ReadFile("tracing_on"), "1\n");
EXPECT_EQ(ReadFile("events/enable"), "X\n");
EXPECT_THAT(GetTraceOutput(), HasSubstr("Hello"));
HardResetFtraceState();
EXPECT_EQ(ReadFile("buffer_size_kb"), "4\n");
EXPECT_EQ(ReadFile("tracing_on"), "0\n");
EXPECT_EQ(ReadFile("events/enable"), "0\n");
EXPECT_THAT(GetTraceOutput(), Not(HasSubstr("Hello")));
}
TEST_F(FtraceProcfsIntegrationTest, ANDROID_ONLY_TEST(ReadEnabledEvents)) {
EXPECT_THAT(ftrace_->ReadEnabledEvents(), IsEmpty());
ftrace_->EnableEvent("sched", "sched_switch");
ftrace_->EnableEvent("kmem", "kmalloc");
EXPECT_THAT(ftrace_->ReadEnabledEvents(),
UnorderedElementsAre("sched/sched_switch", "kmem/kmalloc"));
ftrace_->DisableEvent("sched", "sched_switch");
ftrace_->DisableEvent("kmem", "kmalloc");
EXPECT_THAT(ftrace_->ReadEnabledEvents(), IsEmpty());
}
} // namespace
} // namespace perfetto
<|endoftext|> |
<commit_before>/* Luwra
* Minimal-overhead Lua wrapper for C++
*
* Copyright (C) 2015, Ole Krüger <[email protected]>
*/
#ifndef LUWRA_COMMON_H_
#define LUWRA_COMMON_H_
extern "C" {
#include <lua.h>
#include <lualib.h>
#include <lauxlib.h>
}
// Check for proper Lua version
#if !defined(LUA_VERSION_NUM) || LUA_VERSION_NUM < 501 || LUA_VERSION_NUM >= 600
#error Luwra has not been tested against your installed version of Lua
#endif
// Namespaces
#define LUWRA_NS_BEGIN namespace luwra {
#define LUWRA_NS_END }
// Version MAJOR.MINOR.PATCH
#define LUWRA_VERSION_MAJOR 0
#define LUWRA_VERSION_MINOR 4
#define LUWRA_VERSION_PATCH 1
// LUA_OK does not exist in Lua 5.1 and earlier
#ifndef LUA_OK
#define LUA_OK 0
#endif
// Because VS C++
#ifdef _MSC_VER
#define __LUWRA_NS_RESOLVE(a, b) a::##b
#else
#define __LUWRA_NS_RESOLVE(a, b) a::b
#endif
LUWRA_NS_BEGIN
// Lua aliases
using Integer = lua_Integer;
using Number = lua_Number;
using State = lua_State;
using CFunction = lua_CFunction;
LUWRA_NS_END
#endif
<commit_msg>Bump version to 0.4.2<commit_after>/* Luwra
* Minimal-overhead Lua wrapper for C++
*
* Copyright (C) 2015, Ole Krüger <[email protected]>
*/
#ifndef LUWRA_COMMON_H_
#define LUWRA_COMMON_H_
extern "C" {
#include <lua.h>
#include <lualib.h>
#include <lauxlib.h>
}
// Check for proper Lua version
#if !defined(LUA_VERSION_NUM) || LUA_VERSION_NUM < 501 || LUA_VERSION_NUM >= 600
#error Luwra has not been tested against your installed version of Lua
#endif
// Namespaces
#define LUWRA_NS_BEGIN namespace luwra {
#define LUWRA_NS_END }
// Version MAJOR.MINOR.PATCH
#define LUWRA_VERSION_MAJOR 0
#define LUWRA_VERSION_MINOR 4
#define LUWRA_VERSION_PATCH 2
// LUA_OK does not exist in Lua 5.1 and earlier
#ifndef LUA_OK
#define LUA_OK 0
#endif
// Because VS C++
#ifdef _MSC_VER
#define __LUWRA_NS_RESOLVE(a, b) a::##b
#else
#define __LUWRA_NS_RESOLVE(a, b) a::b
#endif
LUWRA_NS_BEGIN
// Lua aliases
using Integer = lua_Integer;
using Number = lua_Number;
using State = lua_State;
using CFunction = lua_CFunction;
LUWRA_NS_END
#endif
<|endoftext|> |
<commit_before>// Copyright (c) 2014-2015 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/ColinH/PEGTL/
#ifndef PEGTL_INTERNAL_RULE_MATCH_TWO_HH
#define PEGTL_INTERNAL_RULE_MATCH_TWO_HH
#include <cstdlib>
#include "../apply_mode.hh"
#include "apply_here.hh"
#include "rule_match_three.hh"
namespace pegtl
{
namespace internal
{
template< typename Rule, apply_mode A, template< typename ... > class Action, template< typename ... > class Control, apply_here H > struct rule_match_two;
template< typename Rule, apply_mode A, template< typename ... > class Action, template< typename ... > class Control >
struct rule_match_two< Rule, A, Action, Control, apply_here::NOTHING >
{
template< typename Input, typename ... States >
static bool match( Input & in, States && ... st )
{
Control< Rule >::start( static_cast< const Input & >( in ), st ... );
if ( rule_match_three< Rule, A, Action, Control >::match( in, st ... ) ) {
Control< Rule >::success( static_cast< const Input & >( in ), st ... );
return true;
}
Control< Rule >::failure( static_cast< const Input & >( in ), st ... );
return false;
}
};
template< typename Rule, apply_mode A, template< typename ... > class Action, template< typename ... > class Control >
struct rule_match_two< Rule, A, Action, Control, apply_here::ACTION >
{
template< typename Input, typename ... States >
static bool match( Input & in, States && ... st )
{
auto m = in.mark();
Control< Rule >::start( static_cast< const Input & >( in ), st ... );
if ( rule_match_three< Rule, A, Action, Control >::match( in, st ... ) ) {
Control< Rule >::success( static_cast< const Input & >( in ), st ... );
Action< Rule >::apply( Input( m ), st ... );
return m( true );
}
Control< Rule >::failure( static_cast< const Input & >( in ), st ... );
return false;
}
};
} // internal
} // pegtl
#endif
<commit_msg>Simplified, reduce ACTION to NOTHING case<commit_after>// Copyright (c) 2014-2015 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/ColinH/PEGTL/
#ifndef PEGTL_INTERNAL_RULE_MATCH_TWO_HH
#define PEGTL_INTERNAL_RULE_MATCH_TWO_HH
#include <cstdlib>
#include "../apply_mode.hh"
#include "apply_here.hh"
#include "rule_match_three.hh"
namespace pegtl
{
namespace internal
{
template< typename Rule, apply_mode A, template< typename ... > class Action, template< typename ... > class Control, apply_here H > struct rule_match_two;
template< typename Rule, apply_mode A, template< typename ... > class Action, template< typename ... > class Control >
struct rule_match_two< Rule, A, Action, Control, apply_here::NOTHING >
{
template< typename Input, typename ... States >
static bool match( Input & in, States && ... st )
{
Control< Rule >::start( static_cast< const Input & >( in ), st ... );
if ( rule_match_three< Rule, A, Action, Control >::match( in, st ... ) ) {
Control< Rule >::success( static_cast< const Input & >( in ), st ... );
return true;
}
Control< Rule >::failure( static_cast< const Input & >( in ), st ... );
return false;
}
};
template< typename Rule, apply_mode A, template< typename ... > class Action, template< typename ... > class Control >
struct rule_match_two< Rule, A, Action, Control, apply_here::ACTION >
{
template< typename Input, typename ... States >
static bool match( Input & in, States && ... st )
{
auto m = in.mark();
if ( rule_match_two< Rule, A, Action, Control, apply_here::NOTHING >::match( in, st ... ) ) {
Action< Rule >::apply( Input( m ), st ... );
return m( true );
}
return false;
}
};
} // internal
} // pegtl
#endif
<|endoftext|> |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.