text stringlengths 54 60.6k |
|---|
<commit_before>#ifndef ALEPH_COMPLEXES_FLANN_HH__
#define ALEPH_COMPLEXES_FLANN_HH__
#include "complexes/NearestNeighbours.hh"
#include <flann/flann.hpp>
#include <algorithm>
#include <vector>
#include "distances/Traits.hh"
namespace aleph
{
namespace complexes
{
template <class Container, class DistanceFunctor>
class FLANN : public NearestNeighbours< FLANN<Container, DistanceFunctor>, std::size_t, typename Container::ElementType >
{
public:
using IndexType = std::size_t;
using ElementType = typename Container::ElementType;
using Traits = aleph::distances::Traits<DistanceFunctor>;
FLANN( const Container& container )
: _container( container )
{
_matrix
= flann::Matrix<ElementType>( container.data(),
container.size(), container.dimension() );
flann::IndexParams indexParameters
= flann::KDTreeSingleIndexParams();
_index
= new flann::Index<DistanceFunctor>( _matrix, indexParameters );
_index->buildIndex();
}
~FLANN()
{
delete _index;
}
void radiusSearch( ElementType radius,
std::vector< std::vector<IndexType> >& indices,
std::vector< std::vector<ElementType> >& distances )
{
flann::SearchParams searchParameters = flann::SearchParams();
searchParameters.checks = flann::FLANN_CHECKS_UNLIMITED;
using ResultType = typename DistanceFunctor::ResultType;
std::vector< std::vector<int> > internalIndices;
std::vector< std::vector<ResultType> > internalDistances;
_index->radiusSearch( _matrix,
internalIndices,
distances,
static_cast<float>( _traits.to( radius ) ),
searchParameters );
// Perform transformation of indices -------------------------------
indices.clear();
indices.resize( _matrix.rows );
for( std::size_t i = 0; i < internalIndices.size(); i++ )
{
indices[i] = std::vector<IndexType>( internalIndices[i].size() );
std::transform( internalIndices[i].begin(), internalIndices[i].end(),
indices[i].begin(),
[] ( int j )
{
return static_cast<IndexType>( j );
} );
}
// Perform transformation of distances -----------------------------
for( auto&& D : distances )
{
std::transform( D.begin(), D.end(), D.begin(),
[this] ( ElementType x )
{
return _traits.from( x );
} );
}
}
// The wrapper must not be copied. Else, clients will run afoul of memory
// management issues.
FLANN( const FLANN& other ) = delete;
FLANN& operator=( const FLANN& other ) = delete;
private:
const Container& _container;
/**
Copy of container data. This makes interfacing with FLANN easier, at
the expense of having large storage costs.
*/
flann::Matrix<ElementType> _matrix;
/** Index structure for queries. */
flann::Index<DistanceFunctor>* _index = nullptr;
/** Required for optional distance functor conversions */
Traits _traits;
};
}
}
#endif
<commit_msg>Implemented missing `size()` function for FLANN wrapper<commit_after>#ifndef ALEPH_COMPLEXES_FLANN_HH__
#define ALEPH_COMPLEXES_FLANN_HH__
#include "complexes/NearestNeighbours.hh"
#include <flann/flann.hpp>
#include <algorithm>
#include <vector>
#include "distances/Traits.hh"
namespace aleph
{
namespace complexes
{
template <class Container, class DistanceFunctor>
class FLANN : public NearestNeighbours< FLANN<Container, DistanceFunctor>, std::size_t, typename Container::ElementType >
{
public:
using IndexType = std::size_t;
using ElementType = typename Container::ElementType;
using Traits = aleph::distances::Traits<DistanceFunctor>;
FLANN( const Container& container )
: _container( container )
{
_matrix
= flann::Matrix<ElementType>( container.data(),
container.size(), container.dimension() );
flann::IndexParams indexParameters
= flann::KDTreeSingleIndexParams();
_index
= new flann::Index<DistanceFunctor>( _matrix, indexParameters );
_index->buildIndex();
}
~FLANN()
{
delete _index;
}
void radiusSearch( ElementType radius,
std::vector< std::vector<IndexType> >& indices,
std::vector< std::vector<ElementType> >& distances )
{
flann::SearchParams searchParameters = flann::SearchParams();
searchParameters.checks = flann::FLANN_CHECKS_UNLIMITED;
using ResultType = typename DistanceFunctor::ResultType;
std::vector< std::vector<int> > internalIndices;
std::vector< std::vector<ResultType> > internalDistances;
_index->radiusSearch( _matrix,
internalIndices,
distances,
static_cast<float>( _traits.to( radius ) ),
searchParameters );
// Perform transformation of indices -------------------------------
indices.clear();
indices.resize( _matrix.rows );
for( std::size_t i = 0; i < internalIndices.size(); i++ )
{
indices[i] = std::vector<IndexType>( internalIndices[i].size() );
std::transform( internalIndices[i].begin(), internalIndices[i].end(),
indices[i].begin(),
[] ( int j )
{
return static_cast<IndexType>( j );
} );
}
// Perform transformation of distances -----------------------------
for( auto&& D : distances )
{
std::transform( D.begin(), D.end(), D.begin(),
[this] ( ElementType x )
{
return _traits.from( x );
} );
}
}
std::size_t size() const noexcept
{
return _container.size();
}
// The wrapper must not be copied. Else, clients will run afoul of memory
// management issues.
FLANN( const FLANN& other ) = delete;
FLANN& operator=( const FLANN& other ) = delete;
private:
const Container& _container;
/**
Copy of container data. This makes interfacing with FLANN easier, at
the expense of having large storage costs.
*/
flann::Matrix<ElementType> _matrix;
/** Index structure for queries. */
flann::Index<DistanceFunctor>* _index = nullptr;
/** Required for optional distance functor conversions */
Traits _traits;
};
}
}
#endif
<|endoftext|> |
<commit_before>// Filename: physicsCollisionHandler.cxx
// Created by: drose (16Mar02)
//
////////////////////////////////////////////////////////////////////
//
// PANDA 3D SOFTWARE
// Copyright (c) 2001, Disney Enterprises, Inc. All rights reserved
//
// All use of this software is subject to the terms of the Panda 3d
// Software license. You should have received a copy of this license
// along with this source code; you will also find a current copy of
// the license at http://www.panda3d.org/license.txt .
//
// To contact the maintainers of this program write to
// panda3d@yahoogroups.com .
//
////////////////////////////////////////////////////////////////////
#include "physicsCollisionHandler.h"
#include "collisionNode.h"
#include "collisionEntry.h"
#include "collisionPolygon.h"
#include "config_collide.h"
#include "dcast.h"
TypeHandle PhysicsCollisionHandler::_type_handle;
////////////////////////////////////////////////////////////////////
// Function: PhysicsCollisionHandler::Constructor
// Access: Public
// Description:
////////////////////////////////////////////////////////////////////
PhysicsCollisionHandler::
PhysicsCollisionHandler() {
set_horizontal(false);
}
////////////////////////////////////////////////////////////////////
// Function: PhysicsCollisionHandler::Destructor
// Access: Public, Virtual
// Description:
////////////////////////////////////////////////////////////////////
PhysicsCollisionHandler::
~PhysicsCollisionHandler() {
}
////////////////////////////////////////////////////////////////////
// Function: PhysicsCollisionHandler::apply_linear_force
// Access: Protected, Virtual
// Description:
////////////////////////////////////////////////////////////////////
void PhysicsCollisionHandler::
apply_linear_force(ColliderDef &def, const LVector3f &force) {
CollisionHandlerPusher::apply_linear_force(def, force);
if (force == LVector3f::zero()) {
return;
}
if (!def._node) {
return;
}
ActorNode *actor=DCAST(ActorNode, def._node);
LVector3f vel=actor->get_physics_object()->get_velocity();
if (vel == LVector3f::zero()) {
return;
}
physics_debug("apply_linear_force() {");
physics_debug(" vel "<<vel<<" len "<<vel.length());
physics_debug(" force "<<force<<" len "<<force.length());
LVector3f old_vel=vel;
// Copy the force vector while translating it
// into the physics object coordinate system:
LVector3f adjustment=force;
physics_debug(" adjustment set "<<adjustment<<" len "<<adjustment.length());
//NodePath np(def._node);
//CPT(TransformState) trans = np.get_net_transform();
//adjustment=adjustment*trans->get_mat();
physics_debug(" adjustment trn "<<adjustment<<" len "<<adjustment.length());
adjustment=adjustment*actor->get_physics_object()->get_lcs();
physics_debug(" adjustment lcs "<<adjustment<<" len "<<adjustment.length());
adjustment.normalize();
physics_debug(" adjustment nrm "<<adjustment<<" len "<<adjustment.length());
float adjustmentLength=-(adjustment.dot(vel));
physics_debug(" adjustmentLength "<<adjustmentLength);
float angle=-normalize(old_vel).dot(normalize(force));
physics_debug(" angle "<<angle);
// Are we in contact with something:
if (angle>0.0f) {
physics_debug(" positive contact");
adjustment*=adjustmentLength;
physics_debug(" adjustment mul "<<adjustment<<" len "<<adjustment.length());
// This adjustment to our velocity will not reflect us off the surface,
// but will deflect us parallel (or tangent) to the surface:
vel+=adjustment;
physics_debug(" vel "<<vel<<" len "<<vel.length());
if (vel!=LVector3f::zero()) {
const float almostStationary=0.1f;
float frictionCoefficient=0.0f;
// Determine the friction:
if (vel.length()<almostStationary) {
physics_debug(" static friction");
frictionCoefficient=0.9f;
} else {
physics_debug(" dynamic friction");
frictionCoefficient=0.5f;
}
// Apply the friction:
physics_debug(" vel pre friction "<<vel<<" len "<<vel.length());
float friction=frictionCoefficient*angle;
physics_debug(" friction "<<friction);
if (friction<0.0f && friction>1.0f) {
cerr<<"\n\nfriction error "<<friction<<endl;
friction=1.0f;
}
#if 0
float dt=ClockObject::get_global_clock()->get_dt();
vel *= (1.0f-friction) * dt * dt;
#else
vel *= 1.0f-friction;
#endif
physics_debug(" vel post friction "<<vel<<" len "<<vel.length());
}
} else if (adjustmentLength==0.0f) {
physics_debug(" brushing contact");
} else {
physics_debug(" negative contact");
}
#ifndef NDEBUG //[
if (vel.length() > old_vel.length()) {
// This is a check to avoid adding engergy:
physics_debug(" vel.length() > old_vel.length() "<<vel.length()<<" > "<<old_vel.length());
}
if (vel.length() > 10.0f) {
// This is a check to see if the velocity is higher than I expect it
// to go. The check value is arbitrary.
physics_debug(" vel.length() > 10.0f "<<vel.length());
}
#endif //]
physics_debug(" force "<<force<<" len "<<force.length());
physics_debug(" vel "<<vel<<" len "<<vel.length());
physics_debug("}");
actor->set_contact_vector(adjustment);
actor->get_physics_object()->set_velocity(vel);
}
<commit_msg>use new NodePath-based interface for physics<commit_after>// Filename: physicsCollisionHandler.cxx
// Created by: drose (16Mar02)
//
////////////////////////////////////////////////////////////////////
//
// PANDA 3D SOFTWARE
// Copyright (c) 2001, Disney Enterprises, Inc. All rights reserved
//
// All use of this software is subject to the terms of the Panda 3d
// Software license. You should have received a copy of this license
// along with this source code; you will also find a current copy of
// the license at http://www.panda3d.org/license.txt .
//
// To contact the maintainers of this program write to
// panda3d@yahoogroups.com .
//
////////////////////////////////////////////////////////////////////
#include "physicsCollisionHandler.h"
#include "collisionNode.h"
#include "collisionEntry.h"
#include "collisionPolygon.h"
#include "config_collide.h"
#include "dcast.h"
TypeHandle PhysicsCollisionHandler::_type_handle;
////////////////////////////////////////////////////////////////////
// Function: PhysicsCollisionHandler::Constructor
// Access: Public
// Description:
////////////////////////////////////////////////////////////////////
PhysicsCollisionHandler::
PhysicsCollisionHandler() {
set_horizontal(false);
}
////////////////////////////////////////////////////////////////////
// Function: PhysicsCollisionHandler::Destructor
// Access: Public, Virtual
// Description:
////////////////////////////////////////////////////////////////////
PhysicsCollisionHandler::
~PhysicsCollisionHandler() {
}
////////////////////////////////////////////////////////////////////
// Function: PhysicsCollisionHandler::apply_linear_force
// Access: Protected, Virtual
// Description:
////////////////////////////////////////////////////////////////////
void PhysicsCollisionHandler::
apply_linear_force(ColliderDef &def, const LVector3f &force) {
CollisionHandlerPusher::apply_linear_force(def, force);
if (force == LVector3f::zero()) {
return;
}
if (def._target.is_empty()) {
return;
}
ActorNode *actor;
DCAST_INTO_V(actor, def._target.node());
LVector3f vel=actor->get_physics_object()->get_velocity();
if (vel == LVector3f::zero()) {
return;
}
physics_debug("apply_linear_force() {");
physics_debug(" vel "<<vel<<" len "<<vel.length());
physics_debug(" force "<<force<<" len "<<force.length());
LVector3f old_vel=vel;
// Copy the force vector while translating it
// into the physics object coordinate system:
LVector3f adjustment=force;
physics_debug(" adjustment set "<<adjustment<<" len "<<adjustment.length());
//NodePath np(def._node);
//CPT(TransformState) trans = np.get_net_transform();
//adjustment=adjustment*trans->get_mat();
physics_debug(" adjustment trn "<<adjustment<<" len "<<adjustment.length());
adjustment=adjustment*actor->get_physics_object()->get_lcs();
physics_debug(" adjustment lcs "<<adjustment<<" len "<<adjustment.length());
adjustment.normalize();
physics_debug(" adjustment nrm "<<adjustment<<" len "<<adjustment.length());
float adjustmentLength=-(adjustment.dot(vel));
physics_debug(" adjustmentLength "<<adjustmentLength);
float angle=-normalize(old_vel).dot(normalize(force));
physics_debug(" angle "<<angle);
// Are we in contact with something:
if (angle>0.0f) {
physics_debug(" positive contact");
adjustment*=adjustmentLength;
physics_debug(" adjustment mul "<<adjustment<<" len "<<adjustment.length());
// This adjustment to our velocity will not reflect us off the surface,
// but will deflect us parallel (or tangent) to the surface:
vel+=adjustment;
physics_debug(" vel "<<vel<<" len "<<vel.length());
if (vel!=LVector3f::zero()) {
const float almostStationary=0.1f;
float frictionCoefficient=0.0f;
// Determine the friction:
if (vel.length()<almostStationary) {
physics_debug(" static friction");
frictionCoefficient=0.9f;
} else {
physics_debug(" dynamic friction");
frictionCoefficient=0.5f;
}
// Apply the friction:
physics_debug(" vel pre friction "<<vel<<" len "<<vel.length());
float friction=frictionCoefficient*angle;
physics_debug(" friction "<<friction);
if (friction<0.0f && friction>1.0f) {
cerr<<"\n\nfriction error "<<friction<<endl;
friction=1.0f;
}
#if 0
float dt=ClockObject::get_global_clock()->get_dt();
vel *= (1.0f-friction) * dt * dt;
#else
vel *= 1.0f-friction;
#endif
physics_debug(" vel post friction "<<vel<<" len "<<vel.length());
}
} else if (adjustmentLength==0.0f) {
physics_debug(" brushing contact");
} else {
physics_debug(" negative contact");
}
#ifndef NDEBUG //[
if (vel.length() > old_vel.length()) {
// This is a check to avoid adding engergy:
physics_debug(" vel.length() > old_vel.length() "<<vel.length()<<" > "<<old_vel.length());
}
if (vel.length() > 10.0f) {
// This is a check to see if the velocity is higher than I expect it
// to go. The check value is arbitrary.
physics_debug(" vel.length() > 10.0f "<<vel.length());
}
#endif //]
physics_debug(" force "<<force<<" len "<<force.length());
physics_debug(" vel "<<vel<<" len "<<vel.length());
physics_debug("}");
actor->set_contact_vector(adjustment);
actor->get_physics_object()->set_velocity(vel);
}
<|endoftext|> |
<commit_before>/*
* utils.cpp
*
* Created on: 22 maj 2015
* Author: parhansson
*/
#include <stdio.h>
#include <stddef.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/syscall.h> /* For SYS_xxx definitions */
#include <unistd.h> // getpagesize
#include "utils.h"
#include "mongoose.h"
#include "dbg.h"
int mmapNamedFile(MappedFile& mmFile, const char * fileName){
FILE *fp = (FILE *) fopen (fileName, "r+");
int result = mmapFile(mmFile, fp);
fclose(fp);
return result;
}
int mmapFile(MappedFile& mmFile, FILE *fp){
if (fp == NULL) {
debug("Failed to open file");
return -1;
}
struct stat st;
int pagesize, offset, fd;
fd = fileno(fp);
fstat(fd, &st);
mmFile.filesize = st.st_size;
offset = 0;
pagesize = getpagesize(); // should use sysconf(_SC_PAGE_SIZE) instead.
mmFile.mapsize = (mmFile.filesize/pagesize)*pagesize+pagesize; // align memory allocation with pagesize
//memory map tmp file and parse it.
mmFile.addr = (char*)mmap((caddr_t)0, mmFile.mapsize, PROT_READ, MAP_PRIVATE, fd, offset);
return 0;
}
void unmapFile(MappedFile& mmFile){
munmap(mmFile.addr, mmFile.mapsize);
}
void absolutePath(const char * relativePath, char * absolutePath){
const char * rootDir = mg_get_option(server, "document_root");
sprintf(absolutePath, "%s/%s",rootDir,relativePath);
}
<commit_msg>Resolve realpath from when converting relative to absolute paths<commit_after>/*
* utils.cpp
*
* Created on: 22 maj 2015
* Author: parhansson
*/
#include <stdio.h>
#include <stddef.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/syscall.h> /* For SYS_xxx definitions */
#include <unistd.h> // getpagesize
#include "utils.h"
#include "mongoose.h"
#include "dbg.h"
int mmapNamedFile(MappedFile& mmFile, const char * fileName){
FILE *fp = (FILE *) fopen (fileName, "r+");
int result = mmapFile(mmFile, fp);
fclose(fp);
return result;
}
int mmapFile(MappedFile& mmFile, FILE *fp){
if (fp == NULL) {
debug("Failed to open file");
return -1;
}
struct stat st;
int pagesize, offset, fd;
fd = fileno(fp);
fstat(fd, &st);
mmFile.filesize = st.st_size;
offset = 0;
pagesize = getpagesize(); // should use sysconf(_SC_PAGE_SIZE) instead.
mmFile.mapsize = (mmFile.filesize/pagesize)*pagesize+pagesize; // align memory allocation with pagesize
//memory map tmp file and parse it.
mmFile.addr = (char*)mmap((caddr_t)0, mmFile.mapsize, PROT_READ, MAP_PRIVATE, fd, offset);
return 0;
}
void unmapFile(MappedFile& mmFile){
munmap(mmFile.addr, mmFile.mapsize);
}
void absolutePath(const char * relativePath, char * actualpath){
char absolute [256/*PATH_MAX*/];
if(relativePath[0]=='/'){
sprintf(absolute, "%s",relativePath);
} else {
const char * rootDir = mg_get_option(server, "document_root");
sprintf(absolute, "%s/%s",rootDir,relativePath);
}
if(realpath(absolute, actualpath) == NULL){
printf("Error resolving relative path %s from %s\n", relativePath, absolute);
sprintf(actualpath, "%s",absolute);
}
}
<|endoftext|> |
<commit_before>#ifndef HMLIB_RANDOM_RANDOMENGINE_INC
#define HMLIB_RANDOM_RANDOMENGINE_INC 100
#
/*
===random_engine===
C++11の乱数ライブラリをラッピングして提供
random_engine v1_00/130328 hmIto
randomから分離
*/
#include<algorithm>
#include<functional>
#include<vector>
#include<random>
#include<numeric>
#
namespace hmLib{
namespace random{
template<typename engine_type>
engine_type randomized_engine(){
engine_type Engine;
// ランダムデバイス
std::random_device rnd ;
// 初期化用ベクタ
std::vector< unsigned int> v(10) ;
// ベクタの初期化
std::generate( v.begin(), v.end(), std::ref(rnd) ) ;
//シード配列作成
std::seed_seq Seq( v.begin(), v.end() );
//シードで初期化
Engine.seed(Seq);
return Engine;
}
}
template<typename tag, typename random_engine_type = std::mt19937_64>
struct singleton_random_engine{
private:
using my_type = singleton_random_engine<tag, random_engine_type>;
public:
using result_type = typename random_engine_type::result_type;
private:
static random_engine_type Engine;
public:
constexpr static result_type min() { return random_engine_type::min(); }
constexpr static result_type max() { return random_engine_type::max(); }
static void singleton_seed(){Engine.seed();}
static void singleton_seed(result_type Seed){Engine.seed(Seed);}
public:
singleton_random_engine()=default;
result_type operator()(void){return Engine();}
void discard(unsigned long long z){Engine.discard(z);}
};
template<typename tag, typename random_engine_type>
random_engine_type singleton_random_engine<tag,random_engine_type>::Engine = random::randomized_engine<random_engine_type>();
namespace random{
struct default_engine_tag{};
using default_engine = singleton_random_engine<default_engine_tag>;
template<typename value_type>
value_type uniform_int(value_type Min,value_type Max){return std::uniform_int_distribution<value_type>(Min,Max)(default_engine());}
template<typename value_type>
value_type uniform_real(value_type Min, value_type Max){return std::uniform_real_distribution<value_type>(Min,Max)(default_engine());}
template<typename value_type>
value_type normal(value_type meen, value_type sigma){return std::normal_distribution<value_type>(meen,sigma)(default_engine());}
}
}
#
#endif
<commit_msg>Fix: rvalue URNG is not applicable for random number distribution.<commit_after>#ifndef HMLIB_RANDOM_RANDOMENGINE_INC
#define HMLIB_RANDOM_RANDOMENGINE_INC 100
#
/*
===random_engine===
C++11の乱数ライブラリをラッピングして提供
random_engine v1_00/130328 hmIto
randomから分離
*/
#include<algorithm>
#include<functional>
#include<vector>
#include<random>
#include<numeric>
#
namespace hmLib{
namespace random{
template<typename engine_type>
engine_type randomized_engine(){
engine_type Engine;
// ランダムデバイス
std::random_device rnd ;
// 初期化用ベクタ
std::vector< unsigned int> v(10) ;
// ベクタの初期化
std::generate( v.begin(), v.end(), std::ref(rnd) ) ;
//シード配列作成
std::seed_seq Seq( v.begin(), v.end() );
//シードで初期化
Engine.seed(Seq);
return Engine;
}
}
template<typename tag, typename random_engine_type = std::mt19937_64>
struct singleton_random_engine{
private:
using my_type = singleton_random_engine<tag, random_engine_type>;
public:
using result_type = typename random_engine_type::result_type;
private:
static random_engine_type Engine;
public:
constexpr static result_type min() { return random_engine_type::min(); }
constexpr static result_type max() { return random_engine_type::max(); }
static void singleton_seed(){Engine.seed();}
static void singleton_seed(result_type Seed){Engine.seed(Seed);}
public:
singleton_random_engine()=default;
result_type operator()(void){return Engine();}
void discard(unsigned long long z){Engine.discard(z);}
};
template<typename tag, typename random_engine_type>
random_engine_type singleton_random_engine<tag,random_engine_type>::Engine = random::randomized_engine<random_engine_type>();
namespace random{
struct default_engine_tag{};
using default_engine = singleton_random_engine<default_engine_tag>;
template<typename value_type>
value_type uniform_int(value_type Min,value_type Max){
default_engine Engine;
return std::uniform_int_distribution<value_type>(Min,Max)(Engine);
}
template<typename value_type>
value_type uniform_real(value_type Min, value_type Max){
default_engine Engine;
return std::uniform_real_distribution<value_type>(Min,Max)(Engine);
}
template<typename value_type>
value_type normal(value_type meen, value_type sigma){
default_engine Engine;
return std::normal_distribution<value_type>(meen,sigma)(Engine);
}
}
}
#
#endif
<|endoftext|> |
<commit_before>/*
* This file is part of Poedit (https://poedit.net)
*
* Copyright (C) 1999-2019 Vaclav Slavik
*
* 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 "fileviewer.h"
#include <wx/filename.h>
#include <wx/log.h>
#include <wx/button.h>
#include <wx/panel.h>
#include <wx/stattext.h>
#include <wx/choice.h>
#include <wx/config.h>
#include <wx/sizer.h>
#include <wx/settings.h>
#include <wx/listctrl.h>
#include <wx/fontenum.h>
#include <wx/ffile.h>
#include <wx/utils.h>
#include <wx/stc/stc.h>
#include "customcontrols.h"
#include "hidpi.h"
#include "utility.h"
#include "unicode_helpers.h"
namespace
{
#ifdef __WXOSX__
const int FRAME_STYLE = wxDEFAULT_FRAME_STYLE | wxFRAME_TOOL_WINDOW;
#else
const int FRAME_STYLE = wxDEFAULT_FRAME_STYLE;
#endif
} // anonymous namespace
FileViewer *FileViewer::ms_instance = nullptr;
FileViewer *FileViewer::GetAndActivate()
{
if (!ms_instance)
ms_instance = new FileViewer(nullptr);
ms_instance->Show();
ms_instance->Raise();
return ms_instance;
}
FileViewer::FileViewer(wxWindow*)
: wxFrame(nullptr, wxID_ANY, _("Source file"), wxDefaultPosition, wxDefaultSize, FRAME_STYLE)
{
SetName("fileviewer");
wxPanel *panel = new wxPanel(this, -1);
wxSizer *sizer = new wxBoxSizer(wxVERTICAL);
panel->SetSizer(sizer);
#ifdef __WXOSX__
panel->SetWindowVariant(wxWINDOW_VARIANT_SMALL);
#endif
wxSizer *barsizer = new wxBoxSizer(wxHORIZONTAL);
sizer->Add(barsizer, wxSizerFlags().Expand().PXBorderAll());
barsizer->Add(new wxStaticText(panel, wxID_ANY,
_("Source file occurrence:")),
wxSizerFlags().Center().PXBorder(wxRIGHT));
m_file = new wxChoice(panel, wxID_ANY);
barsizer->Add(m_file, wxSizerFlags(1).Center());
m_openInEditor = new wxButton(panel, wxID_ANY, MSW_OR_OTHER(_("Open in editor"), _("Open in Editor")));
barsizer->Add(m_openInEditor, wxSizerFlags().Center().Border(wxLEFT, PX(10)));
m_text = new wxStyledTextCtrl(panel, wxID_ANY,
wxDefaultPosition, wxDefaultSize,
wxBORDER_THEME);
SetupTextCtrl();
sizer->Add(m_text, 1, wxEXPAND);
m_error = new wxStaticText(panel, wxID_ANY, "");
m_error->SetForegroundColour(ExplanationLabel::GetTextColor());
m_error->SetFont(m_error->GetFont().Larger().Larger());
sizer->Add(m_error, wxSizerFlags(1).Center().Border(wxTOP|wxBOTTOM, PX(80)));
RestoreWindowState(this, wxSize(PX(600), PX(400)));
wxSizer *topsizer = new wxBoxSizer(wxVERTICAL);
topsizer->Add(panel, wxSizerFlags(1).Expand());
SetSizer(topsizer);
// avoid flicker with these initial settings:
m_file->Disable();
sizer->Hide(m_error);
sizer->Hide(m_text);
Layout();
m_file->Bind(wxEVT_CHOICE, &FileViewer::OnChoice, this);
m_openInEditor->Bind(wxEVT_BUTTON, &FileViewer::OnEditFile, this);
#ifdef __WXOSX__
wxAcceleratorEntry entries[] = {
{ wxACCEL_CMD, 'W', wxID_CLOSE }
};
wxAcceleratorTable accel(WXSIZEOF(entries), entries);
SetAcceleratorTable(accel);
Bind(wxEVT_MENU, [=](wxCommandEvent&){ Destroy(); }, wxID_CLOSE);
#endif
}
FileViewer::~FileViewer()
{
ms_instance = nullptr;
SaveWindowState(this);
}
void FileViewer::SetupTextCtrl()
{
wxStyledTextCtrl& t = *m_text;
wxFont font = wxSystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT);
#ifdef __WXGTK__
font.SetFaceName("monospace");
#else
static const char *s_monospaced_fonts[] = {
#ifdef __WXMSW__
"Consolas",
"Lucida Console",
#endif
#ifdef __WXOSX__
"Menlo",
"Monaco",
#endif
NULL
};
for ( const char **f = s_monospaced_fonts; *f; ++f )
{
if ( wxFontEnumerator::IsValidFacename(*f) )
{
font.SetFaceName(*f);
break;
}
}
#endif
// style used:
wxString fontspec = wxString::Format("face:%s,size:%d",
font.GetFaceName().c_str(),
#ifdef __WXOSX__
font.GetPointSize() - 1
#else
font.GetPointSize()
#endif
);
const wxString DEFAULT = fontspec + ",fore:black,back:white";
const wxString STRING = fontspec + ",bold,fore:#882d21";
const wxString COMMENT = fontspec + ",fore:#487e18";
const wxString KEYWORD = fontspec + ",fore:#2f00f9";
const wxString LINENUMBERS = fontspec + ",fore:#5d8bab";
// current line marker
t.MarkerDefine(1, wxSTC_MARK_BACKGROUND, wxNullColour, wxColour(255,255,0));
// set fonts
t.StyleSetSpec(wxSTC_STYLE_DEFAULT, DEFAULT);
t.StyleSetSpec(wxSTC_STYLE_LINENUMBER, LINENUMBERS);
// line numbers margin size:
t.SetMarginType(0, wxSTC_MARGIN_NUMBER);
t.SetMarginWidth(0,
t.TextWidth(wxSTC_STYLE_LINENUMBER, "9999 "));
t.SetMarginWidth(1, 0);
t.SetMarginWidth(2, 3);
// set syntax highlighting styling
t.StyleSetSpec(wxSTC_C_STRING, STRING);
t.StyleSetSpec(wxSTC_C_COMMENT, COMMENT);
t.StyleSetSpec(wxSTC_C_COMMENTLINE, COMMENT);
t.StyleSetSpec(wxSTC_P_STRING, STRING);
t.StyleSetSpec(wxSTC_P_COMMENTLINE, COMMENT);
t.StyleSetSpec(wxSTC_P_COMMENTBLOCK, COMMENT);
t.StyleSetSpec(wxSTC_LUA_STRING, STRING);
t.StyleSetSpec(wxSTC_LUA_LITERALSTRING, STRING);
t.StyleSetSpec(wxSTC_LUA_COMMENT, COMMENT);
t.StyleSetSpec(wxSTC_LUA_COMMENTLINE, COMMENT);
t.StyleSetSpec(wxSTC_HPHP_HSTRING, STRING);
t.StyleSetSpec(wxSTC_HPHP_SIMPLESTRING, STRING);
t.StyleSetSpec(wxSTC_HPHP_COMMENT, COMMENT);
t.StyleSetSpec(wxSTC_HPHP_COMMENTLINE, COMMENT);
t.StyleSetSpec(wxSTC_TCL_COMMENT, COMMENT);
t.StyleSetSpec(wxSTC_TCL_COMMENTLINE, COMMENT);
t.StyleSetSpec(wxSTC_TCL_BLOCK_COMMENT, COMMENT);
t.StyleSetSpec(wxSTC_PAS_STRING, STRING);
t.StyleSetSpec(wxSTC_PAS_COMMENT, COMMENT);
t.StyleSetSpec(wxSTC_PAS_COMMENT2, COMMENT);
t.StyleSetSpec(wxSTC_PAS_COMMENTLINE, COMMENT);
}
int FileViewer::GetLexer(const wxString& ext)
{
struct LexerInfo
{
const char *ext;
int lexer;
};
static const LexerInfo s_lexer[] = {
{ "c", wxSTC_LEX_CPP },
{ "cpp", wxSTC_LEX_CPP },
{ "cc", wxSTC_LEX_CPP },
{ "cxx", wxSTC_LEX_CPP },
{ "h", wxSTC_LEX_CPP },
{ "hxx", wxSTC_LEX_CPP },
{ "hpp", wxSTC_LEX_CPP },
{ "py", wxSTC_LEX_PYTHON },
{ "htm", wxSTC_LEX_HTML },
{ "html", wxSTC_LEX_HTML },
{ "php", wxSTC_LEX_PHPSCRIPT },
{ "xml", wxSTC_LEX_XML },
{ "pas", wxSTC_LEX_PASCAL },
{ NULL, -1 }
};
wxString e = ext.Lower();
for ( const LexerInfo *i = s_lexer; i->ext; ++i )
{
if ( e == wxString::FromAscii(i->ext) )
return i->lexer;
}
return wxSTC_LEX_NULL;
}
wxFileName FileViewer::GetFilename(wxString ref) const
{
if ( ref.length() >= 3 &&
ref[1] == _T(':') &&
(ref[2] == _T('\\') || ref[2] == _T('/')) )
{
// This is an absolute Windows path (c:\foo... or c:/foo...); fix
// the latter case.
ref.Replace("/", "\\");
}
wxPathFormat pathfmt = ref.Contains(_T('\\')) ? wxPATH_WIN : wxPATH_UNIX;
wxFileName filename(ref.BeforeLast(_T(':')), pathfmt);
if ( filename.IsRelative() )
{
wxFileName relative(filename);
wxString basePath(m_basePath);
// Sometimes, the path in source reference is not relative to the PO
// file's location, but is relative to e.g. the root directory. See
// https://code.djangoproject.com/ticket/13936 for exhaustive
// discussion with plenty of examples.
//
// Deal with this by trying parent directories of m_basePath too. So if
// a file named project/locales/cs/foo.po has a reference to src/main.c,
// try not only project/locales/cs/src/main.c, but also
// project/locales/src/main.c and project/src/main.c etc.
while ( !basePath.empty() )
{
filename = relative;
filename.MakeAbsolute(basePath);
if ( filename.FileExists() )
{
return filename; // good, found the file
}
else
{
// remove the last path component
size_t last = basePath.find_last_of("\\/");
if ( last == wxString::npos )
break;
else
basePath.erase(last);
}
}
}
return wxFileName(); // invalid
}
void FileViewer::ShowReferences(CatalogPtr catalog, CatalogItemPtr item, int defaultReference)
{
m_basePath = catalog->GetSourcesBasePath();
if (m_basePath.empty())
m_basePath = wxPathOnly(catalog->GetFileName());
if (item)
m_references = item->GetReferences();
m_file->Clear();
m_file->Enable(m_references.size() > 1);
if (m_references.empty())
{
ShowError(_("No references for the selected item."));
}
else
{
for (auto& r: m_references)
m_file->Append(bidi::platform_mark_direction(r));
m_file->SetSelection(defaultReference);
SelectReference(m_references[defaultReference]);
}
}
void FileViewer::SelectReference(const wxString& ref)
{
const wxFileName filename = GetFilename(ref);
if (!filename.IsOk())
{
ShowError(wxString::Format(_("Error opening file %s!"), ref.BeforeLast(':')));
m_openInEditor->Disable();
return;
}
wxFFile file;
wxString data;
if ( !filename.IsFileReadable() ||
!file.Open(filename.GetFullPath()) ||
!file.ReadAll(&data, wxConvAuto()) )
{
ShowError(wxString::Format(_("Error opening file %s!"), ref.BeforeLast(':')));
m_openInEditor->Disable();
return;
}
m_openInEditor->Enable();
m_error->GetContainingSizer()->Hide(m_error);
m_text->GetContainingSizer()->Show(m_text);
Layout();
// support GNOME's xml2po's extension to references in the form of
// filename:line(xml_node):
wxString linenumStr = ref.AfterLast(_T(':')).BeforeFirst(_T('('));
long linenum;
if (!linenumStr.ToLong(&linenum))
linenum = 0;
m_text->SetReadOnly(false);
m_text->SetValue(data);
m_text->SetReadOnly(true);
m_text->MarkerDeleteAll(1);
m_text->MarkerAdd((int)linenum - 1, 1);
// Center the highlighted line:
int lineHeight = m_text->TextHeight((int)linenum);
int linesInWnd = m_text->GetSize().y / lineHeight;
m_text->ScrollToLine(wxMax(0, (int)linenum - linesInWnd/2));
}
void FileViewer::ShowError(const wxString& msg)
{
m_error->SetLabel(msg);
m_error->GetContainingSizer()->Show(m_error);
m_text->GetContainingSizer()->Hide(m_text);
Layout();
}
void FileViewer::OnChoice(wxCommandEvent &event)
{
SelectReference(m_references[event.GetSelection()]);
}
void FileViewer::OnEditFile(wxCommandEvent&)
{
wxFileName filename = GetFilename(bidi::strip_control_chars(m_file->GetStringSelection()));
if (filename.IsOk())
wxLaunchDefaultApplication(filename.GetFullPath());
}
<commit_msg>Unminimize references window on Windows when activated<commit_after>/*
* This file is part of Poedit (https://poedit.net)
*
* Copyright (C) 1999-2019 Vaclav Slavik
*
* 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 "fileviewer.h"
#include <wx/filename.h>
#include <wx/log.h>
#include <wx/button.h>
#include <wx/panel.h>
#include <wx/stattext.h>
#include <wx/choice.h>
#include <wx/config.h>
#include <wx/sizer.h>
#include <wx/settings.h>
#include <wx/listctrl.h>
#include <wx/fontenum.h>
#include <wx/ffile.h>
#include <wx/utils.h>
#include <wx/stc/stc.h>
#include "customcontrols.h"
#include "hidpi.h"
#include "utility.h"
#include "unicode_helpers.h"
namespace
{
#ifdef __WXOSX__
const int FRAME_STYLE = wxDEFAULT_FRAME_STYLE | wxFRAME_TOOL_WINDOW;
#else
const int FRAME_STYLE = wxDEFAULT_FRAME_STYLE;
#endif
} // anonymous namespace
FileViewer *FileViewer::ms_instance = nullptr;
FileViewer *FileViewer::GetAndActivate()
{
if (!ms_instance)
ms_instance = new FileViewer(nullptr);
ms_instance->Show();
if (ms_instance->IsIconized())
ms_instance->Iconize(false);
ms_instance->Raise();
return ms_instance;
}
FileViewer::FileViewer(wxWindow*)
: wxFrame(nullptr, wxID_ANY, _("Source file"), wxDefaultPosition, wxDefaultSize, FRAME_STYLE)
{
SetName("fileviewer");
wxPanel *panel = new wxPanel(this, -1);
wxSizer *sizer = new wxBoxSizer(wxVERTICAL);
panel->SetSizer(sizer);
#ifdef __WXOSX__
panel->SetWindowVariant(wxWINDOW_VARIANT_SMALL);
#endif
wxSizer *barsizer = new wxBoxSizer(wxHORIZONTAL);
sizer->Add(barsizer, wxSizerFlags().Expand().PXBorderAll());
barsizer->Add(new wxStaticText(panel, wxID_ANY,
_("Source file occurrence:")),
wxSizerFlags().Center().PXBorder(wxRIGHT));
m_file = new wxChoice(panel, wxID_ANY);
barsizer->Add(m_file, wxSizerFlags(1).Center());
m_openInEditor = new wxButton(panel, wxID_ANY, MSW_OR_OTHER(_("Open in editor"), _("Open in Editor")));
barsizer->Add(m_openInEditor, wxSizerFlags().Center().Border(wxLEFT, PX(10)));
m_text = new wxStyledTextCtrl(panel, wxID_ANY,
wxDefaultPosition, wxDefaultSize,
wxBORDER_THEME);
SetupTextCtrl();
sizer->Add(m_text, 1, wxEXPAND);
m_error = new wxStaticText(panel, wxID_ANY, "");
m_error->SetForegroundColour(ExplanationLabel::GetTextColor());
m_error->SetFont(m_error->GetFont().Larger().Larger());
sizer->Add(m_error, wxSizerFlags(1).Center().Border(wxTOP|wxBOTTOM, PX(80)));
RestoreWindowState(this, wxSize(PX(600), PX(400)));
wxSizer *topsizer = new wxBoxSizer(wxVERTICAL);
topsizer->Add(panel, wxSizerFlags(1).Expand());
SetSizer(topsizer);
// avoid flicker with these initial settings:
m_file->Disable();
sizer->Hide(m_error);
sizer->Hide(m_text);
Layout();
m_file->Bind(wxEVT_CHOICE, &FileViewer::OnChoice, this);
m_openInEditor->Bind(wxEVT_BUTTON, &FileViewer::OnEditFile, this);
#ifdef __WXOSX__
wxAcceleratorEntry entries[] = {
{ wxACCEL_CMD, 'W', wxID_CLOSE }
};
wxAcceleratorTable accel(WXSIZEOF(entries), entries);
SetAcceleratorTable(accel);
Bind(wxEVT_MENU, [=](wxCommandEvent&){ Destroy(); }, wxID_CLOSE);
#endif
}
FileViewer::~FileViewer()
{
ms_instance = nullptr;
SaveWindowState(this);
}
void FileViewer::SetupTextCtrl()
{
wxStyledTextCtrl& t = *m_text;
wxFont font = wxSystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT);
#ifdef __WXGTK__
font.SetFaceName("monospace");
#else
static const char *s_monospaced_fonts[] = {
#ifdef __WXMSW__
"Consolas",
"Lucida Console",
#endif
#ifdef __WXOSX__
"Menlo",
"Monaco",
#endif
NULL
};
for ( const char **f = s_monospaced_fonts; *f; ++f )
{
if ( wxFontEnumerator::IsValidFacename(*f) )
{
font.SetFaceName(*f);
break;
}
}
#endif
// style used:
wxString fontspec = wxString::Format("face:%s,size:%d",
font.GetFaceName().c_str(),
#ifdef __WXOSX__
font.GetPointSize() - 1
#else
font.GetPointSize()
#endif
);
const wxString DEFAULT = fontspec + ",fore:black,back:white";
const wxString STRING = fontspec + ",bold,fore:#882d21";
const wxString COMMENT = fontspec + ",fore:#487e18";
const wxString KEYWORD = fontspec + ",fore:#2f00f9";
const wxString LINENUMBERS = fontspec + ",fore:#5d8bab";
// current line marker
t.MarkerDefine(1, wxSTC_MARK_BACKGROUND, wxNullColour, wxColour(255,255,0));
// set fonts
t.StyleSetSpec(wxSTC_STYLE_DEFAULT, DEFAULT);
t.StyleSetSpec(wxSTC_STYLE_LINENUMBER, LINENUMBERS);
// line numbers margin size:
t.SetMarginType(0, wxSTC_MARGIN_NUMBER);
t.SetMarginWidth(0,
t.TextWidth(wxSTC_STYLE_LINENUMBER, "9999 "));
t.SetMarginWidth(1, 0);
t.SetMarginWidth(2, 3);
// set syntax highlighting styling
t.StyleSetSpec(wxSTC_C_STRING, STRING);
t.StyleSetSpec(wxSTC_C_COMMENT, COMMENT);
t.StyleSetSpec(wxSTC_C_COMMENTLINE, COMMENT);
t.StyleSetSpec(wxSTC_P_STRING, STRING);
t.StyleSetSpec(wxSTC_P_COMMENTLINE, COMMENT);
t.StyleSetSpec(wxSTC_P_COMMENTBLOCK, COMMENT);
t.StyleSetSpec(wxSTC_LUA_STRING, STRING);
t.StyleSetSpec(wxSTC_LUA_LITERALSTRING, STRING);
t.StyleSetSpec(wxSTC_LUA_COMMENT, COMMENT);
t.StyleSetSpec(wxSTC_LUA_COMMENTLINE, COMMENT);
t.StyleSetSpec(wxSTC_HPHP_HSTRING, STRING);
t.StyleSetSpec(wxSTC_HPHP_SIMPLESTRING, STRING);
t.StyleSetSpec(wxSTC_HPHP_COMMENT, COMMENT);
t.StyleSetSpec(wxSTC_HPHP_COMMENTLINE, COMMENT);
t.StyleSetSpec(wxSTC_TCL_COMMENT, COMMENT);
t.StyleSetSpec(wxSTC_TCL_COMMENTLINE, COMMENT);
t.StyleSetSpec(wxSTC_TCL_BLOCK_COMMENT, COMMENT);
t.StyleSetSpec(wxSTC_PAS_STRING, STRING);
t.StyleSetSpec(wxSTC_PAS_COMMENT, COMMENT);
t.StyleSetSpec(wxSTC_PAS_COMMENT2, COMMENT);
t.StyleSetSpec(wxSTC_PAS_COMMENTLINE, COMMENT);
}
int FileViewer::GetLexer(const wxString& ext)
{
struct LexerInfo
{
const char *ext;
int lexer;
};
static const LexerInfo s_lexer[] = {
{ "c", wxSTC_LEX_CPP },
{ "cpp", wxSTC_LEX_CPP },
{ "cc", wxSTC_LEX_CPP },
{ "cxx", wxSTC_LEX_CPP },
{ "h", wxSTC_LEX_CPP },
{ "hxx", wxSTC_LEX_CPP },
{ "hpp", wxSTC_LEX_CPP },
{ "py", wxSTC_LEX_PYTHON },
{ "htm", wxSTC_LEX_HTML },
{ "html", wxSTC_LEX_HTML },
{ "php", wxSTC_LEX_PHPSCRIPT },
{ "xml", wxSTC_LEX_XML },
{ "pas", wxSTC_LEX_PASCAL },
{ NULL, -1 }
};
wxString e = ext.Lower();
for ( const LexerInfo *i = s_lexer; i->ext; ++i )
{
if ( e == wxString::FromAscii(i->ext) )
return i->lexer;
}
return wxSTC_LEX_NULL;
}
wxFileName FileViewer::GetFilename(wxString ref) const
{
if ( ref.length() >= 3 &&
ref[1] == _T(':') &&
(ref[2] == _T('\\') || ref[2] == _T('/')) )
{
// This is an absolute Windows path (c:\foo... or c:/foo...); fix
// the latter case.
ref.Replace("/", "\\");
}
wxPathFormat pathfmt = ref.Contains(_T('\\')) ? wxPATH_WIN : wxPATH_UNIX;
wxFileName filename(ref.BeforeLast(_T(':')), pathfmt);
if ( filename.IsRelative() )
{
wxFileName relative(filename);
wxString basePath(m_basePath);
// Sometimes, the path in source reference is not relative to the PO
// file's location, but is relative to e.g. the root directory. See
// https://code.djangoproject.com/ticket/13936 for exhaustive
// discussion with plenty of examples.
//
// Deal with this by trying parent directories of m_basePath too. So if
// a file named project/locales/cs/foo.po has a reference to src/main.c,
// try not only project/locales/cs/src/main.c, but also
// project/locales/src/main.c and project/src/main.c etc.
while ( !basePath.empty() )
{
filename = relative;
filename.MakeAbsolute(basePath);
if ( filename.FileExists() )
{
return filename; // good, found the file
}
else
{
// remove the last path component
size_t last = basePath.find_last_of("\\/");
if ( last == wxString::npos )
break;
else
basePath.erase(last);
}
}
}
return wxFileName(); // invalid
}
void FileViewer::ShowReferences(CatalogPtr catalog, CatalogItemPtr item, int defaultReference)
{
m_basePath = catalog->GetSourcesBasePath();
if (m_basePath.empty())
m_basePath = wxPathOnly(catalog->GetFileName());
if (item)
m_references = item->GetReferences();
m_file->Clear();
m_file->Enable(m_references.size() > 1);
if (m_references.empty())
{
ShowError(_("No references for the selected item."));
}
else
{
for (auto& r: m_references)
m_file->Append(bidi::platform_mark_direction(r));
m_file->SetSelection(defaultReference);
SelectReference(m_references[defaultReference]);
}
}
void FileViewer::SelectReference(const wxString& ref)
{
const wxFileName filename = GetFilename(ref);
if (!filename.IsOk())
{
ShowError(wxString::Format(_("Error opening file %s!"), ref.BeforeLast(':')));
m_openInEditor->Disable();
return;
}
wxFFile file;
wxString data;
if ( !filename.IsFileReadable() ||
!file.Open(filename.GetFullPath()) ||
!file.ReadAll(&data, wxConvAuto()) )
{
ShowError(wxString::Format(_("Error opening file %s!"), ref.BeforeLast(':')));
m_openInEditor->Disable();
return;
}
m_openInEditor->Enable();
m_error->GetContainingSizer()->Hide(m_error);
m_text->GetContainingSizer()->Show(m_text);
Layout();
// support GNOME's xml2po's extension to references in the form of
// filename:line(xml_node):
wxString linenumStr = ref.AfterLast(_T(':')).BeforeFirst(_T('('));
long linenum;
if (!linenumStr.ToLong(&linenum))
linenum = 0;
m_text->SetReadOnly(false);
m_text->SetValue(data);
m_text->SetReadOnly(true);
m_text->MarkerDeleteAll(1);
m_text->MarkerAdd((int)linenum - 1, 1);
// Center the highlighted line:
int lineHeight = m_text->TextHeight((int)linenum);
int linesInWnd = m_text->GetSize().y / lineHeight;
m_text->ScrollToLine(wxMax(0, (int)linenum - linesInWnd/2));
}
void FileViewer::ShowError(const wxString& msg)
{
m_error->SetLabel(msg);
m_error->GetContainingSizer()->Show(m_error);
m_text->GetContainingSizer()->Hide(m_text);
Layout();
}
void FileViewer::OnChoice(wxCommandEvent &event)
{
SelectReference(m_references[event.GetSelection()]);
}
void FileViewer::OnEditFile(wxCommandEvent&)
{
wxFileName filename = GetFilename(bidi::strip_control_chars(m_file->GetStringSelection()));
if (filename.IsOk())
wxLaunchDefaultApplication(filename.GetFullPath());
}
<|endoftext|> |
<commit_before>#include "Cloth.h"
/*ClothPoint*/
ClothPoint::ClothPoint()
{
this->position = new vector3d(0.f, 0.f, 0.f, vector3d::rect);
this->mass = 0.0f;
this->velocity = new vector3d(0.f, 0.f, 0.f, vector3d::rect);
this->forces_sum = new vector3d(0.f, 0.f, 0.f, vector3d::rect);
this->normal = new vector3d(0.f, 0.f, 0.f, vector3d::rect);
this->intern_forces_sum = new vector3d(0.f, 0.f, 0.f, vector3d::rect);
}
ClothPoint::~ClothPoint()
{
}
ClothPoint::ClothPoint(vector3d* pos, float mass, vector3d* start_velocity) {
this->position = pos;
this->mass = mass;
this->velocity = start_velocity;
this->forces_sum = new vector3d(0.f,0.f,0.f,vector3d::rect);
this->normal = new vector3d(0.f, 0.f, 0.f, vector3d::rect);
this->intern_forces_sum = new vector3d(0.f, 0.f, 0.f, vector3d::rect);
}
void ClothPoint::give_force(vector3d* f) {
this->forces_sum->xyz()[0] += f->xyz()[0];
this->forces_sum->xyz()[1] += f->xyz()[1];
this->forces_sum->xyz()[2] += f->xyz()[2];
}
void ClothPoint::give_intern_force(vector3d* f) {
*(this->intern_forces_sum) += (*f);
}
void ClothPoint::calculate_pos(float dt) {
/*
accel_ij(t+dt) = (1/mass)*F_i,j(t)
vel_ij(t+dt) = vel_ij(t) + dt*accel_ij(t+dt)
pos_ij(t+dt) = pos_ij(t) + dt*vel_ij(t+dt)
*/
//calculate acceleration
vector3d* acc = *(this->forces_sum) - *(this->intern_forces_sum);
(*acc) /= this->mass;
//you know, let's try this out. It's a normal integral. Is it right? dunno. let's try.
//figure out new position
this->position->xyz()[0] = (0.5f * acc->xyz()[0] * dt*dt) + (this->velocity->xyz()[0] * dt) + (this->position->xyz()[0]);
this->position->xyz()[1] = (0.5f * acc->xyz()[1] * dt*dt) + (this->velocity->xyz()[1] * dt) + (this->position->xyz()[1]);
this->position->xyz()[2] = (0.5f * acc->xyz()[2] * dt*dt) + (this->velocity->xyz()[2] * dt) + (this->position->xyz()[2]);
//reset forces_sum
this->forces_sum->nullify();
this->intern_forces_sum->nullify();
delete acc;
}
void ClothPoint::set_pos(vector3d* pos) {
if (this->position != NULL) {
delete this->position;
}
this->position = pos;
}
void ClothPoint::set_pos(float x, float y, float z) {
vector3d temp(x, y, z, vector3d::rect);
if (this->position == NULL) {
this->position = new vector3d(x, y, z, vector3d::rect);
}else {
this->position->set_this_to_be_passed_in_value(&temp);
}
}
void ClothPoint::set_norm(vector3d* pos) {
this->normal->set_this_to_be_passed_in_value(pos);
}
vector3d* ClothPoint::get_pos() {
return this->position;
}
vector3d* ClothPoint::get_vel() {
return this->velocity;
}
vector3d* ClothPoint::get_norm() {
return this->normal;
}
void ClothPoint::set_mass(float m) {
this->mass = m;
}
float ClothPoint::get_mass() {
return this->mass;
}
/*CLOTH*/
Cloth::Cloth()
{
this->gravity = new vector3d(0.f, 0.f, 0.f, vector3d::rect);;
this->normal_distance = 0.1f;
this->stiffness = 10.0f;
this->dampening = 2;
this->viscoscity = 1;
}
Cloth::~Cloth()
{
}
void Cloth::apply_phyisics(VectorDefiner* vdef) {
vector3d* grav = new vector3d();
vector3d* vel = new vector3d();
/*external forces*/
for (int i = 0; i < 10; ++i) {
for (int j = 0; j < 10; ++j) {
ClothPoint p = this->the_grid[i][j];
//gravity
grav->set_this_to_be_passed_in_value(this->gravity);
(*grav)*= p.get_mass();
p.give_force(grav);
//dampening
vel->set_this_to_be_passed_in_value(p.get_vel());
(*vel) *= (-1.f * this->dampening);
p.give_force(vel);
//viscosity
vector3d* fluid_velocity = vdef->get_vector_at_pos(p.get_pos);
vector3d* temp = ((*fluid_velocity) - p.get_vel());
vector3d* norm;
vector3d* a;
vector3d* b;
//getting the normal at the point
if (i == 9) {
if (j==9) {
a = (*this->the_grid[i-1][j].get_pos() - *p.get_pos());
b = (*this->the_grid[i][j - 1].get_pos() - *p.get_pos());
norm = vector3d::Cross(a, b);
}else {
a = (*this->the_grid[i - 1][j].get_pos() - *p.get_pos());
b = (*this->the_grid[i][j + 1].get_pos() - *p.get_pos());
norm = vector3d::Cross(b, a);
}
}else if (j == 9) {
if (i == 9) {
a = (*this->the_grid[i - 1][j].get_pos() - *p.get_pos());
b = (*this->the_grid[i][j - 1].get_pos() - *p.get_pos());
norm = vector3d::Cross(a, b);
}
else{
b = (*this->the_grid[i][j - 1].get_pos() - *p.get_pos());
a = (*this->the_grid[i + 1][j].get_pos() - *p.get_pos());
norm = vector3d::Cross(b, a);
}
}else {
a = (*this->the_grid[i + 1][j].get_pos() - *p.get_pos());
b = (*this->the_grid[i][j + 1].get_pos() - *p.get_pos());
norm = vector3d::Cross(a, b);
}
//done get normal
float d = (*norm) * (*temp);
(*norm) *= d;
(*norm) *= this->viscoscity;
p.give_force(norm);//give
//cleanup
delete norm;
delete a;
delete b;
delete temp;
delete fluid_velocity;
}
}
/*Internal Forces*/
for (int i = 0; i < 9; ++i) {
for (int j = 0; j < 9; ++j) {
ClothPoint p = this->the_grid[i][j];
if (i < 8) {
ClothPoint pi2 = this->the_grid[i + 2][j];
this->spring_helper(&p, &pi2);
}
if (j < 8) {
ClothPoint pj2 = this->the_grid[i][j + 2];
this->spring_helper(&p, &pj2);
}
ClothPoint pi1 = this->the_grid[i + 1][j];
this->spring_helper(&p, &pi1);
ClothPoint pj1 = this->the_grid[i][j + 1];
this->spring_helper(&p, &pj1);
//crisscross
ClothPoint pi1j1 = this->the_grid[i + 1][j + 1];
this->spring_helper(&p, &pi1j1);
}
}
/*Internal Forces part 2*/
for (int i = 9; i > 0; --i) {
for (int j = 0; j < 9; ++j) {
ClothPoint p = this->the_grid[i][j];
ClothPoint pi1j1 = this->the_grid[i - 1][j + 1];
this->spring_helper(&p, &pi1j1);
}
}
delete grav;
delete vel;
}
void Cloth::spring_helper(ClothPoint* a, ClothPoint* b) {
//stiffness*[len - norm_len*(len/len_mag)]
vector3d* len = *b->get_pos() - *a->get_pos();
vector3d* len_unit = new vector3d(len); len_unit->unitize();
(*len_unit) *= this->normal_distance;
vector3d* temp = *len - *len_unit;
(*temp) *= this->stiffness;
a->give_intern_force(temp);
(*temp) *= -1.f;
b->give_intern_force(temp);
delete temp;
}
void Cloth::render() {
glBegin(GL_TRIANGLES);
glColor3f(0.1f, 0.2f, 0.3f);
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
glVertex3f(the_grid[i][j].get_pos()->xyz()[0], the_grid[i][j].get_pos()->xyz()[1], the_grid[i][j].get_pos()->xyz()[2]);
glVertex3f(the_grid[i + 1][j].get_pos()->xyz()[0], the_grid[i + 1][j].get_pos()->xyz()[1], the_grid[i + 1][j].get_pos()->xyz()[2]);
glVertex3f(the_grid[i][j + 1].get_pos()->xyz()[0], the_grid[i][j + 1].get_pos()->xyz()[1], the_grid[i][j + 1].get_pos()->xyz()[2]);
glVertex3f(the_grid[i + 1][j].get_pos()->xyz()[0], the_grid[i + 1][j].get_pos()->xyz()[1], the_grid[i + 1][j].get_pos()->xyz()[2]);
glVertex3f(the_grid[i + 1][j + 1].get_pos()->xyz()[0], the_grid[i + 1][j + 1].get_pos()->xyz()[1], the_grid[i + 1][j + 1].get_pos()->xyz()[2]);
glVertex3f(the_grid[i][j + 1].get_pos()->xyz()[0], the_grid[i][j + 1].get_pos()->xyz()[1], the_grid[i][j + 1].get_pos()->xyz()[2]);
}
}
glEnd();
}
<commit_msg>it builds now. sorry.<commit_after>#include "Cloth.h"
/*ClothPoint*/
ClothPoint::ClothPoint()
{
this->position = new vector3d(0.f, 0.f, 0.f, vector3d::rect);
this->mass = 0.0f;
this->velocity = new vector3d(0.f, 0.f, 0.f, vector3d::rect);
this->forces_sum = new vector3d(0.f, 0.f, 0.f, vector3d::rect);
this->normal = new vector3d(0.f, 0.f, 0.f, vector3d::rect);
this->intern_forces_sum = new vector3d(0.f, 0.f, 0.f, vector3d::rect);
}
ClothPoint::~ClothPoint()
{
}
ClothPoint::ClothPoint(vector3d* pos, float mass, vector3d* start_velocity) {
this->position = pos;
this->mass = mass;
this->velocity = start_velocity;
this->forces_sum = new vector3d(0.f,0.f,0.f,vector3d::rect);
this->normal = new vector3d(0.f, 0.f, 0.f, vector3d::rect);
this->intern_forces_sum = new vector3d(0.f, 0.f, 0.f, vector3d::rect);
}
void ClothPoint::give_force(vector3d* f) {
this->forces_sum->xyz()[0] += f->xyz()[0];
this->forces_sum->xyz()[1] += f->xyz()[1];
this->forces_sum->xyz()[2] += f->xyz()[2];
}
void ClothPoint::give_intern_force(vector3d* f) {
*(this->intern_forces_sum) += (*f);
}
void ClothPoint::calculate_pos(float dt) {
/*
accel_ij(t+dt) = (1/mass)*F_i,j(t)
vel_ij(t+dt) = vel_ij(t) + dt*accel_ij(t+dt)
pos_ij(t+dt) = pos_ij(t) + dt*vel_ij(t+dt)
*/
//calculate acceleration
vector3d* acc = *(this->forces_sum) - *(this->intern_forces_sum);
(*acc) /= this->mass;
//you know, let's try this out. It's a normal integral. Is it right? dunno. let's try.
//figure out new position
this->position->xyz()[0] = (0.5f * acc->xyz()[0] * dt*dt) + (this->velocity->xyz()[0] * dt) + (this->position->xyz()[0]);
this->position->xyz()[1] = (0.5f * acc->xyz()[1] * dt*dt) + (this->velocity->xyz()[1] * dt) + (this->position->xyz()[1]);
this->position->xyz()[2] = (0.5f * acc->xyz()[2] * dt*dt) + (this->velocity->xyz()[2] * dt) + (this->position->xyz()[2]);
//reset forces_sum
this->forces_sum->nullify();
this->intern_forces_sum->nullify();
delete acc;
}
void ClothPoint::set_pos(vector3d* pos) {
if (this->position != NULL) {
delete this->position;
}
this->position = pos;
}
void ClothPoint::set_pos(float x, float y, float z) {
vector3d temp(x, y, z, vector3d::rect);
if (this->position == NULL) {
this->position = new vector3d(x, y, z, vector3d::rect);
}else {
this->position->set_this_to_be_passed_in_value(&temp);
}
}
void ClothPoint::set_norm(vector3d* pos) {
this->normal->set_this_to_be_passed_in_value(pos);
}
vector3d* ClothPoint::get_pos() {
return this->position;
}
vector3d* ClothPoint::get_vel() {
return this->velocity;
}
vector3d* ClothPoint::get_norm() {
return this->normal;
}
void ClothPoint::set_mass(float m) {
this->mass = m;
}
float ClothPoint::get_mass() {
return this->mass;
}
/*CLOTH*/
Cloth::Cloth()
{
this->gravity = new vector3d(0.f, 0.f, 0.f, vector3d::rect);;
this->normal_distance = 0.1f;
this->stiffness = 10.0f;
this->dampening = 2;
this->viscoscity = 1;
}
Cloth::~Cloth()
{
}
void Cloth::apply_phyisics(VectorDefiner* vdef) {
vector3d* grav = new vector3d();
vector3d* vel = new vector3d();
/*external forces*/
for (int i = 0; i < 10; ++i) {
for (int j = 0; j < 10; ++j) {
ClothPoint p = this->the_grid[i][j];
//gravity
grav->set_this_to_be_passed_in_value(this->gravity);
(*grav)*= p.get_mass();
p.give_force(grav);
//dampening
vel->set_this_to_be_passed_in_value(p.get_vel());
(*vel) *= (-1.f * this->dampening);
p.give_force(vel);
//viscosity
vector3d* fluid_velocity = vdef->get_vector_at_pos(p.get_pos());
vector3d* temp = ((*fluid_velocity) - p.get_vel());
vector3d* norm;
vector3d* a;
vector3d* b;
//getting the normal at the point
if (i == 9) {
if (j==9) {
a = (*this->the_grid[i-1][j].get_pos() - *p.get_pos());
b = (*this->the_grid[i][j - 1].get_pos() - *p.get_pos());
norm = vector3d::Cross(a, b);
}else {
a = (*this->the_grid[i - 1][j].get_pos() - *p.get_pos());
b = (*this->the_grid[i][j + 1].get_pos() - *p.get_pos());
norm = vector3d::Cross(b, a);
}
}else if (j == 9) {
if (i == 9) {
a = (*this->the_grid[i - 1][j].get_pos() - *p.get_pos());
b = (*this->the_grid[i][j - 1].get_pos() - *p.get_pos());
norm = vector3d::Cross(a, b);
}
else{
b = (*this->the_grid[i][j - 1].get_pos() - *p.get_pos());
a = (*this->the_grid[i + 1][j].get_pos() - *p.get_pos());
norm = vector3d::Cross(b, a);
}
}else {
a = (*this->the_grid[i + 1][j].get_pos() - *p.get_pos());
b = (*this->the_grid[i][j + 1].get_pos() - *p.get_pos());
norm = vector3d::Cross(a, b);
}
//done get normal
float d = (*norm) * (*temp);
(*norm) *= d;
(*norm) *= this->viscoscity;
p.give_force(norm);//give
//cleanup
delete norm;
delete a;
delete b;
delete temp;
delete fluid_velocity;
}
}
/*Internal Forces*/
for (int i = 0; i < 9; ++i) {
for (int j = 0; j < 9; ++j) {
ClothPoint p = this->the_grid[i][j];
if (i < 8) {
ClothPoint pi2 = this->the_grid[i + 2][j];
this->spring_helper(&p, &pi2);
}
if (j < 8) {
ClothPoint pj2 = this->the_grid[i][j + 2];
this->spring_helper(&p, &pj2);
}
ClothPoint pi1 = this->the_grid[i + 1][j];
this->spring_helper(&p, &pi1);
ClothPoint pj1 = this->the_grid[i][j + 1];
this->spring_helper(&p, &pj1);
//crisscross
ClothPoint pi1j1 = this->the_grid[i + 1][j + 1];
this->spring_helper(&p, &pi1j1);
}
}
/*Internal Forces part 2*/
for (int i = 9; i > 0; --i) {
for (int j = 0; j < 9; ++j) {
ClothPoint p = this->the_grid[i][j];
ClothPoint pi1j1 = this->the_grid[i - 1][j + 1];
this->spring_helper(&p, &pi1j1);
}
}
delete grav;
delete vel;
}
void Cloth::spring_helper(ClothPoint* a, ClothPoint* b) {
//stiffness*[len - norm_len*(len/len_mag)]
vector3d* len = *b->get_pos() - *a->get_pos();
vector3d* len_unit = new vector3d(len); len_unit->unitize();
(*len_unit) *= this->normal_distance;
vector3d* temp = *len - *len_unit;
(*temp) *= this->stiffness;
a->give_intern_force(temp);
(*temp) *= -1.f;
b->give_intern_force(temp);
delete temp;
}
void Cloth::render() {
glBegin(GL_TRIANGLES);
glColor3f(0.1f, 0.2f, 0.3f);
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
glVertex3f(the_grid[i][j].get_pos()->xyz()[0], the_grid[i][j].get_pos()->xyz()[1], the_grid[i][j].get_pos()->xyz()[2]);
glVertex3f(the_grid[i + 1][j].get_pos()->xyz()[0], the_grid[i + 1][j].get_pos()->xyz()[1], the_grid[i + 1][j].get_pos()->xyz()[2]);
glVertex3f(the_grid[i][j + 1].get_pos()->xyz()[0], the_grid[i][j + 1].get_pos()->xyz()[1], the_grid[i][j + 1].get_pos()->xyz()[2]);
glVertex3f(the_grid[i + 1][j].get_pos()->xyz()[0], the_grid[i + 1][j].get_pos()->xyz()[1], the_grid[i + 1][j].get_pos()->xyz()[2]);
glVertex3f(the_grid[i + 1][j + 1].get_pos()->xyz()[0], the_grid[i + 1][j + 1].get_pos()->xyz()[1], the_grid[i + 1][j + 1].get_pos()->xyz()[2]);
glVertex3f(the_grid[i][j + 1].get_pos()->xyz()[0], the_grid[i][j + 1].get_pos()->xyz()[1], the_grid[i][j + 1].get_pos()->xyz()[2]);
}
}
glEnd();
}
<|endoftext|> |
<commit_before>#include "scientistservice.h"
using namespace std;
//operator overloading for scientistSort.
bool sortByNameAsc (const Scientist &a, const Scientist &b) { return a.getName() < b.getName(); }
bool sortByNameDesc(const Scientist &a, const Scientist &b) { return a.getName() > b.getName(); }
bool sortByGender (const Scientist &a, const Scientist &b) { return a.getGender() < b.getGender(); }
bool sortByBirth (const Scientist &a, const Scientist &b) { return a.getBirth() < b.getBirth(); }
bool sortByDeath (const Scientist &a, const Scientist &b) { return a.getDeath() < b.getDeath(); }
bool sortByAge (const Scientist &a, const Scientist &b) { return a.getAge() < b.getAge(); }
ScientistService::ScientistService()
{
}
vector<Scientist> ScientistService::getScientists()
{ // Uploads the list of scientists from file.
DataAccess data;
_scientists = data.loadScientists();
return _scientists;
}
bool ScientistService::addScientist(string name, char gender, int birth, int death, int age)
{ // Adds a scientist to the list and updates the file.
// returns true if adding succeded, false otherwise.
Scientist scientist(name, gender, birth, death, age);
DataAccess data;
if (findScientistByName(name).size() > 0)
{
return false;
}
else
{
_scientists.push_back(scientist);
data.saveScientists(_scientists);
return true;
}
}
bool ScientistService::removeScientist(string name)
{ // removes a scientist with that name from the vector.
// returns true if removeing succeded, false otherwise.
DataAccess data;
if (findScientistByName(name).size() > 0)
{
Scientist toRemove = findScientistByName(name).at(0);
_scientists.erase(remove(_scientists.begin(), _scientists.end(), toRemove), _scientists.end());
data.saveScientists(_scientists);
return true;
}
return false;
}
void ScientistService::scientistSort(int sortType)
{ // Sort by parameter, 1 = name(A-Z), 2 = name(Z-A), 3 = gender, 4 = birth, 5 = death, 6 = age
// change to switch case?
DataAccess data;
if (sortType == 1)
{
sort(_scientists.begin(), _scientists.end(), sortByNameAsc);
}
else if (sortType == 2)
{
sort(_scientists.begin(), _scientists.end(), sortByNameDesc);
}
else if (sortType == 3)
{
sort(_scientists.begin(), _scientists.end(), sortByGender);
}
else if (sortType == 4)
{
sort(_scientists.begin(), _scientists.end(), sortByBirth);
}
else if (sortType == 5)
{
sort(_scientists.begin(), _scientists.end(), sortByDeath);
}
else if (sortType == 6)
{
sort(_scientists.begin(), _scientists.end(), sortByAge);
}
data.saveScientists(_scientists);
}
vector<Scientist> ScientistService::findScientistByName(string name)
{ // Returns all scientists with the full name specified.
// TODO leita eftir part úr nafni?
vector<Scientist> scientist;
string databaseName;
for (size_t i = 0; i < _scientists.size(); i++)
{
databaseName = _scientists[i].getName();
transform(databaseName.begin(), databaseName.end(), databaseName.begin(), ::tolower);
transform(name.begin(), name.end(), name.begin(), ::tolower);
if (databaseName == name)
{
scientist.push_back(_scientists[i]);
}
}
return scientist;
}
vector<Scientist> ScientistService::findScientistByGender(char gender)
{ // Returns all scientists of that gender.
vector<Scientist> scientist;
for (size_t i = 0; i < _scientists.size(); i++)
{
if (_scientists[i].getGender() == gender)
{
scientist.push_back(_scientists[i]);
}
}
return scientist;
}
vector<Scientist> ScientistService::findScientistByBirth(int birth)
{ // Returns all scientists born that year.
vector<Scientist> scientist;
for (size_t i = 0; i < _scientists.size(); i++)
{
if (_scientists[i].getBirth() == birth)
{
scientist.push_back(_scientists[i]);
}
}
return scientist;
}
vector<Scientist> ScientistService::findScientistByBirthRange(int birth1, int birth2)
{ // Returns all scientists with same age as parameter ( int age )
vector<Scientist> scientist;
int temp;
if(birth1 > birth2)
{
temp = birth1;
birth1 = birth2;
birth2 = temp;
}
for (size_t i = 0; i < _scientists.size(); i++)
{
if (_scientists[i].getBirth() > birth1 && _scientists[i].getBirth() < birth2)
{
scientist.push_back(_scientists[i]);
}
}
return scientist;
}
vector<Scientist> ScientistService::findScientistByDeath(int death)
{ // Returns all scientists that died that year, or death = 0 for still alive..
vector<Scientist> scientist;
for (size_t i = 0; i < _scientists.size(); i++)
{
if (_scientists[i].getDeath() == death)
{
scientist.push_back(_scientists[i]);
}
}
return scientist;
}
vector<Scientist> ScientistService::findScientistByDeathRange(int death1, int death2)
{ // Returns all scientists with same age as parameter ( int age )
vector<Scientist> scientist;
int temp;
if(death1 > death2)
{
temp = death1;
death1 = death2;
death2 = temp;
}
for (size_t i = 0; i < _scientists.size(); i++)
{
if (_scientists[i].getDeath() > death1 && _scientists[i].getDeath() < death2)
{
scientist.push_back(_scientists[i]);
}
}
return scientist;
}
vector<Scientist> ScientistService::findScientistByAge(int age)
{ // Returns all scientists with same age as parameter ( int age )
vector<Scientist> scientist;
for (size_t i = 0; i < _scientists.size(); i++)
{
if (_scientists[i].getAge() == age)
{
scientist.push_back(_scientists[i]);
}
}
return scientist;
}
vector<Scientist> ScientistService::findScientistByAgeRange(int age1, int age2)
{ // Returns all scientists with same age as parameter ( int age )
vector<Scientist> scientist;
int temp;
if(age1 > age2)
{
temp = age1;
age1 = age2;
age2 = temp;
}
for (size_t i = 0; i < _scientists.size(); i++)
{
if (_scientists[i].getAge() > age1 && _scientists[i].getAge() < age2)
{
scientist.push_back(_scientists[i]);
}
}
return scientist;
}
<commit_msg>made the name sort incase sensitive<commit_after>#include "scientistservice.h"
using namespace std;
//operator overloading for scientistSort.
bool sortByNameAsc (const Scientist &a, const Scientist &b)
{ // also makes the sort case insensitive
string aName = a.getName(), bName = b.getName();
transform(aName.begin(), aName.end(), aName.begin(), ::tolower);
transform(bName.begin(), bName.end(), bName.begin(), ::tolower);
return aName < bName;
}
bool sortByNameDesc(const Scientist &a, const Scientist &b)
{ // also makes the sort case insensitive
string aName = a.getName(), bName = b.getName();
transform(aName.begin(), aName.end(), aName.begin(), ::tolower);
transform(bName.begin(), bName.end(), bName.begin(), ::tolower);
return aName > bName;
}
bool sortByGender (const Scientist &a, const Scientist &b) { return a.getGender() < b.getGender(); }
bool sortByBirth (const Scientist &a, const Scientist &b) { return a.getBirth() < b.getBirth(); }
bool sortByDeath (const Scientist &a, const Scientist &b) { return a.getDeath() < b.getDeath(); }
bool sortByAge (const Scientist &a, const Scientist &b) { return a.getAge() < b.getAge(); }
ScientistService::ScientistService()
{
}
vector<Scientist> ScientistService::getScientists()
{ // Uploads the list of scientists from file.
DataAccess data;
_scientists = data.loadScientists();
return _scientists;
}
bool ScientistService::addScientist(string name, char gender, int birth, int death, int age)
{ // Adds a scientist to the list and updates the file.
// returns true if adding succeded, false otherwise.
Scientist scientist(name, gender, birth, death, age);
DataAccess data;
if (findScientistByName(name).size() > 0)
{
return false;
}
else
{
_scientists.push_back(scientist);
data.saveScientists(_scientists);
return true;
}
}
bool ScientistService::removeScientist(string name)
{ // removes a scientist with that name from the vector.
// returns true if removeing succeded, false otherwise.
DataAccess data;
if (findScientistByName(name).size() > 0)
{
Scientist toRemove = findScientistByName(name).at(0);
_scientists.erase(remove(_scientists.begin(), _scientists.end(), toRemove), _scientists.end());
data.saveScientists(_scientists);
return true;
}
return false;
}
void ScientistService::scientistSort(int sortType)
{ // Sort by parameter, 1 = name(A-Z), 2 = name(Z-A), 3 = gender, 4 = birth, 5 = death, 6 = age
// change to switch case?
DataAccess data;
if (sortType == 1)
{
sort(_scientists.begin(), _scientists.end(), sortByNameAsc);
}
else if (sortType == 2)
{
sort(_scientists.begin(), _scientists.end(), sortByNameDesc);
}
else if (sortType == 3)
{
sort(_scientists.begin(), _scientists.end(), sortByGender);
}
else if (sortType == 4)
{
sort(_scientists.begin(), _scientists.end(), sortByBirth);
}
else if (sortType == 5)
{
sort(_scientists.begin(), _scientists.end(), sortByDeath);
}
else if (sortType == 6)
{
sort(_scientists.begin(), _scientists.end(), sortByAge);
}
data.saveScientists(_scientists);
}
vector<Scientist> ScientistService::findScientistByName(string name)
{ // Returns all scientists with the full name specified.
// TODO leita eftir part úr nafni?
vector<Scientist> scientist;
string databaseName;
for (size_t i = 0; i < _scientists.size(); i++)
{
databaseName = _scientists[i].getName();
transform(databaseName.begin(), databaseName.end(), databaseName.begin(), ::tolower);
transform(name.begin(), name.end(), name.begin(), ::tolower);
if (databaseName == name)
{
scientist.push_back(_scientists[i]);
}
}
return scientist;
}
vector<Scientist> ScientistService::findScientistByGender(char gender)
{ // Returns all scientists of that gender.
vector<Scientist> scientist;
for (size_t i = 0; i < _scientists.size(); i++)
{
if (_scientists[i].getGender() == gender)
{
scientist.push_back(_scientists[i]);
}
}
return scientist;
}
vector<Scientist> ScientistService::findScientistByBirth(int birth)
{ // Returns all scientists born that year.
vector<Scientist> scientist;
for (size_t i = 0; i < _scientists.size(); i++)
{
if (_scientists[i].getBirth() == birth)
{
scientist.push_back(_scientists[i]);
}
}
return scientist;
}
vector<Scientist> ScientistService::findScientistByBirthRange(int birth1, int birth2)
{ // Returns all scientists with same age as parameter ( int age )
vector<Scientist> scientist;
int temp;
if(birth1 > birth2)
{
temp = birth1;
birth1 = birth2;
birth2 = temp;
}
for (size_t i = 0; i < _scientists.size(); i++)
{
if (_scientists[i].getBirth() > birth1 && _scientists[i].getBirth() < birth2)
{
scientist.push_back(_scientists[i]);
}
}
return scientist;
}
vector<Scientist> ScientistService::findScientistByDeath(int death)
{ // Returns all scientists that died that year, or death = 0 for still alive..
vector<Scientist> scientist;
for (size_t i = 0; i < _scientists.size(); i++)
{
if (_scientists[i].getDeath() == death)
{
scientist.push_back(_scientists[i]);
}
}
return scientist;
}
vector<Scientist> ScientistService::findScientistByDeathRange(int death1, int death2)
{ // Returns all scientists with same age as parameter ( int age )
vector<Scientist> scientist;
int temp;
if(death1 > death2)
{
temp = death1;
death1 = death2;
death2 = temp;
}
for (size_t i = 0; i < _scientists.size(); i++)
{
if (_scientists[i].getDeath() > death1 && _scientists[i].getDeath() < death2)
{
scientist.push_back(_scientists[i]);
}
}
return scientist;
}
vector<Scientist> ScientistService::findScientistByAge(int age)
{ // Returns all scientists with same age as parameter ( int age )
vector<Scientist> scientist;
for (size_t i = 0; i < _scientists.size(); i++)
{
if (_scientists[i].getAge() == age)
{
scientist.push_back(_scientists[i]);
}
}
return scientist;
}
vector<Scientist> ScientistService::findScientistByAgeRange(int age1, int age2)
{ // Returns all scientists with same age as parameter ( int age )
vector<Scientist> scientist;
int temp;
if(age1 > age2)
{
temp = age1;
age1 = age2;
age2 = temp;
}
for (size_t i = 0; i < _scientists.size(); i++)
{
if (_scientists[i].getAge() > age1 && _scientists[i].getAge() < age2)
{
scientist.push_back(_scientists[i]);
}
}
return scientist;
}
<|endoftext|> |
<commit_before>/*
Dwarf Therapist
Copyright (c) 2010 Justin Ehlert
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 "caste.h"
#include "dfinstance.h"
#include "memorylayout.h"
#include "truncatingfilelogger.h"
#include <QtDebug>
#include "gamedatareader.h"
Caste::Caste(DFInstance *df, VIRTADDR address, QString race_name, QObject *parent)
: QObject(parent)
, m_address(address)
, m_race_name(race_name)
, m_tag(QString::null)
, m_name(QString::null)
, m_description(QString::null)
, m_df(df)
, m_mem(df->memory_layout())
{
load_data();
}
Caste::~Caste() {
}
Caste* Caste::get_caste(DFInstance *df, const VIRTADDR & address, QString race_name) {
return new Caste(df, address, race_name);
}
void Caste::load_data() {
if (!m_df || !m_df->memory_layout() || !m_df->memory_layout()->is_valid()) {
LOGW << "load of Castes called but we're not connected";
return;
}
// make sure our reference is up to date to the active memory layout
m_mem = m_df->memory_layout();
TRACE << "Starting refresh of Caste data at" << hexify(m_address);
read_caste();
}
void Caste::read_caste() {
m_tag = m_df->read_string(m_address);
m_name = capitalizeEach(m_df->read_string(m_address + m_mem->caste_offset("caste_name")));
//needed for mods with caste's name not specified
if (m_name.toLower()==m_race_name.toLower())
{
if ((m_tag.toLower()!="male")&&(m_tag.toLower()!="female"))
{
m_name = capitalizeEach(m_tag.remove("_MALE").remove("_FEMALE").replace("_"," ").toLower());
}
}
m_description = m_df->read_string(m_address + m_mem->caste_offset("caste_descr"));
// could update this to read the child/baby sizes instead of just the adult size
// QVector<VIRTADDR> body_sizes = m_df->enumerate_vector(m_address + m_mem->caste_offset("body_sizes_vector"));
// foreach(VIRTADDR size, body_sizes){
// m_body_sizes.prepend((int)size);
// }
m_body_sizes.append(m_df->read_int(m_address + m_mem->caste_offset("adult_size")));
}
void Caste::load_attribute_info(){
//physical attributes (seems mental attribs follow so load them all at once)
VIRTADDR base = m_address + m_mem->caste_offset("caste_phys_att_ranges");
for (int i=0; i<19; i++)
{
att_range r;
int max = m_df->read_int(base + i*28 + 12) + 1000; //max is median + 1000
//load the raws, add the 0-first bin
r.raw_bins.append(0);
for (int j=0; j<7; j++)
{
int val = m_df->read_int(base + i*28 + j*4);
r.raw_bins.append(val);
//TRACE << m_name << " " << i << " " << j << " " << val;
}
//add the top range - 5000 bin
r.raw_bins.append(5000);
//now load the display/descriptor ranges
for(int k=0; k<9; k++){
//avoid the median
if(k!=4)
r.display_bins.prepend(max < 0 ? 0 : max);
max -= 250; //game spaces by 250 per description bin
}
m_ranges.insert(i,r);
}
}
Caste::attribute_level Caste::get_attribute_level(int id, int value)
{
if(m_ranges.count()<=0)
load_attribute_info();
att_range r = m_ranges.value(id);
attribute_level l;
l.rating = 0;
int idx = 0;
Attribute *a = GameDataReader::ptr()->get_attribute(id);
for(int i=0; i < r.display_bins.length(); i++){
if(value <= r.display_bins.at(i)){
if(i!=4){
if(i<4) //the middle bin is always 0
idx=4;
else if(i>4)
idx=5;
l.rating = r.display_bins.at(i) - r.raw_bins.at(idx);
if(l.rating==0)
l.rating=250;
l.rating /= 66.66; //this is for our drawing rating (-15 -> +15)
}
l.description = a->m_display_descriptions.at(i);
return l;
}
}
l.description = a->m_display_descriptions.at(a->m_display_descriptions.count()-1);
l.rating = 20;
return l;
}
int Caste::get_body_size(int index){
if(m_body_sizes.size()>index)
return m_body_sizes.at(index);
else
return 0;
}
<commit_msg>change for castes to always read the caste name, rather than using the id as the caste name in cases where the mod author left out the CASTE_NAME tag<commit_after>/*
Dwarf Therapist
Copyright (c) 2010 Justin Ehlert
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 "caste.h"
#include "dfinstance.h"
#include "memorylayout.h"
#include "truncatingfilelogger.h"
#include <QtDebug>
#include "gamedatareader.h"
Caste::Caste(DFInstance *df, VIRTADDR address, QString race_name, QObject *parent)
: QObject(parent)
, m_address(address)
, m_race_name(race_name)
, m_tag(QString::null)
, m_name(QString::null)
, m_description(QString::null)
, m_df(df)
, m_mem(df->memory_layout())
{
load_data();
}
Caste::~Caste() {
}
Caste* Caste::get_caste(DFInstance *df, const VIRTADDR & address, QString race_name) {
return new Caste(df, address, race_name);
}
void Caste::load_data() {
if (!m_df || !m_df->memory_layout() || !m_df->memory_layout()->is_valid()) {
LOGW << "load of Castes called but we're not connected";
return;
}
// make sure our reference is up to date to the active memory layout
m_mem = m_df->memory_layout();
TRACE << "Starting refresh of Caste data at" << hexify(m_address);
read_caste();
}
void Caste::read_caste() {
m_tag = m_df->read_string(m_address);
m_name = capitalizeEach(m_df->read_string(m_address + m_mem->caste_offset("caste_name")));
// //needed for mods with caste's name not specified
// !!!!doesn't work with mods that require hidden castes. mod creators shouldn't be creating castes with no names unless they want them hidden...
// if (m_name.toLower()==m_race_name.toLower())
// {
// if ((m_tag.toLower()!="male")&&(m_tag.toLower()!="female"))
// {
// m_name = capitalizeEach(m_tag.remove("_MALE").remove("_FEMALE").replace("_"," ").toLower());
// }
// }
m_description = m_df->read_string(m_address + m_mem->caste_offset("caste_descr"));
// could update this to read the child/baby sizes instead of just the adult size
// QVector<VIRTADDR> body_sizes = m_df->enumerate_vector(m_address + m_mem->caste_offset("body_sizes_vector"));
// foreach(VIRTADDR size, body_sizes){
// m_body_sizes.prepend((int)size);
// }
m_body_sizes.append(m_df->read_int(m_address + m_mem->caste_offset("adult_size")));
}
void Caste::load_attribute_info(){
//physical attributes (seems mental attribs follow so load them all at once)
VIRTADDR base = m_address + m_mem->caste_offset("caste_phys_att_ranges");
for (int i=0; i<19; i++)
{
att_range r;
int max = m_df->read_int(base + i*28 + 12) + 1000; //max is median + 1000
//load the raws, add the 0-first bin
r.raw_bins.append(0);
for (int j=0; j<7; j++)
{
int val = m_df->read_int(base + i*28 + j*4);
r.raw_bins.append(val);
//TRACE << m_name << " " << i << " " << j << " " << val;
}
//add the top range - 5000 bin
r.raw_bins.append(5000);
//now load the display/descriptor ranges
for(int k=0; k<9; k++){
//avoid the median
if(k!=4)
r.display_bins.prepend(max < 0 ? 0 : max);
max -= 250; //game spaces by 250 per description bin
}
m_ranges.insert(i,r);
}
}
Caste::attribute_level Caste::get_attribute_level(int id, int value)
{
if(m_ranges.count()<=0)
load_attribute_info();
att_range r = m_ranges.value(id);
attribute_level l;
l.rating = 0;
int idx = 0;
Attribute *a = GameDataReader::ptr()->get_attribute(id);
for(int i=0; i < r.display_bins.length(); i++){
if(value <= r.display_bins.at(i)){
if(i!=4){
if(i<4) //the middle bin is always 0
idx=4;
else if(i>4)
idx=5;
l.rating = r.display_bins.at(i) - r.raw_bins.at(idx);
if(l.rating==0)
l.rating=250;
l.rating /= 66.66; //this is for our drawing rating (-15 -> +15)
}
l.description = a->m_display_descriptions.at(i);
return l;
}
}
l.description = a->m_display_descriptions.at(a->m_display_descriptions.count()-1);
l.rating = 20;
return l;
}
int Caste::get_body_size(int index){
if(m_body_sizes.size()>index)
return m_body_sizes.at(index);
else
return 0;
}
<|endoftext|> |
<commit_before>/*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Author: sligocki@google.com (Shawn Ligocki)
#include "net/instaweb/rewriter/public/css_image_rewriter.h"
#include "base/scoped_ptr.h"
#include "net/instaweb/rewriter/public/cache_extender.h"
#include "net/instaweb/rewriter/public/img_rewrite_filter.h"
#include "net/instaweb/rewriter/public/output_resource.h"
#include "net/instaweb/rewriter/public/resource_manager.h"
#include "net/instaweb/rewriter/public/rewrite_driver.h"
#include "net/instaweb/util/public/google_url.h"
#include "net/instaweb/util/public/message_handler.h"
#include "net/instaweb/util/public/statistics.h"
#include <string>
#include "net/instaweb/util/public/string_util.h"
#include "webutil/css/parser.h"
namespace net_instaweb {
// Statistics names.
const char CssImageRewriter::kImageRewrites[] = "css_image_rewrites";
const char CssImageRewriter::kCacheExtends[] = "css_image_cache_extends";
const char CssImageRewriter::kNoRewrite[] = "css_image_no_rewrite";
CssImageRewriter::CssImageRewriter(RewriteDriver* driver,
CacheExtender* cache_extender,
ImgRewriteFilter* image_rewriter)
: driver_(driver),
cache_extender_(cache_extender),
image_rewriter_(image_rewriter),
image_rewrites_(NULL),
cache_extends_(NULL),
no_rewrite_(NULL) {
Statistics* stats = driver_->resource_manager()->statistics();
if (stats != NULL) {
image_rewrites_ = stats->GetVariable(kImageRewrites);
// TODO(sligocki): Should this be shared with CacheExtender or kept
// separately? I think it's useful to know how many images were optimized
// from CSS files, but people probably also want to know how many total
// images were cache-extended.
cache_extends_ = stats->GetVariable(kCacheExtends);
no_rewrite_ = stats->GetVariable(kNoRewrite);
}
}
CssImageRewriter::~CssImageRewriter() {}
void CssImageRewriter::Initialize(Statistics* statistics) {
statistics->AddVariable(kImageRewrites);
statistics->AddVariable(kCacheExtends);
statistics->AddVariable(kNoRewrite);
}
bool CssImageRewriter::RewriteImageUrl(const GURL& base_url,
const StringPiece& old_rel_url,
std::string* new_url,
MessageHandler* handler) {
bool ret = false;
const char* old_rel_url_cstr = old_rel_url.as_string().c_str();
scoped_ptr<Resource> input_resource(
driver_->resource_manager()->CreateInputResource(
base_url, old_rel_url, driver_->options(), handler));
if (input_resource.get() != NULL) {
scoped_ptr<OutputResource::CachedResult> rewrite_info;
// TODO(sligocki): Try image rewriting.
//handler->Message(kInfo, "Attempting to rewrite image %s",
// old_rel_url_cstr);
//rewrite_info.reset(img_rewriter_->RewriteWithCaching(original_url_string));
//if (rewrite_info.get() != NULL && rewrite_info->optimizable()) {
// if (image_rewrites_ != NULL) {
// image_rewrites_->Add(1);
// }
// *new_url = rewrite_info->url();
// ret = true;
//} else
{
// Try cache extending.
handler->Message(kInfo, "Attempting to cache extend image %s",
old_rel_url_cstr);
rewrite_info.reset(
cache_extender_->RewriteExternalResource(input_resource.get()));
if (rewrite_info.get() != NULL && rewrite_info->optimizable()) {
if (cache_extends_ != NULL) {
cache_extends_->Add(1);
}
*new_url = rewrite_info->url();
ret = true;
}
}
}
return ret;
}
bool CssImageRewriter::RewriteCssImages(const GURL& base_url,
Css::Stylesheet* stylesheet,
MessageHandler* handler) {
bool editted = false;
handler->Message(kInfo, "Starting to rewrite images in CSS in %s",
base_url.spec().c_str());
Css::Rulesets& rulesets = stylesheet->mutable_rulesets();
for (Css::Rulesets::iterator ruleset_iter = rulesets.begin();
ruleset_iter != rulesets.end(); ++ruleset_iter) {
Css::Ruleset* ruleset = *ruleset_iter;
Css::Declarations& decls = ruleset->mutable_declarations();
for (Css::Declarations::iterator decl_iter = decls.begin();
decl_iter != decls.end(); ++decl_iter) {
Css::Declaration* decl = *decl_iter;
// Only edit image declarations.
switch (decl->prop()) {
case Css::Property::BACKGROUND:
case Css::Property::BACKGROUND_IMAGE:
case Css::Property::LIST_STYLE:
case Css::Property::LIST_STYLE_IMAGE: {
// Rewrite all URLs. Technically, background-image should only
// have a single value which is a URL, but background could have
// more values.
Css::Values* values = decl->mutable_values();
for (Css::Values::iterator value_iter = values->begin();
value_iter != values->end(); ++value_iter) {
Css::Value* value = *value_iter;
if (value->GetLexicalUnitType() == Css::Value::URI) {
std::string rel_url =
UnicodeTextToUTF8(value->GetStringValue());
handler->Message(kInfo, "Found image URL %s", rel_url.c_str());
std::string new_url;
if (RewriteImageUrl(base_url, rel_url, &new_url, handler)) {
// Replace the URL.
*value_iter = new Css::Value(Css::Value::URI,
UTF8ToUnicodeText(new_url));
delete value;
editted = true;
handler->Message(kInfo, "Successfully rewrote %s to %s",
rel_url.c_str(), new_url.c_str());
} else {
if (no_rewrite_ != NULL) {
no_rewrite_->Add(1);
}
handler->Message(kInfo, "Could not rewrite %s "
"(Perhaps it is being fetched).",
rel_url.c_str());
}
}
}
break;
}
default:
break;
}
}
}
return editted;
}
} // namespace net_instaweb
<commit_msg>Fix bad pointer (morlovich)<commit_after>/*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Author: sligocki@google.com (Shawn Ligocki)
#include "net/instaweb/rewriter/public/css_image_rewriter.h"
#include "base/scoped_ptr.h"
#include "net/instaweb/rewriter/public/cache_extender.h"
#include "net/instaweb/rewriter/public/img_rewrite_filter.h"
#include "net/instaweb/rewriter/public/output_resource.h"
#include "net/instaweb/rewriter/public/resource_manager.h"
#include "net/instaweb/rewriter/public/rewrite_driver.h"
#include "net/instaweb/util/public/google_url.h"
#include "net/instaweb/util/public/message_handler.h"
#include "net/instaweb/util/public/statistics.h"
#include <string>
#include "net/instaweb/util/public/string_util.h"
#include "webutil/css/parser.h"
namespace net_instaweb {
// Statistics names.
const char CssImageRewriter::kImageRewrites[] = "css_image_rewrites";
const char CssImageRewriter::kCacheExtends[] = "css_image_cache_extends";
const char CssImageRewriter::kNoRewrite[] = "css_image_no_rewrite";
CssImageRewriter::CssImageRewriter(RewriteDriver* driver,
CacheExtender* cache_extender,
ImgRewriteFilter* image_rewriter)
: driver_(driver),
cache_extender_(cache_extender),
image_rewriter_(image_rewriter),
image_rewrites_(NULL),
cache_extends_(NULL),
no_rewrite_(NULL) {
Statistics* stats = driver_->resource_manager()->statistics();
if (stats != NULL) {
image_rewrites_ = stats->GetVariable(kImageRewrites);
// TODO(sligocki): Should this be shared with CacheExtender or kept
// separately? I think it's useful to know how many images were optimized
// from CSS files, but people probably also want to know how many total
// images were cache-extended.
cache_extends_ = stats->GetVariable(kCacheExtends);
no_rewrite_ = stats->GetVariable(kNoRewrite);
}
}
CssImageRewriter::~CssImageRewriter() {}
void CssImageRewriter::Initialize(Statistics* statistics) {
statistics->AddVariable(kImageRewrites);
statistics->AddVariable(kCacheExtends);
statistics->AddVariable(kNoRewrite);
}
bool CssImageRewriter::RewriteImageUrl(const GURL& base_url,
const StringPiece& old_rel_url,
std::string* new_url,
MessageHandler* handler) {
bool ret = false;
scoped_ptr<Resource> input_resource(
driver_->resource_manager()->CreateInputResource(
base_url, old_rel_url, driver_->options(), handler));
if (input_resource.get() != NULL) {
scoped_ptr<OutputResource::CachedResult> rewrite_info;
// TODO(sligocki): Try image rewriting.
//handler->Message(kInfo, "Attempting to rewrite image %s",
// old_rel_url_cstr);
//rewrite_info.reset(img_rewriter_->RewriteWithCaching(original_url_string));
//if (rewrite_info.get() != NULL && rewrite_info->optimizable()) {
// if (image_rewrites_ != NULL) {
// image_rewrites_->Add(1);
// }
// *new_url = rewrite_info->url();
// ret = true;
//} else
{
// Try cache extending.
handler->Message(kInfo, "Attempting to cache extend image %s",
old_rel_url.as_string().c_str());
rewrite_info.reset(
cache_extender_->RewriteExternalResource(input_resource.get()));
if (rewrite_info.get() != NULL && rewrite_info->optimizable()) {
if (cache_extends_ != NULL) {
cache_extends_->Add(1);
}
*new_url = rewrite_info->url();
ret = true;
}
}
}
return ret;
}
bool CssImageRewriter::RewriteCssImages(const GURL& base_url,
Css::Stylesheet* stylesheet,
MessageHandler* handler) {
bool editted = false;
handler->Message(kInfo, "Starting to rewrite images in CSS in %s",
base_url.spec().c_str());
Css::Rulesets& rulesets = stylesheet->mutable_rulesets();
for (Css::Rulesets::iterator ruleset_iter = rulesets.begin();
ruleset_iter != rulesets.end(); ++ruleset_iter) {
Css::Ruleset* ruleset = *ruleset_iter;
Css::Declarations& decls = ruleset->mutable_declarations();
for (Css::Declarations::iterator decl_iter = decls.begin();
decl_iter != decls.end(); ++decl_iter) {
Css::Declaration* decl = *decl_iter;
// Only edit image declarations.
switch (decl->prop()) {
case Css::Property::BACKGROUND:
case Css::Property::BACKGROUND_IMAGE:
case Css::Property::LIST_STYLE:
case Css::Property::LIST_STYLE_IMAGE: {
// Rewrite all URLs. Technically, background-image should only
// have a single value which is a URL, but background could have
// more values.
Css::Values* values = decl->mutable_values();
for (Css::Values::iterator value_iter = values->begin();
value_iter != values->end(); ++value_iter) {
Css::Value* value = *value_iter;
if (value->GetLexicalUnitType() == Css::Value::URI) {
std::string rel_url =
UnicodeTextToUTF8(value->GetStringValue());
handler->Message(kInfo, "Found image URL %s", rel_url.c_str());
std::string new_url;
if (RewriteImageUrl(base_url, rel_url, &new_url, handler)) {
// Replace the URL.
*value_iter = new Css::Value(Css::Value::URI,
UTF8ToUnicodeText(new_url));
delete value;
editted = true;
handler->Message(kInfo, "Successfully rewrote %s to %s",
rel_url.c_str(), new_url.c_str());
} else {
if (no_rewrite_ != NULL) {
no_rewrite_->Add(1);
}
handler->Message(kInfo, "Could not rewrite %s "
"(Perhaps it is being fetched).",
rel_url.c_str());
}
}
}
break;
}
default:
break;
}
}
}
return editted;
}
} // namespace net_instaweb
<|endoftext|> |
<commit_before>#define DEBUG 1
/**
* File : C.cpp
* Author : Kazune Takahashi
* Created : 11/9/2019, 9:10:42 PM
* Powered by Visual Studio Code
*/
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <vector>
#include <string>
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <bitset>
#include <functional>
#include <random>
#include <chrono>
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;
template <typename T>
void ch_max(T &left, T right)
{
if (left < right)
{
left = right;
}
}
template <typename T>
void ch_min(T &left, T right)
{
if (left > right)
{
left = right;
}
}
using ll = long long;
constexpr ll MOD{1000000007LL};
constexpr ll MAX_SIZE{3000010LL};
template <ll MOD = MOD>
class Mint
{
public:
ll x;
Mint() : x{0LL} {}
Mint(ll x) : x{x % MOD} {}
Mint operator-() const { return x ? MOD - x : 0; }
Mint &operator+=(const Mint &a)
{
if ((x += a.x) >= MOD)
{
x -= MOD;
}
return *this;
}
Mint &operator-=(const Mint &a) { return *this += -a; }
Mint &operator*=(const Mint &a)
{
(x *= a.x) %= MOD;
return *this;
}
Mint &operator/=(const Mint &a)
{
Mint b{a};
return *this *= b.power(MOD - 2);
}
Mint operator+(const Mint &a) const { return Mint(*this) += a; }
Mint operator-(const Mint &a) const { return Mint(*this) -= a; }
Mint operator*(const Mint &a) const { return Mint(*this) *= a; }
Mint operator/(const Mint &a) const { return Mint(*this) /= a; }
bool operator<(const Mint &a) const { return x < a.x; }
bool operator==(const Mint &a) const { return x == a.x; }
const Mint power(ll N)
{
if (N == 0)
{
return 1;
}
else if (N % 2 == 1)
{
return *this * power(N - 1);
}
else
{
Mint half = power(N / 2);
return half * half;
}
}
};
template <ll MOD>
Mint<MOD> operator+(ll lhs, const Mint<MOD> &rhs)
{
return rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator-(ll lhs, const Mint<MOD> &rhs)
{
return -rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator*(ll lhs, const Mint<MOD> &rhs)
{
return rhs * lhs;
}
template <ll MOD>
Mint<MOD> operator/(ll lhs, const Mint<MOD> &rhs)
{
return Mint<MOD>{lhs} / rhs;
}
template <ll MOD>
istream &operator>>(istream &stream, Mint<MOD> &a)
{
return stream >> a.x;
}
template <ll MOD>
ostream &operator<<(ostream &stream, const Mint<MOD> &a)
{
return stream << a.x;
}
template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE>
class Combination
{
public:
vector<Mint<MOD>> inv, fact, factinv;
Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)
{
inv[1] = 1;
for (auto i = 2LL; i < MAX_SIZE; i++)
{
inv[i] = (-inv[MOD % i]) * (MOD / i);
}
fact[0] = factinv[0] = 1;
for (auto i = 1LL; i < MAX_SIZE; i++)
{
fact[i] = Mint<MOD>(i) * fact[i - 1];
factinv[i] = inv[i] * factinv[i - 1];
}
}
Mint<MOD> operator()(int n, int k)
{
if (n >= 0 && k >= 0 && n - k >= 0)
{
return fact[n] * factinv[k] * factinv[n - k];
}
return 0;
}
Mint<MOD> catalan(int x, int y)
{
return (*this)(x + y, y) - (*this)(x + y, y - 1);
}
};
// for C++14
using mint = Mint<MOD>;
using combination = Combination<MOD, MAX_SIZE>;
ll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; }
// constexpr double epsilon = 1e-10;
// constexpr ll infty = 1000000000000000LL;
// constexpr int dx[4] = {1, 0, -1, 0};
// constexpr int dy[4] = {0, 1, 0, -1};
void Yes()
{
cout << "Yes" << endl;
exit(0);
}
void No()
{
cout << "No" << endl;
exit(0);
}
using Info = tuple<int, int>;
int main()
{
int N;
cin >> N;
vector<int> A(N), B(N);
for (auto i = 0; i < N; i++)
{
cin >> A[i];
}
for (auto i = 0; i < N; i++)
{
cin >> B[i];
}
vector<Info> V(N);
for (auto i = 0; i < N; i++)
{
V[i] = Info(B[i], A[i]);
}
sort(A.begin(), A.end());
sort(B.begin(), B.end());
for (auto i = 0; i < N; i++)
{
if (A[i] > B[i])
{
No();
}
}
vector<bool> C(N, true);
for (auto i = 1; i < N; i++)
{
C[i] = (A[i] <= B[i - 1]);
}
vector<int> sum(N, 0);
for (auto i = 1; i < N; i++)
{
int t{C[i] ? 0 : 1};
sum[i] = sum[i - 1] + t;
}
for (auto k = 0; k < N; k++)
{
int x{get<1>(V[k])};
int y{get<0>(V[k])};
if (x > y)
{
continue;
}
auto it_a{upper_bound(A.begin(), A.end(), x)};
--it_a;
assert(*it_a == x);
auto it_b{lower_bound(B.begin(), B.end(), y)};
assert(*it_b == y);
int num_a(it_a - A.begin());
int num_b(it_b - B.begin());
if (num_b <= num_a)
{
Yes();
}
else
{
bool ok{true};
for (auto i = num_a + 1; i <= num_b; i++)
{
if (!C[i])
{
ok = false;
break;
}
}
if (ok)
{
Yes();
}
}
}
No();
}<commit_msg>submit C.cpp to 'C - Swaps' (nikkei2019-2-qual) [C++14 (GCC 5.4.1)]<commit_after>#define DEBUG 1
/**
* File : C.cpp
* Author : Kazune Takahashi
* Created : 11/9/2019, 9:10:42 PM
* Powered by Visual Studio Code
*/
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <vector>
#include <string>
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <bitset>
#include <functional>
#include <random>
#include <chrono>
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;
template <typename T>
void ch_max(T &left, T right)
{
if (left < right)
{
left = right;
}
}
template <typename T>
void ch_min(T &left, T right)
{
if (left > right)
{
left = right;
}
}
using ll = long long;
constexpr ll MOD{1000000007LL};
constexpr ll MAX_SIZE{3000010LL};
template <ll MOD = MOD>
class Mint
{
public:
ll x;
Mint() : x{0LL} {}
Mint(ll x) : x{x % MOD} {}
Mint operator-() const { return x ? MOD - x : 0; }
Mint &operator+=(const Mint &a)
{
if ((x += a.x) >= MOD)
{
x -= MOD;
}
return *this;
}
Mint &operator-=(const Mint &a) { return *this += -a; }
Mint &operator*=(const Mint &a)
{
(x *= a.x) %= MOD;
return *this;
}
Mint &operator/=(const Mint &a)
{
Mint b{a};
return *this *= b.power(MOD - 2);
}
Mint operator+(const Mint &a) const { return Mint(*this) += a; }
Mint operator-(const Mint &a) const { return Mint(*this) -= a; }
Mint operator*(const Mint &a) const { return Mint(*this) *= a; }
Mint operator/(const Mint &a) const { return Mint(*this) /= a; }
bool operator<(const Mint &a) const { return x < a.x; }
bool operator==(const Mint &a) const { return x == a.x; }
const Mint power(ll N)
{
if (N == 0)
{
return 1;
}
else if (N % 2 == 1)
{
return *this * power(N - 1);
}
else
{
Mint half = power(N / 2);
return half * half;
}
}
};
template <ll MOD>
Mint<MOD> operator+(ll lhs, const Mint<MOD> &rhs)
{
return rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator-(ll lhs, const Mint<MOD> &rhs)
{
return -rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator*(ll lhs, const Mint<MOD> &rhs)
{
return rhs * lhs;
}
template <ll MOD>
Mint<MOD> operator/(ll lhs, const Mint<MOD> &rhs)
{
return Mint<MOD>{lhs} / rhs;
}
template <ll MOD>
istream &operator>>(istream &stream, Mint<MOD> &a)
{
return stream >> a.x;
}
template <ll MOD>
ostream &operator<<(ostream &stream, const Mint<MOD> &a)
{
return stream << a.x;
}
template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE>
class Combination
{
public:
vector<Mint<MOD>> inv, fact, factinv;
Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)
{
inv[1] = 1;
for (auto i = 2LL; i < MAX_SIZE; i++)
{
inv[i] = (-inv[MOD % i]) * (MOD / i);
}
fact[0] = factinv[0] = 1;
for (auto i = 1LL; i < MAX_SIZE; i++)
{
fact[i] = Mint<MOD>(i) * fact[i - 1];
factinv[i] = inv[i] * factinv[i - 1];
}
}
Mint<MOD> operator()(int n, int k)
{
if (n >= 0 && k >= 0 && n - k >= 0)
{
return fact[n] * factinv[k] * factinv[n - k];
}
return 0;
}
Mint<MOD> catalan(int x, int y)
{
return (*this)(x + y, y) - (*this)(x + y, y - 1);
}
};
// for C++14
using mint = Mint<MOD>;
using combination = Combination<MOD, MAX_SIZE>;
ll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; }
// constexpr double epsilon = 1e-10;
// constexpr ll infty = 1000000000000000LL;
// constexpr int dx[4] = {1, 0, -1, 0};
// constexpr int dy[4] = {0, 1, 0, -1};
void Yes()
{
cout << "Yes" << endl;
exit(0);
}
void No()
{
cout << "No" << endl;
exit(0);
}
using Info = tuple<int, int>;
int main()
{
int N;
cin >> N;
vector<int> A(N), B(N);
for (auto i = 0; i < N; i++)
{
cin >> A[i];
}
for (auto i = 0; i < N; i++)
{
cin >> B[i];
}
vector<Info> V(N);
for (auto i = 0; i < N; i++)
{
V[i] = Info(B[i], A[i]);
}
sort(A.begin(), A.end());
sort(B.begin(), B.end());
for (auto i = 0; i < N; i++)
{
if (A[i] > B[i])
{
No();
}
}
assert(false);
vector<bool> C(N, true);
for (auto i = 1; i < N; i++)
{
C[i] = (A[i] <= B[i - 1]);
}
vector<int> sum(N, 0);
for (auto i = 1; i < N; i++)
{
int t{C[i] ? 0 : 1};
sum[i] = sum[i - 1] + t;
}
for (auto k = 0; k < N; k++)
{
int x{get<1>(V[k])};
int y{get<0>(V[k])};
if (x > y)
{
continue;
}
auto it_a{upper_bound(A.begin(), A.end(), x)};
--it_a;
assert(*it_a == x);
auto it_b{lower_bound(B.begin(), B.end(), y)};
assert(*it_b == y);
int num_a(it_a - A.begin());
int num_b(it_b - B.begin());
if (num_b <= num_a)
{
Yes();
}
else
{
bool ok{true};
for (auto i = num_a + 1; i <= num_b; i++)
{
if (!C[i])
{
ok = false;
break;
}
}
if (ok)
{
Yes();
}
}
}
No();
}<|endoftext|> |
<commit_before>#define DEBUG 1
/**
* File : C.cpp
* Author : Kazune Takahashi
* Created : 11/9/2019, 9:10:42 PM
* Powered by Visual Studio Code
*/
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <vector>
#include <string>
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <bitset>
#include <functional>
#include <random>
#include <chrono>
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;
template <typename T>
void ch_max(T &left, T right)
{
if (left < right)
{
left = right;
}
}
template <typename T>
void ch_min(T &left, T right)
{
if (left > right)
{
left = right;
}
}
using ll = long long;
constexpr ll MOD{1000000007LL};
constexpr ll MAX_SIZE{3000010LL};
template <ll MOD = MOD>
class Mint
{
public:
ll x;
Mint() : x{0LL} {}
Mint(ll x) : x{x % MOD} {}
Mint operator-() const { return x ? MOD - x : 0; }
Mint &operator+=(const Mint &a)
{
if ((x += a.x) >= MOD)
{
x -= MOD;
}
return *this;
}
Mint &operator-=(const Mint &a) { return *this += -a; }
Mint &operator*=(const Mint &a)
{
(x *= a.x) %= MOD;
return *this;
}
Mint &operator/=(const Mint &a)
{
Mint b{a};
return *this *= b.power(MOD - 2);
}
Mint operator+(const Mint &a) const { return Mint(*this) += a; }
Mint operator-(const Mint &a) const { return Mint(*this) -= a; }
Mint operator*(const Mint &a) const { return Mint(*this) *= a; }
Mint operator/(const Mint &a) const { return Mint(*this) /= a; }
bool operator<(const Mint &a) const { return x < a.x; }
bool operator==(const Mint &a) const { return x == a.x; }
const Mint power(ll N)
{
if (N == 0)
{
return 1;
}
else if (N % 2 == 1)
{
return *this * power(N - 1);
}
else
{
Mint half = power(N / 2);
return half * half;
}
}
};
template <ll MOD>
Mint<MOD> operator+(ll lhs, const Mint<MOD> &rhs)
{
return rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator-(ll lhs, const Mint<MOD> &rhs)
{
return -rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator*(ll lhs, const Mint<MOD> &rhs)
{
return rhs * lhs;
}
template <ll MOD>
Mint<MOD> operator/(ll lhs, const Mint<MOD> &rhs)
{
return Mint<MOD>{lhs} / rhs;
}
template <ll MOD>
istream &operator>>(istream &stream, Mint<MOD> &a)
{
return stream >> a.x;
}
template <ll MOD>
ostream &operator<<(ostream &stream, const Mint<MOD> &a)
{
return stream << a.x;
}
template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE>
class Combination
{
public:
vector<Mint<MOD>> inv, fact, factinv;
Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)
{
inv[1] = 1;
for (auto i = 2LL; i < MAX_SIZE; i++)
{
inv[i] = (-inv[MOD % i]) * (MOD / i);
}
fact[0] = factinv[0] = 1;
for (auto i = 1LL; i < MAX_SIZE; i++)
{
fact[i] = Mint<MOD>(i) * fact[i - 1];
factinv[i] = inv[i] * factinv[i - 1];
}
}
Mint<MOD> operator()(int n, int k)
{
if (n >= 0 && k >= 0 && n - k >= 0)
{
return fact[n] * factinv[k] * factinv[n - k];
}
return 0;
}
Mint<MOD> catalan(int x, int y)
{
return (*this)(x + y, y) - (*this)(x + y, y - 1);
}
};
// for C++14
using mint = Mint<MOD>;
using combination = Combination<MOD, MAX_SIZE>;
ll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; }
// constexpr double epsilon = 1e-10;
// constexpr ll infty = 1000000000000000LL;
// constexpr int dx[4] = {1, 0, -1, 0};
// constexpr int dy[4] = {0, 1, 0, -1};
void Yes()
{
cout << "Yes" << endl;
exit(0);
}
void No()
{
cout << "No" << endl;
exit(0);
}
using Info = tuple<int, int>;
int main()
{
int N;
cin >> N;
vector<int> A(N), B(N);
for (auto i = 0; i < N; i++)
{
cin >> A[i];
}
for (auto i = 0; i < N; i++)
{
cin >> B[i];
}
vector<Info> I(N);
for (auto i = 0; i < N; i++)
{
I[i] = Info(B[i], A[i]);
}
sort(I.begin(), I.end());
for (auto i = 0; i < N; i++)
{
A[i] = get<1>(I[i]);
}
vector<int> old_A{A}, old_B{B};
sort(A.begin(), A.end());
sort(B.begin(), B.end());
for (auto i = 0; i < N; i++)
{
if (A[i] > B[i])
{
No();
}
}
for (auto i = 0; i < N; i++)
{
if (old_A[i] == A[i])
{
Yes();
}
}
assert(false);
vector<bool> C(N, true);
for (auto i = 1; i < N; i++)
{
C[i] = (A[i] <= B[i - 1]);
}
for (auto k = 0; k < N; k++)
{
int x{old_A[k]};
int y{old_B[k]};
if (x > y)
{
continue;
}
auto it_a{upper_bound(A.begin(), A.end(), x)};
--it_a;
assert(*it_a == x);
auto it_b{lower_bound(B.begin(), B.end(), y)};
assert(*it_b == y);
int num_a(it_a - A.begin());
int num_b(it_b - B.begin());
if (num_b <= num_a)
{
Yes();
}
else
{
bool ok{true};
for (auto i = num_a + 1; i <= num_b; i++)
{
if (!C[i])
{
ok = false;
break;
}
}
if (ok)
{
Yes();
}
}
}
for (auto i = 0; i < N; i++)
{
if (old_A[i] == A[i])
{
Yes();
}
}
assert(false);
vector<int> V(N, -1);
for (auto i = 0; i < N; i++)
{
auto it{lower_bound(A.begin(), A.end(), old_A[i])};
int num(it - A.begin());
V[num] = i;
}
for (auto i = 0; i < N; i++)
{
if (V[i] == -1)
{
Yes();
}
}
vector<bool> used(N, false);
int now{0};
int cnt{0};
while (cnt < N)
{
if (used[now])
{
Yes();
}
used[now] = true;
cnt++;
now = V[now];
}
No();
}<commit_msg>submit C.cpp to 'C - Swaps' (nikkei2019-2-qual) [C++14 (GCC 5.4.1)]<commit_after>#define DEBUG 1
/**
* File : C.cpp
* Author : Kazune Takahashi
* Created : 11/9/2019, 9:10:42 PM
* Powered by Visual Studio Code
*/
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <vector>
#include <string>
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <bitset>
#include <functional>
#include <random>
#include <chrono>
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;
template <typename T>
void ch_max(T &left, T right)
{
if (left < right)
{
left = right;
}
}
template <typename T>
void ch_min(T &left, T right)
{
if (left > right)
{
left = right;
}
}
using ll = long long;
constexpr ll MOD{1000000007LL};
constexpr ll MAX_SIZE{3000010LL};
template <ll MOD = MOD>
class Mint
{
public:
ll x;
Mint() : x{0LL} {}
Mint(ll x) : x{x % MOD} {}
Mint operator-() const { return x ? MOD - x : 0; }
Mint &operator+=(const Mint &a)
{
if ((x += a.x) >= MOD)
{
x -= MOD;
}
return *this;
}
Mint &operator-=(const Mint &a) { return *this += -a; }
Mint &operator*=(const Mint &a)
{
(x *= a.x) %= MOD;
return *this;
}
Mint &operator/=(const Mint &a)
{
Mint b{a};
return *this *= b.power(MOD - 2);
}
Mint operator+(const Mint &a) const { return Mint(*this) += a; }
Mint operator-(const Mint &a) const { return Mint(*this) -= a; }
Mint operator*(const Mint &a) const { return Mint(*this) *= a; }
Mint operator/(const Mint &a) const { return Mint(*this) /= a; }
bool operator<(const Mint &a) const { return x < a.x; }
bool operator==(const Mint &a) const { return x == a.x; }
const Mint power(ll N)
{
if (N == 0)
{
return 1;
}
else if (N % 2 == 1)
{
return *this * power(N - 1);
}
else
{
Mint half = power(N / 2);
return half * half;
}
}
};
template <ll MOD>
Mint<MOD> operator+(ll lhs, const Mint<MOD> &rhs)
{
return rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator-(ll lhs, const Mint<MOD> &rhs)
{
return -rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator*(ll lhs, const Mint<MOD> &rhs)
{
return rhs * lhs;
}
template <ll MOD>
Mint<MOD> operator/(ll lhs, const Mint<MOD> &rhs)
{
return Mint<MOD>{lhs} / rhs;
}
template <ll MOD>
istream &operator>>(istream &stream, Mint<MOD> &a)
{
return stream >> a.x;
}
template <ll MOD>
ostream &operator<<(ostream &stream, const Mint<MOD> &a)
{
return stream << a.x;
}
template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE>
class Combination
{
public:
vector<Mint<MOD>> inv, fact, factinv;
Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)
{
inv[1] = 1;
for (auto i = 2LL; i < MAX_SIZE; i++)
{
inv[i] = (-inv[MOD % i]) * (MOD / i);
}
fact[0] = factinv[0] = 1;
for (auto i = 1LL; i < MAX_SIZE; i++)
{
fact[i] = Mint<MOD>(i) * fact[i - 1];
factinv[i] = inv[i] * factinv[i - 1];
}
}
Mint<MOD> operator()(int n, int k)
{
if (n >= 0 && k >= 0 && n - k >= 0)
{
return fact[n] * factinv[k] * factinv[n - k];
}
return 0;
}
Mint<MOD> catalan(int x, int y)
{
return (*this)(x + y, y) - (*this)(x + y, y - 1);
}
};
// for C++14
using mint = Mint<MOD>;
using combination = Combination<MOD, MAX_SIZE>;
ll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; }
// constexpr double epsilon = 1e-10;
// constexpr ll infty = 1000000000000000LL;
// constexpr int dx[4] = {1, 0, -1, 0};
// constexpr int dy[4] = {0, 1, 0, -1};
void Yes()
{
cout << "Yes" << endl;
exit(0);
}
void No()
{
cout << "No" << endl;
exit(0);
}
using Info = tuple<int, int>;
int main()
{
int N;
cin >> N;
vector<int> A(N), B(N);
for (auto i = 0; i < N; i++)
{
cin >> A[i];
}
for (auto i = 0; i < N; i++)
{
cin >> B[i];
}
vector<Info> I(N);
for (auto i = 0; i < N; i++)
{
I[i] = Info(B[i], A[i]);
}
sort(I.begin(), I.end());
for (auto i = 0; i < N; i++)
{
A[i] = get<1>(I[i]);
}
vector<int> old_A{A}, old_B{B};
sort(A.begin(), A.end());
sort(B.begin(), B.end());
for (auto i = 0; i < N; i++)
{
if (A[i] > B[i])
{
No();
}
}
for (auto i = 0; i < N; i++)
{
if (old_A[i] == A[i])
{
Yes();
}
}
vector<int> V(N, -1);
for (auto i = 0; i < N; i++)
{
auto it{lower_bound(A.begin(), A.end(), old_A[i])};
int num(it - A.begin());
V[num] = i;
}
for (auto i = 0; i < N; i++)
{
if (V[i] == -1)
{
Yes();
}
}
vector<bool> used(N, false);
int now{0};
int cnt{0};
while (cnt < N)
{
if (used[now])
{
Yes();
}
used[now] = true;
cnt++;
now = V[now];
}
No();
}<|endoftext|> |
<commit_before>/*--------------------------------------------------------------------------
File : timer_hf_nrf5x.cpp
Author : Hoang Nguyen Hoan Sep. 7, 2017
Desc : timer class implementation on Nordic nRF5x series
using high frequency timer (TIMERx)
Copyright (c) 2017, I-SYST inc., all rights reserved
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, and none of the
names : I-SYST or its contributors may be used to endorse or
promote products derived from this software without specific prior written
permission.
For info or contributing contact : hnhoan at i-syst dot com
THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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.
----------------------------------------------------------------------------
Modified by Date Description
----------------------------------------------------------------------------*/
#include "nrf.h"
#include "timer_nrf5x.h"
static TimerHFnRF5x *s_pDevObj[TIMER_NRF5X_HF_MAX] = {
NULL,
};
void TimerHFnRF5x::IRQHandler()
{
uint32_t evt = 0;
uint32_t count;
vpReg->TASKS_CAPTURE[0] = 1;
count = vpReg->CC[0];
for (int i = 0; i < vMaxNbTrigEvt; i++)
{
if (vpReg->EVENTS_COMPARE[i])
{
evt |= 1 << (i + 2);
vpReg->EVENTS_COMPARE[i] = 0;
if (vTrigType[i] == TIMER_TRIG_TYPE_CONTINUOUS)
{
vpReg->CC[i] = count + vCC[i];
}
}
}
if (count < vLastCount)
{
// Counter wrap arround
evt |= TIMER_EVT_COUNTER_OVR;
vRollover += vFreq;
}
vLastCount = count;
if (vEvtHandler)
{
vEvtHandler(this, evt);
}
}
extern "C" {
void TIMER0_IRQHandler()
{
if (s_pDevObj[0])
s_pDevObj[0]->IRQHandler();
}
void TIMER1_IRQHandler()
{
if (s_pDevObj[1])
s_pDevObj[1]->IRQHandler();
}
void TIMER2_IRQHandler()
{
if (s_pDevObj[2])
s_pDevObj[2]->IRQHandler();
}
void TIMER3_IRQHandler()
{
if (s_pDevObj[3])
s_pDevObj[3]->IRQHandler();
}
void TIMER4_IRQHandler()
{
if (s_pDevObj[4])
s_pDevObj[4]->IRQHandler();
}
} // extern "C"
TimerHFnRF5x::TimerHFnRF5x()
{
}
TimerHFnRF5x::~TimerHFnRF5x()
{
}
bool TimerHFnRF5x::Init(const TIMER_CFG &Cfg)
{
if (Cfg.DevNo < 0 || Cfg.DevNo >= TIMER_NRF5X_HF_MAX)
return false;
vMaxNbTrigEvt = TIMER_NRF5X_HF_MAX_TRIGGER_EVT - 2;
switch (Cfg.DevNo)
{
case 0:
s_pDevObj[0] = this;
vpReg = NRF_TIMER0;
break;
case 1:
s_pDevObj[1] = this;
vpReg = NRF_TIMER1;
break;
case 2:
s_pDevObj[2] = this;
vpReg = NRF_TIMER2;
break;
case 3:
s_pDevObj[3] = this;
vpReg = NRF_TIMER3;
vMaxNbTrigEvt = TIMER_NRF5X_HF_MAX_TRIGGER_EVT;
break;
case 4:
s_pDevObj[4] = this;
vpReg = NRF_TIMER4;
vMaxNbTrigEvt = TIMER_NRF5X_HF_MAX_TRIGGER_EVT;
break;
}
vpReg->TASKS_STOP = 1;
vpReg->TASKS_CLEAR = 1;
NRF_CLOCK->TASKS_HFCLKSTOP = 1;
vEvtHandler = Cfg.EvtHandler;
vDevNo = Cfg.DevNo;
// Only support timer mode, 32bits counter
vpReg->MODE = TIMER_MODE_MODE_Timer;
vpReg->BITMODE = TIMER_BITMODE_BITMODE_32Bit;
uint32_t prescaler = 0;
if (Cfg.Freq > 0)
{
uint32_t divisor = 16000000 / Cfg.Freq;
prescaler = 31 - __builtin_clzl(divisor);
if (prescaler > 9)
{
prescaler = 9;
}
}
vpReg->PRESCALER = prescaler;
vFreq = 16000000 / (1 << prescaler);
// Pre-calculate periods for faster timer counter to time conversion use later
vnsPeriod = 1000000000 / vFreq; // Period in nsec
if (Cfg.EvtHandler)
{
switch (Cfg.DevNo)
{
case 0:
NVIC_ClearPendingIRQ(TIMER0_IRQn);
NVIC_SetPriority(TIMER0_IRQn, Cfg.IntPrio);
NVIC_EnableIRQ(TIMER0_IRQn);
break;
case 1:
NVIC_ClearPendingIRQ(TIMER1_IRQn);
NVIC_SetPriority(TIMER1_IRQn, Cfg.IntPrio);
NVIC_EnableIRQ(TIMER1_IRQn);
break;
case 2:
NVIC_ClearPendingIRQ(TIMER2_IRQn);
NVIC_SetPriority(TIMER2_IRQn, Cfg.IntPrio);
NVIC_EnableIRQ(TIMER2_IRQn);
break;
case 3:
NVIC_ClearPendingIRQ(TIMER3_IRQn);
NVIC_SetPriority(TIMER3_IRQn, Cfg.IntPrio);
NVIC_EnableIRQ(TIMER3_IRQn);
break;
case 4:
NVIC_ClearPendingIRQ(TIMER4_IRQn);
NVIC_SetPriority(TIMER4_IRQn, Cfg.IntPrio);
NVIC_EnableIRQ(TIMER4_IRQn);
break;
}
}
// Clock source not available. Only 64MHz XTAL
NRF_CLOCK->TASKS_HFCLKSTART = 1;
int timout = 1000000;
do
{
if ((NRF_CLOCK->HFCLKSTAT & CLOCK_HFCLKSTAT_STATE_Msk) || NRF_CLOCK->EVENTS_HFCLKSTARTED)
break;
} while (timout-- > 0);
if (timout <= 0)
return false;
NRF_CLOCK->EVENTS_HFCLKSTARTED = 0;
vpReg->TASKS_START = 1;
return true;
}
bool TimerHFnRF5x::Enable()
{
return true;
}
void TimerHFnRF5x::Disable()
{
}
void TimerHFnRF5x::Reset()
{
vpReg->TASKS_CLEAR = 1;
}
uint32_t TimerHFnRF5x::Frequency(uint32_t Freq)
{
}
uint64_t TimerHFnRF5x::TickCount()
{
if (vpReg->INTENSET == 0)
{
vpReg->TASKS_CAPTURE[vDevNo] = 1;
uint32_t count = vpReg->CC[vDevNo];
if (count < vLastCount)
{
// Counter wrap arround
vRollover += vFreq;
}
vLastCount = count;
}
return vLastCount + vRollover;
}
uint32_t TimerHFnRF5x::EnableTimerTrigger(int TrigNo, uint32_t nsPeriod, TIMER_TRIG_TYPE Type)
{
if (TrigNo < 0 || TrigNo >= vMaxNbTrigEvt)
return 0;
uint32_t cc = nsPeriod / vnsPeriod;
if (cc <= 0)
{
return 0;
}
vTrigType[TrigNo] = Type;
vCC[TrigNo] = cc;
if (vEvtHandler)
{
vpReg->INTENSET = 1 << (TrigNo + TIMER_INTENSET_COMPARE0_Pos);
}
vpReg->TASKS_CAPTURE[TrigNo] = 1;
uint32_t count = vpReg->CC[TrigNo];
vpReg->CC[TrigNo] += cc;
if (count < vLastCount)
{
// Counter wrap arround
vRollover += vFreq;
}
vLastCount = count;
return vnsPeriod * cc; // Return real period in nsec
}
void TimerHFnRF5x::DisableTimerTrigger(int TrigNo)
{
if (TrigNo < 0 || TrigNo >= vMaxNbTrigEvt)
return;
vTrigType[TrigNo] = TIMER_TRIG_TYPE_SINGLE;
vCC[TrigNo] = 0;
vpReg->CC[TrigNo] = 0;
vpReg->INTENCLR = 1 << (TrigNo + TIMER_INTENSET_COMPARE0_Pos);
}
<commit_msg>More precision adjustment<commit_after>/*--------------------------------------------------------------------------
File : timer_hf_nrf5x.cpp
Author : Hoang Nguyen Hoan Sep. 7, 2017
Desc : timer class implementation on Nordic nRF5x series
using high frequency timer (TIMERx)
Copyright (c) 2017, I-SYST inc., all rights reserved
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, and none of the
names : I-SYST or its contributors may be used to endorse or
promote products derived from this software without specific prior written
permission.
For info or contributing contact : hnhoan at i-syst dot com
THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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.
----------------------------------------------------------------------------
Modified by Date Description
----------------------------------------------------------------------------*/
#include "nrf.h"
#include "timer_nrf5x.h"
#include "iopinctrl.h"
#define INTERRUPT_LATENCY 11
static TimerHFnRF5x *s_pDevObj[TIMER_NRF5X_HF_MAX] = {
NULL,
};
void TimerHFnRF5x::IRQHandler()
{
uint32_t evt = 0;
uint32_t count;
vpReg->TASKS_CAPTURE[0] = 1;
count = vpReg->CC[0];
for (int i = 0; i < vMaxNbTrigEvt; i++)
{
if (vpReg->EVENTS_COMPARE[i])
{
evt |= 1 << (i + 2);
vpReg->EVENTS_COMPARE[i] = 0;
if (vTrigType[i] == TIMER_TRIG_TYPE_CONTINUOUS)
{
vpReg->CC[i] = count + vCC[i] - INTERRUPT_LATENCY;
}
}
}
if (count < vLastCount)
{
// Counter wrap arround
evt |= TIMER_EVT_COUNTER_OVR;
vRollover += vFreq;
}
vLastCount = count;
IOPinToggle(0, 22);
if (vEvtHandler)
{
vEvtHandler(this, evt);
}
}
extern "C" {
void TIMER0_IRQHandler()
{
if (s_pDevObj[0])
s_pDevObj[0]->IRQHandler();
}
void TIMER1_IRQHandler()
{
if (s_pDevObj[1])
s_pDevObj[1]->IRQHandler();
}
void TIMER2_IRQHandler()
{
if (s_pDevObj[2])
s_pDevObj[2]->IRQHandler();
}
void TIMER3_IRQHandler()
{
if (s_pDevObj[3])
s_pDevObj[3]->IRQHandler();
}
void TIMER4_IRQHandler()
{
if (s_pDevObj[4])
s_pDevObj[4]->IRQHandler();
}
} // extern "C"
TimerHFnRF5x::TimerHFnRF5x()
{
}
TimerHFnRF5x::~TimerHFnRF5x()
{
}
bool TimerHFnRF5x::Init(const TIMER_CFG &Cfg)
{
if (Cfg.DevNo < 0 || Cfg.DevNo >= TIMER_NRF5X_HF_MAX)
return false;
vMaxNbTrigEvt = TIMER_NRF5X_HF_MAX_TRIGGER_EVT - 2;
switch (Cfg.DevNo)
{
case 0:
s_pDevObj[0] = this;
vpReg = NRF_TIMER0;
break;
case 1:
s_pDevObj[1] = this;
vpReg = NRF_TIMER1;
break;
case 2:
s_pDevObj[2] = this;
vpReg = NRF_TIMER2;
break;
case 3:
s_pDevObj[3] = this;
vpReg = NRF_TIMER3;
vMaxNbTrigEvt = TIMER_NRF5X_HF_MAX_TRIGGER_EVT;
break;
case 4:
s_pDevObj[4] = this;
vpReg = NRF_TIMER4;
vMaxNbTrigEvt = TIMER_NRF5X_HF_MAX_TRIGGER_EVT;
break;
}
vpReg->TASKS_STOP = 1;
vpReg->TASKS_CLEAR = 1;
NRF_CLOCK->TASKS_HFCLKSTOP = 1;
vEvtHandler = Cfg.EvtHandler;
vDevNo = Cfg.DevNo;
// Only support timer mode, 32bits counter
vpReg->MODE = TIMER_MODE_MODE_Timer;
vpReg->BITMODE = TIMER_BITMODE_BITMODE_32Bit;
uint32_t prescaler = 0;
if (Cfg.Freq > 0)
{
uint32_t divisor = 16000000 / Cfg.Freq;
prescaler = 31 - __builtin_clzl(divisor);
if (prescaler > 9)
{
prescaler = 9;
}
}
vpReg->PRESCALER = prescaler;
vFreq = 16000000 / (1 << prescaler);
// Pre-calculate periods for faster timer counter to time conversion use later
vnsPeriod = 10000000000ULL / vFreq; // Period in nsec
if (Cfg.EvtHandler)
{
switch (Cfg.DevNo)
{
case 0:
NVIC_ClearPendingIRQ(TIMER0_IRQn);
NVIC_SetPriority(TIMER0_IRQn, Cfg.IntPrio);
NVIC_EnableIRQ(TIMER0_IRQn);
break;
case 1:
NVIC_ClearPendingIRQ(TIMER1_IRQn);
NVIC_SetPriority(TIMER1_IRQn, Cfg.IntPrio);
NVIC_EnableIRQ(TIMER1_IRQn);
break;
case 2:
NVIC_ClearPendingIRQ(TIMER2_IRQn);
NVIC_SetPriority(TIMER2_IRQn, Cfg.IntPrio);
NVIC_EnableIRQ(TIMER2_IRQn);
break;
case 3:
NVIC_ClearPendingIRQ(TIMER3_IRQn);
NVIC_SetPriority(TIMER3_IRQn, Cfg.IntPrio);
NVIC_EnableIRQ(TIMER3_IRQn);
break;
case 4:
NVIC_ClearPendingIRQ(TIMER4_IRQn);
NVIC_SetPriority(TIMER4_IRQn, Cfg.IntPrio);
NVIC_EnableIRQ(TIMER4_IRQn);
break;
}
}
// Clock source not available. Only 64MHz XTAL
NRF_CLOCK->TASKS_HFCLKSTART = 1;
int timout = 1000000;
do
{
if ((NRF_CLOCK->HFCLKSTAT & CLOCK_HFCLKSTAT_STATE_Msk) || NRF_CLOCK->EVENTS_HFCLKSTARTED)
break;
} while (timout-- > 0);
if (timout <= 0)
return false;
NRF_CLOCK->EVENTS_HFCLKSTARTED = 0;
vpReg->TASKS_START = 1;
return true;
}
bool TimerHFnRF5x::Enable()
{
return true;
}
void TimerHFnRF5x::Disable()
{
}
void TimerHFnRF5x::Reset()
{
vpReg->TASKS_CLEAR = 1;
}
uint32_t TimerHFnRF5x::Frequency(uint32_t Freq)
{
}
uint64_t TimerHFnRF5x::TickCount()
{
if (vpReg->INTENSET == 0)
{
vpReg->TASKS_CAPTURE[vDevNo] = 1;
uint32_t count = vpReg->CC[vDevNo];
if (count < vLastCount)
{
// Counter wrap arround
vRollover += vFreq;
}
vLastCount = count;
}
return vLastCount + vRollover;
}
uint64_t TimerHFnRF5x::EnableTimerTrigger(int TrigNo, uint64_t nsPeriod, TIMER_TRIG_TYPE Type)
{
if (TrigNo < 0 || TrigNo >= vMaxNbTrigEvt)
return 0;
uint32_t cc = (nsPeriod * 10ULL + (vnsPeriod >> 1)) / vnsPeriod;
if (cc <= 0)
{
return 0;
}
vTrigType[TrigNo] = Type;
vCC[TrigNo] = cc;
vpReg->TASKS_CAPTURE[TrigNo] = 1;
uint32_t count = vpReg->CC[TrigNo];
vpReg->SHORTS |= TIMER_SHORTS_COMPARE0_CLEAR_Msk << TrigNo;
if (vEvtHandler)
{
vpReg->INTENSET = 1 << (TrigNo + TIMER_INTENSET_COMPARE0_Pos);
}
vpReg->CC[TrigNo] = count + cc - INTERRUPT_LATENCY;
if (count < vLastCount)
{
// Counter wrap arround
vRollover += vFreq;
}
vLastCount = count;
return vnsPeriod * (uint64_t)cc / 10ULL; // Return real period in nsec
}
void TimerHFnRF5x::DisableTimerTrigger(int TrigNo)
{
if (TrigNo < 0 || TrigNo >= vMaxNbTrigEvt)
return;
vTrigType[TrigNo] = TIMER_TRIG_TYPE_SINGLE;
vCC[TrigNo] = 0;
vpReg->CC[TrigNo] = 0;
vpReg->INTENCLR = 1 << (TrigNo + TIMER_INTENSET_COMPARE0_Pos);
}
<|endoftext|> |
<commit_before>// mat.hxx -- a material in the scene graph.
// TODO: this class needs to be renamed.
//
// Written by Curtis Olson, started May 1998.
// Overhauled by David Megginson, December 2001
//
// Copyright (C) 1998 - 2000 Curtis L. Olson - curt@flightgear.org
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation; either version 2 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
//
// $Id$
#ifndef _SG_MAT_HXX
#define _SG_MAT_HXX
#ifndef __cplusplus
# error This library requires C++
#endif
#include <simgear/compiler.h>
#include STL_STRING // Standard C++ string library
#include <plib/sg.h>
#include <plib/ssg.h>
#include <simgear/props/props.hxx>
#include "matmodel.hxx"
SG_USING_STD(string);
/**
* A material in the scene graph.
*
* A material represents information about a single surface type
* in the 3D scene graph, including texture, colour, lighting,
* tiling, and so on; most of the materials in FlightGear are
* defined in the $FG_ROOT/materials.xml file, and can be changed
* at runtime.
*/
class SGMaterial {
public:
////////////////////////////////////////////////////////////////////
// Public Constructors.
////////////////////////////////////////////////////////////////////
/**
* Construct a material from a set of properties.
*
* @param props A property node containing subnodes with the
* state information for the material. This node is usually
* loaded from the $FG_ROOT/materials.xml file.
*/
SGMaterial( const string &fg_root, const SGPropertyNode *props );
/**
* Construct a material from an absolute texture path.
*
* @param texture_path A string containing an absolute path
* to a texture file (usually RGB).
*/
SGMaterial( const string &texpath );
/**
* Construct a material around an existing SSG state.
*
* This constructor allows the application to create a custom,
* low-level state for the scene graph and wrap a material around
* it. Note: the pointer ownership is transferred to the material.
*
* @param s The SSG state for this material.
*/
SGMaterial( ssgSimpleState *s );
/**
* Destructor.
*/
virtual ~SGMaterial( void );
////////////////////////////////////////////////////////////////////
// Public methods.
////////////////////////////////////////////////////////////////////
/**
* Force the texture to load if it hasn't already.
*
* @return true if the texture loaded, false if it was loaded
* already.
*/
virtual bool load_texture ();
/**
* Get the textured state.
*/
virtual inline ssgSimpleState *get_state () const { return state; }
/**
* Get the xsize of the texture, in meters.
*/
virtual inline double get_xsize() const { return xsize; }
/**
* Get the ysize of the texture, in meters.
*/
virtual inline double get_ysize() const { return ysize; }
/**
* Get the light coverage.
*
* A smaller number means more generated night lighting.
*
* @return The area (m^2?) covered by each light.
*/
virtual inline double get_light_coverage () const { return light_coverage; }
/**
* Get the number of randomly-placed objects defined for this material.
*/
virtual int get_object_group_count () const { return object_groups.size(); }
/**
* Get a randomly-placed object for this material.
*/
virtual SGMatModelGroup * get_object_group (int index) const {
return object_groups[index];
}
/**
* Increment the reference count for this material.
*
* A material with 0 references may be deleted by the
* material library.
*/
virtual inline void ref () { refcount++; }
/**
* Decrement the reference count for this material.
*/
virtual inline void deRef () { refcount--; }
/**
* Get the reference count for this material.
*
* @return The number of references (0 if none).
*/
virtual inline int getRef () const { return refcount; }
protected:
////////////////////////////////////////////////////////////////////
// Protected methods.
////////////////////////////////////////////////////////////////////
/**
* Initialization method, invoked by all public constructors.
*/
virtual void init();
private:
////////////////////////////////////////////////////////////////////
// Internal state.
////////////////////////////////////////////////////////////////////
// names
string texture_path;
// pointers to ssg states
ssgSimpleState *state;
// texture size
double xsize, ysize;
// wrap texture?
bool wrapu, wrapv;
// use mipmapping?
int mipmap;
// coverage of night lighting.
double light_coverage;
// material properties
sgVec4 ambient, diffuse, specular, emission;
double shininess;
// true if texture loading deferred, and not yet loaded
bool texture_loaded;
vector<SGMatModelGroup *> object_groups;
// ref count so we can properly delete if we have multiple
// pointers to this record
int refcount;
////////////////////////////////////////////////////////////////////
// Internal constructors and methods.
////////////////////////////////////////////////////////////////////
SGMaterial( const string &fg_root, const SGMaterial &mat ); // unimplemented
void read_properties( const string &fg_root, const SGPropertyNode *props );
void build_ssg_state( bool defer_tex_load );
void set_ssg_state( ssgSimpleState *s );
};
#endif // _SG_MAT_HXX
<commit_msg>Forgot to #include <vector><commit_after>// mat.hxx -- a material in the scene graph.
// TODO: this class needs to be renamed.
//
// Written by Curtis Olson, started May 1998.
// Overhauled by David Megginson, December 2001
//
// Copyright (C) 1998 - 2000 Curtis L. Olson - curt@flightgear.org
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation; either version 2 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
//
// $Id$
#ifndef _SG_MAT_HXX
#define _SG_MAT_HXX
#ifndef __cplusplus
# error This library requires C++
#endif
#include <simgear/compiler.h>
#include STL_STRING // Standard C++ string library
#include <vector>
#include <plib/sg.h>
#include <plib/ssg.h>
#include <simgear/props/props.hxx>
#include "matmodel.hxx"
SG_USING_STD(string);
SG_USING_STD(vector);
/**
* A material in the scene graph.
*
* A material represents information about a single surface type
* in the 3D scene graph, including texture, colour, lighting,
* tiling, and so on; most of the materials in FlightGear are
* defined in the $FG_ROOT/materials.xml file, and can be changed
* at runtime.
*/
class SGMaterial {
public:
////////////////////////////////////////////////////////////////////
// Public Constructors.
////////////////////////////////////////////////////////////////////
/**
* Construct a material from a set of properties.
*
* @param props A property node containing subnodes with the
* state information for the material. This node is usually
* loaded from the $FG_ROOT/materials.xml file.
*/
SGMaterial( const string &fg_root, const SGPropertyNode *props );
/**
* Construct a material from an absolute texture path.
*
* @param texture_path A string containing an absolute path
* to a texture file (usually RGB).
*/
SGMaterial( const string &texpath );
/**
* Construct a material around an existing SSG state.
*
* This constructor allows the application to create a custom,
* low-level state for the scene graph and wrap a material around
* it. Note: the pointer ownership is transferred to the material.
*
* @param s The SSG state for this material.
*/
SGMaterial( ssgSimpleState *s );
/**
* Destructor.
*/
virtual ~SGMaterial( void );
////////////////////////////////////////////////////////////////////
// Public methods.
////////////////////////////////////////////////////////////////////
/**
* Force the texture to load if it hasn't already.
*
* @return true if the texture loaded, false if it was loaded
* already.
*/
virtual bool load_texture ();
/**
* Get the textured state.
*/
virtual inline ssgSimpleState *get_state () const { return state; }
/**
* Get the xsize of the texture, in meters.
*/
virtual inline double get_xsize() const { return xsize; }
/**
* Get the ysize of the texture, in meters.
*/
virtual inline double get_ysize() const { return ysize; }
/**
* Get the light coverage.
*
* A smaller number means more generated night lighting.
*
* @return The area (m^2?) covered by each light.
*/
virtual inline double get_light_coverage () const { return light_coverage; }
/**
* Get the number of randomly-placed objects defined for this material.
*/
virtual int get_object_group_count () const { return object_groups.size(); }
/**
* Get a randomly-placed object for this material.
*/
virtual SGMatModelGroup * get_object_group (int index) const {
return object_groups[index];
}
/**
* Increment the reference count for this material.
*
* A material with 0 references may be deleted by the
* material library.
*/
virtual inline void ref () { refcount++; }
/**
* Decrement the reference count for this material.
*/
virtual inline void deRef () { refcount--; }
/**
* Get the reference count for this material.
*
* @return The number of references (0 if none).
*/
virtual inline int getRef () const { return refcount; }
protected:
////////////////////////////////////////////////////////////////////
// Protected methods.
////////////////////////////////////////////////////////////////////
/**
* Initialization method, invoked by all public constructors.
*/
virtual void init();
private:
////////////////////////////////////////////////////////////////////
// Internal state.
////////////////////////////////////////////////////////////////////
// names
string texture_path;
// pointers to ssg states
ssgSimpleState *state;
// texture size
double xsize, ysize;
// wrap texture?
bool wrapu, wrapv;
// use mipmapping?
int mipmap;
// coverage of night lighting.
double light_coverage;
// material properties
sgVec4 ambient, diffuse, specular, emission;
double shininess;
// true if texture loading deferred, and not yet loaded
bool texture_loaded;
vector<SGMatModelGroup *> object_groups;
// ref count so we can properly delete if we have multiple
// pointers to this record
int refcount;
////////////////////////////////////////////////////////////////////
// Internal constructors and methods.
////////////////////////////////////////////////////////////////////
SGMaterial( const string &fg_root, const SGMaterial &mat ); // unimplemented
void read_properties( const string &fg_root, const SGPropertyNode *props );
void build_ssg_state( bool defer_tex_load );
void set_ssg_state( ssgSimpleState *s );
};
#endif // _SG_MAT_HXX
<|endoftext|> |
<commit_before>MatrixXcd X = MatrixXcd::Random(4,4);
MatrixXcd A = X + X.adjoint();
cout << "Here is a random self-adjoint 4x4 matrix:" << endl << A << endl << endl;
Tridiagonalization<MatrixXcd> triOfA(A);
MatrixXcd T = triOfA.matrixT();
cout << "The tridiagonal matrix T is:" << endl << triOfA.matrixT() << endl << endl;
cout << "We can also extract the diagonals of T directly ..." << endl;
VectorXd diag = triOfA.diagonal();
cout << "The diagonal is:" << endl << diag << endl;
VectorXd subdiag = triOfA.subDiagonal();
cout << "The subdiagonal is:" << endl << subdiag << endl;
<commit_msg>Fix compilation of Tridiagonalization_diagonal example. After changeset 63806965d637, matrixT() is a real matrix even if the matrix which is decomposed is complex.<commit_after>MatrixXcd X = MatrixXcd::Random(4,4);
MatrixXcd A = X + X.adjoint();
cout << "Here is a random self-adjoint 4x4 matrix:" << endl << A << endl << endl;
Tridiagonalization<MatrixXcd> triOfA(A);
MatrixXd T = triOfA.matrixT();
cout << "The tridiagonal matrix T is:" << endl << triOfA.matrixT() << endl << endl;
cout << "We can also extract the diagonals of T directly ..." << endl;
VectorXd diag = triOfA.diagonal();
cout << "The diagonal is:" << endl << diag << endl;
VectorXd subdiag = triOfA.subDiagonal();
cout << "The subdiagonal is:" << endl << subdiag << endl;
<|endoftext|> |
<commit_before>/*
Flexisip, a flexible SIP proxy server with media capabilities.
Copyright (C) 2010-2015 Belledonne Communications SARL, All rights reserved.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <sys/types.h>
#include <dirent.h>
#include "pushnotificationservice.hh"
#include "pushnotificationclient.hh"
#include "common.hh"
#include <boost/bind.hpp>
#include <sstream>
static const char *APN_DEV_ADDRESS = "gateway.sandbox.push.apple.com";
static const char *APN_PROD_ADDRESS = "gateway.push.apple.com";
static const char *APN_PORT = "2195";
static const char *GPN_ADDRESS = "android.googleapis.com";
static const char *GPN_PORT = "443";
static const char *WPPN_PORT = "80";
using namespace ::std;
namespace ssl = boost::asio::ssl;
int PushNotificationService::sendRequest(const std::shared_ptr<PushNotificationRequest> &pn) {
std::shared_ptr<PushNotificationClient> client=mClients[pn->getAppIdentifier()];
if (client==0){
if (pn->getType().compare(string("wp"))==0) {
string wpClient = pn->getAppIdentifier();
std::shared_ptr<ssl::context> ctx(new ssl::context(mIOService, ssl::context::sslv23_client));
boost::system::error_code err;
ctx->set_options(ssl::context::default_workarounds, err);
ctx->set_verify_mode(ssl::context::verify_none);
mClients[wpClient] = std::make_shared<PushNotificationClient>(wpClient, this, ctx, pn->getAppIdentifier(), WPPN_PORT, mMaxQueueSize, false);
LOGD("Creating PN client for %s",pn->getAppIdentifier().c_str());
client = mClients[wpClient];
} else {
LOGE("No push notification certificate for client %s",pn->getAppIdentifier().c_str());
return -1;
}
}
//this method is called from flexisip main thread, while service is running in its own thread.
//To avoid using dedicated mutex, use the server post() method to delegate the processing of the push notification to the service thread.
mIOService.post(std::bind(&PushNotificationClient::sendRequest,client,pn));
return 0;
}
void PushNotificationService::start() {
if (mThread && !mThread->joinable()) {
delete mThread;
mThread = NULL;
}
if (mThread == NULL) {
LOGD("Start PushNotificationService");
mHaveToStop = false;
mThread = new thread(&PushNotificationService::run, this);
}
}
void PushNotificationService::stop() {
if (mThread != NULL) {
LOGD("Stopping PushNotificationService");
mHaveToStop = true;
mIOService.stop();
if (mThread->joinable()) {
mThread->join();
}
delete mThread;
mThread = NULL;
}
}
void PushNotificationService::waitEnd() {
if (mThread != NULL) {
LOGD("Waiting for PushNotificationService to end");
bool finished = false;
while (!finished) {
finished = true;
map<string, std::shared_ptr<PushNotificationClient> >::const_iterator it;
for (it = mClients.begin(); it != mClients.end(); ++it) {
if (!it->second->isIdle()) {
finished = false;
break;
}
}
}
usleep(100000); // avoid eating all cpu for nothing
}
}
void PushNotificationService::setupErrorClient(){
// Error client
std::shared_ptr<ssl::context> ctx(new ssl::context(mIOService, ssl::context::sslv23_client));
boost::system::error_code err;
ctx->set_options(ssl::context::default_workarounds, err);
ctx->set_verify_mode(ssl::context::verify_none);
mClients["error"]=std::make_shared<PushNotificationClient>("error", this, ctx, "127.0.0.1", "1", mMaxQueueSize, false);
}
void PushNotificationService::setupGenericClient(const url_t *url){
std::shared_ptr<ssl::context> ctx(new ssl::context(mIOService, ssl::context::sslv23_client));
boost::system::error_code err;
ctx->set_options(ssl::context::default_workarounds, err);
ctx->set_verify_mode(ssl::context::verify_none);
mClients["generic"]=std::make_shared<PushNotificationClient>("generic", this, ctx, url->url_host, url_port(url), mMaxQueueSize, false);
}
void PushNotificationService::setupiOSClient(const std::string &certdir, const std::string &cafile) {
struct dirent *dirent;
DIR *dirp;
dirp=opendir(certdir.c_str());
if (dirp==NULL){
LOGE("Could not open push notification certificates directory (%s): %s",certdir.c_str(),strerror(errno));
return;
}
SLOGD << "Searching push notification client on dir [" << certdir << "]";
while(true){
errno = 0;
if((dirent=readdir(dirp))==NULL) {
if(errno) SLOGE << "Cannot read dir [" << certdir << "] because [" << strerror(errno) << "]";
break;
}
string cert=string(dirent->d_name);
//only consider files which end with .pem
if(cert.compare(".") == 0 || cert.compare("..") == 0 || (cert.compare (cert.length() - ".pem".length(), ".pem".length(), ".pem") != 0)) {
continue;
}
string certpath= string(certdir)+"/"+cert;
std::shared_ptr<ssl::context> context(new ssl::context(mIOService, ssl::context::sslv23_client));
boost::system::error_code error;
context->set_options(ssl::context::default_workarounds, error);
context->set_password_callback(bind(&PushNotificationService::handle_password_callback, this, _1, _2));
if (!cafile.empty()) {
context->set_verify_mode(ssl::context::verify_peer);
#if BOOST_VERSION >= 104800
context->set_verify_callback(bind(&PushNotificationService::handle_verify_callback, this, _1, _2));
#endif
context->load_verify_file(cafile, error);
if (error) {
LOGE("load_verify_file: %s",error.message().c_str());
continue;
}
} else {
context->set_verify_mode(ssl::context::verify_none);
}
context->add_verify_path("/etc/ssl/certs");
if (!cert.empty()) {
context->use_certificate_file(certpath, ssl::context::file_format::pem, error);
if (error) {
LOGE("use_certificate_file %s: %s",certpath.c_str(), error.message().c_str());
continue;
}
}
string key=certpath;
if (!key.empty()) {
context->use_private_key_file(key, ssl::context::file_format::pem, error);
if (error) {
LOGE("use_private_key_file %s: %s", certpath.c_str(), error.message().c_str());
continue;
}
}
string certName = cert.substr(0, cert.size() - 4); // Remove .pem at the end of cert
const char *apn_server;
if (certName.find(".dev")!=string::npos)
apn_server=APN_DEV_ADDRESS;
else apn_server=APN_PROD_ADDRESS;
mClients[certName]=std::make_shared<PushNotificationClient>(cert, this, context, apn_server, APN_PORT, mMaxQueueSize, true);
SLOGD << "Adding ios push notification client [" << certName << "]";
}
closedir(dirp);
}
void PushNotificationService::setupAndroidClient(const std::map<std::string, std::string> googleKeys) {
map<string, string>::const_iterator it;
for (it = googleKeys.begin(); it != googleKeys.end(); ++it) {
string android_app_id = it->first;
std::shared_ptr<ssl::context> ctx(new ssl::context(mIOService, ssl::context::sslv23_client));
boost::system::error_code err;
ctx->set_options(ssl::context::default_workarounds, err);
ctx->set_verify_mode(ssl::context::verify_none);
mClients[android_app_id]=std::make_shared<PushNotificationClient>("google", this, ctx, GPN_ADDRESS, GPN_PORT, mMaxQueueSize, true);
SLOGD << "Adding android push notification client [" << android_app_id << "]";
}
}
PushNotificationService::PushNotificationService(int maxQueueSize) :
mIOService(), mThread(NULL), mMaxQueueSize(maxQueueSize), mClients(), mCountFailed(NULL), mCountSent(NULL) {
setupErrorClient();
}
PushNotificationService::~PushNotificationService() {
stop();
}
int PushNotificationService::run() {
LOGD("PushNotificationService Start");
boost::asio::io_service::work work(mIOService);
mIOService.run();
LOGD("PushNotificationService End");
return 0;
}
void PushNotificationService::clientEnded() {
}
boost::asio::io_service &PushNotificationService::getService() {
return mIOService;
}
string PushNotificationService::handle_password_callback(size_t max_length, ssl::context_base::password_purpose purpose) const {
return mPassword;
}
#if BOOST_VERSION >= 104800
bool PushNotificationService::handle_verify_callback(bool preverified, ssl::verify_context& ctx) const {
char subject_name[256];
#if not(__GNUC__ == 4 && __GNUC_MINOR__ < 5 )
SLOGD << "Verifying " << [&] () {
X509* cert = X509_STORE_CTX_get_current_cert(ctx.native_handle());
X509_NAME_oneline(X509_get_subject_name(cert), subject_name, 256);
return subject_name;
}();
#else
X509* cert = X509_STORE_CTX_get_current_cert(ctx.native_handle());
X509_NAME_oneline(X509_get_subject_name(cert), subject_name, 256);
SLOGD << "Verifying " << subject_name;
#endif
return preverified;
}
#endif
<commit_msg>gcc: fix compilation warning<commit_after>/*
Flexisip, a flexible SIP proxy server with media capabilities.
Copyright (C) 2010-2015 Belledonne Communications SARL, All rights reserved.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <sys/types.h>
#include <dirent.h>
#include "pushnotificationservice.hh"
#include "pushnotificationclient.hh"
#include "common.hh"
#include <boost/bind.hpp>
#include <sstream>
static const char *APN_DEV_ADDRESS = "gateway.sandbox.push.apple.com";
static const char *APN_PROD_ADDRESS = "gateway.push.apple.com";
static const char *APN_PORT = "2195";
static const char *GPN_ADDRESS = "android.googleapis.com";
static const char *GPN_PORT = "443";
static const char *WPPN_PORT = "80";
using namespace ::std;
namespace ssl = boost::asio::ssl;
int PushNotificationService::sendRequest(const std::shared_ptr<PushNotificationRequest> &pn) {
std::shared_ptr<PushNotificationClient> client=mClients[pn->getAppIdentifier()];
if (client==0){
if (pn->getType().compare(string("wp"))==0) {
string wpClient = pn->getAppIdentifier();
std::shared_ptr<ssl::context> ctx(new ssl::context(mIOService, ssl::context::sslv23_client));
boost::system::error_code err;
ctx->set_options(ssl::context::default_workarounds, err);
ctx->set_verify_mode(ssl::context::verify_none);
mClients[wpClient] = std::make_shared<PushNotificationClient>(wpClient, this, ctx, pn->getAppIdentifier(), WPPN_PORT, mMaxQueueSize, false);
LOGD("Creating PN client for %s",pn->getAppIdentifier().c_str());
client = mClients[wpClient];
} else {
LOGE("No push notification certificate for client %s",pn->getAppIdentifier().c_str());
return -1;
}
}
//this method is called from flexisip main thread, while service is running in its own thread.
//To avoid using dedicated mutex, use the server post() method to delegate the processing of the push notification to the service thread.
mIOService.post(std::bind(&PushNotificationClient::sendRequest,client,pn));
return 0;
}
void PushNotificationService::start() {
if (mThread && !mThread->joinable()) {
delete mThread;
mThread = NULL;
}
if (mThread == NULL) {
LOGD("Start PushNotificationService");
mHaveToStop = false;
mThread = new thread(&PushNotificationService::run, this);
}
}
void PushNotificationService::stop() {
if (mThread != NULL) {
LOGD("Stopping PushNotificationService");
mHaveToStop = true;
mIOService.stop();
if (mThread->joinable()) {
mThread->join();
}
delete mThread;
mThread = NULL;
}
}
void PushNotificationService::waitEnd() {
if (mThread != NULL) {
LOGD("Waiting for PushNotificationService to end");
bool finished = false;
while (!finished) {
finished = true;
map<string, std::shared_ptr<PushNotificationClient> >::const_iterator it;
for (it = mClients.begin(); it != mClients.end(); ++it) {
if (!it->second->isIdle()) {
finished = false;
break;
}
}
}
usleep(100000); // avoid eating all cpu for nothing
}
}
void PushNotificationService::setupErrorClient(){
// Error client
std::shared_ptr<ssl::context> ctx(new ssl::context(mIOService, ssl::context::sslv23_client));
boost::system::error_code err;
ctx->set_options(ssl::context::default_workarounds, err);
ctx->set_verify_mode(ssl::context::verify_none);
mClients["error"]=std::make_shared<PushNotificationClient>("error", this, ctx, "127.0.0.1", "1", mMaxQueueSize, false);
}
void PushNotificationService::setupGenericClient(const url_t *url){
std::shared_ptr<ssl::context> ctx(new ssl::context(mIOService, ssl::context::sslv23_client));
boost::system::error_code err;
ctx->set_options(ssl::context::default_workarounds, err);
ctx->set_verify_mode(ssl::context::verify_none);
mClients["generic"]=std::make_shared<PushNotificationClient>("generic", this, ctx, url->url_host, url_port(url), mMaxQueueSize, false);
}
void PushNotificationService::setupiOSClient(const std::string &certdir, const std::string &cafile) {
struct dirent *dirent;
DIR *dirp;
dirp=opendir(certdir.c_str());
if (dirp==NULL){
LOGE("Could not open push notification certificates directory (%s): %s",certdir.c_str(),strerror(errno));
return;
}
SLOGD << "Searching push notification client on dir [" << certdir << "]";
while(true){
errno = 0;
if((dirent=readdir(dirp))==NULL) {
if(errno) SLOGE << "Cannot read dir [" << certdir << "] because [" << strerror(errno) << "]";
break;
}
string cert=string(dirent->d_name);
//only consider files which end with .pem
string suffix = ".pem";
if(cert.compare(".") == 0 || cert.compare("..") == 0 || (cert.compare (cert.length() - suffix.length(), suffix.length(), suffix) != 0)) {
continue;
}
string certpath= string(certdir)+"/"+cert;
std::shared_ptr<ssl::context> context(new ssl::context(mIOService, ssl::context::sslv23_client));
boost::system::error_code error;
context->set_options(ssl::context::default_workarounds, error);
context->set_password_callback(bind(&PushNotificationService::handle_password_callback, this, _1, _2));
if (!cafile.empty()) {
context->set_verify_mode(ssl::context::verify_peer);
#if BOOST_VERSION >= 104800
context->set_verify_callback(bind(&PushNotificationService::handle_verify_callback, this, _1, _2));
#endif
context->load_verify_file(cafile, error);
if (error) {
LOGE("load_verify_file: %s",error.message().c_str());
continue;
}
} else {
context->set_verify_mode(ssl::context::verify_none);
}
context->add_verify_path("/etc/ssl/certs");
if (!cert.empty()) {
context->use_certificate_file(certpath, ssl::context::file_format::pem, error);
if (error) {
LOGE("use_certificate_file %s: %s",certpath.c_str(), error.message().c_str());
continue;
}
}
string key=certpath;
if (!key.empty()) {
context->use_private_key_file(key, ssl::context::file_format::pem, error);
if (error) {
LOGE("use_private_key_file %s: %s", certpath.c_str(), error.message().c_str());
continue;
}
}
string certName = cert.substr(0, cert.size() - 4); // Remove .pem at the end of cert
const char *apn_server;
if (certName.find(".dev")!=string::npos)
apn_server=APN_DEV_ADDRESS;
else apn_server=APN_PROD_ADDRESS;
mClients[certName]=std::make_shared<PushNotificationClient>(cert, this, context, apn_server, APN_PORT, mMaxQueueSize, true);
SLOGD << "Adding ios push notification client [" << certName << "]";
}
closedir(dirp);
}
void PushNotificationService::setupAndroidClient(const std::map<std::string, std::string> googleKeys) {
map<string, string>::const_iterator it;
for (it = googleKeys.begin(); it != googleKeys.end(); ++it) {
string android_app_id = it->first;
std::shared_ptr<ssl::context> ctx(new ssl::context(mIOService, ssl::context::sslv23_client));
boost::system::error_code err;
ctx->set_options(ssl::context::default_workarounds, err);
ctx->set_verify_mode(ssl::context::verify_none);
mClients[android_app_id]=std::make_shared<PushNotificationClient>("google", this, ctx, GPN_ADDRESS, GPN_PORT, mMaxQueueSize, true);
SLOGD << "Adding android push notification client [" << android_app_id << "]";
}
}
PushNotificationService::PushNotificationService(int maxQueueSize) :
mIOService(), mThread(NULL), mMaxQueueSize(maxQueueSize), mClients(), mCountFailed(NULL), mCountSent(NULL) {
setupErrorClient();
}
PushNotificationService::~PushNotificationService() {
stop();
}
int PushNotificationService::run() {
LOGD("PushNotificationService Start");
boost::asio::io_service::work work(mIOService);
mIOService.run();
LOGD("PushNotificationService End");
return 0;
}
void PushNotificationService::clientEnded() {
}
boost::asio::io_service &PushNotificationService::getService() {
return mIOService;
}
string PushNotificationService::handle_password_callback(size_t max_length, ssl::context_base::password_purpose purpose) const {
return mPassword;
}
#if BOOST_VERSION >= 104800
bool PushNotificationService::handle_verify_callback(bool preverified, ssl::verify_context& ctx) const {
char subject_name[256];
#if not(__GNUC__ == 4 && __GNUC_MINOR__ < 5 )
SLOGD << "Verifying " << [&] () {
X509* cert = X509_STORE_CTX_get_current_cert(ctx.native_handle());
X509_NAME_oneline(X509_get_subject_name(cert), subject_name, 256);
return subject_name;
}();
#else
X509* cert = X509_STORE_CTX_get_current_cert(ctx.native_handle());
X509_NAME_oneline(X509_get_subject_name(cert), subject_name, 256);
SLOGD << "Verifying " << subject_name;
#endif
return preverified;
}
#endif
<|endoftext|> |
<commit_before>// Given a non-empty binary search tree and a target value, find the value in
// the BST that is closest to the target.
// Note:
// Given target value is a floating point.
// You are guaranteed to have only one unique value in the BST that is
// closest to the target.
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int closestValue(TreeNode *root, double target) {
TreeNode *prev = nullptr;
stack<TreeNode *> s;
while (!s.empty() || root)
if (root) {
s.push(root);
root = root->left;
} else {
root = s.top();
s.pop();
// visit root
if (target == root->val)
return target;
if (target < root->val)
if (!prev)
return root->val;
else
return target - prev->val > root->val - target
? root->val
: prev->val;
prev = root;
root = root->right;
}
return prev->val; // right most
}
};<commit_msg>270. Closest Binary Search Tree Value<commit_after>// Given a non-empty binary search tree and a target value, find the value in
// the BST that is closest to the target.
// Note:
// Given target value is a floating point.
// You are guaranteed to have only one unique value in the BST that is
// closest to the target.
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
// recursion
class Solution {
public:
int closestValue(TreeNode *root, double target) {
int a = root->val;
TreeNode *child = target < root->val ? root->left : root->right;
if (!child)
return a;
int b = closestValue(child, target);
return abs(a - target) < abs(b - target) ? a : b;
}
};
// binary search
class Solution {
public:
int closestValue(TreeNode *root, double target) {
pair<TreeNode *, TreeNode *> bound = make_pair(nullptr, nullptr);
while (root) {
if (target == root->val)
return target;
if (target > root->val) {
bound.first = root;
root = root->right;
} else {
bound.second = root;
root = root->left;
}
}
return (!bound.second || bound.first && target - bound.first->val <
bound.second->val - target)
? bound.first->val
: bound.second->val;
}
};
// binary search
class Solution {
public:
int closestValue(TreeNode *root, double target) {
pair<double, double> bound = make_pair(numeric_limits<double>::lowest(),
numeric_limits<double>::max());
while (root) {
if (target == root->val)
return target;
if (target > root->val) {
bound.first = root->val;
root = root->right;
} else {
bound.second = root->val;
root = root->left;
}
}
return (bound.second == numeric_limits<double>::max() ||
bound.first != numeric_limits<double>::lowest() &&
target - bound.first < bound.second - target)
? bound.first
: bound.second;
}
};
// inorder traverse
class Solution {
public:
int closestValue(TreeNode *root, double target) {
TreeNode *prev = nullptr;
stack<TreeNode *> s;
while (!s.empty() || root)
if (root) {
s.push(root);
root = root->left;
} else {
root = s.top();
s.pop();
// visit root
if (target == root->val)
return target;
if (target < root->val)
if (!prev)
return root->val;
else
return target - prev->val > root->val - target
? root->val
: prev->val;
prev = root;
root = root->right;
}
return prev->val; // right most
}
};<|endoftext|> |
<commit_before>// $Id: NMRSpectrum_test.C,v 1.1 2000/09/22 00:33:47 amoll Exp $
#include <BALL/CONCEPT/classTest.h>
///////////////////////////
#include <BALL/NMR/NMRSpectrum.h>
#include <BALL/FORMAT/HINFile.h>
#include <BALL/FORMAT/PDBFile.h>
///////////////////////////
START_TEST(NMRSpectrum, "$Id: NMRSpectrum_test.C,v 1.1 2000/09/22 00:33:47 amoll Exp $")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
using namespace BALL;
CHECK("testname")
RESULT
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
<commit_msg>added more tests<commit_after>// $Id: NMRSpectrum_test.C,v 1.2 2000/09/22 14:11:30 amoll Exp $
#include <BALL/CONCEPT/classTest.h>
///////////////////////////
#include <BALL/FORMAT/HINFile.h>
#include <BALL/NMR/NMRSpectrum.h>
#include <BALL/NMR/peak.h>
#include <BALL/KERNEL/system.h>
///////////////////////////
START_TEST(NMRSpectrum, "$Id: NMRSpectrum_test.C,v 1.2 2000/09/22 14:11:30 amoll Exp $")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
using namespace BALL;
NMRSpectrum* p;
CHECK(NMRSpectrum::NMRSpectrum())
p = new NMRSpectrum;
TEST_NOT_EQUAL(p, 0);
RESULT
CHECK(NMRSpectrum::~NMRSpectrum())
delete p;
RESULT
NMRSpectrum spectrum;
HINFile f("data/NMRSpectrum_test.hin");
System system;
f >> system;
CHECK(NMRSpectrum::setSystem(System* s)/getSystem())
TEST_EQUAL(spectrum.getSystem(), 0)
spectrum.setSystem(&system);
TEST_EQUAL(spectrum.getSystem(), &system)
RESULT
CHECK(NMRSpectrum::setDensity(Size density)/getDensity())
TEST_EQUAL(spectrum.getDensity(), 100)
spectrum.setDensity(50);
TEST_EQUAL(spectrum.getDensity(), 50)
spectrum.setDensity(100);
RESULT
CHECK(NMRSpectrum::calculateShifts())
spectrum.calculateShifts();
RESULT
CHECK(NMRSpectrum::createSpectrum())
spectrum.createSpectrum();
RESULT
list<Peak1D> peaks;
CHECK(NMRSpectrum::getPeakList() const )
peaks = spectrum.getPeakList();
TEST_EQUAL(peaks.size(), 15)
TEST_EQUAL(peaks.front().getValue(), 0)
TEST_EQUAL(peaks.back().getValue(), 0)
RESULT
CHECK(NMRSpectrum::getSpectrumMin() const )
TEST_EQUAL(spectrum.getSpectrumMin(), 0)
RESULT
CHECK(NMRSpectrum::getSpectrumMax() const )
TEST_EQUAL(spectrum.getSpectrumMax(), 0) // ???
RESULT
CHECK(NMRSpectrum::setPeakList(const list<Peak1D>& spectrum))
NMRSpectrum spectrum2;
spectrum2.setPeakList(peaks);
RESULT
CHECK(NMRSpectrum::sortSpectrum())
spectrum.sortSpectrum();
RESULT
String filename;
CHECK(NMRSpectrum::plotSpectrum(const String& filename) const )
// terminiert nicht ???
/*
NEW_TMP_FILE(filename)
spectrum.plotSpectrum(filename);
TEST_FILE(filename.c_str(), "data/NMRSpectrum/plotSpectrum.txt", false)*/
RESULT
CHECK(NMRSpectrum::plotPeaks(const String& filename) const )
NEW_TMP_FILE(filename)
spectrum.plotPeaks(filename);
TEST_FILE(filename.c_str(), "data/NMRSpectrum/plotPeaks.txt", false)
RESULT
CHECK(NMRSpectrum::writePeaks(const String& filename) const )
NEW_TMP_FILE(filename)
spectrum.writePeaks(filename);
TEST_FILE(filename.c_str(), "data/NMRSpectrum/writePeaks.txt", false)
RESULT
CHECK(NMRSpectrum::makeDifference(const float&, const String&, const String&, const String&))
//BAUSTELLE
RESULT
CHECK(NMRSpectrum::setDifference(NMRSpectrum*, NMRSpectrum*, String, String))
//BAUSTELLE
RESULT
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
<|endoftext|> |
<commit_before>#include <jni.h>
#include <mpv/client.h>
#include "globals.h"
#include "jni_utils.h"
#include "log.h"
static void sendPropertyUpdateToJava(JNIEnv *env, mpv_event_property *prop) {
jstring jprop = env->NewStringUTF(prop->name);
jstring jvalue = NULL;
switch (prop->format) {
case MPV_FORMAT_NONE:
env->CallStaticVoidMethod(mpv_MPVLib, mpv_MPVLib_eventProperty_S, jprop);
break;
case MPV_FORMAT_FLAG:
env->CallStaticVoidMethod(mpv_MPVLib, mpv_MPVLib_eventProperty_Sb, jprop, *(int*)prop->data);
break;
case MPV_FORMAT_INT64:
env->CallStaticVoidMethod(mpv_MPVLib, mpv_MPVLib_eventProperty_Sl, jprop, *(int64_t*)prop->data);
break;
case MPV_FORMAT_STRING:
jvalue = env->NewStringUTF(*(const char**)prop->data);
env->CallStaticVoidMethod(mpv_MPVLib, mpv_MPVLib_eventProperty_SS, jprop, jvalue);
break;
default:
ALOGV("sendPropertyUpdateToJava: Unknown property update format received in callback: %d!", prop->format);
break;
}
}
static void sendEventToJava(JNIEnv *env, int event) {
env->CallStaticVoidMethod(mpv_MPVLib, mpv_MPVLib_event, event);
}
void *event_thread(void *arg) {
JNIEnv *env = NULL;
acquire_jni_env(g_vm, &env);
if (!env)
die("failed to acquire java env");
while (1) {
mpv_event *mp_event;
mpv_event_property *mp_property = NULL;
mpv_event_log_message *msg = NULL;
mp_event = mpv_wait_event(g_mpv, -1.0);
if (g_event_thread_request_exit)
break;
if (mp_event->event_id == MPV_EVENT_NONE)
continue;
switch (mp_event->event_id) {
case MPV_EVENT_LOG_MESSAGE:
msg = (mpv_event_log_message*)mp_event->data;
ALOGV("[%s:%s] %s", msg->prefix, msg->level, msg->text);
break;
case MPV_EVENT_PROPERTY_CHANGE:
mp_property = (mpv_event_property*)mp_event->data;
sendPropertyUpdateToJava(env, mp_property);
break;
default:
ALOGV("event: %s\n", mpv_event_name(mp_event->event_id));
sendEventToJava(env, mp_event->event_id);
break;
}
}
g_vm->DetachCurrentThread();
return NULL;
}
<commit_msg>jni/event: free property/value strings in sendPropertyUpdateToJava<commit_after>#include <jni.h>
#include <mpv/client.h>
#include "globals.h"
#include "jni_utils.h"
#include "log.h"
static void sendPropertyUpdateToJava(JNIEnv *env, mpv_event_property *prop) {
jstring jprop = env->NewStringUTF(prop->name);
jstring jvalue = NULL;
switch (prop->format) {
case MPV_FORMAT_NONE:
env->CallStaticVoidMethod(mpv_MPVLib, mpv_MPVLib_eventProperty_S, jprop);
break;
case MPV_FORMAT_FLAG:
env->CallStaticVoidMethod(mpv_MPVLib, mpv_MPVLib_eventProperty_Sb, jprop, *(int*)prop->data);
break;
case MPV_FORMAT_INT64:
env->CallStaticVoidMethod(mpv_MPVLib, mpv_MPVLib_eventProperty_Sl, jprop, *(int64_t*)prop->data);
break;
case MPV_FORMAT_STRING:
jvalue = env->NewStringUTF(*(const char**)prop->data);
env->CallStaticVoidMethod(mpv_MPVLib, mpv_MPVLib_eventProperty_SS, jprop, jvalue);
break;
default:
ALOGV("sendPropertyUpdateToJava: Unknown property update format received in callback: %d!", prop->format);
break;
}
if (jprop)
env->DeleteLocalRef(jprop);
if (jvalue)
env->DeleteLocalRef(jvalue);
}
static void sendEventToJava(JNIEnv *env, int event) {
env->CallStaticVoidMethod(mpv_MPVLib, mpv_MPVLib_event, event);
}
void *event_thread(void *arg) {
JNIEnv *env = NULL;
acquire_jni_env(g_vm, &env);
if (!env)
die("failed to acquire java env");
while (1) {
mpv_event *mp_event;
mpv_event_property *mp_property = NULL;
mpv_event_log_message *msg = NULL;
mp_event = mpv_wait_event(g_mpv, -1.0);
if (g_event_thread_request_exit)
break;
if (mp_event->event_id == MPV_EVENT_NONE)
continue;
switch (mp_event->event_id) {
case MPV_EVENT_LOG_MESSAGE:
msg = (mpv_event_log_message*)mp_event->data;
ALOGV("[%s:%s] %s", msg->prefix, msg->level, msg->text);
break;
case MPV_EVENT_PROPERTY_CHANGE:
mp_property = (mpv_event_property*)mp_event->data;
sendPropertyUpdateToJava(env, mp_property);
break;
default:
ALOGV("event: %s\n", mpv_event_name(mp_event->event_id));
sendEventToJava(env, mp_event->event_id);
break;
}
}
g_vm->DetachCurrentThread();
return NULL;
}
<|endoftext|> |
<commit_before>#include "btree/slice_dispatching_to_masterstore.hpp"
#include "replication/masterstore.hpp"
using replication::masterstore_t;
/* store_t interface. */
store_t::get_result_t btree_slice_dispatching_to_masterstore_t::get(store_key_t *key) {
on_thread_t th(slice_->home_thread);
return slice_->get(key);
}
store_t::get_result_t btree_slice_dispatching_to_masterstore_t::get_cas(store_key_t *key, castime_t maybe_castime) {
on_thread_t th(slice_->home_thread);
castime_t castime = generate_if_necessary(maybe_castime);
if (masterstore_) spawn_on_home(masterstore_, boost::bind(&masterstore_t::get_cas, _1, key, castime));
return slice_->get_cas(key, castime);
}
store_t::rget_result_t btree_slice_dispatching_to_masterstore_t::rget(store_key_t *start, store_key_t *end, bool left_open, bool right_open) {
on_thread_t th(slice_->home_thread);
return slice_->rget(start, end, left_open, right_open);
}
store_t::set_result_t btree_slice_dispatching_to_masterstore_t::set(store_key_t *key, data_provider_t *data, mcflags_t flags, exptime_t exptime, castime_t maybe_castime) {
on_thread_t th(slice_->home_thread);
castime_t castime = generate_if_necessary(maybe_castime);
if (masterstore_) spawn_on_home(masterstore_, boost::bind(&masterstore_t::set, _1, key, data, flags, exptime, castime));
return slice_->set(key, data, flags, exptime, castime);
}
store_t::set_result_t btree_slice_dispatching_to_masterstore_t::add(store_key_t *key, data_provider_t *data, mcflags_t flags, exptime_t exptime, castime_t maybe_castime) {
on_thread_t th(slice_->home_thread);
castime_t castime = generate_if_necessary(maybe_castime);
if (masterstore_) spawn_on_home(masterstore_, boost::bind(&masterstore_t::add, _1, key, data, flags, exptime, castime));
return slice_->add(key, data, flags, exptime, castime);
}
store_t::set_result_t btree_slice_dispatching_to_masterstore_t::replace(store_key_t *key, data_provider_t *data, mcflags_t flags, exptime_t exptime, castime_t maybe_castime) {
on_thread_t th(slice_->home_thread);
castime_t castime = generate_if_necessary(maybe_castime);
if (masterstore_) spawn_on_home(masterstore_, boost::bind(&masterstore_t::replace, _1, key, data, flags, exptime, castime));
return slice_->replace(key, data, flags, exptime, castime);
}
store_t::set_result_t btree_slice_dispatching_to_masterstore_t::cas(store_key_t *key, data_provider_t *data, mcflags_t flags, exptime_t exptime, cas_t unique, castime_t maybe_castime) {
on_thread_t th(slice_->home_thread);
castime_t castime = generate_if_necessary(maybe_castime);
if (masterstore_) spawn_on_home(masterstore_, boost::bind(&masterstore_t::cas, _1, key, data, flags, exptime, unique, castime));
return slice_->cas(key, data, flags, exptime, unique, castime);
}
store_t::incr_decr_result_t btree_slice_dispatching_to_masterstore_t::incr(store_key_t *key, unsigned long long amount, castime_t maybe_castime) {
on_thread_t th(slice_->home_thread);
castime_t castime = generate_if_necessary(maybe_castime);
if (masterstore_) spawn_on_home(masterstore_, boost::bind(&masterstore_t::incr, _1, key, amount, castime));
return slice_->incr(key, amount, castime);
}
store_t::incr_decr_result_t btree_slice_dispatching_to_masterstore_t::decr(store_key_t *key, unsigned long long amount, castime_t maybe_castime) {
on_thread_t th(slice_->home_thread);
castime_t castime = generate_if_necessary(maybe_castime);
if (masterstore_) spawn_on_home(masterstore_, boost::bind(&masterstore_t::decr, _1, key, amount, castime));
return slice_->decr(key, amount, castime);
}
store_t::append_prepend_result_t btree_slice_dispatching_to_masterstore_t::append(store_key_t *key, data_provider_t *data, castime_t maybe_castime) {
on_thread_t th(slice_->home_thread);
castime_t castime = generate_if_necessary(maybe_castime);
if (masterstore_) spawn_on_home(masterstore_, boost::bind(&masterstore_t::append, _1, key, data, castime));
return slice_->append(key, data, castime);
}
store_t::append_prepend_result_t btree_slice_dispatching_to_masterstore_t::prepend(store_key_t *key, data_provider_t *data, castime_t maybe_castime) {
on_thread_t th(slice_->home_thread);
castime_t castime = generate_if_necessary(maybe_castime);
if (masterstore_) spawn_on_home(masterstore_, boost::bind(&masterstore_t::prepend, _1, key, data, castime));
return slice_->prepend(key, data, castime);
}
store_t::delete_result_t btree_slice_dispatching_to_masterstore_t::delete_key(store_key_t *key, repli_timestamp maybe_timestamp) {
on_thread_t th(slice_->home_thread);
repli_timestamp timestamp = generate_if_necessary(maybe_timestamp);
if (masterstore_) spawn_on_home(masterstore_, boost::bind(&masterstore_t::delete_key, _1, key, timestamp));
return slice_->delete_key(key, timestamp);
}
castime_t btree_slice_dispatching_to_masterstore_t::gen_castime() {
repli_timestamp timestamp = current_time();
cas_t cas = (uint64_t(timestamp.time) << 32) | ++cas_counter_;
return castime_t(cas, timestamp);
}
castime_t btree_slice_dispatching_to_masterstore_t::generate_if_necessary(castime_t castime) {
return castime.is_dummy() ? gen_castime() : castime;
}
repli_timestamp btree_slice_dispatching_to_masterstore_t::generate_if_necessary(repli_timestamp timestamp) {
return timestamp.time == repli_timestamp::invalid.time ? current_time() : timestamp;
}
<commit_msg>Made btree_slice_dispatching_to_masterstore_t::set use the borrower.<commit_after>#include "btree/slice_dispatching_to_masterstore.hpp"
#include "replication/masterstore.hpp"
using replication::masterstore_t;
/* store_t interface. */
store_t::get_result_t btree_slice_dispatching_to_masterstore_t::get(store_key_t *key) {
on_thread_t th(slice_->home_thread);
return slice_->get(key);
}
store_t::get_result_t btree_slice_dispatching_to_masterstore_t::get_cas(store_key_t *key, castime_t maybe_castime) {
on_thread_t th(slice_->home_thread);
castime_t castime = generate_if_necessary(maybe_castime);
if (masterstore_) spawn_on_home(masterstore_, boost::bind(&masterstore_t::get_cas, _1, key, castime));
return slice_->get_cas(key, castime);
}
store_t::rget_result_t btree_slice_dispatching_to_masterstore_t::rget(store_key_t *start, store_key_t *end, bool left_open, bool right_open) {
on_thread_t th(slice_->home_thread);
return slice_->rget(start, end, left_open, right_open);
}
store_t::set_result_t btree_slice_dispatching_to_masterstore_t::set(store_key_t *key, data_provider_t *data, mcflags_t flags, exptime_t exptime, castime_t maybe_castime) {
on_thread_t th(slice_->home_thread);
castime_t castime = generate_if_necessary(maybe_castime);
if (masterstore_) {
buffer_borrowing_data_provider_t borrower(masterstore_->home_thread, data);
spawn_on_home(masterstore_, boost::bind(&masterstore_t::set, _1, key, borrower.side_provider(), flags, exptime, castime));
return slice_->set(key, &borrower, flags, exptime, castime);
} else {
return slice_->set(key, data, flags, exptime, castime);
}
}
store_t::set_result_t btree_slice_dispatching_to_masterstore_t::add(store_key_t *key, data_provider_t *data, mcflags_t flags, exptime_t exptime, castime_t maybe_castime) {
on_thread_t th(slice_->home_thread);
castime_t castime = generate_if_necessary(maybe_castime);
if (masterstore_) spawn_on_home(masterstore_, boost::bind(&masterstore_t::add, _1, key, data, flags, exptime, castime));
return slice_->add(key, data, flags, exptime, castime);
}
store_t::set_result_t btree_slice_dispatching_to_masterstore_t::replace(store_key_t *key, data_provider_t *data, mcflags_t flags, exptime_t exptime, castime_t maybe_castime) {
on_thread_t th(slice_->home_thread);
castime_t castime = generate_if_necessary(maybe_castime);
if (masterstore_) spawn_on_home(masterstore_, boost::bind(&masterstore_t::replace, _1, key, data, flags, exptime, castime));
return slice_->replace(key, data, flags, exptime, castime);
}
store_t::set_result_t btree_slice_dispatching_to_masterstore_t::cas(store_key_t *key, data_provider_t *data, mcflags_t flags, exptime_t exptime, cas_t unique, castime_t maybe_castime) {
on_thread_t th(slice_->home_thread);
castime_t castime = generate_if_necessary(maybe_castime);
if (masterstore_) spawn_on_home(masterstore_, boost::bind(&masterstore_t::cas, _1, key, data, flags, exptime, unique, castime));
return slice_->cas(key, data, flags, exptime, unique, castime);
}
store_t::incr_decr_result_t btree_slice_dispatching_to_masterstore_t::incr(store_key_t *key, unsigned long long amount, castime_t maybe_castime) {
on_thread_t th(slice_->home_thread);
castime_t castime = generate_if_necessary(maybe_castime);
if (masterstore_) spawn_on_home(masterstore_, boost::bind(&masterstore_t::incr, _1, key, amount, castime));
return slice_->incr(key, amount, castime);
}
store_t::incr_decr_result_t btree_slice_dispatching_to_masterstore_t::decr(store_key_t *key, unsigned long long amount, castime_t maybe_castime) {
on_thread_t th(slice_->home_thread);
castime_t castime = generate_if_necessary(maybe_castime);
if (masterstore_) spawn_on_home(masterstore_, boost::bind(&masterstore_t::decr, _1, key, amount, castime));
return slice_->decr(key, amount, castime);
}
store_t::append_prepend_result_t btree_slice_dispatching_to_masterstore_t::append(store_key_t *key, data_provider_t *data, castime_t maybe_castime) {
on_thread_t th(slice_->home_thread);
castime_t castime = generate_if_necessary(maybe_castime);
if (masterstore_) spawn_on_home(masterstore_, boost::bind(&masterstore_t::append, _1, key, data, castime));
return slice_->append(key, data, castime);
}
store_t::append_prepend_result_t btree_slice_dispatching_to_masterstore_t::prepend(store_key_t *key, data_provider_t *data, castime_t maybe_castime) {
on_thread_t th(slice_->home_thread);
castime_t castime = generate_if_necessary(maybe_castime);
if (masterstore_) spawn_on_home(masterstore_, boost::bind(&masterstore_t::prepend, _1, key, data, castime));
return slice_->prepend(key, data, castime);
}
store_t::delete_result_t btree_slice_dispatching_to_masterstore_t::delete_key(store_key_t *key, repli_timestamp maybe_timestamp) {
on_thread_t th(slice_->home_thread);
repli_timestamp timestamp = generate_if_necessary(maybe_timestamp);
if (masterstore_) spawn_on_home(masterstore_, boost::bind(&masterstore_t::delete_key, _1, key, timestamp));
return slice_->delete_key(key, timestamp);
}
castime_t btree_slice_dispatching_to_masterstore_t::gen_castime() {
repli_timestamp timestamp = current_time();
cas_t cas = (uint64_t(timestamp.time) << 32) | ++cas_counter_;
return castime_t(cas, timestamp);
}
castime_t btree_slice_dispatching_to_masterstore_t::generate_if_necessary(castime_t castime) {
return castime.is_dummy() ? gen_castime() : castime;
}
repli_timestamp btree_slice_dispatching_to_masterstore_t::generate_if_necessary(repli_timestamp timestamp) {
return timestamp.time == repli_timestamp::invalid.time ? current_time() : timestamp;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2012-2019 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <coins.h>
#include <consensus/consensus.h>
#include <logging.h>
#include <random.h>
#include <version.h>
bool CCoinsView::GetCoin(const COutPoint &outpoint, Coin &coin) const { return false; }
uint256 CCoinsView::GetBestBlock() const { return uint256(); }
std::vector<uint256> CCoinsView::GetHeadBlocks() const { return std::vector<uint256>(); }
bool CCoinsView::BatchWrite(CCoinsMap& mapCoins, const uint256& hashBlock, const mw::CoinsViewCache::Ptr& derivedView) { return false; }
CCoinsViewCursor *CCoinsView::Cursor() const { return nullptr; }
bool CCoinsView::HaveCoin(const OutputIndex& index) const
{
if (index.type() == typeid(mw::Hash)) {
if (!GetMWEBView()) return false;
return GetMWEBView()->HasCoin(boost::get<mw::Hash>(index));
} else {
Coin coin;
return GetCoin(boost::get<COutPoint>(index), coin);
}
}
CCoinsViewBacked::CCoinsViewBacked(CCoinsView *viewIn) : base(viewIn) { }
bool CCoinsViewBacked::GetCoin(const COutPoint &outpoint, Coin &coin) const { return base->GetCoin(outpoint, coin); }
bool CCoinsViewBacked::HaveCoin(const OutputIndex& index) const { return base->HaveCoin(index); }
uint256 CCoinsViewBacked::GetBestBlock() const { return base->GetBestBlock(); }
std::vector<uint256> CCoinsViewBacked::GetHeadBlocks() const { return base->GetHeadBlocks(); }
void CCoinsViewBacked::SetBackend(CCoinsView& viewIn) { base = &viewIn; }
bool CCoinsViewBacked::BatchWrite(CCoinsMap& mapCoins, const uint256& hashBlock, const mw::CoinsViewCache::Ptr& derivedView) { return base->BatchWrite(mapCoins, hashBlock, derivedView); }
CCoinsViewCursor *CCoinsViewBacked::Cursor() const { return base->Cursor(); }
size_t CCoinsViewBacked::EstimateSize() const { return base->EstimateSize(); }
mw::ICoinsView::Ptr CCoinsViewBacked::GetMWEBView() const { return base->GetMWEBView(); }
bool CCoinsViewBacked::GetMWEBCoin(const mw::Hash& output_id, Output& coin) const { return base->GetMWEBCoin(output_id, coin); }
SaltedOutpointHasher::SaltedOutpointHasher() : k0(GetRand(std::numeric_limits<uint64_t>::max())), k1(GetRand(std::numeric_limits<uint64_t>::max())) {}
CCoinsViewCache::CCoinsViewCache(CCoinsView* baseIn) : CCoinsViewBacked(baseIn), cachedCoinsUsage(0), mweb_view(baseIn->GetMWEBView() ? std::make_shared<mw::CoinsViewCache>(baseIn->GetMWEBView()) : nullptr) {}
size_t CCoinsViewCache::DynamicMemoryUsage() const {
return memusage::DynamicUsage(cacheCoins) + cachedCoinsUsage;
}
CCoinsMap::iterator CCoinsViewCache::FetchCoin(const COutPoint &outpoint) const {
CCoinsMap::iterator it = cacheCoins.find(outpoint);
if (it != cacheCoins.end())
return it;
Coin tmp;
if (!base->GetCoin(outpoint, tmp))
return cacheCoins.end();
CCoinsMap::iterator ret = cacheCoins.emplace(std::piecewise_construct, std::forward_as_tuple(outpoint), std::forward_as_tuple(std::move(tmp))).first;
if (ret->second.coin.IsSpent()) {
// The parent only has an empty entry for this outpoint; we can consider our
// version as fresh.
ret->second.flags = CCoinsCacheEntry::FRESH;
}
cachedCoinsUsage += ret->second.coin.DynamicMemoryUsage();
return ret;
}
bool CCoinsViewCache::GetCoin(const COutPoint &outpoint, Coin &coin) const {
CCoinsMap::const_iterator it = FetchCoin(outpoint);
if (it != cacheCoins.end()) {
coin = it->second.coin;
return !coin.IsSpent();
}
return false;
}
void CCoinsViewCache::AddCoin(const COutPoint &outpoint, Coin&& coin, bool possible_overwrite) {
assert(!coin.IsSpent());
if (coin.out.scriptPubKey.IsUnspendable()) return;
CCoinsMap::iterator it;
bool inserted;
std::tie(it, inserted) = cacheCoins.emplace(std::piecewise_construct, std::forward_as_tuple(outpoint), std::tuple<>());
bool fresh = false;
if (!inserted) {
cachedCoinsUsage -= it->second.coin.DynamicMemoryUsage();
}
if (!possible_overwrite) {
if (!it->second.coin.IsSpent()) {
throw std::logic_error("Attempted to overwrite an unspent coin (when possible_overwrite is false)");
}
// If the coin exists in this cache as a spent coin and is DIRTY, then
// its spentness hasn't been flushed to the parent cache. We're
// re-adding the coin to this cache now but we can't mark it as FRESH.
// If we mark it FRESH and then spend it before the cache is flushed
// we would remove it from this cache and would never flush spentness
// to the parent cache.
//
// Re-adding a spent coin can happen in the case of a re-org (the coin
// is 'spent' when the block adding it is disconnected and then
// re-added when it is also added in a newly connected block).
//
// If the coin doesn't exist in the current cache, or is spent but not
// DIRTY, then it can be marked FRESH.
fresh = !(it->second.flags & CCoinsCacheEntry::DIRTY);
}
it->second.coin = std::move(coin);
it->second.flags |= CCoinsCacheEntry::DIRTY | (fresh ? CCoinsCacheEntry::FRESH : 0);
cachedCoinsUsage += it->second.coin.DynamicMemoryUsage();
}
void AddCoins(CCoinsViewCache& cache, const CTransaction &tx, int nHeight, bool check_for_overwrite) {
bool fCoinbase = tx.IsCoinBase();
const uint256& txid = tx.GetHash();
for (size_t i = 0; i < tx.vout.size(); ++i) {
// MWEB: The first output in the HogEx transaction is the HogAddr.
// The HogAddr is always spent in the next HogEx, so should not be subjected to pegout maturity rules.
bool fPegout = tx.IsHogEx() && i > 0;
bool overwrite = check_for_overwrite ? cache.HaveCoin(COutPoint(txid, i)) : fCoinbase;
// Coinbase transactions can always be overwritten, in order to correctly
// deal with the pre-BIP30 occurrences of duplicate coinbase transactions.
cache.AddCoin(COutPoint(txid, i), Coin(tx.vout[i], nHeight, fCoinbase, fPegout), overwrite);
}
}
bool CCoinsViewCache::SpendCoin(const COutPoint &outpoint, Coin* moveout) {
CCoinsMap::iterator it = FetchCoin(outpoint);
if (it == cacheCoins.end()) return false;
cachedCoinsUsage -= it->second.coin.DynamicMemoryUsage();
if (moveout) {
*moveout = std::move(it->second.coin);
}
if (it->second.flags & CCoinsCacheEntry::FRESH) {
cacheCoins.erase(it);
} else {
it->second.flags |= CCoinsCacheEntry::DIRTY;
it->second.coin.Clear();
}
return true;
}
static const Coin coinEmpty;
const Coin& CCoinsViewCache::AccessCoin(const COutPoint &outpoint) const {
CCoinsMap::const_iterator it = FetchCoin(outpoint);
if (it == cacheCoins.end()) {
return coinEmpty;
} else {
return it->second.coin;
}
}
bool CCoinsViewCache::HaveCoin(const OutputIndex& index) const {
if (index.type() == typeid(mw::Hash)) {
const mw::Hash& output_id = boost::get<mw::Hash>(index);
if (GetMWEBCacheView()->HasCoinInCache(output_id)) {
return true;
}
if (GetMWEBCacheView()->HasSpendInCache(output_id)) {
return false;
}
return base->HaveCoin(index);
} else {
CCoinsMap::const_iterator it = FetchCoin(boost::get<COutPoint>(index));
return (it != cacheCoins.end() && !it->second.coin.IsSpent());
}
}
bool CCoinsViewCache::GetMWEBCoin(const mw::Hash& output_id, Output& coin) const {
if (GetMWEBCacheView()->HasCoinInCache(output_id)) {
std::vector<UTXO::CPtr> utxos = GetMWEBCacheView()->GetUTXOs(output_id);
assert(!utxos.empty());
coin = utxos.front()->GetOutput();
return true;
}
if (GetMWEBCacheView()->HasSpendInCache(output_id)) {
return false;
}
return base->GetMWEBCoin(output_id, coin);
}
bool CCoinsViewCache::HaveCoinInCache(const OutputIndex& index) const {
if (index.type() == typeid(COutPoint)) {
CCoinsMap::const_iterator it = cacheCoins.find(boost::get<COutPoint>(index));
return (it != cacheCoins.end() && !it->second.coin.IsSpent());
}
return false;
}
uint256 CCoinsViewCache::GetBestBlock() const {
if (hashBlock.IsNull())
hashBlock = base->GetBestBlock();
return hashBlock;
}
void CCoinsViewCache::SetBackend(CCoinsView& viewIn) {
base = &viewIn;
mweb_view = viewIn.GetMWEBView() ? std::make_shared<mw::CoinsViewCache>(viewIn.GetMWEBView()) : nullptr;
}
void CCoinsViewCache::SetBestBlock(const uint256 &hashBlockIn) {
hashBlock = hashBlockIn;
}
bool CCoinsViewCache::BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlockIn, const mw::CoinsViewCache::Ptr& derivedView) {
for (CCoinsMap::iterator it = mapCoins.begin(); it != mapCoins.end(); it = mapCoins.erase(it)) {
// Ignore non-dirty entries (optimization).
if (!(it->second.flags & CCoinsCacheEntry::DIRTY)) {
continue;
}
CCoinsMap::iterator itUs = cacheCoins.find(it->first);
if (itUs == cacheCoins.end()) {
// The parent cache does not have an entry, while the child cache does.
// We can ignore it if it's both spent and FRESH in the child
if (!(it->second.flags & CCoinsCacheEntry::FRESH && it->second.coin.IsSpent())) {
// Create the coin in the parent cache, move the data up
// and mark it as dirty.
CCoinsCacheEntry& entry = cacheCoins[it->first];
entry.coin = std::move(it->second.coin);
cachedCoinsUsage += entry.coin.DynamicMemoryUsage();
entry.flags = CCoinsCacheEntry::DIRTY;
// We can mark it FRESH in the parent if it was FRESH in the child
// Otherwise it might have just been flushed from the parent's cache
// and already exist in the grandparent
if (it->second.flags & CCoinsCacheEntry::FRESH) {
entry.flags |= CCoinsCacheEntry::FRESH;
}
}
} else {
// Found the entry in the parent cache
if ((it->second.flags & CCoinsCacheEntry::FRESH) && !itUs->second.coin.IsSpent()) {
// The coin was marked FRESH in the child cache, but the coin
// exists in the parent cache. If this ever happens, it means
// the FRESH flag was misapplied and there is a logic error in
// the calling code.
throw std::logic_error("FRESH flag misapplied to coin that exists in parent cache");
}
if ((itUs->second.flags & CCoinsCacheEntry::FRESH) && it->second.coin.IsSpent()) {
// The grandparent cache does not have an entry, and the coin
// has been spent. We can just delete it from the parent cache.
cachedCoinsUsage -= itUs->second.coin.DynamicMemoryUsage();
cacheCoins.erase(itUs);
} else {
// A normal modification.
cachedCoinsUsage -= itUs->second.coin.DynamicMemoryUsage();
itUs->second.coin = std::move(it->second.coin);
cachedCoinsUsage += itUs->second.coin.DynamicMemoryUsage();
itUs->second.flags |= CCoinsCacheEntry::DIRTY;
// NOTE: It isn't safe to mark the coin as FRESH in the parent
// cache. If it already existed and was spent in the parent
// cache then marking it FRESH would prevent that spentness
// from being flushed to the grandparent.
}
}
}
// MWEB: Flushes mweb coins
derivedView->Flush(nullptr);
hashBlock = hashBlockIn;
return true;
}
bool CCoinsViewCache::Flush() {
bool fOk = base->BatchWrite(cacheCoins, hashBlock, mweb_view);
cacheCoins.clear();
cachedCoinsUsage = 0;
return fOk;
}
void CCoinsViewCache::Uncache(const OutputIndex& coin)
{
if (coin.type() == typeid(COutPoint)) {
CCoinsMap::iterator it = cacheCoins.find(boost::get<COutPoint>(coin));
if (it != cacheCoins.end() && it->second.flags == 0) {
cachedCoinsUsage -= it->second.coin.DynamicMemoryUsage();
cacheCoins.erase(it);
}
}
}
unsigned int CCoinsViewCache::GetCacheSize() const {
return cacheCoins.size();
}
bool CCoinsViewCache::HaveInputs(const CTransaction& tx) const
{
if (!tx.IsCoinBase()) {
for (const CTxInput& input : tx.GetInputs()) {
if (!HaveCoin(input.GetIndex())) {
return false;
}
}
}
return true;
}
void CCoinsViewCache::ReallocateCache()
{
// Cache should be empty when we're calling this.
assert(cacheCoins.size() == 0);
cacheCoins.~CCoinsMap();
::new (&cacheCoins) CCoinsMap();
}
static const size_t MIN_TRANSACTION_OUTPUT_WEIGHT = WITNESS_SCALE_FACTOR * ::GetSerializeSize(CTxOut(), PROTOCOL_VERSION);
static const size_t MAX_OUTPUTS_PER_BLOCK = MAX_BLOCK_WEIGHT / MIN_TRANSACTION_OUTPUT_WEIGHT;
const Coin& AccessByTxid(const CCoinsViewCache& view, const uint256& txid)
{
COutPoint iter(txid, 0);
while (iter.n < MAX_OUTPUTS_PER_BLOCK) {
const Coin& alternate = view.AccessCoin(iter);
if (!alternate.IsSpent()) return alternate;
++iter.n;
}
return coinEmpty;
}
bool CCoinsViewErrorCatcher::GetCoin(const COutPoint &outpoint, Coin &coin) const {
try {
return CCoinsViewBacked::GetCoin(outpoint, coin);
} catch(const std::runtime_error& e) {
for (auto f : m_err_callbacks) {
f();
}
LogPrintf("Error reading from database: %s\n", e.what());
// Starting the shutdown sequence and returning false to the caller would be
// interpreted as 'entry not found' (as opposed to unable to read data), and
// could lead to invalid interpretation. Just exit immediately, as we can't
// continue anyway, and all writes should be atomic.
std::abort();
}
}
<commit_msg>Build fix<commit_after>// Copyright (c) 2012-2019 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <coins.h>
#include <consensus/consensus.h>
#include <logging.h>
#include <random.h>
#include <version.h>
bool CCoinsView::GetCoin(const COutPoint &outpoint, Coin &coin) const { return false; }
uint256 CCoinsView::GetBestBlock() const { return uint256(); }
std::vector<uint256> CCoinsView::GetHeadBlocks() const { return std::vector<uint256>(); }
bool CCoinsView::BatchWrite(CCoinsMap& mapCoins, const uint256& hashBlock, const mw::CoinsViewCache::Ptr& derivedView) { return false; }
CCoinsViewCursor *CCoinsView::Cursor() const { return nullptr; }
bool CCoinsView::HaveCoin(const OutputIndex& index) const
{
if (index.type() == typeid(mw::Hash)) {
if (!GetMWEBView()) return false;
return GetMWEBView()->HasCoin(boost::get<mw::Hash>(index));
} else {
Coin coin;
return GetCoin(boost::get<COutPoint>(index), coin);
}
}
CCoinsViewBacked::CCoinsViewBacked(CCoinsView *viewIn) : base(viewIn) { }
bool CCoinsViewBacked::GetCoin(const COutPoint &outpoint, Coin &coin) const { return base->GetCoin(outpoint, coin); }
bool CCoinsViewBacked::HaveCoin(const OutputIndex& index) const { return base->HaveCoin(index); }
uint256 CCoinsViewBacked::GetBestBlock() const { return base->GetBestBlock(); }
std::vector<uint256> CCoinsViewBacked::GetHeadBlocks() const { return base->GetHeadBlocks(); }
void CCoinsViewBacked::SetBackend(CCoinsView& viewIn) { base = &viewIn; }
bool CCoinsViewBacked::BatchWrite(CCoinsMap& mapCoins, const uint256& hashBlock, const mw::CoinsViewCache::Ptr& derivedView) { return base->BatchWrite(mapCoins, hashBlock, derivedView); }
CCoinsViewCursor *CCoinsViewBacked::Cursor() const { return base->Cursor(); }
size_t CCoinsViewBacked::EstimateSize() const { return base->EstimateSize(); }
mw::ICoinsView::Ptr CCoinsViewBacked::GetMWEBView() const { return base->GetMWEBView(); }
bool CCoinsViewBacked::GetMWEBCoin(const mw::Hash& output_id, Output& coin) const { return base->GetMWEBCoin(output_id, coin); }
SaltedOutpointHasher::SaltedOutpointHasher() : k0(GetRand(std::numeric_limits<uint64_t>::max())), k1(GetRand(std::numeric_limits<uint64_t>::max())) {}
CCoinsViewCache::CCoinsViewCache(CCoinsView* baseIn) : CCoinsViewBacked(baseIn), cachedCoinsUsage(0), mweb_view(baseIn->GetMWEBView() ? std::make_shared<mw::CoinsViewCache>(baseIn->GetMWEBView()) : nullptr) {}
size_t CCoinsViewCache::DynamicMemoryUsage() const {
return memusage::DynamicUsage(cacheCoins) + cachedCoinsUsage;
}
CCoinsMap::iterator CCoinsViewCache::FetchCoin(const COutPoint &outpoint) const {
CCoinsMap::iterator it = cacheCoins.find(outpoint);
if (it != cacheCoins.end())
return it;
Coin tmp;
if (!base->GetCoin(outpoint, tmp))
return cacheCoins.end();
CCoinsMap::iterator ret = cacheCoins.emplace(std::piecewise_construct, std::forward_as_tuple(outpoint), std::forward_as_tuple(std::move(tmp))).first;
if (ret->second.coin.IsSpent()) {
// The parent only has an empty entry for this outpoint; we can consider our
// version as fresh.
ret->second.flags = CCoinsCacheEntry::FRESH;
}
cachedCoinsUsage += ret->second.coin.DynamicMemoryUsage();
return ret;
}
bool CCoinsViewCache::GetCoin(const COutPoint &outpoint, Coin &coin) const {
CCoinsMap::const_iterator it = FetchCoin(outpoint);
if (it != cacheCoins.end()) {
coin = it->second.coin;
return !coin.IsSpent();
}
return false;
}
void CCoinsViewCache::AddCoin(const COutPoint &outpoint, Coin&& coin, bool possible_overwrite) {
assert(!coin.IsSpent());
if (coin.out.scriptPubKey.IsUnspendable()) return;
CCoinsMap::iterator it;
bool inserted;
std::tie(it, inserted) = cacheCoins.emplace(std::piecewise_construct, std::forward_as_tuple(outpoint), std::tuple<>());
bool fresh = false;
if (!inserted) {
cachedCoinsUsage -= it->second.coin.DynamicMemoryUsage();
}
if (!possible_overwrite) {
if (!it->second.coin.IsSpent()) {
throw std::logic_error("Attempted to overwrite an unspent coin (when possible_overwrite is false)");
}
// If the coin exists in this cache as a spent coin and is DIRTY, then
// its spentness hasn't been flushed to the parent cache. We're
// re-adding the coin to this cache now but we can't mark it as FRESH.
// If we mark it FRESH and then spend it before the cache is flushed
// we would remove it from this cache and would never flush spentness
// to the parent cache.
//
// Re-adding a spent coin can happen in the case of a re-org (the coin
// is 'spent' when the block adding it is disconnected and then
// re-added when it is also added in a newly connected block).
//
// If the coin doesn't exist in the current cache, or is spent but not
// DIRTY, then it can be marked FRESH.
fresh = !(it->second.flags & CCoinsCacheEntry::DIRTY);
}
it->second.coin = std::move(coin);
it->second.flags |= CCoinsCacheEntry::DIRTY | (fresh ? CCoinsCacheEntry::FRESH : 0);
cachedCoinsUsage += it->second.coin.DynamicMemoryUsage();
}
void AddCoins(CCoinsViewCache& cache, const CTransaction &tx, int nHeight, bool check_for_overwrite) {
bool fCoinbase = tx.IsCoinBase();
const uint256& txid = tx.GetHash();
for (size_t i = 0; i < tx.vout.size(); ++i) {
// MWEB: The first output in the HogEx transaction is the HogAddr.
// The HogAddr is always spent in the next HogEx, so should not be subjected to pegout maturity rules.
bool fPegout = tx.IsHogEx() && i > 0;
bool overwrite = check_for_overwrite ? cache.HaveCoin(COutPoint(txid, i)) : fCoinbase;
// Coinbase transactions can always be overwritten, in order to correctly
// deal with the pre-BIP30 occurrences of duplicate coinbase transactions.
cache.AddCoin(COutPoint(txid, i), Coin(tx.vout[i], nHeight, fCoinbase, fPegout), overwrite);
}
}
bool CCoinsViewCache::SpendCoin(const COutPoint &outpoint, Coin* moveout) {
CCoinsMap::iterator it = FetchCoin(outpoint);
if (it == cacheCoins.end()) return false;
cachedCoinsUsage -= it->second.coin.DynamicMemoryUsage();
if (moveout) {
*moveout = std::move(it->second.coin);
}
if (it->second.flags & CCoinsCacheEntry::FRESH) {
cacheCoins.erase(it);
} else {
it->second.flags |= CCoinsCacheEntry::DIRTY;
it->second.coin.Clear();
}
return true;
}
static const Coin coinEmpty;
const Coin& CCoinsViewCache::AccessCoin(const COutPoint &outpoint) const {
CCoinsMap::const_iterator it = FetchCoin(outpoint);
if (it == cacheCoins.end()) {
return coinEmpty;
} else {
return it->second.coin;
}
}
bool CCoinsViewCache::HaveCoin(const OutputIndex& index) const {
if (index.type() == typeid(mw::Hash)) {
const mw::Hash& output_id = boost::get<mw::Hash>(index);
if (GetMWEBCacheView()->HasCoinInCache(output_id)) {
return true;
}
if (GetMWEBCacheView()->HasSpendInCache(output_id)) {
return false;
}
return base->HaveCoin(index);
} else {
CCoinsMap::const_iterator it = FetchCoin(boost::get<COutPoint>(index));
return (it != cacheCoins.end() && !it->second.coin.IsSpent());
}
}
bool CCoinsViewCache::GetMWEBCoin(const mw::Hash& output_id, Output& coin) const {
if (GetMWEBCacheView()->HasCoinInCache(output_id)) {
UTXO::CPtr utxo = GetMWEBCacheView()->GetUTXO(output_id);
assert(utxo != nullptr);
coin = utxo->GetOutput();
return true;
}
if (GetMWEBCacheView()->HasSpendInCache(output_id)) {
return false;
}
return base->GetMWEBCoin(output_id, coin);
}
bool CCoinsViewCache::HaveCoinInCache(const OutputIndex& index) const {
if (index.type() == typeid(COutPoint)) {
CCoinsMap::const_iterator it = cacheCoins.find(boost::get<COutPoint>(index));
return (it != cacheCoins.end() && !it->second.coin.IsSpent());
}
return false;
}
uint256 CCoinsViewCache::GetBestBlock() const {
if (hashBlock.IsNull())
hashBlock = base->GetBestBlock();
return hashBlock;
}
void CCoinsViewCache::SetBackend(CCoinsView& viewIn) {
base = &viewIn;
mweb_view = viewIn.GetMWEBView() ? std::make_shared<mw::CoinsViewCache>(viewIn.GetMWEBView()) : nullptr;
}
void CCoinsViewCache::SetBestBlock(const uint256 &hashBlockIn) {
hashBlock = hashBlockIn;
}
bool CCoinsViewCache::BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlockIn, const mw::CoinsViewCache::Ptr& derivedView) {
for (CCoinsMap::iterator it = mapCoins.begin(); it != mapCoins.end(); it = mapCoins.erase(it)) {
// Ignore non-dirty entries (optimization).
if (!(it->second.flags & CCoinsCacheEntry::DIRTY)) {
continue;
}
CCoinsMap::iterator itUs = cacheCoins.find(it->first);
if (itUs == cacheCoins.end()) {
// The parent cache does not have an entry, while the child cache does.
// We can ignore it if it's both spent and FRESH in the child
if (!(it->second.flags & CCoinsCacheEntry::FRESH && it->second.coin.IsSpent())) {
// Create the coin in the parent cache, move the data up
// and mark it as dirty.
CCoinsCacheEntry& entry = cacheCoins[it->first];
entry.coin = std::move(it->second.coin);
cachedCoinsUsage += entry.coin.DynamicMemoryUsage();
entry.flags = CCoinsCacheEntry::DIRTY;
// We can mark it FRESH in the parent if it was FRESH in the child
// Otherwise it might have just been flushed from the parent's cache
// and already exist in the grandparent
if (it->second.flags & CCoinsCacheEntry::FRESH) {
entry.flags |= CCoinsCacheEntry::FRESH;
}
}
} else {
// Found the entry in the parent cache
if ((it->second.flags & CCoinsCacheEntry::FRESH) && !itUs->second.coin.IsSpent()) {
// The coin was marked FRESH in the child cache, but the coin
// exists in the parent cache. If this ever happens, it means
// the FRESH flag was misapplied and there is a logic error in
// the calling code.
throw std::logic_error("FRESH flag misapplied to coin that exists in parent cache");
}
if ((itUs->second.flags & CCoinsCacheEntry::FRESH) && it->second.coin.IsSpent()) {
// The grandparent cache does not have an entry, and the coin
// has been spent. We can just delete it from the parent cache.
cachedCoinsUsage -= itUs->second.coin.DynamicMemoryUsage();
cacheCoins.erase(itUs);
} else {
// A normal modification.
cachedCoinsUsage -= itUs->second.coin.DynamicMemoryUsage();
itUs->second.coin = std::move(it->second.coin);
cachedCoinsUsage += itUs->second.coin.DynamicMemoryUsage();
itUs->second.flags |= CCoinsCacheEntry::DIRTY;
// NOTE: It isn't safe to mark the coin as FRESH in the parent
// cache. If it already existed and was spent in the parent
// cache then marking it FRESH would prevent that spentness
// from being flushed to the grandparent.
}
}
}
// MWEB: Flushes mweb coins
derivedView->Flush(nullptr);
hashBlock = hashBlockIn;
return true;
}
bool CCoinsViewCache::Flush() {
bool fOk = base->BatchWrite(cacheCoins, hashBlock, mweb_view);
cacheCoins.clear();
cachedCoinsUsage = 0;
return fOk;
}
void CCoinsViewCache::Uncache(const OutputIndex& coin)
{
if (coin.type() == typeid(COutPoint)) {
CCoinsMap::iterator it = cacheCoins.find(boost::get<COutPoint>(coin));
if (it != cacheCoins.end() && it->second.flags == 0) {
cachedCoinsUsage -= it->second.coin.DynamicMemoryUsage();
cacheCoins.erase(it);
}
}
}
unsigned int CCoinsViewCache::GetCacheSize() const {
return cacheCoins.size();
}
bool CCoinsViewCache::HaveInputs(const CTransaction& tx) const
{
if (!tx.IsCoinBase()) {
for (const CTxInput& input : tx.GetInputs()) {
if (!HaveCoin(input.GetIndex())) {
return false;
}
}
}
return true;
}
void CCoinsViewCache::ReallocateCache()
{
// Cache should be empty when we're calling this.
assert(cacheCoins.size() == 0);
cacheCoins.~CCoinsMap();
::new (&cacheCoins) CCoinsMap();
}
static const size_t MIN_TRANSACTION_OUTPUT_WEIGHT = WITNESS_SCALE_FACTOR * ::GetSerializeSize(CTxOut(), PROTOCOL_VERSION);
static const size_t MAX_OUTPUTS_PER_BLOCK = MAX_BLOCK_WEIGHT / MIN_TRANSACTION_OUTPUT_WEIGHT;
const Coin& AccessByTxid(const CCoinsViewCache& view, const uint256& txid)
{
COutPoint iter(txid, 0);
while (iter.n < MAX_OUTPUTS_PER_BLOCK) {
const Coin& alternate = view.AccessCoin(iter);
if (!alternate.IsSpent()) return alternate;
++iter.n;
}
return coinEmpty;
}
bool CCoinsViewErrorCatcher::GetCoin(const COutPoint &outpoint, Coin &coin) const {
try {
return CCoinsViewBacked::GetCoin(outpoint, coin);
} catch(const std::runtime_error& e) {
for (auto f : m_err_callbacks) {
f();
}
LogPrintf("Error reading from database: %s\n", e.what());
// Starting the shutdown sequence and returning false to the caller would be
// interpreted as 'entry not found' (as opposed to unable to read data), and
// could lead to invalid interpretation. Just exit immediately, as we can't
// continue anyway, and all writes should be atomic.
std::abort();
}
}
<|endoftext|> |
<commit_before>/** @file
*****************************************************************************
Implementation of a Merkle tree based set commitment scheme.
*****************************************************************************
* @author This file is part of libsnark, developed by SCIPR Lab
* and contributors (see AUTHORS).
* @copyright MIT license (see LICENSE file)
*****************************************************************************/
#ifndef SET_COMMITMENT_TCC_
#define SET_COMMITMENT_TCC_
namespace libsnark {
template<typename HashT>
set_commitment_accumulator<HashT>::set_commitment_accumulator(const size_t max_entries, const size_t value_size) :
value_size(value_size)
{
depth = log2(max_entries);
digest_size = HashT::get_digest_len();
HashT::sample_randomness(2*digest_size);
tree.reset(new merkle_tree<HashT>(depth, digest_size));
}
template<typename HashT>
void set_commitment_accumulator<HashT>::add(const bit_vector &value)
{
assert(value_size == 0 || value.size() == value_size);
const bit_vector hash = HashT::get_hash(value);
if (hash_to_pos.find(hash) == hash_to_pos.end())
{
const size_t pos = hash_to_pos.size();
tree->set_value(pos, hash);
hash_to_pos[hash] = pos;
}
}
template<typename HashT>
bool set_commitment_accumulator<HashT>::is_in_set(const bit_vector &value) const
{
assert(value_size == 0 || value.size() == value_size);
const bit_vector hash = HashT::get_hash(value);
return (hash_to_pos.find(hash) != hash_to_pos.end());
}
template<typename HashT>
set_commitment set_commitment_accumulator<HashT>::get_commitment() const
{
return tree->get_root();
}
template<typename HashT>
set_membership_proof set_commitment_accumulator<HashT>::get_membership_proof(const bit_vector &value) const
{
const bit_vector hash = HashT::get_hash(value);
auto it = hash_to_pos.find(hash);
assert(it != hash_to_pos.end());
set_membership_proof proof;
proof.address = it->second;
proof.merkle_path = tree->get_path(it->second);
return proof;
}
} // libsnark
#endif // SET_COMMITMENT_TCC_
<commit_msg>Remove knapsack-specific initialization from set commitment accumulator.<commit_after>/** @file
*****************************************************************************
Implementation of a Merkle tree based set commitment scheme.
*****************************************************************************
* @author This file is part of libsnark, developed by SCIPR Lab
* and contributors (see AUTHORS).
* @copyright MIT license (see LICENSE file)
*****************************************************************************/
#ifndef SET_COMMITMENT_TCC_
#define SET_COMMITMENT_TCC_
namespace libsnark {
template<typename HashT>
set_commitment_accumulator<HashT>::set_commitment_accumulator(const size_t max_entries, const size_t value_size) :
value_size(value_size)
{
depth = log2(max_entries);
digest_size = HashT::get_digest_len();
tree.reset(new merkle_tree<HashT>(depth, digest_size));
}
template<typename HashT>
void set_commitment_accumulator<HashT>::add(const bit_vector &value)
{
assert(value_size == 0 || value.size() == value_size);
const bit_vector hash = HashT::get_hash(value);
if (hash_to_pos.find(hash) == hash_to_pos.end())
{
const size_t pos = hash_to_pos.size();
tree->set_value(pos, hash);
hash_to_pos[hash] = pos;
}
}
template<typename HashT>
bool set_commitment_accumulator<HashT>::is_in_set(const bit_vector &value) const
{
assert(value_size == 0 || value.size() == value_size);
const bit_vector hash = HashT::get_hash(value);
return (hash_to_pos.find(hash) != hash_to_pos.end());
}
template<typename HashT>
set_commitment set_commitment_accumulator<HashT>::get_commitment() const
{
return tree->get_root();
}
template<typename HashT>
set_membership_proof set_commitment_accumulator<HashT>::get_membership_proof(const bit_vector &value) const
{
const bit_vector hash = HashT::get_hash(value);
auto it = hash_to_pos.find(hash);
assert(it != hash_to_pos.end());
set_membership_proof proof;
proof.address = it->second;
proof.merkle_path = tree->get_path(it->second);
return proof;
}
} // libsnark
#endif // SET_COMMITMENT_TCC_
<|endoftext|> |
<commit_before>#include "../search/search.hpp"
#include "../utils/pool.hpp"
template <class D> struct Speediest : public SearchAlgorithm<D> {
typedef typename D::State State;
typedef typename D::PackedState PackedState;
typedef typename D::Cost Cost;
typedef typename D::Oper Oper;
struct Node : SearchNode<D> {
Cost d;
float sortval;
unsigned long depth;
static bool pred(Node *a, Node *b) {
if (a->sortval == b->sortval) {
if (a->d == b->d)
return a->g > b->g;
return a->d < b->d;
}
return a->sortval < b->sortval;
}
static typename D::Cost prio(Node *n) { return n->sortval; }
static typename D::Cost tieprio(Node *n) { return n->g; }
};
Speediest(int argc, const char *argv[]) :
SearchAlgorithm<D>(argc, argv), closed(30000001) {
nodes = new Pool<Node>();
}
~Speediest() {
delete nodes;
}
void search(D &d, typename D::State &s0) {
this->start();
closed.init(d);
Node *n0 = init(d, s0);
closed.add(n0);
open.push(n0);
while (!open.empty() && !SearchAlgorithm<D>::limit()) {
Node *n = open.pop();
State buf, &state = d.unpack(buf, n->packed);
if (d.isgoal(state)) {
SearchAlgorithm<D>::res.goal(d, n);
break;
}
expand(d, n, state);
}
this->finish();
}
virtual void reset() {
SearchAlgorithm<D>::reset();
open.clear();
closed.clear();
delete nodes;
nodes = new Pool<Node>();
}
virtual void output(FILE *out) {
SearchAlgorithm<D>::output(out);
closed.prstats(stdout, "closed ");
dfpair(stdout, "open list type", "%s", open.kind());
dfpair(stdout, "node size", "%u", sizeof(Node));
}
private:
void expand(D &d, Node *n, State &state) {
SearchAlgorithm<D>::res.expd++;
typename D::Operators ops(d, state);
for (unsigned int i = 0; i < ops.size(); i++) {
if (ops[i] == n->pop)
continue;
SearchAlgorithm<D>::res.gend++;
considerkid(d, n, state, ops[i]);
}
}
void considerkid(D &d, Node *parent, State &state, Oper op) {
Node *kid = nodes->construct();
typename D::Edge e(d, state, op);
d.pack(kid->packed, e.state);
unsigned long hash = d.hash(kid->packed);
SearchNode<D> *dup = closed.find(kid->packed, hash);
if (dup) {
this->res.dups++;
nodes->destruct(kid);
} else {
kid->g = parent->g + e.cost;
kid->depth = parent->depth + 1;
kid->d = d.d(e.state);
kid->sortval = kid->d / (kid->d + kid->depth);
kid->update(kid->g, parent, op, e.revop);
closed.add(kid, hash);
open.push(kid);
}
}
Node *init(D &d, State &s0) {
Node *n0 = nodes->construct();
d.pack(n0->packed, s0);
n0->g = Cost(0);
n0->d = d.d(s0);
n0->sortval = 1;
n0->depth = 0;
n0->op = n0->pop = D::Nop;
n0->parent = NULL;
return n0;
}
OpenList<Node, Node, Cost> open;
ClosedList<SearchNode<D>, SearchNode<D>, D> closed;
Pool<Node> *nodes;
};
<commit_msg>Use a binary heap for the speediest open list. The values are not sorted on the domain's Cost, they are sorted on the floating point sort value.<commit_after>#include "../search/search.hpp"
#include "../utils/pool.hpp"
template <class D> struct Speediest : public SearchAlgorithm<D> {
typedef typename D::State State;
typedef typename D::PackedState PackedState;
typedef typename D::Cost Cost;
typedef typename D::Oper Oper;
struct Node : SearchNode<D> {
Cost d;
float sortval;
unsigned long depth;
static bool pred(Node *a, Node *b) {
if (a->sortval == b->sortval) {
if (a->d == b->d)
return a->g > b->g;
return a->d < b->d;
}
return a->sortval < b->sortval;
}
static typename D::Cost prio(Node *n) { return n->sortval; }
static typename D::Cost tieprio(Node *n) { return n->g; }
};
Speediest(int argc, const char *argv[]) :
SearchAlgorithm<D>(argc, argv), closed(30000001) {
nodes = new Pool<Node>();
}
~Speediest() {
delete nodes;
}
void search(D &d, typename D::State &s0) {
this->start();
closed.init(d);
Node *n0 = init(d, s0);
closed.add(n0);
open.push(n0);
while (!open.empty() && !SearchAlgorithm<D>::limit()) {
Node *n = *open.pop();
State buf, &state = d.unpack(buf, n->packed);
if (d.isgoal(state)) {
SearchAlgorithm<D>::res.goal(d, n);
break;
}
expand(d, n, state);
}
this->finish();
}
virtual void reset() {
SearchAlgorithm<D>::reset();
open.clear();
closed.clear();
delete nodes;
nodes = new Pool<Node>();
}
virtual void output(FILE *out) {
SearchAlgorithm<D>::output(out);
closed.prstats(stdout, "closed ");
dfpair(stdout, "open list type", "binheap");
dfpair(stdout, "node size", "%u", sizeof(Node));
}
private:
void expand(D &d, Node *n, State &state) {
SearchAlgorithm<D>::res.expd++;
typename D::Operators ops(d, state);
for (unsigned int i = 0; i < ops.size(); i++) {
if (ops[i] == n->pop)
continue;
SearchAlgorithm<D>::res.gend++;
considerkid(d, n, state, ops[i]);
}
}
void considerkid(D &d, Node *parent, State &state, Oper op) {
Node *kid = nodes->construct();
typename D::Edge e(d, state, op);
d.pack(kid->packed, e.state);
unsigned long hash = d.hash(kid->packed);
SearchNode<D> *dup = closed.find(kid->packed, hash);
if (dup) {
this->res.dups++;
nodes->destruct(kid);
} else {
kid->g = parent->g + e.cost;
kid->depth = parent->depth + 1;
kid->d = d.d(e.state);
kid->sortval = kid->d / (kid->d + kid->depth);
kid->update(kid->g, parent, op, e.revop);
closed.add(kid, hash);
open.push(kid);
}
}
Node *init(D &d, State &s0) {
Node *n0 = nodes->construct();
d.pack(n0->packed, s0);
n0->g = Cost(0);
n0->d = d.d(s0);
n0->sortval = 1;
n0->depth = 0;
n0->op = n0->pop = D::Nop;
n0->parent = NULL;
return n0;
}
BinHeap<Node, Node*> open;
ClosedList<SearchNode<D>, SearchNode<D>, D> closed;
Pool<Node> *nodes;
};
<|endoftext|> |
<commit_before>// Licensed under the Apache License, Version 2.0.
// Author: Jin Qing (http://blog.csdn.net/jq0123)
#include "server_method_call_cqtag.h"
#include <grpc_cb/service.h> // for Service
#include <grpc_cb/impl/call.h> // for Call
#include <grpc_cb/impl/cqueue_for_next.h> // for c_cq()
namespace grpc_cb {
ServerMethodCallCqTag::ServerMethodCallCqTag(grpc_server* server,
Service* service,
size_t method_index,
void* registered_method,
const CQueueForNextSptr& cq4n_sptr)
: server_(server),
service_(service),
method_index_(method_index),
registered_method_(registered_method),
cq4n_sptr_(cq4n_sptr),
call_ptr_(nullptr),
deadline_(gpr_inf_future(GPR_CLOCK_REALTIME)),
payload_ptr_(nullptr) {
assert(server);
assert(registered_method);
assert(cq4n_sptr);
assert(method_index < service->GetMethodCount());
memset(&initial_metadata_array_, 0, sizeof(initial_metadata_array_));
grpc_completion_queue* ccq = &cq4n_sptr->c_cq();
grpc_byte_buffer **optional_payload =
service->IsMethodClientStreaming(method_index) ?
nullptr : &payload_ptr_;
grpc_call_error ret = grpc_server_request_registered_call(
server, registered_method, &call_ptr_, &deadline_,
&initial_metadata_array_, optional_payload, ccq, ccq, this);
assert(GRPC_CALL_OK == ret);
}
ServerMethodCallCqTag::~ServerMethodCallCqTag() {
grpc_metadata_array_destroy(&initial_metadata_array_);
}
void ServerMethodCallCqTag::DoComplete(bool success)
{
if (success) {
// Deal payload.
assert(service_);
assert(call_ptr_);
CallSptr call_sptr(new Call(call_ptr_)); // destroys grpc_call
service_->CallMethod(method_index_, payload_ptr_, call_sptr);
}
// Request the next method call.
// Calls grpc_server_request_registered_call() in ctr().
// Delete in Server::Run().
new ServerMethodCallCqTag(server_, service_, method_index_,
registered_method_, cq4n_sptr_);
}
} // namespace grpc_cb
<commit_msg>grpc_byte_buffer_destroy(payload_ptr_)<commit_after>// Licensed under the Apache License, Version 2.0.
// Author: Jin Qing (http://blog.csdn.net/jq0123)
#include "server_method_call_cqtag.h"
#include <grpc_cb/service.h> // for Service
#include <grpc_cb/impl/call.h> // for Call
#include <grpc_cb/impl/cqueue_for_next.h> // for c_cq()
namespace grpc_cb {
ServerMethodCallCqTag::ServerMethodCallCqTag(grpc_server* server,
Service* service,
size_t method_index,
void* registered_method,
const CQueueForNextSptr& cq4n_sptr)
: server_(server),
service_(service),
method_index_(method_index),
registered_method_(registered_method),
cq4n_sptr_(cq4n_sptr),
call_ptr_(nullptr),
deadline_(gpr_inf_future(GPR_CLOCK_REALTIME)),
payload_ptr_(nullptr) {
assert(server);
assert(registered_method);
assert(cq4n_sptr);
assert(method_index < service->GetMethodCount());
memset(&initial_metadata_array_, 0, sizeof(initial_metadata_array_));
grpc_completion_queue* ccq = &cq4n_sptr->c_cq();
grpc_byte_buffer **optional_payload =
service->IsMethodClientStreaming(method_index) ?
nullptr : &payload_ptr_;
grpc_call_error ret = grpc_server_request_registered_call(
server, registered_method, &call_ptr_, &deadline_,
&initial_metadata_array_, optional_payload, ccq, ccq, this);
assert(GRPC_CALL_OK == ret);
}
ServerMethodCallCqTag::~ServerMethodCallCqTag() {
grpc_metadata_array_destroy(&initial_metadata_array_);
grpc_byte_buffer_destroy(payload_ptr_);
}
void ServerMethodCallCqTag::DoComplete(bool success)
{
if (success) {
// Deal payload.
assert(service_);
assert(call_ptr_);
CallSptr call_sptr(new Call(call_ptr_)); // destroys grpc_call
service_->CallMethod(method_index_, payload_ptr_, call_sptr);
}
// Request the next method call.
// Calls grpc_server_request_registered_call() in ctr().
// Delete in Server::Run().
new ServerMethodCallCqTag(server_, service_, method_index_,
registered_method_, cq4n_sptr_);
}
} // namespace grpc_cb
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2014-2016, imec
* All rights reserved.
*/
#include "error.h"
#include "bpmf.h"
#include <random>
#include <memory>
#include <cstdio>
#include <iostream>
#include <climits>
#include <stdexcept>
typedef Eigen::PermutationMatrix<Eigen::Dynamic, Eigen::Dynamic> PermMatrix;
void Sys::permuteCols(const PermMatrix &perm, Sys &other)
{
// permute local matrices
T = T * perm;
Pavg = Pavg * perm;
Pm2 = Pm2 * perm;
M = M * perm;
propMu * perm;
propLambda * perm;
// permute other matrices
other.T = T.transpose();
other.Pavg = Pavg.transpose();
other.Pm2 = Pm2.transpose();
other.M = M.transpose();
}
//
// Distributes users/movies accros several nodes
// takes into account load balance and communication cost
//
void Sys::assign(Sys &other)
{
if (nprocs == 1) {
dom[0] = 0;
dom[1] = num();
return;
}
if (!permute) {
int p = num() / nprocs;
int i=0; for(; i<nprocs; ++i) dom[i] = i*p;
dom[i] = num();
return;
}
std::vector<std::vector<double>> comm_cost(num());
if (other.assigned) {
// comm_cost[i][j] == communication cost if item i is assigned to processor j
for(int i=0; i<num(); ++i) {
std::vector<unsigned> comm_per_proc(nprocs);
const int count = M.innerVector(i).nonZeros();
for (SparseMatrixD::InnerIterator it(M,i); it; ++it) comm_per_proc.at(other.proc(it.row()))++;
for(int j=0; j<nprocs; j++) comm_cost.at(i).push_back(count - comm_per_proc.at(j));
}
}
std::vector<unsigned> nnz_per_proc(nprocs);
std::vector<unsigned> items_per_proc(nprocs);
std::vector<double> work_per_proc(nprocs);
std::vector<int> item_to_proc(num(), -1);
unsigned total_nnz = 1;
unsigned total_items = 1;
double total_work = 0.01;
unsigned total_comm = 0;
// computes best node to assign movie/user idx
auto best = [&](int idx, double r1, double r2) {
double min_cost = 1e9;
int best_proc = -1;
for(int i=0; i<nprocs; ++i) {
//double nnz_unbalance = (double)nnz_per_proc[i] / total_nnz;
//double items_unbalance = (double)items_per_proc[i] / total_items;
//double work_unbalance = std::max(nnz_unbalance, items_unbalance);
double work_unbalance = work_per_proc[i] / total_work;
double comm = other.assigned ? comm_cost.at(idx).at(i) : 0.0;
double total_cost = r1 * work_unbalance + r2 * comm;
if (total_cost > min_cost) continue;
best_proc = i;
min_cost = total_cost;
}
return best_proc;
};
// update cost function when item is assigned to proc
auto assign = [&](int item, int proc) {
const int nnz = M.innerVector(item).nonZeros();
double work = 10.0 + nnz; // one item is as expensive as NZs
item_to_proc[item] = proc;
nnz_per_proc [proc] += nnz;
items_per_proc[proc]++;
work_per_proc [proc] += work;
total_nnz += nnz;
total_items++;
total_work+= work;
total_comm += (other.assigned ? comm_cost.at(item).at(proc) : 0);
};
// update cost function when item is removed from proc
auto unassign = [&](int item) {
int proc = item_to_proc[item];
if (proc < 0) return;
const int nnz = M.innerVector(item).nonZeros();
double work = 7.1 + nnz;
item_to_proc[item] = -1;
nnz_per_proc [proc] -= nnz;
items_per_proc[proc]--;
work_per_proc [proc] -= work;
total_nnz -= nnz;
total_items--;
total_work -= work;
total_comm -= (other.assigned ? comm_cost.at(item).at(proc) : 0);
};
// print cost after iterating once
auto print = [&](int iter) {
Sys::cout() << name << " -- iter " << iter << " -- \n";
if (Sys::procid == 0) {
int max_nnz = *std::max_element(nnz_per_proc.begin(), nnz_per_proc.end());
int min_nnz = *std::min_element(nnz_per_proc.begin(), nnz_per_proc.end());
int avg_nnz = nnz() / nprocs;
int max_items = *std::max_element(items_per_proc.begin(), items_per_proc.end());
int min_items = *std::min_element(items_per_proc.begin(), items_per_proc.end());
int avg_items = num() / nprocs;
double max_work = *std::max_element(work_per_proc.begin(), work_per_proc.end());
double min_work = *std::min_element(work_per_proc.begin(), work_per_proc.end());
double avg_work = total_work / nprocs;
Sys::cout() << name << ": comm cost " << 100.0 * total_comm / nnz() / nprocs << "%\n";
Sys::cout() << name << ": nnz unbalance: " << (int)(100.0 * Sys::nprocs * (max_nnz - min_nnz) / nnz()) << "%"
<< "\t(" << max_nnz << " <-> " << avg_nnz << " <-> " << min_nnz << ")\n";
Sys::cout() << name << ": items unbalance: " << (int)(100.0 * Sys::nprocs * (max_items - min_items) / num()) << "%"
<< "\t(" << max_items << " <-> " << avg_items << " <-> " << min_items << ")\n";
Sys::cout() << name << ": work unbalance: " << (int)(100.0 * Sys::nprocs * (max_work - min_work) / total_work) << "%"
<< "\t(" << max_work << " <-> " << avg_work << " <-> " << min_work << ")\n\n";
}
Sys::cout() << name << ": nnz:\t" << nnz_per_proc[procid] << " / " << nnz() << "\n";
Sys::cout() << name << ": items:\t" << items_per_proc[procid] << " / " << num() << "\n";
Sys::cout() << name << ": work:\t" << work_per_proc[procid] << " / " << total_work << "\n";
};
for(int j=0; j<3; ++j) {
for(int i=0; i<num(); ++i) {
unassign(i);
assign(i, best(i, 10000, 0));
}
print(j);
}
std::vector<std::vector<unsigned>> proc_to_item(nprocs);
for(int i=0; i<num(); ++i) proc_to_item[item_to_proc[i]].push_back(i);
// permute T, P based on assignment done before
unsigned pos = 0;
Eigen::PermutationMatrix<Eigen::Dynamic, Eigen::Dynamic> perm(num());
for(auto p: proc_to_item) for(auto i: p) perm.indices()(pos++) = i;
auto oldT = T;
this->permuteCols(perm, other);
int i = 0;
int n = 0;
dom[0] = 0;
for(auto p : items_per_proc) dom[++i] = (n += p);
#ifndef NDEBUG
int j = 0;
for(auto i : proc_to_item.at(0)) assert(T.col(j++).nonZeros() == oldT.col(i).nonZeros());
#endif
Sys::cout() << name << " domain:" << std::endl;
print_dom(Sys::cout());
Sys::cout() << std::endl;
assigned = true;
}
//
// Update connectivity map (where to send certain items)
// based on assignment to nodes
//
void Sys::update_conn(Sys& other)
{
unsigned tot = 0;
conn_map.clear();
conn_count_map.clear();
assert(nprocs <= (int)max_procs);
conn_map.resize(num());
for (int k=0; k<num(); ++k) {
std::bitset<max_procs> &bm = conn_map[k];
for (SparseMatrixD::InnerIterator it(M,k); it; ++it) bm.set(other.proc(it.row()));
for (SparseMatrixD::InnerIterator it(Pavg,k); it; ++it) bm.set(other.proc(it.row()));
bm.reset(proc(k)); // not to self
tot += bm.count();
// keep track of how may proc to proc sends
auto from_proc = proc(k);
for(int to_proc=0; to_proc<Sys::nprocs; to_proc++) {
if (!bm.test(to_proc)) continue;
conn_count_map[std::make_pair(from_proc, to_proc)]++;
}
}
if (Sys::procid == 0) {
Sys::cout() << name << ": avg items to send per iter: " << tot << " / " << num() << " = " << (double)tot / (double)num() << std::endl;
Sys::cout() << name << ": messages from -> to proc\n";
for(int i=0; i<Sys::nprocs; ++i) Sys::cout() << "\t" << i;
Sys::cout() << "\n";
for(int i=0; i<Sys::nprocs; ++i) {
Sys::cout() << i;
for(int j=0; j<Sys::nprocs; ++j) Sys::cout() << "\t" << conn_count(i,j);
Sys::cout() << "\n";
}
}
}
//
// try to keep items that have to be sent to the same node next to eachothe
//
void Sys::opt_conn(Sys& other)
{
// sort internally according to hamming distance
PermMatrix perm(num());
perm.setIdentity();
std::vector<std::string> s(num());
auto v = perm.indices().data();
#pragma omp parallel for
for (auto p = 0; p < nprocs; ++p)
{
for (int i = from(p); i < to(p); ++i)
{
s[i] = conn(i).to_string();
}
std::sort(v + from(p), v + to(p), [&](const int &a, const int &b) { return (s[a] < s[b]); });
}
permuteCols(perm, other);
}
void Sys::build_conn(Sys& other)
{
if (nprocs == 1) return;
update_conn(other);
//opt_conn(other);
//update_conn(other);
}<commit_msg>FIX: don't permute if no propagate posterior<commit_after>/*
* Copyright (c) 2014-2016, imec
* All rights reserved.
*/
#include "error.h"
#include "bpmf.h"
#include <random>
#include <memory>
#include <cstdio>
#include <iostream>
#include <climits>
#include <stdexcept>
typedef Eigen::PermutationMatrix<Eigen::Dynamic, Eigen::Dynamic> PermMatrix;
void Sys::permuteCols(const PermMatrix &perm, Sys &other)
{
// permute local matrices
T = T * perm;
Pavg = Pavg * perm;
Pm2 = Pm2 * perm;
M = M * perm;
if (has_prop_posterior())
{
propMu *= perm;
propLambda *= perm;
}
// permute other matrices
other.T = T.transpose();
other.Pavg = Pavg.transpose();
other.Pm2 = Pm2.transpose();
other.M = M.transpose();
}
//
// Distributes users/movies accros several nodes
// takes into account load balance and communication cost
//
void Sys::assign(Sys &other)
{
if (nprocs == 1) {
dom[0] = 0;
dom[1] = num();
return;
}
if (!permute) {
int p = num() / nprocs;
int i=0; for(; i<nprocs; ++i) dom[i] = i*p;
dom[i] = num();
return;
}
std::vector<std::vector<double>> comm_cost(num());
if (other.assigned) {
// comm_cost[i][j] == communication cost if item i is assigned to processor j
for(int i=0; i<num(); ++i) {
std::vector<unsigned> comm_per_proc(nprocs);
const int count = M.innerVector(i).nonZeros();
for (SparseMatrixD::InnerIterator it(M,i); it; ++it) comm_per_proc.at(other.proc(it.row()))++;
for(int j=0; j<nprocs; j++) comm_cost.at(i).push_back(count - comm_per_proc.at(j));
}
}
std::vector<unsigned> nnz_per_proc(nprocs);
std::vector<unsigned> items_per_proc(nprocs);
std::vector<double> work_per_proc(nprocs);
std::vector<int> item_to_proc(num(), -1);
unsigned total_nnz = 1;
unsigned total_items = 1;
double total_work = 0.01;
unsigned total_comm = 0;
// computes best node to assign movie/user idx
auto best = [&](int idx, double r1, double r2) {
double min_cost = 1e9;
int best_proc = -1;
for(int i=0; i<nprocs; ++i) {
//double nnz_unbalance = (double)nnz_per_proc[i] / total_nnz;
//double items_unbalance = (double)items_per_proc[i] / total_items;
//double work_unbalance = std::max(nnz_unbalance, items_unbalance);
double work_unbalance = work_per_proc[i] / total_work;
double comm = other.assigned ? comm_cost.at(idx).at(i) : 0.0;
double total_cost = r1 * work_unbalance + r2 * comm;
if (total_cost > min_cost) continue;
best_proc = i;
min_cost = total_cost;
}
return best_proc;
};
// update cost function when item is assigned to proc
auto assign = [&](int item, int proc) {
const int nnz = M.innerVector(item).nonZeros();
double work = 10.0 + nnz; // one item is as expensive as NZs
item_to_proc[item] = proc;
nnz_per_proc [proc] += nnz;
items_per_proc[proc]++;
work_per_proc [proc] += work;
total_nnz += nnz;
total_items++;
total_work+= work;
total_comm += (other.assigned ? comm_cost.at(item).at(proc) : 0);
};
// update cost function when item is removed from proc
auto unassign = [&](int item) {
int proc = item_to_proc[item];
if (proc < 0) return;
const int nnz = M.innerVector(item).nonZeros();
double work = 7.1 + nnz;
item_to_proc[item] = -1;
nnz_per_proc [proc] -= nnz;
items_per_proc[proc]--;
work_per_proc [proc] -= work;
total_nnz -= nnz;
total_items--;
total_work -= work;
total_comm -= (other.assigned ? comm_cost.at(item).at(proc) : 0);
};
// print cost after iterating once
auto print = [&](int iter) {
Sys::cout() << name << " -- iter " << iter << " -- \n";
if (Sys::procid == 0) {
int max_nnz = *std::max_element(nnz_per_proc.begin(), nnz_per_proc.end());
int min_nnz = *std::min_element(nnz_per_proc.begin(), nnz_per_proc.end());
int avg_nnz = nnz() / nprocs;
int max_items = *std::max_element(items_per_proc.begin(), items_per_proc.end());
int min_items = *std::min_element(items_per_proc.begin(), items_per_proc.end());
int avg_items = num() / nprocs;
double max_work = *std::max_element(work_per_proc.begin(), work_per_proc.end());
double min_work = *std::min_element(work_per_proc.begin(), work_per_proc.end());
double avg_work = total_work / nprocs;
Sys::cout() << name << ": comm cost " << 100.0 * total_comm / nnz() / nprocs << "%\n";
Sys::cout() << name << ": nnz unbalance: " << (int)(100.0 * Sys::nprocs * (max_nnz - min_nnz) / nnz()) << "%"
<< "\t(" << max_nnz << " <-> " << avg_nnz << " <-> " << min_nnz << ")\n";
Sys::cout() << name << ": items unbalance: " << (int)(100.0 * Sys::nprocs * (max_items - min_items) / num()) << "%"
<< "\t(" << max_items << " <-> " << avg_items << " <-> " << min_items << ")\n";
Sys::cout() << name << ": work unbalance: " << (int)(100.0 * Sys::nprocs * (max_work - min_work) / total_work) << "%"
<< "\t(" << max_work << " <-> " << avg_work << " <-> " << min_work << ")\n\n";
}
Sys::cout() << name << ": nnz:\t" << nnz_per_proc[procid] << " / " << nnz() << "\n";
Sys::cout() << name << ": items:\t" << items_per_proc[procid] << " / " << num() << "\n";
Sys::cout() << name << ": work:\t" << work_per_proc[procid] << " / " << total_work << "\n";
};
for(int j=0; j<3; ++j) {
for(int i=0; i<num(); ++i) {
unassign(i);
assign(i, best(i, 10000, 0));
}
print(j);
}
std::vector<std::vector<unsigned>> proc_to_item(nprocs);
for(int i=0; i<num(); ++i) proc_to_item[item_to_proc[i]].push_back(i);
// permute T, P based on assignment done before
unsigned pos = 0;
Eigen::PermutationMatrix<Eigen::Dynamic, Eigen::Dynamic> perm(num());
for(auto p: proc_to_item) for(auto i: p) perm.indices()(pos++) = i;
auto oldT = T;
this->permuteCols(perm, other);
int i = 0;
int n = 0;
dom[0] = 0;
for(auto p : items_per_proc) dom[++i] = (n += p);
#ifndef NDEBUG
int j = 0;
for(auto i : proc_to_item.at(0)) assert(T.col(j++).nonZeros() == oldT.col(i).nonZeros());
#endif
Sys::cout() << name << " domain:" << std::endl;
print_dom(Sys::cout());
Sys::cout() << std::endl;
assigned = true;
}
//
// Update connectivity map (where to send certain items)
// based on assignment to nodes
//
void Sys::update_conn(Sys& other)
{
unsigned tot = 0;
conn_map.clear();
conn_count_map.clear();
assert(nprocs <= (int)max_procs);
conn_map.resize(num());
for (int k=0; k<num(); ++k) {
std::bitset<max_procs> &bm = conn_map[k];
for (SparseMatrixD::InnerIterator it(M,k); it; ++it) bm.set(other.proc(it.row()));
for (SparseMatrixD::InnerIterator it(Pavg,k); it; ++it) bm.set(other.proc(it.row()));
bm.reset(proc(k)); // not to self
tot += bm.count();
// keep track of how may proc to proc sends
auto from_proc = proc(k);
for(int to_proc=0; to_proc<Sys::nprocs; to_proc++) {
if (!bm.test(to_proc)) continue;
conn_count_map[std::make_pair(from_proc, to_proc)]++;
}
}
if (Sys::procid == 0) {
Sys::cout() << name << ": avg items to send per iter: " << tot << " / " << num() << " = " << (double)tot / (double)num() << std::endl;
Sys::cout() << name << ": messages from -> to proc\n";
for(int i=0; i<Sys::nprocs; ++i) Sys::cout() << "\t" << i;
Sys::cout() << "\n";
for(int i=0; i<Sys::nprocs; ++i) {
Sys::cout() << i;
for(int j=0; j<Sys::nprocs; ++j) Sys::cout() << "\t" << conn_count(i,j);
Sys::cout() << "\n";
}
}
}
//
// try to keep items that have to be sent to the same node next to eachothe
//
void Sys::opt_conn(Sys& other)
{
// sort internally according to hamming distance
PermMatrix perm(num());
perm.setIdentity();
std::vector<std::string> s(num());
auto v = perm.indices().data();
#pragma omp parallel for
for (auto p = 0; p < nprocs; ++p)
{
for (int i = from(p); i < to(p); ++i)
{
s[i] = conn(i).to_string();
}
std::sort(v + from(p), v + to(p), [&](const int &a, const int &b) { return (s[a] < s[b]); });
}
permuteCols(perm, other);
}
void Sys::build_conn(Sys& other)
{
if (nprocs == 1) return;
update_conn(other);
//opt_conn(other);
//update_conn(other);
}<|endoftext|> |
<commit_before>/******************************************************************************
* Copyright 2018 The Apollo 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 "modules/perception/common/geometry/roi_filter.h"
#include "gtest/gtest.h"
#include "modules/perception/base/hdmap_struct.h"
#include "modules/perception/base/object.h"
#include "modules/perception/base/point_cloud.h"
namespace apollo {
namespace perception {
namespace common {
using apollo::perception::base::HdmapStruct;
using HdmapStructConstPtr =
std::shared_ptr<const apollo::perception::base::HdmapStruct>;
using HdmapStructPtr = std::shared_ptr<apollo::perception::base::HdmapStruct>;
using apollo::perception::base::PointD;
using apollo::perception::base::Object;
using ObjectConstPtr = std::shared_ptr<const apollo::perception::base::Object>;
using ObjectPtr = std::shared_ptr<apollo::perception::base::Object>;
TEST(IsPtInRoiTest, test_roi) {
HdmapStructPtr hdmap = HdmapStructPtr(new HdmapStruct());
hdmap->junction_polygons.resize(1);
PointD pt;
pt.x = -1.0;
pt.y = -1.0;
pt.z = 0.0;
hdmap->junction_polygons[0].push_back(pt);
pt.x = 1.0;
pt.y = -1.0;
pt.z = 0.0;
hdmap->junction_polygons[0].push_back(pt);
pt.x = 0.0;
pt.y = 1.0;
pt.z = 0.0;
hdmap->junction_polygons[0].push_back(pt);
bool flag = false;
pt.x = 0.0;
pt.y = 0.0;
pt.z = 0.0;
const HdmapStructConstPtr hdmo_const = hdmap;
flag = IsPtInRoi(hdmo_const, pt);
EXPECT_TRUE(flag);
pt.x = 10.0;
pt.y = 10.0;
pt.z = 10.0;
flag = IsPtInRoi(hdmo_const, pt);
EXPECT_FALSE(flag);
}
TEST(IsObjectInRoiTest, test_roi) {
HdmapStructPtr hdmap = HdmapStructPtr(new HdmapStruct());
hdmap->junction_polygons.resize(1);
PointD pt;
pt.x = -1.0;
pt.y = -1.0;
pt.z = 0.0;
hdmap->junction_polygons[0].push_back(pt);
pt.x = 1.0;
pt.y = -1.0;
pt.z = 0.0;
hdmap->junction_polygons[0].push_back(pt);
pt.x = 0.0;
pt.y = 1.0;
pt.z = 0.0;
hdmap->junction_polygons[0].push_back(pt);
bool flag = false;
ObjectConstPtr obj = ObjectPtr(new Object());
const HdmapStructConstPtr hdmo_const = hdmap;
flag = IsObjectInRoi(hdmo_const, obj);
EXPECT_TRUE(flag);
}
TEST(IsObjectBboxInRoiTest, test_roi) {
HdmapStructPtr hdmap = HdmapStructPtr(new HdmapStruct());
hdmap->junction_polygons.resize(1);
PointD pt;
pt.x = -1.0;
pt.y = -1.0;
pt.z = 0.0;
hdmap->junction_polygons[0].push_back(pt);
pt.x = 1.0;
pt.y = -1.0;
pt.z = 0.0;
hdmap->junction_polygons[0].push_back(pt);
pt.x = 0.0;
pt.y = 1.0;
pt.z = 0.0;
hdmap->junction_polygons[0].push_back(pt);
bool flag = false;
ObjectConstPtr obj = ObjectPtr(new Object());
const HdmapStructConstPtr hdmo_const = hdmap;
flag = IsObjectBboxInRoi(hdmo_const, obj);
EXPECT_TRUE(flag);
ObjectPtr obj_unconst = ObjectPtr(new Object());
obj_unconst->center[0] = 10.0;
obj_unconst->center[1] = 10.0;
obj_unconst->center[2] = 10.0;
flag = IsObjectBboxInRoi(hdmo_const, obj_unconst);
EXPECT_FALSE(flag);
obj_unconst->direction[0] = 0.0;
obj_unconst->center[0] = 0.0;
obj_unconst->center[1] = 0.0;
obj_unconst->center[2] = 0.0;
flag = IsObjectBboxInRoi(hdmo_const, obj_unconst);
EXPECT_TRUE(flag);
}
TEST(ObjectInRoiTest, test_roi) {
HdmapStructPtr hdmap = nullptr;
std::vector<ObjectPtr> objects;
std::vector<ObjectPtr> valid_objects;
ObjectPtr obj(new Object);
obj->center = Eigen::Vector3d(0, 0, 0);
objects.push_back(obj);
EXPECT_EQ(ObjectInRoiCheck(hdmap, objects, &valid_objects), true);
EXPECT_EQ(valid_objects.size(), 1);
hdmap.reset(new HdmapStruct());
valid_objects.clear();
EXPECT_EQ(ObjectInRoiCheck(hdmap, objects, &valid_objects), false);
EXPECT_EQ(valid_objects.size(), 1);
hdmap->road_polygons.resize(1);
PointD pt;
pt.x = -1.0;
pt.y = -1.0;
pt.z = 0;
hdmap->road_polygons[0].push_back(pt);
pt.x = 1.0;
pt.y = -1.0;
pt.z = 0;
hdmap->road_polygons[0].push_back(pt);
pt.x = 0;
pt.y = 1;
pt.z = 0;
hdmap->road_polygons[0].push_back(pt);
valid_objects.clear();
EXPECT_EQ(ObjectInRoiCheck(hdmap, objects, &valid_objects), false);
EXPECT_EQ(valid_objects.size(), 1);
hdmap->road_polygons[0][2].y = -0.1;
valid_objects.clear();
EXPECT_EQ(ObjectInRoiCheck(hdmap, objects, &valid_objects), false);
EXPECT_EQ(valid_objects.size(), 0);
}
} // namespace common
} // namespace perception
} // namespace apollo
<commit_msg>Perception: fixed a test failure<commit_after>/******************************************************************************
* Copyright 2018 The Apollo 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 "modules/perception/common/geometry/roi_filter.h"
#include "gtest/gtest.h"
#include "modules/perception/base/hdmap_struct.h"
#include "modules/perception/base/object.h"
#include "modules/perception/base/point_cloud.h"
namespace apollo {
namespace perception {
namespace common {
using apollo::perception::base::HdmapStruct;
using HdmapStructConstPtr =
std::shared_ptr<const apollo::perception::base::HdmapStruct>;
using HdmapStructPtr = std::shared_ptr<apollo::perception::base::HdmapStruct>;
using apollo::perception::base::PointD;
using apollo::perception::base::Object;
using ObjectConstPtr = std::shared_ptr<const apollo::perception::base::Object>;
using ObjectPtr = std::shared_ptr<apollo::perception::base::Object>;
TEST(IsPtInRoiTest, test_roi) {
HdmapStructPtr hdmap = HdmapStructPtr(new HdmapStruct());
hdmap->junction_polygons.resize(1);
PointD pt;
pt.x = -1.0;
pt.y = -1.0;
pt.z = 0.0;
hdmap->junction_polygons[0].push_back(pt);
pt.x = 1.0;
pt.y = -1.0;
pt.z = 0.0;
hdmap->junction_polygons[0].push_back(pt);
pt.x = 0.0;
pt.y = 1.0;
pt.z = 0.0;
hdmap->junction_polygons[0].push_back(pt);
bool flag = false;
pt.x = 0.0;
pt.y = 0.0;
pt.z = 0.0;
const HdmapStructConstPtr hdmo_const = hdmap;
flag = IsPtInRoi(hdmo_const, pt);
EXPECT_TRUE(flag);
pt.x = 10.0;
pt.y = 10.0;
pt.z = 10.0;
flag = IsPtInRoi(hdmo_const, pt);
EXPECT_FALSE(flag);
}
TEST(IsObjectInRoiTest, test_roi) {
HdmapStructPtr hdmap = HdmapStructPtr(new HdmapStruct());
hdmap->junction_polygons.resize(1);
PointD pt;
pt.x = -1.0;
pt.y = -1.0;
pt.z = 0.0;
hdmap->junction_polygons[0].push_back(pt);
pt.x = 1.0;
pt.y = -1.0;
pt.z = 0.0;
hdmap->junction_polygons[0].push_back(pt);
pt.x = 0.0;
pt.y = 1.0;
pt.z = 0.0;
hdmap->junction_polygons[0].push_back(pt);
bool flag = false;
ObjectConstPtr obj = ObjectPtr(new Object());
const HdmapStructConstPtr hdmo_const = hdmap;
flag = IsObjectInRoi(hdmo_const, obj);
EXPECT_TRUE(flag);
}
TEST(IsObjectBboxInRoiTest, test_roi) {
HdmapStructPtr hdmap = HdmapStructPtr(new HdmapStruct());
hdmap->junction_polygons.resize(1);
PointD pt;
pt.x = -1.0;
pt.y = -1.0;
pt.z = 0.0;
hdmap->junction_polygons[0].push_back(pt);
pt.x = 1.0;
pt.y = -1.0;
pt.z = 0.0;
hdmap->junction_polygons[0].push_back(pt);
pt.x = 0.0;
pt.y = 1.0;
pt.z = 0.0;
hdmap->junction_polygons[0].push_back(pt);
bool flag = false;
ObjectConstPtr obj = ObjectPtr(new Object());
const HdmapStructConstPtr hdmo_const = hdmap;
flag = IsObjectBboxInRoi(hdmo_const, obj);
EXPECT_TRUE(flag);
ObjectPtr obj_unconst = ObjectPtr(new Object());
obj_unconst->center[0] = 10.0;
obj_unconst->center[1] = 10.0;
obj_unconst->center[2] = 10.0;
flag = IsObjectBboxInRoi(hdmo_const, obj_unconst);
EXPECT_FALSE(flag);
obj_unconst->direction[0] = 0.0;
obj_unconst->center[0] = 0.0;
obj_unconst->center[1] = 0.0;
obj_unconst->center[2] = 0.0;
flag = IsObjectBboxInRoi(hdmo_const, obj_unconst);
EXPECT_TRUE(flag);
}
TEST(ObjectInRoiTest, test_roi) {
HdmapStructPtr hdmap = nullptr;
std::vector<ObjectPtr> objects;
std::vector<ObjectPtr> valid_objects;
ObjectPtr obj(new Object);
obj->center = Eigen::Vector3d(0, 0, 0);
objects.push_back(obj);
EXPECT_EQ(ObjectInRoiCheck(hdmap, objects, &valid_objects), true);
EXPECT_EQ(valid_objects.size(), 1);
hdmap.reset(new HdmapStruct());
valid_objects.clear();
EXPECT_EQ(ObjectInRoiCheck(hdmap, objects, &valid_objects), true);
EXPECT_EQ(valid_objects.size(), 1);
hdmap->road_polygons.resize(1);
PointD pt;
pt.x = -1.0;
pt.y = -1.0;
pt.z = 0;
hdmap->road_polygons[0].push_back(pt);
pt.x = 1.0;
pt.y = -1.0;
pt.z = 0;
hdmap->road_polygons[0].push_back(pt);
pt.x = 0;
pt.y = 1;
pt.z = 0;
hdmap->road_polygons[0].push_back(pt);
valid_objects.clear();
EXPECT_EQ(ObjectInRoiCheck(hdmap, objects, &valid_objects), true);
EXPECT_EQ(valid_objects.size(), 1);
hdmap->road_polygons[0][2].y = -0.1;
valid_objects.clear();
EXPECT_EQ(ObjectInRoiCheck(hdmap, objects, &valid_objects), false);
EXPECT_EQ(valid_objects.size(), 0);
}
} // namespace common
} // namespace perception
} // namespace apollo
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2014-2016, imec
* All rights reserved.
*/
#include "error.h"
#include "bpmf.h"
#include <random>
#include <memory>
#include <cstdio>
#include <iostream>
#include <climits>
#include <stdexcept>
#include "io.h"
static const bool measure_perf = false;
std::ostream *Sys::os;
int Sys::procid = -1;
int Sys::nprocs = -1;
int Sys::nsims;
int Sys::burnin;
int Sys::update_freq;
double Sys::alpha = 2.0;
std::string Sys::odirname = "";
bool Sys::permute = true;
bool Sys::verbose = false;
unsigned Sys::grain_size;
void calc_upper_part(MatrixNNd &m, VectorNd v); // function for calcutation of an upper part of a symmetric matrix: m = v * v.transpose();
void copy_lower_part(MatrixNNd &m); // function to copy an upper part of a symmetric matrix to a lower part
// verifies that A has the same non-zero structure as B
void assert_same_struct(SparseMatrixD &A, SparseMatrixD &B)
{
assert(A.cols() == B.cols());
assert(A.rows() == B.rows());
for(int i=0; i<A.cols(); ++i) assert(A.col(i).nonZeros() == B.col(i).nonZeros());
}
//
// Does predictions for prediction matrix T
// Computes RMSE (Root Means Square Error)
//
void Sys::predict(Sys& other, bool all)
{
int n = (iter < burnin) ? 0 : (iter - burnin);
double se(0.0); // squared err
double se_avg(0.0); // squared avg err
unsigned nump(0); // number of predictions
int lo = all ? 0 : from();
int hi = all ? num() : to();
#pragma omp parallel for reduction(+:se,se_avg,nump)
for(int k = lo; k<hi; k++) {
for (Eigen::SparseMatrix<double>::InnerIterator it(T,k); it; ++it)
{
auto m = items().col(it.col());
auto u = other.items().col(it.row());
assert(m.norm() > 0.0);
assert(u.norm() > 0.0);
const double pred = m.dot(u) + mean_rating;
se += sqr(it.value() - pred);
// update average prediction
double &avg = Pavg.coeffRef(it.row(), it.col());
double delta = pred - avg;
avg = (n == 0) ? pred : (avg + delta/n);
double &m2 = Pm2.coeffRef(it.row(), it.col());
m2 = (n == 0) ? 0 : m2 + delta * (pred - avg);
se_avg += sqr(it.value() - avg);
nump++;
}
}
rmse = sqrt( se / nump );
rmse_avg = sqrt( se_avg / nump );
}
//
// Prints sampling progress
//
void Sys::print(double items_per_sec, double ratings_per_sec, double norm_u, double norm_m) {
char buf[1024];
std::string phase = (iter < Sys::burnin) ? "Burnin" : "Sampling";
sprintf(buf, "%d: %s iteration %d:\t RMSE: %3.4f\tavg RMSE: %3.4f\tFU(%6.2f)\tFM(%6.2f)\titems/sec: %6.2f\tratings/sec: %6.2fM\n",
Sys::procid, phase.c_str(), iter, rmse, rmse_avg, norm_u, norm_m, items_per_sec, ratings_per_sec / 1e6);
Sys::cout() << buf;
}
//
// Constructor with that reads MTX files
//
Sys::Sys(std::string name, std::string fname, std::string probename)
: name(name), iter(-1), assigned(false), dom(nprocs+1)
{
read_matrix(fname, M);
read_matrix(probename, T);
auto rows = std::max(M.rows(), T.rows());
auto cols = std::max(M.cols(), T.cols());
M.conservativeResize(rows,cols);
T.conservativeResize(rows,cols);
Pm2 = Pavg = Torig = T; // reference ratings and predicted ratings
assert(M.rows() == Pavg.rows());
assert(M.cols() == Pavg.cols());
assert(Sys::nprocs <= (int)Sys::max_procs);
}
//
// Constructs Sys as transpose of existing Sys
//
Sys::Sys(std::string name, const SparseMatrixD &Mt, const SparseMatrixD &Pt) : name(name), iter(-1), assigned(false), dom(nprocs+1) {
M = Mt.transpose();
Pm2 = Pavg = T = Torig = Pt.transpose(); // reference ratings and predicted ratings
assert(M.rows() == Pavg.rows());
assert(M.cols() == Pavg.cols());
}
Sys::~Sys()
{
if (measure_perf) {
Sys::cout() << " --------------------\n";
Sys::cout() << name << ": sampling times on " << procid << "\n";
for(int i = from(); i<to(); ++i)
{
Sys::cout() << "\t" << nnz(i) << "\t" << sample_time.at(i) / nsims << "\n";
}
Sys::cout() << " --------------------\n\n";
}
}
bool Sys::has_prop_posterior() const
{
return propMu.nonZeros() > 0;
}
void Sys::add_prop_posterior(std::string fnames)
{
if (fnames.empty()) return;
std::size_t pos = fnames.find_first_of(",");
std::string mu_name = fnames.substr(0, pos);
std::string lambda_name = fnames.substr(pos+1);
read_matrix(mu_name, propMu);
read_matrix(lambda_name, propLambda);
assert(propMu.cols() == num());
assert(propLambda.cols() == num());
assert(propMu.rows() == num_latent);
assert(propLambda.rows() == num_latent * num_latent);
}
//
// Intializes internal Matrices and Vectors
//
void Sys::init()
{
//-- M
assert(M.rows() > 0 && M.cols() > 0);
mean_rating = M.sum() / M.nonZeros();
items().setZero();
sum_map().setZero();
cov_map().setZero();
norm_map().setZero();
col_permutation.setIdentity(num());
if (Sys::odirname.size())
{
aggrMu = Eigen::MatrixXd::Zero(num_latent, num());
aggrLambda = Eigen::MatrixXd::Zero(num_latent * num_latent, num());
}
int count_larger_bp1 = 0;
int count_larger_bp2 = 0;
int count_sum = 0;
for(int k = 0; k<M.cols(); k++) {
int count = M.col(k).nonZeros();
count_sum += count;
if (count > breakpoint1) count_larger_bp1++;
if (count > breakpoint2) count_larger_bp2++;
}
Sys::cout() << "mean rating: " << mean_rating << std::endl;
Sys::cout() << "total number of ratings in train: " << M.nonZeros() << std::endl;
Sys::cout() << "total number of ratings in test: " << T.nonZeros() << std::endl;
Sys::cout() << "average ratings per row: " << (double)count_sum / (double)M.cols() << std::endl;
Sys::cout() << "rows > break_point1: " << 100. * (double)count_larger_bp1 / (double)M.cols() << std::endl;
Sys::cout() << "rows > break_point2: " << 100. * (double)count_larger_bp2 / (double)M.cols() << std::endl;
Sys::cout() << "num " << name << ": " << num() << std::endl;
if (has_prop_posterior())
{
Sys::cout() << "with propagated posterior" << std::endl;
}
if (measure_perf) sample_time.resize(num(), .0);
}
class PrecomputedLLT : public Eigen::LLT<MatrixNNd>
{
public:
void operator=(const MatrixNNd &m) { m_matrix = m; m_isInitialized = true; m_info = Eigen::Success; }
};
//
// Update ONE movie or one user
//
VectorNd Sys::sample(long idx, const MapNXd in)
{
auto start = tick();
VectorNd hp_mu;
MatrixNNd hp_LambdaF;
MatrixNNd hp_LambdaL;
if (has_prop_posterior())
{
hp_mu = propMu.col(idx);
hp_LambdaF = Eigen::Map<MatrixNNd>(propLambda.col(idx).data());
hp_LambdaL = hp_LambdaF.llt().matrixL();
}
else
{
hp_mu = hp.mu;
hp_LambdaF = hp.LambdaF;
hp_LambdaL = hp.LambdaL;
}
const int count = M.innerVector(idx).nonZeros(); // count of nonzeros elements in idx-th row of M matrix
// (how many movies watched idx-th user?).
VectorNd rr = hp_LambdaF * hp.mu; // vector num_latent x 1, we will use it in formula (14) from the paper
PrecomputedLLT chol; // matrix num_latent x num_latent, chol="lambda_i with *" from formula (14)
// if this user movie has less than 1K ratings,
// we do a serial rank update
if( count < breakpoint1 ) {
chol = hp_LambdaL;
for (SparseMatrixD::InnerIterator it(M,idx); it; ++it) {
auto col = in.col(it.row());
chol.rankUpdate(col, alpha);
rr.noalias() += col * ((it.value() - mean_rating) * alpha);
}
// else we do a serial full cholesky decomposition
// (not used if breakpoint1 == breakpoint2)
} else if (count < breakpoint2) {
MatrixNNd MM(MatrixNNd::Zero());
for (SparseMatrixD::InnerIterator it(M,idx); it; ++it) {
auto col = in.col(it.row());
//MM.noalias() += col * col.transpose();
calc_upper_part(MM, col);
rr.noalias() += col * ((it.value() - mean_rating) * alpha);
}
// Here, we copy a triangular upper part to a triangular lower part, because the matrix is symmetric.
copy_lower_part(MM);
chol.compute(hp_LambdaF + alpha * MM);
// for > 10K ratings, we have additional thread-level parallellism
} else {
const int task_size = count / 100;
auto from = M.outerIndexPtr()[idx]; // "from" belongs to [1..m], m - number of movies in M matrix
auto to = M.outerIndexPtr()[idx+1]; // "to" belongs to [1..m], m - number of movies in M matrix
MatrixNNd MM(MatrixNNd::Zero()); // matrix num_latent x num_latent
thread_vector<VectorNd> rrs(VectorNd::Zero());
thread_vector<MatrixNNd> MMs(MatrixNNd::Zero());
for(int i = from; i<to; i+=task_size) {
#pragma omp task shared(rrs, MMs)
for(int j = i; j<std::min(i+task_size, to); j++)
{
// for each nonzeros elemen in the i-th row of M matrix
auto val = M.valuePtr()[j]; // value of the j-th nonzeros element from idx-th row of M matrix
auto idx = M.innerIndexPtr()[j]; // index "j" of the element [i,j] from M matrix in compressed M matrix
auto col = in.col(idx); // vector num_latent x 1 from V matrix: M[i,j] = U[i,:] x V[idx,:]
//MM.noalias() += col * col.transpose(); // outer product
calc_upper_part(MMs.local(), col);
rrs.local().noalias() += col * ((val - mean_rating) * alpha); // vector num_latent x 1
}
}
#pragma omp taskwait
// accumulate
MM += MMs.combine();
rr += rrs.combine();
copy_lower_part(MM);
chol.compute(hp_LambdaF + alpha * MM); // matrix num_latent x num_latent
// chol="lambda_i with *" from formula (14)
// lambda_i with * = LambdaU + alpha * MM
}
if(chol.info() != Eigen::Success) THROWERROR("Cholesky failed");
// now we should calculate formula (14) from the paper
// u_i for k-th iteration = Gaussian distribution N(u_i | mu_i with *, [lambda_i with *]^-1) =
// = mu_i with * + s * [U]^-1,
// where
// s is a random vector with N(0, I),
// mu_i with * is a vector num_latent x 1,
// mu_i with * = [lambda_i with *]^-1 * rr,
// lambda_i with * = L * U
// Expression u_i = U \ (s + (L \ rr)) in Matlab looks for Eigen library like:
chol.matrixL().solveInPlace(rr); // L*Y=rr => Y=L\rr, we store Y result again in rr vector
rr += nrandn(); // rr=s+(L\rr), we store result again in rr vector
chol.matrixU().solveInPlace(rr); // u_i=U\rr
items().col(idx) = rr; // we save rr vector in items matrix (it is user features matrix)
auto stop = tick();
register_time(idx, 1e6 * (stop - start));
//Sys::cout() << " " << count << ": " << 1e6*(stop - start) << std::endl;
assert(rr.norm() > .0);
return rr;
}
//
// update ALL movies / users in parallel
//
void Sys::sample(Sys &in)
{
iter++;
thread_vector<VectorNd> sums(VectorNd::Zero()); // sum
thread_vector<double> norms(0.0); // squared norm
thread_vector<MatrixNNd> prods(MatrixNNd::Zero()); // outer prod
#pragma omp parallel for schedule(guided)
for (int i = from(); i < to(); ++i)
{
#pragma omp task
{
auto r = sample(i, in.items());
MatrixNNd cov = (r * r.transpose());
prods.local() += cov;
sums.local() += r;
norms.local() += r.squaredNorm();
if (iter >= burnin && Sys::odirname.size())
{
aggrMu.col(i) += r;
aggrLambda.col(i) += Eigen::Map<Eigen::VectorXd>(cov.data(), num_latent * num_latent);
}
send_item(i);
}
}
#pragma omp taskwait
VectorNd sum = sums.combine();
MatrixNNd prod = prods.combine();
double norm = norms.combine();
const int N = num();
local_sum() = sum;
local_cov() = (prod - (sum * sum.transpose() / N)) / (N-1);
local_norm() = norm;
}
void Sys::register_time(int i, double t)
{
if (measure_perf) sample_time.at(i) += t;
}
void calc_upper_part(MatrixNNd &m, VectorNd v)
{
// we use the formula: m = m + v * v.transpose(), but we calculate only an upper part of m matrix
for (int j=0; j<num_latent; j++) // columns
{
for(int i=0; i<=j; i++) // rows
{
m(i,j) = m(i,j) + v[j] * v[i];
}
}
}
void copy_lower_part(MatrixNNd &m)
{
// Here, we copy a triangular upper part to a triangular lower part, because the matrix is symmetric.
for (int j=1; j<num_latent; j++) // columns
{
for(int i=0; i<=j-1; i++) // rows
{
m(j,i) = m(i,j);
}
}
}
<commit_msg>WIP: simplify Lambda calc<commit_after>/*
* Copyright (c) 2014-2016, imec
* All rights reserved.
*/
#include "error.h"
#include "bpmf.h"
#include <random>
#include <memory>
#include <cstdio>
#include <iostream>
#include <climits>
#include <stdexcept>
#include "io.h"
static const bool measure_perf = false;
std::ostream *Sys::os;
int Sys::procid = -1;
int Sys::nprocs = -1;
int Sys::nsims;
int Sys::burnin;
int Sys::update_freq;
double Sys::alpha = 2.0;
std::string Sys::odirname = "";
bool Sys::permute = true;
bool Sys::verbose = false;
unsigned Sys::grain_size;
void calc_upper_part(MatrixNNd &m, VectorNd v); // function for calcutation of an upper part of a symmetric matrix: m = v * v.transpose();
void copy_lower_part(MatrixNNd &m); // function to copy an upper part of a symmetric matrix to a lower part
// verifies that A has the same non-zero structure as B
void assert_same_struct(SparseMatrixD &A, SparseMatrixD &B)
{
assert(A.cols() == B.cols());
assert(A.rows() == B.rows());
for(int i=0; i<A.cols(); ++i) assert(A.col(i).nonZeros() == B.col(i).nonZeros());
}
//
// Does predictions for prediction matrix T
// Computes RMSE (Root Means Square Error)
//
void Sys::predict(Sys& other, bool all)
{
int n = (iter < burnin) ? 0 : (iter - burnin);
double se(0.0); // squared err
double se_avg(0.0); // squared avg err
unsigned nump(0); // number of predictions
int lo = all ? 0 : from();
int hi = all ? num() : to();
#pragma omp parallel for reduction(+:se,se_avg,nump)
for(int k = lo; k<hi; k++) {
for (Eigen::SparseMatrix<double>::InnerIterator it(T,k); it; ++it)
{
auto m = items().col(it.col());
auto u = other.items().col(it.row());
assert(m.norm() > 0.0);
assert(u.norm() > 0.0);
const double pred = m.dot(u) + mean_rating;
se += sqr(it.value() - pred);
// update average prediction
double &avg = Pavg.coeffRef(it.row(), it.col());
double delta = pred - avg;
avg = (n == 0) ? pred : (avg + delta/n);
double &m2 = Pm2.coeffRef(it.row(), it.col());
m2 = (n == 0) ? 0 : m2 + delta * (pred - avg);
se_avg += sqr(it.value() - avg);
nump++;
}
}
rmse = sqrt( se / nump );
rmse_avg = sqrt( se_avg / nump );
}
//
// Prints sampling progress
//
void Sys::print(double items_per_sec, double ratings_per_sec, double norm_u, double norm_m) {
char buf[1024];
std::string phase = (iter < Sys::burnin) ? "Burnin" : "Sampling";
sprintf(buf, "%d: %s iteration %d:\t RMSE: %3.4f\tavg RMSE: %3.4f\tFU(%6.2f)\tFM(%6.2f)\titems/sec: %6.2f\tratings/sec: %6.2fM\n",
Sys::procid, phase.c_str(), iter, rmse, rmse_avg, norm_u, norm_m, items_per_sec, ratings_per_sec / 1e6);
Sys::cout() << buf;
}
//
// Constructor with that reads MTX files
//
Sys::Sys(std::string name, std::string fname, std::string probename)
: name(name), iter(-1), assigned(false), dom(nprocs+1)
{
read_matrix(fname, M);
read_matrix(probename, T);
auto rows = std::max(M.rows(), T.rows());
auto cols = std::max(M.cols(), T.cols());
M.conservativeResize(rows,cols);
T.conservativeResize(rows,cols);
Pm2 = Pavg = Torig = T; // reference ratings and predicted ratings
assert(M.rows() == Pavg.rows());
assert(M.cols() == Pavg.cols());
assert(Sys::nprocs <= (int)Sys::max_procs);
}
//
// Constructs Sys as transpose of existing Sys
//
Sys::Sys(std::string name, const SparseMatrixD &Mt, const SparseMatrixD &Pt) : name(name), iter(-1), assigned(false), dom(nprocs+1) {
M = Mt.transpose();
Pm2 = Pavg = T = Torig = Pt.transpose(); // reference ratings and predicted ratings
assert(M.rows() == Pavg.rows());
assert(M.cols() == Pavg.cols());
}
Sys::~Sys()
{
if (measure_perf) {
Sys::cout() << " --------------------\n";
Sys::cout() << name << ": sampling times on " << procid << "\n";
for(int i = from(); i<to(); ++i)
{
Sys::cout() << "\t" << nnz(i) << "\t" << sample_time.at(i) / nsims << "\n";
}
Sys::cout() << " --------------------\n\n";
}
}
bool Sys::has_prop_posterior() const
{
return propMu.nonZeros() > 0;
}
void Sys::add_prop_posterior(std::string fnames)
{
if (fnames.empty()) return;
std::size_t pos = fnames.find_first_of(",");
std::string mu_name = fnames.substr(0, pos);
std::string lambda_name = fnames.substr(pos+1);
read_matrix(mu_name, propMu);
read_matrix(lambda_name, propLambda);
assert(propMu.cols() == num());
assert(propLambda.cols() == num());
assert(propMu.rows() == num_latent);
assert(propLambda.rows() == num_latent * num_latent);
}
//
// Intializes internal Matrices and Vectors
//
void Sys::init()
{
//-- M
assert(M.rows() > 0 && M.cols() > 0);
mean_rating = M.sum() / M.nonZeros();
items().setZero();
sum_map().setZero();
cov_map().setZero();
norm_map().setZero();
col_permutation.setIdentity(num());
if (Sys::odirname.size())
{
aggrMu = Eigen::MatrixXd::Zero(num_latent, num());
aggrLambda = Eigen::MatrixXd::Zero(num_latent * num_latent, num());
}
int count_sum = 0;
for(int k = 0; k<M.cols(); k++) {
int count = M.col(k).nonZeros();
count_sum += count;
}
Sys::cout() << "mean rating: " << mean_rating << std::endl;
Sys::cout() << "total number of ratings in train: " << M.nonZeros() << std::endl;
Sys::cout() << "total number of ratings in test: " << T.nonZeros() << std::endl;
Sys::cout() << "average ratings per row: " << (double)count_sum / (double)M.cols() << std::endl;
Sys::cout() << "num " << name << ": " << num() << std::endl;
if (has_prop_posterior())
{
Sys::cout() << "with propagated posterior" << std::endl;
}
if (measure_perf) sample_time.resize(num(), .0);
}
class PrecomputedLLT : public Eigen::LLT<MatrixNNd>
{
public:
void operator=(const MatrixNNd &m) { m_matrix = m; m_isInitialized = true; m_info = Eigen::Success; }
};
//
// Update ONE movie or one user
//
VectorNd Sys::sample(long idx, const MapNXd in)
{
auto start = tick();
VectorNd hp_mu;
MatrixNNd hp_LambdaF;
MatrixNNd hp_LambdaL;
if (has_prop_posterior())
{
hp_mu = propMu.col(idx);
hp_LambdaF = Eigen::Map<MatrixNNd>(propLambda.col(idx).data());
hp_LambdaL = hp_LambdaF.llt().matrixL();
}
else
{
hp_mu = hp.mu;
hp_LambdaF = hp.LambdaF;
hp_LambdaL = hp.LambdaL;
}
VectorNd rr = hp_LambdaF * hp.mu; // vector num_latent x 1, we will use it in formula (14) from the paper
PrecomputedLLT chol; // matrix num_latent x num_latent, chol="lambda_i with *" from formula (14)
MatrixNNd MM(MatrixNNd::Zero());
for (SparseMatrixD::InnerIterator it(M, idx); it; ++it)
{
auto col = in.col(it.row());
//MM.noalias() += col * col.transpose();
calc_upper_part(MM, col);
rr.noalias() += col * ((it.value() - mean_rating) * alpha);
}
// Here, we copy a triangular upper part to a triangular lower part, because the matrix is symmetric.
copy_lower_part(MM);
chol.compute(hp_LambdaF + alpha * MM);
if(chol.info() != Eigen::Success) THROWERROR("Cholesky failed");
// now we should calculate formula (14) from the paper
// u_i for k-th iteration = Gaussian distribution N(u_i | mu_i with *, [lambda_i with *]^-1) =
// = mu_i with * + s * [U]^-1,
// where
// s is a random vector with N(0, I),
// mu_i with * is a vector num_latent x 1,
// mu_i with * = [lambda_i with *]^-1 * rr,
// lambda_i with * = L * U
// Expression u_i = U \ (s + (L \ rr)) in Matlab looks for Eigen library like:
chol.matrixL().solveInPlace(rr); // L*Y=rr => Y=L\rr, we store Y result again in rr vector
rr += nrandn(); // rr=s+(L\rr), we store result again in rr vector
chol.matrixU().solveInPlace(rr); // u_i=U\rr
items().col(idx) = rr; // we save rr vector in items matrix (it is user features matrix)
auto stop = tick();
register_time(idx, 1e6 * (stop - start));
//Sys::cout() << " " << count << ": " << 1e6*(stop - start) << std::endl;
assert(rr.norm() > .0);
return rr;
}
//
// update ALL movies / users in parallel
//
void Sys::sample(Sys &in)
{
iter++;
thread_vector<VectorNd> sums(VectorNd::Zero()); // sum
thread_vector<double> norms(0.0); // squared norm
thread_vector<MatrixNNd> prods(MatrixNNd::Zero()); // outer prod
#pragma omp parallel for schedule(guided)
for (int i = from(); i < to(); ++i)
{
#pragma omp task
{
auto r = sample(i, in.items());
MatrixNNd cov = (r * r.transpose());
prods.local() += cov;
sums.local() += r;
norms.local() += r.squaredNorm();
if (iter >= burnin && Sys::odirname.size())
{
aggrMu.col(i) += r;
aggrLambda.col(i) += Eigen::Map<Eigen::VectorXd>(cov.data(), num_latent * num_latent);
}
send_item(i);
}
}
#pragma omp taskwait
VectorNd sum = sums.combine();
MatrixNNd prod = prods.combine();
double norm = norms.combine();
const int N = num();
local_sum() = sum;
local_cov() = (prod - (sum * sum.transpose() / N)) / (N-1);
local_norm() = norm;
}
void Sys::register_time(int i, double t)
{
if (measure_perf) sample_time.at(i) += t;
}
void calc_upper_part(MatrixNNd &m, VectorNd v)
{
// we use the formula: m = m + v * v.transpose(), but we calculate only an upper part of m matrix
for (int j=0; j<num_latent; j++) // columns
{
for(int i=0; i<=j; i++) // rows
{
m(i,j) = m(i,j) + v[j] * v[i];
}
}
}
void copy_lower_part(MatrixNNd &m)
{
// Here, we copy a triangular upper part to a triangular lower part, because the matrix is symmetric.
for (int j=1; j<num_latent; j++) // columns
{
for(int i=0; i<=j-1; i++) // rows
{
m(j,i) = m(i,j);
}
}
}
<|endoftext|> |
<commit_before>#pragma once
#include <string>
#include <vector>
#include <algorithm>
#include <optional>
#include <functional>
#include "acmacs-base/sfinae.hh"
#include "acmacs-base/read-file.hh"
#include "acmacs-base/rjson.hh"
// ----------------------------------------------------------------------
namespace acmacs::settings
{
inline namespace v1
{
class field_base;
class object;
template <typename T> class array_basic;
template <typename T> class array;
// --------------------------------------------------
class not_set : public std::runtime_error
{
public:
not_set(std::string path) : runtime_error("not set: " + path) {}
};
// --------------------------------------------------
class base
{
public:
base() = default;
base(const base&) = default;
base(base&&) = default;
virtual ~base() = default;
virtual void inject_default() = 0;
virtual std::string path() const = 0;
protected:
virtual rjson::value& set() = 0;
virtual const rjson::value& get() const = 0;
friend class object;
template <typename T> friend class array_basic;
template <typename T> friend class array;
};
// --------------------------------------------------
class container : public base
{
public:
container() = default;
container(const container&) = delete;
container(container&&) = delete;
};
// --------------------------------------------------
class object_base : public container
{
public:
void inject_default() override;
protected:
void register_field(field_base* fld) { fields_.push_back(fld); }
private:
std::vector<field_base*> fields_;
friend class field_base;
};
// --------------------------------------------------
class field_base : public base
{
public:
field_base(object_base& parent, const char* name) : parent_(parent), name_(name) { parent.register_field(this); }
field_base(const field_base&) = delete;
field_base(field_base&&) = delete;
rjson::value& set() override { return parent_.set().set(name_); }
const rjson::value& get() const override { return parent_.get().get(name_); }
std::string path() const override { return parent_.path() + '.' + name_; }
private:
object_base& parent_;
const char* name_;
};
// --------------------------------------------------
class toplevel : public object_base
{
public:
toplevel() = default;
std::string path() const override { return {}; }
std::string to_string() const { return rjson::to_string(value_); }
std::string pretty() const { return rjson::pretty(value_); }
void read_from_file(std::string filename) { value_ = rjson::parse_file(filename); }
void update_from_file(std::string filename) { value_.update(rjson::parse_file(filename)); }
void write_to_file(std::string filename) const { file::write(filename, static_cast<std::string_view>(rjson::pretty(value_))); }
protected:
rjson::value& set() override { if (value_.is_null()) value_ = rjson::object{}; return value_; }
const rjson::value& get() const override { return value_; }
private:
rjson::value value_;
};
// --------------------------------------------------
class object : public object_base
{
public:
object(base& parent) : parent_(parent) {}
std::string path() const override { return parent_.path(); }
protected:
rjson::value& set() override { auto& val = parent_.set(); if (val.is_null()) val = rjson::object{}; return val; }
const rjson::value& get() const override { return parent_.get(); }
private:
base& parent_;
friend inline std::ostream& operator<<(std::ostream& out, const object& obj) { return out << obj.get(); }
};
// --------------------------------------------------
template <typename T> class array_basic : public container
{
public:
array_basic(base& parent) : parent_(parent) {}
std::string path() const override { return parent_.path(); }
// void inject_default() override { std::for_each(content_.begin(), content_.end(), [](T& elt) { elt.inject_default(); }); }
void inject_default() override {}
bool empty() const { return parent_.get().empty(); }
size_t size() const { return parent_.get().size(); }
T operator[](size_t index) const { return get()[index]; }
rjson::value& operator[](size_t index) { return set()[index]; }
T append(const T& to_append) { return set().append(to_append); }
void clear() { set().clear(); }
protected:
rjson::value& set() override { auto& val = parent_.set(); if (val.is_null()) val = rjson::array{}; return val; }
const rjson::value& get() const override { return parent_.get(); }
private:
base& parent_;
friend inline std::ostream& operator<<(std::ostream& out, const array_basic<T>& arr) { return out << arr.get(); }
};
// --------------------------------------------------
template <typename T> class array_element : public base
{
public:
array_element(rjson::value& val, std::string path) : value_(val), content_(*this), path_(path) {}
array_element(const array_element& src) : value_(src.value_), content_(*this), path_(src.path_) {}
array_element(array_element&& src) : value_(std::move(src.value_)), content_(*this), path_(std::move(src.path_)) {}
array_element& operator=(const array_element& src) { value_ = src.value_; path_ = src.path_; }
array_element& operator=(array_element&& src) { value_ = std::move(src.value_); path_ = std::move(src.path_); }
std::string path() const override { return path_; }
void inject_default() override { content_.inject_default(); }
T& operator*() { return content_; }
const T& operator*() const { return content_; }
T* operator->() { return &content_; }
const T* operator->() const { return &content_; }
protected:
rjson::value& set() override { return value_; }
const rjson::value& get() const override { return value_; }
private:
std::reference_wrapper<rjson::value> value_;
T content_;
std::string path_;
friend class object;
};
template <typename T> class array : public container
{
public:
array(base& parent) : parent_(parent) {}
std::string path() const override { return parent_.path(); }
void inject_default() override {}
bool empty() const { return parent_.get().empty(); }
size_t size() const { return parent_.get().size(); }
array_element<T> operator[](size_t index) const { return {get()[index], make_element_path(index)}; }
array_element<T> operator[](size_t index) { return {set()[index], make_element_path(index)}; }
array_element<T> append() { const size_t index = size(); array_element<T> res(set().append(rjson::object{}), make_element_path(index)); res.inject_default(); return res; }
void clear() { set().clear(); }
protected:
rjson::value& set() override { auto& val = parent_.set(); if (val.is_null()) val = rjson::array{}; return val; }
const rjson::value& get() const override { return parent_.get(); }
private:
base& parent_;
std::string make_element_path(size_t index) { return path() + '[' + std::to_string(index) + ']'; }
friend inline std::ostream& operator<<(std::ostream& out, const array_basic<T>& arr) { return out << arr.get(); }
};
// --------------------------------------------------
template <typename T> class field : public field_base
{
public:
field(object_base* parent, const char* name, T&& default_value) : field_base(*parent, name), default_(std::forward<T>(default_value)) { }
field(object_base* parent, const char* name) : field_base(*parent, name) { }
void inject_default() override;
field& operator=(const T& source);
operator T() const;
private:
std::optional<T> default_;
};
template <typename T> inline std::ostream& operator<<(std::ostream& out, const field<T>& fld) { return out << static_cast<T>(fld); }
// --------------------------------------------------
// T must be derived from object
template <typename T> class field_object : public field_base
{
public:
field_object(object_base* parent, const char* name) : field_base(*parent, name), content_(*this) {}
void inject_default() override { content_.inject_default(); }
T& operator*() { return content_; }
const T& operator*() const { return content_; }
T* operator->() { return &content_; }
const T* operator->() const { return &content_; }
private:
T content_;
};
template <typename T> inline std::ostream& operator<<(std::ostream& out, const field_object<T>& fld) { return out << *fld; }
// --------------------------------------------------
template <typename T> class field_array : public field_base
{
public:
field_array(object_base* parent, const char* name) : field_base(*parent, name), content_(*this) {}
field_array(object_base* parent, const char* name, std::initializer_list<T> init) : field_base(*parent, name), content_(*this), default_{init} {}
void inject_default() override;
bool empty() const { return content_.empty(); }
size_t size() const { return content_.size(); }
T operator[](size_t index) const { return content_[index]; }
void append(const T& to_append) { content_.append(to_append); }
void append() { content_.append({}); }
void clear() { content_.clear(); }
array_basic<T>& operator*() { return content_; }
const array_basic<T>& operator*() const { return content_; }
private:
array_basic<T> content_;
std::vector<T> default_;
};
template <typename T> inline std::ostream& operator<<(std::ostream& out, const field_array<T>& fld) { return out << *fld; }
// --------------------------------------------------
template <typename T> class field_array_of : public field_base
{
public:
field_array_of(object_base* parent, const char* name) : field_base(*parent, name), content_(*this) {}
void inject_default() override {}
bool empty() const { return content_.empty(); }
size_t size() const { return content_.size(); }
array_element<T> operator[](size_t index) { return content_[index]; }
array_element<T> operator[](size_t index) const { return content_[index]; }
array_element<T> append() { return content_.append(); }
void clear() { content_.clear(); }
array<T>& operator*() { return content_; }
const array<T>& operator*() const { return content_; }
private:
array<T> content_;
};
// **********************************************************************
// implementation
// **********************************************************************
inline void object_base::inject_default()
{
std::for_each(fields_.begin(), fields_.end(), [](field_base* fld) { fld->inject_default(); });
}
template <typename T> inline void field<T>::inject_default()
{
if (default_) {
if (auto& val = set(); val.is_null())
val = *default_;
}
}
template <typename T> inline field<T>& field<T>::operator=(const T& source)
{
set() = source;
return *this;
}
template <typename T> inline field<T>::operator T() const
{
if (auto& val = get(); !val.is_null()) {
if constexpr (std::is_same_v<std::decay_t<T>, bool>)
return val.get_bool();
else
return val;
}
else if (default_)
return *default_;
else
throw not_set(path());
}
template <typename T> inline void field_array<T>::inject_default()
{
if (empty() && !default_.empty()) {
for (const T& val : default_)
append(val);
}
}
} // namespace v1
} // namespace acmacs::settings
// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<commit_msg>acmacs::settings::v1<commit_after>#pragma once
#include <string>
#include <vector>
#include <algorithm>
#include <optional>
#include <functional>
#include "acmacs-base/sfinae.hh"
#include "acmacs-base/read-file.hh"
#include "acmacs-base/rjson.hh"
// ----------------------------------------------------------------------
namespace acmacs::settings
{
inline namespace v1
{
class field_base;
class object;
template <typename T> class array_basic;
template <typename T> class array;
// --------------------------------------------------
class not_set : public std::runtime_error
{
public:
not_set(std::string path) : runtime_error("not set: " + path) {}
};
// --------------------------------------------------
class base
{
public:
base() = default;
base(const base&) = default;
base(base&&) = default;
virtual ~base() = default;
virtual void inject_default() = 0;
virtual std::string path() const = 0;
protected:
virtual rjson::value& set() = 0;
virtual const rjson::value& get() const = 0;
friend class object;
template <typename T> friend class array_basic;
template <typename T> friend class array;
};
// --------------------------------------------------
class container : public base
{
public:
container() = default;
container(const container&) = delete;
container(container&&) = delete;
};
// --------------------------------------------------
class object_base : public container
{
public:
void inject_default() override;
protected:
void register_field(field_base* fld) { fields_.push_back(fld); }
private:
std::vector<field_base*> fields_;
friend class field_base;
};
// --------------------------------------------------
class field_base : public base
{
public:
field_base(object_base& parent, const char* name) : parent_(parent), name_(name) { parent.register_field(this); }
field_base(const field_base&) = delete;
field_base(field_base&&) = delete;
rjson::value& set() override { return parent_.set().set(name_); }
const rjson::value& get() const override { return parent_.get().get(name_); }
std::string path() const override { return parent_.path() + '.' + name_; }
private:
object_base& parent_;
const char* name_;
};
// --------------------------------------------------
class toplevel : public object_base
{
public:
toplevel() = default;
std::string path() const override { return {}; }
std::string to_string() const { return rjson::to_string(value_); }
std::string pretty() const { return rjson::pretty(value_); }
void read_from_file(std::string filename) { value_ = rjson::parse_file(filename); }
void update_from_file(std::string filename) { value_.update(rjson::parse_file(filename)); }
void write_to_file(std::string filename) const { file::write(filename, static_cast<std::string_view>(rjson::pretty(value_))); }
protected:
rjson::value& set() override { if (value_.is_null()) value_ = rjson::object{}; return value_; }
const rjson::value& get() const override { return value_; }
private:
rjson::value value_;
};
// --------------------------------------------------
class object : public object_base
{
public:
object(base& parent) : parent_(parent) {}
std::string path() const override { return parent_.path(); }
protected:
rjson::value& set() override { auto& val = parent_.set(); if (val.is_null()) val = rjson::object{}; return val; }
const rjson::value& get() const override { return parent_.get(); }
private:
base& parent_;
friend inline std::ostream& operator<<(std::ostream& out, const object& obj) { return out << obj.get(); }
};
// --------------------------------------------------
template <typename T> class array_basic : public container
{
public:
array_basic(base& parent) : parent_(parent) {}
std::string path() const override { return parent_.path(); }
// void inject_default() override { std::for_each(content_.begin(), content_.end(), [](T& elt) { elt.inject_default(); }); }
void inject_default() override {}
bool empty() const { return parent_.get().empty(); }
size_t size() const { return parent_.get().size(); }
T operator[](size_t index) const { return get()[index]; }
rjson::value& operator[](size_t index) { return set()[index]; }
T append(const T& to_append) { return set().append(to_append); }
void clear() { set().clear(); }
protected:
rjson::value& set() override { auto& val = parent_.set(); if (val.is_null()) val = rjson::array{}; return val; }
const rjson::value& get() const override { return parent_.get(); }
private:
base& parent_;
friend inline std::ostream& operator<<(std::ostream& out, const array_basic<T>& arr) { return out << arr.get(); }
};
// --------------------------------------------------
template <typename T> class const_array_element : public base
{
public:
const_array_element(const rjson::value& val, std::string path) : value_(const_cast<rjson::value&>(val)), content_(*this), path_(path) {}
const_array_element(const const_array_element& src) : value_(src.value_), content_(*this), path_(src.path_) {}
const_array_element(const_array_element&& src) : value_(std::move(src.value_)), content_(*this), path_(std::move(src.path_)) {}
const_array_element& operator=(const const_array_element& src) { value_ = src.value_; path_ = src.path_; }
const_array_element& operator=(const_array_element&& src) { value_ = std::move(src.value_); path_ = std::move(src.path_); }
std::string path() const override { return path_; }
void inject_default() override {}
const T& operator*() const { return content_; }
const T* operator->() const { return &content_; }
protected:
rjson::value& set() override { return value_; }
const rjson::value& get() const override { return value_; }
T& content() { return content_; }
private:
std::reference_wrapper<rjson::value> value_;
T content_;
std::string path_;
friend class object;
};
template <typename T> class array_element : public const_array_element<T>
{
public:
using const_array_element<T>::const_array_element;
using const_array_element<T>::operator*;
using const_array_element<T>::operator->;
void inject_default() override { const_array_element<T>::content().inject_default(); }
T& operator*() { return const_array_element<T>::content(); }
T* operator->() { return &const_array_element<T>::content(); }
};
template <typename T> class array : public container
{
public:
array(base& parent) : parent_(parent) {}
std::string path() const override { return parent_.path(); }
void inject_default() override {}
bool empty() const { return parent_.get().empty(); }
size_t size() const { return parent_.get().size(); }
const_array_element<T> operator[](size_t index) const { return {get()[index], make_element_path(index)}; }
array_element<T> operator[](size_t index) { return {set()[index], make_element_path(index)}; }
array_element<T> append() { const size_t index = size(); array_element<T> res(set().append(rjson::object{}), make_element_path(index)); res.inject_default(); return res; }
void clear() { set().clear(); }
template <typename F> std::optional<array_element<T>> find(F func) const;
protected:
rjson::value& set() override { auto& val = parent_.set(); if (val.is_null()) val = rjson::array{}; return val; }
const rjson::value& get() const override { return parent_.get(); }
private:
base& parent_;
std::string make_element_path(size_t index) { return path() + '[' + std::to_string(index) + ']'; }
friend inline std::ostream& operator<<(std::ostream& out, const array_basic<T>& arr) { return out << arr.get(); }
};
// --------------------------------------------------
template <typename T> class field : public field_base
{
public:
field(object_base* parent, const char* name, T&& default_value) : field_base(*parent, name), default_(std::forward<T>(default_value)) { }
field(object_base* parent, const char* name) : field_base(*parent, name) { }
void inject_default() override;
field& operator=(const T& source);
operator T() const;
private:
std::optional<T> default_;
};
template <typename T> inline std::ostream& operator<<(std::ostream& out, const field<T>& fld) { return out << static_cast<T>(fld); }
// --------------------------------------------------
// T must be derived from object
template <typename T> class field_object : public field_base
{
public:
field_object(object_base* parent, const char* name) : field_base(*parent, name), content_(*this) {}
void inject_default() override { content_.inject_default(); }
T& operator*() { return content_; }
const T& operator*() const { return content_; }
T* operator->() { return &content_; }
const T* operator->() const { return &content_; }
private:
T content_;
};
template <typename T> inline std::ostream& operator<<(std::ostream& out, const field_object<T>& fld) { return out << *fld; }
// --------------------------------------------------
template <typename T> class field_array : public field_base
{
public:
field_array(object_base* parent, const char* name) : field_base(*parent, name), content_(*this) {}
field_array(object_base* parent, const char* name, std::initializer_list<T> init) : field_base(*parent, name), content_(*this), default_{init} {}
void inject_default() override;
bool empty() const { return content_.empty(); }
size_t size() const { return content_.size(); }
T operator[](size_t index) const { return content_[index]; }
void append(const T& to_append) { content_.append(to_append); }
void append() { content_.append({}); }
void clear() { content_.clear(); }
array_basic<T>& operator*() { return content_; }
const array_basic<T>& operator*() const { return content_; }
private:
array_basic<T> content_;
std::vector<T> default_;
};
template <typename T> inline std::ostream& operator<<(std::ostream& out, const field_array<T>& fld) { return out << *fld; }
// --------------------------------------------------
template <typename T> class field_array_of : public field_base
{
public:
field_array_of(object_base* parent, const char* name) : field_base(*parent, name), content_(*this) {}
void inject_default() override {}
bool empty() const { return content_.empty(); }
size_t size() const { return content_.size(); }
array_element<T> operator[](size_t index) { return content_[index]; }
array_element<T> operator[](size_t index) const { return content_[index]; }
array_element<T> append() { return content_.append(); }
void clear() { content_.clear(); }
array<T>& operator*() { return content_; }
const array<T>& operator*() const { return content_; }
private:
array<T> content_;
};
// **********************************************************************
// implementation
// **********************************************************************
inline void object_base::inject_default()
{
std::for_each(fields_.begin(), fields_.end(), [](field_base* fld) { fld->inject_default(); });
}
template <typename T> inline void field<T>::inject_default()
{
if (default_) {
if (auto& val = set(); val.is_null())
val = *default_;
}
}
template <typename T> inline field<T>& field<T>::operator=(const T& source)
{
set() = source;
return *this;
}
template <typename T> inline field<T>::operator T() const
{
if (auto& val = get(); !val.is_null()) {
if constexpr (std::is_same_v<std::decay_t<T>, bool>)
return val.get_bool();
else
return val;
}
else if (default_)
return *default_;
else
throw not_set(path());
}
template <typename T> inline void field_array<T>::inject_default()
{
if (empty() && !default_.empty()) {
for (const T& val : default_)
append(val);
}
}
} // namespace v1
} // namespace acmacs::settings
// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<|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.
*/
/*
* $Id$
*/
#include <xercesc/framework/LocalFileFormatTarget.hpp>
#include <xercesc/framework/MemoryManager.hpp>
#include <xercesc/util/IOException.hpp>
#include <xercesc/util/OutOfMemoryException.hpp>
#include <assert.h>
#include <string.h>
XERCES_CPP_NAMESPACE_BEGIN
const XMLSize_t MAX_BUFFER_SIZE = 65536;
LocalFileFormatTarget::LocalFileFormatTarget( const XMLCh* const fileName
, MemoryManager* const manager)
: fSource(0)
, fDataBuf(0)
, fIndex(0)
, fCapacity(1024)
, fMemoryManager(manager)
{
fSource = XMLPlatformUtils::openFileToWrite(fileName, manager);
if (fSource == (FileHandle) XERCES_Invalid_File_Handle)
ThrowXMLwithMemMgr1(IOException, XMLExcepts::File_CouldNotOpenFile, fileName, fMemoryManager);
fDataBuf = (XMLByte*) fMemoryManager->allocate (
fCapacity * sizeof(XMLByte));
}
LocalFileFormatTarget::LocalFileFormatTarget( const char* const fileName
, MemoryManager* const manager)
: fSource(0)
, fDataBuf(0)
, fIndex(0)
, fCapacity(1024)
, fMemoryManager(manager)
{
fSource = XMLPlatformUtils::openFileToWrite(fileName, manager);
if (fSource == (FileHandle) XERCES_Invalid_File_Handle)
ThrowXMLwithMemMgr1(IOException, XMLExcepts::File_CouldNotOpenFile, fileName, fMemoryManager);
fDataBuf = (XMLByte*) fMemoryManager->allocate (
fCapacity * sizeof(XMLByte));
}
LocalFileFormatTarget::~LocalFileFormatTarget()
{
try
{
// flush remaining buffer before destroy
XMLPlatformUtils::writeBufferToFile(fSource, fIndex, fDataBuf, fMemoryManager);
if (fSource)
XMLPlatformUtils::closeFile(fSource, fMemoryManager);
}
catch (...)
{
// There is nothing we can do about it here.
}
fMemoryManager->deallocate(fDataBuf);//delete [] fDataBuf;
}
void LocalFileFormatTarget::flush()
{
XMLPlatformUtils::writeBufferToFile(fSource, fIndex, fDataBuf, fMemoryManager);
fIndex = 0;
}
void LocalFileFormatTarget::writeChars(const XMLByte* const toWrite
, const XMLSize_t count
, XMLFormatter * const)
{
if (count)
{
if (count < MAX_BUFFER_SIZE)
{
// If we don't have enough space, see if we can grow the buffer.
//
if (fIndex + count > fCapacity && fCapacity < MAX_BUFFER_SIZE)
insureCapacity (count);
// If still not enough space, flush the buffer.
//
if (fIndex + count > fCapacity)
{
XMLPlatformUtils::writeBufferToFile(fSource, fIndex, fDataBuf, fMemoryManager);
fIndex = 0;
}
memcpy(&fDataBuf[fIndex], toWrite, count * sizeof(XMLByte));
fIndex += count;
}
else
XMLPlatformUtils::writeBufferToFile(fSource, count, toWrite, fMemoryManager);
}
return;
}
void LocalFileFormatTarget::insureCapacity(const XMLSize_t extraNeeded)
{
XMLSize_t newCap = fCapacity * 2;
while (fIndex + extraNeeded > newCap)
newCap *= 2;
XMLByte* newBuf = (XMLByte*) fMemoryManager->allocate (
newCap * sizeof(XMLByte));
// Copy over the old stuff
memcpy(newBuf, fDataBuf, fIndex * sizeof(XMLByte));
// Clean up old buffer and store new stuff
fMemoryManager->deallocate(fDataBuf);
fDataBuf = newBuf;
fCapacity = newCap;
}
XERCES_CPP_NAMESPACE_END
<commit_msg>Fix a bug in the new LocalFileFormatTarget buffering implementation.<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.
*/
/*
* $Id$
*/
#include <xercesc/framework/LocalFileFormatTarget.hpp>
#include <xercesc/framework/MemoryManager.hpp>
#include <xercesc/util/IOException.hpp>
#include <xercesc/util/OutOfMemoryException.hpp>
#include <assert.h>
#include <string.h>
XERCES_CPP_NAMESPACE_BEGIN
const XMLSize_t MAX_BUFFER_SIZE = 65536;
LocalFileFormatTarget::LocalFileFormatTarget( const XMLCh* const fileName
, MemoryManager* const manager)
: fSource(0)
, fDataBuf(0)
, fIndex(0)
, fCapacity(1024)
, fMemoryManager(manager)
{
fSource = XMLPlatformUtils::openFileToWrite(fileName, manager);
if (fSource == (FileHandle) XERCES_Invalid_File_Handle)
ThrowXMLwithMemMgr1(IOException, XMLExcepts::File_CouldNotOpenFile, fileName, fMemoryManager);
fDataBuf = (XMLByte*) fMemoryManager->allocate (
fCapacity * sizeof(XMLByte));
}
LocalFileFormatTarget::LocalFileFormatTarget( const char* const fileName
, MemoryManager* const manager)
: fSource(0)
, fDataBuf(0)
, fIndex(0)
, fCapacity(1024)
, fMemoryManager(manager)
{
fSource = XMLPlatformUtils::openFileToWrite(fileName, manager);
if (fSource == (FileHandle) XERCES_Invalid_File_Handle)
ThrowXMLwithMemMgr1(IOException, XMLExcepts::File_CouldNotOpenFile, fileName, fMemoryManager);
fDataBuf = (XMLByte*) fMemoryManager->allocate (
fCapacity * sizeof(XMLByte));
}
LocalFileFormatTarget::~LocalFileFormatTarget()
{
try
{
// flush remaining buffer before destroy
XMLPlatformUtils::writeBufferToFile(fSource, fIndex, fDataBuf, fMemoryManager);
if (fSource)
XMLPlatformUtils::closeFile(fSource, fMemoryManager);
}
catch (...)
{
// There is nothing we can do about it here.
}
fMemoryManager->deallocate(fDataBuf);//delete [] fDataBuf;
}
void LocalFileFormatTarget::flush()
{
XMLPlatformUtils::writeBufferToFile(fSource, fIndex, fDataBuf, fMemoryManager);
fIndex = 0;
}
void LocalFileFormatTarget::writeChars(const XMLByte* const toWrite
, const XMLSize_t count
, XMLFormatter * const)
{
if (count)
{
if (count < MAX_BUFFER_SIZE)
{
// If we don't have enough space, see if we can grow the buffer.
//
if (fIndex + count > fCapacity && fCapacity < MAX_BUFFER_SIZE)
insureCapacity (count);
// If still not enough space, flush the buffer.
//
if (fIndex + count > fCapacity)
{
XMLPlatformUtils::writeBufferToFile(fSource, fIndex, fDataBuf, fMemoryManager);
fIndex = 0;
}
memcpy(&fDataBuf[fIndex], toWrite, count * sizeof(XMLByte));
fIndex += count;
}
else
{
if (fIndex)
{
XMLPlatformUtils::writeBufferToFile(fSource, fIndex, fDataBuf, fMemoryManager);
fIndex = 0;
}
XMLPlatformUtils::writeBufferToFile(fSource, count, toWrite, fMemoryManager);
}
}
return;
}
void LocalFileFormatTarget::insureCapacity(const XMLSize_t extraNeeded)
{
XMLSize_t newCap = fCapacity * 2;
while (fIndex + extraNeeded > newCap)
newCap *= 2;
XMLByte* newBuf = (XMLByte*) fMemoryManager->allocate (
newCap * sizeof(XMLByte));
// Copy over the old stuff
memcpy(newBuf, fDataBuf, fIndex * sizeof(XMLByte));
// Clean up old buffer and store new stuff
fMemoryManager->deallocate(fDataBuf);
fDataBuf = newBuf;
fCapacity = newCap;
}
XERCES_CPP_NAMESPACE_END
<|endoftext|> |
<commit_before>/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil -*- */
/**
* Copyright (C) 2013 Regents of the University of California.
* @author: Jeff Thompson <jefft0@remap.ucla.edu>
* See COPYING for copyright and distribution information.
*/
#include <stdexcept>
#include "../security-exception.hpp"
#include "memory-identity-storage.hpp"
using namespace std;
using namespace ndn::ptr_lib;
namespace ndn {
MemoryIdentityStorage::~MemoryIdentityStorage()
{
}
bool
MemoryIdentityStorage::doesIdentityExist(const Name& identityName)
{
string identityUri = identityName.toUri();
return find(identityStore_.begin(), identityStore_.end(), identityUri) != identityStore_.end();
}
void
MemoryIdentityStorage::addIdentity(const Name& identityName)
{
string identityUri = identityName.toUri();
if (find(identityStore_.begin(), identityStore_.end(), identityUri) != identityStore_.end())
throw SecurityException("Identity already exists: " + identityUri);
identityStore_.push_back(identityUri);
}
bool
MemoryIdentityStorage::revokeIdentity()
{
#if 1
throw std::runtime_error("MemoryIdentityStorage::revokeIdentity not implemented");
#endif
}
Name
MemoryIdentityStorage::getNewKeyName(const Name& identityName, bool useKsk)
{
#if 1
throw std::runtime_error("MemoryIdentityStorage::getNewKeyName not implemented");
#endif
}
bool
MemoryIdentityStorage::doesKeyExist(const Name& keyName)
{
#if 1
throw std::runtime_error("MemoryIdentityStorage::doesKeyExist not implemented");
#endif
}
Name
MemoryIdentityStorage::getKeyNameForCertificate(const Name& certificateName)
{
int i = certificateName.getComponentCount() - 1;
for (; i >= 0; --i) {
if(certificateName.getComponent(i).toEscapedString() == string("ID-CERT"))
break;
}
return certificateName.getSubName(0, i);
}
void
MemoryIdentityStorage::addKey(const Name& keyName, KeyType keyType, const Blob& publicKeyDer)
{
#if 1
throw std::runtime_error("MemoryIdentityStorage::addKey not implemented");
#endif
}
Blob
MemoryIdentityStorage::getKey(const Name& keyName)
{
#if 1
throw std::runtime_error("MemoryIdentityStorage::getKey not implemented");
#endif
}
void
MemoryIdentityStorage::activateKey(const Name& keyName)
{
#if 1
throw std::runtime_error("MemoryIdentityStorage::activateKey not implemented");
#endif
}
void
MemoryIdentityStorage::deactivateKey(const Name& keyName)
{
#if 1
throw std::runtime_error("MemoryIdentityStorage::deactivateKey not implemented");
#endif
}
bool
MemoryIdentityStorage::doesCertificateExist(const Name& certificateName)
{
#if 1
throw std::runtime_error("MemoryIdentityStorage::doesCertificateExist not implemented");
#endif
}
void
MemoryIdentityStorage::addCertificate(const Certificate& certificate)
{
#if 1
throw std::runtime_error("MemoryIdentityStorage::addCertificate not implemented");
#endif
}
ptr_lib::shared_ptr<Certificate>
MemoryIdentityStorage::getCertificate(const Name &certificateName, bool allowAny)
{
#if 1
throw std::runtime_error("MemoryIdentityStorage::getCertificate not implemented");
#endif
}
Name
MemoryIdentityStorage::getDefaultIdentity()
{
return Name(defaultIdentity_);
}
Name
MemoryIdentityStorage::getDefaultKeyNameForIdentity(const Name& identityName)
{
#if 1
throw std::runtime_error("MemoryIdentityStorage::getDefaultKeyNameForIdentity not implemented");
#endif
}
Name
MemoryIdentityStorage::getDefaultCertificateNameForKey(const Name& keyName)
{
#if 1
throw std::runtime_error("MemoryIdentityStorage::getDefaultCertificateNameForKey not implemented");
#endif
}
void
MemoryIdentityStorage::setDefaultIdentity(const Name& identityName)
{
string identityUri = identityName.toUri();
if (find(identityStore_.begin(), identityStore_.end(), identityUri) != identityStore_.end())
defaultIdentity_ = identityUri;
else
// The identity doesn't exist, so clear the default.
defaultIdentity_.clear();
}
void
MemoryIdentityStorage::setDefaultKeyNameForIdentity(const Name& keyName, const Name& identityName)
{
#if 1
throw std::runtime_error("MemoryIdentityStorage::setDefaultKeyNameForIdentity not implemented");
#endif
}
void
MemoryIdentityStorage::setDefaultCertificateNameForKey(const Name& keyName, const Name& certificateName)
{
#if 1
throw std::runtime_error("MemoryIdentityStorage::setDefaultCertificateNameForKey not implemented");
#endif
}
}
<commit_msg>security: Need to include <algorithm> to get find function.<commit_after>/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil -*- */
/**
* Copyright (C) 2013 Regents of the University of California.
* @author: Jeff Thompson <jefft0@remap.ucla.edu>
* See COPYING for copyright and distribution information.
*/
#if 1
#include <stdexcept>
#endif
#include <algorithm>
#include "../security-exception.hpp"
#include "memory-identity-storage.hpp"
using namespace std;
using namespace ndn::ptr_lib;
namespace ndn {
MemoryIdentityStorage::~MemoryIdentityStorage()
{
}
bool
MemoryIdentityStorage::doesIdentityExist(const Name& identityName)
{
string identityUri = identityName.toUri();
return find(identityStore_.begin(), identityStore_.end(), identityUri) != identityStore_.end();
}
void
MemoryIdentityStorage::addIdentity(const Name& identityName)
{
string identityUri = identityName.toUri();
if (find(identityStore_.begin(), identityStore_.end(), identityUri) != identityStore_.end())
throw SecurityException("Identity already exists: " + identityUri);
identityStore_.push_back(identityUri);
}
bool
MemoryIdentityStorage::revokeIdentity()
{
#if 1
throw std::runtime_error("MemoryIdentityStorage::revokeIdentity not implemented");
#endif
}
Name
MemoryIdentityStorage::getNewKeyName(const Name& identityName, bool useKsk)
{
#if 1
throw std::runtime_error("MemoryIdentityStorage::getNewKeyName not implemented");
#endif
}
bool
MemoryIdentityStorage::doesKeyExist(const Name& keyName)
{
#if 1
throw std::runtime_error("MemoryIdentityStorage::doesKeyExist not implemented");
#endif
}
Name
MemoryIdentityStorage::getKeyNameForCertificate(const Name& certificateName)
{
int i = certificateName.getComponentCount() - 1;
for (; i >= 0; --i) {
if(certificateName.getComponent(i).toEscapedString() == string("ID-CERT"))
break;
}
return certificateName.getSubName(0, i);
}
void
MemoryIdentityStorage::addKey(const Name& keyName, KeyType keyType, const Blob& publicKeyDer)
{
#if 1
throw std::runtime_error("MemoryIdentityStorage::addKey not implemented");
#endif
}
Blob
MemoryIdentityStorage::getKey(const Name& keyName)
{
#if 1
throw std::runtime_error("MemoryIdentityStorage::getKey not implemented");
#endif
}
void
MemoryIdentityStorage::activateKey(const Name& keyName)
{
#if 1
throw std::runtime_error("MemoryIdentityStorage::activateKey not implemented");
#endif
}
void
MemoryIdentityStorage::deactivateKey(const Name& keyName)
{
#if 1
throw std::runtime_error("MemoryIdentityStorage::deactivateKey not implemented");
#endif
}
bool
MemoryIdentityStorage::doesCertificateExist(const Name& certificateName)
{
#if 1
throw std::runtime_error("MemoryIdentityStorage::doesCertificateExist not implemented");
#endif
}
void
MemoryIdentityStorage::addCertificate(const Certificate& certificate)
{
#if 1
throw std::runtime_error("MemoryIdentityStorage::addCertificate not implemented");
#endif
}
ptr_lib::shared_ptr<Certificate>
MemoryIdentityStorage::getCertificate(const Name &certificateName, bool allowAny)
{
#if 1
throw std::runtime_error("MemoryIdentityStorage::getCertificate not implemented");
#endif
}
Name
MemoryIdentityStorage::getDefaultIdentity()
{
return Name(defaultIdentity_);
}
Name
MemoryIdentityStorage::getDefaultKeyNameForIdentity(const Name& identityName)
{
#if 1
throw std::runtime_error("MemoryIdentityStorage::getDefaultKeyNameForIdentity not implemented");
#endif
}
Name
MemoryIdentityStorage::getDefaultCertificateNameForKey(const Name& keyName)
{
#if 1
throw std::runtime_error("MemoryIdentityStorage::getDefaultCertificateNameForKey not implemented");
#endif
}
void
MemoryIdentityStorage::setDefaultIdentity(const Name& identityName)
{
string identityUri = identityName.toUri();
if (find(identityStore_.begin(), identityStore_.end(), identityUri) != identityStore_.end())
defaultIdentity_ = identityUri;
else
// The identity doesn't exist, so clear the default.
defaultIdentity_.clear();
}
void
MemoryIdentityStorage::setDefaultKeyNameForIdentity(const Name& keyName, const Name& identityName)
{
#if 1
throw std::runtime_error("MemoryIdentityStorage::setDefaultKeyNameForIdentity not implemented");
#endif
}
void
MemoryIdentityStorage::setDefaultCertificateNameForKey(const Name& keyName, const Name& certificateName)
{
#if 1
throw std::runtime_error("MemoryIdentityStorage::setDefaultCertificateNameForKey not implemented");
#endif
}
}
<|endoftext|> |
<commit_before>/**
* @file joint_limits.cpp
* @brief This defines a joint limit filter.
*
* @author Jorge Nicho
* @date April 1, 2016
* @version TODO
* @bug No known bugs
*
* @copyright Copyright (c) 2016, Southwest Research Institute
*
* @par License
* Software License Agreement (Apache License)
* @par
* 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
* @par
* 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 <ros/console.h>
#include <pluginlib/class_list_macros.h>
#include <moveit/robot_state/conversions.h>
#include <stomp_moveit/noisy_filters/joint_limits.h>
PLUGINLIB_EXPORT_CLASS(stomp_moveit::noisy_filters::JointLimits,stomp_moveit::noisy_filters::StompNoisyFilter);
namespace stomp_moveit
{
namespace noisy_filters
{
JointLimits::JointLimits():
lock_start_(true),
lock_goal_(true)
{
// TODO Auto-generated constructor stub
}
JointLimits::~JointLimits()
{
// TODO Auto-generated destructor stub
}
bool JointLimits::initialize(moveit::core::RobotModelConstPtr robot_model_ptr,
const std::string& group_name,const XmlRpc::XmlRpcValue& config)
{
using namespace moveit::core;
robot_model_ = robot_model_ptr;
group_name_ = group_name;
// creating states
start_state_.reset(new RobotState(robot_model_));
goal_state_.reset(new RobotState(robot_model_));
return configure(config);
}
bool JointLimits::configure(const XmlRpc::XmlRpcValue& config)
{
// check parameter presence
auto members = {"lock_start","lock_goal"};
for(auto& m : members)
{
if(!config.hasMember(m))
{
ROS_ERROR("%s failed to find one or more required parameters",getName().c_str());
return false;
}
}
try
{
XmlRpc::XmlRpcValue c = config;
lock_start_ = static_cast<bool>(c["lock_start"]);
lock_goal_ = static_cast<bool>(c["lock_goal"]);
}
catch(XmlRpc::XmlRpcException& e)
{
ROS_ERROR("JointLimits plugin failed to load parameters %s",e.getMessage().c_str());
return false;
}
return true;
}
bool JointLimits::setMotionPlanRequest(const planning_scene::PlanningSceneConstPtr& planning_scene,
const moveit_msgs::MotionPlanRequest &req,
const stomp_core::StompConfiguration &config,
moveit_msgs::MoveItErrorCodes& error_code)
{
using namespace moveit::core;
error_code.val = error_code.val | moveit_msgs::MoveItErrorCodes::SUCCESS;
// saving start state
if(!robotStateMsgToRobotState(req.start_state,*start_state_))
{
ROS_ERROR_STREAM("Failed to save start state");
return false;
}
if(!start_state_->satisfiesBounds(robot_model_->getJointModelGroup(group_name_)))
{
ROS_WARN("%s Requested Start State is out of bounds",getName().c_str());
}
// saving goal state
if(lock_goal_)
{
bool goal_state_saved = false;
for(auto& gc: req.goal_constraints)
{
for(auto& jc : gc.joint_constraints)
{
goal_state_->setVariablePosition(jc.joint_name,jc.position);
goal_state_saved = true;
}
if(!goal_state_->satisfiesBounds(robot_model_->getJointModelGroup(group_name_)))
{
ROS_WARN("%s Requested Goal State is out of bounds",getName().c_str());
}
break;
}
if(!goal_state_saved)
{
ROS_ERROR_STREAM("Failed to save goal state");
return false;
}
}
return true;
}
bool JointLimits::filter(std::size_t start_timestep,std::size_t num_timesteps,
int iteration_number,int rollout_number,Eigen::MatrixXd& parameters,bool& filtered)
{
using namespace moveit::core;
filtered = false;
const JointModelGroup* joint_group = robot_model_->getJointModelGroup(group_name_);
const std::vector<const JointModel*>& joint_models = joint_group->getActiveJointModels();
std::size_t num_joints = joint_group->getActiveJointModelNames().size();
if(parameters.rows() != num_joints)
{
ROS_ERROR("Incorrect number of joints in the 'parameters' matrix");
return false;
}
if(lock_start_)
{
for(auto j = 0u; j < num_joints; j++)
{
parameters(j,0) = *start_state_->getJointPositions(joint_models[j]);
}
filtered = true;
}
if(lock_goal_)
{
auto last_index = parameters.cols()-1;
for(auto j = 0u; j < num_joints; j++)
{
parameters(j,last_index) = *goal_state_->getJointPositions(joint_models[j]);
}
filtered = true;
}
double val;
for (auto j = 0u; j < num_joints; ++j)
{
for (auto t=0u; t< parameters.cols(); ++t)
{
val = parameters(j,t);
if(joint_models[j]->enforcePositionBounds(&val))
{
parameters(j,t) = val;
filtered = true;
}
}
}
return true;
}
} /* namespace filters */
} /* namespace stomp_moveit */
<commit_msg>Only enforce goal constraints if defined in joint space<commit_after>/**
* @file joint_limits.cpp
* @brief This defines a joint limit filter.
*
* @author Jorge Nicho
* @date April 1, 2016
* @version TODO
* @bug No known bugs
*
* @copyright Copyright (c) 2016, Southwest Research Institute
*
* @par License
* Software License Agreement (Apache License)
* @par
* 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
* @par
* 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 <ros/console.h>
#include <pluginlib/class_list_macros.h>
#include <moveit/robot_state/conversions.h>
#include <stomp_moveit/noisy_filters/joint_limits.h>
PLUGINLIB_EXPORT_CLASS(stomp_moveit::noisy_filters::JointLimits,stomp_moveit::noisy_filters::StompNoisyFilter);
namespace stomp_moveit
{
namespace noisy_filters
{
JointLimits::JointLimits():
lock_start_(true),
lock_goal_(true)
{
// TODO Auto-generated constructor stub
}
JointLimits::~JointLimits()
{
// TODO Auto-generated destructor stub
}
bool JointLimits::initialize(moveit::core::RobotModelConstPtr robot_model_ptr,
const std::string& group_name,const XmlRpc::XmlRpcValue& config)
{
using namespace moveit::core;
robot_model_ = robot_model_ptr;
group_name_ = group_name;
// creating states
start_state_.reset(new RobotState(robot_model_));
goal_state_.reset(new RobotState(robot_model_));
return configure(config);
}
bool JointLimits::configure(const XmlRpc::XmlRpcValue& config)
{
// check parameter presence
auto members = {"lock_start","lock_goal"};
for(auto& m : members)
{
if(!config.hasMember(m))
{
ROS_ERROR("%s failed to find one or more required parameters",getName().c_str());
return false;
}
}
try
{
XmlRpc::XmlRpcValue c = config;
lock_start_ = static_cast<bool>(c["lock_start"]);
lock_goal_ = static_cast<bool>(c["lock_goal"]);
}
catch(XmlRpc::XmlRpcException& e)
{
ROS_ERROR("JointLimits plugin failed to load parameters %s",e.getMessage().c_str());
return false;
}
return true;
}
bool JointLimits::setMotionPlanRequest(const planning_scene::PlanningSceneConstPtr& planning_scene,
const moveit_msgs::MotionPlanRequest &req,
const stomp_core::StompConfiguration &config,
moveit_msgs::MoveItErrorCodes& error_code)
{
using namespace moveit::core;
error_code.val = error_code.val | moveit_msgs::MoveItErrorCodes::SUCCESS;
// saving start state
if(!robotStateMsgToRobotState(req.start_state,*start_state_))
{
ROS_ERROR_STREAM("Failed to save start state");
return false;
}
if(!start_state_->satisfiesBounds(robot_model_->getJointModelGroup(group_name_), 0.01))
{
ROS_WARN("%s Requested Start State is out of bounds",getName().c_str());
}
// saving goal state
if(lock_goal_)
{
bool goal_state_saved = false;
for(auto& gc: req.goal_constraints)
{
for(auto& jc : gc.joint_constraints)
{
goal_state_->setVariablePosition(jc.joint_name,jc.position);
goal_state_saved = true;
}
if(not gc.joint_constraints.empty())
{
if(!goal_state_->satisfiesBounds(robot_model_->getJointModelGroup(group_name_), 0.1))
{
ROS_WARN("%s Requested Goal State is out of bounds",getName().c_str());
break;
}
}
}
if(!goal_state_saved)
{
ROS_ERROR_STREAM("Failed to save goal state");
return false;
}
}
return true;
}
bool JointLimits::filter(std::size_t start_timestep,std::size_t num_timesteps,
int iteration_number,int rollout_number,Eigen::MatrixXd& parameters,bool& filtered)
{
using namespace moveit::core;
filtered = false;
const JointModelGroup* joint_group = robot_model_->getJointModelGroup(group_name_);
const std::vector<const JointModel*>& joint_models = joint_group->getActiveJointModels();
std::size_t num_joints = joint_group->getActiveJointModelNames().size();
if(parameters.rows() != num_joints)
{
ROS_ERROR("Incorrect number of joints in the 'parameters' matrix");
return false;
}
if(lock_start_)
{
for(auto j = 0u; j < num_joints; j++)
{
parameters(j,0) = *start_state_->getJointPositions(joint_models[j]);
}
filtered = true;
}
if(lock_goal_)
{
auto last_index = parameters.cols()-1;
for(auto j = 0u; j < num_joints; j++)
{
parameters(j,last_index) = *goal_state_->getJointPositions(joint_models[j]);
}
filtered = true;
}
double val;
for (auto j = 0u; j < num_joints; ++j)
{
for (auto t=0u; t< parameters.cols(); ++t)
{
val = parameters(j,t);
if(joint_models[j]->enforcePositionBounds(&val))
{
parameters(j,t) = val;
filtered = true;
}
}
}
return true;
}
} /* namespace filters */
} /* namespace stomp_moveit */
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: viewcontactofpageobj.cxx,v $
*
* $Revision: 1.13 $
*
* last change: $Author: hr $ $Date: 2007-06-26 12:06:06 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svx.hxx"
#ifndef _SDR_CONTACT_VIEWCONTACTOFPAGEOBJ_HXX
#include <svx/sdr/contact/viewcontactofpageobj.hxx>
#endif
#ifndef _SVDOPAGE_HXX
#include <svdopage.hxx>
#endif
#ifndef _SDR_CONTACT_DISPLAYINFO_HXX
#include <svx/sdr/contact/displayinfo.hxx>
#endif
#ifndef _SV_OUTDEV_HXX
#include <vcl/outdev.hxx>
#endif
#ifndef _SVDMODEL_HXX
#include <svdmodel.hxx>
#endif
#ifndef _SVDPAGE_HXX
#include <svdpage.hxx>
#endif
#ifndef _SDR_CONTACT_OBJECTCONTACTOFOBJLISTPAINTER_HXX
#include <svx/sdr/contact/objectcontactofobjlistpainter.hxx>
#endif
#ifndef _XOUTX_HXX
#include <xoutx.hxx>
#endif
#ifndef _SDR_CONTACT_VIEWOBJECTCONTACT_HXX
#include <svx/sdr/contact/viewobjectcontact.hxx>
#endif
//////////////////////////////////////////////////////////////////////////////
// Own PagePainter which takes over initialisation tasks
namespace sdr
{
namespace contact
{
class OCOfPageObjPagePainter : public ObjectContactOfPagePainter
{
protected:
Rectangle maDestinationRectangle;
Point maTranslate;
Fraction maScaleX;
Fraction maScaleY;
ViewContact& mrUserViewContact;
public:
// basic constructor
OCOfPageObjPagePainter(const SdrPage* pPage, ViewContact& rUserViewContact);
// The destructor. When PrepareDelete() was not called before (see there)
// warnings will be generated in debug version if there are still contacts
// existing.
virtual ~OCOfPageObjPagePainter();
// Own paint
sal_Bool PaintIt(DisplayInfo& rDisplayInfo, const Rectangle& rDestinationRectangle);
// Own reaction on changes
virtual void InvalidatePartOfView(const Rectangle& rRectangle) const;
};
//////////////////////////////////////////////////////////////////////////////
// Implementation
OCOfPageObjPagePainter::OCOfPageObjPagePainter(const SdrPage* pPage, ViewContact& rUserViewContact)
: ObjectContactOfPagePainter(pPage),
mrUserViewContact(rUserViewContact)
{
// #i71130# Mark this view as preview renderer
mbIsPreviewRenderer = true;
}
OCOfPageObjPagePainter::~OCOfPageObjPagePainter()
{
}
sal_Bool OCOfPageObjPagePainter::PaintIt(DisplayInfo& rDisplayInfo, const Rectangle& rDestinationRectangle)
{
// save old clipping from OutDev
sal_Bool bRetval(sal_False);
OutputDevice* pOut = rDisplayInfo.GetOutputDevice();
maDestinationRectangle = rDestinationRectangle;
if(pOut)
{
// remap sizes. Destination size is size of rPaintRectangle,
// source size is the page size.
MapMode aOldMapMode = pOut->GetMapMode();
// calc translation
maTranslate = Point(maDestinationRectangle.TopLeft() + aOldMapMode.GetOrigin());
// calc scaling
maScaleX = Fraction(maDestinationRectangle.GetWidth(), mpStartPage->GetWdt());
maScaleY = Fraction(maDestinationRectangle.GetHeight(), mpStartPage->GetHgt());
// save clipping
sal_Bool bRememberedClipping(pOut->IsClipRegion());
Region aRememberedClipping;
if(bRememberedClipping)
{
aRememberedClipping = pOut->GetClipRegion();
}
// add clipping against object bounds
pOut->IntersectClipRegion(maDestinationRectangle);
// change origin
MapMode aNewMapMode(pOut->GetMapMode());
aNewMapMode.SetOrigin(maTranslate);
pOut->SetMapMode(aNewMapMode);
// change scaling
Point aEmptyPoint;
pOut->SetMapMode(MapMode(MAP_RELATIVE, aEmptyPoint, maScaleX, maScaleY));
// create copy of DisplayInfo. Do copy PageView to have it available at
// included page painting.
DisplayInfo aDisplayInfo(rDisplayInfo.GetPageView());
aDisplayInfo.SetExtendedOutputDevice(rDisplayInfo.GetExtendedOutputDevice());
aDisplayInfo.SetPaintInfoRec(rDisplayInfo.GetPaintInfoRec());
aDisplayInfo.SetOutputDevice(pOut);
// make MasterPages visible
aDisplayInfo.SetPagePainting(sal_True); // #i72889#
// do processing
ProcessDisplay(aDisplayInfo);
// restore original MapMode
pOut->SetMapMode(aOldMapMode);
// restore remembered clipping
if(bRememberedClipping)
{
pOut->SetClipRegion(aRememberedClipping);
}
else
{
pOut->SetClipRegion();
}
}
return bRetval;
}
void OCOfPageObjPagePainter::InvalidatePartOfView(const Rectangle& /*rRectangle*/) const
{
// call user change
mrUserViewContact.ActionChanged();
}
} // end of namespace contact
} // end of namespace sdr
//////////////////////////////////////////////////////////////////////////////
namespace sdr
{
namespace contact
{
// Access to referenced page
const SdrPage* ViewContactOfPageObj::GetReferencedPage() const
{
return GetPageObj().GetReferencedPage();
}
// method to recalculate the PaintRectangle if the validity flag shows that
// it is invalid. The flag is set from GetPaintRectangle, thus the implementation
// only needs to refresh maPaintRectangle itself.
void ViewContactOfPageObj::CalcPaintRectangle()
{
maPaintRectangle = GetPageObj().GetCurrentBoundRect();
}
// get rid of evtl. remembered PagePainter
void ViewContactOfPageObj::GetRidOfPagePainter()
{
if(mpPagePainter)
{
mpPagePainter->PrepareDelete();
delete mpPagePainter;
mpPagePainter = 0L;
}
}
// Prepare a PagePainter for current referenced page. This may
// refresh, create or delete a PagePainter instance in
// mpPagePainter
void ViewContactOfPageObj::PreparePagePainter(const SdrPage* pPage)
{
if(pPage)
{
if(mpPagePainter)
{
mpPagePainter->SetStartPage(pPage);
}
else
{
mpPagePainter = new OCOfPageObjPagePainter(pPage, *this);
}
}
else
{
GetRidOfPagePainter();
}
}
Rectangle ViewContactOfPageObj::GetPageRectangle (void)
{
CalcPaintRectangle();
return maPaintRectangle;
}
// Paint support methods for page content painting
sal_Bool ViewContactOfPageObj::PaintPageContents(
DisplayInfo& rDisplayInfo,
const Rectangle& rPaintRectangle,
const ViewObjectContact& /*rAssociatedVOC*/)
{
// Prepare page painter
sal_Bool bRetval(sal_False);
const SdrPage* pPage = GetReferencedPage();
PreparePagePainter(pPage);
if(mpPagePainter)
{
bRetval = mpPagePainter->PaintIt(rDisplayInfo, rPaintRectangle);
}
return bRetval;
}
sal_Bool ViewContactOfPageObj::PaintPageReplacement(
DisplayInfo& rDisplayInfo,
const Rectangle& rPaintRectangle,
const ViewObjectContact& /*rAssociatedVOC*/)
{
// If painting recursive, paint a replacement visualization
OutputDevice* pOut = rDisplayInfo.GetOutputDevice();
svtools::ColorConfigValue aDocColor(
rDisplayInfo.GetColorConfig().GetColorValue(svtools::DOCCOLOR));
svtools::ColorConfigValue aBorderColor(
rDisplayInfo.GetColorConfig().GetColorValue(svtools::DOCBOUNDARIES));
pOut->SetFillColor(aDocColor.nColor);
pOut->SetLineColor(aBorderColor.bIsVisible ? aBorderColor.nColor: aDocColor.nColor);
pOut->DrawRect(rPaintRectangle);
return sal_True;
}
sal_Bool ViewContactOfPageObj::PaintPageBorder(
DisplayInfo& rDisplayInfo,
const Rectangle& rPaintRectangle,
const ViewObjectContact& /*rAssociatedVOC*/)
{
OutputDevice* pOut = rDisplayInfo.GetOutputDevice();
sal_Bool bRetval(sal_False);
svtools::ColorConfigValue aFrameColor(
rDisplayInfo.GetColorConfig().GetColorValue(svtools::OBJECTBOUNDARIES));
if( aFrameColor.bIsVisible )
{
pOut->SetFillColor();
pOut->SetLineColor(aFrameColor.nColor);
pOut->DrawRect(rPaintRectangle);
bRetval = sal_True;
}
return bRetval;
}
// On StopGettingViewed the PagePainter can be dismissed.
void ViewContactOfPageObj::StopGettingViewed()
{
// call parent
ViewContactOfSdrObj::StopGettingViewed();
// dismiss PagePainter
GetRidOfPagePainter();
}
ViewContactOfPageObj::ViewContactOfPageObj(SdrPageObj& rPageObj)
: ViewContactOfSdrObj(rPageObj),
mpPagePainter(0L),
mbIsPainting(sal_False),
mbIsInActionChange(sal_False)
{
}
ViewContactOfPageObj::~ViewContactOfPageObj()
{
GetRidOfPagePainter();
}
// Paint this object. This is before evtl. SubObjects get painted. It needs to return
// sal_True when something was pained and the paint output rectangle in rPaintRectangle.
sal_Bool ViewContactOfPageObj::PaintObject(DisplayInfo& rDisplayInfo, Rectangle& rPaintRectangle, const ViewObjectContact& rAssociatedVOC)
{
sal_Bool bRetval(sal_False);
// get page to be displayed
const SdrPage* pPage = GetReferencedPage();
// avoid recursive painting
if(mbIsPainting)
{
// Paint a replacement object
const Rectangle aNewRectangle(GetPageRectangle());
bRetval |= PaintPageReplacement(rDisplayInfo, aNewRectangle, rAssociatedVOC);
rPaintRectangle.Union(aNewRectangle);
}
else
{
// something to paint?
if(pPage)
{
// set recursion flag, see description in *.hxx
mbIsPainting = sal_True;
// Paint a replacement object.
const Rectangle aNewRectangle(GetPageRectangle());
bRetval |= PaintPageContents(rDisplayInfo, aNewRectangle, rAssociatedVOC);
rPaintRectangle.Union(aNewRectangle);
// reset recursion flag, see description in *.hxx
mbIsPainting = sal_False;
}
}
// paint frame, but not when printing and no page available
if(!(rDisplayInfo.OutputToPrinter() && !pPage))
{
// #i54989# fill aNewRectangle before usage
const Rectangle aNewRectangle(GetPageRectangle());
bRetval |= PaintPageBorder(rDisplayInfo, aNewRectangle, rAssociatedVOC);
rPaintRectangle.Union(aNewRectangle);
}
return bRetval;
}
// #i35972# React on changes of the object of this ViewContact
void ViewContactOfPageObj::ActionChanged()
{
if(!mbIsInActionChange)
{
// set recursion flag, see description in *.hxx
mbIsInActionChange = sal_True;
// call parent
ViewContactOfSdrObj::ActionChanged();
// reset recursion flag, see description in *.hxx
mbIsInActionChange = sal_False;
}
}
} // end of namespace contact
} // end of namespace sdr
//////////////////////////////////////////////////////////////////////////////
// eof
<commit_msg>INTEGRATION: CWS vgbugs07 (1.12.130); FILE MERGED 2007/06/04 13:27:16 vg 1.12.130.1: #i76605# Remove -I .../inc/module hack introduced by hedaburemove01<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: viewcontactofpageobj.cxx,v $
*
* $Revision: 1.14 $
*
* last change: $Author: hr $ $Date: 2007-06-27 18:45:36 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svx.hxx"
#ifndef _SDR_CONTACT_VIEWCONTACTOFPAGEOBJ_HXX
#include <svx/sdr/contact/viewcontactofpageobj.hxx>
#endif
#ifndef _SVDOPAGE_HXX
#include <svx/svdopage.hxx>
#endif
#ifndef _SDR_CONTACT_DISPLAYINFO_HXX
#include <svx/sdr/contact/displayinfo.hxx>
#endif
#ifndef _SV_OUTDEV_HXX
#include <vcl/outdev.hxx>
#endif
#ifndef _SVDMODEL_HXX
#include <svx/svdmodel.hxx>
#endif
#ifndef _SVDPAGE_HXX
#include <svx/svdpage.hxx>
#endif
#ifndef _SDR_CONTACT_OBJECTCONTACTOFOBJLISTPAINTER_HXX
#include <svx/sdr/contact/objectcontactofobjlistpainter.hxx>
#endif
#ifndef _XOUTX_HXX
#include <svx/xoutx.hxx>
#endif
#ifndef _SDR_CONTACT_VIEWOBJECTCONTACT_HXX
#include <svx/sdr/contact/viewobjectcontact.hxx>
#endif
//////////////////////////////////////////////////////////////////////////////
// Own PagePainter which takes over initialisation tasks
namespace sdr
{
namespace contact
{
class OCOfPageObjPagePainter : public ObjectContactOfPagePainter
{
protected:
Rectangle maDestinationRectangle;
Point maTranslate;
Fraction maScaleX;
Fraction maScaleY;
ViewContact& mrUserViewContact;
public:
// basic constructor
OCOfPageObjPagePainter(const SdrPage* pPage, ViewContact& rUserViewContact);
// The destructor. When PrepareDelete() was not called before (see there)
// warnings will be generated in debug version if there are still contacts
// existing.
virtual ~OCOfPageObjPagePainter();
// Own paint
sal_Bool PaintIt(DisplayInfo& rDisplayInfo, const Rectangle& rDestinationRectangle);
// Own reaction on changes
virtual void InvalidatePartOfView(const Rectangle& rRectangle) const;
};
//////////////////////////////////////////////////////////////////////////////
// Implementation
OCOfPageObjPagePainter::OCOfPageObjPagePainter(const SdrPage* pPage, ViewContact& rUserViewContact)
: ObjectContactOfPagePainter(pPage),
mrUserViewContact(rUserViewContact)
{
// #i71130# Mark this view as preview renderer
mbIsPreviewRenderer = true;
}
OCOfPageObjPagePainter::~OCOfPageObjPagePainter()
{
}
sal_Bool OCOfPageObjPagePainter::PaintIt(DisplayInfo& rDisplayInfo, const Rectangle& rDestinationRectangle)
{
// save old clipping from OutDev
sal_Bool bRetval(sal_False);
OutputDevice* pOut = rDisplayInfo.GetOutputDevice();
maDestinationRectangle = rDestinationRectangle;
if(pOut)
{
// remap sizes. Destination size is size of rPaintRectangle,
// source size is the page size.
MapMode aOldMapMode = pOut->GetMapMode();
// calc translation
maTranslate = Point(maDestinationRectangle.TopLeft() + aOldMapMode.GetOrigin());
// calc scaling
maScaleX = Fraction(maDestinationRectangle.GetWidth(), mpStartPage->GetWdt());
maScaleY = Fraction(maDestinationRectangle.GetHeight(), mpStartPage->GetHgt());
// save clipping
sal_Bool bRememberedClipping(pOut->IsClipRegion());
Region aRememberedClipping;
if(bRememberedClipping)
{
aRememberedClipping = pOut->GetClipRegion();
}
// add clipping against object bounds
pOut->IntersectClipRegion(maDestinationRectangle);
// change origin
MapMode aNewMapMode(pOut->GetMapMode());
aNewMapMode.SetOrigin(maTranslate);
pOut->SetMapMode(aNewMapMode);
// change scaling
Point aEmptyPoint;
pOut->SetMapMode(MapMode(MAP_RELATIVE, aEmptyPoint, maScaleX, maScaleY));
// create copy of DisplayInfo. Do copy PageView to have it available at
// included page painting.
DisplayInfo aDisplayInfo(rDisplayInfo.GetPageView());
aDisplayInfo.SetExtendedOutputDevice(rDisplayInfo.GetExtendedOutputDevice());
aDisplayInfo.SetPaintInfoRec(rDisplayInfo.GetPaintInfoRec());
aDisplayInfo.SetOutputDevice(pOut);
// make MasterPages visible
aDisplayInfo.SetPagePainting(sal_True); // #i72889#
// do processing
ProcessDisplay(aDisplayInfo);
// restore original MapMode
pOut->SetMapMode(aOldMapMode);
// restore remembered clipping
if(bRememberedClipping)
{
pOut->SetClipRegion(aRememberedClipping);
}
else
{
pOut->SetClipRegion();
}
}
return bRetval;
}
void OCOfPageObjPagePainter::InvalidatePartOfView(const Rectangle& /*rRectangle*/) const
{
// call user change
mrUserViewContact.ActionChanged();
}
} // end of namespace contact
} // end of namespace sdr
//////////////////////////////////////////////////////////////////////////////
namespace sdr
{
namespace contact
{
// Access to referenced page
const SdrPage* ViewContactOfPageObj::GetReferencedPage() const
{
return GetPageObj().GetReferencedPage();
}
// method to recalculate the PaintRectangle if the validity flag shows that
// it is invalid. The flag is set from GetPaintRectangle, thus the implementation
// only needs to refresh maPaintRectangle itself.
void ViewContactOfPageObj::CalcPaintRectangle()
{
maPaintRectangle = GetPageObj().GetCurrentBoundRect();
}
// get rid of evtl. remembered PagePainter
void ViewContactOfPageObj::GetRidOfPagePainter()
{
if(mpPagePainter)
{
mpPagePainter->PrepareDelete();
delete mpPagePainter;
mpPagePainter = 0L;
}
}
// Prepare a PagePainter for current referenced page. This may
// refresh, create or delete a PagePainter instance in
// mpPagePainter
void ViewContactOfPageObj::PreparePagePainter(const SdrPage* pPage)
{
if(pPage)
{
if(mpPagePainter)
{
mpPagePainter->SetStartPage(pPage);
}
else
{
mpPagePainter = new OCOfPageObjPagePainter(pPage, *this);
}
}
else
{
GetRidOfPagePainter();
}
}
Rectangle ViewContactOfPageObj::GetPageRectangle (void)
{
CalcPaintRectangle();
return maPaintRectangle;
}
// Paint support methods for page content painting
sal_Bool ViewContactOfPageObj::PaintPageContents(
DisplayInfo& rDisplayInfo,
const Rectangle& rPaintRectangle,
const ViewObjectContact& /*rAssociatedVOC*/)
{
// Prepare page painter
sal_Bool bRetval(sal_False);
const SdrPage* pPage = GetReferencedPage();
PreparePagePainter(pPage);
if(mpPagePainter)
{
bRetval = mpPagePainter->PaintIt(rDisplayInfo, rPaintRectangle);
}
return bRetval;
}
sal_Bool ViewContactOfPageObj::PaintPageReplacement(
DisplayInfo& rDisplayInfo,
const Rectangle& rPaintRectangle,
const ViewObjectContact& /*rAssociatedVOC*/)
{
// If painting recursive, paint a replacement visualization
OutputDevice* pOut = rDisplayInfo.GetOutputDevice();
svtools::ColorConfigValue aDocColor(
rDisplayInfo.GetColorConfig().GetColorValue(svtools::DOCCOLOR));
svtools::ColorConfigValue aBorderColor(
rDisplayInfo.GetColorConfig().GetColorValue(svtools::DOCBOUNDARIES));
pOut->SetFillColor(aDocColor.nColor);
pOut->SetLineColor(aBorderColor.bIsVisible ? aBorderColor.nColor: aDocColor.nColor);
pOut->DrawRect(rPaintRectangle);
return sal_True;
}
sal_Bool ViewContactOfPageObj::PaintPageBorder(
DisplayInfo& rDisplayInfo,
const Rectangle& rPaintRectangle,
const ViewObjectContact& /*rAssociatedVOC*/)
{
OutputDevice* pOut = rDisplayInfo.GetOutputDevice();
sal_Bool bRetval(sal_False);
svtools::ColorConfigValue aFrameColor(
rDisplayInfo.GetColorConfig().GetColorValue(svtools::OBJECTBOUNDARIES));
if( aFrameColor.bIsVisible )
{
pOut->SetFillColor();
pOut->SetLineColor(aFrameColor.nColor);
pOut->DrawRect(rPaintRectangle);
bRetval = sal_True;
}
return bRetval;
}
// On StopGettingViewed the PagePainter can be dismissed.
void ViewContactOfPageObj::StopGettingViewed()
{
// call parent
ViewContactOfSdrObj::StopGettingViewed();
// dismiss PagePainter
GetRidOfPagePainter();
}
ViewContactOfPageObj::ViewContactOfPageObj(SdrPageObj& rPageObj)
: ViewContactOfSdrObj(rPageObj),
mpPagePainter(0L),
mbIsPainting(sal_False),
mbIsInActionChange(sal_False)
{
}
ViewContactOfPageObj::~ViewContactOfPageObj()
{
GetRidOfPagePainter();
}
// Paint this object. This is before evtl. SubObjects get painted. It needs to return
// sal_True when something was pained and the paint output rectangle in rPaintRectangle.
sal_Bool ViewContactOfPageObj::PaintObject(DisplayInfo& rDisplayInfo, Rectangle& rPaintRectangle, const ViewObjectContact& rAssociatedVOC)
{
sal_Bool bRetval(sal_False);
// get page to be displayed
const SdrPage* pPage = GetReferencedPage();
// avoid recursive painting
if(mbIsPainting)
{
// Paint a replacement object
const Rectangle aNewRectangle(GetPageRectangle());
bRetval |= PaintPageReplacement(rDisplayInfo, aNewRectangle, rAssociatedVOC);
rPaintRectangle.Union(aNewRectangle);
}
else
{
// something to paint?
if(pPage)
{
// set recursion flag, see description in *.hxx
mbIsPainting = sal_True;
// Paint a replacement object.
const Rectangle aNewRectangle(GetPageRectangle());
bRetval |= PaintPageContents(rDisplayInfo, aNewRectangle, rAssociatedVOC);
rPaintRectangle.Union(aNewRectangle);
// reset recursion flag, see description in *.hxx
mbIsPainting = sal_False;
}
}
// paint frame, but not when printing and no page available
if(!(rDisplayInfo.OutputToPrinter() && !pPage))
{
// #i54989# fill aNewRectangle before usage
const Rectangle aNewRectangle(GetPageRectangle());
bRetval |= PaintPageBorder(rDisplayInfo, aNewRectangle, rAssociatedVOC);
rPaintRectangle.Union(aNewRectangle);
}
return bRetval;
}
// #i35972# React on changes of the object of this ViewContact
void ViewContactOfPageObj::ActionChanged()
{
if(!mbIsInActionChange)
{
// set recursion flag, see description in *.hxx
mbIsInActionChange = sal_True;
// call parent
ViewContactOfSdrObj::ActionChanged();
// reset recursion flag, see description in *.hxx
mbIsInActionChange = sal_False;
}
}
} // end of namespace contact
} // end of namespace sdr
//////////////////////////////////////////////////////////////////////////////
// eof
<|endoftext|> |
<commit_before>/**
This software was developed by the University of Tennessee as part of the
Distributed Data Analysis of Neutron Scattering Experiments (DANSE)
project funded by the US National Science Foundation.
If you use DANSE applications to do scientific research that leads to
publication, we ask that you acknowledge the use of the software with the
following sentence:
"This work benefited from DANSE software developed under NSF award DMR-0520547."
copyright 2009, University of Tennessee
*/
#include "smearer.hh"
#include <stdio.h>
#include <math.h>
using namespace std;
/**
* Constructor for BaseSmearer
*
* @param qmin: minimum Q value
* @param qmax: maximum Q value
* @param nbins: number of Q bins
*/
BaseSmearer :: BaseSmearer(double qmin, double qmax, int nbins) {
// Number of bins
this->nbins = nbins;
this->qmin = qmin;
this->qmax = qmax;
// Flag to keep track of whether we have a smearing matrix or
// whether we need to compute one
has_matrix = false;
even_binning = true;
};
/**
* Constructor for BaseSmearer
*
* Used for uneven binning
* @param q: array of Q values
* @param nbins: number of Q bins
*/
BaseSmearer :: BaseSmearer(double* q, int nbins) {
// Number of bins
this->nbins = nbins;
this->q_values = q;
// Flag to keep track of whether we have a smearing matrix or
// whether we need to compute one
has_matrix = false;
even_binning = false;
};
/**
* Constructor for SlitSmearer
*
* @param width: slit width in Q units
* @param height: slit height in Q units
* @param qmin: minimum Q value
* @param qmax: maximum Q value
* @param nbins: number of Q bins
*/
SlitSmearer :: SlitSmearer(double width, double height, double qmin, double qmax, int nbins) :
BaseSmearer(qmin, qmax, nbins){
this->height = height;
this->width = width;
};
/**
* Constructor for SlitSmearer
*
* @param width: slit width in Q units
* @param height: slit height in Q units
* @param q: array of Q values
* @param nbins: number of Q bins
*/
SlitSmearer :: SlitSmearer(double width, double height, double* q, int nbins) :
BaseSmearer(q, nbins){
this->height = height;
this->width = width;
};
/**
* Constructor for QSmearer
*
* @param width: array slit widths for each Q point, in Q units
* @param qmin: minimum Q value
* @param qmax: maximum Q value
* @param nbins: number of Q bins
*/
QSmearer :: QSmearer(double* width, double qmin, double qmax, int nbins) :
BaseSmearer(qmin, qmax, nbins){
this->width = width;
};
/**
* Constructor for QSmearer
*
* @param width: array slit widths for each Q point, in Q units
* @param q: array of Q values
* @param nbins: number of Q bins
*/
QSmearer :: QSmearer(double* width, double* q, int nbins) :
BaseSmearer(q, nbins){
this->width = width;
};
/**
* Compute the slit smearing matrix
*
* For even binning (q_min to q_max with nbins):
*
* step = (q_max-q_min)/(nbins-1)
* first bin goes from q_min to q_min+step
* last bin goes from q_max to q_max+step
*
* For binning according to q array:
*
* Each q point represents a bin going from half the distance between it
* and the previous point to half the distance between it and the next point.
*
* Example: bin i goes from (q_values[i-1]+q_values[i])/2 to (q_values[i]+q_values[i+1])/2
*
* The exceptions are the first and last bins, which are centered at the first and
* last q-values, respectively. The width of the first and last bins is the distance between
* their respective neighboring q-value.
*/
void SlitSmearer :: compute_matrix(){
weights = new vector<double>(nbins*nbins,0);
// Check the length of the data
if (nbins<2) return;
// Loop over all q-values
for(int i=0; i<nbins; i++) {
double q, q_min, q_max;
get_bin_range(i, &q, &q_min, &q_max);
// For each q-value, compute the weight of each other q-bin
// in the I(q) array
int npts_h = height>0 ? npts : 1;
int npts_w = width>0 ? npts : 1;
// If both height and width are great than zero,
// modify the number of points in each direction so
// that the total number of points is still what
// the user would expect (downgrade resolution)
if(npts_h>1 && npts_w>1){
npts_h = (int)ceil(sqrt((double)npts));
npts_w = npts_h;
}
double shift_h, shift_w;
for(int k=0; k<npts_h; k++){
if(npts_h==1){
shift_h = 0;
} else {
shift_h = height/((double)npts_h-1.0) * (double)k;
}
for(int j=0; j<npts_w; j++){
if(npts_w==1){
shift_w = 0;
} else {
shift_w = width/((double)npts_w-1.0) * (double)j;
}
double q_shifted = sqrt( ((q-shift_w)*(q-shift_w) + shift_h*shift_h) );
// Find in which bin this shifted value belongs
int q_i=nbins;
if (even_binning) {
// This is kept for backward compatibility since the binning
// was originally defined differently for even bins.
q_i = (int)(floor( (q_shifted-qmin) /((qmax-qmin)/((double)nbins -1.0)) ));
} else {
for(int t=0; t<nbins; t++) {
double q_t, q_high, q_low;
get_bin_range(t, &q_t, &q_low, &q_high);
if(q_shifted>=q_low && q_shifted<q_high) {
q_i = t;
break;
}
}
}
// Skip the entries outside our I(q) range
//TODO: be careful with edge effect
if(q_i<nbins)
(*weights)[i*nbins+q_i]++;
}
}
}
};
/**
* Compute the point smearing matrix
*/
void QSmearer :: compute_matrix(){
weights = new vector<double>(nbins*nbins,0);
// Loop over all q-values
double step = (qmax-qmin)/((double)nbins-1.0);
double q, q_min, q_max;
double q_j, q_jmax, q_jmin;
for(int i=0; i<nbins; i++) {
get_bin_range(i, &q, &q_min, &q_max);
for(int j=0; j<nbins; j++) {
get_bin_range(j, &q_j, &q_jmin, &q_jmax);
// Compute the fraction of the Gaussian contributing
// to the q_j bin between q_jmin and q_jmax
double value = erf( (q_jmax-q)/(sqrt(2.0)*width[i]) );
value -= erf( (q_jmin-q)/(sqrt(2.0)*width[i]) );
(*weights)[i*nbins+j] += value;
}
}
}
/**
* Computes the Q range of a given bin of the Q distribution.
* The range is computed according the the data distribution that
* was given to the object at initialization.
*
* @param i: number of the bin in the distribution
* @param q: q-value of bin i
* @param q_min: lower bound of the bin
* @param q_max: higher bound of the bin
*
*/
int BaseSmearer :: get_bin_range(int i, double* q, double* q_min, double* q_max) {
if (even_binning) {
double step = (qmax-qmin)/((double)nbins-1.0);
*q = qmin + (double)i*step;
*q_min = *q - 0.5*step;
*q_max = *q + 0.5*step;
return 1;
} else if (i>=0 && i<nbins) {
*q = q_values[i];
if (i==0) {
double step = (q_values[1]-q_values[0])/2.0;
*q_min = *q - step;
*q_max = *q + step;
} else if (i==nbins-1) {
double step = (q_values[i]-q_values[i-1])/2.0;
*q_min = *q - step;
*q_max = *q + step;
} else {
*q_min = *q - (q_values[i]-q_values[i-1])/2.0;
*q_max = *q + (q_values[i+1]-q_values[i])/2.0;
}
return 1;
}
return -1;
}
/**
* Perform smearing by applying the smearing matrix to the input Q array
*/
void BaseSmearer :: smear(double *iq_in, double *iq_out, int first_bin, int last_bin){
// If we haven't computed the smearing matrix, do it now
if(!has_matrix) {
compute_matrix();
has_matrix = true;
}
// Loop over q-values and multiply apply matrix
for(int q_i=first_bin; q_i<=last_bin; q_i++){
double sum = 0.0;
double counts = 0.0;
for(int i=first_bin; i<=last_bin; i++){
// Skip if weight is less than 1e-04(this value is much smaller than
// the weight at the 3*sigma distance
// Will speed up a little bit...
if ((*weights)[q_i*nbins+i] < 1.0e-004){
continue;
}
sum += iq_in[i] * (*weights)[q_i*nbins+i];
counts += (*weights)[q_i*nbins+i];
}
// Normalize counts
iq_out[q_i] = (counts>0.0) ? sum/counts : 0;
}
}
<commit_msg>reduced an issue when both height and width are entered for smearing<commit_after>/**
This software was developed by the University of Tennessee as part of the
Distributed Data Analysis of Neutron Scattering Experiments (DANSE)
project funded by the US National Science Foundation.
If you use DANSE applications to do scientific research that leads to
publication, we ask that you acknowledge the use of the software with the
following sentence:
"This work benefited from DANSE software developed under NSF award DMR-0520547."
copyright 2009, University of Tennessee
*/
#include "smearer.hh"
#include <stdio.h>
#include <math.h>
using namespace std;
/**
* Constructor for BaseSmearer
*
* @param qmin: minimum Q value
* @param qmax: maximum Q value
* @param nbins: number of Q bins
*/
BaseSmearer :: BaseSmearer(double qmin, double qmax, int nbins) {
// Number of bins
this->nbins = nbins;
this->qmin = qmin;
this->qmax = qmax;
// Flag to keep track of whether we have a smearing matrix or
// whether we need to compute one
has_matrix = false;
even_binning = true;
};
/**
* Constructor for BaseSmearer
*
* Used for uneven binning
* @param q: array of Q values
* @param nbins: number of Q bins
*/
BaseSmearer :: BaseSmearer(double* q, int nbins) {
// Number of bins
this->nbins = nbins;
this->q_values = q;
// Flag to keep track of whether we have a smearing matrix or
// whether we need to compute one
has_matrix = false;
even_binning = false;
};
/**
* Constructor for SlitSmearer
*
* @param width: slit width in Q units
* @param height: slit height in Q units
* @param qmin: minimum Q value
* @param qmax: maximum Q value
* @param nbins: number of Q bins
*/
SlitSmearer :: SlitSmearer(double width, double height, double qmin, double qmax, int nbins) :
BaseSmearer(qmin, qmax, nbins){
this->height = height;
this->width = width;
};
/**
* Constructor for SlitSmearer
*
* @param width: slit width in Q units
* @param height: slit height in Q units
* @param q: array of Q values
* @param nbins: number of Q bins
*/
SlitSmearer :: SlitSmearer(double width, double height, double* q, int nbins) :
BaseSmearer(q, nbins){
this->height = height;
this->width = width;
};
/**
* Constructor for QSmearer
*
* @param width: array slit widths for each Q point, in Q units
* @param qmin: minimum Q value
* @param qmax: maximum Q value
* @param nbins: number of Q bins
*/
QSmearer :: QSmearer(double* width, double qmin, double qmax, int nbins) :
BaseSmearer(qmin, qmax, nbins){
this->width = width;
};
/**
* Constructor for QSmearer
*
* @param width: array slit widths for each Q point, in Q units
* @param q: array of Q values
* @param nbins: number of Q bins
*/
QSmearer :: QSmearer(double* width, double* q, int nbins) :
BaseSmearer(q, nbins){
this->width = width;
};
/**
* Compute the slit smearing matrix
*
* For even binning (q_min to q_max with nbins):
*
* step = (q_max-q_min)/(nbins-1)
* first bin goes from q_min to q_min+step
* last bin goes from q_max to q_max+step
*
* For binning according to q array:
*
* Each q point represents a bin going from half the distance between it
* and the previous point to half the distance between it and the next point.
*
* Example: bin i goes from (q_values[i-1]+q_values[i])/2 to (q_values[i]+q_values[i+1])/2
*
* The exceptions are the first and last bins, which are centered at the first and
* last q-values, respectively. The width of the first and last bins is the distance between
* their respective neighboring q-value.
*/
void SlitSmearer :: compute_matrix(){
weights = new vector<double>(nbins*nbins,0);
// Check the length of the data
if (nbins<2) return;
// Loop over all q-values
for(int i=0; i<nbins; i++) {
double q, q_min, q_max;
get_bin_range(i, &q, &q_min, &q_max);
// For each q-value, compute the weight of each other q-bin
// in the I(q) array
int npts_h = height>0 ? npts : 1;
int npts_w = width>0 ? npts : 1;
// If both height and width are great than zero,
// modify the number of points in each direction so
// that the total number of points is still what
// the user would expect (downgrade resolution)
// Never down-grade npts_h. That will give incorrect slit smearing...
if(npts_h>1 && npts_w>1){
npts_h = npts;//(int)ceil(sqrt((double)npts));
// In general width is much smaller than height, so smaller npt_w
// should work fine.
// Todo: It is still very expansive in time. Think about better way.
npts_w = (int)ceil(npts_h / 100);
}
double shift_h, shift_w;
for(int k=0; k<npts_h; k++){
if(npts_h==1){
shift_h = 0;
} else {
shift_h = height/((double)npts_h-1.0) * (double)k;
}
for(int j=0; j<npts_w; j++){
if(npts_w==1){
shift_w = 0;
} else {
shift_w = width/((double)npts_w-1.0) * (double)j;
}
double q_shifted = sqrt( ((q-shift_w)*(q-shift_w) + shift_h*shift_h) );
// Find in which bin this shifted value belongs
int q_i=nbins;
if (even_binning) {
// This is kept for backward compatibility since the binning
// was originally defined differently for even bins.
q_i = (int)(floor( (q_shifted-qmin) /((qmax-qmin)/((double)nbins -1.0)) ));
} else {
for(int t=0; t<nbins; t++) {
double q_t, q_high, q_low;
get_bin_range(t, &q_t, &q_low, &q_high);
if(q_shifted>=q_low && q_shifted<q_high) {
q_i = t;
break;
}
}
}
// Skip the entries outside our I(q) range
//TODO: be careful with edge effect
if(q_i<nbins)
(*weights)[i*nbins+q_i]++;
}
}
}
};
/**
* Compute the point smearing matrix
*/
void QSmearer :: compute_matrix(){
weights = new vector<double>(nbins*nbins,0);
// Loop over all q-values
double step = (qmax-qmin)/((double)nbins-1.0);
double q, q_min, q_max;
double q_j, q_jmax, q_jmin;
for(int i=0; i<nbins; i++) {
get_bin_range(i, &q, &q_min, &q_max);
for(int j=0; j<nbins; j++) {
get_bin_range(j, &q_j, &q_jmin, &q_jmax);
// Compute the fraction of the Gaussian contributing
// to the q_j bin between q_jmin and q_jmax
double value = erf( (q_jmax-q)/(sqrt(2.0)*width[i]) );
value -= erf( (q_jmin-q)/(sqrt(2.0)*width[i]) );
(*weights)[i*nbins+j] += value;
}
}
}
/**
* Computes the Q range of a given bin of the Q distribution.
* The range is computed according the the data distribution that
* was given to the object at initialization.
*
* @param i: number of the bin in the distribution
* @param q: q-value of bin i
* @param q_min: lower bound of the bin
* @param q_max: higher bound of the bin
*
*/
int BaseSmearer :: get_bin_range(int i, double* q, double* q_min, double* q_max) {
if (even_binning) {
double step = (qmax-qmin)/((double)nbins-1.0);
*q = qmin + (double)i*step;
*q_min = *q - 0.5*step;
*q_max = *q + 0.5*step;
return 1;
} else if (i>=0 && i<nbins) {
*q = q_values[i];
if (i==0) {
double step = (q_values[1]-q_values[0])/2.0;
*q_min = *q - step;
*q_max = *q + step;
} else if (i==nbins-1) {
double step = (q_values[i]-q_values[i-1])/2.0;
*q_min = *q - step;
*q_max = *q + step;
} else {
*q_min = *q - (q_values[i]-q_values[i-1])/2.0;
*q_max = *q + (q_values[i+1]-q_values[i])/2.0;
}
return 1;
}
return -1;
}
/**
* Perform smearing by applying the smearing matrix to the input Q array
*/
void BaseSmearer :: smear(double *iq_in, double *iq_out, int first_bin, int last_bin){
// If we haven't computed the smearing matrix, do it now
if(!has_matrix) {
compute_matrix();
has_matrix = true;
}
// Loop over q-values and multiply apply matrix
for(int q_i=first_bin; q_i<=last_bin; q_i++){
double sum = 0.0;
double counts = 0.0;
for(int i=first_bin; i<=last_bin; i++){
// Skip if weight is less than 1e-04(this value is much smaller than
// the weight at the 3*sigma distance
// Will speed up a little bit...
if ((*weights)[q_i*nbins+i] < 1.0e-004){
continue;
}
sum += iq_in[i] * (*weights)[q_i*nbins+i];
counts += (*weights)[q_i*nbins+i];
}
// Normalize counts
iq_out[q_i] = (counts>0.0) ? sum/counts : 0;
}
}
<|endoftext|> |
<commit_before>#include "OrbitCamera.h"
void OrbitCamera::updatePosition() {
Position.x = Distance * glm::sin(HorizontalAngle) * glm::cos(VerticalAngle);
Position.z = Distance * glm::cos(HorizontalAngle) * glm::cos(VerticalAngle);
Position.y = Distance * glm::sin(-VerticalAngle);
}
OrbitCamera::OrbitCamera(glm::vec3 center) {
HorizontalAngle = 0.0f;
VerticalAngle = 0.0f;
Distance = 2.5f;
MouseSpeed /= 2;
Center = center;
updatePosition();
}
OrbitCamera::~OrbitCamera() {
}
void OrbitCamera::update() {
static double lastTime = glfwGetTime();
double currentTime = glfwGetTime();
float deltaTime = float(currentTime - lastTime);
lastTime = currentTime;
int width, height;
glfwGetWindowSize(Window, &width, &height);
double xPos, yPos;
glfwGetCursorPos(Window, &xPos, &yPos);
glfwSetCursorPos(Window, width / 2., height / 2.);
HorizontalAngle += MouseSpeed * glm::min((Distance - 1.0)/2, 1.0) * float(glm::floor(width / 2.0) - xPos);
HorizontalAngle = std::fmod(HorizontalAngle, 3.14f * 2);
VerticalAngle += MouseSpeed * glm::min((Distance - 1.0) / 2, 1.0) * float(glm::floor(height / 2.0) - yPos);
VerticalAngle = glm::clamp(VerticalAngle, -1.57f, 1.57f);
glm::vec3 up = glm::vec3(0, 1, 0);
updatePosition();
View = glm::lookAt(Position, Center, up);
Projection = glm::perspective(FoV, float(width)/float(height), 0.1f, 100.0f);
}
<commit_msg>Camera now uses click and drag to orbit rather than attaching to mouse<commit_after>#include "OrbitCamera.h"
void OrbitCamera::updatePosition() {
Position.x = Distance * glm::sin(HorizontalAngle) * glm::cos(VerticalAngle);
Position.z = Distance * glm::cos(HorizontalAngle) * glm::cos(VerticalAngle);
Position.y = Distance * glm::sin(-VerticalAngle);
}
OrbitCamera::OrbitCamera(glm::vec3 center) {
HorizontalAngle = 0.0f;
VerticalAngle = 0.0f;
Distance = 2.5f;
MouseSpeed /= 2;
Center = center;
updatePosition();
}
OrbitCamera::~OrbitCamera() {
}
void OrbitCamera::update() {
static double lastTime = glfwGetTime();
double currentTime = glfwGetTime();
float deltaTime = float(currentTime - lastTime);
lastTime = currentTime;
int width, height;
glfwGetWindowSize(Window, &width, &height);
static double lastX = -1, lastY = -1;
if(lastX == -1 || lastY == -1) {
glfwGetCursorPos(Window, &lastX, &lastY);
}
double xPos, yPos;
glfwGetCursorPos(Window, &xPos, &yPos);
//glfwSetCursorPos(Window, width / 2., height / 2.);
double dx = lastX - xPos;
double dy = lastY - yPos;
if(glfwGetMouseButton(Window, GLFW_MOUSE_BUTTON_LEFT) == GLFW_PRESS) {
HorizontalAngle += MouseSpeed * glm::min((Distance - 1.0) / 2, 1.0) * float(dx);// glm::floor(width / 2.0) - xPos);
HorizontalAngle = std::fmod(HorizontalAngle, 3.14f * 2);
VerticalAngle += MouseSpeed * glm::min((Distance - 1.0) / 2, 1.0) * float(dy);// glm::floor(height / 2.0) - yPos);
VerticalAngle = glm::clamp(VerticalAngle, -1.57f, 1.57f);
}
updatePosition();
View = glm::lookAt(Position, Center, up);
Projection = glm::perspective(FoV, float(width) / float(height), 0.1f, 100.0f);
lastX = xPos;
lastY = yPos;
}
<|endoftext|> |
<commit_before>#include "stdafx.h"
#include "CppUnitTest.h"
#include "math/vector2.h"
#include "PhysicalObject.h"
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
namespace
{
oxygine::UpdateState oneSecondUpdate()
{
oxygine::UpdateState update;
update.dt = 1000;
return update;
}
static const oxygine::UpdateState oneSecondUpdateStruct = oneSecondUpdate();
static const PhysicalObject::Point oneUnitHorizontalyAndVertically{ pixel, pixel };
static const PhysicalObject::Point someLocation = oneUnitHorizontalyAndVertically;
static const PhysicalObject::Point zeroPoint{ Distance(0), Distance(0) };
static const PhysicalObject::Point oneUnitHorisontallyPoint{ Distance(1), Distance(0) };
static const PhysicalObject::SpeedVector zeroSpeed{ Speed(0), Speed(0) };
static const PhysicalObject::SpeedVector oneUnitPerSecondHorizontally{ pixelPerSecond, Speed(0) };
static const PhysicalObject::AccelerationVector zeroAccelerationVector{ Acceleration(0), Acceleration(0) };
static const PhysicalObject::AccelerationVector oneUnitPerSecondSquaredVertically{ Acceleration(0), pixelPerSquareSecond };
static const PhysicalObject::AccelerationVector oneUnitPerSecondSquaredHorizontally{ pixelPerSquareSecond, Acceleration(0)};
}
namespace PlatformerTest
{
TEST_CLASS(TestOfPhysicalObject)
{
public:
TEST_METHOD(ConstructedWithZeroSpeedAndZeroPointLocation)
{
PhysicalObject object;
Assert::IsTrue(zeroPoint == object.GetLocation());
Assert::IsTrue(zeroSpeed == object.GetSpeed());
}
TEST_METHOD(ConstructedWithLocation)
{
PhysicalObject object(someLocation);
Assert::IsTrue(someLocation == object.GetLocation());
}
TEST_METHOD(SetSpeed)
{
PhysicalObject object;
object.SetSpeed(oneUnitPerSecondHorizontally);
Assert::IsTrue(oneUnitPerSecondHorizontally == object.GetSpeed());
}
TEST_METHOD(SetGravity)
{
PhysicalObject::SetGravity(oneUnitPerSecondSquaredVertically);
Assert::IsTrue(PhysicalObject::GetGravity() == oneUnitPerSecondSquaredVertically);
}
TEST_METHOD(MovesWhenNonZeroSpeed)
{
PhysicalObject::SetGravity(zeroAccelerationVector);
PhysicalObject object;
object.SetSpeed(oneUnitPerSecondHorizontally);
object.Update(oneSecondUpdateStruct);
Assert::IsTrue(oneUnitHorisontallyPoint == object.GetLocation());
}
TEST_METHOD(MovesWithGravity)
{
PhysicalObject::SetGravity(oneUnitPerSecondSquaredVertically);
PhysicalObject object;
object.SetSpeed(oneUnitPerSecondHorizontally);
object.Update(oneSecondUpdateStruct);
Assert::IsTrue(oneUnitHorizontalyAndVertically == object.GetLocation());
}
TEST_METHOD(MovesWithGravityAndCustomAcceleration)
{
PhysicalObject::SetGravity(oneUnitPerSecondSquaredVertically);
PhysicalObject object;
object.SetAcceleration(oneUnitPerSecondSquaredHorizontally);
object.Update(oneSecondUpdateStruct);
Assert::IsTrue(oneUnitHorizontalyAndVertically == object.GetLocation());
}
};
}<commit_msg>Negative tests of PhysicalObject added. It is necessary to avoid simple (but incorrect) implementation, such as 'return true;'<commit_after>#include "stdafx.h"
#include "CppUnitTest.h"
#include "math/vector2.h"
#include "PhysicalObject.h"
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
namespace
{
oxygine::UpdateState oneSecondUpdate()
{
oxygine::UpdateState update;
update.dt = 1000;
return update;
}
static const oxygine::UpdateState oneSecondUpdateStruct = oneSecondUpdate();
static const PhysicalObject::Point oneUnitHorizontalyAndVertically{ pixel, pixel };
static const PhysicalObject::Point someLocation = oneUnitHorizontalyAndVertically;
static const PhysicalObject::Point zeroPoint{ Distance(0), Distance(0) };
static const PhysicalObject::Point oneUnitHorisontallyPoint{ Distance(1), Distance(0) };
static const PhysicalObject::SpeedVector zeroSpeed{ Speed(0), Speed(0) };
static const PhysicalObject::SpeedVector oneUnitPerSecondHorizontally{ pixelPerSecond, Speed(0) };
static const PhysicalObject::SpeedVector oneUnitPerSecondVertically{ Speed(0), pixelPerSecond };
static const PhysicalObject::AccelerationVector zeroAccelerationVector{ Acceleration(0), Acceleration(0) };
static const PhysicalObject::AccelerationVector oneUnitPerSecondSquaredVertically{ Acceleration(0), pixelPerSquareSecond };
static const PhysicalObject::AccelerationVector oneUnitPerSecondSquaredHorizontally{ pixelPerSquareSecond, Acceleration(0)};
static const PhysicalObject::AccelerationVector oneUnitPerSecondSquaredVerticallyAndHorizontally{ Acceleration(0), Acceleration(0) };
}
namespace PlatformerTest
{
TEST_CLASS(TestOfPhysicalObject)
{
public:
TEST_METHOD(ConstructedWithZeroSpeedAndZeroPointLocation)
{
PhysicalObject object;
Assert::IsTrue(zeroPoint == object.GetLocation());
Assert::IsTrue(zeroSpeed == object.GetSpeed());
}
TEST_METHOD(ConstructedWithLocation)
{
PhysicalObject object(someLocation);
Assert::IsTrue(someLocation == object.GetLocation());
}
TEST_METHOD(SetSpeed)
{
PhysicalObject object;
object.SetSpeed(oneUnitPerSecondHorizontally);
Assert::IsTrue(oneUnitPerSecondHorizontally == object.GetSpeed());
}
TEST_METHOD(SetGravity)
{
PhysicalObject::SetGravity(oneUnitPerSecondSquaredVertically);
Assert::IsTrue(PhysicalObject::GetGravity() == oneUnitPerSecondSquaredVertically);
}
TEST_METHOD(SetGravityAndGravityNegativeResult)
{
PhysicalObject object;
object.SetSpeed(oneUnitPerSecondHorizontally);
PhysicalObject::SetGravity(oneUnitPerSecondSquaredVertically);
Assert::IsFalse(oneUnitPerSecondVertically == object.GetSpeed());
Assert::IsFalse(PhysicalObject::GetGravity() == oneUnitPerSecondSquaredHorizontally);
}
TEST_METHOD(MovesWhenNonZeroSpeed)
{
PhysicalObject::SetGravity(zeroAccelerationVector);
PhysicalObject object;
object.SetSpeed(oneUnitPerSecondHorizontally);
object.Update(oneSecondUpdateStruct);
Assert::IsTrue(oneUnitHorisontallyPoint == object.GetLocation());
}
TEST_METHOD(MovesWithGravity)
{
PhysicalObject::SetGravity(oneUnitPerSecondSquaredVertically);
PhysicalObject object;
object.SetSpeed(oneUnitPerSecondHorizontally);
object.Update(oneSecondUpdateStruct);
Assert::IsTrue(oneUnitHorizontalyAndVertically == object.GetLocation());
}
TEST_METHOD(MovesWithGravityNegativeResult)
{
PhysicalObject::SetGravity(oneUnitPerSecondSquaredVertically);
PhysicalObject object;
object.SetSpeed(oneUnitPerSecondVertically);
object.Update(oneSecondUpdateStruct);
Assert::IsFalse(oneUnitHorizontalyAndVertically == object.GetLocation());
}
TEST_METHOD(MovesWithGravityAndCustomAcceleration)
{
PhysicalObject::SetGravity(oneUnitPerSecondSquaredVertically);
PhysicalObject object;
object.SetAcceleration(oneUnitPerSecondSquaredHorizontally);
object.Update(oneSecondUpdateStruct);
Assert::IsTrue(oneUnitHorizontalyAndVertically == object.GetLocation());
}
TEST_METHOD(MovesWithGravityAndCustomAccelerationNegativeResult)
{
PhysicalObject::SetGravity(oneUnitPerSecondSquaredVertically);
PhysicalObject object;
object.SetAcceleration(oneUnitPerSecondSquaredVerticallyAndHorizontally);
object.Update(oneSecondUpdateStruct);
Assert::IsFalse(oneUnitHorizontalyAndVertically == object.GetLocation());
}
};
}<|endoftext|> |
<commit_before>// Copyright 2019 Dell EMC
//
// 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 <iostream>
#include <fstream>
#include <string>
#include "stratum/hal/lib/phal/onlp/sfp_configurator.h"
#include "stratum/hal/lib/common/common.pb.h"
using namespace std; // NOLINT
using namespace google::protobuf::util; // NOLINT
namespace stratum {
namespace hal {
namespace phal {
namespace onlp {
OnlpSfpConfigurator::OnlpSfpConfigurator(int id,
std::shared_ptr<OnlpSfpDataSource>datasource,
AttributeGroup* sfp_group, OnlpInterface* onlp_interface)
: id_(id),
datasource_(datasource),
sfp_group_(sfp_group),
onlp_interface_(onlp_interface) {
// lock us so we can modify
auto mutable_sfp = sfp_group_->AcquireMutable();
// Ok, now go add the sfp attributes
mutable_sfp->AddAttribute("id", datasource_->GetSfpId());
mutable_sfp->AddAttribute("description", datasource_->GetSfpDesc());
mutable_sfp->AddAttribute("hardware_state",
datasource_->GetSfpHardwareState());
}
::util::StatusOr<std::unique_ptr<OnlpSfpConfigurator>>
OnlpSfpConfigurator::Make(int id,
std::shared_ptr<OnlpSfpDataSource>datasource,
AttributeGroup* sfp_group,
OnlpInterface* onlp_interface) {
return absl::WrapUnique(
new OnlpSfpConfigurator(id, datasource, sfp_group, onlp_interface));
}
::util::Status OnlpSfpConfigurator::HandleEvent(HwState state) {
// Check SFP state
switch (state) {
// Add SFP attributes
case HW_STATE_PRESENT:
RETURN_IF_ERROR(AddSfp());
break;
// Remove SFP attributes
case HW_STATE_NOT_PRESENT:
RETURN_IF_ERROR(RemoveSfp());
break;
default:
RETURN_ERROR() << "Unknown SFP event state " << state << ".";
}
return ::util::OkStatus();
}
// Add an Sfp transceiver
// Note: you can't hold a mutable lock on parent attribute group
// while also holding a mutable lock on a child attribute group
// and adding attributes (via the AddAttribute call) to the child
// attribute group. Could be a bug, but for now the code below
// works around the problem.
::util::Status OnlpSfpConfigurator::AddSfp() {
// Make sure we don't already have a datasource added to the DB
absl::WriterMutexLock l(&config_lock_);
if (initialized_) {
RETURN_ERROR() << "sfp id " << id_ << " already added";
}
// lock us so we can modify
auto mutable_sfp = sfp_group_->AcquireMutable();
mutable_sfp->AddAttribute("media_type", datasource_->GetSfpMediaType());
mutable_sfp->AddAttribute("connector_type",
datasource_->GetSfpType());
mutable_sfp->AddAttribute("module_type", datasource_->GetSfpModuleType());
mutable_sfp->AddAttribute("cable_length", datasource_->GetSfpCableLength());
mutable_sfp->AddAttribute("cable_length_desc",
datasource_->GetSfpCableLengthDesc());
mutable_sfp->AddAttribute("temperature", datasource_->GetSfpTemperature());
mutable_sfp->AddAttribute("vcc", datasource_->GetSfpVoltage());
mutable_sfp->AddAttribute("channel_count",
datasource_->GetSfpChannelCount());
// Get HardwareInfo DB group
ASSIGN_OR_RETURN(auto info, mutable_sfp->AddChildGroup("info"));
// release sfp lock & acquire info lock
mutable_sfp = nullptr;
auto mutable_info = info->AcquireMutable();
// Ok, now go add the info attributes
mutable_info->AddAttribute("mfg_name", datasource_->GetSfpVendor());
mutable_info->AddAttribute("part_no", datasource_->GetSfpModel());
mutable_info->AddAttribute("serial_no", datasource_->GetSfpSerialNumber());
// release info lock
mutable_info = nullptr;
// Get SfpModuleCaps DB group
mutable_sfp = sfp_group_->AcquireMutable();
ASSIGN_OR_RETURN(auto caps,
mutable_sfp->AddChildGroup("module_capabilities"));
// release sfp & acquire caps lock
mutable_sfp = nullptr;
auto mutable_caps = caps->AcquireMutable();
// Ok, now go remove the attributes
mutable_caps->AddAttribute("f_100", datasource_->GetModCapF100());
mutable_caps->AddAttribute("f_1g", datasource_->GetModCapF1G());
mutable_caps->AddAttribute("f_10g", datasource_->GetModCapF10G());
mutable_caps->AddAttribute("f_40g", datasource_->GetModCapF40G());
mutable_caps->AddAttribute("f_100g", datasource_->GetModCapF100G());
// release caps lock
mutable_caps = nullptr;
// Add SFPChannel Attributes
// note: use a 0-based index for both database and ONLP
ASSIGN_OR_RETURN(sfp_channel_count_,
datasource_->GetSfpChannelCount()->ReadValue<int>());
for (int id=0; id < sfp_channel_count_; id++) {
// lock us so we can modify
mutable_sfp = sfp_group_->AcquireMutable();
// Get a new channel
ASSIGN_OR_RETURN(auto channel,
mutable_sfp->AddRepeatedChildGroup("channels"));
// release lock
mutable_sfp = nullptr;
// Note: don't move pointer, just a reference
AddChannel(id, channel);
}
// we're now initialized
initialized_ = true;
return ::util::OkStatus();
}
::util::Status OnlpSfpConfigurator::RemoveSfp() {
// Make sure we have a been initialized
absl::WriterMutexLock l(&config_lock_);
if (!initialized_) {
RETURN_ERROR() << "sfp id " << id_ << " has not been added";
}
// lock us so we can modify
auto mutable_sfp = sfp_group_->AcquireMutable();
mutable_sfp->RemoveAttribute("media_type");
mutable_sfp->RemoveAttribute("connector_type");
mutable_sfp->RemoveAttribute("module_type");
mutable_sfp->RemoveAttribute("cable_length");
mutable_sfp->RemoveAttribute("cable_length_desc");
mutable_sfp->RemoveAttribute("temperature");
mutable_sfp->RemoveAttribute("vcc");
// Get HardwareInfo DB group
ASSIGN_OR_RETURN(auto info, mutable_sfp->GetChildGroup("info"));
auto mutable_info = info->AcquireMutable();
// Ok, now go remove the attributes
mutable_info->RemoveAttribute("mfg_name");
mutable_info->RemoveAttribute("part_no");
mutable_info->RemoveAttribute("serial_no");
// Remove "info" group
mutable_info = nullptr;
RETURN_IF_ERROR(mutable_sfp->RemoveChildGroup("info"));
// Get SfpModuleCaps DB group
ASSIGN_OR_RETURN(auto caps,
mutable_sfp->GetChildGroup("module_capabilities"));
auto mutable_caps = caps->AcquireMutable();
// Ok, now go remove the attributes
mutable_caps->RemoveAttribute("f_100");
mutable_caps->RemoveAttribute("f_1g");
mutable_caps->RemoveAttribute("f_10g");
mutable_caps->RemoveAttribute("f_40g");
mutable_caps->RemoveAttribute("f_100g");
// Remove "module_caps" group
mutable_caps = nullptr;
RETURN_IF_ERROR(mutable_sfp->RemoveChildGroup("module_capabilities"));
// Remove SFPChannel Attributes
// note: use a 0-based index for both database and ONLP
for (int id=0; id < sfp_channel_count_; id++) {
// Get channel group
ASSIGN_OR_RETURN(auto channel,
mutable_sfp->GetRepeatedChildGroup("channels", id));
// Note: don't move pointer, just a reference
RemoveChannel(id, channel);
}
// Remove all the channel groups
RETURN_IF_ERROR(mutable_sfp->RemoveRepeatedChildGroup("channels"));
// free up datasource
datasource_ = nullptr;
// we're now not initialized
initialized_ = false;
return ::util::OkStatus();
}
::util::Status OnlpSfpConfigurator::AddChannel(int id,
AttributeGroup* channel) {
// lcok channel group
auto mutable_channel = channel->AcquireMutable();
// Now add the attributes
mutable_channel->AddAttribute("rx_power", datasource_->GetSfpRxPower(id));
mutable_channel->AddAttribute("tx_power", datasource_->GetSfpTxPower(id));
mutable_channel->AddAttribute("tx_bias", datasource_->GetSfpTxBias(id));
return ::util::OkStatus();
}
::util::Status OnlpSfpConfigurator::RemoveChannel(int id,
AttributeGroup* channel) {
// lock channel group
auto mutable_channel = channel->AcquireMutable();
// Remove the attributes
mutable_channel->RemoveAttribute("rx_power");
mutable_channel->RemoveAttribute("tx_power");
mutable_channel->RemoveAttribute("tx_bias");
return ::util::OkStatus();
}
} // namespace onlp
} // namespace phal
} // namespace hal
} // namespace stratum
<commit_msg>Do not clear datasource on SFP removal (#323)<commit_after>// Copyright 2019 Dell EMC
//
// 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 <iostream>
#include <fstream>
#include <string>
#include "stratum/hal/lib/phal/onlp/sfp_configurator.h"
#include "stratum/hal/lib/common/common.pb.h"
using namespace std; // NOLINT
using namespace google::protobuf::util; // NOLINT
namespace stratum {
namespace hal {
namespace phal {
namespace onlp {
OnlpSfpConfigurator::OnlpSfpConfigurator(int id,
std::shared_ptr<OnlpSfpDataSource>datasource,
AttributeGroup* sfp_group, OnlpInterface* onlp_interface)
: id_(id),
datasource_(ABSL_DIE_IF_NULL(datasource)),
sfp_group_(ABSL_DIE_IF_NULL(sfp_group)),
onlp_interface_(ABSL_DIE_IF_NULL(onlp_interface)) {
// lock us so we can modify
auto mutable_sfp = sfp_group_->AcquireMutable();
// Ok, now go add the sfp attributes
mutable_sfp->AddAttribute("id", datasource_->GetSfpId());
mutable_sfp->AddAttribute("description", datasource_->GetSfpDesc());
mutable_sfp->AddAttribute("hardware_state",
datasource_->GetSfpHardwareState());
}
::util::StatusOr<std::unique_ptr<OnlpSfpConfigurator>>
OnlpSfpConfigurator::Make(int id,
std::shared_ptr<OnlpSfpDataSource>datasource,
AttributeGroup* sfp_group,
OnlpInterface* onlp_interface) {
return absl::WrapUnique(
new OnlpSfpConfigurator(id, datasource, sfp_group, onlp_interface));
}
::util::Status OnlpSfpConfigurator::HandleEvent(HwState state) {
// Check SFP state
switch (state) {
// Add SFP attributes
case HW_STATE_PRESENT:
RETURN_IF_ERROR(AddSfp());
break;
// Remove SFP attributes
case HW_STATE_NOT_PRESENT:
RETURN_IF_ERROR(RemoveSfp());
break;
default:
RETURN_ERROR() << "Unknown SFP event state " << state << ".";
}
return ::util::OkStatus();
}
// Add an Sfp transceiver
// Note: you can't hold a mutable lock on parent attribute group
// while also holding a mutable lock on a child attribute group
// and adding attributes (via the AddAttribute call) to the child
// attribute group. Could be a bug, but for now the code below
// works around the problem.
::util::Status OnlpSfpConfigurator::AddSfp() {
// Make sure we don't already have a datasource added to the DB
absl::WriterMutexLock l(&config_lock_);
if (initialized_) {
RETURN_ERROR() << "sfp id " << id_ << " already added";
}
// lock us so we can modify
auto mutable_sfp = sfp_group_->AcquireMutable();
mutable_sfp->AddAttribute("media_type", datasource_->GetSfpMediaType());
mutable_sfp->AddAttribute("connector_type",
datasource_->GetSfpType());
mutable_sfp->AddAttribute("module_type", datasource_->GetSfpModuleType());
mutable_sfp->AddAttribute("cable_length", datasource_->GetSfpCableLength());
mutable_sfp->AddAttribute("cable_length_desc",
datasource_->GetSfpCableLengthDesc());
mutable_sfp->AddAttribute("temperature", datasource_->GetSfpTemperature());
mutable_sfp->AddAttribute("vcc", datasource_->GetSfpVoltage());
mutable_sfp->AddAttribute("channel_count",
datasource_->GetSfpChannelCount());
// Get HardwareInfo DB group
ASSIGN_OR_RETURN(auto info, mutable_sfp->AddChildGroup("info"));
// release sfp lock & acquire info lock
mutable_sfp = nullptr;
auto mutable_info = info->AcquireMutable();
// Ok, now go add the info attributes
mutable_info->AddAttribute("mfg_name", datasource_->GetSfpVendor());
mutable_info->AddAttribute("part_no", datasource_->GetSfpModel());
mutable_info->AddAttribute("serial_no", datasource_->GetSfpSerialNumber());
// release info lock
mutable_info = nullptr;
// Get SfpModuleCaps DB group
mutable_sfp = sfp_group_->AcquireMutable();
ASSIGN_OR_RETURN(auto caps,
mutable_sfp->AddChildGroup("module_capabilities"));
// release sfp & acquire caps lock
mutable_sfp = nullptr;
auto mutable_caps = caps->AcquireMutable();
// Ok, now go remove the attributes
mutable_caps->AddAttribute("f_100", datasource_->GetModCapF100());
mutable_caps->AddAttribute("f_1g", datasource_->GetModCapF1G());
mutable_caps->AddAttribute("f_10g", datasource_->GetModCapF10G());
mutable_caps->AddAttribute("f_40g", datasource_->GetModCapF40G());
mutable_caps->AddAttribute("f_100g", datasource_->GetModCapF100G());
// release caps lock
mutable_caps = nullptr;
// Add SFPChannel Attributes
// note: use a 0-based index for both database and ONLP
ASSIGN_OR_RETURN(sfp_channel_count_,
datasource_->GetSfpChannelCount()->ReadValue<int>());
for (int id=0; id < sfp_channel_count_; id++) {
// lock us so we can modify
mutable_sfp = sfp_group_->AcquireMutable();
// Get a new channel
ASSIGN_OR_RETURN(auto channel,
mutable_sfp->AddRepeatedChildGroup("channels"));
// release lock
mutable_sfp = nullptr;
// Note: don't move pointer, just a reference
AddChannel(id, channel);
}
// we're now initialized
initialized_ = true;
return ::util::OkStatus();
}
::util::Status OnlpSfpConfigurator::RemoveSfp() {
// Make sure we have a been initialized
absl::WriterMutexLock l(&config_lock_);
if (!initialized_) {
RETURN_ERROR() << "sfp id " << id_ << " has not been added";
}
// lock us so we can modify
auto mutable_sfp = sfp_group_->AcquireMutable();
mutable_sfp->RemoveAttribute("media_type");
mutable_sfp->RemoveAttribute("connector_type");
mutable_sfp->RemoveAttribute("module_type");
mutable_sfp->RemoveAttribute("cable_length");
mutable_sfp->RemoveAttribute("cable_length_desc");
mutable_sfp->RemoveAttribute("temperature");
mutable_sfp->RemoveAttribute("vcc");
// Get HardwareInfo DB group
ASSIGN_OR_RETURN(auto info, mutable_sfp->GetChildGroup("info"));
auto mutable_info = info->AcquireMutable();
// Ok, now go remove the attributes
mutable_info->RemoveAttribute("mfg_name");
mutable_info->RemoveAttribute("part_no");
mutable_info->RemoveAttribute("serial_no");
// Remove "info" group
mutable_info = nullptr;
RETURN_IF_ERROR(mutable_sfp->RemoveChildGroup("info"));
// Get SfpModuleCaps DB group
ASSIGN_OR_RETURN(auto caps,
mutable_sfp->GetChildGroup("module_capabilities"));
auto mutable_caps = caps->AcquireMutable();
// Ok, now go remove the attributes
mutable_caps->RemoveAttribute("f_100");
mutable_caps->RemoveAttribute("f_1g");
mutable_caps->RemoveAttribute("f_10g");
mutable_caps->RemoveAttribute("f_40g");
mutable_caps->RemoveAttribute("f_100g");
// Remove "module_caps" group
mutable_caps = nullptr;
RETURN_IF_ERROR(mutable_sfp->RemoveChildGroup("module_capabilities"));
// Remove SFPChannel Attributes
// note: use a 0-based index for both database and ONLP
for (int id=0; id < sfp_channel_count_; id++) {
// Get channel group
ASSIGN_OR_RETURN(auto channel,
mutable_sfp->GetRepeatedChildGroup("channels", id));
// Note: don't move pointer, just a reference
RemoveChannel(id, channel);
}
// Remove all the channel groups
RETURN_IF_ERROR(mutable_sfp->RemoveRepeatedChildGroup("channels"));
// we're now not initialized
initialized_ = false;
return ::util::OkStatus();
}
::util::Status OnlpSfpConfigurator::AddChannel(int id,
AttributeGroup* channel) {
// lcok channel group
auto mutable_channel = channel->AcquireMutable();
// Now add the attributes
mutable_channel->AddAttribute("rx_power", datasource_->GetSfpRxPower(id));
mutable_channel->AddAttribute("tx_power", datasource_->GetSfpTxPower(id));
mutable_channel->AddAttribute("tx_bias", datasource_->GetSfpTxBias(id));
return ::util::OkStatus();
}
::util::Status OnlpSfpConfigurator::RemoveChannel(int id,
AttributeGroup* channel) {
// lock channel group
auto mutable_channel = channel->AcquireMutable();
// Remove the attributes
mutable_channel->RemoveAttribute("rx_power");
mutable_channel->RemoveAttribute("tx_power");
mutable_channel->RemoveAttribute("tx_bias");
return ::util::OkStatus();
}
} // namespace onlp
} // namespace phal
} // namespace hal
} // namespace stratum
<|endoftext|> |
<commit_before>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
//-----------------------------------------------------------------//
// //
// Implementation of the TOF PID class //
// Origin: Iouri Belikov, CERN, Jouri.Belikov@cern.ch //
// //
//-----------------------------------------------------------------//
#include "TMath.h"
#include "AliLog.h"
#include "AliTOFPIDResponse.h"
ClassImp(AliTOFPIDResponse)
//_________________________________________________________________________
AliTOFPIDResponse::AliTOFPIDResponse():
fSigma(0),
fPmax(0), // zero at 0.5 GeV/c for pp
fTime0(0)
{
fPar[0] = 0.;
fPar[1] = 0.;
fPar[2] = 0.018;
fPar[3] = 50.0;
// Reset T0 info
ResetT0info();
SetMomBoundary();
}
//_________________________________________________________________________
AliTOFPIDResponse::AliTOFPIDResponse(Double_t *param):
fSigma(param[0]),
fPmax(0), // zero at 0.5 GeV/c for pp
fTime0(0)
{
//
// The main constructor
//
//
//fPmax=TMath::Exp(-0.5*3*3)/fSigma; // ~3 sigma at 0.5 GeV/c for PbPb
fPar[0] = 0.;
fPar[1] = 0.;
fPar[2] = 0.018;
fPar[3] = 50.0;
// Reset T0 info
ResetT0info();
SetMomBoundary();
}
//_________________________________________________________________________
Double_t
AliTOFPIDResponse::GetMismatchProbability(Double_t p, Double_t mass) const {
//
// Returns the probability of mismatching
// assuming 1/(p*beta)^2 scaling
//
const Double_t km=0.5; // "reference" momentum (GeV/c)
Double_t ref2=km*km*km*km/(km*km + mass*mass);// "reference" (p*beta)^2
Double_t p2beta2=p*p*p*p/(p*p + mass*mass);
return fPmax*ref2/p2beta2;
}
//_________________________________________________________________________
Double_t AliTOFPIDResponse::GetExpectedSigma(Float_t mom, Float_t time, Float_t mass) const {
//
// Return the expected sigma of the PID signal for the specified
// particle type.
// If the operation is not possible, return a negative value.
//
Double_t dpp=fPar[0] + fPar[1]*mom + fPar[2]*mass/mom; //mean relative pt resolution;
Double_t sigma = dpp*time/(1.+ mom*mom/(mass*mass));
Int_t index = GetMomBin(mom);
Double_t t0res = fT0resolution[index];
return TMath::Sqrt(sigma*sigma + fPar[3]*fPar[3]/mom/mom + fSigma*fSigma + t0res*t0res);
}
//_________________________________________________________________________
Int_t AliTOFPIDResponse::GetMomBin(Float_t p) const{
//
// Returns the momentum bin index
//
Int_t i=0;
while(p > fPCutMin[i] && i < fNmomBins) i++;
if(i > 0) i--;
return i;
}
//_________________________________________________________________________
void AliTOFPIDResponse::SetMomBoundary(){
//
// Set boundaries for momentum bins
//
fPCutMin[0] = 0.3;
fPCutMin[1] = 0.5;
fPCutMin[2] = 0.6;
fPCutMin[3] = 0.7;
fPCutMin[4] = 0.8;
fPCutMin[5] = 0.9;
fPCutMin[6] = 1;
fPCutMin[7] = 1.2;
fPCutMin[8] = 1.5;
fPCutMin[9] = 2;
fPCutMin[10] = 3;
}
//_________________________________________________________________________
Float_t AliTOFPIDResponse::GetStartTime(Float_t mom) const {
//
// Returns event_time value as estimated by TOF combinatorial algorithm
//
Int_t ibin = GetMomBin(mom);
return GetT0bin(ibin);
}
//_________________________________________________________________________
Float_t AliTOFPIDResponse::GetStartTimeRes(Float_t mom) const {
//
// Returns event_time resolution as estimated by TOF combinatorial algorithm
//
Int_t ibin = GetMomBin(mom);
return GetT0binRes(ibin);
}
//_________________________________________________________________________
Int_t AliTOFPIDResponse::GetStartTimeMask(Float_t mom) const {
//
// Returns event_time mask
//
Int_t ibin = GetMomBin(mom);
return GetT0binMask(ibin);
}
<commit_msg>#94948: Change in the TOF response and porting into the v5-02 release<commit_after>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
//-----------------------------------------------------------------//
// //
// Implementation of the TOF PID class //
// Origin: Iouri Belikov, CERN, Jouri.Belikov@cern.ch //
// //
//-----------------------------------------------------------------//
#include "TMath.h"
#include "AliLog.h"
#include "AliTOFPIDResponse.h"
ClassImp(AliTOFPIDResponse)
//_________________________________________________________________________
AliTOFPIDResponse::AliTOFPIDResponse():
fSigma(0),
fPmax(0), // zero at 0.5 GeV/c for pp
fTime0(0)
{
fPar[0] = 0.008;
fPar[1] = 0.008;
fPar[2] = 0.002;
fPar[3] = 40.0;
// Reset T0 info
ResetT0info();
SetMomBoundary();
}
//_________________________________________________________________________
AliTOFPIDResponse::AliTOFPIDResponse(Double_t *param):
fSigma(param[0]),
fPmax(0), // zero at 0.5 GeV/c for pp
fTime0(0)
{
//
// The main constructor
//
//
//fPmax=TMath::Exp(-0.5*3*3)/fSigma; // ~3 sigma at 0.5 GeV/c for PbPb
fPar[0] = 0.008;
fPar[1] = 0.008;
fPar[2] = 0.002;
fPar[3] = 40.0;
// Reset T0 info
ResetT0info();
SetMomBoundary();
}
//_________________________________________________________________________
Double_t
AliTOFPIDResponse::GetMismatchProbability(Double_t p, Double_t mass) const {
//
// Returns the probability of mismatching
// assuming 1/(p*beta)^2 scaling
//
const Double_t km=0.5; // "reference" momentum (GeV/c)
Double_t ref2=km*km*km*km/(km*km + mass*mass);// "reference" (p*beta)^2
Double_t p2beta2=p*p*p*p/(p*p + mass*mass);
return fPmax*ref2/p2beta2;
}
//_________________________________________________________________________
Double_t AliTOFPIDResponse::GetExpectedSigma(Float_t mom, Float_t time, Float_t mass) const {
//
// Return the expected sigma of the PID signal for the specified
// particle type.
// If the operation is not possible, return a negative value.
//
Double_t dpp=fPar[0] + fPar[1]*mom + fPar[2]*mass/mom; //mean relative pt resolution;
Double_t sigma = dpp*time/(1.+ mom*mom/(mass*mass));
Int_t index = GetMomBin(mom);
Double_t t0res = fT0resolution[index];
return TMath::Sqrt(sigma*sigma + fPar[3]*fPar[3]/mom/mom + fSigma*fSigma + t0res*t0res);
}
//_________________________________________________________________________
Int_t AliTOFPIDResponse::GetMomBin(Float_t p) const{
//
// Returns the momentum bin index
//
Int_t i=0;
while(p > fPCutMin[i] && i < fNmomBins) i++;
if(i > 0) i--;
return i;
}
//_________________________________________________________________________
void AliTOFPIDResponse::SetMomBoundary(){
//
// Set boundaries for momentum bins
//
fPCutMin[0] = 0.3;
fPCutMin[1] = 0.5;
fPCutMin[2] = 0.6;
fPCutMin[3] = 0.7;
fPCutMin[4] = 0.8;
fPCutMin[5] = 0.9;
fPCutMin[6] = 1;
fPCutMin[7] = 1.2;
fPCutMin[8] = 1.5;
fPCutMin[9] = 2;
fPCutMin[10] = 3;
}
//_________________________________________________________________________
Float_t AliTOFPIDResponse::GetStartTime(Float_t mom) const {
//
// Returns event_time value as estimated by TOF combinatorial algorithm
//
Int_t ibin = GetMomBin(mom);
return GetT0bin(ibin);
}
//_________________________________________________________________________
Float_t AliTOFPIDResponse::GetStartTimeRes(Float_t mom) const {
//
// Returns event_time resolution as estimated by TOF combinatorial algorithm
//
Int_t ibin = GetMomBin(mom);
return GetT0binRes(ibin);
}
//_________________________________________________________________________
Int_t AliTOFPIDResponse::GetStartTimeMask(Float_t mom) const {
//
// Returns event_time mask
//
Int_t ibin = GetMomBin(mom);
return GetT0binMask(ibin);
}
<|endoftext|> |
<commit_before>/*
This file is part of kdepim.
Copyright (c) 2004 Cornelius Schumacher <schumacher@kde.org>
Copyright (c) 2004 Till Adam <adam@kde.org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#include "kabc_resourcegroupwarebase.h"
#include "kabc_groupwareprefs.h"
#include "folderlister.h"
#include "addressbookadaptor.h"
#include "groupwaredownloadjob.h"
#include "groupwareuploadjob.h"
#include <kabc/addressee.h>
#include <kabc/vcardconverter.h>
#include <klocale.h>
using namespace KABC;
ResourceGroupwareBase::ResourceGroupwareBase( const KConfig *config )
: ResourceCached( config ),
mPrefs(0), mFolderLister(0), mAdaptor(0), mDownloadJob(0), mUploadJob(0)
{
if ( config ) readConfig( config );
}
ResourceGroupwareBase::ResourceGroupwareBase( const KURL &url,
const QString &user,
const QString &password )
: ResourceCached( 0 ),
mPrefs(0), mFolderLister(0), mAdaptor(0), mDownloadJob(0), mUploadJob(0)
{
mBaseUrl = url;
mBaseUrl.setUser( user );
mBaseUrl.setPass( password );
}
ResourceGroupwareBase::~ResourceGroupwareBase()
{
delete mPrefs;
mPrefs = 0;
}
KPIM::GroupwareDownloadJob *ResourceGroupwareBase::createDownloadJob( AddressBookAdaptor *adaptor )
{
return new KPIM::GroupwareDownloadJob( adaptor );
}
KPIM::GroupwareUploadJob *ResourceGroupwareBase::createUploadJob( AddressBookAdaptor *adaptor )
{
return new KPIM::GroupwareUploadJob( adaptor );
}
void ResourceGroupwareBase::setPrefs( GroupwarePrefsBase *newprefs )
{
if ( !newprefs ) return;
if ( mPrefs ) delete mPrefs;
mPrefs = newprefs;
mPrefs->addGroupPrefix( identifier() );
mPrefs->readConfig();
mBaseUrl = KURL( prefs()->url() );
mBaseUrl.setUser( prefs()->user() );
mBaseUrl.setPass( prefs()->password() );
}
void ResourceGroupwareBase::setFolderLister( KPIM::FolderLister *folderLister )
{
if ( !folderLister ) return;
if ( mFolderLister ) delete mFolderLister;
mFolderLister = folderLister;
if ( mAdaptor ) mAdaptor->setFolderLister( mFolderLister );
}
void ResourceGroupwareBase::setAdaptor( AddressBookAdaptor *adaptor )
{
if ( !adaptor ) return;
if ( mAdaptor ) delete mAdaptor;
mAdaptor = adaptor;
mAdaptor->setFolderLister( mFolderLister );
mAdaptor->setDownloadProgressMessage( i18n("Downloading addressbook") );
mAdaptor->setUploadProgressMessage( i18n("Uploading addressbook") );
if ( prefs() ) {
mAdaptor->setUser( prefs()->user() );
mAdaptor->setPassword( prefs()->password() );
}
mAdaptor->setIdMapper( &idMapper() );
mAdaptor->setResource( this );
}
void ResourceGroupwareBase::init()
{
mDownloadJob = 0;
}
GroupwarePrefsBase *ResourceGroupwareBase::createPrefs()
{
return new GroupwarePrefsBase();
}
void ResourceGroupwareBase::readConfig( const KConfig *config )
{
kdDebug(5700) << "KABC::ResourceGroupwareBase::readConfig()" << endl;
// ResourceCached::readConfig( config );
if ( mFolderLister ) {
mFolderLister->readConfig( config );
}
}
void ResourceGroupwareBase::writeConfig( KConfig *config )
{
Resource::writeConfig( config );
mPrefs->writeConfig();
mFolderLister->writeConfig( config );
}
Ticket *ResourceGroupwareBase::requestSaveTicket()
{
if ( !addressBook() ) {
kdDebug(5700) << "no addressbook" << endl;
return 0;
}
return createTicket( this );
}
void ResourceGroupwareBase::releaseSaveTicket( Ticket *ticket )
{
delete ticket;
}
bool ResourceGroupwareBase::doOpen()
{
return true;
}
void ResourceGroupwareBase::doClose()
{
kdDebug(5800) << "ResourceGroupwareBase::doClose()" << endl;
if ( mDownloadJob ) mDownloadJob->kill();
}
bool ResourceGroupwareBase::load()
{
return asyncLoad();
}
bool ResourceGroupwareBase::asyncLoad()
{
if ( mDownloadJob ) {
kdWarning() << "Download still in progress" << endl;
return false;
}
mAddrMap.clear();
loadCache();
mDownloadJob = createDownloadJob( mAdaptor );
connect( mDownloadJob, SIGNAL( result( KPIM::GroupwareJob * ) ),
SLOT( slotDownloadJobResult( KPIM::GroupwareJob * ) ) );
return true;
}
void ResourceGroupwareBase::slotDownloadJobResult( KPIM::GroupwareJob *job )
{
kdDebug(5800) << "ResourceGroupwareBase::slotJobResult(): " << endl;
if ( job->error() ) {
kdError() << "job failed: " << job->errorString() << endl;
} else {
emit loadingFinished( this );
}
mDownloadJob = 0;
}
bool ResourceGroupwareBase::save( Ticket *ticket )
{
return asyncSave( ticket );
}
bool ResourceGroupwareBase::asyncSave( Ticket* )
{
if ( mUploadJob ) {
kdWarning() << "Upload still in progress." << endl;
return false;
}
mUploadJob = createUploadJob( mAdaptor );
connect( mUploadJob, SIGNAL( result( KPIM::GroupwareJob * ) ),
SLOT( slotUploadJobResult( KPIM::GroupwareJob * ) ) );
mUploadJob->setBaseUrl( mBaseUrl );
KABC::Addressee::List addr;
KABC::Addressee::List::Iterator it;
KPIM::GroupwareUploadItem::List addedItems, changedItems, deletedItems;
addr = addedAddressees();
for( it = addr.begin(); it != addr.end(); ++it ) {
addedItems.append( adaptor()->newUploadItem( *it, KPIM::GroupwareUploadItem::Added ) );
}
// TODO: Check if the item has changed on the server...
// In particular, check if the version we based our change on is still current
// on the server
addr = changedAddressees();
for( it = addr.begin(); it != addr.end(); ++it ) {
changedItems.append( adaptor()->newUploadItem( *it, KPIM::GroupwareUploadItem::Changed ) );
}
addr = deletedAddressees();
for( it = addr.begin(); it != addr.end(); ++it ) {
deletedItems.append( adaptor()->newUploadItem( *it, KPIM::GroupwareUploadItem::Deleted ) );
}
mUploadJob->setAddedItems( addedItems );
mUploadJob->setChangedItems( changedItems );
mUploadJob->setDeletedItems( deletedItems );
return true;
}
void ResourceGroupwareBase::slotUploadJobResult( KPIM::GroupwareJob *job )
{
kdDebug(5800) << "ResourceGroupwareBase::slotJobResult(): " << endl;
if ( job->error() ) {
kdError() << "job failed: " << job->errorString() << endl;
} else {
}
mUploadJob = 0;
}
#include "kabc_resourcegroupwarebase.moc"
<commit_msg>FIXMEs for myself<commit_after>/*
This file is part of kdepim.
Copyright (c) 2004 Cornelius Schumacher <schumacher@kde.org>
Copyright (c) 2004 Till Adam <adam@kde.org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#include "kabc_resourcegroupwarebase.h"
#include "kabc_groupwareprefs.h"
#include "folderlister.h"
#include "addressbookadaptor.h"
#include "groupwaredownloadjob.h"
#include "groupwareuploadjob.h"
#include <kabc/addressee.h>
#include <kabc/vcardconverter.h>
#include <klocale.h>
using namespace KABC;
ResourceGroupwareBase::ResourceGroupwareBase( const KConfig *config )
: ResourceCached( config ),
mPrefs(0), mFolderLister(0), mAdaptor(0), mDownloadJob(0), mUploadJob(0)
{
if ( config ) readConfig( config );
}
ResourceGroupwareBase::ResourceGroupwareBase( const KURL &url,
const QString &user,
const QString &password )
: ResourceCached( 0 ),
mPrefs(0), mFolderLister(0), mAdaptor(0), mDownloadJob(0), mUploadJob(0)
{
mBaseUrl = url;
mBaseUrl.setUser( user );
mBaseUrl.setPass( password );
}
ResourceGroupwareBase::~ResourceGroupwareBase()
{
delete mPrefs;
mPrefs = 0;
}
KPIM::GroupwareDownloadJob *ResourceGroupwareBase::createDownloadJob( AddressBookAdaptor *adaptor )
{
return new KPIM::GroupwareDownloadJob( adaptor );
}
KPIM::GroupwareUploadJob *ResourceGroupwareBase::createUploadJob( AddressBookAdaptor *adaptor )
{
return new KPIM::GroupwareUploadJob( adaptor );
}
void ResourceGroupwareBase::setPrefs( GroupwarePrefsBase *newprefs )
{
if ( !newprefs ) return;
if ( mPrefs ) delete mPrefs;
mPrefs = newprefs;
mPrefs->addGroupPrefix( identifier() );
mPrefs->readConfig();
mBaseUrl = KURL( prefs()->url() );
mBaseUrl.setUser( prefs()->user() );
mBaseUrl.setPass( prefs()->password() );
}
void ResourceGroupwareBase::setFolderLister( KPIM::FolderLister *folderLister )
{
if ( !folderLister ) return;
if ( mFolderLister ) delete mFolderLister;
mFolderLister = folderLister;
if ( mAdaptor ) mAdaptor->setFolderLister( mFolderLister );
}
void ResourceGroupwareBase::setAdaptor( AddressBookAdaptor *adaptor )
{
if ( !adaptor ) return;
if ( mAdaptor ) delete mAdaptor;
mAdaptor = adaptor;
mAdaptor->setFolderLister( mFolderLister );
mAdaptor->setDownloadProgressMessage( i18n("Downloading addressbook") );
mAdaptor->setUploadProgressMessage( i18n("Uploading addressbook") );
if ( prefs() ) {
mAdaptor->setUser( prefs()->user() );
mAdaptor->setPassword( prefs()->password() );
}
mAdaptor->setIdMapper( &idMapper() );
mAdaptor->setResource( this );
}
void ResourceGroupwareBase::init()
{
mDownloadJob = 0;
}
GroupwarePrefsBase *ResourceGroupwareBase::createPrefs()
{
return new GroupwarePrefsBase();
}
void ResourceGroupwareBase::readConfig( const KConfig *config )
{
kdDebug(5700) << "KABC::ResourceGroupwareBase::readConfig()" << endl;
// ResourceCached::readConfig( config );
if ( mFolderLister ) {
mFolderLister->readConfig( config );
}
}
void ResourceGroupwareBase::writeConfig( KConfig *config )
{
Resource::writeConfig( config );
mPrefs->writeConfig();
mFolderLister->writeConfig( config );
}
Ticket *ResourceGroupwareBase::requestSaveTicket()
{
if ( !addressBook() ) {
kdDebug(5700) << "no addressbook" << endl;
return 0;
}
return createTicket( this );
}
void ResourceGroupwareBase::releaseSaveTicket( Ticket *ticket )
{
delete ticket;
}
bool ResourceGroupwareBase::doOpen()
{
return true;
}
void ResourceGroupwareBase::doClose()
{
kdDebug(5800) << "ResourceGroupwareBase::doClose()" << endl;
if ( mDownloadJob ) mDownloadJob->kill();
}
bool ResourceGroupwareBase::load()
{
return asyncLoad();
}
bool ResourceGroupwareBase::asyncLoad()
{
if ( mDownloadJob ) {
kdWarning() << "Download still in progress" << endl;
return false;
}
mAddrMap.clear();
loadCache();
mDownloadJob = createDownloadJob( mAdaptor );
connect( mDownloadJob, SIGNAL( result( KPIM::GroupwareJob * ) ),
SLOT( slotDownloadJobResult( KPIM::GroupwareJob * ) ) );
return true;
}
void ResourceGroupwareBase::slotDownloadJobResult( KPIM::GroupwareJob *job )
{
kdDebug(5800) << "ResourceGroupwareBase::slotJobResult(): " << endl;
if ( job->error() ) {
kdError() << "job failed: " << job->errorString() << endl;
} else {
emit loadingFinished( this );
}
mDownloadJob = 0;
}
bool ResourceGroupwareBase::save( Ticket *ticket )
{
return asyncSave( ticket );
}
bool ResourceGroupwareBase::asyncSave( Ticket* )
{
if ( mUploadJob ) {
// FIXME: If the user cancels, we need to reset the mUploadJob variable to 0.
kdWarning() << "Upload still in progress." << endl;
return false;
}
mUploadJob = createUploadJob( mAdaptor );
connect( mUploadJob, SIGNAL( result( KPIM::GroupwareJob * ) ),
SLOT( slotUploadJobResult( KPIM::GroupwareJob * ) ) );
mUploadJob->setBaseUrl( mBaseUrl );
KABC::Addressee::List addr;
KABC::Addressee::List::Iterator it;
KPIM::GroupwareUploadItem::List addedItems, changedItems, deletedItems;
addr = addedAddressees();
for( it = addr.begin(); it != addr.end(); ++it ) {
addedItems.append( adaptor()->newUploadItem( *it, KPIM::GroupwareUploadItem::Added ) );
}
// TODO: Check if the item has changed on the server...
// In particular, check if the version we based our change on is still current
// on the server
addr = changedAddressees();
for( it = addr.begin(); it != addr.end(); ++it ) {
changedItems.append( adaptor()->newUploadItem( *it, KPIM::GroupwareUploadItem::Changed ) );
}
addr = deletedAddressees();
for( it = addr.begin(); it != addr.end(); ++it ) {
deletedItems.append( adaptor()->newUploadItem( *it, KPIM::GroupwareUploadItem::Deleted ) );
}
mUploadJob->setAddedItems( addedItems );
mUploadJob->setChangedItems( changedItems );
mUploadJob->setDeletedItems( deletedItems );
return true;
}
void ResourceGroupwareBase::slotUploadJobResult( KPIM::GroupwareJob *job )
{
kdDebug(5800) << "ResourceGroupwareBase::slotJobResult(): " << endl;
if ( job->error() ) {
kdError() << "job failed: " << job->errorString() << endl;
} else {
// FIXME
}
mUploadJob = 0;
}
#include "kabc_resourcegroupwarebase.moc"
<|endoftext|> |
<commit_before>// Copyright 2014 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/base/platform/time.h"
#if V8_OS_MACOSX
#include <mach/mach_time.h>
#endif
#if V8_OS_POSIX
#include <sys/time.h>
#endif
#if V8_OS_WIN
#include "src/base/win32-headers.h"
#endif
#include "src/base/platform/elapsed-timer.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace v8 {
namespace base {
TEST(TimeDelta, FromAndIn) {
EXPECT_EQ(TimeDelta::FromDays(2), TimeDelta::FromHours(48));
EXPECT_EQ(TimeDelta::FromHours(3), TimeDelta::FromMinutes(180));
EXPECT_EQ(TimeDelta::FromMinutes(2), TimeDelta::FromSeconds(120));
EXPECT_EQ(TimeDelta::FromSeconds(2), TimeDelta::FromMilliseconds(2000));
EXPECT_EQ(TimeDelta::FromMilliseconds(2), TimeDelta::FromMicroseconds(2000));
EXPECT_EQ(static_cast<int>(13), TimeDelta::FromDays(13).InDays());
EXPECT_EQ(static_cast<int>(13), TimeDelta::FromHours(13).InHours());
EXPECT_EQ(static_cast<int>(13), TimeDelta::FromMinutes(13).InMinutes());
EXPECT_EQ(static_cast<int64_t>(13), TimeDelta::FromSeconds(13).InSeconds());
EXPECT_EQ(13.0, TimeDelta::FromSeconds(13).InSecondsF());
EXPECT_EQ(static_cast<int64_t>(13),
TimeDelta::FromMilliseconds(13).InMilliseconds());
EXPECT_EQ(13.0, TimeDelta::FromMilliseconds(13).InMillisecondsF());
EXPECT_EQ(static_cast<int64_t>(13),
TimeDelta::FromMicroseconds(13).InMicroseconds());
}
#if V8_OS_MACOSX
TEST(TimeDelta, MachTimespec) {
TimeDelta null = TimeDelta();
EXPECT_EQ(null, TimeDelta::FromMachTimespec(null.ToMachTimespec()));
TimeDelta delta1 = TimeDelta::FromMilliseconds(42);
EXPECT_EQ(delta1, TimeDelta::FromMachTimespec(delta1.ToMachTimespec()));
TimeDelta delta2 = TimeDelta::FromDays(42);
EXPECT_EQ(delta2, TimeDelta::FromMachTimespec(delta2.ToMachTimespec()));
}
#endif
TEST(Time, JsTime) {
Time t = Time::FromJsTime(700000.3);
EXPECT_EQ(700000.3, t.ToJsTime());
}
#if V8_OS_POSIX
TEST(Time, Timespec) {
Time null;
EXPECT_TRUE(null.IsNull());
EXPECT_EQ(null, Time::FromTimespec(null.ToTimespec()));
Time now = Time::Now();
EXPECT_EQ(now, Time::FromTimespec(now.ToTimespec()));
Time now_sys = Time::NowFromSystemTime();
EXPECT_EQ(now_sys, Time::FromTimespec(now_sys.ToTimespec()));
Time unix_epoch = Time::UnixEpoch();
EXPECT_EQ(unix_epoch, Time::FromTimespec(unix_epoch.ToTimespec()));
Time max = Time::Max();
EXPECT_TRUE(max.IsMax());
EXPECT_EQ(max, Time::FromTimespec(max.ToTimespec()));
}
TEST(Time, Timeval) {
Time null;
EXPECT_TRUE(null.IsNull());
EXPECT_EQ(null, Time::FromTimeval(null.ToTimeval()));
Time now = Time::Now();
EXPECT_EQ(now, Time::FromTimeval(now.ToTimeval()));
Time now_sys = Time::NowFromSystemTime();
EXPECT_EQ(now_sys, Time::FromTimeval(now_sys.ToTimeval()));
Time unix_epoch = Time::UnixEpoch();
EXPECT_EQ(unix_epoch, Time::FromTimeval(unix_epoch.ToTimeval()));
Time max = Time::Max();
EXPECT_TRUE(max.IsMax());
EXPECT_EQ(max, Time::FromTimeval(max.ToTimeval()));
}
#endif
#if V8_OS_WIN
TEST(Time, Filetime) {
Time null;
EXPECT_TRUE(null.IsNull());
EXPECT_EQ(null, Time::FromFiletime(null.ToFiletime()));
Time now = Time::Now();
EXPECT_EQ(now, Time::FromFiletime(now.ToFiletime()));
Time now_sys = Time::NowFromSystemTime();
EXPECT_EQ(now_sys, Time::FromFiletime(now_sys.ToFiletime()));
Time unix_epoch = Time::UnixEpoch();
EXPECT_EQ(unix_epoch, Time::FromFiletime(unix_epoch.ToFiletime()));
Time max = Time::Max();
EXPECT_TRUE(max.IsMax());
EXPECT_EQ(max, Time::FromFiletime(max.ToFiletime()));
}
#endif
namespace {
template <typename T>
static void ResolutionTest(T (*Now)(), TimeDelta target_granularity) {
// We're trying to measure that intervals increment in a VERY small amount
// of time -- according to the specified target granularity. Unfortunately,
// if we happen to have a context switch in the middle of our test, the
// context switch could easily exceed our limit. So, we iterate on this
// several times. As long as we're able to detect the fine-granularity
// timers at least once, then the test has succeeded.
static const TimeDelta kExpirationTimeout = TimeDelta::FromSeconds(1);
ElapsedTimer timer;
timer.Start();
TimeDelta delta;
do {
T start = Now();
T now = start;
// Loop until we can detect that the clock has changed. Non-HighRes timers
// will increment in chunks, i.e. 15ms. By spinning until we see a clock
// change, we detect the minimum time between measurements.
do {
now = Now();
delta = now - start;
} while (now <= start);
EXPECT_NE(static_cast<int64_t>(0), delta.InMicroseconds());
} while (delta > target_granularity && !timer.HasExpired(kExpirationTimeout));
EXPECT_LE(delta, target_granularity);
}
}
TEST(Time, NowResolution) {
// We assume that Time::Now() has at least 16ms resolution.
static const TimeDelta kTargetGranularity = TimeDelta::FromMilliseconds(16);
ResolutionTest<Time>(&Time::Now, kTargetGranularity);
}
TEST(TimeTicks, NowResolution) {
// We assume that TimeTicks::Now() has at least 16ms resolution.
static const TimeDelta kTargetGranularity = TimeDelta::FromMilliseconds(16);
ResolutionTest<TimeTicks>(&TimeTicks::Now, kTargetGranularity);
}
TEST(TimeTicks, HighResolutionNowResolution) {
if (!TimeTicks::IsHighResolutionClockWorking()) return;
// We assume that TimeTicks::HighResolutionNow() has sub-ms resolution.
static const TimeDelta kTargetGranularity = TimeDelta::FromMilliseconds(1);
ResolutionTest<TimeTicks>(&TimeTicks::HighResolutionNow, kTargetGranularity);
}
TEST(TimeTicks, IsMonotonic) {
TimeTicks previous_normal_ticks;
TimeTicks previous_highres_ticks;
ElapsedTimer timer;
timer.Start();
while (!timer.HasExpired(TimeDelta::FromMilliseconds(100))) {
TimeTicks normal_ticks = TimeTicks::Now();
TimeTicks highres_ticks = TimeTicks::HighResolutionNow();
EXPECT_GE(normal_ticks, previous_normal_ticks);
EXPECT_GE((normal_ticks - previous_normal_ticks).InMicroseconds(), 0);
EXPECT_GE(highres_ticks, previous_highres_ticks);
EXPECT_GE((highres_ticks - previous_highres_ticks).InMicroseconds(), 0);
previous_normal_ticks = normal_ticks;
previous_highres_ticks = highres_ticks;
}
}
} // namespace base
} // namespace v8
<commit_msg>Use EXPECT_DOUBLE_EQ for floating point comparisons.<commit_after>// Copyright 2014 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/base/platform/time.h"
#if V8_OS_MACOSX
#include <mach/mach_time.h>
#endif
#if V8_OS_POSIX
#include <sys/time.h>
#endif
#if V8_OS_WIN
#include "src/base/win32-headers.h"
#endif
#include "src/base/platform/elapsed-timer.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace v8 {
namespace base {
TEST(TimeDelta, FromAndIn) {
EXPECT_EQ(TimeDelta::FromDays(2), TimeDelta::FromHours(48));
EXPECT_EQ(TimeDelta::FromHours(3), TimeDelta::FromMinutes(180));
EXPECT_EQ(TimeDelta::FromMinutes(2), TimeDelta::FromSeconds(120));
EXPECT_EQ(TimeDelta::FromSeconds(2), TimeDelta::FromMilliseconds(2000));
EXPECT_EQ(TimeDelta::FromMilliseconds(2), TimeDelta::FromMicroseconds(2000));
EXPECT_EQ(static_cast<int>(13), TimeDelta::FromDays(13).InDays());
EXPECT_EQ(static_cast<int>(13), TimeDelta::FromHours(13).InHours());
EXPECT_EQ(static_cast<int>(13), TimeDelta::FromMinutes(13).InMinutes());
EXPECT_EQ(static_cast<int64_t>(13), TimeDelta::FromSeconds(13).InSeconds());
EXPECT_DOUBLE_EQ(13.0, TimeDelta::FromSeconds(13).InSecondsF());
EXPECT_EQ(static_cast<int64_t>(13),
TimeDelta::FromMilliseconds(13).InMilliseconds());
EXPECT_DOUBLE_EQ(13.0, TimeDelta::FromMilliseconds(13).InMillisecondsF());
EXPECT_EQ(static_cast<int64_t>(13),
TimeDelta::FromMicroseconds(13).InMicroseconds());
}
#if V8_OS_MACOSX
TEST(TimeDelta, MachTimespec) {
TimeDelta null = TimeDelta();
EXPECT_EQ(null, TimeDelta::FromMachTimespec(null.ToMachTimespec()));
TimeDelta delta1 = TimeDelta::FromMilliseconds(42);
EXPECT_EQ(delta1, TimeDelta::FromMachTimespec(delta1.ToMachTimespec()));
TimeDelta delta2 = TimeDelta::FromDays(42);
EXPECT_EQ(delta2, TimeDelta::FromMachTimespec(delta2.ToMachTimespec()));
}
#endif
TEST(Time, JsTime) {
Time t = Time::FromJsTime(700000.3);
EXPECT_DOUBLE_EQ(700000.3, t.ToJsTime());
}
#if V8_OS_POSIX
TEST(Time, Timespec) {
Time null;
EXPECT_TRUE(null.IsNull());
EXPECT_EQ(null, Time::FromTimespec(null.ToTimespec()));
Time now = Time::Now();
EXPECT_EQ(now, Time::FromTimespec(now.ToTimespec()));
Time now_sys = Time::NowFromSystemTime();
EXPECT_EQ(now_sys, Time::FromTimespec(now_sys.ToTimespec()));
Time unix_epoch = Time::UnixEpoch();
EXPECT_EQ(unix_epoch, Time::FromTimespec(unix_epoch.ToTimespec()));
Time max = Time::Max();
EXPECT_TRUE(max.IsMax());
EXPECT_EQ(max, Time::FromTimespec(max.ToTimespec()));
}
TEST(Time, Timeval) {
Time null;
EXPECT_TRUE(null.IsNull());
EXPECT_EQ(null, Time::FromTimeval(null.ToTimeval()));
Time now = Time::Now();
EXPECT_EQ(now, Time::FromTimeval(now.ToTimeval()));
Time now_sys = Time::NowFromSystemTime();
EXPECT_EQ(now_sys, Time::FromTimeval(now_sys.ToTimeval()));
Time unix_epoch = Time::UnixEpoch();
EXPECT_EQ(unix_epoch, Time::FromTimeval(unix_epoch.ToTimeval()));
Time max = Time::Max();
EXPECT_TRUE(max.IsMax());
EXPECT_EQ(max, Time::FromTimeval(max.ToTimeval()));
}
#endif
#if V8_OS_WIN
TEST(Time, Filetime) {
Time null;
EXPECT_TRUE(null.IsNull());
EXPECT_EQ(null, Time::FromFiletime(null.ToFiletime()));
Time now = Time::Now();
EXPECT_EQ(now, Time::FromFiletime(now.ToFiletime()));
Time now_sys = Time::NowFromSystemTime();
EXPECT_EQ(now_sys, Time::FromFiletime(now_sys.ToFiletime()));
Time unix_epoch = Time::UnixEpoch();
EXPECT_EQ(unix_epoch, Time::FromFiletime(unix_epoch.ToFiletime()));
Time max = Time::Max();
EXPECT_TRUE(max.IsMax());
EXPECT_EQ(max, Time::FromFiletime(max.ToFiletime()));
}
#endif
namespace {
template <typename T>
static void ResolutionTest(T (*Now)(), TimeDelta target_granularity) {
// We're trying to measure that intervals increment in a VERY small amount
// of time -- according to the specified target granularity. Unfortunately,
// if we happen to have a context switch in the middle of our test, the
// context switch could easily exceed our limit. So, we iterate on this
// several times. As long as we're able to detect the fine-granularity
// timers at least once, then the test has succeeded.
static const TimeDelta kExpirationTimeout = TimeDelta::FromSeconds(1);
ElapsedTimer timer;
timer.Start();
TimeDelta delta;
do {
T start = Now();
T now = start;
// Loop until we can detect that the clock has changed. Non-HighRes timers
// will increment in chunks, i.e. 15ms. By spinning until we see a clock
// change, we detect the minimum time between measurements.
do {
now = Now();
delta = now - start;
} while (now <= start);
EXPECT_NE(static_cast<int64_t>(0), delta.InMicroseconds());
} while (delta > target_granularity && !timer.HasExpired(kExpirationTimeout));
EXPECT_LE(delta, target_granularity);
}
}
TEST(Time, NowResolution) {
// We assume that Time::Now() has at least 16ms resolution.
static const TimeDelta kTargetGranularity = TimeDelta::FromMilliseconds(16);
ResolutionTest<Time>(&Time::Now, kTargetGranularity);
}
TEST(TimeTicks, NowResolution) {
// We assume that TimeTicks::Now() has at least 16ms resolution.
static const TimeDelta kTargetGranularity = TimeDelta::FromMilliseconds(16);
ResolutionTest<TimeTicks>(&TimeTicks::Now, kTargetGranularity);
}
TEST(TimeTicks, HighResolutionNowResolution) {
if (!TimeTicks::IsHighResolutionClockWorking()) return;
// We assume that TimeTicks::HighResolutionNow() has sub-ms resolution.
static const TimeDelta kTargetGranularity = TimeDelta::FromMilliseconds(1);
ResolutionTest<TimeTicks>(&TimeTicks::HighResolutionNow, kTargetGranularity);
}
TEST(TimeTicks, IsMonotonic) {
TimeTicks previous_normal_ticks;
TimeTicks previous_highres_ticks;
ElapsedTimer timer;
timer.Start();
while (!timer.HasExpired(TimeDelta::FromMilliseconds(100))) {
TimeTicks normal_ticks = TimeTicks::Now();
TimeTicks highres_ticks = TimeTicks::HighResolutionNow();
EXPECT_GE(normal_ticks, previous_normal_ticks);
EXPECT_GE((normal_ticks - previous_normal_ticks).InMicroseconds(), 0);
EXPECT_GE(highres_ticks, previous_highres_ticks);
EXPECT_GE((highres_ticks - previous_highres_ticks).InMicroseconds(), 0);
previous_normal_ticks = normal_ticks;
previous_highres_ticks = highres_ticks;
}
}
} // namespace base
} // namespace v8
<|endoftext|> |
<commit_before>/*
//////////////////////////////////
// This File has been generated //
// by Expressik light generator //
// Powered by : Eve CSTB //
//////////////////////////////////
* *************************************************************************
* *
* STEP Early Classes C++ *
* *
* Copyright (C) 2009 CSTB *
* *
* *
* For further information please contact *
* *
* eve@cstb.fr *
* or *
* Mod-Eve, CSTB *
* 290, route des Lucioles *
* BP 209 *
* 06904 Sophia Antipolis, France *
* *
***************************************************************************
*/
#include "ifc2x3/IfcGeometricRepresentationContext.h"
#include "ifc2x3/CopyOp.h"
#include "ifc2x3/IfcAxis2Placement.h"
#include "ifc2x3/IfcDirection.h"
#include "ifc2x3/IfcGeometricRepresentationSubContext.h"
#include "ifc2x3/IfcRepresentationContext.h"
#include "ifc2x3/Visitor.h"
#include <Step/BaseExpressDataSet.h>
#include <Step/BaseObject.h>
#include <Step/ClassType.h>
#include <Step/Referenced.h>
#include <Step/SPFFunctions.h>
#include <Step/logger.h>
#include <stdlib.h>
#include <string>
#include <vector>
using namespace ifc2x3;
IfcGeometricRepresentationContext::IfcGeometricRepresentationContext(Step::Id id, Step::SPFData *args) : IfcRepresentationContext(id, args) {
m_coordinateSpaceDimension = Step::getUnset(m_coordinateSpaceDimension);
m_precision = Step::getUnset(m_precision);
m_worldCoordinateSystem = new IfcAxis2Placement;
m_trueNorth = NULL;
}
IfcGeometricRepresentationContext::~IfcGeometricRepresentationContext() {
}
bool IfcGeometricRepresentationContext::acceptVisitor(Step::BaseVisitor *visitor) {
return static_cast< Visitor * > (visitor)->visitIfcGeometricRepresentationContext(this);
}
const std::string &IfcGeometricRepresentationContext::type() const {
return IfcGeometricRepresentationContext::s_type.getName();
}
const Step::ClassType &IfcGeometricRepresentationContext::getClassType() {
return IfcGeometricRepresentationContext::s_type;
}
const Step::ClassType &IfcGeometricRepresentationContext::getType() const {
return IfcGeometricRepresentationContext::s_type;
}
bool IfcGeometricRepresentationContext::isOfType(const Step::ClassType &t) const {
return IfcGeometricRepresentationContext::s_type == t ? true : IfcRepresentationContext::isOfType(t);
}
IfcDimensionCount IfcGeometricRepresentationContext::getCoordinateSpaceDimension() {
if (Step::BaseObject::inited()) {
return m_coordinateSpaceDimension;
}
else {
return Step::getUnset(m_coordinateSpaceDimension);
}
}
const IfcDimensionCount IfcGeometricRepresentationContext::getCoordinateSpaceDimension() const {
IfcGeometricRepresentationContext * deConstObject = const_cast< IfcGeometricRepresentationContext * > (this);
return deConstObject->getCoordinateSpaceDimension();
}
void IfcGeometricRepresentationContext::setCoordinateSpaceDimension(IfcDimensionCount value) {
m_coordinateSpaceDimension = value;
}
void IfcGeometricRepresentationContext::unsetCoordinateSpaceDimension() {
m_coordinateSpaceDimension = Step::getUnset(getCoordinateSpaceDimension());
}
bool IfcGeometricRepresentationContext::testCoordinateSpaceDimension() const {
return !Step::isUnset(getCoordinateSpaceDimension());
}
Step::Real IfcGeometricRepresentationContext::getPrecision() {
if (Step::BaseObject::inited()) {
return m_precision;
}
else {
return Step::getUnset(m_precision);
}
}
const Step::Real IfcGeometricRepresentationContext::getPrecision() const {
IfcGeometricRepresentationContext * deConstObject = const_cast< IfcGeometricRepresentationContext * > (this);
return deConstObject->getPrecision();
}
void IfcGeometricRepresentationContext::setPrecision(Step::Real value) {
m_precision = value;
}
void IfcGeometricRepresentationContext::unsetPrecision() {
m_precision = Step::getUnset(getPrecision());
}
bool IfcGeometricRepresentationContext::testPrecision() const {
return !Step::isUnset(getPrecision());
}
IfcAxis2Placement *IfcGeometricRepresentationContext::getWorldCoordinateSystem() {
if (Step::BaseObject::inited()) {
return m_worldCoordinateSystem.get();
}
else {
return NULL;
}
}
const IfcAxis2Placement *IfcGeometricRepresentationContext::getWorldCoordinateSystem() const {
IfcGeometricRepresentationContext * deConstObject = const_cast< IfcGeometricRepresentationContext * > (this);
return deConstObject->getWorldCoordinateSystem();
}
void IfcGeometricRepresentationContext::setWorldCoordinateSystem(const Step::RefPtr< IfcAxis2Placement > &value) {
m_worldCoordinateSystem = value;
}
void IfcGeometricRepresentationContext::unsetWorldCoordinateSystem() {
m_worldCoordinateSystem = Step::getUnset(getWorldCoordinateSystem());
}
bool IfcGeometricRepresentationContext::testWorldCoordinateSystem() const {
return !Step::isUnset(getWorldCoordinateSystem());
}
IfcDirection *IfcGeometricRepresentationContext::getTrueNorth() {
if (Step::BaseObject::inited()) {
return m_trueNorth.get();
}
else {
return NULL;
}
}
const IfcDirection *IfcGeometricRepresentationContext::getTrueNorth() const {
IfcGeometricRepresentationContext * deConstObject = const_cast< IfcGeometricRepresentationContext * > (this);
return deConstObject->getTrueNorth();
}
void IfcGeometricRepresentationContext::setTrueNorth(const Step::RefPtr< IfcDirection > &value) {
m_trueNorth = value;
}
void IfcGeometricRepresentationContext::unsetTrueNorth() {
m_trueNorth = Step::getUnset(getTrueNorth());
}
bool IfcGeometricRepresentationContext::testTrueNorth() const {
return !Step::isUnset(getTrueNorth());
}
Inverse_Set_IfcGeometricRepresentationSubContext_0_n &IfcGeometricRepresentationContext::getHasSubContexts() {
if (Step::BaseObject::inited()) {
return m_hasSubContexts;
}
else {
m_hasSubContexts.setUnset(true);
return m_hasSubContexts;
}
}
const Inverse_Set_IfcGeometricRepresentationSubContext_0_n &IfcGeometricRepresentationContext::getHasSubContexts() const {
IfcGeometricRepresentationContext * deConstObject = const_cast< IfcGeometricRepresentationContext * > (this);
return deConstObject->getHasSubContexts();
}
bool IfcGeometricRepresentationContext::testHasSubContexts() const {
return !Step::isUnset(getHasSubContexts());
}
bool IfcGeometricRepresentationContext::init() {
bool status = IfcRepresentationContext::init();
std::string arg;
std::vector< Step::Id > *inverses;
if (!status) {
return false;
}
arg = m_args->getNext();
if (arg == "$" || arg == "*") {
m_coordinateSpaceDimension = Step::getUnset(m_coordinateSpaceDimension);
}
else {
m_coordinateSpaceDimension = Step::spfToInteger(arg);
}
arg = m_args->getNext();
if (arg == "$" || arg == "*") {
m_precision = Step::getUnset(m_precision);
}
else {
m_precision = Step::spfToReal(arg);
}
arg = m_args->getNext();
if (arg == "$" || arg == "*") {
m_worldCoordinateSystem = NULL;
}
else {
m_worldCoordinateSystem = new IfcAxis2Placement;
if (arg[0] == '#') {
m_worldCoordinateSystem->set(m_expressDataSet->get(atoi(arg.c_str() + 1)));
}
else if (arg[arg.length() - 1] == ')') {
std::string type1;
unsigned int i1;
i1 = arg.find('(');
if (i1 != std::string::npos) {
type1 = arg.substr(0, i1);
arg = arg.substr(i1 + 1, arg.length() - i1 - 2);
}
}
}
arg = m_args->getNext();
if (arg == "$" || arg == "*") {
m_trueNorth = NULL;
}
else {
m_trueNorth = static_cast< IfcDirection * > (m_expressDataSet->get(Step::getIdParam(arg)));
}
inverses = m_args->getInverses(IfcGeometricRepresentationSubContext::getClassType(), 6);
if (inverses) {
unsigned int i;
m_hasSubContexts.setUnset(false);
for (i = 0; i < inverses->size(); i++) {
m_hasSubContexts.insert(static_cast< IfcGeometricRepresentationSubContext * > (m_expressDataSet->get((*inverses)[i])));
}
}
return true;
}
void IfcGeometricRepresentationContext::copy(const IfcGeometricRepresentationContext &obj, const CopyOp ©op) {
IfcRepresentationContext::copy(obj, copyop);
setCoordinateSpaceDimension(obj.m_coordinateSpaceDimension);
setPrecision(obj.m_precision);
m_worldCoordinateSystem = new IfcAxis2Placement;
m_worldCoordinateSystem->copy(*(obj.m_worldCoordinateSystem.get()), copyop);
setTrueNorth((IfcDirection*)copyop(obj.m_trueNorth.get()));
return;
}
IFC2X3_DLL_DEF Step::ClassType IfcGeometricRepresentationContext::s_type("IfcGeometricRepresentationContext");
<commit_msg> init was setting the Select to null<commit_after>/*
//////////////////////////////////
// This File has been generated //
// by Expressik light generator //
// Powered by : Eve CSTB //
//////////////////////////////////
* *************************************************************************
* *
* STEP Early Classes C++ *
* *
* Copyright (C) 2009 CSTB *
* *
* *
* For further information please contact *
* *
* eve@cstb.fr *
* or *
* Mod-Eve, CSTB *
* 290, route des Lucioles *
* BP 209 *
* 06904 Sophia Antipolis, France *
* *
***************************************************************************
*/
#include "ifc2x3/IfcGeometricRepresentationContext.h"
#include "ifc2x3/CopyOp.h"
#include "ifc2x3/IfcAxis2Placement.h"
#include "ifc2x3/IfcDirection.h"
#include "ifc2x3/IfcGeometricRepresentationSubContext.h"
#include "ifc2x3/IfcRepresentationContext.h"
#include "ifc2x3/Visitor.h"
#include <Step/BaseExpressDataSet.h>
#include <Step/BaseObject.h>
#include <Step/ClassType.h>
#include <Step/Referenced.h>
#include <Step/SPFFunctions.h>
#include <Step/logger.h>
#include <stdlib.h>
#include <string>
#include <vector>
using namespace ifc2x3;
IfcGeometricRepresentationContext::IfcGeometricRepresentationContext(Step::Id id, Step::SPFData *args) : IfcRepresentationContext(id, args) {
m_coordinateSpaceDimension = Step::getUnset(m_coordinateSpaceDimension);
m_precision = Step::getUnset(m_precision);
m_worldCoordinateSystem = new IfcAxis2Placement;
m_trueNorth = NULL;
}
IfcGeometricRepresentationContext::~IfcGeometricRepresentationContext() {
}
bool IfcGeometricRepresentationContext::acceptVisitor(Step::BaseVisitor *visitor) {
return static_cast< Visitor * > (visitor)->visitIfcGeometricRepresentationContext(this);
}
const std::string &IfcGeometricRepresentationContext::type() const {
return IfcGeometricRepresentationContext::s_type.getName();
}
const Step::ClassType &IfcGeometricRepresentationContext::getClassType() {
return IfcGeometricRepresentationContext::s_type;
}
const Step::ClassType &IfcGeometricRepresentationContext::getType() const {
return IfcGeometricRepresentationContext::s_type;
}
bool IfcGeometricRepresentationContext::isOfType(const Step::ClassType &t) const {
return IfcGeometricRepresentationContext::s_type == t ? true : IfcRepresentationContext::isOfType(t);
}
IfcDimensionCount IfcGeometricRepresentationContext::getCoordinateSpaceDimension() {
if (Step::BaseObject::inited()) {
return m_coordinateSpaceDimension;
}
else {
return Step::getUnset(m_coordinateSpaceDimension);
}
}
const IfcDimensionCount IfcGeometricRepresentationContext::getCoordinateSpaceDimension() const {
IfcGeometricRepresentationContext * deConstObject = const_cast< IfcGeometricRepresentationContext * > (this);
return deConstObject->getCoordinateSpaceDimension();
}
void IfcGeometricRepresentationContext::setCoordinateSpaceDimension(IfcDimensionCount value) {
m_coordinateSpaceDimension = value;
}
void IfcGeometricRepresentationContext::unsetCoordinateSpaceDimension() {
m_coordinateSpaceDimension = Step::getUnset(getCoordinateSpaceDimension());
}
bool IfcGeometricRepresentationContext::testCoordinateSpaceDimension() const {
return !Step::isUnset(getCoordinateSpaceDimension());
}
Step::Real IfcGeometricRepresentationContext::getPrecision() {
if (Step::BaseObject::inited()) {
return m_precision;
}
else {
return Step::getUnset(m_precision);
}
}
const Step::Real IfcGeometricRepresentationContext::getPrecision() const {
IfcGeometricRepresentationContext * deConstObject = const_cast< IfcGeometricRepresentationContext * > (this);
return deConstObject->getPrecision();
}
void IfcGeometricRepresentationContext::setPrecision(Step::Real value) {
m_precision = value;
}
void IfcGeometricRepresentationContext::unsetPrecision() {
m_precision = Step::getUnset(getPrecision());
}
bool IfcGeometricRepresentationContext::testPrecision() const {
return !Step::isUnset(getPrecision());
}
IfcAxis2Placement *IfcGeometricRepresentationContext::getWorldCoordinateSystem() {
if (Step::BaseObject::inited()) {
return m_worldCoordinateSystem.get();
}
else {
return NULL;
}
}
const IfcAxis2Placement *IfcGeometricRepresentationContext::getWorldCoordinateSystem() const {
IfcGeometricRepresentationContext * deConstObject = const_cast< IfcGeometricRepresentationContext * > (this);
return deConstObject->getWorldCoordinateSystem();
}
void IfcGeometricRepresentationContext::setWorldCoordinateSystem(const Step::RefPtr< IfcAxis2Placement > &value) {
m_worldCoordinateSystem = value;
}
void IfcGeometricRepresentationContext::unsetWorldCoordinateSystem() {
m_worldCoordinateSystem = Step::getUnset(getWorldCoordinateSystem());
}
bool IfcGeometricRepresentationContext::testWorldCoordinateSystem() const {
return !Step::isUnset(getWorldCoordinateSystem());
}
IfcDirection *IfcGeometricRepresentationContext::getTrueNorth() {
if (Step::BaseObject::inited()) {
return m_trueNorth.get();
}
else {
return NULL;
}
}
const IfcDirection *IfcGeometricRepresentationContext::getTrueNorth() const {
IfcGeometricRepresentationContext * deConstObject = const_cast< IfcGeometricRepresentationContext * > (this);
return deConstObject->getTrueNorth();
}
void IfcGeometricRepresentationContext::setTrueNorth(const Step::RefPtr< IfcDirection > &value) {
m_trueNorth = value;
}
void IfcGeometricRepresentationContext::unsetTrueNorth() {
m_trueNorth = Step::getUnset(getTrueNorth());
}
bool IfcGeometricRepresentationContext::testTrueNorth() const {
return !Step::isUnset(getTrueNorth());
}
Inverse_Set_IfcGeometricRepresentationSubContext_0_n &IfcGeometricRepresentationContext::getHasSubContexts() {
if (Step::BaseObject::inited()) {
return m_hasSubContexts;
}
else {
m_hasSubContexts.setUnset(true);
return m_hasSubContexts;
}
}
const Inverse_Set_IfcGeometricRepresentationSubContext_0_n &IfcGeometricRepresentationContext::getHasSubContexts() const {
IfcGeometricRepresentationContext * deConstObject = const_cast< IfcGeometricRepresentationContext * > (this);
return deConstObject->getHasSubContexts();
}
bool IfcGeometricRepresentationContext::testHasSubContexts() const {
return !Step::isUnset(getHasSubContexts());
}
bool IfcGeometricRepresentationContext::init() {
bool status = IfcRepresentationContext::init();
std::string arg;
std::vector< Step::Id > *inverses;
if (!status) {
return false;
}
arg = m_args->getNext();
if (arg == "$" || arg == "*") {
m_coordinateSpaceDimension = Step::getUnset(m_coordinateSpaceDimension);
}
else {
m_coordinateSpaceDimension = Step::spfToInteger(arg);
}
arg = m_args->getNext();
if (arg == "$" || arg == "*") {
m_precision = Step::getUnset(m_precision);
}
else {
m_precision = Step::spfToReal(arg);
}
arg = m_args->getNext();
if (arg == "$" || arg == "*") {
m_worldCoordinateSystem = new IfcAxis2Placement;
}
else {
m_worldCoordinateSystem = new IfcAxis2Placement;
if (arg[0] == '#') {
m_worldCoordinateSystem->set(m_expressDataSet->get(atoi(arg.c_str() + 1)));
}
else if (arg[arg.length() - 1] == ')') {
std::string type1;
unsigned int i1;
i1 = arg.find('(');
if (i1 != std::string::npos) {
type1 = arg.substr(0, i1);
arg = arg.substr(i1 + 1, arg.length() - i1 - 2);
}
}
}
arg = m_args->getNext();
if (arg == "$" || arg == "*") {
m_trueNorth = NULL;
}
else {
m_trueNorth = static_cast< IfcDirection * > (m_expressDataSet->get(Step::getIdParam(arg)));
}
inverses = m_args->getInverses(IfcGeometricRepresentationSubContext::getClassType(), 6);
if (inverses) {
unsigned int i;
m_hasSubContexts.setUnset(false);
for (i = 0; i < inverses->size(); i++) {
m_hasSubContexts.insert(static_cast< IfcGeometricRepresentationSubContext * > (m_expressDataSet->get((*inverses)[i])));
}
}
return true;
}
void IfcGeometricRepresentationContext::copy(const IfcGeometricRepresentationContext &obj, const CopyOp ©op) {
IfcRepresentationContext::copy(obj, copyop);
setCoordinateSpaceDimension(obj.m_coordinateSpaceDimension);
setPrecision(obj.m_precision);
m_worldCoordinateSystem = new IfcAxis2Placement;
m_worldCoordinateSystem->copy(*(obj.m_worldCoordinateSystem.get()), copyop);
setTrueNorth((IfcDirection*)copyop(obj.m_trueNorth.get()));
return;
}
IFC2X3_DLL_DEF Step::ClassType IfcGeometricRepresentationContext::s_type("IfcGeometricRepresentationContext");
<|endoftext|> |
<commit_before>// Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon
// We are making my contributions/submissions to this project solely in our
// personal capacity and are not conveying any rights to any intellectual
// property of any third parties.
#include <Rosetta/Cards/Cards.hpp>
#include <Rosetta/Enchants/Effects.hpp>
#include <Rosetta/Enchants/Enchants.hpp>
#include <regex>
namespace RosettaStone
{
Enchant Enchants::GetEnchantFromText(const std::string& cardID)
{
std::vector<Effect> effects;
bool isOneTurn = false;
static std::regex attackHealthRegex("\\+([[:digit:]]+)/\\+([[:digit:]]+)");
static std::regex attackRegex("\\+([[:digit:]]+) Attack");
static std::regex healthRegex("\\+([[:digit:]]+) Health");
const std::string text = Cards::FindCardByID(cardID).text;
std::smatch values;
if (std::regex_search(text, values, attackHealthRegex))
{
effects.emplace_back(Effects::AttackN(std::stoi(values[1].str())));
effects.emplace_back(Effects::HealthN(std::stoi(values[2].str())));
}
else if (std::regex_search(text, values, attackRegex))
{
effects.emplace_back(Effects::AttackN(std::stoi(values[1].str())));
}
else if (std::regex_search(text, values, healthRegex))
{
effects.emplace_back(Effects::HealthN(std::stoi(values[1].str())));
}
if (text.find("this turn") != std::string::npos)
{
isOneTurn = true;
}
return Enchant(effects, isOneTurn);
}
} // namespace RosettaStone
<commit_msg>feat(card-impl): Add code to consider ability 'Taunt'<commit_after>// Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon
// We are making my contributions/submissions to this project solely in our
// personal capacity and are not conveying any rights to any intellectual
// property of any third parties.
#include <Rosetta/Cards/Cards.hpp>
#include <Rosetta/Enchants/Effects.hpp>
#include <Rosetta/Enchants/Enchants.hpp>
#include <regex>
namespace RosettaStone
{
Enchant Enchants::GetEnchantFromText(const std::string& cardID)
{
std::vector<Effect> effects;
bool isOneTurn = false;
static std::regex attackHealthRegex("\\+([[:digit:]]+)/\\+([[:digit:]]+)");
static std::regex attackRegex("\\+([[:digit:]]+) Attack");
static std::regex healthRegex("\\+([[:digit:]]+) Health");
const std::string text = Cards::FindCardByID(cardID).text;
std::smatch values;
if (std::regex_search(text, values, attackHealthRegex))
{
effects.emplace_back(Effects::AttackN(std::stoi(values[1].str())));
effects.emplace_back(Effects::HealthN(std::stoi(values[2].str())));
}
else if (std::regex_search(text, values, attackRegex))
{
effects.emplace_back(Effects::AttackN(std::stoi(values[1].str())));
}
else if (std::regex_search(text, values, healthRegex))
{
effects.emplace_back(Effects::HealthN(std::stoi(values[1].str())));
}
if (text.find("<b>Taunt</b>") != std::string::npos)
{
effects.emplace_back(Effects::Taunt);
}
if (text.find("this turn") != std::string::npos)
{
isOneTurn = true;
}
return Enchant(effects, isOneTurn);
}
} // namespace RosettaStone
<|endoftext|> |
<commit_before>/*=========================================================================
Library: CTK
Copyright (c) Kitware Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.commontk.org/LICENSE
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.
=========================================================================*/
// Qt includes
#include <QApplication>
#include <QTreeView>
#include <QSettings>
#include <QDir>
#include <QResource>
// CTK widget includes
#include <ctkDICOMAppWidget.h>
// ctkDICOMCore includes
#include "ctkDICOMDatabase.h"
#include "ctkDICOMModel.h"
// Logger
#include "ctkLogger.h"
// STD includes
#include <iostream>
int main(int argc, char** argv)
{
ctkLogger::configure();
QApplication app(argc, argv);
app.setOrganizationName("commontk");
app.setOrganizationDomain("commontk.org");
app.setApplicationName("ctkDICOM");
// set up Qt resource files
QResource::registerResource("./Resources/ctkDICOMViewer.qrc");
QSettings settings;
QString databaseDirectory;
// set up the database
if (argc > 1)
{
QString directory(argv[1]);
settings.setValue("DatabaseDirectory", directory);
settings.sync();
}
if ( settings.value("DatabaseDirectory", "") == "" )
{
databaseDirectory = QString("./ctkDICOM-Database");
std::cerr << "No DatabaseDirectory on command line or in settings. Using \"" << databaseDirectory.toLatin1().data() << "\".\n";
} else
{
databaseDirectory = settings.value("DatabaseDirectory", "").toString();
}
QDir qdir(databaseDirectory);
if ( !qdir.exists(databaseDirectory) )
{
if ( !qdir.mkpath(databaseDirectory) )
{
std::cerr << "Could not create database directory \"" << databaseDirectory.toLatin1().data() << "\".\n";
return EXIT_FAILURE;
}
}
ctkDICOMAppWidget DICOMApp;
DICOMApp.setDatabaseDirectory(databaseDirectory);
DICOMApp.show();
DICOMApp.raise();
return app.exec();
}
<commit_msg>Fix indent for consistency<commit_after>/*=========================================================================
Library: CTK
Copyright (c) Kitware Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.commontk.org/LICENSE
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.
=========================================================================*/
// Qt includes
#include <QApplication>
#include <QTreeView>
#include <QSettings>
#include <QDir>
#include <QResource>
// CTK widget includes
#include <ctkDICOMAppWidget.h>
// ctkDICOMCore includes
#include "ctkDICOMDatabase.h"
#include "ctkDICOMModel.h"
// Logger
#include "ctkLogger.h"
// STD includes
#include <iostream>
int main(int argc, char** argv)
{
ctkLogger::configure();
QApplication app(argc, argv);
app.setOrganizationName("commontk");
app.setOrganizationDomain("commontk.org");
app.setApplicationName("ctkDICOM");
// set up Qt resource files
QResource::registerResource("./Resources/ctkDICOMViewer.qrc");
QSettings settings;
QString databaseDirectory;
// set up the database
if (argc > 1)
{
QString directory(argv[1]);
settings.setValue("DatabaseDirectory", directory);
settings.sync();
}
if ( settings.value("DatabaseDirectory", "") == "" )
{
databaseDirectory = QString("./ctkDICOM-Database");
std::cerr << "No DatabaseDirectory on command line or in settings. Using \"" << databaseDirectory.toLatin1().data() << "\".\n";
} else
{
databaseDirectory = settings.value("DatabaseDirectory", "").toString();
}
QDir qdir(databaseDirectory);
if ( !qdir.exists(databaseDirectory) )
{
if ( !qdir.mkpath(databaseDirectory) )
{
std::cerr << "Could not create database directory \"" << databaseDirectory.toLatin1().data() << "\".\n";
return EXIT_FAILURE;
}
}
ctkDICOMAppWidget DICOMApp;
DICOMApp.setDatabaseDirectory(databaseDirectory);
DICOMApp.show();
DICOMApp.raise();
return app.exec();
}
<|endoftext|> |
<commit_before>// This may look like C code, but it is really -*- C++ -*-
//
// Copyright Bob Friesenhahn, 2003
//
// Test STL colorHistogram function
//
#undef USE_VECTOR
#define USE_MAP
#include <Magick++.h>
#include <string>
#include <iostream>
#include <iomanip>
#if defined(USE_VECTOR)
# include <vector>
# include <utility>
#endif
#if defined(USE_MAP)
# include <map>
#endif
using namespace std;
using namespace Magick;
int main( int /*argc*/, char ** argv)
{
// Initialize ImageMagick install location for Windows
InitializeMagick(*argv);
int failures=0;
try {
string srcdir("");
if(getenv("SRCDIR") != 0)
srcdir = getenv("SRCDIR");
// Read image
Image image;
image.read( srcdir + "test_image.miff" );
// Create histogram vector
#if defined(USE_MAP)
std::map<Color,size_t> histogram;
#elif defined(USE_VECTOR)
std::vector<std::pair<Color,size_t> > histogram;
#endif
colorHistogram( &histogram, image );
// Print out histogram
#if (MAGICKCORE_QUANTUM_DEPTH == 8)
int quantum_width=3;
#elif (MAGICKCORE_QUANTUM_DEPTH == 16)
int quantum_width=5;
#else
int quantum_width=10;
#endif
cout << "Histogram for file \"" << image.fileName() << "\"" << endl
<< histogram.size() << " entries:" << endl;
#if defined(USE_MAP)
std::map<Color,size_t>::const_iterator p=histogram.begin();
#elif defined(USE_VECTOR)
std::vector<std::pair<Color,size_t> >::const_iterator p=histogram.begin();
#endif
while (p != histogram.end())
{
cout << setw(10) << (int)p->second << ": ("
<< setw(quantum_width) << (int)p->first.redQuantum() << ","
<< setw(quantum_width) << (int)p->first.greenQuantum() << ","
<< setw(quantum_width) << (int)p->first.blueQuantum() << ")"
<< endl;
p++;
}
}
catch( Exception &error_ )
{
cout << "Caught exception: " << error_.what() << endl;
return 1;
}
catch( exception &error_ )
{
cout << "Caught exception: " << error_.what() << endl;
return 1;
}
if ( failures )
{
cout << failures << " failures" << endl;
return 1;
}
return 0;
}
<commit_msg>Fixed test.<commit_after>// This may look like C code, but it is really -*- C++ -*-
//
// Copyright Bob Friesenhahn, 2003
//
// Test STL colorHistogram function
//
#undef USE_VECTOR
#define USE_MAP
#include <Magick++.h>
#include <string>
#include <iostream>
#include <iomanip>
#if defined(USE_VECTOR)
# include <vector>
# include <utility>
#endif
#if defined(USE_MAP)
# include <map>
#endif
using namespace std;
using namespace Magick;
int main( int /*argc*/, char ** argv)
{
// Initialize ImageMagick install location for Windows
InitializeMagick(*argv);
int failures=0;
try {
string srcdir("");
if(getenv("SRCDIR") != 0)
srcdir = getenv("SRCDIR");
// Read image
Image image;
image.read( srcdir + "test_image.miff" );
// Create histogram vector
#if defined(USE_MAP)
std::map<Color,size_t> histogram;
#elif defined(USE_VECTOR)
std::vector<std::pair<Color,size_t> > histogram;
#endif
colorHistogram( &histogram, image );
// Print out histogram
#if (MAGICKCORE_QUANTUM_DEPTH == 8)
int quantum_width=3;
#elif (MAGICKCORE_QUANTUM_DEPTH == 16)
int quantum_width=5;
#else
int quantum_width=10;
#endif
cout << "Histogram for file \"" << image.fileName() << "\"" << endl
<< histogram.size() << " entries:" << endl;
#if defined(USE_MAP)
std::map<Color,size_t>::const_iterator p=histogram.begin();
#elif defined(USE_VECTOR)
std::vector<std::pair<Color,size_t> >::const_iterator p=histogram.begin();
#endif
while (p != histogram.end())
{
cout << setw(10) << (int)p->second << ": ("
<< setw(quantum_width) << (int)p->first.quantumRed() << ","
<< setw(quantum_width) << (int)p->first.quantumGreen() << ","
<< setw(quantum_width) << (int)p->first.quantumBlue() << ")"
<< endl;
p++;
}
}
catch( Exception &error_ )
{
cout << "Caught exception: " << error_.what() << endl;
return 1;
}
catch( exception &error_ )
{
cout << "Caught exception: " << error_.what() << endl;
return 1;
}
if ( failures )
{
cout << failures << " failures" << endl;
return 1;
}
return 0;
}
<|endoftext|> |
<commit_before>/** Display model class
*
* Glcd.cpp
* Created 10-01-17 By: Smitty
*
* A longer description.
*/
#include "Glcd.hpp"
/**
* @brief Glcd constructor
*/
Glcd::Glcd(void)
{
//display = new ST7565(MB_SID, MB_SCLK, MB_A0, MB_RST, MB_CS);
// U8G2_ST7565_LM6059_F_4W_SW_SPI u8g2(U8G2_R0, MB_SCLK, MB_SID, MB_CS, MB_A0, MB_RST);
display = new U8G2_ST7565_LM6059_F_4W_SW_SPI(U8G2_R0, MB_SCLK, MB_SID, MB_CS, MB_A0, MB_RST);
// initialize the glcd and set the contrast to 0x18
display->begin();
display->clearBuffer();
display->setContrast(130);
pinMode(MB_R, OUTPUT);
pinMode(MB_G, OUTPUT);
pinMode(MB_B, OUTPUT);
}
/**
* @brief Glcd destructor
*/
Glcd::~Glcd(void)
{
//delete display;
}
/**
* @brief
* @note
* @retval None
*/
void Glcd::update(void)
{
}
//displays the current mode selection on the GLCD in a graphical manner. There is a drop capital so that the mode is easily distinguishable
void Glcd::drawModeSelection(Stage stage)
{
display->setFont(u8g2_font_profont29_tr);
//display->clearBuffer(); //clear the screen
display->setDrawColor(0); //clear the previous mode
//how wide x tall should this box be?
display->drawBox(MODE_START_X, MODE_START_Y-48, 50, 52);
display->setDrawColor(1);
switch(stage){
case STAGE_STANDBY:
display->drawStr(MODE_START_X, MODE_START_Y, "S");
display->setFont(u8g2_font_profont12_tr);
display->drawStr(MODE_START_X+14, MODE_START_Y, "stdby");
break;
case STAGE_PRECHARGE:
display->drawStr(MODE_START_X, MODE_START_Y, "P");
display->setFont(u8g2_font_profont12_tr);
display->drawStr(MODE_START_X+14, MODE_START_Y, "re");
break;
case STAGE_ENERGIZED:
display->drawStr(MODE_START_X, MODE_START_Y, "E");
display->setFont(u8g2_font_profont12_tr);
display->drawStr(MODE_START_X+14, MODE_START_Y, "nergize");
break;
case STAGE_DRIVING:
display->drawStr(MODE_START_X, MODE_START_Y, "D");
display->setFont(u8g2_font_profont12_tr);
display->drawStr(MODE_START_X+14, MODE_START_Y, "rive");
break;
default: break;
}
dirtyBit = true;
}
void Glcd::flushGlcdBuffer(void)
{
display->sendBuffer();
dirtyBit = false;
}
void Glcd::clearGlcdBuffer(void)
{
display->clearBuffer();
dirtyBit = true;
}
bool Glcd::getDirtyBit(void)
{
return dirtyBit;
}
//took out LV batt bar
void Glcd::drawBattBars(uint8_t lvBattPercent, uint8_t hvBattPercent)
{
// int lvBarLength = ((BAR_LENGTH-2)*lvBattPercent) / 100;
int hvBarLength = ((BAR_LENGTH-2)*hvBattPercent) / 100;
display->setDrawColor(0); //now drawing blank pixels, clear old bar
display->drawRBox(BATT_BAR_START_X+1, HV_BAR_START_Y+3, BAR_LENGTH-2, HV_batt_height-4, 3);
// display->drawRBox(BATT_BAR_START_X+1, LV_BAR_START_Y+3, BAR_LENGTH-2, LV_Batt_height-4, 3);
display->setDrawColor(1); //draw black now
if(hvBarLength > 2){
display->drawRBox(BATT_BAR_START_X+1, HV_BAR_START_Y+3, hvBarLength, HV_batt_height-4, 3);
}
// else if(lvBarLength > 2) {
// display->drawRBox(BATT_BAR_START_X+1, LV_BAR_START_Y+3, hvBarLength, LV_Batt_height-4, 3);
// }
dirtyBit = true;
}
void Glcd::setupBattBars(){
display->drawXBM(2, HV_BAR_START_Y, HV_batt_width, HV_batt_width, HV_batt_bits);
//display->drawXBM(2, LV_BAR_START_Y, LV_Batt_width, LV_Batt_height, LV_Batt_bits);
display->drawRFrame(BATT_BAR_START_X, HV_BAR_START_Y+2, BAR_LENGTH, HV_batt_height-2, 3);
// display->drawRFrame(BATT_BAR_START_X, LV_BAR_START_Y+2, BAR_LENGTH, LV_Batt_height-2, 3);
dirtyBit = true;
}
void Glcd::setupTempScreen(void)
{
display->setFont(u8g2_font_profont12_tr);
display->drawXBM(TEMP_LIST_START_X, TEMP_LIST_START_Y, HV_batt_width, HV_batt_height, HV_batt_bits);
display->drawStr(TEMP_LIST_START_X+(TEMP_LIST_PADDING), TEMP_LIST_START_Y+(TEMP_LIST_TEXT_PADDING), "HV MAX: ");
display->drawStr(TEMP_LIST_START_X+(TEMP_LIST_PADDING), TEMP_LIST_START_Y+(TEMP_LIST_TEXT_PADDING*2), "MC: ");
display->drawStr(TEMP_LIST_START_X+(TEMP_LIST_PADDING), TEMP_LIST_START_Y+(TEMP_LIST_TEXT_PADDING*3), "Water: ");
display->drawStr(TEMP_LIST_START_X+(TEMP_LIST_PADDING), TEMP_LIST_START_Y+(TEMP_LIST_TEXT_PADDING*4), "Motor: ");
dirtyBit = true;
}
void Glcd::drawTemps(uint8_t HV_max, uint8_t Unitek_temp, uint8_t Motor_temp, uint8_t water_temp)
{
char buf[8];
sprintf(buf, "%d C", HV_max);
display->drawStr(TEMP_LIST_TEMP_X, TEMP_LIST_START_Y+(TEMP_LIST_TEXT_PADDING), buf);
sprintf(buf, "%d C", Unitek_temp);
display->drawStr(TEMP_LIST_TEMP_X, TEMP_LIST_START_Y+(TEMP_LIST_TEXT_PADDING*2), buf);
sprintf(buf, "%d C", Motor_temp);
display->drawStr(TEMP_LIST_TEMP_X, TEMP_LIST_START_Y+(TEMP_LIST_TEXT_PADDING*3), buf);
sprintf(buf, "%d C", water_temp);
display->drawStr(TEMP_LIST_TEMP_X, TEMP_LIST_START_Y+(TEMP_LIST_TEXT_PADDING*4), buf);
dirtyBit = true;
}
void Glcd::showShutdownLogo(void)
{
display->clearBuffer();
display->drawXBM(0, 0, Shutdown_width, Shutdown_height, Shutdown_bits);
display->setFont(u8g2_font_profont12_tr);
display->drawStr(35, 15, "Power Cycle Req.");
dirtyBit = true;
}
void Glcd::drawOkIcon(void)
{
display->drawXBM(OK_ICON_X, OK_ICON_Y, OK_icon_width, OK_icon_height, OK_icon_bits);
dirtyBit = true;
}
void Glcd::drawErrors(err_type err)
{
if(err == ERR_NONE) {return;}
display->drawXBM(ERR_START_X, ERR_START_Y, o_fok_width, o_fok_height, o_fok_bits);
switch(err)
{
case ERR_ORION:
display->drawXBM(ERR_START_X+(ERR_PADDING), ERR_START_Y, HV_batt_width, HV_batt_height, HV_batt_bits);
display->drawXBM(ERR_START_X+(ERR_PADDING*2), ERR_START_Y, BMS_ERR_width, BMS_ERR_height, BMS_ERR_bits);
break;
case ERR_IMD:
display->drawXBM(ERR_START_X+(ERR_PADDING*3), ERR_START_Y, IMD_ERR_width, IMD_ERR_height, IMD_ERR_bits);
break;
case ERR_TMP:
display->drawXBM(ERR_START_X+(ERR_PADDING*4), ERR_START_Y, water_temp_width, water_temp_height, water_temp_bits);
case ERR_UNITEK:
display->drawXBM(ERR_START_X+(ERR_PADDING*5), ERR_START_Y, MC_ERR_width, MC_ERR_height, MC_ERR_bits);
break;
case ERR_ALL:
display->drawXBM(ERR_START_X+(ERR_PADDING), ERR_START_Y, HV_batt_width, HV_batt_height, HV_batt_bits);
display->drawXBM(ERR_START_X+(ERR_PADDING*2), ERR_START_Y, BMS_ERR_width, BMS_ERR_height, BMS_ERR_bits);
display->drawXBM(ERR_START_X+(ERR_PADDING*3), ERR_START_Y, IMD_ERR_width, IMD_ERR_height, IMD_ERR_bits);
display->drawXBM(ERR_START_X+(ERR_PADDING*4), ERR_START_Y, water_temp_width, water_temp_height, water_temp_bits);
display->drawXBM(ERR_START_X+(ERR_PADDING*5), ERR_START_Y, MC_ERR_width, MC_ERR_height, MC_ERR_bits);
break;
default: break;
}
dirtyBit = true;
}
void Glcd::clearAllErrors(void)
{
display->setDrawColor(0);
display->drawBox(ERR_START_X, ERR_START_Y, ERR_START_Y+(ERR_PADDING*6), 18);
dirtyBit = true;
display->setDrawColor(1);
}
void Glcd::setBacklightRgb(int r, int g, int b)
{
analogWrite(MB_R, r);
analogWrite(MB_G, g);
analogWrite(MB_B, b);
}
/**
* @brief displays image of "Just Barely" on the screen
* @note
* @retval None
*/
void Glcd::showBootLogo(void)
{
// draw the bitmap
// display->clear();
// display->drawbitmap(0, 0, JustBarelyLogo, 128, 64, BLACK);
// display->display();
display->clearBuffer();
display->drawXBM(0, 0, Just_Barely_width, Just_Barely_height, Just_Barely_bits);
// display->setFont(u8g2_font_ncenB14_tr);
// display->drawStr(0,20,"SPLASH SCREEN");
display->sendBuffer(); //this is ok since we're in start
}<commit_msg>Should fix issue #169<commit_after>/** Display model class
*
* Glcd.cpp
* Created 10-01-17 By: Smitty
*
* A longer description.
*/
#include "Glcd.hpp"
/**
* @brief Glcd constructor
*/
Glcd::Glcd(void)
{
//display = new ST7565(MB_SID, MB_SCLK, MB_A0, MB_RST, MB_CS);
// U8G2_ST7565_LM6059_F_4W_SW_SPI u8g2(U8G2_R0, MB_SCLK, MB_SID, MB_CS, MB_A0, MB_RST);
display = new U8G2_ST7565_LM6059_F_4W_SW_SPI(U8G2_R0, MB_SCLK, MB_SID, MB_CS, MB_A0, MB_RST);
// initialize the glcd and set the contrast to 0x18
display->begin();
display->clearBuffer();
display->setContrast(130);
pinMode(MB_R, OUTPUT);
pinMode(MB_G, OUTPUT);
pinMode(MB_B, OUTPUT);
}
/**
* @brief Glcd destructor
*/
Glcd::~Glcd(void)
{
//delete display;
}
/**
* @brief
* @note
* @retval None
*/
void Glcd::update(void)
{
}
//displays the current mode selection on the GLCD in a graphical manner. There is a drop capital so that the mode is easily distinguishable
void Glcd::drawModeSelection(Stage stage)
{
display->setFont(u8g2_font_profont29_tr);
//display->clearBuffer(); //clear the screen
display->setDrawColor(0); //clear the previous mode
//how wide x tall should this box be?
display->drawBox(MODE_START_X, MODE_START_Y-48, 50, 52);
display->setDrawColor(1);
switch(stage){
case STAGE_STANDBY:
display->drawStr(MODE_START_X, MODE_START_Y, "S");
display->setFont(u8g2_font_profont12_tr);
display->drawStr(MODE_START_X+14, MODE_START_Y, "stdby");
break;
case STAGE_PRECHARGE:
display->drawStr(MODE_START_X, MODE_START_Y, "P");
display->setFont(u8g2_font_profont12_tr);
display->drawStr(MODE_START_X+14, MODE_START_Y, "re");
break;
case STAGE_ENERGIZED:
display->drawStr(MODE_START_X, MODE_START_Y, "E");
display->setFont(u8g2_font_profont12_tr);
display->drawStr(MODE_START_X+14, MODE_START_Y, "nergize");
break;
case STAGE_DRIVING:
display->drawStr(MODE_START_X, MODE_START_Y, "D");
display->setFont(u8g2_font_profont12_tr);
display->drawStr(MODE_START_X+14, MODE_START_Y, "rive");
break;
default: break;
}
dirtyBit = true;
}
void Glcd::flushGlcdBuffer(void)
{
display->sendBuffer();
dirtyBit = false;
}
void Glcd::clearGlcdBuffer(void)
{
display->clearBuffer();
dirtyBit = true;
}
bool Glcd::getDirtyBit(void)
{
return dirtyBit;
}
//took out LV batt bar
void Glcd::drawBattBars(uint8_t lvBattPercent, uint8_t hvBattPercent)
{
//clamp % to 0-100 range.
if(lvBattPercent < 0) {lvBattPercent = 0; }
if(hvBattPercent < 0) {hvBattPercent = 0; }
if(hvBattPercent > 100) {hvBattPercent = 100; }
if(lvBattPercent > 100) {lvBattPercent = 100; }
// int lvBarLength = ((BAR_LENGTH-2)*lvBattPercent) / 100;
int hvBarLength = ((BAR_LENGTH-2)*hvBattPercent) / 100;
display->setDrawColor(0); //now drawing blank pixels, clear old bar
display->drawRBox(BATT_BAR_START_X+1, HV_BAR_START_Y+3, BAR_LENGTH-2, HV_batt_height-4, 3);
// display->drawRBox(BATT_BAR_START_X+1, LV_BAR_START_Y+3, BAR_LENGTH-2, LV_Batt_height-4, 3);
display->setDrawColor(1); //draw black now
if(hvBarLength > 2){
display->drawRBox(BATT_BAR_START_X+1, HV_BAR_START_Y+3, hvBarLength, HV_batt_height-4, 3);
}
// else if(lvBarLength > 2) {
// display->drawRBox(BATT_BAR_START_X+1, LV_BAR_START_Y+3, hvBarLength, LV_Batt_height-4, 3);
// }
dirtyBit = true;
}
void Glcd::setupBattBars(){
display->drawXBM(2, HV_BAR_START_Y, HV_batt_width, HV_batt_width, HV_batt_bits);
//display->drawXBM(2, LV_BAR_START_Y, LV_Batt_width, LV_Batt_height, LV_Batt_bits);
display->drawRFrame(BATT_BAR_START_X, HV_BAR_START_Y+2, BAR_LENGTH, HV_batt_height-2, 3);
// display->drawRFrame(BATT_BAR_START_X, LV_BAR_START_Y+2, BAR_LENGTH, LV_Batt_height-2, 3);
dirtyBit = true;
}
void Glcd::setupTempScreen(void)
{
display->setFont(u8g2_font_profont12_tr);
display->drawXBM(TEMP_LIST_START_X, TEMP_LIST_START_Y, HV_batt_width, HV_batt_height, HV_batt_bits);
display->drawStr(TEMP_LIST_START_X+(TEMP_LIST_PADDING), TEMP_LIST_START_Y+(TEMP_LIST_TEXT_PADDING), "HV MAX: ");
display->drawStr(TEMP_LIST_START_X+(TEMP_LIST_PADDING), TEMP_LIST_START_Y+(TEMP_LIST_TEXT_PADDING*2), "MC: ");
display->drawStr(TEMP_LIST_START_X+(TEMP_LIST_PADDING), TEMP_LIST_START_Y+(TEMP_LIST_TEXT_PADDING*3), "Water: ");
display->drawStr(TEMP_LIST_START_X+(TEMP_LIST_PADDING), TEMP_LIST_START_Y+(TEMP_LIST_TEXT_PADDING*4), "Motor: ");
dirtyBit = true;
}
void Glcd::drawTemps(uint8_t HV_max, uint8_t Unitek_temp, uint8_t Motor_temp, uint8_t water_temp)
{
char buf[8];
sprintf(buf, "%d C", HV_max);
display->drawStr(TEMP_LIST_TEMP_X, TEMP_LIST_START_Y+(TEMP_LIST_TEXT_PADDING), buf);
sprintf(buf, "%d C", Unitek_temp);
display->drawStr(TEMP_LIST_TEMP_X, TEMP_LIST_START_Y+(TEMP_LIST_TEXT_PADDING*2), buf);
sprintf(buf, "%d C", Motor_temp);
display->drawStr(TEMP_LIST_TEMP_X, TEMP_LIST_START_Y+(TEMP_LIST_TEXT_PADDING*3), buf);
sprintf(buf, "%d C", water_temp);
display->drawStr(TEMP_LIST_TEMP_X, TEMP_LIST_START_Y+(TEMP_LIST_TEXT_PADDING*4), buf);
dirtyBit = true;
}
void Glcd::showShutdownLogo(void)
{
display->clearBuffer();
display->drawXBM(0, 0, Shutdown_width, Shutdown_height, Shutdown_bits);
display->setFont(u8g2_font_profont12_tr);
display->drawStr(35, 15, "Power Cycle Req.");
dirtyBit = true;
}
void Glcd::drawOkIcon(void)
{
display->drawXBM(OK_ICON_X, OK_ICON_Y, OK_icon_width, OK_icon_height, OK_icon_bits);
dirtyBit = true;
}
void Glcd::drawErrors(err_type err)
{
if(err == ERR_NONE) {return;}
display->drawXBM(ERR_START_X, ERR_START_Y, o_fok_width, o_fok_height, o_fok_bits);
switch(err)
{
case ERR_ORION:
display->drawXBM(ERR_START_X+(ERR_PADDING), ERR_START_Y, HV_batt_width, HV_batt_height, HV_batt_bits);
display->drawXBM(ERR_START_X+(ERR_PADDING*2), ERR_START_Y, BMS_ERR_width, BMS_ERR_height, BMS_ERR_bits);
break;
case ERR_IMD:
display->drawXBM(ERR_START_X+(ERR_PADDING*3), ERR_START_Y, IMD_ERR_width, IMD_ERR_height, IMD_ERR_bits);
break;
case ERR_TMP:
display->drawXBM(ERR_START_X+(ERR_PADDING*4), ERR_START_Y, water_temp_width, water_temp_height, water_temp_bits);
case ERR_UNITEK:
display->drawXBM(ERR_START_X+(ERR_PADDING*5), ERR_START_Y, MC_ERR_width, MC_ERR_height, MC_ERR_bits);
break;
case ERR_ALL:
display->drawXBM(ERR_START_X+(ERR_PADDING), ERR_START_Y, HV_batt_width, HV_batt_height, HV_batt_bits);
display->drawXBM(ERR_START_X+(ERR_PADDING*2), ERR_START_Y, BMS_ERR_width, BMS_ERR_height, BMS_ERR_bits);
display->drawXBM(ERR_START_X+(ERR_PADDING*3), ERR_START_Y, IMD_ERR_width, IMD_ERR_height, IMD_ERR_bits);
display->drawXBM(ERR_START_X+(ERR_PADDING*4), ERR_START_Y, water_temp_width, water_temp_height, water_temp_bits);
display->drawXBM(ERR_START_X+(ERR_PADDING*5), ERR_START_Y, MC_ERR_width, MC_ERR_height, MC_ERR_bits);
break;
default: break;
}
dirtyBit = true;
}
void Glcd::clearAllErrors(void)
{
display->setDrawColor(0);
display->drawBox(ERR_START_X, ERR_START_Y, ERR_START_Y+(ERR_PADDING*6), 18);
dirtyBit = true;
display->setDrawColor(1);
}
void Glcd::setBacklightRgb(int r, int g, int b)
{
analogWrite(MB_R, r);
analogWrite(MB_G, g);
analogWrite(MB_B, b);
}
/**
* @brief displays image of "Just Barely" on the screen
* @note
* @retval None
*/
void Glcd::showBootLogo(void)
{
// draw the bitmap
// display->clear();
// display->drawbitmap(0, 0, JustBarelyLogo, 128, 64, BLACK);
// display->display();
display->clearBuffer();
display->drawXBM(0, 0, Just_Barely_width, Just_Barely_height, Just_Barely_bits);
// display->setFont(u8g2_font_ncenB14_tr);
// display->drawStr(0,20,"SPLASH SCREEN");
display->sendBuffer(); //this is ok since we're in start
}<|endoftext|> |
<commit_before>/*******************************************************************************
*
* Filename : HiggsCombineSubmitter.cc
* Description : Helper class for submitting higgs combine data cards
* Author : Yi-Mu "Enoch" Chen [ ensc@hep1.phys.ntu.edu.tw ]
*
*******************************************************************************/
#include "ManagerUtils/SysUtils/interface/HiggsCombineSubmitter.hpp"
#include "ManagerUtils/SysUtils/interface/ProcessUtils.hpp"
#include "ManagerUtils/SysUtils/interface/FilenameMgr.hpp"
#include "ManagerUtils/BaseClass/interface/ConfigReader.hpp"
#include <boost/filesystem.hpp>
#include <cstdlib>
#include <iostream>
#include <thread>
using namespace std;
using namespace mgr;
//------------------------------------------------------------------------------
// Constructor and Destructor
//------------------------------------------------------------------------------
HiggsCombineSubmitter::HiggsCombineSubmitter( const string& config_file )
{
const ConfigReader config( config_file );
_scram_arch = config.GetStaticString("Scram Arch");
_store_path = config.GetStaticString("Store Path");
_cmssw_version = config.GetStaticString("CMSSW Version");
_higg_combine_version = config.GetStaticString("Higgs Combine Version");
if( !check_higgs_dir() ){ // throwing error message for now
throw std::invalid_argument("Higgs Combine package doesn't exists!");
// init_higgs_dir();
}
}
HiggsCombineSubmitter::~HiggsCombineSubmitter()
{
}
//------------------------------------------------------------------------------
// Main control flows
//------------------------------------------------------------------------------
static const string higgs_subdir = "HiggsAnalysis/CombinedLimit";
int HiggsCombineSubmitter::SubmitDataCard( const CombineRequest& x ) const
{
const string script_file = temp_script_name(x.mass_point,x.combine_method);
MakeScripts(x);
cout << "Running script " << script_file << endl;
const int result = system( script_file.c_str() );
system( ("rm "+script_file).c_str() );
return result;
}
string HiggsCombineSubmitter::MakeScripts( const CombineRequest& x ) const
{
const string script_name = temp_script_name(x.mass_point,x.combine_method);
FILE* script_file = fopen( script_name.c_str() , "w" );
fprintf( script_file , "#!/bin/bash\n" );
fprintf( script_file , "cd %s\n" , higgs_cmssw_dir().c_str() );
fprintf( script_file , "eval `scramv1 runtime -sh` &> /dev/null\n" );
fprintf(
script_file , "combine -M %s -m %d %s %s",
x.combine_method.c_str(),
x.mass_point,
x.card_file.c_str(),
x.additional_options.c_str()
);
if( x.log_file != "stdout" ){
fprintf( script_file , " &> %s" , x.log_file.c_str() );
}
fprintf( script_file ,"\n");
fprintf( script_file , "result=$?\n" );
fprintf(
script_file , "mv %s/higgsCombineTest.%s.mH%d.root %s\n",
higgs_cmssw_dir().c_str(),
x.combine_method.c_str(),
x.mass_point,
x.output_file.c_str()
);
fprintf( script_file, "exit $result\n");
fclose( script_file );
system( ("chmod +x "+script_name).c_str() );
return script_name;
}
vector<int> HiggsCombineSubmitter::SubmitParallel( const vector<CombineRequest>& list ) const
{
vector<int> ans(0,list.size());
vector<thread> thread_list;
for( const auto& req : list ){ // Naively generating new thread for all processes
cout << "Creating thread for" << req.card_file << "..." << endl;
thread_list.push_back( thread( &HiggsCombineSubmitter::SubmitDataCard ,this, req ));
}
for( auto& thd : thread_list ){ thd.join(); }
return ans; // Indiviual run results are not availiable.. yet
}
//------------------------------------------------------------------------------
// Helper private functions
//------------------------------------------------------------------------------
static const string git_repo = "https://github.com/cms-analysis/HiggsAnalysis-CombinedLimit.git";
static const string install_script = "./._higgs_install_script.sh" ;
bool HiggsCombineSubmitter::check_higgs_dir() const
{
using namespace boost::filesystem;
if( !exists(_store_path + "/" + _cmssw_version + "/src/" + higgs_subdir ) ){ return false; }
// TODO: Make sure to correct version tag.. 2016-07-04
return true;
}
void HiggsCombineSubmitter::init_higgs_dir() const
{// Script for automatically installing Higgs Combine package...
}
string HiggsCombineSubmitter::higgs_cmssw_dir() const
{
return _store_path + "/" + _cmssw_version + "/src/" ;
}
string HiggsCombineSubmitter::temp_script_name(const int mass_point, const string& combine_method) const
{
char ans[1024];
sprintf(
ans , "%s/.temp_script_m%d_M%s.sh",
getenv("PWD"),
mass_point,
combine_method.c_str()
);
return ans;
}
//------------------------------------------------------------------------------
// CombineRequest class
//------------------------------------------------------------------------------
CombineRequest::CombineRequest(
const std::string& _card_file,
const std::string& _output_file,
const int _mass_point,
const std::string& _combine_method,
const std::string& _additional_options,
const std::string& _log_file
):
card_file(FilenameMgr::ConvertToAbsPath(_card_file)),
output_file(FilenameMgr::ConvertToAbsPath(_output_file)),
mass_point(_mass_point),
combine_method(_combine_method),
additional_options(_additional_options)
{
if( _log_file != "stdout" ){
log_file = FilenameMgr::ConvertToAbsPath(_log_file);
} else {
log_file = _log_file;
}
}
CombineRequest::~CombineRequest()
{
}
<commit_msg>Update to higgs combine submitter<commit_after>/*******************************************************************************
*
* Filename : HiggsCombineSubmitter.cc
* Description : Helper class for submitting higgs combine data cards
* Author : Yi-Mu "Enoch" Chen [ ensc@hep1.phys.ntu.edu.tw ]
*
*******************************************************************************/
#include "ManagerUtils/SysUtils/interface/HiggsCombineSubmitter.hpp"
#include "ManagerUtils/SysUtils/interface/ProcessUtils.hpp"
#include "ManagerUtils/SysUtils/interface/FilenameMgr.hpp"
#include "ManagerUtils/BaseClass/interface/ConfigReader.hpp"
#include <boost/filesystem.hpp>
#include <cstdlib>
#include <iostream>
#include <thread>
using namespace std;
using namespace mgr;
//------------------------------------------------------------------------------
// Constructor and Destructor
//------------------------------------------------------------------------------
HiggsCombineSubmitter::HiggsCombineSubmitter( const string& config_file )
{
const ConfigReader config( config_file );
_scram_arch = config.GetStaticString("Scram Arch");
_store_path = config.GetStaticString("Store Path");
_cmssw_version = config.GetStaticString("CMSSW Version");
_higg_combine_version = config.GetStaticString("Higgs Combine Version");
if( !check_higgs_dir() ){ // throwing error message for now
throw std::invalid_argument("Higgs Combine package doesn't exists!");
// init_higgs_dir();
}
}
HiggsCombineSubmitter::~HiggsCombineSubmitter()
{
}
//------------------------------------------------------------------------------
// Main control flows
//------------------------------------------------------------------------------
static const string higgs_subdir = "HiggsAnalysis/CombinedLimit";
int HiggsCombineSubmitter::SubmitDataCard( const CombineRequest& x ) const
{
const string script_file = temp_script_name(x.mass_point,x.combine_method);
MakeScripts(x);
cout << "Running script " << script_file << endl;
const int result = system( script_file.c_str() );
system( ("rm "+script_file).c_str() );
return result;
}
string HiggsCombineSubmitter::MakeScripts( const CombineRequest& x ) const
{
const string script_name = temp_script_name(x.mass_point,x.combine_method);
FILE* script_file = fopen( script_name.c_str() , "w" );
fprintf( script_file , "#!/bin/bash\n" );
fprintf( script_file , "cd %s\n" , higgs_cmssw_dir().c_str() );
fprintf( script_file , "eval `scramv1 runtime -sh` &> /dev/null\n" );
fprintf(
script_file , "combine -M %s -m %d %s %s",
x.combine_method.c_str(),
x.mass_point,
x.card_file.c_str(),
x.additional_options.c_str()
);
if( x.log_file != "stdout" ){
fprintf( script_file , " &> %s" , x.log_file.c_str() );
}
fprintf( script_file ,"\n");
fprintf( script_file , "result=$?\n" );
fprintf(
script_file , "mv %s/higgsCombineTest.%s.mH%d.root %s\n",
higgs_cmssw_dir().c_str(),
x.combine_method.c_str(),
x.mass_point,
x.output_file.c_str()
);
fprintf( script_file, "exit $result\n");
fclose( script_file );
system( "sleep 1" );
system( ("chmod +x "+script_name).c_str() );
return script_name;
}
vector<int> HiggsCombineSubmitter::SubmitParallel( const vector<CombineRequest>& list ) const
{
vector<int> ans(0,list.size());
vector<thread> thread_list;
for( const auto& req : list ){ // Naively generating new thread for all processes
cout << "Creating thread for" << req.card_file << "..." << endl;
thread_list.push_back( thread( &HiggsCombineSubmitter::SubmitDataCard, this, req ));
}
for( auto& thd : thread_list ){ thd.join(); }
return ans; // Indiviual run results are not availiable.. yet
}
//------------------------------------------------------------------------------
// Helper private functions
//------------------------------------------------------------------------------
static const string git_repo = "https://github.com/cms-analysis/HiggsAnalysis-CombinedLimit.git";
static const string install_script = "./._higgs_install_script.sh" ;
bool HiggsCombineSubmitter::check_higgs_dir() const
{
using namespace boost::filesystem;
if( !exists(_store_path + "/" + _cmssw_version + "/src/" + higgs_subdir ) ){ return false; }
// TODO: Make sure to correct version tag.. 2016-07-04
return true;
}
void HiggsCombineSubmitter::init_higgs_dir() const
{// Script for automatically installing Higgs Combine package...
}
string HiggsCombineSubmitter::higgs_cmssw_dir() const
{
return _store_path + "/" + _cmssw_version + "/src/" ;
}
string HiggsCombineSubmitter::temp_script_name(const int mass_point, const string& combine_method) const
{
char ans[1024];
sprintf(
ans , "%s/.temp_script_m%d_M%s.sh",
getenv("PWD"),
mass_point,
combine_method.c_str()
);
return ans;
}
//------------------------------------------------------------------------------
// CombineRequest class
//------------------------------------------------------------------------------
CombineRequest::CombineRequest(
const std::string& _card_file,
const std::string& _output_file,
const int _mass_point,
const std::string& _combine_method,
const std::string& _additional_options,
const std::string& _log_file
):
card_file(FilenameMgr::ConvertToAbsPath(_card_file)),
output_file(FilenameMgr::ConvertToAbsPath(_output_file)),
mass_point(_mass_point),
combine_method(_combine_method),
additional_options(_additional_options)
{
if( _log_file != "stdout" ){
log_file = FilenameMgr::ConvertToAbsPath(_log_file);
} else {
log_file = _log_file;
}
}
CombineRequest::~CombineRequest()
{
}
<|endoftext|> |
<commit_before>#ifndef AIKIDO_CONSTRAINT_IKSAMPLEABLE_H
#define AIKIDO_CONSTRAINT_IKSAMPLEABLE_H
#include "Sampleable.hpp"
#include <dart/dynamics/dynamics.h>
namespace aikido {
namespace constraint {
// Transforms Isometry3d region to IK region
class IKSampleableConstraint : public SampleableConstraint<Eigen::VectorXd>
{
public:
using SampleablePoseConstraint =
std::shared_ptr<SampleableConstraint<Eigen::Isometry3d>>;
IKSampleableConstraint(
const SampleablePoseConstraint&
_isometry3dConstraint,
const dart::dynamics::InverseKinematicsPtr& _ikPtr,
std::unique_ptr<util::RNG> _rng,
int _maxNumTrials);
IKSampleableConstraint(const IKSampleableConstraint& other);
IKSampleableConstraint(IKSampleableConstraint&& other);
IKSampleableConstraint& operator=(
const IKSampleableConstraint& other);
IKSampleableConstraint& operator=(IKSampleableConstraint&& other);
virtual ~IKSampleableConstraint() = default;
/// Returns VectorXd sample generator.
std::unique_ptr<SampleGenerator<Eigen::VectorXd>>
createSampleGenerator() const override;
/// Set rng seed.
void setRNG(std::unique_ptr<util::RNG> rng);
private:
std::unique_ptr<util::RNG> mRng;
SampleablePoseConstraint mIsometry3dConstraintPtr;
dart::dynamics::InverseKinematicsPtr mIKPtr;
int mMaxNumTrials;
};
class IKSampleGenerator : public SampleGenerator<Eigen::VectorXd>
{
friend class IKSampleableConstraint;
public:
IKSampleGenerator(const IKSampleGenerator&) = delete;
IKSampleGenerator(IKSampleGenerator&& other) = delete;
IKSampleGenerator& operator=(const IKSampleGenerator& other) = delete;
IKSampleGenerator& operator=(IKSampleGenerator&& other) = delete;
virtual ~IKSampleGenerator() = default;
boost::optional<Eigen::VectorXd> sample() override;
bool canSample() const override;
int getNumSamples() const override;
private:
IKSampleGenerator(
std::unique_ptr<SampleGenerator<Eigen::Isometry3d>> _isometrySampler,
const dart::dynamics::InverseKinematicsPtr& _ikPtr,
std::unique_ptr<util::RNG> _rng,
int _maxNumTrials);
dart::dynamics::InverseKinematicsPtr mIKPtr;
std::unique_ptr<SampleGenerator<Eigen::Isometry3d>> mIsometrySampler;
int mMaxNumTrials;
std::unique_ptr<util::RNG> mRng;
};
using IKSampleGeneratorPtr = std::shared_ptr<const IKSampleGenerator>;
using IKSampleGeneratorUniquePtr = std::unique_ptr<IKSampleGenerator>;
using IKSampleableConstraintPtr = std::shared_ptr<const IKSampleableConstraint>;
using IKSampleableConstraintUniquePtr = std::unique_ptr<IKSampleableConstraint>;
} // namespace constraint
} // namespace aikido
#endif // AIKIDO_Constraint_IKSAMPLEABLE_H
<commit_msg>[aikido] Added comments to IkSampleable.<commit_after>#ifndef AIKIDO_CONSTRAINT_IKSAMPLEABLE_H
#define AIKIDO_CONSTRAINT_IKSAMPLEABLE_H
#include "Sampleable.hpp"
#include <dart/dynamics/dynamics.h>
namespace aikido {
namespace constraint {
/// Transforms a Isometry3d SampleableConstraint into a VectorXd
/// SampleableConstraint that represents the positions of a Skeleton by
/// sampling an Isometry3d and using inverse kinematics to "lift" that pose
/// into the Skeleton's configuration space. This class will retry a
/// configurable number of times if sampling from the Isometry3d constaint or
/// finding an inverse kinematic solution fails.
class IKSampleableConstraint : public SampleableConstraint<Eigen::VectorXd>
{
public:
using SampleablePoseConstraint =
std::shared_ptr<SampleableConstraint<Eigen::Isometry3d>>;
/// Constructor.
///
/// \param[in] _isometry3dConstraint pose constraint to lift
/// \param[in] _ikPtr inverse kinematics solver to use for lifting
/// \param[in] _rng random number generator used by sample generators
/// \param[in] _maxNumTrials number of retry attempts
IKSampleableConstraint(
const SampleablePoseConstraint& _isometry3dConstraint,
const dart::dynamics::InverseKinematicsPtr& _ikPtr,
std::unique_ptr<util::RNG> _rng,
int _maxNumTrials);
IKSampleableConstraint(const IKSampleableConstraint& other);
IKSampleableConstraint(IKSampleableConstraint&& other);
IKSampleableConstraint& operator=(
const IKSampleableConstraint& other);
IKSampleableConstraint& operator=(IKSampleableConstraint&& other);
virtual ~IKSampleableConstraint() = default;
// Documentation inherited.
std::unique_ptr<SampleGenerator<Eigen::VectorXd>>
createSampleGenerator() const override;
/// Set rng seed.
void setRNG(std::unique_ptr<util::RNG> rng);
private:
std::unique_ptr<util::RNG> mRng;
SampleablePoseConstraint mIsometry3dConstraintPtr;
dart::dynamics::InverseKinematicsPtr mIKPtr;
int mMaxNumTrials;
};
// For internal use only.
class IKSampleGenerator : public SampleGenerator<Eigen::VectorXd>
{
public:
IKSampleGenerator(const IKSampleGenerator&) = delete;
IKSampleGenerator(IKSampleGenerator&& other) = delete;
IKSampleGenerator& operator=(const IKSampleGenerator& other) = delete;
IKSampleGenerator& operator=(IKSampleGenerator&& other) = delete;
virtual ~IKSampleGenerator() = default;
// Documentation inherited.
boost::optional<Eigen::VectorXd> sample() override;
// Documentation inherited.
bool canSample() const override;
// Documentation inherited.
int getNumSamples() const override;
private:
// For internal use only.
IKSampleGenerator(
std::unique_ptr<SampleGenerator<Eigen::Isometry3d>> _isometrySampler,
const dart::dynamics::InverseKinematicsPtr& _ikPtr,
std::unique_ptr<util::RNG> _rng,
int _maxNumTrials);
dart::dynamics::InverseKinematicsPtr mIKPtr;
std::unique_ptr<SampleGenerator<Eigen::Isometry3d>> mIsometrySampler;
int mMaxNumTrials;
std::unique_ptr<util::RNG> mRng;
friend class IKSampleableConstraint;
};
using IKSampleGeneratorPtr = std::shared_ptr<const IKSampleGenerator>;
using IKSampleGeneratorUniquePtr = std::unique_ptr<IKSampleGenerator>;
using IKSampleableConstraintPtr = std::shared_ptr<const IKSampleableConstraint>;
using IKSampleableConstraintUniquePtr = std::unique_ptr<IKSampleableConstraint>;
} // namespace constraint
} // namespace aikido
#endif // AIKIDO_Constraint_IKSAMPLEABLE_H
<|endoftext|> |
<commit_before>#pragma once
#include <agency/cuda/execution/executor/grid_executor.hpp>
#include <agency/detail/tuple.hpp>
#include <agency/detail/invoke.hpp>
#include <agency/detail/type_traits.hpp>
namespace agency
{
namespace cuda
{
namespace detail
{
template<class Function>
struct block_executor_helper_functor
{
mutable Function f_;
// this is the form of operator() for then_execute() with a non-void future and a shared parameter
template<class Arg1, class Arg2>
__device__
auto operator()(grid_executor::index_type idx, Arg1& past_arg, agency::detail::unit, Arg2& inner_shared_param) const ->
decltype(agency::detail::invoke(f_, agency::detail::get<1>(idx), past_arg, inner_shared_param))
{
return agency::detail::invoke(f_, agency::detail::get<1>(idx), past_arg, inner_shared_param);
}
// this is the form of operator() for then_execute() with a void future and a shared parameter
template<class Arg>
__device__
auto operator()(grid_executor::index_type idx, agency::detail::unit, Arg& inner_shared_param) const ->
decltype(agency::detail::invoke(f_, agency::detail::get<1>(idx), inner_shared_param))
{
return agency::detail::invoke(f_, agency::detail::get<1>(idx), inner_shared_param);
}
};
// this container exposes a public interface that makes it look
// like a container that a grid_executor can produce values into (i.e., it is two-dimensional)
// internally, it discards the first dimension of the shape & index and forwards the second
// dimension of each to the actual Container
template<class Container>
class block_executor_helper_container : public Container
{
private:
using super_t = Container;
public:
__host__ __device__
block_executor_helper_container()
: super_t()
{}
__host__ __device__
block_executor_helper_container(Container&& super)
: super_t(std::move(super))
{}
__host__ __device__
auto operator[](grid_executor::index_type idx) ->
decltype(this->operator[](agency::detail::get<1>(idx)))
{
return super_t::operator[](agency::detail::get<1>(idx));
}
};
template<class Factory>
struct block_executor_helper_container_factory
{
Factory factory_;
using factory_arg_type = typename std::tuple_element<1,grid_executor::shape_type>::type;
using block_executor_container_type = agency::detail::result_of_t<Factory(factory_arg_type)>;
__host__ __device__
block_executor_helper_container<block_executor_container_type> operator()(grid_executor::shape_type shape)
{
return block_executor_helper_container<block_executor_container_type>(factory_(agency::detail::get<1>(shape)));
}
};
// XXX eliminate the stuff above this once we scrub use of old executor_traits
template<class Function>
struct new_block_executor_helper_functor
{
mutable Function f_;
// this is the form of operator() for bulk_then_execute() with a non-void predecessor future
template<class Arg1, class Arg2>
__device__
void operator()(grid_executor::index_type idx, Arg1& predecessor, agency::detail::unit, Arg2& inner_shared_param) const
{
agency::detail::invoke(f_, agency::detail::get<1>(idx), predecessor, inner_shared_param);
}
// this is the form of operator() for then_execute() with a void predecessor future
template<class Arg>
__device__
void operator()(grid_executor::index_type idx, agency::detail::unit, Arg& inner_shared_param) const
{
agency::detail::invoke(f_, agency::detail::get<1>(idx), inner_shared_param);
}
};
} // end detail
class block_executor : private grid_executor
{
private:
using super_t = grid_executor;
using super_traits = executor_traits<super_t>;
using traits = executor_traits<block_executor>;
public:
using execution_category = concurrent_execution_tag;
using shape_type = std::tuple_element<1, super_traits::shape_type>::type;
using index_type = std::tuple_element<1, super_traits::index_type>::type;
template<class T>
using future = super_traits::future<T>;
template<class T>
using container = detail::array<T, shape_type>;
future<void> make_ready_future()
{
return super_traits::template make_ready_future<void>(*this);
}
using super_t::super_t;
using super_t::device;
template<class Function>
__host__ __device__
shape_type max_shape(Function f) const
{
return super_t::max_shape(f).y;
}
// XXX eliminate this once we finish scrubbing use of the old-style executor_traits
template<class Function, class Factory1, class T, class Factory2,
class = agency::detail::result_of_continuation_t<
Function,
index_type,
async_future<T>,
agency::detail::result_of_t<Factory2()>&
>
>
async_future<agency::detail::result_of_t<Factory1(shape_type)>>
then_execute(Function f, Factory1 result_factory, shape_type shape, async_future<T>& fut, Factory2 shared_factory)
{
// wrap f with a functor which accepts indices which grid_executor produces
auto wrapped_f = detail::block_executor_helper_functor<Function>{f};
// wrap result_factory with a factory which creates a container with indices that grid_executor produces
auto wrapped_result_factory = detail::block_executor_helper_container_factory<Factory1>{result_factory};
return super_traits::then_execute(*this, wrapped_f, wrapped_result_factory, super_t::shape_type{1,shape}, fut, agency::detail::unit_factory(), shared_factory);
}
template<class Function, class T, class ResultFactory, class SharedFactory,
class = agency::detail::result_of_continuation_t<
Function,
index_type,
async_future<T>,
agency::detail::result_of_t<ResultFactory()>&,
agency::detail::result_of_t<SharedFactory()>&
>
>
async_future<agency::detail::result_of_t<ResultFactory()>>
bulk_then_execute(Function f, shape_type shape, async_future<T>& predecessor, ResultFactory result_factory, SharedFactory shared_factory)
{
// wrap f with a functor which accepts indices which grid_executor produces
auto wrapped_f = detail::new_block_executor_helper_functor<Function>{f};
// call grid_executor's .bulk_then_execute()
return super_t::bulk_then_execute(wrapped_f, super_t::shape_type{1,shape}, predecessor, result_factory, agency::detail::unit_factory(), shared_factory);
}
};
} // end cuda
} // end agency
<commit_msg>Fix cuda::block_executor's helper functor<commit_after>#pragma once
#include <agency/cuda/execution/executor/grid_executor.hpp>
#include <agency/detail/tuple.hpp>
#include <agency/detail/invoke.hpp>
#include <agency/detail/type_traits.hpp>
namespace agency
{
namespace cuda
{
namespace detail
{
template<class Function>
struct block_executor_helper_functor
{
mutable Function f_;
// this is the form of operator() for then_execute() with a non-void future and a shared parameter
template<class Arg1, class Arg2>
__device__
auto operator()(grid_executor::index_type idx, Arg1& past_arg, agency::detail::unit, Arg2& inner_shared_param) const ->
decltype(agency::detail::invoke(f_, agency::detail::get<1>(idx), past_arg, inner_shared_param))
{
return agency::detail::invoke(f_, agency::detail::get<1>(idx), past_arg, inner_shared_param);
}
// this is the form of operator() for then_execute() with a void future and a shared parameter
template<class Arg>
__device__
auto operator()(grid_executor::index_type idx, agency::detail::unit, Arg& inner_shared_param) const ->
decltype(agency::detail::invoke(f_, agency::detail::get<1>(idx), inner_shared_param))
{
return agency::detail::invoke(f_, agency::detail::get<1>(idx), inner_shared_param);
}
};
// this container exposes a public interface that makes it look
// like a container that a grid_executor can produce values into (i.e., it is two-dimensional)
// internally, it discards the first dimension of the shape & index and forwards the second
// dimension of each to the actual Container
template<class Container>
class block_executor_helper_container : public Container
{
private:
using super_t = Container;
public:
__host__ __device__
block_executor_helper_container()
: super_t()
{}
__host__ __device__
block_executor_helper_container(Container&& super)
: super_t(std::move(super))
{}
__host__ __device__
auto operator[](grid_executor::index_type idx) ->
decltype(this->operator[](agency::detail::get<1>(idx)))
{
return super_t::operator[](agency::detail::get<1>(idx));
}
};
template<class Factory>
struct block_executor_helper_container_factory
{
Factory factory_;
using factory_arg_type = typename std::tuple_element<1,grid_executor::shape_type>::type;
using block_executor_container_type = agency::detail::result_of_t<Factory(factory_arg_type)>;
__host__ __device__
block_executor_helper_container<block_executor_container_type> operator()(grid_executor::shape_type shape)
{
return block_executor_helper_container<block_executor_container_type>(factory_(agency::detail::get<1>(shape)));
}
};
// XXX eliminate the stuff above this once we scrub use of old executor_traits
template<class Function>
struct new_block_executor_helper_functor
{
mutable Function f_;
// this is the form of operator() for bulk_then_execute() with a non-void predecessor future
template<class Predecessor, class Result, class InnerSharedArg>
__device__
void operator()(grid_executor::index_type idx, Predecessor& predecessor, Result& result, agency::detail::unit, InnerSharedArg& inner_shared_arg) const
{
agency::detail::invoke(f_, agency::detail::get<1>(idx), predecessor, result, inner_shared_arg);
}
// this is the form of operator() for bulk_then_execute() with a void predecessor future
template<class Result, class InnerSharedArg>
__device__
void operator()(grid_executor::index_type idx, Result& result, agency::detail::unit, InnerSharedArg& inner_shared_arg) const
{
agency::detail::invoke(f_, agency::detail::get<1>(idx), result, inner_shared_arg);
}
};
} // end detail
class block_executor : private grid_executor
{
private:
using super_t = grid_executor;
using super_traits = executor_traits<super_t>;
using traits = executor_traits<block_executor>;
public:
using execution_category = concurrent_execution_tag;
using shape_type = std::tuple_element<1, super_traits::shape_type>::type;
using index_type = std::tuple_element<1, super_traits::index_type>::type;
template<class T>
using future = super_traits::future<T>;
template<class T>
using container = detail::array<T, shape_type>;
future<void> make_ready_future()
{
return super_traits::template make_ready_future<void>(*this);
}
using super_t::super_t;
using super_t::device;
template<class Function>
__host__ __device__
shape_type max_shape(Function f) const
{
return super_t::max_shape(f).y;
}
// XXX eliminate this once we finish scrubbing use of the old-style executor_traits
template<class Function, class Factory1, class T, class Factory2,
class = agency::detail::result_of_continuation_t<
Function,
index_type,
async_future<T>,
agency::detail::result_of_t<Factory2()>&
>
>
async_future<agency::detail::result_of_t<Factory1(shape_type)>>
then_execute(Function f, Factory1 result_factory, shape_type shape, async_future<T>& fut, Factory2 shared_factory)
{
// wrap f with a functor which accepts indices which grid_executor produces
auto wrapped_f = detail::block_executor_helper_functor<Function>{f};
// wrap result_factory with a factory which creates a container with indices that grid_executor produces
auto wrapped_result_factory = detail::block_executor_helper_container_factory<Factory1>{result_factory};
return super_traits::then_execute(*this, wrapped_f, wrapped_result_factory, super_t::shape_type{1,shape}, fut, agency::detail::unit_factory(), shared_factory);
}
template<class Function, class T, class ResultFactory, class SharedFactory,
class = agency::detail::result_of_continuation_t<
Function,
index_type,
async_future<T>,
agency::detail::result_of_t<ResultFactory()>&,
agency::detail::result_of_t<SharedFactory()>&
>
>
async_future<agency::detail::result_of_t<ResultFactory()>>
bulk_then_execute(Function f, shape_type shape, async_future<T>& predecessor, ResultFactory result_factory, SharedFactory shared_factory)
{
// wrap f with a functor which accepts indices which grid_executor produces
auto wrapped_f = detail::new_block_executor_helper_functor<Function>{f};
// call grid_executor's .bulk_then_execute()
return super_t::bulk_then_execute(wrapped_f, super_t::shape_type{1,shape}, predecessor, result_factory, agency::detail::unit_factory(), shared_factory);
}
};
} // end cuda
} // end agency
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2017 Cryptonomex, Inc., and contributors.
*
* The MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#pragma once
#include <graphene/chain/protocol/asset_ops.hpp>
#include <boost/multi_index/composite_key.hpp>
#include <graphene/db/generic_index.hpp>
/**
* @defgroup prediction_market Prediction Market
*
* A prediction market is a specialized BitAsset such that total debt and total collateral are always equal amounts
* (although asset IDs differ). No margin calls or force settlements may be performed on a prediction market asset. A
* prediction market is globally settled by the issuer after the event being predicted resolves, thus a prediction
* market must always have the @ref global_settle permission enabled. The maximum price for global settlement or short
* sale of a prediction market asset is 1-to-1.
*/
namespace graphene { namespace chain {
class account_object;
class database;
using namespace graphene::db;
/**
* @brief tracks the asset information that changes frequently
* @ingroup object
* @ingroup implementation
*
* Because the asset_object is very large it doesn't make sense to save an undo state
* for all of the parameters that never change. This object factors out the parameters
* of an asset that change in almost every transaction that involves the asset.
*
* This object exists as an implementation detail and its ID should never be referenced by
* a blockchain operation.
*/
class asset_dynamic_data_object : public abstract_object<asset_dynamic_data_object>
{
public:
static const uint8_t space_id = implementation_ids;
static const uint8_t type_id = impl_asset_dynamic_data_type;
/// The number of shares currently in existence
share_type current_supply;
share_type confidential_supply; ///< total asset held in confidential balances
share_type accumulated_fees; ///< fees accumulate to be paid out over time
share_type fee_pool; ///< in core asset
};
/**
* @brief tracks the parameters of an asset
* @ingroup object
*
* All assets have a globally unique symbol name that controls how they are traded and an issuer who
* has authority over the parameters of the asset.
*/
class asset_object : public graphene::db::abstract_object<asset_object>
{
public:
static const uint8_t space_id = protocol_ids;
static const uint8_t type_id = asset_object_type;
/// This function does not check if any registered asset has this symbol or not; it simply checks whether the
/// symbol would be valid.
/// @return true if symbol is a valid ticker symbol; false otherwise.
static bool is_valid_symbol( const string& symbol );
/// @return true if this is a market-issued asset; false otherwise.
bool is_market_issued()const { return bitasset_data_id.valid(); }
/// @return true if users may request force-settlement of this market-issued asset; false otherwise
bool can_force_settle()const { return !(options.flags & disable_force_settle); }
/// @return true if the issuer of this market-issued asset may globally settle the asset; false otherwise
bool can_global_settle()const { return options.issuer_permissions & global_settle; }
/// @return true if this asset charges a fee for the issuer on market operations; false otherwise
bool charges_market_fees()const { return options.flags & charge_market_fee; }
/// @return true if this asset may only be transferred to/from the issuer or market orders
bool is_transfer_restricted()const { return options.flags & transfer_restricted; }
bool can_override()const { return options.flags & override_authority; }
bool allow_confidential()const { return !(options.flags & asset_issuer_permission_flags::disable_confidential); }
/// Helper function to get an asset object with the given amount in this asset's type
asset amount(share_type a)const { return asset(a, id); }
/// Convert a string amount (i.e. "123.45") to an asset object with this asset's type
/// The string may have a decimal and/or a negative sign.
asset amount_from_string(string amount_string)const;
/// Convert an asset to a textual representation, i.e. "123.45"
string amount_to_string(share_type amount)const;
/// Convert an asset to a textual representation, i.e. "123.45"
string amount_to_string(const asset& amount)const
{ FC_ASSERT(amount.asset_id == id); return amount_to_string(amount.amount); }
/// Convert an asset to a textual representation with symbol, i.e. "123.45 USD"
string amount_to_pretty_string(share_type amount)const
{ return amount_to_string(amount) + " " + symbol; }
/// Convert an asset to a textual representation with symbol, i.e. "123.45 USD"
string amount_to_pretty_string(const asset &amount)const
{ FC_ASSERT(amount.asset_id == id); return amount_to_pretty_string(amount.amount); }
/// Ticker symbol for this asset, i.e. "USD"
string symbol;
/// Maximum number of digits after the decimal point (must be <= 12)
uint8_t precision = 0;
/// ID of the account which issued this asset.
account_id_type issuer;
asset_options options;
/// Current supply, fee pool, and collected fees are stored in a separate object as they change frequently.
asset_dynamic_data_id_type dynamic_asset_data_id;
/// Extra data associated with BitAssets. This field is non-null if and only if is_market_issued() returns true
optional<asset_bitasset_data_id_type> bitasset_data_id;
optional<account_id_type> buyback_account;
asset_id_type get_id()const { return id; }
void validate()const
{
// UIAs may not be prediction markets, have force settlement, or global settlements
if( !is_market_issued() )
{
FC_ASSERT(!(options.flags & disable_force_settle || options.flags & global_settle));
FC_ASSERT(!(options.issuer_permissions & disable_force_settle || options.issuer_permissions & global_settle));
}
}
template<class DB>
const asset_bitasset_data_object& bitasset_data(const DB& db)const
{ assert(bitasset_data_id); return db.get(*bitasset_data_id); }
template<class DB>
const asset_dynamic_data_object& dynamic_data(const DB& db)const
{ return db.get(dynamic_asset_data_id); }
/**
* The total amount of an asset that is reserved for future issuance.
*/
template<class DB>
share_type reserved( const DB& db )const
{ return options.max_supply - dynamic_data(db).current_supply; }
};
/**
* @brief contains properties that only apply to bitassets (market issued assets)
*
* @ingroup object
* @ingroup implementation
*/
class asset_bitasset_data_object : public abstract_object<asset_bitasset_data_object>
{
public:
static const uint8_t space_id = implementation_ids;
static const uint8_t type_id = impl_asset_bitasset_data_type;
/// The tunable options for BitAssets are stored in this field.
bitasset_options options;
/// Feeds published for this asset. If issuer is not committee, the keys in this map are the feed publishing
/// accounts; otherwise, the feed publishers are the currently active committee_members and witnesses and this map
/// should be treated as an implementation detail. The timestamp on each feed is the time it was published.
flat_map<account_id_type, pair<time_point_sec,price_feed>> feeds;
/// This is the currently active price feed, calculated as the median of values from the currently active
/// feeds.
price_feed current_feed;
/// This is the publication time of the oldest feed which was factored into current_feed.
time_point_sec current_feed_publication_time;
/// True if this asset implements a @ref prediction_market
bool is_prediction_market = false;
/// This is the volume of this asset which has been force-settled this maintanence interval
share_type force_settled_volume;
/// Calculate the maximum force settlement volume per maintenance interval, given the current share supply
share_type max_force_settlement_volume(share_type current_supply)const;
/** return true if there has been a black swan, false otherwise */
bool has_settlement()const { return !settlement_price.is_null(); }
/**
* In the event of a black swan, the swan price is saved in the settlement price, and all margin positions
* are settled at the same price with the siezed collateral being moved into the settlement fund. From this
* point on no further updates to the asset are permitted (no feeds, etc) and forced settlement occurs
* immediately when requested, using the settlement price and fund.
*/
///@{
/// Price at which force settlements of a black swanned asset will occur
price settlement_price;
/// Amount of collateral which is available for force settlement
share_type settlement_fund;
///@}
time_point_sec feed_expiration_time()const
{ return current_feed_publication_time + options.feed_lifetime_sec; }
bool feed_is_expired_before_hardfork_615(time_point_sec current_time)const
{ return feed_expiration_time() >= current_time; }
bool feed_is_expired(time_point_sec current_time)const
{ return feed_expiration_time() <= current_time; }
void update_median_feeds(time_point_sec current_time);
};
struct by_feed_expiration;
typedef multi_index_container<
asset_bitasset_data_object,
indexed_by<
ordered_unique< tag<by_id>, member< object, object_id_type, &object::id > >,
ordered_non_unique< tag<by_feed_expiration>,
const_mem_fun< asset_bitasset_data_object, time_point_sec, &asset_bitasset_data_object::feed_expiration_time >
>
>
> asset_bitasset_data_object_multi_index_type;
typedef generic_index<asset_bitasset_data_object, asset_bitasset_data_object_multi_index_type> asset_bitasset_data_index;
struct by_symbol;
struct by_type;
struct by_issuer;
typedef multi_index_container<
asset_object,
indexed_by<
ordered_unique< tag<by_id>, member< object, object_id_type, &object::id > >,
ordered_unique< tag<by_symbol>, member<asset_object, string, &asset_object::symbol> >,
ordered_non_unique< tag<by_issuer>, member<asset_object, account_id_type, &asset_object::issuer > >,
ordered_unique< tag<by_type>,
composite_key< asset_object,
const_mem_fun<asset_object, bool, &asset_object::is_market_issued>,
member< object, object_id_type, &object::id >
>
>
>
> asset_object_multi_index_type;
typedef generic_index<asset_object, asset_object_multi_index_type> asset_index;
} } // graphene::chain
FC_REFLECT_DERIVED( graphene::chain::asset_dynamic_data_object, (graphene::db::object),
(current_supply)(confidential_supply)(accumulated_fees)(fee_pool) )
FC_REFLECT_DERIVED( graphene::chain::asset_bitasset_data_object, (graphene::db::object),
(feeds)
(current_feed)
(current_feed_publication_time)
(options)
(force_settled_volume)
(is_prediction_market)
(settlement_price)
(settlement_fund)
)
FC_REFLECT_DERIVED( graphene::chain::asset_object, (graphene::db::object),
(symbol)
(precision)
(issuer)
(options)
(dynamic_asset_data_id)
(bitasset_data_id)
(buyback_account)
)
<commit_msg>Removed unused index by_feed_expiration<commit_after>/*
* Copyright (c) 2017 Cryptonomex, Inc., and contributors.
*
* The MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#pragma once
#include <graphene/chain/protocol/asset_ops.hpp>
#include <boost/multi_index/composite_key.hpp>
#include <graphene/db/generic_index.hpp>
/**
* @defgroup prediction_market Prediction Market
*
* A prediction market is a specialized BitAsset such that total debt and total collateral are always equal amounts
* (although asset IDs differ). No margin calls or force settlements may be performed on a prediction market asset. A
* prediction market is globally settled by the issuer after the event being predicted resolves, thus a prediction
* market must always have the @ref global_settle permission enabled. The maximum price for global settlement or short
* sale of a prediction market asset is 1-to-1.
*/
namespace graphene { namespace chain {
class account_object;
class database;
using namespace graphene::db;
/**
* @brief tracks the asset information that changes frequently
* @ingroup object
* @ingroup implementation
*
* Because the asset_object is very large it doesn't make sense to save an undo state
* for all of the parameters that never change. This object factors out the parameters
* of an asset that change in almost every transaction that involves the asset.
*
* This object exists as an implementation detail and its ID should never be referenced by
* a blockchain operation.
*/
class asset_dynamic_data_object : public abstract_object<asset_dynamic_data_object>
{
public:
static const uint8_t space_id = implementation_ids;
static const uint8_t type_id = impl_asset_dynamic_data_type;
/// The number of shares currently in existence
share_type current_supply;
share_type confidential_supply; ///< total asset held in confidential balances
share_type accumulated_fees; ///< fees accumulate to be paid out over time
share_type fee_pool; ///< in core asset
};
/**
* @brief tracks the parameters of an asset
* @ingroup object
*
* All assets have a globally unique symbol name that controls how they are traded and an issuer who
* has authority over the parameters of the asset.
*/
class asset_object : public graphene::db::abstract_object<asset_object>
{
public:
static const uint8_t space_id = protocol_ids;
static const uint8_t type_id = asset_object_type;
/// This function does not check if any registered asset has this symbol or not; it simply checks whether the
/// symbol would be valid.
/// @return true if symbol is a valid ticker symbol; false otherwise.
static bool is_valid_symbol( const string& symbol );
/// @return true if this is a market-issued asset; false otherwise.
bool is_market_issued()const { return bitasset_data_id.valid(); }
/// @return true if users may request force-settlement of this market-issued asset; false otherwise
bool can_force_settle()const { return !(options.flags & disable_force_settle); }
/// @return true if the issuer of this market-issued asset may globally settle the asset; false otherwise
bool can_global_settle()const { return options.issuer_permissions & global_settle; }
/// @return true if this asset charges a fee for the issuer on market operations; false otherwise
bool charges_market_fees()const { return options.flags & charge_market_fee; }
/// @return true if this asset may only be transferred to/from the issuer or market orders
bool is_transfer_restricted()const { return options.flags & transfer_restricted; }
bool can_override()const { return options.flags & override_authority; }
bool allow_confidential()const { return !(options.flags & asset_issuer_permission_flags::disable_confidential); }
/// Helper function to get an asset object with the given amount in this asset's type
asset amount(share_type a)const { return asset(a, id); }
/// Convert a string amount (i.e. "123.45") to an asset object with this asset's type
/// The string may have a decimal and/or a negative sign.
asset amount_from_string(string amount_string)const;
/// Convert an asset to a textual representation, i.e. "123.45"
string amount_to_string(share_type amount)const;
/// Convert an asset to a textual representation, i.e. "123.45"
string amount_to_string(const asset& amount)const
{ FC_ASSERT(amount.asset_id == id); return amount_to_string(amount.amount); }
/// Convert an asset to a textual representation with symbol, i.e. "123.45 USD"
string amount_to_pretty_string(share_type amount)const
{ return amount_to_string(amount) + " " + symbol; }
/// Convert an asset to a textual representation with symbol, i.e. "123.45 USD"
string amount_to_pretty_string(const asset &amount)const
{ FC_ASSERT(amount.asset_id == id); return amount_to_pretty_string(amount.amount); }
/// Ticker symbol for this asset, i.e. "USD"
string symbol;
/// Maximum number of digits after the decimal point (must be <= 12)
uint8_t precision = 0;
/// ID of the account which issued this asset.
account_id_type issuer;
asset_options options;
/// Current supply, fee pool, and collected fees are stored in a separate object as they change frequently.
asset_dynamic_data_id_type dynamic_asset_data_id;
/// Extra data associated with BitAssets. This field is non-null if and only if is_market_issued() returns true
optional<asset_bitasset_data_id_type> bitasset_data_id;
optional<account_id_type> buyback_account;
asset_id_type get_id()const { return id; }
void validate()const
{
// UIAs may not be prediction markets, have force settlement, or global settlements
if( !is_market_issued() )
{
FC_ASSERT(!(options.flags & disable_force_settle || options.flags & global_settle));
FC_ASSERT(!(options.issuer_permissions & disable_force_settle || options.issuer_permissions & global_settle));
}
}
template<class DB>
const asset_bitasset_data_object& bitasset_data(const DB& db)const
{ assert(bitasset_data_id); return db.get(*bitasset_data_id); }
template<class DB>
const asset_dynamic_data_object& dynamic_data(const DB& db)const
{ return db.get(dynamic_asset_data_id); }
/**
* The total amount of an asset that is reserved for future issuance.
*/
template<class DB>
share_type reserved( const DB& db )const
{ return options.max_supply - dynamic_data(db).current_supply; }
};
/**
* @brief contains properties that only apply to bitassets (market issued assets)
*
* @ingroup object
* @ingroup implementation
*/
class asset_bitasset_data_object : public abstract_object<asset_bitasset_data_object>
{
public:
static const uint8_t space_id = implementation_ids;
static const uint8_t type_id = impl_asset_bitasset_data_type;
/// The tunable options for BitAssets are stored in this field.
bitasset_options options;
/// Feeds published for this asset. If issuer is not committee, the keys in this map are the feed publishing
/// accounts; otherwise, the feed publishers are the currently active committee_members and witnesses and this map
/// should be treated as an implementation detail. The timestamp on each feed is the time it was published.
flat_map<account_id_type, pair<time_point_sec,price_feed>> feeds;
/// This is the currently active price feed, calculated as the median of values from the currently active
/// feeds.
price_feed current_feed;
/// This is the publication time of the oldest feed which was factored into current_feed.
time_point_sec current_feed_publication_time;
/// True if this asset implements a @ref prediction_market
bool is_prediction_market = false;
/// This is the volume of this asset which has been force-settled this maintanence interval
share_type force_settled_volume;
/// Calculate the maximum force settlement volume per maintenance interval, given the current share supply
share_type max_force_settlement_volume(share_type current_supply)const;
/** return true if there has been a black swan, false otherwise */
bool has_settlement()const { return !settlement_price.is_null(); }
/**
* In the event of a black swan, the swan price is saved in the settlement price, and all margin positions
* are settled at the same price with the siezed collateral being moved into the settlement fund. From this
* point on no further updates to the asset are permitted (no feeds, etc) and forced settlement occurs
* immediately when requested, using the settlement price and fund.
*/
///@{
/// Price at which force settlements of a black swanned asset will occur
price settlement_price;
/// Amount of collateral which is available for force settlement
share_type settlement_fund;
///@}
time_point_sec feed_expiration_time()const
{ return current_feed_publication_time + options.feed_lifetime_sec; }
bool feed_is_expired_before_hardfork_615(time_point_sec current_time)const
{ return feed_expiration_time() >= current_time; }
bool feed_is_expired(time_point_sec current_time)const
{ return feed_expiration_time() <= current_time; }
void update_median_feeds(time_point_sec current_time);
};
typedef multi_index_container<
asset_bitasset_data_object,
indexed_by<
ordered_unique< tag<by_id>, member< object, object_id_type, &object::id > >
>
> asset_bitasset_data_object_multi_index_type;
typedef generic_index<asset_bitasset_data_object, asset_bitasset_data_object_multi_index_type> asset_bitasset_data_index;
struct by_symbol;
struct by_type;
struct by_issuer;
typedef multi_index_container<
asset_object,
indexed_by<
ordered_unique< tag<by_id>, member< object, object_id_type, &object::id > >,
ordered_unique< tag<by_symbol>, member<asset_object, string, &asset_object::symbol> >,
ordered_non_unique< tag<by_issuer>, member<asset_object, account_id_type, &asset_object::issuer > >,
ordered_unique< tag<by_type>,
composite_key< asset_object,
const_mem_fun<asset_object, bool, &asset_object::is_market_issued>,
member< object, object_id_type, &object::id >
>
>
>
> asset_object_multi_index_type;
typedef generic_index<asset_object, asset_object_multi_index_type> asset_index;
} } // graphene::chain
FC_REFLECT_DERIVED( graphene::chain::asset_dynamic_data_object, (graphene::db::object),
(current_supply)(confidential_supply)(accumulated_fees)(fee_pool) )
FC_REFLECT_DERIVED( graphene::chain::asset_bitasset_data_object, (graphene::db::object),
(feeds)
(current_feed)
(current_feed_publication_time)
(options)
(force_settled_volume)
(is_prediction_market)
(settlement_price)
(settlement_fund)
)
FC_REFLECT_DERIVED( graphene::chain::asset_object, (graphene::db::object),
(symbol)
(precision)
(issuer)
(options)
(dynamic_asset_data_id)
(bitasset_data_id)
(buyback_account)
)
<|endoftext|> |
<commit_before>/*=========================================================================
Program: KWSys - Kitware System Library
Module: testDynamicLoader.cxx
Copyright (c) Kitware, Inc., Insight Consortium. All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "kwsysPrivate.h"
#include KWSYS_HEADER(DynamicLoader.hxx)
#include KWSYS_HEADER(ios/iostream)
#include KWSYS_HEADER(stl/string)
// Work-around CMake dependency scanning limitation. This must
// duplicate the above list of headers.
#if 0
# include "DynamicLoader.hxx.in"
# include "kwsys_ios_iostream.h.in"
# include "kwsys_stl_string.hxx.in"
#endif
#include "testSystemTools.h"
kwsys_stl::string GetLibName(const char* lname)
{
// Construct proper name of lib
kwsys_stl::string slname;
slname = EXECUTABLE_OUTPUT_PATH;
#ifdef CMAKE_INTDIR
slname += "/";
slname += CMAKE_INTDIR;
#endif
slname += "/";
slname += kwsys::DynamicLoader::LibPrefix();
slname += lname;
slname += kwsys::DynamicLoader::LibExtension();
return slname;
}
/* libname = Library name (proper prefix, proper extension)
* System = symbol to lookup in libname
* r1: should OpenLibrary succeed ?
* r2: should GetSymbolAddress succeed ?
* r3: should CloseLibrary succeed ?
*/
int TestDynamicLoader(const char* libname, const char* symbol, int r1, int r2, int r3)
{
kwsys_ios::cerr << "Testing: " << libname << kwsys_ios::endl;
kwsys::LibHandle l = kwsys::DynamicLoader::OpenLibrary(libname);
// If result is incompatible with expectation just fails (xor):
if( (r1 && !l) || (!r1 && l) )
{
kwsys_ios::cerr
<< kwsys::DynamicLoader::LastError() << kwsys_ios::endl;
return 1;
}
kwsys::DynamicLoaderFunction f = kwsys::DynamicLoader::GetSymbolAddress(l, symbol);
if( (r2 && !f) || (!r2 && f) )
{
kwsys_ios::cerr
<< kwsys::DynamicLoader::LastError() << kwsys_ios::endl;
return 1;
}
#ifndef __APPLE__
int s = kwsys::DynamicLoader::CloseLibrary(l);
if( (r3 && !s) || (!r3 && s) )
{
kwsys_ios::cerr
<< kwsys::DynamicLoader::LastError() << kwsys_ios::endl;
return 1;
}
#endif
return 0;
}
int main(int argc, char *argv[])
{
int res;
if( argc == 3 )
{
// User specify a libname and symbol to check.
res = TestDynamicLoader(argv[1], argv[2],1,1,1);
return res;
}
// Make sure that inexistant lib is giving correct result
res = TestDynamicLoader("azerty_", "foo_bar",0,0,0);
// Make sure that random binary file cannnot be assimilated as dylib
res += TestDynamicLoader(TEST_SYSTEMTOOLS_BIN_FILE, "wp",0,0,0);
#ifdef __linux__
// This one is actually fun to test, since dlopen is by default loaded...wonder why :)
res += TestDynamicLoader("foobar.lib", "dlopen",0,1,0);
res += TestDynamicLoader("libdl.so", "dlopen",1,1,1);
res += TestDynamicLoader("libdl.so", "TestDynamicLoader",1,0,1);
#endif
// Now try on the generated library
kwsys_stl::string libname = GetLibName("testDynload");
res += TestDynamicLoader(libname.c_str(), "dummy",1,0,1);
res += TestDynamicLoader(libname.c_str(), "TestDynamicLoaderFunction",1,1,1);
res += TestDynamicLoader(libname.c_str(), "_TestDynamicLoaderFunction",1,0,1);
res += TestDynamicLoader(libname.c_str(), "TestDynamicLoaderData",1,1,1);
res += TestDynamicLoader(libname.c_str(), "_TestDynamicLoaderData",1,0,1);
return res;
}
<commit_msg>COMP: Fix warning<commit_after>/*=========================================================================
Program: KWSys - Kitware System Library
Module: testDynamicLoader.cxx
Copyright (c) Kitware, Inc., Insight Consortium. All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "kwsysPrivate.h"
#include KWSYS_HEADER(DynamicLoader.hxx)
#include KWSYS_HEADER(ios/iostream)
#include KWSYS_HEADER(stl/string)
// Work-around CMake dependency scanning limitation. This must
// duplicate the above list of headers.
#if 0
# include "DynamicLoader.hxx.in"
# include "kwsys_ios_iostream.h.in"
# include "kwsys_stl_string.hxx.in"
#endif
#include "testSystemTools.h"
kwsys_stl::string GetLibName(const char* lname)
{
// Construct proper name of lib
kwsys_stl::string slname;
slname = EXECUTABLE_OUTPUT_PATH;
#ifdef CMAKE_INTDIR
slname += "/";
slname += CMAKE_INTDIR;
#endif
slname += "/";
slname += kwsys::DynamicLoader::LibPrefix();
slname += lname;
slname += kwsys::DynamicLoader::LibExtension();
return slname;
}
/* libname = Library name (proper prefix, proper extension)
* System = symbol to lookup in libname
* r1: should OpenLibrary succeed ?
* r2: should GetSymbolAddress succeed ?
* r3: should CloseLibrary succeed ?
*/
int TestDynamicLoader(const char* libname, const char* symbol, int r1, int r2, int r3)
{
kwsys_ios::cerr << "Testing: " << libname << kwsys_ios::endl;
kwsys::LibHandle l = kwsys::DynamicLoader::OpenLibrary(libname);
// If result is incompatible with expectation just fails (xor):
if( (r1 && !l) || (!r1 && l) )
{
kwsys_ios::cerr
<< kwsys::DynamicLoader::LastError() << kwsys_ios::endl;
return 1;
}
kwsys::DynamicLoaderFunction f = kwsys::DynamicLoader::GetSymbolAddress(l, symbol);
if( (r2 && !f) || (!r2 && f) )
{
kwsys_ios::cerr
<< kwsys::DynamicLoader::LastError() << kwsys_ios::endl;
return 1;
}
#ifndef __APPLE__
int s = kwsys::DynamicLoader::CloseLibrary(l);
if( (r3 && !s) || (!r3 && s) )
{
kwsys_ios::cerr
<< kwsys::DynamicLoader::LastError() << kwsys_ios::endl;
return 1;
}
#else
(void)r3;
#endif
return 0;
}
int main(int argc, char *argv[])
{
int res;
if( argc == 3 )
{
// User specify a libname and symbol to check.
res = TestDynamicLoader(argv[1], argv[2],1,1,1);
return res;
}
// Make sure that inexistant lib is giving correct result
res = TestDynamicLoader("azerty_", "foo_bar",0,0,0);
// Make sure that random binary file cannnot be assimilated as dylib
res += TestDynamicLoader(TEST_SYSTEMTOOLS_BIN_FILE, "wp",0,0,0);
#ifdef __linux__
// This one is actually fun to test, since dlopen is by default loaded...wonder why :)
res += TestDynamicLoader("foobar.lib", "dlopen",0,1,0);
res += TestDynamicLoader("libdl.so", "dlopen",1,1,1);
res += TestDynamicLoader("libdl.so", "TestDynamicLoader",1,0,1);
#endif
// Now try on the generated library
kwsys_stl::string libname = GetLibName("testDynload");
res += TestDynamicLoader(libname.c_str(), "dummy",1,0,1);
res += TestDynamicLoader(libname.c_str(), "TestDynamicLoaderFunction",1,1,1);
res += TestDynamicLoader(libname.c_str(), "_TestDynamicLoaderFunction",1,0,1);
res += TestDynamicLoader(libname.c_str(), "TestDynamicLoaderData",1,1,1);
res += TestDynamicLoader(libname.c_str(), "_TestDynamicLoaderData",1,0,1);
return res;
}
<|endoftext|> |
<commit_before>/***********************************************************************************************************************
**
** Copyright (c) 2011, 2013 ETH Zurich
** All rights reserved.
**
** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
** following conditions are met:
**
** * Redistributions of source code must retain the above copyright notice, this list of conditions and the following
** disclaimer.
** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
** following disclaimer in the documentation and/or other materials provided with the distribution.
** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products
** derived from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
***********************************************************************************************************************/
#include "VList.h"
#include "Static.h"
#include "Text.h"
#include "../declarative/DeclarativeItemDef.h"
#include "../shapes/Shape.h"
namespace Visualization {
ITEM_COMMON_DEFINITIONS(VList, "item")
VList::VList(Item* parent, NodeType* node, const StyleType* style) : Super(parent, node, style)
{}
void VList::determineRange()
{
setRange(0, node()->size());
}
void VList::setRange(int begin, int end)
{
Q_ASSERT(0 <= begin);
Q_ASSERT(begin <= end);
Q_ASSERT(end <= node()->size());
Q_ASSERT(begin < node()->size() || node()->size() == 0);
rangeBegin_ = begin;
rangeEnd_ = end;
}
void VList::initializeForms()
{
auto listOfNodesGetter = [](Item* i)
{
auto v = static_cast<VList*>(i);
return v->node()->nodes().toList().mid(v->rangeBegin_, v->rangeEnd_ - v->rangeBegin_);
};
auto spaceBetweenElementsGetter = [](Item* i)
{return static_cast<VList*>(i)->style()->itemsStyle().spaceBetweenElements();};
auto hasCursorWhenEmptyGetter = [](Item* i)
{return static_cast<VList*>(i)->style()->itemsStyle().hasCursorWhenEmpty();};
auto notLocationEquivalentGetter = [](Item* i)
{return static_cast<VList*>(i)->style()->itemsStyle().notLocationEquivalentCursors();};
auto noBoundaryCursorsGetter = [](Item* i)
{return static_cast<VList*>(i)->style()->itemsStyle().noBoundaryCursorsInsideShape();};
auto noInnerCursorsGetter = [](Item* i)
{return static_cast<VList*>(i)->style()->itemsStyle().noInnerCursors();};
// Form 0: horizontal orientation
addForm((new SequentialLayoutFormElement())
->setHorizontal()->setSpaceBetweenElements(spaceBetweenElementsGetter)
->setHasCursorWhenEmpty(hasCursorWhenEmptyGetter)
->setNotLocationEquivalentCursors(notLocationEquivalentGetter)
->setNoBoundaryCursors(noBoundaryCursorsGetter)
->setNoInnerCursors(noInnerCursorsGetter)
->setListOfNodes(listOfNodesGetter)
->setMinWidth(3)->setMinHeight(10));
// Form 1: vertical orientation
addForm((new SequentialLayoutFormElement())
->setVertical()->setSpaceBetweenElements(spaceBetweenElementsGetter)
->setHasCursorWhenEmpty(hasCursorWhenEmptyGetter)
->setNotLocationEquivalentCursors(notLocationEquivalentGetter)
->setNoBoundaryCursors(noBoundaryCursorsGetter)
->setNoInnerCursors(noInnerCursorsGetter)
->setListOfNodes(listOfNodesGetter)
->setMinWidth(10)->setMinHeight(3));
// Form 2: EmptyList with a tip
addForm(item<Static>(&I::emptyTip_, [](I* v){ return &v->style()->selectedTip(); }));
}
int VList::determineForm()
{
determineRange();
if (itemOrChildHasFocus() && node()->isEmpty() && style()->showTipWhenSelectedAndEmpty()) return 2;
if (style()->itemsStyle().isHorizontal()) return 0;
else return 1;
}
bool VList::moveCursor(CursorMoveDirection dir, QPoint reference)
{
bool startsFocused = hasFocus();
// If we're already focused and the user pressed a keyboard key, do not stay within the item
if (startsFocused && node()->isEmpty() && style()->showTipWhenSelectedAndEmpty() && dir != MoveOnPosition)
return false;
bool res = Super::moveCursor(dir, reference);
if (res && !startsFocused && node()->isEmpty() && style()->showTipWhenSelectedAndEmpty())
setUpdateNeeded(StandardUpdate);
return res;
}
void VList::updateGeometry(int availableWidth, int availableHeight)
{
Super::updateGeometry(availableWidth, availableHeight);
if (node()->isEmpty() && style()->showTipWhenSelectedAndEmpty() && (height() == 0 || width() == 0))
{
if (height() == 0) setHeight(1);
if (width() == 0) setWidth(1);
}
}
QList<ItemRegion> VList::regions()
{
if (!node()->isEmpty() || !style()->showTipWhenSelectedAndEmpty())
return Super::regions();
//Otherwise returna whole item region
auto ir = ItemRegion(boundingRect().toRect());
Cursor* cur = new Cursor(this, Cursor::BoxCursor);
cur->setRegion( ir.region() );
cur->setPosition( ir.region().center() );
ir.setCursor(cur);
return {ir};
}
void VList::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
Super::paint(painter, option, widget);
if (node()->isEmpty() || !style()->useBackgroundColors() || style()->backgroundColors().isEmpty()) return;
auto children = childItems();
if (children.isEmpty()) return;
QPoint topLeft{0,0};
auto w = width();
auto h = height();
QPoint endPoint{w, h};
if (auto shape = getShape())
{
auto contentRect = shape->contentRect();
topLeft = contentRect.topLeft();
w = contentRect.width();
h = contentRect.height();
endPoint.setX(topLeft.x() + w);
endPoint.setY(topLeft.y() + h);
}
auto horizontal = style()->itemsStyle().isHorizontal();
for(int i = 0; i<children.size(); ++i)
{
if (i+1 < children.size())
{
if (horizontal)
w = (children.at(i)->pos().x() + children.at(i)->width() + children.at(i+1)->pos().x())/2 - topLeft.x();
else
h = (children.at(i)->pos().y() + children.at(i)->height() + children.at(i+1)->pos().y())/2 - topLeft.y();
}
else
{
if (horizontal) w = endPoint.x() - topLeft.x();
else h = endPoint.y() - topLeft.y();
}
painter->fillRect(topLeft.x(), topLeft.y(), w, h,
style()->backgroundColors()[i % style()->backgroundColors().size()]);
if (horizontal) topLeft.rx() += w;
else topLeft.ry() += h;
}
}
}
<commit_msg>Fix the visualization of list item backgrounds to respect item order<commit_after>/***********************************************************************************************************************
**
** Copyright (c) 2011, 2013 ETH Zurich
** All rights reserved.
**
** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
** following conditions are met:
**
** * Redistributions of source code must retain the above copyright notice, this list of conditions and the following
** disclaimer.
** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
** following disclaimer in the documentation and/or other materials provided with the distribution.
** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products
** derived from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
***********************************************************************************************************************/
#include "VList.h"
#include "Static.h"
#include "Text.h"
#include "../declarative/DeclarativeItemDef.h"
#include "../shapes/Shape.h"
namespace Visualization {
ITEM_COMMON_DEFINITIONS(VList, "item")
VList::VList(Item* parent, NodeType* node, const StyleType* style) : Super(parent, node, style)
{}
void VList::determineRange()
{
setRange(0, node()->size());
}
void VList::setRange(int begin, int end)
{
Q_ASSERT(0 <= begin);
Q_ASSERT(begin <= end);
Q_ASSERT(end <= node()->size());
Q_ASSERT(begin < node()->size() || node()->size() == 0);
rangeBegin_ = begin;
rangeEnd_ = end;
}
void VList::initializeForms()
{
auto listOfNodesGetter = [](Item* i)
{
auto v = static_cast<VList*>(i);
return v->node()->nodes().toList().mid(v->rangeBegin_, v->rangeEnd_ - v->rangeBegin_);
};
auto spaceBetweenElementsGetter = [](Item* i)
{return static_cast<VList*>(i)->style()->itemsStyle().spaceBetweenElements();};
auto hasCursorWhenEmptyGetter = [](Item* i)
{return static_cast<VList*>(i)->style()->itemsStyle().hasCursorWhenEmpty();};
auto notLocationEquivalentGetter = [](Item* i)
{return static_cast<VList*>(i)->style()->itemsStyle().notLocationEquivalentCursors();};
auto noBoundaryCursorsGetter = [](Item* i)
{return static_cast<VList*>(i)->style()->itemsStyle().noBoundaryCursorsInsideShape();};
auto noInnerCursorsGetter = [](Item* i)
{return static_cast<VList*>(i)->style()->itemsStyle().noInnerCursors();};
// Form 0: horizontal orientation
addForm((new SequentialLayoutFormElement())
->setHorizontal()->setSpaceBetweenElements(spaceBetweenElementsGetter)
->setHasCursorWhenEmpty(hasCursorWhenEmptyGetter)
->setNotLocationEquivalentCursors(notLocationEquivalentGetter)
->setNoBoundaryCursors(noBoundaryCursorsGetter)
->setNoInnerCursors(noInnerCursorsGetter)
->setListOfNodes(listOfNodesGetter)
->setMinWidth(3)->setMinHeight(10));
// Form 1: vertical orientation
addForm((new SequentialLayoutFormElement())
->setVertical()->setSpaceBetweenElements(spaceBetweenElementsGetter)
->setHasCursorWhenEmpty(hasCursorWhenEmptyGetter)
->setNotLocationEquivalentCursors(notLocationEquivalentGetter)
->setNoBoundaryCursors(noBoundaryCursorsGetter)
->setNoInnerCursors(noInnerCursorsGetter)
->setListOfNodes(listOfNodesGetter)
->setMinWidth(10)->setMinHeight(3));
// Form 2: EmptyList with a tip
addForm(item<Static>(&I::emptyTip_, [](I* v){ return &v->style()->selectedTip(); }));
}
int VList::determineForm()
{
determineRange();
if (itemOrChildHasFocus() && node()->isEmpty() && style()->showTipWhenSelectedAndEmpty()) return 2;
if (style()->itemsStyle().isHorizontal()) return 0;
else return 1;
}
bool VList::moveCursor(CursorMoveDirection dir, QPoint reference)
{
bool startsFocused = hasFocus();
// If we're already focused and the user pressed a keyboard key, do not stay within the item
if (startsFocused && node()->isEmpty() && style()->showTipWhenSelectedAndEmpty() && dir != MoveOnPosition)
return false;
bool res = Super::moveCursor(dir, reference);
if (res && !startsFocused && node()->isEmpty() && style()->showTipWhenSelectedAndEmpty())
setUpdateNeeded(StandardUpdate);
return res;
}
void VList::updateGeometry(int availableWidth, int availableHeight)
{
Super::updateGeometry(availableWidth, availableHeight);
if (node()->isEmpty() && style()->showTipWhenSelectedAndEmpty() && (height() == 0 || width() == 0))
{
if (height() == 0) setHeight(1);
if (width() == 0) setWidth(1);
}
}
QList<ItemRegion> VList::regions()
{
if (!node()->isEmpty() || !style()->showTipWhenSelectedAndEmpty())
return Super::regions();
//Otherwise returna whole item region
auto ir = ItemRegion(boundingRect().toRect());
Cursor* cur = new Cursor(this, Cursor::BoxCursor);
cur->setRegion( ir.region() );
cur->setPosition( ir.region().center() );
ir.setCursor(cur);
return {ir};
}
void VList::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
Super::paint(painter, option, widget);
if (node()->isEmpty() || !style()->useBackgroundColors() || style()->backgroundColors().isEmpty()) return;
auto children = childItems();
if (children.isEmpty()) return;
auto horizontal = style()->itemsStyle().isHorizontal();
// Sort the children so that they appear in the right order
if (horizontal)
qSort(children.begin(), children.end(), [](const Item* left, const Item* right)
{return left->pos().x() < right->pos().x();});
else
qSort(children.begin(), children.end(), [=](const Item* left, const Item* right)
{return left->pos().y() < right->pos().y();});
QPoint topLeft{0,0};
auto w = width();
auto h = height();
QPoint endPoint{w, h};
if (auto shape = getShape())
{
auto contentRect = shape->contentRect();
topLeft = contentRect.topLeft();
w = contentRect.width();
h = contentRect.height();
endPoint.setX(topLeft.x() + w);
endPoint.setY(topLeft.y() + h);
}
for(int i = 0; i<children.size(); ++i)
{
if (i+1 < children.size())
{
if (horizontal)
w = (children.at(i)->pos().x() + children.at(i)->width() + children.at(i+1)->pos().x())/2 - topLeft.x();
else
h = (children.at(i)->pos().y() + children.at(i)->height() + children.at(i+1)->pos().y())/2 - topLeft.y();
}
else
{
if (horizontal) w = endPoint.x() - topLeft.x();
else h = endPoint.y() - topLeft.y();
}
painter->fillRect(topLeft.x(), topLeft.y(), w, h,
style()->backgroundColors()[i % style()->backgroundColors().size()]);
if (horizontal) topLeft.rx() += w;
else topLeft.ry() += h;
}
}
}
<|endoftext|> |
<commit_before>// NegotiateProxy.cpp: .
//
#include "stdafx.h"
int main()
{
return 0;
}
<commit_msg>Add code<commit_after>// NegotiateProxy.cpp
#include "stdafx.h"
#define SECURITY_WIN32
#include <winsock2.h>
#include <stdio.h>
#include <Sspi.h>
#include <wincred.h>
#include <stdlib.h>
#include <Ws2tcpip.h>
#pragma comment(lib, "ws2_32.lib")
#pragma comment(lib, "Secur32.lib")
#pragma comment(lib, "Credui.lib")
// Define parameters
#define BUFF_SIZE 12*1024 // buffer size
#define MAXCONN 10 // The number of connections to the proxy - server
// The parameters for the authentication dialog
BOOL fSave = FALSE; // Checkmark "Remember user"
PSEC_WINNT_AUTH_IDENTITY_OPAQUE pAuthIdentityEx2 = NULL; // The structure for storing user data entered
DWORD dwFlags = 0; // Flags
int WSAInit(void)
{
int iResult;
WSADATA wsaData;
// Initialize Winsock
iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != 0)
{
wprintf(L"WSAStartup failed with error: %d\n", iResult);
}
return iResult;
}
int createEv(WSAEVENT *Event)
{
*Event = WSACreateEvent();
if (*Event == NULL)
{
wprintf(L"WSACreateEvent failed with error: %d\n", GetLastError());
WSACleanup();
return -1;
}
return 0;
}
SOCKET newSock(void)
{
SOCKET sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (sock == INVALID_SOCKET)
{
wprintf(L"socket function failed with error: %d\n", WSAGetLastError());
WSACleanup();
}
return sock;
}
size_t base64_encode(const char *inp, size_t insize, char **outptr)
{
// Base64 Encoding/Decoding Table
static const char table64[] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
unsigned char ibuf[3];
unsigned char obuf[4];
int i;
int inputparts;
char *output;
char *base64data;
char *indata = (char *)inp;
*outptr = NULL; // set to NULL in case of failure before we reach the end
if (0 == insize)
insize = strlen(indata);
base64data = output = (char*)malloc(insize * 4 / 3 + 4);
if (NULL == output)
return 0;
while (insize > 0)
{
for (i = inputparts = 0; i < 3; i++)
{
if (insize > 0)
{
inputparts++;
ibuf[i] = *indata;
indata++;
insize--;
}
else
ibuf[i] = 0;
}
obuf[0] = (unsigned char)((ibuf[0] & 0xFC) >> 2);
obuf[1] = (unsigned char)(((ibuf[0] & 0x03) << 4) | \
((ibuf[1] & 0xF0) >> 4));
obuf[2] = (unsigned char)(((ibuf[1] & 0x0F) << 2) | \
((ibuf[2] & 0xC0) >> 6));
obuf[3] = (unsigned char)(ibuf[2] & 0x3F);
switch (inputparts)
{
case 1: // only one byte read
_snprintf_s(output, 5, _TRUNCATE, "%c%c==",
table64[obuf[0]],
table64[obuf[1]]);
break;
case 2: // two bytes read
_snprintf_s(output, 5, _TRUNCATE, "%c%c%c=",
table64[obuf[0]],
table64[obuf[1]],
table64[obuf[2]]);
break;
default:
_snprintf_s(output, 5, _TRUNCATE, "%c%c%c%c",
table64[obuf[0]],
table64[obuf[1]],
table64[obuf[2]],
table64[obuf[3]]);
break;
}
output += 4;
}
*output = 0;
*outptr = base64data; // make it return the actual data memory
return strlen(base64data); // return the length of the new data
}
int getIpPort(char *inBuff, char *outIp, char *OutPort, int len)
{
int i, n, m;
for (m = 0; (inBuff[m] != ' ') && (m<len); m++) {}
for (n = ++m; (inBuff[n] != ':') && (n<len); n++) {}
for (i = 0; m < n; outIp[i] = inBuff[m], i++, m++) {} outIp[i] = 0;
for (; (inBuff[n] != ' ') && (n<len); n++) {}
for (i = 0, m++; m < n; OutPort[i] = inBuff[m], i++, m++) {} OutPort[i] = 0;
return 0;
}
SECURITY_STATUS getToken(char **negotiateToken, WCHAR *hostName)
{
//----------------------------------------------------------------------
unsigned long cPackages;
PSecPkgInfo PackageInfo;
SECURITY_STATUS stat;
// Get the name of the package
stat = EnumerateSecurityPackages(
&cPackages,
&PackageInfo
);
if (stat != SEC_E_OK)
{
wprintf(
L"Security function failed with error: %#x\n",
stat
);
return stat;
}
SEC_WCHAR *szPackage = PackageInfo->Name;
unsigned long m_cbMaxToken = PackageInfo->cbMaxToken;
PBYTE m_pOutBuf = (PBYTE)malloc(m_cbMaxToken);
BOOL m_fHaveCtxtHandle = false;
//--------------------------------------------------------------------
CREDUI_INFO creduiInfo = { 0 };
creduiInfo.cbSize = sizeof(creduiInfo);
// Change the message text and caption to the actual text for your dialog.
creduiInfo.pszCaptionText = L"Enter the network password";
creduiInfo.pszMessageText = L"Enter your username and password to connect to the proxy-server";
SEC_WCHAR targetName[NI_MAXHOST];
WCHAR *domain = new WCHAR[wcslen(hostName) + 1], *pDomain = domain;
for (int i = wcslen(hostName), point = 0; i >= 0; i--)
{
point += (hostName[i] == L'.');
if (point == 2)
{
domain = &domain[i + 1];
break;
}
domain[i] = towupper(hostName[i]);
}
_snwprintf_s(
targetName,
NI_MAXHOST,
_TRUNCATE,
L"HTTP/%s@%s",
hostName,
domain);
delete[] pDomain;
// Pass user authentication
if (pAuthIdentityEx2 == NULL)
{
stat = SspiPromptForCredentials(
targetName,
&creduiInfo,
0,
szPackage,
NULL,
&pAuthIdentityEx2,
&fSave,
dwFlags
);
if (stat != SEC_E_OK)
{
wprintf(
L"Authentification failed with error: %#x\n",
stat
);
return stat;
}
}
//--------------------------------------------------------------------
if (NULL != pAuthIdentityEx2)
{
//--------------------------------------------------------------------
CredHandle hCredential;
TimeStamp tsExpiry;
stat = AcquireCredentialsHandle(
NULL,
szPackage,
SECPKG_CRED_OUTBOUND,
NULL,
pAuthIdentityEx2,
NULL,
NULL,
&hCredential,
&tsExpiry);
if (stat != SEC_E_OK)
{
wprintf(
L"Credentials function failed with error: %#x\n",
stat
);
return stat;
}
//--------------------------------------------------------------------
CtxtHandle m_hCtxt;
SecBufferDesc outSecBufDesc;
SecBuffer outSecBuf;
unsigned long fContextAttr;
BOOL done = false;
// prepare output buffer
outSecBufDesc.ulVersion = 0;
outSecBufDesc.cBuffers = 1;
outSecBufDesc.pBuffers = &outSecBuf;
outSecBuf.cbBuffer = m_cbMaxToken;
outSecBuf.BufferType = SECBUFFER_TOKEN;
outSecBuf.pvBuffer = m_pOutBuf;
//char *negotiateToken;
stat = InitializeSecurityContext(
&hCredential,
NULL,
targetName,
ISC_REQ_CONFIDENTIALITY,
0, // reserved1
SECURITY_NATIVE_DREP,
NULL,
0, // reserved2
&m_hCtxt,
&outSecBufDesc,
&fContextAttr,
&tsExpiry
);
switch (stat)
{
case SEC_E_OK:
case SEC_I_CONTINUE_NEEDED:
case SEC_I_COMPLETE_AND_CONTINUE: break;
default: return stat;
}
if (outSecBuf.cbBuffer)
{
base64_encode(reinterpret_cast < char* > (m_pOutBuf), outSecBuf.cbBuffer, negotiateToken);
}
}
FreeContextBuffer(PackageInfo);
return SEC_E_OK;
}
int setAuthBuf(char(&buff)[BUFF_SIZE], char *ip, char *port, WCHAR *hostName)
{
char *negotiateToken;
if (getToken(&negotiateToken, hostName) == SEC_E_OK)
{
memset(buff, 0, sizeof(buff));
_snprintf_s(
buff,
BUFF_SIZE,
_TRUNCATE,
"CONNECT %s:%s HTTP/1.0\r\nHost: %s\r\n%s\r\n%s %s\r\n\r\n",
ip,
port,
ip,
"Proxy-Connection: Keep-Alive",
"Proxy-Authorization: Negotiate",
negotiateToken
);
return strlen(buff);
}
else
return -1;
}
int transmit(char(&buff)[BUFF_SIZE], SOCKET sockFrom, SOCKET sockTo, bool toProxy, bool *needAuth, WCHAR *hostName)
{
memset(buff, 0, BUFF_SIZE);
char ip[255], port[10];
memset(ip, 0, 255);
memset(port, 0, 10);
int len = recv(sockFrom, buff, BUFF_SIZE, 0);
if (len < 0) return len;
if (toProxy & *needAuth)
{
getIpPort(buff, ip, port, len);
len = setAuthBuf(buff, ip, port, hostName);
if (len < 0) { return -1; }
*needAuth = false;
}
len = send(sockTo, buff, len, 0);
wprintf(L"%s %i bytes%s\n", toProxy ? L"--> Send to proxy" : L"<-- Send to client", len, len<0 ? L". Transmission failed" : L"");
return len;
}
void info(_TCHAR *progName)
{
wprintf(L"usage: \n%s [LP <lPort>] <rAddr> <rPort>\n\n", progName);
wprintf(L"lPort - the port on which the server listens, by default 3128\n");
wprintf(L"rAddr - address of the proxy-server to which you are connecting\n");
wprintf(L"rPort - proxy-server port to which you are connecting\n\n");
wprintf(L"example: \n%s LP 8080 proxy.host.ru 3128\n", progName);
exit(0);
}
int _tmain(int argc, _TCHAR* argv[])
{
// Get the command line options
WCHAR *lPort, *rPort, *rAddr;
int i = 1;
argv[i] ? NULL : info(argv[0]);
if (!wcscmp(argv[i], L"LP"))
{
(lPort = argv[++i]) ? NULL : info(argv[0]);
(rAddr = argv[++i]) ? NULL : info(argv[0]);
(rPort = argv[++i]) ? NULL : info(argv[0]);
}
else
{
lPort = L"3128";
(rAddr = argv[i++]) ? NULL : info(argv[0]);
(rPort = argv[i++]) ? NULL : info(argv[0]);
}
if (WSAInit()) return -1;
//----------------------------------------------------------------------------------------------------
//SEC_CHAR *targetName = "HTTP/prox.apmes.ru@APMES.RU";
//----------------------------------------------------------------------------------------------------
ADDRINFOT hints, *remoteAddr = NULL, *inetAddr = NULL;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
int iResult = GetAddrInfo(rAddr, rPort, &hints, &remoteAddr);
if (iResult != 0)
{
switch (iResult)
{
case WSAHOST_NOT_FOUND: wprintf(L"Host not found\n"); break;
case WSANO_DATA: wprintf(L"No data record found\n"); break;
default: wprintf(L"Gethost function failed with error: %i\n", iResult);
}
return -1;
}
WCHAR host[NI_MAXHOST];
iResult = GetNameInfo(remoteAddr->ai_addr, sizeof(SOCKADDR), host, NI_MAXHOST, NULL, 0, NI_NAMEREQD);
if (iResult != 0)
{
switch (iResult)
{
case EAI_AGAIN: wprintf(L"The name can not be determined at the moment\n"); break;
case EAI_BADFLAGS: wprintf(L"The flags parameter has an invalid value\n"); break;
case EAI_FAIL: wprintf(L"Name info failed\n"); break;
case EAI_FAMILY: wprintf(L"It does not recognize the address family\n"); break;
case EAI_MEMORY: wprintf(L"Not enough memory\n"); break;
case EAI_NONAME: wprintf(L"The name can not be determined\n"); break;
default: wprintf(L"Nameinfo function failed with error: %i\n", iResult);
}
return -1;
}
// Create a listening socket
SOCKET ListenSocket = newSock();
if (ListenSocket == INVALID_SOCKET) return -1;
// Listen address
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE;
iResult = GetAddrInfo(NULL, lPort, &hints, &inetAddr);
if (iResult != 0)
{
switch (iResult)
{
case WSAHOST_NOT_FOUND: wprintf(L"Host not found\n"); break;
case WSANO_DATA: wprintf(L"No data record found\n"); break;
default: wprintf(L"Gethost function failed with error: %i\n", iResult);
}
return -1;
}
//-------------------------
// Bind the listening socket
iResult = bind(ListenSocket, inetAddr->ai_addr, sizeof(SOCKADDR));
if (iResult != 0)
{
wprintf(L"bind failed with error: %#x\n", WSAGetLastError());
return -1;
}
//-------------------------
// Create a new event
WSAEVENT NewEvent;
if (createEv(&NewEvent)) return -1;
//-------------------------
// Associate event types FD_ACCEPT and FD_CLOSE
// with the listening socket and NewEvent
iResult = WSAEventSelect(ListenSocket, NewEvent, FD_ACCEPT);
if (iResult != 0)
{
wprintf(L"WSAEventSelect failed with error: %#x\n", WSAGetLastError());
return -1;
}
//-------------------------
// Start listening on the socket
iResult = listen(ListenSocket, MAXCONN);
if (iResult != 0)
{
wprintf(L"listen failed with error: %#x\n", WSAGetLastError());
return -1;
}
wprintf(L"MyProxy listen on port %s\n", lPort);
//-------------------------
// Add the socket and event to the arrays, increment number of events
SOCKET SocketArray[WSA_MAXIMUM_WAIT_EVENTS];
WSAEVENT EventArray[WSA_MAXIMUM_WAIT_EVENTS];
DWORD EventTotal = 0;
SocketArray[EventTotal] = ListenSocket;
EventArray[EventTotal] = NewEvent;
EventTotal++;
bool needAuth[WSA_MAXIMUM_WAIT_EVENTS];
memset(needAuth, true, sizeof(needAuth));
bool toProxy;
DWORD Index;
SOCKET ClientSocket, ProxySocket;
WSANETWORKEVENTS NetworkEvents;
// The buffers for the reception - transmission
char prBuff[BUFF_SIZE], clBuff[BUFF_SIZE];
while (1)
{
// Wait for network events on all sockets
Index = WSAWaitForMultipleEvents(EventTotal, EventArray, FALSE, WSA_INFINITE, FALSE);
Index -= WSA_WAIT_EVENT_0;
if ((Index != WSA_WAIT_FAILED) && (Index != WSA_WAIT_TIMEOUT))
{
WSAEnumNetworkEvents(SocketArray[Index], EventArray[Index], &NetworkEvents);
WSAResetEvent(EventArray[Index]);
toProxy = (Index % 2) ? true : false;
if ((NetworkEvents.lNetworkEvents & FD_ACCEPT) && (NetworkEvents.iErrorCode[FD_ACCEPT_BIT] == 0))
{
ClientSocket = accept(ListenSocket, NULL, NULL);
if (INVALID_SOCKET == ClientSocket) wprintf(L"Invalid socket\n");
ProxySocket = socket(AF_INET, SOCK_STREAM, 0);
if (INVALID_SOCKET == ProxySocket) wprintf(L"INVALID_SOCKET ERROR!!!\n");
iResult = connect(ProxySocket, remoteAddr->ai_addr, sizeof(SOCKADDR));
if (iResult != 0)
{
wprintf(L"Connection failed with error: %d\n", WSAGetLastError());
return -1;
}
if (createEv(&NewEvent)) return -1;
SocketArray[EventTotal] = ClientSocket;
EventArray[EventTotal] = NewEvent;
//-------------------------
// Associate event types FD_READ and FD_CLOSE
// with the client socket and NewEvent
iResult = WSAEventSelect(SocketArray[EventTotal], EventArray[EventTotal], FD_READ | FD_CLOSE);
if (iResult != 0)
{
wprintf(L"WSAEventSelect failed with error: %d\n", WSAGetLastError());
return -1;
}
EventTotal++;
if (createEv(&NewEvent)) return -1;
SocketArray[EventTotal] = ProxySocket;
EventArray[EventTotal] = NewEvent;
//-------------------------
// Associate event types FD_READ and FD_CLOSE
// with the proxy socket and NewEvent
iResult = WSAEventSelect(SocketArray[EventTotal], EventArray[EventTotal], FD_READ | FD_CLOSE);
if (iResult != 0)
{
wprintf(L"WSAEventSelect failed with error: %d\n", WSAGetLastError());
return -1;
}
EventTotal++;
}
if ((NetworkEvents.lNetworkEvents & FD_READ) && (NetworkEvents.iErrorCode[FD_READ_BIT] == 0))
{
// transfers data
iResult = transmit(toProxy ? prBuff : clBuff,
SocketArray[Index],
toProxy ? SocketArray[Index + 1] : SocketArray[Index - 1],
toProxy,
&needAuth[Index],
host);
if (iResult < 0) return -1;
}
if (NetworkEvents.lNetworkEvents & FD_CLOSE)
{
shutdown(SocketArray[toProxy ? Index + 1 : Index - 1], SD_BOTH);
shutdown(SocketArray[Index], SD_BOTH);
closesocket(SocketArray[toProxy ? Index + 1 : Index - 1]);
closesocket(SocketArray[Index]);
needAuth[toProxy ? Index : Index - 1] = true;
wprintf(L"Connection closed\n");
}
}
}
return 0;
}<|endoftext|> |
<commit_before>#include "engine/dukintegration.h"
#include <map>
#include <functional>
#include "core/ecs-systems.h"
#include "core/random.h"
#include "core/log.h"
#include "core/sol.h"
#include "engine/components.h"
#include "engine/input.h"
#include "engine/dukregistry.h"
#include "engine/objectemplate.h"
#include "engine/cameradata.h"
LOG_SPECIFY_DEFAULT_LOGGER("engine.duk.integration")
namespace euphoria::engine
{
template<typename T>
std::vector<T> GetVector(const sol::table& table)
{
std::vector<T> r;
r.reserve(table.size());
for(unsigned int i=0; i<table.size(); i+=1)
{
r.emplace_back(table[i+1]);
}
return r;
}
void ReportFirstError(const sol::protected_function_result& val, Sol* ctx,const std::string& action, const std::string& where)
{
if (val.valid())
{
return;
}
const sol::error err = val;
const auto message = fmt::format("Failed to {0} in {1}: {2}", action, where, err.what());
LOG_ERROR("{0}", message);
if (!ctx->has_error)
{
ctx->has_error = true;
ctx->error = message;
}
}
struct DukUpdateSystem
: public core::ecs::ComponentSystem
, public core::ecs::ComponentSystemUpdate
{
// using UpdateFunction = std::function<void(float)>;
using UpdateFunction = sol::protected_function;
Sol* duk;
UpdateFunction func;
DukUpdateSystem(const std::string& name, Sol* d, UpdateFunction f)
: ComponentSystem(name)
, duk(d)
, func(f)
{
ASSERT(func);
}
void
Update(core::ecs::Registry*, float dt) const override
{
auto result = func(dt);
ReportFirstError(result, duk, "update", name);
}
void
RegisterCallbacks(core::ecs::Systems* systems) override
{
systems->update.Add(this);
}
};
struct DukInitSystem
: public core::ecs::ComponentSystem
, public core::ecs::ComponentSystemInit
{
// using InitFunction = std::function<void(core::ecs::EntityId)>;
using InitFunction = sol::protected_function;
core::ecs::Registry* reg;
Sol* duk;
std::vector<core::ecs::ComponentId> types;
InitFunction func;
DukInitSystem
(
const std::string& name,
Sol* d,
core::ecs::Registry* r,
const std::vector<core::ecs::ComponentId>& t,
InitFunction f
)
: ComponentSystem(name)
, reg(r)
, duk(d)
, types(t)
, func(f)
{
}
void
OnAdd(core::ecs::EntityId entity) const override
{
ASSERT(reg);
ASSERT(!types.empty());
for(const auto& type: types)
{
const auto component = reg->GetComponent(entity, type);
const bool has_component = component != nullptr;
if(!has_component)
{
return;
}
}
auto result = func(entity);
ReportFirstError(result, duk, "init", name);
}
void
RegisterCallbacks(core::ecs::Systems* systems) override
{
systems->init.Add(this);
}
};
struct DukSystems
{
core::ecs::Systems* systems;
Sol* duk;
explicit DukSystems(core::ecs::Systems* s, Sol* d)
: systems(s)
, duk(d)
{
}
void
AddUpdate(const std::string& name, DukUpdateSystem::UpdateFunction func)
{
systems->AddAndRegister(std::make_shared<DukUpdateSystem>(name, duk, func));
}
void
AddInit
(
const std::string& name,
core::ecs::Registry* reg,
const std::vector<core::ecs::ComponentId>& types,
DukInitSystem::InitFunction func
)
{
systems->AddAndRegister(std::make_shared<DukInitSystem>(name, duk, reg, types, func));
}
};
struct DukIntegrationPimpl
{
DukIntegrationPimpl
(
core::ecs::Systems* sys,
core::ecs::World* world,
Sol* duk,
ObjectCreator* creator,
Components* components,
CameraData* cam
)
: systems(sys, duk)
, registry(&world->reg, components)
, input(duk->lua["Input"].get_or_create<sol::table>())
, world(world)
, creator(creator)
, components(components)
, camera(cam)
{
}
void
Integrate(Sol* duk)
{
auto systems_table = duk->lua["Systems"].get_or_create<sol::table>();
systems_table["AddUpdate"] = [&](const std::string& name, sol::function func)
{
systems.AddUpdate(name, func);
};
systems_table["OnInit"] = [&]
(
const std::string& name,
sol::table types,
sol::function func
)
{
auto vtypes = GetVector<core::ecs::ComponentId>(types);
systems.AddInit(name, &world->reg, vtypes, func);
};
auto math_table = duk->lua["Math"].get_or_create<sol::table>();
math_table["NewRandom"] = [&]() { return std::make_shared<core::Random>(); };
auto templates_table = duk->lua["Templates"].get_or_create<sol::table>();
templates_table["Find"] = [&](const std::string& name)
{
return creator->FindTemplate(name);
};
duk->lua.new_usertype<ObjectTemplate>("Template");
duk->lua["Template"]["Create"] = [&, duk](ObjectTemplate* t)
{
return t->CreateObject(ObjectCreationArgs{world, ®istry, duk, duk});
};
auto camera_table = duk->lua["Camera"].get_or_create<sol::table>();
camera_table["GetRect"] = [&]() { return &camera->screen; };
duk->lua.new_usertype<CustomArguments>
(
"CustomArguments",
"GetNumber", [](const CustomArguments& args, const std::string& name) -> float
{
const auto f = args.numbers.find(name);
if(f == args.numbers.end())
{
return 0;
}
else
{
return f->second;
}
}
);
auto registry_table = duk->lua["Registry"].get_or_create<sol::table>();
registry_table["Entities"] = [&](sol::table types)
{
return registry.EntityView(GetVector<core::ecs::ComponentId>(types));
};
registry_table["GetSpriteId"] = [&]()
{
return registry.components->sprite;
};
registry_table["DestroyEntity"] = [&](core::ecs::EntityId entity)
{
registry.DestroyEntity(entity);
};
registry_table["GetPosition2Id"] = [&]()
{
LOG_INFO("Getting position 2d");
return registry.components->position2;
};
registry_table["GetSpriteId"] = [&]()
{
return registry.components->sprite;
};
registry_table["New"] = sol::overload
(
[&](const std::string& name, sol::function setup)
{
return registry.CreateNewId(name, setup);
},
[&](const std::string& name)
{
return registry.CreateNewId(name);
}
);
registry_table["Get"] = [&](core::ecs::EntityId ent, core::ecs::ComponentId comp)
{
return registry.GetProperty(ent, comp);
};
registry_table["Set"] = [&](core::ecs::EntityId ent, core::ecs::ComponentId comp, sol::table val)
{
registry.SetProperty(ent, comp, val);
};
registry_table["GetSprite"] = [&](core::ecs::ComponentId ent)
{
return registry.GetComponentOrNull<CSprite>(ent, components->sprite);
};
registry_table["GetPosition2"] = [&](core::ecs::ComponentId ent)
{
return registry.GetComponentOrNull<CPosition2>(ent, components->position2);
};
registry_table["GetPosition2vec"] = [&](core::ecs::ComponentId ent)
{
auto c = registry.GetComponentOrNull<CPosition2>(ent, components->position2);
return c == nullptr ? nullptr : &c->pos;
};
duk->lua.new_usertype<CPosition2>("CPosition2", "vec", &CPosition2::pos);
duk->lua.new_usertype<CSprite>
(
"CSprite",
"GetRect", [](const CSprite& sp, const CPosition2& p)
{
return GetSpriteRect(p.pos, *sp.texture);
}
);
/*
duk->lua.new_usertype<Rectf>(
"Rectf",
sol::no_constructor,
"Contains",
&Rectf::ContainsExclusive,
"GetHeight",
&Rectf::GetHeight,
"GetWidth",
&Rectf::GetWidth);
*/
auto random_type = duk->lua.new_usertype<core::Random>("Random");
random_type["NextFloat01"] = &core::Random::NextFloat01;
random_type["NextRangeFloat"] = [](core::Random& r, float f) -> float
{
return r.NextRange(f);
};
// "NextBool", &Random::NextBool,
// "NextPoint", &Random::NextPoint
}
DukSystems systems;
DukRegistry registry;
sol::table input;
core::ecs::World* world;
ObjectCreator* creator;
Components* components;
CameraData* camera;
};
DukIntegration::DukIntegration
(
core::ecs::Systems* systems,
core::ecs::World* reg,
Sol* duk,
ObjectCreator* creator,
Components* components,
CameraData* camera
)
{
pimpl.reset
(
new DukIntegrationPimpl
(
systems,
reg,
duk,
creator,
components,
camera
)
);
pimpl->Integrate(duk);
}
DukIntegration::~DukIntegration()
{
Clear();
}
void
DukIntegration::Clear()
{
pimpl.reset();
}
DukRegistry&
DukIntegration::Registry()
{
ASSERT(pimpl);
return pimpl->registry;
}
void
DukIntegration::BindKeys(Sol* duk, const Input& input)
{
input.Set(&pimpl->input);
}
}
TYPEID_SETUP_TYPE(euphoria::core::Random);
TYPEID_SETUP_TYPE(euphoria::engine::ObjectTemplate);
TYPEID_SETUP_TYPE(euphoria::core::Rect<float>);
<commit_msg>implemented missing random functions<commit_after>#include "engine/dukintegration.h"
#include <map>
#include <functional>
#include "core/ecs-systems.h"
#include "core/random.h"
#include "core/log.h"
#include "core/sol.h"
#include "engine/components.h"
#include "engine/input.h"
#include "engine/dukregistry.h"
#include "engine/objectemplate.h"
#include "engine/cameradata.h"
LOG_SPECIFY_DEFAULT_LOGGER("engine.duk.integration")
namespace euphoria::engine
{
template<typename T>
std::vector<T> GetVector(const sol::table& table)
{
std::vector<T> r;
r.reserve(table.size());
for(unsigned int i=0; i<table.size(); i+=1)
{
r.emplace_back(table[i+1]);
}
return r;
}
void ReportFirstError(const sol::protected_function_result& val, Sol* ctx,const std::string& action, const std::string& where)
{
if (val.valid())
{
return;
}
const sol::error err = val;
const auto message = fmt::format("Failed to {0} in {1}: {2}", action, where, err.what());
LOG_ERROR("{0}", message);
if (!ctx->has_error)
{
ctx->has_error = true;
ctx->error = message;
}
}
struct DukUpdateSystem
: public core::ecs::ComponentSystem
, public core::ecs::ComponentSystemUpdate
{
// using UpdateFunction = std::function<void(float)>;
using UpdateFunction = sol::protected_function;
Sol* duk;
UpdateFunction func;
DukUpdateSystem(const std::string& name, Sol* d, UpdateFunction f)
: ComponentSystem(name)
, duk(d)
, func(f)
{
ASSERT(func);
}
void
Update(core::ecs::Registry*, float dt) const override
{
auto result = func(dt);
ReportFirstError(result, duk, "update", name);
}
void
RegisterCallbacks(core::ecs::Systems* systems) override
{
systems->update.Add(this);
}
};
struct DukInitSystem
: public core::ecs::ComponentSystem
, public core::ecs::ComponentSystemInit
{
// using InitFunction = std::function<void(core::ecs::EntityId)>;
using InitFunction = sol::protected_function;
core::ecs::Registry* reg;
Sol* duk;
std::vector<core::ecs::ComponentId> types;
InitFunction func;
DukInitSystem
(
const std::string& name,
Sol* d,
core::ecs::Registry* r,
const std::vector<core::ecs::ComponentId>& t,
InitFunction f
)
: ComponentSystem(name)
, reg(r)
, duk(d)
, types(t)
, func(f)
{
}
void
OnAdd(core::ecs::EntityId entity) const override
{
ASSERT(reg);
ASSERT(!types.empty());
for(const auto& type: types)
{
const auto component = reg->GetComponent(entity, type);
const bool has_component = component != nullptr;
if(!has_component)
{
return;
}
}
auto result = func(entity);
ReportFirstError(result, duk, "init", name);
}
void
RegisterCallbacks(core::ecs::Systems* systems) override
{
systems->init.Add(this);
}
};
struct DukSystems
{
core::ecs::Systems* systems;
Sol* duk;
explicit DukSystems(core::ecs::Systems* s, Sol* d)
: systems(s)
, duk(d)
{
}
void
AddUpdate(const std::string& name, DukUpdateSystem::UpdateFunction func)
{
systems->AddAndRegister(std::make_shared<DukUpdateSystem>(name, duk, func));
}
void
AddInit
(
const std::string& name,
core::ecs::Registry* reg,
const std::vector<core::ecs::ComponentId>& types,
DukInitSystem::InitFunction func
)
{
systems->AddAndRegister(std::make_shared<DukInitSystem>(name, duk, reg, types, func));
}
};
struct DukIntegrationPimpl
{
DukIntegrationPimpl
(
core::ecs::Systems* sys,
core::ecs::World* world,
Sol* duk,
ObjectCreator* creator,
Components* components,
CameraData* cam
)
: systems(sys, duk)
, registry(&world->reg, components)
, input(duk->lua["Input"].get_or_create<sol::table>())
, world(world)
, creator(creator)
, components(components)
, camera(cam)
{
}
void
Integrate(Sol* duk)
{
auto systems_table = duk->lua["Systems"].get_or_create<sol::table>();
systems_table["AddUpdate"] = [&](const std::string& name, sol::function func)
{
systems.AddUpdate(name, func);
};
systems_table["OnInit"] = [&]
(
const std::string& name,
sol::table types,
sol::function func
)
{
auto vtypes = GetVector<core::ecs::ComponentId>(types);
systems.AddInit(name, &world->reg, vtypes, func);
};
auto math_table = duk->lua["Math"].get_or_create<sol::table>();
math_table["NewRandom"] = [&]() { return std::make_shared<core::Random>(); };
auto templates_table = duk->lua["Templates"].get_or_create<sol::table>();
templates_table["Find"] = [&](const std::string& name)
{
return creator->FindTemplate(name);
};
duk->lua.new_usertype<ObjectTemplate>("Template");
duk->lua["Template"]["Create"] = [&, duk](ObjectTemplate* t)
{
return t->CreateObject(ObjectCreationArgs{world, ®istry, duk, duk});
};
auto camera_table = duk->lua["Camera"].get_or_create<sol::table>();
camera_table["GetRect"] = [&]() { return &camera->screen; };
duk->lua.new_usertype<CustomArguments>
(
"CustomArguments",
"GetNumber", [](const CustomArguments& args, const std::string& name) -> float
{
const auto f = args.numbers.find(name);
if(f == args.numbers.end())
{
return 0;
}
else
{
return f->second;
}
}
);
auto registry_table = duk->lua["Registry"].get_or_create<sol::table>();
registry_table["Entities"] = [&](sol::table types)
{
return registry.EntityView(GetVector<core::ecs::ComponentId>(types));
};
registry_table["GetSpriteId"] = [&]()
{
return registry.components->sprite;
};
registry_table["DestroyEntity"] = [&](core::ecs::EntityId entity)
{
registry.DestroyEntity(entity);
};
registry_table["GetPosition2Id"] = [&]()
{
LOG_INFO("Getting position 2d");
return registry.components->position2;
};
registry_table["GetSpriteId"] = [&]()
{
return registry.components->sprite;
};
registry_table["New"] = sol::overload
(
[&](const std::string& name, sol::function setup)
{
return registry.CreateNewId(name, setup);
},
[&](const std::string& name)
{
return registry.CreateNewId(name);
}
);
registry_table["Get"] = [&](core::ecs::EntityId ent, core::ecs::ComponentId comp)
{
return registry.GetProperty(ent, comp);
};
registry_table["Set"] = [&](core::ecs::EntityId ent, core::ecs::ComponentId comp, sol::table val)
{
registry.SetProperty(ent, comp, val);
};
registry_table["GetSprite"] = [&](core::ecs::ComponentId ent)
{
return registry.GetComponentOrNull<CSprite>(ent, components->sprite);
};
registry_table["GetPosition2"] = [&](core::ecs::ComponentId ent)
{
return registry.GetComponentOrNull<CPosition2>(ent, components->position2);
};
registry_table["GetPosition2vec"] = [&](core::ecs::ComponentId ent)
{
auto c = registry.GetComponentOrNull<CPosition2>(ent, components->position2);
return c == nullptr ? nullptr : &c->pos;
};
duk->lua.new_usertype<CPosition2>("CPosition2", "vec", &CPosition2::pos);
duk->lua.new_usertype<CSprite>
(
"CSprite",
"GetRect", [](const CSprite& sp, const CPosition2& p)
{
return GetSpriteRect(p.pos, *sp.texture);
}
);
/*
duk->lua.new_usertype<Rectf>(
"Rectf",
sol::no_constructor,
"Contains",
&Rectf::ContainsExclusive,
"GetHeight",
&Rectf::GetHeight,
"GetWidth",
&Rectf::GetWidth);
*/
auto random_type = duk->lua.new_usertype<core::Random>("Random");
random_type["NextFloat01"] = &core::Random::NextFloat01;
random_type["NextRangeFloat"] = [](core::Random& r, float f) -> float
{
return r.NextRange(f);
};
random_type["NextBool"] = &core::Random::NextBool;
random_type["NextPoint2"] = [](core::Random& r, core::Rectf& rect) -> core::vec2f
{
return rect.RandomPoint(&r);
};
}
DukSystems systems;
DukRegistry registry;
sol::table input;
core::ecs::World* world;
ObjectCreator* creator;
Components* components;
CameraData* camera;
};
DukIntegration::DukIntegration
(
core::ecs::Systems* systems,
core::ecs::World* reg,
Sol* duk,
ObjectCreator* creator,
Components* components,
CameraData* camera
)
{
pimpl.reset
(
new DukIntegrationPimpl
(
systems,
reg,
duk,
creator,
components,
camera
)
);
pimpl->Integrate(duk);
}
DukIntegration::~DukIntegration()
{
Clear();
}
void
DukIntegration::Clear()
{
pimpl.reset();
}
DukRegistry&
DukIntegration::Registry()
{
ASSERT(pimpl);
return pimpl->registry;
}
void
DukIntegration::BindKeys(Sol* duk, const Input& input)
{
input.Set(&pimpl->input);
}
}
TYPEID_SETUP_TYPE(euphoria::core::Random);
TYPEID_SETUP_TYPE(euphoria::engine::ObjectTemplate);
TYPEID_SETUP_TYPE(euphoria::core::Rect<float>);
<|endoftext|> |
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/login/version_info_updater.h"
#include <string>
#include <vector>
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/chromeos/chromeos_version.h"
#include "base/string16.h"
#include "base/string_util.h"
#include "base/stringprintf.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/chromeos/cros/cros_library.h"
#include "chrome/browser/chromeos/cros_settings.h"
#include "chrome/browser/chromeos/cros_settings_names.h"
#include "chrome/browser/policy/browser_policy_connector.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/common/chrome_notification_types.h"
#include "chrome/common/chrome_version_info.h"
#include "googleurl/src/gurl.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#include "third_party/cros_system_api/window_manager/chromeos_wm_ipc_enums.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
namespace chromeos {
namespace {
const char* kReportingFlags[] = {
chromeos::kReportDeviceVersionInfo,
chromeos::kReportDeviceActivityTimes,
chromeos::kReportDeviceBootMode,
};
}
///////////////////////////////////////////////////////////////////////////////
// VersionInfoUpdater public:
VersionInfoUpdater::VersionInfoUpdater(Delegate* delegate)
: enterprise_reporting_hint_(false),
cros_settings_(chromeos::CrosSettings::Get()),
delegate_(delegate) {
}
VersionInfoUpdater::~VersionInfoUpdater() {
}
void VersionInfoUpdater::StartUpdate(bool is_official_build) {
if (base::chromeos::IsRunningOnChromeOS()) {
version_loader_.GetVersion(
&version_consumer_,
base::Bind(&VersionInfoUpdater::OnVersion, base::Unretained(this)),
is_official_build ?
VersionLoader::VERSION_SHORT_WITH_DATE :
VersionLoader::VERSION_FULL);
boot_times_loader_.GetBootTimes(
&boot_times_consumer_,
base::Bind(is_official_build ? &VersionInfoUpdater::OnBootTimesNoop :
&VersionInfoUpdater::OnBootTimes,
base::Unretained(this)));
} else {
UpdateVersionLabel();
}
policy::CloudPolicySubsystem* cloud_policy =
g_browser_process->browser_policy_connector()->
device_cloud_policy_subsystem();
if (cloud_policy) {
// Two-step reset because we want to construct new ObserverRegistrar after
// destruction of old ObserverRegistrar to avoid DCHECK violation because
// of adding existing observer.
cloud_policy_registrar_.reset();
cloud_policy_registrar_.reset(
new policy::CloudPolicySubsystem::ObserverRegistrar(
cloud_policy, this));
// Ensure that we have up-to-date enterprise info in case enterprise policy
// is already fetched and has finished initialization.
UpdateEnterpriseInfo();
}
// Watch for changes to the reporting flags.
for (unsigned int i = 0; i < arraysize(kReportingFlags); ++i)
cros_settings_->AddSettingsObserver(kReportingFlags[i], this);
}
void VersionInfoUpdater::UpdateVersionLabel() {
if (!base::chromeos::IsRunningOnChromeOS()) {
if (delegate_) {
delegate_->OnOSVersionLabelTextUpdated(
CrosLibrary::Get()->load_error_string());
}
return;
}
if (version_text_.empty())
return;
chrome::VersionInfo version_info;
std::string label_text = l10n_util::GetStringFUTF8(
IDS_LOGIN_VERSION_LABEL_FORMAT,
l10n_util::GetStringUTF16(IDS_PRODUCT_NAME),
UTF8ToUTF16(version_info.Version()),
UTF8ToUTF16(version_text_));
if (!enterprise_domain_text_.empty()) {
label_text += ' ';
if (enterprise_status_text_.empty()) {
label_text += l10n_util::GetStringFUTF8(
IDS_LOGIN_MANAGED_BY_LABEL_FORMAT,
UTF8ToUTF16(enterprise_domain_text_));
} else {
label_text += l10n_util::GetStringFUTF8(
IDS_LOGIN_MANAGED_BY_WITH_STATUS_LABEL_FORMAT,
UTF8ToUTF16(enterprise_domain_text_),
UTF8ToUTF16(enterprise_status_text_));
}
}
// Workaround over incorrect width calculation in old fonts.
// TODO(glotov): remove the following line when new fonts are used.
label_text += ' ';
if (delegate_)
delegate_->OnOSVersionLabelTextUpdated(label_text);
}
void VersionInfoUpdater::UpdateEnterpriseInfo() {
policy::BrowserPolicyConnector* policy_connector =
g_browser_process->browser_policy_connector();
std::string status_text;
policy::CloudPolicySubsystem* cloud_policy_subsystem =
policy_connector->device_cloud_policy_subsystem();
if (cloud_policy_subsystem) {
switch (cloud_policy_subsystem->state()) {
case policy::CloudPolicySubsystem::UNENROLLED:
status_text = l10n_util::GetStringUTF8(
IDS_LOGIN_MANAGED_BY_STATUS_PENDING);
break;
case policy::CloudPolicySubsystem::UNMANAGED:
case policy::CloudPolicySubsystem::BAD_GAIA_TOKEN:
case policy::CloudPolicySubsystem::LOCAL_ERROR:
status_text = l10n_util::GetStringUTF8(
IDS_LOGIN_MANAGED_BY_STATUS_LOST_CONNECTION);
break;
case policy::CloudPolicySubsystem::NETWORK_ERROR:
status_text = l10n_util::GetStringUTF8(
IDS_LOGIN_MANAGED_BY_STATUS_NETWORK_ERROR);
break;
case policy::CloudPolicySubsystem::TOKEN_FETCHED:
case policy::CloudPolicySubsystem::SUCCESS:
break;
}
}
bool reporting_hint = false;
for (unsigned int i = 0; i < arraysize(kReportingFlags); ++i) {
bool enabled = false;
if (cros_settings_->GetBoolean(kReportingFlags[i], &enabled) && enabled) {
reporting_hint = true;
break;
}
}
SetEnterpriseInfo(policy_connector->GetEnterpriseDomain(),
status_text,
reporting_hint);
}
void VersionInfoUpdater::SetEnterpriseInfo(const std::string& domain_name,
const std::string& status_text,
bool reporting_hint) {
if (domain_name != enterprise_domain_text_ ||
status_text != enterprise_status_text_ ||
reporting_hint != enterprise_reporting_hint_) {
enterprise_domain_text_ = domain_name;
enterprise_status_text_ = status_text;
enterprise_reporting_hint_ = enterprise_reporting_hint_;
UpdateVersionLabel();
// Update the notification about device status reporting.
if (delegate_) {
std::string enterprise_info;
if (!domain_name.empty()) {
enterprise_info = l10n_util::GetStringFUTF8(
IDS_LOGIN_MANAGED_BY_NOTICE,
UTF8ToUTF16(enterprise_domain_text_));
delegate_->OnEnterpriseInfoUpdated(enterprise_info, reporting_hint);
}
}
}
}
void VersionInfoUpdater::OnVersion(
VersionLoader::Handle handle, std::string version) {
version_text_.swap(version);
UpdateVersionLabel();
}
void VersionInfoUpdater::OnBootTimesNoop(
BootTimesLoader::Handle handle, BootTimesLoader::BootTimes boot_times) {
}
void VersionInfoUpdater::OnBootTimes(
BootTimesLoader::Handle handle, BootTimesLoader::BootTimes boot_times) {
const char* kBootTimesNoChromeExec =
"Non-firmware boot took %.2f seconds (kernel %.2fs, system %.2fs)";
const char* kBootTimesChromeExec =
"Non-firmware boot took %.2f seconds "
"(kernel %.2fs, system %.2fs, chrome %.2fs)";
std::string boot_times_text;
if (boot_times.chrome > 0) {
boot_times_text =
base::StringPrintf(
kBootTimesChromeExec,
boot_times.total,
boot_times.pre_startup,
boot_times.system,
boot_times.chrome);
} else {
boot_times_text =
base::StringPrintf(
kBootTimesNoChromeExec,
boot_times.total,
boot_times.pre_startup,
boot_times.system);
}
// Use UTF8ToWide once this string is localized.
if (delegate_)
delegate_->OnBootTimesLabelTextUpdated(boot_times_text);
}
void VersionInfoUpdater::OnPolicyStateChanged(
policy::CloudPolicySubsystem::PolicySubsystemState state,
policy::CloudPolicySubsystem::ErrorDetails error_details) {
UpdateEnterpriseInfo();
}
void VersionInfoUpdater::Observe(
int type,
const content::NotificationSource& source,
const content::NotificationDetails& details) {
if (type == chrome::NOTIFICATION_SYSTEM_SETTING_CHANGED)
UpdateEnterpriseInfo();
else
NOTREACHED();
}
} // namespace chromeos
<commit_msg>CrOS: Fix assign-to-self.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/login/version_info_updater.h"
#include <string>
#include <vector>
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/chromeos/chromeos_version.h"
#include "base/string16.h"
#include "base/string_util.h"
#include "base/stringprintf.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/chromeos/cros/cros_library.h"
#include "chrome/browser/chromeos/cros_settings.h"
#include "chrome/browser/chromeos/cros_settings_names.h"
#include "chrome/browser/policy/browser_policy_connector.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/common/chrome_notification_types.h"
#include "chrome/common/chrome_version_info.h"
#include "googleurl/src/gurl.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#include "third_party/cros_system_api/window_manager/chromeos_wm_ipc_enums.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
namespace chromeos {
namespace {
const char* kReportingFlags[] = {
chromeos::kReportDeviceVersionInfo,
chromeos::kReportDeviceActivityTimes,
chromeos::kReportDeviceBootMode,
};
}
///////////////////////////////////////////////////////////////////////////////
// VersionInfoUpdater public:
VersionInfoUpdater::VersionInfoUpdater(Delegate* delegate)
: enterprise_reporting_hint_(false),
cros_settings_(chromeos::CrosSettings::Get()),
delegate_(delegate) {
}
VersionInfoUpdater::~VersionInfoUpdater() {
}
void VersionInfoUpdater::StartUpdate(bool is_official_build) {
if (base::chromeos::IsRunningOnChromeOS()) {
version_loader_.GetVersion(
&version_consumer_,
base::Bind(&VersionInfoUpdater::OnVersion, base::Unretained(this)),
is_official_build ?
VersionLoader::VERSION_SHORT_WITH_DATE :
VersionLoader::VERSION_FULL);
boot_times_loader_.GetBootTimes(
&boot_times_consumer_,
base::Bind(is_official_build ? &VersionInfoUpdater::OnBootTimesNoop :
&VersionInfoUpdater::OnBootTimes,
base::Unretained(this)));
} else {
UpdateVersionLabel();
}
policy::CloudPolicySubsystem* cloud_policy =
g_browser_process->browser_policy_connector()->
device_cloud_policy_subsystem();
if (cloud_policy) {
// Two-step reset because we want to construct new ObserverRegistrar after
// destruction of old ObserverRegistrar to avoid DCHECK violation because
// of adding existing observer.
cloud_policy_registrar_.reset();
cloud_policy_registrar_.reset(
new policy::CloudPolicySubsystem::ObserverRegistrar(
cloud_policy, this));
// Ensure that we have up-to-date enterprise info in case enterprise policy
// is already fetched and has finished initialization.
UpdateEnterpriseInfo();
}
// Watch for changes to the reporting flags.
for (unsigned int i = 0; i < arraysize(kReportingFlags); ++i)
cros_settings_->AddSettingsObserver(kReportingFlags[i], this);
}
void VersionInfoUpdater::UpdateVersionLabel() {
if (!base::chromeos::IsRunningOnChromeOS()) {
if (delegate_) {
delegate_->OnOSVersionLabelTextUpdated(
CrosLibrary::Get()->load_error_string());
}
return;
}
if (version_text_.empty())
return;
chrome::VersionInfo version_info;
std::string label_text = l10n_util::GetStringFUTF8(
IDS_LOGIN_VERSION_LABEL_FORMAT,
l10n_util::GetStringUTF16(IDS_PRODUCT_NAME),
UTF8ToUTF16(version_info.Version()),
UTF8ToUTF16(version_text_));
if (!enterprise_domain_text_.empty()) {
label_text += ' ';
if (enterprise_status_text_.empty()) {
label_text += l10n_util::GetStringFUTF8(
IDS_LOGIN_MANAGED_BY_LABEL_FORMAT,
UTF8ToUTF16(enterprise_domain_text_));
} else {
label_text += l10n_util::GetStringFUTF8(
IDS_LOGIN_MANAGED_BY_WITH_STATUS_LABEL_FORMAT,
UTF8ToUTF16(enterprise_domain_text_),
UTF8ToUTF16(enterprise_status_text_));
}
}
// Workaround over incorrect width calculation in old fonts.
// TODO(glotov): remove the following line when new fonts are used.
label_text += ' ';
if (delegate_)
delegate_->OnOSVersionLabelTextUpdated(label_text);
}
void VersionInfoUpdater::UpdateEnterpriseInfo() {
policy::BrowserPolicyConnector* policy_connector =
g_browser_process->browser_policy_connector();
std::string status_text;
policy::CloudPolicySubsystem* cloud_policy_subsystem =
policy_connector->device_cloud_policy_subsystem();
if (cloud_policy_subsystem) {
switch (cloud_policy_subsystem->state()) {
case policy::CloudPolicySubsystem::UNENROLLED:
status_text = l10n_util::GetStringUTF8(
IDS_LOGIN_MANAGED_BY_STATUS_PENDING);
break;
case policy::CloudPolicySubsystem::UNMANAGED:
case policy::CloudPolicySubsystem::BAD_GAIA_TOKEN:
case policy::CloudPolicySubsystem::LOCAL_ERROR:
status_text = l10n_util::GetStringUTF8(
IDS_LOGIN_MANAGED_BY_STATUS_LOST_CONNECTION);
break;
case policy::CloudPolicySubsystem::NETWORK_ERROR:
status_text = l10n_util::GetStringUTF8(
IDS_LOGIN_MANAGED_BY_STATUS_NETWORK_ERROR);
break;
case policy::CloudPolicySubsystem::TOKEN_FETCHED:
case policy::CloudPolicySubsystem::SUCCESS:
break;
}
}
bool reporting_hint = false;
for (unsigned int i = 0; i < arraysize(kReportingFlags); ++i) {
bool enabled = false;
if (cros_settings_->GetBoolean(kReportingFlags[i], &enabled) && enabled) {
reporting_hint = true;
break;
}
}
SetEnterpriseInfo(policy_connector->GetEnterpriseDomain(),
status_text,
reporting_hint);
}
void VersionInfoUpdater::SetEnterpriseInfo(const std::string& domain_name,
const std::string& status_text,
bool reporting_hint) {
if (domain_name != enterprise_domain_text_ ||
status_text != enterprise_status_text_ ||
reporting_hint != enterprise_reporting_hint_) {
enterprise_domain_text_ = domain_name;
enterprise_status_text_ = status_text;
enterprise_reporting_hint_ = reporting_hint;
UpdateVersionLabel();
// Update the notification about device status reporting.
if (delegate_) {
std::string enterprise_info;
if (!domain_name.empty()) {
enterprise_info = l10n_util::GetStringFUTF8(
IDS_LOGIN_MANAGED_BY_NOTICE,
UTF8ToUTF16(enterprise_domain_text_));
delegate_->OnEnterpriseInfoUpdated(enterprise_info, reporting_hint);
}
}
}
}
void VersionInfoUpdater::OnVersion(
VersionLoader::Handle handle, std::string version) {
version_text_.swap(version);
UpdateVersionLabel();
}
void VersionInfoUpdater::OnBootTimesNoop(
BootTimesLoader::Handle handle, BootTimesLoader::BootTimes boot_times) {
}
void VersionInfoUpdater::OnBootTimes(
BootTimesLoader::Handle handle, BootTimesLoader::BootTimes boot_times) {
const char* kBootTimesNoChromeExec =
"Non-firmware boot took %.2f seconds (kernel %.2fs, system %.2fs)";
const char* kBootTimesChromeExec =
"Non-firmware boot took %.2f seconds "
"(kernel %.2fs, system %.2fs, chrome %.2fs)";
std::string boot_times_text;
if (boot_times.chrome > 0) {
boot_times_text =
base::StringPrintf(
kBootTimesChromeExec,
boot_times.total,
boot_times.pre_startup,
boot_times.system,
boot_times.chrome);
} else {
boot_times_text =
base::StringPrintf(
kBootTimesNoChromeExec,
boot_times.total,
boot_times.pre_startup,
boot_times.system);
}
// Use UTF8ToWide once this string is localized.
if (delegate_)
delegate_->OnBootTimesLabelTextUpdated(boot_times_text);
}
void VersionInfoUpdater::OnPolicyStateChanged(
policy::CloudPolicySubsystem::PolicySubsystemState state,
policy::CloudPolicySubsystem::ErrorDetails error_details) {
UpdateEnterpriseInfo();
}
void VersionInfoUpdater::Observe(
int type,
const content::NotificationSource& source,
const content::NotificationDetails& details) {
if (type == chrome::NOTIFICATION_SYSTEM_SETTING_CHANGED)
UpdateEnterpriseInfo();
else
NOTREACHED();
}
} // namespace chromeos
<|endoftext|> |
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/importer/firefox_importer_utils.h"
#include <shlobj.h>
#include "base/file_util.h"
#include "base/registry.h"
// NOTE: Keep these in order since we need test all those paths according
// to priority. For example. One machine has multiple users. One non-admin
// user installs Firefox 2, which causes there is a Firefox2 entry under HKCU.
// One admin user installs Firefox 3, which causes there is a Firefox 3 entry
// under HKLM. So when the non-admin user log in, we should deal with Firefox 2
// related data instead of Firefox 3.
static const HKEY kFireFoxRegistryPaths[] = {
HKEY_CURRENT_USER,
HKEY_LOCAL_MACHINE
};
int GetCurrentFirefoxMajorVersionFromRegistry() {
TCHAR ver_buffer[128];
DWORD ver_buffer_length = sizeof(ver_buffer);
int highest_version = 0;
// When installing Firefox with admin account, the product keys will be
// written under HKLM\Mozilla. Otherwise it the keys will be written under
// HKCU\Mozilla.
for (int i = 0; i < arraysize(kFireFoxRegistryPaths); ++i) {
RegKey reg_key(kFireFoxRegistryPaths[i],
L"Software\\Mozilla\\Mozilla Firefox");
bool result = reg_key.ReadValue(L"CurrentVersion", ver_buffer,
&ver_buffer_length, NULL);
if (!result)
continue;
highest_version = std::max(highest_version, _wtoi(ver_buffer));
}
return highest_version;
}
std::wstring GetFirefoxInstallPathFromRegistry() {
// Detects the path that Firefox is installed in.
std::wstring registry_path = L"Software\\Mozilla\\Mozilla Firefox";
TCHAR buffer[MAX_PATH];
DWORD buffer_length = sizeof(buffer);
RegKey reg_key(HKEY_LOCAL_MACHINE, registry_path.c_str());
bool result = reg_key.ReadValue(L"CurrentVersion", buffer,
&buffer_length, NULL);
if (!result)
return std::wstring();
registry_path += L"\\" + std::wstring(buffer) + L"\\Main";
buffer_length = sizeof(buffer);
reg_key = RegKey(HKEY_LOCAL_MACHINE, registry_path.c_str());
result = reg_key.ReadValue(L"Install Directory", buffer,
&buffer_length, NULL);
if (!result)
return std::wstring();
return buffer;
}
FilePath GetProfilesINI() {
FilePath ini_file;
// The default location of the profile folder containing user data is
// under the "Application Data" folder in Windows XP.
wchar_t buffer[MAX_PATH] = {0};
if (SUCCEEDED(SHGetFolderPath(NULL, CSIDL_APPDATA, NULL,
SHGFP_TYPE_CURRENT, buffer))) {
ini_file = FilePath(buffer).Append(L"Mozilla\\Firefox\\profiles.ini");
}
if (file_util::PathExists(ini_file))
return ini_file;
return FilePath();
}
<commit_msg>Reusing the RegKey used to get the CurrentVersion to also get the Install Directory was causing an InvalidHandle exception, and causing FF import to fail.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/importer/firefox_importer_utils.h"
#include <shlobj.h>
#include "base/file_util.h"
#include "base/registry.h"
// NOTE: Keep these in order since we need test all those paths according
// to priority. For example. One machine has multiple users. One non-admin
// user installs Firefox 2, which causes there is a Firefox2 entry under HKCU.
// One admin user installs Firefox 3, which causes there is a Firefox 3 entry
// under HKLM. So when the non-admin user log in, we should deal with Firefox 2
// related data instead of Firefox 3.
static const HKEY kFireFoxRegistryPaths[] = {
HKEY_CURRENT_USER,
HKEY_LOCAL_MACHINE
};
int GetCurrentFirefoxMajorVersionFromRegistry() {
TCHAR ver_buffer[128];
DWORD ver_buffer_length = sizeof(ver_buffer);
int highest_version = 0;
// When installing Firefox with admin account, the product keys will be
// written under HKLM\Mozilla. Otherwise it the keys will be written under
// HKCU\Mozilla.
for (int i = 0; i < arraysize(kFireFoxRegistryPaths); ++i) {
RegKey reg_key(kFireFoxRegistryPaths[i],
L"Software\\Mozilla\\Mozilla Firefox");
bool result = reg_key.ReadValue(L"CurrentVersion", ver_buffer,
&ver_buffer_length, NULL);
if (!result)
continue;
highest_version = std::max(highest_version, _wtoi(ver_buffer));
}
return highest_version;
}
std::wstring GetFirefoxInstallPathFromRegistry() {
// Detects the path that Firefox is installed in.
std::wstring registry_path = L"Software\\Mozilla\\Mozilla Firefox";
TCHAR buffer[MAX_PATH];
DWORD buffer_length = sizeof(buffer);
RegKey reg_key(HKEY_LOCAL_MACHINE, registry_path.c_str());
bool result = reg_key.ReadValue(L"CurrentVersion", buffer,
&buffer_length, NULL);
if (!result)
return std::wstring();
registry_path += L"\\" + std::wstring(buffer) + L"\\Main";
buffer_length = sizeof(buffer);
RegKey reg_key_directory = RegKey(HKEY_LOCAL_MACHINE, registry_path.c_str());
result = reg_key_directory.ReadValue(L"Install Directory", buffer,
&buffer_length, NULL);
if (!result)
return std::wstring();
return buffer;
}
FilePath GetProfilesINI() {
FilePath ini_file;
// The default location of the profile folder containing user data is
// under the "Application Data" folder in Windows XP.
wchar_t buffer[MAX_PATH] = {0};
if (SUCCEEDED(SHGetFolderPath(NULL, CSIDL_APPDATA, NULL,
SHGFP_TYPE_CURRENT, buffer))) {
ini_file = FilePath(buffer).Append(L"Mozilla\\Firefox\\profiles.ini");
}
if (file_util::PathExists(ini_file))
return ini_file;
return FilePath();
}
<|endoftext|> |
<commit_before>/****************************************************************************
*
* Copyright (c) 2013-2015 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 land_detector_main.cpp
* Land detection algorithm
*
* @author Johan Jansen <jnsn.johan@gmail.com>
*/
#include <px4_config.h>
#include <px4_defines.h>
#include <px4_tasks.h>
#include <px4_posix.h>
#include <unistd.h> //usleep
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <drivers/drv_hrt.h>
#include <systemlib/systemlib.h> //Scheduler
#include <systemlib/err.h> //print to console
#include "FixedwingLandDetector.h"
#include "MulticopterLandDetector.h"
//Function prototypes
static int land_detector_start(const char *mode);
static void land_detector_stop();
/**
* land detector app start / stop handling function
* This makes the land detector module accessible from the nuttx shell
* @ingroup apps
*/
extern "C" __EXPORT int land_detector_main(int argc, char *argv[]);
//Private variables
static LandDetector *land_detector_task = nullptr;
static int _landDetectorTaskID = -1;
static char _currentMode[12];
/**
* Deamon thread function
**/
static void land_detector_deamon_thread(int argc, char *argv[])
{
land_detector_task->start();
}
/**
* Stop the task, force killing it if it doesn't stop by itself
**/
static void land_detector_stop()
{
if (land_detector_task == nullptr || _landDetectorTaskID == -1) {
warnx("not running");
return;
}
land_detector_task->shutdown();
//Wait for task to die
int i = 0;
do {
/* wait 20ms */
usleep(20000);
/* if we have given up, kill it */
if (++i > 50) {
px4_task_delete(_landDetectorTaskID);
break;
}
} while (land_detector_task->isRunning());
delete land_detector_task;
land_detector_task = nullptr;
_landDetectorTaskID = -1;
warnx("land_detector has been stopped");
}
/**
* Start new task, fails if it is already running. Returns OK if successful
**/
static int land_detector_start(const char *mode)
{
if (land_detector_task != nullptr || _landDetectorTaskID != -1) {
warnx("already running");
return -1;
}
//Allocate memory
if (!strcmp(mode, "fixedwing")) {
land_detector_task = new FixedwingLandDetector();
} else if (!strcmp(mode, "multicopter")) {
land_detector_task = new MulticopterLandDetector();
} else {
warnx("[mode] must be either 'fixedwing' or 'multicopter'");
return -1;
}
//Check if alloc worked
if (land_detector_task == nullptr) {
warnx("alloc failed");
return -1;
}
//Start new thread task
_landDetectorTaskID = px4_task_spawn_cmd("land_detector",
SCHED_DEFAULT,
SCHED_PRIORITY_DEFAULT,
1000,
(px4_main_t)&land_detector_deamon_thread,
nullptr);
if (_landDetectorTaskID < 0) {
warnx("task start failed: %d", -errno);
return -1;
}
/* avoid memory fragmentation by not exiting start handler until the task has fully started */
const uint32_t timeout = hrt_absolute_time() + 5000000; //5 second timeout
/* avoid printing dots just yet and do one sleep before the first check */
usleep(10000);
/* check if the waiting involving dots and a newline are still needed */
if (!land_detector_task->isRunning()) {
while (!land_detector_task->isRunning()) {
printf(".");
fflush(stdout);
usleep(50000);
if (hrt_absolute_time() > timeout) {
warnx("start failed - timeout");
land_detector_stop();
return 1;
}
}
printf("\n");
}
//Remember current active mode
strncpy(_currentMode, mode, 12);
return 0;
}
/**
* Main entry point for this module
**/
int land_detector_main(int argc, char *argv[])
{
if (argc < 2) {
goto exiterr;
}
if (argc >= 2 && !strcmp(argv[1], "start")) {
if (land_detector_start(argv[2]) != 0) {
warnx("land_detector start failed");
return 1;
}
}
if (!strcmp(argv[1], "stop")) {
land_detector_stop();
return 0;
}
if (!strcmp(argv[1], "status")) {
if (land_detector_task) {
if (land_detector_task->isRunning()) {
warnx("running (%s): %s", _currentMode, (land_detector_task->isLanded()) ? "LANDED" : "IN AIR");
} else {
warnx("exists, but not running (%s)", _currentMode);
}
return 0;
} else {
warnx("not running");
return 1;
}
}
exiterr:
warnx("usage: land_detector {start|stop|status} [mode]");
warnx("mode can either be 'fixedwing' or 'multicopter'");
return 1;
}
<commit_msg>land_detector: shut up if started correctly<commit_after>/****************************************************************************
*
* Copyright (c) 2013-2015 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 land_detector_main.cpp
* Land detection algorithm
*
* @author Johan Jansen <jnsn.johan@gmail.com>
*/
#include <px4_config.h>
#include <px4_defines.h>
#include <px4_tasks.h>
#include <px4_posix.h>
#include <unistd.h> //usleep
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <drivers/drv_hrt.h>
#include <systemlib/systemlib.h> //Scheduler
#include <systemlib/err.h> //print to console
#include "FixedwingLandDetector.h"
#include "MulticopterLandDetector.h"
//Function prototypes
static int land_detector_start(const char *mode);
static void land_detector_stop();
/**
* land detector app start / stop handling function
* This makes the land detector module accessible from the nuttx shell
* @ingroup apps
*/
extern "C" __EXPORT int land_detector_main(int argc, char *argv[]);
//Private variables
static LandDetector *land_detector_task = nullptr;
static int _landDetectorTaskID = -1;
static char _currentMode[12];
/**
* Deamon thread function
**/
static void land_detector_deamon_thread(int argc, char *argv[])
{
land_detector_task->start();
}
/**
* Stop the task, force killing it if it doesn't stop by itself
**/
static void land_detector_stop()
{
if (land_detector_task == nullptr || _landDetectorTaskID == -1) {
warnx("not running");
return;
}
land_detector_task->shutdown();
//Wait for task to die
int i = 0;
do {
/* wait 20ms */
usleep(20000);
/* if we have given up, kill it */
if (++i > 50) {
px4_task_delete(_landDetectorTaskID);
break;
}
} while (land_detector_task->isRunning());
delete land_detector_task;
land_detector_task = nullptr;
_landDetectorTaskID = -1;
warnx("land_detector has been stopped");
}
/**
* Start new task, fails if it is already running. Returns OK if successful
**/
static int land_detector_start(const char *mode)
{
if (land_detector_task != nullptr || _landDetectorTaskID != -1) {
warnx("already running");
return -1;
}
//Allocate memory
if (!strcmp(mode, "fixedwing")) {
land_detector_task = new FixedwingLandDetector();
} else if (!strcmp(mode, "multicopter")) {
land_detector_task = new MulticopterLandDetector();
} else {
warnx("[mode] must be either 'fixedwing' or 'multicopter'");
return -1;
}
//Check if alloc worked
if (land_detector_task == nullptr) {
warnx("alloc failed");
return -1;
}
//Start new thread task
_landDetectorTaskID = px4_task_spawn_cmd("land_detector",
SCHED_DEFAULT,
SCHED_PRIORITY_DEFAULT,
1000,
(px4_main_t)&land_detector_deamon_thread,
nullptr);
if (_landDetectorTaskID < 0) {
warnx("task start failed: %d", -errno);
return -1;
}
/* avoid memory fragmentation by not exiting start handler until the task has fully started */
const uint32_t timeout = hrt_absolute_time() + 5000000; //5 second timeout
/* avoid printing dots just yet and do one sleep before the first check */
usleep(10000);
/* check if the waiting involving dots and a newline are still needed */
if (!land_detector_task->isRunning()) {
while (!land_detector_task->isRunning()) {
printf(".");
fflush(stdout);
usleep(50000);
if (hrt_absolute_time() > timeout) {
warnx("start failed - timeout");
land_detector_stop();
return 1;
}
}
printf("\n");
}
//Remember current active mode
strncpy(_currentMode, mode, 12);
return 0;
}
/**
* Main entry point for this module
**/
int land_detector_main(int argc, char *argv[])
{
if (argc < 2) {
goto exiterr;
}
if (argc >= 2 && !strcmp(argv[1], "start")) {
if (land_detector_start(argv[2]) != 0) {
warnx("land_detector start failed");
return 1;
}
return 0;
}
if (!strcmp(argv[1], "stop")) {
land_detector_stop();
return 0;
}
if (!strcmp(argv[1], "status")) {
if (land_detector_task) {
if (land_detector_task->isRunning()) {
warnx("running (%s): %s", _currentMode, (land_detector_task->isLanded()) ? "LANDED" : "IN AIR");
} else {
warnx("exists, but not running (%s)", _currentMode);
}
return 0;
} else {
warnx("not running");
return 1;
}
}
exiterr:
warnx("usage: land_detector {start|stop|status} [mode]");
warnx("mode can either be 'fixedwing' or 'multicopter'");
return 1;
}
<|endoftext|> |
<commit_before>/*********************************************************************************
*
* Inviwo - Interactive Visualization Workshop
*
* Copyright (c) 2022 Inviwo Foundation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*********************************************************************************/
#include <inviwo/dataframe/properties/filterlistproperty.h>
#include <inviwo/core/properties/boolcompositeproperty.h>
#include <inviwo/core/properties/stringproperty.h>
#include <inviwo/core/properties/boolproperty.h>
#include <inviwo/core/properties/ordinalproperty.h>
#include <inviwo/core/properties/minmaxproperty.h>
#include <inviwo/core/properties/optionproperty.h>
#include <inviwo/dataframe/util/filters.h>
#include <limits>
#include <regex>
#include <functional>
#include <algorithm>
namespace inviwo {
const std::string FilterListProperty::classIdentifier = "org.inviwo.FilterListProperty";
std::string FilterListProperty::getClassIdentifier() const { return classIdentifier; }
FilterListProperty::FilterListProperty(std::string_view identifier, std::string_view displayName,
bool supportsFilterOnHeader, FilterTypes supportedFilters,
size_t maxNumberOfElements, ListPropertyUIFlags uiFlags,
InvalidationLevel invalidationLevel,
PropertySemantics semantics)
: ListProperty(identifier, displayName, maxNumberOfElements, uiFlags, invalidationLevel,
semantics) {
auto onHeaderProp = [enable = supportsFilterOnHeader]() {
auto p = std::make_unique<BoolProperty>("filterOnHeader", "Filter on Header", enable);
p->setVisible(enable);
return p;
};
if (supportedFilters.contains(FilterType::Rows)) {
{
auto emptyLines =
std::make_unique<BoolCompositeProperty>("emptyLines", "Empty Lines", true);
emptyLines->addProperty(onHeaderProp());
addPrefab(std::move(emptyLines));
}
{
auto rowBegin = std::make_unique<BoolCompositeProperty>("rowBegin", "Row Begin", true);
rowBegin->addProperty(onHeaderProp());
rowBegin->addProperty(std::make_unique<StringProperty>("match", "Matching String", ""));
addPrefab(std::move(rowBegin));
}
{
auto lineRange =
std::make_unique<BoolCompositeProperty>("lineRange", "Line Range", true);
lineRange->addProperty(onHeaderProp());
lineRange->addProperty(std::make_unique<IntMinMaxProperty>(
"range", "Line Range", 0, 100, 0, std::numeric_limits<int>::max(), 1, 0,
InvalidationLevel::InvalidOutput, PropertySemantics::Text));
addPrefab(std::move(lineRange));
}
}
auto columnProp = []() {
return std::make_unique<IntProperty>(
"column", "Column", 0, 0, std::numeric_limits<int>::max(), 1,
InvalidationLevel::InvalidOutput, PropertySemantics::Text);
};
if (supportedFilters.contains(FilterType::StringItem)) {
auto stringItem =
std::make_unique<BoolCompositeProperty>("stringItem", "String Match", true);
stringItem->addProperty(columnProp());
stringItem->addProperty(std::make_unique<TemplateOptionProperty<filters::StringComp>>(
"comp", "Comparison",
std::vector<OptionPropertyOption<filters::StringComp>>{
{"equal", "equal (==)", filters::StringComp::Equal},
{"notEqual", "Not Equal (!=)", filters::StringComp::NotEqual},
{"regex", "Regex", filters::StringComp::Regex},
{"regexPartial", "Regex (Partial)", filters::StringComp::RegexPartial}},
0));
stringItem->addProperty(std::make_unique<StringProperty>("match", "Matching String", ""));
addPrefab(std::move(stringItem));
}
if (supportedFilters.contains(FilterType::IntItem)) {
auto intItem =
std::make_unique<BoolCompositeProperty>("intItem", "Integer Comparison", true);
intItem->addProperty(columnProp());
intItem->addProperty(std::make_unique<TemplateOptionProperty<filters::NumberComp>>(
"comp", "Comparison",
std::vector<OptionPropertyOption<filters::NumberComp>>{
{"equal", "equal (==)", filters::NumberComp::Equal},
{"notEqual", "Not Equal (!=)", filters::NumberComp::NotEqual},
{"less", "Less (<)", filters::NumberComp::Less},
{"lessEqual", "Less Equal (<=)", filters::NumberComp::LessEqual},
{"greater", "greater (>)", filters::NumberComp::Greater},
{"greaterEqual", "Greater Equal (>=)", filters::NumberComp::GreaterEqual}},
0));
intItem->addProperty(std::make_unique<Int64Property>(
"value", "Value", 0, std::numeric_limits<int64_t>::min(),
std::numeric_limits<int64_t>::max(), 1, InvalidationLevel::InvalidOutput,
PropertySemantics::Text));
addPrefab(std::move(intItem));
}
if (supportedFilters.contains(FilterType::DoubleItem)) {
auto doubleItem =
std::make_unique<BoolCompositeProperty>("doubleItem", "Double Comparison", true);
doubleItem->addProperty(columnProp());
doubleItem->addProperty(std::make_unique<TemplateOptionProperty<filters::NumberComp>>(
"comp", "Comparison",
std::vector<OptionPropertyOption<filters::NumberComp>>{
{"equal", "equal (==)", filters::NumberComp::Equal},
{"notEqual", "Not Equal (!=)", filters::NumberComp::NotEqual},
{"less", "Less (<)", filters::NumberComp::Less},
{"lessEqual", "Less Equal (<=)", filters::NumberComp::LessEqual},
{"greater", "greater (>)", filters::NumberComp::Greater},
{"greaterEqual", "Greater Equal (>=)", filters::NumberComp::GreaterEqual}},
0));
doubleItem->addProperty(std::make_unique<DoubleProperty>(
"value", "Value", 0.0, std::numeric_limits<double>::lowest(),
std::numeric_limits<double>::max(), 0.1, InvalidationLevel::InvalidOutput,
PropertySemantics::Text));
doubleItem->addProperty(std::make_unique<DoubleProperty>(
"epsilon", "Epsilon", 0.0, 0.0, std::numeric_limits<double>::max(), 0.1,
InvalidationLevel::InvalidOutput, PropertySemantics::Text));
addPrefab(std::move(doubleItem));
}
if (supportedFilters.contains(FilterType::IntRange)) {
auto intRange = std::make_unique<BoolCompositeProperty>("intRangeItem", "Int Range", true);
intRange->addProperty(columnProp());
intRange->addProperty(std::make_unique<Int64MinMaxProperty>(
"range", "Integer Range", 0, 100, std::numeric_limits<int64_t>::min(),
std::numeric_limits<int64_t>::max(), 1, 0, InvalidationLevel::InvalidOutput,
PropertySemantics::Text));
addPrefab(std::move(intRange));
}
if (supportedFilters.contains(FilterType::DoubleRange)) {
auto doubleRange =
std::make_unique<BoolCompositeProperty>("doubleRangeItem", "Double Range", true);
doubleRange->addProperty(columnProp());
doubleRange->addProperty(std::make_unique<DoubleMinMaxProperty>(
"range", "Double Range", 0.0, 100.0, std::numeric_limits<double>::min(),
std::numeric_limits<double>::max(), 0.1, 0.0, InvalidationLevel::InvalidOutput,
PropertySemantics::Text));
addPrefab(std::move(doubleRange));
}
}
FilterListProperty* FilterListProperty::clone() const { return new FilterListProperty(*this); }
} // namespace inviwo
<commit_msg>DataFrame: FilterListProperty serialization fix<commit_after>/*********************************************************************************
*
* Inviwo - Interactive Visualization Workshop
*
* Copyright (c) 2022 Inviwo Foundation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*********************************************************************************/
#include <inviwo/dataframe/properties/filterlistproperty.h>
#include <inviwo/core/properties/boolcompositeproperty.h>
#include <inviwo/core/properties/stringproperty.h>
#include <inviwo/core/properties/boolproperty.h>
#include <inviwo/core/properties/ordinalproperty.h>
#include <inviwo/core/properties/minmaxproperty.h>
#include <inviwo/core/properties/optionproperty.h>
#include <inviwo/dataframe/util/filters.h>
#include <limits>
#include <regex>
#include <functional>
#include <algorithm>
namespace inviwo {
const std::string FilterListProperty::classIdentifier = "org.inviwo.FilterListProperty";
std::string FilterListProperty::getClassIdentifier() const { return classIdentifier; }
FilterListProperty::FilterListProperty(std::string_view identifier, std::string_view displayName,
bool supportsFilterOnHeader, FilterTypes supportedFilters,
size_t maxNumberOfElements, ListPropertyUIFlags uiFlags,
InvalidationLevel invalidationLevel,
PropertySemantics semantics)
: ListProperty(identifier, displayName, maxNumberOfElements, uiFlags, invalidationLevel,
semantics) {
auto onHeaderProp = [enable = supportsFilterOnHeader]() {
auto p = std::make_unique<BoolProperty>("filterOnHeader", "Filter on Header", enable);
p->setVisible(enable);
return p;
};
auto createBoolComposite = [](std::string_view identifier, std::string_view displayName) {
auto p = std::make_unique<BoolCompositeProperty>(identifier, displayName, true);
p->getBoolProperty()->setSerializationMode(PropertySerializationMode::All);
return p;
};
if (supportedFilters.contains(FilterType::Rows)) {
{
auto emptyLines = createBoolComposite("emptyLines", "Empty Lines");
emptyLines->addProperty(onHeaderProp());
addPrefab(std::move(emptyLines));
}
{
auto rowBegin = createBoolComposite("rowBegin", "Row Begin");
rowBegin->addProperty(onHeaderProp());
rowBegin->addProperty(std::make_unique<StringProperty>("match", "Matching String", ""));
addPrefab(std::move(rowBegin));
}
{
auto lineRange = createBoolComposite("lineRange", "Line Range");
lineRange->addProperty(onHeaderProp());
lineRange->addProperty(std::make_unique<IntMinMaxProperty>(
"range", "Line Range", 0, 100, 0, std::numeric_limits<int>::max(), 1, 0,
InvalidationLevel::InvalidOutput, PropertySemantics::Text));
addPrefab(std::move(lineRange));
}
}
auto columnProp = []() {
return std::make_unique<IntProperty>(
"column", "Column", 0, 0, std::numeric_limits<int>::max(), 1,
InvalidationLevel::InvalidOutput, PropertySemantics::Text);
};
if (supportedFilters.contains(FilterType::StringItem)) {
auto stringItem = createBoolComposite("stringItem", "String Match");
stringItem->addProperty(columnProp());
stringItem->addProperty(std::make_unique<TemplateOptionProperty<filters::StringComp>>(
"comp", "Comparison",
std::vector<OptionPropertyOption<filters::StringComp>>{
{"equal", "equal (==)", filters::StringComp::Equal},
{"notEqual", "Not Equal (!=)", filters::StringComp::NotEqual},
{"regex", "Regex", filters::StringComp::Regex},
{"regexPartial", "Regex (Partial)", filters::StringComp::RegexPartial}},
0));
stringItem->addProperty(std::make_unique<StringProperty>("match", "Matching String", ""));
addPrefab(std::move(stringItem));
}
if (supportedFilters.contains(FilterType::IntItem)) {
auto intItem = createBoolComposite("intItem", "Integer Comparison");
intItem->addProperty(columnProp());
intItem->addProperty(std::make_unique<TemplateOptionProperty<filters::NumberComp>>(
"comp", "Comparison",
std::vector<OptionPropertyOption<filters::NumberComp>>{
{"equal", "equal (==)", filters::NumberComp::Equal},
{"notEqual", "Not Equal (!=)", filters::NumberComp::NotEqual},
{"less", "Less (<)", filters::NumberComp::Less},
{"lessEqual", "Less Equal (<=)", filters::NumberComp::LessEqual},
{"greater", "greater (>)", filters::NumberComp::Greater},
{"greaterEqual", "Greater Equal (>=)", filters::NumberComp::GreaterEqual}},
0));
intItem->addProperty(std::make_unique<Int64Property>(
"value", "Value", 0, std::numeric_limits<int64_t>::min(),
std::numeric_limits<int64_t>::max(), 1, InvalidationLevel::InvalidOutput,
PropertySemantics::Text));
addPrefab(std::move(intItem));
}
if (supportedFilters.contains(FilterType::DoubleItem)) {
auto doubleItem = createBoolComposite("doubleItem", "Double Comparison");
doubleItem->addProperty(columnProp());
doubleItem->addProperty(std::make_unique<TemplateOptionProperty<filters::NumberComp>>(
"comp", "Comparison",
std::vector<OptionPropertyOption<filters::NumberComp>>{
{"equal", "equal (==)", filters::NumberComp::Equal},
{"notEqual", "Not Equal (!=)", filters::NumberComp::NotEqual},
{"less", "Less (<)", filters::NumberComp::Less},
{"lessEqual", "Less Equal (<=)", filters::NumberComp::LessEqual},
{"greater", "greater (>)", filters::NumberComp::Greater},
{"greaterEqual", "Greater Equal (>=)", filters::NumberComp::GreaterEqual}},
0));
doubleItem->addProperty(std::make_unique<DoubleProperty>(
"value", "Value", 0.0, std::numeric_limits<double>::lowest(),
std::numeric_limits<double>::max(), 0.1, InvalidationLevel::InvalidOutput,
PropertySemantics::Text));
doubleItem->addProperty(std::make_unique<DoubleProperty>(
"epsilon", "Epsilon", 0.0, 0.0, std::numeric_limits<double>::max(), 0.1,
InvalidationLevel::InvalidOutput, PropertySemantics::Text));
addPrefab(std::move(doubleItem));
}
if (supportedFilters.contains(FilterType::IntRange)) {
auto intRange = createBoolComposite("intRangeItem", "Int Range");
intRange->addProperty(columnProp());
intRange->addProperty(std::make_unique<Int64MinMaxProperty>(
"range", "Integer Range", 0, 100, std::numeric_limits<int64_t>::min(),
std::numeric_limits<int64_t>::max(), 1, 0, InvalidationLevel::InvalidOutput,
PropertySemantics::Text));
addPrefab(std::move(intRange));
}
if (supportedFilters.contains(FilterType::DoubleRange)) {
auto doubleRange = createBoolComposite("doubleRangeItem", "Double Range");
doubleRange->addProperty(columnProp());
doubleRange->addProperty(std::make_unique<DoubleMinMaxProperty>(
"range", "Double Range", 0.0, 100.0, std::numeric_limits<double>::lowest(),
std::numeric_limits<double>::max(), 0.1, 0.0, InvalidationLevel::InvalidOutput,
PropertySemantics::Text));
addPrefab(std::move(doubleRange));
}
}
FilterListProperty* FilterListProperty::clone() const { return new FilterListProperty(*this); }
} // namespace inviwo
<|endoftext|> |
<commit_before>/******************************************************************************
* Copyright 2017 The Apollo 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.
*****************************************************************************/
/**
* @file
**/
#include <vector>
#include <limits>
#include "modules/planning/tasks/traffic_decider/signal_lights.h"
#include "modules/planning/common/planning_gflags.h"
#include "modules/common/adapters/adapter_manager.h"
#include "modules/common/vehicle_state/vehicle_state.h"
#include "modules/common/proto/pnc_point.pb.h"
#include "modules/planning/common/frame.h"
namespace apollo {
namespace planning {
using apollo::common::adapter::AdapterManager;
using apollo::perception::TrafficLight;
using apollo::perception::TrafficLightDetection;
SignalLights::SignalLights() : TrafficRule("SignalLights") {}
bool SignalLights::ApplyRule(Frame *frame,
ReferenceLineInfo *const reference_line_info) {
if (!FLAGS_enable_signal_lights) {
return true;
}
Init();
if (!FindValidSignalLights(reference_line_info)) {
return true;
}
ReadSignals();
MakeDecisions(frame, reference_line_info);
return true;
}
void SignalLights::Init() {
signals_.clear();
signal_lights_.clear();
}
void SignalLights::ReadSignals() {
if (!AdapterManager::GetTrafficLightDetection()->Empty()) {
return;
}
const TrafficLightDetection& detection =
AdapterManager::GetTrafficLightDetection()->GetLatestObserved();
for (int j = 0; j < detection.traffic_light_size(); j++) {
const TrafficLight& signal = detection.traffic_light(j);
signals_[signal.id()] = &signal;
}
}
bool SignalLights::FindValidSignalLights(
ReferenceLineInfo *const reference_line_info) {
const std::vector<hdmap::PathOverlap> &signal_lights = reference_line_info
->reference_line().map_path().signal_overlaps();
if (signal_lights.size() <= 0) {
return false;
}
for (const hdmap::PathOverlap &signal_light : signal_lights) {
if (signal_light.start_s + FLAGS_max_distance_for_light_stop_buffer
> reference_line_info->AdcSlBoundary().end_s()) {
signal_lights_.push_back(&signal_light);
}
}
return signal_lights_.size() > 0;
}
void SignalLights::MakeDecisions(Frame* frame,
ReferenceLineInfo *const reference_line_info) {
for (const hdmap::PathOverlap* signal_light : signal_lights_) {
const TrafficLight signal = GetSignal(signal_light->object_id);
double stop_deceleration = GetStopDeceleration(reference_line_info,
signal_light);
if ((signal.color() == TrafficLight::RED &&
stop_deceleration < 6) ||
(signal.color() == TrafficLight::UNKNOWN &&
stop_deceleration < 6) ||
(signal.color() == TrafficLight::YELLOW &&
stop_deceleration < 4)) {
CreateStopObstacle(frame, reference_line_info, signal_light);
}
}
}
const TrafficLight SignalLights::GetSignal(const std::string &signal_id) {
auto iter = signals_.find(signal_id);
if (iter == signals_.end()) {
TrafficLight traffic_light;
traffic_light.set_id(signal_id);
traffic_light.set_color(TrafficLight::UNKNOWN);
traffic_light.set_confidence(0.0);
traffic_light.set_tracking_time(0.0);
return traffic_light;
}
return *iter->second;
}
double SignalLights::GetStopDeceleration(
ReferenceLineInfo *const reference_line_info,
const hdmap::PathOverlap* signal_light) {
double adc_speed = common::VehicleState::instance()->linear_velocity();
if (adc_speed < FLAGS_min_speed_for_light_stop) {
return 0.0;
}
double stop_distance = 0;
double adc_front_s = reference_line_info->AdcSlBoundary().end_s();
double stop_line_s = signal_light->start_s;
if (stop_line_s > adc_front_s) {
stop_distance = stop_line_s - adc_front_s;
} else {
stop_distance = stop_line_s +
FLAGS_max_distance_for_light_stop_buffer - adc_front_s;
}
if (stop_distance < 1e-5) {
return std::numeric_limits<double>::max();
}
return (adc_speed * adc_speed) / (2 * stop_distance);
}
void SignalLights::CreateStopObstacle(
Frame* frame,
ReferenceLineInfo *const reference_line_info,
const hdmap::PathOverlap* signal_light) {
common::SLPoint sl_point;
sl_point.set_s(signal_light->start_s);
sl_point.set_l(0);
common::math::Vec2d vec2d;
reference_line_info->reference_line().SLToXY(sl_point, &vec2d);
double heading = reference_line_info->reference_line().
GetReferencePoint(signal_light->start_s).heading();
double left_lane_width;
double right_lane_width;
reference_line_info->reference_line().GetLaneWidth(
signal_light->start_s, &left_lane_width, &right_lane_width);
common::math::Box2d stop_box{{vec2d.x(), vec2d.y()},
heading,
FLAGS_virtual_stop_wall_length,
left_lane_width + right_lane_width};
reference_line_info->AddObstacle(
frame->AddStaticVirtualObstacle(
FLAGS_signal_light_virtual_object_prefix + signal_light->object_id,
stop_box));
}
} // namespace planning
} // namespace apollo
<commit_msg>[planning] added decision for signal light stop obstacle.<commit_after>/******************************************************************************
* Copyright 2017 The Apollo 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.
*****************************************************************************/
/**
* @file
**/
#include <vector>
#include <limits>
#include "modules/planning/tasks/traffic_decider/signal_lights.h"
#include "modules/planning/common/planning_gflags.h"
#include "modules/common/adapters/adapter_manager.h"
#include "modules/common/vehicle_state/vehicle_state.h"
#include "modules/common/proto/pnc_point.pb.h"
#include "modules/planning/common/frame.h"
namespace apollo {
namespace planning {
using apollo::common::adapter::AdapterManager;
using apollo::perception::TrafficLight;
using apollo::perception::TrafficLightDetection;
SignalLights::SignalLights() : TrafficRule("SignalLights") {}
bool SignalLights::ApplyRule(Frame *frame,
ReferenceLineInfo *const reference_line_info) {
if (!FLAGS_enable_signal_lights) {
return true;
}
Init();
if (!FindValidSignalLights(reference_line_info)) {
return true;
}
ReadSignals();
MakeDecisions(frame, reference_line_info);
return true;
}
void SignalLights::Init() {
signals_.clear();
signal_lights_.clear();
}
void SignalLights::ReadSignals() {
if (!AdapterManager::GetTrafficLightDetection()->Empty()) {
return;
}
const TrafficLightDetection& detection =
AdapterManager::GetTrafficLightDetection()->GetLatestObserved();
for (int j = 0; j < detection.traffic_light_size(); j++) {
const TrafficLight& signal = detection.traffic_light(j);
signals_[signal.id()] = &signal;
}
}
bool SignalLights::FindValidSignalLights(
ReferenceLineInfo *const reference_line_info) {
const std::vector<hdmap::PathOverlap> &signal_lights = reference_line_info
->reference_line().map_path().signal_overlaps();
if (signal_lights.size() <= 0) {
return false;
}
for (const hdmap::PathOverlap &signal_light : signal_lights) {
if (signal_light.start_s + FLAGS_max_distance_for_light_stop_buffer
> reference_line_info->AdcSlBoundary().end_s()) {
signal_lights_.push_back(&signal_light);
}
}
return signal_lights_.size() > 0;
}
void SignalLights::MakeDecisions(Frame* frame,
ReferenceLineInfo *const reference_line_info) {
for (const hdmap::PathOverlap* signal_light : signal_lights_) {
const TrafficLight signal = GetSignal(signal_light->object_id);
double stop_deceleration = GetStopDeceleration(reference_line_info,
signal_light);
if ((signal.color() == TrafficLight::RED &&
stop_deceleration < 6) ||
(signal.color() == TrafficLight::UNKNOWN &&
stop_deceleration < 6) ||
(signal.color() == TrafficLight::YELLOW &&
stop_deceleration < 4)) {
CreateStopObstacle(frame, reference_line_info, signal_light);
}
}
}
const TrafficLight SignalLights::GetSignal(const std::string &signal_id) {
auto iter = signals_.find(signal_id);
if (iter == signals_.end()) {
TrafficLight traffic_light;
traffic_light.set_id(signal_id);
traffic_light.set_color(TrafficLight::UNKNOWN);
traffic_light.set_confidence(0.0);
traffic_light.set_tracking_time(0.0);
return traffic_light;
}
return *iter->second;
}
double SignalLights::GetStopDeceleration(
ReferenceLineInfo *const reference_line_info,
const hdmap::PathOverlap* signal_light) {
double adc_speed = common::VehicleState::instance()->linear_velocity();
if (adc_speed < FLAGS_min_speed_for_light_stop) {
return 0.0;
}
double stop_distance = 0;
double adc_front_s = reference_line_info->AdcSlBoundary().end_s();
double stop_line_s = signal_light->start_s;
if (stop_line_s > adc_front_s) {
stop_distance = stop_line_s - adc_front_s;
} else {
stop_distance = stop_line_s +
FLAGS_max_distance_for_light_stop_buffer - adc_front_s;
}
if (stop_distance < 1e-5) {
return std::numeric_limits<double>::max();
}
return (adc_speed * adc_speed) / (2 * stop_distance);
}
void SignalLights::CreateStopObstacle(
Frame* frame,
ReferenceLineInfo *const reference_line_info,
const hdmap::PathOverlap* signal_light) {
common::SLPoint sl_point;
sl_point.set_s(signal_light->start_s);
sl_point.set_l(0);
common::math::Vec2d vec2d;
reference_line_info->reference_line().SLToXY(sl_point, &vec2d);
double heading = reference_line_info->reference_line().
GetReferencePoint(signal_light->start_s).heading();
double left_lane_width;
double right_lane_width;
reference_line_info->reference_line().GetLaneWidth(
signal_light->start_s, &left_lane_width, &right_lane_width);
common::math::Box2d stop_box{{vec2d.x(), vec2d.y()},
heading,
FLAGS_virtual_stop_wall_length,
left_lane_width + right_lane_width};
PathObstacle* stop_wall = reference_line_info->AddObstacle(
frame->AddStaticVirtualObstacle(
FLAGS_signal_light_virtual_object_prefix + signal_light->object_id,
stop_box));
auto* path_decision = reference_line_info->path_decision();
ObjectDecisionType stop;
stop.mutable_stop();
path_decision->AddLongitudinalDecision(Name(), stop_wall->Id(), stop);
}
} // namespace planning
} // namespace apollo
<|endoftext|> |
<commit_before>
// Cef3View.cpp : implementation of the CCef3View class
//
#include "stdafx.h"
// SHARED_HANDLERS can be defined in an ATL project implementing preview, thumbnail
// and search filter handlers and allows sharing of document code with that project.
#ifndef SHARED_HANDLERS
#include "Cef3.h"
#endif
#include "Cef3Doc.h"
#include "Cef3View.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CCef3View
IMPLEMENT_DYNCREATE(CCef3View, CView)
BEGIN_MESSAGE_MAP(CCef3View, CView)
ON_WM_CREATE()
ON_WM_SIZE()
// Standard printing commands
ON_COMMAND(ID_FILE_PRINT, &CView::OnFilePrint)
ON_COMMAND(ID_FILE_PRINT_DIRECT, &CView::OnFilePrint)
ON_COMMAND(ID_FILE_PRINT_PREVIEW, &CView::OnFilePrintPreview)
// CUSTOM MESSAGE
ON_BN_CLICKED(ID_EXECUTE_JS, &CCef3View::OnAddJS)
END_MESSAGE_MAP()
// CCef3View construction/destruction
CCef3View::CCef3View()
{
// TODO: add construction code here
}
CCef3View::~CCef3View()
{
}
BOOL CCef3View::PreCreateWindow(CREATESTRUCT& cs)
{
// TODO: Modify the Window class or styles here by modifying
// the CREATESTRUCT cs
return CView::PreCreateWindow(cs);
}
// CCef3View drawing
void CCef3View::OnDraw(CDC* /*pDC*/)
{
CCef3Doc* pDoc = GetDocument();
ASSERT_VALID(pDoc);
if (!pDoc)
return;
// TODO: add draw code for native data here
}
int CCef3View::OnCreate(LPCREATESTRUCT pCreateStruct)
{
if (CView::OnCreate(pCreateStruct) == -1) {
return -1;
}
m_browserCtrl.Create(this, "index.html");
return 0;
}
void CCef3View::OnSize(UINT nType, int cx, int cy)
{
CWnd::OnSize(nType, cx, cy);
CRect clientRect;
GetClientRect(&clientRect);
m_browserCtrl.SetWindowPos(
nullptr,
clientRect.left,
clientRect.top,
clientRect.Width(),
clientRect.Height(),
SWP_NOZORDER);
}
// CCef3View printing
BOOL CCef3View::OnPreparePrinting(CPrintInfo* pInfo)
{
// default preparation
return DoPreparePrinting(pInfo);
}
void CCef3View::OnBeginPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/)
{
// TODO: add extra initialization before printing
}
void CCef3View::OnEndPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/)
{
// TODO: add cleanup after printing
}
// CCef3View diagnostics
#ifdef _DEBUG
void CCef3View::AssertValid() const
{
CView::AssertValid();
}
void CCef3View::Dump(CDumpContext& dc) const
{
CView::Dump(dc);
}
void CCef3View::OnAddJS()
{
m_browserCtrl.ExecuteJS("addHtml", "{ \"text\" : \"<p>Added From Cpp</p>\" }");
}
CCef3Doc* CCef3View::GetDocument() const // non-debug version is inline
{
ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CCef3Doc)));
return (CCef3Doc*)m_pDocument;
}
#endif //_DEBUG
// CCef3View message handlers
<commit_msg>Move CCef3View::OnAddJS() out of DEBUG code<commit_after>
// Cef3View.cpp : implementation of the CCef3View class
//
#include "stdafx.h"
// SHARED_HANDLERS can be defined in an ATL project implementing preview, thumbnail
// and search filter handlers and allows sharing of document code with that project.
#ifndef SHARED_HANDLERS
#include "Cef3.h"
#endif
#include "Cef3Doc.h"
#include "Cef3View.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CCef3View
IMPLEMENT_DYNCREATE(CCef3View, CView)
BEGIN_MESSAGE_MAP(CCef3View, CView)
ON_WM_CREATE()
ON_WM_SIZE()
// Standard printing commands
ON_COMMAND(ID_FILE_PRINT, &CView::OnFilePrint)
ON_COMMAND(ID_FILE_PRINT_DIRECT, &CView::OnFilePrint)
ON_COMMAND(ID_FILE_PRINT_PREVIEW, &CView::OnFilePrintPreview)
// CUSTOM MESSAGE
ON_BN_CLICKED(ID_EXECUTE_JS, &CCef3View::OnAddJS)
END_MESSAGE_MAP()
// CCef3View construction/destruction
CCef3View::CCef3View()
{
// TODO: add construction code here
}
CCef3View::~CCef3View()
{
}
BOOL CCef3View::PreCreateWindow(CREATESTRUCT& cs)
{
// TODO: Modify the Window class or styles here by modifying
// the CREATESTRUCT cs
return CView::PreCreateWindow(cs);
}
// CCef3View drawing
void CCef3View::OnDraw(CDC* /*pDC*/)
{
CCef3Doc* pDoc = GetDocument();
ASSERT_VALID(pDoc);
if (!pDoc)
return;
// TODO: add draw code for native data here
}
int CCef3View::OnCreate(LPCREATESTRUCT pCreateStruct)
{
if (CView::OnCreate(pCreateStruct) == -1) {
return -1;
}
m_browserCtrl.Create(this, "index.html");
return 0;
}
void CCef3View::OnSize(UINT nType, int cx, int cy)
{
CWnd::OnSize(nType, cx, cy);
CRect clientRect;
GetClientRect(&clientRect);
m_browserCtrl.SetWindowPos(
nullptr,
clientRect.left,
clientRect.top,
clientRect.Width(),
clientRect.Height(),
SWP_NOZORDER);
}
void CCef3View::OnAddJS()
{
m_browserCtrl.ExecuteJS("addHtml", "{ \"text\" : \"<p>Added From Cpp</p>\" }");
}
// CCef3View printing
BOOL CCef3View::OnPreparePrinting(CPrintInfo* pInfo)
{
// default preparation
return DoPreparePrinting(pInfo);
}
void CCef3View::OnBeginPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/)
{
// TODO: add extra initialization before printing
}
void CCef3View::OnEndPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/)
{
// TODO: add cleanup after printing
}
// CCef3View diagnostics
#ifdef _DEBUG
void CCef3View::AssertValid() const
{
CView::AssertValid();
}
void CCef3View::Dump(CDumpContext& dc) const
{
CView::Dump(dc);
}
CCef3Doc* CCef3View::GetDocument() const // non-debug version is inline
{
ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CCef3Doc)));
return (CCef3Doc*)m_pDocument;
}
#endif //_DEBUG
// CCef3View message handlers
<|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://www.qtsoftware.com/contact.
**
**************************************************************************/
#include <QtCore/QDebug>
#include <QtGui/QAction>
#include <QtGui/QShortcut>
#include "command_p.h"
/*!
\class Core::Command
\mainclass
\brief The class Command represents an action like a menu item, tool button, or shortcut.
You don't create Command objects directly, instead use \l{ActionManager::registerAction()}
to register an action and retrieve a Command. The Command object represents the user visible
action and its properties. If multiple actions are registered with the same ID (but
different contexts) the returned Command is the shared one between these actions.
A Command has two basic properties: A default shortcut and a default text. The default
shortcut is a key sequence that the user can use to trigger the active action that
the Command represents. The default text is e.g. used for representing the Command
in the keyboard shortcut preference pane. If the default text is empty, the text
of the visible action is used.
The user visible action is updated to represent the state of the active action (if any).
For performance reasons only the enabled and visible state are considered by default though.
You can tell a Command to also update the actions icon and text by setting the
corresponding \l{Command::CommandAttribute}{attribute}.
If there is no active action, the default behavior of the visible action is to be disabled.
You can change that behavior to make the visible action hide instead via the Command's
\l{Command::CommandAttribute}{attributes}.
*/
/*!
\enum Command::CommandAttribute
Defines how the user visible action is updated when the active action changes.
The default is to update the enabled and visible state, and to disable the
user visible action when there is no active action.
\omitvalue CA_Mask
\value CA_UpdateText
Also update the actions text.
\value CA_UpdateIcon
Also update the actions icon.
\value CA_Hide
When there is no active action, hide the user "visible" action, instead of just
disabling it.
\value CA_NonConfigureable
Flag to indicate that the keyboard shortcut of this Command should not be
configurable by the user.
*/
/*!
\fn void Command::setDefaultKeySequence(const QKeySequence &key)
Set the default keyboard shortcut that can be used to activate this command to \a key.
This is used if the user didn't customize the shortcut, or resets the shortcut
to the default one.
*/
/*!
\fn void Command::defaultKeySequence() const
Returns the default keyboard shortcut that can be used to activate this command.
\sa setDefaultKeySequence()
*/
/*!
\fn void Command::keySequenceChanged()
Sent when the keyboard shortcut assigned to this Command changes, e.g.
when the user sets it in the keyboard shortcut settings dialog.
*/
/*!
\fn QKeySequence Command::keySequence() const
Returns the current keyboard shortcut assigned to this Command.
\sa defaultKeySequence()
*/
/*!
\fn void Command::setKeySequence(const QKeySequence &key)
\internal
*/
/*!
\fn void Command::setDefaultText(const QString &text)
Set the \a text that is used to represent the Command in the
keyboard shortcut settings dialog. If you don't set this,
the current text from the user visible action is taken (which
is ok in many cases).
*/
/*!
\fn QString Command::defaultText() const
Returns the text that is used to present this Command to the user.
\sa setDefaultText()
*/
/*!
\fn int Command::id() const
\internal
*/
/*!
\fn QString Command::stringWithAppendedShortcut(const QString &string) const
Returns the \a string with an appended representation of the keyboard shortcut
that is currently assigned to this Command.
*/
/*!
\fn QAction *Command::action() const
Returns the user visible action for this Command.
If the Command represents a shortcut, it returns null.
Use this action to put it on e.g. tool buttons. The action
automatically forwards trigger and toggle signals to the
action that is currently active for this Command.
It also shows the current keyboard shortcut in its
tool tip (in addition to the tool tip of the active action)
and gets disabled/hidden when there is
no active action for the current context.
*/
/*!
\fn QShortcut *Command::shortcut() const
Returns the shortcut for this Command.
If the Command represents an action, it returns null.
*/
/*!
\fn void Command::setAttribute(CommandAttribute attribute)
Add the \a attribute to the attributes of this Command.
\sa CommandAttribute
\sa removeAttribute()
\sa hasAttribute()
*/
/*!
\fn void Command::removeAttribute(CommandAttribute attribute)
Remove the \a attribute from the attributes of this Command.
\sa CommandAttribute
\sa setAttribute()
*/
/*!
\fn bool Command::hasAttribute(CommandAttribute attribute) const
Returns if the Command has the \a attribute set.
\sa CommandAttribute
\sa removeAttribute()
\sa setAttribute()
*/
/*!
\fn bool Command::isActive() const
Returns if the Command has an active action/shortcut for the current
context.
*/
/*!
\fn Command::~Command()
\internal
*/
using namespace Core::Internal;
/*!
\class CommandPrivate
\internal
*/
CommandPrivate::CommandPrivate(int id)
: m_attributes(0), m_id(id)
{
}
void CommandPrivate::setDefaultKeySequence(const QKeySequence &key)
{
m_defaultKey = key;
}
QKeySequence CommandPrivate::defaultKeySequence() const
{
return m_defaultKey;
}
void CommandPrivate::setDefaultText(const QString &text)
{
m_defaultText = text;
}
QString CommandPrivate::defaultText() const
{
return m_defaultText;
}
int CommandPrivate::id() const
{
return m_id;
}
QAction *CommandPrivate::action() const
{
return 0;
}
QShortcut *CommandPrivate::shortcut() const
{
return 0;
}
void CommandPrivate::setAttribute(CommandAttribute attr)
{
m_attributes |= attr;
}
void CommandPrivate::removeAttribute(CommandAttribute attr)
{
m_attributes &= ~attr;
}
bool CommandPrivate::hasAttribute(CommandAttribute attr) const
{
return (m_attributes & attr);
}
QString CommandPrivate::stringWithAppendedShortcut(const QString &str) const
{
return QString("%1 <span style=\"color: gray; font-size: small\">%2</span>").arg(str).arg(
keySequence().toString(QKeySequence::NativeText));
}
// ---------- Shortcut ------------
/*!
\class Shortcut
\internal
*/
Shortcut::Shortcut(int id)
: CommandPrivate(id), m_shortcut(0)
{
}
QString Shortcut::name() const
{
if (!m_shortcut)
return QString();
return m_shortcut->whatsThis();
}
void Shortcut::setShortcut(QShortcut *shortcut)
{
m_shortcut = shortcut;
}
QShortcut *Shortcut::shortcut() const
{
return m_shortcut;
}
void Shortcut::setContext(const QList<int> &context)
{
m_context = context;
}
QList<int> Shortcut::context() const
{
return m_context;
}
void Shortcut::setDefaultKeySequence(const QKeySequence &key)
{
setKeySequence(key);
CommandPrivate::setDefaultKeySequence(key);
}
void Shortcut::setKeySequence(const QKeySequence &key)
{
m_shortcut->setKey(key);
emit keySequenceChanged();
}
QKeySequence Shortcut::keySequence() const
{
return m_shortcut->key();
}
void Shortcut::setDefaultText(const QString &text)
{
m_defaultText = text;
}
QString Shortcut::defaultText() const
{
return m_defaultText;
}
bool Shortcut::setCurrentContext(const QList<int> &context)
{
foreach (int ctxt, m_context) {
if (context.contains(ctxt)) {
m_shortcut->setEnabled(true);
return true;
}
}
m_shortcut->setEnabled(false);
return false;
}
bool Shortcut::isActive() const
{
return m_shortcut->isEnabled();
}
// ---------- Action ------------
/*!
\class Action
\internal
*/
Action::Action(int id)
: CommandPrivate(id), m_action(0)
{
}
QString Action::name() const
{
if (!m_action)
return QString();
return m_action->text();
}
void Action::setAction(QAction *action)
{
m_action = action;
if (m_action) {
m_action->setParent(this);
m_toolTip = m_action->toolTip();
}
}
QAction *Action::action() const
{
return m_action;
}
void Action::setLocations(const QList<CommandLocation> &locations)
{
m_locations = locations;
}
QList<CommandLocation> Action::locations() const
{
return m_locations;
}
void Action::setDefaultKeySequence(const QKeySequence &key)
{
setKeySequence(key);
CommandPrivate::setDefaultKeySequence(key);
}
void Action::setKeySequence(const QKeySequence &key)
{
m_action->setShortcut(key);
updateToolTipWithKeySequence();
emit keySequenceChanged();
}
void Action::updateToolTipWithKeySequence()
{
if (m_action->shortcut().isEmpty())
m_action->setToolTip(m_toolTip);
else
m_action->setToolTip(stringWithAppendedShortcut(m_toolTip));
}
QKeySequence Action::keySequence() const
{
return m_action->shortcut();
}
// ---------- OverrideableAction ------------
/*!
\class OverrideableAction
\internal
*/
OverrideableAction::OverrideableAction(int id)
: Action(id), m_currentAction(0), m_active(false),
m_contextInitialized(false)
{
}
void OverrideableAction::setAction(QAction *action)
{
Action::setAction(action);
}
bool OverrideableAction::setCurrentContext(const QList<int> &context)
{
m_context = context;
QAction *oldAction = m_currentAction;
m_currentAction = 0;
for (int i = 0; i < m_context.size(); ++i) {
if (QAction *a = m_contextActionMap.value(m_context.at(i), 0)) {
m_currentAction = a;
break;
}
}
if (m_currentAction == oldAction && m_contextInitialized)
return true;
m_contextInitialized = true;
if (oldAction) {
disconnect(oldAction, SIGNAL(changed()), this, SLOT(actionChanged()));
disconnect(m_action, SIGNAL(triggered(bool)), oldAction, SIGNAL(triggered(bool)));
disconnect(m_action, SIGNAL(toggled(bool)), oldAction, SLOT(setChecked(bool)));
}
if (m_currentAction) {
connect(m_currentAction, SIGNAL(changed()), this, SLOT(actionChanged()));
// we want to avoid the toggling semantic on slot trigger(), so we just connect the signals
connect(m_action, SIGNAL(triggered(bool)), m_currentAction, SIGNAL(triggered(bool)));
// we need to update the checked state, so we connect to setChecked slot, which also fires a toggled signal
connect(m_action, SIGNAL(toggled(bool)), m_currentAction, SLOT(setChecked(bool)));
actionChanged();
m_active = true;
return true;
}
if (hasAttribute(CA_Hide))
m_action->setVisible(false);
m_action->setEnabled(false);
m_active = false;
return false;
}
void OverrideableAction::addOverrideAction(QAction *action, const QList<int> &context)
{
if (context.isEmpty()) {
m_contextActionMap.insert(0, action);
} else {
for (int i=0; i<context.size(); ++i) {
int k = context.at(i);
if (m_contextActionMap.contains(k))
qWarning() << QString("addOverrideAction: action already registered for context when registering '%1'").arg(action->text());
m_contextActionMap.insert(k, action);
}
}
}
void OverrideableAction::actionChanged()
{
if (hasAttribute(CA_UpdateIcon)) {
m_action->setIcon(m_currentAction->icon());
m_action->setIconText(m_currentAction->iconText());
}
if (hasAttribute(CA_UpdateText)) {
m_action->setText(m_currentAction->text());
m_toolTip = m_currentAction->toolTip();
updateToolTipWithKeySequence();
m_action->setStatusTip(m_currentAction->statusTip());
m_action->setWhatsThis(m_currentAction->whatsThis());
}
bool block = m_action->blockSignals(true);
m_action->setChecked(m_currentAction->isChecked());
m_action->blockSignals(block);
m_action->setEnabled(m_currentAction->isEnabled());
m_action->setVisible(m_currentAction->isVisible());
}
bool OverrideableAction::isActive() const
{
return m_active;
}
<commit_msg>Setting the default key sequence should only set the current sequence if none is set. Otherwise, it overrides the user configuration in QtCreator.ini.<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://www.qtsoftware.com/contact.
**
**************************************************************************/
#include <QtCore/QDebug>
#include <QtGui/QAction>
#include <QtGui/QShortcut>
#include "command_p.h"
/*!
\class Core::Command
\mainclass
\brief The class Command represents an action like a menu item, tool button, or shortcut.
You don't create Command objects directly, instead use \l{ActionManager::registerAction()}
to register an action and retrieve a Command. The Command object represents the user visible
action and its properties. If multiple actions are registered with the same ID (but
different contexts) the returned Command is the shared one between these actions.
A Command has two basic properties: A default shortcut and a default text. The default
shortcut is a key sequence that the user can use to trigger the active action that
the Command represents. The default text is e.g. used for representing the Command
in the keyboard shortcut preference pane. If the default text is empty, the text
of the visible action is used.
The user visible action is updated to represent the state of the active action (if any).
For performance reasons only the enabled and visible state are considered by default though.
You can tell a Command to also update the actions icon and text by setting the
corresponding \l{Command::CommandAttribute}{attribute}.
If there is no active action, the default behavior of the visible action is to be disabled.
You can change that behavior to make the visible action hide instead via the Command's
\l{Command::CommandAttribute}{attributes}.
*/
/*!
\enum Command::CommandAttribute
Defines how the user visible action is updated when the active action changes.
The default is to update the enabled and visible state, and to disable the
user visible action when there is no active action.
\omitvalue CA_Mask
\value CA_UpdateText
Also update the actions text.
\value CA_UpdateIcon
Also update the actions icon.
\value CA_Hide
When there is no active action, hide the user "visible" action, instead of just
disabling it.
\value CA_NonConfigureable
Flag to indicate that the keyboard shortcut of this Command should not be
configurable by the user.
*/
/*!
\fn void Command::setDefaultKeySequence(const QKeySequence &key)
Set the default keyboard shortcut that can be used to activate this command to \a key.
This is used if the user didn't customize the shortcut, or resets the shortcut
to the default one.
*/
/*!
\fn void Command::defaultKeySequence() const
Returns the default keyboard shortcut that can be used to activate this command.
\sa setDefaultKeySequence()
*/
/*!
\fn void Command::keySequenceChanged()
Sent when the keyboard shortcut assigned to this Command changes, e.g.
when the user sets it in the keyboard shortcut settings dialog.
*/
/*!
\fn QKeySequence Command::keySequence() const
Returns the current keyboard shortcut assigned to this Command.
\sa defaultKeySequence()
*/
/*!
\fn void Command::setKeySequence(const QKeySequence &key)
\internal
*/
/*!
\fn void Command::setDefaultText(const QString &text)
Set the \a text that is used to represent the Command in the
keyboard shortcut settings dialog. If you don't set this,
the current text from the user visible action is taken (which
is ok in many cases).
*/
/*!
\fn QString Command::defaultText() const
Returns the text that is used to present this Command to the user.
\sa setDefaultText()
*/
/*!
\fn int Command::id() const
\internal
*/
/*!
\fn QString Command::stringWithAppendedShortcut(const QString &string) const
Returns the \a string with an appended representation of the keyboard shortcut
that is currently assigned to this Command.
*/
/*!
\fn QAction *Command::action() const
Returns the user visible action for this Command.
If the Command represents a shortcut, it returns null.
Use this action to put it on e.g. tool buttons. The action
automatically forwards trigger and toggle signals to the
action that is currently active for this Command.
It also shows the current keyboard shortcut in its
tool tip (in addition to the tool tip of the active action)
and gets disabled/hidden when there is
no active action for the current context.
*/
/*!
\fn QShortcut *Command::shortcut() const
Returns the shortcut for this Command.
If the Command represents an action, it returns null.
*/
/*!
\fn void Command::setAttribute(CommandAttribute attribute)
Add the \a attribute to the attributes of this Command.
\sa CommandAttribute
\sa removeAttribute()
\sa hasAttribute()
*/
/*!
\fn void Command::removeAttribute(CommandAttribute attribute)
Remove the \a attribute from the attributes of this Command.
\sa CommandAttribute
\sa setAttribute()
*/
/*!
\fn bool Command::hasAttribute(CommandAttribute attribute) const
Returns if the Command has the \a attribute set.
\sa CommandAttribute
\sa removeAttribute()
\sa setAttribute()
*/
/*!
\fn bool Command::isActive() const
Returns if the Command has an active action/shortcut for the current
context.
*/
/*!
\fn Command::~Command()
\internal
*/
using namespace Core::Internal;
/*!
\class CommandPrivate
\internal
*/
CommandPrivate::CommandPrivate(int id)
: m_attributes(0), m_id(id)
{
}
void CommandPrivate::setDefaultKeySequence(const QKeySequence &key)
{
m_defaultKey = key;
}
QKeySequence CommandPrivate::defaultKeySequence() const
{
return m_defaultKey;
}
void CommandPrivate::setDefaultText(const QString &text)
{
m_defaultText = text;
}
QString CommandPrivate::defaultText() const
{
return m_defaultText;
}
int CommandPrivate::id() const
{
return m_id;
}
QAction *CommandPrivate::action() const
{
return 0;
}
QShortcut *CommandPrivate::shortcut() const
{
return 0;
}
void CommandPrivate::setAttribute(CommandAttribute attr)
{
m_attributes |= attr;
}
void CommandPrivate::removeAttribute(CommandAttribute attr)
{
m_attributes &= ~attr;
}
bool CommandPrivate::hasAttribute(CommandAttribute attr) const
{
return (m_attributes & attr);
}
QString CommandPrivate::stringWithAppendedShortcut(const QString &str) const
{
return QString("%1 <span style=\"color: gray; font-size: small\">%2</span>").arg(str).arg(
keySequence().toString(QKeySequence::NativeText));
}
// ---------- Shortcut ------------
/*!
\class Shortcut
\internal
*/
Shortcut::Shortcut(int id)
: CommandPrivate(id), m_shortcut(0)
{
}
QString Shortcut::name() const
{
if (!m_shortcut)
return QString();
return m_shortcut->whatsThis();
}
void Shortcut::setShortcut(QShortcut *shortcut)
{
m_shortcut = shortcut;
}
QShortcut *Shortcut::shortcut() const
{
return m_shortcut;
}
void Shortcut::setContext(const QList<int> &context)
{
m_context = context;
}
QList<int> Shortcut::context() const
{
return m_context;
}
void Shortcut::setDefaultKeySequence(const QKeySequence &key)
{
setKeySequence(key);
CommandPrivate::setDefaultKeySequence(key);
}
void Shortcut::setKeySequence(const QKeySequence &key)
{
m_shortcut->setKey(key);
emit keySequenceChanged();
}
QKeySequence Shortcut::keySequence() const
{
return m_shortcut->key();
}
void Shortcut::setDefaultText(const QString &text)
{
m_defaultText = text;
}
QString Shortcut::defaultText() const
{
return m_defaultText;
}
bool Shortcut::setCurrentContext(const QList<int> &context)
{
foreach (int ctxt, m_context) {
if (context.contains(ctxt)) {
m_shortcut->setEnabled(true);
return true;
}
}
m_shortcut->setEnabled(false);
return false;
}
bool Shortcut::isActive() const
{
return m_shortcut->isEnabled();
}
// ---------- Action ------------
/*!
\class Action
\internal
*/
Action::Action(int id)
: CommandPrivate(id), m_action(0)
{
}
QString Action::name() const
{
if (!m_action)
return QString();
return m_action->text();
}
void Action::setAction(QAction *action)
{
m_action = action;
if (m_action) {
m_action->setParent(this);
m_toolTip = m_action->toolTip();
}
}
QAction *Action::action() const
{
return m_action;
}
void Action::setLocations(const QList<CommandLocation> &locations)
{
m_locations = locations;
}
QList<CommandLocation> Action::locations() const
{
return m_locations;
}
void Action::setDefaultKeySequence(const QKeySequence &key)
{
if(m_action->shortcut().isEmpty())
setKeySequence(key);
CommandPrivate::setDefaultKeySequence(key);
}
void Action::setKeySequence(const QKeySequence &key)
{
m_action->setShortcut(key);
updateToolTipWithKeySequence();
emit keySequenceChanged();
}
void Action::updateToolTipWithKeySequence()
{
if (m_action->shortcut().isEmpty())
m_action->setToolTip(m_toolTip);
else
m_action->setToolTip(stringWithAppendedShortcut(m_toolTip));
}
QKeySequence Action::keySequence() const
{
return m_action->shortcut();
}
// ---------- OverrideableAction ------------
/*!
\class OverrideableAction
\internal
*/
OverrideableAction::OverrideableAction(int id)
: Action(id), m_currentAction(0), m_active(false),
m_contextInitialized(false)
{
}
void OverrideableAction::setAction(QAction *action)
{
Action::setAction(action);
}
bool OverrideableAction::setCurrentContext(const QList<int> &context)
{
m_context = context;
QAction *oldAction = m_currentAction;
m_currentAction = 0;
for (int i = 0; i < m_context.size(); ++i) {
if (QAction *a = m_contextActionMap.value(m_context.at(i), 0)) {
m_currentAction = a;
break;
}
}
if (m_currentAction == oldAction && m_contextInitialized)
return true;
m_contextInitialized = true;
if (oldAction) {
disconnect(oldAction, SIGNAL(changed()), this, SLOT(actionChanged()));
disconnect(m_action, SIGNAL(triggered(bool)), oldAction, SIGNAL(triggered(bool)));
disconnect(m_action, SIGNAL(toggled(bool)), oldAction, SLOT(setChecked(bool)));
}
if (m_currentAction) {
connect(m_currentAction, SIGNAL(changed()), this, SLOT(actionChanged()));
// we want to avoid the toggling semantic on slot trigger(), so we just connect the signals
connect(m_action, SIGNAL(triggered(bool)), m_currentAction, SIGNAL(triggered(bool)));
// we need to update the checked state, so we connect to setChecked slot, which also fires a toggled signal
connect(m_action, SIGNAL(toggled(bool)), m_currentAction, SLOT(setChecked(bool)));
actionChanged();
m_active = true;
return true;
}
if (hasAttribute(CA_Hide))
m_action->setVisible(false);
m_action->setEnabled(false);
m_active = false;
return false;
}
void OverrideableAction::addOverrideAction(QAction *action, const QList<int> &context)
{
if (context.isEmpty()) {
m_contextActionMap.insert(0, action);
} else {
for (int i=0; i<context.size(); ++i) {
int k = context.at(i);
if (m_contextActionMap.contains(k))
qWarning() << QString("addOverrideAction: action already registered for context when registering '%1'").arg(action->text());
m_contextActionMap.insert(k, action);
}
}
}
void OverrideableAction::actionChanged()
{
if (hasAttribute(CA_UpdateIcon)) {
m_action->setIcon(m_currentAction->icon());
m_action->setIconText(m_currentAction->iconText());
}
if (hasAttribute(CA_UpdateText)) {
m_action->setText(m_currentAction->text());
m_toolTip = m_currentAction->toolTip();
updateToolTipWithKeySequence();
m_action->setStatusTip(m_currentAction->statusTip());
m_action->setWhatsThis(m_currentAction->whatsThis());
}
bool block = m_action->blockSignals(true);
m_action->setChecked(m_currentAction->isChecked());
m_action->blockSignals(block);
m_action->setEnabled(m_currentAction->isEnabled());
m_action->setVisible(m_currentAction->isVisible());
}
bool OverrideableAction::isActive() const
{
return m_active;
}
<|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 config.tests 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$
**
****************************************************************************/
#include "qwaylandwindow.h"
#include "qwaylandbuffer.h"
#include "qwaylanddisplay.h"
#include "qwaylandinputdevice.h"
#include "qwaylandscreen.h"
#include "qwaylandshell.h"
#include "qwaylandshellsurface.h"
#include <QtGui/QWindow>
#ifdef QT_WAYLAND_WINDOWMANAGER_SUPPORT
#include "windowmanager_integration/qwaylandwindowmanagerintegration.h"
#endif
#include "qwaylandextendedsurface.h"
#include "qwaylandsubsurface.h"
#include <QCoreApplication>
#include <QtGui/QWindowSystemInterface>
QWaylandWindow::QWaylandWindow(QWindow *window)
: QPlatformWindow(window)
, mDisplay(QWaylandScreen::waylandScreenFromWindow(window)->display())
, mSurface(mDisplay->createSurface(this))
, mShellSurface(mDisplay->shell()->createShellSurface(this))
, mExtendedWindow(0)
, mSubSurfaceWindow(0)
, mBuffer(0)
, mWaitingForFrameSync(false)
, mFrameCallback(0)
{
static WId id = 1;
mWindowId = id++;
if (mDisplay->windowExtension())
mExtendedWindow = mDisplay->windowExtension()->getExtendedWindow(this);
if (mDisplay->subSurfaceExtension())
mSubSurfaceWindow = mDisplay->subSurfaceExtension()->getSubSurfaceAwareWindow(this);
#ifdef QT_WAYLAND_WINDOWMANAGER_SUPPORT
mDisplay->windowManagerIntegration()->mapClientToProcess(qApp->applicationPid());
mDisplay->windowManagerIntegration()->authenticateWithToken();
#endif
if (parent() && mSubSurfaceWindow) {
mSubSurfaceWindow->setParent(static_cast<const QWaylandWindow *>(parent()));
} else {
wl_shell_surface_set_toplevel(mShellSurface->handle());
}
}
QWaylandWindow::~QWaylandWindow()
{
if (mSurface) {
delete mShellSurface;
delete mExtendedWindow;
wl_surface_destroy(mSurface);
}
QList<QWaylandInputDevice *> inputDevices = mDisplay->inputDevices();
for (int i = 0; i < inputDevices.size(); ++i)
inputDevices.at(i)->handleWindowDestroyed(this);
}
WId QWaylandWindow::winId() const
{
return mWindowId;
}
void QWaylandWindow::setParent(const QPlatformWindow *parent)
{
const QWaylandWindow *parentWaylandWindow = static_cast<const QWaylandWindow *>(parent);
if (subSurfaceWindow()) {
subSurfaceWindow()->setParent(parentWaylandWindow);
}
}
void QWaylandWindow::setVisible(bool visible)
{
if (visible) {
if (mBuffer) {
wl_surface_attach(mSurface, mBuffer->buffer(),0,0);
QWindowSystemInterface::handleSynchronousExposeEvent(window(), QRect(QPoint(), geometry().size()));
}
} else {
wl_surface_attach(mSurface, 0,0,0);
}
}
void QWaylandWindow::configure(uint32_t time, uint32_t edges,
int32_t x, int32_t y,
int32_t width, int32_t height)
{
Q_UNUSED(time);
Q_UNUSED(edges);
QRect geometry = QRect(x, y, width, height);
setGeometry(geometry);
QWindowSystemInterface::handleGeometryChange(window(), geometry);
}
void QWaylandWindow::attach(QWaylandBuffer *buffer)
{
mBuffer = buffer;
if (window()->visible()) {
wl_surface_attach(mSurface, mBuffer->buffer(),0,0);
if (buffer)
QWindowSystemInterface::handleSynchronousExposeEvent(window(), QRect(QPoint(), geometry().size()));
}
}
void QWaylandWindow::damage(const QRect &rect)
{
//We have to do sync stuff before calling damage, or we might
//get a frame callback before we get the timestamp
if (!mWaitingForFrameSync) {
mFrameCallback = wl_surface_frame(mSurface);
wl_callback_add_listener(mFrameCallback,&QWaylandWindow::callbackListener,this);
mWaitingForFrameSync = true;
}
wl_surface_damage(mSurface,
rect.x(), rect.y(), rect.width(), rect.height());
}
const wl_callback_listener QWaylandWindow::callbackListener = {
QWaylandWindow::frameCallback
};
void QWaylandWindow::frameCallback(void *data, struct wl_callback *wl_callback, uint32_t time)
{
Q_UNUSED(time);
Q_UNUSED(wl_callback);
QWaylandWindow *self = static_cast<QWaylandWindow*>(data);
self->mWaitingForFrameSync = false;
if (self->mFrameCallback) {
wl_callback_destroy(self->mFrameCallback);
self->mFrameCallback = 0;
}
}
void QWaylandWindow::waitForFrameSync()
{
mDisplay->flushRequests();
while (mWaitingForFrameSync)
mDisplay->blockingReadEvents();
}
QWaylandShellSurface *QWaylandWindow::shellSurface() const
{
return mShellSurface;
}
QWaylandExtendedSurface *QWaylandWindow::extendedWindow() const
{
return mExtendedWindow;
}
QWaylandSubSurface *QWaylandWindow::subSurfaceWindow() const
{
return mSubSurfaceWindow;
}
<commit_msg>Do not attach null buffer.<commit_after>/****************************************************************************
**
** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/
**
** This file is part of the config.tests 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$
**
****************************************************************************/
#include "qwaylandwindow.h"
#include "qwaylandbuffer.h"
#include "qwaylanddisplay.h"
#include "qwaylandinputdevice.h"
#include "qwaylandscreen.h"
#include "qwaylandshell.h"
#include "qwaylandshellsurface.h"
#include <QtGui/QWindow>
#ifdef QT_WAYLAND_WINDOWMANAGER_SUPPORT
#include "windowmanager_integration/qwaylandwindowmanagerintegration.h"
#endif
#include "qwaylandextendedsurface.h"
#include "qwaylandsubsurface.h"
#include <QCoreApplication>
#include <QtGui/QWindowSystemInterface>
QWaylandWindow::QWaylandWindow(QWindow *window)
: QPlatformWindow(window)
, mDisplay(QWaylandScreen::waylandScreenFromWindow(window)->display())
, mSurface(mDisplay->createSurface(this))
, mShellSurface(mDisplay->shell()->createShellSurface(this))
, mExtendedWindow(0)
, mSubSurfaceWindow(0)
, mBuffer(0)
, mWaitingForFrameSync(false)
, mFrameCallback(0)
{
static WId id = 1;
mWindowId = id++;
if (mDisplay->windowExtension())
mExtendedWindow = mDisplay->windowExtension()->getExtendedWindow(this);
if (mDisplay->subSurfaceExtension())
mSubSurfaceWindow = mDisplay->subSurfaceExtension()->getSubSurfaceAwareWindow(this);
#ifdef QT_WAYLAND_WINDOWMANAGER_SUPPORT
mDisplay->windowManagerIntegration()->mapClientToProcess(qApp->applicationPid());
mDisplay->windowManagerIntegration()->authenticateWithToken();
#endif
if (parent() && mSubSurfaceWindow) {
mSubSurfaceWindow->setParent(static_cast<const QWaylandWindow *>(parent()));
} else {
wl_shell_surface_set_toplevel(mShellSurface->handle());
}
}
QWaylandWindow::~QWaylandWindow()
{
if (mSurface) {
delete mShellSurface;
delete mExtendedWindow;
wl_surface_destroy(mSurface);
}
QList<QWaylandInputDevice *> inputDevices = mDisplay->inputDevices();
for (int i = 0; i < inputDevices.size(); ++i)
inputDevices.at(i)->handleWindowDestroyed(this);
}
WId QWaylandWindow::winId() const
{
return mWindowId;
}
void QWaylandWindow::setParent(const QPlatformWindow *parent)
{
const QWaylandWindow *parentWaylandWindow = static_cast<const QWaylandWindow *>(parent);
if (subSurfaceWindow()) {
subSurfaceWindow()->setParent(parentWaylandWindow);
}
}
void QWaylandWindow::setVisible(bool visible)
{
if (visible) {
if (mBuffer) {
wl_surface_attach(mSurface, mBuffer->buffer(),0,0);
QWindowSystemInterface::handleSynchronousExposeEvent(window(), QRect(QPoint(), geometry().size()));
}
}
}
void QWaylandWindow::configure(uint32_t time, uint32_t edges,
int32_t x, int32_t y,
int32_t width, int32_t height)
{
Q_UNUSED(time);
Q_UNUSED(edges);
QRect geometry = QRect(x, y, width, height);
setGeometry(geometry);
QWindowSystemInterface::handleGeometryChange(window(), geometry);
}
void QWaylandWindow::attach(QWaylandBuffer *buffer)
{
mBuffer = buffer;
if (window()->visible()) {
wl_surface_attach(mSurface, mBuffer->buffer(),0,0);
if (buffer)
QWindowSystemInterface::handleSynchronousExposeEvent(window(), QRect(QPoint(), geometry().size()));
}
}
void QWaylandWindow::damage(const QRect &rect)
{
//We have to do sync stuff before calling damage, or we might
//get a frame callback before we get the timestamp
if (!mWaitingForFrameSync) {
mFrameCallback = wl_surface_frame(mSurface);
wl_callback_add_listener(mFrameCallback,&QWaylandWindow::callbackListener,this);
mWaitingForFrameSync = true;
}
wl_surface_damage(mSurface,
rect.x(), rect.y(), rect.width(), rect.height());
}
const wl_callback_listener QWaylandWindow::callbackListener = {
QWaylandWindow::frameCallback
};
void QWaylandWindow::frameCallback(void *data, struct wl_callback *wl_callback, uint32_t time)
{
Q_UNUSED(time);
Q_UNUSED(wl_callback);
QWaylandWindow *self = static_cast<QWaylandWindow*>(data);
self->mWaitingForFrameSync = false;
if (self->mFrameCallback) {
wl_callback_destroy(self->mFrameCallback);
self->mFrameCallback = 0;
}
}
void QWaylandWindow::waitForFrameSync()
{
mDisplay->flushRequests();
while (mWaitingForFrameSync)
mDisplay->blockingReadEvents();
}
QWaylandShellSurface *QWaylandWindow::shellSurface() const
{
return mShellSurface;
}
QWaylandExtendedSurface *QWaylandWindow::extendedWindow() const
{
return mExtendedWindow;
}
QWaylandSubSurface *QWaylandWindow::subSurfaceWindow() const
{
return mSubSurfaceWindow;
}
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms and
** conditions see http://www.qt.io/terms-conditions. For further information
** use the contact form at http://www.qt.io/contact-us.
**
** 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 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, The Qt Company gives you certain additional
** rights. These rights are described in The Qt Company LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "toolchainmanager.h"
#include "abi.h"
#include "kitinformation.h"
#include "toolchain.h"
#include <coreplugin/icore.h>
#include <extensionsystem/pluginmanager.h>
#include <utils/fileutils.h>
#include <utils/persistentsettings.h>
#include <utils/qtcassert.h>
#include <utils/algorithm.h>
#include <QDir>
#include <QSettings>
static const char TOOLCHAIN_DATA_KEY[] = "ToolChain.";
static const char TOOLCHAIN_COUNT_KEY[] = "ToolChain.Count";
static const char TOOLCHAIN_FILE_VERSION_KEY[] = "Version";
static const char TOOLCHAIN_FILENAME[] = "/qtcreator/toolchains.xml";
static const char LEGACY_TOOLCHAIN_FILENAME[] = "/toolChains.xml";
using namespace Utils;
static FileName settingsFileName(const QString &path)
{
QFileInfo settingsLocation(Core::ICore::settings()->fileName());
return FileName::fromString(settingsLocation.absolutePath() + path);
}
namespace ProjectExplorer {
namespace Internal {
// --------------------------------------------------------------------------
// ToolChainManagerPrivate
// --------------------------------------------------------------------------
class ToolChainManagerPrivate
{
public:
ToolChainManagerPrivate() : m_writer(0) {}
~ToolChainManagerPrivate();
QMap<QString, FileName> m_abiToDebugger;
PersistentSettingsWriter *m_writer;
QList<ToolChain *> m_toolChains; // prioritized List
};
ToolChainManagerPrivate::~ToolChainManagerPrivate()
{
qDeleteAll(m_toolChains);
m_toolChains.clear();
delete m_writer;
}
static ToolChainManager *m_instance = 0;
static ToolChainManagerPrivate *d;
} // namespace Internal
using namespace Internal;
// --------------------------------------------------------------------------
// ToolChainManager
// --------------------------------------------------------------------------
ToolChainManager::ToolChainManager(QObject *parent) :
QObject(parent)
{
Q_ASSERT(!m_instance);
m_instance = this;
d = new ToolChainManagerPrivate;
connect(Core::ICore::instance(), SIGNAL(saveSettingsRequested()),
this, SLOT(saveToolChains()));
connect(this, SIGNAL(toolChainAdded(ProjectExplorer::ToolChain*)),
this, SIGNAL(toolChainsChanged()));
connect(this, SIGNAL(toolChainRemoved(ProjectExplorer::ToolChain*)),
this, SIGNAL(toolChainsChanged()));
connect(this, SIGNAL(toolChainUpdated(ProjectExplorer::ToolChain*)),
this, SIGNAL(toolChainsChanged()));
}
ToolChainManager::~ToolChainManager()
{
delete d;
m_instance = 0;
}
ToolChainManager *ToolChainManager::instance()
{
return m_instance;
}
static QList<ToolChain *> restoreFromFile(const FileName &fileName)
{
QList<ToolChain *> result;
PersistentSettingsReader reader;
if (!reader.load(fileName))
return result;
QVariantMap data = reader.restoreValues();
// Check version:
int version = data.value(QLatin1String(TOOLCHAIN_FILE_VERSION_KEY), 0).toInt();
if (version < 1)
return result;
QList<ToolChainFactory *> factories = ExtensionSystem::PluginManager::getObjects<ToolChainFactory>();
int count = data.value(QLatin1String(TOOLCHAIN_COUNT_KEY), 0).toInt();
for (int i = 0; i < count; ++i) {
const QString key = QString::fromLatin1(TOOLCHAIN_DATA_KEY) + QString::number(i);
if (!data.contains(key))
break;
const QVariantMap tcMap = data.value(key).toMap();
bool restored = false;
foreach (ToolChainFactory *f, factories) {
if (f->canRestore(tcMap)) {
if (ToolChain *tc = f->restore(tcMap)) {
result.append(tc);
restored = true;
break;
}
}
}
if (!restored)
qWarning("Warning: '%s': Unable to restore compiler type '%s' for tool chain %s.",
qPrintable(fileName.toUserOutput()),
qPrintable(ToolChainFactory::typeIdFromMap(tcMap).toString()),
qPrintable(QString::fromUtf8(ToolChainFactory::idFromMap(tcMap))));
}
return result;
}
void ToolChainManager::restoreToolChains()
{
QTC_ASSERT(!d->m_writer, return);
d->m_writer =
new PersistentSettingsWriter(settingsFileName(QLatin1String(TOOLCHAIN_FILENAME)), QLatin1String("QtCreatorToolChains"));
QList<ToolChain *> tcsToRegister;
QList<ToolChain *> tcsToCheck;
// read all tool chains from SDK
QFileInfo systemSettingsFile(Core::ICore::settings(QSettings::SystemScope)->fileName());
QList<ToolChain *> readTcs =
restoreFromFile(FileName::fromString(systemSettingsFile.absolutePath() + QLatin1String(TOOLCHAIN_FILENAME)));
// make sure we mark these as autodetected!
foreach (ToolChain *tc, readTcs)
tc->setDetection(ToolChain::AutoDetection);
tcsToRegister = readTcs; // SDK TCs are always considered to be up-to-date, so no need to
// recheck them.
// read all tool chains from user file.
// Read legacy settings once and keep them around...
FileName fileName = settingsFileName(QLatin1String(TOOLCHAIN_FILENAME));
if (!fileName.exists())
fileName = settingsFileName(QLatin1String(LEGACY_TOOLCHAIN_FILENAME));
readTcs = restoreFromFile(fileName);
foreach (ToolChain *tc, readTcs) {
if (tc->isAutoDetected())
tcsToCheck.append(tc);
else
tcsToRegister.append(tc);
}
readTcs.clear();
// Remove TCs configured by the SDK:
foreach (ToolChain *tc, tcsToRegister) {
for (int i = tcsToCheck.count() - 1; i >= 0; --i) {
if (tcsToCheck.at(i)->id() == tc->id()) {
delete tcsToCheck.at(i);
tcsToCheck.removeAt(i);
}
}
}
// Then auto detect
QList<ToolChain *> detectedTcs;
QList<ToolChainFactory *> factories = ExtensionSystem::PluginManager::getObjects<ToolChainFactory>();
foreach (ToolChainFactory *f, factories)
detectedTcs.append(f->autoDetect());
// Find/update autodetected tool chains:
ToolChain *toStore = 0;
foreach (ToolChain *currentDetected, detectedTcs) {
toStore = currentDetected;
// Check whether we had this TC stored and prefer the old one with the old id, marked
// as auto-detection.
for (int i = 0; i < tcsToCheck.count(); ++i) {
if (*(tcsToCheck.at(i)) == *currentDetected) {
toStore = tcsToCheck.at(i);
toStore->setDetection(ToolChain::AutoDetection);
tcsToCheck.removeAt(i);
delete currentDetected;
break;
}
}
tcsToRegister += toStore;
}
// Keep toolchains that were not rediscovered but are still executable and delete the rest
foreach (ToolChain *tc, tcsToCheck) {
if (!tc->isValid()) {
qWarning() << QString::fromLatin1("ToolChain \"%1\" (%2) dropped since it is not valid")
.arg(tc->displayName()).arg(QString::fromUtf8(tc->id()));
delete tc;
} else {
tcsToRegister += tc;
}
}
// Store manual tool chains
foreach (ToolChain *tc, tcsToRegister)
registerToolChain(tc);
emit m_instance->toolChainsLoaded();
}
void ToolChainManager::saveToolChains()
{
QVariantMap data;
data.insert(QLatin1String(TOOLCHAIN_FILE_VERSION_KEY), 1);
int count = 0;
foreach (ToolChain *tc, d->m_toolChains) {
if (tc->isValid()) {
QVariantMap tmp = tc->toMap();
if (tmp.isEmpty())
continue;
data.insert(QString::fromLatin1(TOOLCHAIN_DATA_KEY) + QString::number(count), tmp);
++count;
}
}
data.insert(QLatin1String(TOOLCHAIN_COUNT_KEY), count);
d->m_writer->save(data, Core::ICore::mainWindow());
// Do not save default debuggers! Those are set by the SDK!
}
QList<ToolChain *> ToolChainManager::toolChains()
{
return d->m_toolChains;
}
QList<ToolChain *> ToolChainManager::findToolChains(const Abi &abi)
{
QList<ToolChain *> result;
foreach (ToolChain *tc, d->m_toolChains) {
Abi targetAbi = tc->targetAbi();
if (targetAbi.isCompatibleWith(abi))
result.append(tc);
}
return result;
}
ToolChain *ToolChainManager::findToolChain(const QByteArray &id)
{
if (id.isEmpty())
return 0;
ToolChain *tc = Utils::findOrDefault(d->m_toolChains, Utils::equal(&ToolChain::id, id));
// Compatibility with versions 3.5 and earlier:
if (!tc) {
const int pos = id.indexOf(':');
if (pos < 0)
return tc;
const QByteArray shortId = id.mid(pos + 1);
tc = Utils::findOrDefault(d->m_toolChains, Utils::equal(&ToolChain::id, shortId));
}
return tc;
}
FileName ToolChainManager::defaultDebugger(const Abi &abi)
{
return d->m_abiToDebugger.value(abi.toString());
}
bool ToolChainManager::isLoaded()
{
return d->m_writer;
}
void ToolChainManager::notifyAboutUpdate(ToolChain *tc)
{
if (!tc || !d->m_toolChains.contains(tc))
return;
emit m_instance->toolChainUpdated(tc);
}
bool ToolChainManager::registerToolChain(ToolChain *tc)
{
QTC_ASSERT(d->m_writer, return false);
if (!tc || d->m_toolChains.contains(tc))
return true;
foreach (ToolChain *current, d->m_toolChains) {
if (*tc == *current && !tc->isAutoDetected())
return false;
QTC_ASSERT(current->id() != tc->id(), return false);
}
d->m_toolChains.append(tc);
emit m_instance->toolChainAdded(tc);
return true;
}
void ToolChainManager::deregisterToolChain(ToolChain *tc)
{
if (!tc || !d->m_toolChains.contains(tc))
return;
d->m_toolChains.removeOne(tc);
emit m_instance->toolChainRemoved(tc);
delete tc;
}
} // namespace ProjectExplorer
<commit_msg>ToolChainManager: Demote previously auto-detected ToolChains to manual<commit_after>/****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms and
** conditions see http://www.qt.io/terms-conditions. For further information
** use the contact form at http://www.qt.io/contact-us.
**
** 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 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, The Qt Company gives you certain additional
** rights. These rights are described in The Qt Company LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "toolchainmanager.h"
#include "abi.h"
#include "kitinformation.h"
#include "toolchain.h"
#include <coreplugin/icore.h>
#include <extensionsystem/pluginmanager.h>
#include <utils/fileutils.h>
#include <utils/persistentsettings.h>
#include <utils/qtcassert.h>
#include <utils/algorithm.h>
#include <QDir>
#include <QSettings>
static const char TOOLCHAIN_DATA_KEY[] = "ToolChain.";
static const char TOOLCHAIN_COUNT_KEY[] = "ToolChain.Count";
static const char TOOLCHAIN_FILE_VERSION_KEY[] = "Version";
static const char TOOLCHAIN_FILENAME[] = "/qtcreator/toolchains.xml";
static const char LEGACY_TOOLCHAIN_FILENAME[] = "/toolChains.xml";
using namespace Utils;
static FileName settingsFileName(const QString &path)
{
QFileInfo settingsLocation(Core::ICore::settings()->fileName());
return FileName::fromString(settingsLocation.absolutePath() + path);
}
namespace ProjectExplorer {
namespace Internal {
// --------------------------------------------------------------------------
// ToolChainManagerPrivate
// --------------------------------------------------------------------------
class ToolChainManagerPrivate
{
public:
ToolChainManagerPrivate() : m_writer(0) {}
~ToolChainManagerPrivate();
QMap<QString, FileName> m_abiToDebugger;
PersistentSettingsWriter *m_writer;
QList<ToolChain *> m_toolChains; // prioritized List
};
ToolChainManagerPrivate::~ToolChainManagerPrivate()
{
qDeleteAll(m_toolChains);
m_toolChains.clear();
delete m_writer;
}
static ToolChainManager *m_instance = 0;
static ToolChainManagerPrivate *d;
} // namespace Internal
using namespace Internal;
// --------------------------------------------------------------------------
// ToolChainManager
// --------------------------------------------------------------------------
ToolChainManager::ToolChainManager(QObject *parent) :
QObject(parent)
{
Q_ASSERT(!m_instance);
m_instance = this;
d = new ToolChainManagerPrivate;
connect(Core::ICore::instance(), SIGNAL(saveSettingsRequested()),
this, SLOT(saveToolChains()));
connect(this, SIGNAL(toolChainAdded(ProjectExplorer::ToolChain*)),
this, SIGNAL(toolChainsChanged()));
connect(this, SIGNAL(toolChainRemoved(ProjectExplorer::ToolChain*)),
this, SIGNAL(toolChainsChanged()));
connect(this, SIGNAL(toolChainUpdated(ProjectExplorer::ToolChain*)),
this, SIGNAL(toolChainsChanged()));
}
ToolChainManager::~ToolChainManager()
{
delete d;
m_instance = 0;
}
ToolChainManager *ToolChainManager::instance()
{
return m_instance;
}
static QList<ToolChain *> restoreFromFile(const FileName &fileName)
{
QList<ToolChain *> result;
PersistentSettingsReader reader;
if (!reader.load(fileName))
return result;
QVariantMap data = reader.restoreValues();
// Check version:
int version = data.value(QLatin1String(TOOLCHAIN_FILE_VERSION_KEY), 0).toInt();
if (version < 1)
return result;
QList<ToolChainFactory *> factories = ExtensionSystem::PluginManager::getObjects<ToolChainFactory>();
int count = data.value(QLatin1String(TOOLCHAIN_COUNT_KEY), 0).toInt();
for (int i = 0; i < count; ++i) {
const QString key = QString::fromLatin1(TOOLCHAIN_DATA_KEY) + QString::number(i);
if (!data.contains(key))
break;
const QVariantMap tcMap = data.value(key).toMap();
bool restored = false;
foreach (ToolChainFactory *f, factories) {
if (f->canRestore(tcMap)) {
if (ToolChain *tc = f->restore(tcMap)) {
result.append(tc);
restored = true;
break;
}
}
}
if (!restored)
qWarning("Warning: '%s': Unable to restore compiler type '%s' for tool chain %s.",
qPrintable(fileName.toUserOutput()),
qPrintable(ToolChainFactory::typeIdFromMap(tcMap).toString()),
qPrintable(QString::fromUtf8(ToolChainFactory::idFromMap(tcMap))));
}
return result;
}
void ToolChainManager::restoreToolChains()
{
QTC_ASSERT(!d->m_writer, return);
d->m_writer =
new PersistentSettingsWriter(settingsFileName(QLatin1String(TOOLCHAIN_FILENAME)), QLatin1String("QtCreatorToolChains"));
QList<ToolChain *> tcsToRegister;
QList<ToolChain *> tcsToCheck;
// read all tool chains from SDK
QFileInfo systemSettingsFile(Core::ICore::settings(QSettings::SystemScope)->fileName());
QList<ToolChain *> readTcs =
restoreFromFile(FileName::fromString(systemSettingsFile.absolutePath() + QLatin1String(TOOLCHAIN_FILENAME)));
// make sure we mark these as autodetected!
foreach (ToolChain *tc, readTcs)
tc->setDetection(ToolChain::AutoDetection);
tcsToRegister = readTcs; // SDK TCs are always considered to be up-to-date, so no need to
// recheck them.
// read all tool chains from user file.
// Read legacy settings once and keep them around...
FileName fileName = settingsFileName(QLatin1String(TOOLCHAIN_FILENAME));
if (!fileName.exists())
fileName = settingsFileName(QLatin1String(LEGACY_TOOLCHAIN_FILENAME));
readTcs = restoreFromFile(fileName);
foreach (ToolChain *tc, readTcs) {
if (tc->isAutoDetected())
tcsToCheck.append(tc);
else
tcsToRegister.append(tc);
}
readTcs.clear();
// Remove TCs configured by the SDK:
foreach (ToolChain *tc, tcsToRegister) {
for (int i = tcsToCheck.count() - 1; i >= 0; --i) {
if (tcsToCheck.at(i)->id() == tc->id()) {
delete tcsToCheck.at(i);
tcsToCheck.removeAt(i);
}
}
}
// Then auto detect
QList<ToolChain *> detectedTcs;
QList<ToolChainFactory *> factories = ExtensionSystem::PluginManager::getObjects<ToolChainFactory>();
foreach (ToolChainFactory *f, factories)
detectedTcs.append(f->autoDetect());
// Find/update autodetected tool chains:
ToolChain *toStore = 0;
foreach (ToolChain *currentDetected, detectedTcs) {
toStore = currentDetected;
// Check whether we had this TC stored and prefer the old one with the old id, marked
// as auto-detection.
for (int i = 0; i < tcsToCheck.count(); ++i) {
if (*(tcsToCheck.at(i)) == *currentDetected) {
toStore = tcsToCheck.at(i);
toStore->setDetection(ToolChain::AutoDetection);
tcsToCheck.removeAt(i);
delete currentDetected;
break;
}
}
tcsToRegister += toStore;
}
// Keep toolchains that were not rediscovered but are still executable and delete the rest
foreach (ToolChain *tc, tcsToCheck) {
if (!tc->isValid()) {
qWarning() << QString::fromLatin1("ToolChain \"%1\" (%2) dropped since it is not valid")
.arg(tc->displayName()).arg(QString::fromUtf8(tc->id()));
delete tc;
} else {
tc->setDetection(ToolChain::ManualDetection); // "demote" to manual toolchain
tcsToRegister += tc;
}
}
// Store manual tool chains
foreach (ToolChain *tc, tcsToRegister)
registerToolChain(tc);
emit m_instance->toolChainsLoaded();
}
void ToolChainManager::saveToolChains()
{
QVariantMap data;
data.insert(QLatin1String(TOOLCHAIN_FILE_VERSION_KEY), 1);
int count = 0;
foreach (ToolChain *tc, d->m_toolChains) {
if (tc->isValid()) {
QVariantMap tmp = tc->toMap();
if (tmp.isEmpty())
continue;
data.insert(QString::fromLatin1(TOOLCHAIN_DATA_KEY) + QString::number(count), tmp);
++count;
}
}
data.insert(QLatin1String(TOOLCHAIN_COUNT_KEY), count);
d->m_writer->save(data, Core::ICore::mainWindow());
// Do not save default debuggers! Those are set by the SDK!
}
QList<ToolChain *> ToolChainManager::toolChains()
{
return d->m_toolChains;
}
QList<ToolChain *> ToolChainManager::findToolChains(const Abi &abi)
{
QList<ToolChain *> result;
foreach (ToolChain *tc, d->m_toolChains) {
Abi targetAbi = tc->targetAbi();
if (targetAbi.isCompatibleWith(abi))
result.append(tc);
}
return result;
}
ToolChain *ToolChainManager::findToolChain(const QByteArray &id)
{
if (id.isEmpty())
return 0;
ToolChain *tc = Utils::findOrDefault(d->m_toolChains, Utils::equal(&ToolChain::id, id));
// Compatibility with versions 3.5 and earlier:
if (!tc) {
const int pos = id.indexOf(':');
if (pos < 0)
return tc;
const QByteArray shortId = id.mid(pos + 1);
tc = Utils::findOrDefault(d->m_toolChains, Utils::equal(&ToolChain::id, shortId));
}
return tc;
}
FileName ToolChainManager::defaultDebugger(const Abi &abi)
{
return d->m_abiToDebugger.value(abi.toString());
}
bool ToolChainManager::isLoaded()
{
return d->m_writer;
}
void ToolChainManager::notifyAboutUpdate(ToolChain *tc)
{
if (!tc || !d->m_toolChains.contains(tc))
return;
emit m_instance->toolChainUpdated(tc);
}
bool ToolChainManager::registerToolChain(ToolChain *tc)
{
QTC_ASSERT(d->m_writer, return false);
if (!tc || d->m_toolChains.contains(tc))
return true;
foreach (ToolChain *current, d->m_toolChains) {
if (*tc == *current && !tc->isAutoDetected())
return false;
QTC_ASSERT(current->id() != tc->id(), return false);
}
d->m_toolChains.append(tc);
emit m_instance->toolChainAdded(tc);
return true;
}
void ToolChainManager::deregisterToolChain(ToolChain *tc)
{
if (!tc || !d->m_toolChains.contains(tc))
return;
d->m_toolChains.removeOne(tc);
emit m_instance->toolChainRemoved(tc);
delete tc;
}
} // namespace ProjectExplorer
<|endoftext|> |
<commit_before>
/**
* projectM -- Milkdrop-esque visualisation SDK
* Copyright (C)2003-2004 projectM Team
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public
* License as published by the Free Software Foundation; either
* version 2.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 General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* See 'LICENSE.txt' included within this release
*
*/
/* $Id: parec-simple.c 1418 2007-01-04 13:43:45Z ossman $ */
/***
This file was copied from PulseAudio.
PulseAudio is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published
by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
PulseAudio is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with PulseAudio; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
USA.
***/
#include <fcntl.h>
#include <stdlib.h>
#include <math.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <projectM.hpp>
#include <qprojectm_mainwindow.hpp>
#include <QApplication>
#include <QtDebug>
#include "ConfigFile.h"
#include <string>
#include <iostream>
#include <stdio.h>
#include <unistd.h>
#include <QAction>
#include <QThread>
#include <QTimer>
#define CONFIG_FILE "/share/projectM/config.inp"
std::string read_config();
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
//#include <pulsecore/gccmacro.h>
#include "QPulseAudioThread.hpp"
#include "QPulseAudioDeviceChooser.hpp"
int dumpFrame = 0;
int frameNumber = 0;
int texsize=512;
int gx=32,gy=24;
int wvw=512,wvh=512;
int fvw=1024,fvh=768;
int fps=30, fullscreen=0;
int main ( int argc, char*argv[] )
{
int i;
char projectM_data[1024];
QApplication app ( argc, argv );
setlocale(LC_NUMERIC, "C"); // Fix
std::string config_file;
config_file = read_config();
QMutex audioMutex;
QProjectM_MainWindow * mainWindow = new QProjectM_MainWindow ( config_file, &audioMutex);
QAction pulseAction("Pulse audio settings...", mainWindow);
mainWindow->registerSettingsAction(&pulseAction);
mainWindow->show();
QPulseAudioThread * pulseThread = new QPulseAudioThread(argc, argv, mainWindow);
pulseThread->start();
//QApplication::connect
// (mainWindow->qprojectMWidget(), SIGNAL(projectM_Initialized(QProjectM *)), pulseThread, SLOT(setQrojectMWidget(QProjectMWidget*)));
QPulseAudioDeviceChooser devChooser(pulseThread, mainWindow);
QApplication::connect(&pulseAction, SIGNAL(triggered()), &devChooser, SLOT(open()));
//QApplication::connect(pulseThread, SIGNAL(threadCleanedUp()), mainWindow, SLOT(close()));
//QApplication::connect(mainWindow, SIGNAL(shuttingDown()), pulseThread, SLOT(cleanup()), Qt::DirectConnection);
int ret = app.exec();
if (pulseThread != 0)
devChooser.writeSettings();
if (mainWindow)
mainWindow->unregisterSettingsAction(&pulseAction);
pulseThread->cleanup();
delete(pulseThread);
return ret;
}
std::string read_config()
{
int n;
char num[512];
FILE *in;
FILE *out;
char* home;
char projectM_home[1024];
char projectM_config[1024];
strcpy ( projectM_config, PROJECTM_PREFIX );
strcpy ( projectM_config+strlen ( PROJECTM_PREFIX ), CONFIG_FILE );
projectM_config[strlen ( PROJECTM_PREFIX ) +strlen ( CONFIG_FILE ) ]='\0';
printf ( "dir:%s \n",projectM_config );
home=getenv ( "HOME" );
strcpy ( projectM_home, home );
strcpy ( projectM_home+strlen ( home ), "/.projectM/config.inp" );
projectM_home[strlen ( home ) +strlen ( "/.projectM/config.inp" ) ]='\0';
if ( ( in = fopen ( projectM_home, "r" ) ) != 0 )
{
printf ( "reading ~/.projectM/config.inp \n" );
fclose ( in );
return std::string ( projectM_home );
}
else
{
printf ( "trying to create ~/.projectM/config.inp \n" );
strcpy ( projectM_home, home );
strcpy ( projectM_home+strlen ( home ), "/.projectM" );
projectM_home[strlen ( home ) +strlen ( "/.projectM" ) ]='\0';
mkdir ( projectM_home, 0755 );
strcpy ( projectM_home, home );
strcpy ( projectM_home+strlen ( home ), "/.projectM/config.inp" );
projectM_home[strlen ( home ) +strlen ( "/.projectM/config.inp" ) ]='\0';
if ( ( out = fopen ( projectM_home,"w" ) ) !=0 )
{
if ( ( in = fopen ( projectM_config, "r" ) ) != 0 )
{
while ( fgets ( num,80,in ) !=NULL )
{
fputs ( num,out );
}
fclose ( in );
fclose ( out );
if ( ( in = fopen ( projectM_home, "r" ) ) != 0 )
{
printf ( "created ~/.projectM/config.inp successfully\n" );
fclose ( in );
return std::string ( projectM_home );
}
else{printf ( "This shouldn't happen, using implementation defualts\n" );abort();}
}
else{printf ( "Cannot find projectM default config, using implementation defaults\n" );abort();}
}
else
{
printf ( "Cannot create ~/.projectM/config.inp, using default config file\n" );
if ( ( in = fopen ( projectM_config, "r" ) ) != 0 )
{
printf ( "Successfully opened default config file\n" );
fclose ( in );
return std::string ( projectM_config );
}
else{ printf ( "Using implementation defaults, your system is really messed up, I'm suprised we even got this far\n" ); abort();}
}
}
abort();
}
<commit_msg>Add stat.h to projectM-pulseaudio fix FTBFS in some cases.<commit_after>
/**
* projectM -- Milkdrop-esque visualisation SDK
* Copyright (C)2003-2004 projectM Team
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public
* License as published by the Free Software Foundation; either
* version 2.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 General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* See 'LICENSE.txt' included within this release
*
*/
/* $Id: parec-simple.c 1418 2007-01-04 13:43:45Z ossman $ */
/***
This file was copied from PulseAudio.
PulseAudio is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published
by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
PulseAudio is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with PulseAudio; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
USA.
***/
#include <fcntl.h>
#include <stdlib.h>
#include <math.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <projectM.hpp>
#include <qprojectm_mainwindow.hpp>
#include <QApplication>
#include <QtDebug>
#include "ConfigFile.h"
#include <string>
#include <iostream>
#include <stdio.h>
#include <unistd.h>
#include <QAction>
#include <QThread>
#include <QTimer>
#define CONFIG_FILE "/share/projectM/config.inp"
std::string read_config();
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <sys/stat.h>
//#include <pulsecore/gccmacro.h>
#include "QPulseAudioThread.hpp"
#include "QPulseAudioDeviceChooser.hpp"
int dumpFrame = 0;
int frameNumber = 0;
int texsize=512;
int gx=32,gy=24;
int wvw=512,wvh=512;
int fvw=1024,fvh=768;
int fps=30, fullscreen=0;
int main ( int argc, char*argv[] )
{
int i;
char projectM_data[1024];
QApplication app ( argc, argv );
setlocale(LC_NUMERIC, "C"); // Fix
std::string config_file;
config_file = read_config();
QMutex audioMutex;
QProjectM_MainWindow * mainWindow = new QProjectM_MainWindow ( config_file, &audioMutex);
QAction pulseAction("Pulse audio settings...", mainWindow);
mainWindow->registerSettingsAction(&pulseAction);
mainWindow->show();
QPulseAudioThread * pulseThread = new QPulseAudioThread(argc, argv, mainWindow);
pulseThread->start();
//QApplication::connect
// (mainWindow->qprojectMWidget(), SIGNAL(projectM_Initialized(QProjectM *)), pulseThread, SLOT(setQrojectMWidget(QProjectMWidget*)));
QPulseAudioDeviceChooser devChooser(pulseThread, mainWindow);
QApplication::connect(&pulseAction, SIGNAL(triggered()), &devChooser, SLOT(open()));
//QApplication::connect(pulseThread, SIGNAL(threadCleanedUp()), mainWindow, SLOT(close()));
//QApplication::connect(mainWindow, SIGNAL(shuttingDown()), pulseThread, SLOT(cleanup()), Qt::DirectConnection);
int ret = app.exec();
if (pulseThread != 0)
devChooser.writeSettings();
if (mainWindow)
mainWindow->unregisterSettingsAction(&pulseAction);
pulseThread->cleanup();
delete(pulseThread);
return ret;
}
std::string read_config()
{
int n;
char num[512];
FILE *in;
FILE *out;
char* home;
char projectM_home[1024];
char projectM_config[1024];
strcpy ( projectM_config, PROJECTM_PREFIX );
strcpy ( projectM_config+strlen ( PROJECTM_PREFIX ), CONFIG_FILE );
projectM_config[strlen ( PROJECTM_PREFIX ) +strlen ( CONFIG_FILE ) ]='\0';
printf ( "dir:%s \n",projectM_config );
home=getenv ( "HOME" );
strcpy ( projectM_home, home );
strcpy ( projectM_home+strlen ( home ), "/.projectM/config.inp" );
projectM_home[strlen ( home ) +strlen ( "/.projectM/config.inp" ) ]='\0';
if ( ( in = fopen ( projectM_home, "r" ) ) != 0 )
{
printf ( "reading ~/.projectM/config.inp \n" );
fclose ( in );
return std::string ( projectM_home );
}
else
{
printf ( "trying to create ~/.projectM/config.inp \n" );
strcpy ( projectM_home, home );
strcpy ( projectM_home+strlen ( home ), "/.projectM" );
projectM_home[strlen ( home ) +strlen ( "/.projectM" ) ]='\0';
mkdir ( projectM_home, 0755 );
strcpy ( projectM_home, home );
strcpy ( projectM_home+strlen ( home ), "/.projectM/config.inp" );
projectM_home[strlen ( home ) +strlen ( "/.projectM/config.inp" ) ]='\0';
if ( ( out = fopen ( projectM_home,"w" ) ) !=0 )
{
if ( ( in = fopen ( projectM_config, "r" ) ) != 0 )
{
while ( fgets ( num,80,in ) !=NULL )
{
fputs ( num,out );
}
fclose ( in );
fclose ( out );
if ( ( in = fopen ( projectM_home, "r" ) ) != 0 )
{
printf ( "created ~/.projectM/config.inp successfully\n" );
fclose ( in );
return std::string ( projectM_home );
}
else{printf ( "This shouldn't happen, using implementation defualts\n" );abort();}
}
else{printf ( "Cannot find projectM default config, using implementation defaults\n" );abort();}
}
else
{
printf ( "Cannot create ~/.projectM/config.inp, using default config file\n" );
if ( ( in = fopen ( projectM_config, "r" ) ) != 0 )
{
printf ( "Successfully opened default config file\n" );
fclose ( in );
return std::string ( projectM_config );
}
else{ printf ( "Using implementation defaults, your system is really messed up, I'm suprised we even got this far\n" ); abort();}
}
}
abort();
}
<|endoftext|> |
<commit_before>/* Copyright 2015-2018 Egor Yusov
*
* 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
*
* 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 OF ANY PROPRIETARY RIGHTS.
*
* In no event and under no legal theory, whether in tort (including negligence),
* contract, or otherwise, unless required by applicable law (such as deliberate
* and grossly negligent acts) or agreed to in writing, shall any Contributor be
* liable for any damages, including any direct, indirect, special, incidental,
* or consequential damages of any character arising as a result of this License or
* out of the use or inability to use the software (including but not limited to damages
* for loss of goodwill, work stoppage, computer failure or malfunction, or any and
* all other commercial damages or losses), even if such Contributor has been advised
* of the possibility of such damages.
*/
#include "pch.h"
#include "ShaderGLImpl.h"
#include "RenderDeviceGLImpl.h"
#include "DataBlobImpl.h"
#include "GLSLSourceBuilder.h"
using namespace Diligent;
namespace Diligent
{
ShaderGLImpl::ShaderGLImpl(IReferenceCounters *pRefCounters, RenderDeviceGLImpl *pDeviceGL, const ShaderCreationAttribs &CreationAttribs, bool bIsDeviceInternal) :
TShaderBase( pRefCounters, pDeviceGL, CreationAttribs.Desc, bIsDeviceInternal ),
m_GlProgObj(false),
m_GLShaderObj( false, GLObjectWrappers::GLShaderObjCreateReleaseHelper( GetGLShaderType( m_Desc.ShaderType ) ) )
{
auto GLSLSource = BuildGLSLSourceString(CreationAttribs, TargetGLSLCompiler::driver);
// Note: there is a simpler way to create the program:
//m_uiShaderSeparateProg = glCreateShaderProgramv(GL_VERTEX_SHADER, _countof(ShaderStrings), ShaderStrings);
// NOTE: glCreateShaderProgramv() is considered equivalent to both a shader compilation and a program linking
// operation. Since it performs both at the same time, compiler or linker errors can be encountered. However,
// since this function only returns a program object, compiler-type errors will be reported as linker errors
// through the following API:
// GLint isLinked = 0;
// glGetProgramiv(program, GL_LINK_STATUS, &isLinked);
// The log can then be queried in the same way
// Create empty shader object
auto GLShaderType = GetGLShaderType(m_Desc.ShaderType);
GLObjectWrappers::GLShaderObj ShaderObj(true, GLObjectWrappers::GLShaderObjCreateReleaseHelper(GLShaderType));
// Each element in the length array may contain the length of the corresponding string
// (the null character is not counted as part of the string length).
// Not specifying lengths causes shader compilation errors on Android
const char * ShaderStrings[] = { GLSLSource.c_str() };
GLint Lenghts[] = { static_cast<GLint>(GLSLSource.length()) };
// Provide source strings (the strings will be saved in internal OpenGL memory)
glShaderSource(ShaderObj, _countof(ShaderStrings), ShaderStrings, Lenghts );
// When the shader is compiled, it will be compiled as if all of the given strings were concatenated end-to-end.
glCompileShader(ShaderObj);
GLint compiled = GL_FALSE;
// Get compilation status
glGetShaderiv(ShaderObj, GL_COMPILE_STATUS, &compiled);
if(!compiled)
{
std::string FullSource;
for(const auto *str : ShaderStrings)
FullSource.append(str);
std::stringstream ErrorMsgSS;
ErrorMsgSS << "Failed to compile shader file \""<< (CreationAttribs.Desc.Name != nullptr ? CreationAttribs.Desc.Name : "") << '\"' << std::endl;
int infoLogLen = 0;
// The function glGetShaderiv() tells how many bytes to allocate; the length includes the NULL terminator.
glGetShaderiv(ShaderObj, GL_INFO_LOG_LENGTH, &infoLogLen);
std::vector<GLchar> infoLog(infoLogLen);
if (infoLogLen > 0)
{
int charsWritten = 0;
// Get the log. infoLogLen is the size of infoLog. This tells OpenGL how many bytes at maximum it will write
// charsWritten is a return value, specifying how many bytes it actually wrote. One may pass NULL if he
// doesn't care
glGetShaderInfoLog(ShaderObj, infoLogLen, &charsWritten, infoLog.data());
VERIFY(charsWritten == infoLogLen-1, "Unexpected info log length");
ErrorMsgSS << "InfoLog:" << std::endl << infoLog.data() << std::endl;
}
if (CreationAttribs.ppCompilerOutput != nullptr)
{
// infoLogLen accounts for null terminator
auto *pOutputDataBlob = MakeNewRCObj<DataBlobImpl>()(infoLogLen + FullSource.length() + 1);
char* DataPtr = reinterpret_cast<char*>(pOutputDataBlob->GetDataPtr());
memcpy(DataPtr, !infoLog.empty() ? infoLog.data() : nullptr, infoLogLen);
memcpy(DataPtr + infoLogLen, FullSource.data(), FullSource.length() + 1);
pOutputDataBlob->QueryInterface(IID_DataBlob, reinterpret_cast<IObject**>(CreationAttribs.ppCompilerOutput));
}
else
{
// Dump full source code to debug output
LOG_INFO_MESSAGE("Failed shader full source: \n\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n", FullSource, "\n<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n\n");
}
LOG_ERROR_AND_THROW(ErrorMsgSS.str().c_str());
}
auto DeviceCaps = pDeviceGL->GetDeviceCaps();
if( DeviceCaps.bSeparableProgramSupported )
{
m_GlProgObj.Create();
// GL_PROGRAM_SEPARABLE parameter must be set before linking!
glProgramParameteri( m_GlProgObj, GL_PROGRAM_SEPARABLE, GL_TRUE );
glAttachShader( m_GlProgObj, ShaderObj );
//With separable program objects, interfaces between shader stages may
//involve the outputs from one program object and the inputs from a
//second program object. For such interfaces, it is not possible to
//detect mismatches at link time, because the programs are linked
//separately. When each such program is linked, all inputs or outputs
//interfacing with another program stage are treated as active. The
//linker will generate an executable that assumes the presence of a
//compatible program on the other side of the interface. If a mismatch
//between programs occurs, no GL error will be generated, but some or all
//of the inputs on the interface will be undefined.
glLinkProgram( m_GlProgObj );
CHECK_GL_ERROR( "glLinkProgram() failed" );
int IsLinked = GL_FALSE;
glGetProgramiv( m_GlProgObj, GL_LINK_STATUS, (int *)&IsLinked );
CHECK_GL_ERROR( "glGetProgramiv() failed" );
if( !IsLinked )
{
int LengthWithNull = 0, Length = 0;
// Notice that glGetProgramiv is used to get the length for a shader program, not glGetShaderiv.
// The length of the info log includes a null terminator.
glGetProgramiv( m_GlProgObj, GL_INFO_LOG_LENGTH, &LengthWithNull );
// The maxLength includes the NULL character
std::vector<char> shaderProgramInfoLog( LengthWithNull );
// Notice that glGetProgramInfoLog is used, not glGetShaderInfoLog.
glGetProgramInfoLog( m_GlProgObj, LengthWithNull, &Length, &shaderProgramInfoLog[0] );
VERIFY( Length == LengthWithNull-1, "Incorrect program info log len" );
LOG_ERROR_AND_THROW( "Failed to link shader program:\n", &shaderProgramInfoLog[0], '\n');
}
glDetachShader( m_GlProgObj, ShaderObj );
// glDeleteShader() deletes the shader immediately if it is not attached to any program
// object. Otherwise, the shader is flagged for deletion and will be deleted when it is
// no longer attached to any program object. If an object is flagged for deletion, its
// boolean status bit DELETE_STATUS is set to true
ShaderObj.Release();
m_GlProgObj.InitResources(pDeviceGL, m_Desc.DefaultVariableType, m_Desc.VariableDesc, m_Desc.NumVariables, m_Desc.StaticSamplers, m_Desc.NumStaticSamplers, *this);
}
else
{
m_GLShaderObj = std::move( ShaderObj );
}
}
ShaderGLImpl::~ShaderGLImpl()
{
}
IMPLEMENT_QUERY_INTERFACE( ShaderGLImpl, IID_ShaderGL, TShaderBase )
void ShaderGLImpl::BindResources( IResourceMapping* pResourceMapping, Uint32 Flags )
{
if( static_cast<GLuint>(m_GlProgObj) )
{
m_GlProgObj.BindConstantResources( pResourceMapping, Flags );
}
else
{
static bool FirstTime = true;
if( FirstTime )
{
LOG_WARNING_MESSAGE( "IShader::BindResources() effectively does nothing when separable programs are not supported by the device. Use IDeviceContext::BindShaderResources() instead." );
FirstTime = false;
}
}
}
IShaderVariable* ShaderGLImpl::GetShaderVariable( const Char* Name )
{
DEV_CHECK_ERR(m_GlProgObj, "Shader variable queries are currently supported for separable programs only");
if( m_GlProgObj )
return m_GlProgObj.GetConstantResources().GetShaderVariable(Name);
else
return nullptr;
}
Uint32 ShaderGLImpl::GetVariableCount() const
{
DEV_CHECK_ERR(m_GlProgObj, "Shader variable queries are currently supported for separable programs only");
if( m_GlProgObj )
return m_GlProgObj.GetConstantResources().GetVariableCount();
else
return 0;
}
IShaderVariable* ShaderGLImpl::GetShaderVariable(Uint32 Index)
{
DEV_CHECK_ERR(m_GlProgObj, "Shader variable queries are currently supported for separable programs only");
if( m_GlProgObj )
return m_GlProgObj.GetConstantResources().GetShaderVariable(Index);
else
return 0;
}
}
<commit_msg>Fixed one more gcc warning<commit_after>/* Copyright 2015-2018 Egor Yusov
*
* 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
*
* 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 OF ANY PROPRIETARY RIGHTS.
*
* In no event and under no legal theory, whether in tort (including negligence),
* contract, or otherwise, unless required by applicable law (such as deliberate
* and grossly negligent acts) or agreed to in writing, shall any Contributor be
* liable for any damages, including any direct, indirect, special, incidental,
* or consequential damages of any character arising as a result of this License or
* out of the use or inability to use the software (including but not limited to damages
* for loss of goodwill, work stoppage, computer failure or malfunction, or any and
* all other commercial damages or losses), even if such Contributor has been advised
* of the possibility of such damages.
*/
#include "pch.h"
#include "ShaderGLImpl.h"
#include "RenderDeviceGLImpl.h"
#include "DataBlobImpl.h"
#include "GLSLSourceBuilder.h"
using namespace Diligent;
namespace Diligent
{
ShaderGLImpl::ShaderGLImpl(IReferenceCounters *pRefCounters, RenderDeviceGLImpl *pDeviceGL, const ShaderCreationAttribs &CreationAttribs, bool bIsDeviceInternal) :
TShaderBase( pRefCounters, pDeviceGL, CreationAttribs.Desc, bIsDeviceInternal ),
m_GlProgObj(false),
m_GLShaderObj( false, GLObjectWrappers::GLShaderObjCreateReleaseHelper( GetGLShaderType( m_Desc.ShaderType ) ) )
{
auto GLSLSource = BuildGLSLSourceString(CreationAttribs, TargetGLSLCompiler::driver);
// Note: there is a simpler way to create the program:
//m_uiShaderSeparateProg = glCreateShaderProgramv(GL_VERTEX_SHADER, _countof(ShaderStrings), ShaderStrings);
// NOTE: glCreateShaderProgramv() is considered equivalent to both a shader compilation and a program linking
// operation. Since it performs both at the same time, compiler or linker errors can be encountered. However,
// since this function only returns a program object, compiler-type errors will be reported as linker errors
// through the following API:
// GLint isLinked = 0;
// glGetProgramiv(program, GL_LINK_STATUS, &isLinked);
// The log can then be queried in the same way
// Create empty shader object
auto GLShaderType = GetGLShaderType(m_Desc.ShaderType);
GLObjectWrappers::GLShaderObj ShaderObj(true, GLObjectWrappers::GLShaderObjCreateReleaseHelper(GLShaderType));
// Each element in the length array may contain the length of the corresponding string
// (the null character is not counted as part of the string length).
// Not specifying lengths causes shader compilation errors on Android
const char * ShaderStrings[] = { GLSLSource.c_str() };
GLint Lenghts[] = { static_cast<GLint>(GLSLSource.length()) };
// Provide source strings (the strings will be saved in internal OpenGL memory)
glShaderSource(ShaderObj, _countof(ShaderStrings), ShaderStrings, Lenghts );
// When the shader is compiled, it will be compiled as if all of the given strings were concatenated end-to-end.
glCompileShader(ShaderObj);
GLint compiled = GL_FALSE;
// Get compilation status
glGetShaderiv(ShaderObj, GL_COMPILE_STATUS, &compiled);
if(!compiled)
{
std::string FullSource;
for(const auto *str : ShaderStrings)
FullSource.append(str);
std::stringstream ErrorMsgSS;
ErrorMsgSS << "Failed to compile shader file \""<< (CreationAttribs.Desc.Name != nullptr ? CreationAttribs.Desc.Name : "") << '\"' << std::endl;
int infoLogLen = 0;
// The function glGetShaderiv() tells how many bytes to allocate; the length includes the NULL terminator.
glGetShaderiv(ShaderObj, GL_INFO_LOG_LENGTH, &infoLogLen);
std::vector<GLchar> infoLog(infoLogLen);
if (infoLogLen > 0)
{
int charsWritten = 0;
// Get the log. infoLogLen is the size of infoLog. This tells OpenGL how many bytes at maximum it will write
// charsWritten is a return value, specifying how many bytes it actually wrote. One may pass NULL if he
// doesn't care
glGetShaderInfoLog(ShaderObj, infoLogLen, &charsWritten, infoLog.data());
VERIFY(charsWritten == infoLogLen-1, "Unexpected info log length");
ErrorMsgSS << "InfoLog:" << std::endl << infoLog.data() << std::endl;
}
if (CreationAttribs.ppCompilerOutput != nullptr)
{
// infoLogLen accounts for null terminator
auto *pOutputDataBlob = MakeNewRCObj<DataBlobImpl>()(infoLogLen + FullSource.length() + 1);
char* DataPtr = reinterpret_cast<char*>(pOutputDataBlob->GetDataPtr());
if (infoLogLen > 0)
memcpy(DataPtr, infoLog.data(), infoLogLen);
memcpy(DataPtr + infoLogLen, FullSource.data(), FullSource.length() + 1);
pOutputDataBlob->QueryInterface(IID_DataBlob, reinterpret_cast<IObject**>(CreationAttribs.ppCompilerOutput));
}
else
{
// Dump full source code to debug output
LOG_INFO_MESSAGE("Failed shader full source: \n\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n", FullSource, "\n<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n\n");
}
LOG_ERROR_AND_THROW(ErrorMsgSS.str().c_str());
}
auto DeviceCaps = pDeviceGL->GetDeviceCaps();
if( DeviceCaps.bSeparableProgramSupported )
{
m_GlProgObj.Create();
// GL_PROGRAM_SEPARABLE parameter must be set before linking!
glProgramParameteri( m_GlProgObj, GL_PROGRAM_SEPARABLE, GL_TRUE );
glAttachShader( m_GlProgObj, ShaderObj );
//With separable program objects, interfaces between shader stages may
//involve the outputs from one program object and the inputs from a
//second program object. For such interfaces, it is not possible to
//detect mismatches at link time, because the programs are linked
//separately. When each such program is linked, all inputs or outputs
//interfacing with another program stage are treated as active. The
//linker will generate an executable that assumes the presence of a
//compatible program on the other side of the interface. If a mismatch
//between programs occurs, no GL error will be generated, but some or all
//of the inputs on the interface will be undefined.
glLinkProgram( m_GlProgObj );
CHECK_GL_ERROR( "glLinkProgram() failed" );
int IsLinked = GL_FALSE;
glGetProgramiv( m_GlProgObj, GL_LINK_STATUS, (int *)&IsLinked );
CHECK_GL_ERROR( "glGetProgramiv() failed" );
if( !IsLinked )
{
int LengthWithNull = 0, Length = 0;
// Notice that glGetProgramiv is used to get the length for a shader program, not glGetShaderiv.
// The length of the info log includes a null terminator.
glGetProgramiv( m_GlProgObj, GL_INFO_LOG_LENGTH, &LengthWithNull );
// The maxLength includes the NULL character
std::vector<char> shaderProgramInfoLog( LengthWithNull );
// Notice that glGetProgramInfoLog is used, not glGetShaderInfoLog.
glGetProgramInfoLog( m_GlProgObj, LengthWithNull, &Length, &shaderProgramInfoLog[0] );
VERIFY( Length == LengthWithNull-1, "Incorrect program info log len" );
LOG_ERROR_AND_THROW( "Failed to link shader program:\n", &shaderProgramInfoLog[0], '\n');
}
glDetachShader( m_GlProgObj, ShaderObj );
// glDeleteShader() deletes the shader immediately if it is not attached to any program
// object. Otherwise, the shader is flagged for deletion and will be deleted when it is
// no longer attached to any program object. If an object is flagged for deletion, its
// boolean status bit DELETE_STATUS is set to true
ShaderObj.Release();
m_GlProgObj.InitResources(pDeviceGL, m_Desc.DefaultVariableType, m_Desc.VariableDesc, m_Desc.NumVariables, m_Desc.StaticSamplers, m_Desc.NumStaticSamplers, *this);
}
else
{
m_GLShaderObj = std::move( ShaderObj );
}
}
ShaderGLImpl::~ShaderGLImpl()
{
}
IMPLEMENT_QUERY_INTERFACE( ShaderGLImpl, IID_ShaderGL, TShaderBase )
void ShaderGLImpl::BindResources( IResourceMapping* pResourceMapping, Uint32 Flags )
{
if( static_cast<GLuint>(m_GlProgObj) )
{
m_GlProgObj.BindConstantResources( pResourceMapping, Flags );
}
else
{
static bool FirstTime = true;
if( FirstTime )
{
LOG_WARNING_MESSAGE( "IShader::BindResources() effectively does nothing when separable programs are not supported by the device. Use IDeviceContext::BindShaderResources() instead." );
FirstTime = false;
}
}
}
IShaderVariable* ShaderGLImpl::GetShaderVariable( const Char* Name )
{
DEV_CHECK_ERR(m_GlProgObj, "Shader variable queries are currently supported for separable programs only");
if( m_GlProgObj )
return m_GlProgObj.GetConstantResources().GetShaderVariable(Name);
else
return nullptr;
}
Uint32 ShaderGLImpl::GetVariableCount() const
{
DEV_CHECK_ERR(m_GlProgObj, "Shader variable queries are currently supported for separable programs only");
if( m_GlProgObj )
return m_GlProgObj.GetConstantResources().GetVariableCount();
else
return 0;
}
IShaderVariable* ShaderGLImpl::GetShaderVariable(Uint32 Index)
{
DEV_CHECK_ERR(m_GlProgObj, "Shader variable queries are currently supported for separable programs only");
if( m_GlProgObj )
return m_GlProgObj.GetConstantResources().GetShaderVariable(Index);
else
return 0;
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: viewcontactofe3dscene.cxx,v $
* $Revision: 1.9 $
*
* 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.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svx.hxx"
#include <svx/sdr/contact/viewcontactofe3dscene.hxx>
#include <svx/polysc3d.hxx>
#include <svx/sdr/contact/displayinfo.hxx>
//////////////////////////////////////////////////////////////////////////////
namespace sdr
{
namespace contact
{
// method to recalculate the PaintRectangle if the validity flag shows that
// it is invalid. The flag is set from GetPaintRectangle, thus the implementation
// only needs to refresh maPaintRectangle itself.
void ViewContactOfE3dScene::CalcPaintRectangle()
{
maPaintRectangle = GetE3dScene().GetCurrentBoundRect();
}
ViewContactOfE3dScene::ViewContactOfE3dScene(E3dScene& rScene)
: ViewContactOfSdrObj(rScene)
{
}
ViewContactOfE3dScene::~ViewContactOfE3dScene()
{
}
// When ShouldPaintObject() returns sal_True, the object itself is painted and
// PaintObject() is called.
sal_Bool ViewContactOfE3dScene::ShouldPaintObject(DisplayInfo& rDisplayInfo, const ViewObjectContact& /*rAssociatedVOC*/)
{
// Test layer visibility, force to flat SdrObject here for 3D (!)
if(!rDisplayInfo.GetProcessLayers().IsSet(GetSdrObject().SdrObject::GetLayer()))
{
return sal_False;
}
// Test area visibility
const Region& rRedrawArea = rDisplayInfo.GetRedrawArea();
if(!rRedrawArea.IsEmpty() && !rRedrawArea.IsOver(GetPaintRectangle()))
{
return sal_False;
}
// Test calc hide/draft features
if(!DoPaintForCalc(rDisplayInfo))
{
return sal_False;
}
// Always paint E3dScenes
return sal_True;
}
// These methods decide which parts of the objects will be painted:
// When ShouldPaintDrawHierarchy() returns sal_True, the DrawHierarchy of the object is painted.
// Else, the flags and rectangles of the VOCs of the sub-hierarchy are set to the values of the
// object's VOC.
sal_Bool ViewContactOfE3dScene::ShouldPaintDrawHierarchy(DisplayInfo& /*rDisplayInfo*/, const ViewObjectContact& /*rAssociatedVOC*/)
{
// 3D Scenes do draw their hierarchy themselves, so switch off
// painting DrawHierarchy.
return sal_False;
}
// Paint this object. This is before evtl. SubObjects get painted. It needs to return
// sal_True when something was pained and the paint output rectangle in rPaintRectangle.
sal_Bool ViewContactOfE3dScene::PaintObject(DisplayInfo& rDisplayInfo, Rectangle& rPaintRectangle, const ViewObjectContact& /*rAssociatedVOC*/)
{
sal_Bool bRetval(sal_False);
if(GetE3dScene().GetSubList() && GetE3dScene().GetSubList()->GetObjCount())
{
// copy the saved original PaintMode from the DisplayInfo to the old
// structures so that it is available for the old 3D rendering.
rDisplayInfo.GetPaintInfoRec()->nOriginalDrawMode = rDisplayInfo.GetOriginalDrawMode();
rDisplayInfo.GetPaintInfoRec()->bNotActive = rDisplayInfo.IsGhostedDrawModeActive();
// Paint the 3D scene. Just hand over to the old Paint() ATM.
GetSdrObject().DoPaintObject(
*rDisplayInfo.GetExtendedOutputDevice(),
*rDisplayInfo.GetPaintInfoRec());
rPaintRectangle = GetPaintRectangle();
bRetval = sal_True;
}
else
{
// Paint a replacement object.
bRetval = PaintReplacementObject(rDisplayInfo, rPaintRectangle);
}
return bRetval;
}
} // end of namespace contact
} // end of namespace sdr
//////////////////////////////////////////////////////////////////////////////
// eof
<commit_msg>INTEGRATION: CWS aw033 (1.4.16); FILE MERGED 2008/06/24 15:42:24 aw 1.4.16.22: #i39532# corrections 2008/06/10 09:31:40 aw 1.4.16.21: #i39532# changed 3d primitive stuff to use viewinformation3d 2008/05/27 14:49:57 aw 1.4.16.20: #i39532# changes DEV300 m12 resync corrections 2008/05/14 14:00:41 aw 1.4.16.19: RESYNC: (1.8-1.9); FILE MERGED 2008/05/14 09:55:15 aw 1.4.16.18: #i39532# aw033 progresses from git 2008/03/19 04:33:35 aw 1.4.16.17: #i39532# chart adaptions for 3D 2008/03/13 08:22:28 aw 1.4.16.16: #i39532# diverse support for chart2 2008/01/29 10:27:32 aw 1.4.16.15: updated refresh for ActionChanged(), diverse removals 2008/01/22 12:29:29 aw 1.4.16.14: adaptions and 1st stripping 2007/12/03 16:40:02 aw 1.4.16.13: RESYNC: (1.7-1.8); FILE MERGED 2007/08/09 18:46:15 aw 1.4.16.12: RESYNC: (1.6-1.7); FILE MERGED 2007/07/06 13:43:07 aw 1.4.16.11: #i39532# moved from Primitive2DReference to Primitive2DSequence where possible to avoid extra-group primitive creations and deeper hierarchies as necessary 2007/01/25 12:47:05 aw 1.4.16.10: #i39532# change 3D scene content generation to be usable from API implementation, too 2006/12/11 17:40:57 aw 1.4.16.9: #i39532# changes after resync 2006/11/28 11:17:54 aw 1.4.16.8: #i39532# 2006/11/07 15:52:20 aw 1.4.16.7: #i39532# changed various aspevcts of XPrimitive2D implementations 2006/10/19 10:59:13 aw 1.4.16.6: #i39532# primitive 2006/09/27 16:40:58 aw 1.4.16.5: #i39532# changes after resync to m185 2006/09/26 19:20:50 aw 1.4.16.4: RESYNC: (1.4-1.6); FILE MERGED 2006/08/09 17:12:23 aw 1.4.16.3: #i39532# 2006/06/02 14:17:49 aw 1.4.16.2: #i39532# adaptions to new primitives, error corrections 2006/05/12 12:46:22 aw 1.4.16.1: code changes for primitive support<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: viewcontactofe3dscene.cxx,v $
* $Revision: 1.10 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svx.hxx"
#include <svx/sdr/contact/viewcontactofe3dscene.hxx>
#include <svx/polysc3d.hxx>
#include <svx/sdr/contact/displayinfo.hxx>
#include <svx/sdr/contact/viewobjectcontact.hxx>
#include <basegfx/polygon/b2dpolygontools.hxx>
#include <basegfx/color/bcolor.hxx>
#include <drawinglayer/primitive2d/polygonprimitive2d.hxx>
#include <svx/sdr/primitive2d/sdrattributecreator.hxx>
#include <svx/sdr/contact/viewobjectcontactofe3dscene.hxx>
#include <basegfx/matrix/b2dhommatrix.hxx>
#include <basegfx/range/b3drange.hxx>
#include <drawinglayer/attribute/sdrattribute3d.hxx>
#include <drawinglayer/primitive3d/baseprimitive3d.hxx>
#include <svx/sdr/contact/viewcontactofe3d.hxx>
#include <drawinglayer/primitive2d/sceneprimitive2d.hxx>
#include <drawinglayer/primitive3d/transformprimitive3d.hxx>
//////////////////////////////////////////////////////////////////////////////
using namespace com::sun::star;
//////////////////////////////////////////////////////////////////////////////
namespace
{
// pActiveVC is only true if ghosted is still activated and maybe needs to be switched off in this path
void createSubPrimitive3DVector(
const sdr::contact::ViewContact& rCandidate,
drawinglayer::primitive3d::Primitive3DSequence& o_rAllTarget,
drawinglayer::primitive3d::Primitive3DSequence* o_pVisibleTarget,
const SetOfByte* pVisibleLayerSet,
const bool bTestSelectedVisibility)
{
const sdr::contact::ViewContactOfE3dScene* pViewContactOfE3dScene = dynamic_cast< const sdr::contact::ViewContactOfE3dScene* >(&rCandidate);
if(pViewContactOfE3dScene)
{
const sal_uInt32 nChildrenCount(rCandidate.GetObjectCount());
if(nChildrenCount)
{
// provide new collection sequences
drawinglayer::primitive3d::Primitive3DSequence aNewAllTarget;
drawinglayer::primitive3d::Primitive3DSequence aNewVisibleTarget;
// add children recursively
for(sal_uInt32 a(0L); a < nChildrenCount; a++)
{
createSubPrimitive3DVector(
rCandidate.GetViewContact(a),
aNewAllTarget,
o_pVisibleTarget ? &aNewVisibleTarget : 0,
pVisibleLayerSet,
bTestSelectedVisibility);
}
// create transform primitive for the created content combining content and transformtion
const drawinglayer::primitive3d::Primitive3DReference xReference(new drawinglayer::primitive3d::TransformPrimitive3D(
pViewContactOfE3dScene->GetE3dScene().GetTransform(),
aNewAllTarget));
// add created content to all target
drawinglayer::primitive3d::appendPrimitive3DReferenceToPrimitive3DSequence(o_rAllTarget, xReference);
// add created content to visibiel target if exists
if(o_pVisibleTarget)
{
drawinglayer::primitive3d::appendPrimitive3DReferenceToPrimitive3DSequence(*o_pVisibleTarget, xReference);
}
}
}
else
{
// access view independent representation of rCandidate
const sdr::contact::ViewContactOfE3d* pViewContactOfE3d = dynamic_cast< const sdr::contact::ViewContactOfE3d* >(&rCandidate);
if(pViewContactOfE3d)
{
drawinglayer::primitive3d::Primitive3DSequence xPrimitive3DSeq(pViewContactOfE3d->getViewIndependentPrimitive3DSequence());
if(xPrimitive3DSeq.hasElements())
{
// add to all target vector
drawinglayer::primitive3d::appendPrimitive3DSequenceToPrimitive3DSequence(o_rAllTarget, xPrimitive3DSeq);
if(o_pVisibleTarget)
{
// test visibility. Primitive is visible when both tests are true (AND)
bool bVisible(true);
if(pVisibleLayerSet)
{
// test layer visibility
const E3dObject& rE3dObject = pViewContactOfE3d->GetE3dObject();
const SdrLayerID aLayerID(rE3dObject.GetLayer());
bVisible = pVisibleLayerSet->IsSet(aLayerID);
}
if(bVisible && bTestSelectedVisibility)
{
// test selected visibility (see 3D View's DrawMarkedObj implementation)
const E3dObject& rE3dObject = pViewContactOfE3d->GetE3dObject();
bVisible = rE3dObject.GetSelected();
}
if(bVisible && o_pVisibleTarget)
{
// add to visible target vector
drawinglayer::primitive3d::appendPrimitive3DSequenceToPrimitive3DSequence(*o_pVisibleTarget, xPrimitive3DSeq);
}
}
}
}
}
}
} // end of anonymous namespace
//////////////////////////////////////////////////////////////////////////////
namespace sdr
{
namespace contact
{
// Create a Object-Specific ViewObjectContact, set ViewContact and
// ObjectContact. Always needs to return something.
ViewObjectContact& ViewContactOfE3dScene::CreateObjectSpecificViewObjectContact(ObjectContact& rObjectContact)
{
ViewObjectContact* pRetval = new ViewObjectContactOfE3dScene(rObjectContact, *this);
DBG_ASSERT(pRetval, "ViewContactOfE3dScene::CreateObjectSpecificViewObjectContact() failed (!)");
return *pRetval;
}
ViewContactOfE3dScene::ViewContactOfE3dScene(E3dScene& rScene)
: ViewContactOfSdrObj(rScene),
mpViewInformation3D(0),
mpObjectTransformation(0),
mpSdrSceneAttribute(0),
mpSdrLightingAttribute(0)
{
}
ViewContactOfE3dScene::~ViewContactOfE3dScene()
{
delete mpViewInformation3D;
delete mpObjectTransformation;
delete mpSdrSceneAttribute;
delete mpSdrLightingAttribute;
}
void ViewContactOfE3dScene::createViewInformation3D(const basegfx::B3DRange& rContentRange)
{
basegfx::B3DHomMatrix aTransformation;
basegfx::B3DHomMatrix aOrientation;
basegfx::B3DHomMatrix aProjection;
basegfx::B3DHomMatrix aDeviceToView;
// create transformation (scene as group's transformation)
// For historical reasons, the outmost scene's transformation is handles as part of the
// view transformation. This means that the BoundRect of the contained 3D Objects is
// without that transformation and makes it necessary to NOT add the first scene to the
// Primitive3DSequence of contained objects.
{
aTransformation = GetE3dScene().GetTransform();
}
// create orientation (world to camera coordinate system)
{
// calculate orientation from VRP, VPN and VUV
const B3dCamera& rSceneCamera = GetE3dScene().GetCameraSet();
const basegfx::B3DPoint aVRP(rSceneCamera.GetVRP());
const basegfx::B3DVector aVPN(rSceneCamera.GetVRP());
const basegfx::B3DVector aVUV(rSceneCamera.GetVUV());
aOrientation.orientation(aVRP, aVPN, aVUV);
}
// create projection (camera coordinate system to relative 2d where X,Y and Z are [0.0 .. 1.0])
{
const basegfx::B3DHomMatrix aWorldToCamera(aOrientation * aTransformation);
basegfx::B3DRange aCameraRange(rContentRange);
aCameraRange.transform(aWorldToCamera);
// remember Z-Values, but change orientation
const double fMinZ(-aCameraRange.getMaxZ());
const double fMaxZ(-aCameraRange.getMinZ());
// construct temorary matrix from world to device. Use unit values here to measure expansion
basegfx::B3DHomMatrix aWorldToDevice(aWorldToCamera);
const drawinglayer::attribute::SdrSceneAttribute& rSdrSceneAttribute = getSdrSceneAttribute();
if(::com::sun::star::drawing::ProjectionMode_PERSPECTIVE == rSdrSceneAttribute.getProjectionMode())
{
aWorldToDevice.frustum(-1.0, 1.0, -1.0, 1.0, fMinZ, fMaxZ);
}
else
{
aWorldToDevice.ortho(-1.0, 1.0, -1.0, 1.0, fMinZ, fMaxZ);
}
// create B3DRange in device. This will create the real used ranges
// in camera space. Do not use the Z-Values, though.
basegfx::B3DRange aDeviceRange(rContentRange);
aDeviceRange.transform(aWorldToDevice);
// set projection
if(::com::sun::star::drawing::ProjectionMode_PERSPECTIVE == rSdrSceneAttribute.getProjectionMode())
{
aProjection.frustum(
aDeviceRange.getMinX(), aDeviceRange.getMaxX(),
aDeviceRange.getMinY(), aDeviceRange.getMaxY(),
fMinZ, fMaxZ);
}
else
{
aProjection.ortho(
aDeviceRange.getMinX(), aDeviceRange.getMaxX(),
aDeviceRange.getMinY(), aDeviceRange.getMaxY(),
fMinZ, fMaxZ);
}
}
// create device to view transform
{
// create standard deviceToView projection for geometry
// input is [-1.0 .. 1.0] in X,Y and Z. bring to [0.0 .. 1.0]. Also
// necessary to flip Y due to screen orientation
// Z is not needed, but will also be brought to [0.0 .. 1.0]
aDeviceToView.scale(0.5, -0.5, 0.5);
aDeviceToView.translate(0.5, 0.5, 0.5);
}
const uno::Sequence< beans::PropertyValue > aEmptyProperties;
mpViewInformation3D = new drawinglayer::geometry::ViewInformation3D(aTransformation, aOrientation, aProjection, aDeviceToView, 0.0, aEmptyProperties);
}
void ViewContactOfE3dScene::createObjectTransformation()
{
// create 2d Object Transformation from relative point in 2d scene to world
mpObjectTransformation = new basegfx::B2DHomMatrix;
const Rectangle& rRectangle = GetE3dScene().GetSnapRect();
mpObjectTransformation->set(0, 0, rRectangle.getWidth());
mpObjectTransformation->set(1, 1, rRectangle.getHeight());
mpObjectTransformation->set(0, 2, rRectangle.Left());
mpObjectTransformation->set(1, 2, rRectangle.Top());
}
void ViewContactOfE3dScene::createSdrSceneAttribute()
{
const SfxItemSet& rItemSet = GetE3dScene().GetMergedItemSet();
mpSdrSceneAttribute = drawinglayer::primitive2d::createNewSdrSceneAttribute(rItemSet);
}
void ViewContactOfE3dScene::createSdrLightingAttribute()
{
const SfxItemSet& rItemSet = GetE3dScene().GetMergedItemSet();
mpSdrLightingAttribute = drawinglayer::primitive2d::createNewSdrLightingAttribute(rItemSet, GetE3dScene().GetLightGroup());
}
drawinglayer::primitive2d::Primitive2DSequence ViewContactOfE3dScene::createScenePrimitive2DSequence(const SetOfByte* pLayerVisibility) const
{
drawinglayer::primitive2d::Primitive2DSequence xRetval;
const sal_uInt32 nChildrenCount(GetObjectCount());
if(nChildrenCount)
{
// create 3d scene primitive with visible content tested against rLayerVisibility
drawinglayer::primitive3d::Primitive3DSequence aAllSequence;
drawinglayer::primitive3d::Primitive3DSequence aVisibleSequence;
const bool bTestLayerVisibility(0 != pLayerVisibility);
const bool bTestSelectedVisibility(GetE3dScene().DoDrawOnlySelected());
const bool bTestVisibility(bTestLayerVisibility || bTestSelectedVisibility);
// add children recursively. Do NOT start with (*this), this would create
// a 3D transformPrimitive for the start scene. While this is theoretically not
// a bad thing, for historical reasons the transformation of the outmost scene
// is seen as part of the ViewTransformation (see text in createViewInformation3D)
for(sal_uInt32 a(0L); a < nChildrenCount; a++)
{
createSubPrimitive3DVector(
GetViewContact(a),
aAllSequence,
bTestLayerVisibility ? &aVisibleSequence : 0,
bTestLayerVisibility ? pLayerVisibility : 0,
bTestSelectedVisibility);
}
const sal_uInt32 nAllSize(aAllSequence.hasElements() ? aAllSequence.getLength() : 0);
const sal_uInt32 nVisibleSize(aVisibleSequence.hasElements() ? aVisibleSequence.getLength() : 0);
if((bTestVisibility && nVisibleSize) || nAllSize)
{
// for getting the 3D range using getB3DRangeFromPrimitive3DSequence a ViewInformation3D
// needs to be given for evtl. decompositions. At the same time createViewInformation3D
// currently is based on creating the target-ViewInformation3D using a given range. To
// get the true range, use a neutral ViewInformation3D here. This leaves all matrices
// on identity and the time on 0.0.
const uno::Sequence< beans::PropertyValue > aEmptyProperties;
const drawinglayer::geometry::ViewInformation3D aNeutralViewInformation3D(aEmptyProperties);
const basegfx::B3DRange aContentRange(drawinglayer::primitive3d::getB3DRangeFromPrimitive3DSequence(aAllSequence, aNeutralViewInformation3D));
// create 2d primitive 3dscene with generated sub-list from collector
const drawinglayer::primitive2d::Primitive2DReference xReference(new drawinglayer::primitive2d::ScenePrimitive2D(
bTestVisibility ? aVisibleSequence : aAllSequence,
getSdrSceneAttribute(),
getSdrLightingAttribute(),
getObjectTransformation(),
getViewInformation3D(aContentRange)));
xRetval = drawinglayer::primitive2d::Primitive2DSequence(&xReference, 1);
}
}
return xRetval;
}
drawinglayer::primitive2d::Primitive2DSequence ViewContactOfE3dScene::createViewIndependentPrimitive2DSequence() const
{
drawinglayer::primitive2d::Primitive2DSequence xRetval;
if(GetObjectCount())
{
// create a default ScenePrimitive2D (without visibility test of members)
xRetval = createScenePrimitive2DSequence(0);
}
if(xRetval.hasElements())
{
return xRetval;
}
else
{
// create a gray placeholder hairline polygon in object size as empty 3D scene marker. Use object size
// model information directly, NOT getBoundRect()/getSnapRect() since these will
// be using the geometry data we get just asked for. AFAIK for empty 3D Scenes, the model data
// is SdrObject::aOutRect which i can access directly using GetLastBoundRect() here
const Rectangle aEmptySceneGeometry(GetE3dScene().GetLastBoundRect());
const basegfx::B2DPolygon aOutline(basegfx::tools::createPolygonFromRect(basegfx::B2DRange(
aEmptySceneGeometry.Left(), aEmptySceneGeometry.Top(),
aEmptySceneGeometry.Right(), aEmptySceneGeometry.Bottom())));
const double fGrayTone(0xc0 / 255.0);
const basegfx::BColor aGrayTone(fGrayTone, fGrayTone, fGrayTone);
const drawinglayer::primitive2d::Primitive2DReference xReference(new drawinglayer::primitive2d::PolygonHairlinePrimitive2D(aOutline, aGrayTone));
// The replacement object may also get a text like 'empty 3D Scene' here later
return drawinglayer::primitive2d::Primitive2DSequence(&xReference, 1);
}
}
void ViewContactOfE3dScene::ActionChanged()
{
// call parent
ViewContactOfSdrObj::ActionChanged();
// mark locally cached values as invalid
delete mpViewInformation3D;
mpViewInformation3D = 0;
delete mpObjectTransformation;
mpObjectTransformation = 0;
delete mpSdrSceneAttribute;
mpSdrSceneAttribute = 0;
delete mpSdrLightingAttribute;
mpSdrLightingAttribute = 0;
}
const drawinglayer::geometry::ViewInformation3D& ViewContactOfE3dScene::getViewInformation3D() const
{
if(!mpViewInformation3D)
{
// this version will create the content range on demand locally and thus is less
// performant than the other one. Since the information is buffered the planned
// behaviour is that the version with the given range is used initially.
basegfx::B3DRange aContentRange(getAllContentRange3D());
if(aContentRange.isEmpty())
{
// empty scene, no 3d action should be necessary. Prepare some
// fallback size
OSL_ENSURE(false, "No need to get ViewInformation3D from an empty scene (!)");
aContentRange.expand(basegfx::B3DPoint(-100.0, -100.0, -100.0));
aContentRange.expand(basegfx::B3DPoint( 100.0, 100.0, 100.0));
}
const_cast < ViewContactOfE3dScene* >(this)->createViewInformation3D(aContentRange);
}
return *mpViewInformation3D;
}
const drawinglayer::geometry::ViewInformation3D& ViewContactOfE3dScene::getViewInformation3D(const basegfx::B3DRange& rContentRange) const
{
if(!mpViewInformation3D)
{
const_cast < ViewContactOfE3dScene* >(this)->createViewInformation3D(rContentRange);
}
return *mpViewInformation3D;
}
const basegfx::B2DHomMatrix& ViewContactOfE3dScene::getObjectTransformation() const
{
if(!mpObjectTransformation)
{
const_cast < ViewContactOfE3dScene* >(this)->createObjectTransformation();
}
return *mpObjectTransformation;
}
const drawinglayer::attribute::SdrSceneAttribute& ViewContactOfE3dScene::getSdrSceneAttribute() const
{
if(!mpSdrSceneAttribute)
{
const_cast < ViewContactOfE3dScene* >(this)->createSdrSceneAttribute();
}
return *mpSdrSceneAttribute;
}
const drawinglayer::attribute::SdrLightingAttribute& ViewContactOfE3dScene::getSdrLightingAttribute() const
{
if(!mpSdrLightingAttribute)
{
const_cast < ViewContactOfE3dScene* >(this)->createSdrLightingAttribute();
}
return *mpSdrLightingAttribute;
}
drawinglayer::primitive3d::Primitive3DSequence ViewContactOfE3dScene::getAllPrimitive3DSequence() const
{
drawinglayer::primitive3d::Primitive3DSequence aAllPrimitive3DSequence;
const sal_uInt32 nChildrenCount(GetObjectCount());
// add children recursively. Do NOT start with (*this), this would create
// a 3D transformPrimitive for the start scene. While this is theoretically not
// a bad thing, for historical reasons the transformation of the outmost scene
// is seen as part of the ViewTransformation (see text in createViewInformation3D)
for(sal_uInt32 a(0L); a < nChildrenCount; a++)
{
createSubPrimitive3DVector(GetViewContact(a), aAllPrimitive3DSequence, 0, 0, false);
}
return aAllPrimitive3DSequence;
}
basegfx::B3DRange ViewContactOfE3dScene::getAllContentRange3D() const
{
const drawinglayer::primitive3d::Primitive3DSequence xAllSequence(getAllPrimitive3DSequence());
basegfx::B3DRange aAllContentRange3D;
if(xAllSequence.hasElements())
{
// for getting the 3D range using getB3DRangeFromPrimitive3DSequence a ViewInformation3D
// needs to be given for evtl. decompositions. Use a neutral ViewInformation3D here. This
// leaves all matrices on identity and the time on 0.0.
const uno::Sequence< beans::PropertyValue > aEmptyProperties;
const drawinglayer::geometry::ViewInformation3D aNeutralViewInformation3D(aEmptyProperties);
aAllContentRange3D = drawinglayer::primitive3d::getB3DRangeFromPrimitive3DSequence(xAllSequence, aNeutralViewInformation3D);
}
return aAllContentRange3D;
}
} // end of namespace contact
} // end of namespace sdr
//////////////////////////////////////////////////////////////////////////////
// eof
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: fmtwrapinfluenceonobjpos.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: vg $ $Date: 2007-10-22 15:10:25 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sw.hxx"
#ifndef _FMTWRAPINFLUENCEONOBJPOS_HXX
#include <fmtwrapinfluenceonobjpos.hxx>
#endif
#ifndef _UNOMID_H
#include <unomid.h>
#endif
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
TYPEINIT1(SwFmtWrapInfluenceOnObjPos, SfxPoolItem);
SwFmtWrapInfluenceOnObjPos::SwFmtWrapInfluenceOnObjPos(
sal_Int16 _nWrapInfluenceOnPosition )
: SfxPoolItem( RES_WRAP_INFLUENCE_ON_OBJPOS ),
mnWrapInfluenceOnPosition( _nWrapInfluenceOnPosition )
{
}
SwFmtWrapInfluenceOnObjPos::SwFmtWrapInfluenceOnObjPos(
const SwFmtWrapInfluenceOnObjPos& _rCpy )
: SfxPoolItem( RES_WRAP_INFLUENCE_ON_OBJPOS ),
mnWrapInfluenceOnPosition( _rCpy.GetWrapInfluenceOnObjPos() )
{
}
SwFmtWrapInfluenceOnObjPos::~SwFmtWrapInfluenceOnObjPos()
{
}
SwFmtWrapInfluenceOnObjPos& SwFmtWrapInfluenceOnObjPos::operator=(
const SwFmtWrapInfluenceOnObjPos& _rSource )
{
mnWrapInfluenceOnPosition = _rSource.GetWrapInfluenceOnObjPos();
return *this;
}
int SwFmtWrapInfluenceOnObjPos::operator==( const SfxPoolItem& _rAttr ) const
{
ASSERT( SfxPoolItem::operator==( _rAttr ), "keine gleichen Attribute" );
return ( mnWrapInfluenceOnPosition ==
static_cast<const SwFmtWrapInfluenceOnObjPos&>(_rAttr).
GetWrapInfluenceOnObjPos() );
}
SfxPoolItem* SwFmtWrapInfluenceOnObjPos::Clone( SfxItemPool * ) const
{
return new SwFmtWrapInfluenceOnObjPos(*this);
}
BOOL SwFmtWrapInfluenceOnObjPos::QueryValue( Any& rVal, BYTE nMemberId ) const
{
nMemberId &= ~CONVERT_TWIPS;
sal_Bool bRet = sal_True;
switch ( nMemberId )
{
case MID_WRAP_INFLUENCE:
{
rVal <<= GetWrapInfluenceOnObjPos();
}
break;
default:
ASSERT( false, "<SwFmtWrapInfluenceOnObjPos::QueryValue()> - unknown MemberId" );
bRet = sal_False;
}
return bRet;
}
BOOL SwFmtWrapInfluenceOnObjPos::PutValue( const Any& rVal, BYTE nMemberId )
{
nMemberId &= ~CONVERT_TWIPS;
sal_Bool bRet = sal_True;
switch ( nMemberId )
{
case MID_WRAP_INFLUENCE:
{
sal_Int16 nNewWrapInfluence;
rVal >>= nNewWrapInfluence;
// --> OD 2004-10-18 #i35017# - constant names have changed and
// <ITERATIVE> has been added
if ( nNewWrapInfluence == text::WrapInfluenceOnPosition::ONCE_SUCCESSIVE ||
nNewWrapInfluence == text::WrapInfluenceOnPosition::ONCE_CONCURRENT ||
nNewWrapInfluence == text::WrapInfluenceOnPosition::ITERATIVE )
// <--
{
SetWrapInfluenceOnObjPos( nNewWrapInfluence );
}
else
{
ASSERT( false, "<SwFmtWrapInfluenceOnObjPos::PutValue(..)> - invalid attribute value" );
bRet = sal_False;
}
}
break;
default:
ASSERT( false, "<SwFmtWrapInfluenceOnObjPos::QueryValue()> - unknown MemberId" );
bRet = sal_False;
}
return bRet;
}
void SwFmtWrapInfluenceOnObjPos::SetWrapInfluenceOnObjPos( sal_Int16 _nWrapInfluenceOnPosition )
{
// --> OD 2004-10-18 #i35017# - constant names have changed and consider
// new value <ITERATIVE>
if ( _nWrapInfluenceOnPosition == text::WrapInfluenceOnPosition::ONCE_SUCCESSIVE ||
_nWrapInfluenceOnPosition == text::WrapInfluenceOnPosition::ONCE_CONCURRENT ||
_nWrapInfluenceOnPosition == text::WrapInfluenceOnPosition::ITERATIVE )
// <--
{
mnWrapInfluenceOnPosition = _nWrapInfluenceOnPosition;
}
else
{
ASSERT( false, "<SwFmtWrapInfluenceOnObjPos::SetWrapInfluenceOnObjPos(..)> - invalid attribute value" );
}
}
// --> OD 2004-10-18 #i35017# - add parameter <_bIterativeAsOnceConcurrent>
// to control, if value <ITERATIVE> has to be treated as <ONCE_CONCURRENT>
sal_Int16 SwFmtWrapInfluenceOnObjPos::GetWrapInfluenceOnObjPos(
const bool _bIterativeAsOnceConcurrent ) const
{
sal_Int16 nWrapInfluenceOnPosition( mnWrapInfluenceOnPosition );
if ( _bIterativeAsOnceConcurrent &&
nWrapInfluenceOnPosition == text::WrapInfluenceOnPosition::ITERATIVE )
{
nWrapInfluenceOnPosition = text::WrapInfluenceOnPosition::ONCE_CONCURRENT;
}
return nWrapInfluenceOnPosition;
}
// <--
<commit_msg>INTEGRATION: CWS pj86 (1.6.4); FILE MERGED 2007/11/07 08:09:07 pjanik 1.6.4.2: RESYNC: (1.6-1.7); FILE MERGED 2007/09/28 21:30:43 pjanik 1.6.4.1: *** empty log message ***<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: fmtwrapinfluenceonobjpos.cxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: rt $ $Date: 2007-11-12 16:22:12 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sw.hxx"
#ifndef _FMTWRAPINFLUENCEONOBJPOS_HXX
#include <fmtwrapinfluenceonobjpos.hxx>
#endif
#ifndef _UNOMID_H
#include <unomid.h>
#endif
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
TYPEINIT1(SwFmtWrapInfluenceOnObjPos, SfxPoolItem);
SwFmtWrapInfluenceOnObjPos::SwFmtWrapInfluenceOnObjPos(
sal_Int16 _nWrapInfluenceOnPosition )
: SfxPoolItem( RES_WRAP_INFLUENCE_ON_OBJPOS ),
mnWrapInfluenceOnPosition( _nWrapInfluenceOnPosition )
{
}
SwFmtWrapInfluenceOnObjPos::SwFmtWrapInfluenceOnObjPos(
const SwFmtWrapInfluenceOnObjPos& _rCpy )
: SfxPoolItem( RES_WRAP_INFLUENCE_ON_OBJPOS ),
mnWrapInfluenceOnPosition( _rCpy.GetWrapInfluenceOnObjPos() )
{
}
SwFmtWrapInfluenceOnObjPos::~SwFmtWrapInfluenceOnObjPos()
{
}
SwFmtWrapInfluenceOnObjPos& SwFmtWrapInfluenceOnObjPos::operator=(
const SwFmtWrapInfluenceOnObjPos& _rSource )
{
mnWrapInfluenceOnPosition = _rSource.GetWrapInfluenceOnObjPos();
return *this;
}
int SwFmtWrapInfluenceOnObjPos::operator==( const SfxPoolItem& _rAttr ) const
{
ASSERT( SfxPoolItem::operator==( _rAttr ), "keine gleichen Attribute" );
return ( mnWrapInfluenceOnPosition ==
static_cast<const SwFmtWrapInfluenceOnObjPos&>(_rAttr).
GetWrapInfluenceOnObjPos() );
}
SfxPoolItem* SwFmtWrapInfluenceOnObjPos::Clone( SfxItemPool * ) const
{
return new SwFmtWrapInfluenceOnObjPos(*this);
}
BOOL SwFmtWrapInfluenceOnObjPos::QueryValue( Any& rVal, BYTE nMemberId ) const
{
nMemberId &= ~CONVERT_TWIPS;
sal_Bool bRet = sal_True;
switch ( nMemberId )
{
case MID_WRAP_INFLUENCE:
{
rVal <<= GetWrapInfluenceOnObjPos();
}
break;
default:
ASSERT( false, "<SwFmtWrapInfluenceOnObjPos::QueryValue()> - unknown MemberId" );
bRet = sal_False;
}
return bRet;
}
BOOL SwFmtWrapInfluenceOnObjPos::PutValue( const Any& rVal, BYTE nMemberId )
{
nMemberId &= ~CONVERT_TWIPS;
sal_Bool bRet = sal_True;
switch ( nMemberId )
{
case MID_WRAP_INFLUENCE:
{
sal_Int16 nNewWrapInfluence = 0;
rVal >>= nNewWrapInfluence;
// --> OD 2004-10-18 #i35017# - constant names have changed and
// <ITERATIVE> has been added
if ( nNewWrapInfluence == text::WrapInfluenceOnPosition::ONCE_SUCCESSIVE ||
nNewWrapInfluence == text::WrapInfluenceOnPosition::ONCE_CONCURRENT ||
nNewWrapInfluence == text::WrapInfluenceOnPosition::ITERATIVE )
// <--
{
SetWrapInfluenceOnObjPos( nNewWrapInfluence );
}
else
{
ASSERT( false, "<SwFmtWrapInfluenceOnObjPos::PutValue(..)> - invalid attribute value" );
bRet = sal_False;
}
}
break;
default:
ASSERT( false, "<SwFmtWrapInfluenceOnObjPos::QueryValue()> - unknown MemberId" );
bRet = sal_False;
}
return bRet;
}
void SwFmtWrapInfluenceOnObjPos::SetWrapInfluenceOnObjPos( sal_Int16 _nWrapInfluenceOnPosition )
{
// --> OD 2004-10-18 #i35017# - constant names have changed and consider
// new value <ITERATIVE>
if ( _nWrapInfluenceOnPosition == text::WrapInfluenceOnPosition::ONCE_SUCCESSIVE ||
_nWrapInfluenceOnPosition == text::WrapInfluenceOnPosition::ONCE_CONCURRENT ||
_nWrapInfluenceOnPosition == text::WrapInfluenceOnPosition::ITERATIVE )
// <--
{
mnWrapInfluenceOnPosition = _nWrapInfluenceOnPosition;
}
else
{
ASSERT( false, "<SwFmtWrapInfluenceOnObjPos::SetWrapInfluenceOnObjPos(..)> - invalid attribute value" );
}
}
// --> OD 2004-10-18 #i35017# - add parameter <_bIterativeAsOnceConcurrent>
// to control, if value <ITERATIVE> has to be treated as <ONCE_CONCURRENT>
sal_Int16 SwFmtWrapInfluenceOnObjPos::GetWrapInfluenceOnObjPos(
const bool _bIterativeAsOnceConcurrent ) const
{
sal_Int16 nWrapInfluenceOnPosition( mnWrapInfluenceOnPosition );
if ( _bIterativeAsOnceConcurrent &&
nWrapInfluenceOnPosition == text::WrapInfluenceOnPosition::ITERATIVE )
{
nWrapInfluenceOnPosition = text::WrapInfluenceOnPosition::ONCE_CONCURRENT;
}
return nWrapInfluenceOnPosition;
}
// <--
<|endoftext|> |
<commit_before>/*
* File: CudaRtHandler.cpp
* Author: cjg
*
* Created on October 10, 2009, 10:51 PM
*/
#include <host_defines.h>
#include <builtin_types.h>
#include <driver_types.h>
#include <GL/gl.h>
#include <cuda_runtime_api.h>
#include <cstring>
#include "CudaUtil.h"
#include "CudaRtHandler.h"
using namespace std;
map<string, CudaRtHandler::CudaRoutineHandler> *CudaRtHandler::mspHandlers = NULL;
CudaRtHandler::CudaRtHandler() {
mpDeviceMemory = new map<string, void *>();
Initialize();
}
CudaRtHandler::~CudaRtHandler() {
}
static cudaError_t GetDeviceCount(CudaRtHandler *pThis, char *in_buffer,
size_t in_buffer_size, char **out_buffer, size_t *out_buffer_size) {
/* cudaError_t cudaGetDeviceCount(int *count) */
int *count = (int *) in_buffer;
cudaError_t result = cudaGetDeviceCount(count);
if (result == cudaSuccess) {
*out_buffer_size = sizeof (int);
*out_buffer = new char[*out_buffer_size];
memmove(*out_buffer, count, sizeof (int));
}
return result;
}
static cudaError_t GetDeviceProperties(CudaRtHandler *pThis, char *in_buffer,
size_t in_buffer_size, char **out_buffer, size_t *out_buffer_size) {
/* cudaError_t cudaGetDeviceCount(struct cudaDeviceProp *prop,
int device) */
struct cudaDeviceProp *prop = (struct cudaDeviceProp *) in_buffer;
int device = *((int *) (in_buffer + sizeof (struct cudaDeviceProp)));
cudaError_t result = cudaGetDeviceProperties(prop, device);
if (result == cudaSuccess) {
*out_buffer_size = sizeof (struct cudaDeviceProp);
*out_buffer = new char[*out_buffer_size];
memmove(*out_buffer, prop, sizeof (struct cudaDeviceProp));
}
return result;
}
static cudaError_t Free(CudaRtHandler *pThis, char *in_buffer,
size_t in_buffer_size, char **out_buffer, size_t *out_buffer_size) {
/* cudaError_t cudaFree(void *devPtr) */
void *devPtr = pThis->GetDevicePointer(in_buffer);
cudaError_t result = cudaFree(devPtr);
if(result == cudaSuccess) {
*out_buffer_size = 0;
*out_buffer = NULL;
}
return result;
}
static cudaError_t Malloc(CudaRtHandler *pThis, char *in_buffer,
size_t in_buffer_size, char **out_buffer, size_t *out_buffer_size) {
/* cudaError_t cudaMalloc(void **devPtr, size_t size) */
void *devPtr = NULL;
size_t size = *((size_t *) (in_buffer + sizeof (void *) * 2 + 3));
cudaError_t result = cudaMalloc(&devPtr, size);
pThis->RegisterDevicePointer(in_buffer, devPtr);
if (result == cudaSuccess) {
*out_buffer_size = 0;
*out_buffer = NULL;
}
return result;
}
static cudaError_t Memcpy(CudaRtHandler *pThis, char *in_buffer,
size_t in_buffer_size, char **out_buffer, size_t *out_buffer_size) {
/* cudaError_t cudaError_t cudaMemcpy(void *dst, const void *src,
size_t count, cudaMemcpyKind kind) */
void *dst = NULL;
void *src = NULL;
size_t count = *((size_t *) (in_buffer + in_buffer_size
- sizeof(size_t) - sizeof(cudaMemcpyKind)));
cudaMemcpyKind kind = *((cudaMemcpyKind *) (in_buffer + in_buffer_size
- sizeof(cudaMemcpyKind)));
cudaError_t result;
switch(kind) {
case cudaMemcpyHostToHost:
// This should nevere happer
break;
case cudaMemcpyHostToDevice:
dst = pThis->GetDevicePointer(in_buffer);
src = in_buffer + CudaUtil::MarshaledDevicePointerSize;
result = cudaMemcpy(dst, src, count, kind);
if(result == cudaSuccess) {
*out_buffer_size = 0;
*out_buffer = NULL;
}
break;
case cudaMemcpyDeviceToHost:
*out_buffer_size = count;
*out_buffer = new char[*out_buffer_size];
dst = *out_buffer;
src = pThis->GetDevicePointer(in_buffer);
result = cudaMemcpy(dst, src, count, kind);
break;
case cudaMemcpyDeviceToDevice:
dst = pThis->GetDevicePointer(in_buffer);
src = pThis->GetDevicePointer(in_buffer
+ CudaUtil::MarshaledDevicePointerSize);
result = cudaMemcpy(dst, src, count, kind);
if(result == cudaSuccess) {
*out_buffer_size = 0;
*out_buffer = NULL;
}
break;
}
return result;
}
void CudaRtHandler::RegisterDevicePointer(std::string& handler, void* devPtr) {
map<string, void *>::iterator it = mpDeviceMemory->find(handler);
if (it != mpDeviceMemory->end()) {
/* FIXME: think about freeing memory */
mpDeviceMemory->erase(it);
}
mpDeviceMemory->insert(make_pair(handler, devPtr));
cout << "Registered DevicePointer " << devPtr << " with handler " << handler << endl;
}
void CudaRtHandler::RegisterDevicePointer(const char* handler, void* devPtr) {
string tmp(handler);
RegisterDevicePointer(tmp, devPtr);
}
void * CudaRtHandler::GetDevicePointer(string & handler) {
map<string, void *>::iterator it = mpDeviceMemory->find(handler);
if (it == mpDeviceMemory->end())
throw "Device Pointer '" + handler + "' not found";
return it->second;
}
void * CudaRtHandler::GetDevicePointer(const char * handler) {
string tmp(handler);
return GetDevicePointer(tmp);
}
void CudaRtHandler::UnregisterDevicePointer(std::string& handler) {
map<string, void *>::iterator it = mpDeviceMemory->find(handler);
if (it == mpDeviceMemory->end()) {
/* FIXME: think about throwing an exception */
return;
}
/* FIXME: think about freeing memory */
mpDeviceMemory->erase(it);
}
void CudaRtHandler::UnregisterDevicePointer(const char* handler) {
string tmp(handler);
UnregisterDevicePointer(tmp);
}
cudaError_t CudaRtHandler::Execute(std::string routine, char* in_buffer,
size_t in_buffer_size, char** out_buffer, size_t* out_buffer_size) {
map<string, CudaRtHandler::CudaRoutineHandler>::iterator it;
it = mspHandlers->find(routine);
if(it == mspHandlers->end())
throw "No handler for '" + routine + "' found!";
return it->second(this, in_buffer, in_buffer_size, out_buffer,
out_buffer_size);
}
void CudaRtHandler::Initialize() {
if(mspHandlers != NULL)
return;
mspHandlers = new map<string, CudaRtHandler::CudaRoutineHandler>();
mspHandlers->insert(make_pair("cudaGetDeviceCount", GetDeviceCount));
mspHandlers->insert(make_pair("cudaGetDeviceProperties", GetDeviceProperties));
mspHandlers->insert(make_pair("cudaFree", Free));
mspHandlers->insert(make_pair("cudaMalloc", Malloc));
mspHandlers->insert(make_pair("cudaMemcpy", Memcpy));
}<commit_msg>unregistering device pointer on cudaFree<commit_after>/*
* File: CudaRtHandler.cpp
* Author: cjg
*
* Created on October 10, 2009, 10:51 PM
*/
#include <host_defines.h>
#include <builtin_types.h>
#include <driver_types.h>
#include <GL/gl.h>
#include <cuda_runtime_api.h>
#include <cstring>
#include "CudaUtil.h"
#include "CudaRtHandler.h"
using namespace std;
map<string, CudaRtHandler::CudaRoutineHandler> *CudaRtHandler::mspHandlers = NULL;
CudaRtHandler::CudaRtHandler() {
mpDeviceMemory = new map<string, void *>();
Initialize();
}
CudaRtHandler::~CudaRtHandler() {
}
static cudaError_t GetDeviceCount(CudaRtHandler *pThis, char *in_buffer,
size_t in_buffer_size, char **out_buffer, size_t *out_buffer_size) {
/* cudaError_t cudaGetDeviceCount(int *count) */
int *count = (int *) in_buffer;
cudaError_t result = cudaGetDeviceCount(count);
if (result == cudaSuccess) {
*out_buffer_size = sizeof (int);
*out_buffer = new char[*out_buffer_size];
memmove(*out_buffer, count, sizeof (int));
}
return result;
}
static cudaError_t GetDeviceProperties(CudaRtHandler *pThis, char *in_buffer,
size_t in_buffer_size, char **out_buffer, size_t *out_buffer_size) {
/* cudaError_t cudaGetDeviceCount(struct cudaDeviceProp *prop,
int device) */
struct cudaDeviceProp *prop = (struct cudaDeviceProp *) in_buffer;
int device = *((int *) (in_buffer + sizeof (struct cudaDeviceProp)));
cudaError_t result = cudaGetDeviceProperties(prop, device);
if (result == cudaSuccess) {
*out_buffer_size = sizeof (struct cudaDeviceProp);
*out_buffer = new char[*out_buffer_size];
memmove(*out_buffer, prop, sizeof (struct cudaDeviceProp));
}
return result;
}
static cudaError_t Free(CudaRtHandler *pThis, char *in_buffer,
size_t in_buffer_size, char **out_buffer, size_t *out_buffer_size) {
/* cudaError_t cudaFree(void *devPtr) */
void *devPtr = pThis->GetDevicePointer(in_buffer);
cudaError_t result = cudaFree(devPtr);
pThis->UnregisterDevicePointer(in_buffer);
if(result == cudaSuccess) {
*out_buffer_size = 0;
*out_buffer = NULL;
}
return result;
}
static cudaError_t Malloc(CudaRtHandler *pThis, char *in_buffer,
size_t in_buffer_size, char **out_buffer, size_t *out_buffer_size) {
/* cudaError_t cudaMalloc(void **devPtr, size_t size) */
void *devPtr = NULL;
size_t size = *((size_t *) (in_buffer + sizeof (void *) * 2 + 3));
cudaError_t result = cudaMalloc(&devPtr, size);
pThis->RegisterDevicePointer(in_buffer, devPtr);
if (result == cudaSuccess) {
*out_buffer_size = 0;
*out_buffer = NULL;
}
return result;
}
static cudaError_t Memcpy(CudaRtHandler *pThis, char *in_buffer,
size_t in_buffer_size, char **out_buffer, size_t *out_buffer_size) {
/* cudaError_t cudaError_t cudaMemcpy(void *dst, const void *src,
size_t count, cudaMemcpyKind kind) */
void *dst = NULL;
void *src = NULL;
size_t count = *((size_t *) (in_buffer + in_buffer_size
- sizeof(size_t) - sizeof(cudaMemcpyKind)));
cudaMemcpyKind kind = *((cudaMemcpyKind *) (in_buffer + in_buffer_size
- sizeof(cudaMemcpyKind)));
cudaError_t result;
switch(kind) {
case cudaMemcpyHostToHost:
// This should nevere happer
break;
case cudaMemcpyHostToDevice:
dst = pThis->GetDevicePointer(in_buffer);
src = in_buffer + CudaUtil::MarshaledDevicePointerSize;
result = cudaMemcpy(dst, src, count, kind);
if(result == cudaSuccess) {
*out_buffer_size = 0;
*out_buffer = NULL;
}
break;
case cudaMemcpyDeviceToHost:
*out_buffer_size = count;
*out_buffer = new char[*out_buffer_size];
dst = *out_buffer;
src = pThis->GetDevicePointer(in_buffer);
result = cudaMemcpy(dst, src, count, kind);
break;
case cudaMemcpyDeviceToDevice:
dst = pThis->GetDevicePointer(in_buffer);
src = pThis->GetDevicePointer(in_buffer
+ CudaUtil::MarshaledDevicePointerSize);
result = cudaMemcpy(dst, src, count, kind);
if(result == cudaSuccess) {
*out_buffer_size = 0;
*out_buffer = NULL;
}
break;
}
return result;
}
void CudaRtHandler::RegisterDevicePointer(std::string& handler, void* devPtr) {
map<string, void *>::iterator it = mpDeviceMemory->find(handler);
if (it != mpDeviceMemory->end()) {
/* FIXME: think about freeing memory */
mpDeviceMemory->erase(it);
}
mpDeviceMemory->insert(make_pair(handler, devPtr));
cout << "Registered DevicePointer " << devPtr << " with handler " << handler << endl;
}
void CudaRtHandler::RegisterDevicePointer(const char* handler, void* devPtr) {
string tmp(handler);
RegisterDevicePointer(tmp, devPtr);
}
void * CudaRtHandler::GetDevicePointer(string & handler) {
map<string, void *>::iterator it = mpDeviceMemory->find(handler);
if (it == mpDeviceMemory->end())
throw "Device Pointer '" + handler + "' not found";
return it->second;
}
void * CudaRtHandler::GetDevicePointer(const char * handler) {
string tmp(handler);
return GetDevicePointer(tmp);
}
void CudaRtHandler::UnregisterDevicePointer(std::string& handler) {
map<string, void *>::iterator it = mpDeviceMemory->find(handler);
if (it == mpDeviceMemory->end()) {
/* FIXME: think about throwing an exception */
return;
}
/* FIXME: think about freeing memory */
cout << "Registered DevicePointer " << it->second << " with handler " << handler << endl;
mpDeviceMemory->erase(it);
}
void CudaRtHandler::UnregisterDevicePointer(const char* handler) {
string tmp(handler);
UnregisterDevicePointer(tmp);
}
cudaError_t CudaRtHandler::Execute(std::string routine, char* in_buffer,
size_t in_buffer_size, char** out_buffer, size_t* out_buffer_size) {
map<string, CudaRtHandler::CudaRoutineHandler>::iterator it;
it = mspHandlers->find(routine);
if(it == mspHandlers->end())
throw "No handler for '" + routine + "' found!";
return it->second(this, in_buffer, in_buffer_size, out_buffer,
out_buffer_size);
}
void CudaRtHandler::Initialize() {
if(mspHandlers != NULL)
return;
mspHandlers = new map<string, CudaRtHandler::CudaRoutineHandler>();
mspHandlers->insert(make_pair("cudaGetDeviceCount", GetDeviceCount));
mspHandlers->insert(make_pair("cudaGetDeviceProperties", GetDeviceProperties));
mspHandlers->insert(make_pair("cudaFree", Free));
mspHandlers->insert(make_pair("cudaMalloc", Malloc));
mspHandlers->insert(make_pair("cudaMemcpy", Memcpy));
}<|endoftext|> |
<commit_before>#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE HitFinderToolsTests
#include <boost/test/unit_test.hpp>
#include "HitFinderTools.h"
BOOST_AUTO_TEST_SUITE (HitFinderToolsSuite)
BOOST_AUTO_TEST_CASE (HitFinder)
{
// All times are in picoseconds
JPetBarrelSlot BS(7, true, "string", 1.0, 1);
JPetScin Scintillator(1);
JPetPhysSignal sig1;
sig1.setTime(12452);
sig1.setTimeWindowIndex(1);
JPetPM PM1;
PM1.setSide(JPetPM::SideA);
PM1.setBarrelSlot(BS);
PM1.setScin(Scintillator);
sig1.setPM(PM1);
JPetPhysSignal sig2;
sig2.setTime(3146613);
sig2.setTimeWindowIndex(1);
JPetPM PM2;
PM2.setSide(JPetPM::SideA);
PM2.setBarrelSlot(BS);
PM2.setScin(Scintillator);
sig2.setPM(PM2);
JPetPhysSignal sig3;
sig3.setTime(87361353);
sig3.setTimeWindowIndex(1);
JPetPM PM3;
PM3.setSide(JPetPM::SideA);
PM3.setBarrelSlot(BS);
PM3.setScin(Scintillator);
sig3.setPM(PM3);
JPetPhysSignal sig4;
sig4.setTime(46785);
sig4.setTimeWindowIndex(1);
JPetPM PM4;
PM4.setSide(JPetPM::SideB);
PM4.setBarrelSlot(BS);
PM4.setScin(Scintillator);
sig4.setPM(PM4);
JPetPhysSignal sig5;
sig5.setTime(3132169);
sig5.setTimeWindowIndex(1);
JPetPM PM5;
PM5.setSide(JPetPM::SideB);
PM5.setBarrelSlot(BS);
PM5.setScin(Scintillator);
sig5.setPM(PM5);
JPetPhysSignal sig6;
sig6.setTime(87338621);
sig6.setTimeWindowIndex(1);
JPetPM PM6;
PM6.setSide(JPetPM::SideB);
PM6.setBarrelSlot(BS);
PM6.setScin(Scintillator);
sig6.setPM(PM6);
HitFinderTools HitFinder;
std::vector<JPetPhysSignal> sideA = {sig1, sig2, sig3};
std::vector<JPetPhysSignal> sideB = {sig4, sig5, sig6};
HitFinderTools::SignalsContainer container;
container.emplace(7, std::make_pair(sideA, sideB));
double expectedHitsTimeWindow1ns = 0;
double expectedHitsTimeWindow50ns = 3;
double expectedHitsTimeWindow5000ns = 5;
double expectedHitsTimeWindow1ms = 9;
double kTimeWindow1ns = pow(10,3);
double kTimeWindow50ns = 50*pow(10,3);
double kTimeWindow5000ns = 5000*pow(10,3);
double kTimeWindow1ms = pow(10,9);
BOOST_REQUIRE_EQUAL(HitFinder.createHits(container, kTimeWindow1ns).size(), expectedHitsTimeWindow1ns);
BOOST_REQUIRE_EQUAL(HitFinder.createHits(container, kTimeWindow50ns).size(), expectedHitsTimeWindow50ns);
BOOST_REQUIRE_EQUAL(HitFinder.createHits(container, kTimeWindow5000ns).size(), expectedHitsTimeWindow5000ns);
BOOST_REQUIRE_EQUAL(HitFinder.createHits(container, kTimeWindow1ms).size(), expectedHitsTimeWindow1ms);
}
BOOST_AUTO_TEST_SUITE_END()
<commit_msg>Remove outdated HitFinderToolsTest<commit_after><|endoftext|> |
<commit_before>#include "getusername.h"
#include <errno.h>
#include <langinfo.h>
#include <locale.h>
#include <unistd.h>
#include <string>
#include <vector>
#include <scxcorelib/scxstrencodingconv.h>
using std::string;
using std::vector;
using SCXCoreLib::Utf8ToUtf16le;
const string utf8 = "UTF-8";
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms724432(v=vs.85).aspx
// Sets errno to:
// ERROR_INVALID_PARAMETER - parameter is not valid
// ERROR_BAD_ENVIRONMENT - locale is not UTF-8
// ERROR_TOO_MANY_OPEN_FILES - already have the maximum allowed number of open files
// ERROR_NO_ASSOCIATION - calling process has no controlling terminal
// ERROR_INSUFFICIENT_BUFFER - buffer not large enough to hold username string
// ERROR_NO_SUCH_USER - there was no corresponding entry in the utmp-file
// ERROR_OUTOFMEMORY - insufficient memory to allocate passwd structure
// ERROR_NO_ASSOCIATION - standard input didn't refer to a terminal
// ERROR_INVALID_FUNCTION - getlogin_r() returned an unrecognized error code
//
// Returns:
// 1 - succeeded
// 0 - failed
BOOL GetUserName(WCHAR_T *lpBuffer, LPDWORD lpnSize)
{
errno = 0;
// Check parameters
if (!lpBuffer || !lpnSize) {
errno = ERROR_INVALID_PARAMETER;
return 0;
}
// Select locale from environment
setlocale(LC_ALL, "");
// Check that locale is UTF-8
if (nl_langinfo(CODESET) != utf8) {
errno = ERROR_BAD_ENVIRONMENT;
return 0;
}
// Get username from system in a thread-safe manner
char userName[*lpnSize];
int err = getlogin_r(userName, *lpnSize);
// Map errno to Win32 Error Codes
if (err != 0) {
switch (errno) {
case EMFILE:
case ENFILE:
errno = ERROR_TOO_MANY_OPEN_FILES;
break;
case ENXIO:
errno = ERROR_NO_ASSOCIATION;
break;
case ERANGE:
errno = ERROR_INSUFFICIENT_BUFFER;
break;
case ENOENT:
errno = ERROR_NO_SUCH_USER;
break;
case ENOMEM:
errno = ERROR_OUTOFMEMORY;
break;
case ENOTTY:
errno = ERROR_NO_ASSOCIATION;
break;
default:
errno = ERROR_INVALID_FUNCTION;
}
return 0;
}
// Convert to char * to WCHAR_T * (UTF-8 to UTF-16 LE w/o BOM)
string input = string(userName);
vector<unsigned char> output;
Utf8ToUtf16le(input, output);
if (output.size()/2 + 1 > *lpnSize) {
errno = ERROR_INSUFFICIENT_BUFFER;
return 0;
}
// Add two null bytes (because it's UTF-16)
output.push_back('\0');
output.push_back('\0');
memcpy(lpBuffer, &output[0], output.size());
*lpnSize = output.size()/2;
return 1;
}
<commit_msg>Change global to local static const<commit_after>#include "getusername.h"
#include <errno.h>
#include <langinfo.h>
#include <locale.h>
#include <unistd.h>
#include <string>
#include <vector>
#include <scxcorelib/scxstrencodingconv.h>
using std::string;
using std::vector;
using SCXCoreLib::Utf8ToUtf16le;
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms724432(v=vs.85).aspx
// Sets errno to:
// ERROR_INVALID_PARAMETER - parameter is not valid
// ERROR_BAD_ENVIRONMENT - locale is not UTF-8
// ERROR_TOO_MANY_OPEN_FILES - already have the maximum allowed number of open files
// ERROR_NO_ASSOCIATION - calling process has no controlling terminal
// ERROR_INSUFFICIENT_BUFFER - buffer not large enough to hold username string
// ERROR_NO_SUCH_USER - there was no corresponding entry in the utmp-file
// ERROR_OUTOFMEMORY - insufficient memory to allocate passwd structure
// ERROR_NO_ASSOCIATION - standard input didn't refer to a terminal
// ERROR_INVALID_FUNCTION - getlogin_r() returned an unrecognized error code
//
// Returns:
// 1 - succeeded
// 0 - failed
BOOL GetUserName(WCHAR_T *lpBuffer, LPDWORD lpnSize)
{
static const std::string utf8 = "UTF-8";
errno = 0;
// Check parameters
if (!lpBuffer || !lpnSize) {
errno = ERROR_INVALID_PARAMETER;
return 0;
}
// Select locale from environment
setlocale(LC_ALL, "");
// Check that locale is UTF-8
if (nl_langinfo(CODESET) != utf8) {
errno = ERROR_BAD_ENVIRONMENT;
return 0;
}
// Get username from system in a thread-safe manner
char userName[*lpnSize];
int err = getlogin_r(userName, *lpnSize);
// Map errno to Win32 Error Codes
if (err != 0) {
switch (errno) {
case EMFILE:
case ENFILE:
errno = ERROR_TOO_MANY_OPEN_FILES;
break;
case ENXIO:
errno = ERROR_NO_ASSOCIATION;
break;
case ERANGE:
errno = ERROR_INSUFFICIENT_BUFFER;
break;
case ENOENT:
errno = ERROR_NO_SUCH_USER;
break;
case ENOMEM:
errno = ERROR_OUTOFMEMORY;
break;
case ENOTTY:
errno = ERROR_NO_ASSOCIATION;
break;
default:
errno = ERROR_INVALID_FUNCTION;
}
return 0;
}
// Convert to char * to WCHAR_T * (UTF-8 to UTF-16 LE w/o BOM)
string input = string(userName);
vector<unsigned char> output;
Utf8ToUtf16le(input, output);
if (output.size()/2 + 1 > *lpnSize) {
errno = ERROR_INSUFFICIENT_BUFFER;
return 0;
}
// Add two null bytes (because it's UTF-16)
output.push_back('\0');
output.push_back('\0');
memcpy(lpBuffer, &output[0], output.size());
*lpnSize = output.size()/2;
return 1;
}
<|endoftext|> |
<commit_before>/* Copyright 2018 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.
==============================================================================*/
#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM
#include "tensorflow/core/kernels/cwise_ops_gpu_common.cu.h"
namespace tensorflow {
namespace functor {
#if GOOGLE_CUDA
DEFINE_BINARY5(xlogy, Eigen::half, float, double, complex64, complex128);
#elif TENSORFLOW_USE_ROCM
// ROCM TODO: enable complex64 / complex128 after compiler fix.
DEFINE_BINARY3(xlogy, Eigen::half, float, double);
#endif
} // namespace functor
} // namespace tensorflow
#endif // GOOGLE_CUDA || TENSORFLOW_USE_ROCM
<commit_msg>Update cwise_op_gpu_xlogy.cu.cc<commit_after>/* Copyright 2018 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.
==============================================================================*/
#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM
#include "tensorflow/core/kernels/cwise_ops_gpu_common.cu.h"
namespace tensorflow {
namespace functor {
#if GOOGLE_CUDA
DEFINE_BINARY5(xlogy, Eigen::half, float, double, complex64, complex128);
#elif TENSORFLOW_USE_ROCM
// TODO(ROCm): enable complex64 / complex128 after compiler fix.
DEFINE_BINARY3(xlogy, Eigen::half, float, double);
#endif
} // namespace functor
} // namespace tensorflow
#endif // GOOGLE_CUDA || TENSORFLOW_USE_ROCM
<|endoftext|> |
<commit_before>#include "renderers.h"
#include <QWidget>
#include <QPainter>
#include <QBitmap>
void drawInterlaced(const QPixmap &imgL, const QPixmap &imgR, int panX, int panY, QPainter &painter, QBitmap &mask, qreal zoom, QWidget *parent){
if(zoom <= 0.0){
zoom = qMin(qreal(painter.window().width()) / qreal(imgL.width()), qreal(painter.window().height()) / qreal(imgL.height()));
}
QRect outRect(panX + painter.window().width() / 2 - (imgL.width() / 2) * zoom,
panY + painter.window().height() / 2 - (imgL.height() / 2) * zoom,
imgL.width() * zoom, imgL.height() * zoom);
painter.setClipRect(outRect);
painter.setCompositionMode(QPainter::CompositionMode_Clear);
painter.drawRect(painter.window());
painter.setCompositionMode(QPainter::CompositionMode_Source);
painter.setBackgroundMode(Qt::TransparentMode);
// TODO - offset this based on widget's position on screen.
for(int x = outRect.left(); x < outRect.right(); x += mask.width()){
for(int y = outRect.top(); y < outRect.bottom(); y += mask.height()){
painter.drawPixmap(x, y, mask);
}
}
painter.setCompositionMode(QPainter::CompositionMode_SourceIn);
painter.drawPixmap(outRect, imgL);
painter.setCompositionMode(QPainter::CompositionMode_DestinationOver);
painter.drawPixmap(outRect, imgR);
}
<commit_msg>reduce extra drawPixmap calls when interlaced/checkerboard render is zoomed in.<commit_after>#include "renderers.h"
#include <QWidget>
#include <QPainter>
#include <QBitmap>
void drawInterlaced(const QPixmap &imgL, const QPixmap &imgR, int panX, int panY, QPainter &painter, QBitmap &mask, qreal zoom, QWidget *parent){
if(zoom <= 0.0){
zoom = qMin(qreal(painter.window().width()) / qreal(imgL.width()), qreal(painter.window().height()) / qreal(imgL.height()));
}
QRect outRect(panX + painter.window().width() / 2 - (imgL.width() / 2) * zoom,
panY + painter.window().height() / 2 - (imgL.height() / 2) * zoom,
imgL.width() * zoom, imgL.height() * zoom);
QRect maskArea = outRect & painter.window();
painter.setClipRect(maskArea);
painter.setCompositionMode(QPainter::CompositionMode_Clear);
painter.drawRect(maskArea);
painter.setCompositionMode(QPainter::CompositionMode_Source);
painter.setBackgroundMode(Qt::TransparentMode);
// TODO - offset this based on widget's position on screen.
for(int x = maskArea.left(); x < maskArea.right(); x += mask.width()){
for(int y = maskArea.top(); y < maskArea.bottom(); y += mask.height()){
painter.drawPixmap(x, y, mask);
}
}
painter.setCompositionMode(QPainter::CompositionMode_SourceIn);
painter.drawPixmap(outRect, imgL);
painter.setCompositionMode(QPainter::CompositionMode_DestinationOver);
painter.drawPixmap(outRect, imgR);
}
<|endoftext|> |
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/renderer_host/web_input_event_aura.h"
#include "content/browser/renderer_host/input/web_input_event_util.h"
#include "content/browser/renderer_host/ui_events_helper.h"
#include "ui/aura/window.h"
#include "ui/events/event.h"
#include "ui/events/event_utils.h"
#if defined(USE_OZONE)
#include "ui/events/keycodes/keyboard_code_conversion.h"
#endif
namespace content {
#if defined(OS_WIN)
blink::WebMouseEvent MakeUntranslatedWebMouseEventFromNativeEvent(
const base::NativeEvent& native_event);
blink::WebMouseWheelEvent MakeUntranslatedWebMouseWheelEventFromNativeEvent(
const base::NativeEvent& native_event);
blink::WebKeyboardEvent MakeWebKeyboardEventFromNativeEvent(
const base::NativeEvent& native_event);
blink::WebGestureEvent MakeWebGestureEventFromNativeEvent(
const base::NativeEvent& native_event);
#endif
#if defined(USE_X11) || defined(USE_OZONE)
blink::WebKeyboardEvent MakeWebKeyboardEventFromAuraEvent(
ui::KeyEvent* event) {
blink::WebKeyboardEvent webkit_event;
webkit_event.timeStampSeconds = event->time_stamp().InSecondsF();
webkit_event.modifiers = EventFlagsToWebEventModifiers(event->flags());
switch (event->type()) {
case ui::ET_KEY_PRESSED:
webkit_event.type = event->is_char() ? blink::WebInputEvent::Char :
blink::WebInputEvent::RawKeyDown;
break;
case ui::ET_KEY_RELEASED:
webkit_event.type = blink::WebInputEvent::KeyUp;
break;
default:
NOTREACHED();
}
if (webkit_event.modifiers & blink::WebInputEvent::AltKey)
webkit_event.isSystemKey = true;
webkit_event.windowsKeyCode = event->GetLocatedWindowsKeyboardCode();
webkit_event.nativeKeyCode = event->platform_keycode();
webkit_event.unmodifiedText[0] = event->GetUnmodifiedText();
webkit_event.text[0] = event->GetText();
webkit_event.setKeyIdentifierFromWindowsKeyCode();
return webkit_event;
}
blink::WebMouseWheelEvent MakeWebMouseWheelEventFromAuraEvent(
ui::ScrollEvent* event) {
blink::WebMouseWheelEvent webkit_event;
webkit_event.type = blink::WebInputEvent::MouseWheel;
webkit_event.button = blink::WebMouseEvent::ButtonNone;
webkit_event.modifiers = EventFlagsToWebEventModifiers(event->flags());
webkit_event.timeStampSeconds = event->time_stamp().InSecondsF();
webkit_event.hasPreciseScrollingDeltas = true;
float offset_ordinal_x = 0.f;
float offset_ordinal_y = 0.f;
if ((event->flags() & ui::EF_SHIFT_DOWN) != 0 && event->x_offset() == 0) {
webkit_event.deltaX = event->y_offset();
webkit_event.deltaY = 0;
offset_ordinal_x = event->y_offset_ordinal();
offset_ordinal_y = event->x_offset_ordinal();
} else {
webkit_event.deltaX = event->x_offset();
webkit_event.deltaY = event->y_offset();
offset_ordinal_x = event->x_offset_ordinal();
offset_ordinal_y = event->y_offset_ordinal();
}
if (offset_ordinal_x != 0.f && webkit_event.deltaX != 0.f)
webkit_event.accelerationRatioX = offset_ordinal_x / webkit_event.deltaX;
webkit_event.wheelTicksX = webkit_event.deltaX / kPixelsPerTick;
webkit_event.wheelTicksY = webkit_event.deltaY / kPixelsPerTick;
if (offset_ordinal_y != 0.f && webkit_event.deltaY != 0.f)
webkit_event.accelerationRatioY = offset_ordinal_y / webkit_event.deltaY;
return webkit_event;
}
blink::WebGestureEvent MakeWebGestureEventFromAuraEvent(
ui::ScrollEvent* event) {
blink::WebGestureEvent webkit_event;
switch (event->type()) {
case ui::ET_SCROLL_FLING_START:
webkit_event.type = blink::WebInputEvent::GestureFlingStart;
webkit_event.data.flingStart.velocityX = event->x_offset();
webkit_event.data.flingStart.velocityY = event->y_offset();
break;
case ui::ET_SCROLL_FLING_CANCEL:
webkit_event.type = blink::WebInputEvent::GestureFlingCancel;
break;
case ui::ET_SCROLL:
NOTREACHED() << "Invalid gesture type: " << event->type();
break;
default:
NOTREACHED() << "Unknown gesture type: " << event->type();
}
webkit_event.sourceDevice = blink::WebGestureDeviceTouchpad;
webkit_event.modifiers = EventFlagsToWebEventModifiers(event->flags());
webkit_event.timeStampSeconds = event->time_stamp().InSecondsF();
return webkit_event;
}
#endif
blink::WebMouseEvent MakeWebMouseEventFromAuraEvent(
ui::MouseEvent* event);
blink::WebMouseWheelEvent MakeWebMouseWheelEventFromAuraEvent(
ui::MouseWheelEvent* event);
// General approach:
//
// ui::Event only carries a subset of possible event data provided to Aura by
// the host platform. WebKit utilizes a larger subset of that information than
// Aura itself. WebKit includes some built in cracking functionality that we
// rely on to obtain this information cleanly and consistently.
//
// The only place where an ui::Event's data differs from what the underlying
// base::NativeEvent would provide is position data, since we would like to
// provide coordinates relative to the aura::Window that is hosting the
// renderer, not the top level platform window.
//
// The approach is to fully construct a blink::WebInputEvent from the
// ui::Event's base::NativeEvent, and then replace the coordinate fields with
// the translated values from the ui::Event.
//
// The exception is mouse events on linux. The ui::MouseEvent contains enough
// necessary information to construct a WebMouseEvent. So instead of extracting
// the information from the XEvent, which can be tricky when supporting both
// XInput2 and XInput, the WebMouseEvent is constructed from the
// ui::MouseEvent. This will not be necessary once only XInput2 is supported.
//
blink::WebMouseEvent MakeWebMouseEvent(ui::MouseEvent* event) {
// Construct an untranslated event from the platform event data.
blink::WebMouseEvent webkit_event =
#if defined(OS_WIN)
// On Windows we have WM_ events comming from desktop and pure aura
// events comming from metro mode.
event->native_event().message ?
MakeUntranslatedWebMouseEventFromNativeEvent(event->native_event()) :
MakeWebMouseEventFromAuraEvent(event);
#else
MakeWebMouseEventFromAuraEvent(event);
#endif
// Replace the event's coordinate fields with translated position data from
// |event|.
webkit_event.windowX = webkit_event.x = event->x();
webkit_event.windowY = webkit_event.y = event->y();
#if defined(OS_WIN)
if (event->native_event().message)
return webkit_event;
#endif
const gfx::Point root_point = event->root_location();
webkit_event.globalX = root_point.x();
webkit_event.globalY = root_point.y();
return webkit_event;
}
blink::WebMouseWheelEvent MakeWebMouseWheelEvent(ui::MouseWheelEvent* event) {
#if defined(OS_WIN)
// Construct an untranslated event from the platform event data.
blink::WebMouseWheelEvent webkit_event = event->native_event().message ?
MakeUntranslatedWebMouseWheelEventFromNativeEvent(event->native_event()) :
MakeWebMouseWheelEventFromAuraEvent(event);
#else
blink::WebMouseWheelEvent webkit_event =
MakeWebMouseWheelEventFromAuraEvent(event);
#endif
// Replace the event's coordinate fields with translated position data from
// |event|.
webkit_event.windowX = webkit_event.x = event->x();
webkit_event.windowY = webkit_event.y = event->y();
const gfx::Point root_point = event->root_location();
webkit_event.globalX = root_point.x();
webkit_event.globalY = root_point.y();
return webkit_event;
}
blink::WebMouseWheelEvent MakeWebMouseWheelEvent(ui::ScrollEvent* event) {
#if defined(OS_WIN)
// Construct an untranslated event from the platform event data.
blink::WebMouseWheelEvent webkit_event =
MakeUntranslatedWebMouseWheelEventFromNativeEvent(event->native_event());
#else
blink::WebMouseWheelEvent webkit_event =
MakeWebMouseWheelEventFromAuraEvent(event);
#endif
// Replace the event's coordinate fields with translated position data from
// |event|.
webkit_event.windowX = webkit_event.x = event->x();
webkit_event.windowY = webkit_event.y = event->y();
const gfx::Point root_point = event->root_location();
webkit_event.globalX = root_point.x();
webkit_event.globalY = root_point.y();
return webkit_event;
}
blink::WebKeyboardEvent MakeWebKeyboardEvent(ui::KeyEvent* event) {
// Windows can figure out whether or not to construct a RawKeyDown or a Char
// WebInputEvent based on the type of message carried in
// event->native_event(). X11 is not so fortunate, there is no separate
// translated event type, so DesktopHostLinux sends an extra KeyEvent with
// is_char() == true. We need to pass the ui::KeyEvent to the X11 function
// to detect this case so the right event type can be constructed.
#if defined(OS_WIN)
if (!event->HasNativeEvent())
return blink::WebKeyboardEvent();
// Key events require no translation by the aura system.
return MakeWebKeyboardEventFromNativeEvent(event->native_event());
#else
return MakeWebKeyboardEventFromAuraEvent(event);
#endif
}
blink::WebGestureEvent MakeWebGestureEvent(ui::GestureEvent* event) {
blink::WebGestureEvent gesture_event;
#if defined(OS_WIN)
if (event->HasNativeEvent())
gesture_event = MakeWebGestureEventFromNativeEvent(event->native_event());
else
gesture_event = MakeWebGestureEventFromUIEvent(*event);
#else
gesture_event = MakeWebGestureEventFromUIEvent(*event);
#endif
gesture_event.x = event->x();
gesture_event.y = event->y();
const gfx::Point root_point = event->root_location();
gesture_event.globalX = root_point.x();
gesture_event.globalY = root_point.y();
return gesture_event;
}
blink::WebGestureEvent MakeWebGestureEvent(ui::ScrollEvent* event) {
blink::WebGestureEvent gesture_event;
#if defined(OS_WIN)
gesture_event = MakeWebGestureEventFromNativeEvent(event->native_event());
#else
gesture_event = MakeWebGestureEventFromAuraEvent(event);
#endif
gesture_event.x = event->x();
gesture_event.y = event->y();
const gfx::Point root_point = event->root_location();
gesture_event.globalX = root_point.x();
gesture_event.globalY = root_point.y();
return gesture_event;
}
blink::WebGestureEvent MakeWebGestureEventFlingCancel() {
blink::WebGestureEvent gesture_event;
// All other fields are ignored on a GestureFlingCancel event.
gesture_event.type = blink::WebInputEvent::GestureFlingCancel;
gesture_event.sourceDevice = blink::WebGestureDeviceTouchpad;
return gesture_event;
}
blink::WebMouseEvent MakeWebMouseEventFromAuraEvent(ui::MouseEvent* event) {
blink::WebMouseEvent webkit_event;
webkit_event.modifiers = EventFlagsToWebEventModifiers(event->flags());
webkit_event.timeStampSeconds = event->time_stamp().InSecondsF();
webkit_event.button = blink::WebMouseEvent::ButtonNone;
int button_flags = event->flags();
if (event->type() == ui::ET_MOUSE_PRESSED ||
event->type() == ui::ET_MOUSE_RELEASED) {
// We want to use changed_button_flags() for mouse pressed & released.
// These flags can be used only if they are set which is not always the case
// (see e.g. GetChangedMouseButtonFlagsFromNative() in events_win.cc).
if (event->changed_button_flags())
button_flags = event->changed_button_flags();
}
if (button_flags & ui::EF_LEFT_MOUSE_BUTTON)
webkit_event.button = blink::WebMouseEvent::ButtonLeft;
if (button_flags & ui::EF_MIDDLE_MOUSE_BUTTON)
webkit_event.button = blink::WebMouseEvent::ButtonMiddle;
if (button_flags & ui::EF_RIGHT_MOUSE_BUTTON)
webkit_event.button = blink::WebMouseEvent::ButtonRight;
switch (event->type()) {
case ui::ET_MOUSE_PRESSED:
webkit_event.type = blink::WebInputEvent::MouseDown;
webkit_event.clickCount = event->GetClickCount();
break;
case ui::ET_MOUSE_RELEASED:
webkit_event.type = blink::WebInputEvent::MouseUp;
webkit_event.clickCount = event->GetClickCount();
break;
case ui::ET_MOUSE_ENTERED:
case ui::ET_MOUSE_EXITED:
case ui::ET_MOUSE_MOVED:
case ui::ET_MOUSE_DRAGGED:
webkit_event.type = blink::WebInputEvent::MouseMove;
break;
default:
NOTIMPLEMENTED() << "Received unexpected event: " << event->type();
break;
}
return webkit_event;
}
blink::WebMouseWheelEvent MakeWebMouseWheelEventFromAuraEvent(
ui::MouseWheelEvent* event) {
blink::WebMouseWheelEvent webkit_event;
webkit_event.type = blink::WebInputEvent::MouseWheel;
webkit_event.button = blink::WebMouseEvent::ButtonNone;
webkit_event.modifiers = EventFlagsToWebEventModifiers(event->flags());
webkit_event.timeStampSeconds = event->time_stamp().InSecondsF();
if ((event->flags() & ui::EF_SHIFT_DOWN) != 0 && event->x_offset() == 0) {
webkit_event.deltaX = event->y_offset();
webkit_event.deltaY = 0;
} else {
webkit_event.deltaX = event->x_offset();
webkit_event.deltaY = event->y_offset();
}
webkit_event.wheelTicksX = webkit_event.deltaX / kPixelsPerTick;
webkit_event.wheelTicksY = webkit_event.deltaY / kPixelsPerTick;
return webkit_event;
}
} // namespace content
<commit_msg>Fix native key code under X11.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/renderer_host/web_input_event_aura.h"
#include "content/browser/renderer_host/input/web_input_event_util.h"
#include "content/browser/renderer_host/ui_events_helper.h"
#include "ui/aura/window.h"
#include "ui/events/event.h"
#include "ui/events/event_utils.h"
#if defined(USE_X11) || defined(USE_OZONE)
#include "ui/events/keycodes/dom4/keycode_converter.h"
#endif
namespace content {
#if defined(OS_WIN)
blink::WebMouseEvent MakeUntranslatedWebMouseEventFromNativeEvent(
const base::NativeEvent& native_event);
blink::WebMouseWheelEvent MakeUntranslatedWebMouseWheelEventFromNativeEvent(
const base::NativeEvent& native_event);
blink::WebKeyboardEvent MakeWebKeyboardEventFromNativeEvent(
const base::NativeEvent& native_event);
blink::WebGestureEvent MakeWebGestureEventFromNativeEvent(
const base::NativeEvent& native_event);
#endif
#if defined(USE_X11) || defined(USE_OZONE)
blink::WebKeyboardEvent MakeWebKeyboardEventFromAuraEvent(
ui::KeyEvent* event) {
blink::WebKeyboardEvent webkit_event;
webkit_event.timeStampSeconds = event->time_stamp().InSecondsF();
webkit_event.modifiers = EventFlagsToWebEventModifiers(event->flags());
switch (event->type()) {
case ui::ET_KEY_PRESSED:
webkit_event.type = event->is_char() ? blink::WebInputEvent::Char :
blink::WebInputEvent::RawKeyDown;
break;
case ui::ET_KEY_RELEASED:
webkit_event.type = blink::WebInputEvent::KeyUp;
break;
default:
NOTREACHED();
}
if (webkit_event.modifiers & blink::WebInputEvent::AltKey)
webkit_event.isSystemKey = true;
webkit_event.windowsKeyCode = event->GetLocatedWindowsKeyboardCode();
webkit_event.nativeKeyCode =
ui::KeycodeConverter::CodeToNativeKeycode(event->code().c_str());
webkit_event.unmodifiedText[0] = event->GetUnmodifiedText();
webkit_event.text[0] = event->GetText();
webkit_event.setKeyIdentifierFromWindowsKeyCode();
return webkit_event;
}
blink::WebMouseWheelEvent MakeWebMouseWheelEventFromAuraEvent(
ui::ScrollEvent* event) {
blink::WebMouseWheelEvent webkit_event;
webkit_event.type = blink::WebInputEvent::MouseWheel;
webkit_event.button = blink::WebMouseEvent::ButtonNone;
webkit_event.modifiers = EventFlagsToWebEventModifiers(event->flags());
webkit_event.timeStampSeconds = event->time_stamp().InSecondsF();
webkit_event.hasPreciseScrollingDeltas = true;
float offset_ordinal_x = 0.f;
float offset_ordinal_y = 0.f;
if ((event->flags() & ui::EF_SHIFT_DOWN) != 0 && event->x_offset() == 0) {
webkit_event.deltaX = event->y_offset();
webkit_event.deltaY = 0;
offset_ordinal_x = event->y_offset_ordinal();
offset_ordinal_y = event->x_offset_ordinal();
} else {
webkit_event.deltaX = event->x_offset();
webkit_event.deltaY = event->y_offset();
offset_ordinal_x = event->x_offset_ordinal();
offset_ordinal_y = event->y_offset_ordinal();
}
if (offset_ordinal_x != 0.f && webkit_event.deltaX != 0.f)
webkit_event.accelerationRatioX = offset_ordinal_x / webkit_event.deltaX;
webkit_event.wheelTicksX = webkit_event.deltaX / kPixelsPerTick;
webkit_event.wheelTicksY = webkit_event.deltaY / kPixelsPerTick;
if (offset_ordinal_y != 0.f && webkit_event.deltaY != 0.f)
webkit_event.accelerationRatioY = offset_ordinal_y / webkit_event.deltaY;
return webkit_event;
}
blink::WebGestureEvent MakeWebGestureEventFromAuraEvent(
ui::ScrollEvent* event) {
blink::WebGestureEvent webkit_event;
switch (event->type()) {
case ui::ET_SCROLL_FLING_START:
webkit_event.type = blink::WebInputEvent::GestureFlingStart;
webkit_event.data.flingStart.velocityX = event->x_offset();
webkit_event.data.flingStart.velocityY = event->y_offset();
break;
case ui::ET_SCROLL_FLING_CANCEL:
webkit_event.type = blink::WebInputEvent::GestureFlingCancel;
break;
case ui::ET_SCROLL:
NOTREACHED() << "Invalid gesture type: " << event->type();
break;
default:
NOTREACHED() << "Unknown gesture type: " << event->type();
}
webkit_event.sourceDevice = blink::WebGestureDeviceTouchpad;
webkit_event.modifiers = EventFlagsToWebEventModifiers(event->flags());
webkit_event.timeStampSeconds = event->time_stamp().InSecondsF();
return webkit_event;
}
#endif
blink::WebMouseEvent MakeWebMouseEventFromAuraEvent(
ui::MouseEvent* event);
blink::WebMouseWheelEvent MakeWebMouseWheelEventFromAuraEvent(
ui::MouseWheelEvent* event);
// General approach:
//
// ui::Event only carries a subset of possible event data provided to Aura by
// the host platform. WebKit utilizes a larger subset of that information than
// Aura itself. WebKit includes some built in cracking functionality that we
// rely on to obtain this information cleanly and consistently.
//
// The only place where an ui::Event's data differs from what the underlying
// base::NativeEvent would provide is position data, since we would like to
// provide coordinates relative to the aura::Window that is hosting the
// renderer, not the top level platform window.
//
// The approach is to fully construct a blink::WebInputEvent from the
// ui::Event's base::NativeEvent, and then replace the coordinate fields with
// the translated values from the ui::Event.
//
// The exception is mouse events on linux. The ui::MouseEvent contains enough
// necessary information to construct a WebMouseEvent. So instead of extracting
// the information from the XEvent, which can be tricky when supporting both
// XInput2 and XInput, the WebMouseEvent is constructed from the
// ui::MouseEvent. This will not be necessary once only XInput2 is supported.
//
blink::WebMouseEvent MakeWebMouseEvent(ui::MouseEvent* event) {
// Construct an untranslated event from the platform event data.
blink::WebMouseEvent webkit_event =
#if defined(OS_WIN)
// On Windows we have WM_ events comming from desktop and pure aura
// events comming from metro mode.
event->native_event().message ?
MakeUntranslatedWebMouseEventFromNativeEvent(event->native_event()) :
MakeWebMouseEventFromAuraEvent(event);
#else
MakeWebMouseEventFromAuraEvent(event);
#endif
// Replace the event's coordinate fields with translated position data from
// |event|.
webkit_event.windowX = webkit_event.x = event->x();
webkit_event.windowY = webkit_event.y = event->y();
#if defined(OS_WIN)
if (event->native_event().message)
return webkit_event;
#endif
const gfx::Point root_point = event->root_location();
webkit_event.globalX = root_point.x();
webkit_event.globalY = root_point.y();
return webkit_event;
}
blink::WebMouseWheelEvent MakeWebMouseWheelEvent(ui::MouseWheelEvent* event) {
#if defined(OS_WIN)
// Construct an untranslated event from the platform event data.
blink::WebMouseWheelEvent webkit_event = event->native_event().message ?
MakeUntranslatedWebMouseWheelEventFromNativeEvent(event->native_event()) :
MakeWebMouseWheelEventFromAuraEvent(event);
#else
blink::WebMouseWheelEvent webkit_event =
MakeWebMouseWheelEventFromAuraEvent(event);
#endif
// Replace the event's coordinate fields with translated position data from
// |event|.
webkit_event.windowX = webkit_event.x = event->x();
webkit_event.windowY = webkit_event.y = event->y();
const gfx::Point root_point = event->root_location();
webkit_event.globalX = root_point.x();
webkit_event.globalY = root_point.y();
return webkit_event;
}
blink::WebMouseWheelEvent MakeWebMouseWheelEvent(ui::ScrollEvent* event) {
#if defined(OS_WIN)
// Construct an untranslated event from the platform event data.
blink::WebMouseWheelEvent webkit_event =
MakeUntranslatedWebMouseWheelEventFromNativeEvent(event->native_event());
#else
blink::WebMouseWheelEvent webkit_event =
MakeWebMouseWheelEventFromAuraEvent(event);
#endif
// Replace the event's coordinate fields with translated position data from
// |event|.
webkit_event.windowX = webkit_event.x = event->x();
webkit_event.windowY = webkit_event.y = event->y();
const gfx::Point root_point = event->root_location();
webkit_event.globalX = root_point.x();
webkit_event.globalY = root_point.y();
return webkit_event;
}
blink::WebKeyboardEvent MakeWebKeyboardEvent(ui::KeyEvent* event) {
// Windows can figure out whether or not to construct a RawKeyDown or a Char
// WebInputEvent based on the type of message carried in
// event->native_event(). X11 is not so fortunate, there is no separate
// translated event type, so DesktopHostLinux sends an extra KeyEvent with
// is_char() == true. We need to pass the ui::KeyEvent to the X11 function
// to detect this case so the right event type can be constructed.
#if defined(OS_WIN)
if (!event->HasNativeEvent())
return blink::WebKeyboardEvent();
// Key events require no translation by the aura system.
return MakeWebKeyboardEventFromNativeEvent(event->native_event());
#else
return MakeWebKeyboardEventFromAuraEvent(event);
#endif
}
blink::WebGestureEvent MakeWebGestureEvent(ui::GestureEvent* event) {
blink::WebGestureEvent gesture_event;
#if defined(OS_WIN)
if (event->HasNativeEvent())
gesture_event = MakeWebGestureEventFromNativeEvent(event->native_event());
else
gesture_event = MakeWebGestureEventFromUIEvent(*event);
#else
gesture_event = MakeWebGestureEventFromUIEvent(*event);
#endif
gesture_event.x = event->x();
gesture_event.y = event->y();
const gfx::Point root_point = event->root_location();
gesture_event.globalX = root_point.x();
gesture_event.globalY = root_point.y();
return gesture_event;
}
blink::WebGestureEvent MakeWebGestureEvent(ui::ScrollEvent* event) {
blink::WebGestureEvent gesture_event;
#if defined(OS_WIN)
gesture_event = MakeWebGestureEventFromNativeEvent(event->native_event());
#else
gesture_event = MakeWebGestureEventFromAuraEvent(event);
#endif
gesture_event.x = event->x();
gesture_event.y = event->y();
const gfx::Point root_point = event->root_location();
gesture_event.globalX = root_point.x();
gesture_event.globalY = root_point.y();
return gesture_event;
}
blink::WebGestureEvent MakeWebGestureEventFlingCancel() {
blink::WebGestureEvent gesture_event;
// All other fields are ignored on a GestureFlingCancel event.
gesture_event.type = blink::WebInputEvent::GestureFlingCancel;
gesture_event.sourceDevice = blink::WebGestureDeviceTouchpad;
return gesture_event;
}
blink::WebMouseEvent MakeWebMouseEventFromAuraEvent(ui::MouseEvent* event) {
blink::WebMouseEvent webkit_event;
webkit_event.modifiers = EventFlagsToWebEventModifiers(event->flags());
webkit_event.timeStampSeconds = event->time_stamp().InSecondsF();
webkit_event.button = blink::WebMouseEvent::ButtonNone;
int button_flags = event->flags();
if (event->type() == ui::ET_MOUSE_PRESSED ||
event->type() == ui::ET_MOUSE_RELEASED) {
// We want to use changed_button_flags() for mouse pressed & released.
// These flags can be used only if they are set which is not always the case
// (see e.g. GetChangedMouseButtonFlagsFromNative() in events_win.cc).
if (event->changed_button_flags())
button_flags = event->changed_button_flags();
}
if (button_flags & ui::EF_LEFT_MOUSE_BUTTON)
webkit_event.button = blink::WebMouseEvent::ButtonLeft;
if (button_flags & ui::EF_MIDDLE_MOUSE_BUTTON)
webkit_event.button = blink::WebMouseEvent::ButtonMiddle;
if (button_flags & ui::EF_RIGHT_MOUSE_BUTTON)
webkit_event.button = blink::WebMouseEvent::ButtonRight;
switch (event->type()) {
case ui::ET_MOUSE_PRESSED:
webkit_event.type = blink::WebInputEvent::MouseDown;
webkit_event.clickCount = event->GetClickCount();
break;
case ui::ET_MOUSE_RELEASED:
webkit_event.type = blink::WebInputEvent::MouseUp;
webkit_event.clickCount = event->GetClickCount();
break;
case ui::ET_MOUSE_ENTERED:
case ui::ET_MOUSE_EXITED:
case ui::ET_MOUSE_MOVED:
case ui::ET_MOUSE_DRAGGED:
webkit_event.type = blink::WebInputEvent::MouseMove;
break;
default:
NOTIMPLEMENTED() << "Received unexpected event: " << event->type();
break;
}
return webkit_event;
}
blink::WebMouseWheelEvent MakeWebMouseWheelEventFromAuraEvent(
ui::MouseWheelEvent* event) {
blink::WebMouseWheelEvent webkit_event;
webkit_event.type = blink::WebInputEvent::MouseWheel;
webkit_event.button = blink::WebMouseEvent::ButtonNone;
webkit_event.modifiers = EventFlagsToWebEventModifiers(event->flags());
webkit_event.timeStampSeconds = event->time_stamp().InSecondsF();
if ((event->flags() & ui::EF_SHIFT_DOWN) != 0 && event->x_offset() == 0) {
webkit_event.deltaX = event->y_offset();
webkit_event.deltaY = 0;
} else {
webkit_event.deltaX = event->x_offset();
webkit_event.deltaY = event->y_offset();
}
webkit_event.wheelTicksX = webkit_event.deltaX / kPixelsPerTick;
webkit_event.wheelTicksY = webkit_event.deltaY / kPixelsPerTick;
return webkit_event;
}
} // namespace content
<|endoftext|> |
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/renderer/renderer_accessibility_focus_only.h"
#include "content/common/accessibility_node_data.h"
#include "content/renderer/render_view_impl.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebDocument.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebElement.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebFrame.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebNode.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebView.h"
using WebKit::WebDocument;
using WebKit::WebElement;
using WebKit::WebFrame;
using WebKit::WebNode;
using WebKit::WebView;
namespace {
// The root node will always have id 1. Let each child node have a new
// id starting with 2.
const int kInitialId = 2;
}
namespace content {
RendererAccessibilityFocusOnly::RendererAccessibilityFocusOnly(
RenderViewImpl* render_view)
: RendererAccessibility(render_view),
next_id_(kInitialId) {
}
RendererAccessibilityFocusOnly::~RendererAccessibilityFocusOnly() {
}
void RendererAccessibilityFocusOnly::HandleWebAccessibilityNotification(
const WebKit::WebAccessibilityObject& obj,
WebKit::WebAccessibilityNotification notification) {
// Do nothing.
}
void RendererAccessibilityFocusOnly::FocusedNodeChanged(const WebNode& node) {
// Send the new accessible tree and post a native focus event.
HandleFocusedNodeChanged(node, true);
}
void RendererAccessibilityFocusOnly::DidFinishLoad(WebKit::WebFrame* frame) {
WebView* view = render_view()->GetWebView();
if (view->focusedFrame() != frame)
return;
WebDocument document = frame->document();
// Send an accessible tree to the browser, but do not post a native
// focus event. This is important so that if focus is initially in an
// editable text field, Windows will know to pop up the keyboard if the
// user touches it and focus doesn't change.
HandleFocusedNodeChanged(document.focusedNode(), false);
}
void RendererAccessibilityFocusOnly::HandleFocusedNodeChanged(
const WebNode& node,
bool send_focus_event) {
const WebDocument& document = GetMainDocument();
if (document.isNull())
return;
bool node_has_focus;
bool node_is_editable_text;
// Check HasIMETextFocus first, because it will correctly handle
// focus in a text box inside a ppapi plug-in. Otherwise fall back on
// checking the focused node in WebKit.
if (render_view_->HasIMETextFocus()) {
node_has_focus = true;
node_is_editable_text = true;
} else {
node_has_focus = !node.isNull();
node_is_editable_text =
node_has_focus && render_view_->IsEditableNode(node);
}
std::vector<AccessibilityHostMsg_NotificationParams> notifications;
notifications.push_back(AccessibilityHostMsg_NotificationParams());
AccessibilityHostMsg_NotificationParams& notification = notifications[0];
// If we want to update the browser's accessibility tree but not send a
// native focus changed notification, we can send a LayoutComplete
// notification, which doesn't post a native event on Windows.
notification.notification_type =
send_focus_event ?
AccessibilityNotificationFocusChanged :
AccessibilityNotificationLayoutComplete;
// This means that the new tree we send supercedes any previous tree,
// not just a previous node.
notification.includes_children = true;
// Set the id that the notification applies to: the root node if nothing
// has focus, otherwise the focused node.
notification.id = node_has_focus ? next_id_ : 1;
// Always include the root of the tree, the document. It always has id 1.
notification.acc_tree.id = 1;
notification.acc_tree.role = AccessibilityNodeData::ROLE_ROOT_WEB_AREA;
notification.acc_tree.state =
(1 << AccessibilityNodeData::STATE_READONLY) |
(1 << AccessibilityNodeData::STATE_FOCUSABLE);
if (!node_has_focus)
notification.acc_tree.state |= (1 << AccessibilityNodeData::STATE_FOCUSED);
notification.acc_tree.location = gfx::Rect(render_view_->size());
notification.acc_tree.children.push_back(AccessibilityNodeData());
AccessibilityNodeData& child = notification.acc_tree.children[0];
child.id = next_id_;
child.role = AccessibilityNodeData::ROLE_GROUP;
if (!node.isNull() && node.isElementNode()) {
child.location = gfx::Rect(
const_cast<WebNode&>(node).to<WebElement>().boundsInViewportSpace());
} else {
child.location = gfx::Rect();
}
if (node_has_focus) {
child.state =
(1 << AccessibilityNodeData::STATE_FOCUSABLE) |
(1 << AccessibilityNodeData::STATE_FOCUSED);
if (!node_is_editable_text)
child.state |= (1 << AccessibilityNodeData::STATE_READONLY);
}
#ifndef NDEBUG
if (logging_) {
LOG(INFO) << "Accessibility update: \n"
<< "routing id=" << routing_id()
<< " notification="
<< AccessibilityNotificationToString(notification.notification_type)
<< "\n" << notification.acc_tree.DebugString(true);
}
#endif
Send(new AccessibilityHostMsg_Notifications(routing_id(), notifications));
// Increment the id, wrap back when we get past a million.
next_id_++;
if (next_id_ > 1000000)
next_id_ = kInitialId;
}
} // namespace content
<commit_msg>Make plug-in text fields open the win 8 on-screen keyboard on touch.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/renderer/renderer_accessibility_focus_only.h"
#include "content/common/accessibility_node_data.h"
#include "content/renderer/render_view_impl.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebDocument.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebElement.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebFrame.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebNode.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebView.h"
using WebKit::WebDocument;
using WebKit::WebElement;
using WebKit::WebFrame;
using WebKit::WebNode;
using WebKit::WebView;
namespace {
// The root node will always have id 1. Let each child node have a new
// id starting with 2.
const int kInitialId = 2;
}
namespace content {
RendererAccessibilityFocusOnly::RendererAccessibilityFocusOnly(
RenderViewImpl* render_view)
: RendererAccessibility(render_view),
next_id_(kInitialId) {
}
RendererAccessibilityFocusOnly::~RendererAccessibilityFocusOnly() {
}
void RendererAccessibilityFocusOnly::HandleWebAccessibilityNotification(
const WebKit::WebAccessibilityObject& obj,
WebKit::WebAccessibilityNotification notification) {
// Do nothing.
}
void RendererAccessibilityFocusOnly::FocusedNodeChanged(const WebNode& node) {
// Send the new accessible tree and post a native focus event.
HandleFocusedNodeChanged(node, true);
}
void RendererAccessibilityFocusOnly::DidFinishLoad(WebKit::WebFrame* frame) {
WebView* view = render_view()->GetWebView();
if (view->focusedFrame() != frame)
return;
WebDocument document = frame->document();
// Send an accessible tree to the browser, but do not post a native
// focus event. This is important so that if focus is initially in an
// editable text field, Windows will know to pop up the keyboard if the
// user touches it and focus doesn't change.
HandleFocusedNodeChanged(document.focusedNode(), false);
}
void RendererAccessibilityFocusOnly::HandleFocusedNodeChanged(
const WebNode& node,
bool send_focus_event) {
const WebDocument& document = GetMainDocument();
if (document.isNull())
return;
bool node_has_focus;
bool node_is_editable_text;
// Check HasIMETextFocus first, because it will correctly handle
// focus in a text box inside a ppapi plug-in. Otherwise fall back on
// checking the focused node in WebKit.
if (render_view_->HasIMETextFocus()) {
node_has_focus = true;
node_is_editable_text = true;
} else {
node_has_focus = !node.isNull();
node_is_editable_text =
node_has_focus && render_view_->IsEditableNode(node);
}
std::vector<AccessibilityHostMsg_NotificationParams> notifications;
notifications.push_back(AccessibilityHostMsg_NotificationParams());
AccessibilityHostMsg_NotificationParams& notification = notifications[0];
// If we want to update the browser's accessibility tree but not send a
// native focus changed notification, we can send a LayoutComplete
// notification, which doesn't post a native event on Windows.
notification.notification_type =
send_focus_event ?
AccessibilityNotificationFocusChanged :
AccessibilityNotificationLayoutComplete;
// This means that the new tree we send supercedes any previous tree,
// not just a previous node.
notification.includes_children = true;
// Set the id that the notification applies to: the root node if nothing
// has focus, otherwise the focused node.
notification.id = node_has_focus ? next_id_ : 1;
// Always include the root of the tree, the document. It always has id 1.
notification.acc_tree.id = 1;
notification.acc_tree.role = AccessibilityNodeData::ROLE_ROOT_WEB_AREA;
notification.acc_tree.state =
(1 << AccessibilityNodeData::STATE_READONLY) |
(1 << AccessibilityNodeData::STATE_FOCUSABLE);
if (!node_has_focus)
notification.acc_tree.state |= (1 << AccessibilityNodeData::STATE_FOCUSED);
notification.acc_tree.location = gfx::Rect(render_view_->size());
notification.acc_tree.children.push_back(AccessibilityNodeData());
AccessibilityNodeData& child = notification.acc_tree.children[0];
child.id = next_id_;
child.role = AccessibilityNodeData::ROLE_GROUP;
if (!node.isNull() && node.isElementNode()) {
child.location = gfx::Rect(
const_cast<WebNode&>(node).to<WebElement>().boundsInViewportSpace());
} else if (render_view_->HasIMETextFocus()) {
child.location = notification.acc_tree.location;
} else {
child.location = gfx::Rect();
}
if (node_has_focus) {
child.state =
(1 << AccessibilityNodeData::STATE_FOCUSABLE) |
(1 << AccessibilityNodeData::STATE_FOCUSED);
if (!node_is_editable_text)
child.state |= (1 << AccessibilityNodeData::STATE_READONLY);
}
#ifndef NDEBUG
if (logging_) {
LOG(INFO) << "Accessibility update: \n"
<< "routing id=" << routing_id()
<< " notification="
<< AccessibilityNotificationToString(notification.notification_type)
<< "\n" << notification.acc_tree.DebugString(true);
}
#endif
Send(new AccessibilityHostMsg_Notifications(routing_id(), notifications));
// Increment the id, wrap back when we get past a million.
next_id_++;
if (next_id_ > 1000000)
next_id_ = kInitialId;
}
} // namespace content
<|endoftext|> |
<commit_before>/*
FMD DA for online calibration of conditions
Contact: canute@nbi.dk
Link: fmd.nbi.dk/fmd/offline
Run Type: GAIN
DA Type: LDC
Number of events needed: usually 102400
Input Files: raw data
Output Files: gains.csv
Trigger types used: GAIN
*/
#include <TSystem.h>
#include <TString.h>
#include <AliFMDParameters.h>
#include <AliRawReader.h>
#include <TStopwatch.h>
#include <AliFMDGainDA.h>
#include <AliRawReaderDate.h>
#include <AliRawReaderRoot.h>
#include "daqDA.h"
#include "TROOT.h"
#include "TPluginManager.h"
int main(int argc, char **argv)
{
gROOT->GetPluginManager()->AddHandler("TVirtualStreamerInfo",
"*",
"TStreamerInfo",
"RIO",
"TStreamerInfo()");
Bool_t diagnostics = kFALSE;
Char_t* fileName = argv[1];
TString secondArgument(argv[2]);
if(secondArgument.Contains("--diagnostics=true"))
diagnostics = kTRUE;
if(secondArgument.Contains("--help")) {
std::cout<<"Usage: filename --diagnostics=true/false . --help this help"<<std::endl;
return 0;
}
if(!secondArgument.IsWhitespace()&& !secondArgument.Contains("--help")
&& !secondArgument.Contains("--diagnostics=true")) {
std::cout<<"Second argument wrong. Use --help"<<std::endl;
return -1;
}
Bool_t old = kTRUE;
AliFMDParameters::Instance()->Init(kFALSE,0);
//This will only work for FDR 1 data. When newer data becomes available the ! must be removed!
AliFMDParameters::Instance()->UseCompleteHeader(!old);
AliRawReader *reader = 0;
TString fileNam(fileName);
if (fileNam.EndsWith(".root")) reader = new AliRawReaderRoot(fileName);
else reader = new AliRawReaderDate(fileName);
if (!reader) {
std::cerr << "Don't know how to make reader for " << fileNam
<< std::endl;
return -2;
}
TStopwatch timer;
timer.Start();
AliFMDGainDA gainDA;
gainDA.SetSaveDiagnostics(diagnostics);
gainDA.Run(reader);
timer.Stop();
timer.Print();
Int_t retvalConditions = daqDA_FES_storeFile("conditions.csv", AliFMDParameters::Instance()->GetConditionsShuttleID());
Int_t retvalGain = daqDA_FES_storeFile("gains.csv", AliFMDParameters::Instance()->GetGainShuttleID());
if(retvalConditions!=0 || retvalGain!=0)
std::cerr << "Pedestal DA failed" << std::endl;
if(retvalGain != 0) return retvalGain;
else return retvalConditions;
}
<commit_msg>New version to recon the coming of the SOD event<commit_after>/*
FMD DA for online calibration of conditions
Contact: canute@nbi.dk
Link: fmd.nbi.dk/fmd/offline
Run Type: GAIN
DA Type: LDC
Number of events needed: usually 102400
Input Files: raw data
Output Files: gains.csv
Trigger types used: GAIN
*/
#include <TSystem.h>
#include <TString.h>
#include <AliFMDParameters.h>
#include <AliRawReader.h>
#include <TStopwatch.h>
#include <AliFMDGainDA.h>
#include <AliRawReaderDate.h>
#include <AliRawReaderRoot.h>
#include <AliLog.h>
#include "daqDA.h"
#include "TROOT.h"
#include "TPluginManager.h"
int main(int argc, char **argv)
{
gROOT->GetPluginManager()->AddHandler("TVirtualStreamerInfo",
"*",
"TStreamerInfo",
"RIO",
"TStreamerInfo()");
Bool_t diagnostics = kFALSE;
Char_t* fileName = argv[1];
TString secondArgument(argv[2]);
if(secondArgument.Contains("--diagnostics=true"))
diagnostics = kTRUE;
if(secondArgument.Contains("--help")) {
std::cout<<"Usage: filename --diagnostics=true/false . --help this help"<<std::endl;
return 0;
}
if(!secondArgument.IsWhitespace()&& !secondArgument.Contains("--help")
&& !secondArgument.Contains("--diagnostics=true")) {
std::cout<<"Second argument wrong. Use --help"<<std::endl;
return -1;
}
Bool_t old = kTRUE;
AliFMDParameters::Instance()->Init(kFALSE,0);
//This will only work for FDR 1 data. When newer data becomes available the ! must be removed!
AliFMDParameters::Instance()->UseCompleteHeader(old);
AliLog::SetModuleDebugLevel("FMD", 1);
AliRawReader *reader = 0;
TString fileNam(fileName);
if (fileNam.EndsWith(".root"))
reader = new AliRawReaderRoot(fileName);
else reader = new AliRawReaderDate(fileName);
if (!reader) {
std::cerr << "Don't know how to make reader for " << fileNam
<< std::endl;
return -2;
}
TStopwatch timer;
timer.Start();
AliFMDGainDA gainDA;
gainDA.SetSaveDiagnostics(diagnostics);
gainDA.Run(reader);
timer.Stop();
timer.Print();
Int_t retvalConditions = daqDA_FES_storeFile("conditions.csv", AliFMDParameters::Instance()->GetConditionsShuttleID());
Int_t retvalGain = daqDA_FES_storeFile("gains.csv", AliFMDParameters::Instance()->GetGainShuttleID());
if(retvalConditions!=0 || retvalGain!=0)
std::cerr << "Pedestal DA failed" << std::endl;
if(retvalGain != 0) return retvalGain;
else return retvalConditions;
}
<|endoftext|> |
<commit_before>// Copyright 2014 PDFium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com
#include "../../../include/fpdfapi/fpdf_parser.h"
#include "../../../include/fpdfapi/fpdf_module.h"
CPDF_Document::CPDF_Document(CPDF_Parser* pParser)
: CPDF_IndirectObjects(pParser) {
ASSERT(pParser != NULL);
m_pRootDict = NULL;
m_pInfoDict = NULL;
m_bLinearized = FALSE;
m_dwFirstPageNo = 0;
m_dwFirstPageObjNum = 0;
m_pDocPage = CPDF_ModuleMgr::Get()->GetPageModule()->CreateDocData(this);
m_pDocRender = CPDF_ModuleMgr::Get()->GetRenderModule()->CreateDocData(this);
}
CPDF_DocPageData* CPDF_Document::GetValidatePageData() {
if (m_pDocPage) {
return m_pDocPage;
}
m_pDocPage = CPDF_ModuleMgr::Get()->GetPageModule()->CreateDocData(this);
return m_pDocPage;
}
CPDF_DocRenderData* CPDF_Document::GetValidateRenderData() {
if (m_pDocRender) {
return m_pDocRender;
}
m_pDocRender = CPDF_ModuleMgr::Get()->GetRenderModule()->CreateDocData(this);
return m_pDocRender;
}
void CPDF_Document::LoadDoc() {
m_LastObjNum = m_pParser->GetLastObjNum();
CPDF_Object* pRootObj = GetIndirectObject(m_pParser->GetRootObjNum());
if (pRootObj == NULL) {
return;
}
m_pRootDict = pRootObj->GetDict();
if (m_pRootDict == NULL) {
return;
}
CPDF_Object* pInfoObj = GetIndirectObject(m_pParser->GetInfoObjNum());
if (pInfoObj) {
m_pInfoDict = pInfoObj->GetDict();
}
CPDF_Array* pIDArray = m_pParser->GetIDArray();
if (pIDArray) {
m_ID1 = pIDArray->GetString(0);
m_ID2 = pIDArray->GetString(1);
}
m_PageList.SetSize(_GetPageCount());
}
void CPDF_Document::LoadAsynDoc(CPDF_Dictionary* pLinearized) {
m_bLinearized = TRUE;
m_LastObjNum = m_pParser->GetLastObjNum();
CPDF_Object* indirectObj = GetIndirectObject(m_pParser->GetRootObjNum());
m_pRootDict = indirectObj ? indirectObj->GetDict() : NULL;
if (m_pRootDict == NULL) {
return;
}
indirectObj = GetIndirectObject(m_pParser->GetInfoObjNum());
m_pInfoDict = indirectObj ? indirectObj->GetDict() : NULL;
CPDF_Array* pIDArray = m_pParser->GetIDArray();
if (pIDArray) {
m_ID1 = pIDArray->GetString(0);
m_ID2 = pIDArray->GetString(1);
}
FX_DWORD dwPageCount = 0;
CPDF_Object* pCount = pLinearized->GetElement(FX_BSTRC("N"));
if (pCount && pCount->GetType() == PDFOBJ_NUMBER) {
dwPageCount = pCount->GetInteger();
}
m_PageList.SetSize(dwPageCount);
CPDF_Object* pNo = pLinearized->GetElement(FX_BSTRC("P"));
if (pNo && pNo->GetType() == PDFOBJ_NUMBER) {
m_dwFirstPageNo = pNo->GetInteger();
}
CPDF_Object* pObjNum = pLinearized->GetElement(FX_BSTRC("O"));
if (pObjNum && pObjNum->GetType() == PDFOBJ_NUMBER) {
m_dwFirstPageObjNum = pObjNum->GetInteger();
}
}
void CPDF_Document::LoadPages() {
m_PageList.SetSize(_GetPageCount());
}
CPDF_Document::~CPDF_Document() {
if (m_pDocPage) {
CPDF_ModuleMgr::Get()->GetPageModule()->ReleaseDoc(this);
CPDF_ModuleMgr::Get()->GetPageModule()->ClearStockFont(this);
}
if (m_pDocRender) {
CPDF_ModuleMgr::Get()->GetRenderModule()->DestroyDocData(m_pDocRender);
}
}
#define FX_MAX_PAGE_LEVEL 1024
CPDF_Dictionary* CPDF_Document::_FindPDFPage(CPDF_Dictionary* pPages,
int iPage,
int nPagesToGo,
int level) {
CPDF_Array* pKidList = pPages->GetArray(FX_BSTRC("Kids"));
if (pKidList == NULL) {
if (nPagesToGo == 0) {
return pPages;
}
return NULL;
}
if (level >= FX_MAX_PAGE_LEVEL) {
return NULL;
}
int nKids = pKidList->GetCount();
for (int i = 0; i < nKids; i++) {
CPDF_Dictionary* pKid = pKidList->GetDict(i);
if (pKid == NULL) {
nPagesToGo--;
continue;
}
if (pKid == pPages) {
continue;
}
if (!pKid->KeyExist(FX_BSTRC("Kids"))) {
if (nPagesToGo == 0) {
return pKid;
}
m_PageList.SetAt(iPage - nPagesToGo, pKid->GetObjNum());
nPagesToGo--;
} else {
int nPages = pKid->GetInteger(FX_BSTRC("Count"));
if (nPagesToGo < nPages) {
return _FindPDFPage(pKid, iPage, nPagesToGo, level + 1);
}
nPagesToGo -= nPages;
}
}
return NULL;
}
CPDF_Dictionary* CPDF_Document::GetPage(int iPage) {
if (iPage < 0 || iPage >= m_PageList.GetSize()) {
return NULL;
}
if (m_bLinearized && (iPage == (int)m_dwFirstPageNo)) {
CPDF_Object* pObj = GetIndirectObject(m_dwFirstPageObjNum);
if (pObj && pObj->GetType() == PDFOBJ_DICTIONARY) {
return (CPDF_Dictionary*)pObj;
}
}
int objnum = m_PageList.GetAt(iPage);
if (objnum) {
CPDF_Object* pObj = GetIndirectObject(objnum);
ASSERT(pObj->GetType() == PDFOBJ_DICTIONARY);
return (CPDF_Dictionary*)pObj;
}
CPDF_Dictionary* pRoot = GetRoot();
if (pRoot == NULL) {
return NULL;
}
CPDF_Dictionary* pPages = pRoot->GetDict(FX_BSTRC("Pages"));
if (pPages == NULL) {
return NULL;
}
CPDF_Dictionary* pPage = _FindPDFPage(pPages, iPage, iPage, 0);
if (pPage == NULL) {
return NULL;
}
m_PageList.SetAt(iPage, pPage->GetObjNum());
return pPage;
}
int CPDF_Document::_FindPageIndex(CPDF_Dictionary* pNode,
FX_DWORD& skip_count,
FX_DWORD objnum,
int& index,
int level) {
if (pNode->KeyExist(FX_BSTRC("Kids"))) {
CPDF_Array* pKidList = pNode->GetArray(FX_BSTRC("Kids"));
if (pKidList == NULL) {
return -1;
}
if (level >= FX_MAX_PAGE_LEVEL) {
return -1;
}
FX_DWORD count = pNode->GetInteger(FX_BSTRC("Count"));
if (count <= skip_count) {
skip_count -= count;
index += count;
return -1;
}
if (count && count == pKidList->GetCount()) {
for (FX_DWORD i = 0; i < count; i++) {
CPDF_Object* pKid = pKidList->GetElement(i);
if (pKid && pKid->GetType() == PDFOBJ_REFERENCE) {
if (((CPDF_Reference*)pKid)->GetRefObjNum() == objnum) {
m_PageList.SetAt(index + i, objnum);
return index + i;
}
}
}
}
for (FX_DWORD i = 0; i < pKidList->GetCount(); i++) {
CPDF_Dictionary* pKid = pKidList->GetDict(i);
if (pKid == NULL) {
continue;
}
if (pKid == pNode) {
continue;
}
int found_index =
_FindPageIndex(pKid, skip_count, objnum, index, level + 1);
if (found_index >= 0) {
return found_index;
}
}
} else {
if (objnum == pNode->GetObjNum()) {
return index;
}
if (skip_count) {
skip_count--;
}
index++;
}
return -1;
}
int CPDF_Document::GetPageIndex(FX_DWORD objnum) {
FX_DWORD nPages = m_PageList.GetSize();
FX_DWORD skip_count = 0;
FX_BOOL bSkipped = FALSE;
for (FX_DWORD i = 0; i < nPages; i++) {
FX_DWORD objnum1 = m_PageList.GetAt(i);
if (objnum1 == objnum) {
return i;
}
if (!bSkipped && objnum1 == 0) {
skip_count = i;
bSkipped = TRUE;
}
}
CPDF_Dictionary* pRoot = GetRoot();
if (pRoot == NULL) {
return -1;
}
CPDF_Dictionary* pPages = pRoot->GetDict(FX_BSTRC("Pages"));
if (pPages == NULL) {
return -1;
}
int index = 0;
return _FindPageIndex(pPages, skip_count, objnum, index);
}
int CPDF_Document::GetPageCount() const {
return m_PageList.GetSize();
}
static int _CountPages(CPDF_Dictionary* pPages, int level) {
if (level > 128) {
return 0;
}
int count = pPages->GetInteger(FX_BSTRC("Count"));
if (count > 0 && count < FPDF_PAGE_MAX_NUM) {
return count;
}
CPDF_Array* pKidList = pPages->GetArray(FX_BSTRC("Kids"));
if (pKidList == NULL) {
return 0;
}
count = 0;
for (FX_DWORD i = 0; i < pKidList->GetCount(); i++) {
CPDF_Dictionary* pKid = pKidList->GetDict(i);
if (pKid == NULL) {
continue;
}
if (!pKid->KeyExist(FX_BSTRC("Kids"))) {
count++;
} else {
count += _CountPages(pKid, level + 1);
}
}
pPages->SetAtInteger(FX_BSTRC("Count"), count);
return count;
}
int CPDF_Document::_GetPageCount() const {
CPDF_Dictionary* pRoot = GetRoot();
if (pRoot == NULL) {
return 0;
}
CPDF_Dictionary* pPages = pRoot->GetDict(FX_BSTRC("Pages"));
if (pPages == NULL) {
return 0;
}
if (!pPages->KeyExist(FX_BSTRC("Kids"))) {
return 1;
}
return _CountPages(pPages, 0);
}
FX_BOOL CPDF_Document::IsContentUsedElsewhere(FX_DWORD objnum,
CPDF_Dictionary* pThisPageDict) {
for (int i = 0; i < m_PageList.GetSize(); i++) {
CPDF_Dictionary* pPageDict = GetPage(i);
if (pPageDict == pThisPageDict) {
continue;
}
CPDF_Object* pContents =
pPageDict ? pPageDict->GetElement(FX_BSTRC("Contents")) : NULL;
if (pContents == NULL) {
continue;
}
if (pContents->GetDirectType() == PDFOBJ_ARRAY) {
CPDF_Array* pArray = (CPDF_Array*)pContents->GetDirect();
for (FX_DWORD j = 0; j < pArray->GetCount(); j++) {
CPDF_Object* pRef = pArray->GetElement(j);
if (pRef == NULL || pRef->GetType() != PDFOBJ_REFERENCE) {
continue;
}
if (((CPDF_Reference*)pRef)->GetRefObjNum() == objnum) {
return TRUE;
}
}
} else if (pContents->GetObjNum() == objnum) {
return TRUE;
}
}
return FALSE;
}
FX_DWORD CPDF_Document::GetUserPermissions(FX_BOOL bCheckRevision) const {
if (m_pParser == NULL) {
return (FX_DWORD)-1;
}
return m_pParser->GetPermissions(bCheckRevision);
}
FX_BOOL CPDF_Document::IsOwner() const {
if (m_pParser == NULL) {
return TRUE;
}
return m_pParser->IsOwner();
}
FX_BOOL CPDF_Document::IsFormStream(FX_DWORD objnum, FX_BOOL& bForm) const {
{
CPDF_Object* pObj;
if (m_IndirectObjs.Lookup((void*)(uintptr_t)objnum, (void*&)pObj)) {
bForm = pObj->GetType() == PDFOBJ_STREAM &&
((CPDF_Stream*)pObj)->GetDict()->GetString(FX_BSTRC("Subtype")) ==
FX_BSTRC("Form");
return TRUE;
}
}
if (m_pParser == NULL) {
bForm = FALSE;
return TRUE;
}
return m_pParser->IsFormStream(objnum, bForm);
}
void CPDF_Document::ClearPageData() {
if (m_pDocPage) {
CPDF_ModuleMgr::Get()->GetPageModule()->ClearDoc(this);
}
}
void CPDF_Document::ClearRenderData() {
if (m_pDocRender) {
CPDF_ModuleMgr::Get()->GetRenderModule()->ClearDocData(m_pDocRender);
}
}
<commit_msg>Turn a failing assert into an actual check.<commit_after>// Copyright 2014 PDFium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com
#include "../../../include/fpdfapi/fpdf_parser.h"
#include "../../../include/fpdfapi/fpdf_module.h"
CPDF_Document::CPDF_Document(CPDF_Parser* pParser)
: CPDF_IndirectObjects(pParser) {
ASSERT(pParser != NULL);
m_pRootDict = NULL;
m_pInfoDict = NULL;
m_bLinearized = FALSE;
m_dwFirstPageNo = 0;
m_dwFirstPageObjNum = 0;
m_pDocPage = CPDF_ModuleMgr::Get()->GetPageModule()->CreateDocData(this);
m_pDocRender = CPDF_ModuleMgr::Get()->GetRenderModule()->CreateDocData(this);
}
CPDF_DocPageData* CPDF_Document::GetValidatePageData() {
if (m_pDocPage) {
return m_pDocPage;
}
m_pDocPage = CPDF_ModuleMgr::Get()->GetPageModule()->CreateDocData(this);
return m_pDocPage;
}
CPDF_DocRenderData* CPDF_Document::GetValidateRenderData() {
if (m_pDocRender) {
return m_pDocRender;
}
m_pDocRender = CPDF_ModuleMgr::Get()->GetRenderModule()->CreateDocData(this);
return m_pDocRender;
}
void CPDF_Document::LoadDoc() {
m_LastObjNum = m_pParser->GetLastObjNum();
CPDF_Object* pRootObj = GetIndirectObject(m_pParser->GetRootObjNum());
if (pRootObj == NULL) {
return;
}
m_pRootDict = pRootObj->GetDict();
if (m_pRootDict == NULL) {
return;
}
CPDF_Object* pInfoObj = GetIndirectObject(m_pParser->GetInfoObjNum());
if (pInfoObj) {
m_pInfoDict = pInfoObj->GetDict();
}
CPDF_Array* pIDArray = m_pParser->GetIDArray();
if (pIDArray) {
m_ID1 = pIDArray->GetString(0);
m_ID2 = pIDArray->GetString(1);
}
m_PageList.SetSize(_GetPageCount());
}
void CPDF_Document::LoadAsynDoc(CPDF_Dictionary* pLinearized) {
m_bLinearized = TRUE;
m_LastObjNum = m_pParser->GetLastObjNum();
CPDF_Object* indirectObj = GetIndirectObject(m_pParser->GetRootObjNum());
m_pRootDict = indirectObj ? indirectObj->GetDict() : NULL;
if (m_pRootDict == NULL) {
return;
}
indirectObj = GetIndirectObject(m_pParser->GetInfoObjNum());
m_pInfoDict = indirectObj ? indirectObj->GetDict() : NULL;
CPDF_Array* pIDArray = m_pParser->GetIDArray();
if (pIDArray) {
m_ID1 = pIDArray->GetString(0);
m_ID2 = pIDArray->GetString(1);
}
FX_DWORD dwPageCount = 0;
CPDF_Object* pCount = pLinearized->GetElement(FX_BSTRC("N"));
if (pCount && pCount->GetType() == PDFOBJ_NUMBER) {
dwPageCount = pCount->GetInteger();
}
m_PageList.SetSize(dwPageCount);
CPDF_Object* pNo = pLinearized->GetElement(FX_BSTRC("P"));
if (pNo && pNo->GetType() == PDFOBJ_NUMBER) {
m_dwFirstPageNo = pNo->GetInteger();
}
CPDF_Object* pObjNum = pLinearized->GetElement(FX_BSTRC("O"));
if (pObjNum && pObjNum->GetType() == PDFOBJ_NUMBER) {
m_dwFirstPageObjNum = pObjNum->GetInteger();
}
}
void CPDF_Document::LoadPages() {
m_PageList.SetSize(_GetPageCount());
}
CPDF_Document::~CPDF_Document() {
if (m_pDocPage) {
CPDF_ModuleMgr::Get()->GetPageModule()->ReleaseDoc(this);
CPDF_ModuleMgr::Get()->GetPageModule()->ClearStockFont(this);
}
if (m_pDocRender) {
CPDF_ModuleMgr::Get()->GetRenderModule()->DestroyDocData(m_pDocRender);
}
}
#define FX_MAX_PAGE_LEVEL 1024
CPDF_Dictionary* CPDF_Document::_FindPDFPage(CPDF_Dictionary* pPages,
int iPage,
int nPagesToGo,
int level) {
CPDF_Array* pKidList = pPages->GetArray(FX_BSTRC("Kids"));
if (pKidList == NULL) {
if (nPagesToGo == 0) {
return pPages;
}
return NULL;
}
if (level >= FX_MAX_PAGE_LEVEL) {
return NULL;
}
int nKids = pKidList->GetCount();
for (int i = 0; i < nKids; i++) {
CPDF_Dictionary* pKid = pKidList->GetDict(i);
if (pKid == NULL) {
nPagesToGo--;
continue;
}
if (pKid == pPages) {
continue;
}
if (!pKid->KeyExist(FX_BSTRC("Kids"))) {
if (nPagesToGo == 0) {
return pKid;
}
m_PageList.SetAt(iPage - nPagesToGo, pKid->GetObjNum());
nPagesToGo--;
} else {
int nPages = pKid->GetInteger(FX_BSTRC("Count"));
if (nPagesToGo < nPages) {
return _FindPDFPage(pKid, iPage, nPagesToGo, level + 1);
}
nPagesToGo -= nPages;
}
}
return NULL;
}
CPDF_Dictionary* CPDF_Document::GetPage(int iPage) {
if (iPage < 0 || iPage >= m_PageList.GetSize())
return nullptr;
if (m_bLinearized && (iPage == (int)m_dwFirstPageNo)) {
CPDF_Object* pObj = GetIndirectObject(m_dwFirstPageObjNum);
if (pObj && pObj->GetType() == PDFOBJ_DICTIONARY) {
return static_cast<CPDF_Dictionary*>(pObj);
}
}
int objnum = m_PageList.GetAt(iPage);
if (objnum) {
CPDF_Object* pObj = GetIndirectObject(objnum);
if (pObj && pObj->GetType() == PDFOBJ_DICTIONARY) {
return static_cast<CPDF_Dictionary*>(pObj);
}
}
CPDF_Dictionary* pRoot = GetRoot();
if (!pRoot)
return nullptr;
CPDF_Dictionary* pPages = pRoot->GetDict(FX_BSTRC("Pages"));
if (!pPages)
return nullptr;
CPDF_Dictionary* pPage = _FindPDFPage(pPages, iPage, iPage, 0);
if (!pPage)
return nullptr;
m_PageList.SetAt(iPage, pPage->GetObjNum());
return pPage;
}
int CPDF_Document::_FindPageIndex(CPDF_Dictionary* pNode,
FX_DWORD& skip_count,
FX_DWORD objnum,
int& index,
int level) {
if (pNode->KeyExist(FX_BSTRC("Kids"))) {
CPDF_Array* pKidList = pNode->GetArray(FX_BSTRC("Kids"));
if (pKidList == NULL) {
return -1;
}
if (level >= FX_MAX_PAGE_LEVEL) {
return -1;
}
FX_DWORD count = pNode->GetInteger(FX_BSTRC("Count"));
if (count <= skip_count) {
skip_count -= count;
index += count;
return -1;
}
if (count && count == pKidList->GetCount()) {
for (FX_DWORD i = 0; i < count; i++) {
CPDF_Object* pKid = pKidList->GetElement(i);
if (pKid && pKid->GetType() == PDFOBJ_REFERENCE) {
if (((CPDF_Reference*)pKid)->GetRefObjNum() == objnum) {
m_PageList.SetAt(index + i, objnum);
return index + i;
}
}
}
}
for (FX_DWORD i = 0; i < pKidList->GetCount(); i++) {
CPDF_Dictionary* pKid = pKidList->GetDict(i);
if (pKid == NULL) {
continue;
}
if (pKid == pNode) {
continue;
}
int found_index =
_FindPageIndex(pKid, skip_count, objnum, index, level + 1);
if (found_index >= 0) {
return found_index;
}
}
} else {
if (objnum == pNode->GetObjNum()) {
return index;
}
if (skip_count) {
skip_count--;
}
index++;
}
return -1;
}
int CPDF_Document::GetPageIndex(FX_DWORD objnum) {
FX_DWORD nPages = m_PageList.GetSize();
FX_DWORD skip_count = 0;
FX_BOOL bSkipped = FALSE;
for (FX_DWORD i = 0; i < nPages; i++) {
FX_DWORD objnum1 = m_PageList.GetAt(i);
if (objnum1 == objnum) {
return i;
}
if (!bSkipped && objnum1 == 0) {
skip_count = i;
bSkipped = TRUE;
}
}
CPDF_Dictionary* pRoot = GetRoot();
if (pRoot == NULL) {
return -1;
}
CPDF_Dictionary* pPages = pRoot->GetDict(FX_BSTRC("Pages"));
if (pPages == NULL) {
return -1;
}
int index = 0;
return _FindPageIndex(pPages, skip_count, objnum, index);
}
int CPDF_Document::GetPageCount() const {
return m_PageList.GetSize();
}
static int _CountPages(CPDF_Dictionary* pPages, int level) {
if (level > 128) {
return 0;
}
int count = pPages->GetInteger(FX_BSTRC("Count"));
if (count > 0 && count < FPDF_PAGE_MAX_NUM) {
return count;
}
CPDF_Array* pKidList = pPages->GetArray(FX_BSTRC("Kids"));
if (pKidList == NULL) {
return 0;
}
count = 0;
for (FX_DWORD i = 0; i < pKidList->GetCount(); i++) {
CPDF_Dictionary* pKid = pKidList->GetDict(i);
if (pKid == NULL) {
continue;
}
if (!pKid->KeyExist(FX_BSTRC("Kids"))) {
count++;
} else {
count += _CountPages(pKid, level + 1);
}
}
pPages->SetAtInteger(FX_BSTRC("Count"), count);
return count;
}
int CPDF_Document::_GetPageCount() const {
CPDF_Dictionary* pRoot = GetRoot();
if (pRoot == NULL) {
return 0;
}
CPDF_Dictionary* pPages = pRoot->GetDict(FX_BSTRC("Pages"));
if (pPages == NULL) {
return 0;
}
if (!pPages->KeyExist(FX_BSTRC("Kids"))) {
return 1;
}
return _CountPages(pPages, 0);
}
FX_BOOL CPDF_Document::IsContentUsedElsewhere(FX_DWORD objnum,
CPDF_Dictionary* pThisPageDict) {
for (int i = 0; i < m_PageList.GetSize(); i++) {
CPDF_Dictionary* pPageDict = GetPage(i);
if (pPageDict == pThisPageDict) {
continue;
}
CPDF_Object* pContents =
pPageDict ? pPageDict->GetElement(FX_BSTRC("Contents")) : NULL;
if (pContents == NULL) {
continue;
}
if (pContents->GetDirectType() == PDFOBJ_ARRAY) {
CPDF_Array* pArray = (CPDF_Array*)pContents->GetDirect();
for (FX_DWORD j = 0; j < pArray->GetCount(); j++) {
CPDF_Object* pRef = pArray->GetElement(j);
if (pRef == NULL || pRef->GetType() != PDFOBJ_REFERENCE) {
continue;
}
if (((CPDF_Reference*)pRef)->GetRefObjNum() == objnum) {
return TRUE;
}
}
} else if (pContents->GetObjNum() == objnum) {
return TRUE;
}
}
return FALSE;
}
FX_DWORD CPDF_Document::GetUserPermissions(FX_BOOL bCheckRevision) const {
if (m_pParser == NULL) {
return (FX_DWORD)-1;
}
return m_pParser->GetPermissions(bCheckRevision);
}
FX_BOOL CPDF_Document::IsOwner() const {
if (m_pParser == NULL) {
return TRUE;
}
return m_pParser->IsOwner();
}
FX_BOOL CPDF_Document::IsFormStream(FX_DWORD objnum, FX_BOOL& bForm) const {
{
CPDF_Object* pObj;
if (m_IndirectObjs.Lookup((void*)(uintptr_t)objnum, (void*&)pObj)) {
bForm = pObj->GetType() == PDFOBJ_STREAM &&
((CPDF_Stream*)pObj)->GetDict()->GetString(FX_BSTRC("Subtype")) ==
FX_BSTRC("Form");
return TRUE;
}
}
if (m_pParser == NULL) {
bForm = FALSE;
return TRUE;
}
return m_pParser->IsFormStream(objnum, bForm);
}
void CPDF_Document::ClearPageData() {
if (m_pDocPage) {
CPDF_ModuleMgr::Get()->GetPageModule()->ClearDoc(this);
}
}
void CPDF_Document::ClearRenderData() {
if (m_pDocRender) {
CPDF_ModuleMgr::Get()->GetRenderModule()->ClearDocData(m_pDocRender);
}
}
<|endoftext|> |
<commit_before>/**
* @file
* @author 2012 Stefan Radomski (stefan.radomski@cs.tu-darmstadt.de)
* @copyright Simplified BSD
*
* @cond
* This program is free software: you can redistribute it and/or modify
* it under the terms of the FreeBSD license as published by the FreeBSD
* project.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*
* You should have received a copy of the FreeBSD license along with this
* program. If not, see <http://www.opensource.org/licenses/bsd-license>.
* @endcond
*/
#ifdef WIN32
#include <time.h>
#include <WinSock2.h>
#include <ws2tcpip.h>
#include <Windows.h>
#endif
#include "umundo/connection/zeromq/ZeroMQPublisher.h"
#include "umundo/connection/zeromq/ZeroMQNode.h"
#include "umundo/common/Message.h"
#include "umundo/common/UUID.h"
#include "umundo/config.h"
#if defined UNIX || defined IOS || defined IOSSIM
#include <string.h> // strlen, memcpy
#include <stdio.h> // snprintf
#endif
namespace umundo {
shared_ptr<Implementation> ZeroMQPublisher::create(void* facade) {
shared_ptr<Implementation> instance(new ZeroMQPublisher());
boost::static_pointer_cast<ZeroMQPublisher>(instance)->_facade = facade;
return instance;
}
void ZeroMQPublisher::destroy() {
delete(this);
}
void ZeroMQPublisher::init(shared_ptr<Configuration> config) {
_uuid = (_uuid.length() > 0 ? _uuid : UUID::getUUID());
_config = boost::static_pointer_cast<PublisherConfig>(config);
_transport = "tcp";
(_socket = zmq_socket(ZeroMQNode::getZeroMQContext(), ZMQ_XPUB)) || LOG_WARN("zmq_socket: %s",zmq_strerror(errno));
(_closer = zmq_socket(ZeroMQNode::getZeroMQContext(), ZMQ_SUB)) || LOG_WARN("zmq_socket: %s",zmq_strerror(errno));
zmq_setsockopt(_closer, ZMQ_SUBSCRIBE, _uuid.c_str(), _uuid.size()) && LOG_WARN("zmq_setsockopt: %s",zmq_strerror(errno));
int hwm = NET_ZEROMQ_SND_HWM;
zmq_setsockopt(_socket, ZMQ_SNDHWM, &hwm, sizeof(hwm)) && LOG_WARN("zmq_setsockopt: %s",zmq_strerror(errno));
std::stringstream ssInProc;
ssInProc << "inproc://" << _uuid;
zmq_bind(_socket, ssInProc.str().c_str()) && LOG_WARN("zmq_bind: %s",zmq_strerror(errno));
uint16_t port = 4242;
std::stringstream ssNet;
ssNet << _transport << "://*:" << port;
while(zmq_bind(_socket, ssNet.str().c_str()) < 0) {
switch(errno) {
case EADDRINUSE:
port++;
ssNet.clear(); // clear error bits
ssNet.str(string()); // reset string
ssNet << _transport << "://*:" << port;
break;
default:
LOG_WARN("zmq_bind: %s",zmq_strerror(errno));
Thread::sleepMs(100);
}
}
_port = port;
start();
LOG_INFO("creating publisher for %s on %s", _channelName.c_str(), ssNet.str().c_str());
LOG_DEBUG("creating publisher on %s", ssInProc.str().c_str());
}
ZeroMQPublisher::ZeroMQPublisher() {
}
ZeroMQPublisher::~ZeroMQPublisher() {
LOG_INFO("deleting publisher for %s", _channelName.c_str());
stop();
join();
zmq_close(_socket) && LOG_WARN("zmq_close: %s",zmq_strerror(errno));
zmq_close(_closer) && LOG_WARN("zmq_close: %s",zmq_strerror(errno));
}
void ZeroMQPublisher::join() {
UMUNDO_LOCK(_mutex);
stop();
std::stringstream ssInProc;
ssInProc << "inproc://" << _uuid;
zmq_connect(_closer, ssInProc.str().c_str()) && LOG_WARN("zmq_connect: %s", zmq_strerror(errno));
Thread::join();
UMUNDO_UNLOCK(_mutex);
}
void ZeroMQPublisher::suspend() {
if (_isSuspended)
return;
_isSuspended = true;
stop();
join();
zmq_close(_socket) && LOG_WARN("zmq_close: %s",zmq_strerror(errno));
zmq_close(_closer) && LOG_WARN("zmq_close: %s",zmq_strerror(errno));
}
void ZeroMQPublisher::resume() {
if (!_isSuspended)
return;
_isSuspended = false;
init(_config);
}
void ZeroMQPublisher::run() {
// read subscription requests from the pub socket
while(isStarted()) {
zmq_msg_t message;
zmq_msg_init(&message) && LOG_WARN("zmq_msg_init: %s", zmq_strerror(errno));
int rv;
{
ScopeLock lock(&_mutex);
while ((rv = zmq_recvmsg(_socket, &message, ZMQ_DONTWAIT)) < 0) {
if (errno == EAGAIN) // no messages available at the moment
break;
if (errno != EINTR)
LOG_WARN("zmq_recvmsg: %s",zmq_strerror(errno));
}
}
// zmq_recvmsg is blocking and we use an ipc socket _closer to unblock in join() - not needed as we use ZMQ_DONTWAIT
//if (!isStarted()) {
// zmq_msg_close(&message) && LOG_WARN("zmq_msg_close: %s", zmq_strerror(errno));
// return;
//}
if (rv > 0) {
size_t msgSize = zmq_msg_size(&message);
// every subscriber will sent its uuid as a subscription as well
if (msgSize == 37) {
//ScopeLock lock(&_mutex);
char* data = (char*)zmq_msg_data(&message);
bool subscription = (data[0] == 0x1);
char* subId = data+1;
subId[msgSize - 1] = 0;
if (subscription) {
LOG_INFO("%s received ZMQ subscription from %s", _channelName.c_str(), subId);
_pendingZMQSubscriptions.insert(subId);
addedSubscriber("", subId);
} else {
LOG_INFO("%s received ZMQ unsubscription from %s", _channelName.c_str(), subId);
}
}
// zmq_msg_close(&message) && LOG_WARN("zmq_msg_close: %s", zmq_strerror(errno));
} else {
Thread::sleepMs(50);
}
}
}
/**
* Block until we have a given number of subscribers.
*/
int ZeroMQPublisher::waitForSubscribers(int count, int timeoutMs) {
while (_subscriptions.size() < (unsigned int)count) {
UMUNDO_WAIT(_pubLock);
#ifdef WIN32
// even after waiting for the signal from ZMQ subscriptions Windows needs a moment
//Thread::sleepMs(300);
#endif
}
return _subscriptions.size();
}
void ZeroMQPublisher::addedSubscriber(const string remoteId, const string subId) {
ScopeLock lock(&_mutex);
// ZeroMQPublisher::run calls us without a remoteId
if (remoteId.length() != 0) {
// we already know about this subscription
if (_pendingSubscriptions.find(subId) != _pendingSubscriptions.end())
return;
_pendingSubscriptions[subId] = remoteId;
}
// if we received a subscription from xpub and the node socket
if (_pendingSubscriptions.find(subId) == _pendingSubscriptions.end() ||
_pendingZMQSubscriptions.find(subId) == _pendingZMQSubscriptions.end()) {
return;
}
_subscriptions[subId] = _pendingSubscriptions[subId];
_pendingSubscriptions.erase(subId);
_pendingZMQSubscriptions.erase(subId);
if (_greeter != NULL)
_greeter->welcome((Publisher*)_facade, _pendingSubscriptions[subId], subId);
UMUNDO_SIGNAL(_pubLock);
}
void ZeroMQPublisher::removedSubscriber(const string remoteId, const string subId) {
ScopeLock lock(&_mutex);
assert(_subscriptions.find(subId) != _subscriptions.end());
_subscriptions.erase(subId);
if (_greeter != NULL)
_greeter->farewell((Publisher*)_facade, _pendingSubscriptions[subId], subId);
UMUNDO_SIGNAL(_pubLock);
}
void ZeroMQPublisher::send(Message* msg) {
//LOG_DEBUG("ZeroMQPublisher sending msg on %s", _channelName.c_str());
if (_isSuspended) {
LOG_WARN("Not sending message on suspended publisher");
return;
}
// topic name or explicit subscriber id is first message in envelope
zmq_msg_t channelEnvlp;
if (msg->getMeta().find("subscriber") != msg->getMeta().end()) {
// explicit destination
ZMQ_PREPARE_STRING(channelEnvlp, msg->getMeta("subscriber").c_str(), msg->getMeta("subscriber").size());
} else {
// everyone on channel
ZMQ_PREPARE_STRING(channelEnvlp, _channelName.c_str(), _channelName.size());
}
zmq_sendmsg(_socket, &channelEnvlp, ZMQ_SNDMORE) >= 0 || LOG_WARN("zmq_sendmsg: %s",zmq_strerror(errno));
zmq_msg_close(&channelEnvlp) && LOG_WARN("zmq_msg_close: %s",zmq_strerror(errno));
// mandatory meta fields
msg->putMeta("publisher", _uuid);
msg->putMeta("proc", procUUID);
// all our meta information
map<string, string>::const_iterator metaIter;
for (metaIter = msg->getMeta().begin(); metaIter != msg->getMeta().end(); metaIter++) {
// string key(metaIter->first);
// string value(metaIter->second);
// std::cout << key << ": " << value << std::endl;
// string length of key + value + two null bytes as string delimiters
size_t metaSize = (metaIter->first).length() + (metaIter->second).length() + 2;
zmq_msg_t metaMsg;
ZMQ_PREPARE(metaMsg, metaSize);
char* writePtr = (char*)zmq_msg_data(&metaMsg);
memcpy(writePtr, (metaIter->first).data(), (metaIter->first).length());
// indexes start at zero, so length is the byte after the string
((char*)zmq_msg_data(&metaMsg))[(metaIter->first).length()] = '\0';
assert(strlen((char*)zmq_msg_data(&metaMsg)) == (metaIter->first).length());
assert(strlen(writePtr) == (metaIter->first).length()); // just to be sure
// increment write pointer
writePtr += (metaIter->first).length() + 1;
memcpy(writePtr,
(metaIter->second).data(),
(metaIter->second).length());
// first string + null byte + second string
((char*)zmq_msg_data(&metaMsg))[(metaIter->first).length() + 1 + (metaIter->second).length()] = '\0';
assert(strlen(writePtr) == (metaIter->second).length());
zmq_sendmsg(_socket, &metaMsg, ZMQ_SNDMORE) >= 0 || LOG_WARN("zmq_sendmsg: %s",zmq_strerror(errno));
zmq_msg_close(&metaMsg) && LOG_WARN("zmq_msg_close: %s",zmq_strerror(errno));
}
// data as the second part of a multipart message
zmq_msg_t publication;
ZMQ_PREPARE_DATA(publication, msg->data(), msg->size());
zmq_sendmsg(_socket, &publication, 0) >= 0 || LOG_WARN("zmq_sendmsg: %s",zmq_strerror(errno));
zmq_msg_close(&publication) && LOG_WARN("zmq_msg_close: %s",zmq_strerror(errno));
}
}<commit_msg>Added todo<commit_after>/**
* @file
* @author 2012 Stefan Radomski (stefan.radomski@cs.tu-darmstadt.de)
* @copyright Simplified BSD
*
* @cond
* This program is free software: you can redistribute it and/or modify
* it under the terms of the FreeBSD license as published by the FreeBSD
* project.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*
* You should have received a copy of the FreeBSD license along with this
* program. If not, see <http://www.opensource.org/licenses/bsd-license>.
* @endcond
*/
#ifdef WIN32
#include <time.h>
#include <WinSock2.h>
#include <ws2tcpip.h>
#include <Windows.h>
#endif
#include "umundo/connection/zeromq/ZeroMQPublisher.h"
#include "umundo/connection/zeromq/ZeroMQNode.h"
#include "umundo/common/Message.h"
#include "umundo/common/UUID.h"
#include "umundo/config.h"
#if defined UNIX || defined IOS || defined IOSSIM
#include <string.h> // strlen, memcpy
#include <stdio.h> // snprintf
#endif
namespace umundo {
shared_ptr<Implementation> ZeroMQPublisher::create(void* facade) {
shared_ptr<Implementation> instance(new ZeroMQPublisher());
boost::static_pointer_cast<ZeroMQPublisher>(instance)->_facade = facade;
return instance;
}
void ZeroMQPublisher::destroy() {
delete(this);
}
void ZeroMQPublisher::init(shared_ptr<Configuration> config) {
_uuid = (_uuid.length() > 0 ? _uuid : UUID::getUUID());
_config = boost::static_pointer_cast<PublisherConfig>(config);
_transport = "tcp";
/// @todo: We might want all publishers to share only a few sockets
(_socket = zmq_socket(ZeroMQNode::getZeroMQContext(), ZMQ_XPUB)) || LOG_WARN("zmq_socket: %s",zmq_strerror(errno));
(_closer = zmq_socket(ZeroMQNode::getZeroMQContext(), ZMQ_SUB)) || LOG_WARN("zmq_socket: %s",zmq_strerror(errno));
zmq_setsockopt(_closer, ZMQ_SUBSCRIBE, _uuid.c_str(), _uuid.size()) && LOG_WARN("zmq_setsockopt: %s",zmq_strerror(errno));
int hwm = NET_ZEROMQ_SND_HWM;
zmq_setsockopt(_socket, ZMQ_SNDHWM, &hwm, sizeof(hwm)) && LOG_WARN("zmq_setsockopt: %s",zmq_strerror(errno));
std::stringstream ssInProc;
ssInProc << "inproc://" << _uuid;
zmq_bind(_socket, ssInProc.str().c_str()) && LOG_WARN("zmq_bind: %s",zmq_strerror(errno));
uint16_t port = 4242;
std::stringstream ssNet;
ssNet << _transport << "://*:" << port;
while(zmq_bind(_socket, ssNet.str().c_str()) < 0) {
switch(errno) {
case EADDRINUSE:
port++;
ssNet.clear(); // clear error bits
ssNet.str(string()); // reset string
ssNet << _transport << "://*:" << port;
break;
default:
LOG_WARN("zmq_bind: %s",zmq_strerror(errno));
Thread::sleepMs(100);
}
}
_port = port;
start();
LOG_INFO("creating publisher for %s on %s", _channelName.c_str(), ssNet.str().c_str());
LOG_DEBUG("creating publisher on %s", ssInProc.str().c_str());
}
ZeroMQPublisher::ZeroMQPublisher() {
}
ZeroMQPublisher::~ZeroMQPublisher() {
LOG_INFO("deleting publisher for %s", _channelName.c_str());
stop();
join();
zmq_close(_socket) && LOG_WARN("zmq_close: %s",zmq_strerror(errno));
zmq_close(_closer) && LOG_WARN("zmq_close: %s",zmq_strerror(errno));
}
void ZeroMQPublisher::join() {
UMUNDO_LOCK(_mutex);
stop();
std::stringstream ssInProc;
ssInProc << "inproc://" << _uuid;
zmq_connect(_closer, ssInProc.str().c_str()) && LOG_WARN("zmq_connect: %s", zmq_strerror(errno));
Thread::join();
UMUNDO_UNLOCK(_mutex);
}
void ZeroMQPublisher::suspend() {
if (_isSuspended)
return;
_isSuspended = true;
stop();
join();
zmq_close(_socket) && LOG_WARN("zmq_close: %s",zmq_strerror(errno));
zmq_close(_closer) && LOG_WARN("zmq_close: %s",zmq_strerror(errno));
}
void ZeroMQPublisher::resume() {
if (!_isSuspended)
return;
_isSuspended = false;
init(_config);
}
void ZeroMQPublisher::run() {
// read subscription requests from the pub socket
while(isStarted()) {
zmq_msg_t message;
zmq_msg_init(&message) && LOG_WARN("zmq_msg_init: %s", zmq_strerror(errno));
int rv;
{
ScopeLock lock(&_mutex);
while ((rv = zmq_recvmsg(_socket, &message, ZMQ_DONTWAIT)) < 0) {
if (errno == EAGAIN) // no messages available at the moment
break;
if (errno != EINTR)
LOG_WARN("zmq_recvmsg: %s",zmq_strerror(errno));
}
}
// zmq_recvmsg is blocking and we use an ipc socket _closer to unblock in join() - not needed as we use ZMQ_DONTWAIT
//if (!isStarted()) {
// zmq_msg_close(&message) && LOG_WARN("zmq_msg_close: %s", zmq_strerror(errno));
// return;
//}
if (rv > 0) {
size_t msgSize = zmq_msg_size(&message);
// every subscriber will sent its uuid as a subscription as well
if (msgSize == 37) {
//ScopeLock lock(&_mutex);
char* data = (char*)zmq_msg_data(&message);
bool subscription = (data[0] == 0x1);
char* subId = data+1;
subId[msgSize - 1] = 0;
if (subscription) {
LOG_INFO("%s received ZMQ subscription from %s", _channelName.c_str(), subId);
_pendingZMQSubscriptions.insert(subId);
addedSubscriber("", subId);
} else {
LOG_INFO("%s received ZMQ unsubscription from %s", _channelName.c_str(), subId);
}
}
// zmq_msg_close(&message) && LOG_WARN("zmq_msg_close: %s", zmq_strerror(errno));
} else {
Thread::sleepMs(50);
}
}
}
/**
* Block until we have a given number of subscribers.
*/
int ZeroMQPublisher::waitForSubscribers(int count, int timeoutMs) {
while (_subscriptions.size() < (unsigned int)count) {
UMUNDO_WAIT(_pubLock);
#ifdef WIN32
// even after waiting for the signal from ZMQ subscriptions Windows needs a moment
//Thread::sleepMs(300);
#endif
}
return _subscriptions.size();
}
void ZeroMQPublisher::addedSubscriber(const string remoteId, const string subId) {
ScopeLock lock(&_mutex);
// ZeroMQPublisher::run calls us without a remoteId
if (remoteId.length() != 0) {
// we already know about this subscription
if (_pendingSubscriptions.find(subId) != _pendingSubscriptions.end())
return;
_pendingSubscriptions[subId] = remoteId;
}
// if we received a subscription from xpub and the node socket
if (_pendingSubscriptions.find(subId) == _pendingSubscriptions.end() ||
_pendingZMQSubscriptions.find(subId) == _pendingZMQSubscriptions.end()) {
return;
}
_subscriptions[subId] = _pendingSubscriptions[subId];
_pendingSubscriptions.erase(subId);
_pendingZMQSubscriptions.erase(subId);
if (_greeter != NULL)
_greeter->welcome((Publisher*)_facade, _pendingSubscriptions[subId], subId);
UMUNDO_SIGNAL(_pubLock);
}
void ZeroMQPublisher::removedSubscriber(const string remoteId, const string subId) {
ScopeLock lock(&_mutex);
assert(_subscriptions.find(subId) != _subscriptions.end());
_subscriptions.erase(subId);
if (_greeter != NULL)
_greeter->farewell((Publisher*)_facade, _pendingSubscriptions[subId], subId);
UMUNDO_SIGNAL(_pubLock);
}
void ZeroMQPublisher::send(Message* msg) {
//LOG_DEBUG("ZeroMQPublisher sending msg on %s", _channelName.c_str());
if (_isSuspended) {
LOG_WARN("Not sending message on suspended publisher");
return;
}
// topic name or explicit subscriber id is first message in envelope
zmq_msg_t channelEnvlp;
if (msg->getMeta().find("subscriber") != msg->getMeta().end()) {
// explicit destination
ZMQ_PREPARE_STRING(channelEnvlp, msg->getMeta("subscriber").c_str(), msg->getMeta("subscriber").size());
} else {
// everyone on channel
ZMQ_PREPARE_STRING(channelEnvlp, _channelName.c_str(), _channelName.size());
}
zmq_sendmsg(_socket, &channelEnvlp, ZMQ_SNDMORE) >= 0 || LOG_WARN("zmq_sendmsg: %s",zmq_strerror(errno));
zmq_msg_close(&channelEnvlp) && LOG_WARN("zmq_msg_close: %s",zmq_strerror(errno));
// mandatory meta fields
msg->putMeta("publisher", _uuid);
msg->putMeta("proc", procUUID);
// all our meta information
map<string, string>::const_iterator metaIter;
for (metaIter = msg->getMeta().begin(); metaIter != msg->getMeta().end(); metaIter++) {
// string key(metaIter->first);
// string value(metaIter->second);
// std::cout << key << ": " << value << std::endl;
// string length of key + value + two null bytes as string delimiters
size_t metaSize = (metaIter->first).length() + (metaIter->second).length() + 2;
zmq_msg_t metaMsg;
ZMQ_PREPARE(metaMsg, metaSize);
char* writePtr = (char*)zmq_msg_data(&metaMsg);
memcpy(writePtr, (metaIter->first).data(), (metaIter->first).length());
// indexes start at zero, so length is the byte after the string
((char*)zmq_msg_data(&metaMsg))[(metaIter->first).length()] = '\0';
assert(strlen((char*)zmq_msg_data(&metaMsg)) == (metaIter->first).length());
assert(strlen(writePtr) == (metaIter->first).length()); // just to be sure
// increment write pointer
writePtr += (metaIter->first).length() + 1;
memcpy(writePtr,
(metaIter->second).data(),
(metaIter->second).length());
// first string + null byte + second string
((char*)zmq_msg_data(&metaMsg))[(metaIter->first).length() + 1 + (metaIter->second).length()] = '\0';
assert(strlen(writePtr) == (metaIter->second).length());
zmq_sendmsg(_socket, &metaMsg, ZMQ_SNDMORE) >= 0 || LOG_WARN("zmq_sendmsg: %s",zmq_strerror(errno));
zmq_msg_close(&metaMsg) && LOG_WARN("zmq_msg_close: %s",zmq_strerror(errno));
}
// data as the second part of a multipart message
zmq_msg_t publication;
ZMQ_PREPARE_DATA(publication, msg->data(), msg->size());
zmq_sendmsg(_socket, &publication, 0) >= 0 || LOG_WARN("zmq_sendmsg: %s",zmq_strerror(errno));
zmq_msg_close(&publication) && LOG_WARN("zmq_msg_close: %s",zmq_strerror(errno));
}
}<|endoftext|> |
<commit_before>// Copyright 2011-2013 Johann Duscher (a.k.a. Jonny Dee). 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 JOHANN DUSCHER ''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 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.
//
// 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 Johann Duscher.
#include "pubsub/PubSubClient.h"
#include "pubsub/PubSubServer.h"
#include <QCoreApplication>
#include <QString>
#include <QtTest>
namespace nzmqt
{
class NzmqtTest : public QObject
{
Q_OBJECT
public:
NzmqtTest();
protected:
QThread* makeExecutionThread(samples::SampleBase& sample) const;
private slots:
void testPubSub();
};
NzmqtTest::NzmqtTest()
{
qRegisterMetaType< QList<QByteArray> >();
}
QThread* NzmqtTest::makeExecutionThread(samples::SampleBase& sample) const
{
QThread* thread = new QThread;
sample.moveToThread(thread);
bool connected = false;
connected = connect(thread, SIGNAL(started()), &sample, SLOT(start())); Q_ASSERT(connected);
connected = connect(&sample, SIGNAL(finished()), thread, SLOT(quit())); Q_ASSERT(connected);
connected = connect(&sample, SIGNAL(finished()), &sample, SLOT(deleteLater())); Q_ASSERT(connected);
connected = connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater())); Q_ASSERT(connected);
return thread;
}
void NzmqtTest::testPubSub()
{
try {
QScopedPointer<ZMQContext> context(nzmqt::createDefaultContext());
// Create publisher.
samples::PubSubServer* publisher = new samples::PubSubServer(*context, "inproc://pubsub", "ping");
QSignalSpy spyPublisherPingSent(publisher, SIGNAL(pingSent(const QList<QByteArray>&)));
QSignalSpy spyPublisherFailure(publisher, SIGNAL(failure(const QString&)));
QSignalSpy spyPublisherFinished(publisher, SIGNAL(finished()));
// Create publisher execution thread.
QThread* publisherThread = makeExecutionThread(*publisher);
QSignalSpy spyPublisherThreadFinished(publisherThread, SIGNAL(finished()));
// Create subscriber.
samples::PubSubClient* subscriber = new samples::PubSubClient(*context, "inproc://pubsub", "ping");
QSignalSpy spySubscriberPingReceived(subscriber, SIGNAL(pingReceived(const QList<QByteArray>&)));
QSignalSpy spySubscriberFailure(subscriber, SIGNAL(failure(const QString&)));
QSignalSpy spySubscriberFinished(subscriber, SIGNAL(finished()));
// Create subscriber execution thread.
QThread* subscriberThread = makeExecutionThread(*subscriber);
QSignalSpy spySubscriberThreadFinished(subscriberThread, SIGNAL(finished()));
//
// START TEST
//
context->start();
publisherThread->start();
QTest::qWait(500);
subscriberThread->start();
QTimer::singleShot(6000, publisher, SLOT(stop()));
QTimer::singleShot(6000, subscriber, SLOT(stop()));
QTest::qWait(8000);
//
// CHECK POSTCONDITIONS
//
qDebug() << "Publisher pings sent:" << spyPublisherPingSent.size();
qDebug() << "Subscriber pings received:" << spySubscriberPingReceived.size();
QCOMPARE(spyPublisherFailure.size(), 0);
QCOMPARE(spySubscriberFailure.size(), 0);
QVERIFY2(spyPublisherPingSent.size() > 3, "Server didn't send any/enough pings.");
QVERIFY2(spySubscriberPingReceived.size() > 3, "Client didn't receive any/enough pings.");
QVERIFY2(qAbs(spyPublisherPingSent.size() - spySubscriberPingReceived.size()) < 3, "Publisher and subscriber communication flawed.");
QCOMPARE(spyPublisherFinished.size(), 1);
QCOMPARE(spySubscriberFinished.size(), 1);
QCOMPARE(spyPublisherThreadFinished.size(), 1);
QCOMPARE(spySubscriberThreadFinished.size(), 1);
}
catch (std::exception& ex)
{
QFAIL(ex.what());
}
}
}
QTEST_MAIN(nzmqt::NzmqtTest)
#include "nzmqt_test.moc"
<commit_msg>testing,reqrep: Add unit test for REQ-REP protocol.<commit_after>// Copyright 2011-2013 Johann Duscher (a.k.a. Jonny Dee). 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 JOHANN DUSCHER ''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 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.
//
// 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 Johann Duscher.
#include "pubsub/PubSubClient.h"
#include "pubsub/PubSubServer.h"
#include "reqrep/ReqRepClient.h"
#include "reqrep/ReqRepServer.h"
#include <QCoreApplication>
#include <QString>
#include <QtTest>
namespace nzmqt
{
class NzmqtTest : public QObject
{
Q_OBJECT
public:
NzmqtTest();
protected:
QThread* makeExecutionThread(samples::SampleBase& sample) const;
private slots:
void testPubSub();
void testReqRep();
};
NzmqtTest::NzmqtTest()
{
qRegisterMetaType< QList<QByteArray> >();
}
QThread* NzmqtTest::makeExecutionThread(samples::SampleBase& sample) const
{
QThread* thread = new QThread;
sample.moveToThread(thread);
bool connected = false;
connected = connect(thread, SIGNAL(started()), &sample, SLOT(start())); Q_ASSERT(connected);
connected = connect(&sample, SIGNAL(finished()), thread, SLOT(quit())); Q_ASSERT(connected);
connected = connect(&sample, SIGNAL(finished()), &sample, SLOT(deleteLater())); Q_ASSERT(connected);
connected = connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater())); Q_ASSERT(connected);
return thread;
}
void NzmqtTest::testPubSub()
{
try {
QScopedPointer<ZMQContext> context(nzmqt::createDefaultContext());
// Create publisher.
samples::PubSubServer* publisher = new samples::PubSubServer(*context, "inproc://pubsub", "ping");
QSignalSpy spyPublisherPingSent(publisher, SIGNAL(pingSent(const QList<QByteArray>&)));
QSignalSpy spyPublisherFailure(publisher, SIGNAL(failure(const QString&)));
QSignalSpy spyPublisherFinished(publisher, SIGNAL(finished()));
// Create publisher execution thread.
QThread* publisherThread = makeExecutionThread(*publisher);
QSignalSpy spyPublisherThreadFinished(publisherThread, SIGNAL(finished()));
// Create subscriber.
samples::PubSubClient* subscriber = new samples::PubSubClient(*context, "inproc://pubsub", "ping");
QSignalSpy spySubscriberPingReceived(subscriber, SIGNAL(pingReceived(const QList<QByteArray>&)));
QSignalSpy spySubscriberFailure(subscriber, SIGNAL(failure(const QString&)));
QSignalSpy spySubscriberFinished(subscriber, SIGNAL(finished()));
// Create subscriber execution thread.
QThread* subscriberThread = makeExecutionThread(*subscriber);
QSignalSpy spySubscriberThreadFinished(subscriberThread, SIGNAL(finished()));
//
// START TEST
//
context->start();
publisherThread->start();
QTest::qWait(500);
subscriberThread->start();
QTimer::singleShot(6000, publisher, SLOT(stop()));
QTimer::singleShot(6000, subscriber, SLOT(stop()));
QTest::qWait(8000);
//
// CHECK POSTCONDITIONS
//
qDebug() << "Publisher pings sent:" << spyPublisherPingSent.size();
qDebug() << "Subscriber pings received:" << spySubscriberPingReceived.size();
QCOMPARE(spyPublisherFailure.size(), 0);
QCOMPARE(spySubscriberFailure.size(), 0);
QVERIFY2(spyPublisherPingSent.size() > 3, "Server didn't send any/enough pings.");
QVERIFY2(spySubscriberPingReceived.size() > 3, "Client didn't receive any/enough pings.");
QVERIFY2(qAbs(spyPublisherPingSent.size() - spySubscriberPingReceived.size()) < 3, "Publisher and subscriber communication flawed.");
QCOMPARE(spyPublisherFinished.size(), 1);
QCOMPARE(spySubscriberFinished.size(), 1);
QCOMPARE(spyPublisherThreadFinished.size(), 1);
QCOMPARE(spySubscriberThreadFinished.size(), 1);
}
catch (std::exception& ex)
{
QFAIL(ex.what());
}
}
void NzmqtTest::testReqRep()
{
try {
QScopedPointer<ZMQContext> context(nzmqt::createDefaultContext());
// Create server.
samples::ReqRepServer* server = new samples::ReqRepServer(*context, "inproc://reqrep", "world");
QSignalSpy spyServerRequestReceived(server, SIGNAL(requestReceived(const QList<QByteArray>&)));
QSignalSpy spyServerFailure(server, SIGNAL(failure(const QString&)));
QSignalSpy spyServerFinished(server, SIGNAL(finished()));
// Create server execution thread.
QThread* serverThread = makeExecutionThread(*server);
QSignalSpy spyServerThreadFinished(serverThread, SIGNAL(finished()));
// Create client.
samples::ReqRepClient* client = new samples::ReqRepClient(*context, "inproc://reqrep", "hello");
QSignalSpy spyClientRequestSent(client, SIGNAL(requestSent(const QList<QByteArray>&)));
QSignalSpy spyClientFailure(client, SIGNAL(failure(const QString&)));
QSignalSpy spyClientFinished(client, SIGNAL(finished()));
// Create client execution thread.
QThread* clientThread = makeExecutionThread(*client);
QSignalSpy spyClientThreadFinished(clientThread, SIGNAL(finished()));
//
// START TEST
//
context->start();
serverThread->start();
QTest::qWait(500);
clientThread->start();
QTimer::singleShot(6000, server, SLOT(stop()));
QTimer::singleShot(6000, client, SLOT(stop()));
QTest::qWait(8000);
//
// CHECK POSTCONDITIONS
//
qDebug() << "Client requests sent:" << spyClientRequestSent.size();
qDebug() << "Server requests received:" << spyServerRequestReceived.size();
QCOMPARE(spyServerFailure.size(), 0);
QCOMPARE(spyClientFailure.size(), 0);
QVERIFY2(spyServerRequestReceived.size() > 3, "Server didn't send any/enough pings.");
QVERIFY2(spyClientRequestSent.size() > 3, "Client didn't receive any/enough pings.");
QCOMPARE(spyServerRequestReceived.size(), spyClientRequestSent.size());
QCOMPARE(spyServerFinished.size(), 1);
QCOMPARE(spyClientFinished.size(), 1);
QCOMPARE(spyServerThreadFinished.size(), 1);
QCOMPARE(spyClientThreadFinished.size(), 1);
}
catch (std::exception& ex)
{
QFAIL(ex.what());
}
}
}
QTEST_MAIN(nzmqt::NzmqtTest)
#include "nzmqt_test.moc"
<|endoftext|> |
<commit_before>// Copyright 2019 The TCMalloc Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://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.
//
// Check memalign related routines.
//
// We can't really do a huge amount of checking, but at the very
// least, the following code checks that return values are properly
// aligned, and that writing into the objects works.
#define _XOPEN_SOURCE 600 // to get posix_memalign
#include <assert.h>
#include <errno.h>
#include <malloc.h>
#include <stddef.h>
#include <stdint.h>
#include <stdlib.h>
#include <unistd.h>
#include <iostream>
#include <memory>
#include <vector>
#include "gtest/gtest.h"
#include "absl/random/random.h"
#include "benchmark/benchmark.h"
#include "tcmalloc/testing/testutil.h"
namespace tcmalloc {
namespace {
// Return the next interesting size/delta to check. Returns -1 if no more.
int NextSize(int size) {
if (size < 100) {
return size + 1;
} else if (size < 1048576) {
// Find next power of two
int power = 1;
while (power < size) {
power <<= 1;
}
// Yield (power-1, power, power+1)
if (size < power - 1) {
return power - 1;
} else if (size == power - 1) {
return power;
} else {
assert(size == power);
return power + 1;
}
} else {
return -1;
}
}
// Check alignment
void CheckAlignment(void* p, int align) {
ASSERT_EQ(0, reinterpret_cast<uintptr_t>(p) % align)
<< "wrong alignment; wanted 0x" << std::hex << align << "; got " << p;
}
// Fill a buffer of the specified size with a predetermined pattern
void Fill(void* p, int n, char seed) {
unsigned char* buffer = reinterpret_cast<unsigned char*>(p);
for (int i = 0; i < n; i++) {
buffer[i] = ((seed + i) & 0xff);
}
}
// Check that the specified buffer has the predetermined pattern
// generated by Fill()
bool Valid(const void* p, int n, char seed) {
const unsigned char* buffer = reinterpret_cast<const unsigned char*>(p);
for (int i = 0; i < n; i++) {
if (buffer[i] != ((seed + i) & 0xff)) {
return false;
}
}
return true;
}
// Check that we do not fail catastrophically when we allocate a pointer with
// aligned_alloc and then realloc it. Note: realloc is not expected to
// preserve alignment.
TEST(MemalignTest, AlignedAllocRealloc) {
absl::BitGen rand;
struct alloc {
void* ptr;
size_t size;
size_t alignment;
};
std::vector<alloc> allocated;
for (int i = 0; i < 100; ++i) {
alloc a;
a.size = absl::LogUniform(rand, 0, 1 << 20);
a.alignment = 1 << absl::Uniform(rand, 0, 6);
a.size = (a.size + a.alignment - 1) & ~(a.alignment - 1);
a.ptr = aligned_alloc(a.alignment, a.size);
ASSERT_TRUE(a.ptr != nullptr);
ASSERT_EQ(0, reinterpret_cast<uintptr_t>(a.ptr) %
static_cast<size_t>(a.alignment));
allocated.emplace_back(a);
}
for (int i = 0; i < 100; ++i) {
size_t new_size = absl::LogUniform(rand, 0, 1 << 20);
void* new_ptr = realloc(allocated[i].ptr, new_size);
ASSERT_TRUE(new_size == 0 || new_ptr != nullptr)
<< allocated[i].size << " " << new_size;
allocated[i].ptr = new_ptr;
}
for (int i = 0; i < 100; ++i) {
free(allocated[i].ptr);
}
}
// Produces a vector of sizes to allocate, all with the specified alignment.
std::vector<size_t> SizesWithAlignment(size_t align) {
std::vector<size_t> v;
for (size_t s = 0; s < 100; s += align) {
v.push_back(s + align);
}
for (size_t s = 128; s < 1048576; s *= 2) {
if (s <= align) {
continue;
}
v.push_back(s - align);
v.push_back(s);
v.push_back(s + align);
}
return v;
}
TEST(MemalignTest, AlignedAlloc) {
// Try allocating data with a bunch of alignments and sizes
for (int a = 1; a < 1048576; a *= 2) {
for (auto s : SizesWithAlignment(a)) {
void* ptr = aligned_alloc(a, s);
CheckAlignment(ptr, a);
Fill(ptr, s, 'x');
ASSERT_TRUE(Valid(ptr, s, 'x'));
free(ptr);
}
}
// Grab some memory so that the big allocation below will definitely fail.
// This allocates 4MB of RAM, therefore the request below for 2^64-4KB*i will
// fail as it cannot possibly be represented in our address space, since
// 4MB + (2^64-4KB*i) > 2^64 for i = {1...kMinusNTimes}
void* p_small = malloc(4 * 1048576);
ASSERT_NE(nullptr, p_small);
// Make sure overflow is returned as nullptr.
const size_t zero = 0;
static const size_t kMinusNTimes = 10;
for (size_t i = 1; i < kMinusNTimes; ++i) {
EXPECT_EQ(nullptr, aligned_alloc(1024, zero - 1024 * i));
}
free(p_small);
}
#ifndef NDEBUG
TEST(MemalignTest, AlignedAllocDeathTest) {
EXPECT_DEATH(benchmark::DoNotOptimize(aligned_alloc(0, 1)), "");
EXPECT_DEATH(benchmark::DoNotOptimize(aligned_alloc(sizeof(void*) + 1, 1)),
"");
EXPECT_DEATH(benchmark::DoNotOptimize(aligned_alloc(4097, 1)), "");
}
#endif
TEST(MemalignTest, Memalign) {
// Try allocating data with a bunch of alignments and sizes
for (int a = 1; a < 1048576; a *= 2) {
for (auto s : SizesWithAlignment(a)) {
void* ptr = memalign(a, s);
CheckAlignment(ptr, a);
Fill(ptr, s, 'x');
ASSERT_TRUE(Valid(ptr, s, 'x'));
free(ptr);
}
}
{
// Check various corner cases
void* p1 = memalign(1 << 20, 1 << 19);
void* p2 = memalign(1 << 19, 1 << 19);
void* p3 = memalign(1 << 21, 1 << 19);
CheckAlignment(p1, 1 << 20);
CheckAlignment(p2, 1 << 19);
CheckAlignment(p3, 1 << 21);
Fill(p1, 1 << 19, 'a');
Fill(p2, 1 << 19, 'b');
Fill(p3, 1 << 19, 'c');
ASSERT_TRUE(Valid(p1, 1 << 19, 'a'));
ASSERT_TRUE(Valid(p2, 1 << 19, 'b'));
ASSERT_TRUE(Valid(p3, 1 << 19, 'c'));
free(p1);
free(p2);
free(p3);
}
}
TEST(MemalignTest, PosixMemalign) {
// Try allocating data with a bunch of alignments and sizes
for (int a = sizeof(void*); a < 1048576; a *= 2) {
for (auto s : SizesWithAlignment(a)) {
void* ptr;
ASSERT_EQ(0, posix_memalign(&ptr, a, s));
CheckAlignment(ptr, a);
Fill(ptr, s, 'x');
ASSERT_TRUE(Valid(ptr, s, 'x'));
free(ptr);
}
}
}
TEST(MemalignTest, PosixMemalignFailure) {
void* ptr;
ASSERT_EQ(posix_memalign(&ptr, 0, 1), EINVAL);
ASSERT_EQ(posix_memalign(&ptr, sizeof(void*) / 2, 1), EINVAL);
ASSERT_EQ(posix_memalign(&ptr, sizeof(void*) + 1, 1), EINVAL);
ASSERT_EQ(posix_memalign(&ptr, 4097, 1), EINVAL);
// Grab some memory so that the big allocation below will definitely fail.
void* p_small = malloc(4 * 1048576);
ASSERT_NE(p_small, nullptr);
// Make sure overflow is returned as ENOMEM
const size_t zero = 0;
static const size_t kMinusNTimes = 10;
for (size_t i = 1; i < kMinusNTimes; ++i) {
int r = posix_memalign(&ptr, 1024, zero - i);
ASSERT_EQ(r, ENOMEM);
}
free(p_small);
}
TEST(MemalignTest, valloc) {
const int pagesize = getpagesize();
for (int s = 0; s != -1; s = NextSize(s)) {
void* p = valloc(s);
CheckAlignment(p, pagesize);
Fill(p, s, 'v');
ASSERT_TRUE(Valid(p, s, 'v'));
free(p);
}
}
TEST(MemalignTest, pvalloc) {
const int pagesize = getpagesize();
for (int s = 0; s != -1; s = NextSize(s)) {
void* p = pvalloc(s);
CheckAlignment(p, pagesize);
int alloc_needed = ((s + pagesize - 1) / pagesize) * pagesize;
Fill(p, alloc_needed, 'x');
ASSERT_TRUE(Valid(p, alloc_needed, 'x'));
free(p);
}
// should be safe to write upto a page in pvalloc(0) region
void* p = pvalloc(0);
Fill(p, pagesize, 'y');
ASSERT_TRUE(Valid(p, pagesize, 'y'));
free(p);
}
} // namespace
} // namespace tcmalloc
<commit_msg>testing: guard `pvalloc` related tests with libc checks<commit_after>// Copyright 2019 The TCMalloc Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://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.
//
// Check memalign related routines.
//
// We can't really do a huge amount of checking, but at the very
// least, the following code checks that return values are properly
// aligned, and that writing into the objects works.
#define _XOPEN_SOURCE 600 // to get posix_memalign
#include <assert.h>
#include <errno.h>
#include <malloc.h>
#include <stddef.h>
#include <stdint.h>
#include <stdlib.h>
#include <unistd.h>
#include <iostream>
#include <memory>
#include <vector>
#include "gtest/gtest.h"
#include "absl/random/random.h"
#include "benchmark/benchmark.h"
#include "tcmalloc/testing/testutil.h"
namespace tcmalloc {
namespace {
// Return the next interesting size/delta to check. Returns -1 if no more.
int NextSize(int size) {
if (size < 100) {
return size + 1;
} else if (size < 1048576) {
// Find next power of two
int power = 1;
while (power < size) {
power <<= 1;
}
// Yield (power-1, power, power+1)
if (size < power - 1) {
return power - 1;
} else if (size == power - 1) {
return power;
} else {
assert(size == power);
return power + 1;
}
} else {
return -1;
}
}
// Check alignment
void CheckAlignment(void* p, int align) {
ASSERT_EQ(0, reinterpret_cast<uintptr_t>(p) % align)
<< "wrong alignment; wanted 0x" << std::hex << align << "; got " << p;
}
// Fill a buffer of the specified size with a predetermined pattern
void Fill(void* p, int n, char seed) {
unsigned char* buffer = reinterpret_cast<unsigned char*>(p);
for (int i = 0; i < n; i++) {
buffer[i] = ((seed + i) & 0xff);
}
}
// Check that the specified buffer has the predetermined pattern
// generated by Fill()
bool Valid(const void* p, int n, char seed) {
const unsigned char* buffer = reinterpret_cast<const unsigned char*>(p);
for (int i = 0; i < n; i++) {
if (buffer[i] != ((seed + i) & 0xff)) {
return false;
}
}
return true;
}
// Check that we do not fail catastrophically when we allocate a pointer with
// aligned_alloc and then realloc it. Note: realloc is not expected to
// preserve alignment.
TEST(MemalignTest, AlignedAllocRealloc) {
absl::BitGen rand;
struct alloc {
void* ptr;
size_t size;
size_t alignment;
};
std::vector<alloc> allocated;
for (int i = 0; i < 100; ++i) {
alloc a;
a.size = absl::LogUniform(rand, 0, 1 << 20);
a.alignment = 1 << absl::Uniform(rand, 0, 6);
a.size = (a.size + a.alignment - 1) & ~(a.alignment - 1);
a.ptr = aligned_alloc(a.alignment, a.size);
ASSERT_TRUE(a.ptr != nullptr);
ASSERT_EQ(0, reinterpret_cast<uintptr_t>(a.ptr) %
static_cast<size_t>(a.alignment));
allocated.emplace_back(a);
}
for (int i = 0; i < 100; ++i) {
size_t new_size = absl::LogUniform(rand, 0, 1 << 20);
void* new_ptr = realloc(allocated[i].ptr, new_size);
ASSERT_TRUE(new_size == 0 || new_ptr != nullptr)
<< allocated[i].size << " " << new_size;
allocated[i].ptr = new_ptr;
}
for (int i = 0; i < 100; ++i) {
free(allocated[i].ptr);
}
}
// Produces a vector of sizes to allocate, all with the specified alignment.
std::vector<size_t> SizesWithAlignment(size_t align) {
std::vector<size_t> v;
for (size_t s = 0; s < 100; s += align) {
v.push_back(s + align);
}
for (size_t s = 128; s < 1048576; s *= 2) {
if (s <= align) {
continue;
}
v.push_back(s - align);
v.push_back(s);
v.push_back(s + align);
}
return v;
}
TEST(MemalignTest, AlignedAlloc) {
// Try allocating data with a bunch of alignments and sizes
for (int a = 1; a < 1048576; a *= 2) {
for (auto s : SizesWithAlignment(a)) {
void* ptr = aligned_alloc(a, s);
CheckAlignment(ptr, a);
Fill(ptr, s, 'x');
ASSERT_TRUE(Valid(ptr, s, 'x'));
free(ptr);
}
}
// Grab some memory so that the big allocation below will definitely fail.
// This allocates 4MB of RAM, therefore the request below for 2^64-4KB*i will
// fail as it cannot possibly be represented in our address space, since
// 4MB + (2^64-4KB*i) > 2^64 for i = {1...kMinusNTimes}
void* p_small = malloc(4 * 1048576);
ASSERT_NE(nullptr, p_small);
// Make sure overflow is returned as nullptr.
const size_t zero = 0;
static const size_t kMinusNTimes = 10;
for (size_t i = 1; i < kMinusNTimes; ++i) {
EXPECT_EQ(nullptr, aligned_alloc(1024, zero - 1024 * i));
}
free(p_small);
}
#ifndef NDEBUG
TEST(MemalignTest, AlignedAllocDeathTest) {
EXPECT_DEATH(benchmark::DoNotOptimize(aligned_alloc(0, 1)), "");
EXPECT_DEATH(benchmark::DoNotOptimize(aligned_alloc(sizeof(void*) + 1, 1)),
"");
EXPECT_DEATH(benchmark::DoNotOptimize(aligned_alloc(4097, 1)), "");
}
#endif
TEST(MemalignTest, Memalign) {
// Try allocating data with a bunch of alignments and sizes
for (int a = 1; a < 1048576; a *= 2) {
for (auto s : SizesWithAlignment(a)) {
void* ptr = memalign(a, s);
CheckAlignment(ptr, a);
Fill(ptr, s, 'x');
ASSERT_TRUE(Valid(ptr, s, 'x'));
free(ptr);
}
}
{
// Check various corner cases
void* p1 = memalign(1 << 20, 1 << 19);
void* p2 = memalign(1 << 19, 1 << 19);
void* p3 = memalign(1 << 21, 1 << 19);
CheckAlignment(p1, 1 << 20);
CheckAlignment(p2, 1 << 19);
CheckAlignment(p3, 1 << 21);
Fill(p1, 1 << 19, 'a');
Fill(p2, 1 << 19, 'b');
Fill(p3, 1 << 19, 'c');
ASSERT_TRUE(Valid(p1, 1 << 19, 'a'));
ASSERT_TRUE(Valid(p2, 1 << 19, 'b'));
ASSERT_TRUE(Valid(p3, 1 << 19, 'c'));
free(p1);
free(p2);
free(p3);
}
}
TEST(MemalignTest, PosixMemalign) {
// Try allocating data with a bunch of alignments and sizes
for (int a = sizeof(void*); a < 1048576; a *= 2) {
for (auto s : SizesWithAlignment(a)) {
void* ptr;
ASSERT_EQ(0, posix_memalign(&ptr, a, s));
CheckAlignment(ptr, a);
Fill(ptr, s, 'x');
ASSERT_TRUE(Valid(ptr, s, 'x'));
free(ptr);
}
}
}
TEST(MemalignTest, PosixMemalignFailure) {
void* ptr;
ASSERT_EQ(posix_memalign(&ptr, 0, 1), EINVAL);
ASSERT_EQ(posix_memalign(&ptr, sizeof(void*) / 2, 1), EINVAL);
ASSERT_EQ(posix_memalign(&ptr, sizeof(void*) + 1, 1), EINVAL);
ASSERT_EQ(posix_memalign(&ptr, 4097, 1), EINVAL);
// Grab some memory so that the big allocation below will definitely fail.
void* p_small = malloc(4 * 1048576);
ASSERT_NE(p_small, nullptr);
// Make sure overflow is returned as ENOMEM
const size_t zero = 0;
static const size_t kMinusNTimes = 10;
for (size_t i = 1; i < kMinusNTimes; ++i) {
int r = posix_memalign(&ptr, 1024, zero - i);
ASSERT_EQ(r, ENOMEM);
}
free(p_small);
}
TEST(MemalignTest, valloc) {
const int pagesize = getpagesize();
for (int s = 0; s != -1; s = NextSize(s)) {
void* p = valloc(s);
CheckAlignment(p, pagesize);
Fill(p, s, 'v');
ASSERT_TRUE(Valid(p, s, 'v'));
free(p);
}
}
#if defined(__BIONIC__) || defined(__GLIBC__) || defined(__NEWLIB__)
TEST(MemalignTest, pvalloc) {
const int pagesize = getpagesize();
for (int s = 0; s != -1; s = NextSize(s)) {
void* p = pvalloc(s);
CheckAlignment(p, pagesize);
int alloc_needed = ((s + pagesize - 1) / pagesize) * pagesize;
Fill(p, alloc_needed, 'x');
ASSERT_TRUE(Valid(p, alloc_needed, 'x'));
free(p);
}
// should be safe to write upto a page in pvalloc(0) region
void* p = pvalloc(0);
Fill(p, pagesize, 'y');
ASSERT_TRUE(Valid(p, pagesize, 'y'));
free(p);
}
#endif
} // namespace
} // namespace tcmalloc
<|endoftext|> |
<commit_before>///
/// \file AliFemtoDummyPairCut.cxx
///
#include "AliFemtoDummyPairCut.h"
#include <string>
#include <cstdio>
#ifdef __ROOT__
/// \cond CLASSIMP
ClassImp(AliFemtoDummyPairCut);
/// \endcond
#endif
//__________________
AliFemtoDummyPairCut::AliFemtoDummyPairCut() :
fNPairsPassed(0),
fNPairsFailed(0)
{
/* no-op */
}
//__________________
AliFemtoDummyPairCut::~AliFemtoDummyPairCut()
{
/* no-op */
}
//__________________
bool AliFemtoDummyPairCut::Pass(const AliFemtoPair* /* pair */)
{
// Pass all pairs
bool temp = true;
temp ? fNPairsPassed++ : fNPairsFailed++;
return true;
}
//__________________
AliFemtoString AliFemtoDummyPairCut::Report()
{
// prepare a report from the execution
string stemp = "AliFemtoDummy Pair Cut - total dummy-- always returns true\n";
char ctemp[100];
snprintf(ctemp , 100, "Number of pairs which passed:\t%ld Number which failed:\t%ld\n",fNPairsPassed,fNPairsFailed);
stemp += ctemp;
AliFemtoString returnThis = stemp;
return returnThis;
}
//__________________
TList *AliFemtoDummyPairCut::ListSettings()
{
// return a list of settings in a writable form
TList *tListSetttings = new TList();
return tListSetttings;
}
<commit_msg>AliFemtoDummyPairCut - Simplify Report method<commit_after>///
/// \file AliFemtoDummyPairCut.cxx
///
#include "AliFemtoDummyPairCut.h"
#include <string>
#include <cstdio>
#ifdef __ROOT__
/// \cond CLASSIMP
ClassImp(AliFemtoDummyPairCut);
/// \endcond
#endif
//__________________
AliFemtoDummyPairCut::AliFemtoDummyPairCut() :
fNPairsPassed(0),
fNPairsFailed(0)
{
/* no-op */
}
//__________________
AliFemtoDummyPairCut::~AliFemtoDummyPairCut()
{
/* no-op */
}
//__________________
bool AliFemtoDummyPairCut::Pass(const AliFemtoPair* /* pair */)
{
// Pass all pairs
bool temp = true;
temp ? fNPairsPassed++ : fNPairsFailed++;
return true;
}
//__________________
AliFemtoString AliFemtoDummyPairCut::Report()
{
// prepare a report from the execution
AliFemtoString report = "AliFemtoDummy Pair Cut - total dummy-- always returns true\n";
report += Form("Number of pairs which passed:\t%ld Number which failed:\t%ld\n",fNPairsPassed,fNPairsFailed);
return report;
}
//__________________
TList *AliFemtoDummyPairCut::ListSettings()
{
// return a list of settings in a writable form
TList *tListSetttings = new TList();
return tListSetttings;
}
<|endoftext|> |
<commit_before>/**
* @file AddTaskTriggerCorrection.C
* @author Valentina Zaccolo
* @date Mon Feb 3 13:56:26 2014
*
* @brief Script to add a task to create trigger bias correction
*
*
*/
AliAnalysisTask*
AddTaskTriggerCorrection(const char* trig="INEL",
Double_t vzMin=-4,
Double_t vzMax=4)
{
// Make our object. 2nd argumenent is absolute max Eta 3rd argument
// is absolute max Vz
AliForwardTriggerBiasCorrection* task =
new AliForwardTriggerBiasCorrection("TriggerCorrection");
task->SetIpZRange(vzMin, vzMax);
task->SetTriggerMask(trig);
task->DefaultBins();
task->Connect();
return task;
}
//________________________________________________________________________
//
// EOF
//
<commit_msg>Return AliAnalysisTaskSE<commit_after>/**
* @file AddTaskTriggerCorrection.C
* @author Valentina Zaccolo
* @date Mon Feb 3 13:56:26 2014
*
* @brief Script to add a task to create trigger bias correction
*
*
*/
AliAnalysisTaskSE*
AddTaskTriggerCorrection(const char* trig="INEL",
Double_t vzMin=-4,
Double_t vzMax=4)
{
// Make our object. 2nd argumenent is absolute max Eta 3rd argument
// is absolute max Vz
AliForwardTriggerBiasCorrection* task =
new AliForwardTriggerBiasCorrection("TriggerCorrection");
task->SetIpZRange(vzMin, vzMax);
task->SetTriggerMask(trig);
task->DefaultBins();
task->Connect();
return task;
}
//________________________________________________________________________
//
// EOF
//
<|endoftext|> |
<commit_before>/***************************************************************************
adash@cern.ch - last modified on 05/09/2016
// *** Configuration script for KStar-Meson analysis with 2016 PbPb runs ***
//
// A configuration script for RSN package needs to define the followings:
//
// (1) decay tree of each resonance to be studied, which is needed to select
// true pairs and to assign the right mass to all candidate daughters
// (2) cuts at all levels: single daughters, tracks, events
// (3) output objects: histograms or trees
****************************************************************************/
Bool_t ConfigKStarpPbRunII(AliRsnMiniAnalysisTask *task,
Bool_t isMC,
Bool_t isPP,
AliRsnCutSet *cutsPair,
Int_t Strcut = 2011,
Int_t customQualityCutsID = AliRsnCutSetDaughterParticle::kDisableCustom,
AliRsnCutSetDaughterParticle::ERsnDaughterCutSet cutKaCandidate=AliRsnCutSetDaughterParticle::kTPCTOFpidphikstarpPb2016,
Float_t nsigmaPi = 2.0,
Float_t nsigmaK = 2.0,
Float_t nsigmaTOF= 3.0,
Bool_t enableMonitor = kTRUE
)
{
// retrieve mass from PDG database
Int_t pdg = 313;
TDatabasePDG *db = TDatabasePDG::Instance();
TParticlePDG *part = db->GetParticle(pdg);
Double_t mass = part->Mass();
// set daughter cuts
AliRsnCutSetDaughterParticle* cutSetPi;
AliRsnCutSetDaughterParticle* cutSetK;
AliRsnCutTrackQuality* trkQualityCut= new AliRsnCutTrackQuality("myQualityCut");
if(!trkQualityCut) return kFALSE;
if(SetCustomQualityCut(trkQualityCut,customQualityCutsID,Strcut)){
cutSetPi=new AliRsnCutSetDaughterParticle(Form("cutPi%i_%2.1fsigmaTPC_%2.1fsigmaTOF",cutKaCandidate,nsigmaPi,nsigmaTOF),trkQualityCut,cutKaCandidate,AliPID::kPion,nsigmaPi,nsigmaTOF);
cutSetK=new AliRsnCutSetDaughterParticle(Form("cutK%i_%2.1fsigma_%2.1fsigmaTOF",cutKaCandidate, nsigmaK,nsigmaTOF),trkQualityCut,cutKaCandidate,AliPID::kKaon,nsigmaK,nsigmaTOF);
}
else{
printf("Doughter Track cuts has been selected =================\n");
return kFALSE;
}
Int_t iCutPi = task->AddTrackCuts(cutSetPi);
Int_t iCutK = task->AddTrackCuts(cutSetK);
if(enableMonitor){
Printf("======== Monitoring cut AliRsnCutSetDaughterParticle enabled");
gROOT->LoadMacro("$ALICE_PHYSICS/PWGLF/RESONANCES/macros/mini/AddMonitorOutput.C");
AddMonitorOutput(isMC, cutSetPi->GetMonitorOutput());
AddMonitorOutput(isMC, cutSetK->GetMonitorOutput());
}
// -- Values ------------------------------------------------------------------------------------
/* invariant mass */ Int_t imID = task->CreateValue(AliRsnMiniValue::kInvMass, kFALSE);
/* IM resolution */ Int_t resID = task->CreateValue(AliRsnMiniValue::kInvMassRes, kTRUE);
/* transv. momentum */ Int_t ptID = task->CreateValue(AliRsnMiniValue::kPt, kFALSE);
/* centrality */ Int_t centID = task->CreateValue(AliRsnMiniValue::kMult, kFALSE);
/* pseudorapidity */ Int_t etaID = task->CreateValue(AliRsnMiniValue::kEta, kFALSE);
/* rapidity */ Int_t yID = task->CreateValue(AliRsnMiniValue::kY, kFALSE);
// -- Create all needed outputs -----------------------------------------------------------------
// use an array for more compact writing, which are different on mixing and charges
// [0] = unlike
// [1] = mixing
// [2] = like ++
// [3] = like --
return kTRUE;
Bool_t use [12] = {1 ,1 ,1 ,1 ,1 ,1 ,isMC ,isMC ,isMC ,isMC ,isMC ,isMC };
Bool_t useIM [12] = {1 ,1 ,1 ,1 ,1 ,1 ,1 ,1 ,1 ,1 ,0 ,0 };
TString name [12] = {"UnlikePM","UnlikeMP","MixingPM","MixingMP","LikePP","LikeMM","MCGenPM","MCGenMP","TruesPM","TruesMP","ResPM" ,"ResMP" };
TString comp [12] = {"PAIR" ,"PAIR" ,"MIX" ,"MIX" ,"PAIR" ,"PAIR" ,"MOTHER" ,"MOTHER" ,"TRUE" ,"TRUE" ,"TRUE" ,"TRUE" };
TString output [12] = {"SPARSE" ,"SPARSE" ,"SPARSE" ,"SPARSE" ,"SPARSE","SPARSE","SPARSE" ,"SPARSE" ,"SPARSE" ,"SPARSE" ,"SPARSE","SPARSE"};
Char_t charge1 [12] = {'+' ,'-' ,'+' ,'-' ,'+' ,'-' ,'+' ,'-' ,'+' ,'-' ,'+' ,'-' };
Char_t charge2 [12] = {'-' ,'+' ,'-' ,'+' ,'+' ,'-' ,'-' ,'+' ,'_' ,'+' ,'-' ,'+' };
Int_t cutIDK [12] = {iCutK ,iCutK ,iCutK ,iCutK ,iCutK ,iCutK ,iCutK ,iCutK ,iCutK ,iCutK ,iCutK ,iCutK };
Int_t cutIDPi [12] = {iCutPi ,iCutPi ,iCutPi ,iCutPi ,iCutPi ,iCutPi ,iCutPi ,iCutPi ,iCutPi ,iCutPi ,iCutPi ,iCutPi };
Int_t PDGCode [12] = {313 ,-313 ,313 ,313 ,313 ,313 ,313 ,-313 ,313 ,-313 ,313 ,-313 };
for (Int_t i = 0; i < 12; i++) {
if (!use[i]) continue;
AliRsnMiniOutput *out = task->CreateOutput(Form("CustomId%d_%s", customQualityCutsID, name[i].Data()), output[i].Data(), comp[i].Data());
out->SetDaughter(0, AliRsnDaughter::kKaon);
out->SetDaughter(1, AliRsnDaughter::kPion);
out->SetCutID(0, cutIDK[i]);
out->SetCutID(1, cutIDPi[i]);
out->SetCharge(0, charge1[i]);
out->SetCharge(1, charge2[i]);
out->SetMotherPDG(PDGCode[i]);
out->SetMotherMass(mass);
out->SetPairCuts(cutsPair);
// axis X: invmass (or resolution)
if (useIM[i])
out->AddAxis(imID, 180, 0.6, 1.5);
else
out->AddAxis(resID, 200, -0.02, 0.02);
// axis Y: transverse momentum
out->AddAxis(ptID, 500, 0.0, 50.0);
// axis Z: centrality-multiplicity
//if (!isPP)
out->AddAxis(centID, 100, 0.0, 100.0);
//else
//out->AddAxis(centID, 400, 0.0, 400.0);
//axis W: pseudorapidity
//out->AddAxis(etaID, 20, -1.0, 1.0);
//axis J: rapidity
//out->AddAxis(yID, 90, -4.5, 4.5);
}
return kTRUE;
}
Bool_t SetCustomQualityCut(AliRsnCutTrackQuality * trkQualityCut, Int_t customQualityCutsID = 0,Int_t trCut = 2011)
{
//Sets configuration for track quality object different from std quality cuts.
//Returns kTRUE if track quality cut object is successfully defined,
//returns kFALSE if an invalid set of cuts (customQualityCutsID) is chosen or if the
//object to be configured does not exist.
if ((!trkQualityCut)){
Printf("::::: SetCustomQualityCut:: use default quality cuts specified in task configuration.");
return kFALSE;
}
if(customQualityCutsID>=1 && customQualityCutsID<100 && customQualityCutsID!=2){
if(trCut == 2011){
trkQualityCut->SetDefaults2011(kTRUE,kTRUE);
Printf(Form("::::: SetCustomQualityCut:: using standard 2011 track quality cuts"));
}
else if(trCut == 2015){
trkQualityCut->SetDefaults2011(kTRUE,kTRUE);
trkQualityCut->GetESDtrackCuts()->SetCutGeoNcrNcl(3., 130., 1.5, 0.85, 0.7);
Printf(Form("::::: SetCustomQualityCut:: using standard 2015 track quality cuts"));
}
if(customQualityCutsID==3){trkQualityCut->GetESDtrackCuts()->SetMaxDCAToVertexXYPtDep("0.015+0.05/pt^1.1");}//10Sig // D = 7*(0.0015+0.0050/pt^1.1)
else if(customQualityCutsID==4){trkQualityCut->GetESDtrackCuts()->SetMaxDCAToVertexXYPtDep("0.006+0.02/pt^1.1");}//4Sig
else if(customQualityCutsID==5){trkQualityCut->GetESDtrackCuts()->SetMaxDCAToVertexZ(3.);}// D = 2.
else if(customQualityCutsID==6){trkQualityCut->GetESDtrackCuts()->SetMaxDCAToVertexZ(1.);}
else if(customQualityCutsID==7){trkQualityCut->GetESDtrackCuts()->SetMaxDCAToVertexZ(0.2);}
else if(customQualityCutsID==8){trkQualityCut->GetESDtrackCuts()->SetMaxChi2PerClusterTPC(5.);}// D = 4
else if(customQualityCutsID==9){trkQualityCut->GetESDtrackCuts()->SetMaxChi2PerClusterTPC(3);}
else if(customQualityCutsID==10){trkQualityCut->GetESDtrackCuts()->SetMinNCrossedRowsTPC(60);}// D = 70
else if(customQualityCutsID==11){trkQualityCut->GetESDtrackCuts()->SetMinNCrossedRowsTPC(80);}
else if(customQualityCutsID==12){trkQualityCut->GetESDtrackCuts()->SetMinNCrossedRowsTPC(100);}
else if(customQualityCutsID==13){trkQualityCut->GetESDtrackCuts()->SetMinRatioCrossedRowsOverFindableClustersTPC(0.7);}// D = 8
else if(customQualityCutsID==14){trkQualityCut->GetESDtrackCuts()->SetMinRatioCrossedRowsOverFindableClustersTPC(0.9);}
else if(customQualityCutsID==15){trkQualityCut->GetESDtrackCuts()->SetMaxChi2PerClusterITS(49.);}// D = 36
else if(customQualityCutsID==16){trkQualityCut->GetESDtrackCuts()->SetMaxChi2PerClusterITS(25.);}
else if(customQualityCutsID==17){trkQualityCut->GetESDtrackCuts()->SetMaxChi2TPCConstrainedGlobal(49.);}// D = 36
else if(customQualityCutsID==18){trkQualityCut->GetESDtrackCuts()->SetMaxChi2TPCConstrainedGlobal(25.);}
else if(customQualityCutsID==19){trkQualityCut->GetESDtrackCuts()->SetClusterRequirementITS(AliESDtrackCuts::kSPD,AliESDtrackCuts::kOff);}
trkQualityCut->Print();
return kTRUE;
}else if(customQualityCutsID==2 || (customQualityCutsID>=100 && customQualityCutsID<200)){
trkQualityCut->SetDefaultsTPCOnly(kTRUE);
Printf(Form("::::: SetCustomQualityCut:: using TPC-only track quality cuts"));
if(customQualityCutsID==103){trkQualityCut->GetESDtrackCuts()->SetMaxDCAToVertexXY(3.);}
else if(customQualityCutsID==104){trkQualityCut->GetESDtrackCuts()->SetMaxDCAToVertexXY(1.);}
else if(customQualityCutsID==105){trkQualityCut->GetESDtrackCuts()->SetMaxDCAToVertexZ(4.);}
else if(customQualityCutsID==106){trkQualityCut->GetESDtrackCuts()->SetMaxDCAToVertexZ(1.);}
else if(customQualityCutsID==107){trkQualityCut->GetESDtrackCuts()->SetMaxChi2PerClusterTPC(7.);}
else if(customQualityCutsID==108){trkQualityCut->GetESDtrackCuts()->SetMaxChi2PerClusterTPC(2.5);}
else if(customQualityCutsID==109){trkQualityCut->GetESDtrackCuts()->SetMinNClustersTPC(30);}
else if(customQualityCutsID==110){trkQualityCut->GetESDtrackCuts()->SetMinNClustersTPC(85);}
trkQualityCut->Print();
return kTRUE;
}else{
Printf("::::: SetCustomQualityCut:: use default quality cuts specified in task configuration.");
return kFALSE;
}
trkQualityCut->SetPtRange(0.15, 100000.0);
trkQualityCut->SetEtaRange(-0.8, 0.8);
Printf(Form("::::: SetCustomQualityCut:: using custom track quality cuts #%i",customQualityCutsID));
trkQualityCut->Print();
return kTRUE;
}
<commit_msg>Fix mistake on Config macro for KStar analysis in p-Pb collisions<commit_after>/***************************************************************************
adash@cern.ch - last modified on 05/09/2016
// *** Configuration script for KStar-Meson analysis with 2016 PbPb runs ***
//
// A configuration script for RSN package needs to define the followings:
//
// (1) decay tree of each resonance to be studied, which is needed to select
// true pairs and to assign the right mass to all candidate daughters
// (2) cuts at all levels: single daughters, tracks, events
// (3) output objects: histograms or trees
****************************************************************************/
Bool_t ConfigKStarpPbRunII(AliRsnMiniAnalysisTask *task,
Bool_t isMC,
Bool_t isPP,
AliRsnCutSet *cutsPair,
Int_t Strcut = 2011,
Int_t customQualityCutsID = AliRsnCutSetDaughterParticle::kDisableCustom,
AliRsnCutSetDaughterParticle::ERsnDaughterCutSet cutKaCandidate=AliRsnCutSetDaughterParticle::kTPCTOFpidphikstarpPb2016,
Float_t nsigmaPi = 2.0,
Float_t nsigmaK = 2.0,
Float_t nsigmaTOF= 3.0,
Bool_t enableMonitor = kTRUE
)
{
// retrieve mass from PDG database
Int_t pdg = 313;
TDatabasePDG *db = TDatabasePDG::Instance();
TParticlePDG *part = db->GetParticle(pdg);
Double_t mass = part->Mass();
// set daughter cuts
AliRsnCutSetDaughterParticle* cutSetPi;
AliRsnCutSetDaughterParticle* cutSetK;
AliRsnCutTrackQuality* trkQualityCut= new AliRsnCutTrackQuality("myQualityCut");
if(!trkQualityCut) return kFALSE;
if(SetCustomQualityCut(trkQualityCut,customQualityCutsID,Strcut)){
cutSetPi=new AliRsnCutSetDaughterParticle(Form("cutPi%i_%2.1fsigmaTPC_%2.1fsigmaTOF",cutKaCandidate,nsigmaPi,nsigmaTOF),trkQualityCut,cutKaCandidate,AliPID::kPion,nsigmaPi,nsigmaTOF);
cutSetK=new AliRsnCutSetDaughterParticle(Form("cutK%i_%2.1fsigma_%2.1fsigmaTOF",cutKaCandidate, nsigmaK,nsigmaTOF),trkQualityCut,cutKaCandidate,AliPID::kKaon,nsigmaK,nsigmaTOF);
}
else{
printf("Doughter Track cuts has been selected =================\n");
return kFALSE;
}
Int_t iCutPi = task->AddTrackCuts(cutSetPi);
Int_t iCutK = task->AddTrackCuts(cutSetK);
if(enableMonitor){
Printf("======== Monitoring cut AliRsnCutSetDaughterParticle enabled");
gROOT->LoadMacro("$ALICE_PHYSICS/PWGLF/RESONANCES/macros/mini/AddMonitorOutput.C");
AddMonitorOutput(isMC, cutSetPi->GetMonitorOutput());
AddMonitorOutput(isMC, cutSetK->GetMonitorOutput());
}
// -- Values ------------------------------------------------------------------------------------
/* invariant mass */ Int_t imID = task->CreateValue(AliRsnMiniValue::kInvMass, kFALSE);
/* IM resolution */ Int_t resID = task->CreateValue(AliRsnMiniValue::kInvMassRes, kTRUE);
/* transv. momentum */ Int_t ptID = task->CreateValue(AliRsnMiniValue::kPt, kFALSE);
/* centrality */ Int_t centID = task->CreateValue(AliRsnMiniValue::kMult, kFALSE);
/* pseudorapidity */ Int_t etaID = task->CreateValue(AliRsnMiniValue::kEta, kFALSE);
/* rapidity */ Int_t yID = task->CreateValue(AliRsnMiniValue::kY, kFALSE);
// -- Create all needed outputs -----------------------------------------------------------------
// use an array for more compact writing, which are different on mixing and charges
// [0] = unlike
// [1] = mixing
// [2] = like ++
// [3] = like --
// return kTRUE;
Bool_t use [12] = {1 ,1 ,1 ,1 ,1 ,1 ,isMC ,isMC ,isMC ,isMC ,isMC ,isMC };
Bool_t useIM [12] = {1 ,1 ,1 ,1 ,1 ,1 ,1 ,1 ,1 ,1 ,0 ,0 };
TString name [12] = {"UnlikePM","UnlikeMP","MixingPM","MixingMP","LikePP","LikeMM","MCGenPM","MCGenMP","TruesPM","TruesMP","ResPM" ,"ResMP" };
TString comp [12] = {"PAIR" ,"PAIR" ,"MIX" ,"MIX" ,"PAIR" ,"PAIR" ,"MOTHER" ,"MOTHER" ,"TRUE" ,"TRUE" ,"TRUE" ,"TRUE" };
TString output [12] = {"SPARSE" ,"SPARSE" ,"SPARSE" ,"SPARSE" ,"SPARSE","SPARSE","SPARSE" ,"SPARSE" ,"SPARSE" ,"SPARSE" ,"SPARSE","SPARSE"};
Char_t charge1 [12] = {'+' ,'-' ,'+' ,'-' ,'+' ,'-' ,'+' ,'-' ,'+' ,'-' ,'+' ,'-' };
Char_t charge2 [12] = {'-' ,'+' ,'-' ,'+' ,'+' ,'-' ,'-' ,'+' ,'_' ,'+' ,'-' ,'+' };
Int_t cutIDK [12] = {iCutK ,iCutK ,iCutK ,iCutK ,iCutK ,iCutK ,iCutK ,iCutK ,iCutK ,iCutK ,iCutK ,iCutK };
Int_t cutIDPi [12] = {iCutPi ,iCutPi ,iCutPi ,iCutPi ,iCutPi ,iCutPi ,iCutPi ,iCutPi ,iCutPi ,iCutPi ,iCutPi ,iCutPi };
Int_t PDGCode [12] = {313 ,-313 ,313 ,313 ,313 ,313 ,313 ,-313 ,313 ,-313 ,313 ,-313 };
for (Int_t i = 0; i < 12; i++) {
if (!use[i]) continue;
AliRsnMiniOutput *out = task->CreateOutput(Form("CustomId%d_%s", customQualityCutsID, name[i].Data()), output[i].Data(), comp[i].Data());
out->SetDaughter(0, AliRsnDaughter::kKaon);
out->SetDaughter(1, AliRsnDaughter::kPion);
out->SetCutID(0, cutIDK[i]);
out->SetCutID(1, cutIDPi[i]);
out->SetCharge(0, charge1[i]);
out->SetCharge(1, charge2[i]);
out->SetMotherPDG(PDGCode[i]);
out->SetMotherMass(mass);
out->SetPairCuts(cutsPair);
// axis X: invmass (or resolution)
if (useIM[i])
out->AddAxis(imID, 180, 0.6, 1.5);
else
out->AddAxis(resID, 200, -0.02, 0.02);
// axis Y: transverse momentum
out->AddAxis(ptID, 500, 0.0, 50.0);
// axis Z: centrality-multiplicity
//if (!isPP)
out->AddAxis(centID, 100, 0.0, 100.0);
//else
//out->AddAxis(centID, 400, 0.0, 400.0);
//axis W: pseudorapidity
//out->AddAxis(etaID, 20, -1.0, 1.0);
//axis J: rapidity
//out->AddAxis(yID, 90, -4.5, 4.5);
}
return kTRUE;
}
Bool_t SetCustomQualityCut(AliRsnCutTrackQuality * trkQualityCut, Int_t customQualityCutsID = 0,Int_t trCut = 2011)
{
//Sets configuration for track quality object different from std quality cuts.
//Returns kTRUE if track quality cut object is successfully defined,
//returns kFALSE if an invalid set of cuts (customQualityCutsID) is chosen or if the
//object to be configured does not exist.
if ((!trkQualityCut)){
Printf("::::: SetCustomQualityCut:: use default quality cuts specified in task configuration.");
return kFALSE;
}
if(customQualityCutsID>=1 && customQualityCutsID<100 && customQualityCutsID!=2){
if(trCut == 2011){
trkQualityCut->SetDefaults2011(kTRUE,kTRUE);
Printf(Form("::::: SetCustomQualityCut:: using standard 2011 track quality cuts"));
}
else if(trCut == 2015){
trkQualityCut->SetDefaults2011(kTRUE,kTRUE);
trkQualityCut->GetESDtrackCuts()->SetCutGeoNcrNcl(3., 130., 1.5, 0.85, 0.7);
Printf(Form("::::: SetCustomQualityCut:: using standard 2015 track quality cuts"));
}
if(customQualityCutsID==3){trkQualityCut->GetESDtrackCuts()->SetMaxDCAToVertexXYPtDep("0.015+0.05/pt^1.1");}//10Sig // D = 7*(0.0015+0.0050/pt^1.1)
else if(customQualityCutsID==4){trkQualityCut->GetESDtrackCuts()->SetMaxDCAToVertexXYPtDep("0.006+0.02/pt^1.1");}//4Sig
else if(customQualityCutsID==5){trkQualityCut->GetESDtrackCuts()->SetMaxDCAToVertexZ(3.);}// D = 2.
else if(customQualityCutsID==6){trkQualityCut->GetESDtrackCuts()->SetMaxDCAToVertexZ(1.);}
else if(customQualityCutsID==7){trkQualityCut->GetESDtrackCuts()->SetMaxDCAToVertexZ(0.2);}
else if(customQualityCutsID==8){trkQualityCut->GetESDtrackCuts()->SetMaxChi2PerClusterTPC(5.);}// D = 4
else if(customQualityCutsID==9){trkQualityCut->GetESDtrackCuts()->SetMaxChi2PerClusterTPC(3);}
else if(customQualityCutsID==10){trkQualityCut->GetESDtrackCuts()->SetMinNCrossedRowsTPC(60);}// D = 70
else if(customQualityCutsID==11){trkQualityCut->GetESDtrackCuts()->SetMinNCrossedRowsTPC(80);}
else if(customQualityCutsID==12){trkQualityCut->GetESDtrackCuts()->SetMinNCrossedRowsTPC(100);}
else if(customQualityCutsID==13){trkQualityCut->GetESDtrackCuts()->SetMinRatioCrossedRowsOverFindableClustersTPC(0.7);}// D = 8
else if(customQualityCutsID==14){trkQualityCut->GetESDtrackCuts()->SetMinRatioCrossedRowsOverFindableClustersTPC(0.9);}
else if(customQualityCutsID==15){trkQualityCut->GetESDtrackCuts()->SetMaxChi2PerClusterITS(49.);}// D = 36
else if(customQualityCutsID==16){trkQualityCut->GetESDtrackCuts()->SetMaxChi2PerClusterITS(25.);}
else if(customQualityCutsID==17){trkQualityCut->GetESDtrackCuts()->SetMaxChi2TPCConstrainedGlobal(49.);}// D = 36
else if(customQualityCutsID==18){trkQualityCut->GetESDtrackCuts()->SetMaxChi2TPCConstrainedGlobal(25.);}
else if(customQualityCutsID==19){trkQualityCut->GetESDtrackCuts()->SetClusterRequirementITS(AliESDtrackCuts::kSPD,AliESDtrackCuts::kOff);}
trkQualityCut->Print();
return kTRUE;
}else if(customQualityCutsID==2 || (customQualityCutsID>=100 && customQualityCutsID<200)){
trkQualityCut->SetDefaultsTPCOnly(kTRUE);
Printf(Form("::::: SetCustomQualityCut:: using TPC-only track quality cuts"));
if(customQualityCutsID==103){trkQualityCut->GetESDtrackCuts()->SetMaxDCAToVertexXY(3.);}
else if(customQualityCutsID==104){trkQualityCut->GetESDtrackCuts()->SetMaxDCAToVertexXY(1.);}
else if(customQualityCutsID==105){trkQualityCut->GetESDtrackCuts()->SetMaxDCAToVertexZ(4.);}
else if(customQualityCutsID==106){trkQualityCut->GetESDtrackCuts()->SetMaxDCAToVertexZ(1.);}
else if(customQualityCutsID==107){trkQualityCut->GetESDtrackCuts()->SetMaxChi2PerClusterTPC(7.);}
else if(customQualityCutsID==108){trkQualityCut->GetESDtrackCuts()->SetMaxChi2PerClusterTPC(2.5);}
else if(customQualityCutsID==109){trkQualityCut->GetESDtrackCuts()->SetMinNClustersTPC(30);}
else if(customQualityCutsID==110){trkQualityCut->GetESDtrackCuts()->SetMinNClustersTPC(85);}
trkQualityCut->Print();
return kTRUE;
}else{
Printf("::::: SetCustomQualityCut:: use default quality cuts specified in task configuration.");
return kFALSE;
}
trkQualityCut->SetPtRange(0.15, 100000.0);
trkQualityCut->SetEtaRange(-0.8, 0.8);
Printf(Form("::::: SetCustomQualityCut:: using custom track quality cuts #%i",customQualityCutsID));
trkQualityCut->Print();
return kTRUE;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <lcm/lcm-cpp.hpp>
#include "drake/Path.h"
#include "drake/core/Vector.h"
#include "drake/systems/plants/IKoptions.h"
#include "drake/systems/plants/RigidBodyIK.h"
#include "drake/systems/plants/RigidBodyTree.h"
#include "drake/systems/plants/constraint/RigidBodyConstraint.h"
#include "lcmtypes/drake/lcmt_iiwa_command.hpp"
#include "lcmtypes/drake/lcmt_iiwa_status.hpp"
#include "iiwa_status.h"
using Eigen::MatrixXd;
using Eigen::VectorXd;
using Eigen::VectorXi;
using Drake::Vector1d;
using Eigen::Vector2d;
using Eigen::Vector3d;
namespace drake {
namespace examples {
namespace kuka_iiwa_arm {
namespace {
const char* lcm_command_channel = "IIWA_COMMAND";
// This is a really simple demo class to run a trajectory which is the
// output of an IK plan. It lacks a lot of useful things, like a
// controller which does a remotely good job of mapping the
// trajectory onto the robot.
class TrajectoryRunner {
public:
TrajectoryRunner(std::shared_ptr<lcm::LCM> lcm, int nT, const double* t,
const Eigen::MatrixXd& traj)
: lcm_(lcm), nT_(nT), t_(t), traj_(traj) {
lcm_->subscribe(IiwaStatus<double>::channel(),
&TrajectoryRunner::HandleStatus, this);
}
void Run() {
int64_t start_time = -1;
int cur_step = 0;
// Don't try to run an instantaneous command to time zero. It
// won't make any sense.
if (t_[cur_step] == 0.0) {
cur_step++;
}
lcmt_iiwa_command iiwa_command;
iiwa_command.num_joints = num_joints_;
iiwa_command.joint_position.resize(num_joints_, 0.);
while (cur_step < nT_) {
int handled = lcm_->handleTimeout(10); // timeout is in msec -
// should be safely
// bigger than e.g. a
// 200Hz input rate
if (handled <= 0) {
std::cerr << "Failed to receive LCM status." << std::endl;
return;
}
if (start_time == -1) {
start_time = iiwa_status_.timestamp;
}
const auto desired_next = traj_.col(cur_step);
iiwa_command.timestamp = iiwa_status_.timestamp;
// This is totally arbitrary. There's no good reason to
// implement this as a maximum delta to submit per tick. What
// we actually need is something like a proper controller which
// spreads the motion out over the entire duration from
// current_t to next_t, and commands the next position taking
// into account the velocity of the joints and the distance
// remaining.
const double max_joint_delta = 0.1;
for (int joint = 0; joint < num_joints_; joint++) {
double joint_delta =
desired_next[joint] - iiwa_status_.joint_position_measured[joint];
joint_delta = std::max(-max_joint_delta,
std::min(max_joint_delta, joint_delta));
iiwa_command.joint_position[joint] =
iiwa_status_.joint_position_measured[joint] + joint_delta;
}
lcm_->publish(lcm_command_channel, &iiwa_command);
if ((iiwa_status_.timestamp - start_time) / 1e3 > t_[cur_step]) {
cur_step++;
}
}
}
private:
void HandleStatus(const lcm::ReceiveBuffer* rbuf, const std::string& chan,
const lcmt_iiwa_status* status) {
iiwa_status_ = *status;
}
static const int num_joints_ = 7;
std::shared_ptr<lcm::LCM> lcm_;
const int nT_;
const double* t_;
const Eigen::MatrixXd& traj_;
lcmt_iiwa_status iiwa_status_;
};
int do_main(int argc, const char* argv[]) {
std::shared_ptr<lcm::LCM> lcm = std::make_shared<lcm::LCM>();
RigidBodyTree rbm(
Drake::getDrakePath() + "/examples/kuka_iiwa_arm/urdf/iiwa14.urdf",
DrakeJoint::FIXED);
Vector2d tspan;
tspan << 0, 10;
VectorXd zero_conf = rbm.getZeroConfiguration();
VectorXd joint_lb = zero_conf - VectorXd::Constant(7, 0.01);
VectorXd joint_ub = zero_conf + VectorXd::Constant(7, 0.01);
PostureConstraint pc1(&rbm, Vector2d(0, 0.5));
VectorXi joint_idx(7);
joint_idx << 0, 1, 2, 3, 4, 5, 6;
pc1.setJointLimits(joint_idx, joint_lb, joint_ub);
Vector3d pos_end;
pos_end << 0.56, 0, 0.315;
Vector3d pos_lb = pos_end - Vector3d::Constant(0.01);
Vector3d pos_ub = pos_end + Vector3d::Constant(0.01);
WorldPositionConstraint wpc(&rbm, rbm.FindBodyIndex("iiwa_link_ee"),
Vector3d::Zero(), pos_lb, pos_ub, Vector2d(1, 3));
PostureConstraint pc2(&rbm, Vector2d(4, 5.9));
pc2.setJointLimits(joint_idx, joint_lb, joint_ub);
Eigen::VectorXi joint_idx_3(1);
joint_idx_3(0) = rbm.findJoint("iiwa_joint_2")->position_num_start;
PostureConstraint pc3(&rbm, Vector2d(6, 8));
pc3.setJointLimits(joint_idx_3, Vector1d(0.3), Vector1d(0.4));
WorldPositionConstraint wpc2(&rbm, rbm.FindBodyIndex("iiwa_link_ee"),
Vector3d::Zero(), pos_lb, pos_ub, Vector2d(6, 9));
const int kNumTimesteps = 5;
double t[kNumTimesteps] = { 0.0, 2.0, 5.0, 7.0, 9.0 };
MatrixXd q0(rbm.number_of_positions(), kNumTimesteps);
for (int i = 0; i < kNumTimesteps; i++) {
q0.col(i) = zero_conf;
}
std::vector<RigidBodyConstraint*> constraint_array;
constraint_array.push_back(&pc1);
constraint_array.push_back(&wpc);
constraint_array.push_back(&pc2);
constraint_array.push_back(&pc3);
constraint_array.push_back(&wpc2);
IKoptions ikoptions(&rbm);
int info[kNumTimesteps];
MatrixXd q_sol(rbm.number_of_positions(), kNumTimesteps);
std::vector<std::string> infeasible_constraint;
inverseKinPointwise(&rbm, kNumTimesteps, t, q0, q0, constraint_array.size(),
constraint_array.data(), ikoptions, &q_sol, info,
&infeasible_constraint);
bool info_good = true;
for (int i = 0; i < kNumTimesteps; i++) {
printf("INFO[%d] = %d ", i, info[i]);
if (info[i] != 1) {
info_good = false;
}
}
printf("\n");
if (!info_good) {
std::cerr << "Solution failed, not sending." << std::endl;
return 1;
}
// Now run through the plan.
TrajectoryRunner runner(lcm, kNumTimesteps, t, q_sol);
runner.Run();
return 0;
}
} // namespace
} // namespace kuka_iiwa_arm
} // namespace examples
} // namespace drake
int main(int argc, const char* argv[]) {
return drake::examples::kuka_iiwa_arm::do_main(argc, argv);
}
<commit_msg>Tighten up some constraints and move the position a bit.<commit_after>#include <iostream>
#include <lcm/lcm-cpp.hpp>
#include "drake/Path.h"
#include "drake/core/Vector.h"
#include "drake/systems/plants/IKoptions.h"
#include "drake/systems/plants/RigidBodyIK.h"
#include "drake/systems/plants/RigidBodyTree.h"
#include "drake/systems/plants/constraint/RigidBodyConstraint.h"
#include "lcmtypes/drake/lcmt_iiwa_command.hpp"
#include "lcmtypes/drake/lcmt_iiwa_status.hpp"
#include "iiwa_status.h"
using Eigen::MatrixXd;
using Eigen::VectorXd;
using Eigen::VectorXi;
using Drake::Vector1d;
using Eigen::Vector2d;
using Eigen::Vector3d;
namespace drake {
namespace examples {
namespace kuka_iiwa_arm {
namespace {
const char* lcm_command_channel = "IIWA_COMMAND";
// This is a really simple demo class to run a trajectory which is the
// output of an IK plan. It lacks a lot of useful things, like a
// controller which does a remotely good job of mapping the
// trajectory onto the robot.
class TrajectoryRunner {
public:
TrajectoryRunner(std::shared_ptr<lcm::LCM> lcm, int nT, const double* t,
const Eigen::MatrixXd& traj)
: lcm_(lcm), nT_(nT), t_(t), traj_(traj) {
lcm_->subscribe(IiwaStatus<double>::channel(),
&TrajectoryRunner::HandleStatus, this);
}
void Run() {
int64_t start_time = -1;
int cur_step = 0;
// Don't try to run an instantaneous command to time zero. It
// won't make any sense.
if (t_[cur_step] == 0.0) {
cur_step++;
}
lcmt_iiwa_command iiwa_command;
iiwa_command.num_joints = num_joints_;
iiwa_command.joint_position.resize(num_joints_, 0.);
while (cur_step < nT_) {
int handled = lcm_->handleTimeout(10); // timeout is in msec -
// should be safely
// bigger than e.g. a
// 200Hz input rate
if (handled <= 0) {
std::cerr << "Failed to receive LCM status." << std::endl;
return;
}
if (start_time == -1) {
start_time = iiwa_status_.timestamp;
}
const auto desired_next = traj_.col(cur_step);
iiwa_command.timestamp = iiwa_status_.timestamp;
// This is totally arbitrary. There's no good reason to
// implement this as a maximum delta to submit per tick. What
// we actually need is something like a proper controller which
// spreads the motion out over the entire duration from
// current_t to next_t, and commands the next position taking
// into account the velocity of the joints and the distance
// remaining.
const double max_joint_delta = 0.1;
for (int joint = 0; joint < num_joints_; joint++) {
double joint_delta =
desired_next[joint] - iiwa_status_.joint_position_measured[joint];
joint_delta = std::max(-max_joint_delta,
std::min(max_joint_delta, joint_delta));
iiwa_command.joint_position[joint] =
iiwa_status_.joint_position_measured[joint] + joint_delta;
}
lcm_->publish(lcm_command_channel, &iiwa_command);
if ((iiwa_status_.timestamp - start_time) / 1e3 > t_[cur_step]) {
cur_step++;
}
}
}
private:
void HandleStatus(const lcm::ReceiveBuffer* rbuf, const std::string& chan,
const lcmt_iiwa_status* status) {
iiwa_status_ = *status;
}
static const int num_joints_ = 7;
std::shared_ptr<lcm::LCM> lcm_;
const int nT_;
const double* t_;
const Eigen::MatrixXd& traj_;
lcmt_iiwa_status iiwa_status_;
};
int do_main(int argc, const char* argv[]) {
std::shared_ptr<lcm::LCM> lcm = std::make_shared<lcm::LCM>();
RigidBodyTree rbm(
Drake::getDrakePath() + "/examples/kuka_iiwa_arm/urdf/iiwa14.urdf",
DrakeJoint::FIXED);
Vector2d tspan;
tspan << 0, 10;
VectorXd zero_conf = rbm.getZeroConfiguration();
VectorXd joint_lb = zero_conf - VectorXd::Constant(7, 0.01);
VectorXd joint_ub = zero_conf + VectorXd::Constant(7, 0.01);
PostureConstraint pc1(&rbm, Vector2d(0, 0.5));
VectorXi joint_idx(7);
joint_idx << 0, 1, 2, 3, 4, 5, 6;
pc1.setJointLimits(joint_idx, joint_lb, joint_ub);
Vector3d pos_end;
pos_end << 0.6, 0, 0.325;
Vector3d pos_lb = pos_end - Vector3d::Constant(0.005);
Vector3d pos_ub = pos_end + Vector3d::Constant(0.005);
WorldPositionConstraint wpc(&rbm, rbm.FindBodyIndex("iiwa_link_ee"),
Vector3d::Zero(), pos_lb, pos_ub, Vector2d(1, 3));
PostureConstraint pc2(&rbm, Vector2d(4, 5.9));
pc2.setJointLimits(joint_idx, joint_lb, joint_ub);
Eigen::VectorXi joint_idx_3(1);
joint_idx_3(0) = rbm.findJoint("iiwa_joint_2")->position_num_start;
PostureConstraint pc3(&rbm, Vector2d(6, 8));
pc3.setJointLimits(joint_idx_3, Vector1d(0.63), Vector1d(0.7));
WorldPositionConstraint wpc2(&rbm, rbm.FindBodyIndex("iiwa_link_ee"),
Vector3d::Zero(), pos_lb, pos_ub, Vector2d(6, 9));
const int kNumTimesteps = 5;
double t[kNumTimesteps] = { 0.0, 2.0, 5.0, 7.0, 9.0 };
MatrixXd q0(rbm.number_of_positions(), kNumTimesteps);
for (int i = 0; i < kNumTimesteps; i++) {
q0.col(i) = zero_conf;
}
std::vector<RigidBodyConstraint*> constraint_array;
constraint_array.push_back(&pc1);
constraint_array.push_back(&wpc);
constraint_array.push_back(&pc2);
constraint_array.push_back(&pc3);
constraint_array.push_back(&wpc2);
IKoptions ikoptions(&rbm);
int info[kNumTimesteps];
MatrixXd q_sol(rbm.number_of_positions(), kNumTimesteps);
std::vector<std::string> infeasible_constraint;
inverseKinPointwise(&rbm, kNumTimesteps, t, q0, q0, constraint_array.size(),
constraint_array.data(), ikoptions, &q_sol, info,
&infeasible_constraint);
bool info_good = true;
for (int i = 0; i < kNumTimesteps; i++) {
printf("INFO[%d] = %d ", i, info[i]);
if (info[i] != 1) {
info_good = false;
}
}
printf("\n");
if (!info_good) {
std::cerr << "Solution failed, not sending." << std::endl;
return 1;
}
// Now run through the plan.
TrajectoryRunner runner(lcm, kNumTimesteps, t, q_sol);
runner.Run();
return 0;
}
} // namespace
} // namespace kuka_iiwa_arm
} // namespace examples
} // namespace drake
int main(int argc, const char* argv[]) {
return drake::examples::kuka_iiwa_arm::do_main(argc, argv);
}
<|endoftext|> |
<commit_before>///
/// @file ParallelPrimeSieve.cpp
/// @brief Multi-threaded prime sieve.
///
/// Copyright (C) 2017 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <primesieve/config.hpp>
#include <primesieve/ParallelPrimeSieve.hpp>
#include <primesieve/PrimeSieve.hpp>
#include <primesieve/LockGuard.hpp>
#include <primesieve/pmath.hpp>
#include <stdint.h>
#include <algorithm>
#include <cassert>
#include <chrono>
#include <mutex>
#include <thread>
using namespace std;
namespace primesieve {
ParallelPrimeSieve::ParallelPrimeSieve() :
shm_(nullptr),
numThreads_(getMaxThreads())
{ }
void ParallelPrimeSieve::init(SharedMemory& shm)
{
setStart(shm.start);
setStop(shm.stop);
setSieveSize(shm.sieveSize);
setFlags(shm.flags);
setNumThreads(shm.threads);
shm_ = &shm;
}
int ParallelPrimeSieve::getNumThreads() const
{
return numThreads_;
}
void ParallelPrimeSieve::setNumThreads(int threads)
{
numThreads_ = inBetween(1, threads, getMaxThreads());
}
/// Get an ideal number of threads for
/// the start_ and stop_ numbers.
///
int ParallelPrimeSieve::idealNumThreads() const
{
if (start_ > stop_)
return 1;
uint64_t threshold = max(config::MIN_THREAD_DISTANCE, isqrt(stop_) / 5);
uint64_t threads = getDistance() / threshold;
threads = inBetween(1, threads, numThreads_);
return (int) threads;
}
/// Get a thread distance which ensures a good load
/// balance when using multiple threads.
///
uint64_t ParallelPrimeSieve::getThreadDistance(int threads) const
{
assert(threads > 0);
uint64_t unbalanced = getDistance() / threads;
uint64_t balanced = isqrt(stop_) * 1000;
uint64_t fastest = min(balanced, unbalanced);
uint64_t threadDistance = inBetween(config::MIN_THREAD_DISTANCE, fastest, config::MAX_THREAD_DISTANCE);
uint64_t chunks = getDistance() / threadDistance;
if (chunks < threads * 5u)
threadDistance = max(config::MIN_THREAD_DISTANCE, unbalanced);
threadDistance += 30 - threadDistance % 30;
return threadDistance;
}
/// Align n to modulo 30 + 2 to prevent prime k-tuplet
/// (twin primes, prime triplets) gaps.
///
uint64_t ParallelPrimeSieve::align(uint64_t n) const
{
if (checkedAdd(n, 32) >= stop_)
return stop_;
n = checkedAdd(n, 32) - n % 30;
n = min(n, stop_);
return n;
}
int ParallelPrimeSieve::getMaxThreads()
{
return max<int>(1, thread::hardware_concurrency());
}
/// Sieve the primes and prime k-tuplets within [start_, stop_]
/// in parallel using multi-threading.
///
void ParallelPrimeSieve::sieve()
{
reset();
if (start_ > stop_)
return;
int64_t threads = idealNumThreads();
if (threads == 1)
PrimeSieve::sieve();
else
{
auto t1 = chrono::system_clock::now();
uint64_t threadDistance = getThreadDistance(threads);
int64_t iters = ((getDistance() - 1) / threadDistance) + 1;
int64_t i = 0;
mutex lock;
auto task = [&]()
{
PrimeSieve ps(this);
vector<uint64_t> counts(6, 0);
while (true)
{
auto start = start_;
{
lock_guard<mutex> guard(lock);
if (i >= iters)
break;
start += i * threadDistance;
i += 1;
}
uint64_t stop = checkedAdd(start, threadDistance);
stop = align(stop);
if (start > start_)
start = align(start) + 1;
ps.sieve(start, stop);
counts += ps.counts_;
}
lock_guard<mutex> guard(lock);
counts_ += counts;
};
threads = min(threads, iters);
vector<thread> pool;
pool.reserve(threads);
for (int64_t t = 0; t < threads; t++)
pool.emplace_back(task);
for (thread &t : pool)
t.join();
auto t2 = chrono::system_clock::now();
chrono::duration<double> seconds = t2 - t1;
seconds_ = seconds.count();
}
if (shm_)
{
// communicate the sieving results to
// the primesieve GUI application
copy(counts_.begin(), counts_.end(), shm_->counts);
shm_->seconds = seconds_;
}
}
/// Calculate the sieving status.
/// @processed: Sum of recently processed segments.
///
bool ParallelPrimeSieve::updateStatus(uint64_t processed, bool wait)
{
LockGuard lock(lock_, wait);
if (lock.isSet())
{
PrimeSieve::updateStatus(processed);
if (shm_)
shm_->status = getStatus();
}
return lock.isSet();
}
} // namespace
<commit_msg>Update documentation<commit_after>///
/// @file ParallelPrimeSieve.cpp
/// @brief Multi-threaded prime sieve using std::thread.
///
/// Copyright (C) 2017 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <primesieve/config.hpp>
#include <primesieve/ParallelPrimeSieve.hpp>
#include <primesieve/PrimeSieve.hpp>
#include <primesieve/LockGuard.hpp>
#include <primesieve/pmath.hpp>
#include <stdint.h>
#include <algorithm>
#include <cassert>
#include <chrono>
#include <mutex>
#include <thread>
using namespace std;
namespace primesieve {
ParallelPrimeSieve::ParallelPrimeSieve() :
shm_(nullptr),
numThreads_(getMaxThreads())
{ }
void ParallelPrimeSieve::init(SharedMemory& shm)
{
setStart(shm.start);
setStop(shm.stop);
setSieveSize(shm.sieveSize);
setFlags(shm.flags);
setNumThreads(shm.threads);
shm_ = &shm;
}
int ParallelPrimeSieve::getMaxThreads()
{
return max<int>(1, thread::hardware_concurrency());
}
int ParallelPrimeSieve::getNumThreads() const
{
return numThreads_;
}
void ParallelPrimeSieve::setNumThreads(int threads)
{
numThreads_ = inBetween(1, threads, getMaxThreads());
}
/// Get an ideal number of threads for
/// the start_ and stop_ numbers.
///
int ParallelPrimeSieve::idealNumThreads() const
{
if (start_ > stop_)
return 1;
uint64_t threshold = max(config::MIN_THREAD_DISTANCE, isqrt(stop_) / 5);
uint64_t threads = getDistance() / threshold;
threads = inBetween(1, threads, numThreads_);
return (int) threads;
}
/// Get a thread distance which ensures a good load
/// balance when using multiple threads.
///
uint64_t ParallelPrimeSieve::getThreadDistance(int threads) const
{
assert(threads > 0);
uint64_t unbalanced = getDistance() / threads;
uint64_t balanced = isqrt(stop_) * 1000;
uint64_t fastest = min(balanced, unbalanced);
uint64_t threadDistance = inBetween(config::MIN_THREAD_DISTANCE, fastest, config::MAX_THREAD_DISTANCE);
uint64_t chunks = getDistance() / threadDistance;
if (chunks < threads * 5u)
threadDistance = max(config::MIN_THREAD_DISTANCE, unbalanced);
threadDistance += 30 - threadDistance % 30;
return threadDistance;
}
/// Align n to modulo 30 + 2 to prevent prime k-tuplet
/// (twin primes, prime triplets) gaps.
///
uint64_t ParallelPrimeSieve::align(uint64_t n) const
{
if (checkedAdd(n, 32) >= stop_)
return stop_;
n = checkedAdd(n, 32) - n % 30;
n = min(n, stop_);
return n;
}
/// Sieve the primes and prime k-tuplets within [start_, stop_]
/// in parallel using multi-threading.
///
void ParallelPrimeSieve::sieve()
{
reset();
if (start_ > stop_)
return;
int64_t threads = idealNumThreads();
if (threads == 1)
PrimeSieve::sieve();
else
{
auto t1 = chrono::system_clock::now();
uint64_t threadDistance = getThreadDistance(threads);
int64_t iters = ((getDistance() - 1) / threadDistance) + 1;
int64_t i = 0;
mutex lock;
auto task = [&]()
{
PrimeSieve ps(this);
vector<uint64_t> counts(6, 0);
while (true)
{
auto start = start_;
{
lock_guard<mutex> guard(lock);
if (i >= iters)
break;
start += i * threadDistance;
i += 1;
}
uint64_t stop = checkedAdd(start, threadDistance);
stop = align(stop);
if (start > start_)
start = align(start) + 1;
ps.sieve(start, stop);
counts += ps.counts_;
}
lock_guard<mutex> guard(lock);
counts_ += counts;
};
threads = min(threads, iters);
vector<thread> pool;
pool.reserve(threads);
for (int64_t t = 0; t < threads; t++)
pool.emplace_back(task);
for (thread &t : pool)
t.join();
auto t2 = chrono::system_clock::now();
chrono::duration<double> seconds = t2 - t1;
seconds_ = seconds.count();
}
if (shm_)
{
// communicate the sieving results to
// the primesieve GUI application
copy(counts_.begin(), counts_.end(), shm_->counts);
shm_->seconds = seconds_;
}
}
/// Calculate the sieving status.
/// @processed: Sum of recently processed segments.
///
bool ParallelPrimeSieve::updateStatus(uint64_t processed, bool wait)
{
LockGuard lock(lock_, wait);
if (lock.isSet())
{
PrimeSieve::updateStatus(processed);
if (shm_)
shm_->status = getStatus();
}
return lock.isSet();
}
} // namespace
<|endoftext|> |
<commit_before>#include "stdafx.h"
#include "common.h"
#include "dispatcher.h"
#include "condition.h"
#include "temple_functions.h"
#include "obj.h"
ConditionSystem conds;
class ConditionFunctionReplacement : public TempleFix {
public:
const char* name() override {
return "Condition Function Replacement";
}
void apply() override {
logger->info("Replacing Condition-related Functions");
replaceFunction(0x100E19C0, _CondStructAddToHashtable);
replaceFunction(0x100E1A80, _GetCondStructFromHashcode);
replaceFunction(0x100E1AB0, _CondNodeGetArg);
replaceFunction(0x100E1AD0, _CondNodeSetArg);
replaceFunction(0x100E1DD0, _CondNodeAddToSubDispNodeArray);
replaceFunction(0x100E22D0, _ConditionAddDispatch);
replaceFunction(0x100E24C0, _ConditionAddToAttribs_NumArgs0);
replaceFunction(0x100E2500, _ConditionAddToAttribs_NumArgs2);
replaceFunction(0x100E24E0, _ConditionAdd_NumArgs0);
replaceFunction(0x100E2530, _ConditionAdd_NumArgs2);
replaceFunction(0x100E2560, _ConditionAdd_NumArgs3);
replaceFunction(0x100E2590, _ConditionAdd_NumArgs4);
replaceFunction(0x100ECF30, ConditionPrevent);
replaceFunction(0x100F7BE0, _GetCondStructFromFeat);
}
} condFuncReplacement;
CondNode::CondNode(CondStruct *cond) {
memset(this, 0, sizeof(CondNode));
condStruct = cond;
}
#pragma region Condition Add Functions
int32_t _CondNodeGetArg(CondNode* condNode, uint32_t argIdx)
{
return conds.CondNodeGetArg(condNode, argIdx);
}
void _CondNodeSetArg(CondNode* condNode, uint32_t argIdx, uint32_t argVal)
{
conds.CondNodeSetArg(condNode, argIdx, argVal);
}
uint32_t _ConditionAddDispatch(Dispatcher* dispatcher, CondNode** ppCondNode, CondStruct* condStruct, uint32_t arg1, uint32_t arg2, uint32_t arg3, uint32_t arg4) {
assert(condStruct->numArgs >= 0 && condStruct->numArgs <= 6);
vector<int> args;
if (condStruct->numArgs > 0) {
args.push_back(arg1);
}
if (condStruct->numArgs > 1) {
args.push_back(arg2);
}
if (condStruct->numArgs > 2) {
args.push_back(arg2);
}
if (condStruct->numArgs > 3) {
args.push_back(arg3);
}
if (condStruct->numArgs > 4) {
args.push_back(arg4);
}
return _ConditionAddDispatchArgs(dispatcher, ppCondNode, condStruct, args);
};
uint32_t _ConditionAddDispatchArgs(Dispatcher* dispatcher, CondNode** ppCondNode, CondStruct* condStruct, const vector<int> &args) {
assert(condStruct->numArgs >= args.size());
// pre-add section (may abort adding condition, or cause another condition to be deleted first)
DispIoCondStruct dispIO14h;
dispIO14h.dispIOType = dispIoTypeCondStruct;
dispIO14h.condStruct = condStruct;
dispIO14h.outputFlag = 1;
dispIO14h.arg1 = 0;
dispIO14h.arg2 = 0;
if (args.size() > 0) {
dispIO14h.arg1 = args[0];
}
if (args.size() > 1) {
dispIO14h.arg2 = args[1];
}
_DispatcherProcessor(dispatcher, dispTypeConditionAddPre, 0, (DispIO*)&dispIO14h);
if (dispIO14h.outputFlag == 0) {
return 0;
}
// adding condition
auto condNodeNew = new CondNode(condStruct);
for (unsigned int i = 0; i < condStruct->numArgs; ++i) {
if (i < args.size()) {
condNodeNew->args[i] = args[i];
} else {
// Fill the rest with zeros
condNodeNew->args[i] = 0;
}
}
CondNode** ppNextCondeNode = ppCondNode;
while (*ppNextCondeNode != nullptr) {
ppNextCondeNode = &(*ppNextCondeNode)->nextCondNode;
}
*ppNextCondeNode = condNodeNew;
_CondNodeAddToSubDispNodeArray(dispatcher, condNodeNew);
auto dispatcherSubDispNodeType1 = dispatcher->subDispNodes[1];
while (dispatcherSubDispNodeType1 != nullptr) {
if (dispatcherSubDispNodeType1->subDispDef->dispKey == 0
&& (dispatcherSubDispNodeType1->condNode->flags & 1) == 0
&& condNodeNew == dispatcherSubDispNodeType1->condNode) {
dispatcherSubDispNodeType1->subDispDef->dispCallback(dispatcherSubDispNodeType1, dispatcher->objHnd, dispTypeConditionAdd, 0, nullptr);
}
dispatcherSubDispNodeType1 = dispatcherSubDispNodeType1->next;
}
return 1;
};
void _CondNodeAddToSubDispNodeArray(Dispatcher* dispatcher, CondNode* condNode) {
auto subDispDef = condNode->condStruct->subDispDefs;
while (subDispDef->dispType != 0) {
auto subDispNodeNew = (SubDispNode *)allocFuncs._malloc_0(sizeof(SubDispNode));
subDispNodeNew->subDispDef = subDispDef;
subDispNodeNew->next = nullptr;
subDispNodeNew->condNode = condNode;
auto dispType = subDispDef->dispType;
assert(dispType >= 0 && dispType < dispTypeCount);
auto ppDispatcherSubDispNode = &(dispatcher->subDispNodes[dispType]);
if (*ppDispatcherSubDispNode != nullptr) {
while ((*ppDispatcherSubDispNode)->next != nullptr) {
ppDispatcherSubDispNode = &((*ppDispatcherSubDispNode)->next);
}
(*ppDispatcherSubDispNode)->next = subDispNodeNew;
}
else {
dispatcher->subDispNodes[subDispDef->dispType] = subDispNodeNew;
}
subDispDef += 1;
}
};
uint32_t _ConditionAddToAttribs_NumArgs0(Dispatcher* dispatcher, CondStruct* condStruct) {
return _ConditionAddDispatch(dispatcher, &dispatcher->attributeConds, condStruct, 0, 0, 0, 0);
};
uint32_t _ConditionAddToAttribs_NumArgs2(Dispatcher* dispatcher, CondStruct* condStruct, uint32_t arg1, uint32_t arg2) {
return _ConditionAddDispatch(dispatcher, &dispatcher->attributeConds, condStruct, arg1, arg2, 0, 0);
};
uint32_t _ConditionAdd_NumArgs0(Dispatcher* dispatcher, CondStruct* condStruct) {
return _ConditionAddDispatch(dispatcher, &dispatcher->otherConds, condStruct, 0, 0, 0, 0);
};
uint32_t _ConditionAdd_NumArgs1(Dispatcher* dispatcher, CondStruct* condStruct, uint32_t arg1) {
return _ConditionAddDispatch(dispatcher, &dispatcher->otherConds, condStruct, arg1, 0, 0, 0);
};
uint32_t _ConditionAdd_NumArgs2(Dispatcher* dispatcher, CondStruct* condStruct, uint32_t arg1, uint32_t arg2) {
return _ConditionAddDispatch(dispatcher, &dispatcher->otherConds, condStruct, arg1, arg2, 0, 0);
};
uint32_t _ConditionAdd_NumArgs3(Dispatcher* dispatcher, CondStruct* condStruct, uint32_t arg1, uint32_t arg2, uint32_t arg3) {
return _ConditionAddDispatch(dispatcher, &dispatcher->otherConds, condStruct, arg1, arg2, arg3, 0);
};
uint32_t _ConditionAdd_NumArgs4(Dispatcher* dispatcher, CondStruct* condStruct, uint32_t arg1, uint32_t arg2, uint32_t arg3, uint32_t arg4) {
return _ConditionAddDispatch(dispatcher, &dispatcher->otherConds, condStruct, arg1, arg2, arg3, arg4);
};
#pragma endregion
uint32_t ConditionPrevent(DispatcherCallbackArgs args)
{
DispIoCondStruct * dispIO = _DispIoCheckIoType1((DispIoCondStruct*)args.dispIO);
if (dispIO == nullptr)
{
logger->error("Dispatcher Error! Condition {} fuckup, wrong DispIO type", args.subDispNode->condNode->condStruct->condName);
return 0; // if we get here then VERY BAD!
}
if (dispIO->condStruct == (CondStruct *)args.subDispNode->subDispDef->data1)
{
dispIO->outputFlag = 0;
}
return 0;
};
uint32_t _GetCondStructFromFeat(feat_enums featEnum, CondStruct ** condStructOut, uint32_t * arg2Out)
{
feat_enums * featFromDict = & ( conds.FeatConditionDict->featEnum );
uint32_t iter = 0;
while (
( (int32_t)featEnum != featFromDict[0] || featFromDict[1] != -1)
&& ( (int32_t)featEnum < (int32_t)featFromDict[0]
|| (int32_t)featEnum >= (int32_t)featFromDict[1] )
)
{
iter += 16;
featFromDict += 4;
if (iter >= 0x540){ return 0; }
}
*condStructOut = (CondStruct *)*(featFromDict - 1);
*arg2Out = featEnum + featFromDict[2] - featFromDict[0];
return 1;
}
uint32_t _CondStructAddToHashtable(CondStruct * condStruct)
{
return conds.hashmethods.CondStructAddToHashtable(condStruct);
}
CondStruct * _GetCondStructFromHashcode(uint32_t key)
{
return conds.hashmethods.GetCondStruct(key);
}
CondStruct* ConditionSystem::GetByName(const string& name) {
auto key = templeFuncs.StringHash(name.c_str());
return hashmethods.GetCondStruct(key);
}
void ConditionSystem::AddToItem(objHndl item, const CondStruct* cond, const vector<int>& args) {
assert(args.size() == cond->numArgs);
auto curCondCount = templeFuncs.Obj_Get_IdxField_NumItems(item, obj_f_item_pad_wielder_condition_array);
auto curCondArgCount = templeFuncs.Obj_Get_IdxField_NumItems(item, obj_f_item_pad_wielder_argument_array);
// Add the condition name hash to the list
auto key = templeFuncs.StringHash(cond->condName);
templeFuncs.Obj_Set_IdxField_byValue(item, obj_f_item_pad_wielder_condition_array, curCondCount, key);
auto idx = curCondArgCount;
for (auto arg : args) {
templeFuncs.Obj_Set_IdxField_byValue(item, obj_f_item_pad_wielder_argument_array, idx, arg);
idx++;
}
}
bool ConditionSystem::AddTo(objHndl handle, const CondStruct* cond, const vector<int>& args) {
assert(args.size() == cond->numArgs);
auto dispatcher = objects.GetDispatcher(handle);
if (!dispatcher) {
return false;
}
return _ConditionAddDispatchArgs(dispatcher, &dispatcher->otherConds, const_cast<CondStruct*>(cond), args) != 0;
}
bool ConditionSystem::AddTo(objHndl handle, const string& name, const vector<int>& args) {
auto cond = GetByName(name);
if (!cond) {
logger->warn("Unable to find condition {}", name);
return false;
}
return AddTo(handle, cond, args);
}
int32_t ConditionSystem::CondNodeGetArg(CondNode* condNode, uint32_t argIdx)
{
if (argIdx < condNode->condStruct->numArgs)
{
return condNode->args[argIdx];
}
return 0;
}
void ConditionSystem::CondNodeSetArg(CondNode* condNode, uint32_t argIdx, uint32_t argVal)
{
if (argIdx < condNode->condStruct->numArgs)
{
condNode->args[argIdx] = argVal;
}
}<commit_msg>Fixed bug in ConditionAddDispatch (typo in args)<commit_after>#include "stdafx.h"
#include "common.h"
#include "dispatcher.h"
#include "condition.h"
#include "temple_functions.h"
#include "obj.h"
ConditionSystem conds;
class ConditionFunctionReplacement : public TempleFix {
public:
const char* name() override {
return "Condition Function Replacement";
}
void apply() override {
logger->info("Replacing Condition-related Functions");
replaceFunction(0x100E19C0, _CondStructAddToHashtable);
replaceFunction(0x100E1A80, _GetCondStructFromHashcode);
replaceFunction(0x100E1AB0, _CondNodeGetArg);
replaceFunction(0x100E1AD0, _CondNodeSetArg);
replaceFunction(0x100E1DD0, _CondNodeAddToSubDispNodeArray);
replaceFunction(0x100E22D0, _ConditionAddDispatch);
replaceFunction(0x100E24C0, _ConditionAddToAttribs_NumArgs0);
replaceFunction(0x100E2500, _ConditionAddToAttribs_NumArgs2);
replaceFunction(0x100E24E0, _ConditionAdd_NumArgs0);
replaceFunction(0x100E2530, _ConditionAdd_NumArgs2);
replaceFunction(0x100E2560, _ConditionAdd_NumArgs3);
replaceFunction(0x100E2590, _ConditionAdd_NumArgs4);
replaceFunction(0x100ECF30, ConditionPrevent);
replaceFunction(0x100F7BE0, _GetCondStructFromFeat);
}
} condFuncReplacement;
CondNode::CondNode(CondStruct *cond) {
memset(this, 0, sizeof(CondNode));
condStruct = cond;
}
#pragma region Condition Add Functions
int32_t _CondNodeGetArg(CondNode* condNode, uint32_t argIdx)
{
return conds.CondNodeGetArg(condNode, argIdx);
}
void _CondNodeSetArg(CondNode* condNode, uint32_t argIdx, uint32_t argVal)
{
conds.CondNodeSetArg(condNode, argIdx, argVal);
}
uint32_t _ConditionAddDispatch(Dispatcher* dispatcher, CondNode** ppCondNode, CondStruct* condStruct, uint32_t arg1, uint32_t arg2, uint32_t arg3, uint32_t arg4) {
assert(condStruct->numArgs >= 0 && condStruct->numArgs <= 6);
vector<int> args;
if (condStruct->numArgs > 0) {
args.push_back(arg1);
}
if (condStruct->numArgs > 1) {
args.push_back(arg2);
}
if (condStruct->numArgs > 2) {
args.push_back(arg3);
}
if (condStruct->numArgs > 3) {
args.push_back(arg4);
}
return _ConditionAddDispatchArgs(dispatcher, ppCondNode, condStruct, args);
};
uint32_t _ConditionAddDispatchArgs(Dispatcher* dispatcher, CondNode** ppCondNode, CondStruct* condStruct, const vector<int> &args) {
assert(condStruct->numArgs >= args.size());
// pre-add section (may abort adding condition, or cause another condition to be deleted first)
DispIoCondStruct dispIO14h;
dispIO14h.dispIOType = dispIoTypeCondStruct;
dispIO14h.condStruct = condStruct;
dispIO14h.outputFlag = 1;
dispIO14h.arg1 = 0;
dispIO14h.arg2 = 0;
if (args.size() > 0) {
dispIO14h.arg1 = args[0];
}
if (args.size() > 1) {
dispIO14h.arg2 = args[1];
}
_DispatcherProcessor(dispatcher, dispTypeConditionAddPre, 0, (DispIO*)&dispIO14h);
if (dispIO14h.outputFlag == 0) {
return 0;
}
// adding condition
auto condNodeNew = new CondNode(condStruct);
for (unsigned int i = 0; i < condStruct->numArgs; ++i) {
if (i < args.size()) {
condNodeNew->args[i] = args[i];
} else {
// Fill the rest with zeros
condNodeNew->args[i] = 0;
}
}
CondNode** ppNextCondeNode = ppCondNode;
while (*ppNextCondeNode != nullptr) {
ppNextCondeNode = &(*ppNextCondeNode)->nextCondNode;
}
*ppNextCondeNode = condNodeNew;
_CondNodeAddToSubDispNodeArray(dispatcher, condNodeNew);
auto dispatcherSubDispNodeType1 = dispatcher->subDispNodes[1];
while (dispatcherSubDispNodeType1 != nullptr) {
if (dispatcherSubDispNodeType1->subDispDef->dispKey == 0
&& (dispatcherSubDispNodeType1->condNode->flags & 1) == 0
&& condNodeNew == dispatcherSubDispNodeType1->condNode) {
dispatcherSubDispNodeType1->subDispDef->dispCallback(dispatcherSubDispNodeType1, dispatcher->objHnd, dispTypeConditionAdd, 0, nullptr);
}
dispatcherSubDispNodeType1 = dispatcherSubDispNodeType1->next;
}
return 1;
};
void _CondNodeAddToSubDispNodeArray(Dispatcher* dispatcher, CondNode* condNode) {
auto subDispDef = condNode->condStruct->subDispDefs;
while (subDispDef->dispType != 0) {
auto subDispNodeNew = (SubDispNode *)allocFuncs._malloc_0(sizeof(SubDispNode));
subDispNodeNew->subDispDef = subDispDef;
subDispNodeNew->next = nullptr;
subDispNodeNew->condNode = condNode;
auto dispType = subDispDef->dispType;
assert(dispType >= 0 && dispType < dispTypeCount);
auto ppDispatcherSubDispNode = &(dispatcher->subDispNodes[dispType]);
if (*ppDispatcherSubDispNode != nullptr) {
while ((*ppDispatcherSubDispNode)->next != nullptr) {
ppDispatcherSubDispNode = &((*ppDispatcherSubDispNode)->next);
}
(*ppDispatcherSubDispNode)->next = subDispNodeNew;
}
else {
dispatcher->subDispNodes[subDispDef->dispType] = subDispNodeNew;
}
subDispDef += 1;
}
};
uint32_t _ConditionAddToAttribs_NumArgs0(Dispatcher* dispatcher, CondStruct* condStruct) {
return _ConditionAddDispatch(dispatcher, &dispatcher->attributeConds, condStruct, 0, 0, 0, 0);
};
uint32_t _ConditionAddToAttribs_NumArgs2(Dispatcher* dispatcher, CondStruct* condStruct, uint32_t arg1, uint32_t arg2) {
return _ConditionAddDispatch(dispatcher, &dispatcher->attributeConds, condStruct, arg1, arg2, 0, 0);
};
uint32_t _ConditionAdd_NumArgs0(Dispatcher* dispatcher, CondStruct* condStruct) {
return _ConditionAddDispatch(dispatcher, &dispatcher->otherConds, condStruct, 0, 0, 0, 0);
};
uint32_t _ConditionAdd_NumArgs1(Dispatcher* dispatcher, CondStruct* condStruct, uint32_t arg1) {
return _ConditionAddDispatch(dispatcher, &dispatcher->otherConds, condStruct, arg1, 0, 0, 0);
};
uint32_t _ConditionAdd_NumArgs2(Dispatcher* dispatcher, CondStruct* condStruct, uint32_t arg1, uint32_t arg2) {
return _ConditionAddDispatch(dispatcher, &dispatcher->otherConds, condStruct, arg1, arg2, 0, 0);
};
uint32_t _ConditionAdd_NumArgs3(Dispatcher* dispatcher, CondStruct* condStruct, uint32_t arg1, uint32_t arg2, uint32_t arg3) {
return _ConditionAddDispatch(dispatcher, &dispatcher->otherConds, condStruct, arg1, arg2, arg3, 0);
};
uint32_t _ConditionAdd_NumArgs4(Dispatcher* dispatcher, CondStruct* condStruct, uint32_t arg1, uint32_t arg2, uint32_t arg3, uint32_t arg4) {
return _ConditionAddDispatch(dispatcher, &dispatcher->otherConds, condStruct, arg1, arg2, arg3, arg4);
};
#pragma endregion
uint32_t ConditionPrevent(DispatcherCallbackArgs args)
{
DispIoCondStruct * dispIO = _DispIoCheckIoType1((DispIoCondStruct*)args.dispIO);
if (dispIO == nullptr)
{
logger->error("Dispatcher Error! Condition {} fuckup, wrong DispIO type", args.subDispNode->condNode->condStruct->condName);
return 0; // if we get here then VERY BAD!
}
if (dispIO->condStruct == (CondStruct *)args.subDispNode->subDispDef->data1)
{
dispIO->outputFlag = 0;
}
return 0;
};
uint32_t _GetCondStructFromFeat(feat_enums featEnum, CondStruct ** condStructOut, uint32_t * arg2Out)
{
feat_enums * featFromDict = & ( conds.FeatConditionDict->featEnum );
uint32_t iter = 0;
while (
( (int32_t)featEnum != featFromDict[0] || featFromDict[1] != -1)
&& ( (int32_t)featEnum < (int32_t)featFromDict[0]
|| (int32_t)featEnum >= (int32_t)featFromDict[1] )
)
{
iter += 16;
featFromDict += 4;
if (iter >= 0x540){ return 0; }
}
*condStructOut = (CondStruct *)*(featFromDict - 1);
*arg2Out = featEnum + featFromDict[2] - featFromDict[0];
return 1;
}
uint32_t _CondStructAddToHashtable(CondStruct * condStruct)
{
return conds.hashmethods.CondStructAddToHashtable(condStruct);
}
CondStruct * _GetCondStructFromHashcode(uint32_t key)
{
return conds.hashmethods.GetCondStruct(key);
}
CondStruct* ConditionSystem::GetByName(const string& name) {
auto key = templeFuncs.StringHash(name.c_str());
return hashmethods.GetCondStruct(key);
}
void ConditionSystem::AddToItem(objHndl item, const CondStruct* cond, const vector<int>& args) {
assert(args.size() == cond->numArgs);
auto curCondCount = templeFuncs.Obj_Get_IdxField_NumItems(item, obj_f_item_pad_wielder_condition_array);
auto curCondArgCount = templeFuncs.Obj_Get_IdxField_NumItems(item, obj_f_item_pad_wielder_argument_array);
// Add the condition name hash to the list
auto key = templeFuncs.StringHash(cond->condName);
templeFuncs.Obj_Set_IdxField_byValue(item, obj_f_item_pad_wielder_condition_array, curCondCount, key);
auto idx = curCondArgCount;
for (auto arg : args) {
templeFuncs.Obj_Set_IdxField_byValue(item, obj_f_item_pad_wielder_argument_array, idx, arg);
idx++;
}
}
bool ConditionSystem::AddTo(objHndl handle, const CondStruct* cond, const vector<int>& args) {
assert(args.size() == cond->numArgs);
auto dispatcher = objects.GetDispatcher(handle);
if (!dispatcher) {
return false;
}
return _ConditionAddDispatchArgs(dispatcher, &dispatcher->otherConds, const_cast<CondStruct*>(cond), args) != 0;
}
bool ConditionSystem::AddTo(objHndl handle, const string& name, const vector<int>& args) {
auto cond = GetByName(name);
if (!cond) {
logger->warn("Unable to find condition {}", name);
return false;
}
return AddTo(handle, cond, args);
}
int32_t ConditionSystem::CondNodeGetArg(CondNode* condNode, uint32_t argIdx)
{
if (argIdx < condNode->condStruct->numArgs)
{
return condNode->args[argIdx];
}
return 0;
}
void ConditionSystem::CondNodeSetArg(CondNode* condNode, uint32_t argIdx, uint32_t argVal)
{
if (argIdx < condNode->condStruct->numArgs)
{
condNode->args[argIdx] = argVal;
}
}<|endoftext|> |
<commit_before>/*********************************************************************************
*
* Inviwo - Interactive Visualization Workshop
*
* Copyright (c) 2012-2015 Inviwo Foundation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*********************************************************************************/
#include <inviwo/core/common/inviwoapplication.h>
#include <inviwo/qt/editor/processorlistwidget.h>
#include <inviwo/qt/editor/helpwidget.h>
#include <inviwo/core/processors/processorstate.h>
#include <inviwo/core/processors/processortags.h>
#include <inviwo/core/network/processornetwork.h>
#include <inviwo/core/common/inviwomodule.h>
#include <inviwo/core/util/tooltiphelper.h>
#include <inviwo/qt/widgets/inviwoqtutils.h>
#include <inviwo/core/metadata/processormetadata.h>
#include <warn/push>
#include <warn/ignore/all>
#include <QApplication>
#include <QLayout>
#include <QLabel>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QWidget>
#include <QMimeData>
#include <QHeaderView>
#include <warn/pop>
namespace inviwo {
const int ProcessorTree::IDENTIFIER_ROLE = Qt::UserRole + 1;
void ProcessorTree::mousePressEvent(QMouseEvent* e) {
if (e->buttons() & Qt::LeftButton) dragStartPosition_ = e->pos();
QTreeWidget::mousePressEvent(e);
}
void ProcessorTree::mouseMoveEvent(QMouseEvent* e) {
if (e->buttons() & Qt::LeftButton) {
if ((e->pos() - dragStartPosition_).manhattanLength() < QApplication::startDragDistance())
return;
QTreeWidgetItem* selectedProcessor = itemAt(dragStartPosition_);
if (selectedProcessor && selectedProcessor->parent())
new ProcessorDragObject(this, selectedProcessor->data(0, IDENTIFIER_ROLE).toString());
}
}
ProcessorTree::ProcessorTree(QWidget* parent) : QTreeWidget(parent) {}
ProcessorTreeWidget::ProcessorTreeWidget(QWidget* parent, HelpWidget* helpWidget)
: InviwoDockWidget(tr("Processors"), parent), helpWidget_(helpWidget) {
setObjectName("ProcessorTreeWidget");
setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea);
QWidget* centralWidget = new QWidget();
QVBoxLayout* vLayout = new QVBoxLayout(centralWidget);
vLayout->setSpacing(7);
vLayout->setContentsMargins(7, 7, 7, 7);
lineEdit_ = new QLineEdit(centralWidget);
lineEdit_->setPlaceholderText("Filter processor list...");
#if (QT_VERSION >= QT_VERSION_CHECK(5, 2, 0))
lineEdit_->setClearButtonEnabled(true);
#endif // QT_VERSION
connect(lineEdit_, SIGNAL(textChanged(const QString&)), this, SLOT(addProcessorsToTree()));
vLayout->addWidget(lineEdit_);
QHBoxLayout* listViewLayout = new QHBoxLayout();
listViewLayout->addWidget(new QLabel("Group by", centralWidget));
listView_ = new QComboBox(centralWidget);
listView_->addItem("Alphabet");
listView_->addItem("Category");
listView_->addItem("Code State");
listView_->addItem("Module");
listView_->setCurrentIndex(1);
connect(listView_, SIGNAL(currentIndexChanged(int)), this, SLOT(addProcessorsToTree()));
listView_->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Preferred);
listViewLayout->addWidget(listView_);
vLayout->addLayout(listViewLayout);
iconStable_ = QIcon(":/icons/processor_stable.png");
iconExperimental_ = QIcon(":/icons/processor_experimental.png");
iconBroken_ = QIcon(":/icons/processor_broken.png");
processorTree_ = new ProcessorTree(this);
processorTree_->setHeaderHidden(true);
processorTree_->setColumnCount(2);
processorTree_->setIndentation(10);
processorTree_->setAnimated(true);
processorTree_->header()->setStretchLastSection(false);
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
processorTree_->header()->setSectionResizeMode(0, QHeaderView::Stretch);
processorTree_->header()->setSectionResizeMode(1, QHeaderView::Fixed);
#else
processorTree_->header()->setResizeMode(0, QHeaderView::Stretch);
processorTree_->header()->setResizeMode(1, QHeaderView::Fixed);
#endif
processorTree_->header()->setDefaultSectionSize(40);
connect(processorTree_, SIGNAL(currentItemChanged(QTreeWidgetItem*, QTreeWidgetItem*)), this,
SLOT(currentItemChanged(QTreeWidgetItem*, QTreeWidgetItem*)));
addProcessorsToTree();
vLayout->addWidget(processorTree_);
centralWidget->setLayout(vLayout);
setWidget(centralWidget);
}
ProcessorTreeWidget::~ProcessorTreeWidget() {}
void ProcessorTreeWidget::focusSearch() {
raise();
lineEdit_->setFocus();
lineEdit_->selectAll();
}
void ProcessorTreeWidget::addSelectedProcessor() {
std::string id;
auto items = processorTree_->selectedItems();
if (items.size() > 0) {
id = items[0]->data(0, ProcessorTree::IDENTIFIER_ROLE).toString().toStdString();
} else {
auto count = processorTree_->topLevelItemCount();
if (count == 1) {
auto item = processorTree_->topLevelItem(0);
if (item->childCount() == 1) {
id = item->child(0)
->data(0, ProcessorTree::IDENTIFIER_ROLE)
.toString()
.toStdString();
}
}
}
if (!id.empty()) {
addProcessor(id);
} else {
processorTree_->setFocus();
processorTree_->topLevelItem(0)->child(0)->setSelected(true);
}
}
void ProcessorTreeWidget::addProcessor(std::string className) {
try {
// create processor, add it to processor network, and generate it's widgets
auto network = InviwoApplication::getPtr()->getProcessorNetwork();
if (auto p = ProcessorFactory::getPtr()->create(className)) {
auto meta = p->getMetaData<ProcessorMetaData>(ProcessorMetaData::CLASS_IDENTIFIER);
auto pos = util::transform(network->getProcessors(), [](Processor* elem) {
return elem->getMetaData<ProcessorMetaData>(ProcessorMetaData::CLASS_IDENTIFIER)
->getPosition();
});
pos.push_back(ivec2(0, 0));
auto min = std::min_element(pos.begin(), pos.end(),
[](const ivec2& a, const ivec2& b) { return a.y > b.y; });
meta->setPosition(*min + ivec2(0, 75));
network->addProcessor(p.get());
network->autoLinkProcessor(p.get());
p.release();
}
} catch (Exception& exception) {
util::log(exception.getContext(),
"Unable to create processor " + className + " due to " + exception.getMessage(),
LogLevel::Error);
}
}
bool ProcessorTreeWidget::processorFits(ProcessorFactoryObject* processor, const QString& filter) {
return (
QString::fromStdString(processor->getDisplayName()).contains(filter, Qt::CaseInsensitive) ||
QString::fromStdString(processor->getClassIdentifier())
.contains(filter, Qt::CaseInsensitive) ||
QString::fromStdString(processor->getTags().getString())
.contains(filter, Qt::CaseInsensitive));
}
const QIcon* ProcessorTreeWidget::getCodeStateIcon(CodeState state) const {
switch (state) {
case CodeState::Stable:
return &iconStable_;
case CodeState::Broken:
return &iconBroken_;
case CodeState::Experimental:
default:
return &iconExperimental_;
}
}
QTreeWidgetItem* ProcessorTreeWidget::addToplevelItemTo(QString title) {
QTreeWidgetItem* newItem = new QTreeWidgetItem(QStringList(title));
processorTree_->addTopLevelItem(newItem);
processorTree_->setFirstItemColumnSpanned(newItem, true);
return newItem;
}
QTreeWidgetItem* ProcessorTreeWidget::addProcessorItemTo(QTreeWidgetItem* item,
ProcessorFactoryObject* processor,
std::string moduleId) {
QTreeWidgetItem* newItem = new QTreeWidgetItem();
newItem->setIcon(0, *getCodeStateIcon(processor->getCodeState()));
newItem->setText(0, QString::fromStdString(processor->getDisplayName()));
newItem->setText(1, QString::fromStdString(processor->getTags().getString() + " "));
newItem->setTextAlignment(1, Qt::AlignRight);
newItem->setData(0, ProcessorTree::IDENTIFIER_ROLE,
QString::fromStdString(processor->getClassIdentifier()));
ToolTipHelper t(processor->getDisplayName());
t.row("Module", moduleId);
t.row("Identifier", processor->getClassIdentifier());
t.row("Category", processor->getCategory());
t.row("Code", Processor::getCodeStateString(processor->getCodeState()));
t.row("Tags", processor->getTags().getString());
newItem->setToolTip(0, utilqt::toLocalQString(t));
QFont font = newItem->font(1);
font.setWeight(QFont::Bold);
newItem->setFont(1, font);
item->addChild(newItem);
if (processor->getTags().tags_.size() == 0) {
processorTree_->setFirstItemColumnSpanned(newItem, true);
}
return newItem;
}
void ProcessorTreeWidget::addProcessorsToTree() {
processorTree_->clear();
// add processors from all modules to the list
InviwoApplication* inviwoApp = InviwoApplication::getPtr();
if (listView_->currentIndex() == 2) {
addToplevelItemTo("Stable Processors");
addToplevelItemTo("Experimental Processors");
addToplevelItemTo("Broken Processors");
}
for (auto& elem : inviwoApp->getModules()) {
std::vector<ProcessorFactoryObject*> curProcessorList = elem->getProcessors();
QList<QTreeWidgetItem*> items;
for (auto& processor : curProcessorList) {
if (lineEdit_->text().isEmpty() || processorFits(processor, lineEdit_->text())) {
std::string categoryName;
switch (listView_->currentIndex()) {
case 0: // By Alphabet
categoryName = processor->getDisplayName().substr(0, 1);
break;
case 1: // By Category
categoryName = processor->getCategory();
break;
case 2: // By Code State
categoryName = Processor::getCodeStateString(processor->getCodeState());
break;
case 3: // By Module
categoryName = elem->getIdentifier();
break;
default:
categoryName = "Unkonwn";
}
QString category = QString::fromStdString(categoryName);
items = processorTree_->findItems(category, Qt::MatchFixedString, 0);
if (items.empty()) items.push_back(addToplevelItemTo(category));
addProcessorItemTo(items[0], processor, elem->getIdentifier());
}
}
}
// Apply sorting
switch (listView_->currentIndex()) {
case 2: { // By Code State
int i = 0;
while (i < processorTree_->topLevelItemCount()) {
QTreeWidgetItem* item = processorTree_->topLevelItem(i);
if (item->childCount() == 0) {
delete processorTree_->takeTopLevelItem(i);
} else {
item->sortChildren(0, Qt::AscendingOrder);
i++;
}
}
break;
}
default:
processorTree_->sortItems(0, Qt::AscendingOrder);
break;
}
processorTree_->expandAll();
processorTree_->resizeColumnToContents(1);
}
void ProcessorTreeWidget::currentItemChanged(QTreeWidgetItem* current, QTreeWidgetItem* previous) {
if (!current) return;
std::string classname =
current->data(0, ProcessorTree::IDENTIFIER_ROLE).toString().toUtf8().constData();
if (!classname.empty()) helpWidget_->showDocForClassName(classname);
}
static QString mimeType = "inviwo/ProcessorDragObject";
ProcessorDragObject::ProcessorDragObject(QWidget* source, const QString className) : QDrag(source) {
QByteArray byteData;
{
QDataStream ds(&byteData, QIODevice::WriteOnly);
ds << className;
}
QMimeData* mimeData = new QMimeData;
mimeData->setData(mimeType, byteData);
mimeData->setData("text/plain", className.toLatin1().data());
setMimeData(mimeData);
start(Qt::MoveAction);
}
bool ProcessorDragObject::canDecode(const QMimeData* mimeData) {
if (mimeData->hasFormat(mimeType))
return true;
else
return false;
}
bool ProcessorDragObject::decode(const QMimeData* mimeData, QString& className) {
QByteArray byteData = mimeData->data(mimeType);
if (byteData.isEmpty()) return false;
QDataStream ds(&byteData, QIODevice::ReadOnly);
ds >> className;
return true;
}
} // namespace<commit_msg>Qt: Processorlistwidget fix<commit_after>/*********************************************************************************
*
* Inviwo - Interactive Visualization Workshop
*
* Copyright (c) 2012-2015 Inviwo Foundation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*********************************************************************************/
#include <inviwo/core/common/inviwoapplication.h>
#include <inviwo/qt/editor/processorlistwidget.h>
#include <inviwo/qt/editor/helpwidget.h>
#include <inviwo/core/processors/processorstate.h>
#include <inviwo/core/processors/processortags.h>
#include <inviwo/core/network/processornetwork.h>
#include <inviwo/core/common/inviwomodule.h>
#include <inviwo/core/util/tooltiphelper.h>
#include <inviwo/qt/widgets/inviwoqtutils.h>
#include <inviwo/core/metadata/processormetadata.h>
#include <warn/push>
#include <warn/ignore/all>
#include <QApplication>
#include <QLayout>
#include <QLabel>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QWidget>
#include <QMimeData>
#include <QHeaderView>
#include <warn/pop>
namespace inviwo {
const int ProcessorTree::IDENTIFIER_ROLE = Qt::UserRole + 1;
void ProcessorTree::mousePressEvent(QMouseEvent* e) {
if (e->buttons() & Qt::LeftButton) dragStartPosition_ = e->pos();
QTreeWidget::mousePressEvent(e);
}
void ProcessorTree::mouseMoveEvent(QMouseEvent* e) {
if (e->buttons() & Qt::LeftButton) {
if ((e->pos() - dragStartPosition_).manhattanLength() < QApplication::startDragDistance())
return;
QTreeWidgetItem* selectedProcessor = itemAt(dragStartPosition_);
if (selectedProcessor && selectedProcessor->parent())
new ProcessorDragObject(this, selectedProcessor->data(0, IDENTIFIER_ROLE).toString());
}
}
ProcessorTree::ProcessorTree(QWidget* parent) : QTreeWidget(parent) {}
ProcessorTreeWidget::ProcessorTreeWidget(QWidget* parent, HelpWidget* helpWidget)
: InviwoDockWidget(tr("Processors"), parent), helpWidget_(helpWidget) {
setObjectName("ProcessorTreeWidget");
setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea);
QWidget* centralWidget = new QWidget();
QVBoxLayout* vLayout = new QVBoxLayout(centralWidget);
vLayout->setSpacing(7);
vLayout->setContentsMargins(7, 7, 7, 7);
lineEdit_ = new QLineEdit(centralWidget);
lineEdit_->setPlaceholderText("Filter processor list...");
#if (QT_VERSION >= QT_VERSION_CHECK(5, 2, 0))
lineEdit_->setClearButtonEnabled(true);
#endif // QT_VERSION
connect(lineEdit_, SIGNAL(textChanged(const QString&)), this, SLOT(addProcessorsToTree()));
vLayout->addWidget(lineEdit_);
QHBoxLayout* listViewLayout = new QHBoxLayout();
listViewLayout->addWidget(new QLabel("Group by", centralWidget));
listView_ = new QComboBox(centralWidget);
listView_->addItem("Alphabet");
listView_->addItem("Category");
listView_->addItem("Code State");
listView_->addItem("Module");
listView_->setCurrentIndex(1);
connect(listView_, SIGNAL(currentIndexChanged(int)), this, SLOT(addProcessorsToTree()));
listView_->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Preferred);
listViewLayout->addWidget(listView_);
vLayout->addLayout(listViewLayout);
iconStable_ = QIcon(":/icons/processor_stable.png");
iconExperimental_ = QIcon(":/icons/processor_experimental.png");
iconBroken_ = QIcon(":/icons/processor_broken.png");
processorTree_ = new ProcessorTree(this);
processorTree_->setHeaderHidden(true);
processorTree_->setColumnCount(2);
processorTree_->setIndentation(10);
processorTree_->setAnimated(true);
processorTree_->header()->setStretchLastSection(false);
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
processorTree_->header()->setSectionResizeMode(0, QHeaderView::Stretch);
processorTree_->header()->setSectionResizeMode(1, QHeaderView::Fixed);
#else
processorTree_->header()->setResizeMode(0, QHeaderView::Stretch);
processorTree_->header()->setResizeMode(1, QHeaderView::Fixed);
#endif
processorTree_->header()->setDefaultSectionSize(40);
connect(processorTree_, SIGNAL(currentItemChanged(QTreeWidgetItem*, QTreeWidgetItem*)), this,
SLOT(currentItemChanged(QTreeWidgetItem*, QTreeWidgetItem*)));
addProcessorsToTree();
vLayout->addWidget(processorTree_);
centralWidget->setLayout(vLayout);
setWidget(centralWidget);
}
ProcessorTreeWidget::~ProcessorTreeWidget() {}
void ProcessorTreeWidget::focusSearch() {
raise();
lineEdit_->setFocus();
lineEdit_->selectAll();
}
void ProcessorTreeWidget::addSelectedProcessor() {
std::string id;
auto items = processorTree_->selectedItems();
if (items.size() > 0) {
id = items[0]->data(0, ProcessorTree::IDENTIFIER_ROLE).toString().toStdString();
} else {
auto count = processorTree_->topLevelItemCount();
if (count == 1) {
auto item = processorTree_->topLevelItem(0);
if (item->childCount() == 1) {
id = item->child(0)
->data(0, ProcessorTree::IDENTIFIER_ROLE)
.toString()
.toStdString();
}
}
}
if (!id.empty()) {
addProcessor(id);
processorTree_->clearSelection();
} else {
processorTree_->setFocus();
processorTree_->topLevelItem(0)->child(0)->setSelected(true);
}
}
void ProcessorTreeWidget::addProcessor(std::string className) {
try {
// create processor, add it to processor network, and generate it's widgets
auto network = InviwoApplication::getPtr()->getProcessorNetwork();
if (auto p = ProcessorFactory::getPtr()->create(className)) {
auto meta = p->getMetaData<ProcessorMetaData>(ProcessorMetaData::CLASS_IDENTIFIER);
auto pos = util::transform(network->getProcessors(), [](Processor* elem) {
return elem->getMetaData<ProcessorMetaData>(ProcessorMetaData::CLASS_IDENTIFIER)
->getPosition();
});
pos.push_back(ivec2(0, 0));
auto min = std::min_element(pos.begin(), pos.end(),
[](const ivec2& a, const ivec2& b) { return a.y > b.y; });
meta->setPosition(*min + ivec2(0, 75));
network->addProcessor(p.get());
network->autoLinkProcessor(p.get());
p.release();
}
} catch (Exception& exception) {
util::log(exception.getContext(),
"Unable to create processor " + className + " due to " + exception.getMessage(),
LogLevel::Error);
}
}
bool ProcessorTreeWidget::processorFits(ProcessorFactoryObject* processor, const QString& filter) {
return (
QString::fromStdString(processor->getDisplayName()).contains(filter, Qt::CaseInsensitive) ||
QString::fromStdString(processor->getClassIdentifier())
.contains(filter, Qt::CaseInsensitive) ||
QString::fromStdString(processor->getTags().getString())
.contains(filter, Qt::CaseInsensitive));
}
const QIcon* ProcessorTreeWidget::getCodeStateIcon(CodeState state) const {
switch (state) {
case CodeState::Stable:
return &iconStable_;
case CodeState::Broken:
return &iconBroken_;
case CodeState::Experimental:
default:
return &iconExperimental_;
}
}
QTreeWidgetItem* ProcessorTreeWidget::addToplevelItemTo(QString title) {
QTreeWidgetItem* newItem = new QTreeWidgetItem(QStringList(title));
processorTree_->addTopLevelItem(newItem);
processorTree_->setFirstItemColumnSpanned(newItem, true);
return newItem;
}
QTreeWidgetItem* ProcessorTreeWidget::addProcessorItemTo(QTreeWidgetItem* item,
ProcessorFactoryObject* processor,
std::string moduleId) {
QTreeWidgetItem* newItem = new QTreeWidgetItem();
newItem->setIcon(0, *getCodeStateIcon(processor->getCodeState()));
newItem->setText(0, QString::fromStdString(processor->getDisplayName()));
newItem->setText(1, QString::fromStdString(processor->getTags().getString() + " "));
newItem->setTextAlignment(1, Qt::AlignRight);
newItem->setData(0, ProcessorTree::IDENTIFIER_ROLE,
QString::fromStdString(processor->getClassIdentifier()));
ToolTipHelper t(processor->getDisplayName());
t.row("Module", moduleId);
t.row("Identifier", processor->getClassIdentifier());
t.row("Category", processor->getCategory());
t.row("Code", Processor::getCodeStateString(processor->getCodeState()));
t.row("Tags", processor->getTags().getString());
newItem->setToolTip(0, utilqt::toLocalQString(t));
QFont font = newItem->font(1);
font.setWeight(QFont::Bold);
newItem->setFont(1, font);
item->addChild(newItem);
if (processor->getTags().tags_.size() == 0) {
processorTree_->setFirstItemColumnSpanned(newItem, true);
}
return newItem;
}
void ProcessorTreeWidget::addProcessorsToTree() {
processorTree_->clear();
// add processors from all modules to the list
InviwoApplication* inviwoApp = InviwoApplication::getPtr();
if (listView_->currentIndex() == 2) {
addToplevelItemTo("Stable Processors");
addToplevelItemTo("Experimental Processors");
addToplevelItemTo("Broken Processors");
}
for (auto& elem : inviwoApp->getModules()) {
std::vector<ProcessorFactoryObject*> curProcessorList = elem->getProcessors();
QList<QTreeWidgetItem*> items;
for (auto& processor : curProcessorList) {
if (lineEdit_->text().isEmpty() || processorFits(processor, lineEdit_->text())) {
std::string categoryName;
switch (listView_->currentIndex()) {
case 0: // By Alphabet
categoryName = processor->getDisplayName().substr(0, 1);
break;
case 1: // By Category
categoryName = processor->getCategory();
break;
case 2: // By Code State
categoryName = Processor::getCodeStateString(processor->getCodeState());
break;
case 3: // By Module
categoryName = elem->getIdentifier();
break;
default:
categoryName = "Unkonwn";
}
QString category = QString::fromStdString(categoryName);
items = processorTree_->findItems(category, Qt::MatchFixedString, 0);
if (items.empty()) items.push_back(addToplevelItemTo(category));
addProcessorItemTo(items[0], processor, elem->getIdentifier());
}
}
}
// Apply sorting
switch (listView_->currentIndex()) {
case 2: { // By Code State
int i = 0;
while (i < processorTree_->topLevelItemCount()) {
QTreeWidgetItem* item = processorTree_->topLevelItem(i);
if (item->childCount() == 0) {
delete processorTree_->takeTopLevelItem(i);
} else {
item->sortChildren(0, Qt::AscendingOrder);
i++;
}
}
break;
}
default:
processorTree_->sortItems(0, Qt::AscendingOrder);
break;
}
processorTree_->expandAll();
processorTree_->resizeColumnToContents(1);
}
void ProcessorTreeWidget::currentItemChanged(QTreeWidgetItem* current, QTreeWidgetItem* previous) {
if (!current) return;
std::string classname =
current->data(0, ProcessorTree::IDENTIFIER_ROLE).toString().toUtf8().constData();
if (!classname.empty()) helpWidget_->showDocForClassName(classname);
}
static QString mimeType = "inviwo/ProcessorDragObject";
ProcessorDragObject::ProcessorDragObject(QWidget* source, const QString className) : QDrag(source) {
QByteArray byteData;
{
QDataStream ds(&byteData, QIODevice::WriteOnly);
ds << className;
}
QMimeData* mimeData = new QMimeData;
mimeData->setData(mimeType, byteData);
mimeData->setData("text/plain", className.toLatin1().data());
setMimeData(mimeData);
start(Qt::MoveAction);
}
bool ProcessorDragObject::canDecode(const QMimeData* mimeData) {
if (mimeData->hasFormat(mimeType))
return true;
else
return false;
}
bool ProcessorDragObject::decode(const QMimeData* mimeData, QString& className) {
QByteArray byteData = mimeData->data(mimeType);
if (byteData.isEmpty()) return false;
QDataStream ds(&byteData, QIODevice::ReadOnly);
ds >> className;
return true;
}
} // namespace<|endoftext|> |
<commit_before>#include <Rcpp.h>
/*
* Functionalities to speed up working with dependency parsing results
*/
std::vector<int> pluck_int(const Rcpp::List& x, const unsigned int& i) {
if(i >= x.size()){
Rcpp::Rcout << "Trying to extract list element " << i << "/" << x.size() << std::endl;
Rcpp::stop("This is not possible");
}
std::vector<int> rows = x[i-1];
return rows;
}
std::tuple<std::vector<int>, std::vector<int>, std::vector<unsigned int> > dependency_rowlocations_recursive(const unsigned int& row, const Rcpp::List& x, const int depth = 1) {
std::vector<int> newrows = pluck_int(x, row);
int n = newrows.size();
std::vector<int> newdepth;
std::vector<unsigned int> from;
for(int j = 0; j < n; j++){
newdepth.push_back(depth);
from.push_back(row);
}
for(int j = 0; j < n; j++){
std::tuple<std::vector<int>, std::vector<int>, std::vector<unsigned int> > extra = dependency_rowlocations_recursive(newrows[j], x, depth + 1);
int n_extra = std::get<0>(extra).size();
for(int k = 0; k < n_extra; k++){
newrows.push_back(std::get<0>(extra)[k]);
newdepth.push_back(std::get<1>(extra)[k]);
from.push_back(std::get<2>(extra)[k]);
}
}
return std::make_tuple(newrows, newdepth, from);
}
// [[Rcpp::export]]
Rcpp::List dependency_rowlocations(const unsigned int& row, const Rcpp::List& x, const int depth = 1){
std::tuple<std::vector<int>, std::vector<int>, std::vector<unsigned int> > info = dependency_rowlocations_recursive(row, x, depth);
Rcpp::List output = Rcpp::List::create(Rcpp::Named("row") = std::get<0>(info),
Rcpp::Named("depth") = std::get<1>(info),
Rcpp::Named("from") = std::get<2>(info));
return output;
}
<commit_msg>Make sure this does not happen<commit_after>#include <Rcpp.h>
/*
* Functionalities to speed up working with dependency parsing results
*/
std::vector<int> pluck_int(const Rcpp::List& x, const unsigned int& i) {
if(i > x.size() | i < 1){
Rcpp::Rcout << "Trying to extract list element " << i << " out of " << x.size() << std::endl;
Rcpp::stop("This is not possible");
}
std::vector<int> rows = x[i-1];
return rows;
}
std::tuple<std::vector<int>, std::vector<int>, std::vector<unsigned int> > dependency_rowlocations_recursive(const unsigned int& row, const Rcpp::List& x, const int depth = 1) {
std::vector<int> newrows = pluck_int(x, row);
int n = newrows.size();
std::vector<int> newdepth;
std::vector<unsigned int> from;
for(int j = 0; j < n; j++){
newdepth.push_back(depth);
from.push_back(row);
}
for(int j = 0; j < n; j++){
std::tuple<std::vector<int>, std::vector<int>, std::vector<unsigned int> > extra = dependency_rowlocations_recursive(newrows[j], x, depth + 1);
int n_extra = std::get<0>(extra).size();
for(int k = 0; k < n_extra; k++){
newrows.push_back(std::get<0>(extra)[k]);
newdepth.push_back(std::get<1>(extra)[k]);
from.push_back(std::get<2>(extra)[k]);
}
}
return std::make_tuple(newrows, newdepth, from);
}
// [[Rcpp::export]]
Rcpp::List dependency_rowlocations(const unsigned int& row, const Rcpp::List& x, const int depth = 1){
std::tuple<std::vector<int>, std::vector<int>, std::vector<unsigned int> > info = dependency_rowlocations_recursive(row, x, depth);
Rcpp::List output = Rcpp::List::create(Rcpp::Named("row") = std::get<0>(info),
Rcpp::Named("depth") = std::get<1>(info),
Rcpp::Named("from") = std::get<2>(info));
return output;
}
<|endoftext|> |
<commit_before>/********************************************************************************
File name: monster.cpp
Written by: Daniel Nguyen
Written on 08/27/2016
Purpose: This is a c++ file containing classes for all monsters
Class: CPSC 362
*********************************************************************************/
#include <sstream>
#include <string>
#include <cstdlib>
#include <ctime>
#include<iostream>
/*********************************************************************
This is the base class for all enemies. It include title, skills, hp,
exp. Item drops haven't been implemented.
*********************************************************************/
class Enemy{
protected:
std::string name;
int hp;
int exp;
int min_atk;
int max_atk;
std::string description;
public:
//Accessor functions for hp
void set_hp(int num){ hp = num;}
int get_hp(){return hp;}
//Accessor functions for exp
int get_exp(){return exp;}
//Accessor function for min_atk
void set_min_atk(int num){min_atk = num;}
//Accessor function for max_atk
void set_max_atk(int num){max_atk = num;}
//Function for attacks that randomize number between minimum atk and maximum atk
//The function also ouputs the attack command
int attack(){
//Use time function to get a "seed" value for srand
unsigned seed = time(0);
srand(seed);
//Generate and return a random number between min_atk and max_atk
int range = max_atk - min_atk;
int atk_damage = rand() % range + min_atk;
return atk_damage;
}
//Function that takes an int as argument and subtract it from the monster's hp
void take_damage(int damage){
hp = hp - damage;
}
//Stores length of name and name, hp, exp, min atk, max atk, length of description
//and description
void write_to_stream(std::ostream & str)
{
//Write length and data for name
int name_length = name.length();
str.write(reinterpret_cast<char *>(&name_length),sizeof(int));
str.write(name.data(), name_length);
//Write hp
str.write(reinterpret_cast<char *>(&hp),sizeof(hp));
//Write exp
str.write(reinterpret_cast<char *>(&exp),sizeof(exp));
//write min_atk
str.write(reinterpret_cast<char *>(&min_atk),sizeof(min_atk));
//write max atk
str.write(reinterpret_cast<char *>(&max_atk),sizeof(max_atk));
//write length and data for description
int description_length = description.length();
str.write(reinterpret_cast<char *>(&description_length),sizeof(int));
str.write(description.data(), description_length);
}
//Reads the data in the format written by Monster::pack
void read_to_file(std::istream & str)
{
const int BUFFER_SIZE = 256;
static char buffer[256];
//Getting name's length, read the data into a local buffer and assign to name
int name_length;
str.read(reinterpret_cast<char *>(&name_length),sizeof(int));
str.read(buffer, name_length);
buffer[name_length] = '\0';
name = buffer;
//Getting hp
str.read(reinterpret_cast<char *>(&hp),sizeof(hp));
//Getting exp
str.read(reinterpret_cast<char *> (&exp),sizeof(exp));
//Getting min_atk
str.read(reinterpret_cast<char *> (&min_atk),sizeof(min_atk));
//Getting max atk
str.read(reinterpret_cast<char *> (&max_atk),sizeof(max_atk));
//Getting description's length, read the data into a local buffer and assign
//to description
int description_length;
str.read(reinterpret_cast<char *>(&description_length),sizeof(int));
str.read(buffer, description_length);
buffer[description_length] = '\0';
description = buffer;
}
template<typename T> std::string convert_to_string(T data){
std::stringstream stream;
std::string str;
stream << data;
stream >> str;
str += '/';
return str;
}
std::string pack(){
std::string retVal = "";
//Add name and '/' following it to retVal string
retVal += name;
retVal += '/';
//Convert hp to string, add hp string and '/' to reVal
retVal+= convert_to_string(hp);
//Convert exp to string, add exp string and '/' to retVal
retVal += convert_to_string(exp);
//Convert min_atk to string, add min_atk string and '/' to retVal
retVal += convert_to_string(min_atk);
//Convert max_atk to string, add max_atk string and '/' to retVal
retVal += convert_to_string(max_atk);
//Add description to retVal string
retVal+= description;
retVal+='/';
return retVal;
}
void unpack(std::string str)
{
std::string token;
std::istringstream ss(str);
int mem_var = 1;
while(std::getline(ss, token, '/'))
{
std::istringstream stream(token);
switch(mem_var){
case 1:
stream >> name;
mem_var++;
break;
case 2:
stream >> hp;
mem_var++;
break;
case 3:
stream >> exp;
mem_var++;
break;
case 4:
stream >> min_atk;
mem_var++;
break;
case 5:
stream >> max_atk;
mem_var++;
break;
case 6:
stream >> description;
break;
}
}
}
};
/************************************************************************
The following classes contain information about different monster.
Again, skills haven't been implemented.
*************************************************************************/
class Hedgehog : public Enemy
{
public:
Hedgehog(){
this->name= "Hedgehog";
this->hp = 50;
this->exp = 2;
this->min_atk = 7;
this->max_atk = 10;
this->description = "Small, spiny monster that shoots spiens at enemies";
}
};
class Dead_Tree: public Enemy
{
public:
Dead_Tree(){
this->name = "Dead_Tree";
this->hp = 95;
this->exp = 5;
this->min_atk =9;
this->max_atk =12;
this->description = "A tree monster. The feature and sound that it makes "
"are incredibly eerie";
}
};
class Giant_Frog :public Enemy
{
public:
Giant_Frog(){
this->name = "Giant Frog";
this->hp = 133;
this->exp = 6;
this->min_atk = 11;
this->max_atk =14;
this->description="A mutant frog that is 5 times the size of normal frog."
" It makes annoying sounds.";
}
};
class Roach_Egg : public Enemy
{
public:
Roach_Egg(){
this->name = "Roach Egg";
this->hp = 48;
this->exp =8;
this->min_atk = 0;
this->max_atk = 0;
this->description="It hatches into several Roaches It makes "
"horrible omelette.";
}
};
class CockRoach : public Enemy
{
public:
CockRoach(){
this->name = "Cockroach";
this->hp=126;
this->exp = 17;
this->min_atk = 18;
this->max_atk =24;
this->description="Dirty, filthy creatures that tend to work in swarms.";
}
};
class Skeleton : public Enemy
{
public:
Skeleton(){
this->name = "Skeleton";
this->hp = 234;
this->exp =18;
this->min_atk = 39;
this->max_atk = 47;
this->description="A skeleton of a dead person who had died holding "
"a grudge. It's undead so of course it hates living things.";
}
};
class Violinist : public Enemy
{
public:
Violinist(){
this->name = "Violinist";
this->hp =198;
this->exp =20;
this->min_atk = 24;
this->max_atk = 29;
this->description = "A long-horned grass hopper of a romantic turn of mind,"
" that always play a violin. Most consider him as the main "
"culprit for noise.";
}
};
class GruBat: public Enemy
{
public:
GruBat(){
this->name="GruBat";
this->hp=155;
this->exp =28;
this->min_atk = 20;
this->max_atk = 28;
this->description = "A gray bat that's not very strong, but annoying because"
" it attacks very fast and relentlessly pursuits passerby";
}
};
class Arthropod : public Enemy
{
public:
Arthropod(){
this->name="Arthropod";
this->hp = 507;
this->exp =38;
this->min_atk = 28;
this->max_atk = 37;
this->description = "Kukre is a small bug living near the beach.";
}
};
class Zombie : public Enemy
{
public:
Zombie(){
this->name="Zombie";
this->hp = 534;
this->exp =50;
this->min_atk = 67;
this->max_atk = 79;
this->description = "A walking curse which has been cursed by an evil shaman."
" Beware of its poisonous breath.";
}
};
class Roddent_Tail : public Enemy
{
public:
Roddent_Tail(){
this->name ="Roddent Tail";
this->hp = 426;
this->exp =59;
this->min_atk = 42;
this->max_atk = 51;
this->description = "A roddent that uses whipping attacks with a "
"tail that looks like a blade of grass.";
}
};
class Poison_Hedgehog : public Enemy
{
public:
Poison_Hedgehog(){
this->name = "Poison Hedgehog";
this->hp = 344;
this->exp =81;
this->min_atk = 59;
this->max_atk = 72;
this->description = "A kind of Hedgehog living in the swarm. It is covered "
"with poisonous elastic skins all around the body.";
}
};
class Steel_Fly : public Enemy
{
public:
Steel_Fly(){
this->name="Steel Fly";
this->hp = 530;
this->exp =109;
this->min_atk = 54;
this->max_atk = 65;
this->description = "A kind of fly that has a firm shell covering its body.";
}
};
class Crazy_Squirrel : public Enemy
{
public:
Crazy_Squirrel(){
this->name="Crazy Squrirrel";
this->hp = 817;
this->exp =120;
this->min_atk = 56;
this->max_atk = 67;
this->description = "A small squirrel that is not that strong but very fast."
" It has dark piercing eyes and is always holding an Acorn.";
}
};
class Horn : public Enemy
{
public:
Horn(){
this->name="Horn";
this->hp = 659;
this->exp =134;
this->min_atk = 58;
this->max_atk = 69;
this->description = "A giant ground beetle that never cares about things"
" going around except its business. When it's threatened, it uses sciccor-like"
" mandibles to attack enemies.";
}
};
class Fire_Ant : public Enemy
{
public:
Fire_Ant(){
this->name="Fire Ant";
this->hp = 760;
this->exp =135;
this->min_atk = 68;
this->max_atk = 79;
this->description = "A kind of ant of red color. They live in group and are "
"very cooperative to attack.";
}
};
int main(){
Horn newHorn;
std::string testString = newHorn.pack();
std::cout << testString << std::endl;
std::string testInput= "ahah/23/34/45/65/I am crazy.";
newHorn.unpack(testInput);
std::cout << newHorn.get_exp() << " " << newHorn.get_hp() << std::endl;
}
<commit_msg>adding some comments<commit_after>/********************************************************************************
File name: monster.cpp
Written by: Daniel Nguyen
Written on 08/27/2016
Purpose: This is a c++ file containing classes for all monsters
Class: CPSC 362
*********************************************************************************/
#include <sstream>
#include <string>
#include <cstdlib>
#include <ctime>
#include<iostream>
/*********************************************************************
This is the base class for all enemies. It include title, skills, hp,
exp. Item drops haven't been implemented.
*********************************************************************/
class Enemy{
protected:
std::string name;
int hp;
int exp;
int min_atk;
int max_atk;
std::string description;
public:
//Accessor functions for hp
void set_hp(int num){ hp = num;}
int get_hp(){return hp;}
//Accessor functions for exp
int get_exp(){return exp;}
//Accessor function for min_atk
void set_min_atk(int num){min_atk = num;}
//Accessor function for max_atk
void set_max_atk(int num){max_atk = num;}
//Function for attacks that randomize number between minimum atk and maximum atk
//The function also ouputs the attack command
int attack(){
//Use time function to get a "seed" value for srand
unsigned seed = time(0);
srand(seed);
//Generate and return a random number between min_atk and max_atk
int range = max_atk - min_atk;
int atk_damage = rand() % range + min_atk;
return atk_damage;
}
//Function that takes an int as argument and subtract it from the monster's hp
void take_damage(int damage){
hp = hp - damage;
}
//Stores length of name and name, hp, exp, min atk, max atk, length of description
//and description
void write_to_stream(std::ostream & str)
{
//Write length and data for name
int name_length = name.length();
str.write(reinterpret_cast<char *>(&name_length),sizeof(int));
str.write(name.data(), name_length);
//Write hp
str.write(reinterpret_cast<char *>(&hp),sizeof(hp));
//Write exp
str.write(reinterpret_cast<char *>(&exp),sizeof(exp));
//write min_atk
str.write(reinterpret_cast<char *>(&min_atk),sizeof(min_atk));
//write max atk
str.write(reinterpret_cast<char *>(&max_atk),sizeof(max_atk));
//write length and data for description
int description_length = description.length();
str.write(reinterpret_cast<char *>(&description_length),sizeof(int));
str.write(description.data(), description_length);
}
//Reads the data in the format written by Monster::pack
void read_from_file(std::istream & str)
{
const int BUFFER_SIZE = 256;
static char buffer[256];
//Getting name's length, read the data into a local buffer and assign to name
int name_length;
str.read(reinterpret_cast<char *>(&name_length),sizeof(int));
str.read(buffer, name_length);
buffer[name_length] = '\0';
name = buffer;
//Getting hp
str.read(reinterpret_cast<char *>(&hp),sizeof(hp));
//Getting exp
str.read(reinterpret_cast<char *> (&exp),sizeof(exp));
//Getting min_atk
str.read(reinterpret_cast<char *> (&min_atk),sizeof(min_atk));
//Getting max atk
str.read(reinterpret_cast<char *> (&max_atk),sizeof(max_atk));
//Getting description's length, read the data into a local buffer and assign
//to description
int description_length;
str.read(reinterpret_cast<char *>(&description_length),sizeof(int));
str.read(buffer, description_length);
buffer[description_length] = '\0';
description = buffer;
}
//This function converts a template data type to a string and add
//a '/' to end of string as delimiter.
template<typename T> std::string convert_to_string(T data){
std::stringstream stream;
std::string str;
stream << data;
stream >> str;
str += '/';
return str;
}
//Pack() function packs every single member variable using the
//convert_to_string function and return a string containing all
//the stats
std::string pack(){
std::string retVal = "";
//Add name and '/' following it to retVal string
retVal += name;
retVal += '/';
//Convert hp to string, add hp string and '/' to reVal
retVal+= convert_to_string(hp);
//Convert exp to string, add exp string and '/' to retVal
retVal += convert_to_string(exp);
//Convert min_atk to string, add min_atk string and '/' to retVal
retVal += convert_to_string(min_atk);
//Convert max_atk to string, add max_atk string and '/' to retVal
retVal += convert_to_string(max_atk);
//Add description to retVal string
retVal+= description;
retVal+='/';
return retVal;
}
//Unpack() function converts str to corresponding data type. It uses mem_var
//as a counter in the switch statemen
void unpack(std::string str)
{
std::string token;
std::istringstream ss(str);
int mem_var = 1;
while(std::getline(ss, token, '/'))
{
std::istringstream stream(token);
switch(mem_var){
case 1:
stream >> name;
mem_var++;
break;
case 2:
stream >> hp;
mem_var++;
break;
case 3:
stream >> exp;
mem_var++;
break;
case 4:
stream >> min_atk;
mem_var++;
break;
case 5:
stream >> max_atk;
mem_var++;
break;
case 6:
stream >> description;
break;
}
}
}
};
/************************************************************************
The following classes contain information about different monster.
Again, skills haven't been implemented.
*************************************************************************/
class Hedgehog : public Enemy
{
public:
Hedgehog(){
this->name= "Hedgehog";
this->hp = 50;
this->exp = 2;
this->min_atk = 7;
this->max_atk = 10;
this->description = "Small, spiny monster that shoots spiens at enemies";
}
};
class Dead_Tree: public Enemy
{
public:
Dead_Tree(){
this->name = "Dead_Tree";
this->hp = 95;
this->exp = 5;
this->min_atk =9;
this->max_atk =12;
this->description = "A tree monster. The feature and sound that it makes "
"are incredibly eerie";
}
};
class Giant_Frog :public Enemy
{
public:
Giant_Frog(){
this->name = "Giant Frog";
this->hp = 133;
this->exp = 6;
this->min_atk = 11;
this->max_atk =14;
this->description="A mutant frog that is 5 times the size of normal frog."
" It makes annoying sounds.";
}
};
class Roach_Egg : public Enemy
{
public:
Roach_Egg(){
this->name = "Roach Egg";
this->hp = 48;
this->exp =8;
this->min_atk = 0;
this->max_atk = 0;
this->description="It hatches into several Roaches It makes "
"horrible omelette.";
}
};
class CockRoach : public Enemy
{
public:
CockRoach(){
this->name = "Cockroach";
this->hp=126;
this->exp = 17;
this->min_atk = 18;
this->max_atk =24;
this->description="Dirty, filthy creatures that tend to work in swarms.";
}
};
class Skeleton : public Enemy
{
public:
Skeleton(){
this->name = "Skeleton";
this->hp = 234;
this->exp =18;
this->min_atk = 39;
this->max_atk = 47;
this->description="A skeleton of a dead person who had died holding "
"a grudge. It's undead so of course it hates living things.";
}
};
class Violinist : public Enemy
{
public:
Violinist(){
this->name = "Violinist";
this->hp =198;
this->exp =20;
this->min_atk = 24;
this->max_atk = 29;
this->description = "A long-horned grass hopper of a romantic turn of mind,"
" that always play a violin. Most consider him as the main "
"culprit for noise.";
}
};
class GruBat: public Enemy
{
public:
GruBat(){
this->name="GruBat";
this->hp=155;
this->exp =28;
this->min_atk = 20;
this->max_atk = 28;
this->description = "A gray bat that's not very strong, but annoying because"
" it attacks very fast and relentlessly pursuits passerby";
}
};
class Arthropod : public Enemy
{
public:
Arthropod(){
this->name="Arthropod";
this->hp = 507;
this->exp =38;
this->min_atk = 28;
this->max_atk = 37;
this->description = "Kukre is a small bug living near the beach.";
}
};
class Zombie : public Enemy
{
public:
Zombie(){
this->name="Zombie";
this->hp = 534;
this->exp =50;
this->min_atk = 67;
this->max_atk = 79;
this->description = "A walking curse which has been cursed by an evil shaman."
" Beware of its poisonous breath.";
}
};
class Roddent_Tail : public Enemy
{
public:
Roddent_Tail(){
this->name ="Roddent Tail";
this->hp = 426;
this->exp =59;
this->min_atk = 42;
this->max_atk = 51;
this->description = "A roddent that uses whipping attacks with a "
"tail that looks like a blade of grass.";
}
};
class Poison_Hedgehog : public Enemy
{
public:
Poison_Hedgehog(){
this->name = "Poison Hedgehog";
this->hp = 344;
this->exp =81;
this->min_atk = 59;
this->max_atk = 72;
this->description = "A kind of Hedgehog living in the swarm. It is covered "
"with poisonous elastic skins all around the body.";
}
};
class Steel_Fly : public Enemy
{
public:
Steel_Fly(){
this->name="Steel Fly";
this->hp = 530;
this->exp =109;
this->min_atk = 54;
this->max_atk = 65;
this->description = "A kind of fly that has a firm shell covering its body.";
}
};
class Crazy_Squirrel : public Enemy
{
public:
Crazy_Squirrel(){
this->name="Crazy Squrirrel";
this->hp = 817;
this->exp =120;
this->min_atk = 56;
this->max_atk = 67;
this->description = "A small squirrel that is not that strong but very fast."
" It has dark piercing eyes and is always holding an Acorn.";
}
};
class Horn : public Enemy
{
public:
Horn(){
this->name="Horn";
this->hp = 659;
this->exp =134;
this->min_atk = 58;
this->max_atk = 69;
this->description = "A giant ground beetle that never cares about things"
" going around except its business. When it's threatened, it uses sciccor-like"
" mandibles to attack enemies.";
}
};
class Fire_Ant : public Enemy
{
public:
Fire_Ant(){
this->name="Fire Ant";
this->hp = 760;
this->exp =135;
this->min_atk = 68;
this->max_atk = 79;
this->description = "A kind of ant of red color. They live in group and are "
"very cooperative to attack.";
}
};
int main(){
Horn newHorn;
std::string testString = newHorn.pack();
std::cout << testString << std::endl;
std::string testInput= "ahah/23/34/45/65/I am crazy.";
newHorn.unpack(testInput);
std::cout << newHorn.get_exp() << " " << newHorn.get_hp() << std::endl;
}
<|endoftext|> |
<commit_before><commit_msg>fix namespace<commit_after><|endoftext|> |
<commit_before>///
/// @file C1.cpp
/// @brief Simple demonstration implementation of the C(x, y) formula
/// in Xavier Gourdon's prime counting algorithm. This
/// implementation uses O(x^(1/2)) memory instead of O(x^(1/3))
/// in order to simplify the implementation.
///
/// Currently this implementation is quite slow when compared
/// to Xavier Gourdon's fastpix11.exe binary. This
/// implementation is slow mainly because it iterates over all
/// integers and for each integer checks whether it is coprime
/// to the first b primes. It is possible to iterate only over
/// the square free integers which are coprime to the first b
/// primes which is obviously much faster (see C2.cpp).
///
/// Copyright (C) 2019 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <PiTable.hpp>
#include <primecount-internal.hpp>
#include <fast_div.hpp>
#include <generate.hpp>
#include <int128_t.hpp>
#include <min.hpp>
#include <imath.hpp>
#include <print.hpp>
#include <S2Status.hpp>
#include <stdint.h>
#include <vector>
using namespace std;
using namespace primecount;
namespace {
template <typename T, typename Primes>
T C_OpenMP(T x,
int64_t y,
int64_t z,
int64_t k,
Primes& primes,
int threads)
{
T sum = 0;
int64_t x_star = get_x_star_gourdon(x, y);
int64_t thread_threshold = 1000;
threads = ideal_num_threads(threads, x_star, thread_threshold);
PiTable pi(isqrt(x));
int64_t pi_x_star = pi[x_star];
S2Status status(x);
auto mu = generate_moebius(z);
auto lpf = generate_lpf(z);
auto mpf = generate_mpf(z);
#pragma omp parallel for schedule(dynamic) num_threads(threads) reduction(-: sum)
for (int64_t b = k + 1; b <= pi_x_star; b++)
{
int64_t prime = primes[b];
T xp = x / prime;
int64_t m = min(xp / prime, z);
int64_t min_m = max(x / ipow<T>(prime, 3), z / prime);
for (; m > min_m; m--)
{
if (lpf[m] > prime &&
mpf[m] <= y)
{
int64_t xpm = fast_div64(xp, m);
sum -= mu[m] * (pi[xpm] - b + 2);
}
}
if (is_print())
status.print(b, pi_x_star);
}
return sum;
}
} // namespace
namespace primecount {
int64_t C(int64_t x,
int64_t y,
int64_t z,
int64_t k,
int threads)
{
print("");
print("=== C(x, y) ===");
print(x, y, z, k, threads);
double time = get_time();
auto primes = generate_primes<int32_t>(y);
int64_t c = C_OpenMP((intfast64_t) x, y, z, k, primes, threads);
print("C", c, time);
return c;
}
#ifdef HAVE_INT128_T
int128_t C(int128_t x,
int64_t y,
int64_t z,
int64_t k,
int threads)
{
print("");
print("=== C(x, y) ===");
print(x, y, z, k, threads);
double time = get_time();
int128_t c;
// uses less memory
if (y <= numeric_limits<uint32_t>::max())
{
auto primes = generate_primes<uint32_t>(y);
c = C_OpenMP((intfast128_t) x, y, z, k, primes, threads);
}
else
{
auto primes = generate_primes<int64_t>(y);
c = C_OpenMP((intfast128_t) x, y, z, k, primes, threads);
}
print("C", c, time);
return c;
}
#endif
} // namespace
<commit_msg>Fix 128-bit issue<commit_after>///
/// @file C1.cpp
/// @brief Simple demonstration implementation of the C(x, y) formula
/// in Xavier Gourdon's prime counting algorithm. This
/// implementation uses O(x^(1/2)) memory instead of O(x^(1/3))
/// in order to simplify the implementation.
///
/// Currently this implementation is quite slow when compared
/// to Xavier Gourdon's fastpix11.exe binary. This
/// implementation is slow mainly because it iterates over all
/// integers and for each integer checks whether it is coprime
/// to the first b primes. It is possible to iterate only over
/// the square free integers which are coprime to the first b
/// primes which is obviously much faster (see C2.cpp).
///
/// Copyright (C) 2019 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <PiTable.hpp>
#include <primecount-internal.hpp>
#include <fast_div.hpp>
#include <generate.hpp>
#include <int128_t.hpp>
#include <min.hpp>
#include <imath.hpp>
#include <print.hpp>
#include <S2Status.hpp>
#include <stdint.h>
#include <vector>
using namespace std;
using namespace primecount;
namespace {
template <typename T, typename Primes>
T C_OpenMP(T x,
int64_t y,
int64_t z,
int64_t k,
Primes& primes,
int threads)
{
T sum = 0;
int64_t x_star = get_x_star_gourdon(x, y);
int64_t thread_threshold = 1000;
threads = ideal_num_threads(threads, x_star, thread_threshold);
PiTable pi(isqrt(x));
int64_t pi_x_star = pi[x_star];
S2Status status(x);
auto mu = generate_moebius(z);
auto lpf = generate_lpf(z);
auto mpf = generate_mpf(z);
#pragma omp parallel for schedule(dynamic) num_threads(threads) reduction(-: sum)
for (int64_t b = k + 1; b <= pi_x_star; b++)
{
int64_t prime = primes[b];
T xp = x / prime;
int64_t m = min(xp / prime, z);
T min_m = max(x / ipow<T>(prime, 3), z / prime);
for (; m > min_m; m--)
{
if (lpf[m] > prime &&
mpf[m] <= y)
{
int64_t xpm = fast_div64(xp, m);
sum -= mu[m] * (pi[xpm] - b + 2);
}
}
if (is_print())
status.print(b, pi_x_star);
}
return sum;
}
} // namespace
namespace primecount {
int64_t C(int64_t x,
int64_t y,
int64_t z,
int64_t k,
int threads)
{
print("");
print("=== C(x, y) ===");
print(x, y, z, k, threads);
double time = get_time();
auto primes = generate_primes<int32_t>(y);
int64_t c = C_OpenMP((intfast64_t) x, y, z, k, primes, threads);
print("C", c, time);
return c;
}
#ifdef HAVE_INT128_T
int128_t C(int128_t x,
int64_t y,
int64_t z,
int64_t k,
int threads)
{
print("");
print("=== C(x, y) ===");
print(x, y, z, k, threads);
double time = get_time();
int128_t c;
// uses less memory
if (y <= numeric_limits<uint32_t>::max())
{
auto primes = generate_primes<uint32_t>(y);
c = C_OpenMP((intfast128_t) x, y, z, k, primes, threads);
}
else
{
auto primes = generate_primes<int64_t>(y);
c = C_OpenMP((intfast128_t) x, y, z, k, primes, threads);
}
print("C", c, time);
return c;
}
#endif
} // namespace
<|endoftext|> |
<commit_before>#include "EntityFactory.h"
namespace ros2_components
{
QHash<QString, const QMetaObject*> EntityFactory::metaObjs;
EntityFactory::EntityFactory(QObject *parent) : QObject(parent)
{
}
void EntityFactory::AddQObject(QObject *obj)
{
EntityFactory::metaObjs.insert(obj->metaObject()->className(), obj->metaObject());
}
std::shared_ptr<EntityBase> EntityFactory::CreateInstanceFromName(string className,QGenericArgument arg1, QGenericArgument arg2, QGenericArgument arg3)
{
if(!metaObjs.keys().contains(QString::fromStdString(className)))
throw std::runtime_error("Class with name: " +className+" not registered");
const QMetaObject *meta = metaObjs[QString::fromStdString(className)];
std::cout << "Class name from staticMetaObject: " << meta->className() << std::endl;
std::cout << meta->constructor(0).methodSignature().toStdString() << std::endl;
QObject *o = meta->newInstance(arg1,arg2,arg3);
EntityBase* ptr = dynamic_cast<EntityBase*>(o);
if(ptr == NULL)
throw std::runtime_error("Could not cast QObject* to EntityBase* - The EntityFactory is for Entities only");
std::shared_ptr<EntityBase> sptr(ptr);
return sptr;
}
std::shared_ptr<QMetaObject> EntityFactory::GetQMetaObject(string className)
{
if(!metaObjs.keys().contains(QString::fromStdString(className)))
throw std::runtime_error("Class with name: " +className+" not registered");
const QMetaObject *meta = metaObjs[QString::fromStdString(className)];
std::cout << "Class name from staticMetaObject: " << meta->className() << std::endl;
return std::shared_ptr<QMetaObject>(const_cast<QMetaObject*>(meta));
}
}
<commit_msg>removed one debug line that cause trouble with older qt installations<commit_after>#include "EntityFactory.h"
namespace ros2_components
{
QHash<QString, const QMetaObject*> EntityFactory::metaObjs;
EntityFactory::EntityFactory(QObject *parent) : QObject(parent)
{
}
void EntityFactory::AddQObject(QObject *obj)
{
EntityFactory::metaObjs.insert(obj->metaObject()->className(), obj->metaObject());
}
std::shared_ptr<EntityBase> EntityFactory::CreateInstanceFromName(string className,QGenericArgument arg1, QGenericArgument arg2, QGenericArgument arg3)
{
if(!metaObjs.keys().contains(QString::fromStdString(className)))
throw std::runtime_error("Class with name: " +className+" not registered");
const QMetaObject *meta = metaObjs[QString::fromStdString(className)];
std::cout << "Class name from staticMetaObject: " << meta->className() << std::endl;
//std::cout << meta->constructor(0).methodSignature().toStdString() << std::endl;
QObject *o = meta->newInstance(arg1,arg2,arg3);
EntityBase* ptr = dynamic_cast<EntityBase*>(o);
if(ptr == NULL)
throw std::runtime_error("Could not cast QObject* to EntityBase* - The EntityFactory is for Entities only");
std::shared_ptr<EntityBase> sptr(ptr);
return sptr;
}
std::shared_ptr<QMetaObject> EntityFactory::GetQMetaObject(string className)
{
if(!metaObjs.keys().contains(QString::fromStdString(className)))
throw std::runtime_error("Class with name: " +className+" not registered");
const QMetaObject *meta = metaObjs[QString::fromStdString(className)];
std::cout << "Class name from staticMetaObject: " << meta->className() << std::endl;
return std::shared_ptr<QMetaObject>(const_cast<QMetaObject*>(meta));
}
}
<|endoftext|> |
<commit_before>//
// File: csg_update.cc
// Author: ruehle
//
// Created on June 11, 2008, 10:31 AM
//
/// this is the most dirtyest program, clean it up, don't copy anything from here!!!
#define kB 8.3109*0.01
#include <math.h>
#include <iostream>
#include <fstream>
#include <string>
#include <boost/program_options.hpp>
#include <tools/table.h>
using namespace std;
namespace po = boost::program_options;
int DoIBM(const string &in, const string &out, const string &target, const string ¤t, double T, double scale);
int main(int argc, char** argv)
{
string method, type;
string action;
string in, out;
string target, current;
double T, scale;
// lets read in some program options
// Declare the supported options.
po::options_description desc("Allowed options");
desc.add_options()
("help", "produce this help message")
//("version", "show version info")
("in", boost::program_options::value<string>(&in), "file containing current potential")
("out", boost::program_options::value<string>(&out)->default_value("out.dat"), "file to write the new potential")
("cur", boost::program_options::value<string>(¤t), "file containing current rdf")
("target", boost::program_options::value<string>(&target), "file containing target rdf")
("action", boost::program_options::value<string>(&action)->default_value("ibm"), "ibm (to do: smooth, imc,...)")
("T", boost::program_options::value<double>(&T)->default_value(300.), "temperature");
("scale", boost::program_options::value<double>(&scale)->default_value(1.), "correction scaling");
// ("type", boost::program_options::value<string>()->default_value("nb"), "nb, bond, ang, dih")
;
// now read in the command line
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm);
// does the user want help?
if (vm.count("help")) {
cout << "csg_update \n\n";
cout << desc << endl;
return 0;
}
if(action == "ibm") {
return DoIBM(in, out, target, current, T, scale);
}
else
cerr << "unknown action\n";
return -1;
}
// do inverse boltzmann
int DoIBM(const string &in, const string &out, const string &target_dist, const string ¤t, double T, double scale)
{
Table target;
Table pout;
//
if(target_dist=="") {
cerr << "error, not target given for iterative inverse boltzmann";
return -1;
}
target.Load(target_dist);
// if no input potential is given, do initial guess
if(in=="") {
pout.resize(target.size());
pout.x() = target.x();
pout.flags() = ub::scalar_vector<unsigned short>(target.size(), 0);
for(int i=0; i<pout.size(); ++i) {
if(target.y(i) == 0) {
pout.y(i) = 0;
pout.flags(i) |= TBL_INVALID;
}
else
pout.y(i) = -kB*T*log(target.y(i));
}
}
// otherwise do ibm update
else {
Table pin;
if(current == "") {
cerr << "error, give current distribution";
return -1;
}
// read in the current potential
pin.Load(in);
// read the current distribution
Table cur;
cur.Load(current);
pout = pin;
for(int i=0; i<pout.size(); ++i) {
if(target.y(i) == 0 || cur.y(i) == 0) {
pout.y(i) = 0;
pout.flags(i) |= TBL_INVALID;
}
else
pout.y(i) += -kB*T*log(cur.y(i) / target.y(i));
}
}
pout.Save(out);
// should not get here
return 0;
}
<commit_msg>added Nsmooth option<commit_after>//
// File: csg_update.cc
// Author: ruehle
//
// Created on June 11, 2008, 10:31 AM
//
/// this is the most dirtyest program, clean it up, don't copy anything from here!!!
#define kB 8.3109*0.01
#include <math.h>
#include <iostream>
#include <fstream>
#include <string>
#include <boost/program_options.hpp>
#include <tools/table.h>
using namespace std;
namespace po = boost::program_options;
int DoIBM(const string &in, const string &out, const string &target, const string ¤t, double T, double scalem, int Nsmooth);
int main(int argc, char** argv)
{
string method, type;
string action;
string in, out;
string target, current;
int Nsmooth;
double T, scale;
// lets read in some program options
// Declare the supported options.
po::options_description desc("Allowed options");
desc.add_options()
("help", "produce this help message")
//("version", "show version info")
("in", boost::program_options::value<string>(&in), "file containing current potential")
("out", boost::program_options::value<string>(&out)->default_value("out.dat"), "file to write the new potential")
("cur", boost::program_options::value<string>(¤t), "file containing current rdf")
("target", boost::program_options::value<string>(&target), "file containing target rdf")
("action", boost::program_options::value<string>(&action)->default_value("ibm"), "ibm (to do: smooth, imc,...)")
("T", boost::program_options::value<double>(&T)->default_value(300.), "temperature")
("scale", boost::program_options::value<double>(&scale)->default_value(1.), "correction scaling")
("Nsmooth", boost::program_options::value<int>(&Nsmooth)->default_value(0), "smooth Nsmooth times before writing table")
//("type", boost::program_options::value<string>()->default_value("nb"), "nb, bond, ang, dih")
;
// now read in the command line
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm);
// does the user want help?
if (vm.count("help")) {
cout << "csg_update \n\n";
cout << desc << endl;
return 0;
}
if(action == "ibm") {
return DoIBM(in, out, target, current, T, scale, Nsmooth);
}
else
cerr << "unknown action\n";
return -1;
}
// do inverse boltzmann
int DoIBM(const string &in, const string &out, const string &target_dist, const string ¤t, double T, double scale, int Nsmooth)
{
Table target;
Table pout;
//
if(target_dist=="") {
cerr << "error, not target given for iterative inverse boltzmann";
return -1;
}
target.Load(target_dist);
// if no input potential is given, do initial guess
if(in=="") {
pout.resize(target.size());
pout.x() = target.x();
pout.flags() = ub::scalar_vector<unsigned short>(target.size(), 0);
for(int i=0; i<pout.size(); ++i) {
if(target.y(i) == 0) {
pout.y(i) = 0;
pout.flags(i) |= TBL_INVALID;
}
else
pout.y(i) = -kB*T*log(target.y(i));
}
}
// otherwise do ibm update
else {
Table pin;
if(current == "") {
cerr << "error, give current distribution";
return -1;
}
// read in the current potential
pin.Load(in);
// read the current distribution
Table cur;
cur.Load(current);
pout = pin;
for(int i=0; i<pout.size(); ++i) {
if(target.y(i) == 0 || cur.y(i) == 0) {
pout.y(i) = 0;
pout.flags(i) |= TBL_INVALID;
}
else
pout.y(i) += -kB*T*log(cur.y(i) / target.y(i));
}
}
pout.Smooth(Nsmooth);
pout.Save(out);
// should not get here
return 0;
}
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/*
* This file is part of the libone project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include <cstring>
#include <iostream>
#include <iomanip>
#include <libone/libone.h>
#include "FileNodeList.h"
#include "libone_utils.h"
#include "libone_types.h"
namespace libone {
FileNodeList::FileNodeList(uint64_t new_location, uint64_t new_size) {
location = new_location;
size = new_size;
}
void FileNodeList::parse_header(librevenge::RVNGInputStream *input) {
uint32_t expected_fragment_sequence;
bool found = false;
// ONE_DEBUG_MSG(("fragment position begin ")) << std::hex << input->tell() << '\n';
next_fragment_location = input->tell() + size - 8 - 12;
// ONE_DEBUG_MSG(("\n"));
uintMagic = readU64 (input, false);
if (uintMagic != 0xa4567ab1f5f7f4c4) {
ONE_DEBUG_MSG(("uintMagic not correct; position %ld\n", input->tell()));
end = true;
}
FileNodeListID = readU32 (input, false);/*
for (auto i: Transactions) {
if (i.first == FileNodeListID) {
list_length = i.second;*/
// ONE_DEBUG_MSG((" from transactions\n"));
/* found = true;
break;
}
}*/
if (!found) {
ONE_DEBUG_MSG(("length not found for list %d\n", FileNodeListID));
}
expected_fragment_sequence = readU32 (input, false);
if (expected_fragment_sequence != nFragmentSequence) {
ONE_DEBUG_MSG(("expected fragment %d, got %d\n", nFragmentSequence, expected_fragment_sequence));
}
else nFragmentSequence++;
// ONE_DEBUG_MSG((" nFragmentSequence ")) << nFragmentSequence << '\n';
}
std::string FileNodeList::to_string() {
std::stringstream stream;
stream << std::hex << "uintMagic " << uintMagic << '\n';
stream << std::dec << "FileNodeListID " << FileNodeListID << '\n';
stream << "nFragmentSequence " << nFragmentSequence << '\n';
for (FileNode i: rgFileNodes)
stream << i.to_string() << '\n';
return stream.str();
}
FileNode FileNodeList::get_next_node(librevenge::RVNGInputStream *input) {
bool next_fragment_wanted = false;
FileChunkReference next_fragment = FileChunkReference(FileChunkReferenceSize::Size64x32);
FileNode node;
if (!header_parsed) {
parse_header(input);
header_parsed = true;
}
// ONE_DEBUG_MSG((node.to_string));
if ((input->tell() >= next_fragment_location) || (next_fragment_location - input->tell() <= 4)) {
ONE_DEBUG_MSG(("wanting next fragment\n"));
next_fragment_wanted = true;
}
if (!next_fragment_wanted) {
node.parse(input);
if (node.get_FileNodeID() == FileNode::ChunkTerminatorFND)
next_fragment_wanted = true;
else
elements_parsed++;
}
if (next_fragment_wanted) {
input->seek(next_fragment_location, librevenge::RVNG_SEEK_SET);
next_fragment.parse(input);
if (readU64(input, false) != 0x8BC215C38233BA4B) {
FileNode zero;
ONE_DEBUG_MSG(("footer not correct, position %ld\n", input->tell()));
end = true;
zero.zero();
return zero;
}
if (next_fragment.is_fcrNil()) end = true;
else {
location = next_fragment.get_location();
size = next_fragment.get_size();
input->seek(location, librevenge::RVNG_SEEK_SET);
ONE_DEBUG_MSG(("what's up in here? %ld\n", input->tell()));
parse_header(input);
node.parse(input);
elements_parsed++;
}
next_fragment_wanted = false;
}
if (node.get_FileNodeID() == FileNode::DUNNO)
end = true;
if (elements_parsed == list_length) {
end = true;
ONE_DEBUG_MSG(("got to list length %d, parsed %d\n", list_length, elements_parsed));
} else {
ONE_DEBUG_MSG(("list id %d, element %d, length %d, position %ld, next fragment@%ld\n", FileNodeListID, elements_parsed, list_length, input->tell(), next_fragment_location));
}
return node;
}
FileNode FileNodeList::force_get_next_node(librevenge::RVNGInputStream *input) {
FileNode node = force_get_next_node(input);
end = false;
return node;
}
bool FileNodeList::is_end() {
return end;
}
}
<commit_msg>FileNodeList: throw in another two asserts<commit_after>/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/*
* This file is part of the libone project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include <cstring>
#include <iostream>
#include <iomanip>
#include <libone/libone.h>
#include "FileNodeList.h"
#include "libone_utils.h"
#include "libone_types.h"
namespace libone {
FileNodeList::FileNodeList(uint64_t new_location, uint64_t new_size) {
location = new_location;
size = new_size;
}
void FileNodeList::parse_header(librevenge::RVNGInputStream *input) {
uint32_t expected_fragment_sequence;
bool found = false;
// ONE_DEBUG_MSG(("fragment position begin ")) << std::hex << input->tell() << '\n';
next_fragment_location = input->tell() + size - 8 - 12;
// ONE_DEBUG_MSG(("\n"));
uintMagic = readU64 (input, false);
assert(uintMagic == 0xa4567ab1f5f7f4c4);
FileNodeListID = readU32 (input, false);/*
for (auto i: Transactions) {
if (i.first == FileNodeListID) {
list_length = i.second;*/
// ONE_DEBUG_MSG((" from transactions\n"));
/* found = true;
break;
}
}*/
if (!found) {
ONE_DEBUG_MSG(("length not found for list %d\n", FileNodeListID));
}
expected_fragment_sequence = readU32 (input, false);
if (expected_fragment_sequence != nFragmentSequence) {
ONE_DEBUG_MSG(("expected fragment %d, got %d\n", nFragmentSequence, expected_fragment_sequence));
}
else nFragmentSequence++;
// ONE_DEBUG_MSG((" nFragmentSequence ")) << nFragmentSequence << '\n';
}
std::string FileNodeList::to_string() {
std::stringstream stream;
stream << std::hex << "uintMagic " << uintMagic << '\n';
stream << std::dec << "FileNodeListID " << FileNodeListID << '\n';
stream << "nFragmentSequence " << nFragmentSequence << '\n';
for (FileNode i: rgFileNodes)
stream << i.to_string() << '\n';
return stream.str();
}
FileNode FileNodeList::get_next_node(librevenge::RVNGInputStream *input) {
bool next_fragment_wanted = false;
FileChunkReference next_fragment = FileChunkReference(FileChunkReferenceSize::Size64x32);
FileNode node;
if (!header_parsed) {
parse_header(input);
header_parsed = true;
}
// ONE_DEBUG_MSG((node.to_string));
if ((input->tell() >= next_fragment_location) || (next_fragment_location - input->tell() <= 4)) {
ONE_DEBUG_MSG(("wanting next fragment\n"));
next_fragment_wanted = true;
}
if (!next_fragment_wanted) {
node.parse(input);
if (node.get_FileNodeID() == FileNode::ChunkTerminatorFND)
next_fragment_wanted = true;
else
elements_parsed++;
}
if (next_fragment_wanted) {
input->seek(next_fragment_location, librevenge::RVNG_SEEK_SET);
next_fragment.parse(input);
assert (readU64(input, false) == 0x8BC215C38233BA4B);
if (next_fragment.is_fcrNil()) end = true;
else {
location = next_fragment.get_location();
size = next_fragment.get_size();
input->seek(location, librevenge::RVNG_SEEK_SET);
ONE_DEBUG_MSG(("what's up in here? %ld\n", input->tell()));
parse_header(input);
node.parse(input);
elements_parsed++;
}
next_fragment_wanted = false;
}
if (node.get_FileNodeID() == FileNode::DUNNO)
end = true;
if (elements_parsed == list_length) {
end = true;
ONE_DEBUG_MSG(("got to list length %d, parsed %d\n", list_length, elements_parsed));
} else {
ONE_DEBUG_MSG(("list id %d, element %d, length %d, position %ld, next fragment@%ld\n", FileNodeListID, elements_parsed, list_length, input->tell(), next_fragment_location));
}
return node;
}
FileNode FileNodeList::force_get_next_node(librevenge::RVNGInputStream *input) {
FileNode node = force_get_next_node(input);
end = false;
return node;
}
bool FileNodeList::is_end() {
return end;
}
}
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/*
* This file is part of the libvisio project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#ifndef BOOST_LEXICAL_CAST_ASSUME_C_LOCALE
#define BOOST_LEXICAL_CAST_ASSUME_C_LOCALE 1
#endif
#include <sstream>
#include <istream>
#include <vector>
#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>
#include <libxml/xmlIO.h>
#include <libxml/xmlstring.h>
#include <librevenge-stream/librevenge-stream.h>
#include "VSDXMLHelper.h"
#include "libvisio_utils.h"
namespace
{
extern "C" {
static int vsdxInputCloseFunc(void *)
{
return 0;
}
static int vsdxInputReadFunc(void *context, char *buffer, int len)
{
librevenge::RVNGInputStream *input = (librevenge::RVNGInputStream *)context;
if ((!input) || (!buffer) || (len < 0))
return -1;
if (input->isEnd())
return 0;
unsigned long tmpNumBytesRead = 0;
const unsigned char *tmpBuffer = input->read(len, tmpNumBytesRead);
if (tmpBuffer && tmpNumBytesRead)
memcpy(buffer, tmpBuffer, tmpNumBytesRead);
return tmpNumBytesRead;
}
#ifdef DEBUG
static void vsdxReaderErrorFunc(void *, const char *message, xmlParserSeverities severity, xmlTextReaderLocatorPtr)
#else
static void vsdxReaderErrorFunc(void *, const char *, xmlParserSeverities severity, xmlTextReaderLocatorPtr)
#endif
{
switch (severity)
{
case XML_PARSER_SEVERITY_VALIDITY_WARNING:
VSD_DEBUG_MSG(("Found xml parser severity validity warning %s\n", message));
break;
case XML_PARSER_SEVERITY_VALIDITY_ERROR:
VSD_DEBUG_MSG(("Found xml parser severity validity error %s\n", message));
break;
case XML_PARSER_SEVERITY_WARNING:
VSD_DEBUG_MSG(("Found xml parser severity warning %s\n", message));
break;
case XML_PARSER_SEVERITY_ERROR:
VSD_DEBUG_MSG(("Found xml parser severity error %s\n", message));
break;
default:
break;
}
}
} // extern "C"
} // anonymous namespace
// xmlTextReader helper function
xmlTextReaderPtr libvisio::xmlReaderForStream(librevenge::RVNGInputStream *input, const char *URL, const char *encoding, int options)
{
xmlTextReaderPtr reader = xmlReaderForIO(vsdxInputReadFunc, vsdxInputCloseFunc, (void *)input, URL, encoding, options);
xmlTextReaderSetErrorHandler(reader, vsdxReaderErrorFunc, 0);
return reader;
}
libvisio::Colour libvisio::xmlStringToColour(const xmlChar *s)
{
if (xmlStrEqual(s, BAD_CAST("Themed")))
return libvisio::Colour();
std::string str((const char *)s);
if (str[0] == '#')
{
if (str.length() != 7)
{
VSD_DEBUG_MSG(("Throwing XmlParserException\n"));
throw XmlParserException();
}
else
str.erase(str.begin());
}
else
{
if (str.length() != 6)
{
VSD_DEBUG_MSG(("Throwing XmlParserException\n"));
throw XmlParserException();
}
}
std::istringstream istr(str);
unsigned val = 0;
istr >> std::hex >> val;
return Colour((val & 0xff0000) >> 16, (val & 0xff00) >> 8, val & 0xff, 0);
}
long libvisio::xmlStringToLong(const xmlChar *s)
{
using boost::lexical_cast;
using boost::bad_lexical_cast;
if (xmlStrEqual(s, BAD_CAST("Themed")))
return 0;
try
{
return boost::lexical_cast<long, const char *>((const char *)s);
}
catch (const boost::bad_lexical_cast &)
{
VSD_DEBUG_MSG(("Throwing XmlParserException\n"));
throw XmlParserException();
}
return 0;
}
double libvisio::xmlStringToDouble(const xmlChar *s)
{
if (xmlStrEqual(s, BAD_CAST("Themed")))
return 0.0;
try
{
return boost::lexical_cast<double, const char *>((const char *)s);
}
catch (const boost::bad_lexical_cast &)
{
VSD_DEBUG_MSG(("Throwing XmlParserException\n"));
throw XmlParserException();
}
return 0.0;
}
bool libvisio::xmlStringToBool(const xmlChar *s)
{
if (xmlStrEqual(s, BAD_CAST("Themed")))
return 0;
bool value = false;
if (xmlStrEqual(s, BAD_CAST("true")) || xmlStrEqual(s, BAD_CAST("1")))
value = true;
else if (xmlStrEqual(s, BAD_CAST("false")) || xmlStrEqual(s, BAD_CAST("0")))
value = false;
else
{
VSD_DEBUG_MSG(("Throwing XmlParserException\n"));
throw XmlParserException();
}
return value;
}
// VSDXRelationship
libvisio::VSDXRelationship::VSDXRelationship(xmlTextReaderPtr reader)
: m_id(), m_type(), m_target()
{
if (reader)
// TODO: check whether we are actually parsing "Relationship" element
{
while (xmlTextReaderMoveToNextAttribute(reader))
{
const xmlChar *name = xmlTextReaderConstName(reader);
const xmlChar *value = xmlTextReaderConstValue(reader);
if (xmlStrEqual(name, BAD_CAST("Id")))
m_id = (const char *)value;
else if (xmlStrEqual(name, BAD_CAST("Type")))
m_type = (const char *)value;
else if (xmlStrEqual(name, BAD_CAST("Target")))
m_target = (const char *)value;
}
// VSD_DEBUG_MSG(("Relationship : %s type: %s target: %s\n", m_id.c_str(), m_type.c_str(), m_target.c_str()));
}
}
libvisio::VSDXRelationship::VSDXRelationship()
: m_id(), m_type(), m_target()
{
}
libvisio::VSDXRelationship::~VSDXRelationship()
{
}
void libvisio::VSDXRelationship::rebaseTarget(const char *baseDir)
{
std::string target(baseDir ? baseDir : "");
if (!target.empty())
target += "/";
target += m_target;
// normalize path by resolving any ".." or "." segments
// and eliminating duplicate path separators
std::vector<std::string> segments;
boost::split(segments, target, boost::is_any_of("/\\"));
std::vector<std::string> normalizedSegments;
for (unsigned i = 0; i < segments.size(); ++i)
{
if (segments[i] == "..")
normalizedSegments.pop_back();
else if (segments[i] != "." && !segments[i].empty())
normalizedSegments.push_back(segments[i]);
}
target.clear();
for (unsigned j = 0; j < normalizedSegments.size(); ++j)
{
if (!target.empty())
target.append("/");
target.append(normalizedSegments[j]);
}
// VSD_DEBUG_MSG(("VSDXRelationship::rebaseTarget %s -> %s\n", m_target.c_str(), target.c_str()));
m_target = target;
}
// VSDXRelationships
libvisio::VSDXRelationships::VSDXRelationships(librevenge::RVNGInputStream *input)
: m_relsByType(), m_relsById()
{
if (input)
{
xmlTextReaderPtr reader = xmlReaderForStream(input, 0, 0, XML_PARSE_NOBLANKS|XML_PARSE_NOENT|XML_PARSE_NONET|XML_PARSE_RECOVER);
if (reader)
{
bool inRelationships = false;
int ret = xmlTextReaderRead(reader);
while (ret == 1)
{
const xmlChar *name = xmlTextReaderConstName(reader);
if (name)
{
if (xmlStrEqual(name, BAD_CAST("Relationships")))
{
if (xmlTextReaderNodeType(reader) == 1)
{
// VSD_DEBUG_MSG(("Relationships ON\n"));
inRelationships = true;
}
else if (xmlTextReaderNodeType(reader) == 15)
{
// VSD_DEBUG_MSG(("Relationships OFF\n"));
inRelationships = false;
}
}
else if (xmlStrEqual(name, BAD_CAST("Relationship")))
{
if (inRelationships)
{
VSDXRelationship relationship(reader);
m_relsByType[relationship.getType()] = relationship;
m_relsById[relationship.getId()] = relationship;
}
}
}
ret = xmlTextReaderRead(reader);
}
xmlFreeTextReader(reader);
}
}
}
libvisio::VSDXRelationships::~VSDXRelationships()
{
}
void libvisio::VSDXRelationships::rebaseTargets(const char *baseDir)
{
std::map<std::string, libvisio::VSDXRelationship>::iterator iter;
for (iter = m_relsByType.begin(); iter != m_relsByType.end(); ++iter)
iter->second.rebaseTarget(baseDir);
for (iter = m_relsById.begin(); iter != m_relsById.end(); ++iter)
iter->second.rebaseTarget(baseDir);
}
const libvisio::VSDXRelationship *libvisio::VSDXRelationships::getRelationshipByType(const char *type) const
{
if (!type)
return 0;
std::map<std::string, libvisio::VSDXRelationship>::const_iterator iter = m_relsByType.find(type);
if (iter != m_relsByType.end())
return &(iter->second);
return 0;
}
const libvisio::VSDXRelationship *libvisio::VSDXRelationships::getRelationshipById(const char *id) const
{
if (!id)
return 0;
std::map<std::string, libvisio::VSDXRelationship>::const_iterator iter = m_relsById.find(id);
if (iter != m_relsById.end())
return &(iter->second);
return 0;
}
/* vim:set shiftwidth=2 softtabstop=2 expandtab: */
<commit_msg>coverity#1165322 unreachable return statement<commit_after>/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/*
* This file is part of the libvisio project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#ifndef BOOST_LEXICAL_CAST_ASSUME_C_LOCALE
#define BOOST_LEXICAL_CAST_ASSUME_C_LOCALE 1
#endif
#include <sstream>
#include <istream>
#include <vector>
#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>
#include <libxml/xmlIO.h>
#include <libxml/xmlstring.h>
#include <librevenge-stream/librevenge-stream.h>
#include "VSDXMLHelper.h"
#include "libvisio_utils.h"
namespace
{
extern "C" {
static int vsdxInputCloseFunc(void *)
{
return 0;
}
static int vsdxInputReadFunc(void *context, char *buffer, int len)
{
librevenge::RVNGInputStream *input = (librevenge::RVNGInputStream *)context;
if ((!input) || (!buffer) || (len < 0))
return -1;
if (input->isEnd())
return 0;
unsigned long tmpNumBytesRead = 0;
const unsigned char *tmpBuffer = input->read(len, tmpNumBytesRead);
if (tmpBuffer && tmpNumBytesRead)
memcpy(buffer, tmpBuffer, tmpNumBytesRead);
return tmpNumBytesRead;
}
#ifdef DEBUG
static void vsdxReaderErrorFunc(void *, const char *message, xmlParserSeverities severity, xmlTextReaderLocatorPtr)
#else
static void vsdxReaderErrorFunc(void *, const char *, xmlParserSeverities severity, xmlTextReaderLocatorPtr)
#endif
{
switch (severity)
{
case XML_PARSER_SEVERITY_VALIDITY_WARNING:
VSD_DEBUG_MSG(("Found xml parser severity validity warning %s\n", message));
break;
case XML_PARSER_SEVERITY_VALIDITY_ERROR:
VSD_DEBUG_MSG(("Found xml parser severity validity error %s\n", message));
break;
case XML_PARSER_SEVERITY_WARNING:
VSD_DEBUG_MSG(("Found xml parser severity warning %s\n", message));
break;
case XML_PARSER_SEVERITY_ERROR:
VSD_DEBUG_MSG(("Found xml parser severity error %s\n", message));
break;
default:
break;
}
}
} // extern "C"
} // anonymous namespace
// xmlTextReader helper function
xmlTextReaderPtr libvisio::xmlReaderForStream(librevenge::RVNGInputStream *input, const char *URL, const char *encoding, int options)
{
xmlTextReaderPtr reader = xmlReaderForIO(vsdxInputReadFunc, vsdxInputCloseFunc, (void *)input, URL, encoding, options);
xmlTextReaderSetErrorHandler(reader, vsdxReaderErrorFunc, 0);
return reader;
}
libvisio::Colour libvisio::xmlStringToColour(const xmlChar *s)
{
if (xmlStrEqual(s, BAD_CAST("Themed")))
return libvisio::Colour();
std::string str((const char *)s);
if (str[0] == '#')
{
if (str.length() != 7)
{
VSD_DEBUG_MSG(("Throwing XmlParserException\n"));
throw XmlParserException();
}
else
str.erase(str.begin());
}
else
{
if (str.length() != 6)
{
VSD_DEBUG_MSG(("Throwing XmlParserException\n"));
throw XmlParserException();
}
}
std::istringstream istr(str);
unsigned val = 0;
istr >> std::hex >> val;
return Colour((val & 0xff0000) >> 16, (val & 0xff00) >> 8, val & 0xff, 0);
}
long libvisio::xmlStringToLong(const xmlChar *s)
{
using boost::lexical_cast;
using boost::bad_lexical_cast;
if (xmlStrEqual(s, BAD_CAST("Themed")))
return 0;
try
{
return boost::lexical_cast<long, const char *>((const char *)s);
}
catch (const boost::bad_lexical_cast &)
{
VSD_DEBUG_MSG(("Throwing XmlParserException\n"));
throw XmlParserException();
}
return 0;
}
double libvisio::xmlStringToDouble(const xmlChar *s) try
{
if (xmlStrEqual(s, BAD_CAST("Themed")))
return 0.0;
return boost::lexical_cast<double, const char *>((const char *)s);
}
catch (const boost::bad_lexical_cast &)
{
VSD_DEBUG_MSG(("Throwing XmlParserException\n"));
throw XmlParserException();
}
bool libvisio::xmlStringToBool(const xmlChar *s)
{
if (xmlStrEqual(s, BAD_CAST("Themed")))
return 0;
bool value = false;
if (xmlStrEqual(s, BAD_CAST("true")) || xmlStrEqual(s, BAD_CAST("1")))
value = true;
else if (xmlStrEqual(s, BAD_CAST("false")) || xmlStrEqual(s, BAD_CAST("0")))
value = false;
else
{
VSD_DEBUG_MSG(("Throwing XmlParserException\n"));
throw XmlParserException();
}
return value;
}
// VSDXRelationship
libvisio::VSDXRelationship::VSDXRelationship(xmlTextReaderPtr reader)
: m_id(), m_type(), m_target()
{
if (reader)
// TODO: check whether we are actually parsing "Relationship" element
{
while (xmlTextReaderMoveToNextAttribute(reader))
{
const xmlChar *name = xmlTextReaderConstName(reader);
const xmlChar *value = xmlTextReaderConstValue(reader);
if (xmlStrEqual(name, BAD_CAST("Id")))
m_id = (const char *)value;
else if (xmlStrEqual(name, BAD_CAST("Type")))
m_type = (const char *)value;
else if (xmlStrEqual(name, BAD_CAST("Target")))
m_target = (const char *)value;
}
// VSD_DEBUG_MSG(("Relationship : %s type: %s target: %s\n", m_id.c_str(), m_type.c_str(), m_target.c_str()));
}
}
libvisio::VSDXRelationship::VSDXRelationship()
: m_id(), m_type(), m_target()
{
}
libvisio::VSDXRelationship::~VSDXRelationship()
{
}
void libvisio::VSDXRelationship::rebaseTarget(const char *baseDir)
{
std::string target(baseDir ? baseDir : "");
if (!target.empty())
target += "/";
target += m_target;
// normalize path by resolving any ".." or "." segments
// and eliminating duplicate path separators
std::vector<std::string> segments;
boost::split(segments, target, boost::is_any_of("/\\"));
std::vector<std::string> normalizedSegments;
for (unsigned i = 0; i < segments.size(); ++i)
{
if (segments[i] == "..")
normalizedSegments.pop_back();
else if (segments[i] != "." && !segments[i].empty())
normalizedSegments.push_back(segments[i]);
}
target.clear();
for (unsigned j = 0; j < normalizedSegments.size(); ++j)
{
if (!target.empty())
target.append("/");
target.append(normalizedSegments[j]);
}
// VSD_DEBUG_MSG(("VSDXRelationship::rebaseTarget %s -> %s\n", m_target.c_str(), target.c_str()));
m_target = target;
}
// VSDXRelationships
libvisio::VSDXRelationships::VSDXRelationships(librevenge::RVNGInputStream *input)
: m_relsByType(), m_relsById()
{
if (input)
{
xmlTextReaderPtr reader = xmlReaderForStream(input, 0, 0, XML_PARSE_NOBLANKS|XML_PARSE_NOENT|XML_PARSE_NONET|XML_PARSE_RECOVER);
if (reader)
{
bool inRelationships = false;
int ret = xmlTextReaderRead(reader);
while (ret == 1)
{
const xmlChar *name = xmlTextReaderConstName(reader);
if (name)
{
if (xmlStrEqual(name, BAD_CAST("Relationships")))
{
if (xmlTextReaderNodeType(reader) == 1)
{
// VSD_DEBUG_MSG(("Relationships ON\n"));
inRelationships = true;
}
else if (xmlTextReaderNodeType(reader) == 15)
{
// VSD_DEBUG_MSG(("Relationships OFF\n"));
inRelationships = false;
}
}
else if (xmlStrEqual(name, BAD_CAST("Relationship")))
{
if (inRelationships)
{
VSDXRelationship relationship(reader);
m_relsByType[relationship.getType()] = relationship;
m_relsById[relationship.getId()] = relationship;
}
}
}
ret = xmlTextReaderRead(reader);
}
xmlFreeTextReader(reader);
}
}
}
libvisio::VSDXRelationships::~VSDXRelationships()
{
}
void libvisio::VSDXRelationships::rebaseTargets(const char *baseDir)
{
std::map<std::string, libvisio::VSDXRelationship>::iterator iter;
for (iter = m_relsByType.begin(); iter != m_relsByType.end(); ++iter)
iter->second.rebaseTarget(baseDir);
for (iter = m_relsById.begin(); iter != m_relsById.end(); ++iter)
iter->second.rebaseTarget(baseDir);
}
const libvisio::VSDXRelationship *libvisio::VSDXRelationships::getRelationshipByType(const char *type) const
{
if (!type)
return 0;
std::map<std::string, libvisio::VSDXRelationship>::const_iterator iter = m_relsByType.find(type);
if (iter != m_relsByType.end())
return &(iter->second);
return 0;
}
const libvisio::VSDXRelationship *libvisio::VSDXRelationships::getRelationshipById(const char *id) const
{
if (!id)
return 0;
std::map<std::string, libvisio::VSDXRelationship>::const_iterator iter = m_relsById.find(id);
if (iter != m_relsById.end())
return &(iter->second);
return 0;
}
/* vim:set shiftwidth=2 softtabstop=2 expandtab: */
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- */
/* libwpd
* Copyright (C) 2012 Fridrich Strba (fridrich.strba@bluewin.ch)
*
* 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; if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02111-1301 USA
*
* For further information visit http://libwpd.sourceforge.net
*/
#include <string>
#include <string.h>
#include <stdio.h>
#include <zlib.h>
#include "WPXZipStream.h"
#include "WPXStreamImplementation.h"
namespace
{
class StreamException
{
};
struct LocalFileHeader
{
unsigned short min_version;
unsigned short general_flag;
unsigned short compression;
unsigned short lastmod_time;
unsigned short lastmod_date;
unsigned crc32;
unsigned compressed_size;
unsigned uncompressed_size;
unsigned short filename_size;
unsigned short extra_field_size;
std::string filename;
std::string extra_field;
LocalFileHeader()
: min_version(0), general_flag(0), compression(0), lastmod_time(0), lastmod_date(0),
crc32(0), compressed_size(0), uncompressed_size(0), filename_size(0), extra_field_size(0),
filename(), extra_field() {}
~LocalFileHeader() {}
};
struct CentralDirectoryEntry
{
unsigned short creator_version;
unsigned short min_version;
unsigned short general_flag;
unsigned short compression;
unsigned short lastmod_time;
unsigned short lastmod_date;
unsigned crc32;
unsigned compressed_size;
unsigned uncompressed_size;
unsigned short filename_size;
unsigned short extra_field_size;
unsigned short file_comment_size;
unsigned short disk_num;
unsigned short internal_attr;
unsigned external_attr;
unsigned offset;
std::string filename;
std::string extra_field;
std::string file_comment;
CentralDirectoryEntry()
: creator_version(0), min_version(0), general_flag(0), compression(0), lastmod_time(0),
lastmod_date(0), crc32(0), compressed_size(0), uncompressed_size(0), filename_size(0),
extra_field_size(0), file_comment_size(0), disk_num(0), internal_attr(0),
external_attr(0), offset(0), filename(), extra_field(), file_comment() {}
~CentralDirectoryEntry() {}
};
struct CentralDirectoryEnd
{
unsigned short disk_num;
unsigned short cdir_disk;
unsigned short disk_entries;
unsigned short cdir_entries;
unsigned cdir_size;
unsigned cdir_offset;
unsigned short comment_size;
std::string comment;
CentralDirectoryEnd()
: disk_num(0), cdir_disk(0), disk_entries(0), cdir_entries(0),
cdir_size(0), cdir_offset(0), comment_size(0), comment() {}
~CentralDirectoryEnd() {}
};
#define CDIR_ENTRY_SIG 0x02014b50
#define LOC_FILE_HEADER_SIG 0x04034b50
#define CDIR_END_SIG 0x06054b50
static unsigned char getByte(WPXInputStream *input)
{
unsigned long numBytesRead = 0;
const unsigned char *ret = input->read(1, numBytesRead);
if (numBytesRead != 1)
throw StreamException();
return ret[0];
}
static unsigned short getShort(WPXInputStream *input)
{
return (unsigned short)getByte(input)+((unsigned short)getByte(input)<<8);
}
static unsigned getInt(WPXInputStream *input)
{
return (unsigned)getByte(input)+((unsigned)getByte(input)<<8)+((unsigned)getByte(input)<<16)+((unsigned)getByte(input)<<24);
}
static bool readCentralDirectoryEnd(WPXInputStream *input, CentralDirectoryEnd &end)
{
try
{
unsigned signature = getInt(input);
if (signature != CDIR_END_SIG)
return false;
end.disk_num = getShort(input);
end.cdir_disk = getShort(input);
end.disk_entries = getShort(input);
end.cdir_entries = getShort(input);
end.cdir_size = getInt(input);
end.cdir_offset = getInt(input);
end.comment_size = getShort(input);
end.comment.clear();
for (unsigned short i = 0; i < end.comment_size; i++)
end.comment.append(1, (char)getByte(input));
}
catch (...)
{
return false;
}
return true;
}
static bool readCentralDirectoryEntry(WPXInputStream *input, CentralDirectoryEntry &entry)
{
try
{
unsigned signature = getInt(input);
if (signature != CDIR_ENTRY_SIG)
return false;
entry.creator_version = getShort(input);
entry.min_version = getShort(input);
entry.general_flag = getShort(input);
entry.compression = getShort(input);
entry.lastmod_time = getShort(input);
entry.lastmod_date = getShort(input);
entry.crc32 = getInt(input);
entry.compressed_size = getInt(input);
entry.uncompressed_size = getInt(input);
entry.filename_size = getShort(input);
entry.extra_field_size = getShort(input);
entry.file_comment_size = getShort(input);
entry.disk_num = getShort(input);
entry.internal_attr = getShort(input);
entry.external_attr = getInt(input);
entry.offset = getInt(input);
unsigned short i = 0;
entry.filename.clear();
for (i=0; i < entry.filename_size; i++)
entry.filename.append(1, (char)getByte(input));
entry.extra_field.clear();
for (i=0; i < entry.extra_field_size; i++)
entry.extra_field.append(1, (char)getByte(input));
entry.file_comment.clear();
for (i=0; i < entry.file_comment_size; i++)
entry.file_comment.append(1, (char)getByte(input));
}
catch (...)
{
return false;
}
return true;
}
static bool readLocalFileHeader(WPXInputStream *input, LocalFileHeader &header)
{
try
{
unsigned signature = getInt(input);
if (signature != LOC_FILE_HEADER_SIG)
return false;
header.min_version = getShort(input);
header.general_flag = getShort(input);
header.compression = getShort(input);
header.lastmod_time = getShort(input);
header.lastmod_date = getShort(input);
header.crc32 = getInt(input);
header.compressed_size = getInt(input);
header.uncompressed_size = getInt(input);
header.filename_size = getShort(input);
header.extra_field_size = getShort(input);
unsigned short i = 0;
header.filename.clear();
for (i=0; i < header.filename_size; i++)
header.filename.append(1, (char)getByte(input));
header.extra_field.clear();
for (i=0; i < header.extra_field_size; i++)
header.extra_field.append(1, (char)getByte(input));
}
catch (...)
{
return false;
}
return true;
}
static bool areHeadersConsistent(const LocalFileHeader &header, const CentralDirectoryEntry &entry)
{
if (header.min_version != entry.min_version)
return false;
if (header.general_flag != entry.general_flag)
return false;
if (header.compression != entry.compression)
return false;
if (!(header.general_flag & 0x08))
{
if (header.crc32 != entry.crc32)
return false;
if (header.compressed_size != entry.compressed_size)
return false;
if (header.uncompressed_size != entry.uncompressed_size)
return false;
}
return true;
}
static bool findCentralDirectoryEnd(WPXInputStream *input)
{
input->seek(0, WPX_SEEK_SET);
try
{
while (!input->atEOS())
{
unsigned signature = getInt(input);
if (signature == CDIR_END_SIG)
{
input->seek(-4, WPX_SEEK_CUR);
return true;
}
else
input->seek(-3, WPX_SEEK_CUR);
}
}
catch (...)
{
return false;
}
return false;
}
static bool findDataStream(WPXInputStream *input, CentralDirectoryEntry &entry, const char *name)
{
unsigned short name_size = strlen(name);
if (!findCentralDirectoryEnd(input))
return false;
CentralDirectoryEnd end;
if (!readCentralDirectoryEnd(input, end))
return false;
input->seek(end.cdir_offset, WPX_SEEK_SET);
while (!input->atEOS() && (unsigned)input->tell() < end.cdir_offset + end.cdir_size)
{
if (!readCentralDirectoryEntry(input, entry))
return false;
if (name_size == entry.filename_size && entry.filename == name)
break;
}
if (name_size != entry.filename_size)
return false;
if (entry.filename != name)
return false;
input->seek(entry.offset, WPX_SEEK_SET);
LocalFileHeader header;
printf("%x %x\n", (int)input->tell(), entry.offset);
if (!readLocalFileHeader(input, header))
return false;
if (!areHeadersConsistent(header, entry))
return false;
return true;
}
} // anonymous namespace
bool WPXZipStream::isZipFile(WPXInputStream *input)
{
// look for central directory end
if (!findCentralDirectoryEnd(input))
return false;
CentralDirectoryEnd end;
if (!readCentralDirectoryEnd(input, end))
return false;
input->seek(end.cdir_offset, WPX_SEEK_SET);
// read first entry in the central directory
CentralDirectoryEntry entry;
if (!readCentralDirectoryEntry(input, entry))
return false;
input->seek(entry.offset, WPX_SEEK_SET);
// read the local file header and compare with the central directory information
LocalFileHeader header;
if (!readLocalFileHeader(input, header))
return false;
if (!areHeadersConsistent(header, entry))
return false;
return true;
}
WPXInputStream *WPXZipStream::getSubstream(WPXInputStream *input, const char *name)
{
CentralDirectoryEntry entry;
if (!findDataStream(input, entry, name))
return 0;
unsigned long numBytesRead = 0;
const unsigned char *compressedData = input->read(entry.compressed_size, numBytesRead);
if (numBytesRead != entry.compressed_size)
return 0;
if (!entry.compression)
return new WPXStringStream(compressedData, numBytesRead);
else
{
int ret;
z_stream strm;
/* allocate inflate state */
strm.zalloc = Z_NULL;
strm.zfree = Z_NULL;
strm.opaque = Z_NULL;
strm.avail_in = 0;
strm.next_in = Z_NULL;
ret = inflateInit2(&strm,-MAX_WBITS);
if (ret != Z_OK)
return 0;
strm.avail_in = numBytesRead;
strm.next_in = (Bytef *)compressedData;
std::vector<unsigned char>data(entry.uncompressed_size);
strm.avail_out = entry.uncompressed_size;
strm.next_out = reinterpret_cast<Bytef *>(&data[0]);
ret = inflate(&strm, Z_FINISH);
switch (ret)
{
case Z_NEED_DICT:
case Z_DATA_ERROR:
case Z_MEM_ERROR:
(void)inflateEnd(&strm);
data.clear();
return 0;
}
return new WPXStringStream(&data[0], data.size());
}
}
/* vim:set shiftwidth=4 softtabstop=4 noexpandtab: */
<commit_msg>Make valgrind happy<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- */
/* libwpd
* Copyright (C) 2012 Fridrich Strba (fridrich.strba@bluewin.ch)
*
* 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; if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02111-1301 USA
*
* For further information visit http://libwpd.sourceforge.net
*/
#include <string>
#include <string.h>
#include <stdio.h>
#include <zlib.h>
#include "WPXZipStream.h"
#include "WPXStreamImplementation.h"
namespace
{
class StreamException
{
};
struct LocalFileHeader
{
unsigned short min_version;
unsigned short general_flag;
unsigned short compression;
unsigned short lastmod_time;
unsigned short lastmod_date;
unsigned crc32;
unsigned compressed_size;
unsigned uncompressed_size;
unsigned short filename_size;
unsigned short extra_field_size;
std::string filename;
std::string extra_field;
LocalFileHeader()
: min_version(0), general_flag(0), compression(0), lastmod_time(0), lastmod_date(0),
crc32(0), compressed_size(0), uncompressed_size(0), filename_size(0), extra_field_size(0),
filename(), extra_field() {}
~LocalFileHeader() {}
};
struct CentralDirectoryEntry
{
unsigned short creator_version;
unsigned short min_version;
unsigned short general_flag;
unsigned short compression;
unsigned short lastmod_time;
unsigned short lastmod_date;
unsigned crc32;
unsigned compressed_size;
unsigned uncompressed_size;
unsigned short filename_size;
unsigned short extra_field_size;
unsigned short file_comment_size;
unsigned short disk_num;
unsigned short internal_attr;
unsigned external_attr;
unsigned offset;
std::string filename;
std::string extra_field;
std::string file_comment;
CentralDirectoryEntry()
: creator_version(0), min_version(0), general_flag(0), compression(0), lastmod_time(0),
lastmod_date(0), crc32(0), compressed_size(0), uncompressed_size(0), filename_size(0),
extra_field_size(0), file_comment_size(0), disk_num(0), internal_attr(0),
external_attr(0), offset(0), filename(), extra_field(), file_comment() {}
~CentralDirectoryEntry() {}
};
struct CentralDirectoryEnd
{
unsigned short disk_num;
unsigned short cdir_disk;
unsigned short disk_entries;
unsigned short cdir_entries;
unsigned cdir_size;
unsigned cdir_offset;
unsigned short comment_size;
std::string comment;
CentralDirectoryEnd()
: disk_num(0), cdir_disk(0), disk_entries(0), cdir_entries(0),
cdir_size(0), cdir_offset(0), comment_size(0), comment() {}
~CentralDirectoryEnd() {}
};
#define CDIR_ENTRY_SIG 0x02014b50
#define LOC_FILE_HEADER_SIG 0x04034b50
#define CDIR_END_SIG 0x06054b50
static unsigned char getByte(WPXInputStream *input)
{
unsigned long numBytesRead = 0;
const unsigned char *ret = input->read(1, numBytesRead);
if (numBytesRead != 1)
throw StreamException();
return ret[0];
}
static unsigned short getShort(WPXInputStream *input)
{
return (unsigned short)getByte(input)+((unsigned short)getByte(input)<<8);
}
static unsigned getInt(WPXInputStream *input)
{
return (unsigned)getByte(input)+((unsigned)getByte(input)<<8)+((unsigned)getByte(input)<<16)+((unsigned)getByte(input)<<24);
}
static bool readCentralDirectoryEnd(WPXInputStream *input, CentralDirectoryEnd &end)
{
try
{
unsigned signature = getInt(input);
if (signature != CDIR_END_SIG)
return false;
end.disk_num = getShort(input);
end.cdir_disk = getShort(input);
end.disk_entries = getShort(input);
end.cdir_entries = getShort(input);
end.cdir_size = getInt(input);
end.cdir_offset = getInt(input);
end.comment_size = getShort(input);
end.comment.clear();
for (unsigned short i = 0; i < end.comment_size; i++)
end.comment.append(1, (char)getByte(input));
}
catch (...)
{
return false;
}
return true;
}
static bool readCentralDirectoryEntry(WPXInputStream *input, CentralDirectoryEntry &entry)
{
try
{
unsigned signature = getInt(input);
if (signature != CDIR_ENTRY_SIG)
return false;
entry.creator_version = getShort(input);
entry.min_version = getShort(input);
entry.general_flag = getShort(input);
entry.compression = getShort(input);
entry.lastmod_time = getShort(input);
entry.lastmod_date = getShort(input);
entry.crc32 = getInt(input);
entry.compressed_size = getInt(input);
entry.uncompressed_size = getInt(input);
entry.filename_size = getShort(input);
entry.extra_field_size = getShort(input);
entry.file_comment_size = getShort(input);
entry.disk_num = getShort(input);
entry.internal_attr = getShort(input);
entry.external_attr = getInt(input);
entry.offset = getInt(input);
unsigned short i = 0;
entry.filename.clear();
for (i=0; i < entry.filename_size; i++)
entry.filename.append(1, (char)getByte(input));
entry.extra_field.clear();
for (i=0; i < entry.extra_field_size; i++)
entry.extra_field.append(1, (char)getByte(input));
entry.file_comment.clear();
for (i=0; i < entry.file_comment_size; i++)
entry.file_comment.append(1, (char)getByte(input));
}
catch (...)
{
return false;
}
return true;
}
static bool readLocalFileHeader(WPXInputStream *input, LocalFileHeader &header)
{
try
{
unsigned signature = getInt(input);
if (signature != LOC_FILE_HEADER_SIG)
return false;
header.min_version = getShort(input);
header.general_flag = getShort(input);
header.compression = getShort(input);
header.lastmod_time = getShort(input);
header.lastmod_date = getShort(input);
header.crc32 = getInt(input);
header.compressed_size = getInt(input);
header.uncompressed_size = getInt(input);
header.filename_size = getShort(input);
header.extra_field_size = getShort(input);
unsigned short i = 0;
header.filename.clear();
for (i=0; i < header.filename_size; i++)
header.filename.append(1, (char)getByte(input));
header.extra_field.clear();
for (i=0; i < header.extra_field_size; i++)
header.extra_field.append(1, (char)getByte(input));
}
catch (...)
{
return false;
}
return true;
}
static bool areHeadersConsistent(const LocalFileHeader &header, const CentralDirectoryEntry &entry)
{
if (header.min_version != entry.min_version)
return false;
if (header.general_flag != entry.general_flag)
return false;
if (header.compression != entry.compression)
return false;
if (!(header.general_flag & 0x08))
{
if (header.crc32 != entry.crc32)
return false;
if (header.compressed_size != entry.compressed_size)
return false;
if (header.uncompressed_size != entry.uncompressed_size)
return false;
}
return true;
}
static bool findCentralDirectoryEnd(WPXInputStream *input)
{
input->seek(0, WPX_SEEK_SET);
try
{
while (!input->atEOS())
{
unsigned signature = getInt(input);
if (signature == CDIR_END_SIG)
{
input->seek(-4, WPX_SEEK_CUR);
return true;
}
else
input->seek(-3, WPX_SEEK_CUR);
}
}
catch (...)
{
return false;
}
return false;
}
static bool findDataStream(WPXInputStream *input, CentralDirectoryEntry &entry, const char *name)
{
unsigned short name_size = strlen(name);
if (!findCentralDirectoryEnd(input))
return false;
CentralDirectoryEnd end;
if (!readCentralDirectoryEnd(input, end))
return false;
input->seek(end.cdir_offset, WPX_SEEK_SET);
while (!input->atEOS() && (unsigned)input->tell() < end.cdir_offset + end.cdir_size)
{
if (!readCentralDirectoryEntry(input, entry))
return false;
if (name_size == entry.filename_size && entry.filename == name)
break;
}
if (name_size != entry.filename_size)
return false;
if (entry.filename != name)
return false;
input->seek(entry.offset, WPX_SEEK_SET);
LocalFileHeader header;
if (!readLocalFileHeader(input, header))
return false;
if (!areHeadersConsistent(header, entry))
return false;
return true;
}
} // anonymous namespace
bool WPXZipStream::isZipFile(WPXInputStream *input)
{
// look for central directory end
if (!findCentralDirectoryEnd(input))
return false;
CentralDirectoryEnd end;
if (!readCentralDirectoryEnd(input, end))
return false;
input->seek(end.cdir_offset, WPX_SEEK_SET);
// read first entry in the central directory
CentralDirectoryEntry entry;
if (!readCentralDirectoryEntry(input, entry))
return false;
input->seek(entry.offset, WPX_SEEK_SET);
// read the local file header and compare with the central directory information
LocalFileHeader header;
if (!readLocalFileHeader(input, header))
return false;
if (!areHeadersConsistent(header, entry))
return false;
return true;
}
WPXInputStream *WPXZipStream::getSubstream(WPXInputStream *input, const char *name)
{
CentralDirectoryEntry entry;
if (!findDataStream(input, entry, name))
return 0;
if (!entry.compressed_size)
return 0;
unsigned long numBytesRead = 0;
const unsigned char *compressedData = input->read(entry.compressed_size, numBytesRead);
if (numBytesRead != entry.compressed_size)
return 0;
if (!entry.compression)
return new WPXStringStream(compressedData, numBytesRead);
else
{
int ret;
z_stream strm;
/* allocate inflate state */
strm.zalloc = Z_NULL;
strm.zfree = Z_NULL;
strm.opaque = Z_NULL;
strm.avail_in = 0;
strm.next_in = Z_NULL;
ret = inflateInit2(&strm,-MAX_WBITS);
if (ret != Z_OK)
return 0;
strm.avail_in = numBytesRead;
strm.next_in = (Bytef *)compressedData;
std::vector<unsigned char>data(entry.uncompressed_size);
strm.avail_out = entry.uncompressed_size;
strm.next_out = reinterpret_cast<Bytef *>(&data[0]);
ret = inflate(&strm, Z_FINISH);
switch (ret)
{
case Z_NEED_DICT:
case Z_DATA_ERROR:
case Z_MEM_ERROR:
(void)inflateEnd(&strm);
data.clear();
return 0;
}
(void)inflateEnd(&strm);
return new WPXStringStream(&data[0], data.size());
}
}
/* vim:set shiftwidth=4 softtabstop=4 noexpandtab: */
<|endoftext|> |
<commit_before>#include "DynamicVertexBufferDemo.hpp"
#include <ciri/util/Log.hpp>
DynamicVertexBufferDemo::DynamicVertexBufferDemo()
: IDemo(), _graphicsDevice(nullptr), _window(nullptr) {
}
DynamicVertexBufferDemo::~DynamicVertexBufferDemo() {
}
DemoConfig DynamicVertexBufferDemo::getConfig() {
DemoConfig cfg;
cfg.deviceType = ciri::GraphicsDeviceFactory::OpenGL;
_shaderExtension = (ciri::GraphicsDeviceFactory::OpenGL == cfg.deviceType) ? ".glsl" : ".hlsl";
return cfg;
}
void DynamicVertexBufferDemo::onInitialize( ciri::Window* window, ciri::IGraphicsDevice* graphicsDevice ) {
_window = window;
_graphicsDevice = graphicsDevice;
// window size
const cc::Vec2ui windowSize = window->getSize();
// configure the camera
_camera.setAspect((float)windowSize.x / (float)windowSize.y);
_camera.setPlanes(0.1f, 1000.0f);
_camera.setYaw(247.9f);
_camera.setPitch(22.4f);
_camera.setOffset(49.5f);
_camera.setSensitivity(100.0f, 50.0f, 10.0f);
_camera.setLerpStrength(100.0f);
_camera.resetPosition();
}
void DynamicVertexBufferDemo::onLoadContent() {
if( !_grid.create(_graphicsDevice, _shaderExtension) ) {
ciri::Logs::get(ciri::Logs::Debug).printError("Failed to create grid.");
}
if( !_axis.create(5.0f, _shaderExtension, _graphicsDevice) ) {
ciri::Logs::get(ciri::Logs::Debug).printError("Failed to create axis.");
}
if( !_simpleShader.create(_graphicsDevice, _shaderExtension) ) {
ciri::Logs::get(ciri::Logs::Debug).printError("Failed to create simple shader.");
}
if( _flagpole.addFromObj("dynvb/flag-pole.obj") ) {
if( !_flagpole.build(_graphicsDevice) ) {
ciri::Logs::get(ciri::Logs::Debug).printError("Failed to build flagpole model.obj.");
}
} else {
ciri::Logs::get(ciri::Logs::Debug).printError("Failed to load flag-pole.obj.");
}
_flagpole.setShader(_simpleShader.getShader());
}
void DynamicVertexBufferDemo::onEvent( ciri::WindowEvent evt ) {
}
void DynamicVertexBufferDemo::onUpdate( double deltaTime, double elapsedTime ) {
// get current input states
ciri::KeyboardState currKeyState;
ciri::MouseState currMouseState;
ciri::Input::getKeyboardState(&currKeyState);
ciri::Input::getMouseState(&currMouseState, _window);
// check for close w/ escape
if( currKeyState.isKeyDown(ciri::Keyboard::Escape) ) {
_window->destroy();
return;
}
// debug camera info
if( currKeyState.isKeyDown(ciri::Keyboard::F9) && _prevKeyState.isKeyUp(ciri::Keyboard::F9) ) {
const cc::Vec3f& pos = _camera.getPosition();
const float yaw = _camera.getYaw();
const float pitch = _camera.getPitch();
const float dolly = _camera.getOffset();
printf("pos(%f/%f/%f); yaw(%f); pitch(%f); dolly(%f)\n", pos.x, pos.y, pos.z, yaw, pitch, dolly);
}
// camera movement
if( currKeyState.isKeyDown(ciri::Keyboard::LAlt) ) {
// rotation
if( currMouseState.isButtonDown(ciri::MouseButton::Left) ) {
const float dx = (float)currMouseState.x - (float)_prevMouseState.x;
const float dy = (float)currMouseState.y - (float)_prevMouseState.y;
_camera.rotateYaw(-dx * deltaTime);
_camera.rotatePitch(-dy * deltaTime);
}
// dolly
if( currMouseState.isButtonDown(ciri::MouseButton::Right) ) {
const float dx = (float)currMouseState.x - (float)_prevMouseState.x;
const float dy = (float)currMouseState.y - (float)_prevMouseState.y;
const float val = (fabsf(dx) > fabsf(dy)) ? dx : dy;
_camera.dolly(val * deltaTime);
}
// pan
if( currMouseState.isButtonDown(ciri::MouseButton::Middle) ) {
const float dx = (float)currMouseState.x - (float)_prevMouseState.x;
const float dy = (float)currMouseState.y - (float)_prevMouseState.y;
_camera.pan(dx * deltaTime, -dy * deltaTime);
}
}
_camera.update(deltaTime);
// update previous input states
_prevKeyState = currKeyState;
_prevMouseState = currMouseState;
}
void DynamicVertexBufferDemo::onDraw() {
_graphicsDevice->clear(ciri::ClearFlags::Color);
// camera's viewproj matrix
const cc::Mat4f cameraViewProj = _camera.getProj() * _camera.getView();
// render the grid
if( _grid.isValid() ) {
const cc::Mat4f gridXform = cameraViewProj * cc::Mat4f(1.0f);
if( _grid.updateConstants(gridXform) ) {
_graphicsDevice->applyShader(_grid.getShader());
_graphicsDevice->setVertexBuffer(_grid.getVertexBuffer());
_graphicsDevice->drawArrays(ciri::PrimitiveTopology::LineList, _grid.getVertexBuffer()->getVertexCount(), 0);
}
}
// render the axis
if( _axis.isValid() ) {
const cc::Mat4f axisXform = cameraViewProj * cc::Mat4f(1.0f);
if( _axis.updateConstants(axisXform) ) {
_graphicsDevice->applyShader(_axis.getShader());
_graphicsDevice->setVertexBuffer(_axis.getVertexBuffer());
_graphicsDevice->drawArrays(ciri::PrimitiveTopology::LineList, _axis.getVertexBuffer()->getVertexCount(), 0);
}
}
// render the flagpole
if( _flagpole.getShader() != nullptr && _flagpole.getShader()->isValid() ) {
// update constant buffer
_simpleShader.getConstants().world = _flagpole.getXform().getWorld();
_simpleShader.getConstants().xform = cameraViewProj * _simpleShader.getConstants().world;
_simpleShader.getMaterialConstants().hasDiffuseTexture = 0;
_simpleShader.getMaterialConstants().diffuseColor = cc::Vec3f(1.0f, 1.0f, 1.0f);
if( !_simpleShader.updateConstants() ) {
ciri::Logs::get(ciri::Logs::Debug).printError("Failed to update simple constant buffer data.");
}
// apply shader
_graphicsDevice->applyShader(_flagpole.getShader());
// set vertex buffer and index buffer
_graphicsDevice->setVertexBuffer(_flagpole.getVertexBuffer());
if( _flagpole.getIndexBuffer() != nullptr ) {
_graphicsDevice->setIndexBuffer(_flagpole.getIndexBuffer());
_graphicsDevice->drawIndexed(ciri::PrimitiveTopology::TriangleList, _flagpole.getIndexBuffer()->getIndexCount());
} else {
_graphicsDevice->drawArrays(ciri::PrimitiveTopology::TriangleList, _flagpole.getVertexBuffer()->getVertexCount(), 0);
}
}
_graphicsDevice->present();
}
void DynamicVertexBufferDemo::onUnloadContent() {
_grid.clean();
}<commit_msg>Oops! Just realized the camera's mouse input has been tied to time all along. Fixed that now.<commit_after>#include "DynamicVertexBufferDemo.hpp"
#include <ciri/util/Log.hpp>
DynamicVertexBufferDemo::DynamicVertexBufferDemo()
: IDemo(), _graphicsDevice(nullptr), _window(nullptr) {
}
DynamicVertexBufferDemo::~DynamicVertexBufferDemo() {
}
DemoConfig DynamicVertexBufferDemo::getConfig() {
DemoConfig cfg;
cfg.deviceType = ciri::GraphicsDeviceFactory::OpenGL;
_shaderExtension = (ciri::GraphicsDeviceFactory::OpenGL == cfg.deviceType) ? ".glsl" : ".hlsl";
return cfg;
}
void DynamicVertexBufferDemo::onInitialize( ciri::Window* window, ciri::IGraphicsDevice* graphicsDevice ) {
_window = window;
_graphicsDevice = graphicsDevice;
// window size
const cc::Vec2ui windowSize = window->getSize();
// configure the camera
_camera.setAspect((float)windowSize.x / (float)windowSize.y);
_camera.setPlanes(0.1f, 1000.0f);
_camera.setYaw(247.9f);
_camera.setPitch(22.4f);
_camera.setOffset(49.5f);
_camera.setSensitivity(1.0f, 1.0f, 0.25f);
_camera.setLerpStrength(100.0f);
_camera.resetPosition();
}
void DynamicVertexBufferDemo::onLoadContent() {
if( !_grid.create(_graphicsDevice, _shaderExtension) ) {
ciri::Logs::get(ciri::Logs::Debug).printError("Failed to create grid.");
}
if( !_axis.create(5.0f, _shaderExtension, _graphicsDevice) ) {
ciri::Logs::get(ciri::Logs::Debug).printError("Failed to create axis.");
}
if( !_simpleShader.create(_graphicsDevice, _shaderExtension) ) {
ciri::Logs::get(ciri::Logs::Debug).printError("Failed to create simple shader.");
}
if( _flagpole.addFromObj("dynvb/flag-pole.obj") ) {
if( !_flagpole.build(_graphicsDevice) ) {
ciri::Logs::get(ciri::Logs::Debug).printError("Failed to build flagpole model.obj.");
}
} else {
ciri::Logs::get(ciri::Logs::Debug).printError("Failed to load flag-pole.obj.");
}
_flagpole.setShader(_simpleShader.getShader());
}
void DynamicVertexBufferDemo::onEvent( ciri::WindowEvent evt ) {
}
void DynamicVertexBufferDemo::onUpdate( double deltaTime, double elapsedTime ) {
// get current input states
ciri::KeyboardState currKeyState;
ciri::MouseState currMouseState;
ciri::Input::getKeyboardState(&currKeyState);
ciri::Input::getMouseState(&currMouseState, _window);
// check for close w/ escape
if( currKeyState.isKeyDown(ciri::Keyboard::Escape) ) {
_window->destroy();
return;
}
// debug camera info
if( currKeyState.isKeyDown(ciri::Keyboard::F9) && _prevKeyState.isKeyUp(ciri::Keyboard::F9) ) {
const cc::Vec3f& pos = _camera.getPosition();
const float yaw = _camera.getYaw();
const float pitch = _camera.getPitch();
const float dolly = _camera.getOffset();
printf("pos(%f/%f/%f); yaw(%f); pitch(%f); dolly(%f)\n", pos.x, pos.y, pos.z, yaw, pitch, dolly);
}
// camera movement
if( currKeyState.isKeyDown(ciri::Keyboard::LAlt) ) {
// rotation
if( currMouseState.isButtonDown(ciri::MouseButton::Left) ) {
const float dx = (float)currMouseState.x - (float)_prevMouseState.x;
const float dy = (float)currMouseState.y - (float)_prevMouseState.y;
_camera.rotateYaw(-dx);
_camera.rotatePitch(-dy);
}
// dolly
if( currMouseState.isButtonDown(ciri::MouseButton::Right) ) {
const float dx = (float)currMouseState.x - (float)_prevMouseState.x;
const float dy = (float)currMouseState.y - (float)_prevMouseState.y;
const float val = (fabsf(dx) > fabsf(dy)) ? dx : dy;
_camera.dolly(val);
}
// pan
if( currMouseState.isButtonDown(ciri::MouseButton::Middle) ) {
const float dx = (float)currMouseState.x - (float)_prevMouseState.x;
const float dy = (float)currMouseState.y - (float)_prevMouseState.y;
_camera.pan(dx, -dy);
}
}
_camera.update(deltaTime);
// update previous input states
_prevKeyState = currKeyState;
_prevMouseState = currMouseState;
}
void DynamicVertexBufferDemo::onDraw() {
_graphicsDevice->clear(ciri::ClearFlags::Color);
// camera's viewproj matrix
const cc::Mat4f cameraViewProj = _camera.getProj() * _camera.getView();
// render the grid
if( _grid.isValid() ) {
const cc::Mat4f gridXform = cameraViewProj * cc::Mat4f(1.0f);
if( _grid.updateConstants(gridXform) ) {
_graphicsDevice->applyShader(_grid.getShader());
_graphicsDevice->setVertexBuffer(_grid.getVertexBuffer());
_graphicsDevice->drawArrays(ciri::PrimitiveTopology::LineList, _grid.getVertexBuffer()->getVertexCount(), 0);
}
}
// render the axis
if( _axis.isValid() ) {
const cc::Mat4f axisXform = cameraViewProj * cc::Mat4f(1.0f);
if( _axis.updateConstants(axisXform) ) {
_graphicsDevice->applyShader(_axis.getShader());
_graphicsDevice->setVertexBuffer(_axis.getVertexBuffer());
_graphicsDevice->drawArrays(ciri::PrimitiveTopology::LineList, _axis.getVertexBuffer()->getVertexCount(), 0);
}
}
// render the flagpole
if( _flagpole.getShader() != nullptr && _flagpole.getShader()->isValid() ) {
// update constant buffer
_simpleShader.getConstants().world = _flagpole.getXform().getWorld();
_simpleShader.getConstants().xform = cameraViewProj * _simpleShader.getConstants().world;
_simpleShader.getMaterialConstants().hasDiffuseTexture = 0;
_simpleShader.getMaterialConstants().diffuseColor = cc::Vec3f(1.0f, 1.0f, 1.0f);
if( !_simpleShader.updateConstants() ) {
ciri::Logs::get(ciri::Logs::Debug).printError("Failed to update simple constant buffer data.");
}
// apply shader
_graphicsDevice->applyShader(_flagpole.getShader());
// set vertex buffer and index buffer
_graphicsDevice->setVertexBuffer(_flagpole.getVertexBuffer());
if( _flagpole.getIndexBuffer() != nullptr ) {
_graphicsDevice->setIndexBuffer(_flagpole.getIndexBuffer());
_graphicsDevice->drawIndexed(ciri::PrimitiveTopology::TriangleList, _flagpole.getIndexBuffer()->getIndexCount());
} else {
_graphicsDevice->drawArrays(ciri::PrimitiveTopology::TriangleList, _flagpole.getVertexBuffer()->getVertexCount(), 0);
}
}
_graphicsDevice->present();
}
void DynamicVertexBufferDemo::onUnloadContent() {
_grid.clean();
}<|endoftext|> |
<commit_before>/*
* Diffie-Hellman
* (C) 1999-2007 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/
#include <botan/internal/pk_utils.h>
#include <botan/dh.h>
#include <botan/workfactor.h>
#include <botan/pow_mod.h>
#include <botan/blinding.h>
namespace Botan {
/*
* DH_PublicKey Constructor
*/
DH_PublicKey::DH_PublicKey(const DL_Group& grp, const BigInt& y1)
{
m_group = grp;
m_y = y1;
}
/*
* Return the public value for key agreement
*/
std::vector<byte> DH_PublicKey::public_value() const
{
return unlock(BigInt::encode_1363(m_y, group_p().bytes()));
}
/*
* Create a DH private key
*/
DH_PrivateKey::DH_PrivateKey(RandomNumberGenerator& rng,
const DL_Group& grp,
const BigInt& x_arg)
{
m_group = grp;
m_x = x_arg;
if(m_x == 0)
{
const BigInt& p = group_p();
m_x.randomize(rng, dl_exponent_size(p.bits()));
}
if(m_y == 0)
m_y = power_mod(group_g(), m_x, group_p());
if(m_x == 0)
gen_check(rng);
else
load_check(rng);
}
/*
* Load a DH private key
*/
DH_PrivateKey::DH_PrivateKey(const AlgorithmIdentifier& alg_id,
const secure_vector<byte>& key_bits,
RandomNumberGenerator& rng) :
DL_Scheme_PrivateKey(alg_id, key_bits, DL_Group::ANSI_X9_42)
{
if(m_y == 0)
m_y = power_mod(group_g(), m_x, group_p());
load_check(rng);
}
/*
* Return the public value for key agreement
*/
std::vector<byte> DH_PrivateKey::public_value() const
{
return DH_PublicKey::public_value();
}
namespace {
/**
* DH operation
*/
class DH_KA_Operation : public PK_Ops::Key_Agreement_with_KDF
{
public:
typedef DH_PrivateKey Key_Type;
DH_KA_Operation(const DH_PrivateKey& key, const std::string& kdf);
secure_vector<byte> raw_agree(const byte w[], size_t w_len) override;
private:
const BigInt& m_p;
Fixed_Exponent_Power_Mod m_powermod_x_p;
Blinder m_blinder;
};
DH_KA_Operation::DH_KA_Operation(const DH_PrivateKey& dh, const std::string& kdf) :
PK_Ops::Key_Agreement_with_KDF(kdf),
m_p(dh.group_p()),
m_powermod_x_p(dh.get_x(), m_p),
m_blinder(m_p,
[](const BigInt& k) { return k; },
[this](const BigInt& k) { return m_powermod_x_p(inverse_mod(k, m_p)); })
{
}
secure_vector<byte> DH_KA_Operation::raw_agree(const byte w[], size_t w_len)
{
BigInt input = BigInt::decode(w, w_len);
if(input <= 1 || input >= m_p - 1)
throw Invalid_Argument("DH agreement - invalid key provided");
BigInt r = m_blinder.unblind(m_powermod_x_p(m_blinder.blind(input)));
return BigInt::encode_1363(r, m_p.bytes());
}
}
BOTAN_REGISTER_PK_KEY_AGREE_OP("DH", DH_KA_Operation);
}
<commit_msg>fix: load_check() was called instead of gen_check() during DH private key generation<commit_after>/*
* Diffie-Hellman
* (C) 1999-2007 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/
#include <botan/internal/pk_utils.h>
#include <botan/dh.h>
#include <botan/workfactor.h>
#include <botan/pow_mod.h>
#include <botan/blinding.h>
namespace Botan {
/*
* DH_PublicKey Constructor
*/
DH_PublicKey::DH_PublicKey(const DL_Group& grp, const BigInt& y1)
{
m_group = grp;
m_y = y1;
}
/*
* Return the public value for key agreement
*/
std::vector<byte> DH_PublicKey::public_value() const
{
return unlock(BigInt::encode_1363(m_y, group_p().bytes()));
}
/*
* Create a DH private key
*/
DH_PrivateKey::DH_PrivateKey(RandomNumberGenerator& rng,
const DL_Group& grp,
const BigInt& x_arg)
{
const bool generate = (x_arg == 0) ? true : false;
m_group = grp;
m_x = x_arg;
if(m_x == 0)
{
const BigInt& p = group_p();
m_x.randomize(rng, dl_exponent_size(p.bits()));
}
if(m_y == 0)
{
m_y = power_mod(group_g(), m_x, group_p());
}
if(generate)
{
gen_check(rng);
}
else
{
load_check(rng);
}
}
/*
* Load a DH private key
*/
DH_PrivateKey::DH_PrivateKey(const AlgorithmIdentifier& alg_id,
const secure_vector<byte>& key_bits,
RandomNumberGenerator& rng) :
DL_Scheme_PrivateKey(alg_id, key_bits, DL_Group::ANSI_X9_42)
{
if(m_y == 0)
m_y = power_mod(group_g(), m_x, group_p());
load_check(rng);
}
/*
* Return the public value for key agreement
*/
std::vector<byte> DH_PrivateKey::public_value() const
{
return DH_PublicKey::public_value();
}
namespace {
/**
* DH operation
*/
class DH_KA_Operation : public PK_Ops::Key_Agreement_with_KDF
{
public:
typedef DH_PrivateKey Key_Type;
DH_KA_Operation(const DH_PrivateKey& key, const std::string& kdf);
secure_vector<byte> raw_agree(const byte w[], size_t w_len) override;
private:
const BigInt& m_p;
Fixed_Exponent_Power_Mod m_powermod_x_p;
Blinder m_blinder;
};
DH_KA_Operation::DH_KA_Operation(const DH_PrivateKey& dh, const std::string& kdf) :
PK_Ops::Key_Agreement_with_KDF(kdf),
m_p(dh.group_p()),
m_powermod_x_p(dh.get_x(), m_p),
m_blinder(m_p,
[](const BigInt& k) { return k; },
[this](const BigInt& k) { return m_powermod_x_p(inverse_mod(k, m_p)); })
{
}
secure_vector<byte> DH_KA_Operation::raw_agree(const byte w[], size_t w_len)
{
BigInt input = BigInt::decode(w, w_len);
if(input <= 1 || input >= m_p - 1)
throw Invalid_Argument("DH agreement - invalid key provided");
BigInt r = m_blinder.unblind(m_powermod_x_p(m_blinder.blind(input)));
return BigInt::encode_1363(r, m_p.bytes());
}
}
BOTAN_REGISTER_PK_KEY_AGREE_OP("DH", DH_KA_Operation);
}
<|endoftext|> |
<commit_before>/*
* Copyright 2014 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "flatbuffers/flatbuffers.h"
#include "flatbuffers/idl.h"
#include "flatbuffers/util.h"
#include <limits>
#define FLATC_VERSION "1.3.0 (" __DATE__ ")"
static void Error(const std::string &err, bool usage = false,
bool show_exe_name = true);
// This struct allows us to create a table of all possible output generators
// for the various programming languages and formats we support.
struct Generator {
bool (*generate)(const flatbuffers::Parser &parser,
const std::string &path,
const std::string &file_name);
const char *generator_opt_short;
const char *generator_opt_long;
const char *lang_name;
flatbuffers::IDLOptions::Language lang;
const char *generator_help;
std::string (*make_rule)(const flatbuffers::Parser &parser,
const std::string &path,
const std::string &file_name);
};
const Generator generators[] = {
{ flatbuffers::GenerateBinary, "-b", "--binary", "binary",
flatbuffers::IDLOptions::kMAX,
"Generate wire format binaries for any data definitions",
flatbuffers::BinaryMakeRule },
{ flatbuffers::GenerateTextFile, "-t", "--json", "text",
flatbuffers::IDLOptions::kMAX,
"Generate text output for any data definitions",
flatbuffers::TextMakeRule },
{ flatbuffers::GenerateCPP, "-c", "--cpp", "C++",
flatbuffers::IDLOptions::kMAX,
"Generate C++ headers for tables/structs",
flatbuffers::CPPMakeRule },
{ flatbuffers::GenerateGo, "-g", "--go", "Go",
flatbuffers::IDLOptions::kGo,
"Generate Go files for tables/structs",
flatbuffers::GeneralMakeRule },
{ flatbuffers::GenerateGeneral, "-j", "--java", "Java",
flatbuffers::IDLOptions::kJava,
"Generate Java classes for tables/structs",
flatbuffers::GeneralMakeRule },
{ flatbuffers::GenerateJS, "-s", "--js", "JavaScript",
flatbuffers::IDLOptions::kMAX,
"Generate JavaScript code for tables/structs",
flatbuffers::JSMakeRule },
{ flatbuffers::GenerateGeneral, "-n", "--csharp", "C#",
flatbuffers::IDLOptions::kCSharp,
"Generate C# classes for tables/structs",
flatbuffers::GeneralMakeRule },
{ flatbuffers::GeneratePython, "-p", "--python", "Python",
flatbuffers::IDLOptions::kMAX,
"Generate Python files for tables/structs",
flatbuffers::GeneralMakeRule },
{ flatbuffers::GeneratePhp, nullptr, "--php", "PHP",
flatbuffers::IDLOptions::kMAX,
"Generate PHP files for tables/structs",
flatbuffers::GeneralMakeRule },
{ flatbuffers::GenerateGRPC, nullptr, "--grpc", "GRPC",
flatbuffers::IDLOptions::kMAX,
"Generate GRPC interfaces",
flatbuffers::CPPMakeRule },
};
const char *program_name = nullptr;
flatbuffers::Parser *parser = nullptr;
static void Error(const std::string &err, bool usage, bool show_exe_name) {
if (show_exe_name) printf("%s: ", program_name);
printf("%s\n", err.c_str());
if (usage) {
printf("usage: %s [OPTION]... FILE... [-- FILE...]\n", program_name);
for (size_t i = 0; i < sizeof(generators) / sizeof(generators[0]); ++i)
printf(" %-12s %s %s.\n",
generators[i].generator_opt_long,
generators[i].generator_opt_short
? generators[i].generator_opt_short
: " ",
generators[i].generator_help);
printf(
" -o PATH Prefix PATH to all generated files.\n"
" -I PATH Search for includes in the specified path.\n"
" -M Print make rules for generated files.\n"
" --version Print the version number of flatc and exit.\n"
" --strict-json Strict JSON: field names must be / will be quoted,\n"
" no trailing commas in tables/vectors.\n"
" --defaults-json Output fields whose value is the default when\n"
" writing JSON\n"
" --unknown-json Allow fields in JSON that are not defined in the\n"
" schema. These fields will be discared when generating\n"
" binaries.\n"
" --no-prefix Don\'t prefix enum values with the enum type in C++.\n"
" --scoped-enums Use C++11 style scoped and strongly typed enums.\n"
" also implies --no-prefix.\n"
" --gen-includes (deprecated), this is the default behavior.\n"
" If the original behavior is required (no include\n"
" statements) use --no-includes.\n"
" --no-includes Don\'t generate include statements for included\n"
" schemas the generated file depends on (C++).\n"
" --gen-mutable Generate accessors that can mutate buffers in-place.\n"
" --gen-onefile Generate single output file for C#.\n"
" --gen-name-strings Generate type name functions for C++.\n"
" --escape-proto-identifiers Disable appending '_' in namespaces names.\n"
" --raw-binary Allow binaries without file_indentifier to be read.\n"
" This may crash flatc given a mismatched schema.\n"
" --proto Input is a .proto, translate to .fbs.\n"
" --schema Serialize schemas instead of JSON (use with -b)\n"
"FILEs may be schemas, or JSON files (conforming to preceding schema)\n"
"FILEs after the -- must be binary flatbuffer format files.\n"
"Output files are named using the base file name of the input,\n"
"and written to the current directory or the path given by -o.\n"
"example: %s -c -b schema1.fbs schema2.fbs data.json\n",
program_name);
}
if (parser) delete parser;
exit(1);
}
int main(int argc, const char *argv[]) {
program_name = argv[0];
flatbuffers::IDLOptions opts;
std::string output_path;
const size_t num_generators = sizeof(generators) / sizeof(generators[0]);
bool generator_enabled[num_generators] = { false };
bool any_generator = false;
bool print_make_rules = false;
bool raw_binary = false;
bool schema_binary = false;
std::vector<std::string> filenames;
std::vector<const char *> include_directories;
size_t binary_files_from = std::numeric_limits<size_t>::max();
for (int argi = 1; argi < argc; argi++) {
std::string arg = argv[argi];
if (arg[0] == '-') {
if (filenames.size() && arg[1] != '-')
Error("invalid option location: " + arg, true);
if (arg == "-o") {
if (++argi >= argc) Error("missing path following: " + arg, true);
output_path = flatbuffers::ConCatPathFileName(argv[argi], "");
} else if(arg == "-I") {
if (++argi >= argc) Error("missing path following" + arg, true);
include_directories.push_back(argv[argi]);
} else if(arg == "--strict-json") {
opts.strict_json = true;
} else if(arg == "--no-js-exports") {
opts.skip_js_exports = true;
} else if(arg == "--defaults-json") {
opts.output_default_scalars_in_json = true;
} else if (arg == "--unknown-json") {
opts.skip_unexpected_fields_in_json = true;
} else if(arg == "--no-prefix") {
opts.prefixed_enums = false;
} else if(arg == "--scoped-enums") {
opts.prefixed_enums = false;
opts.scoped_enums = true;
} else if(arg == "--gen-mutable") {
opts.mutable_buffer = true;
} else if(arg == "--gen-name-strings") {
opts.generate_name_strings = true;
} else if(arg == "--gen-all") {
opts.generate_all = true;
opts.include_dependence_headers = false;
} else if(arg == "--gen-includes") {
// Deprecated, remove this option some time in the future.
printf("warning: --gen-includes is deprecated (it is now default)\n");
} else if(arg == "--no-includes") {
opts.include_dependence_headers = false;
} else if (arg == "--gen-onefile") {
opts.one_file = true;
} else if (arg == "--raw-binary") {
raw_binary = true;
} else if(arg == "--") { // Separator between text and binary inputs.
binary_files_from = filenames.size();
} else if(arg == "--proto") {
opts.proto_mode = true;
} else if (arg == "--escape-proto-identifiers") {
opts.escape_proto_identifiers = true;
} else if (arg == "--schema") {
schema_binary = true;
} else if(arg == "-M") {
print_make_rules = true;
} else if(arg == "--version") {
printf("flatc version %s\n", FLATC_VERSION);
exit(0);
} else {
for (size_t i = 0; i < num_generators; ++i) {
if (arg == generators[i].generator_opt_long ||
(generators[i].generator_opt_short &&
arg == generators[i].generator_opt_short)) {
generator_enabled[i] = true;
any_generator = true;
goto found;
}
}
Error("unknown commandline argument" + arg, true);
found:;
}
} else {
filenames.push_back(argv[argi]);
}
}
if (!filenames.size()) Error("missing input files", false, true);
if (opts.proto_mode) {
if (any_generator)
Error("cannot generate code directly from .proto files", true);
} else if (!any_generator) {
Error("no options: specify at least one generator.", true);
}
// Now process the files:
parser = new flatbuffers::Parser(opts);
for (auto file_it = filenames.begin();
file_it != filenames.end();
++file_it) {
std::string contents;
if (!flatbuffers::LoadFile(file_it->c_str(), true, &contents))
Error("unable to load file: " + *file_it);
bool is_binary = static_cast<size_t>(file_it - filenames.begin()) >=
binary_files_from;
if (is_binary) {
parser->builder_.Clear();
parser->builder_.PushFlatBuffer(
reinterpret_cast<const uint8_t *>(contents.c_str()),
contents.length());
if (!raw_binary) {
// Generally reading binaries that do not correspond to the schema
// will crash, and sadly there's no way around that when the binary
// does not contain a file identifier.
// We'd expect that typically any binary used as a file would have
// such an identifier, so by default we require them to match.
if (!parser->file_identifier_.length()) {
Error("current schema has no file_identifier: cannot test if \"" +
*file_it +
"\" matches the schema, use --raw-binary to read this file"
" anyway.");
} else if (!flatbuffers::BufferHasIdentifier(contents.c_str(),
parser->file_identifier_.c_str())) {
Error("binary \"" +
*file_it +
"\" does not have expected file_identifier \"" +
parser->file_identifier_ +
"\", use --raw-binary to read this file anyway.");
}
}
} else {
// Check if file contains 0 bytes.
if (contents.length() != strlen(contents.c_str())) {
Error("input file appears to be binary: " + *file_it, true);
}
if (flatbuffers::GetExtension(*file_it) == "fbs") {
// If we're processing multiple schemas, make sure to start each
// one from scratch. If it depends on previous schemas it must do
// so explicitly using an include.
delete parser;
parser = new flatbuffers::Parser(opts);
}
auto local_include_directory = flatbuffers::StripFileName(*file_it);
include_directories.push_back(local_include_directory.c_str());
include_directories.push_back(nullptr);
if (!parser->Parse(contents.c_str(), &include_directories[0],
file_it->c_str()))
Error(parser->error_, false, false);
if (schema_binary) {
parser->Serialize();
parser->file_extension_ = reflection::SchemaExtension();
}
include_directories.pop_back();
include_directories.pop_back();
}
std::string filebase = flatbuffers::StripPath(
flatbuffers::StripExtension(*file_it));
for (size_t i = 0; i < num_generators; ++i) {
parser->opts.lang = generators[i].lang;
if (generator_enabled[i]) {
if (!print_make_rules) {
flatbuffers::EnsureDirExists(output_path);
if (!generators[i].generate(*parser, output_path, filebase)) {
Error(std::string("Unable to generate ") +
generators[i].lang_name +
" for " +
filebase);
}
} else {
std::string make_rule = generators[i].make_rule(
*parser, output_path, *file_it);
if (!make_rule.empty())
printf("%s\n", flatbuffers::WordWrap(
make_rule, 80, " ", " \\").c_str());
}
}
}
if (opts.proto_mode) GenerateFBS(*parser, output_path, filebase, opts.escape_proto_identifiers);
// We do not want to generate code for the definitions in this file
// in any files coming up next.
parser->MarkGenerated();
}
delete parser;
return 0;
}
<commit_msg>Update flatc.cpp<commit_after>/*
* Copyright 2014 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "flatbuffers/flatbuffers.h"
#include "flatbuffers/idl.h"
#include "flatbuffers/util.h"
#include <limits>
#define FLATC_VERSION "1.3.0 (" __DATE__ ")"
static void Error(const std::string &err, bool usage = false,
bool show_exe_name = true);
// This struct allows us to create a table of all possible output generators
// for the various programming languages and formats we support.
struct Generator {
bool (*generate)(const flatbuffers::Parser &parser,
const std::string &path,
const std::string &file_name);
const char *generator_opt_short;
const char *generator_opt_long;
const char *lang_name;
flatbuffers::IDLOptions::Language lang;
const char *generator_help;
std::string (*make_rule)(const flatbuffers::Parser &parser,
const std::string &path,
const std::string &file_name);
};
const Generator generators[] = {
{ flatbuffers::GenerateBinary, "-b", "--binary", "binary",
flatbuffers::IDLOptions::kMAX,
"Generate wire format binaries for any data definitions",
flatbuffers::BinaryMakeRule },
{ flatbuffers::GenerateTextFile, "-t", "--json", "text",
flatbuffers::IDLOptions::kMAX,
"Generate text output for any data definitions",
flatbuffers::TextMakeRule },
{ flatbuffers::GenerateCPP, "-c", "--cpp", "C++",
flatbuffers::IDLOptions::kMAX,
"Generate C++ headers for tables/structs",
flatbuffers::CPPMakeRule },
{ flatbuffers::GenerateGo, "-g", "--go", "Go",
flatbuffers::IDLOptions::kGo,
"Generate Go files for tables/structs",
flatbuffers::GeneralMakeRule },
{ flatbuffers::GenerateGeneral, "-j", "--java", "Java",
flatbuffers::IDLOptions::kJava,
"Generate Java classes for tables/structs",
flatbuffers::GeneralMakeRule },
{ flatbuffers::GenerateJS, "-s", "--js", "JavaScript",
flatbuffers::IDLOptions::kMAX,
"Generate JavaScript code for tables/structs",
flatbuffers::JSMakeRule },
{ flatbuffers::GenerateGeneral, "-n", "--csharp", "C#",
flatbuffers::IDLOptions::kCSharp,
"Generate C# classes for tables/structs",
flatbuffers::GeneralMakeRule },
{ flatbuffers::GeneratePython, "-p", "--python", "Python",
flatbuffers::IDLOptions::kMAX,
"Generate Python files for tables/structs",
flatbuffers::GeneralMakeRule },
{ flatbuffers::GeneratePhp, nullptr, "--php", "PHP",
flatbuffers::IDLOptions::kMAX,
"Generate PHP files for tables/structs",
flatbuffers::GeneralMakeRule },
{ flatbuffers::GenerateGRPC, nullptr, "--grpc", "GRPC",
flatbuffers::IDLOptions::kMAX,
"Generate GRPC interfaces",
flatbuffers::CPPMakeRule },
};
const char *program_name = nullptr;
flatbuffers::Parser *parser = nullptr;
static void Error(const std::string &err, bool usage, bool show_exe_name) {
if (show_exe_name) printf("%s: ", program_name);
printf("%s\n", err.c_str());
if (usage) {
printf("usage: %s [OPTION]... FILE... [-- FILE...]\n", program_name);
for (size_t i = 0; i < sizeof(generators) / sizeof(generators[0]); ++i)
printf(" %-12s %s %s.\n",
generators[i].generator_opt_long,
generators[i].generator_opt_short
? generators[i].generator_opt_short
: " ",
generators[i].generator_help);
printf(
" -o PATH Prefix PATH to all generated files.\n"
" -I PATH Search for includes in the specified path.\n"
" -M Print make rules for generated files.\n"
" --version Print the version number of flatc and exit.\n"
" --strict-json Strict JSON: field names must be / will be quoted,\n"
" no trailing commas in tables/vectors.\n"
" --defaults-json Output fields whose value is the default when\n"
" writing JSON\n"
" --unknown-json Allow fields in JSON that are not defined in the\n"
" schema. These fields will be discared when generating\n"
" binaries.\n"
" --no-prefix Don\'t prefix enum values with the enum type in C++.\n"
" --scoped-enums Use C++11 style scoped and strongly typed enums.\n"
" also implies --no-prefix.\n"
" --gen-includes (deprecated), this is the default behavior.\n"
" If the original behavior is required (no include\n"
" statements) use --no-includes.\n"
" --no-includes Don\'t generate include statements for included\n"
" schemas the generated file depends on (C++).\n"
" --gen-mutable Generate accessors that can mutate buffers in-place.\n"
" --gen-onefile Generate single output file for C#.\n"
" --gen-name-strings Generate type name functions for C++.\n"
" --escape-proto-identifiers Disable appending '_' in namespaces names.\n"
" --raw-binary Allow binaries without file_indentifier to be read.\n"
" This may crash flatc given a mismatched schema.\n"
" --proto Input is a .proto, translate to .fbs.\n"
" --schema Serialize schemas instead of JSON (use with -b)\n"
"FILEs may be schemas, or JSON files (conforming to preceding schema)\n"
"FILEs after the -- must be binary flatbuffer format files.\n"
"Output files are named using the base file name of the input,\n"
"and written to the current directory or the path given by -o.\n"
"example: %s -c -b schema1.fbs schema2.fbs data.json\n",
program_name);
}
if (parser) delete parser;
exit(1);
}
int main(int argc, const char *argv[]) {
program_name = argv[0];
flatbuffers::IDLOptions opts;
std::string output_path;
const size_t num_generators = sizeof(generators) / sizeof(generators[0]);
bool generator_enabled[num_generators] = { false };
bool any_generator = false;
bool print_make_rules = false;
bool raw_binary = false;
bool schema_binary = false;
std::vector<std::string> filenames;
std::vector<const char *> include_directories;
size_t binary_files_from = std::numeric_limits<size_t>::max();
for (int argi = 1; argi < argc; argi++) {
std::string arg = argv[argi];
if (arg[0] == '-') {
if (filenames.size() && arg[1] != '-')
Error("invalid option location: " + arg, true);
if (arg == "-o") {
if (++argi >= argc) Error("missing path following: " + arg, true);
output_path = flatbuffers::ConCatPathFileName(argv[argi], "");
} else if(arg == "-I") {
if (++argi >= argc) Error("missing path following" + arg, true);
include_directories.push_back(argv[argi]);
} else if(arg == "--strict-json") {
opts.strict_json = true;
} else if(arg == "--no-js-exports") {
opts.skip_js_exports = true;
} else if(arg == "--defaults-json") {
opts.output_default_scalars_in_json = true;
} else if (arg == "--unknown-json") {
opts.skip_unexpected_fields_in_json = true;
} else if(arg == "--no-prefix") {
opts.prefixed_enums = false;
} else if(arg == "--scoped-enums") {
opts.prefixed_enums = false;
opts.scoped_enums = true;
} else if(arg == "--gen-mutable") {
opts.mutable_buffer = true;
} else if(arg == "--gen-name-strings") {
opts.generate_name_strings = true;
} else if(arg == "--gen-all") {
opts.generate_all = true;
opts.include_dependence_headers = false;
} else if(arg == "--gen-includes") {
// Deprecated, remove this option some time in the future.
printf("warning: --gen-includes is deprecated (it is now default)\n");
} else if(arg == "--no-includes") {
opts.include_dependence_headers = false;
} else if (arg == "--gen-onefile") {
opts.one_file = true;
} else if (arg == "--raw-binary") {
raw_binary = true;
} else if(arg == "--") { // Separator between text and binary inputs.
binary_files_from = filenames.size();
} else if(arg == "--proto") {
opts.proto_mode = true;
} else if (arg == "--escape-proto-identifiers") {
opts.escape_proto_identifiers = true;
} else if (arg == "--schema") {
schema_binary = true;
} else if(arg == "-M") {
print_make_rules = true;
} else if(arg == "--version") {
printf("flatc version %s\n", FLATC_VERSION);
exit(0);
} else {
for (size_t i = 0; i < num_generators; ++i) {
if (arg == generators[i].generator_opt_long ||
(generators[i].generator_opt_short &&
arg == generators[i].generator_opt_short)) {
generator_enabled[i] = true;
any_generator = true;
goto found;
}
}
Error("unknown commandline argument" + arg, true);
found:;
}
} else {
filenames.push_back(argv[argi]);
}
}
if (!filenames.size()) Error("missing input files", false, true);
if (opts.proto_mode) {
if (any_generator)
Error("cannot generate code directly from .proto files", true);
} else if (!any_generator) {
Error("no options: specify at least one generator.", true);
}
// Now process the files:
parser = new flatbuffers::Parser(opts);
for (auto file_it = filenames.begin();
file_it != filenames.end();
++file_it) {
std::string contents;
if (!flatbuffers::LoadFile(file_it->c_str(), true, &contents))
Error("unable to load file: " + *file_it);
bool is_binary = static_cast<size_t>(file_it - filenames.begin()) >=
binary_files_from;
if (is_binary) {
parser->builder_.Clear();
parser->builder_.PushFlatBuffer(
reinterpret_cast<const uint8_t *>(contents.c_str()),
contents.length());
if (!raw_binary) {
// Generally reading binaries that do not correspond to the schema
// will crash, and sadly there's no way around that when the binary
// does not contain a file identifier.
// We'd expect that typically any binary used as a file would have
// such an identifier, so by default we require them to match.
if (!parser->file_identifier_.length()) {
Error("current schema has no file_identifier: cannot test if \"" +
*file_it +
"\" matches the schema, use --raw-binary to read this file"
" anyway.");
} else if (!flatbuffers::BufferHasIdentifier(contents.c_str(),
parser->file_identifier_.c_str())) {
Error("binary \"" +
*file_it +
"\" does not have expected file_identifier \"" +
parser->file_identifier_ +
"\", use --raw-binary to read this file anyway.");
}
}
} else {
// Check if file contains 0 bytes.
if (contents.length() != strlen(contents.c_str())) {
Error("input file appears to be binary: " + *file_it, true);
}
if (flatbuffers::GetExtension(*file_it) == "fbs") {
// If we're processing multiple schemas, make sure to start each
// one from scratch. If it depends on previous schemas it must do
// so explicitly using an include.
delete parser;
parser = new flatbuffers::Parser(opts);
}
auto local_include_directory = flatbuffers::StripFileName(*file_it);
include_directories.push_back(local_include_directory.c_str());
include_directories.push_back(nullptr);
if (!parser->Parse(contents.c_str(), &include_directories[0],
file_it->c_str()))
Error(parser->error_, false, false);
if (schema_binary) {
parser->Serialize();
parser->file_extension_ = reflection::SchemaExtension();
}
include_directories.pop_back();
include_directories.pop_back();
}
std::string filebase = flatbuffers::StripPath(
flatbuffers::StripExtension(*file_it));
for (size_t i = 0; i < num_generators; ++i) {
parser->opts.lang = generators[i].lang;
if (generator_enabled[i]) {
if (!print_make_rules) {
flatbuffers::EnsureDirExists(output_path);
if (!generators[i].generate(*parser, output_path, filebase)) {
Error(std::string("Unable to generate ") +
generators[i].lang_name +
" for " +
filebase);
}
} else {
std::string make_rule = generators[i].make_rule(
*parser, output_path, *file_it);
if (!make_rule.empty())
printf("%s\n", flatbuffers::WordWrap(
make_rule, 80, " ", " \\").c_str());
}
}
}
if (opts.proto_mode) GenerateFBS(*parser, output_path, filebase, opts.escape_proto_identifiers);
// We do not want to generate code for the definitions in this file
// in any files coming up next.
parser->MarkGenerated();
}
delete parser;
return 0;
}
<|endoftext|> |
<commit_before>/* /////////////////////////////////////////////////////////////////////////
* File: entry.cpp
*
* Purpose: Entry-point implementation file for the mtgrep project.
*
* Created: 28th September 2015
* Updated: 28th September 2015
*
* www: http://www.synesis.com.au/
*
* Copyright (c) 2015, Synesis Software Pty Ltd.
* All rights reserved.
*
* The source code contained herein is subject to the accompanying license,
* https://github.com/synesissoftware/mtgrep/blob/master/LICENSE, which is
* an unmodifed form of the 4-clause BSD license.
*
* ////////////////////////////////////////////////////////////////////// */
/* /////////////////////////////////////////////////////////////////////////
* preprocessor control
*/
/* /////////////////////////////////////////////////////////////////////////
* includes
*/
/* Pantheios header files - 1 */
#include <pantheios/pan.hpp>
/* libCLImate header files */
#include <libclimate/main.hpp>
/* CLASP header files */
#include <systemtools/clasp/clasp.hpp>
/* FastFormat header files */
#include <fastformat/ff.hpp>
#include <fastformat/sinks/ostream.hpp>
/* Pantheios header files - 2 */
/* STLSoft header files */
#include <stlsoft/filesystem/read_line.hpp>
/* Standard C++ header files */
#include <iostream>
#include <regex>
/* /////////////////////////////////////////////////////////////////////////
* constants
*/
static int const verMajor = 0;
static int const verMinor = 0;
static int const verRevision = 8;
static char const* const ToolName = "mtgrep";
static char const* const Summary = "Simple grep program";
static char const* const Copyright = "Copyright (c) Synesis Software Pty Ltd";
static char const* const Description = "simple grep test program";
static char const* const Usage = "mtgrep { --help | --version | <pattern>}";
#ifdef STLSOFT_CF_ENUM_CLASS_SUPPORT
enum class Flags : int
#else
struct Flags { enum
#endif
{
MTGREP_F_IGNORECASE = 0x00000001,
#ifdef STLSOFT_CF_ENUM_CLASS_SUPPORT
#else
};
#endif
};
/* /////////////////////////////////////////////////////////////////////////
* globals
*/
extern "C"
clasp::alias_t const libCLImate_aliases[] =
{
// standard flags
CLASP_GAP_SECTION("Standard Flags:"),
CLASP_FLAG( NULL, "--help", "displays this help and exits"),
CLASP_FLAG( NULL, "--version", "displays version information and exits"),
// program logic
CLASP_GAP_SECTION("Matching Control:"),
CLASP_FLAG_ALIAS( "-y", "--ignore-case"),
CLASP_BIT_FLAG( "-i", "--ignore-case", Flags::MTGREP_F_IGNORECASE, "Ignore case distinctions in both the PATTERN and the input files"),
};
/* /////////////////////////////////////////////////////////////////////////
* helper functions
*/
static void show_usage(clasp_arguments_t const* args);
static void show_version(clasp_arguments_t const* args);
/* /////////////////////////////////////////////////////////////////////////
* main
*/
extern "C++"
int
libCLImate_program_main_Cpp(
clasp::arguments_t const* args
)
{
if(clasp::flag_specified(args, "--help"))
{
show_usage(args);
return EXIT_SUCCESS;
}
if(clasp::flag_specified(args, "--version"))
{
show_version(args);
return EXIT_SUCCESS;
}
int flags = 0;
clasp_checkAllFlags(args, libCLImate_aliases, &flags);
clasp::verify_all_flags_and_options_are_recognised(args, libCLImate_aliases);
if(0 == args->numValues)
{
ff::fmtln(std::cerr, "{0}: no pattern specified; use --help for usage\n", ToolName);
return EXIT_FAILURE;
}
std::regex::flag_type reflags = std::regex::flag_type(0);
if(Flags::MTGREP_F_IGNORECASE & flags)
{
reflags |= std::regex::icase;
}
std::string const pattern(args->values[0].value.ptr, args->values[0].value.len);
std::regex const re(pattern, reflags);
std::string line;
for(; stlsoft::read_line(stdin, line); )
{
if(std::regex_match(line, re))
{
ff::writeln(std::cout, line);
}
}
return EXIT_SUCCESS;
}
/* /////////////////////////////////////////////////////////////////////////
* helper functions
*/
static void show_usage(clasp_arguments_t const* args)
{
clasp_showUsage(
args
, libCLImate_aliases
, ToolName, Summary, Copyright, Description, Usage
, verMajor, verMinor, verRevision
, clasp_showHeaderByFILE, clasp_showBodyByFILE, stdout
, 0
, 0
, 4
, 1
);
}
static void show_version(clasp_arguments_t const* args)
{
clasp_showVersion(
args
, ToolName
, verMajor, verMinor, verRevision
, clasp_showVersionByFILE, stdout
, 0
);
}
/* ///////////////////////////// end of file //////////////////////////// */
<commit_msg>test.scratch.std.regex : + '--line-regexp' / '-x' / MTGREP_F_WHOLELINE<commit_after>/* /////////////////////////////////////////////////////////////////////////
* File: entry.cpp
*
* Purpose: Entry-point implementation file for the mtgrep project.
*
* Created: 28th September 2015
* Updated: 28th September 2015
*
* www: http://www.synesis.com.au/
*
* Copyright (c) 2015, Synesis Software Pty Ltd.
* All rights reserved.
*
* The source code contained herein is subject to the accompanying license,
* https://github.com/synesissoftware/mtgrep/blob/master/LICENSE, which is
* an unmodifed form of the 4-clause BSD license.
*
* ////////////////////////////////////////////////////////////////////// */
/* /////////////////////////////////////////////////////////////////////////
* preprocessor control
*/
/* /////////////////////////////////////////////////////////////////////////
* includes
*/
/* Pantheios header files - 1 */
#include <pantheios/pan.hpp>
/* libCLImate header files */
#include <libclimate/main.hpp>
/* CLASP header files */
#include <systemtools/clasp/clasp.hpp>
/* FastFormat header files */
#include <fastformat/ff.hpp>
#include <fastformat/sinks/ostream.hpp>
/* Pantheios header files - 2 */
/* STLSoft header files */
#include <stlsoft/filesystem/read_line.hpp>
/* Standard C++ header files */
#include <iostream>
#include <regex>
/* /////////////////////////////////////////////////////////////////////////
* constants
*/
static int const verMajor = 0;
static int const verMinor = 0;
static int const verRevision = 9;
static char const* const ToolName = "mtgrep";
static char const* const Summary = "Simple grep program";
static char const* const Copyright = "Copyright (c) Synesis Software Pty Ltd";
static char const* const Description = "simple grep test program";
static char const* const Usage = "mtgrep { --help | --version | <pattern>}";
#ifdef STLSOFT_CF_ENUM_CLASS_SUPPORT
enum class Flags : int
#else
struct Flags { enum
#endif
{
MTGREP_F_IGNORECASE = 0x00000001,
MTGREP_F_WHOLELINE = 0x00000002,
#ifdef STLSOFT_CF_ENUM_CLASS_SUPPORT
#else
};
#endif
};
/* /////////////////////////////////////////////////////////////////////////
* globals
*/
extern "C"
clasp::alias_t const libCLImate_aliases[] =
{
// standard flags
CLASP_GAP_SECTION("Standard Flags:"),
CLASP_FLAG( NULL, "--help", "displays this help and exits"),
CLASP_FLAG( NULL, "--version", "displays version information and exits"),
// program logic
CLASP_GAP_SECTION("Matching Control:"),
CLASP_FLAG_ALIAS( "-y", "--ignore-case"),
CLASP_BIT_FLAG( "-i", "--ignore-case", Flags::MTGREP_F_IGNORECASE, "Ignore case distinctions in both the PATTERN and the input files"),
CLASP_BIT_FLAG( "-x", "--line-regexp", Flags::MTGREP_F_WHOLELINE, "Select only those matches that exactly match the whole line"),
};
/* /////////////////////////////////////////////////////////////////////////
* helper functions
*/
static void show_usage(clasp_arguments_t const* args);
static void show_version(clasp_arguments_t const* args);
/* /////////////////////////////////////////////////////////////////////////
* main
*/
extern "C++"
int
libCLImate_program_main_Cpp(
clasp::arguments_t const* args
)
{
if(clasp::flag_specified(args, "--help"))
{
show_usage(args);
return EXIT_SUCCESS;
}
if(clasp::flag_specified(args, "--version"))
{
show_version(args);
return EXIT_SUCCESS;
}
int flags = 0;
clasp_checkAllFlags(args, libCLImate_aliases, &flags);
clasp::verify_all_flags_and_options_are_recognised(args, libCLImate_aliases);
if(0 == args->numValues)
{
ff::fmtln(std::cerr, "{0}: no pattern specified; use --help for usage\n", ToolName);
return EXIT_FAILURE;
}
std::regex::flag_type reflags = std::regex::flag_type(0);
std::regex_constants::match_flag_type maflags = std::regex_constants::match_default;
if(Flags::MTGREP_F_IGNORECASE & flags)
{
reflags |= std::regex::icase;
}
std::string const pattern(args->values[0].value.ptr, args->values[0].value.len);
std::regex const re(pattern, reflags);
std::string line;
for(; stlsoft::read_line(stdin, line); )
{
bool matched =
(Flags::MTGREP_F_WHOLELINE & flags)
? std::regex_match(line, re, maflags)
: std::regex_search(line, re, maflags)
;
if(matched)
{
ff::writeln(std::cout, line);
}
}
return EXIT_SUCCESS;
}
/* /////////////////////////////////////////////////////////////////////////
* helper functions
*/
static void show_usage(clasp_arguments_t const* args)
{
clasp_showUsage(
args
, libCLImate_aliases
, ToolName, Summary, Copyright, Description, Usage
, verMajor, verMinor, verRevision
, clasp_showHeaderByFILE, clasp_showBodyByFILE, stdout
, 0
, 0
, 4
, 1
);
}
static void show_version(clasp_arguments_t const* args)
{
clasp_showVersion(
args
, ToolName
, verMajor, verMinor, verRevision
, clasp_showVersionByFILE, stdout
, 0
);
}
/* ///////////////////////////// end of file //////////////////////////// */
<|endoftext|> |
<commit_before>
#include <gloperate-qtquick/Application.h>
#include <QUrl>
#include <QQmlContext>
#include <QSurfaceFormat>
#include <cppassist/cmdline/ArgumentParser.h>
#include <qmltoolbox/Application.h>
#include <gloperate/gloperate.h>
#include <gloperate/base/TimerManager.h>
#include <gloperate-qt/base/GLContext.h>
#include <gloperate-qt/base/GLContextFactory.h>
#include <gloperate-qtquick/QmlScriptContext.h>
#include <cppassist/logging/logging.h>
namespace gloperate_qtquick
{
void Application::initialize()
{
qmltoolbox::Application::initialize();
}
Application::Application(int & argc, char ** argv)
: QGuiApplication(argc, argv)
, m_environment()
, m_qmlEngine(&m_environment)
{
// Read command line options
cppassist::ArgumentParser argumentParser;
argumentParser.parse(argc, argv);
const auto contextFormat = argumentParser.value("--context");
if (argumentParser.isSet("-safemode"))
{
m_environment.setSafeMode(true);
}
// Create scripting context
m_environment.setupScripting(
cppassist::make_unique<gloperate_qtquick::QmlScriptContext>(&m_qmlEngine)
);
// Configure plugin paths
m_environment.componentManager()->addPluginPath(
gloperate::pluginPath(), cppexpose::PluginPathType::Internal
);
// Specify desired context format
gloperate::GLContextFormat format;
format.setVersion(3, 2);
format.setProfile(gloperate::GLContextFormat::Profile::Core);
format.setForwardCompatible(true);
if (!contextFormat.empty())
{
if (!format.initializeFromString(contextFormat))
{
// [TODO] Error: Invalid context string
}
}
// Convert and set Qt context format
QSurfaceFormat qFormat = gloperate_qt::GLContextFactory::toQSurfaceFormat(format);
QSurfaceFormat::setDefaultFormat(qFormat);
// Pass additional command line parameters on to the QML
QStringList paramsList;
auto params = argumentParser.params();
for (auto param : params) paramsList << QString::fromStdString(param);
m_qmlEngine.rootContext()->setContextProperty("commandLineParams", paramsList);
// Create global timer
QObject::connect(
&m_timer, &QTimer::timeout,
this, &Application::onTimer
);
m_timer.start(5);
// cppassist::setVerbosityLevel(7);
}
Application::~Application()
{
}
const QString & Application::gloperateModulePath() const
{
return m_qmlEngine.gloperateModulePath();
}
void Application::loadQml(const QString & path)
{
m_qmlEngine.load(QUrl::fromLocalFile(path));
}
const QmlEngine & Application::qmlEngine() const
{
return m_qmlEngine;
}
QmlEngine & Application::qmlEngine()
{
return m_qmlEngine;
}
const gloperate::Environment & Application::environment() const
{
return m_environment;
}
gloperate::Environment & Application::environment()
{
return m_environment;
}
void Application::onTimer()
{
// Update scripting timers
m_environment.timerManager()->update();
}
} // namespace gloperate_qtquick
<commit_msg>Remove debug logging verbosity configuration<commit_after>
#include <gloperate-qtquick/Application.h>
#include <QUrl>
#include <QQmlContext>
#include <QSurfaceFormat>
#include <cppassist/cmdline/ArgumentParser.h>
#include <qmltoolbox/Application.h>
#include <gloperate/gloperate.h>
#include <gloperate/base/TimerManager.h>
#include <gloperate-qt/base/GLContext.h>
#include <gloperate-qt/base/GLContextFactory.h>
#include <gloperate-qtquick/QmlScriptContext.h>
namespace gloperate_qtquick
{
void Application::initialize()
{
qmltoolbox::Application::initialize();
}
Application::Application(int & argc, char ** argv)
: QGuiApplication(argc, argv)
, m_environment()
, m_qmlEngine(&m_environment)
{
// Read command line options
cppassist::ArgumentParser argumentParser;
argumentParser.parse(argc, argv);
const auto contextFormat = argumentParser.value("--context");
if (argumentParser.isSet("-safemode"))
{
m_environment.setSafeMode(true);
}
// Create scripting context
m_environment.setupScripting(
cppassist::make_unique<gloperate_qtquick::QmlScriptContext>(&m_qmlEngine)
);
// Configure plugin paths
m_environment.componentManager()->addPluginPath(
gloperate::pluginPath(), cppexpose::PluginPathType::Internal
);
// Specify desired context format
gloperate::GLContextFormat format;
format.setVersion(3, 2);
format.setProfile(gloperate::GLContextFormat::Profile::Core);
format.setForwardCompatible(true);
if (!contextFormat.empty())
{
if (!format.initializeFromString(contextFormat))
{
// [TODO] Error: Invalid context string
}
}
// Convert and set Qt context format
QSurfaceFormat qFormat = gloperate_qt::GLContextFactory::toQSurfaceFormat(format);
QSurfaceFormat::setDefaultFormat(qFormat);
// Pass additional command line parameters on to the QML
QStringList paramsList;
auto params = argumentParser.params();
for (auto param : params) paramsList << QString::fromStdString(param);
m_qmlEngine.rootContext()->setContextProperty("commandLineParams", paramsList);
// Create global timer
QObject::connect(
&m_timer, &QTimer::timeout,
this, &Application::onTimer
);
m_timer.start(5);
}
Application::~Application()
{
}
const QString & Application::gloperateModulePath() const
{
return m_qmlEngine.gloperateModulePath();
}
void Application::loadQml(const QString & path)
{
m_qmlEngine.load(QUrl::fromLocalFile(path));
}
const QmlEngine & Application::qmlEngine() const
{
return m_qmlEngine;
}
QmlEngine & Application::qmlEngine()
{
return m_qmlEngine;
}
const gloperate::Environment & Application::environment() const
{
return m_environment;
}
gloperate::Environment & Application::environment()
{
return m_environment;
}
void Application::onTimer()
{
// Update scripting timers
m_environment.timerManager()->update();
}
} // namespace gloperate_qtquick
<|endoftext|> |
<commit_before>#include <iostream>
#include <fstream>
#include <chrono>
#include <random>
#include "os/task_t.h"
#include "os/task_system_t.h"
#include "os/parse.h"
#include "os/generator.h"
#include "os/scheduler.h"
#include "lib/io.h"
#include "lib/num.h"
int main(){
std::cout << "Hello world!" << std::endl;
{
std::cout << "TASK PRINT TEST" << std::endl;
os::task_t task;
std::cout << task << std::endl;
}
{
std::cout << "TASK SYSTEM PRINT TEST" << std::endl;
os::task_system_t task_system(5);
std::cout << task_system << std::endl;
}
{
std::cout << "READ FILE TEST" << std::endl;
std::ifstream ifs("system/0", std::ifstream::in);
char c = ifs.get();
while (ifs.good()){
std::cout << c;
c = ifs.get();
}
ifs.close();
std::cout << '\n';
}
{
std::cout << "PARSE FILE TEST" << std::endl;
os::task_system_t task_system;
std::cout << task_system << std::endl;
std::ifstream ifs("system/0", std::ifstream::in);
os::parse_task_system_stream(ifs, task_system);
ifs.close();
std::cout << task_system << std::endl;
}
{
std::cout << "GENERATE SYSTEM TEST" << std::endl;
os::task_system_t task_system;
std::cout << task_system << std::endl;
uint seed = std::chrono::system_clock::now().time_since_epoch().count();
std::default_random_engine generator(seed);
std::uniform_int_distribution<uint> distribution(0,100);
uint usage = 70;
uint n = 5;
os::generate_task_system(generator, distribution, usage, n, task_system);
std::cout << task_system << std::endl;
uint u = 0;
for(auto task : task_system){
u += task.wcet;
}
std::cout << u << std::endl;
}
{
std::cout << "SCHEDULER TEST" << std::endl;
os::task_system_t task_system;
std::cout << task_system << std::endl;
std::ifstream ifs("system/0", std::ifstream::in);
os::parse_task_system_stream(ifs, task_system);
ifs.close();
std::cout << task_system << std::endl;
}
return 0;
}<commit_msg>clean<commit_after>#include <iostream>
#include <fstream>
#include <chrono>
#include <random>
#include "os/task_t.h"
#include "os/task_system_t.h"
#include "os/parse.h"
#include "os/generator.h"
#include "os/scheduler.h"
#include "lib/io.h"
#include "lib/num.h"
int main(){
{
std::cout << "TASK PRINT TEST" << std::endl;
os::task_t task;
std::cout << task << std::endl;
std::cout << std::endl;
}
{
std::cout << "TASK SYSTEM PRINT TEST" << std::endl;
os::task_system_t task_system(5);
std::cout << task_system << std::endl;
std::cout << std::endl;
}
{
std::cout << "READ FILE TEST" << std::endl;
std::ifstream ifs("system/0", std::ifstream::in);
char c = ifs.get();
while (ifs.good()){
std::cout << c;
c = ifs.get();
}
ifs.close();
std::cout << '\n';
std::cout << std::endl;
}
{
std::cout << "PARSE FILE TEST" << std::endl;
os::task_system_t task_system;
std::cout << task_system << std::endl;
std::ifstream ifs("system/0", std::ifstream::in);
os::parse_task_system_stream(ifs, task_system);
ifs.close();
std::cout << task_system << std::endl;
std::cout << std::endl;
}
{
std::cout << "GENERATE SYSTEM TEST" << std::endl;
os::task_system_t task_system;
std::cout << task_system << std::endl;
uint seed = std::chrono::system_clock::now().time_since_epoch().count();
std::default_random_engine generator(seed);
std::uniform_int_distribution<uint> distribution(0,100);
uint usage = 70;
uint n = 5;
os::generate_task_system(generator, distribution, usage, n, task_system);
std::cout << task_system << std::endl;
uint u = 0;
for(auto task : task_system){
u += task.wcet;
}
std::cout << u << std::endl;
std::cout << std::endl;
}
{
std::cout << "SCHEDULER TEST" << std::endl;
os::task_system_t task_system;
std::cout << task_system << std::endl;
std::ifstream ifs("system/0", std::ifstream::in);
os::parse_task_system_stream(ifs, task_system);
ifs.close();
std::cout << task_system << std::endl;
std::cout << std::endl;
}
return 0;
}<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: arrdecl.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: hr $ $Date: 2006-06-19 21:57:15 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _SFX_ARRDECL_HXX
#define _SFX_ARRDECL_HXX
#include <tools/list.hxx>
#ifndef _SVARRAY_HXX
#include <svtools/svarray.hxx>
#endif
#include "minarray.hxx"
struct CntUpdateResult;
SV_DECL_PTRARR_DEL(CntUpdateResults_Impl, CntUpdateResult*, 4, 4)
class SfxObjectShell;
SV_DECL_PTRARR( SfxObjectShellArr_Impl, SfxObjectShell*, 4, 4 )
class SfxViewFrame;
SV_DECL_PTRARR( SfxViewFrameArr_Impl, SfxViewFrame*, 4, 4 )
class SfxViewShell;
SV_DECL_PTRARR( SfxViewShellArr_Impl, SfxViewShell*, 4, 4 )
class SfxObjectFactory;
typedef SfxObjectFactory* SfxObjectFactoryPtr;
SV_DECL_PTRARR( SfxObjectFactoryArr_Impl, SfxObjectFactoryPtr, 3, 3 )
struct SfxTbxCtrlFactory;
SV_DECL_PTRARR_DEL( SfxTbxCtrlFactArr_Impl, SfxTbxCtrlFactory*, 8, 4 )
struct SfxStbCtrlFactory;
SV_DECL_PTRARR_DEL( SfxStbCtrlFactArr_Impl, SfxStbCtrlFactory*, 8, 4 )
struct SfxMenuCtrlFactory;
SV_DECL_PTRARR_DEL( SfxMenuCtrlFactArr_Impl, SfxMenuCtrlFactory*, 2, 2 )
struct SfxChildWinFactory;
SV_DECL_PTRARR_DEL( SfxChildWinFactArr_Impl, SfxChildWinFactory*, 2, 2 )
class SfxModule;
SV_DECL_PTRARR( SfxModuleArr_Impl, SfxModule*, 2, 2 )
class SfxFilter;
DECL_PTRARRAY( SfxFilterArr_Impl, SfxFilter*, 4, 4 )
class SfxFrame;
typedef SfxFrame* SfxFramePtr;
SV_DECL_PTRARR( SfxFrameArr_Impl, SfxFramePtr, 4, 4 )
DECLARE_LIST( SfxFilterList_Impl, SfxFilter* )
struct SfxExternalLib_Impl;
typedef SfxExternalLib_Impl* SfxExternalLibPtr;
SV_DECL_PTRARR_DEL( SfxExternalLibArr_Impl, SfxExternalLibPtr, 2, 2 )
//class XEventListenerRef;
//typedef XEventListenerRef* XEventListenerPtr;
//SV_DECL_PTRARR_DEL( XEventListenerArr_Impl, XEventListenerPtr, 4, 4 )
//class XFrameRef;
//typedef XFrameRef* XFramePtr;
//SV_DECL_PTRARR_DEL( XFrameArr_Impl, XFramePtr, 4, 4 )
class SfxSlot;
typedef SfxSlot* SfxSlotPtr;
SV_DECL_PTRARR( SfxSlotArr_Impl, SfxSlotPtr, 20, 20 )
#endif
<commit_msg>INTEGRATION: CWS vgbugs07 (1.5.308); FILE MERGED 2007/06/04 13:34:36 vg 1.5.308.1: #i76605# Remove -I .../inc/module hack introduced by hedaburemove01<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: arrdecl.hxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: hr $ $Date: 2007-06-27 22:51:44 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _SFX_ARRDECL_HXX
#define _SFX_ARRDECL_HXX
#include <tools/list.hxx>
#ifndef _SVARRAY_HXX
#include <svtools/svarray.hxx>
#endif
#include <sfx2/minarray.hxx>
struct CntUpdateResult;
SV_DECL_PTRARR_DEL(CntUpdateResults_Impl, CntUpdateResult*, 4, 4)
class SfxObjectShell;
SV_DECL_PTRARR( SfxObjectShellArr_Impl, SfxObjectShell*, 4, 4 )
class SfxViewFrame;
SV_DECL_PTRARR( SfxViewFrameArr_Impl, SfxViewFrame*, 4, 4 )
class SfxViewShell;
SV_DECL_PTRARR( SfxViewShellArr_Impl, SfxViewShell*, 4, 4 )
class SfxObjectFactory;
typedef SfxObjectFactory* SfxObjectFactoryPtr;
SV_DECL_PTRARR( SfxObjectFactoryArr_Impl, SfxObjectFactoryPtr, 3, 3 )
struct SfxTbxCtrlFactory;
SV_DECL_PTRARR_DEL( SfxTbxCtrlFactArr_Impl, SfxTbxCtrlFactory*, 8, 4 )
struct SfxStbCtrlFactory;
SV_DECL_PTRARR_DEL( SfxStbCtrlFactArr_Impl, SfxStbCtrlFactory*, 8, 4 )
struct SfxMenuCtrlFactory;
SV_DECL_PTRARR_DEL( SfxMenuCtrlFactArr_Impl, SfxMenuCtrlFactory*, 2, 2 )
struct SfxChildWinFactory;
SV_DECL_PTRARR_DEL( SfxChildWinFactArr_Impl, SfxChildWinFactory*, 2, 2 )
class SfxModule;
SV_DECL_PTRARR( SfxModuleArr_Impl, SfxModule*, 2, 2 )
class SfxFilter;
DECL_PTRARRAY( SfxFilterArr_Impl, SfxFilter*, 4, 4 )
class SfxFrame;
typedef SfxFrame* SfxFramePtr;
SV_DECL_PTRARR( SfxFrameArr_Impl, SfxFramePtr, 4, 4 )
DECLARE_LIST( SfxFilterList_Impl, SfxFilter* )
struct SfxExternalLib_Impl;
typedef SfxExternalLib_Impl* SfxExternalLibPtr;
SV_DECL_PTRARR_DEL( SfxExternalLibArr_Impl, SfxExternalLibPtr, 2, 2 )
//class XEventListenerRef;
//typedef XEventListenerRef* XEventListenerPtr;
//SV_DECL_PTRARR_DEL( XEventListenerArr_Impl, XEventListenerPtr, 4, 4 )
//class XFrameRef;
//typedef XFrameRef* XFramePtr;
//SV_DECL_PTRARR_DEL( XFrameArr_Impl, XFramePtr, 4, 4 )
class SfxSlot;
typedef SfxSlot* SfxSlotPtr;
SV_DECL_PTRARR( SfxSlotArr_Impl, SfxSlotPtr, 20, 20 )
#endif
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2013-2016 John Connor
* Copyright (c) 2016-2017 The Vcash developers
*
* This file is part of vcash.
*
* vcash is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License with
* additional permissions to the one published by the Free Software
* Foundation, either version 3 of the License, or (at your option)
* any later version. For more information see LICENSE.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* Workaround bug in gcc 4.7: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=52680
*/
#if (defined __linux__)
#define _GLIBCXX_USE_NANOSLEEP 1
#endif // __linux__
#include <thread>
#include <coin/db.hpp>
#include <coin/db_env.hpp>
#include <coin/stack_impl.hpp>
#include <coin/utility.hpp>
using namespace coin;
db::db(const std::string & file_name, const std::string & file_mode
)
: m_is_read_only(false)
, m_file_name(file_name)
, m_Db(0)
, m_DbTxn(0)
, state_(state_none)
{
int ret;
m_is_read_only = (
!strchr(file_mode.c_str(), '+') && !strchr(file_mode.c_str(), 'w')
);
auto db_create = strchr(file_mode.c_str(), 'c');
std::int32_t flags = DB_THREAD;
if (db_create)
{
flags |= DB_CREATE;
}
/**
* Make sure no other threads can access the db_env for this scope.
*/
std::lock_guard<std::recursive_mutex> l1(db_env::mutex_DbEnv());
if (stack_impl::get_db_env()->open() == false)
{
throw std::runtime_error("database environment failed to open");
}
++stack_impl::get_db_env()->file_use_counts()[m_file_name];
m_Db = stack_impl::get_db_env()->Dbs()[m_file_name];
if (m_Db == 0)
{
m_Db = new Db(&stack_impl::get_db_env()->get_DbEnv(), 0);
ret = m_Db->open(
0, file_name.c_str(), "main", DB_BTREE, flags, 0
);
if (ret != 0)
{
delete m_Db, m_Db = 0;
--stack_impl::get_db_env()->file_use_counts()[m_file_name];
m_file_name = "";
throw std::runtime_error(
"failed to open database file " + file_name + ", ret = " +
std::to_string(ret)
);
}
if (db_create && exists("version") == false)
{
auto tmp = m_is_read_only;
m_is_read_only = false;
write_version(constants::version_client);
m_is_read_only = tmp;
}
stack_impl::get_db_env()->Dbs()[file_name] = m_Db;
}
/**
* Set state to state_opened.
*/
state_ = state_opened;
}
db::~db()
{
if (state_ == state_opened)
{
close();
}
}
void db::close()
{
if (m_Db && state_ == state_opened)
{
/**
* Set state to state_closed.
*/
state_ = state_closed;
if (m_DbTxn)
{
m_DbTxn->abort(), m_DbTxn = 0;
}
m_Db = 0;
/**
* Flush database activity from memory pool to disk log.
*/
auto minutes = 0;
if (m_is_read_only)
{
minutes = 1;
}
if (utility::is_chain_file(m_file_name))
{
minutes = 2;
}
if (
utility::is_chain_file(m_file_name) &&
utility::is_initial_block_download()
)
{
minutes = 5;
}
/**
* Make sure no other threads can access the db_env for this scope.
*/
std::lock_guard<std::recursive_mutex> l1(db_env::mutex_DbEnv());
if (stack_impl::get_db_env())
{
/**
* -dblogsize
*/
stack_impl::get_db_env()->get_DbEnv().txn_checkpoint(
minutes ? 100 * 1024 : 0, minutes, 0
);
--stack_impl::get_db_env()->file_use_counts()[m_file_name];
}
}
}
Db & db::get_Db()
{
return *m_Db;
}
Dbc * db::get_cursor()
{
if (m_Db)
{
Dbc * ptr_cursor = 0;
auto ret = m_Db->cursor(0, &ptr_cursor, 0);
if (ret != 0)
{
return 0;
}
return ptr_cursor;
}
return 0;
}
int db::read_at_cursor(
Dbc * ptr_cursor, data_buffer & key, data_buffer & value,
const std::int32_t flags
)
{
Dbt datKey;
if (
flags == DB_SET || flags == DB_SET_RANGE || flags == DB_GET_BOTH ||
flags == DB_GET_BOTH_RANGE
)
{
datKey.set_data(key.data());
datKey.set_size(static_cast<std::uint32_t> (key.size()));
}
Dbt datValue;
if (flags == DB_GET_BOTH || flags == DB_GET_BOTH_RANGE)
{
datValue.set_data(value.data());
datValue.set_size(static_cast<std::uint32_t> (value.size()));
}
datKey.set_flags(DB_DBT_MALLOC);
datValue.set_flags(DB_DBT_MALLOC);
int ret = ptr_cursor->get(&datKey, &datValue, flags);
if (ret != 0)
{
return ret;
}
else if (datKey.get_data() == 0 || datValue.get_data() == 0)
{
return 99999;
}
key.clear();
key.write(reinterpret_cast<char *>(datKey.get_data()), datKey.get_size());
value.clear();
value.write(
reinterpret_cast<char *>(datValue.get_data()), datValue.get_size()
);
std::memset(datKey.get_data(), 0, datKey.get_size());
std::memset(datValue.get_data(), 0, datValue.get_size());
free(datKey.get_data());
free(datValue.get_data());
return 0;
}
bool db::txn_begin()
{
if (m_Db == 0 || m_DbTxn)
{
return false;
}
auto ptxn = stack_impl::get_db_env()->txn_begin();
if (ptxn == 0)
{
return false;
}
m_DbTxn = ptxn;
return true;
}
bool db::txn_commit()
{
if (m_Db == 0 || m_DbTxn == 0)
{
return false;
}
auto ret = m_DbTxn->commit(0);
m_DbTxn = 0;
return ret == 0;
}
bool db::txn_abort()
{
if (m_Db == 0 || m_DbTxn == 0)
{
return false;
}
auto ret = m_DbTxn->abort();
m_DbTxn = 0;
return ret == 0;
}
bool db::rewrite(const std::string & file_name, const char * key_skip)
{
while (globals::instance().state() < globals::state_stopping)
{
if (
stack_impl::get_db_env()->file_use_counts().count(file_name) == 0 ||
stack_impl::get_db_env()->file_use_counts()[file_name] == 0
)
{
stack_impl::get_db_env()->close_Db(file_name);
stack_impl::get_db_env()->checkpoint_lsn(file_name);
stack_impl::get_db_env()->file_use_counts().erase(file_name);
auto success = true;
log_debug("DB is rewriting " << file_name << ".");
std::string file_name_tmp = file_name + ".tmp";
db d(file_name.c_str(), "r");
Db * ptr_Db_copy = new Db(
&stack_impl::get_db_env()->get_DbEnv(), 0
);
auto ret = ptr_Db_copy->open(
0, file_name_tmp.c_str(), "main", DB_BTREE, DB_CREATE, 0
);
if (ret > 0)
{
log_error(
"DB is failed copying database " << file_name_tmp << "."
);
success = false;
}
auto ptr_cursor = d.get_cursor();
if (ptr_cursor)
{
while (success)
{
/**
* Read the next record.
*/
data_buffer key, value;
auto ret = d.read_at_cursor(
ptr_cursor, key, value, DB_NEXT
);
if (ret == DB_NOTFOUND)
{
ptr_cursor->close();
break;
}
else if (ret != 0)
{
ptr_cursor->close();
success = false;
break;
}
if (
key_skip && std::strncmp(key.data(), key_skip,
std::min(key.size(), std::strlen(key_skip))) == 0
)
{
continue;
}
/**
* Check if the version needs to be updated.
*/
if (std::strncmp(key.data(), "\x07version", 8) == 0)
{
value.clear();
/**
* Write the version.
*/
value.write_uint32(constants::version_client);
}
Dbt dbt_key(
key.data(), static_cast<std::uint32_t> (key.size())
);
Dbt dbt_value(
value.data(), static_cast<std::uint32_t> (value.size())
);
auto ret2 = ptr_Db_copy->put(
0, &dbt_key, &dbt_value, DB_NOOVERWRITE
);
if (ret2 > 0)
{
success = false;
}
}
}
if (success)
{
d.close();
stack_impl::get_db_env()->close_Db(file_name);
if (ptr_Db_copy->close(0))
{
success = false;
}
delete ptr_Db_copy;
}
if (success)
{
Db dbA(&stack_impl::get_db_env()->get_DbEnv(), 0);
if (dbA.remove(file_name.c_str(), 0, 0))
{
success = false;
}
Db dbB(&stack_impl::get_db_env()->get_DbEnv(), 0);
if (
dbB.rename(file_name_tmp.c_str(), 0, file_name.c_str(), 0)
)
{
success = false;
}
}
if (success == false)
{
log_error("DB rewrite " << file_name_tmp << " failed.");
}
return success;
}
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
return false;
}
const std::string & db::file_name() const
{
return m_file_name;
}
bool db::write_version(const std::int32_t & version)
{
return write(std::string("version"), version);
}
<commit_msg>Fix Windows 'illegal token' (and others) errors Related to windows.h, as it seems to have made min/max into their own macros<commit_after>/*
* Copyright (c) 2013-2016 John Connor
* Copyright (c) 2016-2017 The Vcash developers
*
* This file is part of vcash.
*
* vcash is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License with
* additional permissions to the one published by the Free Software
* Foundation, either version 3 of the License, or (at your option)
* any later version. For more information see LICENSE.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* Workaround bug in gcc 4.7: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=52680
*/
#if (defined __linux__)
#define _GLIBCXX_USE_NANOSLEEP 1
#endif // __linux__
#include <thread>
#include <coin/db.hpp>
#include <coin/db_env.hpp>
#include <coin/stack_impl.hpp>
#include <coin/utility.hpp>
using namespace coin;
db::db(const std::string & file_name, const std::string & file_mode
)
: m_is_read_only(false)
, m_file_name(file_name)
, m_Db(0)
, m_DbTxn(0)
, state_(state_none)
{
int ret;
m_is_read_only = (
!strchr(file_mode.c_str(), '+') && !strchr(file_mode.c_str(), 'w')
);
auto db_create = strchr(file_mode.c_str(), 'c');
std::int32_t flags = DB_THREAD;
if (db_create)
{
flags |= DB_CREATE;
}
/**
* Make sure no other threads can access the db_env for this scope.
*/
std::lock_guard<std::recursive_mutex> l1(db_env::mutex_DbEnv());
if (stack_impl::get_db_env()->open() == false)
{
throw std::runtime_error("database environment failed to open");
}
++stack_impl::get_db_env()->file_use_counts()[m_file_name];
m_Db = stack_impl::get_db_env()->Dbs()[m_file_name];
if (m_Db == 0)
{
m_Db = new Db(&stack_impl::get_db_env()->get_DbEnv(), 0);
ret = m_Db->open(
0, file_name.c_str(), "main", DB_BTREE, flags, 0
);
if (ret != 0)
{
delete m_Db, m_Db = 0;
--stack_impl::get_db_env()->file_use_counts()[m_file_name];
m_file_name = "";
throw std::runtime_error(
"failed to open database file " + file_name + ", ret = " +
std::to_string(ret)
);
}
if (db_create && exists("version") == false)
{
auto tmp = m_is_read_only;
m_is_read_only = false;
write_version(constants::version_client);
m_is_read_only = tmp;
}
stack_impl::get_db_env()->Dbs()[file_name] = m_Db;
}
/**
* Set state to state_opened.
*/
state_ = state_opened;
}
db::~db()
{
if (state_ == state_opened)
{
close();
}
}
void db::close()
{
if (m_Db && state_ == state_opened)
{
/**
* Set state to state_closed.
*/
state_ = state_closed;
if (m_DbTxn)
{
m_DbTxn->abort(), m_DbTxn = 0;
}
m_Db = 0;
/**
* Flush database activity from memory pool to disk log.
*/
auto minutes = 0;
if (m_is_read_only)
{
minutes = 1;
}
if (utility::is_chain_file(m_file_name))
{
minutes = 2;
}
if (
utility::is_chain_file(m_file_name) &&
utility::is_initial_block_download()
)
{
minutes = 5;
}
/**
* Make sure no other threads can access the db_env for this scope.
*/
std::lock_guard<std::recursive_mutex> l1(db_env::mutex_DbEnv());
if (stack_impl::get_db_env())
{
/**
* -dblogsize
*/
stack_impl::get_db_env()->get_DbEnv().txn_checkpoint(
minutes ? 100 * 1024 : 0, minutes, 0
);
--stack_impl::get_db_env()->file_use_counts()[m_file_name];
}
}
}
Db & db::get_Db()
{
return *m_Db;
}
Dbc * db::get_cursor()
{
if (m_Db)
{
Dbc * ptr_cursor = 0;
auto ret = m_Db->cursor(0, &ptr_cursor, 0);
if (ret != 0)
{
return 0;
}
return ptr_cursor;
}
return 0;
}
int db::read_at_cursor(
Dbc * ptr_cursor, data_buffer & key, data_buffer & value,
const std::int32_t flags
)
{
Dbt datKey;
if (
flags == DB_SET || flags == DB_SET_RANGE || flags == DB_GET_BOTH ||
flags == DB_GET_BOTH_RANGE
)
{
datKey.set_data(key.data());
datKey.set_size(static_cast<std::uint32_t> (key.size()));
}
Dbt datValue;
if (flags == DB_GET_BOTH || flags == DB_GET_BOTH_RANGE)
{
datValue.set_data(value.data());
datValue.set_size(static_cast<std::uint32_t> (value.size()));
}
datKey.set_flags(DB_DBT_MALLOC);
datValue.set_flags(DB_DBT_MALLOC);
int ret = ptr_cursor->get(&datKey, &datValue, flags);
if (ret != 0)
{
return ret;
}
else if (datKey.get_data() == 0 || datValue.get_data() == 0)
{
return 99999;
}
key.clear();
key.write(reinterpret_cast<char *>(datKey.get_data()), datKey.get_size());
value.clear();
value.write(
reinterpret_cast<char *>(datValue.get_data()), datValue.get_size()
);
std::memset(datKey.get_data(), 0, datKey.get_size());
std::memset(datValue.get_data(), 0, datValue.get_size());
free(datKey.get_data());
free(datValue.get_data());
return 0;
}
bool db::txn_begin()
{
if (m_Db == 0 || m_DbTxn)
{
return false;
}
auto ptxn = stack_impl::get_db_env()->txn_begin();
if (ptxn == 0)
{
return false;
}
m_DbTxn = ptxn;
return true;
}
bool db::txn_commit()
{
if (m_Db == 0 || m_DbTxn == 0)
{
return false;
}
auto ret = m_DbTxn->commit(0);
m_DbTxn = 0;
return ret == 0;
}
bool db::txn_abort()
{
if (m_Db == 0 || m_DbTxn == 0)
{
return false;
}
auto ret = m_DbTxn->abort();
m_DbTxn = 0;
return ret == 0;
}
bool db::rewrite(const std::string & file_name, const char * key_skip)
{
while (globals::instance().state() < globals::state_stopping)
{
if (
stack_impl::get_db_env()->file_use_counts().count(file_name) == 0 ||
stack_impl::get_db_env()->file_use_counts()[file_name] == 0
)
{
stack_impl::get_db_env()->close_Db(file_name);
stack_impl::get_db_env()->checkpoint_lsn(file_name);
stack_impl::get_db_env()->file_use_counts().erase(file_name);
auto success = true;
log_debug("DB is rewriting " << file_name << ".");
std::string file_name_tmp = file_name + ".tmp";
db d(file_name.c_str(), "r");
Db * ptr_Db_copy = new Db(
&stack_impl::get_db_env()->get_DbEnv(), 0
);
auto ret = ptr_Db_copy->open(
0, file_name_tmp.c_str(), "main", DB_BTREE, DB_CREATE, 0
);
if (ret > 0)
{
log_error(
"DB is failed copying database " << file_name_tmp << "."
);
success = false;
}
auto ptr_cursor = d.get_cursor();
if (ptr_cursor)
{
while (success)
{
/**
* Read the next record.
*/
data_buffer key, value;
auto ret = d.read_at_cursor(
ptr_cursor, key, value, DB_NEXT
);
if (ret == DB_NOTFOUND)
{
ptr_cursor->close();
break;
}
else if (ret != 0)
{
ptr_cursor->close();
success = false;
break;
}
if (
key_skip && std::strncmp(key.data(), key_skip,
(std::min)(key.size(), std::strlen(key_skip))) == 0
)
{
continue;
}
/**
* Check if the version needs to be updated.
*/
if (std::strncmp(key.data(), "\x07version", 8) == 0)
{
value.clear();
/**
* Write the version.
*/
value.write_uint32(constants::version_client);
}
Dbt dbt_key(
key.data(), static_cast<std::uint32_t> (key.size())
);
Dbt dbt_value(
value.data(), static_cast<std::uint32_t> (value.size())
);
auto ret2 = ptr_Db_copy->put(
0, &dbt_key, &dbt_value, DB_NOOVERWRITE
);
if (ret2 > 0)
{
success = false;
}
}
}
if (success)
{
d.close();
stack_impl::get_db_env()->close_Db(file_name);
if (ptr_Db_copy->close(0))
{
success = false;
}
delete ptr_Db_copy;
}
if (success)
{
Db dbA(&stack_impl::get_db_env()->get_DbEnv(), 0);
if (dbA.remove(file_name.c_str(), 0, 0))
{
success = false;
}
Db dbB(&stack_impl::get_db_env()->get_DbEnv(), 0);
if (
dbB.rename(file_name_tmp.c_str(), 0, file_name.c_str(), 0)
)
{
success = false;
}
}
if (success == false)
{
log_error("DB rewrite " << file_name_tmp << " failed.");
}
return success;
}
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
return false;
}
const std::string & db::file_name() const
{
return m_file_name;
}
bool db::write_version(const std::int32_t & version)
{
return write(std::string("version"), version);
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.