text
stringlengths
54
60.6k
<commit_before>/* Copyright (c) 2013, Richard Martin 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 Richard Martin 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 RICHARD MARTIN 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 purpose of this class (and its PIMPL) is to provide a useful implementation of a sliding window which allows pointer-base access to the fundamental datatype array. This is mostly useful for compatability with existing C programmes. Chief among these, at least the primary motivation for this library, is to interface with the GNU Scientific Library, which expects arrays of base types. Simply, the class looks like this: ........1010100110101111001010100100100........................ |--------| window (valid 0 to 9 inc) |--------| window + one tick. (valid 1 to 10 inc) But this data is a member of (potentially) larger file: 0100010010101001101011110010101001001000101100101111101110101000 This class provides a mechanism for the asynchronous loading of data from the file and presenting it in a moving-window interface that is compatabile with the DataSource parent class. */ #ifndef FileSource_HEADER #define FileSource_HEADER #include <string> #include <cmath> #include <exception> #include <memory> #include <algorithm> #include "DataSource.hpp" #include "AsyncIOImpl.hpp" using std::string; using std::unique_ptr; using std::ifstream; using std::exception; using std::move; namespace libsim { template <class T> class FileSourceImpl; template <class T> class FileSource : public DataSource<T> { private: unique_ptr<FileSourceImpl<T>> impl; public: FileSource(string _fn, unsigned int _wsize, launch _policy, int _datapoints) : DataSource<T>(_wsize) { impl = unique_ptr<FileSourceImpl<T>>(new FileSourceImpl<T>(_fn, _wsize, _datapoints)); } FileSource(string _fn, unsigned int _wsize, int _datapoints) : DataSource<T>(_wsize) { impl = unique_ptr<FileSourceImpl<T>>(new FileSourceImpl<T>(_fn, _wsize, launch::deferred, _datapoints)); } FileSource(string _fn, unsigned int _wsize, launch _policy) : DataSource<T>(_wsize) { impl = unique_ptr<FileSourceImpl<T>>(new FileSourceImpl<T>(_fn, _wsize, _policy, -1)); } FileSource(string _fn, unsigned int _wsize) : DataSource<T>(_wsize) { impl = unique_ptr<FileSourceImpl<T>>(new FileSourceImpl<T>(_fn, _wsize, launch::deferred, -1)); } //No copying. That would leave this object in a horrendous state //and I don't want to figure out how to do it. FileSource(FileSource<T> const & cpy) = delete; FileSource<T>& operator =(const FileSource<T>& cpy) = delete; //Moving is fine, so support rvalue move and move assignment operators. FileSource(FileSource<T> && mv) : DataSource<T>(mv.windowsize), impl(move(mv.impl)) {} FileSource<T>& operator =(FileSource<T> && mv) { impl = move(mv.impl); return *this; } ~FileSource() = default; inline virtual T * get() override { return impl->get(); }; inline virtual void tick() override { impl->tock(); }; inline virtual bool eods() override { return impl->eods(); }; }; template <class T> class FileSourceImpl : public AsyncIOImpl<T> { private: ifstream file; virtual vector<T> ioinit() override { auto tmpdata = vector<T>(); tmpdata.reserve(this->read_extent); unsigned int i = 0; for( ; i < this->read_extent; i++) { if((this->datapoints_read + i) == this->datapoints_limit) break; if(file.eof()) break; string stemp; getline(file, stemp); stringstream ss(stemp); T temp; ss >> temp; tmpdata.push_back(temp); this->datapoints_read++; } this->readyio = true; return tmpdata; } virtual vector<T> ionext() override { //Create and configure the //return auto tmpdata = vector<T>(); tmpdata.reserve(this->windowsize); //Now the load unsigned int i = 0; for( ; i < this->windowsize; i++) { if(this->datapoints_read == this->datapoints_limit) break; if(file.eof()) break; string stemp; getline(file, stemp); stringstream ss(stemp); T temp; ss >> temp; tmpdata.push_back(temp); this->datapoints_read++; } this->readyio = true; return tmpdata; } public: FileSourceImpl(string filename, unsigned int _wsize, launch _policy, int datapoints) : AsyncIOImpl<T>(_wsize, _policy, datapoints), file(filename) { } //Absolutely no copying. FileSourceImpl(FileSourceImpl<T> const & cpy) = delete; FileSourceImpl<T>& operator =(const FileSourceImpl<T>& cpy) = delete; FileSourceImpl(FileSourceImpl<T> && mv) = delete; FileSourceImpl<T>& operator =(FileSourceImpl<T> && mv) = delete; ~FileSourceImpl() = default; }; } #endif <commit_msg>Fix a small bug which meant that trunking was ignored when it occured during the intial load<commit_after>/* Copyright (c) 2013, Richard Martin 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 Richard Martin 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 RICHARD MARTIN 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 purpose of this class (and its PIMPL) is to provide a useful implementation of a sliding window which allows pointer-base access to the fundamental datatype array. This is mostly useful for compatability with existing C programmes. Chief among these, at least the primary motivation for this library, is to interface with the GNU Scientific Library, which expects arrays of base types. Simply, the class looks like this: ........1010100110101111001010100100100........................ |--------| window (valid 0 to 9 inc) |--------| window + one tick. (valid 1 to 10 inc) But this data is a member of (potentially) larger file: 0100010010101001101011110010101001001000101100101111101110101000 This class provides a mechanism for the asynchronous loading of data from the file and presenting it in a moving-window interface that is compatabile with the DataSource parent class. */ #ifndef FileSource_HEADER #define FileSource_HEADER #include <string> #include <cmath> #include <exception> #include <memory> #include <algorithm> #include <limits> #include "DataSource.hpp" #include "AsyncIOImpl.hpp" using std::string; using std::unique_ptr; using std::ifstream; using std::exception; using std::move; using std::numeric_limits; namespace libsim { template <class T> class FileSourceImpl; template <class T> class FileSource : public DataSource<T> { private: unique_ptr<FileSourceImpl<T>> impl; public: FileSource(string _fn, unsigned int _wsize, launch _policy, int _datapoints) : DataSource<T>(_wsize) { impl = unique_ptr<FileSourceImpl<T>>(new FileSourceImpl<T>(_fn, _wsize, _datapoints)); } FileSource(string _fn, unsigned int _wsize, int _datapoints) : DataSource<T>(_wsize) { impl = unique_ptr<FileSourceImpl<T>>(new FileSourceImpl<T>(_fn, _wsize, launch::deferred, _datapoints)); } FileSource(string _fn, unsigned int _wsize, launch _policy) : DataSource<T>(_wsize) { impl = unique_ptr<FileSourceImpl<T>>(new FileSourceImpl<T>(_fn, _wsize, _policy, numeric_limits<unsigned int>::max())); } FileSource(string _fn, unsigned int _wsize) : DataSource<T>(_wsize) { impl = unique_ptr<FileSourceImpl<T>>(new FileSourceImpl<T>(_fn, _wsize, launch::deferred, numeric_limits<unsigned int>::max())); } //No copying. That would leave this object in a horrendous state //and I don't want to figure out how to do it. FileSource(FileSource<T> const & cpy) = delete; FileSource<T>& operator =(const FileSource<T>& cpy) = delete; //Moving is fine, so support rvalue move and move assignment operators. FileSource(FileSource<T> && mv) : DataSource<T>(mv.windowsize), impl(move(mv.impl)) {} FileSource<T>& operator =(FileSource<T> && mv) { impl = move(mv.impl); return *this; } ~FileSource() = default; inline virtual T * get() override { return impl->get(); }; inline virtual void tick() override { impl->tock(); }; inline virtual bool eods() override { return impl->eods(); }; }; template <class T> class FileSourceImpl : public AsyncIOImpl<T> { private: ifstream file; virtual vector<T> ioinit() override { auto tmpdata = vector<T>(); tmpdata.reserve(this->read_extent); unsigned int i = 0; for( ; i < this->read_extent; i++) { if(this->datapoints_read == this->datapoints_limit) break; if(file.eof()) break; string stemp; getline(file, stemp); stringstream ss(stemp); T temp; ss >> temp; tmpdata.push_back(temp); this->datapoints_read++; } this->readyio = true; return tmpdata; } virtual vector<T> ionext() override { //Create and configure the //return auto tmpdata = vector<T>(); tmpdata.reserve(this->windowsize); //Now the load unsigned int i = 0; for( ; i < this->windowsize; i++) { if(this->datapoints_read == this->datapoints_limit) break; if(file.eof()) break; string stemp; getline(file, stemp); stringstream ss(stemp); T temp; ss >> temp; tmpdata.push_back(temp); this->datapoints_read++; } this->readyio = true; return tmpdata; } public: FileSourceImpl(string filename, unsigned int _wsize, launch _policy, unsigned int datapoints) : AsyncIOImpl<T>(_wsize, _policy, datapoints), file(filename) { } //Absolutely no copying. FileSourceImpl(FileSourceImpl<T> const & cpy) = delete; FileSourceImpl<T>& operator =(const FileSourceImpl<T>& cpy) = delete; FileSourceImpl(FileSourceImpl<T> && mv) = delete; FileSourceImpl<T>& operator =(FileSourceImpl<T> && mv) = delete; ~FileSourceImpl() = default; }; } #endif <|endoftext|>
<commit_before>#ifndef HUMPConfig_HPP #define HUMPConfig_HPP #include <string> #include <cstring> #include <cstdlib> #include <stdexcept> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <list> #include <vector> #include <cmath> #include <boost/smart_ptr.hpp> #include <boost/numeric/ublas/storage.hpp> #include <boost/algorithm/string.hpp> #include <boost/algorithm/string/replace.hpp> #include <boost/format.hpp> #include <fstream> #include <eigen3/Eigen/Dense> #include "../config/config.hpp" #include "object.hpp" /** version of the library */ #define HUMP_VERSION_MAJOR 2 #define HUMP_VERSION_MINOR 0 //definition of the macro ASSERT #ifndef DEBUG #define ASSERT(x) #else #define ASSERT(x) \ if (! (x)) \ { \ cout << "ERROR!! Assert " << #x << " failed\n"; \ cout << " on line " << __LINE__ << "\n"; \ cout << " in file " << __FILE__ << "\n"; \ } #endif using namespace std; using namespace Eigen; /** This is the main namespace of the library */ namespace HUMotion{ typedef boost::shared_ptr<Object> objectPtr;/**< shared pointer to an object in the scenario */ const double PHI = (-log(2.0)/log(TB));/**< parameter to control when the bounce posture is reached */ const double AP = 15.0*static_cast<double>(M_PI)/180; /**< aperture of the fingers when approaching to pick [rad] */ const double BLANK_PERCENTAGE = 0.10; /**< percentage of steps to eliminate when either reaching to grasp an object OR move at the beginning of a move movement [0,1]*/ const int N_STEP_MIN = 5; /**< minimum number of steps */ const int N_STEP_MAX = 50; /**< maximum number of steps */ const double W_RED_MIN = 1; /**< minimum value of angular velocity reduction when approaching */ const double W_RED_MAX = 15; /**< maximum value of angular velocity reduction when approaching */ /** this struct defines the Denavit-Hartenberg kinematic parameters */ typedef struct{ vector<double> d; /**< distances between consecutive frames along the y axes in [mm] */ vector<double> a; /**< distances between concecutive frames along the z axes in [mm] */ vector<double> alpha; /**< angle around the x axes between consecutive z axes in [rad] */ vector<double> theta; /**< angle around the z axes between consecutive x axes in [rad] */ } DHparameters; /** this struct defines the barrett hand */ typedef struct{ double maxAperture; /**< [mm] max aperture of the hand in [mm] */ double Aw; /**< smallest distance between F1 and F2 in [mm] */ double A1; /**< length of the 1st part of the finger in [mm] */ double A2; /**< length of the first phalax in [mm] */ double A3; /**< length of the second phalax in [mm] */ double D3; /**< depth of the fingertip in [mm] */ double phi2; /**< angular displacement between the 1st part of the finger and the 1st phalax in [rad] */ double phi3; /**< angular displacement between the 1st and the 2nd phalax in [rad] */ vector<int> rk; /**< r parameters of the barrett hand */ vector<int> jk; /**< j parameters of the barrett hand */ } BarrettHand; /** this struct defines a human finger */ typedef struct{ double ux; /**< position of the finger with respect to the center of the palm along the x axis in [mm] */ double uy; /**< position of the finger with respect to the center of the palm along the y axis in [mm] */ double uz; /**< position of the finger with respect to the center of the palm along the z axis in [mm] */ DHparameters finger_specs; /**< the Denavit-Hartenberg parameters of the finger */ } HumanFinger; /** this struct defines a human thumb */ typedef struct{ double uTx; /**< position of the thumb with respect to the center of the palm along the x axis in [mm] */ double uTy; /**< position of the thumb with respect to the center of the palm along the y axis in [mm] */ double uTz; /**< position of the thumb with respect to the center of the palm along the z axis in [mm] */ DHparameters thumb_specs; /**< the Denavit-Hartenberg parameters of the thumb */ } HumanThumb; /** this struct defines a human hand */ typedef struct{ vector<HumanFinger> fingers; /**< fingers of the hand */ HumanThumb thumb; /**< thumb of the hand */ double maxAperture; /**< max aperture of the hand in [mm] */ } HumanHand; /** this struct defines the parameters of the movement */ typedef struct{ int arm_code; /**< the code of the arm: 0 = both arms, 1 = right arm, 2 = left arm */ int hand_code;/**< the code of the hand: 0 = human hand, 1 = barrett hand */ int griptype; /**< the type of the grip */ string mov_infoline; /**< description of the movement */ double dHO;/**< distanche hand-target*/ std::vector<double> finalHand;/**< final posture of the hand */ std::vector<double> target;/**< target / location to reach: target(0)=x, target(1)=y, target(2)=z, target(3)=roll, target(4)=pitch, target(6)=yaw,*/ objectPtr obj; /**< object involved in the movement. The info of the object have to be updated according to the selected movement */ bool approach;/**< true to use the approach options, false otherwise */ bool retreat;/**< true to use the retreat options, false otherwise */ std::vector<double> pre_grasp_approach; /**< (0)= x component, (1)= y component, (2)= z component, (3)= distance from the target*/ std::vector<double> post_grasp_retreat; /**< (0)= x component, (1)= y component, (2)= z component, (3)= distance from the target*/ std::vector<double> pre_place_approach; /**< (0)= x component, (1)= y component, (2)= z component, (3)= distance from the target*/ std::vector<double> post_place_retreat; /**< (0)= x component, (1)= y component, (2)= z component, (3)= distance from the target*/ bool rand_init; /**< true to select randon initialization in "plan" stages */ bool coll; /**< true to enable collisions with the environment (body of the robot included) */ bool use_move_plane; /**< true to constrain the end-effector to move on a plane in move movements, false otherwise*/ std::vector<double> plane_params; /**< plane cartesian parameters in move movements: a*x+b*y+c*z+d=0. a=plane_params(0), b=plane_params(1), c=plane_params(2), d=plane_params(3) */ }mov_params; /** this struct defines the boundary conditions of the movement*/ typedef struct{ vector<double> vel_0; /**< initial velocity of the joints in [rad/s] */ vector<double> vel_f; /**< final velocity of the joints in [rad/s] */ vector<double> acc_0; /**< initial acceleration of the joints in [rad/s²] */ vector<double> acc_f; /**< final acceleration of the joints in [rad/s²] */ } boundaryConditions; /** this struct defines the tolerances that have to be set before planning the trajectory*/ typedef struct{ mov_params mov_specs; /**< specifications of the movement */ vector<double> tolsArm; /**< radius of the spheres along the arm in [mm] */ MatrixXd tolsHand; /**< radius of the spheres along the fingers in [mm] */ MatrixXd final_tolsObstacles; /**< tolerances of the final posture against the obstacles in [mm] */ vector< MatrixXd > singleArm_tolsTarget; /**< tolerances of the trajectory against the target in [mm] */ vector< MatrixXd > singleArm_tolsObstacles; /**< tolerances of the trajectory against the obstacles in [mm] */ double tolTarPos; /**< tolerance of the final position of the hand against the target in [mm] */ double tolTarOr; /**< tolerance of the final orientation of the hand against the target in [mm] */ boundaryConditions bounds; /**< boundary condistions of the bounce problem */ vector<double> vel_approach; /**< velocity of the joints in [rad/s] at the beginning of the approach stage */ vector<double> acc_approach; /**< acceleration of the joints in [rad/s²] at the beginning of the approach stage */ vector<double> lambda_final; /**< weights for the final posture optimization */ vector<double> lambda_bounce; /**< weights for the bounce posture optimization */ vector<double> w_max; /**< maximum angular velocity for each joint [rad/s] */ bool obstacle_avoidance; /**< true to avoid obstacle */ bool target_avoidance; /**< true to avoid the target during the motion */ } hump_params; /** This struct defines the result of the planned trajectory */ typedef struct{ int mov_type;/**< type of the planned movement */ int status;/**< status code of the planning */ string status_msg;/**< status message of the planning */ string object_id;/**< identity of the object involved in the movement */ vector<MatrixXd> trajectory_stages;/**< sequence of the trajectories */ vector<MatrixXd> velocity_stages;/**< sequence of the velocities */ vector<MatrixXd> acceleration_stages;/**< sequence of the accelerations */ vector<double> time_steps; /**< sequence of each time steps for each trajectory */ vector<string> trajectory_descriptions;/**< description of the trajectories */ }planning_result; } // namespace HUMotion #endif // HUMPConfig_HPP <commit_msg>bug fixes<commit_after>#ifndef HUMPConfig_HPP #define HUMPConfig_HPP #include <string> #include <cstring> #include <cstdlib> #include <stdexcept> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <list> #include <vector> #include <cmath> #include <boost/smart_ptr.hpp> #include <boost/numeric/ublas/storage.hpp> #include <boost/algorithm/string.hpp> #include <boost/algorithm/string/replace.hpp> #include <boost/format.hpp> #include <fstream> #include <eigen3/Eigen/Dense> #include "../config/config.hpp" #include "object.hpp" /** version of the library */ #define HUMP_VERSION_MAJOR 2 #define HUMP_VERSION_MINOR 0 //definition of the macro ASSERT #ifndef DEBUG #define ASSERT(x) #else #define ASSERT(x) \ if (! (x)) \ { \ cout << "ERROR!! Assert " << #x << " failed\n"; \ cout << " on line " << __LINE__ << "\n"; \ cout << " in file " << __FILE__ << "\n"; \ } #endif using namespace std; using namespace Eigen; /** This is the main namespace of the library */ namespace HUMotion{ typedef boost::shared_ptr<Object> objectPtr;/**< shared pointer to an object in the scenario */ const double PHI = (-log(2.0)/log(TB));/**< parameter to control when the bounce posture is reached */ const double AP = 15.0*static_cast<double>(M_PI)/180; /**< aperture of the fingers when approaching to pick [rad] */ const double BLANK_PERCENTAGE = 0.10; /**< percentage of steps to eliminate when either reaching to grasp an object OR move at the beginning of a move movement [0,1]*/ const int N_STEP_MIN = 5; /**< minimum number of steps */ const int N_STEP_MAX = 50; /**< maximum number of steps */ const double W_RED_MIN = 1; /**< minimum value of angular velocity reduction when approaching */ const double W_RED_MAX = 20; /**< maximum value of angular velocity reduction when approaching */ /** this struct defines the Denavit-Hartenberg kinematic parameters */ typedef struct{ vector<double> d; /**< distances between consecutive frames along the y axes in [mm] */ vector<double> a; /**< distances between concecutive frames along the z axes in [mm] */ vector<double> alpha; /**< angle around the x axes between consecutive z axes in [rad] */ vector<double> theta; /**< angle around the z axes between consecutive x axes in [rad] */ } DHparameters; /** this struct defines the barrett hand */ typedef struct{ double maxAperture; /**< [mm] max aperture of the hand in [mm] */ double Aw; /**< smallest distance between F1 and F2 in [mm] */ double A1; /**< length of the 1st part of the finger in [mm] */ double A2; /**< length of the first phalax in [mm] */ double A3; /**< length of the second phalax in [mm] */ double D3; /**< depth of the fingertip in [mm] */ double phi2; /**< angular displacement between the 1st part of the finger and the 1st phalax in [rad] */ double phi3; /**< angular displacement between the 1st and the 2nd phalax in [rad] */ vector<int> rk; /**< r parameters of the barrett hand */ vector<int> jk; /**< j parameters of the barrett hand */ } BarrettHand; /** this struct defines a human finger */ typedef struct{ double ux; /**< position of the finger with respect to the center of the palm along the x axis in [mm] */ double uy; /**< position of the finger with respect to the center of the palm along the y axis in [mm] */ double uz; /**< position of the finger with respect to the center of the palm along the z axis in [mm] */ DHparameters finger_specs; /**< the Denavit-Hartenberg parameters of the finger */ } HumanFinger; /** this struct defines a human thumb */ typedef struct{ double uTx; /**< position of the thumb with respect to the center of the palm along the x axis in [mm] */ double uTy; /**< position of the thumb with respect to the center of the palm along the y axis in [mm] */ double uTz; /**< position of the thumb with respect to the center of the palm along the z axis in [mm] */ DHparameters thumb_specs; /**< the Denavit-Hartenberg parameters of the thumb */ } HumanThumb; /** this struct defines a human hand */ typedef struct{ vector<HumanFinger> fingers; /**< fingers of the hand */ HumanThumb thumb; /**< thumb of the hand */ double maxAperture; /**< max aperture of the hand in [mm] */ } HumanHand; /** this struct defines the parameters of the movement */ typedef struct{ int arm_code; /**< the code of the arm: 0 = both arms, 1 = right arm, 2 = left arm */ int hand_code;/**< the code of the hand: 0 = human hand, 1 = barrett hand */ int griptype; /**< the type of the grip */ string mov_infoline; /**< description of the movement */ double dHO;/**< distanche hand-target*/ std::vector<double> finalHand;/**< final posture of the hand */ std::vector<double> target;/**< target / location to reach: target(0)=x, target(1)=y, target(2)=z, target(3)=roll, target(4)=pitch, target(6)=yaw,*/ objectPtr obj; /**< object involved in the movement. The info of the object have to be updated according to the selected movement */ bool approach;/**< true to use the approach options, false otherwise */ bool retreat;/**< true to use the retreat options, false otherwise */ std::vector<double> pre_grasp_approach; /**< (0)= x component, (1)= y component, (2)= z component, (3)= distance from the target*/ std::vector<double> post_grasp_retreat; /**< (0)= x component, (1)= y component, (2)= z component, (3)= distance from the target*/ std::vector<double> pre_place_approach; /**< (0)= x component, (1)= y component, (2)= z component, (3)= distance from the target*/ std::vector<double> post_place_retreat; /**< (0)= x component, (1)= y component, (2)= z component, (3)= distance from the target*/ bool rand_init; /**< true to select randon initialization in "plan" stages */ bool coll; /**< true to enable collisions with the environment (body of the robot included) */ bool use_move_plane; /**< true to constrain the end-effector to move on a plane in move movements, false otherwise*/ std::vector<double> plane_params; /**< plane cartesian parameters in move movements: a*x+b*y+c*z+d=0. a=plane_params(0), b=plane_params(1), c=plane_params(2), d=plane_params(3) */ }mov_params; /** this struct defines the boundary conditions of the movement*/ typedef struct{ vector<double> vel_0; /**< initial velocity of the joints in [rad/s] */ vector<double> vel_f; /**< final velocity of the joints in [rad/s] */ vector<double> acc_0; /**< initial acceleration of the joints in [rad/s²] */ vector<double> acc_f; /**< final acceleration of the joints in [rad/s²] */ } boundaryConditions; /** this struct defines the tolerances that have to be set before planning the trajectory*/ typedef struct{ mov_params mov_specs; /**< specifications of the movement */ vector<double> tolsArm; /**< radius of the spheres along the arm in [mm] */ MatrixXd tolsHand; /**< radius of the spheres along the fingers in [mm] */ MatrixXd final_tolsObstacles; /**< tolerances of the final posture against the obstacles in [mm] */ vector< MatrixXd > singleArm_tolsTarget; /**< tolerances of the trajectory against the target in [mm] */ vector< MatrixXd > singleArm_tolsObstacles; /**< tolerances of the trajectory against the obstacles in [mm] */ double tolTarPos; /**< tolerance of the final position of the hand against the target in [mm] */ double tolTarOr; /**< tolerance of the final orientation of the hand against the target in [mm] */ boundaryConditions bounds; /**< boundary condistions of the bounce problem */ vector<double> vel_approach; /**< velocity of the joints in [rad/s] at the beginning of the approach stage */ vector<double> acc_approach; /**< acceleration of the joints in [rad/s²] at the beginning of the approach stage */ vector<double> lambda_final; /**< weights for the final posture optimization */ vector<double> lambda_bounce; /**< weights for the bounce posture optimization */ vector<double> w_max; /**< maximum angular velocity for each joint [rad/s] */ bool obstacle_avoidance; /**< true to avoid obstacle */ bool target_avoidance; /**< true to avoid the target during the motion */ } hump_params; /** This struct defines the result of the planned trajectory */ typedef struct{ int mov_type;/**< type of the planned movement */ int status;/**< status code of the planning */ string status_msg;/**< status message of the planning */ string object_id;/**< identity of the object involved in the movement */ vector<MatrixXd> trajectory_stages;/**< sequence of the trajectories */ vector<MatrixXd> velocity_stages;/**< sequence of the velocities */ vector<MatrixXd> acceleration_stages;/**< sequence of the accelerations */ vector<double> time_steps; /**< sequence of each time steps for each trajectory */ vector<string> trajectory_descriptions;/**< description of the trajectories */ }planning_result; } // namespace HUMotion #endif // HUMPConfig_HPP <|endoftext|>
<commit_before>/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Module: FGTable.cpp Author: Jon S. Berndt Date started: 1/9/2001 Purpose: Models a lookup table ------------- Copyright (C) 2001 Jon S. Berndt ([email protected]) ------------- This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. Further information about the GNU General Public License can also be found on the world wide web at http://www.gnu.org. FUNCTIONAL DESCRIPTION -------------------------------------------------------------------------------- Models a lookup table HISTORY -------------------------------------------------------------------------------- JSB 1/9/00 Created %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% INCLUDES %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ #include "FGTable.h" #if defined ( sgi ) && !defined( __GNUC__ ) #include <iomanip.h> #else #include <iomanip> #endif static const char *IdSrc = "$Id: FGTable.cpp,v 1.21 2002/01/10 11:51:30 dmegginson Exp $"; static const char *IdHdr = ID_TABLE; /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% CLASS IMPLEMENTATION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ using namespace std; FGTable::FGTable(int NRows, int NCols) : nRows(NRows), nCols(NCols) { if (NCols > 1) { Type = tt2D; colCounter = 1; rowCounter = 0; } else if (NCols == 1) { Type = tt1D; colCounter = 0; rowCounter = 1; } else { cerr << "FGTable cannot accept 'Rows=0'" << endl; } Data = Allocate(); Debug(0); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FGTable::FGTable(int NRows) : nRows(NRows), nCols(1) { Type = tt1D; colCounter = 0; rowCounter = 1; Data = Allocate(); Debug(0); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% double** FGTable::Allocate(void) { Data = new double*[nRows+1]; for (int r=0; r<=nRows; r++) { Data[r] = new double[nCols+1]; for (int c=0; c<=nCols; c++) { Data[r][c] = 0.0; } } return Data; } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FGTable::~FGTable() { for (int r=0; r<=nRows; r++) if (Data[r]) delete[] Data[r]; if (Data) delete[] Data; Debug(1); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% double FGTable::GetValue(double key) { double Factor, Value, Span; int r; for (r=1; r<=nRows; r++) if (Data[r][0] >= key) break; r = r < 2 ? 2 : (r > nRows ? nRows : r); // make sure denominator below does not go to zero. Span = Data[r][0] - Data[r-1][0]; if (Span != 0.0) { Factor = (key - Data[r-1][0]) / Span; if (Factor > 1.0) Factor = 1.0; } else { Factor = 1.0; } Value = Factor*(Data[r][1] - Data[r-1][1]) + Data[r-1][1]; return Value; } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% double FGTable::GetValue(double rowKey, double colKey) { double rFactor, cFactor, col1temp, col2temp, Value; int r, c; for (r=1;r<=nRows;r++) if (Data[r][0] >= rowKey) break; for (c=1;c<=nCols;c++) if (Data[0][c] >= colKey) break; c = c < 2 ? 2 : (c > nCols ? nCols : c); r = r < 2 ? 2 : (r > nRows ? nRows : r); rFactor = (rowKey - Data[r-1][0]) / (Data[r][0] - Data[r-1][0]); cFactor = (colKey - Data[0][c-1]) / (Data[0][c] - Data[0][c-1]); if (rFactor > 1.0) rFactor = 1.0; else if (rFactor < 0.0) rFactor = 0.0; if (cFactor > 1.0) cFactor = 1.0; else if (cFactor < 0.0) cFactor = 0.0; col1temp = rFactor*(Data[r][c-1] - Data[r-1][c-1]) + Data[r-1][c-1]; col2temp = rFactor*(Data[r][c] - Data[r-1][c]) + Data[r-1][c]; Value = col1temp + cFactor*(col2temp - col1temp); return Value; } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% void FGTable::operator<<(FGConfigFile& infile) { int startRow; if (Type == tt1D) startRow = 1; else startRow = 0; for (int r=startRow; r<=nRows; r++) { for (int c=0; c<=nCols; c++) { if (r != 0 || c != 0) { infile >> Data[r][c]; } } } } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FGTable& FGTable::operator<<(const double n) { Data[rowCounter][colCounter] = n; if (colCounter == nCols) { colCounter = 0; rowCounter++; } else { colCounter++; } return *this; } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FGTable& FGTable::operator<<(const int n) { *this << (double)n; return *this; } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% void FGTable::Print(void) { int startRow; if (Type == tt1D) startRow = 1; else startRow = 0; cout.setf(ios::fixed); // set up output stream cout.precision(4); for (int r=startRow; r<=nRows; r++) { cout << " "; for (int c=0; c<=nCols; c++) { if (r == 0 && c == 0) { cout << " "; } else { cout << Data[r][c] << " "; } } cout << endl; } cout.setf((ios_base::fmtflags)0, ios::floatfield); // reset } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // The bitmasked value choices are as follows: // unset: In this case (the default) JSBSim would only print // out the normally expected messages, essentially echoing // the config files as they are read. If the environment // variable is not set, debug_lvl is set to 1 internally // 0: This requests JSBSim not to output any messages // whatsoever. // 1: This value explicity requests the normal JSBSim // startup messages // 2: This value asks for a message to be printed out when // a class is instantiated // 4: When this value is set, a message is displayed when a // FGModel object executes its Run() method // 8: When this value is set, various runtime state variables // are printed out periodically // 16: When set various parameters are sanity checked and // a message is printed out when they go out of bounds void FGTable::Debug(int from) { if (debug_lvl <= 0) return; if (debug_lvl & 1) { // Standard console startup message output if (from == 0) { // Constructor } } if (debug_lvl & 2 ) { // Instantiation/Destruction notification if (from == 0) cout << "Instantiated: FGTable" << endl; if (from == 1) cout << "Destroyed: FGTable" << endl; } if (debug_lvl & 4 ) { // Run() method entry print for FGModel-derived objects } if (debug_lvl & 8 ) { // Runtime state variables } if (debug_lvl & 16) { // Sanity checking } if (debug_lvl & 64) { if (from == 0) { // Constructor cout << IdSrc << endl; cout << IdHdr << endl; } } } <commit_msg>Change from Norman Vine to avoid breaking G++ 2.95.<commit_after>/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Module: FGTable.cpp Author: Jon S. Berndt Date started: 1/9/2001 Purpose: Models a lookup table ------------- Copyright (C) 2001 Jon S. Berndt ([email protected]) ------------- This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. Further information about the GNU General Public License can also be found on the world wide web at http://www.gnu.org. FUNCTIONAL DESCRIPTION -------------------------------------------------------------------------------- Models a lookup table HISTORY -------------------------------------------------------------------------------- JSB 1/9/00 Created %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% INCLUDES %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ #include "FGTable.h" #if defined ( sgi ) && !defined( __GNUC__ ) #include <iomanip.h> #else #include <iomanip> #endif static const char *IdSrc = "$Id: FGTable.cpp,v 1.22 2002/01/11 16:55:14 dmegginson Exp $"; static const char *IdHdr = ID_TABLE; /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% CLASS IMPLEMENTATION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ using namespace std; FGTable::FGTable(int NRows, int NCols) : nRows(NRows), nCols(NCols) { if (NCols > 1) { Type = tt2D; colCounter = 1; rowCounter = 0; } else if (NCols == 1) { Type = tt1D; colCounter = 0; rowCounter = 1; } else { cerr << "FGTable cannot accept 'Rows=0'" << endl; } Data = Allocate(); Debug(0); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FGTable::FGTable(int NRows) : nRows(NRows), nCols(1) { Type = tt1D; colCounter = 0; rowCounter = 1; Data = Allocate(); Debug(0); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% double** FGTable::Allocate(void) { Data = new double*[nRows+1]; for (int r=0; r<=nRows; r++) { Data[r] = new double[nCols+1]; for (int c=0; c<=nCols; c++) { Data[r][c] = 0.0; } } return Data; } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FGTable::~FGTable() { for (int r=0; r<=nRows; r++) if (Data[r]) delete[] Data[r]; if (Data) delete[] Data; Debug(1); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% double FGTable::GetValue(double key) { double Factor, Value, Span; int r; for (r=1; r<=nRows; r++) if (Data[r][0] >= key) break; r = r < 2 ? 2 : (r > nRows ? nRows : r); // make sure denominator below does not go to zero. Span = Data[r][0] - Data[r-1][0]; if (Span != 0.0) { Factor = (key - Data[r-1][0]) / Span; if (Factor > 1.0) Factor = 1.0; } else { Factor = 1.0; } Value = Factor*(Data[r][1] - Data[r-1][1]) + Data[r-1][1]; return Value; } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% double FGTable::GetValue(double rowKey, double colKey) { double rFactor, cFactor, col1temp, col2temp, Value; int r, c; for (r=1;r<=nRows;r++) if (Data[r][0] >= rowKey) break; for (c=1;c<=nCols;c++) if (Data[0][c] >= colKey) break; c = c < 2 ? 2 : (c > nCols ? nCols : c); r = r < 2 ? 2 : (r > nRows ? nRows : r); rFactor = (rowKey - Data[r-1][0]) / (Data[r][0] - Data[r-1][0]); cFactor = (colKey - Data[0][c-1]) / (Data[0][c] - Data[0][c-1]); if (rFactor > 1.0) rFactor = 1.0; else if (rFactor < 0.0) rFactor = 0.0; if (cFactor > 1.0) cFactor = 1.0; else if (cFactor < 0.0) cFactor = 0.0; col1temp = rFactor*(Data[r][c-1] - Data[r-1][c-1]) + Data[r-1][c-1]; col2temp = rFactor*(Data[r][c] - Data[r-1][c]) + Data[r-1][c]; Value = col1temp + cFactor*(col2temp - col1temp); return Value; } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% void FGTable::operator<<(FGConfigFile& infile) { int startRow; if (Type == tt1D) startRow = 1; else startRow = 0; for (int r=startRow; r<=nRows; r++) { for (int c=0; c<=nCols; c++) { if (r != 0 || c != 0) { infile >> Data[r][c]; } } } } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FGTable& FGTable::operator<<(const double n) { Data[rowCounter][colCounter] = n; if (colCounter == nCols) { colCounter = 0; rowCounter++; } else { colCounter++; } return *this; } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FGTable& FGTable::operator<<(const int n) { *this << (double)n; return *this; } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% void FGTable::Print(void) { int startRow; if (Type == tt1D) startRow = 1; else startRow = 0; ios::fmtflags flags = cout.setf(ios::fixed); // set up output stream cout.precision(4); for (int r=startRow; r<=nRows; r++) { cout << " "; for (int c=0; c<=nCols; c++) { if (r == 0 && c == 0) { cout << " "; } else { cout << Data[r][c] << " "; } } cout << endl; } cout.setf(flags); // reset } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // The bitmasked value choices are as follows: // unset: In this case (the default) JSBSim would only print // out the normally expected messages, essentially echoing // the config files as they are read. If the environment // variable is not set, debug_lvl is set to 1 internally // 0: This requests JSBSim not to output any messages // whatsoever. // 1: This value explicity requests the normal JSBSim // startup messages // 2: This value asks for a message to be printed out when // a class is instantiated // 4: When this value is set, a message is displayed when a // FGModel object executes its Run() method // 8: When this value is set, various runtime state variables // are printed out periodically // 16: When set various parameters are sanity checked and // a message is printed out when they go out of bounds void FGTable::Debug(int from) { if (debug_lvl <= 0) return; if (debug_lvl & 1) { // Standard console startup message output if (from == 0) { // Constructor } } if (debug_lvl & 2 ) { // Instantiation/Destruction notification if (from == 0) cout << "Instantiated: FGTable" << endl; if (from == 1) cout << "Destroyed: FGTable" << endl; } if (debug_lvl & 4 ) { // Run() method entry print for FGModel-derived objects } if (debug_lvl & 8 ) { // Runtime state variables } if (debug_lvl & 16) { // Sanity checking } if (debug_lvl & 64) { if (from == 0) { // Constructor cout << IdSrc << endl; cout << IdHdr << endl; } } } <|endoftext|>
<commit_before>/* * The MIT License (MIT) * * Copyright (c) 2016 Julian Ganz * * 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. */ #ifndef CMOH_UTILS_HPP__ #define CMOH_UTILS_HPP__ namespace cmoh { namespace util { /** * Count the number of arguments in a template parameter pack * * Instantiations of this struct will contain a static member `value`, which * will hold the number of arguments supplied to the template. */ template < typename ...Args > struct count; // Specialization for lists of at least one argument template < typename Arg0, typename ...Args > struct count<Arg0, Args...> { static constexpr unsigned long int value = count<Args...>::value + 1; }; // Recursion terminator/specialization for zero arguments template <> struct count<> { static constexpr unsigned long int value = 0; }; /** * Logical conjunction of type traits `Items` * * Providing that each of the `Items` types provides a member `value` of type * bool, this type provides a member `value` of type bool with the value of the * logical conjunction of each of the values taken from the parameters. * * This template mirrors a utility which is expected to ship with C++17 * compliant STL implementations. */ template < typename ...Items > struct conjunction : std::true_type {}; template < typename Item0, typename ...Items > struct conjunction<Item0, Items...> { static constexpr bool value = Item0::value && conjunction<Items...>::value; }; /** * Logical disjunction of type traits `Items` * * Providing that each of the `Items` types provides a member `value` of type * bool, this type provides a member `value` of type bool with the value of the * logical disjunction of each of the values taken from the parameters. * * This template mirrors a utility which is expected to ship with C++17 * compliant STL implementations. */ template < typename ...Items > struct disjunction : std::false_type {}; template < typename Item0, typename ...Items > struct disjunction<Item0, Items...> { static constexpr bool value = Item0::value || disjunction<Items...>::value; }; /** * Test whether a type occurs in a template parameter pack * * Instantiations of this struct contain a static member `value`, which will * be `true` if `Compare` occurs in `Types` and false otherwise. */ template < typename Compare, ///< Type to compare against items in `Types` typename ...Types ///< Types against which to compare `Compare` against > using contains = disjunction<std::is_same<Compare, Types>...>; /** * Predeclaration of the C++17 std::void_t * * Used for SFINAE. */ template < typename... > using void_t = void; /** * Meta type extracting the common type of a parameter pack * * If all `Types` are identical, the type will be exported as the member `type`. * If not all parameters are identical, a compile time error will be issued. */ template < typename ...Types ///< types to unify > struct common_type { static_assert(count<Types...>::value > 0, "Parameter pack is empty"); }; // Specialization for more than one parameter template < typename Type0, typename ...Types > struct common_type<Type0, Types...> { typedef Type0 type; static_assert( std::is_same<type, typename common_type<Types...>::type>::value, "Types are not identical" ); }; // Specialization for exactly one parameter template < typename Type > struct common_type<Type> { typedef Type type; }; /** * Container holding various items, which can be retrieved via criteria * * Use this container if you have a bunch of items of which you want to select * one using some criteria. The container is constructible from values of * arbitrary types. * * At compile time, those items can be accessed through overloads of the variadic * method template `get()`, which takes as template parameters types featuring a * member `value` which is either `true` or `false`. The use case this template * was designed for is when you want to select one of the items based on some * meta function. Example: * * template <typename ...Types> struct foo { * selectable_items<Types...> bar; * // ... * void meth() { * bar.get<has_some_feature<Types>...>(); * } * }; * * Currently, only the retrieval of const references is supported. */ template < typename ...Types ///< types of the items held by the container > struct selectable_items { template <typename...> void get() {} }; // Specialization for at least one parameter template < typename Type0, typename ...Types > struct selectable_items<Type0, Types...> { typedef Type0 value; typedef selectable_items<Types...> next; private: // members have to be declares before get() because of decltype usage value _value; next _next; public: selectable_items(value&& current, Types... values) : _value(std::forward<value>(current)), _next(std::forward<Types>(values)...) {}; selectable_items(selectable_items const&) = default; selectable_items(selectable_items&&) = default; selectable_items() = delete; template < typename BoolType0, typename ...BoolTypes > typename std::enable_if< BoolType0::value, const value& >::type get() const { return _value; } template < typename BoolType0, typename ...BoolTypes > typename std::enable_if< !BoolType0::value, decltype(_next.template get<BoolTypes...>()) >::type get() const { return _next.template get<BoolTypes...>(); } }; } } #endif <commit_msg>Style fix of the return type of cmoh::utils::selectable_items::get()<commit_after>/* * The MIT License (MIT) * * Copyright (c) 2016 Julian Ganz * * 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. */ #ifndef CMOH_UTILS_HPP__ #define CMOH_UTILS_HPP__ namespace cmoh { namespace util { /** * Count the number of arguments in a template parameter pack * * Instantiations of this struct will contain a static member `value`, which * will hold the number of arguments supplied to the template. */ template < typename ...Args > struct count; // Specialization for lists of at least one argument template < typename Arg0, typename ...Args > struct count<Arg0, Args...> { static constexpr unsigned long int value = count<Args...>::value + 1; }; // Recursion terminator/specialization for zero arguments template <> struct count<> { static constexpr unsigned long int value = 0; }; /** * Logical conjunction of type traits `Items` * * Providing that each of the `Items` types provides a member `value` of type * bool, this type provides a member `value` of type bool with the value of the * logical conjunction of each of the values taken from the parameters. * * This template mirrors a utility which is expected to ship with C++17 * compliant STL implementations. */ template < typename ...Items > struct conjunction : std::true_type {}; template < typename Item0, typename ...Items > struct conjunction<Item0, Items...> { static constexpr bool value = Item0::value && conjunction<Items...>::value; }; /** * Logical disjunction of type traits `Items` * * Providing that each of the `Items` types provides a member `value` of type * bool, this type provides a member `value` of type bool with the value of the * logical disjunction of each of the values taken from the parameters. * * This template mirrors a utility which is expected to ship with C++17 * compliant STL implementations. */ template < typename ...Items > struct disjunction : std::false_type {}; template < typename Item0, typename ...Items > struct disjunction<Item0, Items...> { static constexpr bool value = Item0::value || disjunction<Items...>::value; }; /** * Test whether a type occurs in a template parameter pack * * Instantiations of this struct contain a static member `value`, which will * be `true` if `Compare` occurs in `Types` and false otherwise. */ template < typename Compare, ///< Type to compare against items in `Types` typename ...Types ///< Types against which to compare `Compare` against > using contains = disjunction<std::is_same<Compare, Types>...>; /** * Predeclaration of the C++17 std::void_t * * Used for SFINAE. */ template < typename... > using void_t = void; /** * Meta type extracting the common type of a parameter pack * * If all `Types` are identical, the type will be exported as the member `type`. * If not all parameters are identical, a compile time error will be issued. */ template < typename ...Types ///< types to unify > struct common_type { static_assert(count<Types...>::value > 0, "Parameter pack is empty"); }; // Specialization for more than one parameter template < typename Type0, typename ...Types > struct common_type<Type0, Types...> { typedef Type0 type; static_assert( std::is_same<type, typename common_type<Types...>::type>::value, "Types are not identical" ); }; // Specialization for exactly one parameter template < typename Type > struct common_type<Type> { typedef Type type; }; /** * Container holding various items, which can be retrieved via criteria * * Use this container if you have a bunch of items of which you want to select * one using some criteria. The container is constructible from values of * arbitrary types. * * At compile time, those items can be accessed through overloads of the variadic * method template `get()`, which takes as template parameters types featuring a * member `value` which is either `true` or `false`. The use case this template * was designed for is when you want to select one of the items based on some * meta function. Example: * * template <typename ...Types> struct foo { * selectable_items<Types...> bar; * // ... * void meth() { * bar.get<has_some_feature<Types>...>(); * } * }; * * Currently, only the retrieval of const references is supported. */ template < typename ...Types ///< types of the items held by the container > struct selectable_items { template <typename...> void get() {} }; // Specialization for at least one parameter template < typename Type0, typename ...Types > struct selectable_items<Type0, Types...> { typedef Type0 value; typedef selectable_items<Types...> next; private: // members have to be declares before get() because of decltype usage value _value; next _next; public: selectable_items(value&& current, Types... values) : _value(std::forward<value>(current)), _next(std::forward<Types>(values)...) {}; selectable_items(selectable_items const&) = default; selectable_items(selectable_items&&) = default; selectable_items() = delete; template < typename BoolType0, typename ...BoolTypes > typename std::enable_if< BoolType0::value, value const& >::type get() const { return _value; } template < typename BoolType0, typename ...BoolTypes > typename std::enable_if< !BoolType0::value, decltype(_next.template get<BoolTypes...>()) >::type get() const { return _next.template get<BoolTypes...>(); } }; } } #endif <|endoftext|>
<commit_before>// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // http://code.google.com/p/protobuf/ // // 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 Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE 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. // Author: [email protected] (Kenton Varda) #include <google/protobuf/compiler/command_line_interface.h> #include <google/protobuf/compiler/cpp/cpp_generator.h> #include <google/protobuf/compiler/python/python_generator.h> #include <google/protobuf/compiler/java/java_generator.h> int main(int argc, char* argv[]) { google::protobuf::compiler::CommandLineInterface cli; // Proto2 C++ google::protobuf::compiler::cpp::CppGenerator cpp_generator; cli.RegisterGenerator("--cpp_out", &cpp_generator, "Generate C++ header and source."); // Proto2 Java google::protobuf::compiler::java::JavaGenerator java_generator; cli.RegisterGenerator("--java_out", &java_generator, "Generate Java source file."); // Proto2 Python google::protobuf::compiler::python::Generator py_generator; cli.RegisterGenerator("--python_out", &py_generator, "Generate Python source file."); return cli.Run(argc, argv); } <commit_msg>porting code over<commit_after>// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // http://code.google.com/p/protobuf/ // // 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 Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE 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. // Author: [email protected] (Kenton Varda) #include <google/protobuf/compiler/command_line_interface.h> #include <google/protobuf/compiler/cpp/cpp_generator.h> #include <google/protobuf/compiler/python/python_generator.h> #include <google/protobuf/compiler/java/java_generator.h> #include <google/protobuf/compiler/objectivec/objectivec_generator.h> int main(int argc, char* argv[]) { google::protobuf::compiler::CommandLineInterface cli; // Proto2 C++ google::protobuf::compiler::cpp::CppGenerator cpp_generator; cli.RegisterGenerator("--cpp_out", &cpp_generator, "Generate C++ header and source."); // Proto2 Java google::protobuf::compiler::java::JavaGenerator java_generator; cli.RegisterGenerator("--java_out", &java_generator, "Generate Java source file."); // Proto2 Python google::protobuf::compiler::python::Generator py_generator; cli.RegisterGenerator("--python_out", &py_generator, "Generate Python source file."); // Proto2 Objective-C google::protobuf::compiler::objectivec::ObjectiveCGenerator objc_generator; cli.RegisterGenerator("--objc_out", &objc_generator, "Generate Objective-C source file."); return cli.Run(argc, argv); } <|endoftext|>
<commit_before><commit_msg>make sure dialog api object is reset when window is closed ( but not vetoed )<commit_after><|endoftext|>
<commit_before>/* This file is part of cpp-ethereum. cpp-ethereum is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. cpp-ethereum 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 cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. */ /** @file WhisperDB.cpp * @author Vladislav Gluhovsky <[email protected]> * @date July 2015 */ #include "WhisperDB.h" #include <boost/filesystem.hpp> #include <libdevcore/FileSystem.h> #include "WhisperHost.h" using namespace std; using namespace dev; using namespace dev::shh; namespace fs = boost::filesystem; WhisperDB::WhisperDB(string const& _type) { m_readOptions.verify_checksums = true; string path = dev::getDataDir("shh"); fs::create_directories(path); fs::permissions(path, fs::owner_all); path.append("\\").append(_type); leveldb::Options op; op.create_if_missing = true; op.max_open_files = 256; leveldb::DB* p = nullptr; leveldb::Status status = leveldb::DB::Open(op, path, &p); m_db.reset(p); if (!status.ok()) BOOST_THROW_EXCEPTION(FailedToOpenLevelDB(status.ToString())); } string WhisperDB::lookup(dev::h256 const& _key) const { string ret; leveldb::Slice slice((char const*)_key.data(), _key.size); leveldb::Status status = m_db->Get(m_readOptions, slice, &ret); if (!status.ok() && !status.IsNotFound()) BOOST_THROW_EXCEPTION(FailedLookupInLevelDB(status.ToString())); return ret; } void WhisperDB::insert(dev::h256 const& _key, string const& _value) { leveldb::Slice slice((char const*)_key.data(), _key.size); leveldb::Status status = m_db->Put(m_writeOptions, slice, _value); if (!status.ok()) BOOST_THROW_EXCEPTION(FailedInsertInLevelDB(status.ToString())); } void WhisperDB::insert(dev::h256 const& _key, bytes const& _value) { leveldb::Slice k((char const*)_key.data(), _key.size); leveldb::Slice v((char const*)_value.data(), _value.size()); leveldb::Status status = m_db->Put(m_writeOptions, k, v); if (!status.ok()) BOOST_THROW_EXCEPTION(FailedInsertInLevelDB(status.ToString())); } void WhisperDB::kill(dev::h256 const& _key) { leveldb::Slice slice((char const*)_key.data(), _key.size); leveldb::Status status = m_db->Delete(m_writeOptions, slice); if (!status.ok()) BOOST_THROW_EXCEPTION(FailedDeleteInLevelDB(status.ToString())); } void WhisperMessagesDB::loadAllMessages(std::map<h256, Envelope>& o_dst) { leveldb::ReadOptions op; op.fill_cache = false; op.verify_checksums = true; vector<string> wasted; unique_ptr<leveldb::Iterator> it(m_db->NewIterator(op)); unsigned const now = (unsigned)time(0); for (it->SeekToFirst(); it->Valid(); it->Next()) { leveldb::Slice const k = it->key(); leveldb::Slice const v = it->value(); bool useless = true; try { RLP rlp((byte const*)v.data(), v.size()); Envelope e(rlp); h256 h2 = e.sha3(); h256 h1; if (k.size() == h256::size) h1 = h256((byte const*)k.data(), h256::ConstructFromPointer); if (h1 != h2) cwarn << "Corrupted data in Level DB:" << h1.hex() << "versus" << h2.hex(); else if (e.expiry() > now) { o_dst[h1] = e; useless = false; } } catch(RLPException const& ex) { cwarn << "RLPException in WhisperDB::loadAll():" << ex.what(); } catch(Exception const& ex) { cwarn << "Exception in WhisperDB::loadAll():" << ex.what(); } if (useless) wasted.push_back(k.ToString()); } cdebug << "WhisperDB::loadAll(): loaded " << o_dst.size() << ", deleted " << wasted.size() << "messages"; for (auto const& k: wasted) { leveldb::Status status = m_db->Delete(m_writeOptions, k); if (!status.ok()) cwarn << "Failed to delete an entry from Level DB:" << k; } } void WhisperMessagesDB::saveSingleMessage(h256 const& _key, Envelope const& _e) { try { RLPStream rlp; _e.streamRLP(rlp); bytes b; rlp.swapOut(b); insert(_key, b); } catch(RLPException const& ex) { cwarn << boost::diagnostic_information(ex); } catch(FailedInsertInLevelDB const& ex) { cwarn << boost::diagnostic_information(ex); } } vector<unsigned> WhisperFiltersDB::restoreTopicsFromDB(WhisperHost* _host, h256 const& _id) { vector<unsigned> ret; string raw = lookup(_id); if (!raw.empty()) { RLP rlp(raw); auto sz = rlp.itemCountStrict(); for (unsigned i = 0; i < sz; ++i) { RLP r = rlp[i]; bytesConstRef ref(r.toBytesConstRef()); Topics topics; unsigned num = ref.size() / h256::size; for (unsigned j = 0; j < num; ++j) { h256 topic(ref.data() + j * h256::size, h256::ConstructFromPointerType()); topics.push_back(topic); } unsigned w = _host->installWatch(topics); ret.push_back(w); } } return ret; } void WhisperFiltersDB::saveTopicsToDB(WhisperHost const& _host, h256 const& _id) { bytes b; RLPStream rlp; _host.exportFilters(rlp); rlp.swapOut(b); insert(_id, b); } <commit_msg>Fix silly paths for whisper.<commit_after>/* This file is part of cpp-ethereum. cpp-ethereum is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. cpp-ethereum 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 cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. */ /** @file WhisperDB.cpp * @author Vladislav Gluhovsky <[email protected]> * @date July 2015 */ #include "WhisperDB.h" #include <boost/filesystem.hpp> #include <libdevcore/FileSystem.h> #include "WhisperHost.h" using namespace std; using namespace dev; using namespace dev::shh; namespace fs = boost::filesystem; WhisperDB::WhisperDB(string const& _type) { m_readOptions.verify_checksums = true; string path = dev::getDataDir("shh"); fs::create_directories(path); fs::permissions(path, fs::owner_all); path += "/" + _type; leveldb::Options op; op.create_if_missing = true; op.max_open_files = 256; leveldb::DB* p = nullptr; leveldb::Status status = leveldb::DB::Open(op, path, &p); m_db.reset(p); if (!status.ok()) BOOST_THROW_EXCEPTION(FailedToOpenLevelDB(status.ToString())); } string WhisperDB::lookup(dev::h256 const& _key) const { string ret; leveldb::Slice slice((char const*)_key.data(), _key.size); leveldb::Status status = m_db->Get(m_readOptions, slice, &ret); if (!status.ok() && !status.IsNotFound()) BOOST_THROW_EXCEPTION(FailedLookupInLevelDB(status.ToString())); return ret; } void WhisperDB::insert(dev::h256 const& _key, string const& _value) { leveldb::Slice slice((char const*)_key.data(), _key.size); leveldb::Status status = m_db->Put(m_writeOptions, slice, _value); if (!status.ok()) BOOST_THROW_EXCEPTION(FailedInsertInLevelDB(status.ToString())); } void WhisperDB::insert(dev::h256 const& _key, bytes const& _value) { leveldb::Slice k((char const*)_key.data(), _key.size); leveldb::Slice v((char const*)_value.data(), _value.size()); leveldb::Status status = m_db->Put(m_writeOptions, k, v); if (!status.ok()) BOOST_THROW_EXCEPTION(FailedInsertInLevelDB(status.ToString())); } void WhisperDB::kill(dev::h256 const& _key) { leveldb::Slice slice((char const*)_key.data(), _key.size); leveldb::Status status = m_db->Delete(m_writeOptions, slice); if (!status.ok()) BOOST_THROW_EXCEPTION(FailedDeleteInLevelDB(status.ToString())); } void WhisperMessagesDB::loadAllMessages(std::map<h256, Envelope>& o_dst) { leveldb::ReadOptions op; op.fill_cache = false; op.verify_checksums = true; vector<string> wasted; unique_ptr<leveldb::Iterator> it(m_db->NewIterator(op)); unsigned const now = (unsigned)time(0); for (it->SeekToFirst(); it->Valid(); it->Next()) { leveldb::Slice const k = it->key(); leveldb::Slice const v = it->value(); bool useless = true; try { RLP rlp((byte const*)v.data(), v.size()); Envelope e(rlp); h256 h2 = e.sha3(); h256 h1; if (k.size() == h256::size) h1 = h256((byte const*)k.data(), h256::ConstructFromPointer); if (h1 != h2) cwarn << "Corrupted data in Level DB:" << h1.hex() << "versus" << h2.hex(); else if (e.expiry() > now) { o_dst[h1] = e; useless = false; } } catch(RLPException const& ex) { cwarn << "RLPException in WhisperDB::loadAll():" << ex.what(); } catch(Exception const& ex) { cwarn << "Exception in WhisperDB::loadAll():" << ex.what(); } if (useless) wasted.push_back(k.ToString()); } cdebug << "WhisperDB::loadAll(): loaded " << o_dst.size() << ", deleted " << wasted.size() << "messages"; for (auto const& k: wasted) { leveldb::Status status = m_db->Delete(m_writeOptions, k); if (!status.ok()) cwarn << "Failed to delete an entry from Level DB:" << k; } } void WhisperMessagesDB::saveSingleMessage(h256 const& _key, Envelope const& _e) { try { RLPStream rlp; _e.streamRLP(rlp); bytes b; rlp.swapOut(b); insert(_key, b); } catch(RLPException const& ex) { cwarn << boost::diagnostic_information(ex); } catch(FailedInsertInLevelDB const& ex) { cwarn << boost::diagnostic_information(ex); } } vector<unsigned> WhisperFiltersDB::restoreTopicsFromDB(WhisperHost* _host, h256 const& _id) { vector<unsigned> ret; string raw = lookup(_id); if (!raw.empty()) { RLP rlp(raw); auto sz = rlp.itemCountStrict(); for (unsigned i = 0; i < sz; ++i) { RLP r = rlp[i]; bytesConstRef ref(r.toBytesConstRef()); Topics topics; unsigned num = ref.size() / h256::size; for (unsigned j = 0; j < num; ++j) { h256 topic(ref.data() + j * h256::size, h256::ConstructFromPointerType()); topics.push_back(topic); } unsigned w = _host->installWatch(topics); ret.push_back(w); } } return ret; } void WhisperFiltersDB::saveTopicsToDB(WhisperHost const& _host, h256 const& _id) { bytes b; RLPStream rlp; _host.exportFilters(rlp); rlp.swapOut(b); insert(_id, b); } <|endoftext|>
<commit_before><commit_msg>Fix code comment about IMPALA-2031 (query end time < start time)<commit_after><|endoftext|>
<commit_before>#pragma once #include <vector> #include <utility> namespace helene { template <class T, class Allocator = std::allocator<T>> class handle_map { public: typedef typename std::vector<T>::size_type size_type; typedef typename std::vector<size_type>::size_type handle_type; public: typedef typename std::vector<T>::iterator iterator; typedef typename std::vector<T>::const_iterator const_iterator; public: handle_type insert(const T& value) { // always insert at end of dense storage dense_.push_back(value); handle_type new_handle; // find new handle if(free_.empty()) { // no free handle slots, push back new slot sparse_.push_back(dense_.size() - 1); new_handle = sparse_.size() - 1; } else { // slot is available for new handle new_handle = free_.back(); sparse_[new_handle] = dense_.size() - 1; free_.pop_back(); } reverse_.push_back(new_handle); return new_handle; } void erase(handle_type n) { // find handle of dense's back const auto index_of_dense_back = dense_.size() - 1; const auto back_handle = reverse_[index_of_dense_back]; // swap element to erase with back element std::swap(dense_[sparse_[n]], dense_.back()); std::swap(reverse_[n], reverse_[index_of_dense_back]); // update handle reference to new dense location sparse_[back_handle] = sparse_[n]; // pop back dense_.pop_back(); reverse_.pop_back(); // add handle to free list free_.push_back(n); } size_type size() const { return dense_.size(); } bool empty() const { return dense_.empty(); } T& operator[](handle_type n) { return dense_[sparse_[n]]; } const T& operator[](handle_type n) const { return dense_[sparse_[n]]; } iterator begin() { return dense_.begin(); } iterator end() { return dense_.end(); } const_iterator cbegin() const { return dense_.cbegin(); } const_iterator cend() const { return dense_.cend(); } private: std::vector<T> dense_; std::vector<size_type> sparse_; std::vector<handle_type> reverse_; std::vector<handle_type> free_; }; } // namespace helene <commit_msg>Remove unused defaulted template parameter. modified: include/handle_map.hpp<commit_after>#pragma once #include <vector> #include <utility> namespace helene { template <class T> class handle_map { public: typedef typename std::vector<T>::size_type size_type; typedef typename std::vector<size_type>::size_type handle_type; public: typedef typename std::vector<T>::iterator iterator; typedef typename std::vector<T>::const_iterator const_iterator; public: handle_type insert(const T& value) { // always insert at end of dense storage dense_.push_back(value); handle_type new_handle; // find new handle if(free_.empty()) { // no free handle slots, push back new slot sparse_.push_back(dense_.size() - 1); new_handle = sparse_.size() - 1; } else { // slot is available for new handle new_handle = free_.back(); sparse_[new_handle] = dense_.size() - 1; free_.pop_back(); } reverse_.push_back(new_handle); return new_handle; } void erase(handle_type n) { // find handle of dense's back const auto index_of_dense_back = dense_.size() - 1; const auto back_handle = reverse_[index_of_dense_back]; // swap element to erase with back element std::swap(dense_[sparse_[n]], dense_.back()); std::swap(reverse_[n], reverse_[index_of_dense_back]); // update handle reference to new dense location sparse_[back_handle] = sparse_[n]; // pop back dense_.pop_back(); reverse_.pop_back(); // add handle to free list free_.push_back(n); } size_type size() const { return dense_.size(); } bool empty() const { return dense_.empty(); } T& operator[](handle_type n) { return dense_[sparse_[n]]; } const T& operator[](handle_type n) const { return dense_[sparse_[n]]; } iterator begin() { return dense_.begin(); } iterator end() { return dense_.end(); } const_iterator cbegin() const { return dense_.cbegin(); } const_iterator cend() const { return dense_.cend(); } private: std::vector<T> dense_; std::vector<size_type> sparse_; std::vector<handle_type> reverse_; std::vector<handle_type> free_; }; } // namespace helene <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/generic/memory/lib/utils/voltage/gen_mss_voltage_traits.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2018,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ <commit_msg>Move MSS volt attr setters to generic folder<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/generic/memory/lib/utils/voltage/gen_mss_voltage_traits.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2018,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file gen_mss_voltage_traits.H /// @brief Contains voltage traits information /// // *HWP HWP Owner: Stephen Glancy <[email protected]> // *HWP FW Owner: Andre Marin <[email protected]> // *HWP Team: Memory // *HWP Level: 2 // *HWP Consumed by: CI #ifndef _GEN_MSS_VOLTAGE_TRAITS_H_ #define _GEN_MSS_VOLTAGE_TRAITS_H_ #include <fapi2.H> #include <generic/memory/lib/utils/shared/mss_generic_consts.H> namespace mss { /// /// @class Traits and policy class for voltage code /// @tparam M mss::mc_type memory controller type /// @tparam D mss::spd::device_type DRAM device type (generation) /// template< mss::mc_type M, mss::spd::device_type D > class voltage_traits; /// /// @class Traits and policy class for voltage code - specialization for the NIMBUS memory controller type /// template<> class voltage_traits<mss::mc_type::NIMBUS, mss::spd::device_type::DDR4> { public: ////////////////////////////////////////////////////////////// // Target types ////////////////////////////////////////////////////////////// static constexpr fapi2::TargetType VOLTAGE_TARGET_TYPE = fapi2::TARGET_TYPE_MCBIST; static constexpr fapi2::TargetType SPD_TARGET_TYPE = fapi2::TARGET_TYPE_MCS; ////////////////////////////////////////////////////////////// // Traits values ////////////////////////////////////////////////////////////// // List of attribute setter functions for setting voltage rail values // This vector is defined in the p9 space: lib/eff_config/nimbus_mss_voltage.C static const std::vector<fapi2::ReturnCode (*)(const fapi2::Target<VOLTAGE_TARGET_TYPE>&, uint32_t)> voltage_setters; }; } // ns mss #endif <|endoftext|>
<commit_before>// vimshell.cpp : Defines the entry point for the application. // #include "vimshell.h" #include <iostream> #include <fstream> #include <string> #include <windows.h> #include <shellapi.h> bool cvtLPW2stdstring(std::string& s, const LPWSTR pw, UINT codepage = CP_ACP) { bool res = false; char* p = 0; int bsz; bsz = WideCharToMultiByte(codepage, 0, pw,-1, 0,0, 0,0); if (bsz > 0) { p = new char[bsz]; int rc = WideCharToMultiByte(codepage, 0, pw,-1, p,bsz, 0,0); if (rc != 0) { p[bsz-1] = 0; s = p; res = true; } } delete [] p; return res; } std::string FindAndReplace(std::string tInput, std::string tFind, std::string tReplace ) { size_t uPos = 0; size_t uFindLen = tFind.length(); size_t uReplaceLen = tReplace.length(); if( uFindLen == 0 ) { return tInput; } for( ;(uPos = tInput.find( tFind, uPos )) != std::string::npos; ) { tInput.replace( uPos, uFindLen, tReplace ); uPos += uReplaceLen; } return tInput; } int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) { int count; //MessageBox(0, lpCmdLine, 0, 0); LPWSTR* strings = CommandLineToArgvW(GetCommandLineW(), &count); std::string currentDir; cvtLPW2stdstring(currentDir, strings[0]); // Cut off the filename while((currentDir.length() > 0) && (currentDir[currentDir.length()-1] != '/') && (currentDir[currentDir.length()-1] != '\\')) { currentDir = currentDir.substr(0, currentDir.length()-1); } if(currentDir.length() > 0 && currentDir[0] == '"') currentDir = currentDir.substr(1); std::string filename = currentDir + std::string("shell.txt"); std::ifstream fileIn(filename.c_str()); if(!fileIn) { MessageBox(0, "Please create a file called shell.txt in the same folder you put this new vimrun.exe", 0,0); return 1; } std::string argumentshellcommand; std::string silentshellcommand; std::string interactiveshellcommand; std::getline(fileIn, argumentshellcommand); std::getline(fileIn, silentshellcommand); std::getline(fileIn, interactiveshellcommand); std::string args = lpCmdLine; while(args.length() > 0 && args[0] == ' ') args = args.substr(1); bool execSilently = false; if(args.length() > 3 && args[0] == '-' && args[1] == 's' && args[2] == ' ') { args = args.substr(3); execSilently = true; } size_t spacepos = args.find_first_of(" "); args = args.substr(spacepos+1); spacepos = args.find_first_of(" "); args = args.substr(spacepos+1); std::string cmd; if(spacepos == std::string::npos) args = ""; std::string argcmd = execSilently ? silentshellcommand : argumentshellcommand; if(args.length() == 0) { cmd = interactiveshellcommand; } else { std::string quotedPH = "#QQQQ#"; if(argcmd.find(quotedPH) != std::string::npos) { args = FindAndReplace(args,"\"", "\\\""); args = FindAndReplace(args, "\\", "\\\\"); cmd = FindAndReplace(argcmd, quotedPH, args); } else { cmd = argcmd + " " + args; } } //MessageBox(0,cmd.c_str(), 0,0); // I know, I know, baaaaad win16 function, unfortunately I could not get // CreateProcess working as I wanted it (actually showing me the window) // and also if I used CreateProcess, I would have to parse the program name // out of the shell.txt file to know where the parameters begint etc, // which is kinda difficult and not pleasant at all. WinExec(cmd.c_str(), SW_SHOW); return 0; } <commit_msg>Fixed vague for loop that was actually a while loop<commit_after>// vimshell.cpp : Defines the entry point for the application. // #include "vimshell.h" #include <iostream> #include <fstream> #include <string> #include <windows.h> #include <shellapi.h> bool cvtLPW2stdstring(std::string& s, const LPWSTR pw, UINT codepage = CP_ACP) { bool res = false; char* p = 0; int bsz; bsz = WideCharToMultiByte(codepage, 0, pw,-1, 0,0, 0,0); if (bsz > 0) { p = new char[bsz]; int rc = WideCharToMultiByte(codepage, 0, pw,-1, p,bsz, 0,0); if (rc != 0) { p[bsz-1] = 0; s = p; res = true; } } delete [] p; return res; } std::string FindAndReplace(std::string tInput, std::string tFind, std::string tReplace ) { size_t uPos = 0; size_t uFindLen = tFind.length(); size_t uReplaceLen = tReplace.length(); if( uFindLen == 0 ) { return tInput; } while((uPos = tInput.find( tFind, uPos )) != std::string::npos) { tInput.replace( uPos, uFindLen, tReplace ); uPos += uReplaceLen; } return tInput; } int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) { int count; //MessageBox(0, lpCmdLine, 0, 0); LPWSTR* strings = CommandLineToArgvW(GetCommandLineW(), &count); std::string currentDir; cvtLPW2stdstring(currentDir, strings[0]); // Cut off the filename while((currentDir.length() > 0) && (currentDir[currentDir.length()-1] != '/') && (currentDir[currentDir.length()-1] != '\\')) { currentDir = currentDir.substr(0, currentDir.length()-1); } if(currentDir.length() > 0 && currentDir[0] == '"') currentDir = currentDir.substr(1); std::string filename = currentDir + std::string("shell.txt"); std::ifstream fileIn(filename.c_str()); if(!fileIn) { MessageBox(0, "Please create a file called shell.txt in the same folder you put this new vimrun.exe", 0,0); return 1; } std::string argumentshellcommand; std::string silentshellcommand; std::string interactiveshellcommand; std::getline(fileIn, argumentshellcommand); std::getline(fileIn, silentshellcommand); std::getline(fileIn, interactiveshellcommand); std::string args = lpCmdLine; while(args.length() > 0 && args[0] == ' ') args = args.substr(1); bool execSilently = false; if(args.length() > 3 && args[0] == '-' && args[1] == 's' && args[2] == ' ') { args = args.substr(3); execSilently = true; } size_t spacepos = args.find_first_of(" "); args = args.substr(spacepos+1); spacepos = args.find_first_of(" "); args = args.substr(spacepos+1); std::string cmd; if(spacepos == std::string::npos) args = ""; std::string argcmd = execSilently ? silentshellcommand : argumentshellcommand; if(args.length() == 0) { cmd = interactiveshellcommand; } else { std::string quotedPH = "#QQQQ#"; if(argcmd.find(quotedPH) != std::string::npos) { args = FindAndReplace(args,"\"", "\\\""); args = FindAndReplace(args, "\\", "\\\\"); cmd = FindAndReplace(argcmd, quotedPH, args); } else { cmd = argcmd + " " + args; } } //MessageBox(0,cmd.c_str(), 0,0); // I know, I know, baaaaad win16 function, unfortunately I could not get // CreateProcess working as I wanted it (actually showing me the window) // and also if I used CreateProcess, I would have to parse the program name // out of the shell.txt file to know where the parameters begint etc, // which is kinda difficult and not pleasant at all. WinExec(cmd.c_str(), SW_SHOW); return 0; } <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/lib/p9_resclk_defines.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2017,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ <commit_msg>PM: Resonant Clocking Enablement - Infrastructure<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/lib/p9_resclk_defines.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2017,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file p9_resclk_defines.H /// @brief Defines Resonant Clocking default values (provided by clock team). /// // *HWP HWP Owner: // *HWP FW Owner: // *HWP Team: PM // *HWP Level: // *HWP Consumed by: #ifndef __P9_RESCLK_DEFINES_H__ #define __P9_RESCLK_DEFINES_H__ #include <vector> namespace p9_resclk_defines { typedef struct { uint16_t freq; uint8_t idx; } rsclk_freq_idx_t; //############################################################################### // Table 1: Resonant Clocking Control Index // consists of 8 entries consisting of a comma-delimited pair. // Freq(in Mhz), Index(decimal number between 0 & 63, index into the next table) // The first entry is always 0 Mhz. Entries are in ascending order of frequency. // Algorithm will search starting at the bottom of the index until it // finds the first entry at or below target frequency, then walk to that index. //############################################################################### std::vector<rsclk_freq_idx_t> const RESCLK_INDEX_VEC = { // { Freq, Idx} { 0, 3 }, { 1500, 3 }, { 2000, 24 }, { 3000, 24 }, { 3400, 24 }, { 3700, 24 }, { 3900, 24 }, { 4100, 24 } }; //############################################################################### // Table 2: Resonant (Core & L2) Grids Control Data // 64 entries,each entry a 16-bit hex value. // First row corresponds to Index 0 from Table 1. Last row is Index 63. // Left aligned hex value corresponding to the first 13-bits of the QACCR register // 0:3 SB_STRENGTH; 4 SB_SPARE; 6:7 SB_PULSE_MODE; 8:11 SW_RESCLK; 12 SW_SPARE //############################################################################### std::vector<uint16_t> const RESCLK_TABLE_VEC = { 0x2000, 0x3000, 0x1000, 0x0000, 0x0010, 0x0030, 0x0020, 0x0060, 0x0070, 0x0050, 0x0040, 0x00C0, 0x00D0, 0x00F0, 0x00E0, 0x00A0, 0x00B0, 0x0090, 0x0080, 0x8080, 0x9080, 0xB080, 0xA080, 0xE080, 0xF080, 0xF080, 0xF080, 0xF080, 0xF080, 0xF080, 0xF080, 0xF080, 0xF080, 0xF080, 0xF080, 0xF080, 0xF080, 0xF080, 0xF080, 0xF080, 0xF080, 0xF080, 0xF080, 0xF080, 0xF080, 0xF080, 0xF080, 0xF080, 0xF080, 0xF080, 0xF080, 0xF080, 0xF080, 0xF080, 0xF080, 0xF080, 0xF080, 0xF080, 0xF080, 0xF080, 0xF080, 0xF080, 0xF080, 0xF080 }; //############################################################################### // Table 3: L3 Grid Control Data // 4 entries, each a 8-bit hex value to transition between two modes // Entry 0 is the "Full Power" setting // Entry 3 is the "Low Power" setting, for use above voltages defined by // L3_VOLTAGE_THRESHOLD_MV (ATTR_SYSTEM_RESCLK_L3_VOLTAGE_THRESHOLD_MV) // Hex value corresponding to L3 control bits in the QACCR(16:23) // 0:3 SB_STRENGTH; (Not supported: 4 SB_SPARE; 5:7 SB_PULSE_MODE) //############################################################################### std::vector<uint8_t> const L3CLK_TABLE_VEC { 0, 1, 3, 2 }; //############################################################################### // L3 Voltage Threshold (millivolts) //############################################################################### uint16_t const L3_VOLTAGE_THRESHOLD_MV = 600; } #endif //__P9_RESCLK_DEFINES_H__ <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/memory/p9_mss_memdiag.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file p9_mss_memdiag.C /// @brief Mainstore pattern testing /// // *HWP HWP Owner: Brian Silver <[email protected]> // *HWP HWP Backup: Andre Marin <[email protected]> // *HWP Team: Memory // *HWP Level: 2 // *HWP Consumed by: FSP:HB #include <fapi2.H> #include <p9_mss_memdiag.H> #include <lib/utils/poll.H> #include <generic/memory/lib/utils/find.H> #include <lib/utils/count_dimm.H> #include <lib/mcbist/address.H> #include <lib/mcbist/memdiags.H> #include <lib/mcbist/mcbist.H> #include <lib/mc/port.H> #include <lib/ecc/ecc.H> using fapi2::TARGET_TYPE_MCBIST; using fapi2::TARGET_TYPE_SYSTEM; using fapi2::TARGET_TYPE_MCA; extern "C" { /// /// @brief Pattern test the DRAM /// @param[in] i_target the McBIST of the ports of the dram you're training /// @return FAPI2_RC_SUCCESS iff ok /// fapi2::ReturnCode p9_mss_memdiag( const fapi2::Target<TARGET_TYPE_MCBIST>& i_target ) { FAPI_INF("Start memdiag"); // If there are no DIMM we don't need to bother. In fact, we can't as we didn't setup // attributes for the PHY, etc. if (mss::count_dimm(i_target) == 0) { FAPI_INF("... skipping mem_diags %s - no DIMM ...", mss::c_str(i_target)); return fapi2::FAPI2_RC_SUCCESS; } uint8_t l_sim = false; FAPI_TRY( mss::is_simulation( l_sim) ); // Read the bad_dq_bitmap attribute and place corresponding symbol and chip marks for (const auto& l_mca : mss::find_targets<TARGET_TYPE_MCA>(i_target)) { fapi2::buffer<uint8_t> l_repairs_applied; fapi2::buffer<uint8_t> l_repairs_exceeded; std::vector<uint64_t> l_ranks; FAPI_TRY( mss::restore_repairs( l_mca, l_repairs_applied, l_repairs_exceeded) ); // assert if we have exceeded the allowed repairs for (const auto& l_dimm : mss::find_targets<fapi2::TARGET_TYPE_DIMM>(l_mca)) { // Note: using MCA here as the scoms used to collect FFDC data fail on the DIMM level target FAPI_ASSERT( !(l_repairs_exceeded.getBit(mss::index(l_dimm))), fapi2::MSS_MEMDIAGS_REPAIRS_EXCEEDED().set_MCA_TARGET(l_mca), "p9_mss_memdiag bad bit repairs exceeded %s", mss::c_str(l_mca) ); } #ifdef __HOSTBOOT_MODULE // assert if both chip and symbol marks exist for any given rank FAPI_TRY( mss::rank::ranks(l_mca, l_ranks) ); for (const auto l_rank : l_ranks) { if (l_repairs_applied.getBit(l_rank)) { uint64_t l_galois = 0; mss::states l_confirmed = mss::NO; // check for chip mark in hardware mark store FAPI_TRY( mss::ecc::get_hwms(l_mca, l_rank, l_galois, l_confirmed) ); if (l_confirmed) { auto l_type = mss::ecc::fwms::mark_type::CHIP; auto l_region = mss::ecc::fwms::mark_region::DISABLED; auto l_addr = mss::mcbist::address(0); // check for symbol mark in firmware mark store FAPI_TRY( mss::ecc::get_fwms(l_mca, l_rank, l_galois, l_type, l_region, l_addr) ); FAPI_ASSERT( l_region == mss::ecc::fwms::mark_region::DISABLED, fapi2::MSS_MEMDIAGS_CHIPMARK_AND_SYMBOLMARK().set_MCA_TARGET(l_mca).set_RANK(l_rank), "p9_mss_memdiag both chip mark and symbol mark on rank %d: %s", l_rank, mss::c_str(l_mca) ); } } } #endif } // We start the sf_init (write 0's) and it'll tickle the MCBIST complete FIR. PRD will see that // and start a background scrub. FAPI_TRY( mss::memdiags::sf_init(i_target, mss::mcbist::PATTERN_0) ); // If we're in the sim, we want to poll for the FIR bit. I don't think this ever really happens // unless we're expressly testing this API. if (l_sim) { // Poll for the fir bit. We expect this to be set ... fapi2::buffer<uint64_t> l_status; // A small vector of addresses to poll during the polling loop const std::vector<mss::poll_probe<fapi2::TARGET_TYPE_MCBIST>> l_probes = { {i_target, "mcbist current address", MCBIST_MCBMCATQ}, }; mss::poll_parameters l_poll_parameters; bool l_poll_results = mss::poll(i_target, MCBIST_MCBISTFIRQ, l_poll_parameters, [&l_status](const size_t poll_remaining, const fapi2::buffer<uint64_t>& stat_reg) -> bool { FAPI_DBG("mcbist firq 0x%llx, remaining: %d", stat_reg, poll_remaining); l_status = stat_reg; return l_status.getBit<MCBIST_MCBISTFIRQ_MCBIST_PROGRAM_COMPLETE>() == true; }, l_probes); FAPI_ASSERT( l_poll_results == true, fapi2::MSS_MEMDIAGS_SUPERFAST_INIT_FAILED_TO_INIT().set_MCBIST_TARGET(i_target), "p9_mss_memdiags timedout %s", mss::c_str(i_target) ); } fapi_try_exit: FAPI_INF("End memdiag"); return fapi2::current_err; } } <commit_msg>Updated MSS HWP's level and owner change<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/memory/p9_mss_memdiag.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file p9_mss_memdiag.C /// @brief Mainstore pattern testing /// // *HWP HWP Owner: Stephen Glancy <[email protected]> // *HWP HWP Backup: Andre Marin <[email protected]> // *HWP Team: Memory // *HWP Level: 3 // *HWP Consumed by: FSP:HB #include <fapi2.H> #include <p9_mss_memdiag.H> #include <lib/utils/poll.H> #include <generic/memory/lib/utils/find.H> #include <lib/utils/count_dimm.H> #include <lib/mcbist/address.H> #include <lib/mcbist/memdiags.H> #include <lib/mcbist/mcbist.H> #include <lib/mc/port.H> #include <lib/ecc/ecc.H> using fapi2::TARGET_TYPE_MCBIST; using fapi2::TARGET_TYPE_SYSTEM; using fapi2::TARGET_TYPE_MCA; extern "C" { /// /// @brief Pattern test the DRAM /// @param[in] i_target the McBIST of the ports of the dram you're training /// @return FAPI2_RC_SUCCESS iff ok /// fapi2::ReturnCode p9_mss_memdiag( const fapi2::Target<TARGET_TYPE_MCBIST>& i_target ) { FAPI_INF("Start memdiag"); // If there are no DIMM we don't need to bother. In fact, we can't as we didn't setup // attributes for the PHY, etc. if (mss::count_dimm(i_target) == 0) { FAPI_INF("... skipping mem_diags %s - no DIMM ...", mss::c_str(i_target)); return fapi2::FAPI2_RC_SUCCESS; } uint8_t l_sim = false; FAPI_TRY( mss::is_simulation( l_sim) ); // Read the bad_dq_bitmap attribute and place corresponding symbol and chip marks for (const auto& l_mca : mss::find_targets<TARGET_TYPE_MCA>(i_target)) { fapi2::buffer<uint8_t> l_repairs_applied; fapi2::buffer<uint8_t> l_repairs_exceeded; std::vector<uint64_t> l_ranks; FAPI_TRY( mss::restore_repairs( l_mca, l_repairs_applied, l_repairs_exceeded) ); // assert if we have exceeded the allowed repairs for (const auto& l_dimm : mss::find_targets<fapi2::TARGET_TYPE_DIMM>(l_mca)) { // Note: using MCA here as the scoms used to collect FFDC data fail on the DIMM level target FAPI_ASSERT( !(l_repairs_exceeded.getBit(mss::index(l_dimm))), fapi2::MSS_MEMDIAGS_REPAIRS_EXCEEDED().set_MCA_TARGET(l_mca), "p9_mss_memdiag bad bit repairs exceeded %s", mss::c_str(l_mca) ); } #ifdef __HOSTBOOT_MODULE // assert if both chip and symbol marks exist for any given rank FAPI_TRY( mss::rank::ranks(l_mca, l_ranks) ); for (const auto l_rank : l_ranks) { if (l_repairs_applied.getBit(l_rank)) { uint64_t l_galois = 0; mss::states l_confirmed = mss::NO; // check for chip mark in hardware mark store FAPI_TRY( mss::ecc::get_hwms(l_mca, l_rank, l_galois, l_confirmed) ); if (l_confirmed) { auto l_type = mss::ecc::fwms::mark_type::CHIP; auto l_region = mss::ecc::fwms::mark_region::DISABLED; auto l_addr = mss::mcbist::address(0); // check for symbol mark in firmware mark store FAPI_TRY( mss::ecc::get_fwms(l_mca, l_rank, l_galois, l_type, l_region, l_addr) ); FAPI_ASSERT( l_region == mss::ecc::fwms::mark_region::DISABLED, fapi2::MSS_MEMDIAGS_CHIPMARK_AND_SYMBOLMARK().set_MCA_TARGET(l_mca).set_RANK(l_rank), "p9_mss_memdiag both chip mark and symbol mark on rank %d: %s", l_rank, mss::c_str(l_mca) ); } } } #endif } // We start the sf_init (write 0's) and it'll tickle the MCBIST complete FIR. PRD will see that // and start a background scrub. FAPI_TRY( mss::memdiags::sf_init(i_target, mss::mcbist::PATTERN_0) ); // If we're in the sim, we want to poll for the FIR bit. I don't think this ever really happens // unless we're expressly testing this API. if (l_sim) { // Poll for the fir bit. We expect this to be set ... fapi2::buffer<uint64_t> l_status; // A small vector of addresses to poll during the polling loop const std::vector<mss::poll_probe<fapi2::TARGET_TYPE_MCBIST>> l_probes = { {i_target, "mcbist current address", MCBIST_MCBMCATQ}, }; mss::poll_parameters l_poll_parameters; bool l_poll_results = mss::poll(i_target, MCBIST_MCBISTFIRQ, l_poll_parameters, [&l_status](const size_t poll_remaining, const fapi2::buffer<uint64_t>& stat_reg) -> bool { FAPI_DBG("mcbist firq 0x%llx, remaining: %d", stat_reg, poll_remaining); l_status = stat_reg; return l_status.getBit<MCBIST_MCBISTFIRQ_MCBIST_PROGRAM_COMPLETE>() == true; }, l_probes); FAPI_ASSERT( l_poll_results == true, fapi2::MSS_MEMDIAGS_SUPERFAST_INIT_FAILED_TO_INIT().set_MCBIST_TARGET(i_target), "p9_mss_memdiags timedout %s", mss::c_str(i_target) ); } fapi_try_exit: FAPI_INF("End memdiag"); return fapi2::current_err; } } <|endoftext|>
<commit_before>/* Copyright (C) 2016 - Gbor "Razzie" Grzsny 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 <functional> #include <future> #include <mutex> #include <list> #include <thread> namespace raz { template<class T> class Thread { public: template<class... Args> Thread(Args... args) : m_object(std::forward<Args>(args)...) { m_thread = std::thread(&Thread<T>::run, this); } Thread(const Thread&) = delete; Thread& operator=(const Thread&) = delete; ~Thread() { m_exit_token.set_value(); m_thread.join(); } template<class... Args> void operator()(Args... args) { std::lock_guard<std::mutex> guard(m_mutex); m_call_queue.emplace_back([this, args...]() { m_object(args...); }); } private: std::thread m_thread; std::promise<void> m_exit_token; std::mutex m_mutex; std::list<std::function<void()>> m_call_queue; T m_object; class HasParenthesisOp { template<class U> static auto test(bool) -> decltype(std::declval<U>()(), void(), std::true_type{}) { return {}; } template<class U> static auto test(int) -> std::false_type { return {}; } public: static constexpr bool value = decltype(test<T>(true))::value; }; template<bool> void loop(); template<> void loop<true>() { m_object(); } template<> void loop<false>() { } void run() { std::future<void> exit_token = m_exit_token.get_future(); std::list<std::function<void()>> call_queue; for (;;) { m_mutex.lock(); std::swap(m_call_queue, call_queue); m_mutex.unlock(); for (auto& call : call_queue) call(); call_queue.clear(); loop<HasParenthesisOp::value>(); auto exit_status = exit_token.wait_for(std::chrono::milliseconds(1)); if (exit_status == std::future_status::ready) return; } } }; } <commit_msg>The internal object of Thread is constructed inside the newly started thread<commit_after>/* Copyright (C) 2016 - Gbor "Razzie" Grzsny 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 <functional> #include <future> #include <mutex> #include <list> #include <thread> namespace raz { template<class T> class Thread { public: template<class... Args> Thread(Args... args) { m_thread = std::thread(&Thread<T>::run<Args...>, this, std::forward<Args>(args)...); } Thread(const Thread&) = delete; Thread& operator=(const Thread&) = delete; ~Thread() { m_exit_token.set_value(); m_thread.join(); } template<class... Args> void operator()(Args... args) { std::lock_guard<std::mutex> guard(m_mutex); m_call_queue.emplace_back([args...](T& object) { object(args...); }); } private: typedef std::function<void(T&)> ForwardedCall; std::thread m_thread; std::promise<void> m_exit_token; std::mutex m_mutex; std::list<ForwardedCall> m_call_queue; class HasParenthesisOp { template<class U> static auto test(bool) -> decltype(std::declval<U>()(), void(), std::true_type{}) { return {}; } template<class U> static auto test(int) -> std::false_type { return {}; } public: static constexpr bool value = decltype(test<T>(true))::value; }; template<bool> void loop(T&); template<> void loop<true>(T& object) { object(); } template<> void loop<false>(T& object) { } template<class... Args> void run(Args... args) { T object(std::forward<Args>(args)...); std::future<void> exit_token = m_exit_token.get_future(); std::list<ForwardedCall> call_queue; for (;;) { m_mutex.lock(); std::swap(m_call_queue, call_queue); m_mutex.unlock(); for (auto& call : call_queue) call(object); call_queue.clear(); loop<HasParenthesisOp::value>(object); auto exit_status = exit_token.wait_for(std::chrono::milliseconds(1)); if (exit_status == std::future_status::ready) return; } } }; } <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/memory/p9_mss_memdiag.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file p9_mss_memdiag.C /// @brief Mainstore pattern testing /// // *HWP HWP Owner: Brian Silver <[email protected]> // *HWP HWP Backup: Andre Marin <[email protected]> // *HWP Team: Memory // *HWP Level: 2 // *HWP Consumed by: FSP:HB #include <fapi2.H> #include <p9_mss_memdiag.H> #include <lib/utils/poll.H> #include <generic/memory/lib/utils/find.H> #include <lib/utils/count_dimm.H> #include <lib/mcbist/address.H> #include <lib/mcbist/memdiags.H> #include <lib/mcbist/mcbist.H> #include <lib/mc/port.H> #include <lib/ecc/ecc.H> using fapi2::TARGET_TYPE_MCBIST; using fapi2::TARGET_TYPE_SYSTEM; using fapi2::TARGET_TYPE_MCA; extern "C" { /// /// @brief Pattern test the DRAM /// @param[in] i_target the McBIST of the ports of the dram you're training /// @return FAPI2_RC_SUCCESS iff ok /// fapi2::ReturnCode p9_mss_memdiag( const fapi2::Target<TARGET_TYPE_MCBIST>& i_target ) { FAPI_INF("Start memdiag"); // If there are no DIMM we don't need to bother. In fact, we can't as we didn't setup // attributes for the PHY, etc. if (mss::count_dimm(i_target) == 0) { FAPI_INF("... skipping mem_diags %s - no DIMM ...", mss::c_str(i_target)); return fapi2::FAPI2_RC_SUCCESS; } uint8_t l_sim = false; FAPI_TRY( mss::is_simulation( l_sim) ); // Read the bad_dq_bitmap attribute and place corresponding symbol and chip marks for (const auto& l_mca : mss::find_targets<TARGET_TYPE_MCA>(i_target)) { fapi2::buffer<uint8_t> l_repairs_applied; fapi2::buffer<uint8_t> l_repairs_exceeded; std::vector<uint64_t> l_ranks; FAPI_TRY( mss::restore_repairs( l_mca, l_repairs_applied, l_repairs_exceeded) ); // assert if we have exceeded the allowed repairs for (const auto& l_dimm : mss::find_targets<fapi2::TARGET_TYPE_DIMM>(l_mca)) { FAPI_ASSERT( !(l_repairs_exceeded.getBit(mss::index(l_dimm))), fapi2::MSS_MEMDIAGS_REPAIRS_EXCEEDED().set_TARGET(l_dimm), "p9_mss_memdiag bad bit repairs exceeded %s", mss::c_str(l_dimm) ); } #ifdef __HOSTBOOT_MODULE // assert if both chip and symbol marks exist for any given rank FAPI_TRY( mss::rank::ranks(l_mca, l_ranks) ); for (const auto l_rank : l_ranks) { if (l_repairs_applied.getBit(l_rank)) { uint64_t l_galois = 0; mss::states l_confirmed = mss::NO; // check for chip mark in hardware mark store FAPI_TRY( mss::ecc::get_hwms(l_mca, l_rank, l_galois, l_confirmed) ); if (l_confirmed) { auto l_type = mss::ecc::fwms::mark_type::CHIP; auto l_region = mss::ecc::fwms::mark_region::DISABLED; auto l_addr = mss::mcbist::address(0); // check for symbol mark in firmware mark store FAPI_TRY( mss::ecc::get_fwms(l_mca, l_rank, l_galois, l_type, l_region, l_addr) ); FAPI_ASSERT( l_region == mss::ecc::fwms::mark_region::DISABLED, fapi2::MSS_MEMDIAGS_CHIPMARK_AND_SYMBOLMARK().set_TARGET(l_mca).set_RANK(l_rank), "p9_mss_memdiag both chip mark and symbol mark on rank %d: %s", l_rank, mss::c_str(l_mca) ); } } } #endif } // We start the sf_init (write 0's) and it'll tickle the MCBIST complete FIR. PRD will see that // and start a background scrub. FAPI_TRY( memdiags::sf_init(i_target, mss::mcbist::PATTERN_0) ); // If we're in the sim, we want to poll for the FIR bit. I don't think this ever really happens // unless we're expressly testing this API. if (l_sim) { // Poll for the fir bit. We expect this to be set ... fapi2::buffer<uint64_t> l_status; // A small vector of addresses to poll during the polling loop const std::vector<mss::poll_probe<fapi2::TARGET_TYPE_MCBIST>> l_probes = { {i_target, "mcbist current address", MCBIST_MCBMCATQ}, }; mss::poll_parameters l_poll_parameters; bool l_poll_results = mss::poll(i_target, MCBIST_MCBISTFIRQ, l_poll_parameters, [&l_status](const size_t poll_remaining, const fapi2::buffer<uint64_t>& stat_reg) -> bool { FAPI_DBG("mcbist firq 0x%llx, remaining: %d", stat_reg, poll_remaining); l_status = stat_reg; return l_status.getBit<MCBIST_MCBISTFIRQ_MCBIST_PROGRAM_COMPLETE>() == true; }, l_probes); FAPI_ASSERT( l_poll_results == true, fapi2::MSS_MEMDIAGS_SUPERFAST_INIT_FAILED_TO_INIT().set_TARGET(i_target), "p9_mss_memdiags timedout %s", mss::c_str(i_target) ); } fapi_try_exit: FAPI_INF("End memdiag"); return fapi2::current_err; } } <commit_msg>Fixed memdiags fail<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/memory/p9_mss_memdiag.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file p9_mss_memdiag.C /// @brief Mainstore pattern testing /// // *HWP HWP Owner: Brian Silver <[email protected]> // *HWP HWP Backup: Andre Marin <[email protected]> // *HWP Team: Memory // *HWP Level: 2 // *HWP Consumed by: FSP:HB #include <fapi2.H> #include <p9_mss_memdiag.H> #include <lib/utils/poll.H> #include <generic/memory/lib/utils/find.H> #include <lib/utils/count_dimm.H> #include <lib/mcbist/address.H> #include <lib/mcbist/memdiags.H> #include <lib/mcbist/mcbist.H> #include <lib/mc/port.H> #include <lib/ecc/ecc.H> using fapi2::TARGET_TYPE_MCBIST; using fapi2::TARGET_TYPE_SYSTEM; using fapi2::TARGET_TYPE_MCA; extern "C" { /// /// @brief Pattern test the DRAM /// @param[in] i_target the McBIST of the ports of the dram you're training /// @return FAPI2_RC_SUCCESS iff ok /// fapi2::ReturnCode p9_mss_memdiag( const fapi2::Target<TARGET_TYPE_MCBIST>& i_target ) { FAPI_INF("Start memdiag"); // If there are no DIMM we don't need to bother. In fact, we can't as we didn't setup // attributes for the PHY, etc. if (mss::count_dimm(i_target) == 0) { FAPI_INF("... skipping mem_diags %s - no DIMM ...", mss::c_str(i_target)); return fapi2::FAPI2_RC_SUCCESS; } uint8_t l_sim = false; FAPI_TRY( mss::is_simulation( l_sim) ); // Read the bad_dq_bitmap attribute and place corresponding symbol and chip marks for (const auto& l_mca : mss::find_targets<TARGET_TYPE_MCA>(i_target)) { fapi2::buffer<uint8_t> l_repairs_applied; fapi2::buffer<uint8_t> l_repairs_exceeded; std::vector<uint64_t> l_ranks; FAPI_TRY( mss::restore_repairs( l_mca, l_repairs_applied, l_repairs_exceeded) ); // assert if we have exceeded the allowed repairs for (const auto& l_dimm : mss::find_targets<fapi2::TARGET_TYPE_DIMM>(l_mca)) { // Note: using MCA here as the scoms used to collect FFDC data fail on the DIMM level target FAPI_ASSERT( !(l_repairs_exceeded.getBit(mss::index(l_dimm))), fapi2::MSS_MEMDIAGS_REPAIRS_EXCEEDED().set_TARGET(l_mca), "p9_mss_memdiag bad bit repairs exceeded %s", mss::c_str(l_mca) ); } #ifdef __HOSTBOOT_MODULE // assert if both chip and symbol marks exist for any given rank FAPI_TRY( mss::rank::ranks(l_mca, l_ranks) ); for (const auto l_rank : l_ranks) { if (l_repairs_applied.getBit(l_rank)) { uint64_t l_galois = 0; mss::states l_confirmed = mss::NO; // check for chip mark in hardware mark store FAPI_TRY( mss::ecc::get_hwms(l_mca, l_rank, l_galois, l_confirmed) ); if (l_confirmed) { auto l_type = mss::ecc::fwms::mark_type::CHIP; auto l_region = mss::ecc::fwms::mark_region::DISABLED; auto l_addr = mss::mcbist::address(0); // check for symbol mark in firmware mark store FAPI_TRY( mss::ecc::get_fwms(l_mca, l_rank, l_galois, l_type, l_region, l_addr) ); FAPI_ASSERT( l_region == mss::ecc::fwms::mark_region::DISABLED, fapi2::MSS_MEMDIAGS_CHIPMARK_AND_SYMBOLMARK().set_TARGET(l_mca).set_RANK(l_rank), "p9_mss_memdiag both chip mark and symbol mark on rank %d: %s", l_rank, mss::c_str(l_mca) ); } } } #endif } // We start the sf_init (write 0's) and it'll tickle the MCBIST complete FIR. PRD will see that // and start a background scrub. FAPI_TRY( memdiags::sf_init(i_target, mss::mcbist::PATTERN_0) ); // If we're in the sim, we want to poll for the FIR bit. I don't think this ever really happens // unless we're expressly testing this API. if (l_sim) { // Poll for the fir bit. We expect this to be set ... fapi2::buffer<uint64_t> l_status; // A small vector of addresses to poll during the polling loop const std::vector<mss::poll_probe<fapi2::TARGET_TYPE_MCBIST>> l_probes = { {i_target, "mcbist current address", MCBIST_MCBMCATQ}, }; mss::poll_parameters l_poll_parameters; bool l_poll_results = mss::poll(i_target, MCBIST_MCBISTFIRQ, l_poll_parameters, [&l_status](const size_t poll_remaining, const fapi2::buffer<uint64_t>& stat_reg) -> bool { FAPI_DBG("mcbist firq 0x%llx, remaining: %d", stat_reg, poll_remaining); l_status = stat_reg; return l_status.getBit<MCBIST_MCBISTFIRQ_MCBIST_PROGRAM_COMPLETE>() == true; }, l_probes); FAPI_ASSERT( l_poll_results == true, fapi2::MSS_MEMDIAGS_SUPERFAST_INIT_FAILED_TO_INIT().set_TARGET(i_target), "p9_mss_memdiags timedout %s", mss::c_str(i_target) ); } fapi_try_exit: FAPI_INF("End memdiag"); return fapi2::current_err; } } <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ #ifndef INCLUDED_TOOLS_LINK_HXX #define INCLUDED_TOOLS_LINK_HXX #include <tools/toolsdllapi.h> #include <sal/config.h> #include <sal/types.h> #include <tools/solar.h> typedef sal_IntPtr (*PSTUB)( void*, void* ); #define DECL_LINK( Method, ArgType ) \ sal_IntPtr Method( ArgType ); \ static sal_IntPtr LinkStub##Method( void* pThis, void* ) #define DECL_STATIC_LINK( Class, Method, ArgType ) \ static sal_IntPtr LinkStub##Method( void* pThis, void* ); \ static sal_IntPtr Method( Class*, ArgType ) #define DECL_DLLPRIVATE_LINK(Method, ArgType) \ SAL_DLLPRIVATE sal_IntPtr Method(ArgType); \ SAL_DLLPRIVATE static sal_IntPtr LinkStub##Method(void * pThis, void *) #define DECL_DLLPRIVATE_STATIC_LINK(Class, Method, ArgType) \ SAL_DLLPRIVATE static sal_IntPtr LinkStub##Method( void* pThis, void* ); \ SAL_DLLPRIVATE static sal_IntPtr Method(Class *, ArgType) #define IMPL_STUB(Class, Method, ArgType) \ sal_IntPtr Class::LinkStub##Method( void* pThis, void* pCaller) \ { \ return static_cast<Class*>(pThis)->Method( static_cast<ArgType>(pCaller) ); \ } #define IMPL_STATIC_LINK( Class, Method, ArgType, ArgName ) \ sal_IntPtr Class::LinkStub##Method( void* pThis, void* pCaller) \ { \ return Method( static_cast<Class*>(pThis), static_cast<ArgType>(pCaller) ); \ } \ sal_IntPtr Class::Method( Class* pThis, ArgType ArgName ) #define IMPL_STATIC_LINK_NOINSTANCE( Class, Method, ArgType, ArgName ) \ sal_IntPtr Class::LinkStub##Method( void* pThis, void* pCaller) \ { \ return Method( static_cast<Class*>(pThis), static_cast<ArgType>(pCaller) ); \ } \ sal_IntPtr Class::Method( SAL_UNUSED_PARAMETER Class*, ArgType ArgName ) #define IMPL_STATIC_LINK_NOINSTANCE_NOARG( Class, Method ) \ sal_IntPtr Class::LinkStub##Method( void* pThis, void* pCaller) \ { \ return Method( static_cast<Class*>(pThis), pCaller ); \ } \ sal_IntPtr Class::Method( SAL_UNUSED_PARAMETER Class*, SAL_UNUSED_PARAMETER void* ) #define LINK( Inst, Class, Member ) \ Link( static_cast<Class*>(Inst), (PSTUB)&Class::LinkStub##Member ) #define STATIC_LINK( Inst, Class, Member ) LINK(Inst, Class, Member) #define IMPL_LINK( Class, Method, ArgType, ArgName ) \ IMPL_STUB( Class, Method, ArgType ) \ sal_IntPtr Class::Method( ArgType ArgName ) #define IMPL_LINK_NOARG( Class, Method ) \ IMPL_STUB( Class, Method, void* ) \ sal_IntPtr Class::Method( SAL_UNUSED_PARAMETER void* ) #define IMPL_LINK_INLINE_START( Class, Method, ArgType, ArgName ) \ inline sal_IntPtr Class::Method( ArgType ArgName ) #define IMPL_LINK_INLINE_END( Class, Method, ArgType, ArgName ) \ IMPL_STUB( Class, Method, ArgType ) #define IMPL_LINK_NOARG_INLINE_START( Class, Method ) \ inline sal_IntPtr Class::Method( SAL_UNUSED_PARAMETER void* ) #define IMPL_LINK_NOARG_INLINE_END( Class, Method ) \ IMPL_STUB( Class, Method, void* ) #define IMPL_LINK_INLINE( Class, Method, ArgType, ArgName, Body ) \ sal_IntPtr Class::Method( ArgType ArgName ) \ Body \ IMPL_STUB( Class, Method, ArgType ) #define EMPTYARG class TOOLS_DLLPUBLIC Link { void* pInst; PSTUB pFunc; public: Link(); Link( void* pLinkHdl, PSTUB pMemFunc ); sal_IntPtr Call( void* pCaller ) const; bool IsSet() const; bool operator !() const; bool operator==( const Link& rLink ) const; bool operator!=( const Link& rLink ) const { return !(Link::operator==( rLink )); } bool operator<( const Link& rLink ) const { return reinterpret_cast<sal_uIntPtr>(rLink.pFunc) < reinterpret_cast<sal_uIntPtr>(pFunc); } }; inline Link::Link() { pInst = 0; pFunc = 0; } inline Link::Link( void* pLinkHdl, PSTUB pMemFunc ) { pInst = pLinkHdl; pFunc = pMemFunc; } inline sal_IntPtr Link::Call(void *pCaller) const { return pFunc ? (*pFunc)(pInst, pCaller) : 0; } inline bool Link::IsSet() const { if ( pFunc ) return true; else return false; } inline bool Link::operator !() const { if ( !pFunc ) return true; else return false; } #endif /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>Remove redundant C-style cast<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ #ifndef INCLUDED_TOOLS_LINK_HXX #define INCLUDED_TOOLS_LINK_HXX #include <tools/toolsdllapi.h> #include <sal/config.h> #include <sal/types.h> #include <tools/solar.h> typedef sal_IntPtr (*PSTUB)( void*, void* ); #define DECL_LINK( Method, ArgType ) \ sal_IntPtr Method( ArgType ); \ static sal_IntPtr LinkStub##Method( void* pThis, void* ) #define DECL_STATIC_LINK( Class, Method, ArgType ) \ static sal_IntPtr LinkStub##Method( void* pThis, void* ); \ static sal_IntPtr Method( Class*, ArgType ) #define DECL_DLLPRIVATE_LINK(Method, ArgType) \ SAL_DLLPRIVATE sal_IntPtr Method(ArgType); \ SAL_DLLPRIVATE static sal_IntPtr LinkStub##Method(void * pThis, void *) #define DECL_DLLPRIVATE_STATIC_LINK(Class, Method, ArgType) \ SAL_DLLPRIVATE static sal_IntPtr LinkStub##Method( void* pThis, void* ); \ SAL_DLLPRIVATE static sal_IntPtr Method(Class *, ArgType) #define IMPL_STUB(Class, Method, ArgType) \ sal_IntPtr Class::LinkStub##Method( void* pThis, void* pCaller) \ { \ return static_cast<Class*>(pThis)->Method( static_cast<ArgType>(pCaller) ); \ } #define IMPL_STATIC_LINK( Class, Method, ArgType, ArgName ) \ sal_IntPtr Class::LinkStub##Method( void* pThis, void* pCaller) \ { \ return Method( static_cast<Class*>(pThis), static_cast<ArgType>(pCaller) ); \ } \ sal_IntPtr Class::Method( Class* pThis, ArgType ArgName ) #define IMPL_STATIC_LINK_NOINSTANCE( Class, Method, ArgType, ArgName ) \ sal_IntPtr Class::LinkStub##Method( void* pThis, void* pCaller) \ { \ return Method( static_cast<Class*>(pThis), static_cast<ArgType>(pCaller) ); \ } \ sal_IntPtr Class::Method( SAL_UNUSED_PARAMETER Class*, ArgType ArgName ) #define IMPL_STATIC_LINK_NOINSTANCE_NOARG( Class, Method ) \ sal_IntPtr Class::LinkStub##Method( void* pThis, void* pCaller) \ { \ return Method( static_cast<Class*>(pThis), pCaller ); \ } \ sal_IntPtr Class::Method( SAL_UNUSED_PARAMETER Class*, SAL_UNUSED_PARAMETER void* ) #define LINK( Inst, Class, Member ) \ Link( static_cast<Class*>(Inst), &Class::LinkStub##Member ) #define STATIC_LINK( Inst, Class, Member ) LINK(Inst, Class, Member) #define IMPL_LINK( Class, Method, ArgType, ArgName ) \ IMPL_STUB( Class, Method, ArgType ) \ sal_IntPtr Class::Method( ArgType ArgName ) #define IMPL_LINK_NOARG( Class, Method ) \ IMPL_STUB( Class, Method, void* ) \ sal_IntPtr Class::Method( SAL_UNUSED_PARAMETER void* ) #define IMPL_LINK_INLINE_START( Class, Method, ArgType, ArgName ) \ inline sal_IntPtr Class::Method( ArgType ArgName ) #define IMPL_LINK_INLINE_END( Class, Method, ArgType, ArgName ) \ IMPL_STUB( Class, Method, ArgType ) #define IMPL_LINK_NOARG_INLINE_START( Class, Method ) \ inline sal_IntPtr Class::Method( SAL_UNUSED_PARAMETER void* ) #define IMPL_LINK_NOARG_INLINE_END( Class, Method ) \ IMPL_STUB( Class, Method, void* ) #define IMPL_LINK_INLINE( Class, Method, ArgType, ArgName, Body ) \ sal_IntPtr Class::Method( ArgType ArgName ) \ Body \ IMPL_STUB( Class, Method, ArgType ) #define EMPTYARG class TOOLS_DLLPUBLIC Link { void* pInst; PSTUB pFunc; public: Link(); Link( void* pLinkHdl, PSTUB pMemFunc ); sal_IntPtr Call( void* pCaller ) const; bool IsSet() const; bool operator !() const; bool operator==( const Link& rLink ) const; bool operator!=( const Link& rLink ) const { return !(Link::operator==( rLink )); } bool operator<( const Link& rLink ) const { return reinterpret_cast<sal_uIntPtr>(rLink.pFunc) < reinterpret_cast<sal_uIntPtr>(pFunc); } }; inline Link::Link() { pInst = 0; pFunc = 0; } inline Link::Link( void* pLinkHdl, PSTUB pMemFunc ) { pInst = pLinkHdl; pFunc = pMemFunc; } inline sal_IntPtr Link::Call(void *pCaller) const { return pFunc ? (*pFunc)(pInst, pCaller) : 0; } inline bool Link::IsSet() const { if ( pFunc ) return true; else return false; } inline bool Link::operator !() const { if ( !pFunc ) return true; else return false; } #endif /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before><commit_msg>[TDF] Use right Doxy syntax to display image with link.<commit_after><|endoftext|>
<commit_before>/* $Id: ex18.C,v 1.13 2006-12-11 23:17:54 roystgnr Exp $ */ /* The Next Great Finite Element Library. */ /* Copyright (C) 2003 Benjamin S. Kirk */ /* This library is free software; you can redistribute it and/or */ /* modify it under the terms of the GNU Lesser General Public */ /* License as published by the Free Software Foundation; either */ /* version 2.1 of the License, or (at your option) any later version. */ /* This library is distributed in the hope that it will be useful, */ /* but WITHOUT ANY WARRANTY; without even the implied warranty of */ /* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU */ /* Lesser General Public License for more details. */ /* You should have received a copy of the GNU Lesser General Public */ /* License along with this library; if not, write to the Free Software */ /* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ // <h1>Example 18 - Unsteady Navier-Stokes Equations with DiffSystem</h1> // // This example shows how the transient nonlinear problem from // example 13 can be solved using the new (and experimental) // DiffSystem class framework // Basic include files #include "equation_systems.h" #include "error_vector.h" #include "getpot.h" #include "gmv_io.h" #include "kelly_error_estimator.h" #include "mesh.h" #include "mesh_generation.h" #include "mesh_refinement.h" #include "uniform_refinement_estimator.h" // Some (older) compilers do not offer full stream // functionality, OStringStream works around this. #include "o_string_stream.h" // The systems and solvers we may use #include "naviersystem.h" #include "diff_solver.h" #include "euler_solver.h" #include "steady_solver.h" // The main program. int main (int argc, char** argv) { // Initialize libMesh. libMesh::init (argc, argv); { // Parse the input file GetPot infile("ex18.in"); // Read in parameters from the input file const Real global_tolerance = infile("global_tolerance", 0.); const unsigned int nelem_target = infile("n_elements", 400); const bool transient = infile("transient", true); const Real deltat = infile("deltat", 0.005); unsigned int n_timesteps = infile("n_timesteps", 20); const unsigned int write_interval = infile("write_interval", 5); const unsigned int coarsegridsize = infile("coarsegridsize", 1); const unsigned int coarserefinements = infile("coarserefinements", 0); const unsigned int max_adaptivesteps = infile("max_adaptivesteps", 10); const unsigned int dim = infile("dimension", 2); assert (dim == 2 || dim == 3); // Create a n-dimensional mesh. Mesh mesh (dim); // And an object to refine it MeshRefinement mesh_refinement(mesh); mesh_refinement.coarsen_by_parents() = true; mesh_refinement.absolute_global_tolerance() = global_tolerance; mesh_refinement.nelem_target() = nelem_target; mesh_refinement.refine_fraction() = 0.3; mesh_refinement.coarsen_fraction() = 0.3; mesh_refinement.coarsen_threshold() = 0.1; // Use the MeshTools::Generation mesh generator to create a uniform // grid on the square [-1,1]^D. We instruct the mesh generator // to build a mesh of 8x8 \p Quad9 elements in 2D, or \p Hex27 // elements in 3D. Building these higher-order elements allows // us to use higher-order approximation, as in example 3. if (dim == 2) MeshTools::Generation::build_square (mesh, coarsegridsize, coarsegridsize, 0., 1., 0., 1., QUAD9); else if (dim == 3) MeshTools::Generation::build_cube (mesh, coarsegridsize, coarsegridsize, coarsegridsize, 0., 1., 0., 1., 0., 1., HEX27); mesh_refinement.uniformly_refine(coarserefinements); // Print information about the mesh to the screen. mesh.print_info(); // Create an equation systems object. EquationSystems equation_systems (mesh); // Declare the system "Navier-Stokes" and its variables. NavierSystem & system = equation_systems.add_system<NavierSystem> ("Navier-Stokes"); // Solve this as a time-dependent or steady system if (transient) system.time_solver = AutoPtr<TimeSolver>(new EulerSolver(system)); else { system.time_solver = AutoPtr<TimeSolver>(new SteadySolver(system)); assert(n_timesteps == 1); } // Initialize the system equation_systems.init (); // Set the time stepping options system.deltat = deltat; // And the nonlinear solver options DiffSolver &solver = *system.time_solver->diff_solver; solver.quiet = infile("solver_quiet", true); solver.max_nonlinear_iterations = infile("max_nonlinear_iterations", 15); solver.relative_step_tolerance = infile("relative_step_tolerance", 1.e-3); solver.relative_residual_tolerance = infile("relative_residual_tolerance", 0); // And the linear solver options solver.max_linear_iterations = infile("max_linear_iterations", 50000); solver.initial_linear_tolerance = infile("initial_linear_tolerance", 1.e-3); // Print information about the system to the screen. equation_systems.print_info(); // Now we begin the timestep loop to compute the time-accurate // solution of the equations. for (unsigned int t_step=0; t_step != n_timesteps; ++t_step) { // A pretty update message std::cout << " Solving time step " << t_step << ", time = " << system.time << std::endl; // Adaptively solve the timestep unsigned int a_step = 0; for (; a_step != max_adaptivesteps; ++a_step) { system.solve(); ErrorVector error; AutoPtr<ErrorEstimator> error_estimator; // To solve to a tolerance in this problem we // need a better estimator than Kelly if (global_tolerance != 0.) { // We can't adapt to both a tolerance and a mesh // size at once assert (nelem_target == 0); UniformRefinementEstimator *u = new UniformRefinementEstimator; // The lid-driven cavity problem isn't in H1, so // lets estimate H0 (i.e. L2) error u->sobolev_order() = 0; error_estimator.reset(u); } else { // If we aren't adapting to a tolerance we need a // target mesh size assert (nelem_target > 0); // Kelly is a lousy estimator to use for a problem // not in H1 - if we were doing more than a few // timesteps we'd need to turn off or limit the // maximum level of our adaptivity eventually error_estimator.reset(new KellyErrorEstimator); } // Calculate error based on u and v but not p error_estimator->component_scale.push_back(1.0); // u error_estimator->component_scale.push_back(1.0); // v if (dim == 3) error_estimator->component_scale.push_back(1.0); // w error_estimator->component_scale.push_back(0.0); // p error_estimator->estimate_error(system, error); // Print out status at each adaptive step. Real global_error = error.l2_norm(); std::cout << "adaptive step " << a_step << ": "; if (global_tolerance != 0.) std::cout << "global_error = " << global_error << " with "; std::cout << mesh.n_active_elem() << " active elements and " << equation_systems.n_active_dofs() << " active dofs." << std::endl; if (global_tolerance != 0.) std::cout << "worst element error = " << error.maximum() << ", mean = " << error.mean() << std::endl; if (global_tolerance != 0.) { // If we've reached our desired tolerance, we // don't need any more adaptive steps if (global_error < global_tolerance) break; mesh_refinement.flag_elements_by_error_tolerance(error); } else { // If flag_elements_by_nelem_target returns true, this // should be our last adaptive step. if (mesh_refinement.flag_elements_by_nelem_target(error)) { mesh_refinement.refine_and_coarsen_elements(); equation_systems.reinit(); break; } } // Carry out the adaptive mesh refinement/coarsening mesh_refinement.refine_and_coarsen_elements(); equation_systems.reinit(); } // Do one last solve if necessary if (a_step == max_adaptivesteps) { system.solve(); } // Advance to the next timestep in a transient problem system.time_solver->advance_timestep(); // Write out this timestep if we're requested to if ((t_step+1)%write_interval == 0) { OStringStream file_name; // We write the file name in the gmv auto-read format. file_name << "out.gmv."; OSSRealzeroright(file_name,3,0, t_step + 1); GMVIO(mesh).write_equation_systems (file_name.str(), equation_systems); } } } // All done. return libMesh::close (); } <commit_msg>time_solver->diff_solver() is now a function returning an AutoPtr.<commit_after>/* $Id: ex18.C,v 1.14 2007-02-27 16:02:58 jwpeterson Exp $ */ /* The Next Great Finite Element Library. */ /* Copyright (C) 2003 Benjamin S. Kirk */ /* This library is free software; you can redistribute it and/or */ /* modify it under the terms of the GNU Lesser General Public */ /* License as published by the Free Software Foundation; either */ /* version 2.1 of the License, or (at your option) any later version. */ /* This library is distributed in the hope that it will be useful, */ /* but WITHOUT ANY WARRANTY; without even the implied warranty of */ /* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU */ /* Lesser General Public License for more details. */ /* You should have received a copy of the GNU Lesser General Public */ /* License along with this library; if not, write to the Free Software */ /* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ // <h1>Example 18 - Unsteady Navier-Stokes Equations with DiffSystem</h1> // // This example shows how the transient nonlinear problem from // example 13 can be solved using the new (and experimental) // DiffSystem class framework // Basic include files #include "equation_systems.h" #include "error_vector.h" #include "getpot.h" #include "gmv_io.h" #include "kelly_error_estimator.h" #include "mesh.h" #include "mesh_generation.h" #include "mesh_refinement.h" #include "uniform_refinement_estimator.h" // Some (older) compilers do not offer full stream // functionality, OStringStream works around this. #include "o_string_stream.h" // The systems and solvers we may use #include "naviersystem.h" #include "diff_solver.h" #include "euler_solver.h" #include "steady_solver.h" // The main program. int main (int argc, char** argv) { // Initialize libMesh. libMesh::init (argc, argv); { // Parse the input file GetPot infile("ex18.in"); // Read in parameters from the input file const Real global_tolerance = infile("global_tolerance", 0.); const unsigned int nelem_target = infile("n_elements", 400); const bool transient = infile("transient", true); const Real deltat = infile("deltat", 0.005); unsigned int n_timesteps = infile("n_timesteps", 20); const unsigned int write_interval = infile("write_interval", 5); const unsigned int coarsegridsize = infile("coarsegridsize", 1); const unsigned int coarserefinements = infile("coarserefinements", 0); const unsigned int max_adaptivesteps = infile("max_adaptivesteps", 10); const unsigned int dim = infile("dimension", 2); assert (dim == 2 || dim == 3); // Create a n-dimensional mesh. Mesh mesh (dim); // And an object to refine it MeshRefinement mesh_refinement(mesh); mesh_refinement.coarsen_by_parents() = true; mesh_refinement.absolute_global_tolerance() = global_tolerance; mesh_refinement.nelem_target() = nelem_target; mesh_refinement.refine_fraction() = 0.3; mesh_refinement.coarsen_fraction() = 0.3; mesh_refinement.coarsen_threshold() = 0.1; // Use the MeshTools::Generation mesh generator to create a uniform // grid on the square [-1,1]^D. We instruct the mesh generator // to build a mesh of 8x8 \p Quad9 elements in 2D, or \p Hex27 // elements in 3D. Building these higher-order elements allows // us to use higher-order approximation, as in example 3. if (dim == 2) MeshTools::Generation::build_square (mesh, coarsegridsize, coarsegridsize, 0., 1., 0., 1., QUAD9); else if (dim == 3) MeshTools::Generation::build_cube (mesh, coarsegridsize, coarsegridsize, coarsegridsize, 0., 1., 0., 1., 0., 1., HEX27); mesh_refinement.uniformly_refine(coarserefinements); // Print information about the mesh to the screen. mesh.print_info(); // Create an equation systems object. EquationSystems equation_systems (mesh); // Declare the system "Navier-Stokes" and its variables. NavierSystem & system = equation_systems.add_system<NavierSystem> ("Navier-Stokes"); // Solve this as a time-dependent or steady system if (transient) system.time_solver = AutoPtr<TimeSolver>(new EulerSolver(system)); else { system.time_solver = AutoPtr<TimeSolver>(new SteadySolver(system)); assert(n_timesteps == 1); } // Initialize the system equation_systems.init (); // Set the time stepping options system.deltat = deltat; // And the nonlinear solver options DiffSolver &solver = *(system.time_solver->diff_solver().get()); solver.quiet = infile("solver_quiet", true); solver.max_nonlinear_iterations = infile("max_nonlinear_iterations", 15); solver.relative_step_tolerance = infile("relative_step_tolerance", 1.e-3); solver.relative_residual_tolerance = infile("relative_residual_tolerance", 0); // And the linear solver options solver.max_linear_iterations = infile("max_linear_iterations", 50000); solver.initial_linear_tolerance = infile("initial_linear_tolerance", 1.e-3); // Print information about the system to the screen. equation_systems.print_info(); // Now we begin the timestep loop to compute the time-accurate // solution of the equations. for (unsigned int t_step=0; t_step != n_timesteps; ++t_step) { // A pretty update message std::cout << " Solving time step " << t_step << ", time = " << system.time << std::endl; // Adaptively solve the timestep unsigned int a_step = 0; for (; a_step != max_adaptivesteps; ++a_step) { system.solve(); ErrorVector error; AutoPtr<ErrorEstimator> error_estimator; // To solve to a tolerance in this problem we // need a better estimator than Kelly if (global_tolerance != 0.) { // We can't adapt to both a tolerance and a mesh // size at once assert (nelem_target == 0); UniformRefinementEstimator *u = new UniformRefinementEstimator; // The lid-driven cavity problem isn't in H1, so // lets estimate H0 (i.e. L2) error u->sobolev_order() = 0; error_estimator.reset(u); } else { // If we aren't adapting to a tolerance we need a // target mesh size assert (nelem_target > 0); // Kelly is a lousy estimator to use for a problem // not in H1 - if we were doing more than a few // timesteps we'd need to turn off or limit the // maximum level of our adaptivity eventually error_estimator.reset(new KellyErrorEstimator); } // Calculate error based on u and v but not p error_estimator->component_scale.push_back(1.0); // u error_estimator->component_scale.push_back(1.0); // v if (dim == 3) error_estimator->component_scale.push_back(1.0); // w error_estimator->component_scale.push_back(0.0); // p error_estimator->estimate_error(system, error); // Print out status at each adaptive step. Real global_error = error.l2_norm(); std::cout << "adaptive step " << a_step << ": "; if (global_tolerance != 0.) std::cout << "global_error = " << global_error << " with "; std::cout << mesh.n_active_elem() << " active elements and " << equation_systems.n_active_dofs() << " active dofs." << std::endl; if (global_tolerance != 0.) std::cout << "worst element error = " << error.maximum() << ", mean = " << error.mean() << std::endl; if (global_tolerance != 0.) { // If we've reached our desired tolerance, we // don't need any more adaptive steps if (global_error < global_tolerance) break; mesh_refinement.flag_elements_by_error_tolerance(error); } else { // If flag_elements_by_nelem_target returns true, this // should be our last adaptive step. if (mesh_refinement.flag_elements_by_nelem_target(error)) { mesh_refinement.refine_and_coarsen_elements(); equation_systems.reinit(); break; } } // Carry out the adaptive mesh refinement/coarsening mesh_refinement.refine_and_coarsen_elements(); equation_systems.reinit(); } // Do one last solve if necessary if (a_step == max_adaptivesteps) { system.solve(); } // Advance to the next timestep in a transient problem system.time_solver->advance_timestep(); // Write out this timestep if we're requested to if ((t_step+1)%write_interval == 0) { OStringStream file_name; // We write the file name in the gmv auto-read format. file_name << "out.gmv."; OSSRealzeroright(file_name,3,0, t_step + 1); GMVIO(mesh).write_equation_systems (file_name.str(), equation_systems); } } } // All done. return libMesh::close (); } <|endoftext|>
<commit_before>#pragma once /** @file GaussLegendre.hpp * @brief * @author C.D. Clark III * @date 08/04/17 */ #include<array> namespace _2D { namespace GQ { template<typename T, size_t Order> class GaussLegendreQuadrature { public: _1D::GQ::GaussLegendreQuadrature<T,Order> _1dInt; GaussLegendreQuadrature() = default; // This version will integrate a callable between four points template<typename F, typename X, typename Y> T operator()( F f, X a, X b, Y c, Y d ) const; protected: }; template<typename T, size_t Order> template<typename F, typename X, typename Y> T GaussLegendreQuadrature<T,Order>::operator()(F f, X a, X b, Y c, Y d) const { // A 2D integral I = \int \int f(x,y) dx dy // can be written as two 1D integrals // // g(x) = \int f(x,y) dy // I = \int g(x) dx // // first, integrate over y at each of the required points (i.e. create g(x_i)) X apb = (b + a)/2; X amb = (b - a)/2; std::array<T, Order> sums; #pragma parallel for for(size_t i = 0; i < Order; i++) sums[i] = _1dInt( [&](Y y){ return f(apb + amb*_1dInt.getX()[i], y); }, c, d ); // now integrate over x T sum = 0; for(size_t i = 0; i < Order; i++) sum += _1dInt.getW()[i]*sums[i]; sum *= amb; return sum; } } } <commit_msg>feat: added missing header to 2D Gaussian quadrature.<commit_after>#pragma once /** @file GaussLegendre.hpp * @brief * @author C.D. Clark III * @date 08/04/17 */ #include<array> #include "../../_1D/GaussianQuadratures/GaussLegendre.hpp" namespace _2D { namespace GQ { template<typename T, size_t Order> class GaussLegendreQuadrature { public: _1D::GQ::GaussLegendreQuadrature<T,Order> _1dInt; GaussLegendreQuadrature() = default; // This version will integrate a callable between four points template<typename F, typename X, typename Y> T operator()( F f, X a, X b, Y c, Y d ) const; protected: }; template<typename T, size_t Order> template<typename F, typename X, typename Y> T GaussLegendreQuadrature<T,Order>::operator()(F f, X a, X b, Y c, Y d) const { // A 2D integral I = \int \int f(x,y) dx dy // can be written as two 1D integrals // // g(x) = \int f(x,y) dy // I = \int g(x) dx // // first, integrate over y at each of the required points (i.e. create g(x_i)) X apb = (b + a)/2; X amb = (b - a)/2; std::array<T, Order> sums; #pragma parallel for for(size_t i = 0; i < Order; i++) sums[i] = _1dInt( [&](Y y){ return f(apb + amb*_1dInt.getX()[i], y); }, c, d ); // now integrate over x T sum = 0; for(size_t i = 0; i < Order; i++) sum += _1dInt.getW()[i]*sums[i]; sum *= amb; return sum; } } } <|endoftext|>
<commit_before>/*********************************************************************** filename: TreeView.cpp created: Fri Jun 06 2014 author: Timotei Dolean <[email protected]> purpose: Implementation of the base class for all item model-based views. *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ #include "CEGUI/views/TreeView.h" #include "CEGUI/CoordConverter.h" namespace CEGUI { //----------------------------------------------------------------------------// TreeViewWindowRenderer::TreeViewWindowRenderer(const String& type) : ItemViewWindowRenderer(type) { } //----------------------------------------------------------------------------// const String TreeView::EventNamespace("TreeView"); const String TreeView::WidgetTypeName("CEGUI/TreeView"); //----------------------------------------------------------------------------// TreeViewItemRenderingState::TreeViewItemRenderingState() : d_totalChildCount(0), d_size(0, 0), d_isSelected(false), d_childId(0), d_subtreeIsExpanded(false) { } //----------------------------------------------------------------------------// TreeView::TreeView(const String& type, const String& name) : ItemView(type, name) { } //----------------------------------------------------------------------------// TreeView::~TreeView() { } //----------------------------------------------------------------------------// const TreeViewItemRenderingState& TreeView::getRootItemState() const { return d_rootItemState; } //----------------------------------------------------------------------------// void TreeView::prepareForRender() { ItemView::prepareForRender(); if (d_itemModel == 0 || !isDirty()) return; ModelIndex root_index = d_itemModel->getRootIndex(); d_renderedMaxWidth = 0; d_renderedTotalHeight = 0; d_rootItemState = TreeViewItemRenderingState(); d_rootItemState.d_subtreeIsExpanded = true; computeRenderedChildrenForItem(d_rootItemState, root_index, d_renderedMaxWidth, d_renderedTotalHeight); updateScrollbars(); setIsDirty(false); } //----------------------------------------------------------------------------// bool TreeView::handleSelection(const Vector2f& position, bool should_select, bool is_cumulative, bool is_range) { return handleSelection( indexAtWithAction(position, &TreeView::handleSelectionAction), should_select, is_cumulative, is_range); } //----------------------------------------------------------------------------// bool TreeView::handleSelection(const ModelIndex& index, bool should_select, bool is_cumulative, bool is_range) { return ItemView::handleSelection(index, should_select, is_cumulative, is_range); } //----------------------------------------------------------------------------// TreeViewItemRenderingState TreeView::computeRenderingStateForIndex( const ModelIndex& index, float& rendered_max_width, float& rendered_total_height) { if (d_itemModel == 0) return TreeViewItemRenderingState(); TreeViewItemRenderingState state; String text = d_itemModel->getData(index); RenderedString rendered_string = getRenderedStringParser().parse( text, getFont(), &d_textColourRect); state.d_string = rendered_string; state.d_size = Sizef( rendered_string.getHorizontalExtent(this), rendered_string.getVerticalExtent(this)); rendered_max_width = ceguimax(rendered_max_width, state.d_size.d_width); rendered_total_height += state.d_size.d_height; state.d_isSelected = isIndexSelected(index); computeRenderedChildrenForItem(state, index, rendered_max_width, rendered_total_height); return state; } //----------------------------------------------------------------------------// ModelIndex TreeView::indexAt(const Vector2f& position) { return indexAtWithAction(position, &TreeView::noopAction); } //----------------------------------------------------------------------------// CEGUI::ModelIndex TreeView::indexAtWithAction(const Vector2f& position, TreeViewItemAction action) { if (d_itemModel == 0) return ModelIndex(); //TODO: add prepareForLayout() as a cheaper operation alternative? prepareForRender(); Vector2f window_position = CoordConverter::screenToWindow(*this, position); Rectf render_area(getViewRenderer()->getViewRenderArea()); if (!render_area.isPointInRect(window_position)) return ModelIndex(); float cur_height = render_area.d_min.d_y - getVertScrollbar()->getScrollPosition(); bool handled = false; return indexAtRecursive(d_rootItemState, cur_height, window_position, handled, action); } //----------------------------------------------------------------------------// ModelIndex TreeView::indexAtRecursive(TreeViewItemRenderingState& item, float& cur_height, const Vector2f& window_position, bool& handled, TreeViewItemAction action) { float next_height = cur_height + item.d_size.d_height; if (window_position.d_y >= cur_height && window_position.d_y <= next_height) { handled = true; float subtree_expander_width = getViewRenderer()->getSubtreeExpanderSize().d_width; if (window_position.d_x >= 0 && window_position.d_x <= subtree_expander_width) { (this->*action)(item, true); return ModelIndex(); } (this->*action)(item, false); return ModelIndex(d_itemModel->makeIndex(item.d_childId, item.d_parentIndex)); } cur_height = next_height; for (size_t i = 0; i < item.d_renderedChildren.size(); ++i) { ModelIndex index = indexAtRecursive(item.d_renderedChildren.at(i), cur_height, window_position, handled, action); if (handled) return index; } return ModelIndex(); } //----------------------------------------------------------------------------// TreeViewWindowRenderer* TreeView::getViewRenderer() { return static_cast<TreeViewWindowRenderer*>(ItemView::getViewRenderer()); } //----------------------------------------------------------------------------// void TreeView::toggleSubtree(TreeViewItemRenderingState& item) { item.d_subtreeIsExpanded = !item.d_subtreeIsExpanded; std::cout << "Toggled. " << item.d_text << std::endl; if (item.d_subtreeIsExpanded) { computeRenderedChildrenForItem(item, d_itemModel->makeIndex(item.d_childId, item.d_parentIndex), d_renderedMaxWidth, d_renderedTotalHeight); } else { clearItemRenderedChildren(item, d_renderedTotalHeight); } updateScrollbars(); invalidate(false); } //----------------------------------------------------------------------------// void TreeView::computeRenderedChildrenForItem(TreeViewItemRenderingState &item, const ModelIndex& index, float& rendered_max_width, float& rendered_total_height) { if (d_itemModel == 0) return; size_t child_count = d_itemModel->getChildCount(index); item.d_totalChildCount = child_count; if (!item.d_subtreeIsExpanded) return; for (size_t child = 0; child < child_count; ++child) { ModelIndex child_index = d_itemModel->makeIndex(child, index); TreeViewItemRenderingState child_state = computeRenderingStateForIndex(child_index, rendered_max_width, rendered_total_height); child_state.d_parentIndex = index; child_state.d_childId = child; item.d_renderedChildren.push_back(child_state); } } //----------------------------------------------------------------------------// void TreeView::clearItemRenderedChildren(TreeViewItemRenderingState& item, float& renderedTotalHeight) { std::vector<TreeViewItemRenderingState>::iterator itor = item.d_renderedChildren.begin(); while (itor != item.d_renderedChildren.end()) { clearItemRenderedChildren(*itor, renderedTotalHeight); d_renderedTotalHeight -= item.d_size.d_height; itor = item.d_renderedChildren.erase(itor); } } //----------------------------------------------------------------------------// void TreeView::handleSelectionAction(TreeViewItemRenderingState& item, bool toggles_expander) { if (!toggles_expander) return; toggleSubtree(item); } } <commit_msg>Remove debug leftover line :D<commit_after>/*********************************************************************** filename: TreeView.cpp created: Fri Jun 06 2014 author: Timotei Dolean <[email protected]> purpose: Implementation of the base class for all item model-based views. *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ #include "CEGUI/views/TreeView.h" #include "CEGUI/CoordConverter.h" namespace CEGUI { //----------------------------------------------------------------------------// TreeViewWindowRenderer::TreeViewWindowRenderer(const String& type) : ItemViewWindowRenderer(type) { } //----------------------------------------------------------------------------// const String TreeView::EventNamespace("TreeView"); const String TreeView::WidgetTypeName("CEGUI/TreeView"); //----------------------------------------------------------------------------// TreeViewItemRenderingState::TreeViewItemRenderingState() : d_totalChildCount(0), d_size(0, 0), d_isSelected(false), d_childId(0), d_subtreeIsExpanded(false) { } //----------------------------------------------------------------------------// TreeView::TreeView(const String& type, const String& name) : ItemView(type, name) { } //----------------------------------------------------------------------------// TreeView::~TreeView() { } //----------------------------------------------------------------------------// const TreeViewItemRenderingState& TreeView::getRootItemState() const { return d_rootItemState; } //----------------------------------------------------------------------------// void TreeView::prepareForRender() { ItemView::prepareForRender(); if (d_itemModel == 0 || !isDirty()) return; ModelIndex root_index = d_itemModel->getRootIndex(); d_renderedMaxWidth = 0; d_renderedTotalHeight = 0; d_rootItemState = TreeViewItemRenderingState(); d_rootItemState.d_subtreeIsExpanded = true; computeRenderedChildrenForItem(d_rootItemState, root_index, d_renderedMaxWidth, d_renderedTotalHeight); updateScrollbars(); setIsDirty(false); } //----------------------------------------------------------------------------// bool TreeView::handleSelection(const Vector2f& position, bool should_select, bool is_cumulative, bool is_range) { return handleSelection( indexAtWithAction(position, &TreeView::handleSelectionAction), should_select, is_cumulative, is_range); } //----------------------------------------------------------------------------// bool TreeView::handleSelection(const ModelIndex& index, bool should_select, bool is_cumulative, bool is_range) { return ItemView::handleSelection(index, should_select, is_cumulative, is_range); } //----------------------------------------------------------------------------// TreeViewItemRenderingState TreeView::computeRenderingStateForIndex( const ModelIndex& index, float& rendered_max_width, float& rendered_total_height) { if (d_itemModel == 0) return TreeViewItemRenderingState(); TreeViewItemRenderingState state; String text = d_itemModel->getData(index); RenderedString rendered_string = getRenderedStringParser().parse( text, getFont(), &d_textColourRect); state.d_string = rendered_string; state.d_size = Sizef( rendered_string.getHorizontalExtent(this), rendered_string.getVerticalExtent(this)); rendered_max_width = ceguimax(rendered_max_width, state.d_size.d_width); rendered_total_height += state.d_size.d_height; state.d_isSelected = isIndexSelected(index); computeRenderedChildrenForItem(state, index, rendered_max_width, rendered_total_height); return state; } //----------------------------------------------------------------------------// ModelIndex TreeView::indexAt(const Vector2f& position) { return indexAtWithAction(position, &TreeView::noopAction); } //----------------------------------------------------------------------------// CEGUI::ModelIndex TreeView::indexAtWithAction(const Vector2f& position, TreeViewItemAction action) { if (d_itemModel == 0) return ModelIndex(); //TODO: add prepareForLayout() as a cheaper operation alternative? prepareForRender(); Vector2f window_position = CoordConverter::screenToWindow(*this, position); Rectf render_area(getViewRenderer()->getViewRenderArea()); if (!render_area.isPointInRect(window_position)) return ModelIndex(); float cur_height = render_area.d_min.d_y - getVertScrollbar()->getScrollPosition(); bool handled = false; return indexAtRecursive(d_rootItemState, cur_height, window_position, handled, action); } //----------------------------------------------------------------------------// ModelIndex TreeView::indexAtRecursive(TreeViewItemRenderingState& item, float& cur_height, const Vector2f& window_position, bool& handled, TreeViewItemAction action) { float next_height = cur_height + item.d_size.d_height; if (window_position.d_y >= cur_height && window_position.d_y <= next_height) { handled = true; float subtree_expander_width = getViewRenderer()->getSubtreeExpanderSize().d_width; if (window_position.d_x >= 0 && window_position.d_x <= subtree_expander_width) { (this->*action)(item, true); return ModelIndex(); } (this->*action)(item, false); return ModelIndex(d_itemModel->makeIndex(item.d_childId, item.d_parentIndex)); } cur_height = next_height; for (size_t i = 0; i < item.d_renderedChildren.size(); ++i) { ModelIndex index = indexAtRecursive(item.d_renderedChildren.at(i), cur_height, window_position, handled, action); if (handled) return index; } return ModelIndex(); } //----------------------------------------------------------------------------// TreeViewWindowRenderer* TreeView::getViewRenderer() { return static_cast<TreeViewWindowRenderer*>(ItemView::getViewRenderer()); } //----------------------------------------------------------------------------// void TreeView::toggleSubtree(TreeViewItemRenderingState& item) { item.d_subtreeIsExpanded = !item.d_subtreeIsExpanded; if (item.d_subtreeIsExpanded) { computeRenderedChildrenForItem(item, d_itemModel->makeIndex(item.d_childId, item.d_parentIndex), d_renderedMaxWidth, d_renderedTotalHeight); } else { clearItemRenderedChildren(item, d_renderedTotalHeight); } updateScrollbars(); invalidate(false); } //----------------------------------------------------------------------------// void TreeView::computeRenderedChildrenForItem(TreeViewItemRenderingState &item, const ModelIndex& index, float& rendered_max_width, float& rendered_total_height) { if (d_itemModel == 0) return; size_t child_count = d_itemModel->getChildCount(index); item.d_totalChildCount = child_count; if (!item.d_subtreeIsExpanded) return; for (size_t child = 0; child < child_count; ++child) { ModelIndex child_index = d_itemModel->makeIndex(child, index); TreeViewItemRenderingState child_state = computeRenderingStateForIndex(child_index, rendered_max_width, rendered_total_height); child_state.d_parentIndex = index; child_state.d_childId = child; item.d_renderedChildren.push_back(child_state); } } //----------------------------------------------------------------------------// void TreeView::clearItemRenderedChildren(TreeViewItemRenderingState& item, float& renderedTotalHeight) { std::vector<TreeViewItemRenderingState>::iterator itor = item.d_renderedChildren.begin(); while (itor != item.d_renderedChildren.end()) { clearItemRenderedChildren(*itor, renderedTotalHeight); d_renderedTotalHeight -= item.d_size.d_height; itor = item.d_renderedChildren.erase(itor); } } //----------------------------------------------------------------------------// void TreeView::handleSelectionAction(TreeViewItemRenderingState& item, bool toggles_expander) { if (!toggles_expander) return; toggleSubtree(item); } } <|endoftext|>
<commit_before><commit_msg>[Oops] Accidentally added file<commit_after><|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the Qt Creator. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "maemoruncontrol.h" #include "maemosshthread.h" #include "maemorunconfiguration.h" #include <coreplugin/icore.h> #include <coreplugin/progressmanager/progressmanager.h> #include <debugger/debuggermanager.h> #include <extensionsystem/pluginmanager.h> #include <projectexplorer/toolchain.h> #include <utils/qtcassert.h> #include <QtCore/QDir> #include <QtCore/QFileInfo> #include <QtCore/QFuture> #include <QtCore/QProcess> #include <QtCore/QStringBuilder> #include <QtGui/QMessageBox> namespace Qt4ProjectManager { namespace Internal { using ProjectExplorer::RunConfiguration; using ProjectExplorer::ToolChain; AbstractMaemoRunControl::AbstractMaemoRunControl(RunConfiguration *rc) : RunControl(rc) , runConfig(qobject_cast<MaemoRunConfiguration *>(rc)) , devConfig(runConfig ? runConfig->deviceConfig() : MaemoDeviceConfig()) { } AbstractMaemoRunControl::~AbstractMaemoRunControl() { } void AbstractMaemoRunControl::startDeployment(bool forDebugging) { QTC_ASSERT(runConfig, return); if (devConfig.isValid()) { deployables.clear(); if (runConfig->currentlyNeedsDeployment(devConfig.host)) { deployables.append(Deployable(executableFileName(), QFileInfo(executableOnHost()).canonicalPath(), &MaemoRunConfiguration::wasDeployed)); } if (forDebugging && runConfig->debuggingHelpersNeedDeployment(devConfig.host)) { const QFileInfo &info(runConfig->dumperLib()); deployables.append(Deployable(info.fileName(), info.canonicalPath(), &MaemoRunConfiguration::debuggingHelpersDeployed)); } deploy(); } else { handleError(tr("No device configuration set for run configuration.")); handleDeploymentFinished(false); } } void AbstractMaemoRunControl::deploy() { Core::ICore::instance()->progressManager() ->addTask(m_progress.future(), tr("Deploying"), QLatin1String("Maemo.Deploy")); if (!deployables.isEmpty()) { QList<SshDeploySpec> deploySpecs; QStringList files; foreach (const Deployable &deployable, deployables) { const QString srcFilePath = deployable.dir % QDir::separator() % deployable.fileName; const QString tgtFilePath = remoteDir() % QDir::separator() % deployable.fileName; files << srcFilePath; deploySpecs << SshDeploySpec(srcFilePath, tgtFilePath); } emit addToOutputWindow(this, tr("Files to deploy: %1.").arg(files.join(" "))); sshDeployer.reset(new MaemoSshDeployer(devConfig, deploySpecs)); connect(sshDeployer.data(), SIGNAL(finished()), this, SLOT(deployProcessFinished())); connect(sshDeployer.data(), SIGNAL(fileCopied(QString)), this, SLOT(handleFileCopied())); m_progress.setProgressRange(0, deployables.count()); m_progress.setProgressValue(0); m_progress.reportStarted(); emit started(); sshDeployer->start(); } else { m_progress.reportFinished(); handleDeploymentFinished(true); } } void AbstractMaemoRunControl::handleFileCopied() { Deployable deployable = deployables.takeFirst(); (runConfig->*deployable.updateTimestamp)(devConfig.host); m_progress.setProgressValue(m_progress.progressValue() + 1); } void AbstractMaemoRunControl::stopDeployment() { sshDeployer->stop(); } bool AbstractMaemoRunControl::isDeploying() const { return !sshDeployer.isNull() && sshDeployer->isRunning(); } void AbstractMaemoRunControl::deployProcessFinished() { const bool success = !sshDeployer->hasError(); if (success) { emit addToOutputWindow(this, tr("Deployment finished.")); } else { handleError(tr("Deployment failed: %1").arg(sshDeployer->error())); m_progress.reportCanceled(); } m_progress.reportFinished(); handleDeploymentFinished(success); } const QString AbstractMaemoRunControl::executableOnHost() const { qDebug("runconfig->executable: %s", qPrintable(runConfig->executable())); return runConfig->executable(); } const QString AbstractMaemoRunControl::sshPort() const { return devConfig.type == MaemoDeviceConfig::Physical ? QString::number(devConfig.sshPort) : runConfig->simulatorSshPort(); } const QString AbstractMaemoRunControl::executableFileName() const { return QFileInfo(executableOnHost()).fileName(); } const QString AbstractMaemoRunControl::remoteDir() const { return homeDirOnDevice(devConfig.uname); } const QStringList AbstractMaemoRunControl::options() const { const bool usePassword = devConfig.authentication == MaemoDeviceConfig::Password; const QLatin1String opt("-o"); QStringList optionList; if (!usePassword) optionList << QLatin1String("-i") << devConfig.keyFile; return optionList << opt << QString::fromLatin1("PasswordAuthentication=%1"). arg(usePassword ? "yes" : "no") << opt << QString::fromLatin1("PubkeyAuthentication=%1"). arg(usePassword ? "no" : "yes") << opt << QString::fromLatin1("ConnectTimeout=%1").arg(devConfig.timeout) << opt << QLatin1String("CheckHostIP=no") << opt << QLatin1String("StrictHostKeyChecking=no"); } const QString AbstractMaemoRunControl::executableOnTarget() const { return QString::fromLocal8Bit("%1/%2").arg(remoteDir()). arg(executableFileName()); } const QString AbstractMaemoRunControl::targetCmdLinePrefix() const { return QString::fromLocal8Bit("chmod u+x %1; source /etc/profile; "). arg(executableOnTarget()); } void AbstractMaemoRunControl::handleError(const QString &errString) { QMessageBox::critical(0, tr("Remote Execution Failure"), errString); emit error(this, errString); } MaemoRunControl::MaemoRunControl(RunConfiguration *runConfiguration) : AbstractMaemoRunControl(runConfiguration) { } MaemoRunControl::~MaemoRunControl() { stop(); } void MaemoRunControl::start() { stoppedByUser = false; startDeployment(false); } void MaemoRunControl::handleDeploymentFinished(bool success) { if (success) startExecution(); else emit finished(); } void MaemoRunControl::startExecution() { const QString remoteCall = QString::fromLocal8Bit("%1 %2 %3") .arg(targetCmdLinePrefix()).arg(executableOnTarget()) .arg(runConfig->arguments().join(" ")); sshRunner.reset(new MaemoSshRunner(devConfig, remoteCall)); connect(sshRunner.data(), SIGNAL(remoteOutput(QString)), this, SLOT(handleRemoteOutput(QString))); connect(sshRunner.data(), SIGNAL(finished()), this, SLOT(executionFinished())); emit addToOutputWindow(this, tr("Starting remote application.")); emit started(); sshRunner->start(); } void MaemoRunControl::executionFinished() { if (stoppedByUser) { emit addToOutputWindow(this, tr("Remote process stopped by user.")); } else if (sshRunner->hasError()) { emit addToOutputWindow(this, tr("Remote process exited with error: %1") .arg(sshRunner->error())); } else { emit addToOutputWindow(this, tr("Remote process finished successfully.")); } emit finished(); } void MaemoRunControl::stop() { if (!isRunning()) return; stoppedByUser = true; if (isDeploying()) { stopDeployment(); } else { sshRunner->stop(); const QString remoteCall = QString::fromLocal8Bit("pkill -x %1; " "sleep 1; pkill -x -9 %1").arg(executableFileName()); sshStopper.reset(new MaemoSshRunner(devConfig, remoteCall)); sshStopper->start(); } } bool MaemoRunControl::isRunning() const { return isDeploying() || (!sshRunner.isNull() && sshRunner->isRunning()); } void MaemoRunControl::handleRemoteOutput(const QString &output) { emit addToOutputWindowInline(this, output); } MaemoDebugRunControl::MaemoDebugRunControl(RunConfiguration *runConfiguration) : AbstractMaemoRunControl(runConfiguration) , debuggerManager(0) , startParams(new Debugger::DebuggerStartParameters) { debuggerManager = ExtensionSystem::PluginManager::instance() ->getObject<Debugger::DebuggerManager>(); QTC_ASSERT(debuggerManager != 0, return); startParams->startMode = Debugger::StartRemote; startParams->executable = executableOnHost(); startParams->remoteChannel = devConfig.host % QLatin1Char(':') % gdbServerPort(); startParams->remoteArchitecture = QLatin1String("arm"); startParams->sysRoot = runConfig->sysRoot(); startParams->toolChainType = ToolChain::GCC_MAEMO; startParams->debuggerCommand = runConfig->gdbCmd(); startParams->dumperLibrary = runConfig->dumperLib(); startParams->remoteDumperLib = QString::fromLocal8Bit("%1/%2") .arg(remoteDir()).arg(QFileInfo(runConfig->dumperLib()).fileName()); connect(this, SIGNAL(stopRequested()), debuggerManager, SLOT(exitDebugger())); connect(debuggerManager, SIGNAL(debuggingFinished()), this, SLOT(debuggingFinished()), Qt::QueuedConnection); connect(debuggerManager, SIGNAL(applicationOutputAvailable(QString)), this, SLOT(debuggerOutput(QString)), Qt::QueuedConnection); } MaemoDebugRunControl::~MaemoDebugRunControl() { disconnect(SIGNAL(addToOutputWindow(RunControl*,QString))); disconnect(SIGNAL(addToOutputWindowInline(RunControl*,QString))); stop(); debuggingFinished(); } void MaemoDebugRunControl::start() { startDeployment(true); } void MaemoDebugRunControl::handleDeploymentFinished(bool success) { if (success) { startGdbServer(); } else { emit finished(); } } void MaemoDebugRunControl::startGdbServer() { const QString remoteCall(QString::fromLocal8Bit("%1 gdbserver :%2 %3 %4"). arg(targetCmdLinePrefix()).arg(gdbServerPort()) .arg(executableOnTarget()).arg(runConfig->arguments().join(" "))); inferiorPid = -1; sshRunner.reset(new MaemoSshRunner(devConfig, remoteCall)); connect(sshRunner.data(), SIGNAL(remoteOutput(QString)), this, SLOT(gdbServerStarted(QString))); sshRunner->start(); } void MaemoDebugRunControl::gdbServerStartFailed(const QString &reason) { handleError(tr("Debugging failed: %1").arg(reason)); emit stopRequested(); emit finished(); } void MaemoDebugRunControl::gdbServerStarted(const QString &output) { qDebug("gdbserver's stderr output: %s", output.toLatin1().data()); if (inferiorPid != -1) return; const QString searchString("pid = "); const int searchStringLength = searchString.length(); int pidStartPos = output.indexOf(searchString); const int pidEndPos = output.indexOf("\n", pidStartPos + searchStringLength); if (pidStartPos == -1 || pidEndPos == -1) { gdbServerStartFailed(output); return; } pidStartPos += searchStringLength; QString pidString = output.mid(pidStartPos, pidEndPos - pidStartPos); qDebug("pidString = %s", pidString.toLatin1().data()); bool ok; const int pid = pidString.toInt(&ok); if (!ok) { gdbServerStartFailed(tr("Debugging failed, could not parse gdb " "server pid!")); return; } inferiorPid = pid; qDebug("inferiorPid = %d", inferiorPid); disconnect(sshRunner.data(), SIGNAL(remoteOutput(QString)), 0, 0); startDebugging(); } void MaemoDebugRunControl::startDebugging() { debuggerManager->startNewDebugger(startParams); } void MaemoDebugRunControl::stop() { if (!isRunning()) return; emit addToOutputWindow(this, tr("Stopping debugging operation ...")); if (isDeploying()) { stopDeployment(); } else { emit stopRequested(); } } bool MaemoDebugRunControl::isRunning() const { return isDeploying() || (!sshRunner.isNull() && sshRunner->isRunning()) || debuggerManager->state() != Debugger::DebuggerNotReady; } void MaemoDebugRunControl::debuggingFinished() { if (!sshRunner.isNull() && sshRunner->isRunning()) { sshRunner->stop(); const QString remoteCall = QString::fromLocal8Bit("kill %1; sleep 1; " "kill -9 %1; pkill -x -9 gdbserver").arg(inferiorPid); sshStopper.reset(new MaemoSshRunner(devConfig, remoteCall)); sshStopper->start(); } emit addToOutputWindow(this, tr("Debugging finished.")); emit finished(); } void MaemoDebugRunControl::debuggerOutput(const QString &output) { emit addToOutputWindowInline(this, output); } QString MaemoDebugRunControl::gdbServerPort() const { return devConfig.type == MaemoDeviceConfig::Physical ? QString::number(devConfig.gdbServerPort) : runConfig->simulatorGdbServerPort(); } } // namespace Internal } // namespace Qt4ProjectManager <commit_msg>Maemo: Refactor running, debugging and stopping<commit_after>/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the Qt Creator. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "maemoruncontrol.h" #include "maemosshthread.h" #include "maemorunconfiguration.h" #include <coreplugin/icore.h> #include <coreplugin/progressmanager/progressmanager.h> #include <debugger/debuggermanager.h> #include <extensionsystem/pluginmanager.h> #include <projectexplorer/toolchain.h> #include <utils/qtcassert.h> #include <QtCore/QDir> #include <QtCore/QFileInfo> #include <QtCore/QFuture> #include <QtCore/QProcess> #include <QtCore/QStringBuilder> #include <QtGui/QMessageBox> namespace Qt4ProjectManager { namespace Internal { using ProjectExplorer::RunConfiguration; using ProjectExplorer::ToolChain; AbstractMaemoRunControl::AbstractMaemoRunControl(RunConfiguration *rc) : RunControl(rc) , runConfig(qobject_cast<MaemoRunConfiguration *>(rc)) , devConfig(runConfig ? runConfig->deviceConfig() : MaemoDeviceConfig()) { } AbstractMaemoRunControl::~AbstractMaemoRunControl() { } void AbstractMaemoRunControl::startDeployment(bool forDebugging) { QTC_ASSERT(runConfig, return); if (devConfig.isValid()) { deployables.clear(); if (runConfig->currentlyNeedsDeployment(devConfig.host)) { deployables.append(Deployable(executableFileName(), QFileInfo(executableOnHost()).canonicalPath(), &MaemoRunConfiguration::wasDeployed)); } if (forDebugging && runConfig->debuggingHelpersNeedDeployment(devConfig.host)) { const QFileInfo &info(runConfig->dumperLib()); deployables.append(Deployable(info.fileName(), info.canonicalPath(), &MaemoRunConfiguration::debuggingHelpersDeployed)); } deploy(); } else { handleError(tr("No device configuration set for run configuration.")); handleDeploymentFinished(false); } } void AbstractMaemoRunControl::deploy() { Core::ICore::instance()->progressManager() ->addTask(m_progress.future(), tr("Deploying"), QLatin1String("Maemo.Deploy")); if (!deployables.isEmpty()) { QList<SshDeploySpec> deploySpecs; QStringList files; foreach (const Deployable &deployable, deployables) { const QString srcFilePath = deployable.dir % QDir::separator() % deployable.fileName; const QString tgtFilePath = remoteDir() % QDir::separator() % deployable.fileName; files << srcFilePath; deploySpecs << SshDeploySpec(srcFilePath, tgtFilePath); } emit addToOutputWindow(this, tr("Files to deploy: %1.").arg(files.join(" "))); sshDeployer.reset(new MaemoSshDeployer(devConfig, deploySpecs)); connect(sshDeployer.data(), SIGNAL(finished()), this, SLOT(deployProcessFinished())); connect(sshDeployer.data(), SIGNAL(fileCopied(QString)), this, SLOT(handleFileCopied())); m_progress.setProgressRange(0, deployables.count()); m_progress.setProgressValue(0); m_progress.reportStarted(); emit started(); sshDeployer->start(); } else { m_progress.reportFinished(); handleDeploymentFinished(true); } } void AbstractMaemoRunControl::handleFileCopied() { Deployable deployable = deployables.takeFirst(); (runConfig->*deployable.updateTimestamp)(devConfig.host); m_progress.setProgressValue(m_progress.progressValue() + 1); } void AbstractMaemoRunControl::stopDeployment() { sshDeployer->stop(); } bool AbstractMaemoRunControl::isDeploying() const { return sshDeployer && sshDeployer->isRunning(); } void AbstractMaemoRunControl::run(const QString &remoteCall) { sshRunner.reset(new MaemoSshRunner(devConfig, remoteCall)); handleExecutionAboutToStart(sshRunner.data()); sshRunner->start(); } bool AbstractMaemoRunControl::isRunning() const { return isDeploying() || (sshRunner && sshRunner->isRunning()); } void AbstractMaemoRunControl::stopRunning(bool forDebugging) { if (sshRunner && sshRunner->isRunning()) { sshRunner->stop(); QStringList apps(executableFileName()); if (forDebugging) apps << QLatin1String("gdbserver"); kill(apps); } } void AbstractMaemoRunControl::kill(const QStringList &apps) { QString niceKill; QString brutalKill; foreach (const QString &app, apps) { niceKill += QString::fromLocal8Bit("pkill -x %1;").arg(app); brutalKill += QString::fromLocal8Bit("pkill -x -9 %1;").arg(app); } const QString remoteCall = niceKill + QLatin1String("sleep 1; ") + brutalKill; sshStopper.reset(new MaemoSshRunner(devConfig, remoteCall)); sshStopper->start(); } void AbstractMaemoRunControl::deployProcessFinished() { const bool success = !sshDeployer->hasError(); if (success) { emit addToOutputWindow(this, tr("Deployment finished.")); } else { handleError(tr("Deployment failed: %1").arg(sshDeployer->error())); m_progress.reportCanceled(); } m_progress.reportFinished(); handleDeploymentFinished(success); } const QString AbstractMaemoRunControl::executableOnHost() const { qDebug("runconfig->executable: %s", qPrintable(runConfig->executable())); return runConfig->executable(); } const QString AbstractMaemoRunControl::sshPort() const { return devConfig.type == MaemoDeviceConfig::Physical ? QString::number(devConfig.sshPort) : runConfig->simulatorSshPort(); } const QString AbstractMaemoRunControl::executableFileName() const { return QFileInfo(executableOnHost()).fileName(); } const QString AbstractMaemoRunControl::remoteDir() const { return homeDirOnDevice(devConfig.uname); } const QStringList AbstractMaemoRunControl::options() const { const bool usePassword = devConfig.authentication == MaemoDeviceConfig::Password; const QLatin1String opt("-o"); QStringList optionList; if (!usePassword) optionList << QLatin1String("-i") << devConfig.keyFile; return optionList << opt << QString::fromLatin1("PasswordAuthentication=%1"). arg(usePassword ? "yes" : "no") << opt << QString::fromLatin1("PubkeyAuthentication=%1"). arg(usePassword ? "no" : "yes") << opt << QString::fromLatin1("ConnectTimeout=%1").arg(devConfig.timeout) << opt << QLatin1String("CheckHostIP=no") << opt << QLatin1String("StrictHostKeyChecking=no"); } const QString AbstractMaemoRunControl::executableOnTarget() const { return QString::fromLocal8Bit("%1/%2").arg(remoteDir()). arg(executableFileName()); } const QString AbstractMaemoRunControl::targetCmdLinePrefix() const { return QString::fromLocal8Bit("chmod u+x %1; source /etc/profile; "). arg(executableOnTarget()); } void AbstractMaemoRunControl::handleError(const QString &errString) { QMessageBox::critical(0, tr("Remote Execution Failure"), errString); emit error(this, errString); } MaemoRunControl::MaemoRunControl(RunConfiguration *runConfiguration) : AbstractMaemoRunControl(runConfiguration) { } MaemoRunControl::~MaemoRunControl() { stop(); } void MaemoRunControl::start() { stoppedByUser = false; startDeployment(false); } void MaemoRunControl::handleDeploymentFinished(bool success) { if (success) startExecution(); else emit finished(); } void MaemoRunControl::handleExecutionAboutToStart(const MaemoSshRunner *runner) { connect(runner, SIGNAL(remoteOutput(QString)), this, SLOT(handleRemoteOutput(QString))); connect(runner, SIGNAL(finished()), this, SLOT(executionFinished())); emit addToOutputWindow(this, tr("Starting remote application.")); emit started(); } void MaemoRunControl::startExecution() { const QString remoteCall = QString::fromLocal8Bit("%1 %2 %3") .arg(targetCmdLinePrefix()).arg(executableOnTarget()) .arg(runConfig->arguments().join(" ")); run(remoteCall); } void MaemoRunControl::executionFinished() { MaemoSshRunner *runner = static_cast<MaemoSshRunner *>(sender()); if (stoppedByUser) { emit addToOutputWindow(this, tr("Remote process stopped by user.")); } else if (runner->hasError()) { emit addToOutputWindow(this, tr("Remote process exited with error: %1") .arg(runner->error())); } else { emit addToOutputWindow(this, tr("Remote process finished successfully.")); } emit finished(); } void MaemoRunControl::stop() { if (!isRunning()) return; stoppedByUser = true; if (isDeploying()) { stopDeployment(); } else { AbstractMaemoRunControl::stopRunning(false); } } void MaemoRunControl::handleRemoteOutput(const QString &output) { emit addToOutputWindowInline(this, output); } MaemoDebugRunControl::MaemoDebugRunControl(RunConfiguration *runConfiguration) : AbstractMaemoRunControl(runConfiguration) , debuggerManager(0) , startParams(new Debugger::DebuggerStartParameters) { debuggerManager = ExtensionSystem::PluginManager::instance() ->getObject<Debugger::DebuggerManager>(); QTC_ASSERT(debuggerManager != 0, return); startParams->startMode = Debugger::StartRemote; startParams->executable = executableOnHost(); startParams->remoteChannel = devConfig.host % QLatin1Char(':') % gdbServerPort(); startParams->remoteArchitecture = QLatin1String("arm"); startParams->sysRoot = runConfig->sysRoot(); startParams->toolChainType = ToolChain::GCC_MAEMO; startParams->debuggerCommand = runConfig->gdbCmd(); startParams->dumperLibrary = runConfig->dumperLib(); startParams->remoteDumperLib = QString::fromLocal8Bit("%1/%2") .arg(remoteDir()).arg(QFileInfo(runConfig->dumperLib()).fileName()); connect(this, SIGNAL(stopRequested()), debuggerManager, SLOT(exitDebugger())); connect(debuggerManager, SIGNAL(debuggingFinished()), this, SLOT(debuggingFinished()), Qt::QueuedConnection); connect(debuggerManager, SIGNAL(applicationOutputAvailable(QString)), this, SLOT(debuggerOutput(QString)), Qt::QueuedConnection); } MaemoDebugRunControl::~MaemoDebugRunControl() { disconnect(SIGNAL(addToOutputWindow(RunControl*,QString))); disconnect(SIGNAL(addToOutputWindowInline(RunControl*,QString))); stop(); debuggingFinished(); } void MaemoDebugRunControl::start() { startDeployment(true); } void MaemoDebugRunControl::handleDeploymentFinished(bool success) { if (success) { startGdbServer(); } else { emit finished(); } } void MaemoDebugRunControl::handleExecutionAboutToStart(const MaemoSshRunner *runner) { inferiorPid = -1; connect(runner, SIGNAL(remoteOutput(QString)), this, SLOT(gdbServerStarted(QString))); } void MaemoDebugRunControl::startGdbServer() { const QString remoteCall(QString::fromLocal8Bit("%1 gdbserver :%2 %3 %4"). arg(targetCmdLinePrefix()).arg(gdbServerPort()) .arg(executableOnTarget()).arg(runConfig->arguments().join(" "))); run(remoteCall); } void MaemoDebugRunControl::gdbServerStartFailed(const QString &reason) { handleError(tr("Debugging failed: %1").arg(reason)); emit stopRequested(); emit finished(); } void MaemoDebugRunControl::gdbServerStarted(const QString &output) { qDebug("gdbserver's stderr output: %s", output.toLatin1().data()); if (inferiorPid != -1) return; const QString searchString("pid = "); const int searchStringLength = searchString.length(); int pidStartPos = output.indexOf(searchString); const int pidEndPos = output.indexOf("\n", pidStartPos + searchStringLength); if (pidStartPos == -1 || pidEndPos == -1) { gdbServerStartFailed(output); return; } pidStartPos += searchStringLength; QString pidString = output.mid(pidStartPos, pidEndPos - pidStartPos); qDebug("pidString = %s", pidString.toLatin1().data()); bool ok; const int pid = pidString.toInt(&ok); if (!ok) { gdbServerStartFailed(tr("Debugging failed, could not parse gdb " "server pid!")); return; } inferiorPid = pid; qDebug("inferiorPid = %d", inferiorPid); startDebugging(); } void MaemoDebugRunControl::startDebugging() { debuggerManager->startNewDebugger(startParams); } void MaemoDebugRunControl::stop() { if (!isRunning()) return; emit addToOutputWindow(this, tr("Stopping debugging operation ...")); if (isDeploying()) { stopDeployment(); } else { emit stopRequested(); } } bool MaemoDebugRunControl::isRunning() const { return AbstractMaemoRunControl::isRunning() || debuggerManager->state() != Debugger::DebuggerNotReady; } void MaemoDebugRunControl::debuggingFinished() { AbstractMaemoRunControl::stopRunning(true); emit addToOutputWindow(this, tr("Debugging finished.")); emit finished(); } void MaemoDebugRunControl::debuggerOutput(const QString &output) { emit addToOutputWindowInline(this, output); } QString MaemoDebugRunControl::gdbServerPort() const { return devConfig.type == MaemoDeviceConfig::Physical ? QString::number(devConfig.gdbServerPort) : runConfig->simulatorGdbServerPort(); } } // namespace Internal } // namespace Qt4ProjectManager <|endoftext|>
<commit_before>//===-- shm.cpp -----------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Save/restore via shared memory to survive exec*() // //===----------------------------------------------------------------------===// #include "shm.h" #include "ipcreg_internal.h" #include "magic_socket_nums.h" #include "real.h" #include "rename_fd.h" #include <sys/mman.h> #include <sys/stat.h> #include <fcntl.h> #include <errno.h> #include <string.h> static char buf[100]; const char *getShmName() { sprintf(buf, "/ipcd.%d\n", getpid()); return buf; } int get_shm(int flags, mode_t mode) { int fd = shm_open(getShmName(), flags, mode); if (fd != -1) { int ret = fchmod(fd, mode); if (ret == -1) { ipclog("Failure setting shared memory permissions: %s\n", strerror(errno)); } } return fd; } void shm_state_save() { // Create shared memory segment int fd = get_shm(O_RDWR | O_CREAT | O_EXCL, 0600); assert(fd != -1); bool success = rename_fd(fd, MAGIC_SHM_FD, /* cloexec */ false); assert(success && "Failed to rename SHM fd!"); // Do *not* close on exec! :) int flags = __real_fcntl(MAGIC_SHM_FD, F_GETFD, /* kludge */ 0); assert(flags >= 0); flags &= ~FD_CLOEXEC; int ret = __real_fcntl_int(MAGIC_SHM_FD, F_SETFD, flags); assert(ret != -1); // Size the memory segment: ret = ftruncate(MAGIC_SHM_FD, sizeof(libipc_state)); assert(ret != -1); void *stateptr = mmap(NULL, sizeof(libipc_state), PROT_READ | PROT_WRITE, MAP_SHARED, MAGIC_SHM_FD, 0); assert(stateptr != MAP_FAILED); // Copy state to shared memory segment *(libipc_state*)stateptr = state; // Unmap, but don't unlink the shared memory ret = munmap(stateptr, sizeof(libipc_state)); assert(ret != -1); ipclog("State saved!\n"); } bool is_valid_fd(int fd) { return __real_fcntl(fd, F_GETFD, /* kludge */ 0) >= 0; } void shm_state_restore() { // If we have memory to restore, it'll be in our magic FD! if (!is_valid_fd(MAGIC_SHM_FD)) return; ipclog("Inherited ipc state FD, starting state restoration...\n"); void *stateptr = mmap(NULL, sizeof(libipc_state), PROT_READ | PROT_WRITE, MAP_SHARED, MAGIC_SHM_FD, 0); // If our FD is still open, the memory better still be there! assert(stateptr != MAP_FAILED); // Copy state to shared memory segment // Copy state from shared memory segment state = *(libipc_state*)stateptr; int ret = munmap(stateptr, sizeof(libipc_state)); assert(ret != -1); // Done with the shared segment, thank you! ret = __real_close(MAGIC_SHM_FD); assert(ret != -1); ret = shm_unlink(getShmName()); assert(ret != -1); ipclog("State restored!\n"); } void shm_state_destroy() { // If we have memory to restore, it'll be in our magic FD! assert(is_valid_fd(MAGIC_SHM_FD)); int ret = __real_close(MAGIC_SHM_FD); assert(ret == 0); ret = shm_unlink(getShmName()); assert(ret != -1); ipclog("Destroyed saved state!\n"); } <commit_msg>libipc: Add more verbose/handy checking of unix calls, for debugging.<commit_after>//===-- shm.cpp -----------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Save/restore via shared memory to survive exec*() // //===----------------------------------------------------------------------===// #include "shm.h" #include "ipcreg_internal.h" #include "magic_socket_nums.h" #include "real.h" #include "rename_fd.h" #include <sys/mman.h> #include <sys/stat.h> #include <fcntl.h> #include <errno.h> #include <string.h> #define UC(ret, msg) \ unixCheck(ret, msg, __FILE__, __LINE__, __PRETTY_FUNCTION__); void unixCheck(int ret, const char *msg, const char *file, unsigned line, const char *func, int err = errno) { if (ret == -1) { ipclog("Unix call failed in %s at %s:%u: %s - %s\n", func, file, line, msg, strerror(err)); abort(); } } static char buf[100]; const char *getShmName() { sprintf(buf, "/ipcd.%d\n", getpid()); return buf; } int get_shm(int flags, mode_t mode) { int fd = shm_open(getShmName(), flags, mode); UC(fd, "shm_open"); UC(fchmod(fd, mode), "fchmod on shared memory segment"); return fd; } void shm_state_save() { // Create shared memory segment int fd = get_shm(O_RDWR | O_CREAT | O_EXCL, 0600); UC(fd, "get_shm"); bool success = rename_fd(fd, MAGIC_SHM_FD, /* cloexec */ false); assert(success && "Failed to rename SHM fd!"); // Do *not* close on exec! :) int flags = __real_fcntl(MAGIC_SHM_FD, F_GETFD, /* kludge */ 0); assert(flags >= 0); flags &= ~FD_CLOEXEC; int ret = __real_fcntl_int(MAGIC_SHM_FD, F_SETFD, flags); UC(ret, "fcntl CLOEXEC on shared memory segment"); // Size the memory segment: ret = ftruncate(MAGIC_SHM_FD, sizeof(libipc_state)); UC(ret, "ftruncate on shm"); void *stateptr = mmap(NULL, sizeof(libipc_state), PROT_READ | PROT_WRITE, MAP_SHARED, MAGIC_SHM_FD, 0); assert(stateptr != MAP_FAILED); // Copy state to shared memory segment *(libipc_state*)stateptr = state; // Unmap, but don't unlink the shared memory ret = munmap(stateptr, sizeof(libipc_state)); UC(ret, "unmap shm"); ipclog("State saved!\n"); } bool is_valid_fd(int fd) { return __real_fcntl(fd, F_GETFD, /* kludge */ 0) >= 0; } void shm_state_restore() { // If we have memory to restore, it'll be in our magic FD! if (!is_valid_fd(MAGIC_SHM_FD)) return; ipclog("Inherited ipc state FD, starting state restoration...\n"); void *stateptr = mmap(NULL, sizeof(libipc_state), PROT_READ | PROT_WRITE, MAP_SHARED, MAGIC_SHM_FD, 0); // If our FD is still open, the memory better still be there! assert(stateptr != MAP_FAILED); // Copy state to shared memory segment // Copy state from shared memory segment state = *(libipc_state*)stateptr; int ret = munmap(stateptr, sizeof(libipc_state)); UC(ret, "unmap shm"); // Done with the shared segment, thank you! ret = __real_close(MAGIC_SHM_FD); UC(ret, "close shm"); ret = shm_unlink(getShmName()); UC(ret, "shm_unlink after close"); ipclog("State restored!\n"); } void shm_state_destroy() { // If we have memory to restore, it'll be in our magic FD! assert(is_valid_fd(MAGIC_SHM_FD)); int ret = __real_close(MAGIC_SHM_FD); assert(ret == 0); ret = shm_unlink(getShmName()); UC(ret, "shm_unlink"); ipclog("Destroyed saved state!\n"); } <|endoftext|>
<commit_before>/* * Copyright (C) 2019 ScyllaDB */ /* * This file is part of Scylla. * * Scylla is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Scylla is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Scylla. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include <seastar/core/do_with.hh> #include <seastar/util/noncopyable_function.hh> #include <seastar/core/sharded.hh> #include <seastar/util/defer.hh> #include "sstables/sstables.hh" #include "test/lib/tmpdir.hh" #include "test/lib/test_services.hh" namespace sstables { class test_env { sstables_manager& _mgr; public: explicit test_env() : _mgr(test_sstables_manager) { } explicit test_env(sstables_manager& mgr) : _mgr(mgr) { } future<> stop() { return make_ready_future<>(); } shared_sstable make_sstable(schema_ptr schema, sstring dir, unsigned long generation, sstable::version_types v, sstable::format_types f = sstable::format_types::big, size_t buffer_size = default_sstable_buffer_size, gc_clock::time_point now = gc_clock::now()) { return _mgr.make_sstable(std::move(schema), dir, generation, v, f, now, default_io_error_handler_gen(), buffer_size); } future<shared_sstable> reusable_sst(schema_ptr schema, sstring dir, unsigned long generation, sstable::version_types version = sstable::version_types::la, sstable::format_types f = sstable::format_types::big) { auto sst = make_sstable(std::move(schema), dir, generation, version, f); return sst->load().then([sst = std::move(sst)] { return make_ready_future<shared_sstable>(std::move(sst)); }); } sstables_manager& manager() { return _mgr; } future<> working_sst(schema_ptr schema, sstring dir, unsigned long generation) { return reusable_sst(std::move(schema), dir, generation).then([] (auto ptr) { return make_ready_future<>(); }); } template <typename Func> static inline auto do_with(Func&& func) { return seastar::do_with(test_env(), [func = std::move(func)] (test_env& env) mutable { return func(env); }); } template <typename T, typename Func> static inline auto do_with(T&& rval, Func&& func) { return seastar::do_with(test_env(), std::forward<T>(rval), [func = std::move(func)] (test_env& env, T& val) mutable { return func(env, val); }); } static inline future<> do_with_async(noncopyable_function<void (test_env&)> func) { return seastar::async([func = std::move(func)] { auto wait_for_background_jobs = defer([] { sstables::await_background_jobs_on_all_shards().get(); }); test_env env; func(env); }); } static inline future<> do_with_sharded_async(noncopyable_function<void (sharded<test_env>&)> func) { return seastar::async([func = std::move(func)] { auto wait_for_background_jobs = defer([] { sstables::await_background_jobs_on_all_shards().get(); }); sharded<test_env> env; env.start().get(); auto stop = defer([&] { env.stop().get(); }); func(env); }); } template <typename T> static future<T> do_with_async_returning(noncopyable_function<T (test_env&)> func) { return seastar::async([func = std::move(func)] { auto wait_for_background_jobs = defer([] { sstables::await_background_jobs_on_all_shards().get(); }); test_env env; auto stop = defer([&] { env.stop().get(); }); return func(env); }); } }; } // namespace sstables <commit_msg>test: sstables::test_env: close self in do_with helpers<commit_after>/* * Copyright (C) 2019 ScyllaDB */ /* * This file is part of Scylla. * * Scylla is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Scylla is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Scylla. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include <seastar/core/do_with.hh> #include <seastar/util/noncopyable_function.hh> #include <seastar/core/sharded.hh> #include <seastar/util/defer.hh> #include "sstables/sstables.hh" #include "test/lib/tmpdir.hh" #include "test/lib/test_services.hh" namespace sstables { class test_env { sstables_manager& _mgr; public: explicit test_env() : _mgr(test_sstables_manager) { } explicit test_env(sstables_manager& mgr) : _mgr(mgr) { } future<> stop() { return make_ready_future<>(); } shared_sstable make_sstable(schema_ptr schema, sstring dir, unsigned long generation, sstable::version_types v, sstable::format_types f = sstable::format_types::big, size_t buffer_size = default_sstable_buffer_size, gc_clock::time_point now = gc_clock::now()) { return _mgr.make_sstable(std::move(schema), dir, generation, v, f, now, default_io_error_handler_gen(), buffer_size); } future<shared_sstable> reusable_sst(schema_ptr schema, sstring dir, unsigned long generation, sstable::version_types version = sstable::version_types::la, sstable::format_types f = sstable::format_types::big) { auto sst = make_sstable(std::move(schema), dir, generation, version, f); return sst->load().then([sst = std::move(sst)] { return make_ready_future<shared_sstable>(std::move(sst)); }); } sstables_manager& manager() { return _mgr; } future<> working_sst(schema_ptr schema, sstring dir, unsigned long generation) { return reusable_sst(std::move(schema), dir, generation).then([] (auto ptr) { return make_ready_future<>(); }); } template <typename Func> static inline auto do_with(Func&& func) { return seastar::do_with(test_env(), [func = std::move(func)] (test_env& env) mutable { return func(env).finally([&env] { return env.stop(); }); }); } template <typename T, typename Func> static inline auto do_with(T&& rval, Func&& func) { return seastar::do_with(test_env(), std::forward<T>(rval), [func = std::move(func)] (test_env& env, T& val) mutable { return func(env, val).finally([&env] { return env.stop(); }); }); } static inline future<> do_with_async(noncopyable_function<void (test_env&)> func) { return seastar::async([func = std::move(func)] { auto wait_for_background_jobs = defer([] { sstables::await_background_jobs_on_all_shards().get(); }); test_env env; auto close_env = defer([&] { env.stop().get(); }); func(env); }); } static inline future<> do_with_sharded_async(noncopyable_function<void (sharded<test_env>&)> func) { return seastar::async([func = std::move(func)] { auto wait_for_background_jobs = defer([] { sstables::await_background_jobs_on_all_shards().get(); }); sharded<test_env> env; env.start().get(); auto stop = defer([&] { env.stop().get(); }); func(env); }); } template <typename T> static future<T> do_with_async_returning(noncopyable_function<T (test_env&)> func) { return seastar::async([func = std::move(func)] { auto wait_for_background_jobs = defer([] { sstables::await_background_jobs_on_all_shards().get(); }); test_env env; auto stop = defer([&] { env.stop().get(); }); return func(env); }); } }; } // namespace sstables <|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/installer/util/wmi.h" #include <windows.h> #include "base/basictypes.h" #include "base/win/scoped_bstr.h" #include "base/win/scoped_comptr.h" #include "base/win/scoped_variant.h" #pragma comment(lib, "wbemuuid.lib") namespace installer { namespace { // Simple class to manage the lifetime of a variant. // TODO(tommi): Replace this for a more useful class. class VariantHelper : public VARIANT { public: VariantHelper() { vt = VT_EMPTY; } explicit VariantHelper(VARTYPE type) { vt = type; } ~VariantHelper() { ::VariantClear(this); } private: DISALLOW_COPY_AND_ASSIGN(VariantHelper); }; } // namespace bool WMI::CreateLocalConnection(bool set_blanket, IWbemServices** wmi_services) { base::win::ScopedComPtr<IWbemLocator> wmi_locator; HRESULT hr = wmi_locator.CreateInstance(CLSID_WbemLocator, NULL, CLSCTX_INPROC_SERVER); if (FAILED(hr)) return false; base::win::ScopedComPtr<IWbemServices> wmi_services_r; hr = wmi_locator->ConnectServer(base::win::ScopedBstr(L"ROOT\\CIMV2"), NULL, NULL, 0, NULL, 0, 0, wmi_services_r.Receive()); if (FAILED(hr)) return false; if (set_blanket) { hr = ::CoSetProxyBlanket(wmi_services_r, RPC_C_AUTHN_WINNT, RPC_C_AUTHZ_NONE, NULL, RPC_C_AUTHN_LEVEL_CALL, RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE); if (FAILED(hr)) return false; } *wmi_services = wmi_services_r.Detach(); return true; } bool WMI::CreateClassMethodObject(IWbemServices* wmi_services, const std::wstring& class_name, const std::wstring& method_name, IWbemClassObject** class_instance) { // We attempt to instantiate a COM object that represents a WMI object plus // a method rolled into one entity. base::win::ScopedBstr b_class_name(class_name.c_str()); base::win::ScopedBstr b_method_name(method_name.c_str()); base::win::ScopedComPtr<IWbemClassObject> class_object; HRESULT hr; hr = wmi_services->GetObject(b_class_name, 0, NULL, class_object.Receive(), NULL); if (FAILED(hr)) return false; base::win::ScopedComPtr<IWbemClassObject> params_def; hr = class_object->GetMethod(b_method_name, 0, params_def.Receive(), NULL); if (FAILED(hr)) return false; if (NULL == params_def) { // You hit this special case if the WMI class is not a CIM class. MSDN // sometimes tells you this. Welcome to WMI hell. return false; } hr = params_def->SpawnInstance(0, class_instance); return(SUCCEEDED(hr)); } bool SetParameter(IWbemClassObject* class_method, const std::wstring& parameter_name, VARIANT* parameter) { HRESULT hr = class_method->Put(parameter_name.c_str(), 0, parameter, 0); return SUCCEEDED(hr); } // The code in Launch() basically calls the Create Method of the Win32_Process // CIM class is documented here: // http://msdn2.microsoft.com/en-us/library/aa389388(VS.85).aspx bool WMIProcess::Launch(const std::wstring& command_line, int* process_id) { base::win::ScopedComPtr<IWbemServices> wmi_local; if (!WMI::CreateLocalConnection(true, wmi_local.Receive())) return false; const wchar_t class_name[] = L"Win32_Process"; const wchar_t method_name[] = L"Create"; base::win::ScopedComPtr<IWbemClassObject> process_create; if (!WMI::CreateClassMethodObject(wmi_local, class_name, method_name, process_create.Receive())) return false; VariantHelper b_command_line(VT_BSTR); b_command_line.bstrVal = ::SysAllocString(command_line.c_str()); if (!SetParameter(process_create, L"CommandLine", &b_command_line)) return false; base::win::ScopedComPtr<IWbemClassObject> out_params; HRESULT hr = wmi_local->ExecMethod(base::win::ScopedBstr(class_name), base::win::ScopedBstr(method_name), 0, NULL, process_create, out_params.Receive(), NULL); if (FAILED(hr)) return false; VariantHelper ret_value; hr = out_params->Get(L"ReturnValue", 0, &ret_value, NULL, 0); if (FAILED(hr) || (0 != ret_value.uintVal)) return false; VariantHelper pid; hr = out_params->Get(L"ProcessId", 0, &pid, NULL, 0); if (FAILED(hr) || (0 == pid.intVal)) return false; if (process_id) *process_id = pid.intVal; return true; } string16 WMIComputerSystem::GetModel() { base::win::ScopedComPtr<IWbemServices> services; if (!WMI::CreateLocalConnection(true, services.Receive())) return string16(); base::win::ScopedBstr query_language(L"WQL"); base::win::ScopedBstr query(L"SELECT * FROM Win32_ComputerSystem"); base::win::ScopedComPtr<IEnumWbemClassObject> enumerator; HRESULT hr = services->ExecQuery( query_language, query, WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY, NULL, enumerator.Receive()); if (FAILED(hr) || !enumerator) return string16(); base::win::ScopedComPtr<IWbemClassObject> class_object; ULONG items_returned = 0; hr = enumerator->Next(WBEM_INFINITE, 1, class_object.Receive(), &items_returned); if (!items_returned) return string16(); base::win::ScopedVariant manufacturer; class_object->Get(L"Manufacturer", 0, manufacturer.Receive(), 0, 0); base::win::ScopedVariant model; class_object->Get(L"Model", 0, model.Receive(), 0, 0); string16 model_string; if (manufacturer.type() == VT_BSTR) { model_string = V_BSTR(&manufacturer); if (model.type() == VT_BSTR) model_string += L" "; } if (model.type() == VT_BSTR) model_string += V_BSTR(&model); return model_string; } } // namespace installer <commit_msg>Take care of an old todo: Use ScopedVariant instead of VariantHelper.<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/installer/util/wmi.h" #include <windows.h> #include "base/basictypes.h" #include "base/win/scoped_bstr.h" #include "base/win/scoped_comptr.h" #include "base/win/scoped_variant.h" #pragma comment(lib, "wbemuuid.lib") using base::win::ScopedVariant; namespace installer { bool WMI::CreateLocalConnection(bool set_blanket, IWbemServices** wmi_services) { base::win::ScopedComPtr<IWbemLocator> wmi_locator; HRESULT hr = wmi_locator.CreateInstance(CLSID_WbemLocator, NULL, CLSCTX_INPROC_SERVER); if (FAILED(hr)) return false; base::win::ScopedComPtr<IWbemServices> wmi_services_r; hr = wmi_locator->ConnectServer(base::win::ScopedBstr(L"ROOT\\CIMV2"), NULL, NULL, 0, NULL, 0, 0, wmi_services_r.Receive()); if (FAILED(hr)) return false; if (set_blanket) { hr = ::CoSetProxyBlanket(wmi_services_r, RPC_C_AUTHN_WINNT, RPC_C_AUTHZ_NONE, NULL, RPC_C_AUTHN_LEVEL_CALL, RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE); if (FAILED(hr)) return false; } *wmi_services = wmi_services_r.Detach(); return true; } bool WMI::CreateClassMethodObject(IWbemServices* wmi_services, const std::wstring& class_name, const std::wstring& method_name, IWbemClassObject** class_instance) { // We attempt to instantiate a COM object that represents a WMI object plus // a method rolled into one entity. base::win::ScopedBstr b_class_name(class_name.c_str()); base::win::ScopedBstr b_method_name(method_name.c_str()); base::win::ScopedComPtr<IWbemClassObject> class_object; HRESULT hr; hr = wmi_services->GetObject(b_class_name, 0, NULL, class_object.Receive(), NULL); if (FAILED(hr)) return false; base::win::ScopedComPtr<IWbemClassObject> params_def; hr = class_object->GetMethod(b_method_name, 0, params_def.Receive(), NULL); if (FAILED(hr)) return false; if (NULL == params_def) { // You hit this special case if the WMI class is not a CIM class. MSDN // sometimes tells you this. Welcome to WMI hell. return false; } hr = params_def->SpawnInstance(0, class_instance); return(SUCCEEDED(hr)); } bool SetParameter(IWbemClassObject* class_method, const std::wstring& parameter_name, VARIANT* parameter) { HRESULT hr = class_method->Put(parameter_name.c_str(), 0, parameter, 0); return SUCCEEDED(hr); } // The code in Launch() basically calls the Create Method of the Win32_Process // CIM class is documented here: // http://msdn2.microsoft.com/en-us/library/aa389388(VS.85).aspx // NOTE: The documentation for the Create method suggests that the ProcessId // parameter and return value are of type uint32, but when we call the method // the values in the returned out_params, are VT_I4, which is int32. bool WMIProcess::Launch(const std::wstring& command_line, int* process_id) { base::win::ScopedComPtr<IWbemServices> wmi_local; if (!WMI::CreateLocalConnection(true, wmi_local.Receive())) return false; const wchar_t class_name[] = L"Win32_Process"; const wchar_t method_name[] = L"Create"; base::win::ScopedComPtr<IWbemClassObject> process_create; if (!WMI::CreateClassMethodObject(wmi_local, class_name, method_name, process_create.Receive())) return false; ScopedVariant b_command_line(command_line.c_str()); if (!SetParameter(process_create, L"CommandLine", b_command_line.AsInput())) return false; base::win::ScopedComPtr<IWbemClassObject> out_params; HRESULT hr = wmi_local->ExecMethod(base::win::ScopedBstr(class_name), base::win::ScopedBstr(method_name), 0, NULL, process_create, out_params.Receive(), NULL); if (FAILED(hr)) return false; // We're only expecting int32 or uint32 values, so no need for ScopedVariant. VARIANT ret_value = {VT_EMPTY}; hr = out_params->Get(L"ReturnValue", 0, &ret_value, NULL, 0); if (FAILED(hr) || 0 != V_I4(&ret_value)) return false; VARIANT pid = {VT_EMPTY}; hr = out_params->Get(L"ProcessId", 0, &pid, NULL, 0); if (FAILED(hr) || 0 == V_I4(&pid)) return false; if (process_id) *process_id = V_I4(&pid); return true; } string16 WMIComputerSystem::GetModel() { base::win::ScopedComPtr<IWbemServices> services; if (!WMI::CreateLocalConnection(true, services.Receive())) return string16(); base::win::ScopedBstr query_language(L"WQL"); base::win::ScopedBstr query(L"SELECT * FROM Win32_ComputerSystem"); base::win::ScopedComPtr<IEnumWbemClassObject> enumerator; HRESULT hr = services->ExecQuery( query_language, query, WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY, NULL, enumerator.Receive()); if (FAILED(hr) || !enumerator) return string16(); base::win::ScopedComPtr<IWbemClassObject> class_object; ULONG items_returned = 0; hr = enumerator->Next(WBEM_INFINITE, 1, class_object.Receive(), &items_returned); if (!items_returned) return string16(); base::win::ScopedVariant manufacturer; class_object->Get(L"Manufacturer", 0, manufacturer.Receive(), 0, 0); base::win::ScopedVariant model; class_object->Get(L"Model", 0, model.Receive(), 0, 0); string16 model_string; if (manufacturer.type() == VT_BSTR) { model_string = V_BSTR(&manufacturer); if (model.type() == VT_BSTR) model_string += L" "; } if (model.type() == VT_BSTR) model_string += V_BSTR(&model); return model_string; } } // namespace installer <|endoftext|>
<commit_before>//===-- shm.cpp -----------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Save/restore via shared memory to survive exec*() // //===----------------------------------------------------------------------===// #include "shm.h" #include "ipcreg_internal.h" #include "magic_socket_nums.h" #include "real.h" #include "rename_fd.h" #include <sys/mman.h> #include <sys/stat.h> #include <fcntl.h> #include <errno.h> #include <string.h> #define UC(ret, msg) \ unixCheck(ret, msg, __FILE__, __LINE__, __PRETTY_FUNCTION__); void unixCheck(int ret, const char *msg, const char *file, unsigned line, const char *func, int err = errno) { if (ret == -1) { ipclog("Unix call failed in %s at %s:%u: %s - %s\n", func, file, line, msg, strerror(err)); abort(); } } static char buf[100]; const char *getShmName() { sprintf(buf, "/ipcd.%d\n", getpid()); return buf; } int get_shm(int flags, mode_t mode) { int fd = shm_open(getShmName(), flags, mode); if (fd == EEXIST) { ipclog("Shared memory segment exists, attempting to remove it...\n"); int ret = shm_unlink(getShmName()); UC(ret, "Closing existing shm"); // Okay, let's try this again fd = shm_open(getShmName(), flags, mode); } UC(fd, "shm_open"); UC(fchmod(fd, mode), "fchmod on shared memory segment"); return fd; } void shm_state_save() { // Create shared memory segment int fd = get_shm(O_RDWR | O_CREAT | O_EXCL, 0600); UC(fd, "get_shm"); bool success = rename_fd(fd, MAGIC_SHM_FD, /* cloexec */ false); assert(success && "Failed to rename SHM fd!"); // Do *not* close on exec! :) int flags = __real_fcntl(MAGIC_SHM_FD, F_GETFD, /* kludge */ 0); assert(flags >= 0); flags &= ~FD_CLOEXEC; int ret = __real_fcntl_int(MAGIC_SHM_FD, F_SETFD, flags); UC(ret, "fcntl CLOEXEC on shared memory segment"); // Size the memory segment: ret = ftruncate(MAGIC_SHM_FD, sizeof(libipc_state)); UC(ret, "ftruncate on shm"); void *stateptr = mmap(NULL, sizeof(libipc_state), PROT_READ | PROT_WRITE, MAP_SHARED, MAGIC_SHM_FD, 0); assert(stateptr != MAP_FAILED); // Copy state to shared memory segment *(libipc_state*)stateptr = state; // Unmap, but don't unlink the shared memory ret = munmap(stateptr, sizeof(libipc_state)); UC(ret, "unmap shm"); ipclog("State saved!\n"); } bool is_valid_fd(int fd) { return __real_fcntl(fd, F_GETFD, /* kludge */ 0) >= 0; } void shm_state_restore() { // If we have memory to restore, it'll be in our magic FD! if (!is_valid_fd(MAGIC_SHM_FD)) return; ipclog("Inherited ipc state FD, starting state restoration...\n"); void *stateptr = mmap(NULL, sizeof(libipc_state), PROT_READ | PROT_WRITE, MAP_SHARED, MAGIC_SHM_FD, 0); // If our FD is still open, the memory better still be there! assert(stateptr != MAP_FAILED); // Copy state to shared memory segment // Copy state from shared memory segment state = *(libipc_state*)stateptr; int ret = munmap(stateptr, sizeof(libipc_state)); UC(ret, "unmap shm"); // Done with the shared segment, thank you! ret = __real_close(MAGIC_SHM_FD); UC(ret, "close shm"); ret = shm_unlink(getShmName()); UC(ret, "shm_unlink after close"); ipclog("State restored!\n"); } void shm_state_destroy() { // If we have memory to restore, it'll be in our magic FD! assert(is_valid_fd(MAGIC_SHM_FD)); int ret = __real_close(MAGIC_SHM_FD); assert(ret == 0); ret = shm_unlink(getShmName()); UC(ret, "shm_unlink"); ipclog("Destroyed saved state!\n"); } <commit_msg>shm: Heh, actually detect EEXIST on shm_open attempt.<commit_after>//===-- shm.cpp -----------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Save/restore via shared memory to survive exec*() // //===----------------------------------------------------------------------===// #include "shm.h" #include "ipcreg_internal.h" #include "magic_socket_nums.h" #include "real.h" #include "rename_fd.h" #include <sys/mman.h> #include <sys/stat.h> #include <fcntl.h> #include <errno.h> #include <string.h> #define UC(ret, msg) \ unixCheck(ret, msg, __FILE__, __LINE__, __PRETTY_FUNCTION__); void unixCheck(int ret, const char *msg, const char *file, unsigned line, const char *func, int err = errno) { if (ret == -1) { ipclog("Unix call failed in %s at %s:%u: %s - %s\n", func, file, line, msg, strerror(err)); abort(); } } static char buf[100]; const char *getShmName() { sprintf(buf, "/ipcd.%d\n", getpid()); return buf; } int get_shm(int flags, mode_t mode) { int fd = shm_open(getShmName(), flags, mode); if (fd == -1 && errno == EEXIST) { ipclog("Shared memory segment exists, attempting to remove it...\n"); int ret = shm_unlink(getShmName()); UC(ret, "Closing existing shm"); // Okay, let's try this again fd = shm_open(getShmName(), flags, mode); } UC(fd, "shm_open"); UC(fchmod(fd, mode), "fchmod on shared memory segment"); return fd; } void shm_state_save() { // Create shared memory segment int fd = get_shm(O_RDWR | O_CREAT | O_EXCL, 0600); UC(fd, "get_shm"); bool success = rename_fd(fd, MAGIC_SHM_FD, /* cloexec */ false); assert(success && "Failed to rename SHM fd!"); // Do *not* close on exec! :) int flags = __real_fcntl(MAGIC_SHM_FD, F_GETFD, /* kludge */ 0); assert(flags >= 0); flags &= ~FD_CLOEXEC; int ret = __real_fcntl_int(MAGIC_SHM_FD, F_SETFD, flags); UC(ret, "fcntl CLOEXEC on shared memory segment"); // Size the memory segment: ret = ftruncate(MAGIC_SHM_FD, sizeof(libipc_state)); UC(ret, "ftruncate on shm"); void *stateptr = mmap(NULL, sizeof(libipc_state), PROT_READ | PROT_WRITE, MAP_SHARED, MAGIC_SHM_FD, 0); assert(stateptr != MAP_FAILED); // Copy state to shared memory segment *(libipc_state*)stateptr = state; // Unmap, but don't unlink the shared memory ret = munmap(stateptr, sizeof(libipc_state)); UC(ret, "unmap shm"); ipclog("State saved!\n"); } bool is_valid_fd(int fd) { return __real_fcntl(fd, F_GETFD, /* kludge */ 0) >= 0; } void shm_state_restore() { // If we have memory to restore, it'll be in our magic FD! if (!is_valid_fd(MAGIC_SHM_FD)) return; ipclog("Inherited ipc state FD, starting state restoration...\n"); void *stateptr = mmap(NULL, sizeof(libipc_state), PROT_READ | PROT_WRITE, MAP_SHARED, MAGIC_SHM_FD, 0); // If our FD is still open, the memory better still be there! assert(stateptr != MAP_FAILED); // Copy state to shared memory segment // Copy state from shared memory segment state = *(libipc_state*)stateptr; int ret = munmap(stateptr, sizeof(libipc_state)); UC(ret, "unmap shm"); // Done with the shared segment, thank you! ret = __real_close(MAGIC_SHM_FD); UC(ret, "close shm"); ret = shm_unlink(getShmName()); UC(ret, "shm_unlink after close"); ipclog("State restored!\n"); } void shm_state_destroy() { // If we have memory to restore, it'll be in our magic FD! assert(is_valid_fd(MAGIC_SHM_FD)); int ret = __real_close(MAGIC_SHM_FD); assert(ret == 0); ret = shm_unlink(getShmName()); UC(ret, "shm_unlink"); ipclog("Destroyed saved state!\n"); } <|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/nacl/nacl_listener.h" #include <errno.h> #include "base/command_line.h" #include "base/logging.h" #include "base/memory/scoped_ptr.h" #include "base/message_loop.h" #include "chrome/common/nacl_messages.h" #include "ipc/ipc_channel.h" #include "ipc/ipc_switches.h" #include "native_client/src/shared/imc/nacl_imc.h" #include "native_client/src/trusted/service_runtime/sel_main_chrome.h" #if defined(OS_LINUX) #include "content/public/common/child_process_sandbox_support_linux.h" #endif #if defined(OS_WIN) #include <fcntl.h> #include <io.h> #endif #if defined(OS_MACOSX) namespace { // On Mac OS X, shm_open() works in the sandbox but does not give us // an FD that we can map as PROT_EXEC. Rather than doing an IPC to // get an executable SHM region when CreateMemoryObject() is called, // we preallocate one on startup, since NaCl's sel_ldr only needs one // of them. This saves a round trip. base::subtle::Atomic32 g_shm_fd = -1; int CreateMemoryObject(size_t size, bool executable) { if (executable && size > 0) { int result_fd = base::subtle::NoBarrier_AtomicExchange(&g_shm_fd, -1); if (result_fd != -1) { // ftruncate() is disallowed by the Mac OS X sandbox and // returns EPERM. Luckily, we can get the same effect with // lseek() + write(). if (lseek(result_fd, size - 1, SEEK_SET) == -1) { LOG(ERROR) << "lseek() failed: " << errno; return -1; } if (write(result_fd, "", 1) != 1) { LOG(ERROR) << "write() failed: " << errno; return -1; } return result_fd; } } // Fall back to NaCl's default implementation. return -1; } } // namespace #endif // defined(OS_MACOSX) NaClListener::NaClListener() : debug_enabled_(false) {} NaClListener::~NaClListener() {} void NaClListener::Listen() { std::string channel_name = CommandLine::ForCurrentProcess()->GetSwitchValueASCII( switches::kProcessChannelID); IPC::Channel channel(channel_name, IPC::Channel::MODE_CLIENT, this); CHECK(channel.Connect()); MessageLoop::current()->Run(); } bool NaClListener::OnMessageReceived(const IPC::Message& msg) { bool handled = true; IPC_BEGIN_MESSAGE_MAP(NaClListener, msg) IPC_MESSAGE_HANDLER(NaClProcessMsg_Start, OnStartSelLdr) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() return handled; } void NaClListener::OnStartSelLdr(std::vector<nacl::FileDescriptor> handles) { #if defined(OS_LINUX) nacl::SetCreateMemoryObjectFunc(content::MakeSharedMemorySegmentViaIPC); #elif defined(OS_MACOSX) nacl::SetCreateMemoryObjectFunc(CreateMemoryObject); CHECK(handles.size() >= 1); g_shm_fd = nacl::ToNativeHandle(handles[handles.size() - 1]); handles.pop_back(); #endif CHECK(handles.size() >= 1); NaClHandle irt_handle = nacl::ToNativeHandle(handles[handles.size() - 1]); handles.pop_back(); #if defined(OS_WIN) int irt_desc = _open_osfhandle(reinterpret_cast<intptr_t>(irt_handle), _O_RDONLY | _O_BINARY); if (irt_desc < 0) { LOG(ERROR) << "_open_osfhandle() failed"; return; } #else int irt_desc = irt_handle; #endif NaClSetIrtFileDesc(irt_desc); scoped_array<NaClHandle> array(new NaClHandle[handles.size()]); for (size_t i = 0; i < handles.size(); i++) { array[i] = nacl::ToNativeHandle(handles[i]); } NaClMainForChromium(static_cast<int>(handles.size()), array.get(), debug_enabled_); NOTREACHED(); } <commit_msg>NaCl: Switch to using the new extensible startup interface<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/nacl/nacl_listener.h" #include <errno.h> #include "base/command_line.h" #include "base/logging.h" #include "base/memory/scoped_ptr.h" #include "base/message_loop.h" #include "chrome/common/nacl_messages.h" #include "ipc/ipc_channel.h" #include "ipc/ipc_switches.h" #include "native_client/src/trusted/service_runtime/sel_main_chrome.h" #if defined(OS_LINUX) #include "content/public/common/child_process_sandbox_support_linux.h" #endif #if defined(OS_WIN) #include <fcntl.h> #include <io.h> #endif namespace { #if defined(OS_MACOSX) // On Mac OS X, shm_open() works in the sandbox but does not give us // an FD that we can map as PROT_EXEC. Rather than doing an IPC to // get an executable SHM region when CreateMemoryObject() is called, // we preallocate one on startup, since NaCl's sel_ldr only needs one // of them. This saves a round trip. base::subtle::Atomic32 g_shm_fd = -1; int CreateMemoryObject(size_t size, int executable) { if (executable && size > 0) { int result_fd = base::subtle::NoBarrier_AtomicExchange(&g_shm_fd, -1); if (result_fd != -1) { // ftruncate() is disallowed by the Mac OS X sandbox and // returns EPERM. Luckily, we can get the same effect with // lseek() + write(). if (lseek(result_fd, size - 1, SEEK_SET) == -1) { LOG(ERROR) << "lseek() failed: " << errno; return -1; } if (write(result_fd, "", 1) != 1) { LOG(ERROR) << "write() failed: " << errno; return -1; } return result_fd; } } // Fall back to NaCl's default implementation. return -1; } #elif defined(OS_LINUX) int CreateMemoryObject(size_t size, int executable) { return content::MakeSharedMemorySegmentViaIPC(size, executable); } #endif } // namespace NaClListener::NaClListener() : debug_enabled_(false) {} NaClListener::~NaClListener() {} void NaClListener::Listen() { std::string channel_name = CommandLine::ForCurrentProcess()->GetSwitchValueASCII( switches::kProcessChannelID); IPC::Channel channel(channel_name, IPC::Channel::MODE_CLIENT, this); CHECK(channel.Connect()); MessageLoop::current()->Run(); } bool NaClListener::OnMessageReceived(const IPC::Message& msg) { bool handled = true; IPC_BEGIN_MESSAGE_MAP(NaClListener, msg) IPC_MESSAGE_HANDLER(NaClProcessMsg_Start, OnStartSelLdr) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() return handled; } void NaClListener::OnStartSelLdr(std::vector<nacl::FileDescriptor> handles) { struct NaClChromeMainArgs *args = NaClChromeMainArgsCreate(); if (args == NULL) { LOG(ERROR) << "NaClChromeMainArgsCreate() failed"; return; } #if defined(OS_LINUX) || defined(OS_MACOSX) args->create_memory_object_func = CreateMemoryObject; # if defined(OS_MACOSX) CHECK(handles.size() >= 1); g_shm_fd = nacl::ToNativeHandle(handles[handles.size() - 1]); handles.pop_back(); # endif #endif CHECK(handles.size() >= 1); NaClHandle irt_handle = nacl::ToNativeHandle(handles[handles.size() - 1]); handles.pop_back(); #if defined(OS_WIN) args->irt_fd = _open_osfhandle(reinterpret_cast<intptr_t>(irt_handle), _O_RDONLY | _O_BINARY); if (args->irt_fd < 0) { LOG(ERROR) << "_open_osfhandle() failed"; return; } #else args->irt_fd = irt_handle; #endif CHECK(handles.size() == 1); args->imc_bootstrap_handle = nacl::ToNativeHandle(handles[0]); args->enable_debug_stub = debug_enabled_; NaClChromeMainStart(args); NOTREACHED(); } <|endoftext|>
<commit_before>#include "etl/armv7m/exception_table.h" #include "etl/common/attribute_macros.h" ETL_NORETURN void etl_armv7m_reset_handler() { while (1); } // Generate traps for all unused exception vectors. #define ETL_ARMV7M_EXCEPTION(name) \ ETL_NORETURN void etl_armv7m_ ## name ## _handler() { \ while (1); \ } #define ETL_ARMV7M_EXCEPTION_RESERVED(n) #include "etl/armv7m/exceptions.def" <commit_msg>wip minimal<commit_after>#include "etl/armv7m/exception_table.h" #include "etl/common/attribute_macros.h" #include "etl/armv7m/nvic.h" #include "etl/armv7m/scb.h" ETL_NORETURN void etl_armv7m_reset_handler() { etl::armv7m::scb.enable_faults(); while (1); } // Generate traps for all unused exception vectors. #define ETL_ARMV7M_EXCEPTION(name) \ ETL_NORETURN void etl_armv7m_ ## name ## _handler() { \ while (1); \ } #define ETL_ARMV7M_EXCEPTION_RESERVED(n) #include "etl/armv7m/exceptions.def" <|endoftext|>
<commit_before>/*----------------------------------------------------------------------------------------------- The MIT License (MIT) Copyright (c) 2014-2015 Kim Kulling 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 <openddlparser/Value.h> #include <iostream> #include <cassert> BEGIN_ODDLPARSER_NS static Value::Iterator end( ddl_nullptr ); Value::Iterator::Iterator() : m_start( ddl_nullptr ) , m_current( ddl_nullptr ) { // empty } Value::Iterator::Iterator( Value *start ) : m_start( start ) , m_current( start ) { // empty } Value::Iterator::Iterator( const Iterator &rhs ) : m_start( rhs.m_start ) , m_current( rhs.m_current ) { // empty } Value::Iterator::~Iterator() { // empty } bool Value::Iterator::hasNext() const { if( ddl_nullptr == m_current ) { return false; } return ( ddl_nullptr != m_current->getNext() ); } Value *Value::Iterator::getNext() { if( !hasNext() ) { return ddl_nullptr; } Value *v( m_current->getNext() ); m_current = v; return v; } const Value::Iterator Value::Iterator::operator++( int ) { if( ddl_nullptr == m_current ) { return end; } m_current = m_current->getNext(); Iterator inst( m_current ); return inst; } Value::Iterator &Value::Iterator::operator++( ) { if( ddl_nullptr == m_current ) { return end; } m_current = m_current->getNext(); return *this; } bool Value::Iterator::operator == ( const Iterator &rhs ) const { return ( m_current == rhs.m_current ); } Value *Value::Iterator::operator->( ) const { if( nullptr == m_current ) { return ddl_nullptr; } return m_current; } Value::Value( ValueType type ) : m_type( type ) , m_size( 0 ) , m_data( ddl_nullptr ) , m_next( ddl_nullptr ) { // empty } Value::~Value() { // empty } void Value::setBool( bool value ) { assert( ddl_bool == m_type ); ::memcpy( m_data, &value, m_size ); } bool Value::getBool() { assert( ddl_bool == m_type ); return ( *m_data == 1 ); } void Value::setInt8( int8 value ) { assert( ddl_int8 == m_type ); ::memcpy( m_data, &value, m_size ); } int8 Value::getInt8() { assert( ddl_int8 == m_type ); return ( int8 ) ( *m_data ); } void Value::setInt16( int16 value ) { assert( ddl_int16 == m_type ); ::memcpy( m_data, &value, m_size ); } int16 Value::getInt16() { assert( ddl_int16 == m_type ); int16 i; ::memcpy( &i, m_data, m_size ); return i; } void Value::setInt32( int32 value ) { assert( ddl_int32 == m_type ); ::memcpy( m_data, &value, m_size ); } int32 Value::getInt32() { assert( ddl_int32 == m_type ); int32 i; ::memcpy( &i, m_data, m_size ); return i; } void Value::setInt64( int64 value ) { assert( ddl_int64 == m_type ); ::memcpy( m_data, &value, m_size ); } int64 Value::getInt64() { assert( ddl_int64 == m_type ); int64 i; ::memcpy( &i, m_data, m_size ); return i; } void Value::setUnsignedInt8( uint8 value ) { assert( ddl_unsigned_int8 == m_type ); ::memcpy( m_data, &value, m_size ); } uint8 Value::getUnsignedInt8() const { assert( ddl_unsigned_int8 == m_type ); uint8 i; ::memcpy( &i, m_data, m_size ); return i; } void Value::setUnsignedInt16( uint16 value ) { assert( ddl_unsigned_int16 == m_type ); ::memcpy( m_data, &value, m_size ); } uint16 Value::getUnsignedInt16() const { assert( ddl_unsigned_int16 == m_type ); uint16 i; ::memcpy( &i, m_data, m_size ); return i; } void Value::setUnsignedInt32( uint32 value ) { assert( ddl_unsigned_int32 == m_type ); ::memcpy( m_data, &value, m_size ); } uint32 Value::getUnsignedInt32() const { assert( ddl_unsigned_int32 == m_type ); uint32 i; ::memcpy( &i, m_data, m_size ); return i; } void Value::setUnsignedInt64( uint64 value ) { assert( ddl_unsigned_int64 == m_type ); ::memcpy( m_data, &value, m_size ); } uint64 Value::getUnsignedInt64() const { assert( ddl_unsigned_int64 == m_type ); uint64 i; ::memcpy( &i, m_data, m_size ); return i; } void Value::setFloat( float value ) { assert( ddl_float == m_type ); ::memcpy( m_data, &value, m_size ); } float Value::getFloat() const { if( m_type == ddl_float ) { float v; ::memcpy( &v, m_data, m_size ); return ( float ) v; } else { float tmp; ::memcpy( &tmp, m_data, 4 ); return ( float ) tmp; } } void Value::setDouble( double value ) { assert( ddl_double == m_type ); ::memcpy( m_data, &value, m_size ); } double Value::getDouble() const { double v; ::memcpy( &v, m_data, m_size ); return v; } void Value::setString( const std::string &str ) { assert( ddl_string == m_type ); ::memcpy( m_data, str.c_str(), str.size() ); m_data[ str.size() ] = '\0'; } const char *Value::getString() const { return (const char*) m_data; } void Value::dump() { switch( m_type ) { case ddl_none: std::cout << "None" << std::endl; break; case ddl_bool: std::cout << getBool() << std::endl; break; case ddl_int8: std::cout << getInt8() << std::endl; break; case ddl_int16: std::cout << getInt16() << std::endl; break; case ddl_int32: std::cout << getInt32() << std::endl; break; case ddl_int64: std::cout << getInt64() << std::endl; break; case ddl_unsigned_int8: std::cout << "Not supported" << std::endl; break; case ddl_unsigned_int16: std::cout << "Not supported" << std::endl; break; case ddl_unsigned_int32: std::cout << "Not supported" << std::endl; break; case ddl_unsigned_int64: std::cout << "Not supported" << std::endl; break; case ddl_half: std::cout << "Not supported" << std::endl; break; case ddl_float: std::cout << getFloat() << std::endl; break; case ddl_double: std::cout << getDouble() << std::endl; break; case ddl_string: std::cout << "Not supported" << std::endl; break; case ddl_ref: std::cout << "Not supported" << std::endl; break; default: break; } } void Value::setNext( Value *next ) { m_next = next; } Value *Value::getNext() const { return m_next; } Value *ValueAllocator::allocPrimData( Value::ValueType type, size_t len ) { if( type == Value::ddl_none || Value::ddl_types_max == type ) { return ddl_nullptr; } Value *data = new Value( type ); data->m_type = type; switch( type ) { case Value::ddl_bool: data->m_size = sizeof( bool ); break; case Value::ddl_int8: data->m_size = sizeof( int8 ); break; case Value::ddl_int16: data->m_size = sizeof( int16 ); break; case Value::ddl_int32: data->m_size = sizeof( int32 ); break; case Value::ddl_int64: data->m_size = sizeof( int64 ); break; case Value::ddl_unsigned_int8: data->m_size = sizeof( uint8 ); break; case Value::ddl_unsigned_int16: data->m_size = sizeof( uint16 ); break; case Value::ddl_unsigned_int32: data->m_size = sizeof( uint32 ); break; case Value::ddl_unsigned_int64: data->m_size = sizeof( uint64 ); break; case Value::ddl_half: data->m_size = sizeof( short ); break; case Value::ddl_float: data->m_size = sizeof( float ); break; case Value::ddl_double: data->m_size = sizeof( double ); break; case Value::ddl_string: data->m_size = sizeof( char ); break; case Value::ddl_ref: data->m_size = sizeof( char ); break; case Value::ddl_none: case Value::ddl_types_max: default: break; } if( data->m_size ) { size_t len1( len ); if( Value::ddl_string == type ) { len1++; } data->m_size *= len1; data->m_data = new unsigned char[ data->m_size ]; } return data; } void ValueAllocator::releasePrimData( Value **data ) { if( !data ) { return; } delete *data; *data = ddl_nullptr; } END_ODDLPARSER_NS <commit_msg>Value: add missing assert test.<commit_after>/*----------------------------------------------------------------------------------------------- The MIT License (MIT) Copyright (c) 2014-2015 Kim Kulling 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 <openddlparser/Value.h> #include <iostream> #include <cassert> BEGIN_ODDLPARSER_NS static Value::Iterator end( ddl_nullptr ); Value::Iterator::Iterator() : m_start( ddl_nullptr ) , m_current( ddl_nullptr ) { // empty } Value::Iterator::Iterator( Value *start ) : m_start( start ) , m_current( start ) { // empty } Value::Iterator::Iterator( const Iterator &rhs ) : m_start( rhs.m_start ) , m_current( rhs.m_current ) { // empty } Value::Iterator::~Iterator() { // empty } bool Value::Iterator::hasNext() const { if( ddl_nullptr == m_current ) { return false; } return ( ddl_nullptr != m_current->getNext() ); } Value *Value::Iterator::getNext() { if( !hasNext() ) { return ddl_nullptr; } Value *v( m_current->getNext() ); m_current = v; return v; } const Value::Iterator Value::Iterator::operator++( int ) { if( ddl_nullptr == m_current ) { return end; } m_current = m_current->getNext(); Iterator inst( m_current ); return inst; } Value::Iterator &Value::Iterator::operator++( ) { if( ddl_nullptr == m_current ) { return end; } m_current = m_current->getNext(); return *this; } bool Value::Iterator::operator == ( const Iterator &rhs ) const { return ( m_current == rhs.m_current ); } Value *Value::Iterator::operator->( ) const { if( nullptr == m_current ) { return ddl_nullptr; } return m_current; } Value::Value( ValueType type ) : m_type( type ) , m_size( 0 ) , m_data( ddl_nullptr ) , m_next( ddl_nullptr ) { // empty } Value::~Value() { // empty } void Value::setBool( bool value ) { assert( ddl_bool == m_type ); ::memcpy( m_data, &value, m_size ); } bool Value::getBool() { assert( ddl_bool == m_type ); return ( *m_data == 1 ); } void Value::setInt8( int8 value ) { assert( ddl_int8 == m_type ); ::memcpy( m_data, &value, m_size ); } int8 Value::getInt8() { assert( ddl_int8 == m_type ); return ( int8 ) ( *m_data ); } void Value::setInt16( int16 value ) { assert( ddl_int16 == m_type ); ::memcpy( m_data, &value, m_size ); } int16 Value::getInt16() { assert( ddl_int16 == m_type ); int16 i; ::memcpy( &i, m_data, m_size ); return i; } void Value::setInt32( int32 value ) { assert( ddl_int32 == m_type ); ::memcpy( m_data, &value, m_size ); } int32 Value::getInt32() { assert( ddl_int32 == m_type ); int32 i; ::memcpy( &i, m_data, m_size ); return i; } void Value::setInt64( int64 value ) { assert( ddl_int64 == m_type ); ::memcpy( m_data, &value, m_size ); } int64 Value::getInt64() { assert( ddl_int64 == m_type ); int64 i; ::memcpy( &i, m_data, m_size ); return i; } void Value::setUnsignedInt8( uint8 value ) { assert( ddl_unsigned_int8 == m_type ); ::memcpy( m_data, &value, m_size ); } uint8 Value::getUnsignedInt8() const { assert( ddl_unsigned_int8 == m_type ); uint8 i; ::memcpy( &i, m_data, m_size ); return i; } void Value::setUnsignedInt16( uint16 value ) { assert( ddl_unsigned_int16 == m_type ); ::memcpy( m_data, &value, m_size ); } uint16 Value::getUnsignedInt16() const { assert( ddl_unsigned_int16 == m_type ); uint16 i; ::memcpy( &i, m_data, m_size ); return i; } void Value::setUnsignedInt32( uint32 value ) { assert( ddl_unsigned_int32 == m_type ); ::memcpy( m_data, &value, m_size ); } uint32 Value::getUnsignedInt32() const { assert( ddl_unsigned_int32 == m_type ); uint32 i; ::memcpy( &i, m_data, m_size ); return i; } void Value::setUnsignedInt64( uint64 value ) { assert( ddl_unsigned_int64 == m_type ); ::memcpy( m_data, &value, m_size ); } uint64 Value::getUnsignedInt64() const { assert( ddl_unsigned_int64 == m_type ); uint64 i; ::memcpy( &i, m_data, m_size ); return i; } void Value::setFloat( float value ) { assert( ddl_float == m_type ); ::memcpy( m_data, &value, m_size ); } float Value::getFloat() const { if( m_type == ddl_float ) { float v; ::memcpy( &v, m_data, m_size ); return ( float ) v; } else { float tmp; ::memcpy( &tmp, m_data, 4 ); return ( float ) tmp; } } void Value::setDouble( double value ) { assert( ddl_double == m_type ); ::memcpy( m_data, &value, m_size ); } double Value::getDouble() const { assert( ddl_double == m_type ); double v; ::memcpy( &v, m_data, m_size ); return v; } void Value::setString( const std::string &str ) { assert( ddl_string == m_type ); ::memcpy( m_data, str.c_str(), str.size() ); m_data[ str.size() ] = '\0'; } const char *Value::getString() const { assert( ddl_string == m_type ); return (const char*) m_data; } void Value::dump() { switch( m_type ) { case ddl_none: std::cout << "None" << std::endl; break; case ddl_bool: std::cout << getBool() << std::endl; break; case ddl_int8: std::cout << getInt8() << std::endl; break; case ddl_int16: std::cout << getInt16() << std::endl; break; case ddl_int32: std::cout << getInt32() << std::endl; break; case ddl_int64: std::cout << getInt64() << std::endl; break; case ddl_unsigned_int8: std::cout << "Not supported" << std::endl; break; case ddl_unsigned_int16: std::cout << "Not supported" << std::endl; break; case ddl_unsigned_int32: std::cout << "Not supported" << std::endl; break; case ddl_unsigned_int64: std::cout << "Not supported" << std::endl; break; case ddl_half: std::cout << "Not supported" << std::endl; break; case ddl_float: std::cout << getFloat() << std::endl; break; case ddl_double: std::cout << getDouble() << std::endl; break; case ddl_string: std::cout << "Not supported" << std::endl; break; case ddl_ref: std::cout << "Not supported" << std::endl; break; default: break; } } void Value::setNext( Value *next ) { m_next = next; } Value *Value::getNext() const { return m_next; } Value *ValueAllocator::allocPrimData( Value::ValueType type, size_t len ) { if( type == Value::ddl_none || Value::ddl_types_max == type ) { return ddl_nullptr; } Value *data = new Value( type ); data->m_type = type; switch( type ) { case Value::ddl_bool: data->m_size = sizeof( bool ); break; case Value::ddl_int8: data->m_size = sizeof( int8 ); break; case Value::ddl_int16: data->m_size = sizeof( int16 ); break; case Value::ddl_int32: data->m_size = sizeof( int32 ); break; case Value::ddl_int64: data->m_size = sizeof( int64 ); break; case Value::ddl_unsigned_int8: data->m_size = sizeof( uint8 ); break; case Value::ddl_unsigned_int16: data->m_size = sizeof( uint16 ); break; case Value::ddl_unsigned_int32: data->m_size = sizeof( uint32 ); break; case Value::ddl_unsigned_int64: data->m_size = sizeof( uint64 ); break; case Value::ddl_half: data->m_size = sizeof( short ); break; case Value::ddl_float: data->m_size = sizeof( float ); break; case Value::ddl_double: data->m_size = sizeof( double ); break; case Value::ddl_string: data->m_size = sizeof( char ); break; case Value::ddl_ref: data->m_size = sizeof( char ); break; case Value::ddl_none: case Value::ddl_types_max: default: break; } if( data->m_size ) { size_t len1( len ); if( Value::ddl_string == type ) { len1++; } data->m_size *= len1; data->m_data = new unsigned char[ data->m_size ]; } return data; } void ValueAllocator::releasePrimData( Value **data ) { if( !data ) { return; } delete *data; *data = ddl_nullptr; } END_ODDLPARSER_NS <|endoftext|>
<commit_before>/* * Copyright 2008 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "condor_common.h" #include "LoadPlugins.h" #include "condor_config.h" #include "directory.h" #include "simplelist.h" #ifndef WIN32 #include <dlfcn.h> #endif const char * getErrorString() { static std::string szError; #ifdef WIN32 LPVOID lpMsgBuf; DWORD iErrCode = GetLastError(); FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL, (DWORD)iErrCode, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR) &lpMsgBuf, 0, NULL ); szError = (char *) lpMsgBuf; LocalFree(lpMsgBuf); #else szError = dlerror(); #endif return szError.c_str(); } void LoadPlugins() { static bool skip = false; const char *error; StringList plugins; char *plugin_files; MyString plugin_dir; const char *plugin_file; // Only initialize once /*, except for when we are force'd.*/ if (skip /*&& !force*/) { return; } skip = true; // Setup the plugins StringList to contain the filenames for // dlopen. Either a PLUGINS config option is used, preferrably // setup as SUBSYSTEM.PLUGINS, or, in the absense of PLUGINS, // a PLUGINS_DIR config option is used, also // recommended SUBSYSTEM.PLUGINS_DIR. dprintf(D_FULLDEBUG, "Checking for PLUGINS config option\n"); plugin_files = param("PLUGINS"); if (!plugin_files) { char *tmp; dprintf(D_FULLDEBUG, "No PLUGINS config option, trying PLUGIN_DIR option\n"); tmp = param("PLUGIN_DIR"); if (!tmp) { dprintf(D_FULLDEBUG, "No PLUGIN_DIR config option, no plugins loaded\n"); return; } else { plugin_dir = tmp; free(tmp); tmp = NULL; Directory directory(plugin_dir.Value()); while (NULL != (plugin_file = directory.Next())) { // NOTE: This should eventually support .dll for // Windows, .dylib for Darwin, .sl for HPUX, etc if (0 == strcmp(".so", plugin_file + strlen(plugin_file) - 3)) { dprintf(D_FULLDEBUG, "PLUGIN_DIR, found: %s\n", plugin_file); plugins.append((plugin_dir + DIR_DELIM_STRING + plugin_file).Value()); } else { dprintf(D_FULLDEBUG, "PLUGIN_DIR, ignoring: %s\n", plugin_file); } } } } else { plugins.initializeFromString(plugin_files); free(plugin_files); plugin_files = NULL; } #ifndef WIN32 dlerror(); // Clear error #endif plugins.rewind(); while (NULL != (plugin_file = plugins.next())) { // The plugin has a way to automatically register itself // when loaded. // XXX: When Jim's safe path checking code is available // more generally in Condor the path to the // plugin_file here MUST be checked! #ifdef WIN32 if( NULL == LoadLibrary(plugin_file) ) { #else if (!dlopen(plugin_file, RTLD_NOW)) { #endif error = getErrorString(); if (error) { dprintf(D_ALWAYS, "Failed to load plugin: %s reason: %s\n", plugin_file, error); } else { dprintf(D_ALWAYS, "Unknown error while loading plugin: %s\n", plugin_file); } } else { dprintf(D_ALWAYS, "Successfully loaded plugin: %s\n", plugin_file); } } // NOTE: The handle returned is currently ignored, // which means closing is not possible. This is due in part // to the uber scary nature of the linkage to daemon-core } <commit_msg>(#6343) Load plugins with global scope<commit_after>/* * Copyright 2008 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "condor_common.h" #include "LoadPlugins.h" #include "condor_config.h" #include "directory.h" #include "simplelist.h" #ifndef WIN32 #include <dlfcn.h> #endif const char * getErrorString() { static std::string szError; #ifdef WIN32 LPVOID lpMsgBuf; DWORD iErrCode = GetLastError(); FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL, (DWORD)iErrCode, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR) &lpMsgBuf, 0, NULL ); szError = (char *) lpMsgBuf; LocalFree(lpMsgBuf); #else szError = dlerror(); #endif return szError.c_str(); } void LoadPlugins() { static bool skip = false; const char *error; StringList plugins; char *plugin_files; MyString plugin_dir; const char *plugin_file; // Only initialize once /*, except for when we are force'd.*/ if (skip /*&& !force*/) { return; } skip = true; // Setup the plugins StringList to contain the filenames for // dlopen. Either a PLUGINS config option is used, preferrably // setup as SUBSYSTEM.PLUGINS, or, in the absense of PLUGINS, // a PLUGINS_DIR config option is used, also // recommended SUBSYSTEM.PLUGINS_DIR. dprintf(D_FULLDEBUG, "Checking for PLUGINS config option\n"); plugin_files = param("PLUGINS"); if (!plugin_files) { char *tmp; dprintf(D_FULLDEBUG, "No PLUGINS config option, trying PLUGIN_DIR option\n"); tmp = param("PLUGIN_DIR"); if (!tmp) { dprintf(D_FULLDEBUG, "No PLUGIN_DIR config option, no plugins loaded\n"); return; } else { plugin_dir = tmp; free(tmp); tmp = NULL; Directory directory(plugin_dir.Value()); while (NULL != (plugin_file = directory.Next())) { // NOTE: This should eventually support .dll for // Windows, .dylib for Darwin, .sl for HPUX, etc if (0 == strcmp(".so", plugin_file + strlen(plugin_file) - 3)) { dprintf(D_FULLDEBUG, "PLUGIN_DIR, found: %s\n", plugin_file); plugins.append((plugin_dir + DIR_DELIM_STRING + plugin_file).Value()); } else { dprintf(D_FULLDEBUG, "PLUGIN_DIR, ignoring: %s\n", plugin_file); } } } } else { plugins.initializeFromString(plugin_files); free(plugin_files); plugin_files = NULL; } #ifndef WIN32 dlerror(); // Clear error #endif plugins.rewind(); while (NULL != (plugin_file = plugins.next())) { // The plugin has a way to automatically register itself // when loaded. // XXX: When Jim's safe path checking code is available // more generally in Condor the path to the // plugin_file here MUST be checked! #ifdef WIN32 if( NULL == LoadLibrary(plugin_file) ) { #else if (!dlopen(plugin_file, RTLD_NOW | RTLD_GLOBAL)) { #endif error = getErrorString(); if (error) { dprintf(D_ALWAYS, "Failed to load plugin: %s reason: %s\n", plugin_file, error); } else { dprintf(D_ALWAYS, "Unknown error while loading plugin: %s\n", plugin_file); } } else { dprintf(D_ALWAYS, "Successfully loaded plugin: %s\n", plugin_file); } } // NOTE: The handle returned is currently ignored, // which means closing is not possible. This is due in part // to the uber scary nature of the linkage to daemon-core } <|endoftext|>
<commit_before>#ifndef CONTAINERS_BACKINDEX_BAG_HPP_ #define CONTAINERS_BACKINDEX_BAG_HPP_ #include <limits> #include "containers/segmented_vector.hpp" class backindex_bag_index_t { public: backindex_bag_index_t() : index_(NOT_IN_A_BAG) #ifndef NDEBUG , owner_(NULL) #endif { } ~backindex_bag_index_t() { guarantee(index_ == NOT_IN_A_BAG); } private: template <class T> friend class backindex_bag_t; static const size_t NOT_IN_A_BAG = std::numeric_limits<size_t>::max(); // The item's index into a (specific) backindex_bag_t, or NOT_IN_A_BAG if it // doesn't belong to the backindex_bag_t. size_t index_; #ifndef NDEBUG // RSI: Remove this? void *owner_; #endif DISABLE_COPYING(backindex_bag_index_t); }; // A bag of elements that it _does not own_. template <class T> class backindex_bag_t { public: typedef backindex_bag_index_t *(*backindex_bag_index_accessor_t)(T); explicit backindex_bag_t(backindex_bag_index_accessor_t accessor) : accessor_(accessor) { } ~backindex_bag_t() { // Another way to implement this would be to simply remove all its elements. guarantee(vector_.size() == 0); } // Retruns true if the potential element of this container is in fact an element // of this container. The idea behind this function is that some value of type T // could be a member of one of several backindex_bag_t's (or none). We see if // it's a memory of this one. bool has_element(T potential_element) const { const backindex_bag_index_t *const backindex = accessor_(potential_element); bool ret = backindex->index_ < vector_.size() && vector_[backindex->index_] == potential_element; rassert(!ret || backindex->owner_ == this); return ret; } // Removes the element from the bag. void remove(T element) { backindex_bag_index_t *const backindex = accessor_(element); rassert(backindex->index_ != backindex_bag_index_t::NOT_IN_A_BAG); rassert(backindex->owner_ == this); guarantee(backindex->index_ < vector_.size(), "early index has wrong value: index=%zu, size=%zu", backindex->index_, vector_.size()); const size_t index = backindex->index_; // Move the element in the last position to the removed element's position. // The code here feels weird when back_element == element (i.e. when // backindex->index_ == back_element_backindex->index_) but it works (I // hope). const T back_element = vector_.back(); backindex_bag_index_t *const back_element_backindex = accessor_(back_element); rassert(back_element_backindex->owner_ == this); rassert(back_element_backindex->index_ == vector_.size() - 1, "index has wrong value: index=%zu, size=%zu", back_element_backindex->index_, vector_.size()); back_element_backindex->index_ = index; vector_[index] = back_element; vector_.pop_back(); backindex->index_ = backindex_bag_index_t::NOT_IN_A_BAG; #ifndef NDEBUG backindex->owner_ = NULL; #endif } // Adds the element to the bag. void add(T element) { backindex_bag_index_t *const backindex = accessor_(element); rassert(backindex->owner_ == NULL); guarantee(backindex->index_ == backindex_bag_index_t::NOT_IN_A_BAG); backindex->index_ = vector_.size(); #ifndef NDEBUG backindex->owner_ = this; #endif vector_.push_back(element); } size_t size() const { return vector_.size(); } // Accesses an element by index. This is called "access random" because // hopefully the index was randomly generated. There are no guarantees about the // ordering of elements in this bag. T access_random(size_t index) const { rassert(index != backindex_bag_index_t::NOT_IN_A_BAG); guarantee(index < vector_.size()); return vector_[index]; } private: const backindex_bag_index_accessor_t accessor_; // RSP: Huge block size, shitty data structure for a bag. segmented_vector_t<T> vector_; DISABLE_COPYING(backindex_bag_t); }; #endif // CONTAINERS_BACKINDEX_BAG_HPP_ <commit_msg>Some debugfs and guarantees in backindex_bag.<commit_after>#ifndef CONTAINERS_BACKINDEX_BAG_HPP_ #define CONTAINERS_BACKINDEX_BAG_HPP_ #include <limits> #include "containers/segmented_vector.hpp" class backindex_bag_index_t { public: backindex_bag_index_t() : index_(NOT_IN_A_BAG) #ifndef NDEBUG , owner_(NULL) #endif { debugf("index %p create\n", this); } ~backindex_bag_index_t() { debugf("index %p destroy\n", this); guarantee(index_ == NOT_IN_A_BAG); } private: template <class T> friend class backindex_bag_t; static const size_t NOT_IN_A_BAG = std::numeric_limits<size_t>::max(); // The item's index into a (specific) backindex_bag_t, or NOT_IN_A_BAG if it // doesn't belong to the backindex_bag_t. size_t index_; #ifndef NDEBUG // RSI: Remove this? void *owner_; #endif DISABLE_COPYING(backindex_bag_index_t); }; // A bag of elements that it _does not own_. template <class T> class backindex_bag_t { public: typedef backindex_bag_index_t *(*backindex_bag_index_accessor_t)(T); explicit backindex_bag_t(backindex_bag_index_accessor_t accessor) : accessor_(accessor) { debugf("bag %p create\n", this); } ~backindex_bag_t() { debugf("bag %p destroy\n", this); // Another way to implement this would be to simply remove all its elements. guarantee(vector_.size() == 0); } // Retruns true if the potential element of this container is in fact an element // of this container. The idea behind this function is that some value of type T // could be a member of one of several backindex_bag_t's (or none). We see if // it's a memory of this one. bool has_element(T potential_element) const { const backindex_bag_index_t *const backindex = accessor_(potential_element); bool ret = backindex->index_ < vector_.size() && vector_[backindex->index_] == potential_element; debugf("bag %p has_element index %p (index_ = %zu, ret = %d)\n", this, backindex, backindex->index_, static_cast<int>(ret)); rassert(!ret || backindex->owner_ == this); return ret; } // Removes the element from the bag. void remove(T element) { backindex_bag_index_t *const backindex = accessor_(element); debugf("bag %p remove index %p (index_ = %zu)\n", this, backindex, backindex->index_); rassert(backindex->index_ != backindex_bag_index_t::NOT_IN_A_BAG); rassert(backindex->owner_ == this); guarantee(backindex->index_ < vector_.size(), "early index has wrong value: index=%zu, size=%zu", backindex->index_, vector_.size()); const size_t index = backindex->index_; // Move the element in the last position to the removed element's position. // The code here feels weird when back_element == element (i.e. when // backindex->index_ == back_element_backindex->index_) but it works (I // hope). const T back_element = vector_.back(); backindex_bag_index_t *const back_element_backindex = accessor_(back_element); debugf("bag %p remove.. move index %p (index_ = %zu) from %zu to new index_ = %zu\n", this, back_element_backindex, back_element_backindex->index_, vector_.size() - 1, index); rassert(back_element_backindex->owner_ == this); rassert(back_element_backindex->index_ == vector_.size() - 1, "bag %p: index %p has wrong value: index_ = %zu, size = %zu", this, back_element_backindex, back_element_backindex->index_, vector_.size()); back_element_backindex->index_ = index; vector_[index] = back_element; vector_.pop_back(); backindex->index_ = backindex_bag_index_t::NOT_IN_A_BAG; #ifndef NDEBUG backindex->owner_ = NULL; #endif } // Adds the element to the bag. void add(T element) { backindex_bag_index_t *const backindex = accessor_(element); rassert(backindex->owner_ == NULL, "bag %p, backindex = %p", this, backindex); guarantee(backindex->index_ == backindex_bag_index_t::NOT_IN_A_BAG, "bag %p, backindex = %p", this, backindex); backindex->index_ = vector_.size(); debugf("bag %p add index %p (set index_ = %zu)\n", this, backindex, backindex->index_); #ifndef NDEBUG backindex->owner_ = this; #endif vector_.push_back(element); } size_t size() const { return vector_.size(); } // Accesses an element by index. This is called "access random" because // hopefully the index was randomly generated. There are no guarantees about the // ordering of elements in this bag. T access_random(size_t index) const { rassert(index != backindex_bag_index_t::NOT_IN_A_BAG); guarantee(index < vector_.size()); return vector_[index]; } private: const backindex_bag_index_accessor_t accessor_; // RSP: Huge block size, shitty data structure for a bag. segmented_vector_t<T> vector_; DISABLE_COPYING(backindex_bag_t); }; #endif // CONTAINERS_BACKINDEX_BAG_HPP_ <|endoftext|>
<commit_before>#include "pairwise_clustering.h" using namespace Pairwise; void Clustering::initialize(ExpressionMatrix* input) { // pre-allocate workspace _workLabels.resize(input->sampleSize()); } qint8 Clustering::compute( const QVector<Vector2>& X, int numSamples, QVector<qint8>& labels, int minSamples, qint8 minClusters, qint8 maxClusters, Criterion criterion, bool removePreOutliers, bool removePostOutliers) { // remove pre-clustering outliers if ( removePreOutliers ) { markOutliers(X, numSamples, 0, labels, 0, -7); markOutliers(X, numSamples, 1, labels, 0, -7); } // perform clustering only if there are enough samples qint8 bestK = 0; if ( numSamples >= minSamples ) { float bestValue = INFINITY; for ( qint8 K = minClusters; K <= maxClusters; ++K ) { // run each clustering model bool success = fit(X, numSamples, K, _workLabels); if ( !success ) { continue; } // evaluate model float value = INFINITY; switch (criterion) { case Criterion::AIC: value = computeAIC(K, 2, logLikelihood()); break; case Criterion::BIC: value = computeBIC(K, 2, logLikelihood(), numSamples); break; case Criterion::ICL: value = computeICL(K, 2, logLikelihood(), numSamples, entropy()); break; } // save the best model if ( value < bestValue ) { bestK = K; bestValue = value; for ( int i = 0, j = 0; i < numSamples; ++i ) { if ( labels[i] >= 0 ) { labels[i] = _workLabels[j]; ++j; } } } } } if ( bestK > 1 ) { // remove post-clustering outliers if ( removePostOutliers ) { for ( qint8 k = 0; k < bestK; ++k ) { markOutliers(X, numSamples, 0, labels, k, -8); markOutliers(X, numSamples, 1, labels, k, -8); } } } return bestK; } void Clustering::markOutliers(const QVector<Vector2>& X, int N, int j, QVector<qint8>& labels, qint8 cluster, qint8 marker) { // compute x_sorted = X[:, j], filtered and sorted QVector<float> x_sorted; x_sorted.reserve(N); for ( int i = 0; i < N; i++ ) { if ( labels[i] == cluster || labels[i] == marker ) { x_sorted.append(X[i].s[j]); } } if ( x_sorted.size() == 0 ) { return; } std::sort(x_sorted.begin(), x_sorted.end()); // compute quartiles, interquartile range, upper and lower bounds const int n = x_sorted.size(); float Q1 = x_sorted[n * 1 / 4]; float Q3 = x_sorted[n * 3 / 4]; float T_min = Q1 - 1.5f * (Q3 - Q1); float T_max = Q3 + 1.5f * (Q3 - Q1); // mark outliers for ( int i = 0; i < N; ++i ) { if ( labels[i] == cluster && (X[i].s[j] < T_min || T_max < X[i].s[j]) ) { labels[i] = marker; } } } float Clustering::computeAIC(int K, int D, float logL) { int p = K * (1 + D + D * D); return 2 * p - 2 * logL; } float Clustering::computeBIC(int K, int D, float logL, int N) { int p = K * (1 + D + D * D); return log(N) * p - 2 * logL; } float Clustering::computeICL(int K, int D, float logL, int N, float E) { int p = K * (1 + D + D * D); return log(N) * p - 2 * logL - 2 * E; } <commit_msg>Added comments<commit_after>#include "pairwise_clustering.h" using namespace Pairwise; void Clustering::initialize(ExpressionMatrix* input) { // pre-allocate workspace _workLabels.resize(input->sampleSize()); } /*! * Compute clusters for a given dataset. Several clustering models, each one * having a different number of clusters, are fit to the data and the model * with the best criterion value is selected. * * Note that the dataset contains only those samples which were not removed * by pre-processing, while the labels contains all samples from the original * expression matrix. * * @param X * @param numSamples * @param labels * @param minSamples * @param minSamples * @param minClusters * @param maxClusters * @param criterion * @param removePreOutliers * @param removePostOutliers */ qint8 Clustering::compute( const QVector<Vector2>& X, int numSamples, QVector<qint8>& labels, int minSamples, qint8 minClusters, qint8 maxClusters, Criterion criterion, bool removePreOutliers, bool removePostOutliers) { // remove pre-clustering outliers if ( removePreOutliers ) { markOutliers(X, numSamples, 0, labels, 0, -7); markOutliers(X, numSamples, 1, labels, 0, -7); } // perform clustering only if there are enough samples qint8 bestK = 0; if ( numSamples >= minSamples ) { float bestValue = INFINITY; for ( qint8 K = minClusters; K <= maxClusters; ++K ) { // run each clustering model bool success = fit(X, numSamples, K, _workLabels); if ( !success ) { continue; } // evaluate model float value = INFINITY; switch (criterion) { case Criterion::AIC: value = computeAIC(K, 2, logLikelihood()); break; case Criterion::BIC: value = computeBIC(K, 2, logLikelihood(), numSamples); break; case Criterion::ICL: value = computeICL(K, 2, logLikelihood(), numSamples, entropy()); break; } // save the best model if ( value < bestValue ) { bestK = K; bestValue = value; for ( int i = 0, j = 0; i < numSamples; ++i ) { if ( labels[i] >= 0 ) { labels[i] = _workLabels[j]; ++j; } } } } } if ( bestK > 1 ) { // remove post-clustering outliers if ( removePostOutliers ) { for ( qint8 k = 0; k < bestK; ++k ) { markOutliers(X, numSamples, 0, labels, k, -8); markOutliers(X, numSamples, 1, labels, k, -8); } } } return bestK; } void Clustering::markOutliers(const QVector<Vector2>& X, int N, int j, QVector<qint8>& labels, qint8 cluster, qint8 marker) { // compute x_sorted = X[:, j], filtered and sorted QVector<float> x_sorted; x_sorted.reserve(N); for ( int i = 0; i < N; i++ ) { if ( labels[i] == cluster || labels[i] == marker ) { x_sorted.append(X[i].s[j]); } } if ( x_sorted.size() == 0 ) { return; } std::sort(x_sorted.begin(), x_sorted.end()); // compute quartiles, interquartile range, upper and lower bounds const int n = x_sorted.size(); float Q1 = x_sorted[n * 1 / 4]; float Q3 = x_sorted[n * 3 / 4]; float T_min = Q1 - 1.5f * (Q3 - Q1); float T_max = Q3 + 1.5f * (Q3 - Q1); // mark outliers for ( int i = 0; i < N; ++i ) { if ( labels[i] == cluster && (X[i].s[j] < T_min || T_max < X[i].s[j]) ) { labels[i] = marker; } } } float Clustering::computeAIC(int K, int D, float logL) { int p = K * (1 + D + D * D); return 2 * p - 2 * logL; } float Clustering::computeBIC(int K, int D, float logL, int N) { int p = K * (1 + D + D * D); return log(N) * p - 2 * logL; } float Clustering::computeICL(int K, int D, float logL, int N, float E) { int p = K * (1 + D + D * D); return log(N) * p - 2 * logL - 2 * E; } <|endoftext|>
<commit_before>#include "cmm_thread.h" #include "debug.h" #include <stdexcept> #include <pthread.h> #include <assert.h> #include "pthread_util.h" #include <algorithm> #include <functional> using std::for_each; using std::bind2nd; using std::ptr_fun; pthread_key_t thread_name_key; static pthread_once_t key_once = PTHREAD_ONCE_INIT; pthread_mutex_t CMMThread::joinable_lock = PTHREAD_MUTEX_INITIALIZER; std::set<pthread_t> CMMThread::joinable_threads; void ThreadCleanup(void * arg) { CMMThread *thread = (CMMThread *)arg; assert(thread); pthread_mutex_lock(&thread->starter_mutex); thread->running = false; pthread_mutex_unlock(&thread->starter_mutex); { PthreadScopedLock lock(&CMMThread::joinable_lock); CMMThread::joinable_threads.erase(thread->tid); } thread->Finish(); } static void delete_name_string(void *arg) { char *name_str = (char*)arg; delete [] name_str; } static void make_key() { (void)pthread_key_create(&thread_name_key, delete_name_string); pthread_setspecific(thread_name_key, NULL); } void set_thread_name(const char *name) { (void) pthread_once(&key_once, make_key); assert(name); char *old_name = (char*)pthread_getspecific(thread_name_key); delete [] old_name; char *name_str = new char[MAX_NAME_LEN+1]; memset(name_str, 0, MAX_NAME_LEN+1); strncpy(name_str, name, MAX_NAME_LEN); pthread_setspecific(thread_name_key, name_str); } char * get_thread_name() { (void) pthread_once(&key_once, make_key); char * name_str = (char*)pthread_getspecific(thread_name_key); if (!name_str) { char *name = new char[12]; sprintf(name, "%08lx", pthread_self()); pthread_setspecific(thread_name_key, name); name_str = name; } return name_str; } void * ThreadFn(void * arg) { pthread_cleanup_push(ThreadCleanup, arg); (void)get_thread_name(); CMMThread *thread = (CMMThread*)arg; assert(thread); try { pthread_mutex_lock(&thread->starter_mutex); thread->running = true; pthread_cond_signal(&thread->starter_cv); pthread_mutex_unlock(&thread->starter_mutex); thread->Run(); dbgprintf("Thread %08x exited normally.\n", pthread_self()); } catch(const std::exception& e) { dbgprintf("Thread %08x exited: %s\n", pthread_self(), e.what()); } catch(const CMMThreadFinish& e) { dbgprintf("Thread %08x was cancelled via exception.\n", pthread_self()); } pthread_cleanup_pop(1); return NULL; } int CMMThread::start() { pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setstacksize(&attr, 1024*1024); { PthreadScopedLock lock(&joinable_lock); int rc = pthread_create(&tid, &attr, ThreadFn, this); if (rc != 0) { dbgprintf("Failed to create thread! rc=%d\n", rc); return rc; } joinable_threads.insert(tid); } pthread_mutex_lock(&starter_mutex); while (!running) { pthread_cond_wait(&starter_cv, &starter_mutex); } pthread_mutex_unlock(&starter_mutex); return 0; } CMMThread::CMMThread() : tid(0), running(false) { pthread_mutex_init(&starter_mutex, NULL); pthread_cond_init(&starter_cv, NULL); } CMMThread::~CMMThread() { pthread_mutex_destroy(&starter_mutex); pthread_cond_destroy(&starter_cv); } void CMMThread::stop() { PthreadScopedLock lock(&starter_mutex); if (running) { lock.release(); if (pthread_cancel(tid) == 0) { pthread_join(tid, NULL); } } } void CMMThread::join() { { PthreadScopedLock lock(&starter_mutex); if (running) { lock.release(); pthread_join(tid, NULL); } } PthreadScopedLock j_lock(&joinable_lock); joinable_threads.erase(tid); } void CMMThread::detach() { assert(tid == pthread_self()); { PthreadScopedLock j_lock(&joinable_lock); joinable_threads.erase(tid); } pthread_detach(tid); } void CMMThread::join_all() { std::set<pthread_t> joinable_threads_private; { PthreadScopedLock lock(&joinable_lock); joinable_threads_private = joinable_threads; joinable_threads.clear(); } void **result = NULL; for (std::set<pthread_t>::iterator it = joinable_threads_private.begin(); it != joinable_threads_private.end(); it++) { dbgprintf("pthread_join to thread %d\n", *it); pthread_join(*it, result); } } <commit_msg>Trying to figure out why CMMThreads are getting accessed after deletion.<commit_after>#include "cmm_thread.h" #include "debug.h" #include <stdexcept> #include <pthread.h> #include <assert.h> #include "pthread_util.h" #include <algorithm> #include <functional> using std::for_each; using std::bind2nd; using std::ptr_fun; pthread_key_t thread_name_key; static pthread_once_t key_once = PTHREAD_ONCE_INIT; pthread_mutex_t CMMThread::joinable_lock = PTHREAD_MUTEX_INITIALIZER; std::set<pthread_t> CMMThread::joinable_threads; void ThreadCleanup(void * arg) { CMMThread *thread = (CMMThread *)arg; assert(thread); pthread_mutex_lock(&thread->starter_mutex); thread->running = false; pthread_mutex_unlock(&thread->starter_mutex); { PthreadScopedLock lock(&CMMThread::joinable_lock); CMMThread::joinable_threads.erase(thread->tid); } thread->Finish(); } static void delete_name_string(void *arg) { char *name_str = (char*)arg; delete [] name_str; } static void make_key() { (void)pthread_key_create(&thread_name_key, delete_name_string); pthread_setspecific(thread_name_key, NULL); } void set_thread_name(const char *name) { (void) pthread_once(&key_once, make_key); assert(name); char *old_name = (char*)pthread_getspecific(thread_name_key); delete [] old_name; char *name_str = new char[MAX_NAME_LEN+1]; memset(name_str, 0, MAX_NAME_LEN+1); strncpy(name_str, name, MAX_NAME_LEN); pthread_setspecific(thread_name_key, name_str); } char * get_thread_name() { (void) pthread_once(&key_once, make_key); char * name_str = (char*)pthread_getspecific(thread_name_key); if (!name_str) { char *name = new char[12]; sprintf(name, "%08lx", pthread_self()); pthread_setspecific(thread_name_key, name); name_str = name; } return name_str; } void * ThreadFn(void * arg) { pthread_cleanup_push(ThreadCleanup, arg); (void)get_thread_name(); CMMThread *thread = (CMMThread*)arg; assert(thread); try { pthread_mutex_lock(&thread->starter_mutex); thread->running = true; pthread_cond_signal(&thread->starter_cv); pthread_mutex_unlock(&thread->starter_mutex); thread->Run(); dbgprintf("Thread %08x exited normally.\n", pthread_self()); } catch(const std::exception& e) { dbgprintf("Thread %08x exited: %s\n", pthread_self(), e.what()); } catch(const CMMThreadFinish& e) { dbgprintf("Thread %08x was cancelled via exception.\n", pthread_self()); } pthread_cleanup_pop(1); return NULL; } int CMMThread::start() { pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setstacksize(&attr, 1024*1024); { PthreadScopedLock lock(&joinable_lock); int rc = pthread_create(&tid, &attr, ThreadFn, this); if (rc != 0) { dbgprintf("Failed to create thread! rc=%d\n", rc); return rc; } joinable_threads.insert(tid); } pthread_mutex_lock(&starter_mutex); while (!running) { pthread_cond_wait(&starter_cv, &starter_mutex); } pthread_mutex_unlock(&starter_mutex); return 0; } CMMThread::CMMThread() : tid(0), running(false) { pthread_mutex_init(&starter_mutex, NULL); pthread_cond_init(&starter_cv, NULL); } CMMThread::~CMMThread() { dbgprintf("CMMThread %p is being destroyed\n", this); pthread_mutex_destroy(&starter_mutex); pthread_cond_destroy(&starter_cv); } void CMMThread::stop() { PthreadScopedLock lock(&starter_mutex); if (running) { lock.release(); if (pthread_cancel(tid) == 0) { pthread_join(tid, NULL); } } } void CMMThread::join() { { PthreadScopedLock lock(&starter_mutex); if (running) { lock.release(); pthread_join(tid, NULL); } } PthreadScopedLock j_lock(&joinable_lock); joinable_threads.erase(tid); } void CMMThread::detach() { assert(tid == pthread_self()); { PthreadScopedLock j_lock(&joinable_lock); joinable_threads.erase(tid); } pthread_detach(tid); } void CMMThread::join_all() { std::set<pthread_t> joinable_threads_private; { PthreadScopedLock lock(&joinable_lock); joinable_threads_private = joinable_threads; joinable_threads.clear(); } void **result = NULL; for (std::set<pthread_t>::iterator it = joinable_threads_private.begin(); it != joinable_threads_private.end(); it++) { dbgprintf("pthread_join to thread %d\n", *it); pthread_join(*it, result); } } <|endoftext|>
<commit_before>#include <vector> #include <algorithm> #include <iostream> #include <cassert> #include "cnfformula.h" #include "structs.h" /** creates a CNF formula with the given clauses and assignments, with default empty clause and empty assignment vectors */ CNFFormula::CNFFormula(unsigned int n, int k, const std::vector<CNFClause> & clauses, const std::vector<assignment> assignments):n(n), k(k), clauses(clauses),unchecked_assignments(assignments){ } /** solves a CNF formula by brute force - going to all 2^n assignments. assigns satisfying_assignments to contain the satisfying assignments and sets was_solved to true. if was_solved is already set to true then we do not re-solve.*/ void CNFFormula::bruteforce_solve_sat(std::vector<short> partial){ // we don't want to re-solve if it has already been solved if(was_solved){ return; } if(partial.size() == 0){ partial = std::vector<short>(n, -1); } std::vector<short> bitstring; //we enumerate all the bitstrings by taking all permutations of strings //that have i bits to 1 for(unsigned int i = 0; i<=n; i++){ bitstring = std::vector<short>(n, 0); for(unsigned int j = 0; j<i; j++){ bitstring[j] = 1; } do { std::vector<short> bitstringwithpartial(n); for(int j = 0; j<n; j++){ if(partial[j] != -1){ bitstringwithpartial[j] = partial[j]; } else{ bitstringwithpartial[j] = bitstring[j]; } } if(check_bitstring(bitstringwithpartial)){ satisfying_assignments.push_back(bitstringwithpartial); } } while(std::prev_permutation(bitstring.begin(), bitstring.end())); } was_solved = true; } /** checks whether a bitstring solves a CNF formula @param bitstring the candidate bit string @return true if the bitstring satisfies the formula, false otw */ bool CNFFormula::check_bitstring(const std::vector<short> & bitstring) const { for(const auto & clause : clauses){ if(!clause.check_bitstring(bitstring)){ return false; } } return true; } /** adds a clause to the formula @param clause the clause to add */ void CNFFormula::add_clause(const CNFClause & clause){ clauses.push_back(clause); } std::ostream& operator<<(std::ostream& out, const CNFFormula & formula){ for(const auto & clause : formula.clauses){ for(const auto & literal : clause){ if(literal.value == 0){ out << "~"; } out << "x" << literal.variable+1 << ","; } out << std::endl; } if(formula.was_solved){ out << "Assignments:" << std::endl; for(const auto & assig:formula.satisfying_assignments){ int var = 1; for(const auto & lit : assig){ out << "x" << var << "=" << lit << ","; var++; } out << std::endl; } } return out; } /** does the assignment passed in parameter, does not modify the current formula @param assg the assignment to make - 0 or 1 to corresponding variables, -1 for unassigned variables @ return a new CNFFormula with the assignment made */ CNFFormula CNFFormula::make_assignment(const assignment & assg) const { // assert(assg.size() == n); CNFFormula formula(n, k); for(const auto & clause : clauses){ bool addit = true; for(const auto & lit : clause){ //if the variable is not set in the assignment then nothing changes if(assg[lit.variable] == -1){ continue; } // if a literal has the right value then the clause is satisfied and we do not add it if(lit.value == assg[lit.variable]){ addit = false; continue; } //otherwise we create a new clause without the (unsatisfied) literal and we add it //(but not the original clause) else{ CNFClause newclause; for(auto lit1 : clause){ if(lit1.variable != lit.variable){ newclause.add_literal(lit1); } } formula.add_clause(newclause); addit = false; } } //if we still need to add that clause then we do it if(addit){ formula.add_clause(clause); } } return formula; } unsigned int CNFFormula::get_n() const{ return n; } bool CNFFormula::is_unsat() const{ for(auto const & clause : clauses){ if(clause.size() == 0){ return true; } } return false; } int CNFFormula::get_forced_value(int variable) const{ for(auto const & clause : clauses){ if(clause.size() == 1){ if(clause.getliteral(0).variable == variable){ return clause.getliteral(0).value; } } } return -1; } int CNFFormula::get_m() const{ return clauses.size(); } /** bruteforce solves to check if a variable is frozen. quite ugly, but since PPZ is slow as a tetraplegic turtle anyway... */ bool CNFFormula::is_frozen(int variable, std::vector<short> partial){ bruteforce_solve_sat(partial); //if there is no satisfying assignment, the variable has the same value in all sat. assg. if(satisfying_assignments.size() == 0){ return true; } short value = satisfying_assignments[0][variable]; for(auto const & assig : satisfying_assignments){ if(assig[variable] != value){ return false; } } return true; } <commit_msg>removed a signed/unsigned warning<commit_after>#include <vector> #include <algorithm> #include <iostream> #include <cassert> #include "cnfformula.h" #include "structs.h" /** creates a CNF formula with the given clauses and assignments, with default empty clause and empty assignment vectors */ CNFFormula::CNFFormula(unsigned int n, int k, const std::vector<CNFClause> & clauses, const std::vector<assignment> assignments):n(n), k(k), clauses(clauses),unchecked_assignments(assignments){ } /** solves a CNF formula by brute force - going to all 2^n assignments. assigns satisfying_assignments to contain the satisfying assignments and sets was_solved to true. if was_solved is already set to true then we do not re-solve.*/ void CNFFormula::bruteforce_solve_sat(std::vector<short> partial){ // we don't want to re-solve if it has already been solved if(was_solved){ return; } if(partial.size() == 0){ partial = std::vector<short>(n, -1); } std::vector<short> bitstring; //we enumerate all the bitstrings by taking all permutations of strings //that have i bits to 1 for(unsigned int i = 0; i<=n; i++){ bitstring = std::vector<short>(n, 0); for(unsigned int j = 0; j<i; j++){ bitstring[j] = 1; } do { std::vector<short> bitstringwithpartial(n); for(unsigned int j = 0; j<n; j++){ if(partial[j] != -1){ bitstringwithpartial[j] = partial[j]; } else{ bitstringwithpartial[j] = bitstring[j]; } } if(check_bitstring(bitstringwithpartial)){ satisfying_assignments.push_back(bitstringwithpartial); } } while(std::prev_permutation(bitstring.begin(), bitstring.end())); } was_solved = true; } /** checks whether a bitstring solves a CNF formula @param bitstring the candidate bit string @return true if the bitstring satisfies the formula, false otw */ bool CNFFormula::check_bitstring(const std::vector<short> & bitstring) const { for(const auto & clause : clauses){ if(!clause.check_bitstring(bitstring)){ return false; } } return true; } /** adds a clause to the formula @param clause the clause to add */ void CNFFormula::add_clause(const CNFClause & clause){ clauses.push_back(clause); } std::ostream& operator<<(std::ostream& out, const CNFFormula & formula){ for(const auto & clause : formula.clauses){ for(const auto & literal : clause){ if(literal.value == 0){ out << "~"; } out << "x" << literal.variable+1 << ","; } out << std::endl; } if(formula.was_solved){ out << "Assignments:" << std::endl; for(const auto & assig:formula.satisfying_assignments){ int var = 1; for(const auto & lit : assig){ out << "x" << var << "=" << lit << ","; var++; } out << std::endl; } } return out; } /** does the assignment passed in parameter, does not modify the current formula @param assg the assignment to make - 0 or 1 to corresponding variables, -1 for unassigned variables @ return a new CNFFormula with the assignment made */ CNFFormula CNFFormula::make_assignment(const assignment & assg) const { // assert(assg.size() == n); CNFFormula formula(n, k); for(const auto & clause : clauses){ bool addit = true; for(const auto & lit : clause){ //if the variable is not set in the assignment then nothing changes if(assg[lit.variable] == -1){ continue; } // if a literal has the right value then the clause is satisfied and we do not add it if(lit.value == assg[lit.variable]){ addit = false; continue; } //otherwise we create a new clause without the (unsatisfied) literal and we add it //(but not the original clause) else{ CNFClause newclause; for(auto lit1 : clause){ if(lit1.variable != lit.variable){ newclause.add_literal(lit1); } } formula.add_clause(newclause); addit = false; } } //if we still need to add that clause then we do it if(addit){ formula.add_clause(clause); } } return formula; } unsigned int CNFFormula::get_n() const{ return n; } bool CNFFormula::is_unsat() const{ for(auto const & clause : clauses){ if(clause.size() == 0){ return true; } } return false; } int CNFFormula::get_forced_value(int variable) const{ for(auto const & clause : clauses){ if(clause.size() == 1){ if(clause.getliteral(0).variable == variable){ return clause.getliteral(0).value; } } } return -1; } int CNFFormula::get_m() const{ return clauses.size(); } /** bruteforce solves to check if a variable is frozen. quite ugly, but since PPZ is slow as a tetraplegic turtle anyway... */ bool CNFFormula::is_frozen(int variable, std::vector<short> partial){ bruteforce_solve_sat(partial); //if there is no satisfying assignment, the variable has the same value in all sat. assg. if(satisfying_assignments.size() == 0){ return true; } short value = satisfying_assignments[0][variable]; for(auto const & assig : satisfying_assignments){ if(assig[variable] != value){ return false; } } return true; } <|endoftext|>
<commit_before>// Copyright (c) 2020 by Robert Bosch GmbH. All rights reserved. // Copyright (c) 2021 - 2022 by Apex.AI 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. // // SPDX-License-Identifier: Apache-2.0 #include "iceoryx_posh/internal/popo/ports/server_port_roudi.hpp" namespace iox { namespace popo { ServerPortRouDi::ServerPortRouDi(MemberType_t& serverPortData) noexcept : BasePort(&serverPortData) , m_chunkSender(&getMembers()->m_chunkSenderData) , m_chunkReceiver(&getMembers()->m_chunkReceiverData) { } const ServerPortRouDi::MemberType_t* ServerPortRouDi::getMembers() const noexcept { return reinterpret_cast<const MemberType_t*>(BasePort::getMembers()); } ServerPortRouDi::MemberType_t* ServerPortRouDi::getMembers() noexcept { return reinterpret_cast<MemberType_t*>(BasePort::getMembers()); } ConsumerTooSlowPolicy ServerPortRouDi::getClientTooSlowPolicy() const noexcept { return static_cast<ConsumerTooSlowPolicy>(getMembers()->m_chunkSenderData.m_subscriberTooSlowPolicy); } cxx::optional<capro::CaproMessage> ServerPortRouDi::tryGetCaProMessage() noexcept { // get offer state request from user side const auto offeringRequested = getMembers()->m_offeringRequested.load(std::memory_order_relaxed); const auto isOffered = getMembers()->m_offered.load(std::memory_order_relaxed); if (isOffered) { if (!offeringRequested) { capro::CaproMessage caproMessage(capro::CaproMessageType::STOP_OFFER, this->getCaProServiceDescription()); return dispatchCaProMessageAndGetPossibleResponse(caproMessage); } } else { if (offeringRequested) { capro::CaproMessage caproMessage(capro::CaproMessageType::OFFER, this->getCaProServiceDescription()); return dispatchCaProMessageAndGetPossibleResponse(caproMessage); } } // nothing to change return cxx::nullopt; } cxx::optional<capro::CaproMessage> ServerPortRouDi::dispatchCaProMessageAndGetPossibleResponse(const capro::CaproMessage& caProMessage) noexcept { const auto isOffered = getMembers()->m_offered.load(std::memory_order_relaxed); return isOffered ? handleCaProMessageForStateOffered(caProMessage) : handleCaProMessageForStateNotOffered(caProMessage); } void ServerPortRouDi::handleCaProProtocolViolation(const capro::CaproMessageType messageType) const noexcept { // this shouldn't be reached LogFatal() << "CaPro Protocol Violation! Got '" << messageType << "' with offer state '" << (getMembers()->m_offered ? "OFFERED" : "NOT OFFERED") << "'!"; errorHandler(Error::kPOPO__CAPRO_PROTOCOL_ERROR, nullptr, ErrorLevel::SEVERE); } cxx::optional<capro::CaproMessage> ServerPortRouDi::handleCaProMessageForStateOffered(const capro::CaproMessage& caProMessage) noexcept { capro::CaproMessage responseMessage{capro::CaproMessageType::NACK, this->getCaProServiceDescription()}; switch (caProMessage.m_type) { case capro::CaproMessageType::STOP_OFFER: getMembers()->m_offered.store(false, std::memory_order_relaxed); m_chunkSender.removeAllQueues(); return caProMessage; case capro::CaproMessageType::OFFER: return responseMessage; case capro::CaproMessageType::CONNECT: if (caProMessage.m_chunkQueueData == nullptr) { LogWarn() << "No client response queue passed to server"; errorHandler(Error::kPOPO__SERVER_PORT_NO_CLIENT_RESPONSE_QUEUE_TO_CONNECT, nullptr, ErrorLevel::MODERATE); } else { m_chunkSender .tryAddQueue(static_cast<ClientChunkQueueData_t*>(caProMessage.m_chunkQueueData), caProMessage.m_historyCapacity) .and_then([this, &responseMessage]() { responseMessage.m_type = capro::CaproMessageType::ACK; responseMessage.m_chunkQueueData = static_cast<void*>(&getMembers()->m_chunkReceiverData); responseMessage.m_historyCapacity = 0; }); } return responseMessage; case capro::CaproMessageType::DISCONNECT: m_chunkSender.tryRemoveQueue(static_cast<ClientChunkQueueData_t*>(caProMessage.m_chunkQueueData)) .and_then([&responseMessage]() { responseMessage.m_type = capro::CaproMessageType::ACK; }); return responseMessage; default: break; } handleCaProProtocolViolation(caProMessage.m_type); return cxx::nullopt; } cxx::optional<capro::CaproMessage> ServerPortRouDi::handleCaProMessageForStateNotOffered(const capro::CaproMessage& caProMessage) noexcept { switch (caProMessage.m_type) { case capro::CaproMessageType::OFFER: getMembers()->m_offered.store(true, std::memory_order_relaxed); return caProMessage; case capro::CaproMessageType::STOP_OFFER: IOX_FALLTHROUGH; case capro::CaproMessageType::CONNECT: IOX_FALLTHROUGH; case capro::CaproMessageType::DISCONNECT: return capro::CaproMessage(capro::CaproMessageType::NACK, this->getCaProServiceDescription()); default: handleCaProProtocolViolation(caProMessage.m_type); return cxx::nullopt; } } void ServerPortRouDi::releaseAllChunks() noexcept { m_chunkSender.releaseAll(); m_chunkReceiver.releaseAll(); } } // namespace popo } // namespace iox <commit_msg>iox-#27 Move capro protocol violation out of switch statement<commit_after>// Copyright (c) 2020 by Robert Bosch GmbH. All rights reserved. // Copyright (c) 2021 - 2022 by Apex.AI 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. // // SPDX-License-Identifier: Apache-2.0 #include "iceoryx_posh/internal/popo/ports/server_port_roudi.hpp" namespace iox { namespace popo { ServerPortRouDi::ServerPortRouDi(MemberType_t& serverPortData) noexcept : BasePort(&serverPortData) , m_chunkSender(&getMembers()->m_chunkSenderData) , m_chunkReceiver(&getMembers()->m_chunkReceiverData) { } const ServerPortRouDi::MemberType_t* ServerPortRouDi::getMembers() const noexcept { return reinterpret_cast<const MemberType_t*>(BasePort::getMembers()); } ServerPortRouDi::MemberType_t* ServerPortRouDi::getMembers() noexcept { return reinterpret_cast<MemberType_t*>(BasePort::getMembers()); } ConsumerTooSlowPolicy ServerPortRouDi::getClientTooSlowPolicy() const noexcept { return static_cast<ConsumerTooSlowPolicy>(getMembers()->m_chunkSenderData.m_subscriberTooSlowPolicy); } cxx::optional<capro::CaproMessage> ServerPortRouDi::tryGetCaProMessage() noexcept { // get offer state request from user side const auto offeringRequested = getMembers()->m_offeringRequested.load(std::memory_order_relaxed); const auto isOffered = getMembers()->m_offered.load(std::memory_order_relaxed); if (isOffered) { if (!offeringRequested) { capro::CaproMessage caproMessage(capro::CaproMessageType::STOP_OFFER, this->getCaProServiceDescription()); return dispatchCaProMessageAndGetPossibleResponse(caproMessage); } } else { if (offeringRequested) { capro::CaproMessage caproMessage(capro::CaproMessageType::OFFER, this->getCaProServiceDescription()); return dispatchCaProMessageAndGetPossibleResponse(caproMessage); } } // nothing to change return cxx::nullopt; } cxx::optional<capro::CaproMessage> ServerPortRouDi::dispatchCaProMessageAndGetPossibleResponse(const capro::CaproMessage& caProMessage) noexcept { const auto isOffered = getMembers()->m_offered.load(std::memory_order_relaxed); return isOffered ? handleCaProMessageForStateOffered(caProMessage) : handleCaProMessageForStateNotOffered(caProMessage); } void ServerPortRouDi::handleCaProProtocolViolation(const capro::CaproMessageType messageType) const noexcept { // this shouldn't be reached LogFatal() << "CaPro Protocol Violation! Got '" << messageType << "' with offer state '" << (getMembers()->m_offered ? "OFFERED" : "NOT OFFERED") << "'!"; errorHandler(Error::kPOPO__CAPRO_PROTOCOL_ERROR, nullptr, ErrorLevel::SEVERE); } cxx::optional<capro::CaproMessage> ServerPortRouDi::handleCaProMessageForStateOffered(const capro::CaproMessage& caProMessage) noexcept { capro::CaproMessage responseMessage{capro::CaproMessageType::NACK, this->getCaProServiceDescription()}; switch (caProMessage.m_type) { case capro::CaproMessageType::STOP_OFFER: getMembers()->m_offered.store(false, std::memory_order_relaxed); m_chunkSender.removeAllQueues(); return caProMessage; case capro::CaproMessageType::OFFER: return responseMessage; case capro::CaproMessageType::CONNECT: if (caProMessage.m_chunkQueueData == nullptr) { LogWarn() << "No client response queue passed to server"; errorHandler(Error::kPOPO__SERVER_PORT_NO_CLIENT_RESPONSE_QUEUE_TO_CONNECT, nullptr, ErrorLevel::MODERATE); } else { m_chunkSender .tryAddQueue(static_cast<ClientChunkQueueData_t*>(caProMessage.m_chunkQueueData), caProMessage.m_historyCapacity) .and_then([this, &responseMessage]() { responseMessage.m_type = capro::CaproMessageType::ACK; responseMessage.m_chunkQueueData = static_cast<void*>(&getMembers()->m_chunkReceiverData); responseMessage.m_historyCapacity = 0; }); } return responseMessage; case capro::CaproMessageType::DISCONNECT: m_chunkSender.tryRemoveQueue(static_cast<ClientChunkQueueData_t*>(caProMessage.m_chunkQueueData)) .and_then([&responseMessage]() { responseMessage.m_type = capro::CaproMessageType::ACK; }); return responseMessage; default: // leave switch statement and handle protocol violation break; } handleCaProProtocolViolation(caProMessage.m_type); return cxx::nullopt; } cxx::optional<capro::CaproMessage> ServerPortRouDi::handleCaProMessageForStateNotOffered(const capro::CaproMessage& caProMessage) noexcept { switch (caProMessage.m_type) { case capro::CaproMessageType::OFFER: getMembers()->m_offered.store(true, std::memory_order_relaxed); return caProMessage; case capro::CaproMessageType::STOP_OFFER: IOX_FALLTHROUGH; case capro::CaproMessageType::CONNECT: IOX_FALLTHROUGH; case capro::CaproMessageType::DISCONNECT: return capro::CaproMessage(capro::CaproMessageType::NACK, this->getCaProServiceDescription()); default: // leave switch statement and handle protocol violation break; } handleCaProProtocolViolation(caProMessage.m_type); return cxx::nullopt; } void ServerPortRouDi::releaseAllChunks() noexcept { m_chunkSender.releaseAll(); m_chunkReceiver.releaseAll(); } } // namespace popo } // namespace iox <|endoftext|>
<commit_before>// Copyright since 2016 : Evgenii Shatunov (github.com/FrankStain/jnipp) // Apache 2.0 License #pragma once namespace Jni { namespace Marshaling { inline void NativeTypeTraits<bool>::ToJava( const NativeType& source, JavaType& destination ) { destination = ( source )? JNI_TRUE : JNI_FALSE; }; inline void NativeTypeTraits<const char*>::ToJava( const NativeType& source, JavaType& destination ) { auto local_env = VirtualMachine::GetLocalEnvironment(); destination = local_env->NewStringUTF( source ); }; inline void NativeTypeTraits<const char16_t*>::ToJava( const NativeType& source, JavaType& destination ) { auto local_env = VirtualMachine::GetLocalEnvironment(); destination = local_env->NewString( reinterpret_cast<const jchar*>( source ), std::char_traits<char16_t>::length( source ) ); }; inline void NativeTypeTraits<std::string>::ToJava( const NativeType& source, JavaType& destination ) { NativeTypeTraits<const char*>::ToJava( source.c_str(), destination ); }; inline void NativeTypeTraits<std::u16string>::ToJava( const NativeType& source, JavaType& destination ) { NativeTypeTraits<const char16_t*>::ToJava( source.c_str(), destination ); }; inline void NativeTypeTraits<float>::ToJava( const NativeType& source, JavaType& destination ) { destination = source; }; inline void NativeTypeTraits<double>::ToJava( const NativeType& source, JavaType& destination ) { destination = source; }; inline void NativeTypeTraits<int8_t>::ToJava( const NativeType& source, JavaType& destination ) { destination = source; }; inline void NativeTypeTraits<char16_t>::ToJava( const NativeType& source, JavaType& destination ) { destination = source; }; inline void NativeTypeTraits<int16_t>::ToJava( const NativeType& source, JavaType& destination ) { destination = source; }; inline void NativeTypeTraits<int32_t>::ToJava( const NativeType& source, JavaType& destination ) { destination = source; }; inline void NativeTypeTraits<int64_t>::ToJava( const NativeType& source, JavaType& destination ) { destination = source; }; inline void NativeTypeTraits<uint8_t>::ToJava( const NativeType& source, JavaType& destination ) { destination = source; }; inline void NativeTypeTraits<uint16_t>::ToJava( const NativeType& source, JavaType& destination ) { destination = source; }; inline void NativeTypeTraits<uint32_t>::ToJava( const NativeType& source, JavaType& destination ) { destination = source; }; inline void NativeTypeTraits<uint64_t>::ToJava( const NativeType& source, JavaType& destination ) { destination = reinterpret_cast<const int64_t&>( source ); }; template< typename TNativeElementType, typename TAllocatorType > inline void NativeTypeTraits<std::vector<TNativeElementType, TAllocatorType>>::ToJava( const NativeType& source, JavaType& destination ) { }; }; }; <commit_msg>Native array translation function.<commit_after>// Copyright since 2016 : Evgenii Shatunov (github.com/FrankStain/jnipp) // Apache 2.0 License #pragma once namespace Jni { namespace Marshaling { inline void NativeTypeTraits<bool>::ToJava( const NativeType& source, JavaType& destination ) { destination = ( source )? JNI_TRUE : JNI_FALSE; }; inline void NativeTypeTraits<const char*>::ToJava( const NativeType& source, JavaType& destination ) { auto local_env = VirtualMachine::GetLocalEnvironment(); destination = local_env->NewStringUTF( source ); }; inline void NativeTypeTraits<const char16_t*>::ToJava( const NativeType& source, JavaType& destination ) { auto local_env = VirtualMachine::GetLocalEnvironment(); destination = local_env->NewString( reinterpret_cast<const jchar*>( source ), std::char_traits<char16_t>::length( source ) ); }; inline void NativeTypeTraits<std::string>::ToJava( const NativeType& source, JavaType& destination ) { NativeTypeTraits<const char*>::ToJava( source.c_str(), destination ); }; inline void NativeTypeTraits<std::u16string>::ToJava( const NativeType& source, JavaType& destination ) { NativeTypeTraits<const char16_t*>::ToJava( source.c_str(), destination ); }; inline void NativeTypeTraits<float>::ToJava( const NativeType& source, JavaType& destination ) { destination = source; }; inline void NativeTypeTraits<double>::ToJava( const NativeType& source, JavaType& destination ) { destination = source; }; inline void NativeTypeTraits<int8_t>::ToJava( const NativeType& source, JavaType& destination ) { destination = source; }; inline void NativeTypeTraits<char16_t>::ToJava( const NativeType& source, JavaType& destination ) { destination = source; }; inline void NativeTypeTraits<int16_t>::ToJava( const NativeType& source, JavaType& destination ) { destination = source; }; inline void NativeTypeTraits<int32_t>::ToJava( const NativeType& source, JavaType& destination ) { destination = source; }; inline void NativeTypeTraits<int64_t>::ToJava( const NativeType& source, JavaType& destination ) { destination = source; }; inline void NativeTypeTraits<uint8_t>::ToJava( const NativeType& source, JavaType& destination ) { destination = source; }; inline void NativeTypeTraits<uint16_t>::ToJava( const NativeType& source, JavaType& destination ) { destination = source; }; inline void NativeTypeTraits<uint32_t>::ToJava( const NativeType& source, JavaType& destination ) { destination = source; }; inline void NativeTypeTraits<uint64_t>::ToJava( const NativeType& source, JavaType& destination ) { destination = reinterpret_cast<const int64_t&>( source ); }; template< typename TNativeElementType, typename TAllocatorType > inline void NativeTypeTraits<std::vector<TNativeElementType, TAllocatorType>>::ToJava( const NativeType& source, JavaType& destination ) { using ElementTraits = NativeTypeTraits<TNativeElementType>; constexpr auto ARRAY_CONSTRUCT_HANDLER = ElementTraits::ARRAY_CONSTRUCT_HANDLER; auto local_env = VirtualMachine::GetLocalEnvironment(); if( ElementTraits::IS_PLAIN ) { constexpr auto ARRAY_ELEMENTS_ACQUIRE_HANDLER = ElementTraits::ARRAY_ELEMENTS_ACQUIRE_HANDLER; constexpr auto ARRAY_ELEMENTS_RELEASE_HANDLER = ElementTraits::ARRAY_ELEMENTS_RELEASE_HANDLER; destination = (local_env->*ARRAY_CONSTRUCT_HANDLER)( static_cast<jsize>( source.size() ) ); JNI_RETURN_IF( source.empty() ); auto array_elements = (local_env->*ARRAY_ELEMENTS_ACQUIRE_HANDLER)( source, nullptr ); JNI_RETURN_IF_E( array_elements == nullptr, , "Failed to read elements of array." ); std::transform( source.begin(), source.end(), array_elements, []( const TNativeElementType& stored_value ) { return Jni::Marshaling::ToJava<TNativeElementType>( stored_value ); } ); (local_env->*ARRAY_ELEMENTS_RELEASE_HANDLER)( source, array_elements, JNI_OK ); } else { }; }; }; }; <|endoftext|>
<commit_before>/* Copyright (C) 2003 MySQL AB 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 <signaldata/DictTabInfo.hpp> #include <ndb_limits.h> //static const SimpleProperties::SP2StructMapping DictTabInfo::TableMapping[] = { DTIMAPS(Table, TableName, TableName, 0, MAX_TAB_NAME_SIZE), DTIMAP(Table, TableId, TableId), DTIMAPS(Table, PrimaryTable, PrimaryTable, 0, MAX_TAB_NAME_SIZE), DTIMAP(Table, PrimaryTableId, PrimaryTableId), DTIMAP2(Table, TableLoggedFlag, TableLoggedFlag, 0, 1), DTIMAP2(Table, TableTemporaryFlag, TableTemporaryFlag, 0, 1), DTIMAP2(Table, TableKValue, TableKValue, 6, 6), DTIMAP2(Table, MinLoadFactor, MinLoadFactor, 0, 90), DTIMAP2(Table, MaxLoadFactor, MaxLoadFactor, 25, 110), DTIMAP2(Table, FragmentTypeVal, FragmentType, 0, 3), DTIMAP2(Table, TableTypeVal, TableType, 1, 3), DTIMAP(Table, NoOfKeyAttr, NoOfKeyAttr), DTIMAP2(Table, NoOfAttributes, NoOfAttributes, 1, MAX_ATTRIBUTES_IN_TABLE), DTIMAP(Table, NoOfNullable, NoOfNullable), DTIMAP2(Table, NoOfVariable, NoOfVariable, 0, 0), DTIMAP(Table, KeyLength, KeyLength), DTIMAP(Table, TableVersion, TableVersion), DTIMAP(Table, IndexState, IndexState), DTIMAP(Table, InsertTriggerId, InsertTriggerId), DTIMAP(Table, UpdateTriggerId, UpdateTriggerId), DTIMAP(Table, DeleteTriggerId, DeleteTriggerId), DTIMAP(Table, CustomTriggerId, CustomTriggerId), DTIMAP2(Table, FrmLen, FrmLen, 0, MAX_FRM_DATA_SIZE), DTIMAPB(Table, FrmData, FrmData, 0, MAX_FRM_DATA_SIZE, FrmLen), DTIMAP2(Table, FragmentCount, FragmentCount, 0, MAX_NDB_PARTITIONS), DTIMAP2(Table, ReplicaDataLen, ReplicaDataLen, 0, 2*MAX_FRAGMENT_DATA_BYTES), DTIMAPB(Table, ReplicaData, ReplicaData, 0, 2*MAX_FRAGMENT_DATA_BYTES, ReplicaDataLen), DTIMAP2(Table, FragmentDataLen, FragmentDataLen, 0, 6*MAX_NDB_PARTITIONS), DTIMAPB(Table, FragmentData, FragmentData, 0, 6*MAX_NDB_PARTITIONS, FragmentDataLen), DTIMAP2(Table, TablespaceDataLen, TablespaceDataLen, 0, 8*MAX_NDB_PARTITIONS), DTIMAPB(Table, TablespaceData, TablespaceData, 0, 8*MAX_NDB_PARTITIONS, TablespaceDataLen), DTIMAP2(Table, RangeListDataLen, RangeListDataLen, 0, 8*MAX_NDB_PARTITIONS), DTIMAPB(Table, RangeListData, RangeListData, 0, 8*MAX_NDB_PARTITIONS, RangeListDataLen), DTIMAP(Table, TablespaceId, TablespaceId), DTIMAP(Table, TablespaceVersion, TablespaceVersion), DTIMAP(Table, MaxRowsLow, MaxRowsLow), DTIMAP(Table, MaxRowsHigh, MaxRowsHigh), DTIMAP(Table, DefaultNoPartFlag, DefaultNoPartFlag), DTIMAP(Table, LinearHashFlag, LinearHashFlag), DTIMAP(Table, TablespaceVersion, TablespaceVersion), DTIMAP(Table, RowGCIFlag, RowGCIFlag), DTIMAP(Table, RowChecksumFlag, RowChecksumFlag), DTIMAP(Table, MaxRowsLow, MaxRowsLow), DTIMAP(Table, MaxRowsHigh, MaxRowsHigh), DTIMAP(Table, MinRowsLow, MinRowsLow), DTIMAP(Table, MinRowsHigh, MinRowsHigh), DTIBREAK(AttributeName) }; //static const Uint32 DictTabInfo::TableMappingSize = sizeof(DictTabInfo::TableMapping) / sizeof(SimpleProperties::SP2StructMapping); //static const SimpleProperties::SP2StructMapping DictTabInfo::AttributeMapping[] = { DTIMAPS(Attribute, AttributeName, AttributeName, 0, MAX_ATTR_NAME_SIZE), DTIMAP(Attribute, AttributeId, AttributeId), DTIMAP(Attribute, AttributeType, AttributeType), DTIMAP2(Attribute, AttributeSize, AttributeSize, 3, 7), DTIMAP2(Attribute, AttributeArraySize, AttributeArraySize, 0, 65535), DTIMAP2(Attribute, AttributeArrayType, AttributeArrayType, 0, 3), DTIMAP2(Attribute, AttributeKeyFlag, AttributeKeyFlag, 0, 1), DTIMAP2(Attribute, AttributeNullableFlag, AttributeNullableFlag, 0, 1), DTIMAP2(Attribute, AttributeDKey, AttributeDKey, 0, 1), DTIMAP2(Attribute, AttributeStorageType, AttributeStorageType, 0, 1), DTIMAP(Attribute, AttributeExtType, AttributeExtType), DTIMAP(Attribute, AttributeExtPrecision, AttributeExtPrecision), DTIMAP(Attribute, AttributeExtScale, AttributeExtScale), DTIMAP(Attribute, AttributeExtLength, AttributeExtLength), DTIMAP2(Attribute, AttributeAutoIncrement, AttributeAutoIncrement, 0, 1), DTIMAPS(Attribute, AttributeDefaultValue, AttributeDefaultValue, 0, MAX_ATTR_DEFAULT_VALUE_SIZE), DTIBREAK(AttributeEnd) }; //static const Uint32 DictTabInfo::AttributeMappingSize = sizeof(DictTabInfo::AttributeMapping) / sizeof(SimpleProperties::SP2StructMapping); bool printDICTTABINFO(FILE * output, const Uint32 * theData, Uint32 len, Uint16 receiverBlockNo) { // const DictTabInfo * const sig = (DictTabInfo *) theData; fprintf(output, "Signal data: "); Uint32 i = 0; while (i < len) fprintf(output, "H\'%.8x ", theData[i++]); fprintf(output,"\n"); return true; } void DictTabInfo::Table::init(){ memset(TableName, 0, sizeof(TableName));//TableName[0] = 0; TableId = ~0; memset(PrimaryTable, 0, sizeof(PrimaryTable));//PrimaryTable[0] = 0; // Only used when "index" PrimaryTableId = RNIL; TableLoggedFlag = 1; TableTemporaryFlag = 0; NoOfKeyAttr = 0; NoOfAttributes = 0; NoOfNullable = 0; NoOfVariable = 0; TableKValue = 6; MinLoadFactor = 78; MaxLoadFactor = 80; KeyLength = 0; FragmentType = DictTabInfo::AllNodesSmallTable; TableType = DictTabInfo::UndefTableType; TableVersion = 0; IndexState = ~0; InsertTriggerId = RNIL; UpdateTriggerId = RNIL; DeleteTriggerId = RNIL; CustomTriggerId = RNIL; FrmLen = 0; FragmentDataLen = 0; ReplicaDataLen = 0; RangeListDataLen = 0; TablespaceDataLen = 0; memset(FrmData, 0, sizeof(FrmData)); memset(FragmentData, 0, sizeof(FragmentData)); memset(ReplicaData, 0, sizeof(ReplicaData)); memset(RangeListData, 0, sizeof(RangeListData)); memset(TablespaceData, 0, sizeof(TablespaceData)); FragmentCount = 0; TablespaceId = RNIL; TablespaceVersion = ~0; MaxRowsLow = 0; MaxRowsHigh = 0; DefaultNoPartFlag = 1; LinearHashFlag = 1; RowGCIFlag = ~0; RowChecksumFlag = ~0; MaxRowsLow = 0; MaxRowsHigh = 0; MinRowsLow = 0; MinRowsHigh = 0; } void DictTabInfo::Attribute::init(){ memset(AttributeName, 0, sizeof(AttributeName));//AttributeName[0] = 0; AttributeId = 0xFFFF; // ZNIL AttributeType = ~0, // deprecated AttributeSize = DictTabInfo::a32Bit; AttributeArraySize = 1; AttributeArrayType = NDB_ARRAYTYPE_FIXED; AttributeKeyFlag = 0; AttributeNullableFlag = 0; AttributeDKey = 0; AttributeExtType = DictTabInfo::ExtUnsigned, AttributeExtPrecision = 0, AttributeExtScale = 0, AttributeExtLength = 0, AttributeAutoIncrement = false; AttributeStorageType = 0; memset(AttributeDefaultValue, 0, sizeof(AttributeDefaultValue));//AttributeDefaultValue[0] = 0; } //static const SimpleProperties::SP2StructMapping DictFilegroupInfo::Mapping[] = { DFGIMAPS(Filegroup, FilegroupName, FilegroupName, 0, MAX_TAB_NAME_SIZE), DFGIMAP2(Filegroup, FilegroupType, FilegroupType, 0, 1), DFGIMAP(Filegroup, FilegroupId, FilegroupId), DFGIMAP(Filegroup, FilegroupVersion, FilegroupVersion), DFGIMAP(Filegroup, TS_ExtentSize, TS_ExtentSize), DFGIMAP(Filegroup, TS_LogfileGroupId, TS_LogfileGroupId), DFGIMAP(Filegroup, TS_LogfileGroupVersion, TS_LogfileGroupVersion), DFGIMAP(Filegroup, TS_GrowLimit, TS_DataGrow.GrowLimit), DFGIMAP(Filegroup, TS_GrowSizeHi, TS_DataGrow.GrowSizeHi), DFGIMAP(Filegroup, TS_GrowSizeLo, TS_DataGrow.GrowSizeLo), DFGIMAPS(Filegroup, TS_GrowPattern, TS_DataGrow.GrowPattern, 0, PATH_MAX), DFGIMAP(Filegroup, TS_GrowMaxSize, TS_DataGrow.GrowMaxSize), DFGIMAP(Filegroup, LF_UndoBufferSize, LF_UndoBufferSize), DFGIMAP(Filegroup, LF_UndoGrowLimit, LF_UndoGrow.GrowLimit), DFGIMAP(Filegroup, LF_UndoGrowSizeHi, LF_UndoGrow.GrowSizeHi), DFGIMAP(Filegroup, LF_UndoGrowSizeLo, LF_UndoGrow.GrowSizeLo), DFGIMAPS(Filegroup, LF_UndoGrowPattern, LF_UndoGrow.GrowPattern, 0,PATH_MAX), DFGIMAP(Filegroup, LF_UndoGrowMaxSize, LF_UndoGrow.GrowMaxSize), DFGIMAP(Filegroup, LF_UndoFreeWordsHi, LF_UndoFreeWordsHi), DFGIMAP(Filegroup, LF_UndoFreeWordsLo, LF_UndoFreeWordsLo), DFGIBREAK(FileName) }; //static const Uint32 DictFilegroupInfo::MappingSize = sizeof(DictFilegroupInfo::Mapping) / sizeof(SimpleProperties::SP2StructMapping); //static const SimpleProperties::SP2StructMapping DictFilegroupInfo::FileMapping[] = { DFGIMAPS(File, FileName, FileName, 0, PATH_MAX), DFGIMAP2(File, FileType, FileType, 0, 1), DFGIMAP(File, FileId, FileId), DFGIMAP(File, FileVersion, FileVersion), DFGIMAP(File, FileFGroupId, FilegroupId), DFGIMAP(File, FileFGroupVersion, FilegroupVersion), DFGIMAP(File, FileSizeHi, FileSizeHi), DFGIMAP(File, FileSizeLo, FileSizeLo), DFGIMAP(File, FileFreeExtents, FileFreeExtents), DFGIBREAK(FileEnd) }; //static const Uint32 DictFilegroupInfo::FileMappingSize = sizeof(DictFilegroupInfo::FileMapping) / sizeof(SimpleProperties::SP2StructMapping); void DictFilegroupInfo::Filegroup::init(){ memset(FilegroupName, 0, sizeof(FilegroupName)); FilegroupType = ~0; FilegroupId = ~0; FilegroupVersion = ~0; TS_ExtentSize = 0; TS_LogfileGroupId = ~0; TS_LogfileGroupVersion = ~0; TS_DataGrow.GrowLimit = 0; TS_DataGrow.GrowSizeHi = 0; TS_DataGrow.GrowSizeLo = 0; memset(TS_DataGrow.GrowPattern, 0, sizeof(TS_DataGrow.GrowPattern)); TS_DataGrow.GrowMaxSize = 0; LF_UndoFreeWordsHi= 0; LF_UndoFreeWordsLo= 0; } void DictFilegroupInfo::File::init(){ memset(FileName, sizeof(FileName), 0); FileType = ~0; FileId = ~0; FileVersion = ~0; FilegroupId = ~0; FilegroupVersion = ~0; FileSizeHi = 0; FileSizeLo = 0; FileFreeExtents = 0; } // blob table name hack bool DictTabInfo::isBlobTableName(const char* name, Uint32* ptab_id, Uint32* pcol_no) { const char* const prefix = "NDB$BLOB_"; const char* s = strrchr(name, table_name_separator); s = (s == NULL ? name : s + 1); if (strncmp(s, prefix, strlen(prefix)) != 0) return false; s += strlen(prefix); uint i, n; for (i = 0, n = 0; '0' <= s[i] && s[i] <= '9'; i++) n = 10 * n + (s[i] - '0'); if (i == 0 || s[i] != '_') return false; const uint tab_id = n; s = &s[i + 1]; for (i = 0, n = 0; '0' <= s[i] && s[i] <= '9'; i++) n = 10 * n + (s[i] - '0'); if (i == 0 || s[i] != 0) return false; const uint col_no = n; if (ptab_id) *ptab_id = tab_id; if (pcol_no) *pcol_no = col_no; return true; } <commit_msg>DictTabInfo.cpp: Fix for bug#23169 - memset param switching<commit_after>/* Copyright (C) 2003 MySQL AB 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 <signaldata/DictTabInfo.hpp> #include <ndb_limits.h> //static const SimpleProperties::SP2StructMapping DictTabInfo::TableMapping[] = { DTIMAPS(Table, TableName, TableName, 0, MAX_TAB_NAME_SIZE), DTIMAP(Table, TableId, TableId), DTIMAPS(Table, PrimaryTable, PrimaryTable, 0, MAX_TAB_NAME_SIZE), DTIMAP(Table, PrimaryTableId, PrimaryTableId), DTIMAP2(Table, TableLoggedFlag, TableLoggedFlag, 0, 1), DTIMAP2(Table, TableTemporaryFlag, TableTemporaryFlag, 0, 1), DTIMAP2(Table, TableKValue, TableKValue, 6, 6), DTIMAP2(Table, MinLoadFactor, MinLoadFactor, 0, 90), DTIMAP2(Table, MaxLoadFactor, MaxLoadFactor, 25, 110), DTIMAP2(Table, FragmentTypeVal, FragmentType, 0, 3), DTIMAP2(Table, TableTypeVal, TableType, 1, 3), DTIMAP(Table, NoOfKeyAttr, NoOfKeyAttr), DTIMAP2(Table, NoOfAttributes, NoOfAttributes, 1, MAX_ATTRIBUTES_IN_TABLE), DTIMAP(Table, NoOfNullable, NoOfNullable), DTIMAP2(Table, NoOfVariable, NoOfVariable, 0, 0), DTIMAP(Table, KeyLength, KeyLength), DTIMAP(Table, TableVersion, TableVersion), DTIMAP(Table, IndexState, IndexState), DTIMAP(Table, InsertTriggerId, InsertTriggerId), DTIMAP(Table, UpdateTriggerId, UpdateTriggerId), DTIMAP(Table, DeleteTriggerId, DeleteTriggerId), DTIMAP(Table, CustomTriggerId, CustomTriggerId), DTIMAP2(Table, FrmLen, FrmLen, 0, MAX_FRM_DATA_SIZE), DTIMAPB(Table, FrmData, FrmData, 0, MAX_FRM_DATA_SIZE, FrmLen), DTIMAP2(Table, FragmentCount, FragmentCount, 0, MAX_NDB_PARTITIONS), DTIMAP2(Table, ReplicaDataLen, ReplicaDataLen, 0, 2*MAX_FRAGMENT_DATA_BYTES), DTIMAPB(Table, ReplicaData, ReplicaData, 0, 2*MAX_FRAGMENT_DATA_BYTES, ReplicaDataLen), DTIMAP2(Table, FragmentDataLen, FragmentDataLen, 0, 6*MAX_NDB_PARTITIONS), DTIMAPB(Table, FragmentData, FragmentData, 0, 6*MAX_NDB_PARTITIONS, FragmentDataLen), DTIMAP2(Table, TablespaceDataLen, TablespaceDataLen, 0, 8*MAX_NDB_PARTITIONS), DTIMAPB(Table, TablespaceData, TablespaceData, 0, 8*MAX_NDB_PARTITIONS, TablespaceDataLen), DTIMAP2(Table, RangeListDataLen, RangeListDataLen, 0, 8*MAX_NDB_PARTITIONS), DTIMAPB(Table, RangeListData, RangeListData, 0, 8*MAX_NDB_PARTITIONS, RangeListDataLen), DTIMAP(Table, TablespaceId, TablespaceId), DTIMAP(Table, TablespaceVersion, TablespaceVersion), DTIMAP(Table, MaxRowsLow, MaxRowsLow), DTIMAP(Table, MaxRowsHigh, MaxRowsHigh), DTIMAP(Table, DefaultNoPartFlag, DefaultNoPartFlag), DTIMAP(Table, LinearHashFlag, LinearHashFlag), DTIMAP(Table, TablespaceVersion, TablespaceVersion), DTIMAP(Table, RowGCIFlag, RowGCIFlag), DTIMAP(Table, RowChecksumFlag, RowChecksumFlag), DTIMAP(Table, MaxRowsLow, MaxRowsLow), DTIMAP(Table, MaxRowsHigh, MaxRowsHigh), DTIMAP(Table, MinRowsLow, MinRowsLow), DTIMAP(Table, MinRowsHigh, MinRowsHigh), DTIBREAK(AttributeName) }; //static const Uint32 DictTabInfo::TableMappingSize = sizeof(DictTabInfo::TableMapping) / sizeof(SimpleProperties::SP2StructMapping); //static const SimpleProperties::SP2StructMapping DictTabInfo::AttributeMapping[] = { DTIMAPS(Attribute, AttributeName, AttributeName, 0, MAX_ATTR_NAME_SIZE), DTIMAP(Attribute, AttributeId, AttributeId), DTIMAP(Attribute, AttributeType, AttributeType), DTIMAP2(Attribute, AttributeSize, AttributeSize, 3, 7), DTIMAP2(Attribute, AttributeArraySize, AttributeArraySize, 0, 65535), DTIMAP2(Attribute, AttributeArrayType, AttributeArrayType, 0, 3), DTIMAP2(Attribute, AttributeKeyFlag, AttributeKeyFlag, 0, 1), DTIMAP2(Attribute, AttributeNullableFlag, AttributeNullableFlag, 0, 1), DTIMAP2(Attribute, AttributeDKey, AttributeDKey, 0, 1), DTIMAP2(Attribute, AttributeStorageType, AttributeStorageType, 0, 1), DTIMAP(Attribute, AttributeExtType, AttributeExtType), DTIMAP(Attribute, AttributeExtPrecision, AttributeExtPrecision), DTIMAP(Attribute, AttributeExtScale, AttributeExtScale), DTIMAP(Attribute, AttributeExtLength, AttributeExtLength), DTIMAP2(Attribute, AttributeAutoIncrement, AttributeAutoIncrement, 0, 1), DTIMAPS(Attribute, AttributeDefaultValue, AttributeDefaultValue, 0, MAX_ATTR_DEFAULT_VALUE_SIZE), DTIBREAK(AttributeEnd) }; //static const Uint32 DictTabInfo::AttributeMappingSize = sizeof(DictTabInfo::AttributeMapping) / sizeof(SimpleProperties::SP2StructMapping); bool printDICTTABINFO(FILE * output, const Uint32 * theData, Uint32 len, Uint16 receiverBlockNo) { // const DictTabInfo * const sig = (DictTabInfo *) theData; fprintf(output, "Signal data: "); Uint32 i = 0; while (i < len) fprintf(output, "H\'%.8x ", theData[i++]); fprintf(output,"\n"); return true; } void DictTabInfo::Table::init(){ memset(TableName, 0, sizeof(TableName));//TableName[0] = 0; TableId = ~0; memset(PrimaryTable, 0, sizeof(PrimaryTable));//PrimaryTable[0] = 0; // Only used when "index" PrimaryTableId = RNIL; TableLoggedFlag = 1; TableTemporaryFlag = 0; NoOfKeyAttr = 0; NoOfAttributes = 0; NoOfNullable = 0; NoOfVariable = 0; TableKValue = 6; MinLoadFactor = 78; MaxLoadFactor = 80; KeyLength = 0; FragmentType = DictTabInfo::AllNodesSmallTable; TableType = DictTabInfo::UndefTableType; TableVersion = 0; IndexState = ~0; InsertTriggerId = RNIL; UpdateTriggerId = RNIL; DeleteTriggerId = RNIL; CustomTriggerId = RNIL; FrmLen = 0; FragmentDataLen = 0; ReplicaDataLen = 0; RangeListDataLen = 0; TablespaceDataLen = 0; memset(FrmData, 0, sizeof(FrmData)); memset(FragmentData, 0, sizeof(FragmentData)); memset(ReplicaData, 0, sizeof(ReplicaData)); memset(RangeListData, 0, sizeof(RangeListData)); memset(TablespaceData, 0, sizeof(TablespaceData)); FragmentCount = 0; TablespaceId = RNIL; TablespaceVersion = ~0; MaxRowsLow = 0; MaxRowsHigh = 0; DefaultNoPartFlag = 1; LinearHashFlag = 1; RowGCIFlag = ~0; RowChecksumFlag = ~0; MaxRowsLow = 0; MaxRowsHigh = 0; MinRowsLow = 0; MinRowsHigh = 0; } void DictTabInfo::Attribute::init(){ memset(AttributeName, 0, sizeof(AttributeName));//AttributeName[0] = 0; AttributeId = 0xFFFF; // ZNIL AttributeType = ~0, // deprecated AttributeSize = DictTabInfo::a32Bit; AttributeArraySize = 1; AttributeArrayType = NDB_ARRAYTYPE_FIXED; AttributeKeyFlag = 0; AttributeNullableFlag = 0; AttributeDKey = 0; AttributeExtType = DictTabInfo::ExtUnsigned, AttributeExtPrecision = 0, AttributeExtScale = 0, AttributeExtLength = 0, AttributeAutoIncrement = false; AttributeStorageType = 0; memset(AttributeDefaultValue, 0, sizeof(AttributeDefaultValue));//AttributeDefaultValue[0] = 0; } //static const SimpleProperties::SP2StructMapping DictFilegroupInfo::Mapping[] = { DFGIMAPS(Filegroup, FilegroupName, FilegroupName, 0, MAX_TAB_NAME_SIZE), DFGIMAP2(Filegroup, FilegroupType, FilegroupType, 0, 1), DFGIMAP(Filegroup, FilegroupId, FilegroupId), DFGIMAP(Filegroup, FilegroupVersion, FilegroupVersion), DFGIMAP(Filegroup, TS_ExtentSize, TS_ExtentSize), DFGIMAP(Filegroup, TS_LogfileGroupId, TS_LogfileGroupId), DFGIMAP(Filegroup, TS_LogfileGroupVersion, TS_LogfileGroupVersion), DFGIMAP(Filegroup, TS_GrowLimit, TS_DataGrow.GrowLimit), DFGIMAP(Filegroup, TS_GrowSizeHi, TS_DataGrow.GrowSizeHi), DFGIMAP(Filegroup, TS_GrowSizeLo, TS_DataGrow.GrowSizeLo), DFGIMAPS(Filegroup, TS_GrowPattern, TS_DataGrow.GrowPattern, 0, PATH_MAX), DFGIMAP(Filegroup, TS_GrowMaxSize, TS_DataGrow.GrowMaxSize), DFGIMAP(Filegroup, LF_UndoBufferSize, LF_UndoBufferSize), DFGIMAP(Filegroup, LF_UndoGrowLimit, LF_UndoGrow.GrowLimit), DFGIMAP(Filegroup, LF_UndoGrowSizeHi, LF_UndoGrow.GrowSizeHi), DFGIMAP(Filegroup, LF_UndoGrowSizeLo, LF_UndoGrow.GrowSizeLo), DFGIMAPS(Filegroup, LF_UndoGrowPattern, LF_UndoGrow.GrowPattern, 0,PATH_MAX), DFGIMAP(Filegroup, LF_UndoGrowMaxSize, LF_UndoGrow.GrowMaxSize), DFGIMAP(Filegroup, LF_UndoFreeWordsHi, LF_UndoFreeWordsHi), DFGIMAP(Filegroup, LF_UndoFreeWordsLo, LF_UndoFreeWordsLo), DFGIBREAK(FileName) }; //static const Uint32 DictFilegroupInfo::MappingSize = sizeof(DictFilegroupInfo::Mapping) / sizeof(SimpleProperties::SP2StructMapping); //static const SimpleProperties::SP2StructMapping DictFilegroupInfo::FileMapping[] = { DFGIMAPS(File, FileName, FileName, 0, PATH_MAX), DFGIMAP2(File, FileType, FileType, 0, 1), DFGIMAP(File, FileId, FileId), DFGIMAP(File, FileVersion, FileVersion), DFGIMAP(File, FileFGroupId, FilegroupId), DFGIMAP(File, FileFGroupVersion, FilegroupVersion), DFGIMAP(File, FileSizeHi, FileSizeHi), DFGIMAP(File, FileSizeLo, FileSizeLo), DFGIMAP(File, FileFreeExtents, FileFreeExtents), DFGIBREAK(FileEnd) }; //static const Uint32 DictFilegroupInfo::FileMappingSize = sizeof(DictFilegroupInfo::FileMapping) / sizeof(SimpleProperties::SP2StructMapping); void DictFilegroupInfo::Filegroup::init(){ memset(FilegroupName, 0, sizeof(FilegroupName)); FilegroupType = ~0; FilegroupId = ~0; FilegroupVersion = ~0; TS_ExtentSize = 0; TS_LogfileGroupId = ~0; TS_LogfileGroupVersion = ~0; TS_DataGrow.GrowLimit = 0; TS_DataGrow.GrowSizeHi = 0; TS_DataGrow.GrowSizeLo = 0; memset(TS_DataGrow.GrowPattern, 0, sizeof(TS_DataGrow.GrowPattern)); TS_DataGrow.GrowMaxSize = 0; LF_UndoFreeWordsHi= 0; LF_UndoFreeWordsLo= 0; } void DictFilegroupInfo::File::init(){ memset(FileName, 0, sizeof(FileName)); FileType = ~0; FileId = ~0; FileVersion = ~0; FilegroupId = ~0; FilegroupVersion = ~0; FileSizeHi = 0; FileSizeLo = 0; FileFreeExtents = 0; } // blob table name hack bool DictTabInfo::isBlobTableName(const char* name, Uint32* ptab_id, Uint32* pcol_no) { const char* const prefix = "NDB$BLOB_"; const char* s = strrchr(name, table_name_separator); s = (s == NULL ? name : s + 1); if (strncmp(s, prefix, strlen(prefix)) != 0) return false; s += strlen(prefix); uint i, n; for (i = 0, n = 0; '0' <= s[i] && s[i] <= '9'; i++) n = 10 * n + (s[i] - '0'); if (i == 0 || s[i] != '_') return false; const uint tab_id = n; s = &s[i + 1]; for (i = 0, n = 0; '0' <= s[i] && s[i] <= '9'; i++) n = 10 * n + (s[i] - '0'); if (i == 0 || s[i] != 0) return false; const uint col_no = n; if (ptab_id) *ptab_id = tab_id; if (pcol_no) *pcol_no = col_no; return true; } <|endoftext|>
<commit_before>#ifndef ALGODS_LINKEDLIST_HXX #define ALGODS_LINKEDLIST_HXX #include <cassert> #include <iterator> #include <algorithm> #include <sstream> #include <utility> #ifdef DEBUG #include <iostream> #endif namespace algods { namespace linkedlist { using namespace std; template<typename T> struct slnode { slnode(const T& d, slnode* n): data(d), next(n) { } T data; slnode* next; }; template<typename T> class sliterator : public iterator<forward_iterator_tag, T> { public: sliterator(): current(nullptr) { } sliterator(slnode<T>* head): current(head) { } sliterator(const sliterator& right) { current = right.current; } sliterator(sliterator&& right) { current = right.current; right.current = nullptr; } sliterator& operator=(const sliterator& right) { current = right.current; return *this; } sliterator& operator=(sliterator&& right) { current = right.current; right.current = nullptr; return *this; } sliterator& operator++() { if(nullptr != current) { current = current->next; } return *this; } sliterator operator++(int) { sliterator ret(*this); ++(*this); return ret; } T& operator*() { assert(nullptr != current); return current->data; } const T& operator*() const { return this->operator*(); } T* operator->() { assert(nullptr != current); return &(current->data); } bool operator==(const sliterator& right) const { return current == right.current; } bool operator!=(const sliterator& right) const { return !(*this == right); } private: slnode<T>* current; }; template<typename T> sliterator<T> linkedlist_begin(slnode<T>* head) { return sliterator<T>(head); } template<typename T> sliterator<T> linkedlist_end(slnode<T>* head) { return sliterator<T>(); } template<typename T> struct dlnode { dlnode(const T& d, dlnode* p, dlnode* n) : data(d), prev(p), next(n) { } T data; dlnode* prev; dlnode* next; }; template<typename input_iterator> void build_linkedlist(input_iterator begin, input_iterator end, slnode<typename iterator_traits<input_iterator>::value_type>*& head) { typedef typename iterator_traits<input_iterator>::value_type value_t; typedef slnode<value_t> node_t; node_t **current = &head; while(begin != end) { *current = new node_t(*begin, nullptr); current = &((*current)->next); ++begin; } } template<typename input_iterator> void build_linkedlist(input_iterator begin, input_iterator end, dlnode<typename iterator_traits<input_iterator>::value_type>*& head) { typedef typename iterator_traits<input_iterator>::value_type value_t; typedef dlnode<value_t> node_t; node_t *prev = nullptr; node_t **current = &head; while(begin != end) { *current = new node_t(*begin, prev, nullptr); prev = *current; current = &((*current)->next); ++begin; } if(head != nullptr) { *current = head; head->prev = prev; } } template<typename T> void destroy_linkedlist(slnode<T>*& head) { while(head != nullptr) { auto p = head; head = head->next; delete p; } } template<typename T> void destroy_linkedlist(dlnode<T>*& head) { auto pivot = head; while(pivot != nullptr && pivot->next != head) { auto p = pivot; pivot = pivot->next; delete p; } if(pivot != nullptr) { delete pivot; } head = nullptr; } template<typename T> string linkedlist2string(const slnode<T>* head) { if(nullptr == head) { return string("{}"); } sliterator<T> begin(linkedlist_begin(const_cast<slnode<T>*>(head))); sliterator<T> end(linkedlist_end(const_cast<slnode<T>*>(head))); ostringstream oss; copy(begin, end, ostream_iterator<T>(oss, "->")); string s(oss.str()); // remove last "->" s.pop_back(); s.pop_back(); return "{" + s + "}"; } template<typename T> string linkedlist2string(const dlnode<T>* head) { ostringstream oss; auto pivot = head; while(pivot != nullptr && pivot->next != head) { oss << pivot->data << "<->"; pivot = pivot->next; } if(pivot != nullptr) { oss << pivot->data; } return oss.str(); } template<typename T> void reverse_linkedlist(slnode<T>*& head) { slnode<T>* prev = nullptr; while(head != nullptr && head->next != nullptr) { auto next = head->next; head->next = prev; prev = head; head = next; } if(head != nullptr) { head->next = prev; } } template<typename T> void append_node(slnode<T>*& head, const T& data) { slnode<T>** current = &head; while(*current != nullptr) { current = &((*current)->next); } *current = new slnode<T>(data, nullptr); } template<typename T> void remove_node(slnode<T>*& head, slnode<T>*& p) { if(head == nullptr || p == nullptr) { return; } if(head == p) { head = head->next; delete p; p = nullptr; return; } auto current = head; while(current != nullptr && current->next != p) { current = current->next; } if(current != nullptr) { current->next = p->next; delete p; p = nullptr; } } template<typename T> slnode<T>* find_node(slnode<T>* head, const T& value) { while(head != nullptr) { if(head->data == value) { return head; } head = head->next; } return nullptr; } template<typename T> void difference(slnode<T>*& left, slnode<T>* right) { while(right != nullptr) { auto p = find_node(left, right->data); remove_node(left, p); right = right->next; } } template<typename T> slnode<T>* merge_linkedlist(slnode<T>*& left, slnode<T>*& right) { #ifdef DEBUG std::cout << "left list: " << linkedlist2string(left) << std::endl; std::cout << "right list: " << linkedlist2string(right) << std::endl; #endif slnode<T>* head = nullptr; slnode<T>** pp = &head; int i = 0; while(nullptr != left && nullptr != right) { if((i & 0x1) == 0) { *pp = left; pp = &(*pp)->next; left = left->next; } else { *pp = right; pp = &(*pp)->next; right = right->next; } ++i; } if(nullptr != left) { *pp = left; } if(nullptr != right) { *pp = right; } left = nullptr; right = nullptr; #ifdef DEBUG std::cout << "merged list: " << linkedlist2string(head) << std::endl; #endif return head; } /**************************************************************************************** ** Given a singly linked list L: (L0 , L1 , L2...Ln-1 , Ln). ** Write a program to reorder it so that it becomes(L0 , Ln , L1 , Ln-1 , L2 , Ln-2...). ***************************************************************************************/ template<typename T> void reorder_linkedlist(slnode<T>*& head) { #ifdef DEBUG std::cout << "original list: " << linkedlist2string(head) << std::endl; #endif int num = 0; slnode<T>* p = head; while(nullptr != p) { ++num; p = p->next; } int count = 0; p = head; while(count < (num >> 1)) { ++count; p = p->next; } if((num & 0x1) != 0) { p = p->next; } slnode<T>* left = head; slnode<T>* right = p; p = head; while(nullptr != p && right != p->next) { p = p->next; } if(nullptr != p) { p->next = nullptr; } #ifdef DEBUG std::cout << "left list: " << linkedlist2string(left) << std::endl; std::cout << "right list: " << linkedlist2string(right) << std::endl; #endif reverse_linkedlist(right); #ifdef DEBUG std::cout << "reversed right list: " << linkedlist2string(right) << std::endl; #endif head = merge_linkedlist(left, right); #ifdef DEBUG std::cout <<"result list: " << linkedlist2string(head) << std::endl; #endif } } } #endif <commit_msg>more stuff<commit_after>#ifndef ALGODS_LINKEDLIST_HXX #define ALGODS_LINKEDLIST_HXX #include <cassert> #include <iterator> #include <algorithm> #include <sstream> #include <utility> #ifdef DEBUG #include <iostream> #endif namespace algods { namespace linkedlist { using namespace std; template<typename T> struct slnode { slnode(const T& d, slnode* n): data(d), next(n) { } T data; slnode* next; }; template<typename T> class sliterator : public iterator<forward_iterator_tag, T> { public: sliterator(): current(nullptr) { } sliterator(slnode<T>* head): current(head) { } sliterator(const sliterator& right) { current = right.current; } sliterator(sliterator&& right) { current = right.current; right.current = nullptr; } sliterator& operator=(const sliterator& right) { current = right.current; return *this; } sliterator& operator=(sliterator&& right) { current = right.current; right.current = nullptr; return *this; } sliterator& operator++() { if(nullptr != current) { current = current->next; } return *this; } sliterator operator++(int) { sliterator ret(*this); ++(*this); return ret; } T& operator*() { assert(nullptr != current); return current->data; } const T& operator*() const { return this->operator*(); } T* operator->() { assert(nullptr != current); return &(current->data); } bool operator==(const sliterator& right) const { return current == right.current; } bool operator!=(const sliterator& right) const { return !(*this == right); } private: slnode<T>* current; }; template<typename T> sliterator<T> linkedlist_begin(slnode<T>* head) { return sliterator<T>(head); } template<typename T> sliterator<T> linkedlist_end(slnode<T>* head) { return sliterator<T>(); } template<typename T> struct dlnode { dlnode(const T& d, dlnode* p, dlnode* n) : data(d), prev(p), next(n) { } T data; dlnode* prev; dlnode* next; }; template<typename input_iterator> void build_linkedlist(input_iterator begin, input_iterator end, slnode<typename iterator_traits<input_iterator>::value_type>*& head) { typedef typename iterator_traits<input_iterator>::value_type value_t; typedef slnode<value_t> node_t; node_t **current = &head; while(begin != end) { *current = new node_t(*begin, nullptr); current = &((*current)->next); ++begin; } } template<typename input_iterator> void build_linkedlist(input_iterator begin, input_iterator end, dlnode<typename iterator_traits<input_iterator>::value_type>*& head) { typedef typename iterator_traits<input_iterator>::value_type value_t; typedef dlnode<value_t> node_t; node_t *prev = nullptr; node_t **current = &head; while(begin != end) { *current = new node_t(*begin, prev, nullptr); prev = *current; current = &((*current)->next); ++begin; } if(head != nullptr) { *current = head; head->prev = prev; } } template<typename T> void destroy_linkedlist(slnode<T>*& head) { while(head != nullptr) { auto p = head; head = head->next; delete p; } } template<typename T> void destroy_linkedlist(dlnode<T>*& head) { auto pivot = head; while(pivot != nullptr && pivot->next != head) { auto p = pivot; pivot = pivot->next; delete p; } if(pivot != nullptr) { delete pivot; } head = nullptr; } template<typename T> string linkedlist2string(const slnode<T>* head) { if(nullptr == head) { return string("{}"); } sliterator<T> begin(linkedlist_begin(const_cast<slnode<T>*>(head))); sliterator<T> end(linkedlist_end(const_cast<slnode<T>*>(head))); ostringstream oss; copy(begin, end, ostream_iterator<T>(oss, "->")); string s(oss.str()); // remove last "->" s = s.substr(0, s.size() - 2); return "{" + s + "}"; } template<typename T> string linkedlist2string(const dlnode<T>* head) { ostringstream oss; auto pivot = head; while(pivot != nullptr && pivot->next != head) { oss << pivot->data << "<->"; pivot = pivot->next; } if(pivot != nullptr) { oss << pivot->data; } return oss.str(); } template<typename T> void reverse_linkedlist(slnode<T>*& head) { slnode<T>* prev = nullptr; while(head != nullptr && head->next != nullptr) { auto next = head->next; head->next = prev; prev = head; head = next; } if(head != nullptr) { head->next = prev; } } template<typename T> void append_node(slnode<T>*& head, const T& data) { slnode<T>** current = &head; while(*current != nullptr) { current = &((*current)->next); } *current = new slnode<T>(data, nullptr); } template<typename T> void remove_node(slnode<T>*& head, slnode<T>*& p) { if(head == nullptr || p == nullptr) { return; } if(head == p) { head = head->next; delete p; p = nullptr; return; } auto current = head; while(current != nullptr && current->next != p) { current = current->next; } if(current != nullptr) { current->next = p->next; delete p; p = nullptr; } } template<typename T> slnode<T>* find_node(slnode<T>* head, const T& value) { while(head != nullptr) { if(head->data == value) { return head; } head = head->next; } return nullptr; } template<typename T> void difference(slnode<T>*& left, slnode<T>* right) { while(right != nullptr) { auto p = find_node(left, right->data); remove_node(left, p); right = right->next; } } template<typename T> slnode<T>* merge_linkedlist(slnode<T>*& left, slnode<T>*& right) { #ifdef DEBUG std::cout << "left list: " << linkedlist2string(left) << std::endl; std::cout << "right list: " << linkedlist2string(right) << std::endl; #endif slnode<T>* head = nullptr; slnode<T>** pp = &head; int i = 0; while(nullptr != left && nullptr != right) { if((i & 0x1) == 0) { *pp = left; pp = &(*pp)->next; left = left->next; } else { *pp = right; pp = &(*pp)->next; right = right->next; } ++i; } if(nullptr != left) { *pp = left; } if(nullptr != right) { *pp = right; } left = nullptr; right = nullptr; #ifdef DEBUG std::cout << "merged list: " << linkedlist2string(head) << std::endl; #endif return head; } /**************************************************************************************** ** Given a singly linked list L: (L0 , L1 , L2...Ln-1 , Ln). ** Write a program to reorder it so that it becomes(L0 , Ln , L1 , Ln-1 , L2 , Ln-2...). ***************************************************************************************/ template<typename T> void reorder_linkedlist(slnode<T>*& head) { #ifdef DEBUG std::cout << "original list: " << linkedlist2string(head) << std::endl; #endif int num = 0; slnode<T>* p = head; while(nullptr != p) { ++num; p = p->next; } int count = 0; p = head; while(count < (num >> 1)) { ++count; p = p->next; } if((num & 0x1) != 0) { p = p->next; } slnode<T>* left = head; slnode<T>* right = p; p = head; while(nullptr != p && right != p->next) { p = p->next; } if(nullptr != p) { p->next = nullptr; } #ifdef DEBUG std::cout << "left list: " << linkedlist2string(left) << std::endl; std::cout << "right list: " << linkedlist2string(right) << std::endl; #endif reverse_linkedlist(right); #ifdef DEBUG std::cout << "reversed right list: " << linkedlist2string(right) << std::endl; #endif head = merge_linkedlist(left, right); #ifdef DEBUG std::cout <<"result list: " << linkedlist2string(head) << std::endl; #endif } } } #endif <|endoftext|>
<commit_before>// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "rpc_target.h" #include "shared_rpc_resources.h" #include <vespa/fastos/thread.h> #include <vespa/fnet/frt/supervisor.h> #include <vespa/fnet/frt/target.h> #include <vespa/fnet/transport.h> #include <vespa/slobrok/sbregister.h> #include <vespa/slobrok/sbmirror.h> #include <vespa/vespalib/util/exceptions.h> #include <vespa/vespalib/util/host_name.h> #include <vespa/vespalib/util/stringfmt.h> #include <cassert> #include <chrono> #include <thread> #include <vespa/log/log.h> LOG_SETUP(".storage.shared_rpc_resources"); using namespace std::chrono_literals; namespace storage::rpc { namespace { class RpcTargetImpl : public RpcTarget { private: FRT_Target* _target; vespalib::string _spec; public: RpcTargetImpl(FRT_Target* target, const vespalib::string& spec) : _target(target), _spec(spec) {} ~RpcTargetImpl() override { _target->SubRef(); } FRT_Target* get() noexcept override { return _target; } bool is_valid() const noexcept override { return _target->IsValid(); } const vespalib::string& spec() const noexcept override { return _spec; } }; } class SharedRpcResources::RpcTargetFactoryImpl : public RpcTargetFactory { private: FRT_Supervisor& _orb; public: RpcTargetFactoryImpl(FRT_Supervisor& orb) : _orb(orb) {} std::unique_ptr<RpcTarget> make_target(const vespalib::string& connection_spec) const override { auto* raw_target = _orb.GetTarget(connection_spec.c_str()); if (raw_target) { return std::make_unique<RpcTargetImpl>(raw_target, connection_spec); } return std::unique_ptr<RpcTarget>(); } }; SharedRpcResources::SharedRpcResources(const config::ConfigUri& config_uri, int rpc_server_port, size_t rpc_thread_pool_size) : _thread_pool(std::make_unique<FastOS_ThreadPool>(1024*60)), _transport(std::make_unique<FNET_Transport>(rpc_thread_pool_size)), _orb(std::make_unique<FRT_Supervisor>(_transport.get())), _slobrok_register(std::make_unique<slobrok::api::RegisterAPI>(*_orb, slobrok::ConfiguratorFactory(config_uri))), _slobrok_mirror(std::make_unique<slobrok::api::MirrorAPI>(*_orb, slobrok::ConfiguratorFactory(config_uri))), _target_factory(std::make_unique<RpcTargetFactoryImpl>(*_orb)), _hostname(vespalib::HostName::get()), _rpc_server_port(rpc_server_port), _shutdown(false) { } // TODO make sure init/shutdown is safe for aborted init in comm. mgr. SharedRpcResources::~SharedRpcResources() { if (!_shutdown) { shutdown(); } } void SharedRpcResources::start_server_and_register_slobrok(vespalib::stringref my_handle) { LOG(debug, "Starting main RPC supervisor on port %d with slobrok handle '%s'", _rpc_server_port, vespalib::string(my_handle).c_str()); if (!_orb->Listen(_rpc_server_port)) { throw vespalib::IllegalStateException(vespalib::make_string("Failed to listen to RPC port %d", _rpc_server_port), VESPA_STRLOC); } _transport->Start(_thread_pool.get()); _slobrok_register->registerName(my_handle); wait_until_slobrok_is_ready(); _handle = my_handle; } void SharedRpcResources::wait_until_slobrok_is_ready() { // TODO look more closely at how mbus does its slobrok business while (_slobrok_register->busy() || !_slobrok_mirror->ready()) { // TODO some form of timeout mechanism here, and warning logging to identify SB issues LOG(debug, "Waiting for Slobrok to become ready"); std::this_thread::sleep_for(50ms); } } void SharedRpcResources::shutdown() { assert(!_shutdown); _slobrok_register->unregisterName(_handle); _transport->ShutDown(true); _shutdown = true; } int SharedRpcResources::listen_port() const noexcept { return _orb->GetListenPort(); } const RpcTargetFactory& SharedRpcResources::target_factory() const { return *_target_factory; } } <commit_msg>avoid spurious warnings when shutdown happens before successful listen<commit_after>// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "rpc_target.h" #include "shared_rpc_resources.h" #include <vespa/fastos/thread.h> #include <vespa/fnet/frt/supervisor.h> #include <vespa/fnet/frt/target.h> #include <vespa/fnet/transport.h> #include <vespa/slobrok/sbregister.h> #include <vespa/slobrok/sbmirror.h> #include <vespa/vespalib/util/exceptions.h> #include <vespa/vespalib/util/host_name.h> #include <vespa/vespalib/util/stringfmt.h> #include <cassert> #include <chrono> #include <thread> #include <vespa/log/log.h> LOG_SETUP(".storage.shared_rpc_resources"); using namespace std::chrono_literals; namespace storage::rpc { namespace { class RpcTargetImpl : public RpcTarget { private: FRT_Target* _target; vespalib::string _spec; public: RpcTargetImpl(FRT_Target* target, const vespalib::string& spec) : _target(target), _spec(spec) {} ~RpcTargetImpl() override { _target->SubRef(); } FRT_Target* get() noexcept override { return _target; } bool is_valid() const noexcept override { return _target->IsValid(); } const vespalib::string& spec() const noexcept override { return _spec; } }; } class SharedRpcResources::RpcTargetFactoryImpl : public RpcTargetFactory { private: FRT_Supervisor& _orb; public: RpcTargetFactoryImpl(FRT_Supervisor& orb) : _orb(orb) {} std::unique_ptr<RpcTarget> make_target(const vespalib::string& connection_spec) const override { auto* raw_target = _orb.GetTarget(connection_spec.c_str()); if (raw_target) { return std::make_unique<RpcTargetImpl>(raw_target, connection_spec); } return std::unique_ptr<RpcTarget>(); } }; SharedRpcResources::SharedRpcResources(const config::ConfigUri& config_uri, int rpc_server_port, size_t rpc_thread_pool_size) : _thread_pool(std::make_unique<FastOS_ThreadPool>(1024*60)), _transport(std::make_unique<FNET_Transport>(rpc_thread_pool_size)), _orb(std::make_unique<FRT_Supervisor>(_transport.get())), _slobrok_register(std::make_unique<slobrok::api::RegisterAPI>(*_orb, slobrok::ConfiguratorFactory(config_uri))), _slobrok_mirror(std::make_unique<slobrok::api::MirrorAPI>(*_orb, slobrok::ConfiguratorFactory(config_uri))), _target_factory(std::make_unique<RpcTargetFactoryImpl>(*_orb)), _hostname(vespalib::HostName::get()), _rpc_server_port(rpc_server_port), _shutdown(false) { } // TODO make sure init/shutdown is safe for aborted init in comm. mgr. SharedRpcResources::~SharedRpcResources() { if (!_shutdown) { shutdown(); } } void SharedRpcResources::start_server_and_register_slobrok(vespalib::stringref my_handle) { LOG(debug, "Starting main RPC supervisor on port %d with slobrok handle '%s'", _rpc_server_port, vespalib::string(my_handle).c_str()); if (!_orb->Listen(_rpc_server_port)) { throw vespalib::IllegalStateException(vespalib::make_string("Failed to listen to RPC port %d", _rpc_server_port), VESPA_STRLOC); } _transport->Start(_thread_pool.get()); _slobrok_register->registerName(my_handle); wait_until_slobrok_is_ready(); _handle = my_handle; } void SharedRpcResources::wait_until_slobrok_is_ready() { // TODO look more closely at how mbus does its slobrok business while (_slobrok_register->busy() || !_slobrok_mirror->ready()) { // TODO some form of timeout mechanism here, and warning logging to identify SB issues LOG(debug, "Waiting for Slobrok to become ready"); std::this_thread::sleep_for(50ms); } } void SharedRpcResources::shutdown() { assert(!_shutdown); if (listen_port() > 0) { _slobrok_register->unregisterName(_handle); } _transport->ShutDown(true); _shutdown = true; } int SharedRpcResources::listen_port() const noexcept { return _orb->GetListenPort(); } const RpcTargetFactory& SharedRpcResources::target_factory() const { return *_target_factory; } } <|endoftext|>
<commit_before> /* * Copyright 2006 The Android Open Source Project * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkBlurMaskFilter.h" #include "SkBlurMask.h" #include "SkBuffer.h" #include "SkMaskFilter.h" class SkBlurMaskFilterImpl : public SkMaskFilter { public: SkBlurMaskFilterImpl(SkScalar radius, SkBlurMaskFilter::BlurStyle, uint32_t flags); // overrides from SkMaskFilter virtual SkMask::Format getFormat(); virtual bool filterMask(SkMask* dst, const SkMask& src, const SkMatrix&, SkIPoint* margin); virtual BlurType asABlur(BlurInfo*); // overrides from SkFlattenable virtual Factory getFactory(); virtual void flatten(SkFlattenableWriteBuffer&); static SkFlattenable* CreateProc(SkFlattenableReadBuffer&); private: SkScalar fRadius; SkBlurMaskFilter::BlurStyle fBlurStyle; uint32_t fBlurFlags; SkBlurMaskFilterImpl(SkFlattenableReadBuffer&); typedef SkMaskFilter INHERITED; }; SkMaskFilter* SkBlurMaskFilter::Create(SkScalar radius, SkBlurMaskFilter::BlurStyle style, uint32_t flags) { if (radius <= 0 || (unsigned)style >= SkBlurMaskFilter::kBlurStyleCount || flags > SkBlurMaskFilter::kAll_BlurFlag) { return NULL; } return SkNEW_ARGS(SkBlurMaskFilterImpl, (radius, style, flags)); } /////////////////////////////////////////////////////////////////////////////// SkBlurMaskFilterImpl::SkBlurMaskFilterImpl(SkScalar radius, SkBlurMaskFilter::BlurStyle style, uint32_t flags) : fRadius(radius), fBlurStyle(style), fBlurFlags(flags) { #if 0 fGamma = NULL; if (gammaScale) { fGamma = new U8[256]; if (gammaScale > 0) SkBlurMask::BuildSqrGamma(fGamma, gammaScale); else SkBlurMask::BuildSqrtGamma(fGamma, -gammaScale); } #endif SkASSERT(radius >= 0); SkASSERT((unsigned)style < SkBlurMaskFilter::kBlurStyleCount); SkASSERT(flags <= SkBlurMaskFilter::kAll_BlurFlag); } SkMask::Format SkBlurMaskFilterImpl::getFormat() { return SkMask::kA8_Format; } bool SkBlurMaskFilterImpl::filterMask(SkMask* dst, const SkMask& src, const SkMatrix& matrix, SkIPoint* margin) { SkScalar radius; if (fBlurFlags & SkBlurMaskFilter::kIgnoreTransform_BlurFlag) { radius = fRadius; } else { radius = matrix.mapRadius(fRadius); } // To avoid unseemly allocation requests (esp. for finite platforms like // handset) we limit the radius so something manageable. (as opposed to // a request like 10,000) static const SkScalar MAX_RADIUS = SkIntToScalar(128); radius = SkMinScalar(radius, MAX_RADIUS); SkBlurMask::Quality blurQuality = (fBlurFlags & SkBlurMaskFilter::kHighQuality_BlurFlag) ? SkBlurMask::kHigh_Quality : SkBlurMask::kLow_Quality; return SkBlurMask::Blur(dst, src, radius, (SkBlurMask::Style)fBlurStyle, blurQuality, margin); } SkFlattenable* SkBlurMaskFilterImpl::CreateProc(SkFlattenableReadBuffer& buffer) { return SkNEW_ARGS(SkBlurMaskFilterImpl, (buffer)); } SkFlattenable::Factory SkBlurMaskFilterImpl::getFactory() { return CreateProc; } SkBlurMaskFilterImpl::SkBlurMaskFilterImpl(SkFlattenableReadBuffer& buffer) : SkMaskFilter(buffer) { fRadius = buffer.readScalar(); fBlurStyle = (SkBlurMaskFilter::BlurStyle)buffer.readS32(); fBlurFlags = buffer.readU32() & SkBlurMaskFilter::kAll_BlurFlag; SkASSERT(fRadius >= 0); SkASSERT((unsigned)fBlurStyle < SkBlurMaskFilter::kBlurStyleCount); } void SkBlurMaskFilterImpl::flatten(SkFlattenableWriteBuffer& buffer) { this->INHERITED::flatten(buffer); buffer.writeScalar(fRadius); buffer.write32(fBlurStyle); buffer.write32(fBlurFlags); } static const SkMaskFilter::BlurType gBlurStyle2BlurType[] = { SkMaskFilter::kNormal_BlurType, SkMaskFilter::kSolid_BlurType, SkMaskFilter::kOuter_BlurType, SkMaskFilter::kInner_BlurType, }; SkMaskFilter::BlurType SkBlurMaskFilterImpl::asABlur(BlurInfo* info) { if (info) { info->fRadius = fRadius; info->fIgnoreTransform = SkToBool(fBlurFlags & SkBlurMaskFilter::kIgnoreTransform_BlurFlag); info->fHighQuality = SkToBool(fBlurFlags & SkBlurMaskFilter::kHighQuality_BlurFlag); } return gBlurStyle2BlurType[fBlurStyle]; } /////////////////////////////////////////////////////////////////////////////// static SkFlattenable::Registrar gReg("SkBlurMaskFilter", SkBlurMaskFilterImpl::CreateProc); <commit_msg>Ignore blur margin fix flag for backward bug compatibility. http://codereview.appspot.com/4981046/<commit_after> /* * Copyright 2006 The Android Open Source Project * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkBlurMaskFilter.h" #include "SkBlurMask.h" #include "SkBuffer.h" #include "SkMaskFilter.h" class SkBlurMaskFilterImpl : public SkMaskFilter { public: SkBlurMaskFilterImpl(SkScalar radius, SkBlurMaskFilter::BlurStyle, uint32_t flags); // overrides from SkMaskFilter virtual SkMask::Format getFormat(); virtual bool filterMask(SkMask* dst, const SkMask& src, const SkMatrix&, SkIPoint* margin); virtual BlurType asABlur(BlurInfo*); // overrides from SkFlattenable virtual Factory getFactory(); virtual void flatten(SkFlattenableWriteBuffer&); static SkFlattenable* CreateProc(SkFlattenableReadBuffer&); private: SkScalar fRadius; SkBlurMaskFilter::BlurStyle fBlurStyle; uint32_t fBlurFlags; SkBlurMaskFilterImpl(SkFlattenableReadBuffer&); typedef SkMaskFilter INHERITED; }; SkMaskFilter* SkBlurMaskFilter::Create(SkScalar radius, SkBlurMaskFilter::BlurStyle style, uint32_t flags) { if (radius <= 0 || (unsigned)style >= SkBlurMaskFilter::kBlurStyleCount || flags > SkBlurMaskFilter::kAll_BlurFlag) { return NULL; } return SkNEW_ARGS(SkBlurMaskFilterImpl, (radius, style, flags)); } /////////////////////////////////////////////////////////////////////////////// SkBlurMaskFilterImpl::SkBlurMaskFilterImpl(SkScalar radius, SkBlurMaskFilter::BlurStyle style, uint32_t flags) : fRadius(radius), fBlurStyle(style), fBlurFlags(flags) { #if 0 fGamma = NULL; if (gammaScale) { fGamma = new U8[256]; if (gammaScale > 0) SkBlurMask::BuildSqrGamma(fGamma, gammaScale); else SkBlurMask::BuildSqrtGamma(fGamma, -gammaScale); } #endif SkASSERT(radius >= 0); SkASSERT((unsigned)style < SkBlurMaskFilter::kBlurStyleCount); SkASSERT(flags <= SkBlurMaskFilter::kAll_BlurFlag); } SkMask::Format SkBlurMaskFilterImpl::getFormat() { return SkMask::kA8_Format; } bool SkBlurMaskFilterImpl::filterMask(SkMask* dst, const SkMask& src, const SkMatrix& matrix, SkIPoint* margin) { SkScalar radius; if (fBlurFlags & SkBlurMaskFilter::kIgnoreTransform_BlurFlag) { radius = fRadius; } else { radius = matrix.mapRadius(fRadius); } // To avoid unseemly allocation requests (esp. for finite platforms like // handset) we limit the radius so something manageable. (as opposed to // a request like 10,000) static const SkScalar MAX_RADIUS = SkIntToScalar(128); radius = SkMinScalar(radius, MAX_RADIUS); SkBlurMask::Quality blurQuality = (fBlurFlags & SkBlurMaskFilter::kHighQuality_BlurFlag) ? SkBlurMask::kHigh_Quality : SkBlurMask::kLow_Quality; #if defined(SK_BLUR_MASK_FILTER_IGNORE_MARGIN_FIX) if (SkBlurMask::Blur(dst, src, radius, (SkBlurMask::Style)fBlurStyle, blurQuality)) { if (margin) { // we need to integralize radius for our margin, so take the ceil // just to be safe. margin->set(SkScalarCeil(radius), SkScalarCeil(radius)); } return true; } return false; #else return SkBlurMask::Blur(dst, src, radius, (SkBlurMask::Style)fBlurStyle, blurQuality, margin); #endif } SkFlattenable* SkBlurMaskFilterImpl::CreateProc(SkFlattenableReadBuffer& buffer) { return SkNEW_ARGS(SkBlurMaskFilterImpl, (buffer)); } SkFlattenable::Factory SkBlurMaskFilterImpl::getFactory() { return CreateProc; } SkBlurMaskFilterImpl::SkBlurMaskFilterImpl(SkFlattenableReadBuffer& buffer) : SkMaskFilter(buffer) { fRadius = buffer.readScalar(); fBlurStyle = (SkBlurMaskFilter::BlurStyle)buffer.readS32(); fBlurFlags = buffer.readU32() & SkBlurMaskFilter::kAll_BlurFlag; SkASSERT(fRadius >= 0); SkASSERT((unsigned)fBlurStyle < SkBlurMaskFilter::kBlurStyleCount); } void SkBlurMaskFilterImpl::flatten(SkFlattenableWriteBuffer& buffer) { this->INHERITED::flatten(buffer); buffer.writeScalar(fRadius); buffer.write32(fBlurStyle); buffer.write32(fBlurFlags); } static const SkMaskFilter::BlurType gBlurStyle2BlurType[] = { SkMaskFilter::kNormal_BlurType, SkMaskFilter::kSolid_BlurType, SkMaskFilter::kOuter_BlurType, SkMaskFilter::kInner_BlurType, }; SkMaskFilter::BlurType SkBlurMaskFilterImpl::asABlur(BlurInfo* info) { if (info) { info->fRadius = fRadius; info->fIgnoreTransform = SkToBool(fBlurFlags & SkBlurMaskFilter::kIgnoreTransform_BlurFlag); info->fHighQuality = SkToBool(fBlurFlags & SkBlurMaskFilter::kHighQuality_BlurFlag); } return gBlurStyle2BlurType[fBlurStyle]; } /////////////////////////////////////////////////////////////////////////////// static SkFlattenable::Registrar gReg("SkBlurMaskFilter", SkBlurMaskFilterImpl::CreateProc); <|endoftext|>
<commit_before> /* * Copyright 2006 The Android Open Source Project * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkBlurMaskFilter.h" #include "SkBlurMask.h" #include "SkFlattenableBuffers.h" #include "SkMaskFilter.h" class SkBlurMaskFilterImpl : public SkMaskFilter { public: SkBlurMaskFilterImpl(SkScalar radius, SkBlurMaskFilter::BlurStyle, uint32_t flags); // overrides from SkMaskFilter virtual SkMask::Format getFormat() SK_OVERRIDE; virtual bool filterMask(SkMask* dst, const SkMask& src, const SkMatrix&, SkIPoint* margin) SK_OVERRIDE; virtual BlurType asABlur(BlurInfo*) const SK_OVERRIDE; virtual void setAsABlur(const BlurInfo&) SK_OVERRIDE; virtual void computeFastBounds(const SkRect& src, SkRect* dst) SK_OVERRIDE; SK_DECLARE_PUBLIC_FLATTENABLE_DESERIALIZATION_PROCS(SkBlurMaskFilterImpl) protected: virtual FilterReturn filterRectsToNine(const SkRect[], int count, const SkMatrix&, const SkIRect& clipBounds, NinePatch*) SK_OVERRIDE; private: SkScalar fRadius; SkBlurMaskFilter::BlurStyle fBlurStyle; uint32_t fBlurFlags; SkBlurMaskFilterImpl(SkFlattenableReadBuffer&); virtual void flatten(SkFlattenableWriteBuffer&) const SK_OVERRIDE; typedef SkMaskFilter INHERITED; }; SkMaskFilter* SkBlurMaskFilter::Create(SkScalar radius, SkBlurMaskFilter::BlurStyle style, uint32_t flags) { // use !(radius > 0) instead of radius <= 0 to reject NaN values if (!(radius > 0) || (unsigned)style >= SkBlurMaskFilter::kBlurStyleCount || flags > SkBlurMaskFilter::kAll_BlurFlag) { return NULL; } return SkNEW_ARGS(SkBlurMaskFilterImpl, (radius, style, flags)); } /////////////////////////////////////////////////////////////////////////////// SkBlurMaskFilterImpl::SkBlurMaskFilterImpl(SkScalar radius, SkBlurMaskFilter::BlurStyle style, uint32_t flags) : fRadius(radius), fBlurStyle(style), fBlurFlags(flags) { #if 0 fGamma = NULL; if (gammaScale) { fGamma = new U8[256]; if (gammaScale > 0) SkBlurMask::BuildSqrGamma(fGamma, gammaScale); else SkBlurMask::BuildSqrtGamma(fGamma, -gammaScale); } #endif SkASSERT(radius >= 0); SkASSERT((unsigned)style < SkBlurMaskFilter::kBlurStyleCount); SkASSERT(flags <= SkBlurMaskFilter::kAll_BlurFlag); } SkMask::Format SkBlurMaskFilterImpl::getFormat() { return SkMask::kA8_Format; } bool SkBlurMaskFilterImpl::filterMask(SkMask* dst, const SkMask& src, const SkMatrix& matrix, SkIPoint* margin) { SkScalar radius; if (fBlurFlags & SkBlurMaskFilter::kIgnoreTransform_BlurFlag) { radius = fRadius; } else { radius = matrix.mapRadius(fRadius); } // To avoid unseemly allocation requests (esp. for finite platforms like // handset) we limit the radius so something manageable. (as opposed to // a request like 10,000) static const SkScalar MAX_RADIUS = SkIntToScalar(128); radius = SkMinScalar(radius, MAX_RADIUS); SkBlurMask::Quality blurQuality = (fBlurFlags & SkBlurMaskFilter::kHighQuality_BlurFlag) ? SkBlurMask::kHigh_Quality : SkBlurMask::kLow_Quality; #ifdef SK_BLUR_MASK_SEPARABLE return SkBlurMask::BlurSeparable(dst, src, radius, (SkBlurMask::Style)fBlurStyle, blurQuality, margin); #else return SkBlurMask::Blur(dst, src, radius, (SkBlurMask::Style)fBlurStyle, blurQuality, margin); #endif } #include "SkCanvas.h" static bool drawRectsIntoMask(const SkRect rects[], int count, SkMask* mask) { rects[0].roundOut(&mask->fBounds); mask->fRowBytes = SkAlign4(mask->fBounds.width()); mask->fFormat = SkMask::kA8_Format; size_t size = mask->computeImageSize(); mask->fImage = SkMask::AllocImage(size); if (NULL == mask->fImage) { return false; } sk_bzero(mask->fImage, size); SkBitmap bitmap; bitmap.setConfig(SkBitmap::kA8_Config, mask->fBounds.width(), mask->fBounds.height(), mask->fRowBytes); bitmap.setPixels(mask->fImage); SkCanvas canvas(bitmap); canvas.translate(-SkIntToScalar(mask->fBounds.left()), -SkIntToScalar(mask->fBounds.top())); SkPaint paint; paint.setAntiAlias(true); if (1 == count) { canvas.drawRect(rects[0], paint); } else { // todo: do I need a fast way to do this? SkPath path; path.addRect(rects[0]); path.addRect(rects[1]); path.setFillType(SkPath::kEvenOdd_FillType); canvas.drawPath(path, paint); } return true; } static bool rect_exceeds(const SkRect& r, SkScalar v) { return r.fLeft < -v || r.fTop < -v || r.fRight > v || r.fBottom > v || r.width() > v || r.height() > v; } SkMaskFilter::FilterReturn SkBlurMaskFilterImpl::filterRectsToNine(const SkRect rects[], int count, const SkMatrix& matrix, const SkIRect& clipBounds, NinePatch* patch) { if (count < 1 || count > 2) { return kUnimplemented_FilterReturn; } // TODO: take clipBounds into account to limit our coordinates up front // for now, just skip too-large src rects (to take the old code path). if (rect_exceeds(rects[0], SkIntToScalar(32767))) { return kUnimplemented_FilterReturn; } SkIPoint margin; SkMask srcM, dstM; rects[0].roundOut(&srcM.fBounds); srcM.fImage = NULL; srcM.fFormat = SkMask::kA8_Format; srcM.fRowBytes = 0; if (!this->filterMask(&dstM, srcM, matrix, &margin)) { return kFalse_FilterReturn; } /* * smallR is the smallest version of 'rect' that will still guarantee that * we get the same blur results on all edges, plus 1 center row/col that is * representative of the extendible/stretchable edges of the ninepatch. * Since our actual edge may be fractional we inset 1 more to be sure we * don't miss any interior blur. * x is an added pixel of blur, and { and } are the (fractional) edge * pixels from the original rect. * * x x { x x .... x x } x x * * Thus, in this case, we inset by a total of 5 (on each side) beginning * with our outer-rect (dstM.fBounds) */ SkRect smallR[2]; SkIPoint center; // +2 is from +1 for each edge (to account for possible fractional edges int smallW = dstM.fBounds.width() - srcM.fBounds.width() + 2; int smallH = dstM.fBounds.height() - srcM.fBounds.height() + 2; SkIRect innerIR; if (1 == count) { innerIR = srcM.fBounds; center.set(smallW, smallH); } else { SkASSERT(2 == count); rects[1].roundIn(&innerIR); center.set(smallW + (innerIR.left() - srcM.fBounds.left()), smallH + (innerIR.top() - srcM.fBounds.top())); } // +1 so we get a clean, stretchable, center row/col smallW += 1; smallH += 1; // we want the inset amounts to be integral, so we don't change any // fractional phase on the fRight or fBottom of our smallR. const SkScalar dx = SkIntToScalar(innerIR.width() - smallW); const SkScalar dy = SkIntToScalar(innerIR.height() - smallH); if (dx < 0 || dy < 0) { // we're too small, relative to our blur, to break into nine-patch, // so we ask to have our normal filterMask() be called. return kUnimplemented_FilterReturn; } smallR[0].set(rects[0].left(), rects[0].top(), rects[0].right() - dx, rects[0].bottom() - dy); SkASSERT(!smallR[0].isEmpty()); if (2 == count) { smallR[1].set(rects[1].left(), rects[1].top(), rects[1].right() - dx, rects[1].bottom() - dy); SkASSERT(!smallR[1].isEmpty()); } if (!drawRectsIntoMask(smallR, count, &srcM)) { return kFalse_FilterReturn; } SkAutoMaskFreeImage amf(srcM.fImage); if (!this->filterMask(&patch->fMask, srcM, matrix, &margin)) { return kFalse_FilterReturn; } patch->fMask.fBounds.offsetTo(0, 0); patch->fOuterRect = dstM.fBounds; patch->fCenter = center; return kTrue_FilterReturn; } void SkBlurMaskFilterImpl::computeFastBounds(const SkRect& src, SkRect* dst) { dst->set(src.fLeft - fRadius, src.fTop - fRadius, src.fRight + fRadius, src.fBottom + fRadius); } SkBlurMaskFilterImpl::SkBlurMaskFilterImpl(SkFlattenableReadBuffer& buffer) : SkMaskFilter(buffer) { fRadius = buffer.readScalar(); fBlurStyle = (SkBlurMaskFilter::BlurStyle)buffer.readInt(); fBlurFlags = buffer.readUInt() & SkBlurMaskFilter::kAll_BlurFlag; SkASSERT(fRadius >= 0); SkASSERT((unsigned)fBlurStyle < SkBlurMaskFilter::kBlurStyleCount); } void SkBlurMaskFilterImpl::flatten(SkFlattenableWriteBuffer& buffer) const { this->INHERITED::flatten(buffer); buffer.writeScalar(fRadius); buffer.writeInt(fBlurStyle); buffer.writeUInt(fBlurFlags); } static const SkMaskFilter::BlurType gBlurStyle2BlurType[] = { SkMaskFilter::kNormal_BlurType, SkMaskFilter::kSolid_BlurType, SkMaskFilter::kOuter_BlurType, SkMaskFilter::kInner_BlurType, }; SkMaskFilter::BlurType SkBlurMaskFilterImpl::asABlur(BlurInfo* info) const { if (info) { info->fRadius = fRadius; info->fIgnoreTransform = SkToBool(fBlurFlags & SkBlurMaskFilter::kIgnoreTransform_BlurFlag); info->fHighQuality = SkToBool(fBlurFlags & SkBlurMaskFilter::kHighQuality_BlurFlag); } return gBlurStyle2BlurType[fBlurStyle]; } void SkBlurMaskFilterImpl::setAsABlur(const BlurInfo& info) { fRadius = info.fRadius; fBlurFlags = (fBlurFlags & ~(SkBlurMaskFilter::kIgnoreTransform_BlurFlag | SkBlurMaskFilter::kHighQuality_BlurFlag)) | (info.fIgnoreTransform ? SkBlurMaskFilter::kIgnoreTransform_BlurFlag : 0) | (info.fHighQuality ? SkBlurMaskFilter::kHighQuality_BlurFlag : 0); } SK_DEFINE_FLATTENABLE_REGISTRAR_GROUP_START(SkBlurMaskFilter) SK_DEFINE_FLATTENABLE_REGISTRAR_ENTRY(SkBlurMaskFilterImpl) SK_DEFINE_FLATTENABLE_REGISTRAR_GROUP_END <commit_msg>Turn on the separable blur (release the hounds!). This will require rebaselines of the following Skia tests: tilemodes, texteffects, shadows, drawlooper, drawbitmaprect, circles, blurrect_grad, blurrect, blurs, drawbitmapmatrix (max. pixel change in 8888 is 5).<commit_after> /* * Copyright 2006 The Android Open Source Project * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkBlurMaskFilter.h" #include "SkBlurMask.h" #include "SkFlattenableBuffers.h" #include "SkMaskFilter.h" class SkBlurMaskFilterImpl : public SkMaskFilter { public: SkBlurMaskFilterImpl(SkScalar radius, SkBlurMaskFilter::BlurStyle, uint32_t flags); // overrides from SkMaskFilter virtual SkMask::Format getFormat() SK_OVERRIDE; virtual bool filterMask(SkMask* dst, const SkMask& src, const SkMatrix&, SkIPoint* margin) SK_OVERRIDE; virtual BlurType asABlur(BlurInfo*) const SK_OVERRIDE; virtual void setAsABlur(const BlurInfo&) SK_OVERRIDE; virtual void computeFastBounds(const SkRect& src, SkRect* dst) SK_OVERRIDE; SK_DECLARE_PUBLIC_FLATTENABLE_DESERIALIZATION_PROCS(SkBlurMaskFilterImpl) protected: virtual FilterReturn filterRectsToNine(const SkRect[], int count, const SkMatrix&, const SkIRect& clipBounds, NinePatch*) SK_OVERRIDE; private: SkScalar fRadius; SkBlurMaskFilter::BlurStyle fBlurStyle; uint32_t fBlurFlags; SkBlurMaskFilterImpl(SkFlattenableReadBuffer&); virtual void flatten(SkFlattenableWriteBuffer&) const SK_OVERRIDE; typedef SkMaskFilter INHERITED; }; SkMaskFilter* SkBlurMaskFilter::Create(SkScalar radius, SkBlurMaskFilter::BlurStyle style, uint32_t flags) { // use !(radius > 0) instead of radius <= 0 to reject NaN values if (!(radius > 0) || (unsigned)style >= SkBlurMaskFilter::kBlurStyleCount || flags > SkBlurMaskFilter::kAll_BlurFlag) { return NULL; } return SkNEW_ARGS(SkBlurMaskFilterImpl, (radius, style, flags)); } /////////////////////////////////////////////////////////////////////////////// SkBlurMaskFilterImpl::SkBlurMaskFilterImpl(SkScalar radius, SkBlurMaskFilter::BlurStyle style, uint32_t flags) : fRadius(radius), fBlurStyle(style), fBlurFlags(flags) { #if 0 fGamma = NULL; if (gammaScale) { fGamma = new U8[256]; if (gammaScale > 0) SkBlurMask::BuildSqrGamma(fGamma, gammaScale); else SkBlurMask::BuildSqrtGamma(fGamma, -gammaScale); } #endif SkASSERT(radius >= 0); SkASSERT((unsigned)style < SkBlurMaskFilter::kBlurStyleCount); SkASSERT(flags <= SkBlurMaskFilter::kAll_BlurFlag); } SkMask::Format SkBlurMaskFilterImpl::getFormat() { return SkMask::kA8_Format; } bool SkBlurMaskFilterImpl::filterMask(SkMask* dst, const SkMask& src, const SkMatrix& matrix, SkIPoint* margin) { SkScalar radius; if (fBlurFlags & SkBlurMaskFilter::kIgnoreTransform_BlurFlag) { radius = fRadius; } else { radius = matrix.mapRadius(fRadius); } // To avoid unseemly allocation requests (esp. for finite platforms like // handset) we limit the radius so something manageable. (as opposed to // a request like 10,000) static const SkScalar MAX_RADIUS = SkIntToScalar(128); radius = SkMinScalar(radius, MAX_RADIUS); SkBlurMask::Quality blurQuality = (fBlurFlags & SkBlurMaskFilter::kHighQuality_BlurFlag) ? SkBlurMask::kHigh_Quality : SkBlurMask::kLow_Quality; #ifndef SK_DISABLE_SEPARABLE_MASK_BLUR return SkBlurMask::BlurSeparable(dst, src, radius, (SkBlurMask::Style)fBlurStyle, blurQuality, margin); #else return SkBlurMask::Blur(dst, src, radius, (SkBlurMask::Style)fBlurStyle, blurQuality, margin); #endif } #include "SkCanvas.h" static bool drawRectsIntoMask(const SkRect rects[], int count, SkMask* mask) { rects[0].roundOut(&mask->fBounds); mask->fRowBytes = SkAlign4(mask->fBounds.width()); mask->fFormat = SkMask::kA8_Format; size_t size = mask->computeImageSize(); mask->fImage = SkMask::AllocImage(size); if (NULL == mask->fImage) { return false; } sk_bzero(mask->fImage, size); SkBitmap bitmap; bitmap.setConfig(SkBitmap::kA8_Config, mask->fBounds.width(), mask->fBounds.height(), mask->fRowBytes); bitmap.setPixels(mask->fImage); SkCanvas canvas(bitmap); canvas.translate(-SkIntToScalar(mask->fBounds.left()), -SkIntToScalar(mask->fBounds.top())); SkPaint paint; paint.setAntiAlias(true); if (1 == count) { canvas.drawRect(rects[0], paint); } else { // todo: do I need a fast way to do this? SkPath path; path.addRect(rects[0]); path.addRect(rects[1]); path.setFillType(SkPath::kEvenOdd_FillType); canvas.drawPath(path, paint); } return true; } static bool rect_exceeds(const SkRect& r, SkScalar v) { return r.fLeft < -v || r.fTop < -v || r.fRight > v || r.fBottom > v || r.width() > v || r.height() > v; } SkMaskFilter::FilterReturn SkBlurMaskFilterImpl::filterRectsToNine(const SkRect rects[], int count, const SkMatrix& matrix, const SkIRect& clipBounds, NinePatch* patch) { if (count < 1 || count > 2) { return kUnimplemented_FilterReturn; } // TODO: take clipBounds into account to limit our coordinates up front // for now, just skip too-large src rects (to take the old code path). if (rect_exceeds(rects[0], SkIntToScalar(32767))) { return kUnimplemented_FilterReturn; } SkIPoint margin; SkMask srcM, dstM; rects[0].roundOut(&srcM.fBounds); srcM.fImage = NULL; srcM.fFormat = SkMask::kA8_Format; srcM.fRowBytes = 0; if (!this->filterMask(&dstM, srcM, matrix, &margin)) { return kFalse_FilterReturn; } /* * smallR is the smallest version of 'rect' that will still guarantee that * we get the same blur results on all edges, plus 1 center row/col that is * representative of the extendible/stretchable edges of the ninepatch. * Since our actual edge may be fractional we inset 1 more to be sure we * don't miss any interior blur. * x is an added pixel of blur, and { and } are the (fractional) edge * pixels from the original rect. * * x x { x x .... x x } x x * * Thus, in this case, we inset by a total of 5 (on each side) beginning * with our outer-rect (dstM.fBounds) */ SkRect smallR[2]; SkIPoint center; // +2 is from +1 for each edge (to account for possible fractional edges int smallW = dstM.fBounds.width() - srcM.fBounds.width() + 2; int smallH = dstM.fBounds.height() - srcM.fBounds.height() + 2; SkIRect innerIR; if (1 == count) { innerIR = srcM.fBounds; center.set(smallW, smallH); } else { SkASSERT(2 == count); rects[1].roundIn(&innerIR); center.set(smallW + (innerIR.left() - srcM.fBounds.left()), smallH + (innerIR.top() - srcM.fBounds.top())); } // +1 so we get a clean, stretchable, center row/col smallW += 1; smallH += 1; // we want the inset amounts to be integral, so we don't change any // fractional phase on the fRight or fBottom of our smallR. const SkScalar dx = SkIntToScalar(innerIR.width() - smallW); const SkScalar dy = SkIntToScalar(innerIR.height() - smallH); if (dx < 0 || dy < 0) { // we're too small, relative to our blur, to break into nine-patch, // so we ask to have our normal filterMask() be called. return kUnimplemented_FilterReturn; } smallR[0].set(rects[0].left(), rects[0].top(), rects[0].right() - dx, rects[0].bottom() - dy); SkASSERT(!smallR[0].isEmpty()); if (2 == count) { smallR[1].set(rects[1].left(), rects[1].top(), rects[1].right() - dx, rects[1].bottom() - dy); SkASSERT(!smallR[1].isEmpty()); } if (!drawRectsIntoMask(smallR, count, &srcM)) { return kFalse_FilterReturn; } SkAutoMaskFreeImage amf(srcM.fImage); if (!this->filterMask(&patch->fMask, srcM, matrix, &margin)) { return kFalse_FilterReturn; } patch->fMask.fBounds.offsetTo(0, 0); patch->fOuterRect = dstM.fBounds; patch->fCenter = center; return kTrue_FilterReturn; } void SkBlurMaskFilterImpl::computeFastBounds(const SkRect& src, SkRect* dst) { dst->set(src.fLeft - fRadius, src.fTop - fRadius, src.fRight + fRadius, src.fBottom + fRadius); } SkBlurMaskFilterImpl::SkBlurMaskFilterImpl(SkFlattenableReadBuffer& buffer) : SkMaskFilter(buffer) { fRadius = buffer.readScalar(); fBlurStyle = (SkBlurMaskFilter::BlurStyle)buffer.readInt(); fBlurFlags = buffer.readUInt() & SkBlurMaskFilter::kAll_BlurFlag; SkASSERT(fRadius >= 0); SkASSERT((unsigned)fBlurStyle < SkBlurMaskFilter::kBlurStyleCount); } void SkBlurMaskFilterImpl::flatten(SkFlattenableWriteBuffer& buffer) const { this->INHERITED::flatten(buffer); buffer.writeScalar(fRadius); buffer.writeInt(fBlurStyle); buffer.writeUInt(fBlurFlags); } static const SkMaskFilter::BlurType gBlurStyle2BlurType[] = { SkMaskFilter::kNormal_BlurType, SkMaskFilter::kSolid_BlurType, SkMaskFilter::kOuter_BlurType, SkMaskFilter::kInner_BlurType, }; SkMaskFilter::BlurType SkBlurMaskFilterImpl::asABlur(BlurInfo* info) const { if (info) { info->fRadius = fRadius; info->fIgnoreTransform = SkToBool(fBlurFlags & SkBlurMaskFilter::kIgnoreTransform_BlurFlag); info->fHighQuality = SkToBool(fBlurFlags & SkBlurMaskFilter::kHighQuality_BlurFlag); } return gBlurStyle2BlurType[fBlurStyle]; } void SkBlurMaskFilterImpl::setAsABlur(const BlurInfo& info) { fRadius = info.fRadius; fBlurFlags = (fBlurFlags & ~(SkBlurMaskFilter::kIgnoreTransform_BlurFlag | SkBlurMaskFilter::kHighQuality_BlurFlag)) | (info.fIgnoreTransform ? SkBlurMaskFilter::kIgnoreTransform_BlurFlag : 0) | (info.fHighQuality ? SkBlurMaskFilter::kHighQuality_BlurFlag : 0); } SK_DEFINE_FLATTENABLE_REGISTRAR_GROUP_START(SkBlurMaskFilter) SK_DEFINE_FLATTENABLE_REGISTRAR_ENTRY(SkBlurMaskFilterImpl) SK_DEFINE_FLATTENABLE_REGISTRAR_GROUP_END <|endoftext|>
<commit_before>#include <xzero/executor/NativeScheduler.h> #include <xzero/RuntimeError.h> #include <xzero/WallClock.h> #include <xzero/sysconfig.h> #include <algorithm> #include <vector> #include <sys/types.h> #include <sys/time.h> #include <sys/select.h> #include <unistd.h> #include <fcntl.h> namespace xzero { #define PIPE_READ_END 0 #define PIPE_WRITE_END 1 /** * XXX * - registering a key should be *ONESHOT* and *Edge Triggered* * - rename NativeScheduler to SimpleScheduler * * XXX LinuxScheduler * - epoll fuer i/o notification * - eventfd for wakeup implementation * - timerfd_* for timer impl */ NativeScheduler::NativeScheduler( std::function<void(const std::exception&)> errorLogger, WallClock* clock, std::function<void()> preInvoke, std::function<void()> postInvoke) : Scheduler(std::move(errorLogger)), clock_(clock ? clock : WallClock::system()), lock_(), wakeupPipe_(), onPreInvokePending_(preInvoke), onPostInvokePending_(postInvoke) { if (pipe(wakeupPipe_) < 0) { throw SYSTEM_ERROR(errno); } fcntl(wakeupPipe_[0], F_SETFL, O_NONBLOCK); fcntl(wakeupPipe_[1], F_SETFL, O_NONBLOCK); } NativeScheduler::NativeScheduler( std::function<void(const std::exception&)> errorLogger, WallClock* clock) : NativeScheduler(errorLogger, clock, nullptr, nullptr) { } NativeScheduler::NativeScheduler() : NativeScheduler(nullptr, nullptr, nullptr, nullptr) { } NativeScheduler::~NativeScheduler() { ::close(wakeupPipe_[PIPE_READ_END]); ::close(wakeupPipe_[PIPE_WRITE_END]); } void NativeScheduler::execute(Task&& task) { { std::lock_guard<std::mutex> lk(lock_); tasks_.push_back(task); } breakLoop(); } std::string NativeScheduler::toString() const { return "NativeScheduler"; } Scheduler::HandleRef NativeScheduler::executeAfter(TimeSpan delay, Task task) { auto onCancel = [this](Handle* handle) { removeFromTimersList(handle); }; return insertIntoTimersList(clock_->get() + delay, std::make_shared<Handle>(task, onCancel)); } Scheduler::HandleRef NativeScheduler::executeAt(DateTime when, Task task) { return insertIntoTimersList( when, std::make_shared<Handle>(task, std::bind(&NativeScheduler::removeFromTimersList, this, std::placeholders::_1))); } Scheduler::HandleRef NativeScheduler::insertIntoTimersList(DateTime dt, HandleRef handle) { Timer t = { dt, handle }; std::lock_guard<std::mutex> lk(lock_); auto i = timers_.end(); auto e = timers_.begin(); while (i != e) { i--; const Timer& current = *i; if (current.when >= t.when) { timers_.insert(i, t); return handle; } } timers_.push_front(t); return handle; } void NativeScheduler::removeFromTimersList(Handle* handle) { std::lock_guard<std::mutex> lk(lock_); for (auto i = timers_.begin(), e = timers_.end(); i != e; ++i) { if (i->handle.get() == handle) { timers_.erase(i); break; } } } void NativeScheduler::collectTimeouts() { const DateTime now = clock_->get(); std::lock_guard<std::mutex> lk(lock_); for (;;) { if (timers_.empty()) break; const Timer& job = timers_.front(); if (job.when > now) break; tasks_.push_back(job.handle->getAction()); timers_.pop_front(); } } inline Scheduler::HandleRef registerInterest( std::mutex* registryLock, std::list<std::pair<int, Scheduler::HandleRef>>* registry, int fd, Executor::Task task) { auto onCancel = [=](Scheduler::Handle* h) { std::lock_guard<std::mutex> lk(*registryLock); for (auto i: *registry) { if (i.second.get() == h) { return registry->remove(i); } } }; std::lock_guard<std::mutex> lk(*registryLock); auto handle = std::make_shared<Scheduler::Handle>(task, onCancel); registry->push_back(std::make_pair(fd, handle)); return handle; } Scheduler::HandleRef NativeScheduler::executeOnReadable(int fd, Task task) { return registerInterest(&lock_, &readers_, fd, task); } Scheduler::HandleRef NativeScheduler::executeOnWritable(int fd, Task task) { return registerInterest(&lock_, &writers_, fd, task); } inline void collectActiveHandles( std::list<std::pair<int, Scheduler::HandleRef>>* interests, fd_set* fdset, std::vector<Scheduler::HandleRef>* result) { auto i = interests->begin(); auto e = interests->end(); while (i != e) { if (FD_ISSET(i->first, fdset)) { result->push_back(i->second); i = interests->erase(i); } else { i++; } } } size_t NativeScheduler::timerCount() { std::lock_guard<std::mutex> lk(lock_); return timers_.size(); } size_t NativeScheduler::readerCount() { std::lock_guard<std::mutex> lk(lock_); return readers_.size(); } size_t NativeScheduler::writerCount() { std::lock_guard<std::mutex> lk(lock_); return writers_.size(); } void NativeScheduler::runLoopOnce() { fd_set input, output, error; FD_ZERO(&input); FD_ZERO(&output); FD_ZERO(&error); int wmark = 0; timeval tv; { std::lock_guard<std::mutex> lk(lock_); for (auto i: readers_) { FD_SET(i.first, &input); if (i.first > wmark) { wmark = i.first; } } for (auto i: writers_) { FD_SET(i.first, &output); if (i.first > wmark) { wmark = i.first; } } const TimeSpan nextTimeout = !tasks_.empty() ? TimeSpan::Zero : !timers_.empty() ? timers_.front().when - clock_->get() : TimeSpan::fromSeconds(4); tv.tv_sec = static_cast<time_t>(nextTimeout.totalSeconds()), tv.tv_usec = nextTimeout.microseconds(); } FD_SET(wakeupPipe_[PIPE_READ_END], &input); int rv = ::select(wmark + 1, &input, &output, &error, &tv); if (rv < 0 && errno != EINTR) throw SYSTEM_ERROR(errno); if (FD_ISSET(wakeupPipe_[PIPE_READ_END], &input)) { bool consumeMore = true; while (consumeMore) { char buf[sizeof(int) * 128]; consumeMore = ::read(wakeupPipe_[PIPE_READ_END], buf, sizeof(buf)) > 0; } } collectTimeouts(); std::vector<HandleRef> activeHandles; activeHandles.reserve(rv); std::deque<Task> activeTasks; { std::lock_guard<std::mutex> lk(lock_); collectActiveHandles(&readers_, &input, &activeHandles); collectActiveHandles(&writers_, &output, &activeHandles); activeTasks = std::move(tasks_); } safeCall(onPreInvokePending_); safeCallEach(activeHandles); safeCallEach(activeTasks); safeCall(onPostInvokePending_); } void NativeScheduler::breakLoop() { int dummy = 42; ::write(wakeupPipe_[PIPE_WRITE_END], &dummy, sizeof(dummy)); } } // namespace xzero <commit_msg>select() better EINTR safety<commit_after>#include <xzero/executor/NativeScheduler.h> #include <xzero/RuntimeError.h> #include <xzero/WallClock.h> #include <xzero/sysconfig.h> #include <algorithm> #include <vector> #include <sys/types.h> #include <sys/time.h> #include <sys/select.h> #include <unistd.h> #include <fcntl.h> namespace xzero { #define PIPE_READ_END 0 #define PIPE_WRITE_END 1 /** * XXX * - registering a key should be *ONESHOT* and *Edge Triggered* * - rename NativeScheduler to SimpleScheduler * * XXX LinuxScheduler * - epoll fuer i/o notification * - eventfd for wakeup implementation * - timerfd_* for timer impl */ NativeScheduler::NativeScheduler( std::function<void(const std::exception&)> errorLogger, WallClock* clock, std::function<void()> preInvoke, std::function<void()> postInvoke) : Scheduler(std::move(errorLogger)), clock_(clock ? clock : WallClock::system()), lock_(), wakeupPipe_(), onPreInvokePending_(preInvoke), onPostInvokePending_(postInvoke) { if (pipe(wakeupPipe_) < 0) { throw SYSTEM_ERROR(errno); } fcntl(wakeupPipe_[0], F_SETFL, O_NONBLOCK); fcntl(wakeupPipe_[1], F_SETFL, O_NONBLOCK); } NativeScheduler::NativeScheduler( std::function<void(const std::exception&)> errorLogger, WallClock* clock) : NativeScheduler(errorLogger, clock, nullptr, nullptr) { } NativeScheduler::NativeScheduler() : NativeScheduler(nullptr, nullptr, nullptr, nullptr) { } NativeScheduler::~NativeScheduler() { ::close(wakeupPipe_[PIPE_READ_END]); ::close(wakeupPipe_[PIPE_WRITE_END]); } void NativeScheduler::execute(Task&& task) { { std::lock_guard<std::mutex> lk(lock_); tasks_.push_back(task); } breakLoop(); } std::string NativeScheduler::toString() const { return "NativeScheduler"; } Scheduler::HandleRef NativeScheduler::executeAfter(TimeSpan delay, Task task) { auto onCancel = [this](Handle* handle) { removeFromTimersList(handle); }; return insertIntoTimersList(clock_->get() + delay, std::make_shared<Handle>(task, onCancel)); } Scheduler::HandleRef NativeScheduler::executeAt(DateTime when, Task task) { return insertIntoTimersList( when, std::make_shared<Handle>(task, std::bind(&NativeScheduler::removeFromTimersList, this, std::placeholders::_1))); } Scheduler::HandleRef NativeScheduler::insertIntoTimersList(DateTime dt, HandleRef handle) { Timer t = { dt, handle }; std::lock_guard<std::mutex> lk(lock_); auto i = timers_.end(); auto e = timers_.begin(); while (i != e) { i--; const Timer& current = *i; if (current.when >= t.when) { timers_.insert(i, t); return handle; } } timers_.push_front(t); return handle; } void NativeScheduler::removeFromTimersList(Handle* handle) { std::lock_guard<std::mutex> lk(lock_); for (auto i = timers_.begin(), e = timers_.end(); i != e; ++i) { if (i->handle.get() == handle) { timers_.erase(i); break; } } } void NativeScheduler::collectTimeouts() { const DateTime now = clock_->get(); std::lock_guard<std::mutex> lk(lock_); for (;;) { if (timers_.empty()) break; const Timer& job = timers_.front(); if (job.when > now) break; tasks_.push_back(job.handle->getAction()); timers_.pop_front(); } } inline Scheduler::HandleRef registerInterest( std::mutex* registryLock, std::list<std::pair<int, Scheduler::HandleRef>>* registry, int fd, Executor::Task task) { auto onCancel = [=](Scheduler::Handle* h) { std::lock_guard<std::mutex> lk(*registryLock); for (auto i: *registry) { if (i.second.get() == h) { return registry->remove(i); } } }; std::lock_guard<std::mutex> lk(*registryLock); auto handle = std::make_shared<Scheduler::Handle>(task, onCancel); registry->push_back(std::make_pair(fd, handle)); return handle; } Scheduler::HandleRef NativeScheduler::executeOnReadable(int fd, Task task) { return registerInterest(&lock_, &readers_, fd, task); } Scheduler::HandleRef NativeScheduler::executeOnWritable(int fd, Task task) { return registerInterest(&lock_, &writers_, fd, task); } inline void collectActiveHandles( std::list<std::pair<int, Scheduler::HandleRef>>* interests, fd_set* fdset, std::vector<Scheduler::HandleRef>* result) { auto i = interests->begin(); auto e = interests->end(); while (i != e) { if (FD_ISSET(i->first, fdset)) { result->push_back(i->second); i = interests->erase(i); } else { i++; } } } size_t NativeScheduler::timerCount() { std::lock_guard<std::mutex> lk(lock_); return timers_.size(); } size_t NativeScheduler::readerCount() { std::lock_guard<std::mutex> lk(lock_); return readers_.size(); } size_t NativeScheduler::writerCount() { std::lock_guard<std::mutex> lk(lock_); return writers_.size(); } void NativeScheduler::runLoopOnce() { fd_set input, output, error; FD_ZERO(&input); FD_ZERO(&output); FD_ZERO(&error); int wmark = 0; timeval tv; { std::lock_guard<std::mutex> lk(lock_); for (auto i: readers_) { FD_SET(i.first, &input); if (i.first > wmark) { wmark = i.first; } } for (auto i: writers_) { FD_SET(i.first, &output); if (i.first > wmark) { wmark = i.first; } } const TimeSpan nextTimeout = !tasks_.empty() ? TimeSpan::Zero : !timers_.empty() ? timers_.front().when - clock_->get() : TimeSpan::fromSeconds(4); tv.tv_sec = static_cast<time_t>(nextTimeout.totalSeconds()), tv.tv_usec = nextTimeout.microseconds(); } FD_SET(wakeupPipe_[PIPE_READ_END], &input); int rv; do rv = ::select(wmark + 1, &input, &output, &error, &tv); while (rv < 0 && errno == EINTR); if (rv < 0) throw SYSTEM_ERROR(errno); if (FD_ISSET(wakeupPipe_[PIPE_READ_END], &input)) { bool consumeMore = true; while (consumeMore) { char buf[sizeof(int) * 128]; consumeMore = ::read(wakeupPipe_[PIPE_READ_END], buf, sizeof(buf)) > 0; } } collectTimeouts(); std::vector<HandleRef> activeHandles; activeHandles.reserve(rv); std::deque<Task> activeTasks; { std::lock_guard<std::mutex> lk(lock_); collectActiveHandles(&readers_, &input, &activeHandles); collectActiveHandles(&writers_, &output, &activeHandles); activeTasks = std::move(tasks_); } safeCall(onPreInvokePending_); safeCallEach(activeHandles); safeCallEach(activeTasks); safeCall(onPostInvokePending_); } void NativeScheduler::breakLoop() { int dummy = 42; ::write(wakeupPipe_[PIPE_WRITE_END], &dummy, sizeof(dummy)); } } // namespace xzero <|endoftext|>
<commit_before>/************************************************************************************ * Copyright (C) 2014-2016 by Savoir-faire Linux * * Author : Emmanuel Lepage Vallee <[email protected]> * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Lesser General Public * * License as published by the Free Software Foundation; either * * version 2.1 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * * Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public * * License along with this library; if not, write to the Free Software * * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * ***********************************************************************************/ #include "fallbackpersoncollection.h" //Qt #include <QtCore/QFile> #include <QtCore/QDir> #include <QtCore/QHash> #include <QtCore/QTimer> #include <QtCore/QUrl> #include <QtCore/QCryptographicHash> #include <QtCore/QStandardPaths> //Ring #include "person.h" #include "personmodel.h" #include "private/vcardutils.h" #include "contactmethod.h" #include "collectioneditor.h" #include "globalinstances.h" #include "interfaces/pixmapmanipulatori.h" #include "interfaces/actionextenderi.h" #include "interfaces/itemmodelstateserializeri.h" #include "private/threadworker.h" class FallbackPersonBackendEditor final : public CollectionEditor<Person> { public: FallbackPersonBackendEditor(CollectionMediator<Person>* m, const QString& path) : CollectionEditor<Person>(m),m_Path(path) {} virtual bool save ( const Person* item ) override; virtual bool remove ( const Person* item ) override; virtual bool edit ( Person* item ) override; virtual bool addNew ( Person* item ) override; virtual bool addExisting( const Person* item ) override; QVector<Person*> m_lItems; QString m_Path ; QHash<const Person*,QString> m_hPaths; private: virtual QVector<Person*> items() const override; }; class FallbackPersonCollectionPrivate final : public QObject { Q_OBJECT public: FallbackPersonCollectionPrivate(FallbackPersonCollection* parent, CollectionMediator<Person>* mediator, const QString& path); CollectionMediator<Person>* m_pMediator; QString m_Path ; QString m_Name ; FallbackPersonCollection* q_ptr; public Q_SLOTS: void loadAsync(); }; FallbackPersonCollectionPrivate::FallbackPersonCollectionPrivate(FallbackPersonCollection* parent, CollectionMediator<Person>* mediator, const QString& path) : q_ptr(parent), m_pMediator(mediator), m_Path(path) { //Default to somewhere ~/.local/share if (m_Path.isEmpty()) { m_Path = (QStandardPaths::writableLocation(QStandardPaths::DataLocation)) + "/vCard/"; static_cast<FallbackPersonBackendEditor*>(q_ptr->editor<Person>())->m_Path = m_Path; } //Make sure the directory exists so that saving new contacts there doesn't fail if (!QDir().mkpath(m_Path)) qWarning() << "cannot create path for fallbackcollection: " << m_Path; m_Name = path.split('/').last(); if (m_Name.size()) m_Name[0] = m_Name[0].toUpper(); else m_Name = "vCard"; } FallbackPersonCollection::FallbackPersonCollection(CollectionMediator<Person>* mediator, const QString& path, FallbackPersonCollection* parent) : CollectionInterface(new FallbackPersonBackendEditor(mediator,path),parent),d_ptr(new FallbackPersonCollectionPrivate(this,mediator,path)) { } FallbackPersonCollection::~FallbackPersonCollection() { delete d_ptr; } bool FallbackPersonBackendEditor::save(const Person* item) { if (!item) return false; //An UID is required if (item->uid().isEmpty()) { QCryptographicHash hash(QCryptographicHash::Sha1); for (ContactMethod* n : item->phoneNumbers()) hash.addData(n->uri().toLatin1()); hash.addData(item->formattedName().toLatin1()); QByteArray random; for (int i=0;i<5;i++) random.append(QChar((char)(rand()%255))); hash.addData(random); const_cast<Person*>(item)->setUid(hash.result().toHex()); } QFile file(m_Path+'/'+item->uid()+".vcf"); file.open(QIODevice::WriteOnly); file.write(item->toVCard({})); file.close(); return true; } bool FallbackPersonBackendEditor::remove(const Person* item) { if (!item) return false; QString path = m_hPaths[item]; if (path.isEmpty()) path = m_Path+'/'+item->uid()+".vcf"; bool ret = QFile::remove(path); if (ret) { ret &= mediator()->removeItem(item); } return ret; } bool FallbackPersonBackendEditor::edit( Person* item) { GlobalInstances::actionExtender().editPerson(item); return true; } bool FallbackPersonBackendEditor::addNew( Person* item) { item->ensureUid(); bool ret = save(item); if (ret) { addExisting(item); } return ret; } bool FallbackPersonBackendEditor::addExisting(const Person* item) { m_lItems << const_cast<Person*>(item); mediator()->addItem(item); return true; } QVector<Person*> FallbackPersonBackendEditor::items() const { return m_lItems; } QString FallbackPersonCollection::name () const { return d_ptr->m_Name; } QString FallbackPersonCollection::category () const { return QObject::tr("Contact"); } QVariant FallbackPersonCollection::icon() const { return GlobalInstances::pixmapManipulator().collectionIcon(this,Interfaces::PixmapManipulatorI::CollectionIconHint::CONTACT); } bool FallbackPersonCollection::isEnabled() const { /* if ItemModelStateSerializer exists, check if collectin is enabled, else assume it is */ try { return GlobalInstances::itemModelStateSerializer().isChecked(this); } catch (...) { return true; } } bool FallbackPersonCollection::load() { new ThreadWorker([this]() { bool ok; Q_UNUSED(ok) QList< Person* > ret = VCardUtils::loadDir(QUrl(d_ptr->m_Path),ok,static_cast<FallbackPersonBackendEditor*>(editor<Person>())->m_hPaths); for(Person* p : ret) { p->setCollection(this); editor<Person>()->addExisting(p); } }); //Add all sub directories as new backends QTimer::singleShot(0,d_ptr,SLOT(loadAsync())); return true; } bool FallbackPersonCollection::reload() { return false; } FlagPack<CollectionInterface::SupportedFeatures> FallbackPersonCollection::supportedFeatures() const { return CollectionInterface::SupportedFeatures::NONE | CollectionInterface::SupportedFeatures::LOAD | CollectionInterface::SupportedFeatures::CLEAR | CollectionInterface::SupportedFeatures::MANAGEABLE | CollectionInterface::SupportedFeatures::REMOVE | CollectionInterface::SupportedFeatures::ADD ; } bool FallbackPersonCollection::clear() { QDir dir(d_ptr->m_Path); for (const QString& file : dir.entryList({"*.vcf"},QDir::Files)) dir.remove(file); return true; } QByteArray FallbackPersonCollection::id() const { return "fpc2"+d_ptr->m_Path.toLatin1(); } void FallbackPersonCollectionPrivate::loadAsync() { QDir d(m_Path); for (const QString& dir : d.entryList(QDir::AllDirs)) { if (dir != QString('.') && dir != "..") { CollectionInterface* col = PersonModel::instance().addCollection<FallbackPersonCollection,QString,FallbackPersonCollection*>(m_Path+'/'+dir,q_ptr); if (col->isEnabled()) { col->load(); } } } } #include "fallbackpersoncollection.moc" <commit_msg>vcardstore: Check `open()` return value<commit_after>/************************************************************************************ * Copyright (C) 2014-2016 by Savoir-faire Linux * * Author : Emmanuel Lepage Vallee <[email protected]> * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Lesser General Public * * License as published by the Free Software Foundation; either * * version 2.1 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * * Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public * * License along with this library; if not, write to the Free Software * * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * ***********************************************************************************/ #include "fallbackpersoncollection.h" //Qt #include <QtCore/QFile> #include <QtCore/QDir> #include <QtCore/QHash> #include <QtCore/QTimer> #include <QtCore/QUrl> #include <QtCore/QCryptographicHash> #include <QtCore/QStandardPaths> //Ring #include "person.h" #include "personmodel.h" #include "private/vcardutils.h" #include "contactmethod.h" #include "collectioneditor.h" #include "globalinstances.h" #include "interfaces/pixmapmanipulatori.h" #include "interfaces/actionextenderi.h" #include "interfaces/itemmodelstateserializeri.h" #include "private/threadworker.h" class FallbackPersonBackendEditor final : public CollectionEditor<Person> { public: FallbackPersonBackendEditor(CollectionMediator<Person>* m, const QString& path) : CollectionEditor<Person>(m),m_Path(path) {} virtual bool save ( const Person* item ) override; virtual bool remove ( const Person* item ) override; virtual bool edit ( Person* item ) override; virtual bool addNew ( Person* item ) override; virtual bool addExisting( const Person* item ) override; QVector<Person*> m_lItems; QString m_Path ; QHash<const Person*,QString> m_hPaths; private: virtual QVector<Person*> items() const override; }; class FallbackPersonCollectionPrivate final : public QObject { Q_OBJECT public: FallbackPersonCollectionPrivate(FallbackPersonCollection* parent, CollectionMediator<Person>* mediator, const QString& path); CollectionMediator<Person>* m_pMediator; QString m_Path ; QString m_Name ; FallbackPersonCollection* q_ptr; public Q_SLOTS: void loadAsync(); }; FallbackPersonCollectionPrivate::FallbackPersonCollectionPrivate(FallbackPersonCollection* parent, CollectionMediator<Person>* mediator, const QString& path) : q_ptr(parent), m_pMediator(mediator), m_Path(path) { //Default to somewhere ~/.local/share if (m_Path.isEmpty()) { m_Path = (QStandardPaths::writableLocation(QStandardPaths::DataLocation)) + "/vCard/"; static_cast<FallbackPersonBackendEditor*>(q_ptr->editor<Person>())->m_Path = m_Path; } //Make sure the directory exists so that saving new contacts there doesn't fail if (!QDir().mkpath(m_Path)) qWarning() << "cannot create path for fallbackcollection: " << m_Path; m_Name = path.split('/').last(); if (m_Name.size()) m_Name[0] = m_Name[0].toUpper(); else m_Name = "vCard"; } FallbackPersonCollection::FallbackPersonCollection(CollectionMediator<Person>* mediator, const QString& path, FallbackPersonCollection* parent) : CollectionInterface(new FallbackPersonBackendEditor(mediator,path),parent),d_ptr(new FallbackPersonCollectionPrivate(this,mediator,path)) { } FallbackPersonCollection::~FallbackPersonCollection() { delete d_ptr; } bool FallbackPersonBackendEditor::save(const Person* item) { if (!item) return false; //An UID is required if (item->uid().isEmpty()) { QCryptographicHash hash(QCryptographicHash::Sha1); for (ContactMethod* n : item->phoneNumbers()) hash.addData(n->uri().toLatin1()); hash.addData(item->formattedName().toLatin1()); QByteArray random; for (int i=0;i<5;i++) random.append(QChar((char)(rand()%255))); hash.addData(random); const_cast<Person*>(item)->setUid(hash.result().toHex()); } const QString path = m_Path+'/'+item->uid()+".vcf"; QFile file(path); if (Q_UNLIKELY(!file.open(QIODevice::WriteOnly))) { qWarning() << "Can't write to" << path; return false; } file.write(item->toVCard({})); file.close(); return true; } bool FallbackPersonBackendEditor::remove(const Person* item) { if (!item) return false; QString path = m_hPaths[item]; if (path.isEmpty()) path = m_Path+'/'+item->uid()+".vcf"; bool ret = QFile::remove(path); if (ret) { ret &= mediator()->removeItem(item); } return ret; } bool FallbackPersonBackendEditor::edit( Person* item) { GlobalInstances::actionExtender().editPerson(item); return true; } bool FallbackPersonBackendEditor::addNew( Person* item) { item->ensureUid(); bool ret = save(item); if (ret) { addExisting(item); } return ret; } bool FallbackPersonBackendEditor::addExisting(const Person* item) { m_lItems << const_cast<Person*>(item); mediator()->addItem(item); return true; } QVector<Person*> FallbackPersonBackendEditor::items() const { return m_lItems; } QString FallbackPersonCollection::name () const { return d_ptr->m_Name; } QString FallbackPersonCollection::category () const { return QObject::tr("Contact"); } QVariant FallbackPersonCollection::icon() const { return GlobalInstances::pixmapManipulator().collectionIcon(this,Interfaces::PixmapManipulatorI::CollectionIconHint::CONTACT); } bool FallbackPersonCollection::isEnabled() const { /* if ItemModelStateSerializer exists, check if collectin is enabled, else assume it is */ try { return GlobalInstances::itemModelStateSerializer().isChecked(this); } catch (...) { return true; } } bool FallbackPersonCollection::load() { new ThreadWorker([this]() { bool ok; Q_UNUSED(ok) QList< Person* > ret = VCardUtils::loadDir(QUrl(d_ptr->m_Path),ok,static_cast<FallbackPersonBackendEditor*>(editor<Person>())->m_hPaths); for(Person* p : ret) { p->setCollection(this); editor<Person>()->addExisting(p); } }); //Add all sub directories as new backends QTimer::singleShot(0,d_ptr,SLOT(loadAsync())); return true; } bool FallbackPersonCollection::reload() { return false; } FlagPack<CollectionInterface::SupportedFeatures> FallbackPersonCollection::supportedFeatures() const { return CollectionInterface::SupportedFeatures::NONE | CollectionInterface::SupportedFeatures::LOAD | CollectionInterface::SupportedFeatures::CLEAR | CollectionInterface::SupportedFeatures::MANAGEABLE | CollectionInterface::SupportedFeatures::REMOVE | CollectionInterface::SupportedFeatures::ADD ; } bool FallbackPersonCollection::clear() { QDir dir(d_ptr->m_Path); for (const QString& file : dir.entryList({"*.vcf"},QDir::Files)) dir.remove(file); return true; } QByteArray FallbackPersonCollection::id() const { return "fpc2"+d_ptr->m_Path.toLatin1(); } void FallbackPersonCollectionPrivate::loadAsync() { QDir d(m_Path); for (const QString& dir : d.entryList(QDir::AllDirs)) { if (dir != QString('.') && dir != "..") { CollectionInterface* col = PersonModel::instance().addCollection<FallbackPersonCollection,QString,FallbackPersonCollection*>(m_Path+'/'+dir,q_ptr); if (col->isEnabled()) { col->load(); } } } } #include "fallbackpersoncollection.moc" <|endoftext|>
<commit_before>/************************************************************************************ * Copyright (C) 2014-2015 by Savoir-Faire Linux * * Author : Emmanuel Lepage Vallee <[email protected]> * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Lesser General Public * * License as published by the Free Software Foundation; either * * version 2.1 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * * Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public * * License along with this library; if not, write to the Free Software * * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * ***********************************************************************************/ #include "fallbackpersoncollection.h" //Qt #include <QtCore/QFile> #include <QtCore/QDir> #include <QtCore/QHash> #include <QtCore/QTimer> #include <QtCore/QUrl> #include <QtCore/QCryptographicHash> #include <QtWidgets/QApplication> #include <QtCore/QStandardPaths> //Ring #include "person.h" #include "personmodel.h" #include "private/vcardutils.h" #include "contactmethod.h" #include "collectioneditor.h" #include "delegates/pixmapmanipulationdelegate.h" #include "delegates/itemmodelstateserializationdelegate.h" class FallbackPersonBackendEditor : public CollectionEditor<Person> { public: FallbackPersonBackendEditor(CollectionMediator<Person>* m, const QString& path) : CollectionEditor<Person>(m),m_Path(path) {} virtual bool save ( const Person* item ) override; virtual bool remove ( const Person* item ) override; virtual bool edit ( Person* item ) override; virtual bool addNew ( const Person* item ) override; virtual bool addExisting( const Person* item ) override; QVector<Person*> m_lItems; QString m_Path ; QHash<const Person*,QString> m_hPaths; private: virtual QVector<Person*> items() const override; }; class FallbackPersonCollectionPrivate : public QObject { Q_OBJECT public: FallbackPersonCollectionPrivate(FallbackPersonCollection* parent, CollectionMediator<Person>* mediator, const QString& path); CollectionMediator<Person>* m_pMediator; QString m_Path ; QString m_Name ; FallbackPersonCollection* q_ptr; public Q_SLOTS: void loadAsync(); }; FallbackPersonCollectionPrivate::FallbackPersonCollectionPrivate(FallbackPersonCollection* parent, CollectionMediator<Person>* mediator, const QString& path) : q_ptr(parent), m_pMediator(mediator), m_Path(path) { //Default to somewhere ~/.local/share if (m_Path.isEmpty()) { m_Path = (QStandardPaths::writableLocation(QStandardPaths::DataLocation)) + "/vCard/"; static_cast<FallbackPersonBackendEditor*>(q_ptr->editor<Person>())->m_Path = m_Path; } m_Name = path.split('/').last(); if (m_Name.size()) m_Name[0] = m_Name[0].toUpper(); else m_Name = "vCard"; } FallbackPersonCollection::FallbackPersonCollection(CollectionMediator<Person>* mediator, const QString& path, FallbackPersonCollection* parent) : CollectionInterface(new FallbackPersonBackendEditor(mediator,path),parent),d_ptr(new FallbackPersonCollectionPrivate(this,mediator,path)) { } FallbackPersonCollection::~FallbackPersonCollection() { } bool FallbackPersonBackendEditor::save(const Person* item) { if (!item) return false; //An UID is required if (item->uid().isEmpty()) { QCryptographicHash hash(QCryptographicHash::Sha1); for (ContactMethod* n : item->phoneNumbers()) hash.addData(n->uri().toLatin1()); hash.addData(item->formattedName().toLatin1()); QByteArray random; for (int i=0;i<5;i++) random.append(QChar((char)(rand()%255))); hash.addData(random); const_cast<Person*>(item)->setUid(hash.result().toHex()); } QFile file(m_Path+'/'+item->uid()+".vcf"); file.open(QIODevice::WriteOnly); file.write(item->toVCard({})); file.close(); return true; } bool FallbackPersonBackendEditor::remove(const Person* item) { if (!item) return false; QString path = m_hPaths[item]; if (path.isEmpty()) path = m_Path+'/'+item->uid()+".vcf"; bool ret = QFile::remove(path); if (ret) { ret &= mediator()->removeItem(item); } return ret; } bool FallbackPersonBackendEditor::edit( Person* item) { Q_UNUSED(item) return false; } bool FallbackPersonBackendEditor::addNew(const Person* item) { bool ret = save(item); if (ret) { addExisting(item); } return ret; } bool FallbackPersonBackendEditor::addExisting(const Person* item) { m_lItems << const_cast<Person*>(item); mediator()->addItem(item); return true; } QVector<Person*> FallbackPersonBackendEditor::items() const { return m_lItems; } QString FallbackPersonCollection::name () const { return d_ptr->m_Name; } QString FallbackPersonCollection::category () const { return QObject::tr("Contact"); } QVariant FallbackPersonCollection::icon() const { return PixmapManipulationDelegate::instance()->collectionIcon(this,PixmapManipulationDelegate::CollectionIconHint::CONTACT); } bool FallbackPersonCollection::isEnabled() const { return ItemModelStateSerializationDelegate::instance()->isChecked(this); } bool FallbackPersonCollection::load() { bool ok; QList< Person* > ret = VCardUtils::loadDir(QUrl(d_ptr->m_Path),ok,static_cast<FallbackPersonBackendEditor*>(editor<Person>())->m_hPaths); for(Person* p : ret) { p->setCollection(this); editor<Person>()->addExisting(p); } //Add all sub directories as new backends QTimer::singleShot(0,d_ptr,SLOT(loadAsync())); return true; } bool FallbackPersonCollection::reload() { return false; } CollectionInterface::SupportedFeatures FallbackPersonCollection::supportedFeatures() const { return (CollectionInterface::SupportedFeatures) ( CollectionInterface::SupportedFeatures::NONE | CollectionInterface::SupportedFeatures::LOAD | CollectionInterface::SupportedFeatures::CLEAR | CollectionInterface::SupportedFeatures::MANAGEABLE | CollectionInterface::SupportedFeatures::REMOVE | CollectionInterface::SupportedFeatures::ADD ); } bool FallbackPersonCollection::clear() { QDir dir(d_ptr->m_Path); for (const QString& file : dir.entryList({"*.vcf"},QDir::Files)) dir.remove(file); return true; } QByteArray FallbackPersonCollection::id() const { return "fpc2"+d_ptr->m_Path.toLatin1(); } void FallbackPersonCollectionPrivate::loadAsync() { QDir d(m_Path); for (const QString& dir : d.entryList(QDir::AllDirs)) { if (dir != QString('.') && dir != "..") { CollectionInterface* col = PersonModel::instance()->addCollection<FallbackPersonCollection,QString,FallbackPersonCollection*>(m_Path+'/'+dir,q_ptr); if (ItemModelStateSerializationDelegate::instance()->isChecked(col)) { col->load(); } } } } #include "fallbackpersoncollection.moc" <commit_msg>android: Remove invalid #include<commit_after>/************************************************************************************ * Copyright (C) 2014-2015 by Savoir-Faire Linux * * Author : Emmanuel Lepage Vallee <[email protected]> * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Lesser General Public * * License as published by the Free Software Foundation; either * * version 2.1 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * * Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public * * License along with this library; if not, write to the Free Software * * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * ***********************************************************************************/ #include "fallbackpersoncollection.h" //Qt #include <QtCore/QFile> #include <QtCore/QDir> #include <QtCore/QHash> #include <QtCore/QTimer> #include <QtCore/QUrl> #include <QtCore/QCryptographicHash> #include <QtCore/QStandardPaths> //Ring #include "person.h" #include "personmodel.h" #include "private/vcardutils.h" #include "contactmethod.h" #include "collectioneditor.h" #include "delegates/pixmapmanipulationdelegate.h" #include "delegates/itemmodelstateserializationdelegate.h" class FallbackPersonBackendEditor : public CollectionEditor<Person> { public: FallbackPersonBackendEditor(CollectionMediator<Person>* m, const QString& path) : CollectionEditor<Person>(m),m_Path(path) {} virtual bool save ( const Person* item ) override; virtual bool remove ( const Person* item ) override; virtual bool edit ( Person* item ) override; virtual bool addNew ( const Person* item ) override; virtual bool addExisting( const Person* item ) override; QVector<Person*> m_lItems; QString m_Path ; QHash<const Person*,QString> m_hPaths; private: virtual QVector<Person*> items() const override; }; class FallbackPersonCollectionPrivate : public QObject { Q_OBJECT public: FallbackPersonCollectionPrivate(FallbackPersonCollection* parent, CollectionMediator<Person>* mediator, const QString& path); CollectionMediator<Person>* m_pMediator; QString m_Path ; QString m_Name ; FallbackPersonCollection* q_ptr; public Q_SLOTS: void loadAsync(); }; FallbackPersonCollectionPrivate::FallbackPersonCollectionPrivate(FallbackPersonCollection* parent, CollectionMediator<Person>* mediator, const QString& path) : q_ptr(parent), m_pMediator(mediator), m_Path(path) { //Default to somewhere ~/.local/share if (m_Path.isEmpty()) { m_Path = (QStandardPaths::writableLocation(QStandardPaths::DataLocation)) + "/vCard/"; static_cast<FallbackPersonBackendEditor*>(q_ptr->editor<Person>())->m_Path = m_Path; } m_Name = path.split('/').last(); if (m_Name.size()) m_Name[0] = m_Name[0].toUpper(); else m_Name = "vCard"; } FallbackPersonCollection::FallbackPersonCollection(CollectionMediator<Person>* mediator, const QString& path, FallbackPersonCollection* parent) : CollectionInterface(new FallbackPersonBackendEditor(mediator,path),parent),d_ptr(new FallbackPersonCollectionPrivate(this,mediator,path)) { } FallbackPersonCollection::~FallbackPersonCollection() { } bool FallbackPersonBackendEditor::save(const Person* item) { if (!item) return false; //An UID is required if (item->uid().isEmpty()) { QCryptographicHash hash(QCryptographicHash::Sha1); for (ContactMethod* n : item->phoneNumbers()) hash.addData(n->uri().toLatin1()); hash.addData(item->formattedName().toLatin1()); QByteArray random; for (int i=0;i<5;i++) random.append(QChar((char)(rand()%255))); hash.addData(random); const_cast<Person*>(item)->setUid(hash.result().toHex()); } QFile file(m_Path+'/'+item->uid()+".vcf"); file.open(QIODevice::WriteOnly); file.write(item->toVCard({})); file.close(); return true; } bool FallbackPersonBackendEditor::remove(const Person* item) { if (!item) return false; QString path = m_hPaths[item]; if (path.isEmpty()) path = m_Path+'/'+item->uid()+".vcf"; bool ret = QFile::remove(path); if (ret) { ret &= mediator()->removeItem(item); } return ret; } bool FallbackPersonBackendEditor::edit( Person* item) { Q_UNUSED(item) return false; } bool FallbackPersonBackendEditor::addNew(const Person* item) { bool ret = save(item); if (ret) { addExisting(item); } return ret; } bool FallbackPersonBackendEditor::addExisting(const Person* item) { m_lItems << const_cast<Person*>(item); mediator()->addItem(item); return true; } QVector<Person*> FallbackPersonBackendEditor::items() const { return m_lItems; } QString FallbackPersonCollection::name () const { return d_ptr->m_Name; } QString FallbackPersonCollection::category () const { return QObject::tr("Contact"); } QVariant FallbackPersonCollection::icon() const { return PixmapManipulationDelegate::instance()->collectionIcon(this,PixmapManipulationDelegate::CollectionIconHint::CONTACT); } bool FallbackPersonCollection::isEnabled() const { return ItemModelStateSerializationDelegate::instance()->isChecked(this); } bool FallbackPersonCollection::load() { bool ok; QList< Person* > ret = VCardUtils::loadDir(QUrl(d_ptr->m_Path),ok,static_cast<FallbackPersonBackendEditor*>(editor<Person>())->m_hPaths); for(Person* p : ret) { p->setCollection(this); editor<Person>()->addExisting(p); } //Add all sub directories as new backends QTimer::singleShot(0,d_ptr,SLOT(loadAsync())); return true; } bool FallbackPersonCollection::reload() { return false; } CollectionInterface::SupportedFeatures FallbackPersonCollection::supportedFeatures() const { return (CollectionInterface::SupportedFeatures) ( CollectionInterface::SupportedFeatures::NONE | CollectionInterface::SupportedFeatures::LOAD | CollectionInterface::SupportedFeatures::CLEAR | CollectionInterface::SupportedFeatures::MANAGEABLE | CollectionInterface::SupportedFeatures::REMOVE | CollectionInterface::SupportedFeatures::ADD ); } bool FallbackPersonCollection::clear() { QDir dir(d_ptr->m_Path); for (const QString& file : dir.entryList({"*.vcf"},QDir::Files)) dir.remove(file); return true; } QByteArray FallbackPersonCollection::id() const { return "fpc2"+d_ptr->m_Path.toLatin1(); } void FallbackPersonCollectionPrivate::loadAsync() { QDir d(m_Path); for (const QString& dir : d.entryList(QDir::AllDirs)) { if (dir != QString('.') && dir != "..") { CollectionInterface* col = PersonModel::instance()->addCollection<FallbackPersonCollection,QString,FallbackPersonCollection*>(m_Path+'/'+dir,q_ptr); if (ItemModelStateSerializationDelegate::instance()->isChecked(col)) { col->load(); } } } } #include "fallbackpersoncollection.moc" <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the test suite of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <qtest.h> #include <QtDeclarative/qmlengine.h> #include <QtDeclarative/qmlcomponent.h> #include <private/qmlfontloader_p.h> class tst_qmlfontloader : public QObject { Q_OBJECT public: tst_qmlfontloader(); private slots: void namedfont(); void localfont(); private slots: private: QmlEngine engine; }; tst_qmlfontloader::tst_qmlfontloader() { } void tst_qmlfontloader::namedfont() { QString componentStr = "import Qt 4.6\nFontLoader { name: \"Helvetica\" }"; QmlComponent component(&engine, componentStr.toLatin1(), QUrl("file://")); QmlFontLoader *fontObject = qobject_cast<QmlFontLoader*>(component.create()); QVERIFY(fontObject != 0); QCOMPARE(fontObject->name(), QString("Helvetica")); } void tst_qmlfontloader::localfont() { QString componentStr = "import Qt 4.6\nFontLoader { source: \"data/Fontin-Bold.ttf\" }"; QmlComponent component(&engine, componentStr.toLatin1(), QUrl("file://")); QmlFontLoader *fontObject = qobject_cast<QmlFontLoader*>(component.create()); QVERIFY(fontObject != 0); QCOMPARE(fontObject->name(), QString("Fontin")); } QTEST_MAIN(tst_qmlfontloader) #include "tst_qmlfontloader.moc" <commit_msg>autotests<commit_after>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the test suite of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <qtest.h> #include <QtDeclarative/qmlengine.h> #include <QtDeclarative/qmlcomponent.h> #include <private/qmlfontloader_p.h> #include "../../../shared/util.h" class tst_qmlfontloader : public QObject { Q_OBJECT public: tst_qmlfontloader(); private slots: void nofont(); void namedfont(); void localfont(); void webfont(); private slots: private: QmlEngine engine; }; tst_qmlfontloader::tst_qmlfontloader() { } void tst_qmlfontloader::nofont() { QString componentStr = "import Qt 4.6\nFontLoader { }"; QmlComponent component(&engine, componentStr.toLatin1(), QUrl("file://")); QmlFontLoader *fontObject = qobject_cast<QmlFontLoader*>(component.create()); QVERIFY(fontObject != 0); QCOMPARE(fontObject->name(), QString("")); } void tst_qmlfontloader::namedfont() { QString componentStr = "import Qt 4.6\nFontLoader { name: \"Helvetica\" }"; QmlComponent component(&engine, componentStr.toLatin1(), QUrl("file://")); QmlFontLoader *fontObject = qobject_cast<QmlFontLoader*>(component.create()); QVERIFY(fontObject != 0); QCOMPARE(fontObject->name(), QString("Helvetica")); } void tst_qmlfontloader::localfont() { QString componentStr = "import Qt 4.6\nFontLoader { source: \"data/Fontin-Bold.ttf\" }"; QmlComponent component(&engine, componentStr.toLatin1(), QUrl("file://")); QmlFontLoader *fontObject = qobject_cast<QmlFontLoader*>(component.create()); QVERIFY(fontObject != 0); QCOMPARE(fontObject->name(), QString("Fontin")); } void tst_qmlfontloader::webfont() { QString componentStr = "import Qt 4.6\nFontLoader { source: \"http://www.princexml.com/fonts/steffmann/Starburst.ttf\" }"; QmlComponent component(&engine, componentStr.toLatin1(), QUrl("file://")); QmlFontLoader *fontObject = qobject_cast<QmlFontLoader*>(component.create()); QVERIFY(fontObject != 0); QTRY_COMPARE(fontObject->name(), QString("Starburst")); } QTEST_MAIN(tst_qmlfontloader) #include "tst_qmlfontloader.moc" <|endoftext|>
<commit_before>/* * Vehicle.cpp * openc2e * * Created by Alyssa Milburn on Tue May 25 2004. * Copyright (c) 2004 Alyssa Milburn. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License 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 * Lesser General Public License for more details. * */ #include "Vehicle.h" #include "Engine.h" #include "World.h" #include "MetaRoom.h" Vehicle::Vehicle(unsigned int family, unsigned int genus, unsigned int species, unsigned int plane, std::string spritefile, unsigned int firstimage, unsigned int imagecount) : CompoundAgent(family, genus, species, plane, spritefile, firstimage, imagecount) { capacity = 0; bump = 0; cabinleft = 0; cabintop = 0; cabinright = getWidth(); cabinbottom = getHeight(); cabinplane = 1; // TODO: is this sane? seems to be the default in c2e } Vehicle::Vehicle(std::string spritefile, unsigned int firstimage, unsigned int imagecount) : CompoundAgent(spritefile, firstimage, imagecount) { capacity = 0; bump = 0; // TODO: set cabin bounds? we don't know width/height at this point.. cabinplane = 95; // TODO: arbitarily-chosen value (see also SFCFile) } void Vehicle::tick() { CompoundAgent::tick(); if (paused) return; // move by xvec/yvec! moveTo(x + xvec.getInt() / 256.0, y + yvec.getInt() / 256.0); } void Vehicle::carry(AgentRef passenger) { // TODO: 'return' is not a good idea here, because the callung function already does stuff if (passenger->carriedby) return; // TODO: change to assert? if (passenger->invehicle) return; // TODO: change to assert? int cabinwidth = cabinright - cabinleft; int cabinheight = cabinbottom - cabintop; if (engine.version > 2) { // reject if passenger is too big if ((int)passenger->getWidth() > cabinwidth) return; if ((int)passenger->getHeight() > cabinheight) return; } // push into our cabin // TODO: should we use moveTo here? if (passenger->x + passenger->getWidth() > (x + cabinright)) passenger->x = x + cabinright - passenger->getWidth(); if (passenger->x < (x + cabinleft)) passenger->x = x + cabinleft; if (engine.version > 1) { // TODO: not sure if this is good for too-high agents, if it's possible for them to exist (see comment above) if (passenger->y + passenger->getHeight() > (y + cabinbottom)) passenger->y = y + cabinbottom - passenger->getHeight(); if (passenger->y < (y + cabintop)) passenger->y = y + cabintop; } else { passenger->y = y + cabinbottom - passenger->getHeight(); } passengers.push_back(passenger); passenger->invehicle = this; if (engine.version >= 3) passenger->queueScript(121, this); // Vehicle Pickup, TODO: is this valid call? } void Vehicle::drop(AgentRef passenger) { std::vector<AgentRef>::iterator i = std::find(passengers.begin(), passengers.end(), passenger); assert(i != passengers.end()); assert(passenger->invehicle == AgentRef(this)); passengers.erase(i); passenger->beDropped(); if (engine.version >= 3) passenger->queueScript(122, this); // Vehicle Drop, TODO: is this valid call? } void Vehicle::adjustCarried(float xoffset, float yoffset) { Agent::adjustCarried(xoffset, yoffset); for (std::vector<AgentRef>::iterator i = passengers.begin(); i != passengers.end(); i++) { if (!(*i)) continue; // TODO: muh (*i)->moveTo((*i)->x + xoffset, (*i)->y + yoffset); } } void Vehicle::kill() { // TODO: sane? while (passengers.size() > 0) { if (passengers[0]) dropCarried(passengers[0]); else passengers.erase(passengers.begin()); } } /* vim: set noet: */ <commit_msg>call Agent::kill from Vehicle::kill (oops)<commit_after>/* * Vehicle.cpp * openc2e * * Created by Alyssa Milburn on Tue May 25 2004. * Copyright (c) 2004 Alyssa Milburn. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License 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 * Lesser General Public License for more details. * */ #include "Vehicle.h" #include "Engine.h" #include "World.h" #include "MetaRoom.h" Vehicle::Vehicle(unsigned int family, unsigned int genus, unsigned int species, unsigned int plane, std::string spritefile, unsigned int firstimage, unsigned int imagecount) : CompoundAgent(family, genus, species, plane, spritefile, firstimage, imagecount) { capacity = 0; bump = 0; cabinleft = 0; cabintop = 0; cabinright = getWidth(); cabinbottom = getHeight(); cabinplane = 1; // TODO: is this sane? seems to be the default in c2e } Vehicle::Vehicle(std::string spritefile, unsigned int firstimage, unsigned int imagecount) : CompoundAgent(spritefile, firstimage, imagecount) { capacity = 0; bump = 0; // TODO: set cabin bounds? we don't know width/height at this point.. cabinplane = 95; // TODO: arbitarily-chosen value (see also SFCFile) } void Vehicle::tick() { CompoundAgent::tick(); if (paused) return; // move by xvec/yvec! moveTo(x + xvec.getInt() / 256.0, y + yvec.getInt() / 256.0); } void Vehicle::carry(AgentRef passenger) { // TODO: 'return' is not a good idea here, because the callung function already does stuff if (passenger->carriedby) return; // TODO: change to assert? if (passenger->invehicle) return; // TODO: change to assert? int cabinwidth = cabinright - cabinleft; int cabinheight = cabinbottom - cabintop; if (engine.version > 2) { // reject if passenger is too big if ((int)passenger->getWidth() > cabinwidth) return; if ((int)passenger->getHeight() > cabinheight) return; } // push into our cabin // TODO: should we use moveTo here? if (passenger->x + passenger->getWidth() > (x + cabinright)) passenger->x = x + cabinright - passenger->getWidth(); if (passenger->x < (x + cabinleft)) passenger->x = x + cabinleft; if (engine.version > 1) { // TODO: not sure if this is good for too-high agents, if it's possible for them to exist (see comment above) if (passenger->y + passenger->getHeight() > (y + cabinbottom)) passenger->y = y + cabinbottom - passenger->getHeight(); if (passenger->y < (y + cabintop)) passenger->y = y + cabintop; } else { passenger->y = y + cabinbottom - passenger->getHeight(); } passengers.push_back(passenger); passenger->invehicle = this; if (engine.version >= 3) passenger->queueScript(121, this); // Vehicle Pickup, TODO: is this valid call? } void Vehicle::drop(AgentRef passenger) { std::vector<AgentRef>::iterator i = std::find(passengers.begin(), passengers.end(), passenger); assert(i != passengers.end()); assert(passenger->invehicle == AgentRef(this)); passengers.erase(i); passenger->beDropped(); if (engine.version >= 3) passenger->queueScript(122, this); // Vehicle Drop, TODO: is this valid call? } void Vehicle::adjustCarried(float xoffset, float yoffset) { Agent::adjustCarried(xoffset, yoffset); for (std::vector<AgentRef>::iterator i = passengers.begin(); i != passengers.end(); i++) { if (!(*i)) continue; // TODO: muh (*i)->moveTo((*i)->x + xoffset, (*i)->y + yoffset); } } void Vehicle::kill() { // TODO: sane? while (passengers.size() > 0) { if (passengers[0]) dropCarried(passengers[0]); else passengers.erase(passengers.begin()); } Agent::kill(); } /* vim: set noet: */ <|endoftext|>
<commit_before>#include "gamestates/skirmishstate.hpp" #include "gamestates/deploystate.hpp" #include "engine/square.hpp" #include "engine/pathfinding/astar.hpp" #include "engine/pathfinding/path.hpp" #include "gui/texturemanager.hpp" #include "gui/ng/label.hpp" #include "gui/ng/spritewidget.hpp" #include "gui/ng/button.hpp" #include "gui/squaredetailwindow.hpp" #include <SFML/Graphics/Sprite.hpp> #include <iostream> #include <memory> namespace qrw { SkirmishState::SkirmishState(sf::RenderWindow* renderWindow) : SceneState(renderWindow, EGameStateId::EGSID_SKIRMISH_STATE), _squareMarker(new SquareMarker()) { _squareDetailWindow = new SquareDetailWindow(); _guiUptr->addWidget(_squareDetailWindow); _squareMarker->setVisible(false); _playerNameText = new namelessgui::Text(); _playerNameText->setText("Player Name"); _playerNameText->setParentAnchor({0.5, 0}); _playerNameText->setAnchor({0.5, 0}); _toolBar->addWidget(_playerNameText); namelessgui::Button* endTurnButton = new namelessgui::Button(); endTurnButton->setText("End Turn"); endTurnButton->setSize({140, 30}); endTurnButton->setParentAnchor({0.5, 1}); endTurnButton->setAnchor({0.5, 1.0}); endTurnButton->setRelativePosition({0.0f, -5.0f}); endTurnButton->signalclicked.connect(std::bind(&SkirmishState::endTurn, this)); _toolBar->addWidget(endTurnButton); } void SkirmishState::init(GameState *previousState) { SceneState::init(previousState); if(previousState->getId() != EGameStateId::EGSID_DEPLOY_STATE) return; DeployState* deployState = static_cast<DeployState*>(previousState); _board = deployState->getBoard(); _scene->setBoard(_board); _players = deployState->getPlayers(); _currentPlayer = 0; _playerNameText->setText(_players[_currentPlayer]->getName()); // Initialize square detail window. Coordinates cursorPosition = _scene->getCursorPosition(); Unit::Ptr unit = _board->getUnit(cursorPosition); Terrain::Ptr terrain = _board->getSquare(cursorPosition)->getTerrain(); _squareDetailWindow->setUnitAndTerrain(unit, terrain); } void SkirmishState::draw() { SceneState::draw(); _squareMarker->draw(*_renderWindow, sf::RenderStates::Default); drawPath(); } EGameStateId SkirmishState::update() { if(_backToMainMenu) return EGameStateId::EGSID_MAIN_MENU_STATE; return EGameStateId::EGSID_NO_CHANGE; } void SkirmishState::slotCursorMoved(const Coordinates &boardPosition, bool isOnBoard) { if(isOnBoard) { Unit::Ptr unitUnderCursor = _board->getUnit(boardPosition); Terrain::Ptr terrainUnderCursor = _board->getSquare(boardPosition)->getTerrain(); _squareDetailWindow->setUnitAndTerrain(unitUnderCursor, terrainUnderCursor); if(_selectedUnit) { _path.reset(_board->findPath(_selectedUnit->getPosition(), boardPosition)); if(_path) { if(_path->getMovementCosts() > _selectedUnit->getCurrentMovement()) _scene->getCursor().setFillColor(Cursor::Color::ESC_WARNING); else _scene->getCursor().setFillColor(Cursor::Color::ESC_DEFAULT); } } } else _squareDetailWindow->setUnitAndTerrain(nullptr, nullptr); } void SkirmishState::moveUnit() { if(!_selectedUnit) return; if(!_path) return; int pathCosts = _path->getMovementCosts(); if(pathCosts == 0) return; int maxDistance = _selectedUnit->getCurrentMovement(); if(pathCosts > maxDistance) return; int remainingMovement = maxDistance - pathCosts; _selectedUnit->setCurrentMovement(remainingMovement); _board->getSquare(_squareMarker->getBoardPosition())->setUnit(nullptr); _board->getSquare(_path->getTargetPosition())->setUnit(_selectedUnit); std::cout << "Move unit." << std::endl; } void SkirmishState::performAttack() { std::cout << "Attack unit." << std::endl; } void SkirmishState::replenishTroops() { for(int w = 0; w < _board->getWidth(); ++w) { for(int h = 0; h < _board->getHeight(); ++h) { auto unit = _board->getSquare(Coordinates(w, h))->getUnit(); if(unit) unit->setCurrentMovement(unit->getMovement()); } } } void SkirmishState::slotCursorLeftClicked(const Coordinates &boardPosition) { Unit::Ptr unitUnderCursor = _board->getUnit(boardPosition); Terrain::Ptr terrainUnderCursor = _board->getSquare(boardPosition)->getTerrain(); _squareDetailWindow->setUnitAndTerrain(unitUnderCursor, terrainUnderCursor); // Case 1: Unit is selected and instructed to move. if(_selectedUnit && !unitUnderCursor) { // Move unit moveUnit(); deselectUnit(); return; } // Case 2: Unit is selected and instructed to attack enemy. if(_selectedUnit && unitUnderCursor && unitUnderCursor->getPlayer() != _selectedUnit->getPlayer()) { performAttack(); return; } // Do not allow to select units of other player if(unitUnderCursor && unitUnderCursor->getPlayer() != _players[_currentPlayer]) { // Select unit _selectedUnit = unitUnderCursor; _squareMarker->setBoardPosition(boardPosition); _squareMarker->setVisible(true); return; } deselectUnit(); } bool SkirmishState::handleEvent(sf::Event& event) { if(SceneState::handleEvent(event)) return true; if(event.type == sf::Event::MouseButtonReleased) { if(event.mouseButton.button == sf::Mouse::Right) { deselectUnit(); return true; } } return false; } void SkirmishState::endTurn() { _currentPlayer = (_currentPlayer + 1) % _players.size(); _playerNameText->setText(_players[_currentPlayer]->getName()); deselectUnit(); replenishTroops(); } void SkirmishState::drawPath() { if(!_path) return; const int pathLength = _path->getLength(); Square* previous = 0; Square* current = _path->getStep(0); Square* next = _path->getStep(1); sf::Sprite footstep = sf::Sprite(*TextureManager::getInstance()->getTexture("footstep")); // Do not render first step. for(int i = 1; i < pathLength; ++i) { previous = current; current = next; // Reset the previously applied transformations. footstep.setOrigin(16, 16); footstep.setScale(1, 1); footstep.setRotation(0); // Transformations relative to the previous step Coordinates prevDelta(previous->getCoordinates() - current->getCoordinates()); if(prevDelta.getX() != 0) footstep.rotate(-90 * prevDelta.getX()); if(prevDelta.getY() != 0) footstep.scale(1, prevDelta.getY()); // Transformations relative to the next step (if possible) if(i < pathLength - 1) { next = _path->getStep(i+1); Coordinates prevNextDelta(previous->getCoordinates() - next->getCoordinates()); // If the path has a corner at this position if(prevNextDelta.getX() != 0 && prevNextDelta.getY() != 0) { int rotationdirection = 0; // horizontal if(prevDelta.getX() == 0) { rotationdirection = -1; } // vertical else if(prevDelta.getY() == 0) { rotationdirection = +1; } footstep.rotate(rotationdirection * 45 * (prevNextDelta.getX() * prevNextDelta.getY())); } } footstep.setPosition( 32 * (0.5f + current->getXPosition()), 32 * (0.5f + current->getYPosition()) ); _renderWindow->draw(footstep); } } void SkirmishState::deselectUnit() { _selectedUnit = nullptr; _squareMarker->setVisible(false); _scene->getCursor().setFillColor(Cursor::Color::ESC_DEFAULT); _path.reset(); } } // namespace qrw <commit_msg>Fixed movement for square independent unit.<commit_after>#include "gamestates/skirmishstate.hpp" #include "gamestates/deploystate.hpp" #include "engine/square.hpp" #include "engine/pathfinding/astar.hpp" #include "engine/pathfinding/path.hpp" #include "gui/texturemanager.hpp" #include "gui/ng/label.hpp" #include "gui/ng/spritewidget.hpp" #include "gui/ng/button.hpp" #include "gui/squaredetailwindow.hpp" #include <SFML/Graphics/Sprite.hpp> #include <iostream> #include <memory> namespace qrw { SkirmishState::SkirmishState(sf::RenderWindow* renderWindow) : SceneState(renderWindow, EGameStateId::EGSID_SKIRMISH_STATE), _squareMarker(new SquareMarker()) { _squareDetailWindow = new SquareDetailWindow(); _guiUptr->addWidget(_squareDetailWindow); _squareMarker->setVisible(false); _playerNameText = new namelessgui::Text(); _playerNameText->setText("Player Name"); _playerNameText->setParentAnchor({0.5, 0}); _playerNameText->setAnchor({0.5, 0}); _toolBar->addWidget(_playerNameText); namelessgui::Button* endTurnButton = new namelessgui::Button(); endTurnButton->setText("End Turn"); endTurnButton->setSize({140, 30}); endTurnButton->setParentAnchor({0.5, 1}); endTurnButton->setAnchor({0.5, 1.0}); endTurnButton->setRelativePosition({0.0f, -5.0f}); endTurnButton->signalclicked.connect(std::bind(&SkirmishState::endTurn, this)); _toolBar->addWidget(endTurnButton); } void SkirmishState::init(GameState *previousState) { SceneState::init(previousState); if(previousState->getId() != EGameStateId::EGSID_DEPLOY_STATE) return; DeployState* deployState = static_cast<DeployState*>(previousState); _board = deployState->getBoard(); _scene->setBoard(_board); _players = deployState->getPlayers(); _currentPlayer = 0; _playerNameText->setText(_players[_currentPlayer]->getName()); // Initialize square detail window. Coordinates cursorPosition = _scene->getCursorPosition(); Unit::Ptr unit = _board->getUnit(cursorPosition); Terrain::Ptr terrain = _board->getSquare(cursorPosition)->getTerrain(); _squareDetailWindow->setUnitAndTerrain(unit, terrain); } void SkirmishState::draw() { SceneState::draw(); _squareMarker->draw(*_renderWindow, sf::RenderStates::Default); drawPath(); } EGameStateId SkirmishState::update() { if(_backToMainMenu) return EGameStateId::EGSID_MAIN_MENU_STATE; return EGameStateId::EGSID_NO_CHANGE; } void SkirmishState::slotCursorMoved(const Coordinates &boardPosition, bool isOnBoard) { if(isOnBoard) { Unit::Ptr unitUnderCursor = _board->getUnit(boardPosition); Terrain::Ptr terrainUnderCursor = _board->getSquare(boardPosition)->getTerrain(); _squareDetailWindow->setUnitAndTerrain(unitUnderCursor, terrainUnderCursor); if(_selectedUnit) { _path.reset(_board->findPath(_selectedUnit->getPosition(), boardPosition)); if(_path) { if(_path->getMovementCosts() > _selectedUnit->getCurrentMovement()) _scene->getCursor().setFillColor(Cursor::Color::ESC_WARNING); else _scene->getCursor().setFillColor(Cursor::Color::ESC_DEFAULT); } } } else _squareDetailWindow->setUnitAndTerrain(nullptr, nullptr); } void SkirmishState::moveUnit() { if(!_selectedUnit) return; if(!_path) return; int pathCosts = _path->getMovementCosts(); if(pathCosts == 0) return; int maxDistance = _selectedUnit->getCurrentMovement(); if(pathCosts > maxDistance) return; int remainingMovement = maxDistance - pathCosts; _selectedUnit->setCurrentMovement(remainingMovement); _board->moveUnit(_squareMarker->getBoardPosition(), _path->getTargetPosition()); _selectedUnit->setPosition(_path->getTargetPosition()); std::cout << "Move unit." << std::endl; } void SkirmishState::performAttack() { std::cout << "Attack unit." << std::endl; } void SkirmishState::replenishTroops() { for(int w = 0; w < _board->getWidth(); ++w) { for(int h = 0; h < _board->getHeight(); ++h) { auto unit = _board->getSquare(Coordinates(w, h))->getUnit(); if(unit) unit->setCurrentMovement(unit->getMovement()); } } } void SkirmishState::slotCursorLeftClicked(const Coordinates &boardPosition) { Unit::Ptr unitUnderCursor = _board->getUnit(boardPosition); Terrain::Ptr terrainUnderCursor = _board->getSquare(boardPosition)->getTerrain(); _squareDetailWindow->setUnitAndTerrain(unitUnderCursor, terrainUnderCursor); // Case 1: Unit is selected and instructed to move. if(_selectedUnit && !unitUnderCursor) { // Move unit moveUnit(); deselectUnit(); return; } // Case 2: Unit is selected and instructed to attack enemy. if(_selectedUnit && unitUnderCursor && unitUnderCursor->getPlayer() != _selectedUnit->getPlayer()) { performAttack(); return; } // Do not allow to select units of other player if(unitUnderCursor && unitUnderCursor->getPlayer() != _players[_currentPlayer]) { // Select unit _selectedUnit = unitUnderCursor; _squareMarker->setBoardPosition(boardPosition); _squareMarker->setVisible(true); return; } deselectUnit(); } bool SkirmishState::handleEvent(sf::Event& event) { if(SceneState::handleEvent(event)) return true; if(event.type == sf::Event::MouseButtonReleased) { if(event.mouseButton.button == sf::Mouse::Right) { deselectUnit(); return true; } } return false; } void SkirmishState::endTurn() { _currentPlayer = (_currentPlayer + 1) % _players.size(); _playerNameText->setText(_players[_currentPlayer]->getName()); deselectUnit(); replenishTroops(); } void SkirmishState::drawPath() { if(!_path) return; const int pathLength = _path->getLength(); Square* previous = 0; Square* current = _path->getStep(0); Square* next = _path->getStep(1); sf::Sprite footstep = sf::Sprite(*TextureManager::getInstance()->getTexture("footstep")); // Do not render first step. for(int i = 1; i < pathLength; ++i) { previous = current; current = next; // Reset the previously applied transformations. footstep.setOrigin(16, 16); footstep.setScale(1, 1); footstep.setRotation(0); // Transformations relative to the previous step Coordinates prevDelta(previous->getCoordinates() - current->getCoordinates()); if(prevDelta.getX() != 0) footstep.rotate(-90 * prevDelta.getX()); if(prevDelta.getY() != 0) footstep.scale(1, prevDelta.getY()); // Transformations relative to the next step (if possible) if(i < pathLength - 1) { next = _path->getStep(i+1); Coordinates prevNextDelta(previous->getCoordinates() - next->getCoordinates()); // If the path has a corner at this position if(prevNextDelta.getX() != 0 && prevNextDelta.getY() != 0) { int rotationdirection = 0; // horizontal if(prevDelta.getX() == 0) { rotationdirection = -1; } // vertical else if(prevDelta.getY() == 0) { rotationdirection = +1; } footstep.rotate(rotationdirection * 45 * (prevNextDelta.getX() * prevNextDelta.getY())); } } footstep.setPosition( 32 * (0.5f + current->getXPosition()), 32 * (0.5f + current->getYPosition()) ); _renderWindow->draw(footstep); } } void SkirmishState::deselectUnit() { _selectedUnit = nullptr; _squareMarker->setVisible(false); _scene->getCursor().setFillColor(Cursor::Color::ESC_DEFAULT); _path.reset(); } } // namespace qrw <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: precompiled_sc.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2006-12-05 14:26: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): Generated on 2006-07-11 15:52:42.937361 #ifdef PRECOMPILED_HEADERS #include "scitems.hxx" #include <algorithm> #include <assert.h> #include <stdarg.h> #include <stddef.h> #include <stdio.h> #include <string.h> #include <iosfwd> #include <limits.h> #include <limits> #include <list> #include <math.h> #include <memory> #include <new> #include <cfloat> #include <basegfx/polygon/b2dpolygon.hxx> #include <basegfx/polygon/b3dpolygon.hxx> #include <basegfx/polygon/b3dpolypolygon.hxx> #include <com/sun/star/uno/Any.h> #include <com/sun/star/uno/Any.hxx> #include <com/sun/star/uno/Reference.h> #include <com/sun/star/uno/Sequence.h> #include <com/sun/star/uno/Sequence.hxx> #include <com/sun/star/uno/Type.hxx> #include <config/_epilog.h> #include <config/_msvc_warnings_off.h> #include <config/_prolog.h> #include <cppu/macros.hxx> #include <cppuhelper/weakref.hxx> #include <cstddef> #include <cwchar> #include <float.h> #include <functional> #include <goodies/b3dcolor.hxx> #include <goodies/b3dcompo.hxx> #include <goodies/b3dentty.hxx> #include <goodies/b3dlight.hxx> #include <goodies/bucket.hxx> #include <goodies/matril3d.hxx> #include <offuh/com/sun/star/awt/Point.hdl> #include <offuh/com/sun/star/awt/Point.hpp> #include <offuh/com/sun/star/awt/Size.hdl> #include <offuh/com/sun/star/awt/Size.hpp> #include <offuh/com/sun/star/beans/PropertyVetoException.hdl> #include <offuh/com/sun/star/beans/PropertyVetoException.hpp> #include <offuh/com/sun/star/container/ElementExistException.hdl> #include <offuh/com/sun/star/container/ElementExistException.hpp> #include <offuh/com/sun/star/container/NoSuchElementException.hpp> #include <offuh/com/sun/star/container/xElementAccess.hdl> #include <offuh/com/sun/star/container/xElementAccess.hpp> #include <offuh/com/sun/star/container/xNameAccess.hpp> #include <offuh/com/sun/star/datatransfer/dataflavor.hdl> #include <offuh/com/sun/star/datatransfer/dnd/draggestureevent.hpp> #include <offuh/com/sun/star/datatransfer/dnd/dragsourcedragevent.hdl> #include <offuh/com/sun/star/datatransfer/dnd/dragsourcedragevent.hpp> #include <offuh/com/sun/star/datatransfer/dnd/dragsourcedropevent.hdl> #include <offuh/com/sun/star/datatransfer/dnd/dragsourceevent.hpp> #include <offuh/com/sun/star/datatransfer/dnd/droptargetdragenterevent.hdl> #include <offuh/com/sun/star/datatransfer/dnd/droptargetdragenterevent.hpp> #include <offuh/com/sun/star/datatransfer/dnd/droptargetdragevent.hdl> #include <offuh/com/sun/star/datatransfer/dnd/droptargetdragevent.hpp> #include <offuh/com/sun/star/datatransfer/dnd/droptargetdropevent.hpp> #include <offuh/com/sun/star/datatransfer/dnd/droptargetevent.hdl> #include <offuh/com/sun/star/datatransfer/dnd/droptargetevent.hpp> #include <offuh/com/sun/star/datatransfer/dnd/xdraggesturelistener.hdl> #include <offuh/com/sun/star/datatransfer/dnd/xdraggesturelistener.hpp> #include <offuh/com/sun/star/datatransfer/dnd/xdragsource.hdl> #include <offuh/com/sun/star/datatransfer/dnd/xdragsource.hpp> #include <offuh/com/sun/star/datatransfer/dnd/xdragsourcecontext.hdl> #include <offuh/com/sun/star/datatransfer/dnd/xdragsourcecontext.hpp> #include <offuh/com/sun/star/datatransfer/dnd/xdragsourcelistener.hdl> #include <offuh/com/sun/star/datatransfer/dnd/xdragsourcelistener.hpp> #include <offuh/com/sun/star/datatransfer/dnd/xdroptargetdragcontext.hpp> #include <offuh/com/sun/star/datatransfer/dnd/xdroptargetlistener.hdl> #include <offuh/com/sun/star/datatransfer/dnd/xdroptargetlistener.hpp> #include <offuh/com/sun/star/datatransfer/unsupportedflavorexception.hdl> #include <offuh/com/sun/star/datatransfer/xtransferable.hpp> #include <offuh/com/sun/star/drawing/xshape.hpp> #include <offuh/com/sun/star/embed/invalidstorageexception.hpp> #include <offuh/com/sun/star/embed/storagewrappedtargetexception.hdl> #include <offuh/com/sun/star/embed/storagewrappedtargetexception.hpp> #include <offuh/com/sun/star/embed/xstorage.hdl> #include <offuh/com/sun/star/embed/xstorage.hpp> #include <offuh/com/sun/star/io/buffersizeexceededexception.hpp> #include <offuh/com/sun/star/io/ioexception.hdl> #include <offuh/com/sun/star/io/notconnectedexception.hdl> #include <offuh/com/sun/star/io/notconnectedexception.hpp> #include <offuh/com/sun/star/io/xinputstream.hdl> #include <offuh/com/sun/star/io/xinputstream.hpp> #include <offuh/com/sun/star/io/xoutputstream.hdl> #include <offuh/com/sun/star/io/xoutputstream.hpp> #include <offuh/com/sun/star/io/xstream.hdl> #include <offuh/com/sun/star/lang/eventobject.hdl> #include <offuh/com/sun/star/lang/illegalargumentexception.hpp> #include <offuh/com/sun/star/lang/wrappedtargetexception.hdl> #include <offuh/com/sun/star/lang/wrappedtargetexception.hpp> #include <offuh/com/sun/star/lang/xcomponent.hpp> #include <offuh/com/sun/star/lang/xeventlistener.hpp> #include <offuh/com/sun/star/packages/noencryptionexception.hdl> #include <offuh/com/sun/star/packages/noencryptionexception.hpp> #include <offuh/com/sun/star/packages/wrongpasswordexception.hdl> #include <offuh/com/sun/star/packages/wrongpasswordexception.hpp> #include <offuh/com/sun/star/uno/exception.hdl> #include <offuh/com/sun/star/uno/exception.hpp> #include <offuh/com/sun/star/uno/runtimeexception.hdl> #include <offuh/com/sun/star/uno/runtimeexception.hpp> #include <offuh/com/sun/star/uno/xadapter.hdl> #include <offuh/com/sun/star/uno/xadapter.hpp> #include <offuh/com/sun/star/uno/xinterface.hdl> #include <offuh/com/sun/star/uno/xreference.hdl> #include <offuh/com/sun/star/uno/xreference.hpp> #include <offuh/com/sun/star/uno/xweak.hpp> #include <osl/endian.h> #include <osl/interlck.h> #include <osl/mutex.hxx> #include <rtl/alloc.h> #include <rtl/string.h> #include <rtl/ustrbuf.h> #include <rtl/ustring.h> #include <sal/mathconf.h> #include <sal/types.h> #include <sot/exchange.hxx> #include <sot/factory.hxx> #include <sot/storage.hxx> #include <svtools/brdcst.hxx> #include <svtools/cenumitm.hxx> #include <svtools/cintitem.hxx> #include <svtools/fltrcfg.hxx> #include <svtools/intitem.hxx> #include <svtools/listener.hxx> #include <svtools/lstner.hxx> #include <svtools/pathoptions.hxx> #include <svtools/solar.hrc> #include <svtools/useroptions.hxx> #include <svx/editobj.hxx> #include <svx/eeitem.hxx> #include <svx/fmglob.hxx> #include <svx/outlobj.hxx> #include <svx/sdangitm.hxx> #include <svx/sderitm.hxx> #include <svx/sdmetitm.hxx> #include <svx/sdooitm.hxx> #include <svx/sdprcitm.hxx> #include <svx/sdrmasterpagedescriptor.hxx> #include <svx/sdrpageuser.hxx> #include <svx/sdtaitm.hxx> #include <svx/svdglue.hxx> #include <svx/svdlayer.hxx> #include <svx/svdoattr.hxx> #include <svx/svdobj.hxx> #include <svx/svdpage.hxx> #include <svx/svdpool.hxx> #include <svx/svdtrans.hxx> #include <svx/svdtypes.hxx> #include <svx/unoapi.hxx> #include <svx/volume3d.hxx> #include <svx/xcolit.hxx> #include <svx/xenum.hxx> #include <svx/xfillit0.hxx> #include <svx/xflasit.hxx> #include <svx/xlineit0.hxx> #include <svx/xlnasit.hxx> #include <svx/xtextit0.hxx> #include <tools/date.hxx> #include <tools/datetime.hxx> #include <tools/errcode.hxx> #include <tools/errinf.hxx> #include <tools/gen.hxx> #include <tools/globname.hxx> #include <tools/list.hxx> #include <tools/rc.hxx> #include <tools/rtti.hxx> #include <tools/solar.h> #include <tools/string.hxx> #include <tools/toolsdllapi.h> #include <tools/weakbase.h> #include <tools/weakbase.hxx> #include <typeinfo.h> #include <typeinfo> #include <typelib/typeclass.h> #include <typelib/typedescription.h> #include <typelib/uik.h> #include <uno/any2.h> #include <uno/lbnames.h> #include <uno/sequence2.h> #include <unotools/ucbstreamhelper.hxx> #include <vcl/apptypes.hxx> #include <vcl/bitmap.hxx> #include <vcl/bitmapex.hxx> #include <vcl/dllapi.h> #include <vcl/dndhelp.hxx> #include <vcl/edit.hxx> #include <vcl/field.hxx> #include <vcl/fldunit.hxx> #include <vcl/gdimtf.hxx> #include <vcl/inputctx.hxx> #include <vcl/jobset.hxx> #include <vcl/mapmod.hxx> #include <vcl/menu.hxx> #include <vcl/pointr.hxx> #include <vcl/print.hxx> #include <vcl/prntypes.hxx> #include <vcl/ptrstyle.hxx> #include <vcl/region.hxx> #include <vcl/salnativewidgets.hxx> #include <vcl/spinfld.hxx> #include <vcl/sv.h> #include <vcl/svapp.hxx> #include <vcl/vclevent.hxx> #include <vcl/window.hxx> #include <vcl/wintypes.hxx> #include <vos/macros.hxx> #include <vos/object.hxx> #include <vos/types.hxx> #include <wchar.h> #endif <commit_msg>#i10000# #include <sal/config.h><commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: precompiled_sc.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: kz $ $Date: 2006-12-14 16:17:59 $ * * 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): Generated on 2006-07-11 15:52:42.937361 #ifdef PRECOMPILED_HEADERS #include <sal/config.h> #include "scitems.hxx" #include <algorithm> #include <assert.h> #include <stdarg.h> #include <stddef.h> #include <stdio.h> #include <string.h> #include <iosfwd> #include <limits.h> #include <limits> #include <list> #include <math.h> #include <memory> #include <new> #include <cfloat> #include <basegfx/polygon/b2dpolygon.hxx> #include <basegfx/polygon/b3dpolygon.hxx> #include <basegfx/polygon/b3dpolypolygon.hxx> #include <com/sun/star/uno/Any.h> #include <com/sun/star/uno/Any.hxx> #include <com/sun/star/uno/Reference.h> #include <com/sun/star/uno/Sequence.h> #include <com/sun/star/uno/Sequence.hxx> #include <com/sun/star/uno/Type.hxx> #include <config/_epilog.h> #include <config/_msvc_warnings_off.h> #include <config/_prolog.h> #include <cppu/macros.hxx> #include <cppuhelper/weakref.hxx> #include <cstddef> #include <cwchar> #include <float.h> #include <functional> #include <goodies/b3dcolor.hxx> #include <goodies/b3dcompo.hxx> #include <goodies/b3dentty.hxx> #include <goodies/b3dlight.hxx> #include <goodies/bucket.hxx> #include <goodies/matril3d.hxx> #include <offuh/com/sun/star/awt/Point.hdl> #include <offuh/com/sun/star/awt/Point.hpp> #include <offuh/com/sun/star/awt/Size.hdl> #include <offuh/com/sun/star/awt/Size.hpp> #include <offuh/com/sun/star/beans/PropertyVetoException.hdl> #include <offuh/com/sun/star/beans/PropertyVetoException.hpp> #include <offuh/com/sun/star/container/ElementExistException.hdl> #include <offuh/com/sun/star/container/ElementExistException.hpp> #include <offuh/com/sun/star/container/NoSuchElementException.hpp> #include <offuh/com/sun/star/container/xElementAccess.hdl> #include <offuh/com/sun/star/container/xElementAccess.hpp> #include <offuh/com/sun/star/container/xNameAccess.hpp> #include <offuh/com/sun/star/datatransfer/dataflavor.hdl> #include <offuh/com/sun/star/datatransfer/dnd/draggestureevent.hpp> #include <offuh/com/sun/star/datatransfer/dnd/dragsourcedragevent.hdl> #include <offuh/com/sun/star/datatransfer/dnd/dragsourcedragevent.hpp> #include <offuh/com/sun/star/datatransfer/dnd/dragsourcedropevent.hdl> #include <offuh/com/sun/star/datatransfer/dnd/dragsourceevent.hpp> #include <offuh/com/sun/star/datatransfer/dnd/droptargetdragenterevent.hdl> #include <offuh/com/sun/star/datatransfer/dnd/droptargetdragenterevent.hpp> #include <offuh/com/sun/star/datatransfer/dnd/droptargetdragevent.hdl> #include <offuh/com/sun/star/datatransfer/dnd/droptargetdragevent.hpp> #include <offuh/com/sun/star/datatransfer/dnd/droptargetdropevent.hpp> #include <offuh/com/sun/star/datatransfer/dnd/droptargetevent.hdl> #include <offuh/com/sun/star/datatransfer/dnd/droptargetevent.hpp> #include <offuh/com/sun/star/datatransfer/dnd/xdraggesturelistener.hdl> #include <offuh/com/sun/star/datatransfer/dnd/xdraggesturelistener.hpp> #include <offuh/com/sun/star/datatransfer/dnd/xdragsource.hdl> #include <offuh/com/sun/star/datatransfer/dnd/xdragsource.hpp> #include <offuh/com/sun/star/datatransfer/dnd/xdragsourcecontext.hdl> #include <offuh/com/sun/star/datatransfer/dnd/xdragsourcecontext.hpp> #include <offuh/com/sun/star/datatransfer/dnd/xdragsourcelistener.hdl> #include <offuh/com/sun/star/datatransfer/dnd/xdragsourcelistener.hpp> #include <offuh/com/sun/star/datatransfer/dnd/xdroptargetdragcontext.hpp> #include <offuh/com/sun/star/datatransfer/dnd/xdroptargetlistener.hdl> #include <offuh/com/sun/star/datatransfer/dnd/xdroptargetlistener.hpp> #include <offuh/com/sun/star/datatransfer/unsupportedflavorexception.hdl> #include <offuh/com/sun/star/datatransfer/xtransferable.hpp> #include <offuh/com/sun/star/drawing/xshape.hpp> #include <offuh/com/sun/star/embed/invalidstorageexception.hpp> #include <offuh/com/sun/star/embed/storagewrappedtargetexception.hdl> #include <offuh/com/sun/star/embed/storagewrappedtargetexception.hpp> #include <offuh/com/sun/star/embed/xstorage.hdl> #include <offuh/com/sun/star/embed/xstorage.hpp> #include <offuh/com/sun/star/io/buffersizeexceededexception.hpp> #include <offuh/com/sun/star/io/ioexception.hdl> #include <offuh/com/sun/star/io/notconnectedexception.hdl> #include <offuh/com/sun/star/io/notconnectedexception.hpp> #include <offuh/com/sun/star/io/xinputstream.hdl> #include <offuh/com/sun/star/io/xinputstream.hpp> #include <offuh/com/sun/star/io/xoutputstream.hdl> #include <offuh/com/sun/star/io/xoutputstream.hpp> #include <offuh/com/sun/star/io/xstream.hdl> #include <offuh/com/sun/star/lang/eventobject.hdl> #include <offuh/com/sun/star/lang/illegalargumentexception.hpp> #include <offuh/com/sun/star/lang/wrappedtargetexception.hdl> #include <offuh/com/sun/star/lang/wrappedtargetexception.hpp> #include <offuh/com/sun/star/lang/xcomponent.hpp> #include <offuh/com/sun/star/lang/xeventlistener.hpp> #include <offuh/com/sun/star/packages/noencryptionexception.hdl> #include <offuh/com/sun/star/packages/noencryptionexception.hpp> #include <offuh/com/sun/star/packages/wrongpasswordexception.hdl> #include <offuh/com/sun/star/packages/wrongpasswordexception.hpp> #include <offuh/com/sun/star/uno/exception.hdl> #include <offuh/com/sun/star/uno/exception.hpp> #include <offuh/com/sun/star/uno/runtimeexception.hdl> #include <offuh/com/sun/star/uno/runtimeexception.hpp> #include <offuh/com/sun/star/uno/xadapter.hdl> #include <offuh/com/sun/star/uno/xadapter.hpp> #include <offuh/com/sun/star/uno/xinterface.hdl> #include <offuh/com/sun/star/uno/xreference.hdl> #include <offuh/com/sun/star/uno/xreference.hpp> #include <offuh/com/sun/star/uno/xweak.hpp> #include <osl/endian.h> #include <osl/interlck.h> #include <osl/mutex.hxx> #include <rtl/alloc.h> #include <rtl/string.h> #include <rtl/ustrbuf.h> #include <rtl/ustring.h> #include <sal/mathconf.h> #include <sal/types.h> #include <sot/exchange.hxx> #include <sot/factory.hxx> #include <sot/storage.hxx> #include <svtools/brdcst.hxx> #include <svtools/cenumitm.hxx> #include <svtools/cintitem.hxx> #include <svtools/fltrcfg.hxx> #include <svtools/intitem.hxx> #include <svtools/listener.hxx> #include <svtools/lstner.hxx> #include <svtools/pathoptions.hxx> #include <svtools/solar.hrc> #include <svtools/useroptions.hxx> #include <svx/editobj.hxx> #include <svx/eeitem.hxx> #include <svx/fmglob.hxx> #include <svx/outlobj.hxx> #include <svx/sdangitm.hxx> #include <svx/sderitm.hxx> #include <svx/sdmetitm.hxx> #include <svx/sdooitm.hxx> #include <svx/sdprcitm.hxx> #include <svx/sdrmasterpagedescriptor.hxx> #include <svx/sdrpageuser.hxx> #include <svx/sdtaitm.hxx> #include <svx/svdglue.hxx> #include <svx/svdlayer.hxx> #include <svx/svdoattr.hxx> #include <svx/svdobj.hxx> #include <svx/svdpage.hxx> #include <svx/svdpool.hxx> #include <svx/svdtrans.hxx> #include <svx/svdtypes.hxx> #include <svx/unoapi.hxx> #include <svx/volume3d.hxx> #include <svx/xcolit.hxx> #include <svx/xenum.hxx> #include <svx/xfillit0.hxx> #include <svx/xflasit.hxx> #include <svx/xlineit0.hxx> #include <svx/xlnasit.hxx> #include <svx/xtextit0.hxx> #include <tools/date.hxx> #include <tools/datetime.hxx> #include <tools/errcode.hxx> #include <tools/errinf.hxx> #include <tools/gen.hxx> #include <tools/globname.hxx> #include <tools/list.hxx> #include <tools/rc.hxx> #include <tools/rtti.hxx> #include <tools/solar.h> #include <tools/string.hxx> #include <tools/toolsdllapi.h> #include <tools/weakbase.h> #include <tools/weakbase.hxx> #include <typeinfo.h> #include <typeinfo> #include <typelib/typeclass.h> #include <typelib/typedescription.h> #include <typelib/uik.h> #include <uno/any2.h> #include <uno/lbnames.h> #include <uno/sequence2.h> #include <unotools/ucbstreamhelper.hxx> #include <vcl/apptypes.hxx> #include <vcl/bitmap.hxx> #include <vcl/bitmapex.hxx> #include <vcl/dllapi.h> #include <vcl/dndhelp.hxx> #include <vcl/edit.hxx> #include <vcl/field.hxx> #include <vcl/fldunit.hxx> #include <vcl/gdimtf.hxx> #include <vcl/inputctx.hxx> #include <vcl/jobset.hxx> #include <vcl/mapmod.hxx> #include <vcl/menu.hxx> #include <vcl/pointr.hxx> #include <vcl/print.hxx> #include <vcl/prntypes.hxx> #include <vcl/ptrstyle.hxx> #include <vcl/region.hxx> #include <vcl/salnativewidgets.hxx> #include <vcl/spinfld.hxx> #include <vcl/sv.h> #include <vcl/svapp.hxx> #include <vcl/vclevent.hxx> #include <vcl/window.hxx> #include <vcl/wintypes.hxx> #include <vos/macros.hxx> #include <vos/object.hxx> #include <vos/types.hxx> #include <wchar.h> #endif <|endoftext|>
<commit_before><commit_msg>Revert this to build on msvc 2008<commit_after><|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: drformsh.hxx,v $ * * $Revision: 1.1.1.1 $ * * last change: $Author: hr $ $Date: 2000-09-18 16:44:58 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef DRFORMSH_HXX #define DRFORMSH_HXX #ifndef _SFX_SHELL_HXX //autogen #include <sfx2/shell.hxx> #endif #include "shellids.hxx" #ifndef _SFXMODULE_HXX //autogen #include <sfx2/module.hxx> #endif #ifndef _SVDMARK_HXX //autogen #include <svx/svdmark.hxx> #endif class ScViewData; #include "drawsh.hxx" class ScDrawFormShell: public ScDrawShell { public: TYPEINFO(); SFX_DECL_INTERFACE(SCID_FORM_SHELL); ScDrawFormShell(ScViewData* pData); virtual ~ScDrawFormShell(); // void Execute(SfxRequest &); // void GetState(SfxItemSet &); }; #endif <commit_msg>INTEGRATION: CWS ooo19126 (1.1.1.1.942); FILE MERGED 2005/09/05 15:05:18 rt 1.1.1.1.942.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: drformsh.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: rt $ $Date: 2005-09-08 21:22:40 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef DRFORMSH_HXX #define DRFORMSH_HXX #ifndef _SFX_SHELL_HXX //autogen #include <sfx2/shell.hxx> #endif #include "shellids.hxx" #ifndef _SFXMODULE_HXX //autogen #include <sfx2/module.hxx> #endif #ifndef _SVDMARK_HXX //autogen #include <svx/svdmark.hxx> #endif class ScViewData; #include "drawsh.hxx" class ScDrawFormShell: public ScDrawShell { public: TYPEINFO(); SFX_DECL_INTERFACE(SCID_FORM_SHELL); ScDrawFormShell(ScViewData* pData); virtual ~ScDrawFormShell(); // void Execute(SfxRequest &); // void GetState(SfxItemSet &); }; #endif <|endoftext|>
<commit_before>// // weak_symbols.cpp // Parse // // Created by Andrew Hunter on 06/05/2011. // Copyright 2011 __MyCompanyName__. All rights reserved. // #include "TameParse/Lr/weak_symbols.h" using namespace std; using namespace dfa; using namespace contextfree; using namespace lr; /// \brief Constructs a translator with no weak symbols weak_symbols::weak_symbols(const grammar* gram) : m_WeakSymbols(gram) , m_Grammar(gram) { } /// \brief Constructs a rewriter with the specified map of strong to weak symbols weak_symbols::weak_symbols(const item_map& map, const grammar* gram) : m_StrongToWeak(map) , m_WeakSymbols(gram) , m_Grammar(gram) { } /// \brief Copy constructor weak_symbols::weak_symbols(const weak_symbols& copyFrom) : m_StrongToWeak(copyFrom.m_StrongToWeak) , m_WeakSymbols(copyFrom.m_WeakSymbols) , m_Grammar(copyFrom.m_Grammar) { } /// \brief Destructor weak_symbols::~weak_symbols() { } /// \brief Maps the specified strong symbol to the specified set of weak symbols void weak_symbols::add_symbols(const contextfree::item_container& strong, const contextfree::item_set& weak) { // Merge the set of symbols for this strong symbol item_map::iterator weakForStrong = m_StrongToWeak.find(strong); if (weakForStrong == m_StrongToWeak.end()) { weakForStrong = m_StrongToWeak.insert(item_map::value_type(strong, item_set(m_Grammar))).first; } weakForStrong->second.merge(weak); // Store these as weak symbols m_WeakSymbols.merge(weak); } /// \brief Given a set of weak symbols and a DFA (note: NOT an NDFA), determines the appropriate strong symbols and adds them void weak_symbols::add_symbols(ndfa& dfa, const item_set& weak, terminal_dictionary& terminals) { // Nothing to do if there are no weak symbols if (weak.empty()) { return; } // Create a set of the identifiers of the weak terminals in the set set<int> weakIdentifiers; for (item_set::const_iterator it = weak.begin(); it != weak.end(); ++it) { // Only terminal symbols are returned by a NDFA if ((*it)->type() != item::terminal) continue; // Map this item weakIdentifiers.insert((*it)->symbol()); } // Map of weak to strong symbols map<int, int> weakToStrong; // Iterate through all of the DFA states typedef ndfa::accept_action_list accept_actions; for (int state = 0; state < dfa.count_states(); state++) { // Get the accepting actions for this state const accept_actions& accept = dfa.actions_for_state(state); // Ignore this state if it has no accepting actions if (accept.empty()) continue; // Iterate through the accepting action list and determine the 'strongest' symbol int strongest = 0x7fffffff; set<int> usedWeak; for (accept_actions::const_iterator it = accept.begin(); it != accept.end(); it++) { int sym = (*it)->symbol(); // Ignore weak symbols if (weakIdentifiers.find(sym) != weakIdentifiers.end()) { usedWeak.insert(sym); continue; } // Lower symbol IDs are stronger than weaker ones, and the strongest ID is the one that will be accepted // (Same as is defined in the ordering of accept_action) if (sym < strongest) { strongest = sym; } } // If no 'strongest' symbol was found, then all the symbols here are weak, and we can ignore this state if (strongest == 0x7fffffff) continue; // Also can ignore the state if no weak symbols were found if (usedWeak.empty()) continue; // Map the weak symbols we found to this identifier for (set<int>::iterator it = usedWeak.begin(); it != usedWeak.end(); it++) { if (weakToStrong.find(*it) == weakToStrong.end()) { // This is the first conflict between the two symbols. Just mark out the mapping. weakToStrong[*it] = strongest; } else if (weakToStrong[*it] != strongest) { // The weak symbol is used somewhere else with a different meaning // NOTE: this isn't ideal, as if there's an identical conflict somewhere else we generate more and more symbols for each conflicting // state, while we only need one new symbol for each (weak, strong) pair. // Split the weak symbol so that we have two different meanings int splitSymbolId = terminals.split(*it); // Change the accepting action for this state so that it accepts the new symbol dfa.clear_accept(state); dfa.accept(state, splitSymbolId); // Map this in the weakToStrong table weakToStrong[splitSymbolId] = strongest; } } } // TODO: if a weak symbol maps to several strong identifiers, it needs to be split into several symbols // Fill in the strong map for each weak symbol for (map<int, int>::iterator it = weakToStrong.begin(); it != weakToStrong.end(); it++) { // Use the first strong symbol for this weak symbol item_container strongTerm(new terminal(it->second), true); item_container weakTerm(new terminal(it->first), true); item_map::iterator weakForStrong = m_StrongToWeak.find(strongTerm); if (weakForStrong == m_StrongToWeak.end()) { weakForStrong = m_StrongToWeak.insert(item_map::value_type(strongTerm, item_set(m_Grammar))).first; } weakForStrong->second.insert(weakTerm); } // Add to the list of weak symbols m_WeakSymbols.merge(weak); } /// \brief Modifies the specified set of actions according to the rules in this rewriter /// /// To deal with weak symbols, several rewrites are performed. /// /// * All shift actions are left intact (whether weak or strong) /// * All actions for symbols that are 'strong' (not in the m_WeakSymbols table) are left intact /// * Reduce actions on weak symbols where there is an equivalent shift or reduce action on a strong symbol /// are changed to weak reduce actions /// * For strong symbols, any equivalent weak symbol that does not have an action other than weak reduce, the /// same action is added /// /// For states that do not contain any actions containing strong symbols with weak equivalents, there is no /// need to change the contents of the state. /// /// Something to note is that this will change the reduce part of conflicts to refer to the action defined by /// the strong symbol instead of the weak symbol. /// /// Something else to note is that if a strong symbol is considered for an action before a weak symbol where /// there is a potential clash, then it's likely that the parser will be incorrect as weak reduce actions for /// the weak symbol will not be considered in many cases. void weak_symbols::rewrite_actions(int state, lr_action_set& actions, const lalr_builder& builder) const { // Determine if there are any actions referring to strong symbols in this action set bool haveStrong = false; for (lr_action_set::const_iterator it = actions.begin(); it != actions.end(); it++) { // This only deals with actions on terminal items if ((*it)->item()->type() != item::terminal) continue; // See if the symbol is marked as being 'strong' and has weak symbols associated with it item_map::const_iterator found = m_StrongToWeak.find((*it)->item()); if (found != m_StrongToWeak.end() && !found->second.empty()) { haveStrong = true; break; } } // If none of the actions reference strong items with weak equivalents, then the actions can be left as they are if (!haveStrong) return; // Start building up a new set of actions lr_action_set newActions; // Add actions for any strong symbols, and remember the weak symbols that already have actions map<int, int> weakSymbols; // Maps symbols to # actions that refer to them stack<lr_action_container> weakActions; // Weak actions not processed in the first pass stack<lr_action_container> strongActions; // Strong actions that might have associated weak symbols for (lr_action_set::const_iterator act = actions.begin(); act != actions.end(); act++) { // Actions on non-terminal symbols should be preserved if ((*act)->item()->type() != item::terminal) { newActions.insert(*act); continue; } // Work out if this action is on a strong symbol bool isStrong = !m_WeakSymbols.contains((*act)->item()); // Actions on strong symbols should be preserved without alteration if (isStrong) { strongActions.push(*act); newActions.insert(*act); continue; } // Fetch the symbol for this action int sym = (*act)->item()->symbol(); // Mark this weak symbol as having an existing action weakSymbols[sym]++; // Push on to the set of weak actions weakActions.push(*act); } // Transform the actions associated with weak symbols while (!weakActions.empty()) { // Get the next action const lr_action_container& act = weakActions.top(); // How this is rewritten depends on the action switch (act->type()) { case lr_action::act_shift: case lr_action::act_shiftstrong: case lr_action::act_ignore: case lr_action::act_accept: // Preserve the action newActions.insert(act); break; case lr_action::act_reduce: case lr_action::act_weakreduce: { // Reduce actions are rewritten as weak reduce actions // TODO: if the strong symbol equivalent of this weak symbol is not present in the action, then // leave this as a standard reduce lr_action_container weakReduce(new lr_action(lr_action::act_weakreduce, act->item(), act->next_state(), act->rule()), true); newActions.insert(weakReduce); // Remove from the weak symbols table if there are no other actions for this symbol // This means that if there is a strong symbol that is equivalent to this weak symbol that the actions // for that symbol will be generated. If the strong symbol has a higher priority than the weak action // (by default: has a lower symbol ID), then its actions will be considered first, which is incorrect. int sym = act->item()->symbol(); map<int, int>::iterator found = weakSymbols.find(sym); if (found != weakSymbols.end()) { found->second--; if (found->second < 0) { weakSymbols.erase(found); } } break; } default: // ?? unknown action ?? // Remove unknown actions that seem to refer to weak symbols break; } // Next action weakActions.pop(); } // For any action on a strong symbol, generate the same action for equivalent weak symbols (if there is no equivalent action) // TODO: if a new action is the same as an existing weak symbol action (ie, the weak symbol has produced a weak reduce // of the same rule) then we only need one action for (; !strongActions.empty(); strongActions.pop()) { // Get the next action const lr_action_container& act = strongActions.top(); // Look up the equivalent weak symbols for this action item_map::const_iterator equivalent = m_StrongToWeak.find(act->item()); // Nothing to do if there are no equivalent symbols if (equivalent == m_StrongToWeak.end()) continue; // Iterate through the weak symbols and generate equivalent actions for (item_set::const_iterator weakEquiv = equivalent->second.begin(); weakEquiv != equivalent->second.end(); ++weakEquiv) { // Can't deal with non-terminal symbols (should be none, but you can technically add them) if ((*weakEquiv)->type() != item::terminal) continue; // Get the symbol ID of this equivalent symbol int symId = (*weakEquiv)->symbol(); // Nothing to do if this symbol has an alternative action if (weakSymbols.find(symId) != weakSymbols.end()) continue; // Add a duplicate action referring to the weak symbol, identical to the action for the strong symbol lr_action_container weakEquivAct(new lr_action(*act, *weakEquiv), true); // Shift actions become shift-strong actions (so the symbol ID is substituted) if (weakEquivAct->type() == lr_action::act_shift) { weakEquivAct->set_type(lr_action::act_shiftstrong); } newActions.insert(weakEquivAct); } } // Update the action table with our results actions = newActions; } /// \brief Creates a clone of this rewriter action_rewriter* weak_symbols::clone() const { return new weak_symbols(*this); } <commit_msg>A guard action does not 'use' a weak symbol as such (though you do end up with guard actions for both the strong and weak equivalents if there's a conflict)<commit_after>// // weak_symbols.cpp // Parse // // Created by Andrew Hunter on 06/05/2011. // Copyright 2011 __MyCompanyName__. All rights reserved. // #include "TameParse/Lr/weak_symbols.h" using namespace std; using namespace dfa; using namespace contextfree; using namespace lr; /// \brief Constructs a translator with no weak symbols weak_symbols::weak_symbols(const grammar* gram) : m_WeakSymbols(gram) , m_Grammar(gram) { } /// \brief Constructs a rewriter with the specified map of strong to weak symbols weak_symbols::weak_symbols(const item_map& map, const grammar* gram) : m_StrongToWeak(map) , m_WeakSymbols(gram) , m_Grammar(gram) { } /// \brief Copy constructor weak_symbols::weak_symbols(const weak_symbols& copyFrom) : m_StrongToWeak(copyFrom.m_StrongToWeak) , m_WeakSymbols(copyFrom.m_WeakSymbols) , m_Grammar(copyFrom.m_Grammar) { } /// \brief Destructor weak_symbols::~weak_symbols() { } /// \brief Maps the specified strong symbol to the specified set of weak symbols void weak_symbols::add_symbols(const contextfree::item_container& strong, const contextfree::item_set& weak) { // Merge the set of symbols for this strong symbol item_map::iterator weakForStrong = m_StrongToWeak.find(strong); if (weakForStrong == m_StrongToWeak.end()) { weakForStrong = m_StrongToWeak.insert(item_map::value_type(strong, item_set(m_Grammar))).first; } weakForStrong->second.merge(weak); // Store these as weak symbols m_WeakSymbols.merge(weak); } /// \brief Given a set of weak symbols and a DFA (note: NOT an NDFA), determines the appropriate strong symbols and adds them void weak_symbols::add_symbols(ndfa& dfa, const item_set& weak, terminal_dictionary& terminals) { // Nothing to do if there are no weak symbols if (weak.empty()) { return; } // Create a set of the identifiers of the weak terminals in the set set<int> weakIdentifiers; for (item_set::const_iterator it = weak.begin(); it != weak.end(); ++it) { // Only terminal symbols are returned by a NDFA if ((*it)->type() != item::terminal) continue; // Map this item weakIdentifiers.insert((*it)->symbol()); } // Map of weak to strong symbols map<int, int> weakToStrong; // Iterate through all of the DFA states typedef ndfa::accept_action_list accept_actions; for (int state = 0; state < dfa.count_states(); state++) { // Get the accepting actions for this state const accept_actions& accept = dfa.actions_for_state(state); // Ignore this state if it has no accepting actions if (accept.empty()) continue; // Iterate through the accepting action list and determine the 'strongest' symbol int strongest = 0x7fffffff; set<int> usedWeak; for (accept_actions::const_iterator it = accept.begin(); it != accept.end(); it++) { int sym = (*it)->symbol(); // Ignore weak symbols if (weakIdentifiers.find(sym) != weakIdentifiers.end()) { usedWeak.insert(sym); continue; } // Lower symbol IDs are stronger than weaker ones, and the strongest ID is the one that will be accepted // (Same as is defined in the ordering of accept_action) if (sym < strongest) { strongest = sym; } } // If no 'strongest' symbol was found, then all the symbols here are weak, and we can ignore this state if (strongest == 0x7fffffff) continue; // Also can ignore the state if no weak symbols were found if (usedWeak.empty()) continue; // Map the weak symbols we found to this identifier for (set<int>::iterator it = usedWeak.begin(); it != usedWeak.end(); it++) { if (weakToStrong.find(*it) == weakToStrong.end()) { // This is the first conflict between the two symbols. Just mark out the mapping. weakToStrong[*it] = strongest; } else if (weakToStrong[*it] != strongest) { // The weak symbol is used somewhere else with a different meaning // NOTE: this isn't ideal, as if there's an identical conflict somewhere else we generate more and more symbols for each conflicting // state, while we only need one new symbol for each (weak, strong) pair. // Split the weak symbol so that we have two different meanings int splitSymbolId = terminals.split(*it); // Change the accepting action for this state so that it accepts the new symbol dfa.clear_accept(state); dfa.accept(state, splitSymbolId); // Map this in the weakToStrong table weakToStrong[splitSymbolId] = strongest; } } } // TODO: if a weak symbol maps to several strong identifiers, it needs to be split into several symbols // Fill in the strong map for each weak symbol for (map<int, int>::iterator it = weakToStrong.begin(); it != weakToStrong.end(); it++) { // Use the first strong symbol for this weak symbol item_container strongTerm(new terminal(it->second), true); item_container weakTerm(new terminal(it->first), true); item_map::iterator weakForStrong = m_StrongToWeak.find(strongTerm); if (weakForStrong == m_StrongToWeak.end()) { weakForStrong = m_StrongToWeak.insert(item_map::value_type(strongTerm, item_set(m_Grammar))).first; } weakForStrong->second.insert(weakTerm); } // Add to the list of weak symbols m_WeakSymbols.merge(weak); } /// \brief Modifies the specified set of actions according to the rules in this rewriter /// /// To deal with weak symbols, several rewrites are performed. /// /// * All shift actions are left intact (whether weak or strong) /// * All actions for symbols that are 'strong' (not in the m_WeakSymbols table) are left intact /// * Reduce actions on weak symbols where there is an equivalent shift or reduce action on a strong symbol /// are changed to weak reduce actions /// * For strong symbols, any equivalent weak symbol that does not have an action other than weak reduce, the /// same action is added /// /// For states that do not contain any actions containing strong symbols with weak equivalents, there is no /// need to change the contents of the state. /// /// Something to note is that this will change the reduce part of conflicts to refer to the action defined by /// the strong symbol instead of the weak symbol. /// /// Something else to note is that if a strong symbol is considered for an action before a weak symbol where /// there is a potential clash, then it's likely that the parser will be incorrect as weak reduce actions for /// the weak symbol will not be considered in many cases. void weak_symbols::rewrite_actions(int state, lr_action_set& actions, const lalr_builder& builder) const { // Determine if there are any actions referring to strong symbols in this action set bool haveStrong = false; for (lr_action_set::const_iterator it = actions.begin(); it != actions.end(); it++) { // This only deals with actions on terminal items if ((*it)->item()->type() != item::terminal) continue; // See if the symbol is marked as being 'strong' and has weak symbols associated with it item_map::const_iterator found = m_StrongToWeak.find((*it)->item()); if (found != m_StrongToWeak.end() && !found->second.empty()) { haveStrong = true; break; } } // If none of the actions reference strong items with weak equivalents, then the actions can be left as they are if (!haveStrong) return; // Start building up a new set of actions lr_action_set newActions; // Add actions for any strong symbols, and remember the weak symbols that already have actions map<int, int> weakSymbols; // Maps symbols to # actions that refer to them stack<lr_action_container> weakActions; // Weak actions not processed in the first pass stack<lr_action_container> strongActions; // Strong actions that might have associated weak symbols for (lr_action_set::const_iterator act = actions.begin(); act != actions.end(); act++) { // Actions on non-terminal symbols should be preserved if ((*act)->item()->type() != item::terminal) { newActions.insert(*act); continue; } // Work out if this action is on a strong symbol bool isStrong = !m_WeakSymbols.contains((*act)->item()); // Actions on strong symbols should be preserved without alteration if (isStrong) { strongActions.push(*act); newActions.insert(*act); continue; } // Guard actions do not mark a weak symbol as 'used' if ((*act)->type() == lr_action::act_guard) { continue; } // Fetch the symbol for this action int sym = (*act)->item()->symbol(); // Mark this weak symbol as having an existing action weakSymbols[sym]++; // Push on to the set of weak actions weakActions.push(*act); } // Transform the actions associated with weak symbols while (!weakActions.empty()) { // Get the next action const lr_action_container& act = weakActions.top(); // How this is rewritten depends on the action switch (act->type()) { case lr_action::act_shift: case lr_action::act_shiftstrong: case lr_action::act_ignore: case lr_action::act_accept: case lr_action::act_guard: // Preserve the action newActions.insert(act); break; case lr_action::act_reduce: case lr_action::act_weakreduce: { // Reduce actions are rewritten as weak reduce actions // TODO: if the strong symbol equivalent of this weak symbol is not present in the action, then // leave this as a standard reduce lr_action_container weakReduce(new lr_action(lr_action::act_weakreduce, act->item(), act->next_state(), act->rule()), true); newActions.insert(weakReduce); // Remove from the weak symbols table if there are no other actions for this symbol // This means that if there is a strong symbol that is equivalent to this weak symbol that the actions // for that symbol will be generated. If the strong symbol has a higher priority than the weak action // (by default: has a lower symbol ID), then its actions will be considered first, which is incorrect. int sym = act->item()->symbol(); map<int, int>::iterator found = weakSymbols.find(sym); if (found != weakSymbols.end()) { found->second--; if (found->second < 0) { weakSymbols.erase(found); } } break; } default: // ?? unknown action ?? // Remove unknown actions that seem to refer to weak symbols break; } // Next action weakActions.pop(); } // For any action on a strong symbol, generate the same action for equivalent weak symbols (if there is no equivalent action) // TODO: if a new action is the same as an existing weak symbol action (ie, the weak symbol has produced a weak reduce // of the same rule) then we only need one action for (; !strongActions.empty(); strongActions.pop()) { // Get the next action const lr_action_container& act = strongActions.top(); // Look up the equivalent weak symbols for this action item_map::const_iterator equivalent = m_StrongToWeak.find(act->item()); // Nothing to do if there are no equivalent symbols if (equivalent == m_StrongToWeak.end()) continue; // Iterate through the weak symbols and generate equivalent actions for (item_set::const_iterator weakEquiv = equivalent->second.begin(); weakEquiv != equivalent->second.end(); ++weakEquiv) { // Can't deal with non-terminal symbols (should be none, but you can technically add them) if ((*weakEquiv)->type() != item::terminal) continue; // Get the symbol ID of this equivalent symbol int symId = (*weakEquiv)->symbol(); // Nothing to do if this symbol has an alternative action if (weakSymbols.find(symId) != weakSymbols.end()) continue; // Add a duplicate action referring to the weak symbol, identical to the action for the strong symbol lr_action_container weakEquivAct(new lr_action(*act, *weakEquiv), true); // Shift actions become shift-strong actions (so the symbol ID is substituted) if (weakEquivAct->type() == lr_action::act_shift) { weakEquivAct->set_type(lr_action::act_shiftstrong); } newActions.insert(weakEquivAct); } } // Update the action table with our results actions = newActions; } /// \brief Creates a clone of this rewriter action_rewriter* weak_symbols::clone() const { return new weak_symbols(*this); } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: olinewin.hxx,v $ * * $Revision: 1.7 $ * * last change: $Author: obo $ $Date: 2004-06-04 11:36:51 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef SC_OLINEWIN_HXX #define SC_OLINEWIN_HXX #ifndef SC_VIEWDATA_HXX #include "viewdata.hxx" #endif class ScOutlineEntry; class ScOutlineArray; class ScOutlineTable; // ============================================================================ enum ScOutlineMode { SC_OUTLINE_HOR, SC_OUTLINE_VER }; // ---------------------------------------------------------------------------- /** The window left of or above the spreadsheet containing the outline groups and controls to expand/collapse them. */ class ScOutlineWindow : public Window { private: ScViewData& mrViewData; /// View data containing the document. ScSplitPos meWhich; /// Which area in split window. bool mbHoriz; /// true = Horizontal orientation. bool mbMirrorEntries; /// true = mirror the order of entries (including header) bool mbMirrorLevels; /// true = mirror the order of levels, including the border ImageList* mpSymbols; /// Symbols for buttons. Color maLineColor; /// Line color for expanded groups. sal_Int32 mnHeaderSize; /// Size of the header area in entry direction. sal_Int32 mnHeaderPos; /// Position of the header area in entry direction. sal_Int32 mnMainFirstPos; /// First position of main area in entry direction. sal_Int32 mnMainLastPos; /// Last position of main area in entry direction. sal_uInt16 mnMTLevel; /// Mouse tracking: Level of active button. sal_uInt16 mnMTEntry; /// Mouse tracking: Entry index of active button. bool mbMTActive; /// Mouse tracking active? bool mbMTPressed; /// Mouse tracking: Button currently drawed pressed? Rectangle maFocusRect; /// Focus rectangle on screen. sal_uInt16 mnFocusLevel; /// Level of focused button. sal_uInt16 mnFocusEntry; /// Entry index of focused button. bool mbDontDrawFocus; /// Do not redraw focus in next Paint(). public: ScOutlineWindow( Window* pParent, ScOutlineMode eMode, ScViewData* pViewData, ScSplitPos eWhich ); virtual ~ScOutlineWindow(); /** Sets the size of the header area (width/height dep. on window type). */ void SetHeaderSize( sal_Int32 nNewSize ); /** Returns the width/height the window needs to show all levels. */ sal_Int32 GetDepthSize() const; /** Scrolls the window content by the specified amount of pixels. */ void ScrollPixel( sal_Int32 nDiff ); private: /** Initializes color and image settings. */ void InitSettings(); /** Returns the calc document. */ inline ScDocument& GetDoc() const { return *mrViewData.GetDocument(); } /** Returns the current sheet index. */ inline SCTAB GetTab() const { return mrViewData.GetTabNo(); } /** Returns the outline array of the corresponding document. */ const ScOutlineArray* GetOutlineArray() const; /** Returns the specified outline entry. */ const ScOutlineEntry* GetOutlineEntry( sal_uInt16 nLevel, sal_uInt16 nEntry ) const; /** Returns true, if the column/row is hidden. */ bool IsHidden( SCCOLROW nColRowIndex ) const; /** Returns true, if the column/row is filtered. */ bool IsFiltered( SCCOLROW nColRowIndex ) const; /** Returns true, if all columns/rows before nColRowIndex are hidden. */ bool IsFirstVisible( SCCOLROW nColRowIndex ) const; /** Returns the currently visible column/row range. */ void GetVisibleRange( SCCOLROW& rnColRowStart, SCCOLROW& rnColRowEnd ) const; /** Returns the point in the window of the specified position. */ Point GetPoint( sal_Int32 nLevelPos, sal_Int32 nEntryPos ) const; /** Returns the rectangle in the window of the specified position. */ Rectangle GetRectangle( sal_Int32 nLevelStart, sal_Int32 nEntryStart, sal_Int32 nLevelEnd, sal_Int32 nEntryEnd ) const; /** Returns the window size for the level coordinate. */ sal_Int32 GetOutputSizeLevel() const; /** Returns the window size for the entry coordinate. */ sal_Int32 GetOutputSizeEntry() const; /** Returns the count of levels of the outline array. 0 means no outlines. */ sal_uInt16 GetLevelCount() const; /** Returns the pixel position of the specified level. */ sal_Int32 GetLevelPos( sal_uInt16 nLevel ) const; /** Returns the level of the passed pixel position. */ sal_uInt16 GetLevelFromPos( sal_Int32 nLevelPos ) const; /** Returns the start coordinate of the specified column/row in the window. */ sal_Int32 GetColRowPos( SCCOLROW nColRowIndex ) const; /** Returns the entry position of header images. */ sal_Int32 GetHeaderEntryPos() const; /** Calculates the coordinates the outline entry takes in the window. @return false = no part of the group is visible (outside window or collapsed by parent group). */ bool GetEntryPos( sal_uInt16 nLevel, sal_uInt16 nEntry, sal_Int32& rnStartPos, sal_Int32& rnEndPos, sal_Int32& rnImagePos ) const; /** Calculates the absolute position of the image of the specified outline entry. @param nLevel The level of the entry. @param nEntry The entry index or SC_OL_HEADERENTRY for the header image. @return false = image is not visible. */ bool GetImagePos( sal_uInt16 nLevel, sal_uInt16 nEntry, Point& rPos ) const; /** Returns true, if the button of the specified entry is visible in the window. */ bool IsButtonVisible( sal_uInt16 nLevel, sal_uInt16 nEntry ) const; /** Returns true, if rPos is inside of a button or over the line of an expanded group. The outline entry data is stored in the passed variables. */ bool ItemHit( const Point& rPos, sal_uInt16& rnLevel, sal_uInt16& rnEntry, bool& rbButton ) const; /** Returns true, if rPos is inside of a button. The button data is stored in the passed variables. */ bool ButtonHit( const Point& rPos, sal_uInt16& rnLevel, sal_uInt16& rnEntry ) const; /** Returns true, if rPos is over the line of an expanded group. The outline entry data is stored in the passed variables. */ bool LineHit( const Point& rPos, sal_uInt16& rnLevel, sal_uInt16& rnEntry ) const; /** Performs an action with the specified item. @param nLevel The level of the entry. @param nEntry The entry index or SC_OL_HEADERENTRY for the header entry. */ void DoFunction( sal_uInt16 nLevel, sal_uInt16 nEntry ) const; /** Expands the specified entry (does nothing with header entries). */ void DoExpand( sal_uInt16 nLevel, sal_uInt16 nEntry ) const; /** Collapses the specified entry (does nothing with header entries). */ void DoCollapse( sal_uInt16 nLevel, sal_uInt16 nEntry ) const; /** Returns true, if the focused button is visible in the window. */ bool IsFocusButtonVisible() const; /** Calculates index of next/previous focus button in the current level (no paint). @param bFindVisible true = repeats until a visible button has been found. @return true = focus wrapped from end to start or vice versa. */ bool ImplMoveFocusByEntry( bool bForward, bool bFindVisible ); /** Calculates position of focus button in next/previous level (no paint). @return true = focus wrapped from end to start or vice versa. */ bool ImplMoveFocusByLevel( bool bForward ); /** Calculates position of focus button in tab order. @param bFindVisible true = repeats until a visible button has been found. @return true = focus wrapped from end to start or vice versa. */ bool ImplMoveFocusByTabOrder( bool bForward, bool bFindVisible ); /** If the focused entry is invisible, tries to move to visible position. */ void ImplMoveFocusToVisible( bool bForward ); /** Focuses next/previous button in the current level. */ void MoveFocusByEntry( bool bForward ); /** Focuses button in next/previous level. */ void MoveFocusByLevel( bool bForward ); /** Focuses next/previous button in tab order. */ void MoveFocusByTabOrder( bool bForward ); /** Starts mouse tracking after click on a button. */ void StartMouseTracking( sal_uInt16 nLevel, sal_uInt16 nEntry ); /** Returns whether mouse tracking mode is active. */ inline bool IsMouseTracking() const { return mbMTActive; } /** Ends mouse tracking. */ void EndMouseTracking(); /** Sets a clip region for the window area without header. */ void SetEntryAreaClipRegion(); /** Converts coordinates to real window points and draws the line. */ void DrawLineRel( sal_Int32 nLevelStart, sal_Int32 nEntryStart, sal_Int32 nLevelEnd, sal_Int32 nEntryEnd ); /** Converts coordinates to real window points and draws the rectangle. */ void DrawRectRel( sal_Int32 nLevelStart, sal_Int32 nEntryStart, sal_Int32 nLevelEnd, sal_Int32 nEntryEnd ); /** Draws the specified image unpressed. */ void DrawImageRel( sal_Int32 nLevelPos, sal_Int32 nEntryPos, sal_uInt16 nId ); /** Draws a pressed or unpressed border. */ void DrawBorder( const Point& rPos, bool bPressed ); /** Draws a pressed or unpressed border. */ void DrawBorderRel( sal_uInt16 nLevel, sal_uInt16 nEntry, bool bPressed ); /** Draws the focus rectangle into the focused button. */ void ShowFocus(); /** Erases the focus rectangle from the focused button. */ void HideFocus(); /** Scrolls the window in entry-relative direction. */ void ScrollRel( sal_Int32 nEntryDiff ); /** Scrolls the specified range of the window in entry-relative direction. */ void ScrollRel( sal_Int32 nEntryDiff, sal_Int32 nEntryStart, sal_Int32 nEntryEnd ); protected: virtual void Paint( const Rectangle& rRect ); virtual void Resize(); virtual void GetFocus(); virtual void LoseFocus(); virtual void MouseMove( const MouseEvent& rMEvt ); virtual void MouseButtonUp( const MouseEvent& rMEvt ); virtual void MouseButtonDown( const MouseEvent& rMEvt ); virtual void KeyInput( const KeyEvent& rKEvt ); public: virtual void DataChanged( const DataChangedEvent& rDCEvt ); }; // ============================================================================ #endif <commit_msg>INTEGRATION: CWS dr19 (1.6.122); FILE MERGED 2004/06/11 11:55:43 dr 1.6.122.2: RESYNC: (1.6-1.7); FILE MERGED 2004/06/03 18:16:34 dr 1.6.122.1: #i29530# loop while scrolling outline window, type correctness<commit_after>/************************************************************************* * * $RCSfile: olinewin.hxx,v $ * * $Revision: 1.8 $ * * last change: $Author: kz $ $Date: 2004-07-30 16:25:14 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef SC_OLINEWIN_HXX #define SC_OLINEWIN_HXX #ifndef SC_VIEWDATA_HXX #include "viewdata.hxx" #endif class ScOutlineEntry; class ScOutlineArray; class ScOutlineTable; // ============================================================================ enum ScOutlineMode { SC_OUTLINE_HOR, SC_OUTLINE_VER }; // ---------------------------------------------------------------------------- /** The window left of or above the spreadsheet containing the outline groups and controls to expand/collapse them. */ class ScOutlineWindow : public Window { private: ScViewData& mrViewData; /// View data containing the document. ScSplitPos meWhich; /// Which area in split window. bool mbHoriz; /// true = Horizontal orientation. bool mbMirrorEntries; /// true = mirror the order of entries (including header) bool mbMirrorLevels; /// true = mirror the order of levels, including the border ImageList* mpSymbols; /// Symbols for buttons. Color maLineColor; /// Line color for expanded groups. long mnHeaderSize; /// Size of the header area in entry direction. long mnHeaderPos; /// Position of the header area in entry direction. long mnMainFirstPos; /// First position of main area in entry direction. long mnMainLastPos; /// Last position of main area in entry direction. size_t mnMTLevel; /// Mouse tracking: Level of active button. size_t mnMTEntry; /// Mouse tracking: Entry index of active button. bool mbMTActive; /// Mouse tracking active? bool mbMTPressed; /// Mouse tracking: Button currently drawed pressed? Rectangle maFocusRect; /// Focus rectangle on screen. size_t mnFocusLevel; /// Level of focused button. size_t mnFocusEntry; /// Entry index of focused button. bool mbDontDrawFocus; /// Do not redraw focus in next Paint(). public: ScOutlineWindow( Window* pParent, ScOutlineMode eMode, ScViewData* pViewData, ScSplitPos eWhich ); virtual ~ScOutlineWindow(); /** Sets the size of the header area (width/height dep. on window type). */ void SetHeaderSize( long nNewSize ); /** Returns the width/height the window needs to show all levels. */ long GetDepthSize() const; /** Scrolls the window content by the specified amount of pixels. */ void ScrollPixel( long nDiff ); private: /** Initializes color and image settings. */ void InitSettings(); /** Returns the calc document. */ inline ScDocument& GetDoc() const { return *mrViewData.GetDocument(); } /** Returns the current sheet index. */ inline SCTAB GetTab() const { return mrViewData.GetTabNo(); } /** Returns the outline array of the corresponding document. */ const ScOutlineArray* GetOutlineArray() const; /** Returns the specified outline entry. */ const ScOutlineEntry* GetOutlineEntry( size_t nLevel, size_t nEntry ) const; /** Returns true, if the column/row is hidden. */ bool IsHidden( SCCOLROW nColRowIndex ) const; /** Returns true, if the column/row is filtered. */ bool IsFiltered( SCCOLROW nColRowIndex ) const; /** Returns true, if all columns/rows before nColRowIndex are hidden. */ bool IsFirstVisible( SCCOLROW nColRowIndex ) const; /** Returns the currently visible column/row range. */ void GetVisibleRange( SCCOLROW& rnColRowStart, SCCOLROW& rnColRowEnd ) const; /** Returns the point in the window of the specified position. */ Point GetPoint( long nLevelPos, long nEntryPos ) const; /** Returns the rectangle in the window of the specified position. */ Rectangle GetRectangle( long nLevelStart, long nEntryStart, long nLevelEnd, long nEntryEnd ) const; /** Returns the window size for the level coordinate. */ long GetOutputSizeLevel() const; /** Returns the window size for the entry coordinate. */ long GetOutputSizeEntry() const; /** Returns the count of levels of the outline array. 0 means no outlines. */ size_t GetLevelCount() const; /** Returns the pixel position of the specified level. */ long GetLevelPos( size_t nLevel ) const; /** Returns the level of the passed pixel position. */ size_t GetLevelFromPos( long nLevelPos ) const; /** Returns the start coordinate of the specified column/row in the window. */ long GetColRowPos( SCCOLROW nColRowIndex ) const; /** Returns the entry position of header images. */ long GetHeaderEntryPos() const; /** Calculates the coordinates the outline entry takes in the window. @return false = no part of the group is visible (outside window or collapsed by parent group). */ bool GetEntryPos( size_t nLevel, size_t nEntry, long& rnStartPos, long& rnEndPos, long& rnImagePos ) const; /** Calculates the absolute position of the image of the specified outline entry. @param nLevel The level of the entry. @param nEntry The entry index or SC_OL_HEADERENTRY for the header image. @return false = image is not visible. */ bool GetImagePos( size_t nLevel, size_t nEntry, Point& rPos ) const; /** Returns true, if the button of the specified entry is visible in the window. */ bool IsButtonVisible( size_t nLevel, size_t nEntry ) const; /** Returns true, if rPos is inside of a button or over the line of an expanded group. The outline entry data is stored in the passed variables. */ bool ItemHit( const Point& rPos, size_t& rnLevel, size_t& rnEntry, bool& rbButton ) const; /** Returns true, if rPos is inside of a button. The button data is stored in the passed variables. */ bool ButtonHit( const Point& rPos, size_t& rnLevel, size_t& rnEntry ) const; /** Returns true, if rPos is over the line of an expanded group. The outline entry data is stored in the passed variables. */ bool LineHit( const Point& rPos, size_t& rnLevel, size_t& rnEntry ) const; /** Performs an action with the specified item. @param nLevel The level of the entry. @param nEntry The entry index or SC_OL_HEADERENTRY for the header entry. */ void DoFunction( size_t nLevel, size_t nEntry ) const; /** Expands the specified entry (does nothing with header entries). */ void DoExpand( size_t nLevel, size_t nEntry ) const; /** Collapses the specified entry (does nothing with header entries). */ void DoCollapse( size_t nLevel, size_t nEntry ) const; /** Returns true, if the focused button is visible in the window. */ bool IsFocusButtonVisible() const; /** Calculates index of next/previous focus button in the current level (no paint). @param bFindVisible true = repeats until a visible button has been found. @return true = focus wrapped from end to start or vice versa. */ bool ImplMoveFocusByEntry( bool bForward, bool bFindVisible ); /** Calculates position of focus button in next/previous level (no paint). @return true = focus wrapped from end to start or vice versa. */ bool ImplMoveFocusByLevel( bool bForward ); /** Calculates position of focus button in tab order. @param bFindVisible true = repeats until a visible button has been found. @return true = focus wrapped from end to start or vice versa. */ bool ImplMoveFocusByTabOrder( bool bForward, bool bFindVisible ); /** If the focused entry is invisible, tries to move to visible position. */ void ImplMoveFocusToVisible( bool bForward ); /** Focuses next/previous button in the current level. */ void MoveFocusByEntry( bool bForward ); /** Focuses button in next/previous level. */ void MoveFocusByLevel( bool bForward ); /** Focuses next/previous button in tab order. */ void MoveFocusByTabOrder( bool bForward ); /** Starts mouse tracking after click on a button. */ void StartMouseTracking( size_t nLevel, size_t nEntry ); /** Returns whether mouse tracking mode is active. */ inline bool IsMouseTracking() const { return mbMTActive; } /** Ends mouse tracking. */ void EndMouseTracking(); /** Sets a clip region for the window area without header. */ void SetEntryAreaClipRegion(); /** Converts coordinates to real window points and draws the line. */ void DrawLineRel( long nLevelStart, long nEntryStart, long nLevelEnd, long nEntryEnd ); /** Converts coordinates to real window points and draws the rectangle. */ void DrawRectRel( long nLevelStart, long nEntryStart, long nLevelEnd, long nEntryEnd ); /** Draws the specified image unpressed. */ void DrawImageRel( long nLevelPos, long nEntryPos, USHORT nId ); /** Draws a pressed or unpressed border. */ void DrawBorderRel( size_t nLevel, size_t nEntry, bool bPressed ); /** Draws the focus rectangle into the focused button. */ void ShowFocus(); /** Erases the focus rectangle from the focused button. */ void HideFocus(); /** Scrolls the window in entry-relative direction. */ void ScrollRel( long nEntryDiff ); /** Scrolls the specified range of the window in entry-relative direction. */ void ScrollRel( long nEntryDiff, long nEntryStart, long nEntryEnd ); protected: virtual void Paint( const Rectangle& rRect ); virtual void Resize(); virtual void GetFocus(); virtual void LoseFocus(); virtual void MouseMove( const MouseEvent& rMEvt ); virtual void MouseButtonUp( const MouseEvent& rMEvt ); virtual void MouseButtonDown( const MouseEvent& rMEvt ); virtual void KeyInput( const KeyEvent& rKEvt ); public: virtual void DataChanged( const DataChangedEvent& rDCEvt ); }; // ============================================================================ #endif <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: opredlin.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2005-09-08 21:41:35 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _SC_OPREDLIN_HXX #define _SC_OPREDLIN_HXX #ifndef _SFXTABDLG_HXX //autogen #include <sfx2/tabdlg.hxx> #endif #ifndef _GROUP_HXX //autogen #include <vcl/group.hxx> #endif #ifndef _BUTTON_HXX //autogen #include <vcl/button.hxx> #endif #ifndef _LSTBOX_HXX //autogen #include <vcl/lstbox.hxx> #endif #ifndef _FIELD_HXX //autogen #include <vcl/field.hxx> #endif #ifndef _FIXED_HXX //autogen #include <vcl/fixed.hxx> #endif #ifndef _CTRLBOX_HXX //autogen #include <svtools/ctrlbox.hxx> #endif #ifndef _SVX_FNTCTRL_HXX //autogen #include <svx/fntctrl.hxx> #endif #ifndef _SVX_STRARRAY_HXX //autogen #include <svx/strarray.hxx> #endif /*----------------------------------------------------------------------- Beschreibung: Redlining-Optionen -----------------------------------------------------------------------*/ class ScRedlineOptionsTabPage : public SfxTabPage { FixedText aContentFT; ColorListBox aContentColorLB; FixedText aRemoveFT; ColorListBox aRemoveColorLB; FixedText aInsertFT; ColorListBox aInsertColorLB; FixedText aMoveFT; ColorListBox aMoveColorLB; FixedLine aChangedGB; String aAuthorStr; DECL_LINK( ColorHdl, ColorListBox *pColorLB ); public: ScRedlineOptionsTabPage( Window* pParent, const SfxItemSet& rSet ); ~ScRedlineOptionsTabPage(); static SfxTabPage* Create( Window* pParent, const SfxItemSet& rAttrSet ); virtual BOOL FillItemSet( SfxItemSet& rSet ); virtual void Reset( const SfxItemSet& rSet ); }; #endif <commit_msg>INTEGRATION: CWS changefileheader (1.3.700); FILE MERGED 2008/04/01 15:30:58 thb 1.3.700.2: #i85898# Stripping all external header guards 2008/03/31 17:15:45 rt 1.3.700.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: opredlin.hxx,v $ * $Revision: 1.4 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef _SC_OPREDLIN_HXX #define _SC_OPREDLIN_HXX #include <sfx2/tabdlg.hxx> #ifndef _GROUP_HXX //autogen #include <vcl/group.hxx> #endif #ifndef _BUTTON_HXX //autogen #include <vcl/button.hxx> #endif #ifndef _LSTBOX_HXX //autogen #include <vcl/lstbox.hxx> #endif #ifndef _FIELD_HXX //autogen #include <vcl/field.hxx> #endif #ifndef _FIXED_HXX //autogen #include <vcl/fixed.hxx> #endif #include <svtools/ctrlbox.hxx> #include <svx/fntctrl.hxx> #include <svx/strarray.hxx> /*----------------------------------------------------------------------- Beschreibung: Redlining-Optionen -----------------------------------------------------------------------*/ class ScRedlineOptionsTabPage : public SfxTabPage { FixedText aContentFT; ColorListBox aContentColorLB; FixedText aRemoveFT; ColorListBox aRemoveColorLB; FixedText aInsertFT; ColorListBox aInsertColorLB; FixedText aMoveFT; ColorListBox aMoveColorLB; FixedLine aChangedGB; String aAuthorStr; DECL_LINK( ColorHdl, ColorListBox *pColorLB ); public: ScRedlineOptionsTabPage( Window* pParent, const SfxItemSet& rSet ); ~ScRedlineOptionsTabPage(); static SfxTabPage* Create( Window* pParent, const SfxItemSet& rAttrSet ); virtual BOOL FillItemSet( SfxItemSet& rSet ); virtual void Reset( const SfxItemSet& rSet ); }; #endif <|endoftext|>
<commit_before>/* * Copyright (c) 2013 Ambroz Bizjak * 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 AUTHOR BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <stdint.h> #include <stdio.h> #include <math.h> #include <avr/io.h> #include <avr/interrupt.h> #define AMBROLIB_ABORT_ACTION { cli(); while (1); } #include <aprinter/meta/MakeTypeList.h> #include <aprinter/base/DebugObject.h> #include <aprinter/system/AvrEventLoop.h> #include <aprinter/system/AvrClock.h> #include <aprinter/system/AvrPins.h> #include <aprinter/system/AvrPinWatcher.h> #include <aprinter/system/AvrLock.h> #include <aprinter/printer/PrinterMain.h> using namespace APrinter; static const int clock_timer_prescaler = 2; using StepVelType = FixedPoint<11, false, -11-4>; using StepAccType = FixedPoint<11, false, -11-24>; static const int stepper_command_buffer_size_exp = 3; using LedBlinkInterval = AMBRO_WRAP_DOUBLE(0.5); using DefaultInactiveTime = AMBRO_WRAP_DOUBLE(60.0); using SpeedLimitMultiply = AMBRO_WRAP_DOUBLE(1.0 / 60.0); using XDefaultStepsPerUnit = AMBRO_WRAP_DOUBLE(80.0); using XDefaultMaxSpeed = AMBRO_WRAP_DOUBLE(80.0); using XDefaultMaxAccel = AMBRO_WRAP_DOUBLE(500.0); using XDefaultOffset = AMBRO_WRAP_DOUBLE(53.0); using XDefaultLimit = AMBRO_WRAP_DOUBLE(210.0); using XDefaultHomeFastMaxDist = AMBRO_WRAP_DOUBLE(280.0); using XDefaultHomeRetractDist = AMBRO_WRAP_DOUBLE(3.0); using XDefaultHomeSlowMaxDist = AMBRO_WRAP_DOUBLE(5.0); using XDefaultHomeFastSpeed = AMBRO_WRAP_DOUBLE(40.0); using XDefaultHomeRetractSpeed = AMBRO_WRAP_DOUBLE(50.0); using XDefaultHomeSlowSpeed = AMBRO_WRAP_DOUBLE(5.0); using YDefaultStepsPerUnit = AMBRO_WRAP_DOUBLE(80.0); using YDefaultMaxSpeed = AMBRO_WRAP_DOUBLE(80.0); using YDefaultMaxAccel = AMBRO_WRAP_DOUBLE(500.0); using YDefaultOffset = AMBRO_WRAP_DOUBLE(0.0); using YDefaultLimit = AMBRO_WRAP_DOUBLE(170.0); using YDefaultHomeFastMaxDist = AMBRO_WRAP_DOUBLE(280.0); using YDefaultHomeRetractDist = AMBRO_WRAP_DOUBLE(3.0); using YDefaultHomeSlowMaxDist = AMBRO_WRAP_DOUBLE(5.0); using YDefaultHomeFastSpeed = AMBRO_WRAP_DOUBLE(40.0); using YDefaultHomeRetractSpeed = AMBRO_WRAP_DOUBLE(50.0); using YDefaultHomeSlowSpeed = AMBRO_WRAP_DOUBLE(5.0); using ZDefaultStepsPerUnit = AMBRO_WRAP_DOUBLE(4000.0); using ZDefaultMaxSpeed = AMBRO_WRAP_DOUBLE(2.0); using ZDefaultMaxAccel = AMBRO_WRAP_DOUBLE(30.0); using ZDefaultOffset = AMBRO_WRAP_DOUBLE(0.0); using ZDefaultLimit = AMBRO_WRAP_DOUBLE(100.0); using ZDefaultHomeFastMaxDist = AMBRO_WRAP_DOUBLE(100.0); using ZDefaultHomeRetractDist = AMBRO_WRAP_DOUBLE(0.8); using ZDefaultHomeSlowMaxDist = AMBRO_WRAP_DOUBLE(1.2); using ZDefaultHomeFastSpeed = AMBRO_WRAP_DOUBLE(2.0); using ZDefaultHomeRetractSpeed = AMBRO_WRAP_DOUBLE(2.0); using ZDefaultHomeSlowSpeed = AMBRO_WRAP_DOUBLE(0.6); using EDefaultStepsPerUnit = AMBRO_WRAP_DOUBLE(928.0); using EDefaultMaxSpeed = AMBRO_WRAP_DOUBLE(10.0); using EDefaultMaxAccel = AMBRO_WRAP_DOUBLE(250.0); using EDefaultOffset = AMBRO_WRAP_DOUBLE(100.0); using EDefaultLimit = AMBRO_WRAP_DOUBLE(INFINITY); using PrinterParams = PrinterMainParams< PrinterMainSerialParams< UINT32_C(115200), // baud rate GcodeParserParams<8> // receive buffer size exponent >, AvrPin<AvrPortA, 4>, // LED pin LedBlinkInterval, DefaultInactiveTime, SpeedLimitMultiply, MakeTypeList< PrinterMainAxisParams< 'X', // axis name AvrPin<AvrPortC, 5>, // dir pin AvrPin<AvrPortD, 7>, // step pin AvrPin<AvrPortD, 6>, // enable pin true, // invert dir AxisStepperParams< stepper_command_buffer_size_exp, AvrClockInterruptTimer_TC1_OCA // stepper timer >, StepVelType, // velocity type StepAccType, // acceleration type XDefaultStepsPerUnit, // default steps per unit XDefaultMaxSpeed, // default max speed XDefaultMaxAccel, // default max acceleration XDefaultOffset, XDefaultLimit, true, // enable cartesian speed limit PrinterMainHomingParams< AvrPin<AvrPortC, 2>, // endstop pin false, // invert endstop value false, // home direction (false=negative) XDefaultHomeFastMaxDist, XDefaultHomeRetractDist, XDefaultHomeSlowMaxDist, XDefaultHomeFastSpeed, XDefaultHomeRetractSpeed, XDefaultHomeSlowSpeed > >, PrinterMainAxisParams< 'Y', // axis name AvrPin<AvrPortC, 7>, // dir pin AvrPin<AvrPortC, 6>, // step pin AvrPin<AvrPortD, 6>, // enable pin true, // invert dir AxisStepperParams< stepper_command_buffer_size_exp, AvrClockInterruptTimer_TC1_OCB // stepper timer >, StepVelType, // velocity type StepAccType, // acceleration type YDefaultStepsPerUnit, // default steps per unit YDefaultMaxSpeed, // default max speed YDefaultMaxAccel, // default max acceleration YDefaultOffset, YDefaultLimit, true, // enable cartesian speed limit PrinterMainHomingParams< AvrPin<AvrPortC, 3>, // endstop pin false, // invert endstop value false, // home direction (false=negative) YDefaultHomeFastMaxDist, YDefaultHomeRetractDist, YDefaultHomeSlowMaxDist, YDefaultHomeFastSpeed, YDefaultHomeRetractSpeed, YDefaultHomeSlowSpeed > >, PrinterMainAxisParams< 'Z', // axis name AvrPin<AvrPortB, 2>, // dir pin AvrPin<AvrPortB, 3>, // step pin AvrPin<AvrPortA, 5>, // enable pin false, // invert dir AxisStepperParams< stepper_command_buffer_size_exp, AvrClockInterruptTimer_TC3_OCA // stepper timer >, StepVelType, // velocity type StepAccType, // acceleration type ZDefaultStepsPerUnit, // default steps per unit ZDefaultMaxSpeed, // default max speed ZDefaultMaxAccel, // default max acceleration ZDefaultOffset, ZDefaultLimit, true, // enable cartesian speed limit PrinterMainHomingParams< AvrPin<AvrPortC, 4>, // endstop pin false, // invert endstop value false, // home direction (false=negative) ZDefaultHomeFastMaxDist, ZDefaultHomeRetractDist, ZDefaultHomeSlowMaxDist, ZDefaultHomeFastSpeed, ZDefaultHomeRetractSpeed, ZDefaultHomeSlowSpeed > >, PrinterMainAxisParams< 'E', // axis name AvrPin<AvrPortB, 0>, // dir pin AvrPin<AvrPortB, 1>, // step pin AvrPin<AvrPortD, 6>, // enable pin false, // invert dir AxisStepperParams< stepper_command_buffer_size_exp, AvrClockInterruptTimer_TC3_OCB // stepper timer >, StepVelType, // velocity type StepAccType, // acceleration type EDefaultStepsPerUnit, // default steps per unit EDefaultMaxSpeed, // default max speed EDefaultMaxAccel, // default max acceleration EDefaultOffset, EDefaultLimit, false, // enable cartesian speed limit PrinterMainNoHomingParams > > >; struct MyContext; struct EventLoopParams; using MyDebugObjectGroup = DebugObjectGroup<MyContext>; using MyClock = AvrClock<MyContext, clock_timer_prescaler>; using MyLoop = AvrEventLoop<EventLoopParams>; using MyPins = AvrPins<MyContext>; using MyPinWatcherService = AvrPinWatcherService<MyContext>; using MyPrinter = PrinterMain<MyContext, PrinterParams>; struct MyContext { using DebugGroup = MyDebugObjectGroup; using Lock = AvrLock<MyContext>; using Clock = MyClock; using EventLoop = MyLoop; using Pins = MyPins; using PinWatcherService = MyPinWatcherService; MyDebugObjectGroup * debugGroup () const; MyClock * clock () const; MyLoop * eventLoop () const; MyPins * pins () const; MyPinWatcherService * pinWatcherService () const; }; struct EventLoopParams { typedef MyContext Context; }; static MyDebugObjectGroup d_group; static MyClock myclock; static MyLoop myloop; static MyPins mypins; static MyPinWatcherService mypinwatcherservice; static MyPrinter myprinter; MyDebugObjectGroup * MyContext::debugGroup () const { return &d_group; } MyClock * MyContext::clock () const { return &myclock; } MyLoop * MyContext::eventLoop () const { return &myloop; } MyPins * MyContext::pins () const { return &mypins; } MyPinWatcherService * MyContext::pinWatcherService () const { return &mypinwatcherservice; } AMBRO_AVR_CLOCK_ISRS(myclock, MyContext()) AMBRO_AVR_PIN_WATCHER_ISRS(mypinwatcherservice, MyContext()) AMBRO_AVR_SERIAL_ISRS(*myprinter.getSerial(), MyContext()) AMBRO_AVR_CLOCK_INTERRUPT_TIMER_TC1_OCA_ISRS(*myprinter.template getSharer<0>()->getTimer(), MyContext()) AMBRO_AVR_CLOCK_INTERRUPT_TIMER_TC1_OCB_ISRS(*myprinter.template getSharer<1>()->getTimer(), MyContext()) AMBRO_AVR_CLOCK_INTERRUPT_TIMER_TC3_OCA_ISRS(*myprinter.template getSharer<2>()->getTimer(), MyContext()) AMBRO_AVR_CLOCK_INTERRUPT_TIMER_TC3_OCB_ISRS(*myprinter.template getSharer<3>()->getTimer(), MyContext()) FILE uart_output; static int uart_putchar (char ch, FILE *stream) { while (!(UCSR0A & (1 << UDRE0))); UDR0 = ch; return 1; } static void setup_uart_stdio () { uart_output.put = uart_putchar; uart_output.flags = _FDEV_SETUP_WRITE; stdout = &uart_output; stderr = &uart_output; } int main () { setup_uart_stdio(); MyContext c; d_group.init(c); myclock.init(c); #ifdef TCNT3 myclock.initTC3(c); #endif myloop.init(c); mypins.init(c); mypinwatcherservice.init(c); myprinter.init(c); myloop.run(c); } <commit_msg>Reverse extruder direction.<commit_after>/* * Copyright (c) 2013 Ambroz Bizjak * 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 AUTHOR BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <stdint.h> #include <stdio.h> #include <math.h> #include <avr/io.h> #include <avr/interrupt.h> #define AMBROLIB_ABORT_ACTION { cli(); while (1); } #include <aprinter/meta/MakeTypeList.h> #include <aprinter/base/DebugObject.h> #include <aprinter/system/AvrEventLoop.h> #include <aprinter/system/AvrClock.h> #include <aprinter/system/AvrPins.h> #include <aprinter/system/AvrPinWatcher.h> #include <aprinter/system/AvrLock.h> #include <aprinter/printer/PrinterMain.h> using namespace APrinter; static const int clock_timer_prescaler = 2; using StepVelType = FixedPoint<11, false, -11-4>; using StepAccType = FixedPoint<11, false, -11-24>; static const int stepper_command_buffer_size_exp = 3; using LedBlinkInterval = AMBRO_WRAP_DOUBLE(0.5); using DefaultInactiveTime = AMBRO_WRAP_DOUBLE(60.0); using SpeedLimitMultiply = AMBRO_WRAP_DOUBLE(1.0 / 60.0); using XDefaultStepsPerUnit = AMBRO_WRAP_DOUBLE(80.0); using XDefaultMaxSpeed = AMBRO_WRAP_DOUBLE(80.0); using XDefaultMaxAccel = AMBRO_WRAP_DOUBLE(500.0); using XDefaultOffset = AMBRO_WRAP_DOUBLE(53.0); using XDefaultLimit = AMBRO_WRAP_DOUBLE(210.0); using XDefaultHomeFastMaxDist = AMBRO_WRAP_DOUBLE(280.0); using XDefaultHomeRetractDist = AMBRO_WRAP_DOUBLE(3.0); using XDefaultHomeSlowMaxDist = AMBRO_WRAP_DOUBLE(5.0); using XDefaultHomeFastSpeed = AMBRO_WRAP_DOUBLE(40.0); using XDefaultHomeRetractSpeed = AMBRO_WRAP_DOUBLE(50.0); using XDefaultHomeSlowSpeed = AMBRO_WRAP_DOUBLE(5.0); using YDefaultStepsPerUnit = AMBRO_WRAP_DOUBLE(80.0); using YDefaultMaxSpeed = AMBRO_WRAP_DOUBLE(80.0); using YDefaultMaxAccel = AMBRO_WRAP_DOUBLE(500.0); using YDefaultOffset = AMBRO_WRAP_DOUBLE(0.0); using YDefaultLimit = AMBRO_WRAP_DOUBLE(170.0); using YDefaultHomeFastMaxDist = AMBRO_WRAP_DOUBLE(280.0); using YDefaultHomeRetractDist = AMBRO_WRAP_DOUBLE(3.0); using YDefaultHomeSlowMaxDist = AMBRO_WRAP_DOUBLE(5.0); using YDefaultHomeFastSpeed = AMBRO_WRAP_DOUBLE(40.0); using YDefaultHomeRetractSpeed = AMBRO_WRAP_DOUBLE(50.0); using YDefaultHomeSlowSpeed = AMBRO_WRAP_DOUBLE(5.0); using ZDefaultStepsPerUnit = AMBRO_WRAP_DOUBLE(4000.0); using ZDefaultMaxSpeed = AMBRO_WRAP_DOUBLE(2.0); using ZDefaultMaxAccel = AMBRO_WRAP_DOUBLE(30.0); using ZDefaultOffset = AMBRO_WRAP_DOUBLE(0.0); using ZDefaultLimit = AMBRO_WRAP_DOUBLE(100.0); using ZDefaultHomeFastMaxDist = AMBRO_WRAP_DOUBLE(100.0); using ZDefaultHomeRetractDist = AMBRO_WRAP_DOUBLE(0.8); using ZDefaultHomeSlowMaxDist = AMBRO_WRAP_DOUBLE(1.2); using ZDefaultHomeFastSpeed = AMBRO_WRAP_DOUBLE(2.0); using ZDefaultHomeRetractSpeed = AMBRO_WRAP_DOUBLE(2.0); using ZDefaultHomeSlowSpeed = AMBRO_WRAP_DOUBLE(0.6); using EDefaultStepsPerUnit = AMBRO_WRAP_DOUBLE(928.0); using EDefaultMaxSpeed = AMBRO_WRAP_DOUBLE(10.0); using EDefaultMaxAccel = AMBRO_WRAP_DOUBLE(250.0); using EDefaultOffset = AMBRO_WRAP_DOUBLE(100.0); using EDefaultLimit = AMBRO_WRAP_DOUBLE(INFINITY); using PrinterParams = PrinterMainParams< PrinterMainSerialParams< UINT32_C(115200), // baud rate GcodeParserParams<8> // receive buffer size exponent >, AvrPin<AvrPortA, 4>, // LED pin LedBlinkInterval, DefaultInactiveTime, SpeedLimitMultiply, MakeTypeList< PrinterMainAxisParams< 'X', // axis name AvrPin<AvrPortC, 5>, // dir pin AvrPin<AvrPortD, 7>, // step pin AvrPin<AvrPortD, 6>, // enable pin true, // invert dir AxisStepperParams< stepper_command_buffer_size_exp, AvrClockInterruptTimer_TC1_OCA // stepper timer >, StepVelType, // velocity type StepAccType, // acceleration type XDefaultStepsPerUnit, // default steps per unit XDefaultMaxSpeed, // default max speed XDefaultMaxAccel, // default max acceleration XDefaultOffset, XDefaultLimit, true, // enable cartesian speed limit PrinterMainHomingParams< AvrPin<AvrPortC, 2>, // endstop pin false, // invert endstop value false, // home direction (false=negative) XDefaultHomeFastMaxDist, XDefaultHomeRetractDist, XDefaultHomeSlowMaxDist, XDefaultHomeFastSpeed, XDefaultHomeRetractSpeed, XDefaultHomeSlowSpeed > >, PrinterMainAxisParams< 'Y', // axis name AvrPin<AvrPortC, 7>, // dir pin AvrPin<AvrPortC, 6>, // step pin AvrPin<AvrPortD, 6>, // enable pin true, // invert dir AxisStepperParams< stepper_command_buffer_size_exp, AvrClockInterruptTimer_TC1_OCB // stepper timer >, StepVelType, // velocity type StepAccType, // acceleration type YDefaultStepsPerUnit, // default steps per unit YDefaultMaxSpeed, // default max speed YDefaultMaxAccel, // default max acceleration YDefaultOffset, YDefaultLimit, true, // enable cartesian speed limit PrinterMainHomingParams< AvrPin<AvrPortC, 3>, // endstop pin false, // invert endstop value false, // home direction (false=negative) YDefaultHomeFastMaxDist, YDefaultHomeRetractDist, YDefaultHomeSlowMaxDist, YDefaultHomeFastSpeed, YDefaultHomeRetractSpeed, YDefaultHomeSlowSpeed > >, PrinterMainAxisParams< 'Z', // axis name AvrPin<AvrPortB, 2>, // dir pin AvrPin<AvrPortB, 3>, // step pin AvrPin<AvrPortA, 5>, // enable pin false, // invert dir AxisStepperParams< stepper_command_buffer_size_exp, AvrClockInterruptTimer_TC3_OCA // stepper timer >, StepVelType, // velocity type StepAccType, // acceleration type ZDefaultStepsPerUnit, // default steps per unit ZDefaultMaxSpeed, // default max speed ZDefaultMaxAccel, // default max acceleration ZDefaultOffset, ZDefaultLimit, true, // enable cartesian speed limit PrinterMainHomingParams< AvrPin<AvrPortC, 4>, // endstop pin false, // invert endstop value false, // home direction (false=negative) ZDefaultHomeFastMaxDist, ZDefaultHomeRetractDist, ZDefaultHomeSlowMaxDist, ZDefaultHomeFastSpeed, ZDefaultHomeRetractSpeed, ZDefaultHomeSlowSpeed > >, PrinterMainAxisParams< 'E', // axis name AvrPin<AvrPortB, 0>, // dir pin AvrPin<AvrPortB, 1>, // step pin AvrPin<AvrPortD, 6>, // enable pin true, // invert dir AxisStepperParams< stepper_command_buffer_size_exp, AvrClockInterruptTimer_TC3_OCB // stepper timer >, StepVelType, // velocity type StepAccType, // acceleration type EDefaultStepsPerUnit, // default steps per unit EDefaultMaxSpeed, // default max speed EDefaultMaxAccel, // default max acceleration EDefaultOffset, EDefaultLimit, false, // enable cartesian speed limit PrinterMainNoHomingParams > > >; struct MyContext; struct EventLoopParams; using MyDebugObjectGroup = DebugObjectGroup<MyContext>; using MyClock = AvrClock<MyContext, clock_timer_prescaler>; using MyLoop = AvrEventLoop<EventLoopParams>; using MyPins = AvrPins<MyContext>; using MyPinWatcherService = AvrPinWatcherService<MyContext>; using MyPrinter = PrinterMain<MyContext, PrinterParams>; struct MyContext { using DebugGroup = MyDebugObjectGroup; using Lock = AvrLock<MyContext>; using Clock = MyClock; using EventLoop = MyLoop; using Pins = MyPins; using PinWatcherService = MyPinWatcherService; MyDebugObjectGroup * debugGroup () const; MyClock * clock () const; MyLoop * eventLoop () const; MyPins * pins () const; MyPinWatcherService * pinWatcherService () const; }; struct EventLoopParams { typedef MyContext Context; }; static MyDebugObjectGroup d_group; static MyClock myclock; static MyLoop myloop; static MyPins mypins; static MyPinWatcherService mypinwatcherservice; static MyPrinter myprinter; MyDebugObjectGroup * MyContext::debugGroup () const { return &d_group; } MyClock * MyContext::clock () const { return &myclock; } MyLoop * MyContext::eventLoop () const { return &myloop; } MyPins * MyContext::pins () const { return &mypins; } MyPinWatcherService * MyContext::pinWatcherService () const { return &mypinwatcherservice; } AMBRO_AVR_CLOCK_ISRS(myclock, MyContext()) AMBRO_AVR_PIN_WATCHER_ISRS(mypinwatcherservice, MyContext()) AMBRO_AVR_SERIAL_ISRS(*myprinter.getSerial(), MyContext()) AMBRO_AVR_CLOCK_INTERRUPT_TIMER_TC1_OCA_ISRS(*myprinter.template getSharer<0>()->getTimer(), MyContext()) AMBRO_AVR_CLOCK_INTERRUPT_TIMER_TC1_OCB_ISRS(*myprinter.template getSharer<1>()->getTimer(), MyContext()) AMBRO_AVR_CLOCK_INTERRUPT_TIMER_TC3_OCA_ISRS(*myprinter.template getSharer<2>()->getTimer(), MyContext()) AMBRO_AVR_CLOCK_INTERRUPT_TIMER_TC3_OCB_ISRS(*myprinter.template getSharer<3>()->getTimer(), MyContext()) FILE uart_output; static int uart_putchar (char ch, FILE *stream) { while (!(UCSR0A & (1 << UDRE0))); UDR0 = ch; return 1; } static void setup_uart_stdio () { uart_output.put = uart_putchar; uart_output.flags = _FDEV_SETUP_WRITE; stdout = &uart_output; stderr = &uart_output; } int main () { setup_uart_stdio(); MyContext c; d_group.init(c); myclock.init(c); #ifdef TCNT3 myclock.initTC3(c); #endif myloop.init(c); mypins.init(c); mypinwatcherservice.init(c); myprinter.init(c); myloop.run(c); } <|endoftext|>
<commit_before>/*********************************************************************** created: Wed, 8th Feb 2012 author: Lukas E Meindl (based on code by Paul D Turner) David Reepmeyer (added GLES2/GLES3) *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2012 Paul D Turner & The CEGUI Development Team * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ #include "CEGUI/RendererModules/OpenGL/GLES2FBOTextureTarget.h" #include "CEGUI/Exceptions.h" #include "CEGUI/RenderQueue.h" #include "CEGUI/GeometryBuffer.h" #include "CEGUI/RendererModules/OpenGL/GLES2Renderer.h" #include "CEGUI/RendererModules/OpenGL/Texture.h" #include "CEGUI/RendererModules/OpenGL/StateChangeWrapper.h" #include "CEGUI/Logger.h" #include <sstream> #include <iostream> // Start of CEGUI namespace section namespace CEGUI { //----------------------------------------------------------------------------// const float GLES2FBOTextureTarget::DEFAULT_SIZE = 128.0f; //----------------------------------------------------------------------------// GLES2FBOTextureTarget::GLES2FBOTextureTarget(GLES2Renderer& owner) : OpenGLTextureTarget(owner), d_glStateChanger(owner.getOpenGLStateChanger()) { // no need to initialise d_previousFrameBuffer here, it will be // initialised in activate() initialiseRenderTexture(); // setup area and cause the initial texture to be generated. declareRenderSize(Sizef(DEFAULT_SIZE, DEFAULT_SIZE)); } //----------------------------------------------------------------------------// GLES2FBOTextureTarget::~GLES2FBOTextureTarget() { glDeleteFramebuffers(1, &d_frameBuffer); glDeleteRenderbuffers(1, &d_stencilBufferRBO); } //----------------------------------------------------------------------------// void GLES2FBOTextureTarget::declareRenderSize(const Sizef& sz) { setArea(Rectf(d_area.getPosition(), d_owner.getAdjustedTextureSize(sz))); resizeRenderTexture(); } //----------------------------------------------------------------------------// void GLES2FBOTextureTarget::activate() { // remember previously bound FBO to make sure we set it back // when deactivating glGetIntegerv(GL_FRAMEBUFFER_BINDING, reinterpret_cast<GLint*>(&d_previousFrameBuffer)); // switch to rendering to the texture glBindFramebuffer(GL_FRAMEBUFFER, d_frameBuffer); OpenGLTextureTarget::activate(); } //----------------------------------------------------------------------------// void GLES2FBOTextureTarget::deactivate() { OpenGLTextureTarget::deactivate(); // switch back to rendering to the previously bound framebuffer glBindFramebuffer(GL_FRAMEBUFFER, d_previousFrameBuffer); } //----------------------------------------------------------------------------// void GLES2FBOTextureTarget::clear() { const Sizef sz(d_area.getSize()); // Some drivers crash when clearing a 0x0 RTT. This is a workaround for // those cases. if (sz.d_width < 1.0f || sz.d_height < 1.0f) return; // save old clear colour GLfloat old_col[4]; glGetFloatv(GL_COLOR_CLEAR_VALUE, old_col); // remember previously bound FBO to make sure we set it back GLuint previousFBO = 0; glGetIntegerv(GL_FRAMEBUFFER_BINDING, reinterpret_cast<GLint*>(&previousFBO)); // switch to our FBO glBindFramebuffer(GL_FRAMEBUFFER, d_frameBuffer); // Clear it. d_glStateChanger->disable(GL_SCISSOR_TEST); glClearColor(0,0,0,0); if(!d_usesStencil) glClear(GL_COLOR_BUFFER_BIT); else glClear(GL_COLOR_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); // switch back to rendering to the previously bound FBO glBindFramebuffer(GL_FRAMEBUFFER, previousFBO); // restore previous clear colour glClearColor(old_col[0], old_col[1], old_col[2], old_col[3]); } //----------------------------------------------------------------------------// void GLES2FBOTextureTarget::initialiseRenderTexture() { // save old texture binding GLuint old_tex; glGetIntegerv(GL_TEXTURE_BINDING_2D, reinterpret_cast<GLint*>(&old_tex)); // create FBO glGenFramebuffers(1, &d_frameBuffer); #ifndef __ANDROID__ // remember previously bound FBO to make sure we set it back GLuint previousFBO = 0; glGetIntegerv(GL_FRAMEBUFFER_BINDING_EXT, reinterpret_cast<GLint*>(&previousFBO)); #endif glBindFramebuffer(GL_FRAMEBUFFER, d_frameBuffer); // set up the texture the FBO will draw to glGenTextures(1, &d_texture); d_glStateChanger->bindTexture(GL_TEXTURE_2D, d_texture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); #ifdef CEGUI_GLES3_SUPPORT glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, #else glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, #endif static_cast<GLsizei>(DEFAULT_SIZE), static_cast<GLsizei>(DEFAULT_SIZE), 0, GL_RGBA, GL_UNSIGNED_BYTE, 0); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, d_texture, 0); // Set up the stencil buffer for the FBO glGenRenderbuffers(1, &d_stencilBufferRBO); glBindRenderbuffer(GL_RENDERBUFFER, d_stencilBufferRBO); glRenderbufferStorage(GL_RENDERBUFFER, GL_STENCIL_INDEX8, static_cast<GLsizei>(DEFAULT_SIZE), static_cast<GLsizei>(DEFAULT_SIZE)); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, d_stencilBufferRBO); //Check for framebuffer completeness checkFramebufferStatus(); #ifndef __ANDROID__ // switch from our frame buffer back to the previously bound buffer. glBindFramebuffer(GL_FRAMEBUFFER, previousFBO); #endif // ensure the CEGUI::Texture is wrapping the gl texture and has correct size d_CEGUITexture->setOpenGLTexture(d_texture, d_area.getSize()); // restore previous texture binding. d_glStateChanger->bindTexture(GL_TEXTURE_2D, old_tex); } //----------------------------------------------------------------------------// void GLES2FBOTextureTarget::resizeRenderTexture() { // save old texture binding GLuint old_tex; glGetIntegerv(GL_TEXTURE_BINDING_2D, reinterpret_cast<GLint*>(&old_tex)); // Some drivers (hint: Intel) segfault when glTexImage2D is called with // any of the dimensions being 0. The downside of this workaround is very // small. We waste a tiny bit of VRAM on cards with sane drivers and // prevent insane drivers from crashing CEGUI. Sizef sz(d_area.getSize()); if (sz.d_width < 1.0f || sz.d_height < 1.0f) { sz.d_width = 1.0f; sz.d_height = 1.0f; } // set the texture to the required size d_glStateChanger->bindTexture(GL_TEXTURE_2D, d_texture); #ifdef CEGUI_GLES3_SUPPORT glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, #else glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, #endif static_cast<GLsizei>(sz.d_width), static_cast<GLsizei>(sz.d_height), 0, GL_RGBA, GL_UNSIGNED_BYTE, 0); glBindRenderbuffer(GL_RENDERBUFFER, d_stencilBufferRBO); glRenderbufferStorage(GL_RENDERBUFFER, GL_STENCIL_INDEX8, static_cast<GLsizei>(sz.d_width), static_cast<GLsizei>(sz.d_height)); clear(); // ensure the CEGUI::Texture is wrapping the gl texture and has correct size d_CEGUITexture->setOpenGLTexture(d_texture, sz); // restore previous texture binding. d_glStateChanger->bindTexture(GL_TEXTURE_2D, old_tex); } //----------------------------------------------------------------------------// void GLES2FBOTextureTarget::grabTexture() { glDeleteFramebuffers(1, &d_frameBuffer); d_frameBuffer = 0; OpenGLTextureTarget::grabTexture(); } //----------------------------------------------------------------------------// void GLES2FBOTextureTarget::restoreTexture() { OpenGLTextureTarget::restoreTexture(); initialiseRenderTexture(); resizeRenderTexture(); } //----------------------------------------------------------------------------// void GLES2FBOTextureTarget::checkFramebufferStatus() { GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER); // Check for completeness if(status != GL_FRAMEBUFFER_COMPLETE) { std::stringstream stringStream; stringStream << "GLES2Renderer: Error Framebuffer is not complete\n"; switch(status) { case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT: stringStream << "GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT\n"; break; #ifdef CEGUI_GLES3_SUPPORT case GL_FRAMEBUFFER_UNDEFINED: stringStream << "GL_FRAMEBUFFER_UNDEFINED\n"; break; #endif case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: stringStream << "GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT\n"; break; #ifndef __ANDROID__ case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER : stringStream << "GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER\n"; break; case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER: stringStream << "GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER\n"; break; #endif #ifdef CEGUI_GLES3_SUPPORT case GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE: stringStream << "GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE\n"; break; #endif case GL_FRAMEBUFFER_UNSUPPORTED: stringStream << "GL_FRAMEBUFFER_UNSUPPORTED\n"; break; default: stringStream << "Undefined Framebuffer error\n"; break; } if (CEGUI::Logger* logger = CEGUI::Logger::getSingletonPtr()) logger->logEvent(stringStream.str().c_str()); else std::cerr << stringStream.str() << std::endl; } } //----------------------------------------------------------------------------// } // End of CEGUI namespace section <commit_msg>cleanup for initialiseRenderTexture<commit_after>/*********************************************************************** created: Wed, 8th Feb 2012 author: Lukas E Meindl (based on code by Paul D Turner) David Reepmeyer (added GLES2/GLES3) *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2012 Paul D Turner & The CEGUI Development Team * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ #include "CEGUI/RendererModules/OpenGL/GLES2FBOTextureTarget.h" #include "CEGUI/Exceptions.h" #include "CEGUI/RenderQueue.h" #include "CEGUI/GeometryBuffer.h" #include "CEGUI/RendererModules/OpenGL/GLES2Renderer.h" #include "CEGUI/RendererModules/OpenGL/Texture.h" #include "CEGUI/RendererModules/OpenGL/StateChangeWrapper.h" #include "CEGUI/Logger.h" #include <sstream> #include <iostream> // Start of CEGUI namespace section namespace CEGUI { //----------------------------------------------------------------------------// const float GLES2FBOTextureTarget::DEFAULT_SIZE = 128.0f; //----------------------------------------------------------------------------// GLES2FBOTextureTarget::GLES2FBOTextureTarget(GLES2Renderer& owner) : OpenGLTextureTarget(owner), d_glStateChanger(owner.getOpenGLStateChanger()) { // no need to initialise d_previousFrameBuffer here, it will be // initialised in activate() initialiseRenderTexture(); // setup area and cause the initial texture to be generated. declareRenderSize(Sizef(DEFAULT_SIZE, DEFAULT_SIZE)); } //----------------------------------------------------------------------------// GLES2FBOTextureTarget::~GLES2FBOTextureTarget() { glDeleteFramebuffers(1, &d_frameBuffer); glDeleteRenderbuffers(1, &d_stencilBufferRBO); } //----------------------------------------------------------------------------// void GLES2FBOTextureTarget::declareRenderSize(const Sizef& sz) { setArea(Rectf(d_area.getPosition(), d_owner.getAdjustedTextureSize(sz))); resizeRenderTexture(); } //----------------------------------------------------------------------------// void GLES2FBOTextureTarget::activate() { // remember previously bound FBO to make sure we set it back // when deactivating glGetIntegerv(GL_FRAMEBUFFER_BINDING, reinterpret_cast<GLint*>(&d_previousFrameBuffer)); // switch to rendering to the texture glBindFramebuffer(GL_FRAMEBUFFER, d_frameBuffer); OpenGLTextureTarget::activate(); } //----------------------------------------------------------------------------// void GLES2FBOTextureTarget::deactivate() { OpenGLTextureTarget::deactivate(); // switch back to rendering to the previously bound framebuffer glBindFramebuffer(GL_FRAMEBUFFER, d_previousFrameBuffer); } //----------------------------------------------------------------------------// void GLES2FBOTextureTarget::clear() { const Sizef sz(d_area.getSize()); // Some drivers crash when clearing a 0x0 RTT. This is a workaround for // those cases. if (sz.d_width < 1.0f || sz.d_height < 1.0f) return; // save old clear colour GLfloat old_col[4]; glGetFloatv(GL_COLOR_CLEAR_VALUE, old_col); // remember previously bound FBO to make sure we set it back GLuint previousFBO = 0; glGetIntegerv(GL_FRAMEBUFFER_BINDING, reinterpret_cast<GLint*>(&previousFBO)); // switch to our FBO glBindFramebuffer(GL_FRAMEBUFFER, d_frameBuffer); // Clear it. d_glStateChanger->disable(GL_SCISSOR_TEST); glClearColor(0,0,0,0); if(!d_usesStencil) glClear(GL_COLOR_BUFFER_BIT); else glClear(GL_COLOR_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); // switch back to rendering to the previously bound FBO glBindFramebuffer(GL_FRAMEBUFFER, previousFBO); // restore previous clear colour glClearColor(old_col[0], old_col[1], old_col[2], old_col[3]); } //----------------------------------------------------------------------------// void GLES2FBOTextureTarget::initialiseRenderTexture() { // save old texture binding GLuint old_tex; glGetIntegerv(GL_TEXTURE_BINDING_2D, reinterpret_cast<GLint*>(&old_tex)); // create FBO glGenFramebuffers(1, &d_frameBuffer); // remember previously bound FBO to make sure we set it back GLuint previousFBO = 0; //glGetIntegerv(GL_FRAMEBUFFER_BINDING_EXT, glGetIntegerv(GL_FRAMEBUFFER_BINDING, reinterpret_cast<GLint*>(&previousFBO)); glBindFramebuffer(GL_FRAMEBUFFER, d_frameBuffer); // set up the texture the FBO will draw to glGenTextures(1, &d_texture); d_glStateChanger->bindTexture(GL_TEXTURE_2D, d_texture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); #ifdef CEGUI_GLES3_SUPPORT glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, #else glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, #endif static_cast<GLsizei>(DEFAULT_SIZE), static_cast<GLsizei>(DEFAULT_SIZE), 0, GL_RGBA, GL_UNSIGNED_BYTE, 0); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, d_texture, 0); // Set up the stencil buffer for the FBO glGenRenderbuffers(1, &d_stencilBufferRBO); glBindRenderbuffer(GL_RENDERBUFFER, d_stencilBufferRBO); glRenderbufferStorage(GL_RENDERBUFFER, GL_STENCIL_INDEX8, static_cast<GLsizei>(DEFAULT_SIZE), static_cast<GLsizei>(DEFAULT_SIZE)); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, d_stencilBufferRBO); //Check for framebuffer completeness checkFramebufferStatus(); // switch from our frame buffer back to the previously bound buffer. glBindFramebuffer(GL_FRAMEBUFFER, previousFBO); // ensure the CEGUI::Texture is wrapping the gl texture and has correct size d_CEGUITexture->setOpenGLTexture(d_texture, d_area.getSize()); // restore previous texture binding. d_glStateChanger->bindTexture(GL_TEXTURE_2D, old_tex); } //----------------------------------------------------------------------------// void GLES2FBOTextureTarget::resizeRenderTexture() { // save old texture binding GLuint old_tex; glGetIntegerv(GL_TEXTURE_BINDING_2D, reinterpret_cast<GLint*>(&old_tex)); // Some drivers (hint: Intel) segfault when glTexImage2D is called with // any of the dimensions being 0. The downside of this workaround is very // small. We waste a tiny bit of VRAM on cards with sane drivers and // prevent insane drivers from crashing CEGUI. Sizef sz(d_area.getSize()); if (sz.d_width < 1.0f || sz.d_height < 1.0f) { sz.d_width = 1.0f; sz.d_height = 1.0f; } // set the texture to the required size d_glStateChanger->bindTexture(GL_TEXTURE_2D, d_texture); #ifdef CEGUI_GLES3_SUPPORT glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, #else glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, #endif static_cast<GLsizei>(sz.d_width), static_cast<GLsizei>(sz.d_height), 0, GL_RGBA, GL_UNSIGNED_BYTE, 0); glBindRenderbuffer(GL_RENDERBUFFER, d_stencilBufferRBO); glRenderbufferStorage(GL_RENDERBUFFER, GL_STENCIL_INDEX8, static_cast<GLsizei>(sz.d_width), static_cast<GLsizei>(sz.d_height)); clear(); // ensure the CEGUI::Texture is wrapping the gl texture and has correct size d_CEGUITexture->setOpenGLTexture(d_texture, sz); // restore previous texture binding. d_glStateChanger->bindTexture(GL_TEXTURE_2D, old_tex); } //----------------------------------------------------------------------------// void GLES2FBOTextureTarget::grabTexture() { glDeleteFramebuffers(1, &d_frameBuffer); d_frameBuffer = 0; OpenGLTextureTarget::grabTexture(); } //----------------------------------------------------------------------------// void GLES2FBOTextureTarget::restoreTexture() { OpenGLTextureTarget::restoreTexture(); initialiseRenderTexture(); resizeRenderTexture(); } //----------------------------------------------------------------------------// void GLES2FBOTextureTarget::checkFramebufferStatus() { GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER); // Check for completeness if(status != GL_FRAMEBUFFER_COMPLETE) { std::stringstream stringStream; stringStream << "GLES2Renderer: Error Framebuffer is not complete\n"; switch(status) { case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT: stringStream << "GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT\n"; break; #ifdef CEGUI_GLES3_SUPPORT case GL_FRAMEBUFFER_UNDEFINED: stringStream << "GL_FRAMEBUFFER_UNDEFINED\n"; break; #endif case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: stringStream << "GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT\n"; break; #ifndef __ANDROID__ case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER : stringStream << "GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER\n"; break; case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER: stringStream << "GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER\n"; break; #endif #ifdef CEGUI_GLES3_SUPPORT case GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE: stringStream << "GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE\n"; break; #endif case GL_FRAMEBUFFER_UNSUPPORTED: stringStream << "GL_FRAMEBUFFER_UNSUPPORTED\n"; break; default: stringStream << "Undefined Framebuffer error\n"; break; } if (CEGUI::Logger* logger = CEGUI::Logger::getSingletonPtr()) logger->logEvent(stringStream.str().c_str()); else std::cerr << stringStream.str() << std::endl; } } //----------------------------------------------------------------------------// } // End of CEGUI namespace section <|endoftext|>
<commit_before>// // App.cpp // // Copyright (c) 2001-2004 Virtual Terrain Project // Free for all uses, see license.txt for details. // // For compilers that support precompilation, includes "wx/wx.h". #include "wx/wxprec.h" #ifndef WX_PRECOMP #include "wx/wx.h" #endif #include "Frame.h" #include "BuilderView.h" #include "vtdata/vtLog.h" #include "vtui/Helper.h" #include "gdal_priv.h" #include "App.h" #define HEAPBUSTER 0 #if HEAPBUSTER #include "../HeapBuster/HeapBuster.h" #endif IMPLEMENT_APP(BuilderApp) void BuilderApp::Args(int argc, wxChar **argv) { for (int i = 0; i < argc; i++) { wxString2 str = argv[i]; const char *cstr = str.mb_str(); if (!strncmp(cstr, "-locale=", 8)) m_locale_name = cstr+8; } } bool BuilderApp::OnInit() { #if WIN32 && defined(_MSC_VER) && DEBUG _CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF ); #endif g_Log._StartLog("debug.txt"); VTLOG(APPNAME "\nBuild:"); #if DEBUG VTLOG(" Debug"); #else VTLOG(" Release"); #endif #if UNICODE VTLOG(" Unicode"); #endif VTLOG("\n"); #if WIN32 VTLOG(" Running on: "); LogWindowsVersion(); #endif Args(argc, argv); SetupLocale(); // Fill list of layer type names if (vtLayer::LayerTypeNames.IsEmpty()) { // These must correspond to the order of the LayerType enum! vtLayer::LayerTypeNames.Add(_("Raw")); vtLayer::LayerTypeNames.Add(_("Elevation")); vtLayer::LayerTypeNames.Add(_("Image")); vtLayer::LayerTypeNames.Add(_("Road")); vtLayer::LayerTypeNames.Add(_("Structure")); vtLayer::LayerTypeNames.Add(_("Water")); vtLayer::LayerTypeNames.Add(_("Vegetation")); vtLayer::LayerTypeNames.Add(_("Transit")); vtLayer::LayerTypeNames.Add(_("Utility")); } VTLOG("Testing ability to allocate a frame object.\n"); wxFrame *frametest = new wxFrame(NULL, -1, _T("Title")); delete frametest; VTLOG(" Creating Main Frame Window,"); wxString2 title = _T(APPNAME); VTLOG(" title '%s'\n", title.mb_str()); MainFrame* frame = new MainFrame((wxFrame *) NULL, title, wxPoint(50, 50), wxSize(900, 500)); VTLOG(" Setting up the UI.\n"); frame->SetupUI(); VTLOG(" Showing the frame.\n"); frame->Show(TRUE); SetTopWindow(frame); VTLOG(" Initializing GDAL."); g_GDALWrapper.RequestGDALFormats(); VTLOG(" GDAL-supported formats:"); GDALDriverManager *poDM = GetGDALDriverManager(); for( int iDriver = 0; iDriver < poDM->GetDriverCount(); iDriver++ ) { if ((iDriver % 13) == 0) VTLOG("\n "); GDALDriver *poDriver = poDM->GetDriver( iDriver ); const char *name = poDriver->GetDescription(); VTLOG("%s ", name); } VTLOG("\n"); // Stuff for testing // wxString str("E:/Earth Imagery/NASA BlueMarble/MOD09A1.E.interpol.cyl.retouched.topo.3x00054x00027-N.bmp"); // wxString str("E:/Data-USA/Elevation/crater_0513.bt"); /* vtLayer *pLayer = frame->ImportImage(str); bool success = frame->AddLayerWithCheck(pLayer, true); frame->LoadLayer(str); */ // frame->LoadProject("E:/Locations/Romania/giurgiu.vtb"); // frame->ImportDataFromFile(LT_ELEVATION, "E:/Earth/NOAA Globe/g10g.hdr", false); // wxString str("E:/VTP User's Data/Mike Flaxman/catrct_nur.tif"); // frame->LoadLayer(str); // wxString fname("E:/VTP User's Data/Hangzhou/Data/BuildingData/a-bldgs-18dec-subset1.vtst"); // frame->LoadLayer(fname); // vtStructureLayer *pSL = frame->GetActiveStructureLayer(); // vtStructure *str = pSL->GetAt(0); // str->Select(true); // pSL->EditBuildingProperties(); // wxString fname("E:/Locations-USA/Hawai`i Island Data/DRG/O19154F8.TIF"); // frame->ImportDataFromFile(LT_IMAGE, fname, true); // frame->LoadProject("E:/Locations-USA/Hawai`i Island Content/Honoka`a/latest_temp.vtb"); // vtString fname = "E:/Earth Imagery/NASA BlueMarble/FullRes/MOD09A1.W.interpol.cyl.retouched.topo.3x21600x10800-N.bmp"; // frame->ImportDataFromFile(LT_IMAGE, fname, true); frame->ZoomAll(); #if HEAPBUSTER // Pull in the heap buster g_HeapBusterDummy = -1; #endif return TRUE; } int BuilderApp::OnExit() { VTLOG("App Exit\n"); return wxApp::OnExit(); } void BuilderApp::SetupLocale() { wxLog::SetVerbose(true); // Locale stuff int lang = wxLANGUAGE_DEFAULT; int default_lang = m_locale.GetSystemLanguage(); const wxLanguageInfo *info = wxLocale::GetLanguageInfo(default_lang); VTLOG("Default language: %d (%s)\n", default_lang, info->Description.mb_str()); bool bSuccess; if (m_locale_name != "") { VTLOG("Looking up language: %s\n", (const char *) m_locale_name); lang = GetLangFromName(wxString2(m_locale_name)); if (lang == wxLANGUAGE_UNKNOWN) { VTLOG(" Unknown, falling back on default language.\n"); lang = wxLANGUAGE_DEFAULT; } else { info = m_locale.GetLanguageInfo(lang); VTLOG("Initializing locale to language %d, Canonical name '%s', Description: '%s':\n", lang, info->CanonicalName.mb_str(), info->Description.mb_str()); bSuccess = m_locale.Init(lang, wxLOCALE_CONV_ENCODING); } } if (lang == wxLANGUAGE_DEFAULT) { VTLOG("Initializing locale to default language:\n"); bSuccess = m_locale.Init(wxLANGUAGE_DEFAULT, wxLOCALE_CONV_ENCODING); if (bSuccess) lang = default_lang; } if (bSuccess) VTLOG(" succeeded.\n"); else VTLOG(" failed.\n"); if (lang != wxLANGUAGE_ENGLISH_US) { VTLOG("Attempting to load the 'Enviro.mo' catalog for the current locale.\n"); bSuccess = m_locale.AddCatalog(wxT("Enviro")); if (bSuccess) VTLOG(" succeeded.\n"); else VTLOG(" not found.\n"); VTLOG("\n"); } // Test it // wxString test = _("&File"); wxLog::SetVerbose(false); } <commit_msg>tweak test code<commit_after>// // App.cpp // // Copyright (c) 2001-2004 Virtual Terrain Project // Free for all uses, see license.txt for details. // // For compilers that support precompilation, includes "wx/wx.h". #include "wx/wxprec.h" #ifndef WX_PRECOMP #include "wx/wx.h" #endif #include "Frame.h" #include "BuilderView.h" #include "vtdata/vtLog.h" #include "vtui/Helper.h" #include "gdal_priv.h" #include "App.h" #define HEAPBUSTER 0 #if HEAPBUSTER #include "../HeapBuster/HeapBuster.h" #endif IMPLEMENT_APP(BuilderApp) void BuilderApp::Args(int argc, wxChar **argv) { for (int i = 0; i < argc; i++) { wxString2 str = argv[i]; const char *cstr = str.mb_str(); if (!strncmp(cstr, "-locale=", 8)) m_locale_name = cstr+8; } } bool BuilderApp::OnInit() { #if WIN32 && defined(_MSC_VER) && DEBUG _CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF ); #endif g_Log._StartLog("debug.txt"); VTLOG(APPNAME "\nBuild:"); #if DEBUG VTLOG(" Debug"); #else VTLOG(" Release"); #endif #if UNICODE VTLOG(" Unicode"); #endif VTLOG("\n"); #if WIN32 VTLOG(" Running on: "); LogWindowsVersion(); #endif Args(argc, argv); SetupLocale(); // Fill list of layer type names if (vtLayer::LayerTypeNames.IsEmpty()) { // These must correspond to the order of the LayerType enum! vtLayer::LayerTypeNames.Add(_("Raw")); vtLayer::LayerTypeNames.Add(_("Elevation")); vtLayer::LayerTypeNames.Add(_("Image")); vtLayer::LayerTypeNames.Add(_("Road")); vtLayer::LayerTypeNames.Add(_("Structure")); vtLayer::LayerTypeNames.Add(_("Water")); vtLayer::LayerTypeNames.Add(_("Vegetation")); vtLayer::LayerTypeNames.Add(_("Transit")); vtLayer::LayerTypeNames.Add(_("Utility")); } VTLOG("Testing ability to allocate a frame object.\n"); wxFrame *frametest = new wxFrame(NULL, -1, _T("Title")); delete frametest; VTLOG(" Creating Main Frame Window,"); wxString2 title = _T(APPNAME); VTLOG(" title '%s'\n", title.mb_str()); MainFrame* frame = new MainFrame((wxFrame *) NULL, title, wxPoint(50, 50), wxSize(900, 500)); VTLOG(" Setting up the UI.\n"); frame->SetupUI(); VTLOG(" Showing the frame.\n"); frame->Show(TRUE); SetTopWindow(frame); VTLOG(" Initializing GDAL."); g_GDALWrapper.RequestGDALFormats(); VTLOG(" GDAL-supported formats:"); GDALDriverManager *poDM = GetGDALDriverManager(); for( int iDriver = 0; iDriver < poDM->GetDriverCount(); iDriver++ ) { if ((iDriver % 13) == 0) VTLOG("\n "); GDALDriver *poDriver = poDM->GetDriver( iDriver ); const char *name = poDriver->GetDescription(); VTLOG("%s ", name); } VTLOG("\n"); // Stuff for testing // wxString str("E:/Earth Imagery/NASA BlueMarble/MOD09A1.E.interpol.cyl.retouched.topo.3x00054x00027-N.bmp"); // wxString str("E:/Data-USA/Elevation/crater_0513.bt"); /* vtLayer *pLayer = frame->ImportImage(str); bool success = frame->AddLayerWithCheck(pLayer, true); frame->LoadLayer(str); */ // frame->LoadProject("E:/Locations/Romania/giurgiu.vtb"); // frame->ImportDataFromFile(LT_ELEVATION, "E:/Earth/NOAA Globe/g10g.hdr", false); // wxString str("E:/VTP User's Data/Mike Flaxman/catrct_nur.tif"); // frame->LoadLayer(str); // wxString fname("E:/VTP User's Data/Hangzhou/Data/BuildingData/a-bldgs-18dec-subset1.vtst"); // frame->LoadLayer(fname); // vtStructureLayer *pSL = frame->GetActiveStructureLayer(); // vtStructure *str = pSL->GetAt(0); // str->Select(true); // pSL->EditBuildingProperties(); // wxString fname("E:/Locations-USA/Hawai`i Island Data/DRG/O19154F8.TIF"); // frame->ImportDataFromFile(LT_IMAGE, fname, true); // frame->LoadProject("E:/Locations-USA/Hawai`i Island Content/Honoka`a/latest_temp.vtb"); // vtString fname = "E:/Locations-Hawai'i/Hawai`i Island Data/SDTS-DLG/waipahu_HI/transportation/852867.RR.sdts.tar.gz"; // frame->ImportDataFromArchive(LT_ROAD, fname, true); frame->ZoomAll(); #if HEAPBUSTER // Pull in the heap buster g_HeapBusterDummy = -1; #endif return TRUE; } int BuilderApp::OnExit() { VTLOG("App Exit\n"); return wxApp::OnExit(); } void BuilderApp::SetupLocale() { wxLog::SetVerbose(true); // Locale stuff int lang = wxLANGUAGE_DEFAULT; int default_lang = m_locale.GetSystemLanguage(); const wxLanguageInfo *info = wxLocale::GetLanguageInfo(default_lang); VTLOG("Default language: %d (%s)\n", default_lang, info->Description.mb_str()); bool bSuccess; if (m_locale_name != "") { VTLOG("Looking up language: %s\n", (const char *) m_locale_name); lang = GetLangFromName(wxString2(m_locale_name)); if (lang == wxLANGUAGE_UNKNOWN) { VTLOG(" Unknown, falling back on default language.\n"); lang = wxLANGUAGE_DEFAULT; } else { info = m_locale.GetLanguageInfo(lang); VTLOG("Initializing locale to language %d, Canonical name '%s', Description: '%s':\n", lang, info->CanonicalName.mb_str(), info->Description.mb_str()); bSuccess = m_locale.Init(lang, wxLOCALE_CONV_ENCODING); } } if (lang == wxLANGUAGE_DEFAULT) { VTLOG("Initializing locale to default language:\n"); bSuccess = m_locale.Init(wxLANGUAGE_DEFAULT, wxLOCALE_CONV_ENCODING); if (bSuccess) lang = default_lang; } if (bSuccess) VTLOG(" succeeded.\n"); else VTLOG(" failed.\n"); if (lang != wxLANGUAGE_ENGLISH_US) { VTLOG("Attempting to load the 'Enviro.mo' catalog for the current locale.\n"); bSuccess = m_locale.AddCatalog(wxT("Enviro")); if (bSuccess) VTLOG(" succeeded.\n"); else VTLOG(" not found.\n"); VTLOG("\n"); } // Test it // wxString test = _("&File"); wxLog::SetVerbose(false); } <|endoftext|>
<commit_before>#include "gtest/gtest.h" #include <smt> #include <cstdint> TEST(SmtFunctionalTest, DeMorgan) { const smt::ExprPtr<smt::Bool> x = smt::any<smt::Bool>("x"); const smt::ExprPtr<smt::Bool> y = smt::any<smt::Bool>("y"); const smt::ExprPtr<smt::Bool> lhs = !(x && y); const smt::ExprPtr<smt::Bool> rhs = !x || !y; smt::Z3Solver z3_solver; z3_solver.add(lhs != rhs); EXPECT_EQ(smt::unsat, z3_solver.check()); smt::MsatSolver msat_solver; msat_solver.add(lhs != rhs); EXPECT_EQ(smt::unsat, msat_solver.check()); } TEST(SmtFunctionalTest, SeparateDecls) { const smt::Decl<smt::Bool> x_decl("x"); const smt::Decl<smt::Bool> y_decl("y"); const smt::ExprPtr<smt::Bool> x = smt::constant(x_decl); const smt::ExprPtr<smt::Bool> y = smt::constant(y_decl); const smt::ExprPtr<smt::Bool> lhs = !(x && y); const smt::ExprPtr<smt::Bool> rhs = !x || !y; smt::Z3Solver z3_solver; z3_solver.add(lhs != rhs); EXPECT_EQ(smt::unsat, z3_solver.check()); smt::MsatSolver msat_solver; msat_solver.add(lhs != rhs); EXPECT_EQ(smt::unsat, msat_solver.check()); } TEST(SmtFunctionalTest, BitVectors) { const smt::ExprPtr<unsigned long> x = smt::any<unsigned long>("x"); const smt::ExprPtr<unsigned long> y = smt::any<unsigned long>("y"); const smt::ExprPtr<unsigned long> z = smt::any<unsigned long>("z"); const smt::ExprPtr<smt::Bool> equality = (x == y) && ((x & ~y) == z); smt::Z3Solver z3_solver; z3_solver.add(equality); z3_solver.push(); { z3_solver.add(z != 0L); EXPECT_EQ(smt::unsat, z3_solver.check()); } z3_solver.pop(); z3_solver.push(); { z3_solver.add(z == 0L); EXPECT_EQ(smt::sat, z3_solver.check()); } z3_solver.pop(); smt::MsatSolver msat_solver; msat_solver.add(equality); msat_solver.push(); { msat_solver.add(z != 0L); EXPECT_EQ(smt::unsat, msat_solver.check()); } msat_solver.pop(); msat_solver.push(); { msat_solver.add(z == 0L); EXPECT_EQ(smt::sat, msat_solver.check()); } msat_solver.pop(); } TEST(SmtFunctionalTest, UnsafeExpr) { const smt::UnsafeDecl unsafe_decl("x", smt::bv_sort(true, sizeof(int) * 8)); const smt::UnsafeExprPtr x = smt::constant(unsafe_decl); const smt::UnsafeExprPtr equality = (x & smt::literal<int>(3)) != x; smt::Z3Solver z3_solver; z3_solver.unsafe_add(equality); EXPECT_EQ(smt::sat, z3_solver.check()); smt::MsatSolver msat_solver; msat_solver.unsafe_add(equality); EXPECT_EQ(smt::sat, msat_solver.check()); } TEST(SmtFunctionalTest, Reflection) { constexpr size_t bv_int_size = sizeof(int) * 8; EXPECT_EQ(smt::bv_sort(true, bv_int_size), smt::literal<int>(3)->sort()); const smt::ExprPtr<uint32_t> x = smt::any<uint32_t>("x"); EXPECT_TRUE(x->sort().is_bv()); EXPECT_FALSE(x->sort().is_signed()); EXPECT_EQ(32, x->sort().bv_size()); typedef smt::Func<smt::Int, smt::Real, char> SomeFunc; const smt::ExprPtr<SomeFunc> f = smt::any<SomeFunc>("f"); EXPECT_TRUE(f->sort().is_func()); EXPECT_EQ(3, f->sort().sorts_size()); EXPECT_TRUE(f->sort().sorts(0).is_int()); EXPECT_TRUE(f->sort().sorts(1).is_real()); EXPECT_TRUE(f->sort().sorts(2).is_bv()); EXPECT_EQ(sizeof(char) * 8, f->sort().sorts(2).bv_size()); } TEST(SmtFunctionalTest, Array) { typedef smt::Array<smt::Int, char> IntToCharArray; const smt::Decl<IntToCharArray> array_decl("array"); smt::ExprPtr<IntToCharArray> array, new_array; smt::ExprPtr<smt::Int> index; smt::ExprPtr<char> value; array = smt::constant(array_decl); index = smt::any<smt::Int>("index"); value = smt::literal<char>('p'); new_array = smt::store(array, index, value); smt::Z3Solver z3_solver; z3_solver.add(smt::select(new_array, index) != value); EXPECT_EQ(smt::unsat, z3_solver.check()); smt::MsatSolver msat_solver; msat_solver.add(smt::select(new_array, index) != value); EXPECT_EQ(smt::unsat, msat_solver.check()); } TEST(SmtFunctionalTest, Function) { const smt::Decl<smt::Func<smt::Int, smt::Int>> func_decl("f"); const smt::ExprPtr<smt::Int> x = smt::any<smt::Int>("x"); const smt::ExprPtr<smt::Bool> formula = smt::apply(func_decl, 3) == 7 && x == smt::apply(func_decl, 3); smt::Z3Solver z3_solver; z3_solver.add(formula && x != smt::literal<smt::Int>(7)); EXPECT_EQ(smt::unsat, z3_solver.check()); smt::MsatSolver msat_solver; msat_solver.add(formula && x != 7); EXPECT_EQ(smt::unsat, msat_solver.check()); } <commit_msg>Show how to access global solver objects<commit_after>#include "gtest/gtest.h" #include <smt> #include <cstdint> // Only access global solver through a function that has a static local object! smt::Solver& global_solver() { static smt::MsatSolver s_msat_solver; return s_msat_solver; } TEST(SmtFunctionalTest, Reset) { global_solver().reset(); } TEST(SmtFunctionalTest, DeMorgan) { const smt::ExprPtr<smt::Bool> x = smt::any<smt::Bool>("x"); const smt::ExprPtr<smt::Bool> y = smt::any<smt::Bool>("y"); const smt::ExprPtr<smt::Bool> lhs = !(x && y); const smt::ExprPtr<smt::Bool> rhs = !x || !y; smt::Z3Solver z3_solver; z3_solver.add(lhs != rhs); EXPECT_EQ(smt::unsat, z3_solver.check()); smt::MsatSolver msat_solver; msat_solver.add(lhs != rhs); EXPECT_EQ(smt::unsat, msat_solver.check()); } TEST(SmtFunctionalTest, SeparateDecls) { const smt::Decl<smt::Bool> x_decl("x"); const smt::Decl<smt::Bool> y_decl("y"); const smt::ExprPtr<smt::Bool> x = smt::constant(x_decl); const smt::ExprPtr<smt::Bool> y = smt::constant(y_decl); const smt::ExprPtr<smt::Bool> lhs = !(x && y); const smt::ExprPtr<smt::Bool> rhs = !x || !y; smt::Z3Solver z3_solver; z3_solver.add(lhs != rhs); EXPECT_EQ(smt::unsat, z3_solver.check()); smt::MsatSolver msat_solver; msat_solver.add(lhs != rhs); EXPECT_EQ(smt::unsat, msat_solver.check()); } TEST(SmtFunctionalTest, BitVectors) { const smt::ExprPtr<unsigned long> x = smt::any<unsigned long>("x"); const smt::ExprPtr<unsigned long> y = smt::any<unsigned long>("y"); const smt::ExprPtr<unsigned long> z = smt::any<unsigned long>("z"); const smt::ExprPtr<smt::Bool> equality = (x == y) && ((x & ~y) == z); smt::Z3Solver z3_solver; z3_solver.add(equality); z3_solver.push(); { z3_solver.add(z != 0L); EXPECT_EQ(smt::unsat, z3_solver.check()); } z3_solver.pop(); z3_solver.push(); { z3_solver.add(z == 0L); EXPECT_EQ(smt::sat, z3_solver.check()); } z3_solver.pop(); smt::MsatSolver msat_solver; msat_solver.add(equality); msat_solver.push(); { msat_solver.add(z != 0L); EXPECT_EQ(smt::unsat, msat_solver.check()); } msat_solver.pop(); msat_solver.push(); { msat_solver.add(z == 0L); EXPECT_EQ(smt::sat, msat_solver.check()); } msat_solver.pop(); } TEST(SmtFunctionalTest, UnsafeExpr) { const smt::UnsafeDecl unsafe_decl("x", smt::bv_sort(true, sizeof(int) * 8)); const smt::UnsafeExprPtr x = smt::constant(unsafe_decl); const smt::UnsafeExprPtr equality = (x & smt::literal<int>(3)) != x; smt::Z3Solver z3_solver; z3_solver.unsafe_add(equality); EXPECT_EQ(smt::sat, z3_solver.check()); smt::MsatSolver msat_solver; msat_solver.unsafe_add(equality); EXPECT_EQ(smt::sat, msat_solver.check()); } TEST(SmtFunctionalTest, Reflection) { constexpr size_t bv_int_size = sizeof(int) * 8; EXPECT_EQ(smt::bv_sort(true, bv_int_size), smt::literal<int>(3)->sort()); const smt::ExprPtr<uint32_t> x = smt::any<uint32_t>("x"); EXPECT_TRUE(x->sort().is_bv()); EXPECT_FALSE(x->sort().is_signed()); EXPECT_EQ(32, x->sort().bv_size()); typedef smt::Func<smt::Int, smt::Real, char> SomeFunc; const smt::ExprPtr<SomeFunc> f = smt::any<SomeFunc>("f"); EXPECT_TRUE(f->sort().is_func()); EXPECT_EQ(3, f->sort().sorts_size()); EXPECT_TRUE(f->sort().sorts(0).is_int()); EXPECT_TRUE(f->sort().sorts(1).is_real()); EXPECT_TRUE(f->sort().sorts(2).is_bv()); EXPECT_EQ(sizeof(char) * 8, f->sort().sorts(2).bv_size()); } TEST(SmtFunctionalTest, Array) { typedef smt::Array<smt::Int, char> IntToCharArray; const smt::Decl<IntToCharArray> array_decl("array"); smt::ExprPtr<IntToCharArray> array, new_array; smt::ExprPtr<smt::Int> index; smt::ExprPtr<char> value; array = smt::constant(array_decl); index = smt::any<smt::Int>("index"); value = smt::literal<char>('p'); new_array = smt::store(array, index, value); smt::Z3Solver z3_solver; z3_solver.add(smt::select(new_array, index) != value); EXPECT_EQ(smt::unsat, z3_solver.check()); smt::MsatSolver msat_solver; msat_solver.add(smt::select(new_array, index) != value); EXPECT_EQ(smt::unsat, msat_solver.check()); } TEST(SmtFunctionalTest, Function) { const smt::Decl<smt::Func<smt::Int, smt::Int>> func_decl("f"); const smt::ExprPtr<smt::Int> x = smt::any<smt::Int>("x"); const smt::ExprPtr<smt::Bool> formula = smt::apply(func_decl, 3) == 7 && x == smt::apply(func_decl, 3); smt::Z3Solver z3_solver; z3_solver.add(formula && x != smt::literal<smt::Int>(7)); EXPECT_EQ(smt::unsat, z3_solver.check()); smt::MsatSolver msat_solver; msat_solver.add(formula && x != 7); EXPECT_EQ(smt::unsat, msat_solver.check()); } <|endoftext|>
<commit_before><commit_msg>rtl_cipher_decode doesn't like 0 len data<commit_after><|endoftext|>
<commit_before>#include <ostream> #include <gtest/gtest.h> #include "FromEvent.hpp" using namespace org_pqrs_KeyRemap4MacBook; Params_KeyboardEventCallBack::auto_ptr down_return( Params_KeyboardEventCallBack::alloc( EventType::DOWN, Flags(0), KeyCode::RETURN, CharCode(0), CharSet(0), OrigCharCode(0), OrigCharSet(0), KeyboardType(0), false)); Params_KeyboardEventCallBack::auto_ptr up_return( Params_KeyboardEventCallBack::alloc( EventType::UP, Flags(0), KeyCode::RETURN, CharCode(0), CharSet(0), OrigCharCode(0), OrigCharSet(0), KeyboardType(0), false)); Params_KeyboardEventCallBack::auto_ptr down_shift( Params_KeyboardEventCallBack::alloc( EventType::MODIFY, Flags(ModifierFlag::SHIFT_L), KeyCode::SHIFT_L, CharCode(0), CharSet(0), OrigCharCode(0), OrigCharSet(0), KeyboardType(0), false)); Params_KeyboardEventCallBack::auto_ptr up_shift( Params_KeyboardEventCallBack::alloc( EventType::MODIFY, Flags(0), KeyCode::SHIFT_L, CharCode(0), CharSet(0), OrigCharCode(0), OrigCharSet(0), KeyboardType(0), false)); TEST(Generic, getModifierFlag) { { FromEvent fe(KeyCode::RETURN); EXPECT_EQ(ModifierFlag::NONE, fe.getModifierFlag()); } { FromEvent fe(KeyCode::SHIFT_L); EXPECT_EQ(ModifierFlag::SHIFT_L, fe.getModifierFlag()); } { FromEvent fe(ConsumerKeyCode::VOLUME_MUTE); EXPECT_EQ(ModifierFlag::NONE, fe.getModifierFlag()); } { FromEvent fe(PointingButton::LEFT); EXPECT_EQ(ModifierFlag::NONE, fe.getModifierFlag()); } } TEST(Generic, changePressingState) { { FromEvent fe(KeyCode::RETURN); EXPECT_EQ(false, fe.isPressing()); Flags currentFlags(0); Flags fromFlags(0); // ---------------------------------------- // Without Flags // (For example, "change return to tab".) EXPECT_EQ(true, fe.changePressingState(*down_return, currentFlags, fromFlags)); EXPECT_EQ(true, fe.isPressing()); EXPECT_EQ(true, fe.changePressingState(*up_return, currentFlags, fromFlags)); EXPECT_EQ(false, fe.isPressing()); // Another event does not modify state EXPECT_EQ(false, fe.changePressingState(*down_shift, currentFlags, fromFlags)); EXPECT_EQ(false, fe.isPressing()); EXPECT_EQ(false, fe.changePressingState(*up_shift, currentFlags, fromFlags)); EXPECT_EQ(false, fe.isPressing()); // ---------------------------------------- // Set currentFlags // (For example, "change return to tab".) currentFlags = Flags(ModifierFlag::SHIFT_L); EXPECT_EQ(true, fe.changePressingState(*down_return, currentFlags, fromFlags)); EXPECT_EQ(true, fe.isPressing()); EXPECT_EQ(true, fe.changePressingState(*up_return, currentFlags, fromFlags)); EXPECT_EQ(false, fe.isPressing()); // ---------------------------------------- // Set fromFlags // (For example, "change shift-return to tab".) // Does not change state if currentFlags lacks flags. currentFlags = Flags(0); fromFlags = Flags(ModifierFlag::SHIFT_L); EXPECT_EQ(false, fe.changePressingState(*down_return, currentFlags, fromFlags)); EXPECT_EQ(false, fe.isPressing()); EXPECT_EQ(false, fe.changePressingState(*up_return, currentFlags, fromFlags)); EXPECT_EQ(false, fe.isPressing()); // ---------- currentFlags = Flags(ModifierFlag::SHIFT_L); fromFlags = Flags(ModifierFlag::SHIFT_L); EXPECT_EQ(true, fe.changePressingState(*down_return, currentFlags, fromFlags)); EXPECT_EQ(true, fe.isPressing()); EXPECT_EQ(true, fe.changePressingState(*up_return, currentFlags, fromFlags)); EXPECT_EQ(false, fe.isPressing()); // ---------- currentFlags = Flags(ModifierFlag::SHIFT_L); fromFlags = Flags(ModifierFlag::SHIFT_L); EXPECT_EQ(true, fe.changePressingState(*down_return, currentFlags, fromFlags)); EXPECT_EQ(true, fe.isPressing()); // Change state even if currentFlags lacks flags when key is pressing. // This behavior is necessary for this case. // - shift down // - return down (shift-return is pressed.) // - shift up // - return up (shift-return is released.) currentFlags = Flags(0); EXPECT_EQ(true, fe.changePressingState(*up_return, currentFlags, fromFlags)); EXPECT_EQ(false, fe.isPressing()); // return false if call changePressingState once again. EXPECT_EQ(false, fe.changePressingState(*up_return, currentFlags, fromFlags)); } { FromEvent fe(KeyCode::SPACE); EXPECT_EQ(false, fe.changePressingState(*down_return, Flags(0), Flags(0))); EXPECT_EQ(false, fe.changePressingState(*up_return, Flags(0), Flags(0))); } { FromEvent fe(KeyCode::SHIFT_L); EXPECT_EQ(true, fe.changePressingState(*down_shift, Flags(ModifierFlag::SHIFT_L), Flags(0))); EXPECT_EQ(true, fe.isPressing()); EXPECT_EQ(true, fe.changePressingState(*up_shift, Flags(0), Flags(0))); EXPECT_EQ(false, fe.isPressing()); } } TEST(Generic, isTargetDownEvent) { { FromEvent fe(KeyCode::RETURN); EXPECT_EQ(true, fe.isTargetDownEvent(*down_return)); EXPECT_EQ(false, fe.isTargetUpEvent(*down_return)); EXPECT_EQ(false, fe.isTargetDownEvent(*up_return)); EXPECT_EQ(true, fe.isTargetUpEvent(*up_return)); EXPECT_EQ(false, fe.isTargetDownEvent(*down_shift)); EXPECT_EQ(false, fe.isTargetUpEvent(*down_shift)); EXPECT_EQ(false, fe.isTargetDownEvent(*up_shift)); EXPECT_EQ(false, fe.isTargetUpEvent(*up_shift)); } { FromEvent fe(KeyCode::SHIFT_L); EXPECT_EQ(true, fe.isTargetDownEvent(*down_shift)); EXPECT_EQ(false, fe.isTargetUpEvent(*down_shift)); EXPECT_EQ(false, fe.isTargetDownEvent(*up_shift)); EXPECT_EQ(true, fe.isTargetUpEvent(*up_shift)); } } <commit_msg>update Tests<commit_after>#include <ostream> #include <gtest/gtest.h> #include "FromEvent.hpp" using namespace org_pqrs_KeyRemap4MacBook; ParamsUnion down_return( *(Params_KeyboardEventCallBack::auto_ptr( Params_KeyboardEventCallBack::alloc( EventType::DOWN, Flags(0), KeyCode::RETURN, CharCode(0), CharSet(0), OrigCharCode(0), OrigCharSet(0), KeyboardType(0), false)))); ParamsUnion up_return( *(Params_KeyboardEventCallBack::auto_ptr( Params_KeyboardEventCallBack::alloc( EventType::UP, Flags(0), KeyCode::RETURN, CharCode(0), CharSet(0), OrigCharCode(0), OrigCharSet(0), KeyboardType(0), false)))); ParamsUnion down_shift( *(Params_KeyboardEventCallBack::auto_ptr( Params_KeyboardEventCallBack::alloc( EventType::MODIFY, Flags(ModifierFlag::SHIFT_L), KeyCode::SHIFT_L, CharCode(0), CharSet(0), OrigCharCode(0), OrigCharSet(0), KeyboardType(0), false)))); ParamsUnion up_shift( *(Params_KeyboardEventCallBack::auto_ptr( Params_KeyboardEventCallBack::alloc( EventType::MODIFY, Flags(0), KeyCode::SHIFT_L, CharCode(0), CharSet(0), OrigCharCode(0), OrigCharSet(0), KeyboardType(0), false)))); TEST(Generic, getModifierFlag) { { FromEvent fe(KeyCode::RETURN); EXPECT_EQ(ModifierFlag::NONE, fe.getModifierFlag()); } { FromEvent fe(KeyCode::SHIFT_L); EXPECT_EQ(ModifierFlag::SHIFT_L, fe.getModifierFlag()); } { FromEvent fe(ConsumerKeyCode::VOLUME_MUTE); EXPECT_EQ(ModifierFlag::NONE, fe.getModifierFlag()); } { FromEvent fe(PointingButton::LEFT); EXPECT_EQ(ModifierFlag::NONE, fe.getModifierFlag()); } } TEST(Generic, changePressingState) { { FromEvent fe(KeyCode::RETURN); EXPECT_EQ(false, fe.isPressing()); Flags currentFlags(0); Flags fromFlags(0); // ---------------------------------------- // Without Flags // (For example, "change return to tab".) EXPECT_EQ(true, fe.changePressingState(down_return, currentFlags, fromFlags)); EXPECT_EQ(true, fe.isPressing()); EXPECT_EQ(true, fe.changePressingState(up_return, currentFlags, fromFlags)); EXPECT_EQ(false, fe.isPressing()); // Another event does not modify state EXPECT_EQ(false, fe.changePressingState(down_shift, currentFlags, fromFlags)); EXPECT_EQ(false, fe.isPressing()); EXPECT_EQ(false, fe.changePressingState(up_shift, currentFlags, fromFlags)); EXPECT_EQ(false, fe.isPressing()); // ---------------------------------------- // Set currentFlags // (For example, "change return to tab".) currentFlags = Flags(ModifierFlag::SHIFT_L); EXPECT_EQ(true, fe.changePressingState(down_return, currentFlags, fromFlags)); EXPECT_EQ(true, fe.isPressing()); EXPECT_EQ(true, fe.changePressingState(up_return, currentFlags, fromFlags)); EXPECT_EQ(false, fe.isPressing()); // ---------------------------------------- // Set fromFlags // (For example, "change shift-return to tab".) // Does not change state if currentFlags lacks flags. currentFlags = Flags(0); fromFlags = Flags(ModifierFlag::SHIFT_L); EXPECT_EQ(false, fe.changePressingState(down_return, currentFlags, fromFlags)); EXPECT_EQ(false, fe.isPressing()); EXPECT_EQ(false, fe.changePressingState(up_return, currentFlags, fromFlags)); EXPECT_EQ(false, fe.isPressing()); // ---------- currentFlags = Flags(ModifierFlag::SHIFT_L); fromFlags = Flags(ModifierFlag::SHIFT_L); EXPECT_EQ(true, fe.changePressingState(down_return, currentFlags, fromFlags)); EXPECT_EQ(true, fe.isPressing()); EXPECT_EQ(true, fe.changePressingState(up_return, currentFlags, fromFlags)); EXPECT_EQ(false, fe.isPressing()); // ---------- currentFlags = Flags(ModifierFlag::SHIFT_L); fromFlags = Flags(ModifierFlag::SHIFT_L); EXPECT_EQ(true, fe.changePressingState(down_return, currentFlags, fromFlags)); EXPECT_EQ(true, fe.isPressing()); // Change state even if currentFlags lacks flags when key is pressing. // This behavior is necessary for this case. // - shift down // - return down (shift-return is pressed.) // - shift up // - return up (shift-return is released.) currentFlags = Flags(0); EXPECT_EQ(true, fe.changePressingState(up_return, currentFlags, fromFlags)); EXPECT_EQ(false, fe.isPressing()); // return false if call changePressingState once again. EXPECT_EQ(false, fe.changePressingState(up_return, currentFlags, fromFlags)); } { FromEvent fe(KeyCode::SPACE); EXPECT_EQ(false, fe.changePressingState(down_return, Flags(0), Flags(0))); EXPECT_EQ(false, fe.changePressingState(up_return, Flags(0), Flags(0))); } { FromEvent fe(KeyCode::SHIFT_L); EXPECT_EQ(true, fe.changePressingState(down_shift, Flags(ModifierFlag::SHIFT_L), Flags(0))); EXPECT_EQ(true, fe.isPressing()); EXPECT_EQ(true, fe.changePressingState(up_shift, Flags(0), Flags(0))); EXPECT_EQ(false, fe.isPressing()); } } TEST(Generic, unsetPressingState) { { FromEvent fe(KeyCode::RETURN); EXPECT_EQ(true, fe.changePressingState(down_return, Flags(0), Flags(0))); EXPECT_EQ(true, fe.isPressing()); fe.unsetPressingState(); EXPECT_EQ(false, fe.isPressing()); } } TEST(Generic, isTargetDownEvent) { { FromEvent fe(KeyCode::RETURN); EXPECT_EQ(true, fe.isTargetDownEvent(down_return)); EXPECT_EQ(false, fe.isTargetUpEvent(down_return)); EXPECT_EQ(false, fe.isTargetDownEvent(up_return)); EXPECT_EQ(true, fe.isTargetUpEvent(up_return)); EXPECT_EQ(false, fe.isTargetDownEvent(down_shift)); EXPECT_EQ(false, fe.isTargetUpEvent(down_shift)); EXPECT_EQ(false, fe.isTargetDownEvent(up_shift)); EXPECT_EQ(false, fe.isTargetUpEvent(up_shift)); } { FromEvent fe(KeyCode::SHIFT_L); EXPECT_EQ(true, fe.isTargetDownEvent(down_shift)); EXPECT_EQ(false, fe.isTargetUpEvent(down_shift)); EXPECT_EQ(false, fe.isTargetDownEvent(up_shift)); EXPECT_EQ(true, fe.isTargetUpEvent(up_shift)); } } <|endoftext|>
<commit_before>/* * Copyright (c) 2009 Advanced Micro Devices, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders 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. */ #include "cpu/testers/rubytest/RubyTester.hh" #include "mem/physical.hh" #include "mem/ruby/slicc_interface/AbstractController.hh" #include "mem/ruby/system/RubyPort.hh" RubyPort::RubyPort(const Params *p) : MemObject(p) { m_version = p->version; assert(m_version != -1); physmem = p->physmem; m_controller = NULL; m_mandatory_q_ptr = NULL; m_request_cnt = 0; pio_port = NULL; physMemPort = NULL; } void RubyPort::init() { assert(m_controller != NULL); m_mandatory_q_ptr = m_controller->getMandatoryQueue(); } Port * RubyPort::getPort(const std::string &if_name, int idx) { if (if_name == "port") { return new M5Port(csprintf("%s-port%d", name(), idx), this); } if (if_name == "pio_port") { // ensure there is only one pio port assert(pio_port == NULL); pio_port = new PioPort(csprintf("%s-pio-port%d", name(), idx), this); return pio_port; } if (if_name == "physMemPort") { // RubyPort should only have one port to physical memory assert (physMemPort == NULL); physMemPort = new M5Port(csprintf("%s-physMemPort", name()), this); return physMemPort; } if (if_name == "functional") { // Calls for the functional port only want to access // functional memory. Therefore, directly pass these calls // ports to physmem. assert(physmem != NULL); return physmem->getPort(if_name, idx); } return NULL; } RubyPort::PioPort::PioPort(const std::string &_name, RubyPort *_port) : SimpleTimingPort(_name, _port) { DPRINTF(Ruby, "creating port to ruby sequencer to cpu %s\n", _name); ruby_port = _port; } RubyPort::M5Port::M5Port(const std::string &_name, RubyPort *_port) : SimpleTimingPort(_name, _port) { DPRINTF(Ruby, "creating port from ruby sequcner to cpu %s\n", _name); ruby_port = _port; } Tick RubyPort::PioPort::recvAtomic(PacketPtr pkt) { panic("RubyPort::PioPort::recvAtomic() not implemented!\n"); return 0; } Tick RubyPort::M5Port::recvAtomic(PacketPtr pkt) { panic("RubyPort::M5Port::recvAtomic() not implemented!\n"); return 0; } bool RubyPort::PioPort::recvTiming(PacketPtr pkt) { // In FS mode, ruby memory will receive pio responses from devices // and it must forward these responses back to the particular CPU. DPRINTF(MemoryAccess, "Pio response for address %#x\n", pkt->getAddr()); assert(pkt->isResponse()); // First we must retrieve the request port from the sender State RubyPort::SenderState *senderState = safe_cast<RubyPort::SenderState *>(pkt->senderState); M5Port *port = senderState->port; assert(port != NULL); // pop the sender state from the packet pkt->senderState = senderState->saved; delete senderState; port->sendTiming(pkt); return true; } bool RubyPort::M5Port::recvTiming(PacketPtr pkt) { DPRINTF(MemoryAccess, "Timing access caught for address %#x\n", pkt->getAddr()); //dsm: based on SimpleTimingPort::recvTiming(pkt); // The received packets should only be M5 requests, which should never // get nacked. There used to be code to hanldle nacks here, but // I'm pretty sure it didn't work correctly with the drain code, // so that would need to be fixed if we ever added it back. assert(pkt->isRequest()); if (pkt->memInhibitAsserted()) { warn("memInhibitAsserted???"); // snooper will supply based on copy of packet // still target's responsibility to delete packet delete pkt; return true; } // Save the port in the sender state object to be used later to // route the response pkt->senderState = new SenderState(this, pkt->senderState); // Check for pio requests and directly send them to the dedicated // pio port. if (!isPhysMemAddress(pkt->getAddr())) { assert(ruby_port->pio_port != NULL); DPRINTF(MemoryAccess, "Request for address 0x%#x is assumed to be a pio request\n", pkt->getAddr()); return ruby_port->pio_port->sendTiming(pkt); } // For DMA and CPU requests, translate them to ruby requests before // sending them to our assigned ruby port. RubyRequestType type = RubyRequestType_NULL; // If valid, copy the pc to the ruby request Addr pc = 0; if (pkt->req->hasPC()) { pc = pkt->req->getPC(); } if (pkt->isLLSC()) { if (pkt->isWrite()) { DPRINTF(MemoryAccess, "Issuing SC\n"); type = RubyRequestType_Locked_Write; } else { DPRINTF(MemoryAccess, "Issuing LL\n"); assert(pkt->isRead()); type = RubyRequestType_Locked_Read; } } else { if (pkt->isRead()) { if (pkt->req->isInstFetch()) { type = RubyRequestType_IFETCH; } else { type = RubyRequestType_LD; } } else if (pkt->isWrite()) { type = RubyRequestType_ST; } else if (pkt->isReadWrite()) { // Fix me. This conditional will never be executed // because isReadWrite() is just an OR of isRead() and // isWrite(). Furthermore, just because the packet is a // read/write request does not necessary mean it is a // read-modify-write atomic operation. type = RubyRequestType_RMW_Write; } else { panic("Unsupported ruby packet type\n"); } } RubyRequest ruby_request(pkt->getAddr(), pkt->getPtr<uint8_t>(), pkt->getSize(), pc, type, RubyAccessMode_Supervisor, pkt); // Submit the ruby request RequestStatus requestStatus = ruby_port->makeRequest(ruby_request); // If the request successfully issued then we should return true. // Otherwise, we need to delete the senderStatus we just created and return // false. if (requestStatus == RequestStatus_Issued) { return true; } DPRINTF(MemoryAccess, "Request for address #x did not issue because %s\n", pkt->getAddr(), RequestStatus_to_string(requestStatus)); SenderState* senderState = safe_cast<SenderState*>(pkt->senderState); pkt->senderState = senderState->saved; delete senderState; return false; } void RubyPort::ruby_hit_callback(PacketPtr pkt) { // Retrieve the request port from the sender State RubyPort::SenderState *senderState = safe_cast<RubyPort::SenderState *>(pkt->senderState); M5Port *port = senderState->port; assert(port != NULL); // pop the sender state from the packet pkt->senderState = senderState->saved; delete senderState; port->hitCallback(pkt); } void RubyPort::M5Port::hitCallback(PacketPtr pkt) { bool needsResponse = pkt->needsResponse(); // // All responses except failed SC operations access M5 physical memory // bool accessPhysMem = true; if (pkt->isLLSC()) { if (pkt->isWrite()) { if (pkt->req->getExtraData() != 0) { // // Successful SC packets convert to normal writes // pkt->convertScToWrite(); } else { // // Failed SC packets don't access physical memory and thus // the RubyPort itself must convert it to a response. // accessPhysMem = false; pkt->makeAtomicResponse(); } } else { // // All LL packets convert to normal loads so that M5 PhysMem does // not lock the blocks. // pkt->convertLlToRead(); } } DPRINTF(MemoryAccess, "Hit callback needs response %d\n", needsResponse); if (accessPhysMem) { ruby_port->physMemPort->sendAtomic(pkt); } // turn packet around to go back to requester if response expected if (needsResponse) { // sendAtomic() should already have turned packet into // atomic response assert(pkt->isResponse()); DPRINTF(MemoryAccess, "Sending packet back over port\n"); sendTiming(pkt); } else { delete pkt; } DPRINTF(MemoryAccess, "Hit callback done!\n"); } bool RubyPort::M5Port::sendTiming(PacketPtr pkt) { //minimum latency, must be > 0 schedSendTiming(pkt, curTick() + (1 * g_eventQueue_ptr->getClock())); return true; } bool RubyPort::PioPort::sendTiming(PacketPtr pkt) { //minimum latency, must be > 0 schedSendTiming(pkt, curTick() + (1 * g_eventQueue_ptr->getClock())); return true; } bool RubyPort::M5Port::isPhysMemAddress(Addr addr) { AddrRangeList physMemAddrList; bool snoop = false; ruby_port->physMemPort->getPeerAddressRanges(physMemAddrList, snoop); for (AddrRangeIter iter = physMemAddrList.begin(); iter != physMemAddrList.end(); iter++) { if (addr >= iter->start && addr <= iter->end) { DPRINTF(MemoryAccess, "Request found in %#llx - %#llx range\n", iter->start, iter->end); return true; } } return false; } <commit_msg>ruby: Assert for x86 misaligned access<commit_after>/* * Copyright (c) 2009 Advanced Micro Devices, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders 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. */ #include "cpu/testers/rubytest/RubyTester.hh" #include "mem/physical.hh" #include "mem/ruby/slicc_interface/AbstractController.hh" #include "mem/ruby/system/RubyPort.hh" RubyPort::RubyPort(const Params *p) : MemObject(p) { m_version = p->version; assert(m_version != -1); physmem = p->physmem; m_controller = NULL; m_mandatory_q_ptr = NULL; m_request_cnt = 0; pio_port = NULL; physMemPort = NULL; } void RubyPort::init() { assert(m_controller != NULL); m_mandatory_q_ptr = m_controller->getMandatoryQueue(); } Port * RubyPort::getPort(const std::string &if_name, int idx) { if (if_name == "port") { return new M5Port(csprintf("%s-port%d", name(), idx), this); } if (if_name == "pio_port") { // ensure there is only one pio port assert(pio_port == NULL); pio_port = new PioPort(csprintf("%s-pio-port%d", name(), idx), this); return pio_port; } if (if_name == "physMemPort") { // RubyPort should only have one port to physical memory assert (physMemPort == NULL); physMemPort = new M5Port(csprintf("%s-physMemPort", name()), this); return physMemPort; } if (if_name == "functional") { // Calls for the functional port only want to access // functional memory. Therefore, directly pass these calls // ports to physmem. assert(physmem != NULL); return physmem->getPort(if_name, idx); } return NULL; } RubyPort::PioPort::PioPort(const std::string &_name, RubyPort *_port) : SimpleTimingPort(_name, _port) { DPRINTF(Ruby, "creating port to ruby sequencer to cpu %s\n", _name); ruby_port = _port; } RubyPort::M5Port::M5Port(const std::string &_name, RubyPort *_port) : SimpleTimingPort(_name, _port) { DPRINTF(Ruby, "creating port from ruby sequcner to cpu %s\n", _name); ruby_port = _port; } Tick RubyPort::PioPort::recvAtomic(PacketPtr pkt) { panic("RubyPort::PioPort::recvAtomic() not implemented!\n"); return 0; } Tick RubyPort::M5Port::recvAtomic(PacketPtr pkt) { panic("RubyPort::M5Port::recvAtomic() not implemented!\n"); return 0; } bool RubyPort::PioPort::recvTiming(PacketPtr pkt) { // In FS mode, ruby memory will receive pio responses from devices // and it must forward these responses back to the particular CPU. DPRINTF(MemoryAccess, "Pio response for address %#x\n", pkt->getAddr()); assert(pkt->isResponse()); // First we must retrieve the request port from the sender State RubyPort::SenderState *senderState = safe_cast<RubyPort::SenderState *>(pkt->senderState); M5Port *port = senderState->port; assert(port != NULL); // pop the sender state from the packet pkt->senderState = senderState->saved; delete senderState; port->sendTiming(pkt); return true; } bool RubyPort::M5Port::recvTiming(PacketPtr pkt) { DPRINTF(MemoryAccess, "Timing access caught for address %#x\n", pkt->getAddr()); //dsm: based on SimpleTimingPort::recvTiming(pkt); // The received packets should only be M5 requests, which should never // get nacked. There used to be code to hanldle nacks here, but // I'm pretty sure it didn't work correctly with the drain code, // so that would need to be fixed if we ever added it back. assert(pkt->isRequest()); if (pkt->memInhibitAsserted()) { warn("memInhibitAsserted???"); // snooper will supply based on copy of packet // still target's responsibility to delete packet delete pkt; return true; } // Save the port in the sender state object to be used later to // route the response pkt->senderState = new SenderState(this, pkt->senderState); // Check for pio requests and directly send them to the dedicated // pio port. if (!isPhysMemAddress(pkt->getAddr())) { assert(ruby_port->pio_port != NULL); DPRINTF(MemoryAccess, "Request for address 0x%#x is assumed to be a pio request\n", pkt->getAddr()); return ruby_port->pio_port->sendTiming(pkt); } // For DMA and CPU requests, translate them to ruby requests before // sending them to our assigned ruby port. RubyRequestType type = RubyRequestType_NULL; // If valid, copy the pc to the ruby request Addr pc = 0; if (pkt->req->hasPC()) { pc = pkt->req->getPC(); } if (pkt->isLLSC()) { if (pkt->isWrite()) { DPRINTF(MemoryAccess, "Issuing SC\n"); type = RubyRequestType_Locked_Write; } else { DPRINTF(MemoryAccess, "Issuing LL\n"); assert(pkt->isRead()); type = RubyRequestType_Locked_Read; } } else { if (pkt->isRead()) { if (pkt->req->isInstFetch()) { type = RubyRequestType_IFETCH; } else { type = RubyRequestType_LD; } } else if (pkt->isWrite()) { type = RubyRequestType_ST; } else if (pkt->isReadWrite()) { // Fix me. This conditional will never be executed // because isReadWrite() is just an OR of isRead() and // isWrite(). Furthermore, just because the packet is a // read/write request does not necessary mean it is a // read-modify-write atomic operation. type = RubyRequestType_RMW_Write; } else { panic("Unsupported ruby packet type\n"); } } RubyRequest ruby_request(pkt->getAddr(), pkt->getPtr<uint8_t>(), pkt->getSize(), pc, type, RubyAccessMode_Supervisor, pkt); assert(Address(ruby_request.paddr).getOffset() + ruby_request.len <= RubySystem::getBlockSizeBytes()); // Submit the ruby request RequestStatus requestStatus = ruby_port->makeRequest(ruby_request); // If the request successfully issued then we should return true. // Otherwise, we need to delete the senderStatus we just created and return // false. if (requestStatus == RequestStatus_Issued) { return true; } DPRINTF(MemoryAccess, "Request for address %#x did not issue because %s\n", pkt->getAddr(), RequestStatus_to_string(requestStatus)); SenderState* senderState = safe_cast<SenderState*>(pkt->senderState); pkt->senderState = senderState->saved; delete senderState; return false; } void RubyPort::ruby_hit_callback(PacketPtr pkt) { // Retrieve the request port from the sender State RubyPort::SenderState *senderState = safe_cast<RubyPort::SenderState *>(pkt->senderState); M5Port *port = senderState->port; assert(port != NULL); // pop the sender state from the packet pkt->senderState = senderState->saved; delete senderState; port->hitCallback(pkt); } void RubyPort::M5Port::hitCallback(PacketPtr pkt) { bool needsResponse = pkt->needsResponse(); // // All responses except failed SC operations access M5 physical memory // bool accessPhysMem = true; if (pkt->isLLSC()) { if (pkt->isWrite()) { if (pkt->req->getExtraData() != 0) { // // Successful SC packets convert to normal writes // pkt->convertScToWrite(); } else { // // Failed SC packets don't access physical memory and thus // the RubyPort itself must convert it to a response. // accessPhysMem = false; pkt->makeAtomicResponse(); } } else { // // All LL packets convert to normal loads so that M5 PhysMem does // not lock the blocks. // pkt->convertLlToRead(); } } DPRINTF(MemoryAccess, "Hit callback needs response %d\n", needsResponse); if (accessPhysMem) { ruby_port->physMemPort->sendAtomic(pkt); } // turn packet around to go back to requester if response expected if (needsResponse) { // sendAtomic() should already have turned packet into // atomic response assert(pkt->isResponse()); DPRINTF(MemoryAccess, "Sending packet back over port\n"); sendTiming(pkt); } else { delete pkt; } DPRINTF(MemoryAccess, "Hit callback done!\n"); } bool RubyPort::M5Port::sendTiming(PacketPtr pkt) { //minimum latency, must be > 0 schedSendTiming(pkt, curTick() + (1 * g_eventQueue_ptr->getClock())); return true; } bool RubyPort::PioPort::sendTiming(PacketPtr pkt) { //minimum latency, must be > 0 schedSendTiming(pkt, curTick() + (1 * g_eventQueue_ptr->getClock())); return true; } bool RubyPort::M5Port::isPhysMemAddress(Addr addr) { AddrRangeList physMemAddrList; bool snoop = false; ruby_port->physMemPort->getPeerAddressRanges(physMemAddrList, snoop); for (AddrRangeIter iter = physMemAddrList.begin(); iter != physMemAddrList.end(); iter++) { if (addr >= iter->start && addr <= iter->end) { DPRINTF(MemoryAccess, "Request found in %#llx - %#llx range\n", iter->start, iter->end); return true; } } return false; } <|endoftext|>
<commit_before>#include "llvmtgsi.h" #include "pipe/tgsi/exec/tgsi_exec.h" #include "pipe/tgsi/exec/tgsi_token.h" #include "pipe/tgsi/exec/tgsi_build.h" #include "pipe/tgsi/exec/tgsi_util.h" #include "pipe/tgsi/exec/tgsi_parse.h" #include "pipe/tgsi/exec/tgsi_dump.h" //#include "pipe/tgsi/tgsi_platform.h" #include <llvm/Module.h> #include <llvm/CallingConv.h> #include <llvm/Constants.h> #include <llvm/DerivedTypes.h> #include <llvm/Instructions.h> #include <llvm/ModuleProvider.h> #include <llvm/ParameterAttributes.h> #include <llvm/Support/PatternMatch.h> #include <llvm/ExecutionEngine/JIT.h> #include <llvm/ExecutionEngine/Interpreter.h> #include <llvm/ExecutionEngine/GenericValue.h> #include <llvm/Support/MemoryBuffer.h> #include <llvm/Bitcode/ReaderWriter.h> #include <iostream> static void translate_declaration(llvm::Module *module, struct tgsi_full_declaration *decl, struct tgsi_full_declaration *fd) { } static void translate_immediate(llvm::Module *module, struct tgsi_full_immediate *imm) { } static void translate_instruction(llvm::Module *module, struct tgsi_full_instruction *inst, struct tgsi_full_instruction *fi) { } static llvm::Module * tgsi_to_llvm(const struct tgsi_token *tokens) { llvm::Module *mod = new llvm::Module("tgsi"); struct tgsi_parse_context parse; struct tgsi_full_instruction fi; struct tgsi_full_declaration fd; tgsi_parse_init(&parse, tokens); //parse.FullHeader.Processor.Processor //parse.FullVersion.Version.MajorVersion //parse.FullVersion.Version.MinorVersion //parse.FullHeader.Header.HeaderSize //parse.FullHeader.Header.BodySize //parse.FullHeader.Processor.Processor fi = tgsi_default_full_instruction(); fd = tgsi_default_full_declaration(); while(!tgsi_parse_end_of_tokens(&parse)) { tgsi_parse_token(&parse); fprintf(stderr, "Translating %d\n", parse.FullToken.Token.Type); switch (parse.FullToken.Token.Type) { case TGSI_TOKEN_TYPE_DECLARATION: translate_declaration(mod, &parse.FullToken.FullDeclaration, &fd); break; case TGSI_TOKEN_TYPE_IMMEDIATE: translate_immediate(mod, &parse.FullToken.FullImmediate); break; case TGSI_TOKEN_TYPE_INSTRUCTION: translate_instruction(mod, &parse.FullToken.FullInstruction, &fi); break; default: assert(0); } } //TXT("\ntgsi-dump end -------------------\n"); tgsi_parse_free(&parse); return mod; } struct ga_llvm_prog * ga_llvm_from_tgsi(const struct tgsi_token *tokens) { std::cout << "Creating llvm " <<std::endl; struct ga_llvm_prog *ga_llvm = (struct ga_llvm_prog *)malloc(sizeof(struct ga_llvm_prog)); llvm::Module *mod = tgsi_to_llvm(tokens); llvm::ExistingModuleProvider *mp = new llvm::ExistingModuleProvider(mod); //llvm::ExecutionEngine *ee = // llvm::ExecutionEngine::create(mp, false); ga_llvm->module = mod; ga_llvm->engine = 0;//ee; fprintf(stderr, "DUMPX \n"); //tgsi_dump(tokens, TGSI_DUMP_VERBOSE); tgsi_dump(tokens, 0); fprintf(stderr, "DUMPEND \n"); return ga_llvm; } void ga_llvm_prog_delete(struct ga_llvm_prog *prog) { llvm::Module *mod = static_cast<llvm::Module*>(prog->module); delete mod; prog->module = 0; prog->engine = 0; free(prog); } int ga_llvm_prog_exec(struct ga_llvm_prog *prog) { //std::cout << "START "<<std::endl; llvm::Module *mod = static_cast<llvm::Module*>(prog->module); llvm::Function *func = mod->getFunction("main"); llvm::ExecutionEngine *ee = static_cast<llvm::ExecutionEngine*>(prog->engine); std::vector<llvm::GenericValue> args(0); //args[0] = GenericValue(&st); //std::cout << "Mod is "<<*mod; //std::cout << "\n\nRunning llvm: " << std::endl; if (func) { std::cout << "Func is "<<func; llvm::GenericValue gv = ee->runFunction(func, args); } //delete ee; //delete mp; return 0; } <commit_msg>Stub out some conversion.<commit_after>#include "llvmtgsi.h" #include "pipe/tgsi/exec/tgsi_exec.h" #include "pipe/tgsi/exec/tgsi_token.h" #include "pipe/tgsi/exec/tgsi_build.h" #include "pipe/tgsi/exec/tgsi_util.h" #include "pipe/tgsi/exec/tgsi_parse.h" #include "pipe/tgsi/exec/tgsi_dump.h" //#include "pipe/tgsi/tgsi_platform.h" #include <llvm/Module.h> #include <llvm/CallingConv.h> #include <llvm/Constants.h> #include <llvm/DerivedTypes.h> #include <llvm/Instructions.h> #include <llvm/ModuleProvider.h> #include <llvm/ParameterAttributes.h> #include <llvm/Support/PatternMatch.h> #include <llvm/ExecutionEngine/JIT.h> #include <llvm/ExecutionEngine/Interpreter.h> #include <llvm/ExecutionEngine/GenericValue.h> #include <llvm/Support/MemoryBuffer.h> #include <llvm/Bitcode/ReaderWriter.h> #include <iostream> static void translate_declaration(llvm::Module *module, struct tgsi_full_declaration *decl, struct tgsi_full_declaration *fd) { /* i think this is going to be a noop */ } static void translate_immediate(llvm::Module *module, struct tgsi_full_immediate *imm) { } static void translate_instruction(llvm::Module *module, struct tgsi_full_instruction *inst, struct tgsi_full_instruction *fi) { switch (inst->Instruction.Opcode) { case TGSI_OPCODE_ARL: break; case TGSI_OPCODE_MOV: break; case TGSI_OPCODE_LIT: break; case TGSI_OPCODE_RCP: break; case TGSI_OPCODE_RSQ: break; case TGSI_OPCODE_EXP: break; case TGSI_OPCODE_LOG: break; case TGSI_OPCODE_MUL: break; case TGSI_OPCODE_ADD: break; case TGSI_OPCODE_DP3: break; case TGSI_OPCODE_DP4: break; case TGSI_OPCODE_DST: break; case TGSI_OPCODE_MIN: break; case TGSI_OPCODE_MAX: break; case TGSI_OPCODE_SLT: break; case TGSI_OPCODE_SGE: break; case TGSI_OPCODE_MAD: break; case TGSI_OPCODE_SUB: break; case TGSI_OPCODE_LERP: break; case TGSI_OPCODE_CND: break; case TGSI_OPCODE_CND0: break; case TGSI_OPCODE_DOT2ADD: break; case TGSI_OPCODE_INDEX: break; case TGSI_OPCODE_NEGATE: break; case TGSI_OPCODE_FRAC: break; case TGSI_OPCODE_CLAMP: break; case TGSI_OPCODE_FLOOR: break; case TGSI_OPCODE_ROUND: break; case TGSI_OPCODE_EXPBASE2: break; case TGSI_OPCODE_LOGBASE2: break; case TGSI_OPCODE_POWER: break; case TGSI_OPCODE_CROSSPRODUCT: break; case TGSI_OPCODE_MULTIPLYMATRIX: break; case TGSI_OPCODE_ABS: break; case TGSI_OPCODE_RCC: break; case TGSI_OPCODE_DPH: break; case TGSI_OPCODE_COS: break; case TGSI_OPCODE_DDX: break; case TGSI_OPCODE_DDY: break; case TGSI_OPCODE_KILP: break; case TGSI_OPCODE_PK2H: break; case TGSI_OPCODE_PK2US: break; case TGSI_OPCODE_PK4B: break; case TGSI_OPCODE_PK4UB: break; case TGSI_OPCODE_RFL: break; case TGSI_OPCODE_SEQ: break; case TGSI_OPCODE_SFL: break; case TGSI_OPCODE_SGT: break; case TGSI_OPCODE_SIN: break; case TGSI_OPCODE_SLE: break; case TGSI_OPCODE_SNE: break; case TGSI_OPCODE_STR: break; case TGSI_OPCODE_TEX: break; case TGSI_OPCODE_TXD: break; case TGSI_OPCODE_TXP: break; case TGSI_OPCODE_UP2H: break; case TGSI_OPCODE_UP2US: break; case TGSI_OPCODE_UP4B: break; case TGSI_OPCODE_UP4UB: break; case TGSI_OPCODE_X2D: break; case TGSI_OPCODE_ARA: break; case TGSI_OPCODE_ARR: break; case TGSI_OPCODE_BRA: break; case TGSI_OPCODE_CAL: break; case TGSI_OPCODE_RET: break; case TGSI_OPCODE_SSG: break; case TGSI_OPCODE_CMP: break; case TGSI_OPCODE_SCS: break; case TGSI_OPCODE_TXB: break; case TGSI_OPCODE_NRM: break; case TGSI_OPCODE_DIV: break; case TGSI_OPCODE_DP2: break; case TGSI_OPCODE_TXL: break; case TGSI_OPCODE_BRK: break; case TGSI_OPCODE_IF: break; case TGSI_OPCODE_LOOP: break; case TGSI_OPCODE_REP: break; case TGSI_OPCODE_ELSE: break; case TGSI_OPCODE_ENDIF: break; case TGSI_OPCODE_ENDLOOP: break; case TGSI_OPCODE_ENDREP: break; case TGSI_OPCODE_PUSHA: break; case TGSI_OPCODE_POPA: break; case TGSI_OPCODE_CEIL: break; case TGSI_OPCODE_I2F: break; case TGSI_OPCODE_NOT: break; case TGSI_OPCODE_TRUNC: break; case TGSI_OPCODE_SHL: break; case TGSI_OPCODE_SHR: break; case TGSI_OPCODE_AND: break; case TGSI_OPCODE_OR: break; case TGSI_OPCODE_MOD: break; case TGSI_OPCODE_XOR: break; case TGSI_OPCODE_SAD: break; case TGSI_OPCODE_TXF: break; case TGSI_OPCODE_TXQ: break; case TGSI_OPCODE_CONT: break; case TGSI_OPCODE_EMIT: break; case TGSI_OPCODE_ENDPRIM: break; case TGSI_OPCODE_BGNLOOP2: break; case TGSI_OPCODE_BGNSUB: break; case TGSI_OPCODE_ENDLOOP2: break; case TGSI_OPCODE_ENDSUB: break; case TGSI_OPCODE_NOISE1: break; case TGSI_OPCODE_NOISE2: break; case TGSI_OPCODE_NOISE3: break; case TGSI_OPCODE_NOISE4: break; case TGSI_OPCODE_NOP: break; case TGSI_OPCODE_TEXBEM: break; case TGSI_OPCODE_TEXBEML: break; case TGSI_OPCODE_TEXREG2AR: break; case TGSI_OPCODE_TEXM3X2PAD: break; case TGSI_OPCODE_TEXM3X2TEX: break; case TGSI_OPCODE_TEXM3X3PAD: break; case TGSI_OPCODE_TEXM3X3TEX: break; case TGSI_OPCODE_TEXM3X3SPEC: break; case TGSI_OPCODE_TEXM3X3VSPEC: break; case TGSI_OPCODE_TEXREG2GB: break; case TGSI_OPCODE_TEXREG2RGB: break; case TGSI_OPCODE_TEXDP3TEX: break; case TGSI_OPCODE_TEXDP3: break; case TGSI_OPCODE_TEXM3X3: break; case TGSI_OPCODE_TEXM3X2DEPTH: break; case TGSI_OPCODE_TEXDEPTH: break; case TGSI_OPCODE_BEM: break; case TGSI_OPCODE_M4X3: break; case TGSI_OPCODE_M3X4: break; case TGSI_OPCODE_M3X3: break; case TGSI_OPCODE_M3X2: break; case TGSI_OPCODE_NRM4: break; case TGSI_OPCODE_CALLNZ: break; case TGSI_OPCODE_IFC: break; case TGSI_OPCODE_BREAKC: break; case TGSI_OPCODE_KIL: break; case TGSI_OPCODE_END: break; default: fprintf(stderr, "ERROR: Unknown opcode %d\n", inst->Instruction.Opcode); assert(0); break; } switch( inst->Instruction.Saturate ) { case TGSI_SAT_NONE: break; case TGSI_SAT_ZERO_ONE: /*TXT( "_SAT" );*/ break; case TGSI_SAT_MINUS_PLUS_ONE: /*TXT( "_SAT[-1,1]" );*/ break; default: assert( 0 ); } } static llvm::Module * tgsi_to_llvm(const struct tgsi_token *tokens) { llvm::Module *mod = new llvm::Module("tgsi"); struct tgsi_parse_context parse; struct tgsi_full_instruction fi; struct tgsi_full_declaration fd; tgsi_parse_init(&parse, tokens); //parse.FullHeader.Processor.Processor //parse.FullVersion.Version.MajorVersion //parse.FullVersion.Version.MinorVersion //parse.FullHeader.Header.HeaderSize //parse.FullHeader.Header.BodySize //parse.FullHeader.Processor.Processor fi = tgsi_default_full_instruction(); fd = tgsi_default_full_declaration(); while(!tgsi_parse_end_of_tokens(&parse)) { tgsi_parse_token(&parse); fprintf(stderr, "Translating %d\n", parse.FullToken.Token.Type); switch (parse.FullToken.Token.Type) { case TGSI_TOKEN_TYPE_DECLARATION: translate_declaration(mod, &parse.FullToken.FullDeclaration, &fd); break; case TGSI_TOKEN_TYPE_IMMEDIATE: translate_immediate(mod, &parse.FullToken.FullImmediate); break; case TGSI_TOKEN_TYPE_INSTRUCTION: translate_instruction(mod, &parse.FullToken.FullInstruction, &fi); break; default: assert(0); } } //TXT("\ntgsi-dump end -------------------\n"); tgsi_parse_free(&parse); return mod; } struct ga_llvm_prog * ga_llvm_from_tgsi(const struct tgsi_token *tokens) { std::cout << "Creating llvm " <<std::endl; struct ga_llvm_prog *ga_llvm = (struct ga_llvm_prog *)malloc(sizeof(struct ga_llvm_prog)); llvm::Module *mod = tgsi_to_llvm(tokens); llvm::ExistingModuleProvider *mp = new llvm::ExistingModuleProvider(mod); //llvm::ExecutionEngine *ee = // llvm::ExecutionEngine::create(mp, false); ga_llvm->module = mod; ga_llvm->engine = 0;//ee; fprintf(stderr, "DUMPX \n"); //tgsi_dump(tokens, TGSI_DUMP_VERBOSE); tgsi_dump(tokens, 0); fprintf(stderr, "DUMPEND \n"); return ga_llvm; } void ga_llvm_prog_delete(struct ga_llvm_prog *prog) { llvm::Module *mod = static_cast<llvm::Module*>(prog->module); delete mod; prog->module = 0; prog->engine = 0; free(prog); } int ga_llvm_prog_exec(struct ga_llvm_prog *prog) { //std::cout << "START "<<std::endl; llvm::Module *mod = static_cast<llvm::Module*>(prog->module); llvm::Function *func = mod->getFunction("main"); llvm::ExecutionEngine *ee = static_cast<llvm::ExecutionEngine*>(prog->engine); std::vector<llvm::GenericValue> args(0); //args[0] = GenericValue(&st); //std::cout << "Mod is "<<*mod; //std::cout << "\n\nRunning llvm: " << std::endl; if (func) { std::cout << "Func is "<<func; llvm::GenericValue gv = ee->runFunction(func, args); } //delete ee; //delete mp; return 0; } <|endoftext|>
<commit_before>/*************************************************************************** * * * Copyright (C) 2007-2015 by frePPLe bv * * * * This library 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 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 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/>. * * * ***************************************************************************/ #define FREPPLE_CORE #include "frepple/model.h" namespace frepple { void Resource::updateProblems() { // Delete existing problems for this resource Problem::clearProblems(*this, true, false); // Problem detection disabled on this resource if (!getDetectProblems()) return; // Loop through the loadplans Date excessProblemStart; Date shortageProblemStart; bool excessProblem = false; bool shortageProblem = false; double curMax(0.0); double shortageQty(0.0); double curMin(0.0); double excessQty(0.0); for (auto iter = loadplans.begin(); iter != loadplans.end();) { // Process changes in the maximum or minimum targets if (iter->getEventType() == 4) curMax = iter->getMax(); else if (iter->getEventType() == 3) curMin = iter->getMin(); // Only consider the last loadplan for a certain date const TimeLine<LoadPlan>::Event *f = &*(iter++); if (iter != loadplans.end() && iter->getDate() == f->getDate()) continue; // Check against minimum target double delta = f->getOnhand() - curMin; if (delta < -ROUNDING_ERROR) { if (!shortageProblem) { shortageProblemStart = f->getDate(); shortageQty = delta; shortageProblem = true; } else if (delta < shortageQty) // New shortage qty shortageQty = delta; } else { if (shortageProblem) { // New problem now ends if (f->getDate() != shortageProblemStart) new ProblemCapacityUnderload( this, DateRange(shortageProblemStart, f->getDate()), -shortageQty); shortageProblem = false; } } // Note that theoretically we can have a minimum and a maximum problem for // the same moment in time. // Check against maximum target delta = f->getOnhand() - curMax; if (delta > ROUNDING_ERROR) { if (!excessProblem) { excessProblemStart = f->getDate(); excessQty = delta; excessProblem = true; } else if (delta > excessQty) excessQty = delta; } else { if (excessProblem) { // New problem now ends if (f->getDate() != excessProblemStart) new ProblemCapacityOverload(this, excessProblemStart, f->getDate(), excessQty); excessProblem = false; } } } // End of for-loop through the loadplans // The excess lasts till the end of the horizon... if (excessProblem) new ProblemCapacityOverload(this, excessProblemStart, Date::infiniteFuture, excessQty); // The shortage lasts till the end of the horizon... if (shortageProblem) new ProblemCapacityUnderload( this, DateRange(shortageProblemStart, Date::infiniteFuture), -shortageQty); } void ResourceBuckets::updateProblems() { // Delete existing problems for this resource Problem::clearProblems(*this, true, false); // Problem detection disabled on this resource if (!getDetectProblems()) return; // Loop over all events Date startdate = Date::infinitePast; double load = 0.0; for (auto iter = loadplans.begin(); iter != loadplans.end(); iter++) { if (iter->getEventType() != 2) load = iter->getOnhand(); else { // Evaluate previous bucket if (load < -ROUNDING_ERROR) new ProblemCapacityOverload(this, startdate, iter->getDate(), -load); // Reset evaluation for the new bucket startdate = iter->getDate(); load = 0.0; } } // Evaluate the final bucket if (load < -ROUNDING_ERROR) new ProblemCapacityOverload(this, startdate, Date::infiniteFuture, -load); } string ProblemCapacityUnderload::getDescription() const { ostringstream ch; ch << "Resource '" << getResource() << "' has excess capacity of " << qty; return ch.str(); } string ProblemCapacityOverload::getDescription() const { ostringstream ch; ch << "Resource '" << getResource() << "' has capacity shortage of " << qty; return ch.str(); } } // namespace frepple <commit_msg>unconstrained resources shouldn't flag overload problems<commit_after>/*************************************************************************** * * * Copyright (C) 2007-2015 by frePPLe bv * * * * This library 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 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 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/>. * * * ***************************************************************************/ #define FREPPLE_CORE #include "frepple/model.h" namespace frepple { void Resource::updateProblems() { // Delete existing problems for this resource Problem::clearProblems(*this, true, false); // Problem detection disabled on this resource if (!getDetectProblems() || !getConstrained()) return; // Loop through the loadplans Date excessProblemStart; Date shortageProblemStart; bool excessProblem = false; bool shortageProblem = false; double curMax(0.0); double shortageQty(0.0); double curMin(0.0); double excessQty(0.0); for (auto iter = loadplans.begin(); iter != loadplans.end();) { // Process changes in the maximum or minimum targets if (iter->getEventType() == 4) curMax = iter->getMax(); else if (iter->getEventType() == 3) curMin = iter->getMin(); // Only consider the last loadplan for a certain date const TimeLine<LoadPlan>::Event *f = &*(iter++); if (iter != loadplans.end() && iter->getDate() == f->getDate()) continue; // Check against minimum target double delta = f->getOnhand() - curMin; if (delta < -ROUNDING_ERROR) { if (!shortageProblem) { shortageProblemStart = f->getDate(); shortageQty = delta; shortageProblem = true; } else if (delta < shortageQty) // New shortage qty shortageQty = delta; } else { if (shortageProblem) { // New problem now ends if (f->getDate() != shortageProblemStart) new ProblemCapacityUnderload( this, DateRange(shortageProblemStart, f->getDate()), -shortageQty); shortageProblem = false; } } // Note that theoretically we can have a minimum and a maximum problem for // the same moment in time. // Check against maximum target delta = f->getOnhand() - curMax; if (delta > ROUNDING_ERROR) { if (!excessProblem) { excessProblemStart = f->getDate(); excessQty = delta; excessProblem = true; } else if (delta > excessQty) excessQty = delta; } else { if (excessProblem) { // New problem now ends if (f->getDate() != excessProblemStart) new ProblemCapacityOverload(this, excessProblemStart, f->getDate(), excessQty); excessProblem = false; } } } // End of for-loop through the loadplans // The excess lasts till the end of the horizon... if (excessProblem) new ProblemCapacityOverload(this, excessProblemStart, Date::infiniteFuture, excessQty); // The shortage lasts till the end of the horizon... if (shortageProblem) new ProblemCapacityUnderload( this, DateRange(shortageProblemStart, Date::infiniteFuture), -shortageQty); } void ResourceBuckets::updateProblems() { // Delete existing problems for this resource Problem::clearProblems(*this, true, false); // Problem detection disabled on this resource if (!getDetectProblems() || !getConstrained()) return; // Loop over all events Date startdate = Date::infinitePast; double load = 0.0; for (auto iter = loadplans.begin(); iter != loadplans.end(); iter++) { if (iter->getEventType() != 2) load = iter->getOnhand(); else { // Evaluate previous bucket if (load < -ROUNDING_ERROR) new ProblemCapacityOverload(this, startdate, iter->getDate(), -load); // Reset evaluation for the new bucket startdate = iter->getDate(); load = 0.0; } } // Evaluate the final bucket if (load < -ROUNDING_ERROR) new ProblemCapacityOverload(this, startdate, Date::infiniteFuture, -load); } string ProblemCapacityUnderload::getDescription() const { ostringstream ch; ch << "Resource '" << getResource() << "' has excess capacity of " << qty; return ch.str(); } string ProblemCapacityOverload::getDescription() const { ostringstream ch; ch << "Resource '" << getResource() << "' has capacity shortage of " << qty; return ch.str(); } } // namespace frepple <|endoftext|>
<commit_before>// // Copyright © 2020 Arm Ltd. All rights reserved. // SPDX-License-Identifier: MIT // #pragma once #include <ostream> #include <cmath> #include <stdint.h> namespace armnn { class BFloat16 { public: BFloat16() : m_Value(0) {} BFloat16(const BFloat16& v) = default; explicit BFloat16(uint16_t v) : m_Value(v) {} explicit BFloat16(float v) { m_Value = Float32ToBFloat16(v).Val(); } operator float() const { return ToFloat32(); } BFloat16& operator=(const BFloat16& other) = default; BFloat16& operator=(float v) { m_Value = Float32ToBFloat16(v).Val(); return *this; } bool operator==(const BFloat16& r) const { return m_Value == r.Val(); } static BFloat16 Float32ToBFloat16(const float v) { if (std::isnan(v)) { return Nan(); } else { // Round value to the nearest even // Float32 // S EEEEEEEE MMMMMMLRMMMMMMMMMMMMMMM // BFloat16 // S EEEEEEEE MMMMMML // LSB (L): Least significat bit of BFloat16 (last bit of the Mantissa of BFloat16) // R: Rounding bit // LSB = 0, R = 0 -> round down // LSB = 1, R = 0 -> round down // LSB = 0, R = 1, all the rest = 0 -> round down // LSB = 1, R = 1 -> round up // LSB = 0, R = 1 -> round up const uint32_t* u32 = reinterpret_cast<const uint32_t*>(&v); uint16_t u16 = static_cast<uint16_t>(*u32 >> 16u); // Mark the LSB const uint16_t lsb = u16 & 0x0001; // Mark the error to be truncate (the rest of 16 bits of FP32) const uint16_t error = static_cast<uint16_t>((*u32 & 0x0000FFFF)); if ((error > 0x8000 || (error == 0x8000 && lsb == 1))) { u16++; } BFloat16 b(u16); return b; } } float ToFloat32() const { const uint32_t u32 = static_cast<uint32_t>(m_Value << 16u); const float* f32 = reinterpret_cast<const float*>(&u32); return *f32; } uint16_t Val() const { return m_Value; } static BFloat16 Max() { uint16_t max = 0x7F7F; return BFloat16(max); } static BFloat16 Nan() { uint16_t nan = 0x7FC0; return BFloat16(nan); } static BFloat16 Inf() { uint16_t infVal = 0x7F80; return BFloat16(infVal); } private: uint16_t m_Value; }; inline std::ostream& operator<<(std::ostream& os, const BFloat16& b) { os << b.ToFloat32() << "(0x" << std::hex << b.Val() << ")"; return os; } } //namespace armnn <commit_msg>Fix undefined reinterpret_cast in BFloat16.hpp<commit_after>// // Copyright © 2020 Arm Ltd. All rights reserved. // SPDX-License-Identifier: MIT // #pragma once #include <ostream> #include <cmath> #include <cstring> #include <stdint.h> namespace armnn { class BFloat16 { public: BFloat16() : m_Value(0) {} BFloat16(const BFloat16& v) = default; explicit BFloat16(uint16_t v) : m_Value(v) {} explicit BFloat16(float v) { m_Value = Float32ToBFloat16(v).Val(); } operator float() const { return ToFloat32(); } BFloat16& operator=(const BFloat16& other) = default; BFloat16& operator=(float v) { m_Value = Float32ToBFloat16(v).Val(); return *this; } bool operator==(const BFloat16& r) const { return m_Value == r.Val(); } static BFloat16 Float32ToBFloat16(const float v) { if (std::isnan(v)) { return Nan(); } else { // Round value to the nearest even // Float32 // S EEEEEEEE MMMMMMLRMMMMMMMMMMMMMMM // BFloat16 // S EEEEEEEE MMMMMML // LSB (L): Least significat bit of BFloat16 (last bit of the Mantissa of BFloat16) // R: Rounding bit // LSB = 0, R = 0 -> round down // LSB = 1, R = 0 -> round down // LSB = 0, R = 1, all the rest = 0 -> round down // LSB = 1, R = 1 -> round up // LSB = 0, R = 1 -> round up const uint32_t* u32 = reinterpret_cast<const uint32_t*>(&v); uint16_t u16 = static_cast<uint16_t>(*u32 >> 16u); // Mark the LSB const uint16_t lsb = u16 & 0x0001; // Mark the error to be truncate (the rest of 16 bits of FP32) const uint16_t error = static_cast<uint16_t>((*u32 & 0x0000FFFF)); if ((error > 0x8000 || (error == 0x8000 && lsb == 1))) { u16++; } BFloat16 b(u16); return b; } } float ToFloat32() const { const uint32_t u32 = static_cast<uint32_t>(m_Value << 16u); float f32; static_assert(sizeof u32 == sizeof f32, ""); std::memcpy(&f32, &u32, sizeof u32); return f32; } uint16_t Val() const { return m_Value; } static BFloat16 Max() { uint16_t max = 0x7F7F; return BFloat16(max); } static BFloat16 Nan() { uint16_t nan = 0x7FC0; return BFloat16(nan); } static BFloat16 Inf() { uint16_t infVal = 0x7F80; return BFloat16(infVal); } private: uint16_t m_Value; }; inline std::ostream& operator<<(std::ostream& os, const BFloat16& b) { os << b.ToFloat32() << "(0x" << std::hex << b.Val() << ")"; return os; } } //namespace armnn <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: xmlelementwrapper_xmlsecimpl.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: rt $ $Date: 2005-09-09 17:28:05 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _XMLELEMENTWRAPPER_XMLSECIMPL_HXX #define _XMLELEMENTWRAPPER_XMLSECIMPL_HXX #ifndef _COM_SUN_STAR_XML_WRAPPER_XXMLELEMENTWRAPPER_HPP_ #include <com/sun/star/xml/wrapper/XXMLElementWrapper.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XUNOTUNNEL_HPP_ #include <com/sun/star/lang/XUnoTunnel.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_ #include <com/sun/star/lang/XInitialization.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_ #include <com/sun/star/lang/XServiceInfo.hpp> #endif #ifndef _CPPUHELPER_IMPLBASE3_HXX_ #include <cppuhelper/implbase3.hxx> #endif #include <libxml/tree.h> class XMLElementWrapper_XmlSecImpl : public cppu::WeakImplHelper3 < com::sun::star::xml::wrapper::XXMLElementWrapper, com::sun::star::lang::XUnoTunnel, com::sun::star::lang::XServiceInfo > /****** XMLElementWrapper_XmlSecImpl.hxx/CLASS XMLElementWrapper_XmlSecImpl *** * * NAME * XMLElementWrapper_XmlSecImpl -- Class to wrap a libxml2 node * * FUNCTION * Used as a wrapper class to transfer a libxml2 node structure * between different UNO components. * * HISTORY * 05.01.2004 - Interface supported: XXMLElementWrapper, XUnoTunnel * XServiceInfo * * AUTHOR * Michael Mi * Email: [email protected] ******************************************************************************/ { private: /* the libxml2 node wrapped by this object */ xmlNodePtr m_pElement; public: explicit XMLElementWrapper_XmlSecImpl(const xmlNodePtr pNode); virtual ~XMLElementWrapper_XmlSecImpl() {}; /* XXMLElementWrapper */ /* com::sun::star::lang::XUnoTunnel */ virtual sal_Int64 SAL_CALL getSomething( const com::sun::star::uno::Sequence< sal_Int8 >& aIdentifier ) throw (com::sun::star::uno::RuntimeException); static com::sun::star::uno::Sequence < sal_Int8 > getUnoTunnelImplementationId( void ) throw(com::sun::star::uno::RuntimeException); /* com::sun::star::lang::XServiceInfo */ virtual rtl::OUString SAL_CALL getImplementationName( ) throw (com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL supportsService( const rtl::OUString& ServiceName ) throw (com::sun::star::uno::RuntimeException); virtual com::sun::star::uno::Sequence< rtl::OUString > SAL_CALL getSupportedServiceNames( ) throw (com::sun::star::uno::RuntimeException); public: xmlNodePtr getNativeElement( ) const; void setNativeElement(const xmlNodePtr pNode); }; rtl::OUString XMLElementWrapper_XmlSecImpl_getImplementationName() throw ( com::sun::star::uno::RuntimeException ); sal_Bool SAL_CALL XMLElementWrapper_XmlSecImpl_supportsService( const rtl::OUString& ServiceName ) throw ( com::sun::star::uno::RuntimeException ); com::sun::star::uno::Sequence< rtl::OUString > SAL_CALL XMLElementWrapper_XmlSecImpl_getSupportedServiceNames( ) throw ( com::sun::star::uno::RuntimeException ); com::sun::star::uno::Reference< com::sun::star::uno::XInterface > SAL_CALL XMLElementWrapper_XmlSecImpl_createInstance( const com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory > & rSMgr) throw ( com::sun::star::uno::Exception ); #endif <commit_msg>INTEGRATION: CWS changefileheader (1.2.190); FILE MERGED 2008/04/01 16:11:02 thb 1.2.190.3: #i85898# Stripping all external header guards 2008/04/01 13:06:24 thb 1.2.190.2: #i85898# Stripping all external header guards 2008/03/31 16:31:03 rt 1.2.190.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: xmlelementwrapper_xmlsecimpl.hxx,v $ * $Revision: 1.3 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef _XMLELEMENTWRAPPER_XMLSECIMPL_HXX #define _XMLELEMENTWRAPPER_XMLSECIMPL_HXX #include <com/sun/star/xml/wrapper/XXMLElementWrapper.hpp> #include <com/sun/star/lang/XUnoTunnel.hpp> #include <com/sun/star/lang/XInitialization.hpp> #include <com/sun/star/lang/XServiceInfo.hpp> #include <cppuhelper/implbase3.hxx> #include <libxml/tree.h> class XMLElementWrapper_XmlSecImpl : public cppu::WeakImplHelper3 < com::sun::star::xml::wrapper::XXMLElementWrapper, com::sun::star::lang::XUnoTunnel, com::sun::star::lang::XServiceInfo > /****** XMLElementWrapper_XmlSecImpl.hxx/CLASS XMLElementWrapper_XmlSecImpl *** * * NAME * XMLElementWrapper_XmlSecImpl -- Class to wrap a libxml2 node * * FUNCTION * Used as a wrapper class to transfer a libxml2 node structure * between different UNO components. * * HISTORY * 05.01.2004 - Interface supported: XXMLElementWrapper, XUnoTunnel * XServiceInfo * * AUTHOR * Michael Mi * Email: [email protected] ******************************************************************************/ { private: /* the libxml2 node wrapped by this object */ xmlNodePtr m_pElement; public: explicit XMLElementWrapper_XmlSecImpl(const xmlNodePtr pNode); virtual ~XMLElementWrapper_XmlSecImpl() {}; /* XXMLElementWrapper */ /* com::sun::star::lang::XUnoTunnel */ virtual sal_Int64 SAL_CALL getSomething( const com::sun::star::uno::Sequence< sal_Int8 >& aIdentifier ) throw (com::sun::star::uno::RuntimeException); static com::sun::star::uno::Sequence < sal_Int8 > getUnoTunnelImplementationId( void ) throw(com::sun::star::uno::RuntimeException); /* com::sun::star::lang::XServiceInfo */ virtual rtl::OUString SAL_CALL getImplementationName( ) throw (com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL supportsService( const rtl::OUString& ServiceName ) throw (com::sun::star::uno::RuntimeException); virtual com::sun::star::uno::Sequence< rtl::OUString > SAL_CALL getSupportedServiceNames( ) throw (com::sun::star::uno::RuntimeException); public: xmlNodePtr getNativeElement( ) const; void setNativeElement(const xmlNodePtr pNode); }; rtl::OUString XMLElementWrapper_XmlSecImpl_getImplementationName() throw ( com::sun::star::uno::RuntimeException ); sal_Bool SAL_CALL XMLElementWrapper_XmlSecImpl_supportsService( const rtl::OUString& ServiceName ) throw ( com::sun::star::uno::RuntimeException ); com::sun::star::uno::Sequence< rtl::OUString > SAL_CALL XMLElementWrapper_XmlSecImpl_getSupportedServiceNames( ) throw ( com::sun::star::uno::RuntimeException ); com::sun::star::uno::Reference< com::sun::star::uno::XInterface > SAL_CALL XMLElementWrapper_XmlSecImpl_createInstance( const com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory > & rSMgr) throw ( com::sun::star::uno::Exception ); #endif <|endoftext|>
<commit_before>#include <miniMAT/util/PrintResult.hpp> #include <iostream> #include <iomanip> namespace miniMAT { namespace util { void PrintResult(std::string varname, Matrix m, bool suppressed) { if (!suppressed) { // Print a row at a time (default precision is 4) std::cout << varname << " =" << std::endl << std::endl; for (int i = 0; i < m.rows(); i++) { std::cout << " "; for (int j = 0; j < m.cols(); j++) std::cout << std::fixed << std::showpoint << std::setprecision(4) << m(i,j) << " "; std::cout << std::endl; } std::cout << std::endl; } } } }<commit_msg>Fix formatting for matrix output<commit_after>#include <miniMAT/util/PrintResult.hpp> #include <iostream> #include <iomanip> #include <cmath> namespace miniMAT { namespace util { void PrintResult(std::string varname, Matrix m, bool suppressed) { if (!suppressed) { using namespace std; int maxdigits = log10(m.maxCoeff()) + 1; // Get number of digits of max element int precision = 4; int space = 1, dot = 1; // Print a row at a time (default precision is 4) cout << varname << " =" << endl << endl; for (int i = 0; i < m.rows(); i++) { cout << " "; for (int j = 0; j < m.cols(); j++) cout << right << fixed << showpoint << setprecision(precision) << setw(maxdigits + precision + dot + space) << m(i,j); cout << endl; } cout << endl; } } } }<|endoftext|>
<commit_before>#include "xchainer/context.h" #include <cstdlib> #include <future> #include <gtest/gtest.h> #include <nonstd/optional.hpp> #include "xchainer/backend.h" #include "xchainer/device.h" #include "xchainer/native/native_backend.h" #include "xchainer/native/native_device.h" #include "xchainer/testing/threading.h" namespace xchainer { namespace { TEST(ContextTest, Ctor) { Context(); // no throw } TEST(ContextTest, GetBackend) { Context ctx; Backend& backend = ctx.GetBackend("native"); EXPECT_EQ(&backend, &ctx.GetBackend("native")); } TEST(ContextTest, NativeBackend) { Context ctx; native::NativeBackend& backend = ctx.GetNativeBackend(); EXPECT_EQ(&ctx.GetBackend("native"), &backend); } TEST(ContextTest, GetBackendThreadSafe) { static constexpr int kRepeat = 100; static constexpr size_t kThreadCount = 1024; xchainer::testing::CheckThreadSafety( kRepeat, kThreadCount, [](size_t /*repeat*/) { return std::make_unique<Context>(); }, [](size_t /*thread_index*/, const std::unique_ptr<Context>& ctx) { Backend& backend = ctx->GetBackend("native"); return &backend; }, [this](const std::vector<Backend*>& results) { for (Backend* backend : results) { ASSERT_EQ("native", backend->GetName()); ASSERT_EQ(backend, results.front()); } }); } TEST(ContextTest, BackendNotFound) { Context ctx; EXPECT_THROW(ctx.GetBackend("something_that_does_not_exist"), BackendError); } TEST(ContextTest, GetDevice) { Context ctx; Device& device = ctx.GetDevice({"native", 0}); EXPECT_EQ(&device, &ctx.GetDevice({"native:0"})); } TEST(ContextTest, GetDeviceThreadSafe) { static constexpr int kRepeat = 100; static constexpr int kDeviceCount = 4; static constexpr size_t kThreadCountPerDevice = 32; static constexpr size_t kThreadCount = kDeviceCount * kThreadCountPerDevice; xchainer::testing::CheckThreadSafety( kRepeat, kThreadCount, [](size_t /*repeat*/) { return std::make_unique<Context>(); }, [](size_t thread_index, const std::unique_ptr<Context>& ctx) { int device_index = thread_index / kThreadCountPerDevice; Device& device = ctx->GetDevice({"native", device_index}); return &device; }, [this](const std::vector<Device*>& results) { // Check device pointers are identical within each set of threads corresponding to one device for (int device_index = 0; device_index < kDeviceCount; ++device_index) { auto it_first = std::next(results.begin(), device_index * kThreadCountPerDevice); auto it_last = std::next(results.begin(), (device_index + 1) * kThreadCountPerDevice); Device* ref_device = *it_first; // Check the device index ASSERT_EQ(device_index, ref_device->index()); for (auto it = it_first; it != it_last; ++it) { ASSERT_EQ(ref_device, *it); } } }); } TEST(ContextTest, DefaultContext) { SetGlobalDefaultContext(nullptr); SetDefaultContext(nullptr); ASSERT_THROW(GetDefaultContext(), XchainerError); Context ctx; SetGlobalDefaultContext(nullptr); SetDefaultContext(&ctx); ASSERT_EQ(&ctx, &GetDefaultContext()); Context global_ctx; SetGlobalDefaultContext(&global_ctx); SetDefaultContext(nullptr); ASSERT_EQ(&global_ctx, &GetDefaultContext()); SetGlobalDefaultContext(&global_ctx); SetDefaultContext(&ctx); ASSERT_EQ(&ctx, &GetDefaultContext()); } TEST(ContextTest, GlobalDefaultContext) { SetGlobalDefaultContext(nullptr); ASSERT_THROW(GetGlobalDefaultContext(), XchainerError); Context ctx; SetGlobalDefaultContext(&ctx); ASSERT_EQ(&ctx, &GetGlobalDefaultContext()); } TEST(ContextTest, ThreadLocal) { Context ctx; SetDefaultContext(&ctx); Context ctx2; auto future = std::async(std::launch::async, [&ctx2] { SetDefaultContext(&ctx2); return &GetDefaultContext(); }); ASSERT_NE(&GetDefaultContext(), future.get()); } TEST(ContextTest, ContextScopeCtor) { SetGlobalDefaultContext(nullptr); SetDefaultContext(nullptr); Context ctx1; { // ContextScope should work even if default context is not set ContextScope scope(ctx1); EXPECT_EQ(&ctx1, &GetDefaultContext()); } ASSERT_THROW(GetDefaultContext(), XchainerError); SetDefaultContext(&ctx1); { Context ctx2; ContextScope scope(ctx2); EXPECT_EQ(&ctx2, &GetDefaultContext()); } ASSERT_EQ(&ctx1, &GetDefaultContext()); { ContextScope scope; EXPECT_EQ(&ctx1, &GetDefaultContext()); Context ctx2; SetDefaultContext(&ctx2); } ASSERT_EQ(&ctx1, &GetDefaultContext()); Context ctx2; { ContextScope scope(ctx2); scope.Exit(); EXPECT_EQ(&ctx1, &GetDefaultContext()); SetDefaultContext(&ctx2); // not recovered here because the scope has already existed } ASSERT_EQ(&ctx2, &GetDefaultContext()); } TEST(ContextTest, ContextScopeResetDevice) { SetGlobalDefaultContext(nullptr); SetDefaultContext(nullptr); Context ctx1; Context ctx2; { ContextScope ctx_scope1{ctx1}; Device& device1 = ctx1.GetDevice({"native", 0}); DeviceScope dev_scope1{device1}; { ContextScope ctx_scope2{ctx2}; ASSERT_NE(&device1, &GetDefaultDevice()); Device& device2 = ctx2.GetDevice({"native", 0}); SetDefaultDevice(&device2); } EXPECT_EQ(&device1, &GetDefaultDevice()); } } TEST(ContextTest, UserDefinedBackend) { ::setenv("XCHAINER_PATH", XCHAINER_TEST_DIR "/context_testdata", 1); Context ctx; Backend& backend0 = ctx.GetBackend("backend0"); EXPECT_EQ("backend0", backend0.GetName()); Backend& backend0_2 = ctx.GetBackend("backend0"); EXPECT_EQ(&backend0, &backend0_2); Backend& backend1 = ctx.GetBackend("backend1"); EXPECT_EQ("backend1", backend1.GetName()); Device& device0 = ctx.GetDevice(std::string("backend0:0")); EXPECT_EQ(&backend0, &device0.backend()); } TEST(ContextTest, GetBackendOnDefaultContext) { // xchainer::GetBackend Context ctx; SetDefaultContext(&ctx); Backend& backend = GetBackend("native"); EXPECT_EQ(&ctx, &backend.context()); EXPECT_EQ("native", backend.GetName()); } TEST(ContextTest, GetNativeBackendOnDefaultContext) { // xchainer::GetNativeBackend Context ctx; SetDefaultContext(&ctx); native::NativeBackend& backend = GetNativeBackend(); EXPECT_EQ(&ctx.GetNativeBackend(), &backend); } TEST(ContextTest, GetDeviceOnDefaultContext) { // xchainer::GetDevice Context ctx; SetDefaultContext(&ctx); Device& device = GetDevice({"native:0"}); EXPECT_EQ(&ctx, &device.backend().context()); EXPECT_EQ("native:0", device.name()); } } // namespace } // namespace xchainer <commit_msg>int -> size_t<commit_after>#include "xchainer/context.h" #include <cstdlib> #include <future> #include <gtest/gtest.h> #include <nonstd/optional.hpp> #include "xchainer/backend.h" #include "xchainer/device.h" #include "xchainer/native/native_backend.h" #include "xchainer/native/native_device.h" #include "xchainer/testing/threading.h" namespace xchainer { namespace { TEST(ContextTest, Ctor) { Context(); // no throw } TEST(ContextTest, GetBackend) { Context ctx; Backend& backend = ctx.GetBackend("native"); EXPECT_EQ(&backend, &ctx.GetBackend("native")); } TEST(ContextTest, NativeBackend) { Context ctx; native::NativeBackend& backend = ctx.GetNativeBackend(); EXPECT_EQ(&ctx.GetBackend("native"), &backend); } TEST(ContextTest, GetBackendThreadSafe) { static constexpr size_t kRepeat = 100; static constexpr size_t kThreadCount = 1024; xchainer::testing::CheckThreadSafety( kRepeat, kThreadCount, [](size_t /*repeat*/) { return std::make_unique<Context>(); }, [](size_t /*thread_index*/, const std::unique_ptr<Context>& ctx) { Backend& backend = ctx->GetBackend("native"); return &backend; }, [this](const std::vector<Backend*>& results) { for (Backend* backend : results) { ASSERT_EQ("native", backend->GetName()); ASSERT_EQ(backend, results.front()); } }); } TEST(ContextTest, BackendNotFound) { Context ctx; EXPECT_THROW(ctx.GetBackend("something_that_does_not_exist"), BackendError); } TEST(ContextTest, GetDevice) { Context ctx; Device& device = ctx.GetDevice({"native", 0}); EXPECT_EQ(&device, &ctx.GetDevice({"native:0"})); } TEST(ContextTest, GetDeviceThreadSafe) { static constexpr size_t kRepeat = 100; static constexpr int kDeviceCount = 4; static constexpr size_t kThreadCountPerDevice = 32; static constexpr size_t kThreadCount = kDeviceCount * kThreadCountPerDevice; xchainer::testing::CheckThreadSafety( kRepeat, kThreadCount, [](size_t /*repeat*/) { return std::make_unique<Context>(); }, [](size_t thread_index, const std::unique_ptr<Context>& ctx) { int device_index = thread_index / kThreadCountPerDevice; Device& device = ctx->GetDevice({"native", device_index}); return &device; }, [this](const std::vector<Device*>& results) { // Check device pointers are identical within each set of threads corresponding to one device for (int device_index = 0; device_index < kDeviceCount; ++device_index) { auto it_first = std::next(results.begin(), device_index * kThreadCountPerDevice); auto it_last = std::next(results.begin(), (device_index + 1) * kThreadCountPerDevice); Device* ref_device = *it_first; // Check the device index ASSERT_EQ(device_index, ref_device->index()); for (auto it = it_first; it != it_last; ++it) { ASSERT_EQ(ref_device, *it); } } }); } TEST(ContextTest, DefaultContext) { SetGlobalDefaultContext(nullptr); SetDefaultContext(nullptr); ASSERT_THROW(GetDefaultContext(), XchainerError); Context ctx; SetGlobalDefaultContext(nullptr); SetDefaultContext(&ctx); ASSERT_EQ(&ctx, &GetDefaultContext()); Context global_ctx; SetGlobalDefaultContext(&global_ctx); SetDefaultContext(nullptr); ASSERT_EQ(&global_ctx, &GetDefaultContext()); SetGlobalDefaultContext(&global_ctx); SetDefaultContext(&ctx); ASSERT_EQ(&ctx, &GetDefaultContext()); } TEST(ContextTest, GlobalDefaultContext) { SetGlobalDefaultContext(nullptr); ASSERT_THROW(GetGlobalDefaultContext(), XchainerError); Context ctx; SetGlobalDefaultContext(&ctx); ASSERT_EQ(&ctx, &GetGlobalDefaultContext()); } TEST(ContextTest, ThreadLocal) { Context ctx; SetDefaultContext(&ctx); Context ctx2; auto future = std::async(std::launch::async, [&ctx2] { SetDefaultContext(&ctx2); return &GetDefaultContext(); }); ASSERT_NE(&GetDefaultContext(), future.get()); } TEST(ContextTest, ContextScopeCtor) { SetGlobalDefaultContext(nullptr); SetDefaultContext(nullptr); Context ctx1; { // ContextScope should work even if default context is not set ContextScope scope(ctx1); EXPECT_EQ(&ctx1, &GetDefaultContext()); } ASSERT_THROW(GetDefaultContext(), XchainerError); SetDefaultContext(&ctx1); { Context ctx2; ContextScope scope(ctx2); EXPECT_EQ(&ctx2, &GetDefaultContext()); } ASSERT_EQ(&ctx1, &GetDefaultContext()); { ContextScope scope; EXPECT_EQ(&ctx1, &GetDefaultContext()); Context ctx2; SetDefaultContext(&ctx2); } ASSERT_EQ(&ctx1, &GetDefaultContext()); Context ctx2; { ContextScope scope(ctx2); scope.Exit(); EXPECT_EQ(&ctx1, &GetDefaultContext()); SetDefaultContext(&ctx2); // not recovered here because the scope has already existed } ASSERT_EQ(&ctx2, &GetDefaultContext()); } TEST(ContextTest, ContextScopeResetDevice) { SetGlobalDefaultContext(nullptr); SetDefaultContext(nullptr); Context ctx1; Context ctx2; { ContextScope ctx_scope1{ctx1}; Device& device1 = ctx1.GetDevice({"native", 0}); DeviceScope dev_scope1{device1}; { ContextScope ctx_scope2{ctx2}; ASSERT_NE(&device1, &GetDefaultDevice()); Device& device2 = ctx2.GetDevice({"native", 0}); SetDefaultDevice(&device2); } EXPECT_EQ(&device1, &GetDefaultDevice()); } } TEST(ContextTest, UserDefinedBackend) { ::setenv("XCHAINER_PATH", XCHAINER_TEST_DIR "/context_testdata", 1); Context ctx; Backend& backend0 = ctx.GetBackend("backend0"); EXPECT_EQ("backend0", backend0.GetName()); Backend& backend0_2 = ctx.GetBackend("backend0"); EXPECT_EQ(&backend0, &backend0_2); Backend& backend1 = ctx.GetBackend("backend1"); EXPECT_EQ("backend1", backend1.GetName()); Device& device0 = ctx.GetDevice(std::string("backend0:0")); EXPECT_EQ(&backend0, &device0.backend()); } TEST(ContextTest, GetBackendOnDefaultContext) { // xchainer::GetBackend Context ctx; SetDefaultContext(&ctx); Backend& backend = GetBackend("native"); EXPECT_EQ(&ctx, &backend.context()); EXPECT_EQ("native", backend.GetName()); } TEST(ContextTest, GetNativeBackendOnDefaultContext) { // xchainer::GetNativeBackend Context ctx; SetDefaultContext(&ctx); native::NativeBackend& backend = GetNativeBackend(); EXPECT_EQ(&ctx.GetNativeBackend(), &backend); } TEST(ContextTest, GetDeviceOnDefaultContext) { // xchainer::GetDevice Context ctx; SetDefaultContext(&ctx); Device& device = GetDevice({"native:0"}); EXPECT_EQ(&ctx, &device.backend().context()); EXPECT_EQ("native:0", device.name()); } } // namespace } // namespace xchainer <|endoftext|>
<commit_before>// __BEGIN_LICENSE__ // Copyright (c) 2009-2012, United States Government as represented by the // Administrator of the National Aeronautics and Space Administration. All // rights reserved. // // The NGT platform is licensed under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance with the // License. You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // __END_LICENSE__ /// \file dem_adjust.cc /// #include <vw/FileIO.h> #include <vw/Image.h> #include <vw/Cartography.h> #include <vw/Math.h> #include <asp/Core/Macros.h> #include <asp/Core/Common.h> namespace po = boost::program_options; namespace fs = boost::filesystem; using std::endl; using std::string; using namespace vw; using namespace vw::cartography; template <class ImageT> class AdjustDemView : public ImageViewBase<AdjustDemView<ImageT> > { ImageT m_img; GeoReference const& m_georef; ImageViewRef<PixelMask<double> > const& m_delta; GeoReference const& m_delta_georef; double m_nodata_val; public: typedef double pixel_type; typedef double result_type; typedef ProceduralPixelAccessor<AdjustDemView> pixel_accessor; AdjustDemView(ImageT const& img, GeoReference const& georef, ImageViewRef<PixelMask<double> > const& delta, GeoReference const& delta_georef, double nodata_val): m_img(img), m_georef(georef), m_delta(delta), m_delta_georef(delta_georef), m_nodata_val(nodata_val){} inline int32 cols() const { return m_img.cols(); } inline int32 rows() const { return m_img.rows(); } inline int32 planes() const { return 1; } inline pixel_accessor origin() const { return pixel_accessor(*this); } inline result_type operator()( size_t col, size_t row, size_t p=0 ) const { if ( m_img(col, row, p) == m_nodata_val ) return m_nodata_val; Vector2 lonlat = m_georef.pixel_to_lonlat(Vector2(col, row)); // Wrap the lonlat until it is in the [0, 360) x [-90, 90) box for // interpolation. while( lonlat[0] < 0.0 ) lonlat[0] += 360.0; while( lonlat[0] >= 360.0 ) lonlat[0] -= 360.0; while( lonlat[1] < -90.0 ) lonlat[1] += 180.0; while( lonlat[1] >= 90.0 ) lonlat[1] -= 180.0; result_type delta_height = 0.0; Vector2 pix = m_delta_georef.lonlat_to_pixel(lonlat); PixelMask<double> interp_val = m_delta(pix[0], pix[1]); if (is_valid(interp_val)) delta_height = interp_val; result_type height_above_ellipsoid = m_img(col, row, p); result_type height_above_geoid = height_above_ellipsoid - delta_height; return height_above_geoid; } /// \cond INTERNAL typedef AdjustDemView<typename ImageT::prerasterize_type> prerasterize_type; inline prerasterize_type prerasterize( BBox2i const& bbox ) const { return prerasterize_type( m_img.prerasterize(bbox), m_georef, m_delta, m_delta_georef, m_nodata_val ); } template <class DestT> inline void rasterize( DestT const& dest, BBox2i const& bbox ) const { vw::rasterize( prerasterize(bbox), dest, bbox ); } /// \endcond }; template <class ImageT> AdjustDemView<ImageT> adjust_dem( ImageViewBase<ImageT> const& img, GeoReference const& georef, ImageViewRef<PixelMask<double> > const& delta, GeoReference const& delta_georef, double nodata_val) { return AdjustDemView<ImageT>( img.impl(), georef, delta, delta_georef, nodata_val ); } struct Options : asp::BaseOptions { string geoid, delta_file, dem_name, output_prefix; double nodata_value; bool use_float; }; void handle_arguments( int argc, char *argv[], Options& opt ){ po::options_description general_options(""); general_options.add_options() ("nodata_value", po::value(&opt.nodata_value)->default_value(-32767), "The value of no-data pixels, unless specified in the DEM.") ("geoid", po::value(&opt.geoid)->default_value("EGM96"), "Choose a geoid [EGM96, NAVD88].") ("output-prefix,o", po::value(&opt.output_prefix), "Specify the output prefix.") ("float", po::bool_switch(&opt.use_float)->default_value(false), "Output using float (32 bit) instead of using doubles (64 bit)."); general_options.add( asp::BaseOptionsDescription(opt) ); po::options_description positional(""); positional.add_options() ("dem", po::value(&opt.dem_name), "Explicitly specify the DEM."); po::positional_options_description positional_desc; positional_desc.add("dem", 1); std::string usage("[options] <dem>"); po::variables_map vm = asp::check_command_line( argc, argv, opt, general_options, general_options, positional, positional_desc, usage ); // The geoid DEM containing the adjustments #define STR_EXPAND(tok) #tok #define STR_QUOTE(tok) STR_EXPAND(tok) std::string geoid_path = STR_QUOTE(DEM_ADJUST_GEOID_PATH); if (opt.geoid == "EGM96"){ opt.delta_file = geoid_path + "/" + "egm96-5.tif"; }else if(opt.geoid == "NAVD88"){ opt.delta_file = geoid_path + "/" + "NAVD88.tif"; }else{ vw_throw( ArgumentErr() << "Unknown geoid: " << opt.geoid << ".\n\n" << usage << general_options ); } if ( opt.dem_name.empty() ) vw_throw( ArgumentErr() << "Requires <dem> in order to proceed.\n\n" << usage << general_options ); if ( opt.output_prefix.empty() ) { opt.output_prefix = fs::path(opt.dem_name).stem().string(); } } int main( int argc, char *argv[] ) { // Adjust the DEM values so that they are relative to the geoid // rather than to the ellipsoid. Options opt; try { handle_arguments( argc, argv, opt ); // Read the DEM to adjust DiskImageResourceGDAL dem_rsrc(opt.dem_name); double nodata_val = opt.nodata_value; if ( dem_rsrc.has_nodata_read() ) { nodata_val = dem_rsrc.nodata_read(); vw_out() << "\tFound input nodata value for " << opt.dem_name << ": " << nodata_val << endl; } DiskImageView<double> dem_img(dem_rsrc); GeoReference dem_georef; read_georeference(dem_georef, dem_rsrc); // Read the DEM geoid containing the adjustments double delta_nodata_val = opt.nodata_value; DiskImageResourceGDAL delta_rsrc(opt.delta_file); if ( delta_rsrc.has_nodata_read() ) { delta_nodata_val = delta_rsrc.nodata_read(); vw_out() << "\tFound input nodata value for " << opt.delta_file << ": " << delta_nodata_val << endl; } DiskImageView<double> delta_img(delta_rsrc); GeoReference delta_georef; read_georeference(delta_georef, delta_rsrc); ImageViewRef<PixelMask<double> > delta = interpolate(create_mask( delta_img, delta_nodata_val ), BicubicInterpolation(), ZeroEdgeExtension()); ImageViewRef<double> adj_dem = adjust_dem(dem_img, dem_georef, delta, delta_georef, nodata_val); std::string adj_dem_file = opt.output_prefix + "-adj.tif"; vw_out() << "Writing adjusted DEM: " << adj_dem_file << std::endl; if ( opt.use_float ) { ImageViewRef<float> adj_dem_float = channel_cast<float>( adj_dem ); boost::scoped_ptr<DiskImageResourceGDAL> rsrc( asp::build_gdal_rsrc(adj_dem_file, adj_dem_float, opt ) ); rsrc->set_nodata_write( nodata_val ); write_georeference( *rsrc, dem_georef ); block_write_image( *rsrc, adj_dem_float, TerminalProgressCallback("asp", "\t--> Applying DEM adjustment: ") ); } else { boost::scoped_ptr<DiskImageResourceGDAL> rsrc( asp::build_gdal_rsrc(adj_dem_file, adj_dem, opt ) ); rsrc->set_nodata_write( nodata_val ); write_georeference( *rsrc, dem_georef ); block_write_image( *rsrc, adj_dem, TerminalProgressCallback("asp", "\t--> Applying DEM adjustment: ") ); } } ASP_STANDARD_CATCHES; return 0; } <commit_msg>dem_adjust: Speed up by reading geoid in memory, other minor<commit_after>// __BEGIN_LICENSE__ // Copyright (c) 2009-2012, United States Government as represented by the // Administrator of the National Aeronautics and Space Administration. All // rights reserved. // // The NGT platform is licensed under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance with the // License. You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // __END_LICENSE__ /// \file dem_adjust.cc /// #include <vw/FileIO.h> #include <vw/Image.h> #include <vw/Cartography.h> #include <vw/Math.h> #include <asp/Core/Macros.h> #include <asp/Core/Common.h> namespace po = boost::program_options; namespace fs = boost::filesystem; using std::endl; using std::string; using namespace vw; using namespace vw::cartography; template <class ImageT> class DemAdjustView : public ImageViewBase<DemAdjustView<ImageT> > { ImageT m_img; GeoReference const& m_georef; ImageViewRef<PixelMask<double> > const& m_delta; GeoReference const& m_delta_georef; double m_nodata_val; public: typedef double pixel_type; typedef double result_type; typedef ProceduralPixelAccessor<DemAdjustView> pixel_accessor; DemAdjustView(ImageT const& img, GeoReference const& georef, ImageViewRef<PixelMask<double> > const& delta, GeoReference const& delta_georef, double nodata_val): m_img(img), m_georef(georef), m_delta(delta), m_delta_georef(delta_georef), m_nodata_val(nodata_val){} inline int32 cols() const { return m_img.cols(); } inline int32 rows() const { return m_img.rows(); } inline int32 planes() const { return 1; } inline pixel_accessor origin() const { return pixel_accessor(*this); } inline result_type operator()( size_t col, size_t row, size_t p=0 ) const { if ( m_img(col, row, p) == m_nodata_val ) return m_nodata_val; Vector2 lonlat = m_georef.pixel_to_lonlat(Vector2(col, row)); // Wrap the lonlat until it is in the [0, 360) x [-90, 90) box for // interpolation. // lonlat[0] = -121; lonlat[1] = 37; // For testing (see example below) while( lonlat[0] < 0.0 ) lonlat[0] += 360.0; while( lonlat[0] >= 360.0 ) lonlat[0] -= 360.0; while( lonlat[1] < -90.0 ) lonlat[1] += 180.0; while( lonlat[1] >= 90.0 ) lonlat[1] -= 180.0; result_type delta_height = 0.0; Vector2 pix = m_delta_georef.lonlat_to_pixel(lonlat); PixelMask<double> interp_val = m_delta(pix[0], pix[1]); if (is_valid(interp_val)) delta_height = interp_val; result_type height_above_ellipsoid = m_img(col, row, p); // See the note in the main program about the formula below result_type height_above_geoid = height_above_ellipsoid - delta_height; return height_above_geoid; } /// \cond INTERNAL typedef DemAdjustView<typename ImageT::prerasterize_type> prerasterize_type; inline prerasterize_type prerasterize( BBox2i const& bbox ) const { return prerasterize_type( m_img.prerasterize(bbox), m_georef, m_delta, m_delta_georef, m_nodata_val ); } template <class DestT> inline void rasterize( DestT const& dest, BBox2i const& bbox ) const { vw::rasterize( prerasterize(bbox), dest, bbox ); } /// \endcond }; template <class ImageT> DemAdjustView<ImageT> dem_adjust( ImageViewBase<ImageT> const& img, GeoReference const& georef, ImageViewRef<PixelMask<double> > const& delta, GeoReference const& delta_georef, double nodata_val) { return DemAdjustView<ImageT>( img.impl(), georef, delta, delta_georef, nodata_val ); } struct Options : asp::BaseOptions { string geoid, delta_file, dem_name, output_prefix; double nodata_value; bool use_double; }; void handle_arguments( int argc, char *argv[], Options& opt ){ po::options_description general_options(""); general_options.add_options() ("nodata_value", po::value(&opt.nodata_value)->default_value(-32767), "The value of no-data pixels, unless specified in the DEM.") ("geoid", po::value(&opt.geoid)->default_value("EGM96"), "Choose a geoid [EGM96, NAVD88].") ("output-prefix,o", po::value(&opt.output_prefix), "Specify the output prefix.") ("double", po::bool_switch(&opt.use_double)->default_value(false)->implicit_value(true), "Output using double (64 bit) instead of float (32 bit)."); general_options.add( asp::BaseOptionsDescription(opt) ); po::options_description positional(""); positional.add_options() ("dem", po::value(&opt.dem_name), "Explicitly specify the DEM."); po::positional_options_description positional_desc; positional_desc.add("dem", 1); std::string usage("[options] <dem>"); po::variables_map vm = asp::check_command_line( argc, argv, opt, general_options, general_options, positional, positional_desc, usage ); // The geoid DEM containing the adjustments #define STR_EXPAND(tok) #tok #define STR_QUOTE(tok) STR_EXPAND(tok) std::string geoid_path = STR_QUOTE(DEM_ADJUST_GEOID_PATH); if (opt.geoid == "EGM96"){ opt.delta_file = geoid_path + "/" + "egm96-5.tif"; }else if(opt.geoid == "NAVD88"){ opt.delta_file = geoid_path + "/" + "NAVD88.tif"; }else{ vw_throw( ArgumentErr() << "Unknown geoid: " << opt.geoid << ".\n\n" << usage << general_options ); } if ( opt.dem_name.empty() ) vw_throw( ArgumentErr() << "Requires <dem> in order to proceed.\n\n" << usage << general_options ); if ( opt.output_prefix.empty() ) { opt.output_prefix = fs::path(opt.dem_name).stem().string(); } } // Given a DEM, with each height value relative to the datum // ellipsoid, convert the heights to be relative to the geoid. // From: http://earth-info.nga.mil/GandG/wgs84/gravitymod/egm96/intpthel.html // Geoid heights can be used to convert between orthometric // heights (approximately mean sea level) and ellipsoid heights // according to the formula: // h = H + N // where, // h = WGS 84 Ellipsoid height // H = Orthometric height // N = EGM96 Geoid height // Therefore: H = h - N. // We support two geoids: EGM96 and NAVD88. // Online tools for verification: // EGM96: http://earth-info.nga.mil/GandG/wgs84/gravitymod/egm96/intpt.html // NAVD88: http://www.ngs.noaa.gov/cgi-bin/GEOID_STUFF/geoid09_prompt1.prl // // Example, at lat = 37 and lon = -121 (Basalt Hills, CA), we have // EGM96 geoid height = -32.69 // NAVD88 geoid height = -32.931 int main( int argc, char *argv[] ) { Options opt; try { handle_arguments( argc, argv, opt ); // Read the DEM to adjust DiskImageResourceGDAL dem_rsrc(opt.dem_name); double nodata_val = opt.nodata_value; if ( dem_rsrc.has_nodata_read() ) { nodata_val = dem_rsrc.nodata_read(); vw_out() << "\tFound input nodata value for " << opt.dem_name << ": " << nodata_val << endl; } DiskImageView<double> dem_img(dem_rsrc); GeoReference dem_georef; read_georeference(dem_georef, dem_rsrc); // Read the geoid containing the adjustments. Read it in memory // entirely to dramatically speed up the computations. double delta_nodata_val = std::numeric_limits<float>::quiet_NaN(); DiskImageResourceGDAL delta_rsrc(opt.delta_file); if ( delta_rsrc.has_nodata_read() ) { delta_nodata_val = delta_rsrc.nodata_read(); } vw_out() << "\tAdjusting the DEM using the geoid: " << opt.delta_file << endl; ImageView<float> delta_img = DiskImageView<float>(delta_rsrc); GeoReference delta_georef; read_georeference(delta_georef, delta_rsrc); ImageViewRef<PixelMask<double> > delta = interpolate(create_mask( pixel_cast<double>(delta_img), delta_nodata_val ), BicubicInterpolation(), ZeroEdgeExtension()); ImageViewRef<double> adj_dem = dem_adjust(dem_img, dem_georef, delta, delta_georef, nodata_val); std::string adj_dem_file = opt.output_prefix + "-adj.tif"; vw_out() << "Writing adjusted DEM: " << adj_dem_file << std::endl; if ( opt.use_double ) { // Output as double boost::scoped_ptr<DiskImageResourceGDAL> rsrc( asp::build_gdal_rsrc(adj_dem_file, adj_dem, opt ) ); rsrc->set_nodata_write( nodata_val ); write_georeference( *rsrc, dem_georef ); block_write_image( *rsrc, adj_dem, TerminalProgressCallback("asp", "\t--> Applying DEM adjustment: ") ); }else{ // Output as float ImageViewRef<float> adj_dem_float = channel_cast<float>( adj_dem ); boost::scoped_ptr<DiskImageResourceGDAL> rsrc( asp::build_gdal_rsrc(adj_dem_file, adj_dem_float, opt ) ); rsrc->set_nodata_write( nodata_val ); write_georeference( *rsrc, dem_georef ); block_write_image( *rsrc, adj_dem_float, TerminalProgressCallback("asp", "\t--> Applying DEM adjustment: ") ); } } ASP_STANDARD_CATCHES; return 0; } <|endoftext|>
<commit_before>/****************************************************************************** The MIT License(MIT) Embedded Template Library. https://github.com/ETLCPP/etl https://www.etlcpp.com Copyright(c) 2014 jwellbelove Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files(the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and / or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions : The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ******************************************************************************/ #include "unit_test_framework.h" #include "etl/instance_count.h" #include <list> #include <vector> #include <numeric> namespace { SUITE(test_instance_count) { //************************************************************************* TEST(test_count) { struct Test1 : public etl::instance_count<Test1> {}; struct Test2 : public etl::instance_count<Test2> {}; CHECK_EQUAL(0, Test1::get_instance_count()); CHECK_EQUAL(0, Test2::get_instance_count()); Test1 test1a; CHECK_EQUAL(1, Test1::get_instance_count()); CHECK_EQUAL(0, Test2::get_instance_count()); Test1 test1b; Test2 test2a; CHECK_EQUAL(2, Test1::get_instance_count()); CHECK_EQUAL(1, Test2::get_instance_count()); Test2* ptest2b = new Test2; CHECK_EQUAL(2, Test1::get_instance_count()); CHECK_EQUAL(2, Test2::get_instance_count()); Test2 test2c(test2a); CHECK_EQUAL(2, Test1::get_instance_count()); CHECK_EQUAL(3, Test2::get_instance_count()); delete ptest2b; CHECK_EQUAL(2, Test1::get_instance_count()); CHECK_EQUAL(2, Test2::get_instance_count()); } }; } <commit_msg>Added optional counter type to instance_count.<commit_after>/****************************************************************************** The MIT License(MIT) Embedded Template Library. https://github.com/ETLCPP/etl https://www.etlcpp.com Copyright(c) 2014 jwellbelove Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files(the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and / or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions : The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ******************************************************************************/ #include "unit_test_framework.h" #include "etl/instance_count.h" #include <list> #include <vector> #include <numeric> #include <atomic> namespace { SUITE(test_instance_count) { //************************************************************************* TEST(test_count) { struct Test1 : public etl::instance_count<Test1> {}; struct Test2 : public etl::instance_count<Test2> {}; CHECK_EQUAL(0, Test1::get_instance_count()); CHECK_EQUAL(0, Test2::get_instance_count()); Test1 test1a; CHECK_EQUAL(1, Test1::get_instance_count()); CHECK_EQUAL(0, Test2::get_instance_count()); Test1 test1b; Test2 test2a; CHECK_EQUAL(2, Test1::get_instance_count()); CHECK_EQUAL(1, Test2::get_instance_count()); Test2* ptest2b = new Test2; CHECK_EQUAL(2, Test1::get_instance_count()); CHECK_EQUAL(2, Test2::get_instance_count()); Test2 test2c(test2a); CHECK_EQUAL(2, Test1::get_instance_count()); CHECK_EQUAL(3, Test2::get_instance_count()); delete ptest2b; CHECK_EQUAL(2, Test1::get_instance_count()); CHECK_EQUAL(2, Test2::get_instance_count()); } //************************************************************************* TEST(test_atomic_count) { struct Test1 : public etl::instance_count<Test1, std::atomic_uint8_t> {}; struct Test2 : public etl::instance_count<Test2> {}; CHECK_EQUAL(0, Test1::get_instance_count()); CHECK_EQUAL(0, Test2::get_instance_count()); Test1 test1a; CHECK_EQUAL(1, Test1::get_instance_count()); CHECK_EQUAL(0, Test2::get_instance_count()); Test1 test1b; Test2 test2a; CHECK_EQUAL(2, Test1::get_instance_count()); CHECK_EQUAL(1, Test2::get_instance_count()); Test2* ptest2b = new Test2; CHECK_EQUAL(2, Test1::get_instance_count()); CHECK_EQUAL(2, Test2::get_instance_count()); Test2 test2c(test2a); CHECK_EQUAL(2, Test1::get_instance_count()); CHECK_EQUAL(3, Test2::get_instance_count()); delete ptest2b; CHECK_EQUAL(2, Test1::get_instance_count()); CHECK_EQUAL(2, Test2::get_instance_count()); } }; } <|endoftext|>
<commit_before>// // Created by Davide Caroselli on 28/09/16. // #include "SuffixArray.h" #include "dbkv.h" #include <rocksdb/slice_transform.h> #include <rocksdb/merge_operator.h> #include <thread> #include <boost/filesystem.hpp> #include <iostream> #include <util/hashutils.h> namespace fs = boost::filesystem; using namespace rocksdb; using namespace mmt; using namespace mmt::sapt; const domain_t mmt::sapt::kBackgroundModelDomain = 0; static const string kGlobalInfoKey = MakeEmptyKey(kGlobalInfoKeyType); /* * MergePositionOperator */ namespace mmt { namespace sapt { class MergePositionOperator : public AssociativeMergeOperator { public: virtual bool Merge(const Slice &key, const Slice *existing_value, const Slice &value, string *new_value, Logger *logger) const override { switch (key.data_[0]) { case kSourcePrefixKeyType: case kTargetPrefixKeyType: MergePositionLists(existing_value, value, new_value); return true; default: return false; } } inline void MergePositionLists(const Slice *existing_value, const Slice &value, string *new_value) const { if (existing_value) *new_value = existing_value->ToString() + value.ToString(); else *new_value = value.ToString(); } virtual const char *Name() const override { return "MergePositionOperator"; } }; } } /* * SuffixArray - Initialization */ SuffixArray::SuffixArray(const string &modelPath, uint8_t prefixLength, bool prepareForBulkLoad) throw(index_exception, storage_exception) : prefixLength(prefixLength) { fs::path modelDir(modelPath); if (!fs::is_directory(modelDir)) throw invalid_argument("Invalid model path: " + modelPath); fs::path storageFile = fs::absolute(modelDir / fs::path("corpora.bin")); fs::path indexPath = fs::absolute(modelDir / fs::path("index")); rocksdb::Options options; options.create_if_missing = true; options.merge_operator.reset(new MergePositionOperator); options.max_open_files = -1; options.compaction_style = kCompactionStyleLevel; if (prepareForBulkLoad) { options.PrepareForBulkLoad(); } else { unsigned cpus = thread::hardware_concurrency(); if (cpus > 1) options.IncreaseParallelism(cpus > 4 ? 4 : 2); options.level0_file_num_compaction_trigger = 8; options.level0_slowdown_writes_trigger = 17; options.level0_stop_writes_trigger = 24; options.num_levels = 4; options.write_buffer_size = 64L * 1024L * 1024L; options.max_write_buffer_number = 3; options.target_file_size_base = 64L * 1024L * 1024L; options.max_bytes_for_level_base = 512L * 1024L * 1024L; options.max_bytes_for_level_multiplier = 8; } Status status = DB::Open(options, indexPath.string(), &db); if (!status.ok()) throw index_exception(status.ToString()); db->CompactRange(CompactRangeOptions(), NULL, NULL); // Read streams string raw_streams; int64_t storageSize = 0; db->Get(ReadOptions(), kGlobalInfoKey, &raw_streams); DeserializeGlobalInfo(raw_streams.data(), raw_streams.size(), &storageSize, &streams); // Load storage storage = new CorpusStorage(storageFile.string(), storageSize); } SuffixArray::~SuffixArray() { delete db; delete storage; } /* * SuffixArray - Indexing */ void SuffixArray::ForceCompaction() { db->CompactRange(CompactRangeOptions(), NULL, NULL); } void SuffixArray::PutBatch(UpdateBatch &batch) throw(index_exception, storage_exception) { WriteBatch writeBatch; // Compute prefixes unordered_map<string, PostingList> sourcePrefixes; unordered_map<string, PostingList> targetPrefixes; for (auto entry = batch.data.begin(); entry != batch.data.end(); ++entry) { domain_t domain = entry->domain; int64_t offset = storage->Append(entry->source, entry->target, entry->alignment); AddPrefixesToBatch(true, domain, entry->source, offset, sourcePrefixes); AddPrefixesToBatch(false, kBackgroundModelDomain, entry->target, offset, targetPrefixes); } int64_t storageSize = storage->Flush(); // Add prefixes to write batch for (auto prefix = sourcePrefixes.begin(); prefix != sourcePrefixes.end(); ++prefix) { string value = prefix->second.Serialize(); writeBatch.Merge(prefix->first, value); } for (auto prefix = targetPrefixes.begin(); prefix != targetPrefixes.end(); ++prefix) { string value = prefix->second.Serialize(); writeBatch.Merge(prefix->first, value); } // Write global info writeBatch.Put(kGlobalInfoKey, SerializeGlobalInfo(batch.streams, storageSize)); // Commit write batch Status status = db->Write(WriteOptions(), &writeBatch); if (!status.ok()) throw index_exception("Unable to write to index: " + status.ToString()); // Reset streams and domains streams = batch.GetStreams(); } void SuffixArray::AddPrefixesToBatch(bool isSource, domain_t domain, const vector<wid_t> &sentence, int64_t location, unordered_map<string, PostingList> &outBatch) { for (length_t start = 0; start < sentence.size(); ++start) { size_t length = prefixLength; if (start + length > sentence.size()) length = sentence.size() - start; // Add to background model string key = MakePrefixKey(isSource, kBackgroundModelDomain, sentence, start, length); outBatch[key].Append(kBackgroundModelDomain, location, start); // Add to domain if (domain != kBackgroundModelDomain) { string dkey = MakePrefixKey(isSource, domain, sentence, start, length); outBatch[dkey].Append(domain, location, start); } } } /* * SuffixArray - Query */ size_t SuffixArray::CountOccurrences(bool isSource, const vector<wid_t> &phrase) { PostingList locations(phrase); CollectLocations(isSource, kBackgroundModelDomain, phrase, locations); return locations.size(); } void SuffixArray::GetRandomSamples(const vector<wid_t> &phrase, size_t limit, vector<sample_t> &outSamples, const context_t *context, bool searchInBackground) { PostingList inContextLocations(phrase); PostingList outContextLocations(phrase); size_t remaining = limit; if (context) { for (auto score = context->begin(); score != context->end(); ++score) { CollectPositions(true, score->domain, phrase, inContextPositions); std::cerr << "Found " << outSamples.size() << " samples" << std::endl; if (limit > 0) { if (inContextLocations.size() >= limit) { remaining = 0; break; } else { remaining = limit - inContextLocations.size(); } } } } if (searchInBackground && (limit == 0 || remaining > 0)) { unordered_set<int64_t> coveredLocations = inContextLocations.GetLocations(); CollectLocations(true, kBackgroundModelDomain, phrase, outContextLocations, &coveredLocations); } outSamples.clear(); ssize_t inContextSize = inContextLocations.size() - limit; if (inContextSize < 0) { map<int64_t, pair<domain_t, vector<length_t>>> inContext = inContextLocations.GetSamples(); map<int64_t, pair<domain_t, vector<length_t>>> outContext = outContextLocations.GetSamples((size_t) -inContextSize, words_hash(phrase)); Retrieve(inContext, outSamples); Retrieve(outContext, outSamples); } else { map<int64_t, pair<domain_t, vector<length_t>>> inContext = inContextLocations.GetSamples(limit); Retrieve(inContext, outSamples); } } void SuffixArray::CollectLocations(bool isSource, domain_t domain, const vector<wid_t> &sentence, PostingList &output, unordered_set<int64_t> *coveredLocations) { length_t sentenceLength = (length_t) sentence.size(); if (sentenceLength <= prefixLength) { CollectLocations(isSource, domain, sentence, 0, sentence.size(), output, coveredLocations); } else { length_t start = 0; PostingList collected(sentence); while (start < sentenceLength) { if (start + prefixLength > sentenceLength) start = sentenceLength - prefixLength; if (start == 0) { CollectLocations(isSource, domain, sentence, start, prefixLength, collected, coveredLocations); } else { PostingList successors(sentence, start, prefixLength); CollectLocations(isSource, domain, sentence, start, prefixLength, successors, coveredLocations); collected.Retain(successors, start); } if (collected.empty()) break; start += prefixLength; } output.Append(collected); } } void SuffixArray::CollectLocations(bool isSource, domain_t domain, const vector<wid_t> &phrase, size_t offset, size_t length, PostingList &output, const unordered_set<int64_t> *coveredLocations) { string key = MakePrefixKey(isSource, domain, phrase, offset, length); if (length == prefixLength) { string value; db->Get(ReadOptions(), key, &value); output.Append(domain, value.data(), value.size(), coveredLocations); } else { Iterator *it = db->NewIterator(ReadOptions()); for (it->Seek(key); it->Valid() && it->key().starts_with(key); it->Next()) { Slice value = it->value(); output.Append(domain, value.data_, value.size_, coveredLocations); } delete it; } } void SuffixArray::Retrieve(const map<int64_t, pair<domain_t, vector<length_t>>> &locations, vector<sample_t> &outSamples) { // Resolve positions outSamples.reserve(outSamples.size() + locations.size()); for (auto location = locations.begin(); location != locations.end(); ++location) { auto &value = location->second; sample_t sample; sample.domain = value.first; sample.offsets = value.second; storage->Retrieve(location->first, &sample.source, &sample.target, &sample.alignment); outSamples.push_back(sample); } } <commit_msg>fixed name mismatch after merging<commit_after>// // Created by Davide Caroselli on 28/09/16. // #include "SuffixArray.h" #include "dbkv.h" #include <rocksdb/slice_transform.h> #include <rocksdb/merge_operator.h> #include <thread> #include <boost/filesystem.hpp> #include <iostream> #include <util/hashutils.h> namespace fs = boost::filesystem; using namespace rocksdb; using namespace mmt; using namespace mmt::sapt; const domain_t mmt::sapt::kBackgroundModelDomain = 0; static const string kGlobalInfoKey = MakeEmptyKey(kGlobalInfoKeyType); /* * MergePositionOperator */ namespace mmt { namespace sapt { class MergePositionOperator : public AssociativeMergeOperator { public: virtual bool Merge(const Slice &key, const Slice *existing_value, const Slice &value, string *new_value, Logger *logger) const override { switch (key.data_[0]) { case kSourcePrefixKeyType: case kTargetPrefixKeyType: MergePositionLists(existing_value, value, new_value); return true; default: return false; } } inline void MergePositionLists(const Slice *existing_value, const Slice &value, string *new_value) const { if (existing_value) *new_value = existing_value->ToString() + value.ToString(); else *new_value = value.ToString(); } virtual const char *Name() const override { return "MergePositionOperator"; } }; } } /* * SuffixArray - Initialization */ SuffixArray::SuffixArray(const string &modelPath, uint8_t prefixLength, bool prepareForBulkLoad) throw(index_exception, storage_exception) : prefixLength(prefixLength) { fs::path modelDir(modelPath); if (!fs::is_directory(modelDir)) throw invalid_argument("Invalid model path: " + modelPath); fs::path storageFile = fs::absolute(modelDir / fs::path("corpora.bin")); fs::path indexPath = fs::absolute(modelDir / fs::path("index")); rocksdb::Options options; options.create_if_missing = true; options.merge_operator.reset(new MergePositionOperator); options.max_open_files = -1; options.compaction_style = kCompactionStyleLevel; if (prepareForBulkLoad) { options.PrepareForBulkLoad(); } else { unsigned cpus = thread::hardware_concurrency(); if (cpus > 1) options.IncreaseParallelism(cpus > 4 ? 4 : 2); options.level0_file_num_compaction_trigger = 8; options.level0_slowdown_writes_trigger = 17; options.level0_stop_writes_trigger = 24; options.num_levels = 4; options.write_buffer_size = 64L * 1024L * 1024L; options.max_write_buffer_number = 3; options.target_file_size_base = 64L * 1024L * 1024L; options.max_bytes_for_level_base = 512L * 1024L * 1024L; options.max_bytes_for_level_multiplier = 8; } Status status = DB::Open(options, indexPath.string(), &db); if (!status.ok()) throw index_exception(status.ToString()); db->CompactRange(CompactRangeOptions(), NULL, NULL); // Read streams string raw_streams; int64_t storageSize = 0; db->Get(ReadOptions(), kGlobalInfoKey, &raw_streams); DeserializeGlobalInfo(raw_streams.data(), raw_streams.size(), &storageSize, &streams); // Load storage storage = new CorpusStorage(storageFile.string(), storageSize); } SuffixArray::~SuffixArray() { delete db; delete storage; } /* * SuffixArray - Indexing */ void SuffixArray::ForceCompaction() { db->CompactRange(CompactRangeOptions(), NULL, NULL); } void SuffixArray::PutBatch(UpdateBatch &batch) throw(index_exception, storage_exception) { WriteBatch writeBatch; // Compute prefixes unordered_map<string, PostingList> sourcePrefixes; unordered_map<string, PostingList> targetPrefixes; for (auto entry = batch.data.begin(); entry != batch.data.end(); ++entry) { domain_t domain = entry->domain; int64_t offset = storage->Append(entry->source, entry->target, entry->alignment); AddPrefixesToBatch(true, domain, entry->source, offset, sourcePrefixes); AddPrefixesToBatch(false, kBackgroundModelDomain, entry->target, offset, targetPrefixes); } int64_t storageSize = storage->Flush(); // Add prefixes to write batch for (auto prefix = sourcePrefixes.begin(); prefix != sourcePrefixes.end(); ++prefix) { string value = prefix->second.Serialize(); writeBatch.Merge(prefix->first, value); } for (auto prefix = targetPrefixes.begin(); prefix != targetPrefixes.end(); ++prefix) { string value = prefix->second.Serialize(); writeBatch.Merge(prefix->first, value); } // Write global info writeBatch.Put(kGlobalInfoKey, SerializeGlobalInfo(batch.streams, storageSize)); // Commit write batch Status status = db->Write(WriteOptions(), &writeBatch); if (!status.ok()) throw index_exception("Unable to write to index: " + status.ToString()); // Reset streams and domains streams = batch.GetStreams(); } void SuffixArray::AddPrefixesToBatch(bool isSource, domain_t domain, const vector<wid_t> &sentence, int64_t location, unordered_map<string, PostingList> &outBatch) { for (length_t start = 0; start < sentence.size(); ++start) { size_t length = prefixLength; if (start + length > sentence.size()) length = sentence.size() - start; // Add to background model string key = MakePrefixKey(isSource, kBackgroundModelDomain, sentence, start, length); outBatch[key].Append(kBackgroundModelDomain, location, start); // Add to domain if (domain != kBackgroundModelDomain) { string dkey = MakePrefixKey(isSource, domain, sentence, start, length); outBatch[dkey].Append(domain, location, start); } } } /* * SuffixArray - Query */ size_t SuffixArray::CountOccurrences(bool isSource, const vector<wid_t> &phrase) { PostingList locations(phrase); CollectLocations(isSource, kBackgroundModelDomain, phrase, locations); return locations.size(); } void SuffixArray::GetRandomSamples(const vector<wid_t> &phrase, size_t limit, vector<sample_t> &outSamples, const context_t *context, bool searchInBackground) { PostingList inContextLocations(phrase); PostingList outContextLocations(phrase); size_t remaining = limit; if (context) { for (auto score = context->begin(); score != context->end(); ++score) { CollectLocations(true, score->domain, phrase, inContextLocations); std::cerr << "Found " << outSamples.size() << " samples" << std::endl; if (limit > 0) { if (inContextLocations.size() >= limit) { remaining = 0; break; } else { remaining = limit - inContextLocations.size(); } } } } if (searchInBackground && (limit == 0 || remaining > 0)) { unordered_set<int64_t> coveredLocations = inContextLocations.GetLocations(); CollectLocations(true, kBackgroundModelDomain, phrase, outContextLocations, &coveredLocations); } outSamples.clear(); ssize_t inContextSize = inContextLocations.size() - limit; if (inContextSize < 0) { map<int64_t, pair<domain_t, vector<length_t>>> inContext = inContextLocations.GetSamples(); map<int64_t, pair<domain_t, vector<length_t>>> outContext = outContextLocations.GetSamples((size_t) -inContextSize, words_hash(phrase)); Retrieve(inContext, outSamples); Retrieve(outContext, outSamples); } else { map<int64_t, pair<domain_t, vector<length_t>>> inContext = inContextLocations.GetSamples(limit); Retrieve(inContext, outSamples); } } void SuffixArray::CollectLocations(bool isSource, domain_t domain, const vector<wid_t> &sentence, PostingList &output, unordered_set<int64_t> *coveredLocations) { length_t sentenceLength = (length_t) sentence.size(); if (sentenceLength <= prefixLength) { CollectLocations(isSource, domain, sentence, 0, sentence.size(), output, coveredLocations); } else { length_t start = 0; PostingList collected(sentence); while (start < sentenceLength) { if (start + prefixLength > sentenceLength) start = sentenceLength - prefixLength; if (start == 0) { CollectLocations(isSource, domain, sentence, start, prefixLength, collected, coveredLocations); } else { PostingList successors(sentence, start, prefixLength); CollectLocations(isSource, domain, sentence, start, prefixLength, successors, coveredLocations); collected.Retain(successors, start); } if (collected.empty()) break; start += prefixLength; } output.Append(collected); } } void SuffixArray::CollectLocations(bool isSource, domain_t domain, const vector<wid_t> &phrase, size_t offset, size_t length, PostingList &output, const unordered_set<int64_t> *coveredLocations) { string key = MakePrefixKey(isSource, domain, phrase, offset, length); if (length == prefixLength) { string value; db->Get(ReadOptions(), key, &value); output.Append(domain, value.data(), value.size(), coveredLocations); } else { Iterator *it = db->NewIterator(ReadOptions()); for (it->Seek(key); it->Valid() && it->key().starts_with(key); it->Next()) { Slice value = it->value(); output.Append(domain, value.data_, value.size_, coveredLocations); } delete it; } } void SuffixArray::Retrieve(const map<int64_t, pair<domain_t, vector<length_t>>> &locations, vector<sample_t> &outSamples) { // Resolve positions outSamples.reserve(outSamples.size() + locations.size()); for (auto location = locations.begin(); location != locations.end(); ++location) { auto &value = location->second; sample_t sample; sample.domain = value.first; sample.offsets = value.second; storage->Retrieve(location->first, &sample.source, &sample.target, &sample.alignment); outSamples.push_back(sample); } } <|endoftext|>
<commit_before>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "otbWrapperApplication.h" #include "otbWrapperApplicationFactory.h" #include "otbStatisticsXMLFileWriter.h" #include "otbStreamingStatisticsVectorImageFilter.h" namespace otb { namespace Wrapper { class EstimateImagesStatistics: public Application { public: /** Standard class typedefs. */ typedef EstimateImagesStatistics Self; typedef Application Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; /** Standard macro */ itkNewMacro(Self); itkTypeMacro(EstimateImagesStatistics, otb::Application); private: EstimateImagesStatistics() { SetName("EstimateImagesStatistics"); SetDescription("Estimates mean/standard deviation for all images in the input list and optionally saves the results in an XML file"); SetDocName("Estimate Image Statistics Application"); SetDocLongDescription("This application estimates mean/standard deviation for all images in the input list and optionally saves the results in an XML file."); SetDocLimitations("None"); SetDocAuthors("OTB-Team"); SetDocSeeAlso(" "); SetDocCLExample("otbApplicationLauncherCommandLine EstimateImagesStatistics ${OTB-BIN}/bin --il ${OTB-Data}/Input/Classification/QB_1_ortho.tif ${OTB-Data}/Input/Classification/QB_2_ortho.tif ${OTB-Data}/Input/Classification/QB_3_ortho.tif --out EstimateImageStatisticsQB123.xml"); AddDocTag("Classification"); } virtual ~EstimateImagesStatistics() { } void DoCreateParameters() { AddParameter(ParameterType_InputImageList, "il", "Input Image List "); SetParameterDescription( "il", "Input Image List filename." ); AddParameter(ParameterType_Filename, "out", "Output XML file "); SetParameterDescription( "out", "Name of the XML file where the statistics are saved for future reuse" ); MandatoryOff("out"); } void DoUpdateParameters() { // Nothing to do here : all parameters are independent } void DoExecute() { //Statistics estimator typedef otb::StreamingStatisticsVectorImageFilter<FloatVectorImageType> StreamingStatisticsVImageFilterType; // Samples typedef double ValueType; typedef itk::VariableLengthVector<ValueType> MeasurementType; unsigned int nbSamples = 0; unsigned int nbBands = 0; // Build a Measurement Vector of mean MeasurementType mean; // Build a MeasurementVector of variance MeasurementType variance; FloatVectorImageListType* imageList = GetParameterImageList("il"); //Iterate over all input images for (unsigned int imageId = 0; imageId < imageList->Size(); ++imageId) { FloatVectorImageType* image = imageList->GetNthElement(imageId); if (nbBands == 0) { nbBands = image->GetNumberOfComponentsPerPixel(); } else if (nbBands != image->GetNumberOfComponentsPerPixel()) { itkExceptionMacro(<< "The image #" << imageId << " has " << image->GetNumberOfComponentsPerPixel() << " bands, while the first one has " << nbBands ); } FloatVectorImageType::SizeType size = image->GetLargestPossibleRegion().GetSize(); //Set the measurement vectors size if it's the first iteration if (imageId == 0) { mean.SetSize(nbBands); mean.Fill(0.); variance.SetSize(nbBands); variance.Fill(0.); } // Compute Statistics of each VectorImage StreamingStatisticsVImageFilterType::Pointer statsEstimator = StreamingStatisticsVImageFilterType::New(); statsEstimator->SetInput(image); statsEstimator->Update(); mean += statsEstimator->GetMean(); for (unsigned int itBand = 0; itBand < nbBands; itBand++) { variance[itBand] += (size[0] * size[1] - 1) * (statsEstimator->GetCovariance())(itBand, itBand); } //Increment nbSamples nbSamples += size[0] * size[1] * nbBands; } //Divide by the number of input images to get the mean over all layers mean /= imageList->Size(); //Apply the pooled variance formula variance /= (nbSamples - imageList->Size()); MeasurementType stddev; stddev.SetSize(nbBands); stddev.Fill(0.); for (unsigned int i = 0; i < variance.GetSize(); ++i) { stddev[i] = vcl_sqrt(variance[i]); } if( HasValue( "out" )==true ) { // Write the Statistics via the statistic writer typedef otb::StatisticsXMLFileWriter<MeasurementType> StatisticsWriter; StatisticsWriter::Pointer writer = StatisticsWriter::New(); writer->SetFileName(GetParameterString("out")); writer->AddInput("mean", mean); writer->AddInput("stddev", stddev); writer->Update(); } else { std::cout<<"Mean: "<<mean<<std::endl; std::cout<<"Standard Deviation: "<<stddev<<std::endl; } } itk::LightObject::Pointer m_FilterRef; }; } } OTB_APPLICATION_EXPORT(otb::Wrapper::EstimateImagesStatistics) <commit_msg>DOC: doc update.<commit_after>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "otbWrapperApplication.h" #include "otbWrapperApplicationFactory.h" #include "otbStatisticsXMLFileWriter.h" #include "otbStreamingStatisticsVectorImageFilter.h" namespace otb { namespace Wrapper { class EstimateImagesStatistics: public Application { public: /** Standard class typedefs. */ typedef EstimateImagesStatistics Self; typedef Application Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; /** Standard macro */ itkNewMacro(Self); itkTypeMacro(EstimateImagesStatistics, otb::Application); private: EstimateImagesStatistics() { SetName("EstimateImagesStatistics"); SetDescription("Estimates mean/standard deviation for all images in the input list and optionally saves the results in an XML file"); SetDocName("Estimate Image Statistics Application"); SetDocLongDescription("This application estimates mean/standard deviation for all images in the input list and optionally saves the results in an XML file."); SetDocLimitations("None"); SetDocAuthors("OTB-Team"); SetDocSeeAlso(" "); SetDocCLExample("otbApplicationLauncherCommandLine EstimateImagesStatistics ${OTB-BIN}/bin --il ${OTB-Data}/Input/Classification/QB_1_ortho.tif ${OTB-Data}/Input/Classification/QB_2_ortho.tif ${OTB-Data}/Input/Classification/QB_3_ortho.tif --out EstimateImageStatisticsQB123.xml"); AddDocTag("Classification"); } virtual ~EstimateImagesStatistics() { } void DoCreateParameters() { AddParameter(ParameterType_InputImageList, "il", "Input Image List"); SetParameterDescription( "il", "Input Image List filename." ); AddParameter(ParameterType_Filename, "out", "Output XML file"); SetParameterDescription( "out", "Name of the XML file where the statistics are saved for future reuse" ); MandatoryOff("out"); } void DoUpdateParameters() { // Nothing to do here : all parameters are independent } void DoExecute() { //Statistics estimator typedef otb::StreamingStatisticsVectorImageFilter<FloatVectorImageType> StreamingStatisticsVImageFilterType; // Samples typedef double ValueType; typedef itk::VariableLengthVector<ValueType> MeasurementType; unsigned int nbSamples = 0; unsigned int nbBands = 0; // Build a Measurement Vector of mean MeasurementType mean; // Build a MeasurementVector of variance MeasurementType variance; FloatVectorImageListType* imageList = GetParameterImageList("il"); //Iterate over all input images for (unsigned int imageId = 0; imageId < imageList->Size(); ++imageId) { FloatVectorImageType* image = imageList->GetNthElement(imageId); if (nbBands == 0) { nbBands = image->GetNumberOfComponentsPerPixel(); } else if (nbBands != image->GetNumberOfComponentsPerPixel()) { itkExceptionMacro(<< "The image #" << imageId << " has " << image->GetNumberOfComponentsPerPixel() << " bands, while the first one has " << nbBands ); } FloatVectorImageType::SizeType size = image->GetLargestPossibleRegion().GetSize(); //Set the measurement vectors size if it's the first iteration if (imageId == 0) { mean.SetSize(nbBands); mean.Fill(0.); variance.SetSize(nbBands); variance.Fill(0.); } // Compute Statistics of each VectorImage StreamingStatisticsVImageFilterType::Pointer statsEstimator = StreamingStatisticsVImageFilterType::New(); statsEstimator->SetInput(image); statsEstimator->Update(); mean += statsEstimator->GetMean(); for (unsigned int itBand = 0; itBand < nbBands; itBand++) { variance[itBand] += (size[0] * size[1] - 1) * (statsEstimator->GetCovariance())(itBand, itBand); } //Increment nbSamples nbSamples += size[0] * size[1] * nbBands; } //Divide by the number of input images to get the mean over all layers mean /= imageList->Size(); //Apply the pooled variance formula variance /= (nbSamples - imageList->Size()); MeasurementType stddev; stddev.SetSize(nbBands); stddev.Fill(0.); for (unsigned int i = 0; i < variance.GetSize(); ++i) { stddev[i] = vcl_sqrt(variance[i]); } if( HasValue( "out" )==true ) { // Write the Statistics via the statistic writer typedef otb::StatisticsXMLFileWriter<MeasurementType> StatisticsWriter; StatisticsWriter::Pointer writer = StatisticsWriter::New(); writer->SetFileName(GetParameterString("out")); writer->AddInput("mean", mean); writer->AddInput("stddev", stddev); writer->Update(); } else { std::cout<<"Mean: "<<mean<<std::endl; std::cout<<"Standard Deviation: "<<stddev<<std::endl; } } itk::LightObject::Pointer m_FilterRef; }; } } OTB_APPLICATION_EXPORT(otb::Wrapper::EstimateImagesStatistics) <|endoftext|>
<commit_before>/* * Copyright (c) 2016-2017 metaverse core developers (see MVS-AUTHORS). * Copyright (C) 2013, 2016 Swirly Cloud Limited. * * This program is free software; you can redistribute it and/or modify it under the terms of the * GNU General Public License as published by the Free Software Foundation; either version 2 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program; if * not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. */ #include <thread> #include <sstream> #include <metaverse/explorer/json_helper.hpp> #include <metaverse/mgbubble/WsPushServ.hpp> #include <metaverse/server/server_node.hpp> namespace mgbubble { constexpr auto EV_VERSION = "version"; constexpr auto EV_SUBSCRIBE = "subscribe"; constexpr auto EV_UNSUBSCRIBE = "unsubscribe"; constexpr auto EV_SUBSCRIBED = "subscribed"; constexpr auto EV_UNSUBSCRIBED = "unsubscribed"; constexpr auto EV_PUBLISH = "publish"; constexpr auto EV_REQUEST = "request"; constexpr auto EV_RESPONSE = "response"; constexpr auto EV_MG_ERROR = "error"; constexpr auto EV_INFO = "info"; constexpr auto CH_BLOCK = "block"; constexpr auto CH_TRANSACTION = "tx"; } namespace mgbubble { using namespace bc; using namespace libbitcoin; void WsPushServ::run() { log::info(NAME) << "Websocket Service listen on " << node_.server_settings().websocket_listen; node_.subscribe_stop([this](const libbitcoin::code& ec) { stop(); }); node_.subscribe_transaction_pool( std::bind(&WsPushServ::handle_transaction_pool, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)); node_.subscribe_blockchain( std::bind(&WsPushServ::handle_blockchain_reorganization, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4)); base::run(); log::info(NAME) << "Websocket Service Stopped."; } bool WsPushServ::start() { if (node_.server_settings().websocket_service_enabled == false) return true; if (!attach_notify()) return false; return base::start(); } void WsPushServ::spawn_to_mongoose(const std::function<void(uint64_t)>&& handler) { auto msg = std::make_shared<WsEvent>(std::move(handler)); struct mg_event ev { msg->hook() }; if (!notify(ev)) msg->unhook(); } bool WsPushServ::handle_transaction_pool(const code& ec, const index_list&, message::transaction_message::ptr tx) { if (stopped()) return false; if (ec == (code)error::mock || ec == (code)error::service_stopped) return true; if (ec) { log::debug(NAME) << "Failure handling new transaction: " << ec.message(); return true; } notify_transaction(0, null_hash, *tx); return true; } bool WsPushServ::handle_blockchain_reorganization(const code& ec, uint64_t fork_point, const block_list& new_blocks, const block_list&) { if (stopped()) return false; if (ec == (code)error::mock || ec == (code)error::service_stopped) return true; if (ec) { log::debug(NAME) << "Failure handling new block: " << ec.message(); return true; } const auto fork_point32 = static_cast<uint32_t>(fork_point); notify_blocks(fork_point32, new_blocks); return true; } void WsPushServ::notify_blocks(uint32_t fork_point, const block_list& blocks) { if (stopped()) return; auto height = fork_point; for (const auto block : blocks) notify_block(height++, block); } void WsPushServ::notify_block(uint32_t height, const block::ptr block) { if (stopped()) return; const auto block_hash = block->header.hash(); for (const auto& tx : block->transactions) { const auto tx_hash = tx.hash(); notify_transaction(height, block_hash, tx); } } void WsPushServ::notify_transaction(uint32_t height, const hash_digest& block_hash, const transaction& tx) { if (stopped() || tx.outputs.empty()) return; std::map<std::weak_ptr<mg_connection>, std::vector<size_t>, std::owner_less<std::weak_ptr<mg_connection>>> subscribers; { std::lock_guard<std::mutex> guard(subscribers_lock_); if (subscribers_.size() == 0) return; for (auto& con : subscribers_) { if (!con.first.expired()) { subscribers.insert(con); } } if (subscribers.size() != subscribers_.size()) subscribers_ = subscribers; } /* ---------- may has subscribers ---------- */ std::vector<size_t> tx_addrs; for (const auto& input : tx.inputs) { const auto address = payment_address::extract(input.script); if (address) tx_addrs.push_back(std::hash<payment_address>()(address)); } for (const auto& output : tx.outputs) { const auto address = payment_address::extract(output.script); if (address) tx_addrs.push_back(std::hash<payment_address>()(address)); } std::vector<std::weak_ptr<mg_connection>> notify_cons; for (auto& sub : subscribers) { auto& sub_addrs = sub.second; bool bnotify = sub_addrs.size() == 0 ? true : std::any_of(sub_addrs.begin(), sub_addrs.end(), [&tx_addrs](size_t addr_hash) { return tx_addrs.end() != std::find(tx_addrs.begin(), tx_addrs.end(), addr_hash); }); if (bnotify) notify_cons.push_back(sub.first); } if (notify_cons.size() == 0) return; log::info(NAME) << " ******** notify_transaction: height [" << height << "] ******** "; Json::Value root; root["event"] = EV_PUBLISH; root["channel"] = CH_TRANSACTION; root["result"] = explorer::config::json_helper().prop_list(tx, height, true); auto rep = std::make_shared<std::string>(std::move(root.toStyledString())); for (auto& con : notify_cons) { auto shared_con = con.lock(); if (!shared_con) continue; spawn_to_mongoose([this, shared_con, rep](uint64_t id) { size_t active_connections = 0; auto* mgr = &this->mg_mgr(); auto* notify_nc = shared_con.get(); for (auto* nc = mg_next(mgr, NULL); nc != NULL; nc = mg_next(mgr, nc)) { if (!is_websocket(*nc) || is_listen_socket(*nc) || is_notify_socket(*nc)) continue; ++active_connections; if (notify_nc == nc) send_frame(*nc, *rep); } if (active_connections != map_connections_.size()) refresh_connections(); }); } } void WsPushServ::send_bad_response(struct mg_connection& nc, const char* message) { Json::Value root; Json::Value result; result["code"] = 1000001; result["message"] = message ? message : "bad request"; root["event"] = EV_MG_ERROR; root["result"] = result; auto&& tmp = root.toStyledString(); send_frame(nc, tmp.c_str(), tmp.size()); } void WsPushServ::send_response(struct mg_connection& nc, const std::string& event, const std::string& channel) { Json::Value root; root["event"] = event; root["channel"] = channel; auto&& tmp = root.toStyledString(); send_frame(nc, tmp.c_str(), tmp.size()); } void WsPushServ::refresh_connections() { auto* mgr = &mg_mgr(); std::unordered_map<void*, std::shared_ptr<mg_connection>> swap; for (auto* nc = mg_next(mgr, NULL); nc != NULL; nc = mg_next(mgr, nc)) { if (!is_websocket(*nc) || is_listen_socket(*nc) || is_notify_socket(*nc)) continue; std::shared_ptr<struct mg_connection> con(nc, [](struct mg_connection* ptr) { (void)(ptr); }); swap.emplace(&nc, con); } map_connections_.swap(swap); } void WsPushServ::on_ws_handshake_done_handler(struct mg_connection& nc) { std::shared_ptr<struct mg_connection> con(&nc, [](struct mg_connection* ptr) { (void)(ptr); }); map_connections_.emplace(&nc, con); std::string version("{\"event\": \"version\", " "\"result\": \"" MVS_VERSION "\"}"); send_frame(nc, version); std::stringstream ss; Json::Value root; Json::Value connections; connections["connections"] = map_connections_.size(); root["event"] = EV_INFO; root["result"] = connections; auto&& tmp = root.toStyledString(); send_frame(nc, tmp); } void WsPushServ::on_ws_frame_handler(struct mg_connection& nc, websocket_message& msg) { Json::Reader reader; Json::Value root; try { const char* begin = (const char*)msg.data; const char* end = begin + msg.size; if (!reader.parse(begin, end, root) || !root.isObject() || !root["event"].isString() || !root["channel"].isString() || !root["address"].isString()) { stringstream ss; ss << "parse request error, " << reader.getFormattedErrorMessages(); throw std::runtime_error(ss.str()); return; } auto event = root["event"].asString(); auto channel = root["channel"].asString(); if ((event == EV_SUBSCRIBE) && (channel == CH_TRANSACTION)) { auto short_addr = root["address"].asString(); auto pay_addr = payment_address(short_addr); if (!short_addr.empty() && !pay_addr) { send_bad_response(nc, "invalid address."); } else { size_t hash_addr = short_addr.empty() ? 0 : std::hash<payment_address>()(pay_addr); auto it = map_connections_.find(&nc); if (it != map_connections_.end()) { std::lock_guard<std::mutex> guard(subscribers_lock_); std::weak_ptr<struct mg_connection> week_con(it->second); auto sub_it = subscribers_.find(week_con); if (sub_it != subscribers_.end()) { auto& sub_list = sub_it->second; if (hash_addr == 0) { sub_list.clear(); send_response(nc, EV_SUBSCRIBED, channel); } else { if (sub_list.end() == std::find(sub_list.begin(), sub_list.end(), hash_addr)) { sub_list.push_back(hash_addr); send_response(nc, EV_SUBSCRIBED, channel); } else { send_bad_response(nc, "address already subscribed."); } } } else { if (hash_addr == 0) subscribers_.insert({ week_con, {} }); else subscribers_.insert({ week_con, { hash_addr } }); send_response(nc, EV_SUBSCRIBED, channel); } } else { send_bad_response(nc, "connection lost."); } } } else if ((event == EV_UNSUBSCRIBE) && (channel == CH_TRANSACTION)) { auto it = map_connections_.find(&nc); if (it != map_connections_.end()) { std::lock_guard<std::mutex> guard(subscribers_lock_); std::weak_ptr<struct mg_connection> week_con(it->second); subscribers_.erase(week_con); send_response(nc, EV_UNSUBSCRIBED, channel); } else { send_bad_response(nc, "no subscription."); } } else { send_bad_response(nc, "request not support."); } } catch (std::exception& e) { log::info(NAME) << "on on_ws_frame_handler: " << e.what(); send_bad_response(nc); } } void WsPushServ::on_close_handler(struct mg_connection& nc) { if (is_websocket(nc)) { map_connections_.erase(&nc); } } void WsPushServ::on_broadcast(struct mg_connection& nc, const char* ev_data) { if (is_listen_socket(nc) || is_notify_socket(nc)) return; send_frame(nc, ev_data, strlen(ev_data)); } void WsPushServ::on_send_handler(struct mg_connection& nc, int bytes_transfered) { } void WsPushServ::on_notify_handler(struct mg_connection& nc, struct mg_event& ev) { static uint64_t api_call_counter = 0; if (ev.data == nullptr) return; auto& msg = *(WsEvent*)ev.data; msg(++api_call_counter); } } <commit_msg>compiling issue, compatible for osx<commit_after>/* * Copyright (c) 2016-2017 metaverse core developers (see MVS-AUTHORS). * Copyright (C) 2013, 2016 Swirly Cloud Limited. * * This program is free software; you can redistribute it and/or modify it under the terms of the * GNU General Public License as published by the Free Software Foundation; either version 2 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program; if * not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. */ #include <thread> #include <sstream> #include <metaverse/explorer/json_helper.hpp> #include <metaverse/mgbubble/WsPushServ.hpp> #include <metaverse/server/server_node.hpp> namespace mgbubble { constexpr auto EV_VERSION = "version"; constexpr auto EV_SUBSCRIBE = "subscribe"; constexpr auto EV_UNSUBSCRIBE = "unsubscribe"; constexpr auto EV_SUBSCRIBED = "subscribed"; constexpr auto EV_UNSUBSCRIBED = "unsubscribed"; constexpr auto EV_PUBLISH = "publish"; constexpr auto EV_REQUEST = "request"; constexpr auto EV_RESPONSE = "response"; constexpr auto EV_MG_ERROR = "error"; constexpr auto EV_INFO = "info"; constexpr auto CH_BLOCK = "block"; constexpr auto CH_TRANSACTION = "tx"; } namespace mgbubble { using namespace bc; using namespace libbitcoin; void WsPushServ::run() { log::info(NAME) << "Websocket Service listen on " << node_.server_settings().websocket_listen; node_.subscribe_stop([this](const libbitcoin::code& ec) { stop(); }); node_.subscribe_transaction_pool( std::bind(&WsPushServ::handle_transaction_pool, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)); node_.subscribe_blockchain( std::bind(&WsPushServ::handle_blockchain_reorganization, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4)); base::run(); log::info(NAME) << "Websocket Service Stopped."; } bool WsPushServ::start() { if (node_.server_settings().websocket_service_enabled == false) return true; if (!attach_notify()) return false; return base::start(); } void WsPushServ::spawn_to_mongoose(const std::function<void(uint64_t)>&& handler) { auto msg = std::make_shared<WsEvent>(std::move(handler)); struct mg_event ev { msg->hook() }; if (!notify(ev)) msg->unhook(); } bool WsPushServ::handle_transaction_pool(const code& ec, const index_list&, message::transaction_message::ptr tx) { if (stopped()) return false; if (ec == (code)error::mock || ec == (code)error::service_stopped) return true; if (ec) { log::debug(NAME) << "Failure handling new transaction: " << ec.message(); return true; } notify_transaction(0, null_hash, *tx); return true; } bool WsPushServ::handle_blockchain_reorganization(const code& ec, uint64_t fork_point, const block_list& new_blocks, const block_list&) { if (stopped()) return false; if (ec == (code)error::mock || ec == (code)error::service_stopped) return true; if (ec) { log::debug(NAME) << "Failure handling new block: " << ec.message(); return true; } const auto fork_point32 = static_cast<uint32_t>(fork_point); notify_blocks(fork_point32, new_blocks); return true; } void WsPushServ::notify_blocks(uint32_t fork_point, const block_list& blocks) { if (stopped()) return; auto height = fork_point; for (const auto block : blocks) notify_block(height++, block); } void WsPushServ::notify_block(uint32_t height, const block::ptr block) { if (stopped()) return; const auto block_hash = block->header.hash(); for (const auto& tx : block->transactions) { const auto tx_hash = tx.hash(); notify_transaction(height, block_hash, tx); } } void WsPushServ::notify_transaction(uint32_t height, const hash_digest& block_hash, const transaction& tx) { if (stopped() || tx.outputs.empty()) return; std::map<std::weak_ptr<mg_connection>, std::vector<size_t>, std::owner_less<std::weak_ptr<mg_connection>>> subscribers; { std::lock_guard<std::mutex> guard(subscribers_lock_); if (subscribers_.size() == 0) return; for (auto& con : subscribers_) { if (!con.first.expired()) { subscribers.insert(con); } } if (subscribers.size() != subscribers_.size()) subscribers_ = subscribers; } /* ---------- may has subscribers ---------- */ std::vector<size_t> tx_addrs; for (const auto& input : tx.inputs) { const auto address = payment_address::extract(input.script); if (address) tx_addrs.push_back(std::hash<payment_address>()(address)); } for (const auto& output : tx.outputs) { const auto address = payment_address::extract(output.script); if (address) tx_addrs.push_back(std::hash<payment_address>()(address)); } std::vector<std::weak_ptr<mg_connection>> notify_cons; for (auto& sub : subscribers) { auto& sub_addrs = sub.second; bool bnotify = sub_addrs.size() == 0 ? true : std::any_of(sub_addrs.begin(), sub_addrs.end(), [&tx_addrs](size_t addr_hash) { return tx_addrs.end() != std::find(tx_addrs.begin(), tx_addrs.end(), addr_hash); }); if (bnotify) notify_cons.push_back(sub.first); } if (notify_cons.size() == 0) return; log::info(NAME) << " ******** notify_transaction: height [" << height << "] ******** "; Json::Value root; root["event"] = EV_PUBLISH; root["channel"] = CH_TRANSACTION; root["result"] = explorer::config::json_helper().prop_list(tx, height, true); auto rep = std::make_shared<std::string>(root.toStyledString()); for (auto& con : notify_cons) { auto shared_con = con.lock(); if (!shared_con) continue; spawn_to_mongoose([this, shared_con, rep](uint64_t id) { size_t active_connections = 0; auto* mgr = &this->mg_mgr(); auto* notify_nc = shared_con.get(); for (auto* nc = mg_next(mgr, NULL); nc != NULL; nc = mg_next(mgr, nc)) { if (!is_websocket(*nc) || is_listen_socket(*nc) || is_notify_socket(*nc)) continue; ++active_connections; if (notify_nc == nc) send_frame(*nc, *rep); } if (active_connections != map_connections_.size()) refresh_connections(); }); } } void WsPushServ::send_bad_response(struct mg_connection& nc, const char* message) { Json::Value root; Json::Value result; result["code"] = 1000001; result["message"] = message ? message : "bad request"; root["event"] = EV_MG_ERROR; root["result"] = result; auto&& tmp = root.toStyledString(); send_frame(nc, tmp.c_str(), tmp.size()); } void WsPushServ::send_response(struct mg_connection& nc, const std::string& event, const std::string& channel) { Json::Value root; root["event"] = event; root["channel"] = channel; auto&& tmp = root.toStyledString(); send_frame(nc, tmp.c_str(), tmp.size()); } void WsPushServ::refresh_connections() { auto* mgr = &mg_mgr(); std::unordered_map<void*, std::shared_ptr<mg_connection>> swap; for (auto* nc = mg_next(mgr, NULL); nc != NULL; nc = mg_next(mgr, nc)) { if (!is_websocket(*nc) || is_listen_socket(*nc) || is_notify_socket(*nc)) continue; std::shared_ptr<struct mg_connection> con(nc, [](struct mg_connection* ptr) { (void)(ptr); }); swap.emplace(&nc, con); } map_connections_.swap(swap); } void WsPushServ::on_ws_handshake_done_handler(struct mg_connection& nc) { std::shared_ptr<struct mg_connection> con(&nc, [](struct mg_connection* ptr) { (void)(ptr); }); map_connections_.emplace(&nc, con); std::string version("{\"event\": \"version\", " "\"result\": \"" MVS_VERSION "\"}"); send_frame(nc, version); std::stringstream ss; Json::Value root; Json::Value connections; connections["connections"] = static_cast<uint64_t>(map_connections_.size()); root["event"] = EV_INFO; root["result"] = connections; auto&& tmp = root.toStyledString(); send_frame(nc, tmp); } void WsPushServ::on_ws_frame_handler(struct mg_connection& nc, websocket_message& msg) { Json::Reader reader; Json::Value root; try { const char* begin = (const char*)msg.data; const char* end = begin + msg.size; if (!reader.parse(begin, end, root) || !root.isObject() || !root["event"].isString() || !root["channel"].isString() || !root["address"].isString()) { stringstream ss; ss << "parse request error, " << reader.getFormattedErrorMessages(); throw std::runtime_error(ss.str()); return; } auto event = root["event"].asString(); auto channel = root["channel"].asString(); if ((event == EV_SUBSCRIBE) && (channel == CH_TRANSACTION)) { auto short_addr = root["address"].asString(); auto pay_addr = payment_address(short_addr); if (!short_addr.empty() && !pay_addr) { send_bad_response(nc, "invalid address."); } else { size_t hash_addr = short_addr.empty() ? 0 : std::hash<payment_address>()(pay_addr); auto it = map_connections_.find(&nc); if (it != map_connections_.end()) { std::lock_guard<std::mutex> guard(subscribers_lock_); std::weak_ptr<struct mg_connection> week_con(it->second); auto sub_it = subscribers_.find(week_con); if (sub_it != subscribers_.end()) { auto& sub_list = sub_it->second; if (hash_addr == 0) { sub_list.clear(); send_response(nc, EV_SUBSCRIBED, channel); } else { if (sub_list.end() == std::find(sub_list.begin(), sub_list.end(), hash_addr)) { sub_list.push_back(hash_addr); send_response(nc, EV_SUBSCRIBED, channel); } else { send_bad_response(nc, "address already subscribed."); } } } else { if (hash_addr == 0) subscribers_.insert({ week_con, {} }); else subscribers_.insert({ week_con, { hash_addr } }); send_response(nc, EV_SUBSCRIBED, channel); } } else { send_bad_response(nc, "connection lost."); } } } else if ((event == EV_UNSUBSCRIBE) && (channel == CH_TRANSACTION)) { auto it = map_connections_.find(&nc); if (it != map_connections_.end()) { std::lock_guard<std::mutex> guard(subscribers_lock_); std::weak_ptr<struct mg_connection> week_con(it->second); subscribers_.erase(week_con); send_response(nc, EV_UNSUBSCRIBED, channel); } else { send_bad_response(nc, "no subscription."); } } else { send_bad_response(nc, "request not support."); } } catch (std::exception& e) { log::info(NAME) << "on on_ws_frame_handler: " << e.what(); send_bad_response(nc); } } void WsPushServ::on_close_handler(struct mg_connection& nc) { if (is_websocket(nc)) { map_connections_.erase(&nc); } } void WsPushServ::on_broadcast(struct mg_connection& nc, const char* ev_data) { if (is_listen_socket(nc) || is_notify_socket(nc)) return; send_frame(nc, ev_data, strlen(ev_data)); } void WsPushServ::on_send_handler(struct mg_connection& nc, int bytes_transfered) { } void WsPushServ::on_notify_handler(struct mg_connection& nc, struct mg_event& ev) { static uint64_t api_call_counter = 0; if (ev.data == nullptr) return; auto& msg = *(WsEvent*)ev.data; msg(++api_call_counter); } } <|endoftext|>
<commit_before>#include "upsample.h" void upsample(const std::vector<complex> &input, float n, std::vector<complex> &output) { int M = input.size(); int N; for (int i=0; i<24; i++) { if (M <= (1<<i)) { N = 1<<i; break; } } int L = N + int((n-1)*N); std::vector<complex> x(input); x.resize(N); fft(&x[0], N); x.resize(L); for (int i=N-1; i>=N/2; i--) x[L-N+i] = x[i]; for (int i=N/2; i<L-N/2; i++) x[i] = 0; ifft(&x[0], N); output.assign(x.begin(), x.begin() + int(M*n)); } <commit_msg>Fixed upsample<commit_after>#include "upsample.h" void upsample(const std::vector<complex> &input, float n, std::vector<complex> &output) { int M = input.size(); int N; for (int i=0; i<24; i++) { if (M <= (1<<i)) { N = 1<<i; break; } } int L = N + int((n-1)*N); std::vector<complex> x(input); x.resize(N); fft(&x[0], N); x.resize(L); for (int i=N-1; i>=N/2; i--) x[L-N+i] = x[i]; for (int i=N/2; i<L-N/2; i++) x[i] = 0; ifft(&x[0], L); output.assign(x.begin(), x.begin() + int(M*n)); } <|endoftext|>
<commit_before>// This file is part of the "x0" project, http://github.com/christianparpart/x0> // (c) 2009-2017 Christian Parpart <[email protected]> // // Licensed under the MIT License (the "License"); you may not use this // file except in compliance with the License. You may obtain a copy of // the License at: http://opensource.org/licenses/MIT #include <xzero/io/OutputStream.h> #include <xzero/RuntimeError.h> namespace xzero { int OutputStream::write(const std::string& data) { return write(data.data(), data.size()); } int OutputStream::printf(const char* fmt, ...) { char buf[8192]; va_list args; va_start(args, fmt); int pos = vsnprintf(buf, sizeof(buf), fmt, args); va_end(args); if (pos < 0) { RAISE_ERRNO(errno); } if (static_cast<size_t>(pos) < sizeof(buf)) { write(buf, pos); } else { RAISE_ERRNO(errno); } return pos; } } // namespace xzero <commit_msg>[xzero] OutputStream: adds missing include<commit_after>// This file is part of the "x0" project, http://github.com/christianparpart/x0> // (c) 2009-2017 Christian Parpart <[email protected]> // // Licensed under the MIT License (the "License"); you may not use this // file except in compliance with the License. You may obtain a copy of // the License at: http://opensource.org/licenses/MIT #include <xzero/io/OutputStream.h> #include <xzero/RuntimeError.h> #include <stdarg.h> namespace xzero { int OutputStream::write(const std::string& data) { return write(data.data(), data.size()); } int OutputStream::printf(const char* fmt, ...) { char buf[8192]; va_list args; va_start(args, fmt); int pos = vsnprintf(buf, sizeof(buf), fmt, args); va_end(args); if (pos < 0) { RAISE_ERRNO(errno); } if (static_cast<size_t>(pos) < sizeof(buf)) { write(buf, pos); } else { RAISE_ERRNO(errno); } return pos; } } // namespace xzero <|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 * * 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. * ************************************************************************/ #include "vcl/oldprintadaptor.hxx" #include "vcl/gdimtf.hxx" #include "com/sun/star/awt/Size.hpp" #include <vector> namespace vcl { struct AdaptorPage { GDIMetaFile maPage; com::sun::star::awt::Size maPageSize; }; struct ImplOldStyleAdaptorData { std::vector< AdaptorPage > maPages; }; } using namespace vcl; using namespace cppu; using namespace com::sun::star; using namespace com::sun::star::uno; using namespace com::sun::star::beans; OldStylePrintAdaptor::OldStylePrintAdaptor( const boost::shared_ptr< Printer >& i_pPrinter ) : PrinterListener( i_pPrinter ) , mpData( new ImplOldStyleAdaptorData() ) { } OldStylePrintAdaptor::~OldStylePrintAdaptor() { } void OldStylePrintAdaptor::StartPage() { Size aPaperSize( getPrinter()->PixelToLogic( getPrinter()->GetPaperSizePixel(), MapMode( MAP_100TH_MM ) ) ); mpData->maPages.push_back( AdaptorPage() ); mpData->maPages.back().maPageSize.Width = aPaperSize.getWidth(); mpData->maPages.back().maPageSize.Height = aPaperSize.getHeight(); getPrinter()->SetConnectMetaFile( &mpData->maPages.back().maPage ); } void OldStylePrintAdaptor::EndPage() { getPrinter()->SetConnectMetaFile( NULL ); mpData->maPages.back().maPage.WindStart(); } int OldStylePrintAdaptor::getPageCount() const { return int(mpData->maPages.size()); } Sequence< PropertyValue > OldStylePrintAdaptor::getPageParameters( int i_nPage ) const { Sequence< PropertyValue > aRet( 1 ); aRet[0].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("PageSize") ); if( i_nPage < int(mpData->maPages.size() ) ) aRet[0].Value = makeAny( mpData->maPages[i_nPage].maPageSize ); else { awt::Size aEmpty( 0, 0 ); aRet[0].Value = makeAny( aEmpty ); } return aRet; } void OldStylePrintAdaptor::printPage( int i_nPage ) const { if( i_nPage < int(mpData->maPages.size()) ) { mpData->maPages[ i_nPage ].maPage.WindStart(); mpData->maPages[ i_nPage ].maPage.Play( getPrinter().get() ); } } <commit_msg>add missing precompiled header<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 * * 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. * ************************************************************************/ #include "precompiled_vcl.hxx" #include "vcl/oldprintadaptor.hxx" #include "vcl/gdimtf.hxx" #include "com/sun/star/awt/Size.hpp" #include <vector> namespace vcl { struct AdaptorPage { GDIMetaFile maPage; com::sun::star::awt::Size maPageSize; }; struct ImplOldStyleAdaptorData { std::vector< AdaptorPage > maPages; }; } using namespace vcl; using namespace cppu; using namespace com::sun::star; using namespace com::sun::star::uno; using namespace com::sun::star::beans; OldStylePrintAdaptor::OldStylePrintAdaptor( const boost::shared_ptr< Printer >& i_pPrinter ) : PrinterListener( i_pPrinter ) , mpData( new ImplOldStyleAdaptorData() ) { } OldStylePrintAdaptor::~OldStylePrintAdaptor() { } void OldStylePrintAdaptor::StartPage() { Size aPaperSize( getPrinter()->PixelToLogic( getPrinter()->GetPaperSizePixel(), MapMode( MAP_100TH_MM ) ) ); mpData->maPages.push_back( AdaptorPage() ); mpData->maPages.back().maPageSize.Width = aPaperSize.getWidth(); mpData->maPages.back().maPageSize.Height = aPaperSize.getHeight(); getPrinter()->SetConnectMetaFile( &mpData->maPages.back().maPage ); } void OldStylePrintAdaptor::EndPage() { getPrinter()->SetConnectMetaFile( NULL ); mpData->maPages.back().maPage.WindStart(); } int OldStylePrintAdaptor::getPageCount() const { return int(mpData->maPages.size()); } Sequence< PropertyValue > OldStylePrintAdaptor::getPageParameters( int i_nPage ) const { Sequence< PropertyValue > aRet( 1 ); aRet[0].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("PageSize") ); if( i_nPage < int(mpData->maPages.size() ) ) aRet[0].Value = makeAny( mpData->maPages[i_nPage].maPageSize ); else { awt::Size aEmpty( 0, 0 ); aRet[0].Value = makeAny( aEmpty ); } return aRet; } void OldStylePrintAdaptor::printPage( int i_nPage ) const { if( i_nPage < int(mpData->maPages.size()) ) { mpData->maPages[ i_nPage ].maPage.WindStart(); mpData->maPages[ i_nPage ].maPage.Play( getPrinter().get() ); } } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: taskpanelist.cxx,v $ * * $Revision: 1.8 $ * * last change: $Author: hr $ $Date: 2002-03-19 10:51:43 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _SV_SVDATA_HXX #include <svdata.hxx> #endif #ifndef _RCID_H #include <rcid.h> #endif #ifndef _SV_DOCKWIN_HXX #include <dockwin.hxx> #endif #include <taskpanelist.hxx> #include <functional> #include <algorithm> // can't have static linkage because SUNPRO 5.2 complains Point ImplTaskPaneListGetPos( const Window *w ) { Point pos; if( w->ImplIsDockingWindow() ) { pos = ((DockingWindow*)w)->GetPosPixel(); Window *pF = ((DockingWindow*)w)->GetFloatingWindow(); if( pF ) pos = pF->OutputToAbsoluteScreenPixel( pF->ScreenToOutputPixel( pos ) ); else pos = w->OutputToAbsoluteScreenPixel( pos ); } else pos = w->OutputToAbsoluteScreenPixel( w->GetPosPixel() ); return pos; } // compares window pos left-to-right struct LTRSort : public ::std::binary_function< const Window*, const Window*, bool > { bool operator()( const Window* w1, const Window* w2 ) const { Point pos1(ImplTaskPaneListGetPos( w1 )); Point pos2(ImplTaskPaneListGetPos( w2 )); if( pos1.X() == pos2.X() ) return ( pos1.Y() < pos2.Y() ); else return ( pos1.X() < pos2.X() ); } }; struct LTRSortBackward : public ::std::binary_function< const Window*, const Window*, bool > { bool operator()( const Window* w2, const Window* w1 ) const { Point pos1(ImplTaskPaneListGetPos( w1 )); Point pos2(ImplTaskPaneListGetPos( w2 )); if( pos1.X() == pos2.X() ) return ( pos1.Y() < pos2.Y() ); else return ( pos1.X() < pos2.X() ); } }; // -------------------------------------------------- TaskPaneList::TaskPaneList() { } TaskPaneList::~TaskPaneList() { } // -------------------------------------------------- void TaskPaneList::AddWindow( Window *pWindow ) { bool bDockingWindow=false; bool bToolbox=false; bool bDialog=false; bool bUnknown=false; if( pWindow ) { if( pWindow->GetType() == RSC_DOCKINGWINDOW ) bDockingWindow = true; else if( pWindow->GetType() == RSC_TOOLBOX ) bToolbox = true; else if( pWindow->IsDialog() ) bDialog = true; else bUnknown = true; ::std::vector< Window* >::iterator p; p = ::std::find( mTaskPanes.begin(), mTaskPanes.end(), pWindow ); // avoid duplicates if( p == mTaskPanes.end() ) // not found mTaskPanes.push_back( pWindow ); } } // -------------------------------------------------- void TaskPaneList::RemoveWindow( Window *pWindow ) { ::std::vector< Window* >::iterator p; p = ::std::find( mTaskPanes.begin(), mTaskPanes.end(), pWindow ); if( p != mTaskPanes.end() ) mTaskPanes.erase( p ); } // -------------------------------------------------- BOOL TaskPaneList::HandleKeyEvent( KeyEvent aKeyEvent ) { BOOL bFloatsOnly = FALSE; BOOL bFocusInList = FALSE; KeyCode aKeyCode = aKeyEvent.GetKeyCode(); BOOL bForward = !aKeyCode.IsShift(); if( ( aKeyCode.IsMod1() && aKeyCode.GetCode() == KEY_TAB ) // Ctrl-TAB || ( bFloatsOnly = ( aKeyCode.GetCode()) == KEY_F6 ) // F6 ) { // is the focus in the list ? BOOL bHasFocus = FALSE; ::std::vector< Window* >::iterator p = mTaskPanes.begin(); while( p != mTaskPanes.end() ) { Window *pWin = *p; if( (*p)->HasChildPathFocus( TRUE ) ) { // F6 works only in floaters if( bFloatsOnly && (*p)->GetType() != RSC_DOCKINGWINDOW && !(*p)->IsDialog() ) return FALSE; bFocusInList = TRUE; // activate next task pane Window *pNextWin = bFloatsOnly ? FindNextFloat( *p, bForward ) : FindNextPane( *p, bForward ); if( pNextWin != pWin ) { ImplGetSVData()->maWinData.mbNoSaveFocus = TRUE; pNextWin->GrabFocus(); ImplGetSVData()->maWinData.mbNoSaveFocus = FALSE; } else { // we did not find another taskpane, so // put focus back into document: use frame win of topmost parent while( pWin ) { if( !pWin->GetParent() ) { pWin->ImplGetFrameWindow()->GetWindow( WINDOW_CLIENT )->GrabFocus(); break; } pWin = pWin->GetParent(); } } return TRUE; } else p++; } // the focus is not in the list: activate first float if F6 was pressed if( !bFocusInList && bFloatsOnly ) { Window *pWin = FindNextFloat( NULL, bForward ); if( pWin ) { pWin->GrabFocus(); return TRUE; } } } return FALSE; } // -------------------------------------------------- // returns next valid pane Window* TaskPaneList::FindNextPane( Window *pWindow, BOOL bForward ) { if( bForward ) ::std::stable_sort( mTaskPanes.begin(), mTaskPanes.end(), LTRSort() ); else ::std::stable_sort( mTaskPanes.begin(), mTaskPanes.end(), LTRSortBackward() ); ::std::vector< Window* >::iterator p = mTaskPanes.begin(); while( p != mTaskPanes.end() ) { if( *p == pWindow ) { unsigned n = mTaskPanes.size(); while( --n ) { if( ++p == mTaskPanes.end() ) p = mTaskPanes.begin(); if( (*p)->IsVisible() ) return *p; } break; } else ++p; } return pWindow; // nothing found } // -------------------------------------------------- // returns first valid float if pWindow==0, otherwise returns next valid float Window* TaskPaneList::FindNextFloat( Window *pWindow, BOOL bForward ) { if( bForward ) ::std::stable_sort( mTaskPanes.begin(), mTaskPanes.end(), LTRSort() ); else ::std::stable_sort( mTaskPanes.begin(), mTaskPanes.end(), LTRSortBackward() ); ::std::vector< Window* >::iterator p = mTaskPanes.begin(); while( p != mTaskPanes.end() ) { if( !pWindow || *p == pWindow ) { while( p != mTaskPanes.end() ) { if( pWindow ) // increment before test ++p; if( p == mTaskPanes.end() ) return pWindow; // do not wrap, send focus back to document at end of list if( (*p)->IsVisible() && ( (*p)->GetType() == RSC_DOCKINGWINDOW || (*p)->IsDialog() ) ) return *p; if( !pWindow ) // increment after test, otherwise first element is skipped ++p; } break; } else ++p; } return pWindow; // nothing found } // -------------------------------------------------- <commit_msg>#96972# now f6 cycles through everything and ctrl-tab only menu-toolbar-floats<commit_after>/************************************************************************* * * $RCSfile: taskpanelist.cxx,v $ * * $Revision: 1.9 $ * * last change: $Author: ssa $ $Date: 2002-03-22 13:08:08 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _SV_SVDATA_HXX #include <svdata.hxx> #endif #ifndef _RCID_H #include <rcid.h> #endif #ifndef _SV_DOCKWIN_HXX #include <dockwin.hxx> #endif #include <taskpanelist.hxx> #include <functional> #include <algorithm> // can't have static linkage because SUNPRO 5.2 complains Point ImplTaskPaneListGetPos( const Window *w ) { Point pos; if( w->ImplIsDockingWindow() ) { pos = ((DockingWindow*)w)->GetPosPixel(); Window *pF = ((DockingWindow*)w)->GetFloatingWindow(); if( pF ) pos = pF->OutputToAbsoluteScreenPixel( pF->ScreenToOutputPixel( pos ) ); else pos = w->OutputToAbsoluteScreenPixel( pos ); } else pos = w->OutputToAbsoluteScreenPixel( w->GetPosPixel() ); return pos; } // compares window pos left-to-right struct LTRSort : public ::std::binary_function< const Window*, const Window*, bool > { bool operator()( const Window* w1, const Window* w2 ) const { Point pos1(ImplTaskPaneListGetPos( w1 )); Point pos2(ImplTaskPaneListGetPos( w2 )); if( pos1.X() == pos2.X() ) return ( pos1.Y() < pos2.Y() ); else return ( pos1.X() < pos2.X() ); } }; struct LTRSortBackward : public ::std::binary_function< const Window*, const Window*, bool > { bool operator()( const Window* w2, const Window* w1 ) const { Point pos1(ImplTaskPaneListGetPos( w1 )); Point pos2(ImplTaskPaneListGetPos( w2 )); if( pos1.X() == pos2.X() ) return ( pos1.Y() < pos2.Y() ); else return ( pos1.X() < pos2.X() ); } }; // -------------------------------------------------- TaskPaneList::TaskPaneList() { } TaskPaneList::~TaskPaneList() { } // -------------------------------------------------- void TaskPaneList::AddWindow( Window *pWindow ) { bool bDockingWindow=false; bool bToolbox=false; bool bDialog=false; bool bUnknown=false; if( pWindow ) { if( pWindow->GetType() == RSC_DOCKINGWINDOW ) bDockingWindow = true; else if( pWindow->GetType() == RSC_TOOLBOX ) bToolbox = true; else if( pWindow->IsDialog() ) bDialog = true; else bUnknown = true; ::std::vector< Window* >::iterator p; p = ::std::find( mTaskPanes.begin(), mTaskPanes.end(), pWindow ); // avoid duplicates if( p == mTaskPanes.end() ) // not found mTaskPanes.push_back( pWindow ); } } // -------------------------------------------------- void TaskPaneList::RemoveWindow( Window *pWindow ) { ::std::vector< Window* >::iterator p; p = ::std::find( mTaskPanes.begin(), mTaskPanes.end(), pWindow ); if( p != mTaskPanes.end() ) mTaskPanes.erase( p ); } // -------------------------------------------------- BOOL TaskPaneList::HandleKeyEvent( KeyEvent aKeyEvent ) { // F6 cycles through everything and works always // Ctrl-TAB cycles through Menubar, Toolbars and Floatingwindows only and is // only active if one of those items has the focus BOOL bF6 = FALSE; BOOL bFocusInList = FALSE; KeyCode aKeyCode = aKeyEvent.GetKeyCode(); BOOL bForward = !aKeyCode.IsShift(); if( ( aKeyCode.IsMod1() && aKeyCode.GetCode() == KEY_TAB ) // Ctrl-TAB || ( bF6 = ( aKeyCode.GetCode()) == KEY_F6 ) // F6 ) { // is the focus in the list ? BOOL bHasFocus = FALSE; ::std::vector< Window* >::iterator p = mTaskPanes.begin(); while( p != mTaskPanes.end() ) { Window *pWin = *p; if( (*p)->HasChildPathFocus( TRUE ) ) { bFocusInList = TRUE; // Ctrl-TAB works not in Dialogs if( !bF6 && (*p)->IsDialog() ) return FALSE; // activate next task pane Window *pNextWin = bF6 ? FindNextFloat( *p, bForward ) : FindNextPane( *p, bForward ); if( pNextWin != pWin ) { ImplGetSVData()->maWinData.mbNoSaveFocus = TRUE; pNextWin->GrabFocus(); ImplGetSVData()->maWinData.mbNoSaveFocus = FALSE; } else { // we did not find another taskpane, so // put focus back into document: use frame win of topmost parent while( pWin ) { if( !pWin->GetParent() ) { pWin->ImplGetFrameWindow()->GetWindow( WINDOW_CLIENT )->GrabFocus(); break; } pWin = pWin->GetParent(); } } return TRUE; } else p++; } // the focus is not in the list: activate first float if F6 was pressed if( !bFocusInList && bF6 ) { Window *pWin = FindNextFloat( NULL, bForward ); if( pWin ) { pWin->GrabFocus(); return TRUE; } } } return FALSE; } // -------------------------------------------------- // returns next valid pane Window* TaskPaneList::FindNextPane( Window *pWindow, BOOL bForward ) { if( bForward ) ::std::stable_sort( mTaskPanes.begin(), mTaskPanes.end(), LTRSort() ); else ::std::stable_sort( mTaskPanes.begin(), mTaskPanes.end(), LTRSortBackward() ); ::std::vector< Window* >::iterator p = mTaskPanes.begin(); while( p != mTaskPanes.end() ) { if( *p == pWindow ) { unsigned n = mTaskPanes.size(); while( --n ) { if( ++p == mTaskPanes.end() ) p = mTaskPanes.begin(); if( (*p)->IsVisible() && !(*p)->IsDialog() ) return *p; } break; } else ++p; } return pWindow; // nothing found } // -------------------------------------------------- // returns first valid item (regardless of type) if pWindow==0, otherwise returns next valid float Window* TaskPaneList::FindNextFloat( Window *pWindow, BOOL bForward ) { if( bForward ) ::std::stable_sort( mTaskPanes.begin(), mTaskPanes.end(), LTRSort() ); else ::std::stable_sort( mTaskPanes.begin(), mTaskPanes.end(), LTRSortBackward() ); ::std::vector< Window* >::iterator p = mTaskPanes.begin(); while( p != mTaskPanes.end() ) { if( !pWindow || *p == pWindow ) { while( p != mTaskPanes.end() ) { if( pWindow ) // increment before test ++p; if( p == mTaskPanes.end() ) return pWindow; // do not wrap, send focus back to document at end of list if( (*p)->IsVisible() /*&& ( (*p)->GetType() == RSC_DOCKINGWINDOW || (*p)->IsDialog() )*/ ) return *p; if( !pWindow ) // increment after test, otherwise first element is skipped ++p; } break; } else ++p; } return pWindow; // nothing found } // -------------------------------------------------- <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: targetlistener.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2005-09-08 18:32:57 $ * * 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 _TARGETLISTENER_HXX_ #define _TARGETLISTENER_HXX_ #include <windows.h> #include <cppuhelper/implbase1.hxx> #include <com/sun/star/datatransfer/dnd/XDropTargetListener.hpp> #include <com/sun/star/datatransfer/dnd/DropTargetDropEvent.hpp> #include <com/sun/star/datatransfer/dnd/DropTargetDragEvent.hpp> #include <com/sun/star/datatransfer/dnd/DropTargetDragEnterEvent.hpp> using namespace ::com::sun::star::datatransfer; using namespace ::com::sun::star::datatransfer::dnd; using namespace ::cppu; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::lang; class DropTargetListener: public WeakImplHelper1<XDropTargetListener> { // this is a window where droped data are shown as text (only text) HWND m_hEdit; public: DropTargetListener( HWND hEdit); ~DropTargetListener(); virtual void SAL_CALL disposing( const EventObject& Source ) throw(RuntimeException); virtual void SAL_CALL drop( const DropTargetDropEvent& dtde ) throw(RuntimeException); virtual void SAL_CALL dragEnter( const DropTargetDragEnterEvent& dtde ) throw(RuntimeException); virtual void SAL_CALL dragExit( const DropTargetEvent& dte ) throw(RuntimeException); virtual void SAL_CALL dragOver( const DropTargetDragEvent& dtde ) throw(RuntimeException); virtual void SAL_CALL dropActionChanged( const DropTargetDragEvent& dtde ) throw(RuntimeException); }; #endif <commit_msg>INTEGRATION: CWS warnings01 (1.4.4); FILE MERGED 2006/03/09 20:32:32 pl 1.4.4.1: #i55991# removed warnings for windows platform<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: targetlistener.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: hr $ $Date: 2006-06-20 06:09:01 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _TARGETLISTENER_HXX_ #define _TARGETLISTENER_HXX_ #if defined _MSC_VER #pragma warning(push,1) #endif #include <windows.h> #if defined _MSC_VER #pragma warning(pop) #endif #include <cppuhelper/implbase1.hxx> #include <com/sun/star/datatransfer/dnd/XDropTargetListener.hpp> #include <com/sun/star/datatransfer/dnd/DropTargetDropEvent.hpp> #include <com/sun/star/datatransfer/dnd/DropTargetDragEvent.hpp> #include <com/sun/star/datatransfer/dnd/DropTargetDragEnterEvent.hpp> using namespace ::com::sun::star::datatransfer; using namespace ::com::sun::star::datatransfer::dnd; using namespace ::cppu; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::lang; class DropTargetListener: public WeakImplHelper1<XDropTargetListener> { // this is a window where droped data are shown as text (only text) HWND m_hEdit; public: DropTargetListener( HWND hEdit); ~DropTargetListener(); virtual void SAL_CALL disposing( const EventObject& Source ) throw(RuntimeException); virtual void SAL_CALL drop( const DropTargetDropEvent& dtde ) throw(RuntimeException); virtual void SAL_CALL dragEnter( const DropTargetDragEnterEvent& dtde ) throw(RuntimeException); virtual void SAL_CALL dragExit( const DropTargetEvent& dte ) throw(RuntimeException); virtual void SAL_CALL dragOver( const DropTargetDragEvent& dtde ) throw(RuntimeException); virtual void SAL_CALL dropActionChanged( const DropTargetDragEvent& dtde ) throw(RuntimeException); }; #endif <|endoftext|>
<commit_before>#include "SharedMesh.hh" #include "Parsers/Parsers.hh" #include <assert.h> namespace Resources { SharedMesh::SharedMesh(void) { } SharedMesh::~SharedMesh(void) { } bool SharedMesh::load(std::string const &path) { if (loadObj(path, _geometry) == false) return (false); _buffer.init(_geometry.vertices.size(), &_geometry.indices[0]); _buffer.addAttribute(OpenGLTools::Attribute(sizeof(float) * 4, 4, GL_FLOAT)); _buffer.addAttribute(OpenGLTools::Attribute(sizeof(float) * 4, 4, GL_FLOAT)); _buffer.addAttribute(OpenGLTools::Attribute(sizeof(float) * 4, 4, GL_FLOAT)); _buffer.addAttribute(OpenGLTools::Attribute(sizeof(float) * 2, 2, GL_FLOAT)); assert(_geometry.vertices.size() > 0 && "Cannot create mesh without vertices."); _buffer.setBuffer(0, reinterpret_cast<byte *>(&_geometry.vertices[0].x)); if (_geometry.colors.size()) _buffer.setBuffer(1, reinterpret_cast<byte *>(&_geometry.colors[0].x)); if (_geometry.normals.size()) _buffer.setBuffer(2, reinterpret_cast<byte *>(&_geometry.normals[0].x)); if (_geometry.uvs.size()) _buffer.setBuffer(3, reinterpret_cast<byte *>(&_geometry.uvs[0].x)); return (true); } void SharedMesh::draw() const { _buffer.draw(GL_TRIANGLES); } OpenGLTools::VertexBuffer &SharedMesh::getBuffer() { return (_buffer); } }<commit_msg>Obj loader fixed<commit_after>#include "SharedMesh.hh" #include "Parsers/Parsers.hh" #include <assert.h> namespace Resources { SharedMesh::SharedMesh(void) { } SharedMesh::~SharedMesh(void) { } bool SharedMesh::load(std::string const &path) { if (loadObj(path, _geometry) == false) return (false); _buffer.init(_geometry.indices.size(), &_geometry.indices[0]); _buffer.addAttribute(OpenGLTools::Attribute(sizeof(float) * 4, 4, GL_FLOAT)); _buffer.addAttribute(OpenGLTools::Attribute(sizeof(float) * 4, 4, GL_FLOAT)); _buffer.addAttribute(OpenGLTools::Attribute(sizeof(float) * 4, 4, GL_FLOAT)); _buffer.addAttribute(OpenGLTools::Attribute(sizeof(float) * 2, 2, GL_FLOAT)); assert(_geometry.vertices.size() > 0 && "Cannot create mesh without vertices."); _buffer.setBuffer(0, reinterpret_cast<byte *>(&_geometry.vertices[0].x)); if (_geometry.colors.size()) _buffer.setBuffer(1, reinterpret_cast<byte *>(&_geometry.colors[0].x)); if (_geometry.normals.size()) _buffer.setBuffer(2, reinterpret_cast<byte *>(&_geometry.normals[0].x)); if (_geometry.uvs.size()) _buffer.setBuffer(3, reinterpret_cast<byte *>(&_geometry.uvs[0].x)); return (true); } void SharedMesh::draw() const { _buffer.draw(GL_TRIANGLES); } OpenGLTools::VertexBuffer &SharedMesh::getBuffer() { return (_buffer); } }<|endoftext|>
<commit_before>/** * @file test-template-1.cpp * @author Giovanni Curiel ([email protected]) * @brief Test for template * @version 0.1 * @date 2021-10-23 * * @copyright Copyright (c) 2021 */ #include <iostream> #include <list> bool isEven(u_int32_t n) { return n % 2 == 1;} struct Point { int x; int y; bool operator==(const Point& other) const { return x == other.x && y == other.y; } }; enum ProjectionSide { TO_THE_LEFT, TO_THE_RIGHT, NO_PROJECTION }; struct Edge { Point p1; Point p2; bool isWithinYRange(const Point & p) const { return (p.y >= p1.y && p.y <= p2.y) || (p.y <= p1.y && p.y >= p2.y); } }; struct FirstOrderFunction { double m; double a; FirstOrderFunction(const Edge & e) { m = (e.p2.y - e.p1.y) / double (e.p2.x - e.p1.x); a = e.p1.y - m * e.p1.x; } double f(int x) const { return a + m * x; } bool isAbove(const Point & p) const { return f(p.x) > p.y; } bool isBelow(const Point & p) const { return !isAbove(p); } }; struct Vertex : public Point { Vertex(int x, int y) : Point({x, y}) {} Vertex(const Point & p) : Point(p) {} }; bool hasProjectionOnEdge(const Point & point, const Edge & edge, ProjectionSide side) { auto edgeFunction = FirstOrderFunction(edge); switch (side) { case NO_PROJECTION: return !edge.isWithinYRange(point); case TO_THE_LEFT: return edge.isWithinYRange(point) && edgeFunction.isAbove(point); case TO_THE_RIGHT: return edge.isWithinYRange(point) && edgeFunction.isBelow(point); } return false; } struct Polygon { const std::list<Edge> edges; Polygon(const std::list<Vertex> & p) : edges(buildEdgesFrom(p) ) {} static std::list<Edge> buildEdgesFrom(const std::list<Vertex> & vertices) { std::list<Edge> edges; edges.clear(); Vertex const * firstVertex = nullptr; Vertex const * secondVertex = nullptr; for (auto & vertex: vertices) { firstVertex = &vertex; if (secondVertex) { edges.push_back({*secondVertex, *firstVertex}); } secondVertex = firstVertex; } // Last edge edges.push_back((Edge){vertices.back(), vertices.front()}); return edges; } bool contains(const Point & point) const { u_int32_t cross = 0; for (auto & edge: edges) { if (hasProjectionOnEdge(point, edge, TO_THE_LEFT)) { cross++; } } return isEven(cross); } }; std::ostream & operator<<(std::ostream & os, const Point & p) { os << "(" << p.x << ", " << p.y << ")"; return os; } std::ostream & operator<<(std::ostream & os, const Edge & e) { os << "Edge: " << e.p1 << " - " << e.p2; return os; }; int main(void) { Polygon polygon = Polygon ( { {1, 1}, {11, 3}, {14, 14}, {3, 11} } ); std::list<Point> points = { { 0, 0 }, { 2, 0 }, { 5, 0 }, { 13, 0 }, { 15, 0 }, { 0, 2 }, { 2, 2 }, { 5, 2 }, { 10, 2 }, { 13, 2 }, { 15, 2 }, { 0, 5 }, { 2, 5 }, { 5, 5 }, { 13, 5 }, { 15, 5 }, { 0, 13 }, { 2, 13 }, { 5, 13 }, { 13, 13 }, { 15, 13 }, { 0, 15 }, { 2, 15 }, { 5, 15 }, { 13, 15 }, { 15, 15 }, }; for (auto & point: points) { auto state = (polygon.contains(point) ? "" : "not "); std::cout << "Point " << point << " is " << state << "inside the polygon" << std::endl; } return 0; } <commit_msg>fix: fixing a tidybit on c++ polygon algorithm<commit_after>/** * @file test-template-1.cpp * @author Giovanni Curiel ([email protected]) * @brief Test for template * @version 0.1 * @date 2021-10-23 * * @copyright Copyright (c) 2021 */ #include <iostream> #include <list> bool isEven(u_int32_t n) { return n % 2 == 1;} struct Point { int x; int y; bool operator==(const Point& other) const { return x == other.x && y == other.y; } }; enum ProjectionSide { TO_THE_LEFT, TO_THE_RIGHT, NO_PROJECTION }; struct Edge { Point p1; Point p2; bool isWithinYRange(const Point & p) const { return (p.y >= p1.y && p.y <= p2.y) || (p.y <= p1.y && p.y >= p2.y); } }; struct FirstOrderFunction { double m; double a; FirstOrderFunction(const Edge & e) { m = (e.p2.y - e.p1.y) / double (e.p2.x - e.p1.x); a = e.p1.y - m * e.p1.x; } double f(int x) const { return a + m * x; } bool isAbove(const Point & p) const { return f(p.x) >= p.y; } bool isBelow(const Point & p) const { return f(p.x) <= p.y; } }; struct Vertex : public Point { Vertex(int x, int y) : Point({x, y}) {} Vertex(const Point & p) : Point(p) {} }; bool hasProjectionOnEdge(const Point & point, const Edge & edge, ProjectionSide side) { auto edgeFunction = FirstOrderFunction(edge); switch (side) { case NO_PROJECTION: return !edge.isWithinYRange(point); case TO_THE_LEFT: return edge.isWithinYRange(point) && edgeFunction.isAbove(point); case TO_THE_RIGHT: return edge.isWithinYRange(point) && edgeFunction.isBelow(point); } return false; } struct Polygon { const std::list<Edge> edges; Polygon(const std::list<Vertex> & p) : edges(buildEdgesFrom(p) ) {} static std::list<Edge> buildEdgesFrom(const std::list<Vertex> & vertices) { std::list<Edge> edges; edges.clear(); Vertex const * firstVertex = nullptr; Vertex const * secondVertex = nullptr; for (auto & vertex: vertices) { firstVertex = &vertex; if (secondVertex) { edges.push_back({*secondVertex, *firstVertex}); } secondVertex = firstVertex; } // Last edge edges.push_back((Edge){vertices.back(), vertices.front()}); return edges; } bool contains(const Point & point) const { u_int32_t cross = 0; for (auto & edge: edges) { if (hasProjectionOnEdge(point, edge, TO_THE_LEFT)) { cross++; } } return isEven(cross); } }; std::ostream & operator<<(std::ostream & os, const Point & p) { os << "(" << p.x << ", " << p.y << ")"; return os; } std::ostream & operator<<(std::ostream & os, const Edge & e) { os << "Edge: " << e.p1 << " - " << e.p2; return os; }; int main(void) { Polygon polygon = Polygon ( { {1, 1}, {11, 3}, {14, 14}, {3, 11} } ); std::list<Point> points = { { 0, 0 }, { 11, 3 }, { 2, 6 }, { 2, 0 }, { 5, 0 }, { 13, 0 }, { 15, 0 }, { 0, 2 }, { 2, 2 }, { 5, 2 }, { 10, 2 }, { 13, 2 }, { 15, 2 }, { 0, 5 }, { 2, 5 }, { 5, 5 }, { 13, 5 }, { 15, 5 }, { 0, 13 }, { 2, 13 }, { 5, 13 }, { 13, 13 }, { 15, 13 }, { 0, 15 }, { 2, 15 }, { 5, 15 }, { 13, 15 }, { 15, 15 }, }; for (auto & point: points) { auto state = (polygon.contains(point) ? "" : "not "); std::cout << "Point " << point << " is " << state << "inside the polygon" << std::endl; } return 0; } <|endoftext|>
<commit_before>#ifndef VIENNAGRID_SEGMENTED_MESH_HPP #define VIENNAGRID_SEGMENTED_MESH_HPP #include "viennagrid/mesh/mesh.hpp" #include "viennagrid/mesh/segmentation.hpp" namespace viennagrid { template<typename MeshT, typename SegmentationT> struct segmented_mesh { typedef MeshT mesh_type; typedef SegmentationT segmentation_type; mesh_type mesh; segmentation_type segmentation; }; template<typename WrappedMeshConfig, typename WrappedSegmentationConfig> struct segmented_mesh< viennagrid::mesh<WrappedMeshConfig>, viennagrid::segmentation<WrappedSegmentationConfig> > { typedef viennagrid::mesh<WrappedMeshConfig> mesh_type; typedef viennagrid::segmentation<WrappedSegmentationConfig> segmentation_type; segmented_mesh() : segmentation(mesh) {} mesh_type mesh; segmentation_type segmentation; }; } #endif <commit_msg>segmented_mesh.hpp: added initialization of segmentation in constructor<commit_after>#ifndef VIENNAGRID_SEGMENTED_MESH_HPP #define VIENNAGRID_SEGMENTED_MESH_HPP #include "viennagrid/mesh/mesh.hpp" #include "viennagrid/mesh/segmentation.hpp" namespace viennagrid { template<typename MeshT, typename SegmentationT> struct segmented_mesh { typedef MeshT mesh_type; typedef SegmentationT segmentation_type; segmented_mesh() : segmentation(mesh) {} mesh_type mesh; segmentation_type segmentation; }; template<typename WrappedMeshConfig, typename WrappedSegmentationConfig> struct segmented_mesh< viennagrid::mesh<WrappedMeshConfig>, viennagrid::segmentation<WrappedSegmentationConfig> > { typedef viennagrid::mesh<WrappedMeshConfig> mesh_type; typedef viennagrid::segmentation<WrappedSegmentationConfig> segmentation_type; segmented_mesh() : segmentation(mesh) {} mesh_type mesh; segmentation_type segmentation; }; } #endif <|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. ==============================================================================*/ #include "tensorflow/core/distributed_runtime/collective_param_resolver_distributed.h" #include "tensorflow/core/distributed_runtime/cancellable_call.h" #include "tensorflow/core/distributed_runtime/device_resolver_distributed.h" #include "tensorflow/core/distributed_runtime/worker_cache.h" #include "tensorflow/core/protobuf/config.pb.h" namespace tensorflow { namespace { class CompleteGroupCall : public CancellableCall { public: CompleteGroupCall(const CollGroupParams& group, const string& device_name, CancellationManager* cancel_mgr, const string& remote_worker, WorkerCacheInterface* wc) : CancellableCall(cancel_mgr, remote_worker, wc) { req_.set_group_key(group.group_key); req_.set_group_size(group.group_size); req_.set_device_type(group.device_type.type_string()); req_.add_device_name(device_name); } ~CompleteGroupCall() override {} void IssueCall(const StatusCallback& done) override { wi_->CompleteGroupAsync(&opts_, &req_, &resp_, done); } CompleteGroupRequest req_; CompleteGroupResponse resp_; }; class CompleteInstanceCall : public CancellableCall { public: CompleteInstanceCall(const CollGroupParams& group, const CollInstanceParams& instance, const string& node_name, const string& device_name, bool is_source, CancellationManager* cancel_mgr, const string& remote_worker, WorkerCacheInterface* wc) : CancellableCall(cancel_mgr, remote_worker, wc) { req_.set_name(node_name); req_.set_type(instance.type); req_.set_data_type(instance.data_type); instance.shape.AsProto(req_.mutable_shape()); req_.set_group_key(group.group_key); req_.set_group_size(group.group_size); req_.set_instance_key(instance.instance_key); req_.set_device_type(group.device_type.type_string()); for (int32 offset : instance.impl_details.subdiv_offsets) { req_.add_subdiv_offset(offset); } req_.set_device(device_name); req_.set_is_source(is_source); } ~CompleteInstanceCall() override {} void IssueCall(const StatusCallback& done) override { wi_->CompleteInstanceAsync(&opts_, &req_, &resp_, done); } CompleteInstanceRequest req_; CompleteInstanceResponse resp_; }; } // namespace CollectiveParamResolverDistributed::CollectiveParamResolverDistributed( const ConfigProto& config, const DeviceMgr* dev_mgr, DeviceResolverDistributed* dev_resolver, WorkerCacheInterface* worker_cache, const string& task_name) : CollectiveParamResolverLocal(dev_mgr, dev_resolver, task_name), worker_cache_(worker_cache), group_leader_(task_name == config.experimental().collective_group_leader() ? "" : config.experimental().collective_group_leader()) {} void CollectiveParamResolverDistributed::CompleteParamsAsync( const string& device, CollectiveParams* cp, CancellationManager* cancel_mgr, const StatusCallback& done) { CompleteGroupDistributed(device, cp, cancel_mgr, [this, device, cp, cancel_mgr, done]( const Status& s, const GroupRec* gr) { if (s.ok()) { CompleteInstanceDistributed(device, gr, cp, cancel_mgr, done); } else { done(s); } }); } void CollectiveParamResolverDistributed::CompleteGroupAsync( const CompleteGroupRequest* request, CompleteGroupResponse* response, CancellationManager* cancel_mgr, const StatusCallback& done) { CollectiveParams cp; cp.group.group_key = request->group_key(); cp.group.group_size = request->group_size(); cp.group.device_type = DeviceType(request->device_type()); for (const string& dn : request->device_name()) { cp.instance.device_names.push_back(dn); } CompleteGroupDistributed( cp.instance.device_names[0], &cp, cancel_mgr, [this, response, done](const Status& s, const GroupRec* gr) { if (s.ok()) { mutex_lock l(gr->mu); response->set_group_key(gr->group.group_key); response->set_group_size(gr->group.group_size); response->set_device_type(gr->group.device_type.type_string()); response->set_num_tasks(gr->task_set.size()); for (const string& dn : gr->device_list) { response->add_device_name(dn); } for (const string& tn : gr->task_list) { response->add_task_name(tn); } } else { LOG(ERROR) << "Bad status from CompleteGroupDistributed: " << s; } done(s); }); } void CollectiveParamResolverDistributed::CompleteInstanceAsync( const CompleteInstanceRequest* request, CompleteInstanceResponse* response, CancellationManager* cancel_mgr, const StatusCallback& done) { CollectiveParams* cp = new CollectiveParams; cp->name = request->name(); cp->group.group_key = request->group_key(); cp->group.group_size = request->group_size(); cp->group.device_type = DeviceType(request->device_type()); cp->instance.type = CollectiveType(request->type()); cp->instance.instance_key = request->instance_key(); cp->instance.data_type = request->data_type(); cp->instance.shape = TensorShape(request->shape()); for (int32 offset : request->subdiv_offset()) { cp->instance.impl_details.subdiv_offsets.push_back(offset); } VLOG(1) << "New cp " << cp << " for device " << request->device() << " : " << cp->ToString(); StatusCallback done_and_cleanup = [this, cp, done](const Status& s) { done(s); delete cp; }; // Start by completing the group. CompleteGroupDistributed( request->device(), cp, cancel_mgr, [this, cp, request, response, cancel_mgr, done_and_cleanup]( const Status& cg_status, const GroupRec* gr) { if (cg_status.ok()) { // Then complete the instance. CompleteInstanceDistributed( request->device(), gr, cp, cancel_mgr, [this, gr, cp, response, done_and_cleanup](const Status& ci_status) { if (ci_status.ok()) { // Now source_rank should be known, so // retrieve it. FindInstanceRec( gr, cp, [this, gr, cp, response, done_and_cleanup]( const Status& fi_status, InstanceRec* ir) { if (fi_status.ok()) { mutex_lock l(ir->out_mu); ir->WaitForOutMu(l); response->set_instance_key(cp->instance.instance_key); response->set_source_rank(ir->source_rank); done_and_cleanup(fi_status); } else { done_and_cleanup(fi_status); } }); } else { done_and_cleanup(ci_status); } }); } else { done_and_cleanup(cg_status); } }); } bool CollectiveParamResolverDistributed::GroupIsCached(int32 group_key) { mutex_lock l(group_mu_); const auto& it = group_table_.find(group_key); return it != group_table_.end(); } Status CollectiveParamResolverDistributed::UpdateGroupCache( const CompleteGroupResponse& resp) { // Build a new record from resp. std::unique_ptr<GroupRec> gr(new GroupRec); mutex_lock grl(gr->mu); gr->group.device_type = DeviceType(resp.device_type()); gr->group.group_key = resp.group_key(); gr->group.group_size = resp.group_size(); gr->group.num_tasks = resp.num_tasks(); if (resp.device_name_size() != gr->group.group_size) { return errors::Internal( "CompleteGroupResponse group_size doesn't match device_name list"); } for (const string& dn : resp.device_name()) { gr->device_set.insert(dn); gr->device_list.push_back(dn); } if (resp.task_name_size() != gr->group.group_size) { return errors::Internal( "CompleteGroupResponse group_size doesn't match task_name list"); } for (const string& tn : resp.task_name()) { gr->task_list.push_back(tn); gr->task_set.insert(tn); } CHECK_EQ(gr->task_set.size(), gr->group.num_tasks); { // Group membership should never change. Once a record is in group_table_ // it never gets removed. mutex_lock l(group_mu_); auto it = group_table_.find(gr->group.group_key); if (it == group_table_.end()) { group_table_[gr->group.group_key] = std::move(gr); } } return Status::OK(); } void CollectiveParamResolverDistributed::CompleteGroupDistributed( const string& device, CollectiveParams* cp, CancellationManager* cancel_mgr, const GroupRecCallback& done) { VLOG(1) << "CompleteGroupDistributed group_key=" << cp->group.group_key << " dev: " << device << " is_leader=" << (group_leader_.empty()); if (group_leader_.empty()) { // This is the group leader, so resolution is local. return CompleteGroupLocal(device, cp, done); } else if (!GroupIsCached(cp->group.group_key)) { // Need to update Group cache from the leader. CompleteGroupCall* call = new CompleteGroupCall( cp->group, device, cancel_mgr, group_leader_, worker_cache_); call->Start([this, device, cp, call, done](const Status& s) { if (s.ok()) { Status status = UpdateGroupCache(call->resp_); if (status.ok()) { CompleteGroupLocal(device, cp, done); } else { done(status, nullptr); } } else { done(s, nullptr); } delete call; }); return; } else { return CompleteGroupLocal(device, cp, done); } } bool CollectiveParamResolverDistributed::InstanceIsCached(int32 instance_key) { mutex_lock l(instance_mu_); const auto& it = instance_table_.find(instance_key); return it != instance_table_.end(); } void CollectiveParamResolverDistributed::UpdateInstanceCache( const GroupRec* gr, CollectiveParams* cp, const CompleteInstanceResponse& resp, const StatusCallback& done) { Notification note; InstanceRec* ir = nullptr; int32 source_rank = resp.source_rank(); auto continue_with_ir = [this, cp, &ir, source_rank, done](const Status& s) { if (!s.ok()) { done(s); return; } Status status; do { mutex_lock l(ir->out_mu); ir->WaitForOutMu(l); if (ir->source_rank != source_rank) { if (ir->source_rank >= 0) { ir->status = errors::Internal( "UpdateInstanceCache: CompleteInstanceResponse for instance ", cp->instance.instance_key, " gives source_rank=", source_rank, " but cache already holds value=", ir->source_rank); status = ir->status; break; } ir->source_rank = source_rank; } if (ir->known_count < cp->group.group_size) { ir->known_count = cp->group.group_size; if (ir->known.size() != cp->group.group_size) { ir->status = errors::Internal( "UpdateInstanceCache:: CompleteInstanceResponse for instance ", cp->instance.instance_key, " has known.size()=", ir->known.size(), " < group_size=", cp->group.group_size); status = ir->status; break; } for (int i = 0; i < ir->known.size(); ++i) { ir->known[i] = true; } } status = ir->status; } while (false); // Callback outside of lock. done(status); }; FindInstanceRec( gr, cp, [this, &ir, continue_with_ir](const Status s, InstanceRec* irec) { ir = irec; continue_with_ir(s); }); } void CollectiveParamResolverDistributed::CompleteInstanceDistributed( const string& device, const GroupRec* gr, CollectiveParams* cp, CancellationManager* cancel_mgr, const StatusCallback& done) { if (group_leader_.empty()) { // This is the group leader so resolution is local. return CompleteInstanceLocal(device, gr, cp, cp->is_source, done); } else if (InstanceIsCached(cp->instance.instance_key)) { return CompleteInstanceLocal(device, gr, cp, cp->is_source, done); } else { CompleteInstanceCall* call = new CompleteInstanceCall( cp->group, cp->instance, cp->name, device, cp->is_source, cancel_mgr, group_leader_, worker_cache_); call->Start([this, device, gr, cp, call, done](const Status& s) { if (s.ok()) { UpdateInstanceCache( gr, cp, call->resp_, [this, device, gr, cp, done](const Status& s) { if (!s.ok()) { done(s); } else { CompleteInstanceLocal(device, gr, cp, cp->is_source, done); } }); } else { done(s); } delete call; }); return; } } } // namespace tensorflow <commit_msg>Do not capture variables that may be destroyed before callback finishes.<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. ==============================================================================*/ #include "tensorflow/core/distributed_runtime/collective_param_resolver_distributed.h" #include "tensorflow/core/distributed_runtime/cancellable_call.h" #include "tensorflow/core/distributed_runtime/device_resolver_distributed.h" #include "tensorflow/core/distributed_runtime/worker_cache.h" #include "tensorflow/core/protobuf/config.pb.h" namespace tensorflow { namespace { class CompleteGroupCall : public CancellableCall { public: CompleteGroupCall(const CollGroupParams& group, const string& device_name, CancellationManager* cancel_mgr, const string& remote_worker, WorkerCacheInterface* wc) : CancellableCall(cancel_mgr, remote_worker, wc) { req_.set_group_key(group.group_key); req_.set_group_size(group.group_size); req_.set_device_type(group.device_type.type_string()); req_.add_device_name(device_name); } ~CompleteGroupCall() override {} void IssueCall(const StatusCallback& done) override { wi_->CompleteGroupAsync(&opts_, &req_, &resp_, done); } CompleteGroupRequest req_; CompleteGroupResponse resp_; }; class CompleteInstanceCall : public CancellableCall { public: CompleteInstanceCall(const CollGroupParams& group, const CollInstanceParams& instance, const string& node_name, const string& device_name, bool is_source, CancellationManager* cancel_mgr, const string& remote_worker, WorkerCacheInterface* wc) : CancellableCall(cancel_mgr, remote_worker, wc) { req_.set_name(node_name); req_.set_type(instance.type); req_.set_data_type(instance.data_type); instance.shape.AsProto(req_.mutable_shape()); req_.set_group_key(group.group_key); req_.set_group_size(group.group_size); req_.set_instance_key(instance.instance_key); req_.set_device_type(group.device_type.type_string()); for (int32 offset : instance.impl_details.subdiv_offsets) { req_.add_subdiv_offset(offset); } req_.set_device(device_name); req_.set_is_source(is_source); } ~CompleteInstanceCall() override {} void IssueCall(const StatusCallback& done) override { wi_->CompleteInstanceAsync(&opts_, &req_, &resp_, done); } CompleteInstanceRequest req_; CompleteInstanceResponse resp_; }; } // namespace CollectiveParamResolverDistributed::CollectiveParamResolverDistributed( const ConfigProto& config, const DeviceMgr* dev_mgr, DeviceResolverDistributed* dev_resolver, WorkerCacheInterface* worker_cache, const string& task_name) : CollectiveParamResolverLocal(dev_mgr, dev_resolver, task_name), worker_cache_(worker_cache), group_leader_(task_name == config.experimental().collective_group_leader() ? "" : config.experimental().collective_group_leader()) {} void CollectiveParamResolverDistributed::CompleteParamsAsync( const string& device, CollectiveParams* cp, CancellationManager* cancel_mgr, const StatusCallback& done) { CompleteGroupDistributed(device, cp, cancel_mgr, [this, device, cp, cancel_mgr, done]( const Status& s, const GroupRec* gr) { if (s.ok()) { CompleteInstanceDistributed(device, gr, cp, cancel_mgr, done); } else { done(s); } }); } void CollectiveParamResolverDistributed::CompleteGroupAsync( const CompleteGroupRequest* request, CompleteGroupResponse* response, CancellationManager* cancel_mgr, const StatusCallback& done) { CollectiveParams cp; cp.group.group_key = request->group_key(); cp.group.group_size = request->group_size(); cp.group.device_type = DeviceType(request->device_type()); for (const string& dn : request->device_name()) { cp.instance.device_names.push_back(dn); } CompleteGroupDistributed( cp.instance.device_names[0], &cp, cancel_mgr, [this, response, done](const Status& s, const GroupRec* gr) { if (s.ok()) { mutex_lock l(gr->mu); response->set_group_key(gr->group.group_key); response->set_group_size(gr->group.group_size); response->set_device_type(gr->group.device_type.type_string()); response->set_num_tasks(gr->task_set.size()); for (const string& dn : gr->device_list) { response->add_device_name(dn); } for (const string& tn : gr->task_list) { response->add_task_name(tn); } } else { LOG(ERROR) << "Bad status from CompleteGroupDistributed: " << s; } done(s); }); } void CollectiveParamResolverDistributed::CompleteInstanceAsync( const CompleteInstanceRequest* request, CompleteInstanceResponse* response, CancellationManager* cancel_mgr, const StatusCallback& done) { CollectiveParams* cp = new CollectiveParams; cp->name = request->name(); cp->group.group_key = request->group_key(); cp->group.group_size = request->group_size(); cp->group.device_type = DeviceType(request->device_type()); cp->instance.type = CollectiveType(request->type()); cp->instance.instance_key = request->instance_key(); cp->instance.data_type = request->data_type(); cp->instance.shape = TensorShape(request->shape()); for (int32 offset : request->subdiv_offset()) { cp->instance.impl_details.subdiv_offsets.push_back(offset); } string* device = new string(request->device()); VLOG(1) << "New cp " << cp << " for device " << *device << " : " << cp->ToString(); StatusCallback done_and_cleanup = [this, cp, device, done](const Status& s) { done(s); delete cp; delete device; }; // Start by completing the group. CompleteGroupDistributed( *device, cp, cancel_mgr, [this, cp, device, response, cancel_mgr, done_and_cleanup]( const Status& cg_status, const GroupRec* gr) { if (cg_status.ok()) { // Then complete the instance. CompleteInstanceDistributed( *device, gr, cp, cancel_mgr, [this, gr, cp, response, done_and_cleanup](const Status& ci_status) { if (ci_status.ok()) { // Now source_rank should be known, so // retrieve it. FindInstanceRec( gr, cp, [this, gr, cp, response, done_and_cleanup]( const Status& fi_status, InstanceRec* ir) { if (fi_status.ok()) { mutex_lock l(ir->out_mu); ir->WaitForOutMu(l); response->set_instance_key(cp->instance.instance_key); response->set_source_rank(ir->source_rank); done_and_cleanup(fi_status); } else { done_and_cleanup(fi_status); } }); } else { done_and_cleanup(ci_status); } }); } else { done_and_cleanup(cg_status); } }); } bool CollectiveParamResolverDistributed::GroupIsCached(int32 group_key) { mutex_lock l(group_mu_); const auto& it = group_table_.find(group_key); return it != group_table_.end(); } Status CollectiveParamResolverDistributed::UpdateGroupCache( const CompleteGroupResponse& resp) { // Build a new record from resp. std::unique_ptr<GroupRec> gr(new GroupRec); mutex_lock grl(gr->mu); gr->group.device_type = DeviceType(resp.device_type()); gr->group.group_key = resp.group_key(); gr->group.group_size = resp.group_size(); gr->group.num_tasks = resp.num_tasks(); if (resp.device_name_size() != gr->group.group_size) { return errors::Internal( "CompleteGroupResponse group_size doesn't match device_name list"); } for (const string& dn : resp.device_name()) { gr->device_set.insert(dn); gr->device_list.push_back(dn); } if (resp.task_name_size() != gr->group.group_size) { return errors::Internal( "CompleteGroupResponse group_size doesn't match task_name list"); } for (const string& tn : resp.task_name()) { gr->task_list.push_back(tn); gr->task_set.insert(tn); } CHECK_EQ(gr->task_set.size(), gr->group.num_tasks); { // Group membership should never change. Once a record is in group_table_ // it never gets removed. mutex_lock l(group_mu_); auto it = group_table_.find(gr->group.group_key); if (it == group_table_.end()) { group_table_[gr->group.group_key] = std::move(gr); } } return Status::OK(); } void CollectiveParamResolverDistributed::CompleteGroupDistributed( const string& device, CollectiveParams* cp, CancellationManager* cancel_mgr, const GroupRecCallback& done) { VLOG(1) << "CompleteGroupDistributed group_key=" << cp->group.group_key << " dev: " << device << " is_leader=" << (group_leader_.empty()); if (group_leader_.empty()) { // This is the group leader, so resolution is local. return CompleteGroupLocal(device, cp, done); } else if (!GroupIsCached(cp->group.group_key)) { // Need to update Group cache from the leader. CompleteGroupCall* call = new CompleteGroupCall( cp->group, device, cancel_mgr, group_leader_, worker_cache_); call->Start([this, device, cp, call, done](const Status& s) { if (s.ok()) { Status status = UpdateGroupCache(call->resp_); if (status.ok()) { CompleteGroupLocal(device, cp, done); } else { done(status, nullptr); } } else { done(s, nullptr); } delete call; }); return; } else { return CompleteGroupLocal(device, cp, done); } } bool CollectiveParamResolverDistributed::InstanceIsCached(int32 instance_key) { mutex_lock l(instance_mu_); const auto& it = instance_table_.find(instance_key); return it != instance_table_.end(); } void CollectiveParamResolverDistributed::UpdateInstanceCache( const GroupRec* gr, CollectiveParams* cp, const CompleteInstanceResponse& resp, const StatusCallback& done) { using InstanceRecPointer = InstanceRec*; InstanceRecPointer* irp = new InstanceRecPointer(nullptr); int32 source_rank = resp.source_rank(); auto continue_with_ir = [this, cp, irp, source_rank, done](const Status& s) { if (!s.ok()) { done(s); delete irp; return; } Status status; InstanceRec* ir = *irp; do { mutex_lock l(ir->out_mu); ir->WaitForOutMu(l); if (ir->source_rank != source_rank) { if (ir->source_rank >= 0) { ir->status = errors::Internal( "UpdateInstanceCache: CompleteInstanceResponse for instance ", cp->instance.instance_key, " gives source_rank=", source_rank, " but cache already holds value=", ir->source_rank); status = ir->status; break; } ir->source_rank = source_rank; } if (ir->known_count < cp->group.group_size) { ir->known_count = cp->group.group_size; if (ir->known.size() != cp->group.group_size) { ir->status = errors::Internal( "UpdateInstanceCache:: CompleteInstanceResponse for instance ", cp->instance.instance_key, " has known.size()=", ir->known.size(), " < group_size=", cp->group.group_size); status = ir->status; break; } for (int i = 0; i < ir->known.size(); ++i) { ir->known[i] = true; } } status = ir->status; } while (false); // Callback outside of lock. done(status); delete irp; }; FindInstanceRec( gr, cp, [this, irp, continue_with_ir](const Status s, InstanceRec* irec) { *irp = irec; continue_with_ir(s); }); } void CollectiveParamResolverDistributed::CompleteInstanceDistributed( const string& device, const GroupRec* gr, CollectiveParams* cp, CancellationManager* cancel_mgr, const StatusCallback& done) { if (group_leader_.empty()) { // This is the group leader so resolution is local. return CompleteInstanceLocal(device, gr, cp, cp->is_source, done); } else if (InstanceIsCached(cp->instance.instance_key)) { return CompleteInstanceLocal(device, gr, cp, cp->is_source, done); } else { CompleteInstanceCall* call = new CompleteInstanceCall( cp->group, cp->instance, cp->name, device, cp->is_source, cancel_mgr, group_leader_, worker_cache_); call->Start([this, device, gr, cp, call, done](const Status& s) { if (s.ok()) { UpdateInstanceCache( gr, cp, call->resp_, [this, device, gr, cp, done](const Status& s) { if (!s.ok()) { done(s); } else { CompleteInstanceLocal(device, gr, cp, cp->is_source, done); } }); } else { done(s); } delete call; }); return; } } } // namespace tensorflow <|endoftext|>
<commit_before>/* This file is part of Ingen. * Copyright (C) 2007-2009 Dave Robillard <http://drobilla.net> * * Ingen 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. * * Ingen is distributed in the hope that it will be useful, but HAVEOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "ingen-config.h" #include "raul/SharedPtr.hpp" #include "module/Module.hpp" #include "module/World.hpp" #ifdef HAVE_LIBLO #include "OSCEngineSender.hpp" #endif #ifdef HAVE_SOUP #include "HTTPEngineSender.hpp" #endif using namespace Ingen; #ifdef HAVE_LIBLO SharedPtr<Ingen::Shared::EngineInterface> new_osc_interface(Ingen::Shared::World* world, const std::string& url) { Client::OSCEngineSender* oes = Client::OSCEngineSender::create(url); oes->attach(rand(), true); return SharedPtr<Shared::EngineInterface>(oes); } #endif #ifdef HAVE_SOUP SharedPtr<Ingen::Shared::EngineInterface> new_http_interface(Ingen::Shared::World* world, const std::string& url) { Client::HTTPEngineSender* hes = new Client::HTTPEngineSender(world, url); hes->attach(rand(), true); return SharedPtr<Shared::EngineInterface>(hes); } #endif struct IngenClientModule : public Ingen::Shared::Module { void load(Ingen::Shared::World* world) { world->add_interface_factory("osc.udp", &new_osc_interface); world->add_interface_factory("osc.tcp", &new_osc_interface); world->add_interface_factory("http", &new_http_interface); } }; static IngenClientModule* module = NULL; extern "C" { Ingen::Shared::Module* ingen_module_load() { if (!module) module = new IngenClientModule(); return module; } } // extern "C" <commit_msg>Fix compilation without liblo and/or without libsoup.<commit_after>/* This file is part of Ingen. * Copyright (C) 2007-2009 Dave Robillard <http://drobilla.net> * * Ingen 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. * * Ingen is distributed in the hope that it will be useful, but HAVEOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "ingen-config.h" #include "raul/SharedPtr.hpp" #include "module/Module.hpp" #include "module/World.hpp" #ifdef HAVE_LIBLO #include "OSCEngineSender.hpp" #endif #ifdef HAVE_SOUP #include "HTTPEngineSender.hpp" #endif using namespace Ingen; #ifdef HAVE_LIBLO SharedPtr<Ingen::Shared::EngineInterface> new_osc_interface(Ingen::Shared::World* world, const std::string& url) { Client::OSCEngineSender* oes = Client::OSCEngineSender::create(url); oes->attach(rand(), true); return SharedPtr<Shared::EngineInterface>(oes); } #endif #ifdef HAVE_SOUP SharedPtr<Ingen::Shared::EngineInterface> new_http_interface(Ingen::Shared::World* world, const std::string& url) { Client::HTTPEngineSender* hes = new Client::HTTPEngineSender(world, url); hes->attach(rand(), true); return SharedPtr<Shared::EngineInterface>(hes); } #endif struct IngenClientModule : public Ingen::Shared::Module { void load(Ingen::Shared::World* world) { #ifdef HAVE_LIBLO world->add_interface_factory("osc.udp", &new_osc_interface); world->add_interface_factory("osc.tcp", &new_osc_interface); #endif #ifdef HAVE_SOUP world->add_interface_factory("http", &new_http_interface); #endif } }; static IngenClientModule* module = NULL; extern "C" { Ingen::Shared::Module* ingen_module_load() { if (!module) module = new IngenClientModule(); return module; } } // extern "C" <|endoftext|>
<commit_before>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include <mitkContourModelMapper3D.h> #include <vtkPoints.h> #include <vtkCellArray.h> #include <vtkProperty.h> mitk::ContourModelMapper3D::ContourModelMapper3D() { } mitk::ContourModelMapper3D::~ContourModelMapper3D() { } const mitk::ContourModel* mitk::ContourModelMapper3D::GetInput( void ) { //convient way to get the data from the dataNode return static_cast< const mitk::ContourModel * >( this->GetData() ); } vtkProp* mitk::ContourModelMapper3D::GetVtkProp(mitk::BaseRenderer* renderer) { //return the actor corresponding to the renderer return m_LSH.GetLocalStorage(renderer)->m_Actor; } void mitk::ContourModelMapper3D::MitkRenderOverlay(BaseRenderer* renderer) { if ( this->IsVisible(renderer)==false ) return; if ( this->GetVtkProp(renderer)->GetVisibility() ) { this->GetVtkProp(renderer)->RenderOverlay(renderer->GetVtkRenderer()); } } void mitk::ContourModelMapper3D::MitkRenderOpaqueGeometry(BaseRenderer* renderer) { if ( this->IsVisible( renderer )==false ) return; if ( this->GetVtkProp(renderer)->GetVisibility() ) { this->GetVtkProp(renderer)->RenderOpaqueGeometry( renderer->GetVtkRenderer() ); } } void mitk::ContourModelMapper3D::MitkRenderTranslucentGeometry(BaseRenderer* renderer) { if ( this->IsVisible(renderer)==false ) return; if ( this->GetVtkProp(renderer)->GetVisibility() ) { this->GetVtkProp(renderer)->RenderTranslucentPolygonalGeometry(renderer->GetVtkRenderer()); } } void mitk::ContourModelMapper3D::MitkRenderVolumetricGeometry(BaseRenderer* renderer) { if(IsVisible(renderer)==false) return; if ( GetVtkProp(renderer)->GetVisibility() ) { this->GetVtkProp(renderer)->RenderVolumetricGeometry(renderer->GetVtkRenderer()); } } void mitk::ContourModelMapper3D::GenerateDataForRenderer( mitk::BaseRenderer *renderer ) { /* First convert the contourModel to vtkPolyData, then tube filter it and * set it input for our mapper */ LocalStorage *localStorage = m_LSH.GetLocalStorage(renderer); mitk::ContourModel* inputContour = static_cast< mitk::ContourModel* >( this->GetData() ); localStorage->m_OutlinePolyData = this->CreateVtkPolyDataFromContour(inputContour); this->ApplyContourProperties(renderer); //tube filter the polyData localStorage->m_TubeFilter->SetInput(localStorage->m_OutlinePolyData); localStorage->m_TubeFilter->SetRadius(0.2); localStorage->m_TubeFilter->Update(); localStorage->m_Mapper->SetInput(localStorage->m_TubeFilter->GetOutput()); } void mitk::ContourModelMapper3D::Update(mitk::BaseRenderer* renderer) { if ( !this->IsVisible( renderer ) ) { return; } mitk::ContourModel* data = static_cast< mitk::ContourModel*>( this->GetData() ); if ( data == NULL ) { return; } // Calculate time step of the input data for the specified renderer (integer value) this->CalculateTimeStep( renderer ); // Check if time step is valid const TimeSlicedGeometry *dataTimeGeometry = data->GetTimeSlicedGeometry(); if ( ( dataTimeGeometry == NULL ) || ( dataTimeGeometry->GetTimeSteps() == 0 ) || ( !dataTimeGeometry->IsValidTime( this->GetTimestep() ) ) ) { return; } const DataNode *node = this->GetDataNode(); data->UpdateOutputInformation(); LocalStorage *localStorage = m_LSH.GetLocalStorage(renderer); //check if something important has changed and we need to rerender if ( (localStorage->m_LastUpdateTime < node->GetMTime()) //was the node modified? || (localStorage->m_LastUpdateTime < data->GetPipelineMTime()) //Was the data modified? || (localStorage->m_LastUpdateTime < renderer->GetCurrentWorldGeometry2DUpdateTime()) //was the geometry modified? || (localStorage->m_LastUpdateTime < renderer->GetCurrentWorldGeometry2D()->GetMTime()) || (localStorage->m_LastUpdateTime < node->GetPropertyList()->GetMTime()) //was a property modified? || (localStorage->m_LastUpdateTime < node->GetPropertyList(renderer)->GetMTime()) ) { this->GenerateDataForRenderer( renderer ); } // since we have checked that nothing important has changed, we can set // m_LastUpdateTime to the current time localStorage->m_LastUpdateTime.Modified(); } vtkSmartPointer<vtkPolyData> mitk::ContourModelMapper3D::CreateVtkPolyDataFromContour(mitk::ContourModel* inputContour) { //the points to draw vtkSmartPointer<vtkPoints> points = vtkSmartPointer<vtkPoints>::New(); //the lines to connect the points vtkSmartPointer<vtkCellArray> lines = vtkSmartPointer<vtkCellArray>::New(); //iterate over the control points mitk::ContourModel::VertexIterator current = inputContour->IteratorBegin(); mitk::ContourModel::VertexIterator next = inputContour->IteratorBegin(); next++; mitk::ContourModel::VertexIterator end = inputContour->IteratorEnd(); while(next != end) { mitk::ContourModel::VertexType* currentControlPoint = *current; mitk::ContourModel::VertexType* nextControlPoint = *next; vtkIdType p1 = points->InsertNextPoint(currentControlPoint->Coordinates[0], currentControlPoint->Coordinates[1], currentControlPoint->Coordinates[2]); vtkIdType p2 = points->InsertNextPoint(nextControlPoint->Coordinates[0], nextControlPoint->Coordinates[1], nextControlPoint->Coordinates[2]); //add the line between both contorlPoints lines->InsertNextCell(2); lines->InsertCellPoint(p1); lines->InsertCellPoint(p2); current++; next++; } if(inputContour->IsClosed()) { // If the contour is closed add a line from the last to the first control point mitk::ContourModel::VertexType* firstControlPoint = *(inputContour->IteratorBegin()); mitk::ContourModel::VertexType* lastControlPoint = *(--(inputContour->IteratorEnd())); vtkIdType p2 = points->InsertNextPoint(lastControlPoint->Coordinates[0], lastControlPoint->Coordinates[1], lastControlPoint->Coordinates[2]); vtkIdType p1 = points->InsertNextPoint(firstControlPoint->Coordinates[0], firstControlPoint->Coordinates[1], firstControlPoint->Coordinates[2]); //add the line to the cellArray lines->InsertNextCell(2); lines->InsertCellPoint(p1); lines->InsertCellPoint(p2); } // Create a polydata to store everything in vtkSmartPointer<vtkPolyData> polyData = vtkSmartPointer<vtkPolyData>::New(); // Add the points to the dataset polyData->SetPoints(points); // Add the lines to the dataset polyData->SetLines(lines); return polyData; } void mitk::ContourModelMapper3D::ApplyContourProperties(mitk::BaseRenderer* renderer) { LocalStorage *localStorage = m_LSH.GetLocalStorage(renderer); float binaryOutlineWidth(1.0); if (this->GetDataNode()->GetFloatProperty( "contour width", binaryOutlineWidth, renderer )) { localStorage->m_Actor->GetProperty()->SetLineWidth(binaryOutlineWidth); } localStorage->m_Actor->GetProperty()->SetColor(0.9, 1.0, 0.1); } /*+++++++++++++++++++ LocalStorage part +++++++++++++++++++++++++*/ mitk::ContourModelMapper3D::LocalStorage* mitk::ContourModelMapper3D::GetLocalStorage(mitk::BaseRenderer* renderer) { return m_LSH.GetLocalStorage(renderer); } mitk::ContourModelMapper3D::LocalStorage::LocalStorage() { m_Mapper = vtkSmartPointer<vtkPolyDataMapper>::New(); m_Actor = vtkSmartPointer<vtkActor>::New(); m_OutlinePolyData = vtkSmartPointer<vtkPolyData>::New(); m_TubeFilter = vtkSmartPointer<vtkTubeFilter>::New(); //set the mapper for the actor m_Actor->SetMapper(m_Mapper); } void mitk::ContourModelMapper3D::SetDefaultProperties(mitk::DataNode* node, mitk::BaseRenderer* renderer, bool overwrite) { node->AddProperty( "color", ColorProperty::New(1.0,0.0,0.0), renderer, overwrite ); node->AddProperty( "contour width", mitk::FloatProperty::New( 1.0 ), renderer, overwrite ); Superclass::SetDefaultProperties(node, renderer, overwrite); }<commit_msg>support timesteps in 3d<commit_after>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include <mitkContourModelMapper3D.h> #include <vtkPoints.h> #include <vtkCellArray.h> #include <vtkProperty.h> mitk::ContourModelMapper3D::ContourModelMapper3D() { } mitk::ContourModelMapper3D::~ContourModelMapper3D() { } const mitk::ContourModel* mitk::ContourModelMapper3D::GetInput( void ) { //convient way to get the data from the dataNode return static_cast< const mitk::ContourModel * >( this->GetData() ); } vtkProp* mitk::ContourModelMapper3D::GetVtkProp(mitk::BaseRenderer* renderer) { //return the actor corresponding to the renderer return m_LSH.GetLocalStorage(renderer)->m_Actor; } void mitk::ContourModelMapper3D::MitkRenderOverlay(BaseRenderer* renderer) { if ( this->IsVisible(renderer)==false ) return; if ( this->GetVtkProp(renderer)->GetVisibility() ) { this->GetVtkProp(renderer)->RenderOverlay(renderer->GetVtkRenderer()); } } void mitk::ContourModelMapper3D::MitkRenderOpaqueGeometry(BaseRenderer* renderer) { if ( this->IsVisible( renderer )==false ) return; if ( this->GetVtkProp(renderer)->GetVisibility() ) { this->GetVtkProp(renderer)->RenderOpaqueGeometry( renderer->GetVtkRenderer() ); } } void mitk::ContourModelMapper3D::MitkRenderTranslucentGeometry(BaseRenderer* renderer) { if ( this->IsVisible(renderer)==false ) return; if ( this->GetVtkProp(renderer)->GetVisibility() ) { this->GetVtkProp(renderer)->RenderTranslucentPolygonalGeometry(renderer->GetVtkRenderer()); } } void mitk::ContourModelMapper3D::MitkRenderVolumetricGeometry(BaseRenderer* renderer) { if(IsVisible(renderer)==false) return; if ( GetVtkProp(renderer)->GetVisibility() ) { this->GetVtkProp(renderer)->RenderVolumetricGeometry(renderer->GetVtkRenderer()); } } void mitk::ContourModelMapper3D::GenerateDataForRenderer( mitk::BaseRenderer *renderer ) { /* First convert the contourModel to vtkPolyData, then tube filter it and * set it input for our mapper */ LocalStorage *localStorage = m_LSH.GetLocalStorage(renderer); mitk::ContourModel* inputContour = static_cast< mitk::ContourModel* >( this->GetData() ); localStorage->m_OutlinePolyData = this->CreateVtkPolyDataFromContour(inputContour); this->ApplyContourProperties(renderer); //tube filter the polyData localStorage->m_TubeFilter->SetInput(localStorage->m_OutlinePolyData); localStorage->m_TubeFilter->SetRadius(0.2); localStorage->m_TubeFilter->Update(); localStorage->m_Mapper->SetInput(localStorage->m_TubeFilter->GetOutput()); } void mitk::ContourModelMapper3D::Update(mitk::BaseRenderer* renderer) { if ( !this->IsVisible( renderer ) ) { return; } mitk::ContourModel* data = static_cast< mitk::ContourModel*>( this->GetData() ); if ( data == NULL ) { return; } // Calculate time step of the input data for the specified renderer (integer value) this->CalculateTimeStep( renderer ); // Check if time step is valid const TimeSlicedGeometry *dataTimeGeometry = data->GetTimeSlicedGeometry(); if ( ( dataTimeGeometry == NULL ) || ( dataTimeGeometry->GetTimeSteps() == 0 ) || ( !dataTimeGeometry->IsValidTime( renderer->GetTimeStep() ) ) ) { //clear the rendered polydata localStorage->m_Mapper->SetInput(vtkSmartPointer<vtkPolyData>::New()); return; } const DataNode *node = this->GetDataNode(); data->UpdateOutputInformation(); LocalStorage *localStorage = m_LSH.GetLocalStorage(renderer); //check if something important has changed and we need to rerender if ( (localStorage->m_LastUpdateTime < node->GetMTime()) //was the node modified? || (localStorage->m_LastUpdateTime < data->GetPipelineMTime()) //Was the data modified? || (localStorage->m_LastUpdateTime < renderer->GetCurrentWorldGeometry2DUpdateTime()) //was the geometry modified? || (localStorage->m_LastUpdateTime < renderer->GetCurrentWorldGeometry2D()->GetMTime()) || (localStorage->m_LastUpdateTime < node->GetPropertyList()->GetMTime()) //was a property modified? || (localStorage->m_LastUpdateTime < node->GetPropertyList(renderer)->GetMTime()) ) { this->GenerateDataForRenderer( renderer ); } // since we have checked that nothing important has changed, we can set // m_LastUpdateTime to the current time localStorage->m_LastUpdateTime.Modified(); } vtkSmartPointer<vtkPolyData> mitk::ContourModelMapper3D::CreateVtkPolyDataFromContour(mitk::ContourModel* inputContour) { unsigned int timestep = this->GetTimestep(); //the points to draw vtkSmartPointer<vtkPoints> points = vtkSmartPointer<vtkPoints>::New(); //the lines to connect the points vtkSmartPointer<vtkCellArray> lines = vtkSmartPointer<vtkCellArray>::New(); //iterate over the control points mitk::ContourModel::VertexIterator current = inputContour->IteratorBegin(timestep); mitk::ContourModel::VertexIterator next = inputContour->IteratorBegin(timestep); next++; mitk::ContourModel::VertexIterator end = inputContour->IteratorEnd(timestep); while(next != end) { mitk::ContourModel::VertexType* currentControlPoint = *current; mitk::ContourModel::VertexType* nextControlPoint = *next; vtkIdType p1 = points->InsertNextPoint(currentControlPoint->Coordinates[0], currentControlPoint->Coordinates[1], currentControlPoint->Coordinates[2]); vtkIdType p2 = points->InsertNextPoint(nextControlPoint->Coordinates[0], nextControlPoint->Coordinates[1], nextControlPoint->Coordinates[2]); //add the line between both contorlPoints lines->InsertNextCell(2); lines->InsertCellPoint(p1); lines->InsertCellPoint(p2); current++; next++; } if(inputContour->IsClosed(timestep)) { // If the contour is closed add a line from the last to the first control point mitk::ContourModel::VertexType* firstControlPoint = *(inputContour->IteratorBegin(timestep)); mitk::ContourModel::VertexType* lastControlPoint = *(--(inputContour->IteratorEnd(timestep))); vtkIdType p2 = points->InsertNextPoint(lastControlPoint->Coordinates[0], lastControlPoint->Coordinates[1], lastControlPoint->Coordinates[2]); vtkIdType p1 = points->InsertNextPoint(firstControlPoint->Coordinates[0], firstControlPoint->Coordinates[1], firstControlPoint->Coordinates[2]); //add the line to the cellArray lines->InsertNextCell(2); lines->InsertCellPoint(p1); lines->InsertCellPoint(p2); } // Create a polydata to store everything in vtkSmartPointer<vtkPolyData> polyData = vtkSmartPointer<vtkPolyData>::New(); // Add the points to the dataset polyData->SetPoints(points); // Add the lines to the dataset polyData->SetLines(lines); return polyData; } void mitk::ContourModelMapper3D::ApplyContourProperties(mitk::BaseRenderer* renderer) { LocalStorage *localStorage = m_LSH.GetLocalStorage(renderer); float binaryOutlineWidth(1.0); if (this->GetDataNode()->GetFloatProperty( "contour width", binaryOutlineWidth, renderer )) { localStorage->m_Actor->GetProperty()->SetLineWidth(binaryOutlineWidth); } localStorage->m_Actor->GetProperty()->SetColor(0.9, 1.0, 0.1); } /*+++++++++++++++++++ LocalStorage part +++++++++++++++++++++++++*/ mitk::ContourModelMapper3D::LocalStorage* mitk::ContourModelMapper3D::GetLocalStorage(mitk::BaseRenderer* renderer) { return m_LSH.GetLocalStorage(renderer); } mitk::ContourModelMapper3D::LocalStorage::LocalStorage() { m_Mapper = vtkSmartPointer<vtkPolyDataMapper>::New(); m_Actor = vtkSmartPointer<vtkActor>::New(); m_OutlinePolyData = vtkSmartPointer<vtkPolyData>::New(); m_TubeFilter = vtkSmartPointer<vtkTubeFilter>::New(); //set the mapper for the actor m_Actor->SetMapper(m_Mapper); } void mitk::ContourModelMapper3D::SetDefaultProperties(mitk::DataNode* node, mitk::BaseRenderer* renderer, bool overwrite) { node->AddProperty( "color", ColorProperty::New(1.0,0.0,0.0), renderer, overwrite ); node->AddProperty( "contour width", mitk::FloatProperty::New( 1.0 ), renderer, overwrite ); Superclass::SetDefaultProperties(node, renderer, overwrite); }<|endoftext|>
<commit_before>// Copyright (c) 2015 The Brick Authors. #include "brick/window_util.h" #include <gtk/gtk.h> #include <X11/Xlib.h> #include <X11/Xutil.h> #include <X11/Xatom.h> #include "include/internal/cef_linux.h" #include "include/base/cef_logging.h" #include "brick/brick_app.h" namespace { GList *default_icons = NULL; CefWindowHandle leader_window_; double device_scale_factor = 0; const double kCSSDefaultDPI = 96.0; int XErrorHandlerImpl(Display *display, XErrorEvent *event) { LOG(WARNING) << "X error received: " << "type " << event->type << ", " << "serial " << event->serial << ", " << "error_code " << static_cast<int>(event->error_code) << ", " << "request_code " << static_cast<int>(event->request_code) << ", " << "minor_code " << static_cast<int>(event->minor_code); return 0; } int XIOErrorHandlerImpl(Display *display) { return 0; } } // namespace namespace window_util { CefWindowHandle GetParent(CefWindowHandle handle) { ::Window root; ::Window parent; ::Window *children; unsigned int nchildren; XQueryTree(cef_get_xdisplay(), handle, &root, &parent, &children, &nchildren); XFree(children); return parent; } void Resize(CefWindowHandle handle, int width, int height) { XResizeWindow( cef_get_xdisplay(), handle, (unsigned int) width, (unsigned int) height ); } void SetMinSize(CefWindowHandle handle, int width, int height) { XSizeHints *size_hints = XAllocSizeHints(); if (!size_hints) { LOG(ERROR) << "SetMinSize: Can't allocate memory for XAllocSizeHints"; return; } size_hints->flags = PMinSize; size_hints->min_width = width; size_hints->min_height = height; XSetWMNormalHints( cef_get_xdisplay(), handle, size_hints ); XFree(size_hints); } void ConfigureAsDialog(CefWindowHandle handle) { ::XDisplay *display = cef_get_xdisplay(); Atom type = XInternAtom(display, "_NET_WM_WINDOW_TYPE", False); Atom value = XInternAtom(display, "_NET_WM_WINDOW_TYPE_DIALOG", False); XChangeProperty(display, handle, type, XA_ATOM, 32, PropModeReplace, reinterpret_cast<unsigned char *>(&value), 1); } void ConfigureAsTopmost(CefWindowHandle handle) { ConfigureAsDialog(handle); ::XDisplay *display = cef_get_xdisplay(); Atom state[2]; state[0] = XInternAtom(display, "_NET_WM_STATE_SKIP_TASKBAR", False); state[1] = XInternAtom(display, "_NET_WM_STATE_SKIP_PAGER", False); Atom wm_state = XInternAtom(display, "_NET_WM_STATE", False); XChangeProperty (display, handle, wm_state, XA_ATOM, 32, PropModeReplace, reinterpret_cast<unsigned char *>(&state), 2); } void SetGroupByLeader(CefWindowHandle handle) { ::XDisplay *display = cef_get_xdisplay(); XWMHints base_hints; XWMHints * h = XGetWMHints(display, handle); if (!h) { h = &base_hints; h->flags = 0; } h->flags |= WindowGroupHint; h->window_group = leader_window_; XSetWMHints(display, handle, h); if(h != &base_hints) { XFree(h); } } void SetClientLeader(CefWindowHandle handle) { ::XDisplay *display = cef_get_xdisplay(); Atom type = XInternAtom(display, "WM_CLIENT_LEADER", False); XChangeProperty(display, handle, type, XA_WINDOW, 32, PropModeReplace, reinterpret_cast<unsigned char *>(&leader_window_), 1); SetGroupByLeader(handle); } void FixSize(CefWindowHandle handle, int width, int height) { XSizeHints *size_hints = XAllocSizeHints(); ::XDisplay *display = cef_get_xdisplay(); if (!size_hints) { LOG(ERROR) << "FixSize: Can't allocate memory for XAllocSizeHints"; return; } if (width && height) { size_hints->flags = PSize | PMinSize | PMaxSize; size_hints->width = width; size_hints->height = height; size_hints->min_width = width; size_hints->min_height = height; size_hints->max_width = width; size_hints->max_height = height; } else { size_hints->flags = PMinSize | PMaxSize; size_hints->max_width = width; size_hints->max_height = height; } XSetWMNormalHints( display, handle, size_hints ); XFree(size_hints); } void InitAsPopup(CefWindowHandle handle) { ConfigureAsDialog(handle); } void Hide(CefWindowHandle handle) { ::Display *display = cef_get_xdisplay(); DCHECK(display); XUnmapWindow(display, handle); } void Show(CefWindowHandle handle) { ::Display *display = cef_get_xdisplay(); DCHECK(display); XMapWindow(display, handle); } void CenterPosition(CefWindowHandle handle) { ::Display *display = cef_get_xdisplay(); DCHECK(display); XSizeHints *size_hints = XAllocSizeHints(); if (!size_hints) { LOG(ERROR) << "CenterPosition: Can't allocate memory for XAllocSizeHints"; return; } size_hints->flags = PWinGravity; size_hints->win_gravity = CenterGravity; XSetWMNormalHints( display, handle, size_hints ); XFree(size_hints); } void SetTitle(CefWindowHandle handle, std::string title) { std::string titleStr(title); // Retrieve the X11 display shared with Chromium. ::Display *display = cef_get_xdisplay(); DCHECK(display); DCHECK(handle != kNullWindowHandle); // Retrieve the atoms required by the below XChangeProperty call. const char *kAtoms[] = { "_NET_WM_NAME", "UTF8_STRING" }; Atom atoms[2]; int result = XInternAtoms(display, const_cast<char **>(kAtoms), 2, false, atoms); if (!result) NOTREACHED(); // Set the window title. XChangeProperty(display, handle, atoms[0], atoms[1], 8, PropModeReplace, reinterpret_cast<const unsigned char *>(titleStr.c_str()), titleStr.size()); // TODO(erg): This is technically wrong. So XStoreName and friends expect // this in Host Portable Character Encoding instead of UTF-8, which I believe // is Compound Text. This shouldn't matter 90% of the time since this is the // fallback to the UTF8 property above. XStoreName(display, handle, titleStr.c_str()); } void SetClassHints(CefWindowHandle handle, char *res_name, char *res_class) { XClassHint *class_hints = XAllocClassHint(); ::XDisplay *display = cef_get_xdisplay(); if (!class_hints) { LOG(ERROR) << "SetClassHints: Can't allocate memory for XAllocClassHint"; return; } class_hints->res_name = res_name; class_hints->res_class = res_class; XSetClassHint(display, handle, class_hints); XFree(class_hints); } void SetLeaderWindow(CefWindowHandle handle) { leader_window_ = handle; } CefWindowHandle GetLeaderWindow() { return leader_window_; } void InitHooks() { XSetErrorHandler(XErrorHandlerImpl); XSetIOErrorHandler(XIOErrorHandlerImpl); } void InitWindow(CefWindowHandle handle, bool is_leader) { if (is_leader) SetLeaderWindow(handle); else SetClientLeader(handle); SetClassHints(handle, const_cast<char *>(APP_COMMON_NAME), const_cast<char *>(APP_NAME)); } GList* GetDefaultIcons() { return default_icons; } void SetDefaultIcons(GList* icons) { if (default_icons) { g_list_foreach(default_icons, (GFunc) g_object_unref, NULL); g_list_free(default_icons); } default_icons = icons; gtk_window_set_default_icon_list(icons); } BrowserWindow* LookupBrowserWindow(CefWindowHandle native_window) { GdkWindow * gdk_window = GDK_WINDOW(gdk_xid_table_lookup(native_window)); return reinterpret_cast<BrowserWindow*>( g_object_get_data(G_OBJECT(gdk_window), "wrapper") ); } BrowserWindow* LookupBrowserWindow(GdkEvent* event) { if (event->type == GDK_NOTHING) { // GDK_NOTHING event doesn't have any windows return NULL; } GObject *object = G_OBJECT(event->any.window); if (!G_IS_OBJECT(object)) { LOG(ERROR) << "Try lookup browser window of bad native window" << ", event type: " << event->type << ", event window: " << event->any.window; return NULL; } return reinterpret_cast<BrowserWindow*>( g_object_get_data(object, "wrapper") ); } void FlushChanges() { ::XDisplay *display = cef_get_xdisplay(); XFlush(display); } CefRect GetDefaultScreenRect() { GdkRectangle monitor_rect; gdk_screen_get_monitor_geometry(gdk_screen_get_default(), 0, &monitor_rect); return CefRect( monitor_rect.x, monitor_rect.y, monitor_rect.width, monitor_rect.height ); } double GetDPI() { GtkSettings* gtk_settings = gtk_settings_get_default(); DCHECK(gtk_settings); gint gtk_dpi = -1; g_object_get(gtk_settings, "gtk-xft-dpi", &gtk_dpi, NULL); // GTK multiplies the DPI by 1024 before storing it. return (gtk_dpi > 0) ? gtk_dpi / 1024.0 : kCSSDefaultDPI; } double GetDeviceScaleFactor() { if (!device_scale_factor) device_scale_factor = floor((GetDPI() / kCSSDefaultDPI) * 100) / 100; return device_scale_factor; } } // namespace window_util <commit_msg>Fixed building with GCC 6<commit_after>// Copyright (c) 2015 The Brick Authors. #include "brick/window_util.h" #include <gtk/gtk.h> #include <X11/Xlib.h> #include <X11/Xutil.h> #include <X11/Xatom.h> #include <cmath> #include "include/internal/cef_linux.h" #include "include/base/cef_logging.h" #include "brick/brick_app.h" namespace { GList *default_icons = NULL; CefWindowHandle leader_window_; double device_scale_factor = 0; const double kCSSDefaultDPI = 96.0; int XErrorHandlerImpl(Display *display, XErrorEvent *event) { LOG(WARNING) << "X error received: " << "type " << event->type << ", " << "serial " << event->serial << ", " << "error_code " << static_cast<int>(event->error_code) << ", " << "request_code " << static_cast<int>(event->request_code) << ", " << "minor_code " << static_cast<int>(event->minor_code); return 0; } int XIOErrorHandlerImpl(Display *display) { return 0; } } // namespace namespace window_util { CefWindowHandle GetParent(CefWindowHandle handle) { ::Window root; ::Window parent; ::Window *children; unsigned int nchildren; XQueryTree(cef_get_xdisplay(), handle, &root, &parent, &children, &nchildren); XFree(children); return parent; } void Resize(CefWindowHandle handle, int width, int height) { XResizeWindow( cef_get_xdisplay(), handle, (unsigned int) width, (unsigned int) height ); } void SetMinSize(CefWindowHandle handle, int width, int height) { XSizeHints *size_hints = XAllocSizeHints(); if (!size_hints) { LOG(ERROR) << "SetMinSize: Can't allocate memory for XAllocSizeHints"; return; } size_hints->flags = PMinSize; size_hints->min_width = width; size_hints->min_height = height; XSetWMNormalHints( cef_get_xdisplay(), handle, size_hints ); XFree(size_hints); } void ConfigureAsDialog(CefWindowHandle handle) { ::XDisplay *display = cef_get_xdisplay(); Atom type = XInternAtom(display, "_NET_WM_WINDOW_TYPE", False); Atom value = XInternAtom(display, "_NET_WM_WINDOW_TYPE_DIALOG", False); XChangeProperty(display, handle, type, XA_ATOM, 32, PropModeReplace, reinterpret_cast<unsigned char *>(&value), 1); } void ConfigureAsTopmost(CefWindowHandle handle) { ConfigureAsDialog(handle); ::XDisplay *display = cef_get_xdisplay(); Atom state[2]; state[0] = XInternAtom(display, "_NET_WM_STATE_SKIP_TASKBAR", False); state[1] = XInternAtom(display, "_NET_WM_STATE_SKIP_PAGER", False); Atom wm_state = XInternAtom(display, "_NET_WM_STATE", False); XChangeProperty (display, handle, wm_state, XA_ATOM, 32, PropModeReplace, reinterpret_cast<unsigned char *>(&state), 2); } void SetGroupByLeader(CefWindowHandle handle) { ::XDisplay *display = cef_get_xdisplay(); XWMHints base_hints; XWMHints * h = XGetWMHints(display, handle); if (!h) { h = &base_hints; h->flags = 0; } h->flags |= WindowGroupHint; h->window_group = leader_window_; XSetWMHints(display, handle, h); if(h != &base_hints) { XFree(h); } } void SetClientLeader(CefWindowHandle handle) { ::XDisplay *display = cef_get_xdisplay(); Atom type = XInternAtom(display, "WM_CLIENT_LEADER", False); XChangeProperty(display, handle, type, XA_WINDOW, 32, PropModeReplace, reinterpret_cast<unsigned char *>(&leader_window_), 1); SetGroupByLeader(handle); } void FixSize(CefWindowHandle handle, int width, int height) { XSizeHints *size_hints = XAllocSizeHints(); ::XDisplay *display = cef_get_xdisplay(); if (!size_hints) { LOG(ERROR) << "FixSize: Can't allocate memory for XAllocSizeHints"; return; } if (width && height) { size_hints->flags = PSize | PMinSize | PMaxSize; size_hints->width = width; size_hints->height = height; size_hints->min_width = width; size_hints->min_height = height; size_hints->max_width = width; size_hints->max_height = height; } else { size_hints->flags = PMinSize | PMaxSize; size_hints->max_width = width; size_hints->max_height = height; } XSetWMNormalHints( display, handle, size_hints ); XFree(size_hints); } void InitAsPopup(CefWindowHandle handle) { ConfigureAsDialog(handle); } void Hide(CefWindowHandle handle) { ::Display *display = cef_get_xdisplay(); DCHECK(display); XUnmapWindow(display, handle); } void Show(CefWindowHandle handle) { ::Display *display = cef_get_xdisplay(); DCHECK(display); XMapWindow(display, handle); } void CenterPosition(CefWindowHandle handle) { ::Display *display = cef_get_xdisplay(); DCHECK(display); XSizeHints *size_hints = XAllocSizeHints(); if (!size_hints) { LOG(ERROR) << "CenterPosition: Can't allocate memory for XAllocSizeHints"; return; } size_hints->flags = PWinGravity; size_hints->win_gravity = CenterGravity; XSetWMNormalHints( display, handle, size_hints ); XFree(size_hints); } void SetTitle(CefWindowHandle handle, std::string title) { std::string titleStr(title); // Retrieve the X11 display shared with Chromium. ::Display *display = cef_get_xdisplay(); DCHECK(display); DCHECK(handle != kNullWindowHandle); // Retrieve the atoms required by the below XChangeProperty call. const char *kAtoms[] = { "_NET_WM_NAME", "UTF8_STRING" }; Atom atoms[2]; int result = XInternAtoms(display, const_cast<char **>(kAtoms), 2, false, atoms); if (!result) NOTREACHED(); // Set the window title. XChangeProperty(display, handle, atoms[0], atoms[1], 8, PropModeReplace, reinterpret_cast<const unsigned char *>(titleStr.c_str()), titleStr.size()); // TODO(erg): This is technically wrong. So XStoreName and friends expect // this in Host Portable Character Encoding instead of UTF-8, which I believe // is Compound Text. This shouldn't matter 90% of the time since this is the // fallback to the UTF8 property above. XStoreName(display, handle, titleStr.c_str()); } void SetClassHints(CefWindowHandle handle, char *res_name, char *res_class) { XClassHint *class_hints = XAllocClassHint(); ::XDisplay *display = cef_get_xdisplay(); if (!class_hints) { LOG(ERROR) << "SetClassHints: Can't allocate memory for XAllocClassHint"; return; } class_hints->res_name = res_name; class_hints->res_class = res_class; XSetClassHint(display, handle, class_hints); XFree(class_hints); } void SetLeaderWindow(CefWindowHandle handle) { leader_window_ = handle; } CefWindowHandle GetLeaderWindow() { return leader_window_; } void InitHooks() { XSetErrorHandler(XErrorHandlerImpl); XSetIOErrorHandler(XIOErrorHandlerImpl); } void InitWindow(CefWindowHandle handle, bool is_leader) { if (is_leader) SetLeaderWindow(handle); else SetClientLeader(handle); SetClassHints(handle, const_cast<char *>(APP_COMMON_NAME), const_cast<char *>(APP_NAME)); } GList* GetDefaultIcons() { return default_icons; } void SetDefaultIcons(GList* icons) { if (default_icons) { g_list_foreach(default_icons, (GFunc) g_object_unref, NULL); g_list_free(default_icons); } default_icons = icons; gtk_window_set_default_icon_list(icons); } BrowserWindow* LookupBrowserWindow(CefWindowHandle native_window) { GdkWindow * gdk_window = GDK_WINDOW(gdk_xid_table_lookup(native_window)); return reinterpret_cast<BrowserWindow*>( g_object_get_data(G_OBJECT(gdk_window), "wrapper") ); } BrowserWindow* LookupBrowserWindow(GdkEvent* event) { if (event->type == GDK_NOTHING) { // GDK_NOTHING event doesn't have any windows return NULL; } GObject *object = G_OBJECT(event->any.window); if (!G_IS_OBJECT(object)) { LOG(ERROR) << "Try lookup browser window of bad native window" << ", event type: " << event->type << ", event window: " << event->any.window; return NULL; } return reinterpret_cast<BrowserWindow*>( g_object_get_data(object, "wrapper") ); } void FlushChanges() { ::XDisplay *display = cef_get_xdisplay(); XFlush(display); } CefRect GetDefaultScreenRect() { GdkRectangle monitor_rect; gdk_screen_get_monitor_geometry(gdk_screen_get_default(), 0, &monitor_rect); return CefRect( monitor_rect.x, monitor_rect.y, monitor_rect.width, monitor_rect.height ); } double GetDPI() { GtkSettings* gtk_settings = gtk_settings_get_default(); DCHECK(gtk_settings); gint gtk_dpi = -1; g_object_get(gtk_settings, "gtk-xft-dpi", &gtk_dpi, NULL); // GTK multiplies the DPI by 1024 before storing it. return (gtk_dpi > 0) ? gtk_dpi / 1024.0 : kCSSDefaultDPI; } double GetDeviceScaleFactor() { if (!device_scale_factor) device_scale_factor = floor((GetDPI() / kCSSDefaultDPI) * 100) / 100; return device_scale_factor; } } // namespace window_util <|endoftext|>
<commit_before> /* * @file AliForwardTriggerBiasCorrection.cxx * @author Valentina Zaccolo * @date Mon Feb 3 11:30:24 2014 ** * @brief * * * @ingroup pwglf_forward_multdist */ #include <TH1D.h> #include "AliForwardTriggerBiasCorrection.h" #include "AliForwardMultiplicityDistribution.h" #include "AliAODForwardMult.h" #include "AliAODCentralMult.h" #include "AliAODEvent.h" #include "AliFMDMCEventInspector.h" #include "AliAODMCHeader.h" #include "AliAODMCParticle.h" ClassImp(AliForwardTriggerBiasCorrection) #if 0 ; // This is for Emacs - do not delete #endif //_____________________________________________________________________ AliBaseMultTask::Bin* AliForwardTriggerBiasCorrection::MakeBin(Double_t l, Double_t h) { return new Bin(l,h); } //_____________________________________________________________________ Bool_t AliForwardTriggerBiasCorrection::IsESDClass(AliAODForwardMult* m) const { return (m->IsTriggerBits(AliAODForwardMult::kInel) || m->IsTriggerBits(AliAODForwardMult::kV0AND)); } //===================================================================== void AliForwardTriggerBiasCorrection::Bin::CreateOutputObjects(TList* cont, Int_t max) { // // Define eta bin output histos // AliBaseMultTask::Bin::CreateOutputObjects(cont, max); TList* out = static_cast<TList*>(cont->FindObject(GetName())); if (!out) return; fMCClass = new TH1D("fMCClass","fMCClass", max,-0.5,max-.5); fESDClass = new TH1D("fESDClass","fESDClass", max,-0.5,max-.5); fMCESDClass = new TH1D("fMCESDClass","fMCESDClass", max,-0.5,max-.5); out->Add(fMCClass); out->Add(fESDClass); out->Add(fMCESDClass); } //_____________________________________________________________________ void AliForwardTriggerBiasCorrection:: Bin::Process(TH1D* dndetaForward, TH1D* dndetaCentral, TH1D* normForward, TH1D* normCentral, TH1D* mc, Double_t ipZ, Bool_t pileup, Bool_t selectedTrigger, Bool_t isMCClass, Bool_t isESDClass, const AliAODEvent& aodevent, Double_t minIPz, Double_t maxIPz) { // // Process a single eta bin // Double_t mcMult, mcErr, statErr, sysErr; Double_t mult = CalcMult(dndetaForward, dndetaCentral, normForward, normCentral, mc, ipZ, statErr, sysErr, mcMult, mcErr); Double_t trMult = mcMult; Double_t mcIPz = ipZ; if (true) { // retreive MC particles from event TClonesArray* mcArray = static_cast<TClonesArray*>(aodevent. FindListObject(AliAODMCParticle:: StdBranchName())); if(!mcArray){ AliWarning("No MC array found in AOD. Try making it again."); return; } AliAODMCHeader* header = static_cast<AliAODMCHeader*>(aodevent. FindListObject(AliAODMCHeader:: StdBranchName())); if (!header) { AliWarning("No header found."); return; } // Track loop: find MC truth multiplicity in selected eta bin - this // is probably redundant trMult = 0; mcIPz = header->GetVtxZ(); Int_t ntracks = mcArray->GetEntriesFast(); for (Int_t it = 0; it < ntracks; it++) { AliAODMCParticle* particle = (AliAODMCParticle*)mcArray->At(it); if (!particle) { AliError(Form("Could not receive track %d", it)); continue; } if (!particle->IsPhysicalPrimary()) continue; if (particle->Charge() == 0) continue; if (particle->Eta() > fEtaLow && particle->Eta() < fEtaHigh-0.0001) trMult++; } } // fill fMCClass with multiplicity of MC truth NSD events with MC // truth |vtxz|<4 if (mcIPz > minIPz && mcIPz < maxIPz) { if(isMCClass){ fMCClass->Fill(trMult); } } // fill fESDClass with multiplicity from events with a reconstructed // NSD trigger and reconstructed |vtxz|<4 if (ipZ > minIPz && ipZ < maxIPz){ if(isESDClass){ fESDClass->Fill(trMult); } } // fullfilling both requirements of fMCClass and fESDClass if(/* mcIPz > minIPz && mcIPz < maxIPz && */ ipZ > minIPz && ipZ < maxIPz && isMCClass && isESDClass){ fMCESDClass->Fill(trMult); } if (!selectedTrigger) return; fHist->Fill(mult); fHistMC->Fill(mcMult); } //_____________________________________________________________________ // // // EOF <commit_msg>Do not loop over MC particles, as we already have the info in the primary particle histogram<commit_after> /* * @file AliForwardTriggerBiasCorrection.cxx * @author Valentina Zaccolo * @date Mon Feb 3 11:30:24 2014 ** * @brief * * * @ingroup pwglf_forward_multdist */ #include <TH1D.h> #include "AliForwardTriggerBiasCorrection.h" #include "AliForwardMultiplicityDistribution.h" #include "AliAODForwardMult.h" #include "AliAODCentralMult.h" #include "AliAODEvent.h" #include "AliFMDMCEventInspector.h" #include "AliAODMCHeader.h" #include "AliAODMCParticle.h" ClassImp(AliForwardTriggerBiasCorrection) #if 0 ; // This is for Emacs - do not delete #endif //_____________________________________________________________________ AliBaseMultTask::Bin* AliForwardTriggerBiasCorrection::MakeBin(Double_t l, Double_t h) { return new Bin(l,h); } //_____________________________________________________________________ Bool_t AliForwardTriggerBiasCorrection::IsESDClass(AliAODForwardMult* m) const { return (m->IsTriggerBits(AliAODForwardMult::kInel) || m->IsTriggerBits(AliAODForwardMult::kV0AND)); } //===================================================================== void AliForwardTriggerBiasCorrection::Bin::CreateOutputObjects(TList* cont, Int_t max) { // // Define eta bin output histos // AliBaseMultTask::Bin::CreateOutputObjects(cont, max); TList* out = static_cast<TList*>(cont->FindObject(GetName())); if (!out) return; fMCClass = new TH1D("fMCClass","fMCClass", max,-0.5,max-.5); fESDClass = new TH1D("fESDClass","fESDClass", max,-0.5,max-.5); fMCESDClass = new TH1D("fMCESDClass","fMCESDClass", max,-0.5,max-.5); out->Add(fMCClass); out->Add(fESDClass); out->Add(fMCESDClass); } //_____________________________________________________________________ void AliForwardTriggerBiasCorrection:: Bin::Process(TH1D* dndetaForward, TH1D* dndetaCentral, TH1D* normForward, TH1D* normCentral, TH1D* mc, Double_t ipZ, Bool_t pileup, Bool_t selectedTrigger, Bool_t isMCClass, Bool_t isESDClass, const AliAODEvent& aodevent, Double_t minIPz, Double_t maxIPz) { // // Process a single eta bin // Double_t mcMult, mcErr, statErr, sysErr; Double_t mult = CalcMult(dndetaForward, dndetaCentral, normForward, normCentral, mc, ipZ, statErr, sysErr, mcMult, mcErr); Double_t trMult = mcMult; Double_t mcIPz = mc->GetBinContent(0,0); // IP from MC stored here // The stuff below is redundant. We've already filled the MC // histogram with the exact same information, and we have the IPz // from MC in the under-flow bin 0,0 of the MC histogram. // Furthermore, we use the information stored in the MC histogram to // form the response matrix, so we should also use the same // information to build the trigger bias correction. // // In fact, this class is really not very useful, since we could // have the same code in the MC class for doing the response matrix. // That would ensure that we have the same number in. #if 0 // MC particles from event TClonesArray* mcArray = static_cast<TClonesArray*>(aodevent. FindListObject(AliAODMCParticle:: StdBranchName())); if(!mcArray){ AliWarning("No MC array found in AOD. Try making it again."); return; } AliAODMCHeader* header = static_cast<AliAODMCHeader*>(aodevent. FindListObject(AliAODMCHeader:: StdBranchName())); if (!header) { AliWarning("No header found."); return; } // Track loop: find MC truth multiplicity in selected eta bin - this // is probably redundant trMult = 0; mcIPz = header->GetVtxZ(); Int_t ntracks = mcArray->GetEntriesFast(); for (Int_t it = 0; it < ntracks; it++) { AliAODMCParticle* particle = (AliAODMCParticle*)mcArray->At(it); if (!particle) { AliError(Form("Could not receive track %d", it)); continue; } if (!particle->IsPhysicalPrimary()) continue; if (particle->Charge() == 0) continue; if (particle->Eta() > fEtaLow && particle->Eta() < fEtaHigh-0.0001) trMult++; } #endif // fill fMCClass with multiplicity of MC truth NSD events with MC // truth |vtxz|<4 if (mcIPz > minIPz && mcIPz < maxIPz) { if(isMCClass){ fMCClass->Fill(trMult); } } // fill fESDClass with multiplicity from events with a reconstructed // NSD trigger and reconstructed |vtxz|<4 if (ipZ > minIPz && ipZ < maxIPz){ if(isESDClass){ fESDClass->Fill(trMult); } } // fullfilling both requirements of fMCClass and fESDClass if(/* mcIPz > minIPz && mcIPz < maxIPz && */ ipZ > minIPz && ipZ < maxIPz && isMCClass && isESDClass){ fMCESDClass->Fill(trMult); } if (!selectedTrigger) return; fHist->Fill(mult); fHistMC->Fill(mcMult); } //_____________________________________________________________________ // // // EOF <|endoftext|>
<commit_before>/* * summation.cc * * Copyright (C) 2013 Diamond Light Source * * Author: James Parkhurst * * This code is distributed under the BSD license, a copy of which is * included in the root directory of this package. */ #include <boost/python.hpp> #include <boost/python/def.hpp> #include <dials/algorithms/integration/summation.h> #include <dials/model/data/reflection.h> #include <dials/algorithms/shoebox/mask_code.h> using namespace boost::python; namespace dials { namespace algorithms { namespace boost_python { using dials::model::Reflection; template <typename FloatType> void summation_wrapper(const char *name) { typedef Summation<FloatType> SummationType; class_ <SummationType> ("Summation", no_init) .def(init <const af::const_ref<FloatType>&, const af::const_ref<FloatType>&>(( arg("signal"), arg("background")))) .def(init <const af::const_ref<FloatType>&, const af::const_ref<FloatType>&, const af::const_ref<bool>&>(( arg("signal"), arg("background"), arg("mask")))) .def(init <const af::const_ref< FloatType, af::c_grid<2> >&, const af::const_ref< FloatType, af::c_grid<2> >&>(( arg("signal"), arg("background")))) .def(init <const af::const_ref< FloatType, af::c_grid<2> >&, const af::const_ref< FloatType, af::c_grid<2> >&, const af::const_ref< bool, af::c_grid<2> >&>(( arg("signal"), arg("background"), arg("mask")))) .def(init <const af::const_ref< FloatType, af::c_grid<3> >&, const af::const_ref< FloatType, af::c_grid<3> >&>(( arg("signal"), arg("background")))) .def(init <const af::const_ref< FloatType, af::c_grid<3> >&, const af::const_ref< FloatType, af::c_grid<3> >&, const af::const_ref< bool, af::c_grid<3> >&>(( arg("signal"), arg("background"), arg("mask")))) .def("intensity", &SummationType::intensity) .def("variance", &SummationType::variance) .def("standard_deviation", &SummationType::standard_deviation) .def("signal_intensity", &SummationType::signal_intensity) .def("signal_variance", &SummationType::signal_variance) .def("signal_standard_deviation", &SummationType::signal_standard_deviation) .def("background_intensity", &SummationType::background_intensity) .def("background_variance", &SummationType::background_variance) .def("background_standard_deviation", &SummationType::background_standard_deviation); } template <typename FloatType> Summation<FloatType> make_summation_1d( const af::const_ref<FloatType> &image, const af::const_ref<FloatType> &background) { return Summation<FloatType>(image, background); } template <typename FloatType> Summation<FloatType> make_summation_1d_bg( const af::const_ref<FloatType> &image, const af::const_ref<FloatType> &background, const af::const_ref<bool> &mask) { return Summation<FloatType>(image, background, mask); } template <typename FloatType> Summation<FloatType> make_summation_2d( const af::const_ref<FloatType, af::c_grid<2> > &image, const af::const_ref<FloatType, af::c_grid<2> > &background) { return Summation<FloatType>(image, background); } template <typename FloatType> Summation<FloatType> make_summation_2d_bg( const af::const_ref<FloatType, af::c_grid<2> > &image, const af::const_ref<FloatType, af::c_grid<2> > &background, const af::const_ref<bool, af::c_grid<2> > &mask) { return Summation<FloatType>(image, background, mask); } template <typename FloatType> Summation<FloatType> make_summation_3d( const af::const_ref<FloatType, af::c_grid<3> > &image, const af::const_ref<FloatType, af::c_grid<3> > &background) { return Summation<FloatType>(image, background); } template <typename FloatType> Summation<FloatType> make_summation_3d_bg( const af::const_ref<FloatType, af::c_grid<3> > &image, const af::const_ref<FloatType, af::c_grid<3> > &background, const af::const_ref<bool, af::c_grid<3> > &mask) { return Summation<FloatType>(image, background, mask); } template <typename FloatType> void summation_suite() { def("integrate_by_summation", &make_summation_1d<FloatType>, ( arg("image"), arg("background"))); def("integrate_by_summation", &make_summation_1d_bg<FloatType>, ( arg("image"), arg("background"), arg("mask"))); def("integrate_by_summation", &make_summation_2d<FloatType>, ( arg("image"), arg("background"))); def("integrate_by_summation", &make_summation_2d_bg<FloatType>, ( arg("image"), arg("background"), arg("mask"))); def("integrate_by_summation", &make_summation_3d<FloatType>, ( arg("image"), arg("background"))); def("integrate_by_summation", &make_summation_3d_bg<FloatType>, ( arg("image"), arg("background"), arg("mask"))); } void summation_with_reflection(Reflection &r) { af::const_ref< int, af::c_grid<3> > shoebox_mask = r.get_shoebox_mask().const_ref(); af::versa< bool, af::c_grid<3> > mask(shoebox_mask.accessor(), af::init_functor_null<bool>()); for (std::size_t i = 0; i < mask.size(); ++i) { mask[i] = (shoebox_mask[i] & shoebox::Valid) ? true : false; } // Integrate the reflection Summation<Reflection::float_type> result( r.get_shoebox().const_ref(), r.get_shoebox_background().const_ref(), mask.const_ref()); // Set the intensity and variance r.set_intensity(result.intensity()); r.set_intensity_variance(result.variance()); } void summation_with_reflection_list(af::ref<Reflection> reflections) { #pragma omp parallel for for (std::size_t i = 0; i < reflections.size(); ++i) { try { if (reflections[i].is_valid()) { summation_with_reflection(reflections[i]); } } catch (dials::error) { reflections[i].set_valid(false); } } } void export_summation() { summation_wrapper<float>("SummationFloat"); summation_wrapper<double>("SummationDouble"); summation_suite<float>(); summation_suite<double>(); def("integrate_by_summation", &summation_with_reflection); def("integrate_by_summation", &summation_with_reflection_list); } }}} // namespace = dials::algorithms::boost_python <commit_msg>Fixed bug, now just integrating those pixels set as foreground.<commit_after>/* * summation.cc * * Copyright (C) 2013 Diamond Light Source * * Author: James Parkhurst * * This code is distributed under the BSD license, a copy of which is * included in the root directory of this package. */ #include <boost/python.hpp> #include <boost/python/def.hpp> #include <dials/algorithms/integration/summation.h> #include <dials/model/data/reflection.h> #include <dials/algorithms/shoebox/mask_code.h> using namespace boost::python; namespace dials { namespace algorithms { namespace boost_python { using dials::model::Reflection; template <typename FloatType> void summation_wrapper(const char *name) { typedef Summation<FloatType> SummationType; class_ <SummationType> ("Summation", no_init) .def(init <const af::const_ref<FloatType>&, const af::const_ref<FloatType>&>(( arg("signal"), arg("background")))) .def(init <const af::const_ref<FloatType>&, const af::const_ref<FloatType>&, const af::const_ref<bool>&>(( arg("signal"), arg("background"), arg("mask")))) .def(init <const af::const_ref< FloatType, af::c_grid<2> >&, const af::const_ref< FloatType, af::c_grid<2> >&>(( arg("signal"), arg("background")))) .def(init <const af::const_ref< FloatType, af::c_grid<2> >&, const af::const_ref< FloatType, af::c_grid<2> >&, const af::const_ref< bool, af::c_grid<2> >&>(( arg("signal"), arg("background"), arg("mask")))) .def(init <const af::const_ref< FloatType, af::c_grid<3> >&, const af::const_ref< FloatType, af::c_grid<3> >&>(( arg("signal"), arg("background")))) .def(init <const af::const_ref< FloatType, af::c_grid<3> >&, const af::const_ref< FloatType, af::c_grid<3> >&, const af::const_ref< bool, af::c_grid<3> >&>(( arg("signal"), arg("background"), arg("mask")))) .def("intensity", &SummationType::intensity) .def("variance", &SummationType::variance) .def("standard_deviation", &SummationType::standard_deviation) .def("signal_intensity", &SummationType::signal_intensity) .def("signal_variance", &SummationType::signal_variance) .def("signal_standard_deviation", &SummationType::signal_standard_deviation) .def("background_intensity", &SummationType::background_intensity) .def("background_variance", &SummationType::background_variance) .def("background_standard_deviation", &SummationType::background_standard_deviation); } template <typename FloatType> Summation<FloatType> make_summation_1d( const af::const_ref<FloatType> &image, const af::const_ref<FloatType> &background) { return Summation<FloatType>(image, background); } template <typename FloatType> Summation<FloatType> make_summation_1d_bg( const af::const_ref<FloatType> &image, const af::const_ref<FloatType> &background, const af::const_ref<bool> &mask) { return Summation<FloatType>(image, background, mask); } template <typename FloatType> Summation<FloatType> make_summation_2d( const af::const_ref<FloatType, af::c_grid<2> > &image, const af::const_ref<FloatType, af::c_grid<2> > &background) { return Summation<FloatType>(image, background); } template <typename FloatType> Summation<FloatType> make_summation_2d_bg( const af::const_ref<FloatType, af::c_grid<2> > &image, const af::const_ref<FloatType, af::c_grid<2> > &background, const af::const_ref<bool, af::c_grid<2> > &mask) { return Summation<FloatType>(image, background, mask); } template <typename FloatType> Summation<FloatType> make_summation_3d( const af::const_ref<FloatType, af::c_grid<3> > &image, const af::const_ref<FloatType, af::c_grid<3> > &background) { return Summation<FloatType>(image, background); } template <typename FloatType> Summation<FloatType> make_summation_3d_bg( const af::const_ref<FloatType, af::c_grid<3> > &image, const af::const_ref<FloatType, af::c_grid<3> > &background, const af::const_ref<bool, af::c_grid<3> > &mask) { return Summation<FloatType>(image, background, mask); } template <typename FloatType> void summation_suite() { def("integrate_by_summation", &make_summation_1d<FloatType>, ( arg("image"), arg("background"))); def("integrate_by_summation", &make_summation_1d_bg<FloatType>, ( arg("image"), arg("background"), arg("mask"))); def("integrate_by_summation", &make_summation_2d<FloatType>, ( arg("image"), arg("background"))); def("integrate_by_summation", &make_summation_2d_bg<FloatType>, ( arg("image"), arg("background"), arg("mask"))); def("integrate_by_summation", &make_summation_3d<FloatType>, ( arg("image"), arg("background"))); def("integrate_by_summation", &make_summation_3d_bg<FloatType>, ( arg("image"), arg("background"), arg("mask"))); } void summation_with_reflection(Reflection &r) { af::const_ref< int, af::c_grid<3> > shoebox_mask = r.get_shoebox_mask().const_ref(); af::versa< bool, af::c_grid<3> > mask(shoebox_mask.accessor(), af::init_functor_null<bool>()); for (std::size_t i = 0; i < mask.size(); ++i) { mask[i] = (shoebox_mask[i] & shoebox::Valid && shoebox_mask[i] & shoebox::Foreground) ? true : false; } // Integrate the reflection Summation<Reflection::float_type> result( r.get_shoebox().const_ref(), r.get_shoebox_background().const_ref(), mask.const_ref()); // Set the intensity and variance r.set_intensity(result.intensity()); r.set_intensity_variance(result.variance()); } void summation_with_reflection_list(af::ref<Reflection> reflections) { #pragma omp parallel for for (std::size_t i = 0; i < reflections.size(); ++i) { try { if (reflections[i].is_valid()) { summation_with_reflection(reflections[i]); } } catch (dials::error) { reflections[i].set_valid(false); } } } void export_summation() { summation_wrapper<float>("SummationFloat"); summation_wrapper<double>("SummationDouble"); summation_suite<float>(); summation_suite<double>(); def("integrate_by_summation", &summation_with_reflection); def("integrate_by_summation", &summation_with_reflection_list); } }}} // namespace = dials::algorithms::boost_python <|endoftext|>
<commit_before>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "itkExceptionObject.h" #include "itkFixedArray.h" #include "otbLandsatTMIndices.h" #include <vector> #include <algorithm> int otbLandsatTMKernelSpectralRules(int argc, char * argv[]) { typedef double PrecisionType; typedef itk::FixedArray< PrecisionType, 8 > InputPixelType; double TM1 = (::atof(argv[1])); double TM2 = (::atof(argv[2])); double TM3 = (::atof(argv[3])); double TM4 = (::atof(argv[4])); double TM5 = (::atof(argv[5])); double TM61 = (::atof(argv[6])); double TM62 = (::atof(argv[7])); double TM7 = (::atof(argv[8])); InputPixelType pixel; pixel[0] = TM1; pixel[1] = TM2; pixel[2] = TM3; pixel[3] = TM4; pixel[4] = TM5; pixel[5] = TM61; pixel[6] = TM62; pixel[7] = TM7; std::vector< PrecisionType > v123; v123.push_back(TM1); v123.push_back(TM2); v123.push_back(TM3); PrecisionType max123 = *(max_element ( v123.begin(), v123.end() )); PrecisionType min123 = *(min_element ( v123.begin(), v123.end() )); PrecisionType TV1 = 0.7; PrecisionType TV2 = 0.5; typedef otb::Functor::LandsatTM::ThickCloudsSpectralRule<InputPixelType> R1FunctorType; R1FunctorType r1Funct = R1FunctorType(); bool result = r1Funct(pixel); bool goodResult = (min123 >= (TV1 * max123)) and (max123 <= TV1 * TM4) and (TM5 <= TV1 * TM4) and (TM5 >= TV1 * max123) and (TM7 <= TV1 * TM4); std::cout << "Rule 1 " << goodResult << " " << result << std::endl; if( result!=goodResult ) return EXIT_FAILURE; typedef otb::Functor::LandsatTM::ThinCloudsSpectralRule<InputPixelType> R2FunctorType; R2FunctorType r2Funct = R2FunctorType(); result = r2Funct(pixel); goodResult = (min123 >= (TV1 * max123)) and (TM4 >= max123) and !((TM1<=TM2 and TM2<=TM3 and TM3<=TM4) and TM3 >= TV1*TM4) and (TM4 >= TV1*TM5) and (TM5 >= TV1*TM4) and (TM5 >= TV1*max123) and (TM5 >= TV1*TM7); std::cout << "Rule 2 " << goodResult << " " << result << std::endl; if( result!=goodResult ) return EXIT_FAILURE; typedef otb::Functor::LandsatTM::SnowOrIceSpectralRule<InputPixelType> R3FunctorType; R3FunctorType r3Funct = R3FunctorType(); result = r3Funct(pixel); goodResult = (min123 >= (TV1 * max123)) and (TM4 >= TV1 * max123) and (TM5 <= TV2 * TM4) and (TM5 <= TV1* min123) and (TM7 <= TV2 * TM4) and (TM7 <= TV1*min123); std::cout << "Rule 3 " << goodResult << " " << result << std::endl; if( result!=goodResult ) return EXIT_FAILURE; typedef otb::Functor::LandsatTM::WaterOrShadowSpectralRule<InputPixelType> R4FunctorType; R4FunctorType r4Funct = R4FunctorType(); result = r4Funct(pixel); goodResult = (TM1 >= TM2) and (TM2 >= TM3) and (TM3 >= TM4) and (TM4 >= TM5) and (TM4 >= TM7); std::cout << "Rule 4 " << goodResult << " " << result << std::endl; if( result!=goodResult ) return EXIT_FAILURE; typedef otb::Functor::LandsatTM::PitbogOrGreenhouseSpectralRule<InputPixelType> R5FunctorType; R5FunctorType r5Funct = R5FunctorType(); result = r5Funct(pixel); goodResult = (TM3 >= TV1 * TM1) and (TM1 >= TV1 * TM3) and (max123 <= TV1 * TM4) and (TM5 <= TV1 * TM4) and (TM3 >= TV2 * TM5) and (min123 >= TV1 * TM7); std::cout << "Rule 5 " << goodResult << " " << result << std::endl; if( result!=goodResult ) return EXIT_FAILURE; typedef otb::Functor::LandsatTM::DominantBlueSpectralRule<InputPixelType> R6FunctorType; R6FunctorType r6Funct = R6FunctorType(); result = r6Funct(pixel); goodResult = (TM1 >= TV1 * TM2) and (TM1 >= TV1 * TM3) and (TM1 >= TV1 * TM4) and (TM1 >= TV1 * TM5) and (TM1 >= TV1 * TM7); std::cout << "Rule 6 " << goodResult << " " << result << std::endl; if( result!=goodResult ) return EXIT_FAILURE; return EXIT_SUCCESS; } <commit_msg>TEST: Landsat TM vegetation spectral rule<commit_after>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "itkExceptionObject.h" #include "itkFixedArray.h" #include "otbLandsatTMIndices.h" #include <vector> #include <algorithm> int otbLandsatTMKernelSpectralRules(int argc, char * argv[]) { typedef double PrecisionType; typedef itk::FixedArray< PrecisionType, 8 > InputPixelType; double TM1 = (::atof(argv[1])); double TM2 = (::atof(argv[2])); double TM3 = (::atof(argv[3])); double TM4 = (::atof(argv[4])); double TM5 = (::atof(argv[5])); double TM61 = (::atof(argv[6])); double TM62 = (::atof(argv[7])); double TM7 = (::atof(argv[8])); InputPixelType pixel; pixel[0] = TM1; pixel[1] = TM2; pixel[2] = TM3; pixel[3] = TM4; pixel[4] = TM5; pixel[5] = TM61; pixel[6] = TM62; pixel[7] = TM7; std::vector< PrecisionType > v123; v123.push_back(TM1); v123.push_back(TM2); v123.push_back(TM3); PrecisionType max123 = *(max_element ( v123.begin(), v123.end() )); PrecisionType min123 = *(min_element ( v123.begin(), v123.end() )); PrecisionType TV1 = 0.7; PrecisionType TV2 = 0.5; typedef otb::Functor::LandsatTM::ThickCloudsSpectralRule<InputPixelType> R1FunctorType; R1FunctorType r1Funct = R1FunctorType(); bool result = r1Funct(pixel); bool goodResult = (min123 >= (TV1 * max123)) and (max123 <= TV1 * TM4) and (TM5 <= TV1 * TM4) and (TM5 >= TV1 * max123) and (TM7 <= TV1 * TM4); std::cout << "Rule 1 " << goodResult << " " << result << std::endl; if( result!=goodResult ) return EXIT_FAILURE; typedef otb::Functor::LandsatTM::ThinCloudsSpectralRule<InputPixelType> R2FunctorType; R2FunctorType r2Funct = R2FunctorType(); result = r2Funct(pixel); goodResult = (min123 >= (TV1 * max123)) and (TM4 >= max123) and !((TM1<=TM2 and TM2<=TM3 and TM3<=TM4) and TM3 >= TV1*TM4) and (TM4 >= TV1*TM5) and (TM5 >= TV1*TM4) and (TM5 >= TV1*max123) and (TM5 >= TV1*TM7); std::cout << "Rule 2 " << goodResult << " " << result << std::endl; if( result!=goodResult ) return EXIT_FAILURE; typedef otb::Functor::LandsatTM::SnowOrIceSpectralRule<InputPixelType> R3FunctorType; R3FunctorType r3Funct = R3FunctorType(); result = r3Funct(pixel); goodResult = (min123 >= (TV1 * max123)) and (TM4 >= TV1 * max123) and (TM5 <= TV2 * TM4) and (TM5 <= TV1* min123) and (TM7 <= TV2 * TM4) and (TM7 <= TV1*min123); std::cout << "Rule 3 " << goodResult << " " << result << std::endl; if( result!=goodResult ) return EXIT_FAILURE; typedef otb::Functor::LandsatTM::WaterOrShadowSpectralRule<InputPixelType> R4FunctorType; R4FunctorType r4Funct = R4FunctorType(); result = r4Funct(pixel); goodResult = (TM1 >= TM2) and (TM2 >= TM3) and (TM3 >= TM4) and (TM4 >= TM5) and (TM4 >= TM7); std::cout << "Rule 4 " << goodResult << " " << result << std::endl; if( result!=goodResult ) return EXIT_FAILURE; typedef otb::Functor::LandsatTM::PitbogOrGreenhouseSpectralRule<InputPixelType> R5FunctorType; R5FunctorType r5Funct = R5FunctorType(); result = r5Funct(pixel); goodResult = (TM3 >= TV1 * TM1) and (TM1 >= TV1 * TM3) and (max123 <= TV1 * TM4) and (TM5 <= TV1 * TM4) and (TM3 >= TV2 * TM5) and (min123 >= TV1 * TM7); std::cout << "Rule 5 " << goodResult << " " << result << std::endl; if( result!=goodResult ) return EXIT_FAILURE; typedef otb::Functor::LandsatTM::DominantBlueSpectralRule<InputPixelType> R6FunctorType; R6FunctorType r6Funct = R6FunctorType(); result = r6Funct(pixel); goodResult = (TM1 >= TV1 * TM2) and (TM1 >= TV1 * TM3) and (TM1 >= TV1 * TM4) and (TM1 >= TV1 * TM5) and (TM1 >= TV1 * TM7); std::cout << "Rule 6 " << goodResult << " " << result << std::endl; if( result!=goodResult ) return EXIT_FAILURE; typedef otb::Functor::LandsatTM::VegetationSpectralRule<InputPixelType> R7FunctorType; R7FunctorType r7Funct = R7FunctorType(); result = r7Funct(pixel); goodResult = (TM2 >= TV2 * TM1) and (TM2 >= TV1 * TM3) and (TM3 <= TV1 * TM4) and (TM4 >= max123) and (TM5 <= TV1 * TM4) and (TM5 >= TV1 * TM3) and (TM7 <= TV1 * TM5); std::cout << "Rule 7 " << goodResult << " " << result << std::endl; if( result!=goodResult ) return EXIT_FAILURE; return EXIT_SUCCESS; } <|endoftext|>
<commit_before><commit_msg>Revert "tdf#92231 Potential regression curve calculation is wrong"<commit_after><|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////// // // File: ProcessBoundaryExtract.cpp // // For more information, please see: http://www.nektar.info/ // // The MIT License // // Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA), // Department of Aeronautics, Imperial College London (UK), and Scientific // Computing and Imaging Institute, University of Utah (USA). // // License for the specific language governing rights and limitations under // 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. // // Description: Set up boundary to be extracted when writing fld file. // //////////////////////////////////////////////////////////////////////////////// #include <string> #include <iostream> using namespace std; #include "ProcessBoundaryExtract.h" #include <LibUtilities/BasicUtils/SharedArray.hpp> #include <LibUtilities/BasicUtils/ParseUtils.hpp> namespace Nektar { namespace Utilities { ModuleKey ProcessBoundaryExtract::className = GetModuleFactory().RegisterCreatorFunction( ModuleKey(eProcessModule, "extract"), ProcessBoundaryExtract::create, "Extract Boundary field"); ProcessBoundaryExtract::ProcessBoundaryExtract(FieldSharedPtr f) : ProcessModule(f) { // set up dafault values. m_config["bnd"] = ConfigOption(false,"All","Boundary to be extracted"); m_config["fldtoboundary"] = ConfigOption(true,"1","Extract fld values to boundary"); f->m_writeBndFld = true; } ProcessBoundaryExtract::~ProcessBoundaryExtract() { } void ProcessBoundaryExtract::Process(po::variables_map &vm) { if (m_f->m_verbose) { cout << "ProcessBoundaryExtract: Setting up boundary extraction..." << endl; } // Set up Field options to output boundary fld string bvalues = m_config["bnd"].as<string>(); if(bvalues.compare("All") == 0) { Array<OneD, const MultiRegions::ExpListSharedPtr> BndExp = m_f->m_exp[0]->GetBndCondExpansions(); for(int i = 0; i < BndExp.num_elements(); ++i) { m_f->m_bndRegionsToWrite.push_back(i); } } else { ASSERTL0(ParseUtils::GenerateOrderedVector(bvalues.c_str(), m_f->m_bndRegionsToWrite),"Failed to interpret range string"); } if(m_config["fldtoboundary"].as<bool>()) { m_f->m_fldToBnd = true; } } } } <commit_msg>Made keynames more consistent with meshconvert, i.e. extract rather than Extract<commit_after>//////////////////////////////////////////////////////////////////////////////// // // File: ProcessBoundaryExtract.cpp // // For more information, please see: http://www.nektar.info/ // // The MIT License // // Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA), // Department of Aeronautics, Imperial College London (UK), and Scientific // Computing and Imaging Institute, University of Utah (USA). // // License for the specific language governing rights and limitations under // 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. // // Description: Set up boundary to be extracted when writing fld file. // //////////////////////////////////////////////////////////////////////////////// #include <string> #include <iostream> using namespace std; #include "ProcessBoundaryExtract.h" #include <LibUtilities/BasicUtils/SharedArray.hpp> #include <LibUtilities/BasicUtils/ParseUtils.hpp> namespace Nektar { namespace Utilities { ModuleKey ProcessBoundaryExtract::className = GetModuleFactory().RegisterCreatorFunction( ModuleKey(eProcessModule, "extract"), ProcessBoundaryExtract::create, "Extract Boundary field"); ProcessBoundaryExtract::ProcessBoundaryExtract(FieldSharedPtr f) : ProcessModule(f) { // set up dafault values. m_config["bnd"] = ConfigOption(false,"All","Boundary to be extracted"); m_config["fldtoboundary"] = ConfigOption(false,"1","Extract fld values to boundary"); f->m_writeBndFld = true; } ProcessBoundaryExtract::~ProcessBoundaryExtract() { } void ProcessBoundaryExtract::Process(po::variables_map &vm) { if (m_f->m_verbose) { cout << "ProcessBoundaryExtract: Setting up boundary extraction..." << endl; } // Set up Field options to output boundary fld string bvalues = m_config["bnd"].as<string>(); if(bvalues.compare("All") == 0) { Array<OneD, const MultiRegions::ExpListSharedPtr> BndExp = m_f->m_exp[0]->GetBndCondExpansions(); for(int i = 0; i < BndExp.num_elements(); ++i) { m_f->m_bndRegionsToWrite.push_back(i); } } else { ASSERTL0(ParseUtils::GenerateOrderedVector(bvalues.c_str(), m_f->m_bndRegionsToWrite),"Failed to interpret range string"); } if(m_config["fldtoboundary"].as<string>().compare("1") == 0) { m_f->m_fldToBnd = true; } else { m_f->m_fldToBnd = false; } } } } <|endoftext|>
<commit_before>/* * Copyright (C) 2017 Smirnov Vladimir [email protected] * Source code 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 or in file COPYING-APACHE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License.h */ #include "FileUtils.h" #include "Compression.h" #include "Syslogger.h" #include "ThreadUtils.h" #include <assert.h> #include <stdio.h> #include <algorithm> #include <fstream> #include <streambuf> #ifdef HAS_BOOST #include <boost/filesystem.hpp> namespace fs = boost::filesystem; #define u8string string using fserr = boost::system::error_code; #else #include <experimental/filesystem> namespace fs = std::experimental::filesystem; using fserr = std::error_code; #endif #ifdef _MSC_VER #define strtoull _strtoui64 #define getcwd _getcwd #define PATH_MAX _MAX_PATH #endif #if defined( _WIN32) #include <windows.h> #include <io.h> #include <share.h> #include <direct.h> #else #include <unistd.h> #include <errno.h> inline int GetLastError() { return errno; } #endif namespace { static const size_t CHUNK = 16384; } namespace Wuild { class FileInfoPrivate { public: fs::path m_path; }; std::string FileInfo::ToPlatformPath(std::string path) { #ifdef _WIN32 std::replace(path.begin(), path.end(), '/', '\\'); std::transform(path.begin(), path.end(), path.begin(), [](char c) { return ::tolower(c);}); #endif return path; } FileInfo::FileInfo(const FileInfo &rh) : m_impl(new FileInfoPrivate(*rh.m_impl)) { } FileInfo &FileInfo::operator =(const FileInfo &rh) { m_impl.reset(new FileInfoPrivate(*rh.m_impl)); return *this; } FileInfo::FileInfo(const std::string &filename) : m_impl(new FileInfoPrivate()) { m_impl->m_path = filename; } FileInfo::~FileInfo() { } void FileInfo::SetPath(const std::string &path) { m_impl->m_path = path; } std::string FileInfo::GetPath() const { return m_impl->m_path.u8string(); } std::string FileInfo::GetDir(bool ensureEndSlash) const { auto ret = m_impl->m_path.parent_path().u8string(); if (!ret.empty() && ensureEndSlash) ret += '/'; return ret; } std::string FileInfo::GetFullname() const { return m_impl->m_path.filename().u8string(); } std::string FileInfo::GetNameWE() const { const auto name = this->GetFullname(); const auto dot = name.find('.'); return name.substr(0, dot); } std::string FileInfo::GetFullExtension() const { const auto name = this->GetFullname(); const auto dot = name.find('.'); return name.substr( dot ); } std::string FileInfo::GetPlatformShortName() const { #ifdef _WIN32 std::string result = GetPath(); fserr code; result = fs::canonical(result, code).u8string(); long length = 0; // First obtain the size needed by passing NULL and 0. length = GetShortPathNameA(result.c_str(), nullptr, 0); if (length == 0) return result; // Dynamically allocate the correct size // (terminating null char was included in length) std::vector<char> buffer(length + 1); // Now simply call again using same long path. length = GetShortPathNameA(result.c_str(), buffer.data(), length); if (length == 0) return result; return ToPlatformPath(std::string(buffer.data(), length)); #else return GetPath(); #endif } bool FileInfo::ReadCompressed(ByteArrayHolder &data, CompressionInfo compressionInfo) { std::ifstream inFile; inFile.open(GetPath().c_str(), std::ios::binary | std::ios::in); if (!inFile) return false; try { ReadCompressedData(inFile, data, compressionInfo); } catch(std::exception &e) { Syslogger(Syslogger::Err) << "Error on reading:" << e.what() << " for " << GetPath(); return false; } if (Syslogger::IsLogLevelEnabled(Syslogger::Debug)) Syslogger() << "Compressed " << this->GetPath() << ": " << this->GetFileSize() << " -> " << data.size(); return true; } bool FileInfo::WriteCompressed(const ByteArrayHolder & data, CompressionInfo compressionInfo, bool createTmpCopy) { ByteArrayHolder uncompData; try { UncompressDataBuffer(data, uncompData, compressionInfo); } catch(std::exception &e) { Syslogger(Syslogger::Err) << "Error on uncompress:" << e.what() << " for " << GetPath(); return false; } return this->WriteFile(uncompData, createTmpCopy); } bool FileInfo::ReadFile(ByteArrayHolder &data) { FILE * f = fopen(GetPath().c_str(), "rb"); if (!f) return false; ByteArray& dest = data.ref(); unsigned char in[CHUNK]; do { auto avail_in = fread(in, 1, CHUNK, f); if (!avail_in || ferror(f)) break; dest.insert(dest.end(), in, in + avail_in); if (feof(f)) break; } while (true); fclose(f); return true; } bool FileInfo::WriteFile(const ByteArrayHolder &data, bool createTmpCopy) { fserr code; const std::string originalPath = fs::canonical(fs::absolute(m_impl->m_path), code).make_preferred().u8string(); const std::string writePath = createTmpCopy ? originalPath + ".tmp" : originalPath; this->Remove(); try { #ifndef _WIN32 std::ofstream outFile; outFile.open(writePath, std::ios::binary | std::ios::out); outFile.write((const char*)data.data(), data.size()); outFile.close(); #else auto fileHandle = CreateFileA((LPTSTR) writePath.c_str(), // file name GENERIC_WRITE, // open for write 0, // do not share NULL, // default security CREATE_ALWAYS, // overwrite existing FILE_ATTRIBUTE_NORMAL,// normal file NULL); // no template if (fileHandle == INVALID_HANDLE_VALUE) throw std::runtime_error("Failed to open file"); size_t bytesToWrite = data.size(); // <- lossy size_t totalWritten = 0; do { auto blockSize = std::min(bytesToWrite, size_t(32 * 1024 * 1024)); DWORD bytesWritten; if (!::WriteFile(fileHandle, data.data() + totalWritten, blockSize, &bytesWritten, NULL)) { if (totalWritten == 0) { // Note: Only return error if the first WriteFile failed. throw std::runtime_error("Failed to write data"); } break; } if (bytesWritten == 0) break; totalWritten += bytesWritten; bytesToWrite -= bytesWritten; } while (totalWritten < data.size()); if (!::CloseHandle(fileHandle)) throw std::runtime_error("Failed to close file"); #endif } catch(std::exception &e) { Syslogger(Syslogger::Err) << "Error on writing:" << e.what() << " for " << writePath ; return false; } if (createTmpCopy) { fserr code; fs::rename(writePath, originalPath, code); if (code) { Syslogger(Syslogger::Err) << "Failed to rename " << writePath << " -> " << originalPath << " :" << GetLastError(); return false; } } return true; } bool FileInfo::Exists() { fserr code; return fs::exists(m_impl->m_path, code); } size_t FileInfo::GetFileSize() { if (!Exists()) return 0; fserr code; return fs::file_size(m_impl->m_path, code); } void FileInfo::Remove() { fserr code; if (fs::exists(m_impl->m_path, code)) fs::remove(m_impl->m_path, code); } void FileInfo::Mkdirs() { fserr code; fs::create_directories(m_impl->m_path, code); } StringVector FileInfo::GetDirFiles(bool sortByName) { StringVector res; for(const fs::directory_entry& it : fs::directory_iterator(m_impl->m_path)) { const fs::path& p = it.path(); if (fs::is_regular_file(p)) res.push_back( p.filename().u8string() ); } if (sortByName) std::sort(res.begin(), res.end()); return res; } TemporaryFile::~TemporaryFile() { this->Remove(); } std::string GetCWD() { std::vector<char> cwd; std::string workingDir; do { cwd.resize(cwd.size() + 1024); errno = 0; } while (!getcwd(&cwd[0], cwd.size()) && errno == ERANGE); if (errno != 0 && errno != ERANGE) { workingDir = "."; } else { workingDir = cwd.data(); if (workingDir.empty()) workingDir = "."; } std::replace(workingDir.begin(), workingDir.end(), '\\', '/'); if (*workingDir.rbegin() != '/') workingDir += '/'; return workingDir; } void SetCWD(const std::string &cwd) { chdir(cwd.c_str()); } } <commit_msg>Do not canonicalize path.<commit_after>/* * Copyright (C) 2017 Smirnov Vladimir [email protected] * Source code 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 or in file COPYING-APACHE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License.h */ #include "FileUtils.h" #include "Compression.h" #include "Syslogger.h" #include "ThreadUtils.h" #include <assert.h> #include <stdio.h> #include <algorithm> #include <fstream> #include <streambuf> #ifdef HAS_BOOST #include <boost/filesystem.hpp> namespace fs = boost::filesystem; #define u8string string using fserr = boost::system::error_code; #else #include <experimental/filesystem> namespace fs = std::experimental::filesystem; using fserr = std::error_code; #endif #ifdef _MSC_VER #define strtoull _strtoui64 #define getcwd _getcwd #define PATH_MAX _MAX_PATH #endif #if defined( _WIN32) #include <windows.h> #include <io.h> #include <share.h> #include <direct.h> #else #include <unistd.h> #include <errno.h> inline int GetLastError() { return errno; } #endif namespace { static const size_t CHUNK = 16384; } namespace Wuild { class FileInfoPrivate { public: fs::path m_path; }; std::string FileInfo::ToPlatformPath(std::string path) { #ifdef _WIN32 std::replace(path.begin(), path.end(), '/', '\\'); std::transform(path.begin(), path.end(), path.begin(), [](char c) { return ::tolower(c);}); #endif return path; } FileInfo::FileInfo(const FileInfo &rh) : m_impl(new FileInfoPrivate(*rh.m_impl)) { } FileInfo &FileInfo::operator =(const FileInfo &rh) { m_impl.reset(new FileInfoPrivate(*rh.m_impl)); return *this; } FileInfo::FileInfo(const std::string &filename) : m_impl(new FileInfoPrivate()) { m_impl->m_path = filename; } FileInfo::~FileInfo() { } void FileInfo::SetPath(const std::string &path) { m_impl->m_path = path; } std::string FileInfo::GetPath() const { return m_impl->m_path.u8string(); } std::string FileInfo::GetDir(bool ensureEndSlash) const { auto ret = m_impl->m_path.parent_path().u8string(); if (!ret.empty() && ensureEndSlash) ret += '/'; return ret; } std::string FileInfo::GetFullname() const { return m_impl->m_path.filename().u8string(); } std::string FileInfo::GetNameWE() const { const auto name = this->GetFullname(); const auto dot = name.find('.'); return name.substr(0, dot); } std::string FileInfo::GetFullExtension() const { const auto name = this->GetFullname(); const auto dot = name.find('.'); return name.substr( dot ); } std::string FileInfo::GetPlatformShortName() const { #ifdef _WIN32 std::string result = GetPath(); fserr code; result = fs::canonical(result, code).u8string(); long length = 0; // First obtain the size needed by passing NULL and 0. length = GetShortPathNameA(result.c_str(), nullptr, 0); if (length == 0) return result; // Dynamically allocate the correct size // (terminating null char was included in length) std::vector<char> buffer(length + 1); // Now simply call again using same long path. length = GetShortPathNameA(result.c_str(), buffer.data(), length); if (length == 0) return result; return ToPlatformPath(std::string(buffer.data(), length)); #else return GetPath(); #endif } bool FileInfo::ReadCompressed(ByteArrayHolder &data, CompressionInfo compressionInfo) { std::ifstream inFile; inFile.open(GetPath().c_str(), std::ios::binary | std::ios::in); if (!inFile) return false; try { ReadCompressedData(inFile, data, compressionInfo); } catch(std::exception &e) { Syslogger(Syslogger::Err) << "Error on reading:" << e.what() << " for " << GetPath(); return false; } if (Syslogger::IsLogLevelEnabled(Syslogger::Debug)) Syslogger() << "Compressed " << this->GetPath() << ": " << this->GetFileSize() << " -> " << data.size(); return true; } bool FileInfo::WriteCompressed(const ByteArrayHolder & data, CompressionInfo compressionInfo, bool createTmpCopy) { ByteArrayHolder uncompData; try { UncompressDataBuffer(data, uncompData, compressionInfo); } catch(std::exception &e) { Syslogger(Syslogger::Err) << "Error on uncompress:" << e.what() << " for " << GetPath(); return false; } return this->WriteFile(uncompData, createTmpCopy); } bool FileInfo::ReadFile(ByteArrayHolder &data) { FILE * f = fopen(GetPath().c_str(), "rb"); if (!f) return false; ByteArray& dest = data.ref(); unsigned char in[CHUNK]; do { auto avail_in = fread(in, 1, CHUNK, f); if (!avail_in || ferror(f)) break; dest.insert(dest.end(), in, in + avail_in); if (feof(f)) break; } while (true); fclose(f); return true; } bool FileInfo::WriteFile(const ByteArrayHolder &data, bool createTmpCopy) { const std::string originalPath = fs::absolute(m_impl->m_path).u8string(); const std::string writePath = createTmpCopy ? originalPath + ".tmp" : originalPath; this->Remove(); try { #ifndef _WIN32 std::ofstream outFile; outFile.open(writePath, std::ios::binary | std::ios::out); outFile.write((const char*)data.data(), data.size()); outFile.close(); #else auto fileHandle = CreateFileA((LPTSTR) writePath.c_str(), // file name GENERIC_WRITE, // open for write 0, // do not share NULL, // default security CREATE_ALWAYS, // overwrite existing FILE_ATTRIBUTE_NORMAL,// normal file NULL); // no template if (fileHandle == INVALID_HANDLE_VALUE) throw std::runtime_error("Failed to open file"); size_t bytesToWrite = data.size(); // <- lossy size_t totalWritten = 0; do { auto blockSize = std::min(bytesToWrite, size_t(32 * 1024 * 1024)); DWORD bytesWritten; if (!::WriteFile(fileHandle, data.data() + totalWritten, blockSize, &bytesWritten, NULL)) { if (totalWritten == 0) { // Note: Only return error if the first WriteFile failed. throw std::runtime_error("Failed to write data"); } break; } if (bytesWritten == 0) break; totalWritten += bytesWritten; bytesToWrite -= bytesWritten; } while (totalWritten < data.size()); if (!::CloseHandle(fileHandle)) throw std::runtime_error("Failed to close file"); #endif } catch(std::exception &e) { Syslogger(Syslogger::Err) << "Error on writing:" << e.what() << " for " << writePath ; return false; } if (createTmpCopy) { fserr code; fs::rename(writePath, originalPath, code); if (code) { Syslogger(Syslogger::Err) << "Failed to rename " << writePath << " -> " << originalPath << " :" << GetLastError(); return false; } } return true; } bool FileInfo::Exists() { fserr code; return fs::exists(m_impl->m_path, code); } size_t FileInfo::GetFileSize() { if (!Exists()) return 0; fserr code; return fs::file_size(m_impl->m_path, code); } void FileInfo::Remove() { fserr code; if (fs::exists(m_impl->m_path, code)) fs::remove(m_impl->m_path, code); } void FileInfo::Mkdirs() { fserr code; fs::create_directories(m_impl->m_path, code); } StringVector FileInfo::GetDirFiles(bool sortByName) { StringVector res; for(const fs::directory_entry& it : fs::directory_iterator(m_impl->m_path)) { const fs::path& p = it.path(); if (fs::is_regular_file(p)) res.push_back( p.filename().u8string() ); } if (sortByName) std::sort(res.begin(), res.end()); return res; } TemporaryFile::~TemporaryFile() { this->Remove(); } std::string GetCWD() { std::vector<char> cwd; std::string workingDir; do { cwd.resize(cwd.size() + 1024); errno = 0; } while (!getcwd(&cwd[0], cwd.size()) && errno == ERANGE); if (errno != 0 && errno != ERANGE) { workingDir = "."; } else { workingDir = cwd.data(); if (workingDir.empty()) workingDir = "."; } std::replace(workingDir.begin(), workingDir.end(), '\\', '/'); if (*workingDir.rbegin() != '/') workingDir += '/'; return workingDir; } void SetCWD(const std::string &cwd) { chdir(cwd.c_str()); } } <|endoftext|>
<commit_before>/*************************************************************************** * benchmark_disks.cpp * * Sat Aug 24 23:52:15 2002 * Copyright 2002 Roman Dementiev * [email protected] ****************************************************************************/ #include "stxxl/io" #include <cstdio> #include <vector> #include <iomanip> #ifndef BOOST_MSVC #include <unistd.h> #endif #include "stxxl/bits/common/aligned_alloc.h" using namespace stxxl; #ifdef BLOCK_ALIGN #undef BLOCK_ALIGN #endif #define BLOCK_ALIGN 4096 //#define NOREAD //#define DO_ONLY_READ #define POLL_DELAY 1000 #define RAW_ACCESS //#define WATCH_TIMES #ifdef WATCH_TIMES void watch_times(request_ptr reqs[], unsigned n, double * out) { bool * finished = new bool[n]; unsigned count = 0; unsigned i = 0; for (i = 0; i < n; i++) finished[i] = false; while (count != n) { usleep(POLL_DELAY); i = 0; for (i = 0; i < n; i++) { if (!finished[i]) if (reqs[i]->poll()) { finished[i] = true; out[i] = stxxl_timestamp(); count++; } } } delete [] finished; } void out_stat(double start, double end, double * times, unsigned n, const std::vector<std::string> & names) { for (unsigned i = 0; i < n; i++) { std::cout << i << " " << names[i] << " took " << 100. * (times[i] - start) / (end - start) << " %" << std::endl; } } #endif #define MB (1024 * 1024) #define GB (1024 * 1024 * 1024) int main(int argc, char * argv[]) { if (argc < 3) { std::cout << "Usage: " << argv[0] << " offset diskfile..." << std::endl; std::cout << " offset is in GB" << std::endl; exit(0); } unsigned ndisks = 0; unsigned buffer_size = 256 * MB; unsigned buffer_size_int = buffer_size / sizeof(int); unsigned i = 0, j = 0; stxxl::int64 offset = stxxl::int64(GB) * stxxl::int64(atoi(argv[1])); std::vector<std::string> disks_arr; for (int i = 2; i < argc; i++) { std::cout << "Add disk: " << argv[i] << std::endl; disks_arr.push_back(argv[i]); } ndisks = disks_arr.size(); unsigned chunks = 32; request_ptr * reqs = new request_ptr [ndisks * chunks]; file * * disks = new file *[ndisks]; int * buffer = (int *)aligned_alloc<BLOCK_ALIGN>(buffer_size * ndisks); #ifdef WATCH_TIMES double * r_finish_times = new double[ndisks]; double * w_finish_times = new double[ndisks]; #endif int count = (70 * stxxl::int64(GB) - offset) / buffer_size; for (i = 0; i < ndisks * buffer_size_int; i++) buffer[i] = i; for (i = 0; i < ndisks; i++) { #ifdef BOOST_MSVC #ifdef RAW_ACCESS disks[i] = new wincall_file(disks_arr[i], file::CREAT | file::RDWR | file::DIRECT, i); #else disks[i] = new wincall_file(disks_arr[i], file::CREAT | file::RDWR, i); #endif #else #ifdef RAW_ACCESS disks[i] = new syscall_file(disks_arr[i], file::CREAT | file::RDWR | file::DIRECT, i); #else disks[i] = new syscall_file(disks_arr[i], file::CREAT | file::RDWR, i); #endif #endif } try { while (count--) { std::cout << "Disk offset " << std::setw(5) << offset / MB << " MB: "; double begin = stxxl_timestamp(), end; #ifndef DO_ONLY_READ for (i = 0; i < ndisks; i++) { for (j = 0; j < chunks; j++) reqs[i * chunks + j] = disks[i]->awrite( buffer + buffer_size_int * i + buffer_size_int * j / chunks, offset + buffer_size * j / chunks, buffer_size / chunks, stxxl::default_completion_handler() ); } #ifdef WATCH_TIMES watch_times(reqs, ndisks, w_finish_times); #else wait_all( reqs, ndisks * chunks ); #endif end = stxxl_timestamp(); /* std::cout << "WRITE\nDisks: " << ndisks <<" \nElapsed time: "<< end-begin << " \nThroughput: "<< int(1e-6*(buffer_size*ndisks)/(end-begin)) << " Mb/s \nPer one disk:" << int(1e-6*(buffer_size)/(end-begin)) << " Mb/s" << std::endl;*/ #ifdef WATCH_TIMES out_stat(begin, end, w_finish_times, ndisks, disks_arr); #endif std::cout << std::setw(2) << ndisks << " * " << std::setw(3) << int (1e-6 * (buffer_size) / (end - begin)) << " = " << std::setw(3) << int (1e-6 * (buffer_size * ndisks) / (end - begin)) << " MB/s write,"; #endif #ifndef NOREAD begin = stxxl_timestamp(); for (i = 0; i < ndisks; i++) { for (j = 0; j < chunks; j++) reqs[i * chunks + j] = disks[i]->aread( buffer + buffer_size_int * i + buffer_size_int * j / chunks, offset + buffer_size * j / chunks, buffer_size / chunks, stxxl::default_completion_handler() ); } #ifdef WATCH_TIMES watch_times(reqs, ndisks, r_finish_times); #else wait_all( reqs, ndisks * chunks ); #endif end = stxxl_timestamp(); /* std::cout << "READ\nDisks: " << ndisks <<" \nElapsed time: "<< end-begin << " \nThroughput: "<< int(1e-6*(buffer_size*ndisks)/(end-begin)) << " Mb/s \nPer one disk:" << int(1e-6*(buffer_size)/(end-begin)) << " Mb/s" << std::endl;*/ std::cout << std::setw(2) << ndisks << " * " << std::setw(3) << int (1e-6 * (buffer_size) / (end - begin)) << " = " << std::setw(3) << int (1e-6 * (buffer_size * ndisks) / (end - begin)) << " MB/s read" << std::endl; #else std::cout << std::endl; #endif #ifdef WATCH_TIMES out_stat(begin, end, r_finish_times, ndisks, disks_arr); #endif /* std::cout << "Checking..." <<std::endl; for(i=0;i<ndisks*buffer_size_int;i++) { if(buffer[i] != i) { int ibuf = i/buffer_size_int; int pos = i%buffer_size_int; i = (ibuf+1)*buffer_size_int; // jump to next std::cout << "Error on disk "<<ibuf<< " position"<< pos * sizeof(int) << std::endl; } } */ offset += /* 4*stxxl::int64(GB); */ buffer_size; } } catch(const std::exception & ex) { std::cout << std::endl; STXXL_ERRMSG("Cought exception: " << ex.what()); } delete [] reqs; delete [] disks; aligned_dealloc<BLOCK_ALIGN>(buffer); #ifdef WATCH_TIMES delete [] r_finish_times; delete [] w_finish_times; #endif return 0; } <commit_msg>increase disk benchmark details, add average<commit_after>/*************************************************************************** * benchmark_disks.cpp * * Sat Aug 24 23:52:15 2002 * Copyright 2002 Roman Dementiev * [email protected] ****************************************************************************/ /* example gnuplot command for the output of this program: (x-axis: disk offset in GB, y-axis: bandwidth in MB/s) plot \ "disk.log" using ($3/1024):($16) w l title "read", \ "disk.log" using ($3/1024):($9) w l title "write" */ #include "stxxl/io" #include <cstdio> #include <vector> #include <iomanip> #ifndef BOOST_MSVC #include <unistd.h> #endif #include "stxxl/bits/common/aligned_alloc.h" using namespace stxxl; #ifdef BLOCK_ALIGN #undef BLOCK_ALIGN #endif #define BLOCK_ALIGN 4096 //#define NOREAD //#define DO_ONLY_READ #define POLL_DELAY 1000 #define RAW_ACCESS //#define WATCH_TIMES #ifdef WATCH_TIMES void watch_times(request_ptr reqs[], unsigned n, double * out) { bool * finished = new bool[n]; unsigned count = 0; unsigned i = 0; for (i = 0; i < n; i++) finished[i] = false; while (count != n) { usleep(POLL_DELAY); i = 0; for (i = 0; i < n; i++) { if (!finished[i]) if (reqs[i]->poll()) { finished[i] = true; out[i] = stxxl_timestamp(); count++; } } } delete [] finished; } void out_stat(double start, double end, double * times, unsigned n, const std::vector<std::string> & names) { for (unsigned i = 0; i < n; i++) { std::cout << i << " " << names[i] << " took " << 100. * (times[i] - start) / (end - start) << " %" << std::endl; } } #endif #define MB (1024 * 1024) #define GB (1024 * 1024 * 1024) int main(int argc, char * argv[]) { if (argc < 3) { std::cout << "Usage: " << argv[0] << " offset diskfile..." << std::endl; std::cout << " offset is in GB" << std::endl; exit(0); } unsigned ndisks = 0; unsigned buffer_size = 256 * MB; unsigned buffer_size_int = buffer_size / sizeof(int); double totaltimeread = 0, totaltimewrite = 0; stxxl::int64 totalsizeread = 0, totalsizewrite = 0; unsigned i = 0, j = 0; stxxl::int64 offset = stxxl::int64(GB) * stxxl::int64(atoi(argv[1])); std::vector<std::string> disks_arr; for (int i = 2; i < argc; i++) { std::cout << "# Add disk: " << argv[i] << std::endl; disks_arr.push_back(argv[i]); } ndisks = disks_arr.size(); unsigned chunks = 32; request_ptr * reqs = new request_ptr [ndisks * chunks]; file * * disks = new file *[ndisks]; int * buffer = (int *)aligned_alloc<BLOCK_ALIGN>(buffer_size * ndisks); #ifdef WATCH_TIMES double * r_finish_times = new double[ndisks]; double * w_finish_times = new double[ndisks]; #endif int count = (70 * stxxl::int64(GB) - offset) / buffer_size; for (i = 0; i < ndisks * buffer_size_int; i++) buffer[i] = i; for (i = 0; i < ndisks; i++) { #ifdef BOOST_MSVC #ifdef RAW_ACCESS disks[i] = new wincall_file(disks_arr[i], file::CREAT | file::RDWR | file::DIRECT, i); #else disks[i] = new wincall_file(disks_arr[i], file::CREAT | file::RDWR, i); #endif #else #ifdef RAW_ACCESS disks[i] = new syscall_file(disks_arr[i], file::CREAT | file::RDWR | file::DIRECT, i); #else disks[i] = new syscall_file(disks_arr[i], file::CREAT | file::RDWR, i); #endif #endif } std::cout << "# Buffer size: " << buffer_size << " bytes per disk" << std::endl; try { while (count--) { std::cout << "Disk offset " << std::setw(7) << offset / MB << " MB: " << std::fixed; double begin = stxxl_timestamp(), end; #ifndef DO_ONLY_READ for (i = 0; i < ndisks; i++) { for (j = 0; j < chunks; j++) reqs[i * chunks + j] = disks[i]->awrite( buffer + buffer_size_int * i + buffer_size_int * j / chunks, offset + buffer_size * j / chunks, buffer_size / chunks, stxxl::default_completion_handler() ); } #ifdef WATCH_TIMES watch_times(reqs, ndisks, w_finish_times); #else wait_all( reqs, ndisks * chunks ); #endif end = stxxl_timestamp(); totalsizewrite += buffer_size; totaltimewrite += end - begin; /* std::cout << "WRITE\nDisks: " << ndisks <<" \nElapsed time: "<< end-begin << " \nThroughput: "<< int(1e-6*(buffer_size*ndisks)/(end-begin)) << " Mb/s \nPer one disk:" << int(1e-6*(buffer_size)/(end-begin)) << " Mb/s" << std::endl;*/ #ifdef WATCH_TIMES out_stat(begin, end, w_finish_times, ndisks, disks_arr); #endif std::cout << std::setw(2) << ndisks << " * " << std::setw(7) << std::setprecision(3) << (1e-6 * (buffer_size) / (end - begin)) << " = " << std::setw(7) << std::setprecision(3) << (1e-6 * (buffer_size * ndisks) / (end - begin)) << " MB/s write,"; #endif #ifndef NOREAD begin = stxxl_timestamp(); for (i = 0; i < ndisks; i++) { for (j = 0; j < chunks; j++) reqs[i * chunks + j] = disks[i]->aread( buffer + buffer_size_int * i + buffer_size_int * j / chunks, offset + buffer_size * j / chunks, buffer_size / chunks, stxxl::default_completion_handler() ); } #ifdef WATCH_TIMES watch_times(reqs, ndisks, r_finish_times); #else wait_all( reqs, ndisks * chunks ); #endif end = stxxl_timestamp(); totalsizeread += buffer_size; totaltimeread += end - begin; /* std::cout << "READ\nDisks: " << ndisks <<" \nElapsed time: "<< end-begin << " \nThroughput: "<< int(1e-6*(buffer_size*ndisks)/(end-begin)) << " Mb/s \nPer one disk:" << int(1e-6*(buffer_size)/(end-begin)) << " Mb/s" << std::endl;*/ std::cout << std::setw(2) << ndisks << " * " << std::setw(7) << std::setprecision(3) << (1e-6 * (buffer_size) / (end - begin)) << " = " << std::setw(7) << std::setprecision(3) << (1e-6 * (buffer_size * ndisks) / (end - begin)) << " MB/s read" << std::endl; #else std::cout << std::endl; #endif #ifdef WATCH_TIMES out_stat(begin, end, r_finish_times, ndisks, disks_arr); #endif /* std::cout << "Checking..." <<std::endl; for(i=0;i<ndisks*buffer_size_int;i++) { if(buffer[i] != i) { int ibuf = i/buffer_size_int; int pos = i%buffer_size_int; i = (ibuf+1)*buffer_size_int; // jump to next std::cout << "Error on disk "<<ibuf<< " position"<< pos * sizeof(int) << std::endl; } } */ offset += /* 4*stxxl::int64(GB); */ buffer_size; } } catch(const std::exception & ex) { std::cout << std::endl; STXXL_ERRMSG(ex.what()); } std::cout << "# Average over "<< std::setw(7) << totalsizewrite / MB << " MB: "; std::cout << std::setw(2) << ndisks << " * " << std::setw(7) << std::setprecision(3) << (1e-6 * (totalsizewrite) / totaltimewrite) << " = " << std::setw(7) << std::setprecision(3) << (1e-6 * (totalsizewrite * ndisks) / totaltimewrite) << " MB/s write,"; std::cout << std::setw(2) << ndisks << " * " << std::setw(7) << std::setprecision(3) << (1e-6 * (totalsizeread) / totaltimeread) << " = " << std::setw(7) << std::setprecision(3) << (1e-6 * (totalsizeread * ndisks) / totaltimeread) << " MB/s read" << std::endl; delete [] reqs; delete [] disks; aligned_dealloc<BLOCK_ALIGN>(buffer); #ifdef WATCH_TIMES delete [] r_finish_times; delete [] w_finish_times; #endif return 0; } <|endoftext|>
<commit_before>// @(#)root/io:$Id$ // Author: Elvin Sindrilaru 19/05/2011 /************************************************************************* * Copyright (C) 1995-2011, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // TFPBlock // // // // This class represents the encapsulation of a block request. // // It contains the chunks to be prefetched and also serves as a // // container for the information read. // // These blocks are prefetch in a special reader thread by the // // TFilePrefetch class. // // // ////////////////////////////////////////////////////////////////////////// #include "TFPBlock.h" #include "TStorage.h" #include <cstdlib> ClassImp(TFPBlock) //__________________________________________________________________ TFPBlock::TFPBlock(Long64_t* offset, Int_t* length, Int_t nb) { // Constructor. Int_t aux = 0; fNblock = nb; fPos = new Long64_t[nb]; fLen = new Int_t[nb]; for (Int_t i=0; i < nb; i++){ fPos[i] = offset[i]; fLen[i] = length[i]; aux += length[i]; } fFullSize = aux; fBuffer = new char[fFullSize]; } //__________________________________________________________________ TFPBlock::~TFPBlock() { // Destructor. delete[] fPos; delete[] fLen; delete[] fBuffer; } //__________________________________________________________________ Long64_t* TFPBlock::GetPos() const { // Get pointer to the array of postions. return fPos; } //__________________________________________________________________ Int_t* TFPBlock::GetLen() const { // Get pointer to the array of lengths. return fLen; } //__________________________________________________________________ Int_t TFPBlock::GetFullSize() const { // Return size of the block. return fFullSize; } //__________________________________________________________________ Int_t TFPBlock::GetNoElem() const { // Return number of elements in the block. return fNblock; } //__________________________________________________________________ Long64_t TFPBlock::GetPos(Int_t i) const { // Get position of the element at index i. return fPos[i]; } //__________________________________________________________________ Int_t TFPBlock::GetLen(Int_t i) const { // Get length of the element at index i. return fLen[i]; } //__________________________________________________________________ char* TFPBlock::GetBuffer() const { // Get block buffer. return fBuffer; } //__________________________________________________________________ void TFPBlock::SetBuffer(char* buf) { // Set block buffer. fBuffer = buf; } //__________________________________________________________________ void TFPBlock::ReallocBlock(Long64_t* offset, Int_t* length, Int_t nb) { // Reallocate the block's buffer based on the length // of the elements it will contain. Int_t aux = 0; fNblock = nb; fPos = new Long64_t[nb]; fLen = new Int_t[nb]; for(Int_t i=0; i < nb; i++){ fPos[i] = offset[i]; fLen[i] = length[i]; aux += fLen[i]; } fBuffer = TStorage::ReAllocChar(fBuffer, aux, fFullSize); fFullSize = aux; } <commit_msg>From Elvin: fix memory leak<commit_after>// @(#)root/io:$Id$ // Author: Elvin Sindrilaru 19/05/2011 /************************************************************************* * Copyright (C) 1995-2011, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // TFPBlock // // // // This class represents the encapsulation of a block request. // // It contains the chunks to be prefetched and also serves as a // // container for the information read. // // These blocks are prefetch in a special reader thread by the // // TFilePrefetch class. // // // ////////////////////////////////////////////////////////////////////////// #include "TFPBlock.h" #include "TStorage.h" #include <cstdlib> ClassImp(TFPBlock) //__________________________________________________________________ TFPBlock::TFPBlock(Long64_t* offset, Int_t* length, Int_t nb) { // Constructor. Int_t aux = 0; fNblock = nb; fPos = new Long64_t[nb]; fLen = new Int_t[nb]; for (Int_t i=0; i < nb; i++){ fPos[i] = offset[i]; fLen[i] = length[i]; aux += length[i]; } fFullSize = aux; fBuffer = new char[fFullSize]; } //__________________________________________________________________ TFPBlock::~TFPBlock() { // Destructor. delete[] fPos; delete[] fLen; delete[] fBuffer; } //__________________________________________________________________ Long64_t* TFPBlock::GetPos() const { // Get pointer to the array of postions. return fPos; } //__________________________________________________________________ Int_t* TFPBlock::GetLen() const { // Get pointer to the array of lengths. return fLen; } //__________________________________________________________________ Int_t TFPBlock::GetFullSize() const { // Return size of the block. return fFullSize; } //__________________________________________________________________ Int_t TFPBlock::GetNoElem() const { // Return number of elements in the block. return fNblock; } //__________________________________________________________________ Long64_t TFPBlock::GetPos(Int_t i) const { // Get position of the element at index i. return fPos[i]; } //__________________________________________________________________ Int_t TFPBlock::GetLen(Int_t i) const { // Get length of the element at index i. return fLen[i]; } //__________________________________________________________________ char* TFPBlock::GetBuffer() const { // Get block buffer. return fBuffer; } //__________________________________________________________________ void TFPBlock::SetBuffer(char* buf) { // Set block buffer. fBuffer = buf; } //__________________________________________________________________ void TFPBlock::ReallocBlock(Long64_t* offset, Int_t* length, Int_t nb) { // Reallocate the block's buffer based on the length // of the elements it will contain. Int_t aux = 0; fPos = (Long64_t*) TStorage::ReAlloc(fPos, nb * sizeof(Long64_t), fNblock * sizeof(Long64_t)); fLen = TStorage::ReAllocInt(fLen, nb, fNblock); fNblock = nb; for(Int_t i=0; i < nb; i++){ fPos[i] = offset[i]; fLen[i] = length[i]; aux += fLen[i]; } fBuffer = TStorage::ReAllocChar(fBuffer, aux, fFullSize); fFullSize = aux; } <|endoftext|>
<commit_before>// @(#)root/io:$Id$ // Author: Elvin Sindrilaru 19/05/2011 /************************************************************************* * Copyright (C) 1995-2011, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // TFPBlock // // // // This class represents the encapsulation of a block request. // // It contains the chunks to be prefetched and also serves as a // // container for the information read. // // These blocks are prefetch in a special reader thread by the // // TFilePrefetch class. // // // ////////////////////////////////////////////////////////////////////////// #include "TFPBlock.h" #include "TStorage.h" #include <cstdlib> ClassImp(TFPBlock) //__________________________________________________________________ TFPBlock::TFPBlock(Long64_t* offset, Int_t* length, Int_t nb) { // Constructor. Int_t aux = 0; fNblock = nb; fPos = new Long64_t[nb]; fLen = new Int_t[nb]; for (Int_t i=0; i < nb; i++){ fPos[i] = offset[i]; fLen[i] = length[i]; aux += length[i]; } fFullSize = aux; fBuffer = new char[fFullSize]; } //__________________________________________________________________ TFPBlock::~TFPBlock() { // Destructor. delete[] fPos; delete[] fLen; delete[] fBuffer; } //__________________________________________________________________ Long64_t* TFPBlock::GetPos() const { // Get pointer to the array of postions. return fPos; } //__________________________________________________________________ Int_t* TFPBlock::GetLen() const { // Get pointer to the array of lengths. return fLen; } //__________________________________________________________________ Int_t TFPBlock::GetFullSize() const { // Return size of the block. return fFullSize; } //__________________________________________________________________ Int_t TFPBlock::GetNoElem() const { // Return number of elements in the block. return fNblock; } //__________________________________________________________________ Long64_t TFPBlock::GetPos(Int_t i) const { // Get position of the element at index i. return fPos[i]; } //__________________________________________________________________ Int_t TFPBlock::GetLen(Int_t i) const { // Get length of the element at index i. return fLen[i]; } //__________________________________________________________________ char* TFPBlock::GetBuffer() const { // Get block buffer. return fBuffer; } //__________________________________________________________________ void TFPBlock::SetBuffer(char* buf) { // Set block buffer. fBuffer = buf; } //__________________________________________________________________ void TFPBlock::ReallocBlock(Long64_t* offset, Int_t* length, Int_t nb) { // Reallocate the block's buffer based on the length // of the elements it will contain. Int_t aux = 0; fNblock = nb; fPos = new Long64_t[nb]; fLen = new Int_t[nb]; for(Int_t i=0; i < nb; i++){ fPos[i] = offset[i]; fLen[i] = length[i]; aux += fLen[i]; } fBuffer = TStorage::ReAllocChar(fBuffer, aux, fFullSize); fFullSize = aux; } <commit_msg>From Elvin: fix memory leak<commit_after>// @(#)root/io:$Id$ // Author: Elvin Sindrilaru 19/05/2011 /************************************************************************* * Copyright (C) 1995-2011, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // TFPBlock // // // // This class represents the encapsulation of a block request. // // It contains the chunks to be prefetched and also serves as a // // container for the information read. // // These blocks are prefetch in a special reader thread by the // // TFilePrefetch class. // // // ////////////////////////////////////////////////////////////////////////// #include "TFPBlock.h" #include "TStorage.h" #include <cstdlib> ClassImp(TFPBlock) //__________________________________________________________________ TFPBlock::TFPBlock(Long64_t* offset, Int_t* length, Int_t nb) { // Constructor. Int_t aux = 0; fNblock = nb; fPos = new Long64_t[nb]; fLen = new Int_t[nb]; for (Int_t i=0; i < nb; i++){ fPos[i] = offset[i]; fLen[i] = length[i]; aux += length[i]; } fFullSize = aux; fBuffer = new char[fFullSize]; } //__________________________________________________________________ TFPBlock::~TFPBlock() { // Destructor. delete[] fPos; delete[] fLen; delete[] fBuffer; } //__________________________________________________________________ Long64_t* TFPBlock::GetPos() const { // Get pointer to the array of postions. return fPos; } //__________________________________________________________________ Int_t* TFPBlock::GetLen() const { // Get pointer to the array of lengths. return fLen; } //__________________________________________________________________ Int_t TFPBlock::GetFullSize() const { // Return size of the block. return fFullSize; } //__________________________________________________________________ Int_t TFPBlock::GetNoElem() const { // Return number of elements in the block. return fNblock; } //__________________________________________________________________ Long64_t TFPBlock::GetPos(Int_t i) const { // Get position of the element at index i. return fPos[i]; } //__________________________________________________________________ Int_t TFPBlock::GetLen(Int_t i) const { // Get length of the element at index i. return fLen[i]; } //__________________________________________________________________ char* TFPBlock::GetBuffer() const { // Get block buffer. return fBuffer; } //__________________________________________________________________ void TFPBlock::SetBuffer(char* buf) { // Set block buffer. fBuffer = buf; } //__________________________________________________________________ void TFPBlock::ReallocBlock(Long64_t* offset, Int_t* length, Int_t nb) { // Reallocate the block's buffer based on the length // of the elements it will contain. Int_t aux = 0; fPos = (Long64_t*) TStorage::ReAlloc(fPos, nb * sizeof(Long64_t), fNblock * sizeof(Long64_t)); fLen = TStorage::ReAllocInt(fLen, nb, fNblock); fNblock = nb; for(Int_t i=0; i < nb; i++){ fPos[i] = offset[i]; fLen[i] = length[i]; aux += fLen[i]; } fBuffer = TStorage::ReAllocChar(fBuffer, aux, fFullSize); fFullSize = aux; } <|endoftext|>
<commit_before>#include "boost/filesystem.hpp" #include "boost/filesystem/fstream.hpp" #include "soci/soci/src/core/soci.h" #include "soci/soci/src/backends/sqlite3/soci-sqlite3.h" #include <algorithm> #include <cstdlib> #include <exception> #include <iostream> #include <map> #include <string> #include <vector> #include "PlaylistController.h" #include "SettingsController.h" using std::cout; using std::map; using std::string; using std::vector; using namespace soci; using boost::filesystem::ofstream; using boost::filesystem::ifstream; using namespace boost::filesystem; extern SettingsController sc; PlaylistController::PlaylistController() { } void PlaylistController::addplaylist(Playlist& pl, const int pos) { if(pos < 0) { playlists.push_back(pl); selection = begin() + offset; dispoffset = size() - 1; dispselection = begin() + dispoffset; } else if((size_t)pos < playlists.size()) { playlists.insert(begin() + pos, pl); selection = begin() + offset; dispoffset = pos; dispselection = begin() + dispoffset; } } void PlaylistController::autoaddplaylist(path p) { if(!exists(p)) return; if(!is_directory(p)) return; string n = p.filename().string(); if(n.empty()) return; Playlist pl(n); map<string,string> shows; for(auto i = directory_iterator(p); i != directory_iterator(); ++i) { shows[i->path().filename().string()] = i->path().string(); } #if __GNUC__ <= 4 && __GNUC_MINOR__ < 6 size_t size = shows.size(); for(size_t i = 0; i < size; ++i) { Show s(shows[i].second, shows[i].first, EPISODE); pl.add(s); } #else for(auto &i: shows) { Show s(i.second, i.first, EPISODE); pl.add(s); } #endif addplaylist(pl); } auto PlaylistController::begin() -> decltype(playlists.begin()) { return playlists.begin(); } auto PlaylistController::cbegin() -> decltype(playlists.cbegin()) { return playlists.cbegin(); } void deleteselected() {} auto PlaylistController::end() -> decltype(playlists.end()) { return playlists.end(); } auto PlaylistController::cend() -> decltype(playlists.cend()) { return playlists.cend(); } bool PlaylistController::empty() { return playlists.empty(); } auto PlaylistController::getselection() -> decltype(selection) { selection = begin() + offset; return selection; } auto PlaylistController::getdispselection() -> decltype(selection) { dispselection = begin() + dispoffset; return dispselection; } void PlaylistController::go() { offset = dispoffset; selection = dispselection; } void PlaylistController::go(decltype(selection) pos) { //if(pos >= begin() && pos < end()) selection = pos; } void PlaylistController::offsetselection(size_t o) { auto s = selection + o; if(s >= begin() && s < end()) { selection = s; offset += o; } return; } void PlaylistController::offsetdispselection(size_t o) { auto s = dispselection + o; if(s >= begin() && s < end()) { dispselection = s; dispoffset += o; } return; } /** Database loading and saving */ bool PlaylistController::loaddb() { bool ret = true; ifstream db; db.open(sc.data); size_t played, size; unsigned int watched; string name, type, file; //TODO: Better error checking while(db.good()) { db >> played >> size; db.ignore(); getline(db, name); if(db.fail()) { goto cleanup; } Playlist p(name); for(size_t i = 0; i < size; ++i) { db >> watched >> type; db.ignore(100,'\n'); getline(db, name); getline(db, file); // The file was incorrectly formatted if(db.fail()) { ret = false; goto cleanup; } Show s(file, name, Show::gettype(type), watched); p.add(s); } Playlist pl(p.getname(),p); addplaylist(pl); } cleanup: selection = dispselection = begin(); offset = dispoffset = 0; std::sort(begin(), end()); db.close(); return ret; } bool PlaylistController::savedb() { ofstream db; db.open(sc.data); //TODO: Better error checking #if __GNUC__ <= 4 && __GNUC_MINOR__ < 6 size_t size = playlists.size(); for(size_t i = 0; i < size; ++i) { playlists[i].printdetail(db); db << '\n'; size_t shows_size = shows.size(); for(size_t j = 0; j < shows_size; ++j) { shows[j].printdetail(db); db << '\n'; } } #else for(Playlist& p : playlists) { p.printdetail(db); db << '\n'; for(Show& s : p) { s.printdetail(db); db << '\n'; } } #endif db.close(); savedb_new(); return true; } bool PlaylistController::db_create(bool exists, session& db) { const double version = .2; double v = 0; indicator ind; bool init = true, caught = false; // TODO: remove exists once we drop old database stuff if(exists) { try { db << "SELECT Number FROM Version", into(v, ind); } catch (const std::exception& e) { init = true; caught = true; } if(!caught && db.got_data()) { switch(ind) { case i_ok: init = false; break; case i_null: break; case i_truncated: break; } if(v < version) { init = true; } } } else init = true; if(init) { db << "CREATE TABLE IF NOT EXISTS Playlists (" "Name TEXT PRIMARY KEY ASC NOT NULL" ")"; db << "CREATE TABLE IF NOT EXISTS Version (" "Number REAL NOT NULL" ")"; db << "CREATE TABLE IF NOT EXISTS Shows (" "File TEXT PRIMARY KEY ASC NOT NULL, " "Name TEXT, " "ID INT NOT NULL, " "Watched INT DEFAULT 0, " "Type TEXT NOT NULL DEFAULT EPISODE, " "Playlist REFERENCES Playlists (Name) ON DELETE CASCADE ON UPDATE CASCADE" ")"; if(exists && !caught && v < version) { db << "UPDATE Version SET Number = :version", use(version); } else db << "INSERT INTO Version (Number) VALUES(:version)", use(version); // TODO: remove this once we drop old database stuff if(!exists) { #if __GNUC__ <= 4 && __GNUC_MINOR__ < 6 int order = 0; for(auto i = playlists.begin(); i < playlists.end(); ++i) { db << "INSERT INTO Playlists VALUES(:NAME)", use(playlists[i]); for(auto j = playlists[i].begin(); j < playlists[i].end(); ++j) { db << "INSERT INTO Shows VALUES(:FILE,:NAME,:WATCHED,:TYPE,:PLAYLIST)", use(*j), use((*j).getname(), "PLAYLIST"); } } #else int order = 0; for(Playlist& p : playlists) { db << "INSERT INTO Playlists VALUES(:NAME)", use(p); for(Show& s : p) { db << "INSERT INTO Shows VALUES(:FILE,:NAME,:WATCHED,:TYPE,:PLAYLIST)", use(s), use(p.getname(), "PLAYLIST"); } } #endif } db << "SELECT Number FROM Version", into(v, ind); if(db.got_data()) { switch(ind) { case i_ok: return true; break; case i_null: return false; break; case i_truncated: break; } } } return false; } bool PlaylistController::savedb_new() { bool exists = boost::filesystem::exists(sc.db); session db(sqlite3, sc.db.native()); // TODO: remove exists once we drop old database stuff assert(db_create(exists, db)); #if __GNUC__ <= 4 && __GNUC_MINOR__ < 6 size_t size = playlists.size(); for(size_t i = 0; i < size; ++i) { if(playlists[i].haschanged()) { std::string name; indicator ind; db << "SELECT Name FROM Playlists WHERE Name == :OLDNAME", use(playlists[i]), into(name, ind); if(ind == i_ok && db.got_data()) { db << "UPDATE Playlists SET " "Name=:NAME " "WHERE Name == :OLDNAME", use(playlists[i]); } else { db << "INSERT INTO Playlists VALUES(:NAME)", use(playlists[i]); } } size_t shows_size = p.size(); for(size_t j = 0; j < shows_size; ++j) { //s.printdetail(db); //db << '\n'; } } #else for(Playlist& p : playlists) { if(p.haschanged()) { std::string name; indicator ind; db << "SELECT Name FROM Playlists WHERE Name == :OLDNAME", use(p), into(name, ind); if(ind == i_ok && db.got_data()) { db << "UPDATE Playlists SET " "Name=:NAME " "WHERE Name == :OLDNAME", use(p); } else { db << "INSERT INTO Playlists VALUES(:NAME)", use(p); } } for(Show& s : p) { //s.printdetail(db); //db << '\n'; } } #endif return true; } size_t PlaylistController::size() { return playlists.size(); } <commit_msg>attempt a fix for boost::filesystem library changes<commit_after>#include "boost/filesystem.hpp" #include "boost/filesystem/fstream.hpp" #include "soci/soci/src/core/soci.h" #include "soci/soci/src/backends/sqlite3/soci-sqlite3.h" #include <algorithm> #include <cstdlib> #include <exception> #include <iostream> #include <map> #include <string> #include <vector> #include "PlaylistController.h" #include "SettingsController.h" using std::cout; using std::map; using std::string; using std::vector; using namespace soci; using boost::filesystem::ofstream; using boost::filesystem::ifstream; using namespace boost::filesystem; extern SettingsController sc; PlaylistController::PlaylistController() { } void PlaylistController::addplaylist(Playlist& pl, const int pos) { if(pos < 0) { playlists.push_back(pl); selection = begin() + offset; dispoffset = size() - 1; dispselection = begin() + dispoffset; } else if((size_t)pos < playlists.size()) { playlists.insert(begin() + pos, pl); selection = begin() + offset; dispoffset = pos; dispselection = begin() + dispoffset; } } void PlaylistController::autoaddplaylist(path p) { if(!exists(p)) return; if(!is_directory(p)) return; #if BOOST_FILESYSTEM_VERSION == 3 string n = p.filename().string(); #else string n = p.filename(); #endif if(n.empty()) return; Playlist pl(n); map<string,string> shows; for(auto i = directory_iterator(p); i != directory_iterator(); ++i) { #if BOOST_FILESYSTEM_VERSION == 3 shows[i->path().filename().string()] = i->path().string(); #else shows[i->path().filename()] = i->path(); #endif } #if __GNUC__ <= 4 && __GNUC_MINOR__ < 6 size_t size = shows.size(); for(size_t i = 0; i < size; ++i) { Show s(shows[i].second, shows[i].first, EPISODE); pl.add(s); } #else for(auto &i: shows) { Show s(i.second, i.first, EPISODE); pl.add(s); } #endif addplaylist(pl); } auto PlaylistController::begin() -> decltype(playlists.begin()) { return playlists.begin(); } auto PlaylistController::cbegin() -> decltype(playlists.cbegin()) { return playlists.cbegin(); } void deleteselected() {} auto PlaylistController::end() -> decltype(playlists.end()) { return playlists.end(); } auto PlaylistController::cend() -> decltype(playlists.cend()) { return playlists.cend(); } bool PlaylistController::empty() { return playlists.empty(); } auto PlaylistController::getselection() -> decltype(selection) { selection = begin() + offset; return selection; } auto PlaylistController::getdispselection() -> decltype(selection) { dispselection = begin() + dispoffset; return dispselection; } void PlaylistController::go() { offset = dispoffset; selection = dispselection; } void PlaylistController::go(decltype(selection) pos) { //if(pos >= begin() && pos < end()) selection = pos; } void PlaylistController::offsetselection(size_t o) { auto s = selection + o; if(s >= begin() && s < end()) { selection = s; offset += o; } return; } void PlaylistController::offsetdispselection(size_t o) { auto s = dispselection + o; if(s >= begin() && s < end()) { dispselection = s; dispoffset += o; } return; } /** Database loading and saving */ bool PlaylistController::loaddb() { bool ret = true; ifstream db; db.open(sc.data); size_t played, size; unsigned int watched; string name, type, file; //TODO: Better error checking while(db.good()) { db >> played >> size; db.ignore(); getline(db, name); if(db.fail()) { goto cleanup; } Playlist p(name); for(size_t i = 0; i < size; ++i) { db >> watched >> type; db.ignore(100,'\n'); getline(db, name); getline(db, file); // The file was incorrectly formatted if(db.fail()) { ret = false; goto cleanup; } Show s(file, name, Show::gettype(type), watched); p.add(s); } Playlist pl(p.getname(),p); addplaylist(pl); } cleanup: selection = dispselection = begin(); offset = dispoffset = 0; std::sort(begin(), end()); db.close(); return ret; } bool PlaylistController::savedb() { ofstream db; db.open(sc.data); //TODO: Better error checking #if __GNUC__ <= 4 && __GNUC_MINOR__ < 6 size_t size = playlists.size(); for(size_t i = 0; i < size; ++i) { playlists[i].printdetail(db); db << '\n'; size_t shows_size = shows.size(); for(size_t j = 0; j < shows_size; ++j) { shows[j].printdetail(db); db << '\n'; } } #else for(Playlist& p : playlists) { p.printdetail(db); db << '\n'; for(Show& s : p) { s.printdetail(db); db << '\n'; } } #endif db.close(); savedb_new(); return true; } bool PlaylistController::db_create(bool exists, session& db) { const double version = .2; double v = 0; indicator ind; bool init = true, caught = false; // TODO: remove exists once we drop old database stuff if(exists) { try { db << "SELECT Number FROM Version", into(v, ind); } catch (const std::exception& e) { init = true; caught = true; } if(!caught && db.got_data()) { switch(ind) { case i_ok: init = false; break; case i_null: break; case i_truncated: break; } if(v < version) { init = true; } } } else init = true; if(init) { db << "CREATE TABLE IF NOT EXISTS Playlists (" "Name TEXT PRIMARY KEY ASC NOT NULL" ")"; db << "CREATE TABLE IF NOT EXISTS Version (" "Number REAL NOT NULL" ")"; db << "CREATE TABLE IF NOT EXISTS Shows (" "File TEXT PRIMARY KEY ASC NOT NULL, " "Name TEXT, " "ID INT NOT NULL, " "Watched INT DEFAULT 0, " "Type TEXT NOT NULL DEFAULT EPISODE, " "Playlist REFERENCES Playlists (Name) ON DELETE CASCADE ON UPDATE CASCADE" ")"; if(exists && !caught && v < version) { db << "UPDATE Version SET Number = :version", use(version); } else db << "INSERT INTO Version (Number) VALUES(:version)", use(version); // TODO: remove this once we drop old database stuff if(!exists) { #if __GNUC__ <= 4 && __GNUC_MINOR__ < 6 int order = 0; for(auto i = playlists.begin(); i < playlists.end(); ++i) { db << "INSERT INTO Playlists VALUES(:NAME)", use(playlists[i]); for(auto j = playlists[i].begin(); j < playlists[i].end(); ++j) { db << "INSERT INTO Shows VALUES(:FILE,:NAME,:WATCHED,:TYPE,:PLAYLIST)", use(*j), use((*j).getname(), "PLAYLIST"); } } #else int order = 0; for(Playlist& p : playlists) { db << "INSERT INTO Playlists VALUES(:NAME)", use(p); for(Show& s : p) { db << "INSERT INTO Shows VALUES(:FILE,:NAME,:WATCHED,:TYPE,:PLAYLIST)", use(s), use(p.getname(), "PLAYLIST"); } } #endif } db << "SELECT Number FROM Version", into(v, ind); if(db.got_data()) { switch(ind) { case i_ok: return true; break; case i_null: return false; break; case i_truncated: break; } } } return false; } bool PlaylistController::savedb_new() { bool exists = boost::filesystem::exists(sc.db); session db(sqlite3, sc.db.native()); // TODO: remove exists once we drop old database stuff assert(db_create(exists, db)); #if __GNUC__ <= 4 && __GNUC_MINOR__ < 6 size_t size = playlists.size(); for(size_t i = 0; i < size; ++i) { if(playlists[i].haschanged()) { std::string name; indicator ind; db << "SELECT Name FROM Playlists WHERE Name == :OLDNAME", use(playlists[i]), into(name, ind); if(ind == i_ok && db.got_data()) { db << "UPDATE Playlists SET " "Name=:NAME " "WHERE Name == :OLDNAME", use(playlists[i]); } else { db << "INSERT INTO Playlists VALUES(:NAME)", use(playlists[i]); } } size_t shows_size = p.size(); for(size_t j = 0; j < shows_size; ++j) { //s.printdetail(db); //db << '\n'; } } #else for(Playlist& p : playlists) { if(p.haschanged()) { std::string name; indicator ind; db << "SELECT Name FROM Playlists WHERE Name == :OLDNAME", use(p), into(name, ind); if(ind == i_ok && db.got_data()) { db << "UPDATE Playlists SET " "Name=:NAME " "WHERE Name == :OLDNAME", use(p); } else { db << "INSERT INTO Playlists VALUES(:NAME)", use(p); } } for(Show& s : p) { //s.printdetail(db); //db << '\n'; } } #endif return true; } size_t PlaylistController::size() { return playlists.size(); } <|endoftext|>
<commit_before>/* * Software License Agreement (BSD License) * * Copyright (c) 2011, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE 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. * * Author: Suat Gedikli ([email protected]) */ #include <pcl/pcl_config.h> #ifdef HAVE_OPENNI #include <pcl/io/pcd_grabber.h> #include <pcl/point_cloud.h> #include <pcl/point_types.h> #include <pcl/io/pcd_io.h> //////////////////////// GrabberImplementation ////////////////////// struct pcl::PCDGrabberBase::PCDGrabberImpl { PCDGrabberImpl (pcl::PCDGrabberBase& grabber, const std::string& pcd_path, float frames_per_second, bool repeat); PCDGrabberImpl (pcl::PCDGrabberBase& grabber, const std::vector<std::string>& pcd_files, float frames_per_second, bool repeat); void trigger (); void readAhead (); pcl::PCDGrabberBase& grabber_; float frames_per_second_; bool repeat_; bool running_; std::vector<std::string> pcd_files_; std::vector<std::string>::iterator pcd_iterator_; TimeTrigger time_trigger_; sensor_msgs::PointCloud2 next_cloud_; bool valid_; }; pcl::PCDGrabberBase::PCDGrabberImpl::PCDGrabberImpl (pcl::PCDGrabberBase& grabber, const std::string& pcd_path, float frames_per_second, bool repeat) : grabber_ (grabber) , frames_per_second_ (frames_per_second) , repeat_ (repeat) , running_ (false) , time_trigger_ (1.0 / (double) std::max(frames_per_second, 0.001f), boost::bind (&PCDGrabberImpl::trigger, this)) , valid_ (false) { pcd_files_.push_back (pcd_path); pcd_iterator_ = pcd_files_.begin (); } pcl::PCDGrabberBase::PCDGrabberImpl::PCDGrabberImpl (pcl::PCDGrabberBase& grabber, const std::vector<std::string>& pcd_files, float frames_per_second, bool repeat) : grabber_ (grabber) , frames_per_second_ (frames_per_second) , repeat_ (repeat) , running_ (false) , time_trigger_ (1.0 / (double) std::max(frames_per_second, 0.001f), boost::bind (&PCDGrabberImpl::trigger, this)) , valid_ (false) { pcd_files_ = pcd_files; pcd_iterator_ = pcd_files_.begin (); } void pcl::PCDGrabberBase::PCDGrabberImpl::readAhead () { if (pcd_iterator_ != pcd_files_.end ()) { PCDReader reader; int pcd_version; Eigen::Vector4f origin; Eigen::Quaternionf orientation; valid_ = (reader.read (*pcd_iterator_, next_cloud_, origin, orientation, pcd_version) == 0); if (++pcd_iterator_ == pcd_files_.end () && repeat_) pcd_iterator_ = pcd_files_.begin (); } else valid_ = false; } void pcl::PCDGrabberBase::PCDGrabberImpl::trigger () { if (valid_) grabber_.publish (next_cloud_); // use remaining time, if there is time left! readAhead (); } //////////////////////// GrabberBase ////////////////////// pcl::PCDGrabberBase::PCDGrabberBase (const std::string& pcd_path, float frames_per_second, bool repeat) : impl_( new PCDGrabberImpl (*this, pcd_path, frames_per_second, repeat ) ) { } pcl::PCDGrabberBase::PCDGrabberBase (const std::vector<std::string>& pcd_files, float frames_per_second, bool repeat) : impl_( new PCDGrabberImpl (*this, pcd_files, frames_per_second, repeat) ) { } pcl::PCDGrabberBase::~PCDGrabberBase () throw () { stop (); delete impl_; } void pcl::PCDGrabberBase::start () { if (impl_->frames_per_second_ > 0) { impl_->running_ = true; impl_->time_trigger_.start (); } else // manual trigger { impl_->trigger (); } } void pcl::PCDGrabberBase::stop () { if (impl_->frames_per_second_ > 0) { impl_->time_trigger_.stop (); impl_->running_ = false; } } bool pcl::PCDGrabberBase::isRunning () const { return impl_->running_; } std::string pcl::PCDGrabberBase::getName () const { return "PCDGrabber"; } void pcl::PCDGrabberBase::rewind () { impl_->pcd_iterator_ = impl_->pcd_files_.begin (); } float pcl::PCDGrabberBase::getFramesPerSecond () const { return impl_->frames_per_second_; } bool pcl::PCDGrabberBase::isRepeatOn () const { return impl_->repeat_; } #endif <commit_msg>removed OPENNI ifdefs<commit_after>/* * Software License Agreement (BSD License) * * Point Cloud Library (PCL) - www.pointclouds.org * Copyright (c) 2010-2011, Willow Garage, Inc. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE 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 <pcl/pcl_config.h> #include <pcl/io/pcd_grabber.h> #include <pcl/point_cloud.h> #include <pcl/point_types.h> #include <pcl/io/pcd_io.h> /////////////////////////////////////////////////////////////////////////////////////////// //////////////////////// GrabberImplementation ////////////////////// struct pcl::PCDGrabberBase::PCDGrabberImpl { PCDGrabberImpl (pcl::PCDGrabberBase& grabber, const std::string& pcd_path, float frames_per_second, bool repeat); PCDGrabberImpl (pcl::PCDGrabberBase& grabber, const std::vector<std::string>& pcd_files, float frames_per_second, bool repeat); void trigger (); void readAhead (); pcl::PCDGrabberBase& grabber_; float frames_per_second_; bool repeat_; bool running_; std::vector<std::string> pcd_files_; std::vector<std::string>::iterator pcd_iterator_; TimeTrigger time_trigger_; sensor_msgs::PointCloud2 next_cloud_; bool valid_; }; /////////////////////////////////////////////////////////////////////////////////////////// pcl::PCDGrabberBase::PCDGrabberImpl::PCDGrabberImpl (pcl::PCDGrabberBase& grabber, const std::string& pcd_path, float frames_per_second, bool repeat) : grabber_ (grabber) , frames_per_second_ (frames_per_second) , repeat_ (repeat) , running_ (false) , time_trigger_ (1.0 / (double) std::max(frames_per_second, 0.001f), boost::bind (&PCDGrabberImpl::trigger, this)) , valid_ (false) { pcd_files_.push_back (pcd_path); pcd_iterator_ = pcd_files_.begin (); } /////////////////////////////////////////////////////////////////////////////////////////// pcl::PCDGrabberBase::PCDGrabberImpl::PCDGrabberImpl (pcl::PCDGrabberBase& grabber, const std::vector<std::string>& pcd_files, float frames_per_second, bool repeat) : grabber_ (grabber) , frames_per_second_ (frames_per_second) , repeat_ (repeat) , running_ (false) , time_trigger_ (1.0 / (double) std::max(frames_per_second, 0.001f), boost::bind (&PCDGrabberImpl::trigger, this)) , valid_ (false) { pcd_files_ = pcd_files; pcd_iterator_ = pcd_files_.begin (); } /////////////////////////////////////////////////////////////////////////////////////////// void pcl::PCDGrabberBase::PCDGrabberImpl::readAhead () { if (pcd_iterator_ != pcd_files_.end ()) { PCDReader reader; int pcd_version; Eigen::Vector4f origin; Eigen::Quaternionf orientation; valid_ = (reader.read (*pcd_iterator_, next_cloud_, origin, orientation, pcd_version) == 0); if (++pcd_iterator_ == pcd_files_.end () && repeat_) pcd_iterator_ = pcd_files_.begin (); } else valid_ = false; } void pcl::PCDGrabberBase::PCDGrabberImpl::trigger () { if (valid_) grabber_.publish (next_cloud_); // use remaining time, if there is time left! readAhead (); } /////////////////////////////////////////////////////////////////////////////////////////// //////////////////////// GrabberBase ////////////////////// pcl::PCDGrabberBase::PCDGrabberBase (const std::string& pcd_path, float frames_per_second, bool repeat) : impl_( new PCDGrabberImpl (*this, pcd_path, frames_per_second, repeat ) ) { } /////////////////////////////////////////////////////////////////////////////////////////// pcl::PCDGrabberBase::PCDGrabberBase (const std::vector<std::string>& pcd_files, float frames_per_second, bool repeat) : impl_( new PCDGrabberImpl (*this, pcd_files, frames_per_second, repeat) ) { } /////////////////////////////////////////////////////////////////////////////////////////// pcl::PCDGrabberBase::~PCDGrabberBase () throw () { stop (); delete impl_; } /////////////////////////////////////////////////////////////////////////////////////////// void pcl::PCDGrabberBase::start () { if (impl_->frames_per_second_ > 0) { impl_->running_ = true; impl_->time_trigger_.start (); } else // manual trigger impl_->trigger (); } /////////////////////////////////////////////////////////////////////////////////////////// void pcl::PCDGrabberBase::stop () { if (impl_->frames_per_second_ > 0) { impl_->time_trigger_.stop (); impl_->running_ = false; } } /////////////////////////////////////////////////////////////////////////////////////////// bool pcl::PCDGrabberBase::isRunning () const { return (impl_->running_); } /////////////////////////////////////////////////////////////////////////////////////////// std::string pcl::PCDGrabberBase::getName () const { return ("PCDGrabber"); } /////////////////////////////////////////////////////////////////////////////////////////// void pcl::PCDGrabberBase::rewind () { impl_->pcd_iterator_ = impl_->pcd_files_.begin (); } /////////////////////////////////////////////////////////////////////////////////////////// float pcl::PCDGrabberBase::getFramesPerSecond () const { return (impl_->frames_per_second_); } /////////////////////////////////////////////////////////////////////////////////////////// bool pcl::PCDGrabberBase::isRepeatOn () const { return (impl_->repeat_); } <|endoftext|>
<commit_before><commit_msg>gtk: fix display of icons in omnibox popup<commit_after><|endoftext|>
<commit_before>/** * @file */ #pragma once /** * @def LIBBIRCH_ATOMIC_OPENMP * * Set to true for libbirch::Atomic use OpenMP, or false to use std::atomic. * * The advantage of the OpenMP implementation is assured memory model * consistency and the organic disabling of atomics when OpenMP, and thus * multithreading, is disabled (this can improve performance significantly for * single threading). The disadvantage is that OpenMP atomics do not support * compare-and-swap/compare-and-exchange, only swap/exchange, which can * require some clunkier client code, especially for read-write locks. */ #define LIBBIRCH_ATOMIC_OPENMP 1 #if !LIBBIRCH_ATOMIC_OPENMP #include <atomic> #endif namespace libbirch { /** * Atomic value. * * @tparam Value type. */ template<class T> class Atomic { public: /** * Default constructor. Initializes the value, not necessarily atomically. */ Atomic() = default; /** * Constructor. * * @param value Initial value. * * Initializes the value, atomically. */ explicit Atomic(const T& value) { store(value); } /** * Load the value, atomically. */ T load() const { #if LIBBIRCH_ATOMIC_OPENMP T value; #pragma omp atomic read value = this->value; return value; #else return this->value.load(std::memory_order_relaxed); #endif } /** * Store the value, atomically. */ void store(const T& value) { #if LIBBIRCH_ATOMIC_OPENMP #pragma omp atomic write this->value = value; #else this->value.store(value, std::memory_order_relaxed); #endif } /** * Exchange the value with another, atomically. * * @param value New value. * * @return Old value. */ T exchange(const T& value) { #if LIBBIRCH_ATOMIC_OPENMP T old; #pragma omp atomic capture { old = this->value; this->value = value; } return old; #else return this->value.exchange(value, std::memory_order_relaxed); #endif } /** * Apply a mask, with bitwise `and`, and return the previous value, * atomically. * * @param m Mask. * * @return Previous value. */ T exchangeAnd(const T& value) { #if LIBBIRCH_ATOMIC_OPENMP T old; #pragma omp atomic capture { old = this->value; this->value &= value; } return old; #else return this->value.fetch_and(value, std::memory_order_relaxed); #endif } /** * Apply a mask, with bitwise `or`, and return the previous value, * atomically. * * @param m Mask. * * @return Previous value. */ T exchangeOr(const T& value) { #if LIBBIRCH_ATOMIC_OPENMP T old; #pragma omp atomic capture { old = this->value; this->value |= value; } return old; #else return this->value.fetch_or(value, std::memory_order_relaxed); #endif } /** * Apply a mask, with bitwise `and`, atomically. * * @param m Mask. */ void maskAnd(const T& value) { #if LIBBIRCH_ATOMIC_OPENMP #pragma omp atomic update this->value &= value; #else this->value.fetch_and(value, std::memory_order_relaxed); #endif } /** * Apply a mask, with bitwise `or`, atomically. * * @param m Mask. */ void maskOr(const T& value) { #if LIBBIRCH_ATOMIC_OPENMP #pragma omp atomic update this->value |= value; #else this->value.fetch_or(value, std::memory_order_relaxed); #endif } /** * Increment the value by one, atomically, but without capturing the * current value. */ void increment() { #if LIBBIRCH_ATOMIC_OPENMP #pragma omp atomic update ++value; #else value.fetch_add(1, std::memory_order_relaxed); #endif } /** * Decrement the value by one, atomically, but without capturing the * current value. */ void decrement() { #if LIBBIRCH_ATOMIC_OPENMP #pragma omp atomic update --value; #else value.fetch_sub(1, std::memory_order_relaxed); #endif } /** * Add to the value, atomically, but without capturing the current value. */ template<class U> void add(const U& value) { #if LIBBIRCH_ATOMIC_OPENMP #pragma omp atomic update this->value += value; #else this->value.fetch_add(value, std::memory_order_relaxed); #endif } /** * Subtract from the value, atomically, but without capturing the current * value. */ template<class U> void subtract(const U& value) { #if LIBBIRCH_ATOMIC_OPENMP #pragma omp atomic update this->value -= value; #else this->value.fetch_sub(value, std::memory_order_relaxed); #endif } template<class U> T operator+=(const U& value) { #if LIBBIRCH_ATOMIC_OPENMP T result; #pragma omp atomic capture { this->value += value; result = this->value; } return result; #else return this->value.fetch_add(value, std::memory_order_relaxed) + value; #endif } template<class U> T operator-=(const U& value) { #if LIBBIRCH_ATOMIC_OPENMP T result; #pragma omp atomic capture { this->value -= value; result = this->value; } return result; #else return this->value.fetch_sub(value, std::memory_order_relaxed) - value; #endif } T operator++() { #if LIBBIRCH_ATOMIC_OPENMP T result; #pragma omp atomic capture { ++this->value; result = this->value; } return result; #else return this->value.fetch_add(1, std::memory_order_relaxed) + 1; #endif } T operator++(int) { #if LIBBIRCH_ATOMIC_OPENMP T result; #pragma omp atomic capture { result = this->value; ++this->value; } return result; #else return this->value.fetch_add(1, std::memory_order_relaxed); #endif } T operator--() { #if LIBBIRCH_ATOMIC_OPENMP T result; #pragma omp atomic capture { --this->value; result = this->value; } return result; #else return this->value.fetch_sub(1, std::memory_order_relaxed) - 1; #endif } T operator--(int) { #if LIBBIRCH_ATOMIC_OPENMP T result; #pragma omp atomic capture { result = this->value; --this->value; } return result; #else return this->value.fetch_sub(1, std::memory_order_relaxed); #endif } private: /** * Value. */ #if LIBBIRCH_ATOMIC_OPENMP T value; #else std::atomic<T> value; #endif }; } <commit_msg>Switched back to use of std::atomic instead of OpenMP atomics on Mac.<commit_after>/** * @file */ #pragma once /** * @def LIBBIRCH_ATOMIC_OPENMP * * Set to 1 for libbirch::Atomic use OpenMP, or 0 to use std::atomic. * * The advantage of the OpenMP implementation is assured memory model * consistency and the organic disabling of atomics when OpenMP, and thus * multithreading, is disabled (this can improve performance significantly for * single threading). The disadvantage is that OpenMP atomics do not support * compare-and-swap/compare-and-exchange, only swap/exchange, which can * require some clunkier client code, especially for read-write locks. */ #ifdef __APPLE__ /* on Mac, OpenMP atomics appear to cause crashes when release mode is * enabled */ #define LIBBIRCH_ATOMIC_OPENMP 0 #else #define LIBBIRCH_ATOMIC_OPENMP 1 #endif #if !LIBBIRCH_ATOMIC_OPENMP #include <atomic> #endif namespace libbirch { /** * Atomic value. * * @tparam Value type. */ template<class T> class Atomic { public: /** * Default constructor. Initializes the value, not necessarily atomically. */ Atomic() = default; /** * Constructor. * * @param value Initial value. * * Initializes the value, atomically. */ explicit Atomic(const T& value) { store(value); } /** * Load the value, atomically. */ T load() const { #if LIBBIRCH_ATOMIC_OPENMP T value; #pragma omp atomic read value = this->value; return value; #else return this->value.load(std::memory_order_relaxed); #endif } /** * Store the value, atomically. */ void store(const T& value) { #if LIBBIRCH_ATOMIC_OPENMP #pragma omp atomic write this->value = value; #else this->value.store(value, std::memory_order_relaxed); #endif } /** * Exchange the value with another, atomically. * * @param value New value. * * @return Old value. */ T exchange(const T& value) { #if LIBBIRCH_ATOMIC_OPENMP T old; #pragma omp atomic capture { old = this->value; this->value = value; } return old; #else return this->value.exchange(value, std::memory_order_relaxed); #endif } /** * Apply a mask, with bitwise `and`, and return the previous value, * atomically. * * @param m Mask. * * @return Previous value. */ T exchangeAnd(const T& value) { #if LIBBIRCH_ATOMIC_OPENMP T old; #pragma omp atomic capture { old = this->value; this->value &= value; } return old; #else return this->value.fetch_and(value, std::memory_order_relaxed); #endif } /** * Apply a mask, with bitwise `or`, and return the previous value, * atomically. * * @param m Mask. * * @return Previous value. */ T exchangeOr(const T& value) { #if LIBBIRCH_ATOMIC_OPENMP T old; #pragma omp atomic capture { old = this->value; this->value |= value; } return old; #else return this->value.fetch_or(value, std::memory_order_relaxed); #endif } /** * Apply a mask, with bitwise `and`, atomically. * * @param m Mask. */ void maskAnd(const T& value) { #if LIBBIRCH_ATOMIC_OPENMP #pragma omp atomic update this->value &= value; #else this->value.fetch_and(value, std::memory_order_relaxed); #endif } /** * Apply a mask, with bitwise `or`, atomically. * * @param m Mask. */ void maskOr(const T& value) { #if LIBBIRCH_ATOMIC_OPENMP #pragma omp atomic update this->value |= value; #else this->value.fetch_or(value, std::memory_order_relaxed); #endif } /** * Increment the value by one, atomically, but without capturing the * current value. */ void increment() { #if LIBBIRCH_ATOMIC_OPENMP #pragma omp atomic update ++value; #else value.fetch_add(1, std::memory_order_relaxed); #endif } /** * Decrement the value by one, atomically, but without capturing the * current value. */ void decrement() { #if LIBBIRCH_ATOMIC_OPENMP #pragma omp atomic update --value; #else value.fetch_sub(1, std::memory_order_relaxed); #endif } /** * Add to the value, atomically, but without capturing the current value. */ template<class U> void add(const U& value) { #if LIBBIRCH_ATOMIC_OPENMP #pragma omp atomic update this->value += value; #else this->value.fetch_add(value, std::memory_order_relaxed); #endif } /** * Subtract from the value, atomically, but without capturing the current * value. */ template<class U> void subtract(const U& value) { #if LIBBIRCH_ATOMIC_OPENMP #pragma omp atomic update this->value -= value; #else this->value.fetch_sub(value, std::memory_order_relaxed); #endif } template<class U> T operator+=(const U& value) { #if LIBBIRCH_ATOMIC_OPENMP T result; #pragma omp atomic capture { this->value += value; result = this->value; } return result; #else return this->value.fetch_add(value, std::memory_order_relaxed) + value; #endif } template<class U> T operator-=(const U& value) { #if LIBBIRCH_ATOMIC_OPENMP T result; #pragma omp atomic capture { this->value -= value; result = this->value; } return result; #else return this->value.fetch_sub(value, std::memory_order_relaxed) - value; #endif } T operator++() { #if LIBBIRCH_ATOMIC_OPENMP T result; #pragma omp atomic capture { ++this->value; result = this->value; } return result; #else return this->value.fetch_add(1, std::memory_order_relaxed) + 1; #endif } T operator++(int) { #if LIBBIRCH_ATOMIC_OPENMP T result; #pragma omp atomic capture { result = this->value; ++this->value; } return result; #else return this->value.fetch_add(1, std::memory_order_relaxed); #endif } T operator--() { #if LIBBIRCH_ATOMIC_OPENMP T result; #pragma omp atomic capture { --this->value; result = this->value; } return result; #else return this->value.fetch_sub(1, std::memory_order_relaxed) - 1; #endif } T operator--(int) { #if LIBBIRCH_ATOMIC_OPENMP T result; #pragma omp atomic capture { result = this->value; --this->value; } return result; #else return this->value.fetch_sub(1, std::memory_order_relaxed); #endif } private: /** * Value. */ #if LIBBIRCH_ATOMIC_OPENMP T value; #else std::atomic<T> value; #endif }; } <|endoftext|>
<commit_before>/****************************************************************************** * ____ _ _____ * * / ___| / \ | ___| C++ * * | | / _ \ | |_ Actor * * | |___ / ___ \| _| Framework * * \____/_/ \_|_| * * * * Copyright (C) 2011 - 2014 * * Dominik Charousset <dominik.charousset (at) haw-hamburg.de> * * * * Distributed under the terms and conditions of the BSD 3-Clause License or * * (at your option) under the terms and conditions of the Boost Software * * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. * * * * If you did not receive a copy of the license files, see * * http://opensource.org/licenses/BSD-3-Clause and * * http://www.boost.org/LICENSE_1_0.txt. * ******************************************************************************/ #ifndef CAF_OPTIONAL_HPP #define CAF_OPTIONAL_HPP #include <new> #include <utility> #include "caf/none.hpp" #include "caf/unit.hpp" #include "caf/config.hpp" #include "caf/detail/safe_equal.hpp" #include "caf/detail/scope_guard.hpp" namespace caf { /// A C++17 compatible `optional` implementation. template <class T> class optional { public: /// Typdef for `T`. using type = T; /// Creates an instance without value. optional(const none_t& = none) : m_valid(false) { // nop } /// Creates an valid instance from `value`. template <class U, class E = typename std::enable_if< std::is_convertible<U, T>::value >::type> optional(U x) : m_valid(false) { cr(std::move(x)); } optional(const optional& other) : m_valid(false) { if (other.m_valid) { cr(other.m_value); } } optional(optional&& other) : m_valid(false) { if (other.m_valid) { cr(std::move(other.m_value)); } } ~optional() { destroy(); } optional& operator=(const optional& other) { if (m_valid) { if (other.m_valid) m_value = other.m_value; else destroy(); } else if (other.m_valid) { cr(other.m_value); } return *this; } optional& operator=(optional&& other) { if (m_valid) { if (other.m_valid) m_value = std::move(other.m_value); else destroy(); } else if (other.m_valid) { cr(std::move(other.m_value)); } return *this; } /// Checks whether this object contains a value. explicit operator bool() const { return m_valid; } /// Checks whether this object does not contain a value. bool operator!() const { return !m_valid; } /// Returns the value. T& operator*() { CAF_ASSERT(m_valid); return m_value; } /// Returns the value. const T& operator*() const { CAF_ASSERT(m_valid); return m_value; } /// Returns the value. const T* operator->() const { CAF_ASSERT(m_valid); return &m_value; } /// Returns the value. T* operator->() { CAF_ASSERT(m_valid); return &m_value; } /// Returns the value. T& value() { CAF_ASSERT(m_valid); return m_value; } /// Returns the value. const T& value() const { CAF_ASSERT(m_valid); return m_value; } /// Returns the value if `m_valid`, otherwise returns `default_value`. const T& value_or(const T& default_value) const { return m_valid ? value() : default_value; } private: void destroy() { if (m_valid) { m_value.~T(); m_valid = false; } } template <class V> void cr(V&& x) { CAF_ASSERT(!m_valid); m_valid = true; new (&m_value) T(std::forward<V>(x)); } bool m_valid; union { T m_value; }; }; /// Template specialization to allow `optional` to hold a reference /// rather than an actual value with minimal overhead. template <class T> class optional<T&> { public: using type = T; optional(const none_t& = none) : m_value(nullptr) { // nop } optional(T& x) : m_value(&x) { // nop } optional(T* x) : m_value(x) { // nop } optional(const optional& other) = default; optional& operator=(const optional& other) = default; explicit operator bool() const { return m_value != nullptr; } bool operator!() const { return !m_value; } T& operator*() { CAF_ASSERT(m_value); return *m_value; } const T& operator*() const { CAF_ASSERT(m_value); return *m_value; } T* operator->() { CAF_ASSERT(m_value); return m_value; } const T* operator->() const { CAF_ASSERT(m_value); return m_value; } T& value() { CAF_ASSERT(m_value); return *m_value; } const T& value() const { CAF_ASSERT(m_value); return *m_value; } const T& value_or(const T& default_value) const { if (m_value) return value(); return default_value; } private: T* m_value; }; template <> class optional<void> { public: using type = unit_t; optional(none_t = none) : m_value(false) { // nop } optional(unit_t) : m_value(true) { // nop } optional(const optional& other) = default; optional& operator=(const optional& other) = default; explicit operator bool() const { return m_value; } bool operator!() const { return !m_value; } private: bool m_value; }; template <class Inspector, class T> typename std::enable_if<Inspector::reads_state, typename Inspector::result_type>::type inspect(Inspector& f, optional<T>& x) { return x ? f(true, *x) : f(false); } template <class T> struct optional_inspect_helper { bool& enabled; T& storage; template <class Inspector> friend typename Inspector::result_type inspect(Inspector& f, optional_inspect_helper& x) { return x.enabled ? f(x.storage) : f(); } }; template <class Inspector, class T> typename std::enable_if<Inspector::writes_state, typename Inspector::result_type>::type inspect(Inspector& f, optional<T>& x) { bool flag; typename optional<T>::type tmp; optional_inspect_helper<T> helper{flag, tmp}; auto guard = detail::make_scope_guard([&] { if (flag) x = std::move(tmp); else x = none; }); return f(flag, helper); } /// @relates optional template <class T> auto to_string(const optional<T>& x) -> decltype(to_string(*x)) { return x ? "*" + to_string(*x) : "<null>"; } // -- [X.Y.8] comparison with optional ---------------------------------------- /// @relates optional template <class T> bool operator==(const optional<T>& lhs, const optional<T>& rhs) { return static_cast<bool>(lhs) == static_cast<bool>(rhs) && (!lhs || *lhs == *rhs); } /// @relates optional template <class T> bool operator!=(const optional<T>& lhs, const optional<T>& rhs) { return !(lhs == rhs); } /// @relates optional template <class T> bool operator<(const optional<T>& lhs, const optional<T>& rhs) { return static_cast<bool>(rhs) && (!lhs || *lhs < *rhs); } /// @relates optional template <class T> bool operator<=(const optional<T>& lhs, const optional<T>& rhs) { return !(rhs < lhs); } /// @relates optional template <class T> bool operator>=(const optional<T>& lhs, const optional<T>& rhs) { return !(lhs < rhs); } /// @relates optional template <class T> bool operator>(const optional<T>& lhs, const optional<T>& rhs) { return rhs < lhs; } // -- [X.Y.9] comparison with none_t (aka. nullopt_t) ------------------------- /// @relates optional template <class T> bool operator==(const optional<T>& lhs, none_t) { return !lhs; } /// @relates optional template <class T> bool operator==(none_t, const optional<T>& rhs) { return !rhs; } /// @relates optional template <class T> bool operator!=(const optional<T>& lhs, none_t) { return static_cast<bool>(lhs); } /// @relates optional template <class T> bool operator!=(none_t, const optional<T>& rhs) { return static_cast<bool>(rhs); } /// @relates optional template <class T> bool operator<(const optional<T>&, none_t) { return false; } /// @relates optional template <class T> bool operator<(none_t, const optional<T>& rhs) { return static_cast<bool>(rhs); } /// @relates optional template <class T> bool operator<=(const optional<T>& lhs, none_t) { return !lhs; } /// @relates optional template <class T> bool operator<=(none_t, const optional<T>&) { return true; } /// @relates optional template <class T> bool operator>(const optional<T>& lhs, none_t) { return static_cast<bool>(lhs); } /// @relates optional template <class T> bool operator>(none_t, const optional<T>&) { return false; } /// @relates optional template <class T> bool operator>=(const optional<T>&, none_t) { return true; } /// @relates optional template <class T> bool operator>=(none_t, const optional<T>&) { return true; } // -- [X.Y.10] comparison with value type ------------------------------------ /// @relates optional template <class T> bool operator==(const optional<T>& lhs, const T& rhs) { return lhs && *lhs == rhs; } /// @relates optional template <class T> bool operator==(const T& lhs, const optional<T>& rhs) { return rhs && lhs == *rhs; } /// @relates optional template <class T> bool operator!=(const optional<T>& lhs, const T& rhs) { return !lhs || !(*lhs == rhs); } /// @relates optional template <class T> bool operator!=(const T& lhs, const optional<T>& rhs) { return !rhs || !(lhs == *rhs); } /// @relates optional template <class T> bool operator<(const optional<T>& lhs, const T& rhs) { return !lhs || *lhs < rhs; } /// @relates optional template <class T> bool operator<(const T& lhs, const optional<T>& rhs) { return rhs && lhs < *rhs; } /// @relates optional template <class T> bool operator<=(const optional<T>& lhs, const T& rhs) { return !lhs || !(rhs < *lhs); } /// @relates optional template <class T> bool operator<=(const T& lhs, const optional<T>& rhs) { return rhs && !(rhs < lhs); } /// @relates optional template <class T> bool operator>(const optional<T>& lhs, const T& rhs) { return lhs && rhs < *lhs; } /// @relates optional template <class T> bool operator>(const T& lhs, const optional<T>& rhs) { return !rhs || *rhs < lhs; } /// @relates optional template <class T> bool operator>=(const optional<T>& lhs, const T& rhs) { return lhs && !(*lhs < rhs); } /// @relates optional template <class T> bool operator>=(const T& lhs, const optional<T>& rhs) { return !rhs || !(lhs < *rhs); } } // namespace caf #endif // CAF_OPTIONAL_HPP <commit_msg>Mark optional<T>'s move ctor/assignment noexcept<commit_after>/****************************************************************************** * ____ _ _____ * * / ___| / \ | ___| C++ * * | | / _ \ | |_ Actor * * | |___ / ___ \| _| Framework * * \____/_/ \_|_| * * * * Copyright (C) 2011 - 2014 * * Dominik Charousset <dominik.charousset (at) haw-hamburg.de> * * * * Distributed under the terms and conditions of the BSD 3-Clause License or * * (at your option) under the terms and conditions of the Boost Software * * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. * * * * If you did not receive a copy of the license files, see * * http://opensource.org/licenses/BSD-3-Clause and * * http://www.boost.org/LICENSE_1_0.txt. * ******************************************************************************/ #ifndef CAF_OPTIONAL_HPP #define CAF_OPTIONAL_HPP #include <new> #include <utility> #include "caf/none.hpp" #include "caf/unit.hpp" #include "caf/config.hpp" #include "caf/detail/safe_equal.hpp" #include "caf/detail/scope_guard.hpp" namespace caf { /// A C++17 compatible `optional` implementation. template <class T> class optional { public: /// Typdef for `T`. using type = T; /// Creates an instance without value. optional(const none_t& = none) : m_valid(false) { // nop } /// Creates an valid instance from `value`. template <class U, class E = typename std::enable_if< std::is_convertible<U, T>::value >::type> optional(U x) : m_valid(false) { cr(std::move(x)); } optional(const optional& other) : m_valid(false) { if (other.m_valid) { cr(other.m_value); } } optional(optional&& other) noexcept(std::is_nothrow_move_constructible<T>::value) : m_valid(false) { if (other.m_valid) { cr(std::move(other.m_value)); } } ~optional() { destroy(); } optional& operator=(const optional& other) { if (m_valid) { if (other.m_valid) m_value = other.m_value; else destroy(); } else if (other.m_valid) { cr(other.m_value); } return *this; } optional& operator=(optional&& other) noexcept(std::is_nothrow_destructible<T>::value && std::is_nothrow_move_assignable<T>::value) { if (m_valid) { if (other.m_valid) m_value = std::move(other.m_value); else destroy(); } else if (other.m_valid) { cr(std::move(other.m_value)); } return *this; } /// Checks whether this object contains a value. explicit operator bool() const { return m_valid; } /// Checks whether this object does not contain a value. bool operator!() const { return !m_valid; } /// Returns the value. T& operator*() { CAF_ASSERT(m_valid); return m_value; } /// Returns the value. const T& operator*() const { CAF_ASSERT(m_valid); return m_value; } /// Returns the value. const T* operator->() const { CAF_ASSERT(m_valid); return &m_value; } /// Returns the value. T* operator->() { CAF_ASSERT(m_valid); return &m_value; } /// Returns the value. T& value() { CAF_ASSERT(m_valid); return m_value; } /// Returns the value. const T& value() const { CAF_ASSERT(m_valid); return m_value; } /// Returns the value if `m_valid`, otherwise returns `default_value`. const T& value_or(const T& default_value) const { return m_valid ? value() : default_value; } private: void destroy() { if (m_valid) { m_value.~T(); m_valid = false; } } template <class V> void cr(V&& x) { CAF_ASSERT(!m_valid); m_valid = true; new (&m_value) T(std::forward<V>(x)); } bool m_valid; union { T m_value; }; }; /// Template specialization to allow `optional` to hold a reference /// rather than an actual value with minimal overhead. template <class T> class optional<T&> { public: using type = T; optional(const none_t& = none) : m_value(nullptr) { // nop } optional(T& x) : m_value(&x) { // nop } optional(T* x) : m_value(x) { // nop } optional(const optional& other) = default; optional& operator=(const optional& other) = default; explicit operator bool() const { return m_value != nullptr; } bool operator!() const { return !m_value; } T& operator*() { CAF_ASSERT(m_value); return *m_value; } const T& operator*() const { CAF_ASSERT(m_value); return *m_value; } T* operator->() { CAF_ASSERT(m_value); return m_value; } const T* operator->() const { CAF_ASSERT(m_value); return m_value; } T& value() { CAF_ASSERT(m_value); return *m_value; } const T& value() const { CAF_ASSERT(m_value); return *m_value; } const T& value_or(const T& default_value) const { if (m_value) return value(); return default_value; } private: T* m_value; }; template <> class optional<void> { public: using type = unit_t; optional(none_t = none) : m_value(false) { // nop } optional(unit_t) : m_value(true) { // nop } optional(const optional& other) = default; optional& operator=(const optional& other) = default; explicit operator bool() const { return m_value; } bool operator!() const { return !m_value; } private: bool m_value; }; template <class Inspector, class T> typename std::enable_if<Inspector::reads_state, typename Inspector::result_type>::type inspect(Inspector& f, optional<T>& x) { return x ? f(true, *x) : f(false); } template <class T> struct optional_inspect_helper { bool& enabled; T& storage; template <class Inspector> friend typename Inspector::result_type inspect(Inspector& f, optional_inspect_helper& x) { return x.enabled ? f(x.storage) : f(); } }; template <class Inspector, class T> typename std::enable_if<Inspector::writes_state, typename Inspector::result_type>::type inspect(Inspector& f, optional<T>& x) { bool flag; typename optional<T>::type tmp; optional_inspect_helper<T> helper{flag, tmp}; auto guard = detail::make_scope_guard([&] { if (flag) x = std::move(tmp); else x = none; }); return f(flag, helper); } /// @relates optional template <class T> auto to_string(const optional<T>& x) -> decltype(to_string(*x)) { return x ? "*" + to_string(*x) : "<null>"; } // -- [X.Y.8] comparison with optional ---------------------------------------- /// @relates optional template <class T> bool operator==(const optional<T>& lhs, const optional<T>& rhs) { return static_cast<bool>(lhs) == static_cast<bool>(rhs) && (!lhs || *lhs == *rhs); } /// @relates optional template <class T> bool operator!=(const optional<T>& lhs, const optional<T>& rhs) { return !(lhs == rhs); } /// @relates optional template <class T> bool operator<(const optional<T>& lhs, const optional<T>& rhs) { return static_cast<bool>(rhs) && (!lhs || *lhs < *rhs); } /// @relates optional template <class T> bool operator<=(const optional<T>& lhs, const optional<T>& rhs) { return !(rhs < lhs); } /// @relates optional template <class T> bool operator>=(const optional<T>& lhs, const optional<T>& rhs) { return !(lhs < rhs); } /// @relates optional template <class T> bool operator>(const optional<T>& lhs, const optional<T>& rhs) { return rhs < lhs; } // -- [X.Y.9] comparison with none_t (aka. nullopt_t) ------------------------- /// @relates optional template <class T> bool operator==(const optional<T>& lhs, none_t) { return !lhs; } /// @relates optional template <class T> bool operator==(none_t, const optional<T>& rhs) { return !rhs; } /// @relates optional template <class T> bool operator!=(const optional<T>& lhs, none_t) { return static_cast<bool>(lhs); } /// @relates optional template <class T> bool operator!=(none_t, const optional<T>& rhs) { return static_cast<bool>(rhs); } /// @relates optional template <class T> bool operator<(const optional<T>&, none_t) { return false; } /// @relates optional template <class T> bool operator<(none_t, const optional<T>& rhs) { return static_cast<bool>(rhs); } /// @relates optional template <class T> bool operator<=(const optional<T>& lhs, none_t) { return !lhs; } /// @relates optional template <class T> bool operator<=(none_t, const optional<T>&) { return true; } /// @relates optional template <class T> bool operator>(const optional<T>& lhs, none_t) { return static_cast<bool>(lhs); } /// @relates optional template <class T> bool operator>(none_t, const optional<T>&) { return false; } /// @relates optional template <class T> bool operator>=(const optional<T>&, none_t) { return true; } /// @relates optional template <class T> bool operator>=(none_t, const optional<T>&) { return true; } // -- [X.Y.10] comparison with value type ------------------------------------ /// @relates optional template <class T> bool operator==(const optional<T>& lhs, const T& rhs) { return lhs && *lhs == rhs; } /// @relates optional template <class T> bool operator==(const T& lhs, const optional<T>& rhs) { return rhs && lhs == *rhs; } /// @relates optional template <class T> bool operator!=(const optional<T>& lhs, const T& rhs) { return !lhs || !(*lhs == rhs); } /// @relates optional template <class T> bool operator!=(const T& lhs, const optional<T>& rhs) { return !rhs || !(lhs == *rhs); } /// @relates optional template <class T> bool operator<(const optional<T>& lhs, const T& rhs) { return !lhs || *lhs < rhs; } /// @relates optional template <class T> bool operator<(const T& lhs, const optional<T>& rhs) { return rhs && lhs < *rhs; } /// @relates optional template <class T> bool operator<=(const optional<T>& lhs, const T& rhs) { return !lhs || !(rhs < *lhs); } /// @relates optional template <class T> bool operator<=(const T& lhs, const optional<T>& rhs) { return rhs && !(rhs < lhs); } /// @relates optional template <class T> bool operator>(const optional<T>& lhs, const T& rhs) { return lhs && rhs < *lhs; } /// @relates optional template <class T> bool operator>(const T& lhs, const optional<T>& rhs) { return !rhs || *rhs < lhs; } /// @relates optional template <class T> bool operator>=(const optional<T>& lhs, const T& rhs) { return lhs && !(*lhs < rhs); } /// @relates optional template <class T> bool operator>=(const T& lhs, const optional<T>& rhs) { return !rhs || !(lhs < *rhs); } } // namespace caf #endif // CAF_OPTIONAL_HPP <|endoftext|>
<commit_before>/* * Copyright 2021 Google LLC * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "experimental/graphite/src/DrawWriter.h" #include "experimental/graphite/src/DrawBufferManager.h" #include "src/gpu/BufferWriter.h" namespace skgpu { DrawWriter::DrawWriter(DrawDispatcher* dispatcher, DrawBufferManager* bufferManager) : DrawWriter(dispatcher, bufferManager, PrimitiveType::kTriangles, 0, 0) {} DrawWriter::DrawWriter(DrawDispatcher* dispatcher, DrawBufferManager* bufferManager, PrimitiveType primitiveType, size_t vertexStride, size_t instanceStride) : fDispatcher(dispatcher) , fManager(bufferManager) , fPrimitiveType(primitiveType) , fVertexStride(vertexStride) , fInstanceStride(instanceStride) { SkASSERT(dispatcher && bufferManager); } void DrawWriter::setTemplateInternal(BindBufferInfo vertices, BindBufferInfo indices, unsigned int count, bool drawPendingVertices) { SkASSERT(!vertices || fVertexStride > 0); if (vertices != fFixedVertexBuffer || indices != fFixedIndexBuffer || count != fFixedVertexCount) { // Issue any accumulated data that referred to the old template. if (drawPendingVertices) { this->drawPendingVertices(); } fFixedBuffersDirty = true; fFixedVertexBuffer = vertices; fFixedIndexBuffer = indices; fFixedVertexCount = count; } } void DrawWriter::drawInternal(BindBufferInfo instances, unsigned int base, unsigned int instanceCount) { // Draw calls that are only 1 instance and have no extra instance data get routed to // the simpler draw APIs. // TODO: Is there any benefit to this? Does it help hint to drivers? Avoid more bugs? // Or should we always call drawInstanced and drawIndexedInstanced? const bool useNonInstancedDraw = !SkToBool(instances) && base == 0 && instanceCount == 1; SkASSERT(!useNonInstancedDraw || fInstanceStride == 0); // Issue new buffer binds only as necessary // TODO: Should this instead be the responsibility of the CB or DrawDispatcher to remember // what was last bound? if (fFixedBuffersDirty || instances != fLastInstanceBuffer) { fDispatcher->bindDrawBuffers(fFixedVertexBuffer, instances, fFixedIndexBuffer); fFixedBuffersDirty = false; fLastInstanceBuffer = instances; } if (useNonInstancedDraw) { if (fFixedIndexBuffer) { // Should only get here from a direct draw, in which case base should be 0 and any // offset needs to be embedded in the BindBufferInfo by caller. SkASSERT(base == 0); fDispatcher->drawIndexed(fPrimitiveType, 0, fFixedVertexCount, 0); } else { // 'base' offsets accumulated vertex data from another DrawWriter across a state change. fDispatcher->draw(fPrimitiveType, base, fFixedVertexCount); } } else { // 'base' offsets accumulated instance data (or is 0 for a direct instanced draw). It is // assumed that any base vertex and index have been folded into the BindBufferInfos already. if (fFixedIndexBuffer) { fDispatcher->drawIndexedInstanced(fPrimitiveType, 0, fFixedVertexCount, 0, base, instanceCount); } else { fDispatcher->drawInstanced(fPrimitiveType, 0, fFixedVertexCount, base, instanceCount); } } } void DrawWriter::drawPendingVertices() { if (fPendingCount > 0) { if (fPendingMode == VertexMode::kInstances) { // This uses instanced draws, so 'base' will be interpreted in instance units. this->drawInternal(fPendingAttrs, fPendingBaseVertex, fPendingCount); } else { // This triggers a non-instanced draw call so 'base' passed to drawInternal is // interpreted in vertex units. this->setTemplateInternal(fPendingAttrs, {}, fPendingCount, /*drawPending=*/false); this->drawInternal({}, fPendingBaseVertex, 1); } fPendingCount = 0; fPendingBaseVertex = 0; fPendingAttrs = {}; } } VertexWriter DrawWriter::appendData(VertexMode mode, size_t stride, unsigned int count) { if (fPendingMode != mode) { // Switched between accumulating vertices and instances, so issue draws for the old data. this->drawPendingVertices(); fPendingMode = mode; } auto [writer, nextChunk] = fManager->getVertexWriter(count * stride); // Check if next chunk's data is contiguous with what's previously been appended if (nextChunk.fBuffer == fPendingAttrs.fBuffer && fPendingAttrs.fOffset + (fPendingBaseVertex + fPendingCount) * stride == nextChunk.fOffset) { // It is, so the next chunk's vertices that will be written can be folded into the next draw fPendingCount += count; } else { // Alignment mismatch, or the old buffer filled up this->drawPendingVertices(); fPendingCount = count; fPendingBaseVertex = 0; fPendingAttrs = nextChunk; } return std::move(writer); } void DrawWriter::newDynamicState() { // Remember where we left off after we draw, since drawPendingVertices() resets all pending data BindBufferInfo base = fPendingAttrs; unsigned int baseVertex = fPendingBaseVertex + fPendingCount; // Draw anything that used the previous dynamic state this->drawPendingVertices(); fPendingAttrs = base; fPendingBaseVertex = baseVertex; } void DrawWriter::newPipelineState(PrimitiveType type, size_t vertexStride, size_t instanceStride) { // Draw anything that used the previous pipeline this->drawPendingVertices(); // For simplicity, if there's a new pipeline, just forget about any previous buffer bindings, // in which case the new writer only needs to use the dispatcher and buffer manager. this->setTemplateInternal({}, {}, 0, false); fLastInstanceBuffer = {}; fPrimitiveType = type; fVertexStride = vertexStride; fInstanceStride = instanceStride; } } // namespace skgpu <commit_msg>[graphite] Fix instance vs. non-instanced detection<commit_after>/* * Copyright 2021 Google LLC * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "experimental/graphite/src/DrawWriter.h" #include "experimental/graphite/src/DrawBufferManager.h" #include "src/gpu/BufferWriter.h" namespace skgpu { DrawWriter::DrawWriter(DrawDispatcher* dispatcher, DrawBufferManager* bufferManager) : DrawWriter(dispatcher, bufferManager, PrimitiveType::kTriangles, 0, 0) {} DrawWriter::DrawWriter(DrawDispatcher* dispatcher, DrawBufferManager* bufferManager, PrimitiveType primitiveType, size_t vertexStride, size_t instanceStride) : fDispatcher(dispatcher) , fManager(bufferManager) , fPrimitiveType(primitiveType) , fVertexStride(vertexStride) , fInstanceStride(instanceStride) { SkASSERT(dispatcher && bufferManager); } void DrawWriter::setTemplateInternal(BindBufferInfo vertices, BindBufferInfo indices, unsigned int count, bool drawPendingVertices) { SkASSERT(!vertices || fVertexStride > 0); if (vertices != fFixedVertexBuffer || indices != fFixedIndexBuffer || count != fFixedVertexCount) { // Issue any accumulated data that referred to the old template. if (drawPendingVertices) { this->drawPendingVertices(); } fFixedBuffersDirty = true; fFixedVertexBuffer = vertices; fFixedIndexBuffer = indices; fFixedVertexCount = count; } } void DrawWriter::drawInternal(BindBufferInfo instances, unsigned int base, unsigned int instanceCount) { // Draw calls that are only 1 instance and have no extra instance data get routed to // the simpler draw APIs. // TODO: Is there any benefit to this? Does it help hint to drivers? Avoid more bugs? // Or should we always call drawInstanced and drawIndexedInstanced? const bool useInstancedDraw = fInstanceStride > 0 || instanceCount > 1; SkASSERT(useInstancedDraw || (fInstanceStride == 0 && instanceCount == 1 && !SkToBool(instances))); // Issue new buffer binds only as necessary // TODO: Should this instead be the responsibility of the CB or DrawDispatcher to remember // what was last bound? if (fFixedBuffersDirty || instances != fLastInstanceBuffer) { fDispatcher->bindDrawBuffers(fFixedVertexBuffer, instances, fFixedIndexBuffer); fFixedBuffersDirty = false; fLastInstanceBuffer = instances; } if (useInstancedDraw) { // 'base' offsets accumulated instance data (or is 0 for a direct instanced draw). It is // assumed that any base vertex and index have been folded into the BindBufferInfos already. if (fFixedIndexBuffer) { fDispatcher->drawIndexedInstanced(fPrimitiveType, 0, fFixedVertexCount, 0, base, instanceCount); } else { fDispatcher->drawInstanced(fPrimitiveType, 0, fFixedVertexCount, base, instanceCount); } } else { if (fFixedIndexBuffer) { // Should only get here from a direct draw, in which case base should be 0 and any // offset needs to be embedded in the BindBufferInfo by caller. SkASSERT(base == 0); fDispatcher->drawIndexed(fPrimitiveType, 0, fFixedVertexCount, 0); } else { // 'base' offsets accumulated vertex data from another DrawWriter across a state change. fDispatcher->draw(fPrimitiveType, base, fFixedVertexCount); } } } void DrawWriter::drawPendingVertices() { if (fPendingCount > 0) { if (fPendingMode == VertexMode::kInstances) { // This uses instanced draws, so 'base' will be interpreted in instance units. this->drawInternal(fPendingAttrs, fPendingBaseVertex, fPendingCount); } else { // This triggers a non-instanced draw call so 'base' passed to drawInternal is // interpreted in vertex units. this->setTemplateInternal(fPendingAttrs, {}, fPendingCount, /*drawPending=*/false); this->drawInternal({}, fPendingBaseVertex, 1); } fPendingCount = 0; fPendingBaseVertex = 0; fPendingAttrs = {}; } } VertexWriter DrawWriter::appendData(VertexMode mode, size_t stride, unsigned int count) { if (fPendingMode != mode) { // Switched between accumulating vertices and instances, so issue draws for the old data. this->drawPendingVertices(); fPendingMode = mode; } auto [writer, nextChunk] = fManager->getVertexWriter(count * stride); // Check if next chunk's data is contiguous with what's previously been appended if (nextChunk.fBuffer == fPendingAttrs.fBuffer && fPendingAttrs.fOffset + (fPendingBaseVertex + fPendingCount) * stride == nextChunk.fOffset) { // It is, so the next chunk's vertices that will be written can be folded into the next draw fPendingCount += count; } else { // Alignment mismatch, or the old buffer filled up this->drawPendingVertices(); fPendingCount = count; fPendingBaseVertex = 0; fPendingAttrs = nextChunk; } return std::move(writer); } void DrawWriter::newDynamicState() { // Remember where we left off after we draw, since drawPendingVertices() resets all pending data BindBufferInfo base = fPendingAttrs; unsigned int baseVertex = fPendingBaseVertex + fPendingCount; // Draw anything that used the previous dynamic state this->drawPendingVertices(); fPendingAttrs = base; fPendingBaseVertex = baseVertex; } void DrawWriter::newPipelineState(PrimitiveType type, size_t vertexStride, size_t instanceStride) { // Draw anything that used the previous pipeline this->drawPendingVertices(); // For simplicity, if there's a new pipeline, just forget about any previous buffer bindings, // in which case the new writer only needs to use the dispatcher and buffer manager. this->setTemplateInternal({}, {}, 0, false); fLastInstanceBuffer = {}; fPrimitiveType = type; fVertexStride = vertexStride; fInstanceStride = instanceStride; } } // namespace skgpu <|endoftext|>
<commit_before>#ifndef VIENNAGRID_SEGMENTED_MESH_HPP #define VIENNAGRID_SEGMENTED_MESH_HPP #include "viennagrid/mesh/mesh.hpp" #include "viennagrid/mesh/segmentation.hpp" namespace viennagrid { template<typename MeshT, typename SegmentationT> struct segmented_mesh { typedef MeshT mesh_type; typedef SegmentationT segmentation_type; mesh_type mesh; segmentation_type segmentation; }; template<typename WrappedMeshConfig, typename WrappedSegmentationConfig> struct segmented_mesh< viennagrid::mesh<WrappedMeshConfig>, viennagrid::segmentation<WrappedSegmentationConfig> > { typedef segmented_mesh< viennagrid::mesh<WrappedMeshConfig>, viennagrid::segmentation<WrappedSegmentationConfig> > SelfType; typedef viennagrid::mesh<WrappedMeshConfig> mesh_type; typedef viennagrid::segmentation<WrappedSegmentationConfig> segmentation_type; segmented_mesh() : segmentation(mesh) {} segmented_mesh(SelfType const & other) : segmentation(mesh) { *this = other; } SelfType & operator=(SelfType const & other) { clear(); viennagrid::vertex_copy_map<mesh_type, mesh_type> vertex_map(mesh); typedef typename viennagrid::result_of::cell<mesh_type>::type CellType; typedef typename viennagrid::result_of::coord<mesh_type>::type NumericType; typedef typename viennagrid::result_of::const_cell_range<mesh_type>::type ConstCellRangeType; typedef typename viennagrid::result_of::iterator<ConstCellRangeType>::type ConstCellIteratorType; typedef typename viennagrid::result_of::segment_id_range<segmentation_type, CellType>::type SrcSegmentIDRangeType; typedef typename viennagrid::result_of::segment_id<segmentation_type>::type DstSegmentIDType; typedef typename viennagrid::result_of::cell_handle<mesh_type>::type CellHandleType; ConstCellRangeType cells(other.mesh); for (ConstCellIteratorType cit = cells.begin(); cit != cells.end(); ++cit) { CellHandleType cell_handle = vertex_map.copy_element(*cit ); viennagrid::add( segmentation, cell_handle, viennagrid::segment_ids( other.segmentation, *cit ).begin(), viennagrid::segment_ids( other.segmentation, *cit ).end() ); } // mesh = other.mesh; // copy_segmentation( other.mesh, other.segmentation, mesh, segmentation ); return *this; } void clear() { mesh.clear(); segmentation.clear(); } mesh_type mesh; segmentation_type segmentation; private: }; } #endif <commit_msg>fixed depndencies (header)<commit_after>#ifndef VIENNAGRID_SEGMENTED_MESH_HPP #define VIENNAGRID_SEGMENTED_MESH_HPP #include "viennagrid/mesh/mesh.hpp" #include "viennagrid/mesh/segmentation.hpp" #include "viennagrid/mesh/mesh_operations.hpp" namespace viennagrid { template<typename MeshT, typename SegmentationT> struct segmented_mesh { typedef MeshT mesh_type; typedef SegmentationT segmentation_type; mesh_type mesh; segmentation_type segmentation; }; template<typename WrappedMeshConfig, typename WrappedSegmentationConfig> struct segmented_mesh< viennagrid::mesh<WrappedMeshConfig>, viennagrid::segmentation<WrappedSegmentationConfig> > { typedef segmented_mesh< viennagrid::mesh<WrappedMeshConfig>, viennagrid::segmentation<WrappedSegmentationConfig> > SelfType; typedef viennagrid::mesh<WrappedMeshConfig> mesh_type; typedef viennagrid::segmentation<WrappedSegmentationConfig> segmentation_type; segmented_mesh() : segmentation(mesh) {} segmented_mesh(SelfType const & other) : segmentation(mesh) { *this = other; } SelfType & operator=(SelfType const & other) { clear(); viennagrid::vertex_copy_map<mesh_type, mesh_type> vertex_map(mesh); typedef typename viennagrid::result_of::cell<mesh_type>::type CellType; typedef typename viennagrid::result_of::coord<mesh_type>::type NumericType; typedef typename viennagrid::result_of::const_cell_range<mesh_type>::type ConstCellRangeType; typedef typename viennagrid::result_of::iterator<ConstCellRangeType>::type ConstCellIteratorType; typedef typename viennagrid::result_of::segment_id_range<segmentation_type, CellType>::type SrcSegmentIDRangeType; typedef typename viennagrid::result_of::segment_id<segmentation_type>::type DstSegmentIDType; typedef typename viennagrid::result_of::cell_handle<mesh_type>::type CellHandleType; ConstCellRangeType cells(other.mesh); for (ConstCellIteratorType cit = cells.begin(); cit != cells.end(); ++cit) { CellHandleType cell_handle = vertex_map.copy_element(*cit ); viennagrid::add( segmentation, cell_handle, viennagrid::segment_ids( other.segmentation, *cit ).begin(), viennagrid::segment_ids( other.segmentation, *cit ).end() ); } // mesh = other.mesh; // copy_segmentation( other.mesh, other.segmentation, mesh, segmentation ); return *this; } void clear() { mesh.clear(); segmentation.clear(); } mesh_type mesh; segmentation_type segmentation; private: }; } #endif <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////// // Name: test-managedm_Frame.cpp // Purpose: Implementation for wxExtension cpp unit testing // Author: Anton van Wezenbeek // Copyright: (c) 2015 Anton van Wezenbeek //////////////////////////////////////////////////////////////////////////////// #include <wx/wxprec.h> #ifndef WX_PRECOMP #include <wx/wx.h> #endif #include <wx/extension/managedframe.h> #include <wx/extension/defs.h> #include <wx/extension/stc.h> #include <wx/extension/vi.h> #include "test.h" // Also test the toolbar (wxExToolBar). void fixture::testManagedFrame() { CPPUNIT_ASSERT(m_Frame->AllowClose(100, NULL)); wxExSTC* stc = new wxExSTC(m_Frame, "hello world"); wxExVi* vi = &stc->GetVi(); CPPUNIT_ASSERT(!m_Frame->ExecExCommand(":n", NULL)); m_Frame->GetExCommand(vi, "/"); m_Frame->HideExBar(wxExManagedFrame::HIDE_BAR); m_Frame->HideExBar(wxExManagedFrame::HIDE_BAR_FOCUS_STC); m_Frame->HideExBar(wxExManagedFrame::HIDE_BAR_FORCE); m_Frame->HideExBar(wxExManagedFrame::HIDE_BAR_FORCE_FOCUS_STC); CPPUNIT_ASSERT(!m_Frame->GetManager().GetPane("VIBAR").IsShown()); m_Frame->SetRecentFile("testing"); m_Frame->ShowExMessage("hello from m_Frame"); m_Frame->SyncAll(); m_Frame->SyncCloseAll(0); CPPUNIT_ASSERT( m_Frame->GetToolBar() != NULL); CPPUNIT_ASSERT( m_Frame->TogglePane("FINDBAR")); CPPUNIT_ASSERT( m_Frame->GetManager().GetPane("FINDBAR").IsShown()); CPPUNIT_ASSERT( m_Frame->TogglePane("OPTIONSBAR")); CPPUNIT_ASSERT( m_Frame->GetManager().GetPane("OPTIONSBAR").IsShown()); CPPUNIT_ASSERT( m_Frame->TogglePane("TOOLBAR")); CPPUNIT_ASSERT(!m_Frame->GetManager().GetPane("TOOLBAR").IsShown()); CPPUNIT_ASSERT( m_Frame->TogglePane("VIBAR")); CPPUNIT_ASSERT( m_Frame->GetManager().GetPane("VIBAR").IsShown()); CPPUNIT_ASSERT(!m_Frame->TogglePane("XXXXBAR")); CPPUNIT_ASSERT(!m_Frame->GetManager().GetPane("XXXXBAR").IsOk()); for (auto id : std::vector<int> { wxID_PREFERENCES, ID_FIND_FIRST, ID_VIEW_FINDBAR, ID_VIEW_OPTIONSBAR, ID_VIEW_TOOLBAR}) { wxPostEvent(m_Frame, wxCommandEvent(wxEVT_MENU, id)); } } <commit_msg>fixed compile error<commit_after>//////////////////////////////////////////////////////////////////////////////// // Name: test-managedm_Frame.cpp // Purpose: Implementation for wxExtension cpp unit testing // Author: Anton van Wezenbeek // Copyright: (c) 2015 Anton van Wezenbeek //////////////////////////////////////////////////////////////////////////////// #include <wx/wxprec.h> #ifndef WX_PRECOMP #include <wx/wx.h> #endif #include <wx/extension/managedframe.h> #include <wx/extension/defs.h> #include <wx/extension/stc.h> #include <wx/extension/vi.h> #include "test.h" // Also test the toolbar (wxExToolBar). void fixture::testManagedFrame() { CPPUNIT_ASSERT(m_Frame->AllowClose(100, NULL)); wxExSTC* stc = new wxExSTC(m_Frame, "hello world"); wxExVi* vi = &stc->GetVi(); wxExSTC* stc2 = NULL; CPPUNIT_ASSERT(!m_Frame->ExecExCommand(":n", stc2)); CPPUNIT_ASSERT( stc2 == NULL); m_Frame->GetExCommand(vi, "/"); m_Frame->HideExBar(wxExManagedFrame::HIDE_BAR); m_Frame->HideExBar(wxExManagedFrame::HIDE_BAR_FOCUS_STC); m_Frame->HideExBar(wxExManagedFrame::HIDE_BAR_FORCE); m_Frame->HideExBar(wxExManagedFrame::HIDE_BAR_FORCE_FOCUS_STC); CPPUNIT_ASSERT(!m_Frame->GetManager().GetPane("VIBAR").IsShown()); m_Frame->SetRecentFile("testing"); m_Frame->ShowExMessage("hello from m_Frame"); m_Frame->SyncAll(); m_Frame->SyncCloseAll(0); CPPUNIT_ASSERT( m_Frame->GetToolBar() != NULL); CPPUNIT_ASSERT( m_Frame->TogglePane("FINDBAR")); CPPUNIT_ASSERT( m_Frame->GetManager().GetPane("FINDBAR").IsShown()); CPPUNIT_ASSERT( m_Frame->TogglePane("OPTIONSBAR")); CPPUNIT_ASSERT( m_Frame->GetManager().GetPane("OPTIONSBAR").IsShown()); CPPUNIT_ASSERT( m_Frame->TogglePane("TOOLBAR")); CPPUNIT_ASSERT(!m_Frame->GetManager().GetPane("TOOLBAR").IsShown()); CPPUNIT_ASSERT( m_Frame->TogglePane("VIBAR")); CPPUNIT_ASSERT( m_Frame->GetManager().GetPane("VIBAR").IsShown()); CPPUNIT_ASSERT(!m_Frame->TogglePane("XXXXBAR")); CPPUNIT_ASSERT(!m_Frame->GetManager().GetPane("XXXXBAR").IsOk()); for (auto id : std::vector<int> { wxID_PREFERENCES, ID_FIND_FIRST, ID_VIEW_FINDBAR, ID_VIEW_OPTIONSBAR, ID_VIEW_TOOLBAR}) { wxPostEvent(m_Frame, wxCommandEvent(wxEVT_MENU, id)); } } <|endoftext|>