text
stringlengths 54
60.6k
|
|---|
<commit_before>#include "IfNode.h"
#include "../Parser.h"
#include <assert.h>
namespace Language {
IfNode* IfNode::parse(Parser& parser) {
IfNode* node = new IfNode();
node->setStatement(true);
assert(parser.next().type() == Token::Type::KeywordIf);
// parse the condition
node->_conditionNode = parser.parseExpression();
parser.parseNewline();
// and now, parse the body
while (true) {
Token t = parser.peek();
if (t.type() == Token::Type::KeywordEnd || t.type() == Token::Type::KeywordElse) {
break;
}
node->addChild(parser.parseStatement());
}
if (parser.peek().type() == Token::Type::KeywordElse) {
node->_elseNode = ElseNode::parse(parser);
} else {
assert(parser.next().type() == Token::Type::KeywordEnd);
}
return node;
}
ASTNode* IfNode::parseTailing(Parser& parser, ASTNode* node) {
if (parser.peek().type() != Token::Type::KeywordIf) {
return node;
}
assert(parser.next().type() == Token::Type::KeywordIf);
IfNode* ifNode = new IfNode();
ifNode->addChild(node);
ifNode->_conditionNode = parser.parseExpression();
return ifNode;
}
IfNode::IfNode() : _elseNode(NULL) {
}
std::string IfNode::name() const {
return "If";
}
ASTNode* IfNode::condition() const {
return _conditionNode;
}
ElseNode* IfNode::elseStatement() const {
return _elseNode;
}
void IfNode::codeGenCSource(CSourceContext& context) {
context.current()->print("if (");
this->condition()->codeGenCSource(context);
context.current()->printLineAndIndent(") {");
this->codeGenCSourceForChildren(context);
context.current()->decreaseIndentation();
context.current()->printNewLine();
if (this->elseStatement()) {
context.current()->print("} else {");
context.current()->increaseIndentation();
context.current()->printNewLine();
this->elseStatement()->codeGenCSourceForChildren(context);
context.current()->decreaseIndentation();
context.current()->printNewLine();
}
context.current()->print("}");
}
}
<commit_msg>Improvements to C codegen of if statements<commit_after>#include "IfNode.h"
#include "../Parser.h"
#include <assert.h>
namespace Language {
IfNode* IfNode::parse(Parser& parser) {
IfNode* node = new IfNode();
node->setStatement(true);
assert(parser.next().type() == Token::Type::KeywordIf);
// parse the condition
node->_conditionNode = parser.parseExpression();
parser.parseNewline();
// and now, parse the body
while (true) {
Token t = parser.peek();
if (t.type() == Token::Type::KeywordEnd || t.type() == Token::Type::KeywordElse) {
break;
}
node->addChild(parser.parseStatement());
}
if (parser.peek().type() == Token::Type::KeywordElse) {
node->_elseNode = ElseNode::parse(parser);
} else {
assert(parser.next().type() == Token::Type::KeywordEnd);
}
return node;
}
ASTNode* IfNode::parseTailing(Parser& parser, ASTNode* node) {
if (parser.peek().type() != Token::Type::KeywordIf) {
return node;
}
assert(parser.next().type() == Token::Type::KeywordIf);
IfNode* ifNode = new IfNode();
ifNode->addChild(node);
ifNode->_conditionNode = parser.parseExpression();
return ifNode;
}
IfNode::IfNode() : _elseNode(NULL) {
}
std::string IfNode::name() const {
return "If";
}
ASTNode* IfNode::condition() const {
return _conditionNode;
}
ElseNode* IfNode::elseStatement() const {
return _elseNode;
}
void IfNode::codeGenCSource(CSourceContext& context) {
context.current()->print("if (");
this->condition()->codeGenCSource(context);
context.current()->printLineAndIndent(") {");
this->codeGenCSourceForChildren(context);
if (this->elseStatement()) {
context.current()->outdentAndPrintLine("} else {");
context.current()->increaseIndentation();
this->elseStatement()->codeGenCSourceForChildren(context);
}
context.current()->outdentAndPrintLine("}");
}
}
<|endoftext|>
|
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef SC_MATRIX_HXX
#define SC_MATRIX_HXX
#include "global.hxx"
#include "types.hxx"
#include "formula/errorcodes.hxx"
#include "scdllapi.h"
#include <rtl/ustring.hxx>
#include <boost/intrusive_ptr.hpp>
class ScInterpreter;
class SvNumberFormatter;
class ScMatrixImpl;
typedef sal_uInt8 ScMatValType;
const ScMatValType SC_MATVAL_VALUE = 0x00;
const ScMatValType SC_MATVAL_BOOLEAN = 0x01;
const ScMatValType SC_MATVAL_STRING = 0x02;
const ScMatValType SC_MATVAL_EMPTY = SC_MATVAL_STRING | 0x04; // STRING plus flag
const ScMatValType SC_MATVAL_EMPTYPATH = SC_MATVAL_EMPTY | 0x08; // EMPTY plus flag
const ScMatValType SC_MATVAL_NONVALUE = SC_MATVAL_EMPTYPATH; // mask of all non-value bits
struct ScMatrixValue
{
union {
double fVal;
const ::rtl::OUString* pS;
};
ScMatValType nType;
/// Only valid if ScMatrix methods indicate so!
const ::rtl::OUString& GetString() const { return pS ? *pS : EMPTY_OUSTRING; }
/// Only valid if ScMatrix methods indicate that this is no string!
sal_uInt16 GetError() const { return GetDoubleErrorValue( fVal); }
/// Only valid if ScMatrix methods indicate that this is a boolean
bool GetBoolean() const { return fVal != 0.0; }
ScMatrixValue() : fVal(0.0), nType(SC_MATVAL_EMPTY) {}
ScMatrixValue(const ScMatrixValue& r) : fVal(r.fVal), nType(r.nType)
{
if (nType == SC_MATVAL_STRING)
// This is probably not necessary but just in case...
pS = r.pS;
}
bool operator== (const ScMatrixValue& r) const
{
if (nType != r.nType)
return false;
switch (nType)
{
case SC_MATVAL_VALUE:
case SC_MATVAL_BOOLEAN:
return fVal == r.fVal;
break;
default:
;
}
if (!pS)
return r.pS == NULL;
return GetString().equals(r.GetString());
}
bool operator!= (const ScMatrixValue& r) const
{
return !operator==(r);
}
ScMatrixValue& operator= (const ScMatrixValue& r)
{
nType = r.nType;
fVal = r.fVal;
if (nType == SC_MATVAL_STRING)
// This is probably not necessary but just in case...
pS = r.pS;
return *this;
}
};
/**
* Matrix data type that can store values of mixed types. Each element can
* be one of the following types: numeric, string, boolean, empty, and empty
* path.
*
* This class also supports four different density types: filled zero,
* filled empty, sparse zero, and sparse empty. The filled density type
* allocates memory for every single element at all times, whereas the
* sparse density types allocates memory only for non-default elements.
*/
class SC_DLLPUBLIC ScMatrix
{
ScMatrixImpl* pImpl;
mutable size_t nRefCnt; // reference count
// only delete via Delete()
~ScMatrix();
// not implemented, prevent usage
ScMatrix( const ScMatrix& );
ScMatrix& operator=( const ScMatrix&);
public:
enum DensityType
{
FILLED_ZERO,
FILLED_EMPTY,
SPARSE_ZERO,
SPARSE_EMPTY
};
/**
* When adding all numerical matrix elements for a scalar result such as
* summation, the interpreter wants to separate the first non-zero value
* with the rest of the summed values.
*
* TODO: Find out if we still need to do this. If not, we can re-write
* ScInterpreter::IterateParameters() to make it simpler and remove this
* struct.
*/
struct IterateResult
{
double mfFirst;
double mfRest;
size_t mnCount;
IterateResult(double fFirst, double fRest, size_t nCount) :
mfFirst(fFirst), mfRest(fRest), mnCount(nCount) {}
IterateResult(const IterateResult& r) :
mfFirst(r.mfFirst), mfRest(r.mfRest), mnCount(r.mnCount) {}
};
/// The maximum number of elements a matrix may have at runtime.
inline static size_t GetElementsMax()
{
// TODO: Fix me.
return 0x08000000;
#if 0
// Roughly 125MB in total, divided by 8+1 per element => 14M elements.
const size_t nMemMax = 0x08000000 / (sizeof(ScMatrixValue) + sizeof(ScMatValType));
// With MAXROWCOUNT==65536 and 128 columns => 8M elements ~72MB.
const size_t nArbitraryLimit = (size_t)MAXROWCOUNT * 128;
// Stuffed with a million rows would limit this to 14 columns.
return nMemMax < nArbitraryLimit ? nMemMax : nArbitraryLimit;
#endif
}
/// Value or boolean.
inline static bool IsValueType( ScMatValType nType )
{
return nType <= SC_MATVAL_BOOLEAN;
}
/// Boolean.
inline static bool IsBooleanType( ScMatValType nType )
{
return nType == SC_MATVAL_BOOLEAN;
}
/// String, empty or empty path, but not value nor boolean.
inline static bool IsNonValueType( ScMatValType nType )
{
return (nType & SC_MATVAL_NONVALUE) != 0;
}
/** String, but not empty or empty path or any other type.
Not named IsStringType to prevent confusion because previously
IsNonValueType was named IsStringType. */
inline static bool IsRealStringType( ScMatValType nType )
{
return (nType & SC_MATVAL_NONVALUE) == SC_MATVAL_STRING;
}
/// Empty, but not empty path or any other type.
inline static bool IsEmptyType( ScMatValType nType )
{
return (nType & SC_MATVAL_NONVALUE) == SC_MATVAL_EMPTY;
}
/// Empty path, but not empty or any other type.
inline static bool IsEmptyPathType( ScMatValType nType )
{
return (nType & SC_MATVAL_NONVALUE) == SC_MATVAL_EMPTYPATH;
}
ScMatrix(SCSIZE nC, SCSIZE nR);
ScMatrix(SCSIZE nC, SCSIZE nR, double fInitVal);
/** Clone the matrix. */
ScMatrix* Clone() const;
/** Clone the matrix if mbCloneIfConst (immutable) is set, otherwise
return _this_ matrix, to be assigned to a ScMatrixRef. */
ScMatrix* CloneIfConst();
/** Set the matrix to (im)mutable for CloneIfConst(), only the interpreter
should do this and know the consequences. */
void SetImmutable( bool bVal );
/**
* Resize the matrix to specified new dimension.
*/
void Resize( SCSIZE nC, SCSIZE nR);
void Resize(SCSIZE nC, SCSIZE nR, double fVal);
/** Clone the matrix and extend it to the new size. nNewCols and nNewRows
MUST be at least of the size of the original matrix. */
ScMatrix* CloneAndExtend(SCSIZE nNewCols, SCSIZE nNewRows) const;
inline void IncRef() const
{
++nRefCnt;
}
inline void DecRef() const
{
--nRefCnt;
if (nRefCnt == 0)
delete this;
}
void SetErrorInterpreter( ScInterpreter* p);
void GetDimensions( SCSIZE& rC, SCSIZE& rR) const;
SCSIZE GetElementCount() const;
bool ValidColRow( SCSIZE nC, SCSIZE nR) const;
SCSIZE CalcOffset( SCSIZE nC, SCSIZE nR) const;
/** For a row vector or column vector, if the position does not point into
the vector but is a valid column or row offset it is adapted such that
it points to an element to be replicated, same column row 0 for a row
vector, same row column 0 for a column vector. Else, for a 2D matrix,
returns false.
*/
bool ValidColRowReplicated( SCSIZE & rC, SCSIZE & rR ) const;
/** Checks if the matrix position is within the matrix. If it is not, for a
row vector or column vector the position is adapted such that it points
to an element to be replicated, same column row 0 for a row vector,
same row column 0 for a column vector. Else, for a 2D matrix and
position not within matrix, returns false.
*/
bool ValidColRowOrReplicated( SCSIZE & rC, SCSIZE & rR ) const;
void PutDouble( double fVal, SCSIZE nC, SCSIZE nR);
void PutDouble( double fVal, SCSIZE nIndex);
void PutString( const ::rtl::OUString& rStr, SCSIZE nC, SCSIZE nR);
void PutString( const ::rtl::OUString& rStr, SCSIZE nIndex);
void PutEmpty( SCSIZE nC, SCSIZE nR);
/// Jump FALSE without path
void PutEmptyPath( SCSIZE nC, SCSIZE nR);
void PutError( sal_uInt16 nErrorCode, SCSIZE nC, SCSIZE nR );
void PutBoolean( bool bVal, SCSIZE nC, SCSIZE nR);
void FillDouble( double fVal,
SCSIZE nC1, SCSIZE nR1, SCSIZE nC2, SCSIZE nR2 );
/** May be used before obtaining the double value of an element to avoid
passing its NAN around.
@ATTENTION: MUST NOT be used if the element is a string!
Use GetErrorIfNotString() instead if not sure.
@returns 0 if no error, else one of err... constants */
sal_uInt16 GetError( SCSIZE nC, SCSIZE nR) const;
/** Use in ScInterpreter to obtain the error code, if any.
@returns 0 if no error or string element, else one of err... constants */
sal_uInt16 GetErrorIfNotString( SCSIZE nC, SCSIZE nR) const
{ return IsValue( nC, nR) ? GetError( nC, nR) : 0; }
/// @return 0.0 if empty or empty path, else value or DoubleError.
double GetDouble( SCSIZE nC, SCSIZE nR) const;
/// @return 0.0 if empty or empty path, else value or DoubleError.
double GetDouble( SCSIZE nIndex) const;
/// @return empty string if empty or empty path, else string content.
rtl::OUString GetString( SCSIZE nC, SCSIZE nR) const;
/// @return empty string if empty or empty path, else string content.
rtl::OUString GetString( SCSIZE nIndex) const;
/** @returns the matrix element's string if one is present, otherwise the
numerical value formatted as string, or in case of an error the error
string is returned; an empty string for empty, a "FALSE" string for
empty path. */
::rtl::OUString GetString( SvNumberFormatter& rFormatter, SCSIZE nC, SCSIZE nR) const;
/// @ATTENTION: If bString the ScMatrixValue->pS may still be NULL to indicate
/// an empty string!
ScMatrixValue Get( SCSIZE nC, SCSIZE nR) const;
/// @return <TRUE/> if string or empty or empty path, in fact non-value.
sal_Bool IsString( SCSIZE nIndex ) const;
/// @return <TRUE/> if string or empty or empty path, in fact non-value.
sal_Bool IsString( SCSIZE nC, SCSIZE nR ) const;
/// @return <TRUE/> if empty or empty path.
sal_Bool IsEmpty( SCSIZE nC, SCSIZE nR ) const;
/// @return <TRUE/> if empty path.
sal_Bool IsEmptyPath( SCSIZE nC, SCSIZE nR ) const;
/// @return <TRUE/> if value or boolean.
sal_Bool IsValue( SCSIZE nIndex ) const;
/// @return <TRUE/> if value or boolean.
sal_Bool IsValue( SCSIZE nC, SCSIZE nR ) const;
/// @return <TRUE/> if value or boolean or empty or empty path.
sal_Bool IsValueOrEmpty( SCSIZE nC, SCSIZE nR ) const;
/// @return <TRUE/> if boolean.
sal_Bool IsBoolean( SCSIZE nC, SCSIZE nR ) const;
/// @return <TRUE/> if entire matrix is numeric, including booleans, with no strings or empties
sal_Bool IsNumeric() const;
void MatTrans( ScMatrix& mRes) const;
void MatCopy ( ScMatrix& mRes) const;
// Convert ScInterpreter::CompareMat values (-1,0,1) to boolean values
void CompareEqual();
void CompareNotEqual();
void CompareLess();
void CompareGreater();
void CompareLessEqual();
void CompareGreaterEqual();
double And() const; // logical AND of all matrix values, or NAN
double Or() const; // logical OR of all matrix values, or NAN
IterateResult Sum(bool bTextAsZero) const;
IterateResult SumSquare(bool bTextAsZero) const;
IterateResult Product(bool bTextAsZero) const;
size_t Count(bool bCountStrings) const;
// All other matrix functions MatMult, MInv, ... are in ScInterpreter
// to be numerically safe.
};
inline void intrusive_ptr_add_ref(const ScMatrix* p)
{
p->IncRef();
}
inline void intrusive_ptr_release(const ScMatrix* p)
{
p->DecRef();
}
#endif // SC_MATRIX_HXX
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>This is no longer true.<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef SC_MATRIX_HXX
#define SC_MATRIX_HXX
#include "global.hxx"
#include "types.hxx"
#include "formula/errorcodes.hxx"
#include "scdllapi.h"
#include <rtl/ustring.hxx>
#include <boost/intrusive_ptr.hpp>
class ScInterpreter;
class SvNumberFormatter;
class ScMatrixImpl;
typedef sal_uInt8 ScMatValType;
const ScMatValType SC_MATVAL_VALUE = 0x00;
const ScMatValType SC_MATVAL_BOOLEAN = 0x01;
const ScMatValType SC_MATVAL_STRING = 0x02;
const ScMatValType SC_MATVAL_EMPTY = SC_MATVAL_STRING | 0x04; // STRING plus flag
const ScMatValType SC_MATVAL_EMPTYPATH = SC_MATVAL_EMPTY | 0x08; // EMPTY plus flag
const ScMatValType SC_MATVAL_NONVALUE = SC_MATVAL_EMPTYPATH; // mask of all non-value bits
struct ScMatrixValue
{
union {
double fVal;
const ::rtl::OUString* pS;
};
ScMatValType nType;
/// Only valid if ScMatrix methods indicate so!
const ::rtl::OUString& GetString() const { return pS ? *pS : EMPTY_OUSTRING; }
/// Only valid if ScMatrix methods indicate that this is no string!
sal_uInt16 GetError() const { return GetDoubleErrorValue( fVal); }
/// Only valid if ScMatrix methods indicate that this is a boolean
bool GetBoolean() const { return fVal != 0.0; }
ScMatrixValue() : fVal(0.0), nType(SC_MATVAL_EMPTY) {}
ScMatrixValue(const ScMatrixValue& r) : fVal(r.fVal), nType(r.nType)
{
if (nType == SC_MATVAL_STRING)
// This is probably not necessary but just in case...
pS = r.pS;
}
bool operator== (const ScMatrixValue& r) const
{
if (nType != r.nType)
return false;
switch (nType)
{
case SC_MATVAL_VALUE:
case SC_MATVAL_BOOLEAN:
return fVal == r.fVal;
break;
default:
;
}
if (!pS)
return r.pS == NULL;
return GetString().equals(r.GetString());
}
bool operator!= (const ScMatrixValue& r) const
{
return !operator==(r);
}
ScMatrixValue& operator= (const ScMatrixValue& r)
{
nType = r.nType;
fVal = r.fVal;
if (nType == SC_MATVAL_STRING)
// This is probably not necessary but just in case...
pS = r.pS;
return *this;
}
};
/**
* Matrix data type that can store values of mixed types. Each element can
* be one of the following types: numeric, string, boolean, empty, and empty
* path.
*/
class SC_DLLPUBLIC ScMatrix
{
ScMatrixImpl* pImpl;
mutable size_t nRefCnt; // reference count
// only delete via Delete()
~ScMatrix();
// not implemented, prevent usage
ScMatrix( const ScMatrix& );
ScMatrix& operator=( const ScMatrix&);
public:
enum DensityType
{
FILLED_ZERO,
FILLED_EMPTY,
SPARSE_ZERO,
SPARSE_EMPTY
};
/**
* When adding all numerical matrix elements for a scalar result such as
* summation, the interpreter wants to separate the first non-zero value
* with the rest of the summed values.
*
* TODO: Find out if we still need to do this. If not, we can re-write
* ScInterpreter::IterateParameters() to make it simpler and remove this
* struct.
*/
struct IterateResult
{
double mfFirst;
double mfRest;
size_t mnCount;
IterateResult(double fFirst, double fRest, size_t nCount) :
mfFirst(fFirst), mfRest(fRest), mnCount(nCount) {}
IterateResult(const IterateResult& r) :
mfFirst(r.mfFirst), mfRest(r.mfRest), mnCount(r.mnCount) {}
};
/// The maximum number of elements a matrix may have at runtime.
inline static size_t GetElementsMax()
{
// TODO: Fix me.
return 0x08000000;
#if 0
// Roughly 125MB in total, divided by 8+1 per element => 14M elements.
const size_t nMemMax = 0x08000000 / (sizeof(ScMatrixValue) + sizeof(ScMatValType));
// With MAXROWCOUNT==65536 and 128 columns => 8M elements ~72MB.
const size_t nArbitraryLimit = (size_t)MAXROWCOUNT * 128;
// Stuffed with a million rows would limit this to 14 columns.
return nMemMax < nArbitraryLimit ? nMemMax : nArbitraryLimit;
#endif
}
/// Value or boolean.
inline static bool IsValueType( ScMatValType nType )
{
return nType <= SC_MATVAL_BOOLEAN;
}
/// Boolean.
inline static bool IsBooleanType( ScMatValType nType )
{
return nType == SC_MATVAL_BOOLEAN;
}
/// String, empty or empty path, but not value nor boolean.
inline static bool IsNonValueType( ScMatValType nType )
{
return (nType & SC_MATVAL_NONVALUE) != 0;
}
/** String, but not empty or empty path or any other type.
Not named IsStringType to prevent confusion because previously
IsNonValueType was named IsStringType. */
inline static bool IsRealStringType( ScMatValType nType )
{
return (nType & SC_MATVAL_NONVALUE) == SC_MATVAL_STRING;
}
/// Empty, but not empty path or any other type.
inline static bool IsEmptyType( ScMatValType nType )
{
return (nType & SC_MATVAL_NONVALUE) == SC_MATVAL_EMPTY;
}
/// Empty path, but not empty or any other type.
inline static bool IsEmptyPathType( ScMatValType nType )
{
return (nType & SC_MATVAL_NONVALUE) == SC_MATVAL_EMPTYPATH;
}
ScMatrix(SCSIZE nC, SCSIZE nR);
ScMatrix(SCSIZE nC, SCSIZE nR, double fInitVal);
/** Clone the matrix. */
ScMatrix* Clone() const;
/** Clone the matrix if mbCloneIfConst (immutable) is set, otherwise
return _this_ matrix, to be assigned to a ScMatrixRef. */
ScMatrix* CloneIfConst();
/** Set the matrix to (im)mutable for CloneIfConst(), only the interpreter
should do this and know the consequences. */
void SetImmutable( bool bVal );
/**
* Resize the matrix to specified new dimension.
*/
void Resize( SCSIZE nC, SCSIZE nR);
void Resize(SCSIZE nC, SCSIZE nR, double fVal);
/** Clone the matrix and extend it to the new size. nNewCols and nNewRows
MUST be at least of the size of the original matrix. */
ScMatrix* CloneAndExtend(SCSIZE nNewCols, SCSIZE nNewRows) const;
inline void IncRef() const
{
++nRefCnt;
}
inline void DecRef() const
{
--nRefCnt;
if (nRefCnt == 0)
delete this;
}
void SetErrorInterpreter( ScInterpreter* p);
void GetDimensions( SCSIZE& rC, SCSIZE& rR) const;
SCSIZE GetElementCount() const;
bool ValidColRow( SCSIZE nC, SCSIZE nR) const;
SCSIZE CalcOffset( SCSIZE nC, SCSIZE nR) const;
/** For a row vector or column vector, if the position does not point into
the vector but is a valid column or row offset it is adapted such that
it points to an element to be replicated, same column row 0 for a row
vector, same row column 0 for a column vector. Else, for a 2D matrix,
returns false.
*/
bool ValidColRowReplicated( SCSIZE & rC, SCSIZE & rR ) const;
/** Checks if the matrix position is within the matrix. If it is not, for a
row vector or column vector the position is adapted such that it points
to an element to be replicated, same column row 0 for a row vector,
same row column 0 for a column vector. Else, for a 2D matrix and
position not within matrix, returns false.
*/
bool ValidColRowOrReplicated( SCSIZE & rC, SCSIZE & rR ) const;
void PutDouble( double fVal, SCSIZE nC, SCSIZE nR);
void PutDouble( double fVal, SCSIZE nIndex);
void PutString( const ::rtl::OUString& rStr, SCSIZE nC, SCSIZE nR);
void PutString( const ::rtl::OUString& rStr, SCSIZE nIndex);
void PutEmpty( SCSIZE nC, SCSIZE nR);
/// Jump FALSE without path
void PutEmptyPath( SCSIZE nC, SCSIZE nR);
void PutError( sal_uInt16 nErrorCode, SCSIZE nC, SCSIZE nR );
void PutBoolean( bool bVal, SCSIZE nC, SCSIZE nR);
void FillDouble( double fVal,
SCSIZE nC1, SCSIZE nR1, SCSIZE nC2, SCSIZE nR2 );
/** May be used before obtaining the double value of an element to avoid
passing its NAN around.
@ATTENTION: MUST NOT be used if the element is a string!
Use GetErrorIfNotString() instead if not sure.
@returns 0 if no error, else one of err... constants */
sal_uInt16 GetError( SCSIZE nC, SCSIZE nR) const;
/** Use in ScInterpreter to obtain the error code, if any.
@returns 0 if no error or string element, else one of err... constants */
sal_uInt16 GetErrorIfNotString( SCSIZE nC, SCSIZE nR) const
{ return IsValue( nC, nR) ? GetError( nC, nR) : 0; }
/// @return 0.0 if empty or empty path, else value or DoubleError.
double GetDouble( SCSIZE nC, SCSIZE nR) const;
/// @return 0.0 if empty or empty path, else value or DoubleError.
double GetDouble( SCSIZE nIndex) const;
/// @return empty string if empty or empty path, else string content.
rtl::OUString GetString( SCSIZE nC, SCSIZE nR) const;
/// @return empty string if empty or empty path, else string content.
rtl::OUString GetString( SCSIZE nIndex) const;
/** @returns the matrix element's string if one is present, otherwise the
numerical value formatted as string, or in case of an error the error
string is returned; an empty string for empty, a "FALSE" string for
empty path. */
::rtl::OUString GetString( SvNumberFormatter& rFormatter, SCSIZE nC, SCSIZE nR) const;
/// @ATTENTION: If bString the ScMatrixValue->pS may still be NULL to indicate
/// an empty string!
ScMatrixValue Get( SCSIZE nC, SCSIZE nR) const;
/// @return <TRUE/> if string or empty or empty path, in fact non-value.
sal_Bool IsString( SCSIZE nIndex ) const;
/// @return <TRUE/> if string or empty or empty path, in fact non-value.
sal_Bool IsString( SCSIZE nC, SCSIZE nR ) const;
/// @return <TRUE/> if empty or empty path.
sal_Bool IsEmpty( SCSIZE nC, SCSIZE nR ) const;
/// @return <TRUE/> if empty path.
sal_Bool IsEmptyPath( SCSIZE nC, SCSIZE nR ) const;
/// @return <TRUE/> if value or boolean.
sal_Bool IsValue( SCSIZE nIndex ) const;
/// @return <TRUE/> if value or boolean.
sal_Bool IsValue( SCSIZE nC, SCSIZE nR ) const;
/// @return <TRUE/> if value or boolean or empty or empty path.
sal_Bool IsValueOrEmpty( SCSIZE nC, SCSIZE nR ) const;
/// @return <TRUE/> if boolean.
sal_Bool IsBoolean( SCSIZE nC, SCSIZE nR ) const;
/// @return <TRUE/> if entire matrix is numeric, including booleans, with no strings or empties
sal_Bool IsNumeric() const;
void MatTrans( ScMatrix& mRes) const;
void MatCopy ( ScMatrix& mRes) const;
// Convert ScInterpreter::CompareMat values (-1,0,1) to boolean values
void CompareEqual();
void CompareNotEqual();
void CompareLess();
void CompareGreater();
void CompareLessEqual();
void CompareGreaterEqual();
double And() const; // logical AND of all matrix values, or NAN
double Or() const; // logical OR of all matrix values, or NAN
IterateResult Sum(bool bTextAsZero) const;
IterateResult SumSquare(bool bTextAsZero) const;
IterateResult Product(bool bTextAsZero) const;
size_t Count(bool bCountStrings) const;
// All other matrix functions MatMult, MInv, ... are in ScInterpreter
// to be numerically safe.
};
inline void intrusive_ptr_add_ref(const ScMatrix* p)
{
p->IncRef();
}
inline void intrusive_ptr_release(const ScMatrix* p)
{
p->DecRef();
}
#endif // SC_MATRIX_HXX
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>
|
<commit_before>#pragma once
// `krbn::grabber_alerts_monitor` can be used safely in a multi-threaded environment.
#include "constants.hpp"
#include "file_monitor.hpp"
#include "filesystem.hpp"
#include "json_utility.hpp"
#include "logger.hpp"
#include <fstream>
namespace krbn {
class grabber_alerts_monitor final {
public:
// Signals
boost::signals2::signal<void(const nlohmann::json& alerts)> alerts_changed;
// Methods
grabber_alerts_monitor(const grabber_alerts_monitor&) = delete;
grabber_alerts_monitor(const std::string& grabber_alerts_json_file_path) {
std::vector<std::string> targets = {
grabber_alerts_json_file_path,
};
file_monitor_ = std::make_unique<file_monitor>(targets);
file_monitor_->file_changed.connect([this](auto&& changed_file_path, auto&& file_body) {
if (file_body) {
try {
auto json = nlohmann::json::parse(*file_body);
// json example
//
// {
// "alerts": [
// "system_policy_prevents_loading_kext"
// ]
// }
if (auto v = json_utility::find_array(json, "alerts")) {
auto s = v->dump();
if (last_json_string_ != s) {
last_json_string_ = s;
alerts_changed(*v);
}
}
} catch (std::exception& e) {
logger::get_logger().error("parse error in {0}: {1}", changed_file_path, e.what());
}
}
});
}
void async_start(void) {
file_monitor_->async_start();
}
private:
std::unique_ptr<file_monitor> file_monitor_;
boost::optional<std::string> last_json_string_;
};
} // namespace krbn
<commit_msg>update for file_changed updates<commit_after>#pragma once
// `krbn::grabber_alerts_monitor` can be used safely in a multi-threaded environment.
#include "constants.hpp"
#include "file_monitor.hpp"
#include "filesystem.hpp"
#include "json_utility.hpp"
#include "logger.hpp"
#include <fstream>
namespace krbn {
class grabber_alerts_monitor final {
public:
// Signals
boost::signals2::signal<void(const nlohmann::json& alerts)> alerts_changed;
// Methods
grabber_alerts_monitor(const grabber_alerts_monitor&) = delete;
grabber_alerts_monitor(const std::string& grabber_alerts_json_file_path) {
std::vector<std::string> targets = {
grabber_alerts_json_file_path,
};
file_monitor_ = std::make_unique<file_monitor>(targets);
file_monitor_->file_changed.connect([this](auto&& changed_file_path, auto&& weak_changed_file_body) {
if (auto file_body = weak_changed_file_body.lock()) {
try {
auto json = nlohmann::json::parse(*file_body);
// json example
//
// {
// "alerts": [
// "system_policy_prevents_loading_kext"
// ]
// }
if (auto v = json_utility::find_array(json, "alerts")) {
auto s = v->dump();
if (last_json_string_ != s) {
last_json_string_ = s;
alerts_changed(*v);
}
}
} catch (std::exception& e) {
logger::get_logger().error("parse error in {0}: {1}", changed_file_path, e.what());
}
}
});
}
void async_start(void) {
file_monitor_->async_start();
}
private:
std::unique_ptr<file_monitor> file_monitor_;
boost::optional<std::string> last_json_string_;
};
} // namespace krbn
<|endoftext|>
|
<commit_before><commit_msg>INTEGRATION: CWS mav09 (1.5.82); FILE MERGED 2004/07/15 10:50:00 mba 1.5.82.1: #i27773#: XMLFilter needs additional parameter<commit_after><|endoftext|>
|
<commit_before>/****************************************************************************
**
** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/
**
** This file is part of the QtLocation module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
**
** $QT_END_LICENSE$
**
** This file is part of the Ovi services plugin for the Maps and
** Navigation API. The use of these services, whether by use of the
** plugin or by other means, is governed by the terms and conditions
** described by the file OVI_SERVICES_TERMS_AND_CONDITIONS.txt in
** this package, located in the directory containing the Ovi services
** plugin source code.
**
****************************************************************************/
#include "qgeocodingmanagerengine_nokia.h"
#include "qgeocodereply_nokia.h"
#include "marclanguagecodes.h"
#include <qgeoaddress.h>
#include <qgeocoordinate.h>
#include <QNetworkProxy>
#include <QUrl>
#include <QMap>
QT_BEGIN_NAMESPACE
QGeocodingManagerEngineNokia::QGeocodingManagerEngineNokia(const QMap<QString, QVariant> ¶meters, QGeoServiceProvider::Error *error, QString *errorString)
: QGeocodingManagerEngine(parameters),
m_host("loc.desktop.maps.svc.ovi.com"),
m_token(QGeoServiceProviderFactoryNokia::defaultToken),
m_referer(QGeoServiceProviderFactoryNokia::defaultReferer)
{
m_networkManager = new QNetworkAccessManager(this);
if (parameters.contains("places.proxy")) {
QString proxy = parameters.value("places.proxy").toString();
if (!proxy.isEmpty()) {
QUrl proxyUrl(proxy);
if (proxyUrl.isValid()) {
m_networkManager->setProxy(QNetworkProxy(QNetworkProxy::HttpProxy,
proxyUrl.host(),
proxyUrl.port(8080),
proxyUrl.userName(),
proxyUrl.password()));
}
}
}
if (parameters.contains("places.host")) {
QString host = parameters.value("places.host").toString();
if (!host.isEmpty())
m_host = host;
}
if (parameters.contains("places.referer")) {
m_referer = parameters.value("places.referer").toString();
}
if (parameters.contains("places.token")) {
m_token = parameters.value("places.token").toString();
}
else if (parameters.contains("token")) {
m_token = parameters.value("token").toString();
}
if (error)
*error = QGeoServiceProvider::NoError;
if (errorString)
*errorString = "";
}
QGeocodingManagerEngineNokia::~QGeocodingManagerEngineNokia() {}
QGeocodeReply* QGeocodingManagerEngineNokia::geocode(const QGeoAddress &address,
const QGeoBoundingArea &bounds)
{
QString requestString = "http://";
requestString += m_host;
requestString += "/geocoder/gc/2.0?referer=" + m_referer;
if (!m_token.isNull())
requestString += "&token=" + m_token;
requestString += "&lg=";
requestString += languageToMarc(locale().language());
requestString += "&country=";
requestString += address.country();
if (!address.state().isEmpty()) {
requestString += "&state=";
requestString += address.state();
}
if (!address.city().isEmpty()) {
requestString += "&city=";
requestString += address.city();
}
if (!address.postalCode().isEmpty()) {
requestString += "&zip=";
requestString += address.postalCode();
}
if (!address.street().isEmpty()) {
requestString += "&street=";
requestString += address.street();
}
// TODO?
// street number has been removed from QGeoAddress
// do we need to try to split it out from QGeoAddress::street
// in order to geocode properly
// Old code:
// if (!address.streetNumber().isEmpty()) {
// requestString += "&number=";
// requestString += address.streetNumber();
// }
return geocode(requestString, bounds);
}
QGeocodeReply* QGeocodingManagerEngineNokia::reverseGeocode(const QGeoCoordinate &coordinate,
const QGeoBoundingArea &bounds)
{
QString requestString = "http://";
requestString += m_host;
requestString += "/geocoder/rgc/2.0?referer=" + m_referer;
if (!m_token.isNull())
requestString += "&token=" + m_token;
requestString += "&long=";
requestString += trimDouble(coordinate.longitude());
requestString += "&lat=";
requestString += trimDouble(coordinate.latitude());
requestString += "&lg=";
requestString += languageToMarc(locale().language());
return geocode(requestString, bounds);
}
QGeocodeReply* QGeocodingManagerEngineNokia::geocode(const QString &address,
int limit,
int offset,
const QGeoBoundingArea &bounds)
{
QString requestString = "http://";
requestString += m_host;
requestString += "/geocoder/gc/2.0?referer=" + m_referer;
if (!m_token.isNull())
requestString += "&token=" + m_token;
requestString += "&lg=";
requestString += languageToMarc(locale().language());
requestString += "&obloc=";
requestString += address;
if (limit > 0) {
requestString += "&total=";
requestString += QString::number(limit);
}
if (offset > 0) {
requestString += "&offset=";
requestString += QString::number(offset);
}
return geocode(requestString, bounds, limit, offset);
}
QGeocodeReply* QGeocodingManagerEngineNokia::geocode(QString requestString,
const QGeoBoundingArea &bounds,
int limit,
int offset)
{
QNetworkReply *networkReply = m_networkManager->get(QNetworkRequest(QUrl(requestString)));
QGeocodeReplyNokia *reply = new QGeocodeReplyNokia(networkReply, limit, offset, bounds, this);
connect(reply,
SIGNAL(finished()),
this,
SLOT(placesFinished()));
connect(reply,
SIGNAL(error(QGeocodeReply::Error, QString)),
this,
SLOT(placesError(QGeocodeReply::Error, QString)));
return reply;
}
QString QGeocodingManagerEngineNokia::trimDouble(double degree, int decimalDigits)
{
QString sDegree = QString::number(degree, 'g', decimalDigits);
int index = sDegree.indexOf('.');
if (index == -1)
return sDegree;
else
return QString::number(degree, 'g', decimalDigits + index);
}
void QGeocodingManagerEngineNokia::placesFinished()
{
QGeocodeReply *reply = qobject_cast<QGeocodeReply*>(sender());
if (!reply)
return;
if (receivers(SIGNAL(finished(QGeocodeReply*))) == 0) {
reply->deleteLater();
return;
}
emit finished(reply);
}
void QGeocodingManagerEngineNokia::placesError(QGeocodeReply::Error error, const QString &errorString)
{
QGeocodeReply *reply = qobject_cast<QGeocodeReply*>(sender());
if (!reply)
return;
if (receivers(SIGNAL(error(QGeocodeReply*, QGeocodeReply::Error, QString))) == 0) {
reply->deleteLater();
return;
}
emit this->error(reply, error, errorString);
}
QString QGeocodingManagerEngineNokia::languageToMarc(QLocale::Language language)
{
uint offset = 3 * (uint(language));
if (language == QLocale::C || offset + 3 > sizeof(marc_language_code_list))
return QLatin1String("eng");
const unsigned char *c = marc_language_code_list + offset;
if (c[0] == 0)
return QLatin1String("eng");
QString code(3, Qt::Uninitialized);
code[0] = ushort(c[0]);
code[1] = ushort(c[1]);
code[2] = ushort(c[2]);
return code;
}
QT_END_NAMESPACE
<commit_msg>Unexpected Error status of GeocodeModel<commit_after>/****************************************************************************
**
** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/
**
** This file is part of the QtLocation module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
**
** $QT_END_LICENSE$
**
** This file is part of the Ovi services plugin for the Maps and
** Navigation API. The use of these services, whether by use of the
** plugin or by other means, is governed by the terms and conditions
** described by the file OVI_SERVICES_TERMS_AND_CONDITIONS.txt in
** this package, located in the directory containing the Ovi services
** plugin source code.
**
****************************************************************************/
#include "qgeocodingmanagerengine_nokia.h"
#include "qgeocodereply_nokia.h"
#include "marclanguagecodes.h"
#include <qgeoaddress.h>
#include <qgeocoordinate.h>
#include <QNetworkProxy>
#include <QUrl>
#include <QMap>
#include <QStringList>
QT_BEGIN_NAMESPACE
QGeocodingManagerEngineNokia::QGeocodingManagerEngineNokia(const QMap<QString, QVariant> ¶meters, QGeoServiceProvider::Error *error, QString *errorString)
: QGeocodingManagerEngine(parameters),
m_host("loc.desktop.maps.svc.ovi.com"),
m_token(QGeoServiceProviderFactoryNokia::defaultToken),
m_referer(QGeoServiceProviderFactoryNokia::defaultReferer)
{
m_networkManager = new QNetworkAccessManager(this);
if (parameters.contains("places.proxy")) {
QString proxy = parameters.value("places.proxy").toString();
if (!proxy.isEmpty()) {
QUrl proxyUrl(proxy);
if (proxyUrl.isValid()) {
m_networkManager->setProxy(QNetworkProxy(QNetworkProxy::HttpProxy,
proxyUrl.host(),
proxyUrl.port(8080),
proxyUrl.userName(),
proxyUrl.password()));
}
}
}
if (parameters.contains("places.host")) {
QString host = parameters.value("places.host").toString();
if (!host.isEmpty())
m_host = host;
}
if (parameters.contains("places.referer")) {
m_referer = parameters.value("places.referer").toString();
}
if (parameters.contains("places.token")) {
m_token = parameters.value("places.token").toString();
}
else if (parameters.contains("token")) {
m_token = parameters.value("token").toString();
}
if (error)
*error = QGeoServiceProvider::NoError;
if (errorString)
*errorString = "";
}
QGeocodingManagerEngineNokia::~QGeocodingManagerEngineNokia() {}
QGeocodeReply* QGeocodingManagerEngineNokia::geocode(const QGeoAddress &address,
const QGeoBoundingArea &bounds)
{
QString requestString = "http://";
requestString += m_host;
requestString += "/geocoder/gc/2.0?referer=" + m_referer;
if (!m_token.isNull())
requestString += "&token=" + m_token;
requestString += "&lg=";
requestString += languageToMarc(locale().language());
if (address.country().isEmpty()) {
QStringList parts;
if (!address.state().isEmpty())
parts << address.state();
if (!address.city().isEmpty())
parts << address.city();
if (!address.postalCode().isEmpty())
parts << address.postalCode();
if (!address.street().isEmpty())
parts << address.street();
requestString += "&obloc=";
requestString += parts.join(" ");
} else {
requestString += "&country=";
requestString += address.country();
if (!address.state().isEmpty()) {
requestString += "&state=";
requestString += address.state();
}
if (!address.city().isEmpty()) {
requestString += "&city=";
requestString += address.city();
}
if (!address.postalCode().isEmpty()) {
requestString += "&zip=";
requestString += address.postalCode();
}
if (!address.street().isEmpty()) {
requestString += "&street=";
requestString += address.street();
}
}
// TODO?
// street number has been removed from QGeoAddress
// do we need to try to split it out from QGeoAddress::street
// in order to geocode properly
// Old code:
// if (!address.streetNumber().isEmpty()) {
// requestString += "&number=";
// requestString += address.streetNumber();
// }
return geocode(requestString, bounds);
}
QGeocodeReply* QGeocodingManagerEngineNokia::reverseGeocode(const QGeoCoordinate &coordinate,
const QGeoBoundingArea &bounds)
{
QString requestString = "http://";
requestString += m_host;
requestString += "/geocoder/rgc/2.0?referer=" + m_referer;
if (!m_token.isNull())
requestString += "&token=" + m_token;
requestString += "&long=";
requestString += trimDouble(coordinate.longitude());
requestString += "&lat=";
requestString += trimDouble(coordinate.latitude());
requestString += "&lg=";
requestString += languageToMarc(locale().language());
return geocode(requestString, bounds);
}
QGeocodeReply* QGeocodingManagerEngineNokia::geocode(const QString &address,
int limit,
int offset,
const QGeoBoundingArea &bounds)
{
QString requestString = "http://";
requestString += m_host;
requestString += "/geocoder/gc/2.0?referer=" + m_referer;
if (!m_token.isNull())
requestString += "&token=" + m_token;
requestString += "&lg=";
requestString += languageToMarc(locale().language());
requestString += "&obloc=";
requestString += address;
if (limit > 0) {
requestString += "&total=";
requestString += QString::number(limit);
}
if (offset > 0) {
requestString += "&offset=";
requestString += QString::number(offset);
}
return geocode(requestString, bounds, limit, offset);
}
QGeocodeReply* QGeocodingManagerEngineNokia::geocode(QString requestString,
const QGeoBoundingArea &bounds,
int limit,
int offset)
{
QNetworkReply *networkReply = m_networkManager->get(QNetworkRequest(QUrl(requestString)));
QGeocodeReplyNokia *reply = new QGeocodeReplyNokia(networkReply, limit, offset, bounds, this);
connect(reply,
SIGNAL(finished()),
this,
SLOT(placesFinished()));
connect(reply,
SIGNAL(error(QGeocodeReply::Error, QString)),
this,
SLOT(placesError(QGeocodeReply::Error, QString)));
return reply;
}
QString QGeocodingManagerEngineNokia::trimDouble(double degree, int decimalDigits)
{
QString sDegree = QString::number(degree, 'g', decimalDigits);
int index = sDegree.indexOf('.');
if (index == -1)
return sDegree;
else
return QString::number(degree, 'g', decimalDigits + index);
}
void QGeocodingManagerEngineNokia::placesFinished()
{
QGeocodeReply *reply = qobject_cast<QGeocodeReply*>(sender());
if (!reply)
return;
if (receivers(SIGNAL(finished(QGeocodeReply*))) == 0) {
reply->deleteLater();
return;
}
emit finished(reply);
}
void QGeocodingManagerEngineNokia::placesError(QGeocodeReply::Error error, const QString &errorString)
{
QGeocodeReply *reply = qobject_cast<QGeocodeReply*>(sender());
if (!reply)
return;
if (receivers(SIGNAL(error(QGeocodeReply*, QGeocodeReply::Error, QString))) == 0) {
reply->deleteLater();
return;
}
emit this->error(reply, error, errorString);
}
QString QGeocodingManagerEngineNokia::languageToMarc(QLocale::Language language)
{
uint offset = 3 * (uint(language));
if (language == QLocale::C || offset + 3 > sizeof(marc_language_code_list))
return QLatin1String("eng");
const unsigned char *c = marc_language_code_list + offset;
if (c[0] == 0)
return QLatin1String("eng");
QString code(3, Qt::Uninitialized);
code[0] = ushort(c[0]);
code[1] = ushort(c[1]);
code[2] = ushort(c[2]);
return code;
}
QT_END_NAMESPACE
<|endoftext|>
|
<commit_before>//===- ProfileVerifierPass.cpp - LLVM Pass to estimate profile info -------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements a pass that checks profiling information for
// plausibility.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "profile-verifier"
#include "llvm/Instructions.h"
#include "llvm/Module.h"
#include "llvm/Pass.h"
#include "llvm/Analysis/ProfileInfo.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/CallSite.h"
#include "llvm/Support/CFG.h"
#include "llvm/Support/InstIterator.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/Format.h"
#include "llvm/Support/Debug.h"
#include <set>
using namespace llvm;
static cl::opt<bool,false>
ProfileVerifierDisableAssertions("profile-verifier-noassert",
cl::desc("Disable assertions"));
namespace llvm {
template<class FType, class BType>
class ProfileVerifierPassT : public FunctionPass {
struct DetailedBlockInfo {
const BType *BB;
double BBWeight;
double inWeight;
int inCount;
double outWeight;
int outCount;
};
ProfileInfoT<FType, BType> *PI;
std::set<const BType*> BBisVisited;
std::set<const FType*> FisVisited;
bool DisableAssertions;
// When debugging is enabled, the verifier prints a whole slew of debug
// information, otherwise its just the assert. These are all the helper
// functions.
bool PrintedDebugTree;
std::set<const BType*> BBisPrinted;
void debugEntry(DetailedBlockInfo*);
void printDebugInfo(const BType *BB);
public:
static char ID; // Class identification, replacement for typeinfo
explicit ProfileVerifierPassT () : FunctionPass(&ID) {
DisableAssertions = ProfileVerifierDisableAssertions;
}
explicit ProfileVerifierPassT (bool da) : FunctionPass(&ID),
DisableAssertions(da) {
}
void getAnalysisUsage(AnalysisUsage &AU) const {
AU.setPreservesAll();
AU.addRequired<ProfileInfoT<FType, BType> >();
}
const char *getPassName() const {
return "Profiling information verifier";
}
/// run - Verify the profile information.
bool runOnFunction(FType &F);
void recurseBasicBlock(const BType*);
bool exitReachable(const FType*);
double ReadOrAssert(typename ProfileInfoT<FType, BType>::Edge);
void CheckValue(bool, const char*, DetailedBlockInfo*);
};
typedef ProfileVerifierPassT<Function, BasicBlock> ProfileVerifierPass;
template<class FType, class BType>
void ProfileVerifierPassT<FType, BType>::printDebugInfo(const BType *BB) {
if (BBisPrinted.find(BB) != BBisPrinted.end()) return;
double BBWeight = PI->getExecutionCount(BB);
if (BBWeight == ProfileInfoT<FType, BType>::MissingValue) { BBWeight = 0; }
double inWeight = 0;
int inCount = 0;
std::set<const BType*> ProcessedPreds;
for ( pred_const_iterator bbi = pred_begin(BB), bbe = pred_end(BB);
bbi != bbe; ++bbi ) {
if (ProcessedPreds.insert(*bbi).second) {
typename ProfileInfoT<FType, BType>::Edge E = PI->getEdge(*bbi,BB);
double EdgeWeight = PI->getEdgeWeight(E);
if (EdgeWeight == ProfileInfoT<FType, BType>::MissingValue) { EdgeWeight = 0; }
errs() << "calculated in-edge " << E << ": "
<< format("%20.20g",EdgeWeight) << "\n";
inWeight += EdgeWeight;
inCount++;
}
}
double outWeight = 0;
int outCount = 0;
std::set<const BType*> ProcessedSuccs;
for ( succ_const_iterator bbi = succ_begin(BB), bbe = succ_end(BB);
bbi != bbe; ++bbi ) {
if (ProcessedSuccs.insert(*bbi).second) {
typename ProfileInfoT<FType, BType>::Edge E = PI->getEdge(BB,*bbi);
double EdgeWeight = PI->getEdgeWeight(E);
if (EdgeWeight == ProfileInfoT<FType, BType>::MissingValue) { EdgeWeight = 0; }
errs() << "calculated out-edge " << E << ": "
<< format("%20.20g",EdgeWeight) << "\n";
outWeight += EdgeWeight;
outCount++;
}
}
errs() << "Block " << BB->getNameStr() << " in "
<< BB->getParent()->getNameStr() << ":"
<< "BBWeight=" << format("%20.20g",BBWeight) << ","
<< "inWeight=" << format("%20.20g",inWeight) << ","
<< "inCount=" << inCount << ","
<< "outWeight=" << format("%20.20g",outWeight) << ","
<< "outCount" << outCount << "\n";
// mark as visited and recurse into subnodes
BBisPrinted.insert(BB);
for ( succ_const_iterator bbi = succ_begin(BB), bbe = succ_end(BB);
bbi != bbe; ++bbi ) {
printDebugInfo(*bbi);
}
}
template<class FType, class BType>
void ProfileVerifierPassT<FType, BType>::debugEntry (DetailedBlockInfo *DI) {
errs() << "TROUBLE: Block " << DI->BB->getNameStr() << " in "
<< DI->BB->getParent()->getNameStr() << ":"
<< "BBWeight=" << format("%20.20g",DI->BBWeight) << ","
<< "inWeight=" << format("%20.20g",DI->inWeight) << ","
<< "inCount=" << DI->inCount << ","
<< "outWeight=" << format("%20.20g",DI->outWeight) << ","
<< "outCount=" << DI->outCount << "\n";
if (!PrintedDebugTree) {
PrintedDebugTree = true;
printDebugInfo(&(DI->BB->getParent()->getEntryBlock()));
}
}
// This compares A and B for equality.
static bool Equals(double A, double B) {
return A == B;
}
// This checks if the function "exit" is reachable from an given function
// via calls, this is necessary to check if a profile is valid despite the
// counts not fitting exactly.
template<class FType, class BType>
bool ProfileVerifierPassT<FType, BType>::exitReachable(const FType *F) {
if (!F) return false;
if (FisVisited.count(F)) return false;
FType *Exit = F->getParent()->getFunction("exit");
if (Exit == F) {
return true;
}
FisVisited.insert(F);
bool exits = false;
for (const_inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I) {
if (const CallInst *CI = dyn_cast<CallInst>(&*I)) {
FType *F = CI->getCalledFunction();
if (F) {
exits |= exitReachable(F);
} else {
// This is a call to a pointer, all bets are off...
exits = true;
}
if (exits) break;
}
}
return exits;
}
#define ASSERTMESSAGE(M) \
{ errs() << "ASSERT:" << (M) << "\n"; \
if (!DisableAssertions) assert(0 && (M)); }
template<class FType, class BType>
double ProfileVerifierPassT<FType, BType>::ReadOrAssert(typename ProfileInfoT<FType, BType>::Edge E) {
double EdgeWeight = PI->getEdgeWeight(E);
if (EdgeWeight == ProfileInfoT<FType, BType>::MissingValue) {
errs() << "Edge " << E << " in Function "
<< ProfileInfoT<FType, BType>::getFunction(E)->getNameStr() << ": ";
ASSERTMESSAGE("Edge has missing value");
return 0;
} else {
if (EdgeWeight < 0) {
errs() << "Edge " << E << " in Function "
<< ProfileInfoT<FType, BType>::getFunction(E)->getNameStr() << ": ";
ASSERTMESSAGE("Edge has negative value");
}
return EdgeWeight;
}
}
template<class FType, class BType>
void ProfileVerifierPassT<FType, BType>::CheckValue(bool Error,
const char *Message,
DetailedBlockInfo *DI) {
if (Error) {
DEBUG(debugEntry(DI));
errs() << "Block " << DI->BB->getNameStr() << " in Function "
<< DI->BB->getParent()->getNameStr() << ": ";
ASSERTMESSAGE(Message);
}
return;
}
// This calculates the Information for a block and then recurses into the
// successors.
template<class FType, class BType>
void ProfileVerifierPassT<FType, BType>::recurseBasicBlock(const BType *BB) {
// Break the recursion by remembering all visited blocks.
if (BBisVisited.find(BB) != BBisVisited.end()) return;
// Use a data structure to store all the information, this can then be handed
// to debug printers.
DetailedBlockInfo DI;
DI.BB = BB;
DI.outCount = DI.inCount = 0;
DI.inWeight = DI.outWeight = 0;
// Read predecessors.
std::set<const BType*> ProcessedPreds;
pred_const_iterator bpi = pred_begin(BB), bpe = pred_end(BB);
// If there are none, check for (0,BB) edge.
if (bpi == bpe) {
DI.inWeight += ReadOrAssert(PI->getEdge(0,BB));
DI.inCount++;
}
for (;bpi != bpe; ++bpi) {
if (ProcessedPreds.insert(*bpi).second) {
DI.inWeight += ReadOrAssert(PI->getEdge(*bpi,BB));
DI.inCount++;
}
}
// Read successors.
std::set<const BType*> ProcessedSuccs;
succ_const_iterator bbi = succ_begin(BB), bbe = succ_end(BB);
// If there is an (0,BB) edge, consider it too. (This is done not only when
// there are no successors, but every time; not every function contains
// return blocks with no successors (think loop latch as return block)).
double w = PI->getEdgeWeight(PI->getEdge(BB,0));
if (w != ProfileInfoT<FType, BType>::MissingValue) {
DI.outWeight += w;
DI.outCount++;
}
for (;bbi != bbe; ++bbi) {
if (ProcessedSuccs.insert(*bbi).second) {
DI.outWeight += ReadOrAssert(PI->getEdge(BB,*bbi));
DI.outCount++;
}
}
// Read block weight.
DI.BBWeight = PI->getExecutionCount(BB);
CheckValue(DI.BBWeight == ProfileInfoT<FType, BType>::MissingValue,
"BasicBlock has missing value", &DI);
CheckValue(DI.BBWeight < 0,
"BasicBlock has negative value", &DI);
// Check if this block is a setjmp target.
bool isSetJmpTarget = false;
if (DI.outWeight > DI.inWeight) {
for (typename BType::const_iterator i = BB->begin(), ie = BB->end();
i != ie; ++i) {
if (const CallInst *CI = dyn_cast<CallInst>(&*i)) {
FType *F = CI->getCalledFunction();
if (F && (F->getNameStr() == "_setjmp")) {
isSetJmpTarget = true; break;
}
}
}
}
// Check if this block is eventually reaching exit.
bool isExitReachable = false;
if (DI.inWeight > DI.outWeight) {
for (typename BType::const_iterator i = BB->begin(), ie = BB->end();
i != ie; ++i) {
if (const CallInst *CI = dyn_cast<CallInst>(&*i)) {
FType *F = CI->getCalledFunction();
if (F) {
FisVisited.clear();
isExitReachable |= exitReachable(F);
} else {
// This is a call to a pointer, all bets are off...
isExitReachable = true;
}
if (isExitReachable) break;
}
}
}
if (DI.inCount > 0 && DI.outCount == 0) {
// If this is a block with no successors.
if (!isSetJmpTarget) {
CheckValue(!Equals(DI.inWeight,DI.BBWeight),
"inWeight and BBWeight do not match", &DI);
}
} else if (DI.inCount == 0 && DI.outCount > 0) {
// If this is a block with no predecessors.
if (!isExitReachable)
CheckValue(!Equals(DI.BBWeight,DI.outWeight),
"BBWeight and outWeight do not match", &DI);
} else {
// If this block has successors and predecessors.
if (DI.inWeight > DI.outWeight && !isExitReachable)
CheckValue(!Equals(DI.inWeight,DI.outWeight),
"inWeight and outWeight do not match", &DI);
if (DI.inWeight < DI.outWeight && !isSetJmpTarget)
CheckValue(!Equals(DI.inWeight,DI.outWeight),
"inWeight and outWeight do not match", &DI);
}
// Mark this block as visited, rescurse into successors.
BBisVisited.insert(BB);
for ( succ_const_iterator bbi = succ_begin(BB), bbe = succ_end(BB);
bbi != bbe; ++bbi ) {
recurseBasicBlock(*bbi);
}
}
template<class FType, class BType>
bool ProfileVerifierPassT<FType, BType>::runOnFunction(FType &F) {
PI = getAnalysisIfAvailable<ProfileInfoT<FType, BType> >();
if (!PI)
ASSERTMESSAGE("No ProfileInfo available");
// Prepare global variables.
PrintedDebugTree = false;
BBisVisited.clear();
// Fetch entry block and recurse into it.
const BType *entry = &F.getEntryBlock();
recurseBasicBlock(entry);
if (PI->getExecutionCount(&F) != PI->getExecutionCount(entry))
ASSERTMESSAGE("Function count and entry block count do not match");
return false;
}
template<class FType, class BType>
char ProfileVerifierPassT<FType, BType>::ID = 0;
}
static RegisterPass<ProfileVerifierPass>
X("profile-verifier", "Verify profiling information", false, true);
namespace llvm {
FunctionPass *createProfileVerifierPass() {
return new ProfileVerifierPass(ProfileVerifierDisableAssertions);
}
}
<commit_msg><commit_after>//===- ProfileVerifierPass.cpp - LLVM Pass to estimate profile info -------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements a pass that checks profiling information for
// plausibility.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "profile-verifier"
#include "llvm/Instructions.h"
#include "llvm/Module.h"
#include "llvm/Pass.h"
#include "llvm/Analysis/ProfileInfo.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/CallSite.h"
#include "llvm/Support/CFG.h"
#include "llvm/Support/InstIterator.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/Format.h"
#include "llvm/Support/Debug.h"
#include <set>
using namespace llvm;
static cl::opt<bool,false>
ProfileVerifierDisableAssertions("profile-verifier-noassert",
cl::desc("Disable assertions"));
namespace llvm {
template<class FType, class BType>
class ProfileVerifierPassT : public FunctionPass {
struct DetailedBlockInfo {
const BType *BB;
double BBWeight;
double inWeight;
int inCount;
double outWeight;
int outCount;
};
ProfileInfoT<FType, BType> *PI;
std::set<const BType*> BBisVisited;
std::set<const FType*> FisVisited;
bool DisableAssertions;
// When debugging is enabled, the verifier prints a whole slew of debug
// information, otherwise its just the assert. These are all the helper
// functions.
bool PrintedDebugTree;
std::set<const BType*> BBisPrinted;
void debugEntry(DetailedBlockInfo*);
void printDebugInfo(const BType *BB);
public:
static char ID; // Class identification, replacement for typeinfo
explicit ProfileVerifierPassT () : FunctionPass(&ID) {
DisableAssertions = ProfileVerifierDisableAssertions;
}
explicit ProfileVerifierPassT (bool da) : FunctionPass(&ID),
DisableAssertions(da) {
}
void getAnalysisUsage(AnalysisUsage &AU) const {
AU.setPreservesAll();
AU.addRequired<ProfileInfoT<FType, BType> >();
}
const char *getPassName() const {
return "Profiling information verifier";
}
/// run - Verify the profile information.
bool runOnFunction(FType &F);
void recurseBasicBlock(const BType*);
bool exitReachable(const FType*);
double ReadOrAssert(typename ProfileInfoT<FType, BType>::Edge);
void CheckValue(bool, const char*, DetailedBlockInfo*);
};
typedef ProfileVerifierPassT<Function, BasicBlock> ProfileVerifierPass;
template<class FType, class BType>
void ProfileVerifierPassT<FType, BType>::printDebugInfo(const BType *BB) {
if (BBisPrinted.find(BB) != BBisPrinted.end()) return;
double BBWeight = PI->getExecutionCount(BB);
if (BBWeight == ProfileInfoT<FType, BType>::MissingValue) { BBWeight = 0; }
double inWeight = 0;
int inCount = 0;
std::set<const BType*> ProcessedPreds;
for ( pred_const_iterator bbi = pred_begin(BB), bbe = pred_end(BB);
bbi != bbe; ++bbi ) {
if (ProcessedPreds.insert(*bbi).second) {
typename ProfileInfoT<FType, BType>::Edge E = PI->getEdge(*bbi,BB);
double EdgeWeight = PI->getEdgeWeight(E);
if (EdgeWeight == ProfileInfoT<FType, BType>::MissingValue) { EdgeWeight = 0; }
dbgs() << "calculated in-edge " << E << ": "
<< format("%20.20g",EdgeWeight) << "\n";
inWeight += EdgeWeight;
inCount++;
}
}
double outWeight = 0;
int outCount = 0;
std::set<const BType*> ProcessedSuccs;
for ( succ_const_iterator bbi = succ_begin(BB), bbe = succ_end(BB);
bbi != bbe; ++bbi ) {
if (ProcessedSuccs.insert(*bbi).second) {
typename ProfileInfoT<FType, BType>::Edge E = PI->getEdge(BB,*bbi);
double EdgeWeight = PI->getEdgeWeight(E);
if (EdgeWeight == ProfileInfoT<FType, BType>::MissingValue) { EdgeWeight = 0; }
dbgs() << "calculated out-edge " << E << ": "
<< format("%20.20g",EdgeWeight) << "\n";
outWeight += EdgeWeight;
outCount++;
}
}
dbgs() << "Block " << BB->getNameStr() << " in "
<< BB->getParent()->getNameStr() << ":"
<< "BBWeight=" << format("%20.20g",BBWeight) << ","
<< "inWeight=" << format("%20.20g",inWeight) << ","
<< "inCount=" << inCount << ","
<< "outWeight=" << format("%20.20g",outWeight) << ","
<< "outCount" << outCount << "\n";
// mark as visited and recurse into subnodes
BBisPrinted.insert(BB);
for ( succ_const_iterator bbi = succ_begin(BB), bbe = succ_end(BB);
bbi != bbe; ++bbi ) {
printDebugInfo(*bbi);
}
}
template<class FType, class BType>
void ProfileVerifierPassT<FType, BType>::debugEntry (DetailedBlockInfo *DI) {
dbgs() << "TROUBLE: Block " << DI->BB->getNameStr() << " in "
<< DI->BB->getParent()->getNameStr() << ":"
<< "BBWeight=" << format("%20.20g",DI->BBWeight) << ","
<< "inWeight=" << format("%20.20g",DI->inWeight) << ","
<< "inCount=" << DI->inCount << ","
<< "outWeight=" << format("%20.20g",DI->outWeight) << ","
<< "outCount=" << DI->outCount << "\n";
if (!PrintedDebugTree) {
PrintedDebugTree = true;
printDebugInfo(&(DI->BB->getParent()->getEntryBlock()));
}
}
// This compares A and B for equality.
static bool Equals(double A, double B) {
return A == B;
}
// This checks if the function "exit" is reachable from an given function
// via calls, this is necessary to check if a profile is valid despite the
// counts not fitting exactly.
template<class FType, class BType>
bool ProfileVerifierPassT<FType, BType>::exitReachable(const FType *F) {
if (!F) return false;
if (FisVisited.count(F)) return false;
FType *Exit = F->getParent()->getFunction("exit");
if (Exit == F) {
return true;
}
FisVisited.insert(F);
bool exits = false;
for (const_inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I) {
if (const CallInst *CI = dyn_cast<CallInst>(&*I)) {
FType *F = CI->getCalledFunction();
if (F) {
exits |= exitReachable(F);
} else {
// This is a call to a pointer, all bets are off...
exits = true;
}
if (exits) break;
}
}
return exits;
}
#define ASSERTMESSAGE(M) \
{ dbgs() << "ASSERT:" << (M) << "\n"; \
if (!DisableAssertions) assert(0 && (M)); }
template<class FType, class BType>
double ProfileVerifierPassT<FType, BType>::ReadOrAssert(typename ProfileInfoT<FType, BType>::Edge E) {
double EdgeWeight = PI->getEdgeWeight(E);
if (EdgeWeight == ProfileInfoT<FType, BType>::MissingValue) {
dbgs() << "Edge " << E << " in Function "
<< ProfileInfoT<FType, BType>::getFunction(E)->getNameStr() << ": ";
ASSERTMESSAGE("Edge has missing value");
return 0;
} else {
if (EdgeWeight < 0) {
dbgs() << "Edge " << E << " in Function "
<< ProfileInfoT<FType, BType>::getFunction(E)->getNameStr() << ": ";
ASSERTMESSAGE("Edge has negative value");
}
return EdgeWeight;
}
}
template<class FType, class BType>
void ProfileVerifierPassT<FType, BType>::CheckValue(bool Error,
const char *Message,
DetailedBlockInfo *DI) {
if (Error) {
DEBUG(debugEntry(DI));
dbgs() << "Block " << DI->BB->getNameStr() << " in Function "
<< DI->BB->getParent()->getNameStr() << ": ";
ASSERTMESSAGE(Message);
}
return;
}
// This calculates the Information for a block and then recurses into the
// successors.
template<class FType, class BType>
void ProfileVerifierPassT<FType, BType>::recurseBasicBlock(const BType *BB) {
// Break the recursion by remembering all visited blocks.
if (BBisVisited.find(BB) != BBisVisited.end()) return;
// Use a data structure to store all the information, this can then be handed
// to debug printers.
DetailedBlockInfo DI;
DI.BB = BB;
DI.outCount = DI.inCount = 0;
DI.inWeight = DI.outWeight = 0;
// Read predecessors.
std::set<const BType*> ProcessedPreds;
pred_const_iterator bpi = pred_begin(BB), bpe = pred_end(BB);
// If there are none, check for (0,BB) edge.
if (bpi == bpe) {
DI.inWeight += ReadOrAssert(PI->getEdge(0,BB));
DI.inCount++;
}
for (;bpi != bpe; ++bpi) {
if (ProcessedPreds.insert(*bpi).second) {
DI.inWeight += ReadOrAssert(PI->getEdge(*bpi,BB));
DI.inCount++;
}
}
// Read successors.
std::set<const BType*> ProcessedSuccs;
succ_const_iterator bbi = succ_begin(BB), bbe = succ_end(BB);
// If there is an (0,BB) edge, consider it too. (This is done not only when
// there are no successors, but every time; not every function contains
// return blocks with no successors (think loop latch as return block)).
double w = PI->getEdgeWeight(PI->getEdge(BB,0));
if (w != ProfileInfoT<FType, BType>::MissingValue) {
DI.outWeight += w;
DI.outCount++;
}
for (;bbi != bbe; ++bbi) {
if (ProcessedSuccs.insert(*bbi).second) {
DI.outWeight += ReadOrAssert(PI->getEdge(BB,*bbi));
DI.outCount++;
}
}
// Read block weight.
DI.BBWeight = PI->getExecutionCount(BB);
CheckValue(DI.BBWeight == ProfileInfoT<FType, BType>::MissingValue,
"BasicBlock has missing value", &DI);
CheckValue(DI.BBWeight < 0,
"BasicBlock has negative value", &DI);
// Check if this block is a setjmp target.
bool isSetJmpTarget = false;
if (DI.outWeight > DI.inWeight) {
for (typename BType::const_iterator i = BB->begin(), ie = BB->end();
i != ie; ++i) {
if (const CallInst *CI = dyn_cast<CallInst>(&*i)) {
FType *F = CI->getCalledFunction();
if (F && (F->getNameStr() == "_setjmp")) {
isSetJmpTarget = true; break;
}
}
}
}
// Check if this block is eventually reaching exit.
bool isExitReachable = false;
if (DI.inWeight > DI.outWeight) {
for (typename BType::const_iterator i = BB->begin(), ie = BB->end();
i != ie; ++i) {
if (const CallInst *CI = dyn_cast<CallInst>(&*i)) {
FType *F = CI->getCalledFunction();
if (F) {
FisVisited.clear();
isExitReachable |= exitReachable(F);
} else {
// This is a call to a pointer, all bets are off...
isExitReachable = true;
}
if (isExitReachable) break;
}
}
}
if (DI.inCount > 0 && DI.outCount == 0) {
// If this is a block with no successors.
if (!isSetJmpTarget) {
CheckValue(!Equals(DI.inWeight,DI.BBWeight),
"inWeight and BBWeight do not match", &DI);
}
} else if (DI.inCount == 0 && DI.outCount > 0) {
// If this is a block with no predecessors.
if (!isExitReachable)
CheckValue(!Equals(DI.BBWeight,DI.outWeight),
"BBWeight and outWeight do not match", &DI);
} else {
// If this block has successors and predecessors.
if (DI.inWeight > DI.outWeight && !isExitReachable)
CheckValue(!Equals(DI.inWeight,DI.outWeight),
"inWeight and outWeight do not match", &DI);
if (DI.inWeight < DI.outWeight && !isSetJmpTarget)
CheckValue(!Equals(DI.inWeight,DI.outWeight),
"inWeight and outWeight do not match", &DI);
}
// Mark this block as visited, rescurse into successors.
BBisVisited.insert(BB);
for ( succ_const_iterator bbi = succ_begin(BB), bbe = succ_end(BB);
bbi != bbe; ++bbi ) {
recurseBasicBlock(*bbi);
}
}
template<class FType, class BType>
bool ProfileVerifierPassT<FType, BType>::runOnFunction(FType &F) {
PI = getAnalysisIfAvailable<ProfileInfoT<FType, BType> >();
if (!PI)
ASSERTMESSAGE("No ProfileInfo available");
// Prepare global variables.
PrintedDebugTree = false;
BBisVisited.clear();
// Fetch entry block and recurse into it.
const BType *entry = &F.getEntryBlock();
recurseBasicBlock(entry);
if (PI->getExecutionCount(&F) != PI->getExecutionCount(entry))
ASSERTMESSAGE("Function count and entry block count do not match");
return false;
}
template<class FType, class BType>
char ProfileVerifierPassT<FType, BType>::ID = 0;
}
static RegisterPass<ProfileVerifierPass>
X("profile-verifier", "Verify profiling information", false, true);
namespace llvm {
FunctionPass *createProfileVerifierPass() {
return new ProfileVerifierPass(ProfileVerifierDisableAssertions);
}
}
<|endoftext|>
|
<commit_before>#pragma once
#include <iostream>
#include <iomanip>
#include <string>
#include <chrono>
// ----------------------------------------------------------------------
enum class report_time { No, Yes };
class Timeit
{
public:
inline Timeit(std::string msg, report_time aReport = report_time::Yes, std::ostream& out = std::cerr)
: message(msg), out_stream(out), mReport(aReport), start(std::chrono::steady_clock::now()) {}
inline ~Timeit() { report(); }
inline void report()
{
if (mReport == report_time::Yes) {
const auto total = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - start).count();
const decltype(total) s = total / 1000;
const decltype(total) ms = total % 1000;
out_stream << message;
out_stream << s << '.' << std::setw(3) << std::setfill('0') << ms << std::setw(0) << '\n';
mReport = report_time::No;
}
}
inline void message_append(std::string to_append) { message += to_append; }
private:
std::string message;
std::ostream& out_stream;
report_time mReport;
decltype(std::chrono::steady_clock::now()) start;
};
inline report_time do_report_time(bool do_report) { return do_report ? report_time::Yes : report_time::No; }
// ----------------------------------------------------------------------
namespace acmacs
{
using timestamp_t = decltype(std::chrono::steady_clock::now());
inline timestamp_t timestamp() { return std::chrono::steady_clock::now(); }
inline double elapsed(timestamp_t start)
{
const auto diff = std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::steady_clock::now() - start).count();
const decltype(diff) sec = diff / std::nano::den;
const decltype(diff) nanosec = diff % std::nano::den;
return static_cast<double>(sec) + static_cast<double>(nanosec) / double{std::nano::den};
}
} // namespace acmacs
// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<commit_msg>duration format<commit_after>#pragma once
#include <iostream>
#include <sstream>
#include <iomanip>
#include <string>
#include <chrono>
// ----------------------------------------------------------------------
namespace acmacs
{
using timestamp_t = decltype(std::chrono::high_resolution_clock::now());
using duration_t = std::chrono::nanoseconds;
inline timestamp_t timestamp() { return std::chrono::high_resolution_clock::now(); }
inline duration_t elapsed(timestamp_t start) { return std::chrono::duration_cast<duration_t>(timestamp() - start); }
//inline auto days(duration_t duration) { return std::chrono::duration_cast<std::chrono::days>(duration); }
// inline auto hours(duration_t duration) { return std::chrono::duration_cast<std::chrono::hours>(duration); }
inline std::string format(duration_t duration)
{
std::stringstream result;
auto hours = std::chrono::duration_cast<std::chrono::hours>(duration).count();
if (hours > 24) {
result << (hours / 24) << "d:";
hours %= 24;
}
auto format_val = [](auto& target, auto val, char terminator) {
if (val || target.tellg())
target << std::setw(2) << std::setfill('0') << val << terminator;
};
format_val(result, hours, ':');
const auto minutes = std::chrono::duration_cast<std::chrono::minutes>(duration % std::chrono::hours(1)).count();
format_val(result, minutes, ':');
const auto seconds = std::chrono::duration_cast<std::chrono::seconds>(duration % std::chrono::minutes(1)).count();
if (result.tellg())
result << std::setw(2) << std::setfill('0');
result << seconds << '.';
const auto microseconds = std::chrono::duration_cast<std::chrono::microseconds>(duration % std::chrono::seconds(1)).count();
result << std::setw(6) << std::setfill('0') << microseconds;
return result.str();
}
inline double elapsed_seconds(timestamp_t start)
{
const auto diff = elapsed(start).count();
const decltype(diff) sec = diff / std::nano::den;
const decltype(diff) nanosec = diff % std::nano::den;
return static_cast<double>(sec) + static_cast<double>(nanosec) / double{std::nano::den};
}
} // namespace acmacs
// ----------------------------------------------------------------------
enum class report_time { No, Yes };
class Timeit
{
public:
inline Timeit(std::string msg, report_time aReport = report_time::Yes, std::ostream& out = std::cerr)
: message(msg), out_stream(out), mReport(aReport), start(acmacs::timestamp()) {}
inline ~Timeit() { report(); }
inline void report()
{
if (mReport == report_time::Yes) {
// const auto total = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - start).count();
const auto total = std::chrono::duration_cast<std::chrono::milliseconds>(acmacs::elapsed(start)).count();
const decltype(total) s = total / 1000;
const decltype(total) ms = total % 1000;
out_stream << message;
out_stream << s << '.' << std::setw(3) << std::setfill('0') << ms << std::setw(0) << '\n';
mReport = report_time::No;
}
}
inline void message_append(std::string to_append) { message += to_append; }
private:
std::string message;
std::ostream& out_stream;
report_time mReport;
acmacs::timestamp_t start;
};
inline report_time do_report_time(bool do_report) { return do_report ? report_time::Yes : report_time::No; }
// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<|endoftext|>
|
<commit_before>#include <catch.hpp>
#include <luwra.hpp>
#include <iostream>
using namespace luwra;
TEST_CASE("RefHandle") {
StateWrapper state;
state.loadStandardLibrary();
state["didCollect"] = false;
REQUIRE(state.runString(
"return setmetatable({}, {\n"
"__gc = function () didCollect = true end"
"})"
) == LUA_OK);
bool didCollect = state["didCollect"];
REQUIRE(!didCollect);
{
RefLifecycle ref(state, -1);
lua_pop(state, 1);
didCollect = state["didCollect"];
REQUIRE(!didCollect);
lua_gc(state, LUA_GCCOLLECT, 0);
didCollect = state["didCollect"];
REQUIRE(!didCollect);
}
lua_gc(state, LUA_GCCOLLECT, 0);
didCollect = state["didCollect"];
REQUIRE(didCollect);
}
<commit_msg>tests: Fix tests for 'RefLifecycle'<commit_after>#include <catch.hpp>
#include <luwra.hpp>
#include <iostream>
using namespace luwra;
// Set the referenced boolean to true upon garbage collection
struct GCTrigger {
bool& target;
GCTrigger(bool& target): target(target) {
target = false;
}
~GCTrigger() {
target = true;
}
};
TEST_CASE("RefLifecycle") {
StateWrapper state;
state.loadStandardLibrary();
state.registerUserType<GCTrigger>();
bool didCollect;
// We instantiate a type which will set didCollect to true upon garbage collection
construct<GCTrigger>(state, didCollect);
// didCollect starts off as false
REQUIRE(!didCollect);
{
// Create the reference
RefLifecycle refLife(state, -1);
// Remove the user data from the stack and perform a full garbage collection cycle
lua_pop(state, 1);
lua_gc(state, LUA_GCCOLLECT, 0);
// Since the reference still exists, the user data must not have been collected
REQUIRE(!didCollect);
}
// Our reference goes out of scope, therefore making the user data unreachable. In order to
// trigger the finalizers, we must collect the dead user data.
lua_gc(state, LUA_GCCOLLECT, 0);
// At this point, the finalizer should have been invoked
REQUIRE(didCollect);
}
<|endoftext|>
|
<commit_before>#include "itkCommandLineArgumentParser.h"
#include "itkImage.h"
#include "itkRescaleIntensityImageFilter.h"
//#include "itkNumericTraits.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
//-------------------------------------------------------------------------------------
/** run: A macro to call a function. */
#define run(function,type,dim) \
if ( PixelType == #type && Dimension == #dim ) \
{ \
typedef itk::Image< type, dim > InputImageType; \
function< InputImageType >( inputFileName, outputFileName, minimum, maximum ); \
}
//-------------------------------------------------------------------------------------
/** Declare resizeImage. */
template< class InputImageType >
void rescaleIntensity( std::string inputFileName, std::string outputFileName, double minimum, double maximum );
//-------------------------------------------------------------------------------------
int main( int argc, char **argv )
{
/** Check number of arguments. */
if ( argc < 3 || argc > 11 || argv[ 1 ] == "--help" )
{
std::cout << "Usage:" << std::endl;
std::cout << "\tpxrescaleintensityimagefilter -in inputfilename [-out outputfilename] [-mm minimum maximum] [-dim Dimension] [-pt PixelType]" << std::endl;
std::cout << "Defaults: Dimension = 2, PixelType = short, out = in + INTENSITYRESCALED." << std::endl;
std::cout << "Supported: 2D, 3D, (unsigned) short, (unsigned) char." << std::endl;
return 1;
}
/** Create a command line argument parser. */
itk::CommandLineArgumentParser::Pointer parser = itk::CommandLineArgumentParser::New();
parser->SetCommandLineArguments( argc, argv );
/** Get arguments. */
std::string inputFileName = "";
bool ret1 = parser->GetCommandLineArgument( "-in", inputFileName );
std::string outputFileName = inputFileName.substr( 0, inputFileName.rfind( "." ) );
outputFileName += "INTENSITYRESCALED.mhd";
bool ret2 = parser->GetCommandLineArgument( "-out", outputFileName );
std::vector<double> extrema(2);
extrema[ 0 ] = 0.0; extrema[ 1 ] = 0.0;
bool ret3 = parser->GetCommandLineArgument( "-mm", extrema );
double minimum = extrema[ 0 ];
double maximum = extrema[ 1 ];
std::string Dimension = "2";
bool ret4 = parser->GetCommandLineArgument( "-dim", Dimension );
std::string PixelType = "short";
bool ret5 = parser->GetCommandLineArgument( "-pt", PixelType );
/** Check if the required arguments are given. */
if ( !ret1 )
{
std::cerr << "ERROR: You should specify \"-in\"." << std::endl;
return 1;
}
/** Check if the extrema are given (correctly). */
if ( ret3 )
{
if ( extrema.size() != 2 )
{
std::cerr << "ERROR: You should specify \"-mm\" with two values." << std::endl;
return 1;
}
if ( extrema[ 1 ] <= extrema[ 0 ] )
{
std::cerr << "ERROR: You should specify \"-mm\" with two values:" << std::endl;
std::cerr << "minimum maximum, where it should hold that maximum > minimum." << std::endl;
return 1;
}
}
/** Get rid of the possible "_" in PixelType. */
std::basic_string<char>::size_type pos = PixelType.find( "_" );
static const std::basic_string<char>::size_type npos = std::basic_string<char>::npos;
if ( pos != npos )
{
PixelType.replace( pos, 1, " " );
}
/** Run the program. */
try
{
run(rescaleIntensity,unsigned char,2);
run(rescaleIntensity,unsigned char,3);
run(rescaleIntensity,char,2);
run(rescaleIntensity,char,3);
run(rescaleIntensity,unsigned short,2);
run(rescaleIntensity,unsigned short,3);
run(rescaleIntensity,short,2);
run(rescaleIntensity,short,3);
}
catch( itk::ExceptionObject &e )
{
std::cerr << "Caught ITK exception: " << e << std::endl;
return 1;
}
/** End program. */
return 0;
} // end main
/**
* ******************* resizeImage *******************
*
* The rescaleIntensity function templated over the input pixel type.
*/
template< class InputImageType >
void rescaleIntensity( std::string inputFileName, std::string outputFileName, double minimum, double maximum )
{
/** TYPEDEF's. */
typedef itk::RescaleIntensityImageFilter< InputImageType, InputImageType > RescalerType;
typedef itk::ImageFileReader< InputImageType > ReaderType;
typedef itk::ImageFileWriter< InputImageType > WriterType;
typedef typename InputImageType::PixelType PixelType;
/** DECLARATION'S. */
typename RescalerType::Pointer rescaler = RescalerType::New();
typename ReaderType::Pointer reader = ReaderType::New();
typename WriterType::Pointer writer = WriterType::New();
/** Define the extrema. */
PixelType min, max;
if ( minimum == 0.0 && maximum == 0.0 )
{
min = itk::NumericTraits<PixelType>::min();
max = itk::NumericTraits<PixelType>::max();
}
else
{
min = static_cast<PixelType>( minimum );
max = static_cast<PixelType>( maximum );
}
/** Read in the inputImage. */
reader->SetFileName( inputFileName.c_str() );
/** Setup the rescaler. */
rescaler->SetInput( reader->GetOutput() );
rescaler->SetOutputMinimum( min );
rescaler->SetOutputMaximum( max );
/** Write the output image. */
writer->SetFileName( outputFileName.c_str() );
writer->SetInput( rescaler->GetOutput() );
writer->Update();
} // end rescaleIntensity
<commit_msg>SK:<commit_after>#include "itkCommandLineArgumentParser.h"
#include "itkImage.h"
#include "itkRescaleIntensityImageFilter.h"
//#include "itkNumericTraits.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
//-------------------------------------------------------------------------------------
/** run: A macro to call a function. */
#define run(function,type,dim) \
if ( PixelType == #type && Dimension == #dim ) \
{ \
typedef itk::Image< type, dim > InputImageType; \
function< InputImageType >( inputFileName, outputFileName, minimum, maximum ); \
}
//-------------------------------------------------------------------------------------
/** Declare resizeImage. */
template< class InputImageType >
void rescaleIntensity( std::string inputFileName, std::string outputFileName, double minimum, double maximum );
//-------------------------------------------------------------------------------------
int main( int argc, char **argv )
{
/** Check number of arguments. */
if ( argc < 3 || argc > 12 || argv[ 1 ] == "--help" )
{
std::cout << "Usage:" << std::endl;
std::cout << "\tpxrescaleintensityimagefilter -in inputfilename [-out outputfilename] [-mm minimum maximum] [-dim Dimension] [-pt PixelType]" << std::endl;
std::cout << "Defaults: Dimension = 2, PixelType = short, out = in + INTENSITYRESCALED." << std::endl;
std::cout << "Supported: 2D, 3D, (unsigned) short, (unsigned) char." << std::endl;
return 1;
}
/** Create a command line argument parser. */
itk::CommandLineArgumentParser::Pointer parser = itk::CommandLineArgumentParser::New();
parser->SetCommandLineArguments( argc, argv );
/** Get arguments. */
std::string inputFileName = "";
bool ret1 = parser->GetCommandLineArgument( "-in", inputFileName );
std::string outputFileName = inputFileName.substr( 0, inputFileName.rfind( "." ) );
outputFileName += "INTENSITYRESCALED.mhd";
bool ret2 = parser->GetCommandLineArgument( "-out", outputFileName );
std::vector<double> extrema(2);
extrema[ 0 ] = 0.0; extrema[ 1 ] = 0.0;
bool ret3 = parser->GetCommandLineArgument( "-mm", extrema );
double minimum = extrema[ 0 ];
double maximum = extrema[ 1 ];
std::string Dimension = "2";
bool ret4 = parser->GetCommandLineArgument( "-dim", Dimension );
std::string PixelType = "short";
bool ret5 = parser->GetCommandLineArgument( "-pt", PixelType );
/** Check if the required arguments are given. */
if ( !ret1 )
{
std::cerr << "ERROR: You should specify \"-in\"." << std::endl;
return 1;
}
/** Check if the extrema are given (correctly). */
if ( ret3 )
{
if ( extrema.size() != 2 )
{
std::cerr << "ERROR: You should specify \"-mm\" with two values." << std::endl;
return 1;
}
if ( extrema[ 1 ] <= extrema[ 0 ] )
{
std::cerr << "ERROR: You should specify \"-mm\" with two values:" << std::endl;
std::cerr << "minimum maximum, where it should hold that maximum > minimum." << std::endl;
return 1;
}
}
/** Get rid of the possible "_" in PixelType. */
std::basic_string<char>::size_type pos = PixelType.find( "_" );
static const std::basic_string<char>::size_type npos = std::basic_string<char>::npos;
if ( pos != npos )
{
PixelType.replace( pos, 1, " " );
}
/** Run the program. */
try
{
run(rescaleIntensity,unsigned char,2);
run(rescaleIntensity,unsigned char,3);
run(rescaleIntensity,char,2);
run(rescaleIntensity,char,3);
run(rescaleIntensity,unsigned short,2);
run(rescaleIntensity,unsigned short,3);
run(rescaleIntensity,short,2);
run(rescaleIntensity,short,3);
}
catch( itk::ExceptionObject &e )
{
std::cerr << "Caught ITK exception: " << e << std::endl;
return 1;
}
/** End program. */
return 0;
} // end main
/**
* ******************* resizeImage *******************
*
* The rescaleIntensity function templated over the input pixel type.
*/
template< class InputImageType >
void rescaleIntensity( std::string inputFileName, std::string outputFileName, double minimum, double maximum )
{
/** TYPEDEF's. */
typedef itk::RescaleIntensityImageFilter< InputImageType, InputImageType > RescalerType;
typedef itk::ImageFileReader< InputImageType > ReaderType;
typedef itk::ImageFileWriter< InputImageType > WriterType;
typedef typename InputImageType::PixelType PixelType;
/** DECLARATION'S. */
typename RescalerType::Pointer rescaler = RescalerType::New();
typename ReaderType::Pointer reader = ReaderType::New();
typename WriterType::Pointer writer = WriterType::New();
/** Define the extrema. */
PixelType min, max;
if ( minimum == 0.0 && maximum == 0.0 )
{
min = itk::NumericTraits<PixelType>::min();
max = itk::NumericTraits<PixelType>::max();
}
else
{
min = static_cast<PixelType>( minimum );
max = static_cast<PixelType>( maximum );
}
/** Read in the inputImage. */
reader->SetFileName( inputFileName.c_str() );
/** Setup the rescaler. */
rescaler->SetInput( reader->GetOutput() );
rescaler->SetOutputMinimum( min );
rescaler->SetOutputMaximum( max );
/** Write the output image. */
writer->SetFileName( outputFileName.c_str() );
writer->SetInput( rescaler->GetOutput() );
writer->Update();
} // end rescaleIntensity
<|endoftext|>
|
<commit_before>//===-- PrologEpilogInserter.cpp - Insert Prolog/Epilog code in function --===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This pass is responsible for finalizing the functions frame layout, saving
// callee saved registers, and for emitting prolog & epilog code for the
// function.
//
// This pass must be run after register allocation. After this pass is
// executed, it is illegal to construct MO_FrameIndex operands.
//
//===----------------------------------------------------------------------===//
#include "llvm/CodeGen/Passes.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/MachineInstr.h"
#include "llvm/CodeGen/MachineFrameInfo.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/MRegisterInfo.h"
#include "llvm/Target/TargetFrameInfo.h"
#include "llvm/Target/TargetInstrInfo.h"
#include "llvm/Support/Compiler.h"
using namespace llvm;
namespace {
struct VISIBILITY_HIDDEN PEI : public MachineFunctionPass {
const char *getPassName() const {
return "Prolog/Epilog Insertion & Frame Finalization";
}
/// runOnMachineFunction - Insert prolog/epilog code and replace abstract
/// frame indexes with appropriate references.
///
bool runOnMachineFunction(MachineFunction &Fn) {
// Get MachineDebugInfo so that we can track the construction of the
// frame.
if (MachineDebugInfo *DI = getAnalysisToUpdate<MachineDebugInfo>()) {
Fn.getFrameInfo()->setMachineDebugInfo(DI);
}
// Scan the function for modified caller saved registers and insert spill
// code for any caller saved registers that are modified. Also calculate
// the MaxCallFrameSize and HasCalls variables for the function's frame
// information and eliminates call frame pseudo instructions.
calculateCallerSavedRegisters(Fn);
// Add the code to save and restore the caller saved registers
saveCallerSavedRegisters(Fn);
// Allow the target machine to make final modifications to the function
// before the frame layout is finalized.
Fn.getTarget().getRegisterInfo()->processFunctionBeforeFrameFinalized(Fn);
// Calculate actual frame offsets for all of the abstract stack objects...
calculateFrameObjectOffsets(Fn);
// Add prolog and epilog code to the function. This function is required
// to align the stack frame as necessary for any stack variables or
// called functions. Because of this, calculateCallerSavedRegisters
// must be called before this function in order to set the HasCalls
// and MaxCallFrameSize variables.
insertPrologEpilogCode(Fn);
// Replace all MO_FrameIndex operands with physical register references
// and actual offsets.
//
replaceFrameIndices(Fn);
return true;
}
private:
void calculateCallerSavedRegisters(MachineFunction &Fn);
void saveCallerSavedRegisters(MachineFunction &Fn);
void calculateFrameObjectOffsets(MachineFunction &Fn);
void replaceFrameIndices(MachineFunction &Fn);
void insertPrologEpilogCode(MachineFunction &Fn);
};
}
/// createPrologEpilogCodeInserter - This function returns a pass that inserts
/// prolog and epilog code, and eliminates abstract frame references.
///
FunctionPass *llvm::createPrologEpilogCodeInserter() { return new PEI(); }
/// calculateCallerSavedRegisters - Scan the function for modified caller saved
/// registers. Also calculate the MaxCallFrameSize and HasCalls variables for
/// the function's frame information and eliminates call frame pseudo
/// instructions.
///
void PEI::calculateCallerSavedRegisters(MachineFunction &Fn) {
const MRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo();
const TargetFrameInfo *TFI = Fn.getTarget().getFrameInfo();
// Get the callee saved register list...
const unsigned *CSRegs = RegInfo->getCalleeSaveRegs();
// Get the function call frame set-up and tear-down instruction opcode
int FrameSetupOpcode = RegInfo->getCallFrameSetupOpcode();
int FrameDestroyOpcode = RegInfo->getCallFrameDestroyOpcode();
// Early exit for targets which have no callee saved registers and no call
// frame setup/destroy pseudo instructions.
if ((CSRegs == 0 || CSRegs[0] == 0) &&
FrameSetupOpcode == -1 && FrameDestroyOpcode == -1)
return;
unsigned MaxCallFrameSize = 0;
bool HasCalls = false;
for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB)
for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); )
if (I->getOpcode() == FrameSetupOpcode ||
I->getOpcode() == FrameDestroyOpcode) {
assert(I->getNumOperands() >= 1 && "Call Frame Setup/Destroy Pseudo"
" instructions should have a single immediate argument!");
unsigned Size = I->getOperand(0).getImmedValue();
if (Size > MaxCallFrameSize) MaxCallFrameSize = Size;
HasCalls = true;
RegInfo->eliminateCallFramePseudoInstr(Fn, *BB, I++);
} else {
++I;
}
MachineFrameInfo *FFI = Fn.getFrameInfo();
FFI->setHasCalls(HasCalls);
FFI->setMaxCallFrameSize(MaxCallFrameSize);
// Now figure out which *callee saved* registers are modified by the current
// function, thus needing to be saved and restored in the prolog/epilog.
//
const bool *PhysRegsUsed = Fn.getUsedPhysregs();
const TargetRegisterClass* const *CSRegClasses =
RegInfo->getCalleeSaveRegClasses();
std::vector<CalleeSavedInfo> CSI;
for (unsigned i = 0; CSRegs[i]; ++i) {
unsigned Reg = CSRegs[i];
if (PhysRegsUsed[Reg]) {
// If the reg is modified, save it!
CSI.push_back(CalleeSavedInfo(Reg, CSRegClasses[i]));
} else {
for (const unsigned *AliasSet = RegInfo->getAliasSet(Reg);
*AliasSet; ++AliasSet) { // Check alias registers too.
if (PhysRegsUsed[*AliasSet]) {
CSI.push_back(CalleeSavedInfo(Reg, CSRegClasses[i]));
break;
}
}
}
}
if (CSI.empty())
return; // Early exit if no caller saved registers are modified!
unsigned NumFixedSpillSlots;
const std::pair<unsigned,int> *FixedSpillSlots =
TFI->getCalleeSaveSpillSlots(NumFixedSpillSlots);
// Now that we know which registers need to be saved and restored, allocate
// stack slots for them.
for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
unsigned Reg = CSI[i].getReg();
const TargetRegisterClass *RC = CSI[i].getRegClass();
// Check to see if this physreg must be spilled to a particular stack slot
// on this target.
const std::pair<unsigned,int> *FixedSlot = FixedSpillSlots;
while (FixedSlot != FixedSpillSlots+NumFixedSpillSlots &&
FixedSlot->first != Reg)
++FixedSlot;
int FrameIdx;
if (FixedSlot == FixedSpillSlots+NumFixedSpillSlots) {
// Nope, just spill it anywhere convenient.
FrameIdx = FFI->CreateStackObject(RC->getSize(), RC->getAlignment());
} else {
// Spill it to the stack where we must.
FrameIdx = FFI->CreateFixedObject(RC->getSize(), FixedSlot->second);
}
CSI[i].setFrameIdx(FrameIdx);
}
FFI->setCalleeSavedInfo(CSI);
}
/// saveCallerSavedRegisters - Insert spill code for any caller saved registers
/// that are modified in the function.
///
void PEI::saveCallerSavedRegisters(MachineFunction &Fn) {
// Get callee saved register information.
MachineFrameInfo *FFI = Fn.getFrameInfo();
const std::vector<CalleeSavedInfo> &CSI = FFI->getCalleeSavedInfo();
// Early exit if no caller saved registers are modified!
if (CSI.empty())
return;
const MRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo();
// Now that we have a stack slot for each register to be saved, insert spill
// code into the entry block.
MachineBasicBlock *MBB = Fn.begin();
MachineBasicBlock::iterator I = MBB->begin();
for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
// Insert the spill to the stack frame.
RegInfo->storeRegToStackSlot(*MBB, I, CSI[i].getReg(), CSI[i].getFrameIdx(),
CSI[i].getRegClass());
}
// Add code to restore the callee-save registers in each exiting block.
const TargetInstrInfo &TII = *Fn.getTarget().getInstrInfo();
for (MachineFunction::iterator FI = Fn.begin(), E = Fn.end(); FI != E; ++FI)
// If last instruction is a return instruction, add an epilogue.
if (!FI->empty() && TII.isReturn(FI->back().getOpcode())) {
MBB = FI;
I = MBB->end(); --I;
// Skip over all terminator instructions, which are part of the return
// sequence.
MachineBasicBlock::iterator I2 = I;
while (I2 != MBB->begin() && TII.isTerminatorInstr((--I2)->getOpcode()))
I = I2;
bool AtStart = I == MBB->begin();
MachineBasicBlock::iterator BeforeI = I;
if (!AtStart)
--BeforeI;
// Restore all registers immediately before the return and any terminators
// that preceed it.
for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
RegInfo->loadRegFromStackSlot(*MBB, I, CSI[i].getReg(),
CSI[i].getFrameIdx(),
CSI[i].getRegClass());
assert(I != MBB->begin() &&
"loadRegFromStackSlot didn't insert any code!");
// Insert in reverse order. loadRegFromStackSlot can insert multiple
// instructions.
if (AtStart)
I = MBB->begin();
else {
I = BeforeI;
++I;
}
}
}
}
/// calculateFrameObjectOffsets - Calculate actual frame offsets for all of the
/// abstract stack objects.
///
void PEI::calculateFrameObjectOffsets(MachineFunction &Fn) {
const TargetFrameInfo &TFI = *Fn.getTarget().getFrameInfo();
bool StackGrowsDown =
TFI.getStackGrowthDirection() == TargetFrameInfo::StackGrowsDown;
// Loop over all of the stack objects, assigning sequential addresses...
MachineFrameInfo *FFI = Fn.getFrameInfo();
unsigned StackAlignment = TFI.getStackAlignment();
unsigned MaxAlign = 0;
// Start at the beginning of the local area.
// The Offset is the distance from the stack top in the direction
// of stack growth -- so it's always positive.
int Offset = TFI.getOffsetOfLocalArea();
if (StackGrowsDown)
Offset = -Offset;
assert(Offset >= 0
&& "Local area offset should be in direction of stack growth");
// If there are fixed sized objects that are preallocated in the local area,
// non-fixed objects can't be allocated right at the start of local area.
// We currently don't support filling in holes in between fixed sized objects,
// so we adjust 'Offset' to point to the end of last fixed sized
// preallocated object.
for (int i = FFI->getObjectIndexBegin(); i != 0; ++i) {
int FixedOff;
if (StackGrowsDown) {
// The maximum distance from the stack pointer is at lower address of
// the object -- which is given by offset. For down growing stack
// the offset is negative, so we negate the offset to get the distance.
FixedOff = -FFI->getObjectOffset(i);
} else {
// The maximum distance from the start pointer is at the upper
// address of the object.
FixedOff = FFI->getObjectOffset(i) + FFI->getObjectSize(i);
}
if (FixedOff > Offset) Offset = FixedOff;
}
for (unsigned i = 0, e = FFI->getObjectIndexEnd(); i != e; ++i) {
// If stack grows down, we need to add size of find the lowest
// address of the object.
if (StackGrowsDown)
Offset += FFI->getObjectSize(i);
unsigned Align = FFI->getObjectAlignment(i);
// If the alignment of this object is greater than that of the stack, then
// increase the stack alignment to match.
MaxAlign = std::max(MaxAlign, Align);
// Adjust to alignment boundary
Offset = (Offset+Align-1)/Align*Align;
if (StackGrowsDown) {
FFI->setObjectOffset(i, -Offset); // Set the computed offset
} else {
FFI->setObjectOffset(i, Offset);
Offset += FFI->getObjectSize(i);
}
}
// Align the final stack pointer offset, but only if there are calls in the
// function. This ensures that any calls to subroutines have their stack
// frames suitable aligned.
if (FFI->hasCalls())
Offset = (Offset+StackAlignment-1)/StackAlignment*StackAlignment;
// Set the final value of the stack pointer...
FFI->setStackSize(Offset+TFI.getOffsetOfLocalArea());
// Remember the required stack alignment in case targets need it to perform
// dynamic stack alignment.
assert(FFI->getMaxAlignment() == MaxAlign &&
"Stack alignment calculation broken!");
}
/// insertPrologEpilogCode - Scan the function for modified caller saved
/// registers, insert spill code for these caller saved registers, then add
/// prolog and epilog code to the function.
///
void PEI::insertPrologEpilogCode(MachineFunction &Fn) {
// Add prologue to the function...
Fn.getTarget().getRegisterInfo()->emitPrologue(Fn);
// Add epilogue to restore the callee-save registers in each exiting block
const TargetInstrInfo &TII = *Fn.getTarget().getInstrInfo();
for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) {
// If last instruction is a return instruction, add an epilogue
if (!I->empty() && TII.isReturn(I->back().getOpcode()))
Fn.getTarget().getRegisterInfo()->emitEpilogue(Fn, *I);
}
}
/// replaceFrameIndices - Replace all MO_FrameIndex operands with physical
/// register references and actual offsets.
///
void PEI::replaceFrameIndices(MachineFunction &Fn) {
if (!Fn.getFrameInfo()->hasStackObjects()) return; // Nothing to do?
const TargetMachine &TM = Fn.getTarget();
assert(TM.getRegisterInfo() && "TM::getRegisterInfo() must be implemented!");
const MRegisterInfo &MRI = *TM.getRegisterInfo();
for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB)
for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ++I)
for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
if (I->getOperand(i).isFrameIndex()) {
// If this instruction has a FrameIndex operand, we need to use that
// target machine register info object to eliminate it.
MRI.eliminateFrameIndex(I);
break;
}
}
<commit_msg>Rename function. It's determining which callee-save registers to save.<commit_after>//===-- PrologEpilogInserter.cpp - Insert Prolog/Epilog code in function --===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This pass is responsible for finalizing the functions frame layout, saving
// callee saved registers, and for emitting prolog & epilog code for the
// function.
//
// This pass must be run after register allocation. After this pass is
// executed, it is illegal to construct MO_FrameIndex operands.
//
//===----------------------------------------------------------------------===//
#include "llvm/CodeGen/Passes.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/MachineInstr.h"
#include "llvm/CodeGen/MachineFrameInfo.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/MRegisterInfo.h"
#include "llvm/Target/TargetFrameInfo.h"
#include "llvm/Target/TargetInstrInfo.h"
#include "llvm/Support/Compiler.h"
using namespace llvm;
namespace {
struct VISIBILITY_HIDDEN PEI : public MachineFunctionPass {
const char *getPassName() const {
return "Prolog/Epilog Insertion & Frame Finalization";
}
/// runOnMachineFunction - Insert prolog/epilog code and replace abstract
/// frame indexes with appropriate references.
///
bool runOnMachineFunction(MachineFunction &Fn) {
// Get MachineDebugInfo so that we can track the construction of the
// frame.
if (MachineDebugInfo *DI = getAnalysisToUpdate<MachineDebugInfo>()) {
Fn.getFrameInfo()->setMachineDebugInfo(DI);
}
// Scan the function for modified callee saved registers and insert spill
// code for any callee saved registers that are modified. Also calculate
// the MaxCallFrameSize and HasCalls variables for the function's frame
// information and eliminates call frame pseudo instructions.
calculateCalleeSavedRegisters(Fn);
// Add the code to save and restore the caller saved registers
saveCallerSavedRegisters(Fn);
// Allow the target machine to make final modifications to the function
// before the frame layout is finalized.
Fn.getTarget().getRegisterInfo()->processFunctionBeforeFrameFinalized(Fn);
// Calculate actual frame offsets for all of the abstract stack objects...
calculateFrameObjectOffsets(Fn);
// Add prolog and epilog code to the function. This function is required
// to align the stack frame as necessary for any stack variables or
// called functions. Because of this, calculateCalleeSavedRegisters
// must be called before this function in order to set the HasCalls
// and MaxCallFrameSize variables.
insertPrologEpilogCode(Fn);
// Replace all MO_FrameIndex operands with physical register references
// and actual offsets.
//
replaceFrameIndices(Fn);
return true;
}
private:
void calculateCalleeSavedRegisters(MachineFunction &Fn);
void saveCallerSavedRegisters(MachineFunction &Fn);
void calculateFrameObjectOffsets(MachineFunction &Fn);
void replaceFrameIndices(MachineFunction &Fn);
void insertPrologEpilogCode(MachineFunction &Fn);
};
}
/// createPrologEpilogCodeInserter - This function returns a pass that inserts
/// prolog and epilog code, and eliminates abstract frame references.
///
FunctionPass *llvm::createPrologEpilogCodeInserter() { return new PEI(); }
/// calculateCalleeSavedRegisters - Scan the function for modified caller saved
/// registers. Also calculate the MaxCallFrameSize and HasCalls variables for
/// the function's frame information and eliminates call frame pseudo
/// instructions.
///
void PEI::calculateCalleeSavedRegisters(MachineFunction &Fn) {
const MRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo();
const TargetFrameInfo *TFI = Fn.getTarget().getFrameInfo();
// Get the callee saved register list...
const unsigned *CSRegs = RegInfo->getCalleeSaveRegs();
// Get the function call frame set-up and tear-down instruction opcode
int FrameSetupOpcode = RegInfo->getCallFrameSetupOpcode();
int FrameDestroyOpcode = RegInfo->getCallFrameDestroyOpcode();
// Early exit for targets which have no callee saved registers and no call
// frame setup/destroy pseudo instructions.
if ((CSRegs == 0 || CSRegs[0] == 0) &&
FrameSetupOpcode == -1 && FrameDestroyOpcode == -1)
return;
unsigned MaxCallFrameSize = 0;
bool HasCalls = false;
for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB)
for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); )
if (I->getOpcode() == FrameSetupOpcode ||
I->getOpcode() == FrameDestroyOpcode) {
assert(I->getNumOperands() >= 1 && "Call Frame Setup/Destroy Pseudo"
" instructions should have a single immediate argument!");
unsigned Size = I->getOperand(0).getImmedValue();
if (Size > MaxCallFrameSize) MaxCallFrameSize = Size;
HasCalls = true;
RegInfo->eliminateCallFramePseudoInstr(Fn, *BB, I++);
} else {
++I;
}
MachineFrameInfo *FFI = Fn.getFrameInfo();
FFI->setHasCalls(HasCalls);
FFI->setMaxCallFrameSize(MaxCallFrameSize);
// Now figure out which *callee saved* registers are modified by the current
// function, thus needing to be saved and restored in the prolog/epilog.
//
const bool *PhysRegsUsed = Fn.getUsedPhysregs();
const TargetRegisterClass* const *CSRegClasses =
RegInfo->getCalleeSaveRegClasses();
std::vector<CalleeSavedInfo> CSI;
for (unsigned i = 0; CSRegs[i]; ++i) {
unsigned Reg = CSRegs[i];
if (PhysRegsUsed[Reg]) {
// If the reg is modified, save it!
CSI.push_back(CalleeSavedInfo(Reg, CSRegClasses[i]));
} else {
for (const unsigned *AliasSet = RegInfo->getAliasSet(Reg);
*AliasSet; ++AliasSet) { // Check alias registers too.
if (PhysRegsUsed[*AliasSet]) {
CSI.push_back(CalleeSavedInfo(Reg, CSRegClasses[i]));
break;
}
}
}
}
if (CSI.empty())
return; // Early exit if no caller saved registers are modified!
unsigned NumFixedSpillSlots;
const std::pair<unsigned,int> *FixedSpillSlots =
TFI->getCalleeSaveSpillSlots(NumFixedSpillSlots);
// Now that we know which registers need to be saved and restored, allocate
// stack slots for them.
for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
unsigned Reg = CSI[i].getReg();
const TargetRegisterClass *RC = CSI[i].getRegClass();
// Check to see if this physreg must be spilled to a particular stack slot
// on this target.
const std::pair<unsigned,int> *FixedSlot = FixedSpillSlots;
while (FixedSlot != FixedSpillSlots+NumFixedSpillSlots &&
FixedSlot->first != Reg)
++FixedSlot;
int FrameIdx;
if (FixedSlot == FixedSpillSlots+NumFixedSpillSlots) {
// Nope, just spill it anywhere convenient.
FrameIdx = FFI->CreateStackObject(RC->getSize(), RC->getAlignment());
} else {
// Spill it to the stack where we must.
FrameIdx = FFI->CreateFixedObject(RC->getSize(), FixedSlot->second);
}
CSI[i].setFrameIdx(FrameIdx);
}
FFI->setCalleeSavedInfo(CSI);
}
/// saveCallerSavedRegisters - Insert spill code for any caller saved registers
/// that are modified in the function.
///
void PEI::saveCallerSavedRegisters(MachineFunction &Fn) {
// Get callee saved register information.
MachineFrameInfo *FFI = Fn.getFrameInfo();
const std::vector<CalleeSavedInfo> &CSI = FFI->getCalleeSavedInfo();
// Early exit if no caller saved registers are modified!
if (CSI.empty())
return;
const MRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo();
// Now that we have a stack slot for each register to be saved, insert spill
// code into the entry block.
MachineBasicBlock *MBB = Fn.begin();
MachineBasicBlock::iterator I = MBB->begin();
for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
// Insert the spill to the stack frame.
RegInfo->storeRegToStackSlot(*MBB, I, CSI[i].getReg(), CSI[i].getFrameIdx(),
CSI[i].getRegClass());
}
// Add code to restore the callee-save registers in each exiting block.
const TargetInstrInfo &TII = *Fn.getTarget().getInstrInfo();
for (MachineFunction::iterator FI = Fn.begin(), E = Fn.end(); FI != E; ++FI)
// If last instruction is a return instruction, add an epilogue.
if (!FI->empty() && TII.isReturn(FI->back().getOpcode())) {
MBB = FI;
I = MBB->end(); --I;
// Skip over all terminator instructions, which are part of the return
// sequence.
MachineBasicBlock::iterator I2 = I;
while (I2 != MBB->begin() && TII.isTerminatorInstr((--I2)->getOpcode()))
I = I2;
bool AtStart = I == MBB->begin();
MachineBasicBlock::iterator BeforeI = I;
if (!AtStart)
--BeforeI;
// Restore all registers immediately before the return and any terminators
// that preceed it.
for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
RegInfo->loadRegFromStackSlot(*MBB, I, CSI[i].getReg(),
CSI[i].getFrameIdx(),
CSI[i].getRegClass());
assert(I != MBB->begin() &&
"loadRegFromStackSlot didn't insert any code!");
// Insert in reverse order. loadRegFromStackSlot can insert multiple
// instructions.
if (AtStart)
I = MBB->begin();
else {
I = BeforeI;
++I;
}
}
}
}
/// calculateFrameObjectOffsets - Calculate actual frame offsets for all of the
/// abstract stack objects.
///
void PEI::calculateFrameObjectOffsets(MachineFunction &Fn) {
const TargetFrameInfo &TFI = *Fn.getTarget().getFrameInfo();
bool StackGrowsDown =
TFI.getStackGrowthDirection() == TargetFrameInfo::StackGrowsDown;
// Loop over all of the stack objects, assigning sequential addresses...
MachineFrameInfo *FFI = Fn.getFrameInfo();
unsigned StackAlignment = TFI.getStackAlignment();
unsigned MaxAlign = 0;
// Start at the beginning of the local area.
// The Offset is the distance from the stack top in the direction
// of stack growth -- so it's always positive.
int Offset = TFI.getOffsetOfLocalArea();
if (StackGrowsDown)
Offset = -Offset;
assert(Offset >= 0
&& "Local area offset should be in direction of stack growth");
// If there are fixed sized objects that are preallocated in the local area,
// non-fixed objects can't be allocated right at the start of local area.
// We currently don't support filling in holes in between fixed sized objects,
// so we adjust 'Offset' to point to the end of last fixed sized
// preallocated object.
for (int i = FFI->getObjectIndexBegin(); i != 0; ++i) {
int FixedOff;
if (StackGrowsDown) {
// The maximum distance from the stack pointer is at lower address of
// the object -- which is given by offset. For down growing stack
// the offset is negative, so we negate the offset to get the distance.
FixedOff = -FFI->getObjectOffset(i);
} else {
// The maximum distance from the start pointer is at the upper
// address of the object.
FixedOff = FFI->getObjectOffset(i) + FFI->getObjectSize(i);
}
if (FixedOff > Offset) Offset = FixedOff;
}
for (unsigned i = 0, e = FFI->getObjectIndexEnd(); i != e; ++i) {
// If stack grows down, we need to add size of find the lowest
// address of the object.
if (StackGrowsDown)
Offset += FFI->getObjectSize(i);
unsigned Align = FFI->getObjectAlignment(i);
// If the alignment of this object is greater than that of the stack, then
// increase the stack alignment to match.
MaxAlign = std::max(MaxAlign, Align);
// Adjust to alignment boundary
Offset = (Offset+Align-1)/Align*Align;
if (StackGrowsDown) {
FFI->setObjectOffset(i, -Offset); // Set the computed offset
} else {
FFI->setObjectOffset(i, Offset);
Offset += FFI->getObjectSize(i);
}
}
// Align the final stack pointer offset, but only if there are calls in the
// function. This ensures that any calls to subroutines have their stack
// frames suitable aligned.
if (FFI->hasCalls())
Offset = (Offset+StackAlignment-1)/StackAlignment*StackAlignment;
// Set the final value of the stack pointer...
FFI->setStackSize(Offset+TFI.getOffsetOfLocalArea());
// Remember the required stack alignment in case targets need it to perform
// dynamic stack alignment.
assert(FFI->getMaxAlignment() == MaxAlign &&
"Stack alignment calculation broken!");
}
/// insertPrologEpilogCode - Scan the function for modified caller saved
/// registers, insert spill code for these caller saved registers, then add
/// prolog and epilog code to the function.
///
void PEI::insertPrologEpilogCode(MachineFunction &Fn) {
// Add prologue to the function...
Fn.getTarget().getRegisterInfo()->emitPrologue(Fn);
// Add epilogue to restore the callee-save registers in each exiting block
const TargetInstrInfo &TII = *Fn.getTarget().getInstrInfo();
for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) {
// If last instruction is a return instruction, add an epilogue
if (!I->empty() && TII.isReturn(I->back().getOpcode()))
Fn.getTarget().getRegisterInfo()->emitEpilogue(Fn, *I);
}
}
/// replaceFrameIndices - Replace all MO_FrameIndex operands with physical
/// register references and actual offsets.
///
void PEI::replaceFrameIndices(MachineFunction &Fn) {
if (!Fn.getFrameInfo()->hasStackObjects()) return; // Nothing to do?
const TargetMachine &TM = Fn.getTarget();
assert(TM.getRegisterInfo() && "TM::getRegisterInfo() must be implemented!");
const MRegisterInfo &MRI = *TM.getRegisterInfo();
for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB)
for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ++I)
for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
if (I->getOperand(i).isFrameIndex()) {
// If this instruction has a FrameIndex operand, we need to use that
// target machine register info object to eliminate it.
MRI.eliminateFrameIndex(I);
break;
}
}
<|endoftext|>
|
<commit_before>//===- StrongPhiElimination.cpp - Eliminate PHI nodes by inserting copies -===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by Owen Anderson and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This pass eliminates machine instruction PHI nodes by inserting copy
// instructions, using an intelligent copy-folding technique based on
// dominator information. This is technique is derived from:
//
// Budimlic, et al. Fast copy coalescing and live-range identification.
// In Proceedings of the ACM SIGPLAN 2002 Conference on Programming Language
// Design and Implementation (Berlin, Germany, June 17 - 19, 2002).
// PLDI '02. ACM, New York, NY, 25-32.
// DOI= http://doi.acm.org/10.1145/512529.512534
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "strongphielim"
#include "llvm/CodeGen/Passes.h"
#include "llvm/CodeGen/LiveVariables.h"
#include "llvm/CodeGen/MachineDominators.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/MachineInstr.h"
#include "llvm/Target/TargetInstrInfo.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Support/Compiler.h"
using namespace llvm;
namespace {
struct VISIBILITY_HIDDEN StrongPHIElimination : public MachineFunctionPass {
static char ID; // Pass identification, replacement for typeid
StrongPHIElimination() : MachineFunctionPass((intptr_t)&ID) {}
bool runOnMachineFunction(MachineFunction &Fn);
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.addPreserved<LiveVariables>();
AU.addPreservedID(PHIEliminationID);
AU.addRequired<MachineDominatorTree>();
AU.addRequired<LiveVariables>();
AU.setPreservesAll();
MachineFunctionPass::getAnalysisUsage(AU);
}
virtual void releaseMemory() {
preorder.clear();
maxpreorder.clear();
waiting.clear();
}
private:
struct DomForestNode {
private:
std::vector<DomForestNode*> children;
unsigned reg;
void addChild(DomForestNode* DFN) { children.push_back(DFN); }
public:
typedef std::vector<DomForestNode*>::iterator iterator;
DomForestNode(unsigned r, DomForestNode* parent) : reg(r) {
if (parent)
parent->addChild(this);
}
~DomForestNode() {
for (iterator I = begin(), E = end(); I != E; ++I)
delete *I;
}
inline unsigned getReg() { return reg; }
inline DomForestNode::iterator begin() { return children.begin(); }
inline DomForestNode::iterator end() { return children.end(); }
};
DenseMap<MachineBasicBlock*, unsigned> preorder;
DenseMap<MachineBasicBlock*, unsigned> maxpreorder;
DenseMap<MachineBasicBlock*, std::vector<MachineInstr*> > waiting;
void computeDFS(MachineFunction& MF);
void processBlock(MachineBasicBlock* MBB);
std::vector<DomForestNode*> computeDomForest(std::set<unsigned>& instrs);
};
char StrongPHIElimination::ID = 0;
RegisterPass<StrongPHIElimination> X("strong-phi-node-elimination",
"Eliminate PHI nodes for register allocation, intelligently");
}
const PassInfo *llvm::StrongPHIEliminationID = X.getPassInfo();
/// computeDFS - Computes the DFS-in and DFS-out numbers of the dominator tree
/// of the given MachineFunction. These numbers are then used in other parts
/// of the PHI elimination process.
void StrongPHIElimination::computeDFS(MachineFunction& MF) {
SmallPtrSet<MachineDomTreeNode*, 8> frontier;
SmallPtrSet<MachineDomTreeNode*, 8> visited;
unsigned time = 0;
MachineDominatorTree& DT = getAnalysis<MachineDominatorTree>();
MachineDomTreeNode* node = DT.getRootNode();
std::vector<MachineDomTreeNode*> worklist;
worklist.push_back(node);
while (!worklist.empty()) {
MachineDomTreeNode* currNode = worklist.back();
if (!frontier.count(currNode)) {
frontier.insert(currNode);
++time;
preorder.insert(std::make_pair(currNode->getBlock(), time));
}
bool inserted = false;
for (MachineDomTreeNode::iterator I = node->begin(), E = node->end();
I != E; ++I)
if (!frontier.count(*I) && !visited.count(*I)) {
worklist.push_back(*I);
inserted = true;
break;
}
if (!inserted) {
frontier.erase(currNode);
visited.insert(currNode);
maxpreorder.insert(std::make_pair(currNode->getBlock(), time));
worklist.pop_back();
}
}
}
/// PreorderSorter - a helper class that is used to sort registers
/// according to the preorder number of their defining blocks
class PreorderSorter {
private:
DenseMap<MachineBasicBlock*, unsigned>& preorder;
LiveVariables& LV;
public:
PreorderSorter(DenseMap<MachineBasicBlock*, unsigned>& p,
LiveVariables& L) : preorder(p), LV(L) { }
bool operator()(unsigned A, unsigned B) {
if (A == B)
return false;
MachineBasicBlock* ABlock = LV.getVarInfo(A).DefInst->getParent();
MachineBasicBlock* BBlock = LV.getVarInfo(A).DefInst->getParent();
if (preorder[ABlock] < preorder[BBlock])
return true;
else if (preorder[ABlock] > preorder[BBlock])
return false;
assert(0 && "Error sorting by dominance!");
return false;
}
};
/// computeDomForest - compute the subforest of the DomTree corresponding
/// to the defining blocks of the registers in question
std::vector<StrongPHIElimination::DomForestNode*>
StrongPHIElimination::computeDomForest(std::set<unsigned>& regs) {
LiveVariables& LV = getAnalysis<LiveVariables>();
DomForestNode* VirtualRoot = new DomForestNode(0, 0);
maxpreorder.insert(std::make_pair((MachineBasicBlock*)0, ~0UL));
std::vector<unsigned> worklist;
worklist.reserve(regs.size());
for (std::set<unsigned>::iterator I = regs.begin(), E = regs.end();
I != E; ++I)
worklist.push_back(*I);
PreorderSorter PS(preorder, LV);
std::sort(worklist.begin(), worklist.end(), PS);
DomForestNode* CurrentParent = VirtualRoot;
std::vector<DomForestNode*> stack;
stack.push_back(VirtualRoot);
for (std::vector<unsigned>::iterator I = worklist.begin(), E = worklist.end();
I != E; ++I) {
unsigned pre = preorder[LV.getVarInfo(*I).DefInst->getParent()];
MachineBasicBlock* parentBlock =
LV.getVarInfo(CurrentParent->getReg()).DefInst->getParent();
while (pre > maxpreorder[parentBlock]) {
stack.pop_back();
CurrentParent = stack.back();
parentBlock = LV.getVarInfo(CurrentParent->getReg()).DefInst->getParent();
}
DomForestNode* child = new DomForestNode(*I, CurrentParent);
stack.push_back(child);
CurrentParent = child;
}
std::vector<DomForestNode*> ret;
ret.insert(ret.end(), VirtualRoot->begin(), VirtualRoot->end());
return ret;
}
/// isLiveIn - helper method that determines, from a VarInfo, if a register
/// is live into a block
bool isLiveIn(LiveVariables::VarInfo& V, MachineBasicBlock* MBB) {
if (V.AliveBlocks.test(MBB->getNumber()))
return true;
for (std::vector<MachineInstr*>::iterator I = V.Kills.begin(),
E = V.Kills.end(); I != E; ++I)
if ((*I)->getParent() == MBB)
return true;
return false;
}
/// isLiveOut - help method that determines, from a VarInfo, if a register is
/// live out of a block.
bool isLiveOut(LiveVariables::VarInfo& V, MachineBasicBlock* MBB) {
if (V.AliveBlocks.test(MBB->getNumber()))
return true;
if (V.DefInst->getParent() == MBB)
return true;
return false;
}
/// processBlock - Eliminate PHIs in the given block
void StrongPHIElimination::processBlock(MachineBasicBlock* MBB) {
LiveVariables& LV = getAnalysis<LiveVariables>();
// Holds names that have been added to a set in any PHI within this block
// before the current one.
std::set<unsigned> ProcessedNames;
MachineBasicBlock::iterator P = MBB->begin();
while (P->getOpcode() == TargetInstrInfo::PHI) {
LiveVariables::VarInfo& PHIInfo = LV.getVarInfo(P->getOperand(0).getReg());
// Hold the names that are currently in the candidate set.
std::set<unsigned> PHIUnion;
std::set<MachineBasicBlock*> UnionedBlocks;
for (int i = P->getNumOperands() - 1; i >= 2; i-=2) {
unsigned SrcReg = P->getOperand(i-1).getReg();
LiveVariables::VarInfo& SrcInfo = LV.getVarInfo(SrcReg);
if (isLiveIn(SrcInfo, P->getParent())) {
// add a copy from a_i to p in Waiting[From[a_i]]
} else if (isLiveOut(PHIInfo, SrcInfo.DefInst->getParent())) {
// add a copy to Waiting[From[a_i]]
} else if (PHIInfo.DefInst->getOpcode() == TargetInstrInfo::PHI &&
isLiveIn(PHIInfo, SrcInfo.DefInst->getParent())) {
// add a copy to Waiting[From[a_i]]
} else if (ProcessedNames.count(SrcReg)) {
// add a copy to Waiting[From[a_i]]
} else if (UnionedBlocks.count(SrcInfo.DefInst->getParent())) {
// add a copy to Waiting[From[a_i]]
} else {
PHIUnion.insert(SrcReg);
UnionedBlocks.insert(SrcInfo.DefInst->getParent());
// DO STUFF HERE
}
ProcessedNames.insert(PHIUnion.begin(), PHIUnion.end());
}
++P;
}
}
bool StrongPHIElimination::runOnMachineFunction(MachineFunction &Fn) {
computeDFS(Fn);
for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
if (!I->empty() &&
I->begin()->getOpcode() == TargetInstrInfo::PHI)
processBlock(I);
return false;
}
<commit_msg>Take another stab at getting isLiveIn() and isLiveOut() right.<commit_after>//===- StrongPhiElimination.cpp - Eliminate PHI nodes by inserting copies -===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by Owen Anderson and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This pass eliminates machine instruction PHI nodes by inserting copy
// instructions, using an intelligent copy-folding technique based on
// dominator information. This is technique is derived from:
//
// Budimlic, et al. Fast copy coalescing and live-range identification.
// In Proceedings of the ACM SIGPLAN 2002 Conference on Programming Language
// Design and Implementation (Berlin, Germany, June 17 - 19, 2002).
// PLDI '02. ACM, New York, NY, 25-32.
// DOI= http://doi.acm.org/10.1145/512529.512534
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "strongphielim"
#include "llvm/CodeGen/Passes.h"
#include "llvm/CodeGen/LiveVariables.h"
#include "llvm/CodeGen/MachineDominators.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/MachineInstr.h"
#include "llvm/Target/TargetInstrInfo.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Support/Compiler.h"
using namespace llvm;
namespace {
struct VISIBILITY_HIDDEN StrongPHIElimination : public MachineFunctionPass {
static char ID; // Pass identification, replacement for typeid
StrongPHIElimination() : MachineFunctionPass((intptr_t)&ID) {}
bool runOnMachineFunction(MachineFunction &Fn);
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.addPreserved<LiveVariables>();
AU.addPreservedID(PHIEliminationID);
AU.addRequired<MachineDominatorTree>();
AU.addRequired<LiveVariables>();
AU.setPreservesAll();
MachineFunctionPass::getAnalysisUsage(AU);
}
virtual void releaseMemory() {
preorder.clear();
maxpreorder.clear();
waiting.clear();
}
private:
struct DomForestNode {
private:
std::vector<DomForestNode*> children;
unsigned reg;
void addChild(DomForestNode* DFN) { children.push_back(DFN); }
public:
typedef std::vector<DomForestNode*>::iterator iterator;
DomForestNode(unsigned r, DomForestNode* parent) : reg(r) {
if (parent)
parent->addChild(this);
}
~DomForestNode() {
for (iterator I = begin(), E = end(); I != E; ++I)
delete *I;
}
inline unsigned getReg() { return reg; }
inline DomForestNode::iterator begin() { return children.begin(); }
inline DomForestNode::iterator end() { return children.end(); }
};
DenseMap<MachineBasicBlock*, unsigned> preorder;
DenseMap<MachineBasicBlock*, unsigned> maxpreorder;
DenseMap<MachineBasicBlock*, std::vector<MachineInstr*> > waiting;
void computeDFS(MachineFunction& MF);
void processBlock(MachineBasicBlock* MBB);
std::vector<DomForestNode*> computeDomForest(std::set<unsigned>& instrs);
};
char StrongPHIElimination::ID = 0;
RegisterPass<StrongPHIElimination> X("strong-phi-node-elimination",
"Eliminate PHI nodes for register allocation, intelligently");
}
const PassInfo *llvm::StrongPHIEliminationID = X.getPassInfo();
/// computeDFS - Computes the DFS-in and DFS-out numbers of the dominator tree
/// of the given MachineFunction. These numbers are then used in other parts
/// of the PHI elimination process.
void StrongPHIElimination::computeDFS(MachineFunction& MF) {
SmallPtrSet<MachineDomTreeNode*, 8> frontier;
SmallPtrSet<MachineDomTreeNode*, 8> visited;
unsigned time = 0;
MachineDominatorTree& DT = getAnalysis<MachineDominatorTree>();
MachineDomTreeNode* node = DT.getRootNode();
std::vector<MachineDomTreeNode*> worklist;
worklist.push_back(node);
while (!worklist.empty()) {
MachineDomTreeNode* currNode = worklist.back();
if (!frontier.count(currNode)) {
frontier.insert(currNode);
++time;
preorder.insert(std::make_pair(currNode->getBlock(), time));
}
bool inserted = false;
for (MachineDomTreeNode::iterator I = node->begin(), E = node->end();
I != E; ++I)
if (!frontier.count(*I) && !visited.count(*I)) {
worklist.push_back(*I);
inserted = true;
break;
}
if (!inserted) {
frontier.erase(currNode);
visited.insert(currNode);
maxpreorder.insert(std::make_pair(currNode->getBlock(), time));
worklist.pop_back();
}
}
}
/// PreorderSorter - a helper class that is used to sort registers
/// according to the preorder number of their defining blocks
class PreorderSorter {
private:
DenseMap<MachineBasicBlock*, unsigned>& preorder;
LiveVariables& LV;
public:
PreorderSorter(DenseMap<MachineBasicBlock*, unsigned>& p,
LiveVariables& L) : preorder(p), LV(L) { }
bool operator()(unsigned A, unsigned B) {
if (A == B)
return false;
MachineBasicBlock* ABlock = LV.getVarInfo(A).DefInst->getParent();
MachineBasicBlock* BBlock = LV.getVarInfo(A).DefInst->getParent();
if (preorder[ABlock] < preorder[BBlock])
return true;
else if (preorder[ABlock] > preorder[BBlock])
return false;
assert(0 && "Error sorting by dominance!");
return false;
}
};
/// computeDomForest - compute the subforest of the DomTree corresponding
/// to the defining blocks of the registers in question
std::vector<StrongPHIElimination::DomForestNode*>
StrongPHIElimination::computeDomForest(std::set<unsigned>& regs) {
LiveVariables& LV = getAnalysis<LiveVariables>();
DomForestNode* VirtualRoot = new DomForestNode(0, 0);
maxpreorder.insert(std::make_pair((MachineBasicBlock*)0, ~0UL));
std::vector<unsigned> worklist;
worklist.reserve(regs.size());
for (std::set<unsigned>::iterator I = regs.begin(), E = regs.end();
I != E; ++I)
worklist.push_back(*I);
PreorderSorter PS(preorder, LV);
std::sort(worklist.begin(), worklist.end(), PS);
DomForestNode* CurrentParent = VirtualRoot;
std::vector<DomForestNode*> stack;
stack.push_back(VirtualRoot);
for (std::vector<unsigned>::iterator I = worklist.begin(), E = worklist.end();
I != E; ++I) {
unsigned pre = preorder[LV.getVarInfo(*I).DefInst->getParent()];
MachineBasicBlock* parentBlock =
LV.getVarInfo(CurrentParent->getReg()).DefInst->getParent();
while (pre > maxpreorder[parentBlock]) {
stack.pop_back();
CurrentParent = stack.back();
parentBlock = LV.getVarInfo(CurrentParent->getReg()).DefInst->getParent();
}
DomForestNode* child = new DomForestNode(*I, CurrentParent);
stack.push_back(child);
CurrentParent = child;
}
std::vector<DomForestNode*> ret;
ret.insert(ret.end(), VirtualRoot->begin(), VirtualRoot->end());
return ret;
}
/// isLiveIn - helper method that determines, from a VarInfo, if a register
/// is live into a block
bool isLiveIn(LiveVariables::VarInfo& V, MachineBasicBlock* MBB) {
if (V.AliveBlocks.test(MBB->getNumber()))
return true;
if (V.DefInst->getParent() != MBB &&
V.UsedBlocks.test(MBB->getNumber()))
return true;
return false;
}
/// isLiveOut - help method that determines, from a VarInfo, if a register is
/// live out of a block.
bool isLiveOut(LiveVariables::VarInfo& V, MachineBasicBlock* MBB) {
if (MBB == V.DefInst->getParent() ||
V.UsedBlocks.test(MBB->getNumber())) {
for (std::vector<MachineInstr*>::iterator I = V.Kills.begin(),
E = V.Kills.end(); I != E; ++I)
if ((*I)->getParent() == MBB)
return false;
return true;
}
return false;
}
/// processBlock - Eliminate PHIs in the given block
void StrongPHIElimination::processBlock(MachineBasicBlock* MBB) {
LiveVariables& LV = getAnalysis<LiveVariables>();
// Holds names that have been added to a set in any PHI within this block
// before the current one.
std::set<unsigned> ProcessedNames;
MachineBasicBlock::iterator P = MBB->begin();
while (P->getOpcode() == TargetInstrInfo::PHI) {
LiveVariables::VarInfo& PHIInfo = LV.getVarInfo(P->getOperand(0).getReg());
// Hold the names that are currently in the candidate set.
std::set<unsigned> PHIUnion;
std::set<MachineBasicBlock*> UnionedBlocks;
for (int i = P->getNumOperands() - 1; i >= 2; i-=2) {
unsigned SrcReg = P->getOperand(i-1).getReg();
LiveVariables::VarInfo& SrcInfo = LV.getVarInfo(SrcReg);
if (isLiveIn(SrcInfo, P->getParent())) {
// add a copy from a_i to p in Waiting[From[a_i]]
} else if (isLiveOut(PHIInfo, SrcInfo.DefInst->getParent())) {
// add a copy to Waiting[From[a_i]]
} else if (PHIInfo.DefInst->getOpcode() == TargetInstrInfo::PHI &&
isLiveIn(PHIInfo, SrcInfo.DefInst->getParent())) {
// add a copy to Waiting[From[a_i]]
} else if (ProcessedNames.count(SrcReg)) {
// add a copy to Waiting[From[a_i]]
} else if (UnionedBlocks.count(SrcInfo.DefInst->getParent())) {
// add a copy to Waiting[From[a_i]]
} else {
PHIUnion.insert(SrcReg);
UnionedBlocks.insert(SrcInfo.DefInst->getParent());
// DO STUFF HERE
}
ProcessedNames.insert(PHIUnion.begin(), PHIUnion.end());
}
++P;
}
}
bool StrongPHIElimination::runOnMachineFunction(MachineFunction &Fn) {
computeDFS(Fn);
for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
if (!I->empty() &&
I->begin()->getOpcode() == TargetInstrInfo::PHI)
processBlock(I);
return false;
}
<|endoftext|>
|
<commit_before>//===--- CrossTranslationUnit.cpp - -----------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the CrossTranslationUnit interface.
//
//===----------------------------------------------------------------------===//
#include "clang/CrossTU/CrossTranslationUnit.h"
#include "clang/AST/ASTImporter.h"
#include "clang/AST/Decl.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/CrossTU/CrossTUDiagnostic.h"
#include "clang/Frontend/ASTUnit.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Frontend/FrontendDiagnostic.h"
#include "clang/Frontend/TextDiagnosticPrinter.h"
#include "clang/Index/USRGeneration.h"
#include "llvm/ADT/Triple.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/raw_ostream.h"
#include <fstream>
#include <sstream>
namespace clang {
namespace cross_tu {
namespace {
// FIXME: This class is will be removed after the transition to llvm::Error.
class IndexErrorCategory : public std::error_category {
public:
const char *name() const noexcept override { return "clang.index"; }
std::string message(int Condition) const override {
switch (static_cast<index_error_code>(Condition)) {
case index_error_code::unspecified:
return "An unknown error has occurred.";
case index_error_code::missing_index_file:
return "The index file is missing.";
case index_error_code::invalid_index_format:
return "Invalid index file format.";
case index_error_code::multiple_definitions:
return "Multiple definitions in the index file.";
case index_error_code::missing_definition:
return "Missing definition from the index file.";
case index_error_code::failed_import:
return "Failed to import the definition.";
case index_error_code::failed_to_get_external_ast:
return "Failed to load external AST source.";
case index_error_code::failed_to_generate_usr:
return "Failed to generate USR.";
}
llvm_unreachable("Unrecognized index_error_code.");
}
};
static llvm::ManagedStatic<IndexErrorCategory> Category;
} // end anonymous namespace
char IndexError::ID;
void IndexError::log(raw_ostream &OS) const {
OS << Category->message(static_cast<int>(Code)) << '\n';
}
std::error_code IndexError::convertToErrorCode() const {
return std::error_code(static_cast<int>(Code), *Category);
}
llvm::Expected<llvm::StringMap<std::string>>
parseCrossTUIndex(StringRef IndexPath, StringRef CrossTUDir) {
std::ifstream ExternalFnMapFile(IndexPath);
if (!ExternalFnMapFile)
return llvm::make_error<IndexError>(index_error_code::missing_index_file,
IndexPath.str());
llvm::StringMap<std::string> Result;
std::string Line;
unsigned LineNo = 1;
while (std::getline(ExternalFnMapFile, Line)) {
const size_t Pos = Line.find(" ");
if (Pos > 0 && Pos != std::string::npos) {
StringRef LineRef{Line};
StringRef FunctionLookupName = LineRef.substr(0, Pos);
if (Result.count(FunctionLookupName))
return llvm::make_error<IndexError>(
index_error_code::multiple_definitions, IndexPath.str(), LineNo);
StringRef FileName = LineRef.substr(Pos + 1);
SmallString<256> FilePath = CrossTUDir;
if (llvm::sys::path::is_absolute(FileName))
FilePath = FileName;
else
llvm::sys::path::append(FilePath, FileName);
Result[FunctionLookupName] = FilePath.str().str();
} else
return llvm::make_error<IndexError>(
index_error_code::invalid_index_format, IndexPath.str(), LineNo);
LineNo++;
}
return Result;
}
std::string
createCrossTUIndexString(const llvm::StringMap<std::string> &Index) {
std::ostringstream Result;
for (const auto &E : Index)
Result << E.getKey().str() << " " << E.getValue() << '\n';
return Result.str();
}
CrossTranslationUnitContext::CrossTranslationUnitContext(CompilerInstance &CI)
: CI(CI), Context(CI.getASTContext()) {}
CrossTranslationUnitContext::~CrossTranslationUnitContext() {}
std::string CrossTranslationUnitContext::getLookupName(const NamedDecl *ND) {
SmallString<128> DeclUSR;
bool Ret = index::generateUSRForDecl(ND, DeclUSR); (void)Ret;
assert(!Ret && "Unable to generate USR");
return DeclUSR.str();
}
/// Recursively visits the function decls of a DeclContext, and looks up a
/// function based on USRs.
const FunctionDecl *
CrossTranslationUnitContext::findFunctionInDeclContext(const DeclContext *DC,
StringRef LookupFnName) {
assert(DC && "Declaration Context must not be null");
for (const Decl *D : DC->decls()) {
const auto *SubDC = dyn_cast<DeclContext>(D);
if (SubDC)
if (const auto *FD = findFunctionInDeclContext(SubDC, LookupFnName))
return FD;
const auto *ND = dyn_cast<FunctionDecl>(D);
const FunctionDecl *ResultDecl;
if (!ND || !ND->hasBody(ResultDecl))
continue;
if (getLookupName(ResultDecl) != LookupFnName)
continue;
return ResultDecl;
}
return nullptr;
}
llvm::Expected<const FunctionDecl *>
CrossTranslationUnitContext::getCrossTUDefinition(const FunctionDecl *FD,
StringRef CrossTUDir,
StringRef IndexName) {
assert(!FD->hasBody() && "FD has a definition in current translation unit!");
const std::string LookupFnName = getLookupName(FD);
if (LookupFnName.empty())
return llvm::make_error<IndexError>(
index_error_code::failed_to_generate_usr);
llvm::Expected<ASTUnit *> ASTUnitOrError =
loadExternalAST(LookupFnName, CrossTUDir, IndexName);
if (!ASTUnitOrError)
return ASTUnitOrError.takeError();
ASTUnit *Unit = *ASTUnitOrError;
if (!Unit)
return llvm::make_error<IndexError>(
index_error_code::failed_to_get_external_ast);
assert(&Unit->getFileManager() ==
&Unit->getASTContext().getSourceManager().getFileManager());
TranslationUnitDecl *TU = Unit->getASTContext().getTranslationUnitDecl();
if (const FunctionDecl *ResultDecl =
findFunctionInDeclContext(TU, LookupFnName))
return importDefinition(ResultDecl);
return llvm::make_error<IndexError>(index_error_code::failed_import);
}
void CrossTranslationUnitContext::emitCrossTUDiagnostics(const IndexError &IE) {
switch (IE.getCode()) {
case index_error_code::missing_index_file:
Context.getDiagnostics().Report(diag::err_fe_error_opening)
<< IE.getFileName() << "required by the CrossTU functionality";
break;
case index_error_code::invalid_index_format:
Context.getDiagnostics().Report(diag::err_fnmap_parsing)
<< IE.getFileName() << IE.getLineNum();
case index_error_code::multiple_definitions:
Context.getDiagnostics().Report(diag::err_multiple_def_index)
<< IE.getLineNum();
break;
default:
break;
}
}
llvm::Expected<ASTUnit *> CrossTranslationUnitContext::loadExternalAST(
StringRef LookupName, StringRef CrossTUDir, StringRef IndexName) {
// FIXME: The current implementation only supports loading functions with
// a lookup name from a single translation unit. If multiple
// translation units contains functions with the same lookup name an
// error will be returned.
ASTUnit *Unit = nullptr;
auto FnUnitCacheEntry = FunctionASTUnitMap.find(LookupName);
if (FnUnitCacheEntry == FunctionASTUnitMap.end()) {
if (FunctionFileMap.empty()) {
SmallString<256> IndexFile = CrossTUDir;
if (llvm::sys::path::is_absolute(IndexName))
IndexFile = IndexName;
else
llvm::sys::path::append(IndexFile, IndexName);
llvm::Expected<llvm::StringMap<std::string>> IndexOrErr =
parseCrossTUIndex(IndexFile, CrossTUDir);
if (IndexOrErr)
FunctionFileMap = *IndexOrErr;
else
return IndexOrErr.takeError();
}
auto It = FunctionFileMap.find(LookupName);
if (It == FunctionFileMap.end())
return llvm::make_error<IndexError>(index_error_code::missing_definition);
StringRef ASTFileName = It->second;
auto ASTCacheEntry = FileASTUnitMap.find(ASTFileName);
if (ASTCacheEntry == FileASTUnitMap.end()) {
IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
TextDiagnosticPrinter *DiagClient =
new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts);
IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
new DiagnosticsEngine(DiagID, &*DiagOpts, DiagClient));
std::unique_ptr<ASTUnit> LoadedUnit(ASTUnit::LoadFromASTFile(
ASTFileName, CI.getPCHContainerOperations()->getRawReader(),
ASTUnit::LoadEverything, Diags, CI.getFileSystemOpts()));
Unit = LoadedUnit.get();
FileASTUnitMap[ASTFileName] = std::move(LoadedUnit);
} else {
Unit = ASTCacheEntry->second.get();
}
FunctionASTUnitMap[LookupName] = Unit;
} else {
Unit = FnUnitCacheEntry->second;
}
return Unit;
}
llvm::Expected<const FunctionDecl *>
CrossTranslationUnitContext::importDefinition(const FunctionDecl *FD) {
ASTImporter &Importer = getOrCreateASTImporter(FD->getASTContext());
auto *ToDecl =
cast<FunctionDecl>(Importer.Import(const_cast<FunctionDecl *>(FD)));
assert(ToDecl->hasBody());
assert(FD->hasBody() && "Functions already imported should have body.");
return ToDecl;
}
ASTImporter &
CrossTranslationUnitContext::getOrCreateASTImporter(ASTContext &From) {
auto I = ASTUnitImporterMap.find(From.getTranslationUnitDecl());
if (I != ASTUnitImporterMap.end())
return *I->second;
ASTImporter *NewImporter =
new ASTImporter(Context, Context.getSourceManager().getFileManager(),
From, From.getSourceManager().getFileManager(), false);
ASTUnitImporterMap[From.getTranslationUnitDecl()].reset(NewImporter);
return *NewImporter;
}
} // namespace cross_tu
} // namespace clang
<commit_msg>Fix implicit-fallthrough warning by adding missing break<commit_after>//===--- CrossTranslationUnit.cpp - -----------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the CrossTranslationUnit interface.
//
//===----------------------------------------------------------------------===//
#include "clang/CrossTU/CrossTranslationUnit.h"
#include "clang/AST/ASTImporter.h"
#include "clang/AST/Decl.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/CrossTU/CrossTUDiagnostic.h"
#include "clang/Frontend/ASTUnit.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Frontend/FrontendDiagnostic.h"
#include "clang/Frontend/TextDiagnosticPrinter.h"
#include "clang/Index/USRGeneration.h"
#include "llvm/ADT/Triple.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/raw_ostream.h"
#include <fstream>
#include <sstream>
namespace clang {
namespace cross_tu {
namespace {
// FIXME: This class is will be removed after the transition to llvm::Error.
class IndexErrorCategory : public std::error_category {
public:
const char *name() const noexcept override { return "clang.index"; }
std::string message(int Condition) const override {
switch (static_cast<index_error_code>(Condition)) {
case index_error_code::unspecified:
return "An unknown error has occurred.";
case index_error_code::missing_index_file:
return "The index file is missing.";
case index_error_code::invalid_index_format:
return "Invalid index file format.";
case index_error_code::multiple_definitions:
return "Multiple definitions in the index file.";
case index_error_code::missing_definition:
return "Missing definition from the index file.";
case index_error_code::failed_import:
return "Failed to import the definition.";
case index_error_code::failed_to_get_external_ast:
return "Failed to load external AST source.";
case index_error_code::failed_to_generate_usr:
return "Failed to generate USR.";
}
llvm_unreachable("Unrecognized index_error_code.");
}
};
static llvm::ManagedStatic<IndexErrorCategory> Category;
} // end anonymous namespace
char IndexError::ID;
void IndexError::log(raw_ostream &OS) const {
OS << Category->message(static_cast<int>(Code)) << '\n';
}
std::error_code IndexError::convertToErrorCode() const {
return std::error_code(static_cast<int>(Code), *Category);
}
llvm::Expected<llvm::StringMap<std::string>>
parseCrossTUIndex(StringRef IndexPath, StringRef CrossTUDir) {
std::ifstream ExternalFnMapFile(IndexPath);
if (!ExternalFnMapFile)
return llvm::make_error<IndexError>(index_error_code::missing_index_file,
IndexPath.str());
llvm::StringMap<std::string> Result;
std::string Line;
unsigned LineNo = 1;
while (std::getline(ExternalFnMapFile, Line)) {
const size_t Pos = Line.find(" ");
if (Pos > 0 && Pos != std::string::npos) {
StringRef LineRef{Line};
StringRef FunctionLookupName = LineRef.substr(0, Pos);
if (Result.count(FunctionLookupName))
return llvm::make_error<IndexError>(
index_error_code::multiple_definitions, IndexPath.str(), LineNo);
StringRef FileName = LineRef.substr(Pos + 1);
SmallString<256> FilePath = CrossTUDir;
if (llvm::sys::path::is_absolute(FileName))
FilePath = FileName;
else
llvm::sys::path::append(FilePath, FileName);
Result[FunctionLookupName] = FilePath.str().str();
} else
return llvm::make_error<IndexError>(
index_error_code::invalid_index_format, IndexPath.str(), LineNo);
LineNo++;
}
return Result;
}
std::string
createCrossTUIndexString(const llvm::StringMap<std::string> &Index) {
std::ostringstream Result;
for (const auto &E : Index)
Result << E.getKey().str() << " " << E.getValue() << '\n';
return Result.str();
}
CrossTranslationUnitContext::CrossTranslationUnitContext(CompilerInstance &CI)
: CI(CI), Context(CI.getASTContext()) {}
CrossTranslationUnitContext::~CrossTranslationUnitContext() {}
std::string CrossTranslationUnitContext::getLookupName(const NamedDecl *ND) {
SmallString<128> DeclUSR;
bool Ret = index::generateUSRForDecl(ND, DeclUSR); (void)Ret;
assert(!Ret && "Unable to generate USR");
return DeclUSR.str();
}
/// Recursively visits the function decls of a DeclContext, and looks up a
/// function based on USRs.
const FunctionDecl *
CrossTranslationUnitContext::findFunctionInDeclContext(const DeclContext *DC,
StringRef LookupFnName) {
assert(DC && "Declaration Context must not be null");
for (const Decl *D : DC->decls()) {
const auto *SubDC = dyn_cast<DeclContext>(D);
if (SubDC)
if (const auto *FD = findFunctionInDeclContext(SubDC, LookupFnName))
return FD;
const auto *ND = dyn_cast<FunctionDecl>(D);
const FunctionDecl *ResultDecl;
if (!ND || !ND->hasBody(ResultDecl))
continue;
if (getLookupName(ResultDecl) != LookupFnName)
continue;
return ResultDecl;
}
return nullptr;
}
llvm::Expected<const FunctionDecl *>
CrossTranslationUnitContext::getCrossTUDefinition(const FunctionDecl *FD,
StringRef CrossTUDir,
StringRef IndexName) {
assert(!FD->hasBody() && "FD has a definition in current translation unit!");
const std::string LookupFnName = getLookupName(FD);
if (LookupFnName.empty())
return llvm::make_error<IndexError>(
index_error_code::failed_to_generate_usr);
llvm::Expected<ASTUnit *> ASTUnitOrError =
loadExternalAST(LookupFnName, CrossTUDir, IndexName);
if (!ASTUnitOrError)
return ASTUnitOrError.takeError();
ASTUnit *Unit = *ASTUnitOrError;
if (!Unit)
return llvm::make_error<IndexError>(
index_error_code::failed_to_get_external_ast);
assert(&Unit->getFileManager() ==
&Unit->getASTContext().getSourceManager().getFileManager());
TranslationUnitDecl *TU = Unit->getASTContext().getTranslationUnitDecl();
if (const FunctionDecl *ResultDecl =
findFunctionInDeclContext(TU, LookupFnName))
return importDefinition(ResultDecl);
return llvm::make_error<IndexError>(index_error_code::failed_import);
}
void CrossTranslationUnitContext::emitCrossTUDiagnostics(const IndexError &IE) {
switch (IE.getCode()) {
case index_error_code::missing_index_file:
Context.getDiagnostics().Report(diag::err_fe_error_opening)
<< IE.getFileName() << "required by the CrossTU functionality";
break;
case index_error_code::invalid_index_format:
Context.getDiagnostics().Report(diag::err_fnmap_parsing)
<< IE.getFileName() << IE.getLineNum();
break;
case index_error_code::multiple_definitions:
Context.getDiagnostics().Report(diag::err_multiple_def_index)
<< IE.getLineNum();
break;
default:
break;
}
}
llvm::Expected<ASTUnit *> CrossTranslationUnitContext::loadExternalAST(
StringRef LookupName, StringRef CrossTUDir, StringRef IndexName) {
// FIXME: The current implementation only supports loading functions with
// a lookup name from a single translation unit. If multiple
// translation units contains functions with the same lookup name an
// error will be returned.
ASTUnit *Unit = nullptr;
auto FnUnitCacheEntry = FunctionASTUnitMap.find(LookupName);
if (FnUnitCacheEntry == FunctionASTUnitMap.end()) {
if (FunctionFileMap.empty()) {
SmallString<256> IndexFile = CrossTUDir;
if (llvm::sys::path::is_absolute(IndexName))
IndexFile = IndexName;
else
llvm::sys::path::append(IndexFile, IndexName);
llvm::Expected<llvm::StringMap<std::string>> IndexOrErr =
parseCrossTUIndex(IndexFile, CrossTUDir);
if (IndexOrErr)
FunctionFileMap = *IndexOrErr;
else
return IndexOrErr.takeError();
}
auto It = FunctionFileMap.find(LookupName);
if (It == FunctionFileMap.end())
return llvm::make_error<IndexError>(index_error_code::missing_definition);
StringRef ASTFileName = It->second;
auto ASTCacheEntry = FileASTUnitMap.find(ASTFileName);
if (ASTCacheEntry == FileASTUnitMap.end()) {
IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
TextDiagnosticPrinter *DiagClient =
new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts);
IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
new DiagnosticsEngine(DiagID, &*DiagOpts, DiagClient));
std::unique_ptr<ASTUnit> LoadedUnit(ASTUnit::LoadFromASTFile(
ASTFileName, CI.getPCHContainerOperations()->getRawReader(),
ASTUnit::LoadEverything, Diags, CI.getFileSystemOpts()));
Unit = LoadedUnit.get();
FileASTUnitMap[ASTFileName] = std::move(LoadedUnit);
} else {
Unit = ASTCacheEntry->second.get();
}
FunctionASTUnitMap[LookupName] = Unit;
} else {
Unit = FnUnitCacheEntry->second;
}
return Unit;
}
llvm::Expected<const FunctionDecl *>
CrossTranslationUnitContext::importDefinition(const FunctionDecl *FD) {
ASTImporter &Importer = getOrCreateASTImporter(FD->getASTContext());
auto *ToDecl =
cast<FunctionDecl>(Importer.Import(const_cast<FunctionDecl *>(FD)));
assert(ToDecl->hasBody());
assert(FD->hasBody() && "Functions already imported should have body.");
return ToDecl;
}
ASTImporter &
CrossTranslationUnitContext::getOrCreateASTImporter(ASTContext &From) {
auto I = ASTUnitImporterMap.find(From.getTranslationUnitDecl());
if (I != ASTUnitImporterMap.end())
return *I->second;
ASTImporter *NewImporter =
new ASTImporter(Context, Context.getSourceManager().getFileManager(),
From, From.getSourceManager().getFileManager(), false);
ASTUnitImporterMap[From.getTranslationUnitDecl()].reset(NewImporter);
return *NewImporter;
}
} // namespace cross_tu
} // namespace clang
<|endoftext|>
|
<commit_before>#ifndef __STAN__PROB__DISTRIBUTIONS__UNIVARIATE__CONTINUOUS__INV_GAMMA_HPP__
#define __STAN__PROB__DISTRIBUTIONS__UNIVARIATE__CONTINUOUS__INV_GAMMA_HPP__
#include <stan/agrad.hpp>
#include <stan/math/error_handling.hpp>
#include <stan/math/special_functions.hpp>
#include <stan/meta/traits.hpp>
#include <stan/prob/constants.hpp>
#include <stan/prob/traits.hpp>
#include <stan/prob/internal_math.hpp>
namespace stan {
namespace prob {
/**
* The log of an inverse gamma density for y with the specified
* shape and scale parameters.
* Shape and scale parameters must be greater than 0.
* y must be greater than 0.
*
* @param y A scalar variable.
* @param alpha Shape parameter.
* @param beta Scale parameter.
* @throw std::domain_error if alpha is not greater than 0.
* @throw std::domain_error if beta is not greater than 0.
* @throw std::domain_error if y is not greater than 0.
* @tparam T_y Type of scalar.
* @tparam T_shape Type of shape.
* @tparam T_scale Type of scale.
*/
template <bool propto,
typename T_y, typename T_shape, typename T_scale,
class Policy>
typename return_type<T_y,T_shape,T_scale>::type
inv_gamma_log(const T_y& y, const T_shape& alpha, const T_scale& beta,
const Policy&) {
static const char* function = "stan::prob::inv_gamma_log(%1%)";
using stan::is_constant_struct;
using stan::math::check_not_nan;
using stan::math::check_positive;
using stan::math::check_finite;
using boost::math::tools::promote_args;
using stan::math::check_consistent_sizes;
using stan::math::value_of;
// check if any vectors are zero length
if (!(stan::length(y)
&& stan::length(alpha)
&& stan::length(beta)))
return 0.0;
// set up return value accumulator
double logp(0.0);
if (!check_not_nan(function, y, "Random variable", &logp, Policy()))
return logp;
if (!check_finite(function, alpha, "Shape parameter",
&logp, Policy()))
return logp;
if (!check_positive(function, alpha, "Shape parameter",
&logp, Policy()))
return logp;
if (!check_finite(function, beta, "Scale parameter",
&logp, Policy()))
return logp;
if (!check_positive(function, beta, "Scale parameter",
&logp, Policy()))
return logp;
if (!(check_consistent_sizes(function,
y,alpha,beta,
"Random variable","Shape parameter","Scale parameter",
&logp, Policy())))
return logp;
// check if no variables are involved and prop-to
if (!include_summand<propto,T_y,T_shape,T_scale>::value)
return 0.0;
// set up template expressions wrapping scalars into vector views
VectorView<const T_y> y_vec(y);
VectorView<const T_shape> alpha_vec(alpha);
VectorView<const T_scale> beta_vec(beta);
for (size_t n = 0; n < length(y); n++) {
const double y_dbl = value_of(y_vec[n]);
if (y_dbl <= 0)
return LOG_ZERO;
}
size_t N = max_size(y, alpha, beta);
agrad::OperandsAndPartials<T_y, T_shape, T_scale> operands_and_partials(y, alpha, beta);
using boost::math::lgamma;
using stan::math::multiply_log;
using boost::math::digamma;
DoubleVectorView<include_summand<propto,T_y,T_shape>::value,T_y>
log_y(length(y));
DoubleVectorView<include_summand<propto,T_y,T_scale>::value,T_y>
inv_y(length(y));
for(size_t n = 0; n < length(y); n++) {
if (include_summand<propto,T_y,T_shape>::value)
if (value_of(y_vec[n]) > 0)
log_y[n] = log(value_of(y_vec[n]));
if (include_summand<propto,T_y,T_scale>::value)
inv_y[n] = 1.0 / value_of(y_vec[n]);
}
DoubleVectorView<include_summand<propto,T_shape>::value,T_shape>
lgamma_alpha(length(alpha));
DoubleVectorView<!is_constant_struct<T_shape>::value,T_shape>
digamma_alpha(length(alpha));
for (size_t n = 0; n < length(alpha); n++) {
if (include_summand<propto,T_shape>::value)
lgamma_alpha[n] = lgamma(value_of(alpha_vec[n]));
if (!is_constant_struct<T_shape>::value)
digamma_alpha[n] = digamma(value_of(alpha_vec[n]));
}
DoubleVectorView<include_summand<propto,T_shape,T_scale>::value,T_scale>
log_beta(length(beta));
if (include_summand<propto,T_shape,T_scale>::value)
for (size_t n = 0; n < length(beta); n++)
log_beta[n] = log(value_of(beta_vec[n]));
for (size_t n = 0; n < N; n++) {
// pull out values of arguments
const double alpha_dbl = value_of(alpha_vec[n]);
const double beta_dbl = value_of(beta_vec[n]);
if (include_summand<propto,T_shape>::value)
logp -= lgamma_alpha[n];
if (include_summand<propto,T_shape,T_scale>::value)
logp += alpha_dbl * log_beta[n];
if (include_summand<propto,T_y,T_shape>::value)
logp -= (alpha_dbl+1.0) * log_y[n];
if (include_summand<propto,T_y,T_scale>::value)
logp -= beta_dbl * inv_y[n];
// gradients
if (!is_constant<typename is_vector<T_y>::type>::value)
operands_and_partials.d_x1[n] += -(alpha_dbl+1) * inv_y[n] + beta_dbl * inv_y[n] * inv_y[n];
if (!is_constant<typename is_vector<T_shape>::type>::value)
operands_and_partials.d_x2[n] += -digamma_alpha[n] + log_beta[n] - log_y[n];
if (!is_constant<typename is_vector<T_scale>::type>::value)
operands_and_partials.d_x3[n] += alpha_dbl / beta_dbl - inv_y[n];
}
return operands_and_partials.to_var(logp);
}
template <bool propto,
typename T_y, typename T_shape, typename T_scale>
inline
typename return_type<T_y,T_shape,T_scale>::type
inv_gamma_log(const T_y& y, const T_shape& alpha, const T_scale& beta) {
return inv_gamma_log<propto>(y,alpha,beta,stan::math::default_policy());
}
template <typename T_y, typename T_shape, typename T_scale,
class Policy>
inline
typename return_type<T_y,T_shape,T_scale>::type
inv_gamma_log(const T_y& y, const T_shape& alpha, const T_scale& beta,
const Policy&) {
return inv_gamma_log<false>(y,alpha,beta,Policy());
}
template <typename T_y, typename T_shape, typename T_scale>
inline
typename return_type<T_y,T_shape,T_scale>::type
inv_gamma_log(const T_y& y, const T_shape& alpha, const T_scale& beta) {
return inv_gamma_log<false>(y,alpha,beta,stan::math::default_policy());
}
/**
* The CDF of an inverse gamma density for y with the specified
* shape and scale parameters. y, shape, and scale parameters must be greater than 0.
*
* @param y A scalar variable.
* @param alpha Shape parameter.
* @param beta Scale parameter.
* @throw std::domain_error if alpha is not greater than 0.
* @throw std::domain_error if beta is not greater than 0.
* @throw std::domain_error if y is not greater than 0.
* @tparam T_y Type of scalar.
* @tparam T_shape Type of shape.
* @tparam T_scale Type of scale.
*/
template <typename T_y, typename T_shape, typename T_scale, class Policy>
typename return_type<T_y,T_shape,T_scale>::type
inv_gamma_cdf(const T_y& y, const T_shape& alpha, const T_scale& beta, const Policy&) {
// Size checks
if ( !( stan::length(y) && stan::length(alpha) && stan::length(beta) ) ) return 0.0;
// Error checks
static const char* function = "stan::prob::inv_gamma_cdf(%1%)";
using stan::math::check_finite;
using stan::math::check_positive;
using stan::math::check_not_nan;
using stan::math::check_consistent_sizes;
using stan::math::check_greater_or_equal;
using stan::math::check_less_or_equal;
using boost::math::tools::promote_args;
double P(1.0);
if (!check_finite(function, alpha, "Shape parameter", &P, Policy()))
return P;
if (!check_positive(function, alpha, "Shape parameter", &P, Policy()))
return P;
if (!check_finite(function, beta, "Scale parameter", &P, Policy()))
return P;
if (!check_positive(function, beta, "Scale parameter", &P, Policy()))
return P;
if (!check_not_nan(function, y, "Random variable", &P, Policy()))
return P;
if (!check_positive(function, y, "Random variable", &P, Policy()))
return P;
if (!(check_consistent_sizes(function, y, alpha, beta,
"Random variable", "Shape parameter", "Scale Parameter",
&P, Policy())))
return P;
// Wrap arguments in vectors
VectorView<const T_y> y_vec(y);
VectorView<const T_shape> alpha_vec(alpha);
VectorView<const T_scale> beta_vec(beta);
size_t N = max_size(y, alpha, beta);
agrad::OperandsAndPartials<T_y, T_shape, T_scale> operands_and_partials(y, alpha, beta);
std::fill(operands_and_partials.all_partials,
operands_and_partials.all_partials + operands_and_partials.nvaris, 0.0);
// Compute CDF and its gradients
using stan::math::value_of;
using boost::math::gamma_p_derivative;
using boost::math::gamma_q;
using boost::math::digamma;
using boost::math::tgamma;
// Cache a few expensive function calls if nu is a parameter
DoubleVectorView<!is_constant_struct<T_shape>::value, T_shape> gamma_vec(stan::length(alpha));
DoubleVectorView<!is_constant_struct<T_shape>::value, T_shape> digamma_vec(stan::length(alpha));
if (!is_constant_struct<T_shape>::value) {
for (size_t i = 0; i < stan::length(alpha); i++) {
const double alpha_dbl = value_of(alpha_vec[i]);
gamma_vec[i] = tgamma(alpha_dbl);
digamma_vec[i] = digamma(alpha_dbl);
}
}
// Compute vectorized CDF and gradient
for (size_t n = 0; n < N; n++) {
// Pull out values
const double y_dbl = value_of(y_vec[n]);
const double y_inv_dbl = 1.0 / y_dbl;
const double alpha_dbl = value_of(alpha_vec[n]);
const double beta_dbl = value_of(beta_vec[n]);
// Compute
const double Pn = gamma_q(alpha_dbl, beta_dbl * y_inv_dbl);
P *= Pn;
if (!is_constant_struct<T_y>::value)
operands_and_partials.d_x1[n]
+= beta_dbl * y_inv_dbl * y_inv_dbl * gamma_p_derivative(alpha_dbl, beta_dbl * y_inv_dbl) / Pn;
if (!is_constant_struct<T_shape>::value)
operands_and_partials.d_x2[n]
+= stan::math::gradRegIncGamma(alpha_dbl, beta_dbl * y_inv_dbl, gamma_vec[n], digamma_vec[n]) / Pn;
if (!is_constant_struct<T_scale>::value)
operands_and_partials.d_x3[n]
+= - y_inv_dbl * gamma_p_derivative(alpha_dbl, beta_dbl * y_inv_dbl) / Pn;
}
for (size_t n = 0; n < N; n++) {
if (!is_constant_struct<T_y>::value)
operands_and_partials.d_x1[n] *= P;
if (!is_constant_struct<T_shape>::value)
operands_and_partials.d_x2[n] *= P;
if (!is_constant_struct<T_scale>::value)
operands_and_partials.d_x3[n] *= P;
}
return operands_and_partials.to_var(P);
}
template <typename T_y, typename T_shape, typename T_scale>
inline typename return_type<T_y, T_shape, T_scale>::type
inv_gamma_cdf(const T_y& y, const T_shape& alpha, const T_scale& beta) {
return inv_gamma_cdf(y, alpha, beta, stan::math::default_policy());
}
}
}
#endif
<commit_msg>refactoring inv_gamma distribution<commit_after>#ifndef __STAN__PROB__DISTRIBUTIONS__UNIVARIATE__CONTINUOUS__INV_GAMMA_HPP__
#define __STAN__PROB__DISTRIBUTIONS__UNIVARIATE__CONTINUOUS__INV_GAMMA_HPP__
#include <stan/agrad.hpp>
#include <stan/math/error_handling.hpp>
#include <stan/math/special_functions.hpp>
#include <stan/meta/traits.hpp>
#include <stan/prob/constants.hpp>
#include <stan/prob/traits.hpp>
#include <stan/prob/internal_math.hpp>
namespace stan {
namespace prob {
/**
* The log of an inverse gamma density for y with the specified
* shape and scale parameters.
* Shape and scale parameters must be greater than 0.
* y must be greater than 0.
*
* @param y A scalar variable.
* @param alpha Shape parameter.
* @param beta Scale parameter.
* @throw std::domain_error if alpha is not greater than 0.
* @throw std::domain_error if beta is not greater than 0.
* @throw std::domain_error if y is not greater than 0.
* @tparam T_y Type of scalar.
* @tparam T_shape Type of shape.
* @tparam T_scale Type of scale.
*/
template <bool propto,
typename T_y, typename T_shape, typename T_scale,
class Policy>
typename return_type<T_y,T_shape,T_scale>::type
inv_gamma_log(const T_y& y, const T_shape& alpha, const T_scale& beta,
const Policy&) {
static const char* function = "stan::prob::inv_gamma_log(%1%)";
using stan::is_constant_struct;
using stan::math::check_not_nan;
using stan::math::check_positive;
using stan::math::check_finite;
using boost::math::tools::promote_args;
using stan::math::check_consistent_sizes;
using stan::math::value_of;
// check if any vectors are zero length
if (!(stan::length(y)
&& stan::length(alpha)
&& stan::length(beta)))
return 0.0;
// set up return value accumulator
double logp(0.0);
if (!check_not_nan(function, y, "Random variable", &logp, Policy()))
return logp;
if (!check_finite(function, alpha, "Shape parameter",
&logp, Policy()))
return logp;
if (!check_positive(function, alpha, "Shape parameter",
&logp, Policy()))
return logp;
if (!check_finite(function, beta, "Scale parameter",
&logp, Policy()))
return logp;
if (!check_positive(function, beta, "Scale parameter",
&logp, Policy()))
return logp;
if (!(check_consistent_sizes(function,
y,alpha,beta,
"Random variable","Shape parameter","Scale parameter",
&logp, Policy())))
return logp;
// check if no variables are involved and prop-to
if (!include_summand<propto,T_y,T_shape,T_scale>::value)
return 0.0;
// set up template expressions wrapping scalars into vector views
VectorView<const T_y> y_vec(y);
VectorView<const T_shape> alpha_vec(alpha);
VectorView<const T_scale> beta_vec(beta);
for (size_t n = 0; n < length(y); n++) {
const double y_dbl = value_of(y_vec[n]);
if (y_dbl <= 0)
return LOG_ZERO;
}
size_t N = max_size(y, alpha, beta);
agrad::OperandsAndPartials<T_y, T_shape, T_scale> operands_and_partials(y, alpha, beta);
using boost::math::lgamma;
using stan::math::multiply_log;
using boost::math::digamma;
DoubleVectorView<include_summand<propto,T_y,T_shape>::value,is_vector<T_y>::value>
log_y(length(y));
DoubleVectorView<include_summand<propto,T_y,T_scale>::value,is_vector<T_y>::value>
inv_y(length(y));
for(size_t n = 0; n < length(y); n++) {
if (include_summand<propto,T_y,T_shape>::value)
if (value_of(y_vec[n]) > 0)
log_y[n] = log(value_of(y_vec[n]));
if (include_summand<propto,T_y,T_scale>::value)
inv_y[n] = 1.0 / value_of(y_vec[n]);
}
DoubleVectorView<include_summand<propto,T_shape>::value,is_vector<T_shape>::value>
lgamma_alpha(length(alpha));
DoubleVectorView<!is_constant_struct<T_shape>::value,is_vector<T_shape>::value>
digamma_alpha(length(alpha));
for (size_t n = 0; n < length(alpha); n++) {
if (include_summand<propto,T_shape>::value)
lgamma_alpha[n] = lgamma(value_of(alpha_vec[n]));
if (!is_constant_struct<T_shape>::value)
digamma_alpha[n] = digamma(value_of(alpha_vec[n]));
}
DoubleVectorView<include_summand<propto,T_shape,T_scale>::value,is_vector<T_scale>::value>
log_beta(length(beta));
if (include_summand<propto,T_shape,T_scale>::value)
for (size_t n = 0; n < length(beta); n++)
log_beta[n] = log(value_of(beta_vec[n]));
for (size_t n = 0; n < N; n++) {
// pull out values of arguments
const double alpha_dbl = value_of(alpha_vec[n]);
const double beta_dbl = value_of(beta_vec[n]);
if (include_summand<propto,T_shape>::value)
logp -= lgamma_alpha[n];
if (include_summand<propto,T_shape,T_scale>::value)
logp += alpha_dbl * log_beta[n];
if (include_summand<propto,T_y,T_shape>::value)
logp -= (alpha_dbl+1.0) * log_y[n];
if (include_summand<propto,T_y,T_scale>::value)
logp -= beta_dbl * inv_y[n];
// gradients
if (!is_constant<typename is_vector<T_y>::type>::value)
operands_and_partials.d_x1[n] += -(alpha_dbl+1) * inv_y[n] + beta_dbl * inv_y[n] * inv_y[n];
if (!is_constant<typename is_vector<T_shape>::type>::value)
operands_and_partials.d_x2[n] += -digamma_alpha[n] + log_beta[n] - log_y[n];
if (!is_constant<typename is_vector<T_scale>::type>::value)
operands_and_partials.d_x3[n] += alpha_dbl / beta_dbl - inv_y[n];
}
return operands_and_partials.to_var(logp);
}
template <bool propto,
typename T_y, typename T_shape, typename T_scale>
inline
typename return_type<T_y,T_shape,T_scale>::type
inv_gamma_log(const T_y& y, const T_shape& alpha, const T_scale& beta) {
return inv_gamma_log<propto>(y,alpha,beta,stan::math::default_policy());
}
template <typename T_y, typename T_shape, typename T_scale,
class Policy>
inline
typename return_type<T_y,T_shape,T_scale>::type
inv_gamma_log(const T_y& y, const T_shape& alpha, const T_scale& beta,
const Policy&) {
return inv_gamma_log<false>(y,alpha,beta,Policy());
}
template <typename T_y, typename T_shape, typename T_scale>
inline
typename return_type<T_y,T_shape,T_scale>::type
inv_gamma_log(const T_y& y, const T_shape& alpha, const T_scale& beta) {
return inv_gamma_log<false>(y,alpha,beta,stan::math::default_policy());
}
/**
* The CDF of an inverse gamma density for y with the specified
* shape and scale parameters. y, shape, and scale parameters must be greater than 0.
*
* @param y A scalar variable.
* @param alpha Shape parameter.
* @param beta Scale parameter.
* @throw std::domain_error if alpha is not greater than 0.
* @throw std::domain_error if beta is not greater than 0.
* @throw std::domain_error if y is not greater than 0.
* @tparam T_y Type of scalar.
* @tparam T_shape Type of shape.
* @tparam T_scale Type of scale.
*/
template <typename T_y, typename T_shape, typename T_scale, class Policy>
typename return_type<T_y,T_shape,T_scale>::type
inv_gamma_cdf(const T_y& y, const T_shape& alpha, const T_scale& beta, const Policy&) {
// Size checks
if ( !( stan::length(y) && stan::length(alpha) && stan::length(beta) ) ) return 0.0;
// Error checks
static const char* function = "stan::prob::inv_gamma_cdf(%1%)";
using stan::math::check_finite;
using stan::math::check_positive;
using stan::math::check_not_nan;
using stan::math::check_consistent_sizes;
using stan::math::check_greater_or_equal;
using stan::math::check_less_or_equal;
using boost::math::tools::promote_args;
double P(1.0);
if (!check_finite(function, alpha, "Shape parameter", &P, Policy()))
return P;
if (!check_positive(function, alpha, "Shape parameter", &P, Policy()))
return P;
if (!check_finite(function, beta, "Scale parameter", &P, Policy()))
return P;
if (!check_positive(function, beta, "Scale parameter", &P, Policy()))
return P;
if (!check_not_nan(function, y, "Random variable", &P, Policy()))
return P;
if (!check_positive(function, y, "Random variable", &P, Policy()))
return P;
if (!(check_consistent_sizes(function, y, alpha, beta,
"Random variable", "Shape parameter", "Scale Parameter",
&P, Policy())))
return P;
// Wrap arguments in vectors
VectorView<const T_y> y_vec(y);
VectorView<const T_shape> alpha_vec(alpha);
VectorView<const T_scale> beta_vec(beta);
size_t N = max_size(y, alpha, beta);
agrad::OperandsAndPartials<T_y, T_shape, T_scale> operands_and_partials(y, alpha, beta);
std::fill(operands_and_partials.all_partials,
operands_and_partials.all_partials + operands_and_partials.nvaris, 0.0);
// Compute CDF and its gradients
using stan::math::value_of;
using boost::math::gamma_p_derivative;
using boost::math::gamma_q;
using boost::math::digamma;
using boost::math::tgamma;
// Cache a few expensive function calls if nu is a parameter
DoubleVectorView<!is_constant_struct<T_shape>::value, is_vector<T_shape>::value> gamma_vec(stan::length(alpha));
DoubleVectorView<!is_constant_struct<T_shape>::value, is_vector<T_shape>::value> digamma_vec(stan::length(alpha));
if (!is_constant_struct<T_shape>::value) {
for (size_t i = 0; i < stan::length(alpha); i++) {
const double alpha_dbl = value_of(alpha_vec[i]);
gamma_vec[i] = tgamma(alpha_dbl);
digamma_vec[i] = digamma(alpha_dbl);
}
}
// Compute vectorized CDF and gradient
for (size_t n = 0; n < N; n++) {
// Pull out values
const double y_dbl = value_of(y_vec[n]);
const double y_inv_dbl = 1.0 / y_dbl;
const double alpha_dbl = value_of(alpha_vec[n]);
const double beta_dbl = value_of(beta_vec[n]);
// Compute
const double Pn = gamma_q(alpha_dbl, beta_dbl * y_inv_dbl);
P *= Pn;
if (!is_constant_struct<T_y>::value)
operands_and_partials.d_x1[n]
+= beta_dbl * y_inv_dbl * y_inv_dbl * gamma_p_derivative(alpha_dbl, beta_dbl * y_inv_dbl) / Pn;
if (!is_constant_struct<T_shape>::value)
operands_and_partials.d_x2[n]
+= stan::math::gradRegIncGamma(alpha_dbl, beta_dbl * y_inv_dbl, gamma_vec[n], digamma_vec[n]) / Pn;
if (!is_constant_struct<T_scale>::value)
operands_and_partials.d_x3[n]
+= - y_inv_dbl * gamma_p_derivative(alpha_dbl, beta_dbl * y_inv_dbl) / Pn;
}
for (size_t n = 0; n < N; n++) {
if (!is_constant_struct<T_y>::value)
operands_and_partials.d_x1[n] *= P;
if (!is_constant_struct<T_shape>::value)
operands_and_partials.d_x2[n] *= P;
if (!is_constant_struct<T_scale>::value)
operands_and_partials.d_x3[n] *= P;
}
return operands_and_partials.to_var(P);
}
template <typename T_y, typename T_shape, typename T_scale>
inline typename return_type<T_y, T_shape, T_scale>::type
inv_gamma_cdf(const T_y& y, const T_shape& alpha, const T_scale& beta) {
return inv_gamma_cdf(y, alpha, beta, stan::math::default_policy());
}
}
}
#endif
<|endoftext|>
|
<commit_before>#include "Log.h"
#include "utils/FileSystemUtil.h"
#include "platform.h"
#include <iostream>
LogLevel Log::reportingLevel = LogInfo;
FILE* Log::file = NULL; //fopen(getLogPath().c_str(), "w");
LogLevel Log::getReportingLevel()
{
return reportingLevel;
}
std::string Log::getLogPath()
{
std::string home = Utils::FileSystem::getHomePath();
return home + "/.emulationstation/es_log.txt";
}
void Log::setReportingLevel(LogLevel level)
{
reportingLevel = level;
}
void Log::init()
{
remove((getLogPath() + ".bak").c_str());
// rename previous log file
rename(getLogPath().c_str(), (getLogPath() + ".bak").c_str());
return;
}
void Log::open()
{
file = fopen(getLogPath().c_str(), "w");
}
std::ostringstream& Log::get(LogLevel level)
{
os << "lvl" << level << ": \t";
messageLevel = level;
return os;
}
void Log::flush()
{
fflush(getOutput());
}
void Log::close()
{
fclose(file);
file = NULL;
}
FILE* Log::getOutput()
{
return file;
}
Log::~Log()
{
os << std::endl;
if(getOutput() == NULL)
{
// not open yet, print to stdout
std::cerr << "ERROR - tried to write to log file before it was open! The following won't be logged:\n";
std::cerr << os.str();
return;
}
fprintf(getOutput(), "%s", os.str().c_str());
//if it's an error, also print to console
//print all messages if using --debug
if(messageLevel == LogError || reportingLevel >= LogDebug)
fprintf(stderr, "%s", os.str().c_str());
}
<commit_msg>Timestamp'ed log entries<commit_after>#include "Log.h"
#include "utils/FileSystemUtil.h"
#include "platform.h"
#include <iostream>
#include <iomanip>
LogLevel Log::reportingLevel = LogInfo;
FILE* Log::file = NULL; //fopen(getLogPath().c_str(), "w");
LogLevel Log::getReportingLevel()
{
return reportingLevel;
}
std::string Log::getLogPath()
{
std::string home = Utils::FileSystem::getHomePath();
return home + "/.emulationstation/es_log.txt";
}
void Log::setReportingLevel(LogLevel level)
{
reportingLevel = level;
}
void Log::init()
{
remove((getLogPath() + ".bak").c_str());
// rename previous log file
rename(getLogPath().c_str(), (getLogPath() + ".bak").c_str());
return;
}
void Log::open()
{
file = fopen(getLogPath().c_str(), "w");
}
std::ostringstream& Log::get(LogLevel level)
{
time_t t = time(nullptr);
os << std::put_time(localtime(&t), "%b %d %T ") << "lvl" << level << ": \t";
messageLevel = level;
return os;
}
void Log::flush()
{
fflush(getOutput());
}
void Log::close()
{
fclose(file);
file = NULL;
}
FILE* Log::getOutput()
{
return file;
}
Log::~Log()
{
os << std::endl;
if(getOutput() == NULL)
{
// not open yet, print to stdout
std::cerr << "ERROR - tried to write to log file before it was open! The following won't be logged:\n";
std::cerr << os.str();
return;
}
fprintf(getOutput(), "%s", os.str().c_str());
//if it's an error, also print to console
//print all messages if using --debug
if(messageLevel == LogError || reportingLevel >= LogDebug)
fprintf(stderr, "%s", os.str().c_str());
}
<|endoftext|>
|
<commit_before>//===- ValueMapper.cpp - Interface shared by lib/Transforms/Utils ---------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the MapValue function, which is shared by various parts of
// the lib/Transforms/Utils library.
//
//===----------------------------------------------------------------------===//
#include "llvm/Transforms/Utils/ValueMapper.h"
#include "llvm/DerivedTypes.h" // For getNullValue(Type::Int32Ty)
#include "llvm/Constants.h"
#include "llvm/Function.h"
#include "llvm/IntrinsicInst.h"
#include "llvm/Metadata.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/Support/ErrorHandling.h"
using namespace llvm;
Value *llvm::MapValue(const Value *V, ValueMapTy &VM) {
Value *&VMSlot = VM[V];
if (VMSlot) return VMSlot; // Does it exist in the map yet?
// NOTE: VMSlot can be invalidated by any reference to VM, which can grow the
// DenseMap. This includes any recursive calls to MapValue.
// Global values and metadata do not need to be seeded into the ValueMap if
// they are using the identity mapping.
if (isa<GlobalValue>(V) || isa<InlineAsm>(V) || isa<MetadataBase>(V))
return VMSlot = const_cast<Value*>(V);
Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V));
if (C == 0) return 0;
if (isa<ConstantInt>(C) || isa<ConstantFP>(C) ||
isa<ConstantPointerNull>(C) || isa<ConstantAggregateZero>(C) ||
isa<UndefValue>(C) || isa<MDString>(C))
return VMSlot = C; // Primitive constants map directly
if (ConstantArray *CA = dyn_cast<ConstantArray>(C)) {
for (User::op_iterator b = CA->op_begin(), i = b, e = CA->op_end();
i != e; ++i) {
Value *MV = MapValue(*i, VM);
if (MV != *i) {
// This array must contain a reference to a global, make a new array
// and return it.
//
std::vector<Constant*> Values;
Values.reserve(CA->getNumOperands());
for (User::op_iterator j = b; j != i; ++j)
Values.push_back(cast<Constant>(*j));
Values.push_back(cast<Constant>(MV));
for (++i; i != e; ++i)
Values.push_back(cast<Constant>(MapValue(*i, VM)));
return VM[V] = ConstantArray::get(CA->getType(), Values);
}
}
return VM[V] = C;
}
if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
for (User::op_iterator b = CS->op_begin(), i = b, e = CS->op_end();
i != e; ++i) {
Value *MV = MapValue(*i, VM);
if (MV != *i) {
// This struct must contain a reference to a global, make a new struct
// and return it.
//
std::vector<Constant*> Values;
Values.reserve(CS->getNumOperands());
for (User::op_iterator j = b; j != i; ++j)
Values.push_back(cast<Constant>(*j));
Values.push_back(cast<Constant>(MV));
for (++i; i != e; ++i)
Values.push_back(cast<Constant>(MapValue(*i, VM)));
return VM[V] = ConstantStruct::get(CS->getType(), Values);
}
}
return VM[V] = C;
}
if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
std::vector<Constant*> Ops;
for (User::op_iterator i = CE->op_begin(), e = CE->op_end(); i != e; ++i)
Ops.push_back(cast<Constant>(MapValue(*i, VM)));
return VM[V] = CE->getWithOperands(Ops);
}
if (ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
for (User::op_iterator b = CV->op_begin(), i = b, e = CV->op_end();
i != e; ++i) {
Value *MV = MapValue(*i, VM);
if (MV != *i) {
// This vector value must contain a reference to a global, make a new
// vector constant and return it.
//
std::vector<Constant*> Values;
Values.reserve(CV->getNumOperands());
for (User::op_iterator j = b; j != i; ++j)
Values.push_back(cast<Constant>(*j));
Values.push_back(cast<Constant>(MV));
for (++i; i != e; ++i)
Values.push_back(cast<Constant>(MapValue(*i, VM)));
return VM[V] = ConstantVector::get(Values);
}
}
return VM[V] = C;
}
if (BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
Function *F = cast<Function>(MapValue(BA->getFunction(), VM));
BasicBlock *BB = cast_or_null<BasicBlock>(MapValue(BA->getBasicBlock(),VM));
return VM[V] = BlockAddress::get(F, BB ? BB : BA->getBasicBlock());
}
llvm_unreachable("Unknown type of constant!");
return 0;
}
/// RemapInstruction - Convert the instruction operands from referencing the
/// current values into those specified by ValueMap.
///
void llvm::RemapInstruction(Instruction *I, ValueMapTy &ValueMap) {
for (User::op_iterator op = I->op_begin(), E = I->op_end(); op != E; ++op) {
Value *V = MapValue(*op, ValueMap);
assert(V && "Referenced value not in value map!");
*op = V;
}
// Map llvm.dbg.declare instruction's first operand, which points to
// alloca instruction through MDNode. Since MDNodes are not counted as normal
// uses, this will fall through cracks otherwise.
const DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(I);
if (!DDI) return;
Value *AddrInsn = DDI->getAddress();
if (!AddrInsn) return;
ValueMapTy::iterator VMI = ValueMap.find(AddrInsn);
if (VMI == ValueMap.end()) return;
Value *Elts[] = { VMI->second };
MDNode *NewAddr = MDNode::get(AddrInsn->getContext(), Elts, 1);
I->setOperand(1, NewAddr);
}
<commit_msg>Map operands of all function-local metadata, not just metadata passed to llvm.dbg.declare intrinsics<commit_after>//===- ValueMapper.cpp - Interface shared by lib/Transforms/Utils ---------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the MapValue function, which is shared by various parts of
// the lib/Transforms/Utils library.
//
//===----------------------------------------------------------------------===//
#include "llvm/Transforms/Utils/ValueMapper.h"
#include "llvm/DerivedTypes.h" // For getNullValue(Type::Int32Ty)
#include "llvm/Constants.h"
#include "llvm/Function.h"
#include "llvm/IntrinsicInst.h"
#include "llvm/Metadata.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/Support/ErrorHandling.h"
using namespace llvm;
Value *llvm::MapValue(const Value *V, ValueMapTy &VM) {
Value *&VMSlot = VM[V];
if (VMSlot) return VMSlot; // Does it exist in the map yet?
// NOTE: VMSlot can be invalidated by any reference to VM, which can grow the
// DenseMap. This includes any recursive calls to MapValue.
// Global values and non-function-local metadata do not need to be seeded into
// the ValueMap if they are using the identity mapping.
if (isa<GlobalValue>(V) || isa<InlineAsm>(V) || isa<MDString>(V) ||
(isa<MDNode>(V) && !dyn_cast<MDNode>(V)->isFunctionLocal()))
return VMSlot = const_cast<Value*>(V);
if (isa<MDNode>(V)) {
const MDNode *MD = dyn_cast<MDNode>(V);
std::vector<Value*> Elts;
Elts.reserve(MD->getNumOperands());
for (unsigned i = 0; i != MD->getNumOperands(); i++)
Elts.push_back(MapValue(MD->getOperand(i), VM));
return VM[V] = MDNode::get(V->getContext(), Elts.data(), Elts.size());
}
Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V));
if (C == 0) return 0;
if (isa<ConstantInt>(C) || isa<ConstantFP>(C) ||
isa<ConstantPointerNull>(C) || isa<ConstantAggregateZero>(C) ||
isa<UndefValue>(C) || isa<MDString>(C))
return VMSlot = C; // Primitive constants map directly
if (ConstantArray *CA = dyn_cast<ConstantArray>(C)) {
for (User::op_iterator b = CA->op_begin(), i = b, e = CA->op_end();
i != e; ++i) {
Value *MV = MapValue(*i, VM);
if (MV != *i) {
// This array must contain a reference to a global, make a new array
// and return it.
//
std::vector<Constant*> Values;
Values.reserve(CA->getNumOperands());
for (User::op_iterator j = b; j != i; ++j)
Values.push_back(cast<Constant>(*j));
Values.push_back(cast<Constant>(MV));
for (++i; i != e; ++i)
Values.push_back(cast<Constant>(MapValue(*i, VM)));
return VM[V] = ConstantArray::get(CA->getType(), Values);
}
}
return VM[V] = C;
}
if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
for (User::op_iterator b = CS->op_begin(), i = b, e = CS->op_end();
i != e; ++i) {
Value *MV = MapValue(*i, VM);
if (MV != *i) {
// This struct must contain a reference to a global, make a new struct
// and return it.
//
std::vector<Constant*> Values;
Values.reserve(CS->getNumOperands());
for (User::op_iterator j = b; j != i; ++j)
Values.push_back(cast<Constant>(*j));
Values.push_back(cast<Constant>(MV));
for (++i; i != e; ++i)
Values.push_back(cast<Constant>(MapValue(*i, VM)));
return VM[V] = ConstantStruct::get(CS->getType(), Values);
}
}
return VM[V] = C;
}
if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
std::vector<Constant*> Ops;
for (User::op_iterator i = CE->op_begin(), e = CE->op_end(); i != e; ++i)
Ops.push_back(cast<Constant>(MapValue(*i, VM)));
return VM[V] = CE->getWithOperands(Ops);
}
if (ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
for (User::op_iterator b = CV->op_begin(), i = b, e = CV->op_end();
i != e; ++i) {
Value *MV = MapValue(*i, VM);
if (MV != *i) {
// This vector value must contain a reference to a global, make a new
// vector constant and return it.
//
std::vector<Constant*> Values;
Values.reserve(CV->getNumOperands());
for (User::op_iterator j = b; j != i; ++j)
Values.push_back(cast<Constant>(*j));
Values.push_back(cast<Constant>(MV));
for (++i; i != e; ++i)
Values.push_back(cast<Constant>(MapValue(*i, VM)));
return VM[V] = ConstantVector::get(Values);
}
}
return VM[V] = C;
}
if (BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
Function *F = cast<Function>(MapValue(BA->getFunction(), VM));
BasicBlock *BB = cast_or_null<BasicBlock>(MapValue(BA->getBasicBlock(),VM));
return VM[V] = BlockAddress::get(F, BB ? BB : BA->getBasicBlock());
}
llvm_unreachable("Unknown type of constant!");
return 0;
}
/// RemapInstruction - Convert the instruction operands from referencing the
/// current values into those specified by ValueMap.
///
void llvm::RemapInstruction(Instruction *I, ValueMapTy &ValueMap) {
for (User::op_iterator op = I->op_begin(), E = I->op_end(); op != E; ++op) {
Value *V = MapValue(*op, ValueMap);
assert(V && "Referenced value not in value map!");
*op = V;
}
}
<|endoftext|>
|
<commit_before><commit_msg>cleanup chainparams.cpp<commit_after><|endoftext|>
|
<commit_before>//===----------------------------------------------------------------------===//
//
// Peloton
//
// catalog_cache.cpp
//
// Identification: src/catalog/catalog_cache.cpp
//
// Copyright (c) 2015-17, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#include <memory>
#include "catalog/catalog_cache.h"
namespace peloton {
namespace catalog {
/*@brief insert database catalog object into cache
* @param database_object
* @param forced if forced, replace existing object, else return false if oid
* already exists
* @return false only if not forced and database_oid already exists in cache
*/
bool CatalogCache::InsertDatabaseObject(
std::shared_ptr<DatabaseCatalogObject> &database_object, bool forced) {
if (!database_object || database_object->database_oid == INVALID_OID) {
return false; // invalid object
}
// std::lock_guard<std::mutex> lock(database_cache_lock);
auto object_iter = database_objects_cache.find(database_object->database_oid);
if (forced == true && object_iter != database_objects_cache.end()) {
database_objects_cache.erase(object_iter); // Evict old
database_name_cache.erase(database_object->database_name);
object_iter = database_objects_cache.find(database_object->database_oid);
}
if (object_iter == database_objects_cache.end()) {
auto cached_object =
std::shared_ptr<DatabaseCatalogObject>(database_object);
database_objects_cache.insert(
std::make_pair(database_object->database_oid, cached_object));
database_name_cache.insert(std::make_pair(database_object->database_name,
cached_object->database_oid));
return true;
} else {
return false;
}
}
/*@brief evict database catalog object from cache
* @param database_oid
* @return true if database_oid is found and evicted; false if not found
*/
bool CatalogCache::EvictDatabaseObject(oid_t database_oid) {
// std::lock_guard<std::mutex> lock(database_cache_lock);
auto it = database_objects_cache.find(database_oid);
if (it == database_objects_cache.end()) {
return false;
} else {
database_name_cache.erase(it->second->database_name);
database_objects_cache.erase(it);
return true;
}
}
/*@brief get database catalog object from cache
* @param database_oid
* @return database catalog object; if not found return object with invalid oid
*/
std::shared_ptr<DatabaseCatalogObject> CatalogCache::GetDatabaseObject(
oid_t database_oid) {
// std::lock_guard<std::mutex> lock(database_cache_lock);
auto it = database_objects_cache.find(database_oid);
if (it == database_objects_cache.end()) {
return std::make_shared<DatabaseCatalogObject>();
}
return it->second;
}
/*@brief get database catalog object from cache
* @param database_name
* @return database catalog object; if not found return object with invalid oid
*/
std::shared_ptr<DatabaseCatalogObject> CatalogCache::GetDatabaseObject(
const std::string &database_name) {
// std::lock_guard<std::mutex> lock(database_cache_lock);
auto it = database_name_cache.find(database_name);
if (it == database_name_cache.end()) {
return std::make_shared<DatabaseCatalogObject>();
}
oid_t database_oid = it->second;
return database_objects_cache.find(database_oid)->second;
}
/*@brief insert table catalog object into cache
* @param table_object
* @param forced if forced, replace existing object, else return false if oid
* already exists
* @return false only if not forced and table_oid already exists in cache
*/
bool CatalogCache::InsertTableObject(
std::shared_ptr<TableCatalogObject> table_object, bool forced) {
if (!table_object || table_object->table_oid == INVALID_OID) {
return false; // invalid object
}
// find old table catalog object
// std::lock_guard<std::mutex> lock(table_cache_lock);
auto it = table_objects_cache.find(table_object->table_oid);
// forced evict if found
if (forced == true && it != table_objects_cache.end()) {
if (it->second == table_object) return false; // no need to replace
EvictTableObject(table_object->table_oid); // evict old
it = table_objects_cache.find(table_object->table_oid);
}
// insert into table object cache
if (it == table_objects_cache.end()) {
table_objects_cache.insert(
std::make_pair(table_object->table_oid, table_object));
// find and insert into database catalog object too
auto database_object = GetDatabaseObject(table_object->database_oid);
if (database_object) {
database_object->InsertTableObject(table_object, forced);
}
return true;
} else {
return false; // table oid already exists
}
}
/*@brief evict table catalog object from cache
* @param table_oid
* @return true if table_oid is found and evicted; false if not found
*/
bool CatalogCache::EvictTableObject(oid_t table_oid) {
if (table_oid == INVALID_OID) return false;
// std::lock_guard<std::mutex> lock(table_cache_lock);
// find table oid from catalog cache
auto it = table_objects_cache.find(table_oid);
if (it != table_objects_cache.end()) {
auto table_object = it->second;
table_objects_cache.erase(it);
if (table_object) {
// find and evict table name from database object's cache
auto database_object = GetDatabaseObject(table_object->database_oid);
if (database_object) {
database_object->EvictTableObject(
table_object->table_name); // evict old name
}
}
return true;
} else {
return false; // table oid not found in cache
}
}
/*@brief get table catalog object from cache
* @param table_oid
* @return table catalog object; if not found return object with invalid oid
*/
std::shared_ptr<TableCatalogObject> CatalogCache::GetTableObject(
oid_t table_oid) {
// std::lock_guard<std::mutex> lock(table_cache_lock);
auto it = table_objects_cache.find(table_oid);
if (it == table_objects_cache.end()) {
// if (txn == nullptr) return TableCatalogObject();
// bool success = InsertTableObject(
// TableCatalog::GetInstance()->GetTableObject(table_oid, txn));
// PL_ASSERT(success == true);
// it = table_objects_cache.find(table_oid)
return nullptr;
}
return it->second;
}
} // namespace catalog
} // namespace peloton
<commit_msg>fixed shared pointer nullptr problem<commit_after>//===----------------------------------------------------------------------===//
//
// Peloton
//
// catalog_cache.cpp
//
// Identification: src/catalog/catalog_cache.cpp
//
// Copyright (c) 2015-17, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#include <memory>
#include "catalog/catalog_cache.h"
namespace peloton {
namespace catalog {
/*@brief insert database catalog object into cache
* @param database_object
* @param forced if forced, replace existing object, else return false if oid
* already exists
* @return false only if not forced and database_oid already exists in cache
*/
bool CatalogCache::InsertDatabaseObject(
std::shared_ptr<DatabaseCatalogObject> &database_object, bool forced) {
if (!database_object || database_object->database_oid == INVALID_OID) {
return false; // invalid object
}
// std::lock_guard<std::mutex> lock(database_cache_lock);
auto object_iter = database_objects_cache.find(database_object->database_oid);
if (forced == true && object_iter != database_objects_cache.end()) {
database_objects_cache.erase(object_iter); // Evict old
database_name_cache.erase(database_object->database_name);
object_iter = database_objects_cache.find(database_object->database_oid);
}
if (object_iter == database_objects_cache.end()) {
auto cached_object =
std::shared_ptr<DatabaseCatalogObject>(database_object);
database_objects_cache.insert(
std::make_pair(database_object->database_oid, cached_object));
database_name_cache.insert(std::make_pair(database_object->database_name,
cached_object->database_oid));
return true;
} else {
return false;
}
}
/*@brief evict database catalog object from cache
* @param database_oid
* @return true if database_oid is found and evicted; false if not found
*/
bool CatalogCache::EvictDatabaseObject(oid_t database_oid) {
// std::lock_guard<std::mutex> lock(database_cache_lock);
auto it = database_objects_cache.find(database_oid);
if (it == database_objects_cache.end()) {
return false;
} else {
database_name_cache.erase(it->second->database_name);
database_objects_cache.erase(it);
return true;
}
}
/*@brief get database catalog object from cache
* @param database_oid
* @return database catalog object; if not found return object with invalid oid
*/
std::shared_ptr<DatabaseCatalogObject> CatalogCache::GetDatabaseObject(
oid_t database_oid) {
// std::lock_guard<std::mutex> lock(database_cache_lock);
auto it = database_objects_cache.find(database_oid);
if (it == database_objects_cache.end()) {
return nullptr;
}
return it->second;
}
/*@brief get database catalog object from cache
* @param database_name
* @return database catalog object; if not found return object with invalid oid
*/
std::shared_ptr<DatabaseCatalogObject> CatalogCache::GetDatabaseObject(
const std::string &database_name) {
// std::lock_guard<std::mutex> lock(database_cache_lock);
auto it = database_name_cache.find(database_name);
if (it == database_name_cache.end()) {
return nullptr;
}
oid_t database_oid = it->second;
return database_objects_cache.find(database_oid)->second;
}
/*@brief insert table catalog object into cache
* @param table_object
* @param forced if forced, replace existing object, else return false if oid
* already exists
* @return false only if not forced and table_oid already exists in cache
*/
bool CatalogCache::InsertTableObject(
std::shared_ptr<TableCatalogObject> table_object, bool forced) {
if (!table_object || table_object->table_oid == INVALID_OID) {
return false; // invalid object
}
// find old table catalog object
// std::lock_guard<std::mutex> lock(table_cache_lock);
auto it = table_objects_cache.find(table_object->table_oid);
// forced evict if found
if (forced == true && it != table_objects_cache.end()) {
if (it->second == table_object) return false; // no need to replace
EvictTableObject(table_object->table_oid); // evict old
it = table_objects_cache.find(table_object->table_oid);
}
// insert into table object cache
if (it == table_objects_cache.end()) {
table_objects_cache.insert(
std::make_pair(table_object->table_oid, table_object));
// find and insert into database catalog object too
auto database_object = GetDatabaseObject(table_object->database_oid);
if (database_object) {
database_object->InsertTableObject(table_object, forced);
}
return true;
} else {
return false; // table oid already exists
}
}
/*@brief evict table catalog object from cache
* @param table_oid
* @return true if table_oid is found and evicted; false if not found
*/
bool CatalogCache::EvictTableObject(oid_t table_oid) {
if (table_oid == INVALID_OID) return false;
// std::lock_guard<std::mutex> lock(table_cache_lock);
// find table oid from catalog cache
auto it = table_objects_cache.find(table_oid);
if (it != table_objects_cache.end()) {
auto table_object = it->second;
table_objects_cache.erase(it);
if (table_object) {
// find and evict table name from database object's cache
auto database_object = GetDatabaseObject(table_object->database_oid);
if (database_object) {
database_object->EvictTableObject(
table_object->table_name); // evict old name
}
}
return true;
} else {
return false; // table oid not found in cache
}
}
/*@brief get table catalog object from cache
* @param table_oid
* @return table catalog object; if not found return object with invalid oid
*/
std::shared_ptr<TableCatalogObject> CatalogCache::GetTableObject(
oid_t table_oid) {
// std::lock_guard<std::mutex> lock(table_cache_lock);
auto it = table_objects_cache.find(table_oid);
if (it == table_objects_cache.end()) {
// if (txn == nullptr) return TableCatalogObject();
// bool success = InsertTableObject(
// TableCatalog::GetInstance()->GetTableObject(table_oid, txn));
// PL_ASSERT(success == true);
// it = table_objects_cache.find(table_oid)
return nullptr;
}
return it->second;
}
} // namespace catalog
} // namespace peloton
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2008 James Molloy, Jörg Pfähler, Matthew Iselin
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <Debugger.h>
#include <DebuggerIO.h>
#include <LocalIO.h>
#include <SerialIO.h>
#include <utilities/StaticString.h>
#include <processor/Processor.h>
#include <machine/Machine.h>
#include <Log.h>
#include <utilities/utility.h>
#include <panic.h>
void _assert(bool b, const char *file, int line, const char *func)
{
if(b)
return;
ERROR("Assertion failed in file " << file << " (line " << Dec << line << Hex << ")");
ERROR("In function '" << func << "'.");
Processor::breakpoint();
ERROR("You may not resume after a failed assertion.");
// Best reason for a return is that the debugger isn't active. Either way, it's an error condition, panic.
panic("assertion failed");
Processor::halt();
}
<commit_msg>Make sure assertion failure messages don't put really important information such as line numbers past the 80 character limit.<commit_after>/*
* Copyright (c) 2008 James Molloy, Jörg Pfähler, Matthew Iselin
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <Debugger.h>
#include <DebuggerIO.h>
#include <LocalIO.h>
#include <SerialIO.h>
#include <utilities/StaticString.h>
#include <processor/Processor.h>
#include <machine/Machine.h>
#include <Log.h>
#include <utilities/utility.h>
#include <panic.h>
void _assert(bool b, const char *file, int line, const char *func)
{
if(b)
return;
ERROR("Assertion failed in file " << file);
ERROR("In function '" << func << "'");
ERROR("On line " << Dec << line << Hex << ".");
Processor::breakpoint();
ERROR("You may not resume after a failed assertion.");
// Best reason for a return is that the debugger isn't active. Either way, it's an error condition, panic.
panic("assertion failed");
Processor::halt();
}
<|endoftext|>
|
<commit_before>/*
// License Agreement (3-clause BSD License)
// Copyright (c) 2015, Klaus Haag, all rights reserved.
// Third party copyrights and patents are property of their respective owners.
//
// 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 names of the copyright holders nor the names of the contributors
// may be used to endorse or promote products derived from this software
// without specific prior written permission.
//
// This software is provided by 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 copyright holders 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 KCF_DEBUG_HPP_
#define KCF_DEBUG_HPP_
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/core/core.hpp"
#include <iostream>
#include <fstream>
#include "tracker_debug.hpp"
namespace cf_tracking
{
template<typename T>
class KcfDebug : public TrackerDebug
{
public:
KcfDebug() :
_maxResponse(0),
_psrClamped(0)
{}
virtual ~KcfDebug()
{
if (_outputFile.is_open())
_outputFile.close();
}
virtual void init(std::string outputFilePath)
{
namedWindow(_SUB_WINDOW_TITLE, cv::WINDOW_NORMAL);
namedWindow(_RESPONSE_TITLE, cv::WINDOW_NORMAL);
_outputFile.open(outputFilePath.c_str());
}
virtual void printOnImage(cv::Mat& image)
{
_ss.str("");
_ss.clear();
_ss << "Max Response: " << _maxResponse;
putText(image, _ss.str(), cv::Point(20, 40), cv::FONT_HERSHEY_TRIPLEX, 0.5, cv::Scalar(255, 0, 0));
_ss.str("");
_ss.clear();
_ss << "PSR Clamped: " << _psrClamped;
putText(image, _ss.str(), cv::Point(20, 80), cv::FONT_HERSHEY_TRIPLEX, 0.5, cv::Scalar(255, 0, 0));
}
virtual void printConsoleOutput()
{
}
virtual void printToFile()
{
_outputFile << _maxResponse << "," << _psrClamped << std::endl;
}
void showPatch(const cv::Mat& patchResized)
{
imshow(_SUB_WINDOW_TITLE, patchResized);
}
void setPsr(T psrClamped)
{
_psrClamped = psrClamped;
std::cout << "PSR: " << psrClamped << std::endl;
}
void showResponse(const cv::Mat& response, T maxResponse)
{
cv::Mat responseOutput = response.clone();
_maxResponse = maxResponse;
imshow(_RESPONSE_TITLE, responseOutput);
}
private:
const std::string _SUB_WINDOW_TITLE = "Sub Window";
const std::string _RESPONSE_TITLE = "Response";
T _maxResponse;
T _psrClamped;
std::stringstream _ss;
std::ofstream _outputFile;
};
}
#endif
<commit_msg>even more embedded changes<commit_after>/*
// License Agreement (3-clause BSD License)
// Copyright (c) 2015, Klaus Haag, all rights reserved.
// Third party copyrights and patents are property of their respective owners.
//
// 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 names of the copyright holders nor the names of the contributors
// may be used to endorse or promote products derived from this software
// without specific prior written permission.
//
// This software is provided by 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 copyright holders 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 KCF_DEBUG_HPP_
#define KCF_DEBUG_HPP_
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/core/core.hpp"
#include <iostream>
#include <fstream>
#include "tracker_debug.hpp"
namespace cf_tracking
{
template<typename T>
class KcfDebug : public TrackerDebug
{
public:
KcfDebug() :
_maxResponse(0),
_psrClamped(0),
_SUB_WINDOW_TITLE("Sub Window"),
_RESPONSE_TITLE("Response")
{}
virtual ~KcfDebug()
{
if (_outputFile.is_open())
_outputFile.close();
}
virtual void init(std::string outputFilePath)
{
namedWindow(_SUB_WINDOW_TITLE, cv::WINDOW_NORMAL);
namedWindow(_RESPONSE_TITLE, cv::WINDOW_NORMAL);
_outputFile.open(outputFilePath.c_str());
}
virtual void printOnImage(cv::Mat& image)
{
_ss.str("");
_ss.clear();
_ss << "Max Response: " << _maxResponse;
putText(image, _ss.str(), cv::Point(20, 40), cv::FONT_HERSHEY_TRIPLEX, 0.5, cv::Scalar(255, 0, 0));
_ss.str("");
_ss.clear();
_ss << "PSR Clamped: " << _psrClamped;
putText(image, _ss.str(), cv::Point(20, 80), cv::FONT_HERSHEY_TRIPLEX, 0.5, cv::Scalar(255, 0, 0));
}
virtual void printConsoleOutput()
{
}
virtual void printToFile()
{
_outputFile << _maxResponse << "," << _psrClamped << std::endl;
}
void showPatch(const cv::Mat& patchResized)
{
imshow(_SUB_WINDOW_TITLE, patchResized);
}
void setPsr(T psrClamped)
{
_psrClamped = psrClamped;
std::cout << "PSR: " << psrClamped << std::endl;
}
void showResponse(const cv::Mat& response, T maxResponse)
{
cv::Mat responseOutput = response.clone();
_maxResponse = maxResponse;
imshow(_RESPONSE_TITLE, responseOutput);
}
private:
const std::string _SUB_WINDOW_TITLE;
const std::string _RESPONSE_TITLE;
T _maxResponse;
T _psrClamped;
std::stringstream _ss;
std::ofstream _outputFile;
};
}
#endif
<|endoftext|>
|
<commit_before>#ifndef VARIADIC_TEMPLATES_HPP
#define VARIADIC_TEMPLATES_HPP
/*
We need to implement variadic template function that takes arbitrary number
of arguments of unknown types and it should return sum of the arguments with
type int.
*/
#include <iostream>
namespace Templates::VariadicTemplates {
template<typename... Args>
int CalcInts() {
return 0;
}
template<typename T, typename... Args>
int CalcInts(T /*value*/, Args... args) {
return 0 + CalcInts(args...);
}
template<typename... Args>
int CalcInts(int /*value*/, Args... args) {
return 1 + CalcInts(args...);
}
template<typename T>
int CalcInts(T /*value*/) {
return 0;
}
template<>
int CalcInts<int>(int /*value*/) {
return 1;
}
void SumIntegersViaVariadicTemplate() {
std::cout << "Take 1: " << CalcInts() << std::endl;
std::cout << "Take 2: " << CalcInts(1) << std::endl;
std::cout << "Take 3: " << CalcInts("abc") << std::endl;
std::cout << "Take 4: " << CalcInts(1, 2) << std::endl;
std::cout << "Take 5: " << CalcInts("ab", 2) << std::endl;
std::cout << "Take 6: " << CalcInts(5, "ab", 2) << std::endl;
}
void Start() {
SumIntegersViaVariadicTemplate();
}
}
#endif // VARIADIC_TEMPLATES_HPP
<commit_msg>Fix variadic template examples<commit_after>#ifndef VARIADIC_TEMPLATES_HPP
#define VARIADIC_TEMPLATES_HPP
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
namespace Templates::VariadicTemplates {
/*
We need a function that accept unknown number of parameters, convert them
to strings and return vector of these strings
*/
// Template function that transform argument to a string
template<typename T>
std::string ToStringImpl(const T& value) {
std::stringstream ss;
ss << value;
return ss.str();
}
// Base case of the variadic template - no args
std::vector<std::string> ToString() {
return {};
}
// Variadic template that accepts unknown number of args, pass them to
// ToStringImpl() and put result into a vector
template<typename T, typename... Args>
std::vector<std::string> ToString(const T& value, const Args& ... args) {
std::vector<std::string> vec;
vec.push_back(ToStringImpl(value));
const auto remainder = ToString(args...);
vec.insert(vec.end(), remainder.begin(), remainder.end());
return vec;
}
// Simplified solution
template<typename... Args>
std::vector<std::string> ToStringSimplified(const Args& ... args) {
return { ToStringImpl(args)... };
}
void TransformValuesToStrings() {
const auto strings = ToString(1, "hello", 7.1);
for (const auto& s : strings) {
std::cout << s << std::endl;
}
const auto strings2 = ToString("world", 'a');
for (const auto& s : strings2) {
std::cout << s << std::endl;
}
}
/*
We need to implement variadic template function that takes arbitrary number
of arguments of unknown types and it should return sum of the arguments with
type int.
*/
int DetectInt(int /*value*/) {
return 1;
}
template<typename T>
int DetectInt(T /*value*/) {
return 0;
}
int CalcInts() {
return 0;
}
template<typename T, typename... Args>
int CalcInts(T value, Args... args) {
return DetectInt(value) + CalcInts(args...);
}
void SumIntegersViaVariadicTemplate() {
std::cout << "Take 1: " << CalcInts() << std::endl;
std::cout << "Take 2: " << CalcInts(1) << std::endl;
std::cout << "Take 3: " << CalcInts("abc") << std::endl;
std::cout << "Take 4: " << CalcInts(1, 2) << std::endl;
std::cout << "Take 5: " << CalcInts("ab", 2) << std::endl;
std::cout << "Take 6: " << CalcInts(5, "ab", 2, 3) << std::endl;
}
void Start() {
TransformValuesToStrings();
SumIntegersViaVariadicTemplate();
}
}
#endif // VARIADIC_TEMPLATES_HPP
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2010, The Cinder Project (http://libcinder.org)
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that
the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and
the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
the following disclaimer in the documentation and/or other materials provided with the distribution.
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 "cinder/UrlImplWinInet.h"
#include "cinder/Utilities.h"
#include <Windows.h>
#include <Wininet.h>
#include <Strsafe.h>
#pragma comment( lib, "wininet.lib" )
namespace cinder {
namespace { static const WCHAR AGENT_NAME[] = L"libcinder"; }
// Call InternetCloseHandle, testing for NULL. Designed to be the deallocator for shared_ptr's
void safeInternetCloseHandle( HINTERNET hInternet )
{
if( hInternet )
::InternetCloseHandle( hInternet );
}
IStreamUrlImplWinInet::IStreamUrlImplWinInet( const std::string &url, const std::string &user, const std::string &password, const UrlOptions &options )
: IStreamUrlImpl( user, password, options ), mIsFinished( false ), mBuffer( 0 ), mBufferFileOffset( 0 )
{
std::wstring wideUrl = toUtf16( url );
// we need to break the URL up into its constituent parts so we can choose a scheme
URL_COMPONENTS urlComponents;
::memset( &urlComponents, 0, sizeof(urlComponents) );
urlComponents.dwStructSize = sizeof(urlComponents);
urlComponents.dwSchemeLength = 1;
urlComponents.dwHostNameLength = 1;
urlComponents.dwUrlPathLength = 1;
BOOL success = ::InternetCrackUrl( wideUrl.c_str(), 0, 0, &urlComponents );
if( ! success )
throw StreamExc();
// TODO this should be made safe against buffer overflows
WCHAR host[1024], path[2048];
memcpy( host, urlComponents.lpszHostName, urlComponents.dwHostNameLength * sizeof(WCHAR) );
host[urlComponents.dwHostNameLength] = 0;
memcpy( path, urlComponents.lpszUrlPath, urlComponents.dwUrlPathLength * sizeof(WCHAR) );
path[urlComponents.dwUrlPathLength] = 0;
// make sure this a scheme we know about - HTTP(S) or FTP
switch( urlComponents.nScheme ) {
case INTERNET_SCHEME_HTTP: case INTERNET_SCHEME_HTTPS: case INTERNET_SCHEME_FTP: break;
default: throw StreamExc();
}
mSession = std::shared_ptr<void>( ::InternetOpen( AGENT_NAME, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0 ), safeInternetCloseHandle );
if( ! mSession )
throw StreamExc();
std::wstring wideUser = toUtf16( user );
std::wstring widePassword = toUtf16( password );
//check for HTTP and HTTPS here because they both require the same flag in InternetConnect()
if( ( urlComponents.nScheme == INTERNET_SCHEME_HTTP ) ||
( urlComponents.nScheme == INTERNET_SCHEME_HTTPS ) ) {
mConnection = std::shared_ptr<void>( ::InternetConnect( mSession.get(), host, urlComponents.nPort, (wideUser.empty()) ? NULL : wideUser.c_str(), (widePassword.empty()) ? NULL : widePassword.c_str(), INTERNET_SERVICE_HTTP, 0, NULL ),
safeInternetCloseHandle );
}else{
//otherwise we just want to take our best shot at the Scheme type.
mConnection = std::shared_ptr<void>( ::InternetConnect( mSession.get(), host, urlComponents.nPort, (wideUser.empty()) ? NULL : wideUser.c_str(), (widePassword.empty()) ? NULL : widePassword.c_str(), urlComponents.nScheme, 0, NULL ),
safeInternetCloseHandle );
}
if( ! mConnection )
throw StreamExc();
//http and https cases broken out incase someone wishes to modify connection based off of type.
//it is wrong to group http with https.
//http
DWORD flags = INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_NO_COOKIES;
if( options.getIgnoreCache() )
flags |= INTERNET_FLAG_RELOAD;
if( urlComponents.nScheme == INTERNET_SCHEME_HTTP ) {
static LPCTSTR lpszAcceptTypes[] = { L"*/*", NULL };
mRequest = std::shared_ptr<void>( ::HttpOpenRequest( mConnection.get(), L"GET", path, NULL, NULL, lpszAcceptTypes,
flags, NULL ),
safeInternetCloseHandle );
if( ! mRequest )
throw StreamExc();
BOOL success = ::HttpSendRequest( mRequest.get(), NULL, 0, NULL, 0);
if( ! success )
throw StreamExc();
}
//https
else if(urlComponents.nScheme == INTERNET_SCHEME_HTTPS ) {
static LPCTSTR lpszAcceptTypes[] = { L"*/*", NULL };
mRequest = std::shared_ptr<void>( ::HttpOpenRequest( mConnection.get(), L"GET", path, NULL, NULL, lpszAcceptTypes,
flags | INTERNET_FLAG_SECURE, NULL ),
safeInternetCloseHandle );
if( ! mRequest )
throw StreamExc();
BOOL success = ::HttpSendRequest( mRequest.get(), NULL, 0, NULL, 0);
if( ! success )
throw StreamExc();
}
//ftp
else if( urlComponents.nScheme == INTERNET_SCHEME_FTP ) {
mRequest = std::shared_ptr<void>( ::FtpOpenFile( mConnection.get(), path, GENERIC_READ, FTP_TRANSFER_TYPE_BINARY, NULL ),
safeInternetCloseHandle );
if( ! mRequest )
throw StreamExc();
}
mBufferSize = DEFAULT_BUFFER_SIZE;
mBuffer = (uint8_t*)malloc( mBufferSize );
mBufferOffset = 0;
mBufferedBytes = 0;
mBufferFileOffset = 0;
}
IStreamUrlImplWinInet::~IStreamUrlImplWinInet()
{
if( mBuffer )
free( mBuffer );
}
bool IStreamUrlImplWinInet::isEof() const
{
return ( mBufferedBytes - mBufferOffset == 0 ) && ( mIsFinished );
}
void IStreamUrlImplWinInet::seekRelative( off_t relativeOffset )
{
// if this move stays inside the current buffer, we're good
if( ( mBufferOffset + relativeOffset >= 0 ) && ( mBufferOffset + relativeOffset < mBufferedBytes ) ) {
mBufferOffset += relativeOffset;
return;
}
else if( relativeOffset < 0 ) { // if we're moving backwards out of the buffer, we have to reset
throw StreamExc(); // need to implement this
}
else { // moving forward off the end of the buffer - keep buffering til we're in range
throw StreamExc(); // need to implement this
}
}
void IStreamUrlImplWinInet::seekAbsolute( off_t absoluteOffset )
{
seekRelative( absoluteOffset - ( mBufferFileOffset + mBufferOffset ) );
}
off_t IStreamUrlImplWinInet::tell() const
{
return mBufferFileOffset + mBufferOffset;
}
off_t IStreamUrlImplWinInet::size() const
{
return 0; // we don't know the size
}
void IStreamUrlImplWinInet::fillBuffer( int wantBytes ) const
{
// we've already got all the data we need
if( bufferDataRemaining() > wantBytes )
return;
// if we want more bytes than will fit in the rest of the buffer, let's make some room
if( mBufferSize - mBufferedBytes < wantBytes ) {
int bytesCulled = mBufferOffset;
memmove( mBuffer, &mBuffer[mBufferOffset], mBufferedBytes - bytesCulled );
mBufferedBytes -= bytesCulled;
mBufferOffset = 0;
mBufferFileOffset += bytesCulled;
}
// now if we've made all the room there is to make, and we still aren't big enough, reallocate
if( wantBytes > mBufferSize - mBufferedBytes ) {
// not enough space in buffer
int oldBufferSize = mBufferSize;
while( mBufferSize - mBufferedBytes < wantBytes )
mBufferSize *= 2;
uint8_t *newBuff = reinterpret_cast<uint8_t*>( realloc( mBuffer, mBufferSize ) );
if( ! newBuff ) {
throw StreamExc();
}
else {
// realloc suceeded increase buffer size
mBuffer = newBuff;
}
}
do {
::DWORD bytesAvailable, bytesToRead, bytesRead;
if( ! ::InternetQueryDataAvailable( mRequest.get(), &bytesAvailable, 0, 0 ) )
throw StreamExc();
if( bytesAvailable == 0 ) {
mIsFinished = true;
break;
}
bytesToRead = std::min<int>( bytesAvailable, wantBytes );
if( ! ::InternetReadFile( mRequest.get(), mBuffer + mBufferedBytes, bytesToRead, &bytesRead ) )
throw StreamExc();
mBufferedBytes += bytesRead;
wantBytes -= bytesRead;
if( wantBytes < 0 )
wantBytes = 0;
} while( wantBytes );
}
void IStreamUrlImplWinInet::IORead( void *dest, size_t size )
{
fillBuffer( size );
// check if theres data in the buffer - if not fillBuffer() either errored or EOF
if( bufferDataRemaining() < (off_t)size )
throw StreamExc();
memcpy( dest, mBuffer + mBufferOffset, size );
mBufferOffset += size;
}
size_t IStreamUrlImplWinInet::readDataAvailable( void *dest, size_t maxSize )
{
fillBuffer( maxSize );
if( bufferDataRemaining() < (off_t)maxSize )
maxSize = bufferDataRemaining();
memcpy( dest, mBuffer + mBufferOffset, maxSize );
mBufferOffset += maxSize;
return maxSize;
}
} // namespace cinder<commit_msg>Implemented UrlOptions timeout on MSW<commit_after>/*
Copyright (c) 2010, The Cinder Project (http://libcinder.org)
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that
the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and
the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
the following disclaimer in the documentation and/or other materials provided with the distribution.
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 "cinder/UrlImplWinInet.h"
#include "cinder/Utilities.h"
#include <Windows.h>
#include <Wininet.h>
#include <Strsafe.h>
#pragma comment( lib, "wininet.lib" )
namespace cinder {
namespace { static const WCHAR AGENT_NAME[] = L"libcinder"; }
// Call InternetCloseHandle, testing for NULL. Designed to be the deallocator for shared_ptr's
void safeInternetCloseHandle( HINTERNET hInternet )
{
if( hInternet )
::InternetCloseHandle( hInternet );
}
IStreamUrlImplWinInet::IStreamUrlImplWinInet( const std::string &url, const std::string &user, const std::string &password, const UrlOptions &options )
: IStreamUrlImpl( user, password, options ), mIsFinished( false ), mBuffer( 0 ), mBufferFileOffset( 0 )
{
std::wstring wideUrl = toUtf16( url );
// we need to break the URL up into its constituent parts so we can choose a scheme
URL_COMPONENTS urlComponents;
::memset( &urlComponents, 0, sizeof(urlComponents) );
urlComponents.dwStructSize = sizeof(urlComponents);
urlComponents.dwSchemeLength = 1;
urlComponents.dwHostNameLength = 1;
urlComponents.dwUrlPathLength = 1;
BOOL success = ::InternetCrackUrl( wideUrl.c_str(), 0, 0, &urlComponents );
if( ! success )
throw StreamExc();
// TODO this should be made safe against buffer overflows
WCHAR host[1024], path[2048];
memcpy( host, urlComponents.lpszHostName, urlComponents.dwHostNameLength * sizeof(WCHAR) );
host[urlComponents.dwHostNameLength] = 0;
memcpy( path, urlComponents.lpszUrlPath, urlComponents.dwUrlPathLength * sizeof(WCHAR) );
path[urlComponents.dwUrlPathLength] = 0;
// make sure this a scheme we know about - HTTP(S) or FTP
switch( urlComponents.nScheme ) {
case INTERNET_SCHEME_HTTP: case INTERNET_SCHEME_HTTPS: case INTERNET_SCHEME_FTP: break;
default: throw StreamExc();
}
mSession = std::shared_ptr<void>( ::InternetOpen( AGENT_NAME, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0 ), safeInternetCloseHandle );
if( ! mSession )
throw StreamExc();
std::wstring wideUser = toUtf16( user );
std::wstring widePassword = toUtf16( password );
//check for HTTP and HTTPS here because they both require the same flag in InternetConnect()
if( ( urlComponents.nScheme == INTERNET_SCHEME_HTTP ) ||
( urlComponents.nScheme == INTERNET_SCHEME_HTTPS ) ) {
mConnection = std::shared_ptr<void>( ::InternetConnect( mSession.get(), host, urlComponents.nPort, (wideUser.empty()) ? NULL : wideUser.c_str(), (widePassword.empty()) ? NULL : widePassword.c_str(), INTERNET_SERVICE_HTTP, 0, NULL ),
safeInternetCloseHandle );
}else{
//otherwise we just want to take our best shot at the Scheme type.
mConnection = std::shared_ptr<void>( ::InternetConnect( mSession.get(), host, urlComponents.nPort, (wideUser.empty()) ? NULL : wideUser.c_str(), (widePassword.empty()) ? NULL : widePassword.c_str(), urlComponents.nScheme, 0, NULL ),
safeInternetCloseHandle );
}
if( ! mConnection )
throw StreamExc();
//http and https cases broken out incase someone wishes to modify connection based off of type.
//it is wrong to group http with https.
unsigned long timeoutMillis = static_cast<unsigned long>( options.getTimeout() * 1000 );
::InternetSetOptionW( mConnection.get(), INTERNET_OPTION_RECEIVE_TIMEOUT, &timeoutMillis, sizeof(unsigned long) );
::InternetSetOptionW( mConnection.get(), INTERNET_OPTION_CONNECT_TIMEOUT, &timeoutMillis, sizeof(unsigned long) );
::InternetSetOptionW( mConnection.get(), INTERNET_OPTION_SEND_TIMEOUT, &timeoutMillis, sizeof(unsigned long) );
//http
DWORD flags = INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_NO_COOKIES;
if( options.getIgnoreCache() )
flags |= INTERNET_FLAG_RELOAD;
if( urlComponents.nScheme == INTERNET_SCHEME_HTTP ) {
static LPCTSTR lpszAcceptTypes[] = { L"*/*", NULL };
mRequest = std::shared_ptr<void>( ::HttpOpenRequest( mConnection.get(), L"GET", path, NULL, NULL, lpszAcceptTypes,
flags, NULL ),
safeInternetCloseHandle );
if( ! mRequest )
throw StreamExc();
BOOL success = ::HttpSendRequest( mRequest.get(), NULL, 0, NULL, 0);
if( ! success )
throw StreamExc();
}
//https
else if(urlComponents.nScheme == INTERNET_SCHEME_HTTPS ) {
static LPCTSTR lpszAcceptTypes[] = { L"*/*", NULL };
mRequest = std::shared_ptr<void>( ::HttpOpenRequest( mConnection.get(), L"GET", path, NULL, NULL, lpszAcceptTypes,
flags | INTERNET_FLAG_SECURE, NULL ),
safeInternetCloseHandle );
if( ! mRequest )
throw StreamExc();
BOOL success = ::HttpSendRequest( mRequest.get(), NULL, 0, NULL, 0);
if( ! success )
throw StreamExc();
}
//ftp
else if( urlComponents.nScheme == INTERNET_SCHEME_FTP ) {
mRequest = std::shared_ptr<void>( ::FtpOpenFile( mConnection.get(), path, GENERIC_READ, FTP_TRANSFER_TYPE_BINARY, NULL ),
safeInternetCloseHandle );
if( ! mRequest )
throw StreamExc();
}
mBufferSize = DEFAULT_BUFFER_SIZE;
mBuffer = (uint8_t*)malloc( mBufferSize );
mBufferOffset = 0;
mBufferedBytes = 0;
mBufferFileOffset = 0;
}
IStreamUrlImplWinInet::~IStreamUrlImplWinInet()
{
if( mBuffer )
free( mBuffer );
}
bool IStreamUrlImplWinInet::isEof() const
{
return ( mBufferedBytes - mBufferOffset == 0 ) && ( mIsFinished );
}
void IStreamUrlImplWinInet::seekRelative( off_t relativeOffset )
{
// if this move stays inside the current buffer, we're good
if( ( mBufferOffset + relativeOffset >= 0 ) && ( mBufferOffset + relativeOffset < mBufferedBytes ) ) {
mBufferOffset += relativeOffset;
return;
}
else if( relativeOffset < 0 ) { // if we're moving backwards out of the buffer, we have to reset
throw StreamExc(); // need to implement this
}
else { // moving forward off the end of the buffer - keep buffering til we're in range
throw StreamExc(); // need to implement this
}
}
void IStreamUrlImplWinInet::seekAbsolute( off_t absoluteOffset )
{
seekRelative( absoluteOffset - ( mBufferFileOffset + mBufferOffset ) );
}
off_t IStreamUrlImplWinInet::tell() const
{
return mBufferFileOffset + mBufferOffset;
}
off_t IStreamUrlImplWinInet::size() const
{
return 0; // we don't know the size
}
void IStreamUrlImplWinInet::fillBuffer( int wantBytes ) const
{
// we've already got all the data we need
if( bufferDataRemaining() > wantBytes )
return;
// if we want more bytes than will fit in the rest of the buffer, let's make some room
if( mBufferSize - mBufferedBytes < wantBytes ) {
int bytesCulled = mBufferOffset;
memmove( mBuffer, &mBuffer[mBufferOffset], mBufferedBytes - bytesCulled );
mBufferedBytes -= bytesCulled;
mBufferOffset = 0;
mBufferFileOffset += bytesCulled;
}
// now if we've made all the room there is to make, and we still aren't big enough, reallocate
if( wantBytes > mBufferSize - mBufferedBytes ) {
// not enough space in buffer
int oldBufferSize = mBufferSize;
while( mBufferSize - mBufferedBytes < wantBytes )
mBufferSize *= 2;
uint8_t *newBuff = reinterpret_cast<uint8_t*>( realloc( mBuffer, mBufferSize ) );
if( ! newBuff ) {
throw StreamExc();
}
else {
// realloc suceeded increase buffer size
mBuffer = newBuff;
}
}
do {
::DWORD bytesAvailable, bytesToRead, bytesRead;
if( ! ::InternetQueryDataAvailable( mRequest.get(), &bytesAvailable, 0, 0 ) )
throw StreamExc();
if( bytesAvailable == 0 ) {
mIsFinished = true;
break;
}
bytesToRead = std::min<int>( bytesAvailable, wantBytes );
if( ! ::InternetReadFile( mRequest.get(), mBuffer + mBufferedBytes, bytesToRead, &bytesRead ) )
throw StreamExc();
mBufferedBytes += bytesRead;
wantBytes -= bytesRead;
if( wantBytes < 0 )
wantBytes = 0;
} while( wantBytes );
}
void IStreamUrlImplWinInet::IORead( void *dest, size_t size )
{
fillBuffer( size );
// check if theres data in the buffer - if not fillBuffer() either errored or EOF
if( bufferDataRemaining() < (off_t)size )
throw StreamExc();
memcpy( dest, mBuffer + mBufferOffset, size );
mBufferOffset += size;
}
size_t IStreamUrlImplWinInet::readDataAvailable( void *dest, size_t maxSize )
{
fillBuffer( maxSize );
if( bufferDataRemaining() < (off_t)maxSize )
maxSize = bufferDataRemaining();
memcpy( dest, mBuffer + mBufferOffset, maxSize );
mBufferOffset += maxSize;
return maxSize;
}
} // namespace cinder<|endoftext|>
|
<commit_before>/*
This is just a fast checksum to replace the old CRC32, nothing much here.
It hashes 4x4 (16) bytes at a time then merges them at the end.
*/
#ifndef CHECKSUM_H
#define CHECKSUM_H
#include "format.hpp"
class Checksum
{
private:
inline unsigned int Load32(unsigned char *p);
public:
unsigned int IntegrityCheck(Buffer Input);
};
#endif // CHECKSUM_H
<commit_msg>Delete checksum.hpp<commit_after><|endoftext|>
|
<commit_before>#include "StateMachine.h"
#include "Timing.h"
#include "Graphics.h"
#include "Quirks.h"
#include "map/Map.h"
#include "map/StateMap.h"
#include "utility/misc.h"
#include "piaf/Archive.h"
using namespace WalrusRPG;
using WalrusRPG::PIAF::Archive;
int main(int argc, char *argv[])
{
UNUSED(argc);
UNUSED(argv);
Graphics::init();
Timing::init();
Quirks::init();
// Archive arc("samples/one_file.wrf");
uint16_t dungeonTest[] = {
21, 21, 1, 1, 1, 1, 21, 22, 21, 22, 21, 22, 21, 21, 1, 22, 21,
1, 22, 22, 22, 1, 21, 2, 3, 3, 3, 3, 3, 4, 21, 1, 22, 21,
22, 22, 21, 21, 21, 1, 22, 22, 22, 23, 108, 109, 109, 109, 24, 87, 4,
21, 21, 22, 5, 6, 6, 7, 1, 1, 22, 21, 21, 23, 66, 67, 108, 109,
24, 109, 25, 21, 22, 5, 132, 43, 43, 28, 1, 1, 21, 22, 1, 23, 25,
23, 109, 109, 108, 108, 25, 1, 1, 26, 42, 110, 48, 49, 22, 21, 1, 21,
21, 23, 87, 88, 109, 24, 109, 109, 25, 1, 1, 26, 43, 131, 6, 7, 21,
1, 22, 1, 21, 44, 67, 109, 24, 24, 24, 66, 46, 1, 22, 26, 27, 43,
42, 131, 7, 21, 22, 1, 22, 21, 44, 45, 45, 45, 45, 46, 1, 22, 1,
26, 27, 27, 43, 27, 28, 22, 21, 22, 21, 1, 21, 1, 22, 22, 21, 1,
21, 22, 1, 47, 48, 111, 42, 27, 28, 21, 21, 1, 21, 21, 22, 2, 3,
3, 4, 1, 2, 3, 4, 1, 5, 132, 27, 27, 28, 1, 1, 22, 1, 22,
21, 23, 24, 66, 46, 1, 23, 24, 25, 1, 26, 42, 42, 110, 49, 21, 22,
21, 22, 22, 2, 88, 24, 25, 2, 3, 88, 24, 87, 4, 26, 43, 110, 49,
21, 21, 1, 1, 1, 2, 88, 24, 24, 87, 88, 108, 24, 24, 109, 25, 47,
48, 49, 1, 22, 22, 21, 1, 21, 23, 24, 24, 24, 24, 24, 24, 24, 24,
24, 87, 4, 21, 21, 22, 22, 22, 22, 1, 21, 23, 24, 24, 109, 24, 24,
24, 24, 24, 108, 109, 25, 21, 21, 22, 22, 22, 22, 21, 21, 44, 45, 45,
67, 24, 24, 24, 66, 45, 45, 45, 46, 1, 22, 1, 22, 22, 22, 21, 22,
22, 22, 1, 44, 67, 108, 108, 25, 22, 22, 1, 22, 21, 22, 21, 21, 1,
21, 22, 1, 22, 22, 1, 22, 44, 45, 45, 46, 1, 1, 1, 1, 21, 21,
21, 21, 21, 21, 22, 21, 21, 21, 1, 21, 1, 22, 22, 22, 1, 21, 22,
21, 1, 1, 22, 21, 1, 1, 21, 1, 1, 21, 21, 21, 1, 22, 22, 1,
21, 22, 21, 22, 1, 22, 21, 21, 21,
};
uint16_t dungeonTest2[] = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 52, 53, 54, 55, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 73, 74, 75, 76, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 157, 158, 140, 160, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 178, 179, 161, 181, 0, 12, 14, 12, 14, 162, 163, 164, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 183, 184, 185, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 166, 0, 0, 186, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 145, 167, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 133, 134, 134, 135, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 154, 155, 155, 71, 135, 39, 40, 41, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 154, 155, 155, 155, 156, 60, 61, 62, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 175, 176, 51, 155, 156, 81, 82, 83, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 175, 176, 177, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
};
Map map(20, 20, dungeonTest, dungeonTest2);
tinystl::vector<Frame> stripe21;
tinystl::vector<Frame> stripe22;
stripe21.push_back({21, 23 * 546});
stripe21.push_back({22, 31 * 546});
stripe22.push_back({22, 37 * 546});
stripe22.push_back({21, 41 * 546});
map.anim.add_animation(21, {stripe21, true, 0});
map.anim.add_animation(22, {stripe22, true, 0});
StateMachine machine(new States::StateMap(0, 0, map));
machine.run();
Quirks::deinit();
Timing::deinit();
Graphics::deinit();
return 0;
}
<commit_msg>Fixed an include problem cause by min max macros<commit_after>#include "StateMachine.h"
#include "Timing.h"
#include "Graphics.h"
#include "Quirks.h"
#include "map/Map.h"
#include "map/StateMap.h"
#include "piaf/Archive.h"
#include "utility/misc.h"
using namespace WalrusRPG;
using WalrusRPG::PIAF::Archive;
int main(int argc, char *argv[])
{
UNUSED(argc);
UNUSED(argv);
Graphics::init();
Timing::init();
Quirks::init();
// Archive arc("samples/one_file.wrf");
uint16_t dungeonTest[] = {
21, 21, 1, 1, 1, 1, 21, 22, 21, 22, 21, 22, 21, 21, 1, 22, 21,
1, 22, 22, 22, 1, 21, 2, 3, 3, 3, 3, 3, 4, 21, 1, 22, 21,
22, 22, 21, 21, 21, 1, 22, 22, 22, 23, 108, 109, 109, 109, 24, 87, 4,
21, 21, 22, 5, 6, 6, 7, 1, 1, 22, 21, 21, 23, 66, 67, 108, 109,
24, 109, 25, 21, 22, 5, 132, 43, 43, 28, 1, 1, 21, 22, 1, 23, 25,
23, 109, 109, 108, 108, 25, 1, 1, 26, 42, 110, 48, 49, 22, 21, 1, 21,
21, 23, 87, 88, 109, 24, 109, 109, 25, 1, 1, 26, 43, 131, 6, 7, 21,
1, 22, 1, 21, 44, 67, 109, 24, 24, 24, 66, 46, 1, 22, 26, 27, 43,
42, 131, 7, 21, 22, 1, 22, 21, 44, 45, 45, 45, 45, 46, 1, 22, 1,
26, 27, 27, 43, 27, 28, 22, 21, 22, 21, 1, 21, 1, 22, 22, 21, 1,
21, 22, 1, 47, 48, 111, 42, 27, 28, 21, 21, 1, 21, 21, 22, 2, 3,
3, 4, 1, 2, 3, 4, 1, 5, 132, 27, 27, 28, 1, 1, 22, 1, 22,
21, 23, 24, 66, 46, 1, 23, 24, 25, 1, 26, 42, 42, 110, 49, 21, 22,
21, 22, 22, 2, 88, 24, 25, 2, 3, 88, 24, 87, 4, 26, 43, 110, 49,
21, 21, 1, 1, 1, 2, 88, 24, 24, 87, 88, 108, 24, 24, 109, 25, 47,
48, 49, 1, 22, 22, 21, 1, 21, 23, 24, 24, 24, 24, 24, 24, 24, 24,
24, 87, 4, 21, 21, 22, 22, 22, 22, 1, 21, 23, 24, 24, 109, 24, 24,
24, 24, 24, 108, 109, 25, 21, 21, 22, 22, 22, 22, 21, 21, 44, 45, 45,
67, 24, 24, 24, 66, 45, 45, 45, 46, 1, 22, 1, 22, 22, 22, 21, 22,
22, 22, 1, 44, 67, 108, 108, 25, 22, 22, 1, 22, 21, 22, 21, 21, 1,
21, 22, 1, 22, 22, 1, 22, 44, 45, 45, 46, 1, 1, 1, 1, 21, 21,
21, 21, 21, 21, 22, 21, 21, 21, 1, 21, 1, 22, 22, 22, 1, 21, 22,
21, 1, 1, 22, 21, 1, 1, 21, 1, 1, 21, 21, 21, 1, 22, 22, 1,
21, 22, 21, 22, 1, 22, 21, 21, 21,
};
uint16_t dungeonTest2[] = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 52, 53, 54, 55, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 73, 74, 75, 76, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 157, 158, 140, 160, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 178, 179, 161, 181, 0, 12, 14, 12, 14, 162, 163, 164, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 183, 184, 185, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 166, 0, 0, 186, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 145, 167, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 133, 134, 134, 135, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 154, 155, 155, 71, 135, 39, 40, 41, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 154, 155, 155, 155, 156, 60, 61, 62, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 175, 176, 51, 155, 156, 81, 82, 83, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 175, 176, 177, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
};
Map map(20, 20, dungeonTest, dungeonTest2);
tinystl::vector<Frame> stripe21;
tinystl::vector<Frame> stripe22;
stripe21.push_back({21, 23 * 546});
stripe21.push_back({22, 31 * 546});
stripe22.push_back({22, 37 * 546});
stripe22.push_back({21, 41 * 546});
map.anim.add_animation(21, {stripe21, true, 0});
map.anim.add_animation(22, {stripe22, true, 0});
StateMachine machine(new States::StateMap(0, 0, map));
machine.run();
Quirks::deinit();
Timing::deinit();
Graphics::deinit();
return 0;
}
<|endoftext|>
|
<commit_before>/*
Copyright 2011 Joe Hermaszewski. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY JOE HERMASZEWSKI "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 JOE HERMASZEWSKI 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.
The views and conclusions contained in the software and documentation are
those of the authors and should not be interpreted as representing official
policies, either expressed or implied, of Joe Hermaszewski.
*/
#pragma once
#include <memory>
#include <string>
#include <vector>
namespace JoeLang
{
class StateAssignmentBase;
class Pass
{
public:
using StateAssignmentVector =
std::vector<std::unique_ptr<StateAssignmentBase> >;
Pass();
explicit
Pass( std::string name );
Pass( std::string name,
StateAssignmentVector state_assignments);
Pass( Pass&& p ) = default;
~Pass();
void SetState() const;
void ResetState() const;
bool Validate() const;
const std::string& GetName() const;
private:
std::string m_name;
StateAssignmentVector m_stateAssignments;
};
} // namespace JoeLang
<commit_msg>[+] added default move assignment operator<commit_after>/*
Copyright 2011 Joe Hermaszewski. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY JOE HERMASZEWSKI "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 JOE HERMASZEWSKI 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.
The views and conclusions contained in the software and documentation are
those of the authors and should not be interpreted as representing official
policies, either expressed or implied, of Joe Hermaszewski.
*/
#pragma once
#include <memory>
#include <string>
#include <vector>
namespace JoeLang
{
class StateAssignmentBase;
class Pass
{
public:
using StateAssignmentVector =
std::vector<std::unique_ptr<StateAssignmentBase> >;
Pass();
Pass( Pass&& p ) = default;
Pass& operator = ( Pass&& p ) = default;
explicit
Pass( std::string name );
Pass( std::string name,
StateAssignmentVector state_assignments);
~Pass();
void SetState() const;
void ResetState() const;
bool Validate() const;
const std::string& GetName() const;
private:
std::string m_name;
StateAssignmentVector m_stateAssignments;
};
} // namespace JoeLang
<|endoftext|>
|
<commit_before><commit_msg>coverity#705172 Missing break in switch<commit_after><|endoftext|>
|
<commit_before>#include <poddlthread.h>
#include <curl/curl.h>
#include <iostream>
#include <logger.h>
#include <config.h>
#include <utils.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/utsname.h>
#include <unistd.h>
#include <libgen.h>
using namespace newsbeuter;
namespace podbeuter {
static size_t my_write_data(void *buffer, size_t size, size_t nmemb, void *userp);
static int progress_callback(void *clientp, double dltotal, double dlnow, double ultotal, double ulnow);
poddlthread::poddlthread(download * dl_, newsbeuter::configcontainer * c) : dl(dl_), f(new std::ofstream()), bytecount(0), cfg(c) {
}
poddlthread::~poddlthread() {
}
void poddlthread::operator()() {
run();
}
void poddlthread::run() {
// are we resuming previous download?
bool resumed_download = false;
gettimeofday(&tv1, nullptr);
++bytecount;
CURL * easyhandle = curl_easy_init();
utils::set_common_curl_options(easyhandle, cfg);
curl_easy_setopt(easyhandle, CURLOPT_URL, dl->url().c_str());
curl_easy_setopt(easyhandle, CURLOPT_TIMEOUT, 0);
// set up write functions:
curl_easy_setopt(easyhandle, CURLOPT_WRITEFUNCTION, my_write_data);
curl_easy_setopt(easyhandle, CURLOPT_WRITEDATA, this);
// set up progress notification:
curl_easy_setopt(easyhandle, CURLOPT_NOPROGRESS, 0);
curl_easy_setopt(easyhandle, CURLOPT_PROGRESSFUNCTION, progress_callback);
curl_easy_setopt(easyhandle, CURLOPT_PROGRESSDATA, this);
// set up max download speed
int max_dl_speed = cfg->get_configvalue_as_int("max-download-speed");
if (max_dl_speed > 0) {
curl_easy_setopt(easyhandle, CURLOPT_MAX_RECV_SPEED_LARGE, (curl_off_t)(max_dl_speed * 1024));
}
struct stat sb;
if (stat(dl->filename().c_str(), &sb) == -1) {
LOG(LOG_INFO, "poddlthread::run: stat failed: starting normal download");
utils::mkdir_parents(dl->filename());
f->open(dl->filename().c_str(), std::fstream::out);
dl->set_offset(0);
resumed_download = false;
} else {
LOG(LOG_INFO, "poddlthread::run: stat ok: starting download from %u", sb.st_size);
curl_easy_setopt(easyhandle, CURLOPT_RESUME_FROM, sb.st_size);
dl->set_offset(sb.st_size);
f->open(dl->filename(), std::fstream::out | std::fstream::app);
resumed_download = true;
}
if (f->is_open()) {
dl->set_status(DL_DOWNLOADING);
CURLcode success = curl_easy_perform(easyhandle);
f->close();
LOG(LOG_INFO,"poddlthread::run: curl_easy_perform rc = %u (%s)", success, curl_easy_strerror(success));
if (0 == success)
dl->set_status(DL_READY);
else if (dl->status() != DL_CANCELLED) {
// attempt complete re-download
if (resumed_download) {
::unlink(dl->filename().c_str());
this->run();
} else {
dl->set_status(DL_FAILED);
::unlink(dl->filename().c_str());
}
}
} else {
dl->set_status(DL_FAILED);
}
curl_easy_cleanup(easyhandle);
}
static size_t my_write_data(void *buffer, size_t size, size_t nmemb, void *userp) {
poddlthread * thread = (poddlthread *)userp;
return thread->write_data(buffer, size, nmemb);
}
static int progress_callback(void *clientp, double dltotal, double dlnow, double /* ultotal */, double /*ulnow*/) {
poddlthread * thread = (poddlthread *)clientp;
return thread->progress(dlnow, dltotal);
}
size_t poddlthread::write_data(void * buffer, size_t size, size_t nmemb) {
if (dl->status() == DL_CANCELLED)
return 0;
f->write(static_cast<char *>(buffer), size * nmemb);
bytecount += (size * nmemb);
LOG(LOG_DEBUG, "poddlthread::write_data: bad = %u size = %u", f->bad(), size * nmemb);
return f->bad() ? 0 : size * nmemb;
}
int poddlthread::progress(double dlnow, double dltotal) {
if (dl->status() == DL_CANCELLED)
return -1;
gettimeofday(&tv2, nullptr);
double kbps = compute_kbps();
if (kbps > 9999.99) {
kbps = 0.0;
gettimeofday(&tv1, nullptr);
bytecount = 0;
}
dl->set_kbps(kbps);
dl->set_progress(dlnow, dltotal);
return 0;
}
double poddlthread::compute_kbps() {
double result = 0.0;
double t1 = tv1.tv_sec + (tv1.tv_usec/(double)1000000);
double t2 = tv2.tv_sec + (tv2.tv_usec/(double)1000000);
result = (bytecount / (t2 - t1))/1024;
return result;
}
}
<commit_msg>Remove explicit cast to double<commit_after>#include <poddlthread.h>
#include <curl/curl.h>
#include <iostream>
#include <logger.h>
#include <config.h>
#include <utils.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/utsname.h>
#include <unistd.h>
#include <libgen.h>
using namespace newsbeuter;
namespace podbeuter {
static size_t my_write_data(void *buffer, size_t size, size_t nmemb, void *userp);
static int progress_callback(void *clientp, double dltotal, double dlnow, double ultotal, double ulnow);
poddlthread::poddlthread(download * dl_, newsbeuter::configcontainer * c) : dl(dl_), f(new std::ofstream()), bytecount(0), cfg(c) {
}
poddlthread::~poddlthread() {
}
void poddlthread::operator()() {
run();
}
void poddlthread::run() {
// are we resuming previous download?
bool resumed_download = false;
gettimeofday(&tv1, nullptr);
++bytecount;
CURL * easyhandle = curl_easy_init();
utils::set_common_curl_options(easyhandle, cfg);
curl_easy_setopt(easyhandle, CURLOPT_URL, dl->url().c_str());
curl_easy_setopt(easyhandle, CURLOPT_TIMEOUT, 0);
// set up write functions:
curl_easy_setopt(easyhandle, CURLOPT_WRITEFUNCTION, my_write_data);
curl_easy_setopt(easyhandle, CURLOPT_WRITEDATA, this);
// set up progress notification:
curl_easy_setopt(easyhandle, CURLOPT_NOPROGRESS, 0);
curl_easy_setopt(easyhandle, CURLOPT_PROGRESSFUNCTION, progress_callback);
curl_easy_setopt(easyhandle, CURLOPT_PROGRESSDATA, this);
// set up max download speed
int max_dl_speed = cfg->get_configvalue_as_int("max-download-speed");
if (max_dl_speed > 0) {
curl_easy_setopt(easyhandle, CURLOPT_MAX_RECV_SPEED_LARGE, (curl_off_t)(max_dl_speed * 1024));
}
struct stat sb;
if (stat(dl->filename().c_str(), &sb) == -1) {
LOG(LOG_INFO, "poddlthread::run: stat failed: starting normal download");
utils::mkdir_parents(dl->filename());
f->open(dl->filename().c_str(), std::fstream::out);
dl->set_offset(0);
resumed_download = false;
} else {
LOG(LOG_INFO, "poddlthread::run: stat ok: starting download from %u", sb.st_size);
curl_easy_setopt(easyhandle, CURLOPT_RESUME_FROM, sb.st_size);
dl->set_offset(sb.st_size);
f->open(dl->filename(), std::fstream::out | std::fstream::app);
resumed_download = true;
}
if (f->is_open()) {
dl->set_status(DL_DOWNLOADING);
CURLcode success = curl_easy_perform(easyhandle);
f->close();
LOG(LOG_INFO,"poddlthread::run: curl_easy_perform rc = %u (%s)", success, curl_easy_strerror(success));
if (0 == success)
dl->set_status(DL_READY);
else if (dl->status() != DL_CANCELLED) {
// attempt complete re-download
if (resumed_download) {
::unlink(dl->filename().c_str());
this->run();
} else {
dl->set_status(DL_FAILED);
::unlink(dl->filename().c_str());
}
}
} else {
dl->set_status(DL_FAILED);
}
curl_easy_cleanup(easyhandle);
}
static size_t my_write_data(void *buffer, size_t size, size_t nmemb, void *userp) {
poddlthread * thread = (poddlthread *)userp;
return thread->write_data(buffer, size, nmemb);
}
static int progress_callback(void *clientp, double dltotal, double dlnow, double /* ultotal */, double /*ulnow*/) {
poddlthread * thread = (poddlthread *)clientp;
return thread->progress(dlnow, dltotal);
}
size_t poddlthread::write_data(void * buffer, size_t size, size_t nmemb) {
if (dl->status() == DL_CANCELLED)
return 0;
f->write(static_cast<char *>(buffer), size * nmemb);
bytecount += (size * nmemb);
LOG(LOG_DEBUG, "poddlthread::write_data: bad = %u size = %u", f->bad(), size * nmemb);
return f->bad() ? 0 : size * nmemb;
}
int poddlthread::progress(double dlnow, double dltotal) {
if (dl->status() == DL_CANCELLED)
return -1;
gettimeofday(&tv2, nullptr);
double kbps = compute_kbps();
if (kbps > 9999.99) {
kbps = 0.0;
gettimeofday(&tv1, nullptr);
bytecount = 0;
}
dl->set_kbps(kbps);
dl->set_progress(dlnow, dltotal);
return 0;
}
double poddlthread::compute_kbps() {
double result = 0.0;
double t1 = tv1.tv_sec + (tv1.tv_usec/1000000.0);
double t2 = tv2.tv_sec + (tv2.tv_usec/1000000.0);
result = (bytecount / (t2 - t1))/1024;
return result;
}
}
<|endoftext|>
|
<commit_before>#ifndef CONTROLLER_HPP
#define CONTROLLER_HPP
#include "Position6DOF.hpp"
#include "Formation.hpp"
#include "ros/ros.h"
//Ros messages/services
#include "api_application/MoveFormation.h" // ? (D)
#include "../matlab/Vector.h"
#include "control_application/quadcopter_movement.h" // ? (D)
#include "api_application/SetFormation.h"
#include "quadcopter_application/find_all.h"
#include "quadcopter_application/blink.h"
#include "quadcopter_application/quadcopter_status.h"
#include "control_application/BuildFormation.h"
#include "control_application/Shutdown.h"
#include "../position/IPositionReceiver.hpp"
#include <time.h>
#include <stdio.h>
#include <unistd.h>
#include <math.h>
#include <string>
#include <vector>
#include <pthread.h>
#include <list>
#include "Mutex.hpp"
#include <cmath>
#include <time.h>
#include <sstream>
#include <boost/bind.hpp>
#define THRUST_MIN 10001
#define THRUST_STAND_STILL 18001
#define THRUST_START 22000
#define THRUST_DECLINE 20000
#define THRUST_STEP 50
#define ROLL_STEP 2
#define PITCH_STEP 2
#define INVALID -1
/* Used for lists */
#define MAX_NUMBER_QUADCOPTER 10
#define POS_CHECK (current[0] != target[0]) || (current[1] != target[1]) || (current[2] != target[2])
class Controller : public IPositionReceiver {
//class Controller {
public:
Controller();
/* Initializing */
void initialize();
/* Movement and Positioning */
void convertMovement(double* const vector);
Position6DOF* getTargetPosition();
void setTargetPosition();
void updatePositions(std::vector<Vector> positions, std::vector<int> ids, std::vector<int> updates);
void sendMovement();
void calculateMovement();
void reachTrackedArea(std::vector<int> ids);
/* Formation */
bool buildFormation(control_application::BuildFormation::Request &req, control_application::BuildFormation::Response &res);
void shutdownFormation();
bool shutdown(control_application::Shutdown::Request &req, control_application::Shutdown::Response &res);
void checkInputMovement();
protected:
//Callbacks for Ros subscriber
void MoveFormationCallback(const api_application::MoveFormation::ConstPtr& msg);
void SetFormationCallback(const api_application::SetFormation::ConstPtr& msg);
void QuadStatusCallback(const quadcopter_application::quadcopter_status::ConstPtr& msg, int topicNr);
void stopReachTrackedArea();
void moveUp(std::vector<int> ids);
void moveUpNoArg();
private:
/* */
/* Position */
std::vector<Position6DOF> targetPosition;
std::vector<Position6DOF> currentPosition;
//std::vector<rpy-values> sentMovement;
std::list<std::vector<Position6DOF> > listPositions;
std::list<std::vector<Position6DOF> > listTargets;
std::list<std::vector<Position6DOF> > listSendTargets;
/* Identification of Quadcopters */
//Receive data over ROS
Formation formation;
//TODO needs to be with service find all
int totalAmount;
int amount;
float formationMovement[3];
//Mapping of int id to string id/ hardware id qc[id][uri/hardware id]
std::vector<std::string> quadcopters;
/* Set data */ /*TODO*/
int thrust;
float pitch, roll, yawrate;
/* Received data */ /*TODO*/
int id;
std::vector<float> pitch_stab;
std::vector<float> roll_stab;
std::vector<float> yaw_stab;
std::vector<unsigned int> thrust_stab;
std::vector<float> battery_status;
int startProcess;
/* int newTarget;*/
/* int newCurrent;*/
std::vector<std::string> idString;
std::vector<int> idsToGetTracked;
//Control variables
//Array of tracked quadcopters
std::vector<bool> tracked;
//Set when we are in the shutdown process
bool shutdownStarted;
bool getTracked;
/* Mutex */
Mutex curPosMutex;
Mutex tarPosMutex;
Mutex shutdownMutex;
Mutex listPositionsMutex;
Mutex getTrackedMutex;
/* Threads */
pthread_t tCalc;
pthread_t tSend;
pthread_t tGetTracked;
/**
* NodeHandle is the main access point to communications with the ROS system.
* The first NodeHandle constructed will fully initialize this node, and the last
* NodeHandle destructed will close down the node.
*/
ros::NodeHandle n;
//Subscriber
//Subscriber for the MoveFormation data
ros::Subscriber MoveFormation_sub;
//Subscriber for Formation data from API
ros::Subscriber SetFormation_sub;
//Subscriber for Quadcopter data from QuadcopterModul
//ros::Subscriber QuadStatus_sub;
std::vector<ros::Subscriber> QuadStatus_sub;
/* Publisher */
//Publisher for the Movement data of the Quadcopts (1000 is the max. buffered messages)
//ros::Publisher Movement_pub;
std::vector<ros::Publisher> Movement_pub;
/* Services */
//Service for building formation
ros::ServiceServer BuildForm_srv;
//Service for shutingdown formation
ros::ServiceServer Shutdown_srv;
//Clients
ros::ServiceClient FindAll_client;
ros::ServiceClient Blink_client;
};
#endif // CONTROLLER_HPP
<commit_msg>Fixed another error, Problem with Mutex remains<commit_after>#ifndef CONTROLLER_HPP
#define CONTROLLER_HPP
#include "Position6DOF.hpp"
#include "Formation.hpp"
#include "ros/ros.h"
//Ros messages/services
#include "api_application/MoveFormation.h" // ? (D)
#include "../matlab/Vector.h"
#include "control_application/quadcopter_movement.h" // ? (D)
#include "api_application/SetFormation.h"
#include "quadcopter_application/find_all.h"
#include "quadcopter_application/blink.h"
#include "quadcopter_application/quadcopter_status.h"
#include "control_application/BuildFormation.h"
#include "control_application/Shutdown.h"
#include "../position/IPositionReceiver.hpp"
#include <time.h>
#include <stdio.h>
#include <unistd.h>
#include <math.h>
#include <string>
#include <vector>
#include <pthread.h>
#include <list>
#include "Mutex.hpp"
#include <cmath>
#include <time.h>
#include <sstream>
#include <boost/bind.hpp>
#define THRUST_MIN 10001
#define THRUST_STAND_STILL 18001
#define THRUST_START 22000
#define THRUST_DECLINE 20000
#define THRUST_STEP 50
#define ROLL_STEP 2
#define PITCH_STEP 2
#define INVALID -1
/* Used for lists */
#define MAX_NUMBER_QUADCOPTER 10
#define POS_CHECK (current[0] != target[0]) || (current[1] != target[1]) || (current[2] != target[2])
class Controller : public IPositionReceiver {
//class Controller {
public:
Controller();
/* Initializing */
void initialize();
/* Movement and Positioning */
void convertMovement(double* const vector);
Position6DOF* getTargetPosition();
void setTargetPosition();
void updatePositions(std::vector<Vector> positions, std::vector<int> ids, std::vector<int> updates);
void sendMovement();
void calculateMovement();
void reachTrackedArea(std::vector<int> ids);
/* Formation */
bool buildFormation(control_application::BuildFormation::Request &req, control_application::BuildFormation::Response &res);
void shutdownFormation();
bool shutdown(control_application::Shutdown::Request &req, control_application::Shutdown::Response &res);
void checkInputMovement();
void moveUp(std::vector<int> ids);
void moveUpNoArg();
protected:
//Callbacks for Ros subscriber
void MoveFormationCallback(const api_application::MoveFormation::ConstPtr& msg);
void SetFormationCallback(const api_application::SetFormation::ConstPtr& msg);
void QuadStatusCallback(const quadcopter_application::quadcopter_status::ConstPtr& msg, int topicNr);
void stopReachTrackedArea();
private:
/* */
/* Position */
std::vector<Position6DOF> targetPosition;
std::vector<Position6DOF> currentPosition;
//std::vector<rpy-values> sentMovement;
std::list<std::vector<Position6DOF> > listPositions;
std::list<std::vector<Position6DOF> > listTargets;
std::list<std::vector<Position6DOF> > listSendTargets;
/* Identification of Quadcopters */
//Receive data over ROS
Formation formation;
//TODO needs to be with service find all
int totalAmount;
int amount;
float formationMovement[3];
//Mapping of int id to string id/ hardware id qc[id][uri/hardware id]
std::vector<std::string> quadcopters;
/* Set data */ /*TODO*/
int thrust;
float pitch, roll, yawrate;
/* Received data */ /*TODO*/
int id;
std::vector<float> pitch_stab;
std::vector<float> roll_stab;
std::vector<float> yaw_stab;
std::vector<unsigned int> thrust_stab;
std::vector<float> battery_status;
int startProcess;
/* int newTarget;*/
/* int newCurrent;*/
std::vector<std::string> idString;
std::vector<int> idsToGetTracked;
//Control variables
//Array of tracked quadcopters
std::vector<bool> tracked;
//Set when we are in the shutdown process
bool shutdownStarted;
bool getTracked;
/* Mutex */
Mutex curPosMutex;
Mutex tarPosMutex;
Mutex shutdownMutex;
Mutex listPositionsMutex;
Mutex getTrackedMutex;
/* Threads */
pthread_t tCalc;
pthread_t tSend;
pthread_t tGetTracked;
/**
* NodeHandle is the main access point to communications with the ROS system.
* The first NodeHandle constructed will fully initialize this node, and the last
* NodeHandle destructed will close down the node.
*/
ros::NodeHandle n;
//Subscriber
//Subscriber for the MoveFormation data
ros::Subscriber MoveFormation_sub;
//Subscriber for Formation data from API
ros::Subscriber SetFormation_sub;
//Subscriber for Quadcopter data from QuadcopterModul
//ros::Subscriber QuadStatus_sub;
std::vector<ros::Subscriber> QuadStatus_sub;
/* Publisher */
//Publisher for the Movement data of the Quadcopts (1000 is the max. buffered messages)
//ros::Publisher Movement_pub;
std::vector<ros::Publisher> Movement_pub;
/* Services */
//Service for building formation
ros::ServiceServer BuildForm_srv;
//Service for shutingdown formation
ros::ServiceServer Shutdown_srv;
//Clients
ros::ServiceClient FindAll_client;
ros::ServiceClient Blink_client;
};
#endif // CONTROLLER_HPP
<|endoftext|>
|
<commit_before>//
// Copyright(c) 2015 Gabi Melman.
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
//
//
// spdlog usage example
//
//
#define SPDLOG_TRACE_ON
#define SPDLOG_DEBUG_ON
#include "spdlog/sinks/daily_file_sink.h"
#include "spdlog/sinks/rotating_file_sink.h"
#include "spdlog/sinks/simple_file_sink.h"
#include "spdlog/sinks/stdout_color_sinks.h"
#include <iostream>
#include <memory>
void async_example();
void user_defined_example();
void err_handler_example();
namespace spd = spdlog;
int main(int, char *[])
{
try
{
auto console = spdlog::stdout_color_st("console");
console->info("Welcome to spdlog!");
console->info("Welcome to spdlog!");
console->error("Some error message with arg: {}", 1);
err_handler_example();
// Formatting examples
console->warn("Easy padding in numbers like {:08d}", 12);
console->critical("Support for int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}", 42);
console->info("Support for floats {:03.2f}", 1.23456);
console->info("Positional args are {1} {0}..", "too", "supported");
console->info("{:<30}", "left aligned");
spd::get("console")->info("loggers can be retrieved from a global registry using the spdlog::get(logger_name) function");
// Create basic file logger (not rotated)
auto my_logger = spd::basic_logger_mt("basic_logger", "logs/basic-log.txt");
my_logger->info("Some log message");
// Create a file rotating logger with 5mb size max and 3 rotated files
auto rotating_logger = spd::rotating_logger_mt("some_logger_name", "logs/rotating.txt", 1048576 * 5, 3);
for (int i = 0; i < 10; ++i)
{
rotating_logger->info("{} * {} equals {:>10}", i, i, i * i);
}
// Create a daily logger - a new file is created every day on 2:30am
auto daily_logger = spd::daily_logger_mt("daily_logger", "logs/daily.txt", 2, 30);
// trigger flush if the log severity is error or higher
daily_logger->flush_on(spd::level::err);
daily_logger->info(123.44);
// Customize msg format for all messages
spd::set_pattern("[%^+++%$] [%H:%M:%S %z] [thread %t] %v");
console->info("This an info message with custom format");
console->error("This an error message with custom format");
// Change format back to to default
spd::set_pattern("%+");
// Runtime log levels
spd::set_level(spd::level::info); // Set global log level to info
console->debug("This message should not be displayed!");
console->set_level(spd::level::debug); // Set specific logger's log level
console->debug("This message should be displayed..");
// Compile time log levels
// define SPDLOG_DEBUG_ON or SPDLOG_TRACE_ON
SPDLOG_TRACE(console, "Enabled only #ifdef SPDLOG_TRACE_ON..{} ,{}", 1, 3.23);
SPDLOG_DEBUG(console, "Enabled only #ifdef SPDLOG_DEBUG_ON.. {} ,{}", 1, 3.23);
// Asynchronous logging example
async_example();
// Log user-defined types example
user_defined_example();
// Change default log error handler
err_handler_example();
// Apply a function on all registered loggers
spd::apply_all([&](std::shared_ptr<spdlog::logger> l) { l->info("End of example."); });
// Release and close all loggers
spdlog::drop_all();
}
// Exceptions will only be thrown upon failed logger or sink construction (not during logging)
catch (const spd::spdlog_ex &ex)
{
std::cout << "Log init failed: " << ex.what() << std::endl;
return 1;
}
}
// must be included to use async logger
#include "spdlog/async.h"
void async_example()
{
auto async_file = spd::basic_logger_mt<spdlog::create_async>("async_file_logger", "logs/async_log.txt");
// thread pool settings can be modified *before* creating the async logger:
// spdlog::init_thread_pool(32768, 4); // queue with max 32k items 4 backing threads.
for (int i = 0; i < 100; ++i)
{
async_file->info("Async message #{}", i + 1);
}
}
// syslog example (linux/osx/freebsd)
#ifndef _WIN32
#include "spdlog/sinks/syslog_sink.h"
void syslog_example()
{
std::string ident = "spdlog-example";
auto syslog_logger = spd::syslog_logger("syslog", ident, LOG_PID);
syslog_logger->warn("This is warning that will end up in syslog.");
}
#endif
// Android example
#if defined(__ANDROID__)
#incude "spdlog/sinks/android_sink.h"
void android_example()
{
std::string tag = "spdlog-android";
auto android_logger = spd::android_logger("android", tag);
android_logger->critical("Use \"adb shell logcat\" to view this message.");
}
#endif
// user defined types logging by implementing operator<<
struct my_type
{
int i;
template<typename OStream>
friend OStream &operator<<(OStream &os, const my_type &c)
{
return os << "[my_type i=" << c.i << "]";
}
};
#include "spdlog/fmt/ostr.h" // must be included
void user_defined_example()
{
spd::get("console")->info("user defined type: {}", my_type{14});
}
//
// custom error handler
//
void err_handler_example()
{
// can be set globaly or per logger(logger->set_error_handler(..))
spdlog::set_error_handler([](const std::string &msg) { spd::get("console")->error("*******my err handler: {}", msg); });
spd::get("console")->info("some invalid message to trigger an error {}{}{}{}", 3);
// spd::get("console")->info("some invalid message to trigger an error {}{}{}{}", 3);
}
<commit_msg>update example<commit_after>//
// Copyright(c) 2015 Gabi Melman.
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
//
//
// spdlog usage example
//
//
#define SPDLOG_TRACE_ON
#define SPDLOG_DEBUG_ON
#include "spdlog/sinks/daily_file_sink.h"
#include "spdlog/sinks/rotating_file_sink.h"
#include "spdlog/sinks/simple_file_sink.h"
#include "spdlog/sinks/stdout_color_sinks.h"
#include <iostream>
#include <memory>
void async_example();
void user_defined_example();
void err_handler_example();
namespace spd = spdlog;
int main(int, char *[])
{
try
{
auto console = spdlog::stdout_color_st("console");
console->info("Welcome to spdlog!");
console->info("Welcome to spdlog!");
console->error("Some error message with arg: {}", 1);
err_handler_example();
// Formatting examples
console->warn("Easy padding in numbers like {:08d}", 12);
console->critical("Support for int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}", 42);
console->info("Support for floats {:03.2f}", 1.23456);
console->info("Positional args are {1} {0}..", "too", "supported");
console->info("{:<30}", "left aligned");
spd::get("console")->info("loggers can be retrieved from a global registry using the spdlog::get(logger_name) function");
// Create basic file logger (not rotated)
auto my_logger = spd::basic_logger_mt("basic_logger", "logs/basic-log.txt");
my_logger->info("Some log message");
// Create a file rotating logger with 5mb size max and 3 rotated files
auto rotating_logger = spd::rotating_logger_mt("some_logger_name", "logs/rotating.txt", 1048576 * 5, 3);
for (int i = 0; i < 10; ++i)
{
rotating_logger->info("{} * {} equals {:>10}", i, i, i * i);
}
// Create a daily logger - a new file is created every day on 2:30am
auto daily_logger = spd::daily_logger_mt("daily_logger", "logs/daily.txt", 2, 30);
// trigger flush if the log severity is error or higher
daily_logger->flush_on(spd::level::err);
daily_logger->info(123.44);
// Customize msg format for all messages
spd::set_pattern("[%^+++%$] [%H:%M:%S %z] [thread %t] %v");
console->info("This an info message with custom format");
console->error("This an error message with custom format");
// Change format back to to default
spd::set_pattern("%+");
// Runtime log levels
spd::set_level(spd::level::info); // Set global log level to info
console->debug("This message should not be displayed!");
console->set_level(spd::level::debug); // Set specific logger's log level
console->debug("This message should be displayed..");
// Compile time log levels
// define SPDLOG_DEBUG_ON or SPDLOG_TRACE_ON
SPDLOG_TRACE(console, "Enabled only #ifdef SPDLOG_TRACE_ON..{} ,{}", 1, 3.23);
SPDLOG_DEBUG(console, "Enabled only #ifdef SPDLOG_DEBUG_ON.. {} ,{}", 1, 3.23);
// Asynchronous logging example
async_example();
// Log user-defined types example
user_defined_example();
// Change default log error handler
err_handler_example();
// Apply a function on all registered loggers
spd::apply_all([&](std::shared_ptr<spdlog::logger> l) { l->info("End of example."); });
// Release and close all loggers
spdlog::drop_all();
}
// Exceptions will only be thrown upon failed logger or sink construction (not during logging)
catch (const spd::spdlog_ex &ex)
{
std::cout << "Log init failed: " << ex.what() << std::endl;
return 1;
}
}
// must be included to use async logger
#include "spdlog/async.h"
void async_example()
{
auto async_file = spd::basic_logger_mt<spdlog::create_async>("async_file_logger", "logs/async_log.txt");
// thread pool settings can be modified *before* creating the async logger:
// spdlog::init_thread_pool(32768, 4); // queue with max 32k items 4 backing threads.
for (int i = 0; i < 100; ++i)
{
async_file->info("Async message #{}", i + 1);
}
// you can wait for all the messages to processed:
// spdlog::thread_pool()->wait_empty();
}
// syslog example (linux/osx/freebsd)
#ifndef _WIN32
#include "spdlog/sinks/syslog_sink.h"
void syslog_example()
{
std::string ident = "spdlog-example";
auto syslog_logger = spd::syslog_logger("syslog", ident, LOG_PID);
syslog_logger->warn("This is warning that will end up in syslog.");
}
#endif
// Android example
#if defined(__ANDROID__)
#incude "spdlog/sinks/android_sink.h"
void android_example()
{
std::string tag = "spdlog-android";
auto android_logger = spd::android_logger("android", tag);
android_logger->critical("Use \"adb shell logcat\" to view this message.");
}
#endif
// user defined types logging by implementing operator<<
struct my_type
{
int i;
template<typename OStream>
friend OStream &operator<<(OStream &os, const my_type &c)
{
return os << "[my_type i=" << c.i << "]";
}
};
#include "spdlog/fmt/ostr.h" // must be included
void user_defined_example()
{
spd::get("console")->info("user defined type: {}", my_type{14});
}
//
// custom error handler
//
void err_handler_example()
{
// can be set globaly or per logger(logger->set_error_handler(..))
spdlog::set_error_handler([](const std::string &msg) { spd::get("console")->error("*******my err handler: {}", msg); });
spd::get("console")->info("some invalid message to trigger an error {}{}{}{}", 3);
// spd::get("console")->info("some invalid message to trigger an error {}{}{}{}", 3);
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <map>
#include "api/license++.h"
#include "pc-identifiers.h"
#include "ini/SimpleIni.h"
using namespace std;
int main(int argc, char *argv[])
{
map<EVENT_TYPE, string> stringByEventType;
stringByEventType[LICENSE_OK ] = "OK ";
stringByEventType[LICENSE_FILE_NOT_FOUND ] = "license file not found ";
stringByEventType[LICENSE_SERVER_NOT_FOUND ] = "license server can't be contacted ";
stringByEventType[ENVIRONMENT_VARIABLE_NOT_DEFINED] = "environment variable not defined ";
stringByEventType[FILE_FORMAT_NOT_RECOGNIZED ] = "license file has invalid format (not .ini file) ";
stringByEventType[LICENSE_MALFORMED ] = "some mandatory field are missing, or data can't be fully read. ";
stringByEventType[PRODUCT_NOT_LICENSED ] = "this product was not licensed ";
stringByEventType[PRODUCT_EXPIRED ] = "license expired ";
stringByEventType[LICENSE_CORRUPTED ] = "license signature didn't match with current license ";
stringByEventType[IDENTIFIERS_MISMATCH ] = "Calculated identifier and the one provided in license didn't match";
stringByEventType[LICENSE_FILE_FOUND ] = "license file not found ";
stringByEventType[LICENSE_VERIFIED ] = "license verified ";
const string licLocation("example.lic");
LicenseInfo licenseInfo;
LicenseLocation licenseLocation;
licenseLocation.openFileNearModule = false;
licenseLocation.licenseFileLocation = licLocation.c_str();
licenseLocation.environmentVariableName = "";
EVENT_TYPE result = acquire_license("example", licenseLocation, &licenseInfo);
PcSignature signature;
FUNCTION_RETURN generate_ok = generate_user_pc_signature(signature, ETHERNET);
if (result == LICENSE_OK && licenseInfo.linked_to_pc) {
CSimpleIniA ini;
SI_Error rc = ini.LoadFile(licLocation.c_str());
string IDinLicense = ini.GetValue("example", "client_signature", "");
if (IDinLicense == "") {
cout << "No client signature in license file, generate license with -s <id>";
result = IDENTIFIERS_MISMATCH;
} else if (IDinLicense != signature) {
result = IDENTIFIERS_MISMATCH;
}
}
if (result != LICENSE_OK) {
cout << "license ERROR :" << endl;
cout << " " << stringByEventType[result].c_str() << endl;
cout << "the pc signature is :" << endl;
cout << " " << signature << endl;
}
else
cout << "license OK" << endl;
}
<commit_msg>Example use DEFAULT<commit_after>#include <iostream>
#include <map>
#include "api/license++.h"
#include "pc-identifiers.h"
#include "ini/SimpleIni.h"
using namespace std;
int main(int argc, char *argv[])
{
map<EVENT_TYPE, string> stringByEventType;
stringByEventType[LICENSE_OK ] = "OK ";
stringByEventType[LICENSE_FILE_NOT_FOUND ] = "license file not found ";
stringByEventType[LICENSE_SERVER_NOT_FOUND ] = "license server can't be contacted ";
stringByEventType[ENVIRONMENT_VARIABLE_NOT_DEFINED] = "environment variable not defined ";
stringByEventType[FILE_FORMAT_NOT_RECOGNIZED ] = "license file has invalid format (not .ini file) ";
stringByEventType[LICENSE_MALFORMED ] = "some mandatory field are missing, or data can't be fully read. ";
stringByEventType[PRODUCT_NOT_LICENSED ] = "this product was not licensed ";
stringByEventType[PRODUCT_EXPIRED ] = "license expired ";
stringByEventType[LICENSE_CORRUPTED ] = "license signature didn't match with current license ";
stringByEventType[IDENTIFIERS_MISMATCH ] = "Calculated identifier and the one provided in license didn't match";
stringByEventType[LICENSE_FILE_FOUND ] = "license file not found ";
stringByEventType[LICENSE_VERIFIED ] = "license verified ";
const string licLocation("example.lic");
LicenseInfo licenseInfo;
LicenseLocation licenseLocation;
licenseLocation.openFileNearModule = false;
licenseLocation.licenseFileLocation = licLocation.c_str();
licenseLocation.environmentVariableName = "";
EVENT_TYPE result = acquire_license("example", licenseLocation, &licenseInfo);
PcSignature signature;
FUNCTION_RETURN generate_ok = generate_user_pc_signature(signature, DEFAULT);
if (result == LICENSE_OK && licenseInfo.linked_to_pc) {
CSimpleIniA ini;
SI_Error rc = ini.LoadFile(licLocation.c_str());
string IDinLicense = ini.GetValue("example", "client_signature", "");
if (IDinLicense == "") {
cout << "No client signature in license file, generate license with -s <id>";
result = IDENTIFIERS_MISMATCH;
} else if (IDinLicense != signature) {
result = IDENTIFIERS_MISMATCH;
}
}
if (result != LICENSE_OK) {
cout << "license ERROR :" << endl;
cout << " " << stringByEventType[result].c_str() << endl;
cout << "the pc signature is :" << endl;
cout << " " << signature << endl;
}
else
cout << "license OK" << endl;
}
<|endoftext|>
|
<commit_before><commit_msg>A little notice for my code<commit_after><|endoftext|>
|
<commit_before>/* This file is part of Strigi Desktop Search
*
* Copyright (C) 2006 Jos van den Oever <jos@vandenoever.info>
*
* 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 "indexscheduler.h"
#include "indexmanager.h"
#include "indexreader.h"
#include "indexwriter.h"
#include "strigiconfig.h"
#include "event.h"
#include "eventlistenerqueue.h"
#include "analyzerconfiguration.h"
#include "filelister.h"
#include "streamanalyzer.h"
#include <cerrno>
#include <sys/resource.h>
#include "strigilogging.h"
using namespace std;
IndexScheduler* sched;
IndexScheduler::IndexScheduler() :StrigiThread("IndexScheduler") {
sched = this;
m_listenerEventQueue = NULL;
}
IndexScheduler::~IndexScheduler() {
}
std::string
IndexScheduler::getStateString() {
State state = getState();
if (state == Idling) return "idling";
if (state == Working) return "indexing";
return "stopping";
}
int
IndexScheduler::getQueueSize() {
return toindex.size();
}
void
shortsleep(long nanoseconds) {
// set sleep time
struct timespec sleeptime;
sleeptime.tv_sec = 0;
sleeptime.tv_nsec = nanoseconds;
nanosleep(&sleeptime, 0);
}
void *
IndexScheduler::run(void*) {
while (getState() != Stopping) {
shortsleep(100000000);
if (getState() == Working) {
index();
if (getState() == Working) {
setState(Idling);
}
}
else if (getState() == Idling) {
if (m_listenerEventQueue == NULL)
return 0;
vector <Event*> events = m_listenerEventQueue->getEvents();
if (events.size() > 0) {
setState(Working);
processListenerEvents(events);
setState(Idling);
}
}
}
STRIGI_LOG_DEBUG ("strigi.IndexScheduler.run", string("exit state: ") + getStringState());
return 0;
}
void
IndexScheduler::index() {
Strigi::IndexReader* reader = indexmanager->indexReader();
Strigi::IndexWriter* writer = indexmanager->indexWriter();
Strigi::StreamAnalyzer* streamindexer
= new Strigi::StreamAnalyzer(*m_indexerconfiguration);
streamindexer->setIndexWriter(*writer);
if (dbfiles.size() == 0 && toindex.size() == 0) {
// retrieve the list of real files currently in the database
dbfiles = reader->files(0);
char buff [20];
snprintf(buff, 20* sizeof (char), "%i", dbfiles.size());
STRIGI_LOG_DEBUG ("strigi.IndexScheduler", string(buff) + " real files in the database")
// first loop through all files
Strigi::FileLister lister(m_indexerconfiguration);
STRIGI_LOG_DEBUG ("strigi.IndexScheduler", "going to index")
set<string>::const_iterator i;
for (i = dirstoindex.begin(); i != dirstoindex.end(); ++i) {
lister.startListing(i->c_str());
string path;
time_t mtime;
int r = lister.nextFile(path, mtime);
while (r >= 0) {
fprintf(stderr, "r %i\n", r);
if (r > 0) {
map<string, time_t>::iterator i
= sched->dbfiles.find(path);
// if the file has not yet been indexed or if the mtime has
// changed, put it in the list to index
if (i == sched->dbfiles.end() || i->second != mtime) {
sched->toindex[path] = mtime;
} else {
sched->dbfiles.erase(i);
}
}
r = lister.nextFile(path, mtime);
}
}
snprintf(buff, 20* sizeof (char), "%i", dbfiles.size());
STRIGI_LOG_DEBUG ("strigi.IndexScheduler", string(buff) + " files to remove")
snprintf(buff, 20* sizeof (char), "%i", toindex.size());
STRIGI_LOG_DEBUG ("strigi.IndexScheduler", string(buff) + " files to add or update")
}
vector<string> todelete;
map<string,time_t>::iterator it = dbfiles.begin();
while (getState() == Working && it != dbfiles.end()) {
todelete.push_back(it->first);
// writer->deleteEntry(it->first);
dbfiles.erase(it++);
}
writer->deleteEntries(todelete);
it = toindex.begin();
while (getState() == Working && it != toindex.end()) {
streamindexer->indexFile(it->first);
if (writer->itemsInCache() > 10000) {
writer->commit();
}
toindex.erase(it++);
}
if (getState() == Working) {
writer->commit();
writer->optimize();
}
delete streamindexer;
}
void
IndexScheduler::processListenerEvents(vector<Event*>& events) {
Strigi::IndexReader* reader = indexmanager->indexReader();
Strigi::IndexWriter* writer = indexmanager->indexWriter();
Strigi::AnalyzerConfiguration ic;
Strigi::StreamAnalyzer* streamindexer = new Strigi::StreamAnalyzer(ic);
streamindexer->setIndexWriter(*writer);
vector<string> toDelete;
STRIGI_LOG_DEBUG ("strigi.IndexScheduler", "processing listener's events")
for(vector<Event*>::iterator iter = events.begin(); iter != events.end(); iter++)
{
Event* event = *iter;
STRIGI_LOG_DEBUG ("strigi.IndexScheduler", "event infos: " + event->toString())
switch (event->getType())
{
case Event::CREATED:
toindex.insert (make_pair (event->getPath(), event->getTime()));
break;
case Event::UPDATED:
{
time_t indexTime = reader->mTime(reader->documentId(event->getPath()));
if (indexTime < event->getTime())
{
toindex.insert (make_pair (event->getPath(), event->getTime()));
toDelete.push_back (event->getPath());
}
else
STRIGI_LOG_DEBUG ("strigi.IndexScheduler", "ignoring last event")
break;
}
case Event::DELETED:
toDelete.push_back (event->getPath());
break;
}
delete event;
}
writer->deleteEntries(toDelete);
map<string, time_t>::iterator it = toindex.begin();
while (it != toindex.end())
{
streamindexer->indexFile(it->first);
if (writer->itemsInCache() > 10000) {
writer->commit();
}
toindex.erase(it++);
}
writer->commit();
writer->optimize();
delete streamindexer;
}
void
IndexScheduler::setIndexedDirectories(const std::set<std::string> &d) {
dirstoindex.clear();
std::set<std::string>::const_iterator i;
for (i = d.begin(); i!=d.end(); ++i) {
bool ok = true;
std::set<std::string>::iterator j;
for (j = dirstoindex.begin(); ok && j != dirstoindex.end(); ++j) {
if (j->length() >= i->length()
&& j->substr(0, i->length()) == *i) {
dirstoindex.erase(j);
j = dirstoindex.begin();
} else if (i->length() >= j->length()
&& i->substr(0, j->length()) == *j) {
// for now, allow subdirs, because they might not be included otherwise
// ok = false;
}
}
if (ok) {
string dir = *i;
if (dir[dir.length()-1] == '/') {
dir = dir.substr(0, dir.length()-1);
}
dirstoindex.insert(dir);
}
}
if (dirstoindex.size() == 0) {
indexmanager->indexWriter()->deleteAllEntries();
}
}
<commit_msg>remove debugging output<commit_after>/* This file is part of Strigi Desktop Search
*
* Copyright (C) 2006 Jos van den Oever <jos@vandenoever.info>
*
* 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 "indexscheduler.h"
#include "indexmanager.h"
#include "indexreader.h"
#include "indexwriter.h"
#include "strigiconfig.h"
#include "event.h"
#include "eventlistenerqueue.h"
#include "analyzerconfiguration.h"
#include "filelister.h"
#include "streamanalyzer.h"
#include <cerrno>
#include <sys/resource.h>
#include "strigilogging.h"
using namespace std;
IndexScheduler* sched;
IndexScheduler::IndexScheduler() :StrigiThread("IndexScheduler") {
sched = this;
m_listenerEventQueue = NULL;
}
IndexScheduler::~IndexScheduler() {
}
std::string
IndexScheduler::getStateString() {
State state = getState();
if (state == Idling) return "idling";
if (state == Working) return "indexing";
return "stopping";
}
int
IndexScheduler::getQueueSize() {
return toindex.size();
}
void
shortsleep(long nanoseconds) {
// set sleep time
struct timespec sleeptime;
sleeptime.tv_sec = 0;
sleeptime.tv_nsec = nanoseconds;
nanosleep(&sleeptime, 0);
}
void *
IndexScheduler::run(void*) {
while (getState() != Stopping) {
shortsleep(100000000);
if (getState() == Working) {
index();
if (getState() == Working) {
setState(Idling);
}
}
else if (getState() == Idling) {
if (m_listenerEventQueue == NULL)
return 0;
vector <Event*> events = m_listenerEventQueue->getEvents();
if (events.size() > 0) {
setState(Working);
processListenerEvents(events);
setState(Idling);
}
}
}
STRIGI_LOG_DEBUG ("strigi.IndexScheduler.run", string("exit state: ") + getStringState());
return 0;
}
void
IndexScheduler::index() {
Strigi::IndexReader* reader = indexmanager->indexReader();
Strigi::IndexWriter* writer = indexmanager->indexWriter();
Strigi::StreamAnalyzer* streamindexer
= new Strigi::StreamAnalyzer(*m_indexerconfiguration);
streamindexer->setIndexWriter(*writer);
if (dbfiles.size() == 0 && toindex.size() == 0) {
// retrieve the list of real files currently in the database
dbfiles = reader->files(0);
char buff [20];
snprintf(buff, 20* sizeof (char), "%i", dbfiles.size());
STRIGI_LOG_DEBUG ("strigi.IndexScheduler", string(buff) + " real files in the database")
// first loop through all files
Strigi::FileLister lister(m_indexerconfiguration);
STRIGI_LOG_DEBUG ("strigi.IndexScheduler", "going to index")
set<string>::const_iterator i;
for (i = dirstoindex.begin(); i != dirstoindex.end(); ++i) {
lister.startListing(i->c_str());
string path;
time_t mtime;
int r = lister.nextFile(path, mtime);
while (r >= 0) {
if (r > 0) {
map<string, time_t>::iterator i
= sched->dbfiles.find(path);
// if the file has not yet been indexed or if the mtime has
// changed, put it in the list to index
if (i == sched->dbfiles.end() || i->second != mtime) {
sched->toindex[path] = mtime;
} else {
sched->dbfiles.erase(i);
}
}
r = lister.nextFile(path, mtime);
}
}
snprintf(buff, 20* sizeof (char), "%i", dbfiles.size());
STRIGI_LOG_DEBUG ("strigi.IndexScheduler", string(buff) + " files to remove")
snprintf(buff, 20* sizeof (char), "%i", toindex.size());
STRIGI_LOG_DEBUG ("strigi.IndexScheduler", string(buff) + " files to add or update")
}
vector<string> todelete;
map<string,time_t>::iterator it = dbfiles.begin();
while (getState() == Working && it != dbfiles.end()) {
todelete.push_back(it->first);
// writer->deleteEntry(it->first);
dbfiles.erase(it++);
}
writer->deleteEntries(todelete);
it = toindex.begin();
while (getState() == Working && it != toindex.end()) {
streamindexer->indexFile(it->first);
if (writer->itemsInCache() > 10000) {
writer->commit();
}
toindex.erase(it++);
}
if (getState() == Working) {
writer->commit();
writer->optimize();
}
delete streamindexer;
}
void
IndexScheduler::processListenerEvents(vector<Event*>& events) {
Strigi::IndexReader* reader = indexmanager->indexReader();
Strigi::IndexWriter* writer = indexmanager->indexWriter();
Strigi::AnalyzerConfiguration ic;
Strigi::StreamAnalyzer* streamindexer = new Strigi::StreamAnalyzer(ic);
streamindexer->setIndexWriter(*writer);
vector<string> toDelete;
STRIGI_LOG_DEBUG ("strigi.IndexScheduler", "processing listener's events")
for(vector<Event*>::iterator iter = events.begin(); iter != events.end(); iter++)
{
Event* event = *iter;
STRIGI_LOG_DEBUG ("strigi.IndexScheduler", "event infos: " + event->toString())
switch (event->getType())
{
case Event::CREATED:
toindex.insert (make_pair (event->getPath(), event->getTime()));
break;
case Event::UPDATED:
{
time_t indexTime = reader->mTime(reader->documentId(event->getPath()));
if (indexTime < event->getTime())
{
toindex.insert (make_pair (event->getPath(), event->getTime()));
toDelete.push_back (event->getPath());
}
else
STRIGI_LOG_DEBUG ("strigi.IndexScheduler", "ignoring last event")
break;
}
case Event::DELETED:
toDelete.push_back (event->getPath());
break;
}
delete event;
}
writer->deleteEntries(toDelete);
map<string, time_t>::iterator it = toindex.begin();
while (it != toindex.end())
{
streamindexer->indexFile(it->first);
if (writer->itemsInCache() > 10000) {
writer->commit();
}
toindex.erase(it++);
}
writer->commit();
writer->optimize();
delete streamindexer;
}
void
IndexScheduler::setIndexedDirectories(const std::set<std::string> &d) {
dirstoindex.clear();
std::set<std::string>::const_iterator i;
for (i = d.begin(); i!=d.end(); ++i) {
bool ok = true;
std::set<std::string>::iterator j;
for (j = dirstoindex.begin(); ok && j != dirstoindex.end(); ++j) {
if (j->length() >= i->length()
&& j->substr(0, i->length()) == *i) {
dirstoindex.erase(j);
j = dirstoindex.begin();
} else if (i->length() >= j->length()
&& i->substr(0, j->length()) == *j) {
// for now, allow subdirs, because they might not be included otherwise
// ok = false;
}
}
if (ok) {
string dir = *i;
if (dir[dir.length()-1] == '/') {
dir = dir.substr(0, dir.length()-1);
}
dirstoindex.insert(dir);
}
}
if (dirstoindex.size() == 0) {
indexmanager->indexWriter()->deleteAllEntries();
}
}
<|endoftext|>
|
<commit_before>#include "./default_scene_creator.h"
#include <Eigen/Core>
#include <Eigen/Geometry>
#include <string>
#include <vector>
#include <random>
#include "./importer.h"
#include "./nodes.h"
#include "./mesh_node.h"
#include "./meshes_node.h"
#include "./label_node.h"
#include "./volume_node.h"
#include "./camera_node.h"
#include "./utils/persister.h"
BOOST_CLASS_EXPORT_GUID(LabelNode, "LabelNode")
BOOST_CLASS_EXPORT_GUID(MeshNode, "MeshNode")
BOOST_CLASS_EXPORT_GUID(MeshesNode, "MeshesNode")
BOOST_CLASS_EXPORT_GUID(VolumeNode, "VolumeNode")
BOOST_CLASS_EXPORT_GUID(CameraNode, "CameraNode")
DefaultSceneCreator::DefaultSceneCreator(std::shared_ptr<Nodes> nodes,
std::shared_ptr<Labels> labels)
: nodes(nodes), labels(labels)
{
}
void addPedestrianNodes(std::vector<std::shared_ptr<Node>> &sceneNodes)
{
Eigen::Affine3f trans(
Eigen::AngleAxisf(-0.5 * M_PI, Eigen::Vector3f::UnitX()));
sceneNodes.push_back(std::make_shared<VolumeNode>(
"assets/datasets/fussgaenger_graz_iterative.mhd",
"assets/transferfunctions/scapula4.gra", trans.matrix(), true));
const std::string filename = "assets/models/RekoCT2_01-8.dae";
Importer importer;
unsigned int meshIndex = 0;
auto mesh = importer.import(filename, meshIndex);
auto transformation = importer.getTransformationFor(filename, meshIndex);
auto node = new MeshNode(filename, meshIndex, mesh, transformation);
sceneNodes.push_back(std::unique_ptr<MeshNode>(node));
}
void addLIDCIDRINodes(std::vector<std::shared_ptr<Node>> &sceneNodes)
{
Eigen::Affine3f trans(
Eigen::Scaling(2.0f) *
Eigen::Translation3f(Eigen::Vector3f(0.15, 0.145f, 0.15)) *
Eigen::AngleAxisf(M_PI, Eigen::Vector3f::UnitY()) *
Eigen::AngleAxisf(0.5 * M_PI, Eigen::Vector3f::UnitX()));
sceneNodes.push_back(std::make_shared<VolumeNode>(
"assets/datasets/LIDC-IDRI-0469_lung2.mha",
"assets/transferfunctions/LIDC-IDRI-0469.gra", trans.matrix(), false));
sceneNodes.push_back(std::make_shared<VolumeNode>(
"assets/datasets/LIDC-IDRI-0469_lesion1_mask_extracted_blurred.mha",
"assets/transferfunctions/LIDC_IDRI_lesions_mask.gra", trans.matrix(),
false));
sceneNodes.push_back(std::make_shared<VolumeNode>(
"assets/datasets/LIDC-IDRI-0469_lesion2_mask_extracted_blurred.mha",
"assets/transferfunctions/LIDC_IDRI_lesions_mask.gra", trans.matrix(),
false));
sceneNodes.push_back(std::make_shared<VolumeNode>(
"assets/datasets/LIDC-IDRI-0469_lesion3_mask_extracted_blurred.mha",
"assets/transferfunctions/LIDC_IDRI_lesions_mask.gra", trans.matrix(),
false));
sceneNodes.push_back(std::make_shared<VolumeNode>(
"assets/datasets/LIDC-IDRI-0469_lesion4_mask_extracted_blurred.mha",
"assets/transferfunctions/LIDC_IDRI_lesions_mask.gra", trans.matrix(),
false));
}
void addSponza(std::vector<std::shared_ptr<Node>> &sceneNodes)
{
const std::string filename = "assets/models/crytek-sponza/sponza.obj";
Eigen::Affine3f scaling(Eigen::Scaling(0.01f));
Eigen::Matrix4f scalingMatrix = scaling.matrix();
sceneNodes.push_back(std::make_shared<MeshesNode>(filename, scalingMatrix));
}
void addJetEngine(std::vector<std::shared_ptr<Node>> &sceneNodes)
{
const std::string filename = "assets/models/jet_engine.dae";
Eigen::Affine3f trans(
Eigen::Translation3f(Eigen::Vector3f(0, 0, 1)) * Eigen::Scaling(0.01f) *
Eigen::AngleAxisf(-0.5 * M_PI, Eigen::Vector3f::UnitX()));
Eigen::Matrix4f matrix = trans.matrix();
sceneNodes.push_back(std::make_shared<MeshesNode>(filename, matrix));
}
void addArtificial(std::vector<std::shared_ptr<Node>> &sceneNodes)
{
const std::string filename = "assets/models/artificial.dae";
Eigen::Affine3f scaling(Eigen::Scaling(1.0f));
Eigen::Matrix4f scalingMatrix = scaling.matrix();
sceneNodes.push_back(std::make_shared<MeshesNode>(filename, scalingMatrix));
}
void add100Labels(std::vector<std::shared_ptr<Node>> &sceneNodes)
{
Eigen::Affine3f trans(
Eigen::AngleAxisf(-0.5 * M_PI, Eigen::Vector3f::UnitX()));
sceneNodes.push_back(std::make_shared<VolumeNode>(
"assets/datasets/MANIX.mhd", "assets/transferfunctions/scapula2.gra",
trans.matrix(), true));
std::default_random_engine gen;
std::uniform_real_distribution<float> dist(-0.2f, 0.2f);
for (int i = 0; i < 100; ++i)
{
auto label = Label(i, "L " + std::to_string(i),
Eigen::Vector3f(dist(gen), dist(gen), dist(gen)));
label.size = Eigen::Vector2f(64, 32);
sceneNodes.push_back(std::make_shared<LabelNode>(label));
}
}
void DefaultSceneCreator::create()
{
std::vector<std::shared_ptr<Node>> sceneNodes;
// addMeshNodesTo(sceneNodes);
// addLabelNodesTo(sceneNodes);
Eigen::Affine3f trans(
Eigen::AngleAxisf(-0.5 * M_PI, Eigen::Vector3f::UnitX()));
sceneNodes.push_back(std::make_shared<VolumeNode>(
"assets/datasets/dice.mha",
"assets/transferfunctions/dice4.gra", trans.matrix(), true));
// addMultiVolumeNodesTo(sceneNodes);
Persister::save(sceneNodes, "config/scene.xml");
// nodes->addSceneNodesFrom("config/scene.xml");
for (auto &node : sceneNodes)
nodes->addNode(node);
}
void DefaultSceneCreator::addMeshNodesTo(
std::vector<std::shared_ptr<Node>> &sceneNodes)
{
const std::string filename = "assets/human-edited.dae";
Importer importer;
for (unsigned int meshIndex = 0; meshIndex < 2; ++meshIndex)
{
auto mesh = importer.import(filename, meshIndex);
auto transformation = importer.getTransformationFor(filename, meshIndex);
auto node = new MeshNode(filename, meshIndex, mesh, transformation);
sceneNodes.push_back(std::unique_ptr<MeshNode>(node));
}
}
void DefaultSceneCreator::addLabelNodesTo(
std::vector<std::shared_ptr<Node>> &sceneNodes)
{
auto label = Label(1, "Shoulder", Eigen::Vector3f(0.174f, 0.55f, 0.034f));
sceneNodes.push_back(std::make_shared<LabelNode>(label));
auto label2 = Label(2, "Ellbow", Eigen::Vector3f(0.34f, 0.322f, -0.007f));
sceneNodes.push_back(std::make_shared<LabelNode>(label2));
auto label3 = Label(3, "Wound", Eigen::Vector3f(0.262f, 0.422f, 0.058f),
Eigen::Vector2i(128, 128));
sceneNodes.push_back(std::make_shared<LabelNode>(label3));
auto label4 = Label(4, "Wound 2", Eigen::Vector3f(0.034f, 0.373f, 0.141f));
sceneNodes.push_back(std::make_shared<LabelNode>(label4));
}
void DefaultSceneCreator::addMultiVolumeNodesTo(
std::vector<std::shared_ptr<Node>> &sceneNodes)
{
sceneNodes.push_back(std::make_shared<VolumeNode>(
"assets/datasets/GRCH_Abdomen.mhd",
"assets/transferfunctions/scapula4.gra", Eigen::Matrix4f::Identity()));
sceneNodes.push_back(std::make_shared<VolumeNode>(
"assets/datasets/GRCH_Schaedel_fein_H31.mhd",
"assets/transferfunctions/scapula4.gra", Eigen::Matrix4f::Identity()));
}
<commit_msg>Update addMultiVolumeNodesTo in DefaultSceneCreator.<commit_after>#include "./default_scene_creator.h"
#include <Eigen/Core>
#include <Eigen/Geometry>
#include <string>
#include <vector>
#include <random>
#include "./importer.h"
#include "./nodes.h"
#include "./mesh_node.h"
#include "./meshes_node.h"
#include "./label_node.h"
#include "./volume_node.h"
#include "./camera_node.h"
#include "./utils/persister.h"
BOOST_CLASS_EXPORT_GUID(LabelNode, "LabelNode")
BOOST_CLASS_EXPORT_GUID(MeshNode, "MeshNode")
BOOST_CLASS_EXPORT_GUID(MeshesNode, "MeshesNode")
BOOST_CLASS_EXPORT_GUID(VolumeNode, "VolumeNode")
BOOST_CLASS_EXPORT_GUID(CameraNode, "CameraNode")
DefaultSceneCreator::DefaultSceneCreator(std::shared_ptr<Nodes> nodes,
std::shared_ptr<Labels> labels)
: nodes(nodes), labels(labels)
{
}
void addPedestrianNodes(std::vector<std::shared_ptr<Node>> &sceneNodes)
{
Eigen::Affine3f trans(
Eigen::AngleAxisf(-0.5 * M_PI, Eigen::Vector3f::UnitX()));
sceneNodes.push_back(std::make_shared<VolumeNode>(
"assets/datasets/fussgaenger_graz_iterative.mhd",
"assets/transferfunctions/scapula4.gra", trans.matrix(), true));
const std::string filename = "assets/models/RekoCT2_01-8.dae";
Importer importer;
unsigned int meshIndex = 0;
auto mesh = importer.import(filename, meshIndex);
auto transformation = importer.getTransformationFor(filename, meshIndex);
auto node = new MeshNode(filename, meshIndex, mesh, transformation);
sceneNodes.push_back(std::unique_ptr<MeshNode>(node));
}
void addLIDCIDRINodes(std::vector<std::shared_ptr<Node>> &sceneNodes)
{
Eigen::Affine3f trans(
Eigen::Scaling(2.0f) *
Eigen::Translation3f(Eigen::Vector3f(0.15, 0.145f, 0.15)) *
Eigen::AngleAxisf(M_PI, Eigen::Vector3f::UnitY()) *
Eigen::AngleAxisf(0.5 * M_PI, Eigen::Vector3f::UnitX()));
sceneNodes.push_back(std::make_shared<VolumeNode>(
"assets/datasets/LIDC-IDRI-0469_lung2.mha",
"assets/transferfunctions/LIDC-IDRI-0469.gra", trans.matrix(), false));
sceneNodes.push_back(std::make_shared<VolumeNode>(
"assets/datasets/LIDC-IDRI-0469_lesion1_mask_extracted_blurred.mha",
"assets/transferfunctions/LIDC_IDRI_lesions_mask.gra", trans.matrix(),
false));
sceneNodes.push_back(std::make_shared<VolumeNode>(
"assets/datasets/LIDC-IDRI-0469_lesion2_mask_extracted_blurred.mha",
"assets/transferfunctions/LIDC_IDRI_lesions_mask.gra", trans.matrix(),
false));
sceneNodes.push_back(std::make_shared<VolumeNode>(
"assets/datasets/LIDC-IDRI-0469_lesion3_mask_extracted_blurred.mha",
"assets/transferfunctions/LIDC_IDRI_lesions_mask.gra", trans.matrix(),
false));
sceneNodes.push_back(std::make_shared<VolumeNode>(
"assets/datasets/LIDC-IDRI-0469_lesion4_mask_extracted_blurred.mha",
"assets/transferfunctions/LIDC_IDRI_lesions_mask.gra", trans.matrix(),
false));
}
void addSponza(std::vector<std::shared_ptr<Node>> &sceneNodes)
{
const std::string filename = "assets/models/crytek-sponza/sponza.obj";
Eigen::Affine3f scaling(Eigen::Scaling(0.01f));
Eigen::Matrix4f scalingMatrix = scaling.matrix();
sceneNodes.push_back(std::make_shared<MeshesNode>(filename, scalingMatrix));
}
void addJetEngine(std::vector<std::shared_ptr<Node>> &sceneNodes)
{
const std::string filename = "assets/models/jet_engine.dae";
Eigen::Affine3f trans(
Eigen::Translation3f(Eigen::Vector3f(0, 0, 1)) * Eigen::Scaling(0.01f) *
Eigen::AngleAxisf(-0.5 * M_PI, Eigen::Vector3f::UnitX()));
Eigen::Matrix4f matrix = trans.matrix();
sceneNodes.push_back(std::make_shared<MeshesNode>(filename, matrix));
}
void addArtificial(std::vector<std::shared_ptr<Node>> &sceneNodes)
{
const std::string filename = "assets/models/artificial.dae";
Eigen::Affine3f scaling(Eigen::Scaling(1.0f));
Eigen::Matrix4f scalingMatrix = scaling.matrix();
sceneNodes.push_back(std::make_shared<MeshesNode>(filename, scalingMatrix));
}
void add100Labels(std::vector<std::shared_ptr<Node>> &sceneNodes)
{
Eigen::Affine3f trans(
Eigen::AngleAxisf(-0.5 * M_PI, Eigen::Vector3f::UnitX()));
sceneNodes.push_back(std::make_shared<VolumeNode>(
"assets/datasets/MANIX.mhd", "assets/transferfunctions/scapula2.gra",
trans.matrix(), true));
std::default_random_engine gen;
std::uniform_real_distribution<float> dist(-0.2f, 0.2f);
for (int i = 0; i < 100; ++i)
{
auto label = Label(i, "L " + std::to_string(i),
Eigen::Vector3f(dist(gen), dist(gen), dist(gen)));
label.size = Eigen::Vector2f(64, 32);
sceneNodes.push_back(std::make_shared<LabelNode>(label));
}
}
void DefaultSceneCreator::create()
{
std::vector<std::shared_ptr<Node>> sceneNodes;
// addMeshNodesTo(sceneNodes);
// addLabelNodesTo(sceneNodes);
Eigen::Affine3f trans(
Eigen::AngleAxisf(-0.5 * M_PI, Eigen::Vector3f::UnitX()));
sceneNodes.push_back(std::make_shared<VolumeNode>(
"assets/datasets/dice.mha",
"assets/transferfunctions/dice4.gra", trans.matrix(), true));
// addMultiVolumeNodesTo(sceneNodes);
Persister::save(sceneNodes, "config/scene.xml");
// nodes->addSceneNodesFrom("config/scene.xml");
for (auto &node : sceneNodes)
nodes->addNode(node);
}
void DefaultSceneCreator::addMeshNodesTo(
std::vector<std::shared_ptr<Node>> &sceneNodes)
{
const std::string filename = "assets/human-edited.dae";
Importer importer;
for (unsigned int meshIndex = 0; meshIndex < 2; ++meshIndex)
{
auto mesh = importer.import(filename, meshIndex);
auto transformation = importer.getTransformationFor(filename, meshIndex);
auto node = new MeshNode(filename, meshIndex, mesh, transformation);
sceneNodes.push_back(std::unique_ptr<MeshNode>(node));
}
}
void DefaultSceneCreator::addLabelNodesTo(
std::vector<std::shared_ptr<Node>> &sceneNodes)
{
auto label = Label(1, "Shoulder", Eigen::Vector3f(0.174f, 0.55f, 0.034f));
sceneNodes.push_back(std::make_shared<LabelNode>(label));
auto label2 = Label(2, "Ellbow", Eigen::Vector3f(0.34f, 0.322f, -0.007f));
sceneNodes.push_back(std::make_shared<LabelNode>(label2));
auto label3 = Label(3, "Wound", Eigen::Vector3f(0.262f, 0.422f, 0.058f),
Eigen::Vector2i(128, 128));
sceneNodes.push_back(std::make_shared<LabelNode>(label3));
auto label4 = Label(4, "Wound 2", Eigen::Vector3f(0.034f, 0.373f, 0.141f));
sceneNodes.push_back(std::make_shared<LabelNode>(label4));
}
void DefaultSceneCreator::addMultiVolumeNodesTo(
std::vector<std::shared_ptr<Node>> &sceneNodes)
{
Eigen::Affine3f trans(
Eigen::Translation3f(Eigen::Vector3f(0, 0.6f, 0)) *
Eigen::AngleAxisf(-0.5 * M_PI, Eigen::Vector3f::UnitX()));
sceneNodes.push_back(std::make_shared<VolumeNode>(
"assets/datasets/GRCH_Abdomen.mhd",
"assets/transferfunctions/scapula2.gra", trans.matrix()));
sceneNodes.push_back(std::make_shared<VolumeNode>(
"assets/datasets/GRCH_Schaedel_fein_H31.mhd",
"assets/transferfunctions/scapula2.gra", trans.matrix()));
}
<|endoftext|>
|
<commit_before>/// \file Debugger.cpp
#include "chi/Debugger.hpp"
#include <chi/Context.hpp>
#include <chi/LLVMVersion.hpp>
#include <chi/NameMangler.hpp>
#include <chi/NodeInstance.hpp>
#include <chi/Result.hpp>
#include <boost/filesystem.hpp>
#include <boost/uuid/uuid_io.hpp>
#if LLVM_VERSION_LESS_EQUAL(3, 9)
#include <llvm/Bitcode/ReaderWriter.h>
#else
#include <llvm/Bitcode/BitcodeWriter.h>
#endif
#include <llvm/Support/FileSystem.h>
#include <llvm/Support/raw_ostream.h>
#include <lldb/API/SBListener.h>
#include <lldb/API/SBThread.h>
#include <stdlib.h> // for setenv
namespace fs = boost::filesystem;
namespace chi {
Debugger::Debugger(const char* pathToChig, GraphModule& mod) : mModule{&mod} {
// point it to lldb-server
#if __linux__
auto lldbServerPath = fs::path(pathToChig).parent_path() / "lldb-server";
setenv("LLDB_DEBUGSERVER_PATH", lldbServerPath.c_str(), 1);
#endif
lldb::SBDebugger::Initialize();
mDebugger = lldb::SBDebugger::Create();
// set the logger to stderr for testing
mDebugger.SetLoggingCallback(
[](const char* msg, void* dbg) {
std::cerr << msg;
std::cerr.flush();
},
this);
const char* val[] = {"api", nullptr};
mDebugger.EnableLog("lldb", val);
// create target
mTarget = mDebugger.CreateTarget(pathToChig);
}
Debugger::~Debugger() { lldb::SBDebugger::Terminate(); }
Result Debugger::terminate() {
Result res;
if (isAttached()) {
auto err = mProcess.Kill();
if (err.Fail()) {
res.addEntry("EUKN", "Failed to terminate process",
{{"Error Code", err.GetError()}, {"Error String", err.GetCString()}});
return res;
}
}
return res;
}
Result Debugger::processContinue() {
Result res;
if (isAttached()) {
auto err = mProcess.Continue();
if (err.Fail()) {
res.addEntry("EUKN", "Failed to continue process",
{{"Error Code", err.GetError()}, {"Error String", err.GetCString()}});
return res;
}
}
return res;
}
Result Debugger::pause() {
Result res;
if (isAttached()) {
auto err = mProcess.Stop();
if (err.Fail()) {
res.addEntry("EUKN", "Failed to pause process",
{{"Error Code", err.GetError()}, {"Error String", err.GetCString()}});
return res;
}
}
return res;
}
Result Debugger::setBreakpoint(NodeInstance& node, lldb::SBBreakpoint* bp) {
Result res;
int linenum = lineNumberFromNode(node);
// create the breakpoint
auto breakpoint = mTarget.BreakpointCreateByLocation(
node.module().sourceFilePath().string().c_str(), linenum);
// make sure that it's good
if (!breakpoint.IsValid()) {
res.addEntry("EUKN", "Could not set breakpoint on node",
{{"nodeid", node.stringId()},
{"File Name", node.module().sourceFilePath().string()},
{"Line Number", linenum}});
return res;
}
mBreakpoints[&node] = breakpoint;
if (bp != nullptr) { *bp = breakpoint; }
breakpoint.SetEnabled(true);
return res;
}
bool Debugger::removeBreakpoint(NodeInstance& node) {
auto iter = mBreakpoints.find(&node);
if (iter == mBreakpoints.end()) { return false; }
return mTarget.BreakpointDelete(iter->second.GetID());
}
Result Debugger::start(const char** argv, const char** envp,
const boost::filesystem::path& workingDirectory) {
Expects(boost::filesystem::is_directory(workingDirectory));
Result res;
if (!mTarget.IsValid()) {
res.addEntry("EUKN", "Cannot start a debugger process with an invalid target", {});
return res;
}
// generate IR
std::unique_ptr<llvm::Module> mod;
{
res = module().context().compileModule(module(), &mod);
if (!res) { return res; }
}
// write it to a file
fs::path tmpIRPath;
{
tmpIRPath = boost::filesystem::temp_directory_path() / fs::unique_path();
std::error_code ec; // TODO: use ec
llvm::raw_fd_ostream file{tmpIRPath.string(), ec, llvm::sys::fs::F_RW};
llvm::WriteBitcodeToFile(mod.get(), file);
}
// create args
std::vector<const char*> args;
{
args.push_back("interpret");
args.push_back("-i");
args.push_back(tmpIRPath.string().c_str());
args.push_back("-O");
args.push_back("0");
if (argv != nullptr) {
for (; *argv != nullptr; ++argv) { args.push_back(*argv); }
}
args.push_back(nullptr);
}
// start the process
{
lldb::SBError err;
lldb::SBListener invalidListener;
mProcess =
mTarget.Launch(invalidListener, args.data(), envp, nullptr, nullptr, nullptr,
workingDirectory.string().c_str(), lldb::eLaunchFlagDebug, false, err);
if (err.Fail()) {
res.addEntry("EUKN", "Failed to launch process", {{"Error Message", err.GetCString()}});
}
}
return res;
}
std::vector<const NodeInstance*> Debugger::listBreakpoints() const {
std::vector<const NodeInstance*> ret;
ret.reserve(mBreakpoints.size());
for (const auto& bpts : mBreakpoints) { ret.push_back(bpts.first); }
return ret;
}
lldb::SBValue Debugger::inspectNodeOutput(const NodeInstance& inst, size_t id,
lldb::SBFrame frame) {
Expects(id < inst.outputDataConnections.size());
// if frame isn't valid, use the default
if (!frame.IsValid()) {
auto thread = lldbProcess().GetSelectedThread();
if (!thread.IsValid()) { return {}; }
frame = thread.GetSelectedFrame();
}
if (!frame.IsValid()) { return {}; }
// make sure it's in scope
auto func = &nodeFromFrame(frame)->function();
if (func != &inst.function()) { return {}; }
auto variableName = inst.stringId() + "__" + std::to_string(id);
return frame.FindVariable(variableName.c_str());
}
NodeInstance* Debugger::nodeFromFrame(lldb::SBFrame frame) {
using namespace std::string_literals;
// if frame isn't valid, use the default
if (!frame.IsValid()) {
auto thread = lldbProcess().GetSelectedThread();
if (!thread.IsValid()) { return {}; }
frame = thread.GetSelectedFrame();
}
if (!frame.IsValid()) { return {}; }
auto mangledFunctionName = frame.GetFunctionName();
// demangle that
std::string moduleName, functionName;
std::tie(moduleName, functionName) = unmangleFunctionName(mangledFunctionName);
GraphFunction* func = nullptr;
if (mangledFunctionName == "main"s) { func = module().functionFromName("main"); }
if (func == nullptr) {
auto mod = static_cast<GraphModule*>(module().context().moduleByFullName(moduleName));
if (!mod) { return nullptr; }
func = mod->functionFromName(functionName);
}
unsigned lineNo = frame.GetLineEntry().GetLine();
// create assoc TODO: cache these
auto assoc = func->module().createLineNumberAssoc();
auto nodeIter = assoc.left.find(lineNo);
if (nodeIter == assoc.left.end()) { return nullptr; }
return nodeIter->second;
}
unsigned lineNumberFromNode(NodeInstance& inst) {
// TODO: cache these, they're kinda expensive to make
auto lineAssoc = inst.module().createLineNumberAssoc();
auto lineNumberIter = lineAssoc.right.find(&inst);
if (lineNumberIter == lineAssoc.right.end()) { return -1; }
return lineNumberIter->second;
}
} // namespace chi
<commit_msg>Add another missing include for LLVM 3.5<commit_after>/// \file Debugger.cpp
#include "chi/Debugger.hpp"
#include <chi/Context.hpp>
#include <chi/LLVMVersion.hpp>
#include <chi/NameMangler.hpp>
#include <chi/NodeInstance.hpp>
#include <chi/Result.hpp>
#include <boost/filesystem.hpp>
#include <boost/uuid/uuid_io.hpp>
#if LLVM_VERSION_LESS_EQUAL(3, 9)
#include <llvm/Bitcode/ReaderWriter.h>
#else
#include <llvm/Bitcode/BitcodeWriter.h>
#endif
#include <llvm/Support/FileSystem.h>
#include <llvm/Support/raw_ostream.h>
#include <llvm/IR/Module.h>
#include <lldb/API/SBListener.h>
#include <lldb/API/SBThread.h>
#include <stdlib.h> // for setenv
namespace fs = boost::filesystem;
namespace chi {
Debugger::Debugger(const char* pathToChig, GraphModule& mod) : mModule{&mod} {
// point it to lldb-server
#if __linux__
auto lldbServerPath = fs::path(pathToChig).parent_path() / "lldb-server";
setenv("LLDB_DEBUGSERVER_PATH", lldbServerPath.c_str(), 1);
#endif
lldb::SBDebugger::Initialize();
mDebugger = lldb::SBDebugger::Create();
// set the logger to stderr for testing
mDebugger.SetLoggingCallback(
[](const char* msg, void* dbg) {
std::cerr << msg;
std::cerr.flush();
},
this);
const char* val[] = {"api", nullptr};
mDebugger.EnableLog("lldb", val);
// create target
mTarget = mDebugger.CreateTarget(pathToChig);
}
Debugger::~Debugger() { lldb::SBDebugger::Terminate(); }
Result Debugger::terminate() {
Result res;
if (isAttached()) {
auto err = mProcess.Kill();
if (err.Fail()) {
res.addEntry("EUKN", "Failed to terminate process",
{{"Error Code", err.GetError()}, {"Error String", err.GetCString()}});
return res;
}
}
return res;
}
Result Debugger::processContinue() {
Result res;
if (isAttached()) {
auto err = mProcess.Continue();
if (err.Fail()) {
res.addEntry("EUKN", "Failed to continue process",
{{"Error Code", err.GetError()}, {"Error String", err.GetCString()}});
return res;
}
}
return res;
}
Result Debugger::pause() {
Result res;
if (isAttached()) {
auto err = mProcess.Stop();
if (err.Fail()) {
res.addEntry("EUKN", "Failed to pause process",
{{"Error Code", err.GetError()}, {"Error String", err.GetCString()}});
return res;
}
}
return res;
}
Result Debugger::setBreakpoint(NodeInstance& node, lldb::SBBreakpoint* bp) {
Result res;
int linenum = lineNumberFromNode(node);
// create the breakpoint
auto breakpoint = mTarget.BreakpointCreateByLocation(
node.module().sourceFilePath().string().c_str(), linenum);
// make sure that it's good
if (!breakpoint.IsValid()) {
res.addEntry("EUKN", "Could not set breakpoint on node",
{{"nodeid", node.stringId()},
{"File Name", node.module().sourceFilePath().string()},
{"Line Number", linenum}});
return res;
}
mBreakpoints[&node] = breakpoint;
if (bp != nullptr) { *bp = breakpoint; }
breakpoint.SetEnabled(true);
return res;
}
bool Debugger::removeBreakpoint(NodeInstance& node) {
auto iter = mBreakpoints.find(&node);
if (iter == mBreakpoints.end()) { return false; }
return mTarget.BreakpointDelete(iter->second.GetID());
}
Result Debugger::start(const char** argv, const char** envp,
const boost::filesystem::path& workingDirectory) {
Expects(boost::filesystem::is_directory(workingDirectory));
Result res;
if (!mTarget.IsValid()) {
res.addEntry("EUKN", "Cannot start a debugger process with an invalid target", {});
return res;
}
// generate IR
std::unique_ptr<llvm::Module> mod;
{
res = module().context().compileModule(module(), &mod);
if (!res) { return res; }
}
// write it to a file
fs::path tmpIRPath;
{
tmpIRPath = boost::filesystem::temp_directory_path() / fs::unique_path();
std::error_code ec; // TODO: use ec
llvm::raw_fd_ostream file{tmpIRPath.string(), ec, llvm::sys::fs::F_RW};
llvm::WriteBitcodeToFile(mod.get(), file);
}
// create args
std::vector<const char*> args;
{
args.push_back("interpret");
args.push_back("-i");
args.push_back(tmpIRPath.string().c_str());
args.push_back("-O");
args.push_back("0");
if (argv != nullptr) {
for (; *argv != nullptr; ++argv) { args.push_back(*argv); }
}
args.push_back(nullptr);
}
// start the process
{
lldb::SBError err;
lldb::SBListener invalidListener;
mProcess =
mTarget.Launch(invalidListener, args.data(), envp, nullptr, nullptr, nullptr,
workingDirectory.string().c_str(), lldb::eLaunchFlagDebug, false, err);
if (err.Fail()) {
res.addEntry("EUKN", "Failed to launch process", {{"Error Message", err.GetCString()}});
}
}
return res;
}
std::vector<const NodeInstance*> Debugger::listBreakpoints() const {
std::vector<const NodeInstance*> ret;
ret.reserve(mBreakpoints.size());
for (const auto& bpts : mBreakpoints) { ret.push_back(bpts.first); }
return ret;
}
lldb::SBValue Debugger::inspectNodeOutput(const NodeInstance& inst, size_t id,
lldb::SBFrame frame) {
Expects(id < inst.outputDataConnections.size());
// if frame isn't valid, use the default
if (!frame.IsValid()) {
auto thread = lldbProcess().GetSelectedThread();
if (!thread.IsValid()) { return {}; }
frame = thread.GetSelectedFrame();
}
if (!frame.IsValid()) { return {}; }
// make sure it's in scope
auto func = &nodeFromFrame(frame)->function();
if (func != &inst.function()) { return {}; }
auto variableName = inst.stringId() + "__" + std::to_string(id);
return frame.FindVariable(variableName.c_str());
}
NodeInstance* Debugger::nodeFromFrame(lldb::SBFrame frame) {
using namespace std::string_literals;
// if frame isn't valid, use the default
if (!frame.IsValid()) {
auto thread = lldbProcess().GetSelectedThread();
if (!thread.IsValid()) { return {}; }
frame = thread.GetSelectedFrame();
}
if (!frame.IsValid()) { return {}; }
auto mangledFunctionName = frame.GetFunctionName();
// demangle that
std::string moduleName, functionName;
std::tie(moduleName, functionName) = unmangleFunctionName(mangledFunctionName);
GraphFunction* func = nullptr;
if (mangledFunctionName == "main"s) { func = module().functionFromName("main"); }
if (func == nullptr) {
auto mod = static_cast<GraphModule*>(module().context().moduleByFullName(moduleName));
if (!mod) { return nullptr; }
func = mod->functionFromName(functionName);
}
unsigned lineNo = frame.GetLineEntry().GetLine();
// create assoc TODO: cache these
auto assoc = func->module().createLineNumberAssoc();
auto nodeIter = assoc.left.find(lineNo);
if (nodeIter == assoc.left.end()) { return nullptr; }
return nodeIter->second;
}
unsigned lineNumberFromNode(NodeInstance& inst) {
// TODO: cache these, they're kinda expensive to make
auto lineAssoc = inst.module().createLineNumberAssoc();
auto lineNumberIter = lineAssoc.right.find(&inst);
if (lineNumberIter == lineAssoc.right.end()) { return -1; }
return lineNumberIter->second;
}
} // namespace chi
<|endoftext|>
|
<commit_before>#include <libdariadb/interfaces/icallbacks.h>
#include <thread>
using namespace dariadb;
IReadCallback::IReadCallback() {
is_end_called = false;
is_cancel = false;
}
IReadCallback::~IReadCallback() {}
void IReadCallback::is_end() {
is_end_called = true;
}
void IReadCallback::wait() {
// TODO make more smarter.
while (!is_cancel && !is_end_called) {
std::this_thread::sleep_for(std::chrono::milliseconds(300));
}
// mtx.unlock();
}
void IReadCallback::cancel() {
is_cancel = true;
}
bool IReadCallback::is_canceled() const {
return is_cancel;
}<commit_msg>rm TODO.<commit_after>#include <libdariadb/interfaces/icallbacks.h>
#include <thread>
using namespace dariadb;
IReadCallback::IReadCallback() {
is_end_called = false;
is_cancel = false;
}
IReadCallback::~IReadCallback() {}
void IReadCallback::is_end() {
is_end_called = true;
}
void IReadCallback::wait() {
while (!is_cancel && !is_end_called) {
std::this_thread::sleep_for(std::chrono::milliseconds(300));
}
}
void IReadCallback::cancel() {
is_cancel = true;
}
bool IReadCallback::is_canceled() const {
return is_cancel;
}<|endoftext|>
|
<commit_before><commit_msg>tableindex: Evaluate predicate once<commit_after><|endoftext|>
|
<commit_before>#include <iostream>
#include <ref/Class.hpp>
#include <ref/DescriptorsImpl.ipp>
#include <ref/utils/JsonSerializer.hpp>
using namespace ref;
struct Animal;
// Structural features (attributes)
struct Name : String {};
struct Surname : String {};
struct Age : UInt32 {};
struct Alive : Bool {};
struct Emails : Feature< std::vector< std::string > >{};
struct Pets : Feature< std::vector< Animal > >{};
// Classes
struct Animal :
Class< Animal, Features< Alive, Age > >
{
};
struct Person :
Class< Person,
Features< Name, Surname, Emails, Pets >,
Animal >
{
};
int main(int argc, char **argv)
{
Person me;
Animal dog;
// Direct access
me.set< Name >("Andres");
me.set< Surname >("Senac");
me.set< Age >(29);
const std::vector< std::string > emails = {"andres@senac.es", "asenac@senac.es"};
me.set< Emails >(emails);
me.get< Pets >().push_back(dog);
std::cout << me.get< Name >() << " "
<< me.get< Surname >() << " "
<< me.get< Age >() << std::endl;
// Descriptors
const ClassDescriptor * classDesc = me.getClassDescriptor();
const FeatureDescriptorVector features =
classDesc->getAllFeatureDescriptors();
for (size_t i = 0; i < features.size(); i++)
{
const FeatureDescriptor * featureDesc = features[i];
Holder h = featureDesc->getValue(&me);
const TypeDescriptor * typeDesc = h.descriptor();
if (typeDesc->getKind() == TypeDescriptor::kPrimitive)
{
const PrimitiveTypeDescriptor * priTypeDesc =
static_cast< const PrimitiveTypeDescriptor * >(typeDesc);
std::cout << featureDesc->getName() << " = "
<< priTypeDesc->getString(h) << std::endl;
}
else
{
std::cout << featureDesc->getName() << " = non-printable type!" << std::endl;
}
}
std::cout << std::endl;
JsonSerializer js(std::cout);
js.serialize(&me);
std::cout << std::endl;
return 0;
}
<commit_msg>use as method instead of static_cast<commit_after>#include <iostream>
#include <ref/Class.hpp>
#include <ref/DescriptorsImpl.ipp>
#include <ref/utils/JsonSerializer.hpp>
using namespace ref;
struct Animal;
// Structural features (attributes)
struct Name : String {};
struct Surname : String {};
struct Age : UInt32 {};
struct Alive : Bool {};
struct Emails : Feature< std::vector< std::string > >{};
struct Pets : Feature< std::vector< Animal > >{};
// Classes
struct Animal :
Class< Animal, Features< Alive, Age > >
{
};
struct Person :
Class< Person,
Features< Name, Surname, Emails, Pets >,
Animal >
{
};
int main(int argc, char **argv)
{
Person me;
Animal dog;
// Direct access
me.set< Name >("Andres");
me.set< Surname >("Senac");
me.set< Age >(29);
const std::vector< std::string > emails = {"andres@senac.es", "asenac@senac.es"};
me.set< Emails >(emails);
me.get< Pets >().push_back(dog);
std::cout << me.get< Name >() << " "
<< me.get< Surname >() << " "
<< me.get< Age >() << std::endl;
// Descriptors
const ClassDescriptor * classDesc = me.getClassDescriptor();
const FeatureDescriptorVector features =
classDesc->getAllFeatureDescriptors();
for (size_t i = 0; i < features.size(); i++)
{
const FeatureDescriptor * featureDesc = features[i];
Holder h = featureDesc->getValue(&me);
const TypeDescriptor * typeDesc = h.descriptor();
if (typeDesc->getKind() == TypeDescriptor::kPrimitive)
{
const PrimitiveTypeDescriptor *priTypeDesc =
typeDesc->as<PrimitiveTypeDescriptor>();
std::cout << featureDesc->getName() << " = "
<< priTypeDesc->getString(h) << std::endl;
}
else
{
std::cout << featureDesc->getName() << " = non-printable type!" << std::endl;
}
}
std::cout << std::endl;
JsonSerializer js(std::cout);
js.serialize(&me);
std::cout << std::endl;
return 0;
}
<|endoftext|>
|
<commit_before>// The libMesh Finite Element Library.
// Copyright (C) 2002-2021 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner
// 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
// Local includes
#include "libmesh/libmesh_config.h"
#ifdef LIBMESH_ENABLE_HIGHER_ORDER_SHAPES
#include "libmesh/elem.h"
#include "libmesh/fe.h"
#include "libmesh/fe_interface.h"
namespace {
static const libMesh::FEFamily _underlying_fe_family = libMesh::BERNSTEIN;
}
namespace libMesh
{
LIBMESH_DEFAULT_VECTORIZED_FE(2,RATIONAL_BERNSTEIN)
template <>
Real FE<2,RATIONAL_BERNSTEIN>::shape(const Elem * elem,
const Order order,
const unsigned int i,
const Point & p,
const bool add_p_level)
{
libmesh_assert(elem);
int extra_order = add_p_level * elem->p_level();
// FEType object to be passed to various FEInterface functions below.
FEType fe_type(order, _underlying_fe_family);
const unsigned int n_sf =
FEInterface::n_shape_functions(fe_type, extra_order, elem);
const unsigned int n_nodes = elem->n_nodes();
libmesh_assert_equal_to (n_sf, n_nodes);
std::vector<Real> node_weights(n_nodes);
const unsigned char datum_index = elem->mapping_data();
for (unsigned int n=0; n<n_nodes; n++)
node_weights[n] =
elem->node_ref(n).get_extra_datum<Real>(datum_index);
Real weighted_shape_i = 0, weighted_sum = 0;
for (unsigned int sf=0; sf<n_sf; sf++)
{
Real weighted_shape = node_weights[sf] *
FEInterface::shape(fe_type, extra_order, elem, sf, p);
weighted_sum += weighted_shape;
if (sf == i)
weighted_shape_i = weighted_shape;
}
return weighted_shape_i / weighted_sum;
}
template <>
Real FE<2,RATIONAL_BERNSTEIN>::shape(const ElemType,
const Order,
const unsigned int,
const Point &)
{
libmesh_error_msg("Rational bases require the real element \nto query nodal weighting.");
return 0.;
}
template <>
Real FE<2,RATIONAL_BERNSTEIN>::shape(const FEType fet,
const Elem * elem,
const unsigned int i,
const Point & p,
const bool add_p_level)
{
return FE<2,RATIONAL_BERNSTEIN>::shape
(elem, fet.order, i, p, add_p_level);
}
template <>
Real FE<2,RATIONAL_BERNSTEIN>::shape_deriv(const Elem * elem,
const Order order,
const unsigned int i,
const unsigned int j,
const Point & p,
const bool add_p_level)
{
libmesh_assert(elem);
int extra_order = add_p_level * elem->p_level();
// FEType object to be passed to various FEInterface functions below.
FEType fe_type(order, _underlying_fe_family);
const unsigned int n_sf =
FEInterface::n_shape_functions(fe_type, extra_order, elem);
const unsigned int n_nodes = elem->n_nodes();
libmesh_assert_equal_to (n_sf, n_nodes);
std::vector<Real> node_weights(n_nodes);
const unsigned char datum_index = elem->mapping_data();
for (unsigned int n=0; n<n_nodes; n++)
node_weights[n] =
elem->node_ref(n).get_extra_datum<Real>(datum_index);
Real weighted_shape_i = 0, weighted_sum = 0,
weighted_grad_i = 0, weighted_grad_sum = 0;
for (unsigned int sf=0; sf<n_sf; sf++)
{
Real weighted_shape = node_weights[sf] *
FEInterface::shape(fe_type, extra_order, elem, sf, p);
Real weighted_grad = node_weights[sf] *
FEInterface::shape_deriv(fe_type, extra_order, elem, sf, j, p);
weighted_sum += weighted_shape;
weighted_grad_sum += weighted_grad;
if (sf == i)
{
weighted_shape_i = weighted_shape;
weighted_grad_i = weighted_grad;
}
}
return (weighted_sum * weighted_grad_i - weighted_shape_i * weighted_grad_sum) /
weighted_sum / weighted_sum;
}
template <>
Real FE<2,RATIONAL_BERNSTEIN>::shape_deriv(const ElemType,
const Order,
const unsigned int,
const unsigned int,
const Point &)
{
libmesh_error_msg("Rational bases require the real element \nto query nodal weighting.");
return 0.;
}
template <>
Real FE<2,RATIONAL_BERNSTEIN>::shape_deriv(const FEType fet,
const Elem * elem,
const unsigned int i,
const unsigned int j,
const Point & p,
const bool add_p_level)
{
return FE<2,RATIONAL_BERNSTEIN>::shape_deriv
(elem, fet.order, i, j, p, add_p_level);
}
#ifdef LIBMESH_ENABLE_SECOND_DERIVATIVES
template <>
Real FE<2,RATIONAL_BERNSTEIN>::shape_second_deriv(const Elem * elem,
const Order order,
const unsigned int i,
const unsigned int j,
const Point & p,
const bool add_p_level)
{
unsigned int j1, j2;
switch (j)
{
case 0:
// j = 0 ==> d^2 phi / dxi^2
j1 = j2 = 0;
break;
case 1:
// j = 1 ==> d^2 phi / dxi deta
j1 = 0;
j2 = 1;
break;
case 2:
// j = 2 ==> d^2 phi / deta^2
j1 = j2 = 1;
break;
default:
libmesh_error();
}
libmesh_assert(elem);
int extra_order = add_p_level * elem->p_level();
// FEType object to be passed to various FEInterface functions below.
FEType fe_type(order, _underlying_fe_family);
const unsigned int n_sf =
FEInterface::n_shape_functions(fe_type, extra_order, elem);
const unsigned int n_nodes = elem->n_nodes();
libmesh_assert_equal_to (n_sf, n_nodes);
std::vector<Real> node_weights(n_nodes);
const unsigned char datum_index = elem->mapping_data();
for (unsigned int n=0; n<n_nodes; n++)
node_weights[n] =
elem->node_ref(n).get_extra_datum<Real>(datum_index);
Real weighted_shape_i = 0, weighted_sum = 0,
weighted_grada_i = 0, weighted_grada_sum = 0,
weighted_gradb_i = 0, weighted_gradb_sum = 0,
weighted_hess_i = 0, weighted_hess_sum = 0;
for (unsigned int sf=0; sf<n_sf; sf++)
{
Real weighted_shape = node_weights[sf] *
FEInterface::shape(fe_type, extra_order, elem, sf, p);
Real weighted_grada = node_weights[sf] *
FEInterface::shape_deriv(fe_type, extra_order, elem, sf, j1, p);
Real weighted_hess = node_weights[sf] *
FEInterface::shape_second_deriv(fe_type, extra_order, elem, sf, j, p);
weighted_sum += weighted_shape;
weighted_grada_sum += weighted_grada;
Real weighted_gradb = weighted_grada;
if (j1 != j2)
{
weighted_gradb = (j1 == j2) ? weighted_grada :
node_weights[sf] *
FEInterface::shape_deriv(fe_type, extra_order, elem, sf, j2, p);
weighted_grada_sum += weighted_grada;
}
weighted_hess_sum += weighted_hess;
if (sf == i)
{
weighted_shape_i = weighted_shape;
weighted_grada_i = weighted_grada;
weighted_gradb_i = weighted_gradb;
weighted_hess_i = weighted_hess;
}
}
if (j1 == j2)
weighted_gradb_sum = weighted_grada_sum;
return (weighted_sum * weighted_hess_i - weighted_grada_i * weighted_gradb_sum -
weighted_shape_i * weighted_hess_sum - weighted_gradb_i * weighted_grada_sum +
2 * weighted_grada_sum * weighted_shape_i * weighted_gradb_sum / weighted_sum) /
weighted_sum / weighted_sum;
}
template <>
Real FE<2,RATIONAL_BERNSTEIN>::shape_second_deriv(const ElemType,
const Order,
const unsigned int,
const unsigned int,
const Point &)
{
libmesh_error_msg("Rational bases require the real element \nto query nodal weighting.");
return 0.;
}
template <>
Real FE<2,RATIONAL_BERNSTEIN>::shape_second_deriv(const FEType fet,
const Elem * elem,
const unsigned int i,
const unsigned int j,
const Point & p,
const bool add_p_level)
{
return FE<2,RATIONAL_BERNSTEIN>::shape_second_deriv
(elem, fet.order, i, j, p, add_p_level);
}
#endif
} // namespace libMesh
#endif// LIBMESH_ENABLE_HIGHER_ORDER_SHAPES
<commit_msg>Override 2D RATIONAL_BERNSTEIN all_shapes<commit_after>// The libMesh Finite Element Library.
// Copyright (C) 2002-2021 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner
// 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
// Local includes
#include "libmesh/libmesh_config.h"
#ifdef LIBMESH_ENABLE_HIGHER_ORDER_SHAPES
#include "libmesh/elem.h"
#include "libmesh/fe.h"
#include "libmesh/fe_interface.h"
namespace {
using namespace libMesh;
static const FEFamily _underlying_fe_family = BERNSTEIN;
// shapes[i][j] is shape function phi_i at point p[j]
void weighted_shapes(const Elem * elem,
FEType fe_type,
std::vector<std::vector<Real>> & shapes,
const std::vector<Point> & p,
const bool add_p_level)
{
const int extra_order = add_p_level * elem->p_level();
const unsigned int n_sf =
FEInterface::n_shape_functions(fe_type, extra_order, elem);
libmesh_assert_equal_to (n_sf, elem->n_nodes());
std::vector<Real> node_weights(n_sf);
const unsigned char datum_index = elem->mapping_data();
for (unsigned int n=0; n<n_sf; n++)
node_weights[n] =
elem->node_ref(n).get_extra_datum<Real>(datum_index);
const std::size_t n_p = p.size();
shapes.resize(n_sf);
for (unsigned int i=0; i != n_sf; ++i)
{
auto & shapes_i = shapes[i];
shapes_i.resize(n_p, 0);
FEInterface::shapes(2, fe_type, elem, i, p, shapes_i, add_p_level);
for (auto & s : shapes_i)
s *= node_weights[i];
}
}
} // anonymous namespace
namespace libMesh
{
template <>
Real FE<2,RATIONAL_BERNSTEIN>::shape(const Elem * elem,
const Order order,
const unsigned int i,
const Point & p,
const bool add_p_level)
{
libmesh_assert(elem);
int extra_order = add_p_level * elem->p_level();
// FEType object to be passed to various FEInterface functions below.
FEType fe_type(order, _underlying_fe_family);
const unsigned int n_sf =
FEInterface::n_shape_functions(fe_type, extra_order, elem);
const unsigned int n_nodes = elem->n_nodes();
libmesh_assert_equal_to (n_sf, n_nodes);
std::vector<Real> node_weights(n_nodes);
const unsigned char datum_index = elem->mapping_data();
for (unsigned int n=0; n<n_nodes; n++)
node_weights[n] =
elem->node_ref(n).get_extra_datum<Real>(datum_index);
Real weighted_shape_i = 0, weighted_sum = 0;
for (unsigned int sf=0; sf<n_sf; sf++)
{
Real weighted_shape = node_weights[sf] *
FEInterface::shape(fe_type, extra_order, elem, sf, p);
weighted_sum += weighted_shape;
if (sf == i)
weighted_shape_i = weighted_shape;
}
return weighted_shape_i / weighted_sum;
}
template <>
Real FE<2,RATIONAL_BERNSTEIN>::shape(const ElemType,
const Order,
const unsigned int,
const Point &)
{
libmesh_error_msg("Rational bases require the real element \nto query nodal weighting.");
return 0.;
}
template <>
Real FE<2,RATIONAL_BERNSTEIN>::shape(const FEType fet,
const Elem * elem,
const unsigned int i,
const Point & p,
const bool add_p_level)
{
return FE<2,RATIONAL_BERNSTEIN>::shape
(elem, fet.order, i, p, add_p_level);
}
template <>
Real FE<2,RATIONAL_BERNSTEIN>::shape_deriv(const Elem * elem,
const Order order,
const unsigned int i,
const unsigned int j,
const Point & p,
const bool add_p_level)
{
libmesh_assert(elem);
int extra_order = add_p_level * elem->p_level();
// FEType object to be passed to various FEInterface functions below.
FEType fe_type(order, _underlying_fe_family);
const unsigned int n_sf =
FEInterface::n_shape_functions(fe_type, extra_order, elem);
const unsigned int n_nodes = elem->n_nodes();
libmesh_assert_equal_to (n_sf, n_nodes);
std::vector<Real> node_weights(n_nodes);
const unsigned char datum_index = elem->mapping_data();
for (unsigned int n=0; n<n_nodes; n++)
node_weights[n] =
elem->node_ref(n).get_extra_datum<Real>(datum_index);
Real weighted_shape_i = 0, weighted_sum = 0,
weighted_grad_i = 0, weighted_grad_sum = 0;
for (unsigned int sf=0; sf<n_sf; sf++)
{
Real weighted_shape = node_weights[sf] *
FEInterface::shape(fe_type, extra_order, elem, sf, p);
Real weighted_grad = node_weights[sf] *
FEInterface::shape_deriv(fe_type, extra_order, elem, sf, j, p);
weighted_sum += weighted_shape;
weighted_grad_sum += weighted_grad;
if (sf == i)
{
weighted_shape_i = weighted_shape;
weighted_grad_i = weighted_grad;
}
}
return (weighted_sum * weighted_grad_i - weighted_shape_i * weighted_grad_sum) /
weighted_sum / weighted_sum;
}
template <>
Real FE<2,RATIONAL_BERNSTEIN>::shape_deriv(const ElemType,
const Order,
const unsigned int,
const unsigned int,
const Point &)
{
libmesh_error_msg("Rational bases require the real element \nto query nodal weighting.");
return 0.;
}
template <>
Real FE<2,RATIONAL_BERNSTEIN>::shape_deriv(const FEType fet,
const Elem * elem,
const unsigned int i,
const unsigned int j,
const Point & p,
const bool add_p_level)
{
return FE<2,RATIONAL_BERNSTEIN>::shape_deriv
(elem, fet.order, i, j, p, add_p_level);
}
#ifdef LIBMESH_ENABLE_SECOND_DERIVATIVES
template <>
Real FE<2,RATIONAL_BERNSTEIN>::shape_second_deriv(const Elem * elem,
const Order order,
const unsigned int i,
const unsigned int j,
const Point & p,
const bool add_p_level)
{
unsigned int j1, j2;
switch (j)
{
case 0:
// j = 0 ==> d^2 phi / dxi^2
j1 = j2 = 0;
break;
case 1:
// j = 1 ==> d^2 phi / dxi deta
j1 = 0;
j2 = 1;
break;
case 2:
// j = 2 ==> d^2 phi / deta^2
j1 = j2 = 1;
break;
default:
libmesh_error();
}
libmesh_assert(elem);
int extra_order = add_p_level * elem->p_level();
// FEType object to be passed to various FEInterface functions below.
FEType fe_type(order, _underlying_fe_family);
const unsigned int n_sf =
FEInterface::n_shape_functions(fe_type, extra_order, elem);
const unsigned int n_nodes = elem->n_nodes();
libmesh_assert_equal_to (n_sf, n_nodes);
std::vector<Real> node_weights(n_nodes);
const unsigned char datum_index = elem->mapping_data();
for (unsigned int n=0; n<n_nodes; n++)
node_weights[n] =
elem->node_ref(n).get_extra_datum<Real>(datum_index);
Real weighted_shape_i = 0, weighted_sum = 0,
weighted_grada_i = 0, weighted_grada_sum = 0,
weighted_gradb_i = 0, weighted_gradb_sum = 0,
weighted_hess_i = 0, weighted_hess_sum = 0;
for (unsigned int sf=0; sf<n_sf; sf++)
{
Real weighted_shape = node_weights[sf] *
FEInterface::shape(fe_type, extra_order, elem, sf, p);
Real weighted_grada = node_weights[sf] *
FEInterface::shape_deriv(fe_type, extra_order, elem, sf, j1, p);
Real weighted_hess = node_weights[sf] *
FEInterface::shape_second_deriv(fe_type, extra_order, elem, sf, j, p);
weighted_sum += weighted_shape;
weighted_grada_sum += weighted_grada;
Real weighted_gradb = weighted_grada;
if (j1 != j2)
{
weighted_gradb = (j1 == j2) ? weighted_grada :
node_weights[sf] *
FEInterface::shape_deriv(fe_type, extra_order, elem, sf, j2, p);
weighted_grada_sum += weighted_grada;
}
weighted_hess_sum += weighted_hess;
if (sf == i)
{
weighted_shape_i = weighted_shape;
weighted_grada_i = weighted_grada;
weighted_gradb_i = weighted_gradb;
weighted_hess_i = weighted_hess;
}
}
if (j1 == j2)
weighted_gradb_sum = weighted_grada_sum;
return (weighted_sum * weighted_hess_i - weighted_grada_i * weighted_gradb_sum -
weighted_shape_i * weighted_hess_sum - weighted_gradb_i * weighted_grada_sum +
2 * weighted_grada_sum * weighted_shape_i * weighted_gradb_sum / weighted_sum) /
weighted_sum / weighted_sum;
}
template <>
Real FE<2,RATIONAL_BERNSTEIN>::shape_second_deriv(const ElemType,
const Order,
const unsigned int,
const unsigned int,
const Point &)
{
libmesh_error_msg("Rational bases require the real element \nto query nodal weighting.");
return 0.;
}
template <>
Real FE<2,RATIONAL_BERNSTEIN>::shape_second_deriv(const FEType fet,
const Elem * elem,
const unsigned int i,
const unsigned int j,
const Point & p,
const bool add_p_level)
{
return FE<2,RATIONAL_BERNSTEIN>::shape_second_deriv
(elem, fet.order, i, j, p, add_p_level);
}
#endif
// LIBMESH_DEFAULT_VECTORIZED_FE(2, RATIONAL_BERNSTEIN)
template<>
void FE<2,RATIONAL_BERNSTEIN>::shapes
(const Elem * elem,
const Order o,
const unsigned int i,
const std::vector<Point> & p,
std::vector<OutputShape> & vi,
const bool add_p_level)
{
// FE<2,RATIONAL_BERNSTEIN>::default_shapes(elem,o,i,p,vi,add_p_level);
libmesh_assert_equal_to(p.size(), vi.size());
for (auto j : index_range(vi))
vi[j] = FE<2,RATIONAL_BERNSTEIN>::shape (elem, o, i, p[j], add_p_level);
}
template<>
void FE<2,RATIONAL_BERNSTEIN>::all_shapes
(const Elem * elem,
const Order o,
const std::vector<Point> & p,
std::vector<std::vector<OutputShape>> & v,
const bool add_p_level)
{
std::vector<std::vector<Real>> shapes;
FEType fe_type(o, _underlying_fe_family);
weighted_shapes(elem, fe_type, shapes, p, add_p_level);
std::vector<Real> shape_sums(p.size(), 0);
for (auto i : index_range(v))
{
libmesh_assert_equal_to ( p.size(), shapes[i].size() );
for (auto j : index_range(p))
shape_sums[j] += shapes[i][j];
}
for (auto i : index_range(v))
{
libmesh_assert_equal_to ( p.size(), v[i].size() );
for (auto j : index_range(v[i]))
{
v[i][j] = shapes[i][j] / shape_sums[j];
#ifdef DEBUG
Real old_shape = FE<2,RATIONAL_BERNSTEIN>::shape (elem, o, i, p[j], add_p_level);
libmesh_assert(std::abs(v[i][j] - old_shape) < TOLERANCE*TOLERANCE);
#endif
}
}
}
template<>
void FE<2,RATIONAL_BERNSTEIN>::shape_derivs
(const Elem * elem,
const Order o,
const unsigned int i,
const unsigned int j,
const std::vector<Point> & p,
std::vector<OutputShape> & v,
const bool add_p_level)
{
libmesh_assert_equal_to(p.size(), v.size());
for (auto vi : index_range(v))
v[vi] = FE<2,RATIONAL_BERNSTEIN>::shape_deriv (elem, o, i, j, p[vi], add_p_level);
}
} // namespace libMesh
#endif// LIBMESH_ENABLE_HIGHER_ORDER_SHAPES
<|endoftext|>
|
<commit_before>
/* ****************************************************************************
*
* FILE DelilahUtils.cpp
*
* AUTHOR Andreu Urruela
*
* PROJECT Samson
*
* DATE 8/31/11
*
* DESCRIPTION
*
* Copyright 2011 Andreu Urruela. All rights reserved.
*
* ****************************************************************************/
#include <sstream> // std::ostringstream
#include <iomanip> // std::setw
#include "au/Descriptors.h" // au::Descriptors
#include "DelilahUtils.h" // Own interface
namespace samson {
std::string getStreamOperationInfo( const pugi::xml_node& node )
{
// Get information for this state
std::string name = pugi::get( node , "name" );
std::string description = pugi::get( node , "description" );
std::ostringstream output;
output << std::setw(15) << name << " " << description;
return output.str();
}
std::string getBLockListInfo( pugi::node node )
{
size_t size_total = pugi::getUInt64( node , "size_total" );
size_t size_on_memory = pugi::getUInt64( node , "size_on_memory" );
size_t size_on_disk = pugi::getUInt64( node , "size_on_disk" );
int num_blocks = pugi::getInt( node , "num_blocks" );
size_t kvs = pugi::getUInt64( node , "kvs" );
size_t size = pugi::getUInt64( node , "size" );
if( ( kvs == 0 ) && (size == 0) )
return "Empty";
std::ostringstream output;
output << num_blocks << " blocks with ";
output << au::str( kvs , "kvs" ) << " in ";
output << au::str( size , "bytes" ) ;
output << " ";
if( size_total > 0 )
{
double p_memory = (double) size_on_memory / (double) size_total;
double p_disk = (double) size_on_disk / (double) size_total;
output << au::Format::percentage_string( p_memory ) << " on memory & " << au::Format::percentage_string( p_disk ) << " on disk";
}
return output.str();
}
std::string getQueueInfo( const pugi::xml_node& queue )
{
// Get information for this state
std::string name = pugi::get( queue , "name" );
const pugi::node block_list = queue.first_element_by_path("block_list");
std::ostringstream output;
output << std::setw(15) << name << ": [ " << getBLockListInfo (block_list ) << " ]";
return output.str();
}
std::string getStateInfo( const pugi::xml_node& state )
{
std::ostringstream output;
// Get information for this state
std::string name = pugi::get( state, "name" );
int num_state_items = pugi::getInt( state , "num_state_items" );
const pugi::node state_info = state.first_element_by_path("state_info").first_element_by_path("block_list");
const pugi::node input_info = state.first_element_by_path("input_info").first_element_by_path("block_list");
output << "State " << name << ": ( " << num_state_items << " state items ) ";
output << " State: [ " << getBLockListInfo( state_info ) << " ] ";
output << " Input: [ " << getBLockListInfo( input_info ) << " ] ";
output << "\n";
return output.str();
}
std::string getQueueTaskInfo( const pugi::xml_node& queue_task )
{
// Get information for this state
std::string id = pugi::get( queue_task , "id" );
std::string description = pugi::get( queue_task , "description" );
const pugi::node block_list = queue_task.first_element_by_path("block_list");
std::ostringstream output;
output << "Task " << id << " : " << description << "\n";
output << " -> Input " << getBLockListInfo( block_list ) << "\n";
return output.str();
}
std::string getFormatInfo( const pugi::xml_node& node )
{
// Get information for this state
std::string key_format = pugi::get( node , "key_format" );
std::string value_format = pugi::get( node , "value_format" );
std::ostringstream output;
output << "[" << key_format << "-" << value_format << "]";
return output.str();
}
std::string getDataInfo( const pugi::xml_node& node )
{
std::ostringstream output;
// Get information for this state
std::string name = pugi::get( node , "name" );
std::string help = pugi::get( node , "help" );
output << "** " << std::left << std::setw(40) << name << " - " << help;
return output.str();
}
std::string getOperationInfo( const pugi::xml_node& node )
{
std::ostringstream output;
// Get information for this state
std::string name = pugi::get( node , "name" );
std::string type = pugi::get( node , "type" );
std::string help = pugi::get( node , "help" );
output << "** " << name << " ( " << type << " )\n";
output << "\t\tInputs: ";
pugi::xml_node input_formats = node.first_element_by_path("input_formats");
for( pugi::xml_node_iterator n = input_formats.begin() ; n != input_formats.end() ; n++)
output << getFormatInfo(*n) << " ";
output << "\n";
output << "\t\tOutputs: ";
pugi::xml_node output_formats = node.first_element_by_path("output_formats");
for( pugi::xml_node_iterator n = output_formats.begin() ; n != output_formats.end() ; n++)
output << getFormatInfo(*n) << " ";
output << "\n";
output << "\t\tHelp: " << help << "\n";
return output.str();
}
std::string getTaskInfo( const pugi::xml_node& node )
{
std::string id = pugi::get( node , "id" );
std::string job_id = pugi::get( node , "job_id" );
std::string name = pugi::get( node , "name" );
std::string state = pugi::get( node , "state" );
std::ostringstream output;
output << "[ " << id << " ] [ Job " << job_id << " ] [ " << state << " ] " << name << " " ;
if( state == "running" )
{
size_t total_info = pugi::getUInt64( node , "total_info" );
size_t running_info = pugi::getUInt64( node , "running_info" );
size_t processed_info = pugi::getUInt64( node , "processed_info" );
output << "[ Progress: ";
output << au::str( running_info , "bytes" ) << " / ";
output << au::str( processed_info , "bytes" ) << " / ";
output << au::str( total_info , "bytes" );
output << "]";
}
return output.str();
}
std::string getWorkerTaskInfo( const pugi::xml_node& node )
{
std::string task_id = pugi::get( node , "task_id" );
std::string operation = pugi::get( node , "operation" );
std::string status = pugi::get( node , "status" );
int num_workers = (int) pugi::getUInt64( node , "num_workers" );
int num_finished_workers = (int) pugi::getUInt64( node , "num_finished_workers" );
std::ostringstream output;
output << "[ " << task_id << " ] [ " << status << " ] " << operation << " " ;
if( num_finished_workers == num_workers )
output << " All workers finised ";
else
output << " Completed workers " << num_finished_workers << " / " << num_workers;
au::Descriptors descriptors;
pugi::xml_node node_worker_subtasks = node.first_element_by_path("worker_subtasks");
for( pugi::xml_node_iterator n = node_worker_subtasks.begin() ; n != node_worker_subtasks.end() ; n++)
{
std::string description = pugi::get(*n, "description" );
std::string state = pugi::get(*n, "state" );
descriptors.add( au::str( "[ %s : %s ]" , description.c_str() , state.c_str() ) );
}
output << "\n\t SubTasks: " << descriptors.str();
return output.str();
}
std::string getJobInfo( const pugi::xml_node& node )
{
std::ostringstream output;
std::string id = pugi::get( node , "id" );
std::string command = pugi::get( node , "command" );
std::string status = pugi::get( node , "status" );
output << " [ " << id << " ] [ " << std::setw(10) << std::left << status << " ] " << command;
pugi::xml_node current_task = node.first_element_by_path("current_task").first_element_by_path("controller_task");
if( pugi::get( current_task , "id" ) != "" )
output << "\n\tCurrent task: " << getTaskInfo( current_task );
return output.str();
}
std::string getModuleInfo( const pugi::xml_node& node )
{
std::ostringstream output;
std::string name = pugi::get( node , "name" );
std::string version = pugi::get( node , "version" );
std::string author = pugi::get( node , "author" );
int num_operations = getNumChildrens( node.first_element_by_path("operations") , "operation" );
int num_datas = getNumChildrens( node.first_element_by_path("datas") , "dats" );
output << " Module " << std::left << std::setw(25) << name << " " << std::setw(10) << version;
output << std::setw(15) << au::str("[ #ops: %3d #datas: %3d ]",num_operations, num_datas);
output << " ( " << author << ")";
return output.str();
}
std::string getNetworkInfo( const pugi::xml_node& node )
{
std::ostringstream output;
std::string description = pugi::get( node , "description" );
output << description << "\n";
return output.str();
}
std::string getEngineSystemInfo( const pugi::xml_node& node )
{
pugi::xml_node node_memory_manager = node.first_element_by_path("memory_manager");
pugi::xml_node node_disk_manager = node.first_element_by_path("disk_manager");
pugi::xml_node node_process_manager = node.first_element_by_path("process_manager");
std::ostringstream output;
size_t memory = pugi::getUInt64( node_memory_manager , "memory" );
size_t used_memory = pugi::getUInt64( node_memory_manager , "used_memory" );
int num_buffers = (int) pugi::getUInt64( node_memory_manager , "num_buffers" );
output << "** Memory: " << au::str( used_memory , "bytes" ) << " / " << au::str( memory , "bytes" ) << " ( " << num_buffers << " buffers )\n";
size_t num_pending_operations = pugi::getUInt64( node_disk_manager , "num_pending_operations" );
size_t num_running_operations = pugi::getUInt64( node_disk_manager , "num_running_operations" );
std::string t_statistics = pugi::get( node_disk_manager.first_element_by_path("statistics").first_element_by_path("total") , "description" );
std::string r_statistics = pugi::get( node_disk_manager.first_element_by_path("statistics").first_element_by_path("read") , "description" );
std::string w_statistics = pugi::get( node_disk_manager.first_element_by_path("statistics").first_element_by_path("write") , "description" );
output << "\n";
output << "** Disk: Running " << num_running_operations << " ops, waiting " << num_pending_operations << " ops\n";
output << " READ [ " << r_statistics << " ]\n";
output << " WRITE [ " << w_statistics << " ]\n";
output << " TOTAL [ " << t_statistics << " ]\n";
pugi::xml_node running = node_process_manager.first_element_by_path("running");
pugi::xml_node queued = node_process_manager.first_element_by_path("queued");
pugi::xml_node halted = node_process_manager.first_element_by_path("halted");
au::Descriptors queued_elements;
pugi::xml_node_iterator n;
for( n = queued.begin() ; n != queued.end() ; n++)
queued_elements.add( pugi::get(*n , "operation_name" ) );
au::Descriptors halted_elements;
for( n = halted.begin() ; n != halted.end() ; n++)
halted_elements.add( pugi::get(*n , "operation_name" ) );
output << "\n";
output << "** Process manager:\n";
output << " QUEUED: " << queued_elements.str() << "\n";
output << " HALTED: " << halted_elements.str() << "\n";
output << " RUNNING:\n";
for( n = running.begin() ; n != running.end() ; n++)
{
output << " ";
output << "[ Priority " << pugi::get( *n , "priority") << " ] ";
output << "[ Progress " << au::Format::percentage_string( pugi::getDouble( *n , "progress") ) << " ] ";
output << pugi::get( *n , "operation_name");
output << "\n";
}
return output.str();
}
std::string getSetInfo( const pugi::xml_node& queue )
{
std::ostringstream output;
// Get information for this state
std::string name = pugi::get( queue , "name" );
size_t kvs = pugi::getUInt64( queue , "kvs" );
size_t size = pugi::getUInt64( queue , "size" );
size_t num_files = pugi::getUInt64( queue , "num_files" );
pugi::xml_node format_node = queue.first_element_by_path("format");
output << std::setw(30) << name;
output << " ";
output << au::str( kvs );
output << " kvs in ";
output << au::str( size ) << " bytes";
output << " #File: " << num_files;
output << " " << getFormatInfo( format_node );
return output.str();
}
}
<commit_msg>Fix bug about showing the number of datas in a particular module (ls_modules)<commit_after>
/* ****************************************************************************
*
* FILE DelilahUtils.cpp
*
* AUTHOR Andreu Urruela
*
* PROJECT Samson
*
* DATE 8/31/11
*
* DESCRIPTION
*
* Copyright 2011 Andreu Urruela. All rights reserved.
*
* ****************************************************************************/
#include <sstream> // std::ostringstream
#include <iomanip> // std::setw
#include "au/Descriptors.h" // au::Descriptors
#include "DelilahUtils.h" // Own interface
namespace samson {
std::string getStreamOperationInfo( const pugi::xml_node& node )
{
// Get information for this state
std::string name = pugi::get( node , "name" );
std::string description = pugi::get( node , "description" );
std::ostringstream output;
output << std::setw(15) << name << " " << description;
return output.str();
}
std::string getBLockListInfo( pugi::node node )
{
size_t size_total = pugi::getUInt64( node , "size_total" );
size_t size_on_memory = pugi::getUInt64( node , "size_on_memory" );
size_t size_on_disk = pugi::getUInt64( node , "size_on_disk" );
int num_blocks = pugi::getInt( node , "num_blocks" );
size_t kvs = pugi::getUInt64( node , "kvs" );
size_t size = pugi::getUInt64( node , "size" );
if( ( kvs == 0 ) && (size == 0) )
return "Empty";
std::ostringstream output;
output << num_blocks << " blocks with ";
output << au::str( kvs , "kvs" ) << " in ";
output << au::str( size , "bytes" ) ;
output << " ";
if( size_total > 0 )
{
double p_memory = (double) size_on_memory / (double) size_total;
double p_disk = (double) size_on_disk / (double) size_total;
output << au::Format::percentage_string( p_memory ) << " on memory & " << au::Format::percentage_string( p_disk ) << " on disk";
}
return output.str();
}
std::string getQueueInfo( const pugi::xml_node& queue )
{
// Get information for this state
std::string name = pugi::get( queue , "name" );
const pugi::node block_list = queue.first_element_by_path("block_list");
std::ostringstream output;
output << std::setw(15) << name << ": [ " << getBLockListInfo (block_list ) << " ]";
return output.str();
}
std::string getStateInfo( const pugi::xml_node& state )
{
std::ostringstream output;
// Get information for this state
std::string name = pugi::get( state, "name" );
int num_state_items = pugi::getInt( state , "num_state_items" );
const pugi::node state_info = state.first_element_by_path("state_info").first_element_by_path("block_list");
const pugi::node input_info = state.first_element_by_path("input_info").first_element_by_path("block_list");
output << "State " << name << ": ( " << num_state_items << " state items ) ";
output << " State: [ " << getBLockListInfo( state_info ) << " ] ";
output << " Input: [ " << getBLockListInfo( input_info ) << " ] ";
output << "\n";
return output.str();
}
std::string getQueueTaskInfo( const pugi::xml_node& queue_task )
{
// Get information for this state
std::string id = pugi::get( queue_task , "id" );
std::string description = pugi::get( queue_task , "description" );
const pugi::node block_list = queue_task.first_element_by_path("block_list");
std::ostringstream output;
output << "Task " << id << " : " << description << "\n";
output << " -> Input " << getBLockListInfo( block_list ) << "\n";
return output.str();
}
std::string getFormatInfo( const pugi::xml_node& node )
{
// Get information for this state
std::string key_format = pugi::get( node , "key_format" );
std::string value_format = pugi::get( node , "value_format" );
std::ostringstream output;
output << "[" << key_format << "-" << value_format << "]";
return output.str();
}
std::string getDataInfo( const pugi::xml_node& node )
{
std::ostringstream output;
// Get information for this state
std::string name = pugi::get( node , "name" );
std::string help = pugi::get( node , "help" );
output << "** " << std::left << std::setw(40) << name << " - " << help;
return output.str();
}
std::string getOperationInfo( const pugi::xml_node& node )
{
std::ostringstream output;
// Get information for this state
std::string name = pugi::get( node , "name" );
std::string type = pugi::get( node , "type" );
std::string help = pugi::get( node , "help" );
output << "** " << name << " ( " << type << " )\n";
output << "\t\tInputs: ";
pugi::xml_node input_formats = node.first_element_by_path("input_formats");
for( pugi::xml_node_iterator n = input_formats.begin() ; n != input_formats.end() ; n++)
output << getFormatInfo(*n) << " ";
output << "\n";
output << "\t\tOutputs: ";
pugi::xml_node output_formats = node.first_element_by_path("output_formats");
for( pugi::xml_node_iterator n = output_formats.begin() ; n != output_formats.end() ; n++)
output << getFormatInfo(*n) << " ";
output << "\n";
output << "\t\tHelp: " << help << "\n";
return output.str();
}
std::string getTaskInfo( const pugi::xml_node& node )
{
std::string id = pugi::get( node , "id" );
std::string job_id = pugi::get( node , "job_id" );
std::string name = pugi::get( node , "name" );
std::string state = pugi::get( node , "state" );
std::ostringstream output;
output << "[ " << id << " ] [ Job " << job_id << " ] [ " << state << " ] " << name << " " ;
if( state == "running" )
{
size_t total_info = pugi::getUInt64( node , "total_info" );
size_t running_info = pugi::getUInt64( node , "running_info" );
size_t processed_info = pugi::getUInt64( node , "processed_info" );
output << "[ Progress: ";
output << au::str( running_info , "bytes" ) << " / ";
output << au::str( processed_info , "bytes" ) << " / ";
output << au::str( total_info , "bytes" );
output << "]";
}
return output.str();
}
std::string getWorkerTaskInfo( const pugi::xml_node& node )
{
std::string task_id = pugi::get( node , "task_id" );
std::string operation = pugi::get( node , "operation" );
std::string status = pugi::get( node , "status" );
int num_workers = (int) pugi::getUInt64( node , "num_workers" );
int num_finished_workers = (int) pugi::getUInt64( node , "num_finished_workers" );
std::ostringstream output;
output << "[ " << task_id << " ] [ " << status << " ] " << operation << " " ;
if( num_finished_workers == num_workers )
output << " All workers finised ";
else
output << " Completed workers " << num_finished_workers << " / " << num_workers;
au::Descriptors descriptors;
pugi::xml_node node_worker_subtasks = node.first_element_by_path("worker_subtasks");
for( pugi::xml_node_iterator n = node_worker_subtasks.begin() ; n != node_worker_subtasks.end() ; n++)
{
std::string description = pugi::get(*n, "description" );
std::string state = pugi::get(*n, "state" );
descriptors.add( au::str( "[ %s : %s ]" , description.c_str() , state.c_str() ) );
}
output << "\n\t SubTasks: " << descriptors.str();
return output.str();
}
std::string getJobInfo( const pugi::xml_node& node )
{
std::ostringstream output;
std::string id = pugi::get( node , "id" );
std::string command = pugi::get( node , "command" );
std::string status = pugi::get( node , "status" );
output << " [ " << id << " ] [ " << std::setw(10) << std::left << status << " ] " << command;
pugi::xml_node current_task = node.first_element_by_path("current_task").first_element_by_path("controller_task");
if( pugi::get( current_task , "id" ) != "" )
output << "\n\tCurrent task: " << getTaskInfo( current_task );
return output.str();
}
std::string getModuleInfo( const pugi::xml_node& node )
{
std::ostringstream output;
std::string name = pugi::get( node , "name" );
std::string version = pugi::get( node , "version" );
std::string author = pugi::get( node , "author" );
int num_operations = getNumChildrens( node.first_element_by_path("operations") , "operation" );
int num_datas = getNumChildrens( node.first_element_by_path("datas") , "data" );
output << " Module " << std::left << std::setw(25) << name << " " << std::setw(10) << version;
output << std::setw(15) << au::str("[ #ops: %3d #datas: %3d ]",num_operations, num_datas);
output << " ( " << author << ")";
return output.str();
}
std::string getNetworkInfo( const pugi::xml_node& node )
{
std::ostringstream output;
std::string description = pugi::get( node , "description" );
output << description << "\n";
return output.str();
}
std::string getEngineSystemInfo( const pugi::xml_node& node )
{
pugi::xml_node node_memory_manager = node.first_element_by_path("memory_manager");
pugi::xml_node node_disk_manager = node.first_element_by_path("disk_manager");
pugi::xml_node node_process_manager = node.first_element_by_path("process_manager");
std::ostringstream output;
size_t memory = pugi::getUInt64( node_memory_manager , "memory" );
size_t used_memory = pugi::getUInt64( node_memory_manager , "used_memory" );
int num_buffers = (int) pugi::getUInt64( node_memory_manager , "num_buffers" );
output << "** Memory: " << au::str( used_memory , "bytes" ) << " / " << au::str( memory , "bytes" ) << " ( " << num_buffers << " buffers )\n";
size_t num_pending_operations = pugi::getUInt64( node_disk_manager , "num_pending_operations" );
size_t num_running_operations = pugi::getUInt64( node_disk_manager , "num_running_operations" );
std::string t_statistics = pugi::get( node_disk_manager.first_element_by_path("statistics").first_element_by_path("total") , "description" );
std::string r_statistics = pugi::get( node_disk_manager.first_element_by_path("statistics").first_element_by_path("read") , "description" );
std::string w_statistics = pugi::get( node_disk_manager.first_element_by_path("statistics").first_element_by_path("write") , "description" );
output << "\n";
output << "** Disk: Running " << num_running_operations << " ops, waiting " << num_pending_operations << " ops\n";
output << " READ [ " << r_statistics << " ]\n";
output << " WRITE [ " << w_statistics << " ]\n";
output << " TOTAL [ " << t_statistics << " ]\n";
pugi::xml_node running = node_process_manager.first_element_by_path("running");
pugi::xml_node queued = node_process_manager.first_element_by_path("queued");
pugi::xml_node halted = node_process_manager.first_element_by_path("halted");
au::Descriptors queued_elements;
pugi::xml_node_iterator n;
for( n = queued.begin() ; n != queued.end() ; n++)
queued_elements.add( pugi::get(*n , "operation_name" ) );
au::Descriptors halted_elements;
for( n = halted.begin() ; n != halted.end() ; n++)
halted_elements.add( pugi::get(*n , "operation_name" ) );
output << "\n";
output << "** Process manager:\n";
output << " QUEUED: " << queued_elements.str() << "\n";
output << " HALTED: " << halted_elements.str() << "\n";
output << " RUNNING:\n";
for( n = running.begin() ; n != running.end() ; n++)
{
output << " ";
output << "[ Priority " << pugi::get( *n , "priority") << " ] ";
output << "[ Progress " << au::Format::percentage_string( pugi::getDouble( *n , "progress") ) << " ] ";
output << pugi::get( *n , "operation_name");
output << "\n";
}
return output.str();
}
std::string getSetInfo( const pugi::xml_node& queue )
{
std::ostringstream output;
// Get information for this state
std::string name = pugi::get( queue , "name" );
size_t kvs = pugi::getUInt64( queue , "kvs" );
size_t size = pugi::getUInt64( queue , "size" );
size_t num_files = pugi::getUInt64( queue , "num_files" );
pugi::xml_node format_node = queue.first_element_by_path("format");
output << std::setw(30) << name;
output << " ";
output << au::str( kvs );
output << " kvs in ";
output << au::str( size ) << " bytes";
output << " #File: " << num_files;
output << " " << getFormatInfo( format_node );
return output.str();
}
}
<|endoftext|>
|
<commit_before>/* bzflag
* Copyright (c) 1993 - 2006 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named LICENSE that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
/* interface header */
#include "CommandsStandard.h"
/* system implementation headers */
#include <stdio.h>
#include <ctype.h>
#include <string>
/* common implementation headers */
#include "CommandManager.h"
#include "StateDatabase.h"
#include "KeyManager.h"
#include "TextUtils.h"
static bool quitFlag = false;
//
// command handlers
//
static std::string cmdQuit(const std::string&,
const CommandManager::ArgList&, bool*)
{
CommandsStandard::quit();
return std::string();
}
static void onHelpCB(const std::string& name,
void* userData)
{
std::string& result = *static_cast<std::string*>(userData);
result += name;
result += "\n";
}
static std::string cmdHelp(const std::string&,
const CommandManager::ArgList& args, bool*)
{
switch (args.size()) {
case 0: {
std::string result;
CMDMGR.iterate(&onHelpCB, &result);
return result;
}
case 1:
return CMDMGR.getHelp(args[0]);
default:
return "usage: help [<command-name>]";
}
}
static std::string cmdPrint(const std::string&,
const CommandManager::ArgList& args, bool*)
{
// merge all arguments into one string
std::string arg;
const unsigned int n = (int)args.size();
if (n > 0)
arg = args[0];
for (unsigned int i = 1; i < n; ++i) {
arg += " ";
arg += args[i];
}
// interpolate variables
std::string result;
const char* scan = arg.c_str();
while (*scan != '\0') {
if (*scan != '$') {
result.append(scan, 1);
++scan;
} else {
// could be a variable
++scan;
if (*scan == '$') {
// no, it's just $$ which maps to $
result += "$";
++scan;
} else if (*scan != '{') {
// parse variable name
const char* name = scan;
while (*scan != '\0' && !isspace(*scan))
++scan;
// look up variable
result += BZDB.get(std::string(name, scan - name));
} else {
// parse "quoted" variable name
const char* name = ++scan;
while (*scan != '\0' && *scan != '}')
++scan;
if (*scan != '\0') {
// look up variable
result += BZDB.get(std::string(name, scan - name));
// skip }
++scan;
}
}
}
}
std::cout << "printing \"" << result << "\"" << std::endl;
return result;
}
static void onSetCB(const std::string& name,
void* userData)
{
// don't show names starting with _
std::string& result = *static_cast<std::string*>(userData);
if (!name.empty() && name.c_str()[0] != '_') {
result += name;
result += " = ";
result += BZDB.get(name);
result += "\n";
}
}
static std::string cmdSet(const std::string&,
const CommandManager::ArgList& args, bool* error)
{
if(error) *error = false;
switch (args.size()) {
case 0:
{
// print out all values that are set
std::string result;
BZDB.iterate(&onSetCB, &result);
return result;
}
case 1:
{
// the string was set to nothing, so just print value
if (BZDB.isSet(args[0])) {
return args[0] + " is " + BZDB.get(args[0]);
} else {
if(error) *error = true;
return "variable " + args[0] + " does not exist";
}
}
case 2:
{
// set variable to value
BZDB.set(args[0], args[1], StateDatabase::User);
return std::string();
}
default:
{
if(error) *error = true;
return "usage: set <name> [<value>]";
}
}
}
static std::string cmdUnset(const std::string&,
const CommandManager::ArgList& args, bool*)
{
if (args.size() != 1)
return "usage: unset <name>";
BZDB.unset(args[0], StateDatabase::User);
return std::string();
}
static void onBindCB(const std::string& name, bool press,
const std::string& cmd, void* userData)
{
std::string& result = *static_cast<std::string*>(userData);
result += name;
result += (press ? " down " : " up ");
result += cmd;
result += "\n";
}
static std::string cmdBind(const std::string&,
const CommandManager::ArgList& args, bool*)
{
if (args.size() == 0) {
std::string result;
KEYMGR.iterate(&onBindCB, &result);
return result;
} else if (args.size() < 3) {
return "usage: bind <button-name> {up|down} <command> <args>...";
}
BzfKeyEvent key;
if (!KEYMGR.stringToKeyEvent(args[0], key))
return std::string("bind error: unknown button name \"") + args[0] + "\"";
bool down;
if (args[1] == "up")
down = false;
else if (args[1] == "down")
down = true;
else
return std::string("bind error: illegal state \"") + args[1] + "\"";
std::string cmd = args[2];
for (unsigned int i = 3; i < args.size(); ++i) {
cmd += " ";
cmd += args[i];
}
// ignore attempts to modify Esc. we reserve that for the menu
if (key.ascii != 27)
KEYMGR.bind(key, down, cmd);
return std::string();
}
static std::string cmdUnbind(const std::string&,
const CommandManager::ArgList& args, bool*)
{
if (args.size() != 2)
return "usage: unbind <button-name> {up|down}";
BzfKeyEvent key_event;
if (!KEYMGR.stringToKeyEvent(args[0], key_event))
return std::string("bind error: unknown button name \"") + args[0] + "\"";
bool down;
if (args[1] == "up")
down = false;
else if (args[1] == "down")
down = true;
else
return std::string("bind error: illegal state \"") + args[1] + "\"";
if (key_event.ascii != 27)
KEYMGR.unbind(key_event, down);
return std::string();
}
static std::string cmdToggle(const std::string&,
const CommandManager::ArgList& args, bool*)
{
if (args.size() != 1)
return "usage: toggle <name>";
const std::string& name = args[0];
if (BZDB.isTrue(name))
BZDB.set(name, "0", StateDatabase::User);
else
BZDB.set(name, "1", StateDatabase::User);
return std::string();
}
static std::string cmdMult(const std::string&, const CommandManager::ArgList& args, bool*)
{
if (args.size() != 2)
return "usage: mult <name> <value>";
float value;
if (sscanf(BZDB.get(args[0]).c_str(), "%f", &value) != 1)
value = 0.0;
float amount;
if (sscanf(args[1].c_str(), "%f", &amount) != 1)
amount = 1.0;
value *= amount;
BZDB.set(args[0], TextUtils::format("%f", value), StateDatabase::User);
return std::string();
}
//
// command name to function mapping
//
const struct CommandsItem commands[] = {
{ "quit", &cmdQuit, "quit: quit the program" },
{ "help", &cmdHelp, "help [<command-name>]: get help on a command or a list of commands" },
{ "print", &cmdPrint, "print ...: print arguments; $name is replaced by value of variable \"name\"" },
{ "set", &cmdSet, "set [<name> <value>]: set a variable or print all set variables" },
{ "unset", &cmdUnset, "unset <name>: unset a variable" },
{ "bind", &cmdBind, "bind <button-name> {up|down} <command> <args>...: bind a key" },
{ "unbind", &cmdUnbind, "unbind <button-name> {up|down}: unbind a key" },
{ "toggle", &cmdToggle, "toggle <name>: toggle truth value of a variable" },
{ "mult", &cmdMult, "mult <name> <value>: multiply a variable by an amount" }
};
// FIXME -- may want a cmd to cycle through a list
//
// CommandsStandard
//
void CommandsStandard::add()
{
unsigned int i;
for (i = 0; i < countof(commands); ++i)
CMDMGR.add(commands[i].name, commands[i].func, commands[i].help);
}
void CommandsStandard::remove()
{
unsigned int i;
for (i = 0; i < countof(commands); ++i)
CMDMGR.remove(commands[i].name);
}
void CommandsStandard::quit()
{
quitFlag = true;
}
bool CommandsStandard::isQuit()
{
return quitFlag;
}
// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>- added "add" command for key bindings - added ability to set values for the "toggle" key binding command<commit_after>/* bzflag
* Copyright (c) 1993 - 2006 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named LICENSE that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
/* interface header */
#include "CommandsStandard.h"
/* system implementation headers */
#include <stdio.h>
#include <ctype.h>
#include <string>
/* common implementation headers */
#include "CommandManager.h"
#include "StateDatabase.h"
#include "KeyManager.h"
#include "TextUtils.h"
static bool quitFlag = false;
//
// command handlers
//
static std::string cmdQuit(const std::string&,
const CommandManager::ArgList&, bool*)
{
CommandsStandard::quit();
return std::string();
}
static void onHelpCB(const std::string& name,
void* userData)
{
std::string& result = *static_cast<std::string*>(userData);
result += name;
result += "\n";
}
static std::string cmdHelp(const std::string&,
const CommandManager::ArgList& args, bool*)
{
switch (args.size()) {
case 0: {
std::string result;
CMDMGR.iterate(&onHelpCB, &result);
return result;
}
case 1:
return CMDMGR.getHelp(args[0]);
default:
return "usage: help [<command-name>]";
}
}
static std::string cmdPrint(const std::string&,
const CommandManager::ArgList& args, bool*)
{
// merge all arguments into one string
std::string arg;
const unsigned int n = (int)args.size();
if (n > 0)
arg = args[0];
for (unsigned int i = 1; i < n; ++i) {
arg += " ";
arg += args[i];
}
// interpolate variables
std::string result;
const char* scan = arg.c_str();
while (*scan != '\0') {
if (*scan != '$') {
result.append(scan, 1);
++scan;
} else {
// could be a variable
++scan;
if (*scan == '$') {
// no, it's just $$ which maps to $
result += "$";
++scan;
} else if (*scan != '{') {
// parse variable name
const char* name = scan;
while (*scan != '\0' && !isspace(*scan))
++scan;
// look up variable
result += BZDB.get(std::string(name, scan - name));
} else {
// parse "quoted" variable name
const char* name = ++scan;
while (*scan != '\0' && *scan != '}')
++scan;
if (*scan != '\0') {
// look up variable
result += BZDB.get(std::string(name, scan - name));
// skip }
++scan;
}
}
}
}
std::cout << "printing \"" << result << "\"" << std::endl;
return result;
}
static void onSetCB(const std::string& name,
void* userData)
{
// don't show names starting with _
std::string& result = *static_cast<std::string*>(userData);
if (!name.empty() && name.c_str()[0] != '_') {
result += name;
result += " = ";
result += BZDB.get(name);
result += "\n";
}
}
static std::string cmdSet(const std::string&,
const CommandManager::ArgList& args, bool* error)
{
if(error) *error = false;
switch (args.size()) {
case 0:
{
// print out all values that are set
std::string result;
BZDB.iterate(&onSetCB, &result);
return result;
}
case 1:
{
// the string was set to nothing, so just print value
if (BZDB.isSet(args[0])) {
return args[0] + " is " + BZDB.get(args[0]);
} else {
if(error) *error = true;
return "variable " + args[0] + " does not exist";
}
}
case 2:
{
// set variable to value
BZDB.set(args[0], args[1], StateDatabase::User);
return std::string();
}
default:
{
if(error) *error = true;
return "usage: set <name> [<value>]";
}
}
}
static std::string cmdUnset(const std::string&,
const CommandManager::ArgList& args, bool*)
{
if (args.size() != 1)
return "usage: unset <name>";
BZDB.unset(args[0], StateDatabase::User);
return std::string();
}
static void onBindCB(const std::string& name, bool press,
const std::string& cmd, void* userData)
{
std::string& result = *static_cast<std::string*>(userData);
result += name;
result += (press ? " down " : " up ");
result += cmd;
result += "\n";
}
static std::string cmdBind(const std::string&,
const CommandManager::ArgList& args, bool*)
{
if (args.size() == 0) {
std::string result;
KEYMGR.iterate(&onBindCB, &result);
return result;
} else if (args.size() < 3) {
return "usage: bind <button-name> {up|down} <command> <args>...";
}
BzfKeyEvent key;
if (!KEYMGR.stringToKeyEvent(args[0], key))
return std::string("bind error: unknown button name \"") + args[0] + "\"";
bool down;
if (args[1] == "up")
down = false;
else if (args[1] == "down")
down = true;
else
return std::string("bind error: illegal state \"") + args[1] + "\"";
std::string cmd = args[2];
for (unsigned int i = 3; i < args.size(); ++i) {
cmd += " ";
cmd += args[i];
}
// ignore attempts to modify Esc. we reserve that for the menu
if (key.ascii != 27)
KEYMGR.bind(key, down, cmd);
return std::string();
}
static std::string cmdUnbind(const std::string&,
const CommandManager::ArgList& args, bool*)
{
if (args.size() != 2)
return "usage: unbind <button-name> {up|down}";
BzfKeyEvent key_event;
if (!KEYMGR.stringToKeyEvent(args[0], key_event))
return std::string("bind error: unknown button name \"") + args[0] + "\"";
bool down;
if (args[1] == "up")
down = false;
else if (args[1] == "down")
down = true;
else
return std::string("bind error: illegal state \"") + args[1] + "\"";
if (key_event.ascii != 27)
KEYMGR.unbind(key_event, down);
return std::string();
}
static std::string cmdToggle(const std::string&,
const CommandManager::ArgList& args, bool*)
{
if ((args.size() < 1) || (args.size() > 3)) {
return "usage: toggle <name> [first [second]]";
}
const std::string& name = args[0];
if (args.size() == 1) {
BZDB.set(name, BZDB.isTrue(name) ? "0" : "1");
} else if (args.size() == 2) {
BZDB.set(name, BZDB.isTrue(name) ? "0" : args[1]);
} else {
BZDB.set(name, (BZDB.get(name) == args[1]) ? args[2] : args[1]);
}
return std::string();
}
static std::string cmdMult(const std::string&, const CommandManager::ArgList& args, bool*)
{
if (args.size() != 2)
return "usage: mult <name> <value>";
float value;
if (sscanf(BZDB.get(args[0]).c_str(), "%f", &value) != 1)
value = 0.0;
float amount;
if (sscanf(args[1].c_str(), "%f", &amount) != 1)
amount = 1.0;
value *= amount;
BZDB.set(args[0], TextUtils::format("%f", value), StateDatabase::User);
return std::string();
}
static std::string cmdAdd(const std::string&, const CommandManager::ArgList& args, bool*)
{
if (args.size() != 2) {
return "usage: add <name> <value>";
}
float value;
if (sscanf(BZDB.get(args[0]).c_str(), "%f", &value) != 1) {
value = 0.0f;
}
float amount;
if (sscanf(args[1].c_str(), "%f", &amount) != 1) {
amount = 0.0f;
}
value += amount;
BZDB.set(args[0], TextUtils::format("%f", value), StateDatabase::User);
return std::string();
}
//
// command name to function mapping
//
const struct CommandsItem commands[] = {
{ "quit", &cmdQuit, "quit: quit the program" },
{ "help", &cmdHelp, "help [<command-name>]: get help on a command or a list of commands" },
{ "print", &cmdPrint, "print ...: print arguments; $name is replaced by value of variable \"name\"" },
{ "set", &cmdSet, "set [<name> <value>]: set a variable or print all set variables" },
{ "unset", &cmdUnset, "unset <name>: unset a variable" },
{ "bind", &cmdBind, "bind <button-name> {up|down} <command> <args>...: bind a key" },
{ "unbind", &cmdUnbind, "unbind <button-name> {up|down}: unbind a key" },
{ "toggle", &cmdToggle, "toggle <name> [first [second]]: toggle value of a variable" },
{ "mult", &cmdMult, "mult <name> <value>: multiply a variable by an amount" },
{ "add", &cmdAdd, "add <name> <value>: add an amount to a variable" }
};
// FIXME -- may want a cmd to cycle through a list
//
// CommandsStandard
//
void CommandsStandard::add()
{
unsigned int i;
for (i = 0; i < countof(commands); ++i)
CMDMGR.add(commands[i].name, commands[i].func, commands[i].help);
}
void CommandsStandard::remove()
{
unsigned int i;
for (i = 0; i < countof(commands); ++i)
CMDMGR.remove(commands[i].name);
}
void CommandsStandard::quit()
{
quitFlag = true;
}
bool CommandsStandard::isQuit()
{
return quitFlag;
}
// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|>
|
<commit_before><commit_msg>Start dynification tests<commit_after><|endoftext|>
|
<commit_before>#include <boost/thread/mutex.hpp>
#include "gt/model/common.hpp"
namespace GT {
namespace Model {
////////////////////////////////////////////////////////////////////////////////
boost::mutex nullFactoryMutex;
////////////////////////////////////////////////////////////////////////////////
// class NullFactory {
NullFactory* volatile NullFactory::instance = 0;
// public:
NullFactory& NullFactory::getInstance() {
// Singleton implemented according to:
// "C++ and the Perils of Double-Checked Locking"
// but without executing constructor inside getInstance() method
// since it's an eyesore.
if (!instance) {
boost::mutex::scoped_lock lock(nullFactoryMutex);
if (!instance) {
NullFactory* volatile tmp = new NullFactory();
instance = tmp;
}
}
return *instance;
}
IdentifierPtr NullFactory::createIdentifier() {
return IdentifierPtr(new Identifier("NullIdentifier"));
}
MessagePtr NullFactory::createMessage() {
return MessagePtr(new Identifier("NullMessage"));
}
NumberPtr NullFactory::createNumber() {
return NumberPtr(new Number(0));
}
PlayerPtr NullFactory::createPlayer() {
return PlayerPtr(new NullPlayer());
}
ResultPtr NullFactory::createResult() {
return ResultPtr(new NullResult());
}
// private:
NullFactory::NullFactory() {}
// }
////////////////////////////////////////////////////////////////////////////////
} /* END namespace Model */
} /* END namespace GT */
<commit_msg>* Added lacking implementation of createIdentifiers() method.<commit_after>#include <boost/thread/mutex.hpp>
#include "gt/model/common.hpp"
namespace GT {
namespace Model {
////////////////////////////////////////////////////////////////////////////////
boost::mutex nullFactoryMutex;
////////////////////////////////////////////////////////////////////////////////
// class NullFactory {
NullFactory* volatile NullFactory::instance = 0;
// public:
NullFactory& NullFactory::getInstance() {
// Singleton implemented according to:
// "C++ and the Perils of Double-Checked Locking"
// but without executing constructor inside getInstance() method
// since it's an eyesore.
if (!instance) {
boost::mutex::scoped_lock lock(nullFactoryMutex);
if (!instance) {
NullFactory* volatile tmp = new NullFactory();
instance = tmp;
}
}
return *instance;
}
IdentifierPtr NullFactory::createIdentifier() {
return IdentifierPtr(new Identifier("NullIdentifier"));
}
IdentifiersPtr NullFactory::createIdentifiers() {
return IdentifiersPtr(new Identifiers());
}
MessagePtr NullFactory::createMessage() {
return MessagePtr(new Identifier("NullMessage"));
}
NumberPtr NullFactory::createNumber() {
return NumberPtr(new Number(0));
}
PlayerPtr NullFactory::createPlayer() {
return PlayerPtr(new NullPlayer());
}
ResultPtr NullFactory::createResult() {
return ResultPtr(new NullResult());
}
// private:
NullFactory::NullFactory() {}
// }
////////////////////////////////////////////////////////////////////////////////
} /* END namespace Model */
} /* END namespace GT */
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2008 Bertjan Broeksema <b.broeksema@kdemail.net>
Copyright (c) 2008 Volker Krause <vkrause@kde.org>
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 "singlefileresourcebase.h"
#include <akonadi/changerecorder.h>
#include <akonadi/entitydisplayattribute.h>
#include <akonadi/itemfetchscope.h>
#include <kio/job.h>
#include <kio/jobuidelegate.h>
#include <KDebug>
#include <KDirWatch>
#include <KLocale>
#include <KStandardDirs>
#include <QtCore/QDir>
using namespace Akonadi;
SingleFileResourceBase::SingleFileResourceBase( const QString & id )
: ResourceBase( id ), mDownloadJob( 0 ), mUploadJob( 0 )
{
connect( &mDirtyTimer, SIGNAL( timeout() ), SLOT( writeFile() ) );
mDirtyTimer.setSingleShot( true );
connect( this, SIGNAL( reloadConfiguration() ), SLOT( reloadFile() ) );
QTimer::singleShot( 0, this, SLOT( readFile() ) );
changeRecorder()->itemFetchScope().fetchFullPayload();
changeRecorder()->fetchCollection( true );
connect( KDirWatch::self(), SIGNAL( dirty( QString ) ), SLOT( fileChanged( QString ) ) );
}
QString SingleFileResourceBase::cacheFile() const
{
return KStandardDirs::locateLocal( "cache", "akonadi/" + identifier() );
}
void SingleFileResourceBase::setSupportedMimetypes( const QStringList & mimeTypes, const QString &icon )
{
mSupportedMimetypes = mimeTypes;
mCollectionIcon = icon;
}
void SingleFileResourceBase::collectionChanged( const Akonadi::Collection & collection )
{
QString newName = collection.name();
if ( collection.hasAttribute<EntityDisplayAttribute>() ) {
EntityDisplayAttribute *attr = collection.attribute<EntityDisplayAttribute>();
if ( !attr->displayName().isEmpty() )
newName = attr->displayName();
}
if ( newName != name() )
setName( newName );
changeCommitted( collection );
}
void SingleFileResourceBase::reloadFile()
{
// Update the network setting.
setNeedsNetwork( !mCurrentUrl.isEmpty() && !mCurrentUrl.isLocalFile() );
// if we have something loaded already, make sure we write that back in case
// the settings changed
if ( !mCurrentUrl.isEmpty() )
writeFile();
readFile();
synchronize();
}
void SingleFileResourceBase::handleProgress( KJob *, unsigned long pct )
{
emit percent( pct );
}
void SingleFileResourceBase::fileChanged( const QString & fileName )
{
if ( fileName != mCurrentUrl.path() )
return;
// handle conflicts
if ( mDirtyTimer.isActive() && !mCurrentUrl.isEmpty() ) {
const KUrl prevUrl = mCurrentUrl;
int i = 0;
QString lostFoundFileName;
do {
lostFoundFileName = KStandardDirs::locateLocal( "data", identifier() + QDir::separator()
+ prevUrl.fileName() + "-" + QString::number( ++i ) );
} while ( KStandardDirs::exists( lostFoundFileName ) );
mCurrentUrl = KUrl( lostFoundFileName );
writeFile();
emit warning( i18n( "The file '%1' was changed on disk while there were still pending changes in Akonadi. "
"To avoid dataloss, a backup of the internal changes has been created at '%2'.",
prevUrl.prettyUrl(), mCurrentUrl.prettyUrl() ) );
mCurrentUrl = prevUrl;
}
readFile();
synchronize();
}
void SingleFileResourceBase::slotDownloadJobResult( KJob *job )
{
if ( job->error() && job->error() != KIO::ERR_DOES_NOT_EXIST ) {
emit status( Broken, i18n( "Could not load file '%1'.", mCurrentUrl.prettyUrl() ) );
} else {
readFromFile( KUrl( cacheFile() ).url() );
}
mDownloadJob = 0;
KGlobal::deref();
emit status( Idle, i18nc( "@info:status", "Ready" ) );
}
void SingleFileResourceBase::slotUploadJobResult( KJob *job )
{
if ( job->error() ) {
emit status( Broken, i18n( "Could not save file '%1'.", mCurrentUrl.prettyUrl() ) );
}
mUploadJob = 0;
KGlobal::deref();
emit status( Idle, i18nc( "@info:status", "Ready" ) );
}
#include "singlefileresourcebase.moc"
<commit_msg>Also watch "created" signals, since modifications using KSaveFile or similar techniques result in delete+create<commit_after>/*
Copyright (c) 2008 Bertjan Broeksema <b.broeksema@kdemail.net>
Copyright (c) 2008 Volker Krause <vkrause@kde.org>
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 "singlefileresourcebase.h"
#include <akonadi/changerecorder.h>
#include <akonadi/entitydisplayattribute.h>
#include <akonadi/itemfetchscope.h>
#include <kio/job.h>
#include <kio/jobuidelegate.h>
#include <KDebug>
#include <KDirWatch>
#include <KLocale>
#include <KStandardDirs>
#include <QtCore/QDir>
using namespace Akonadi;
SingleFileResourceBase::SingleFileResourceBase( const QString & id )
: ResourceBase( id ), mDownloadJob( 0 ), mUploadJob( 0 )
{
connect( &mDirtyTimer, SIGNAL( timeout() ), SLOT( writeFile() ) );
mDirtyTimer.setSingleShot( true );
connect( this, SIGNAL( reloadConfiguration() ), SLOT( reloadFile() ) );
QTimer::singleShot( 0, this, SLOT( readFile() ) );
changeRecorder()->itemFetchScope().fetchFullPayload();
changeRecorder()->fetchCollection( true );
connect( KDirWatch::self(), SIGNAL( dirty( QString ) ), SLOT( fileChanged( QString ) ) );
connect( KDirWatch::self(), SIGNAL( created( QString ) ), SLOT( fileChanged( QString ) ) );
}
QString SingleFileResourceBase::cacheFile() const
{
return KStandardDirs::locateLocal( "cache", "akonadi/" + identifier() );
}
void SingleFileResourceBase::setSupportedMimetypes( const QStringList & mimeTypes, const QString &icon )
{
mSupportedMimetypes = mimeTypes;
mCollectionIcon = icon;
}
void SingleFileResourceBase::collectionChanged( const Akonadi::Collection & collection )
{
QString newName = collection.name();
if ( collection.hasAttribute<EntityDisplayAttribute>() ) {
EntityDisplayAttribute *attr = collection.attribute<EntityDisplayAttribute>();
if ( !attr->displayName().isEmpty() )
newName = attr->displayName();
}
if ( newName != name() )
setName( newName );
changeCommitted( collection );
}
void SingleFileResourceBase::reloadFile()
{
// Update the network setting.
setNeedsNetwork( !mCurrentUrl.isEmpty() && !mCurrentUrl.isLocalFile() );
// if we have something loaded already, make sure we write that back in case
// the settings changed
if ( !mCurrentUrl.isEmpty() )
writeFile();
readFile();
synchronize();
}
void SingleFileResourceBase::handleProgress( KJob *, unsigned long pct )
{
emit percent( pct );
}
void SingleFileResourceBase::fileChanged( const QString & fileName )
{
if ( fileName != mCurrentUrl.path() )
return;
// handle conflicts
if ( mDirtyTimer.isActive() && !mCurrentUrl.isEmpty() ) {
const KUrl prevUrl = mCurrentUrl;
int i = 0;
QString lostFoundFileName;
do {
lostFoundFileName = KStandardDirs::locateLocal( "data", identifier() + QDir::separator()
+ prevUrl.fileName() + "-" + QString::number( ++i ) );
} while ( KStandardDirs::exists( lostFoundFileName ) );
mCurrentUrl = KUrl( lostFoundFileName );
writeFile();
emit warning( i18n( "The file '%1' was changed on disk while there were still pending changes in Akonadi. "
"To avoid dataloss, a backup of the internal changes has been created at '%2'.",
prevUrl.prettyUrl(), mCurrentUrl.prettyUrl() ) );
mCurrentUrl = prevUrl;
}
readFile();
synchronize();
}
void SingleFileResourceBase::slotDownloadJobResult( KJob *job )
{
if ( job->error() && job->error() != KIO::ERR_DOES_NOT_EXIST ) {
emit status( Broken, i18n( "Could not load file '%1'.", mCurrentUrl.prettyUrl() ) );
} else {
readFromFile( KUrl( cacheFile() ).url() );
}
mDownloadJob = 0;
KGlobal::deref();
emit status( Idle, i18nc( "@info:status", "Ready" ) );
}
void SingleFileResourceBase::slotUploadJobResult( KJob *job )
{
if ( job->error() ) {
emit status( Broken, i18n( "Could not save file '%1'.", mCurrentUrl.prettyUrl() ) );
}
mUploadJob = 0;
KGlobal::deref();
emit status( Idle, i18nc( "@info:status", "Ready" ) );
}
#include "singlefileresourcebase.moc"
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2011. Philipp Wagner <bytefish[at]gmx[dot]de>.
* Released to public domain under terms of the BSD Simplified license.
*
* 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 organization nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* See <http://www.opensource.org/licenses/bsd-license>
*/
#include "opencv2/core/core.hpp"
#include <opencv2/face.hpp>
#include "opencv2/highgui/highgui.hpp"
#include <iostream>
#include <fstream>
#include <sstream>
using namespace cv;
using namespace std;
static void read_csv(const string& filename, vector<Mat>& images, vector<int>& labels, char separator = ';') {
std::ifstream file(filename.c_str(), ifstream::in);
if (!file) {
string error_message = "No valid input file was given, please check the given filename.";
CV_Error(CV_StsBadArg, error_message);
}
string line, path, classlabel;
while (getline(file, line)) {
stringstream liness(line);
getline(liness, path, separator);
getline(liness, classlabel);
if(!path.empty() && !classlabel.empty()) {
images.push_back(imread(path, 0));
labels.push_back(atoi(classlabel.c_str()));
}
}
}
int main(int argc, const char *argv[]) {
// Check for valid command line arguments, print usage
// if no arguments were given.
if (argc != 2) {
cout << "usage: " << argv[0] << " <csv.ext>" << endl;
exit(1);
}
// Get the path to your CSV.
string fn_csv = string(argv[1]);
// These vectors hold the images and corresponding labels.
vector<Mat> images;
vector<int> labels;
// Read in the data. This can fail if no valid
// input filename is given.
try {
read_csv(fn_csv, images, labels);
} catch (cv::Exception& e) {
cerr << "Error opening file \"" << fn_csv << "\". Reason: " << e.msg << endl;
// nothing more we can do
exit(1);
}
// Quit if there are not enough images for this demo.
if(images.size() <= 1) {
string error_message = "This demo needs at least 2 images to work. Please add more images to your data set!";
CV_Error(CV_StsError, error_message);
}
// Get the height from the first image. We'll need this
// later in code to reshape the images to their original
// size:
int height = images[0].rows;
// The following lines simply get the last images from
// your dataset and remove it from the vector. This is
// done, so that the training data (which we learn the
// cv::FaceRecognizer on) and the test data we test
// the model with, do not overlap.
Mat testSample = images[images.size() - 1];
int testLabel = labels[labels.size() - 1];
images.pop_back();
labels.pop_back();
// The following lines create an LBPH model for
// face recognition and train it with the images and
// labels read from the given CSV file.
//
// The LBPHFaceRecognizer uses Extended Local Binary Patterns
// (it's probably configurable with other operators at a later
// point), and has the following default values
//
// radius = 1
// neighbors = 8
// grid_x = 8
// grid_y = 8
//
// So if you want a LBPH FaceRecognizer using a radius of
// 2 and 16 neighbors, call the factory method with:
//
// cv::createLBPHFaceRecognizer(2, 16);
//
// And if you want a threshold (e.g. 123.0) call it with its default values:
//
// cv::createLBPHFaceRecognizer(1,8,8,8,123.0)
//
Ptr<FaceRecognizer> model = createLBPHFaceRecognizer();
model->train(images, labels);
// The following line predicts the label of a given
// test image:
int predictedLabel = model->predict(testSample);
//
// To get the confidence of a prediction call the model with:
//
// int predictedLabel = -1;
// double confidence = 0.0;
// model->predict(testSample, predictedLabel, confidence);
//
string result_message = format("Predicted class = %d / Actual class = %d.", predictedLabel, testLabel);
cout << result_message << endl;
// Sometimes you'll need to get/set internal model data,
// which isn't exposed by the public cv::FaceRecognizer.
// Since each cv::FaceRecognizer is derived from a
// cv::Algorithm, you can query the data.
//
// First we'll use it to set the threshold of the FaceRecognizer
// to 0.0 without retraining the model. This can be useful if
// you are evaluating the model:
//
model->set("threshold", 0.0);
// Now the threshold of this model is set to 0.0. A prediction
// now returns -1, as it's impossible to have a distance below
// it
predictedLabel = model->predict(testSample);
cout << "Predicted class = " << predictedLabel << endl;
// Show some informations about the model, as there's no cool
// Model data to display as in Eigenfaces/Fisherfaces.
// Due to efficiency reasons the LBP images are not stored
// within the model:
cout << "Model Information:" << endl;
string model_info = format("\tLBPH(radius=%i, neighbors=%i, grid_x=%i, grid_y=%i, threshold=%.2f)",
model->getInt("radius"),
model->getInt("neighbors"),
model->getInt("grid_x"),
model->getInt("grid_y"),
model->getDouble("threshold"));
cout << model_info << endl;
// We could get the histograms for example:
vector<Mat> histograms = model->getMatVector("histograms");
// But should I really visualize it? Probably the length is interesting:
cout << "Size of the histograms: " << histograms[0].total() << endl;
return 0;
}
<commit_msg>After fixing local libraries of OpenCV and downloading the latest version of the Facemapper tutorial it finally works<commit_after>/*
* Copyright (c) 2011. Philipp Wagner <bytefish[at]gmx[dot]de>.
* Released to public domain under terms of the BSD Simplified license.
*
* 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 organization nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* See <http://www.opensource.org/licenses/bsd-license>
*/
#include "opencv2/core.hpp"
#include "opencv2/face.hpp"
#include "opencv2/highgui.hpp"
#include <iostream>
#include <fstream>
#include <sstream>
using namespace cv;
using namespace cv::face;
using namespace std;
static void read_csv(const string& filename, vector<Mat>& images, vector<int>& labels, char separator = ';') {
std::ifstream file(filename.c_str(), ifstream::in);
if (!file) {
string error_message = "No valid input file was given, please check the given filename.";
CV_Error(Error::StsBadArg, error_message);
}
string line, path, classlabel;
while (getline(file, line)) {
stringstream liness(line);
getline(liness, path, separator);
getline(liness, classlabel);
if(!path.empty() && !classlabel.empty()) {
images.push_back(imread(path, 0));
labels.push_back(atoi(classlabel.c_str()));
}
}
}
int main(int argc, const char *argv[]) {
// Check for valid command line arguments, print usage
// if no arguments were given.
if (argc != 2) {
cout << "usage: " << argv[0] << " <csv.ext>" << endl;
exit(1);
}
// Get the path to your CSV.
string fn_csv = string(argv[1]);
// These vectors hold the images and corresponding labels.
vector<Mat> images;
vector<int> labels;
// Read in the data. This can fail if no valid
// input filename is given.
try {
read_csv(fn_csv, images, labels);
} catch (cv::Exception& e) {
cerr << "Error opening file \"" << fn_csv << "\". Reason: " << e.msg << endl;
// nothing more we can do
exit(1);
}
// Quit if there are not enough images for this demo.
if(images.size() <= 1) {
string error_message = "This demo needs at least 2 images to work. Please add more images to your data set!";
CV_Error(Error::StsError, error_message);
}
// The following lines simply get the last images from
// your dataset and remove it from the vector. This is
// done, so that the training data (which we learn the
// cv::LBPHFaceRecognizer on) and the test data we test
// the model with, do not overlap.
Mat testSample = images[images.size() - 1];
int testLabel = labels[labels.size() - 1];
images.pop_back();
labels.pop_back();
// The following lines create an LBPH model for
// face recognition and train it with the images and
// labels read from the given CSV file.
//
// The LBPHFaceRecognizer uses Extended Local Binary Patterns
// (it's probably configurable with other operators at a later
// point), and has the following default values
//
// radius = 1
// neighbors = 8
// grid_x = 8
// grid_y = 8
//
// So if you want a LBPH FaceRecognizer using a radius of
// 2 and 16 neighbors, call the factory method with:
//
// cv::createLBPHFaceRecognizer(2, 16);
//
// And if you want a threshold (e.g. 123.0) call it with its default values:
//
// cv::createLBPHFaceRecognizer(1,8,8,8,123.0)
//
Ptr<LBPHFaceRecognizer> model = createLBPHFaceRecognizer();
model->train(images, labels);
// The following line predicts the label of a given
// test image:
int predictedLabel = model->predict(testSample);
//
// To get the confidence of a prediction call the model with:
//
// int predictedLabel = -1;
// double confidence = 0.0;
// model->predict(testSample, predictedLabel, confidence);
//
string result_message = format("Predicted class = %d / Actual class = %d.", predictedLabel, testLabel);
cout << result_message << endl;
// First we'll use it to set the threshold of the LBPHFaceRecognizer
// to 0.0 without retraining the model. This can be useful if
// you are evaluating the model:
//
model->setThreshold(0.0);
// Now the threshold of this model is set to 0.0. A prediction
// now returns -1, as it's impossible to have a distance below
// it
predictedLabel = model->predict(testSample);
cout << "Predicted class = " << predictedLabel << endl;
// Show some informations about the model, as there's no cool
// Model data to display as in Eigenfaces/Fisherfaces.
// Due to efficiency reasons the LBP images are not stored
// within the model:
cout << "Model Information:" << endl;
string model_info = format("\tLBPH(radius=%i, neighbors=%i, grid_x=%i, grid_y=%i, threshold=%.2f)",
model->getRadius(),
model->getNeighbors(),
model->getGridX(),
model->getGridY(),
model->getThreshold());
cout << model_info << endl;
// We could get the histograms for example:
vector<Mat> histograms = model->getHistograms();
// But should I really visualize it? Probably the length is interesting:
cout << "Size of the histograms: " << histograms[0].total() << endl;
return 0;
}
<|endoftext|>
|
<commit_before>//
// Copyright (c) .NET Foundation and Contributors
// See LICENSE file in the project root for full license information.
//
#include "nf_rt_native.h"
HRESULT Library_nf_rt_native_System_Environment::get_TickCount64___STATIC__I8(CLR_RT_StackFrame &stack)
{
NATIVE_PROFILE_CLR_CORE();
NANOCLR_HEADER();
CLR_RT_HeapBlock &ref = stack.PushValue();
// get pointer to object pushed to the stack
// and set with value from EE
ref.Dereference()->NumericByRef().s8 = CLR_RT_ExecutionEngine::GetUptime();
NANOCLR_NOCLEANUP_NOLABEL();
}
<commit_msg>Fix Environment.TickCount64 (#2244)<commit_after>//
// Copyright (c) .NET Foundation and Contributors
// See LICENSE file in the project root for full license information.
//
#include "nf_rt_native.h"
HRESULT Library_nf_rt_native_System_Environment::get_TickCount64___STATIC__I8(CLR_RT_StackFrame &stack)
{
NATIVE_PROFILE_CLR_CORE();
NANOCLR_HEADER();
int64_t ticksValue = CLR_RT_ExecutionEngine::GetUptime();
stack.SetResult_I8(ticksValue);
NANOCLR_NOCLEANUP_NOLABEL();
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <map>
#include <memory>
#include <string>
#include <time.h>
#include <vector>
#include "aggregate_bandwidth.cpp"
#include "aggregate_bandwidth.hpp"
#include "bytes_object.hpp"
#include "log_results.hpp"
#include <derecho/conf/conf.hpp>
#include <derecho/core/derecho.hpp>
#include <derecho/mutils-serialization/SerializationSupport.hpp>
#include <derecho/persistent/Persistent.hpp>
using std::endl;
using test::Bytes;
/**
* RPC Object with a single function that accepts a string
*/
class TestObject {
public:
void fun(const std::string& words) {
}
void bytes_fun(const Bytes& bytes) {
}
bool finishing_call(int x) {
return true;
}
REGISTER_RPC_FUNCTIONS(TestObject, fun, bytes_fun, finishing_call);
};
struct exp_result {
int num_nodes;
long long unsigned int max_msg_size;
unsigned int window_size;
int count;
double avg_msec;
double avg_gbps;
double avg_ops;
void print(std::ofstream& fout) {
fout << num_nodes << " "
<< max_msg_size << " " << window_size << " "
<< count << " "
<< avg_msec << " " << avg_gbps << " "
<< avg_ops << endl;
}
};
#define DEFAULT_PROC_NAME "typed_bw_test"
int main(int argc, char* argv[]) {
int dashdash_pos = argc - 1;
while(dashdash_pos > 0) {
if(strcmp(argv[dashdash_pos], "--") == 0) {
break;
}
dashdash_pos--;
}
if((argc - dashdash_pos) < 3) {
std::cout << "Invalid command line arguments." << std::endl;
std::cout << "USAGE: " << argv[0] << " [ derecho-config-list -- ] <num_of_nodes> <count> [proc_name]" << std::endl;
std::cout << "Note: proc_name sets the process's name as displayed in ps and pkill commands, default is " DEFAULT_PROC_NAME << std::endl;
return -1;
}
derecho::Conf::initialize(argc, argv);
int num_of_nodes = std::stoi(argv[dashdash_pos + 1]);
uint64_t max_msg_size = derecho::getConfUInt64(CONF_SUBGROUP_DEFAULT_MAX_PAYLOAD_SIZE);
int count = std::stoi(argv[dashdash_pos + 2]);
if(dashdash_pos + 3 < argc) {
pthread_setname_np(pthread_self(), argv[dashdash_pos + 3]);
} else {
pthread_setname_np(pthread_self(), DEFAULT_PROC_NAME);
}
derecho::SubgroupInfo subgroup_info{[num_of_nodes](
const std::vector<std::type_index>& subgroup_type_order,
const std::unique_ptr<derecho::View>& prev_view, derecho::View& curr_view) {
if(curr_view.num_members < num_of_nodes) {
std::cout << "not enough members yet:" << curr_view.num_members << " < " << num_of_nodes << std::endl;
throw derecho::subgroup_provisioning_exception();
}
derecho::subgroup_shard_layout_t subgroup_layout(1);
std::vector<uint32_t> members(num_of_nodes);
for(int i = 0; i < num_of_nodes; i++) {
members[i] = i;
}
subgroup_layout[0].emplace_back(curr_view.make_subview(members));
curr_view.next_unassigned_rank = std::max(curr_view.next_unassigned_rank, num_of_nodes);
derecho::subgroup_allocation_map_t subgroup_allocation;
subgroup_allocation.emplace(std::type_index(typeid(TestObject)), std::move(subgroup_layout));
return subgroup_allocation;
}};
auto ba_factory = [](persistent::PersistentRegistry*, derecho::subgroup_id_t) { return std::make_unique<TestObject>(); };
derecho::Group<TestObject> group({}, subgroup_info, {}, std::vector<derecho::view_upcall_t>{}, ba_factory);
std::cout << "Finished constructing/joining Group" << std::endl;
derecho::Replicated<TestObject>& handle = group.get_subgroup<TestObject>();
//std::string str_1k(max_msg_size, 'x');
char* bbuf = (char*)malloc(max_msg_size);
bzero(bbuf, max_msg_size);
Bytes bytes(bbuf, max_msg_size);
struct timespec t1, t2;
clock_gettime(CLOCK_REALTIME, &t1);
for(int i = 0; i < count; i++) {
//handle.ordered_send<RPC_NAME(fun)>(str_1k);
handle.ordered_send<RPC_NAME(bytes_fun)>(bytes);
}
auto members_order = group.get_members();
uint32_t node_rank = group.get_my_rank();
if(node_rank == 0) {
derecho::rpc::QueryResults<bool> results = handle.ordered_send<RPC_NAME(finishing_call)>(0);
std::cout << "waiting for response..." << std::endl;
#pragma GCC diagnostic ignored "-Wunused-variable"
decltype(results)::ReplyMap& replies = results.get();
#pragma GCC diagnostic pop
}
clock_gettime(CLOCK_REALTIME, &t2);
free(bbuf);
int64_t nsec = ((int64_t)t2.tv_sec - t1.tv_sec) * 1000000000 + t2.tv_nsec - t1.tv_nsec;
double msec = (double)nsec / 1000000;
double thp_gbps = ((double)count * max_msg_size * 8) / nsec;
double thp_ops = ((double)count * 1000000000) / nsec;
std::cout << "timespan:" << msec << " millisecond." << std::endl;
std::cout << "throughput:" << thp_gbps << "Gbit/s." << std::endl;
std::cout << "throughput:" << thp_ops << "ops." << std::endl;
// aggregate bandwidth from all nodes
std::pair<double, double> bw_laten(thp_gbps,msec);
bw_laten = aggregate_bandwidth(members_order, members_order[node_rank], bw_laten);
double avg_gbps = bw_laten.first;
double avg_msec = bw_laten.second;
if(node_rank == 0) {
log_results(exp_result{num_of_nodes, max_msg_size,
derecho::getConfUInt32(CONF_SUBGROUP_DEFAULT_WINDOW_SIZE), count,
avg_msec, avg_gbps},
"data_derecho_typed_subgroup_bw");
}
group.barrier_sync();
group.leave();
}
<commit_msg>Added num_sender_selecter to typed_subgroup_bw_test<commit_after>#include <iostream>
#include <map>
#include <memory>
#include <string>
#include <time.h>
#include <vector>
#include "aggregate_bandwidth.cpp"
#include "aggregate_bandwidth.hpp"
#include "bytes_object.hpp"
#include "log_results.hpp"
#include <derecho/conf/conf.hpp>
#include <derecho/core/derecho.hpp>
#include <derecho/mutils-serialization/SerializationSupport.hpp>
#include <derecho/persistent/Persistent.hpp>
#include "partial_senders_allocator.hpp"
using std::endl;
using test::Bytes;
/**
* RPC Object with a single function that accepts a string
*/
class TestObject {
public:
void fun(const std::string& words) {
}
void bytes_fun(const Bytes& bytes) {
}
bool finishing_call(int x) {
return true;
}
REGISTER_RPC_FUNCTIONS(TestObject, fun, bytes_fun, finishing_call);
};
struct exp_result {
int num_nodes;
uint32_t num_sender_sel;
long long unsigned int max_msg_size;
unsigned int window_size;
uint32_t count;
double avg_msec;
double avg_gbps;
double avg_ops;
void print(std::ofstream& fout) {
fout << num_nodes << " " << num_sender_sel
<< max_msg_size << " " << window_size << " "
<< count << " "
<< avg_msec << " " << avg_gbps << " "
<< avg_ops << endl;
}
};
#define DEFAULT_PROC_NAME "typed_bw_test"
int main(int argc, char* argv[]) {
int dashdash_pos = argc - 1;
while(dashdash_pos > 0) {
if(strcmp(argv[dashdash_pos], "--") == 0) {
break;
}
dashdash_pos--;
}
if((argc - dashdash_pos) < 4) {
std::cout << "Invalid command line arguments." << std::endl;
std::cout << "USAGE: " << argv[0] << " [ derecho-config-list -- ] <num_nodes> <count> <num_senders_selector>[proc_name]" << std::endl;
std::cout << "Note: proc_name sets the process's name as displayed in ps and pkill commands, default is " DEFAULT_PROC_NAME << std::endl;
return -1;
}
derecho::Conf::initialize(argc, argv);
const int num_nodes = std::stoi(argv[dashdash_pos + 1]);
const uint64_t max_msg_size = derecho::getConfUInt64(CONF_SUBGROUP_DEFAULT_MAX_PAYLOAD_SIZE);
const uint32_t count = std::stoi(argv[dashdash_pos + 2]);
const uint32_t num_senders_selector = std::stoi(argv[dashdash_pos + 3]);
// Convert this integer to a more readable enum value
const PartialSendMode senders_mode = num_senders_selector == 0
? PartialSendMode::ALL_SENDERS
: (num_senders_selector == 1
? PartialSendMode::HALF_SENDERS
: PartialSendMode::ONE_SENDER);
if(dashdash_pos + 4 < argc) {
pthread_setname_np(pthread_self(), argv[dashdash_pos + 3]);
} else {
pthread_setname_np(pthread_self(), DEFAULT_PROC_NAME);
}
derecho::SubgroupInfo subgroup_info{[num_nodes](
const std::vector<std::type_index>& subgroup_type_order,
const std::unique_ptr<derecho::View>& prev_view, derecho::View& curr_view) {
if(curr_view.num_members < num_nodes) {
std::cout << "not enough members yet:" << curr_view.num_members << " < " << num_nodes << std::endl;
throw derecho::subgroup_provisioning_exception();
}
derecho::subgroup_shard_layout_t subgroup_layout(1);
std::vector<uint32_t> members(num_nodes);
for(int i = 0; i < num_nodes; i++) {
members[i] = i;
}
subgroup_layout[0].emplace_back(curr_view.make_subview(members));
curr_view.next_unassigned_rank = std::max(curr_view.next_unassigned_rank, num_nodes);
derecho::subgroup_allocation_map_t subgroup_allocation;
subgroup_allocation.emplace(std::type_index(typeid(TestObject)), std::move(subgroup_layout));
return subgroup_allocation;
}};
auto ba_factory = [](persistent::PersistentRegistry*, derecho::subgroup_id_t) { return std::make_unique<TestObject>(); };
derecho::Group<TestObject> group({}, subgroup_info, {}, std::vector<derecho::view_upcall_t>{}, ba_factory);
std::cout << "Finished constructing/joining Group" << std::endl;
derecho::Replicated<TestObject>& handle = group.get_subgroup<TestObject>();
//std::string str_1k(max_msg_size, 'x');
char* bbuf = (char*)malloc(max_msg_size);
bzero(bbuf, max_msg_size);
Bytes bytes(bbuf, max_msg_size);
struct timespec t1, t2;
clock_gettime(CLOCK_REALTIME, &t1);
// this function sends all the messages
auto send_all = [&]() {
for(uint i = 0; i < count; i++) {
//handle.ordered_send<RPC_NAME(fun)>(str_1k);
handle.ordered_send<RPC_NAME(bytes_fun)>(bytes);
}
};
int node_rank = group.get_my_rank();
if(senders_mode == PartialSendMode::ALL_SENDERS) {
send_all();
} else if(senders_mode == PartialSendMode::HALF_SENDERS) {
if(node_rank > (num_nodes - 1) / 2) {
send_all();
}
} else {
if(node_rank == num_nodes - 1) {
send_all();
}
}
if(node_rank == 0) {
derecho::rpc::QueryResults<bool> results = handle.ordered_send<RPC_NAME(finishing_call)>(0);
std::cout << "waiting for response..." << std::endl;
#pragma GCC diagnostic ignored "-Wunused-variable"
decltype(results)::ReplyMap& replies = results.get();
#pragma GCC diagnostic pop
}
clock_gettime(CLOCK_REALTIME, &t2);
free(bbuf);
double thp_gbps;
int64_t nsec = ((int64_t)t2.tv_sec - t1.tv_sec) * 1000000000 + t2.tv_nsec - t1.tv_nsec;
if(senders_mode == PartialSendMode::ALL_SENDERS) {
thp_gbps = ((double)count * max_msg_size * 8 * num_nodes) / nsec;
} else if(senders_mode == PartialSendMode::HALF_SENDERS) {
thp_gbps = ((double)count * max_msg_size * 8 * num_nodes/2) / nsec;
} else {
thp_gbps = ((double)count * max_msg_size * 8) / nsec;
}
double msec = (double)nsec / 1000000;
double thp_ops = ((double)count * 1000000000) / nsec;
std::cout << "timespan:" << msec << " millisecond." << std::endl;
std::cout << "throughput:" << thp_gbps << "Gbit/s." << std::endl;
std::cout << "throughput:" << thp_ops << "ops." << std::endl;
// aggregate bandwidth from all nodes
std::pair<double, double> bw_laten(thp_gbps,msec);
auto members_order = group.get_members();
bw_laten = aggregate_bandwidth(members_order, members_order[node_rank], bw_laten);
double avg_gbps = bw_laten.first;
double avg_msec = bw_laten.second;
if(node_rank == 0) {
log_results(exp_result{num_nodes, num_senders_selector, max_msg_size,
derecho::getConfUInt32(CONF_SUBGROUP_DEFAULT_WINDOW_SIZE), count,
avg_msec, avg_gbps},
"data_derecho_typed_subgroup_bw");
}
group.barrier_sync();
group.leave();
}
<|endoftext|>
|
<commit_before>#pragma once
#include "blob_interface.hpp"
#include "ipmi_interface.hpp"
#include <memory>
namespace ipmiblob
{
class BlobHandler : public BlobInterface
{
public:
enum BlobOEMCommands
{
bmcBlobGetCount = 0,
bmcBlobEnumerate = 1,
bmcBlobOpen = 2,
bmcBlobRead = 3,
bmcBlobWrite = 4,
bmcBlobCommit = 5,
bmcBlobClose = 6,
bmcBlobDelete = 7,
bmcBlobStat = 8,
bmcBlobSessionStat = 9,
bmcBlobWriteMeta = 10,
};
/**
* Create a BlobInterface pointer for use given an ipmi handler.
*
* @note This is a convenience method.
* @return a BlobHandler wrapped as a BlobInterface pointer.
*/
static std::unique_ptr<BlobInterface>
CreateBlobHandler(std::unique_ptr<IpmiInterface> ipmi);
explicit BlobHandler(std::unique_ptr<IpmiInterface> ipmi) :
ipmi(std::move(ipmi)){};
~BlobHandler() = default;
BlobHandler(const BlobHandler&) = delete;
BlobHandler& operator=(const BlobHandler&) = delete;
BlobHandler(BlobHandler&&) = default;
BlobHandler& operator=(BlobHandler&&) = default;
/**
* Retrieve the blob count.
*
* @return the number of blob_ids found (0 on failure).
*/
int getBlobCount();
/**
* Given an index into the list of blobs, return the name.
*
* @param[in] index - the index into the list of blob ids.
* @return the name as a string or empty on failure.
*/
std::string enumerateBlob(std::uint32_t index);
/**
* @throws BlobException.
*/
void commit(std::uint16_t session,
const std::vector<std::uint8_t>& bytes) override;
/**
* @throws BlobException.
*/
void writeMeta(std::uint16_t session, std::uint32_t offset,
const std::vector<std::uint8_t>& bytes) override;
/**
* @throw BlobException.
*/
void writeBytes(std::uint16_t session, std::uint32_t offset,
const std::vector<std::uint8_t>& bytes) override;
std::vector<std::string> getBlobList() override;
/**
* @throws BlobException.
*/
StatResponse getStat(const std::string& id) override;
/**
* @throws BlobException.
*/
StatResponse getStat(std::uint16_t session) override;
/**
* @throws BlobException.
*/
std::uint16_t openBlob(const std::string& id,
std::uint16_t handlerFlags) override;
void closeBlob(std::uint16_t session) override;
/**
* @throws BlobException.
*/
std::vector<std::uint8_t> readBytes(std::uint16_t session,
std::uint32_t offset,
std::uint32_t length) override;
private:
/**
* Send the contents of the payload to IPMI, this method handles wrapping
* with the OEN, subcommand and CRC.
*
* @param[in] command - the blob command.
* @param[in] payload - the payload bytes.
* @return the bytes returned from the ipmi interface.
* @throws BlobException.
*/
std::vector<std::uint8_t>
sendIpmiPayload(BlobOEMCommands command,
const std::vector<std::uint8_t>& payload);
/**
* Generic blob byte writer.
*
* @param[in] command - the command associated with this write.
* @param[in] session - the session id.
* @param[in] offset - the offset for the metadata to write.
* @param[in] bytes - the bytes to send.
* @throws BlobException on failure.
*/
void writeGeneric(BlobOEMCommands command, std::uint16_t session,
std::uint32_t offset,
const std::vector<std::uint8_t>& bytes);
/**
* Generic stat reader.
*
* @param[in] command - the command associated with this write.
* @param[in] request - the bytes of the request
* @return the metadata StatResponse
* @throws BlobException on failure.
*/
StatResponse statGeneric(BlobOEMCommands command,
const std::vector<std::uint8_t>& request);
std::unique_ptr<IpmiInterface> ipmi;
};
} // namespace ipmiblob
<commit_msg>blob_handler: make commit data parameter optional<commit_after>#pragma once
#include "blob_interface.hpp"
#include "ipmi_interface.hpp"
#include <memory>
namespace ipmiblob
{
class BlobHandler : public BlobInterface
{
public:
enum BlobOEMCommands
{
bmcBlobGetCount = 0,
bmcBlobEnumerate = 1,
bmcBlobOpen = 2,
bmcBlobRead = 3,
bmcBlobWrite = 4,
bmcBlobCommit = 5,
bmcBlobClose = 6,
bmcBlobDelete = 7,
bmcBlobStat = 8,
bmcBlobSessionStat = 9,
bmcBlobWriteMeta = 10,
};
/**
* Create a BlobInterface pointer for use given an ipmi handler.
*
* @note This is a convenience method.
* @return a BlobHandler wrapped as a BlobInterface pointer.
*/
static std::unique_ptr<BlobInterface>
CreateBlobHandler(std::unique_ptr<IpmiInterface> ipmi);
explicit BlobHandler(std::unique_ptr<IpmiInterface> ipmi) :
ipmi(std::move(ipmi)){};
~BlobHandler() = default;
BlobHandler(const BlobHandler&) = delete;
BlobHandler& operator=(const BlobHandler&) = delete;
BlobHandler(BlobHandler&&) = default;
BlobHandler& operator=(BlobHandler&&) = default;
/**
* Retrieve the blob count.
*
* @return the number of blob_ids found (0 on failure).
*/
int getBlobCount();
/**
* Given an index into the list of blobs, return the name.
*
* @param[in] index - the index into the list of blob ids.
* @return the name as a string or empty on failure.
*/
std::string enumerateBlob(std::uint32_t index);
/**
* @throws BlobException.
*/
void commit(std::uint16_t session,
const std::vector<std::uint8_t>& bytes = {}) override;
/**
* @throws BlobException.
*/
void writeMeta(std::uint16_t session, std::uint32_t offset,
const std::vector<std::uint8_t>& bytes) override;
/**
* @throw BlobException.
*/
void writeBytes(std::uint16_t session, std::uint32_t offset,
const std::vector<std::uint8_t>& bytes) override;
std::vector<std::string> getBlobList() override;
/**
* @throws BlobException.
*/
StatResponse getStat(const std::string& id) override;
/**
* @throws BlobException.
*/
StatResponse getStat(std::uint16_t session) override;
/**
* @throws BlobException.
*/
std::uint16_t openBlob(const std::string& id,
std::uint16_t handlerFlags) override;
void closeBlob(std::uint16_t session) override;
/**
* @throws BlobException.
*/
std::vector<std::uint8_t> readBytes(std::uint16_t session,
std::uint32_t offset,
std::uint32_t length) override;
private:
/**
* Send the contents of the payload to IPMI, this method handles wrapping
* with the OEN, subcommand and CRC.
*
* @param[in] command - the blob command.
* @param[in] payload - the payload bytes.
* @return the bytes returned from the ipmi interface.
* @throws BlobException.
*/
std::vector<std::uint8_t>
sendIpmiPayload(BlobOEMCommands command,
const std::vector<std::uint8_t>& payload);
/**
* Generic blob byte writer.
*
* @param[in] command - the command associated with this write.
* @param[in] session - the session id.
* @param[in] offset - the offset for the metadata to write.
* @param[in] bytes - the bytes to send.
* @throws BlobException on failure.
*/
void writeGeneric(BlobOEMCommands command, std::uint16_t session,
std::uint32_t offset,
const std::vector<std::uint8_t>& bytes);
/**
* Generic stat reader.
*
* @param[in] command - the command associated with this write.
* @param[in] request - the bytes of the request
* @return the metadata StatResponse
* @throws BlobException on failure.
*/
StatResponse statGeneric(BlobOEMCommands command,
const std::vector<std::uint8_t>& request);
std::unique_ptr<IpmiInterface> ipmi;
};
} // namespace ipmiblob
<|endoftext|>
|
<commit_before>/*
* author: Max Kellermann <mk@cm4all.com>
*/
#include "istream_iconv.hxx"
#include "FacadeIstream.hxx"
#include "util/Cast.hxx"
#include "util/ForeignFifoBuffer.hxx"
#include <iconv.h>
#include <assert.h>
#include <errno.h>
class IconvIstream final : public FacadeIstream {
static constexpr size_t BUFFER_SIZE = 1024;
const iconv_t iconv;
ForeignFifoBuffer<uint8_t> buffer;
public:
IconvIstream(struct pool &p, struct istream &_input,
iconv_t _iconv)
:FacadeIstream(p, _input,
MakeIstreamHandler<IconvIstream>::handler, this),
iconv(_iconv),
buffer(PoolAlloc<uint8_t>(p, BUFFER_SIZE), BUFFER_SIZE)
{
}
~IconvIstream() {
buffer.SetNull();
iconv_close(iconv);
}
bool IsOpen() const {
return buffer.IsDefined();
}
/* virtual methods from class Istream */
off_t GetAvailable(bool partial) override {
if (partial)
return buffer.GetAvailable();
return -1;
}
void Read() override;
void Close() override;
/* handler */
size_t OnData(const void *data, size_t length);
ssize_t OnDirect(gcc_unused FdType type, gcc_unused int fd,
gcc_unused size_t max_length) {
gcc_unreachable();
}
void OnEof();
void OnError(GError *error);
private:
size_t Feed(const char *data, size_t length);
};
gcc_const
static GQuark
iconv_quark(void)
{
return g_quark_from_static_string("iconv");
}
static inline size_t
deconst_iconv(iconv_t cd,
const char **inbuf, size_t *inbytesleft,
char **outbuf, size_t *outbytesleft)
{
char **inbuf2 = const_cast<char **>(inbuf);
return iconv(cd, inbuf2, inbytesleft, outbuf, outbytesleft);
}
size_t
IconvIstream::Feed(const char *data, size_t length)
{
const char *src = data;
do {
auto w = buffer.Write();
if (w.IsEmpty()) {
/* no space left in the buffer: attempt to flush it */
size_t nbytes = SendFromBuffer(buffer);
if (nbytes == 0) {
if (!IsOpen())
return 0;
break;
}
assert(IsOpen());
continue;
}
char *const dest0 = (char *)w.data;
char *dest = dest0;
size_t dest_left = w.size;
size_t ret = deconst_iconv(iconv, &src, &length, &dest, &dest_left);
if (dest > dest0)
buffer.Append(dest - dest0);
if (ret == (size_t)-1) {
switch (errno) {
size_t nbytes;
case EILSEQ:
/* invalid sequence: skip this byte */
++src;
--length;
break;
case EINVAL:
/* incomplete sequence: leave it in the buffer */
if (src == data) {
/* XXX we abort here, because we believe if the
incomplete sequence is at the start of the
buffer, this might be EOF; we should rather
buffer this incomplete sequence and report the
caller that we consumed it */
input.Close();
GError *error = g_error_new_literal(iconv_quark(), 0,
"incomplete sequence");
DestroyError(error);
return 0;
}
length = 0;
break;
case E2BIG:
/* output buffer is full: flush dest */
nbytes = SendFromBuffer(buffer);
if (nbytes == 0) {
if (!IsOpen())
return 0;
/* reset length to 0, to make the loop quit
(there's no "double break" to break out of the
while loop in C) */
length = 0;
break;
}
assert(IsOpen());
break;
}
}
} while (length > 0);
SendFromBuffer(buffer);
if (!IsOpen())
return 0;
return src - data;
}
/*
* istream handler
*
*/
size_t
IconvIstream::OnData(const void *data, size_t length)
{
assert(input.IsDefined());
const ScopePoolRef ref(GetPool() TRACE_ARGS);
return Feed((const char *)data, length);
}
void
IconvIstream::OnEof()
{
assert(input.IsDefined());
input.Clear();
if (buffer.IsEmpty())
DestroyEof();
}
void
IconvIstream::OnError(GError *error)
{
assert(input.IsDefined());
DestroyError(error);
}
/*
* istream implementation
*
*/
void
IconvIstream::Read()
{
if (input.IsDefined())
input.Read();
else {
size_t rest = ConsumeFromBuffer(buffer);
if (rest == 0)
DestroyEof();
}
}
void
IconvIstream::Close()
{
if (input.IsDefined())
input.Close();
Destroy();
}
/*
* constructor
*
*/
struct istream *
istream_iconv_new(struct pool *pool, struct istream *input,
const char *tocode, const char *fromcode)
{
assert(input != nullptr);
assert(!istream_has_handler(input));
const iconv_t iconv = iconv_open(tocode, fromcode);
if (iconv == (iconv_t)-1)
return nullptr;
return NewIstream<IconvIstream>(*pool, *input, iconv);
}
<commit_msg>istream/iconv: use "iconv!=-1" in IsOpen()<commit_after>/*
* author: Max Kellermann <mk@cm4all.com>
*/
#include "istream_iconv.hxx"
#include "FacadeIstream.hxx"
#include "util/Cast.hxx"
#include "util/ForeignFifoBuffer.hxx"
#include <iconv.h>
#include <assert.h>
#include <errno.h>
class IconvIstream final : public FacadeIstream {
static constexpr size_t BUFFER_SIZE = 1024;
iconv_t iconv;
ForeignFifoBuffer<uint8_t> buffer;
public:
IconvIstream(struct pool &p, struct istream &_input,
iconv_t _iconv)
:FacadeIstream(p, _input,
MakeIstreamHandler<IconvIstream>::handler, this),
iconv(_iconv),
buffer(PoolAlloc<uint8_t>(p, BUFFER_SIZE), BUFFER_SIZE)
{
}
~IconvIstream() {
iconv_close(iconv);
iconv = (iconv_t)-1;
}
bool IsOpen() const {
return iconv != (iconv_t)-1;
}
/* virtual methods from class Istream */
off_t GetAvailable(bool partial) override {
if (partial)
return buffer.GetAvailable();
return -1;
}
void Read() override;
void Close() override;
/* handler */
size_t OnData(const void *data, size_t length);
ssize_t OnDirect(gcc_unused FdType type, gcc_unused int fd,
gcc_unused size_t max_length) {
gcc_unreachable();
}
void OnEof();
void OnError(GError *error);
private:
size_t Feed(const char *data, size_t length);
};
gcc_const
static GQuark
iconv_quark(void)
{
return g_quark_from_static_string("iconv");
}
static inline size_t
deconst_iconv(iconv_t cd,
const char **inbuf, size_t *inbytesleft,
char **outbuf, size_t *outbytesleft)
{
char **inbuf2 = const_cast<char **>(inbuf);
return iconv(cd, inbuf2, inbytesleft, outbuf, outbytesleft);
}
size_t
IconvIstream::Feed(const char *data, size_t length)
{
const char *src = data;
do {
auto w = buffer.Write();
if (w.IsEmpty()) {
/* no space left in the buffer: attempt to flush it */
size_t nbytes = SendFromBuffer(buffer);
if (nbytes == 0) {
if (!IsOpen())
return 0;
break;
}
assert(IsOpen());
continue;
}
char *const dest0 = (char *)w.data;
char *dest = dest0;
size_t dest_left = w.size;
size_t ret = deconst_iconv(iconv, &src, &length, &dest, &dest_left);
if (dest > dest0)
buffer.Append(dest - dest0);
if (ret == (size_t)-1) {
switch (errno) {
size_t nbytes;
case EILSEQ:
/* invalid sequence: skip this byte */
++src;
--length;
break;
case EINVAL:
/* incomplete sequence: leave it in the buffer */
if (src == data) {
/* XXX we abort here, because we believe if the
incomplete sequence is at the start of the
buffer, this might be EOF; we should rather
buffer this incomplete sequence and report the
caller that we consumed it */
input.Close();
GError *error = g_error_new_literal(iconv_quark(), 0,
"incomplete sequence");
DestroyError(error);
return 0;
}
length = 0;
break;
case E2BIG:
/* output buffer is full: flush dest */
nbytes = SendFromBuffer(buffer);
if (nbytes == 0) {
if (!IsOpen())
return 0;
/* reset length to 0, to make the loop quit
(there's no "double break" to break out of the
while loop in C) */
length = 0;
break;
}
assert(IsOpen());
break;
}
}
} while (length > 0);
SendFromBuffer(buffer);
if (!IsOpen())
return 0;
return src - data;
}
/*
* istream handler
*
*/
size_t
IconvIstream::OnData(const void *data, size_t length)
{
assert(input.IsDefined());
const ScopePoolRef ref(GetPool() TRACE_ARGS);
return Feed((const char *)data, length);
}
void
IconvIstream::OnEof()
{
assert(input.IsDefined());
input.Clear();
if (buffer.IsEmpty())
DestroyEof();
}
void
IconvIstream::OnError(GError *error)
{
assert(input.IsDefined());
DestroyError(error);
}
/*
* istream implementation
*
*/
void
IconvIstream::Read()
{
if (input.IsDefined())
input.Read();
else {
size_t rest = ConsumeFromBuffer(buffer);
if (rest == 0)
DestroyEof();
}
}
void
IconvIstream::Close()
{
if (input.IsDefined())
input.Close();
Destroy();
}
/*
* constructor
*
*/
struct istream *
istream_iconv_new(struct pool *pool, struct istream *input,
const char *tocode, const char *fromcode)
{
assert(input != nullptr);
assert(!istream_has_handler(input));
const iconv_t iconv = iconv_open(tocode, fromcode);
if (iconv == (iconv_t)-1)
return nullptr;
return NewIstream<IconvIstream>(*pool, *input, iconv);
}
<|endoftext|>
|
<commit_before>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of libmeegotouch.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** 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
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/
#include "mapplicationextensionloader.h"
#include "mapplicationextensioninterface.h"
#include "mapplicationextensionmetadata.h"
#include <MDebug>
#include <QPluginLoader>
MApplicationExtensionLoader::MApplicationExtensionLoader()
{
}
MApplicationExtensionInterface *MApplicationExtensionLoader::loadExtension(const MApplicationExtensionMetaData &metadata)
{
QPluginLoader loader(metadata.extensionBinary());
loader.setLoadHints(QLibrary::ResolveAllSymbolsHint | QLibrary::ExportExternalSymbolsHint);
QObject *object = loader.instance();
if (object != NULL) {
if (object->inherits(metadata.interface().toUtf8().constData())) {
MApplicationExtensionInterface *extension = dynamic_cast<MApplicationExtensionInterface *>(object);
if (extension != NULL) {
if (extension->initialize(metadata.interface())) {
return extension;
} else {
mWarning("MApplicationExtensionLoader") << "Application extension" << metadata.fileName() << "could not be initialized.";
}
} else {
mWarning("MApplicationExtensionLoader") << "Application extension" << metadata.fileName() << "could not be instantiated. The extension does not implement MApplicationExtensionInterface.";
}
} else {
mWarning("MApplicationExtensionLoader") << "Application extension" << metadata.fileName() << "could not be instantiated. The extension does not inherit" << metadata.interface();
}
delete object;
} else {
mWarning("MApplicationExtensionLoader") << "Application extension" << metadata.fileName() << "could not be loaded." << loader.errorString();
}
return false;
}
<commit_msg>Fixes: NB#211859 - White and red rectangles in Events view after device reboot<commit_after>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of libmeegotouch.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** 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
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/
#include "mapplicationextensionloader.h"
#include "mapplicationextensioninterface.h"
#include "mapplicationextensionmetadata.h"
#include <MDebug>
#include <QPluginLoader>
MApplicationExtensionLoader::MApplicationExtensionLoader()
{
}
MApplicationExtensionInterface *MApplicationExtensionLoader::loadExtension(const MApplicationExtensionMetaData &metadata)
{
QPluginLoader loader(metadata.extensionBinary());
loader.setLoadHints(QLibrary::ResolveAllSymbolsHint | QLibrary::ExportExternalSymbolsHint);
QObject *object = loader.instance();
if (object != NULL) {
if (object->inherits(metadata.interface().toUtf8().constData())) {
MApplicationExtensionInterface *extension = qobject_cast<MApplicationExtensionInterface *>(object);
if (extension != NULL) {
if (extension->initialize(metadata.interface())) {
return extension;
} else {
mWarning("MApplicationExtensionLoader") << "Application extension" << metadata.fileName() << "could not be initialized.";
}
} else {
mWarning("MApplicationExtensionLoader") << "Application extension" << metadata.fileName() << "could not be instantiated. The extension does not implement MApplicationExtensionInterface.";
}
} else {
mWarning("MApplicationExtensionLoader") << "Application extension" << metadata.fileName() << "could not be instantiated. The extension does not inherit" << metadata.interface();
}
delete object;
} else {
mWarning("MApplicationExtensionLoader") << "Application extension" << metadata.fileName() << "could not be loaded." << loader.errorString();
}
return false;
}
<|endoftext|>
|
<commit_before>/* -*- mode: c++; indent-tabs-mode: nil -*- */
/* -----------------------------------------------------------------------------
ATS
Authors: Ethan Coon (ecoon@lanl.gov)
FieldEvaluator for enthalpy.
----------------------------------------------------------------------------- */
#include "enthalpy_evaluator.hh"
namespace Amanzi {
namespace Energy {
EnthalpyEvaluator::EnthalpyEvaluator(Teuchos::ParameterList& plist) :
SecondaryVariableFieldEvaluator(plist) {
if (my_key_.empty()) {
my_key_ = plist_.get<std::string>("enthalpy key", "surface-enthalpy_liquid");
}
// Set up my dependencies.
std::string domain_name = Keys::getDomain(my_key_);
include_work_ = plist_.get<bool>("include work term", true);
// -- pressure
if (include_work_) {
pres_key_ = Keys::readKey(plist_, domain_name, "pressure", "pressure");
dependencies_.insert(pres_key_);
dens_key_ = Keys::readKey(plist_, domain_name, "molar density liquid", "molar_density_liquid");
dependencies_.insert(dens_key_);
}
ie_key_ = Keys::readKey(plist_, domain_name, "internal energy liquid", "internal_energy_liquid");
dependencies_.insert(ie_key_);
};
EnthalpyEvaluator::EnthalpyEvaluator(const EnthalpyEvaluator& other) :
SecondaryVariableFieldEvaluator(other),
pres_key_(other.pres_key_),
dens_key_(other.dens_key_),
ie_key_(other.ie_key_),
include_work_(other.include_work_) {};
Teuchos::RCP<FieldEvaluator>
EnthalpyEvaluator::Clone() const {
return Teuchos::rcp(new EnthalpyEvaluator(*this));
};
void EnthalpyEvaluator::EvaluateField_(const Teuchos::Ptr<State>& S,
const Teuchos::Ptr<CompositeVector>& result) {
Teuchos::OSTab tab = vo_->getOSTab();
Teuchos::RCP<const CompositeVector> u_l = S->GetFieldData(ie_key_);
*result = *u_l;
if (include_work_) {
Teuchos::RCP<const CompositeVector> pres = S->GetFieldData(pres_key_);
Teuchos::RCP<const CompositeVector> n_l = S->GetFieldData(dens_key_);
for (CompositeVector::name_iterator comp=result->begin();
comp!=result->end(); ++comp) {
const Epetra_MultiVector& pres_v = *pres->ViewComponent(*comp,false);
const Epetra_MultiVector& nl_v = *n_l->ViewComponent(*comp,false);
Epetra_MultiVector& result_v = *result->ViewComponent(*comp,false);
int ncomp = result->size(*comp, false);
for (int i=0; i!=ncomp; ++i) {
// 1.e-6 converts to MJoules
result_v[0][i] += 1.e-6*pres_v[0][i]/nl_v[0][i];
}
}
}
};
void EnthalpyEvaluator::EvaluateFieldPartialDerivative_(const Teuchos::Ptr<State>& S,
Key wrt_key, const Teuchos::Ptr<CompositeVector>& result) {
// not implemented
if (wrt_key == ie_key_) {
result->PutScalar(1.);
} else if (wrt_key ==pres_key_) {
AMANZI_ASSERT(include_work_);
Teuchos::RCP<const CompositeVector> n_l = S->GetFieldData(dens_key_);
for (CompositeVector::name_iterator comp=result->begin();
comp!=result->end(); ++comp) {
const Epetra_MultiVector& nl_v = *n_l->ViewComponent(*comp,false);
Epetra_MultiVector& result_v = *result->ViewComponent(*comp,false);
int ncomp = result->size(*comp, false);
for (int i=0; i!=ncomp; ++i) {
// 1.e-6 converts to MJoules
result_v[0][i] = 1.e-6/nl_v[0][i];
}
}
} else if (wrt_key ==dens_key_) {
AMANZI_ASSERT(include_work_);
Teuchos::RCP<const CompositeVector> pres = S->GetFieldData(pres_key_);
Teuchos::RCP<const CompositeVector> n_l = S->GetFieldData(dens_key_);
for (CompositeVector::name_iterator comp=result->begin();
comp!=result->end(); ++comp) {
const Epetra_MultiVector& nl_v = *n_l->ViewComponent(*comp,false);
const Epetra_MultiVector& pres_v = *pres->ViewComponent(*comp,false);
Epetra_MultiVector& result_v = *result->ViewComponent(*comp,false);
int ncomp = result->size(*comp, false);
for (int i=0; i!=ncomp; ++i) {
// 1.e-6 converts to MJoules
result_v[0][i] = -1.e-6*pres_v[0][i]/std::pow(nl_v[0][i], 2);
}
}
}
};
} //namespace
} //namespace
<commit_msg>makes include work term default to no in enthalpy evaluators -- it is not useful in standard ATS simulations, and does wierd things in frozen conditions<commit_after>/* -*- mode: c++; indent-tabs-mode: nil -*- */
/* -----------------------------------------------------------------------------
ATS
Authors: Ethan Coon (ecoon@lanl.gov)
FieldEvaluator for enthalpy.
----------------------------------------------------------------------------- */
#include "enthalpy_evaluator.hh"
namespace Amanzi {
namespace Energy {
EnthalpyEvaluator::EnthalpyEvaluator(Teuchos::ParameterList& plist) :
SecondaryVariableFieldEvaluator(plist) {
if (my_key_.empty()) {
my_key_ = plist_.get<std::string>("enthalpy key", "surface-enthalpy_liquid");
}
// Set up my dependencies.
std::string domain_name = Keys::getDomain(my_key_);
include_work_ = plist_.get<bool>("include work term", false);
// -- pressure
if (include_work_) {
pres_key_ = Keys::readKey(plist_, domain_name, "pressure", "pressure");
dependencies_.insert(pres_key_);
dens_key_ = Keys::readKey(plist_, domain_name, "molar density liquid", "molar_density_liquid");
dependencies_.insert(dens_key_);
}
ie_key_ = Keys::readKey(plist_, domain_name, "internal energy liquid", "internal_energy_liquid");
dependencies_.insert(ie_key_);
};
EnthalpyEvaluator::EnthalpyEvaluator(const EnthalpyEvaluator& other) :
SecondaryVariableFieldEvaluator(other),
pres_key_(other.pres_key_),
dens_key_(other.dens_key_),
ie_key_(other.ie_key_),
include_work_(other.include_work_) {};
Teuchos::RCP<FieldEvaluator>
EnthalpyEvaluator::Clone() const {
return Teuchos::rcp(new EnthalpyEvaluator(*this));
};
void EnthalpyEvaluator::EvaluateField_(const Teuchos::Ptr<State>& S,
const Teuchos::Ptr<CompositeVector>& result) {
Teuchos::OSTab tab = vo_->getOSTab();
Teuchos::RCP<const CompositeVector> u_l = S->GetFieldData(ie_key_);
*result = *u_l;
if (include_work_) {
Teuchos::RCP<const CompositeVector> pres = S->GetFieldData(pres_key_);
Teuchos::RCP<const CompositeVector> n_l = S->GetFieldData(dens_key_);
for (CompositeVector::name_iterator comp=result->begin();
comp!=result->end(); ++comp) {
const Epetra_MultiVector& pres_v = *pres->ViewComponent(*comp,false);
const Epetra_MultiVector& nl_v = *n_l->ViewComponent(*comp,false);
Epetra_MultiVector& result_v = *result->ViewComponent(*comp,false);
int ncomp = result->size(*comp, false);
for (int i=0; i!=ncomp; ++i) {
// 1.e-6 converts to MJoules
result_v[0][i] += 1.e-6*pres_v[0][i]/nl_v[0][i];
}
}
}
};
void EnthalpyEvaluator::EvaluateFieldPartialDerivative_(const Teuchos::Ptr<State>& S,
Key wrt_key, const Teuchos::Ptr<CompositeVector>& result) {
// not implemented
if (wrt_key == ie_key_) {
result->PutScalar(1.);
} else if (wrt_key ==pres_key_) {
AMANZI_ASSERT(include_work_);
Teuchos::RCP<const CompositeVector> n_l = S->GetFieldData(dens_key_);
for (CompositeVector::name_iterator comp=result->begin();
comp!=result->end(); ++comp) {
const Epetra_MultiVector& nl_v = *n_l->ViewComponent(*comp,false);
Epetra_MultiVector& result_v = *result->ViewComponent(*comp,false);
int ncomp = result->size(*comp, false);
for (int i=0; i!=ncomp; ++i) {
// 1.e-6 converts to MJoules
result_v[0][i] = 1.e-6/nl_v[0][i];
}
}
} else if (wrt_key ==dens_key_) {
AMANZI_ASSERT(include_work_);
Teuchos::RCP<const CompositeVector> pres = S->GetFieldData(pres_key_);
Teuchos::RCP<const CompositeVector> n_l = S->GetFieldData(dens_key_);
for (CompositeVector::name_iterator comp=result->begin();
comp!=result->end(); ++comp) {
const Epetra_MultiVector& nl_v = *n_l->ViewComponent(*comp,false);
const Epetra_MultiVector& pres_v = *pres->ViewComponent(*comp,false);
Epetra_MultiVector& result_v = *result->ViewComponent(*comp,false);
int ncomp = result->size(*comp, false);
for (int i=0; i!=ncomp; ++i) {
// 1.e-6 converts to MJoules
result_v[0][i] = -1.e-6*pres_v[0][i]/std::pow(nl_v[0][i], 2);
}
}
}
};
} //namespace
} //namespace
<|endoftext|>
|
<commit_before>#include "WordModifier.h"
WordModifier::WordModifier()
{
//ctor
}
<commit_msg>Update WordModifier.cpp<commit_after>#include "WordModifier.h"
#include <string>
WordModifier::WordModifier(std::string form)
: form(form)
{
}
<|endoftext|>
|
<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** 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.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/
#include "stateseditorview.h"
#include "stateseditormodel.h"
#include <customnotifications.h>
#include <QPainter>
#include <QTimerEvent>
#include <QDebug>
enum {
debug = false
};
namespace QmlDesigner {
namespace Internal {
/**
We always have 'one' current state, where we get updates from (see sceneChanged()). In case
the current state is the base state, we render the base state + all other states.
*/
StatesEditorView::StatesEditorView(StatesEditorModel *editorModel, QObject *parent) :
QmlModelView(parent),
m_editorModel(editorModel)
{
Q_ASSERT(m_editorModel);
connect(nodeInstanceView(), SIGNAL(instanceRemoved(NodeInstance)), this, SLOT(sceneChanged()));
connect(nodeInstanceView(), SIGNAL(transformPropertyChanged(NodeInstance)), this, SLOT(sceneChanged()));
connect(nodeInstanceView(), SIGNAL(parentPropertyChanged(NodeInstance)), this, SLOT(sceneChanged()));
connect(nodeInstanceView(), SIGNAL(otherPropertyChanged(NodeInstance)), this, SLOT(sceneChanged()));
connect(nodeInstanceView(), SIGNAL(updateItem(NodeInstance)), this, SLOT(sceneChanged()));
}
void StatesEditorView::setCurrentStateSilent(int index)
{
// TODO
QmlModelState state(m_modelStates.at(index));
if (!state.isValid())
return;
if (state == currentState())
return;
QmlModelView::stateChanged(state, currentState());
}
void StatesEditorView::setCurrentState(int index)
{
// TODO
if (m_modelStates.indexOf(currentState()) == index)
return;
if (index >= m_modelStates.count())
return;
QmlModelState state(m_modelStates.at(index));
Q_ASSERT(state.isValid());
QmlModelView::setCurrentState(state);
}
void StatesEditorView::setBackCurrentState(int index, const QmlModelState &oldState)
{
// TODO
QmlModelState state(m_modelStates.at(index));
if (!state.isValid())
return;
if (state == oldState)
return;
QmlModelView::stateChanged(oldState, state);
}
void StatesEditorView::createState(const QString &name)
{
stateRootNode().states().addState(name);
}
void StatesEditorView::removeState(int index)
{
Q_ASSERT(index > 0 && index < m_modelStates.size());
QmlModelState state = m_modelStates.at(index);
Q_ASSERT(state.isValid());
m_modelStates.removeAll(state);
m_editorModel->removeState(index);
QmlModelView::setCurrentState(baseState());
state.destroy();
}
void StatesEditorView::renameState(int index,const QString &newName)
{
Q_ASSERT(index > 0 && index < m_modelStates.size());
QmlModelState state = m_modelStates.at(index);
Q_ASSERT(state.isValid());
if (state.name() != newName) {
// Jump to base state for the change
QmlModelState oldState = currentState();
setCurrentStateSilent(0);
state.setName(newName);
setBackCurrentState(0, oldState);
}
}
void StatesEditorView::duplicateCurrentState(int index)
{
Q_ASSERT(index > 0 && index < m_modelStates.size());
QmlModelState state = m_modelStates.at(index);
Q_ASSERT(state.isValid());
QString newName = state.name();
// Strip out numbers at the end of the string
QRegExp regEx(QString("[0-9]+$"));
int numberIndex = newName.indexOf(regEx);
if ((numberIndex != -1) && (numberIndex+regEx.matchedLength()==newName.length()))
newName = newName.left(numberIndex);
int i = 1;
QStringList stateNames = state.stateGroup().names();
while (stateNames.contains(newName + QString::number(i)))
i++;
state.duplicate(newName + QString::number(i));
}
void StatesEditorView::modelAttached(Model *model)
{
if (model == QmlModelView::model())
return;
Q_ASSERT(model);
QmlModelView::modelAttached(model);
Q_ASSERT(m_editorModel->rowCount(QModelIndex()) == 0);
// find top level states
m_stateRootNode = QmlItemNode(rootModelNode());
if (!m_stateRootNode.isValid())
return;
clearModelStates();
// Add base state
m_modelStates.insert(0, baseState());
m_editorModel->insertState(0, baseState().name());
// Add custom states
for (int i = 0; i < m_stateRootNode.states().allStates().size(); ++i) {
QmlModelState state = QmlItemNode(rootModelNode()).states().allStates().at(i);
insertModelState(i, state);
}
}
void StatesEditorView::modelAboutToBeDetached(Model *model)
{
if (debug)
qDebug() << __FUNCTION__;
clearModelStates();
QmlModelView::modelAboutToBeDetached(model);
}
void StatesEditorView::propertiesAboutToBeRemoved(const QList<AbstractProperty>& propertyList)
{
foreach (const AbstractProperty &property, propertyList) {
// remove all states except base state
if ((property.name()=="states") && (property.parentModelNode().isRootNode())) {
foreach (const QmlModelState &state, m_modelStates) {
if (!state.isBaseState())
removeModelState(state);
}
} else {
ModelNode node (property.parentModelNode().parentProperty().parentModelNode());
if (QmlModelState(node).isValid()) {
startUpdateTimer(modelStateIndex(node) + 1, 0);
}
}
}
}
void StatesEditorView::propertiesRemoved(const QList<AbstractProperty>& propertyList)
{
QmlModelView::propertiesRemoved(propertyList);
}
void StatesEditorView::variantPropertiesChanged(const QList<VariantProperty>& propertyList, PropertyChangeFlags propertyChange)
{
QmlModelView::variantPropertiesChanged(propertyList, propertyChange);
foreach (const VariantProperty &property, propertyList) {
ModelNode node (property.parentModelNode());
if (QmlModelState(node).isValid() && (property.name() == QLatin1String("name"))) {
int index = m_modelStates.indexOf(node);
if (index != -1)
m_editorModel->renameState(index, property.value().toString());
}
}
foreach (const AbstractProperty &property, propertyList) {
ModelNode node (property.parentModelNode().parentProperty().parentModelNode());
if (QmlModelState(node).isValid()) {
startUpdateTimer(modelStateIndex(node) + 1, 0);
} else { //a change to the base state update all
for (int i = 0; i < m_modelStates.count(); ++i)
startUpdateTimer(i, 0);
}
}
}
void StatesEditorView::nodeAboutToBeRemoved(const ModelNode &removedNode)
{
if (removedNode.parentProperty().parentModelNode() == m_stateRootNode
&& QmlModelState(removedNode).isValid()) {
removeModelState(removedNode);
}
QmlModelView::nodeAboutToBeRemoved(removedNode);
}
void StatesEditorView::nodeReparented(const ModelNode &node, const NodeAbstractProperty &newPropertyParent, const NodeAbstractProperty &oldPropertyParent, AbstractView::PropertyChangeFlags propertyChange)
{
QmlModelView::nodeReparented(node, newPropertyParent, oldPropertyParent, propertyChange);
// this would be sliding
Q_ASSERT(newPropertyParent != oldPropertyParent);
if (QmlModelState(node).isValid()) {
if (oldPropertyParent.parentModelNode() == m_stateRootNode) {
if (oldPropertyParent.isNodeListProperty()
&& oldPropertyParent.name() == "states") {
removeModelState(node);
} else {
qWarning() << "States Editor: Reparented model state was not in states property list";
}
}
if (newPropertyParent.parentModelNode() == m_stateRootNode) {
if (newPropertyParent.isNodeListProperty()
&& newPropertyParent.name() == "states") {
NodeListProperty statesProperty = newPropertyParent.toNodeListProperty();
int index = statesProperty.toModelNodeList().indexOf(node);
Q_ASSERT(index >= 0);
insertModelState(index, node);
} else {
qWarning() << "States Editor: Reparented model state is not in the states property list";
}
}
}
}
void StatesEditorView::nodeSlidedToIndex(const NodeListProperty &listProperty, int newIndex, int oldIndex)
{
QmlModelView::nodeSlidedToIndex(listProperty, newIndex, oldIndex);
if (listProperty.parentModelNode() == m_stateRootNode
&& listProperty.name() == "states") {
int index = newIndex;
if (oldIndex < newIndex)
--index;
QmlModelState state = listProperty.toModelNodeList().at(index);
if (state.isValid()) {
Q_ASSERT(oldIndex == modelStateIndex(state));
removeModelState(state);
insertModelState(newIndex, state);
Q_ASSERT(newIndex == modelStateIndex(state));
}
}
}
void StatesEditorView::stateChanged(const QmlModelState &newQmlModelState, const QmlModelState &oldQmlModelState)
{
QmlModelView::stateChanged(newQmlModelState, oldQmlModelState);
if (newQmlModelState.isBaseState())
m_editorModel->emitChangedToState(0);
else
m_editorModel->emitChangedToState(m_modelStates.indexOf(newQmlModelState));
}
void StatesEditorView::customNotification(const AbstractView *view, const QString &identifier, const QList<ModelNode> &nodeList, const QList<QVariant> &data)
{
QmlModelView::customNotification(view, identifier, nodeList, data);
if (identifier == StartRewriterAmend) {
m_oldRewriterAmendState = currentState();
QmlModelView::setCurrentState(baseState());
} else if (identifier == EndRewriterAmend) {
if (m_oldRewriterAmendState.isValid())
QmlModelView::setCurrentState(m_oldRewriterAmendState);
}
}
QPixmap StatesEditorView::renderState(int i)
{
Q_ASSERT(i >= 0 && i < m_modelStates.size());
nodeInstanceView()->setBlockChangeSignal(true);
QmlModelState oldState = currentState();
setCurrentStateSilent(i);
Q_ASSERT(nodeInstanceView());
const int checkerbordSize= 10;
QPixmap tilePixmap(checkerbordSize * 2, checkerbordSize * 2);
tilePixmap.fill(Qt::white);
QPainter tilePainter(&tilePixmap);
QColor color(220, 220, 220);
tilePainter.fillRect(0, 0, checkerbordSize, checkerbordSize, color);
tilePainter.fillRect(checkerbordSize, checkerbordSize, checkerbordSize, checkerbordSize, color);
tilePainter.end();
QSize pixmapSize(nodeInstanceView()->sceneRect().size().toSize());
if (pixmapSize.width() > 150 || pixmapSize.height() > 150) // sensible maximum size
pixmapSize.scale(QSize(150, 150), Qt::KeepAspectRatio);
QPixmap pixmap(pixmapSize);
QPainter painter(&pixmap);
painter.drawTiledPixmap(pixmap.rect(), tilePixmap);
nodeInstanceView()->render(&painter, pixmap.rect(), nodeInstanceView()->sceneRect());
setBackCurrentState(i, oldState);
nodeInstanceView()->setBlockChangeSignal(false);
Q_ASSERT(oldState == currentState());
return pixmap;
}
void StatesEditorView::sceneChanged()
{
// If we are in base state we have to update the pixmaps of all states
// otherwise only the pixmpap for the current state
if (currentState().isValid()) { //during setup we might get sceneChanged signals with an invalid currentState()
if (currentState().isBaseState()) {
for (int i = 0; i < m_modelStates.count(); ++i)
startUpdateTimer(i, i * 80);
} else {
startUpdateTimer(modelStateIndex(currentState()) + 1, 0);
}
}
}
void StatesEditorView::startUpdateTimer(int i, int offset) {
if (i < m_updateTimerIdList.size() && m_updateTimerIdList.at(i) != 0)
return;
// TODO: Add an offset so not all states are rendered at once
Q_ASSERT(i >= 0 && i < m_modelStates.count());
if (i < m_updateTimerIdList.size() && i > 0)
if (m_updateTimerIdList.at(i))
killTimer(m_updateTimerIdList.at(i));
int j = i;
while (m_updateTimerIdList.size() <= i) {
m_updateTimerIdList.insert(j, 0);
j++;
}
m_updateTimerIdList[i] = startTimer(100 + offset);
}
// index without base state
void StatesEditorView::insertModelState(int i, const QmlModelState &state)
{
Q_ASSERT(state.isValid());
Q_ASSERT(!state.isBaseState());
// For m_modelStates / m_editorModel, i=0 is base state
m_modelStates.insert(i+1, state);
m_editorModel->insertState(i+1, state.name());
}
void StatesEditorView::removeModelState(const QmlModelState &state)
{
Q_ASSERT(state.isValid());
Q_ASSERT(!state.isBaseState());
int index = m_modelStates.indexOf(state);
if (index != -1) {
m_modelStates.removeOne(state);
if (m_updateTimerIdList.contains(index)) {
killTimer(m_updateTimerIdList[index]);
m_updateTimerIdList[index] = 0;
}
m_editorModel->removeState(index);
}
}
void StatesEditorView::clearModelStates()
{
// For m_modelStates / m_editorModel, i=0 is base state
while (m_modelStates.size()) {
m_modelStates.removeFirst();
m_editorModel->removeState(0);
}
}
// index without base state
int StatesEditorView::modelStateIndex(const QmlModelState &state)
{
return m_modelStates.indexOf(state) - 1;
}
void StatesEditorView::timerEvent(QTimerEvent *event)
{
int index = m_updateTimerIdList.indexOf(event->timerId());
if (index > -1) {
event->accept();
Q_ASSERT(index >= 0);
if (index < m_modelStates.count()) //there might be updates for a state already deleted 100ms are long
m_editorModel->updateState(index);
killTimer(m_updateTimerIdList[index]);
m_updateTimerIdList[index] = 0;
} else {
QmlModelView::timerEvent(event);
}
}
} // namespace Internal
} // namespace QmlDesigner
<commit_msg>QmlDesigner.statesEditor: updating of thumbnails when propertiesAboutToBeRemoved<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** 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.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/
#include "stateseditorview.h"
#include "stateseditormodel.h"
#include <customnotifications.h>
#include <QPainter>
#include <QTimerEvent>
#include <QDebug>
enum {
debug = false
};
namespace QmlDesigner {
namespace Internal {
/**
We always have 'one' current state, where we get updates from (see sceneChanged()). In case
the current state is the base state, we render the base state + all other states.
*/
StatesEditorView::StatesEditorView(StatesEditorModel *editorModel, QObject *parent) :
QmlModelView(parent),
m_editorModel(editorModel)
{
Q_ASSERT(m_editorModel);
connect(nodeInstanceView(), SIGNAL(instanceRemoved(NodeInstance)), this, SLOT(sceneChanged()));
connect(nodeInstanceView(), SIGNAL(transformPropertyChanged(NodeInstance)), this, SLOT(sceneChanged()));
connect(nodeInstanceView(), SIGNAL(parentPropertyChanged(NodeInstance)), this, SLOT(sceneChanged()));
connect(nodeInstanceView(), SIGNAL(otherPropertyChanged(NodeInstance)), this, SLOT(sceneChanged()));
connect(nodeInstanceView(), SIGNAL(updateItem(NodeInstance)), this, SLOT(sceneChanged()));
}
void StatesEditorView::setCurrentStateSilent(int index)
{
// TODO
QmlModelState state(m_modelStates.at(index));
if (!state.isValid())
return;
if (state == currentState())
return;
QmlModelView::stateChanged(state, currentState());
}
void StatesEditorView::setCurrentState(int index)
{
// TODO
if (m_modelStates.indexOf(currentState()) == index)
return;
if (index >= m_modelStates.count())
return;
QmlModelState state(m_modelStates.at(index));
Q_ASSERT(state.isValid());
QmlModelView::setCurrentState(state);
}
void StatesEditorView::setBackCurrentState(int index, const QmlModelState &oldState)
{
// TODO
QmlModelState state(m_modelStates.at(index));
if (!state.isValid())
return;
if (state == oldState)
return;
QmlModelView::stateChanged(oldState, state);
}
void StatesEditorView::createState(const QString &name)
{
stateRootNode().states().addState(name);
}
void StatesEditorView::removeState(int index)
{
Q_ASSERT(index > 0 && index < m_modelStates.size());
QmlModelState state = m_modelStates.at(index);
Q_ASSERT(state.isValid());
m_modelStates.removeAll(state);
m_editorModel->removeState(index);
QmlModelView::setCurrentState(baseState());
state.destroy();
}
void StatesEditorView::renameState(int index,const QString &newName)
{
Q_ASSERT(index > 0 && index < m_modelStates.size());
QmlModelState state = m_modelStates.at(index);
Q_ASSERT(state.isValid());
if (state.name() != newName) {
// Jump to base state for the change
QmlModelState oldState = currentState();
setCurrentStateSilent(0);
state.setName(newName);
setBackCurrentState(0, oldState);
}
}
void StatesEditorView::duplicateCurrentState(int index)
{
Q_ASSERT(index > 0 && index < m_modelStates.size());
QmlModelState state = m_modelStates.at(index);
Q_ASSERT(state.isValid());
QString newName = state.name();
// Strip out numbers at the end of the string
QRegExp regEx(QString("[0-9]+$"));
int numberIndex = newName.indexOf(regEx);
if ((numberIndex != -1) && (numberIndex+regEx.matchedLength()==newName.length()))
newName = newName.left(numberIndex);
int i = 1;
QStringList stateNames = state.stateGroup().names();
while (stateNames.contains(newName + QString::number(i)))
i++;
state.duplicate(newName + QString::number(i));
}
void StatesEditorView::modelAttached(Model *model)
{
if (model == QmlModelView::model())
return;
Q_ASSERT(model);
QmlModelView::modelAttached(model);
Q_ASSERT(m_editorModel->rowCount(QModelIndex()) == 0);
// find top level states
m_stateRootNode = QmlItemNode(rootModelNode());
if (!m_stateRootNode.isValid())
return;
clearModelStates();
// Add base state
m_modelStates.insert(0, baseState());
m_editorModel->insertState(0, baseState().name());
// Add custom states
for (int i = 0; i < m_stateRootNode.states().allStates().size(); ++i) {
QmlModelState state = QmlItemNode(rootModelNode()).states().allStates().at(i);
insertModelState(i, state);
}
}
void StatesEditorView::modelAboutToBeDetached(Model *model)
{
if (debug)
qDebug() << __FUNCTION__;
clearModelStates();
QmlModelView::modelAboutToBeDetached(model);
}
void StatesEditorView::propertiesAboutToBeRemoved(const QList<AbstractProperty>& propertyList)
{
QmlModelView::propertiesAboutToBeRemoved(propertyList);
foreach (const AbstractProperty &property, propertyList) {
// remove all states except base state
if ((property.name()=="states") && (property.parentModelNode().isRootNode())) {
foreach (const QmlModelState &state, m_modelStates) {
if (!state.isBaseState())
removeModelState(state);
}
} else {
ModelNode node (property.parentModelNode().parentProperty().parentModelNode());
if (QmlModelState(node).isValid()) {
startUpdateTimer(modelStateIndex(node) + 1, 0);
} else { //a change to the base state update all
for (int i = 0; i < m_modelStates.count(); ++i)
startUpdateTimer(i, 0);
}
}
}
}
void StatesEditorView::propertiesRemoved(const QList<AbstractProperty>& propertyList)
{
QmlModelView::propertiesRemoved(propertyList);
}
void StatesEditorView::variantPropertiesChanged(const QList<VariantProperty>& propertyList, PropertyChangeFlags propertyChange)
{
QmlModelView::variantPropertiesChanged(propertyList, propertyChange);
foreach (const VariantProperty &property, propertyList) {
ModelNode node (property.parentModelNode());
if (QmlModelState(node).isValid() && (property.name() == QLatin1String("name"))) {
int index = m_modelStates.indexOf(node);
if (index != -1)
m_editorModel->renameState(index, property.value().toString());
}
}
foreach (const AbstractProperty &property, propertyList) {
ModelNode node (property.parentModelNode().parentProperty().parentModelNode());
if (QmlModelState(node).isValid()) {
startUpdateTimer(modelStateIndex(node) + 1, 0);
} else { //a change to the base state update all
for (int i = 0; i < m_modelStates.count(); ++i)
startUpdateTimer(i, 0);
}
}
}
void StatesEditorView::nodeAboutToBeRemoved(const ModelNode &removedNode)
{
if (removedNode.parentProperty().parentModelNode() == m_stateRootNode
&& QmlModelState(removedNode).isValid()) {
removeModelState(removedNode);
}
QmlModelView::nodeAboutToBeRemoved(removedNode);
}
void StatesEditorView::nodeReparented(const ModelNode &node, const NodeAbstractProperty &newPropertyParent, const NodeAbstractProperty &oldPropertyParent, AbstractView::PropertyChangeFlags propertyChange)
{
QmlModelView::nodeReparented(node, newPropertyParent, oldPropertyParent, propertyChange);
// this would be sliding
Q_ASSERT(newPropertyParent != oldPropertyParent);
if (QmlModelState(node).isValid()) {
if (oldPropertyParent.parentModelNode() == m_stateRootNode) {
if (oldPropertyParent.isNodeListProperty()
&& oldPropertyParent.name() == "states") {
removeModelState(node);
} else {
qWarning() << "States Editor: Reparented model state was not in states property list";
}
}
if (newPropertyParent.parentModelNode() == m_stateRootNode) {
if (newPropertyParent.isNodeListProperty()
&& newPropertyParent.name() == "states") {
NodeListProperty statesProperty = newPropertyParent.toNodeListProperty();
int index = statesProperty.toModelNodeList().indexOf(node);
Q_ASSERT(index >= 0);
insertModelState(index, node);
} else {
qWarning() << "States Editor: Reparented model state is not in the states property list";
}
}
}
}
void StatesEditorView::nodeSlidedToIndex(const NodeListProperty &listProperty, int newIndex, int oldIndex)
{
QmlModelView::nodeSlidedToIndex(listProperty, newIndex, oldIndex);
if (listProperty.parentModelNode() == m_stateRootNode
&& listProperty.name() == "states") {
int index = newIndex;
if (oldIndex < newIndex)
--index;
QmlModelState state = listProperty.toModelNodeList().at(index);
if (state.isValid()) {
Q_ASSERT(oldIndex == modelStateIndex(state));
removeModelState(state);
insertModelState(newIndex, state);
Q_ASSERT(newIndex == modelStateIndex(state));
}
}
}
void StatesEditorView::stateChanged(const QmlModelState &newQmlModelState, const QmlModelState &oldQmlModelState)
{
QmlModelView::stateChanged(newQmlModelState, oldQmlModelState);
if (newQmlModelState.isBaseState())
m_editorModel->emitChangedToState(0);
else
m_editorModel->emitChangedToState(m_modelStates.indexOf(newQmlModelState));
}
void StatesEditorView::customNotification(const AbstractView *view, const QString &identifier, const QList<ModelNode> &nodeList, const QList<QVariant> &data)
{
QmlModelView::customNotification(view, identifier, nodeList, data);
if (identifier == StartRewriterAmend) {
m_oldRewriterAmendState = currentState();
QmlModelView::setCurrentState(baseState());
} else if (identifier == EndRewriterAmend) {
if (m_oldRewriterAmendState.isValid())
QmlModelView::setCurrentState(m_oldRewriterAmendState);
}
}
QPixmap StatesEditorView::renderState(int i)
{
Q_ASSERT(i >= 0 && i < m_modelStates.size());
nodeInstanceView()->setBlockChangeSignal(true);
QmlModelState oldState = currentState();
setCurrentStateSilent(i);
Q_ASSERT(nodeInstanceView());
const int checkerbordSize= 10;
QPixmap tilePixmap(checkerbordSize * 2, checkerbordSize * 2);
tilePixmap.fill(Qt::white);
QPainter tilePainter(&tilePixmap);
QColor color(220, 220, 220);
tilePainter.fillRect(0, 0, checkerbordSize, checkerbordSize, color);
tilePainter.fillRect(checkerbordSize, checkerbordSize, checkerbordSize, checkerbordSize, color);
tilePainter.end();
QSize pixmapSize(nodeInstanceView()->sceneRect().size().toSize());
if (pixmapSize.width() > 150 || pixmapSize.height() > 150) // sensible maximum size
pixmapSize.scale(QSize(150, 150), Qt::KeepAspectRatio);
QPixmap pixmap(pixmapSize);
QPainter painter(&pixmap);
painter.drawTiledPixmap(pixmap.rect(), tilePixmap);
nodeInstanceView()->render(&painter, pixmap.rect(), nodeInstanceView()->sceneRect());
setBackCurrentState(i, oldState);
nodeInstanceView()->setBlockChangeSignal(false);
Q_ASSERT(oldState == currentState());
return pixmap;
}
void StatesEditorView::sceneChanged()
{
// If we are in base state we have to update the pixmaps of all states
// otherwise only the pixmpap for the current state
if (currentState().isValid()) { //during setup we might get sceneChanged signals with an invalid currentState()
if (currentState().isBaseState()) {
for (int i = 0; i < m_modelStates.count(); ++i)
startUpdateTimer(i, i * 80);
} else {
startUpdateTimer(modelStateIndex(currentState()) + 1, 0);
}
}
}
void StatesEditorView::startUpdateTimer(int i, int offset) {
if (i < m_updateTimerIdList.size() && m_updateTimerIdList.at(i) != 0)
return;
// TODO: Add an offset so not all states are rendered at once
Q_ASSERT(i >= 0 && i < m_modelStates.count());
if (i < m_updateTimerIdList.size() && i > 0)
if (m_updateTimerIdList.at(i))
killTimer(m_updateTimerIdList.at(i));
int j = i;
while (m_updateTimerIdList.size() <= i) {
m_updateTimerIdList.insert(j, 0);
j++;
}
m_updateTimerIdList[i] = startTimer(100 + offset);
}
// index without base state
void StatesEditorView::insertModelState(int i, const QmlModelState &state)
{
Q_ASSERT(state.isValid());
Q_ASSERT(!state.isBaseState());
// For m_modelStates / m_editorModel, i=0 is base state
m_modelStates.insert(i+1, state);
m_editorModel->insertState(i+1, state.name());
}
void StatesEditorView::removeModelState(const QmlModelState &state)
{
Q_ASSERT(state.isValid());
Q_ASSERT(!state.isBaseState());
int index = m_modelStates.indexOf(state);
if (index != -1) {
m_modelStates.removeOne(state);
if (m_updateTimerIdList.contains(index)) {
killTimer(m_updateTimerIdList[index]);
m_updateTimerIdList[index] = 0;
}
m_editorModel->removeState(index);
}
}
void StatesEditorView::clearModelStates()
{
// For m_modelStates / m_editorModel, i=0 is base state
while (m_modelStates.size()) {
m_modelStates.removeFirst();
m_editorModel->removeState(0);
}
}
// index without base state
int StatesEditorView::modelStateIndex(const QmlModelState &state)
{
return m_modelStates.indexOf(state) - 1;
}
void StatesEditorView::timerEvent(QTimerEvent *event)
{
int index = m_updateTimerIdList.indexOf(event->timerId());
if (index > -1) {
event->accept();
Q_ASSERT(index >= 0);
if (index < m_modelStates.count()) //there might be updates for a state already deleted 100ms are long
m_editorModel->updateState(index);
killTimer(m_updateTimerIdList[index]);
m_updateTimerIdList[index] = 0;
} else {
QmlModelView::timerEvent(event);
}
}
} // namespace Internal
} // namespace QmlDesigner
<|endoftext|>
|
<commit_before>/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "CmsTemplateTest.h"
#include <integration/IntegrationCommon.h>
#include <decaf/lang/Thread.h>
#include <activemq/connector/stomp/StompConnector.h>
#include <decaf/util/Properties.h>
#include <activemq/transport/TransportFactory.h>
#include <decaf/util/UUID.h>
#include <decaf/util/Properties.h>
#include <decaf/util/StringTokenizer.h>
#include <activemq/connector/ConnectorFactoryMap.h>
#include <decaf/net/SocketFactory.h>
#include <activemq/transport/TransportFactory.h>
#include <decaf/net/Socket.h>
#include <decaf/lang/exceptions/NullPointerException.h>
#include <activemq/core/ActiveMQConnectionFactory.h>
#include <activemq/core/ActiveMQConnection.h>
#include <activemq/core/ActiveMQConsumer.h>
#include <activemq/core/ActiveMQProducer.h>
#include <decaf/util/StringTokenizer.h>
#include <decaf/lang/Boolean.h>
#include <cms/Connection.h>
#include <cms/MessageConsumer.h>
#include <cms/MessageProducer.h>
#include <cms/MessageListener.h>
#include <cms/Startable.h>
#include <cms/Closeable.h>
#include <cms/MessageListener.h>
#include <cms/ExceptionListener.h>
#include <cms/Topic.h>
#include <cms/Queue.h>
#include <cms/TemporaryTopic.h>
#include <cms/TemporaryQueue.h>
#include <cms/Session.h>
#include <cms/BytesMessage.h>
#include <cms/TextMessage.h>
#include <cms/MapMessage.h>
using namespace activemq::connector::stomp;
using namespace activemq::transport;
using namespace activemq::util;
using namespace std;
using namespace cms;
using namespace activemq;
using namespace activemq::core;
using namespace activemq::util;
using namespace activemq::connector;
using namespace activemq::exceptions;
using namespace decaf::net;
using namespace activemq::transport;
using namespace decaf::util::concurrent;
using namespace decaf::lang;
using namespace decaf::util;
using namespace integration;
using namespace integration::connector::stomp;
using namespace activemq::cmsutil;
////////////////////////////////////////////////////////////////////////////////
void CmsTemplateTest::setUp() {
}
////////////////////////////////////////////////////////////////////////////////
void CmsTemplateTest::tearDown() {
}
////////////////////////////////////////////////////////////////////////////////
void CmsTemplateTest::testBasics()
{
try {
Receiver receiver( IntegrationCommon::getInstance().getStompURL(),
false,
"test",
IntegrationCommon::defaultMsgCount);
Thread rt(&receiver);
rt.start();
Sender sender( IntegrationCommon::getInstance().getStompURL(),
false,
"test",
IntegrationCommon::defaultMsgCount);
Thread st(&sender);
st.start();
st.join();
rt.join();
unsigned int numReceived = receiver.getNumReceived();
if( IntegrationCommon::debug ) {
printf("received: %d\n", numReceived );
}
CPPUNIT_ASSERT(
numReceived == IntegrationCommon::defaultMsgCount );
}
AMQ_CATCH_RETHROW( ActiveMQException )
}
////////////////////////////////////////////////////////////////////////////////
void CmsTemplateTest::testReceiveException()
{
try {
activemq::core::ActiveMQConnectionFactory cf("tcp://localhost:61666"); // Invalid URL (at least by default)
activemq::cmsutil::CmsTemplate cmsTemplate(&cf);
cmsTemplate.setDefaultDestinationName("hello");
cmsTemplate.init();
cmsTemplate.receive();
CPPUNIT_FAIL("failed to throw expected exception");
}
catch( ActiveMQException& ex) {
// Expected.
}
}
////////////////////////////////////////////////////////////////////////////////
void CmsTemplateTest::testSendException()
{
try {
activemq::core::ActiveMQConnectionFactory cf("tcp://localhost:61666"); // Invalid URL (at least by default)
activemq::cmsutil::CmsTemplate cmsTemplate(&cf);
cmsTemplate.setDefaultDestinationName("hello");
cmsTemplate.init();
TextMessageCreator msgCreator("hello world");
cmsTemplate.send(&msgCreator);
CPPUNIT_FAIL("failed to throw expected exception");
}
catch( ActiveMQException& ex) {
// Expected.
}
}
<commit_msg>AMQCPP-152 - Adding integ tests for CmsTemplate<commit_after>/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "CmsTemplateTest.h"
#include <integration/IntegrationCommon.h>
#include <decaf/lang/Thread.h>
#include <activemq/connector/stomp/StompConnector.h>
#include <decaf/util/Properties.h>
#include <activemq/transport/TransportFactory.h>
#include <decaf/util/UUID.h>
#include <decaf/util/Properties.h>
#include <decaf/util/StringTokenizer.h>
#include <activemq/connector/ConnectorFactoryMap.h>
#include <decaf/net/SocketFactory.h>
#include <activemq/transport/TransportFactory.h>
#include <decaf/net/Socket.h>
#include <decaf/lang/exceptions/NullPointerException.h>
#include <activemq/core/ActiveMQConnectionFactory.h>
#include <activemq/core/ActiveMQConnection.h>
#include <activemq/core/ActiveMQConsumer.h>
#include <activemq/core/ActiveMQProducer.h>
#include <decaf/util/StringTokenizer.h>
#include <decaf/lang/Boolean.h>
#include <cms/Connection.h>
#include <cms/MessageConsumer.h>
#include <cms/MessageProducer.h>
#include <cms/MessageListener.h>
#include <cms/Startable.h>
#include <cms/Closeable.h>
#include <cms/MessageListener.h>
#include <cms/ExceptionListener.h>
#include <cms/Topic.h>
#include <cms/Queue.h>
#include <cms/TemporaryTopic.h>
#include <cms/TemporaryQueue.h>
#include <cms/Session.h>
#include <cms/BytesMessage.h>
#include <cms/TextMessage.h>
#include <cms/MapMessage.h>
using namespace activemq::connector::stomp;
using namespace activemq::transport;
using namespace activemq::util;
using namespace std;
using namespace cms;
using namespace activemq;
using namespace activemq::core;
using namespace activemq::util;
using namespace activemq::connector;
using namespace activemq::exceptions;
using namespace decaf::net;
using namespace activemq::transport;
using namespace decaf::util::concurrent;
using namespace decaf::lang;
using namespace decaf::util;
using namespace integration;
using namespace integration::connector::stomp;
using namespace activemq::cmsutil;
////////////////////////////////////////////////////////////////////////////////
void CmsTemplateTest::setUp() {
}
////////////////////////////////////////////////////////////////////////////////
void CmsTemplateTest::tearDown() {
}
////////////////////////////////////////////////////////////////////////////////
void CmsTemplateTest::testBasics()
{
try {
Receiver receiver( IntegrationCommon::getInstance().getStompURL(),
false,
"test",
IntegrationCommon::defaultMsgCount);
Thread rt(&receiver);
rt.start();
Sender sender( IntegrationCommon::getInstance().getStompURL(),
false,
"test",
IntegrationCommon::defaultMsgCount);
Thread st(&sender);
st.start();
st.join();
rt.join();
unsigned int numReceived = receiver.getNumReceived();
if( IntegrationCommon::debug ) {
printf("received: %d\n", numReceived );
}
CPPUNIT_ASSERT(
numReceived == IntegrationCommon::defaultMsgCount );
}
AMQ_CATCH_RETHROW( ActiveMQException )
}
////////////////////////////////////////////////////////////////////////////////
void CmsTemplateTest::testReceiveException()
{
// First, try receiving from a bad url
activemq::core::ActiveMQConnectionFactory cf("tcp://localhost:61666"); // Invalid URL (at least by default)
activemq::cmsutil::CmsTemplate cmsTemplate(&cf);
cmsTemplate.setDefaultDestinationName("hello");
cmsTemplate.init();
try {
cmsTemplate.receive();
CPPUNIT_FAIL("failed to throw expected exception");
}
catch( ActiveMQException& ex) {
// Expected.
}
// Now change to a good url and verify that we can reuse the same
// CmsTemplate successfully.
activemq::core::ActiveMQConnectionFactory cf2(IntegrationCommon::getInstance().getStompURL());
cmsTemplate.setConnectionFactory(&cf2);
// Send 1 message.
Sender sender( IntegrationCommon::getInstance().getStompURL(),
false,
"hello",
1);
Thread st(&sender);
st.start();
// Receive the message.
cms::Message* message = cmsTemplate.receive();
CPPUNIT_ASSERT(message != NULL);
delete message;
}
////////////////////////////////////////////////////////////////////////////////
void CmsTemplateTest::testSendException()
{
// First, try sending to a bad url.
activemq::core::ActiveMQConnectionFactory cf("tcp://localhost:61666"); // Invalid URL (at least by default)
activemq::cmsutil::CmsTemplate cmsTemplate(&cf);
cmsTemplate.setDefaultDestinationName("hello");
cmsTemplate.init();
try {
TextMessageCreator msgCreator("hello world");
cmsTemplate.send(&msgCreator);
CPPUNIT_FAIL("failed to throw expected exception");
}
catch( ActiveMQException& ex) {
// Expected.
}
// Now change to a good url and verify that we can reuse the same
// CmsTemplate successfully.
activemq::core::ActiveMQConnectionFactory cf2(IntegrationCommon::getInstance().getStompURL());
cmsTemplate.setConnectionFactory(&cf2);
TextMessageCreator msgCreator("hello world");
cmsTemplate.send(&msgCreator);
}
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2012 Carsten Burstedde, Donna Calhoun
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 "bump_user.h"
#include <fclaw2d_include_all.h>
#include <fclaw2d_clawpatch_options.h>
#include <fclaw2d_clawpatch.h>
#include <fc2d_clawpack46_options.h>
#include <fc2d_clawpack5_options.h>
#include <fc2d_cudaclaw_options.h>
#include <fc2d_clawpack46.h>
#include <fc2d_clawpack5.h>
#include <fc2d_cudaclaw.h>
#include <fc2d_cuda_profiler.h>
static
fclaw2d_domain_t* create_domain(sc_MPI_Comm mpicomm,
fclaw_options_t* fclaw_opt,
user_options_t* user)
{
/* Mapped, multi-block domain */
p4est_connectivity_t *conn = NULL;
fclaw2d_domain_t *domain;
fclaw2d_map_context_t *cont = NULL;
switch (user->example)
{
case 0:
/* Use [ax,bx]x[ay,by] */
conn = p4est_connectivity_new_unitsquare();
cont = fclaw2d_map_new_nomap();
break;
case 1:
printf("Warning : Five patch square not tested.");
exit(0);
conn = p4est_connectivity_new_unitsquare();
cont = fclaw2d_map_new_fivepatch(fclaw_opt->scale,user->alpha);
break;
default:
SC_ABORT_NOT_REACHED ();
}
domain = fclaw2d_domain_new_conn_map (mpicomm, fclaw_opt->minlevel, conn, cont);
fclaw2d_domain_list_levels(domain, FCLAW_VERBOSITY_ESSENTIAL);
fclaw2d_domain_list_neighbors(domain, FCLAW_VERBOSITY_DEBUG);
return domain;
}
static
void run_program(fclaw2d_global_t* glob)
{
/* ---------------------------------------------------------------
Set domain data.
--------------------------------------------------------------- */
fclaw2d_domain_data_new(glob->domain);
user_options_t* user_opt = bump_get_options(glob);
/* Initialize virtual table for ForestClaw */
fclaw2d_vtables_initialize(glob);
/* Initialize virtual tables for solvers */
if(user_opt->cuda)
{
fc2d_cudaclaw_options_t *clawopt = fc2d_cudaclaw_get_options(glob);
fc2d_cudaclaw_initialize_GPUs(glob);
/* this has to be done after GPUs have been initialized */
cudaclaw_set_method_parameters(clawopt->order, clawopt->mthlim, clawopt->mwaves);
fc2d_cudaclaw_solver_initialize();
}
else
{
if (user_opt->claw_version == 4)
{
fc2d_clawpack46_solver_initialize();
}
else if (user_opt->claw_version == 5)
{
fc2d_clawpack5_solver_initialize();
}
}
bump_link_solvers(glob);
/* ---------------------------------------------------------------
Run
--------------------------------------------------------------- */
if (user_opt->cuda == 1)
{
PROFILE_CUDA_GROUP("Allocate GPU and GPU buffers",1);
fc2d_cudaclaw_allocate_buffers(glob);
}
fclaw2d_initialize(glob);
fclaw2d_run(glob);
if (user_opt->cuda == 1)
{
PROFILE_CUDA_GROUP("De-allocate GPU and GPU buffers",1);
fc2d_cudaclaw_deallocate_buffers(glob);
}
fclaw2d_finalize(glob);
}
int
main (int argc, char **argv)
{
fclaw_app_t *app;
int first_arg;
fclaw_exit_type_t vexit;
/* Options */
sc_options_t *options;
user_options_t *user_opt;
fclaw_options_t *fclaw_opt;
fclaw2d_clawpatch_options_t *clawpatch_opt;
fc2d_clawpack46_options_t *claw46_opt;
fc2d_clawpack5_options_t *claw5_opt;
fc2d_cudaclaw_options_t *cuclaw5_opt;
fclaw2d_global_t *glob;
fclaw2d_domain_t *domain;
sc_MPI_Comm mpicomm;
int retval;
/* Initialize application */
app = fclaw_app_new (&argc, &argv, NULL);
/* Create new options packages */
fclaw_opt = fclaw_options_register(app,"fclaw_options.ini");
clawpatch_opt = fclaw2d_clawpatch_options_register(app,"fclaw_options.ini");
claw46_opt = fc2d_clawpack46_options_register(app,"fclaw_options.ini");
claw5_opt = fc2d_clawpack5_options_register(app,"fclaw_options.ini");
cuclaw_opt = fc2d_cudaclaw_options_register(app,"fclaw_options.ini");
user_opt = bump_options_register(app,"fclaw_options.ini");
/* Read configuration file(s) and command line, and process options */
options = fclaw_app_get_options (app);
retval = fclaw_options_read_from_file(options);
vexit = fclaw_app_options_parse (app, &first_arg,"fclaw_options.ini.used");
/* Run the program */
if (!retval & !vexit)
{
/* Options have been checked and are valid */
mpicomm = fclaw_app_get_mpi_size_rank (app, NULL, NULL);
domain = create_domain(mpicomm, fclaw_opt,user_opt);
/* Create global structure which stores the domain, timers, etc */
glob = fclaw2d_global_new();
fclaw2d_global_store_domain(glob, domain);
/* Store option packages in glob */
fclaw2d_options_store (glob, fclaw_opt);
fclaw2d_clawpatch_options_store (glob, clawpatch_opt);
fc2d_clawpack46_options_store (glob, claw46_opt);
fc2d_clawpack5_options_store (glob, claw5_opt);
fc2d_cudaclaw_options_store (glob, cuclaw_opt);
bump_options_store (glob, user_opt);
run_program(glob);
fclaw2d_global_destroy(glob);
}
fclaw_app_destroy (app);
return 0;
}
<commit_msg>(cuda/bump) Fix call to method_parameter<commit_after>/*
Copyright (c) 2012 Carsten Burstedde, Donna Calhoun
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 "bump_user.h"
#include <fclaw2d_include_all.h>
#include <fclaw2d_clawpatch_options.h>
#include <fclaw2d_clawpatch.h>
#include <fc2d_clawpack46_options.h>
#include <fc2d_clawpack5_options.h>
#include <fc2d_cudaclaw_options.h>
#include <fc2d_clawpack46.h>
#include <fc2d_clawpack5.h>
#include <fc2d_cudaclaw.h>
#include <fc2d_cuda_profiler.h>
static
fclaw2d_domain_t* create_domain(sc_MPI_Comm mpicomm,
fclaw_options_t* fclaw_opt,
user_options_t* user)
{
/* Mapped, multi-block domain */
p4est_connectivity_t *conn = NULL;
fclaw2d_domain_t *domain;
fclaw2d_map_context_t *cont = NULL;
switch (user->example)
{
case 0:
/* Use [ax,bx]x[ay,by] */
conn = p4est_connectivity_new_unitsquare();
cont = fclaw2d_map_new_nomap();
break;
case 1:
printf("Warning : Five patch square not tested.");
exit(0);
conn = p4est_connectivity_new_unitsquare();
cont = fclaw2d_map_new_fivepatch(fclaw_opt->scale,user->alpha);
break;
default:
SC_ABORT_NOT_REACHED ();
}
domain = fclaw2d_domain_new_conn_map (mpicomm, fclaw_opt->minlevel, conn, cont);
fclaw2d_domain_list_levels(domain, FCLAW_VERBOSITY_ESSENTIAL);
fclaw2d_domain_list_neighbors(domain, FCLAW_VERBOSITY_DEBUG);
return domain;
}
static
void run_program(fclaw2d_global_t* glob)
{
/* ---------------------------------------------------------------
Set domain data.
--------------------------------------------------------------- */
fclaw2d_domain_data_new(glob->domain);
user_options_t* user_opt = bump_get_options(glob);
/* Initialize virtual table for ForestClaw */
fclaw2d_vtables_initialize(glob);
/* Initialize virtual tables for solvers */
if(user_opt->cuda)
{
fc2d_cudaclaw_options_t *clawopt = fc2d_cudaclaw_get_options(glob);
fc2d_cudaclaw_initialize_GPUs(glob);
/* this has to be done after GPUs have been initialized */
cudaclaw_set_method_parameters(clawopt->order,
clawopt->mthlim,
clawopt->mwaves,
clawopt->use_fwaves);
fc2d_cudaclaw_solver_initialize();
}
else
{
if (user_opt->claw_version == 4)
{
fc2d_clawpack46_solver_initialize();
}
else if (user_opt->claw_version == 5)
{
fc2d_clawpack5_solver_initialize();
}
}
bump_link_solvers(glob);
/* ---------------------------------------------------------------
Run
--------------------------------------------------------------- */
if (user_opt->cuda == 1)
{
PROFILE_CUDA_GROUP("Allocate GPU and GPU buffers",1);
fc2d_cudaclaw_allocate_buffers(glob);
}
fclaw2d_initialize(glob);
fclaw2d_run(glob);
if (user_opt->cuda == 1)
{
PROFILE_CUDA_GROUP("De-allocate GPU and GPU buffers",1);
fc2d_cudaclaw_deallocate_buffers(glob);
}
fclaw2d_finalize(glob);
}
int
main (int argc, char **argv)
{
fclaw_app_t *app;
int first_arg;
fclaw_exit_type_t vexit;
/* Options */
sc_options_t *options;
user_options_t *user_opt;
fclaw_options_t *fclaw_opt;
fclaw2d_clawpatch_options_t *clawpatch_opt;
fc2d_clawpack46_options_t *claw46_opt;
fc2d_clawpack5_options_t *claw5_opt;
fc2d_cudaclaw_options_t *cuclaw5_opt;
fclaw2d_global_t *glob;
fclaw2d_domain_t *domain;
sc_MPI_Comm mpicomm;
int retval;
/* Initialize application */
app = fclaw_app_new (&argc, &argv, NULL);
/* Create new options packages */
fclaw_opt = fclaw_options_register(app,"fclaw_options.ini");
clawpatch_opt = fclaw2d_clawpatch_options_register(app,"fclaw_options.ini");
claw46_opt = fc2d_clawpack46_options_register(app,"fclaw_options.ini");
claw5_opt = fc2d_clawpack5_options_register(app,"fclaw_options.ini");
cuclaw_opt = fc2d_cudaclaw_options_register(app,"fclaw_options.ini");
user_opt = bump_options_register(app,"fclaw_options.ini");
/* Read configuration file(s) and command line, and process options */
options = fclaw_app_get_options (app);
retval = fclaw_options_read_from_file(options);
vexit = fclaw_app_options_parse (app, &first_arg,"fclaw_options.ini.used");
/* Run the program */
if (!retval & !vexit)
{
/* Options have been checked and are valid */
mpicomm = fclaw_app_get_mpi_size_rank (app, NULL, NULL);
domain = create_domain(mpicomm, fclaw_opt,user_opt);
/* Create global structure which stores the domain, timers, etc */
glob = fclaw2d_global_new();
fclaw2d_global_store_domain(glob, domain);
/* Store option packages in glob */
fclaw2d_options_store (glob, fclaw_opt);
fclaw2d_clawpatch_options_store (glob, clawpatch_opt);
fc2d_clawpack46_options_store (glob, claw46_opt);
fc2d_clawpack5_options_store (glob, claw5_opt);
fc2d_cudaclaw_options_store (glob, cuclaw_opt);
bump_options_store (glob, user_opt);
run_program(glob);
fclaw2d_global_destroy(glob);
}
fclaw_app_destroy (app);
return 0;
}
<|endoftext|>
|
<commit_before>/****************************************************************************
*
* Copyright (C) 2018 PX4 Development Team. 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 PX4 nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/**
* @file BerzierQuad.hpp
*
* Quadratic bezier lib
*
* A quadratic bezier function/spline is completely defined by three 3D points in space and a time scaling factor.
* pt0 and pt1 define the start and end points of the spline. ctrl point is a point in space that effects the curvature
* of the spline. The time scaling factor (= duration) defines the time it takes to travel along the spline from pt0 to
* pt1.
* A bezier spline is a continuous function from which position, velocity and acceleration can be extracted. For a given spline,
* acceleration stays constant.
*/
#pragma once
#include <matrix/math.hpp>
namespace bezier
{
template<typename Tp>
class BezierQuad
{
public:
using Vector3_t = matrix::Vector<Tp, 3>;
/**
* Empty constructor
*/
BezierQuad(void) :
_pt0(Vector3_t()), _ctrl(Vector3_t()), _pt1(Vector3_t()), _duration(1.0f) {}
/**
* Constructor from array
*/
BezierQuad(const Tp pt0[3], const Tp ctrl[3], const Tp pt1[3], Tp duration = 1.0f) :
_pt0(Vector3_t(pt0)), _ctrl(Vector3_t(ctrl)), _pt1(Vector3_t(pt1)), _duration(duration) {}
/**
* Constructor from vector
*/
BezierQuad(const Vector3_t &pt0, const Vector3_t &ctrl, const Vector3_t &pt1,
Tp duration = 1.0f):
_pt0(pt0), _ctrl(ctrl), _pt1(pt1), _duration(duration) {}
/*
* Get bezier points
*/
void getBezier(Vector3_t &pt0, Vector3_t &ctrl, Vector3_t &pt1);
/*
* Return pt0
*/
Vector3_t getPt0() {return _pt0;}
/*
* Return ctrl
*/
Vector3_t getCtrl() {return _ctrl;}
/*
* Return pt1
*/
Vector3_t getPt1() {return _pt1;}
/**
* Set new bezier points and duration
*/
void setBezier(const Vector3_t &pt0, const Vector3_t &ctrl, const Vector3_t &pt1,
Tp duration = (Tp)1);
/*
* Set duration
*
* @param time is the total time it takes to travel along the bezier spline.
*/
void setDuration(const Tp time) {_duration = time;}
/**
* Return point on bezier point corresponding to time t
*
* @param t is a time in seconds in between [0, duration]
* @return a point on bezier
*/
Vector3_t getPoint(const Tp t);
/*
* Distance to closest point given a position
*
* @param pose is a position in 3D space from which distance to bezier is computed.
* @return distance to closest point on bezier
*/
Tp getDistToClosestPoint(const Vector3_t &pose);
/*
* Return velocity on bezier corresponding to time t
*
* @param t is a time in seconds in between [0, duration]
* @return velocity vector at time t
*/
Vector3_t getVelocity(const Tp t);
/*
* Return acceleration on bezier corresponding to time t
*
* @return constant acceleration of bezier
*/
Vector3_t getAcceleration();
/*
* Get all states on bezier corresponding to time t
*/
void getStates(Vector3_t &point, Vector3_t &vel, Vector3_t &acc, const Tp t);
/*
* Get states on bezier which are closest to pose in space
*
* @param point is a posiiton on the spline that is closest to a given pose
* @param vel is the velocity at that given point
* @param acc is the acceleration for that spline
* @param pose represent a position in space from which closest point is computed
*/
void getStatesClosest(Vector3_t &point, Vector3_t &vel, Vector3_t &acc,
const Vector3_t pose);
/*
* Compute bezier from velocity at bezier end points and ctrl point
*
* The bezier end points are fully defined by a given control point ctrl, the duration and
* the desired velocity vectors at the end points.
*/
void setBezFromVel(const Vector3_t &ctrl, const Vector3_t &vel0, const Vector3_t &vel1,
const Tp duration = (Tp)1);
/*
* Return the arc length of a bezier spline
*
* The arc length is computed with simpsons integration.
* @param resolution in meters.
*/
Tp getArcLength(const Tp resolution);
private:
Vector3_t _pt0; /**< Bezier starting point */
Vector3_t _ctrl; /**< Bezier control point */
Vector3_t _pt1; /**< bezier end point */
Tp _duration = (Tp)1; /**< Total time to travle along spline */
Tp _cached_arc_length = (Tp)0; /**< The saved arc length of the spline */
Tp _cached_resolution = (Tp)(-1); /**< The resolution used to compute the arc length.
Negative number means that cache is not up to date. */
/*
* Golden section search
*/
Tp _goldenSectionSearch(const Vector3_t &pose);
/*
* Get squared distance from 3D pose in space and a point on bezier.
*
* @param t is the time in between [0, duration] that defines a point on the bezier.
* @param pose is a 3D pose in space.
*/
Tp _getDistanceSquared(const Tp t, const Vector3_t &pose);
};
using BezierQuad_f = BezierQuad<float>;
using BezierQuad_d = BezierQuad<double>;
}
// include implementation
#include "BezierQuad.cpp"
<commit_msg>clang modernize: remove void argument<commit_after>/****************************************************************************
*
* Copyright (C) 2018 PX4 Development Team. 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 PX4 nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/**
* @file BerzierQuad.hpp
*
* Quadratic bezier lib
*
* A quadratic bezier function/spline is completely defined by three 3D points in space and a time scaling factor.
* pt0 and pt1 define the start and end points of the spline. ctrl point is a point in space that effects the curvature
* of the spline. The time scaling factor (= duration) defines the time it takes to travel along the spline from pt0 to
* pt1.
* A bezier spline is a continuous function from which position, velocity and acceleration can be extracted. For a given spline,
* acceleration stays constant.
*/
#pragma once
#include <matrix/math.hpp>
namespace bezier
{
template<typename Tp>
class BezierQuad
{
public:
using Vector3_t = matrix::Vector<Tp, 3>;
/**
* Empty constructor
*/
BezierQuad() :
_pt0(Vector3_t()), _ctrl(Vector3_t()), _pt1(Vector3_t()), _duration(1.0f) {}
/**
* Constructor from array
*/
BezierQuad(const Tp pt0[3], const Tp ctrl[3], const Tp pt1[3], Tp duration = 1.0f) :
_pt0(Vector3_t(pt0)), _ctrl(Vector3_t(ctrl)), _pt1(Vector3_t(pt1)), _duration(duration) {}
/**
* Constructor from vector
*/
BezierQuad(const Vector3_t &pt0, const Vector3_t &ctrl, const Vector3_t &pt1,
Tp duration = 1.0f):
_pt0(pt0), _ctrl(ctrl), _pt1(pt1), _duration(duration) {}
/*
* Get bezier points
*/
void getBezier(Vector3_t &pt0, Vector3_t &ctrl, Vector3_t &pt1);
/*
* Return pt0
*/
Vector3_t getPt0() {return _pt0;}
/*
* Return ctrl
*/
Vector3_t getCtrl() {return _ctrl;}
/*
* Return pt1
*/
Vector3_t getPt1() {return _pt1;}
/**
* Set new bezier points and duration
*/
void setBezier(const Vector3_t &pt0, const Vector3_t &ctrl, const Vector3_t &pt1,
Tp duration = (Tp)1);
/*
* Set duration
*
* @param time is the total time it takes to travel along the bezier spline.
*/
void setDuration(const Tp time) {_duration = time;}
/**
* Return point on bezier point corresponding to time t
*
* @param t is a time in seconds in between [0, duration]
* @return a point on bezier
*/
Vector3_t getPoint(const Tp t);
/*
* Distance to closest point given a position
*
* @param pose is a position in 3D space from which distance to bezier is computed.
* @return distance to closest point on bezier
*/
Tp getDistToClosestPoint(const Vector3_t &pose);
/*
* Return velocity on bezier corresponding to time t
*
* @param t is a time in seconds in between [0, duration]
* @return velocity vector at time t
*/
Vector3_t getVelocity(const Tp t);
/*
* Return acceleration on bezier corresponding to time t
*
* @return constant acceleration of bezier
*/
Vector3_t getAcceleration();
/*
* Get all states on bezier corresponding to time t
*/
void getStates(Vector3_t &point, Vector3_t &vel, Vector3_t &acc, const Tp t);
/*
* Get states on bezier which are closest to pose in space
*
* @param point is a posiiton on the spline that is closest to a given pose
* @param vel is the velocity at that given point
* @param acc is the acceleration for that spline
* @param pose represent a position in space from which closest point is computed
*/
void getStatesClosest(Vector3_t &point, Vector3_t &vel, Vector3_t &acc,
const Vector3_t pose);
/*
* Compute bezier from velocity at bezier end points and ctrl point
*
* The bezier end points are fully defined by a given control point ctrl, the duration and
* the desired velocity vectors at the end points.
*/
void setBezFromVel(const Vector3_t &ctrl, const Vector3_t &vel0, const Vector3_t &vel1,
const Tp duration = (Tp)1);
/*
* Return the arc length of a bezier spline
*
* The arc length is computed with simpsons integration.
* @param resolution in meters.
*/
Tp getArcLength(const Tp resolution);
private:
Vector3_t _pt0; /**< Bezier starting point */
Vector3_t _ctrl; /**< Bezier control point */
Vector3_t _pt1; /**< bezier end point */
Tp _duration = (Tp)1; /**< Total time to travle along spline */
Tp _cached_arc_length = (Tp)0; /**< The saved arc length of the spline */
Tp _cached_resolution = (Tp)(-1); /**< The resolution used to compute the arc length.
Negative number means that cache is not up to date. */
/*
* Golden section search
*/
Tp _goldenSectionSearch(const Vector3_t &pose);
/*
* Get squared distance from 3D pose in space and a point on bezier.
*
* @param t is the time in between [0, duration] that defines a point on the bezier.
* @param pose is a 3D pose in space.
*/
Tp _getDistanceSquared(const Tp t, const Vector3_t &pose);
};
using BezierQuad_f = BezierQuad<float>;
using BezierQuad_d = BezierQuad<double>;
}
// include implementation
#include "BezierQuad.cpp"
<|endoftext|>
|
<commit_before>// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/common/native_mate_converters/net_converter.h"
#include <string>
#include <vector>
#include "atom/common/native_mate_converters/gurl_converter.h"
#include "atom/common/native_mate_converters/value_converter.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/values.h"
#include "native_mate/dictionary.h"
#include "net/base/upload_bytes_element_reader.h"
#include "net/base/upload_data_stream.h"
#include "net/base/upload_element_reader.h"
#include "net/base/upload_file_element_reader.h"
#include "net/cert/x509_certificate.h"
#include "net/http/http_response_headers.h"
#include "net/url_request/url_request.h"
#include "storage/browser/blob/upload_blob_element_reader.h"
#include "atom/common/node_includes.h"
namespace mate {
// static
v8::Local<v8::Value> Converter<const net::AuthChallengeInfo*>::ToV8(
v8::Isolate* isolate, const net::AuthChallengeInfo* val) {
mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate);
dict.Set("isProxy", val->is_proxy);
dict.Set("scheme", val->scheme);
dict.Set("host", val->challenger.host());
dict.Set("port", static_cast<uint32_t>(val->challenger.port()));
dict.Set("realm", val->realm);
return mate::ConvertToV8(isolate, dict);
}
// static
v8::Local<v8::Value> Converter<scoped_refptr<net::X509Certificate>>::ToV8(
v8::Isolate* isolate, const scoped_refptr<net::X509Certificate>& val) {
mate::Dictionary dict(isolate, v8::Object::New(isolate));
std::string encoded_data;
net::X509Certificate::GetPEMEncoded(
val->os_cert_handle(), &encoded_data);
dict.Set("data", encoded_data);
dict.Set("issuer", val->issuer());
dict.Set("issuerName", val->issuer().GetDisplayName());
dict.Set("subject", val->subject());
dict.Set("subjectName", val->subject().GetDisplayName());
dict.Set("serialNumber", base::HexEncode(val->serial_number().data(),
val->serial_number().size()));
dict.Set("validStart", val->valid_start().ToDoubleT());
dict.Set("validExpiry", val->valid_expiry().ToDoubleT());
dict.Set("fingerprint",
net::HashValue(
val->CalculateFingerprint256(val->os_cert_handle())).ToString());
auto intermediates = val->GetIntermediateCertificates();
if (!intermediates.empty()) {
net::X509Certificate::OSCertHandles issuer_intermediates(
val->GetIntermediateCertificates().begin() + 1,
val->GetIntermediateCertificates().end());
const scoped_refptr<net::X509Certificate>& issuer_cert =
net::X509Certificate::CreateFromHandle(
val->GetIntermediateCertificates().front(),
issuer_intermediates);
dict.Set("issuerCert", issuer_cert);
std::vector<std::string> intermediates_encoded;
for (size_t i = 0; i < intermediates.size(); i++) {
auto native_cert = intermediates[i];
std::string encoded;
net::X509Certificate::GetPEMEncoded(native_cert, &encoded);
intermediates_encoded.push_back(encoded);
}
dict.Set("intermediates", intermediates_encoded);
}
return dict.GetHandle();
}
bool Converter<scoped_refptr<net::X509Certificate>>::FromV8(
v8::Isolate* isolate, v8::Local<v8::Value> val,
scoped_refptr<net::X509Certificate>* out) {
mate::Dictionary dict;
if (!ConvertFromV8(isolate, val, &dict))
return false;
std::string data;
dict.Get("data", &data);
auto certificate_list = net::X509Certificate::CreateCertificateListFromBytes(
data.c_str(), data.length(),
net::X509Certificate::FORMAT_SINGLE_CERTIFICATE);
if (certificate_list.empty())
return false;
auto certificate = certificate_list.front();
if (!certificate)
return false;
*out = certificate;
return true;
}
// static
v8::Local<v8::Value> Converter<net::CertPrincipal>::ToV8(
v8::Isolate* isolate, const net::CertPrincipal& val) {
mate::Dictionary dict(isolate, v8::Object::New(isolate));
dict.Set("commonName", val.common_name);
dict.Set("organizations", val.organization_names);
dict.Set("organizationUnits", val.organization_unit_names);
dict.Set("locality", val.locality_name);
dict.Set("state", val.state_or_province_name);
dict.Set("country", val.country_name);
return dict.GetHandle();
}
// static
v8::Local<v8::Value> Converter<net::HttpResponseHeaders*>::ToV8(
v8::Isolate* isolate,
net::HttpResponseHeaders* headers) {
base::DictionaryValue response_headers;
if (headers) {
size_t iter = 0;
std::string key;
std::string value;
while (headers->EnumerateHeaderLines(&iter, &key, &value)) {
key = base::ToLowerASCII(key);
if (response_headers.HasKey(key)) {
base::ListValue* values = nullptr;
if (response_headers.GetList(key, &values))
values->AppendString(value);
} else {
std::unique_ptr<base::ListValue> values(new base::ListValue());
values->AppendString(value);
response_headers.Set(key, std::move(values));
}
}
}
return ConvertToV8(isolate, response_headers);
}
} // namespace mate
namespace atom {
void FillRequestDetails(base::DictionaryValue* details,
const net::URLRequest* request) {
details->SetString("method", request->method());
std::string url;
if (!request->url_chain().empty()) url = request->url().spec();
details->SetStringWithoutPathExpansion("url", url);
details->SetString("referrer", request->referrer());
std::unique_ptr<base::ListValue> list(new base::ListValue);
GetUploadData(list.get(), request);
if (!list->empty())
details->Set("uploadData", std::move(list));
}
void GetUploadData(base::ListValue* upload_data_list,
const net::URLRequest* request) {
const net::UploadDataStream* upload_data = request->get_upload();
if (!upload_data)
return;
const std::vector<std::unique_ptr<net::UploadElementReader>>* readers =
upload_data->GetElementReaders();
for (const auto& reader : *readers) {
std::unique_ptr<base::DictionaryValue> upload_data_dict(
new base::DictionaryValue);
if (reader->AsBytesReader()) {
const net::UploadBytesElementReader* bytes_reader =
reader->AsBytesReader();
std::unique_ptr<base::Value> bytes(
base::BinaryValue::CreateWithCopiedBuffer(bytes_reader->bytes(),
bytes_reader->length()));
upload_data_dict->Set("bytes", std::move(bytes));
} else if (reader->AsFileReader()) {
const net::UploadFileElementReader* file_reader =
reader->AsFileReader();
auto file_path = file_reader->path().AsUTF8Unsafe();
upload_data_dict->SetStringWithoutPathExpansion("file", file_path);
} else {
const storage::UploadBlobElementReader* blob_reader =
static_cast<storage::UploadBlobElementReader*>(reader.get());
upload_data_dict->SetString("blobUUID", blob_reader->uuid());
}
upload_data_list->Append(std::move(upload_data_dict));
}
}
} // namespace atom
<commit_msg>Decode all the intermediates<commit_after>// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/common/native_mate_converters/net_converter.h"
#include <string>
#include <vector>
#include "atom/common/native_mate_converters/gurl_converter.h"
#include "atom/common/native_mate_converters/value_converter.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/values.h"
#include "native_mate/dictionary.h"
#include "net/base/upload_bytes_element_reader.h"
#include "net/base/upload_data_stream.h"
#include "net/base/upload_element_reader.h"
#include "net/base/upload_file_element_reader.h"
#include "net/cert/x509_certificate.h"
#include "net/http/http_response_headers.h"
#include "net/url_request/url_request.h"
#include "storage/browser/blob/upload_blob_element_reader.h"
#include "atom/common/node_includes.h"
namespace mate {
// static
v8::Local<v8::Value> Converter<const net::AuthChallengeInfo*>::ToV8(
v8::Isolate* isolate, const net::AuthChallengeInfo* val) {
mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate);
dict.Set("isProxy", val->is_proxy);
dict.Set("scheme", val->scheme);
dict.Set("host", val->challenger.host());
dict.Set("port", static_cast<uint32_t>(val->challenger.port()));
dict.Set("realm", val->realm);
return mate::ConvertToV8(isolate, dict);
}
// static
v8::Local<v8::Value> Converter<scoped_refptr<net::X509Certificate>>::ToV8(
v8::Isolate* isolate, const scoped_refptr<net::X509Certificate>& val) {
mate::Dictionary dict(isolate, v8::Object::New(isolate));
std::string encoded_data;
net::X509Certificate::GetPEMEncoded(
val->os_cert_handle(), &encoded_data);
dict.Set("data", encoded_data);
dict.Set("issuer", val->issuer());
dict.Set("issuerName", val->issuer().GetDisplayName());
dict.Set("subject", val->subject());
dict.Set("subjectName", val->subject().GetDisplayName());
dict.Set("serialNumber", base::HexEncode(val->serial_number().data(),
val->serial_number().size()));
dict.Set("validStart", val->valid_start().ToDoubleT());
dict.Set("validExpiry", val->valid_expiry().ToDoubleT());
dict.Set("fingerprint",
net::HashValue(
val->CalculateFingerprint256(val->os_cert_handle())).ToString());
auto intermediates = val->GetIntermediateCertificates();
if (!intermediates.empty()) {
net::X509Certificate::OSCertHandles issuer_intermediates(
val->GetIntermediateCertificates().begin() + 1,
val->GetIntermediateCertificates().end());
const scoped_refptr<net::X509Certificate>& issuer_cert =
net::X509Certificate::CreateFromHandle(
val->GetIntermediateCertificates().front(),
issuer_intermediates);
dict.Set("issuerCert", issuer_cert);
std::vector<std::string> intermediates_encoded;
for (size_t i = 0; i < intermediates.size(); i++) {
auto native_cert = intermediates[i];
std::string encoded;
net::X509Certificate::GetPEMEncoded(native_cert, &encoded);
intermediates_encoded.push_back(encoded);
}
dict.Set("intermediates", intermediates_encoded);
}
return dict.GetHandle();
}
bool CertFromData(const std::string& data,
scoped_refptr<net::X509Certificate>* out) {
auto cert_list = net::X509Certificate::CreateCertificateListFromBytes(
data.c_str(), data.length(),
net::X509Certificate::FORMAT_SINGLE_CERTIFICATE);
if (cert_list.empty())
return false;
auto leaf_cert = cert_list.front();
if (!leaf_cert)
return false;
*out = leaf_cert;
return true;
}
bool Converter<scoped_refptr<net::X509Certificate>>::FromV8(
v8::Isolate* isolate, v8::Local<v8::Value> val,
scoped_refptr<net::X509Certificate>* out) {
mate::Dictionary dict;
if (!ConvertFromV8(isolate, val, &dict))
return false;
std::string data;
dict.Get("data", &data);
scoped_refptr<net::X509Certificate> leaf_cert;
if (!CertFromData(data, &leaf_cert))
return false;
std::vector<std::string> intermediates_encoded;
dict.Get("intermediates", &intermediates_encoded);
std::vector<net::X509Certificate::OSCertHandle> intermediates;
for (size_t i = 0; i < intermediates_encoded.size(); i++) {
auto data = intermediates_encoded[i];
scoped_refptr<net::X509Certificate> cert;
if (!CertFromData(data, &cert))
return false;
intermediates.push_back(cert->os_cert_handle());
}
auto cert = net::X509Certificate::CreateFromHandle(
leaf_cert->os_cert_handle(), intermediates);
if (!cert)
return false;
*out = cert;
return true;
}
// static
v8::Local<v8::Value> Converter<net::CertPrincipal>::ToV8(
v8::Isolate* isolate, const net::CertPrincipal& val) {
mate::Dictionary dict(isolate, v8::Object::New(isolate));
dict.Set("commonName", val.common_name);
dict.Set("organizations", val.organization_names);
dict.Set("organizationUnits", val.organization_unit_names);
dict.Set("locality", val.locality_name);
dict.Set("state", val.state_or_province_name);
dict.Set("country", val.country_name);
return dict.GetHandle();
}
// static
v8::Local<v8::Value> Converter<net::HttpResponseHeaders*>::ToV8(
v8::Isolate* isolate,
net::HttpResponseHeaders* headers) {
base::DictionaryValue response_headers;
if (headers) {
size_t iter = 0;
std::string key;
std::string value;
while (headers->EnumerateHeaderLines(&iter, &key, &value)) {
key = base::ToLowerASCII(key);
if (response_headers.HasKey(key)) {
base::ListValue* values = nullptr;
if (response_headers.GetList(key, &values))
values->AppendString(value);
} else {
std::unique_ptr<base::ListValue> values(new base::ListValue());
values->AppendString(value);
response_headers.Set(key, std::move(values));
}
}
}
return ConvertToV8(isolate, response_headers);
}
} // namespace mate
namespace atom {
void FillRequestDetails(base::DictionaryValue* details,
const net::URLRequest* request) {
details->SetString("method", request->method());
std::string url;
if (!request->url_chain().empty()) url = request->url().spec();
details->SetStringWithoutPathExpansion("url", url);
details->SetString("referrer", request->referrer());
std::unique_ptr<base::ListValue> list(new base::ListValue);
GetUploadData(list.get(), request);
if (!list->empty())
details->Set("uploadData", std::move(list));
}
void GetUploadData(base::ListValue* upload_data_list,
const net::URLRequest* request) {
const net::UploadDataStream* upload_data = request->get_upload();
if (!upload_data)
return;
const std::vector<std::unique_ptr<net::UploadElementReader>>* readers =
upload_data->GetElementReaders();
for (const auto& reader : *readers) {
std::unique_ptr<base::DictionaryValue> upload_data_dict(
new base::DictionaryValue);
if (reader->AsBytesReader()) {
const net::UploadBytesElementReader* bytes_reader =
reader->AsBytesReader();
std::unique_ptr<base::Value> bytes(
base::BinaryValue::CreateWithCopiedBuffer(bytes_reader->bytes(),
bytes_reader->length()));
upload_data_dict->Set("bytes", std::move(bytes));
} else if (reader->AsFileReader()) {
const net::UploadFileElementReader* file_reader =
reader->AsFileReader();
auto file_path = file_reader->path().AsUTF8Unsafe();
upload_data_dict->SetStringWithoutPathExpansion("file", file_path);
} else {
const storage::UploadBlobElementReader* blob_reader =
static_cast<storage::UploadBlobElementReader*>(reader.get());
upload_data_dict->SetString("blobUUID", blob_reader->uuid());
}
upload_data_list->Append(std::move(upload_data_dict));
}
}
} // namespace atom
<|endoftext|>
|
<commit_before>//
// Copyright (c) 2015 CNRS
// Author: Mylene Campana, Joseph Mirabel
//
//
// This file is part of hpp-core
// hpp-core 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.
//
// hpp-core 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 Lesser Public License for more details. You should have
// received a copy of the GNU Lesser General Public License along with
// hpp-core If not, see
// <http://www.gnu.org/licenses/>.
#ifndef HPP_CORE_PATH_OPTIMIZATION_SPLINE_GRADIENT_BASED_COLLISION_CONSTRAINTS_HH
# define HPP_CORE_PATH_OPTIMIZATION_SPLINE_GRADIENT_BASED_COLLISION_CONSTRAINTS_HH
#include <hpp/util/exception-factory.hh>
# include <hpp/fcl/collision.h>
# include <hpp/fcl/distance.h>
# include <hpp/pinocchio/configuration.hh>
# include <pinocchio/multibody/liegroup/liegroup.hpp>
# include <hpp/constraints/generic-transformation.hh>
namespace hpp {
namespace core {
namespace pathOptimization {
HPP_PREDEF_CLASS (CollisionFunction);
typedef boost::shared_ptr <CollisionFunction> CollisionFunctionPtr_t;
typedef pinocchio::Transform3f Transform3f;
namespace eigen {
typedef Eigen::Matrix <value_type, 3, 1> vector3_t;
} // namespace eigen
class CollisionFunction : public DifferentiableFunction
{
public:
virtual ~CollisionFunction () {}
template <typename SplinePtr_t>
static CollisionFunctionPtr_t create
(const DevicePtr_t& robot, const SplinePtr_t& freeSpline,
const SplinePtr_t& collSpline,
const CollisionPathValidationReportPtr_t& report)
{
const value_type& tColl = report->parameter;
bool success;
Configuration_t qColl = (*collSpline) (tColl, success);
assert(success);
HPP_STATIC_CAST_REF_CHECK (CollisionValidationReport,
*(report->configurationReport));
CollisionObjectConstPtr_t object1 =
HPP_STATIC_PTR_CAST (CollisionValidationReport,
report->configurationReport)->object1;
CollisionObjectConstPtr_t object2 =
HPP_STATIC_PTR_CAST (CollisionValidationReport,
report->configurationReport)->object2;
hppDout (info, "Collision at ratio (in [0,1]) = " << tColl / collSpline->length());
hppDout (info, "obj1 = " << object1->name()
<< " and obj2 = " << object2->name());
hppDout (info, "qColl = " << qColl.transpose());
// Backtrack collision in previous path (x0) to create constraint
value_type tFree = tColl * freeSpline->length () / collSpline->length();
Configuration_t qFree = (*freeSpline) (tFree, success);
assert(success);
hppDout (info, "qFree = " << qFree.transpose());
return create (robot, qFree, qColl, object1, object2);
}
static CollisionFunctionPtr_t create
(const DevicePtr_t& robot, const Configuration_t& qFree,
const Configuration_t& qColl, const CollisionObjectConstPtr_t& object1,
const CollisionObjectConstPtr_t& object2)
{
CollisionFunction* ptr = new CollisionFunction
(robot, qFree, qColl, object1, object2);
CollisionFunctionPtr_t shPtr (ptr);
return shPtr;
}
protected:
CollisionFunction (const DevicePtr_t& robot,
const Configuration_t& qFree,
const Configuration_t& qColl,
const CollisionObjectConstPtr_t& object1,
const CollisionObjectConstPtr_t& object2)
: DifferentiableFunction (robot->configSize (), robot->numberDof (),
1, ""), robot_ (robot), qFree_ (qFree),
J_ (), difference_ ()
{
difference_.resize (robot->numberDof ());
// Compute contact point in configuration qColl
robot_->currentConfiguration (qColl);
robot_->computeForwardKinematics ();
robot_->updateGeometryPlacements ();
fcl::CollisionResult result;
fcl::CollisionRequest collisionRequest (1, true, false, 1, false, true, fcl::GST_INDEP);
fcl::collide (object1->fcl (), object2->fcl (), collisionRequest, result);
if (result.numContacts() != 1) {
result.clear();
collisionRequest.enable_contact = false;
fcl::collide (object1->fcl (), object2->fcl (), collisionRequest, result);
if (result.isCollision()) {
hppDout (error, "FCL does not returns the same result when asking or not for the contact points.");
}
HPP_THROW(std::invalid_argument,
"Object " << object1->name() << " and " << object2->name()
<< " are not in collision in configuration\n"
<< qColl.transpose().format(IPythonFormat)
<< "\nqFree is\n" << qFree.transpose().format(IPythonFormat));
}
assert (result.numContacts () == 1);
const vector3_t& contactPoint (result.getContact (0).pos);
hppDout (info, "contact point = " << contactPoint.transpose());
JointConstPtr_t joint1 = object1->joint ();
// FIXME this copy can probably be avoided.
Transform3f M1 (joint1->currentTransformation ());
if (object2->joint ()) { // object2 = body part
JointConstPtr_t joint2 = object2->joint ();
Transform3f M2 (joint2->currentTransformation ());
// Position of contact point in each object local frame
vector3_t x1_J1 = M1.actInv (contactPoint);
vector3_t x2_J2 = M2.actInv (contactPoint);
// Compute contact points in configuration qFree
robot_->currentConfiguration (qFree);
robot_->computeForwardKinematics ();
M2 = joint2->currentTransformation ();
M1 = joint1->currentTransformation ();
// Position of x2 in local frame of joint1
vector3_t x2_J1 (M1.actInv (M2.act (x2_J2)));
hppDout (info, "x1 in J1 = " << x1_J1.transpose());
hppDout (info, "x2 in J1 = " << x2_J1.transpose());
eigen::vector3_t u=x2_J1 - x1_J1;
matrix3_t rot;
rot.setIdentity();
DifferentiableFunctionPtr_t f = constraints::RelativePosition::create
("", robot_, joint1, joint2, Transform3f(rot,x1_J1), Transform3f(rot,x2_J2));
matrix_t Jpos (f->outputSize (), f->inputDerivativeSize ());
f->jacobian (Jpos, qFree);
J_ = u.transpose () * Jpos;
assert (J_.rows () == 1);
} else{ // object2 = fixed obstacle and has no joint
vector3_t x1_J1 (M1.actInv(contactPoint));
vector3_t x2_J2 (contactPoint);
// Compute contact points in configuration qFree
robot_->currentConfiguration (qFree);
robot_->computeForwardKinematics ();
Transform3f M1 (joint1->currentTransformation ());
// position of x1 in global frame
vector3_t x1_J2 (M1.act (x1_J1));
hppDout (info, "x1 in J2 = " << x1_J2.transpose());
eigen::vector3_t u=x1_J2 - x2_J2;
matrix3_t rot;
rot.setIdentity();
DifferentiableFunctionPtr_t f = constraints::Position::create
("", robot_, joint1, Transform3f(rot,x1_J1), Transform3f(rot,x2_J2));
matrix_t Jpos (f->outputSize (), f->inputDerivativeSize ());
f->jacobian (Jpos, qFree);
J_ = u.transpose () * Jpos;
assert (J_.rows () == 1);
}
}
virtual void impl_compute (vectorOut_t result, vectorIn_t argument)
const
{
pinocchio::difference<se3::LieGroupTpl> (robot_, argument, qFree_, difference_);
result = J_ * difference_;
}
virtual void impl_jacobian (matrixOut_t jacobian, vectorIn_t) const
{
jacobian = J_;
}
private:
DevicePtr_t robot_;
Configuration_t qFree_;
matrix_t J_;
mutable vector_t difference_;
}; // class CollisionFunction
} // namespace pathOptimization
} // namespace core
} // namespace hpp
#endif // HPP_CORE_PATH_OPTIMIZATION_SPLINE_GRADIENT_BASED_COLLISION_CONSTRAINTS_HH
<commit_msg>Normalize direction in collision constraint<commit_after>//
// Copyright (c) 2015 CNRS
// Author: Mylene Campana, Joseph Mirabel
//
//
// This file is part of hpp-core
// hpp-core 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.
//
// hpp-core 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 Lesser Public License for more details. You should have
// received a copy of the GNU Lesser General Public License along with
// hpp-core If not, see
// <http://www.gnu.org/licenses/>.
#ifndef HPP_CORE_PATH_OPTIMIZATION_SPLINE_GRADIENT_BASED_COLLISION_CONSTRAINTS_HH
# define HPP_CORE_PATH_OPTIMIZATION_SPLINE_GRADIENT_BASED_COLLISION_CONSTRAINTS_HH
#include <hpp/util/exception-factory.hh>
# include <hpp/fcl/collision.h>
# include <hpp/fcl/distance.h>
# include <hpp/pinocchio/configuration.hh>
# include <pinocchio/multibody/liegroup/liegroup.hpp>
# include <hpp/constraints/generic-transformation.hh>
namespace hpp {
namespace core {
namespace pathOptimization {
HPP_PREDEF_CLASS (CollisionFunction);
typedef boost::shared_ptr <CollisionFunction> CollisionFunctionPtr_t;
typedef pinocchio::Transform3f Transform3f;
namespace eigen {
typedef Eigen::Matrix <value_type, 3, 1> vector3_t;
} // namespace eigen
class CollisionFunction : public DifferentiableFunction
{
public:
virtual ~CollisionFunction () {}
template <typename SplinePtr_t>
static CollisionFunctionPtr_t create
(const DevicePtr_t& robot, const SplinePtr_t& freeSpline,
const SplinePtr_t& collSpline,
const CollisionPathValidationReportPtr_t& report)
{
const value_type& tColl = report->parameter;
bool success;
Configuration_t qColl = (*collSpline) (tColl, success);
assert(success);
HPP_STATIC_CAST_REF_CHECK (CollisionValidationReport,
*(report->configurationReport));
CollisionObjectConstPtr_t object1 =
HPP_STATIC_PTR_CAST (CollisionValidationReport,
report->configurationReport)->object1;
CollisionObjectConstPtr_t object2 =
HPP_STATIC_PTR_CAST (CollisionValidationReport,
report->configurationReport)->object2;
hppDout (info, "Collision at ratio (in [0,1]) = " << tColl / collSpline->length());
hppDout (info, "obj1 = " << object1->name()
<< " and obj2 = " << object2->name());
hppDout (info, "qColl = " << qColl.transpose());
// Backtrack collision in previous path (x0) to create constraint
value_type tFree = tColl * freeSpline->length () / collSpline->length();
Configuration_t qFree = (*freeSpline) (tFree, success);
assert(success);
hppDout (info, "qFree = " << qFree.transpose());
return create (robot, qFree, qColl, object1, object2);
}
static CollisionFunctionPtr_t create
(const DevicePtr_t& robot, const Configuration_t& qFree,
const Configuration_t& qColl, const CollisionObjectConstPtr_t& object1,
const CollisionObjectConstPtr_t& object2)
{
CollisionFunction* ptr = new CollisionFunction
(robot, qFree, qColl, object1, object2);
CollisionFunctionPtr_t shPtr (ptr);
return shPtr;
}
protected:
CollisionFunction (const DevicePtr_t& robot,
const Configuration_t& qFree,
const Configuration_t& qColl,
const CollisionObjectConstPtr_t& object1,
const CollisionObjectConstPtr_t& object2)
: DifferentiableFunction (robot->configSize (), robot->numberDof (),
1, ""), robot_ (robot), qFree_ (qFree),
J_ (), difference_ ()
{
difference_.resize (robot->numberDof ());
// Compute contact point in configuration qColl
robot_->currentConfiguration (qColl);
robot_->computeForwardKinematics ();
robot_->updateGeometryPlacements ();
fcl::CollisionResult result;
fcl::CollisionRequest collisionRequest (1, true, false, 1, false, true, fcl::GST_INDEP);
fcl::collide (object1->fcl (), object2->fcl (), collisionRequest, result);
if (result.numContacts() != 1) {
result.clear();
collisionRequest.enable_contact = false;
fcl::collide (object1->fcl (), object2->fcl (), collisionRequest, result);
if (result.isCollision()) {
hppDout (error, "FCL does not returns the same result when asking or not for the contact points.");
}
HPP_THROW(std::invalid_argument,
"Object " << object1->name() << " and " << object2->name()
<< " are not in collision in configuration\n"
<< qColl.transpose().format(IPythonFormat)
<< "\nqFree is\n" << qFree.transpose().format(IPythonFormat));
}
assert (result.numContacts () == 1);
const vector3_t& contactPoint (result.getContact (0).pos);
hppDout (info, "contact point = " << contactPoint.transpose());
JointConstPtr_t joint1 = object1->joint ();
// FIXME this copy can probably be avoided.
Transform3f M1 (joint1->currentTransformation ());
if (object2->joint ()) { // object2 = body part
JointConstPtr_t joint2 = object2->joint ();
Transform3f M2 (joint2->currentTransformation ());
// Position of contact point in each object local frame
vector3_t x1_J1 = M1.actInv (contactPoint);
vector3_t x2_J2 = M2.actInv (contactPoint);
// Compute contact points in configuration qFree
robot_->currentConfiguration (qFree);
robot_->computeForwardKinematics ();
M2 = joint2->currentTransformation ();
M1 = joint1->currentTransformation ();
// Position of x2 in local frame of joint1
vector3_t x2_J1 (M1.actInv (M2.act (x2_J2)));
hppDout (info, "x1 in J1 = " << x1_J1.transpose());
hppDout (info, "x2 in J1 = " << x2_J1.transpose());
eigen::vector3_t u=x2_J1 - x1_J1;
matrix3_t rot;
rot.setIdentity();
DifferentiableFunctionPtr_t f = constraints::RelativePosition::create
("", robot_, joint1, joint2, Transform3f(rot,x1_J1), Transform3f(rot,x2_J2));
matrix_t Jpos (f->outputSize (), f->inputDerivativeSize ());
f->jacobian (Jpos, qFree);
J_ = u.transpose () * Jpos;
assert (J_.rows () == 1);
} else{ // object2 = fixed obstacle and has no joint
vector3_t x1_J1 (M1.actInv(contactPoint));
vector3_t x2_J2 (contactPoint);
// Compute contact points in configuration qFree
robot_->currentConfiguration (qFree);
robot_->computeForwardKinematics ();
Transform3f M1 (joint1->currentTransformation ());
// position of x1 in global frame
vector3_t x1_J2 (M1.act (x1_J1));
hppDout (info, "x1 in J2 = " << x1_J2.transpose());
eigen::vector3_t u=x1_J2 - x2_J2;
u.normalize();
matrix3_t rot;
rot.setIdentity();
DifferentiableFunctionPtr_t f = constraints::Position::create
("", robot_, joint1, Transform3f(rot,x1_J1), Transform3f(rot,x2_J2));
matrix_t Jpos (f->outputSize (), f->inputDerivativeSize ());
f->jacobian (Jpos, qFree);
J_ = u.transpose () * Jpos;
assert (J_.rows () == 1);
}
}
virtual void impl_compute (vectorOut_t result, vectorIn_t argument)
const
{
pinocchio::difference<se3::LieGroupTpl> (robot_, argument, qFree_, difference_);
result = J_ * difference_;
}
virtual void impl_jacobian (matrixOut_t jacobian, vectorIn_t) const
{
jacobian = J_;
}
private:
DevicePtr_t robot_;
Configuration_t qFree_;
matrix_t J_;
mutable vector_t difference_;
}; // class CollisionFunction
} // namespace pathOptimization
} // namespace core
} // namespace hpp
#endif // HPP_CORE_PATH_OPTIMIZATION_SPLINE_GRADIENT_BASED_COLLISION_CONSTRAINTS_HH
<|endoftext|>
|
<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** 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.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/
#include "itemlibrarymodel.h"
#include "metainfo.h"
#include <QVariant>
#include <QMimeData>
#include <QPainter>
#include <QPen>
#include <qdebug.h>
namespace QmlDesigner {
namespace Internal {
template <class T>
ItemLibrarySortedModel<T>::ItemLibrarySortedModel(QObject *parent) :
QDeclarativeListModel(parent)
{
}
template <class T>
ItemLibrarySortedModel<T>::~ItemLibrarySortedModel()
{
clearElements();
}
template <class T>
void ItemLibrarySortedModel<T>::clearElements()
{
while (m_elementOrder.count() > 0)
removeElement(m_elementOrder.at(0).libId);
}
template <class T>
void ItemLibrarySortedModel<T>::addElement(T *element, int libId)
{
struct order_struct orderEntry;
orderEntry.libId = libId;
orderEntry.visible = false;
int pos = 0;
while ((pos < m_elementOrder.count()) &&
(*(m_elementModels.value(m_elementOrder.at(pos).libId)) < *element))
++pos;
m_elementModels.insert(libId, element);
m_elementOrder.insert(pos, orderEntry);
setElementVisible(libId, true);
}
template <class T>
void ItemLibrarySortedModel<T>::removeElement(int libId)
{
T *element = m_elementModels.value(libId);
int pos = findElement(libId);
setElementVisible(libId, false);
m_elementModels.remove(libId);
m_elementOrder.removeAt(pos);
delete element;
}
template <class T>
bool ItemLibrarySortedModel<T>::elementVisible(int libId) const
{
int pos = findElement(libId);
return m_elementOrder.at(pos).visible;
}
template <class T>
bool ItemLibrarySortedModel<T>::setElementVisible(int libId, bool visible)
{
int pos = findElement(libId);
if (m_elementOrder.at(pos).visible == visible)
return false;
int visiblePos = visibleElementPosition(libId);
if (visible)
insert(visiblePos, *(m_elementModels.value(libId)));
else
remove(visiblePos);
m_elementOrder[pos].visible = visible;
return true;
}
template <class T>
const QMap<int, T *> &ItemLibrarySortedModel<T>::elements() const
{
return m_elementModels;
}
template <class T>
T *ItemLibrarySortedModel<T>::elementModel(int libId)
{
return m_elementModels.value(libId);
}
template <class T>
int ItemLibrarySortedModel<T>::findElement(int libId) const
{
int i = 0;
QListIterator<struct order_struct> it(m_elementOrder);
while (it.hasNext()) {
if (it.next().libId == libId)
return i;
++i;
}
return -1;
}
template <class T>
int ItemLibrarySortedModel<T>::visibleElementPosition(int libId) const
{
int i = 0;
QListIterator<struct order_struct> it(m_elementOrder);
while (it.hasNext()) {
struct order_struct order = it.next();
if (order.libId == libId)
return i;
if (order.visible)
++i;
}
return -1;
}
ItemLibraryItemModel::ItemLibraryItemModel(QScriptEngine *scriptEngine, int itemLibId, const QString &itemName)
: QScriptValue(scriptEngine->newObject()),
m_scriptEngine(scriptEngine),
m_libId(itemLibId),
m_name(itemName),
m_icon(),
m_iconSize(64, 64)
{
QScriptValue pixmapScriptValue(m_scriptEngine->newVariant(QPixmap()));
setProperty(QLatin1String("itemLibId"), itemLibId);
setProperty(QLatin1String("itemName"), itemName);
setProperty(QLatin1String("itemPixmap"), pixmapScriptValue);
}
ItemLibraryItemModel::~ItemLibraryItemModel()
{
setProperty(QLatin1String("itemPixmap"), QVariant::Invalid);
}
int ItemLibraryItemModel::itemLibId() const
{
return m_libId;
}
QString ItemLibraryItemModel::itemName() const
{
return m_name;
}
void ItemLibraryItemModel::setItemIcon(const QIcon &itemIcon)
{
m_icon = itemIcon;
QScriptValue pixmapScriptValue(m_scriptEngine->newVariant(m_icon.pixmap(m_iconSize)));
setProperty(QLatin1String("itemPixmap"), pixmapScriptValue);
}
void ItemLibraryItemModel::setItemIconSize(const QSize &itemIconSize)
{
m_iconSize = itemIconSize;
// qDebug() << "set icon size" << itemIconSize;
setItemIcon(m_icon);
}
bool ItemLibraryItemModel::operator<(const ItemLibraryItemModel &other) const
{
return itemName() < other.itemName();
}
ItemLibrarySectionModel::ItemLibrarySectionModel(QScriptEngine *scriptEngine, int sectionLibId, const QString §ionName, QObject *parent)
: QScriptValue(scriptEngine->newObject()),
m_name(sectionName),
m_sectionEntries(parent)
{
QScriptValue::setProperty(QLatin1String("sectionLibId"), sectionLibId);
QScriptValue::setProperty(QLatin1String("sectionName"), sectionName);
QScriptValue::setProperty(QLatin1String("sectionEntries"),
scriptEngine->newVariant(QVariant::fromValue(static_cast<QDeclarativeListModel *>(&m_sectionEntries))));
}
QString ItemLibrarySectionModel::sectionName() const
{
return m_name;
}
void ItemLibrarySectionModel::addSectionEntry(ItemLibraryItemModel *sectionEntry)
{
m_sectionEntries.addElement(sectionEntry, sectionEntry->itemLibId());
}
void ItemLibrarySectionModel::removeSectionEntry(int itemLibId)
{
m_sectionEntries.removeElement(itemLibId);
}
int ItemLibrarySectionModel::visibleItemIndex(int itemLibId)
{
return m_sectionEntries.visibleElementPosition(itemLibId);
}
bool ItemLibrarySectionModel::isItemVisible(int itemLibId)
{
return m_sectionEntries.elementVisible(itemLibId);
}
bool ItemLibrarySectionModel::updateSectionVisibility(const QString &searchText, bool *changed)
{
bool haveVisibleItems = false;
*changed = false;
QMap<int, ItemLibraryItemModel *>::const_iterator itemIt = m_sectionEntries.elements().constBegin();
while (itemIt != m_sectionEntries.elements().constEnd()) {
bool itemVisible = itemIt.value()->itemName().toLower().contains(searchText),
itemChanged = false;
itemChanged = m_sectionEntries.setElementVisible(itemIt.key(), itemVisible);
*changed |= itemChanged;
if (itemVisible)
haveVisibleItems = true;
++itemIt;
}
return haveVisibleItems;
}
void ItemLibrarySectionModel::updateItemIconSize(const QSize &itemIconSize)
{
foreach (ItemLibraryItemModel *item, m_sectionEntries.elements().values()) {
item->setItemIconSize(itemIconSize);
}
}
bool ItemLibrarySectionModel::operator<(const ItemLibrarySectionModel &other) const
{
return sectionName() < other.sectionName();
}
ItemLibraryModel::ItemLibraryModel(QScriptEngine *scriptEngine, QObject *parent)
: ItemLibrarySortedModel<ItemLibrarySectionModel>(parent),
m_scriptEngine(scriptEngine),
m_metaInfo(0),
m_searchText(""),
m_itemIconSize(64, 64),
m_nextLibId(0)
{
}
ItemLibraryModel::~ItemLibraryModel()
{
if (m_metaInfo)
delete m_metaInfo;
}
QString ItemLibraryModel::searchText() const
{
return m_searchText;
}
void ItemLibraryModel::setSearchText(const QString &searchText)
{
QString lowerSearchText = searchText.toLower();
if (m_searchText != lowerSearchText) {
m_searchText = lowerSearchText;
emit searchTextChanged();
updateVisibility();
}
}
void ItemLibraryModel::setItemIconSize(const QSize &itemIconSize)
{
m_itemIconSize = itemIconSize;
foreach (ItemLibrarySectionModel *section, elements().values())
section->updateItemIconSize(itemIconSize);
}
int ItemLibraryModel::getItemSectionIndex(int itemLibId)
{
if (m_sections.contains(itemLibId))
return elementModel(m_sections.value(itemLibId))->visibleItemIndex(itemLibId);
else
return -1;
}
int ItemLibraryModel::getSectionLibId(int itemLibId)
{
return m_sections.value(itemLibId);
}
bool ItemLibraryModel::isItemVisible(int itemLibId)
{
if (!m_sections.contains(itemLibId))
return false;
int sectionLibId = m_sections.value(itemLibId);
if (!elementVisible(sectionLibId))
return false;
return elementModel(sectionLibId)->isItemVisible(itemLibId);
}
void ItemLibraryModel::update(const MetaInfo &metaInfo)
{
QMap<QString, int> sections;
clearElements();
m_itemInfos.clear();
m_sections.clear();
m_nextLibId = 0;
if (!m_metaInfo) {
m_metaInfo = new MetaInfo(metaInfo);
} else {
*m_metaInfo = metaInfo;
}
foreach (const QString &type, metaInfo.itemLibraryItems()) {
foreach (const ItemLibraryInfo &itemLibraryRepresentation, itemLibraryRepresentations(type)) {
QString itemSectionName = itemLibraryRepresentation.category();
ItemLibrarySectionModel *sectionModel;
ItemLibraryItemModel *itemModel;
int itemId = m_nextLibId++, sectionId;
if (sections.contains(itemSectionName)) {
sectionId = sections.value(itemSectionName);
sectionModel = elementModel(sectionId);
} else {
sectionId = m_nextLibId++;
sectionModel = new ItemLibrarySectionModel(m_scriptEngine.data(), sectionId, itemSectionName, this);
addElement(sectionModel, sectionId);
sections.insert(itemSectionName, sectionId);
}
m_itemInfos.insert(itemId, itemLibraryRepresentation);
itemModel = new ItemLibraryItemModel(m_scriptEngine.data(), itemId, itemLibraryRepresentation.name());
itemModel->setItemIcon(itemLibraryRepresentation.icon());
itemModel->setItemIconSize(m_itemIconSize);
sectionModel->addSectionEntry(itemModel);
m_sections.insert(itemId, sectionId);
}
}
updateVisibility();
}
QString ItemLibraryModel::getTypeName(int libId)
{
return m_itemInfos.value(libId).typeName();
}
QMimeData *ItemLibraryModel::getMimeData(int libId)
{
QMimeData *mimeData = new QMimeData();
QByteArray data;
QDataStream stream(&data, QIODevice::WriteOnly);
stream << m_itemInfos.value(libId);
mimeData->setData(QLatin1String("application/vnd.bauhaus.itemlibraryinfo"), data);
const QIcon icon = m_itemInfos.value(libId).dragIcon();
if (!icon.isNull()) {
const QList<QSize> sizes = icon.availableSizes();
if (!sizes.isEmpty())
mimeData->setImageData(icon.pixmap(sizes.front()).toImage());
}
mimeData->removeFormat(QLatin1String("text/plain"));
return mimeData;
}
QIcon ItemLibraryModel::getIcon(int libId)
{
return m_itemInfos.value(libId).icon();
}
void ItemLibraryModel::updateVisibility()
{
bool changed = false;
QMap<int, ItemLibrarySectionModel *>::const_iterator sectionIt = elements().constBegin();
while (sectionIt != elements().constEnd()) {
ItemLibrarySectionModel *sectionModel = sectionIt.value();
QString sectionSearchText = m_searchText;
if (sectionModel->sectionName().toLower().contains(m_searchText))
sectionSearchText = "";
bool sectionChanged = false,
sectionVisibility = sectionModel->updateSectionVisibility(sectionSearchText,
§ionChanged);
if (sectionChanged) {
changed = true;
if (sectionVisibility)
emit sectionVisibilityChanged(sectionIt.key());
}
changed |= setElementVisible(sectionIt.key(), sectionVisibility);
++sectionIt;
}
if (changed)
emit visibilityChanged();
}
QList<ItemLibraryInfo> ItemLibraryModel::itemLibraryRepresentations(const QString &type)
{
QList<ItemLibraryInfo> itemLibraryRepresentationList;
NodeMetaInfo nodeInfo = m_metaInfo->nodeMetaInfo(type);
if (nodeInfo.isQmlGraphicsItem()) {
itemLibraryRepresentationList = m_metaInfo->itemLibraryRepresentations(nodeInfo);
QImage dragImage(64, 64, QImage::Format_RGB32); // TODO: draw item drag icon
dragImage.fill(0xffffffff);
QPainter p(&dragImage);
QPen pen(Qt::gray);
pen.setWidth(2);
p.setPen(pen);
p.drawRect(1, 1, dragImage.width() - 2, dragImage.height() - 2);
QPixmap dragPixmap(QPixmap::fromImage(dragImage));
if (!m_metaInfo->hasNodeMetaInfo(type))
qWarning() << "ItemLibrary: type not declared: " << type;
static QIcon defaultIcon(QLatin1String(":/ItemLibrary/images/item-default-icon.png"));
if (itemLibraryRepresentationList.isEmpty() || !m_metaInfo->hasNodeMetaInfo(type)) {
QIcon icon = nodeInfo.icon();
if (icon.isNull())
icon = defaultIcon;
ItemLibraryInfo itemLibraryInfo;
itemLibraryInfo.setName(type);
itemLibraryInfo.setTypeName(nodeInfo.typeName());
itemLibraryInfo.setCategory(nodeInfo.category());
itemLibraryInfo.setIcon(icon);
itemLibraryInfo.setDragIcon(dragPixmap);
itemLibraryInfo.setMajorVersion(nodeInfo.majorVersion());
itemLibraryInfo.setMinorVersion(nodeInfo.minorVersion());
itemLibraryRepresentationList.append(itemLibraryInfo);
}
else {
foreach (ItemLibraryInfo itemLibraryRepresentation, itemLibraryRepresentationList) {
QIcon icon = itemLibraryRepresentation.icon();
if (itemLibraryRepresentation.icon().isNull())
itemLibraryRepresentation.setIcon(defaultIcon);
if (itemLibraryRepresentation.dragIcon().isNull())
itemLibraryRepresentation.setDragIcon(dragPixmap);
if (itemLibraryRepresentation.category().isEmpty())
itemLibraryRepresentation.setCategory(nodeInfo.category());
}
}
}
return itemLibraryRepresentationList;
}
} // namespace Internal
} // namespace QmlDesigner
<commit_msg>QmlDesigner.itemLibrary: set correct size for dragItem<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** 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.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/
#include "itemlibrarymodel.h"
#include "metainfo.h"
#include <QVariant>
#include <QMimeData>
#include <QPainter>
#include <QPen>
#include <qdebug.h>
namespace QmlDesigner {
namespace Internal {
template <class T>
ItemLibrarySortedModel<T>::ItemLibrarySortedModel(QObject *parent) :
QDeclarativeListModel(parent)
{
}
template <class T>
ItemLibrarySortedModel<T>::~ItemLibrarySortedModel()
{
clearElements();
}
template <class T>
void ItemLibrarySortedModel<T>::clearElements()
{
while (m_elementOrder.count() > 0)
removeElement(m_elementOrder.at(0).libId);
}
template <class T>
void ItemLibrarySortedModel<T>::addElement(T *element, int libId)
{
struct order_struct orderEntry;
orderEntry.libId = libId;
orderEntry.visible = false;
int pos = 0;
while ((pos < m_elementOrder.count()) &&
(*(m_elementModels.value(m_elementOrder.at(pos).libId)) < *element))
++pos;
m_elementModels.insert(libId, element);
m_elementOrder.insert(pos, orderEntry);
setElementVisible(libId, true);
}
template <class T>
void ItemLibrarySortedModel<T>::removeElement(int libId)
{
T *element = m_elementModels.value(libId);
int pos = findElement(libId);
setElementVisible(libId, false);
m_elementModels.remove(libId);
m_elementOrder.removeAt(pos);
delete element;
}
template <class T>
bool ItemLibrarySortedModel<T>::elementVisible(int libId) const
{
int pos = findElement(libId);
return m_elementOrder.at(pos).visible;
}
template <class T>
bool ItemLibrarySortedModel<T>::setElementVisible(int libId, bool visible)
{
int pos = findElement(libId);
if (m_elementOrder.at(pos).visible == visible)
return false;
int visiblePos = visibleElementPosition(libId);
if (visible)
insert(visiblePos, *(m_elementModels.value(libId)));
else
remove(visiblePos);
m_elementOrder[pos].visible = visible;
return true;
}
template <class T>
const QMap<int, T *> &ItemLibrarySortedModel<T>::elements() const
{
return m_elementModels;
}
template <class T>
T *ItemLibrarySortedModel<T>::elementModel(int libId)
{
return m_elementModels.value(libId);
}
template <class T>
int ItemLibrarySortedModel<T>::findElement(int libId) const
{
int i = 0;
QListIterator<struct order_struct> it(m_elementOrder);
while (it.hasNext()) {
if (it.next().libId == libId)
return i;
++i;
}
return -1;
}
template <class T>
int ItemLibrarySortedModel<T>::visibleElementPosition(int libId) const
{
int i = 0;
QListIterator<struct order_struct> it(m_elementOrder);
while (it.hasNext()) {
struct order_struct order = it.next();
if (order.libId == libId)
return i;
if (order.visible)
++i;
}
return -1;
}
ItemLibraryItemModel::ItemLibraryItemModel(QScriptEngine *scriptEngine, int itemLibId, const QString &itemName)
: QScriptValue(scriptEngine->newObject()),
m_scriptEngine(scriptEngine),
m_libId(itemLibId),
m_name(itemName),
m_icon(),
m_iconSize(64, 64)
{
QScriptValue pixmapScriptValue(m_scriptEngine->newVariant(QPixmap()));
setProperty(QLatin1String("itemLibId"), itemLibId);
setProperty(QLatin1String("itemName"), itemName);
setProperty(QLatin1String("itemPixmap"), pixmapScriptValue);
}
ItemLibraryItemModel::~ItemLibraryItemModel()
{
setProperty(QLatin1String("itemPixmap"), QVariant::Invalid);
}
int ItemLibraryItemModel::itemLibId() const
{
return m_libId;
}
QString ItemLibraryItemModel::itemName() const
{
return m_name;
}
void ItemLibraryItemModel::setItemIcon(const QIcon &itemIcon)
{
m_icon = itemIcon;
QScriptValue pixmapScriptValue(m_scriptEngine->newVariant(m_icon.pixmap(m_iconSize)));
setProperty(QLatin1String("itemPixmap"), pixmapScriptValue);
}
void ItemLibraryItemModel::setItemIconSize(const QSize &itemIconSize)
{
m_iconSize = itemIconSize;
// qDebug() << "set icon size" << itemIconSize;
setItemIcon(m_icon);
}
bool ItemLibraryItemModel::operator<(const ItemLibraryItemModel &other) const
{
return itemName() < other.itemName();
}
ItemLibrarySectionModel::ItemLibrarySectionModel(QScriptEngine *scriptEngine, int sectionLibId, const QString §ionName, QObject *parent)
: QScriptValue(scriptEngine->newObject()),
m_name(sectionName),
m_sectionEntries(parent)
{
QScriptValue::setProperty(QLatin1String("sectionLibId"), sectionLibId);
QScriptValue::setProperty(QLatin1String("sectionName"), sectionName);
QScriptValue::setProperty(QLatin1String("sectionEntries"),
scriptEngine->newVariant(QVariant::fromValue(static_cast<QDeclarativeListModel *>(&m_sectionEntries))));
}
QString ItemLibrarySectionModel::sectionName() const
{
return m_name;
}
void ItemLibrarySectionModel::addSectionEntry(ItemLibraryItemModel *sectionEntry)
{
m_sectionEntries.addElement(sectionEntry, sectionEntry->itemLibId());
}
void ItemLibrarySectionModel::removeSectionEntry(int itemLibId)
{
m_sectionEntries.removeElement(itemLibId);
}
int ItemLibrarySectionModel::visibleItemIndex(int itemLibId)
{
return m_sectionEntries.visibleElementPosition(itemLibId);
}
bool ItemLibrarySectionModel::isItemVisible(int itemLibId)
{
return m_sectionEntries.elementVisible(itemLibId);
}
bool ItemLibrarySectionModel::updateSectionVisibility(const QString &searchText, bool *changed)
{
bool haveVisibleItems = false;
*changed = false;
QMap<int, ItemLibraryItemModel *>::const_iterator itemIt = m_sectionEntries.elements().constBegin();
while (itemIt != m_sectionEntries.elements().constEnd()) {
bool itemVisible = itemIt.value()->itemName().toLower().contains(searchText),
itemChanged = false;
itemChanged = m_sectionEntries.setElementVisible(itemIt.key(), itemVisible);
*changed |= itemChanged;
if (itemVisible)
haveVisibleItems = true;
++itemIt;
}
return haveVisibleItems;
}
void ItemLibrarySectionModel::updateItemIconSize(const QSize &itemIconSize)
{
foreach (ItemLibraryItemModel *item, m_sectionEntries.elements().values()) {
item->setItemIconSize(itemIconSize);
}
}
bool ItemLibrarySectionModel::operator<(const ItemLibrarySectionModel &other) const
{
return sectionName() < other.sectionName();
}
ItemLibraryModel::ItemLibraryModel(QScriptEngine *scriptEngine, QObject *parent)
: ItemLibrarySortedModel<ItemLibrarySectionModel>(parent),
m_scriptEngine(scriptEngine),
m_metaInfo(0),
m_searchText(""),
m_itemIconSize(64, 64),
m_nextLibId(0)
{
}
ItemLibraryModel::~ItemLibraryModel()
{
if (m_metaInfo)
delete m_metaInfo;
}
QString ItemLibraryModel::searchText() const
{
return m_searchText;
}
void ItemLibraryModel::setSearchText(const QString &searchText)
{
QString lowerSearchText = searchText.toLower();
if (m_searchText != lowerSearchText) {
m_searchText = lowerSearchText;
emit searchTextChanged();
updateVisibility();
}
}
void ItemLibraryModel::setItemIconSize(const QSize &itemIconSize)
{
m_itemIconSize = itemIconSize;
foreach (ItemLibrarySectionModel *section, elements().values())
section->updateItemIconSize(itemIconSize);
}
int ItemLibraryModel::getItemSectionIndex(int itemLibId)
{
if (m_sections.contains(itemLibId))
return elementModel(m_sections.value(itemLibId))->visibleItemIndex(itemLibId);
else
return -1;
}
int ItemLibraryModel::getSectionLibId(int itemLibId)
{
return m_sections.value(itemLibId);
}
bool ItemLibraryModel::isItemVisible(int itemLibId)
{
if (!m_sections.contains(itemLibId))
return false;
int sectionLibId = m_sections.value(itemLibId);
if (!elementVisible(sectionLibId))
return false;
return elementModel(sectionLibId)->isItemVisible(itemLibId);
}
void ItemLibraryModel::update(const MetaInfo &metaInfo)
{
QMap<QString, int> sections;
clearElements();
m_itemInfos.clear();
m_sections.clear();
m_nextLibId = 0;
if (!m_metaInfo) {
m_metaInfo = new MetaInfo(metaInfo);
} else {
*m_metaInfo = metaInfo;
}
foreach (const QString &type, metaInfo.itemLibraryItems()) {
foreach (const ItemLibraryInfo &itemLibraryRepresentation, itemLibraryRepresentations(type)) {
QString itemSectionName = itemLibraryRepresentation.category();
ItemLibrarySectionModel *sectionModel;
ItemLibraryItemModel *itemModel;
int itemId = m_nextLibId++, sectionId;
if (sections.contains(itemSectionName)) {
sectionId = sections.value(itemSectionName);
sectionModel = elementModel(sectionId);
} else {
sectionId = m_nextLibId++;
sectionModel = new ItemLibrarySectionModel(m_scriptEngine.data(), sectionId, itemSectionName, this);
addElement(sectionModel, sectionId);
sections.insert(itemSectionName, sectionId);
}
m_itemInfos.insert(itemId, itemLibraryRepresentation);
itemModel = new ItemLibraryItemModel(m_scriptEngine.data(), itemId, itemLibraryRepresentation.name());
itemModel->setItemIcon(itemLibraryRepresentation.icon());
itemModel->setItemIconSize(m_itemIconSize);
sectionModel->addSectionEntry(itemModel);
m_sections.insert(itemId, sectionId);
}
}
updateVisibility();
}
QString ItemLibraryModel::getTypeName(int libId)
{
return m_itemInfos.value(libId).typeName();
}
QMimeData *ItemLibraryModel::getMimeData(int libId)
{
QMimeData *mimeData = new QMimeData();
QByteArray data;
QDataStream stream(&data, QIODevice::WriteOnly);
stream << m_itemInfos.value(libId);
mimeData->setData(QLatin1String("application/vnd.bauhaus.itemlibraryinfo"), data);
const QIcon icon = m_itemInfos.value(libId).dragIcon();
if (!icon.isNull()) {
const QList<QSize> sizes = icon.availableSizes();
if (!sizes.isEmpty())
mimeData->setImageData(icon.pixmap(sizes.front()).toImage());
}
mimeData->removeFormat(QLatin1String("text/plain"));
return mimeData;
}
QIcon ItemLibraryModel::getIcon(int libId)
{
return m_itemInfos.value(libId).icon();
}
void ItemLibraryModel::updateVisibility()
{
bool changed = false;
QMap<int, ItemLibrarySectionModel *>::const_iterator sectionIt = elements().constBegin();
while (sectionIt != elements().constEnd()) {
ItemLibrarySectionModel *sectionModel = sectionIt.value();
QString sectionSearchText = m_searchText;
if (sectionModel->sectionName().toLower().contains(m_searchText))
sectionSearchText = "";
bool sectionChanged = false,
sectionVisibility = sectionModel->updateSectionVisibility(sectionSearchText,
§ionChanged);
if (sectionChanged) {
changed = true;
if (sectionVisibility)
emit sectionVisibilityChanged(sectionIt.key());
}
changed |= setElementVisible(sectionIt.key(), sectionVisibility);
++sectionIt;
}
if (changed)
emit visibilityChanged();
}
static inline int getWidth(const ItemLibraryInfo &itemLibraryRepresentation)
{
foreach (const ItemLibraryInfo::Property &property, itemLibraryRepresentation.properties())
{
if (property.name() == QLatin1String("width"))
return property.value().toInt();
}
return 64;
}
static inline int getHeight(const ItemLibraryInfo &itemLibraryRepresentation)
{
foreach (const ItemLibraryInfo::Property &property, itemLibraryRepresentation.properties())
{
if (property.name() == QLatin1String("height"))
return property.value().toInt();
}
return 64;
}
static inline QPixmap createDragPixmap(int width, int height)
{
QImage dragImage(width, height, QImage::Format_RGB32); // TODO: draw item drag icon
dragImage.fill(0xffffffff);
QPainter p(&dragImage);
QPen pen(Qt::gray);
pen.setWidth(2);
p.setPen(pen);
p.drawRect(1, 1, dragImage.width() - 2, dragImage.height() - 2);
return QPixmap::fromImage(dragImage);
}
QList<ItemLibraryInfo> ItemLibraryModel::itemLibraryRepresentations(const QString &type)
{
QList<ItemLibraryInfo> itemLibraryRepresentationList;
NodeMetaInfo nodeInfo = m_metaInfo->nodeMetaInfo(type);
if (nodeInfo.isQmlGraphicsItem()) {
itemLibraryRepresentationList = m_metaInfo->itemLibraryRepresentations(nodeInfo);
if (!m_metaInfo->hasNodeMetaInfo(type))
qWarning() << "ItemLibrary: type not declared: " << type;
static QIcon defaultIcon(QLatin1String(":/ItemLibrary/images/item-default-icon.png"));
if (itemLibraryRepresentationList.isEmpty() || !m_metaInfo->hasNodeMetaInfo(type)) {
QIcon icon = nodeInfo.icon();
if (icon.isNull())
icon = defaultIcon;
ItemLibraryInfo itemLibraryInfo;
itemLibraryInfo.setName(type);
itemLibraryInfo.setTypeName(nodeInfo.typeName());
itemLibraryInfo.setCategory(nodeInfo.category());
itemLibraryInfo.setIcon(icon);
itemLibraryInfo.setDragIcon(createDragPixmap(64, 64));
itemLibraryInfo.setMajorVersion(nodeInfo.majorVersion());
itemLibraryInfo.setMinorVersion(nodeInfo.minorVersion());
itemLibraryRepresentationList.append(itemLibraryInfo);
}
else {
foreach (ItemLibraryInfo itemLibraryRepresentation, itemLibraryRepresentationList) {
QIcon icon = itemLibraryRepresentation.icon();
if (itemLibraryRepresentation.icon().isNull())
itemLibraryRepresentation.setIcon(defaultIcon);
if (itemLibraryRepresentation.dragIcon().isNull())
itemLibraryRepresentation.setDragIcon(createDragPixmap(getWidth(itemLibraryRepresentation), getHeight(itemLibraryRepresentation)));
if (itemLibraryRepresentation.category().isEmpty())
itemLibraryRepresentation.setCategory(nodeInfo.category());
}
}
}
return itemLibraryRepresentationList;
}
} // namespace Internal
} // namespace QmlDesigner
<|endoftext|>
|
<commit_before>#include <stan/math/error_handling/matrix/check_spsd_matrix.hpp>
#include <gtest/gtest.h>
TEST(MathErrorHandlingMatrix, checkSpsdMatrixPosDef) {
Eigen::Matrix<double,Eigen::Dynamic,Eigen::Dynamic> y;
double result;
y.resize(3,3);
y << 2, -1, 0, -1, 2, -1, 0, -1, 2;
EXPECT_TRUE(stan::math::check_spsd_matrix("checkSpsdMatrix(%1%)",
y, "y", &result));
y << 1, 2, 3, 2, 1, 2, 3, 2, 1;
EXPECT_THROW(stan::math::check_spsd_matrix("checkSpsdMatrix(%1%)", y, "y", &result),
std::domain_error);
y.setZero();
EXPECT_TRUE(stan::math::check_spsd_matrix("checkSpsdMatrix(%1%)", y, "y", &result));
}
TEST(MathErrorHandlingMatrix, checkSpsdMatrixZero) {
Eigen::Matrix<double,Eigen::Dynamic,Eigen::Dynamic> y =
Eigen::Matrix<double,Eigen::Dynamic,Eigen::Dynamic>::Zero(3,3);
double result;
EXPECT_TRUE(stan::math::check_spsd_matrix("checkSpsdMatrix(%1%)", y, "y", &result));
}
TEST(MathErrorHandlingMatrix, checkSpsdNotSquare) {
Eigen::Matrix<double,Eigen::Dynamic,Eigen::Dynamic> y =
Eigen::Matrix<double,Eigen::Dynamic,Eigen::Dynamic>::Zero(3,2);
double result;
EXPECT_THROW(stan::math::check_spsd_matrix("checkSpsdMatrix(%1%)", y, "y", &result),
std::domain_error);
}
<commit_msg>added NaN test for check_spsd_matrix<commit_after>#include <stan/math/error_handling/matrix/check_spsd_matrix.hpp>
#include <gtest/gtest.h>
TEST(MathErrorHandlingMatrix, checkSpsdMatrixPosDef) {
Eigen::Matrix<double,Eigen::Dynamic,Eigen::Dynamic> y;
double result;
y.resize(3,3);
y << 2, -1, 0, -1, 2, -1, 0, -1, 2;
EXPECT_TRUE(stan::math::check_spsd_matrix("checkSpsdMatrix(%1%)",
y, "y", &result));
y << 1, 2, 3, 2, 1, 2, 3, 2, 1;
EXPECT_THROW(stan::math::check_spsd_matrix("checkSpsdMatrix(%1%)", y, "y", &result),
std::domain_error);
y.setZero();
EXPECT_TRUE(stan::math::check_spsd_matrix("checkSpsdMatrix(%1%)", y, "y", &result));
}
TEST(MathErrorHandlingMatrix, checkSpsdMatrixZero) {
Eigen::Matrix<double,Eigen::Dynamic,Eigen::Dynamic> y =
Eigen::Matrix<double,Eigen::Dynamic,Eigen::Dynamic>::Zero(3,3);
double result;
EXPECT_TRUE(stan::math::check_spsd_matrix("checkSpsdMatrix(%1%)", y, "y", &result));
}
TEST(MathErrorHandlingMatrix, checkSpsdNotSquare) {
Eigen::Matrix<double,Eigen::Dynamic,Eigen::Dynamic> y =
Eigen::Matrix<double,Eigen::Dynamic,Eigen::Dynamic>::Zero(3,2);
double result;
EXPECT_THROW(stan::math::check_spsd_matrix("checkSpsdMatrix(%1%)", y, "y", &result),
std::domain_error);
}
TEST(MathErrorHandlingMatrix, checkSpsdMatrixPosDef_nan) {
Eigen::Matrix<double,Eigen::Dynamic,Eigen::Dynamic> y;
double result;
double nan = std::numeric_limits<double>::quiet_NaN();
y.resize(3,3);
y << 2, -1, 0, -1, 2, -1, 0, -1, 2;
EXPECT_TRUE(stan::math::check_spsd_matrix("checkSpsdMatrix(%1%)",
y, "y", &result));
y.setZero();
EXPECT_TRUE(stan::math::check_spsd_matrix("checkSpsdMatrix(%1%)", y, "y", &result));
for (int i = 0; i < y.size(); i++) {
y << 2, -1, 0, -1, 2, -1, 0, -1, 2;
y(i) = nan;
EXPECT_THROW(stan::math::check_spsd_matrix("checkSpsdMatrix(%1%)",
y, "y", &result),
std::domain_error);
y.setZero();
y(i) = nan;
EXPECT_THROW(stan::math::check_spsd_matrix("checkSpsdMatrix(%1%)",
y, "y", &result),
std::domain_error);
}
}
<|endoftext|>
|
<commit_before>#include <stan/math/error_handling/matrix/check_unit_vector.hpp>
#include <gtest/gtest.h>
TEST(MathErrorHandlingMatrix, checkUnitVector) {
Eigen::Matrix<double,Eigen::Dynamic,1> y(2);
double result;
y << sqrt(0.5), sqrt(0.5);
EXPECT_TRUE(stan::math::check_unit_vector("checkUnitVector(%1%)",
y, "y", &result));
y[1] = 0.55;
EXPECT_THROW(stan::math::check_unit_vector("checkUnitVector(%1%)", y, "y", &result),
std::domain_error);
}
<commit_msg>added failing nan test for check_unit_vector<commit_after>#include <stan/math/error_handling/matrix/check_unit_vector.hpp>
#include <gtest/gtest.h>
TEST(MathErrorHandlingMatrix, checkUnitVector) {
Eigen::Matrix<double,Eigen::Dynamic,1> y(2);
double result;
y << sqrt(0.5), sqrt(0.5);
EXPECT_TRUE(stan::math::check_unit_vector("checkUnitVector(%1%)",
y, "y", &result));
y[1] = 0.55;
EXPECT_THROW(stan::math::check_unit_vector("checkUnitVector(%1%)", y, "y", &result),
std::domain_error);
}
TEST(MathErrorHandlingMatrix, checkUnitVector_nan) {
Eigen::Matrix<double,Eigen::Dynamic,1> y(2);
double result;
double nan = std::numeric_limits<double>::quiet_NaN();
y << nan, sqrt(0.5);
EXPECT_THROW(stan::math::check_unit_vector("checkUnitVector(%1%)", y, "y", &result),
std::domain_error);
y << sqrt(0.5), nan;
EXPECT_THROW(stan::math::check_unit_vector("checkUnitVector(%1%)", y, "y", &result),
std::domain_error);
y << nan, nan;
EXPECT_THROW(stan::math::check_unit_vector("checkUnitVector(%1%)", y, "y", &result),
std::domain_error);
}
<|endoftext|>
|
<commit_before>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtCore/QString>
#include <QtTest/QtTest>
#include <QtCore/QCoreApplication>
#include "qnfctestcommon.h"
#include "qnfctestutil.h"
#include <qnearfieldmanager.h>
#include <qnearfieldtarget.h>
#include <qndefnfctextrecord.h>
#include <qndefnfcurirecord.h>
#include <qndefmessage.h>
#include <qndefrecord.h>
QTM_USE_NAMESPACE
Q_DECLARE_METATYPE(QNearFieldTarget*)
Q_DECLARE_METATYPE(QNearFieldTarget::Type)
Q_DECLARE_METATYPE(QNdefFilter)
class tst_QNearFieldManager : public QObject
{
Q_OBJECT
public:
tst_QNearFieldManager();
private Q_SLOTS:
void initTestCase();
void cleanupTestCase();
void targetDetected();
void targetDetected_data();
void unregisterTargetDetectedHandler();
void registerTargetDetectedHandler();
void registerTargetDetectedHandler_filter_data();
void registerTargetDetectedHandler_filter();
void registerTargetDetectedHandler_filter_negtive();
void registerTargetDetectedHandler_filter_negtive_data();
};
tst_QNearFieldManager::tst_QNearFieldManager()
{
qRegisterMetaType<QNdefMessage>("QNdefMessage");
qRegisterMetaType<QNearFieldTarget *>("QNearFieldTarget*");
}
void tst_QNearFieldManager::initTestCase()
{
qRegisterMetaType<QNearFieldTarget *>("QNearFieldTarget *");
}
void tst_QNearFieldManager::cleanupTestCase()
{
}
/*!
Description: Unit test for NFC target detected and lost
TestScenario: 1. Touch and remove llcp device/Type1/Type2/Type3/Type4 tag one by one
TestExpectedResults: 1. llcp device/Type1/Type2/Type3/Type4 tag detected/lost signal can be received
*/
void tst_QNearFieldManager::targetDetected()
{
QFETCH(QNearFieldTarget::Type, type);
QFETCH(QString, hint);
QNearFieldManager nfcManager;
QSignalSpy targetDetectedSpy(&nfcManager, SIGNAL(targetDetected(QNearFieldTarget*)));
QSignalSpy targetLostSpy(&nfcManager, SIGNAL(targetLost(QNearFieldTarget*)));
nfcManager.startTargetDetection(type);
QNfcTestUtil::ShowMessage(hint);
QTRY_VERIFY(!targetDetectedSpy.isEmpty());
QNearFieldTarget *target = targetDetectedSpy.at(targetDetectedSpy.count()-1).at(0).value<QNearFieldTarget *>();
QSignalSpy disconnectedSpy(target, SIGNAL(disconnected()));
QVERIFY(target);
if (type != QNearFieldTarget::AnyTarget)
{
QVERIFY(!target->uid().isEmpty());
QCOMPARE(target->type(), type);
}
QNfcTestUtil::ShowMessage("please remove the target");
QTRY_VERIFY(!targetLostSpy.isEmpty());
QNearFieldTarget *lostTarget = targetLostSpy.first().at(0).value<QNearFieldTarget *>();
QCOMPARE(target, lostTarget);
QVERIFY(!disconnectedSpy.isEmpty());
nfcManager.stopTargetDetection();
}
void tst_QNearFieldManager::targetDetected_data()
{
QTest::addColumn<QNearFieldTarget::Type>("type");
QTest::addColumn<QString>("hint");
QTest::newRow("llcp device") << QNearFieldTarget::AnyTarget << "Please touch llcp device";
QTest::newRow("NfcTagType1") << QNearFieldTarget::NfcTagType1 << "Please touch tag type1";
QTest::newRow("NfcTagType2") << QNearFieldTarget::NfcTagType2 << "Please touch tag type2";
QTest::newRow("NfcTagType3") << QNearFieldTarget::NfcTagType3 << "Please touch tag type3";
QTest::newRow("NfcTagType4") << QNearFieldTarget::NfcTagType4 << "Please touch tag type4";
}
/*!
Description: Unit test for NFC unregisterTargetDetectedHandler function
TestScenario: 1.
TestExpectedResults: 1. return false
*/
void tst_QNearFieldManager::unregisterTargetDetectedHandler()
{
QNearFieldManager manager;
QVERIFY(!manager.unregisterTargetDetectedHandler(-1));
QVERIFY(!manager.unregisterTargetDetectedHandler(0));
}
class MessageListener : public QObject
{
Q_OBJECT
signals:
void matchedNdefMessage(const QNdefMessage &message, QNearFieldTarget *target);
};
/*!
Description: Unit test for NFC registerTargetDetectedHandler function
TestScenario: 1. Symbian backend does not support registerTargetDetectedHandler without a QNdefFilter
TestExpectedResults: 1. return -1
*/
void tst_QNearFieldManager::registerTargetDetectedHandler()
{
QNearFieldManager manager;
MessageListener listener;
QSignalSpy messageSpy(&listener, SIGNAL(matchedNdefMessage(QNdefMessage,QNearFieldTarget*)));
int id = manager.registerTargetDetectedHandler(&listener,
SIGNAL(matchedNdefMessage(QNdefMessage,QNearFieldTarget*)));
QVERIFY(id == -1);//symbian backend does not support registerTargetDetectedHandler without QNdefFilter
}
void tst_QNearFieldManager::registerTargetDetectedHandler_filter_data()
{
QTest::addColumn<QNdefFilter>("filter");
QTest::addColumn<QString>("hint");
QNdefFilter filter;
filter.appendRecord(QNdefRecord::NfcRtd, "Sp");
QTest::newRow("SP") << filter << "Please touch a tag with 'SP' NDef message";
filter.clear();
filter.setOrderMatch(true);
filter.appendRecord(QNdefRecord::Mime, "image/gif");
filter.appendRecord<QNdefNfcTextRecord>(2, 10);
filter.appendRecord<QNdefNfcUriRecord>(1, 1);
QTest::newRow("Image + Multiple Text + URI") << filter << "Please touch a tag with 'Image + Multiple Text + URI' NDef message";
filter.clear();
filter.setOrderMatch(true);
filter.appendRecord<QNdefNfcTextRecord>(1, 1);
filter.appendRecord<QNdefNfcUriRecord>(1, 1);
QTest::newRow("Text + URI") << filter << "Please touch a tag with 'Text + URI' NDef message";
//negtive test
filter.clear();
filter.appendRecord<QNdefNfcUriRecord>(1, 1);
QTest::newRow("URI") << filter << "Please touch a tag without 'URI' NDef message";
}
/*!
Description: Unit test for NFC registerTargetDetectedHandler with a NDef filter
TestScenario: 1. Touch a tag with random NDef message/with 'Image + Multiple Text + URI' NDef message/with 'Text + URI' NDef message
TestExpectedResults: 1. matchedNdefMessage signal will be emitted
*/
void tst_QNearFieldManager::registerTargetDetectedHandler_filter()
{
QFETCH(QNdefFilter, filter);
QFETCH(QString, hint);
QNearFieldManager manager;
MessageListener listener;
QSignalSpy messageSpy(&listener, SIGNAL(matchedNdefMessage(QNdefMessage,QNearFieldTarget*)));
int id = manager.registerTargetDetectedHandler(filter, &listener,
SIGNAL(matchedNdefMessage(QNdefMessage,QNearFieldTarget*)));
QVERIFY(id != -1);
QNfcTestUtil::ShowMessage(hint);
QTRY_VERIFY(!messageSpy.isEmpty());
const QNdefMessage message = messageSpy.first().at(0).value<QNdefMessage>();
QNearFieldTarget *target = messageSpy.first().at(1).value<QNearFieldTarget *>();
QVERIFY(target == NULL);//symbain backend always return NULL target
QVERIFY(manager.unregisterTargetDetectedHandler(id));
}
void tst_QNearFieldManager::registerTargetDetectedHandler_filter_negtive_data()
{
QTest::addColumn<QNdefFilter>("filter");
QTest::addColumn<QString>("hint");
//negtive test
QNdefFilter filter;
QTest::newRow("Empty") << filter << "Please touch a tag without NDef message";
filter.clear();
filter.appendRecord<QNdefNfcUriRecord>(1, 1);
QTest::newRow("URI") << filter << "Please touch a tag without 'URI' NDef message";
}
/*!
Description: Unit test for NFC registerTargetDetectedHandler with a NDef filter
TestScenario: 1. Touch a tag without filter expected NDef message
TestExpectedResults: 1. matchedNdefMessage signal will NOT be emitted
*/
void tst_QNearFieldManager::registerTargetDetectedHandler_filter_negtive()
{
QFETCH(QNdefFilter, filter);
QFETCH(QString, hint);
QNearFieldManager manager;
MessageListener listener;
QSignalSpy messageSpy(&listener, SIGNAL(matchedNdefMessage(QNdefMessage,QNearFieldTarget*)));
int id = manager.registerTargetDetectedHandler(filter, &listener,
SIGNAL(matchedNdefMessage(QNdefMessage,QNearFieldTarget*)));
QVERIFY(id != -1);
QNfcTestUtil::ShowMessage(hint);
QTRY_VERIFY(messageSpy.isEmpty());
QVERIFY(manager.unregisterTargetDetectedHandler(id));
}
QTEST_MAIN(tst_QNearFieldManager);
#include "tst_qnearfieldmanager.moc"
<commit_msg>remove unused case<commit_after>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtCore/QString>
#include <QtTest/QtTest>
#include <QtCore/QCoreApplication>
#include "qnfctestcommon.h"
#include "qnfctestutil.h"
#include <qnearfieldmanager.h>
#include <qnearfieldtarget.h>
#include <qndefnfctextrecord.h>
#include <qndefnfcurirecord.h>
#include <qndefmessage.h>
#include <qndefrecord.h>
QTM_USE_NAMESPACE
Q_DECLARE_METATYPE(QNearFieldTarget*)
Q_DECLARE_METATYPE(QNearFieldTarget::Type)
Q_DECLARE_METATYPE(QNdefFilter)
class tst_QNearFieldManager : public QObject
{
Q_OBJECT
public:
tst_QNearFieldManager();
private Q_SLOTS:
void initTestCase();
void cleanupTestCase();
void targetDetected();
void targetDetected_data();
void unregisterTargetDetectedHandler();
void registerTargetDetectedHandler();
void registerTargetDetectedHandler_filter_data();
void registerTargetDetectedHandler_filter();
void registerTargetDetectedHandler_filter_negtive();
void registerTargetDetectedHandler_filter_negtive_data();
};
tst_QNearFieldManager::tst_QNearFieldManager()
{
qRegisterMetaType<QNdefMessage>("QNdefMessage");
qRegisterMetaType<QNearFieldTarget *>("QNearFieldTarget*");
}
void tst_QNearFieldManager::initTestCase()
{
qRegisterMetaType<QNearFieldTarget *>("QNearFieldTarget *");
}
void tst_QNearFieldManager::cleanupTestCase()
{
}
/*!
Description: Unit test for NFC target detected and lost
TestScenario: 1. Touch and remove llcp device/Type1/Type2/Type3/Type4 tag one by one
TestExpectedResults: 1. llcp device/Type1/Type2/Type3/Type4 tag detected/lost signal can be received
*/
void tst_QNearFieldManager::targetDetected()
{
QFETCH(QNearFieldTarget::Type, type);
QFETCH(QString, hint);
QNearFieldManager nfcManager;
QSignalSpy targetDetectedSpy(&nfcManager, SIGNAL(targetDetected(QNearFieldTarget*)));
QSignalSpy targetLostSpy(&nfcManager, SIGNAL(targetLost(QNearFieldTarget*)));
nfcManager.startTargetDetection(type);
QNfcTestUtil::ShowMessage(hint);
QTRY_VERIFY(!targetDetectedSpy.isEmpty());
QNearFieldTarget *target = targetDetectedSpy.at(targetDetectedSpy.count()-1).at(0).value<QNearFieldTarget *>();
QSignalSpy disconnectedSpy(target, SIGNAL(disconnected()));
QVERIFY(target);
if (type != QNearFieldTarget::AnyTarget)
{
QVERIFY(!target->uid().isEmpty());
QCOMPARE(target->type(), type);
}
QNfcTestUtil::ShowMessage("please remove the target");
QTRY_VERIFY(!targetLostSpy.isEmpty());
QNearFieldTarget *lostTarget = targetLostSpy.first().at(0).value<QNearFieldTarget *>();
QCOMPARE(target, lostTarget);
QVERIFY(!disconnectedSpy.isEmpty());
nfcManager.stopTargetDetection();
}
void tst_QNearFieldManager::targetDetected_data()
{
QTest::addColumn<QNearFieldTarget::Type>("type");
QTest::addColumn<QString>("hint");
QTest::newRow("llcp device") << QNearFieldTarget::AnyTarget << "Please touch llcp device";
QTest::newRow("NfcTagType1") << QNearFieldTarget::NfcTagType1 << "Please touch tag type1";
QTest::newRow("NfcTagType2") << QNearFieldTarget::NfcTagType2 << "Please touch tag type2";
QTest::newRow("NfcTagType3") << QNearFieldTarget::NfcTagType3 << "Please touch tag type3";
QTest::newRow("NfcTagType4") << QNearFieldTarget::NfcTagType4 << "Please touch tag type4";
}
/*!
Description: Unit test for NFC unregisterTargetDetectedHandler function
TestScenario: 1.
TestExpectedResults: 1. return false
*/
void tst_QNearFieldManager::unregisterTargetDetectedHandler()
{
QNearFieldManager manager;
QVERIFY(!manager.unregisterTargetDetectedHandler(-1));
QVERIFY(!manager.unregisterTargetDetectedHandler(0));
}
class MessageListener : public QObject
{
Q_OBJECT
signals:
void matchedNdefMessage(const QNdefMessage &message, QNearFieldTarget *target);
};
/*!
Description: Unit test for NFC registerTargetDetectedHandler function
TestScenario: 1. Symbian backend does not support registerTargetDetectedHandler without a QNdefFilter
TestExpectedResults: 1. return -1
*/
void tst_QNearFieldManager::registerTargetDetectedHandler()
{
QNearFieldManager manager;
MessageListener listener;
QSignalSpy messageSpy(&listener, SIGNAL(matchedNdefMessage(QNdefMessage,QNearFieldTarget*)));
int id = manager.registerTargetDetectedHandler(&listener,
SIGNAL(matchedNdefMessage(QNdefMessage,QNearFieldTarget*)));
QVERIFY(id == -1);//symbian backend does not support registerTargetDetectedHandler without QNdefFilter
}
void tst_QNearFieldManager::registerTargetDetectedHandler_filter_data()
{
QTest::addColumn<QNdefFilter>("filter");
QTest::addColumn<QString>("hint");
QNdefFilter filter;
filter.appendRecord(QNdefRecord::NfcRtd, "Sp");
QTest::newRow("SP") << filter << "Please touch a tag with 'SP' NDef message";
filter.clear();
filter.setOrderMatch(true);
filter.appendRecord<QNdefNfcTextRecord>(1, 1);
filter.appendRecord<QNdefNfcUriRecord>(1, 1);
QTest::newRow("Text + URI") << filter << "Please touch a tag with 'Text + URI' NDef message";
filter.clear();
filter.appendRecord<QNdefNfcUriRecord>(1, 1);
QTest::newRow("URI") << filter << "Please touch a tag with 'URI' NDef message";
}
/*!
Description: Unit test for NFC registerTargetDetectedHandler with a NDef filter
TestScenario: 1. Touch a tag with random NDef message/with 'Image + Multiple Text + URI' NDef message/with 'Text + URI' NDef message
TestExpectedResults: 1. matchedNdefMessage signal will be emitted
*/
void tst_QNearFieldManager::registerTargetDetectedHandler_filter()
{
QFETCH(QNdefFilter, filter);
QFETCH(QString, hint);
QNearFieldManager manager;
MessageListener listener;
QSignalSpy messageSpy(&listener, SIGNAL(matchedNdefMessage(QNdefMessage,QNearFieldTarget*)));
int id = manager.registerTargetDetectedHandler(filter, &listener,
SIGNAL(matchedNdefMessage(QNdefMessage,QNearFieldTarget*)));
QVERIFY(id != -1);
QNfcTestUtil::ShowMessage(hint);
QTRY_VERIFY(!messageSpy.isEmpty());
const QNdefMessage message = messageSpy.first().at(0).value<QNdefMessage>();
QNearFieldTarget *target = messageSpy.first().at(1).value<QNearFieldTarget *>();
QVERIFY(target == NULL);//symbain backend always return NULL target
QVERIFY(manager.unregisterTargetDetectedHandler(id));
}
void tst_QNearFieldManager::registerTargetDetectedHandler_filter_negtive_data()
{
QTest::addColumn<QNdefFilter>("filter");
QTest::addColumn<QString>("hint");
//negtive test
QNdefFilter filter;
QTest::newRow("Empty") << filter << "Please touch a tag without NDef message";
filter.clear();
filter.appendRecord<QNdefNfcUriRecord>(1, 1);
QTest::newRow("URI") << filter << "Please touch a tag without 'URI' NDef message";
}
/*!
Description: Unit test for NFC registerTargetDetectedHandler with a NDef filter
TestScenario: 1. Touch a tag without filter expected NDef message
TestExpectedResults: 1. matchedNdefMessage signal will NOT be emitted
*/
void tst_QNearFieldManager::registerTargetDetectedHandler_filter_negtive()
{
QFETCH(QNdefFilter, filter);
QFETCH(QString, hint);
QNearFieldManager manager;
MessageListener listener;
QSignalSpy messageSpy(&listener, SIGNAL(matchedNdefMessage(QNdefMessage,QNearFieldTarget*)));
int id = manager.registerTargetDetectedHandler(filter, &listener,
SIGNAL(matchedNdefMessage(QNdefMessage,QNearFieldTarget*)));
QVERIFY(id != -1);
QNfcTestUtil::ShowMessage(hint);
QTRY_VERIFY(messageSpy.isEmpty());
QVERIFY(manager.unregisterTargetDetectedHandler(id));
}
QTEST_MAIN(tst_QNearFieldManager);
#include "tst_qnearfieldmanager.moc"
<|endoftext|>
|
<commit_before>/**
* This file is part of the CernVM File System.
*/
#include "cvmfs_config.h"
#include "tracer.h"
#include <pthread.h>
#include <cassert>
#include <cerrno>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include "atomic.h"
#include "util/posix.h"
#include "util/string.h"
using namespace std; // NOLINT
void Tracer::Activate(
const int buffer_size,
const int flush_threshold,
const string &trace_file)
{
trace_file_ = trace_file;
buffer_size_ = buffer_size;
flush_threshold_ = flush_threshold;
assert(buffer_size_ > 1 && flush_threshold_>= 0
&& flush_threshold_ < buffer_size_);
ring_buffer_ = new BufferEntry[buffer_size_];
commit_buffer_ = new atomic_int32[buffer_size_];
for (int i = 0; i < buffer_size_; i++)
atomic_init32(&commit_buffer_[i]);
int retval;
retval = pthread_cond_init(&sig_continue_trace_, NULL);
retval |= pthread_mutex_init(&sig_continue_trace_mutex_, NULL);
retval |= pthread_cond_init(&sig_flush_, NULL);
retval |= pthread_mutex_init(&sig_flush_mutex_, NULL);
assert(retval == 0);
active_ = true;
}
/**
* Trace a message. This is usually a lock-free procedure that just
* requires two fetch_and_add operations and a gettimeofday syscall.
* There are two exceptions:
* -# If the ring buffer is full, the function blocks until the flush
* thread made some space. Avoid that by carefully choosing size
* and threshold.
* -# If this message reaches the threshold, the flush thread gets
* signaled.
*
* \param[in] event Arbitrary code, for consistency applications should use one
* of the TraceEvents constants. Negative codes are reserved
* for internal use.
* \param[in] id Arbitrary id, for example file name or module name which is
* doing the trace.
* \return The sequence number which was used to trace the record
*/
int32_t Tracer::DoTrace(
const int event,
const PathString &path,
const string &msg)
{
int32_t my_seq_no = atomic_xadd32(&seq_no_, 1);
timeval now;
gettimeofday(&now, NULL);
int pos = my_seq_no % buffer_size_;
while (my_seq_no - atomic_read32(&flushed_) >= buffer_size_) {
timespec timeout;
int retval;
GetTimespecRel(25, &timeout);
retval = pthread_mutex_lock(&sig_continue_trace_mutex_);
retval |= pthread_cond_timedwait(&sig_continue_trace_,
&sig_continue_trace_mutex_, &timeout);
retval |= pthread_mutex_unlock(&sig_continue_trace_mutex_);
assert(retval == ETIMEDOUT || retval == 0);
}
ring_buffer_[pos].time_stamp = now;
ring_buffer_[pos].code = event;
ring_buffer_[pos].path = path;
ring_buffer_[pos].msg = msg;
atomic_inc32(&commit_buffer_[pos]);
if (my_seq_no - atomic_read32(&flushed_) == flush_threshold_) {
LockMutex(&sig_flush_mutex_);
int err_code __attribute__((unused)) = pthread_cond_signal(&sig_flush_);
assert(err_code == 0 && "Could not signal flush thread");
UnlockMutex(&sig_flush_mutex_);
}
return my_seq_no;
}
void Tracer::Flush() {
if (!active_) return;
int32_t save_seq_no = DoTrace(kEventFlush, PathString("Tracer", 6),
"flushed ring buffer");
while (atomic_read32(&flushed_) <= save_seq_no) {
timespec timeout;
int retval;
atomic_cas32(&flush_immediately_, 0, 1);
LockMutex(&sig_flush_mutex_);
retval = pthread_cond_signal(&sig_flush_);
assert(retval == 0);
UnlockMutex(&sig_flush_mutex_);
GetTimespecRel(250, &timeout);
retval = pthread_mutex_lock(&sig_continue_trace_mutex_);
retval |= pthread_cond_timedwait(&sig_continue_trace_,
&sig_continue_trace_mutex_,
&timeout);
retval |= pthread_mutex_unlock(&sig_continue_trace_mutex_);
assert(retval == ETIMEDOUT || retval == 0);
}
}
void Tracer::GetTimespecRel(const int64_t ms, timespec *ts) {
timeval now;
gettimeofday(&now, NULL);
int64_t nsecs = now.tv_usec * 1000 + (ms % 1000)*1000*1000;
int carry = 0;
if (nsecs >= 1000*1000*1000) {
carry = 1;
nsecs -= 1000*1000*1000;
}
ts->tv_sec = now.tv_sec + ms/1000 + carry;
ts->tv_nsec = nsecs;
}
void *Tracer::MainFlush(void *data) {
Tracer *tracer = reinterpret_cast<Tracer *>(data);
int retval;
LockMutex(&tracer->sig_flush_mutex_);
FILE *f = fopen(tracer->trace_file_.c_str(), "a");
assert(f != NULL && "Could not open trace file");
struct timespec timeout;
do {
while ((atomic_read32(&tracer->terminate_flush_thread_) == 0) &&
(atomic_read32(&tracer->flush_immediately_) == 0) &&
(atomic_read32(&tracer->seq_no_) -
atomic_read32(&tracer->flushed_)
<= tracer->flush_threshold_))
{
tracer->GetTimespecRel(2000, &timeout);
retval = pthread_cond_timedwait(&tracer->sig_flush_,
&tracer->sig_flush_mutex_,
&timeout);
assert(retval != EINVAL);
}
int base = atomic_read32(&tracer->flushed_) % tracer->buffer_size_;
int pos, i = 0;
while ((i <= tracer->flush_threshold_) &&
(atomic_read32(&tracer->commit_buffer_[
pos = ((base + i) % tracer->buffer_size_)]) == 1))
{
string tmp;
tmp = StringifyTimeval(tracer->ring_buffer_[pos].time_stamp);
retval = tracer->WriteCsvFile(f, tmp);
retval |= fputc(',', f) - ',';
tmp = StringifyInt(tracer->ring_buffer_[pos].code);
retval = tracer->WriteCsvFile(f, tmp);
retval |= fputc(',', f) - ',';
retval |= tracer->WriteCsvFile(
f, tracer->ring_buffer_[pos].path.ToString());
retval |= fputc(',', f) - ',';
retval |= tracer->WriteCsvFile(f, tracer->ring_buffer_[pos].msg);
retval |= (fputc(13, f) - 13) | (fputc(10, f) - 10);
assert(retval == 0);
atomic_dec32(&tracer->commit_buffer_[pos]);
++i;
}
retval = fflush(f);
assert(retval == 0);
atomic_xadd32(&tracer->flushed_, i);
atomic_cas32(&tracer->flush_immediately_, 1, 0);
LockMutex(&tracer->sig_continue_trace_mutex_);
retval = pthread_cond_broadcast(&tracer->sig_continue_trace_);
assert(retval == 0);
UnlockMutex(&tracer->sig_continue_trace_mutex_);
} while ((atomic_read32(&tracer->terminate_flush_thread_) == 0) ||
(atomic_read32(&tracer->flushed_) <
atomic_read32(&tracer->seq_no_)));
UnlockMutex(&tracer->sig_flush_mutex_);
retval = fclose(f);
assert(retval == 0);
return NULL;
}
void Tracer::Spawn() {
if (active_) {
int retval = pthread_create(&thread_flush_, NULL, MainFlush, this);
assert(retval == 0);
spawned_ = true;
DoTrace(kEventStart, PathString("Tracer", 6), "Trace buffer created");
}
}
Tracer::Tracer()
: active_(false)
, spawned_(false)
, buffer_size_(0)
, flush_threshold_(0)
, ring_buffer_(NULL)
, commit_buffer_(NULL)
{
memset(&thread_flush_, 0, sizeof(thread_flush_));
atomic_init32(&seq_no_);
atomic_init32(&flushed_);
atomic_init32(&terminate_flush_thread_);
atomic_init32(&flush_immediately_);
}
Tracer::~Tracer() {
if (!active_)
return;
int retval;
if (spawned_) {
DoTrace(kEventStop, PathString("Tracer", 6), "Destroying trace buffer...");
// Trigger flushing and wait for it
atomic_inc32(&terminate_flush_thread_);
LockMutex(&sig_flush_mutex_);
retval = pthread_cond_signal(&sig_flush_);
assert(retval == 0);
UnlockMutex(&sig_flush_mutex_);
retval = pthread_join(thread_flush_, NULL);
assert(retval == 0);
}
retval = pthread_cond_destroy(&sig_continue_trace_);
retval |= pthread_mutex_destroy(&sig_continue_trace_mutex_);
retval |= pthread_cond_destroy(&sig_flush_);
retval |= pthread_mutex_destroy(&sig_flush_mutex_);
assert(retval == 0);
delete[] ring_buffer_;
delete[] commit_buffer_;
}
int Tracer::WriteCsvFile(FILE *fp, const string &field) {
if (fp == NULL)
return 0;
int retval;
if ((retval = fputc('"', fp)) != '"')
return retval;
for (unsigned i = 0, l = field.length(); i < l; ++i) {
if (field[i] == '"') {
if ((retval = fputc('"', fp)) != '"')
return retval;
}
if ((retval = fputc(field[i], fp)) != field[i])
return retval;
}
if ((retval = fputc('"', fp)) != '"')
return retval;
return 0;
}
<commit_msg>remove raw mutex from tracer.cc<commit_after>/**
* This file is part of the CernVM File System.
*/
#include "cvmfs_config.h"
#include "tracer.h"
#include <pthread.h>
#include <cassert>
#include <cerrno>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include "atomic.h"
#include "util/posix.h"
#include "util/string.h"
#include "util_concurrency.h"
using namespace std; // NOLINT
void Tracer::Activate(
const int buffer_size,
const int flush_threshold,
const string &trace_file)
{
trace_file_ = trace_file;
buffer_size_ = buffer_size;
flush_threshold_ = flush_threshold;
assert(buffer_size_ > 1 && flush_threshold_>= 0
&& flush_threshold_ < buffer_size_);
ring_buffer_ = new BufferEntry[buffer_size_];
commit_buffer_ = new atomic_int32[buffer_size_];
for (int i = 0; i < buffer_size_; i++)
atomic_init32(&commit_buffer_[i]);
int retval;
retval = pthread_cond_init(&sig_continue_trace_, NULL);
retval |= pthread_mutex_init(&sig_continue_trace_mutex_, NULL);
retval |= pthread_cond_init(&sig_flush_, NULL);
retval |= pthread_mutex_init(&sig_flush_mutex_, NULL);
assert(retval == 0);
active_ = true;
}
/**
* Trace a message. This is usually a lock-free procedure that just
* requires two fetch_and_add operations and a gettimeofday syscall.
* There are two exceptions:
* -# If the ring buffer is full, the function blocks until the flush
* thread made some space. Avoid that by carefully choosing size
* and threshold.
* -# If this message reaches the threshold, the flush thread gets
* signaled.
*
* \param[in] event Arbitrary code, for consistency applications should use one
* of the TraceEvents constants. Negative codes are reserved
* for internal use.
* \param[in] id Arbitrary id, for example file name or module name which is
* doing the trace.
* \return The sequence number which was used to trace the record
*/
int32_t Tracer::DoTrace(
const int event,
const PathString &path,
const string &msg)
{
int32_t my_seq_no = atomic_xadd32(&seq_no_, 1);
timeval now;
gettimeofday(&now, NULL);
int pos = my_seq_no % buffer_size_;
while (my_seq_no - atomic_read32(&flushed_) >= buffer_size_) {
timespec timeout;
int retval;
GetTimespecRel(25, &timeout);
retval = pthread_mutex_lock(&sig_continue_trace_mutex_);
retval |= pthread_cond_timedwait(&sig_continue_trace_,
&sig_continue_trace_mutex_, &timeout);
retval |= pthread_mutex_unlock(&sig_continue_trace_mutex_);
assert(retval == ETIMEDOUT || retval == 0);
}
ring_buffer_[pos].time_stamp = now;
ring_buffer_[pos].code = event;
ring_buffer_[pos].path = path;
ring_buffer_[pos].msg = msg;
atomic_inc32(&commit_buffer_[pos]);
if (my_seq_no - atomic_read32(&flushed_) == flush_threshold_) {
MutexLockGuard m(&sig_flush_mutex_);
int err_code __attribute__((unused)) = pthread_cond_signal(&sig_flush_);
assert(err_code == 0 && "Could not signal flush thread");
}
return my_seq_no;
}
void Tracer::Flush() {
if (!active_) return;
int32_t save_seq_no = DoTrace(kEventFlush, PathString("Tracer", 6),
"flushed ring buffer");
while (atomic_read32(&flushed_) <= save_seq_no) {
timespec timeout;
int retval;
atomic_cas32(&flush_immediately_, 0, 1);
{
MutexLockGuard m(&sig_flush_mutex_);
retval = pthread_cond_signal(&sig_flush_);
assert(retval == 0);
}
GetTimespecRel(250, &timeout);
retval = pthread_mutex_lock(&sig_continue_trace_mutex_);
retval |= pthread_cond_timedwait(&sig_continue_trace_,
&sig_continue_trace_mutex_,
&timeout);
retval |= pthread_mutex_unlock(&sig_continue_trace_mutex_);
assert(retval == ETIMEDOUT || retval == 0);
}
}
void Tracer::GetTimespecRel(const int64_t ms, timespec *ts) {
timeval now;
gettimeofday(&now, NULL);
int64_t nsecs = now.tv_usec * 1000 + (ms % 1000)*1000*1000;
int carry = 0;
if (nsecs >= 1000*1000*1000) {
carry = 1;
nsecs -= 1000*1000*1000;
}
ts->tv_sec = now.tv_sec + ms/1000 + carry;
ts->tv_nsec = nsecs;
}
void *Tracer::MainFlush(void *data) {
Tracer *tracer = reinterpret_cast<Tracer *>(data);
int retval;
MutexLockGuard m(&tracer->sig_flush_mutex_);
FILE *f = fopen(tracer->trace_file_.c_str(), "a");
assert(f != NULL && "Could not open trace file");
struct timespec timeout;
do {
while ((atomic_read32(&tracer->terminate_flush_thread_) == 0) &&
(atomic_read32(&tracer->flush_immediately_) == 0) &&
(atomic_read32(&tracer->seq_no_) -
atomic_read32(&tracer->flushed_)
<= tracer->flush_threshold_))
{
tracer->GetTimespecRel(2000, &timeout);
retval = pthread_cond_timedwait(&tracer->sig_flush_,
&tracer->sig_flush_mutex_,
&timeout);
assert(retval != EINVAL);
}
int base = atomic_read32(&tracer->flushed_) % tracer->buffer_size_;
int pos, i = 0;
while ((i <= tracer->flush_threshold_) &&
(atomic_read32(&tracer->commit_buffer_[
pos = ((base + i) % tracer->buffer_size_)]) == 1))
{
string tmp;
tmp = StringifyTimeval(tracer->ring_buffer_[pos].time_stamp);
retval = tracer->WriteCsvFile(f, tmp);
retval |= fputc(',', f) - ',';
tmp = StringifyInt(tracer->ring_buffer_[pos].code);
retval = tracer->WriteCsvFile(f, tmp);
retval |= fputc(',', f) - ',';
retval |= tracer->WriteCsvFile(
f, tracer->ring_buffer_[pos].path.ToString());
retval |= fputc(',', f) - ',';
retval |= tracer->WriteCsvFile(f, tracer->ring_buffer_[pos].msg);
retval |= (fputc(13, f) - 13) | (fputc(10, f) - 10);
assert(retval == 0);
atomic_dec32(&tracer->commit_buffer_[pos]);
++i;
}
retval = fflush(f);
assert(retval == 0);
atomic_xadd32(&tracer->flushed_, i);
atomic_cas32(&tracer->flush_immediately_, 1, 0);
{
MutexLockGuard l(&tracer->sig_continue_trace_mutex_);
retval = pthread_cond_broadcast(&tracer->sig_continue_trace_);
assert(retval == 0);
}
} while ((atomic_read32(&tracer->terminate_flush_thread_) == 0) ||
(atomic_read32(&tracer->flushed_) <
atomic_read32(&tracer->seq_no_)));
retval = fclose(f);
assert(retval == 0);
return NULL;
}
void Tracer::Spawn() {
if (active_) {
int retval = pthread_create(&thread_flush_, NULL, MainFlush, this);
assert(retval == 0);
spawned_ = true;
DoTrace(kEventStart, PathString("Tracer", 6), "Trace buffer created");
}
}
Tracer::Tracer()
: active_(false)
, spawned_(false)
, buffer_size_(0)
, flush_threshold_(0)
, ring_buffer_(NULL)
, commit_buffer_(NULL)
{
memset(&thread_flush_, 0, sizeof(thread_flush_));
atomic_init32(&seq_no_);
atomic_init32(&flushed_);
atomic_init32(&terminate_flush_thread_);
atomic_init32(&flush_immediately_);
}
Tracer::~Tracer() {
if (!active_)
return;
int retval;
if (spawned_) {
DoTrace(kEventStop, PathString("Tracer", 6), "Destroying trace buffer...");
// Trigger flushing and wait for it
atomic_inc32(&terminate_flush_thread_);
{
MutexLockGuard m(&sig_flush_mutex_);
retval = pthread_cond_signal(&sig_flush_);
assert(retval == 0);
}
retval = pthread_join(thread_flush_, NULL);
assert(retval == 0);
}
retval = pthread_cond_destroy(&sig_continue_trace_);
retval |= pthread_mutex_destroy(&sig_continue_trace_mutex_);
retval |= pthread_cond_destroy(&sig_flush_);
retval |= pthread_mutex_destroy(&sig_flush_mutex_);
assert(retval == 0);
delete[] ring_buffer_;
delete[] commit_buffer_;
}
int Tracer::WriteCsvFile(FILE *fp, const string &field) {
if (fp == NULL)
return 0;
int retval;
if ((retval = fputc('"', fp)) != '"')
return retval;
for (unsigned i = 0, l = field.length(); i < l; ++i) {
if (field[i] == '"') {
if ((retval = fputc('"', fp)) != '"')
return retval;
}
if ((retval = fputc(field[i], fp)) != field[i])
return retval;
}
if ((retval = fputc('"', fp)) != '"')
return retval;
return 0;
}
<|endoftext|>
|
<commit_before>// Query binary phrase tables.
// Christian Hardmeier, 16 May 2010
#include <cstdlib>
#include <cstring>
#include <string>
#include <vector>
#include "util.h"
#include "OnDiskWrapper.h"
#include "SourcePhrase.h"
using namespace std;
using namespace OnDiskPt;
void usage();
typedef unsigned int uint;
void Tokenize(OnDiskPt::Phrase &phrase
, const std::string &token, bool addSourceNonTerm, bool addTargetNonTerm
, OnDiskPt::OnDiskWrapper &onDiskWrapper)
{
bool nonTerm = false;
size_t tokSize = token.size();
int comStr =token.compare(0, 1, "[");
if (comStr == 0) {
comStr = token.compare(tokSize - 1, 1, "]");
nonTerm = comStr == 0;
}
if (nonTerm) {
// non-term
size_t splitPos = token.find_first_of("[", 2);
string wordStr = token.substr(0, splitPos);
if (splitPos == string::npos) {
// lhs - only 1 word
Word *word = new Word();
word->CreateFromString(wordStr, onDiskWrapper.GetVocab());
phrase.AddWord(word);
} else {
// source & target non-terms
if (addSourceNonTerm) {
Word *word = new Word();
word->CreateFromString(wordStr, onDiskWrapper.GetVocab());
phrase.AddWord(word);
}
wordStr = token.substr(splitPos, tokSize - splitPos);
if (addTargetNonTerm) {
Word *word = new Word();
word->CreateFromString(wordStr, onDiskWrapper.GetVocab());
phrase.AddWord(word);
}
}
} else {
// term
Word *word = new Word();
word->CreateFromString(token, onDiskWrapper.GetVocab());
phrase.AddWord(word);
}
}
int main(int argc, char **argv)
{
int tableLimit = 20;
std::string ttable = "";
bool useAlignments = false;
for(int i = 1; i < argc; i++) {
if(!strcmp(argv[i], "-tlimit")) {
if(i + 1 == argc)
usage();
tableLimit = atoi(argv[++i]);
} else if(!strcmp(argv[i], "-t")) {
if(i + 1 == argc)
usage();
ttable = argv[++i];
}
else
usage();
}
if(ttable == "")
usage();
OnDiskWrapper onDiskWrapper;
bool retDb = onDiskWrapper.BeginLoad(ttable);
CHECK(retDb);
cerr << "Ready..." << endl;
std::string line;
while(getline(std::cin, line)) {
std::vector<std::string> tokens;
tokens = Moses::Tokenize(line, " ");
cerr << "line: " << line << endl;
// create source phrase
SourcePhrase sourcePhrase;
for (size_t pos = 0; pos < tokens.size(); ++pos)
{
const string &tok = tokens[pos];
if (pos == tokens.size() - 1)
{ // last position. LHS non-term
Tokenize(sourcePhrase, tok, false, true, onDiskWrapper);
}
else
{
Tokenize(sourcePhrase, tok, true, true, onDiskWrapper);
}
}
const PhraseNode *node = &onDiskWrapper.GetRootSourceNode();
cerr << "node=" << node << endl;
assert(node);
for (size_t pos = 0; pos < sourcePhrase.GetSize(); ++pos)
{
const Word &word = sourcePhrase.GetWord(pos);
cerr << word << " ";
node = node->GetChild(word, onDiskWrapper);
cerr << "node=" << node << endl;
if (node == NULL)
{
break;
}
}
if (node)
{ // source phrase points to a bunch of rules
const TargetPhraseCollection *coll = node->GetTargetPhraseCollection(tableLimit, onDiskWrapper);
string str = coll->GetDebugStr();
cout << "Found " << coll->GetSize() << endl;
for (size_t ind = 0; ind < coll->GetSize(); ++ind)
{
const TargetPhrase &targetPhrase = coll->GetTargetPhrase(ind);
cerr << " ";
targetPhrase.DebugPrint(cerr, onDiskWrapper.GetVocab());
cerr << endl;
}
}
else
{
cout << "Not found" << endl;
}
std::cout << '\n';
std::cout.flush();
}
cerr << "Finished." << endl;
}
void usage()
{
std::cerr << "Usage: queryOnDiskPt [-n <nscores>] [-a] -t <ttable>\n"
"-tlimit <table limit> max number of rules per source phrase (default: 20)\n"
"-t <ttable> phrase table\n";
exit(1);
}
<commit_msg>Fix compile error.<commit_after>// Query binary phrase tables.
// Christian Hardmeier, 16 May 2010
#include <cstdlib>
#include <cstring>
#include <string>
#include <vector>
#include "Util.h"
#include "OnDiskWrapper.h"
#include "SourcePhrase.h"
using namespace std;
using namespace OnDiskPt;
void usage();
typedef unsigned int uint;
void Tokenize(OnDiskPt::Phrase &phrase
, const std::string &token, bool addSourceNonTerm, bool addTargetNonTerm
, OnDiskPt::OnDiskWrapper &onDiskWrapper)
{
bool nonTerm = false;
size_t tokSize = token.size();
int comStr =token.compare(0, 1, "[");
if (comStr == 0) {
comStr = token.compare(tokSize - 1, 1, "]");
nonTerm = comStr == 0;
}
if (nonTerm) {
// non-term
size_t splitPos = token.find_first_of("[", 2);
string wordStr = token.substr(0, splitPos);
if (splitPos == string::npos) {
// lhs - only 1 word
Word *word = new Word();
word->CreateFromString(wordStr, onDiskWrapper.GetVocab());
phrase.AddWord(word);
} else {
// source & target non-terms
if (addSourceNonTerm) {
Word *word = new Word();
word->CreateFromString(wordStr, onDiskWrapper.GetVocab());
phrase.AddWord(word);
}
wordStr = token.substr(splitPos, tokSize - splitPos);
if (addTargetNonTerm) {
Word *word = new Word();
word->CreateFromString(wordStr, onDiskWrapper.GetVocab());
phrase.AddWord(word);
}
}
} else {
// term
Word *word = new Word();
word->CreateFromString(token, onDiskWrapper.GetVocab());
phrase.AddWord(word);
}
}
int main(int argc, char **argv)
{
int tableLimit = 20;
std::string ttable = "";
bool useAlignments = false;
for(int i = 1; i < argc; i++) {
if(!strcmp(argv[i], "-tlimit")) {
if(i + 1 == argc)
usage();
tableLimit = atoi(argv[++i]);
} else if(!strcmp(argv[i], "-t")) {
if(i + 1 == argc)
usage();
ttable = argv[++i];
}
else
usage();
}
if(ttable == "")
usage();
OnDiskWrapper onDiskWrapper;
bool retDb = onDiskWrapper.BeginLoad(ttable);
CHECK(retDb);
cerr << "Ready..." << endl;
std::string line;
while(getline(std::cin, line)) {
std::vector<std::string> tokens;
tokens = Moses::Tokenize(line, " ");
cerr << "line: " << line << endl;
// create source phrase
SourcePhrase sourcePhrase;
for (size_t pos = 0; pos < tokens.size(); ++pos)
{
const string &tok = tokens[pos];
if (pos == tokens.size() - 1)
{ // last position. LHS non-term
Tokenize(sourcePhrase, tok, false, true, onDiskWrapper);
}
else
{
Tokenize(sourcePhrase, tok, true, true, onDiskWrapper);
}
}
const PhraseNode *node = &onDiskWrapper.GetRootSourceNode();
cerr << "node=" << node << endl;
assert(node);
for (size_t pos = 0; pos < sourcePhrase.GetSize(); ++pos)
{
const Word &word = sourcePhrase.GetWord(pos);
cerr << word << " ";
node = node->GetChild(word, onDiskWrapper);
cerr << "node=" << node << endl;
if (node == NULL)
{
break;
}
}
if (node)
{ // source phrase points to a bunch of rules
const TargetPhraseCollection *coll = node->GetTargetPhraseCollection(tableLimit, onDiskWrapper);
string str = coll->GetDebugStr();
cout << "Found " << coll->GetSize() << endl;
for (size_t ind = 0; ind < coll->GetSize(); ++ind)
{
const TargetPhrase &targetPhrase = coll->GetTargetPhrase(ind);
cerr << " ";
targetPhrase.DebugPrint(cerr, onDiskWrapper.GetVocab());
cerr << endl;
}
}
else
{
cout << "Not found" << endl;
}
std::cout << '\n';
std::cout.flush();
}
cerr << "Finished." << endl;
}
void usage()
{
std::cerr << "Usage: queryOnDiskPt [-n <nscores>] [-a] -t <ttable>\n"
"-tlimit <table limit> max number of rules per source phrase (default: 20)\n"
"-t <ttable> phrase table\n";
exit(1);
}
<|endoftext|>
|
<commit_before>/*
* server_test.cpp
*
* Created on: Jan 16, 2013
* Author: mfleder
*/
#include <stdio.h>
#include <boost/shared_ptr.hpp>
#include "affordance/AffordanceState.h"
//#include "affordance/OpenGL_Affordance.h"
#include <iostream>
using namespace boost;
using namespace std;
using namespace affordance;
int main(int argc, char ** argv)
{
//create affordance cylinder objects
AffPtr c(new AffordanceState());
c->setToCylinder(4, 0.18,
0,0, //uid/map id.
KDL::Frame(KDL::Vector(0,0,1)),
Eigen::Vector3f(0,1,0));
cout << "\nOriginal Cylinder:\n" << *c << endl;
//convert to LCM message
drc::affordance_t msg;
c->toMsg(&msg);
//get the raw bytes of the message
void* buffer = malloc(msg.getEncodedSize());
msg.encode(buffer, 0, msg.getEncodedSize());
//convert to lcm::LogEvent
lcm::LogEvent logEvent;
logEvent.eventnum = 0;
logEvent.timestamp = 0;
logEvent.channel = "test_channel";
logEvent.datalen = msg.getEncodedSize();
logEvent.data = buffer;
//write to disk
//'w' for write
lcm::LogFile *lFileWriter = new lcm::LogFile("lcm_io_test_save.bin", "w");
lFileWriter->writeEvent(&logEvent);
delete lFileWriter;
//read from disk
//'r' for read
lcm::LogFile *lFileReader = new lcm::LogFile("lcm_io_test_save.bin", "r");
const lcm::LogEvent* eventFromFile = lFileReader->readNextEvent();
//construct message from raw bytes
drc::affordance_t msgFromFile;
msgFromFile.decode(eventFromFile->data, 0, eventFromFile->datalen);
//now convert back to an AffordanceStateObject
AffPtr cylinderFromFile(new AffordanceState());
cylinderFromFile->fromMsg(&msgFromFile);
cout << "\n\n=====Read from file:\n" << *cylinderFromFile << endl;
return 0;
}
<commit_msg>updated test<commit_after>/*
* server_test.cpp
*
* Created on: Jan 16, 2013
* Author: mfleder
*/
#include <stdio.h>
#include <boost/shared_ptr.hpp>
#include "affordance/AffordanceState.h"
//#include "affordance/OpenGL_Affordance.h"
#include <iostream>
using namespace boost;
using namespace std;
using namespace affordance;
int main(int argc, char ** argv)
{
//create affordance cylinder objects
AffPtr c(new AffordanceState());
c->setToCylinder(4, 0.18,
0,0, //uid/map id.
KDL::Frame(KDL::Vector(0,0,1)),
Eigen::Vector3f(0,1,0));
cout << "\nOriginal Cylinder:\n" << *c << endl;
//convert to LCM message
drc::affordance_t msg;
c->toMsg(&msg);
//get the raw bytes of the message
void* buffer = malloc(msg.getEncodedSize());
msg.encode(buffer, 0, msg.getEncodedSize());
//convert to lcm::LogEvent
lcm::LogEvent logEvent;
logEvent.eventnum = 0;
logEvent.timestamp = 0;
logEvent.channel = "test_channel";
logEvent.datalen = msg.getEncodedSize();
logEvent.data = buffer;
//write to disk
//'w' for write
lcm::LogFile *lFileWriter = new lcm::LogFile("lcm_io_test_save.bin", "w");
lFileWriter->writeEvent(&logEvent);
delete lFileWriter;
//read from disk
//'r' for read
lcm::LogFile *lFileReader = new lcm::LogFile("lcm_io_test_save.bin", "r");
const lcm::LogEvent* eventFromFile = lFileReader->readNextEvent();
//construct message from raw bytes
drc::affordance_t msgFromFile;
msgFromFile.decode(eventFromFile->data, 0, eventFromFile->datalen);
//NOW we can delete the lFileReader. we couldn't delete it before
//b/c we had a pointer to the log event it read and seems to store internally
delete lFileReader;
//now convert back to an AffordanceStateObject
AffPtr cylinderFromFile(new AffordanceState());
cylinderFromFile->fromMsg(&msgFromFile);
cout << "\n\n=====Read from file:\n" << *cylinderFromFile << endl;
return 0;
}
<|endoftext|>
|
<commit_before>/*=========================================================================
*
* Copyright David Doria 2012 daviddoria@gmail.com
*
* 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 PoissonEditingWrappers_HPP
#define PoissonEditingWrappers_HPP
#include "PoissonEditingWrappers.h" // Appease syntax parser
// Submodules
#include "Helpers/Helpers.h"
#include "ITKHelpers/ITKHelpers.h"
// ITK
#include "itkAddImageFilter.h"
#include "itkImageRegionConstIterator.h"
#include "itkComposeImageFilter.h"
#include "itkLaplacianOperator.h"
#include "itkLaplacianImageFilter.h"
#include "itkVectorIndexSelectionCastImageFilter.h"
// Eigen
#include <Eigen/Sparse>
/** The terminology "targetImage" and "sourceImage" come from Poisson Cloning.
* To interpret these arguments in a Poisson Filling context, there is no source image
* (sourceImage must be nullptr), and the targetImage is the image to be filled.
*/
template <typename TImage>
void FillVectorImage(const TImage* const targetImage, const Mask* const mask,
const std::vector<PoissonEditingParent::GuidanceFieldType::Pointer>& guidanceFields,
TImage* const output, const itk::ImageRegion<2>& regionToProcess,
const TImage* const sourceImage)
{
std::cout << "FillVectorImage()" << std::endl;
if(!mask)
{
throw std::runtime_error("You must specify a mask!");
}
if(guidanceFields.size() != targetImage->GetNumberOfComponentsPerPixel())
{
std::stringstream ss;
ss << "There are " << targetImage->GetNumberOfComponentsPerPixel() << " channels but "
<< guidanceFields.size() << " guidance fields were specified (these must match).";
throw std::runtime_error(ss.str());
}
itk::ImageRegion<2> holeBoundingBox =
ITKHelpers::ComputeBoundingBox(mask, HoleMaskPixelTypeEnum::HOLE);
// Adjust the hole bounding box to be in the target position
itk::ImageRegion<2> holeBoundingBoxPositioned = holeBoundingBox;
holeBoundingBoxPositioned.SetIndex(regionToProcess.GetIndex() +
(holeBoundingBox.GetIndex() - mask->GetLargestPossibleRegion().GetIndex()));
if(!targetImage->GetLargestPossibleRegion().IsInside(holeBoundingBoxPositioned))
{
std::cerr << "Cannot clone at this position! Source image holes are outside of the target image!" << std::endl;
return;
}
// Crop the mask
Mask::Pointer croppedMask = Mask::New();
croppedMask->Allocate();
ITKHelpers::ExtractRegion(mask, holeBoundingBox, croppedMask.GetPointer());
// std::cout << "croppedMask region: " << croppedMask->GetLargestPossibleRegion() << std::endl;
// Setup components of the channel-wise processing
typedef itk::Image<typename TypeTraits<typename TImage::PixelType>::ComponentType, 2> ScalarImageType;
typedef itk::ComposeImageFilter<ScalarImageType, TImage> ReassemblerType;
typename ReassemblerType::Pointer reassembler = ReassemblerType::New();
// Perform the Poisson reconstruction on each channel independently
typedef typename TypeTraits<typename TImage::PixelType>::ComponentType ComponentType;
typedef PoissonEditing<ComponentType> PoissonEditingFilterType;
std::vector<typename ScalarImageType::Pointer> outputChannels(targetImage->GetNumberOfComponentsPerPixel());
//std::cout << "There are " << targetImage->GetNumberOfComponentsPerPixel() << " components in the output image." << std::endl;
for(unsigned int component = 0;
component < targetImage->GetNumberOfComponentsPerPixel(); ++component)
{
std::cout << "Filling component " << component << std::endl;
// Disassemble the target image into its components
typedef itk::VectorIndexSelectionCastImageFilter<TImage, ScalarImageType>
TargetDisassemblerType;
typename TargetDisassemblerType::Pointer targetDisassembler =
TargetDisassemblerType::New();
targetDisassembler->SetIndex(component);
targetDisassembler->SetInput(targetImage);
targetDisassembler->Update();
PoissonEditingParent::GuidanceFieldType::Pointer croppedGuidanceField =
PoissonEditingParent::GuidanceFieldType::New();
croppedGuidanceField->Allocate();
ITKHelpers::ExtractRegion(guidanceFields[component].GetPointer(), holeBoundingBox,
croppedGuidanceField.GetPointer());
// ITKHelpers::WriteImage(croppedGuidanceField.GetPointer(), "CroppedGuidanceField_" + std::to_string(component) + ".mha");
// Perform the actual filling
PoissonEditingFilterType poissonFilter;
poissonFilter.SetTargetImage(targetDisassembler->GetOutput());
poissonFilter.SetRegionToProcess(holeBoundingBoxPositioned);
// Disassemble the source image into its components
if(sourceImage)
{
std::cout << "Using sourceImage..." << std::endl;
typedef itk::VectorIndexSelectionCastImageFilter<TImage, ScalarImageType>
SourceDisassemblerType;
typename SourceDisassemblerType::Pointer sourceDisassembler =
SourceDisassemblerType::New();
sourceDisassembler->SetIndex(component);
sourceDisassembler->SetInput(sourceImage);
sourceDisassembler->Update();
typename ScalarImageType::Pointer croppedSourceImage =
ScalarImageType::New();
croppedSourceImage->Allocate();
ITKHelpers::ExtractRegion(sourceDisassembler->GetOutput(), holeBoundingBox,
croppedSourceImage.GetPointer());
poissonFilter.SetSourceImage(croppedSourceImage.GetPointer());
}
else
{
std::cout << "No source image provided - assuming Poisson Filling (versus Cloning)." << std::endl;
}
poissonFilter.SetGuidanceField(croppedGuidanceField.GetPointer());
poissonFilter.SetMask(croppedMask.GetPointer());
poissonFilter.FillMaskedRegion();
outputChannels[component] = ScalarImageType::New();
ITKHelpers::DeepCopy(poissonFilter.GetOutput(), outputChannels[component].GetPointer());
reassembler->SetInput(component, outputChannels[component]);
} // end loop over components
reassembler->Update();
// std::cout << "Output components per pixel: " << reassembler->GetOutput()->GetNumberOfComponentsPerPixel()
// << std::endl;
// std::cout << "Output size: " << reassembler->GetOutput()->GetLargestPossibleRegion().GetSize() << std::endl;
// ITKHelpers::WriteImage(reassembler->GetOutput(), "Output.mha");
ITKHelpers::DeepCopy(reassembler->GetOutput(), output);
}
/** Specialization for scalar images */
template <typename TScalarPixel>
void FillScalarImage(const itk::Image<TScalarPixel, 2>* const image,
const Mask* const mask,
const PoissonEditingParent::GuidanceFieldType* const guidanceField,
itk::Image<TScalarPixel, 2>* const output,
const itk::ImageRegion<2>& regionToProcess,
const itk::Image<TScalarPixel, 2>* const sourceImage)
{
typedef PoissonEditing<TScalarPixel> PoissonEditingFilterType;
PoissonEditingFilterType poissonFilter;
poissonFilter.SetTargetImage(image);
poissonFilter.SetRegionToProcess(regionToProcess);
poissonFilter.SetGuidanceField(guidanceField);
poissonFilter.SetMask(mask);
// Perform the actual filling
poissonFilter.FillMaskedRegion();
ITKHelpers::DeepCopy(poissonFilter.GetOutput(), output);
}
/** For scalar images. */
template <typename TScalarPixel>
void FillImage(const itk::Image<TScalarPixel, 2>* const image, const Mask* const mask,
const PoissonEditingParent::GuidanceFieldType* const guidanceField,
itk::Image<TScalarPixel, 2>* const output,
const itk::ImageRegion<2>& regionToProcess,
const itk::Image<TScalarPixel, 2>* const sourceImage)
{
FillScalarImage(image, mask, guidanceField, output, regionToProcess, sourceImage);
}
/** For multi-channel images with the same guidance field for each channel. */
template <typename TImage>
void
FillImage(const TImage* const image, const Mask* const mask,
const PoissonEditingParent::GuidanceFieldType* guidanceField,
TImage* const output, const itk::ImageRegion<2>& regionToProcess,
const TImage* const sourceImage)
{
std::cout << "FillImage with same guidance field for each channel." << std::endl;
std::vector<PoissonEditingParent::GuidanceFieldType::Pointer>
guidanceFields(image->GetNumberOfComponentsPerPixel(),
const_cast<PoissonEditingParent::GuidanceFieldType*>(guidanceField));
std::cout << "Duplicated guidance field for each of the "
<< image->GetNumberOfComponentsPerPixel() << " channels." << std::endl;
FillVectorImage(image, mask, guidanceFields, output, regionToProcess, sourceImage);
}
/** For multi-channel images with different guidance fields for each channel. */
template <typename TImage>
void
FillImage(const TImage* const image, const Mask* const mask,
const std::vector<PoissonEditingParent::GuidanceFieldType::Pointer>& guidanceFields,
TImage* const output, const itk::ImageRegion<2>& regionToProcess,
const TImage* const sourceImage)
{
// Always call the vector version, as it is the only one that makes sense
// to have passed a collection of guidance fields.
FillVectorImage(image, mask, guidanceFields, output, regionToProcess, sourceImage);
}
/** For Image<CovariantVector> images. */
template <typename TComponent, unsigned int NumberOfComponents>
void FillImage(const itk::Image<itk::CovariantVector<TComponent,
NumberOfComponents>, 2>* const image,
const Mask* const mask,
const PoissonEditingParent::GuidanceFieldType* const guidanceField,
itk::Image<itk::CovariantVector<TComponent,
NumberOfComponents>, 2>* const output,
const itk::ImageRegion<2>& regionToProcess,
const itk::Image<itk::CovariantVector<TComponent,
NumberOfComponents>, 2>* const sourceImage)
{
std::vector<PoissonEditingParent::GuidanceFieldType::Pointer>
guidanceFields(image->GetNumberOfComponentsPerPixel(),
const_cast<PoissonEditingParent::GuidanceFieldType*>(guidanceField));
FillVectorImage(image, mask, guidanceFields, output, regionToProcess, sourceImage);
}
/** For VectorImage images with the same guidance field for each channel.*/
template <typename TPixel>
static void
FillImage(const itk::VectorImage<TPixel>* const image,
const Mask* const mask,
const PoissonEditingParent::GuidanceFieldType* guidanceField,
itk::VectorImage<TPixel>* const output,
const itk::ImageRegion<2>& regionToProcess,
const itk::VectorImage<TPixel>* const sourceImage)
{
std::vector<PoissonEditingParent::GuidanceFieldType::Pointer>
guidanceFields(image->GetNumberOfComponentsPerPixel(),
const_cast<PoissonEditingParent::GuidanceFieldType*>(guidanceField));
FillVectorImage(image, mask, guidanceFields, output, regionToProcess, sourceImage);
}
/** For VectorImages with different guidance fields for each channel. */
template <typename TPixel>
void
FillImage(const itk::VectorImage<TPixel>* const image,
const Mask* const mask,
const std::vector<PoissonEditingParent::GuidanceFieldType::Pointer>& guidanceFields,
itk::VectorImage<TPixel>* const output,
const itk::ImageRegion<2>& regionToProcess,
const itk::VectorImage<TPixel>* const sourceImage)
{
FillVectorImage(image, mask, guidanceFields, output, regionToProcess, sourceImage);
}
#endif
<commit_msg>Fix bug where source image wasn't used in scalar image filling.<commit_after>/*=========================================================================
*
* Copyright David Doria 2012 daviddoria@gmail.com
*
* 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 PoissonEditingWrappers_HPP
#define PoissonEditingWrappers_HPP
#include "PoissonEditingWrappers.h" // Appease syntax parser
// Submodules
#include "Helpers/Helpers.h"
#include "ITKHelpers/ITKHelpers.h"
// ITK
#include "itkAddImageFilter.h"
#include "itkImageRegionConstIterator.h"
#include "itkComposeImageFilter.h"
#include "itkLaplacianOperator.h"
#include "itkLaplacianImageFilter.h"
#include "itkVectorIndexSelectionCastImageFilter.h"
// Eigen
#include <Eigen/Sparse>
/** The terminology "targetImage" and "sourceImage" come from Poisson Cloning.
* To interpret these arguments in a Poisson Filling context, there is no source image
* (sourceImage must be nullptr), and the targetImage is the image to be filled.
*/
template <typename TImage>
void FillVectorImage(const TImage* const targetImage, const Mask* const mask,
const std::vector<PoissonEditingParent::GuidanceFieldType::Pointer>& guidanceFields,
TImage* const output, const itk::ImageRegion<2>& regionToProcess,
const TImage* const sourceImage)
{
std::cout << "FillVectorImage()" << std::endl;
if(!mask)
{
throw std::runtime_error("You must specify a mask!");
}
if(guidanceFields.size() != targetImage->GetNumberOfComponentsPerPixel())
{
std::stringstream ss;
ss << "There are " << targetImage->GetNumberOfComponentsPerPixel() << " channels but "
<< guidanceFields.size() << " guidance fields were specified (these must match).";
throw std::runtime_error(ss.str());
}
itk::ImageRegion<2> holeBoundingBox =
ITKHelpers::ComputeBoundingBox(mask, HoleMaskPixelTypeEnum::HOLE);
// Adjust the hole bounding box to be in the target position
itk::ImageRegion<2> holeBoundingBoxPositioned = holeBoundingBox;
holeBoundingBoxPositioned.SetIndex(regionToProcess.GetIndex() +
(holeBoundingBox.GetIndex() - mask->GetLargestPossibleRegion().GetIndex()));
if(!targetImage->GetLargestPossibleRegion().IsInside(holeBoundingBoxPositioned))
{
std::cerr << "Cannot clone at this position! Source image holes are outside of the target image!" << std::endl;
return;
}
// Crop the mask
Mask::Pointer croppedMask = Mask::New();
croppedMask->Allocate();
ITKHelpers::ExtractRegion(mask, holeBoundingBox, croppedMask.GetPointer());
// std::cout << "croppedMask region: " << croppedMask->GetLargestPossibleRegion() << std::endl;
// Setup components of the channel-wise processing
typedef itk::Image<typename TypeTraits<typename TImage::PixelType>::ComponentType, 2> ScalarImageType;
typedef itk::ComposeImageFilter<ScalarImageType, TImage> ReassemblerType;
typename ReassemblerType::Pointer reassembler = ReassemblerType::New();
// Perform the Poisson reconstruction on each channel independently
typedef typename TypeTraits<typename TImage::PixelType>::ComponentType ComponentType;
typedef PoissonEditing<ComponentType> PoissonEditingFilterType;
std::vector<typename ScalarImageType::Pointer> outputChannels(targetImage->GetNumberOfComponentsPerPixel());
//std::cout << "There are " << targetImage->GetNumberOfComponentsPerPixel() << " components in the output image." << std::endl;
for(unsigned int component = 0;
component < targetImage->GetNumberOfComponentsPerPixel(); ++component)
{
std::cout << "Filling component " << component << std::endl;
// Disassemble the target image into its components
typedef itk::VectorIndexSelectionCastImageFilter<TImage, ScalarImageType>
TargetDisassemblerType;
typename TargetDisassemblerType::Pointer targetDisassembler =
TargetDisassemblerType::New();
targetDisassembler->SetIndex(component);
targetDisassembler->SetInput(targetImage);
targetDisassembler->Update();
PoissonEditingParent::GuidanceFieldType::Pointer croppedGuidanceField =
PoissonEditingParent::GuidanceFieldType::New();
croppedGuidanceField->Allocate();
ITKHelpers::ExtractRegion(guidanceFields[component].GetPointer(), holeBoundingBox,
croppedGuidanceField.GetPointer());
// ITKHelpers::WriteImage(croppedGuidanceField.GetPointer(), "CroppedGuidanceField_" + std::to_string(component) + ".mha");
// Perform the actual filling
PoissonEditingFilterType poissonFilter;
poissonFilter.SetTargetImage(targetDisassembler->GetOutput());
poissonFilter.SetRegionToProcess(holeBoundingBoxPositioned);
// Disassemble the source image into its components
if(sourceImage)
{
std::cout << "Using sourceImage..." << std::endl;
typedef itk::VectorIndexSelectionCastImageFilter<TImage, ScalarImageType>
SourceDisassemblerType;
typename SourceDisassemblerType::Pointer sourceDisassembler =
SourceDisassemblerType::New();
sourceDisassembler->SetIndex(component);
sourceDisassembler->SetInput(sourceImage);
sourceDisassembler->Update();
typename ScalarImageType::Pointer croppedSourceImage =
ScalarImageType::New();
croppedSourceImage->Allocate();
ITKHelpers::ExtractRegion(sourceDisassembler->GetOutput(), holeBoundingBox,
croppedSourceImage.GetPointer());
poissonFilter.SetSourceImage(croppedSourceImage.GetPointer());
}
else
{
std::cout << "No source image provided - assuming Poisson Filling (versus Cloning)." << std::endl;
}
poissonFilter.SetGuidanceField(croppedGuidanceField.GetPointer());
poissonFilter.SetMask(croppedMask.GetPointer());
poissonFilter.FillMaskedRegion();
outputChannels[component] = ScalarImageType::New();
ITKHelpers::DeepCopy(poissonFilter.GetOutput(), outputChannels[component].GetPointer());
reassembler->SetInput(component, outputChannels[component]);
} // end loop over components
reassembler->Update();
// std::cout << "Output components per pixel: " << reassembler->GetOutput()->GetNumberOfComponentsPerPixel()
// << std::endl;
// std::cout << "Output size: " << reassembler->GetOutput()->GetLargestPossibleRegion().GetSize() << std::endl;
// ITKHelpers::WriteImage(reassembler->GetOutput(), "Output.mha");
ITKHelpers::DeepCopy(reassembler->GetOutput(), output);
}
/** Specialization for scalar images */
template <typename TScalarPixel>
void FillScalarImage(const itk::Image<TScalarPixel, 2>* const image,
const Mask* const mask,
const PoissonEditingParent::GuidanceFieldType* const guidanceField,
itk::Image<TScalarPixel, 2>* const output,
const itk::ImageRegion<2>& regionToProcess,
const itk::Image<TScalarPixel, 2>* const sourceImage)
{
typedef PoissonEditing<TScalarPixel> PoissonEditingFilterType;
PoissonEditingFilterType poissonFilter;
poissonFilter.SetTargetImage(image);
poissonFilter.SetRegionToProcess(regionToProcess);
poissonFilter.SetGuidanceField(guidanceField);
poissonFilter.SetMask(mask);
if(sourceImage)
{
poissonFilter.SetSourceImage(sourceImage);
}
// Perform the actual filling
poissonFilter.FillMaskedRegion();
ITKHelpers::DeepCopy(poissonFilter.GetOutput(), output);
}
/** For scalar images. */
template <typename TScalarPixel>
void FillImage(const itk::Image<TScalarPixel, 2>* const image, const Mask* const mask,
const PoissonEditingParent::GuidanceFieldType* const guidanceField,
itk::Image<TScalarPixel, 2>* const output,
const itk::ImageRegion<2>& regionToProcess,
const itk::Image<TScalarPixel, 2>* const sourceImage)
{
FillScalarImage(image, mask, guidanceField, output, regionToProcess, sourceImage);
}
/** For multi-channel images with the same guidance field for each channel. */
template <typename TImage>
void
FillImage(const TImage* const image, const Mask* const mask,
const PoissonEditingParent::GuidanceFieldType* guidanceField,
TImage* const output, const itk::ImageRegion<2>& regionToProcess,
const TImage* const sourceImage)
{
std::cout << "FillImage with same guidance field for each channel." << std::endl;
std::vector<PoissonEditingParent::GuidanceFieldType::Pointer>
guidanceFields(image->GetNumberOfComponentsPerPixel(),
const_cast<PoissonEditingParent::GuidanceFieldType*>(guidanceField));
std::cout << "Duplicated guidance field for each of the "
<< image->GetNumberOfComponentsPerPixel() << " channels." << std::endl;
FillVectorImage(image, mask, guidanceFields, output, regionToProcess, sourceImage);
}
/** For multi-channel images with different guidance fields for each channel. */
template <typename TImage>
void
FillImage(const TImage* const image, const Mask* const mask,
const std::vector<PoissonEditingParent::GuidanceFieldType::Pointer>& guidanceFields,
TImage* const output, const itk::ImageRegion<2>& regionToProcess,
const TImage* const sourceImage)
{
// Always call the vector version, as it is the only one that makes sense
// to have passed a collection of guidance fields.
FillVectorImage(image, mask, guidanceFields, output, regionToProcess, sourceImage);
}
/** For Image<CovariantVector> images. */
template <typename TComponent, unsigned int NumberOfComponents>
void FillImage(const itk::Image<itk::CovariantVector<TComponent,
NumberOfComponents>, 2>* const image,
const Mask* const mask,
const PoissonEditingParent::GuidanceFieldType* const guidanceField,
itk::Image<itk::CovariantVector<TComponent,
NumberOfComponents>, 2>* const output,
const itk::ImageRegion<2>& regionToProcess,
const itk::Image<itk::CovariantVector<TComponent,
NumberOfComponents>, 2>* const sourceImage)
{
std::vector<PoissonEditingParent::GuidanceFieldType::Pointer>
guidanceFields(image->GetNumberOfComponentsPerPixel(),
const_cast<PoissonEditingParent::GuidanceFieldType*>(guidanceField));
FillVectorImage(image, mask, guidanceFields, output, regionToProcess, sourceImage);
}
/** For VectorImage images with the same guidance field for each channel.*/
template <typename TPixel>
static void
FillImage(const itk::VectorImage<TPixel>* const image,
const Mask* const mask,
const PoissonEditingParent::GuidanceFieldType* guidanceField,
itk::VectorImage<TPixel>* const output,
const itk::ImageRegion<2>& regionToProcess,
const itk::VectorImage<TPixel>* const sourceImage)
{
std::vector<PoissonEditingParent::GuidanceFieldType::Pointer>
guidanceFields(image->GetNumberOfComponentsPerPixel(),
const_cast<PoissonEditingParent::GuidanceFieldType*>(guidanceField));
FillVectorImage(image, mask, guidanceFields, output, regionToProcess, sourceImage);
}
/** For VectorImages with different guidance fields for each channel. */
template <typename TPixel>
void
FillImage(const itk::VectorImage<TPixel>* const image,
const Mask* const mask,
const std::vector<PoissonEditingParent::GuidanceFieldType::Pointer>& guidanceFields,
itk::VectorImage<TPixel>* const output,
const itk::ImageRegion<2>& regionToProcess,
const itk::VectorImage<TPixel>* const sourceImage)
{
FillVectorImage(image, mask, guidanceFields, output, regionToProcess, sourceImage);
}
#endif
<|endoftext|>
|
<commit_before>#include <string>
#include <cmath>
#include <memory>
#include <itkSpatialObjectReader.h>
#include <itkSpatialObjectWriter.h>
#include <vtkVersionMacros.h>
#include <vtkPolyData.h>
#include <vtkPointData.h>
#include <vtkPolyDataReader.h>
#include <vtkXMLPolyDataReader.h>
#include <vtkPolyDataWriter.h>
#include <vtkXMLPolyDataWriter.h>
#include <vtkSmartPointer.h>
#include <vtkCell.h>
#include <vtkFloatArray.h>
#include "fiberio.h"
// hide function to this compilation unit
namespace
{
inline double SQ2(double x)
{
return x * x;
}
};
void writeFiberFile(const std::string & filename, GroupType::Pointer fibergroup, bool saveProperties)
{
// Make sure origins are updated
fibergroup->ComputeObjectToWorldTransform();
// ITK Spatial Object
if( filename.rfind(".fib") != std::string::npos )
{
typedef itk::SpatialObjectWriter<3> WriterType;
WriterType::Pointer writer = WriterType::New();
writer->SetInput(fibergroup);
writer->SetFileName(filename);
writer->Update();
}
// VTK Poly Data
else if( filename.rfind(".vt") != std::string::npos )
{
// Build VTK data structure
vtkSmartPointer<vtkPolyData> polydata(vtkPolyData::New() );
vtkSmartPointer<vtkFloatArray> tensorsdata(vtkFloatArray::New() );
vtkSmartPointer<vtkIdList> ids(vtkIdList::New() );
vtkSmartPointer<vtkPoints> pts(vtkPoints::New() );
tensorsdata->SetNumberOfComponents(9);
polydata->SetPoints(pts);
ids->SetNumberOfIds(0);
pts->SetNumberOfPoints(0);
polydata->Allocate();
vtkFloatArray *scalarFA = vtkFloatArray::New();
vtkFloatArray *scalarMD = vtkFloatArray::New();
vtkFloatArray *scalarRD = vtkFloatArray::New();
vtkFloatArray *scalarAD = vtkFloatArray::New();
scalarFA->SetNumberOfComponents(1);
scalarFA->SetName("FA");
scalarMD->SetNumberOfComponents(1);
scalarMD->SetName("MD");
scalarAD->SetNumberOfComponents(1);
scalarAD->SetName("AD");
scalarRD->SetNumberOfComponents(1);
scalarRD->SetName("RD");
std::auto_ptr<ChildrenListType> children(fibergroup->GetChildren(0) );
typedef ChildrenListType::const_iterator IteratorType;
for( IteratorType it = children->begin(); it != children->end(); it++ )
{
itk::SpatialObject<3>* tmp = (*it).GetPointer();
itk::DTITubeSpatialObject<3>* tube = dynamic_cast<itk::DTITubeSpatialObject<3> *>(tmp);
unsigned int nPointsOnFiber = tube->GetNumberOfPoints();
vtkIdType currentId = ids->GetNumberOfIds();
for( unsigned int k = 0; k < nPointsOnFiber; k++ )
{
itk::Point<double, 3> v(tube->GetPoint(k)->GetPosition() );
itk::Vector<double, 3> spacing(tube->GetSpacing() );
itk::Vector<double, 3> origin(tube->GetObjectToWorldTransform()->GetOffset() );
// convert origin from LPS -> RAS
origin[0] = -origin[0];
origin[1] = -origin[1];
vtkIdType id;
// Need to multiply v by spacing and origin
// Also negate the first to convert from LPS -> RAS
// for slicer 3
id = pts->InsertNextPoint(-v[0] * spacing[0] + origin[0],
-v[1] * spacing[1] + origin[1],
v[2] * spacing[2] + origin[2]);
ids->InsertNextId(id);
itk::DTITubeSpatialObjectPoint<3>* sopt = dynamic_cast<itk::DTITubeSpatialObjectPoint<3> *>(tube->GetPoint(k) );
float vtktensor[9];
vtktensor[0] = sopt->GetTensorMatrix()[0];
vtktensor[1] = sopt->GetTensorMatrix()[1];
vtktensor[2] = sopt->GetTensorMatrix()[2];
vtktensor[3] = sopt->GetTensorMatrix()[1];
vtktensor[4] = sopt->GetTensorMatrix()[3];
vtktensor[5] = sopt->GetTensorMatrix()[4];
vtktensor[6] = sopt->GetTensorMatrix()[2];
vtktensor[7] = sopt->GetTensorMatrix()[4];
vtktensor[8] = sopt->GetTensorMatrix()[5];
//std::cout << "MD = " << sopt->GetField("md") << ", " ;
scalarFA->InsertNextValue(sopt->GetField("fa"));
scalarMD->InsertNextValue(sopt->GetField("md"));
scalarAD->InsertNextValue(sopt->GetField("ad"));
scalarRD->InsertNextValue(sopt->GetField("rd"));
tensorsdata->InsertNextTupleValue(vtktensor);
}
polydata->InsertNextCell(VTK_POLY_LINE, nPointsOnFiber, ids->GetPointer(currentId) );
}
polydata->GetPointData()->SetTensors(tensorsdata);
if (saveProperties)
{
polydata->GetPointData()->AddArray(scalarFA);
polydata->GetPointData()->AddArray(scalarMD);
polydata->GetPointData()->AddArray(scalarAD);
polydata->GetPointData()->AddArray(scalarRD);
}
// Legacy
if( filename.rfind(".vtk") != std::string::npos )
{
vtkSmartPointer<vtkPolyDataWriter> fiberwriter = vtkPolyDataWriter::New();
fiberwriter->SetFileTypeToBinary();
fiberwriter->SetFileName(filename.c_str() );
#if (VTK_MAJOR_VERSION < 6)
fiberwriter->SetInput(polydata);
#else
fiberwriter->SetInputData(polydata);
#endif
fiberwriter->Update();
}
// XML
else if( filename.rfind(".vtp") != std::string::npos )
{
vtkSmartPointer<vtkXMLPolyDataWriter> fiberwriter = vtkXMLPolyDataWriter::New();
fiberwriter->SetFileName(filename.c_str() );
#if (VTK_MAJOR_VERSION < 6)
fiberwriter->SetInput(polydata);
#else
fiberwriter->SetInputData(polydata);
#endif
fiberwriter->Update();
}
else
{
throw itk::ExceptionObject("Unknown file format for fibers");
}
}
else
{
throw itk::ExceptionObject("Unknown file format for fibers");
}
}
GroupType::Pointer readFiberFile(const std::string & filename)
{
// ITK Spatial Object
if( filename.rfind(".fib") != std::string::npos )
{
typedef itk::SpatialObjectReader<3, unsigned char> SpatialObjectReaderType;
// Reading spatial object
SpatialObjectReaderType::Pointer soreader = SpatialObjectReaderType::New();
soreader->SetFileName(filename);
soreader->Update();
return soreader->GetGroup();
}
// VTK Poly Data
else if( filename.rfind(".vt") != std::string::npos )
{
// Build up the principal data structure for fiber tracts
GroupType::Pointer fibergroup = GroupType::New();
vtkSmartPointer<vtkPolyData> fibdata(NULL);
// Legacy
if( filename.rfind(".vtk") != std::string::npos )
{
vtkSmartPointer<vtkPolyDataReader> reader(vtkPolyDataReader::New() );
reader->SetFileName(filename.c_str() );
reader->Update();
fibdata = reader->GetOutput();
}
else if( filename.rfind(".vtp") != std::string::npos )
{
vtkSmartPointer<vtkXMLPolyDataReader> reader(vtkXMLPolyDataReader::New() );
reader->SetFileName(filename.c_str() );
reader->Update();
fibdata = reader->GetOutput();
}
else
{
throw itk::ExceptionObject("Unknown file format for fibers");
}
typedef itk::SymmetricSecondRankTensor<double, 3> ITKTensorType;
typedef ITKTensorType::EigenValuesArrayType LambdaArrayType;
// Iterate over VTK data
const int nfib = fibdata->GetNumberOfCells();
int pindex = -1;
for( int i = 0; i < nfib; ++i )
{
itk::DTITubeSpatialObject<3>::Pointer dtiTube = itk::DTITubeSpatialObject<3>::New();
vtkSmartPointer<vtkCell> fib = fibdata->GetCell(i);
vtkSmartPointer<vtkPoints> points = fib->GetPoints();
typedef itk::DTITubeSpatialObjectPoint<3> DTIPointType;
std::vector<DTIPointType> pointsToAdd;
vtkSmartPointer<vtkDataArray> fibtensordata = fibdata->GetPointData()->GetTensors();
for( int j = 0; j < points->GetNumberOfPoints(); ++j )
{
++pindex;
double * coordinates = points->GetPoint(j);
DTIPointType pt;
// Convert from RAS to LPS for vtk
pt.SetPosition(-coordinates[0], -coordinates[1], coordinates[2]);
pt.SetRadius(0.5);
pt.SetColor(0.0, 1.0, 0.0);
double * vtktensor = fibtensordata->GetTuple9(pindex);
float floattensor[6];
ITKTensorType itktensor;
floattensor[0] = itktensor[0] = vtktensor[0];
floattensor[1] = itktensor[1] = vtktensor[1];
floattensor[2] = itktensor[2] = vtktensor[2];
floattensor[3] = itktensor[3] = vtktensor[4];
floattensor[4] = itktensor[4] = vtktensor[5];
floattensor[5] = itktensor[5] = vtktensor[8];
pt.SetTensorMatrix(floattensor);
LambdaArrayType lambdas;
// Need to do do eigenanalysis of the tensor
itktensor.ComputeEigenValues(lambdas);
// FIXME: We should not be repeating this code here. The code
// for all these computations should be re-factored into a
// common library.
float md = (lambdas[0] + lambdas[1] + lambdas[2]) / 3;
float fa = sqrt(1.5) * sqrt( (lambdas[0] - md) * (lambdas[0] - md)
+ (lambdas[1] - md) * (lambdas[1] - md)
+ (lambdas[2] - md) * (lambdas[2] - md) )
/ sqrt(lambdas[0] * lambdas[0] + lambdas[1] * lambdas[1] + lambdas[2] * lambdas[2]);
float logavg = (log(lambdas[0]) + log(lambdas[1]) + log(lambdas[2]) ) / 3;
float ga = sqrt( SQ2(log(lambdas[0]) - logavg) \
+ SQ2(log(lambdas[1]) - logavg) \
+ SQ2(log(lambdas[2]) - logavg) );
float rd = (lambdas[1] + lambdas[0])/2;
pt.AddField("fa", fa);
pt.AddField("ga", ga);
pt.AddField("md", md);
pt.AddField("l1", lambdas[2]);
pt.AddField("l2", lambdas[1]);
pt.AddField("l3", lambdas[0]);
pt.AddField("rd", rd);
pointsToAdd.push_back(pt);
}
dtiTube->SetPoints(pointsToAdd);
fibergroup->AddSpatialObject(dtiTube);
}
return fibergroup;
} // end process .vtk .vtp
else
{
throw itk::ExceptionObject("Unknown fiber file");
}
}
<commit_msg>COMP: backward compat to vtk5<commit_after>#include <string>
#include <cmath>
#include <memory>
#include <itkSpatialObjectReader.h>
#include <itkSpatialObjectWriter.h>
#include <vtkVersion.h>
#include <vtkPolyData.h>
#include <vtkPointData.h>
#include <vtkPolyDataReader.h>
#include <vtkXMLPolyDataReader.h>
#include <vtkPolyDataWriter.h>
#include <vtkXMLPolyDataWriter.h>
#include <vtkSmartPointer.h>
#include <vtkCell.h>
#include <vtkFloatArray.h>
#include "fiberio.h"
// hide function to this compilation unit
namespace
{
inline double SQ2(double x)
{
return x * x;
}
};
void writeFiberFile(const std::string & filename, GroupType::Pointer fibergroup, bool saveProperties)
{
// Make sure origins are updated
fibergroup->ComputeObjectToWorldTransform();
// ITK Spatial Object
if( filename.rfind(".fib") != std::string::npos )
{
typedef itk::SpatialObjectWriter<3> WriterType;
WriterType::Pointer writer = WriterType::New();
writer->SetInput(fibergroup);
writer->SetFileName(filename);
writer->Update();
}
// VTK Poly Data
else if( filename.rfind(".vt") != std::string::npos )
{
// Build VTK data structure
vtkSmartPointer<vtkPolyData> polydata(vtkPolyData::New() );
vtkSmartPointer<vtkFloatArray> tensorsdata(vtkFloatArray::New() );
vtkSmartPointer<vtkIdList> ids(vtkIdList::New() );
vtkSmartPointer<vtkPoints> pts(vtkPoints::New() );
tensorsdata->SetNumberOfComponents(9);
polydata->SetPoints(pts);
ids->SetNumberOfIds(0);
pts->SetNumberOfPoints(0);
polydata->Allocate();
vtkFloatArray *scalarFA = vtkFloatArray::New();
vtkFloatArray *scalarMD = vtkFloatArray::New();
vtkFloatArray *scalarRD = vtkFloatArray::New();
vtkFloatArray *scalarAD = vtkFloatArray::New();
scalarFA->SetNumberOfComponents(1);
scalarFA->SetName("FA");
scalarMD->SetNumberOfComponents(1);
scalarMD->SetName("MD");
scalarAD->SetNumberOfComponents(1);
scalarAD->SetName("AD");
scalarRD->SetNumberOfComponents(1);
scalarRD->SetName("RD");
std::auto_ptr<ChildrenListType> children(fibergroup->GetChildren(0) );
typedef ChildrenListType::const_iterator IteratorType;
for( IteratorType it = children->begin(); it != children->end(); it++ )
{
itk::SpatialObject<3>* tmp = (*it).GetPointer();
itk::DTITubeSpatialObject<3>* tube = dynamic_cast<itk::DTITubeSpatialObject<3> *>(tmp);
unsigned int nPointsOnFiber = tube->GetNumberOfPoints();
vtkIdType currentId = ids->GetNumberOfIds();
for( unsigned int k = 0; k < nPointsOnFiber; k++ )
{
itk::Point<double, 3> v(tube->GetPoint(k)->GetPosition() );
itk::Vector<double, 3> spacing(tube->GetSpacing() );
itk::Vector<double, 3> origin(tube->GetObjectToWorldTransform()->GetOffset() );
// convert origin from LPS -> RAS
origin[0] = -origin[0];
origin[1] = -origin[1];
vtkIdType id;
// Need to multiply v by spacing and origin
// Also negate the first to convert from LPS -> RAS
// for slicer 3
id = pts->InsertNextPoint(-v[0] * spacing[0] + origin[0],
-v[1] * spacing[1] + origin[1],
v[2] * spacing[2] + origin[2]);
ids->InsertNextId(id);
itk::DTITubeSpatialObjectPoint<3>* sopt = dynamic_cast<itk::DTITubeSpatialObjectPoint<3> *>(tube->GetPoint(k) );
float vtktensor[9];
vtktensor[0] = sopt->GetTensorMatrix()[0];
vtktensor[1] = sopt->GetTensorMatrix()[1];
vtktensor[2] = sopt->GetTensorMatrix()[2];
vtktensor[3] = sopt->GetTensorMatrix()[1];
vtktensor[4] = sopt->GetTensorMatrix()[3];
vtktensor[5] = sopt->GetTensorMatrix()[4];
vtktensor[6] = sopt->GetTensorMatrix()[2];
vtktensor[7] = sopt->GetTensorMatrix()[4];
vtktensor[8] = sopt->GetTensorMatrix()[5];
//std::cout << "MD = " << sopt->GetField("md") << ", " ;
scalarFA->InsertNextValue(sopt->GetField("fa"));
scalarMD->InsertNextValue(sopt->GetField("md"));
scalarAD->InsertNextValue(sopt->GetField("ad"));
scalarRD->InsertNextValue(sopt->GetField("rd"));
tensorsdata->InsertNextTupleValue(vtktensor);
}
polydata->InsertNextCell(VTK_POLY_LINE, nPointsOnFiber, ids->GetPointer(currentId) );
}
polydata->GetPointData()->SetTensors(tensorsdata);
if (saveProperties)
{
polydata->GetPointData()->AddArray(scalarFA);
polydata->GetPointData()->AddArray(scalarMD);
polydata->GetPointData()->AddArray(scalarAD);
polydata->GetPointData()->AddArray(scalarRD);
}
// Legacy
if( filename.rfind(".vtk") != std::string::npos )
{
vtkSmartPointer<vtkPolyDataWriter> fiberwriter = vtkPolyDataWriter::New();
fiberwriter->SetFileTypeToBinary();
fiberwriter->SetFileName(filename.c_str() );
#if (VTK_MAJOR_VERSION < 6)
fiberwriter->SetInput(polydata);
#else
fiberwriter->SetInputData(polydata);
#endif
fiberwriter->Update();
}
// XML
else if( filename.rfind(".vtp") != std::string::npos )
{
vtkSmartPointer<vtkXMLPolyDataWriter> fiberwriter = vtkXMLPolyDataWriter::New();
fiberwriter->SetFileName(filename.c_str() );
#if (VTK_MAJOR_VERSION < 6)
fiberwriter->SetInput(polydata);
#else
fiberwriter->SetInputData(polydata);
#endif
fiberwriter->Update();
}
else
{
throw itk::ExceptionObject("Unknown file format for fibers");
}
}
else
{
throw itk::ExceptionObject("Unknown file format for fibers");
}
}
GroupType::Pointer readFiberFile(const std::string & filename)
{
// ITK Spatial Object
if( filename.rfind(".fib") != std::string::npos )
{
typedef itk::SpatialObjectReader<3, unsigned char> SpatialObjectReaderType;
// Reading spatial object
SpatialObjectReaderType::Pointer soreader = SpatialObjectReaderType::New();
soreader->SetFileName(filename);
soreader->Update();
return soreader->GetGroup();
}
// VTK Poly Data
else if( filename.rfind(".vt") != std::string::npos )
{
// Build up the principal data structure for fiber tracts
GroupType::Pointer fibergroup = GroupType::New();
vtkSmartPointer<vtkPolyData> fibdata(NULL);
// Legacy
if( filename.rfind(".vtk") != std::string::npos )
{
vtkSmartPointer<vtkPolyDataReader> reader(vtkPolyDataReader::New() );
reader->SetFileName(filename.c_str() );
reader->Update();
fibdata = reader->GetOutput();
}
else if( filename.rfind(".vtp") != std::string::npos )
{
vtkSmartPointer<vtkXMLPolyDataReader> reader(vtkXMLPolyDataReader::New() );
reader->SetFileName(filename.c_str() );
reader->Update();
fibdata = reader->GetOutput();
}
else
{
throw itk::ExceptionObject("Unknown file format for fibers");
}
typedef itk::SymmetricSecondRankTensor<double, 3> ITKTensorType;
typedef ITKTensorType::EigenValuesArrayType LambdaArrayType;
// Iterate over VTK data
const int nfib = fibdata->GetNumberOfCells();
int pindex = -1;
for( int i = 0; i < nfib; ++i )
{
itk::DTITubeSpatialObject<3>::Pointer dtiTube = itk::DTITubeSpatialObject<3>::New();
vtkSmartPointer<vtkCell> fib = fibdata->GetCell(i);
vtkSmartPointer<vtkPoints> points = fib->GetPoints();
typedef itk::DTITubeSpatialObjectPoint<3> DTIPointType;
std::vector<DTIPointType> pointsToAdd;
vtkSmartPointer<vtkDataArray> fibtensordata = fibdata->GetPointData()->GetTensors();
for( int j = 0; j < points->GetNumberOfPoints(); ++j )
{
++pindex;
double * coordinates = points->GetPoint(j);
DTIPointType pt;
// Convert from RAS to LPS for vtk
pt.SetPosition(-coordinates[0], -coordinates[1], coordinates[2]);
pt.SetRadius(0.5);
pt.SetColor(0.0, 1.0, 0.0);
double * vtktensor = fibtensordata->GetTuple9(pindex);
float floattensor[6];
ITKTensorType itktensor;
floattensor[0] = itktensor[0] = vtktensor[0];
floattensor[1] = itktensor[1] = vtktensor[1];
floattensor[2] = itktensor[2] = vtktensor[2];
floattensor[3] = itktensor[3] = vtktensor[4];
floattensor[4] = itktensor[4] = vtktensor[5];
floattensor[5] = itktensor[5] = vtktensor[8];
pt.SetTensorMatrix(floattensor);
LambdaArrayType lambdas;
// Need to do do eigenanalysis of the tensor
itktensor.ComputeEigenValues(lambdas);
// FIXME: We should not be repeating this code here. The code
// for all these computations should be re-factored into a
// common library.
float md = (lambdas[0] + lambdas[1] + lambdas[2]) / 3;
float fa = sqrt(1.5) * sqrt( (lambdas[0] - md) * (lambdas[0] - md)
+ (lambdas[1] - md) * (lambdas[1] - md)
+ (lambdas[2] - md) * (lambdas[2] - md) )
/ sqrt(lambdas[0] * lambdas[0] + lambdas[1] * lambdas[1] + lambdas[2] * lambdas[2]);
float logavg = (log(lambdas[0]) + log(lambdas[1]) + log(lambdas[2]) ) / 3;
float ga = sqrt( SQ2(log(lambdas[0]) - logavg) \
+ SQ2(log(lambdas[1]) - logavg) \
+ SQ2(log(lambdas[2]) - logavg) );
float rd = (lambdas[1] + lambdas[0])/2;
pt.AddField("fa", fa);
pt.AddField("ga", ga);
pt.AddField("md", md);
pt.AddField("l1", lambdas[2]);
pt.AddField("l2", lambdas[1]);
pt.AddField("l3", lambdas[0]);
pt.AddField("rd", rd);
pointsToAdd.push_back(pt);
}
dtiTube->SetPoints(pointsToAdd);
fibergroup->AddSpatialObject(dtiTube);
}
return fibergroup;
} // end process .vtk .vtp
else
{
throw itk::ExceptionObject("Unknown fiber file");
}
}
<|endoftext|>
|
<commit_before>//
// 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 "AttributeAnimation.h"
#include "Camera.h"
#include "CoreEvents.h"
#include "Engine.h"
#include "Font.h"
#include "Graphics.h"
#include "Input.h"
#include "Material.h"
#include "Model.h"
#include "Octree.h"
#include "Renderer.h"
#include "ResourceCache.h"
#include "Scene.h"
#include "StaticModel.h"
#include "Text.h"
#include "UI.h"
#include "StaticScene.h"
#include "DebugNew.h"
DEFINE_APPLICATION_MAIN(StaticScene)
StaticScene::StaticScene(Context* context) :
Sample(context),
yaw_(0.0f),
pitch_(0.0f)
{
}
void StaticScene::Start()
{
// Execute base class startup
Sample::Start();
// Create the scene content
CreateScene();
// Create the UI content
CreateInstructions();
// Setup the viewport for displaying the scene
SetupViewport();
// Hook up to the frame update events
SubscribeToEvents();
}
void StaticScene::CreateScene()
{
ResourceCache* cache = GetSubsystem<ResourceCache>();
scene_ = new Scene(context_);
// Create the Octree component to the scene. This is required before adding any drawable components, or else nothing will
// show up. The default octree volume will be from (-1000, -1000, -1000) to (1000, 1000, 1000) in world coordinates; it
// is also legal to place objects outside the volume but their visibility can then not be checked in a hierarchically
// optimizing manner
scene_->CreateComponent<Octree>();
// Create a child scene node (at world origin) and a StaticModel component into it. Set the StaticModel to show a simple
// plane mesh with a "stone" material. Note that naming the scene nodes is optional. Scale the scene node larger
// (100 x 100 world units)
Node* planeNode = scene_->CreateChild("Plane");
planeNode->SetScale(Vector3(100.0f, 1.0f, 100.0f));
StaticModel* planeObject = planeNode->CreateComponent<StaticModel>();
planeObject->SetModel(cache->GetResource<Model>("Models/Plane.mdl"));
planeObject->SetMaterial(cache->GetResource<Material>("Materials/StoneTiled.xml"));
// Create a directional light to the world so that we can see something. The light scene node's orientation controls the
// light direction; we will use the SetDirection() function which calculates the orientation from a forward direction vector.
// The light will use default settings (white light, no shadows)
Node* lightNode = scene_->CreateChild("DirectionalLight");
lightNode->SetDirection(Vector3(0.6f, -1.0f, 0.8f)); // The direction vector does not need to be normalized
Light* light = lightNode->CreateComponent<Light>();
light->SetLightType(LIGHT_DIRECTIONAL);
AttributeAnimation* lightColorAnimation = new AttributeAnimation(context_);
lightColorAnimation->AddKeyFrame(0.0f, Color(1.0f, 1.0f, 1.0f, 1.0f));
lightColorAnimation->AddKeyFrame(1.0f, Color(1.0f, 0.0f, 0.0f, 1.0f));
lightColorAnimation->AddKeyFrame(2.0f, Color(0.0f, 0.0f, 1.0f, 1.0f));
lightColorAnimation->AddKeyFrame(3.0f, Color(1.0f, 1.0f, 1.0f, 1.0f));
light->SetAttributeAnimation("Color", lightColorAnimation);
// Create more StaticModel objects to the scene, randomly positioned, rotated and scaled. For rotation, we construct a
// quaternion from Euler angles where the Y angle (rotation about the Y axis) is randomized. The mushroom model contains
// LOD levels, so the StaticModel component will automatically select the LOD level according to the view distance (you'll
// see the model get simpler as it moves further away). Finally, rendering a large number of the same object with the
// same material allows instancing to be used, if the GPU supports it. This reduces the amount of CPU work in rendering the
// scene.
const unsigned NUM_OBJECTS = 200;
for (unsigned i = 0; i < NUM_OBJECTS; ++i)
{
Node* mushroomNode = scene_->CreateChild("Mushroom");
mushroomNode->SetPosition(Vector3(Random(90.0f) - 45.0f, 0.0f, Random(90.0f) - 45.0f));
mushroomNode->SetRotation(Quaternion(0.0f, Random(360.0f), 0.0f));
mushroomNode->SetScale(0.5f + Random(2.0f));
StaticModel* mushroomObject = mushroomNode->CreateComponent<StaticModel>();
mushroomObject->SetModel(cache->GetResource<Model>("Models/Mushroom.mdl"));
mushroomObject->SetMaterial(cache->GetResource<Material>("Materials/Mushroom.xml"));
}
// Create a scene node for the camera, which we will move around
// The camera will use default settings (1000 far clip distance, 45 degrees FOV, set aspect ratio automatically)
cameraNode_ = scene_->CreateChild("Camera");
cameraNode_->CreateComponent<Camera>();
// Set an initial position for the camera scene node above the plane
cameraNode_->SetPosition(Vector3(0.0f, 5.0f, 0.0f));
}
void StaticScene::CreateInstructions()
{
ResourceCache* cache = GetSubsystem<ResourceCache>();
UI* ui = GetSubsystem<UI>();
// Construct new Text object, set string to display and font to use
Text* instructionText = ui->GetRoot()->CreateChild<Text>();
instructionText->SetText("Use WASD keys and mouse to move");
instructionText->SetFont(cache->GetResource<Font>("Fonts/Anonymous Pro.ttf"), 15);
// Position the text relative to the screen center
instructionText->SetHorizontalAlignment(HA_CENTER);
instructionText->SetVerticalAlignment(VA_CENTER);
instructionText->SetPosition(0, ui->GetRoot()->GetHeight() / 4);
}
void StaticScene::SetupViewport()
{
Renderer* renderer = GetSubsystem<Renderer>();
// Set up a viewport to the Renderer subsystem so that the 3D scene can be seen. We need to define the scene and the camera
// at minimum. Additionally we could configure the viewport screen size and the rendering path (eg. forward / deferred) to
// use, but now we just use full screen and default render path configured in the engine command line options
SharedPtr<Viewport> viewport(new Viewport(context_, scene_, cameraNode_->GetComponent<Camera>()));
renderer->SetViewport(0, viewport);
}
void StaticScene::MoveCamera(float timeStep)
{
// Do not move if the UI has a focused element (the console)
if (GetSubsystem<UI>()->GetFocusElement())
return;
Input* input = GetSubsystem<Input>();
// Movement speed as world units per second
const float MOVE_SPEED = 20.0f;
// Mouse sensitivity as degrees per pixel
const float MOUSE_SENSITIVITY = 0.1f;
// Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees
IntVector2 mouseMove = input->GetMouseMove();
yaw_ += MOUSE_SENSITIVITY * mouseMove.x_;
pitch_ += MOUSE_SENSITIVITY * mouseMove.y_;
pitch_ = Clamp(pitch_, -90.0f, 90.0f);
// Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero
cameraNode_->SetRotation(Quaternion(pitch_, yaw_, 0.0f));
// Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
// Use the TranslateRelative() function to move relative to the node's orientation. Alternatively we could
// multiply the desired direction with the node's orientation quaternion, and use just Translate()
if (input->GetKeyDown('W'))
cameraNode_->TranslateRelative(Vector3::FORWARD * MOVE_SPEED * timeStep);
if (input->GetKeyDown('S'))
cameraNode_->TranslateRelative(Vector3::BACK * MOVE_SPEED * timeStep);
if (input->GetKeyDown('A'))
cameraNode_->TranslateRelative(Vector3::LEFT * MOVE_SPEED * timeStep);
if (input->GetKeyDown('D'))
cameraNode_->TranslateRelative(Vector3::RIGHT * MOVE_SPEED * timeStep);
}
void StaticScene::SubscribeToEvents()
{
// Subscribe HandleUpdate() function for processing update events
SubscribeToEvent(E_UPDATE, HANDLER(StaticScene, HandleUpdate));
}
void StaticScene::HandleUpdate(StringHash eventType, VariantMap& eventData)
{
using namespace Update;
// Take the frame time step, which is stored as a float
float timeStep = eventData[P_TIMESTEP].GetFloat();
// Move the camera, scale movement with time step
MoveCamera(timeStep);
}
<commit_msg>Add commend and use shared ptr for attribute animation. [ci skip]<commit_after>//
// 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 "AttributeAnimation.h"
#include "Camera.h"
#include "CoreEvents.h"
#include "Engine.h"
#include "Font.h"
#include "Graphics.h"
#include "Input.h"
#include "Material.h"
#include "Model.h"
#include "Octree.h"
#include "Renderer.h"
#include "ResourceCache.h"
#include "Scene.h"
#include "StaticModel.h"
#include "Text.h"
#include "UI.h"
#include "StaticScene.h"
#include "DebugNew.h"
DEFINE_APPLICATION_MAIN(StaticScene)
StaticScene::StaticScene(Context* context) :
Sample(context),
yaw_(0.0f),
pitch_(0.0f)
{
}
void StaticScene::Start()
{
// Execute base class startup
Sample::Start();
// Create the scene content
CreateScene();
// Create the UI content
CreateInstructions();
// Setup the viewport for displaying the scene
SetupViewport();
// Hook up to the frame update events
SubscribeToEvents();
}
void StaticScene::CreateScene()
{
ResourceCache* cache = GetSubsystem<ResourceCache>();
scene_ = new Scene(context_);
// Create the Octree component to the scene. This is required before adding any drawable components, or else nothing will
// show up. The default octree volume will be from (-1000, -1000, -1000) to (1000, 1000, 1000) in world coordinates; it
// is also legal to place objects outside the volume but their visibility can then not be checked in a hierarchically
// optimizing manner
scene_->CreateComponent<Octree>();
// Create a child scene node (at world origin) and a StaticModel component into it. Set the StaticModel to show a simple
// plane mesh with a "stone" material. Note that naming the scene nodes is optional. Scale the scene node larger
// (100 x 100 world units)
Node* planeNode = scene_->CreateChild("Plane");
planeNode->SetScale(Vector3(100.0f, 1.0f, 100.0f));
StaticModel* planeObject = planeNode->CreateComponent<StaticModel>();
planeObject->SetModel(cache->GetResource<Model>("Models/Plane.mdl"));
planeObject->SetMaterial(cache->GetResource<Material>("Materials/StoneTiled.xml"));
// Create a directional light to the world so that we can see something. The light scene node's orientation controls the
// light direction; we will use the SetDirection() function which calculates the orientation from a forward direction vector.
// The light will use default settings (white light, no shadows)
Node* lightNode = scene_->CreateChild("DirectionalLight");
lightNode->SetDirection(Vector3(0.6f, -1.0f, 0.8f)); // The direction vector does not need to be normalized
Light* light = lightNode->CreateComponent<Light>();
light->SetLightType(LIGHT_DIRECTIONAL);
// Test code for attribute animation
SharedPtr<AttributeAnimation> lightColorAnimation(new AttributeAnimation(context_));
lightColorAnimation->AddKeyFrame(0.0f, Color(1.0f, 1.0f, 1.0f, 1.0f));
lightColorAnimation->AddKeyFrame(1.0f, Color(1.0f, 0.0f, 0.0f, 1.0f));
lightColorAnimation->AddKeyFrame(2.0f, Color(0.0f, 0.0f, 1.0f, 1.0f));
lightColorAnimation->AddKeyFrame(3.0f, Color(1.0f, 1.0f, 1.0f, 1.0f));
light->SetAttributeAnimation("Color", lightColorAnimation);
// Create more StaticModel objects to the scene, randomly positioned, rotated and scaled. For rotation, we construct a
// quaternion from Euler angles where the Y angle (rotation about the Y axis) is randomized. The mushroom model contains
// LOD levels, so the StaticModel component will automatically select the LOD level according to the view distance (you'll
// see the model get simpler as it moves further away). Finally, rendering a large number of the same object with the
// same material allows instancing to be used, if the GPU supports it. This reduces the amount of CPU work in rendering the
// scene.
const unsigned NUM_OBJECTS = 200;
for (unsigned i = 0; i < NUM_OBJECTS; ++i)
{
Node* mushroomNode = scene_->CreateChild("Mushroom");
mushroomNode->SetPosition(Vector3(Random(90.0f) - 45.0f, 0.0f, Random(90.0f) - 45.0f));
mushroomNode->SetRotation(Quaternion(0.0f, Random(360.0f), 0.0f));
mushroomNode->SetScale(0.5f + Random(2.0f));
StaticModel* mushroomObject = mushroomNode->CreateComponent<StaticModel>();
mushroomObject->SetModel(cache->GetResource<Model>("Models/Mushroom.mdl"));
mushroomObject->SetMaterial(cache->GetResource<Material>("Materials/Mushroom.xml"));
}
// Create a scene node for the camera, which we will move around
// The camera will use default settings (1000 far clip distance, 45 degrees FOV, set aspect ratio automatically)
cameraNode_ = scene_->CreateChild("Camera");
cameraNode_->CreateComponent<Camera>();
// Set an initial position for the camera scene node above the plane
cameraNode_->SetPosition(Vector3(0.0f, 5.0f, 0.0f));
}
void StaticScene::CreateInstructions()
{
ResourceCache* cache = GetSubsystem<ResourceCache>();
UI* ui = GetSubsystem<UI>();
// Construct new Text object, set string to display and font to use
Text* instructionText = ui->GetRoot()->CreateChild<Text>();
instructionText->SetText("Use WASD keys and mouse to move");
instructionText->SetFont(cache->GetResource<Font>("Fonts/Anonymous Pro.ttf"), 15);
// Position the text relative to the screen center
instructionText->SetHorizontalAlignment(HA_CENTER);
instructionText->SetVerticalAlignment(VA_CENTER);
instructionText->SetPosition(0, ui->GetRoot()->GetHeight() / 4);
}
void StaticScene::SetupViewport()
{
Renderer* renderer = GetSubsystem<Renderer>();
// Set up a viewport to the Renderer subsystem so that the 3D scene can be seen. We need to define the scene and the camera
// at minimum. Additionally we could configure the viewport screen size and the rendering path (eg. forward / deferred) to
// use, but now we just use full screen and default render path configured in the engine command line options
SharedPtr<Viewport> viewport(new Viewport(context_, scene_, cameraNode_->GetComponent<Camera>()));
renderer->SetViewport(0, viewport);
}
void StaticScene::MoveCamera(float timeStep)
{
// Do not move if the UI has a focused element (the console)
if (GetSubsystem<UI>()->GetFocusElement())
return;
Input* input = GetSubsystem<Input>();
// Movement speed as world units per second
const float MOVE_SPEED = 20.0f;
// Mouse sensitivity as degrees per pixel
const float MOUSE_SENSITIVITY = 0.1f;
// Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees
IntVector2 mouseMove = input->GetMouseMove();
yaw_ += MOUSE_SENSITIVITY * mouseMove.x_;
pitch_ += MOUSE_SENSITIVITY * mouseMove.y_;
pitch_ = Clamp(pitch_, -90.0f, 90.0f);
// Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero
cameraNode_->SetRotation(Quaternion(pitch_, yaw_, 0.0f));
// Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
// Use the TranslateRelative() function to move relative to the node's orientation. Alternatively we could
// multiply the desired direction with the node's orientation quaternion, and use just Translate()
if (input->GetKeyDown('W'))
cameraNode_->TranslateRelative(Vector3::FORWARD * MOVE_SPEED * timeStep);
if (input->GetKeyDown('S'))
cameraNode_->TranslateRelative(Vector3::BACK * MOVE_SPEED * timeStep);
if (input->GetKeyDown('A'))
cameraNode_->TranslateRelative(Vector3::LEFT * MOVE_SPEED * timeStep);
if (input->GetKeyDown('D'))
cameraNode_->TranslateRelative(Vector3::RIGHT * MOVE_SPEED * timeStep);
}
void StaticScene::SubscribeToEvents()
{
// Subscribe HandleUpdate() function for processing update events
SubscribeToEvent(E_UPDATE, HANDLER(StaticScene, HandleUpdate));
}
void StaticScene::HandleUpdate(StringHash eventType, VariantMap& eventData)
{
using namespace Update;
// Take the frame time step, which is stored as a float
float timeStep = eventData[P_TIMESTEP].GetFloat();
// Move the camera, scale movement with time step
MoveCamera(timeStep);
}
<|endoftext|>
|
<commit_before>// Copyright 2016 Vladimir Alyamkin. All Rights Reserved.
#include "VaRestPluginPrivatePCH.h"
#include "Base64.h"
//////////////////////////////////////////////////////////////////////////
// Helpers
FString UVaRestLibrary::PercentEncode(const FString& Source)
{
FString OutText = Source;
OutText = OutText.Replace(TEXT(" "), TEXT("%20"));
OutText = OutText.Replace(TEXT("!"), TEXT("%21"));
OutText = OutText.Replace(TEXT("\""), TEXT("%22"));
OutText = OutText.Replace(TEXT("#"), TEXT("%23"));
OutText = OutText.Replace(TEXT("$"), TEXT("%24"));
OutText = OutText.Replace(TEXT("&"), TEXT("%26"));
OutText = OutText.Replace(TEXT("'"), TEXT("%27"));
OutText = OutText.Replace(TEXT("("), TEXT("%28"));
OutText = OutText.Replace(TEXT(")"), TEXT("%29"));
OutText = OutText.Replace(TEXT("*"), TEXT("%2A"));
OutText = OutText.Replace(TEXT("+"), TEXT("%2B"));
OutText = OutText.Replace(TEXT(","), TEXT("%2C"));
OutText = OutText.Replace(TEXT("/"), TEXT("%2F"));
OutText = OutText.Replace(TEXT(":"), TEXT("%3A"));
OutText = OutText.Replace(TEXT(";"), TEXT("%3B"));
OutText = OutText.Replace(TEXT("="), TEXT("%3D"));
OutText = OutText.Replace(TEXT("?"), TEXT("%3F"));
OutText = OutText.Replace(TEXT("@"), TEXT("%40"));
OutText = OutText.Replace(TEXT("["), TEXT("%5B"));
OutText = OutText.Replace(TEXT("]"), TEXT("%5D"));
OutText = OutText.Replace(TEXT("{"), TEXT("%7B"));
OutText = OutText.Replace(TEXT("}"), TEXT("%7D"));
return OutText;
}
FString UVaRestLibrary::Base64Encode(const FString& Source)
{
return FBase64::Encode(Source);
}
bool UVaRestLibrary::Base64Decode(const FString& Source, FString& Dest)
{
return FBase64::Decode(Source, Dest);
}
bool UVaRestLibrary::Base64EncodeData(const TArray<uint8>& Data, FString& Dest){
if (Data.Num()) {
Dest=FBase64::Encode(Data);
return true;
}
return false;
}
bool UVaRestLibrary::Base64DecodeData(const FString& Source, TArray<uint8>& Dest) {
return FBase64::Decode(Source, Dest);
}
//////////////////////////////////////////////////////////////////////////
// Easy URL processing
TMap<UVaRestRequestJSON*, FVaRestCallResponse> UVaRestLibrary::RequestMap;
void UVaRestLibrary::CallURL(UObject* WorldContextObject, const FString& URL, ERequestVerb Verb, ERequestContentType ContentType, UVaRestJsonObject* VaRestJson, const FVaRestCallDelegate& Callback)
{
UWorld* World = GEngine->GetWorldFromContextObject(WorldContextObject);
if (World == nullptr)
{
UE_LOG(LogVaRest, Error, TEXT("UVaRestLibrary: Wrong world context"))
return;
}
// Check we have valid data json
if (VaRestJson == nullptr)
{
VaRestJson = UVaRestJsonObject::ConstructJsonObject(WorldContextObject);
}
UVaRestRequestJSON* Request = NewObject<UVaRestRequestJSON>();
Request->SetVerb(Verb);
Request->SetContentType(ContentType);
Request->SetRequestObject(VaRestJson);
FVaRestCallResponse Response;
Response.Request = Request;
Response.WorldContextObject = WorldContextObject;
Response.Callback = Callback;
Response.CompleteDelegateHandle = Request->OnStaticRequestComplete.AddStatic(&UVaRestLibrary::OnCallComplete);
Response.FailDelegateHandle = Request->OnStaticRequestFail.AddStatic(&UVaRestLibrary::OnCallComplete);
RequestMap.Add(Request, Response);
Request->ResetResponseData();
Request->ProcessURL(URL);
}
void UVaRestLibrary::OnCallComplete(UVaRestRequestJSON* Request)
{
if (!RequestMap.Contains(Request))
{
return;
}
FVaRestCallResponse* Response = RequestMap.Find(Request);
Request->OnStaticRequestComplete.Remove(Response->CompleteDelegateHandle);
Request->OnStaticRequestFail.Remove(Response->FailDelegateHandle);
Response->Callback.ExecuteIfBound(Request);
Response->WorldContextObject = nullptr;
Response->Request = nullptr;
RequestMap.Remove(Request);
}
<commit_msg>Fix formatting issues<commit_after>// Copyright 2016 Vladimir Alyamkin. All Rights Reserved.
#include "VaRestPluginPrivatePCH.h"
#include "Base64.h"
//////////////////////////////////////////////////////////////////////////
// Helpers
FString UVaRestLibrary::PercentEncode(const FString& Source)
{
FString OutText = Source;
OutText = OutText.Replace(TEXT(" "), TEXT("%20"));
OutText = OutText.Replace(TEXT("!"), TEXT("%21"));
OutText = OutText.Replace(TEXT("\""), TEXT("%22"));
OutText = OutText.Replace(TEXT("#"), TEXT("%23"));
OutText = OutText.Replace(TEXT("$"), TEXT("%24"));
OutText = OutText.Replace(TEXT("&"), TEXT("%26"));
OutText = OutText.Replace(TEXT("'"), TEXT("%27"));
OutText = OutText.Replace(TEXT("("), TEXT("%28"));
OutText = OutText.Replace(TEXT(")"), TEXT("%29"));
OutText = OutText.Replace(TEXT("*"), TEXT("%2A"));
OutText = OutText.Replace(TEXT("+"), TEXT("%2B"));
OutText = OutText.Replace(TEXT(","), TEXT("%2C"));
OutText = OutText.Replace(TEXT("/"), TEXT("%2F"));
OutText = OutText.Replace(TEXT(":"), TEXT("%3A"));
OutText = OutText.Replace(TEXT(";"), TEXT("%3B"));
OutText = OutText.Replace(TEXT("="), TEXT("%3D"));
OutText = OutText.Replace(TEXT("?"), TEXT("%3F"));
OutText = OutText.Replace(TEXT("@"), TEXT("%40"));
OutText = OutText.Replace(TEXT("["), TEXT("%5B"));
OutText = OutText.Replace(TEXT("]"), TEXT("%5D"));
OutText = OutText.Replace(TEXT("{"), TEXT("%7B"));
OutText = OutText.Replace(TEXT("}"), TEXT("%7D"));
return OutText;
}
FString UVaRestLibrary::Base64Encode(const FString& Source)
{
return FBase64::Encode(Source);
}
bool UVaRestLibrary::Base64Decode(const FString& Source, FString& Dest)
{
return FBase64::Decode(Source, Dest);
}
bool UVaRestLibrary::Base64EncodeData(const TArray<uint8>& Data, FString& Dest)
{
if (Data.Num() > 0)
{
Dest = FBase64::Encode(Data);
return true;
}
return false;
}
bool UVaRestLibrary::Base64DecodeData(const FString& Source, TArray<uint8>& Dest)
{
return FBase64::Decode(Source, Dest);
}
//////////////////////////////////////////////////////////////////////////
// Easy URL processing
TMap<UVaRestRequestJSON*, FVaRestCallResponse> UVaRestLibrary::RequestMap;
void UVaRestLibrary::CallURL(UObject* WorldContextObject, const FString& URL, ERequestVerb Verb, ERequestContentType ContentType, UVaRestJsonObject* VaRestJson, const FVaRestCallDelegate& Callback)
{
UWorld* World = GEngine->GetWorldFromContextObject(WorldContextObject);
if (World == nullptr)
{
UE_LOG(LogVaRest, Error, TEXT("UVaRestLibrary: Wrong world context"))
return;
}
// Check we have valid data json
if (VaRestJson == nullptr)
{
VaRestJson = UVaRestJsonObject::ConstructJsonObject(WorldContextObject);
}
UVaRestRequestJSON* Request = NewObject<UVaRestRequestJSON>();
Request->SetVerb(Verb);
Request->SetContentType(ContentType);
Request->SetRequestObject(VaRestJson);
FVaRestCallResponse Response;
Response.Request = Request;
Response.WorldContextObject = WorldContextObject;
Response.Callback = Callback;
Response.CompleteDelegateHandle = Request->OnStaticRequestComplete.AddStatic(&UVaRestLibrary::OnCallComplete);
Response.FailDelegateHandle = Request->OnStaticRequestFail.AddStatic(&UVaRestLibrary::OnCallComplete);
RequestMap.Add(Request, Response);
Request->ResetResponseData();
Request->ProcessURL(URL);
}
void UVaRestLibrary::OnCallComplete(UVaRestRequestJSON* Request)
{
if (!RequestMap.Contains(Request))
{
return;
}
FVaRestCallResponse* Response = RequestMap.Find(Request);
Request->OnStaticRequestComplete.Remove(Response->CompleteDelegateHandle);
Request->OnStaticRequestFail.Remove(Response->FailDelegateHandle);
Response->Callback.ExecuteIfBound(Request);
Response->WorldContextObject = nullptr;
Response->Request = nullptr;
RequestMap.Remove(Request);
}
<|endoftext|>
|
<commit_before>//
// Created by tseyler on 2/9/16.
//
#include <iostream>
#include "sipproxy_pipeline.hpp"
#include <core/data/proto_net_pipe.hpp>
void
sipproxy_pipeline::ps_pipeline(const proto_net_in_data& req_data, proto_net_out_data& res_data)
{
proto_net_pipe pipe(req_data);
proto_net_data data_in = req_data;
data_in.data_type(data_text);
std::cout << "SipProxy Pipeline: Data in = " << data_in << std::endl;
// res_data = pipe.ps_pipe_data_out();
//proto_net_data data_out = res_data;
// data_out.data_type(data_text);
// std::cout << "SipProxy Pipeline: Data out = " << data_out << std::endl;
}
<commit_msg>Commented out pipe in siproxy_pipeline.<commit_after>//
// Created by tseyler on 2/9/16.
//
#include <iostream>
#include "sipproxy_pipeline.hpp"
#include <core/data/proto_net_pipe.hpp>
void
sipproxy_pipeline::ps_pipeline(const proto_net_in_data& req_data, proto_net_out_data& res_data)
{
// proto_net_pipe pipe(req_data);
proto_net_data data_in = req_data;
data_in.data_type(data_text);
std::cout << "SipProxy Pipeline: Data in = " << data_in << std::endl;
// res_data = pipe.ps_pipe_data_out();
//proto_net_data data_out = res_data;
// data_out.data_type(data_text);
// std::cout << "SipProxy Pipeline: Data out = " << data_out << std::endl;
}
<|endoftext|>
|
<commit_before>#include "Server.h"
#include "logging.h"
Server::Server(const char* localIP, int port){
this->localIP = std::string(localIP);
this->port = port;
sizeAddressClient = sizeof(struct sockaddr);
msg = new char[MAXMSG+1];
/*
* Configurações do endereço
*/
memset(&address, 0, sizeof(address));
address.sin_family = AF_INET;
address.sin_port = htons(port);
//address.sin_addr.s_addr = INADDR_ANY;
address.sin_addr.s_addr = inet_addr(localIP);
connected = false;
exitFlag = false;
waitingFlag =false;
}
bool Server::start(){
if(getSocket() == false){
return false;
}
if(doBind() == false){
return false;
}
if(startListening() == false){
return false;
}
waitingFlag = false;
return true;
}
bool Server::getSocket(){
/*
* Criando o Socket
*
* PARAM1: AF_INET ou AF_INET6 (IPV4 ou IPV6)
* PARAM2: SOCK_STREAM ou SOCK_DGRAM
* PARAM3: protocolo (IP, UDP, TCP, etc). Valor 0 escolhe automaticamente
*/
socketId = socket(AF_INET, SOCK_STREAM, 0);
//Verificar erros
if (socketId == -1)
{
log("SERVER", "Failed to create socket()");
return false;
}
return true;
}
bool Server::doBind(){
//Conectando o socket a uma porta. Executado apenas no lado servidor
if (bind (socketId, (struct sockaddr *)&address, sizeof(struct sockaddr)) == -1)
{
log("SERVER", std::string("Failed to bind() a port (") + std::to_string(port));
return false;
}else{
return true;
}
}
bool Server::startListening(){
//Habilitando o servidor a receber conexoes do cliente
if (listen( socketId, 10 ) == -1)
{
log("SERVER", std::string("Failed to listen() on ") + localIP + std::string("::") + std::to_string(port));
return false;
}else{
return true;
}
}
bool Server::isConnected(){
return connected;
}
void Server::putMessage(std::string msgToSend){
//std::string* bytes = new std::string(msgToSend.c_str());
//sendQueue.push(bytes);
m.lock();
const char* bytesToSend = msgToSend.c_str();
int bytesSent = send(connectionClientId, bytesToSend, strlen(bytesToSend), 0);
if (bytesSent == 0)
{
log("SERVER", "Message sent: \nZero bytes, client finished connection");
return;
}
else if(bytesSent<0)
{
error("SERVER", "ERROR: send returned an error" + std::to_string(errno));
//cerr << "ERROR: send returned an error "<<errno<< endl; // this case is triggered
return;
}else if (bytesSent < strlen(bytesToSend)){
log("SERVER", std::string("Message sent with less characters: \n") + std::string(bytesToSend, bytesSent));
}else if (bytesSent > strlen(bytesToSend)){
log("SERVER", std::string("Message sent with extra characters: \n")
+ std::string(bytesToSend) + std::string("+") + std::to_string(bytesSent-strlen(bytesToSend)));
}else{
log("SERVER", std::string("Message sent: \n") + std::string(bytesToSend));
}
m.unlock();
}
std::string Server::getMessage(){
std::string *msg = messages.pop();
if(msg == NULL){
return "";
}else{
return *msg;
}
}
void Server::startWaiting(){
exitFlag = false;
waitingFlag = true;
std::thread theThread = std::thread(&Server::waitForClientAndReceive, this);
theThread.detach();
}
void Server::stop(){
//std::cout << "Server auto stopping itself\n";
exitFlag = true;
}
bool Server::isWaiting(){
return waitingFlag;
}
void Server::waitForClientAndReceive(){
waitingFlag = true;
//Servidor fica bloqueado esperando uma conexão do cliente
log("SERVER", "Waiting for client...");
connectionClientId = accept( socketId,(struct sockaddr *) &addressClient,&sizeAddressClient );
log("SERVER", std::string("Client connected: ") + std::string(inet_ntoa(addressClient.sin_addr)));
waitingFlag = false;
connected = true;
//Verificando erros
if ( connectionClientId == -1)
{
log("SERVER", "Failed to accept() a client");
return;
}
std::thread recvThread(&Server::receive, this);
//std::thread sendThread(&Server::sendAll, this);
recvThread.detach();
//sendThread.detach();
}
void Server::receive(){
while(!exitFlag){
//receber uma msg do cliente
//std::cout << "Server waiting for a message...\n";
bytesread = recv(connectionClientId,msg,MAXMSG,0);
if (bytesread == -1)
{
log("SERVER", "Message received: \nBroken message | Failed to recv()");
break;
}
else if (bytesread == 0)
{
log("SERVER", "Message received: \nZero bytes, client finished connection");
break;
}
//Inserir o caracter de fim de mensagem
msg[bytesread] = '\0';
log("SERVER", std::string("Message received: \n") + msg);
std::string *s = new std::string(msg);
messages.push(s);
//close(connectionClientId);
}
waitingFlag = false;
connected = false;
close(connectionClientId);
log("SERVER", "Connection to client finished, not receiving anymore");
}
/*void Server::sendAll(){
while(!exitFlag){
std::string* toSend = sendQueue.pop();
if(toSend != NULL){
const char* bytesToSend = toSend->c_str();
int bytesSent = send(connectionClientId, bytesToSend, MAXMSG, 0);
if (bytesSent == 0)
{
log("SERVER", "Message sent: \nZero bytes, client finished connection");
break;
}
else if(bytesSent<0)
{
error("SERVER", "ERROR: send returned an error" + std::to_string(errno));
//cerr << "ERROR: send returned an error "<<errno<< endl; // this case is triggered
//return n;
}else{
log("SERVER", std::string("Message sent: \n") + std::string(bytesToSend, MAXMSG));
}
delete toSend;
delete bytesToSend;
}
}
log("SERVER", "Connection to client finished, not sending anymore");
}*/
<commit_msg>Receiving messages char by char, until '\0' is reached<commit_after>#include "Server.h"
#include "logging.h"
Server::Server(const char* localIP, int port){
this->localIP = std::string(localIP);
this->port = port;
sizeAddressClient = sizeof(struct sockaddr);
msg = new char[MAXMSG+1];
/*
* Configurações do endereço
*/
memset(&address, 0, sizeof(address));
address.sin_family = AF_INET;
address.sin_port = htons(port);
//address.sin_addr.s_addr = INADDR_ANY;
address.sin_addr.s_addr = inet_addr(localIP);
connected = false;
exitFlag = false;
waitingFlag =false;
}
bool Server::start(){
if(getSocket() == false){
return false;
}
if(doBind() == false){
return false;
}
if(startListening() == false){
return false;
}
waitingFlag = false;
return true;
}
bool Server::getSocket(){
/*
* Criando o Socket
*
* PARAM1: AF_INET ou AF_INET6 (IPV4 ou IPV6)
* PARAM2: SOCK_STREAM ou SOCK_DGRAM
* PARAM3: protocolo (IP, UDP, TCP, etc). Valor 0 escolhe automaticamente
*/
socketId = socket(AF_INET, SOCK_STREAM, 0);
//Verificar erros
if (socketId == -1)
{
log("SERVER", "Failed to create socket()");
return false;
}
return true;
}
bool Server::doBind(){
//Conectando o socket a uma porta. Executado apenas no lado servidor
if (bind (socketId, (struct sockaddr *)&address, sizeof(struct sockaddr)) == -1)
{
log("SERVER", std::string("Failed to bind() a port (") + std::to_string(port));
return false;
}else{
return true;
}
}
bool Server::startListening(){
//Habilitando o servidor a receber conexoes do cliente
if (listen( socketId, 10 ) == -1)
{
log("SERVER", std::string("Failed to listen() on ") + localIP + std::string("::") + std::to_string(port));
return false;
}else{
return true;
}
}
bool Server::isConnected(){
return connected;
}
void Server::putMessage(std::string msgToSend){
//std::string* bytes = new std::string(msgToSend.c_str());
//sendQueue.push(bytes);
m.lock();
const char* bytesToSend = msgToSend.c_str();
int bytesSent = send(connectionClientId, bytesToSend, strlen(bytesToSend), 0);
if (bytesSent == 0)
{
log("SERVER", "Message sent: \nZero bytes, client finished connection");
return;
}
else if(bytesSent<0)
{
error("SERVER", "ERROR: send returned an error" + std::to_string(errno));
//cerr << "ERROR: send returned an error "<<errno<< endl; // this case is triggered
return;
}else if (bytesSent < strlen(bytesToSend)){
log("SERVER", std::string("Message sent with less characters: \n") + std::string(bytesToSend, bytesSent));
}else if (bytesSent > strlen(bytesToSend)){
log("SERVER", std::string("Message sent with extra characters: \n")
+ std::string(bytesToSend) + std::string("+") + std::to_string(bytesSent-strlen(bytesToSend)));
}else{
log("SERVER", std::string("Message sent: \n") + std::string(bytesToSend));
}
m.unlock();
}
std::string Server::getMessage(){
std::string *msg = messages.pop();
if(msg == NULL){
return "";
}else{
return *msg;
}
}
void Server::startWaiting(){
exitFlag = false;
waitingFlag = true;
std::thread theThread = std::thread(&Server::waitForClientAndReceive, this);
theThread.detach();
}
void Server::stop(){
//std::cout << "Server auto stopping itself\n";
exitFlag = true;
}
bool Server::isWaiting(){
return waitingFlag;
}
void Server::waitForClientAndReceive(){
waitingFlag = true;
//Servidor fica bloqueado esperando uma conexão do cliente
log("SERVER", "Waiting for client...");
connectionClientId = accept( socketId,(struct sockaddr *) &addressClient,&sizeAddressClient );
log("SERVER", std::string("Client connected: ") + std::string(inet_ntoa(addressClient.sin_addr)));
waitingFlag = false;
connected = true;
//Verificando erros
if ( connectionClientId == -1)
{
log("SERVER", "Failed to accept() a client");
return;
}
std::thread recvThread(&Server::receive, this);
//std::thread sendThread(&Server::sendAll, this);
recvThread.detach();
//sendThread.detach();
}
void Server::receive(){
while(!exitFlag){
//receber uma msg do cliente
//std::cout << "Server waiting for a message...\n";
std::string msgBuilder = "";
char* bytesread;
bool messageBuilt = false;
int nRead = 0;
while(true){
nRead = recv(connectionClientId,bytesread,1,0);
if (nRead == -1)
{
log("SERVER", "Message received: \nBroken message | Failed to recv() (=-1)");
break;
}
else if (nRead == 0)
{
log("SERVER", "Message received: \nZero bytes, client finished connection");
break;
}else{
std::string charStr = std::string(bytesread, nRead);
msgBuilder += charStr;
if(charStr == "\0"){
messageBuilt = true;
break;
}
}
}
if(messageBuilt){
log("SERVER", std::string("Message received: \n") + msg);
std::string *s = new std::string(msg);
messages.push(s);
}else{
exitFlag = true;
}
}
waitingFlag = false;
connected = false;
close(connectionClientId);
log("SERVER", "Connection to client finished, not receiving anymore");
}
/*void Server::sendAll(){
while(!exitFlag){
std::string* toSend = sendQueue.pop();
if(toSend != NULL){
const char* bytesToSend = toSend->c_str();
int bytesSent = send(connectionClientId, bytesToSend, MAXMSG, 0);
if (bytesSent == 0)
{
log("SERVER", "Message sent: \nZero bytes, client finished connection");
break;
}
else if(bytesSent<0)
{
error("SERVER", "ERROR: send returned an error" + std::to_string(errno));
//cerr << "ERROR: send returned an error "<<errno<< endl; // this case is triggered
//return n;
}else{
log("SERVER", std::string("Message sent: \n") + std::string(bytesToSend, MAXMSG));
}
delete toSend;
delete bytesToSend;
}
}
log("SERVER", "Connection to client finished, not sending anymore");
}*/
<|endoftext|>
|
<commit_before>#include <KAI/Core/Detail/Function.h>
#include "MyTestStruct.h"
USING_NAMESPACE_KAI
using namespace std;
bool funCalled[5];
// just making some functions that we will also add to the runtime soon
void Function_0()
{
funCalled[0] = true;
}
void Function_1(int )
{
funCalled[1] = true;
}
String Function_2(int n, int f, String p)
{
funCalled[2] = true;
// KAI_TRACE_3(n, f, p);
return p + "foo";
}
Object Function_3(Object object)
{
funCalled[3] = true;
KAI_TRACE_1(object);
return object["num"];
}
TEST(TestFunctionScripting, Test)
{
try
{
Console console;
console.SetLanguage(Language::Rho);
Object root = console.GetRoot();
Registry ® = console.GetRegistry();
MyStruct::Register(reg);
Pointer<MyStruct> mystruct = reg.New<MyStruct>();
mystruct->num = 345;
mystruct->string = "hello world";
console.GetTree().AddSearchPath(root);//Pathname("/"));
// Process::trace = 10;
root["mystruct"] = mystruct;
AddFunction(root, Function_0, Label("Function0"));
AddFunction(root, Function_1, Label("Function1"));
AddFunction(root, Function_2, Label("Function2"));
AddFunction(root, Function_3, Label("Function3"));
console.Execute("Function0()");
console.Execute("Function1(42)");
console.Execute("Function2(123, 3, \"bar\")");
console.Execute("Function3(mystruct)");
for (int n = 0; n < 2; ++n)
ASSERT_TRUE(funCalled[n]);
Value<Stack> stack = console.GetExecutor()->GetDataStack();
EXPECT_EQ(stack->Size(), 2);
EXPECT_EQ(ConstDeref<int>(stack->Pop()), 345);
EXPECT_EQ(ConstDeref<String>(stack->Pop()), "barfoo");
EXPECT_EQ(stack->Size(), 0);
}
catch (kai::Exception::Base &e)
{
cerr << e.ToString() << endl;
}
catch (std::exception &e)
{
cerr << e.what() << endl;
}
}
<commit_msg>Remove unnecessary try/catch from test now that I found --gtest_use_exceptions.<commit_after>#include <KAI/Core/Detail/Function.h>
#include "MyTestStruct.h"
USING_NAMESPACE_KAI
using namespace std;
bool funCalled[5];
// just making some functions that we will also add to the runtime soon
void Function_0()
{
funCalled[0] = true;
}
void Function_1(int )
{
funCalled[1] = true;
}
String Function_2(int n, int f, String p)
{
funCalled[2] = true;
// KAI_TRACE_3(n, f, p);
return p + "foo";
}
Object Function_3(Object object)
{
funCalled[3] = true;
KAI_TRACE_1(object);
return object["num"];
}
TEST(TestFunctionScripting, Test)
{
Console console;
console.SetLanguage(Language::Rho);
Object root = console.GetRoot();
Registry ® = console.GetRegistry();
MyStruct::Register(reg);
Pointer<MyStruct> mystruct = reg.New<MyStruct>();
mystruct->num = 345;
mystruct->string = "hello world";
console.GetTree().AddSearchPath(root);//Pathname("/"));
// Process::trace = 10;
root["mystruct"] = mystruct;
AddFunction(root, Function_0, Label("Function0"));
AddFunction(root, Function_1, Label("Function1"));
AddFunction(root, Function_2, Label("Function2"));
AddFunction(root, Function_3, Label("Function3"));
console.Execute("Function0()");
console.Execute("Function1(42)");
console.Execute("Function2(123, 3, \"bar\")");
console.Execute("Function3(mystruct)");
for (int n = 0; n < 2; ++n)
ASSERT_TRUE(funCalled[n]);
Value<Stack> stack = console.GetExecutor()->GetDataStack();
EXPECT_EQ(stack->Size(), 2);
EXPECT_EQ(ConstDeref<int>(stack->Pop()), 345);
EXPECT_EQ(ConstDeref<String>(stack->Pop()), "barfoo");
EXPECT_EQ(stack->Size(), 0);
}
<|endoftext|>
|
<commit_before>//
// JdEnvironment.h
// Jigidesign
//
// Created by Steven Massey on 8/24/16.
// Copyright © 2016 Jigidesign. All rights reserved.
//
#ifndef JdEnvironment_h
#define JdEnvironment_h
//#include "JdLibraryManager.h"
#include "JdServer.h"
#include "JdLibraryFactory.h"
#include "IJdBroadcaster.h"
#include "IJdTimers.h"
class JdEnvironment
{
public:
JdEnvironment (bool i_enableTimers = false, bool i_deferSetup = false)
:
m_server (m_libraries),
m_timersEnabled (i_enableTimers)
{
if (not i_deferSetup)
Setup ();
}
virtual ~ JdEnvironment ()
{
Teardown ();
}
void DisableModules (cstr_t i_disabledModules)
{
if (i_disabledModules)
m_disabledModules = Jd::SplitString (i_disabledModules, ",");
}
JdResult Setup (EpigramRef i_configuration = Epigram ())
{
JdResult result;
if (not m_initialized)
{
result = m_server.Setup ();
if (not result)
{
m_libraries.ParseLibraries (& JdLibraryFactory::Get ());
if (i_configuration)
m_server.SetConfiguration (i_configuration);
for (auto moduleName : m_disabledModules)
{
//epilog_(normal, "disable: %s", epistr (moduleName));
m_libraries.DisableModule (moduleName);
}
if (m_timersEnabled)
{
result = jd_timers.Bind (& m_server);
try
{
// jd_broadcaster.Bind (& m_server); // This is the notification delivery module
}
catch (...)
{
}
// auto timers = JdPlatform::Get <IJdPlatform::Notification> ();
// m_timer = timers->ScheduleTimer (10, this, 0);
}
if (not result)
{
auto scheduler = m_server.GetScheduler ();
if (m_timersEnabled)
{
auto driver = jd_timers.Cast <IJdTimerDriver> ();
scheduler->AddTimerThread (driver);
}
// else
// scheduler->AddThreads (1);
scheduler->Start ();
}
m_initialized = true;
}
}
return result;
}
JdResult Teardown ();
void RunMainThread (f64 i_maxDurationInSeconds);
void RunMainLoop (f64 i_durationInSeconds);
operator IJdModuleServer ()
{
return & m_server;
}
JdServer & GetServer () { return m_server; }
protected ://------------------------------------------------------------------------------------------------------
vector <string> m_disabledModules;
JdLibrarian m_libraries;
JdServer m_server;
IJdBroadcaster jd_broadcaster;
IJdTimers jd_timers;
bool m_timersEnabled = false;
bool m_initialized = false;
};
struct JdLinkBasic { static void Setup (); };
struct JdLinkSimple { static void Setup (); };
#endif /* JdEnvironment_h */
<commit_msg>no message<commit_after>//
// JdEnvironment.h
// Jigidesign
//
// Created by Steven Massey on 8/24/16.
// Copyright © 2016 Jigidesign. All rights reserved.
//
#ifndef JdEnvironment_h
#define JdEnvironment_h
//#include "JdLibraryManager.h"
#include "JdServer.h"
#include "JdLibraryFactory.h"
#include "IJdBroadcaster.h"
#include "IJdTimers.h"
class JdEnvironment
{
public:
JdEnvironment (bool i_enableTimers = false, bool i_deferSetup = false)
:
m_server (m_libraries),
m_timersEnabled (i_enableTimers)
{
if (not i_deferSetup)
Setup ();
}
virtual ~ JdEnvironment ()
{
Teardown ();
}
void DisableModules (cstr_t i_disabledModules)
{
if (i_disabledModules)
m_disabledModules = Jd::SplitString (i_disabledModules, ",");
}
JdResult Setup (EpigramRef i_configuration = Epigram ())
{
JdResult result;
if (not m_initialized)
{
result = m_server.Setup ();
if (not result)
{
m_libraries.ParseLibraries (& JdLibraryFactory::Get ());
if (i_configuration)
m_server.SetConfiguration (i_configuration);
for (auto moduleName : m_disabledModules)
{
//epilog_(normal, "disable: %s", epistr (moduleName));
m_libraries.DisableModule (moduleName);
}
if (m_timersEnabled)
{
result = jd_timers.Bind (& m_server);
try
{
// jd_broadcaster.Bind (& m_server); // This is the notification delivery module
}
catch (...)
{
}
// auto timers = JdPlatform::Get <IJdPlatform::Notification> ();
// m_timer = timers->ScheduleTimer (10, this, 0);
}
if (not result)
{
auto scheduler = m_server.GetScheduler ();
if (m_timersEnabled)
{
auto driver = jd_timers.Cast <IJdTimerDriver> ();
scheduler->AddTimerThread (driver);
}
else scheduler->AddThreads (1);
scheduler->Start ();
}
m_initialized = true;
}
}
return result;
}
JdResult Teardown ();
void RunMainThread (f64 i_maxDurationInSeconds);
void RunMainLoop (f64 i_durationInSeconds);
operator IJdModuleServer ()
{
return & m_server;
}
JdServer & GetServer () { return m_server; }
protected ://------------------------------------------------------------------------------------------------------
vector <string> m_disabledModules;
JdLibrarian m_libraries;
JdServer m_server;
IJdBroadcaster jd_broadcaster;
IJdTimers jd_timers;
bool m_timersEnabled = false;
bool m_initialized = false;
};
struct JdLinkBasic { static void Setup (); };
struct JdLinkSimple { static void Setup (); };
#endif /* JdEnvironment_h */
<|endoftext|>
|
<commit_before>/*
* File: Connection.cpp
* Author: Paolo D'Apice
*
* Created on May 24, 2012, 3:43 PM
*/
#include "net/distribute/Connection.hpp"
#include <boost/bind.hpp>
#include <glog/logging.h>
using ba::ip::tcp;
using std::string;
namespace {
/// Connection ID sequence.
unsigned i = 0;
}
// Get connection ID to be printed in logs.
#define ID "(" << id << ") "
NS_IZENELIB_DISTRIBUTE_BEGIN
Connection::Connection(ba::io_service& service, const size_t& size,
const string& dir)
: id(i++), socket(service), bufferSize(size), basedir(dir) {
// TODO: use class FileWriter
buffer = new char[bufferSize];
DLOG(INFO) << ID << "connection instantiated";
}
Connection::~Connection() {
delete[] buffer;
DLOG(INFO) << ID << "connection destroyed";
}
void
Connection::start() {
DLOG(INFO) << ID << "starting ";
// read request header
socket.async_read_some(ba::buffer(buffer, bufferSize),
boost::bind(&Connection::handleReceivedHeader, shared_from_this(),
ba::placeholders::error,
ba::placeholders::bytes_transferred));
}
void
Connection::handleReceivedHeader(const bs::error_code& error, size_t size) {
DLOG(INFO) << ID << "received " << size << " bytes";
if (error) {
LOG(ERROR) << ID << error.message();
return;
}
if (size <= 0) {
LOG(ERROR) << ID << "No data received";
return;
}
// deserialize
msgpack::unpacked unp;
msgpack::unpack(&unp, buffer, size);
request = unp.get().as<Request>();
DLOG(INFO) << ID << "request: " << request;
fileSize = request.getFileSize(); //XXX server?
RequestAck ack(createFile());
// serialize and send
msgpack::sbuffer sbuff;
msgpack::pack(sbuff, ack);
DLOG(INFO) << ID << "sending ack: " << ack;
ba::async_write(socket, ba::buffer(sbuff.data(), sbuff.size()),
boost::bind(&Connection::handleSentHeaderAck, shared_from_this(),
ba::placeholders::error,
ba::placeholders::bytes_transferred));
}
void
Connection::handleSentHeaderAck(const bs::error_code& error, size_t size) {
DLOG(INFO) << ID << "sent " << size << " bytes";
if (error) {
LOG(ERROR) << ID << error.message();
return;
}
if (size <= 0) {
LOG(ERROR) << ID << "No data sent";
return;
}
bool flag = true;
size_t receivedSize = receiveFileData();
if (receivedSize != fileSize) {
LOG(ERROR) << ID << "Received " << receivedSize << "/" << fileSize << " bytes";
flag = false;
}
RequestAck ack(flag, receivedSize);
// serialize and send
msgpack::sbuffer sbuff;
msgpack::pack(sbuff, ack);
DLOG(INFO) << ID << "sending data ack: " << ack;
ba::async_write(socket, ba::buffer(sbuff.data(), sbuff.size()),
boost::bind(&Connection::handleSentFileDataAck, shared_from_this(),
ba::placeholders::error,
ba::placeholders::bytes_transferred));
}
void
Connection::handleSentFileDataAck(const bs::error_code& error, size_t size) {
DLOG(INFO) << ID << "sent " << size << " bytes";
if (error) {
LOG(ERROR) << ID << error.message();
return;
}
if (size <= 0) {
LOG(ERROR) << ID << "No data sent";
return;
}
}
bool
Connection::createFile() {
// actual file path
bfs::path outputpath;
string destination(request.getDestination());
if (not destination.empty()) {
outputpath = basedir/bfs::path(destination)/bfs::path(request.getFileName());
} else {
outputpath = basedir/bfs::path(request.getFileName());
}
DLOG(INFO) << ID << "outputpath: " << outputpath;
if (not bfs::exists(outputpath.parent_path())) {
DLOG(INFO) << ID << "creating path: " << outputpath.parent_path();
bfs::create_directories(outputpath.parent_path());
}
output.open(outputpath, ofstream::out);
if (not output.good()) {
LOG(ERROR) << ID << "Cannot open file: " << outputpath;
return false;
}
DLOG(INFO) << ID << "File correctly opened";
return true;
}
size_t
Connection::receiveFileData() {
LOG(INFO) << ID << "receiving file data ...";
size_t receivedSize = 0;
size_t readSize = 0;
do {
boost::system::error_code error;
readSize = socket.read_some(ba::buffer(buffer, bufferSize), error);
if (error) {
LOG(ERROR) << ID << error.message();
return receivedSize;
}
if (readSize > 0) {
output.write(buffer, readSize);
receivedSize += readSize;
}
} while (output.tellp() != (std::streamsize) fileSize);
if (output.is_open()) {
output.close();
DLOG(INFO) << ID << "file output closed";
}
DLOG(INFO) << ID << "received " << receivedSize << " bytes";
return receivedSize;
}
NS_IZENELIB_DISTRIBUTE_END
<commit_msg>fix data transfer in distribute<commit_after>/*
* File: Connection.cpp
* Author: Paolo D'Apice
*
* Created on May 24, 2012, 3:43 PM
*/
#include "net/distribute/Connection.hpp"
#include <boost/bind.hpp>
#include <glog/logging.h>
using ba::ip::tcp;
using std::string;
namespace {
/// Connection ID sequence.
unsigned i = 0;
}
// Get connection ID to be printed in logs.
#define ID "(" << id << ") "
NS_IZENELIB_DISTRIBUTE_BEGIN
Connection::Connection(ba::io_service& service, const size_t& size,
const string& dir)
: id(i++), socket(service), bufferSize(size), basedir(dir) {
// TODO: use class FileWriter
buffer = new char[bufferSize];
DLOG(INFO) << ID << "connection instantiated";
}
Connection::~Connection() {
delete[] buffer;
DLOG(INFO) << ID << "connection destroyed";
}
void
Connection::start() {
DLOG(INFO) << ID << "starting ";
// read request header
socket.async_read_some(ba::buffer(buffer, bufferSize),
boost::bind(&Connection::handleReceivedHeader, shared_from_this(),
ba::placeholders::error,
ba::placeholders::bytes_transferred));
}
void
Connection::handleReceivedHeader(const bs::error_code& error, size_t size) {
DLOG(INFO) << ID << "received " << size << " bytes";
if (error) {
LOG(ERROR) << ID << error.message();
return;
}
if (size <= 0) {
LOG(ERROR) << ID << "No data received";
return;
}
// deserialize
msgpack::unpacked unp;
msgpack::unpack(&unp, buffer, size);
request = unp.get().as<Request>();
DLOG(INFO) << ID << "request: " << request;
fileSize = request.getFileSize(); //XXX server?
RequestAck ack(createFile());
// serialize and send
msgpack::sbuffer sbuff;
msgpack::pack(sbuff, ack);
DLOG(INFO) << ID << "sending ack: " << ack;
ba::async_write(socket, ba::buffer(sbuff.data(), sbuff.size()),
boost::bind(&Connection::handleSentHeaderAck, shared_from_this(),
ba::placeholders::error,
ba::placeholders::bytes_transferred));
}
void
Connection::handleSentHeaderAck(const bs::error_code& error, size_t size) {
DLOG(INFO) << ID << "sent " << size << " bytes";
if (error) {
LOG(ERROR) << ID << error.message();
return;
}
if (size <= 0) {
LOG(ERROR) << ID << "No data sent";
return;
}
bool flag = true;
size_t receivedSize = receiveFileData();
if (receivedSize != fileSize) {
LOG(ERROR) << ID << "Received " << receivedSize << "/" << fileSize << " bytes";
flag = false;
}
RequestAck ack(flag, receivedSize);
// serialize and send
msgpack::sbuffer sbuff;
msgpack::pack(sbuff, ack);
DLOG(INFO) << ID << "sending data ack: " << ack;
ba::async_write(socket, ba::buffer(sbuff.data(), sbuff.size()),
boost::bind(&Connection::handleSentFileDataAck, shared_from_this(),
ba::placeholders::error,
ba::placeholders::bytes_transferred));
}
void
Connection::handleSentFileDataAck(const bs::error_code& error, size_t size) {
DLOG(INFO) << ID << "sent " << size << " bytes";
if (error) {
LOG(ERROR) << ID << error.message();
return;
}
if (size <= 0) {
LOG(ERROR) << ID << "No data sent";
return;
}
}
bool
Connection::createFile() {
// actual file path
bfs::path outputpath;
string destination(request.getDestination());
if (not destination.empty()) {
outputpath = basedir/bfs::path(destination)/bfs::path(request.getFileName()).filename();
} else {
outputpath = basedir/bfs::path(request.getFileName());
}
DLOG(INFO) << ID << "outputpath: " << outputpath;
if (not bfs::exists(outputpath.parent_path())) {
DLOG(INFO) << ID << "creating path: " << outputpath.parent_path();
bfs::create_directories(outputpath.parent_path());
}
output.open(outputpath, ofstream::out);
if (not output.good()) {
LOG(ERROR) << ID << "Cannot open file: " << outputpath;
return false;
}
DLOG(INFO) << ID << "File correctly opened";
return true;
}
size_t
Connection::receiveFileData() {
LOG(INFO) << ID << "receiving file data ...";
size_t receivedSize = 0;
size_t readSize = 0;
do {
boost::system::error_code error;
readSize = socket.read_some(ba::buffer(buffer, bufferSize), error);
if (error) {
LOG(ERROR) << ID << error.message();
return receivedSize;
}
if (readSize > 0) {
output.write(buffer, readSize);
receivedSize += readSize;
}
} while (output.tellp() != (std::streamsize) fileSize);
if (output.is_open()) {
output.close();
DLOG(INFO) << ID << "file output closed";
}
DLOG(INFO) << ID << "received " << receivedSize << " bytes";
return receivedSize;
}
NS_IZENELIB_DISTRIBUTE_END
<|endoftext|>
|
<commit_before>/*
* File: Connection.cpp
* Author: Paolo D'Apice
*
* Created on May 24, 2012, 3:43 PM
*/
#include "net/distribute/Connection.hpp"
#include <boost/bind.hpp>
#include <glog/logging.h>
using ba::ip::tcp;
using std::string;
namespace {
/// Connection ID sequence.
unsigned i = 0;
}
// Get connection ID to be printed in logs.
#define ID "(" << id << ") "
NS_IZENELIB_DISTRIBUTE_BEGIN
Connection::Connection(ba::io_service& service, const size_t& size,
const string& dir)
: id(i++), socket(service), bufferSize(size), basedir(dir) {
// TODO: use class FileWriter
buffer = new char[bufferSize];
DLOG(INFO) << ID << "connection instantiated";
}
Connection::~Connection() {
delete[] buffer;
DLOG(INFO) << ID << "connection destroyed";
}
void
Connection::start() {
DLOG(INFO) << ID << "starting ";
// read request header
socket.async_read_some(ba::buffer(buffer, bufferSize),
boost::bind(&Connection::handleReceivedHeader, shared_from_this(),
ba::placeholders::error,
ba::placeholders::bytes_transferred));
}
void
Connection::handleReceivedHeader(const bs::error_code& error, size_t size) {
DLOG(INFO) << ID << "received " << size << " bytes";
if (error) {
LOG(ERROR) << ID << error.message();
return;
}
if (size <= 0) {
LOG(ERROR) << ID << "No data received";
return;
}
// deserialize
msgpack::unpacked unp;
msgpack::unpack(&unp, buffer, size);
request = unp.get().as<Request>();
DLOG(INFO) << ID << "request: " << request;
fileSize = request.getFileSize(); //XXX server?
RequestAck ack(createFile());
// serialize and send
msgpack::sbuffer sbuff;
msgpack::pack(sbuff, ack);
DLOG(INFO) << ID << "sending ack: " << ack;
ba::async_write(socket, ba::buffer(sbuff.data(), sbuff.size()),
boost::bind(&Connection::handleSentHeaderAck, shared_from_this(),
ba::placeholders::error,
ba::placeholders::bytes_transferred));
}
void
Connection::handleSentHeaderAck(const bs::error_code& error, size_t size) {
DLOG(INFO) << ID << "sent " << size << " bytes";
if (error) {
LOG(ERROR) << ID << error.message();
return;
}
if (size <= 0) {
LOG(ERROR) << ID << "No data sent";
return;
}
bool flag = true;
size_t receivedSize = receiveFileData();
if (receivedSize != fileSize) {
LOG(ERROR) << ID << "Received " << receivedSize << "/" << fileSize << " bytes";
flag = false;
}
RequestAck ack(flag, receivedSize);
// serialize and send
msgpack::sbuffer sbuff;
msgpack::pack(sbuff, ack);
DLOG(INFO) << ID << "sending data ack: " << ack;
ba::async_write(socket, ba::buffer(sbuff.data(), sbuff.size()),
boost::bind(&Connection::handleSentFileDataAck, shared_from_this(),
ba::placeholders::error,
ba::placeholders::bytes_transferred));
}
void
Connection::handleSentFileDataAck(const bs::error_code& error, size_t size) {
DLOG(INFO) << ID << "sent " << size << " bytes";
if (error) {
LOG(ERROR) << ID << error.message();
return;
}
if (size <= 0) {
LOG(ERROR) << ID << "No data sent";
return;
}
}
bool
Connection::createFile() {
// actual file path
bfs::path outputpath;
string destination(request.getDestination());
if (not destination.empty()) {
outputpath = bfs::path(destination)/bfs::path(request.getFileName()).filename();
} else {
outputpath = basedir/bfs::path(request.getFileName());
}
DLOG(INFO) << ID << "outputpath: " << outputpath;
if (not bfs::exists(outputpath.parent_path())) {
DLOG(INFO) << ID << "creating path: " << outputpath.parent_path();
bfs::create_directories(outputpath.parent_path());
}
output.open(outputpath, ofstream::out);
if (not output.good()) {
LOG(ERROR) << ID << "Cannot open file: " << outputpath;
return false;
}
DLOG(INFO) << ID << "File correctly opened";
return true;
}
size_t
Connection::receiveFileData() {
LOG(INFO) << ID << "receiving file data ...";
size_t receivedSize = 0;
size_t readSize = 0;
do {
boost::system::error_code error;
readSize = socket.read_some(ba::buffer(buffer, bufferSize), error);
if (error) {
LOG(ERROR) << ID << error.message();
return receivedSize;
}
if (readSize > 0) {
output.write(buffer, readSize);
receivedSize += readSize;
}
} while (output.tellp() != (std::streamsize) fileSize);
if (output.is_open()) {
output.close();
DLOG(INFO) << ID << "file output closed";
}
DLOG(INFO) << ID << "received " << receivedSize << " bytes";
return receivedSize;
}
NS_IZENELIB_DISTRIBUTE_END
<commit_msg>fix for data transfer<commit_after>/*
* File: Connection.cpp
* Author: Paolo D'Apice
*
* Created on May 24, 2012, 3:43 PM
*/
#include "net/distribute/Connection.hpp"
#include <boost/bind.hpp>
#include <glog/logging.h>
using ba::ip::tcp;
using std::string;
namespace {
/// Connection ID sequence.
unsigned i = 0;
}
// Get connection ID to be printed in logs.
#define ID "(" << id << ") "
NS_IZENELIB_DISTRIBUTE_BEGIN
Connection::Connection(ba::io_service& service, const size_t& size,
const string& dir)
: id(i++), socket(service), bufferSize(size), basedir(dir) {
// TODO: use class FileWriter
buffer = new char[bufferSize];
DLOG(INFO) << ID << "connection instantiated";
}
Connection::~Connection() {
delete[] buffer;
DLOG(INFO) << ID << "connection destroyed";
}
void
Connection::start() {
DLOG(INFO) << ID << "starting ";
// read request header
socket.async_read_some(ba::buffer(buffer, bufferSize),
boost::bind(&Connection::handleReceivedHeader, shared_from_this(),
ba::placeholders::error,
ba::placeholders::bytes_transferred));
}
void
Connection::handleReceivedHeader(const bs::error_code& error, size_t size) {
DLOG(INFO) << ID << "received " << size << " bytes";
if (error) {
LOG(ERROR) << ID << error.message();
return;
}
if (size <= 0) {
LOG(ERROR) << ID << "No data received";
return;
}
// deserialize
msgpack::unpacked unp;
msgpack::unpack(&unp, buffer, size);
request = unp.get().as<Request>();
DLOG(INFO) << ID << "request: " << request;
fileSize = request.getFileSize(); //XXX server?
RequestAck ack(createFile());
// serialize and send
msgpack::sbuffer sbuff;
msgpack::pack(sbuff, ack);
DLOG(INFO) << ID << "sending ack: " << ack;
ba::async_write(socket, ba::buffer(sbuff.data(), sbuff.size()),
boost::bind(&Connection::handleSentHeaderAck, shared_from_this(),
ba::placeholders::error,
ba::placeholders::bytes_transferred));
}
void
Connection::handleSentHeaderAck(const bs::error_code& error, size_t size) {
DLOG(INFO) << ID << "sent " << size << " bytes";
if (error) {
LOG(ERROR) << ID << error.message();
return;
}
if (size <= 0) {
LOG(ERROR) << ID << "No data sent";
return;
}
bool flag = true;
size_t receivedSize = receiveFileData();
if (receivedSize != fileSize) {
LOG(ERROR) << ID << "Received " << receivedSize << "/" << fileSize << " bytes";
flag = false;
}
RequestAck ack(flag, receivedSize);
// serialize and send
msgpack::sbuffer sbuff;
msgpack::pack(sbuff, ack);
DLOG(INFO) << ID << "sending data ack: " << ack;
ba::async_write(socket, ba::buffer(sbuff.data(), sbuff.size()),
boost::bind(&Connection::handleSentFileDataAck, shared_from_this(),
ba::placeholders::error,
ba::placeholders::bytes_transferred));
}
void
Connection::handleSentFileDataAck(const bs::error_code& error, size_t size) {
DLOG(INFO) << ID << "sent " << size << " bytes";
if (error) {
LOG(ERROR) << ID << error.message();
return;
}
if (size <= 0) {
LOG(ERROR) << ID << "No data sent";
return;
}
}
bool
Connection::createFile() {
// actual file path
bfs::path outputpath;
string destination(request.getDestination());
if (not destination.empty()) {
if (request.getFileName() == bfs::path(destination).filename().string())
{
outputpath = bfs::path(destination);
}
else
{
outputpath = basedir/bfs::path(destination)/bfs::path(request.getFileName()).filename();
}
} else {
outputpath = basedir/bfs::path(request.getFileName());
}
DLOG(INFO) << ID << "outputpath: " << outputpath;
if (not bfs::exists(outputpath.parent_path())) {
DLOG(INFO) << ID << "creating path: " << outputpath.parent_path();
bfs::create_directories(outputpath.parent_path());
}
output.open(outputpath, ofstream::out);
if (not output.good()) {
LOG(ERROR) << ID << "Cannot open file: " << outputpath;
return false;
}
DLOG(INFO) << ID << "File correctly opened";
return true;
}
size_t
Connection::receiveFileData() {
LOG(INFO) << ID << "receiving file data ...";
size_t receivedSize = 0;
size_t readSize = 0;
do {
boost::system::error_code error;
readSize = socket.read_some(ba::buffer(buffer, bufferSize), error);
if (error) {
LOG(ERROR) << ID << error.message();
return receivedSize;
}
if (readSize > 0) {
output.write(buffer, readSize);
receivedSize += readSize;
}
} while (output.tellp() != (std::streamsize) fileSize);
if (output.is_open()) {
output.close();
DLOG(INFO) << ID << "file output closed";
}
DLOG(INFO) << ID << "received " << receivedSize << " bytes";
return receivedSize;
}
NS_IZENELIB_DISTRIBUTE_END
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: DICOM for VTK
Copyright (c) 2012-2017 David Gobbi
All rights reserved.
See Copyright.txt or http://dgobbi.github.io/bsd3.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 notice for more information.
=========================================================================*/
#include "vtkDICOMTagPath.h"
//----------------------------------------------------------------------------
ostream& operator<<(ostream& o, const vtkDICOMTagPath& a)
{
o << "[";
o << a.GetHead();
if (a.HasTail())
{
vtkDICOMTagPath b = a;
while (b.HasTail())
{
o << ",";
o << b.GetIndex();
o << ",";
o << b.GetHead();
b = b.GetTail();
}
}
o << "]";
return o;
}
//----------------------------------------------------------------------------
bool vtkDICOMTagPath::operator==(const vtkDICOMTagPath& b) const
{
return (this->Head == b.Head &&
this->Index == b.Index &&
this->Tail == b.Tail &&
this->Index2 == b.Index2 &&
this->Tail2 == b.Tail2);
}
//----------------------------------------------------------------------------
bool vtkDICOMTagPath::operator!=(const vtkDICOMTagPath& b) const
{
return !(*this == b);
}
//----------------------------------------------------------------------------
bool vtkDICOMTagPath::operator<(const vtkDICOMTagPath& b) const
{
return (this->Head < b.Head ||
(this->Head == b.Head &&
(this->Index < b.Index ||
(this->Index == b.Index &&
(this->Tail < b.Tail ||
(this->Tail == b.Tail &&
(this->Index2 < b.Index2 ||
(this->Index2 == b.Index2 &&
(this->Tail2 < b.Tail2)))))))));
}
//----------------------------------------------------------------------------
bool vtkDICOMTagPath::operator>(const vtkDICOMTagPath& b) const
{
return !(*this < b || *this == b);
}
//----------------------------------------------------------------------------
bool vtkDICOMTagPath::operator<=(const vtkDICOMTagPath& b) const
{
return (*this < b || *this == b);
}
//----------------------------------------------------------------------------
bool vtkDICOMTagPath::operator>=(const vtkDICOMTagPath& b) const
{
return !(*this < b);
}
<commit_msg>Fix stream operator for tag paths.<commit_after>/*=========================================================================
Program: DICOM for VTK
Copyright (c) 2012-2017 David Gobbi
All rights reserved.
See Copyright.txt or http://dgobbi.github.io/bsd3.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 notice for more information.
=========================================================================*/
#include "vtkDICOMTagPath.h"
//----------------------------------------------------------------------------
ostream& operator<<(ostream& o, const vtkDICOMTagPath& a)
{
o << "[";
o << a.GetHead();
if (a.HasTail())
{
unsigned int i = a.GetIndex();
vtkDICOMTagPath b = a.GetTail();
for (;;)
{
o << ",";
o << i;
o << ",";
o << b.GetHead();
if (!b.HasTail())
{
break;
}
i = b.GetIndex();
b = b.GetTail();
}
}
o << "]";
return o;
}
//----------------------------------------------------------------------------
bool vtkDICOMTagPath::operator==(const vtkDICOMTagPath& b) const
{
return (this->Head == b.Head &&
this->Index == b.Index &&
this->Tail == b.Tail &&
this->Index2 == b.Index2 &&
this->Tail2 == b.Tail2);
}
//----------------------------------------------------------------------------
bool vtkDICOMTagPath::operator!=(const vtkDICOMTagPath& b) const
{
return !(*this == b);
}
//----------------------------------------------------------------------------
bool vtkDICOMTagPath::operator<(const vtkDICOMTagPath& b) const
{
return (this->Head < b.Head ||
(this->Head == b.Head &&
(this->Index < b.Index ||
(this->Index == b.Index &&
(this->Tail < b.Tail ||
(this->Tail == b.Tail &&
(this->Index2 < b.Index2 ||
(this->Index2 == b.Index2 &&
(this->Tail2 < b.Tail2)))))))));
}
//----------------------------------------------------------------------------
bool vtkDICOMTagPath::operator>(const vtkDICOMTagPath& b) const
{
return !(*this < b || *this == b);
}
//----------------------------------------------------------------------------
bool vtkDICOMTagPath::operator<=(const vtkDICOMTagPath& b) const
{
return (*this < b || *this == b);
}
//----------------------------------------------------------------------------
bool vtkDICOMTagPath::operator>=(const vtkDICOMTagPath& b) const
{
return !(*this < b);
}
<|endoftext|>
|
<commit_before>/***************************************************************************
* Copyright (c) Juergen Riegel (juergen.riegel@web.de) 2014 *
* Copyright (c) Alexander Golubev (Fat-Zer) <fatzer2@gmail.com> 2015 *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* 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., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
#ifndef _PreComp_
#endif
#include <App/Document.h>
#include "GeoFeatureGroupExtension.h"
#include "OriginFeature.h"
#include "Origin.h"
#include "OriginGroupExtension.h"
#include <Base/Console.h>
//#include "GeoFeatureGroupPy.h"
//#include "FeaturePythonPyImp.h"
using namespace App;
EXTENSION_PROPERTY_SOURCE(App::GeoFeatureGroupExtension, App::GroupExtension)
//===========================================================================
// Feature
//===========================================================================
GeoFeatureGroupExtension::GeoFeatureGroupExtension(void)
{
initExtensionType(GeoFeatureGroupExtension::getExtensionClassTypeId());
Group.setScope(LinkScope::Child);
}
GeoFeatureGroupExtension::~GeoFeatureGroupExtension(void)
{
}
void GeoFeatureGroupExtension::initExtension(ExtensionContainer* obj) {
if(!obj->isDerivedFrom(App::GeoFeature::getClassTypeId()))
throw Base::RuntimeError("GeoFeatureGroupExtension can only be applied to GeoFeatures");
App::GroupExtension::initExtension(obj);
}
PropertyPlacement& GeoFeatureGroupExtension::placement() {
if(!getExtendedContainer())
throw Base::RuntimeError("GeoFeatureGroupExtension was not applied to GeoFeature");
return static_cast<App::GeoFeature*>(getExtendedContainer())->Placement;
}
void GeoFeatureGroupExtension::transformPlacement(const Base::Placement &transform)
{
// NOTE: Keep in sync with APP::GeoFeature
Base::Placement plm = this->placement().getValue();
plm = transform * plm;
this->placement().setValue(plm);
}
DocumentObject* GeoFeatureGroupExtension::getGroupOfObject(const DocumentObject* obj)
{
if(!obj)
return nullptr;
//we will find origins, but not origin features
if(obj->isDerivedFrom(App::OriginFeature::getClassTypeId()))
return OriginGroupExtension::getGroupOfObject(obj);
//compared to GroupExtension we do return here all GeoFeatureGroups including all extensions derived from it
//like OriginGroup. That is needed as we use this function to get all local coordinate systems. Also there
//is no reason to distinguish between GeoFeatuerGroups, there is only between group/geofeaturegroup
auto list = obj->getInList();
for (auto inObj : list) {
//There is a chance that a derived geofeaturegroup links with a local link and hence is not
//the parent group even though it links to the object. We use hasObject as one and only truth
//if it has the object within the group
if(inObj->hasExtension(App::GeoFeatureGroupExtension::getExtensionClassTypeId()) &&
inObj->getExtensionByType<GeoFeatureGroupExtension>()->hasObject(obj)) {
return inObj;
}
}
return nullptr;
}
Base::Placement GeoFeatureGroupExtension::globalGroupPlacement() {
return recursiveGroupPlacement(this);
}
Base::Placement GeoFeatureGroupExtension::recursiveGroupPlacement(GeoFeatureGroupExtension* group) {
auto inList = group->getExtendedObject()->getInList();
for(auto* link : inList) {
if(link->hasExtension(App::GeoFeatureGroupExtension::getExtensionClassTypeId()))
return recursiveGroupPlacement(link->getExtensionByType<GeoFeatureGroupExtension>()) * group->placement().getValue();
}
return group->placement().getValue();
}
std::vector<DocumentObject*> GeoFeatureGroupExtension::addObjects(std::vector<App::DocumentObject*> objects) {
std::vector<DocumentObject*> grp = Group.getValues();
std::vector<DocumentObject*> ret;
for(auto object : objects) {
if(!allowObject(object))
continue;
//cross CoordinateSystem links are not allowed, so we need to move the whole link group
std::vector<App::DocumentObject*> links = getCSRelevantLinks(object);
links.push_back(object);
for( auto obj : links) {
//only one geofeaturegroup per object.
auto *group = App::GeoFeatureGroupExtension::getGroupOfObject(obj);
if(group && group != getExtendedObject())
group->getExtensionByType<App::GroupExtension>()->removeObject(obj);
if (!hasObject(obj)) {
grp.push_back(obj);
ret.push_back(obj);
}
}
}
Group.setValues(grp);
return ret;
}
std::vector<DocumentObject*> GeoFeatureGroupExtension::removeObjects(std::vector<App::DocumentObject*> objects) {
std::vector<DocumentObject*> removed;
std::vector<DocumentObject*> grp = Group.getValues();
for(auto object : objects) {
//cross CoordinateSystem links are not allowed, so we need to remove the whole link group
std::vector< DocumentObject* > links = getCSRelevantLinks(object);
links.push_back(object);
//remove all links out of group
for(auto link : links) {
auto end = std::remove(grp.begin(), grp.end(), link);
if(end != grp.end()) {
grp.erase(end, grp.end());
removed.push_back(link);
}
}
}
if(!removed.empty())
Group.setValues(grp);
return removed;
}
void GeoFeatureGroupExtension::extensionOnChanged(const Property* p) {
//objects are only allowed in a single GeoFeatureGroup
if((strcmp(p->getName(), "Group")==0)) {
bool error = false;
auto corrected = Group.getValues();
for(auto obj : Group.getValues()) {
//we have already set the obj into the group, so in a case of multiple groups getGroupOfObject
//would return anyone of it and hence it is possible that we miss an error. We need a custom check
auto list = obj->getInList();
for (auto in : list) {
if(in->hasExtension(App::GeoFeatureGroupExtension::getExtensionClassTypeId()) &&
in != getExtendedObject()) {
error = true;
corrected.erase(std::remove(corrected.begin(), corrected.end(), obj), corrected.end());
}
}
}
//if an error was found we need to correct the values and inform the user
if(error) {
Group.setValues(corrected);
throw Base::Exception("Object can only be in a single GeoFeatureGroup");
}
}
App::GroupExtension::extensionOnChanged(p);
}
std::vector< DocumentObject* > GeoFeatureGroupExtension::getScopedObjectsFromLinks(const DocumentObject* obj, LinkScope scope) {
if(!obj)
return std::vector< DocumentObject* >();
//we get all linked objects. We can't use outList() as this includes the links from expressions
std::vector< App::DocumentObject* > result;
std::vector<App::Property*> list;
obj->getPropertyList(list);
for(App::Property* prop : list) {
auto vec = getScopedObjectsFromLink(prop, scope);
result.insert(result.end(), vec.begin(), vec.end());
}
//clear all null objects and duplicates
std::sort(result.begin(), result.end());
result.erase(std::unique(result.begin(), result.end()), result.end());
return result;
}
std::vector< DocumentObject* > GeoFeatureGroupExtension::getScopedObjectsFromLink(App::Property* prop, LinkScope scope) {
if(!prop)
return std::vector< DocumentObject* >();
std::vector< App::DocumentObject* > result;
if(prop->getTypeId().isDerivedFrom(App::PropertyLink::getClassTypeId()) &&
static_cast<App::PropertyLink*>(prop)->getScope() == scope) {
result.push_back(static_cast<App::PropertyLink*>(prop)->getValue());
}
if(prop->getTypeId().isDerivedFrom(App::PropertyLinkList::getClassTypeId()) &&
static_cast<App::PropertyLinkList*>(prop)->getScope() == scope) {
auto vec = static_cast<App::PropertyLinkList*>(prop)->getValues();
result.insert(result.end(), vec.begin(), vec.end());
}
if(prop->getTypeId().isDerivedFrom(App::PropertyLinkSub::getClassTypeId()) &&
static_cast<App::PropertyLinkSub*>(prop)->getScope() == scope) {
result.push_back(static_cast<App::PropertyLinkSub*>(prop)->getValue());
}
if(prop->getTypeId().isDerivedFrom(App::PropertyLinkSubList::getClassTypeId()) &&
static_cast<App::PropertyLinkSubList*>(prop)->getScope() == scope) {
auto vec = static_cast<App::PropertyLinkSubList*>(prop)->getValues();
result.insert(result.end(), vec.begin(), vec.end());
}
//it is important to remove all nullptrs
result.erase(std::remove(result.begin(), result.end(), nullptr), result.end());
return result;
}
void GeoFeatureGroupExtension::getCSOutList(const App::DocumentObject* obj,
std::vector< DocumentObject* >& vec) {
if(!obj)
return;
//we get all relevant linked objects. We can't use outList() as this includes the links from expressions,
//also we only want links with scope Local
auto result = getScopedObjectsFromLinks(obj, LinkScope::Local);
//we remove all links to origin features and origins, they belong to a CS too and can't be moved
result.erase(std::remove_if(result.begin(), result.end(), [](App::DocumentObject* obj)->bool {
return (obj->isDerivedFrom(App::OriginFeature::getClassTypeId()) ||
obj->isDerivedFrom(App::Origin::getClassTypeId()));
}), result.end());
vec.insert(vec.end(), result.begin(), result.end());
//post process the vector
std::sort(vec.begin(), vec.end());
vec.erase(std::unique(vec.begin(), vec.end()), vec.end());
}
void GeoFeatureGroupExtension::getCSInList(const DocumentObject* obj,
std::vector< DocumentObject* >& vec) {
if(!obj)
return;
//search the inlist for objects that have non-expression links to us
for(App::DocumentObject* parent : obj->getInList()) {
//not interested in other groups (and here we mean all groups, normal ones and geofeaturegroup)
if(parent->hasExtension(App::GroupExtension::getExtensionClassTypeId()))
continue;
//check if the link is real Local scope one or if it is a expression one (could also be both, so it is not
//enough to check the expressions)
auto res = getScopedObjectsFromLinks(parent, LinkScope::Local);
if(std::find(res.begin(), res.end(), obj) != res.end())
vec.push_back(parent);
}
//clear all duplicates
std::sort(vec.begin(), vec.end());
vec.erase(std::unique(vec.begin(), vec.end()), vec.end());
}
std::vector< DocumentObject* > GeoFeatureGroupExtension::getCSRelevantLinks(const DocumentObject* obj) {
if(!obj)
return std::vector< DocumentObject* >();
//get all out links
std::vector<DocumentObject*> vec;
recursiveCSRelevantLinks(obj, vec);
//post process the list after we added many things
std::sort(vec.begin(), vec.end());
vec.erase(std::unique(vec.begin(), vec.end()), vec.end());
vec.erase(std::remove(vec.begin(), vec.end(), obj), vec.end());
return vec;
}
void GeoFeatureGroupExtension::recursiveCSRelevantLinks(const DocumentObject* obj,
std::vector< DocumentObject* >& vec) {
if(!obj)
return;
std::vector< DocumentObject* > links;
getCSOutList(obj, links);
getCSInList(obj, links);
//go on traversing the graph in all directions!
for(auto o : links) {
if(!o || o == obj || std::find(vec.begin(), vec.end(), o) != vec.end())
continue;
vec.push_back(o);
recursiveCSRelevantLinks(o, vec);
}
}
bool GeoFeatureGroupExtension::areLinksValid(const DocumentObject* obj) {
if(!obj)
return true;
//no cross CS link for local links.
//Base::Console().Message("Check object links: %s\n", obj->getNameInDocument());
std::vector<App::Property*> list;
obj->getPropertyList(list);
for(App::Property* prop : list) {
if(!isLinkValid(prop)) {
//Base::Console().Message("Invalid link: %s\n", prop->getName());
return false;
}
}
return true;
}
bool GeoFeatureGroupExtension::isLinkValid(App::Property* prop) {
if(!prop)
return true;
//get the object that holds the property
if(!prop->getContainer()->isDerivedFrom(App::DocumentObject::getClassTypeId()))
return true; //this link comes not from a document object, scopes are meaningless
auto obj = static_cast<App::DocumentObject*>(prop->getContainer());
//no cross CS link for local links.
auto result = getScopedObjectsFromLink(prop, LinkScope::Local);
auto group = getGroupOfObject(obj);
for(auto link : result) {
if(getGroupOfObject(link) != group)
return false;
}
//for links with scope SubGroup we need to check if all features are part of subgroups
if(obj->hasExtension(App::GeoFeatureGroupExtension::getExtensionClassTypeId())) {
result = getScopedObjectsFromLink(prop, LinkScope::Child);
auto groupExt = obj->getExtensionByType<App::GeoFeatureGroupExtension>();
for(auto link : result) {
if(!groupExt->hasObject(link, true))
return false;
}
}
return true;
}
void GeoFeatureGroupExtension::getInvalidLinkObjects(const DocumentObject* obj, std::vector< DocumentObject* >& vec) {
if(!obj)
return;
//no cross CS link for local links.
auto result = getScopedObjectsFromLinks(obj, LinkScope::Local);
auto group = obj->hasExtension(App::GeoFeatureGroupExtension::getExtensionClassTypeId()) ? obj : getGroupOfObject(obj);
for(auto link : result) {
if(getGroupOfObject(link) != group)
vec.push_back(link);
}
//for links with scope SubGroup we need to check if all features are part of subgroups
if(group) {
result = getScopedObjectsFromLinks(obj, LinkScope::Child);
auto groupExt = group->getExtensionByType<App::GeoFeatureGroupExtension>();
for(auto link : result) {
if(!groupExt->hasObject(link, true))
vec.push_back(link);
}
}
}
// Python feature ---------------------------------------------------------
namespace App {
EXTENSION_PROPERTY_SOURCE_TEMPLATE(App::GeoFeatureGroupExtensionPython, App::GeoFeatureGroupExtension)
// explicit template instantiation
template class AppExport ExtensionPythonT<GroupExtensionPythonT<GeoFeatureGroupExtension>>;
}
<commit_msg>Fix wrong detection of multiple GeoFeatureGroups<commit_after>/***************************************************************************
* Copyright (c) Juergen Riegel (juergen.riegel@web.de) 2014 *
* Copyright (c) Alexander Golubev (Fat-Zer) <fatzer2@gmail.com> 2015 *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* 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., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
#ifndef _PreComp_
#endif
#include <App/Document.h>
#include "GeoFeatureGroupExtension.h"
#include "OriginFeature.h"
#include "Origin.h"
#include "OriginGroupExtension.h"
#include <Base/Console.h>
//#include "GeoFeatureGroupPy.h"
//#include "FeaturePythonPyImp.h"
using namespace App;
EXTENSION_PROPERTY_SOURCE(App::GeoFeatureGroupExtension, App::GroupExtension)
//===========================================================================
// Feature
//===========================================================================
GeoFeatureGroupExtension::GeoFeatureGroupExtension(void)
{
initExtensionType(GeoFeatureGroupExtension::getExtensionClassTypeId());
Group.setScope(LinkScope::Child);
}
GeoFeatureGroupExtension::~GeoFeatureGroupExtension(void)
{
}
void GeoFeatureGroupExtension::initExtension(ExtensionContainer* obj) {
if(!obj->isDerivedFrom(App::GeoFeature::getClassTypeId()))
throw Base::RuntimeError("GeoFeatureGroupExtension can only be applied to GeoFeatures");
App::GroupExtension::initExtension(obj);
}
PropertyPlacement& GeoFeatureGroupExtension::placement() {
if(!getExtendedContainer())
throw Base::RuntimeError("GeoFeatureGroupExtension was not applied to GeoFeature");
return static_cast<App::GeoFeature*>(getExtendedContainer())->Placement;
}
void GeoFeatureGroupExtension::transformPlacement(const Base::Placement &transform)
{
// NOTE: Keep in sync with APP::GeoFeature
Base::Placement plm = this->placement().getValue();
plm = transform * plm;
this->placement().setValue(plm);
}
DocumentObject* GeoFeatureGroupExtension::getGroupOfObject(const DocumentObject* obj)
{
if(!obj)
return nullptr;
//we will find origins, but not origin features
if(obj->isDerivedFrom(App::OriginFeature::getClassTypeId()))
return OriginGroupExtension::getGroupOfObject(obj);
//compared to GroupExtension we do return here all GeoFeatureGroups including all extensions derived from it
//like OriginGroup. That is needed as we use this function to get all local coordinate systems. Also there
//is no reason to distinguish between GeoFeatuerGroups, there is only between group/geofeaturegroup
auto list = obj->getInList();
for (auto inObj : list) {
//There is a chance that a derived geofeaturegroup links with a local link and hence is not
//the parent group even though it links to the object. We use hasObject as one and only truth
//if it has the object within the group
if(inObj->hasExtension(App::GeoFeatureGroupExtension::getExtensionClassTypeId()) &&
inObj->getExtensionByType<GeoFeatureGroupExtension>()->hasObject(obj)) {
return inObj;
}
}
return nullptr;
}
Base::Placement GeoFeatureGroupExtension::globalGroupPlacement() {
return recursiveGroupPlacement(this);
}
Base::Placement GeoFeatureGroupExtension::recursiveGroupPlacement(GeoFeatureGroupExtension* group) {
auto inList = group->getExtendedObject()->getInList();
for(auto* link : inList) {
if(link->hasExtension(App::GeoFeatureGroupExtension::getExtensionClassTypeId()))
return recursiveGroupPlacement(link->getExtensionByType<GeoFeatureGroupExtension>()) * group->placement().getValue();
}
return group->placement().getValue();
}
std::vector<DocumentObject*> GeoFeatureGroupExtension::addObjects(std::vector<App::DocumentObject*> objects) {
std::vector<DocumentObject*> grp = Group.getValues();
std::vector<DocumentObject*> ret;
for(auto object : objects) {
if(!allowObject(object))
continue;
//cross CoordinateSystem links are not allowed, so we need to move the whole link group
std::vector<App::DocumentObject*> links = getCSRelevantLinks(object);
links.push_back(object);
for( auto obj : links) {
//only one geofeaturegroup per object.
auto *group = App::GeoFeatureGroupExtension::getGroupOfObject(obj);
if(group && group != getExtendedObject())
group->getExtensionByType<App::GroupExtension>()->removeObject(obj);
if (!hasObject(obj)) {
grp.push_back(obj);
ret.push_back(obj);
}
}
}
Group.setValues(grp);
return ret;
}
std::vector<DocumentObject*> GeoFeatureGroupExtension::removeObjects(std::vector<App::DocumentObject*> objects) {
std::vector<DocumentObject*> removed;
std::vector<DocumentObject*> grp = Group.getValues();
for(auto object : objects) {
//cross CoordinateSystem links are not allowed, so we need to remove the whole link group
std::vector< DocumentObject* > links = getCSRelevantLinks(object);
links.push_back(object);
//remove all links out of group
for(auto link : links) {
auto end = std::remove(grp.begin(), grp.end(), link);
if(end != grp.end()) {
grp.erase(end, grp.end());
removed.push_back(link);
}
}
}
if(!removed.empty())
Group.setValues(grp);
return removed;
}
void GeoFeatureGroupExtension::extensionOnChanged(const Property* p) {
//objects are only allowed in a single GeoFeatureGroup
if((strcmp(p->getName(), "Group")==0)) {
bool error = false;
auto corrected = Group.getValues();
for(auto obj : Group.getValues()) {
//we have already set the obj into the group, so in a case of multiple groups getGroupOfObject
//would return anyone of it and hence it is possible that we miss an error. We need a custom check
auto list = obj->getInList();
for (auto in : list) {
if(in->hasExtension(App::GeoFeatureGroupExtension::getExtensionClassTypeId()) && //is GeoFeatureGroup?
in != getExtendedObject() && //is a different one?
in->getExtensionByType<App::GeoFeatureGroupExtension>()->hasObject(obj)) { //is not a non-grouping link?
error = true;
corrected.erase(std::remove(corrected.begin(), corrected.end(), obj), corrected.end());
}
}
}
//if an error was found we need to correct the values and inform the user
if(error) {
Group.setValues(corrected);
throw Base::Exception("Object can only be in a single GeoFeatureGroup");
}
}
App::GroupExtension::extensionOnChanged(p);
}
std::vector< DocumentObject* > GeoFeatureGroupExtension::getScopedObjectsFromLinks(const DocumentObject* obj, LinkScope scope) {
if(!obj)
return std::vector< DocumentObject* >();
//we get all linked objects. We can't use outList() as this includes the links from expressions
std::vector< App::DocumentObject* > result;
std::vector<App::Property*> list;
obj->getPropertyList(list);
for(App::Property* prop : list) {
auto vec = getScopedObjectsFromLink(prop, scope);
result.insert(result.end(), vec.begin(), vec.end());
}
//clear all null objects and duplicates
std::sort(result.begin(), result.end());
result.erase(std::unique(result.begin(), result.end()), result.end());
return result;
}
std::vector< DocumentObject* > GeoFeatureGroupExtension::getScopedObjectsFromLink(App::Property* prop, LinkScope scope) {
if(!prop)
return std::vector< DocumentObject* >();
std::vector< App::DocumentObject* > result;
if(prop->getTypeId().isDerivedFrom(App::PropertyLink::getClassTypeId()) &&
static_cast<App::PropertyLink*>(prop)->getScope() == scope) {
result.push_back(static_cast<App::PropertyLink*>(prop)->getValue());
}
if(prop->getTypeId().isDerivedFrom(App::PropertyLinkList::getClassTypeId()) &&
static_cast<App::PropertyLinkList*>(prop)->getScope() == scope) {
auto vec = static_cast<App::PropertyLinkList*>(prop)->getValues();
result.insert(result.end(), vec.begin(), vec.end());
}
if(prop->getTypeId().isDerivedFrom(App::PropertyLinkSub::getClassTypeId()) &&
static_cast<App::PropertyLinkSub*>(prop)->getScope() == scope) {
result.push_back(static_cast<App::PropertyLinkSub*>(prop)->getValue());
}
if(prop->getTypeId().isDerivedFrom(App::PropertyLinkSubList::getClassTypeId()) &&
static_cast<App::PropertyLinkSubList*>(prop)->getScope() == scope) {
auto vec = static_cast<App::PropertyLinkSubList*>(prop)->getValues();
result.insert(result.end(), vec.begin(), vec.end());
}
//it is important to remove all nullptrs
result.erase(std::remove(result.begin(), result.end(), nullptr), result.end());
return result;
}
void GeoFeatureGroupExtension::getCSOutList(const App::DocumentObject* obj,
std::vector< DocumentObject* >& vec) {
if(!obj)
return;
//we get all relevant linked objects. We can't use outList() as this includes the links from expressions,
//also we only want links with scope Local
auto result = getScopedObjectsFromLinks(obj, LinkScope::Local);
//we remove all links to origin features and origins, they belong to a CS too and can't be moved
result.erase(std::remove_if(result.begin(), result.end(), [](App::DocumentObject* obj)->bool {
return (obj->isDerivedFrom(App::OriginFeature::getClassTypeId()) ||
obj->isDerivedFrom(App::Origin::getClassTypeId()));
}), result.end());
vec.insert(vec.end(), result.begin(), result.end());
//post process the vector
std::sort(vec.begin(), vec.end());
vec.erase(std::unique(vec.begin(), vec.end()), vec.end());
}
void GeoFeatureGroupExtension::getCSInList(const DocumentObject* obj,
std::vector< DocumentObject* >& vec) {
if(!obj)
return;
//search the inlist for objects that have non-expression links to us
for(App::DocumentObject* parent : obj->getInList()) {
//not interested in other groups (and here we mean all groups, normal ones and geofeaturegroup)
if(parent->hasExtension(App::GroupExtension::getExtensionClassTypeId()))
continue;
//check if the link is real Local scope one or if it is a expression one (could also be both, so it is not
//enough to check the expressions)
auto res = getScopedObjectsFromLinks(parent, LinkScope::Local);
if(std::find(res.begin(), res.end(), obj) != res.end())
vec.push_back(parent);
}
//clear all duplicates
std::sort(vec.begin(), vec.end());
vec.erase(std::unique(vec.begin(), vec.end()), vec.end());
}
std::vector< DocumentObject* > GeoFeatureGroupExtension::getCSRelevantLinks(const DocumentObject* obj) {
if(!obj)
return std::vector< DocumentObject* >();
//get all out links
std::vector<DocumentObject*> vec;
recursiveCSRelevantLinks(obj, vec);
//post process the list after we added many things
std::sort(vec.begin(), vec.end());
vec.erase(std::unique(vec.begin(), vec.end()), vec.end());
vec.erase(std::remove(vec.begin(), vec.end(), obj), vec.end());
return vec;
}
void GeoFeatureGroupExtension::recursiveCSRelevantLinks(const DocumentObject* obj,
std::vector< DocumentObject* >& vec) {
if(!obj)
return;
std::vector< DocumentObject* > links;
getCSOutList(obj, links);
getCSInList(obj, links);
//go on traversing the graph in all directions!
for(auto o : links) {
if(!o || o == obj || std::find(vec.begin(), vec.end(), o) != vec.end())
continue;
vec.push_back(o);
recursiveCSRelevantLinks(o, vec);
}
}
bool GeoFeatureGroupExtension::areLinksValid(const DocumentObject* obj) {
if(!obj)
return true;
//no cross CS link for local links.
//Base::Console().Message("Check object links: %s\n", obj->getNameInDocument());
std::vector<App::Property*> list;
obj->getPropertyList(list);
for(App::Property* prop : list) {
if(!isLinkValid(prop)) {
//Base::Console().Message("Invalid link: %s\n", prop->getName());
return false;
}
}
return true;
}
bool GeoFeatureGroupExtension::isLinkValid(App::Property* prop) {
if(!prop)
return true;
//get the object that holds the property
if(!prop->getContainer()->isDerivedFrom(App::DocumentObject::getClassTypeId()))
return true; //this link comes not from a document object, scopes are meaningless
auto obj = static_cast<App::DocumentObject*>(prop->getContainer());
//no cross CS link for local links.
auto result = getScopedObjectsFromLink(prop, LinkScope::Local);
auto group = getGroupOfObject(obj);
for(auto link : result) {
if(getGroupOfObject(link) != group)
return false;
}
//for links with scope SubGroup we need to check if all features are part of subgroups
if(obj->hasExtension(App::GeoFeatureGroupExtension::getExtensionClassTypeId())) {
result = getScopedObjectsFromLink(prop, LinkScope::Child);
auto groupExt = obj->getExtensionByType<App::GeoFeatureGroupExtension>();
for(auto link : result) {
if(!groupExt->hasObject(link, true))
return false;
}
}
return true;
}
void GeoFeatureGroupExtension::getInvalidLinkObjects(const DocumentObject* obj, std::vector< DocumentObject* >& vec) {
if(!obj)
return;
//no cross CS link for local links.
auto result = getScopedObjectsFromLinks(obj, LinkScope::Local);
auto group = obj->hasExtension(App::GeoFeatureGroupExtension::getExtensionClassTypeId()) ? obj : getGroupOfObject(obj);
for(auto link : result) {
if(getGroupOfObject(link) != group)
vec.push_back(link);
}
//for links with scope SubGroup we need to check if all features are part of subgroups
if(group) {
result = getScopedObjectsFromLinks(obj, LinkScope::Child);
auto groupExt = group->getExtensionByType<App::GeoFeatureGroupExtension>();
for(auto link : result) {
if(!groupExt->hasObject(link, true))
vec.push_back(link);
}
}
}
// Python feature ---------------------------------------------------------
namespace App {
EXTENSION_PROPERTY_SOURCE_TEMPLATE(App::GeoFeatureGroupExtensionPython, App::GeoFeatureGroupExtension)
// explicit template instantiation
template class AppExport ExtensionPythonT<GroupExtensionPythonT<GeoFeatureGroupExtension>>;
}
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "otbCompareImages.h"
#include "otbVectorImage.h"
#include "otbImageFileReader.h"
#include "otbMultiToMonoChannelExtractROI.h"
#include "otbStreamingCompareImageFilter.h"
#include <iostream>
namespace otb
{
int CompareImages::Describe(ApplicationDescriptor* descriptor)
{
descriptor->SetName("CompareImages");
descriptor->SetDescription("Estimator between 2 images");
descriptor->AddOption("InputReference","The reference image","-inR", 1, true,ApplicationDescriptor::String);
descriptor->AddOption("InputMeasured","The measured image","-inM", 1, true,ApplicationDescriptor::String);
descriptor->AddOption("NumBandRefImage","The channel number to compare in the reference image (between 1 and number of channels)","-chR", 1, false,ApplicationDescriptor::Integer);
descriptor->AddOption("NumBandMeasuredImage","The channel number to compare in the measured image (between 1 and number of channels)","-chM", 1, false,ApplicationDescriptor::Integer);
descriptor->AddOption("StartX", "first point in x-axis ", "-x0", 1, false, ApplicationDescriptor::Real);
descriptor->AddOption("StartY", "first point in y-axis ", "-y0", 1, false, ApplicationDescriptor::Real);
descriptor->AddOption("SizeX", "size in x-axis ", "-Nx", 1, false, ApplicationDescriptor::Integer);
descriptor->AddOption("SizeY", "size in y-axis ", "-Ny", 1, false, ApplicationDescriptor::Integer);
return EXIT_SUCCESS;
}
int CompareImages::Execute(otb::ApplicationOptionsResult* parseResult)
{
typedef double PixelType;
typedef otb::VectorImage<PixelType, 2> ImageType;
typedef otb::ImageFileReader<ImageType> ReaderType;
typedef otb::MultiToMonoChannelExtractROI<PixelType, PixelType> ExtractROIMonoFilterType;
typedef otb::StreamingCompareImageFilter<ExtractROIMonoFilterType::OutputImageType> StreamingCompareImageFilterType;
//typedef otb::StreamingStatisticsImageFilter<ExtractROIMonoFilterType::OutputImageType> StreamingCompareImageFilterType;
// Read input images information
ReaderType::Pointer reader1= ReaderType::New();
reader1->SetFileName(parseResult->GetParameterString("InputReference"));
reader1->GenerateOutputInformation();
ReaderType::Pointer reader2= ReaderType::New();
reader2->SetFileName(parseResult->GetParameterString("InputMeasured"));
reader2->GenerateOutputInformation();
unsigned int layer1 = 1;
unsigned int layer2 = 1;
if (parseResult->IsOptionPresent("NumBandRefImage"))
{
layer1 = parseResult->GetParameterUInt("NumBandRefImage");
}
if (parseResult->IsOptionPresent("NumBandMeasuredImage"))
{
layer2 = parseResult->GetParameterUInt("NumBandMeasuredImage");
}
ExtractROIMonoFilterType::Pointer extractROIMonoFilter1= ExtractROIMonoFilterType::New();
extractROIMonoFilter1->SetInput(reader1->GetOutput());
extractROIMonoFilter1->SetChannel( layer1 );
ExtractROIMonoFilterType::Pointer extractROIMonoFilter2= ExtractROIMonoFilterType::New();
extractROIMonoFilter2->SetInput(reader2->GetOutput());
extractROIMonoFilter2->SetChannel( layer2 );
if (parseResult->IsOptionPresent("StartX"))
{
extractROIMonoFilter1->SetStartX(parseResult->GetParameterULong("StartX"));
extractROIMonoFilter2->SetStartX(parseResult->GetParameterULong("StartX"));
}
if (parseResult->IsOptionPresent("StartY"))
{
extractROIMonoFilter1->SetStartY(parseResult->GetParameterULong("StartY"));
extractROIMonoFilter2->SetStartY(parseResult->GetParameterULong("StartY"));
}
if (parseResult->IsOptionPresent("SizeX"))
{
extractROIMonoFilter1->SetSizeX(parseResult->GetParameterULong("SizeX"));
extractROIMonoFilter2->SetSizeX(parseResult->GetParameterULong("SizeX"));
}
if (parseResult->IsOptionPresent("SizeY"))
{
extractROIMonoFilter1->SetSizeY(parseResult->GetParameterULong("SizeY"));
extractROIMonoFilter2->SetSizeY(parseResult->GetParameterULong("SizeY"));
}
StreamingCompareImageFilterType::Pointer filter = StreamingCompareImageFilterType::New();
filter->SetInput1(extractROIMonoFilter1->GetOutput());
filter->SetInput2(extractROIMonoFilter2->GetOutput());
filter->Update();
std::cout << "MSE: " << filter->GetMSE() << std::endl;
std::cout << "MAE: " << filter->GetMAE() << std::endl;
std::cout << "PSNR: " << filter->GetPSNR() << std::endl;
return EXIT_SUCCESS;
}
}
<commit_msg>ENH : remove the - from the option alias name<commit_after>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "otbCompareImages.h"
#include "otbVectorImage.h"
#include "otbImageFileReader.h"
#include "otbMultiToMonoChannelExtractROI.h"
#include "otbStreamingCompareImageFilter.h"
#include <iostream>
namespace otb
{
int CompareImages::Describe(ApplicationDescriptor* descriptor)
{
descriptor->SetName("CompareImages");
descriptor->SetDescription("Estimator between 2 images");
descriptor->AddOption("InputReference","The reference image","inR", 1, true,ApplicationDescriptor::String);
descriptor->AddOption("InputMeasured","The measured image","inM", 1, true,ApplicationDescriptor::String);
descriptor->AddOption("NumBandRefImage","The channel number to compare in the reference image (between 1 and number of channels)","chR", 1, false,ApplicationDescriptor::Integer);
descriptor->AddOption("NumBandMeasuredImage","The channel number to compare in the measured image (between 1 and number of channels)","chM", 1, false,ApplicationDescriptor::Integer);
descriptor->AddOption("StartX", "first point in x-axis ", "x0", 1, false, ApplicationDescriptor::Real);
descriptor->AddOption("StartY", "first point in y-axis ", "y0", 1, false, ApplicationDescriptor::Real);
descriptor->AddOption("SizeX", "size in x-axis ", "Nx", 1, false, ApplicationDescriptor::Integer);
descriptor->AddOption("SizeY", "size in y-axis ", "Ny", 1, false, ApplicationDescriptor::Integer);
return EXIT_SUCCESS;
}
int CompareImages::Execute(otb::ApplicationOptionsResult* parseResult)
{
typedef double PixelType;
typedef otb::VectorImage<PixelType, 2> ImageType;
typedef otb::ImageFileReader<ImageType> ReaderType;
typedef otb::MultiToMonoChannelExtractROI<PixelType, PixelType> ExtractROIMonoFilterType;
typedef otb::StreamingCompareImageFilter<ExtractROIMonoFilterType::OutputImageType> StreamingCompareImageFilterType;
//typedef otb::StreamingStatisticsImageFilter<ExtractROIMonoFilterType::OutputImageType> StreamingCompareImageFilterType;
// Read input images information
ReaderType::Pointer reader1= ReaderType::New();
reader1->SetFileName(parseResult->GetParameterString("InputReference"));
reader1->GenerateOutputInformation();
ReaderType::Pointer reader2= ReaderType::New();
reader2->SetFileName(parseResult->GetParameterString("InputMeasured"));
reader2->GenerateOutputInformation();
unsigned int layer1 = 1;
unsigned int layer2 = 1;
if (parseResult->IsOptionPresent("NumBandRefImage"))
{
layer1 = parseResult->GetParameterUInt("NumBandRefImage");
}
if (parseResult->IsOptionPresent("NumBandMeasuredImage"))
{
layer2 = parseResult->GetParameterUInt("NumBandMeasuredImage");
}
ExtractROIMonoFilterType::Pointer extractROIMonoFilter1= ExtractROIMonoFilterType::New();
extractROIMonoFilter1->SetInput(reader1->GetOutput());
extractROIMonoFilter1->SetChannel( layer1 );
ExtractROIMonoFilterType::Pointer extractROIMonoFilter2= ExtractROIMonoFilterType::New();
extractROIMonoFilter2->SetInput(reader2->GetOutput());
extractROIMonoFilter2->SetChannel( layer2 );
if (parseResult->IsOptionPresent("StartX"))
{
extractROIMonoFilter1->SetStartX(parseResult->GetParameterULong("StartX"));
extractROIMonoFilter2->SetStartX(parseResult->GetParameterULong("StartX"));
}
if (parseResult->IsOptionPresent("StartY"))
{
extractROIMonoFilter1->SetStartY(parseResult->GetParameterULong("StartY"));
extractROIMonoFilter2->SetStartY(parseResult->GetParameterULong("StartY"));
}
if (parseResult->IsOptionPresent("SizeX"))
{
extractROIMonoFilter1->SetSizeX(parseResult->GetParameterULong("SizeX"));
extractROIMonoFilter2->SetSizeX(parseResult->GetParameterULong("SizeX"));
}
if (parseResult->IsOptionPresent("SizeY"))
{
extractROIMonoFilter1->SetSizeY(parseResult->GetParameterULong("SizeY"));
extractROIMonoFilter2->SetSizeY(parseResult->GetParameterULong("SizeY"));
}
StreamingCompareImageFilterType::Pointer filter = StreamingCompareImageFilterType::New();
filter->SetInput1(extractROIMonoFilter1->GetOutput());
filter->SetInput2(extractROIMonoFilter2->GetOutput());
filter->Update();
std::cout << "MSE: " << filter->GetMSE() << std::endl;
std::cout << "MAE: " << filter->GetMAE() << std::endl;
std::cout << "PSNR: " << filter->GetPSNR() << std::endl;
return EXIT_SUCCESS;
}
}
<|endoftext|>
|
<commit_before>/****************************************************************************
*
* Copyright (c) 2016 PX4 Development Team. 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 PX4 nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/**
* @file df_ms5611_wrapper.cpp
* Lightweight driver to access the MS5611 of the DriverFramework.
*/
#include <px4_config.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdint.h>
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <unistd.h>
#include <px4_getopt.h>
#include <errno.h>
#include <perf/perf_counter.h>
#include <systemlib/err.h>
#include <drivers/drv_baro.h>
#include <drivers/drv_hrt.h>
#include <board_config.h>
#include <ms5611/MS5611.hpp>
#include <DevMgr.hpp>
extern "C" { __EXPORT int df_ms5611_wrapper_main(int argc, char *argv[]); }
using namespace DriverFramework;
class DfMS5611Wrapper : public MS5611
{
public:
DfMS5611Wrapper();
~DfMS5611Wrapper();
/**
* Start automatic measurement.
*
* @return 0 on success
*/
int start();
/**
* Stop automatic measurement.
*
* @return 0 on success
*/
int stop();
private:
int _publish(struct baro_sensor_data &data);
orb_advert_t _baro_topic;
int _baro_orb_class_instance;
perf_counter_t _baro_sample_perf;
};
DfMS5611Wrapper::DfMS5611Wrapper() :
MS5611(BARO_DEVICE_PATH),
_baro_topic(nullptr),
_baro_orb_class_instance(-1),
_baro_sample_perf(perf_alloc(PC_ELAPSED, "df_baro_read"))
{
}
DfMS5611Wrapper::~DfMS5611Wrapper()
{
perf_free(_baro_sample_perf);
}
int DfMS5611Wrapper::start()
{
/* Init device and start sensor. */
int ret = init();
if (ret != 0) {
PX4_ERR("MS5611 init fail: %d", ret);
return ret;
}
ret = MS5611::start();
if (ret != 0) {
PX4_ERR("MS5611 start fail: %d", ret);
return ret;
}
return 0;
}
int DfMS5611Wrapper::stop()
{
/* Stop sensor. */
int ret = MS5611::stop();
if (ret != 0) {
PX4_ERR("MS5611 stop fail: %d", ret);
return ret;
}
return 0;
}
int DfMS5611Wrapper::_publish(struct baro_sensor_data &data)
{
perf_begin(_baro_sample_perf);
baro_report baro_report;
baro_report.timestamp = hrt_absolute_time();
baro_report.pressure = data.pressure_pa / 100.0f; // convert to mbar
baro_report.temperature = data.temperature_c;
// TODO: when is this ever blocked?
if (!(m_pub_blocked)) {
if (_baro_topic == nullptr) {
_baro_topic = orb_advertise_multi(ORB_ID(sensor_baro), &baro_report,
&_baro_orb_class_instance, ORB_PRIO_DEFAULT);
} else {
orb_publish(ORB_ID(sensor_baro), _baro_topic, &baro_report);
}
}
perf_end(_baro_sample_perf);
return 0;
};
namespace df_ms5611_wrapper
{
DfMS5611Wrapper *g_dev = nullptr;
int start(/* enum Rotation rotation */);
int stop();
int info();
void usage();
int start(/*enum Rotation rotation*/)
{
g_dev = new DfMS5611Wrapper(/*rotation*/);
if (g_dev == nullptr) {
PX4_ERR("failed instantiating DfMS5611Wrapper object");
return -1;
}
int ret = g_dev->start();
if (ret != 0) {
PX4_ERR("DfMS5611Wrapper start failed");
return ret;
}
// Open the IMU sensor
DevHandle h;
DevMgr::getHandle(BARO_DEVICE_PATH, h);
if (!h.isValid()) {
DF_LOG_INFO("Error: unable to obtain a valid handle for the receiver at: %s (%d)",
BARO_DEVICE_PATH, h.getError());
return -1;
}
DevMgr::releaseHandle(h);
return 0;
}
int stop()
{
if (g_dev == nullptr) {
PX4_ERR("driver not running");
return 1;
}
int ret = g_dev->stop();
if (ret != 0) {
PX4_ERR("driver could not be stopped");
return ret;
}
delete g_dev;
g_dev = nullptr;
return 0;
}
/**
* Print a little info about the driver.
*/
int
info()
{
if (g_dev == nullptr) {
PX4_ERR("driver not running");
return 1;
}
PX4_DEBUG("state @ %p", g_dev);
return 0;
}
void
usage()
{
PX4_WARN("Usage: df_ms5611_wrapper 'start', 'info', 'stop'");
}
} // namespace df_ms5611_wrapper
int
df_ms5611_wrapper_main(int argc, char *argv[])
{
int ret = 0;
int myoptind = 1;
if (argc <= 1) {
df_ms5611_wrapper::usage();
return 1;
}
const char *verb = argv[myoptind];
if (!strcmp(verb, "start")) {
ret = df_ms5611_wrapper::start();
}
else if (!strcmp(verb, "stop")) {
ret = df_ms5611_wrapper::stop();
}
else if (!strcmp(verb, "info")) {
ret = df_ms5611_wrapper::info();
}
else {
df_ms5611_wrapper::usage();
return 1;
}
return ret;
}
<commit_msg>df_ms5611_wrapper: fix initialization of error_count & device_id<commit_after>/****************************************************************************
*
* Copyright (c) 2016 PX4 Development Team. 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 PX4 nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/**
* @file df_ms5611_wrapper.cpp
* Lightweight driver to access the MS5611 of the DriverFramework.
*/
#include <px4_config.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdint.h>
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <unistd.h>
#include <px4_getopt.h>
#include <errno.h>
#include <perf/perf_counter.h>
#include <systemlib/err.h>
#include <drivers/drv_baro.h>
#include <drivers/drv_hrt.h>
#include <board_config.h>
#include <ms5611/MS5611.hpp>
#include <DevMgr.hpp>
extern "C" { __EXPORT int df_ms5611_wrapper_main(int argc, char *argv[]); }
using namespace DriverFramework;
class DfMS5611Wrapper : public MS5611
{
public:
DfMS5611Wrapper();
~DfMS5611Wrapper();
/**
* Start automatic measurement.
*
* @return 0 on success
*/
int start();
/**
* Stop automatic measurement.
*
* @return 0 on success
*/
int stop();
private:
int _publish(struct baro_sensor_data &data);
orb_advert_t _baro_topic;
int _baro_orb_class_instance;
perf_counter_t _baro_sample_perf;
};
DfMS5611Wrapper::DfMS5611Wrapper() :
MS5611(BARO_DEVICE_PATH),
_baro_topic(nullptr),
_baro_orb_class_instance(-1),
_baro_sample_perf(perf_alloc(PC_ELAPSED, "df_baro_read"))
{
}
DfMS5611Wrapper::~DfMS5611Wrapper()
{
perf_free(_baro_sample_perf);
}
int DfMS5611Wrapper::start()
{
/* Init device and start sensor. */
int ret = init();
if (ret != 0) {
PX4_ERR("MS5611 init fail: %d", ret);
return ret;
}
ret = MS5611::start();
if (ret != 0) {
PX4_ERR("MS5611 start fail: %d", ret);
return ret;
}
return 0;
}
int DfMS5611Wrapper::stop()
{
/* Stop sensor. */
int ret = MS5611::stop();
if (ret != 0) {
PX4_ERR("MS5611 stop fail: %d", ret);
return ret;
}
return 0;
}
int DfMS5611Wrapper::_publish(struct baro_sensor_data &data)
{
perf_begin(_baro_sample_perf);
baro_report baro_report;
baro_report.timestamp = hrt_absolute_time();
baro_report.pressure = data.pressure_pa / 100.0f; // convert to mbar
baro_report.temperature = data.temperature_c;
baro_report.error_count = data.error_counter;
baro_report.device_id = m_id.dev_id;
// TODO: when is this ever blocked?
if (!(m_pub_blocked)) {
if (_baro_topic == nullptr) {
_baro_topic = orb_advertise_multi(ORB_ID(sensor_baro), &baro_report,
&_baro_orb_class_instance, ORB_PRIO_DEFAULT);
} else {
orb_publish(ORB_ID(sensor_baro), _baro_topic, &baro_report);
}
}
perf_end(_baro_sample_perf);
return 0;
};
namespace df_ms5611_wrapper
{
DfMS5611Wrapper *g_dev = nullptr;
int start(/* enum Rotation rotation */);
int stop();
int info();
void usage();
int start(/*enum Rotation rotation*/)
{
g_dev = new DfMS5611Wrapper(/*rotation*/);
if (g_dev == nullptr) {
PX4_ERR("failed instantiating DfMS5611Wrapper object");
return -1;
}
int ret = g_dev->start();
if (ret != 0) {
PX4_ERR("DfMS5611Wrapper start failed");
return ret;
}
// Open the IMU sensor
DevHandle h;
DevMgr::getHandle(BARO_DEVICE_PATH, h);
if (!h.isValid()) {
DF_LOG_INFO("Error: unable to obtain a valid handle for the receiver at: %s (%d)",
BARO_DEVICE_PATH, h.getError());
return -1;
}
DevMgr::releaseHandle(h);
return 0;
}
int stop()
{
if (g_dev == nullptr) {
PX4_ERR("driver not running");
return 1;
}
int ret = g_dev->stop();
if (ret != 0) {
PX4_ERR("driver could not be stopped");
return ret;
}
delete g_dev;
g_dev = nullptr;
return 0;
}
/**
* Print a little info about the driver.
*/
int
info()
{
if (g_dev == nullptr) {
PX4_ERR("driver not running");
return 1;
}
PX4_DEBUG("state @ %p", g_dev);
return 0;
}
void
usage()
{
PX4_WARN("Usage: df_ms5611_wrapper 'start', 'info', 'stop'");
}
} // namespace df_ms5611_wrapper
int
df_ms5611_wrapper_main(int argc, char *argv[])
{
int ret = 0;
int myoptind = 1;
if (argc <= 1) {
df_ms5611_wrapper::usage();
return 1;
}
const char *verb = argv[myoptind];
if (!strcmp(verb, "start")) {
ret = df_ms5611_wrapper::start();
}
else if (!strcmp(verb, "stop")) {
ret = df_ms5611_wrapper::stop();
}
else if (!strcmp(verb, "info")) {
ret = df_ms5611_wrapper::info();
}
else {
df_ms5611_wrapper::usage();
return 1;
}
return ret;
}
<|endoftext|>
|
<commit_before>#include "RenderManager.hpp"
#include <GL/glew.h>
#include "../Manager/Managers.hpp"
#include "../Manager/ResourceManager.hpp"
#include "Default3D.vert.hpp"
#include "Default3D.frag.hpp"
#include "../Shader/ShaderProgram.hpp"
#include "../Entity/Entity.hpp"
#include "../Component/Lens.hpp"
#include "../Component/Transform.hpp"
#include "../Component/Mesh.hpp"
#include "../Geometry/Geometry3D.hpp"
#include "../Lighting/DeferredLighting.hpp"
#include <glm/gtc/matrix_transform.hpp>
using namespace Component;
RenderManager::RenderManager(const glm::vec2& screenSize) {
vertexShader = Managers().resourceManager->CreateShader(DEFAULT3D_VERT, DEFAULT3D_VERT_LENGTH, GL_VERTEX_SHADER);
fragmentShader = Managers().resourceManager->CreateShader(DEFAULT3D_FRAG, DEFAULT3D_FRAG_LENGTH, GL_FRAGMENT_SHADER);
shaderProgram = Managers().resourceManager->CreateShaderProgram({ vertexShader, fragmentShader });
deferredLighting = new DeferredLighting(screenSize);
}
RenderManager::~RenderManager() {
Managers().resourceManager->FreeShader(vertexShader);
Managers().resourceManager->FreeShader(fragmentShader);
Managers().resourceManager->FreeShaderProgram(shaderProgram);
delete deferredLighting;
}
void RenderManager::Render(Scene& scene, const glm::vec2& screenSize) {
deferredLighting->SetTarget();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glViewport(0, 0, static_cast<GLsizei>(screenSize.x), static_cast<GLsizei>(screenSize.y));
// Find camera entity.
Entity* camera = nullptr;
std::vector<Lens*> lenses = scene.GetComponents<Lens>();
for (Lens* lens : lenses) {
if (lens->entity->GetComponent<Transform>() != nullptr)
camera = lens->entity;
};
// Render from camera.
if (camera != nullptr) {
shaderProgram->Use();
glm::mat4 viewMat = camera->GetComponent<Component::Transform>()->GetCameraOrientation() * glm::translate(glm::mat4(), -camera->GetComponent<Transform>()->position);
glm::mat4 projectionMat = camera->GetComponent<Component::Lens>()->GetProjection(screenSize);
glm::mat4 viewProjectionMat = projectionMat * viewMat;
glUniformMatrix4fv(shaderProgram->GetUniformLocation("viewProjection"), 1, GL_FALSE, &viewProjectionMat[0][0]);
// Finds models in scene.
std::vector<Mesh*> meshes = scene.GetComponents<Mesh>();
for (Mesh* mesh : meshes) {
Entity* model = mesh->entity;
Transform* transform = model->GetComponent<Component::Transform>();
if (transform != nullptr) {
glm::mat4 modelMat = transform->GetModelMatrix();
glBindVertexArray(mesh->geometry->GetVertexArray());
// Render model.
glUniformMatrix4fv(shaderProgram->GetUniformLocation("model"), 1, GL_FALSE, &modelMat[0][0]);
glm::mat4 normalMat = glm::transpose(glm::inverse(viewMat * modelMat));
glUniformMatrix3fv(shaderProgram->GetUniformLocation("normalMatrix"), 1, GL_FALSE, &glm::mat3(normalMat)[0][0]);
glDrawElements(GL_TRIANGLES, mesh->geometry->GetIndexCount(), GL_UNSIGNED_INT, (void*)0);
}
}
glBindVertexArray(0);
}
// Light the scene.
deferredLighting->ResetTarget();
deferredLighting->Render(scene, camera, screenSize);
}
<commit_msg>Don't render meshes with no geometry.<commit_after>#include "RenderManager.hpp"
#include <GL/glew.h>
#include "../Manager/Managers.hpp"
#include "../Manager/ResourceManager.hpp"
#include "Default3D.vert.hpp"
#include "Default3D.frag.hpp"
#include "../Shader/ShaderProgram.hpp"
#include "../Entity/Entity.hpp"
#include "../Component/Lens.hpp"
#include "../Component/Transform.hpp"
#include "../Component/Mesh.hpp"
#include "../Geometry/Geometry3D.hpp"
#include "../Lighting/DeferredLighting.hpp"
#include <glm/gtc/matrix_transform.hpp>
using namespace Component;
RenderManager::RenderManager(const glm::vec2& screenSize) {
vertexShader = Managers().resourceManager->CreateShader(DEFAULT3D_VERT, DEFAULT3D_VERT_LENGTH, GL_VERTEX_SHADER);
fragmentShader = Managers().resourceManager->CreateShader(DEFAULT3D_FRAG, DEFAULT3D_FRAG_LENGTH, GL_FRAGMENT_SHADER);
shaderProgram = Managers().resourceManager->CreateShaderProgram({ vertexShader, fragmentShader });
deferredLighting = new DeferredLighting(screenSize);
}
RenderManager::~RenderManager() {
Managers().resourceManager->FreeShader(vertexShader);
Managers().resourceManager->FreeShader(fragmentShader);
Managers().resourceManager->FreeShaderProgram(shaderProgram);
delete deferredLighting;
}
void RenderManager::Render(Scene& scene, const glm::vec2& screenSize) {
deferredLighting->SetTarget();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glViewport(0, 0, static_cast<GLsizei>(screenSize.x), static_cast<GLsizei>(screenSize.y));
// Find camera entity.
Entity* camera = nullptr;
std::vector<Lens*> lenses = scene.GetComponents<Lens>();
for (Lens* lens : lenses) {
if (lens->entity->GetComponent<Transform>() != nullptr)
camera = lens->entity;
};
// Render from camera.
if (camera != nullptr) {
shaderProgram->Use();
glm::mat4 viewMat = camera->GetComponent<Component::Transform>()->GetCameraOrientation() * glm::translate(glm::mat4(), -camera->GetComponent<Transform>()->position);
glm::mat4 projectionMat = camera->GetComponent<Component::Lens>()->GetProjection(screenSize);
glm::mat4 viewProjectionMat = projectionMat * viewMat;
glUniformMatrix4fv(shaderProgram->GetUniformLocation("viewProjection"), 1, GL_FALSE, &viewProjectionMat[0][0]);
// Finds models in scene.
std::vector<Mesh*> meshes = scene.GetComponents<Mesh>();
for (Mesh* mesh : meshes) {
Entity* model = mesh->entity;
Transform* transform = model->GetComponent<Component::Transform>();
if (transform != nullptr && mesh->geometry != nullptr) {
glm::mat4 modelMat = transform->GetModelMatrix();
glBindVertexArray(mesh->geometry->GetVertexArray());
// Render model.
glUniformMatrix4fv(shaderProgram->GetUniformLocation("model"), 1, GL_FALSE, &modelMat[0][0]);
glm::mat4 normalMat = glm::transpose(glm::inverse(viewMat * modelMat));
glUniformMatrix3fv(shaderProgram->GetUniformLocation("normalMatrix"), 1, GL_FALSE, &glm::mat3(normalMat)[0][0]);
glDrawElements(GL_TRIANGLES, mesh->geometry->GetIndexCount(), GL_UNSIGNED_INT, (void*)0);
}
}
glBindVertexArray(0);
}
// Light the scene.
deferredLighting->ResetTarget();
deferredLighting->Render(scene, camera, screenSize);
}
<|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_lite_support/c/task/vision/image_classifier.h"
#include <string.h>
#include "tensorflow_lite_support/c/task/processor/classification_result.h"
#include "tensorflow_lite_support/c/task/vision/core/frame_buffer.h"
#include "tensorflow_lite_support/c/test/task/vision/utils/image_utils.h"
#include "tensorflow_lite_support/cc/port/gmock.h"
#include "tensorflow_lite_support/cc/port/gtest.h"
#include "tensorflow_lite_support/cc/test/test_utils.h"
namespace tflite {
namespace task {
namespace vision {
namespace {
using ::tflite::task::JoinPath;
constexpr char kTestDataDirectory[] =
"tensorflow_lite_support/cc/test/testdata/task/vision/";
// Quantized model.
constexpr char kMobileNetQuantizedWithMetadata[] =
"mobilenet_v1_0.25_224_quant.tflite";
CImageData LoadImage(const char* image_name) {
return CDecodeImageFromFile(
JoinPath("./" /*test src dir*/, kTestDataDirectory, image_name).data());
}
TEST(CImageClassifierFromOptionsTest, FailsWithMissingModelPath) {
TfLiteImageClassifierOptions options = {0};
TfLiteImageClassifier* image_classifier =
TfLiteImageClassifierFromOptions(&options);
ASSERT_EQ(image_classifier, nullptr);
}
TEST(CImageClassifierFromOptionsTest, SucceedsWithModelPath) {
// TfLiteImageClassifierOptions* options =
// TfLiteImageClassifierOptionsCreate();
const char* model_path = JoinPath("./" /*test src dir*/, kTestDataDirectory,
kMobileNetQuantizedWithMetadata)
.data();
TfLiteImageClassifierOptions options = {0};
options.base_options.model_file.file_path = model_path;
TfLiteImageClassifier* image_classifier =
TfLiteImageClassifierFromOptions(&options);
EXPECT_NE(image_classifier, nullptr);
TfLiteImageClassifierDelete(image_classifier);
}
TEST(CImageClassifierFromOptionsTest, SucceedsWithNumberOfThreads) {
const char* model_path = JoinPath("./" /*test src dir*/, kTestDataDirectory,
kMobileNetQuantizedWithMetadata)
.data();
TfLiteImageClassifierOptions options = {0};
options.base_options.model_file.file_path = model_path;
options.base_options.compute_settings.tflite_settings.cpu_settings
.num_threads = 3;
TfLiteImageClassifier* image_classifier =
TfLiteImageClassifierFromOptions(&options);
EXPECT_NE(image_classifier, nullptr);
TfLiteImageClassifierDelete(image_classifier);
}
TEST(CImageClassifierFromOptionsTest,
FailsWithClassNameBlackListAndClassNameWhiteList) {
const char* model_path = JoinPath("./" /*test src dir*/, kTestDataDirectory,
kMobileNetQuantizedWithMetadata)
.data();
TfLiteImageClassifierOptions options = {0};
options.base_options.model_file.file_path = model_path;
char* class_name_blacklist[] = {"brambling"};
options.classification_options.class_name_blacklist.list =
class_name_blacklist;
options.classification_options.class_name_blacklist.length = 1;
char* class_name_whitelist[] = {"cheeseburger"};
options.classification_options.class_name_whitelist.list =
class_name_whitelist;
options.classification_options.class_name_whitelist.length = 1;
TfLiteImageClassifier* image_classifier =
TfLiteImageClassifierFromOptions(&options);
EXPECT_EQ(image_classifier, nullptr);
if (image_classifier) TfLiteImageClassifierDelete(image_classifier);
}
class CImageClassifierClassifyTest : public ::testing::Test {
protected:
void SetUp() override {
TfLiteImageClassifierOptions options = {0};
options.base_options.model_file.file_path =
JoinPath("./" /*test src dir*/, kTestDataDirectory,
kMobileNetQuantizedWithMetadata)
.data();
image_classifier = TfLiteImageClassifierFromOptions(&options);
ASSERT_NE(image_classifier, nullptr);
}
void TearDown() override { TfLiteImageClassifierDelete(image_classifier); }
TfLiteImageClassifier* image_classifier;
};
TEST_F(CImageClassifierClassifyTest, SucceedsWithImageData) {
CImageData image_data = LoadImage("burger-224.png");
TfLiteFrameBuffer frame_buffer = {.dimension.width = image_data.width,
.dimension.height = image_data.height,
.buffer = image_data.pixel_data,
.format = kRGB};
TfLiteClassificationResult* classification_result =
TfLiteImageClassifierClassify(image_classifier, &frame_buffer);
CImageDataFree(&image_data);
ASSERT_NE(classification_result, nullptr) << "Classification Result is NULL";
EXPECT_TRUE(classification_result->size >= 1)
<< "Classification Result size is 0";
EXPECT_NE(classification_result->classifications, nullptr)
<< "Classification Result Classifications is NULL";
EXPECT_TRUE(classification_result->classifications->size >= 1)
<< "Classification Result Classifications Size is 0";
EXPECT_NE(classification_result->classifications->categories, nullptr)
<< "Classification Result Classifications Classes is NULL";
TfLiteClassificationResultDelete(classification_result);
}
TEST_F(CImageClassifierClassifyTest, SucceedsWithRoiWithinImageBounds) {
CImageData image_data = LoadImage("burger-224.png");
TfLiteFrameBuffer frame_buffer = {.dimension.width = image_data.width,
.dimension.height = image_data.height,
.buffer = image_data.pixel_data,
.format = kRGB};
TfLiteBoundingBox bounding_box = {
.origin_x = 0, .origin_y = 0, .width = 100, .height = 100};
TfLiteClassificationResult* classification_result =
TfLiteImageClassifierClassifyWithRoi(image_classifier, &frame_buffer,
&bounding_box);
CImageDataFree(&image_data);
ASSERT_NE(classification_result, nullptr) << "Classification Result is NULL";
EXPECT_TRUE(classification_result->size >= 1)
<< "Classification Result size is 0";
EXPECT_NE(classification_result->classifications, nullptr)
<< "Classification Result Classifications is NULL";
EXPECT_TRUE(classification_result->classifications->size >= 1)
<< "Classification Result Classifications Size is 0";
EXPECT_NE(classification_result->classifications->categories, nullptr)
<< "Classification Result Classifications Classes is NULL";
TfLiteClassificationResultDelete(classification_result);
}
TEST_F(CImageClassifierClassifyTest, FailsWithRoiOutsideImageBounds) {
CImageData image_data = LoadImage("burger-224.png");
TfLiteFrameBuffer frame_buffer = {.dimension.width = image_data.width,
.dimension.height = image_data.height,
.buffer = image_data.pixel_data,
.format = kRGB};
TfLiteBoundingBox bounding_box = {
.origin_x = 0, .origin_y = 0, .width = 250, .height = 250};
TfLiteClassificationResult* classification_result =
TfLiteImageClassifierClassifyWithRoi(image_classifier, &frame_buffer,
&bounding_box);
CImageDataFree(&image_data);
ASSERT_EQ(classification_result, nullptr)
<< "Classification Result is not NULL";
if (classification_result != nullptr)
TfLiteClassificationResultDelete(classification_result);
}
TEST(CImageClassifierWithUserDefinedOptionsClassifyTest,
SucceedsWithClassNameBlackList) {
char* blacklisted_label_name = "cheeseburger";
const char* model_path = JoinPath("./" /*test src dir*/, kTestDataDirectory,
kMobileNetQuantizedWithMetadata)
.data();
TfLiteImageClassifierOptions options = {0};
options.base_options.model_file.file_path = model_path;
char* class_name_blacklist[] = {blacklisted_label_name};
options.classification_options.class_name_blacklist.list =
class_name_blacklist;
options.classification_options.class_name_blacklist.length = 1;
TfLiteImageClassifier* image_classifier =
TfLiteImageClassifierFromOptions(&options);
ASSERT_NE(image_classifier, nullptr);
CImageData image_data = LoadImage("burger-224.png");
TfLiteFrameBuffer frame_buffer = {.dimension.width = image_data.width,
.dimension.height = image_data.height,
.buffer = image_data.pixel_data,
.format = kRGB};
TfLiteClassificationResult* classification_result =
TfLiteImageClassifierClassify(image_classifier, &frame_buffer);
CImageDataFree(&image_data);
ASSERT_NE(classification_result, nullptr) << "Classification Result is NULL";
EXPECT_TRUE(classification_result->size >= 1)
<< "Classification Result size is 0";
EXPECT_NE(classification_result->classifications, nullptr)
<< "Classification Result Classifications is NULL";
EXPECT_TRUE(classification_result->classifications->size >= 1)
<< "Classification Result Classifications Size is 0";
EXPECT_NE(classification_result->classifications->categories, nullptr)
<< "Classification Result Classifications Categories is NULL";
EXPECT_TRUE(
strcmp(classification_result->classifications->categories[0].label,
blacklisted_label_name) != 0)
<< "Black listed class is present in classification results ";
if (image_classifier) TfLiteImageClassifierDelete(image_classifier);
TfLiteClassificationResultDelete(classification_result);
}
TEST(CImageClassifierWithUserDefinedOptionsClassifyTest,
SucceedsWithClassNameWhiteList) {
char* whitelisted_label_name = "cheeseburger";
const char* model_path = JoinPath("./" /*test src dir*/, kTestDataDirectory,
kMobileNetQuantizedWithMetadata)
.data();
TfLiteImageClassifierOptions options = {0};
options.base_options.model_file.file_path = model_path;
char* class_name_whitelist[] = {"cheeseburger"};
options.classification_options.class_name_whitelist.list =
class_name_whitelist;
options.classification_options.class_name_whitelist.length = 1;
TfLiteImageClassifier* image_classifier =
TfLiteImageClassifierFromOptions(&options);
ASSERT_NE(image_classifier, nullptr);
CImageData image_data = LoadImage("burger-224.png");
TfLiteFrameBuffer frame_buffer = {.dimension.width = image_data.width,
.dimension.height = image_data.height,
.buffer = image_data.pixel_data,
.format = kRGB};
TfLiteClassificationResult* classification_result =
TfLiteImageClassifierClassify(image_classifier, &frame_buffer);
CImageDataFree(&image_data);
ASSERT_NE(classification_result, nullptr) << "Classification Result is NULL";
EXPECT_TRUE(classification_result->size >= 1)
<< "Classification Result size is 0";
EXPECT_NE(classification_result->classifications, nullptr)
<< "Classification Result Classifications is NULL";
EXPECT_TRUE(classification_result->classifications->size == 1)
<< "Classification Result Classifications Size is 0";
EXPECT_NE(classification_result->classifications->categories, nullptr)
<< "Classification Result Classifications Categories is NULL";
EXPECT_TRUE(
strcmp(classification_result->classifications->categories[0].label,
whitelisted_label_name) == 0)
<< "White listed class is not present in classification results.";
if (image_classifier) TfLiteImageClassifierDelete(image_classifier);
TfLiteClassificationResultDelete(classification_result);
}
} // namespace
} // namespace vision
} // namespace task
} // namespace tflite
<commit_msg>Updated tests to reflect new structure of TfLiteBaseOptions<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_lite_support/c/task/vision/image_classifier.h"
#include <string.h>
#include "tensorflow_lite_support/c/task/processor/classification_result.h"
#include "tensorflow_lite_support/c/task/vision/core/frame_buffer.h"
#include "tensorflow_lite_support/c/test/task/vision/utils/image_utils.h"
#include "tensorflow_lite_support/cc/port/gmock.h"
#include "tensorflow_lite_support/cc/port/gtest.h"
#include "tensorflow_lite_support/cc/test/test_utils.h"
namespace tflite {
namespace task {
namespace vision {
namespace {
using ::tflite::task::JoinPath;
constexpr char kTestDataDirectory[] =
"tensorflow_lite_support/cc/test/testdata/task/vision/";
// Quantized model.
constexpr char kMobileNetQuantizedWithMetadata[] =
"mobilenet_v1_0.25_224_quant.tflite";
CImageData LoadImage(const char* image_name) {
return CDecodeImageFromFile(
JoinPath("./" /*test src dir*/, kTestDataDirectory, image_name).data());
}
TEST(CImageClassifierFromOptionsTest, FailsWithMissingModelPath) {
TfLiteImageClassifierOptions options = {0};
TfLiteImageClassifier* image_classifier =
TfLiteImageClassifierFromOptions(&options);
ASSERT_EQ(image_classifier, nullptr);
}
TEST(CImageClassifierFromOptionsTest, SucceedsWithModelPath) {
// TfLiteImageClassifierOptions* options =
// TfLiteImageClassifierOptionsCreate();
const char* model_path = JoinPath("./" /*test src dir*/, kTestDataDirectory,
kMobileNetQuantizedWithMetadata)
.data();
TfLiteImageClassifierOptions options = {0};
options.base_options.model_file.file_path = model_path;
TfLiteImageClassifier* image_classifier =
TfLiteImageClassifierFromOptions(&options);
EXPECT_NE(image_classifier, nullptr);
TfLiteImageClassifierDelete(image_classifier);
}
TEST(CImageClassifierFromOptionsTest, SucceedsWithNumberOfThreads) {
const char* model_path = JoinPath("./" /*test src dir*/, kTestDataDirectory,
kMobileNetQuantizedWithMetadata)
.data();
TfLiteImageClassifierOptions options = {0};
options.base_options.model_file.file_path = model_path;
options.base_options.compute_settings.num_threads = 3;
TfLiteImageClassifier* image_classifier =
TfLiteImageClassifierFromOptions(&options);
EXPECT_NE(image_classifier, nullptr);
TfLiteImageClassifierDelete(image_classifier);
}
TEST(CImageClassifierFromOptionsTest,
FailsWithClassNameBlackListAndClassNameWhiteList) {
const char* model_path = JoinPath("./" /*test src dir*/, kTestDataDirectory,
kMobileNetQuantizedWithMetadata)
.data();
TfLiteImageClassifierOptions options = {0};
options.base_options.model_file.file_path = model_path;
char* class_name_blacklist[] = {"brambling"};
options.classification_options.class_name_blacklist.list =
class_name_blacklist;
options.classification_options.class_name_blacklist.length = 1;
char* class_name_whitelist[] = {"cheeseburger"};
options.classification_options.class_name_whitelist.list =
class_name_whitelist;
options.classification_options.class_name_whitelist.length = 1;
TfLiteImageClassifier* image_classifier =
TfLiteImageClassifierFromOptions(&options);
EXPECT_EQ(image_classifier, nullptr);
if (image_classifier) TfLiteImageClassifierDelete(image_classifier);
}
class CImageClassifierClassifyTest : public ::testing::Test {
protected:
void SetUp() override {
TfLiteImageClassifierOptions options = {0};
options.base_options.model_file.file_path =
JoinPath("./" /*test src dir*/, kTestDataDirectory,
kMobileNetQuantizedWithMetadata)
.data();
image_classifier = TfLiteImageClassifierFromOptions(&options);
ASSERT_NE(image_classifier, nullptr);
}
void TearDown() override { TfLiteImageClassifierDelete(image_classifier); }
TfLiteImageClassifier* image_classifier;
};
TEST_F(CImageClassifierClassifyTest, SucceedsWithImageData) {
CImageData image_data = LoadImage("burger-224.png");
TfLiteFrameBuffer frame_buffer = {.dimension.width = image_data.width,
.dimension.height = image_data.height,
.buffer = image_data.pixel_data,
.format = kRGB};
TfLiteClassificationResult* classification_result =
TfLiteImageClassifierClassify(image_classifier, &frame_buffer);
CImageDataFree(&image_data);
ASSERT_NE(classification_result, nullptr) << "Classification Result is NULL";
EXPECT_TRUE(classification_result->size >= 1)
<< "Classification Result size is 0";
EXPECT_NE(classification_result->classifications, nullptr)
<< "Classification Result Classifications is NULL";
EXPECT_TRUE(classification_result->classifications->size >= 1)
<< "Classification Result Classifications Size is 0";
EXPECT_NE(classification_result->classifications->categories, nullptr)
<< "Classification Result Classifications Classes is NULL";
TfLiteClassificationResultDelete(classification_result);
}
TEST_F(CImageClassifierClassifyTest, SucceedsWithRoiWithinImageBounds) {
CImageData image_data = LoadImage("burger-224.png");
TfLiteFrameBuffer frame_buffer = {.dimension.width = image_data.width,
.dimension.height = image_data.height,
.buffer = image_data.pixel_data,
.format = kRGB};
TfLiteBoundingBox bounding_box = {
.origin_x = 0, .origin_y = 0, .width = 100, .height = 100};
TfLiteClassificationResult* classification_result =
TfLiteImageClassifierClassifyWithRoi(image_classifier, &frame_buffer,
&bounding_box);
CImageDataFree(&image_data);
ASSERT_NE(classification_result, nullptr) << "Classification Result is NULL";
EXPECT_TRUE(classification_result->size >= 1)
<< "Classification Result size is 0";
EXPECT_NE(classification_result->classifications, nullptr)
<< "Classification Result Classifications is NULL";
EXPECT_TRUE(classification_result->classifications->size >= 1)
<< "Classification Result Classifications Size is 0";
EXPECT_NE(classification_result->classifications->categories, nullptr)
<< "Classification Result Classifications Classes is NULL";
TfLiteClassificationResultDelete(classification_result);
}
TEST_F(CImageClassifierClassifyTest, FailsWithRoiOutsideImageBounds) {
CImageData image_data = LoadImage("burger-224.png");
TfLiteFrameBuffer frame_buffer = {.dimension.width = image_data.width,
.dimension.height = image_data.height,
.buffer = image_data.pixel_data,
.format = kRGB};
TfLiteBoundingBox bounding_box = {
.origin_x = 0, .origin_y = 0, .width = 250, .height = 250};
TfLiteClassificationResult* classification_result =
TfLiteImageClassifierClassifyWithRoi(image_classifier, &frame_buffer,
&bounding_box);
CImageDataFree(&image_data);
ASSERT_EQ(classification_result, nullptr)
<< "Classification Result is not NULL";
if (classification_result != nullptr)
TfLiteClassificationResultDelete(classification_result);
}
TEST(CImageClassifierWithUserDefinedOptionsClassifyTest,
SucceedsWithClassNameBlackList) {
char* blacklisted_label_name = "cheeseburger";
const char* model_path = JoinPath("./" /*test src dir*/, kTestDataDirectory,
kMobileNetQuantizedWithMetadata)
.data();
TfLiteImageClassifierOptions options = {0};
options.base_options.model_file.file_path = model_path;
char* class_name_blacklist[] = {blacklisted_label_name};
options.classification_options.class_name_blacklist.list =
class_name_blacklist;
options.classification_options.class_name_blacklist.length = 1;
TfLiteImageClassifier* image_classifier =
TfLiteImageClassifierFromOptions(&options);
ASSERT_NE(image_classifier, nullptr);
CImageData image_data = LoadImage("burger-224.png");
TfLiteFrameBuffer frame_buffer = {.dimension.width = image_data.width,
.dimension.height = image_data.height,
.buffer = image_data.pixel_data,
.format = kRGB};
TfLiteClassificationResult* classification_result =
TfLiteImageClassifierClassify(image_classifier, &frame_buffer);
CImageDataFree(&image_data);
ASSERT_NE(classification_result, nullptr) << "Classification Result is NULL";
EXPECT_TRUE(classification_result->size >= 1)
<< "Classification Result size is 0";
EXPECT_NE(classification_result->classifications, nullptr)
<< "Classification Result Classifications is NULL";
EXPECT_TRUE(classification_result->classifications->size >= 1)
<< "Classification Result Classifications Size is 0";
EXPECT_NE(classification_result->classifications->categories, nullptr)
<< "Classification Result Classifications Categories is NULL";
EXPECT_TRUE(
strcmp(classification_result->classifications->categories[0].label,
blacklisted_label_name) != 0)
<< "Black listed class is present in classification results ";
if (image_classifier) TfLiteImageClassifierDelete(image_classifier);
TfLiteClassificationResultDelete(classification_result);
}
TEST(CImageClassifierWithUserDefinedOptionsClassifyTest,
SucceedsWithClassNameWhiteList) {
char* whitelisted_label_name = "cheeseburger";
const char* model_path = JoinPath("./" /*test src dir*/, kTestDataDirectory,
kMobileNetQuantizedWithMetadata)
.data();
TfLiteImageClassifierOptions options = {0};
options.base_options.model_file.file_path = model_path;
char* class_name_whitelist[] = {"cheeseburger"};
options.classification_options.class_name_whitelist.list =
class_name_whitelist;
options.classification_options.class_name_whitelist.length = 1;
TfLiteImageClassifier* image_classifier =
TfLiteImageClassifierFromOptions(&options);
ASSERT_NE(image_classifier, nullptr);
CImageData image_data = LoadImage("burger-224.png");
TfLiteFrameBuffer frame_buffer = {.dimension.width = image_data.width,
.dimension.height = image_data.height,
.buffer = image_data.pixel_data,
.format = kRGB};
TfLiteClassificationResult* classification_result =
TfLiteImageClassifierClassify(image_classifier, &frame_buffer);
CImageDataFree(&image_data);
ASSERT_NE(classification_result, nullptr) << "Classification Result is NULL";
EXPECT_TRUE(classification_result->size >= 1)
<< "Classification Result size is 0";
EXPECT_NE(classification_result->classifications, nullptr)
<< "Classification Result Classifications is NULL";
EXPECT_TRUE(classification_result->classifications->size == 1)
<< "Classification Result Classifications Size is 0";
EXPECT_NE(classification_result->classifications->categories, nullptr)
<< "Classification Result Classifications Categories is NULL";
EXPECT_TRUE(
strcmp(classification_result->classifications->categories[0].label,
whitelisted_label_name) == 0)
<< "White listed class is not present in classification results.";
if (image_classifier) TfLiteImageClassifierDelete(image_classifier);
TfLiteClassificationResultDelete(classification_result);
}
} // namespace
} // namespace vision
} // namespace task
} // namespace tflite
<|endoftext|>
|
<commit_before>#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <iterator>
#include <ctime>
#include <unordered_map>
#include <algorithm>
#include <cmath>
#include <chrono>
#include <iostream>
#include <fstream>
#include <string>
#include <iterator>
#include <unordered_map>
#include <unordered_set>
#include <set>
#include <algorithm>
#include <chrono>
#include <map>
#include <set>
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
using namespace std;
char randomNucleotide(){
switch (rand() % 4){
case 0:
return 'A';
case 1:
return 'C';
case 2:
return 'G';
case 3:
return 'T';
}
return 'A';
}
string randomSequence(const uint length){
string result(length, 'A');
for(uint i(0); i < length; ++i){
result[i] = randomNucleotide();
}
return result;
}
void insertion(double rate, string& result){
uint dice(rand() % 100);
if(dice < rate){
char newNucleotide(randomNucleotide());
result.push_back(newNucleotide);
insertion(rate, result);
}
}
string mutateSequence(const string& referenceSequence, uint maxMutRate=0, vector <double> ratioMutation={0.06,0.73,0.21}){
//~ string mutateSequence(const string& referenceSequence, uint maxMutRate=3, vector <double> ratioMutation={0.06,0.73,0.21}){
string result;
result.reserve(5 * referenceSequence.size());
for(uint i(0); i < referenceSequence.size(); ++i){
uint mutRate(maxMutRate);
//~ uint mutRate(rand() % maxMutRate);
double substitutionRate(mutRate * ratioMutation[0]);
double insertionRate(mutRate * ratioMutation[1]);
double deletionRate(mutRate * ratioMutation[2]);
uint dice(rand() % 100);
if (dice <substitutionRate ){
//SUBSTITUTION
char newNucleotide(randomNucleotide());
while(newNucleotide == referenceSequence[i]){
newNucleotide = randomNucleotide();
}
result.push_back(newNucleotide);
continue;
} else if(dice < deletionRate+substitutionRate){
//DELETION
uint dice2(rand() % 100);
while (dice2 < deletionRate+substitutionRate){ // deletions larger than 1
++i;
dice2 = rand() % 100;
}
continue;
} else if (dice < deletionRate + substitutionRate + insertionRate){
//INSERTION
char newNucleotide(randomNucleotide());
result.push_back(referenceSequence[i]);
result.push_back(newNucleotide);
//~ --i;
insertion(deletionRate + substitutionRate + insertionRate, result); // larger than 1 insertions
continue;
} else {
//NO ERROR
result.push_back(referenceSequence[i]);
}
}
return result;
}
//~ vector<string> generateAlternativeTranscriptReferences(uint transcriptNumber=3, uint totalExonNumber=15, uint exonNumber=6, uint sizeExons=100){
vector<vector<string>> generateAlternativeTranscriptReferences(ifstream& refFile, uint referenceNumber, uint transcriptNumber=3, uint totalExonNumber=14, uint exonNumber=10, uint sizeExons=200){
string sequence;
vector<vector<string>> result;
uint nbRef(0);
uint position(0);
string transcript;
unordered_set<uint> selectedExons;
while (not refFile.eof() and nbRef < referenceNumber){
getline(refFile, sequence);
getline(refFile, sequence);
uint lengthExons;
if (sequence.size()/sizeExons < totalExonNumber){
lengthExons = sequence.size()/(totalExonNumber+1);
} else {
lengthExons = sizeExons;
}
if (lengthExons > 30){
position = 0;
vector<string> exonList;
uint i(0);
while (i < totalExonNumber and position < sequence.size()){ // creation of exons from genomic sequence
string exon(sequence.substr(position, lengthExons));
exonList.push_back(exon);
position += lengthExons;
++i;
}
++nbRef;
vector<string> transcriptList;
for(uint i(0); i < transcriptNumber; ++i){
uint dice1(rand() % (totalExonNumber - 3));
uint transcriptExonNumber(dice1 + 3);
transcript = "";
selectedExons = {};
while(selectedExons.size() != transcriptExonNumber){
selectedExons.insert(rand() % exonList.size());
}
for(uint ii(0); ii < exonList.size(); ++ii){
if(selectedExons.count(ii) == 1){
transcript += exonList[ii];
}
}
transcriptList.push_back(transcript);
}
result.push_back(transcriptList);
}
}
return result;
}
unordered_map<uint, uint> geneExpressionChunks(uint referencesNumber, uint numberReads){
uint nbMidExpressed(referencesNumber * 0.6); // code 1
uint nbHighlyExpressed(referencesNumber * 0.1+1); // code 0
unordered_map<uint, uint> result;
cout << "high:" << nbHighlyExpressed << " medium:" << nbMidExpressed << " low:" << referencesNumber - nbMidExpressed - nbHighlyExpressed << endl;
unordered_set<uint> refs;
for (uint i(0); i < referencesNumber; ++i){
refs.insert(i);
}
uint i(0);
for (auto j (refs.begin()); j != refs.end(), i < nbHighlyExpressed;){
result.insert({*j, 0});
j = refs.erase(j);
++i;
}
i = 0;
for (auto j (refs.begin()); j != refs.end(), i < nbMidExpressed;){
result.insert({*j, 1});
j = refs.erase(j);
++i;
}
cout << "check size " << refs.size();
for (auto j (refs.begin()); j != refs.end(); ++j){
result.insert({*j, 2});
}
return result;
}
void generateReads(uint numberReads, ifstream& inRef, uint referencesNumber=1, const string& outFileName="simulatedReads.fa", const string& outRefFileName="RefFile"){
ofstream out(outFileName);
ofstream outRef(outRefFileName);
vector<vector<string>> referenceList(generateAlternativeTranscriptReferences(inRef, referencesNumber));
int highly(numberReads);
int regular(0);
int rare(0);
//~ int highly(numberReads*0.5);
//~ int regular(numberReads*0.4);
//~ int rare(numberReads - highly - regular);
unordered_map<uint, uint> geneExpression(geneExpressionChunks(referencesNumber, numberReads));
cout << "nb reads:" << numberReads << " nb rare reads:" << rare << " nb regular reads:"<< regular << " nb high reads:"<< highly << endl;
for(uint i(0);i < referenceList.size(); ++i){
string expr;
switch (geneExpression[i]){
case 0:
expr = "highExpression";
break;
case 1:
expr = "regularExpression";
break;
case 2:
expr = "shallowExpression";
break;
}
for(uint ii(0); ii<referenceList[i].size(); ++ii){
outRef << ">referenceNumber:" << i << " alternativeNumber" << ii << " " << expr <<endl;
outRef << referenceList[i][ii] << endl;
}
}
string refRead,realRead;
int hi(0), re(0), ra(0);
while (hi < highly or re < regular or ra < rare){
uint dice1(rand() % referencesNumber);
uint dice2(rand() % (referenceList[dice1].size() ));
int expr(geneExpression[dice1]);
if (expr == 0 and hi < highly){
++hi;
string expression = "highExpression";
refRead = referenceList[dice1][dice2];
realRead = mutateSequence(refRead);
out << ">referenceNumber:" << dice1 << " alternativeNumber:" << dice2 << " " << expression << endl;
out << realRead << endl;
}
if (expr == 1 and re < regular){
++re;
string expression = "regularExpression";
refRead = referenceList[dice1][dice2];
realRead = mutateSequence(refRead);
out << ">referenceNumber:" << dice1 << " alternativeNumber:" << dice2 << " " << expression << endl;
out << realRead << endl;
}
if (expr == 2 and ra < rare){
++ra;
string expression = "lowExpression";
refRead = referenceList[dice1][dice2];
realRead = mutateSequence(refRead);
out << ">referenceNumber:" << dice1 << " alternativeNumber:" << dice2 << " " << expression << endl;
out << realRead << endl;
}
}
}
int main(int argc, char ** argv){
if (argc > 1){
string refName = argv[1];
ifstream refFile(refName);
srand (time(NULL));
auto startChrono = chrono::system_clock::now();
generateReads(50, refFile);
auto end = chrono::system_clock::now(); auto waitedFor = end - startChrono;
cout << "Time in ms : " << (chrono::duration_cast<chrono::milliseconds>(waitedFor).count()) << endl;
}
return 0;
}
<commit_msg>fixed when there is only one reference<commit_after>#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <iterator>
#include <ctime>
#include <unordered_map>
#include <algorithm>
#include <cmath>
#include <chrono>
#include <iostream>
#include <fstream>
#include <string>
#include <iterator>
#include <unordered_map>
#include <unordered_set>
#include <set>
#include <algorithm>
#include <chrono>
#include <map>
#include <set>
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
using namespace std;
char randomNucleotide(){
switch (rand() % 4){
case 0:
return 'A';
case 1:
return 'C';
case 2:
return 'G';
case 3:
return 'T';
}
return 'A';
}
string randomSequence(const uint length){
string result(length, 'A');
for(uint i(0); i < length; ++i){
result[i] = randomNucleotide();
}
return result;
}
void insertion(double rate, string& result){
uint dice(rand() % 100);
if(dice < rate){
char newNucleotide(randomNucleotide());
result.push_back(newNucleotide);
insertion(rate, result);
}
}
string mutateSequence(const string& referenceSequence, uint maxMutRate=0, vector <double> ratioMutation={0.06,0.73,0.21}){
//~ string mutateSequence(const string& referenceSequence, uint maxMutRate=3, vector <double> ratioMutation={0.06,0.73,0.21}){
string result;
result.reserve(5 * referenceSequence.size());
for(uint i(0); i < referenceSequence.size(); ++i){
uint mutRate(maxMutRate);
//~ uint mutRate(rand() % maxMutRate);
double substitutionRate(mutRate * ratioMutation[0]);
double insertionRate(mutRate * ratioMutation[1]);
double deletionRate(mutRate * ratioMutation[2]);
uint dice(rand() % 100);
if (dice <substitutionRate ){
//SUBSTITUTION
char newNucleotide(randomNucleotide());
while(newNucleotide == referenceSequence[i]){
newNucleotide = randomNucleotide();
}
result.push_back(newNucleotide);
continue;
} else if(dice < deletionRate+substitutionRate){
//DELETION
uint dice2(rand() % 100);
while (dice2 < deletionRate+substitutionRate){ // deletions larger than 1
++i;
dice2 = rand() % 100;
}
continue;
} else if (dice < deletionRate + substitutionRate + insertionRate){
//INSERTION
char newNucleotide(randomNucleotide());
result.push_back(referenceSequence[i]);
result.push_back(newNucleotide);
//~ --i;
insertion(deletionRate + substitutionRate + insertionRate, result); // larger than 1 insertions
continue;
} else {
//NO ERROR
result.push_back(referenceSequence[i]);
}
}
return result;
}
//~ vector<string> generateAlternativeTranscriptReferences(uint transcriptNumber=3, uint totalExonNumber=15, uint exonNumber=6, uint sizeExons=100){
vector<vector<string>> generateAlternativeTranscriptReferences(ifstream& refFile, uint referenceNumber, uint transcriptNumber=3, uint totalExonNumber=14, uint exonNumber=10, uint sizeExons=200){
string sequence;
vector<vector<string>> result;
uint nbRef(0);
uint position(0);
string transcript;
unordered_set<uint> selectedExons;
while (not refFile.eof() and nbRef < referenceNumber){
getline(refFile, sequence);
getline(refFile, sequence);
uint lengthExons;
if (sequence.size()/sizeExons < totalExonNumber){
lengthExons = sequence.size()/(totalExonNumber+1);
} else {
lengthExons = sizeExons;
}
if (lengthExons > 30){
position = 0;
vector<string> exonList;
uint i(0);
while (i < totalExonNumber and position < sequence.size()){ // creation of exons from genomic sequence
string exon(sequence.substr(position, lengthExons));
exonList.push_back(exon);
position += lengthExons;
++i;
}
++nbRef;
vector<string> transcriptList;
for(uint i(0); i < transcriptNumber; ++i){
uint dice1(rand() % (totalExonNumber - 3));
uint transcriptExonNumber(dice1 + 3);
transcript = "";
selectedExons = {};
while(selectedExons.size() != transcriptExonNumber){
selectedExons.insert(rand() % exonList.size());
}
for(uint ii(0); ii < exonList.size(); ++ii){
if(selectedExons.count(ii) == 1){
transcript += exonList[ii];
}
}
transcriptList.push_back(transcript);
}
result.push_back(transcriptList);
}
}
return result;
}
unordered_map<uint, uint> geneExpressionChunks(uint referencesNumber, uint numberReads){
uint nbMidExpressed, nbHighlyExpressed;
if (referencesNumber > 1){
nbMidExpressed = referencesNumber * 0.6; // code 1
nbHighlyExpressed = referencesNumber * 0.1+1; // code 0
} else {
nbMidExpressed = 0;
nbHighlyExpressed = 1;
}
unordered_map<uint, uint> result;
cout << "high:" << nbHighlyExpressed << " medium:" << nbMidExpressed << " low:" << referencesNumber - nbMidExpressed - nbHighlyExpressed << endl;
unordered_set<uint> refs;
for (uint i(0); i < referencesNumber; ++i){
refs.insert(i);
}
uint i(0);
for (auto j (refs.begin()); j != refs.end(), i < nbHighlyExpressed;){
result.insert({*j, 0});
j = refs.erase(j);
++i;
}
//~ i = 0;
for (auto j (refs.begin()); j != refs.end(), i < nbMidExpressed + nbHighlyExpressed;){
result.insert({*j, 1});
j = refs.erase(j);
++i;
}
//~ cout << "check size " << refs.size();
for (auto j (refs.begin()); j != refs.end(); ++j){
result.insert({*j, 2});
}
return result;
}
void generateReads(uint numberReads, ifstream& inRef, uint referencesNumber=1, const string& outFileName="simulatedReads.fa", const string& outRefFileName="RefFile"){
ofstream out(outFileName);
ofstream outRef(outRefFileName);
vector<vector<string>> referenceList(generateAlternativeTranscriptReferences(inRef, referencesNumber));
int highly, regular, rare;
if (referencesNumber >1){
highly = numberReads*0.5;
regular = numberReads*0.4;
rare= numberReads - highly - regular;
} else {
highly = numberReads;
regular = 0;
rare = 0;
}
unordered_map<uint, uint> geneExpression(geneExpressionChunks(referencesNumber, numberReads));
cout << "nb reads:" << numberReads << " nb rare reads:" << rare << " nb regular reads:"<< regular << " nb high reads:"<< highly << endl;
for(uint i(0);i < referenceList.size(); ++i){
string expr;
switch (geneExpression[i]){
case 0:
expr = "highExpression";
break;
case 1:
expr = "regularExpression";
break;
case 2:
expr = "shallowExpression";
break;
}
for(uint ii(0); ii<referenceList[i].size(); ++ii){
outRef << ">referenceNumber:" << i << " alternativeNumber" << ii << " " << expr <<endl;
outRef << referenceList[i][ii] << endl;
}
}
string refRead,realRead;
int hi(0), re(0), ra(0);
while (hi < highly or re < regular or ra < rare){
uint dice1(rand() % referencesNumber);
uint dice2(rand() % (referenceList[dice1].size() ));
int expr(geneExpression[dice1]);
if (expr == 0 and hi < highly){
++hi;
string expression = "highExpression";
refRead = referenceList[dice1][dice2];
realRead = mutateSequence(refRead);
out << ">referenceNumber:" << dice1 << " alternativeNumber:" << dice2 << " " << expression << endl;
out << realRead << endl;
}
if (expr == 1 and re < regular){
++re;
string expression = "regularExpression";
refRead = referenceList[dice1][dice2];
realRead = mutateSequence(refRead);
out << ">referenceNumber:" << dice1 << " alternativeNumber:" << dice2 << " " << expression << endl;
out << realRead << endl;
}
if (expr == 2 and ra < rare){
++ra;
string expression = "lowExpression";
refRead = referenceList[dice1][dice2];
realRead = mutateSequence(refRead);
out << ">referenceNumber:" << dice1 << " alternativeNumber:" << dice2 << " " << expression << endl;
out << realRead << endl;
}
}
}
int main(int argc, char ** argv){
if (argc > 1){
string refName = argv[1];
ifstream refFile(refName);
srand (time(NULL));
auto startChrono = chrono::system_clock::now();
generateReads(100, refFile);
auto end = chrono::system_clock::now(); auto waitedFor = end - startChrono;
cout << "Time in ms : " << (chrono::duration_cast<chrono::milliseconds>(waitedFor).count()) << endl;
}
return 0;
}
<|endoftext|>
|
<commit_before>/***************************************************************************
* Copyright (c) 2019 WandererFan <wandererfan@gmail.com> *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* 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., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
#ifndef _PreComp_
#include <BRep_Builder.hxx>
#include <TopoDS_Compound.hxx>
# include <TopoDS_Shape.hxx>
# include <TopoDS_Edge.hxx>
# include <TopoDS.hxx>
# include <BRepAdaptor_Curve.hxx>
# include <Precision.hxx>
# include <QGraphicsScene>
# include <QGraphicsSceneMouseEvent>
# include <QGraphicsItem>
# include <QPainter>
# include <QPaintDevice>
# include <QSvgGenerator>
#include <QRegExp>
# include <math.h>
#endif
#include <App/Application.h>
#include <App/Material.h>
#include <Base/Console.h>
#include <Base/Exception.h>
#include <Base/Parameter.h>
#include <Base/UnitsApi.h>
#include <Gui/Command.h>
#include <Mod/Part/App/PartFeature.h>
#include <Mod/TechDraw/App/DrawRichAnno.h>
#include <Mod/TechDraw/App/DrawUtil.h>
#include <Mod/TechDraw/App/Geometry.h>
#include "Rez.h"
#include "ZVALUE.h"
#include "QGIArrow.h"
#include "ViewProviderRichAnno.h"
#include "MDIViewPage.h"
#include "DrawGuiUtil.h"
#include "QGVPage.h"
#include "QGIPrimPath.h"
#include "QGEPath.h"
#include "QGMText.h"
#include "QGIView.h"
#include "QGIRichAnno.h"
using namespace TechDraw;
using namespace TechDrawGui;
//**************************************************************
QGIRichAnno::QGIRichAnno(QGraphicsItem* myParent,
TechDraw::DrawRichAnno* anno)
{
setHandlesChildEvents(false);
setAcceptHoverEvents(false);
setFlag(QGraphicsItem::ItemIsSelectable, false); //we actually select & drag m_text
setFlag(QGraphicsItem::ItemIsMovable, false);
setFlag(QGraphicsItem::ItemSendsScenePositionChanges, true);
setFlag(QGraphicsItem::ItemSendsGeometryChanges,true);
if (myParent != nullptr) {
setParentItem(myParent);
}
setViewFeature(anno);
m_text = new QGMText();
m_text->setTextInteractionFlags(Qt::NoTextInteraction);
addToGroup(m_text);
m_text->setZValue(ZVALUE::DIMENSION);
setZValue(ZVALUE::DIMENSION);
QObject::connect(
m_text, SIGNAL(dragging()),
this , SLOT (textDragging())
);
QObject::connect(
m_text, SIGNAL(dragFinished()),
this , SLOT (textDragFinished())
);
QObject::connect(
m_text, SIGNAL(selected(bool)),
this , SLOT (select(bool)));
QObject::connect(
m_text, SIGNAL(hover(bool)),
this , SLOT (hover(bool)));
}
QVariant QGIRichAnno::itemChange(GraphicsItemChange change, const QVariant &value)
{
if (change == ItemSelectedHasChanged && scene()) {
//There's nothing special for QGIRA to do when selection changes!
} else if(change == ItemSceneChange && scene()) {
// nothing special!
}
return QGIView::itemChange(change, value);
}
void QGIRichAnno::textDragging(void)
{
// Base::Console().Message("QGIRA::textDragging()\n");
//this is the long way around. can we do it without crossing the App/Gui boundary?
//just update graphics until drag finished.
// auto lead( dynamic_cast<TechDraw::DrawRichAnno*>(getFeature()) );
// if( lead == nullptr ) {
// return;
// }
// double x = Rez::appX(m_text->x()),
// y = Rez::appX(m_text->y());
// Base::Vector3d tPos(x,-y,0.0);
// Gui::Command::openCommand("Drag Text");
// lead->TextPosition.setValue(tPos);
// Gui::Command::commitCommand();
// draw();
}
void QGIRichAnno::textDragFinished(void)
{
// Base::Console().Message("QGIRA::textDragFinished()\n");
auto anno( dynamic_cast<TechDraw::DrawRichAnno*>(getFeature()) );
if( anno == nullptr ) {
return;
}
double x = Rez::appX(m_text->x()),
y = - Rez::appX(m_text->y());
anno->X.setValue(x);
anno->Y.setValue(y);
}
void QGIRichAnno::select(bool state)
{
setSelected(state);
draw();
}
void QGIRichAnno::hover(bool state)
{
m_hasHover = state;
draw();
}
void QGIRichAnno::updateView(bool update)
{
// Base::Console().Message("QGIRA::updateView() - %s\n", getViewName());
Q_UNUSED(update);
auto annoFeat( dynamic_cast<TechDraw::DrawRichAnno*>(getViewObject()) );
if ( annoFeat == nullptr ) {
Base::Console().Log("QGIRA::updateView - no feature!\n");
return;
}
auto vp = static_cast<ViewProviderRichAnno*>(getViewProvider(getViewObject()));
if ( vp == nullptr ) {
return;
}
draw();
}
void QGIRichAnno::drawBorder()
{
////Leaders have no border!
// QGIView::drawBorder(); //good for debugging
}
void QGIRichAnno::draw()
{
// Base::Console().Log("QGITL::draw() - %s\n",getFeature()->getNameInDocument());
if (!isVisible()) {
Base::Console().Log("QGITL::draw - not visible\n");
return;
}
TechDraw::DrawRichAnno* annoFeat = getFeature();
if((!annoFeat) ) {
Base::Console().Log("QGITL::draw - no feature\n");
return;
}
auto vp = static_cast<ViewProviderRichAnno*>(getViewProvider(getFeature()));
if ( vp == nullptr ) {
Base::Console().Log("QGITL::draw - no viewprovider\n");
return;
}
QGIView::draw();
setTextItem();
}
void QGIRichAnno::setTextItem()
{
// Base::Console().Message("QGIRA::setTextItem() - %s\n",getViewName());
TechDraw::DrawRichAnno* annoFeat = getFeature();
auto vp = static_cast<ViewProviderRichAnno*>(getViewProvider(annoFeat));
if ( vp == nullptr ) {
Base::Console().Log("QGIRA::setTextItem - no ViewProvider\n");
return;
}
QFont font = m_text->font();
font.setPointSizeF(Rez::guiX(vp->Fontsize.getValue()));
font.setFamily(QString::fromLatin1(vp->Font.getValue()));
m_text->setFont(font);
//convert point font sizes to (Rez,mm) font sizes
QRegExp rxFontSize(QString::fromUtf8("font-size:([0-9]*)pt;"));
QString inHtml = QString::fromUtf8(annoFeat->AnnoText.getValue());
QString match;
double mmPerPoint = 0.353;
double sizeConvert = Rez::getRezFactor() * mmPerPoint;
int pos = 0;
QStringList findList;
QStringList replList;
while ((pos = rxFontSize.indexIn(inHtml, pos)) != -1) {
QString found = rxFontSize.cap(0);
findList << found;
QString qsOldSize = rxFontSize.cap(1);
QString repl = found;
double newSize = qsOldSize.toDouble();
newSize = newSize * sizeConvert;
QString qsNewSize = QString::number(newSize, 'f', 2);
repl.replace(qsOldSize,qsNewSize);
replList << repl;
pos += rxFontSize.matchedLength();
}
QString outHtml = inHtml;
int iRepl = 0;
//TODO: check list for duplicates?
for ( ; iRepl < findList.size(); iRepl++) {
outHtml = outHtml.replace(findList[iRepl], replList[iRepl]);
}
m_text->setHtml(outHtml);
m_text->setTextWidth(Rez::guiX(annoFeat->MaxWidth.getValue()));
m_text->showBox(annoFeat->ShowFrame.getValue());
double scale = getScale();
double x = Rez::guiX(annoFeat->X.getValue());
double y = Rez::guiX(annoFeat->Y.getValue());
Base::Vector3d textPos(x,y,0.0);
QPointF tPos(textPos.x * scale,- textPos.y * scale);
m_text->setPos(tPos);
}
//void QGIRichAnno::drawBorder()
//{
//////Leaders have no border!
//// QGIView::drawBorder(); //good for debugging
//}
TechDraw::DrawRichAnno* QGIRichAnno::getFeature(void)
{
TechDraw::DrawRichAnno* result =
static_cast<TechDraw::DrawRichAnno*>(getViewObject());
return result;
}
QRectF QGIRichAnno::boundingRect() const
{
QRectF rect = mapFromItem(m_text,m_text->boundingRect()).boundingRect();
return rect.adjusted(-10.,-10.,10.,10.);
}
QPainterPath QGIRichAnno::shape() const
{
return QGraphicsItemGroup::shape();
}
void QGIRichAnno::paint ( QPainter * painter, const QStyleOptionGraphicsItem * option, QWidget * widget) {
QStyleOptionGraphicsItem myOption(*option);
myOption.state &= ~QStyle::State_Selected;
// painter->drawRect(boundingRect()); //good for debugging
QGIView::paint (painter, &myOption, widget);
}
#include <Mod/TechDraw/Gui/moc_QGIRichAnno.cpp>
<commit_msg>Fix RichAnno positioning for Scale != 1<commit_after>/***************************************************************************
* Copyright (c) 2019 WandererFan <wandererfan@gmail.com> *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* 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., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
#ifndef _PreComp_
#include <BRep_Builder.hxx>
#include <TopoDS_Compound.hxx>
# include <TopoDS_Shape.hxx>
# include <TopoDS_Edge.hxx>
# include <TopoDS.hxx>
# include <BRepAdaptor_Curve.hxx>
# include <Precision.hxx>
# include <QGraphicsScene>
# include <QGraphicsSceneMouseEvent>
# include <QGraphicsItem>
# include <QPainter>
# include <QPaintDevice>
# include <QSvgGenerator>
#include <QRegExp>
# include <math.h>
#endif
#include <App/Application.h>
#include <App/Material.h>
#include <Base/Console.h>
#include <Base/Exception.h>
#include <Base/Parameter.h>
#include <Base/UnitsApi.h>
#include <Gui/Command.h>
#include <Mod/Part/App/PartFeature.h>
#include <Mod/TechDraw/App/DrawRichAnno.h>
#include <Mod/TechDraw/App/DrawUtil.h>
#include <Mod/TechDraw/App/Geometry.h>
#include "Rez.h"
#include "ZVALUE.h"
#include "QGIArrow.h"
#include "ViewProviderRichAnno.h"
#include "MDIViewPage.h"
#include "DrawGuiUtil.h"
#include "QGVPage.h"
#include "QGIPrimPath.h"
#include "QGEPath.h"
#include "QGMText.h"
#include "QGIView.h"
#include "QGIRichAnno.h"
using namespace TechDraw;
using namespace TechDrawGui;
//**************************************************************
QGIRichAnno::QGIRichAnno(QGraphicsItem* myParent,
TechDraw::DrawRichAnno* anno)
{
setHandlesChildEvents(false);
setAcceptHoverEvents(false);
setFlag(QGraphicsItem::ItemIsSelectable, false); //we actually select & drag m_text
setFlag(QGraphicsItem::ItemIsMovable, false);
setFlag(QGraphicsItem::ItemSendsScenePositionChanges, true);
setFlag(QGraphicsItem::ItemSendsGeometryChanges,true);
if (myParent != nullptr) {
setParentItem(myParent);
}
setViewFeature(anno);
m_text = new QGMText();
m_text->setTextInteractionFlags(Qt::NoTextInteraction);
addToGroup(m_text);
m_text->setZValue(ZVALUE::DIMENSION);
setZValue(ZVALUE::DIMENSION);
QObject::connect(
m_text, SIGNAL(dragging()),
this , SLOT (textDragging())
);
QObject::connect(
m_text, SIGNAL(dragFinished()),
this , SLOT (textDragFinished())
);
QObject::connect(
m_text, SIGNAL(selected(bool)),
this , SLOT (select(bool)));
QObject::connect(
m_text, SIGNAL(hover(bool)),
this , SLOT (hover(bool)));
}
QVariant QGIRichAnno::itemChange(GraphicsItemChange change, const QVariant &value)
{
if (change == ItemSelectedHasChanged && scene()) {
//There's nothing special for QGIRA to do when selection changes!
} else if(change == ItemSceneChange && scene()) {
// nothing special!
}
return QGIView::itemChange(change, value);
}
void QGIRichAnno::textDragging(void)
{
// Base::Console().Message("QGIRA::textDragging()\n");
//this is the long way around. can we do it without crossing the App/Gui boundary?
//just update graphics until drag finished.
// auto lead( dynamic_cast<TechDraw::DrawRichAnno*>(getFeature()) );
// if( lead == nullptr ) {
// return;
// }
// double x = Rez::appX(m_text->x()),
// y = Rez::appX(m_text->y());
// Base::Vector3d tPos(x,-y,0.0);
// Gui::Command::openCommand("Drag Text");
// lead->TextPosition.setValue(tPos);
// Gui::Command::commitCommand();
// draw();
}
void QGIRichAnno::textDragFinished(void)
{
// Base::Console().Message("QGIRA::textDragFinished()\n");
auto anno( dynamic_cast<TechDraw::DrawRichAnno*>(getFeature()) );
if( anno == nullptr ) {
return;
}
double x = Rez::appX(m_text->x()) / getScale();
double y = - Rez::appX(m_text->y()) / getScale();
anno->X.setValue(x);
anno->Y.setValue(y);
}
void QGIRichAnno::select(bool state)
{
setSelected(state);
draw();
}
void QGIRichAnno::hover(bool state)
{
m_hasHover = state;
draw();
}
void QGIRichAnno::updateView(bool update)
{
// Base::Console().Message("QGIRA::updateView() - %s\n", getViewName());
Q_UNUSED(update);
auto annoFeat( dynamic_cast<TechDraw::DrawRichAnno*>(getViewObject()) );
if ( annoFeat == nullptr ) {
Base::Console().Log("QGIRA::updateView - no feature!\n");
return;
}
auto vp = static_cast<ViewProviderRichAnno*>(getViewProvider(getViewObject()));
if ( vp == nullptr ) {
return;
}
draw();
}
void QGIRichAnno::drawBorder()
{
////Leaders have no border!
// QGIView::drawBorder(); //good for debugging
}
void QGIRichAnno::draw()
{
// Base::Console().Log("QGITL::draw() - %s\n",getFeature()->getNameInDocument());
if (!isVisible()) {
Base::Console().Log("QGITL::draw - not visible\n");
return;
}
TechDraw::DrawRichAnno* annoFeat = getFeature();
if((!annoFeat) ) {
Base::Console().Log("QGITL::draw - no feature\n");
return;
}
auto vp = static_cast<ViewProviderRichAnno*>(getViewProvider(getFeature()));
if ( vp == nullptr ) {
Base::Console().Log("QGITL::draw - no viewprovider\n");
return;
}
QGIView::draw();
setTextItem();
}
void QGIRichAnno::setTextItem()
{
// Base::Console().Message("QGIRA::setTextItem() - %s\n",getViewName());
TechDraw::DrawRichAnno* annoFeat = getFeature();
auto vp = static_cast<ViewProviderRichAnno*>(getViewProvider(annoFeat));
if ( vp == nullptr ) {
Base::Console().Log("QGIRA::setTextItem - no ViewProvider\n");
return;
}
QFont font = m_text->font();
font.setPointSizeF(Rez::guiX(vp->Fontsize.getValue()));
font.setFamily(QString::fromLatin1(vp->Font.getValue()));
m_text->setFont(font);
//convert point font sizes to (Rez,mm) font sizes
QRegExp rxFontSize(QString::fromUtf8("font-size:([0-9]*)pt;"));
QString inHtml = QString::fromUtf8(annoFeat->AnnoText.getValue());
QString match;
double mmPerPoint = 0.353;
double sizeConvert = Rez::getRezFactor() * mmPerPoint;
int pos = 0;
QStringList findList;
QStringList replList;
while ((pos = rxFontSize.indexIn(inHtml, pos)) != -1) {
QString found = rxFontSize.cap(0);
findList << found;
QString qsOldSize = rxFontSize.cap(1);
QString repl = found;
double newSize = qsOldSize.toDouble();
newSize = newSize * sizeConvert;
QString qsNewSize = QString::number(newSize, 'f', 2);
repl.replace(qsOldSize,qsNewSize);
replList << repl;
pos += rxFontSize.matchedLength();
}
QString outHtml = inHtml;
int iRepl = 0;
//TODO: check list for duplicates?
for ( ; iRepl < findList.size(); iRepl++) {
outHtml = outHtml.replace(findList[iRepl], replList[iRepl]);
}
m_text->setHtml(outHtml);
m_text->setTextWidth(Rez::guiX(annoFeat->MaxWidth.getValue()));
m_text->showBox(annoFeat->ShowFrame.getValue());
double scale = getScale();
double x = Rez::guiX(annoFeat->X.getValue());
double y = Rez::guiX(annoFeat->Y.getValue());
Base::Vector3d textPos(x,y,0.0);
QPointF tPos(textPos.x * scale,- textPos.y * scale);
m_text->setPos(tPos);
}
//void QGIRichAnno::drawBorder()
//{
//////Leaders have no border!
//// QGIView::drawBorder(); //good for debugging
//}
TechDraw::DrawRichAnno* QGIRichAnno::getFeature(void)
{
TechDraw::DrawRichAnno* result =
static_cast<TechDraw::DrawRichAnno*>(getViewObject());
return result;
}
QRectF QGIRichAnno::boundingRect() const
{
QRectF rect = mapFromItem(m_text,m_text->boundingRect()).boundingRect();
return rect.adjusted(-10.,-10.,10.,10.);
}
QPainterPath QGIRichAnno::shape() const
{
return QGraphicsItemGroup::shape();
}
void QGIRichAnno::paint ( QPainter * painter, const QStyleOptionGraphicsItem * option, QWidget * widget) {
QStyleOptionGraphicsItem myOption(*option);
myOption.state &= ~QStyle::State_Selected;
// painter->drawRect(boundingRect()); //good for debugging
QGIView::paint (painter, &myOption, widget);
}
#include <Mod/TechDraw/Gui/moc_QGIRichAnno.cpp>
<|endoftext|>
|
<commit_before>#include <SDL2/SDL.h>
#include <SDL2/SDL_ttf.h>
#include <fstream>
#include "../MasterHeader.h"
using namespace std;
//color pallette
static SDL_Color yellow{ 255,231,76,255 };
static SDL_Color red{ 255,89,100,255 };
static SDL_Color white{ 255,255,255,255 };
static SDL_Color blue{ 53,167,255,255 };
static SDL_Color green{ 56,230,140,255 };
//helper function for setting the color
void SetDrawColor(SDL_Renderer* render, const SDL_Color& color)
{
SDL_SetRenderDrawColor(render, color.r, color.g, color.b, color.a);
}
//temp global variables to retain state for gui elements that will be contained within a window
//e.g. sliders and toggles need to retain state
static float vertSliderValue = 0.0f;
//todo: find a way to remove TTF_Font* parameter pass to all GUI related functions that need to display text
//e.g. GUI::Label() and GUI::TextField()
bool WindowFunction(int ui_id,const SDL_Rect* relativePos,TTF_Font* font)
{
SDL_Rect buttonRect{ relativePos->x + 100 - 75 / 2,relativePos->y + 100 - 20 / 2,75,20 };
SDL_Color blue2{ 0,0,255,255 };
int buttonID = __LINE__;
if (GUI::Button(buttonID, &buttonRect, blue2, "OK", font))
{
printf("Window ID: %d\nButton ID: %d\n", ui_id, buttonID);
puts("Button pressed from window");
}
SDL_Rect vertSliderRect{relativePos->x + 10,relativePos->y + 10,20,150 };
int sliderID = __LINE__;
vertSliderValue = GUI::VerticalSlider(sliderID, &vertSliderRect, vertSliderValue, SDL_Color{ 255,0,0,255 });
//temp ~ if window doesn't have exclusive focus with the mice (i.e. the mouse is pressing on other gui elements in the window)
//the window should not be dragged
return GUI::ui_global_state.keyboardFocusID != ui_id;
}
static string mapName;
static string levelWidth;
static string levelHeight;
static string tileWidth;
static string tileHeight;
static bool windowToggled = false;
//prototyped-canned code temporary
bool NewMapWindow(int ui_id, const SDL_Rect* relativePos, TTF_Font* font)
{
int fontHeight = TTF_FontHeight(font);
int titleYOffset = 10;
int leftMargin = 10;
int labelID = __LINE__;
int titleWidth, titleHeight;
TTF_SizeText(font, "New Map", &titleWidth, &titleHeight);
//center title label along x-axis
SDL_Point titlePos{ relativePos->x + (relativePos->w / 2 - titleWidth / 2), relativePos->y + titleYOffset};
GUI::Label(labelID, &titlePos, font, "New Map", white);
//map filename field
int yOffset = (titlePos.y - relativePos->y) + titleHeight;
SDL_Point labelPos{ relativePos->x + leftMargin,relativePos->y + fontHeight + yOffset };
GUI::Label(__LINE__, &labelPos, font, "Map Filename: ", white);
int textFieldID = __LINE__;
int widthOffset;
TTF_SizeText(font, "Map Filename: ", &widthOffset, NULL);
SDL_Rect textFieldPos{ relativePos->x + widthOffset + leftMargin,labelPos.y - 2,relativePos->w * 0.5f,fontHeight + 4};
mapName = GUI::TextField(textFieldID, &textFieldPos, mapName, white, font);
//level dimensions field
yOffset = textFieldPos.y - relativePos->y + titleHeight;
int levelDimensionsFieldID = __LINE__;
SDL_Point label2Pos{ relativePos->x + leftMargin,relativePos->y + fontHeight + yOffset };
GUI::Label(levelDimensionsFieldID, &label2Pos, font, "Level WxH: ", white);
TTF_SizeText(font, "Level WxH: ", &widthOffset, NULL);
SDL_Rect textFieldPos2{ relativePos->x + leftMargin + widthOffset,label2Pos.y - 2,relativePos->w * 0.2f,fontHeight + 4 };
levelWidth = GUI::TextField(__LINE__, &textFieldPos2, levelWidth, white, font);
SDL_Point label3Pos{ relativePos->x + leftMargin + textFieldPos2.w + widthOffset,textFieldPos2.y };
GUI::Label(__LINE__, &label3Pos, font, " x ", white);
TTF_SizeText(font, " x ", &widthOffset, NULL);
SDL_Rect textFieldPos3{ label3Pos.x + widthOffset, textFieldPos2.y,relativePos->w * 0.2f,fontHeight + 4 };
levelHeight = GUI::TextField(__LINE__, &textFieldPos3, levelHeight, white, font);
//tile dimensions field
yOffset = textFieldPos3.y - relativePos->y + titleHeight;
SDL_Point label4Pos{ relativePos->x + leftMargin,relativePos->y + fontHeight + yOffset };
GUI::Label(__LINE__, &label4Pos, font, "Tile WxH: ", white);
TTF_SizeText(font, "Tile WxH: ", &widthOffset, NULL);
SDL_Rect textFieldPos4{ relativePos->x + leftMargin + widthOffset,label4Pos.y - 2,relativePos->w * 0.2f,fontHeight + 4 };
tileWidth = GUI::TextField(__LINE__, &textFieldPos4, tileWidth, white, font);
SDL_Point label5Pos{ relativePos->x + leftMargin + textFieldPos4.w + widthOffset,textFieldPos4.y };
GUI::Label(__LINE__, &label5Pos, font, " x ", white);
TTF_SizeText(font, " x ", &widthOffset, NULL);
SDL_Rect textFieldPos6{ label5Pos.x + widthOffset, textFieldPos4.y,relativePos->w * 0.2f,fontHeight + 4 };
tileHeight = GUI::TextField(__LINE__, &textFieldPos6, tileHeight, white, font);
int buttonWidth = relativePos->w * 0.2;
int buttonHeight = relativePos->h * 0.2;
SDL_Rect buttonRect{ relativePos->x + relativePos->w / 2 - buttonWidth / 2,relativePos->y + relativePos->h * 0.7,buttonWidth,buttonHeight};
if (GUI::Button(__LINE__, &buttonRect, red, "OK", font))
{
//temporary functionality as this can be dangerous to do since creating a file that already exists
//in the file system overrides that file!
puts("Close this window and save the new file created");
windowToggled = false;
string mainPath(SDL_GetBasePath());
mainPath += string("resources/");
string filePath(mainPath + mapName);
ofstream outputFile;
outputFile.open(filePath, ifstream::out);
if (outputFile.good())
{
//write map level name
outputFile << mapName << endl;
//write level dimensions
outputFile << levelWidth << " " << levelHeight << endl;
//write tile dimensions
outputFile << tileWidth << " " << tileHeight << endl;
outputFile.close();
}
else
{
printf("File is bad\n");
}
}
return false;
}
bool ToolbarPrototype(int ui_id, const SDL_Rect* relativePos, TTF_Font* font)
{
int newMapID = __LINE__;
int saveMapID = __LINE__;
int openMapID = __LINE__;
int loadTileSetID = __LINE__;
//construct rects for toolbar buttons
int buttonWidth = 800 / 4;
int buttonHeight = relativePos->h;
int margin = 2;
SDL_Rect buttonRects[4];
for (int i = 0;i < 4;++i)
{
buttonRects[i].w = buttonWidth;
buttonRects[i].h = buttonHeight;
buttonRects[i].x = (i * (buttonWidth + margin)) + relativePos->x;
buttonRects[i].y = relativePos->y;
}
if (GUI::Button(newMapID, &buttonRects[0], blue, "New Map", font))
{
windowToggled = !windowToggled;
}
GUI::Button(saveMapID, &buttonRects[1], green, "Save Map", font);
GUI::Button(openMapID, &buttonRects[2], blue, "Open Map", font);
GUI::Button(loadTileSetID, &buttonRects[3], green, "Load Tileset", font);
if (windowToggled)
{
int windowWidth = 300;
int windowHeight = 150;
SDL_Rect newMapRect{ 800 / 2 - windowWidth / 2,600 / 2 - windowHeight / 2,windowWidth,windowHeight };
GUI::Window(__LINE__, &newMapRect, font, NewMapWindow);
}
return false;
}
int main(int argc, char* argv[])
{
Core core;
SDL_Renderer* render = core.getRenderer();
string mainPath(SDL_GetBasePath());
mainPath += string("resources/");
//load in font
string fontPath = mainPath + string("SourceCodePro-Black.ttf");
int fontSize = 12;
TTF_Font* font = TTF_OpenFont(fontPath.c_str(), fontSize);
//load in sample tilesheet to use
ImageStore imageStore(render);
string imageFile("tiles-stones.png");
string imagePath(mainPath + imageFile);
Image* src = imageStore.Load(imageFile, imagePath);
int frameWidth = 64, frameHeight = 64;
SpriteSheet tileSheet(render, src, frameWidth, frameHeight);
//positions of each panel
SDL_Rect toolbarRect;
toolbarRect.x = 0;
toolbarRect.y = 0;
toolbarRect.w = SCREEN_WIDTH;
toolbarRect.h = 20;
SDL_Rect levelWindowRect{ 0,20,800,600 };
SDL_Rect sidePanelRect{ 800,20,400,600 };
SDL_Rect tilePreviewRect{ 825,50,150,150 };
SDL_Rect tileSetRect{ 805,250, 190, 360 };
SDL_Rect guiWindowRect{ 100,100,200,200 };
bool isToggled = true;
SDL_Rect toggleBounds{ 100,50, 25,25 };
float sliderValue2 = 0.0f;
SDL_Rect sliderRect2{ 400,50,20,200 };
int selectedButton = -1;
SDL_Rect newWindowRect;
newWindowRect.w = 800 * 0.3f;
newWindowRect.h = 600 * 0.35f;
newWindowRect.x = 400 - newWindowRect.w / 2;
newWindowRect.y = 300 - newWindowRect.h / 2;
//---------------- Game Loop ------------------//
GUI::Init(render);
GameLoop::InitTimer();
bool running = true;
while (running)
{
SDL_Event event;
while (SDL_PollEvent(&event))
{
GUI::ProcessEvent(&event);
switch (event.type)
{
case SDL_QUIT:
running = false;
break;
}
}
/* GAME LOGIC FUNCTIONS GO HERE*/
//Task : draw a mockup of where all the panels will go on the tile map editor window
SetDrawColor(render, blue);
SDL_RenderFillRect(render, &toolbarRect);
SetDrawColor(render, white);
SDL_RenderFillRect(render, &levelWindowRect);
SetDrawColor(render, red);
SDL_RenderFillRect(render, &sidePanelRect);
SetDrawColor(render, yellow);
SDL_RenderFillRect(render, &tilePreviewRect);
SetDrawColor(render, green);
SDL_RenderFillRect(render, &tileSetRect);
//GUI::Window(__LINE__, &toolbarRect, font, ToolbarPrototype);
//toolbar temp
vector<string> strings;
strings.push_back("New");
strings.push_back("Open");
strings.push_back("Save");
int buttonToSelect = GUI::Toolbar(__LINE__,&toolbarRect, -1, strings,font);
if (buttonToSelect != -1)
{
windowToggled = true;
selectedButton = buttonToSelect;
}
if (!windowToggled)
{
selectedButton = -1;
}
enum TOOLMAP_BUTTONS { NEW, OPEN, SAVE };
switch (selectedButton)
{
case NEW:
GUI::Window(__LINE__, &newWindowRect, font, NewMapWindow);
break;
case OPEN:
break;
case SAVE:
break;
}
SDL_RenderPresent(render);
SDL_SetRenderDrawColor(render, 0, 0, 0, 0);
SDL_RenderClear(render);
GameLoop::UpdateFPS();
GameLoop::CapFramerate(core.getTargetDeltaTime());
float currentTime = GameLoop::UpdateCurrentTime();
GameLoop::DisplayFPS(core.getWindow(), 500.0f);
GUI::SetTimeAndOldMousePos(currentTime);
}
TTF_CloseFont(font);
return 0;
}<commit_msg>Incorporate GridSelector into LevelEditor Prototype<commit_after>#include <SDL2/SDL.h>
#include <SDL2/SDL_ttf.h>
#include <fstream>
#include "../MasterHeader.h"
using namespace std;
//initialization and shutdown of SDL
static Core core;
static SDL_Renderer* render = core.getRenderer();
//image store
static ImageStore imageStore(render);
static SpriteSheet* tileSheet = nullptr;
//color pallette
static SDL_Color yellow{ 255,231,76,255 };
static SDL_Color red{ 255,89,100,255 };
static SDL_Color white{ 255,255,255,255 };
static SDL_Color blue{ 53,167,255,255 };
static SDL_Color green{ 56,230,140,255 };
//main path for saving/loading resources
static string mainPath(SDL_GetBasePath() + string("resources/"));
//helper function for setting the color
void SetDrawColor(SDL_Renderer* render, const SDL_Color& color)
{
SDL_SetRenderDrawColor(render, color.r, color.g, color.b, color.a);
}
//temp global variables to retain state for gui elements that will be contained within a window
//e.g. sliders and toggles need to retain state
static float vertSliderValue = 0.0f;
//todo: find a way to remove TTF_Font* parameter pass to all GUI related functions that need to display text
//e.g. GUI::Label() and GUI::TextField()
bool WindowFunction(int ui_id,const SDL_Rect* relativePos,TTF_Font* font)
{
SDL_Rect buttonRect{ relativePos->x + 100 - 75 / 2,relativePos->y + 100 - 20 / 2,75,20 };
SDL_Color blue2{ 0,0,255,255 };
int buttonID = __LINE__;
if (GUI::Button(buttonID, &buttonRect, blue2, "OK", font))
{
printf("Window ID: %d\nButton ID: %d\n", ui_id, buttonID);
puts("Button pressed from window");
}
SDL_Rect vertSliderRect{relativePos->x + 10,relativePos->y + 10,20,150 };
int sliderID = __LINE__;
vertSliderValue = GUI::VerticalSlider(sliderID, &vertSliderRect, vertSliderValue, SDL_Color{ 255,0,0,255 });
//temp ~ if window doesn't have exclusive focus with the mice (i.e. the mouse is pressing on other gui elements in the window)
//the window should not be dragged
return GUI::ui_global_state.keyboardFocusID != ui_id;
}
static string mapName;
static string levelWidth;
static string levelHeight;
static string tileWidth;
static string tileHeight;
static bool windowToggled = false;
//prototyped-canned code temporary
static bool NewMapWindow(int ui_id, const SDL_Rect* relativePos, TTF_Font* font)
{
int fontHeight = TTF_FontHeight(font);
int titleYOffset = 10;
int leftMargin = 10;
int labelID = __LINE__;
int titleWidth, titleHeight;
TTF_SizeText(font, "New Map", &titleWidth, &titleHeight);
//center title label along x-axis
SDL_Point titlePos{ relativePos->x + (relativePos->w / 2 - titleWidth / 2), relativePos->y + titleYOffset};
GUI::Label(labelID, &titlePos, font, "New Map", white);
//map filename field
int yOffset = (titlePos.y - relativePos->y) + titleHeight;
SDL_Point labelPos{ relativePos->x + leftMargin,relativePos->y + fontHeight + yOffset };
GUI::Label(__LINE__, &labelPos, font, "Map Filename: ", white);
int textFieldID = __LINE__;
int widthOffset;
TTF_SizeText(font, "Map Filename: ", &widthOffset, NULL);
SDL_Rect textFieldPos{ relativePos->x + widthOffset + leftMargin,labelPos.y - 2,relativePos->w * 0.5f,fontHeight + 4};
mapName = GUI::TextField(textFieldID, &textFieldPos, mapName, white, font);
//level dimensions field
yOffset = textFieldPos.y - relativePos->y + titleHeight;
int levelDimensionsFieldID = __LINE__;
SDL_Point label2Pos{ relativePos->x + leftMargin,relativePos->y + fontHeight + yOffset };
GUI::Label(levelDimensionsFieldID, &label2Pos, font, "Level WxH: ", white);
TTF_SizeText(font, "Level WxH: ", &widthOffset, NULL);
SDL_Rect textFieldPos2{ relativePos->x + leftMargin + widthOffset,label2Pos.y - 2,relativePos->w * 0.2f,fontHeight + 4 };
levelWidth = GUI::TextField(__LINE__, &textFieldPos2, levelWidth, white, font);
SDL_Point label3Pos{ relativePos->x + leftMargin + textFieldPos2.w + widthOffset,textFieldPos2.y };
GUI::Label(__LINE__, &label3Pos, font, " x ", white);
TTF_SizeText(font, " x ", &widthOffset, NULL);
SDL_Rect textFieldPos3{ label3Pos.x + widthOffset, textFieldPos2.y,relativePos->w * 0.2f,fontHeight + 4 };
levelHeight = GUI::TextField(__LINE__, &textFieldPos3, levelHeight, white, font);
//tile dimensions field
yOffset = textFieldPos3.y - relativePos->y + titleHeight;
SDL_Point label4Pos{ relativePos->x + leftMargin,relativePos->y + fontHeight + yOffset };
GUI::Label(__LINE__, &label4Pos, font, "Tile WxH: ", white);
TTF_SizeText(font, "Tile WxH: ", &widthOffset, NULL);
SDL_Rect textFieldPos4{ relativePos->x + leftMargin + widthOffset,label4Pos.y - 2,relativePos->w * 0.2f,fontHeight + 4 };
tileWidth = GUI::TextField(__LINE__, &textFieldPos4, tileWidth, white, font);
SDL_Point label5Pos{ relativePos->x + leftMargin + textFieldPos4.w + widthOffset,textFieldPos4.y };
GUI::Label(__LINE__, &label5Pos, font, " x ", white);
TTF_SizeText(font, " x ", &widthOffset, NULL);
SDL_Rect textFieldPos6{ label5Pos.x + widthOffset, textFieldPos4.y,relativePos->w * 0.2f,fontHeight + 4 };
tileHeight = GUI::TextField(__LINE__, &textFieldPos6, tileHeight, white, font);
int buttonWidth = relativePos->w * 0.2;
int buttonHeight = relativePos->h * 0.2;
SDL_Rect buttonRect{ relativePos->x + relativePos->w / 2 - buttonWidth / 2,relativePos->y + relativePos->h * 0.7,buttonWidth,buttonHeight};
if (GUI::Button(__LINE__, &buttonRect, red, "OK", font))
{
//temporary functionality as this can be dangerous to do since creating a file that already exists
//in the file system overrides that file!
puts("Close this window and save the new file created");
windowToggled = false;
string filePath(mainPath + mapName);
ofstream outputFile;
outputFile.open(filePath, ifstream::out);
if (outputFile.good())
{
//write map level name
outputFile << mapName << endl;
//write level dimensions
outputFile << levelWidth << " " << levelHeight << endl;
//write tile dimensions
outputFile << tileWidth << " " << tileHeight << endl;
outputFile.close();
}
else
{
printf("File is bad\n");
}
}
return false;
}
static string tileSetName;
static string sliceWidth;
static string sliceHeight;
static bool TileSetWindow(int ui_id, const SDL_Rect* relativePos, TTF_Font* font)
{
int fontHeight = TTF_FontHeight(font);
int titleYOffset = 10;
int leftMargin = 10;
int titleWidth, titleHeight;
TTF_SizeText(font, "Load Tile Set", &titleWidth, &titleHeight);
//center title label along x-axis
SDL_Point titlePos{ relativePos->x + (relativePos->w / 2 - titleWidth / 2), relativePos->y + titleYOffset };
GUI::Label(__LINE__, &titlePos, font, "Load Tile Set", white);
int yOffset = (titlePos.y - relativePos->y) + titleHeight;
SDL_Point labelPos{ relativePos->x + leftMargin,relativePos->y + fontHeight + yOffset };
GUI::Label(__LINE__, &labelPos, font, "Tile Set File: ", white);
int widthOffset;
TTF_SizeText(font, "Tile Set File: ", &widthOffset, NULL);
SDL_Rect textFieldPos{ relativePos->x + widthOffset,labelPos.y - 2,relativePos->w * 0.5f,fontHeight + 4 };
tileSetName = GUI::TextField(__LINE__, &textFieldPos, tileSetName, white, font);
yOffset = (labelPos.y - relativePos->y) + titleHeight;
SDL_Point labelPos2{relativePos->x + leftMargin,relativePos->y + fontHeight + yOffset};
GUI::Label(__LINE__, &labelPos2, font, "Slice Width: ", white);
TTF_SizeText(font, "Slice Width: ", &widthOffset, NULL);
SDL_Rect textFieldPos2{ relativePos->x + widthOffset,labelPos2.y - 2,relativePos->w * 0.25f,fontHeight + 4 };
sliceWidth = GUI::TextField(__LINE__, &textFieldPos2, sliceWidth, white, font);
yOffset = (labelPos2.y - relativePos->y) + titleHeight;
SDL_Point labelPos3{ relativePos->x + leftMargin,relativePos->y + fontHeight + yOffset };
GUI::Label(__LINE__, &labelPos3, font, "Slice Height: ", white);
TTF_SizeText(font, "Slice Height: ", &widthOffset, NULL);
SDL_Rect textFieldPos3{ relativePos->x + widthOffset,labelPos3.y - 2,relativePos->w * 0.25f,fontHeight + 4 };
sliceHeight = GUI::TextField(__LINE__, &textFieldPos3, sliceHeight, white, font);
int buttonWidth = relativePos->w * 0.2;
int buttonHeight = relativePos->h * 0.2;
SDL_Rect buttonRect{ relativePos->x + relativePos->w / 2 - buttonWidth / 2,relativePos->y + relativePos->h * 0.7,buttonWidth,buttonHeight };
if (GUI::Button(__LINE__, &buttonRect, red, "OK", font))
{
windowToggled = false;
if (tileSheet != nullptr)
{
delete tileSheet;
tileSheet = nullptr;
}
printf("Loading tileset: %s\n", tileSetName.c_str());
string filePath(mainPath + tileSetName);
//load tileset from file system
Image* img_src = imageStore.Load(tileSetName, filePath);
//create spritesheet from img_src
int frameWidth = stoi(sliceWidth);
int frameHeight = stoi(sliceHeight);
tileSheet = new SpriteSheet(render, img_src, frameWidth, frameHeight);
}
return false;
}
int main(int argc, char* argv[])
{
//load in font
string fontPath = mainPath + string("SourceCodePro-Black.ttf");
int fontSize = 12;
TTF_Font* font = TTF_OpenFont(fontPath.c_str(), fontSize);
//load in sample tilesheet to use
//ImageStore imageStore(render);
//string imageFile("tiles-stones.png");
//string imagePath(mainPath + imageFile);
//Image* src = imageStore.Load(imageFile, imagePath);
//int frameWidth = 64, frameHeight = 64;
//SpriteSheet tileSheet(render, src, frameWidth, frameHeight);
//positions of each panel
SDL_Rect toolbarRect;
toolbarRect.x = 0;
toolbarRect.y = 0;
toolbarRect.w = SCREEN_WIDTH;
toolbarRect.h = 20;
SDL_Rect levelWindowRect{ 0,20,800,600 };
SDL_Rect sidePanelRect{ 800,20,400,600 };
SDL_Rect tilePreviewRect{ 825,50,150,150 };
SDL_Rect tileSetRect{ 805,250, 190, 360 };
SDL_Rect guiWindowRect{ 100,100,200,200 };
bool isToggled = true;
SDL_Rect toggleBounds{ 100,50, 25,25 };
float sliderValue2 = 0.0f;
SDL_Rect sliderRect2{ 400,50,20,200 };
//windows
#define EDITOR_WIDTH 800
#define EDITOR_HEIGHT 600
int selectedButton = -1;
SDL_Rect newWindowRect;
newWindowRect.w = EDITOR_WIDTH * 0.3f;
newWindowRect.h = EDITOR_HEIGHT * 0.35f;
newWindowRect.x = EDITOR_WIDTH / 2 - newWindowRect.w / 2;
newWindowRect.y = EDITOR_HEIGHT / 2 - newWindowRect.h / 2;
SDL_Rect tileSetWindowRect;
tileSetWindowRect.w = EDITOR_WIDTH * 0.35f;
tileSetWindowRect.h = EDITOR_HEIGHT * 0.35f;
tileSetWindowRect.x = EDITOR_WIDTH / 2 - tileSetWindowRect.w / 2;
tileSetWindowRect.y = EDITOR_HEIGHT / 2 - tileSetWindowRect.h / 2;
//tile selector
int selectedTileIndex = -1;
//---------------- Game Loop ------------------//
GUI::Init(render);
GameLoop::InitTimer();
bool running = true;
while (running)
{
SDL_Event event;
while (SDL_PollEvent(&event))
{
GUI::ProcessEvent(&event);
switch (event.type)
{
case SDL_QUIT:
running = false;
break;
}
}
/* GAME LOGIC FUNCTIONS GO HERE*/
//Task : draw a mockup of where all the panels will go on the tile map editor window
SetDrawColor(render, blue);
SDL_RenderFillRect(render, &toolbarRect);
SetDrawColor(render, white);
SDL_RenderFillRect(render, &levelWindowRect);
SetDrawColor(render, red);
SDL_RenderFillRect(render, &sidePanelRect);
SetDrawColor(render, yellow);
SDL_RenderFillRect(render, &tilePreviewRect);
SetDrawColor(render, green);
SDL_RenderFillRect(render, &tileSetRect);
//toolbar temp
vector<string> strings;
strings.push_back("New");
strings.push_back("Open");
strings.push_back("Save");
strings.push_back("Load TileSet");
int buttonToSelect = GUI::Toolbar(__LINE__,&toolbarRect, -1, strings,font);
if (buttonToSelect != -1)
{
windowToggled = true;
selectedButton = buttonToSelect;
}
if (!windowToggled)
selectedButton = -1;
enum TOOLMAP_BUTTONS { NEW, OPEN, SAVE,LOAD_TILESET };
switch (selectedButton)
{
case NEW:
GUI::Window(__LINE__, &newWindowRect, font, NewMapWindow);
break;
case OPEN:
break;
case SAVE:
break;
case LOAD_TILESET:
GUI::Window(__LINE__, &tileSetWindowRect, font, TileSetWindow);
break;
}
//display tilesheet
if (tileSheet != nullptr)
{
int tileIndex = GUI::GridSelector(__LINE__, &tileSetRect, tileSheet, 4);
if (tileIndex != -1)
selectedTileIndex = tileIndex;
//draw tile selected preview
if(selectedTileIndex != -1)
SDL_RenderCopy(render, tileSheet->texture, tileSheet->GetFrame(selectedTileIndex), &tilePreviewRect);
}
SDL_RenderPresent(render);
SDL_SetRenderDrawColor(render, 0, 0, 0, 0);
SDL_RenderClear(render);
GameLoop::UpdateFPS();
GameLoop::CapFramerate(core.getTargetDeltaTime());
float currentTime = GameLoop::UpdateCurrentTime();
GameLoop::DisplayFPS(core.getWindow(), 500.0f);
GUI::SetTimeAndOldMousePos(currentTime);
}
TTF_CloseFont(font);
return 0;
}<|endoftext|>
|
<commit_before>#include <Grappa.hpp>
#include "MatchesDHT.hpp"
#include <Cache.hpp>
#include <AsyncParallelFor.hpp>
#include <string>
#include <fstream>
#include <vector>
DEFINE_uint64( numTuples, 32, "Number of tuples to generate" );
std::vector<std::string> &split(const std::string &s, char delim, std::vector<std::string> &elems) {
std::stringstream ss(s);
std::string item;
while(std::getline(ss, item, delim)) {
elems.push_back(item);
}
return elems;
}
std::vector<std::string> split(const std::string &s, char delim) {
std::vector<std::string> elems;
return split(s, delim, elems);
}
#define TUPLE_LEN 3
struct Tuple {
int64_t columns[TUPLE_LEN];
};
std::ostream& operator<<( std::ostream& o, const Tuple& t ) {
o << "T( ";
for (uint64_t i=0; i<TUPLE_LEN; i++) {
o << t.columns[i] << ", ";
}
o << ")";
}
typedef uint64_t Column;
uint64_t identity_hash( int64_t k ) {
return k;
}
// local portal to DHT
typedef MatchesDHT<int64_t, Tuple, identity_hash> DHT_type;
DHT_type joinTable;
// local RO copies
GlobalAddress<Tuple> local_tuples;
Column local_joinIndex1, local_joinIndex2, local_joinIndex3;
// TODO: incorporate the edge tuples generation (although only does triples)
void tuple_gen( Tuple * slot ) {
Tuple r;
for ( uint64_t i=0; i<TUPLE_LEN; i++ ) {
r.columns[i] = rand()%10;
}
*slot = r;
}
void scanAndHash( Tuple * t ) {
int64_t key = t->columns[local_joinIndex1];
Tuple val = *t;
joinTable.insert( key, val );
}
void secondJoin( GlobalAddress<Tuple> start, int64_t iters);
void firstJoin( Tuple * t ) {
int64_t key = t->columns[local_joinIndex2];
GlobalAddress<Tuple> results;
size_t num_results = joinTable.lookup( key, &results );
DVLOG(4) << "key " << *t << " finds (" << results << ", " << num_results << ")";
// inner for loop
async_parallel_for<Tuple, secondJoin, joinerSpawn<Tuple,secondJoin,ASYNC_PAR_FOR_DEFAULT>, ASYNC_PAR_FOR_DEFAULT >( results, num_results );
}
void printAll( GlobalAddress<Tuple> ts, size_t num ) {
Tuple storage[num];
Incoherent<Tuple>::RO c_ts( ts, num, storage );
for (uint64_t i=0; i<num; i++) {
VLOG(1) << c_ts[i];
}
}
void secondJoin( GlobalAddress<Tuple> start, int64_t iters ) {
Tuple tuples_s[iters];
Incoherent<Tuple>::RO tuples(start, iters, tuples_s);
for (int64_t i = 0; i < iters; i++) {
int64_t key = tuples[i].columns[local_joinIndex3];
GlobalAddress<Tuple> results;
size_t num_results = joinTable.lookup( key, &results );
VLOG(1) << "results key " << key << " (n=" << num_results;
printAll( results, num_results );
}
}
LOOP_FUNCTOR(join_f_init2, nid, ((GlobalAddress<Tuple>,tuples)) ((Column,ji1)) ((Column,ji2)) ((Column,ji3)) ) {
local_tuples = tuples;
local_joinIndex1 = ji1;
local_joinIndex2 = ji2;
local_joinIndex3 = ji3;
}
LOOP_FUNCTION(global_joiner_reset, nid) {
global_joiner.reset();
}
LOOP_FUNCTION(global_joiner_wait, nid) {
global_joiner.wait();
}
void join2( GlobalAddress<Tuple> tuples, Column ji1, Column ji2, Column ji3 ) {
// initialization
on_all_nodes( join_f_init2, tuples, ji1, ji2, ji3 );
// scan tuples and hash join col 1
VLOG(1) << "Scan tuples, creating index on subject";
forall_local<Tuple, scanAndHash>( tuples, FLAGS_numTuples );
printAll(tuples, FLAGS_numTuples);
// tell the DHT we are done with inserts
VLOG(1) << "DHT setting to RO";
DHT_type::set_RO_global( &joinTable );
// firstJoin contains unsynced nested parallel loops, so require
// this surrounding join
// FIXME: this synchronization is overly complicated
{ global_joiner_reset f; fork_join_custom(&f); }
VLOG(1) << "Starting 1st join";
forall_local<Tuple, firstJoin>( tuples, FLAGS_numTuples );
{ global_joiner_wait f; fork_join_custom(&f); }
}
void user_main( int * ignore ) {
GlobalAddress<Tuple> tuples = Grappa_typed_malloc<Tuple>( FLAGS_numTuples );
VLOG(1) << "Generating some data";
//forall_local<Tuple, tuple_gen>( tuples, FLAGS_numTuples );
std::ifstream testfile("testcase.txt");
std::string line;
int fin = 0;
if (testfile.is_open()) {
while (testfile.good() && (fin++)<FLAGS_numTuples) {
std::getline( testfile, line );
std::cout<< "L " << line << std::endl;
Incoherent<Tuple>::WO lr(tuples, 1);
std::vector<std::string> tokens = split( line, ' ' );
std::cout<< tokens[0] << " " << tokens[1] << std::endl;
(*lr).columns[0] = std::stoi(tokens[0]);
(*lr).columns[1] = 0;
(*lr).columns[2] = stoi(tokens[1]);
}
testfile.close();
}
Incoherent<Tuple>::WO r(tuples, 6);
DHT_type::init_global_DHT( &joinTable, 64 );
Column joinIndex1 = 0; // subject
Column joinIndex2 = 2; // object
Column joinIndex3 = 2; // object
// double join case (assuming one index to build)
join2( tuples, joinIndex1, joinIndex2, joinIndex3 );
}
/// Main() entry
int main (int argc, char** argv) {
Grappa_init( &argc, &argv );
Grappa_activate();
Grappa_run_user_main( &user_main, (int*)NULL );
CHECK( Grappa_done() == true ) << "Grappa not done before scheduler exit";
Grappa_finish( 0 );
}
// insert conflicts use java-style arraylist, enabling memcpy for next step of join
<commit_msg>changes for join performance collection<commit_after>#include <Grappa.hpp>
#include "MatchesDHT.hpp"
#include <Cache.hpp>
#include <AsyncParallelFor.hpp>
#include <string>
#include <fstream>
#include <vector>
DEFINE_uint64( numTuples, 32, "Number of tuples to generate" );
DEFINE_string( in, "", "Input file relation" );
DEFINE_bool( print, false, "Print results" );
std::vector<std::string> &split(const std::string &s, char delim, std::vector<std::string> &elems) {
std::stringstream ss(s);
std::string item;
while(std::getline(ss, item, delim)) {
elems.push_back(item);
}
return elems;
}
std::vector<std::string> split(const std::string &s, char delim) {
std::vector<std::string> elems;
return split(s, delim, elems);
}
#define TUPLE_LEN 2
struct Tuple {
int64_t columns[TUPLE_LEN];
};
std::ostream& operator<<( std::ostream& o, const Tuple& t ) {
o << "T( ";
for (uint64_t i=0; i<TUPLE_LEN; i++) {
o << t.columns[i] << ", ";
}
o << ")";
}
typedef uint64_t Column;
uint64_t identity_hash( int64_t k ) {
return k;
}
// local portal to DHT
typedef MatchesDHT<int64_t, Tuple, identity_hash> DHT_type;
DHT_type joinTable;
// local RO copies
GlobalAddress<Tuple> local_tuples;
Column local_joinIndex1, local_joinIndex2, local_joinIndex3;
// TODO: incorporate the edge tuples generation (although only does triples)
void tuple_gen( Tuple * slot ) {
Tuple r;
for ( uint64_t i=0; i<TUPLE_LEN; i++ ) {
r.columns[i] = rand()%FLAGS_numTuples;
}
*slot = r;
}
void scanAndHash( Tuple * t ) {
int64_t key = t->columns[local_joinIndex1];
Tuple val = *t;
VLOG(2) << "insert " << key << " | " << val;
joinTable.insert( key, val );
}
void secondJoin( GlobalAddress<Tuple> start, int64_t iters);
void firstJoin( Tuple * t ) {
int64_t key = t->columns[local_joinIndex2];
GlobalAddress<Tuple> results;
size_t num_results = joinTable.lookup( key, &results );
DVLOG(4) << "key " << *t << " finds (" << results << ", " << num_results << ")";
// inner for loop
async_parallel_for<Tuple, secondJoin, joinerSpawn<Tuple,secondJoin,ASYNC_PAR_FOR_DEFAULT>, ASYNC_PAR_FOR_DEFAULT >( results, num_results );
}
void printAll( GlobalAddress<Tuple> ts, size_t num ) {
Tuple storage[num];
Incoherent<Tuple>::RO c_ts( ts, num, storage );
for (uint64_t i=0; i<num; i++) {
VLOG(1) << c_ts[i];
}
}
void secondJoin( GlobalAddress<Tuple> start, int64_t iters ) {
Tuple tuples_s[iters];
Incoherent<Tuple>::RO tuples(start, iters, tuples_s);
for (int64_t i = 0; i < iters; i++) {
int64_t key = tuples[i].columns[local_joinIndex3];
GlobalAddress<Tuple> results;
size_t num_results = joinTable.lookup( key, &results );
if (FLAGS_print) {
VLOG(1) << "results key " << key << " (n=" << num_results;
printAll( results, num_results );
}
}
}
LOOP_FUNCTOR(join_f_init2, nid, ((GlobalAddress<Tuple>,tuples)) ((Column,ji1)) ((Column,ji2)) ((Column,ji3)) ) {
local_tuples = tuples;
local_joinIndex1 = ji1;
local_joinIndex2 = ji2;
local_joinIndex3 = ji3;
}
LOOP_FUNCTION(global_joiner_reset, nid) {
global_joiner.reset();
}
LOOP_FUNCTION(global_joiner_wait, nid) {
global_joiner.wait();
}
void join2( GlobalAddress<Tuple> tuples, Column ji1, Column ji2, Column ji3 ) {
// initialization
on_all_nodes( join_f_init2, tuples, ji1, ji2, ji3 );
// scan tuples and hash join col 1
VLOG(1) << "Scan tuples, creating index on subject";
double start = Grappa_walltime();
forall_local<Tuple, scanAndHash>( tuples, FLAGS_numTuples );
double end = Grappa_walltime();
VLOG(1) << "insertions: " << (end-start)/FLAGS_numTuples << " per sec";
#if DEBUG
printAll(tuples, FLAGS_numTuples);
#endif
// tell the DHT we are done with inserts
VLOG(1) << "DHT setting to RO";
DHT_type::set_RO_global( &joinTable );
// firstJoin contains unsynced nested parallel loops, so require
// this surrounding join
// FIXME: this synchronization is overly complicated
start = Grappa_walltime();
{ global_joiner_reset f; fork_join_custom(&f); }
VLOG(1) << "Starting 1st join";
forall_local<Tuple, firstJoin>( tuples, FLAGS_numTuples );
{ global_joiner_wait f; fork_join_custom(&f); }
end = Grappa_walltime();
VLOG(1) << "joins: " << (end-start) << " seconds";
}
void user_main( int * ignore ) {
GlobalAddress<Tuple> tuples = Grappa_typed_malloc<Tuple>( FLAGS_numTuples );
if ( FLAGS_in == "" ) {
VLOG(1) << "Generating some data";
forall_local<Tuple, tuple_gen>( tuples, FLAGS_numTuples );
} else {
VLOG(1) << "Reading data from " << FLAGS_in;
std::ifstream testfile(FLAGS_in);
std::string line;
int fin = 0;
if (testfile.is_open()) {
while (testfile.good() && fin<FLAGS_numTuples) {
std::getline( testfile, line );
Incoherent<Tuple>::WO lr(tuples+fin, 1);
std::vector<std::string> tokens = split( line, ' ' );
(*lr).columns[0] = std::stoi(tokens[0]);
(*lr).columns[1] = stoi(tokens[1]);
fin++;
}
testfile.close();
}
}
Incoherent<Tuple>::WO r(tuples, 6);
DHT_type::init_global_DHT( &joinTable, 64 );
Column joinIndex1 = 0; // subject
Column joinIndex2 = 1; // object
// double join case (assuming one index to build)
join2( tuples, joinIndex1, joinIndex2, joinIndex2 );
}
/// Main() entry
int main (int argc, char** argv) {
Grappa_init( &argc, &argv );
Grappa_activate();
Grappa_run_user_main( &user_main, (int*)NULL );
CHECK( Grappa_done() == true ) << "Grappa not done before scheduler exit";
Grappa_finish( 0 );
}
// insert conflicts use java-style arraylist, enabling memcpy for next step of join
<|endoftext|>
|
<commit_before>// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/component_updater/widevine_cdm_component_installer.h"
#include <string.h>
#include <vector>
#include "base/base_paths.h"
#include "base/bind.h"
#include "base/command_line.h"
#include "base/compiler_specific.h"
#include "base/file_util.h"
#include "base/files/file_path.h"
#include "base/logging.h"
#include "base/path_service.h"
#include "base/string_util.h"
#include "base/values.h"
#include "base/version.h"
#include "build/build_config.h"
#include "chrome/browser/component_updater/component_updater_service.h"
#include "chrome/browser/plugins/plugin_prefs.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/widevine_cdm_constants.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/plugin_service.h"
#include "content/public/common/pepper_plugin_info.h"
#include "third_party/widevine/cdm/widevine_cdm_common.h"
#include "widevine_cdm_version.h" // In SHARED_INTERMEDIATE_DIR.
using content::BrowserThread;
using content::PluginService;
namespace {
// TODO(xhwang): Move duplicate code among all component installer
// implementations to some common place.
// TODO(xhwang): This is the sha256sum of "Widevine CDM". Get the real extension
// ID for Widevine CDM.
// CRX hash. The extension id is: lgafhhiijclkaikclkjjofekikijofcm.
const uint8 kSha2Hash[] = {0xb6, 0x05, 0x77, 0x88, 0x92, 0xba, 0x08, 0xa2,
0xba, 0x99, 0xe5, 0x4a, 0x8a, 0x89, 0xe5, 0x2c,
0x88, 0x38, 0x2f, 0xf5, 0xa7, 0x7b, 0x93, 0xe7,
0xf1, 0x84, 0xcc, 0x37, 0xe1, 0xe5, 0x7a, 0xbd};
// File name of the Widevine CDM component manifest on different platforms.
const char kWidevineCdmManifestName[] = "WidevineCdm";
// Name of the Widevine CDM OS in the component manifest.
const char kWidevineCdmOperatingSystem[] =
#if defined(OS_MACOSX)
"mac";
#elif defined(OS_WIN)
"win";
#else // OS_LINUX, etc. TODO(viettrungluu): Separate out Chrome OS and Android?
"linux";
#endif
// Name of the Widevine CDM architecture in the component manifest.
const char kWidevineCdmArch[] =
#if defined(ARCH_CPU_X86)
"ia32";
#elif defined(ARCH_CPU_X86_64)
"x64";
#else // TODO(viettrungluu): Support an ARM check?
"???";
#endif
// If we don't have a Widevine CDM component, this is the version we claim.
const char kNullVersion[] = "0.0.0.0";
// The base directory on Windows looks like:
// <profile>\AppData\Local\Google\Chrome\User Data\WidevineCdm\.
base::FilePath GetWidevineCdmBaseDirectory() {
base::FilePath result;
PathService::Get(chrome::DIR_WIDEVINE_CDM, &result);
return result;
}
#if defined(WIDEVINE_CDM_AVAILABLE) && defined(WIDEVINE_CDM_IS_COMPONENT)
// Widevine CDM plugins have the version encoded in the path itself
// so we need to enumerate the directories to find the full path.
// On success, |latest_dir| returns something like:
// <profile>\AppData\Local\Google\Chrome\User Data\WidevineCdm\10.3.44.555\.
// |latest_version| returns the corresponding version number. |older_dirs|
// returns directories of all older versions.
bool GetWidevineCdmDirectory(base::FilePath* latest_dir,
base::Version* latest_version,
std::vector<base::FilePath>* older_dirs) {
base::FilePath base_dir = GetWidevineCdmBaseDirectory();
bool found = false;
file_util::FileEnumerator file_enumerator(
base_dir, false, file_util::FileEnumerator::DIRECTORIES);
for (base::FilePath path = file_enumerator.Next(); !path.value().empty();
path = file_enumerator.Next()) {
base::Version version(path.BaseName().MaybeAsASCII());
if (!version.IsValid())
continue;
if (found) {
if (version.CompareTo(*latest_version) > 0) {
older_dirs->push_back(*latest_dir);
*latest_dir = path;
*latest_version = version;
} else {
older_dirs->push_back(path);
}
} else {
*latest_dir = path;
*latest_version = version;
found = true;
}
}
return found;
}
#endif // defined(WIDEVINE_CDM_AVAILABLE) && defined(WIDEVINE_CDM_IS_COMPONENT)
bool MakeWidevineCdmPluginInfo(const base::FilePath& path,
const base::Version& version,
content::PepperPluginInfo* plugin_info) {
if (!version.IsValid() ||
version.components().size() !=
static_cast<size_t>(kWidevineCdmVersionNumComponents)) {
return false;
}
plugin_info->is_internal = false;
// Widevine CDM must run out of process.
plugin_info->is_out_of_process = true;
plugin_info->path = path;
plugin_info->name = kWidevineCdmPluginName;
plugin_info->description = kWidevineCdmPluginDescription;
plugin_info->version = version.GetString();
webkit::WebPluginMimeType widevine_cdm_mime_type(
kWidevineCdmPluginMimeType,
kWidevineCdmPluginExtension,
kWidevineCdmPluginMimeTypeDescription);
plugin_info->mime_types.push_back(widevine_cdm_mime_type);
plugin_info->permissions = kWidevineCdmPluginPermissions;
return true;
}
void RegisterWidevineCdmWithChrome(const base::FilePath& path,
const base::Version& version) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
content::PepperPluginInfo plugin_info;
if (!MakeWidevineCdmPluginInfo(path, version, &plugin_info))
return;
PluginService::GetInstance()->RegisterInternalPlugin(
plugin_info.ToWebPluginInfo(), true);
PluginService::GetInstance()->RefreshPlugins();
}
// Returns true if this browser is compatible with the given Widevine CDM
// manifest, with the version specified in the manifest in |version_out|.
bool CheckWidevineCdmManifest(const base::DictionaryValue& manifest,
base::Version* version_out) {
std::string name;
manifest.GetStringASCII("name", &name);
if (name != kWidevineCdmManifestName)
return false;
std::string proposed_version;
manifest.GetStringASCII("version", &proposed_version);
base::Version version(proposed_version.c_str());
if (!version.IsValid())
return false;
std::string os;
manifest.GetStringASCII("x-widevine-cdm-os", &os);
if (os != kWidevineCdmOperatingSystem)
return false;
std::string arch;
manifest.GetStringASCII("x-widevine-cdm-arch", &arch);
if (arch != kWidevineCdmArch)
return false;
*version_out = version;
return true;
}
} // namespace
class WidevineCdmComponentInstaller : public ComponentInstaller {
public:
explicit WidevineCdmComponentInstaller(const base::Version& version);
virtual ~WidevineCdmComponentInstaller() {}
virtual void OnUpdateError(int error) OVERRIDE;
virtual bool Install(const base::DictionaryValue& manifest,
const base::FilePath& unpack_path) OVERRIDE;
private:
base::Version current_version_;
};
WidevineCdmComponentInstaller::WidevineCdmComponentInstaller(
const base::Version& version)
: current_version_(version) {
DCHECK(version.IsValid());
}
void WidevineCdmComponentInstaller::OnUpdateError(int error) {
NOTREACHED() << "Widevine CDM update error: " << error;
}
bool WidevineCdmComponentInstaller::Install(
const base::DictionaryValue& manifest,
const base::FilePath& unpack_path) {
base::Version version;
if (!CheckWidevineCdmManifest(manifest, &version))
return false;
if (current_version_.CompareTo(version) > 0)
return false;
// TODO(xhwang): Also check if Widevine CDM binary exists.
if (!file_util::PathExists(unpack_path.Append(kWidevineCdmPluginFileName)))
return false;
// Passed the basic tests. Time to install it.
base::FilePath path =
GetWidevineCdmBaseDirectory().AppendASCII(version.GetString());
if (file_util::PathExists(path))
return false;
if (!file_util::Move(unpack_path, path))
return false;
// Installation is done. Now register the Widevine CDM with chrome.
current_version_ = version;
path = path.Append(kWidevineCdmPluginFileName);
BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
base::Bind(&RegisterWidevineCdmWithChrome, path, version));
return true;
}
namespace {
#if defined(WIDEVINE_CDM_AVAILABLE) && defined(WIDEVINE_CDM_IS_COMPONENT)
void FinishWidevineCdmUpdateRegistration(ComponentUpdateService* cus,
const base::Version& version) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
CrxComponent widevine_cdm;
widevine_cdm.name = "WidevineCdm";
widevine_cdm.installer = new WidevineCdmComponentInstaller(version);
widevine_cdm.version = version;
widevine_cdm.pk_hash.assign(kSha2Hash, &kSha2Hash[sizeof(kSha2Hash)]);
if (cus->RegisterComponent(widevine_cdm) != ComponentUpdateService::kOk) {
NOTREACHED() << "Widevine CDM component registration failed.";
return;
}
}
void StartWidevineCdmUpdateRegistration(ComponentUpdateService* cus) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
base::FilePath path = GetWidevineCdmBaseDirectory();
if (!file_util::PathExists(path) && !file_util::CreateDirectory(path)) {
NOTREACHED() << "Could not create Widevine CDM directory.";
return;
}
base::Version version(kNullVersion);
std::vector<base::FilePath> older_dirs;
if (GetWidevineCdmDirectory(&path, &version, &older_dirs)) {
path = path.Append(kWidevineCdmPluginFileName);
if (file_util::PathExists(path)) {
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
base::Bind(&RegisterWidevineCdmWithChrome, path, version));
} else {
version = base::Version(kNullVersion);
}
}
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
base::Bind(&FinishWidevineCdmUpdateRegistration, cus, version));
// Remove older versions of Widevine CDM.
for (std::vector<base::FilePath>::iterator iter = older_dirs.begin();
iter != older_dirs.end(); ++iter) {
file_util::Delete(*iter, true);
}
}
#endif // defined(WIDEVINE_CDM_AVAILABLE) && defined(WIDEVINE_CDM_IS_COMPONENT)
} // namespace
void RegisterWidevineCdmComponent(ComponentUpdateService* cus) {
#if defined(WIDEVINE_CDM_AVAILABLE) && defined(WIDEVINE_CDM_IS_COMPONENT)
BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
base::Bind(&StartWidevineCdmUpdateRegistration, cus));
#endif // defined(WIDEVINE_CDM_AVAILABLE) && defined(WIDEVINE_CDM_IS_COMPONENT)
}
<commit_msg>Update extension ID and CRX hash for Widevine CDM component.<commit_after>// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/component_updater/widevine_cdm_component_installer.h"
#include <string.h>
#include <vector>
#include "base/base_paths.h"
#include "base/bind.h"
#include "base/command_line.h"
#include "base/compiler_specific.h"
#include "base/file_util.h"
#include "base/files/file_path.h"
#include "base/logging.h"
#include "base/path_service.h"
#include "base/string_util.h"
#include "base/values.h"
#include "base/version.h"
#include "build/build_config.h"
#include "chrome/browser/component_updater/component_updater_service.h"
#include "chrome/browser/plugins/plugin_prefs.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/widevine_cdm_constants.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/plugin_service.h"
#include "content/public/common/pepper_plugin_info.h"
#include "third_party/widevine/cdm/widevine_cdm_common.h"
#include "widevine_cdm_version.h" // In SHARED_INTERMEDIATE_DIR.
using content::BrowserThread;
using content::PluginService;
namespace {
// TODO(xhwang): Move duplicate code among all component installer
// implementations to some common place.
// CRX hash. The extension id is: pdkaonnflpjcgibpgaanildgengnihcm.
const uint8 kSha2Hash[] = { 0xf3, 0xa0, 0xed, 0xd5, 0xbf, 0x92, 0x68, 0x1f,
0x60, 0x0d, 0x8b, 0x36, 0x4d, 0x6d, 0x87, 0x2c,
0x86, 0x61, 0x12, 0x20, 0x21, 0xf8, 0x94, 0xdd,
0xe1, 0xb6, 0xb4, 0x55, 0x34, 0x8c, 0x2e, 0x20 };
// File name of the Widevine CDM component manifest on different platforms.
const char kWidevineCdmManifestName[] = "WidevineCdm";
// Name of the Widevine CDM OS in the component manifest.
const char kWidevineCdmOperatingSystem[] =
#if defined(OS_MACOSX)
"mac";
#elif defined(OS_WIN)
"win";
#else // OS_LINUX, etc. TODO(viettrungluu): Separate out Chrome OS and Android?
"linux";
#endif
// Name of the Widevine CDM architecture in the component manifest.
const char kWidevineCdmArch[] =
#if defined(ARCH_CPU_X86)
"ia32";
#elif defined(ARCH_CPU_X86_64)
"x64";
#else // TODO(viettrungluu): Support an ARM check?
"???";
#endif
// If we don't have a Widevine CDM component, this is the version we claim.
const char kNullVersion[] = "0.0.0.0";
// The base directory on Windows looks like:
// <profile>\AppData\Local\Google\Chrome\User Data\WidevineCdm\.
base::FilePath GetWidevineCdmBaseDirectory() {
base::FilePath result;
PathService::Get(chrome::DIR_WIDEVINE_CDM, &result);
return result;
}
#if defined(WIDEVINE_CDM_AVAILABLE) && defined(WIDEVINE_CDM_IS_COMPONENT)
// Widevine CDM plugins have the version encoded in the path itself
// so we need to enumerate the directories to find the full path.
// On success, |latest_dir| returns something like:
// <profile>\AppData\Local\Google\Chrome\User Data\WidevineCdm\10.3.44.555\.
// |latest_version| returns the corresponding version number. |older_dirs|
// returns directories of all older versions.
bool GetWidevineCdmDirectory(base::FilePath* latest_dir,
base::Version* latest_version,
std::vector<base::FilePath>* older_dirs) {
base::FilePath base_dir = GetWidevineCdmBaseDirectory();
bool found = false;
file_util::FileEnumerator file_enumerator(
base_dir, false, file_util::FileEnumerator::DIRECTORIES);
for (base::FilePath path = file_enumerator.Next(); !path.value().empty();
path = file_enumerator.Next()) {
base::Version version(path.BaseName().MaybeAsASCII());
if (!version.IsValid())
continue;
if (found) {
if (version.CompareTo(*latest_version) > 0) {
older_dirs->push_back(*latest_dir);
*latest_dir = path;
*latest_version = version;
} else {
older_dirs->push_back(path);
}
} else {
*latest_dir = path;
*latest_version = version;
found = true;
}
}
return found;
}
#endif // defined(WIDEVINE_CDM_AVAILABLE) && defined(WIDEVINE_CDM_IS_COMPONENT)
bool MakeWidevineCdmPluginInfo(const base::FilePath& path,
const base::Version& version,
content::PepperPluginInfo* plugin_info) {
if (!version.IsValid() ||
version.components().size() !=
static_cast<size_t>(kWidevineCdmVersionNumComponents)) {
return false;
}
plugin_info->is_internal = false;
// Widevine CDM must run out of process.
plugin_info->is_out_of_process = true;
plugin_info->path = path;
plugin_info->name = kWidevineCdmPluginName;
plugin_info->description = kWidevineCdmPluginDescription;
plugin_info->version = version.GetString();
webkit::WebPluginMimeType widevine_cdm_mime_type(
kWidevineCdmPluginMimeType,
kWidevineCdmPluginExtension,
kWidevineCdmPluginMimeTypeDescription);
plugin_info->mime_types.push_back(widevine_cdm_mime_type);
plugin_info->permissions = kWidevineCdmPluginPermissions;
return true;
}
void RegisterWidevineCdmWithChrome(const base::FilePath& path,
const base::Version& version) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
content::PepperPluginInfo plugin_info;
if (!MakeWidevineCdmPluginInfo(path, version, &plugin_info))
return;
PluginService::GetInstance()->RegisterInternalPlugin(
plugin_info.ToWebPluginInfo(), true);
PluginService::GetInstance()->RefreshPlugins();
}
// Returns true if this browser is compatible with the given Widevine CDM
// manifest, with the version specified in the manifest in |version_out|.
bool CheckWidevineCdmManifest(const base::DictionaryValue& manifest,
base::Version* version_out) {
std::string name;
manifest.GetStringASCII("name", &name);
if (name != kWidevineCdmManifestName)
return false;
std::string proposed_version;
manifest.GetStringASCII("version", &proposed_version);
base::Version version(proposed_version.c_str());
if (!version.IsValid())
return false;
std::string os;
manifest.GetStringASCII("x-widevine-cdm-os", &os);
if (os != kWidevineCdmOperatingSystem)
return false;
std::string arch;
manifest.GetStringASCII("x-widevine-cdm-arch", &arch);
if (arch != kWidevineCdmArch)
return false;
*version_out = version;
return true;
}
} // namespace
class WidevineCdmComponentInstaller : public ComponentInstaller {
public:
explicit WidevineCdmComponentInstaller(const base::Version& version);
virtual ~WidevineCdmComponentInstaller() {}
virtual void OnUpdateError(int error) OVERRIDE;
virtual bool Install(const base::DictionaryValue& manifest,
const base::FilePath& unpack_path) OVERRIDE;
private:
base::Version current_version_;
};
WidevineCdmComponentInstaller::WidevineCdmComponentInstaller(
const base::Version& version)
: current_version_(version) {
DCHECK(version.IsValid());
}
void WidevineCdmComponentInstaller::OnUpdateError(int error) {
NOTREACHED() << "Widevine CDM update error: " << error;
}
bool WidevineCdmComponentInstaller::Install(
const base::DictionaryValue& manifest,
const base::FilePath& unpack_path) {
base::Version version;
if (!CheckWidevineCdmManifest(manifest, &version))
return false;
if (current_version_.CompareTo(version) > 0)
return false;
// TODO(xhwang): Also check if Widevine CDM binary exists.
if (!file_util::PathExists(unpack_path.Append(kWidevineCdmPluginFileName)))
return false;
// Passed the basic tests. Time to install it.
base::FilePath path =
GetWidevineCdmBaseDirectory().AppendASCII(version.GetString());
if (file_util::PathExists(path))
return false;
if (!file_util::Move(unpack_path, path))
return false;
// Installation is done. Now register the Widevine CDM with chrome.
current_version_ = version;
path = path.Append(kWidevineCdmPluginFileName);
BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
base::Bind(&RegisterWidevineCdmWithChrome, path, version));
return true;
}
namespace {
#if defined(WIDEVINE_CDM_AVAILABLE) && defined(WIDEVINE_CDM_IS_COMPONENT)
void FinishWidevineCdmUpdateRegistration(ComponentUpdateService* cus,
const base::Version& version) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
CrxComponent widevine_cdm;
widevine_cdm.name = "WidevineCdm";
widevine_cdm.installer = new WidevineCdmComponentInstaller(version);
widevine_cdm.version = version;
widevine_cdm.pk_hash.assign(kSha2Hash, &kSha2Hash[sizeof(kSha2Hash)]);
if (cus->RegisterComponent(widevine_cdm) != ComponentUpdateService::kOk) {
NOTREACHED() << "Widevine CDM component registration failed.";
return;
}
}
void StartWidevineCdmUpdateRegistration(ComponentUpdateService* cus) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
base::FilePath path = GetWidevineCdmBaseDirectory();
if (!file_util::PathExists(path) && !file_util::CreateDirectory(path)) {
NOTREACHED() << "Could not create Widevine CDM directory.";
return;
}
base::Version version(kNullVersion);
std::vector<base::FilePath> older_dirs;
if (GetWidevineCdmDirectory(&path, &version, &older_dirs)) {
path = path.Append(kWidevineCdmPluginFileName);
if (file_util::PathExists(path)) {
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
base::Bind(&RegisterWidevineCdmWithChrome, path, version));
} else {
version = base::Version(kNullVersion);
}
}
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
base::Bind(&FinishWidevineCdmUpdateRegistration, cus, version));
// Remove older versions of Widevine CDM.
for (std::vector<base::FilePath>::iterator iter = older_dirs.begin();
iter != older_dirs.end(); ++iter) {
file_util::Delete(*iter, true);
}
}
#endif // defined(WIDEVINE_CDM_AVAILABLE) && defined(WIDEVINE_CDM_IS_COMPONENT)
} // namespace
void RegisterWidevineCdmComponent(ComponentUpdateService* cus) {
#if defined(WIDEVINE_CDM_AVAILABLE) && defined(WIDEVINE_CDM_IS_COMPONENT)
BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
base::Bind(&StartWidevineCdmUpdateRegistration, cus));
#endif // defined(WIDEVINE_CDM_AVAILABLE) && defined(WIDEVINE_CDM_IS_COMPONENT)
}
<|endoftext|>
|
<commit_before>#include "CurlInitializer.h"
#include "ExceptionHelpers.h"
using namespace Instagram;
CurlInitializer::CurlInitializer(CurlApiPtr curlApi) : mCurlApi(curlApi)
{
if (mCurlApi->curl_global_init(CURL_GLOBAL_ALL))
Throw(CURL_GLOBAL_INIT_FAILED);
}
CurlInitializer::~CurlInitializer()
{
mCurlApi->curl_global_cleanup();
}
<commit_msg>Always instantiate CurlInitializer in static memory when cpp-instagram is linked.<commit_after>#include "CurlApiImpl.h"
#include "CurlInitializer.h"
#include "ExceptionHelpers.h"
using namespace Instagram;
namespace
{
// Initializing will be called during global variables initialization
CurlInitializer curlInitializer(CurlApiPtr(new CurlApiImpl));
}
CurlInitializer::CurlInitializer(CurlApiPtr curlApi) : mCurlApi(curlApi)
{
if (mCurlApi->curl_global_init(CURL_GLOBAL_ALL))
Throw(CURL_GLOBAL_INIT_FAILED);
}
CurlInitializer::~CurlInitializer()
{
mCurlApi->curl_global_cleanup();
}
<|endoftext|>
|
<commit_before>/***************************************************************************
* Copyright (c) 2004 Werner Mayer <wmayer[at]users.sourceforge.net> *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* 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., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
#ifndef _PreComp_
# include <QContextMenuEvent>
# include <QMenu>
#endif
#include <Base/Console.h>
#include <App/Application.h>
#include "PrefWidgets.h"
#include "FileDialog.h"
#include <cstring>
using Base::Console;
using namespace Gui;
/** Constructs a preference widget.
*/
PrefWidget::PrefWidget()
: WindowParameter("")
{
}
/**
* Destroys the widget and detaches it from its parameter group.
*/
PrefWidget::~PrefWidget()
{
if (getWindowParameter().isValid())
getWindowParameter()->Detach(this);
}
/** Sets the preference name to \a name. */
void PrefWidget::setEntryName( const QByteArray& name )
{
m_sPrefName = name;
}
/** Returns the widget's preference name. */
QByteArray PrefWidget::entryName() const
{
return m_sPrefName;
}
/** Sets the preference path to \a path. */
void PrefWidget::setParamGrpPath( const QByteArray& path )
{
#ifdef FC_DEBUG
if (getWindowParameter().isValid())
{
if ( paramGrpPath() != path )
Base::Console().Warning("Widget already attached\n");
}
#endif
if ( paramGrpPath() != path )
{
if ( setGroupName( path ) )
{
m_sPrefGrp = path;
assert(getWindowParameter().isValid());
getWindowParameter()->Attach(this);
}
}
}
/** Returns the widget's preferences path. */
QByteArray PrefWidget::paramGrpPath() const
{
return m_sPrefGrp;
}
/**
* This method is called if one ore more values in the parameter settings are changed
* where getParamGrp() points to.
* Note: This method is called for each parameter inside the parameter group. So
* you have to filter out the appropriate parameter with the name \a sReason.
* \a rCaller calls this method.
*/
void PrefWidget::OnChange(Base::Subject<const char*> &rCaller, const char * sReason)
{
if (std::strcmp(sReason,m_sPrefName) == 0)
restorePreferences();
}
/**
* Saves the current preferences of the widget.
* All preference widget attached to the same parameter group are notified.
*/
void PrefWidget::onSave()
{
savePreferences();
if (getWindowParameter().isValid())
getWindowParameter()->Notify( entryName() );
#ifdef FC_DEBUG
else
qFatal( "No parameter group specified!" );
#endif
}
/**
* Restores the preferences of the widget.
*/
void PrefWidget::onRestore()
{
#ifdef FC_DEBUG
if (getWindowParameter().isNull())
qWarning( "No parameter group specified!" );
#endif
restorePreferences();
}
// --------------------------------------------------------------------
PrefSpinBox::PrefSpinBox ( QWidget * parent )
: QSpinBox(parent), PrefWidget()
{
}
PrefSpinBox::~PrefSpinBox()
{
}
void PrefSpinBox::restorePreferences()
{
if ( getWindowParameter().isNull() )
{
Console().Warning("Cannot restore!\n");
return;
}
int nVal = getWindowParameter()->GetInt( entryName(), QSpinBox::value() );
setValue( nVal );
}
void PrefSpinBox::savePreferences()
{
if (getWindowParameter().isNull())
{
Console().Warning("Cannot save!\n");
return;
}
getWindowParameter()->SetInt( entryName() , (int)value() );
}
// --------------------------------------------------------------------
PrefDoubleSpinBox::PrefDoubleSpinBox ( QWidget * parent )
: QDoubleSpinBox(parent), PrefWidget()
{
}
PrefDoubleSpinBox::~PrefDoubleSpinBox()
{
}
void PrefDoubleSpinBox::restorePreferences()
{
if ( getWindowParameter().isNull() )
{
Console().Warning("Cannot restore!\n");
return;
}
double fVal = (double)getWindowParameter()->GetFloat( entryName() , value() );
setValue(fVal);
}
void PrefDoubleSpinBox::savePreferences()
{
if (getWindowParameter().isNull())
{
Console().Warning("Cannot save!\n");
return;
}
getWindowParameter()->SetFloat( entryName(), value() );
}
// --------------------------------------------------------------------
PrefLineEdit::PrefLineEdit ( QWidget * parent )
: QLineEdit(parent), PrefWidget()
{
}
PrefLineEdit::~PrefLineEdit()
{
}
void PrefLineEdit::restorePreferences()
{
if (getWindowParameter().isNull())
{
Console().Warning("Cannot restore!\n");
return;
}
QString text = this->text();
text = QString::fromUtf8(getWindowParameter()->GetASCII(entryName(), text.toUtf8()).c_str());
setText(text);
}
void PrefLineEdit::savePreferences()
{
if (getWindowParameter().isNull())
{
Console().Warning("Cannot save!\n");
return;
}
getWindowParameter()->SetASCII(entryName(), text().toUtf8());
}
// --------------------------------------------------------------------
PrefFileChooser::PrefFileChooser ( QWidget * parent )
: FileChooser(parent), PrefWidget()
{
}
PrefFileChooser::~PrefFileChooser()
{
}
void PrefFileChooser::restorePreferences()
{
if (getWindowParameter().isNull())
{
Console().Warning("Cannot restore!\n");
return;
}
QString txt = QString::fromUtf8(getWindowParameter()->GetASCII(entryName(), fileName().toUtf8()).c_str());
setFileName(txt);
}
void PrefFileChooser::savePreferences()
{
if (getWindowParameter().isNull())
{
Console().Warning("Cannot save!\n");
return;
}
getWindowParameter()->SetASCII(entryName(), fileName().toUtf8());
}
// --------------------------------------------------------------------
PrefComboBox::PrefComboBox ( QWidget * parent )
: QComboBox(parent), PrefWidget()
{
}
PrefComboBox::~PrefComboBox()
{
}
void PrefComboBox::restorePreferences()
{
if (getWindowParameter().isNull())
{
Console().Warning("Cannot restore!\n");
return;
}
int index = getWindowParameter()->GetInt(entryName(), currentIndex());
setCurrentIndex(index);
}
void PrefComboBox::savePreferences()
{
if (getWindowParameter().isNull())
{
Console().Warning("Cannot save!\n");
return;
}
getWindowParameter()->SetInt(entryName() , currentIndex());
}
// --------------------------------------------------------------------
PrefCheckBox::PrefCheckBox ( QWidget * parent )
: QCheckBox(parent), PrefWidget()
{
}
PrefCheckBox::~PrefCheckBox()
{
}
void PrefCheckBox::restorePreferences()
{
if (getWindowParameter().isNull())
{
Console().Warning("Cannot restore!\n");
return;
}
bool enable = getWindowParameter()->GetBool( entryName(), isChecked() );
setChecked(enable);
}
void PrefCheckBox::savePreferences()
{
if (getWindowParameter().isNull())
{
Console().Warning("Cannot save!\n");
return;
}
getWindowParameter()->SetBool( entryName(), isChecked() );
}
// --------------------------------------------------------------------
PrefRadioButton::PrefRadioButton ( QWidget * parent )
: QRadioButton(parent), PrefWidget()
{
}
PrefRadioButton::~PrefRadioButton()
{
}
void PrefRadioButton::restorePreferences()
{
if (getWindowParameter().isNull())
{
Console().Warning("Cannot restore!\n");
return;
}
bool enable = getWindowParameter()->GetBool( entryName(), isChecked() );
setChecked(enable);
}
void PrefRadioButton::savePreferences()
{
if (getWindowParameter().isNull())
{
Console().Warning("Cannot save!\n");
return;
}
getWindowParameter()->SetBool( entryName() , isChecked() );
}
// --------------------------------------------------------------------
PrefSlider::PrefSlider ( QWidget * parent )
: QSlider(parent), PrefWidget()
{
}
PrefSlider::~PrefSlider()
{
}
void PrefSlider::restorePreferences()
{
if ( getWindowParameter().isNull() )
{
Console().Warning("Cannot restore!\n");
return;
}
int nVal = getWindowParameter()->GetInt(entryName(), QSlider::value());
setValue(nVal);
}
void PrefSlider::savePreferences()
{
if (getWindowParameter().isNull())
{
Console().Warning("Cannot save!\n");
return;
}
getWindowParameter()->SetInt(entryName() , (int)value());
}
// --------------------------------------------------------------------
PrefColorButton::PrefColorButton ( QWidget * parent )
: ColorButton(parent), PrefWidget()
{
}
PrefColorButton::~PrefColorButton()
{
}
void PrefColorButton::restorePreferences()
{
if (getWindowParameter().isNull())
{
Console().Warning("Cannot restore!\n");
return;
}
QColor col = color();
unsigned long lcol = (col.red() << 24) | (col.green() << 16) | (col.blue() << 8);
lcol = getWindowParameter()->GetUnsigned( entryName(), lcol );
int r = (lcol >> 24)&0xff;
int g = (lcol >> 16)&0xff;
int b = (lcol >> 8)&0xff;
setColor(QColor(r,g,b));
}
void PrefColorButton::savePreferences()
{
if (getWindowParameter().isNull())
{
Console().Warning("Cannot save!\n");
return;
}
QColor col = color();
// (r,g,b,a) with a = 255 (opaque)
unsigned long lcol = (col.red() << 24) | (col.green() << 16) | (col.blue() << 8) | 255;
getWindowParameter()->SetUnsigned( entryName(), lcol );
}
// --------------------------------------------------------------------
namespace Gui {
class PrefQuantitySpinBoxPrivate
{
public:
PrefQuantitySpinBoxPrivate() :
historySize(5)
{
}
~PrefQuantitySpinBoxPrivate()
{
}
QByteArray prefGrp;
ParameterGrp::handle handle;
int historySize;
};
}
PrefQuantitySpinBox::PrefQuantitySpinBox (QWidget * parent)
: QuantitySpinBox(parent), d_ptr(new PrefQuantitySpinBoxPrivate())
{
}
PrefQuantitySpinBox::~PrefQuantitySpinBox()
{
}
void PrefQuantitySpinBox::contextMenuEvent(QContextMenuEvent *event)
{
Q_D(PrefQuantitySpinBox);
QMenu *editMenu = lineEdit()->createStandardContextMenu();
editMenu->setTitle(tr("Edit"));
QMenu* menu = new QMenu(QString::fromAscii("PrefQuantitySpinBox"));
menu->addMenu(editMenu);
menu->addSeparator();
// datastructure to remember actions for values
std::vector<QString> values;
std::vector<QAction *> actions;
// add the history menu part...
QStringList history = getHistory();
for (QStringList::const_iterator it = history.begin();it!= history.end();++it) {
actions.push_back(menu->addAction(*it));
values.push_back(*it);
}
// add the save value portion of the menu
menu->addSeparator();
QAction *saveValueAction = menu->addAction(tr("Save value"));
QAction *clearListAction = menu->addAction(tr("Clear list"));
clearListAction->setDisabled(history.empty());
// call the menu and wait until its back
QAction *userAction = menu->exec(event->globalPos());
// look what the user has choosen
if (userAction == saveValueAction) {
pushToHistory(this->text());
}
else if (userAction == clearListAction) {
d->handle->Clear();
}
else {
int i=0;
for (std::vector<QAction *>::const_iterator it = actions.begin();it!=actions.end();++it,i++) {
if (*it == userAction) {
lineEdit()->setText(values[i]);
break;
}
}
}
delete menu;
}
void PrefQuantitySpinBox::pushToHistory(const QString &valueq)
{
Q_D(PrefQuantitySpinBox);
QString val;
if (valueq.isEmpty())
val = this->text();
else
val = valueq;
std::string value(val.toUtf8());
if (d->handle.isValid()) {
// do nothing if the given value is on top of the history
std::string tHist = d->handle->GetASCII("Hist0");
if (tHist != val.toUtf8().constData()) {
for (int i = d->historySize -1 ; i>=0 ;i--) {
QByteArray hist1 = "Hist";
QByteArray hist0 = "Hist";
hist1.append(QByteArray::number(i+1));
hist0.append(QByteArray::number(i));
std::string tHist = d->handle->GetASCII(hist0);
if (!tHist.empty())
d->handle->SetASCII(hist1,tHist.c_str());
}
d->handle->SetASCII("Hist0",value.c_str());
}
}
}
QStringList PrefQuantitySpinBox::getHistory() const
{
Q_D(const PrefQuantitySpinBox);
QStringList res;
if (d->handle.isValid()) {
std::string tmp;
for (int i = 0 ; i< d->historySize ;i++) {
QByteArray hist = "Hist";
hist.append(QByteArray::number(i));
tmp = d->handle->GetASCII(hist);
if (!tmp.empty())
res.push_back(QString::fromUtf8(tmp.c_str()));
else
break; // end of history reached
}
}
return res;
}
void PrefQuantitySpinBox::setToLastUsedValue()
{
QStringList hist = getHistory();
if (!hist.empty())
lineEdit()->setText(hist[0]);
}
void PrefQuantitySpinBox::setParamGrpPath(const QByteArray& path)
{
Q_D(PrefQuantitySpinBox);
d->handle = App::GetApplication().GetParameterGroupByPath(path);
if (d->handle.isValid())
d->prefGrp = path;
}
QByteArray PrefQuantitySpinBox::paramGrpPath() const
{
Q_D(const PrefQuantitySpinBox);
if (d->handle.isValid())
return d->prefGrp;
return QByteArray();
}
int PrefQuantitySpinBox::historySize() const
{
Q_D(const PrefQuantitySpinBox);
return d->historySize;
}
void PrefQuantitySpinBox::setHistorySize(int i)
{
Q_D(PrefQuantitySpinBox);
d->historySize = i;
}
#include "moc_PrefWidgets.cpp"
<commit_msg>properly cast to unsigned before the shift<commit_after>/***************************************************************************
* Copyright (c) 2004 Werner Mayer <wmayer[at]users.sourceforge.net> *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* 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., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
#ifndef _PreComp_
# include <QContextMenuEvent>
# include <QMenu>
#endif
#include <Base/Console.h>
#include <App/Application.h>
#include "PrefWidgets.h"
#include "FileDialog.h"
#include <cstring>
using Base::Console;
using namespace Gui;
/** Constructs a preference widget.
*/
PrefWidget::PrefWidget()
: WindowParameter("")
{
}
/**
* Destroys the widget and detaches it from its parameter group.
*/
PrefWidget::~PrefWidget()
{
if (getWindowParameter().isValid())
getWindowParameter()->Detach(this);
}
/** Sets the preference name to \a name. */
void PrefWidget::setEntryName( const QByteArray& name )
{
m_sPrefName = name;
}
/** Returns the widget's preference name. */
QByteArray PrefWidget::entryName() const
{
return m_sPrefName;
}
/** Sets the preference path to \a path. */
void PrefWidget::setParamGrpPath( const QByteArray& path )
{
#ifdef FC_DEBUG
if (getWindowParameter().isValid())
{
if ( paramGrpPath() != path )
Base::Console().Warning("Widget already attached\n");
}
#endif
if ( paramGrpPath() != path )
{
if ( setGroupName( path ) )
{
m_sPrefGrp = path;
assert(getWindowParameter().isValid());
getWindowParameter()->Attach(this);
}
}
}
/** Returns the widget's preferences path. */
QByteArray PrefWidget::paramGrpPath() const
{
return m_sPrefGrp;
}
/**
* This method is called if one ore more values in the parameter settings are changed
* where getParamGrp() points to.
* Note: This method is called for each parameter inside the parameter group. So
* you have to filter out the appropriate parameter with the name \a sReason.
* \a rCaller calls this method.
*/
void PrefWidget::OnChange(Base::Subject<const char*> &rCaller, const char * sReason)
{
if (std::strcmp(sReason,m_sPrefName) == 0)
restorePreferences();
}
/**
* Saves the current preferences of the widget.
* All preference widget attached to the same parameter group are notified.
*/
void PrefWidget::onSave()
{
savePreferences();
if (getWindowParameter().isValid())
getWindowParameter()->Notify( entryName() );
#ifdef FC_DEBUG
else
qFatal( "No parameter group specified!" );
#endif
}
/**
* Restores the preferences of the widget.
*/
void PrefWidget::onRestore()
{
#ifdef FC_DEBUG
if (getWindowParameter().isNull())
qWarning( "No parameter group specified!" );
#endif
restorePreferences();
}
// --------------------------------------------------------------------
PrefSpinBox::PrefSpinBox ( QWidget * parent )
: QSpinBox(parent), PrefWidget()
{
}
PrefSpinBox::~PrefSpinBox()
{
}
void PrefSpinBox::restorePreferences()
{
if ( getWindowParameter().isNull() )
{
Console().Warning("Cannot restore!\n");
return;
}
int nVal = getWindowParameter()->GetInt( entryName(), QSpinBox::value() );
setValue( nVal );
}
void PrefSpinBox::savePreferences()
{
if (getWindowParameter().isNull())
{
Console().Warning("Cannot save!\n");
return;
}
getWindowParameter()->SetInt( entryName() , (int)value() );
}
// --------------------------------------------------------------------
PrefDoubleSpinBox::PrefDoubleSpinBox ( QWidget * parent )
: QDoubleSpinBox(parent), PrefWidget()
{
}
PrefDoubleSpinBox::~PrefDoubleSpinBox()
{
}
void PrefDoubleSpinBox::restorePreferences()
{
if ( getWindowParameter().isNull() )
{
Console().Warning("Cannot restore!\n");
return;
}
double fVal = (double)getWindowParameter()->GetFloat( entryName() , value() );
setValue(fVal);
}
void PrefDoubleSpinBox::savePreferences()
{
if (getWindowParameter().isNull())
{
Console().Warning("Cannot save!\n");
return;
}
getWindowParameter()->SetFloat( entryName(), value() );
}
// --------------------------------------------------------------------
PrefLineEdit::PrefLineEdit ( QWidget * parent )
: QLineEdit(parent), PrefWidget()
{
}
PrefLineEdit::~PrefLineEdit()
{
}
void PrefLineEdit::restorePreferences()
{
if (getWindowParameter().isNull())
{
Console().Warning("Cannot restore!\n");
return;
}
QString text = this->text();
text = QString::fromUtf8(getWindowParameter()->GetASCII(entryName(), text.toUtf8()).c_str());
setText(text);
}
void PrefLineEdit::savePreferences()
{
if (getWindowParameter().isNull())
{
Console().Warning("Cannot save!\n");
return;
}
getWindowParameter()->SetASCII(entryName(), text().toUtf8());
}
// --------------------------------------------------------------------
PrefFileChooser::PrefFileChooser ( QWidget * parent )
: FileChooser(parent), PrefWidget()
{
}
PrefFileChooser::~PrefFileChooser()
{
}
void PrefFileChooser::restorePreferences()
{
if (getWindowParameter().isNull())
{
Console().Warning("Cannot restore!\n");
return;
}
QString txt = QString::fromUtf8(getWindowParameter()->GetASCII(entryName(), fileName().toUtf8()).c_str());
setFileName(txt);
}
void PrefFileChooser::savePreferences()
{
if (getWindowParameter().isNull())
{
Console().Warning("Cannot save!\n");
return;
}
getWindowParameter()->SetASCII(entryName(), fileName().toUtf8());
}
// --------------------------------------------------------------------
PrefComboBox::PrefComboBox ( QWidget * parent )
: QComboBox(parent), PrefWidget()
{
}
PrefComboBox::~PrefComboBox()
{
}
void PrefComboBox::restorePreferences()
{
if (getWindowParameter().isNull())
{
Console().Warning("Cannot restore!\n");
return;
}
int index = getWindowParameter()->GetInt(entryName(), currentIndex());
setCurrentIndex(index);
}
void PrefComboBox::savePreferences()
{
if (getWindowParameter().isNull())
{
Console().Warning("Cannot save!\n");
return;
}
getWindowParameter()->SetInt(entryName() , currentIndex());
}
// --------------------------------------------------------------------
PrefCheckBox::PrefCheckBox ( QWidget * parent )
: QCheckBox(parent), PrefWidget()
{
}
PrefCheckBox::~PrefCheckBox()
{
}
void PrefCheckBox::restorePreferences()
{
if (getWindowParameter().isNull())
{
Console().Warning("Cannot restore!\n");
return;
}
bool enable = getWindowParameter()->GetBool( entryName(), isChecked() );
setChecked(enable);
}
void PrefCheckBox::savePreferences()
{
if (getWindowParameter().isNull())
{
Console().Warning("Cannot save!\n");
return;
}
getWindowParameter()->SetBool( entryName(), isChecked() );
}
// --------------------------------------------------------------------
PrefRadioButton::PrefRadioButton ( QWidget * parent )
: QRadioButton(parent), PrefWidget()
{
}
PrefRadioButton::~PrefRadioButton()
{
}
void PrefRadioButton::restorePreferences()
{
if (getWindowParameter().isNull())
{
Console().Warning("Cannot restore!\n");
return;
}
bool enable = getWindowParameter()->GetBool( entryName(), isChecked() );
setChecked(enable);
}
void PrefRadioButton::savePreferences()
{
if (getWindowParameter().isNull())
{
Console().Warning("Cannot save!\n");
return;
}
getWindowParameter()->SetBool( entryName() , isChecked() );
}
// --------------------------------------------------------------------
PrefSlider::PrefSlider ( QWidget * parent )
: QSlider(parent), PrefWidget()
{
}
PrefSlider::~PrefSlider()
{
}
void PrefSlider::restorePreferences()
{
if ( getWindowParameter().isNull() )
{
Console().Warning("Cannot restore!\n");
return;
}
int nVal = getWindowParameter()->GetInt(entryName(), QSlider::value());
setValue(nVal);
}
void PrefSlider::savePreferences()
{
if (getWindowParameter().isNull())
{
Console().Warning("Cannot save!\n");
return;
}
getWindowParameter()->SetInt(entryName() , (int)value());
}
// --------------------------------------------------------------------
PrefColorButton::PrefColorButton ( QWidget * parent )
: ColorButton(parent), PrefWidget()
{
}
PrefColorButton::~PrefColorButton()
{
}
void PrefColorButton::restorePreferences()
{
if (getWindowParameter().isNull())
{
Console().Warning("Cannot restore!\n");
return;
}
QColor col = color();
unsigned long lcol = (col.red() << 24) | (col.green() << 16) | (col.blue() << 8);
lcol = getWindowParameter()->GetUnsigned( entryName(), lcol );
int r = (lcol >> 24)&0xff;
int g = (lcol >> 16)&0xff;
int b = (lcol >> 8)&0xff;
setColor(QColor(r,g,b));
}
void PrefColorButton::savePreferences()
{
if (getWindowParameter().isNull())
{
Console().Warning("Cannot save!\n");
return;
}
QColor col = color();
// (r,g,b,a) with a = 255 (opaque)
unsigned long lcol = (static_cast<unsigned long> (col.red()) << 24)
| (static_cast<unsigned long> (col.green()) << 16)
| (static_cast<unsigned long> (col.blue()) << 8) | 255;
getWindowParameter()->SetUnsigned( entryName(), lcol );
}
// --------------------------------------------------------------------
namespace Gui {
class PrefQuantitySpinBoxPrivate
{
public:
PrefQuantitySpinBoxPrivate() :
historySize(5)
{
}
~PrefQuantitySpinBoxPrivate()
{
}
QByteArray prefGrp;
ParameterGrp::handle handle;
int historySize;
};
}
PrefQuantitySpinBox::PrefQuantitySpinBox (QWidget * parent)
: QuantitySpinBox(parent), d_ptr(new PrefQuantitySpinBoxPrivate())
{
}
PrefQuantitySpinBox::~PrefQuantitySpinBox()
{
}
void PrefQuantitySpinBox::contextMenuEvent(QContextMenuEvent *event)
{
Q_D(PrefQuantitySpinBox);
QMenu *editMenu = lineEdit()->createStandardContextMenu();
editMenu->setTitle(tr("Edit"));
QMenu* menu = new QMenu(QString::fromAscii("PrefQuantitySpinBox"));
menu->addMenu(editMenu);
menu->addSeparator();
// datastructure to remember actions for values
std::vector<QString> values;
std::vector<QAction *> actions;
// add the history menu part...
QStringList history = getHistory();
for (QStringList::const_iterator it = history.begin();it!= history.end();++it) {
actions.push_back(menu->addAction(*it));
values.push_back(*it);
}
// add the save value portion of the menu
menu->addSeparator();
QAction *saveValueAction = menu->addAction(tr("Save value"));
QAction *clearListAction = menu->addAction(tr("Clear list"));
clearListAction->setDisabled(history.empty());
// call the menu and wait until its back
QAction *userAction = menu->exec(event->globalPos());
// look what the user has choosen
if (userAction == saveValueAction) {
pushToHistory(this->text());
}
else if (userAction == clearListAction) {
d->handle->Clear();
}
else {
int i=0;
for (std::vector<QAction *>::const_iterator it = actions.begin();it!=actions.end();++it,i++) {
if (*it == userAction) {
lineEdit()->setText(values[i]);
break;
}
}
}
delete menu;
}
void PrefQuantitySpinBox::pushToHistory(const QString &valueq)
{
Q_D(PrefQuantitySpinBox);
QString val;
if (valueq.isEmpty())
val = this->text();
else
val = valueq;
std::string value(val.toUtf8());
if (d->handle.isValid()) {
// do nothing if the given value is on top of the history
std::string tHist = d->handle->GetASCII("Hist0");
if (tHist != val.toUtf8().constData()) {
for (int i = d->historySize -1 ; i>=0 ;i--) {
QByteArray hist1 = "Hist";
QByteArray hist0 = "Hist";
hist1.append(QByteArray::number(i+1));
hist0.append(QByteArray::number(i));
std::string tHist = d->handle->GetASCII(hist0);
if (!tHist.empty())
d->handle->SetASCII(hist1,tHist.c_str());
}
d->handle->SetASCII("Hist0",value.c_str());
}
}
}
QStringList PrefQuantitySpinBox::getHistory() const
{
Q_D(const PrefQuantitySpinBox);
QStringList res;
if (d->handle.isValid()) {
std::string tmp;
for (int i = 0 ; i< d->historySize ;i++) {
QByteArray hist = "Hist";
hist.append(QByteArray::number(i));
tmp = d->handle->GetASCII(hist);
if (!tmp.empty())
res.push_back(QString::fromUtf8(tmp.c_str()));
else
break; // end of history reached
}
}
return res;
}
void PrefQuantitySpinBox::setToLastUsedValue()
{
QStringList hist = getHistory();
if (!hist.empty())
lineEdit()->setText(hist[0]);
}
void PrefQuantitySpinBox::setParamGrpPath(const QByteArray& path)
{
Q_D(PrefQuantitySpinBox);
d->handle = App::GetApplication().GetParameterGroupByPath(path);
if (d->handle.isValid())
d->prefGrp = path;
}
QByteArray PrefQuantitySpinBox::paramGrpPath() const
{
Q_D(const PrefQuantitySpinBox);
if (d->handle.isValid())
return d->prefGrp;
return QByteArray();
}
int PrefQuantitySpinBox::historySize() const
{
Q_D(const PrefQuantitySpinBox);
return d->historySize;
}
void PrefQuantitySpinBox::setHistorySize(int i)
{
Q_D(PrefQuantitySpinBox);
d->historySize = i;
}
#include "moc_PrefWidgets.cpp"
<|endoftext|>
|
<commit_before>/** Copyright (C) 2015 Ultimaker - Released under terms of the AGPLv3 License */
#include "LayerPlanBuffer.h"
#include "gcodeExport.h"
#include "utils/logoutput.h"
#include "FffProcessor.h"
namespace cura {
void LayerPlanBuffer::flush()
{
if (buffer.size() > 0)
{
insertPreheatCommands(); // insert preheat commands of the very last layer
}
while (!buffer.empty())
{
buffer.front().writeGCode(gcode);
if (CommandSocket::isInstantiated())
{
CommandSocket::getInstance()->flushGcode();
}
buffer.pop_front();
}
}
void LayerPlanBuffer::insertPreheatCommand(ExtruderPlan& extruder_plan_before, double time_after_extruder_plan_start, int extruder, double temp)
{
double acc_time = 0.0;
for (unsigned int path_idx = 0; path_idx < extruder_plan_before.paths.size(); path_idx++)
{
GCodePath& path = extruder_plan_before.paths[path_idx];
acc_time += path.estimates.getTotalTime();
if (acc_time > time_after_extruder_plan_start)
{
// logError("Inserting %f\t seconds too early!\n", acc_time - time_after_extruder_plan_start);
extruder_plan_before.insertCommand(path_idx, extruder, temp, false, acc_time - time_after_extruder_plan_start);
return;
}
}
// TODO: walk over paths from back to front instead of front to back!
extruder_plan_before.insertCommand(extruder_plan_before.paths.size(), extruder, temp, false); // insert at end of extruder plan if time_after_extruder_plan_start > extruder_plan.time
// = special insert after all extruder plans
}
Preheat::WarmUpResult LayerPlanBuffer::timeBeforeExtruderPlanToInsert(std::vector<GCodePlanner*>& layers, unsigned int layer_plan_idx, unsigned int extruder_plan_idx)
{
ExtruderPlan& extruder_plan = layers[layer_plan_idx]->extruder_plans[extruder_plan_idx];
int extruder = extruder_plan.extruder;
double required_temp = extruder_plan.required_temp;
unsigned int extruder_plan_before_idx = extruder_plan_idx - 1;
bool first_it = true;
double in_between_time = 0.0;
for (unsigned int layer_idx = layer_plan_idx; int(layer_idx) >= 0; layer_idx--)
{ // find a previous extruder plan where the same extruder is used to see what time this extruder wasn't used
GCodePlanner& layer = *layers[layer_idx];
if (!first_it)
{
extruder_plan_before_idx = layer.extruder_plans.size() - 1;
}
for ( ; int(extruder_plan_before_idx) >= 0; extruder_plan_before_idx--)
{
ExtruderPlan& extruder_plan = layer.extruder_plans[extruder_plan_before_idx];
if (extruder_plan.extruder == extruder)
{
Preheat::WarmUpResult warm_up = preheat_config.timeBeforeEndToInsertPreheatCommand_coolDownWarmUp(in_between_time, extruder, required_temp);
warm_up.heating_time = std::min(in_between_time, warm_up.heating_time + time_to_start_warmup_earlier_to_be_extra_sure_we_dont_have_to_wait);
return warm_up;
}
in_between_time += extruder_plan.estimates.getTotalTime();
}
first_it = false;
}
// The last extruder plan with the same extruder falls outside of the buffer
// assume the nozzle has cooled down to strandby temperature already.
Preheat::WarmUpResult warm_up;
warm_up.total_time_window = in_between_time;
warm_up.lowest_temperature = preheat_config.getStandbyTemp(extruder);
warm_up.heating_time = preheat_config.timeBeforeEndToInsertPreheatCommand_warmUp(warm_up.lowest_temperature, extruder, required_temp, false);
if (warm_up.heating_time > in_between_time)
{
warm_up.heating_time = in_between_time;
warm_up.lowest_temperature = in_between_time / preheat_config.getTimeToHeatup1Degree(extruder);
}
warm_up.heating_time = warm_up.heating_time + time_to_start_warmup_earlier_to_be_extra_sure_we_dont_have_to_wait;
return warm_up;
}
void LayerPlanBuffer::insertPreheatCommand_singleExtrusion(ExtruderPlan& prev_extruder_plan, int extruder, double required_temp)
{
// time_before_extruder_plan_end is halved, so that at the layer change the temperature will be half way betewen the two requested temperatures
double time_before_extruder_plan_end = 0.5 * preheat_config.timeBeforeEndToInsertPreheatCommand_warmUp(prev_extruder_plan.required_temp, extruder, required_temp, true);
double time_after_extruder_plan_start = prev_extruder_plan.estimates.getTotalTime() - time_before_extruder_plan_end;
if (time_after_extruder_plan_start < 0)
{
time_after_extruder_plan_start = 0; // don't override the extruder plan with same extruder of the previous layer
}
insertPreheatCommand(prev_extruder_plan, time_after_extruder_plan_start, extruder, required_temp);
}
void LayerPlanBuffer::handleStandbyTemp(std::vector<GCodePlanner*>& layers, unsigned int layer_plan_idx, unsigned int extruder_plan_idx, double standby_temp)
{
ExtruderPlan& extruder_plan = layers[layer_plan_idx]->extruder_plans[extruder_plan_idx];
int extruder = extruder_plan.extruder;
unsigned int extruder_plan_before_idx = extruder_plan_idx - 1;
bool first_it = true;
for (unsigned int layer_idx = layer_plan_idx; int(layer_idx) >= 0; layer_idx--)
{ // find a previous extruder plan where the same extruder is used to see what time this extruder wasn't used
GCodePlanner& layer = *layers[layer_idx];
if (!first_it)
{
extruder_plan_before_idx = layer.extruder_plans.size() - 1;
}
for ( ; int(extruder_plan_before_idx) >= 0; extruder_plan_before_idx--)
{
ExtruderPlan& extruder_plan = layer.extruder_plans[extruder_plan_before_idx];
if (extruder_plan.extruder == extruder)
{
extruder_plan.prev_extruder_standby_temp = standby_temp;
return;
}
}
first_it = false;
}
}
void LayerPlanBuffer::insertPreheatCommand_multiExtrusion(std::vector<GCodePlanner*>& layers, unsigned int layer_plan_idx, unsigned int extruder_plan_idx)
{
ExtruderPlan& extruder_plan = layers[layer_plan_idx]->extruder_plans[extruder_plan_idx];
int extruder = extruder_plan.extruder;
double required_temp = extruder_plan.required_temp;
Preheat::WarmUpResult heating_time_and_from_temp = timeBeforeExtruderPlanToInsert(layers, layer_plan_idx, extruder_plan_idx);
handleStandbyTemp(layers, layer_plan_idx, extruder_plan_idx, heating_time_and_from_temp.lowest_temperature);
double time_before_extruder_plan_to_insert = heating_time_and_from_temp.heating_time;
unsigned int extruder_plan_before_idx = extruder_plan_idx - 1;
bool first_it = true; // Whether it's the first iteration of the for loop below
for (unsigned int layer_idx = layer_plan_idx; int(layer_idx) >= 0; layer_idx--)
{
GCodePlanner& layer = *layers[layer_idx];
if (!first_it)
{ // go over all extruder plans in the layer except for the layer of this extruder plan
extruder_plan_before_idx = layer.extruder_plans.size() - 1;
}
for ( ; int(extruder_plan_before_idx) >= 0; extruder_plan_before_idx--)
{
ExtruderPlan& extruder_plan_before = layer.extruder_plans[extruder_plan_before_idx];
assert (extruder_plan_before.extruder != extruder);
double time_here = extruder_plan_before.estimates.getTotalTime();
if (time_here >= time_before_extruder_plan_to_insert)
{
insertPreheatCommand(extruder_plan_before, time_here - time_before_extruder_plan_to_insert, extruder, required_temp);
return;
}
time_before_extruder_plan_to_insert -= time_here;
}
first_it = false;
}
// time_before_extruder_plan_to_insert falls before all plans in the buffer
ExtruderPlan& first_extruder_plan = layers[0]->extruder_plans[0];
first_extruder_plan.insertCommand(0, extruder, required_temp, false); // insert preheat command at verfy beginning of buffer
}
void LayerPlanBuffer::insertPreheatCommand(std::vector<GCodePlanner*>& layers, unsigned int layer_plan_idx, unsigned int extruder_plan_idx)
{
ExtruderPlan& extruder_plan = layers[layer_plan_idx]->extruder_plans[extruder_plan_idx];
int extruder = extruder_plan.extruder;
double required_temp = extruder_plan.required_temp;
ExtruderPlan* prev_extruder_plan = nullptr;
if (extruder_plan_idx == 0)
{
if (layer_plan_idx == 0)
{ // the very first extruder plan of the current meshgroup
for (int extruder_idx = 0; extruder_idx < getSettingAsCount("machine_extruder_count"); extruder_idx++)
{ // set temperature of the first nozzle, turn other nozzles down
if (FffProcessor::getInstance()->getMeshgroupNr() == 0)
{
// override values from GCodeExport::setInitialTemps
// the first used extruder should be set to the required temp in the start gcode
// see FffGcodeWriter::processStartingCode
if (extruder_idx == extruder)
{
gcode.setInitialTemp(extruder_idx, required_temp);
}
else
{
gcode.setInitialTemp(extruder_idx, preheat_config.getStandbyTemp(extruder_idx));
}
}
else
{
if (extruder_idx == extruder)
{
extruder_plan.required_temp = required_temp;
}
else
{ // TODO: do we need to do this?
extruder_plan.prev_extruder_standby_temp = preheat_config.getStandbyTemp(extruder_idx);
}
}
}
return;
}
prev_extruder_plan = &layers[layer_plan_idx - 1]->extruder_plans.back();
}
else
{
prev_extruder_plan = &layers[layer_plan_idx]->extruder_plans[extruder_plan_idx - 1];
}
assert(prev_extruder_plan != nullptr);
int prev_extruder = prev_extruder_plan->extruder;
if (prev_extruder != extruder)
{ // set previous extruder to standby temperature
extruder_plan.prev_extruder_standby_temp = preheat_config.getStandbyTemp(prev_extruder);
}
if (prev_extruder == extruder)
{
if (preheat_config.usesFlowDependentTemp(extruder))
{
insertPreheatCommand_singleExtrusion(*prev_extruder_plan, extruder, required_temp);
}
}
else
{
insertPreheatCommand_multiExtrusion(layers, layer_plan_idx, extruder_plan_idx);
}
}
void LayerPlanBuffer::insertPreheatCommands()
{
if (buffer.back().extruder_plans.size() == 0 || (buffer.back().extruder_plans.size() == 1 && buffer.back().extruder_plans[0].paths.size() == 0))
{ // disregard empty layer
buffer.pop_back();
return;
}
std::vector<GCodePlanner*> layers;
layers.reserve(buffer.size());
for (GCodePlanner& layer_plan : buffer)
{
layers.push_back(&layer_plan);
}
unsigned int layer_idx = layers.size() - 1;
// insert commands for all extruder plans on this layer
GCodePlanner& layer_plan = *layers[layer_idx];
for (unsigned int extruder_plan_idx = 0; extruder_plan_idx < layer_plan.extruder_plans.size(); extruder_plan_idx++)
{
ExtruderPlan& extruder_plan = layer_plan.extruder_plans[extruder_plan_idx];
double time = extruder_plan.estimates.getTotalUnretractedTime();
if (time <= 0.0
|| extruder_plan.estimates.getMaterial() == 0.0 // extruder plan only consists of moves (when an extruder switch occurs at the beginning of a layer)
)
{
continue;
}
double avg_flow = extruder_plan.estimates.getMaterial() / time; // TODO: subtract retracted travel time
extruder_plan.required_temp = preheat_config.getTemp(extruder_plan.extruder, avg_flow);
insertPreheatCommand(layers, layer_idx, extruder_plan_idx);
}
}
} // namespace cura<commit_msg>fix: removed superfluous if case (CURA-1731)<commit_after>/** Copyright (C) 2015 Ultimaker - Released under terms of the AGPLv3 License */
#include "LayerPlanBuffer.h"
#include "gcodeExport.h"
#include "utils/logoutput.h"
#include "FffProcessor.h"
namespace cura {
void LayerPlanBuffer::flush()
{
if (buffer.size() > 0)
{
insertPreheatCommands(); // insert preheat commands of the very last layer
}
while (!buffer.empty())
{
buffer.front().writeGCode(gcode);
if (CommandSocket::isInstantiated())
{
CommandSocket::getInstance()->flushGcode();
}
buffer.pop_front();
}
}
void LayerPlanBuffer::insertPreheatCommand(ExtruderPlan& extruder_plan_before, double time_after_extruder_plan_start, int extruder, double temp)
{
double acc_time = 0.0;
for (unsigned int path_idx = 0; path_idx < extruder_plan_before.paths.size(); path_idx++)
{
GCodePath& path = extruder_plan_before.paths[path_idx];
acc_time += path.estimates.getTotalTime();
if (acc_time > time_after_extruder_plan_start)
{
// logError("Inserting %f\t seconds too early!\n", acc_time - time_after_extruder_plan_start);
extruder_plan_before.insertCommand(path_idx, extruder, temp, false, acc_time - time_after_extruder_plan_start);
return;
}
}
// TODO: walk over paths from back to front instead of front to back!
extruder_plan_before.insertCommand(extruder_plan_before.paths.size(), extruder, temp, false); // insert at end of extruder plan if time_after_extruder_plan_start > extruder_plan.time
// = special insert after all extruder plans
}
Preheat::WarmUpResult LayerPlanBuffer::timeBeforeExtruderPlanToInsert(std::vector<GCodePlanner*>& layers, unsigned int layer_plan_idx, unsigned int extruder_plan_idx)
{
ExtruderPlan& extruder_plan = layers[layer_plan_idx]->extruder_plans[extruder_plan_idx];
int extruder = extruder_plan.extruder;
double required_temp = extruder_plan.required_temp;
unsigned int extruder_plan_before_idx = extruder_plan_idx - 1;
bool first_it = true;
double in_between_time = 0.0;
for (unsigned int layer_idx = layer_plan_idx; int(layer_idx) >= 0; layer_idx--)
{ // find a previous extruder plan where the same extruder is used to see what time this extruder wasn't used
GCodePlanner& layer = *layers[layer_idx];
if (!first_it)
{
extruder_plan_before_idx = layer.extruder_plans.size() - 1;
}
for ( ; int(extruder_plan_before_idx) >= 0; extruder_plan_before_idx--)
{
ExtruderPlan& extruder_plan = layer.extruder_plans[extruder_plan_before_idx];
if (extruder_plan.extruder == extruder)
{
Preheat::WarmUpResult warm_up = preheat_config.timeBeforeEndToInsertPreheatCommand_coolDownWarmUp(in_between_time, extruder, required_temp);
warm_up.heating_time = std::min(in_between_time, warm_up.heating_time + time_to_start_warmup_earlier_to_be_extra_sure_we_dont_have_to_wait);
return warm_up;
}
in_between_time += extruder_plan.estimates.getTotalTime();
}
first_it = false;
}
// The last extruder plan with the same extruder falls outside of the buffer
// assume the nozzle has cooled down to strandby temperature already.
Preheat::WarmUpResult warm_up;
warm_up.total_time_window = in_between_time;
warm_up.lowest_temperature = preheat_config.getStandbyTemp(extruder);
warm_up.heating_time = preheat_config.timeBeforeEndToInsertPreheatCommand_warmUp(warm_up.lowest_temperature, extruder, required_temp, false);
if (warm_up.heating_time > in_between_time)
{
warm_up.heating_time = in_between_time;
warm_up.lowest_temperature = in_between_time / preheat_config.getTimeToHeatup1Degree(extruder);
}
warm_up.heating_time = warm_up.heating_time + time_to_start_warmup_earlier_to_be_extra_sure_we_dont_have_to_wait;
return warm_up;
}
void LayerPlanBuffer::insertPreheatCommand_singleExtrusion(ExtruderPlan& prev_extruder_plan, int extruder, double required_temp)
{
// time_before_extruder_plan_end is halved, so that at the layer change the temperature will be half way betewen the two requested temperatures
double time_before_extruder_plan_end = 0.5 * preheat_config.timeBeforeEndToInsertPreheatCommand_warmUp(prev_extruder_plan.required_temp, extruder, required_temp, true);
double time_after_extruder_plan_start = prev_extruder_plan.estimates.getTotalTime() - time_before_extruder_plan_end;
if (time_after_extruder_plan_start < 0)
{
time_after_extruder_plan_start = 0; // don't override the extruder plan with same extruder of the previous layer
}
insertPreheatCommand(prev_extruder_plan, time_after_extruder_plan_start, extruder, required_temp);
}
void LayerPlanBuffer::handleStandbyTemp(std::vector<GCodePlanner*>& layers, unsigned int layer_plan_idx, unsigned int extruder_plan_idx, double standby_temp)
{
ExtruderPlan& extruder_plan = layers[layer_plan_idx]->extruder_plans[extruder_plan_idx];
int extruder = extruder_plan.extruder;
unsigned int extruder_plan_before_idx = extruder_plan_idx - 1;
bool first_it = true;
for (unsigned int layer_idx = layer_plan_idx; int(layer_idx) >= 0; layer_idx--)
{ // find a previous extruder plan where the same extruder is used to see what time this extruder wasn't used
GCodePlanner& layer = *layers[layer_idx];
if (!first_it)
{
extruder_plan_before_idx = layer.extruder_plans.size() - 1;
}
for ( ; int(extruder_plan_before_idx) >= 0; extruder_plan_before_idx--)
{
ExtruderPlan& extruder_plan = layer.extruder_plans[extruder_plan_before_idx];
if (extruder_plan.extruder == extruder)
{
extruder_plan.prev_extruder_standby_temp = standby_temp;
return;
}
}
first_it = false;
}
}
void LayerPlanBuffer::insertPreheatCommand_multiExtrusion(std::vector<GCodePlanner*>& layers, unsigned int layer_plan_idx, unsigned int extruder_plan_idx)
{
ExtruderPlan& extruder_plan = layers[layer_plan_idx]->extruder_plans[extruder_plan_idx];
int extruder = extruder_plan.extruder;
double required_temp = extruder_plan.required_temp;
Preheat::WarmUpResult heating_time_and_from_temp = timeBeforeExtruderPlanToInsert(layers, layer_plan_idx, extruder_plan_idx);
handleStandbyTemp(layers, layer_plan_idx, extruder_plan_idx, heating_time_and_from_temp.lowest_temperature);
double time_before_extruder_plan_to_insert = heating_time_and_from_temp.heating_time;
unsigned int extruder_plan_before_idx = extruder_plan_idx - 1;
bool first_it = true; // Whether it's the first iteration of the for loop below
for (unsigned int layer_idx = layer_plan_idx; int(layer_idx) >= 0; layer_idx--)
{
GCodePlanner& layer = *layers[layer_idx];
if (!first_it)
{ // go over all extruder plans in the layer except for the layer of this extruder plan
extruder_plan_before_idx = layer.extruder_plans.size() - 1;
}
for ( ; int(extruder_plan_before_idx) >= 0; extruder_plan_before_idx--)
{
ExtruderPlan& extruder_plan_before = layer.extruder_plans[extruder_plan_before_idx];
assert (extruder_plan_before.extruder != extruder);
double time_here = extruder_plan_before.estimates.getTotalTime();
if (time_here >= time_before_extruder_plan_to_insert)
{
insertPreheatCommand(extruder_plan_before, time_here - time_before_extruder_plan_to_insert, extruder, required_temp);
return;
}
time_before_extruder_plan_to_insert -= time_here;
}
first_it = false;
}
// time_before_extruder_plan_to_insert falls before all plans in the buffer
ExtruderPlan& first_extruder_plan = layers[0]->extruder_plans[0];
first_extruder_plan.insertCommand(0, extruder, required_temp, false); // insert preheat command at verfy beginning of buffer
}
void LayerPlanBuffer::insertPreheatCommand(std::vector<GCodePlanner*>& layers, unsigned int layer_plan_idx, unsigned int extruder_plan_idx)
{
ExtruderPlan& extruder_plan = layers[layer_plan_idx]->extruder_plans[extruder_plan_idx];
int extruder = extruder_plan.extruder;
double required_temp = extruder_plan.required_temp;
ExtruderPlan* prev_extruder_plan = nullptr;
if (extruder_plan_idx == 0)
{
if (layer_plan_idx == 0)
{ // the very first extruder plan of the current meshgroup
for (int extruder_idx = 0; extruder_idx < getSettingAsCount("machine_extruder_count"); extruder_idx++)
{ // set temperature of the first nozzle, turn other nozzles down
if (FffProcessor::getInstance()->getMeshgroupNr() == 0)
{
// override values from GCodeExport::setInitialTemps
// the first used extruder should be set to the required temp in the start gcode
// see FffGcodeWriter::processStartingCode
if (extruder_idx == extruder)
{
gcode.setInitialTemp(extruder_idx, required_temp);
}
else
{
gcode.setInitialTemp(extruder_idx, preheat_config.getStandbyTemp(extruder_idx));
}
}
else
{
if (extruder_idx != extruder)
{ // TODO: do we need to do this?
extruder_plan.prev_extruder_standby_temp = preheat_config.getStandbyTemp(extruder_idx);
}
}
}
return;
}
prev_extruder_plan = &layers[layer_plan_idx - 1]->extruder_plans.back();
}
else
{
prev_extruder_plan = &layers[layer_plan_idx]->extruder_plans[extruder_plan_idx - 1];
}
assert(prev_extruder_plan != nullptr);
int prev_extruder = prev_extruder_plan->extruder;
if (prev_extruder != extruder)
{ // set previous extruder to standby temperature
extruder_plan.prev_extruder_standby_temp = preheat_config.getStandbyTemp(prev_extruder);
}
if (prev_extruder == extruder)
{
if (preheat_config.usesFlowDependentTemp(extruder))
{
insertPreheatCommand_singleExtrusion(*prev_extruder_plan, extruder, required_temp);
}
}
else
{
insertPreheatCommand_multiExtrusion(layers, layer_plan_idx, extruder_plan_idx);
}
}
void LayerPlanBuffer::insertPreheatCommands()
{
if (buffer.back().extruder_plans.size() == 0 || (buffer.back().extruder_plans.size() == 1 && buffer.back().extruder_plans[0].paths.size() == 0))
{ // disregard empty layer
buffer.pop_back();
return;
}
std::vector<GCodePlanner*> layers;
layers.reserve(buffer.size());
for (GCodePlanner& layer_plan : buffer)
{
layers.push_back(&layer_plan);
}
unsigned int layer_idx = layers.size() - 1;
// insert commands for all extruder plans on this layer
GCodePlanner& layer_plan = *layers[layer_idx];
for (unsigned int extruder_plan_idx = 0; extruder_plan_idx < layer_plan.extruder_plans.size(); extruder_plan_idx++)
{
ExtruderPlan& extruder_plan = layer_plan.extruder_plans[extruder_plan_idx];
double time = extruder_plan.estimates.getTotalUnretractedTime();
if (time <= 0.0
|| extruder_plan.estimates.getMaterial() == 0.0 // extruder plan only consists of moves (when an extruder switch occurs at the beginning of a layer)
)
{
continue;
}
double avg_flow = extruder_plan.estimates.getMaterial() / time; // TODO: subtract retracted travel time
extruder_plan.required_temp = preheat_config.getTemp(extruder_plan.extruder, avg_flow);
insertPreheatCommand(layers, layer_idx, extruder_plan_idx);
}
}
} // namespace cura<|endoftext|>
|
<commit_before>//===- tools/dsymutil/CompileUnit.h - Dwarf compile unit ------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "CompileUnit.h"
#include "DeclContext.h"
namespace llvm {
namespace dsymutil {
/// Check if the DIE at \p Idx is in the scope of a function.
static bool inFunctionScope(CompileUnit &U, unsigned Idx) {
while (Idx) {
if (U.getOrigUnit().getDIEAtIndex(Idx).getTag() == dwarf::DW_TAG_subprogram)
return true;
Idx = U.getInfo(Idx).ParentIdx;
}
return false;
}
void CompileUnit::markEverythingAsKept() {
unsigned Idx = 0;
setHasInterestingContent();
for (auto &I : Info) {
// Mark everything that wasn't explicit marked for pruning.
I.Keep = !I.Prune;
auto DIE = OrigUnit.getDIEAtIndex(Idx++);
// Try to guess which DIEs must go to the accelerator tables. We do that
// just for variables, because functions will be handled depending on
// whether they carry a DW_AT_low_pc attribute or not.
if (DIE.getTag() != dwarf::DW_TAG_variable &&
DIE.getTag() != dwarf::DW_TAG_constant)
continue;
Optional<DWARFFormValue> Value;
if (!(Value = DIE.find(dwarf::DW_AT_location))) {
if ((Value = DIE.find(dwarf::DW_AT_const_value)) &&
!inFunctionScope(*this, I.ParentIdx))
I.InDebugMap = true;
continue;
}
if (auto Block = Value->getAsBlock()) {
if (Block->size() > OrigUnit.getAddressByteSize() &&
(*Block)[0] == dwarf::DW_OP_addr)
I.InDebugMap = true;
}
}
}
uint64_t CompileUnit::computeNextUnitOffset() {
NextUnitOffset = StartOffset + 11 /* Header size */;
// The root DIE might be null, meaning that the Unit had nothing to
// contribute to the linked output. In that case, we will emit the
// unit header without any actual DIE.
if (NewUnit)
NextUnitOffset += NewUnit->getUnitDie().getSize();
return NextUnitOffset;
}
/// Keep track of a forward cross-cu reference from this unit
/// to \p Die that lives in \p RefUnit.
void CompileUnit::noteForwardReference(DIE *Die, const CompileUnit *RefUnit,
DeclContext *Ctxt, PatchLocation Attr) {
ForwardDIEReferences.emplace_back(Die, RefUnit, Ctxt, Attr);
}
void CompileUnit::fixupForwardReferences() {
for (const auto &Ref : ForwardDIEReferences) {
DIE *RefDie;
const CompileUnit *RefUnit;
PatchLocation Attr;
DeclContext *Ctxt;
std::tie(RefDie, RefUnit, Ctxt, Attr) = Ref;
if (Ctxt && Ctxt->getCanonicalDIEOffset())
Attr.set(Ctxt->getCanonicalDIEOffset());
else
Attr.set(RefDie->getOffset() + RefUnit->getStartOffset());
}
}
void CompileUnit::addLabelLowPc(uint64_t LabelLowPc, int64_t PcOffset) {
Labels.insert({LabelLowPc, PcOffset});
}
void CompileUnit::addFunctionRange(uint64_t FuncLowPc, uint64_t FuncHighPc,
int64_t PcOffset) {
Ranges.insert(FuncLowPc, FuncHighPc, PcOffset);
this->LowPc = std::min(LowPc, FuncLowPc + PcOffset);
this->HighPc = std::max(HighPc, FuncHighPc + PcOffset);
}
void CompileUnit::noteRangeAttribute(const DIE &Die, PatchLocation Attr) {
if (Die.getTag() != dwarf::DW_TAG_compile_unit)
RangeAttributes.push_back(Attr);
else
UnitRangeAttribute = Attr;
}
void CompileUnit::noteLocationAttribute(PatchLocation Attr, int64_t PcOffset) {
LocationAttributes.emplace_back(Attr, PcOffset);
}
void CompileUnit::addNamespaceAccelerator(const DIE *Die,
DwarfStringPoolEntryRef Name) {
Namespaces.emplace_back(Name, Die);
}
void CompileUnit::addObjCAccelerator(const DIE *Die,
DwarfStringPoolEntryRef Name,
bool SkipPubSection) {
ObjC.emplace_back(Name, Die, SkipPubSection);
}
void CompileUnit::addNameAccelerator(const DIE *Die,
DwarfStringPoolEntryRef Name,
bool SkipPubSection) {
Pubnames.emplace_back(Name, Die, SkipPubSection);
}
void CompileUnit::addTypeAccelerator(const DIE *Die,
DwarfStringPoolEntryRef Name,
bool ObjcClassImplementation,
uint32_t QualifiedNameHash) {
Pubtypes.emplace_back(Name, Die, QualifiedNameHash, ObjcClassImplementation);
}
} // namespace dsymutil
} // namespace llvm
<commit_msg>[dsymutil] Fix assertion triggered by empty address range.<commit_after>//===- tools/dsymutil/CompileUnit.h - Dwarf compile unit ------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "CompileUnit.h"
#include "DeclContext.h"
namespace llvm {
namespace dsymutil {
/// Check if the DIE at \p Idx is in the scope of a function.
static bool inFunctionScope(CompileUnit &U, unsigned Idx) {
while (Idx) {
if (U.getOrigUnit().getDIEAtIndex(Idx).getTag() == dwarf::DW_TAG_subprogram)
return true;
Idx = U.getInfo(Idx).ParentIdx;
}
return false;
}
void CompileUnit::markEverythingAsKept() {
unsigned Idx = 0;
setHasInterestingContent();
for (auto &I : Info) {
// Mark everything that wasn't explicit marked for pruning.
I.Keep = !I.Prune;
auto DIE = OrigUnit.getDIEAtIndex(Idx++);
// Try to guess which DIEs must go to the accelerator tables. We do that
// just for variables, because functions will be handled depending on
// whether they carry a DW_AT_low_pc attribute or not.
if (DIE.getTag() != dwarf::DW_TAG_variable &&
DIE.getTag() != dwarf::DW_TAG_constant)
continue;
Optional<DWARFFormValue> Value;
if (!(Value = DIE.find(dwarf::DW_AT_location))) {
if ((Value = DIE.find(dwarf::DW_AT_const_value)) &&
!inFunctionScope(*this, I.ParentIdx))
I.InDebugMap = true;
continue;
}
if (auto Block = Value->getAsBlock()) {
if (Block->size() > OrigUnit.getAddressByteSize() &&
(*Block)[0] == dwarf::DW_OP_addr)
I.InDebugMap = true;
}
}
}
uint64_t CompileUnit::computeNextUnitOffset() {
NextUnitOffset = StartOffset + 11 /* Header size */;
// The root DIE might be null, meaning that the Unit had nothing to
// contribute to the linked output. In that case, we will emit the
// unit header without any actual DIE.
if (NewUnit)
NextUnitOffset += NewUnit->getUnitDie().getSize();
return NextUnitOffset;
}
/// Keep track of a forward cross-cu reference from this unit
/// to \p Die that lives in \p RefUnit.
void CompileUnit::noteForwardReference(DIE *Die, const CompileUnit *RefUnit,
DeclContext *Ctxt, PatchLocation Attr) {
ForwardDIEReferences.emplace_back(Die, RefUnit, Ctxt, Attr);
}
void CompileUnit::fixupForwardReferences() {
for (const auto &Ref : ForwardDIEReferences) {
DIE *RefDie;
const CompileUnit *RefUnit;
PatchLocation Attr;
DeclContext *Ctxt;
std::tie(RefDie, RefUnit, Ctxt, Attr) = Ref;
if (Ctxt && Ctxt->getCanonicalDIEOffset())
Attr.set(Ctxt->getCanonicalDIEOffset());
else
Attr.set(RefDie->getOffset() + RefUnit->getStartOffset());
}
}
void CompileUnit::addLabelLowPc(uint64_t LabelLowPc, int64_t PcOffset) {
Labels.insert({LabelLowPc, PcOffset});
}
void CompileUnit::addFunctionRange(uint64_t FuncLowPc, uint64_t FuncHighPc,
int64_t PcOffset) {
// Don't add empty ranges to the interval map. They are a problem because
// the interval map expects half open intervals. This is safe because they
// are empty anyway.
if (FuncHighPc != FuncLowPc)
Ranges.insert(FuncLowPc, FuncHighPc, PcOffset);
this->LowPc = std::min(LowPc, FuncLowPc + PcOffset);
this->HighPc = std::max(HighPc, FuncHighPc + PcOffset);
}
void CompileUnit::noteRangeAttribute(const DIE &Die, PatchLocation Attr) {
if (Die.getTag() != dwarf::DW_TAG_compile_unit)
RangeAttributes.push_back(Attr);
else
UnitRangeAttribute = Attr;
}
void CompileUnit::noteLocationAttribute(PatchLocation Attr, int64_t PcOffset) {
LocationAttributes.emplace_back(Attr, PcOffset);
}
void CompileUnit::addNamespaceAccelerator(const DIE *Die,
DwarfStringPoolEntryRef Name) {
Namespaces.emplace_back(Name, Die);
}
void CompileUnit::addObjCAccelerator(const DIE *Die,
DwarfStringPoolEntryRef Name,
bool SkipPubSection) {
ObjC.emplace_back(Name, Die, SkipPubSection);
}
void CompileUnit::addNameAccelerator(const DIE *Die,
DwarfStringPoolEntryRef Name,
bool SkipPubSection) {
Pubnames.emplace_back(Name, Die, SkipPubSection);
}
void CompileUnit::addTypeAccelerator(const DIE *Die,
DwarfStringPoolEntryRef Name,
bool ObjcClassImplementation,
uint32_t QualifiedNameHash) {
Pubtypes.emplace_back(Name, Die, QualifiedNameHash, ObjcClassImplementation);
}
} // namespace dsymutil
} // namespace llvm
<|endoftext|>
|
<commit_before>
#include "Globals.h"
#include "LoggerListeners.h"
#include <chrono>
#if defined(_WIN32)
#include <io.h> // Needed for _isatty(), not available on Linux
#include <time.h>
#elif defined(__linux) && !defined(ANDROID_NDK)
#include <unistd.h> // Needed for isatty() on Linux
#elif defined(ANDROID_NDK)
#include <android/log.h>
#endif
#if defined(_WIN32) || (defined (__linux) && !defined(ANDROID_NDK))
class cColouredConsoleListener
: public cLogger::cListener
{
protected:
virtual void SetLogColour(cLogger::eLogLevel a_LogLevel) = 0;
virtual void SetDefaultLogColour() = 0;
virtual void Log(AString a_Message, cLogger::eLogLevel a_LogLevel) override
{
SetLogColour(a_LogLevel);
fputs(a_Message.c_str(), stdout);
SetDefaultLogColour();
}
};
#endif
#ifdef _WIN32
class cWindowsConsoleListener
: public cColouredConsoleListener
{
typedef cColouredConsoleListener super;
public:
cWindowsConsoleListener(HANDLE a_Console, WORD a_DefaultConsoleAttrib) :
m_Console(a_Console),
m_DefaultConsoleAttrib(a_DefaultConsoleAttrib)
{
}
#ifdef _DEBUG
virtual void Log(AString a_Message, cLogger::eLogLevel a_LogLevel) override
{
super::Log(a_Message, a_LogLevel);
// In a Windows Debug build, output the log to debug console as well:
OutputDebugStringA(a_Message.c_str());
}
#endif
virtual void SetLogColour(cLogger::eLogLevel a_LogLevel) override
{
// by default, gray on black
WORD Attrib = FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED;
switch (a_LogLevel)
{
case cLogger::llRegular:
{
// Gray on black
Attrib = FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED;
break;
}
case cLogger::llInfo:
{
// Yellow on black
Attrib = FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY;
break;
}
case cLogger::llWarning:
{
// Red on black
Attrib = FOREGROUND_RED | FOREGROUND_INTENSITY;
break;
}
case cLogger::llError:
{
// Black on red
Attrib = BACKGROUND_RED | BACKGROUND_INTENSITY;
break;
}
}
SetConsoleTextAttribute(m_Console, Attrib);
}
virtual void SetDefaultLogColour() override
{
SetConsoleTextAttribute(m_Console, m_DefaultConsoleAttrib);
}
private:
HANDLE m_Console;
WORD m_DefaultConsoleAttrib;
};
#elif defined (__linux) && !defined(ANDROID_NDK)
class cLinuxConsoleListener
: public cColouredConsoleListener
{
public:
virtual void SetLogColour(cLogger::eLogLevel a_LogLevel) override
{
switch (a_LogLevel)
{
case cLogger::llRegular:
{
// Whatever the console default is
printf("\x1b[0m");
break;
}
case cLogger::llInfo:
{
// Yellow on black
printf("\x1b[33;1m");
break;
}
case cLogger::llWarning:
{
// Red on black
printf("\x1b[31;1m");
break;
}
case cLogger::llError:
{
// Yellow on red
printf("\x1b[1;33;41;1m");
break;
}
}
}
virtual void SetDefaultLogColour() override
{
// Whatever the console default is
printf("\x1b[0m");
}
};
#elif defined(ANDROID_NDK)
class cAndroidConsoleListener
: public cLogger::cListener
{
public:
virtual void Log(AString a_Message, cLogger::eLogLevel a_LogLevel) override
{
android_LogPriority AndroidLogLevel;
switch (a_LogLevel)
{
case cLogger::llRegular:
{
AndroidLogLevel = ANDROID_LOG_VERBOSE;
break;
}
case cLogger::llInfo:
{
AndroidLogLevel = ANDROID_LOG_INFO;
break;
}
case cLogger::llWarning:
{
AndroidLogLevel = ANDROID_LOG_WARNING;
break;
}
case cLogger::llError:
{
AndroidLogLevel = ANDROID_LOG_ERROR;
break;
}
}
__android_log_print(AndroidLogLevel, "MCServer", "%s", a_Message.c_str());
}
};
#endif
class cVanillaCPPConsoleListener
: public cLogger::cListener
{
public:
virtual void Log(AString a_Message, cLogger::eLogLevel a_LogLevel) override
{
AString LogLevelString;
switch (a_LogLevel)
{
case cLogger::llRegular:
{
LogLevelString = "Log";
break;
}
case cLogger::llInfo:
{
LogLevelString = "Info";
break;
}
case cLogger::llWarning:
{
LogLevelString = "Warning";
break;
}
case cLogger::llError:
{
LogLevelString = "Error";
break;
}
}
printf("%s: %s", LogLevelString.c_str(), a_Message.c_str());
}
};
// Listener for when stdout is closed, i.e. When running as a daemon.
class cNullConsoleListener
: public cLogger::cListener
{
virtual void Log(AString a_Message, cLogger::eLogLevel a_LogLevel) override
{
}
};
cLogger::cListener * MakeConsoleListener(bool a_IsService)
{
if (a_IsService)
{
return new cNullConsoleListener;
}
#ifdef _WIN32
// See whether we are writing to a console the default console attrib:
bool ShouldColorOutput = (_isatty(_fileno(stdin)) != 0);
if (ShouldColorOutput)
{
CONSOLE_SCREEN_BUFFER_INFO sbi;
HANDLE Console = GetStdHandle(STD_OUTPUT_HANDLE);
GetConsoleScreenBufferInfo(Console, &sbi);
WORD DefaultConsoleAttrib = sbi.wAttributes;
return new cWindowsConsoleListener(Console, DefaultConsoleAttrib);
}
else
{
return new cVanillaCPPConsoleListener;
}
#elif defined (__linux) && !defined(ANDROID_NDK)
// TODO: lookup terminal in terminfo
if (isatty(fileno(stdout)))
{
return new cLinuxConsoleListener();
}
else
{
return new cVanillaCPPConsoleListener();
}
#else
return new cVanillaCPPConsoleListener();
#endif
}
////////////////////////////////////////////////////////////////////////////////
// cFileListener:
cFileListener::cFileListener(void)
{
cFile::CreateFolder(FILE_IO_PREFIX + AString("logs"));
m_File.Open(
FILE_IO_PREFIX + Printf(
"logs/LOG_%lld.txt",
std::chrono::duration_cast<std::chrono::seconds>(
std::chrono::system_clock::now().time_since_epoch()
).count()
),
cFile::fmAppend
);
}
void cFileListener::Log(AString a_Message, cLogger::eLogLevel a_LogLevel)
{
const char * LogLevelPrefix = "Unkn ";
switch (a_LogLevel)
{
case cLogger::llRegular:
{
LogLevelPrefix = " ";
break;
}
case cLogger::llInfo:
{
LogLevelPrefix = "Info ";
break;
}
case cLogger::llWarning:
{
LogLevelPrefix = "Warn ";
break;
}
case cLogger::llError:
{
LogLevelPrefix = "Err ";
break;
}
}
m_File.Printf("%s%s", LogLevelPrefix, a_Message.c_str());
}
<commit_msg>Fixed tigers format string<commit_after>
#include "Globals.h"
#include "LoggerListeners.h"
#include <chrono>
#if defined(_WIN32)
#include <io.h> // Needed for _isatty(), not available on Linux
#include <time.h>
#elif defined(__linux) && !defined(ANDROID_NDK)
#include <unistd.h> // Needed for isatty() on Linux
#elif defined(ANDROID_NDK)
#include <android/log.h>
#endif
#if defined(_WIN32) || (defined (__linux) && !defined(ANDROID_NDK))
class cColouredConsoleListener
: public cLogger::cListener
{
protected:
virtual void SetLogColour(cLogger::eLogLevel a_LogLevel) = 0;
virtual void SetDefaultLogColour() = 0;
virtual void Log(AString a_Message, cLogger::eLogLevel a_LogLevel) override
{
SetLogColour(a_LogLevel);
fputs(a_Message.c_str(), stdout);
SetDefaultLogColour();
}
};
#endif
#ifdef _WIN32
class cWindowsConsoleListener
: public cColouredConsoleListener
{
typedef cColouredConsoleListener super;
public:
cWindowsConsoleListener(HANDLE a_Console, WORD a_DefaultConsoleAttrib) :
m_Console(a_Console),
m_DefaultConsoleAttrib(a_DefaultConsoleAttrib)
{
}
#ifdef _DEBUG
virtual void Log(AString a_Message, cLogger::eLogLevel a_LogLevel) override
{
super::Log(a_Message, a_LogLevel);
// In a Windows Debug build, output the log to debug console as well:
OutputDebugStringA(a_Message.c_str());
}
#endif
virtual void SetLogColour(cLogger::eLogLevel a_LogLevel) override
{
// by default, gray on black
WORD Attrib = FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED;
switch (a_LogLevel)
{
case cLogger::llRegular:
{
// Gray on black
Attrib = FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED;
break;
}
case cLogger::llInfo:
{
// Yellow on black
Attrib = FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY;
break;
}
case cLogger::llWarning:
{
// Red on black
Attrib = FOREGROUND_RED | FOREGROUND_INTENSITY;
break;
}
case cLogger::llError:
{
// Black on red
Attrib = BACKGROUND_RED | BACKGROUND_INTENSITY;
break;
}
}
SetConsoleTextAttribute(m_Console, Attrib);
}
virtual void SetDefaultLogColour() override
{
SetConsoleTextAttribute(m_Console, m_DefaultConsoleAttrib);
}
private:
HANDLE m_Console;
WORD m_DefaultConsoleAttrib;
};
#elif defined (__linux) && !defined(ANDROID_NDK)
class cLinuxConsoleListener
: public cColouredConsoleListener
{
public:
virtual void SetLogColour(cLogger::eLogLevel a_LogLevel) override
{
switch (a_LogLevel)
{
case cLogger::llRegular:
{
// Whatever the console default is
printf("\x1b[0m");
break;
}
case cLogger::llInfo:
{
// Yellow on black
printf("\x1b[33;1m");
break;
}
case cLogger::llWarning:
{
// Red on black
printf("\x1b[31;1m");
break;
}
case cLogger::llError:
{
// Yellow on red
printf("\x1b[1;33;41;1m");
break;
}
}
}
virtual void SetDefaultLogColour() override
{
// Whatever the console default is
printf("\x1b[0m");
}
};
#elif defined(ANDROID_NDK)
class cAndroidConsoleListener
: public cLogger::cListener
{
public:
virtual void Log(AString a_Message, cLogger::eLogLevel a_LogLevel) override
{
android_LogPriority AndroidLogLevel;
switch (a_LogLevel)
{
case cLogger::llRegular:
{
AndroidLogLevel = ANDROID_LOG_VERBOSE;
break;
}
case cLogger::llInfo:
{
AndroidLogLevel = ANDROID_LOG_INFO;
break;
}
case cLogger::llWarning:
{
AndroidLogLevel = ANDROID_LOG_WARNING;
break;
}
case cLogger::llError:
{
AndroidLogLevel = ANDROID_LOG_ERROR;
break;
}
}
__android_log_print(AndroidLogLevel, "MCServer", "%s", a_Message.c_str());
}
};
#endif
class cVanillaCPPConsoleListener
: public cLogger::cListener
{
public:
virtual void Log(AString a_Message, cLogger::eLogLevel a_LogLevel) override
{
AString LogLevelString;
switch (a_LogLevel)
{
case cLogger::llRegular:
{
LogLevelString = "Log";
break;
}
case cLogger::llInfo:
{
LogLevelString = "Info";
break;
}
case cLogger::llWarning:
{
LogLevelString = "Warning";
break;
}
case cLogger::llError:
{
LogLevelString = "Error";
break;
}
}
printf("%s: %s", LogLevelString.c_str(), a_Message.c_str());
}
};
// Listener for when stdout is closed, i.e. When running as a daemon.
class cNullConsoleListener
: public cLogger::cListener
{
virtual void Log(AString a_Message, cLogger::eLogLevel a_LogLevel) override
{
}
};
cLogger::cListener * MakeConsoleListener(bool a_IsService)
{
if (a_IsService)
{
return new cNullConsoleListener;
}
#ifdef _WIN32
// See whether we are writing to a console the default console attrib:
bool ShouldColorOutput = (_isatty(_fileno(stdin)) != 0);
if (ShouldColorOutput)
{
CONSOLE_SCREEN_BUFFER_INFO sbi;
HANDLE Console = GetStdHandle(STD_OUTPUT_HANDLE);
GetConsoleScreenBufferInfo(Console, &sbi);
WORD DefaultConsoleAttrib = sbi.wAttributes;
return new cWindowsConsoleListener(Console, DefaultConsoleAttrib);
}
else
{
return new cVanillaCPPConsoleListener;
}
#elif defined (__linux) && !defined(ANDROID_NDK)
// TODO: lookup terminal in terminfo
if (isatty(fileno(stdout)))
{
return new cLinuxConsoleListener();
}
else
{
return new cVanillaCPPConsoleListener();
}
#else
return new cVanillaCPPConsoleListener();
#endif
}
////////////////////////////////////////////////////////////////////////////////
// cFileListener:
cFileListener::cFileListener(void)
{
cFile::CreateFolder(FILE_IO_PREFIX + AString("logs"));
m_File.Open(
FILE_IO_PREFIX + Printf(
"logs/LOG_%d.txt",
std::chrono::duration_cast<std::chrono::duration<int, std::ratio<1>>>(
std::chrono::system_clock::now().time_since_epoch()
).count()
),
cFile::fmAppend
);
}
void cFileListener::Log(AString a_Message, cLogger::eLogLevel a_LogLevel)
{
const char * LogLevelPrefix = "Unkn ";
switch (a_LogLevel)
{
case cLogger::llRegular:
{
LogLevelPrefix = " ";
break;
}
case cLogger::llInfo:
{
LogLevelPrefix = "Info ";
break;
}
case cLogger::llWarning:
{
LogLevelPrefix = "Warn ";
break;
}
case cLogger::llError:
{
LogLevelPrefix = "Err ";
break;
}
}
m_File.Printf("%s%s", LogLevelPrefix, a_Message.c_str());
}
<|endoftext|>
|
<commit_before>#include <cassert>
#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
int detectorid(unsigned int wirepos, unsigned int gridpos) {
// Should depend on the instance of a specific detector geomoetry,
// and calibration data
unsigned int wire = 128 * (wirepos - 0) / (1231);
unsigned int grid = 96 * (gridpos - 0) / (1920);
unsigned id;
assert(wire >= 0);
assert(wire <= 128);
assert(grid >= 0);
assert(grid <= 96);
id = grid * 128 + wire;
return id;
}
class DetMultiGrid {
public:
enum class hdr { DAT = 0x00, HDR, END = 0x03 };
typedef struct {
unsigned int n_words : 12;
unsigned int adc_res : 3;
unsigned int out_format : 1;
unsigned int module_id : 8;
unsigned int sub_header : 6;
unsigned int header_sig : 2;
} EventHeader;
typedef struct {
unsigned int adc_data : 14;
unsigned int overflow : 1;
unsigned int nop : 1;
unsigned int channel : 5;
unsigned int fix : 9;
unsigned int data_sig : 2;
} DataWord;
typedef struct {
unsigned int trigger : 30;
unsigned int footer_sig : 2;
} Footer;
union {
EventHeader eh;
DataWord dw;
Footer ef;
} data;
unsigned int wthresh{230}; // Current values from Anton
unsigned int gthresh{170}; // -=-
const char * df[9]= {"w0 amp", "w1 amp", "w0 pos", "w1 pos", "g0 amp",
"g1 amp", "g0 pos", "g1 pos", "time "};
unsigned int readsz{sizeof data};
};
int main(int argc, char * argv[]) {
DetMultiGrid det;
char * filename;
struct stat_t {
int rx; // file stats - Rx bytes
int errors; // event stat - header errors
int events; // event stat - number of events
int noise; //
int multi; // event stat - number of multi events
} stat;
unsigned int rxdata[9], maxdata[9], mindata[9]; // readout data
if (argc == 2) { // Filename only
filename = argv[1];
} else if (argc == 4) { // filename wthresh gthresh
det.wthresh = atoi(argv[2]); // signed int to unsigned int
det.gthresh = atoi(argv[3]);
assert(det.wthresh < 16384); // check for negative numbers
assert(det.gthresh < 16384);
filename = argv[1];
} else {
printf("usage: %s filename [wire_thresh grid_thresh]\n", argv[0]);
return -1;
}
bzero(&stat, sizeof(stat));
memset(maxdata, 0x00, sizeof(maxdata));
memset(mindata, 0xff, sizeof(mindata));
printf("file: %s\n", filename);
printf("wire thresh: %u\n", det.wthresh);
printf("grid thresh: %u\n", det.gthresh);
FILE *f = fopen(filename, "r");
if (f == NULL) {
printf("error: cannot open file \'%s\'\n", filename);
return -1;
}
assert(det.readsz == 4);
while (fread(&det.data, det.readsz, 1, f) > 0){
stat.rx += det.readsz;
if (det.data.eh.header_sig == (int)DetMultiGrid::hdr::HDR) { // Read Header
int nread = det.data.eh.n_words;
assert(nread == 9);
bzero(rxdata, sizeof(rxdata));
for (int j = 0; j < nread - 1; j++) {
if (fread(&det.data, det.readsz, 1, f) > 0) { // Read Data
stat.rx += det.readsz;
if (det.data.dw.data_sig != (int)DetMultiGrid::hdr::DAT) {
stat.errors++;
continue;
}
unsigned int ch = det.data.dw.channel;
unsigned int dat = det.data.dw.adc_data;
rxdata[ch] = dat;
maxdata[ch] = std::max(maxdata[ch], dat);
mindata[ch] = std::min(mindata[ch], dat);
}
}
// Read Footer
if (fread(&det.data, det.readsz, 1, f) > 0) {
stat.rx += det.readsz;
if (det.data.ef.footer_sig != (int)DetMultiGrid::hdr::END) {
stat.errors++;
continue;
}
maxdata[8] = std::max(maxdata[8], det.data.ef.trigger);
mindata[8] = std::min(mindata[8], det.data.ef.trigger);
// We have data - Process event
// Discard noisy data
if ((rxdata[0] < det.wthresh) || (rxdata[4] < det.gthresh)) {
stat.noise++;
continue;
}
// Detect and discard double neutron event
if ((rxdata[1] >= det.wthresh) && (rxdata[5] >= det.gthresh)) {
stat.multi++;
continue;
}
// Real event
stat.events++;
detectorid(rxdata[2], rxdata[6]);
}
}
}
printf("=======================\nStats\n");
printf("Bytes read: %d\n", stat.rx);
printf("Total samples: %d\n", stat.multi + stat.noise + stat.events);
printf(" events: %d\n", stat.events);
printf(" noise: %d\n", stat.noise);
printf(" double: %d\n", stat.multi);
printf("Errors: %d\n", stat.errors);
printf("-----------------------\n");
printf("Name Min Max\n");
for (int j = 0; j < 9; j++) {
printf("%s %5u %8u\n", det.df[j], mindata[j], maxdata[j]);
}
printf("-----------------------\n");
return 0;
}
<commit_msg>small edit<commit_after>#include <cassert>
#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
int detectorid(unsigned int wirepos, unsigned int gridpos) {
// Should depend on the instance of a specific detector geomoetry,
// and calibration data
unsigned int wire = 128 * (wirepos - 0) / (1231);
unsigned int grid = 96 * (gridpos - 0) / (1920);
unsigned id;
assert(wire >= 0);
assert(wire <= 128);
assert(grid >= 0);
assert(grid <= 96);
id = grid * 128 + wire;
return id;
}
class DetMultiGrid {
public:
enum class hdr { DAT = 0x00, HDR, END = 0x03 };
typedef struct {
unsigned int n_words : 12;
unsigned int adc_res : 3;
unsigned int out_format : 1;
unsigned int module_id : 8;
unsigned int sub_header : 6;
unsigned int header_sig : 2;
} EventHeader;
typedef struct {
unsigned int adc_data : 14;
unsigned int overflow : 1;
unsigned int nop : 1;
unsigned int channel : 5;
unsigned int fix : 9;
unsigned int data_sig : 2;
} DataWord;
typedef struct {
unsigned int trigger : 30;
unsigned int footer_sig : 2;
} Footer;
union {
EventHeader eh;
DataWord dw;
Footer ef;
} data;
unsigned int wthresh{230}; // Current values from Anton
unsigned int gthresh{170}; // -=-
const char * df[9]= {"w0 amp", "w1 amp", "w0 pos", "w1 pos", "g0 amp",
"g1 amp", "g0 pos", "g1 pos", "time "};
unsigned int readsz{sizeof data};
};
int main(int argc, char * argv[]) {
DetMultiGrid det;
char * filename;
struct stat_t {
int rx; // file stats - Rx bytes
int errors; // event stat - header errors
int events; // event stat - number of events
int noise; //
int multi; // event stat - number of multi events
} stat;
unsigned int rxdata[9], maxdata[9], mindata[9]; // readout data
if (argc == 2) { // Filename only
filename = argv[1];
} else if (argc == 4) { // filename wthresh gthresh
det.wthresh = atoi(argv[2]); // signed int to unsigned int
det.gthresh = atoi(argv[3]);
assert(det.wthresh < 16384); // check for negative numbers
assert(det.gthresh < 16384);
filename = argv[1];
} else {
printf("usage: %s filename [wire_thresh grid_thresh]\n", argv[0]);
return -1;
}
bzero(&stat, sizeof(stat));
memset(maxdata, 0x00, sizeof(maxdata));
memset(mindata, 0xff, sizeof(mindata));
printf("file: %s\n", filename);
printf("wire thresh: %u\n", det.wthresh);
printf("grid thresh: %u\n", det.gthresh);
FILE *f = fopen(filename, "r");
if (f == NULL) {
printf("error: cannot open file \'%s\'\n", filename);
return -1;
}
assert(det.readsz == 4);
while (fread(&det.data, det.readsz, 1, f) > 0){
stat.rx += det.readsz;
if (det.data.eh.header_sig == (int)DetMultiGrid::hdr::HDR) { // Read Header
int nread = det.data.eh.n_words;
assert(nread == 9);
bzero(rxdata, sizeof(rxdata));
for (int j = 0; j < nread - 1; j++) {
if (fread(&det.data, det.readsz, 1, f) > 0) { // Read Data
stat.rx += det.readsz;
if (det.data.dw.data_sig != (int)DetMultiGrid::hdr::DAT) {
stat.errors++;
continue;
}
auto ch = det.data.dw.channel;
auto dat = det.data.dw.adc_data;
rxdata[ch] = dat;
maxdata[ch] = std::max(maxdata[ch], dat);
mindata[ch] = std::min(mindata[ch], dat);
}
}
// Read Footer
if (fread(&det.data, det.readsz, 1, f) > 0) {
stat.rx += det.readsz;
if (det.data.ef.footer_sig != (int)DetMultiGrid::hdr::END) {
stat.errors++;
continue;
}
maxdata[8] = std::max(maxdata[8], det.data.ef.trigger);
mindata[8] = std::min(mindata[8], det.data.ef.trigger);
// We have data - Process event
// Discard noisy data
if ((rxdata[0] < det.wthresh) || (rxdata[4] < det.gthresh)) {
stat.noise++;
continue;
}
// Detect and discard double neutron event
if ((rxdata[1] >= det.wthresh) && (rxdata[5] >= det.gthresh)) {
stat.multi++;
continue;
}
// Real event
stat.events++;
detectorid(rxdata[2], rxdata[6]);
}
}
}
printf("=======================\nStats\n");
printf("Bytes read: %d\n", stat.rx);
printf("Total samples: %d\n", stat.multi + stat.noise + stat.events);
printf(" events: %d\n", stat.events);
printf(" noise: %d\n", stat.noise);
printf(" double: %d\n", stat.multi);
printf("Errors: %d\n", stat.errors);
printf("-----------------------\n");
printf("Name Min Max\n");
for (int j = 0; j < 9; j++) {
printf("%s %5u %8u\n", det.df[j], mindata[j], maxdata[j]);
}
printf("-----------------------\n");
return 0;
}
<|endoftext|>
|
<commit_before><commit_msg>clang: Assigned value is garbage or undefined<commit_after><|endoftext|>
|
<commit_before>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of libmeegotouch.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** 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
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/
#include <QProcess>
#include <QStringList>
#include <QObject>
#include <QDebug>
#include <MApplication>
#include <MApplicationService>
#ifdef HAVE_DBUS
#include <MApplicationIfAdaptor>
#endif //HAVE_DBUS
#include <MApplicationWindow>
#include <MApplicationPage>
#include <MAction>
#include <MLocale>
#include <MGConfItem>
#include <MSceneManager>
#include <MComponentCache>
#include "mainpage.h"
#include "timedemo.h"
#include "swaphook.h"
#include "widgetsgalleryretranslator.h"
#include "../../benchmarks/performancebenchmark/emptymainloophelper.h"
class MyApplicationService: public MApplicationService
{
public:
MyApplicationService(QObject *parent = 0) :
MApplicationService("com.nokia.widgetsgallery", parent) {
}
void launch() {
launchAnotherWithQProcess();
}
void handleServiceRegistrationFailure() {
qDebug() << "MyApplicationService::handleServiceRegistrationFailure()";
incrementAndRegister();
}
};
#ifndef Q_OS_WIN
M_EXPORT
#endif
int main(int argc, char **argv)
{
#ifdef M_OS_MAEMO5
QApplication::setGraphicsSystem(QLatin1String("native"));
#endif //M_OS_MAEMO5
//MApplication application(argc, argv, "widgetsgallery", new MyApplicationService() );
MApplication *application = MComponentCache::mApplication(argc, argv);
WidgetsgalleryRetranslator widgetsgalleryRetranslator;
QObject::connect(application, SIGNAL(localeSettingsChanged()), &widgetsgalleryRetranslator, SLOT(widgetsgalleryRetranslate()));
MApplicationWindow* window = MComponentCache::mApplicationWindow();
window->show();
MainPage *mainPage = new MainPage;
Timedemo *timedemo = 0;
if (qApp->arguments().indexOf("-timedemo") >= 0) {
QStringList demoPages;
int idx = qApp->arguments().indexOf("-demopages");
if (idx >= 0 && idx + 1 < qApp->arguments().count()) {
demoPages = qApp->arguments()[idx + 1].split(',');
}
timedemo = new Timedemo(mainPage, demoPages);
idx = qApp->arguments().indexOf("-outputcsv");
if (idx >= 0 && idx + 1 < qApp->arguments().count()) {
timedemo->setOutputCsv(qApp->arguments()[idx + 1]);
}
idx = qApp->arguments().indexOf("-framelog");
if (idx >= 0 && idx + 1 < qApp->arguments().count()) {
timedemo->setFramelog(qApp->arguments()[idx + 1]);
}
}
int index = qApp->arguments().indexOf("-initialpage");
if (index >= 0) {
if (index + 1 < qApp->arguments().count()) {
mainPage->setInitialPageToShow(qApp->arguments()[index + 1]);
}
}
EmptyMainLoopHelper mainLoopHelper;
// -quitimmediately will create fully the content of the main page
// -exitimmediately will skip creating the content of the main page
if (qApp->arguments().indexOf("-quitimmediately") >= 0 || qApp->arguments().indexOf("-exitimmediately") >= 0) {
// terminate widgetsgallery as soon as the content is shown and main loop is idle
mainPage->setMainLoopHelper(&mainLoopHelper);
mainLoopHelper.triggerTermination(EmptyMainLoopHelper::QuitOnEmpty);
}
window->sceneManager()->appearSceneWindowNow(mainPage);
int exitCode = application->exec();
delete timedemo;
delete mainPage;
delete window;
delete application;
return exitCode;
}
<commit_msg>Changes: Show widgetsgallery window, after the content is ready for rendering.<commit_after>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of libmeegotouch.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** 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
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/
#include <QProcess>
#include <QStringList>
#include <QObject>
#include <QDebug>
#include <MApplication>
#include <MApplicationService>
#ifdef HAVE_DBUS
#include <MApplicationIfAdaptor>
#endif //HAVE_DBUS
#include <MApplicationWindow>
#include <MApplicationPage>
#include <MAction>
#include <MLocale>
#include <MGConfItem>
#include <MSceneManager>
#include <MComponentCache>
#include "mainpage.h"
#include "timedemo.h"
#include "swaphook.h"
#include "widgetsgalleryretranslator.h"
#include "../../benchmarks/performancebenchmark/emptymainloophelper.h"
class MyApplicationService: public MApplicationService
{
public:
MyApplicationService(QObject *parent = 0) :
MApplicationService("com.nokia.widgetsgallery", parent) {
}
void launch() {
launchAnotherWithQProcess();
}
void handleServiceRegistrationFailure() {
qDebug() << "MyApplicationService::handleServiceRegistrationFailure()";
incrementAndRegister();
}
};
#ifndef Q_OS_WIN
M_EXPORT
#endif
int main(int argc, char **argv)
{
#ifdef M_OS_MAEMO5
QApplication::setGraphicsSystem(QLatin1String("native"));
#endif //M_OS_MAEMO5
//MApplication application(argc, argv, "widgetsgallery", new MyApplicationService() );
MApplication *application = MComponentCache::mApplication(argc, argv);
WidgetsgalleryRetranslator widgetsgalleryRetranslator;
QObject::connect(application, SIGNAL(localeSettingsChanged()), &widgetsgalleryRetranslator, SLOT(widgetsgalleryRetranslate()));
MApplicationWindow* window = MComponentCache::mApplicationWindow();
MainPage *mainPage = new MainPage;
Timedemo *timedemo = 0;
if (qApp->arguments().indexOf("-timedemo") >= 0) {
QStringList demoPages;
int idx = qApp->arguments().indexOf("-demopages");
if (idx >= 0 && idx + 1 < qApp->arguments().count()) {
demoPages = qApp->arguments()[idx + 1].split(',');
}
timedemo = new Timedemo(mainPage, demoPages);
idx = qApp->arguments().indexOf("-outputcsv");
if (idx >= 0 && idx + 1 < qApp->arguments().count()) {
timedemo->setOutputCsv(qApp->arguments()[idx + 1]);
}
idx = qApp->arguments().indexOf("-framelog");
if (idx >= 0 && idx + 1 < qApp->arguments().count()) {
timedemo->setFramelog(qApp->arguments()[idx + 1]);
}
}
int index = qApp->arguments().indexOf("-initialpage");
if (index >= 0) {
if (index + 1 < qApp->arguments().count()) {
mainPage->setInitialPageToShow(qApp->arguments()[index + 1]);
}
}
EmptyMainLoopHelper mainLoopHelper;
// -quitimmediately will create fully the content of the main page
// -exitimmediately will skip creating the content of the main page
if (qApp->arguments().indexOf("-quitimmediately") >= 0 || qApp->arguments().indexOf("-exitimmediately") >= 0) {
// terminate widgetsgallery as soon as the content is shown and main loop is idle
mainPage->setMainLoopHelper(&mainLoopHelper);
mainLoopHelper.triggerTermination(EmptyMainLoopHelper::QuitOnEmpty);
}
window->sceneManager()->appearSceneWindowNow(mainPage);
window->show();
int exitCode = application->exec();
delete timedemo;
delete mainPage;
delete window;
delete application;
return exitCode;
}
<|endoftext|>
|
<commit_before>//-----------------------------------------------------------------------
// Copyright 2011 Ciaran McHale.
//
// 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 "SchemaTypeTable.h"
#include "Common.h"
namespace CONFIG4CPP_NAMESPACE {
void
SchemaTypeTable::checkRule(
const SchemaValidator * sv,
const Configuration * cfg,
const char * typeName,
const StringVector & typeArgs,
const char * rule) const throw(ConfigurationException)
{
unused(cfg);
StringBuffer msg;
int i;
const char * columnType;
SchemaType * typeDef;
//--------
// Check there is at least one pair of column-type, column-name
// arguments.
//--------
int len = typeArgs.length();
if ((len == 0) || (len % 2 != 0)) {
msg << "the '" << typeName << "' type requires pairs of column-type "
<< "and column-name arguments in " << "rule '" << rule << "'";
throw ConfigurationException(msg.c_str());
}
//--------
// Check that all the column-type arguments are valid types.
//--------
for (i = 0; i < len; i+=2) {
columnType = typeArgs[i+0];
typeDef = findType(sv, columnType);
if (typeDef == 0) {
msg << "unknown type '" << columnType << "' in rule '"
<< rule << "'";
throw ConfigurationException(msg.c_str());
}
switch (typeDef->cfgType()) {
case Configuration::CFG_STRING:
break;
case Configuration::CFG_LIST:
msg << "you cannot embed a list type ('" << columnType
<< "') inside a table in rule '" << rule << "'";
throw ConfigurationException(msg.c_str());
case Configuration::CFG_SCOPE:
msg << "you cannot embed a scope type ('" << columnType
<< "') inside a table in rule '" << rule << "'";
throw ConfigurationException(msg.c_str());
default:
assert(0); // Bug!
}
}
}
void
SchemaTypeTable::validate(
const SchemaValidator * sv,
const Configuration * cfg,
const char * scope,
const char * name,
const char * typeName,
const char * origTypeName,
const StringVector & typeArgs,
int indentLevel) const
throw(ConfigurationException)
{
unused(origTypeName);
StringBuffer msg;
StringBuffer errSuffix;
StringBuffer fullyScopedName;
const char ** list;
const char * colValue;
const char * colTypeName;
int i;
int listSize;
int typeArgsSize;
int colNameIndex;
int typeIndex;
int rowNum;
int numColumns;
SchemaType * colTypeDef;
StringVector emptyArgs;
bool ok;
const char * sep;
//--------
// Check that the length of the list is a multiple of the number
// of columns in the table.
//--------
typeArgsSize = typeArgs.length();
assert(typeArgsSize != 0);
assert(typeArgsSize % 2 == 0);
numColumns = typeArgsSize / 2;
cfg->lookupList(scope, name, list, listSize);
if (listSize % numColumns != 0) {
cfg->mergeNames(scope, name, fullyScopedName);
msg << cfg->fileName() << ": the number of entries in the '"
<< fullyScopedName << "' " << typeName
<< " is not a multiple of " << numColumns;
throw ConfigurationException(msg.c_str());
}
//--------
// Check each item in the list is of the type specified for its column
//--------
for (i = 0; i < listSize; i++) {
typeIndex = (i * 2 + 0) % typeArgsSize;
colNameIndex = (i * 2 + 1) % typeArgsSize;
rowNum = (i / numColumns) + 1;
colValue = list[i];
colTypeName = typeArgs[typeIndex];
colTypeDef = findType(sv, colTypeName);
ok = callIsA(colTypeDef, sv, cfg, colValue, colTypeName, emptyArgs,
indentLevel + 1, errSuffix);
if (!ok) {
if (errSuffix.length() == 0) {
sep = "";
} else {
sep = "; ";
}
cfg->mergeNames(scope, name, fullyScopedName);
msg << cfg->fileName() << ": bad " << colTypeName << " value ('"
<< colValue << "') for the '" << typeArgs[colNameIndex]
<< "' column in row " << rowNum << " of the '"
<< fullyScopedName << "' " << typeName << sep << errSuffix;
throw ConfigurationException(msg.c_str());
}
}
}
} // namespace CONFIG4CPP_NAMESPACE
<commit_msg>Fixes.<commit_after>//-----------------------------------------------------------------------
// Copyright 2011 Ciaran McHale.
//
// 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 "SchemaTypeTable.h"
#include "Common.h"
namespace CONFIG4CPP_NAMESPACE {
void
SchemaTypeTable::checkRule(
const SchemaValidator * sv,
const Configuration * cfg,
const char * typeName,
const StringVector & typeArgs,
const char * rule) const throw(ConfigurationException)
{
unused(cfg);
StringBuffer msg;
//--------
// Check there is at least one pair of column-type, column-name
// arguments.
//--------
int len = typeArgs.length();
if ((len == 0) || (len % 2 != 0)) {
msg << "the '" << typeName << "' type requires pairs of column-type "
<< "and column-name arguments in " << "rule '" << rule << "'";
throw ConfigurationException(msg.c_str());
}
//--------
// Check that all the column-type arguments are valid types.
//--------
for (int i = 0; i < len; i+=2) {
const char* columnType = typeArgs[i+0];
SchemaType* typeDef = findType(sv, columnType);
if (typeDef == 0) {
msg << "unknown type '" << columnType << "' in rule '"
<< rule << "'";
throw ConfigurationException(msg.c_str());
}
switch (typeDef->cfgType()) {
case Configuration::CFG_STRING:
break;
case Configuration::CFG_LIST:
msg << "you cannot embed a list type ('" << columnType
<< "') inside a table in rule '" << rule << "'";
throw ConfigurationException(msg.c_str());
case Configuration::CFG_SCOPE:
msg << "you cannot embed a scope type ('" << columnType
<< "') inside a table in rule '" << rule << "'";
throw ConfigurationException(msg.c_str());
default:
assert(0); // Bug!
}
}
}
void
SchemaTypeTable::validate(
const SchemaValidator * sv,
const Configuration * cfg,
const char * scope,
const char * name,
const char * typeName,
const char * origTypeName,
const StringVector & typeArgs,
int indentLevel) const
throw(ConfigurationException)
{
unused(origTypeName);
StringBuffer msg;
StringBuffer errSuffix;
StringBuffer fullyScopedName;
const char ** list;
int listSize;
StringVector emptyArgs;
//--------
// Check that the length of the list is a multiple of the number
// of columns in the table.
//--------
int typeArgsSize = typeArgs.length();
assert(typeArgsSize != 0);
assert(typeArgsSize % 2 == 0);
int numColumns = typeArgsSize / 2;
cfg->lookupList(scope, name, list, listSize);
if (listSize % numColumns != 0) {
cfg->mergeNames(scope, name, fullyScopedName);
msg << cfg->fileName() << ": the number of entries in the '"
<< fullyScopedName << "' " << typeName
<< " is not a multiple of " << numColumns;
throw ConfigurationException(msg.c_str());
}
//--------
// Check each item in the list is of the type specified for its column
//--------
for (int i = 0; i < listSize; i++) {
int typeIndex = (i * 2 + 0) % typeArgsSize;
int colNameIndex = (i * 2 + 1) % typeArgsSize;
int rowNum = (i / numColumns) + 1;
const char* colValue = list[i];
const char* colTypeName = typeArgs[typeIndex];
SchemaType* colTypeDef = findType(sv, colTypeName);
bool ok = callIsA(colTypeDef, sv, cfg, colValue, colTypeName, emptyArgs,
indentLevel + 1, errSuffix);
if (!ok) {
const char* sep;
if (errSuffix.length() == 0) {
sep = "";
} else {
sep = "; ";
}
cfg->mergeNames(scope, name, fullyScopedName);
msg << cfg->fileName() << ": bad " << colTypeName << " value ('"
<< colValue << "') for the '" << typeArgs[colNameIndex]
<< "' column in row " << rowNum << " of the '"
<< fullyScopedName << "' " << typeName << sep << errSuffix;
throw ConfigurationException(msg.c_str());
}
}
}
} // namespace CONFIG4CPP_NAMESPACE
<|endoftext|>
|
<commit_before>// SetWorkspaceName.cc for Fluxbox
// Copyright (c) 2003 Henrik Kinnunen (fluxgen(at)users.sourceforge.net)
//
// 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.
// $Id: SetWorkspaceName.cc,v 1.2 2003/08/27 18:05:12 fluxgen Exp $
#include "SetWorkspaceName.hh"
#include "Screen.hh"
#include "Workspace.hh"
#include "WinClient.hh"
#include "FbWinFrameTheme.hh"
#include "FbTk/EventManager.hh"
#include "FbTk/App.hh"
#include <X11/keysym.h>
#include <X11/Xutil.h>
#include <iostream>
using namespace std;
SetWorkspaceName::SetWorkspaceName(BScreen &screen):
FbWindow(screen.rootWindow().screenNumber(),
0, 0, 1, 1, 0),
m_textbox(*this, m_font, screen.currentWorkspace()->name()),
m_label(*this, m_font, "Set workspace name:"),
m_font("fixed"),
m_gc(m_textbox),
m_screen(screen),
m_move_x(0),
m_move_y(0) {
m_label.setGC(screen.winFrameTheme().labelTextFocusGC());
m_label.setBackgroundColor(screen.winFrameTheme().labelFocusTexture().color());
m_label.moveResize(0, 0,
200, m_font.height() + 2);
m_label.setEventMask(m_label.eventMask() | ButtonPressMask | ButtonMotionMask); // we listen to motion notify too
m_label.show();
m_textbox.setBackgroundColor(FbTk::Color("white", m_textbox.screenNumber()));
FbTk::Color black("black", m_textbox.screenNumber());
m_gc.setForeground(black);
m_textbox.setGC(m_gc.gc());
m_textbox.moveResize(0, m_label.height(),
200, m_font.height() + 2);
m_textbox.show();
resize(200, m_textbox.height() + m_label.height());
// move to center of the screen
move((screen.width() - width())/2, (screen.height() - height())/2);
// we need ConfigureNotify from children
FbTk::EventManager::instance()->addParent(*this, *this);
}
SetWorkspaceName::~SetWorkspaceName() {
FbTk::EventManager::instance()->remove(*this);
hide();
}
void SetWorkspaceName::show() {
FbTk::FbWindow::show();
m_textbox.setInputFocus();
m_textbox.setText(m_screen.currentWorkspace()->name());
m_textbox.clear();
m_label.clear();
}
void SetWorkspaceName::hide() {
FbTk::FbWindow::hide();
// return focus to fluxbox window
if (Fluxbox::instance()->getFocusedWindow() &&
Fluxbox::instance()->getFocusedWindow()->fbwindow())
Fluxbox::instance()->getFocusedWindow()->fbwindow()->setInputFocus();
}
void SetWorkspaceName::buttonPressEvent(XButtonEvent &event) {
m_textbox.setInputFocus();
m_move_x = event.x_root - x();
m_move_y = event.y_root - y();
}
void SetWorkspaceName::handleEvent(XEvent &event) {
if (event.type == ConfigureNotify && event.xconfigure.window != window()) {
moveResize(event.xconfigure.x, event.xconfigure.y,
event.xconfigure.width, event.xconfigure.height);
} else if (event.type == DestroyNotify)
delete this;
}
void SetWorkspaceName::motionNotifyEvent(XMotionEvent &event) {
int new_x = event.x_root - m_move_x;
int new_y = event.y_root - m_move_y;
move(new_x, new_y);
}
void SetWorkspaceName::keyPressEvent(XKeyEvent &event) {
if (event.state)
return;
KeySym ks;
char keychar[1];
XLookupString(&event, keychar, 1, &ks, 0);
if (ks == XK_Return) {
m_screen.currentWorkspace()->setName(m_textbox.text());
m_screen.updateWorkspaceNamesAtom();
Fluxbox::instance()->save_rc();
delete this; // end this
} else if (ks == XK_Escape)
delete this; // end this
}
<commit_msg>minor fix<commit_after>// SetWorkspaceName.cc for Fluxbox
// Copyright (c) 2003 Henrik Kinnunen (fluxgen(at)users.sourceforge.net)
//
// 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.
// $Id: SetWorkspaceName.cc,v 1.3 2003/12/19 00:47:55 fluxgen Exp $
#include "SetWorkspaceName.hh"
#include "Screen.hh"
#include "Workspace.hh"
#include "WinClient.hh"
#include "FbWinFrameTheme.hh"
#include "fluxbox.hh"
#include "FbTk/EventManager.hh"
#include "FbTk/App.hh"
#include <X11/keysym.h>
#include <X11/Xutil.h>
#include <iostream>
using namespace std;
SetWorkspaceName::SetWorkspaceName(BScreen &screen):
FbWindow(screen.rootWindow().screenNumber(),
0, 0, 1, 1, 0),
m_textbox(*this, m_font, screen.currentWorkspace()->name()),
m_label(*this, m_font, "Set workspace name:"),
m_font("fixed"),
m_gc(m_textbox),
m_screen(screen),
m_move_x(0),
m_move_y(0) {
m_label.setGC(screen.winFrameTheme().labelTextFocusGC());
m_label.setBackgroundColor(screen.winFrameTheme().labelFocusTexture().color());
m_label.moveResize(0, 0,
200, m_font.height() + 2);
m_label.setEventMask(m_label.eventMask() | ButtonPressMask | ButtonMotionMask); // we listen to motion notify too
m_label.show();
m_textbox.setBackgroundColor(FbTk::Color("white", m_textbox.screenNumber()));
FbTk::Color black("black", m_textbox.screenNumber());
m_gc.setForeground(black);
m_textbox.setGC(m_gc.gc());
m_textbox.moveResize(0, m_label.height(),
200, m_font.height() + 2);
m_textbox.show();
resize(200, m_textbox.height() + m_label.height());
// move to center of the screen
move((screen.width() - width())/2, (screen.height() - height())/2);
// we need ConfigureNotify from children
FbTk::EventManager::instance()->addParent(*this, *this);
}
SetWorkspaceName::~SetWorkspaceName() {
FbTk::EventManager::instance()->remove(*this);
hide();
}
void SetWorkspaceName::show() {
FbTk::FbWindow::show();
m_textbox.setInputFocus();
m_textbox.setText(m_screen.currentWorkspace()->name());
m_textbox.clear();
m_label.clear();
}
void SetWorkspaceName::hide() {
FbTk::FbWindow::hide();
// return focus to fluxbox window
if (Fluxbox::instance()->getFocusedWindow() &&
Fluxbox::instance()->getFocusedWindow()->fbwindow())
Fluxbox::instance()->getFocusedWindow()->fbwindow()->setInputFocus();
}
void SetWorkspaceName::buttonPressEvent(XButtonEvent &event) {
m_textbox.setInputFocus();
m_move_x = event.x_root - x();
m_move_y = event.y_root - y();
}
void SetWorkspaceName::handleEvent(XEvent &event) {
if (event.type == ConfigureNotify && event.xconfigure.window != window()) {
moveResize(event.xconfigure.x, event.xconfigure.y,
event.xconfigure.width, event.xconfigure.height);
} else if (event.type == DestroyNotify)
delete this;
}
void SetWorkspaceName::motionNotifyEvent(XMotionEvent &event) {
int new_x = event.x_root - m_move_x;
int new_y = event.y_root - m_move_y;
move(new_x, new_y);
}
void SetWorkspaceName::keyPressEvent(XKeyEvent &event) {
if (event.state)
return;
KeySym ks;
char keychar[1];
XLookupString(&event, keychar, 1, &ks, 0);
if (ks == XK_Return) {
m_screen.currentWorkspace()->setName(m_textbox.text());
m_screen.updateWorkspaceNamesAtom();
Fluxbox::instance()->save_rc();
delete this; // end this
} else if (ks == XK_Escape)
delete this; // end this
}
<|endoftext|>
|
<commit_before>/*
* author: Max Kellermann <mk@cm4all.com>
*/
#ifndef BENG_PROXY_SLICE_FIFO_BUFFER_HXX
#define BENG_PROXY_SLICE_FIFO_BUFFER_HXX
#include "socket_wrapper.hxx"
#include "util/ForeignFifoBuffer.hxx"
#include <stdint.h>
struct SlicePool;
struct SliceArea;
class SliceFifoBuffer : public ForeignFifoBuffer<uint8_t> {
SliceArea *area;
public:
SliceFifoBuffer():ForeignFifoBuffer<uint8_t>(nullptr) {}
SliceFifoBuffer(SlicePool &pool)
:ForeignFifoBuffer<uint8_t>(nullptr) {
Allocate(pool);
}
void Swap(SliceFifoBuffer &other) {
ForeignFifoBuffer<uint8_t>::Swap(other);
std::swap(area, other.area);
}
void Allocate(SlicePool &pool);
void Free(SlicePool &pool);
bool IsDefinedAndFull() const {
return IsDefined() && IsFull();
}
void AllocateIfNull(SlicePool &pool) {
if (IsNull())
Allocate(pool);
}
void FreeIfDefined(SlicePool &pool) {
if (IsDefined())
Free(pool);
}
void FreeIfEmpty(SlicePool &pool) {
if (IsEmpty())
FreeIfDefined(pool);
}
/**
* Move as much data as possible from the specified buffer. If
* the destination buffer is empty, the buffers are swapped. Care
* is taken that neither buffer suddenly becomes nulled
* afterwards, because some callers may not be prepared for this.
*/
void MoveFrom(SliceFifoBuffer &src) {
if (IsEmpty() && !IsNull() && !src.IsNull())
/* optimized special case: swap buffer pointers instead of
copying data */
Swap(src);
else
ForeignFifoBuffer<uint8_t>::MoveFrom(src);
}
/**
* Like MoveFrom(), but allow the destination to be nulled. This
* is useful when #src can be freed, but this object cannot.
*/
void MoveFromAllowNull(SliceFifoBuffer &src) {
if (IsEmpty() && (!src.IsEmpty() || !IsNull()))
/* optimized special case: swap buffer pointers instead of
copying data */
Swap(src);
else
ForeignFifoBuffer<uint8_t>::MoveFrom(src);
}
/**
* Swaps the two buffers if #src is nulled. This is useful when
* #src can be freed, but this object cannot.
*/
void SwapIfNull(SliceFifoBuffer &src) {
if (src.IsNull() && IsEmpty() && !IsNull())
Swap(src);
}
};
#endif
<commit_msg>SliceFifoBuffer: add method CycleIfEmpty()<commit_after>/*
* author: Max Kellermann <mk@cm4all.com>
*/
#ifndef BENG_PROXY_SLICE_FIFO_BUFFER_HXX
#define BENG_PROXY_SLICE_FIFO_BUFFER_HXX
#include "socket_wrapper.hxx"
#include "util/ForeignFifoBuffer.hxx"
#include <stdint.h>
struct SlicePool;
struct SliceArea;
class SliceFifoBuffer : public ForeignFifoBuffer<uint8_t> {
SliceArea *area;
public:
SliceFifoBuffer():ForeignFifoBuffer<uint8_t>(nullptr) {}
SliceFifoBuffer(SlicePool &pool)
:ForeignFifoBuffer<uint8_t>(nullptr) {
Allocate(pool);
}
void Swap(SliceFifoBuffer &other) {
ForeignFifoBuffer<uint8_t>::Swap(other);
std::swap(area, other.area);
}
void Allocate(SlicePool &pool);
void Free(SlicePool &pool);
bool IsDefinedAndFull() const {
return IsDefined() && IsFull();
}
void AllocateIfNull(SlicePool &pool) {
if (IsNull())
Allocate(pool);
}
void FreeIfDefined(SlicePool &pool) {
if (IsDefined())
Free(pool);
}
void FreeIfEmpty(SlicePool &pool) {
if (IsEmpty())
FreeIfDefined(pool);
}
/**
* If this buffer is empty, free the buffer and reallocate a new
* one. This is useful to work around #SliceArea fragmentation.
*/
void CycleIfEmpty(SlicePool &pool) {
if (IsDefined() && IsEmpty()) {
Free(pool);
Allocate(pool);
}
}
/**
* Move as much data as possible from the specified buffer. If
* the destination buffer is empty, the buffers are swapped. Care
* is taken that neither buffer suddenly becomes nulled
* afterwards, because some callers may not be prepared for this.
*/
void MoveFrom(SliceFifoBuffer &src) {
if (IsEmpty() && !IsNull() && !src.IsNull())
/* optimized special case: swap buffer pointers instead of
copying data */
Swap(src);
else
ForeignFifoBuffer<uint8_t>::MoveFrom(src);
}
/**
* Like MoveFrom(), but allow the destination to be nulled. This
* is useful when #src can be freed, but this object cannot.
*/
void MoveFromAllowNull(SliceFifoBuffer &src) {
if (IsEmpty() && (!src.IsEmpty() || !IsNull()))
/* optimized special case: swap buffer pointers instead of
copying data */
Swap(src);
else
ForeignFifoBuffer<uint8_t>::MoveFrom(src);
}
/**
* Swaps the two buffers if #src is nulled. This is useful when
* #src can be freed, but this object cannot.
*/
void SwapIfNull(SliceFifoBuffer &src) {
if (src.IsNull() && IsEmpty() && !IsNull())
Swap(src);
}
};
#endif
<|endoftext|>
|
<commit_before>/*
* author: Max Kellermann <mk@cm4all.com>
*/
#ifndef BENG_PROXY_SLICE_FIFO_BUFFER_HXX
#define BENG_PROXY_SLICE_FIFO_BUFFER_HXX
#include "socket_wrapper.hxx"
#include "util/ForeignFifoBuffer.hxx"
#include <stdint.h>
class SliceFifoBuffer : public ForeignFifoBuffer<uint8_t> {
struct slice_area *area;
public:
SliceFifoBuffer():ForeignFifoBuffer<uint8_t>(nullptr) {}
SliceFifoBuffer(struct slice_pool &pool)
:ForeignFifoBuffer<uint8_t>(nullptr) {
Allocate(pool);
}
void Allocate(struct slice_pool &pool);
void Free(struct slice_pool &pool);
bool IsDefinedAndFull() const {
return IsDefined() && IsFull();
}
void AllocateIfNull(struct slice_pool &pool) {
if (IsNull())
Allocate(pool);
}
void FreeIfDefined(struct slice_pool &pool) {
if (IsDefined())
Free(pool);
}
void FreeIfEmpty(struct slice_pool &pool) {
if (IsEmpty())
FreeIfDefined(pool);
}
};
#endif
<commit_msg>SliceFifoBuffer: add method Swap()<commit_after>/*
* author: Max Kellermann <mk@cm4all.com>
*/
#ifndef BENG_PROXY_SLICE_FIFO_BUFFER_HXX
#define BENG_PROXY_SLICE_FIFO_BUFFER_HXX
#include "socket_wrapper.hxx"
#include "util/ForeignFifoBuffer.hxx"
#include <stdint.h>
class SliceFifoBuffer : public ForeignFifoBuffer<uint8_t> {
struct slice_area *area;
public:
SliceFifoBuffer():ForeignFifoBuffer<uint8_t>(nullptr) {}
SliceFifoBuffer(struct slice_pool &pool)
:ForeignFifoBuffer<uint8_t>(nullptr) {
Allocate(pool);
}
void Swap(SliceFifoBuffer &other) {
ForeignFifoBuffer<uint8_t>::Swap(other);
std::swap(area, other.area);
}
void Allocate(struct slice_pool &pool);
void Free(struct slice_pool &pool);
bool IsDefinedAndFull() const {
return IsDefined() && IsFull();
}
void AllocateIfNull(struct slice_pool &pool) {
if (IsNull())
Allocate(pool);
}
void FreeIfDefined(struct slice_pool &pool) {
if (IsDefined())
Free(pool);
}
void FreeIfEmpty(struct slice_pool &pool) {
if (IsEmpty())
FreeIfDefined(pool);
}
};
#endif
<|endoftext|>
|
<commit_before>#pragma once
#include "../StandardInclude.hpp"
#include "../EntityInclude.hpp"
#include "../StateInterface.hpp"
class GameTitle : public StateInterface
{
public: static GameTitle &GetInstance(void) { static auto instance = GameTitle(); return instance; }
private: GameTitle() { }
private:
bool IsInitial = true;
int logoHandle;
public:
// 場面名を取得します
string StateName()
{
return "Title";
}
// 更新(ターゲット時のみ)
void Update()
{
if (IsInitial)
{
IsInitial = false;
logoHandle = LoadGraph("Image/logo.png", 1);
}
}
// 描画(常時)
void Draw()
{
if (Core::GetInstance().GetNowStateName() == StateName())
{
int temp[2];
GetGraphSize(logoHandle, &temp[0], &temp[1]);
Point imageRightBottom = Point(temp[0], temp[1]);
Size screenSize = Core::GetInstance().ScreenSize;
Point screenRightBottom = Point(screenSize.GetWidth(), screenSize.GetHeight());
Point location = screenRightBottom / 2 - imageRightBottom / 2;
location.AddY(-150);
DrawGraph(location.GetX(), location.GetY(), logoHandle, 1);
}
}
};<commit_msg>Fix to cast Size to Point<commit_after>#pragma once
#include "../StandardInclude.hpp"
#include "../EntityInclude.hpp"
#include "../StateInterface.hpp"
class GameTitle : public StateInterface
{
public: static GameTitle &GetInstance(void) { static auto instance = GameTitle(); return instance; }
private: GameTitle() { }
private:
bool IsInitial = true;
int logoHandle;
public:
// 場面名を取得します
string StateName()
{
return "Title";
}
// 更新(ターゲット時のみ)
void Update()
{
if (IsInitial)
{
IsInitial = false;
logoHandle = LoadGraph("Image/logo.png", 1);
}
}
// 描画(常時)
void Draw()
{
if (Core::GetInstance().GetNowStateName() == StateName())
{
int temp[2];
GetGraphSize(logoHandle, &temp[0], &temp[1]);
Point imageRightBottom = Point(temp[0], temp[1]);
Point screenRightBottom = (Point)Core::GetInstance().ScreenSize;
Point location = screenRightBottom / 2 - imageRightBottom / 2;
location.AddY(-150);
DrawGraph(location.GetX(), location.GetY(), logoHandle, 1);
}
}
};<|endoftext|>
|
<commit_before>/*
* System_fileSync.cpp
*
* Created on: Jun 24, 2014
* Author: Pimenta
*/
// this
#include "System.hpp"
// local
#include "Defines.hpp"
#include "FD8Protocol.hpp"
#include "FileSystem.hpp"
using namespace std;
using namespace helpers;
using namespace concurrency;
using namespace network;
using namespace fd8protocol;
void System::send_createFile(const string& fullPath, const ByteQueue& info) {
Thread([this, fullPath, info]() {
set<uint32_t> peers;
for (auto& kv : users) {
peers.insert(kv.first);
if (kv.first == localAddress.ip)
continue;
TCPConnection conn(Address(kv.first, Address("", TCPUDP_MAIN).port));
conn.send(char(MTYPE_CREATE_FILE));
conn.send(fullPath);
conn.send(uint32_t(info.size()));
conn.send(info);
}
FileSystem::initTmpFileSystem();
list<FileSystem::Command*> cmds = FileSystem::calculateDuplications(peers);
list<FileSystem::Command*> balCmds = FileSystem::calculateBalance(peers);
for (auto& cmd : balCmds)
cmds.push_back(cmd);
ByteQueue data = FileSystem::Command::serialize(cmds);
for (auto& kv : users) {
if (kv.first == localAddress.ip)
continue;
TCPConnection conn(Address(kv.first, Address("", TCPUDP_MAIN).port));
conn.send(char(MTYPE_COMMANDS));
conn.send(uint32_t(data.size()));
conn.send(data);
}
send_files(cmds);
FileSystem::processCommands(cmds);
for (auto& cmd : cmds)
delete cmd;
}).start();
}
void System::send_updateFile(const string& fullPath, const string& newName) {
Thread([this, fullPath, newName]() {
for (auto& kv : users) {
if (kv.first == localAddress.ip)
continue;
TCPConnection conn(Address(kv.first, Address("", TCPUDP_MAIN).port));
conn.send(char(MTYPE_UPDATE_FILE));
conn.send(fullPath);
conn.send(newName);
}
}).start();
}
void System::send_deleteFile(const string& fullPath) {
Thread([this, fullPath]() {
set<uint32_t> peers;
for (auto& kv : users) {
peers.insert(kv.first);
if (kv.first == localAddress.ip)
continue;
TCPConnection conn(Address(kv.first, Address("", TCPUDP_MAIN).port));
conn.send(char(MTYPE_DELETE_FILE));
conn.send(fullPath);
}
FileSystem::initTmpFileSystem();
list<FileSystem::Command*> cmds = FileSystem::calculateBalance(peers);
ByteQueue data = FileSystem::Command::serialize(cmds);
for (auto& kv : users) {
if (kv.first == localAddress.ip)
continue;
TCPConnection conn(Address(kv.first, Address("", TCPUDP_MAIN).port));
conn.send(char(MTYPE_COMMANDS));
conn.send(uint32_t(data.size()));
conn.send(data);
}
send_files(cmds);
FileSystem::processCommands(cmds);
for (auto& cmd : cmds)
delete cmd;
}).start();
}
void System::recv_createFile(const string& fullPath, ByteQueue& info) {
FileSystem::createFile(fullPath, info);
}
void System::recv_updateFile(const string& fullPath, const string& newName) {
FileSystem::updateFile(fullPath, newName);
}
void System::recv_deleteFile(const string& fullPath) {
FileSystem::deleteFile(fullPath);
}
void System::send_files(const list<FileSystem::Command*>& cmds) {
for (auto& cmd : cmds) {
if(cmd->type() == MTYPE_CMD_DUPLICATION && ((FileSystem::DuplicationCommand*)cmd)->srcPeer == localAddress.ip) {
FileSystem::DuplicationCommand dupCmd = *((FileSystem::DuplicationCommand*)cmd);
Thread([this, dupCmd]() {
char tmp[25];
char buf[SIZE_FILEBUFFER_MAXLEN];
TCPConnection conn(Address(dupCmd.dstPeer, Address("", TCPUDP_MAIN).port));
sprintf(tmp, "www/files/%08x", dupCmd.fileID);
FILE* fp = fopen(tmp, "rb");
fseek(fp, 0, SEEK_END);
conn.send(char(fd8protocol::MTYPE_FILE));
conn.send(uint32_t(dupCmd.fileID));
conn.send(uint32_t(ftell(fp)));
fclose(fp);
fp = fopen(tmp, "rb");
for (
size_t readBytes;
(readBytes = fread(buf, 1, SIZE_FILEBUFFER_MAXLEN, fp)) > 0 && state == STATE_IDLE;
conn.send(buf, readBytes)
);
fclose(fp);
}).start();
}
else if(cmd->type() == MTYPE_CMD_BALANCING && ((FileSystem::BalancingCommand*)cmd)->srcPeer == localAddress.ip) {
FileSystem::BalancingCommand& balCmd = *((FileSystem::BalancingCommand*)cmd);
string zuera;
FileSystem::File file = *FileSystem::retrieveFolder("/", zuera)->findFile(balCmd.fileID);
Thread([this, balCmd, file]() {
char buf[SIZE_FILEBUFFER_MAXLEN];
// getting file name
char tmp[25];
sprintf(tmp, "www/files/%08x", balCmd.fileID);
// getting file size
FILE* fp = fopen(tmp, "rb");
fseek(fp, 0, SEEK_END);
uint32_t fileSize = ftell(fp);
fclose(fp);
// sending to peer 1
if (balCmd.peer1 != file.peer1 && balCmd.peer1 != file.peer2) {
TCPConnection conn(Address(balCmd.peer1, Address("", TCPUDP_MAIN).port));
conn.send(char(fd8protocol::MTYPE_FILE));
conn.send(uint32_t(balCmd.fileID));
conn.send(fileSize);
fp = fopen(tmp, "rb");
for (
size_t readBytes;
(readBytes = fread(buf, 1, SIZE_FILEBUFFER_MAXLEN, fp)) > 0 && state == STATE_IDLE;
conn.send(buf, readBytes)
);
fclose(fp);
}
// sending to peer 2
if (balCmd.peer2 != file.peer1 && balCmd.peer2 != file.peer2) {
TCPConnection conn(Address(balCmd.peer2, Address("", TCPUDP_MAIN).port));
conn.send(char(fd8protocol::MTYPE_FILE));
conn.send(uint32_t(balCmd.fileID));
conn.send(fileSize);
fp = fopen(tmp, "rb");
for (
size_t readBytes;
(readBytes = fread(buf, 1, SIZE_FILEBUFFER_MAXLEN, fp)) > 0 && state == STATE_IDLE;
conn.send(buf, readBytes)
);
fclose(fp);
}
remove(tmp);
}).start();
}
}
}
<commit_msg>Fixing bug<commit_after>/*
* System_fileSync.cpp
*
* Created on: Jun 24, 2014
* Author: Pimenta
*/
// this
#include "System.hpp"
// local
#include "Defines.hpp"
#include "FD8Protocol.hpp"
#include "FileSystem.hpp"
using namespace std;
using namespace helpers;
using namespace concurrency;
using namespace network;
using namespace fd8protocol;
void System::send_createFile(const string& fullPath, const ByteQueue& info) {
Thread([this, fullPath, info]() {
set<uint32_t> peers;
for (auto& kv : users) {
peers.insert(kv.first);
if (kv.first == localAddress.ip)
continue;
TCPConnection conn(Address(kv.first, Address("", TCPUDP_MAIN).port));
conn.send(char(MTYPE_CREATE_FILE));
conn.send(fullPath);
conn.send(uint32_t(info.size()));
conn.send(info);
}
FileSystem::initTmpFileSystem();
list<FileSystem::Command*> cmds = FileSystem::calculateDuplications(peers);
list<FileSystem::Command*> balCmds = FileSystem::calculateBalance(peers);
for (auto& cmd : balCmds)
cmds.push_back(cmd);
ByteQueue data = FileSystem::Command::serialize(cmds);
for (auto& kv : users) {
if (kv.first == localAddress.ip)
continue;
TCPConnection conn(Address(kv.first, Address("", TCPUDP_MAIN).port));
conn.send(char(MTYPE_COMMANDS));
conn.send(uint32_t(data.size()));
conn.send(data);
}
send_files(cmds);
FileSystem::processCommands(cmds);
for (auto& cmd : cmds)
delete cmd;
}).start();
}
void System::send_updateFile(const string& fullPath, const string& newName) {
Thread([this, fullPath, newName]() {
for (auto& kv : users) {
if (kv.first == localAddress.ip)
continue;
TCPConnection conn(Address(kv.first, Address("", TCPUDP_MAIN).port));
conn.send(char(MTYPE_UPDATE_FILE));
conn.send(fullPath);
conn.send(newName);
}
}).start();
}
void System::send_deleteFile(const string& fullPath) {
Thread([this, fullPath]() {
set<uint32_t> peers;
for (auto& kv : users) {
peers.insert(kv.first);
if (kv.first == localAddress.ip)
continue;
TCPConnection conn(Address(kv.first, Address("", TCPUDP_MAIN).port));
conn.send(char(MTYPE_DELETE_FILE));
conn.send(fullPath);
}
FileSystem::initTmpFileSystem();
list<FileSystem::Command*> cmds = FileSystem::calculateBalance(peers);
ByteQueue data = FileSystem::Command::serialize(cmds);
for (auto& kv : users) {
if (kv.first == localAddress.ip)
continue;
TCPConnection conn(Address(kv.first, Address("", TCPUDP_MAIN).port));
conn.send(char(MTYPE_COMMANDS));
conn.send(uint32_t(data.size()));
conn.send(data);
}
send_files(cmds);
FileSystem::processCommands(cmds);
for (auto& cmd : cmds)
delete cmd;
}).start();
}
void System::recv_createFile(const string& fullPath, ByteQueue& info) {
FileSystem::createFile(fullPath, info);
}
void System::recv_updateFile(const string& fullPath, const string& newName) {
FileSystem::updateFile(fullPath, newName);
}
void System::recv_deleteFile(const string& fullPath) {
FileSystem::deleteFile(fullPath);
}
void System::send_files(const list<FileSystem::Command*>& cmds) {
for (auto& cmd : cmds) {
if(cmd->type() == MTYPE_CMD_DUPLICATION && ((FileSystem::DuplicationCommand*)cmd)->srcPeer == localAddress.ip) {
FileSystem::DuplicationCommand dupCmd = *((FileSystem::DuplicationCommand*)cmd);
Thread([this, dupCmd]() {
char tmp[25];
char buf[SIZE_FILEBUFFER_MAXLEN];
TCPConnection conn(Address(dupCmd.dstPeer, Address("", TCPUDP_MAIN).port));
sprintf(tmp, "www/files/%08x", dupCmd.fileID);
FILE* fp = fopen(tmp, "rb");
fseek(fp, 0, SEEK_END);
conn.send(char(fd8protocol::MTYPE_FILE));
conn.send(uint32_t(dupCmd.fileID));
conn.send(uint32_t(ftell(fp)));
fclose(fp);
fp = fopen(tmp, "rb");
for (
size_t readBytes;
(readBytes = fread(buf, 1, SIZE_FILEBUFFER_MAXLEN, fp)) > 0 && state == STATE_IDLE;
conn.send(buf, readBytes)
);
fclose(fp);
}).start();
}
else if (cmd->type() == MTYPE_CMD_BALANCING) {
FileSystem::BalancingCommand& balCmd = *((FileSystem::BalancingCommand*)cmd);
string zuera;
FileSystem::File file = *FileSystem::retrieveFolder("/", zuera)->findFile(balCmd.fileID);
if (balCmd.srcPeer == localAddress.ip) {
Thread([this, balCmd, file]() {
char buf[SIZE_FILEBUFFER_MAXLEN];
// getting file name
char tmp[25];
sprintf(tmp, "www/files/%08x", balCmd.fileID);
// getting file size
FILE* fp = fopen(tmp, "rb");
fseek(fp, 0, SEEK_END);
uint32_t fileSize = ftell(fp);
fclose(fp);
// sending to peer 1
if (balCmd.peer1 != file.peer1 && balCmd.peer1 != file.peer2) {
TCPConnection conn(Address(balCmd.peer1, Address("", TCPUDP_MAIN).port));
conn.send(char(fd8protocol::MTYPE_FILE));
conn.send(uint32_t(balCmd.fileID));
conn.send(fileSize);
fp = fopen(tmp, "rb");
for (
size_t readBytes;
(readBytes = fread(buf, 1, SIZE_FILEBUFFER_MAXLEN, fp)) > 0 && state == STATE_IDLE;
conn.send(buf, readBytes)
);
fclose(fp);
}
// sending to peer 2
if (balCmd.peer2 != file.peer1 && balCmd.peer2 != file.peer2) {
TCPConnection conn(Address(balCmd.peer2, Address("", TCPUDP_MAIN).port));
conn.send(char(fd8protocol::MTYPE_FILE));
conn.send(uint32_t(balCmd.fileID));
conn.send(fileSize);
fp = fopen(tmp, "rb");
for (
size_t readBytes;
(readBytes = fread(buf, 1, SIZE_FILEBUFFER_MAXLEN, fp)) > 0 && state == STATE_IDLE;
conn.send(buf, readBytes)
);
fclose(fp);
}
remove(tmp);
}).start();
}
else if ((file.peer1 == localAddress.ip || file.peer2 == localAddress.ip) && balCmd.peer1 != localAddress.ip && balCmd.peer2 != localAddress.ip) {
char tmp[25];
sprintf(tmp, "www/files/%08x", balCmd.fileID);
remove(tmp);
}
}
}
}
<|endoftext|>
|
<commit_before>#include "ImageRenderer.hpp"
#include "FAST/Exception.hpp"
#include "FAST/DeviceManager.hpp"
#include "FAST/Utility.hpp"
#include "FAST/SceneGraph.hpp"
#if defined(__APPLE__) || defined(__MACOSX)
#include <OpenCL/cl_gl.h>
#include <OpenGL/gl.h>
#include <OpenGL/OpenGL.h>
#else
#if _WIN32
#include <GL/gl.h>
#include <CL/cl_gl.h>
#else
#include <GL/glx.h>
#include <CL/cl_gl.h>
#endif
#endif
#include <boost/thread/lock_guard.hpp>
using namespace fast;
#ifndef GL_RGBA32F // this is missing on windows and mac for some reason
#define GL_RGBA32F 0x8814
#endif
void ImageRenderer::execute() {
boost::lock_guard<boost::mutex> lock(mMutex);
// This simply gets the input data for each connection and puts it into a data structure
for(uint inputNr = 0; inputNr < getNrOfInputData(); inputNr++) {
Image::pointer input = getStaticInputData<Image>(inputNr);
mImagesToRender[inputNr] = input;
}
}
void ImageRenderer::addInputConnection(ProcessObjectPort port) {
uint nr = getNrOfInputData();
if(nr > 0)
createInputPort<Image>(nr);
releaseInputAfterExecute(nr, false);
setInputConnection(nr, port);
}
ImageRenderer::ImageRenderer() : Renderer() {
createInputPort<Image>(0, false);
createOpenCLProgram(std::string(FAST_SOURCE_DIR) + "/Visualization/ImageRenderer/ImageRenderer.cl", "3D");
createOpenCLProgram(std::string(FAST_SOURCE_DIR) + "/Visualization/ImageRenderer/ImageRenderer2D.cl", "2D");
mIsModified = false;
}
void ImageRenderer::draw() {
boost::lock_guard<boost::mutex> lock(mMutex);
boost::unordered_map<uint, Image::pointer>::iterator it;
for(it = mImagesToRender.begin(); it != mImagesToRender.end(); it++) {
Image::pointer input = it->second;
uint inputNr = it->first;
// Check if a texture has already been created for this image
if(mTexturesToRender.count(inputNr) > 0 && mImageUsed[inputNr] == input)
continue; // If it has already been created, skip it
// If it has not been created, create the texture
// Determine level and window
float window = mWindow;
float level = mLevel;
// If mWindow/mLevel is equal to -1 use default level/window values
if(window == -1) {
window = getDefaultIntensityWindow(input->getDataType());
}
if(level == -1) {
level = getDefaultIntensityLevel(input->getDataType());
}
OpenCLDevice::pointer device = getMainDevice();
OpenCLImageAccess::pointer access = input->getOpenCLImageAccess(ACCESS_READ, device);
cl::Image2D* clImage = access->get2DImage();
glEnable(GL_TEXTURE_2D);
if(mTexturesToRender.count(inputNr) > 0) {
// Delete old texture
glDeleteTextures(1, &mTexturesToRender[inputNr]);
mTexturesToRender.erase(inputNr);
}
// Create OpenGL texture
GLuint textureID;
glGenTextures(1, &textureID);
glBindTexture(GL_TEXTURE_2D, textureID);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, clImage->getImageInfo<CL_IMAGE_WIDTH>(), clImage->getImageInfo<CL_IMAGE_HEIGHT>(), 0, GL_RGBA, GL_FLOAT, 0);
glBindTexture(GL_TEXTURE_2D, 0);
glFinish();
mTexturesToRender[inputNr] = textureID;
mImageUsed[inputNr] = input;
// Create CL-GL image
#if defined(CL_VERSION_1_2)
cl::ImageGL mImageGL = cl::ImageGL(
device->getContext(),
CL_MEM_READ_WRITE,
GL_TEXTURE_2D,
0,
textureID
);
#else
cl::Image2DGL mImageGL = cl::Image2DGL(
device->getContext(),
CL_MEM_READ_WRITE,
GL_TEXTURE_2D,
0,
textureID
);
#endif
std::string kernelName = "renderToTextureInt";
if(input->getDataType() == TYPE_FLOAT) {
kernelName = "renderToTextureFloat";
} else if(input->getDataType() == TYPE_UINT8 || input->getDataType() == TYPE_UINT16) {
kernelName = "renderToTextureUint";
}
mKernel = cl::Kernel(getOpenCLProgram(device, "3D"), kernelName.c_str());
// Run kernel to fill the texture
cl::CommandQueue queue = device->getCommandQueue();
std::vector<cl::Memory> v;
v.push_back(mImageGL);
queue.enqueueAcquireGLObjects(&v);
mKernel.setArg(0, *clImage);
mKernel.setArg(1, mImageGL);
mKernel.setArg(2, level);
mKernel.setArg(3, window);
queue.enqueueNDRangeKernel(
mKernel,
cl::NullRange,
cl::NDRange(clImage->getImageInfo<CL_IMAGE_WIDTH>(), clImage->getImageInfo<CL_IMAGE_HEIGHT>()),
cl::NullRange
);
queue.enqueueReleaseGLObjects(&v);
queue.finish();
}
// This is the actual rendering
for(it = mImageUsed.begin(); it != mImageUsed.end(); it++) {
glPushMatrix();
AffineTransformation transform = SceneGraph::getAffineTransformationFromData(it->second);
transform.scale(it->second->getSpacing()); // Apply image spacing
glMultMatrixf(transform.data());
glBindTexture(GL_TEXTURE_2D, mTexturesToRender[it->first]);
uint width = it->second->getWidth();
uint height = it->second->getHeight();
glColor3f(1,1,1); // black white texture
glBegin(GL_QUADS);
glTexCoord2i(0, 0);
glVertex3f(0, height, 0.0f);
glTexCoord2i(1, 0);
glVertex3f(width, height, 0.0f);
glTexCoord2i(1, 1);
glVertex3f(width, 0, 0.0f);
glTexCoord2i(0, 1);
glVertex3f(0, 0, 0.0f);
glEnd();
glBindTexture(GL_TEXTURE_2D, 0);
glPopMatrix();
}
}
void ImageRenderer::draw2D(cl::BufferGL PBO, uint width, uint height, Eigen::Transform<float, 3, Eigen::Affine> pixelToViewportTransform, float PBOspacing, Vector2f translation) {
boost::lock_guard<boost::mutex> lock(mMutex);
OpenCLDevice::pointer device = getMainDevice();
cl::CommandQueue queue = device->getCommandQueue();
std::vector<cl::Memory> v;
v.push_back(PBO);
queue.enqueueAcquireGLObjects(&v);
// Create an aux PBO
cl::Buffer PBO2(
device->getContext(),
CL_MEM_READ_WRITE,
sizeof(float)*width*height*4
);
boost::unordered_map<uint, Image::pointer>::iterator it;
for(it = mImagesToRender.begin(); it != mImagesToRender.end(); it++) {
Image::pointer input = it->second;
// Determine level and window
float window = mWindow;
float level = mLevel;
// If mWindow/mLevel is equal to -1 use default level/window values
if(window == -1) {
window = getDefaultIntensityWindow(input->getDataType());
}
if(level == -1) {
level = getDefaultIntensityLevel(input->getDataType());
}
if(input->getDimensions() == 2) {
cl::Kernel kernel(getOpenCLProgram(device, "2D"), "render2Dimage");
// Run kernel to fill the texture
OpenCLImageAccess::pointer access = input->getOpenCLImageAccess(ACCESS_READ, device);
cl::Image2D* clImage = access->get2DImage();
kernel.setArg(0, *clImage);
kernel.setArg(1, PBO); // Read from this
kernel.setArg(2, PBO2); // Write to this
kernel.setArg(3, input->getSpacing().x());
kernel.setArg(4, input->getSpacing().y());
kernel.setArg(5, PBOspacing);
kernel.setArg(6, level);
kernel.setArg(7, window);
kernel.setArg(8, translation.x());
kernel.setArg(9, translation.y());
// Run the draw 2D kernel
device->getCommandQueue().enqueueNDRangeKernel(
kernel,
cl::NullRange,
cl::NDRange(width, height),
cl::NullRange
);
} else {
// Get transform of the image
AffineTransformation dataTransform = SceneGraph::getAffineTransformationFromData(input);
dataTransform.scale(it->second->getSpacing()); // Apply image spacing
// Transfer transformations
Eigen::Affine3f transform = dataTransform.inverse()*pixelToViewportTransform;
cl::Buffer transformBuffer(
device->getContext(),
CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR,
16*sizeof(float),
transform.data()
);
cl::Kernel kernel(getOpenCLProgram(device, "2D"), "render3Dimage");
// Run kernel to fill the texture
OpenCLImageAccess::pointer access = input->getOpenCLImageAccess(ACCESS_READ, device);
cl::Image3D* clImage = access->get3DImage();
kernel.setArg(0, *clImage);
kernel.setArg(1, PBO); // Read from this
kernel.setArg(2, PBO2); // Write to this
kernel.setArg(3, transformBuffer);
kernel.setArg(4, level);
kernel.setArg(5, window);
// Run the draw 3D image kernel
device->getCommandQueue().enqueueNDRangeKernel(
kernel,
cl::NullRange,
cl::NDRange(width, height),
cl::NullRange
);
}
// Copy PBO2 to PBO
queue.enqueueCopyBuffer(PBO2, PBO, 0, 0, sizeof(float)*width*height*4);
}
queue.enqueueReleaseGLObjects(&v);
queue.finish();
}
BoundingBox ImageRenderer::getBoundingBox() {
std::vector<Vector3f> coordinates;
boost::unordered_map<uint, Image::pointer>::iterator it;
for(it = mImagesToRender.begin(); it != mImagesToRender.end(); it++) {
BoundingBox transformedBoundingBox;
transformedBoundingBox = it->second->getTransformedBoundingBox();
MatrixXf corners = transformedBoundingBox.getCorners();
for(uint j = 0; j < 8; j++) {
coordinates.push_back((Vector3f)corners.row(j));
}
}
return BoundingBox(coordinates);
}
<commit_msg>fixed image spacing issue in image renderer<commit_after>#include "ImageRenderer.hpp"
#include "FAST/Exception.hpp"
#include "FAST/DeviceManager.hpp"
#include "FAST/Utility.hpp"
#include "FAST/SceneGraph.hpp"
#if defined(__APPLE__) || defined(__MACOSX)
#include <OpenCL/cl_gl.h>
#include <OpenGL/gl.h>
#include <OpenGL/OpenGL.h>
#else
#if _WIN32
#include <GL/gl.h>
#include <CL/cl_gl.h>
#else
#include <GL/glx.h>
#include <CL/cl_gl.h>
#endif
#endif
#include <boost/thread/lock_guard.hpp>
using namespace fast;
#ifndef GL_RGBA32F // this is missing on windows and mac for some reason
#define GL_RGBA32F 0x8814
#endif
void ImageRenderer::execute() {
boost::lock_guard<boost::mutex> lock(mMutex);
// This simply gets the input data for each connection and puts it into a data structure
for(uint inputNr = 0; inputNr < getNrOfInputData(); inputNr++) {
Image::pointer input = getStaticInputData<Image>(inputNr);
mImagesToRender[inputNr] = input;
}
}
void ImageRenderer::addInputConnection(ProcessObjectPort port) {
uint nr = getNrOfInputData();
if(nr > 0)
createInputPort<Image>(nr);
releaseInputAfterExecute(nr, false);
setInputConnection(nr, port);
}
ImageRenderer::ImageRenderer() : Renderer() {
createInputPort<Image>(0, false);
createOpenCLProgram(std::string(FAST_SOURCE_DIR) + "/Visualization/ImageRenderer/ImageRenderer.cl", "3D");
createOpenCLProgram(std::string(FAST_SOURCE_DIR) + "/Visualization/ImageRenderer/ImageRenderer2D.cl", "2D");
mIsModified = false;
}
void ImageRenderer::draw() {
boost::lock_guard<boost::mutex> lock(mMutex);
boost::unordered_map<uint, Image::pointer>::iterator it;
for(it = mImagesToRender.begin(); it != mImagesToRender.end(); it++) {
Image::pointer input = it->second;
uint inputNr = it->first;
// Check if a texture has already been created for this image
if(mTexturesToRender.count(inputNr) > 0 && mImageUsed[inputNr] == input)
continue; // If it has already been created, skip it
// If it has not been created, create the texture
// Determine level and window
float window = mWindow;
float level = mLevel;
// If mWindow/mLevel is equal to -1 use default level/window values
if(window == -1) {
window = getDefaultIntensityWindow(input->getDataType());
}
if(level == -1) {
level = getDefaultIntensityLevel(input->getDataType());
}
OpenCLDevice::pointer device = getMainDevice();
OpenCLImageAccess::pointer access = input->getOpenCLImageAccess(ACCESS_READ, device);
cl::Image2D* clImage = access->get2DImage();
glEnable(GL_TEXTURE_2D);
if(mTexturesToRender.count(inputNr) > 0) {
// Delete old texture
glDeleteTextures(1, &mTexturesToRender[inputNr]);
mTexturesToRender.erase(inputNr);
}
// Create OpenGL texture
GLuint textureID;
glGenTextures(1, &textureID);
glBindTexture(GL_TEXTURE_2D, textureID);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, clImage->getImageInfo<CL_IMAGE_WIDTH>(), clImage->getImageInfo<CL_IMAGE_HEIGHT>(), 0, GL_RGBA, GL_FLOAT, 0);
glBindTexture(GL_TEXTURE_2D, 0);
glFinish();
mTexturesToRender[inputNr] = textureID;
mImageUsed[inputNr] = input;
// Create CL-GL image
#if defined(CL_VERSION_1_2)
cl::ImageGL mImageGL = cl::ImageGL(
device->getContext(),
CL_MEM_READ_WRITE,
GL_TEXTURE_2D,
0,
textureID
);
#else
cl::Image2DGL mImageGL = cl::Image2DGL(
device->getContext(),
CL_MEM_READ_WRITE,
GL_TEXTURE_2D,
0,
textureID
);
#endif
std::string kernelName = "renderToTextureInt";
if(input->getDataType() == TYPE_FLOAT) {
kernelName = "renderToTextureFloat";
} else if(input->getDataType() == TYPE_UINT8 || input->getDataType() == TYPE_UINT16) {
kernelName = "renderToTextureUint";
}
mKernel = cl::Kernel(getOpenCLProgram(device, "3D"), kernelName.c_str());
// Run kernel to fill the texture
cl::CommandQueue queue = device->getCommandQueue();
std::vector<cl::Memory> v;
v.push_back(mImageGL);
queue.enqueueAcquireGLObjects(&v);
mKernel.setArg(0, *clImage);
mKernel.setArg(1, mImageGL);
mKernel.setArg(2, level);
mKernel.setArg(3, window);
queue.enqueueNDRangeKernel(
mKernel,
cl::NullRange,
cl::NDRange(clImage->getImageInfo<CL_IMAGE_WIDTH>(), clImage->getImageInfo<CL_IMAGE_HEIGHT>()),
cl::NullRange
);
queue.enqueueReleaseGLObjects(&v);
queue.finish();
}
// This is the actual rendering
for(it = mImageUsed.begin(); it != mImageUsed.end(); it++) {
glPushMatrix();
AffineTransformation transform = SceneGraph::getAffineTransformationFromData(it->second);
glMultMatrixf(transform.data());
glBindTexture(GL_TEXTURE_2D, mTexturesToRender[it->first]);
// Get width and height in mm
float width = it->second->getWidth()*it->second->getSpacing().x();
float height = it->second->getHeight()*it->second->getSpacing().y();
glColor3f(1,1,1); // black white texture
glBegin(GL_QUADS);
glTexCoord2i(0, 0);
glVertex3f(0, height, 0.0f);
glTexCoord2i(1, 0);
glVertex3f(width, height, 0.0f);
glTexCoord2i(1, 1);
glVertex3f(width, 0, 0.0f);
glTexCoord2i(0, 1);
glVertex3f(0, 0, 0.0f);
glEnd();
glBindTexture(GL_TEXTURE_2D, 0);
glPopMatrix();
}
}
void ImageRenderer::draw2D(cl::BufferGL PBO, uint width, uint height, Eigen::Transform<float, 3, Eigen::Affine> pixelToViewportTransform, float PBOspacing, Vector2f translation) {
boost::lock_guard<boost::mutex> lock(mMutex);
OpenCLDevice::pointer device = getMainDevice();
cl::CommandQueue queue = device->getCommandQueue();
std::vector<cl::Memory> v;
v.push_back(PBO);
queue.enqueueAcquireGLObjects(&v);
// Create an aux PBO
cl::Buffer PBO2(
device->getContext(),
CL_MEM_READ_WRITE,
sizeof(float)*width*height*4
);
boost::unordered_map<uint, Image::pointer>::iterator it;
for(it = mImagesToRender.begin(); it != mImagesToRender.end(); it++) {
Image::pointer input = it->second;
// Determine level and window
float window = mWindow;
float level = mLevel;
// If mWindow/mLevel is equal to -1 use default level/window values
if(window == -1) {
window = getDefaultIntensityWindow(input->getDataType());
}
if(level == -1) {
level = getDefaultIntensityLevel(input->getDataType());
}
if(input->getDimensions() == 2) {
cl::Kernel kernel(getOpenCLProgram(device, "2D"), "render2Dimage");
// Run kernel to fill the texture
OpenCLImageAccess::pointer access = input->getOpenCLImageAccess(ACCESS_READ, device);
cl::Image2D* clImage = access->get2DImage();
kernel.setArg(0, *clImage);
kernel.setArg(1, PBO); // Read from this
kernel.setArg(2, PBO2); // Write to this
kernel.setArg(3, input->getSpacing().x());
kernel.setArg(4, input->getSpacing().y());
kernel.setArg(5, PBOspacing);
kernel.setArg(6, level);
kernel.setArg(7, window);
kernel.setArg(8, translation.x());
kernel.setArg(9, translation.y());
// Run the draw 2D kernel
device->getCommandQueue().enqueueNDRangeKernel(
kernel,
cl::NullRange,
cl::NDRange(width, height),
cl::NullRange
);
} else {
// Get transform of the image
AffineTransformation dataTransform = SceneGraph::getAffineTransformationFromData(input);
dataTransform.scale(it->second->getSpacing()); // Apply image spacing
// Transfer transformations
Eigen::Affine3f transform = dataTransform.inverse()*pixelToViewportTransform;
cl::Buffer transformBuffer(
device->getContext(),
CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR,
16*sizeof(float),
transform.data()
);
cl::Kernel kernel(getOpenCLProgram(device, "2D"), "render3Dimage");
// Run kernel to fill the texture
OpenCLImageAccess::pointer access = input->getOpenCLImageAccess(ACCESS_READ, device);
cl::Image3D* clImage = access->get3DImage();
kernel.setArg(0, *clImage);
kernel.setArg(1, PBO); // Read from this
kernel.setArg(2, PBO2); // Write to this
kernel.setArg(3, transformBuffer);
kernel.setArg(4, level);
kernel.setArg(5, window);
// Run the draw 3D image kernel
device->getCommandQueue().enqueueNDRangeKernel(
kernel,
cl::NullRange,
cl::NDRange(width, height),
cl::NullRange
);
}
// Copy PBO2 to PBO
queue.enqueueCopyBuffer(PBO2, PBO, 0, 0, sizeof(float)*width*height*4);
}
queue.enqueueReleaseGLObjects(&v);
queue.finish();
}
BoundingBox ImageRenderer::getBoundingBox() {
std::vector<Vector3f> coordinates;
boost::unordered_map<uint, Image::pointer>::iterator it;
for(it = mImagesToRender.begin(); it != mImagesToRender.end(); it++) {
BoundingBox transformedBoundingBox;
transformedBoundingBox = it->second->getTransformedBoundingBox();
MatrixXf corners = transformedBoundingBox.getCorners();
for(uint j = 0; j < 8; j++) {
coordinates.push_back((Vector3f)corners.row(j));
}
}
return BoundingBox(coordinates);
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2020 ASMlover. 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 ofconditions 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 materialsprovided 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 <functional>
#include <iostream>
#include <vector>
#include "lexer.hh"
#include "value.hh"
#include "chunk.hh"
#include "vm.hh"
#include "compiler.hh"
namespace tadpole {
enum class Precedence {
NONE,
ASSIGN, // =
TERM, // - +
FACTOR, // / *
CALL, // ()
PRIMARY,
};
template <typename T> inline Precedence operator+(Precedence a, T b) noexcept {
return as_type<Precedence>(as_type<int>(a) + as_type<int>(b));
}
struct ParseRule {
using ParseFn = std::function<void (GlobalParser&, bool)>;
ParseFn prefix;
ParseFn infix;
Precedence precedence;
};
struct LocalVar {
Token name;
int depth{};
bool is_upvalue{};
LocalVar(const Token& arg_name, int arg_depth = -1, bool arg_upvalue = false) noexcept
: name(arg_name), depth(arg_depth), is_upvalue(arg_upvalue) {
}
};
struct Upvalue {
u8_t index{};
bool is_local{};
Upvalue(u8_t arg_index = 0, bool arg_local = false) noexcept
: index(arg_index), is_local(arg_local) {
}
inline bool operator==(Upvalue r) const noexcept {
return index == r.index && is_local == r.is_local;
}
inline bool operator!=(Upvalue r) const noexcept {
return !(*this == r);
}
inline bool is_equal(u8_t arg_index, bool arg_local) const noexcept {
return index == arg_index && is_local == arg_local;
}
};
FunctionObject* GlobalCompiler::compile(VM& vm, const str_t& source_bytes) {
return nullptr;
}
void GlobalCompiler::mark_compiler() {
}
}
<commit_msg>:construction: chore(compiler): add basic compiler for function<commit_after>// Copyright (c) 2020 ASMlover. 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 ofconditions 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 materialsprovided 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 <functional>
#include <iostream>
#include <vector>
#include "lexer.hh"
#include "value.hh"
#include "chunk.hh"
#include "vm.hh"
#include "compiler.hh"
namespace tadpole {
enum class Precedence {
NONE,
ASSIGN, // =
TERM, // - +
FACTOR, // / *
CALL, // ()
PRIMARY,
};
template <typename T> inline Precedence operator+(Precedence a, T b) noexcept {
return as_type<Precedence>(as_type<int>(a) + as_type<int>(b));
}
struct ParseRule {
using ParseFn = std::function<void (GlobalParser&, bool)>;
ParseFn prefix;
ParseFn infix;
Precedence precedence;
};
struct LocalVar {
Token name;
int depth{};
bool is_upvalue{};
LocalVar(const Token& arg_name, int arg_depth = -1, bool arg_upvalue = false) noexcept
: name(arg_name), depth(arg_depth), is_upvalue(arg_upvalue) {
}
};
struct Upvalue {
u8_t index{};
bool is_local{};
Upvalue(u8_t arg_index = 0, bool arg_local = false) noexcept
: index(arg_index), is_local(arg_local) {
}
inline bool operator==(Upvalue r) const noexcept {
return index == r.index && is_local == r.is_local;
}
inline bool operator!=(Upvalue r) const noexcept {
return !(*this == r);
}
inline bool is_equal(u8_t arg_index, bool arg_local) const noexcept {
return index == arg_index && is_local == arg_local;
}
};
enum class FunType {
FUNCTION,
TOPLEVEL,
};
class Compiler final : private UnCopyable {
using ErrorFn = std::function<void (const str_t&)>;
Compiler* enclosing_{};
FunctionObject* fn_{};
FunType fn_type_{};
int scope_depth_{};
std::vector<LocalVar> locals_;
std::vector<Upvalue> upvalues_;
public:
Compiler() noexcept {}
Compiler(Compiler* enclosing,
FunctionObject* fn, FunType fn_type, int scope_depth = 0) noexcept
: enclosing_(enclosing), fn_(fn), fn_type_(fn_type), scope_depth_(scope_depth) {
}
inline void set_compiler(Compiler* enclosing,
FunctionObject* fn, FunType fn_type, int scope_depth = 0) noexcept {
enclosing_ = enclosing;
fn_ = fn;
fn_type_ = fn_type;
scope_depth_ = scope_depth;
}
inline Compiler* enclosing() const noexcept { return enclosing_; }
inline FunctionObject* fn() const noexcept { return fn_; }
inline FunType fn_type() const noexcept { return fn_type_; }
inline int scope_depth() const noexcept { return scope_depth_; }
inline void set_scope_depth(int depth) noexcept { scope_depth_ = depth; }
inline int locals_count() const noexcept { return as_type<int>(locals_.size()); }
inline LocalVar& get_local(sz_t i) noexcept { return locals_[i]; }
inline const LocalVar& get_local(sz_t i) const noexcept { return locals_[i]; }
inline LocalVar& peek_local() noexcept { return locals_.back(); }
inline const LocalVar& peek_local() const noexcept { return locals_.back(); }
inline void append_local(const LocalVar& var) noexcept { return locals_.push_back(var); }
inline Upvalue& get_upvalue(sz_t i) noexcept { return upvalues_[i]; }
inline const Upvalue& get_upvalue(sz_t i) const noexcept { return upvalues_[i]; }
inline void append_upvalue(const Upvalue& u) noexcept { upvalues_.push_back(u); }
};
FunctionObject* GlobalCompiler::compile(VM& vm, const str_t& source_bytes) {
return nullptr;
}
void GlobalCompiler::mark_compiler() {
}
}
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.