text
stringlengths
54
60.6k
<commit_before>#include "Claw.hpp" #ifndef M_PI #define M_PI 3.14159265 #endif #include <Solenoid.h> #include <DriverStationLCD.h> Claw::Claw(unsigned int clawRotatePort, unsigned int clawWheelPort, unsigned int zeroSwitchPort, unsigned int haveBallPort) : m_settings( "RobotSettings.txt" ) { m_clawRotator = new GearBox<Talon>( 0 , 7 , 8 , clawRotatePort ); m_intakeWheel = new GearBox<Talon>( 0 , 0 , 0 , clawWheelPort ); // Sets degrees rotated per pulse of encoder m_clawRotator->setDistancePerPulse( (1.0/71.0f)*14.0 /44.0 ); m_clawRotator->setReversed(true); m_ballShooter.push_back( new Solenoid( 1 ) ); m_ballShooter.push_back( new Solenoid( 2 ) ); m_ballShooter.push_back( new Solenoid( 3 ) ); m_ballShooter.push_back( new Solenoid( 4 ) ); m_zeroSwitch = new DigitalInput(zeroSwitchPort); m_haveBallSwitch = new DigitalInput(haveBallPort); // Set up interrupt for encoder reset m_zeroSwitch->RequestInterrupts( Claw::ResetClawEncoder , this ); m_zeroSwitch->SetUpSourceEdge( true , true ); m_zeroSwitch->EnableInterrupts(); // Set up interrupt for catching ball m_haveBallSwitch->RequestInterrupts( Claw::CloseClaw , this ); m_haveBallSwitch->SetUpSourceEdge( false , true ); //m_haveBallSwitch->EnableInterrupts(); //magical values found using empirical testing don't change. setK(0.238f); m_l = 69.0f; m_collectorArm = new Solenoid(5); m_vacuum = new Solenoid (6); ReloadPID(); m_shooterStates = SHOOTER_IDLE; } Claw::~Claw(){ // Free solenoids for ( unsigned int i = 0 ; i < m_ballShooter.size() ; i++ ) { delete m_ballShooter[i]; } delete m_collectorArm; m_zeroSwitch->DisableInterrupts(); delete m_zeroSwitch; m_haveBallSwitch->DisableInterrupts(); delete m_haveBallSwitch; delete m_vacuum; m_ballShooter.clear(); } void Claw::SetAngle(float shooterAngle){ m_clawRotator->setSetpoint( shooterAngle ); m_setpoint = shooterAngle; } void Claw::ManualSetAngle(float value) { if((!m_zeroSwitch->Get() && value > 0) || m_zeroSwitch->Get()) { m_clawRotator->setManual(value); } } double Claw::GetTargetAngle() const { return m_clawRotator->getSetpoint(); } double Claw::GetAngle() { return m_clawRotator->getDistance(); } void Claw::SetWheelSetpoint( float speed ) { m_intakeWheel->setSetpoint( speed ); } void Claw::SetWheelManual( float speed ) { m_intakeWheel->setManual( speed ); } void Claw::ResetEncoders() { m_clawRotator->resetEncoder(); m_intakeWheel->resetEncoder(); } void Claw::ReloadPID() { m_settings.update(); float p = 0.f; float i = 0.f; float d = 0.f; // Set shooter rotator PID p = atof( m_settings.getValueFor( "PID_ARM_ROTATE_P" ).c_str() ); i = atof( m_settings.getValueFor( "PID_ARM_ROTATE_I" ).c_str() ); d = atof( m_settings.getValueFor( "PID_ARM_ROTATE_D" ).c_str() ); m_clawRotator->setPID( p , i , d ); } void Claw::Shoot() { if (m_shooterStates == SHOOTER_IDLE){ m_collectorArm->Set(true); m_shooterStates = SHOOTER_ARMISLIFTING; m_shootTimer.Start(); m_shootTimer.Reset(); } } void Claw::SetCollectorMode(bool collectorMode){ m_collectorArm->Set(collectorMode); } bool Claw::GetCollectorMode(){ return m_collectorArm->Get(); } void Claw::Update() { if (m_shooterStates == SHOOTER_ARMISLIFTING && m_shootTimer.HasPeriodPassed(0.5)){ for ( unsigned int i = 0 ; i < m_ballShooter.size() ; i++ ) { m_ballShooter[i]->Set( true ); } m_shootTimer.Reset(); m_shooterStates = SHOOTER_SHOOTING; } if (m_shooterStates == SHOOTER_SHOOTING && m_shootTimer.HasPeriodPassed(2.0)){ for ( unsigned int i = 0 ; i < m_ballShooter.size() ; i++ ) { m_ballShooter[i]->Set( false ); } m_vacuum->Set(true); m_shootTimer.Reset(); m_shooterStates = SHOOTER_VACUUMING; } if (m_shooterStates == SHOOTER_VACUUMING && m_shootTimer.HasPeriodPassed(1.5)){ m_vacuum->Set(false); m_collectorArm->Set (false); m_shootTimer.Reset(); m_shooterStates = SHOOTER_IDLE; } if (!m_zeroSwitch->Get()){ ResetEncoders(); } setF(calcF()); // Spins intake wheel to keep ball in while rotating claw at high speeds if ( fabs(m_clawRotator->getRate()) > 35.f ) { SetWheelManual( -1.f ); } /* Fixes arm, when at reset angle, not touching zeroSwitch due to gradual * encoder error. If limit switch isn't pressed but arm is supposedly at * zeroing point or farther: */ if ( m_zeroSwitch->Get() && GetTargetAngle() <= 1.f && m_clawRotator->onTarget() ) { m_clawRotator->setSetpoint( GetTargetAngle() - 5.f ); } DriverStationLCD::GetInstance()->PrintfLine(DriverStationLCD::kUser_Line1, "Angle: %f", m_clawRotator->getDistance()); DriverStationLCD::GetInstance()->PrintfLine(DriverStationLCD::kUser_Line2, "A Setpt: %f", GetTargetAngle()); DriverStationLCD::GetInstance()->PrintfLine(DriverStationLCD::kUser_Line3, "Limit On: %u", !m_zeroSwitch->Get()); DriverStationLCD::GetInstance()->PrintfLine(DriverStationLCD::kUser_Line4, "OnTarget: %u", static_cast<unsigned int>(m_clawRotator->onTarget())); DriverStationLCD::GetInstance()->PrintfLine(DriverStationLCD::kUser_Line5, "A Rate: %f", m_clawRotator->getRate()); DriverStationLCD::GetInstance()->UpdateLCD(); } void Claw::setF(float f) { m_clawRotator->setF(f); } void Claw::setK(float k) { m_k = k; } float Claw::calcF() { if(GetTargetAngle() == 0) { return 0.0f; } return m_k*cos((GetAngle()+m_l)*M_PI/180.0f)/GetTargetAngle(); } bool Claw::IsShooting() const { if (m_shooterStates != SHOOTER_IDLE){ return true; } else{ return false; } } void Claw::ResetClawEncoder( long unsigned int interruptAssertedMask, void* obj ) { Claw* claw = static_cast<Claw*>(obj); if ( claw->GetTargetAngle() <= 0.0 ) { claw->m_clawRotator->resetPID(); claw->m_clawRotator->resetEncoder(); claw->m_clawRotator->setSetpoint( 0.f ); } } void Claw::CloseClaw( long unsigned int interruptAssertedMask, void* obj ) { std::cout << "CloseClaw INTERRUPT\n"; Claw* claw = static_cast<Claw*>(obj); if ( !claw->IsShooting() ) { claw->SetCollectorMode( false ); } } <commit_msg>Enabled ball switch interrupts<commit_after>#include "Claw.hpp" #ifndef M_PI #define M_PI 3.14159265 #endif #include <Solenoid.h> #include <DriverStationLCD.h> Claw::Claw(unsigned int clawRotatePort, unsigned int clawWheelPort, unsigned int zeroSwitchPort, unsigned int haveBallPort) : m_settings( "RobotSettings.txt" ) { m_clawRotator = new GearBox<Talon>( 0 , 7 , 8 , clawRotatePort ); m_intakeWheel = new GearBox<Talon>( 0 , 0 , 0 , clawWheelPort ); // Sets degrees rotated per pulse of encoder m_clawRotator->setDistancePerPulse( (1.0/71.0f)*14.0 /44.0 ); m_clawRotator->setReversed(true); m_ballShooter.push_back( new Solenoid( 1 ) ); m_ballShooter.push_back( new Solenoid( 2 ) ); m_ballShooter.push_back( new Solenoid( 3 ) ); m_ballShooter.push_back( new Solenoid( 4 ) ); m_zeroSwitch = new DigitalInput(zeroSwitchPort); m_haveBallSwitch = new DigitalInput(haveBallPort); // Set up interrupt for encoder reset m_zeroSwitch->RequestInterrupts( Claw::ResetClawEncoder , this ); m_zeroSwitch->SetUpSourceEdge( true , true ); m_zeroSwitch->EnableInterrupts(); // Set up interrupt for catching ball m_haveBallSwitch->RequestInterrupts( Claw::CloseClaw , this ); m_haveBallSwitch->SetUpSourceEdge( false , true ); m_haveBallSwitch->EnableInterrupts(); //magical values found using empirical testing don't change. setK(0.238f); m_l = 69.0f; m_collectorArm = new Solenoid(5); m_vacuum = new Solenoid (6); ReloadPID(); m_shooterStates = SHOOTER_IDLE; } Claw::~Claw(){ // Free solenoids for ( unsigned int i = 0 ; i < m_ballShooter.size() ; i++ ) { delete m_ballShooter[i]; } delete m_collectorArm; m_zeroSwitch->DisableInterrupts(); delete m_zeroSwitch; m_haveBallSwitch->DisableInterrupts(); delete m_haveBallSwitch; delete m_vacuum; m_ballShooter.clear(); } void Claw::SetAngle(float shooterAngle){ m_clawRotator->setSetpoint( shooterAngle ); m_setpoint = shooterAngle; } void Claw::ManualSetAngle(float value) { if((!m_zeroSwitch->Get() && value > 0) || m_zeroSwitch->Get()) { m_clawRotator->setManual(value); } } double Claw::GetTargetAngle() const { return m_clawRotator->getSetpoint(); } double Claw::GetAngle() { return m_clawRotator->getDistance(); } void Claw::SetWheelSetpoint( float speed ) { m_intakeWheel->setSetpoint( speed ); } void Claw::SetWheelManual( float speed ) { m_intakeWheel->setManual( speed ); } void Claw::ResetEncoders() { m_clawRotator->resetEncoder(); m_intakeWheel->resetEncoder(); } void Claw::ReloadPID() { m_settings.update(); float p = 0.f; float i = 0.f; float d = 0.f; // Set shooter rotator PID p = atof( m_settings.getValueFor( "PID_ARM_ROTATE_P" ).c_str() ); i = atof( m_settings.getValueFor( "PID_ARM_ROTATE_I" ).c_str() ); d = atof( m_settings.getValueFor( "PID_ARM_ROTATE_D" ).c_str() ); m_clawRotator->setPID( p , i , d ); } void Claw::Shoot() { if (m_shooterStates == SHOOTER_IDLE){ m_collectorArm->Set(true); m_shooterStates = SHOOTER_ARMISLIFTING; m_shootTimer.Start(); m_shootTimer.Reset(); } } void Claw::SetCollectorMode(bool collectorMode){ m_collectorArm->Set(collectorMode); } bool Claw::GetCollectorMode(){ return m_collectorArm->Get(); } void Claw::Update() { if (m_shooterStates == SHOOTER_ARMISLIFTING && m_shootTimer.HasPeriodPassed(0.5)){ for ( unsigned int i = 0 ; i < m_ballShooter.size() ; i++ ) { m_ballShooter[i]->Set( true ); } m_shootTimer.Reset(); m_shooterStates = SHOOTER_SHOOTING; } if (m_shooterStates == SHOOTER_SHOOTING && m_shootTimer.HasPeriodPassed(2.0)){ for ( unsigned int i = 0 ; i < m_ballShooter.size() ; i++ ) { m_ballShooter[i]->Set( false ); } m_vacuum->Set(true); m_shootTimer.Reset(); m_shooterStates = SHOOTER_VACUUMING; } if (m_shooterStates == SHOOTER_VACUUMING && m_shootTimer.HasPeriodPassed(1.5)){ m_vacuum->Set(false); m_collectorArm->Set (false); m_shootTimer.Reset(); m_shooterStates = SHOOTER_IDLE; } setF(calcF()); // Spins intake wheel to keep ball in while rotating claw at high speeds if ( fabs(m_clawRotator->getRate()) > 35.f ) { SetWheelManual( -1.f ); } /* Fixes arm, when at reset angle, not touching zeroSwitch due to gradual * encoder error. If limit switch isn't pressed but arm is supposedly at * zeroing point or farther: */ if ( m_zeroSwitch->Get() && GetTargetAngle() <= 1.f && m_clawRotator->onTarget() ) { m_clawRotator->setSetpoint( GetTargetAngle() - 5.f ); } DriverStationLCD::GetInstance()->PrintfLine(DriverStationLCD::kUser_Line1, "Angle: %f", m_clawRotator->getDistance()); DriverStationLCD::GetInstance()->PrintfLine(DriverStationLCD::kUser_Line2, "A Setpt: %f", GetTargetAngle()); DriverStationLCD::GetInstance()->PrintfLine(DriverStationLCD::kUser_Line3, "Limit On: %u", !m_zeroSwitch->Get()); DriverStationLCD::GetInstance()->PrintfLine(DriverStationLCD::kUser_Line4, "OnTarget: %u", static_cast<unsigned int>(m_clawRotator->onTarget())); DriverStationLCD::GetInstance()->PrintfLine(DriverStationLCD::kUser_Line5, "A Rate: %f", m_clawRotator->getRate()); DriverStationLCD::GetInstance()->UpdateLCD(); } void Claw::setF(float f) { m_clawRotator->setF(f); } void Claw::setK(float k) { m_k = k; } float Claw::calcF() { if(GetTargetAngle() == 0) { return 0.0f; } return m_k*cos((GetAngle()+m_l)*M_PI/180.0f)/GetTargetAngle(); } bool Claw::IsShooting() const { if (m_shooterStates != SHOOTER_IDLE){ return true; } else{ return false; } } void Claw::ResetClawEncoder( long unsigned int interruptAssertedMask, void* obj ) { Claw* claw = static_cast<Claw*>(obj); if ( claw->GetTargetAngle() <= 0.0 ) { claw->m_clawRotator->resetPID(); claw->m_clawRotator->resetEncoder(); claw->m_clawRotator->setSetpoint( 0.f ); } } void Claw::CloseClaw( long unsigned int interruptAssertedMask, void* obj ) { std::cout << "CloseClaw INTERRUPT\n"; Claw* claw = static_cast<Claw*>(obj); if ( !claw->IsShooting() ) { claw->SetCollectorMode( false ); } } <|endoftext|>
<commit_before>// vim:filetype=cpp:textwidth=80:shiftwidth=2:softtabstop=2:expandtab // Copyright 2014 [email protected] #include <cassert> #include <algorithm> #include <iostream> #include <iomanip> #include <map> #include <random> #include <string> #include <sstream> #include <vector> #include <./formula.h> #include <./maybe.h> using namespace lela; struct Point { Point() {} Point(size_t x, size_t y) : x(x), y(y) {} bool operator<(const Point& p) const { return x < p.x || (x == p.x && y < p.y); } std::set<Point> Neighbors() const { std::set<Point> s; s.insert(Point(x-1, y-1)); s.insert(Point(x-1, y )); s.insert(Point(x-1, y+1)); s.insert(Point(x , y-1)); s.insert(Point(x , y+1)); s.insert(Point(x+1, y-1)); s.insert(Point(x+1, y )); s.insert(Point(x+1, y+1)); return s; } size_t x; size_t y; }; namespace util { template<class T> void Subsets(const typename std::set<T>::const_iterator first, const typename std::set<T>::const_iterator last, const size_t n, const std::set<T>& current, std::set<std::set<T>>& subsets) { if (current.size() == n) { subsets.insert(current); return; } if (first == last || current.size() + static_cast<ssize_t>(std::distance(first, last)) < n) { return; } Subsets(std::next(first), last, n, current, subsets); std::set<T> current1 = current; current1.insert(*first); Subsets(std::next(first), last, n, current1, subsets); } template<class T> std::set<std::set<T>> Subsets(const std::set<T>& s, size_t n) { std::set<std::set<T>> ss; Subsets(s.begin(), s.end(), n, {}, ss); return ss; } } // namespace util class Field { public: static constexpr int UNEXPLORED = -2; static constexpr int HIT_MINE = -1; Field(const size_t dimen, const size_t n_mines) : dimen_(dimen), distribution_(0, dimen_ - 1) { mines_.resize(dimen_ * dimen_, false); picks_.resize(dimen_ * dimen_, false); assert(mines_.size() == dimen_ * dimen_); assert(n_mines <= dimen_ * dimen_); for (n_mines_ = 0; n_mines_ < n_mines; ) { Point p; p.x = distribution_(generator_); p.y = distribution_(generator_); if (!mine(p)) { set_mine(p, true); ++n_mines_; } } assert(n_mines == n_mines_); } size_t dimension() const { return dimen_; } size_t n_mines() const { return n_mines_; } std::set<Point> NeighborsOf(Point p) const { return FilterNeighborsOf(p, [](const Point& p) { return true; }); } template<class UnaryPredicate> std::set<Point> FilterNeighborsOf(Point p, UnaryPredicate pred) const { std::set<Point> s = p.Neighbors(); for (auto it = s.begin(); it != s.end(); ) { if (!valid(*it) || !pred(*it)) { it = s.erase(it); } else { ++it; } } return s; } Point toPoint(size_t index) const { Point p(index / dimen_, index % dimen_); assert(dimen_ * p.x + p.y == index); return p; } bool valid(Point p) const { return p.x < dimen_ && p.y < dimen_; } void set_mine(Point p, bool is_mine) { assert(valid(p)); mines_[dimen_ * p.x + p.y] = is_mine; } bool mine(Point p) const { assert(valid(p)); return mines_[dimen_ * p.x + p.y]; } bool picked(Point p) const { assert(valid(p)); return picks_[dimen_ * p.x + p.y]; } int PickRandom() { Point p; p.x = distribution_(generator_); p.y = distribution_(generator_); return Pick(p); } int Pick(Point p) { assert(!picked(p)); picks_[dimen_ * p.x + p.y] = true; assert(picked(p)); return state(p); } int PickWithFrontier(Point p) { int s = Pick(p); if (s == 0) { for (const Point q : NeighborsOf(p)) { if (!picked(q)) { PickWithFrontier(q); } } } return s; } int state(Point p) const { if (!picked(p)) { return UNEXPLORED; } if (mine(p)) { return HIT_MINE; } const Field* self = this; return FilterNeighborsOf(p, [self](const Point& q) { return self->mine(q); }).size(); } bool all_explored() const { for (size_t x = 0; x < dimen_; ++x) { for (size_t y = 0; y < dimen_; ++y) { if (!picked(Point(x, y)) && !mine(Point(x, y))) { return false; } } } return true; } private: std::vector<bool> mines_; std::vector<bool> picks_; size_t dimen_; size_t n_mines_; std::default_random_engine generator_; std::uniform_int_distribution<size_t> distribution_; }; class Printer { public: void Print(std::ostream& os, const Field& f) { const int width = 3; os << std::setw(width) << ""; for (size_t x = 0; x < f.dimension(); ++x) { os << std::setw(width) << x; } os << std::endl; for (size_t y = 0; y < f.dimension(); ++y) { os << std::setw(width) << y; for (size_t x = 0; x < f.dimension(); ++x) { os << std::setw(width) << label(f, Point(x, y)); } os << std::endl; } } virtual std::string label(const Field& f, Point p) = 0; }; class OmniscientPrinter : public Printer { public: std::string label(const Field& f, Point p) { return f.mine(p) ? "X" : ""; } }; class SimplePrinter : public Printer { public: std::string label(const Field& f, Point p) override { switch (f.state(p)) { case Field::UNEXPLORED: return ""; case Field::HIT_MINE: return "X"; case 0: return "."; default: { std::stringstream ss; ss << f.state(p); return ss.str(); } } } }; class SetupPrinter : public Printer { public: SetupPrinter(const Field* f) : f_(f) { processed_.resize(f_->dimension() * f_->dimension(), false); } Literal MineLit(bool is, Point p) { return Literal({}, is, p.x * f_->dimension() + p.y, {}); } Clause MineClause(bool sign, const std::set<Point> ns) { SimpleClause c; for (const Point p : ns) { c.insert(MineLit(sign, p)); } return Clause(Ewff::TRUE, c); } std::string label(const Field& f, Point p) override { assert(&f == f_); UpdateKb(); switch (f.state(p)) { case Field::UNEXPLORED: { SimpleClause yes_mine({MineLit(true, p)}); SimpleClause no_mine({MineLit(false, p)}); for (Setup::split_level k = 0; k < 3; ++k) { if (s_.Entails(yes_mine, k)) { assert(f_->mine(p)); return "X"; } else if (s_.Entails(no_mine, k)) { assert(!f_->mine(p)); return "$"; } } return ""; } case Field::HIT_MINE: { return "X"; } default: { const int m = f.state(p); if (m == 0) { return "."; } std::stringstream ss; ss << m; return ss.str(); } } } const Setup& setup() const { return s_; } private: void UpdateKb() { for (size_t index = 0; index < f_->dimension() * f_->dimension(); ++index) { if (!processed_[index]) { processed_[index] = UpdateKb(f_->toPoint(index)); } } } bool UpdateKb(Point p) { const int m = f_->state(p); switch (m) { case Field::UNEXPLORED: { return false; } case Field::HIT_MINE: { s_.AddClause(Clause(Ewff::TRUE, {MineLit(true, p)})); return true; } default: { std::set<Point> ns = f_->NeighborsOf(p); const int n = ns.size(); //std::cerr << "n = " << n << ", m = " << m << std::endl; for (const std::set<Point>& ps : util::Subsets(ns, n - m + 1)) { s_.AddClause(MineClause(true, ps)); } for (const std::set<Point>& ps : util::Subsets(ns, m + 1)) { s_.AddClause(MineClause(false, ps)); } s_.AddClause(Clause(Ewff::TRUE, {MineLit(false, p)})); return true; } } } const Field* f_; Setup s_; std::vector<bool> processed_; }; int main(int argc, char *argv[]) { size_t dimen = 9; size_t n_mines = 10; if (argc >= 2) { dimen = atoi(argv[1]); n_mines = dimen + 1; } if (argc >= 3) { n_mines = atoi(argv[2]); } Field f(dimen, n_mines); SetupPrinter printer(&f); printer.Print(std::cout, f); std::cout << std::endl; std::cout << std::endl; if (argv[argc - 1] == std::string("play")) { int s; do { Point p; std::cout << "X and Y coordinates: "; std::cin >> p.x >> p.y; if (!f.valid(p) && f.picked(p)) { std::cout << "Invalid coordinates, repeat" << std::endl; continue; } s = f.PickWithFrontier(p); printer.Print(std::cout, f); std::cout << std::endl; std::cout << std::endl; } while (s != Field::HIT_MINE && !f.all_explored()); OmniscientPrinter().Print(std::cout, f); std::cout << std::endl; std::cout << std::endl; if (s == Field::HIT_MINE) { std::cout << "You loose :-(" << std::endl; } else { std::cout << "You win :-)" << std::endl; } } return 0; } #if 0 class MwBat : public Bat { public: virtual Maybe<Formula::ObjPtr> RegressOneStep(const Atom& a) = 0; void GuaranteeConsistency(split_level k) override { s_.GuaranteeConsistency(k); } void AddClause(const Clause& c) override { s_.AddClause(c); names_init_ = false; } bool InconsistentAt(belief_level p, split_level k) const override { assert(p == 0); return s_.Inconsistent(k); } bool EntailsClauseAt(belief_level p, const SimpleClause& c, split_level k) const override { assert(p == 0); return s_.Entails(c, k); } size_t n_levels() const override { return 1; } const StdName::SortedSet& names() const override { if (!names_init_) { names_ = s_.hplus().WithoutPlaceholders(); names_init_ = true; } return names_; } private: Setup s_; mutable StdName::SortedSet names_; mutable bool names_init_ = false; }; #endif <commit_msg>Minesweeper now has colorful output.<commit_after>// vim:filetype=cpp:textwidth=80:shiftwidth=2:softtabstop=2:expandtab // Copyright 2014 [email protected] #include <cassert> #include <algorithm> #include <iostream> #include <iomanip> #include <map> #include <random> #include <string> #include <sstream> #include <vector> #include <./formula.h> #include <./maybe.h> using namespace lela; struct Point { Point() {} Point(size_t x, size_t y) : x(x), y(y) {} bool operator<(const Point& p) const { return x < p.x || (x == p.x && y < p.y); } std::set<Point> Neighbors() const { std::set<Point> s; s.insert(Point(x-1, y-1)); s.insert(Point(x-1, y )); s.insert(Point(x-1, y+1)); s.insert(Point(x , y-1)); s.insert(Point(x , y+1)); s.insert(Point(x+1, y-1)); s.insert(Point(x+1, y )); s.insert(Point(x+1, y+1)); return s; } size_t x; size_t y; }; namespace util { template<class T> void Subsets(const typename std::set<T>::const_iterator first, const typename std::set<T>::const_iterator last, const size_t n, const std::set<T>& current, std::set<std::set<T>>& subsets) { if (current.size() == n) { subsets.insert(current); return; } if (first == last || current.size() + static_cast<ssize_t>(std::distance(first, last)) < n) { return; } Subsets(std::next(first), last, n, current, subsets); std::set<T> current1 = current; current1.insert(*first); Subsets(std::next(first), last, n, current1, subsets); } template<class T> std::set<std::set<T>> Subsets(const std::set<T>& s, size_t n) { std::set<std::set<T>> ss; Subsets(s.begin(), s.end(), n, {}, ss); return ss; } } // namespace util class Field { public: static constexpr int UNEXPLORED = -2; static constexpr int HIT_MINE = -1; Field(const size_t dimen, const size_t n_mines) : dimen_(dimen), distribution_(0, dimen_ - 1) { mines_.resize(dimen_ * dimen_, false); picks_.resize(dimen_ * dimen_, false); assert(mines_.size() == dimen_ * dimen_); assert(n_mines <= dimen_ * dimen_); for (n_mines_ = 0; n_mines_ < n_mines; ) { Point p; p.x = distribution_(generator_); p.y = distribution_(generator_); if (!mine(p)) { set_mine(p, true); ++n_mines_; } } assert(n_mines == n_mines_); } size_t dimension() const { return dimen_; } size_t n_mines() const { return n_mines_; } std::set<Point> NeighborsOf(Point p) const { return FilterNeighborsOf(p, [](const Point& p) { return true; }); } template<class UnaryPredicate> std::set<Point> FilterNeighborsOf(Point p, UnaryPredicate pred) const { std::set<Point> s = p.Neighbors(); for (auto it = s.begin(); it != s.end(); ) { if (!valid(*it) || !pred(*it)) { it = s.erase(it); } else { ++it; } } return s; } Point toPoint(size_t index) const { Point p(index / dimen_, index % dimen_); assert(dimen_ * p.x + p.y == index); return p; } bool valid(Point p) const { return p.x < dimen_ && p.y < dimen_; } void set_mine(Point p, bool is_mine) { assert(valid(p)); mines_[dimen_ * p.x + p.y] = is_mine; } bool mine(Point p) const { assert(valid(p)); return mines_[dimen_ * p.x + p.y]; } bool picked(Point p) const { assert(valid(p)); return picks_[dimen_ * p.x + p.y]; } int PickRandom() { Point p; p.x = distribution_(generator_); p.y = distribution_(generator_); return Pick(p); } int Pick(Point p) { assert(!picked(p)); picks_[dimen_ * p.x + p.y] = true; assert(picked(p)); return state(p); } int PickWithFrontier(Point p) { int s = Pick(p); if (s == 0) { for (const Point q : NeighborsOf(p)) { if (!picked(q)) { PickWithFrontier(q); } } } return s; } int state(Point p) const { if (!picked(p)) { return UNEXPLORED; } if (mine(p)) { return HIT_MINE; } const Field* self = this; return FilterNeighborsOf(p, [self](const Point& q) { return self->mine(q); }).size(); } bool all_explored() const { for (size_t x = 0; x < dimen_; ++x) { for (size_t y = 0; y < dimen_; ++y) { if (!picked(Point(x, y)) && !mine(Point(x, y))) { return false; } } } return true; } private: std::vector<bool> mines_; std::vector<bool> picks_; size_t dimen_; size_t n_mines_; std::default_random_engine generator_; std::uniform_int_distribution<size_t> distribution_; }; class Printer { public: static constexpr int RESET = 0; static constexpr int BRIGHT = 1; static constexpr int DIM = 2; static constexpr int BLACK = 30; static constexpr int RED = 31; static constexpr int GREEN = 32; void Print(std::ostream& os, const Field& f) { const int width = 3; os << std::setw(width) << ""; for (size_t x = 0; x < f.dimension(); ++x) { os << std::setw(width) << x; } os << std::endl; for (size_t y = 0; y < f.dimension(); ++y) { os << std::setw(width) << y; for (size_t x = 0; x < f.dimension(); ++x) { std::pair<int, std::string> l = label(f, Point(x, y)); os << "\033[" << l.first << "m" << std::setw(width) << l.second << "\033[0m"; } os << std::endl; } } virtual std::pair<int, std::string> label(const Field&, Point) = 0; }; class OmniscientPrinter : public Printer { public: std::pair<int, std::string> label(const Field& f, Point p) { return f.mine(p) ? std::make_pair(RED, "X") : std::make_pair(RESET, ""); } }; class SimplePrinter : public Printer { public: std::pair<int, std::string> label(const Field& f, Point p) override { switch (f.state(p)) { case Field::UNEXPLORED: return std::make_pair(RESET, ""); case Field::HIT_MINE: return std::make_pair(RED, "X"); case 0: return std::make_pair(DIM, "."); default: { std::stringstream ss; ss << f.state(p); return std::make_pair(RESET, ss.str()); } } } }; class SetupPrinter : public Printer { public: SetupPrinter(const Field* f) : f_(f) { processed_.resize(f_->dimension() * f_->dimension(), false); } Literal MineLit(bool is, Point p) { return Literal({}, is, p.x * f_->dimension() + p.y, {}); } Clause MineClause(bool sign, const std::set<Point> ns) { SimpleClause c; for (const Point p : ns) { c.insert(MineLit(sign, p)); } return Clause(Ewff::TRUE, c); } std::pair<int, std::string> label(const Field& f, Point p) override { assert(&f == f_); UpdateKb(); switch (f.state(p)) { case Field::UNEXPLORED: { SimpleClause yes_mine({MineLit(true, p)}); SimpleClause no_mine({MineLit(false, p)}); for (Setup::split_level k = 0; k < 2; ++k) { if (s_.Entails(yes_mine, k)) { assert(f_->mine(p)); return std::make_pair(RED, "X"); } else if (s_.Entails(no_mine, k)) { assert(!f_->mine(p)); return std::make_pair(GREEN, "$"); } } return std::make_pair(RESET, ""); } case Field::HIT_MINE: { return std::make_pair(RED, "X"); } default: { const int m = f.state(p); if (m == 0) { return std::make_pair(DIM, "."); } std::stringstream ss; ss << m; return std::make_pair(RESET, ss.str()); } } } const Setup& setup() const { return s_; } private: void UpdateKb() { for (size_t index = 0; index < f_->dimension() * f_->dimension(); ++index) { if (!processed_[index]) { processed_[index] = UpdateKb(f_->toPoint(index)); } } } bool UpdateKb(Point p) { const int m = f_->state(p); switch (m) { case Field::UNEXPLORED: { return false; } case Field::HIT_MINE: { s_.AddClause(Clause(Ewff::TRUE, {MineLit(true, p)})); return true; } default: { std::set<Point> ns = f_->NeighborsOf(p); const int n = ns.size(); //std::cerr << "n = " << n << ", m = " << m << std::endl; for (const std::set<Point>& ps : util::Subsets(ns, n - m + 1)) { s_.AddClause(MineClause(true, ps)); } for (const std::set<Point>& ps : util::Subsets(ns, m + 1)) { s_.AddClause(MineClause(false, ps)); } s_.AddClause(Clause(Ewff::TRUE, {MineLit(false, p)})); return true; } } } const Field* f_; Setup s_; std::vector<bool> processed_; }; int main(int argc, char *argv[]) { size_t dimen = 9; size_t n_mines = 10; if (argc >= 2) { dimen = atoi(argv[1]); n_mines = dimen + 1; } if (argc >= 3) { n_mines = atoi(argv[2]); } Field f(dimen, n_mines); SetupPrinter printer(&f); printer.Print(std::cout, f); std::cout << std::endl; std::cout << std::endl; if (argv[argc - 1] == std::string("play")) { int s; do { Point p; std::cout << "X and Y coordinates: "; std::cin >> p.x >> p.y; if (!f.valid(p) && f.picked(p)) { std::cout << "Invalid coordinates, repeat" << std::endl; continue; } s = f.PickWithFrontier(p); printer.Print(std::cout, f); std::cout << std::endl; std::cout << std::endl; } while (s != Field::HIT_MINE && !f.all_explored()); OmniscientPrinter().Print(std::cout, f); std::cout << std::endl; std::cout << std::endl; if (s == Field::HIT_MINE) { std::cout << "You loose :-(" << std::endl; } else { std::cout << "You win :-)" << std::endl; } } return 0; } #if 0 class MwBat : public Bat { public: virtual Maybe<Formula::ObjPtr> RegressOneStep(const Atom& a) = 0; void GuaranteeConsistency(split_level k) override { s_.GuaranteeConsistency(k); } void AddClause(const Clause& c) override { s_.AddClause(c); names_init_ = false; } bool InconsistentAt(belief_level p, split_level k) const override { assert(p == 0); return s_.Inconsistent(k); } bool EntailsClauseAt(belief_level p, const SimpleClause& c, split_level k) const override { assert(p == 0); return s_.Entails(c, k); } size_t n_levels() const override { return 1; } const StdName::SortedSet& names() const override { if (!names_init_) { names_ = s_.hplus().WithoutPlaceholders(); names_init_ = true; } return names_; } private: Setup s_; mutable StdName::SortedSet names_; mutable bool names_init_ = false; }; #endif <|endoftext|>
<commit_before>#include "BigFix/Error.h" #include "BigFix/DataRef.h" #include "BigFix/Number.h" #include <gtest/gtest.h> using namespace BigFix; TEST( NumberTest, Read4ByteIntger ) { uint8_t number[4] = { 0x01, 0x02, 0x03, 0x04 }; EXPECT_EQ( 67305985, ReadLittleEndian( DataRef( number, number + 4 ) ) ); } TEST( NumberTest, Read8ByteIntger ) { uint8_t number[8] = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 }; EXPECT_EQ( 578437695752307201, ReadLittleEndian( DataRef( number, number + 8 ) ) ); } TEST( NumberTest, Write4ByteInteger ) { uint8_t number[4]; WriteLittleEndian( 67305985, number, 4 ); EXPECT_EQ( 1, number[0] ); EXPECT_EQ( 2, number[1] ); EXPECT_EQ( 3, number[2] ); EXPECT_EQ( 4, number[3] ); } TEST( NumberTest, Write8ByteInteger ) { uint8_t number[8]; WriteLittleEndian( 578437695752307201, number, 8 ); EXPECT_EQ( 1, number[0] ); EXPECT_EQ( 2, number[1] ); EXPECT_EQ( 3, number[2] ); EXPECT_EQ( 4, number[3] ); EXPECT_EQ( 5, number[4] ); EXPECT_EQ( 6, number[5] ); EXPECT_EQ( 7, number[6] ); EXPECT_EQ( 8, number[7] ); } <commit_msg>Add tests for ReadAsciiNumber<commit_after>#include "BigFix/Error.h" #include "BigFix/DataRef.h" #include "BigFix/Number.h" #include <gtest/gtest.h> using namespace BigFix; TEST( NumberTest, Read4ByteIntger ) { uint8_t number[4] = { 0x01, 0x02, 0x03, 0x04 }; EXPECT_EQ( 67305985, ReadLittleEndian( DataRef( number, number + 4 ) ) ); } TEST( NumberTest, Read8ByteIntger ) { uint8_t number[8] = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 }; EXPECT_EQ( 578437695752307201, ReadLittleEndian( DataRef( number, number + 8 ) ) ); } TEST( NumberTest, Write4ByteInteger ) { uint8_t number[4]; WriteLittleEndian( 67305985, number, 4 ); EXPECT_EQ( 1, number[0] ); EXPECT_EQ( 2, number[1] ); EXPECT_EQ( 3, number[2] ); EXPECT_EQ( 4, number[3] ); } TEST( NumberTest, Write8ByteInteger ) { uint8_t number[8]; WriteLittleEndian( 578437695752307201, number, 8 ); EXPECT_EQ( 1, number[0] ); EXPECT_EQ( 2, number[1] ); EXPECT_EQ( 3, number[2] ); EXPECT_EQ( 4, number[3] ); EXPECT_EQ( 5, number[4] ); EXPECT_EQ( 6, number[5] ); EXPECT_EQ( 7, number[6] ); EXPECT_EQ( 8, number[7] ); } TEST( NumberTest, ReadAsciiNumber ) { EXPECT_EQ( 42, ReadAsciiNumber<uint8_t>( DataRef( "42" ) ) ); EXPECT_EQ( 1970, ReadAsciiNumber<int32_t>( DataRef( "1970" ) ) ); EXPECT_THROW( ReadAsciiNumber<uint8_t>( DataRef( "hello" ) ), Error ); } <|endoftext|>
<commit_before>/*========================================================================= * * Copyright RTK Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #ifndef rtkImportImageFilter_hxx #define rtkImportImageFilter_hxx #include "rtkImportImageFilter.h" #include "itkObjectFactory.h" namespace rtk { /** * */ template< typename TImage > ImportImageFilter< TImage > ::ImportImageFilter() { unsigned int idx; for ( idx = 0; idx < TImage::ImageDimension; ++idx ) { m_Spacing[idx] = 1.0; m_Origin[idx] = 0.0; } m_Direction.SetIdentity(); m_ImportPointer = ITK_NULLPTR; m_FilterManageMemory = false; m_Size = 0; } /** * */ template< typename TImage > ImportImageFilter< TImage > ::~ImportImageFilter() { if ( m_ImportPointer && m_FilterManageMemory ) { delete[] m_ImportPointer; } } /** * */ template< typename TImage > void ImportImageFilter< TImage > ::PrintSelf(std::ostream & os, itk::Indent indent) const { int i; this->Superclass::PrintSelf(os, indent); if ( m_ImportPointer ) { os << indent << "Imported pointer: (" << m_ImportPointer << ")" << std::endl; } else { os << indent << "Imported pointer: (None)" << std::endl; } os << indent << "Import buffer size: " << m_Size << std::endl; os << indent << "Import buffer size: " << m_Size << std::endl; os << indent << "Filter manages memory: " << ( m_FilterManageMemory ? "true" : "false" ) << std::endl; os << indent << "Spacing: ["; for ( i = 0; i < static_cast< int >( TImage::ImageDimension ) - 1; i++ ) { os << m_Spacing[i] << ", "; } os << m_Spacing[i] << "]" << std::endl; os << indent << "Origin: ["; for ( i = 0; i < static_cast< int >( TImage::ImageDimension ) - 1; i++ ) { os << m_Origin[i] << ", "; } os << m_Origin[i] << "]" << std::endl; os << indent << "Direction: " << std::endl << this->GetDirection() << std::endl; } /** * */ template< typename TImage > void ImportImageFilter< TImage > ::SetImportPointer(PixelType *ptr, SizeValueType num, bool LetFilterManageMemory) { if ( ptr != m_ImportPointer ) { if ( m_ImportPointer && m_FilterManageMemory ) { delete[] m_ImportPointer; } m_ImportPointer = ptr; this->Modified(); } m_FilterManageMemory = LetFilterManageMemory; m_Size = num; } /** * */ template< typename TImage > typename TImage::PixelType * ImportImageFilter< TImage > ::GetImportPointer() { return m_ImportPointer; } /** * */ template< typename TImage > void ImportImageFilter< TImage > ::EnlargeOutputRequestedRegion(itk::DataObject *output) { // call the superclass' implementation of this method Superclass::EnlargeOutputRequestedRegion(output); // get pointer to the output OutputImagePointer outputPtr = this->GetOutput(); // set the requested region to the largest possible region (in this case // the amount of data that we have) outputPtr->SetRequestedRegion( outputPtr->GetLargestPossibleRegion() ); } /** * */ template< typename TImage > void ImportImageFilter< TImage > ::GenerateOutputInformation() { // call the superclass' implementation of this method Superclass::GenerateOutputInformation(); // get pointer to the output OutputImagePointer outputPtr = this->GetOutput(); // we need to compute the output spacing, the output origin, the // output image size, and the output image start index outputPtr->SetSpacing(m_Spacing); outputPtr->SetOrigin(m_Origin); outputPtr->SetDirection(m_Direction); outputPtr->SetLargestPossibleRegion(m_Region); } /** * */ template< typename TImage > void ImportImageFilter< TImage > ::GenerateData() { // Normally, GenerateData() allocates memory. However, the application // provides the memory for this filter via the SetImportPointer() method. // Therefore, this filter does not call outputPtr->Allocate(). // get pointer to the output OutputImagePointer outputPtr = this->GetOutput(); // the output buffer size is set to the size specified by the user via the // SetRegion() method. outputPtr->SetBufferedRegion( outputPtr->GetLargestPossibleRegion() ); // pass the pointer down to the container during each Update() since // a call to Initialize() causes the container to forget the // pointer. Note that we tell the container NOT to manage the // memory itself. This filter will properly manage the memory (as // opposed to the container) if the user wants it to. outputPtr->GetPixelContainer()->SetImportPointer(m_ImportPointer, m_Size, false); } //---------------------------------------------------------------------------- template< typename TImage > void ImportImageFilter< TImage > ::SetDirection(const DirectionType & direction) { bool modified = false; for ( unsigned int r = 0; r < TImage::ImageDimension; r++ ) { for ( unsigned int c = 0; c < TImage::ImageDimension; c++ ) { if ( m_Direction[r][c] != direction[r][c] ) { m_Direction[r][c] = direction[r][c]; modified = true; } } } if ( modified ) { this->Modified(); } } } // end namespace itk #endif <commit_msg>Fixed bug in rtkImportImageFilter: the CudaImageDataManager did not correctly allocate the GPU buffer<commit_after>/*========================================================================= * * Copyright RTK Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #ifndef rtkImportImageFilter_hxx #define rtkImportImageFilter_hxx #include "rtkImportImageFilter.h" #include "itkObjectFactory.h" namespace rtk { /** * */ template< typename TImage > ImportImageFilter< TImage > ::ImportImageFilter() { unsigned int idx; for ( idx = 0; idx < TImage::ImageDimension; ++idx ) { m_Spacing[idx] = 1.0; m_Origin[idx] = 0.0; } m_Direction.SetIdentity(); m_ImportPointer = ITK_NULLPTR; m_FilterManageMemory = false; m_Size = 0; } /** * */ template< typename TImage > ImportImageFilter< TImage > ::~ImportImageFilter() { if ( m_ImportPointer && m_FilterManageMemory ) { delete[] m_ImportPointer; } } /** * */ template< typename TImage > void ImportImageFilter< TImage > ::PrintSelf(std::ostream & os, itk::Indent indent) const { int i; this->Superclass::PrintSelf(os, indent); if ( m_ImportPointer ) { os << indent << "Imported pointer: (" << m_ImportPointer << ")" << std::endl; } else { os << indent << "Imported pointer: (None)" << std::endl; } os << indent << "Import buffer size: " << m_Size << std::endl; os << indent << "Import buffer size: " << m_Size << std::endl; os << indent << "Filter manages memory: " << ( m_FilterManageMemory ? "true" : "false" ) << std::endl; os << indent << "Spacing: ["; for ( i = 0; i < static_cast< int >( TImage::ImageDimension ) - 1; i++ ) { os << m_Spacing[i] << ", "; } os << m_Spacing[i] << "]" << std::endl; os << indent << "Origin: ["; for ( i = 0; i < static_cast< int >( TImage::ImageDimension ) - 1; i++ ) { os << m_Origin[i] << ", "; } os << m_Origin[i] << "]" << std::endl; os << indent << "Direction: " << std::endl << this->GetDirection() << std::endl; } /** * */ template< typename TImage > void ImportImageFilter< TImage > ::SetImportPointer(PixelType *ptr, SizeValueType num, bool LetFilterManageMemory) { if ( ptr != m_ImportPointer ) { if ( m_ImportPointer && m_FilterManageMemory ) { delete[] m_ImportPointer; } m_ImportPointer = ptr; this->Modified(); } m_FilterManageMemory = LetFilterManageMemory; m_Size = num; } /** * */ template< typename TImage > typename TImage::PixelType * ImportImageFilter< TImage > ::GetImportPointer() { return m_ImportPointer; } /** * */ template< typename TImage > void ImportImageFilter< TImage > ::EnlargeOutputRequestedRegion(itk::DataObject *output) { // call the superclass' implementation of this method Superclass::EnlargeOutputRequestedRegion(output); // get pointer to the output OutputImagePointer outputPtr = this->GetOutput(); // set the requested region to the largest possible region (in this case // the amount of data that we have) outputPtr->SetRequestedRegion( outputPtr->GetLargestPossibleRegion() ); } /** * */ template< typename TImage > void ImportImageFilter< TImage > ::GenerateOutputInformation() { // call the superclass' implementation of this method Superclass::GenerateOutputInformation(); // get pointer to the output OutputImagePointer outputPtr = this->GetOutput(); // we need to compute the output spacing, the output origin, the // output image size, and the output image start index outputPtr->SetSpacing(m_Spacing); outputPtr->SetOrigin(m_Origin); outputPtr->SetDirection(m_Direction); outputPtr->SetLargestPossibleRegion(m_Region); } /** * */ template< typename TImage > void ImportImageFilter< TImage > ::GenerateData() { // Normally, GenerateData() allocates memory. However, the application // provides the memory for this filter via the SetImportPointer() method. // Therefore, this filter does not call outputPtr->Allocate(). // get pointer to the output OutputImagePointer outputPtr = this->GetOutput(); // the output buffer size is set to the size specified by the user via the // SetRegion() method. outputPtr->SetBufferedRegion( outputPtr->GetLargestPossibleRegion() ); // pass the pointer down to the container during each Update() since // a call to Initialize() causes the container to forget the // pointer. Note that we tell the container NOT to manage the // memory itself. This filter will properly manage the memory (as // opposed to the container) if the user wants it to. outputPtr->GetPixelContainer()->SetImportPointer(m_ImportPointer, m_Size, false); #ifdef RTK_USE_CUDA typedef itk::CudaImage<typename TImage::PixelType, TImage::ImageDimension> TCudaImage; if (TCudaImage* cudaOutputPtr = dynamic_cast<TCudaImage*>(outputPtr.GetPointer())) { cudaOutputPtr->GetDataManager()->SetBufferSize(m_Size * sizeof(typename OutputImageType::PixelType)); cudaOutputPtr->GetDataManager()->SetImagePointer(outputPtr); cudaOutputPtr->GetDataManager()->SetCPUBufferPointer(m_ImportPointer); cudaOutputPtr->GetDataManager()->SetGPUDirtyFlag(true); cudaOutputPtr->GetDataManager()->SetCPUDirtyFlag(false); cudaOutputPtr->GetDataManager()->SetTimeStamp(outputPtr->GetPixelContainer()->GetTimeStamp()); } #endif } //---------------------------------------------------------------------------- template< typename TImage > void ImportImageFilter< TImage > ::SetDirection(const DirectionType & direction) { bool modified = false; for ( unsigned int r = 0; r < TImage::ImageDimension; r++ ) { for ( unsigned int c = 0; c < TImage::ImageDimension; c++ ) { if ( m_Direction[r][c] != direction[r][c] ) { m_Direction[r][c] = direction[r][c]; modified = true; } } } if ( modified ) { this->Modified(); } } } // end namespace itk #endif <|endoftext|>
<commit_before>#include <arpa/inet.h> #include <sys/socket.h> #include <sys/types.h> #include <cstring> #include <iostream> extern "C" struct sockaddr_in; using namespace std; int main(int argc, char *argv[]) { int sockfd; struct sockaddr_in my_addr; sockfd = socket(AF_INET, SOCK_STREAM, 0); if (errno) { cerr << "Failed to call socket()" << endl; exit(1); } my_addr.sin_family = AF_INET; // AF_INET means we want to send stuff via IP my_addr.sin_port = 0; // Choose the port automatically my_addr.sin_addr.s_addr = INADDR_ANY; // Choose this machine's IP address memset(&(my_addr.sin_zero), 0x00, 8); bind(sockfd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr)); return 0; } <commit_msg>timefetch: finish adding socket code, work on getting the server's response<commit_after>#include <arpa/inet.h> #include <sys/socket.h> #include <sys/types.h> #include <netdb.h> #include <unistd.h> #include <cstring> #include <iostream> extern "C" { struct sockaddr_in; struct addrinfo; typedef struct { unsigned li : 2; // Only two bits. Leap indicator. unsigned vn : 3; // Only three bits. Version number of the protocol. unsigned mode : 3; // Only three bits. Mode. Client will pick mode 3 for client. uint8_t stratum; // Eight bits. Stratum level of the local clock. uint8_t poll; // Eight bits. Maximum interval between successive messages. uint8_t precision; // Eight bits. Precision of the local clock. uint32_t rootDelay; // 32 bits. Total round trip delay time. uint32_t rootDispersion; // 32 bits. Max error aloud from primary clock source. uint32_t refId; // 32 bits. Reference clock identifier. uint32_t refTm_s; // 32 bits. Reference time-stamp seconds. uint32_t refTm_f; // 32 bits. Reference time-stamp fraction of a second. uint32_t origTm_s; // 32 bits. Originate time-stamp seconds. uint32_t origTm_f; // 32 bits. Originate time-stamp fraction of a second. uint32_t rxTm_s; // 32 bits. Received time-stamp seconds. uint32_t rxTm_f; // 32 bits. Received time-stamp fraction of a second. uint32_t txTm_s; // 32 bits and the most important field the client cares about. Transmit time-stamp seconds. uint32_t txTm_f; // 32 bits. Transmit time-stamp fraction of a second. } ntp_packet; // Total: 384 bits or 48 bytes. }; using namespace std; int main(int argc, char *argv[]) { int sockfd, retval = 0; ssize_t sendto_retval, recv_retval; string address; ntp_packet packet = {}; packet.vn = 3; packet.mode = 3; struct addrinfo *result, *resp_node; struct addrinfo hints = {}; hints.ai_family = AF_UNSPEC; // IPv4 and v6 are allowed hints.ai_socktype = SOCK_DGRAM; if (argc != 2) { address = "pool.ntp.org"; cerr << "Wrong number of arguments, using the default server " << '"' << address << '"' << endl; } else { address = argv[1]; } if (int e = getaddrinfo(address.c_str(), "123", &hints, &result)) { cerr << "getaddrinfo() failed with" << e << endl; exit(1); } for (resp_node = result; resp_node != nullptr; resp_node = resp_node->ai_next) { sockfd = socket(resp_node->ai_family, resp_node->ai_socktype, resp_node->ai_protocol); if (sockfd == -1) continue; if (connect(sockfd, resp_node->ai_addr, resp_node->ai_addrlen) == 0) break; close(sockfd); } if (resp_node == nullptr) { cerr << "Could not connect() to any of the results" << endl; exit(1); } struct sockaddr_in *addr = (sockaddr_in *)resp_node->ai_addr; cout << "Connected to " << inet_ntoa(addr->sin_addr) << endl; sendto_retval = send(sockfd, &packet, sizeof(packet), 0); if (sendto_retval != -1) { cout << "Successfuly sent " << sendto_retval << " bytes" << endl; } else { cerr << "Failed to send the NTP packet" << endl; cerr << "Errno: " << gai_strerror(errno) << endl; retval = 1; goto fini; } recv_retval = recv(sockfd, &packet, sizeof(packet), 0); if (recv_retval != -1) { cout << "Successfuly received " << recv_retval << " bytes" << endl; } else { cerr << "Failed to receive the NTP packet" << endl; retval = 1; goto fini; } fini: close(sockfd); return retval; } <|endoftext|>
<commit_before>#include <libport/unit-test.hh> #include <libport/sysexits.hh> using libport::test_suite; #ifndef LIBPORT_NO_SSL # define LIBPORT_NO_SSL #endif #include <libport/asio.hh> #include <libport/utime.hh> #include <libport/unistd.h> bool abort_ctor = false; const char* msg = "coincoin\n"; // On OSX: // listen connect status // "127.0.0.1" "127.0.0.1" PASS // "localhost" "localhost" PASS // "" "localhost" PASS // "" "127.0.0.1" FAIL static const char* listen_host = ""; static const char* connect_host = "localhost"; template<class T> void hold_for(T, libport::utime_t duration) { usleep(duration); BOOST_TEST_MESSAGE("Done holding your T"); } void delayed_response(boost::shared_ptr<libport::UDPLink> l, libport::utime_t duration) { usleep(duration); l->reply("hop hop\n"); } // Hack until we can kill listenig sockets. static bool enable_delay = false; void reply_delay(const void*, int, boost::shared_ptr<libport::UDPLink> l, libport::utime_t duration) { libport::startThread(boost::bind(&delayed_response, l, duration)); } void echo(const void* d, int s, boost::shared_ptr<libport::UDPLink> l) { if (enable_delay) reply_delay(d, s, l, 500000); else l->reply(d, s); } class TestSocket: public libport::Socket { public: TestSocket() : nRead(0), echo(false), dump(false) { BOOST_CHECK(!abort_ctor); nInstance++; } TestSocket(bool echo, bool dump) : nRead(0), echo(echo), dump(dump) { BOOST_CHECK(!abort_ctor); nInstance++; } virtual ~TestSocket() { nInstance--; //BOOST_TEST_MESSAGE(this <<" dying, in " << K_get() << " lasterror=" << lastError.message()); //assert(false); } int onRead(const void* data, size_t size) { nRead++; //BOOST_TEST_MESSAGE(this << " read " << size); if (echo) write(data, size); if (dump) received += std::string((const char*)data, size); return size; } void onError(boost::system::error_code erc) { lastError = erc; destroy(); } // Number of times read callback was called int nRead; // Echo back what is received. bool echo; // Store what is received in received. bool dump; std::string received; boost::system::error_code lastError; static TestSocket* factory() { return lastInstance = new TestSocket(); } static TestSocket* factoryEx(bool echo, bool dump) { return lastInstance = new TestSocket(echo, dump); } static int nInstance; // Last factory-created instance. static TestSocket* lastInstance; }; int TestSocket::nInstance = 0; TestSocket* TestSocket::lastInstance = 0; // Delay in microseconds used to sleep when something asynchronous // is happening. static const int delay = 200000; static const int AVAIL_PORT = 7890; static const std::string S_AVAIL_PORT = "7890"; void test_one(bool proto) { TestSocket* client = new TestSocket(false, true); boost::system::error_code err = client->connect(connect_host, S_AVAIL_PORT, proto); BOOST_REQUIRE_MESSAGE(!err, err.message()); BOOST_CHECK_NO_THROW(client->send(msg)); usleep(delay); BOOST_CHECK_EQUAL(TestSocket::nInstance, proto ? 1 : 2); BOOST_CHECK_EQUAL(client->received, msg); if (!proto) BOOST_CHECK_EQUAL(TestSocket::lastInstance->received, msg); BOOST_CHECK_EQUAL(client->getRemotePort(), AVAIL_PORT); if (!proto) BOOST_CHECK_EQUAL(TestSocket::lastInstance->getLocalPort(), AVAIL_PORT); if (!proto) BOOST_CHECK_EQUAL(TestSocket::lastInstance->getRemotePort(), client->getLocalPort()); // Close client-end. Should send error both ways and destroy all sockets. client->close(); usleep(delay); BOOST_CHECK_EQUAL(TestSocket::nInstance, 0); } #define RESOLVE() \ do { \ libport::resolve<boost::asio::ip::tcp>(connect_host, \ S_AVAIL_PORT, err); \ BOOST_TEST_MESSAGE("Resolve: " + err.message()); \ } while (0) static void test() { // Basic TCP BOOST_TEST_MESSAGE("##Safe destruction"); boost::system::error_code err; TestSocket* s = new TestSocket(false, false); s->connect(connect_host, S_AVAIL_PORT, false); s->destroy(); usleep(delay); RESOLVE(); libport::Socket* h = new libport::Socket(); err = h->listen(boost::bind(&TestSocket::factoryEx, true, true), listen_host, S_AVAIL_PORT, false); BOOST_CHECK_MESSAGE(!err, err.message()); BOOST_CHECK_EQUAL(h->getLocalPort(), AVAIL_PORT); BOOST_TEST_MESSAGE("##One client"); RESOLVE(); RESOLVE(); RESOLVE(); RESOLVE(); std::cerr << "BEFORE TEST_ONE" << std::endl; test_one(false); BOOST_CHECK_EQUAL(h->getLocalPort(), AVAIL_PORT); std::cerr << "AFTER TEST_ONE" << std::endl; RESOLVE(); test_one(false); BOOST_CHECK_EQUAL(h->getLocalPort(), AVAIL_PORT); RESOLVE(); test_one(false); BOOST_TEST_MESSAGE("Socket on stack"); { TestSocket s(false, true); err = s.connect(connect_host, S_AVAIL_PORT, false); BOOST_CHECK_MESSAGE(!err, err.message()); s.send(msg); usleep(delay); } usleep(delay*2); BOOST_CHECK_EQUAL(TestSocket::nInstance, 0); test_one(false); BOOST_TEST_MESSAGE("##many clients"); std::vector<TestSocket*> clients; for (int i=0; i<10; i++) { TestSocket* client = new TestSocket(false, true); err = client->connect(connect_host, S_AVAIL_PORT, false); BOOST_CHECK_MESSAGE(!err, err.message()); client->send(msg); clients.push_back(client); } usleep(delay*3); BOOST_CHECK_EQUAL(TestSocket::nInstance, 20); foreach(TestSocket* s, clients) { BOOST_CHECK_EQUAL(s->received, msg); s->close(); } usleep(delay*3); BOOST_CHECK_EQUAL(TestSocket::nInstance, 0); BOOST_TEST_MESSAGE("##Failing connections"); { TestSocket* client = new TestSocket(); err = client->connect("auunsinsr.nosuch.hostaufisgiu.com.", "20000", false); BOOST_CHECK_MESSAGE(err, err.message()); err = client->connect(connect_host, "nosuchport", false); BOOST_CHECK_MESSAGE(err, err.message()); // Try to reuse that wasted socket. err = client->connect(connect_host, S_AVAIL_PORT, false); BOOST_CHECK_MESSAGE(!err, err.message()); // Destroy without closing. client->destroy(); usleep(delay); BOOST_CHECK_EQUAL(TestSocket::nInstance, 0); } // Timeout BOOST_TEST_MESSAGE("##Timeout connect"); { TestSocket* client = new TestSocket(); libport::utime_t start = libport::utime(); err = client->connect("1.1.1.1", "10000", false, 1000000); BOOST_CHECK_MESSAGE(err, err.message()); libport::utime_t timeout = libport::utime() - start; // Give it a good margin. BOOST_CHECK_LT(timeout, 1400000); client->destroy(); } BOOST_TEST_MESSAGE("##Destruction locking"); { TestSocket* client = new TestSocket(); err = client->connect(connect_host, S_AVAIL_PORT, false); BOOST_CHECK_MESSAGE(!err, err.message()); usleep(delay); libport::startThread( boost::bind(&hold_for<libport::Destructible::DestructionLock>, client->getDestructionLock(), 1000000)); client->destroy(); usleep(500000); // There can be 1 or 2 sockets at this point. Client must be still // alive because of the lock, but server might have died. BOOST_CHECK_MESSAGE(TestSocket::nInstance, TestSocket::nInstance); usleep(500000+delay); BOOST_CHECK_EQUAL(TestSocket::nInstance, 0); } BOOST_TEST_MESSAGE("Destroy listener"); { h->close(); usleep(delay); TestSocket* client = new TestSocket(); abort_ctor = true; err = client->connect(connect_host, S_AVAIL_PORT, false); BOOST_CHECK_MESSAGE(err, err.message()); client->destroy(); h->destroy(); usleep(delay); abort_ctor = false; } BOOST_TEST_MESSAGE("##UDP"); { libport::Socket::Handle hu = libport::Socket::listenUDP(listen_host, S_AVAIL_PORT, &echo, err); (void)hu; BOOST_CHECK_MESSAGE(!err, err.message()); test_one(true); usleep(delay); test_one(true); TestSocket* client = new TestSocket(); err = client->connect("auunsinsr.nosuch.hostaufisgiu.com.", "20000", true); BOOST_CHECK_MESSAGE(err, err.message()); err = client->connect(connect_host, "nosuchport", true); BOOST_CHECK_MESSAGE(err, err.message()); // Try to reuse that wasted socket. err = client->connect(connect_host, S_AVAIL_PORT, true); BOOST_CHECK_MESSAGE(!err, err.message()); // Destroy without closing. client->destroy(); usleep(delay); BOOST_CHECK_EQUAL(TestSocket::nInstance, 0); // Check one-write-one-packet semantic client = new TestSocket(false, true); err = client->connect(connect_host, S_AVAIL_PORT, true); BOOST_CHECK_MESSAGE(!err, err.message()); client->send("coin"); client->send("pan"); usleep(delay*2); BOOST_CHECK_EQUAL(client->received, "coinpan"); BOOST_CHECK_EQUAL(client->nRead, 2); enable_delay = true; client = new TestSocket(false, true); err = client->connect(connect_host, S_AVAIL_PORT, true); BOOST_CHECK_MESSAGE(!err, err.message()); client->send("coin"); usleep(500000+delay); BOOST_CHECK_EQUAL(client->received, "hop hop\n"); } } test_suite* init_test_suite() { // This test cannot run properly with current versions of WineHQ, // because they only provide a stub for acceptex. const char* running_wine = getenv("RUNNING_WINE"); const char* running_qemu = getenv("RUNNING_QEMU"); if ((running_wine && *running_wine) || (running_qemu && *running_qemu)) std::cerr << "running under Wine, skipping this test" << std::endl << libport::exit(EX_SKIP); test_suite* suite = BOOST_TEST_SUITE("libport::asio test suite"); suite->add(BOOST_TEST_CASE(test)); return suite; } <commit_msg>Liport.Asio: Fix test.<commit_after>#include <libport/unit-test.hh> #include <libport/sysexits.hh> using libport::test_suite; #ifndef LIBPORT_NO_SSL # define LIBPORT_NO_SSL #endif #include <libport/asio.hh> #include <libport/utime.hh> #include <libport/unistd.h> bool abort_ctor = false; const char* msg = "coincoin\n"; // On OSX: // listen connect status // "127.0.0.1" "127.0.0.1" PASS IPv4 // "localhost" "localhost" PASS IPv6 // "" "localhost" PASS IPv6 // "" "127.0.0.1" FAIL // "" "" PASS IPv6 static const char* listen_host = "127.0.0.1"; static const char* connect_host = "127.0.0.1"; template<class T> void hold_for(T, libport::utime_t duration) { usleep(duration); BOOST_TEST_MESSAGE("Done holding your T"); } void delayed_response(boost::shared_ptr<libport::UDPLink> l, libport::utime_t duration) { usleep(duration); l->reply("hop hop\n"); } // Hack until we can kill listenig sockets. static bool enable_delay = false; void reply_delay(const void*, int, boost::shared_ptr<libport::UDPLink> l, libport::utime_t duration) { libport::startThread(boost::bind(&delayed_response, l, duration)); } void echo(const void* d, int s, boost::shared_ptr<libport::UDPLink> l) { if (enable_delay) reply_delay(d, s, l, 500000); else l->reply(d, s); } class TestSocket: public libport::Socket { public: TestSocket() : nRead(0), echo(false), dump(false) { BOOST_CHECK(!abort_ctor); nInstance++; } TestSocket(bool echo, bool dump) : nRead(0), echo(echo), dump(dump) { BOOST_CHECK(!abort_ctor); nInstance++; } virtual ~TestSocket() { nInstance--; //BOOST_TEST_MESSAGE(this <<" dying, in " << K_get() << " lasterror=" << lastError.message()); //assert(false); } int onRead(const void* data, size_t size) { nRead++; //BOOST_TEST_MESSAGE(this << " read " << size); if (echo) write(data, size); if (dump) received += std::string((const char*)data, size); return size; } void onError(boost::system::error_code erc) { lastError = erc; destroy(); } // Number of times read callback was called int nRead; // Echo back what is received. bool echo; // Store what is received in received. bool dump; std::string received; boost::system::error_code lastError; static TestSocket* factory() { return lastInstance = new TestSocket(); } static TestSocket* factoryEx(bool echo, bool dump) { return lastInstance = new TestSocket(echo, dump); } static int nInstance; // Last factory-created instance. static TestSocket* lastInstance; }; int TestSocket::nInstance = 0; TestSocket* TestSocket::lastInstance = 0; // Delay in microseconds used to sleep when something asynchronous // is happening. static const int delay = 200000; static const int AVAIL_PORT = 7890; static const std::string S_AVAIL_PORT = "7890"; void test_one(bool proto) { TestSocket* client = new TestSocket(false, true); boost::system::error_code err = client->connect(connect_host, S_AVAIL_PORT, proto); BOOST_REQUIRE_MESSAGE(!err, err.message()); BOOST_CHECK_NO_THROW(client->send(msg)); usleep(delay); BOOST_CHECK_EQUAL(TestSocket::nInstance, proto ? 1 : 2); BOOST_CHECK_EQUAL(client->received, msg); if (!proto) BOOST_CHECK_EQUAL(TestSocket::lastInstance->received, msg); BOOST_CHECK_EQUAL(client->getRemotePort(), AVAIL_PORT); if (!proto) BOOST_CHECK_EQUAL(TestSocket::lastInstance->getLocalPort(), AVAIL_PORT); if (!proto) BOOST_CHECK_EQUAL(TestSocket::lastInstance->getRemotePort(), client->getLocalPort()); // Close client-end. Should send error both ways and destroy all sockets. client->close(); usleep(delay); BOOST_CHECK_EQUAL(TestSocket::nInstance, 0); } #define RESOLVE() \ do { \ libport::resolve<boost::asio::ip::tcp>(connect_host, \ S_AVAIL_PORT, err); \ BOOST_TEST_MESSAGE("Resolve: " + err.message()); \ } while (0) static void test() { // Basic TCP BOOST_TEST_MESSAGE("##Safe destruction"); boost::system::error_code err; TestSocket* s = new TestSocket(false, false); s->connect(connect_host, S_AVAIL_PORT, false); s->destroy(); usleep(delay); RESOLVE(); libport::Socket* h = new libport::Socket(); err = h->listen(boost::bind(&TestSocket::factoryEx, true, true), listen_host, S_AVAIL_PORT, false); BOOST_CHECK_MESSAGE(!err, err.message()); BOOST_CHECK_EQUAL(h->getLocalPort(), AVAIL_PORT); BOOST_TEST_MESSAGE("##One client"); RESOLVE(); RESOLVE(); RESOLVE(); RESOLVE(); test_one(false); BOOST_CHECK_EQUAL(h->getLocalPort(), AVAIL_PORT); RESOLVE(); test_one(false); BOOST_CHECK_EQUAL(h->getLocalPort(), AVAIL_PORT); RESOLVE(); test_one(false); BOOST_TEST_MESSAGE("Socket on stack"); { TestSocket s(false, true); err = s.connect(connect_host, S_AVAIL_PORT, false); BOOST_CHECK_MESSAGE(!err, err.message()); s.send(msg); usleep(delay); } usleep(delay*2); BOOST_CHECK_EQUAL(TestSocket::nInstance, 0); test_one(false); BOOST_TEST_MESSAGE("##many clients"); std::vector<TestSocket*> clients; for (int i=0; i<10; i++) { TestSocket* client = new TestSocket(false, true); err = client->connect(connect_host, S_AVAIL_PORT, false); BOOST_CHECK_MESSAGE(!err, err.message()); client->send(msg); clients.push_back(client); } usleep(delay*3); BOOST_CHECK_EQUAL(TestSocket::nInstance, 20); foreach(TestSocket* s, clients) { BOOST_CHECK_EQUAL(s->received, msg); s->close(); } usleep(delay*3); BOOST_CHECK_EQUAL(TestSocket::nInstance, 0); BOOST_TEST_MESSAGE("##Failing connections"); { TestSocket* client = new TestSocket(); err = client->connect("auunsinsr.nosuch.hostaufisgiu.com.", "20000", false); BOOST_CHECK_MESSAGE(err, err.message()); err = client->connect(connect_host, "nosuchport", false); BOOST_CHECK_MESSAGE(err, err.message()); // Try to reuse that wasted socket. err = client->connect(connect_host, S_AVAIL_PORT, false); BOOST_CHECK_MESSAGE(!err, err.message()); // Destroy without closing. client->destroy(); usleep(delay); BOOST_CHECK_EQUAL(TestSocket::nInstance, 0); } // Timeout BOOST_TEST_MESSAGE("##Timeout connect"); { TestSocket* client = new TestSocket(); libport::utime_t start = libport::utime(); err = client->connect("1.1.1.1", "10000", false, 1000000); BOOST_CHECK_MESSAGE(err, err.message()); libport::utime_t timeout = libport::utime() - start; // Give it a good margin. BOOST_CHECK_LT(timeout, 1400000); client->destroy(); } BOOST_TEST_MESSAGE("##Destruction locking"); { TestSocket* client = new TestSocket(); err = client->connect(connect_host, S_AVAIL_PORT, false); BOOST_CHECK_MESSAGE(!err, err.message()); usleep(delay); libport::startThread( boost::bind(&hold_for<libport::Destructible::DestructionLock>, client->getDestructionLock(), 1000000)); client->destroy(); usleep(500000); // There can be 1 or 2 sockets at this point. Client must be still // alive because of the lock, but server might have died. BOOST_CHECK_MESSAGE(TestSocket::nInstance, TestSocket::nInstance); usleep(500000+delay); BOOST_CHECK_EQUAL(TestSocket::nInstance, 0); } BOOST_TEST_MESSAGE("Destroy listener"); { h->close(); usleep(delay); TestSocket* client = new TestSocket(); abort_ctor = true; err = client->connect(connect_host, S_AVAIL_PORT, false); BOOST_CHECK_MESSAGE(err, err.message()); client->destroy(); h->destroy(); usleep(delay); abort_ctor = false; } BOOST_TEST_MESSAGE("##UDP"); { libport::Socket::Handle hu = libport::Socket::listenUDP(listen_host, S_AVAIL_PORT, &echo, err); (void)hu; BOOST_CHECK_MESSAGE(!err, err.message()); test_one(true); usleep(delay); test_one(true); TestSocket* client = new TestSocket(); err = client->connect("auunsinsr.nosuch.hostaufisgiu.com.", "20000", true); BOOST_CHECK_MESSAGE(err, err.message()); err = client->connect(connect_host, "nosuchport", true); BOOST_CHECK_MESSAGE(err, err.message()); // Try to reuse that wasted socket. err = client->connect(connect_host, S_AVAIL_PORT, true); BOOST_CHECK_MESSAGE(!err, err.message()); // Destroy without closing. client->destroy(); usleep(delay); BOOST_CHECK_EQUAL(TestSocket::nInstance, 0); // Check one-write-one-packet semantic client = new TestSocket(false, true); err = client->connect(connect_host, S_AVAIL_PORT, true); BOOST_CHECK_MESSAGE(!err, err.message()); client->send("coin"); client->send("pan"); usleep(delay*2); BOOST_CHECK_EQUAL(client->received, "coinpan"); BOOST_CHECK_EQUAL(client->nRead, 2); enable_delay = true; client = new TestSocket(false, true); err = client->connect(connect_host, S_AVAIL_PORT, true); BOOST_CHECK_MESSAGE(!err, err.message()); client->send("coin"); usleep(500000+delay); BOOST_CHECK_EQUAL(client->received, "hop hop\n"); } } test_suite* init_test_suite() { // This test cannot run properly with current versions of WineHQ, // because they only provide a stub for acceptex. const char* running_wine = getenv("RUNNING_WINE"); const char* running_qemu = getenv("RUNNING_QEMU"); if ((running_wine && *running_wine) || (running_qemu && *running_qemu)) std::cerr << "running under Wine, skipping this test" << std::endl << libport::exit(EX_SKIP); test_suite* suite = BOOST_TEST_SUITE("libport::asio test suite"); suite->add(BOOST_TEST_CASE(test)); return suite; } <|endoftext|>
<commit_before>// RUN: %check_clang_tidy %s hicpp-signed-bitwise %t -- -- -std=c++11 -target x86_64-unknown-unknown // These could cause false positives and should not be considered. struct StreamClass { }; StreamClass &operator<<(StreamClass &os, unsigned int i) { return os; } StreamClass &operator<<(StreamClass &os, int i) { return os; } StreamClass &operator>>(StreamClass &os, unsigned int i) { return os; } StreamClass &operator>>(StreamClass &os, int i) { return os; } struct AnotherStream { AnotherStream &operator<<(unsigned char c) { return *this; } AnotherStream &operator<<(signed char c) { return *this; } AnotherStream &operator>>(unsigned char c) { return *this; } AnotherStream &operator>>(signed char c) { return *this; } }; void binary_bitwise() { int SValue = 42; int SResult; unsigned int UValue = 42; unsigned int UResult; SResult = SValue & 1; // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: use of a signed integer operand with a binary bitwise operator SResult = SValue & -1; // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: use of a signed integer operand with a binary bitwise operator SResult = SValue & SValue; // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: use of a signed integer operand with a binary bitwise operator UResult = SValue & 1; // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: use of a signed integer operand with a binary bitwise operator UResult = SValue & -1; // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: use of a signed integer operand with a binary bitwise operator UResult = UValue & 1u; // Ok UResult = UValue & UValue; // Ok unsigned char UByte1 = 0u; unsigned char UByte2 = 16u; signed char SByte1 = 0; signed char SByte2 = 16; UByte1 = UByte1 & UByte2; // Ok UByte1 = SByte1 & UByte2; // CHECK-MESSAGES: :[[@LINE-1]]:12: warning: use of a signed integer operand with a binary bitwise operator UByte1 = SByte1 & SByte2; // CHECK-MESSAGES: :[[@LINE-1]]:12: warning: use of a signed integer operand with a binary bitwise operator SByte1 = SByte1 & SByte2; // CHECK-MESSAGES: :[[@LINE-1]]:12: warning: use of a signed integer operand with a binary bitwise operator // More complex expressions. UResult = UValue & (SByte1 + (SByte1 | SByte2)); // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: use of a signed integer operand with a binary bitwise operator // CHECK-MESSAGES: :[[@LINE-2]]:33: warning: use of a signed integer operand with a binary bitwise operator // The rest is to demonstrate functionality but all operators are matched equally. // Therefore functionality is the same for all binary operations. UByte1 = UByte1 | UByte2; // Ok UByte1 = UByte1 | SByte2; // CHECK-MESSAGES: :[[@LINE-1]]:12: warning: use of a signed integer operand with a binary bitwise operator UByte1 = UByte1 ^ UByte2; // Ok UByte1 = UByte1 ^ SByte2; // CHECK-MESSAGES: :[[@LINE-1]]:12: warning: use of a signed integer operand with a binary bitwise operator UByte1 = UByte1 >> UByte2; // Ok UByte1 = UByte1 >> SByte2; // CHECK-MESSAGES: :[[@LINE-1]]:12: warning: use of a signed integer operand with a binary bitwise operator UByte1 = UByte1 << UByte2; // Ok UByte1 = UByte1 << SByte2; // CHECK-MESSAGES: :[[@LINE-1]]:12: warning: use of a signed integer operand with a binary bitwise operator int SignedInt1 = 1 << 12; // CHECK-MESSAGES: :[[@LINE-1]]:20: warning: use of a signed integer operand with a binary bitwise operator int SignedInt2 = 1u << 12; // CHECK-MESSAGES: :[[@LINE-1]]:20: warning: use of a signed integer operand with a binary bitwise operator } void f1(unsigned char c) {} void f2(signed char c) {} void f3(int c) {} void unary_bitwise() { unsigned char UByte1 = 0u; signed char SByte1 = 0; UByte1 = ~UByte1; // Ok SByte1 = ~UByte1; SByte1 = ~SByte1; // CHECK-MESSAGES: :[[@LINE-1]]:12: warning: use of a signed integer operand with a unary bitwise operator UByte1 = ~SByte1; // CHECK-MESSAGES: :[[@LINE-1]]:12: warning: use of a signed integer operand with a unary bitwise operator unsigned int UInt = 0u; int SInt = 0; f1(~UByte1); // Ok f1(~SByte1); // CHECK-MESSAGES: :[[@LINE-1]]:6: warning: use of a signed integer operand with a unary bitwise operator f1(~UInt); f1(~SInt); // CHECK-MESSAGES: :[[@LINE-1]]:6: warning: use of a signed integer operand with a unary bitwise operator f2(~UByte1); f2(~SByte1); // CHECK-MESSAGES: :[[@LINE-1]]:6: warning: use of a signed integer operand with a unary bitwise operator f2(~UInt); f2(~SInt); // CHECK-MESSAGES: :[[@LINE-1]]:6: warning: use of a signed integer operand with a unary bitwise operator f3(~UByte1); // Ok f3(~SByte1); // CHECK-MESSAGES: :[[@LINE-1]]:6: warning: use of a signed integer operand with a unary bitwise operator } /// HICPP uses these examples to demonstrate the rule. void standard_examples() { int i = 3; unsigned int k = 0u; int r = i << -1; // Emits -Wshift-count-negative from clang // CHECK-MESSAGES: :[[@LINE-1]]:11: warning: use of a signed integer operand with a binary bitwise operator r = i << 1; // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use of a signed integer operand with a binary bitwise operator r = -1 >> -1; // Emits -Wshift-count-negative from clang // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use of a signed integer operand with a binary bitwise operator r = -1 >> 1; // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use of a signed integer operand with a binary bitwise operator r = -1 >> i; // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use of a signed integer operand with a binary bitwise operator r = -1 >> -i; // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use of a signed integer operand with a binary bitwise operator r = ~0; // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use of a signed integer operand with a unary bitwise operator r = ~0u; // Ok k = ~k; // Ok unsigned int u = (-1) & 2u; // CHECK-MESSAGES: :[[@LINE-1]]:20: warning: use of a signed integer operand with a binary bitwise operator u = (-1) | 1u; // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use of a signed integer operand with a binary bitwise operator u = (-1) ^ 1u; // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use of a signed integer operand with a binary bitwise operator } void streams_should_work() { StreamClass s; s << 1u; // Ok s << 1; // Ok s >> 1; // Ok s >> 1u; // Ok AnotherStream as; unsigned char uc = 1u; signed char sc = 1; as << uc; // Ok as << sc; // Ok as >> uc; // Ok as >> sc; // Ok } enum OldEnum { ValueOne, ValueTwo, }; enum OldSigned : int { IntOne, IntTwo, }; void classicEnums() { OldEnum e1 = ValueOne, e2 = ValueTwo; int e3; // Using the enum type, results in an error. e3 = ValueOne | ValueTwo; // Ok e3 = ValueOne & ValueTwo; // Ok e3 = ValueOne ^ ValueTwo; // Ok e3 = e1 | e2; // Ok e3 = e1 & e2; // Ok e3 = e1 ^ e2; // Ok OldSigned s1 = IntOne, s2 = IntTwo; int s3; s3 = IntOne | IntTwo; // Signed // CHECK-MESSAGES: [[@LINE-1]]:8: warning: use of a signed integer operand with a binary bitwise operator s3 = IntOne & IntTwo; // Signed // CHECK-MESSAGES: [[@LINE-1]]:8: warning: use of a signed integer operand with a binary bitwise operator s3 = IntOne ^ IntTwo; // Signed // CHECK-MESSAGES: [[@LINE-1]]:8: warning: use of a signed integer operand with a binary bitwise operator s3 = s1 | s2; // Signed // CHECK-MESSAGES: [[@LINE-1]]:8: warning: use of a signed integer operand with a binary bitwise operator s3 = s1 & s2; // Signed // CHECK-MESSAGES: [[@LINE-1]]:8: warning: use of a signed integer operand with a binary bitwise operator s3 = s1 ^ s2; // Signed // CHECK-MESSAGES: [[@LINE-1]]:8: warning: use of a signed integer operand with a binary bitwise operator } enum EnumConstruction { one = 1, two = 2, test1 = 1 << 12, // CHECK-MESSAGES: [[@LINE-1]]:11: warning: use of a signed integer operand with a binary bitwise operator test2 = one << two, // CHECK-MESSAGES: [[@LINE-1]]:11: warning: use of a signed integer operand with a binary bitwise operator test3 = 1u << 12, // CHECK-MESSAGES: [[@LINE-1]]:11: warning: use of a signed integer operand with a binary bitwise operator }; <commit_msg>[clang-tidy] Remove target specification hicpp-signed-bitwise<commit_after>// RUN: %check_clang_tidy %s hicpp-signed-bitwise %t -- -- -std=c++11 // These could cause false positives and should not be considered. struct StreamClass { }; StreamClass &operator<<(StreamClass &os, unsigned int i) { return os; } StreamClass &operator<<(StreamClass &os, int i) { return os; } StreamClass &operator>>(StreamClass &os, unsigned int i) { return os; } StreamClass &operator>>(StreamClass &os, int i) { return os; } struct AnotherStream { AnotherStream &operator<<(unsigned char c) { return *this; } AnotherStream &operator<<(signed char c) { return *this; } AnotherStream &operator>>(unsigned char c) { return *this; } AnotherStream &operator>>(signed char c) { return *this; } }; void binary_bitwise() { int SValue = 42; int SResult; unsigned int UValue = 42; unsigned int UResult; SResult = SValue & 1; // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: use of a signed integer operand with a binary bitwise operator SResult = SValue & -1; // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: use of a signed integer operand with a binary bitwise operator SResult = SValue & SValue; // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: use of a signed integer operand with a binary bitwise operator UResult = SValue & 1; // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: use of a signed integer operand with a binary bitwise operator UResult = SValue & -1; // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: use of a signed integer operand with a binary bitwise operator UResult = UValue & 1u; // Ok UResult = UValue & UValue; // Ok unsigned char UByte1 = 0u; unsigned char UByte2 = 16u; signed char SByte1 = 0; signed char SByte2 = 16; UByte1 = UByte1 & UByte2; // Ok UByte1 = SByte1 & UByte2; // CHECK-MESSAGES: :[[@LINE-1]]:12: warning: use of a signed integer operand with a binary bitwise operator UByte1 = SByte1 & SByte2; // CHECK-MESSAGES: :[[@LINE-1]]:12: warning: use of a signed integer operand with a binary bitwise operator SByte1 = SByte1 & SByte2; // CHECK-MESSAGES: :[[@LINE-1]]:12: warning: use of a signed integer operand with a binary bitwise operator // More complex expressions. UResult = UValue & (SByte1 + (SByte1 | SByte2)); // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: use of a signed integer operand with a binary bitwise operator // CHECK-MESSAGES: :[[@LINE-2]]:33: warning: use of a signed integer operand with a binary bitwise operator // The rest is to demonstrate functionality but all operators are matched equally. // Therefore functionality is the same for all binary operations. UByte1 = UByte1 | UByte2; // Ok UByte1 = UByte1 | SByte2; // CHECK-MESSAGES: :[[@LINE-1]]:12: warning: use of a signed integer operand with a binary bitwise operator UByte1 = UByte1 ^ UByte2; // Ok UByte1 = UByte1 ^ SByte2; // CHECK-MESSAGES: :[[@LINE-1]]:12: warning: use of a signed integer operand with a binary bitwise operator UByte1 = UByte1 >> UByte2; // Ok UByte1 = UByte1 >> SByte2; // CHECK-MESSAGES: :[[@LINE-1]]:12: warning: use of a signed integer operand with a binary bitwise operator UByte1 = UByte1 << UByte2; // Ok UByte1 = UByte1 << SByte2; // CHECK-MESSAGES: :[[@LINE-1]]:12: warning: use of a signed integer operand with a binary bitwise operator int SignedInt1 = 1 << 12; // CHECK-MESSAGES: :[[@LINE-1]]:20: warning: use of a signed integer operand with a binary bitwise operator int SignedInt2 = 1u << 12; // CHECK-MESSAGES: :[[@LINE-1]]:20: warning: use of a signed integer operand with a binary bitwise operator } void f1(unsigned char c) {} void f2(signed char c) {} void f3(int c) {} void unary_bitwise() { unsigned char UByte1 = 0u; signed char SByte1 = 0; UByte1 = ~UByte1; // Ok SByte1 = ~UByte1; SByte1 = ~SByte1; // CHECK-MESSAGES: :[[@LINE-1]]:12: warning: use of a signed integer operand with a unary bitwise operator UByte1 = ~SByte1; // CHECK-MESSAGES: :[[@LINE-1]]:12: warning: use of a signed integer operand with a unary bitwise operator unsigned int UInt = 0u; int SInt = 0; f1(~UByte1); // Ok f1(~SByte1); // CHECK-MESSAGES: :[[@LINE-1]]:6: warning: use of a signed integer operand with a unary bitwise operator f1(~UInt); f1(~SInt); // CHECK-MESSAGES: :[[@LINE-1]]:6: warning: use of a signed integer operand with a unary bitwise operator f2(~UByte1); f2(~SByte1); // CHECK-MESSAGES: :[[@LINE-1]]:6: warning: use of a signed integer operand with a unary bitwise operator f2(~UInt); f2(~SInt); // CHECK-MESSAGES: :[[@LINE-1]]:6: warning: use of a signed integer operand with a unary bitwise operator f3(~UByte1); // Ok f3(~SByte1); // CHECK-MESSAGES: :[[@LINE-1]]:6: warning: use of a signed integer operand with a unary bitwise operator } /// HICPP uses these examples to demonstrate the rule. void standard_examples() { int i = 3; unsigned int k = 0u; int r = i << -1; // Emits -Wshift-count-negative from clang // CHECK-MESSAGES: :[[@LINE-1]]:11: warning: use of a signed integer operand with a binary bitwise operator r = i << 1; // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use of a signed integer operand with a binary bitwise operator r = -1 >> -1; // Emits -Wshift-count-negative from clang // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use of a signed integer operand with a binary bitwise operator r = -1 >> 1; // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use of a signed integer operand with a binary bitwise operator r = -1 >> i; // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use of a signed integer operand with a binary bitwise operator r = -1 >> -i; // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use of a signed integer operand with a binary bitwise operator r = ~0; // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use of a signed integer operand with a unary bitwise operator r = ~0u; // Ok k = ~k; // Ok unsigned int u = (-1) & 2u; // CHECK-MESSAGES: :[[@LINE-1]]:20: warning: use of a signed integer operand with a binary bitwise operator u = (-1) | 1u; // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use of a signed integer operand with a binary bitwise operator u = (-1) ^ 1u; // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use of a signed integer operand with a binary bitwise operator } void streams_should_work() { StreamClass s; s << 1u; // Ok s << 1; // Ok s >> 1; // Ok s >> 1u; // Ok AnotherStream as; unsigned char uc = 1u; signed char sc = 1; as << uc; // Ok as << sc; // Ok as >> uc; // Ok as >> sc; // Ok } enum OldEnum { ValueOne, ValueTwo, }; enum OldSigned : int { IntOne, IntTwo, }; void classicEnums() { OldEnum e1 = ValueOne, e2 = ValueTwo; int e3; // Using the enum type, results in an error. e3 = ValueOne | ValueTwo; // Ok e3 = ValueOne & ValueTwo; // Ok e3 = ValueOne ^ ValueTwo; // Ok e3 = e1 | e2; // Ok e3 = e1 & e2; // Ok e3 = e1 ^ e2; // Ok OldSigned s1 = IntOne, s2 = IntTwo; int s3; s3 = IntOne | IntTwo; // Signed // CHECK-MESSAGES: [[@LINE-1]]:8: warning: use of a signed integer operand with a binary bitwise operator s3 = IntOne & IntTwo; // Signed // CHECK-MESSAGES: [[@LINE-1]]:8: warning: use of a signed integer operand with a binary bitwise operator s3 = IntOne ^ IntTwo; // Signed // CHECK-MESSAGES: [[@LINE-1]]:8: warning: use of a signed integer operand with a binary bitwise operator s3 = s1 | s2; // Signed // CHECK-MESSAGES: [[@LINE-1]]:8: warning: use of a signed integer operand with a binary bitwise operator s3 = s1 & s2; // Signed // CHECK-MESSAGES: [[@LINE-1]]:8: warning: use of a signed integer operand with a binary bitwise operator s3 = s1 ^ s2; // Signed // CHECK-MESSAGES: [[@LINE-1]]:8: warning: use of a signed integer operand with a binary bitwise operator } enum EnumConstruction { one = 1, two = 2, test1 = 1 << 12, // CHECK-MESSAGES: [[@LINE-1]]:11: warning: use of a signed integer operand with a binary bitwise operator test2 = one << two, // CHECK-MESSAGES: [[@LINE-1]]:11: warning: use of a signed integer operand with a binary bitwise operator test3 = 1u << 12, // CHECK-MESSAGES: [[@LINE-1]]:11: warning: use of a signed integer operand with a binary bitwise operator }; <|endoftext|>
<commit_before>// Copyright (c) 2013, Matthew Harvey. All rights reserved. #include "transaction_ctrl.hpp" #include "account.hpp" #include "account_ctrl.hpp" #include "account_reader.hpp" #include "account_type.hpp" #include "b_string.hpp" #include "date.hpp" #include "date_ctrl.hpp" #include "decimal_text_ctrl.hpp" #include "decimal_validator.hpp" #include "entry.hpp" #include "finformat.hpp" #include "frame.hpp" #include "ordinary_journal.hpp" #include "locale.hpp" #include "phatbooks_database_connection.hpp" #include "top_panel.hpp" #include "transaction_type_ctrl.hpp" #include "transaction_type.hpp" #include <boost/date_time/gregorian/gregorian.hpp> #include <boost/scoped_ptr.hpp> #include <jewel/debug_log.hpp> #include <jewel/decimal.hpp> #include <jewel/on_windows.hpp> #include <wx/arrstr.h> #include <wx/button.h> #include <wx/combobox.h> #include <wx/panel.h> #include <wx/event.h> #include <wx/msgdlg.h> #include <wx/gbsizer.h> #include <wx/stattext.h> #include <wx/string.h> #include <wx/textctrl.h> #include <algorithm> #include <cassert> #include <iostream> #include <vector> using boost::scoped_ptr; using jewel::Decimal; using std::endl; using std::vector; namespace gregorian = boost::gregorian; namespace phatbooks { namespace gui { BEGIN_EVENT_TABLE(TransactionCtrl, wxPanel) EVT_BUTTON ( wxID_OK, TransactionCtrl::on_ok_button_click ) EVT_BUTTON ( s_recurring_transaction_button_id, TransactionCtrl::on_recurring_transaction_button_click ) EVT_BUTTON ( wxID_CANCEL, TransactionCtrl::on_cancel_button_click ) END_EVENT_TABLE() // WARNING There are bugs in wxWidgets' wxDatePickerCtrl under wxGTK. // Firstly, tab traversal gets stuck on that control. // Secondly, if we type a different date and then press "Enter" for OK, // the date that actually gets picked up as the transaction date always // seems to be TODAY's date, not the date actually entered. This appears to // be an unresolved bug in wxWidgets. // Note adding wxTAB_TRAVERSAL to style does not seem to fix the problem. // We have used a simple custom class, DateCtrl here instead, to avoid // these problems. Might later add a button to pop up a wxCalendarCtrl // if the user wants one. TransactionCtrl::TransactionCtrl ( TopPanel* p_parent, vector<Account> const& p_balance_sheet_accounts, vector<Account> const& p_pl_accounts, PhatbooksDatabaseConnection& p_database_connection ): wxPanel ( p_parent, wxID_ANY, wxDefaultPosition, wxDefaultSize ), m_top_sizer(0), m_transaction_type_ctrl(0), m_primary_amount_ctrl(0), m_date_ctrl(0), m_cancel_button(0), m_recurring_transaction_button(0), m_ok_button(0), m_database_connection(p_database_connection) { assert (m_account_name_boxes.empty()); assert (m_comment_boxes.empty()); assert (m_split_buttons.empty()); assert (!p_balance_sheet_accounts.empty() || !p_pl_accounts.empty()); assert (p_balance_sheet_accounts.size() + p_pl_accounts.size() >= 2); // Figure out the natural TransactionType given the Accounts we have // been passed. We will use this initialize the TransactionTypeCtrl. Account account_x(p_database_connection); Account account_y(p_database_connection); if (p_balance_sheet_accounts.empty()) { assert (p_pl_accounts.size() >= 2); account_x = p_pl_accounts[0]; account_y = p_pl_accounts[1]; } else if (p_pl_accounts.empty()) { assert (p_balance_sheet_accounts.size() >= 2); account_x = p_balance_sheet_accounts[0]; account_y = p_balance_sheet_accounts[1]; } else { assert (!p_balance_sheet_accounts.empty()); assert (!p_pl_accounts.empty()); account_x = p_balance_sheet_accounts[0]; account_y = p_pl_accounts[0]; } if (account_y.account_type() == account_type::revenue) { using std::swap; swap(account_x, account_y); } assert (account_x.has_id()); assert (account_y.has_id()); transaction_type::TransactionType const initial_transaction_type = natural_transaction_type(account_x, account_y); size_t row = 0; // We construct m_ok_button first as we want to be able to refer to its // size when sizing certain other controls below. But we will not add // the OK button to m_top_sizer till later. m_ok_button = new wxButton ( this, wxID_OK, wxString("&OK"), wxDefaultPosition, wxDefaultSize ); wxSize const ok_button_size = m_ok_button->GetSize(); // Top sizer m_top_sizer = new wxGridBagSizer(); SetSizer(m_top_sizer); m_transaction_type_ctrl = new TransactionTypeCtrl ( this, wxID_ANY, wxSize(ok_button_size.x * 2, ok_button_size.y) ); m_transaction_type_ctrl->set_transaction_type(initial_transaction_type); m_top_sizer->Add(m_transaction_type_ctrl, wxGBPosition(row, 1)); m_primary_amount_ctrl = new DecimalTextCtrl ( this, s_primary_amount_ctrl_id, wxSize(ok_button_size.x * 2, ok_button_size.y), m_database_connection.default_commodity().precision(), false ); m_top_sizer->Add(m_primary_amount_ctrl, wxGBPosition(row, 2)); wxSize const date_ctrl_sz(ok_button_size.x, ok_button_size.y); m_date_ctrl = new DateCtrl(this, wxID_ANY, date_ctrl_sz); m_top_sizer->Add(m_date_ctrl, wxGBPosition(row, 4)); row += 2; // We need the names of available Accounts, for the given // TransactionType, from which the user will choose // Accounts, for each side of the transaction. scoped_ptr<AccountReaderBase> const account_reader_x ( create_source_account_reader ( m_database_connection, initial_transaction_type ) ); scoped_ptr<AccountReaderBase> const account_reader_y ( create_destination_account_reader ( m_database_connection, initial_transaction_type ) ); // Rows for entering Entry details typedef vector<Account>::size_type Size; vector<Account> accounts; accounts.push_back(account_x); accounts.push_back(account_y); Size const sz = accounts.size(); for (Size id = s_min_entry_row_id, i = 0 ; i != sz; ++i, id += 2, ++row) { Account const account = accounts[i]; assert ((i == 0) || (i == 1)); assert (accounts.size() == 2); AccountReaderBase* account_reader = ( (i == 0)? account_reader_x.get(): account_reader_y.get() ); AccountCtrl* account_name_box = new AccountCtrl ( this, id, account, wxSize(ok_button_size.x * 2, ok_button_size.y), account_reader->begin(), account_reader->end(), m_database_connection ); wxSize const account_name_box_size = account_name_box->GetSize(); wxTextCtrl* comment_ctrl = new wxTextCtrl ( this, id, wxEmptyString, wxDefaultPosition, wxSize(ok_button_size.x * 4.5, account_name_box_size.y), wxALIGN_LEFT ); wxButton* split_button = new wxButton ( this, id + 1, wxString("&Split..."), wxDefaultPosition, ok_button_size ); int base_flag = wxLEFT; if (i == 0) base_flag |= wxTOP; m_top_sizer->Add(account_name_box, wxGBPosition(row, 1)); m_top_sizer->Add(comment_ctrl, wxGBPosition(row, 2), wxGBSpan(1, 2)); m_top_sizer->Add(split_button, wxGBPosition(row, 4)); m_account_name_boxes.push_back(account_name_box); m_comment_boxes.push_back(comment_ctrl); m_split_buttons.push_back(split_button); } // Button row m_cancel_button = new wxButton ( this, wxID_CANCEL, wxString("&Cancel"), wxDefaultPosition, ok_button_size ); m_top_sizer->Add(m_cancel_button, wxGBPosition(row, 1)); m_recurring_transaction_button = new wxButton ( this, s_recurring_transaction_button_id, wxString("&Recurring..."), wxDefaultPosition, wxSize(ok_button_size.x, ok_button_size.y) ); m_top_sizer->Add(m_recurring_transaction_button, wxGBPosition(row, 2)); m_top_sizer->Add(m_ok_button, wxGBPosition(row, 4)); m_ok_button->SetDefault(); // Enter key will now trigger "OK" button ++row; // Radio box for selecting actual vs. budget wxArrayString radio_box_strings; radio_box_strings.Add(wxString("Actual")); radio_box_strings.Add(wxString("Budget")); // "Admin" // SetSizer(m_top_sizer); m_top_sizer->Fit(this); m_top_sizer->SetSizeHints(this); Layout(); } void TransactionCtrl::refresh_for_transaction_type ( transaction_type::TransactionType p_transaction_type ) { JEWEL_DEBUG_LOG << "Called TransactionCtrl::refresh_for_transaction_type." << endl; // TODO Implement. } void TransactionCtrl::on_ok_button_click(wxCommandEvent& event) { (void)event; // Silence compiler re. unused parameter. if (Validate() && TransferDataFromWindow()) { if (is_balanced()) { post_journal(); TopPanel* const panel = dynamic_cast<TopPanel*>(GetParent()); assert (panel); panel->update(); } else { wxMessageBox("Transaction does not balance."); } } return; } void TransactionCtrl::on_recurring_transaction_button_click(wxCommandEvent& event) { (void)event; // Silence compiler re. unused parameter. return; } void TransactionCtrl::on_cancel_button_click(wxCommandEvent& event) { (void)event; // Silence compiler re. unused parameter. TopPanel* const panel = dynamic_cast<TopPanel*>(GetParent()); assert (panel); panel->update(); } void TransactionCtrl::post_journal() const { OrdinaryJournal journal(m_database_connection); transaction_type::TransactionType const ttype = m_transaction_type_ctrl->transaction_type(); journal.set_whether_actual(transaction_type_is_actual(ttype)); size_t const sz = m_account_name_boxes.size(); assert (sz == m_comment_boxes.size()); Decimal const primary_amount = wx_to_decimal ( wxString(m_primary_amount_ctrl->GetValue()), locale() ); // WARNING This can't yet handle Journals with a number of entries // other than 2. assert (sz == 2); for (size_t i = 0; i != sz; ++i) { Account const account ( m_database_connection, wx_to_bstring(wxString(m_account_name_boxes[i]->GetValue())) ); Entry entry(m_database_connection); entry.set_account(account); entry.set_comment ( wx_to_bstring(m_comment_boxes[i]->GetValue()) ); Decimal amount = primary_amount; if (i == 0) { // This is the source account amount = -amount; } if (!journal.is_actual()) { amount = -amount; } amount = round(amount, account.commodity().precision()); entry.set_amount(amount); entry.set_whether_reconciled(false); journal.push_entry(entry); } assert (journal.is_balanced()); journal.set_comment(""); // Process date journal.set_date(m_date_ctrl->date()); // Save journal journal.save(); } bool TransactionCtrl::is_balanced() const { // WARNING For now this is trivial, as we have only the primary_amount // informing one each of only two sides of the transaction. But it // probably won't always be trivial. return true; /* Decimal balance(0, 0); vector<DecimalTextCtrl*>::size_type i = 0; vector<DecimalTextCtrl*>::size_type const sz = m_amount_boxes.size(); for ( ; i != sz; ++i) { balance += wx_to_decimal(m_amount_boxes[i]->GetValue(), locale()); } return balance == Decimal(0, 0); */ } } // namespace gui } // namespace phatbooks <commit_msg>Repositioned and resized some elements in TransactionCtrl. Date is now on bottom row. Added labels "Source:", "Destination:" and "Comment:" to help user navigate the interface. Put spaces between rows.<commit_after>// Copyright (c) 2013, Matthew Harvey. All rights reserved. #include "transaction_ctrl.hpp" #include "account.hpp" #include "account_ctrl.hpp" #include "account_reader.hpp" #include "account_type.hpp" #include "b_string.hpp" #include "date.hpp" #include "date_ctrl.hpp" #include "decimal_text_ctrl.hpp" #include "decimal_validator.hpp" #include "entry.hpp" #include "finformat.hpp" #include "frame.hpp" #include "ordinary_journal.hpp" #include "locale.hpp" #include "phatbooks_database_connection.hpp" #include "top_panel.hpp" #include "transaction_type_ctrl.hpp" #include "transaction_type.hpp" #include <boost/date_time/gregorian/gregorian.hpp> #include <boost/scoped_ptr.hpp> #include <jewel/debug_log.hpp> #include <jewel/decimal.hpp> #include <jewel/on_windows.hpp> #include <wx/arrstr.h> #include <wx/button.h> #include <wx/combobox.h> #include <wx/panel.h> #include <wx/event.h> #include <wx/msgdlg.h> #include <wx/gbsizer.h> #include <wx/stattext.h> #include <wx/string.h> #include <wx/textctrl.h> #include <algorithm> #include <cassert> #include <iostream> #include <vector> using boost::scoped_ptr; using jewel::Decimal; using std::endl; using std::vector; namespace gregorian = boost::gregorian; namespace phatbooks { namespace gui { BEGIN_EVENT_TABLE(TransactionCtrl, wxPanel) EVT_BUTTON ( wxID_OK, TransactionCtrl::on_ok_button_click ) EVT_BUTTON ( s_recurring_transaction_button_id, TransactionCtrl::on_recurring_transaction_button_click ) EVT_BUTTON ( wxID_CANCEL, TransactionCtrl::on_cancel_button_click ) END_EVENT_TABLE() // WARNING There are bugs in wxWidgets' wxDatePickerCtrl under wxGTK. // Firstly, tab traversal gets stuck on that control. // Secondly, if we type a different date and then press "Enter" for OK, // the date that actually gets picked up as the transaction date always // seems to be TODAY's date, not the date actually entered. This appears to // be an unresolved bug in wxWidgets. // Note adding wxTAB_TRAVERSAL to style does not seem to fix the problem. // We have used a simple custom class, DateCtrl here instead, to avoid // these problems. Might later add a button to pop up a wxCalendarCtrl // if the user wants one. TransactionCtrl::TransactionCtrl ( TopPanel* p_parent, vector<Account> const& p_balance_sheet_accounts, vector<Account> const& p_pl_accounts, PhatbooksDatabaseConnection& p_database_connection ): wxPanel ( p_parent, wxID_ANY, wxDefaultPosition, wxDefaultSize ), m_top_sizer(0), m_transaction_type_ctrl(0), m_primary_amount_ctrl(0), m_date_ctrl(0), m_cancel_button(0), m_recurring_transaction_button(0), m_ok_button(0), m_database_connection(p_database_connection) { assert (m_account_name_boxes.empty()); assert (m_comment_boxes.empty()); assert (m_split_buttons.empty()); assert (!p_balance_sheet_accounts.empty() || !p_pl_accounts.empty()); assert (p_balance_sheet_accounts.size() + p_pl_accounts.size() >= 2); // Figure out the natural TransactionType given the Accounts we have // been passed. We will use this initialize the TransactionTypeCtrl. Account account_x(p_database_connection); Account account_y(p_database_connection); if (p_balance_sheet_accounts.empty()) { assert (p_pl_accounts.size() >= 2); account_x = p_pl_accounts[0]; account_y = p_pl_accounts[1]; } else if (p_pl_accounts.empty()) { assert (p_balance_sheet_accounts.size() >= 2); account_x = p_balance_sheet_accounts[0]; account_y = p_balance_sheet_accounts[1]; } else { assert (!p_balance_sheet_accounts.empty()); assert (!p_pl_accounts.empty()); account_x = p_balance_sheet_accounts[0]; account_y = p_pl_accounts[0]; } if (account_y.account_type() == account_type::revenue) { using std::swap; swap(account_x, account_y); } assert (account_x.has_id()); assert (account_y.has_id()); transaction_type::TransactionType const initial_transaction_type = natural_transaction_type(account_x, account_y); size_t row = 0; // We construct m_ok_button first as we want to be able to refer to its // size when sizing certain other controls below. But we will not add // the OK button to m_top_sizer till later. m_ok_button = new wxButton ( this, wxID_OK, wxString("&OK"), wxDefaultPosition, wxDefaultSize ); wxSize const ok_button_size = m_ok_button->GetSize(); // Top sizer m_top_sizer = new wxGridBagSizer(); SetSizer(m_top_sizer); m_transaction_type_ctrl = new TransactionTypeCtrl ( this, wxID_ANY, wxSize(ok_button_size.x * 2, ok_button_size.y) ); m_transaction_type_ctrl->set_transaction_type(initial_transaction_type); m_top_sizer->Add(m_transaction_type_ctrl, wxGBPosition(row, 1)); wxString const currency_abbreviation = bstring_to_wx ( m_database_connection.default_commodity().abbreviation() ); wxStaticText* const currency_text = new wxStaticText ( this, wxID_ANY, currency_abbreviation, wxDefaultPosition, ok_button_size, wxALIGN_RIGHT ); m_top_sizer->Add ( currency_text, wxGBPosition(row, 2), wxDefaultSpan, wxALIGN_RIGHT ); m_primary_amount_ctrl = new DecimalTextCtrl ( this, s_primary_amount_ctrl_id, wxSize(ok_button_size.x * 2, ok_button_size.y), m_database_connection.default_commodity().precision(), false ); m_top_sizer->Add ( m_primary_amount_ctrl, wxGBPosition(row, 3), wxDefaultSpan, wxALIGN_RIGHT ); wxSize const date_ctrl_sz(ok_button_size.x, ok_button_size.y); row += 2; // We need the names of available Accounts, for the given // TransactionType, from which the user will choose // Accounts, for each side of the transaction. scoped_ptr<AccountReaderBase> const account_reader_x ( create_source_account_reader ( m_database_connection, initial_transaction_type ) ); scoped_ptr<AccountReaderBase> const account_reader_y ( create_destination_account_reader ( m_database_connection, initial_transaction_type ) ); // Rows for entering Entry details typedef vector<Account>::size_type Size; vector<Account> accounts; accounts.push_back(account_x); accounts.push_back(account_y); ++row; Size const sz = accounts.size(); for (Size id = s_min_entry_row_id, i = 0 ; i != sz; ++i, id += 2, row += 3) { wxStaticText* const account_label = new wxStaticText ( this, wxID_ANY, ((i == 0)? wxString(" Source:"): wxString(" Destination:")), wxDefaultPosition, wxDefaultSize, wxALIGN_LEFT ); m_top_sizer->Add(account_label, wxGBPosition(row - 1, 1)); wxStaticText* const comment_label = new wxStaticText ( this, wxID_ANY, wxString("Comment:"), wxDefaultPosition, wxDefaultSize, wxALIGN_LEFT ); m_top_sizer->Add(comment_label, wxGBPosition(row - 1, 2)); Account const account = accounts[i]; assert ((i == 0) || (i == 1)); assert (accounts.size() == 2); AccountReaderBase* account_reader = ( (i == 0)? account_reader_x.get(): account_reader_y.get() ); AccountCtrl* account_name_box = new AccountCtrl ( this, id, account, wxSize(ok_button_size.x * 2, ok_button_size.y), account_reader->begin(), account_reader->end(), m_database_connection ); wxSize const account_name_box_size = account_name_box->GetSize(); wxTextCtrl* comment_ctrl = new wxTextCtrl ( this, id, wxEmptyString, wxDefaultPosition, wxSize(ok_button_size.x * 4.5, account_name_box_size.y), wxALIGN_LEFT ); wxButton* split_button = new wxButton ( this, id + 1, wxString("Split..."), wxDefaultPosition, ok_button_size ); int base_flag = wxLEFT; if (i == 0) base_flag |= wxTOP; m_top_sizer->Add(account_name_box, wxGBPosition(row, 1)); m_top_sizer->Add(comment_ctrl, wxGBPosition(row, 2), wxGBSpan(1, 2)); m_top_sizer->Add(split_button, wxGBPosition(row, 4)); m_account_name_boxes.push_back(account_name_box); m_comment_boxes.push_back(comment_ctrl); m_split_buttons.push_back(split_button); } m_cancel_button = new wxButton ( this, wxID_CANCEL, wxString("&Cancel"), wxDefaultPosition, ok_button_size ); m_top_sizer->Add(m_cancel_button, wxGBPosition(row, 1)); m_date_ctrl = new DateCtrl(this, wxID_ANY, date_ctrl_sz); m_top_sizer->Add(m_date_ctrl, wxGBPosition(row, 2)); m_recurring_transaction_button = new wxButton ( this, s_recurring_transaction_button_id, wxString("&Recurring..."), wxDefaultPosition, wxSize(ok_button_size.x, ok_button_size.y) ); m_top_sizer->Add(m_recurring_transaction_button, wxGBPosition(row, 3)); m_top_sizer->Add(m_ok_button, wxGBPosition(row, 4)); m_ok_button->SetDefault(); // Enter key will now trigger "OK" button ++row; // Radio box for selecting actual vs. budget wxArrayString radio_box_strings; radio_box_strings.Add(wxString("Actual")); radio_box_strings.Add(wxString("Budget")); // "Admin" // SetSizer(m_top_sizer); m_top_sizer->Fit(this); m_top_sizer->SetSizeHints(this); Layout(); } void TransactionCtrl::refresh_for_transaction_type ( transaction_type::TransactionType p_transaction_type ) { JEWEL_DEBUG_LOG << "Called TransactionCtrl::refresh_for_transaction_type." << endl; // TODO Implement. } void TransactionCtrl::on_ok_button_click(wxCommandEvent& event) { (void)event; // Silence compiler re. unused parameter. if (Validate() && TransferDataFromWindow()) { if (is_balanced()) { post_journal(); TopPanel* const panel = dynamic_cast<TopPanel*>(GetParent()); assert (panel); panel->update(); } else { wxMessageBox("Transaction does not balance."); } } return; } void TransactionCtrl::on_recurring_transaction_button_click(wxCommandEvent& event) { (void)event; // Silence compiler re. unused parameter. return; } void TransactionCtrl::on_cancel_button_click(wxCommandEvent& event) { (void)event; // Silence compiler re. unused parameter. TopPanel* const panel = dynamic_cast<TopPanel*>(GetParent()); assert (panel); panel->update(); } void TransactionCtrl::post_journal() const { OrdinaryJournal journal(m_database_connection); transaction_type::TransactionType const ttype = m_transaction_type_ctrl->transaction_type(); journal.set_whether_actual(transaction_type_is_actual(ttype)); size_t const sz = m_account_name_boxes.size(); assert (sz == m_comment_boxes.size()); Decimal const primary_amount = wx_to_decimal ( wxString(m_primary_amount_ctrl->GetValue()), locale() ); // WARNING This can't yet handle Journals with a number of entries // other than 2. assert (sz == 2); for (size_t i = 0; i != sz; ++i) { Account const account ( m_database_connection, wx_to_bstring(wxString(m_account_name_boxes[i]->GetValue())) ); Entry entry(m_database_connection); entry.set_account(account); entry.set_comment ( wx_to_bstring(m_comment_boxes[i]->GetValue()) ); Decimal amount = primary_amount; if (i == 0) { // This is the source account amount = -amount; } if (!journal.is_actual()) { amount = -amount; } amount = round(amount, account.commodity().precision()); entry.set_amount(amount); entry.set_whether_reconciled(false); journal.push_entry(entry); } assert (journal.is_balanced()); journal.set_comment(""); // Process date journal.set_date(m_date_ctrl->date()); // Save journal journal.save(); } bool TransactionCtrl::is_balanced() const { // WARNING For now this is trivial, as we have only the primary_amount // informing one each of only two sides of the transaction. But it // probably won't always be trivial. return true; /* Decimal balance(0, 0); vector<DecimalTextCtrl*>::size_type i = 0; vector<DecimalTextCtrl*>::size_type const sz = m_amount_boxes.size(); for ( ; i != sz; ++i) { balance += wx_to_decimal(m_amount_boxes[i]->GetValue(), locale()); } return balance == Decimal(0, 0); */ } } // namespace gui } // namespace phatbooks <|endoftext|>
<commit_before>/** * This file is part of the CernVM File System. * * Some common functions. */ #ifndef __STDC_FORMAT_MACROS // NOLINTNEXTLINE #define __STDC_FORMAT_MACROS #endif #include <algorithm> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> #include <cstring> #include "cvmfs_config.h" #include "util/algorithm.h" #include "util/string.h" #ifdef CVMFS_NAMESPACE_GUARD namespace CVMFS_NAMESPACE_GUARD { #endif bool HighPrecisionTimer::g_is_enabled = false; double DiffTimeSeconds(struct timeval start, struct timeval end) { // Time substraction, from GCC documentation if (end.tv_usec < start.tv_usec) { int64_t nsec = (end.tv_usec - start.tv_usec) / 1000000 + 1; start.tv_usec -= 1000000 * nsec; start.tv_sec += nsec; } if (end.tv_usec - start.tv_usec > 1000000) { int64_t nsec = (end.tv_usec - start.tv_usec) / 1000000; start.tv_usec += 1000000 * nsec; start.tv_sec -= nsec; } // Compute the time remaining to wait in microseconds. // tv_usec is certainly positive. uint64_t elapsed_usec = ((end.tv_sec - start.tv_sec)*1000000) + (end.tv_usec - start.tv_usec); return static_cast<double>(elapsed_usec)/1000000.0; } void StopWatch::Start() { assert(!running_); gettimeofday(&start_, NULL); running_ = true; } void StopWatch::Stop() { assert(running_); gettimeofday(&end_, NULL); running_ = false; } void StopWatch::Reset() { start_ = timeval(); end_ = timeval(); running_ = false; } double StopWatch::GetTime() const { assert(!running_); return DiffTimeSeconds(start_, end_); } namespace { static unsigned int CountDigits(uint64_t n) { return static_cast<unsigned int>(floor(log10(static_cast<double>(n)))) + 1; } static std::string GenerateStars(unsigned int n) { return std::string(n, '*'); } } // anonymous namespace Log2Histogram::Log2Histogram(unsigned int nbins) { assert(nbins != 0); this->bins_.assign(nbins + 1, 0); // +1 for overflow bin. this->boundary_values_.assign(nbins + 1, 0); // +1 to avoid big if statement unsigned int i; for (i = 1; i <= nbins; i++) { this->boundary_values_[i] = (1 << ((i - 1) + 1)); } } std::vector<atomic_int32> UTLog2Histogram::GetBins(const Log2Histogram &h) { return h.bins_; } unsigned int Log2Histogram::GetQuantile(float n) { uint64_t total = this->N(); // pivot is the index of the element corresponding to the requested quantile uint64_t pivot = total * static_cast<uint64_t>(n); float normalized_pivot = 0.0; // now we iterate through all the bins // note that we _exclude_ the overflow bin unsigned int i = 0; for (i = 1; 1 <= this->bins_.size() - 1; i++) { unsigned int bin_value = static_cast<unsigned int>(atomic_read32(&(this->bins_[i]))); if (pivot <= bin_value) { normalized_pivot = static_cast<float>(pivot) / static_cast<float>(bin_value); break; } pivot -= bin_value; } // now i stores the index of the bin corresponding to the requested quantile // and normalized_pivot is the element we want inside the bin unsigned int min_value = this->boundary_values_[i - 1]; unsigned int max_value = this->boundary_values_[i]; // and we return the linear interpolation return min_value + static_cast<unsigned int>( static_cast<float>(max_value - min_value) * normalized_pivot); } std::string Log2Histogram::ToString() { unsigned int i = 0; unsigned int max_left_boundary_count = 1; unsigned int max_right_boundary_count = 1; unsigned int max_value_count = 1; unsigned int max_stars = 0; unsigned int max_bins = 0; unsigned int total_stars = 38; uint64_t total_sum_of_bins = 0; for (i = 1; i <= this->bins_.size() - 1; i++) { max_left_boundary_count = std::max(max_left_boundary_count, CountDigits(boundary_values_[i] / 2)); max_right_boundary_count = std::max(max_right_boundary_count, CountDigits(boundary_values_[i] - 1)); max_value_count = std::max(max_value_count, CountDigits(this->bins_[i])); max_bins = std::max(max_bins, static_cast<unsigned int>( atomic_read32(&(this->bins_[i])))); total_sum_of_bins += static_cast<unsigned int>(atomic_read32(&(this->bins_[i]))); } max_bins = std::max(max_bins, static_cast<unsigned int>( atomic_read32(&(this->bins_[0])))); total_sum_of_bins += static_cast<unsigned int>(atomic_read32(&(this->bins_[0]))); if (total_sum_of_bins != 0) { max_stars = max_bins * total_stars / total_sum_of_bins; } std::string format = " %" + StringifyUint(max_left_boundary_count < 2 ? 2 : max_left_boundary_count) + "d -> %" + StringifyUint(max_right_boundary_count) + "d : %" + StringifyUint(max_value_count) + "d | %" + StringifyUint(max_stars < 12 ? 12 : max_stars) + "s |\n"; std::string title_format = " %" + StringifyUint((max_left_boundary_count < 2 ? 2 : max_left_boundary_count) + max_right_boundary_count + 4) + "s | %" + StringifyUint(max_value_count + 4) + "s | %" + StringifyUint(max_stars < 12 ? 12 : max_stars) + "s |\n"; std::string overflow_format = "%" + StringifyUint(max_left_boundary_count + max_right_boundary_count + 5) + "s : %" + StringifyUint(max_value_count + 4) + "d | %" + StringifyUint(max_stars < 12 ? 12 : max_stars) + "s |\n"; std::string total_format = "%" + StringifyUint(max_left_boundary_count + max_right_boundary_count + 5 < 8 ? 8 : max_left_boundary_count + max_right_boundary_count + 5) + "s : %" + StringifyUint(max_value_count + 4) + "lld\n"; std::string result_string = ""; const unsigned int kBufSize = 300; char buffer[kBufSize]; memset(buffer, 0, sizeof(buffer)); snprintf(buffer, kBufSize, title_format.c_str(), "nsec", "count", "distribution"); result_string += buffer; memset(buffer, 0, sizeof(buffer)); for (i = 1; i <= this->bins_.size() - 1; i++) { unsigned int n_of_stars = 0; if (total_sum_of_bins != 0) { n_of_stars = static_cast<unsigned int>(atomic_read32(&(this->bins_[i]))) * total_stars / total_sum_of_bins; } snprintf(buffer, kBufSize, format.c_str(), boundary_values_[i - 1], boundary_values_[i] - 1, static_cast<unsigned int>(atomic_read32(&this->bins_[i])), GenerateStars(n_of_stars).c_str()); result_string += buffer; memset(buffer, 0, sizeof(buffer)); } unsigned int n_of_stars = 0; if (total_sum_of_bins != 0) { n_of_stars = static_cast<unsigned int>(atomic_read32(&(this->bins_[0]))) * total_stars / total_sum_of_bins; } snprintf(buffer, kBufSize, overflow_format.c_str(), "overflow", static_cast<unsigned int>(atomic_read32(&(this->bins_[0]))), GenerateStars(n_of_stars).c_str()); result_string += buffer; memset(buffer, 0, sizeof(buffer)); snprintf(buffer, kBufSize, total_format.c_str(), "total", total_sum_of_bins); result_string += buffer; memset(buffer, 0, sizeof(buffer)); float qs[15] = {.1, .2, .25, .3, .4, .5, .6, .7, .75, .8, .9, .95, .99, .995, .999}; snprintf(buffer, kBufSize, "\n\nQuantiles\n" "%0.4f,%0.4f,%0.4f,%0.4f,%0.4f,%0.4f,%0.4f,%0.4f,%0.4f,%0.4f,%0.4f," "%0.4f,%0.4f,%0.4f,%0.4f\n" "%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d\n" "End Quantiles" "\n-----------------------\n", qs[0], qs[1], qs[2], qs[3], qs[4], qs[5], qs[6], qs[7], qs[8], qs[9], qs[10], qs[11], qs[12], qs[13], qs[14], GetQuantile(qs[0]), GetQuantile(qs[1]), GetQuantile(qs[2]), GetQuantile(qs[3]), GetQuantile(qs[4]), GetQuantile(qs[5]), GetQuantile(qs[6]), GetQuantile(qs[7]), GetQuantile(qs[8]), GetQuantile(qs[9]), GetQuantile(qs[10]), GetQuantile(qs[11]), GetQuantile(qs[12]), GetQuantile(qs[13]), GetQuantile(qs[14])); result_string += buffer; memset(buffer, 0, sizeof(buffer)); return result_string; } void Log2Histogram::PrintLog2Histogram() { printf("%s", this->ToString().c_str()); } #ifdef CVMFS_NAMESPACE_GUARD } // namespace CVMFS_NAMESPACE_GUARD #endif <commit_msg>[tidy] Fix arithmetic in Log2Histogram<commit_after>/** * This file is part of the CernVM File System. * * Some common functions. */ #ifndef __STDC_FORMAT_MACROS // NOLINTNEXTLINE #define __STDC_FORMAT_MACROS #endif #include <algorithm> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> #include <cstring> #include "cvmfs_config.h" #include "util/algorithm.h" #include "util/string.h" #ifdef CVMFS_NAMESPACE_GUARD namespace CVMFS_NAMESPACE_GUARD { #endif bool HighPrecisionTimer::g_is_enabled = false; double DiffTimeSeconds(struct timeval start, struct timeval end) { // Time substraction, from GCC documentation if (end.tv_usec < start.tv_usec) { int64_t nsec = (end.tv_usec - start.tv_usec) / 1000000 + 1; start.tv_usec -= 1000000 * nsec; start.tv_sec += nsec; } if (end.tv_usec - start.tv_usec > 1000000) { int64_t nsec = (end.tv_usec - start.tv_usec) / 1000000; start.tv_usec += 1000000 * nsec; start.tv_sec -= nsec; } // Compute the time remaining to wait in microseconds. // tv_usec is certainly positive. uint64_t elapsed_usec = ((end.tv_sec - start.tv_sec)*1000000) + (end.tv_usec - start.tv_usec); return static_cast<double>(elapsed_usec)/1000000.0; } void StopWatch::Start() { assert(!running_); gettimeofday(&start_, NULL); running_ = true; } void StopWatch::Stop() { assert(running_); gettimeofday(&end_, NULL); running_ = false; } void StopWatch::Reset() { start_ = timeval(); end_ = timeval(); running_ = false; } double StopWatch::GetTime() const { assert(!running_); return DiffTimeSeconds(start_, end_); } namespace { static unsigned int CountDigits(uint64_t n) { return static_cast<unsigned int>(floor(log10(static_cast<double>(n)))) + 1; } static std::string GenerateStars(unsigned int n) { return std::string(n, '*'); } } // anonymous namespace Log2Histogram::Log2Histogram(unsigned int nbins) { assert(nbins != 0); this->bins_.assign(nbins + 1, 0); // +1 for overflow bin. this->boundary_values_.assign(nbins + 1, 0); // +1 to avoid big if statement unsigned int i; for (i = 1; i <= nbins; i++) { this->boundary_values_[i] = (1 << ((i - 1) + 1)); } } std::vector<atomic_int32> UTLog2Histogram::GetBins(const Log2Histogram &h) { return h.bins_; } unsigned int Log2Histogram::GetQuantile(float n) { uint64_t total = this->N(); // pivot is the index of the element corresponding to the requested quantile uint64_t pivot = static_cast<uint64_t>(static_cast<float>(total) * n); float normalized_pivot = 0.0; // now we iterate through all the bins // note that we _exclude_ the overflow bin unsigned int i = 0; for (i = 1; 1 <= this->bins_.size() - 1; i++) { unsigned int bin_value = static_cast<unsigned int>(atomic_read32(&(this->bins_[i]))); if (pivot <= bin_value) { normalized_pivot = static_cast<float>(pivot) / static_cast<float>(bin_value); break; } pivot -= bin_value; } // now i stores the index of the bin corresponding to the requested quantile // and normalized_pivot is the element we want inside the bin unsigned int min_value = this->boundary_values_[i - 1]; unsigned int max_value = this->boundary_values_[i]; // and we return the linear interpolation return min_value + static_cast<unsigned int>( static_cast<float>(max_value - min_value) * normalized_pivot); } std::string Log2Histogram::ToString() { unsigned int i = 0; unsigned int max_left_boundary_count = 1; unsigned int max_right_boundary_count = 1; unsigned int max_value_count = 1; unsigned int max_stars = 0; unsigned int max_bins = 0; unsigned int total_stars = 38; uint64_t total_sum_of_bins = 0; for (i = 1; i <= this->bins_.size() - 1; i++) { max_left_boundary_count = std::max(max_left_boundary_count, CountDigits(boundary_values_[i] / 2)); max_right_boundary_count = std::max(max_right_boundary_count, CountDigits(boundary_values_[i] - 1)); max_value_count = std::max(max_value_count, CountDigits(this->bins_[i])); max_bins = std::max(max_bins, static_cast<unsigned int>( atomic_read32(&(this->bins_[i])))); total_sum_of_bins += static_cast<unsigned int>(atomic_read32(&(this->bins_[i]))); } max_bins = std::max(max_bins, static_cast<unsigned int>( atomic_read32(&(this->bins_[0])))); total_sum_of_bins += static_cast<unsigned int>(atomic_read32(&(this->bins_[0]))); if (total_sum_of_bins != 0) { max_stars = max_bins * total_stars / total_sum_of_bins; } std::string format = " %" + StringifyUint(max_left_boundary_count < 2 ? 2 : max_left_boundary_count) + "d -> %" + StringifyUint(max_right_boundary_count) + "d : %" + StringifyUint(max_value_count) + "d | %" + StringifyUint(max_stars < 12 ? 12 : max_stars) + "s |\n"; std::string title_format = " %" + StringifyUint((max_left_boundary_count < 2 ? 2 : max_left_boundary_count) + max_right_boundary_count + 4) + "s | %" + StringifyUint(max_value_count + 4) + "s | %" + StringifyUint(max_stars < 12 ? 12 : max_stars) + "s |\n"; std::string overflow_format = "%" + StringifyUint(max_left_boundary_count + max_right_boundary_count + 5) + "s : %" + StringifyUint(max_value_count + 4) + "d | %" + StringifyUint(max_stars < 12 ? 12 : max_stars) + "s |\n"; std::string total_format = "%" + StringifyUint(max_left_boundary_count + max_right_boundary_count + 5 < 8 ? 8 : max_left_boundary_count + max_right_boundary_count + 5) + "s : %" + StringifyUint(max_value_count + 4) + "lld\n"; std::string result_string = ""; const unsigned int kBufSize = 300; char buffer[kBufSize]; memset(buffer, 0, sizeof(buffer)); snprintf(buffer, kBufSize, title_format.c_str(), "nsec", "count", "distribution"); result_string += buffer; memset(buffer, 0, sizeof(buffer)); for (i = 1; i <= this->bins_.size() - 1; i++) { unsigned int n_of_stars = 0; if (total_sum_of_bins != 0) { n_of_stars = static_cast<unsigned int>(atomic_read32(&(this->bins_[i]))) * total_stars / total_sum_of_bins; } snprintf(buffer, kBufSize, format.c_str(), boundary_values_[i - 1], boundary_values_[i] - 1, static_cast<unsigned int>(atomic_read32(&this->bins_[i])), GenerateStars(n_of_stars).c_str()); result_string += buffer; memset(buffer, 0, sizeof(buffer)); } unsigned int n_of_stars = 0; if (total_sum_of_bins != 0) { n_of_stars = static_cast<unsigned int>(atomic_read32(&(this->bins_[0]))) * total_stars / total_sum_of_bins; } snprintf(buffer, kBufSize, overflow_format.c_str(), "overflow", static_cast<unsigned int>(atomic_read32(&(this->bins_[0]))), GenerateStars(n_of_stars).c_str()); result_string += buffer; memset(buffer, 0, sizeof(buffer)); snprintf(buffer, kBufSize, total_format.c_str(), "total", total_sum_of_bins); result_string += buffer; memset(buffer, 0, sizeof(buffer)); float qs[15] = {.1, .2, .25, .3, .4, .5, .6, .7, .75, .8, .9, .95, .99, .995, .999}; snprintf(buffer, kBufSize, "\n\nQuantiles\n" "%0.4f,%0.4f,%0.4f,%0.4f,%0.4f,%0.4f,%0.4f,%0.4f,%0.4f,%0.4f,%0.4f," "%0.4f,%0.4f,%0.4f,%0.4f\n" "%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d\n" "End Quantiles" "\n-----------------------\n", qs[0], qs[1], qs[2], qs[3], qs[4], qs[5], qs[6], qs[7], qs[8], qs[9], qs[10], qs[11], qs[12], qs[13], qs[14], GetQuantile(qs[0]), GetQuantile(qs[1]), GetQuantile(qs[2]), GetQuantile(qs[3]), GetQuantile(qs[4]), GetQuantile(qs[5]), GetQuantile(qs[6]), GetQuantile(qs[7]), GetQuantile(qs[8]), GetQuantile(qs[9]), GetQuantile(qs[10]), GetQuantile(qs[11]), GetQuantile(qs[12]), GetQuantile(qs[13]), GetQuantile(qs[14])); result_string += buffer; memset(buffer, 0, sizeof(buffer)); return result_string; } void Log2Histogram::PrintLog2Histogram() { printf("%s", this->ToString().c_str()); } #ifdef CVMFS_NAMESPACE_GUARD } // namespace CVMFS_NAMESPACE_GUARD #endif <|endoftext|>
<commit_before>#include <fstream> #include <iostream> #include "..\include\Common.h" #include "..\include\Player.h" using namespace std; using namespace Common; void Player::SaveGame(){ ofstream WriteData; WriteData.open("data.txt"); WriteData << player_type << endl << name << endl << level << endl << experience << endl << health << endl << arrows << endl << bombs << endl << potions << endl << whetstones << endl << weaponstrength << endl << coins; WriteData.close(); } void Player::SetPlayerData(){ // Primarily initializes default values at the beginning of the game. ifstream ReadData; ReadData.clear(); ReadData.open("data.txt"); ReadData >> player_type; ReadData >> name; ReadData >> level; ReadData >> experience; ReadData >> health; ReadData >> arrows; ReadData >> bombs; ReadData >> potions; ReadData >> whetstones; ReadData >> weaponstrength; ReadData >> coins; ReadData.close(); } int Player::Attack(){ // Returns the amount of attack points the player gives. // Also the main battle screen. int choice = 0; // Displays the inventory. DisplayInventory(); // Gives player a list of moves to choose from. cout << "Choose your move:" << endl << "1) Attack" << endl << "2) Risk Attack" << endl << "3) Bow and Arrow" << endl << "4) Heal" << endl << endl << "5) Use Bomb" << endl << "6) Use Potion" << endl << "7) Use Whetstone" << endl << "0) Get me out of here!" << endl << endl; while (true) { choice = input(); // Evaluates player's choice. switch (choice) { case 0: return Flee(); case 1: // Player generically attacks. return GenericAttack(); case 2: // Player takes a risk and attacks. return RiskAttack(); case 3: // Player shoots their bow. if (arrows > 0) return BowAndArrow(); break; case 4: // Player heals, no damage is done to enemy. Heal(); return 0; case 5: // Player throws a bomb. // Does not execute if there are no bombs in the inventory. if (bombs > 0) return UseBomb(); break; case 6: // Player drinks a potion. // Does not execute if there are no potions in the inventory. if (potions > 0) { UsePotion(); return 0; } break; case 7: // Player sharpens their weapon with a whetstone. // Does not execute if there are no whetstones in inventory. // No damage is done to the enemy. if (whetstones > 0) { UseWhetstone(); return 0; } break; default: // Generically attacks by default if player's choice does not equal above cases. return GenericAttack(); } } } void Player::UseItem() { // Use item from inventory int choice = 0; while (true) { ClearScreen(); // Displays the inventory. DisplayInventory(); // Gives player a list of moves to choose from. cout << "Choose which item use:" << endl << "1) Use Potion" << endl << "2) Use Whetstone" << endl << "0) Quit" << endl << endl; choice = input(); // Evaluates player's choice. switch (choice) { case 0: return; case 1: // Player drinks a potion. // Does not execute if there are no potions in the inventory. if (potions > 0) { UsePotion(); Sleep(SLEEP_MS); } break; case 2: // Player sharpens their weapon with a whetstone. // Does not execute if there are no whetstones in inventory. // No damage is done to the enemy. if (whetstones > 0) { UseWhetstone(); Sleep(SLEEP_MS); } break; default: break; } } } void Player::AddToInventory(vector<int> drops){ // Adds items to inventory and prints out what the player received. // Adds items received to total items. arrows += drops.at(0); bombs += drops.at(1); potions += drops.at(2); whetstones += drops.at(3); coins += drops.at(4); // Prints number of items received. cout << "You have gained: " << endl; if (drops[0] > 0) cout << "[" << drops.at(0) << "] arrows" << endl; if (drops[1] > 0) cout << "[" << drops.at(1) << "] bombs" << endl; if (drops[2] > 0) cout << "[" << drops.at(2) << "] potions" << endl; if (drops[3] > 0) cout << "[" << drops.at(3) << "] whetstones" << endl; if (drops[4] > 0) cout << "[" << drops.at(4) << "] coins" << endl; cout << endl; } void Player::DisplayHUD(Enemy *_Enemy){ // Displays player's name and health bar. Enemy object is used to print name on the same line as player name for aesthetics. // Prints player's name. cout << endl; ColourPrint(name, DARK_GREY); // Tabs to make room for enemy's name. if (name.length() > 5){ cout << "\t\t\t"; } else { cout <<" \t\t\t"; } // Prints enemy name. ColourPrint(_Enemy->GetName(), DARK_GREY); cout << endl; DisplayHealthBar(); } void Player::ReplenishHealth(){ // Adds health points after player has defeated an enemy. if (health <= 0) health = 100; else { health += 30; if (health > 100) health = 100; } } void Player::AddExperience(int xp){ // Adds points to the player's experience and levels player up. // Adds experience from passed in integer to local class variable experience. experience += xp; // Evaluates if experience is higher than 99, which means a level up is in order. if (experience>99) { // Experience is set to 0. experience = 0; // Player is leveled up. level+=1; // Sets level cap to 50, player cannot level higher than that. if (level >= 50) level = 50; // Alerts player that they have leveled up. cout << "You leveled up! Now you are level " << level << "!" << endl; Sleep(SLEEP_MS); } } void Player::LoseExperience(int xp){ // Deducts points from the player's experience and de-levels player. // Deducts experience from passed in integer to local class variable experience. experience -= xp; // Evaluates if experience is less than 0. if (experience<0){ // Experience is deducted continuing from the experience which de-leveled the player (hard to explain...) experience = 100-(0-experience); // De-levels player. level-=1; // Checks any glitches and sets player level to 1 if level is below 1 or above 50. // Also resets experience points. if (level<1 || level>50){ level=1; experience = 0; } // Alerts the player that they have de-leveled. else { cout << "You de-leveled back to level " << level << "..." << endl; Sleep(SLEEP_MS); } } } void Player::AddCoins(int c){ coins += c; } void Player::LoseCoins(int c){ coins -= c; if (coins < 0) coins = 0; } void Player::DisplayInventory(){ // Checks valid weapon strength. if (weaponstrength < 0){ weaponstrength = 0; } // Simply prints the player's inventory. cout << "*----------- INVENTORY -----------* " << endl; cout << "Level " << level << "\t\t\t" << experience << "/100 xp" << endl; cout << "| Arrows: [" << arrows << "]" << endl; cout << "| Potions: [" << potions << "]" << endl; cout << "| Bombs: [" << bombs << "]" << endl; cout << "| Whetstones: [" << whetstones << "]" << endl; cout << "| Weapon strength: [" << weaponstrength << "%]" << endl; cout << "| Wealth: [" << coins << "] coins" << endl; cout << "*---------------------------------*" << endl << endl; } int Player::GenericAttack(){ int damage = ReturnDamage(); DeductDamage(damage); ColourPrint(name, DARK_GREY); cout << " attacks! He deals "; ColourPrint(to_string(damage), RED); cout << " damage points!" << endl; if (damage>0) weaponstrength-= 2+rand()%5; return damage; } int Player::RiskAttack(){ int damage = ReturnRiskAttackDamage(); DeductDamage(damage); ColourPrint(name, DARK_GREY); cout << " takes a risk and attack! It deals "; ColourPrint(to_string(damage), RED); cout << " damage points!" << endl; if (damage>0) weaponstrength-= 4+rand()%5; return damage; } int Player::BowAndArrow(){ int damage = ReturnBowDamage(); ColourPrint(name, DARK_GREY); cout << " shoots his bow! He deals "; SetConsoleTextAttribute(hConsole, RED); cout << damage; SetConsoleTextAttribute(hConsole, GREY); cout << " damage points!" << endl; return damage; } void Player::UseWhetstone(){ weaponstrength=100; ColourPrint(name, DARK_GREY); cout << " sharpened his weapon!" << endl; whetstones--; } void Player::UsePotion(){ health=100; ColourPrint(name, DARK_GREY); cout << " drank a healing potion!" << endl; potions--; } int Player::UseBomb(){ ColourPrint(name, DARK_GREY); cout << " hurls a bomb! It deals "; ColourPrint("50", RED); cout << " damage points!" << endl; bombs--; return 50; } void Player::DeductDamage(int &damage){ if (weaponstrength<=75&&weaponstrength>50) damage-=1; else if (weaponstrength<=50&&weaponstrength>30) damage-=4; else if (weaponstrength<=30&&weaponstrength>20) damage-=5; else if (weaponstrength<=20&&weaponstrength>10) damage-=6; else if (weaponstrength<=10) damage-=7; if (damage<0) damage=0; } int Player::ReturnBowDamage(){ if (arrows < 1) return 0; arrows--; return 10+rand()%6; // 10 - 15 } int Player::Flee(){ ColourPrint(name, DARK_GREY); cout << " chooses to flee!" << endl; return -1; }<commit_msg>Added messages when items = 0<commit_after>#include <fstream> #include <iostream> #include "..\include\Common.h" #include "..\include\Player.h" using namespace std; using namespace Common; void Player::SaveGame(){ ofstream WriteData; WriteData.open("data.txt"); WriteData << player_type << endl << name << endl << level << endl << experience << endl << health << endl << arrows << endl << bombs << endl << potions << endl << whetstones << endl << weaponstrength << endl << coins; WriteData.close(); } void Player::SetPlayerData(){ // Primarily initializes default values at the beginning of the game. ifstream ReadData; ReadData.clear(); ReadData.open("data.txt"); ReadData >> player_type; ReadData >> name; ReadData >> level; ReadData >> experience; ReadData >> health; ReadData >> arrows; ReadData >> bombs; ReadData >> potions; ReadData >> whetstones; ReadData >> weaponstrength; ReadData >> coins; ReadData.close(); } int Player::Attack(){ // Returns the amount of attack points the player gives. // Also the main battle screen. int choice = 0; // Displays the inventory. DisplayInventory(); // Gives player a list of moves to choose from. cout << "Choose your move:" << endl << "1) Attack" << endl << "2) Risk Attack" << endl << "3) Bow and Arrow" << endl << "4) Heal" << endl << endl << "5) Use Bomb" << endl << "6) Use Potion" << endl << "7) Use Whetstone" << endl << "0) Get me out of here!" << endl << endl; while (true) { choice = input(); // Evaluates player's choice. switch (choice) { case 0: return Flee(); case 1: // Player generically attacks. return GenericAttack(); case 2: // Player takes a risk and attacks. return RiskAttack(); case 3: // Player shoots their bow. if (arrows > 0) return BowAndArrow(); break; case 4: // Player heals, no damage is done to enemy. Heal(); return 0; case 5: // Player throws a bomb. // Does not execute if there are no bombs in the inventory. if (bombs > 0) return UseBomb(); break; case 6: // Player drinks a potion. // Does not execute if there are no potions in the inventory. if (potions > 0) { UsePotion(); return 0; } break; case 7: // Player sharpens their weapon with a whetstone. // Does not execute if there are no whetstones in inventory. // No damage is done to the enemy. if (whetstones > 0) { UseWhetstone(); return 0; } break; default: // Generically attacks by default if player's choice does not equal above cases. return GenericAttack(); } } } void Player::UseItem() { // Use item from inventory int choice = 0; while (true) { ClearScreen(); // Displays the inventory. DisplayInventory(); // Gives player a list of moves to choose from. cout << "Choose which item use:" << endl << "1) Use Potion" << endl << "2) Use Whetstone" << endl << "0) Quit" << endl << endl; choice = input(); // Evaluates player's choice. switch (choice) { case 0: return; case 1: // Player drinks a potion. // Does not execute if there are no potions in the inventory. if (potions > 0) { UsePotion(); Sleep(SLEEP_MS); } else { cout << "No potions in the inventory!" << endl; Sleep(SLEEP_MS); } break; case 2: // Player sharpens their weapon with a whetstone. // Does not execute if there are no whetstones in inventory. // No damage is done to the enemy. if (whetstones > 0) { UseWhetstone(); Sleep(SLEEP_MS); } else { cout << "No whetstones in the inventory!" << endl; Sleep(SLEEP_MS); } break; default: break; } } } void Player::AddToInventory(vector<int> drops){ // Adds items to inventory and prints out what the player received. // Adds items received to total items. arrows += drops.at(0); bombs += drops.at(1); potions += drops.at(2); whetstones += drops.at(3); coins += drops.at(4); // Prints number of items received. cout << "You have gained: " << endl; if (drops[0] > 0) cout << "[" << drops.at(0) << "] arrows" << endl; if (drops[1] > 0) cout << "[" << drops.at(1) << "] bombs" << endl; if (drops[2] > 0) cout << "[" << drops.at(2) << "] potions" << endl; if (drops[3] > 0) cout << "[" << drops.at(3) << "] whetstones" << endl; if (drops[4] > 0) cout << "[" << drops.at(4) << "] coins" << endl; cout << endl; } void Player::DisplayHUD(Enemy *_Enemy){ // Displays player's name and health bar. Enemy object is used to print name on the same line as player name for aesthetics. // Prints player's name. cout << endl; ColourPrint(name, DARK_GREY); // Tabs to make room for enemy's name. if (name.length() > 5){ cout << "\t\t\t"; } else { cout <<" \t\t\t"; } // Prints enemy name. ColourPrint(_Enemy->GetName(), DARK_GREY); cout << endl; DisplayHealthBar(); } void Player::ReplenishHealth(){ // Adds health points after player has defeated an enemy. if (health <= 0) health = 100; else { health += 30; if (health > 100) health = 100; } } void Player::AddExperience(int xp){ // Adds points to the player's experience and levels player up. // Adds experience from passed in integer to local class variable experience. experience += xp; // Evaluates if experience is higher than 99, which means a level up is in order. if (experience>99) { // Experience is set to 0. experience = 0; // Player is leveled up. level+=1; // Sets level cap to 50, player cannot level higher than that. if (level >= 50) level = 50; // Alerts player that they have leveled up. cout << "You leveled up! Now you are level " << level << "!" << endl; Sleep(SLEEP_MS); } } void Player::LoseExperience(int xp){ // Deducts points from the player's experience and de-levels player. // Deducts experience from passed in integer to local class variable experience. experience -= xp; // Evaluates if experience is less than 0. if (experience<0){ // Experience is deducted continuing from the experience which de-leveled the player (hard to explain...) experience = 100-(0-experience); // De-levels player. level-=1; // Checks any glitches and sets player level to 1 if level is below 1 or above 50. // Also resets experience points. if (level<1 || level>50){ level=1; experience = 0; } // Alerts the player that they have de-leveled. else { cout << "You de-leveled back to level " << level << "..." << endl; Sleep(SLEEP_MS); } } } void Player::AddCoins(int c){ coins += c; } void Player::LoseCoins(int c){ coins -= c; if (coins < 0) coins = 0; } void Player::DisplayInventory(){ // Checks valid weapon strength. if (weaponstrength < 0){ weaponstrength = 0; } // Simply prints the player's inventory. cout << "*----------- INVENTORY -----------* " << endl; cout << "Level " << level << "\t\t\t" << experience << "/100 xp" << endl; cout << "| Arrows: [" << arrows << "]" << endl; cout << "| Potions: [" << potions << "]" << endl; cout << "| Bombs: [" << bombs << "]" << endl; cout << "| Whetstones: [" << whetstones << "]" << endl; cout << "| Weapon strength: [" << weaponstrength << "%]" << endl; cout << "| Wealth: [" << coins << "] coins" << endl; cout << "*---------------------------------*" << endl << endl; } int Player::GenericAttack(){ int damage = ReturnDamage(); DeductDamage(damage); ColourPrint(name, DARK_GREY); cout << " attacks! He deals "; ColourPrint(to_string(damage), RED); cout << " damage points!" << endl; if (damage>0) weaponstrength-= 2+rand()%5; return damage; } int Player::RiskAttack(){ int damage = ReturnRiskAttackDamage(); DeductDamage(damage); ColourPrint(name, DARK_GREY); cout << " takes a risk and attack! It deals "; ColourPrint(to_string(damage), RED); cout << " damage points!" << endl; if (damage>0) weaponstrength-= 4+rand()%5; return damage; } int Player::BowAndArrow(){ int damage = ReturnBowDamage(); ColourPrint(name, DARK_GREY); cout << " shoots his bow! He deals "; SetConsoleTextAttribute(hConsole, RED); cout << damage; SetConsoleTextAttribute(hConsole, GREY); cout << " damage points!" << endl; return damage; } void Player::UseWhetstone(){ weaponstrength=100; ColourPrint(name, DARK_GREY); cout << " sharpened his weapon!" << endl; whetstones--; } void Player::UsePotion(){ health=100; ColourPrint(name, DARK_GREY); cout << " drank a healing potion!" << endl; potions--; } int Player::UseBomb(){ ColourPrint(name, DARK_GREY); cout << " hurls a bomb! It deals "; ColourPrint("50", RED); cout << " damage points!" << endl; bombs--; return 50; } void Player::DeductDamage(int &damage){ if (weaponstrength<=75&&weaponstrength>50) damage-=1; else if (weaponstrength<=50&&weaponstrength>30) damage-=4; else if (weaponstrength<=30&&weaponstrength>20) damage-=5; else if (weaponstrength<=20&&weaponstrength>10) damage-=6; else if (weaponstrength<=10) damage-=7; if (damage<0) damage=0; } int Player::ReturnBowDamage(){ if (arrows < 1) return 0; arrows--; return 10+rand()%6; // 10 - 15 } int Player::Flee(){ ColourPrint(name, DARK_GREY); cout << " chooses to flee!" << endl; return -1; } <|endoftext|>
<commit_before>// Copyright 2010-2012 RethinkDB, all rights reserved. #ifndef RPC_CONNECTIVITY_MESSAGES_HPP_ #define RPC_CONNECTIVITY_MESSAGES_HPP_ #include <vector> // For cluster_version_t. Once we drop old gcc's, we can just declare "enum class // cluster_version_t;" in this header. // RSI: Can we do that now? #include "version.hpp" class connectivity_service_t; class peer_id_t; class read_stream_t; class write_stream_t; namespace boost { template <class> class function; } /* `message_service_t` is an abstract superclass for things that let you send messages to other nodes. `message_handler_t` is an abstract superclass for things that handle messages received from other nodes. The general pattern usually looks something like this: class cluster_t : public message_service_t { public: class run_t { public: run_t(cluster_t *, message_handler_t *); }; ... }; class application_t : public message_handler_t { public: application_t(message_service_t *); ... }; void do_cluster() { cluster_t cluster; application_t app(&cluster); cluster_t::run_t cluster_run(&cluster, &app); ... } The rationale for splitting the lower-level messaging stuff into two components (e.g. `cluster_t` and `cluster_t::run_t`) is that it makes it clear how to stop further messages from being delivered. When the `cluster_t::run_t` is destroyed, no further messages are delivered. This gives a natural way to make sure that no messages are still being delivered at the time that the `application_t` destructor is called. */ class send_message_write_callback_t { public: virtual ~send_message_write_callback_t() { } virtual void write(cluster_version_t cluster_version, write_stream_t *stream) = 0; }; class message_service_t { public: virtual void send_message(peer_id_t dest_peer, send_message_write_callback_t *callback) = 0; virtual void kill_connection(peer_id_t dest_peer) = 0; virtual connectivity_service_t *get_connectivity_service() = 0; protected: virtual ~message_service_t() { } }; class message_handler_t { public: virtual void on_message(peer_id_t source_peer, cluster_version_t version, read_stream_t *) = 0; // Default implementation. Override to optimize for the local case. virtual void on_local_message(peer_id_t source_peer, cluster_version_t version, std::vector<char> &&data); protected: virtual ~message_handler_t() { } }; #endif /* RPC_CONNECTIVITY_MESSAGES_HPP_ */ <commit_msg>Removed pointless RSI comment.<commit_after>// Copyright 2010-2012 RethinkDB, all rights reserved. #ifndef RPC_CONNECTIVITY_MESSAGES_HPP_ #define RPC_CONNECTIVITY_MESSAGES_HPP_ #include <vector> #include "version.hpp" class connectivity_service_t; class peer_id_t; class read_stream_t; class write_stream_t; namespace boost { template <class> class function; } /* `message_service_t` is an abstract superclass for things that let you send messages to other nodes. `message_handler_t` is an abstract superclass for things that handle messages received from other nodes. The general pattern usually looks something like this: class cluster_t : public message_service_t { public: class run_t { public: run_t(cluster_t *, message_handler_t *); }; ... }; class application_t : public message_handler_t { public: application_t(message_service_t *); ... }; void do_cluster() { cluster_t cluster; application_t app(&cluster); cluster_t::run_t cluster_run(&cluster, &app); ... } The rationale for splitting the lower-level messaging stuff into two components (e.g. `cluster_t` and `cluster_t::run_t`) is that it makes it clear how to stop further messages from being delivered. When the `cluster_t::run_t` is destroyed, no further messages are delivered. This gives a natural way to make sure that no messages are still being delivered at the time that the `application_t` destructor is called. */ class send_message_write_callback_t { public: virtual ~send_message_write_callback_t() { } virtual void write(cluster_version_t cluster_version, write_stream_t *stream) = 0; }; class message_service_t { public: virtual void send_message(peer_id_t dest_peer, send_message_write_callback_t *callback) = 0; virtual void kill_connection(peer_id_t dest_peer) = 0; virtual connectivity_service_t *get_connectivity_service() = 0; protected: virtual ~message_service_t() { } }; class message_handler_t { public: virtual void on_message(peer_id_t source_peer, cluster_version_t version, read_stream_t *) = 0; // Default implementation. Override to optimize for the local case. virtual void on_local_message(peer_id_t source_peer, cluster_version_t version, std::vector<char> &&data); protected: virtual ~message_handler_t() { } }; #endif /* RPC_CONNECTIVITY_MESSAGES_HPP_ */ <|endoftext|>
<commit_before>#include "WProgram.h" #include "Midi.h" #include <GUI.h> void __attribute__((weak)) setup() { } void __attribute__((weak)) loop() { } void __attribute__((weak)) onNoteOn(uint8_t *msg) { } void __attribute__((weak)) onNoteOff(uint8_t *msg) { } void __attribute__((weak)) onControlChange(uint8_t *msg) { } void __attribute__((weak)) onNoteOn2(uint8_t *msg) { } void __attribute__((weak)) onNoteOff2(uint8_t *msg) { } void __attribute__((weak)) onControlChange2(uint8_t *msg) { } void __attribute__((weak)) on16Callback(uint32_t pos) { } void __attribute__((weak)) on32Callback(uint32_t pos) { } bool __attribute__((weak)) handleEvent(gui_event_t *evt) { return false; } class DefaultCallbacks : public MidiCallback, public ClockCallback { public: void onNoteOn(uint8_t *msg) { ::onNoteOn(msg); } void onNoteOff(uint8_t *msg) { ::onNoteOff(msg); } void onControlChange(uint8_t *msg) { ::onControlChange(msg); } void onNoteOn2(uint8_t *msg) { ::onNoteOn2(msg); } void onNoteOff2(uint8_t *msg) { ::onNoteOff2(msg); } void onControlChange2(uint8_t *msg) { ::onControlChange2(msg); } void on16Callback(uint32_t pos) { ::on16Callback(pos); } void on32Callback(uint32_t pos) { ::on32Callback(pos); } void setupMidiCallbacks() { Midi.addOnNoteOnCallback(this, (midi_callback_ptr_t)&DefaultCallbacks::onNoteOn); Midi.addOnNoteOffCallback(this, (midi_callback_ptr_t)&DefaultCallbacks::onNoteOff); Midi.addOnControlChangeCallback(this, (midi_callback_ptr_t)&DefaultCallbacks::onControlChange); Midi2.addOnNoteOnCallback(this, (midi_callback_ptr_t)&DefaultCallbacks::onNoteOn2); Midi2.addOnNoteOffCallback(this, (midi_callback_ptr_t)&DefaultCallbacks::onNoteOff2); Midi2.addOnControlChangeCallback(this, (midi_callback_ptr_t)&DefaultCallbacks::onControlChange2); } void setupClockCallbacks() { MidiClock.addOn16Callback(this, (midi_clock_callback_ptr_t)&DefaultCallbacks::on16Callback); MidiClock.addOn32Callback(this, (midi_clock_callback_ptr_t)&DefaultCallbacks::on32Callback); } }; DefaultCallbacks defaultCallbacks; void __attribute__((weak)) setupEventHandlers() { GUI.addEventHandler(&handleEvent); } void __attribute__((weak)) setupMidiCallbacks() { defaultCallbacks.setupMidiCallbacks(); } void __attribute__((weak)) setupClockCallbacks() { defaultCallbacks.setupClockCallbacks(); } <commit_msg>added comment to test refing in commit messages<commit_after>#include "WProgram.h" #include "Midi.h" #include <GUI.h> void __attribute__((weak)) setup() { } void __attribute__((weak)) loop() { } void __attribute__((weak)) onNoteOn(uint8_t *msg) { } void __attribute__((weak)) onNoteOff(uint8_t *msg) { } void __attribute__((weak)) onControlChange(uint8_t *msg) { } void __attribute__((weak)) onNoteOn2(uint8_t *msg) { } void __attribute__((weak)) onNoteOff2(uint8_t *msg) { } void __attribute__((weak)) onControlChange2(uint8_t *msg) { } void __attribute__((weak)) on16Callback(uint32_t pos) { } void __attribute__((weak)) on32Callback(uint32_t pos) { } bool __attribute__((weak)) handleEvent(gui_event_t *evt) { return false; } class DefaultCallbacks : public MidiCallback, public ClockCallback { public: void onNoteOn(uint8_t *msg) { ::onNoteOn(msg); } void onNoteOff(uint8_t *msg) { ::onNoteOff(msg); } void onControlChange(uint8_t *msg) { ::onControlChange(msg); } void onNoteOn2(uint8_t *msg) { ::onNoteOn2(msg); } void onNoteOff2(uint8_t *msg) { ::onNoteOff2(msg); } void onControlChange2(uint8_t *msg) { ::onControlChange2(msg); } void on16Callback(uint32_t pos) { ::on16Callback(pos); } void on32Callback(uint32_t pos) { ::on32Callback(pos); } void setupMidiCallbacks() { Midi.addOnNoteOnCallback(this, (midi_callback_ptr_t)&DefaultCallbacks::onNoteOn); Midi.addOnNoteOffCallback(this, (midi_callback_ptr_t)&DefaultCallbacks::onNoteOff); Midi.addOnControlChangeCallback(this, (midi_callback_ptr_t)&DefaultCallbacks::onControlChange); Midi2.addOnNoteOnCallback(this, (midi_callback_ptr_t)&DefaultCallbacks::onNoteOn2); Midi2.addOnNoteOffCallback(this, (midi_callback_ptr_t)&DefaultCallbacks::onNoteOff2); Midi2.addOnControlChangeCallback(this, (midi_callback_ptr_t)&DefaultCallbacks::onControlChange2); } void setupClockCallbacks() { MidiClock.addOn16Callback(this, (midi_clock_callback_ptr_t)&DefaultCallbacks::on16Callback); // on32callbacks weakly linked, XXX check performance MidiClock.addOn32Callback(this, (midi_clock_callback_ptr_t)&DefaultCallbacks::on32Callback); } }; DefaultCallbacks defaultCallbacks; void __attribute__((weak)) setupEventHandlers() { GUI.addEventHandler(&handleEvent); } void __attribute__((weak)) setupMidiCallbacks() { defaultCallbacks.setupMidiCallbacks(); } void __attribute__((weak)) setupClockCallbacks() { defaultCallbacks.setupClockCallbacks(); } <|endoftext|>
<commit_before>/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*- Copyright 2017 Raffaello D. Di Napoli This file is part of Lofty. Lofty is free software: you can redistribute it and/or modify it under the terms of version 2.1 of the GNU Lesser General Public License as published by the Free Software Foundation. Lofty 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 <lofty.hxx> #include <lofty/app.hxx> #include <lofty/collections/vector.hxx> #include <lofty/defer_to_scope_end.hxx> #include <lofty/io/text.hxx> #include <lofty/logging.hxx> #include <lofty/net/udp.hxx> using namespace lofty; ////////////////////////////////////////////////////////////////////////////////////////////////////////////// class udp_echo_client_app : public app { public: /*! Main function of the program. @param args Arguments that were provided to this program via command line. @return Return value of this program. */ virtual int main(collections::vector<str> & args) override { LOFTY_TRACE_METHOD(); LOFTY_UNUSED_ARG(args); net::udp::client client; LOFTY_FOR_EACH(auto arg, args) { auto dgram_data(_std::make_shared<io::binary::memory_stream>()); { auto dgram_ostream(io::text::make_ostream(dgram_data)); LOFTY_DEFER_TO_SCOPE_END(dgram_ostream->finalize()); dgram_ostream->print(LOFTY_SL("{}\n"), arg); } net::udp::datagram dgram(net::ip::address::localhost_v4, net::ip::port(9081), _std::move(dgram_data)); LOFTY_LOG(info, LOFTY_SL("client: sending datagram\n")); client.send(dgram); } return 0; } }; LOFTY_APP_CLASS(udp_echo_client_app) <commit_msg>Use auto const & to iterate over vector<commit_after>/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*- Copyright 2017-2018 Raffaello D. Di Napoli This file is part of Lofty. Lofty is free software: you can redistribute it and/or modify it under the terms of version 2.1 of the GNU Lesser General Public License as published by the Free Software Foundation. Lofty 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 <lofty.hxx> #include <lofty/app.hxx> #include <lofty/collections/vector.hxx> #include <lofty/defer_to_scope_end.hxx> #include <lofty/io/text.hxx> #include <lofty/logging.hxx> #include <lofty/net/udp.hxx> using namespace lofty; ////////////////////////////////////////////////////////////////////////////////////////////////////////////// class udp_echo_client_app : public app { public: /*! Main function of the program. @param args Arguments that were provided to this program via command line. @return Return value of this program. */ virtual int main(collections::vector<str> & args) override { LOFTY_TRACE_METHOD(); LOFTY_UNUSED_ARG(args); net::udp::client client; LOFTY_FOR_EACH(auto const & arg, args) { auto dgram_data(_std::make_shared<io::binary::memory_stream>()); { auto dgram_ostream(io::text::make_ostream(dgram_data)); LOFTY_DEFER_TO_SCOPE_END(dgram_ostream->finalize()); dgram_ostream->print(LOFTY_SL("{}\n"), arg); } net::udp::datagram dgram(net::ip::address::localhost_v4, net::ip::port(9081), _std::move(dgram_data)); LOFTY_LOG(info, LOFTY_SL("client: sending datagram\n")); client.send(dgram); } return 0; } }; LOFTY_APP_CLASS(udp_echo_client_app) <|endoftext|>
<commit_before> #include <stack.cpp> #include <catch.hpp> #include <iostream> //using namespace std; SCENARIO("count", "[count]"){ stack<int> s; s.push(1); REQUIRE(s.count()==1); } SCENARIO("push", "[push]"){ stack<int> s; s.push(1); REQUIRE(s.count()==1); REQUIRE(s.top()==1); } SCENARIO("top", "[top]"){ stack<int> s; s.push(1); REQUIRE(s.count()==1); REQUIRE(s.top()==1); } SCENARIO("pop", "[pop]"){ stack<int> s; s.push(1); s.push(2); s.pop(); REQUIRE(s.count()==1); REQUIRE(s.top()==1); } SCENARIO("prisv", "[prisv]"){ stack<int> s; s.push(1); stack<int> s2; s2=s; REQUIRE(s.count()==1); REQUIRE(s.top()==1); } SCENARIO("copy", "[copy]"){ stack<int> s; s.push(1); stack <int> a = s; REQUIRE(a.count()==1); REQUIRE(a.top()==1); } SCENARIO("test", "[test]"){ stack<int> s; REQUIRE(s.count()==0); } SCENARIO("empty", "[empty]"){ stack<int> s; REQUIRE(s.empty()==true); } <commit_msg>Update init.cpp<commit_after>#include <stack.cpp> #include <catch.hpp> #include <iostream> using namespace std; SCENARIO("count", "[count]"){ stack<int> s; s.push(1); REQUIRE(s.count()==1); } SCENARIO("push", "[push]"){ stack<int> s; s.push(1); REQUIRE(s.count()==1); REQUIRE(s.pop()==1); } SCENARIO("pop", "[pop]"){ stack<int> s; s.push(1); REQUIRE(s.count()==1); REQUIRE(s.pop()==1); } SCENARIO("prisv", "[prisv]"){ stack<int> s; s.push(1); stack<int> s2; s2=s; REQUIRE(s.count()==1); REQUIRE(s.pop()==1); } SCENARIO("copy", "[copy]"){ stack<int> s; s.push(1); stack <int> a = s; REQUIRE(a.count()==1); REQUIRE(a.pop()==1); } SCENARIO("test", "[test]"){ stack<int> s; REQUIRE(s.count()==0); } <|endoftext|>
<commit_before>#define PY_SSIZE_T_CLEAN 1 #include <Python.h> #include <bytesobject.h> #include "../enc/encode.h" #include "../dec/decode.h" #include "../tools/version.h" #if PY_MAJOR_VERSION >= 3 #define PyInt_Check PyLong_Check #define PyInt_AsLong PyLong_AsLong #endif using namespace brotli; static PyObject *BrotliError; static int mode_convertor(PyObject *o, BrotliParams::Mode *mode) { if (!PyInt_Check(o)) { PyErr_SetString(BrotliError, "Invalid mode"); return 0; } *mode = (BrotliParams::Mode) PyInt_AsLong(o); if (*mode != BrotliParams::MODE_GENERIC && *mode != BrotliParams::MODE_TEXT && *mode != BrotliParams::MODE_FONT) { PyErr_SetString(BrotliError, "Invalid mode"); return 0; } return 1; } static int quality_convertor(PyObject *o, int *quality) { if (!PyInt_Check(o)) { PyErr_SetString(BrotliError, "Invalid quality"); return 0; } *quality = PyInt_AsLong(o); if (*quality < 0 || *quality > 11) { PyErr_SetString(BrotliError, "Invalid quality. Range is 0 to 11."); return 0; } return 1; } static int lgwin_convertor(PyObject *o, int *lgwin) { if (!PyInt_Check(o)) { PyErr_SetString(BrotliError, "Invalid lgwin"); return 0; } *lgwin = PyInt_AsLong(o); if (*lgwin < 10 || *lgwin > 24) { PyErr_SetString(BrotliError, "Invalid lgwin. Range is 10 to 24."); return 0; } return 1; } static int lgblock_convertor(PyObject *o, int *lgblock) { if (!PyInt_Check(o)) { PyErr_SetString(BrotliError, "Invalid lgblock"); return 0; } *lgblock = PyInt_AsLong(o); if ((*lgblock != 0 && *lgblock < 16) || *lgblock > 24) { PyErr_SetString(BrotliError, "Invalid lgblock. Can be 0 or in range 16 to 24."); return 0; } return 1; } PyDoc_STRVAR(compress__doc__, "Compress a byte string.\n" "\n" "Signature:\n" " compress(string, mode=MODE_GENERIC, quality=11, lgwin=22, lgblock=0)\n" "\n" "Args:\n" " string (bytes): The input data.\n" " mode (int, optional): The compression mode can be MODE_GENERIC (default),\n" " MODE_TEXT (for UTF-8 format text input) or MODE_FONT (for WOFF 2.0). \n" " quality (int, optional): Controls the compression-speed vs compression-\n" " density tradeoff. The higher the quality, the slower the compression.\n" " Range is 0 to 11. Defaults to 11.\n" " lgwin (int, optional): Base 2 logarithm of the sliding window size. Range\n" " is 10 to 24. Defaults to 22.\n" " lgblock (int, optional): Base 2 logarithm of the maximum input block size.\n" " Range is 16 to 24. If set to 0, the value will be set based on the\n" " quality. Defaults to 0.\n" "\n" "Returns:\n" " The compressed byte string.\n" "\n" "Raises:\n" " brotli.error: If arguments are invalid, or compressor fails.\n"); static PyObject* brotli_compress(PyObject *self, PyObject *args, PyObject *keywds) { PyObject *ret = NULL; uint8_t *input, *output; size_t length, output_length; BrotliParams::Mode mode = (BrotliParams::Mode) -1; int quality = -1; int lgwin = -1; int lgblock = -1; int ok; static const char *kwlist[] = {"string", "mode", "quality", "lgwin", "lgblock", NULL}; ok = PyArg_ParseTupleAndKeywords(args, keywds, "s#|O&O&O&O&:compress", const_cast<char **>(kwlist), &input, &length, &mode_convertor, &mode, &quality_convertor, &quality, &lgwin_convertor, &lgwin, &lgblock_convertor, &lgblock); if (!ok) return NULL; output_length = 1.2 * length + 10240; output = new uint8_t[output_length]; BrotliParams params; if (mode != -1) params.mode = mode; if (quality != -1) params.quality = quality; if (lgwin != -1) params.lgwin = lgwin; if (lgblock != -1) params.lgblock = lgblock; ok = BrotliCompressBuffer(params, length, input, &output_length, output); if (ok) { ret = PyBytes_FromStringAndSize((char*)output, output_length); } else { PyErr_SetString(BrotliError, "BrotliCompressBuffer failed"); } delete[] output; return ret; } PyDoc_STRVAR(decompress__doc__, "Decompress a compressed byte string.\n" "\n" "Signature:\n" " decompress(string)\n" "\n" "Args:\n" " string (bytes): The compressed input data.\n" "\n" "Returns:\n" " The decompressed byte string.\n" "\n" "Raises:\n" " brotli.error: If decompressor fails.\n"); static PyObject* brotli_decompress(PyObject *self, PyObject *args) { PyObject *ret = NULL; uint8_t *input; size_t length; int ok; ok = PyArg_ParseTuple(args, "s#:decompress", &input, &length); if (!ok) return NULL; std::vector<uint8_t> output; const size_t kBufferSize = 65536; uint8_t* buffer = new uint8_t[kBufferSize]; BrotliState state; BrotliStateInit(&state); BrotliResult result = BROTLI_RESULT_NEEDS_MORE_OUTPUT; while (result == BROTLI_RESULT_NEEDS_MORE_OUTPUT) { size_t available_out = kBufferSize; uint8_t* next_out = buffer; size_t total_out = 0; result = BrotliDecompressStream(&length, &input, &available_out, &next_out, &total_out, &state); size_t used_out = kBufferSize - available_out; if (used_out != 0) output->insert(output->end(), buffer, buffer + used_out); } ok = result == BROTLI_RESULT_SUCCESS; if (ok) { ret = PyBytes_FromStringAndSize((char*)(output.size() ? &output[0] : NULL), output.size()); } else { PyErr_SetString(BrotliError, "BrotliDecompress failed"); } BrotliStateCleanup(&state); delete[] buffer; return ret; } static PyMethodDef brotli_methods[] = { {"compress", (PyCFunction)brotli_compress, METH_VARARGS | METH_KEYWORDS, compress__doc__}, {"decompress", brotli_decompress, METH_VARARGS, decompress__doc__}, {NULL, NULL, 0, NULL} }; PyDoc_STRVAR(brotli__doc__, "The functions in this module allow compression and decompression using the\n" "Brotli library.\n\n"); #if PY_MAJOR_VERSION >= 3 #define INIT_BROTLI PyInit_brotli #define CREATE_BROTLI PyModule_Create(&brotli_module) #define RETURN_BROTLI return m static struct PyModuleDef brotli_module = { PyModuleDef_HEAD_INIT, "brotli", brotli__doc__, 0, brotli_methods, NULL, NULL, NULL }; #else #define INIT_BROTLI initbrotli #define CREATE_BROTLI Py_InitModule3("brotli", brotli_methods, brotli__doc__) #define RETURN_BROTLI return #endif PyMODINIT_FUNC INIT_BROTLI(void) { PyObject *m = CREATE_BROTLI; BrotliError = PyErr_NewException((char*) "brotli.error", NULL, NULL); if (BrotliError != NULL) { Py_INCREF(BrotliError); PyModule_AddObject(m, "error", BrotliError); } PyModule_AddIntConstant(m, "MODE_GENERIC", (int) BrotliParams::MODE_GENERIC); PyModule_AddIntConstant(m, "MODE_TEXT", (int) BrotliParams::MODE_TEXT); PyModule_AddIntConstant(m, "MODE_FONT", (int) BrotliParams::MODE_FONT); PyModule_AddStringConstant(m, "__version__", BROTLI_VERSION); RETURN_BROTLI; } <commit_msg>Fix pointer dereferencing.<commit_after>#define PY_SSIZE_T_CLEAN 1 #include <Python.h> #include <bytesobject.h> #include "../enc/encode.h" #include "../dec/decode.h" #include "../tools/version.h" #if PY_MAJOR_VERSION >= 3 #define PyInt_Check PyLong_Check #define PyInt_AsLong PyLong_AsLong #endif using namespace brotli; static PyObject *BrotliError; static int mode_convertor(PyObject *o, BrotliParams::Mode *mode) { if (!PyInt_Check(o)) { PyErr_SetString(BrotliError, "Invalid mode"); return 0; } *mode = (BrotliParams::Mode) PyInt_AsLong(o); if (*mode != BrotliParams::MODE_GENERIC && *mode != BrotliParams::MODE_TEXT && *mode != BrotliParams::MODE_FONT) { PyErr_SetString(BrotliError, "Invalid mode"); return 0; } return 1; } static int quality_convertor(PyObject *o, int *quality) { if (!PyInt_Check(o)) { PyErr_SetString(BrotliError, "Invalid quality"); return 0; } *quality = PyInt_AsLong(o); if (*quality < 0 || *quality > 11) { PyErr_SetString(BrotliError, "Invalid quality. Range is 0 to 11."); return 0; } return 1; } static int lgwin_convertor(PyObject *o, int *lgwin) { if (!PyInt_Check(o)) { PyErr_SetString(BrotliError, "Invalid lgwin"); return 0; } *lgwin = PyInt_AsLong(o); if (*lgwin < 10 || *lgwin > 24) { PyErr_SetString(BrotliError, "Invalid lgwin. Range is 10 to 24."); return 0; } return 1; } static int lgblock_convertor(PyObject *o, int *lgblock) { if (!PyInt_Check(o)) { PyErr_SetString(BrotliError, "Invalid lgblock"); return 0; } *lgblock = PyInt_AsLong(o); if ((*lgblock != 0 && *lgblock < 16) || *lgblock > 24) { PyErr_SetString(BrotliError, "Invalid lgblock. Can be 0 or in range 16 to 24."); return 0; } return 1; } PyDoc_STRVAR(compress__doc__, "Compress a byte string.\n" "\n" "Signature:\n" " compress(string, mode=MODE_GENERIC, quality=11, lgwin=22, lgblock=0)\n" "\n" "Args:\n" " string (bytes): The input data.\n" " mode (int, optional): The compression mode can be MODE_GENERIC (default),\n" " MODE_TEXT (for UTF-8 format text input) or MODE_FONT (for WOFF 2.0). \n" " quality (int, optional): Controls the compression-speed vs compression-\n" " density tradeoff. The higher the quality, the slower the compression.\n" " Range is 0 to 11. Defaults to 11.\n" " lgwin (int, optional): Base 2 logarithm of the sliding window size. Range\n" " is 10 to 24. Defaults to 22.\n" " lgblock (int, optional): Base 2 logarithm of the maximum input block size.\n" " Range is 16 to 24. If set to 0, the value will be set based on the\n" " quality. Defaults to 0.\n" "\n" "Returns:\n" " The compressed byte string.\n" "\n" "Raises:\n" " brotli.error: If arguments are invalid, or compressor fails.\n"); static PyObject* brotli_compress(PyObject *self, PyObject *args, PyObject *keywds) { PyObject *ret = NULL; uint8_t *input, *output; size_t length, output_length; BrotliParams::Mode mode = (BrotliParams::Mode) -1; int quality = -1; int lgwin = -1; int lgblock = -1; int ok; static const char *kwlist[] = {"string", "mode", "quality", "lgwin", "lgblock", NULL}; ok = PyArg_ParseTupleAndKeywords(args, keywds, "s#|O&O&O&O&:compress", const_cast<char **>(kwlist), &input, &length, &mode_convertor, &mode, &quality_convertor, &quality, &lgwin_convertor, &lgwin, &lgblock_convertor, &lgblock); if (!ok) return NULL; output_length = 1.2 * length + 10240; output = new uint8_t[output_length]; BrotliParams params; if (mode != -1) params.mode = mode; if (quality != -1) params.quality = quality; if (lgwin != -1) params.lgwin = lgwin; if (lgblock != -1) params.lgblock = lgblock; ok = BrotliCompressBuffer(params, length, input, &output_length, output); if (ok) { ret = PyBytes_FromStringAndSize((char*)output, output_length); } else { PyErr_SetString(BrotliError, "BrotliCompressBuffer failed"); } delete[] output; return ret; } PyDoc_STRVAR(decompress__doc__, "Decompress a compressed byte string.\n" "\n" "Signature:\n" " decompress(string)\n" "\n" "Args:\n" " string (bytes): The compressed input data.\n" "\n" "Returns:\n" " The decompressed byte string.\n" "\n" "Raises:\n" " brotli.error: If decompressor fails.\n"); static PyObject* brotli_decompress(PyObject *self, PyObject *args) { PyObject *ret = NULL; uint8_t *input; size_t length; int ok; ok = PyArg_ParseTuple(args, "s#:decompress", &input, &length); if (!ok) return NULL; std::vector<uint8_t> output; const size_t kBufferSize = 65536; uint8_t* buffer = new uint8_t[kBufferSize]; BrotliState state; BrotliStateInit(&state); BrotliResult result = BROTLI_RESULT_NEEDS_MORE_OUTPUT; while (result == BROTLI_RESULT_NEEDS_MORE_OUTPUT) { size_t available_out = kBufferSize; uint8_t* next_out = buffer; size_t total_out = 0; result = BrotliDecompressStream(&length, &input, &available_out, &next_out, &total_out, &state); size_t used_out = kBufferSize - available_out; if (used_out != 0) output.insert(output.end(), buffer, buffer + used_out); } ok = result == BROTLI_RESULT_SUCCESS; if (ok) { ret = PyBytes_FromStringAndSize((char*)(output.size() ? &output[0] : NULL), output.size()); } else { PyErr_SetString(BrotliError, "BrotliDecompress failed"); } BrotliStateCleanup(&state); delete[] buffer; return ret; } static PyMethodDef brotli_methods[] = { {"compress", (PyCFunction)brotli_compress, METH_VARARGS | METH_KEYWORDS, compress__doc__}, {"decompress", brotli_decompress, METH_VARARGS, decompress__doc__}, {NULL, NULL, 0, NULL} }; PyDoc_STRVAR(brotli__doc__, "The functions in this module allow compression and decompression using the\n" "Brotli library.\n\n"); #if PY_MAJOR_VERSION >= 3 #define INIT_BROTLI PyInit_brotli #define CREATE_BROTLI PyModule_Create(&brotli_module) #define RETURN_BROTLI return m static struct PyModuleDef brotli_module = { PyModuleDef_HEAD_INIT, "brotli", brotli__doc__, 0, brotli_methods, NULL, NULL, NULL }; #else #define INIT_BROTLI initbrotli #define CREATE_BROTLI Py_InitModule3("brotli", brotli_methods, brotli__doc__) #define RETURN_BROTLI return #endif PyMODINIT_FUNC INIT_BROTLI(void) { PyObject *m = CREATE_BROTLI; BrotliError = PyErr_NewException((char*) "brotli.error", NULL, NULL); if (BrotliError != NULL) { Py_INCREF(BrotliError); PyModule_AddObject(m, "error", BrotliError); } PyModule_AddIntConstant(m, "MODE_GENERIC", (int) BrotliParams::MODE_GENERIC); PyModule_AddIntConstant(m, "MODE_TEXT", (int) BrotliParams::MODE_TEXT); PyModule_AddIntConstant(m, "MODE_FONT", (int) BrotliParams::MODE_FONT); PyModule_AddStringConstant(m, "__version__", BROTLI_VERSION); RETURN_BROTLI; } <|endoftext|>
<commit_before>#include <iostream> #include <string> #include <utility> #include "Bool.hh" #include "Number.hh" #include "String.hh" #include "Table.hh" using namespace py; using std::unique_ptr; //------------------------------------------------------------------------------ namespace { void tp_dealloc(Table* self) { self->~Table(); self->ob_type->tp_free(self); } int tp_init(Table* self, Tuple* args, Dict* kw_args) { // No arguments. static char const* arg_names[] = {nullptr}; Arg::ParseTupleAndKeywords(args, kw_args, "", (char**) arg_names); new(self) Table; self->table_ = unique_ptr<fixfmt::Table>(new fixfmt::Table()); return 0; } ref<Object> tp_call(Table* self, Tuple* args, Dict* kw_args) { static char const* arg_names[] = {"index", nullptr}; long index; Arg::ParseTupleAndKeywords(args, kw_args, "l", arg_names, &index); if (index < 0) throw Exception(PyExc_IndexError, "negative index"); if (index >= self->table_->get_length()) throw Exception(PyExc_IndexError, "index larger than length"); return Unicode::from((*self->table_)(index)); } Py_ssize_t sq_length(Table* table) { return table->table_->get_length(); } PySequenceMethods const tp_as_sequence = { (lenfunc) sq_length, // sq_length (binaryfunc) nullptr, // sq_concat (ssizeargfunc) nullptr, // sq_repeat (ssizeargfunc) nullptr, // sq_item (void*) nullptr, // was_sq_slice (ssizeobjargproc) nullptr, // sq_ass_item (void*) nullptr, // was_sq_ass_slice (objobjproc) nullptr, // sq_contains (binaryfunc) nullptr, // sq_inplace_concat (ssizeargfunc) nullptr, // sq_inplace_repeat }; ref<Object> add_string(Table* self, Tuple* args, Dict* kw_args) { static char const* arg_names[] = {"str", nullptr}; char* str; Arg::ParseTupleAndKeywords(args, kw_args, "s", arg_names, &str); self->table_->add_string(std::string(str)); return none_ref(); } /** * Template method for adding a column to the table. * * 'buf' is a 'bytes' object containing contiguous values of type 'TYPE', e.g. * 'int' or 'double'. 'PYFMT" is a Python object that wraps a formatter for * 'TYPE' values. */ template<typename TYPE, typename PYFMT> ref<Object> add_column(Table* self, Tuple* args, Dict* kw_args) { static char const* arg_names[] = {"buf", "format", nullptr}; PyObject* array; PYFMT* format; Arg::ParseTupleAndKeywords( args, kw_args, "OO!", arg_names, &array, &PYFMT::type_, &format); BufferRef buffer(array, PyBUF_CONTIG_RO); if (buffer->ndim != 1) throw Exception(PyExc_TypeError, "not a one-dimensional array"); if (buffer->itemsize != sizeof(TYPE)) throw Exception(PyExc_TypeError, "wrong itemsize"); using ColumnUptr = unique_ptr<fixfmt::Column>; using Column = fixfmt::ColumnImpl<TYPE, typename PYFMT::Formatter>; long const len = buffer->len / buffer->itemsize; self->table_->add_column( ColumnUptr(new Column((TYPE*) buffer->buf, len, *format->fmt_))); self->buffers_.emplace_back(std::move(buffer)); return none_ref(); } /** * Column of Python object pointers, with an object first converted with 'str()' * and then formatted as a string. */ class StrObjectColumn : public fixfmt::Column { public: StrObjectColumn(Object** values, long const length, fixfmt::String format) : values_(values), length_(length), format_(std::move(format)) { } virtual ~StrObjectColumn() override {} virtual int get_width() const override { return format_.get_width(); } virtual long get_length() const override { return length_; } virtual std::string operator()(long const index) const override { // Convert (or cast) to string. auto str = values_[index]->Str(); // Format the string. return format_(str->as_utf8_string()); } private: Object** const values_; long const length_; fixfmt::String const format_; }; ref<Object> add_str_object_column(Table* self, Tuple* args, Dict* kw_args) { static char const* arg_names[] = {"buf", "format", nullptr}; PyObject* array; String* format; Arg::ParseTupleAndKeywords( args, kw_args, "OO!", arg_names, &array, &String::type_, &format); BufferRef buffer(array, PyBUF_CONTIG_RO); if (buffer->ndim != 1) throw Exception(PyExc_TypeError, "not a one-dimensional array"); if (buffer->itemsize != sizeof(Object*)) throw Exception(PyExc_TypeError, "wrong itemsize"); using ColumnUptr = unique_ptr<fixfmt::Column>; long const len = buffer->len / buffer->itemsize; self->table_->add_column(ColumnUptr( new StrObjectColumn((Object**) buffer->buf, len, *format->fmt_))); self->buffers_.emplace_back(std::move(buffer)); return none_ref(); } auto methods = Methods<Table>() .add<add_string> ("add_string") .add<add_column<bool, Bool>> ("add_bool") .add<add_column<char, Number>> ("add_int8") .add<add_column<short, Number>> ("add_int16") .add<add_column<int, Number>> ("add_int32") .add<add_column<long, Number>> ("add_int64") .add<add_column<float, Number>> ("add_float32") .add<add_column<double, Number>> ("add_float64") .add<add_str_object_column> ("add_str_object") ; Object* get_length(Table* const self, void* /* closure */) { return Long::FromLong(self->table_->get_length()).release(); } Object* get_width(Table* const self, void* /* closure */) { return Long::FromLong(self->table_->get_width()).release(); } PyGetSetDef const tp_getset[] = { { (char*) "length", // name (getter) get_length, // get (setter) nullptr, // set (char*) nullptr, // doc (void*) nullptr, // closure }, { (char*) "width", // name (getter) get_width, // get (setter) nullptr, // set (char*) nullptr, // doc (void*) nullptr, // closure }, GETSETDEF_END }; } // anonymous namespace Type Table::type_ = PyTypeObject{ PyVarObject_HEAD_INIT(nullptr, 0) (char const*) "fixfmt.Table", // tp_name (Py_ssize_t) sizeof(Table), // tp_basicsize (Py_ssize_t) 0, // tp_itemsize (destructor) tp_dealloc, // tp_dealloc (printfunc) nullptr, // tp_print (getattrfunc) nullptr, // tp_getattr (setattrfunc) nullptr, // tp_setattr (void*) nullptr, // tp_reserved (reprfunc) nullptr, // tp_repr (PyNumberMethods*) nullptr, // tp_as_number (PySequenceMethods*) &tp_as_sequence, // tp_as_sequence (PyMappingMethods*) nullptr, // tp_as_mapping (hashfunc) nullptr, // tp_hash (ternaryfunc) wrap<Table, tp_call>, // tp_call (reprfunc) nullptr, // tp_str (getattrofunc) nullptr, // tp_getattro (setattrofunc) nullptr, // tp_setattro (PyBufferProcs*) nullptr, // tp_as_buffer (unsigned long) Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, // tp_flags (char const*) nullptr, // tp_doc (traverseproc) nullptr, // tp_traverse (inquiry) nullptr, // tp_clear (richcmpfunc) nullptr, // tp_richcompare (Py_ssize_t) 0, // tp_weaklistoffset (getiterfunc) nullptr, // tp_iter (iternextfunc) nullptr, // tp_iternext (PyMethodDef*) methods, // tp_methods (PyMemberDef*) nullptr, // tp_members (PyGetSetDef*) tp_getset, // tp_getset (_typeobject*) nullptr, // tp_base (PyObject*) nullptr, // tp_dict (descrgetfunc) nullptr, // tp_descr_get (descrsetfunc) nullptr, // tp_descr_set (Py_ssize_t) 0, // tp_dictoffset (initproc) tp_init, // tp_init (allocfunc) nullptr, // tp_alloc (newfunc) PyType_GenericNew, // tp_new (freefunc) nullptr, // tp_free (inquiry) nullptr, // tp_is_gc (PyObject*) nullptr, // tp_bases (PyObject*) nullptr, // tp_mro (PyObject*) nullptr, // tp_cache (PyObject*) nullptr, // tp_subclasses (PyObject*) nullptr, // tp_weaklist (destructor) nullptr, // tp_del (unsigned int) 0, // tp_version_tag (destructor) nullptr, // tp_finalize }; <commit_msg>Cleanups.<commit_after>#include <iostream> #include <string> #include <utility> #include "Bool.hh" #include "Number.hh" #include "String.hh" #include "Table.hh" using namespace py; using std::unique_ptr; //------------------------------------------------------------------------------ namespace { void tp_dealloc(Table* self) { self->~Table(); self->ob_type->tp_free(self); } int tp_init(Table* self, Tuple* args, Dict* kw_args) { // No arguments. static char const* arg_names[] = {nullptr}; Arg::ParseTupleAndKeywords(args, kw_args, "", (char**) arg_names); new(self) Table; self->table_ = unique_ptr<fixfmt::Table>(new fixfmt::Table()); return 0; } ref<Object> tp_call(Table* self, Tuple* args, Dict* kw_args) { static char const* arg_names[] = {"index", nullptr}; long index; Arg::ParseTupleAndKeywords(args, kw_args, "l", arg_names, &index); if (index < 0) throw Exception(PyExc_IndexError, "negative index"); if (index >= self->table_->get_length()) throw Exception(PyExc_IndexError, "index larger than length"); return Unicode::from((*self->table_)(index)); } Py_ssize_t sq_length(Table* table) { return table->table_->get_length(); } PySequenceMethods const tp_as_sequence = { (lenfunc) sq_length, // sq_length (binaryfunc) nullptr, // sq_concat (ssizeargfunc) nullptr, // sq_repeat (ssizeargfunc) nullptr, // sq_item (void*) nullptr, // was_sq_slice (ssizeobjargproc) nullptr, // sq_ass_item (void*) nullptr, // was_sq_ass_slice (objobjproc) nullptr, // sq_contains (binaryfunc) nullptr, // sq_inplace_concat (ssizeargfunc) nullptr, // sq_inplace_repeat }; ref<Object> add_string(Table* self, Tuple* args, Dict* kw_args) { static char const* arg_names[] = {"str", nullptr}; char* str; Arg::ParseTupleAndKeywords(args, kw_args, "s", arg_names, &str); self->table_->add_string(std::string(str)); return none_ref(); } /** * Template method for adding a column to the table. * * 'buf' is a 'bytes' object containing contiguous values of type 'TYPE', e.g. * 'int' or 'double'. 'PYFMT' is a Python object that wraps a formatter for * 'TYPE' values. */ template<typename TYPE, typename PYFMT> ref<Object> add_column(Table* self, Tuple* args, Dict* kw_args) { // Parse args. static char const* arg_names[] = {"buf", "format", nullptr}; PyObject* array; PYFMT* format; Arg::ParseTupleAndKeywords( args, kw_args, "OO!", arg_names, &array, &PYFMT::type_, &format); // Validate args. BufferRef buffer(array, PyBUF_ND); if (buffer->ndim != 1) throw Exception(PyExc_TypeError, "not a one-dimensional array"); if (buffer->itemsize != sizeof(TYPE)) throw Exception(PyExc_TypeError, "wrong itemsize"); // Add the column. using Column = fixfmt::ColumnImpl<TYPE, typename PYFMT::Formatter>; self->table_->add_column(std::make_unique<Column>( reinterpret_cast<TYPE*>(buffer->buf), buffer->shape[0], *format->fmt_)); // Hold on to the buffer ref. self->buffers_.push_back(std::move(buffer)); return none_ref(); } /** * Column of Python object pointers, with an object first converted with 'str()' * and then formatted as a string. */ class StrObjectColumn : public fixfmt::Column { public: StrObjectColumn(Object** values, long const length, fixfmt::String format) : values_(values), length_(length), format_(std::move(format)) { } virtual ~StrObjectColumn() override {} virtual int get_width() const override { return format_.get_width(); } virtual long get_length() const override { return length_; } virtual std::string operator()(long const index) const override { // Convert (or cast) to string. auto str = values_[index]->Str(); // Format the string. return format_(str->as_utf8_string()); } private: Object** const values_; long const length_; fixfmt::String const format_; }; ref<Object> add_str_object_column(Table* self, Tuple* args, Dict* kw_args) { // Parse args. static char const* arg_names[] = {"buf", "format", nullptr}; PyObject* array; String* format; Arg::ParseTupleAndKeywords( args, kw_args, "OO!", arg_names, &array, &String::type_, &format); // Validate args. BufferRef buffer(array, PyBUF_ND); if (buffer->ndim != 1) throw Exception(PyExc_TypeError, "not a one-dimensional array"); if (buffer->itemsize != sizeof(Object*)) throw Exception(PyExc_TypeError, "wrong itemsize"); // Add the column. self->table_->add_column(std::make_unique<StrObjectColumn>( reinterpret_cast<Object**>(buffer->buf), buffer->shape[0], *format->fmt_)); // Hold on to the buffer ref. self->buffers_.emplace_back(std::move(buffer)); return none_ref(); } auto methods = Methods<Table>() .add<add_string> ("add_string") .add<add_column<bool, Bool>> ("add_bool") .add<add_column<char, Number>> ("add_int8") .add<add_column<short, Number>> ("add_int16") .add<add_column<int, Number>> ("add_int32") .add<add_column<long, Number>> ("add_int64") .add<add_column<float, Number>> ("add_float32") .add<add_column<double, Number>> ("add_float64") .add<add_str_object_column> ("add_str_object") ; Object* get_length(Table* const self, void* /* closure */) { return Long::FromLong(self->table_->get_length()).release(); } Object* get_width(Table* const self, void* /* closure */) { return Long::FromLong(self->table_->get_width()).release(); } PyGetSetDef const tp_getset[] = { { (char*) "length", // name (getter) get_length, // get (setter) nullptr, // set (char*) nullptr, // doc (void*) nullptr, // closure }, { (char*) "width", // name (getter) get_width, // get (setter) nullptr, // set (char*) nullptr, // doc (void*) nullptr, // closure }, GETSETDEF_END }; } // anonymous namespace Type Table::type_ = PyTypeObject{ PyVarObject_HEAD_INIT(nullptr, 0) (char const*) "fixfmt.Table", // tp_name (Py_ssize_t) sizeof(Table), // tp_basicsize (Py_ssize_t) 0, // tp_itemsize (destructor) tp_dealloc, // tp_dealloc (printfunc) nullptr, // tp_print (getattrfunc) nullptr, // tp_getattr (setattrfunc) nullptr, // tp_setattr (void*) nullptr, // tp_reserved (reprfunc) nullptr, // tp_repr (PyNumberMethods*) nullptr, // tp_as_number (PySequenceMethods*) &tp_as_sequence, // tp_as_sequence (PyMappingMethods*) nullptr, // tp_as_mapping (hashfunc) nullptr, // tp_hash (ternaryfunc) wrap<Table, tp_call>, // tp_call (reprfunc) nullptr, // tp_str (getattrofunc) nullptr, // tp_getattro (setattrofunc) nullptr, // tp_setattro (PyBufferProcs*) nullptr, // tp_as_buffer (unsigned long) Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, // tp_flags (char const*) nullptr, // tp_doc (traverseproc) nullptr, // tp_traverse (inquiry) nullptr, // tp_clear (richcmpfunc) nullptr, // tp_richcompare (Py_ssize_t) 0, // tp_weaklistoffset (getiterfunc) nullptr, // tp_iter (iternextfunc) nullptr, // tp_iternext (PyMethodDef*) methods, // tp_methods (PyMemberDef*) nullptr, // tp_members (PyGetSetDef*) tp_getset, // tp_getset (_typeobject*) nullptr, // tp_base (PyObject*) nullptr, // tp_dict (descrgetfunc) nullptr, // tp_descr_get (descrsetfunc) nullptr, // tp_descr_set (Py_ssize_t) 0, // tp_dictoffset (initproc) tp_init, // tp_init (allocfunc) nullptr, // tp_alloc (newfunc) PyType_GenericNew, // tp_new (freefunc) nullptr, // tp_free (inquiry) nullptr, // tp_is_gc (PyObject*) nullptr, // tp_bases (PyObject*) nullptr, // tp_mro (PyObject*) nullptr, // tp_cache (PyObject*) nullptr, // tp_subclasses (PyObject*) nullptr, // tp_weaklist (destructor) nullptr, // tp_del (unsigned int) 0, // tp_version_tag (destructor) nullptr, // tp_finalize }; <|endoftext|>
<commit_before>#include "CppUTest/TestHarness.h" #include <string> #include "vrp.h" TEST_GROUP(ReadVrpFile) { }; TEST(ReadVrpFile, name) { Vrp vrp("Vrp-All/E/E-n13-k4.vrp"); std::string name = vrp.name(); CHECK_EQUAL("E-n13-k4", name); } TEST(ReadVrpFile, demension) { Vrp vrp("Vrp-All/E/E-n13-k4.vrp"); LONGS_EQUAL(13, vrp.demension()); } TEST(ReadVrpFile, edge_weight_type) { Vrp vrp("Vrp-All/E/E-n13-k4.vrp"); CHECK_EQUAL("EXPLICIT", vrp.edge_weight_type()); } <commit_msg>コンストラクトをsetupにまとめた<commit_after>#include "CppUTest/TestHarness.h" #include <string> #include "vrp.h" TEST_GROUP(ReadVrpFile) { Vrp *vrp; void setup(void) { vrp = new Vrp("Vrp-All/E/E-n13-k4.vrp"); } void teardown(void) { delete vrp; } }; TEST(ReadVrpFile, name) { std::string name = vrp->name(); CHECK_EQUAL("E-n13-k4", name); } TEST(ReadVrpFile, demension) { LONGS_EQUAL(13, vrp->demension()); } TEST(ReadVrpFile, edge_weight_type) { CHECK_EQUAL("EXPLICIT", vrp->edge_weight_type()); } <|endoftext|>
<commit_before>int MdApi::queryAllTickers(int exchange_id) { XTP_EXCHANGE_TYPE myreq = XTP_EXCHANGE_TYPE(); memset(&myreq, 0, sizeof(myreq)); int i = this->api->QueryAllTickers(&myreq, (XTP_EXCHANGE_TYPE) exchange_id); return i; }; int MdApi::queryTickersPriceInfo(char ticker, int count, int exchange_id) { char myreq = char(); memset(&myreq, 0, sizeof(myreq)); int i = this->api->QueryTickersPriceInfo(&myreq, (XTP_EXCHANGE_TYPE) exchange_id); return i; }; int MdApi::queryAllTickersPriceInfo() { char myreq = char(); memset(&myreq, 0, sizeof(myreq)); int i = this->api->QueryAllTickersPriceInfo(&myreq, (XTP_EXCHANGE_TYPE) exchange_id); return i; }; <commit_msg>Update xtp_md_source_function.cpp<commit_after>int MdApi::queryAllTickers(int exchange_id) { XTP_EXCHANGE_TYPE myreq = XTP_EXCHANGE_TYPE(); memset(&myreq, 0, sizeof(myreq)); int i = this->api->QueryAllTickers(&myreq, (XTP_EXCHANGE_TYPE) exchange_id); return i; }; int MdApi::queryTickersPriceInfo(string ticker, int count, int exchange_id) { char myreq = char(); memset(&myreq, 0, sizeof(myreq)); int i = this->api->QueryTickersPriceInfo(&myreq, reqid); return i; }; int MdApi::queryAllTickersPriceInfo() { char myreq = char(); memset(&myreq, 0, sizeof(myreq)); int i = this->api->QueryAllTickersPriceInfo(&myreq, reqid); return i; }; <|endoftext|>
<commit_before>//============================================================================ // Name : main.cpp // Author : 熊子良 // Version : //============================================================================ #include <signal.h> #include <unistd.h> #include <iostream> #include "Rtsp/UDPServer.h" #include "Rtsp/RtspSession.h" #include "Rtmp/RtmpSession.h" #include "Http/HttpSession.h" #ifdef ENABLE_OPENSSL #include "Util/SSLBox.h" #include "Http/HttpsSession.h" #endif//ENABLE_OPENSSL #include "Util/logger.h" #include "Util/onceToken.h" #include "Util/File.h" #include "Network/TcpServer.h" #include "Poller/EventPoller.h" #include "Thread/WorkThreadPool.h" #include "Device/PlayerProxy.h" #include "Shell/ShellSession.h" #include <map> using namespace std; using namespace ZL::Util; using namespace ZL::Http; using namespace ZL::Rtsp; using namespace ZL::Rtmp; using namespace ZL::Shell; using namespace ZL::Thread; using namespace ZL::Network; using namespace ZL::DEV; void programExit(int arg) { EventPoller::Instance().shutdown(); } int main(int argc,char *argv[]){ signal(SIGINT, programExit); Logger::Instance().add(std::make_shared<ConsoleChannel>("stdout", LTrace)); //support rtmp and rtsp url //just support H264+AAC auto urlList = {"rtmp://live.hkstv.hk.lxdns.com/live/hks", "rtsp://184.72.239.149/vod/mp4://BigBuckBunny_175k.mov"}; map<string , PlayerProxy::Ptr> proxyMap; int i=0; for(auto url : urlList){ //PlayerProxy构造函数前两个参数分别为应用名(app),流id(streamId) //比如说应用为live,流id为0,那么直播地址为: //http://127.0.0.1/live/0/hls.m3u8 //rtsp://127.0.0.1/live/0 //rtmp://127.0.0.1/live/0 //录像地址为: //http://127.0.0.1/record/live/0/2017-04-11/11-09-38.mp4 //rtsp://127.0.0.1/record/live/0/2017-04-11/11-09-38.mp4 //rtmp://127.0.0.1/record/live/0/2017-04-11/11-09-38.mp4 PlayerProxy::Ptr player(new PlayerProxy("live",std::to_string(i++).data())); player->play(url); proxyMap.emplace(string(url),player); } #ifdef ENABLE_OPENSSL //请把证书"test_server.pem"放置在本程序可执行程序同目录下 try{ SSL_Initor::Instance().loadServerPem((exePath() + ".pem").data()); }catch(...){ FatalL << "请把证书:" << (exeName() + ".pem") << "放置在本程序可执行程序同目录下:" << exeDir() << endl; return 0; } #endif //ENABLE_OPENSSL TcpServer<RtspSession>::Ptr rtspSrv(new TcpServer<RtspSession>()); TcpServer<RtmpSession>::Ptr rtmpSrv(new TcpServer<RtmpSession>()); TcpServer<HttpSession>::Ptr httpSrv(new TcpServer<HttpSession>()); TcpServer<ShellSession>::Ptr shellSrv(new TcpServer<ShellSession>()); rtspSrv->start(mINI::Instance()[Config::Rtsp::kPort]); rtmpSrv->start(mINI::Instance()[Config::Rtmp::kPort]); httpSrv->start(mINI::Instance()[Config::Http::kPort]); //简单的telnet服务器,可用于服务器调试,但是不能使用23端口 //测试方法:telnet 127.0.0.1 8023 //输入用户名和密码登录(user:test,pwd:123456),输入help命令查看帮助 ShellSession::addUser("test","123456"); shellSrv->start(8023); #ifdef ENABLE_OPENSSL TcpServer<HttpsSession>::Ptr httpsSrv(new TcpServer<HttpsSession>()); httpsSrv->start(mINI::Instance()[Config::Http::kSSLPort]); #endif //ENABLE_OPENSSL EventPoller::Instance().runLoop(); proxyMap.clear(); rtspSrv.reset(); rtmpSrv.reset(); httpSrv.reset(); shellSrv.reset(); #ifdef ENABLE_OPENSSL httpsSrv.reset(); #endif //ENABLE_OPENSSL UDPServer::Destory(); WorkThreadPool::Destory(); EventPoller::Destory(); Logger::Destory(); return 0; } <commit_msg>添加读写配置文件<commit_after>//============================================================================ // Name : main.cpp // Author : 熊子良 // Version : //============================================================================ #include <signal.h> #include <unistd.h> #include <iostream> #include "Rtsp/UDPServer.h" #include "Rtsp/RtspSession.h" #include "Rtmp/RtmpSession.h" #include "Http/HttpSession.h" #ifdef ENABLE_OPENSSL #include "Util/SSLBox.h" #include "Http/HttpsSession.h" #endif//ENABLE_OPENSSL #include "Util/logger.h" #include "Util/onceToken.h" #include "Util/File.h" #include "Network/TcpServer.h" #include "Poller/EventPoller.h" #include "Thread/WorkThreadPool.h" #include "Device/PlayerProxy.h" #include "Shell/ShellSession.h" #include "Common/config.h" #include <map> using namespace std; using namespace ZL::Util; using namespace ZL::Http; using namespace ZL::Rtsp; using namespace ZL::Rtmp; using namespace ZL::Shell; using namespace ZL::Thread; using namespace ZL::Network; using namespace ZL::DEV; void programExit(int arg) { EventPoller::Instance().shutdown(); } int main(int argc,char *argv[]){ signal(SIGINT, programExit); Logger::Instance().add(std::make_shared<ConsoleChannel>("stdout", LTrace)); Config::loaIniConfig(); //support rtmp and rtsp url //just support H264+AAC auto urlList = {"rtmp://live.hkstv.hk.lxdns.com/live/hks", "rtsp://184.72.239.149/vod/mp4://BigBuckBunny_175k.mov"}; map<string , PlayerProxy::Ptr> proxyMap; int i=0; for(auto url : urlList){ //PlayerProxy构造函数前两个参数分别为应用名(app),流id(streamId) //比如说应用为live,流id为0,那么直播地址为: //http://127.0.0.1/live/0/hls.m3u8 //rtsp://127.0.0.1/live/0 //rtmp://127.0.0.1/live/0 //录像地址为: //http://127.0.0.1/record/live/0/2017-04-11/11-09-38.mp4 //rtsp://127.0.0.1/record/live/0/2017-04-11/11-09-38.mp4 //rtmp://127.0.0.1/record/live/0/2017-04-11/11-09-38.mp4 PlayerProxy::Ptr player(new PlayerProxy("live",std::to_string(i++).data())); player->play(url); proxyMap.emplace(string(url),player); } #ifdef ENABLE_OPENSSL //请把证书"test_server.pem"放置在本程序可执行程序同目录下 try{ SSL_Initor::Instance().loadServerPem((exePath() + ".pem").data()); }catch(...){ FatalL << "请把证书:" << (exeName() + ".pem") << "放置在本程序可执行程序同目录下:" << exeDir() << endl; return 0; } #endif //ENABLE_OPENSSL TcpServer<RtspSession>::Ptr rtspSrv(new TcpServer<RtspSession>()); TcpServer<RtmpSession>::Ptr rtmpSrv(new TcpServer<RtmpSession>()); TcpServer<HttpSession>::Ptr httpSrv(new TcpServer<HttpSession>()); TcpServer<ShellSession>::Ptr shellSrv(new TcpServer<ShellSession>()); rtspSrv->start(mINI::Instance()[Config::Rtsp::kPort]); rtmpSrv->start(mINI::Instance()[Config::Rtmp::kPort]); httpSrv->start(mINI::Instance()[Config::Http::kPort]); //简单的telnet服务器,可用于服务器调试,但是不能使用23端口 //测试方法:telnet 127.0.0.1 8023 //输入用户名和密码登录(user:test,pwd:123456),输入help命令查看帮助 ShellSession::addUser("test","123456"); shellSrv->start(8023); #ifdef ENABLE_OPENSSL TcpServer<HttpsSession>::Ptr httpsSrv(new TcpServer<HttpsSession>()); httpsSrv->start(mINI::Instance()[Config::Http::kSSLPort]); #endif //ENABLE_OPENSSL EventPoller::Instance().runLoop(); proxyMap.clear(); rtspSrv.reset(); rtmpSrv.reset(); httpSrv.reset(); shellSrv.reset(); #ifdef ENABLE_OPENSSL httpsSrv.reset(); #endif //ENABLE_OPENSSL UDPServer::Destory(); WorkThreadPool::Destory(); EventPoller::Destory(); Logger::Destory(); return 0; } <|endoftext|>
<commit_before>/* * Copyright 2012 Matthew McCormick * * 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 <cstring> #include <ostream> #include <sstream> #include <string> #include <cstdlib> // EXIT_SUCCESS // Tmux color lookup tables for the different metrics. #include "luts.h" #if defined(__APPLE__) && defined(__MACH__) // Apple osx system #include "osx/cpu.h" #include "osx/memory.h" #include "osx/load.h" #elif defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) // BSD system // TODO: Includes and *BSD support #define BSD_BASED 1 // include _get_cpu_percentage (see osx/cpu.cc) // include cpu_percentage (see osx/cpu.cc) #else // assume linux system #include "linux/cpu.h" #include "linux/memory.h" #include "linux/load.h" #endif #include "graph.h" // Function declarations. // TODO: those should stay in separate headers // LINUX: DONE/partial // OSX: DONE/partial // BSD: TODO std::string cpu_string( unsigned int cpu_usage_delay, unsigned int graph_lines, bool use_colors = false ) { float percentage; //output stuff std::ostringstream oss; oss.precision( 1 ); oss.setf( std::ios::fixed | std::ios::right ); // get % percentage = cpu_percentage( cpu_usage_delay ); if( use_colors ) oss << cpu_percentage_lut[static_cast<unsigned int>( percentage )]; oss << "["; oss << getGraphByPercentage( unsigned(percentage), graph_lines ); oss << "]"; oss.width( 5 ); oss << percentage; oss << "%"; if( use_colors ) oss << "#[fg=default,bg=default]"; return oss.str(); } int main(int argc, char** argv) { unsigned int cpu_usage_delay = 900000; int graph_lines = 10; bool use_colors = false; try { std::istringstream iss; iss.exceptions ( std::ifstream::failbit | std::ifstream::badbit ); std::string current_arg; unsigned int arg_index = 1; if( argc > arg_index ) { if( strcmp( argv[arg_index], "--colors" ) == 0 ) { use_colors = true; ++arg_index; } } if( argc > arg_index ) { iss.str( argv[arg_index] ); int status_interval; iss >> status_interval; if( status_interval < 1 ) { std::cerr << "Status interval argument must be one or greater." << std::endl; return EXIT_FAILURE; } cpu_usage_delay = status_interval * 1000000 - 100000; ++arg_index; } if( argc > arg_index ) { iss.str( argv[arg_index] ); iss.clear(); iss >> graph_lines; if( graph_lines < 1 ) { std::cerr << "Graph lines argument must be one or greater." << std::endl; return EXIT_FAILURE; } } } catch(const std::exception &e) { std::cerr << "Usage: " << argv[0] << " [--colors] [tmux_status-interval(seconds)] [graph lines]" << std::endl; return EXIT_FAILURE; } std::cout << mem_string( use_colors ) << ' ' << cpu_string( cpu_usage_delay, graph_lines, use_colors ) << ' ' << load_string( use_colors ); return EXIT_SUCCESS; } <commit_msg>restore headers<commit_after>/* * Copyright 2012 Matthew McCormick * * 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 <cstring> #include <iostream> #include <fstream> #include <sstream> #include <string> #include <cstdlib> // EXIT_SUCCESS // Tmux color lookup tables for the different metrics. #include "luts.h" #if defined(__APPLE__) && defined(__MACH__) // Apple osx system #include "osx/cpu.h" #include "osx/memory.h" #include "osx/load.h" #elif defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) // BSD system // TODO: Includes and *BSD support #define BSD_BASED 1 // include _get_cpu_percentage (see osx/cpu.cc) // include cpu_percentage (see osx/cpu.cc) #else // assume linux system #include "linux/cpu.h" #include "linux/memory.h" #include "linux/load.h" #endif #include "graph.h" // Function declarations. // TODO: those should stay in separate headers // LINUX: DONE/partial // OSX: DONE/partial // BSD: TODO std::string cpu_string( unsigned int cpu_usage_delay, unsigned int graph_lines, bool use_colors = false ) { float percentage; //output stuff std::ostringstream oss; oss.precision( 1 ); oss.setf( std::ios::fixed | std::ios::right ); // get % percentage = cpu_percentage( cpu_usage_delay ); if( use_colors ) oss << cpu_percentage_lut[static_cast<unsigned int>( percentage )]; oss << "["; oss << getGraphByPercentage( unsigned(percentage), graph_lines ); oss << "]"; oss.width( 5 ); oss << percentage; oss << "%"; if( use_colors ) oss << "#[fg=default,bg=default]"; return oss.str(); } int main(int argc, char** argv) { unsigned int cpu_usage_delay = 900000; int graph_lines = 10; bool use_colors = false; try { std::istringstream iss; iss.exceptions ( std::ifstream::failbit | std::ifstream::badbit ); std::string current_arg; unsigned int arg_index = 1; if( argc > arg_index ) { if( strcmp( argv[arg_index], "--colors" ) == 0 ) { use_colors = true; ++arg_index; } } if( argc > arg_index ) { iss.str( argv[arg_index] ); int status_interval; iss >> status_interval; if( status_interval < 1 ) { std::cerr << "Status interval argument must be one or greater." << std::endl; return EXIT_FAILURE; } cpu_usage_delay = status_interval * 1000000 - 100000; ++arg_index; } if( argc > arg_index ) { iss.str( argv[arg_index] ); iss.clear(); iss >> graph_lines; if( graph_lines < 1 ) { std::cerr << "Graph lines argument must be one or greater." << std::endl; return EXIT_FAILURE; } } } catch(const std::exception &e) { std::cerr << "Usage: " << argv[0] << " [--colors] [tmux_status-interval(seconds)] [graph lines]" << std::endl; return EXIT_FAILURE; } std::cout << mem_string( use_colors ) << ' ' << cpu_string( cpu_usage_delay, graph_lines, use_colors ) << ' ' << load_string( use_colors ); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>// Copyright (c) 2017 Franka Emika GmbH // Use of this source code is governed by the Apache-2.0 license, see LICENSE #include <algorithm> #include <atomic> #include <chrono> #include <thread> #include <actionlib/server/simple_action_server.h> #include <controller_manager/controller_manager.h> #include <franka/exception.h> #include <franka/robot.h> #include <franka_hw/franka_hw.h> #include <franka_hw/services.h> #include <franka_msgs/ErrorRecoveryAction.h> #include <ros/ros.h> #include <std_srvs/Trigger.h> using franka_hw::ServiceContainer; using namespace std::chrono_literals; int main(int argc, char** argv) { ros::init(argc, argv, "franka_control_node"); ros::NodeHandle public_node_handle; ros::NodeHandle node_handle("~"); franka_hw::FrankaHW franka_control; if (!franka_control.init(public_node_handle, node_handle)) { ROS_ERROR("franka_control_node: Failed to initialize FrankaHW class. Shutting down!"); return 1; } auto services = std::make_unique<ServiceContainer>(); std::unique_ptr<actionlib::SimpleActionServer<franka_msgs::ErrorRecoveryAction>> recovery_action_server; std::atomic_bool has_error(false); auto connect = [&]() { franka_control.connect(); std::lock_guard<std::mutex> lock(franka_control.robotMutex()); auto& robot = franka_control.robot(); services = std::make_unique<ServiceContainer>(); franka_hw::setupServices(robot, franka_control.robotMutex(), node_handle, *services); recovery_action_server = std::make_unique<actionlib::SimpleActionServer<franka_msgs::ErrorRecoveryAction>>( node_handle, "error_recovery", [&](const franka_msgs::ErrorRecoveryGoalConstPtr&) { try { std::lock_guard<std::mutex> lock(franka_control.robotMutex()); robot.automaticErrorRecovery(); has_error = false; recovery_action_server->setSucceeded(); ROS_INFO("Recovered from error"); } catch (const franka::Exception& ex) { recovery_action_server->setAborted(franka_msgs::ErrorRecoveryResult(), ex.what()); } }, false); recovery_action_server->start(); // Initialize robot state before loading any controller franka_control.update(robot.readOnce()); }; auto disconnectHandler = [&](std_srvs::Trigger::Request& request, std_srvs::Trigger::Response& response) -> bool { if (franka_control.controllerActive()) { response.success = 0u; response.message = "Controller is active. Cannont disconnect while a controller is running."; return true; } services.reset(); recovery_action_server.reset(); auto result = franka_control.disconnect(); response.success = result ? 1u : 0u; response.message = result ? "" : "Failed to disconnect robot."; return true; }; auto connectHandler = [&](std_srvs::Trigger::Request& request, std_srvs::Trigger::Response& response) -> bool { if (franka_control.connected()) { response.success = 0u; response.message = "Already connected to robot. Cannot connect twice."; return true; } connect(); response.success = 1u; response.message = ""; return true; }; connect(); ros::ServiceServer connect_server = node_handle.advertiseService<std_srvs::Trigger::Request, std_srvs::Trigger::Response>( "connect", connectHandler); ros::ServiceServer disconnect_server = node_handle.advertiseService<std_srvs::Trigger::Request, std_srvs::Trigger::Response>( "disconnect", disconnectHandler); controller_manager::ControllerManager control_manager(&franka_control, public_node_handle); // Start background threads for message handling ros::AsyncSpinner spinner(4); spinner.start(); while (ros::ok()) { ros::Time last_time = ros::Time::now(); // Wait until controller has been activated or error has been recovered while (!franka_control.controllerActive() || has_error) { if (franka_control.connected()) { try { std::lock_guard<std::mutex> lock(franka_control.robotMutex()); franka_control.update(franka_control.robot().readOnce()); ros::Time now = ros::Time::now(); control_manager.update(now, now - last_time); franka_control.checkJointLimits(); last_time = now; } catch (const std::logic_error& e) { } } else { std::this_thread::sleep_for(1ms); } if (!ros::ok()) { return 0; } } if (franka_control.connected()) { try { // Run control loop. Will exit if the controller is switched. franka_control.control([&](const ros::Time& now, const ros::Duration& period) { if (period.toSec() == 0.0) { // Reset controllers before starting a motion control_manager.update(now, period, true); franka_control.checkJointLimits(); franka_control.reset(); } else { control_manager.update(now, period); franka_control.checkJointLimits(); franka_control.enforceLimits(period); } return ros::ok(); }); } catch (const franka::ControlException& e) { ROS_ERROR("%s", e.what()); has_error = true; } } ROS_INFO_THROTTLE(1, "franka_control, main loop"); } return 0; } <commit_msg>format fix<commit_after>// Copyright (c) 2017 Franka Emika GmbH // Use of this source code is governed by the Apache-2.0 license, see LICENSE #include <algorithm> #include <atomic> #include <chrono> #include <thread> #include <actionlib/server/simple_action_server.h> #include <controller_manager/controller_manager.h> #include <franka/exception.h> #include <franka/robot.h> #include <franka_hw/franka_hw.h> #include <franka_hw/services.h> #include <franka_msgs/ErrorRecoveryAction.h> #include <ros/ros.h> #include <std_srvs/Trigger.h> using franka_hw::ServiceContainer; using namespace std::chrono_literals; int main(int argc, char** argv) { ros::init(argc, argv, "franka_control_node"); ros::NodeHandle public_node_handle; ros::NodeHandle node_handle("~"); franka_hw::FrankaHW franka_control; if (!franka_control.init(public_node_handle, node_handle)) { ROS_ERROR("franka_control_node: Failed to initialize FrankaHW class. Shutting down!"); return 1; } auto services = std::make_unique<ServiceContainer>(); std::unique_ptr<actionlib::SimpleActionServer<franka_msgs::ErrorRecoveryAction>> recovery_action_server; std::atomic_bool has_error(false); auto connect = [&]() { franka_control.connect(); std::lock_guard<std::mutex> lock(franka_control.robotMutex()); auto& robot = franka_control.robot(); services = std::make_unique<ServiceContainer>(); franka_hw::setupServices(robot, franka_control.robotMutex(), node_handle, *services); recovery_action_server = std::make_unique<actionlib::SimpleActionServer<franka_msgs::ErrorRecoveryAction>>( node_handle, "error_recovery", [&](const franka_msgs::ErrorRecoveryGoalConstPtr&) { try { std::lock_guard<std::mutex> lock(franka_control.robotMutex()); robot.automaticErrorRecovery(); has_error = false; recovery_action_server->setSucceeded(); ROS_INFO("Recovered from error"); } catch (const franka::Exception& ex) { recovery_action_server->setAborted(franka_msgs::ErrorRecoveryResult(), ex.what()); } }, false); recovery_action_server->start(); // Initialize robot state before loading any controller franka_control.update(robot.readOnce()); }; auto disconnectHandler = [&](std_srvs::Trigger::Request& request, std_srvs::Trigger::Response& response) -> bool { if (franka_control.controllerActive()) { response.success = 0u; response.message = "Controller is active. Cannont disconnect while a controller is running."; return true; } services.reset(); recovery_action_server.reset(); auto result = franka_control.disconnect(); response.success = result ? 1u : 0u; response.message = result ? "" : "Failed to disconnect robot."; return true; }; auto connectHandler = [&](std_srvs::Trigger::Request& request, std_srvs::Trigger::Response& response) -> bool { if (franka_control.connected()) { response.success = 0u; response.message = "Already connected to robot. Cannot connect twice."; return true; } connect(); response.success = 1u; response.message = ""; return true; }; connect(); ros::ServiceServer connect_server = node_handle.advertiseService<std_srvs::Trigger::Request, std_srvs::Trigger::Response>( "connect", connectHandler); ros::ServiceServer disconnect_server = node_handle.advertiseService<std_srvs::Trigger::Request, std_srvs::Trigger::Response>( "disconnect", disconnectHandler); controller_manager::ControllerManager control_manager(&franka_control, public_node_handle); // Start background threads for message handling ros::AsyncSpinner spinner(4); spinner.start(); while (ros::ok()) { ros::Time last_time = ros::Time::now(); // Wait until controller has been activated or error has been recovered while (!franka_control.controllerActive() || has_error) { if (franka_control.connected()) { try { std::lock_guard<std::mutex> lock(franka_control.robotMutex()); franka_control.update(franka_control.robot().readOnce()); ros::Time now = ros::Time::now(); control_manager.update(now, now - last_time); franka_control.checkJointLimits(); last_time = now; } catch (const std::logic_error& e) { } } else { std::this_thread::sleep_for(1ms); } if (!ros::ok()) { return 0; } } if (franka_control.connected()) { try { // Run control loop. Will exit if the controller is switched. franka_control.control([&](const ros::Time& now, const ros::Duration& period) { if (period.toSec() == 0.0) { // Reset controllers before starting a motion control_manager.update(now, period, true); franka_control.checkJointLimits(); franka_control.reset(); } else { control_manager.update(now, period); franka_control.checkJointLimits(); franka_control.enforceLimits(period); } return ros::ok(); }); } catch (const franka::ControlException& e) { ROS_ERROR("%s", e.what()); has_error = true; } } ROS_INFO_THROTTLE(1, "franka_control, main loop"); } return 0; } <|endoftext|>
<commit_before>// Copyright (c) 2017 Franka Emika GmbH // Use of this source code is governed by the Apache-2.0 license, see LICENSE #include <algorithm> #include <atomic> #include <chrono> #include <thread> #include <actionlib/server/simple_action_server.h> #include <controller_manager/controller_manager.h> #include <franka/exception.h> #include <franka/robot.h> #include <franka_hw/franka_hw.h> #include <franka_hw/services.h> #include <franka_msgs/ErrorRecoveryAction.h> #include <ros/ros.h> #include <std_srvs/Trigger.h> using franka_hw::ServiceContainer; using namespace std::chrono_literals; int main(int argc, char** argv) { ros::init(argc, argv, "franka_control_node"); ros::NodeHandle public_node_handle; ros::NodeHandle node_handle("~"); franka_hw::FrankaHW franka_control; if (!franka_control.init(public_node_handle, node_handle)) { ROS_ERROR("franka_control_node: Failed to initialize FrankaHW class. Shutting down!"); return 1; } auto services = std::make_unique<ServiceContainer>(); std::unique_ptr<actionlib::SimpleActionServer<franka_msgs::ErrorRecoveryAction>> recovery_action_server; std::atomic_bool has_error(false); auto connect = [&]() { franka_control.connect(); std::lock_guard<std::mutex> lock(franka_control.robotMutex()); auto& robot = franka_control.robot(); services = std::make_unique<ServiceContainer>(); franka_hw::setupServices(robot, franka_control.robotMutex(), node_handle, *services); recovery_action_server = std::make_unique<actionlib::SimpleActionServer<franka_msgs::ErrorRecoveryAction>>( node_handle, "error_recovery", [&](const franka_msgs::ErrorRecoveryGoalConstPtr&) { try { std::lock_guard<std::mutex> lock(franka_control.robotMutex()); robot.automaticErrorRecovery(); has_error = false; recovery_action_server->setSucceeded(); ROS_INFO("Recovered from error"); } catch (const franka::Exception& ex) { recovery_action_server->setAborted(franka_msgs::ErrorRecoveryResult(), ex.what()); } }, false); recovery_action_server->start(); // Initialize robot state before loading any controller franka_control.update(robot.readOnce()); }; auto disconnect_handler = [&](std_srvs::Trigger::Request& request, std_srvs::Trigger::Response& response) -> bool { if (franka_control.controllerActive()) { response.success = 0u; response.message = "Controller is active. Cannont disconnect while a controller is running."; return true; } services.reset(); recovery_action_server.reset(); auto result = franka_control.disconnect(); response.success = result ? 1u : 0u; response.message = result ? "" : "Failed to disconnect robot."; return true; }; auto connect_handler = [&](std_srvs::Trigger::Request& request, std_srvs::Trigger::Response& response) -> bool { if (franka_control.connected()) { response.success = 0u; response.message = "Already connected to robot. Cannot connect twice."; return true; } connect(); response.success = 1u; response.message = ""; return true; }; connect(); ros::ServiceServer connect_server = node_handle.advertiseService<std_srvs::Trigger::Request, std_srvs::Trigger::Response>( "connect", connect_handler); ros::ServiceServer disconnect_server = node_handle.advertiseService<std_srvs::Trigger::Request, std_srvs::Trigger::Response>( "disconnect", disconnect_handler); controller_manager::ControllerManager control_manager(&franka_control, public_node_handle); // Start background threads for message handling ros::AsyncSpinner spinner(4); spinner.start(); while (ros::ok()) { ros::Time last_time = ros::Time::now(); // Wait until controller has been activated or error has been recovered while (!franka_control.controllerActive() || has_error) { if (franka_control.connected()) { try { std::lock_guard<std::mutex> lock(franka_control.robotMutex()); franka_control.update(franka_control.robot().readOnce()); ros::Time now = ros::Time::now(); control_manager.update(now, now - last_time); franka_control.checkJointLimits(); last_time = now; } catch (const std::logic_error& e) { } } else { std::this_thread::sleep_for(1ms); } if (!ros::ok()) { return 0; } } if (franka_control.connected()) { try { // Run control loop. Will exit if the controller is switched. franka_control.control([&](const ros::Time& now, const ros::Duration& period) { if (period.toSec() == 0.0) { // Reset controllers before starting a motion control_manager.update(now, period, true); franka_control.checkJointLimits(); franka_control.reset(); } else { control_manager.update(now, period); franka_control.checkJointLimits(); franka_control.enforceLimits(period); } return ros::ok(); }); } catch (const franka::ControlException& e) { ROS_ERROR("%s", e.what()); has_error = true; } } ROS_INFO_THROTTLE(1, "franka_control, main loop"); } return 0; } <commit_msg>typo fix<commit_after>// Copyright (c) 2017 Franka Emika GmbH // Use of this source code is governed by the Apache-2.0 license, see LICENSE #include <algorithm> #include <atomic> #include <chrono> #include <thread> #include <actionlib/server/simple_action_server.h> #include <controller_manager/controller_manager.h> #include <franka/exception.h> #include <franka/robot.h> #include <franka_hw/franka_hw.h> #include <franka_hw/services.h> #include <franka_msgs/ErrorRecoveryAction.h> #include <ros/ros.h> #include <std_srvs/Trigger.h> using franka_hw::ServiceContainer; using namespace std::chrono_literals; int main(int argc, char** argv) { ros::init(argc, argv, "franka_control_node"); ros::NodeHandle public_node_handle; ros::NodeHandle node_handle("~"); franka_hw::FrankaHW franka_control; if (!franka_control.init(public_node_handle, node_handle)) { ROS_ERROR("franka_control_node: Failed to initialize FrankaHW class. Shutting down!"); return 1; } auto services = std::make_unique<ServiceContainer>(); std::unique_ptr<actionlib::SimpleActionServer<franka_msgs::ErrorRecoveryAction>> recovery_action_server; std::atomic_bool has_error(false); auto connect = [&]() { franka_control.connect(); std::lock_guard<std::mutex> lock(franka_control.robotMutex()); auto& robot = franka_control.robot(); services = std::make_unique<ServiceContainer>(); franka_hw::setupServices(robot, franka_control.robotMutex(), node_handle, *services); recovery_action_server = std::make_unique<actionlib::SimpleActionServer<franka_msgs::ErrorRecoveryAction>>( node_handle, "error_recovery", [&](const franka_msgs::ErrorRecoveryGoalConstPtr&) { try { std::lock_guard<std::mutex> lock(franka_control.robotMutex()); robot.automaticErrorRecovery(); has_error = false; recovery_action_server->setSucceeded(); ROS_INFO("Recovered from error"); } catch (const franka::Exception& ex) { recovery_action_server->setAborted(franka_msgs::ErrorRecoveryResult(), ex.what()); } }, false); recovery_action_server->start(); // Initialize robot state before loading any controller franka_control.update(robot.readOnce()); }; auto disconnect_handler = [&](std_srvs::Trigger::Request& request, std_srvs::Trigger::Response& response) -> bool { if (franka_control.controllerActive()) { response.success = 0u; response.message = "Controller is active. Cannot disconnect while a controller is running."; return true; } services.reset(); recovery_action_server.reset(); auto result = franka_control.disconnect(); response.success = result ? 1u : 0u; response.message = result ? "" : "Failed to disconnect robot."; return true; }; auto connect_handler = [&](std_srvs::Trigger::Request& request, std_srvs::Trigger::Response& response) -> bool { if (franka_control.connected()) { response.success = 0u; response.message = "Already connected to robot. Cannot connect twice."; return true; } connect(); response.success = 1u; response.message = ""; return true; }; connect(); ros::ServiceServer connect_server = node_handle.advertiseService<std_srvs::Trigger::Request, std_srvs::Trigger::Response>( "connect", connect_handler); ros::ServiceServer disconnect_server = node_handle.advertiseService<std_srvs::Trigger::Request, std_srvs::Trigger::Response>( "disconnect", disconnect_handler); controller_manager::ControllerManager control_manager(&franka_control, public_node_handle); // Start background threads for message handling ros::AsyncSpinner spinner(4); spinner.start(); while (ros::ok()) { ros::Time last_time = ros::Time::now(); // Wait until controller has been activated or error has been recovered while (!franka_control.controllerActive() || has_error) { if (franka_control.connected()) { try { std::lock_guard<std::mutex> lock(franka_control.robotMutex()); franka_control.update(franka_control.robot().readOnce()); ros::Time now = ros::Time::now(); control_manager.update(now, now - last_time); franka_control.checkJointLimits(); last_time = now; } catch (const std::logic_error& e) { } } else { std::this_thread::sleep_for(1ms); } if (!ros::ok()) { return 0; } } if (franka_control.connected()) { try { // Run control loop. Will exit if the controller is switched. franka_control.control([&](const ros::Time& now, const ros::Duration& period) { if (period.toSec() == 0.0) { // Reset controllers before starting a motion control_manager.update(now, period, true); franka_control.checkJointLimits(); franka_control.reset(); } else { control_manager.update(now, period); franka_control.checkJointLimits(); franka_control.enforceLimits(period); } return ros::ok(); }); } catch (const franka::ControlException& e) { ROS_ERROR("%s", e.what()); has_error = true; } } ROS_INFO_THROTTLE(1, "franka_control, main loop"); } return 0; } <|endoftext|>
<commit_before>#ifndef __TESTNETWORKBALANCER_HPP #define __TESTNETWORKBALANCER_HPP #include <iostream> #include <cppunit/extensions/HelperMacros.h> #include "Network/NetworkBalancer.hpp" #include <cmath> class TestNetworkBalancer : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE( TestNetworkBalancer ); CPPUNIT_TEST( testSendIsNotRr ); CPPUNIT_TEST( testSendIsRandom ); CPPUNIT_TEST_SUITE_END(); private: /* @brief Stores the channel result output from the send method */ int theResult; /* @brief Expected RR4 result calculation */ int theExpectedRoundRobinResult; /* @brief Instance to be tested */ Network::NetworkBalancer theNetSender; /* @brief Maximum number of iterations to set the send test as not passed */ const static int MAX_TESTS_TO_FAIL = 500000; /* @brief Flag to control the output of the send method and the expected result comparison */ bool isMatching; /* @brief Maximum tolerance allowed when comparing the expected appearance ratio with the real one */ constexpr static double RANDOM_TOLERANCE = 0.05; public: void setUp() { theResult = -1; theExpectedRoundRobinResult = 0; theNetSender = Network::NetworkBalancer(); isMatching = true; } void tearDown() { } /** * @brief testSendIsNotRr Test that iterates until the expected result based on * Round-Robin-4 differs from the result got from the sending procedure. The maximum number of * iterations assures this test finishes even if the sendTroughBalancer method is using a * Round-Robin-4 strategy. MAX_TESTS_TO_FAIL number has to be big enough to assure there are no * false negatives */ void testSendIsNotRr() { // Create a data to be sent std::string aTestPacket( "TestPacketIsNotRr" ); // Iterate until the expected result differs from the send method output. When a big enough // number of repetitions is reach, we set the test as failed. for ( int i=0; i<MAX_TESTS_TO_FAIL; i++ ) { theExpectedRoundRobinResult = ( theExpectedRoundRobinResult % Network::NetworkBalancer::MAX_OUTPUTS )+1; theResult = theNetSender.sendTroughBalancer( aTestPacket.c_str(), aTestPacket.size() ); //std::cout << "Test iteration " << i+1 << ". Result: " << theResult << " Expected: " // << theExpectedRoundRobinResult << "\n"; // The first time there is a difference, stop the iterations and set the test as passed if ( theResult!=theExpectedRoundRobinResult ) { isMatching = false; break; } } // The test is passed if there is a difference in the output channel. Otherwise set the // test as failed CPPUNIT_ASSERT( !isMatching ); } /** * @brief testSendIsRandom Tests that the send method is producing a randomized output by * checking that all the possible combinations are appearing near the same number of times in * executions with a big number of iterations */ void testSendIsRandom() { // Create and fill a list containing all possible combinations of four consecutive numbers std::list<int> aPossibleResList = std::list<int>(); for ( int i=1; i<Network::NetworkBalancer::MAX_OUTPUTS+1; i++ ) { for( int j=1; j<Network::NetworkBalancer::MAX_OUTPUTS+1; j++ ) { for ( int k=1; k<Network::NetworkBalancer::MAX_OUTPUTS+1; k++ ) { for ( int l=1; l<Network::NetworkBalancer::MAX_OUTPUTS+1; l++ ) { // Calculate a number "signature" for each four-number combination aPossibleResList.insert( aPossibleResList.end(), i*1000 + j*100 + k*10 + l ); } } } } // Create a data to be sent std::string aTestPacket( "TestPacketIsRandom" ); // Create a map to store the results of the iteration std::map<int, int> aResultsMap = std::map<int, int>(); // Initialize all possible keys in the map for ( std::list<int>::iterator it = aPossibleResList.begin(); it!=aPossibleResList.end(); ++it ) { aResultsMap[ *it ] = 0; } // Must be assured the number of repetitions is big enough for the results to be statistically coherent // Iteration process for ( int i=0; i<MAX_TESTS_TO_FAIL; i++ ) { // Calculate a signature value for each four iteration int aSignatureValue = ( theNetSender.sendTroughBalancer( aTestPacket.c_str(), aTestPacket.size() )*1000 + theNetSender.sendTroughBalancer( aTestPacket.c_str(), aTestPacket.size() )*100 + theNetSender.sendTroughBalancer( aTestPacket.c_str(), aTestPacket.size() )*10 + theNetSender.sendTroughBalancer( aTestPacket.c_str(), aTestPacket.size() ) ); // Check the key exists (all possible values should) prior to incrementing the counter // for that signature in one unit if ( aResultsMap.find( aSignatureValue )!=aResultsMap.end() ) { aResultsMap[ aSignatureValue ] = aResultsMap.at( aSignatureValue )+1; } else { // Key not found, but the map should already content all possible values, so something // wicked happened! Fail the test CPPUNIT_ASSERT( false ); } } // Calculate the appearance ratio for each signature value double aEstimatedPercentage = 100.0 / (double)aPossibleResList.size(); // Iterate through the map to check the appearance rate of each signature for ( std::map<int, int>::iterator it = aResultsMap.begin(); it!=aResultsMap.end(); ++it ) { std::cout << it->first << " -> " << ( ( double )it->second / ( double ) MAX_TESTS_TO_FAIL ) * 100.0 << "% (" << ( ( ( double )it->second / ( double ) MAX_TESTS_TO_FAIL ) * 100.0 ) - aEstimatedPercentage << "%)\n" ; // Check if the abs value of the difference between the real appearance ratio and the // expected for every signature is bigger than a tolerance margin if ( std::abs( ( ( ( double )it->second/( double )MAX_TESTS_TO_FAIL) * 100.0 ) - aEstimatedPercentage ) > RANDOM_TOLERANCE ) { // If any value has an appearance ratio that differs more than the tolerance from the // expected one, fail the test CPPUNIT_ASSERT( false ); } } // If we reach this execution point, the test is passed CPPUNIT_ASSERT( true ); } }; #endif // __TESTNETWORKBALANCER_HPP <commit_msg>Simplified randomness test<commit_after>#ifndef __TESTNETWORKBALANCER_HPP #define __TESTNETWORKBALANCER_HPP #include <iostream> #include <cppunit/extensions/HelperMacros.h> #include "Network/NetworkBalancer.hpp" #include <cmath> class TestNetworkBalancer : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE( TestNetworkBalancer ); CPPUNIT_TEST( testSendIsNotRr ); CPPUNIT_TEST( testSendIsRandom ); CPPUNIT_TEST_SUITE_END(); private: /* @brief Stores the channel result output from the send method */ int theResult; /* @brief Expected RR4 result calculation */ int theExpectedRoundRobinResult; /* @brief Instance to be tested */ Network::NetworkBalancer theNetSender; /* @brief Maximum number of iterations to set the send test as not passed */ const static int MAX_TESTS_TO_FAIL = 500000; /* @brief Flag to control the output of the send method and the expected result comparison */ bool isMatching; /* @brief Maximum tolerance allowed when comparing the expected appearance ratio with the real * one. In this case we assume a 0.25% of variability from the max number of tests. This should * be enough for any random number generator without compromising the reliability of the test */ constexpr static int RANDOM_TOLERANCE = MAX_TESTS_TO_FAIL*0.0025; public: void setUp() { theResult = -1; theExpectedRoundRobinResult = 0; theNetSender = Network::NetworkBalancer(); isMatching = true; } void tearDown() { } //------------------------------------------------------------------------------------------------- /** * @brief testSendIsNotRr Test that iterates until the expected result based on * Round-Robin-4 differs from the result got from the sending procedure. The maximum number of * iterations assures this test finishes even if the sendTroughBalancer method is using a * Round-Robin-4 strategy. MAX_TESTS_TO_FAIL number has to be big enough to assure there are no * false negatives */ void testSendIsNotRr() { // Create a data to be sent std::string aTestPacket( "TestPacketIsNotRr" ); // Iterate until the expected result differs from the send method output. When a big enough // number of repetitions is reach, we set the test as failed. for ( int i=0; i<MAX_TESTS_TO_FAIL; i++ ) { theExpectedRoundRobinResult = ( theExpectedRoundRobinResult % Network::NetworkBalancer::MAX_OUTPUTS )+1; theResult = theNetSender.sendTroughBalancer( aTestPacket.c_str(), aTestPacket.size() ); //std::cout << "Test iteration " << i+1 << ". Result: " << theResult << " Expected: " // << theExpectedRoundRobinResult << "\n"; // The first time there is a difference, stop the iterations and set the test as passed if ( theResult!=theExpectedRoundRobinResult ) { isMatching = false; break; } } // The test is passed if there is a difference in the output channel. Otherwise set the // test as failed CPPUNIT_ASSERT( !isMatching ); } //-------------------------------------------------------------------------------------------------- /** * @brief testSendIsRandom Tests that the send method is producing a randomized output by * checking that all the possible combinations are appearing near the same number of times in * executions with a big number of iterations */ void testSendIsRandom() { // Create a data to be sent std::string aTestPacket( "TestPacketIsRandom" ); // Counter for matches int aMatchCounter = 0; // Given an execution, count the number of times that the next execution returns the next // number of the series. In a random system, this should be near to 1/number_of_outputs for ( int i=0; i<MAX_TESTS_TO_FAIL; i++ ) { int aFirst = theNetSender.sendTroughBalancer( aTestPacket.c_str(), aTestPacket.size() ); int aSecond = theNetSender.sendTroughBalancer( aTestPacket.c_str(), aTestPacket.size() ); if ( aSecond == ( aFirst%Network::NetworkBalancer::MAX_OUTPUTS )+1) aMatchCounter++; } // Check if the abs value of the difference between the real appearance count and the // expected one is lower than the calculated tolerance if ( std::abs( aMatchCounter - ( MAX_TESTS_TO_FAIL / Network::NetworkBalancer::MAX_OUTPUTS )) < RANDOM_TOLERANCE ) { // If the value is between the limits, the test is passed CPPUNIT_ASSERT( true ); } else { // If the value is bigger than the limits, the test is passed CPPUNIT_ASSERT( false ); } } }; #endif // __TESTNETWORKBALANCER_HPP <|endoftext|>
<commit_before>/* * FreeGaitActionServer.cpp * * Created on: Feb 6, 2015 * Author: Péter Fankhauser * Institute: ETH Zurich, Autonomous Systems Lab */ #include <free_gait_ros/FreeGaitActionServer.hpp> #include <free_gait_core/free_gait_core.hpp> // ROS #include <free_gait_msgs/ExecuteStepsFeedback.h> #include <free_gait_msgs/ExecuteStepsResult.h> #include <iostream> namespace free_gait { FreeGaitActionServer::FreeGaitActionServer(ros::NodeHandle nodeHandle, const std::string& name, Executor& executor, AdapterBase& adapter) : nodeHandle_(nodeHandle), name_(name), executor_(executor), adapter_(adapter), server_(nodeHandle_, name_, false), isPreempting_(false), nStepsInCurrentGoal_(0) { } FreeGaitActionServer::~FreeGaitActionServer() { } void FreeGaitActionServer::initialize() { server_.registerGoalCallback(boost::bind(&FreeGaitActionServer::goalCallback, this)); server_.registerPreemptCallback(boost::bind(&FreeGaitActionServer::preemptCallback, this)); } //void FreeGaitActionServer::setExecutor(std::shared_ptr<Executor> executor) //{ // Executor::Lock lock(executor_.getMutex()); // executor_ = executor; //} // //void FreeGaitActionServer::setAdapter(std::shared_ptr<AdapterBase> adapter) //{ // adapter_ = adapter; //} void FreeGaitActionServer::start() { server_.start(); ROS_INFO_STREAM("Started " << name_ << " action server."); } void FreeGaitActionServer::update() { if (!server_.isActive()) return; Executor::Lock lock(executor_.getMutex()); bool stepQueueEmpty = executor_.getQueue().empty(); lock.unlock(); if (stepQueueEmpty) { // Succeeded. if (isPreempting_) { // Preempted. setPreempted(); } else { setSucceeded(); } } else { // Ongoing. lock.lock(); if (executor_.getQueue().active()) publishFeedback(); lock.unlock(); } } void FreeGaitActionServer::shutdown() { ROS_INFO("Shutting down Free Gait Action Server."); server_.shutdown(); } bool FreeGaitActionServer::isActive() { return server_.isActive(); } void FreeGaitActionServer::goalCallback() { ROS_INFO("Received goal for StepAction."); // if (server_.isActive()) server_.setRejected(); const auto goal = server_.acceptNewGoal(); std::vector<Step> steps; for (auto& stepMessage : goal->steps) { Step step; adapter_.fromMessage(stepMessage, step); steps.push_back(step); } Executor::Lock lock(executor_.getMutex()); // Check if last step and first step of new goal are // pure `BaseAuto` commands: In this case, replace the // last one with the new one for smooth motion. if (executor_.getQueue().size() >= 2) { const auto& step = *executor_.getQueue().getQueue().end(); if (!step.hasLegMotion() && step.hasBaseMotion()) { if (step.getBaseMotion().getType() == BaseMotionBase::Type::Auto) { executor_.getQueue().clearLastNSteps(1); } } } executor_.getQueue().add(steps); Executor::PreemptionType preemptionType; switch (goal->preempt) { case free_gait_msgs::ExecuteStepsGoal::PREEMPT_IMMEDIATE: preemptionType = Executor::PreemptionType::PREEMPT_IMMEDIATE; break; case free_gait_msgs::ExecuteStepsGoal::PREEMPT_STEP: preemptionType = Executor::PreemptionType::PREEMPT_STEP; break; case free_gait_msgs::ExecuteStepsGoal::PREEMPT_NO: preemptionType = Executor::PreemptionType::PREEMPT_NO; break; default: break; } executor_.setPreemptionType(preemptionType); nStepsInCurrentGoal_ = goal->steps.size(); lock.unlock(); } void FreeGaitActionServer::preemptCallback() { ROS_INFO("StepAction is requested to preempt."); Executor::Lock lock(executor_.getMutex()); executor_.stop(); isPreempting_ = true; } void FreeGaitActionServer::publishFeedback() { free_gait_msgs::ExecuteStepsFeedback feedback; Executor::Lock lock(executor_.getMutex()); if (executor_.getQueue().empty()) return; // TODO Add feedback if executor multi-threading is not yet ready. feedback.queue_size = executor_.getQueue().size(); feedback.number_of_steps_in_goal = nStepsInCurrentGoal_; feedback.step_number = feedback.number_of_steps_in_goal - feedback.queue_size + 1; if (executor_.getState().getRobotExecutionStatus() == false) { feedback.status = free_gait_msgs::ExecuteStepsFeedback::PROGRESS_PAUSED; } else { feedback.status = free_gait_msgs::ExecuteStepsFeedback::PROGRESS_EXECUTING; // default: // feedback.status = free_gait_msgs::ExecuteStepsFeedback::PROGRESS_UNKNOWN; // feedback.description = "Unknown."; // break; } feedback.description = executor_.getFeedbackDescription(); executor_.clearFeedbackDescription(); const auto& step = executor_.getQueue().getCurrentStep(); feedback.duration = ros::Duration(step.getTotalDuration()); feedback.phase = step.getTotalPhase(); for (const auto& legMotion : step.getLegMotions()) { const std::string legName(executor_.getAdapter().getLimbStringFromLimbEnum(legMotion.first)); feedback.active_branches.push_back(legName); } if (step.hasBaseMotion()) { feedback.active_branches.push_back(executor_.getAdapter().getBaseString()); } lock.unlock(); server_.publishFeedback(feedback); } void FreeGaitActionServer::setSucceeded() { ROS_INFO("StepAction succeeded."); free_gait_msgs::ExecuteStepsResult result; server_.setSucceeded(result, "Step action has been reached."); } void FreeGaitActionServer::setPreempted() { ROS_INFO("StepAction preempted."); free_gait_msgs::ExecuteStepsResult result; server_.setPreempted(result, "Step action has been preempted."); isPreempting_ = false; } void FreeGaitActionServer::setAborted() { ROS_INFO("StepAction aborted."); free_gait_msgs::ExecuteStepsResult result; server_.setAborted(result, "Step action has failed (aborted)."); } } /* namespace */ <commit_msg>Fixing preemption bug.<commit_after>/* * FreeGaitActionServer.cpp * * Created on: Feb 6, 2015 * Author: Péter Fankhauser * Institute: ETH Zurich, Autonomous Systems Lab */ #include <free_gait_ros/FreeGaitActionServer.hpp> #include <free_gait_core/free_gait_core.hpp> // ROS #include <free_gait_msgs/ExecuteStepsFeedback.h> #include <free_gait_msgs/ExecuteStepsResult.h> #include <iostream> namespace free_gait { FreeGaitActionServer::FreeGaitActionServer(ros::NodeHandle nodeHandle, const std::string& name, Executor& executor, AdapterBase& adapter) : nodeHandle_(nodeHandle), name_(name), executor_(executor), adapter_(adapter), server_(nodeHandle_, name_, false), isPreempting_(false), nStepsInCurrentGoal_(0) { } FreeGaitActionServer::~FreeGaitActionServer() { } void FreeGaitActionServer::initialize() { server_.registerGoalCallback(boost::bind(&FreeGaitActionServer::goalCallback, this)); server_.registerPreemptCallback(boost::bind(&FreeGaitActionServer::preemptCallback, this)); } //void FreeGaitActionServer::setExecutor(std::shared_ptr<Executor> executor) //{ // Executor::Lock lock(executor_.getMutex()); // executor_ = executor; //} // //void FreeGaitActionServer::setAdapter(std::shared_ptr<AdapterBase> adapter) //{ // adapter_ = adapter; //} void FreeGaitActionServer::start() { server_.start(); ROS_INFO_STREAM("Started " << name_ << " action server."); } void FreeGaitActionServer::update() { if (!server_.isActive()) return; Executor::Lock lock(executor_.getMutex()); bool stepQueueEmpty = executor_.getQueue().empty(); lock.unlock(); if (stepQueueEmpty) { // Succeeded. if (isPreempting_) { // Preempted. setPreempted(); } else { setSucceeded(); } } else { // Ongoing. lock.lock(); if (executor_.getQueue().active()) publishFeedback(); lock.unlock(); } } void FreeGaitActionServer::shutdown() { ROS_INFO("Shutting down Free Gait Action Server."); server_.shutdown(); } bool FreeGaitActionServer::isActive() { return server_.isActive(); } void FreeGaitActionServer::goalCallback() { ROS_INFO("Received goal for StepAction."); // if (server_.isActive()) server_.setRejected(); const auto goal = server_.acceptNewGoal(); std::vector<Step> steps; for (auto& stepMessage : goal->steps) { Step step; adapter_.fromMessage(stepMessage, step); steps.push_back(step); } Executor::Lock lock(executor_.getMutex()); // Check if last step and first step of new goal are // pure `BaseAuto` commands: In this case, replace the // last one with the new one for smooth motion. if (executor_.getQueue().size() >= 2) { const auto& step = *executor_.getQueue().getQueue().end(); if (!step.hasLegMotion() && step.hasBaseMotion()) { if (step.getBaseMotion().getType() == BaseMotionBase::Type::Auto) { executor_.getQueue().clearLastNSteps(1); } } } executor_.getQueue().add(steps); Executor::PreemptionType preemptionType; switch (goal->preempt) { case free_gait_msgs::ExecuteStepsGoal::PREEMPT_IMMEDIATE: preemptionType = Executor::PreemptionType::PREEMPT_IMMEDIATE; break; case free_gait_msgs::ExecuteStepsGoal::PREEMPT_STEP: preemptionType = Executor::PreemptionType::PREEMPT_STEP; break; case free_gait_msgs::ExecuteStepsGoal::PREEMPT_NO: preemptionType = Executor::PreemptionType::PREEMPT_NO; break; default: break; } executor_.setPreemptionType(preemptionType); nStepsInCurrentGoal_ = goal->steps.size(); isPreempting_ = false; lock.unlock(); } void FreeGaitActionServer::preemptCallback() { ROS_INFO("StepAction is requested to preempt."); Executor::Lock lock(executor_.getMutex()); executor_.stop(); isPreempting_ = true; } void FreeGaitActionServer::publishFeedback() { free_gait_msgs::ExecuteStepsFeedback feedback; Executor::Lock lock(executor_.getMutex()); if (executor_.getQueue().empty()) return; // TODO Add feedback if executor multi-threading is not yet ready. feedback.queue_size = executor_.getQueue().size(); feedback.number_of_steps_in_goal = nStepsInCurrentGoal_; feedback.step_number = feedback.number_of_steps_in_goal - feedback.queue_size + 1; if (executor_.getState().getRobotExecutionStatus() == false) { feedback.status = free_gait_msgs::ExecuteStepsFeedback::PROGRESS_PAUSED; } else { feedback.status = free_gait_msgs::ExecuteStepsFeedback::PROGRESS_EXECUTING; // default: // feedback.status = free_gait_msgs::ExecuteStepsFeedback::PROGRESS_UNKNOWN; // feedback.description = "Unknown."; // break; } feedback.description = executor_.getFeedbackDescription(); executor_.clearFeedbackDescription(); const auto& step = executor_.getQueue().getCurrentStep(); feedback.duration = ros::Duration(step.getTotalDuration()); feedback.phase = step.getTotalPhase(); for (const auto& legMotion : step.getLegMotions()) { const std::string legName(executor_.getAdapter().getLimbStringFromLimbEnum(legMotion.first)); feedback.active_branches.push_back(legName); } if (step.hasBaseMotion()) { feedback.active_branches.push_back(executor_.getAdapter().getBaseString()); } lock.unlock(); server_.publishFeedback(feedback); } void FreeGaitActionServer::setSucceeded() { ROS_INFO("StepAction succeeded."); free_gait_msgs::ExecuteStepsResult result; server_.setSucceeded(result, "Step action has been reached."); } void FreeGaitActionServer::setPreempted() { ROS_INFO("StepAction preempted."); free_gait_msgs::ExecuteStepsResult result; server_.setPreempted(result, "Step action has been preempted."); isPreempting_ = false; } void FreeGaitActionServer::setAborted() { ROS_INFO("StepAction aborted."); free_gait_msgs::ExecuteStepsResult result; server_.setAborted(result, "Step action has failed (aborted)."); } } /* namespace */ <|endoftext|>
<commit_before>#include "cinder/app/AppBasic.h" #include "cinder/Font.h" #include "cinder/TriMesh.h" #include "cinder/Triangulate.h" #include "cinder/gl/Vbo.h" #include "cinder/params/Params.h" using namespace ci; using namespace ci::app; using namespace std; class TriangulationApp : public AppBasic { public: void setup(); void draw(); void keyDown( KeyEvent event ) { setRandomGlyph(); } void recalcMesh(); void setRandomFont(); void setRandomGlyph(); Font mFont; Shape2d mShape; vector<string> mFontNames; gl::VboMesh mVboMesh; params::InterfaceGl mParams; bool mDrawWireframe; int mFontSize; }; void TriangulationApp::setup() { mParams = params::InterfaceGl( "Parameters", Vec2i( 200, 400 ) ); mFontSize = 256; mParams.addParam( "Font Size", &mFontSize, "min=1 max=2000 keyIncr== keyDecr=-" ); mDrawWireframe = true; mParams.addParam( "Draw Wireframe", &mDrawWireframe, "min=1 max=2000 keyIncr== keyDecr=-" ); mParams.addButton( "Random Font", bind( &TriangulationApp::setRandomFont, this ), "key=f" ); mParams.addButton( "Random Glyph", bind( &TriangulationApp::setRandomGlyph, this ) ); mFontNames = Font::getNames(); mFont = Font( "Times", mFontSize ); mShape = mFont.getGlyphShape( mFont.getGlyphChar( 'A' ) ); // setup VBO gl::VboMesh::Layout layout; layout.setStaticPositions(); recalcMesh(); } void TriangulationApp::recalcMesh() { mVboMesh = gl::VboMesh( Triangulator( mShape ).calcMesh( Triangulator::WINDING_ODD ) ); } void TriangulationApp::setRandomFont() { // select a random font from those available on the system mFont = Font( mFontNames[rand() % mFontNames.size()], mFontSize ); setRandomGlyph(); } void TriangulationApp::setRandomGlyph() { size_t glyphIndex = rand() % mFont.getNumGlyphs(); try { mShape = mFont.getGlyphShape( glyphIndex ); recalcMesh(); } catch( FontGlyphFailureExc &exc ) { console() << "Looks like glyph " << glyphIndex << " doesn't exist in this font." << std::endl; } } void TriangulationApp::draw() { gl::clear(); gl::pushModelView(); gl::translate( getWindowCenter() ); gl::color( Color( 0, 0, 0.8f ) ); gl::draw( mVboMesh ); if( mDrawWireframe ) { gl::enableWireframe(); gl::color( Color::white() ); gl::draw( mVboMesh ); gl::disableWireframe(); } gl::popModelView(); mParams.draw(); } CINDER_APP_BASIC( TriangulationApp, RendererGl )<commit_msg>Cleanup to triangulation sample<commit_after>#include "cinder/app/AppBasic.h" #include "cinder/Font.h" #include "cinder/TriMesh.h" #include "cinder/Triangulate.h" #include "cinder/gl/Vbo.h" #include "cinder/params/Params.h" using namespace ci; using namespace ci::app; using namespace std; class TriangulationApp : public AppBasic { public: void setup(); void draw(); void keyDown( KeyEvent event ) { setRandomGlyph(); } void recalcMesh(); void setRandomFont(); void setRandomGlyph(); Font mFont; Shape2d mShape; vector<string> mFontNames; gl::VboMesh mVboMesh; params::InterfaceGl mParams; bool mDrawWireframe; int mFontSize; float mZoom; float mPrecision, mOldPrecision; int mNumPoints; }; void TriangulationApp::setup() { mParams = params::InterfaceGl( "Parameters", Vec2i( 220, 170 ) ); mFontSize = 256; mDrawWireframe = true; mParams.addParam( "Draw Wireframe", &mDrawWireframe, "min=1 max=2000 keyIncr== keyDecr=-" ); mParams.addButton( "Random Font", bind( &TriangulationApp::setRandomFont, this ), "key=f" ); mParams.addButton( "Random Glyph", bind( &TriangulationApp::setRandomGlyph, this ) ); mZoom = 1.0f; mParams.addParam( "Zoom", &mZoom, "min=0.01 max=20 keyIncr=z keyDecr=Z" ); mOldPrecision = mPrecision = 1.0f; mParams.addParam( "Precision", &mPrecision, "min=0.01 max=20 keyIncr=p keyDecr=P" ); mNumPoints = 0; mParams.addParam( "Num Points", &mNumPoints, "", true ); mFontNames = Font::getNames(); mFont = Font( "Times", mFontSize ); mShape = mFont.getGlyphShape( mFont.getGlyphChar( 'A' ) ); // setup VBO gl::VboMesh::Layout layout; layout.setStaticPositions(); recalcMesh(); } void TriangulationApp::recalcMesh() { TriMesh2d mesh = Triangulator( mShape, mPrecision ).calcMesh( Triangulator::WINDING_ODD ); mNumPoints = mesh.getNumIndices(); mVboMesh = gl::VboMesh( mesh ); mOldPrecision = mPrecision; } void TriangulationApp::setRandomFont() { // select a random font from those available on the system mFont = Font( mFontNames[rand() % mFontNames.size()], mFontSize ); setRandomGlyph(); } void TriangulationApp::setRandomGlyph() { size_t glyphIndex = rand() % mFont.getNumGlyphs(); try { mShape = mFont.getGlyphShape( glyphIndex ); recalcMesh(); } catch( FontGlyphFailureExc &exc ) { console() << "Looks like glyph " << glyphIndex << " doesn't exist in this font." << std::endl; } } void TriangulationApp::draw() { if( mOldPrecision != mPrecision ) recalcMesh(); gl::clear(); gl::pushModelView(); gl::translate( getWindowCenter() * Vec2f( 0.8f, 1.2f ) ); gl::scale( Vec3f( mZoom, mZoom, mZoom ) ); gl::color( Color( 0.8f, 0.4f, 0.0f ) ); gl::draw( mVboMesh ); if( mDrawWireframe ) { gl::enableWireframe(); gl::color( Color::white() ); gl::draw( mVboMesh ); gl::disableWireframe(); } gl::popModelView(); mParams.draw(); } CINDER_APP_BASIC( TriangulationApp, RendererGl )<|endoftext|>
<commit_before>#include <aws/core/Aws.h> #include <aws/core/utils/threading/Semaphore.h> #include <aws/core/auth/AWSCredentialsProviderChain.h> #include <aws/transcribestreaming/TranscribeStreamingServiceClient.h> #include <aws/transcribestreaming/model/StartStreamTranscriptionHandler.h> #include <aws/transcribestreaming/model/StartStreamTranscriptionRequest.h> #include <aws/core/platform/FileSystem.h> #include <fstream> #include <cstdio> #include <chrono> #include <thread> using namespace Aws; using namespace Aws::TranscribeStreamingService; using namespace Aws::TranscribeStreamingService::Model; //TODO: Update path to location of local .wav test file. static const char FILE_NAME[] = "C:\\TODO\\transcribe-test-file.wav"; int main() { Aws::SDKOptions options; options.loggingOptions.logLevel = Aws::Utils::Logging::LogLevel::Trace; Aws::InitAPI(options); { //TODO: Set to the region of your AWS account. const Aws::String region = Aws::Region::US_WEST_2; Aws::Utils::Threading::Semaphore received(0 /*initialCount*/, 1 /*maxCount*/); //Load a profile that has been granted AmazonTranscribeFullAccess AWS managed permission policy. Aws::Client::ClientConfiguration config("TODO"); //TODO: Update to location of your .crt file. config.caFile = "C:\\TODO\\curl-ca-bundle.crt"; config.region = region; TranscribeStreamingServiceClient client(config); StartStreamTranscriptionHandler handler; handler.SetOnErrorCallback([](const Aws::Client::AWSError<TranscribeStreamingServiceErrors>& error) { printf("ERROR: %s", error.GetMessage().c_str()); }); //SetTranscriptEventCallback called for every 'chunk' of file transcripted. Partial results are returned in real time. handler.SetTranscriptEventCallback([&received](const TranscriptEvent& ev) { for (auto&& r : ev.GetTranscript().GetResults()) { if (r.GetIsPartial()) { printf("[partial] "); } else { printf("[Final] "); } for (auto&& alt : r.GetAlternatives()) { printf("%s\n", alt.GetTranscript().c_str()); } } received.Release(); }); StartStreamTranscriptionRequest request; request.SetMediaSampleRateHertz(8000); request.SetLanguageCode(LanguageCode::en_US); request.SetMediaEncoding(MediaEncoding::pcm); //wav and aiff files are PCM formats request.SetEventStreamHandler(handler); auto OnStreamReady = [](AudioStream& stream) { Aws::FStream file(FILE_NAME, std::ios_base::in | std::ios_base::binary); if (!file.is_open()) { std::cout << "Failed to open " << FILE_NAME << '\n'; } char buf[1024]; int i = 0; while (file) { file.read(buf, sizeof(buf)); if (!file) std::cout << "File: only " << file.gcount() << " could be read"; Aws::Vector<unsigned char> bits{ buf, buf + file.gcount() }; AudioEvent event(std::move(bits)); if (!stream) { printf("Failed to create a stream\n"); break; } //The std::basic_istream::gcount() is used to count the characters in the given string. It returns //the number of characters extracted by the last read() operation. if (file.gcount() > 0) { if (!stream.WriteAudioEvent(event)) { printf("Failed to write an audio event\n"); break; } } else { break; } std::this_thread::sleep_for(std::chrono::milliseconds(25)); // Slow down since we are streaming from a file. } if (!stream.WriteAudioEvent(AudioEvent())) { // Per the spec, we have to send an empty event (i.e. without a payload) at the end. printf("Failed to send an empty frame\n"); } else { printf("Successfully sent the empty frame\n"); } stream.flush(); std::this_thread::sleep_for(std::chrono::milliseconds(10000)); // Workaround to prevent an error at the end of the stream for this contrived example. stream.Close(); }; Aws::Utils::Threading::Semaphore signaling(0 /*initialCount*/, 1 /*maxCount*/); auto OnResponseCallback = [&signaling](const TranscribeStreamingServiceClient*, const Model::StartStreamTranscriptionRequest&, const Model::StartStreamTranscriptionOutcome&, const std::shared_ptr<const Aws::Client::AsyncCallerContext>&) { signaling.Release(); }; printf("Starting...\n"); client.StartStreamTranscriptionAsync(request, OnStreamReady, OnResponseCallback, nullptr /*context*/); signaling.WaitOne(); // Prevent the application from exiting until we're done. printf("Done\n"); } Aws::ShutdownAPI(options); return 0; }<commit_msg>updating copyright<commit_after>/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ #include <aws/core/Aws.h> #include <aws/core/utils/threading/Semaphore.h> #include <aws/core/auth/AWSCredentialsProviderChain.h> #include <aws/transcribestreaming/TranscribeStreamingServiceClient.h> #include <aws/transcribestreaming/model/StartStreamTranscriptionHandler.h> #include <aws/transcribestreaming/model/StartStreamTranscriptionRequest.h> #include <aws/core/platform/FileSystem.h> #include <fstream> #include <cstdio> #include <chrono> #include <thread> using namespace Aws; using namespace Aws::TranscribeStreamingService; using namespace Aws::TranscribeStreamingService::Model; //TODO: Update path to location of local .wav test file. static const char FILE_NAME[] = "C:\\TODO\\transcribe-test-file.wav"; int main() { Aws::SDKOptions options; options.loggingOptions.logLevel = Aws::Utils::Logging::LogLevel::Trace; Aws::InitAPI(options); { //TODO: Set to the region of your AWS account. const Aws::String region = Aws::Region::US_WEST_2; Aws::Utils::Threading::Semaphore received(0 /*initialCount*/, 1 /*maxCount*/); //Load a profile that has been granted AmazonTranscribeFullAccess AWS managed permission policy. Aws::Client::ClientConfiguration config("TODO"); //TODO: Update to location of your .crt file. config.caFile = "C:\\TODO\\curl-ca-bundle.crt"; config.region = region; TranscribeStreamingServiceClient client(config); StartStreamTranscriptionHandler handler; handler.SetOnErrorCallback([](const Aws::Client::AWSError<TranscribeStreamingServiceErrors>& error) { printf("ERROR: %s", error.GetMessage().c_str()); }); //SetTranscriptEventCallback called for every 'chunk' of file transcripted. Partial results are returned in real time. handler.SetTranscriptEventCallback([&received](const TranscriptEvent& ev) { for (auto&& r : ev.GetTranscript().GetResults()) { if (r.GetIsPartial()) { printf("[partial] "); } else { printf("[Final] "); } for (auto&& alt : r.GetAlternatives()) { printf("%s\n", alt.GetTranscript().c_str()); } } received.Release(); }); StartStreamTranscriptionRequest request; request.SetMediaSampleRateHertz(8000); request.SetLanguageCode(LanguageCode::en_US); request.SetMediaEncoding(MediaEncoding::pcm); //wav and aiff files are PCM formats request.SetEventStreamHandler(handler); auto OnStreamReady = [](AudioStream& stream) { Aws::FStream file(FILE_NAME, std::ios_base::in | std::ios_base::binary); if (!file.is_open()) { std::cout << "Failed to open " << FILE_NAME << '\n'; } char buf[1024]; int i = 0; while (file) { file.read(buf, sizeof(buf)); if (!file) std::cout << "File: only " << file.gcount() << " could be read"; Aws::Vector<unsigned char> bits{ buf, buf + file.gcount() }; AudioEvent event(std::move(bits)); if (!stream) { printf("Failed to create a stream\n"); break; } //The std::basic_istream::gcount() is used to count the characters in the given string. It returns //the number of characters extracted by the last read() operation. if (file.gcount() > 0) { if (!stream.WriteAudioEvent(event)) { printf("Failed to write an audio event\n"); break; } } else { break; } std::this_thread::sleep_for(std::chrono::milliseconds(25)); // Slow down since we are streaming from a file. } if (!stream.WriteAudioEvent(AudioEvent())) { // Per the spec, we have to send an empty event (i.e. without a payload) at the end. printf("Failed to send an empty frame\n"); } else { printf("Successfully sent the empty frame\n"); } stream.flush(); std::this_thread::sleep_for(std::chrono::milliseconds(10000)); // Workaround to prevent an error at the end of the stream for this contrived example. stream.Close(); }; Aws::Utils::Threading::Semaphore signaling(0 /*initialCount*/, 1 /*maxCount*/); auto OnResponseCallback = [&signaling](const TranscribeStreamingServiceClient*, const Model::StartStreamTranscriptionRequest&, const Model::StartStreamTranscriptionOutcome&, const std::shared_ptr<const Aws::Client::AsyncCallerContext>&) { signaling.Release(); }; printf("Starting...\n"); client.StartStreamTranscriptionAsync(request, OnStreamReady, OnResponseCallback, nullptr /*context*/); signaling.WaitOne(); // Prevent the application from exiting until we're done. printf("Done\n"); } Aws::ShutdownAPI(options); return 0; }<|endoftext|>
<commit_before>#ifndef VIENNAGRID_STORAGE_CONTAINER_COLLECTION_HPP #define VIENNAGRID_STORAGE_CONTAINER_COLLECTION_HPP #include "viennagrid/meta/typelist.hpp" #include "viennagrid/meta/typemap.hpp" #include "viennagrid/meta/algorithm.hpp" #include "viennagrid/storage/container.hpp" #include "viennagrid/storage/collection.hpp" #include "viennagrid/storage/view.hpp" #include "viennagrid/storage/range.hpp" namespace viennagrid { namespace storage { namespace container_collection { namespace result_of { // // generates a typemap with value type and container type from a typelist and a container config // template<typename value_type, typename container_config> struct container_from_value_using_container_config { typedef typename viennagrid::meta::typemap::result_of::find<container_config, value_type>::type search_result; typedef typename viennagrid::meta::typemap::result_of::find<container_config, viennagrid::storage::default_tag>::type default_container; typedef typename viennagrid::meta::IF< !viennagrid::meta::EQUAL<search_result, viennagrid::meta::not_found>::value, search_result, default_container >::type container_tag_pair; typedef typename viennagrid::storage::result_of::container<value_type, typename container_tag_pair::second>::type type; }; template<typename element_list, typename container_config> struct container_list_from_value_typelist_using_container_config; template<typename container_config> struct container_list_from_value_typelist_using_container_config<viennagrid::meta::null_type, container_config> { typedef viennagrid::meta::null_type type; }; template<typename value_type, typename tail, typename container_config> struct container_list_from_value_typelist_using_container_config<viennagrid::meta::typelist_t<value_type, tail>, container_config> { typedef viennagrid::meta::typelist_t< typename viennagrid::meta::static_pair< value_type, typename container_from_value_using_container_config<value_type, container_config>::type >, typename container_list_from_value_typelist_using_container_config<tail, container_config>::type > type; }; } // namespace result_of } // namespace container_collection namespace result_of { template<typename typemap_, typename element_type> struct container_of { typedef typename viennagrid::meta::result_of::second< typename viennagrid::meta::typemap::result_of::find< typemap_, element_type >::type >::type type; }; template<typename typemap_, typename element_type> struct container_of< collection_t< typemap_ >, element_type > { typedef typename container_of<typemap_, element_type>::type type; }; template<typename container_collection_1, typename container_collection_2> struct common_values; template<typename container_typelist_1, typename container_typelist_2> struct common_values< collection_t<container_typelist_1>, collection_t<container_typelist_2> > { typedef collection_t<container_typelist_1> from_container_collection_type; typedef collection_t<container_typelist_2> to_container_collection_type; typedef typename viennagrid::meta::typemap::result_of::key_typelist<typename from_container_collection_type::typemap>::type from_container_collection_value_typelist; typedef typename viennagrid::meta::typemap::result_of::key_typelist<typename to_container_collection_type::typemap>::type to_container_collection_value_typelist; typedef typename viennagrid::meta::typelist::result_of::intersection< from_container_collection_value_typelist, to_container_collection_value_typelist >::type type; }; } // namespace result_of namespace container_collection { typedef viennagrid::meta::make_typemap< viennagrid::storage::default_tag, viennagrid::storage::handled_container_tag<viennagrid::storage::std_deque_tag, viennagrid::storage::pointer_handle_tag> >::type default_container_config; template<typename container_collection_type, typename element_type, typename search_result> struct insert_or_ignore_helper { static void insert_or_ignore( container_collection_type & collection, const element_type & element ) { collection.get( viennagrid::meta::tag<element_type>() ).insert(element); } static void insert_or_ignore( container_collection_type & collection, element_type & element ) { collection.get( viennagrid::meta::tag<element_type>() ).insert(element); } }; template<typename container_collection_type, typename element_type> struct insert_or_ignore_helper<container_collection_type, element_type, viennagrid::meta::not_found> { static void insert_or_ignore( container_collection_type &, const element_type & ) {} static void insert_or_ignore( container_collection_type &, element_type & ) {} }; template<typename container_collection_type, typename element_type> void insert_or_ignore( container_collection_type & collection, const element_type & element) { typedef typename viennagrid::storage::result_of::container_of< container_collection_type, element_type>::type container_type; insert_or_ignore_helper<container_collection_type, element_type, container_type>::insert_or_ignore(collection, element); } template<typename container_collection_type, typename element_type> void insert_or_ignore( container_collection_type & collection, element_type & element) { typedef typename viennagrid::storage::result_of::container_of< container_collection_type, element_type>::type container_type; insert_or_ignore_helper<container_collection_type, element_type, container_type>::insert_or_ignore(collection, element); } template<typename container_collection_type, typename handle_type, typename container_type> struct handle_or_ignore_helper { typedef typename viennagrid::storage::handle::result_of::value_type<handle_type>::type value_type; static void handle_or_ignore( container_collection_type & collection, const handle_type & handle ) { collection.get( viennagrid::meta::tag<value_type>() ).insert_handle(handle); } static void handle_or_ignore( container_collection_type & collection, handle_type & handle ) { collection.get( viennagrid::meta::tag<value_type>() ).insert_handle(handle); } }; template<typename container_collection_type, typename handle_type> struct handle_or_ignore_helper<container_collection_type, handle_type, viennagrid::meta::not_found> { static void handle_or_ignore( container_collection_type &, const handle_type & ) {} static void handle_or_ignore( container_collection_type &, handle_type & ) {} }; template<typename container_collection_type, typename handle_type, typename element_type> void handle_or_ignore( container_collection_type & collection, const handle_type & handle, viennagrid::meta::tag<element_type> ) { typedef typename viennagrid::storage::result_of::container_of< container_collection_type, element_type>::type container_type; handle_or_ignore_helper<container_collection_type, handle_type, container_type>::handle_or_ignore(collection, handle); } template<typename container_collection_type, typename handle_type, typename element_type> void handle_or_ignore( container_collection_type & collection, handle_type & handle, viennagrid::meta::tag<element_type> ) { typedef typename viennagrid::storage::result_of::container_of< container_collection_type, element_type>::type container_type; handle_or_ignore_helper<container_collection_type, handle_type, container_type>::handle_or_ignore(collection, handle); } template<typename container_collection_type> struct clear_all_functor { clear_all_functor( container_collection_type & container_collection_ ) : container_collection(container_collection_) {} template<typename type> void operator() ( viennagrid::meta::tag<type> ) { viennagrid::storage::collection::get<type>( container_collection ).clear(); } container_collection_type & container_collection; }; template<typename container_collection_typemap> void clear_all( collection_t<container_collection_typemap> & container_collection) { clear_all_functor< collection_t<container_collection_typemap> > f( container_collection ); viennagrid::meta::typelist::for_each< typename viennagrid::meta::typemap::result_of::key_typelist<container_collection_typemap>::type >( f ); } } // namespace container_collection namespace result_of { template<typename value_typelist, typename container_config> struct container_collection { typedef collection_t< typename viennagrid::storage::container_collection::result_of::container_list_from_value_typelist_using_container_config< value_typelist, container_config >::type > type; }; } } // namespace storage } // namespace viennagrid #endif <commit_msg>handle_or_ignore needs to use insert_unique_handle instead of insert_handle; multiple instances of the same handle might be within a view when using inserter otherwise<commit_after>#ifndef VIENNAGRID_STORAGE_CONTAINER_COLLECTION_HPP #define VIENNAGRID_STORAGE_CONTAINER_COLLECTION_HPP #include "viennagrid/meta/typelist.hpp" #include "viennagrid/meta/typemap.hpp" #include "viennagrid/meta/algorithm.hpp" #include "viennagrid/storage/container.hpp" #include "viennagrid/storage/collection.hpp" #include "viennagrid/storage/view.hpp" #include "viennagrid/storage/range.hpp" namespace viennagrid { namespace storage { namespace container_collection { namespace result_of { // // generates a typemap with value type and container type from a typelist and a container config // template<typename value_type, typename container_config> struct container_from_value_using_container_config { typedef typename viennagrid::meta::typemap::result_of::find<container_config, value_type>::type search_result; typedef typename viennagrid::meta::typemap::result_of::find<container_config, viennagrid::storage::default_tag>::type default_container; typedef typename viennagrid::meta::IF< !viennagrid::meta::EQUAL<search_result, viennagrid::meta::not_found>::value, search_result, default_container >::type container_tag_pair; typedef typename viennagrid::storage::result_of::container<value_type, typename container_tag_pair::second>::type type; }; template<typename element_list, typename container_config> struct container_list_from_value_typelist_using_container_config; template<typename container_config> struct container_list_from_value_typelist_using_container_config<viennagrid::meta::null_type, container_config> { typedef viennagrid::meta::null_type type; }; template<typename value_type, typename tail, typename container_config> struct container_list_from_value_typelist_using_container_config<viennagrid::meta::typelist_t<value_type, tail>, container_config> { typedef viennagrid::meta::typelist_t< typename viennagrid::meta::static_pair< value_type, typename container_from_value_using_container_config<value_type, container_config>::type >, typename container_list_from_value_typelist_using_container_config<tail, container_config>::type > type; }; } // namespace result_of } // namespace container_collection namespace result_of { template<typename typemap_, typename element_type> struct container_of { typedef typename viennagrid::meta::result_of::second< typename viennagrid::meta::typemap::result_of::find< typemap_, element_type >::type >::type type; }; template<typename typemap_, typename element_type> struct container_of< collection_t< typemap_ >, element_type > { typedef typename container_of<typemap_, element_type>::type type; }; template<typename container_collection_1, typename container_collection_2> struct common_values; template<typename container_typelist_1, typename container_typelist_2> struct common_values< collection_t<container_typelist_1>, collection_t<container_typelist_2> > { typedef collection_t<container_typelist_1> from_container_collection_type; typedef collection_t<container_typelist_2> to_container_collection_type; typedef typename viennagrid::meta::typemap::result_of::key_typelist<typename from_container_collection_type::typemap>::type from_container_collection_value_typelist; typedef typename viennagrid::meta::typemap::result_of::key_typelist<typename to_container_collection_type::typemap>::type to_container_collection_value_typelist; typedef typename viennagrid::meta::typelist::result_of::intersection< from_container_collection_value_typelist, to_container_collection_value_typelist >::type type; }; } // namespace result_of namespace container_collection { typedef viennagrid::meta::make_typemap< viennagrid::storage::default_tag, viennagrid::storage::handled_container_tag<viennagrid::storage::std_deque_tag, viennagrid::storage::pointer_handle_tag> >::type default_container_config; template<typename container_collection_type, typename element_type, typename search_result> struct insert_or_ignore_helper { static void insert_or_ignore( container_collection_type & collection, const element_type & element ) { collection.get( viennagrid::meta::tag<element_type>() ).insert(element); } static void insert_or_ignore( container_collection_type & collection, element_type & element ) { collection.get( viennagrid::meta::tag<element_type>() ).insert(element); } }; template<typename container_collection_type, typename element_type> struct insert_or_ignore_helper<container_collection_type, element_type, viennagrid::meta::not_found> { static void insert_or_ignore( container_collection_type &, const element_type & ) {} static void insert_or_ignore( container_collection_type &, element_type & ) {} }; template<typename container_collection_type, typename element_type> void insert_or_ignore( container_collection_type & collection, const element_type & element) { typedef typename viennagrid::storage::result_of::container_of< container_collection_type, element_type>::type container_type; insert_or_ignore_helper<container_collection_type, element_type, container_type>::insert_or_ignore(collection, element); } template<typename container_collection_type, typename element_type> void insert_or_ignore( container_collection_type & collection, element_type & element) { typedef typename viennagrid::storage::result_of::container_of< container_collection_type, element_type>::type container_type; insert_or_ignore_helper<container_collection_type, element_type, container_type>::insert_or_ignore(collection, element); } template<typename container_collection_type, typename handle_type, typename container_type> struct handle_or_ignore_helper { typedef typename viennagrid::storage::handle::result_of::value_type<handle_type>::type value_type; static void handle_or_ignore( container_collection_type & collection, const handle_type & handle ) { collection.get( viennagrid::meta::tag<value_type>() ).insert_unique_handle(handle); } static void handle_or_ignore( container_collection_type & collection, handle_type & handle ) { collection.get( viennagrid::meta::tag<value_type>() ).insert_unique_handle(handle); } }; template<typename container_collection_type, typename handle_type> struct handle_or_ignore_helper<container_collection_type, handle_type, viennagrid::meta::not_found> { static void handle_or_ignore( container_collection_type &, const handle_type & ) {} static void handle_or_ignore( container_collection_type &, handle_type & ) {} }; template<typename container_collection_type, typename handle_type, typename element_type> void handle_or_ignore( container_collection_type & collection, const handle_type & handle, viennagrid::meta::tag<element_type> ) { typedef typename viennagrid::storage::result_of::container_of< container_collection_type, element_type>::type container_type; handle_or_ignore_helper<container_collection_type, handle_type, container_type>::handle_or_ignore(collection, handle); } template<typename container_collection_type, typename handle_type, typename element_type> void handle_or_ignore( container_collection_type & collection, handle_type & handle, viennagrid::meta::tag<element_type> ) { typedef typename viennagrid::storage::result_of::container_of< container_collection_type, element_type>::type container_type; handle_or_ignore_helper<container_collection_type, handle_type, container_type>::handle_or_ignore(collection, handle); } template<typename container_collection_type> struct clear_all_functor { clear_all_functor( container_collection_type & container_collection_ ) : container_collection(container_collection_) {} template<typename type> void operator() ( viennagrid::meta::tag<type> ) { viennagrid::storage::collection::get<type>( container_collection ).clear(); } container_collection_type & container_collection; }; template<typename container_collection_typemap> void clear_all( collection_t<container_collection_typemap> & container_collection) { clear_all_functor< collection_t<container_collection_typemap> > f( container_collection ); viennagrid::meta::typelist::for_each< typename viennagrid::meta::typemap::result_of::key_typelist<container_collection_typemap>::type >( f ); } } // namespace container_collection namespace result_of { template<typename value_typelist, typename container_config> struct container_collection { typedef collection_t< typename viennagrid::storage::container_collection::result_of::container_list_from_value_typelist_using_container_config< value_typelist, container_config >::type > type; }; } } // namespace storage } // namespace viennagrid #endif <|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/views/tab_contents/native_tab_contents_container_aura.h" #include "chrome/browser/ui/view_ids.h" #include "chrome/browser/ui/views/tab_contents/native_tab_contents_container_views.h" #include "chrome/browser/ui/views/tab_contents/tab_contents_container.h" #include "chrome/browser/ui/views/tab_contents/tab_contents_view_views.h" #include "content/browser/tab_contents/interstitial_page.h" #include "content/browser/tab_contents/tab_contents.h" #include "ui/aura/window.h" #include "ui/base/accessibility/accessible_view_state.h" #include "views/views_delegate.h" #include "views/focus/focus_manager.h" #include "views/focus/widget_focus_manager.h" //////////////////////////////////////////////////////////////////////////////// // NativeTabContentsContainerAura, public: NativeTabContentsContainerAura::NativeTabContentsContainerAura( TabContentsContainer* container) : container_(container) { set_id(VIEW_ID_TAB_CONTAINER_FOCUS_VIEW); } NativeTabContentsContainerAura::~NativeTabContentsContainerAura() { } //////////////////////////////////////////////////////////////////////////////// // NativeTabContentsContainerAura, NativeTabContentsContainer overrides: void NativeTabContentsContainerAura::AttachContents(TabContents* contents) { // We need to register the tab contents window with the BrowserContainer so // that the BrowserContainer is the focused view when the focus is on the // TabContents window (for the TabContents case). set_focus_view(this); Attach(contents->GetNativeView()); } void NativeTabContentsContainerAura::DetachContents(TabContents* contents) { // Detach the TabContents. Do this before we unparent the // TabContentsViewViews so that the window hierarchy is intact for any // cleanup during Detach(). Detach(); } void NativeTabContentsContainerAura::SetFastResize(bool fast_resize) { NOTIMPLEMENTED(); } void NativeTabContentsContainerAura::RenderViewHostChanged( RenderViewHost* old_host, RenderViewHost* new_host) { // If we are focused, we need to pass the focus to the new RenderViewHost. if (GetFocusManager()->GetFocusedView() == this) OnFocus(); } views::View* NativeTabContentsContainerAura::GetView() { return this; } void NativeTabContentsContainerAura::TabContentsFocused( TabContents* tab_contents) { views::FocusManager* focus_manager = GetFocusManager(); if (!focus_manager) { NOTREACHED(); return; } focus_manager->SetFocusedView(this); } //////////////////////////////////////////////////////////////////////////////// // NativeTabContentsContainerAura, views::View overrides: bool NativeTabContentsContainerAura::SkipDefaultKeyEventProcessing( const views::KeyEvent& e) { // Don't look-up accelerators or tab-traversal if we are showing a non-crashed // TabContents. // We'll first give the page a chance to process the key events. If it does // not process them, they'll be returned to us and we'll treat them as // accelerators then. return container_->tab_contents() && !container_->tab_contents()->is_crashed(); } bool NativeTabContentsContainerAura::IsFocusable() const { // We need to be focusable when our contents is not a view hierarchy, as // clicking on the contents needs to focus us. return container_->tab_contents() != NULL; } void NativeTabContentsContainerAura::OnFocus() { if (container_->tab_contents()) container_->tab_contents()->Focus(); } void NativeTabContentsContainerAura::RequestFocus() { // This is a hack to circumvent the fact that a the OnFocus() method is not // invoked when RequestFocus() is called on an already focused view. // The TabContentsContainer is the view focused when the TabContents has // focus. When switching between from one tab that has focus to another tab // that should also have focus, RequestFocus() is invoked one the // TabContentsContainer. In order to make sure OnFocus() is invoked we need // to clear the focus before hands. { // Disable notifications. Clear focus will assign the focus to the main // browser window. Because this change of focus was not user requested, // don't send it to listeners. views::AutoNativeNotificationDisabler local_notification_disabler; GetFocusManager()->ClearFocus(); } View::RequestFocus(); } void NativeTabContentsContainerAura::AboutToRequestFocusFromTabTraversal( bool reverse) { container_->tab_contents()->FocusThroughTabTraversal(reverse); } void NativeTabContentsContainerAura::GetAccessibleState( ui::AccessibleViewState* state) { state->role = ui::AccessibilityTypes::ROLE_GROUPING; } gfx::NativeViewAccessible NativeTabContentsContainerAura::GetNativeViewAccessible() { // TODO(beng): NOTIMPLEMENTED(); return View::GetNativeViewAccessible(); } //////////////////////////////////////////////////////////////////////////////// // NativeTabContentsContainer, public: // static NativeTabContentsContainer* NativeTabContentsContainer::CreateNativeContainer( TabContentsContainer* container) { // return new NativeTabContentsContainerViews(container); // TODO(beng): switch this over once we're using this container. return new NativeTabContentsContainerAura(container); } <commit_msg>aura: Keep using the non-aura RWHV stuff for touchui.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/views/tab_contents/native_tab_contents_container_aura.h" #include "chrome/browser/ui/view_ids.h" #include "chrome/browser/ui/views/tab_contents/native_tab_contents_container_views.h" #include "chrome/browser/ui/views/tab_contents/tab_contents_container.h" #include "chrome/browser/ui/views/tab_contents/tab_contents_view_views.h" #include "content/browser/tab_contents/interstitial_page.h" #include "content/browser/tab_contents/tab_contents.h" #include "ui/aura/window.h" #include "ui/base/accessibility/accessible_view_state.h" #include "views/views_delegate.h" #include "views/focus/focus_manager.h" #include "views/focus/widget_focus_manager.h" //////////////////////////////////////////////////////////////////////////////// // NativeTabContentsContainerAura, public: NativeTabContentsContainerAura::NativeTabContentsContainerAura( TabContentsContainer* container) : container_(container) { set_id(VIEW_ID_TAB_CONTAINER_FOCUS_VIEW); } NativeTabContentsContainerAura::~NativeTabContentsContainerAura() { } //////////////////////////////////////////////////////////////////////////////// // NativeTabContentsContainerAura, NativeTabContentsContainer overrides: void NativeTabContentsContainerAura::AttachContents(TabContents* contents) { // We need to register the tab contents window with the BrowserContainer so // that the BrowserContainer is the focused view when the focus is on the // TabContents window (for the TabContents case). set_focus_view(this); Attach(contents->GetNativeView()); } void NativeTabContentsContainerAura::DetachContents(TabContents* contents) { // Detach the TabContents. Do this before we unparent the // TabContentsViewViews so that the window hierarchy is intact for any // cleanup during Detach(). Detach(); } void NativeTabContentsContainerAura::SetFastResize(bool fast_resize) { NOTIMPLEMENTED(); } void NativeTabContentsContainerAura::RenderViewHostChanged( RenderViewHost* old_host, RenderViewHost* new_host) { // If we are focused, we need to pass the focus to the new RenderViewHost. if (GetFocusManager()->GetFocusedView() == this) OnFocus(); } views::View* NativeTabContentsContainerAura::GetView() { return this; } void NativeTabContentsContainerAura::TabContentsFocused( TabContents* tab_contents) { views::FocusManager* focus_manager = GetFocusManager(); if (!focus_manager) { NOTREACHED(); return; } focus_manager->SetFocusedView(this); } //////////////////////////////////////////////////////////////////////////////// // NativeTabContentsContainerAura, views::View overrides: bool NativeTabContentsContainerAura::SkipDefaultKeyEventProcessing( const views::KeyEvent& e) { // Don't look-up accelerators or tab-traversal if we are showing a non-crashed // TabContents. // We'll first give the page a chance to process the key events. If it does // not process them, they'll be returned to us and we'll treat them as // accelerators then. return container_->tab_contents() && !container_->tab_contents()->is_crashed(); } bool NativeTabContentsContainerAura::IsFocusable() const { // We need to be focusable when our contents is not a view hierarchy, as // clicking on the contents needs to focus us. return container_->tab_contents() != NULL; } void NativeTabContentsContainerAura::OnFocus() { if (container_->tab_contents()) container_->tab_contents()->Focus(); } void NativeTabContentsContainerAura::RequestFocus() { // This is a hack to circumvent the fact that a the OnFocus() method is not // invoked when RequestFocus() is called on an already focused view. // The TabContentsContainer is the view focused when the TabContents has // focus. When switching between from one tab that has focus to another tab // that should also have focus, RequestFocus() is invoked one the // TabContentsContainer. In order to make sure OnFocus() is invoked we need // to clear the focus before hands. { // Disable notifications. Clear focus will assign the focus to the main // browser window. Because this change of focus was not user requested, // don't send it to listeners. views::AutoNativeNotificationDisabler local_notification_disabler; GetFocusManager()->ClearFocus(); } View::RequestFocus(); } void NativeTabContentsContainerAura::AboutToRequestFocusFromTabTraversal( bool reverse) { container_->tab_contents()->FocusThroughTabTraversal(reverse); } void NativeTabContentsContainerAura::GetAccessibleState( ui::AccessibleViewState* state) { state->role = ui::AccessibilityTypes::ROLE_GROUPING; } gfx::NativeViewAccessible NativeTabContentsContainerAura::GetNativeViewAccessible() { // TODO(beng): NOTIMPLEMENTED(); return View::GetNativeViewAccessible(); } //////////////////////////////////////////////////////////////////////////////// // NativeTabContentsContainer, public: // static NativeTabContentsContainer* NativeTabContentsContainer::CreateNativeContainer( TabContentsContainer* container) { #if defined(TOUCH_UI) return new NativeTabContentsContainerViews(container); #else // TODO(beng): switch this over once we're using this container. return new NativeTabContentsContainerAura(container); #endif } <|endoftext|>
<commit_before>#include "ColorCoordinator.h" ColorCoordinator::olorCoordinator() { _red_mgr = ColorManager(); _grn_mgr = ColorManager(); _blu_mgr = ColorManager(); } void ColorCoordinator::colorTouch(uint8_t aColor) { switch( aColor ) { case RED: { _red_mgr.touch(_baseline_color.red); break; } case GREEN: { _grn_mgr.touch(_baseline_color.green); break; } case BLUE: { _blu_mgr.touch(_baseline_color.blue); } } } void ColorCoordinator::colorRelease(uint8_t aColor) { switch( aColor ) { case RED: { _red_mgr.release(); break; } case GREEN: { _grn_mgr.release(); break; } case BLUE: { _blu_mgr.release(); break; } } } void ColorCoordinator::update() { _red_mgr.update(); _grn_mgr.update(); _blu_mgr.update(); } void ColorCoordinator::setBaselineColor(CRGB aColor) { _baseline_color = aColor; } CRGB ChairAffair_ColorCoordinator::drivingColor() { return CRGB(_red_mgr.value(), _grn_mgr.value(), _blu_mgr.value()); }<commit_msg>Fixed name of constructor<commit_after>#include "ColorCoordinator.h" ColorCoordinator::ColorCoordinator() { _red_mgr = ColorManager(); _grn_mgr = ColorManager(); _blu_mgr = ColorManager(); } void ColorCoordinator::colorTouch(uint8_t aColor) { switch( aColor ) { case RED: { _red_mgr.touch(_baseline_color.red); break; } case GREEN: { _grn_mgr.touch(_baseline_color.green); break; } case BLUE: { _blu_mgr.touch(_baseline_color.blue); } } } void ColorCoordinator::colorRelease(uint8_t aColor) { switch( aColor ) { case RED: { _red_mgr.release(); break; } case GREEN: { _grn_mgr.release(); break; } case BLUE: { _blu_mgr.release(); break; } } } void ColorCoordinator::update() { _red_mgr.update(); _grn_mgr.update(); _blu_mgr.update(); } void ColorCoordinator::setBaselineColor(CRGB aColor) { _baseline_color = aColor; } CRGB ChairAffair_ColorCoordinator::drivingColor() { return CRGB(_red_mgr.value(), _grn_mgr.value(), _blu_mgr.value()); }<|endoftext|>
<commit_before><?hh // partial namespace package\examples; require_once __DIR__ . '/../vendor/autoload.php'; use package\Package; $params = shape( 'namespace' => 'package\\examples\\classes\\', 'packageDirectory' => realpath(__DIR__ . '/src') ); $package = new Package($params); foreach ($package->getClassFiles() as $class) { $instance = $class->instantiate(); var_dump($instance); } <commit_msg>Update eample<commit_after><?hh // partial namespace package\examples; require_once __DIR__ . '/../vendor/autoload.php'; use package\Package; $package = Package::fromOptions(shape( 'namespace' => 'package\\examples\\classes\\', 'packageDirectory' => realpath(__DIR__ . '/src') )); foreach ($package->getClassFiles() as $class) { $instance = $class->instantiate(); var_dump($instance); } <|endoftext|>
<commit_before>/****************************************************************************** * SOFA, Simulation Open-Framework Architecture, development version * * (c) 2006-2016 INRIA, USTL, UJF, CNRS, MGH * * * * 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. * ******************************************************************************* * SOFA :: Framework * * * * Authors: The SOFA Team (see Authors.txt) * * * * Contact information: [email protected] * ******************************************************************************/ #include <sofa/helper/BackTrace.h> #if !defined(WIN32) && !defined(_XBOX) && !defined(PS3) #include <signal.h> #endif #if !defined(WIN32) && !defined(_XBOX) && !defined(__APPLE__) && !defined(PS3) #include <execinfo.h> #include <unistd.h> #endif #if defined(__GNUC__) && !defined(PS3) #include <cxxabi.h> #endif #include <cstdio> #include <cstdlib> #include <cstring> namespace sofa { namespace helper { /// Dump current backtrace to stderr. /// Currently only works on Linux. NOOP on other architectures. void BackTrace::dump() { #if defined(__GNUC__) && !defined(__APPLE__) && !defined(WIN32) && !defined(_XBOX) && !defined(PS3) void *array[128]; int size = backtrace(array, sizeof(array) / sizeof(array[0])); if (size > 0) { char** symbols = backtrace_symbols(array, size); if (symbols != NULL) { for (int i = 0; i < size; ++i) { char* symbol = symbols[i]; // Decode the method's name to a more readable form if possible char *beginmangled = strrchr(symbol,'('); if (beginmangled != NULL) { ++beginmangled; char *endmangled = strrchr(beginmangled ,')'); if (endmangled != NULL) { // remove +0x[0-9a-fA-f]* suffix char* savedend = endmangled; while((endmangled[-1]>='0' && endmangled[-1]<='9') || (endmangled[-1]>='a' && endmangled[-1]<='f') || (endmangled[-1]>='A' && endmangled[-1]<='F')) --endmangled; if (endmangled[-1]=='x' && endmangled[-2]=='0' && endmangled[-3]=='+') endmangled -= 3; else endmangled = savedend; // suffix not found char* name = (char*)malloc(endmangled-beginmangled+1); memcpy(name, beginmangled, endmangled-beginmangled); name[endmangled-beginmangled] = '\0'; int status; char* realname = abi::__cxa_demangle(name, 0, 0, &status); if (realname != NULL) { free(name); name = realname; } fprintf(stderr,"-> %.*s%s%s\n",(int)(beginmangled-symbol),symbol,name,endmangled); free(name); } else fprintf(stderr,"-> %s\n",symbol); } else fprintf(stderr,"-> %s\n",symbol); } free(symbols); } else { backtrace_symbols_fd(array, size, STDERR_FILENO); } } #endif } /// Enable dump of backtrace when a signal is received. /// Useful to have information about crashes without starting a debugger (as it is not always easy to do, i.e. for parallel/distributed applications). /// Currently only works on Linux. NOOP on other architectures void BackTrace::autodump() { #if !defined(WIN32) && !defined(_XBOX) && !defined(PS3) signal(SIGSEGV, BackTrace::sig); signal(SIGILL, BackTrace::sig); signal(SIGFPE, BackTrace::sig); signal(SIGPIPE, BackTrace::sig); signal(SIGINT, BackTrace::sig); signal(SIGTERM, BackTrace::sig); #endif } void BackTrace::sig(int sig) { #if !defined(WIN32) && !defined(_XBOX) && !defined(PS3) fprintf(stderr,"\n########## SIG %d ##########\n",sig); dump(); signal(sig,SIG_DFL); raise(sig); #else fprintf(stderr,"\nERROR: BackTrace::sig(%d) not supported.\n",sig); #endif } } // namespace helper } // namespace sofa <commit_msg>ADD: Backtrace::dump() implementation for Windows<commit_after>/****************************************************************************** * SOFA, Simulation Open-Framework Architecture, development version * * (c) 2006-2016 INRIA, USTL, UJF, CNRS, MGH * * * * 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. * ******************************************************************************* * SOFA :: Framework * * * * Authors: The SOFA Team (see Authors.txt) * * * * Contact information: [email protected] * ******************************************************************************/ #include <sofa/helper/BackTrace.h> #if !defined(_XBOX) && !defined(PS3) #include <signal.h> #endif #if !defined(WIN32) && !defined(_XBOX) && !defined(__APPLE__) && !defined(PS3) #include <execinfo.h> #include <unistd.h> #endif #if defined(WIN32) #include "windows.h" #include "DbgHelp.h" #pragma comment(lib, "Dbghelp.lib") #endif #if defined(__GNUC__) && !defined(PS3) #include <cxxabi.h> #endif #include <iostream> #include <string> namespace sofa { namespace helper { /// Dump current backtrace to stderr. /// Currently only works on Linux. NOOP on other architectures. void BackTrace::dump() { #if defined(__GNUC__) && !defined(__APPLE__) && !defined(WIN32) && !defined(_XBOX) && !defined(PS3) void *array[128]; int size = backtrace(array, sizeof(array) / sizeof(array[0])); if (size > 0) { char** symbols = backtrace_symbols(array, size); if (symbols != NULL) { for (int i = 0; i < size; ++i) { char* symbol = symbols[i]; // Decode the method's name to a more readable form if possible char *beginmangled = strrchr(symbol,'('); if (beginmangled != NULL) { ++beginmangled; char *endmangled = strrchr(beginmangled ,')'); if (endmangled != NULL) { // remove +0x[0-9a-fA-f]* suffix char* savedend = endmangled; while((endmangled[-1]>='0' && endmangled[-1]<='9') || (endmangled[-1]>='a' && endmangled[-1]<='f') || (endmangled[-1]>='A' && endmangled[-1]<='F')) --endmangled; if (endmangled[-1]=='x' && endmangled[-2]=='0' && endmangled[-3]=='+') endmangled -= 3; else endmangled = savedend; // suffix not found char* name = (char*)malloc(endmangled-beginmangled+1); memcpy(name, beginmangled, endmangled-beginmangled); name[endmangled-beginmangled] = '\0'; int status; char* realname = abi::__cxa_demangle(name, 0, 0, &status); if (realname != NULL) { free(name); name = realname; } fprintf(stderr,"-> %.*s%s%s\n",(int)(beginmangled-symbol),symbol,name,endmangled); free(name); } else fprintf(stderr,"-> %s\n",symbol); } else fprintf(stderr,"-> %s\n",symbol); } free(symbols); } else { backtrace_symbols_fd(array, size, STDERR_FILENO); } } #else #if !defined(__GNUC__) && !defined(__APPLE__) && defined(WIN32) && !defined(_XBOX) && !defined(PS3) unsigned int i; void * stack[100]; unsigned short frames; SYMBOL_INFO * symbol; HANDLE process; process = GetCurrentProcess(); SymInitialize(process, NULL, TRUE); frames = CaptureStackBackTrace(0, 100, stack, NULL); symbol = (SYMBOL_INFO *)calloc(sizeof(SYMBOL_INFO) + 256 * sizeof(char), 1); symbol->MaxNameLen = 255; symbol->SizeOfStruct = sizeof(SYMBOL_INFO); for (i = 0; i < frames; i++) { SymFromAddr(process, (DWORD64)(stack[i]), 0, symbol); std::cerr << (frames - i - 1) << ": " << symbol->Name << " - 0x" << std::hex << symbol->Address << std::dec << std::endl; } free(symbol); #endif } /// Enable dump of backtrace when a signal is received. /// Useful to have information about crashes without starting a debugger (as it is not always easy to do, i.e. for parallel/distributed applications). /// Currently only works on Linux. NOOP on other architectures void BackTrace::autodump() { #if !defined(_XBOX) && !defined(PS3) signal(SIGABRT, BackTrace::sig); signal(SIGSEGV, BackTrace::sig); signal(SIGILL, BackTrace::sig); signal(SIGFPE, BackTrace::sig); signal(SIGINT, BackTrace::sig); signal(SIGTERM, BackTrace::sig); #if !defined(WIN32) signal(SIGPIPE, BackTrace::sig); #endif #endif } static std::string SigDescription(int sig) { switch (sig) { case SIGABRT: return "SIGABRT: usually caused by an abort() or assert()"; break; case SIGFPE: return "SIGFPE: arithmetic exception, such as divide by zero"; break; case SIGILL: return "SIGILL: illegal instruction"; break; case SIGINT: return "SIGINT: interactive attention signal, probably a ctrl+c"; break; case SIGSEGV: return "SIGSEGV: segfault"; break; case SIGTERM: default: return "SIGTERM: a termination request was sent to the program"; break; } return "Unknown signal"; } void BackTrace::sig(int sig) { #if !defined(_XBOX) && !defined(PS3) std::cerr << std::endl << "########## SIG " << sig << " - " << SigDescription(sig) << " ##########" << std::endl; dump(); signal(sig,SIG_DFL); raise(sig); #else std::cerr << std::endl << "ERROR: BackTrace::sig(" << sig << " - " << SigDescription(sig) << ") not supported." << std::endl; #endif } } // namespace helper } // namespace sofa <|endoftext|>
<commit_before>#include "vm.hpp" #include "shared_state.hpp" #include "config_parser.hpp" #include "config.h" #include "objectmemory.hpp" #include "environment.hpp" #include "instruments/tooling.hpp" #include "instruments/timing.hpp" #include "global_cache.hpp" #include "capi/handle.hpp" #include "util/thread.hpp" #include "inline_cache.hpp" #include "configuration.hpp" #include "agent.hpp" #include "world_state.hpp" #ifdef ENABLE_LLVM #include "llvm/state.hpp" #endif namespace rubinius { SharedState::SharedState(Environment* env, Configuration& config, ConfigParser& cp) : initialized_(false) , signal_handler_(0) , global_handles_(new capi::Handles) , cached_handles_(new capi::Handles) , global_serial_(0) , world_(new WorldState) , ic_registry_(new InlineCacheRegistry) , class_count_(0) , thread_ids_(0) , agent_(0) , root_vm_(0) , env_(env) , tool_broker_(new tooling::ToolBroker) , ruby_critical_set_(false) , check_gc_(false) , om(0) , global_cache(new GlobalCache) , config(config) , user_variables(cp) , llvm_state(0) { ref(); for(int i = 0; i < Primitives::cTotalPrimitives; i++) { primitive_hits_[i] = 0; } } SharedState::~SharedState() { if(!initialized_) return; if(config.gc_show) { std::cerr << "Time spenting waiting: " << world_->time_waiting() << "\n"; } #ifdef ENABLE_LLVM if(llvm_state) { delete llvm_state; } #endif delete tool_broker_; delete world_; delete ic_registry_; delete om; delete global_cache; delete global_handles_; delete cached_handles_; if(agent_) { delete agent_; } } void SharedState::add_managed_thread(ManagedThread* thr) { SYNC_TL; threads_.push_back(thr); } void SharedState::remove_managed_thread(ManagedThread* thr) { SYNC_TL; threads_.remove(thr); } int SharedState::size() { return sizeof(SharedState) + sizeof(WorldState) + symbols.byte_size(); } void SharedState::discard(SharedState* ss) { if(ss->deref()) delete ss; } uint32_t SharedState::new_thread_id() { SYNC_TL; return ++thread_ids_; } VM* SharedState::new_vm() { uint32_t id = new_thread_id(); SYNC_TL; // TODO calculate the thread id by finding holes in the // field of ids, so we reuse ids. VM* vm = new VM(id, *this); threads_.push_back(vm); this->ref(); // If there is no root vm, then the first one created becomes it. if(!root_vm_) root_vm_ = vm; return vm; } void SharedState::remove_vm(VM* vm) { SYNC_TL; this->deref(); // Don't delete ourself here, it's too problematic. } void SharedState::add_global_handle(STATE, capi::Handle* handle) { SYNC(state); global_handles_->add(handle); } void SharedState::make_handle_cached(STATE, capi::Handle* handle) { SYNC(state); global_handles_->move(handle, cached_handles_); } QueryAgent* SharedState::autostart_agent(STATE) { SYNC(state); if(agent_) return agent_; agent_ = new QueryAgent(*this, state); return agent_; } void SharedState::pre_exec() { SYNC_TL; if(agent_) agent_->cleanup(); } void SharedState::reinit(STATE) { // For now, we disable inline debugging here. This makes inspecting // it much less confusing. config.jit_inline_debug.set("no"); env_->state = state; threads_.clear(); threads_.push_back(state->vm()); // Reinit the locks for this object lock_init(state->vm()); global_cache->lock_init(state->vm()); ic_registry_->lock_init(state->vm()); onig_lock_.init(); ruby_critical_lock_.init(); capi_lock_.init(); world_->reinit(); if(agent_) { agent_->on_fork(); delete agent_; agent_ = 0; } } bool SharedState::should_stop() { return world_->should_stop(); } bool SharedState::stop_the_world(THREAD) { return world_->wait_til_alone(state); } void SharedState::stop_threads_externally() { world_->stop_threads_externally(); } void SharedState::restart_world(THREAD) { world_->wake_all_waiters(state); } void SharedState::restart_threads_externally() { world_->restart_threads_externally(); } bool SharedState::checkpoint(THREAD) { return world_->checkpoint(state); } void SharedState::gc_dependent(STATE) { world_->become_dependent(state->vm()); } void SharedState::gc_independent(STATE) { world_->become_independent(state->vm()); } void SharedState::gc_dependent(THREAD) { world_->become_dependent(state); } void SharedState::gc_independent(THREAD) { world_->become_independent(state); } void SharedState::set_critical(STATE) { SYNC(state); if(!ruby_critical_set_ || !pthread_equal(ruby_critical_thread_, pthread_self())) { UNSYNC; GCIndependent gc_guard(state); ruby_critical_lock_.lock(); ruby_critical_thread_ = pthread_self(); ruby_critical_set_ = true; } return; } void SharedState::clear_critical(STATE) { SYNC(state); if(ruby_critical_set_ && pthread_equal(ruby_critical_thread_, pthread_self())) { ruby_critical_set_ = false; ruby_critical_lock_.unlock(); } } void SharedState::enter_capi(STATE, const char* file, int line) { capi_lock_.lock(state->vm(), file, line); } void SharedState::leave_capi(STATE) { capi_lock_.unlock(state->vm()); } } <commit_msg>Minor correction to typo<commit_after>#include "vm.hpp" #include "shared_state.hpp" #include "config_parser.hpp" #include "config.h" #include "objectmemory.hpp" #include "environment.hpp" #include "instruments/tooling.hpp" #include "instruments/timing.hpp" #include "global_cache.hpp" #include "capi/handle.hpp" #include "util/thread.hpp" #include "inline_cache.hpp" #include "configuration.hpp" #include "agent.hpp" #include "world_state.hpp" #ifdef ENABLE_LLVM #include "llvm/state.hpp" #endif namespace rubinius { SharedState::SharedState(Environment* env, Configuration& config, ConfigParser& cp) : initialized_(false) , signal_handler_(0) , global_handles_(new capi::Handles) , cached_handles_(new capi::Handles) , global_serial_(0) , world_(new WorldState) , ic_registry_(new InlineCacheRegistry) , class_count_(0) , thread_ids_(0) , agent_(0) , root_vm_(0) , env_(env) , tool_broker_(new tooling::ToolBroker) , ruby_critical_set_(false) , check_gc_(false) , om(0) , global_cache(new GlobalCache) , config(config) , user_variables(cp) , llvm_state(0) { ref(); for(int i = 0; i < Primitives::cTotalPrimitives; i++) { primitive_hits_[i] = 0; } } SharedState::~SharedState() { if(!initialized_) return; if(config.gc_show) { std::cerr << "Time spent waiting: " << world_->time_waiting() << "\n"; } #ifdef ENABLE_LLVM if(llvm_state) { delete llvm_state; } #endif delete tool_broker_; delete world_; delete ic_registry_; delete om; delete global_cache; delete global_handles_; delete cached_handles_; if(agent_) { delete agent_; } } void SharedState::add_managed_thread(ManagedThread* thr) { SYNC_TL; threads_.push_back(thr); } void SharedState::remove_managed_thread(ManagedThread* thr) { SYNC_TL; threads_.remove(thr); } int SharedState::size() { return sizeof(SharedState) + sizeof(WorldState) + symbols.byte_size(); } void SharedState::discard(SharedState* ss) { if(ss->deref()) delete ss; } uint32_t SharedState::new_thread_id() { SYNC_TL; return ++thread_ids_; } VM* SharedState::new_vm() { uint32_t id = new_thread_id(); SYNC_TL; // TODO calculate the thread id by finding holes in the // field of ids, so we reuse ids. VM* vm = new VM(id, *this); threads_.push_back(vm); this->ref(); // If there is no root vm, then the first one created becomes it. if(!root_vm_) root_vm_ = vm; return vm; } void SharedState::remove_vm(VM* vm) { SYNC_TL; this->deref(); // Don't delete ourself here, it's too problematic. } void SharedState::add_global_handle(STATE, capi::Handle* handle) { SYNC(state); global_handles_->add(handle); } void SharedState::make_handle_cached(STATE, capi::Handle* handle) { SYNC(state); global_handles_->move(handle, cached_handles_); } QueryAgent* SharedState::autostart_agent(STATE) { SYNC(state); if(agent_) return agent_; agent_ = new QueryAgent(*this, state); return agent_; } void SharedState::pre_exec() { SYNC_TL; if(agent_) agent_->cleanup(); } void SharedState::reinit(STATE) { // For now, we disable inline debugging here. This makes inspecting // it much less confusing. config.jit_inline_debug.set("no"); env_->state = state; threads_.clear(); threads_.push_back(state->vm()); // Reinit the locks for this object lock_init(state->vm()); global_cache->lock_init(state->vm()); ic_registry_->lock_init(state->vm()); onig_lock_.init(); ruby_critical_lock_.init(); capi_lock_.init(); world_->reinit(); if(agent_) { agent_->on_fork(); delete agent_; agent_ = 0; } } bool SharedState::should_stop() { return world_->should_stop(); } bool SharedState::stop_the_world(THREAD) { return world_->wait_til_alone(state); } void SharedState::stop_threads_externally() { world_->stop_threads_externally(); } void SharedState::restart_world(THREAD) { world_->wake_all_waiters(state); } void SharedState::restart_threads_externally() { world_->restart_threads_externally(); } bool SharedState::checkpoint(THREAD) { return world_->checkpoint(state); } void SharedState::gc_dependent(STATE) { world_->become_dependent(state->vm()); } void SharedState::gc_independent(STATE) { world_->become_independent(state->vm()); } void SharedState::gc_dependent(THREAD) { world_->become_dependent(state); } void SharedState::gc_independent(THREAD) { world_->become_independent(state); } void SharedState::set_critical(STATE) { SYNC(state); if(!ruby_critical_set_ || !pthread_equal(ruby_critical_thread_, pthread_self())) { UNSYNC; GCIndependent gc_guard(state); ruby_critical_lock_.lock(); ruby_critical_thread_ = pthread_self(); ruby_critical_set_ = true; } return; } void SharedState::clear_critical(STATE) { SYNC(state); if(ruby_critical_set_ && pthread_equal(ruby_critical_thread_, pthread_self())) { ruby_critical_set_ = false; ruby_critical_lock_.unlock(); } } void SharedState::enter_capi(STATE, const char* file, int line) { capi_lock_.lock(state->vm(), file, line); } void SharedState::leave_capi(STATE) { capi_lock_.unlock(state->vm()); } } <|endoftext|>
<commit_before>/////////////////////////////////////////////////////////////////////// // // // MongBlog - Superfast simple blogging platform // // Blog Class // // (c) 2010 Michael Cullen http://cullen-online.com // // Released under the BSD licence as define in the // // accompanying LICENCE file. Please read it :-) // // // /////////////////////////////////////////////////////////////////////// #include "Blog.hpp" #include <vector> #include <iostream> #include <sstream> #include <boost/algorithm/string.hpp> using std::string; using std::fstream; using std::ios_base; using std::stringstream; using std::vector; using std::cout; using std::endl; using namespace cgicc; using namespace boost; Blog::~Blog() { if(templ) delete templ; if(storage) delete storage; } void Blog::urlDeEncode(string &str) { str = templ->substitute(str,"+"," "); str = templ->substitute(str,"%27","'"); str = templ->substitute(str,"%0A","\n"); str = templ->substitute(str,"%0D","\r"); str = templ->substitute(str,"%2B","+"); str = templ->substitute(str,"%24","$"); str = templ->substitute(str,"%26","&"); str = templ->substitute(str,"%2C",","); str = templ->substitute(str,"%2F","/"); str = templ->substitute(str,"%3A",":"); str = templ->substitute(str,"%3B",";"); str = templ->substitute(str,"%3D","="); str = templ->substitute(str,"%3F","?"); str = templ->substitute(str,"%40","@"); str = templ->substitute(str,"%20"," "); str = templ->substitute(str,"%22","\""); str = templ->substitute(str,"%3C","<"); str = templ->substitute(str,"%3E",">"); str = templ->substitute(str,"%23","#"); str = templ->substitute(str,"%28","("); str = templ->substitute(str,"%29",")"); str = templ->substitute(str,"%7B","{"); str = templ->substitute(str,"%7D","}"); str = templ->substitute(str,"%5C","|"); str = templ->substitute(str,"%5E","^"); str = templ->substitute(str,"%7E","~"); str = templ->substitute(str,"%5B","["); str = templ->substitute(str,"%5D","]"); str = templ->substitute(str,"%60","`"); str = templ->substitute(str,"%21","!"); str = templ->substitute(str,"%25","%"); } //constructor that uses a config file Blog::Blog(std::string config) { templatename = "hahaha"; pagetitle = "MongoBlog"; fstream file; string line; file.open(config.c_str(),ios_base::in); while(file >> line) { int pos = line.find(':',0); string name = line.substr(0,pos); string val = line.substr(pos+1); if(!name.compare("hostname")) { dbserver = val; } else if(!name.compare("database")) { database = val; } else if(!name.compare("uname")) { dbuser = val; } else if(!name.compare("password")) { dbpassword = val; } else if(!name.compare("useauth")) { stringstream thisval(val); thisval >> dbauth; } } file.close(); //cout << "Read:" <<endl << "hostname: " << dbserver << " database: " << database <<endl << "uname: " << dbuser << " useauth: " << dbauth <<endl; init(); } void Blog::init() { //check for post things CgiEnvironment env = cgi.getEnvironment(); storage = new StorageEngine(dbserver,database,dbuser,dbpassword); string post = env.getPostData(); vector<key_val> kvpairs = parseargs(post); vector<key_val>::iterator it; bool headers_sent = false; for(it=kvpairs.begin();it<kvpairs.end();it++) { //is it a login attempt? if(!it->key.compare("user")) { flush(cout); login_proc(kvpairs); headers_sent = true; } //is it a post? else if(!it->key.compare("body")) { if(admin_cookie()) { post_proc(kvpairs); } } } if(!headers_sent) cout << HTTPHTMLHeader(); //storage is after header so any error messages get outputted //if there is no servername, and no auth, use this. templ = new Template(templatename); templ->set_page_title(pagetitle); } void Blog::post_proc(vector<key_val> kvpairs) { string title; string body; bool update = false; string oid; vector<key_val>::iterator it; for(it=kvpairs.begin();it<kvpairs.end();it++) { if(!it->key.compare("title")) { title = it->value; urlDeEncode(title); } else if(!it->key.compare("body")) { body = it->value; urlDeEncode(body); } else if(!it->key.compare("id")) { oid = it->value; urlDeEncode(oid); if(oid.length() > 0) update = true; } } if(body.length() > 0) { if(update) { storage->dopost(title,body,oid); } else { storage->dopost(title,body); } } } void Blog::login_proc(vector<key_val> kvpairs) { string user; string password; flush(cout); vector<key_val>::iterator it; for(it=kvpairs.begin();it<kvpairs.end();it++) { if(!it->key.compare("user")) { user = it->value; } else if(!it->key.compare("pass")) { password = it->value; } } //make sure it's at least sort of worked if(user.length() > 0) { flush(cout); string cookie = storage->login(user,password); flush(cout); //if login didn't fail if(cookie.length() > 0) { cout << HTTPHTMLHeader().setCookie(HTTPCookie("MongoBlogUser",cookie,"","",0,"",0)); recentcookie = cookie; flush(cout); } else cout << HTTPHTMLHeader(); } flush(cout); exit(0); } void Blog::homepage() { templ->render_head(); vector<post> posts = storage->getposts(); if(posts.size() == 0) { templ->render_post("Post not found","There are no posts here."); } else { vector<post>::iterator pit; for(pit=posts.begin();pit!= posts.end();pit++) { stringstream titlelink; //if oid is set, it's a post, otherwise it's a message. if(pit->oid.length() > 0) { titlelink << "<a href=\"post/" << pit->oid << "/\" >" << pit->title << "</a>"; } else { titlelink << pit->title; } templ->render_post(titlelink.str(),pit->body); } } templ->render_footer(); } void Blog::showPost(string objid) { post p = storage->getpost(objid); templ->render_head(); templ->render_post(p.title,p.body); templ->render_footer(); } vector<key_val> Blog::parseargs(string in) { vector<string> args; split(args,in, is_any_of("&") ); vector<string>::iterator it; vector<key_val> kvpairs; for(it=args.begin();it<args.end();it++) { vector<string> tmp; split(tmp,*it,is_any_of("=")); key_val kv; kv.key = tmp[0]; if(tmp.size() > 1) kv.value = tmp[1]; kvpairs.push_back(kv); } return kvpairs; } //decides what page to show and shows it. This is the main entry point from main. void Blog::run() { string get = cgi.getEnvironment().getQueryString(); vector<key_val> kvpairs = parseargs(get); vector<key_val>::iterator kvit; for(kvit = kvpairs.begin();kvit<kvpairs.end();kvit++) { if(!(kvit->key.compare("post"))) { showPost(kvit->value); return; } if(!(kvit->key.compare("admin"))) { admin(); return; } } //as a default in case none of the above are present: homepage(); } bool Blog::admin_cookie() { const_cookie_iterator it; CgiEnvironment env = cgi.getEnvironment(); User u; if(recentcookie.length() > 0) { storage->getUser(u,recentcookie); } else { for(it=env.getCookieList().begin();it<env.getCookieList().end();it++) { if(!(it->getName().compare("MongoBlogUser"))) { storage->getUser(u,it->getValue()); break; //get out of for loop - we've found the cookie! } } } return u.is_admin; } void Blog::login() { templ->render_head(); stringstream out; out << "<form method=\"POST\" action=\"\">" << endl << "Username: <input name=\"user\" type=\"text\"/><br/>" << endl << "Password: <input name=\"pass\" type=\"password\"/><br/>" << endl << "<input name=\"sub\" type=\"submit\"/><br/>" << endl << "</form>" << endl; templ->render_post("Login",out.str()); templ->render_footer(); } void Blog::admin() { if(!admin_cookie()) { login(); return; } vector<post> posts = storage->getposts(); stringstream js; js << "<script type=\"text/javascript\" src=\"/static/jquery.js\"></script>"; js << "<script type=\"text/javascript\" src=\"/static/tiny_mce/tiny_mce.js\"></script>"; js << "<script type=\"text/javascript\" src=\"/static/tiny_mce/jquery.tinymce.js\"></script>"; js << "<script type=\"text/javascript\">"; js << " $(document).ready(function(){" << endl; js << "$(\"#textareabox\").tinymce({" << endl; js << "script_url : '/static/tiny_mce/tiny_mce.js'," << endl; js << "mode : \"textareas\"," << endl; js << "theme : \"advanced\"," << endl; js << "plugins : \"safari,advlink,table,spellchecker,pagebreak,style,layer,\"," << endl; js << "theme_advanced_buttons1 : \",bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,styleselect,formatselect,fontselect,fontsizeselect,forecolor,\"," << endl; js << "theme_advanced_buttons2 : \"cut,copy,paste,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,|,code|,fullscreen\"," << endl; js << "theme_advanced_buttons3 : \"tablecontrols,|,hr,sub,sup,|,charmap,spellchecker,|,cite,abbr,acronym,del,ins,attribs\"," << endl; js << "theme_advanced_toolbar_location : \"top\","; js << "});" << endl; //wow jquery looks horrible in C++... vector<post>::iterator pit; for(pit=posts.begin();pit!= posts.end();pit++) { js << "$(\"#" << pit->oid << "\").click(function(event) {" << endl; js << "event.preventDefault();"; js << "$(\"#titlebox\").val(\"" << templ->substitute(pit->title,"\"","\\\"") << "\");" << endl; js << "$(\"#id\").val(\"" << pit->oid << "\");" << endl; js << "$(\"#textareabox\").html('" << templ->substitute(templ->substitute(templ->substitute(pit->body,"\"","\\\""),"\n","\\\n"),"\r","") << "');" << endl; js << "});"; } js << "});"; js << "</script>"; templ->render_head(js.str()); stringstream out; out << "<form method=\"POST\" action=\"\">" << endl << "Title: <input id=\"titlebox\" name=\"title\" type=\"text\"/><br/>" << endl << "Post Body: <textarea id=\"textareabox\" name=\"body\"></textarea><br/>" << endl << "<input id=\"id\" name=\"id\" type=\"hidden\"/>" << endl << "<input name=\"sub\" type=\"submit\"/><br/>" << endl << "</form>" << endl; templ->render_post("Make post",out.str()); out.str(""); if(posts.size() == 0) { templ->render_post("<tr><td colspan=3>Post not found","There are no posts here.</td></tr>"); } else { out << "<table border=\"0\"><tr><td>Title</td><td>Body</td><td>Actions</td></tr>" << endl; vector<post>::iterator pit; for(pit=posts.begin();pit!= posts.end();pit++) { if(pit->body.length() > 140) pit->body.resize(140); out << "<tr><td>" << pit->title << "</td><td>" << pit->body << "</td><td> <a href=\"#\" id=\"" << pit->oid << "\">Edit</a></td></tr>" << endl; } out << "</table>" << endl; templ->render_post("Manage posts",out.str()); } templ->render_footer(); } <commit_msg>Escaping single quotes to avoid too much javascript messup<commit_after>/////////////////////////////////////////////////////////////////////// // // // MongBlog - Superfast simple blogging platform // // Blog Class // // (c) 2010 Michael Cullen http://cullen-online.com // // Released under the BSD licence as define in the // // accompanying LICENCE file. Please read it :-) // // // /////////////////////////////////////////////////////////////////////// #include "Blog.hpp" #include <vector> #include <iostream> #include <sstream> #include <boost/algorithm/string.hpp> using std::string; using std::fstream; using std::ios_base; using std::stringstream; using std::vector; using std::cout; using std::endl; using namespace cgicc; using namespace boost; Blog::~Blog() { if(templ) delete templ; if(storage) delete storage; } void Blog::urlDeEncode(string &str) { str = templ->substitute(str,"+"," "); str = templ->substitute(str,"%27","'"); str = templ->substitute(str,"%0A","\n"); str = templ->substitute(str,"%0D","\r"); str = templ->substitute(str,"%2B","+"); str = templ->substitute(str,"%24","$"); str = templ->substitute(str,"%26","&"); str = templ->substitute(str,"%2C",","); str = templ->substitute(str,"%2F","/"); str = templ->substitute(str,"%3A",":"); str = templ->substitute(str,"%3B",";"); str = templ->substitute(str,"%3D","="); str = templ->substitute(str,"%3F","?"); str = templ->substitute(str,"%40","@"); str = templ->substitute(str,"%20"," "); str = templ->substitute(str,"%22","\""); str = templ->substitute(str,"%3C","<"); str = templ->substitute(str,"%3E",">"); str = templ->substitute(str,"%23","#"); str = templ->substitute(str,"%28","("); str = templ->substitute(str,"%29",")"); str = templ->substitute(str,"%7B","{"); str = templ->substitute(str,"%7D","}"); str = templ->substitute(str,"%5C","|"); str = templ->substitute(str,"%5E","^"); str = templ->substitute(str,"%7E","~"); str = templ->substitute(str,"%5B","["); str = templ->substitute(str,"%5D","]"); str = templ->substitute(str,"%60","`"); str = templ->substitute(str,"%21","!"); str = templ->substitute(str,"%25","%"); } //constructor that uses a config file Blog::Blog(std::string config) { templatename = "hahaha"; pagetitle = "MongoBlog"; fstream file; string line; file.open(config.c_str(),ios_base::in); while(file >> line) { int pos = line.find(':',0); string name = line.substr(0,pos); string val = line.substr(pos+1); if(!name.compare("hostname")) { dbserver = val; } else if(!name.compare("database")) { database = val; } else if(!name.compare("uname")) { dbuser = val; } else if(!name.compare("password")) { dbpassword = val; } else if(!name.compare("useauth")) { stringstream thisval(val); thisval >> dbauth; } } file.close(); //cout << "Read:" <<endl << "hostname: " << dbserver << " database: " << database <<endl << "uname: " << dbuser << " useauth: " << dbauth <<endl; init(); } void Blog::init() { //check for post things CgiEnvironment env = cgi.getEnvironment(); storage = new StorageEngine(dbserver,database,dbuser,dbpassword); string post = env.getPostData(); vector<key_val> kvpairs = parseargs(post); vector<key_val>::iterator it; bool headers_sent = false; for(it=kvpairs.begin();it<kvpairs.end();it++) { //is it a login attempt? if(!it->key.compare("user")) { flush(cout); login_proc(kvpairs); headers_sent = true; } //is it a post? else if(!it->key.compare("body")) { if(admin_cookie()) { post_proc(kvpairs); } } } if(!headers_sent) cout << HTTPHTMLHeader(); //storage is after header so any error messages get outputted //if there is no servername, and no auth, use this. templ = new Template(templatename); templ->set_page_title(pagetitle); } void Blog::post_proc(vector<key_val> kvpairs) { string title; string body; bool update = false; string oid; vector<key_val>::iterator it; for(it=kvpairs.begin();it<kvpairs.end();it++) { if(!it->key.compare("title")) { title = it->value; urlDeEncode(title); } else if(!it->key.compare("body")) { body = it->value; urlDeEncode(body); } else if(!it->key.compare("id")) { oid = it->value; urlDeEncode(oid); if(oid.length() > 0) update = true; } } if(body.length() > 0) { if(update) { storage->dopost(title,body,oid); } else { storage->dopost(title,body); } } } void Blog::login_proc(vector<key_val> kvpairs) { string user; string password; flush(cout); vector<key_val>::iterator it; for(it=kvpairs.begin();it<kvpairs.end();it++) { if(!it->key.compare("user")) { user = it->value; } else if(!it->key.compare("pass")) { password = it->value; } } //make sure it's at least sort of worked if(user.length() > 0) { flush(cout); string cookie = storage->login(user,password); flush(cout); //if login didn't fail if(cookie.length() > 0) { cout << HTTPHTMLHeader().setCookie(HTTPCookie("MongoBlogUser",cookie,"","",0,"",0)); recentcookie = cookie; flush(cout); } else cout << HTTPHTMLHeader(); } flush(cout); exit(0); } void Blog::homepage() { templ->render_head(); vector<post> posts = storage->getposts(); if(posts.size() == 0) { templ->render_post("Post not found","There are no posts here."); } else { vector<post>::iterator pit; for(pit=posts.begin();pit!= posts.end();pit++) { stringstream titlelink; //if oid is set, it's a post, otherwise it's a message. if(pit->oid.length() > 0) { titlelink << "<a href=\"post/" << pit->oid << "/\" >" << pit->title << "</a>"; } else { titlelink << pit->title; } templ->render_post(titlelink.str(),pit->body); } } templ->render_footer(); } void Blog::showPost(string objid) { post p = storage->getpost(objid); templ->render_head(); templ->render_post(p.title,p.body); templ->render_footer(); } vector<key_val> Blog::parseargs(string in) { vector<string> args; split(args,in, is_any_of("&") ); vector<string>::iterator it; vector<key_val> kvpairs; for(it=args.begin();it<args.end();it++) { vector<string> tmp; split(tmp,*it,is_any_of("=")); key_val kv; kv.key = tmp[0]; if(tmp.size() > 1) kv.value = tmp[1]; kvpairs.push_back(kv); } return kvpairs; } //decides what page to show and shows it. This is the main entry point from main. void Blog::run() { string get = cgi.getEnvironment().getQueryString(); vector<key_val> kvpairs = parseargs(get); vector<key_val>::iterator kvit; for(kvit = kvpairs.begin();kvit<kvpairs.end();kvit++) { if(!(kvit->key.compare("post"))) { showPost(kvit->value); return; } if(!(kvit->key.compare("admin"))) { admin(); return; } } //as a default in case none of the above are present: homepage(); } bool Blog::admin_cookie() { const_cookie_iterator it; CgiEnvironment env = cgi.getEnvironment(); User u; if(recentcookie.length() > 0) { storage->getUser(u,recentcookie); } else { for(it=env.getCookieList().begin();it<env.getCookieList().end();it++) { if(!(it->getName().compare("MongoBlogUser"))) { storage->getUser(u,it->getValue()); break; //get out of for loop - we've found the cookie! } } } return u.is_admin; } void Blog::login() { templ->render_head(); stringstream out; out << "<form method=\"POST\" action=\"\">" << endl << "Username: <input name=\"user\" type=\"text\"/><br/>" << endl << "Password: <input name=\"pass\" type=\"password\"/><br/>" << endl << "<input name=\"sub\" type=\"submit\"/><br/>" << endl << "</form>" << endl; templ->render_post("Login",out.str()); templ->render_footer(); } void Blog::admin() { if(!admin_cookie()) { login(); return; } vector<post> posts = storage->getposts(); stringstream js; js << "<script type=\"text/javascript\" src=\"/static/jquery.js\"></script>"; js << "<script type=\"text/javascript\" src=\"/static/tiny_mce/tiny_mce.js\"></script>"; js << "<script type=\"text/javascript\" src=\"/static/tiny_mce/jquery.tinymce.js\"></script>"; js << "<script type=\"text/javascript\">"; js << " $(document).ready(function(){" << endl; js << "$(\"#textareabox\").tinymce({" << endl; js << "script_url : '/static/tiny_mce/tiny_mce.js'," << endl; js << "mode : \"textareas\"," << endl; js << "theme : \"advanced\"," << endl; js << "plugins : \"safari,advlink,table,spellchecker,pagebreak,style,layer,\"," << endl; js << "theme_advanced_buttons1 : \",bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,styleselect,formatselect,fontselect,fontsizeselect,forecolor,\"," << endl; js << "theme_advanced_buttons2 : \"cut,copy,paste,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,|,code|,fullscreen\"," << endl; js << "theme_advanced_buttons3 : \"tablecontrols,|,hr,sub,sup,|,charmap,spellchecker,|,cite,abbr,acronym,del,ins,attribs\"," << endl; js << "theme_advanced_toolbar_location : \"top\","; js << "});" << endl; //wow jquery looks horrible in C++... vector<post>::iterator pit; for(pit=posts.begin();pit!= posts.end();pit++) { js << "$(\"#" << pit->oid << "\").click(function(event) {" << endl; js << "event.preventDefault();"; js << "$(\"#titlebox\").val(\"" << templ->substitute(pit->title,"\"","\\\"") << "\");" << endl; js << "$(\"#id\").val(\"" << pit->oid << "\");" << endl; js << "$(\"#textareabox\").html('" << templ->substitute(templ->substitute(templ->substitute(templ->substitute(pit->body,"\"","\\\""),"\n","\\\n"),"\r",""),"'","\\'") << "');" << endl; js << "});"; } js << "});"; js << "</script>"; templ->render_head(js.str()); stringstream out; out << "<form method=\"POST\" action=\"\">" << endl << "Title: <input id=\"titlebox\" name=\"title\" type=\"text\"/><br/>" << endl << "Post Body: <textarea id=\"textareabox\" name=\"body\"></textarea><br/>" << endl << "<input id=\"id\" name=\"id\" type=\"hidden\"/>" << endl << "<input name=\"sub\" type=\"submit\"/><br/>" << endl << "</form>" << endl; templ->render_post("Make post",out.str()); out.str(""); if(posts.size() == 0) { templ->render_post("<tr><td colspan=3>Post not found","There are no posts here.</td></tr>"); } else { out << "<table border=\"0\"><tr><td>Title</td><td>Body</td><td>Actions</td></tr>" << endl; vector<post>::iterator pit; for(pit=posts.begin();pit!= posts.end();pit++) { if(pit->body.length() > 140) pit->body.resize(140); out << "<tr><td>" << pit->title << "</td><td>" << pit->body << "</td><td> <a href=\"#\" id=\"" << pit->oid << "\">Edit</a></td></tr>" << endl; } out << "</table>" << endl; templ->render_post("Manage posts",out.str()); } templ->render_footer(); } <|endoftext|>
<commit_before>#include "KinematicSystem.hpp" #include "EntityManager.hpp" #include "data/KinematicComponent.hpp" #include "data/PhysicsComponent.hpp" #include "data/TransformComponent.hpp" #include "functions/Execute.hpp" #include "angle.hpp" namespace kengine { // declarations static void execute(EntityManager & em, float deltaTime); // EntityCreatorFunctor<64> KinematicSystem(EntityManager & em) { return [&](Entity & e) { e += functions::Execute{ [&](float deltaTime) { execute(em, deltaTime); } }; }; } static void execute(EntityManager & em, float deltaTime) { for (const auto & [e, transform, physics, kinematic] : em.getEntities<TransformComponent, PhysicsComponent, KinematicComponent>()) { transform.boundingBox.position += physics.movement * deltaTime; const auto applyRotation = [deltaTime](float & transformMember, float physicsMember) { transformMember += physicsMember * deltaTime; transformMember = putils::constrainAngle(transformMember); }; applyRotation(transform.pitch, physics.pitch); applyRotation(transform.yaw, physics.yaw); applyRotation(transform.roll, physics.roll); } } } <commit_msg>add regions to KinematicSystem<commit_after>#include "KinematicSystem.hpp" #include "EntityManager.hpp" #include "data/KinematicComponent.hpp" #include "data/PhysicsComponent.hpp" #include "data/TransformComponent.hpp" #include "functions/Execute.hpp" #include "angle.hpp" namespace kengine { #pragma region declarations static void execute(EntityManager & em, float deltaTime); #pragma endregion EntityCreatorFunctor<64> KinematicSystem(EntityManager & em) { return [&](Entity & e) { e += functions::Execute{ [&](float deltaTime) { execute(em, deltaTime); } }; }; } static void execute(EntityManager & em, float deltaTime) { for (const auto & [e, transform, physics, kinematic] : em.getEntities<TransformComponent, PhysicsComponent, KinematicComponent>()) { transform.boundingBox.position += physics.movement * deltaTime; const auto applyRotation = [deltaTime](float & transformMember, float physicsMember) { transformMember += physicsMember * deltaTime; transformMember = putils::constrainAngle(transformMember); }; applyRotation(transform.pitch, physics.pitch); applyRotation(transform.yaw, physics.yaw); applyRotation(transform.roll, physics.roll); } } } <|endoftext|>
<commit_before>/* * Copyright 2016 Ivan Ryabov * * 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. */ /** * An example of Using application framework and command line argument handling. * */ #include <solace/framework/application.hpp> #include <solace/framework/commandlineParser.hpp> #include <iostream> using namespace Solace; using namespace Solace::Framework; class ExampleApp : public Application { public: explicit ExampleApp(const String& name) : Application(Version(1, 0, 0, "Demo")), _name(name) {} using Application::init; Result<void, Error> init(int argc, const char *argv[]) override { int someParam = 0; return CommandlineParser("Solace framework example", { CommandlineParser::printHelp(), CommandlineParser::printVersion("sol_example", getVersion()), {0, "some-param", "Some useless parameter for the demo", &someParam}, {'u', "name", "Name to call", &_name} }) .parse(argc, argv) .then([](const CommandlineParser*) { return; }); } Solace::Result<int, Solace::Error> run() { std::cout << "Hello "; if (_name.empty()) std::cout << "world"; else std::cout << _name; std::cout << std::endl; return Solace::Ok<int>(EXIT_SUCCESS); } private: Solace::String _name; }; int main(int argc, char **argv) { ExampleApp app("Demo App"); return app.init(argc, argv) .then([&app]() { return app.run(); }) .orElse([](const Solace::Error& error) { if (error) { std::cerr << "Error: " << error << std::endl; } return Ok(EXIT_FAILURE); }) .unwrap(); } <commit_msg>Added endianness output to app example<commit_after>/* * Copyright 2016 Ivan Ryabov * * 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. */ /** * An example of Using application framework and command line argument handling. * */ #include <solace/framework/application.hpp> #include <solace/framework/commandlineParser.hpp> #include <iostream> using namespace Solace; using namespace Solace::Framework; class ExampleApp : public Application { public: explicit ExampleApp(const String& name) : Application(Version(1, 0, 0, "Demo")), _name(name) {} using Application::init; Result<void, Error> init(int argc, const char *argv[]) override { int someParam = 0; return CommandlineParser("Solace app-framework example", { CommandlineParser::printHelp(), CommandlineParser::printVersion("application", getVersion()), {0, "some-param", "Some useless parameter for the demo", &someParam}, {'u', "name", "Name to call", &_name} }) .parse(argc, argv) .then([](const CommandlineParser*) { return; }); } Solace::Result<int, Solace::Error> run() { std::cout << "Hello"; if (Solace::isBigendian()) std::cout << ", big-endian "; else std::cout << ", little-endian "; if (_name.empty()) std::cout << "world"; else std::cout << _name; std::cout << std::endl; return Solace::Ok<int>(EXIT_SUCCESS); } private: Solace::String _name; }; int main(int argc, char **argv) { ExampleApp app("Demo App"); return app.init(argc, argv) .then([&app]() { return app.run(); }) .orElse([](const Solace::Error& error) { if (error) { std::cerr << "Error: " << error << std::endl; } return Ok(EXIT_FAILURE); }) .unwrap(); } <|endoftext|>
<commit_before>#include <stingray/toolkit/Factory.h> #include <stingray/toolkit/any.h> #include <stingray/app/PushVideoOnDemand.h> #include <stingray/app/activation_manager/ActivationIntent.h> #include <stingray/app/application_context/AppChannel.h> #include <stingray/app/application_context/ChannelList.h> #include <stingray/app/scheduler/ScheduledEvents.h> #include <stingray/app/tests/AutoFilter.h> #include <stingray/app/zapper/User.h> #include <stingray/ca/BasicSubscription.h> #include <stingray/crypto/PlainCipherKey.h> #include <stingray/details/IReceiverTrait.h> #include <stingray/hdmi/IHDMI.h> #include <stingray/media/ImageFileMediaData.h> #include <stingray/media/MediaInfoBase.h> #include <stingray/media/Mp3MediaInfo.h> #include <stingray/media/formats/flv/MediaInfo.h> #include <stingray/media/formats/mp4/MediaInfo.h> #include <stingray/media/formats/mp4/Stream.h> #include <stingray/media/formats/mp4/SubstreamDescriptors.h> #include <stingray/mpeg/Stream.h> #include <stingray/net/DHCPInterfaceConfiguration.h> #include <stingray/net/IgnoredInterfaceConfiguration.h> #include <stingray/net/LinkLocalInterfaceConfiguration.h> #include <stingray/net/ManualInterfaceConfiguration.h> #include <stingray/parentalcontrol/AgeRating.h> #ifdef PLATFORM_EMU # include <stingray/platform/emu/scanner/Channel.h> #endif #ifdef PLATFORM_MSTAR # include <stingray/platform/mstar/crypto/HardwareCipherKey.h> #endif #ifdef PLATFORM_OPENSSL # include <stingray/platform/openssl/crypto/Certificate.h> #endif #ifdef PLATFORM_OPENSSL # include <stingray/platform/openssl/crypto/EvpKey.h> #endif #ifdef PLATFORM_STAPI # include <stingray/platform/stapi/crypto/HardwareCipherKey.h> #endif #include <stingray/records/FileSystemRecord.h> #include <stingray/rpc/UrlObjectId.h> #include <stingray/scanner/DVBServiceId.h> #include <stingray/scanner/DefaultDVBTBandInfo.h> #include <stingray/scanner/DefaultMpegService.h> #include <stingray/scanner/DefaultMpegSubstreamDescriptor.h> #include <stingray/scanner/DefaultScanParams.h> #include <stingray/scanner/DreCasGeographicRegion.h> #include <stingray/scanner/LybidScanParams.h> #include <stingray/scanner/TerrestrialScanParams.h> #include <stingray/scanner/TricolorGeographicRegion.h> #include <stingray/scanner/TricolorScanParams.h> #include <stingray/scanner/lybid/LybidServiceMetaInfo.h> #include <stingray/scanner/terrestrial/TerrestrialServiceMetaInfo.h> #include <stingray/scanner/tricolor/TricolorServiceMetaInfo.h> #include <stingray/stats/ChannelViewingEventInfo.h> #include <stingray/streams/PlaybackStreamContent.h> #include <stingray/streams/RecordStreamContent.h> #include <stingray/streams/RecordStreamMetaInfo.h> #include <stingray/tuners/TunerState.h> #include <stingray/tuners/dvbs/Antenna.h> #include <stingray/tuners/dvbs/DefaultDVBSTransport.h> #include <stingray/tuners/dvbs/Satellite.h> #include <stingray/tuners/dvbt/DVBTTransport.h> #include <stingray/tuners/ip/TsOverIpTransport.h> #include <stingray/update/VersionRequirement.h> #include <stingray/update/system/CopyFile.h> #include <stingray/update/system/EraseFlashPartition.h> #include <stingray/update/system/MountFilesystem.h> #include <stingray/update/system/MoveFile.h> #include <stingray/update/system/RemoveFile.h> #include <stingray/update/system/UnmountFilesystem.h> #include <stingray/update/system/WriteFlashPartition.h> /* WARNING! This is autogenerated file, DO NOT EDIT! */ namespace stingray { namespace Detail { void Factory::RegisterTypes() { #ifdef BUILD_SHARED_LIB /*nothing*/ #else TOOLKIT_REGISTER_CLASS_EXPLICIT(app::PVODVideoInfo); TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ActivationKeyIntent); TOOLKIT_REGISTER_CLASS_EXPLICIT(app::PersonalCodeIntent); TOOLKIT_REGISTER_CLASS_EXPLICIT(app::PlatformNameIntent); TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ReceiverTraitIntent); TOOLKIT_REGISTER_CLASS_EXPLICIT(app::AppChannel); TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ChannelList); TOOLKIT_REGISTER_CLASS_EXPLICIT(app::CinemaHallScheduledViewing); TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ContinuousScheduledEvent); TOOLKIT_REGISTER_CLASS_EXPLICIT(app::DeferredStandby); TOOLKIT_REGISTER_CLASS_EXPLICIT(app::InfiniteScheduledEvent); TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ScheduledEvent); TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ScheduledRecord); TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ScheduledViewing); TOOLKIT_REGISTER_CLASS_EXPLICIT(app::AutoFilter); TOOLKIT_REGISTER_CLASS_EXPLICIT(app::User); TOOLKIT_REGISTER_CLASS_EXPLICIT(BasicSubscription); TOOLKIT_REGISTER_CLASS_EXPLICIT(BasicSubscriptionProvider); TOOLKIT_REGISTER_CLASS_EXPLICIT(PlainCipherKey); TOOLKIT_REGISTER_CLASS_EXPLICIT(DVBCReceiverTrait); TOOLKIT_REGISTER_CLASS_EXPLICIT(DVBSReceiverTrait); TOOLKIT_REGISTER_CLASS_EXPLICIT(DVBTReceiverTrait); TOOLKIT_REGISTER_CLASS_EXPLICIT(HouseholdClientTrait); TOOLKIT_REGISTER_CLASS_EXPLICIT(HouseholdServerTrait); TOOLKIT_REGISTER_CLASS_EXPLICIT(LybidOperatorTrait); TOOLKIT_REGISTER_CLASS_EXPLICIT(TricolorOperatorTrait); TOOLKIT_REGISTER_CLASS_EXPLICIT(HDMIConfig); TOOLKIT_REGISTER_CLASS_EXPLICIT(ImageFileMediaInfo); TOOLKIT_REGISTER_CLASS_EXPLICIT(ImageFileMediaPreview); TOOLKIT_REGISTER_CLASS_EXPLICIT(InMemoryImageMediaPreview); TOOLKIT_REGISTER_CLASS_EXPLICIT(MediaInfoBase); TOOLKIT_REGISTER_CLASS_EXPLICIT(Mp3MediaInfo); TOOLKIT_REGISTER_CLASS_EXPLICIT(flv::MediaInfo); TOOLKIT_REGISTER_CLASS_EXPLICIT(mp4::MediaInfo); TOOLKIT_REGISTER_CLASS_EXPLICIT(mp4::Stream); TOOLKIT_REGISTER_CLASS_EXPLICIT(mp4::Mp4MediaAudioSubstreamDescriptor); TOOLKIT_REGISTER_CLASS_EXPLICIT(mp4::Mp4MediaVideoSubstreamDescriptor); TOOLKIT_REGISTER_CLASS_EXPLICIT(mpeg::Stream); TOOLKIT_REGISTER_CLASS_EXPLICIT(DHCPInterfaceConfiguration); TOOLKIT_REGISTER_CLASS_EXPLICIT(IgnoredInterfaceConfiguration); TOOLKIT_REGISTER_CLASS_EXPLICIT(LinkLocalInterfaceConfiguration); TOOLKIT_REGISTER_CLASS_EXPLICIT(ManualInterfaceConfiguration); TOOLKIT_REGISTER_CLASS_EXPLICIT(AgeRating); #ifdef PLATFORM_EMU TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::EmuServiceId); #endif #ifdef PLATFORM_EMU TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::RadioChannel); #endif #ifdef PLATFORM_EMU TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::SubstreamDescriptor); #endif #ifdef PLATFORM_EMU TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::TVChannel); #endif #ifdef PLATFORM_MSTAR TOOLKIT_REGISTER_CLASS_EXPLICIT(mstar::HardwareCipherKey); #endif #ifdef PLATFORM_OPENSSL TOOLKIT_REGISTER_CLASS_EXPLICIT(openssl::Certificate); #endif #ifdef PLATFORM_OPENSSL TOOLKIT_REGISTER_CLASS_EXPLICIT(openssl::EvpKey); #endif #ifdef PLATFORM_STAPI TOOLKIT_REGISTER_CLASS_EXPLICIT(stapi::HardwareCipherKey); #endif TOOLKIT_REGISTER_CLASS_EXPLICIT(FileSystemRecord); TOOLKIT_REGISTER_CLASS_EXPLICIT(rpc::UrlObjectId); TOOLKIT_REGISTER_CLASS_EXPLICIT(DVBServiceId); TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultDVBTBandInfo); TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMpegRadioChannel); TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMpegService); TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMpegTVChannel); TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegAudioSubstreamDescriptor); TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegDataCarouselSubstreamDescriptor); TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegPcrSubstreamDescriptor); TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegSubtitlesSubstreamDescriptor); TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegTeletextBasedSubtitlesSubstreamDescriptor); TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegTeletextSubstreamDescriptor); TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegVideoSubstreamDescriptor); TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultScanParams); TOOLKIT_REGISTER_CLASS_EXPLICIT(DreCasGeographicRegion); TOOLKIT_REGISTER_CLASS_EXPLICIT(LybidScanParams); TOOLKIT_REGISTER_CLASS_EXPLICIT(TerrestrialScanParams); TOOLKIT_REGISTER_CLASS_EXPLICIT(TricolorGeographicRegion); TOOLKIT_REGISTER_CLASS_EXPLICIT(TricolorScanParams); TOOLKIT_REGISTER_CLASS_EXPLICIT(LybidServiceMetaInfo); TOOLKIT_REGISTER_CLASS_EXPLICIT(TerrestrialServiceMetaInfo); TOOLKIT_REGISTER_CLASS_EXPLICIT(TricolorServiceMetaInfo); TOOLKIT_REGISTER_CLASS_EXPLICIT(::stingray::Detail::any::ObjectHolder<stingray::ChannelViewingEventInfo>); TOOLKIT_REGISTER_CLASS_EXPLICIT(PlaybackStreamContent); TOOLKIT_REGISTER_CLASS_EXPLICIT(RecordStreamContent); TOOLKIT_REGISTER_CLASS_EXPLICIT(RecordStreamMetaInfo); TOOLKIT_REGISTER_CLASS_EXPLICIT(CircuitedTunerState); TOOLKIT_REGISTER_CLASS_EXPLICIT(LockedTunerState); TOOLKIT_REGISTER_CLASS_EXPLICIT(UnlockedTunerState); TOOLKIT_REGISTER_CLASS_EXPLICIT(Antenna); TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultDVBSTransport); TOOLKIT_REGISTER_CLASS_EXPLICIT(Satellite); TOOLKIT_REGISTER_CLASS_EXPLICIT(DVBTTransport); TOOLKIT_REGISTER_CLASS_EXPLICIT(TsOverIpTransport); TOOLKIT_REGISTER_CLASS_EXPLICIT(VersionRequirement); TOOLKIT_REGISTER_CLASS_EXPLICIT(CopyFile); TOOLKIT_REGISTER_CLASS_EXPLICIT(EraseFlashPartition); TOOLKIT_REGISTER_CLASS_EXPLICIT(MountFilesystem); TOOLKIT_REGISTER_CLASS_EXPLICIT(MoveFile); TOOLKIT_REGISTER_CLASS_EXPLICIT(RemoveFile); TOOLKIT_REGISTER_CLASS_EXPLICIT(UnmountFilesystem); TOOLKIT_REGISTER_CLASS_EXPLICIT(WriteFlashPartition); #endif } }} <commit_msg>update factory classes<commit_after>#include <stingray/toolkit/Factory.h> #include <stingray/toolkit/any.h> #include <stingray/app/PushVideoOnDemand.h> #include <stingray/app/activation_manager/ActivationIntent.h> #include <stingray/app/application_context/AppChannel.h> #include <stingray/app/application_context/ChannelList.h> #include <stingray/app/scheduler/ScheduledEvents.h> #include <stingray/app/tests/AutoFilter.h> #include <stingray/app/zapper/User.h> #include <stingray/ca/BasicSubscription.h> #include <stingray/crypto/PlainCipherKey.h> #include <stingray/details/IReceiverTrait.h> #include <stingray/hdmi/IHDMI.h> #include <stingray/media/ImageFileMediaData.h> #include <stingray/media/MediaInfoBase.h> #include <stingray/media/Mp3MediaInfo.h> #include <stingray/media/formats/flv/MediaInfo.h> #include <stingray/media/formats/mp4/MediaInfo.h> #include <stingray/media/formats/mp4/Stream.h> #include <stingray/media/formats/mp4/SubstreamDescriptors.h> #include <stingray/mpeg/Stream.h> #include <stingray/net/DHCPInterfaceConfiguration.h> #include <stingray/net/IgnoredInterfaceConfiguration.h> #include <stingray/net/LinkLocalInterfaceConfiguration.h> #include <stingray/net/ManualInterfaceConfiguration.h> #include <stingray/parentalcontrol/AgeRating.h> #ifdef PLATFORM_EMU # include <stingray/platform/emu/scanner/Channel.h> #endif #ifdef PLATFORM_MSTAR # include <stingray/platform/mstar/crypto/HardwareCipherKey.h> #endif #ifdef PLATFORM_OPENSSL # include <stingray/platform/openssl/crypto/Certificate.h> #endif #ifdef PLATFORM_OPENSSL # include <stingray/platform/openssl/crypto/EvpKey.h> #endif #ifdef PLATFORM_STAPI # include <stingray/platform/stapi/crypto/HardwareCipherKey.h> #endif #include <stingray/records/FileSystemRecord.h> #include <stingray/rpc/UrlObjectId.h> #include <stingray/scanner/DVBServiceId.h> #include <stingray/scanner/DefaultDVBTBandInfo.h> #include <stingray/scanner/DefaultMpegService.h> #include <stingray/scanner/DefaultMpegSubstreamDescriptor.h> #include <stingray/scanner/DefaultScanParams.h> #include <stingray/scanner/DreCasGeographicRegion.h> #include <stingray/scanner/LybidScanParams.h> #include <stingray/scanner/TerrestrialScanParams.h> #include <stingray/scanner/TricolorGeographicRegion.h> #include <stingray/scanner/TricolorScanParams.h> #include <stingray/scanner/lybid/LybidServiceMetaInfo.h> #include <stingray/scanner/terrestrial/TerrestrialServiceMetaInfo.h> #include <stingray/scanner/tricolor/TricolorServiceMetaInfo.h> #include <stingray/stats/ChannelViewingEventInfo.h> #include <stingray/streams/PlaybackStreamContent.h> #include <stingray/streams/RecordStreamContent.h> #include <stingray/streams/RecordStreamMetaInfo.h> #include <stingray/tuners/TunerState.h> #include <stingray/tuners/dvbs/Antenna.h> #include <stingray/tuners/dvbs/DefaultDVBSTransport.h> #include <stingray/tuners/dvbs/Satellite.h> #include <stingray/tuners/dvbt/DVBTTransport.h> #include <stingray/tuners/ip/TsOverIpTransport.h> #include <stingray/update/VersionRequirement.h> #include <stingray/update/system/CopyFile.h> #include <stingray/update/system/EraseFlashPartition.h> #include <stingray/update/system/MountFilesystem.h> #include <stingray/update/system/MoveFile.h> #include <stingray/update/system/RemoveFile.h> #include <stingray/update/system/UnmountFilesystem.h> #include <stingray/update/system/WriteFlashPartition.h> /* WARNING! This is autogenerated file, DO NOT EDIT! */ namespace stingray { namespace Detail { void Factory::RegisterTypes() { #ifdef BUILD_SHARED_LIB /*nothing*/ #else TOOLKIT_REGISTER_CLASS_EXPLICIT(app::PVODVideoInfo); TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ActivationKeyIntent); TOOLKIT_REGISTER_CLASS_EXPLICIT(app::PersonalCodeIntent); TOOLKIT_REGISTER_CLASS_EXPLICIT(app::PlatformNameIntent); TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ReceiverTraitIntent); TOOLKIT_REGISTER_CLASS_EXPLICIT(app::AppChannel); TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ChannelList); TOOLKIT_REGISTER_CLASS_EXPLICIT(app::CinemaHallScheduledViewing); TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ContinuousScheduledEvent); TOOLKIT_REGISTER_CLASS_EXPLICIT(app::DeferredStandby); TOOLKIT_REGISTER_CLASS_EXPLICIT(app::InfiniteScheduledEvent); TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ScheduledEvent); TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ScheduledRecord); TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ScheduledViewing); TOOLKIT_REGISTER_CLASS_EXPLICIT(app::AutoFilter); TOOLKIT_REGISTER_CLASS_EXPLICIT(app::User); TOOLKIT_REGISTER_CLASS_EXPLICIT(BasicSubscription); TOOLKIT_REGISTER_CLASS_EXPLICIT(BasicSubscriptionProvider); TOOLKIT_REGISTER_CLASS_EXPLICIT(PlainCipherKey); TOOLKIT_REGISTER_CLASS_EXPLICIT(DVBCReceiverTrait); TOOLKIT_REGISTER_CLASS_EXPLICIT(DVBSReceiverTrait); TOOLKIT_REGISTER_CLASS_EXPLICIT(DVBTReceiverTrait); TOOLKIT_REGISTER_CLASS_EXPLICIT(HouseholdClientTrait); TOOLKIT_REGISTER_CLASS_EXPLICIT(HouseholdServerTrait); TOOLKIT_REGISTER_CLASS_EXPLICIT(LybidOperatorTrait); TOOLKIT_REGISTER_CLASS_EXPLICIT(TricolorOperatorTrait); TOOLKIT_REGISTER_CLASS_EXPLICIT(HDMIConfig); TOOLKIT_REGISTER_CLASS_EXPLICIT(ImageFileMediaInfo); TOOLKIT_REGISTER_CLASS_EXPLICIT(ImageFileMediaPreview); TOOLKIT_REGISTER_CLASS_EXPLICIT(InMemoryImageMediaPreview); TOOLKIT_REGISTER_CLASS_EXPLICIT(MediaInfoBase); TOOLKIT_REGISTER_CLASS_EXPLICIT(Mp3MediaInfo); TOOLKIT_REGISTER_CLASS_EXPLICIT(flv::MediaInfo); TOOLKIT_REGISTER_CLASS_EXPLICIT(mp4::MediaInfo); TOOLKIT_REGISTER_CLASS_EXPLICIT(mp4::Stream); TOOLKIT_REGISTER_CLASS_EXPLICIT(mp4::Mp4MediaAudioSubstreamDescriptor); TOOLKIT_REGISTER_CLASS_EXPLICIT(mp4::Mp4MediaVideoSubstreamDescriptor); TOOLKIT_REGISTER_CLASS_EXPLICIT(mpeg::Stream); TOOLKIT_REGISTER_CLASS_EXPLICIT(DHCPInterfaceConfiguration); TOOLKIT_REGISTER_CLASS_EXPLICIT(IgnoredInterfaceConfiguration); TOOLKIT_REGISTER_CLASS_EXPLICIT(LinkLocalInterfaceConfiguration); TOOLKIT_REGISTER_CLASS_EXPLICIT(ManualInterfaceConfiguration); TOOLKIT_REGISTER_CLASS_EXPLICIT(AgeRating); #ifdef PLATFORM_EMU TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::EmuServiceId); #endif #ifdef PLATFORM_EMU TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::RadioChannel); #endif #ifdef PLATFORM_EMU TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::SubstreamDescriptor); #endif #ifdef PLATFORM_EMU TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::TVChannel); #endif #ifdef PLATFORM_MSTAR TOOLKIT_REGISTER_CLASS_EXPLICIT(mstar::HardwareCipherKey); #endif #ifdef PLATFORM_OPENSSL TOOLKIT_REGISTER_CLASS_EXPLICIT(openssl::Certificate); #endif #ifdef PLATFORM_OPENSSL TOOLKIT_REGISTER_CLASS_EXPLICIT(openssl::EvpKey); #endif #ifdef PLATFORM_STAPI TOOLKIT_REGISTER_CLASS_EXPLICIT(stapi::HardwareCipherKey); #endif TOOLKIT_REGISTER_CLASS_EXPLICIT(FileSystemRecord); TOOLKIT_REGISTER_CLASS_EXPLICIT(rpc::UrlObjectId); TOOLKIT_REGISTER_CLASS_EXPLICIT(DVBServiceId); TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultDVBTBandInfo); TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMpegRadioChannel); TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMpegService); TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMpegTVChannel); TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegAudioSubstreamDescriptor); TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegDataCarouselSubstreamDescriptor); TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegPcrSubstreamDescriptor); TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegSubtitlesSubstreamDescriptor); TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegTeletextBasedSubtitlesSubstreamDescriptor); TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegTeletextSubstreamDescriptor); TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegVideoSubstreamDescriptor); TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultScanParams); TOOLKIT_REGISTER_CLASS_EXPLICIT(DreCasGeographicRegion); TOOLKIT_REGISTER_CLASS_EXPLICIT(LybidScanParams); TOOLKIT_REGISTER_CLASS_EXPLICIT(TerrestrialScanParams); TOOLKIT_REGISTER_CLASS_EXPLICIT(TricolorGeographicRegion); TOOLKIT_REGISTER_CLASS_EXPLICIT(TricolorScanParams); TOOLKIT_REGISTER_CLASS_EXPLICIT(LybidServiceMetaInfo); TOOLKIT_REGISTER_CLASS_EXPLICIT(TerrestrialServiceMetaInfo); TOOLKIT_REGISTER_CLASS_EXPLICIT(TricolorServiceMetaInfo); TOOLKIT_REGISTER_CLASS_EXPLICIT(Detail::any::ObjectHolder<stingray::ChannelViewingEventInfo>); TOOLKIT_REGISTER_CLASS_EXPLICIT(PlaybackStreamContent); TOOLKIT_REGISTER_CLASS_EXPLICIT(RecordStreamContent); TOOLKIT_REGISTER_CLASS_EXPLICIT(RecordStreamMetaInfo); TOOLKIT_REGISTER_CLASS_EXPLICIT(CircuitedTunerState); TOOLKIT_REGISTER_CLASS_EXPLICIT(LockedTunerState); TOOLKIT_REGISTER_CLASS_EXPLICIT(UnlockedTunerState); TOOLKIT_REGISTER_CLASS_EXPLICIT(Antenna); TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultDVBSTransport); TOOLKIT_REGISTER_CLASS_EXPLICIT(Satellite); TOOLKIT_REGISTER_CLASS_EXPLICIT(DVBTTransport); TOOLKIT_REGISTER_CLASS_EXPLICIT(TsOverIpTransport); TOOLKIT_REGISTER_CLASS_EXPLICIT(VersionRequirement); TOOLKIT_REGISTER_CLASS_EXPLICIT(CopyFile); TOOLKIT_REGISTER_CLASS_EXPLICIT(EraseFlashPartition); TOOLKIT_REGISTER_CLASS_EXPLICIT(MountFilesystem); TOOLKIT_REGISTER_CLASS_EXPLICIT(MoveFile); TOOLKIT_REGISTER_CLASS_EXPLICIT(RemoveFile); TOOLKIT_REGISTER_CLASS_EXPLICIT(UnmountFilesystem); TOOLKIT_REGISTER_CLASS_EXPLICIT(WriteFlashPartition); #endif } }} <|endoftext|>
<commit_before>#include <SFML/Graphics.hpp> int main() { sf::RenderWindow window(sf::VideoMode(200, 200), "SFML works!"); sf::CircleShape shape(100.f); shape.setFillColor(sf::Color::Green); while (window.isOpen()) { sf::Event event; while (window.pollEvent(event)) { if (event.type == sf::Event::Closed) window.close(); } window.clear(); window.draw(shape); window.display(); } return EXIT_SUCCESS; }<commit_msg>Define initial window dimensions<commit_after>#include <SFML/Graphics.hpp> #define WINDOW_WIDTH 400 #define WINDOW_HEIGHT 400 int main() { sf::RenderWindow window(sf::VideoMode(WINDOW_WIDTH, WINDOW_HEIGHT), "Ninja Chess"); sf::CircleShape shape(100.f); shape.setFillColor(sf::Color::Green); while (window.isOpen()) { sf::Event event; while (window.pollEvent(event)) { if (event.type == sf::Event::Closed) window.close(); } window.clear(); window.draw(shape); window.display(); } return EXIT_SUCCESS; }<|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: wrtswtbl.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: cmc $ $Date: 2002-11-18 15:17:35 $ * * 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 _WRTSWTBL_HXX #define _WRTSWTBL_HXX #ifndef _SOLAR_H #include <tools/solar.h> #endif #ifndef _TOOLS_COLOR_HXX #include <tools/color.hxx> #endif #ifndef _SVARRAY_HXX #include <svtools/svarray.hxx> #endif #ifndef _ORNTENUM_HXX #include <orntenum.hxx> #endif #ifndef _HORIORNT_HXX #include <horiornt.hxx> #endif class Color; class SwTableBox; class SwTableBoxes; class SwTableLine; class SwTableLines; class SwTable; class SwFrmFmt; class SwHTMLTableLayout; class SvxBrushItem; class SvxBoxItem; class SvxBorderLine; //--------------------------------------------------------------------------- // Code aus dem HTML-Filter fuers schreiben von Tabellen //--------------------------------------------------------------------------- #define COLFUZZY 20 #define ROWFUZZY 20 #define COL_DFLT_WIDTH ((2*COLFUZZY)+1) #define ROW_DFLT_HEIGHT (2*ROWFUZZY)+1 //----------------------------------------------------------------------- class SwWriteTableCell { const SwTableBox *pBox; // SwTableBox der Zelle const SvxBrushItem *pBackground; // geerbter Hintergrund einer Zeile long nHeight; // fixe/Mindest-Hoehe der Zeile USHORT nWidthOpt; // Breite aus Option; USHORT nRow; // Start-Zeile USHORT nCol; // Start-Spalte USHORT nRowSpan; // ueberspannte Zeilen USHORT nColSpan; // ueberspannte Spalten BOOL bPrcWidthOpt; public: SwWriteTableCell(const SwTableBox *pB, USHORT nR, USHORT nC, USHORT nRSpan, USHORT nCSpan, long nHght, const SvxBrushItem *pBGround) : pBox( pB ), pBackground( pBGround ), nHeight( nHght ), nWidthOpt( 0 ), nRow( nR ), nCol( nC ), nRowSpan( nRSpan ), nColSpan( nCSpan ), bPrcWidthOpt( FALSE ) {} const SwTableBox *GetBox() const { return pBox; } USHORT GetRow() const { return nRow; } USHORT GetCol() const { return nCol; } USHORT GetRowSpan() const { return nRowSpan; } USHORT GetColSpan() const { return nColSpan; } long GetHeight() const { return nHeight; } SwVertOrient GetVertOri() const; const SvxBrushItem *GetBackground() const { return pBackground; } void SetWidthOpt( USHORT nWidth, BOOL bPrc ) { nWidthOpt = nWidth; bPrcWidthOpt = bPrc; } USHORT GetWidthOpt() const { return nWidthOpt; } BOOL HasPrcWidthOpt() const { return bPrcWidthOpt; } }; typedef SwWriteTableCell *SwWriteTableCellPtr; SV_DECL_PTRARR_DEL( SwWriteTableCells, SwWriteTableCellPtr, 5, 5 ) //----------------------------------------------------------------------- class SwWriteTableRow { SwWriteTableCells aCells; // Alle Zellen der Rows const SvxBrushItem *pBackground;// Hintergrund long nPos; // End-Position (twips) der Zeile BOOL mbUseLayoutHeights; public: USHORT nTopBorder; // Dicke der oberen/unteren Umrandugen USHORT nBottomBorder; BOOL bTopBorder : 1; // Welche Umrandungen sind da? BOOL bBottomBorder : 1; SwWriteTableRow( long nPos, BOOL bUseLayoutHeights ); SwWriteTableCell *AddCell( const SwTableBox *pBox, USHORT nRow, USHORT nCol, USHORT nRowSpan, USHORT nColSpan, long nHeight, const SvxBrushItem *pBackground ); void SetBackground( const SvxBrushItem *pBGround ) { pBackground = pBGround; } const SvxBrushItem *GetBackground() const { return pBackground; } BOOL HasTopBorder() const { return bTopBorder; } BOOL HasBottomBorder() const { return bBottomBorder; } long GetPos() const { return nPos; } const SwWriteTableCells& GetCells() const { return aCells; } inline int operator==( const SwWriteTableRow& rRow ) const; inline int operator<( const SwWriteTableRow& rRow2 ) const; }; inline int SwWriteTableRow::operator==( const SwWriteTableRow& rRow ) const { // etwas Unschaerfe zulassen return (nPos >= rRow.nPos ? nPos - rRow.nPos : rRow.nPos - nPos ) <= (mbUseLayoutHeights ? 0 : ROWFUZZY); } inline int SwWriteTableRow::operator<( const SwWriteTableRow& rRow ) const { // Da wir hier nur die Wahrheits-Grade 0 und 1 kennen, lassen wir lieber // auch nicht zu, dass x==y und x<y gleichzeitig gilt ;-) return nPos < rRow.nPos - (mbUseLayoutHeights ? 0 : ROWFUZZY); } typedef SwWriteTableRow *SwWriteTableRowPtr; SV_DECL_PTRARR_SORT_DEL( SwWriteTableRows, SwWriteTableRowPtr, 5, 5 ) //----------------------------------------------------------------------- class SwWriteTableCol { USHORT nPos; // End Position der Spalte USHORT nWidthOpt; BOOL bRelWidthOpt : 1; BOOL bOutWidth : 1; // Spaltenbreite ausgeben? public: BOOL bLeftBorder : 1; // Welche Umrandungen sind da? BOOL bRightBorder : 1; SwWriteTableCol( USHORT nPosition ); USHORT GetPos() const { return nPos; } void SetLeftBorder( BOOL bBorder ) { bLeftBorder = bBorder; } BOOL HasLeftBorder() const { return bLeftBorder; } void SetRightBorder( BOOL bBorder ) { bRightBorder = bBorder; } BOOL HasRightBorder() const { return bRightBorder; } void SetOutWidth( BOOL bSet ) { bOutWidth = bSet; } BOOL GetOutWidth() const { return bOutWidth; } inline int operator==( const SwWriteTableCol& rCol ) const; inline int operator<( const SwWriteTableCol& rCol ) const; void SetWidthOpt( USHORT nWidth, BOOL bRel ) { nWidthOpt = nWidth; bRelWidthOpt = bRel; } USHORT GetWidthOpt() const { return nWidthOpt; } BOOL HasRelWidthOpt() const { return bRelWidthOpt; } }; inline int SwWriteTableCol::operator==( const SwWriteTableCol& rCol ) const { // etwas Unschaerfe zulassen return (nPos >= rCol.nPos ? nPos - rCol.nPos : rCol.nPos - nPos ) <= COLFUZZY; } inline int SwWriteTableCol::operator<( const SwWriteTableCol& rCol ) const { // Da wir hier nur die Wahrheits-Grade 0 und 1 kennen, lassen wir lieber // auch nicht zu, dass x==y und x<y gleichzeitig gilt ;-) return nPos < rCol.nPos - COLFUZZY; } typedef SwWriteTableCol *SwWriteTableColPtr; SV_DECL_PTRARR_SORT_DEL( SwWriteTableCols, SwWriteTableColPtr, 5, 5 ) //----------------------------------------------------------------------- class SwWriteTable { protected: SwWriteTableCols aCols; // alle Spalten SwWriteTableRows aRows; // alle Zellen UINT32 nBorderColor; // Umrandungsfarbe USHORT nCellSpacing; // Dicke der inneren Umrandung USHORT nCellPadding; // Absatnd Umrandung-Inhalt USHORT nBorder; // Dicke der ausseren Umrandung USHORT nInnerBorder; // Dicke der inneren Umrandung USHORT nBaseWidth; // Bezugsgroesse fur Breiten SwFmtFrmSize USHORT nHeadEndRow; // letzte Zeile des Tabellen-Kopfes USHORT nLeftSub; USHORT nRightSub; long nTabWidth; // Absolute/Relative Breite der Tabelle BOOL bRelWidths : 1; // Breiten relativ ausgeben? BOOL bUseLayoutHeights : 1; // Layout zur Hoehenbestimmung nehmen? #ifndef PRODUCT BOOL bGetLineHeightCalled : 1; #endif BOOL bColsOption : 1; BOOL bColTags : 1; BOOL bLayoutExport : 1; BOOL bCollectBorderWidth : 1; virtual BOOL ShouldExpandSub( const SwTableBox *pBox, BOOL bExpandedBefore, USHORT nDepth ) const; void CollectTableRowsCols( long nStartRPos, USHORT nStartCPos, long nParentLineHeight, USHORT nParentLineWidth, const SwTableLines& rLines, USHORT nDepth ); void FillTableRowsCols( long nStartRPos, USHORT nStartRow, USHORT nStartCPos, USHORT nStartCol, long nParentLineHeight, USHORT nParentLineWidth, const SwTableLines& rLines, const SvxBrushItem* pLineBrush, USHORT nDepth ); void MergeBorders( const SvxBorderLine* pBorderLine, BOOL bTable ); USHORT MergeBoxBorders( const SwTableBox *pBox, USHORT nRow, USHORT nCol, USHORT nRowSpan, USHORT nColSpan, USHORT &rTopBorder, USHORT &rBottomBorder ); USHORT GetBaseWidth() const { return nBaseWidth; } BOOL HasRelWidths() const { return bRelWidths; } public: static long GetBoxWidth( const SwTableBox *pBox ); protected: long GetLineHeight( const SwTableLine *pLine ); long GetLineHeight( const SwTableBox *pBox ) const; const SvxBrushItem *GetLineBrush( const SwTableBox *pBox, SwWriteTableRow *pRow ); USHORT GetLeftSpace( USHORT nCol ) const; USHORT GetRightSpace( USHORT nCol, USHORT nColSpan ) const; USHORT GetRawWidth( USHORT nCol, USHORT nColSpan ) const; USHORT GetAbsWidth( USHORT nCol, USHORT nColSpan ) const; USHORT GetRelWidth( USHORT nCol, USHORT nColSpan ) const; USHORT GetPrcWidth( USHORT nCol, USHORT nColSpan ) const; long GetAbsHeight( long nRawWidth, USHORT nRow, USHORT nRowSpan ) const; public: SwWriteTable( const SwTableLines& rLines, long nWidth, USHORT nBWidth, BOOL bRel, USHORT nMaxDepth = USHRT_MAX, USHORT nLeftSub=0, USHORT nRightSub=0 ); SwWriteTable( const SwHTMLTableLayout *pLayoutInfo ); const SwWriteTableCols& GetCols() const { return aCols; } const SwWriteTableRows& GetRows() const { return aRows; } }; #endif <commit_msg>INTEGRATION: CWS mullingarfilterteam18 (1.3.444); FILE MERGED 2003/11/17 13:59:26 cmc 1.3.444.1: #i9055# add dtor to SwWriteTable<commit_after>/************************************************************************* * * $RCSfile: wrtswtbl.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: obo $ $Date: 2004-01-13 16:46:57 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _WRTSWTBL_HXX #define _WRTSWTBL_HXX #ifndef _SOLAR_H #include <tools/solar.h> #endif #ifndef _TOOLS_COLOR_HXX #include <tools/color.hxx> #endif #ifndef _SVARRAY_HXX #include <svtools/svarray.hxx> #endif #ifndef _ORNTENUM_HXX #include <orntenum.hxx> #endif #ifndef _HORIORNT_HXX #include <horiornt.hxx> #endif class Color; class SwTableBox; class SwTableBoxes; class SwTableLine; class SwTableLines; class SwTable; class SwFrmFmt; class SwHTMLTableLayout; class SvxBrushItem; class SvxBoxItem; class SvxBorderLine; //--------------------------------------------------------------------------- // Code aus dem HTML-Filter fuers schreiben von Tabellen //--------------------------------------------------------------------------- #define COLFUZZY 20 #define ROWFUZZY 20 #define COL_DFLT_WIDTH ((2*COLFUZZY)+1) #define ROW_DFLT_HEIGHT (2*ROWFUZZY)+1 //----------------------------------------------------------------------- class SwWriteTableCell { const SwTableBox *pBox; // SwTableBox der Zelle const SvxBrushItem *pBackground; // geerbter Hintergrund einer Zeile long nHeight; // fixe/Mindest-Hoehe der Zeile USHORT nWidthOpt; // Breite aus Option; USHORT nRow; // Start-Zeile USHORT nCol; // Start-Spalte USHORT nRowSpan; // ueberspannte Zeilen USHORT nColSpan; // ueberspannte Spalten BOOL bPrcWidthOpt; public: SwWriteTableCell(const SwTableBox *pB, USHORT nR, USHORT nC, USHORT nRSpan, USHORT nCSpan, long nHght, const SvxBrushItem *pBGround) : pBox( pB ), pBackground( pBGround ), nHeight( nHght ), nWidthOpt( 0 ), nRow( nR ), nCol( nC ), nRowSpan( nRSpan ), nColSpan( nCSpan ), bPrcWidthOpt( FALSE ) {} const SwTableBox *GetBox() const { return pBox; } USHORT GetRow() const { return nRow; } USHORT GetCol() const { return nCol; } USHORT GetRowSpan() const { return nRowSpan; } USHORT GetColSpan() const { return nColSpan; } long GetHeight() const { return nHeight; } SwVertOrient GetVertOri() const; const SvxBrushItem *GetBackground() const { return pBackground; } void SetWidthOpt( USHORT nWidth, BOOL bPrc ) { nWidthOpt = nWidth; bPrcWidthOpt = bPrc; } USHORT GetWidthOpt() const { return nWidthOpt; } BOOL HasPrcWidthOpt() const { return bPrcWidthOpt; } }; typedef SwWriteTableCell *SwWriteTableCellPtr; SV_DECL_PTRARR_DEL( SwWriteTableCells, SwWriteTableCellPtr, 5, 5 ) //----------------------------------------------------------------------- class SwWriteTableRow { SwWriteTableCells aCells; // Alle Zellen der Rows const SvxBrushItem *pBackground;// Hintergrund long nPos; // End-Position (twips) der Zeile BOOL mbUseLayoutHeights; public: USHORT nTopBorder; // Dicke der oberen/unteren Umrandugen USHORT nBottomBorder; BOOL bTopBorder : 1; // Welche Umrandungen sind da? BOOL bBottomBorder : 1; SwWriteTableRow( long nPos, BOOL bUseLayoutHeights ); SwWriteTableCell *AddCell( const SwTableBox *pBox, USHORT nRow, USHORT nCol, USHORT nRowSpan, USHORT nColSpan, long nHeight, const SvxBrushItem *pBackground ); void SetBackground( const SvxBrushItem *pBGround ) { pBackground = pBGround; } const SvxBrushItem *GetBackground() const { return pBackground; } BOOL HasTopBorder() const { return bTopBorder; } BOOL HasBottomBorder() const { return bBottomBorder; } long GetPos() const { return nPos; } const SwWriteTableCells& GetCells() const { return aCells; } inline int operator==( const SwWriteTableRow& rRow ) const; inline int operator<( const SwWriteTableRow& rRow2 ) const; }; inline int SwWriteTableRow::operator==( const SwWriteTableRow& rRow ) const { // etwas Unschaerfe zulassen return (nPos >= rRow.nPos ? nPos - rRow.nPos : rRow.nPos - nPos ) <= (mbUseLayoutHeights ? 0 : ROWFUZZY); } inline int SwWriteTableRow::operator<( const SwWriteTableRow& rRow ) const { // Da wir hier nur die Wahrheits-Grade 0 und 1 kennen, lassen wir lieber // auch nicht zu, dass x==y und x<y gleichzeitig gilt ;-) return nPos < rRow.nPos - (mbUseLayoutHeights ? 0 : ROWFUZZY); } typedef SwWriteTableRow *SwWriteTableRowPtr; SV_DECL_PTRARR_SORT_DEL( SwWriteTableRows, SwWriteTableRowPtr, 5, 5 ) //----------------------------------------------------------------------- class SwWriteTableCol { USHORT nPos; // End Position der Spalte USHORT nWidthOpt; BOOL bRelWidthOpt : 1; BOOL bOutWidth : 1; // Spaltenbreite ausgeben? public: BOOL bLeftBorder : 1; // Welche Umrandungen sind da? BOOL bRightBorder : 1; SwWriteTableCol( USHORT nPosition ); USHORT GetPos() const { return nPos; } void SetLeftBorder( BOOL bBorder ) { bLeftBorder = bBorder; } BOOL HasLeftBorder() const { return bLeftBorder; } void SetRightBorder( BOOL bBorder ) { bRightBorder = bBorder; } BOOL HasRightBorder() const { return bRightBorder; } void SetOutWidth( BOOL bSet ) { bOutWidth = bSet; } BOOL GetOutWidth() const { return bOutWidth; } inline int operator==( const SwWriteTableCol& rCol ) const; inline int operator<( const SwWriteTableCol& rCol ) const; void SetWidthOpt( USHORT nWidth, BOOL bRel ) { nWidthOpt = nWidth; bRelWidthOpt = bRel; } USHORT GetWidthOpt() const { return nWidthOpt; } BOOL HasRelWidthOpt() const { return bRelWidthOpt; } }; inline int SwWriteTableCol::operator==( const SwWriteTableCol& rCol ) const { // etwas Unschaerfe zulassen return (nPos >= rCol.nPos ? nPos - rCol.nPos : rCol.nPos - nPos ) <= COLFUZZY; } inline int SwWriteTableCol::operator<( const SwWriteTableCol& rCol ) const { // Da wir hier nur die Wahrheits-Grade 0 und 1 kennen, lassen wir lieber // auch nicht zu, dass x==y und x<y gleichzeitig gilt ;-) return nPos < rCol.nPos - COLFUZZY; } typedef SwWriteTableCol *SwWriteTableColPtr; SV_DECL_PTRARR_SORT_DEL( SwWriteTableCols, SwWriteTableColPtr, 5, 5 ) //----------------------------------------------------------------------- class SwWriteTable { protected: SwWriteTableCols aCols; // alle Spalten SwWriteTableRows aRows; // alle Zellen UINT32 nBorderColor; // Umrandungsfarbe USHORT nCellSpacing; // Dicke der inneren Umrandung USHORT nCellPadding; // Absatnd Umrandung-Inhalt USHORT nBorder; // Dicke der ausseren Umrandung USHORT nInnerBorder; // Dicke der inneren Umrandung USHORT nBaseWidth; // Bezugsgroesse fur Breiten SwFmtFrmSize USHORT nHeadEndRow; // letzte Zeile des Tabellen-Kopfes USHORT nLeftSub; USHORT nRightSub; long nTabWidth; // Absolute/Relative Breite der Tabelle BOOL bRelWidths : 1; // Breiten relativ ausgeben? BOOL bUseLayoutHeights : 1; // Layout zur Hoehenbestimmung nehmen? #ifndef PRODUCT BOOL bGetLineHeightCalled : 1; #endif BOOL bColsOption : 1; BOOL bColTags : 1; BOOL bLayoutExport : 1; BOOL bCollectBorderWidth : 1; virtual BOOL ShouldExpandSub( const SwTableBox *pBox, BOOL bExpandedBefore, USHORT nDepth ) const; void CollectTableRowsCols( long nStartRPos, USHORT nStartCPos, long nParentLineHeight, USHORT nParentLineWidth, const SwTableLines& rLines, USHORT nDepth ); void FillTableRowsCols( long nStartRPos, USHORT nStartRow, USHORT nStartCPos, USHORT nStartCol, long nParentLineHeight, USHORT nParentLineWidth, const SwTableLines& rLines, const SvxBrushItem* pLineBrush, USHORT nDepth ); void MergeBorders( const SvxBorderLine* pBorderLine, BOOL bTable ); USHORT MergeBoxBorders( const SwTableBox *pBox, USHORT nRow, USHORT nCol, USHORT nRowSpan, USHORT nColSpan, USHORT &rTopBorder, USHORT &rBottomBorder ); USHORT GetBaseWidth() const { return nBaseWidth; } BOOL HasRelWidths() const { return bRelWidths; } public: static long GetBoxWidth( const SwTableBox *pBox ); protected: long GetLineHeight( const SwTableLine *pLine ); long GetLineHeight( const SwTableBox *pBox ) const; const SvxBrushItem *GetLineBrush( const SwTableBox *pBox, SwWriteTableRow *pRow ); USHORT GetLeftSpace( USHORT nCol ) const; USHORT GetRightSpace( USHORT nCol, USHORT nColSpan ) const; USHORT GetRawWidth( USHORT nCol, USHORT nColSpan ) const; USHORT GetAbsWidth( USHORT nCol, USHORT nColSpan ) const; USHORT GetRelWidth( USHORT nCol, USHORT nColSpan ) const; USHORT GetPrcWidth( USHORT nCol, USHORT nColSpan ) const; long GetAbsHeight( long nRawWidth, USHORT nRow, USHORT nRowSpan ) const; public: SwWriteTable( const SwTableLines& rLines, long nWidth, USHORT nBWidth, BOOL bRel, USHORT nMaxDepth = USHRT_MAX, USHORT nLeftSub=0, USHORT nRightSub=0 ); SwWriteTable( const SwHTMLTableLayout *pLayoutInfo ); virtual ~SwWriteTable(); const SwWriteTableCols& GetCols() const { return aCols; } const SwWriteTableRows& GetRows() const { return aRows; } }; #endif <|endoftext|>
<commit_before>/* * Copyright 2011-2017 Branimir Karadzic. All rights reserved. * License: https://github.com/bkaradzic/bx#license-bsd-2-clause */ #include <string> #include <vector> #include <bx/commandline.h> #include <bx/crtimpl.h> #include <bx/string.h> class Bin2cWriter : public bx::WriterI { public: Bin2cWriter(bx::WriterI* _writer, const char* _name) : m_writer(_writer) , m_name(_name) { } virtual ~Bin2cWriter() { } virtual int32_t write(const void* _data, int32_t _size, bx::Error* /*_err*/ = NULL) override { const char* data = (const char*)_data; m_buffer.insert(m_buffer.end(), data, data+_size); return _size; } void finish() { #define HEX_DUMP_WIDTH 16 #define HEX_DUMP_SPACE_WIDTH 96 #define HEX_DUMP_FORMAT "%-" BX_STRINGIZE(HEX_DUMP_SPACE_WIDTH) "." BX_STRINGIZE(HEX_DUMP_SPACE_WIDTH) "s" const uint8_t* data = &m_buffer[0]; uint32_t size = (uint32_t)m_buffer.size(); bx::writePrintf(m_writer, "static const uint8_t %s[%d] =\n{\n", m_name.c_str(), size); if (NULL != data) { char hex[HEX_DUMP_SPACE_WIDTH+1]; char ascii[HEX_DUMP_WIDTH+1]; uint32_t hexPos = 0; uint32_t asciiPos = 0; for (uint32_t ii = 0; ii < size; ++ii) { bx::snprintf(&hex[hexPos], sizeof(hex)-hexPos, "0x%02x, ", data[asciiPos]); hexPos += 6; ascii[asciiPos] = isprint(data[asciiPos]) && data[asciiPos] != '\\' ? data[asciiPos] : '.'; asciiPos++; if (HEX_DUMP_WIDTH == asciiPos) { ascii[asciiPos] = '\0'; bx::writePrintf(m_writer, "\t" HEX_DUMP_FORMAT "// %s\n", hex, ascii); data += asciiPos; hexPos = 0; asciiPos = 0; } } if (0 != asciiPos) { ascii[asciiPos] = '\0'; bx::writePrintf(m_writer, "\t" HEX_DUMP_FORMAT "// %s\n", hex, ascii); } } bx::writePrintf(m_writer, "};\n"); #undef HEX_DUMP_WIDTH #undef HEX_DUMP_SPACE_WIDTH #undef HEX_DUMP_FORMAT m_buffer.clear(); } bx::WriterI* m_writer; std::string m_filePath; std::string m_name; typedef std::vector<uint8_t> Buffer; Buffer m_buffer; }; void help(const char* _error = NULL) { bx::WriterI* stdOut = bx::getStdOut(); if (NULL != _error) { bx::writePrintf(stdOut, "Error:\n%s\n\n", _error); } bx::writePrintf(stdOut , "bin2c, binary to C\n" "Copyright 2011-2017 Branimir Karadzic. All rights reserved.\n" "License: https://github.com/bkaradzic/bx#license-bsd-2-clause\n\n" ); bx::writePrintf(stdOut , "Usage: bin2c -f <in> -o <out> -n <name>\n" "\n" "Options:\n" " -f <file path> Input file path.\n" " -o <file path> Output file path.\n" " -n <name> Array name.\n" "\n" "For additional information, see https://github.com/bkaradzic/bx\n" ); } int main(int _argc, const char* _argv[]) { bx::CommandLine cmdLine(_argc, _argv); if (cmdLine.hasArg('h', "help") ) { help(); return bx::kExitFailure; } const char* filePath = cmdLine.findOption('f'); if (NULL == filePath) { help("Input file name must be specified."); return bx::kExitFailure; } const char* outFilePath = cmdLine.findOption('o'); if (NULL == outFilePath) { help("Output file name must be specified."); return bx::kExitFailure; } const char* name = cmdLine.findOption('n'); if (NULL == name) { name = "data"; } void* data = NULL; uint32_t size = 0; bx::FileReader fr; if (bx::open(&fr, filePath) ) { size = uint32_t(bx::getSize(&fr) ); bx::DefaultAllocator allocator; data = BX_ALLOC(&allocator, size); bx::read(&fr, data, size); bx::FileWriter fw; if (bx::open(&fw, outFilePath) ) { Bin2cWriter writer(&fw, name); bx::write(&writer, data, size); writer.finish(); bx::close(&fw); } BX_FREE(&allocator, data); } return 0; } <commit_msg>Fixed build.<commit_after>/* * Copyright 2011-2017 Branimir Karadzic. All rights reserved. * License: https://github.com/bkaradzic/bx#license-bsd-2-clause */ #include <string> #include <vector> #include <bx/commandline.h> #include <bx/file.h> #include <bx/string.h> class Bin2cWriter : public bx::WriterI { public: Bin2cWriter(bx::WriterI* _writer, const char* _name) : m_writer(_writer) , m_name(_name) { } virtual ~Bin2cWriter() { } virtual int32_t write(const void* _data, int32_t _size, bx::Error* /*_err*/ = NULL) override { const char* data = (const char*)_data; m_buffer.insert(m_buffer.end(), data, data+_size); return _size; } void finish() { #define HEX_DUMP_WIDTH 16 #define HEX_DUMP_SPACE_WIDTH 96 #define HEX_DUMP_FORMAT "%-" BX_STRINGIZE(HEX_DUMP_SPACE_WIDTH) "." BX_STRINGIZE(HEX_DUMP_SPACE_WIDTH) "s" const uint8_t* data = &m_buffer[0]; uint32_t size = (uint32_t)m_buffer.size(); bx::writePrintf(m_writer, "static const uint8_t %s[%d] =\n{\n", m_name.c_str(), size); if (NULL != data) { char hex[HEX_DUMP_SPACE_WIDTH+1]; char ascii[HEX_DUMP_WIDTH+1]; uint32_t hexPos = 0; uint32_t asciiPos = 0; for (uint32_t ii = 0; ii < size; ++ii) { bx::snprintf(&hex[hexPos], sizeof(hex)-hexPos, "0x%02x, ", data[asciiPos]); hexPos += 6; ascii[asciiPos] = isprint(data[asciiPos]) && data[asciiPos] != '\\' ? data[asciiPos] : '.'; asciiPos++; if (HEX_DUMP_WIDTH == asciiPos) { ascii[asciiPos] = '\0'; bx::writePrintf(m_writer, "\t" HEX_DUMP_FORMAT "// %s\n", hex, ascii); data += asciiPos; hexPos = 0; asciiPos = 0; } } if (0 != asciiPos) { ascii[asciiPos] = '\0'; bx::writePrintf(m_writer, "\t" HEX_DUMP_FORMAT "// %s\n", hex, ascii); } } bx::writePrintf(m_writer, "};\n"); #undef HEX_DUMP_WIDTH #undef HEX_DUMP_SPACE_WIDTH #undef HEX_DUMP_FORMAT m_buffer.clear(); } bx::WriterI* m_writer; std::string m_filePath; std::string m_name; typedef std::vector<uint8_t> Buffer; Buffer m_buffer; }; void help(const char* _error = NULL) { bx::WriterI* stdOut = bx::getStdOut(); if (NULL != _error) { bx::writePrintf(stdOut, "Error:\n%s\n\n", _error); } bx::writePrintf(stdOut , "bin2c, binary to C\n" "Copyright 2011-2017 Branimir Karadzic. All rights reserved.\n" "License: https://github.com/bkaradzic/bx#license-bsd-2-clause\n\n" ); bx::writePrintf(stdOut , "Usage: bin2c -f <in> -o <out> -n <name>\n" "\n" "Options:\n" " -f <file path> Input file path.\n" " -o <file path> Output file path.\n" " -n <name> Array name.\n" "\n" "For additional information, see https://github.com/bkaradzic/bx\n" ); } int main(int _argc, const char* _argv[]) { bx::CommandLine cmdLine(_argc, _argv); if (cmdLine.hasArg('h', "help") ) { help(); return bx::kExitFailure; } const char* filePath = cmdLine.findOption('f'); if (NULL == filePath) { help("Input file name must be specified."); return bx::kExitFailure; } const char* outFilePath = cmdLine.findOption('o'); if (NULL == outFilePath) { help("Output file name must be specified."); return bx::kExitFailure; } const char* name = cmdLine.findOption('n'); if (NULL == name) { name = "data"; } void* data = NULL; uint32_t size = 0; bx::FileReader fr; if (bx::open(&fr, filePath) ) { size = uint32_t(bx::getSize(&fr) ); bx::DefaultAllocator allocator; data = BX_ALLOC(&allocator, size); bx::read(&fr, data, size); bx::FileWriter fw; if (bx::open(&fw, outFilePath) ) { Bin2cWriter writer(&fw, name); bx::write(&writer, data, size); writer.finish(); bx::close(&fw); } BX_FREE(&allocator, data); } return 0; } <|endoftext|>
<commit_before>// // $Id$ // #include "AVGSDLFontManager.h" #include "AVGException.h" #include "AVGPlayer.h" #include "AVGLogger.h" #include "AVGSDLFont.h" #include <SDL/SDL_ttf.h> #include <iostream> #include <sstream> #include <stdlib.h> using namespace std; AVGSDLFontManager::AVGSDLFontManager (const string& sFontPath) : AVGFontManager(sFontPath) { if (!TTF_WasInit()) { int err = TTF_Init(); if (err == -1) { AVG_TRACE(AVGPlayer::DEBUG_ERROR, "Could not initialize SDL_ttf. Font support is broken."); } } } AVGSDLFontManager::~AVGSDLFontManager () { TTF_Quit(); } IAVGFont * AVGSDLFontManager::loadFont(const string& Filename, int Size) { return new AVGSDLFont(Filename, Size); } <commit_msg>Fixed init for some sdl_ttf versions<commit_after>// // $Id$ // #include "AVGSDLFontManager.h" #include "AVGException.h" #include "AVGPlayer.h" #include "AVGLogger.h" #include "AVGSDLFont.h" #include <SDL/SDL_ttf.h> #include <iostream> #include <sstream> #include <stdlib.h> using namespace std; AVGSDLFontManager::AVGSDLFontManager (const string& sFontPath) : AVGFontManager(sFontPath) { // if (!TTF_WasInit()) { int err = TTF_Init(); if (err == -1) { AVG_TRACE(AVGPlayer::DEBUG_ERROR, "Could not initialize SDL_ttf. Font support is broken."); } // } } AVGSDLFontManager::~AVGSDLFontManager () { TTF_Quit(); } IAVGFont * AVGSDLFontManager::loadFont(const string& Filename, int Size) { return new AVGSDLFont(Filename, Size); } <|endoftext|>
<commit_before>#include <iostream> #include <malloc.h> #include <cstdlib> #include "stxxl/bits/common/utils.h" using std::cin; using std::cout; using std::cerr; using std::endl; void print_malloc_stats() { struct mallinfo info = mallinfo(); STXXL_MSG("MALLOC statistics BEGIN"); STXXL_MSG("==============================================================="); STXXL_MSG("non-mmapped space allocated from system (bytes): " << info.arena); STXXL_MSG("number of free chunks : " << info.ordblks); STXXL_MSG("number of fastbin blocks : " << info.smblks); STXXL_MSG("number of chunks allocated via mmap() : " << info.hblks); STXXL_MSG("total number of bytes allocated via mmap() : " << info.hblkhd); STXXL_MSG("maximum total allocated space (bytes) : " << info.usmblks); STXXL_MSG("space available in freed fastbin blocks (bytes): " << info.fsmblks); STXXL_MSG("number of bytes allocated and in use : " << info.uordblks); STXXL_MSG("number of bytes allocated but not in use : " << info.fordblks); STXXL_MSG("top-most, releasable (via malloc_trim) space : " << info.keepcost); STXXL_MSG("================================================================"); } int main(int argc, char * argv[]) { if (argc < 2) { cerr << "Usage: " << argv[0] << " bytes_to_allocate" << endl; return -1; } sbrk(128 * 1024 * 1024); cout << "Nothing allocated" << endl; print_malloc_stats(); char tmp; cin >> tmp; const unsigned bytes = atoi(argv[1]); char * ptr = new char[bytes]; cout << "Allocated " << bytes << " bytes" << endl; print_malloc_stats(); delete[] ptr; cout << "Deallocated " << endl; print_malloc_stats(); } <commit_msg>struct mallinfo is not available on macosx<commit_after>#include <iostream> #ifndef __APPLE__ #include <malloc.h> #endif #include <cstdlib> #include "stxxl/bits/common/utils.h" using std::cin; using std::cout; using std::cerr; using std::endl; void print_malloc_stats() { #ifndef __APPLE__ struct mallinfo info = mallinfo(); STXXL_MSG("MALLOC statistics BEGIN"); STXXL_MSG("==============================================================="); STXXL_MSG("non-mmapped space allocated from system (bytes): " << info.arena); STXXL_MSG("number of free chunks : " << info.ordblks); STXXL_MSG("number of fastbin blocks : " << info.smblks); STXXL_MSG("number of chunks allocated via mmap() : " << info.hblks); STXXL_MSG("total number of bytes allocated via mmap() : " << info.hblkhd); STXXL_MSG("maximum total allocated space (bytes) : " << info.usmblks); STXXL_MSG("space available in freed fastbin blocks (bytes): " << info.fsmblks); STXXL_MSG("number of bytes allocated and in use : " << info.uordblks); STXXL_MSG("number of bytes allocated but not in use : " << info.fordblks); STXXL_MSG("top-most, releasable (via malloc_trim) space : " << info.keepcost); STXXL_MSG("================================================================"); #else STXXL_MSG("MALLOC statistics are not supported on this platform"); #endif } int main(int argc, char * argv[]) { if (argc < 2) { cerr << "Usage: " << argv[0] << " bytes_to_allocate" << endl; return -1; } sbrk(128 * 1024 * 1024); cout << "Nothing allocated" << endl; print_malloc_stats(); char tmp; cin >> tmp; const unsigned bytes = atoi(argv[1]); char * ptr = new char[bytes]; cout << "Allocated " << bytes << " bytes" << endl; print_malloc_stats(); delete[] ptr; cout << "Deallocated " << endl; print_malloc_stats(); } <|endoftext|>
<commit_before>#include "Arduino.h" #include <EBot.h> #define IN1 6 #define IN2 7 #define IN3 8 #define IN4 9 #define ENA 5 #define ENB 11 #define ServoPin 3 #define Echo A4 #define Trig A5 #define receiverpin 12 #define LS1 10 #define LS2 4 #define LS3 2 EBot::EBot() { } EBot::~EBot() { } void EBot::begin() { pinMode(IN1, OUTPUT); pinMode(IN2, OUTPUT); pinMode(IN3, OUTPUT); pinMode(IN4, OUTPUT); pinMode(ENA, OUTPUT); pinMode(ENB, OUTPUT); pinMode(Echo, INPUT); pinMode(Trig, OUTPUT); servo.attach(ServoPin); servo.write(90); } void EBot::stop() { digitalWrite(ENA, LOW); digitalWrite(IN1, LOW); digitalWrite(IN2, LOW); digitalWrite(ENB, LOW); digitalWrite(IN3, LOW); digitalWrite(IN4, LOW); } void EBot::rightWheelForward() { digitalWrite(ENA, HIGH); digitalWrite(IN1, HIGH); digitalWrite(IN2, LOW); } void EBot::rightWheelForward(int speed) { analogWrite(ENA, speed); digitalWrite(IN1, HIGH); digitalWrite(IN2, LOW); } void EBot::rightWheelBackward() { digitalWrite(ENA, HIGH); digitalWrite(IN1, LOW); digitalWrite(IN2, HIGH); } void EBot::rightWheelBackward(int speed) { analogWrite(ENA, speed); digitalWrite(IN1, LOW); digitalWrite(IN2, HIGH); } void EBot::rightWheelStop() { digitalWrite(ENA, LOW); digitalWrite(IN1, LOW); digitalWrite(IN2, LOW); } void EBot::leftWheelForward() { digitalWrite(ENB, HIGH); digitalWrite(IN3, LOW); digitalWrite(IN4, HIGH); } void EBot::leftWheelForward(int speed) { analogWrite(ENB, speed); digitalWrite(IN3, LOW); digitalWrite(IN4, HIGH); } void EBot::leftWheelBackward() { digitalWrite(ENB, HIGH); digitalWrite(IN3, HIGH); digitalWrite(IN4, LOW); } void EBot::leftWheelBackward(int speed) { analogWrite(ENB, speed); digitalWrite(IN3, HIGH); digitalWrite(IN4, LOW); } void EBot::leftWheelStop() { digitalWrite(ENB, LOW); digitalWrite(IN3, LOW); digitalWrite(IN4, LOW); } void EBot::forward() { digitalWrite(ENA, HIGH); digitalWrite(IN1, HIGH); digitalWrite(IN2, LOW); digitalWrite(ENB, HIGH); digitalWrite(IN3, LOW); digitalWrite(IN4, HIGH); } void EBot::forward(int speed) { analogWrite(ENA, speed); digitalWrite(IN1, HIGH); digitalWrite(IN2, LOW); analogWrite(ENB, speed); digitalWrite(IN3, LOW); digitalWrite(IN4, HIGH); } void EBot::backward() { digitalWrite(ENA, HIGH); digitalWrite(IN1, LOW); digitalWrite(IN2, HIGH); digitalWrite(ENB, HIGH); digitalWrite(IN3, HIGH); digitalWrite(IN4, LOW); } void EBot::backward(int speed) { analogWrite(ENA, speed); digitalWrite(IN1, LOW); digitalWrite(IN2, HIGH); analogWrite(ENB, speed); digitalWrite(IN3, HIGH); digitalWrite(IN4, LOW); } void EBot::rotateRight() { digitalWrite(ENA, HIGH); digitalWrite(IN1, LOW); digitalWrite(IN2, HIGH); digitalWrite(ENB, HIGH); digitalWrite(IN3, LOW); digitalWrite(IN4, HIGH); } void EBot::rotateRight(int speed) { analogWrite(ENA, speed); digitalWrite(IN1, LOW); digitalWrite(IN2, HIGH); analogWrite(ENB, speed); digitalWrite(IN3, LOW); digitalWrite(IN4, HIGH); } void EBot::rotateLeft() { digitalWrite(ENA, HIGH); digitalWrite(IN1, HIGH); digitalWrite(IN2, LOW); digitalWrite(ENB, HIGH); digitalWrite(IN3, HIGH); digitalWrite(IN4, LOW); } void EBot::rotateLeft(int speed) { analogWrite(ENA, speed); digitalWrite(IN1, HIGH); digitalWrite(IN2, LOW); analogWrite(ENB, speed); digitalWrite(IN3, HIGH); digitalWrite(IN4, LOW); } void EBot::write(int angle) { angle = angle < 0 ? 0 : angle; angle = angle > 180 ? 180 : angle; servo.write(angle); } unsigned long EBot::distance() { unsigned long duration; digitalWrite(Trig, LOW); delayMicroseconds(2); digitalWrite(Trig, HIGH); delayMicroseconds(5); digitalWrite(Trig, LOW); duration = pulseIn(Echo, HIGH); return duration / 29 / 2; } bool EBot::readLS1() { return digitalRead(LS1); } bool EBot::readLS2() { return digitalRead(LS2); } bool EBot::readLS3() { return digitalRead(LS3); } <commit_msg>added security checks<commit_after>#include "Arduino.h" #include <EBot.h> #define IN1 6 #define IN2 7 #define IN3 8 #define IN4 9 #define ENA 5 #define ENB 11 #define ServoPin 3 #define Echo A4 #define Trig A5 #define receiverpin 12 #define LS1 10 #define LS2 4 #define LS3 2 EBot::EBot() { } EBot::~EBot() { } void EBot::begin() { pinMode(IN1, OUTPUT); pinMode(IN2, OUTPUT); pinMode(IN3, OUTPUT); pinMode(IN4, OUTPUT); pinMode(ENA, OUTPUT); pinMode(ENB, OUTPUT); pinMode(Echo, INPUT); pinMode(Trig, OUTPUT); servo.attach(ServoPin); servo.write(90); } void EBot::stop() { digitalWrite(ENA, LOW); digitalWrite(IN1, LOW); digitalWrite(IN2, LOW); digitalWrite(ENB, LOW); digitalWrite(IN3, LOW); digitalWrite(IN4, LOW); } void EBot::rightWheelForward() { digitalWrite(ENA, HIGH); digitalWrite(IN1, HIGH); digitalWrite(IN2, LOW); } void EBot::rightWheelForward(int speed) { speed = boundaries(speed, 0, 255); analogWrite(ENA, speed); digitalWrite(IN1, HIGH); digitalWrite(IN2, LOW); } void EBot::rightWheelBackward() { digitalWrite(ENA, HIGH); digitalWrite(IN1, LOW); digitalWrite(IN2, HIGH); } void EBot::rightWheelBackward(int speed) { speed = boundaries(speed, 0, 255); analogWrite(ENA, speed); digitalWrite(IN1, LOW); digitalWrite(IN2, HIGH); } void EBot::rightWheelStop() { digitalWrite(ENA, LOW); digitalWrite(IN1, LOW); digitalWrite(IN2, LOW); } void EBot::leftWheelForward() { digitalWrite(ENB, HIGH); digitalWrite(IN3, LOW); digitalWrite(IN4, HIGH); } void EBot::leftWheelForward(int speed) { speed = boundaries(speed, 0, 255); analogWrite(ENB, speed); digitalWrite(IN3, LOW); digitalWrite(IN4, HIGH); } void EBot::leftWheelBackward() { digitalWrite(ENB, HIGH); digitalWrite(IN3, HIGH); digitalWrite(IN4, LOW); } void EBot::leftWheelBackward(int speed) { speed = boundaries(speed, 0, 255); analogWrite(ENB, speed); digitalWrite(IN3, HIGH); digitalWrite(IN4, LOW); } void EBot::leftWheelStop() { digitalWrite(ENB, LOW); digitalWrite(IN3, LOW); digitalWrite(IN4, LOW); } void EBot::forward() { digitalWrite(ENA, HIGH); digitalWrite(IN1, HIGH); digitalWrite(IN2, LOW); digitalWrite(ENB, HIGH); digitalWrite(IN3, LOW); digitalWrite(IN4, HIGH); } void EBot::forward(int speed) { speed = boundaries(speed, 0, 255); analogWrite(ENA, speed); digitalWrite(IN1, HIGH); digitalWrite(IN2, LOW); analogWrite(ENB, speed); digitalWrite(IN3, LOW); digitalWrite(IN4, HIGH); } void EBot::backward() { digitalWrite(ENA, HIGH); digitalWrite(IN1, LOW); digitalWrite(IN2, HIGH); digitalWrite(ENB, HIGH); digitalWrite(IN3, HIGH); digitalWrite(IN4, LOW); } void EBot::backward(int speed) { speed = boundaries(speed, 0, 255); analogWrite(ENA, speed); digitalWrite(IN1, LOW); digitalWrite(IN2, HIGH); analogWrite(ENB, speed); digitalWrite(IN3, HIGH); digitalWrite(IN4, LOW); } void EBot::rotateRight() { digitalWrite(ENA, HIGH); digitalWrite(IN1, LOW); digitalWrite(IN2, HIGH); digitalWrite(ENB, HIGH); digitalWrite(IN3, LOW); digitalWrite(IN4, HIGH); } void EBot::rotateRight(int speed) { speed = boundaries(speed, 0, 255); analogWrite(ENA, speed); digitalWrite(IN1, LOW); digitalWrite(IN2, HIGH); analogWrite(ENB, speed); digitalWrite(IN3, LOW); digitalWrite(IN4, HIGH); } void EBot::rotateLeft() { digitalWrite(ENA, HIGH); digitalWrite(IN1, HIGH); digitalWrite(IN2, LOW); digitalWrite(ENB, HIGH); digitalWrite(IN3, HIGH); digitalWrite(IN4, LOW); } void EBot::rotateLeft(int speed) { speed = boundaries(speed, 0, 255); analogWrite(ENA, speed); digitalWrite(IN1, HIGH); digitalWrite(IN2, LOW); analogWrite(ENB, speed); digitalWrite(IN3, HIGH); digitalWrite(IN4, LOW); } void EBot::write(int angle) { angle = boundaries(angle, 0, 180); servo.write(angle); } unsigned long EBot::distance() { unsigned long duration; digitalWrite(Trig, LOW); delayMicroseconds(2); digitalWrite(Trig, HIGH); delayMicroseconds(5); digitalWrite(Trig, LOW); duration = pulseIn(Echo, HIGH); return duration / 29 / 2; } bool EBot::readLS1() { return digitalRead(LS1); } bool EBot::readLS2() { return digitalRead(LS2); } bool EBot::readLS3() { return digitalRead(LS3); } int EBot::boundaries(int value, int min, int max) { value = value < min ? min : value; value = value > max ? max : value; return value; } <|endoftext|>
<commit_before>/** * Project * # # # ###### ###### * # # # # # # # # * # # # # # # # # * ### # # ###### ###### * # # ####### # # # # * # # # # # # # # * # # # # # # # # * * Copyright (c) 2014, Project KARR * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "AngularInstrument.h" AngularInstrument::AngularInstrument() : Instrument() { } AngularInstrument::~AngularInstrument() { } void AngularInstrument::draw() { } bool AngularInstrument::parseFromTree(boost::property_tree::ptree &) { return false; } <commit_msg>Add implementation for update.<commit_after>/** * Project * # # # ###### ###### * # # # # # # # # * # # # # # # # # * ### # # ###### ###### * # # ####### # # # # * # # # # # # # # * # # # # # # # # * * Copyright (c) 2014, Project KARR * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "AngularInstrument.h" AngularInstrument::AngularInstrument() : Instrument() { } AngularInstrument::~AngularInstrument() { } void AngularInstrument::draw() { } void AngularInstrument::update(float newVal) { } bool AngularInstrument::parseFromTree(boost::property_tree::ptree &) { return false; } <|endoftext|>
<commit_before> /* Jim Viebke Oct 21, 2015*/ #include "utilities.h" // string utilities unsigned U::to_unsigned(const std::string & word) { // "a1b2c3" will return 123. "abc" will return 0. unsigned count = 0; for (const char & digit : word) // for each character in the second command { if (digit >= '0' && digit <= '9') // if the character is a digit { count *= 10; // shift digits to the left count += digit - '0'; // add newest digit } } return count; } void U::to_lower_case(std::string & word) { // convert a vector of strings passed by reference to a vector of lowercase strings if (word.length() > 0) { std::transform(word.begin(), word.end(), word.begin(), ::tolower); } } std::string U::capitalize(std::string & word) { // immediately return the string if it is empty if (word.size() == 0) return word; // if the first letter is in the range a-z, convert the letter to capital by subtracting 32 if (word[0] >= 'a' && word[0] <= 'z') word[0] -= 32; return word; } std::string U::capitalize(const std::string & word) { // immediately return the string if it is empty if (word.size() == 0) return word; // copy 'word' to a string that can be modified std::string result = word; // if the first letter is in the range a-z, convert the letter to capital by subtracting 32 if (result[0] >= 'a' && result[0] <= 'z') result[0] -= 32; return result; } // grammar std::string U::get_article_for(const std::string & noun) { // get an iterator to the <key, value> pair for <noun, article> const std::map<std::string, std::string>::const_iterator it = C::articles.find(noun); // return the article if the key exists, else return generic "a(n)". return ((it != C::articles.cend()) ? it->second : "a(n)"); } std::string U::get_plural_for(const std::string & noun) { // get an iterator to the <key, value> pair for <noun, article> const std::map<std::string, std::string>::const_iterator it = C::plurals.find(noun); // return the article if the key exists, else return the original noun return ((it != C::plurals.cend()) ? it->second : noun); } std::string U::get_singular_for(const std::string & noun) { for (const auto & pair : C::articles) { if (pair.second == noun) return pair.first; } return noun; // return the original word if the singular form could not be found } // math int U::euclidean_distance(const int & x1, const int & y1, const int & x2, const int & y2) { int x_diff = difference(x1, x2); int y_diff = difference(y1, y2); return static_cast<int>(sqrt( // use Pythagoras' theorem (x_diff * x_diff) + (y_diff * y_diff) )); } int U::diagonal_distance(const int & x1, const int & y1, const int & x2, const int & y2) { return std::max(difference(x1, x2), difference(x2, y2)); } // pathfinding int U::diagonal_movement_cost(const int & x1, const int & y1, const int & x2, const int & y2) { // Because this uses different movement costs, this works for AI pathfinding, but // not so much for determining if a coordinate is visible from another coordinate. // a diagonal move = (sqrt(2) * straight move) int dx = abs(x1 - x2); int dy = abs(y1 - y2); return C::AI_MOVEMENT_COST * (dx + dy) + (C::AI_MOVEMENT_COST_DIAGONAL - 2 * C::AI_MOVEMENT_COST) * std::min(dx, dy); } // random utils int U::random_int_from(const int & min, const int & max) { return min + (rand() % (max - min + 1)); } unsigned U::random_int_from(const unsigned & min, const unsigned & max) { return min + (rand() % (max - min + 1)); } <commit_msg>documentation<commit_after> /* Jim Viebke Oct 21, 2015*/ #include "utilities.h" // string utilities unsigned U::to_unsigned(const std::string & word) { // "a1b2c3" will return 123. "abc" will return 0. unsigned count = 0; for (const char & digit : word) // for each character in the second command { if (digit >= '0' && digit <= '9') // if the character is a digit { count *= 10; // shift digits to the left count += digit - '0'; // add newest digit } } return count; } void U::to_lower_case(std::string & word) { // convert a vector of strings passed by reference to a vector of lowercase strings if (word.length() > 0) { std::transform(word.begin(), word.end(), word.begin(), ::tolower); } } std::string U::capitalize(std::string & word) { // immediately return the string if it is empty if (word.size() == 0) return word; // if the first letter is in the range a-z, convert the letter to capital by subtracting 32 if (word[0] >= 'a' && word[0] <= 'z') word[0] -= 32; return word; } std::string U::capitalize(const std::string & word) { // immediately return the string if it is empty if (word.size() == 0) return word; // copy 'word' to a string that can be modified std::string result = word; // if the first letter is in the range a-z, convert the letter to capital by subtracting 32 if (result[0] >= 'a' && result[0] <= 'z') result[0] -= 32; return result; } // grammar std::string U::get_article_for(const std::string & noun) { // get an iterator to the <key, value> pair for <noun, article> const std::map<std::string, std::string>::const_iterator it = C::articles.find(noun); // return the article if the key exists, else return generic "a(n)". return ((it != C::articles.cend()) ? it->second : "a(n)"); } std::string U::get_plural_for(const std::string & noun) { // get an iterator to the <key, value> pair for <noun, article> const std::map<std::string, std::string>::const_iterator it = C::plurals.find(noun); // return the article if the key exists, else return the original noun return ((it != C::plurals.cend()) ? it->second : noun); } std::string U::get_singular_for(const std::string & noun) { // We're doing a reverse-lookup here. Not very efficient, but oh well. // for each singular/plural pair for (const auto & pair : C::articles) { // if the plural matches the passed noun if (pair.second == noun) return pair.first; // return the singular form of the passed plural } return noun; // return the original word if the singular form could not be found } // math int U::euclidean_distance(const int & x1, const int & y1, const int & x2, const int & y2) { int x_diff = difference(x1, x2); int y_diff = difference(y1, y2); return static_cast<int>(sqrt( // use Pythagoras' theorem (x_diff * x_diff) + (y_diff * y_diff) )); } int U::diagonal_distance(const int & x1, const int & y1, const int & x2, const int & y2) { return std::max(difference(x1, x2), difference(x2, y2)); } // pathfinding int U::diagonal_movement_cost(const int & x1, const int & y1, const int & x2, const int & y2) { // Because this uses different movement costs, this works for AI pathfinding, but // not so much for determining if a coordinate is visible from another coordinate. // a diagonal move = (sqrt(2) * straight move) int dx = abs(x1 - x2); int dy = abs(y1 - y2); return C::AI_MOVEMENT_COST * (dx + dy) + (C::AI_MOVEMENT_COST_DIAGONAL - 2 * C::AI_MOVEMENT_COST) * std::min(dx, dy); } // random utils int U::random_int_from(const int & min, const int & max) { return min + (rand() % (max - min + 1)); } unsigned U::random_int_from(const unsigned & min, const unsigned & max) { return min + (rand() % (max - min + 1)); } <|endoftext|>
<commit_before> #include "CaptureDeviceImpl.h" #include "Error.h" #include "logging.h" #include "utils.h" #include "serialization.h" using namespace tcam; CaptureDeviceImpl::CaptureDeviceImpl () : pipeline(nullptr), property_handler(nullptr), device(nullptr) {} CaptureDeviceImpl::CaptureDeviceImpl (const DeviceInfo& device) : pipeline(nullptr), property_handler(nullptr), device(nullptr) { if (!openDevice(device)) { tcam_log(TCAM_LOG_ERROR, "Unable to open device"); } } CaptureDeviceImpl::~CaptureDeviceImpl () {} bool CaptureDeviceImpl::load_configuration (const std::string& filename) { resetError(); if (!isDeviceOpen()) { return false; } auto vec = property_handler->get_properties(); return load_xml_description(filename, open_device, active_format, vec); } bool CaptureDeviceImpl::save_configuration (const std::string& filename) { resetError(); if (!isDeviceOpen()) { return false; } return save_xml_description(filename, open_device, device->get_active_video_format(), property_handler->get_properties()); } bool CaptureDeviceImpl::openDevice (const DeviceInfo& device_desc) { resetError(); if (isDeviceOpen()) { bool ret = closeDevice(); if (ret == false) { tcam_log(TCAM_LOG_ERROR, "Unable to close previous device."); // setError(Error("A device is already open", EPERM)); return false; } } open_device = device_desc; device = openDeviceInterface(open_device); if (device == nullptr) { return false; } pipeline = std::make_shared<PipelineManager>(); pipeline->setSource(device); property_handler = std::make_shared<PropertyHandler>(); property_handler->set_properties(device->getProperties(), pipeline->getFilterProperties()); return true; } bool CaptureDeviceImpl::isDeviceOpen () const { resetError(); if (device != nullptr) { return true; } return false; } DeviceInfo CaptureDeviceImpl::getDevice () const { return this->open_device; } bool CaptureDeviceImpl::closeDevice () { if (!isDeviceOpen()) { return true; } std::string name = open_device.get_name(); pipeline->destroyPipeline(); open_device = DeviceInfo (); device.reset(); property_handler = nullptr; tcam_log(TCAM_LOG_INFO, "Closed device %s.", name.c_str()); return true; } std::vector<Property*> CaptureDeviceImpl::getAvailableProperties () { resetError(); if (!isDeviceOpen()) { return std::vector<Property*>(); } std::vector<Property*> props; for ( const auto& p : property_handler->get_properties()) { props.push_back(&*p); } return props; } std::vector<VideoFormatDescription> CaptureDeviceImpl::getAvailableVideoFormats () const { resetError(); if (!isDeviceOpen()) { return std::vector<VideoFormatDescription>(); } return pipeline->getAvailableVideoFormats(); } bool CaptureDeviceImpl::setVideoFormat (const VideoFormat& new_format) { resetError(); if (!isDeviceOpen()) { return false; } pipeline->setVideoFormat(new_format); return this->device->set_video_format(new_format); } VideoFormat CaptureDeviceImpl::getActiveVideoFormat () const { resetError(); if(!isDeviceOpen()) { return VideoFormat(); } return device->get_active_video_format(); } bool CaptureDeviceImpl::startStream (std::shared_ptr<SinkInterface> sink) { resetError(); if (!isDeviceOpen()) { return false; } pipeline->setSink(sink); return pipeline->set_status(TCAM_PIPELINE_PLAYING); } bool CaptureDeviceImpl::stopStream () { resetError(); if (!isDeviceOpen()) { return false; } return pipeline->set_status(TCAM_PIPELINE_STOPPED); } <commit_msg>Add security checks<commit_after> #include "CaptureDeviceImpl.h" #include "Error.h" #include "logging.h" #include "utils.h" #include "serialization.h" using namespace tcam; CaptureDeviceImpl::CaptureDeviceImpl () : pipeline(nullptr), property_handler(nullptr), device(nullptr) {} CaptureDeviceImpl::CaptureDeviceImpl (const DeviceInfo& device) : pipeline(nullptr), property_handler(nullptr), device(nullptr) { if (!openDevice(device)) { tcam_log(TCAM_LOG_ERROR, "Unable to open device"); } } CaptureDeviceImpl::~CaptureDeviceImpl () {} bool CaptureDeviceImpl::load_configuration (const std::string& filename) { resetError(); if (!isDeviceOpen()) { return false; } auto vec = property_handler->get_properties(); return load_xml_description(filename, open_device, active_format, vec); } bool CaptureDeviceImpl::save_configuration (const std::string& filename) { resetError(); if (!isDeviceOpen()) { return false; } return save_xml_description(filename, open_device, device->get_active_video_format(), property_handler->get_properties()); } bool CaptureDeviceImpl::openDevice (const DeviceInfo& device_desc) { resetError(); if (isDeviceOpen()) { bool ret = closeDevice(); if (ret == false) { tcam_log(TCAM_LOG_ERROR, "Unable to close previous device."); // setError(Error("A device is already open", EPERM)); return false; } } open_device = device_desc; device = openDeviceInterface(open_device); if (device == nullptr) { return false; } pipeline = std::make_shared<PipelineManager>(); pipeline->setSource(device); property_handler = std::make_shared<PropertyHandler>(); property_handler->set_properties(device->getProperties(), pipeline->getFilterProperties()); return true; } bool CaptureDeviceImpl::isDeviceOpen () const { resetError(); if (device != nullptr) { return true; } return false; } DeviceInfo CaptureDeviceImpl::getDevice () const { return this->open_device; } bool CaptureDeviceImpl::closeDevice () { if (!isDeviceOpen()) { return true; } std::string name = open_device.get_name(); pipeline->destroyPipeline(); open_device = DeviceInfo (); device.reset(); property_handler = nullptr; tcam_log(TCAM_LOG_INFO, "Closed device %s.", name.c_str()); return true; } std::vector<Property*> CaptureDeviceImpl::getAvailableProperties () { resetError(); if (!isDeviceOpen()) { return std::vector<Property*>(); } std::vector<Property*> props; for ( const auto& p : property_handler->get_properties()) { props.push_back(&*p); } return props; } std::vector<VideoFormatDescription> CaptureDeviceImpl::getAvailableVideoFormats () const { resetError(); if (!isDeviceOpen()) { return std::vector<VideoFormatDescription>(); } return pipeline->getAvailableVideoFormats(); } bool CaptureDeviceImpl::setVideoFormat (const VideoFormat& new_format) { resetError(); if (!isDeviceOpen()) { return false; } pipeline->setVideoFormat(new_format); return this->device->set_video_format(new_format); } VideoFormat CaptureDeviceImpl::getActiveVideoFormat () const { resetError(); if(!isDeviceOpen()) { return VideoFormat(); } return device->get_active_video_format(); } bool CaptureDeviceImpl::startStream (std::shared_ptr<SinkInterface> sink) { resetError(); if (!isDeviceOpen()) { tcam_log(TCAM_LOG_ERROR, "Device is not open"); return false; } if (!pipeline->setSink(sink)) { return false; } return pipeline->set_status(TCAM_PIPELINE_PLAYING); } bool CaptureDeviceImpl::stopStream () { resetError(); if (!isDeviceOpen()) { return false; } return pipeline->set_status(TCAM_PIPELINE_STOPPED); } <|endoftext|>
<commit_before> #include "Gfdi.h" #include <array> #include <cassert> #include <cmath> // helper functions and data namespace { // numerous constants used in the analytic approximations const std::array<double, 5> x = {{ 7.265351e-2, 0.2694608, 0.533122, 0.7868801, 0.9569313}}; const std::array<double, 5> xi = {{ 0.26356032, 1.4134031, 3.5964258, 7.0858100, 12.640801}}; const std::array<double, 5> h = {{ 3.818735e-2, 0.1256732, 0.1986308, 0.1976334, 0.1065420}}; const std::array<double, 5> v = {{ 0.29505869, 0.32064856, 7.3915570e-2, 3.6087389e-3, 2.3369894e-5}}; const std::array<std::array<double, 5>, 3> c = {{ {{0.37045057, 0.41258437, 9.777982e-2, 5.3734153e-3, 3.8746281e-5}}, {{0.39603109, 0.69468795, 0.22322760, 1.5262934e-2, 1.3081939e-4}}, {{0.76934619, 1.7891437, 0.70754974, 5.6755672e-2, 5.5571480e-4}}}}; const std::array<std::array<double, 5>, 3> khi = {{ {{0.43139881, 1.7597537, 4.1044654, 7.7467038, 13.457678}}, {{0.81763176, 2.4723339, 5.1160061, 9.0441465, 15.049882}}, {{1.2558461, 3.2070406, 6.1239082, 10.316126, 16.597079}}}}; double cube(const double x) { return x*x*x; } // helper function for GFDI work double gfdi_helper(const int k, const double chi, const double tau, const double r) { if (chi*tau < 1.e-4 && chi > 0) { return pow(chi, k+3./2)/(k+3./2); } else if (k==0) { return (chi + 1/tau)*r/2 - pow(2*tau, -3./2) * log(1 + tau*chi + sqrt(2*tau)*r); } else if (k==1) { return (2./3*cube(r) - gfdi_helper(0, chi, tau, r)) / tau; } else if (k==2) { return (2*chi*cube(r) - 5*gfdi_helper(1, chi, tau, r)) / (4*tau); } else { return 0.0; } } } // end anonymous namespace double gfdi(const GFDI order, const double chi, const double tau) { // TODO: something more like a SpEC require? assert(tau <= 100. && "GFDI: outside of known convergence region"); const int k = static_cast<int>(order); if (chi <= 0.6) { double value = 0; for (int i=1; i<=5; i++) { value += c[k][i-1] * sqrt(1 + khi[k][i-1]*tau/2) / (exp(-khi[k][i-1]) + exp(-chi)); } return value; } else if (chi < 14) { double value = 0; for (int i=1; i<=5; i++) { value += h[i-1] * pow(x[i-1], k) * pow(chi, k+3./2) * sqrt(1 + chi*x[i-1]*tau/2) / (1 + exp(chi*(x[i-1] - 1))) + v[i-1] * pow(xi[i-1] + chi, k+1./2) * sqrt(1 + (xi[i-1] + chi)*tau/2); } return value; } else { const double r = sqrt(chi*(1 + chi*tau/2)); return gfdi_helper(k, chi, tau, r) + M_PI*M_PI/6. * pow(chi, k) * (k + 1./2 + (k+1)*chi*tau/2) / r; } } <commit_msg>Gfdi: Cleanup and c++11-ify<commit_after> #include "Gfdi.h" #include <array> #include <cassert> #include <cmath> // helper functions and data namespace { // numerous constants used in the analytic approximations //const std::array<double, 5> x = {{ const auto x = std::array<double, 5> {{ 7.265351e-2, 0.2694608, 0.533122, 0.7868801, 0.9569313}}; const auto xi = std::array<double, 5> {{ 0.26356032, 1.4134031, 3.5964258, 7.0858100, 12.640801}}; const auto h = std::array<double, 5> {{ 3.818735e-2, 0.1256732, 0.1986308, 0.1976334, 0.1065420}}; const auto v = std::array<double, 5> {{ 0.29505869, 0.32064856, 7.3915570e-2, 3.6087389e-3, 2.3369894e-5}}; const auto c = std::array<std::array<double, 5>, 3> {{ {{0.37045057, 0.41258437, 9.777982e-2, 5.3734153e-3, 3.8746281e-5}}, {{0.39603109, 0.69468795, 0.22322760, 1.5262934e-2, 1.3081939e-4}}, {{0.76934619, 1.7891437, 0.70754974, 5.6755672e-2, 5.5571480e-4}}}}; const auto khi = std::array<std::array<double, 5>, 3> {{ {{0.43139881, 1.7597537, 4.1044654, 7.7467038, 13.457678}}, {{0.81763176, 2.4723339, 5.1160061, 9.0441465, 15.049882}}, {{1.2558461, 3.2070406, 6.1239082, 10.316126, 16.597079}}}}; inline double cube(const double x) { return x*x*x; } // helper function for GFDI work double gfdi_helper(const int k, const double chi, const double tau, const double r) { if (chi*tau < 1.e-4 && chi > 0.0) { return pow(chi, k+3./2)/(k+3./2); } else if (k==0) { return (chi + 1/tau)*r/2 - pow(2*tau, -3./2) * log(1 + tau*chi + sqrt(2*tau)*r); } else if (k==1) { return (2./3*cube(r) - gfdi_helper(0, chi, tau, r)) / tau; } else if (k==2) { return (2*chi*cube(r) - 5*gfdi_helper(1, chi, tau, r)) / (4*tau); } else { return 0.0; } } } // end anonymous namespace double gfdi(const GFDI order, const double chi, const double tau) { // TODO: something more like a SpEC require? assert(tau <= 100. && "GFDI: outside of known convergence region"); const int k = static_cast<int>(order); if (chi <= 0.6) { double value = 0; for (int i=1; i<=5; i++) { value += c[k][i-1] * sqrt(1 + khi[k][i-1]*tau/2) / (exp(-khi[k][i-1]) + exp(-chi)); } return value; } else if (chi < 14.0) { double value = 0; for (int i=1; i<=5; i++) { value += h[i-1] * pow(x[i-1], k) * pow(chi, k+3./2) * sqrt(1 + chi*x[i-1]*tau/2) / (1 + exp(chi*(x[i-1] - 1))) + v[i-1] * pow(xi[i-1] + chi, k+1./2) * sqrt(1 + (xi[i-1] + chi)*tau/2); } return value; } else { const double r = sqrt(chi*(1 + chi*tau/2)); return gfdi_helper(k, chi, tau, r) + M_PI*M_PI/6. * pow(chi, k) * (k + 1./2 + (k+1)*chi*tau/2) / r; } } <|endoftext|>
<commit_before>#include "Http.hpp" #include "CLog.hpp" #include "version.hpp" #include <boost/asio/system_timer.hpp> #include <boost/spirit/include/qi.hpp> Http::Http(std::string token) : m_SslContext(asio::ssl::context::sslv23), m_Token(token), m_NetworkThreadRunning(true), m_NetworkThread(std::bind(&Http::NetworkThreadFunc, this)) { } Http::~Http() { m_NetworkThreadRunning = false; m_NetworkThread.join(); } void Http::NetworkThreadFunc() { std::unordered_map<std::string, TimePoint_t> path_ratelimit; unsigned int retry_counter = 0; unsigned int const MaxRetries = 3; bool skip_entry = false; if (!Connect()) return; while (m_NetworkThreadRunning) { TimePoint_t current_time = std::chrono::system_clock::now(); m_QueueMutex.lock(); auto it = m_Queue.begin(); while (it != m_Queue.end()) { auto const &entry = *it; // check if we're rate-limited auto pr_it = path_ratelimit.find(entry->Request->target().to_string()); if (pr_it != path_ratelimit.end()) { // rate-limit for this path exists // are we still within the rate-limit timepoint? if (current_time < pr_it->second) { // yes, ignore this request for now it++; continue; } // no, delete rate-limit and go on path_ratelimit.erase(pr_it); } boost::system::error_code error_code; Response_t response; Streambuf_t sb; retry_counter = 0; skip_entry = false; do { bool do_reconnect = false; beast::http::write(*m_SslStream, *entry->Request, error_code); if (error_code) { CLog::Get()->Log(LogLevel::ERROR, "Error while sending HTTP {} request to '{}': {}", entry->Request->method_string().to_string(), entry->Request->target().to_string(), error_code.message()); do_reconnect = true; } else { beast::http::read(*m_SslStream, sb, response, error_code); if (error_code) { CLog::Get()->Log(LogLevel::ERROR, "Error while retrieving HTTP {} response from '{}': {}", entry->Request->method_string().to_string(), entry->Request->target().to_string(), error_code.message()); do_reconnect = true; } } if (do_reconnect) { if (retry_counter++ >= MaxRetries || !ReconnectRetry()) { // we failed to reconnect, discard this request CLog::Get()->Log(LogLevel::WARNING, "Failed to send request, discarding"); it = m_Queue.erase(it); skip_entry = true; break; // break out of do-while loop } } } while (error_code); if (skip_entry) continue; // continue queue loop auto it_r = response.find("X-RateLimit-Remaining"); if (it_r != response.end()) { if (it_r->value().compare("0") == 0) { // we're now officially rate-limited // the next call to this path will fail std::string limited_url = entry->Request->target().to_string(); auto lit = path_ratelimit.find(limited_url); if (lit != path_ratelimit.end()) { CLog::Get()->Log(LogLevel::ERROR, "Error while processing rate-limit: already rate-limited path '{}'", limited_url); // skip this request, but leave it in our list to retry later it++; continue; } it_r = response.find("X-RateLimit-Reset"); if (it_r != response.end()) { TimePoint_t current_time = std::chrono::system_clock::now(); CLog::Get()->Log(LogLevel::DEBUG, "rate-limiting path {} until {} (current time: {})", limited_url, it_r->value().to_string(), std::chrono::duration_cast<std::chrono::seconds>( current_time.time_since_epoch()).count()); string const &reset_time_str = it_r->value().to_string(); long long reset_time_secs = 0; boost::spirit::qi::parse(reset_time_str.begin(), reset_time_str.end(), boost::spirit::qi::any_int_parser<long long>(), reset_time_secs); TimePoint_t reset_time{ std::chrono::seconds(reset_time_secs) }; path_ratelimit.insert({ limited_url, reset_time }); } } } m_QueueMutex.unlock(); // allow requests to be queued from within callback if (entry->Callback) entry->Callback(sb, response); m_QueueMutex.lock(); it = m_Queue.erase(it); } m_QueueMutex.unlock(); std::this_thread::sleep_for(std::chrono::milliseconds(10)); } Disconnect(); } bool Http::Connect() { CLog::Get()->Log(LogLevel::DEBUG, "Http::Connect"); // connect to REST API asio::ip::tcp::resolver r{ m_IoService }; boost::system::error_code error; auto target = r.resolve({ "discordapp.com", "https" }, error); if (error) { CLog::Get()->Log(LogLevel::ERROR, "Can't resolve Discord API URL: {} ({})", error.message(), error.value()); return false; } m_SslStream.reset(new SslStream_t(m_IoService, m_SslContext)); asio::connect(m_SslStream->lowest_layer(), target, error); if (error) { CLog::Get()->Log(LogLevel::ERROR, "Can't connect to Discord API: {} ({})", error.message(), error.value()); return false; } // SSL handshake m_SslStream->set_verify_mode(asio::ssl::verify_none, error); if (error) { CLog::Get()->Log(LogLevel::ERROR, "Can't configure SSL stream peer verification mode for Discord API: {} ({})", error.message(), error.value()); return false; } m_SslStream->handshake(asio::ssl::stream_base::client, error); if (error) { CLog::Get()->Log(LogLevel::ERROR, "Can't establish secured connection to Discord API: {} ({})", error.message(), error.value()); return false; } return true; } void Http::Disconnect() { CLog::Get()->Log(LogLevel::DEBUG, "Http::Disconnect"); boost::system::error_code error; m_SslStream->shutdown(error); if (error && error != boost::asio::error::eof) { CLog::Get()->Log(LogLevel::WARNING, "Error while shutting down SSL on HTTP connection: {} ({})", error.message(), error.value()); } m_SslStream->lowest_layer().shutdown(asio::ip::tcp::socket::shutdown_both, error); if (error && error != boost::asio::error::eof) { CLog::Get()->Log(LogLevel::WARNING, "Error while shutting down HTTP connection: {} ({})", error.message(), error.value()); } m_SslStream->lowest_layer().close(error); if (error) { CLog::Get()->Log(LogLevel::WARNING, "Error while closing HTTP connection: {} ({})", error.message(), error.value()); } } bool Http::ReconnectRetry() { CLog::Get()->Log(LogLevel::DEBUG, "Http::ReconnectRetry"); unsigned int reconnect_counter = 0; do { CLog::Get()->Log(LogLevel::INFO, "trying reconnect #{}...", reconnect_counter + 1); Disconnect(); if (Connect()) { CLog::Get()->Log(LogLevel::INFO, "reconnect succeeded, resending request"); return true; } else { unsigned int seconds_to_wait = static_cast<unsigned int>(std::pow(2U, reconnect_counter)); CLog::Get()->Log(LogLevel::WARNING, "reconnect failed, waiting {} seconds...", seconds_to_wait); std::this_thread::sleep_for(std::chrono::seconds(seconds_to_wait)); } } while (++reconnect_counter < 3); CLog::Get()->Log(LogLevel::ERROR, "Could not reconnect to Discord"); return false; } Http::SharedRequest_t Http::PrepareRequest(beast::http::verb const method, std::string const &url, std::string const &content) { CLog::Get()->Log(LogLevel::DEBUG, "Http::PrepareRequest"); auto req = std::make_shared<Request_t>(); req->method(method); req->target("/api/v6" + url); req->version(11); req->insert("Host", "discordapp.com"); req->insert("User-Agent", "DiscordBot (github.com/maddinat0r/samp-discord-connector, " PLUGIN_VERSION ")"); if (!content.empty()) req->insert("Content-Type", "application/json"); req->insert("Authorization", "Bot " + m_Token); req->body() = content; req->prepare_payload(); return req; } void Http::SendRequest(beast::http::verb const method, std::string const &url, std::string const &content, ResponseCallback_t &&callback) { CLog::Get()->Log(LogLevel::DEBUG, "Http::SendRequest"); SharedRequest_t req = PrepareRequest(method, url, content); std::lock_guard<std::mutex> lock_guard(m_QueueMutex); m_Queue.push_back(std::make_shared<QueueEntry>(req, std::move(callback))); } void Http::Get(std::string const &url, GetCallback_t &&callback) { CLog::Get()->Log(LogLevel::DEBUG, "Http::Get"); SendRequest(beast::http::verb::get, url, "", [callback](Streambuf_t &sb, Response_t &resp) { std::stringstream ss_body, ss_data; ss_body << beast::buffers(resp.body().data()); ss_data << beast::buffers(sb.data()); callback({ resp.result_int(), resp.reason().to_string(), ss_body.str(), ss_data.str() }); }); } void Http::Post(std::string const &url, std::string const &content) { CLog::Get()->Log(LogLevel::DEBUG, "Http::Post"); SendRequest(beast::http::verb::post, url, content, nullptr); } <commit_msg>add keep-alive http header on all requests<commit_after>#include "Http.hpp" #include "CLog.hpp" #include "version.hpp" #include <boost/asio/system_timer.hpp> #include <boost/spirit/include/qi.hpp> Http::Http(std::string token) : m_SslContext(asio::ssl::context::sslv23), m_Token(token), m_NetworkThreadRunning(true), m_NetworkThread(std::bind(&Http::NetworkThreadFunc, this)) { } Http::~Http() { m_NetworkThreadRunning = false; m_NetworkThread.join(); } void Http::NetworkThreadFunc() { std::unordered_map<std::string, TimePoint_t> path_ratelimit; unsigned int retry_counter = 0; unsigned int const MaxRetries = 3; bool skip_entry = false; if (!Connect()) return; while (m_NetworkThreadRunning) { TimePoint_t current_time = std::chrono::system_clock::now(); m_QueueMutex.lock(); auto it = m_Queue.begin(); while (it != m_Queue.end()) { auto const &entry = *it; // check if we're rate-limited auto pr_it = path_ratelimit.find(entry->Request->target().to_string()); if (pr_it != path_ratelimit.end()) { // rate-limit for this path exists // are we still within the rate-limit timepoint? if (current_time < pr_it->second) { // yes, ignore this request for now it++; continue; } // no, delete rate-limit and go on path_ratelimit.erase(pr_it); } boost::system::error_code error_code; Response_t response; Streambuf_t sb; retry_counter = 0; skip_entry = false; do { bool do_reconnect = false; beast::http::write(*m_SslStream, *entry->Request, error_code); if (error_code) { CLog::Get()->Log(LogLevel::ERROR, "Error while sending HTTP {} request to '{}': {}", entry->Request->method_string().to_string(), entry->Request->target().to_string(), error_code.message()); do_reconnect = true; } else { beast::http::read(*m_SslStream, sb, response, error_code); if (error_code) { CLog::Get()->Log(LogLevel::ERROR, "Error while retrieving HTTP {} response from '{}': {}", entry->Request->method_string().to_string(), entry->Request->target().to_string(), error_code.message()); do_reconnect = true; } } if (do_reconnect) { if (retry_counter++ >= MaxRetries || !ReconnectRetry()) { // we failed to reconnect, discard this request CLog::Get()->Log(LogLevel::WARNING, "Failed to send request, discarding"); it = m_Queue.erase(it); skip_entry = true; break; // break out of do-while loop } } } while (error_code); if (skip_entry) continue; // continue queue loop auto it_r = response.find("X-RateLimit-Remaining"); if (it_r != response.end()) { if (it_r->value().compare("0") == 0) { // we're now officially rate-limited // the next call to this path will fail std::string limited_url = entry->Request->target().to_string(); auto lit = path_ratelimit.find(limited_url); if (lit != path_ratelimit.end()) { CLog::Get()->Log(LogLevel::ERROR, "Error while processing rate-limit: already rate-limited path '{}'", limited_url); // skip this request, but leave it in our list to retry later it++; continue; } it_r = response.find("X-RateLimit-Reset"); if (it_r != response.end()) { TimePoint_t current_time = std::chrono::system_clock::now(); CLog::Get()->Log(LogLevel::DEBUG, "rate-limiting path {} until {} (current time: {})", limited_url, it_r->value().to_string(), std::chrono::duration_cast<std::chrono::seconds>( current_time.time_since_epoch()).count()); string const &reset_time_str = it_r->value().to_string(); long long reset_time_secs = 0; boost::spirit::qi::parse(reset_time_str.begin(), reset_time_str.end(), boost::spirit::qi::any_int_parser<long long>(), reset_time_secs); TimePoint_t reset_time{ std::chrono::seconds(reset_time_secs) }; path_ratelimit.insert({ limited_url, reset_time }); } } } m_QueueMutex.unlock(); // allow requests to be queued from within callback if (entry->Callback) entry->Callback(sb, response); m_QueueMutex.lock(); it = m_Queue.erase(it); } m_QueueMutex.unlock(); std::this_thread::sleep_for(std::chrono::milliseconds(10)); } Disconnect(); } bool Http::Connect() { CLog::Get()->Log(LogLevel::DEBUG, "Http::Connect"); // connect to REST API asio::ip::tcp::resolver r{ m_IoService }; boost::system::error_code error; auto target = r.resolve({ "discordapp.com", "https" }, error); if (error) { CLog::Get()->Log(LogLevel::ERROR, "Can't resolve Discord API URL: {} ({})", error.message(), error.value()); return false; } m_SslStream.reset(new SslStream_t(m_IoService, m_SslContext)); asio::connect(m_SslStream->lowest_layer(), target, error); if (error) { CLog::Get()->Log(LogLevel::ERROR, "Can't connect to Discord API: {} ({})", error.message(), error.value()); return false; } // SSL handshake m_SslStream->set_verify_mode(asio::ssl::verify_none, error); if (error) { CLog::Get()->Log(LogLevel::ERROR, "Can't configure SSL stream peer verification mode for Discord API: {} ({})", error.message(), error.value()); return false; } m_SslStream->handshake(asio::ssl::stream_base::client, error); if (error) { CLog::Get()->Log(LogLevel::ERROR, "Can't establish secured connection to Discord API: {} ({})", error.message(), error.value()); return false; } return true; } void Http::Disconnect() { CLog::Get()->Log(LogLevel::DEBUG, "Http::Disconnect"); boost::system::error_code error; m_SslStream->shutdown(error); if (error && error != boost::asio::error::eof) { CLog::Get()->Log(LogLevel::WARNING, "Error while shutting down SSL on HTTP connection: {} ({})", error.message(), error.value()); } m_SslStream->lowest_layer().shutdown(asio::ip::tcp::socket::shutdown_both, error); if (error && error != boost::asio::error::eof) { CLog::Get()->Log(LogLevel::WARNING, "Error while shutting down HTTP connection: {} ({})", error.message(), error.value()); } m_SslStream->lowest_layer().close(error); if (error) { CLog::Get()->Log(LogLevel::WARNING, "Error while closing HTTP connection: {} ({})", error.message(), error.value()); } } bool Http::ReconnectRetry() { CLog::Get()->Log(LogLevel::DEBUG, "Http::ReconnectRetry"); unsigned int reconnect_counter = 0; do { CLog::Get()->Log(LogLevel::INFO, "trying reconnect #{}...", reconnect_counter + 1); Disconnect(); if (Connect()) { CLog::Get()->Log(LogLevel::INFO, "reconnect succeeded, resending request"); return true; } else { unsigned int seconds_to_wait = static_cast<unsigned int>(std::pow(2U, reconnect_counter)); CLog::Get()->Log(LogLevel::WARNING, "reconnect failed, waiting {} seconds...", seconds_to_wait); std::this_thread::sleep_for(std::chrono::seconds(seconds_to_wait)); } } while (++reconnect_counter < 3); CLog::Get()->Log(LogLevel::ERROR, "Could not reconnect to Discord"); return false; } Http::SharedRequest_t Http::PrepareRequest(beast::http::verb const method, std::string const &url, std::string const &content) { CLog::Get()->Log(LogLevel::DEBUG, "Http::PrepareRequest"); auto req = std::make_shared<Request_t>(); req->method(method); req->target("/api/v6" + url); req->version(11); req->insert("Connection", "keep-alive"); req->insert("Host", "discordapp.com"); req->insert("User-Agent", "DiscordBot (github.com/maddinat0r/samp-discord-connector, " PLUGIN_VERSION ")"); if (!content.empty()) req->insert("Content-Type", "application/json"); req->insert("Authorization", "Bot " + m_Token); req->body() = content; req->prepare_payload(); return req; } void Http::SendRequest(beast::http::verb const method, std::string const &url, std::string const &content, ResponseCallback_t &&callback) { CLog::Get()->Log(LogLevel::DEBUG, "Http::SendRequest"); SharedRequest_t req = PrepareRequest(method, url, content); std::lock_guard<std::mutex> lock_guard(m_QueueMutex); m_Queue.push_back(std::make_shared<QueueEntry>(req, std::move(callback))); } void Http::Get(std::string const &url, GetCallback_t &&callback) { CLog::Get()->Log(LogLevel::DEBUG, "Http::Get"); SendRequest(beast::http::verb::get, url, "", [callback](Streambuf_t &sb, Response_t &resp) { std::stringstream ss_body, ss_data; ss_body << beast::buffers(resp.body().data()); ss_data << beast::buffers(sb.data()); callback({ resp.result_int(), resp.reason().to_string(), ss_body.str(), ss_data.str() }); }); } void Http::Post(std::string const &url, std::string const &content) { CLog::Get()->Log(LogLevel::DEBUG, "Http::Post"); SendRequest(beast::http::verb::post, url, content, nullptr); } <|endoftext|>
<commit_before>#include "Http.hpp" #include "CLog.hpp" #include "version.hpp" #include <boost/asio/system_timer.hpp> #include <boost/spirit/include/qi.hpp> Http::Http(std::string token) : m_SslContext(asio::ssl::context::sslv23), m_SslStream(m_IoService, m_SslContext), m_Token(token), m_NetworkThreadRunning(true), m_NetworkThread(std::bind(&Http::NetworkThreadFunc, this)) { if (!Connect()) return; } Http::~Http() { m_NetworkThreadRunning = false; m_NetworkThread.join(); Disconnect(); } void Http::NetworkThreadFunc() { std::unordered_map<std::string, TimePoint_t> path_ratelimit; unsigned int retry_counter = 0; unsigned int const MaxRetries = 3; bool skip_entry = false; while (m_NetworkThreadRunning) { TimePoint_t current_time = std::chrono::system_clock::now(); m_QueueMutex.lock(); auto it = m_Queue.begin(); while (it != m_Queue.end()) { auto const &entry = *it; // check if we're rate-limited auto pr_it = path_ratelimit.find(entry->Request->target().to_string()); if (pr_it != path_ratelimit.end()) { // rate-limit for this path exists // are we still within the rate-limit timepoint? if (current_time < pr_it->second) { // yes, ignore this request for now it++; continue; } // no, delete rate-limit and go on path_ratelimit.erase(pr_it); } boost::system::error_code error_code; retry_counter = 0; skip_entry = false; do { beast::http::write(m_SslStream, *entry->Request, error_code); if (error_code) { CLog::Get()->Log(LogLevel::ERROR, "Error while sending HTTP {} request to '{}': {}", entry->Request->method_string().to_string(), entry->Request->target().to_string(), error_code.message()); // try reconnecting if (retry_counter++ >= MaxRetries || !ReconnectRetry()) { // we failed to reconnect, discard this request CLog::Get()->Log(LogLevel::WARNING, "Failed to send request, discarding"); it = m_Queue.erase(it); skip_entry = true; break; // break out of do-while loop } } } while (error_code); if (skip_entry) continue; // continue queue loop Streambuf_t sb; Response_t response; retry_counter = 0; skip_entry = false; do { beast::http::read(m_SslStream, sb, response, error_code); if (error_code) { CLog::Get()->Log(LogLevel::ERROR, "Error while retrieving HTTP {} response from '{}': {}", entry->Request->method_string().to_string(), entry->Request->target().to_string(), error_code.message()); // try reconnecting if (retry_counter++ >= MaxRetries || !ReconnectRetry()) { // we failed to reconnect, discard this request CLog::Get()->Log(LogLevel::WARNING, "Failed to read response, discarding"); it = m_Queue.erase(it); skip_entry = true; break; // break out of do-while loop } } } while (error_code); if (skip_entry) continue; // continue queue loop auto it_r = response.find("X-RateLimit-Remaining"); if (it_r != response.end()) { if (it_r->value().compare("0") == 0) { // we're now officially rate-limited // the next call to this path will fail std::string limited_url = entry->Request->target().to_string(); auto lit = path_ratelimit.find(limited_url); if (lit != path_ratelimit.end()) { CLog::Get()->Log(LogLevel::ERROR, "Error while processing rate-limit: already rate-limited path '{}'", limited_url); // skip this request, but leave it in our list to retry later it++; continue; } it_r = response.find("X-RateLimit-Reset"); if (it_r != response.end()) { TimePoint_t current_time = std::chrono::system_clock::now(); CLog::Get()->Log(LogLevel::DEBUG, "rate-limiting path {} until {} (current time: {})", limited_url, it_r->value().to_string(), std::chrono::duration_cast<std::chrono::seconds>( current_time.time_since_epoch()).count()); string const &reset_time_str = it_r->value().to_string(); long long reset_time_secs = 0; boost::spirit::qi::parse(reset_time_str.begin(), reset_time_str.end(), boost::spirit::qi::any_int_parser<long long>(), reset_time_secs); TimePoint_t reset_time{ std::chrono::seconds(reset_time_secs) }; path_ratelimit.insert({ limited_url, reset_time }); } } } m_QueueMutex.unlock(); // allow requests to be queued from within callback if (entry->Callback) entry->Callback(sb, response); m_QueueMutex.lock(); it = m_Queue.erase(it); } m_QueueMutex.unlock(); std::this_thread::sleep_for(std::chrono::milliseconds(10)); } } bool Http::Connect() { CLog::Get()->Log(LogLevel::DEBUG, "Http::Connect"); // connect to REST API asio::ip::tcp::resolver r{ m_IoService }; boost::system::error_code error; auto target = r.resolve({ "discordapp.com", "https" }, error); if (error) { CLog::Get()->Log(LogLevel::ERROR, "Can't resolve Discord API URL: {} ({})", error.message(), error.value()); return false; } asio::connect(m_SslStream.lowest_layer(), target, error); if (error) { CLog::Get()->Log(LogLevel::ERROR, "Can't connect to Discord API: {} ({})", error.message(), error.value()); return false; } // SSL handshake m_SslStream.set_verify_mode(asio::ssl::verify_none, error); if (error) { CLog::Get()->Log(LogLevel::ERROR, "Can't configure SSL stream peer verification mode for Discord API: {} ({})", error.message(), error.value()); return false; } m_SslStream.handshake(asio::ssl::stream_base::client, error); if (error) { CLog::Get()->Log(LogLevel::ERROR, "Can't establish secured connection to Discord API: {} ({})", error.message(), error.value()); return false; } return true; } void Http::Disconnect() { CLog::Get()->Log(LogLevel::DEBUG, "Http::Disconnect"); boost::system::error_code error; m_SslStream.shutdown(error); if (error && error != boost::asio::error::eof) { CLog::Get()->Log(LogLevel::WARNING, "Error while shutting down SSL on HTTP connection: {} ({})", error.message(), error.value()); } m_SslStream.lowest_layer().shutdown(asio::ip::tcp::socket::shutdown_both, error); if (error && error != boost::asio::error::eof) { CLog::Get()->Log(LogLevel::WARNING, "Error while shutting down HTTP connection: {} ({})", error.message(), error.value()); } m_SslStream.lowest_layer().close(error); if (error) { CLog::Get()->Log(LogLevel::WARNING, "Error while closing HTTP connection: {} ({})", error.message(), error.value()); } } bool Http::ReconnectRetry() { CLog::Get()->Log(LogLevel::DEBUG, "Http::ReconnectRetry"); unsigned int reconnect_counter = 0; do { CLog::Get()->Log(LogLevel::INFO, "trying reconnect #{}...", reconnect_counter + 1); Disconnect(); if (Connect()) { CLog::Get()->Log(LogLevel::INFO, "reconnect succeeded, resending request"); return true; } else { unsigned int seconds_to_wait = static_cast<unsigned int>(std::pow(2U, reconnect_counter)); CLog::Get()->Log(LogLevel::WARNING, "reconnect failed, waiting {} seconds...", seconds_to_wait); std::this_thread::sleep_for(std::chrono::seconds(seconds_to_wait)); } } while (++reconnect_counter < 3); CLog::Get()->Log(LogLevel::ERROR, "Could not reconnect to Discord"); return false; } Http::SharedRequest_t Http::PrepareRequest(beast::http::verb const method, std::string const &url, std::string const &content) { CLog::Get()->Log(LogLevel::DEBUG, "Http::PrepareRequest"); auto req = std::make_shared<Request_t>(); req->method(method); req->target("/api/v6" + url); req->version(11); req->insert("Host", "discordapp.com"); req->insert("User-Agent", "DiscordBot (github.com/maddinat0r/samp-discord-connector, " PLUGIN_VERSION ")"); if (!content.empty()) req->insert("Content-Type", "application/json"); req->insert("Authorization", "Bot " + m_Token); req->body() = content; req->prepare_payload(); return req; } void Http::SendRequest(beast::http::verb const method, std::string const &url, std::string const &content, ResponseCallback_t &&callback) { CLog::Get()->Log(LogLevel::DEBUG, "Http::SendRequest"); SharedRequest_t req = PrepareRequest(method, url, content); std::lock_guard<std::mutex> lock_guard(m_QueueMutex); m_Queue.push_back(std::make_shared<QueueEntry>(req, std::move(callback))); } void Http::Get(std::string const &url, GetCallback_t &&callback) { CLog::Get()->Log(LogLevel::DEBUG, "Http::Get"); SendRequest(beast::http::verb::get, url, "", [callback](Streambuf_t &sb, Response_t &resp) { std::stringstream ss_body, ss_data; ss_body << beast::buffers(resp.body().data()); ss_data << beast::buffers(sb.data()); callback({ resp.result_int(), resp.reason().to_string(), ss_body.str(), ss_data.str() }); }); } void Http::Post(std::string const &url, std::string const &content) { CLog::Get()->Log(LogLevel::DEBUG, "Http::Post"); SendRequest(beast::http::verb::post, url, content, nullptr); } <commit_msg>fix HTTP request retry logic<commit_after>#include "Http.hpp" #include "CLog.hpp" #include "version.hpp" #include <boost/asio/system_timer.hpp> #include <boost/spirit/include/qi.hpp> Http::Http(std::string token) : m_SslContext(asio::ssl::context::sslv23), m_SslStream(m_IoService, m_SslContext), m_Token(token), m_NetworkThreadRunning(true), m_NetworkThread(std::bind(&Http::NetworkThreadFunc, this)) { if (!Connect()) return; } Http::~Http() { m_NetworkThreadRunning = false; m_NetworkThread.join(); Disconnect(); } void Http::NetworkThreadFunc() { std::unordered_map<std::string, TimePoint_t> path_ratelimit; unsigned int retry_counter = 0; unsigned int const MaxRetries = 3; bool skip_entry = false; while (m_NetworkThreadRunning) { TimePoint_t current_time = std::chrono::system_clock::now(); m_QueueMutex.lock(); auto it = m_Queue.begin(); while (it != m_Queue.end()) { auto const &entry = *it; // check if we're rate-limited auto pr_it = path_ratelimit.find(entry->Request->target().to_string()); if (pr_it != path_ratelimit.end()) { // rate-limit for this path exists // are we still within the rate-limit timepoint? if (current_time < pr_it->second) { // yes, ignore this request for now it++; continue; } // no, delete rate-limit and go on path_ratelimit.erase(pr_it); } boost::system::error_code error_code; Response_t response; Streambuf_t sb; retry_counter = 0; skip_entry = false; do { bool do_reconnect = false; beast::http::write(m_SslStream, *entry->Request, error_code); if (error_code) { CLog::Get()->Log(LogLevel::ERROR, "Error while sending HTTP {} request to '{}': {}", entry->Request->method_string().to_string(), entry->Request->target().to_string(), error_code.message()); do_reconnect = true; } else { beast::http::read(m_SslStream, sb, response, error_code); if (error_code) { CLog::Get()->Log(LogLevel::ERROR, "Error while retrieving HTTP {} response from '{}': {}", entry->Request->method_string().to_string(), entry->Request->target().to_string(), error_code.message()); do_reconnect = true; } } if (do_reconnect) { if (retry_counter++ >= MaxRetries || !ReconnectRetry()) { // we failed to reconnect, discard this request CLog::Get()->Log(LogLevel::WARNING, "Failed to send request, discarding"); it = m_Queue.erase(it); skip_entry = true; break; // break out of do-while loop } } } while (error_code); if (skip_entry) continue; // continue queue loop auto it_r = response.find("X-RateLimit-Remaining"); if (it_r != response.end()) { if (it_r->value().compare("0") == 0) { // we're now officially rate-limited // the next call to this path will fail std::string limited_url = entry->Request->target().to_string(); auto lit = path_ratelimit.find(limited_url); if (lit != path_ratelimit.end()) { CLog::Get()->Log(LogLevel::ERROR, "Error while processing rate-limit: already rate-limited path '{}'", limited_url); // skip this request, but leave it in our list to retry later it++; continue; } it_r = response.find("X-RateLimit-Reset"); if (it_r != response.end()) { TimePoint_t current_time = std::chrono::system_clock::now(); CLog::Get()->Log(LogLevel::DEBUG, "rate-limiting path {} until {} (current time: {})", limited_url, it_r->value().to_string(), std::chrono::duration_cast<std::chrono::seconds>( current_time.time_since_epoch()).count()); string const &reset_time_str = it_r->value().to_string(); long long reset_time_secs = 0; boost::spirit::qi::parse(reset_time_str.begin(), reset_time_str.end(), boost::spirit::qi::any_int_parser<long long>(), reset_time_secs); TimePoint_t reset_time{ std::chrono::seconds(reset_time_secs) }; path_ratelimit.insert({ limited_url, reset_time }); } } } m_QueueMutex.unlock(); // allow requests to be queued from within callback if (entry->Callback) entry->Callback(sb, response); m_QueueMutex.lock(); it = m_Queue.erase(it); } m_QueueMutex.unlock(); std::this_thread::sleep_for(std::chrono::milliseconds(10)); } } bool Http::Connect() { CLog::Get()->Log(LogLevel::DEBUG, "Http::Connect"); // connect to REST API asio::ip::tcp::resolver r{ m_IoService }; boost::system::error_code error; auto target = r.resolve({ "discordapp.com", "https" }, error); if (error) { CLog::Get()->Log(LogLevel::ERROR, "Can't resolve Discord API URL: {} ({})", error.message(), error.value()); return false; } asio::connect(m_SslStream.lowest_layer(), target, error); if (error) { CLog::Get()->Log(LogLevel::ERROR, "Can't connect to Discord API: {} ({})", error.message(), error.value()); return false; } // SSL handshake m_SslStream.set_verify_mode(asio::ssl::verify_none, error); if (error) { CLog::Get()->Log(LogLevel::ERROR, "Can't configure SSL stream peer verification mode for Discord API: {} ({})", error.message(), error.value()); return false; } m_SslStream.handshake(asio::ssl::stream_base::client, error); if (error) { CLog::Get()->Log(LogLevel::ERROR, "Can't establish secured connection to Discord API: {} ({})", error.message(), error.value()); return false; } return true; } void Http::Disconnect() { CLog::Get()->Log(LogLevel::DEBUG, "Http::Disconnect"); boost::system::error_code error; m_SslStream.shutdown(error); if (error && error != boost::asio::error::eof) { CLog::Get()->Log(LogLevel::WARNING, "Error while shutting down SSL on HTTP connection: {} ({})", error.message(), error.value()); } m_SslStream.lowest_layer().shutdown(asio::ip::tcp::socket::shutdown_both, error); if (error && error != boost::asio::error::eof) { CLog::Get()->Log(LogLevel::WARNING, "Error while shutting down HTTP connection: {} ({})", error.message(), error.value()); } m_SslStream.lowest_layer().close(error); if (error) { CLog::Get()->Log(LogLevel::WARNING, "Error while closing HTTP connection: {} ({})", error.message(), error.value()); } } bool Http::ReconnectRetry() { CLog::Get()->Log(LogLevel::DEBUG, "Http::ReconnectRetry"); unsigned int reconnect_counter = 0; do { CLog::Get()->Log(LogLevel::INFO, "trying reconnect #{}...", reconnect_counter + 1); Disconnect(); if (Connect()) { CLog::Get()->Log(LogLevel::INFO, "reconnect succeeded, resending request"); return true; } else { unsigned int seconds_to_wait = static_cast<unsigned int>(std::pow(2U, reconnect_counter)); CLog::Get()->Log(LogLevel::WARNING, "reconnect failed, waiting {} seconds...", seconds_to_wait); std::this_thread::sleep_for(std::chrono::seconds(seconds_to_wait)); } } while (++reconnect_counter < 3); CLog::Get()->Log(LogLevel::ERROR, "Could not reconnect to Discord"); return false; } Http::SharedRequest_t Http::PrepareRequest(beast::http::verb const method, std::string const &url, std::string const &content) { CLog::Get()->Log(LogLevel::DEBUG, "Http::PrepareRequest"); auto req = std::make_shared<Request_t>(); req->method(method); req->target("/api/v6" + url); req->version(11); req->insert("Host", "discordapp.com"); req->insert("User-Agent", "DiscordBot (github.com/maddinat0r/samp-discord-connector, " PLUGIN_VERSION ")"); if (!content.empty()) req->insert("Content-Type", "application/json"); req->insert("Authorization", "Bot " + m_Token); req->body() = content; req->prepare_payload(); return req; } void Http::SendRequest(beast::http::verb const method, std::string const &url, std::string const &content, ResponseCallback_t &&callback) { CLog::Get()->Log(LogLevel::DEBUG, "Http::SendRequest"); SharedRequest_t req = PrepareRequest(method, url, content); std::lock_guard<std::mutex> lock_guard(m_QueueMutex); m_Queue.push_back(std::make_shared<QueueEntry>(req, std::move(callback))); } void Http::Get(std::string const &url, GetCallback_t &&callback) { CLog::Get()->Log(LogLevel::DEBUG, "Http::Get"); SendRequest(beast::http::verb::get, url, "", [callback](Streambuf_t &sb, Response_t &resp) { std::stringstream ss_body, ss_data; ss_body << beast::buffers(resp.body().data()); ss_data << beast::buffers(sb.data()); callback({ resp.result_int(), resp.reason().to_string(), ss_body.str(), ss_data.str() }); }); } void Http::Post(std::string const &url, std::string const &content) { CLog::Get()->Log(LogLevel::DEBUG, "Http::Post"); SendRequest(beast::http::verb::post, url, content, nullptr); } <|endoftext|>
<commit_before>#include <windows.h> #include <gl\gl.h> #ifdef _MSC_VER #define _USE_MATH_DEFINES #endif #include <math.h> #include "Window.h" #include "Body.h" #include "Error.h" #include "Info.h" #define NAME_FONT_NAME "Arial" #define NAME_FONT_SIZE_AT_H600 24 #define NAME_FONT_SIZE (NAME_FONT_SIZE_AT_H600*scrheight/600) #define NAME_TEXT_COLOR_R 1.00f #define NAME_TEXT_COLOR_G 1.00f #define NAME_TEXT_COLOR_B 1.00f #define NAME_TEXT_COLOR_A 0.50f #define INFO_FONT_NAME "Arial" #define INFO_FONT_SIZE_AT_H600 16 #define INFO_FONT_SIZE (INFO_FONT_SIZE_AT_H600*scrheight/600) #define INFO_TEXT_COLOR_R 1.00f #define INFO_TEXT_COLOR_G 1.00f #define INFO_TEXT_COLOR_B 1.00f #define INFO_TEXT_COLOR_A 0.50f #define SPACING_COEF 1.13f #define LINES_AFTER_NAME 1.00f #define WINDOW_COLOR_R 0.50f #define WINDOW_COLOR_G 0.50f #define WINDOW_COLOR_B 0.50f #define WINDOW_COLOR_A 0.25f #define MAX_FADE_TIME 3.0f #define FADE_TIME_RATIO 0.10f #define FADE_TIME(totaltime) min(MAX_FADE_TIME, (totaltime)*FADE_TIME_RATIO) #define WINDOW_BORDER_REL 0.0125f #define WINDOW_BORDER (WINDOW_BORDER_REL*scrheight) #define WINDOW_WIDTH_REL_Y (0.3075f*4.0f/3.0f) #define WINDOW_WIDTH (WINDOW_WIDTH_REL_Y*scrheight) #define WINDOW_HEIGHT_REL 0.25f #define WINDOW_HEIGHT (WINDOW_HEIGHT_REL*scrheight) #define WINDOW_POS_X1 (WINDOW_BORDER) #define WINDOW_POS_Y1 (WINDOW_BORDER) #define WINDOW_POS_X2 (WINDOW_POS_X1+WINDOW_WIDTH) #define WINDOW_POS_Y2 (WINDOW_POS_Y1+WINDOW_HEIGHT) #define MARGIN_TOP_REL 0.100f #define MARGIN_LEFT_REL 0.075f #define MARGIN_WIDTH (WINDOW_WIDTH*MARGIN_LEFT_REL) #define MARGIN_HEIGHT (WINDOW_HEIGHT*MARGIN_TOP_REL) CInfo::CInfo() { Init(); } CInfo::~CInfo() { Free(); } void CInfo::Init() { loaded=false; scrwidth=0; scrheight=0; winlist=0; namelist=infolist=0; time=0; starttime=endtime=0; fadetime=1; alpha=0; } void CInfo::Free() { nametext.Free(); infotext.Free(); if (winlist) { if (glIsList(winlist)) glDeleteLists(winlist,3); } Init(); } bool CInfo::Load() { Free(); scrwidth=CWindow::GetWidth(); scrheight=CWindow::GetHeight(); winlist=glGenLists(3); if (!winlist) { CError::LogError(WARNING_CODE,"Unable to load planet info - failed to generate display lists."); Free(); return false; } namelist=winlist+1; infolist=namelist+1; MakeWindow(winlist); loaded=true; loaded&=nametext.BuildFTFont(NAME_FONT_NAME,(int)NAME_FONT_SIZE); loaded&=infotext.BuildFTFont(INFO_FONT_NAME,(int)INFO_FONT_SIZE); if (!loaded) { CError::LogError(WARNING_CODE,"Unable to load planet info - failed to load font."); Free(); } return loaded; } void CInfo::MakeWindow(int list) { glNewList(list,GL_COMPILE); { int l=(int)WINDOW_POS_X1; int r=(int)WINDOW_POS_X2; int b=(int)WINDOW_POS_Y1; int t=(int)WINDOW_POS_Y2; glDisable(GL_TEXTURE_2D); glLoadIdentity(); glBegin(GL_QUADS); { glVertex2f((float)l,(float)b); glVertex2f((float)r,(float)b); glVertex2f((float)r,(float)t); glVertex2f((float)l,(float)t); } glEnd(); } glEndList(); } void CInfo::GetNameCoords(const char *text, int *x, int *y) { float tw; nametext.GetTextSize(text,&tw,NULL); int th=(int)NAME_FONT_SIZE; if (x) *x=(int)(WINDOW_POS_X1+(WINDOW_WIDTH-tw)*0.5f); if (y) *y=(int)(WINDOW_POS_Y2-MARGIN_HEIGHT)-th; } void CInfo::GetInfoCoords(int linenum, int *x, int *y) { int namey; GetNameCoords(" ",NULL,&namey); float nameadd; nametext.GetTextSize(" ",NULL,&nameadd); nameadd*=(SPACING_COEF*LINES_AFTER_NAME); float th; infotext.GetTextSize(" ",NULL,&th); th*=SPACING_COEF; int thi=(int)th*(linenum-1); if (x) *x=(int)(WINDOW_POS_X1+MARGIN_WIDTH); if (y) *y=namey-(int)nameadd-thi; } void CInfo::MakeName(int list, char *targetname) { if (!targetname) return; if (*targetname==' ') targetname++; int x,y; GetNameCoords(targetname,&x,&y); glNewList(list,GL_COMPILE); { glEnable(GL_TEXTURE_2D); glLoadIdentity(); glTranslatef((float)x,(float)y,0); nametext.Print(targetname); } glEndList(); } void CInfo::MakeInfoLine(int linenum, char *line) { int x,y; GetInfoCoords(linenum,&x,&y); glPushMatrix(); glTranslatef((float)x,(float)y,0); infotext.Print(line); glPopMatrix(); } void CInfo::MakeInfo(int list, CBody *targetbody) { bool star=(targetbody==NULL); if (star) targetbody=CBody::bodycache[0]; glNewList(list,GL_COMPILE); { int n=0; glEnable(GL_TEXTURE_2D); glLoadIdentity(); if (star) { char line[64]; n++; sprintf(line,"star name: %s",targetbody->name); MakeInfoLine(n,line); } for (int i=0;i<targetbody->info.numlines;i++) { if (targetbody->info.textlines[i][0]=='/') continue; n++; MakeInfoLine(n,targetbody->info.textlines[i]); } } glEndList(); } void CInfo::Start(float seconds, float duration, char *targetname, CBody *targetbody) { if (!loaded) return; char name[32]; strcpy(name,targetname); int l=strlen(name); for (int i=0;i<l;i++) if (name[i]=='_') name[i]=' '; starttime=seconds; endtime=starttime+duration; fadetime=FADE_TIME(duration); MakeName(namelist,name); MakeInfo(infolist,targetbody); } void CInfo::Update(float seconds) { time=seconds; if (time<(endtime-fadetime)) alpha=min(1,(time-starttime)/fadetime); else alpha=max(0,(endtime-time)/fadetime); } void CInfo::Restart() { starttime-=time; endtime-=time; time=0; } void CInfo::Draw() { if (!alpha || !loaded) return; glDisable(GL_LIGHTING); glDisable(GL_DEPTH_TEST); glDisable(GL_CULL_FACE); glEnable(GL_BLEND); glColor4f(WINDOW_COLOR_R,WINDOW_COLOR_G,WINDOW_COLOR_B,WINDOW_COLOR_A*alpha); glCallList(winlist); glColor4f(NAME_TEXT_COLOR_R,NAME_TEXT_COLOR_G,NAME_TEXT_COLOR_B,NAME_TEXT_COLOR_A*alpha); glCallList(namelist); glColor4f(INFO_TEXT_COLOR_R,INFO_TEXT_COLOR_G,INFO_TEXT_COLOR_B,INFO_TEXT_COLOR_A*alpha); glCallList(infolist); } <commit_msg>Corrections to info text coordinate calculation.<commit_after>#include <windows.h> #include <gl\gl.h> #ifdef _MSC_VER #define _USE_MATH_DEFINES #endif #include <math.h> #include "Window.h" #include "Body.h" #include "Error.h" #include "Info.h" #define NAME_FONT_NAME "Arial" #define NAME_FONT_SIZE_AT_H600 24 #define NAME_FONT_SIZE (NAME_FONT_SIZE_AT_H600*scrheight/600) #define NAME_TEXT_COLOR_R 1.00f #define NAME_TEXT_COLOR_G 1.00f #define NAME_TEXT_COLOR_B 1.00f #define NAME_TEXT_COLOR_A 0.50f #define INFO_FONT_NAME "Arial" #define INFO_FONT_SIZE_AT_H600 16 #define INFO_FONT_SIZE (INFO_FONT_SIZE_AT_H600*scrheight/600) #define INFO_TEXT_COLOR_R 1.00f #define INFO_TEXT_COLOR_G 1.00f #define INFO_TEXT_COLOR_B 1.00f #define INFO_TEXT_COLOR_A 0.50f #define SPACING_COEF 1.15f #define LINES_AFTER_NAME 1.00f #define WINDOW_COLOR_R 0.50f #define WINDOW_COLOR_G 0.50f #define WINDOW_COLOR_B 0.50f #define WINDOW_COLOR_A 0.25f #define MAX_FADE_TIME 3.0f #define FADE_TIME_RATIO 0.10f #define FADE_TIME(totaltime) min(MAX_FADE_TIME, (totaltime)*FADE_TIME_RATIO) #define WINDOW_BORDER_REL 0.0125f #define WINDOW_BORDER (WINDOW_BORDER_REL*scrheight) #define WINDOW_WIDTH_REL_Y (0.3075f*4.0f/3.0f) #define WINDOW_WIDTH (WINDOW_WIDTH_REL_Y*scrheight) #define WINDOW_HEIGHT_REL 0.25f #define WINDOW_HEIGHT (WINDOW_HEIGHT_REL*scrheight) #define WINDOW_POS_X1 (WINDOW_BORDER) #define WINDOW_POS_Y1 (WINDOW_BORDER) #define WINDOW_POS_X2 (WINDOW_POS_X1+WINDOW_WIDTH) #define WINDOW_POS_Y2 (WINDOW_POS_Y1+WINDOW_HEIGHT) #define MARGIN_TOP_REL 0.100f #define MARGIN_LEFT_REL 0.075f #define MARGIN_WIDTH (WINDOW_WIDTH*MARGIN_LEFT_REL) #define MARGIN_HEIGHT (WINDOW_HEIGHT*MARGIN_TOP_REL) CInfo::CInfo() { Init(); } CInfo::~CInfo() { Free(); } void CInfo::Init() { loaded=false; scrwidth=0; scrheight=0; winlist=0; namelist=infolist=0; time=0; starttime=endtime=0; fadetime=1; alpha=0; } void CInfo::Free() { nametext.Free(); infotext.Free(); if (winlist) { if (glIsList(winlist)) glDeleteLists(winlist,3); } Init(); } bool CInfo::Load() { Free(); scrwidth=CWindow::GetWidth(); scrheight=CWindow::GetHeight(); winlist=glGenLists(3); if (!winlist) { CError::LogError(WARNING_CODE,"Unable to load planet info - failed to generate display lists."); Free(); return false; } namelist=winlist+1; infolist=namelist+1; MakeWindow(winlist); loaded=true; loaded&=nametext.BuildFTFont(NAME_FONT_NAME,(int)NAME_FONT_SIZE); loaded&=infotext.BuildFTFont(INFO_FONT_NAME,(int)INFO_FONT_SIZE); if (!loaded) { CError::LogError(WARNING_CODE,"Unable to load planet info - failed to load font."); Free(); } return loaded; } void CInfo::MakeWindow(int list) { glNewList(list,GL_COMPILE); { int l=(int)WINDOW_POS_X1; int r=(int)WINDOW_POS_X2; int b=(int)WINDOW_POS_Y1; int t=(int)WINDOW_POS_Y2; glDisable(GL_TEXTURE_2D); glLoadIdentity(); glBegin(GL_QUADS); { glVertex2f((float)l,(float)b); glVertex2f((float)r,(float)b); glVertex2f((float)r,(float)t); glVertex2f((float)l,(float)t); } glEnd(); } glEndList(); } void CInfo::GetNameCoords(const char *text, int *x, int *y) { float tw; nametext.GetTextSize(text,&tw,NULL); int th=(int)NAME_FONT_SIZE; if (x) *x=(int)(WINDOW_POS_X1+(WINDOW_WIDTH-tw)*0.5f); if (y) *y=(int)(WINDOW_POS_Y2-MARGIN_HEIGHT)-th; } void CInfo::GetInfoCoords(int linenum, int *x, int *y) { int ymargin=(int)(WINDOW_POS_Y2-MARGIN_HEIGHT); float nameheight; nametext.GetTextSize("",NULL,&nameheight); float nameadd; nameadd=nameheight*SPACING_COEF*LINES_AFTER_NAME; int ioffset=(int)INFO_FONT_SIZE; float th; infotext.GetTextSize("",NULL,&th); th*=SPACING_COEF; int thi=(int)th*(linenum-1); if (x) *x=(int)(WINDOW_POS_X1+MARGIN_WIDTH); if (y) *y=ymargin-(int)nameadd-ioffset-thi; } void CInfo::MakeName(int list, char *targetname) { if (!targetname) return; if (*targetname==' ') targetname++; int x,y; GetNameCoords(targetname,&x,&y); glNewList(list,GL_COMPILE); { glEnable(GL_TEXTURE_2D); glLoadIdentity(); glTranslatef((float)x,(float)y,0); nametext.Print(targetname); } glEndList(); } void CInfo::MakeInfoLine(int linenum, char *line) { int x,y; GetInfoCoords(linenum,&x,&y); glPushMatrix(); glTranslatef((float)x,(float)y,0); infotext.Print(line); glPopMatrix(); } void CInfo::MakeInfo(int list, CBody *targetbody) { bool star=(targetbody==NULL); if (star) targetbody=CBody::bodycache[0]; glNewList(list,GL_COMPILE); { int n=0; glEnable(GL_TEXTURE_2D); glLoadIdentity(); if (star) { char line[64]; n++; sprintf(line,"star name: %s",targetbody->name); MakeInfoLine(n,line); } for (int i=0;i<targetbody->info.numlines;i++) { if (targetbody->info.textlines[i][0]=='/') continue; n++; MakeInfoLine(n,targetbody->info.textlines[i]); } } glEndList(); } void CInfo::Start(float seconds, float duration, char *targetname, CBody *targetbody) { if (!loaded) return; char name[32]; strcpy(name,targetname); int l=strlen(name); for (int i=0;i<l;i++) if (name[i]=='_') name[i]=' '; starttime=seconds; endtime=starttime+duration; fadetime=FADE_TIME(duration); MakeName(namelist,name); MakeInfo(infolist,targetbody); } void CInfo::Update(float seconds) { time=seconds; if (time<(endtime-fadetime)) alpha=min(1,(time-starttime)/fadetime); else alpha=max(0,(endtime-time)/fadetime); } void CInfo::Restart() { starttime-=time; endtime-=time; time=0; } void CInfo::Draw() { if (!alpha || !loaded) return; glDisable(GL_LIGHTING); glDisable(GL_DEPTH_TEST); glDisable(GL_CULL_FACE); glEnable(GL_BLEND); glColor4f(WINDOW_COLOR_R,WINDOW_COLOR_G,WINDOW_COLOR_B,WINDOW_COLOR_A*alpha); glCallList(winlist); glColor4f(NAME_TEXT_COLOR_R,NAME_TEXT_COLOR_G,NAME_TEXT_COLOR_B,NAME_TEXT_COLOR_A*alpha); glCallList(namelist); glColor4f(INFO_TEXT_COLOR_R,INFO_TEXT_COLOR_G,INFO_TEXT_COLOR_B,INFO_TEXT_COLOR_A*alpha); glCallList(infolist); } <|endoftext|>
<commit_before>/* * Global Presence - wraps calls to set and get presence for all accounts. * * Copyright (C) 2011 David Edmundson <[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 St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "global-presence.h" #include "presence.h" #include <TelepathyQt/AccountSet> #include <TelepathyQt/Account> #include <TelepathyQt/PendingReady> #include "ktp-debug.h" namespace KTp { GlobalPresence::GlobalPresence(QObject *parent) : QObject(parent), m_connectionStatus(Tp::ConnectionStatusDisconnected), m_changingPresence(false) { Tp::Presence unknown; unknown.setStatus(Tp::ConnectionPresenceTypeUnknown, QLatin1String("unknown"), QString()); m_requestedPresence = KTp::Presence(unknown); m_currentPresence = KTp::Presence(unknown); } void GlobalPresence::setAccountManager(const Tp::AccountManagerPtr &accountManager) { if (! accountManager->isReady()) { qCWarning(KTP_COMMONINTERNALS) << "GlobalPresence used with unready account manager"; } m_enabledAccounts = accountManager->enabledAccounts(); m_onlineAccounts = accountManager->onlineAccounts(); Q_FOREACH(const Tp::AccountPtr &account, m_enabledAccounts->accounts()) { onAccountAdded(account); } onCurrentPresenceChanged(); onRequestedPresenceChanged(); onChangingPresence(); onConnectionStatusChanged(); connect(m_enabledAccounts.data(), SIGNAL(accountAdded(Tp::AccountPtr)), SLOT(onAccountAdded(Tp::AccountPtr))); connect(m_enabledAccounts.data(), SIGNAL(accountRemoved(Tp::AccountPtr)), this, SIGNAL(enabledAccountsChanged())); } void GlobalPresence::addAccountManager(const Tp::AccountManagerPtr &accountManager) { m_accountManager = accountManager; connect(m_accountManager->becomeReady(), SIGNAL(finished(Tp::PendingOperation*)), this, SLOT(onAccountManagerReady(Tp::PendingOperation*))); } Tp::AccountManagerPtr GlobalPresence::accountManager() const { return m_accountManager; } void GlobalPresence::onAccountManagerReady(Tp::PendingOperation* op) { if (op->isError()) { qCDebug(KTP_COMMONINTERNALS) << op->errorName(); qCDebug(KTP_COMMONINTERNALS) << op->errorMessage(); //TODO: Create signal to send to client qCDebug(KTP_COMMONINTERNALS) << "Something unexpected happened to the core part of your Instant Messaging system " << "and it couldn't be initialized. Try restarting the client."; return; } setAccountManager(m_accountManager); Q_EMIT(accountManagerReady()); } Tp::ConnectionStatus GlobalPresence::connectionStatus() const { return m_connectionStatus; } Presence GlobalPresence::currentPresence() const { return m_currentPresence; } QString GlobalPresence::currentPresenceMessage() const { KTp::Presence p = currentPresence(); return p.statusMessage(); } QIcon GlobalPresence::currentPresenceIcon() const { return currentPresence().icon(); } QString GlobalPresence::currentPresenceIconName() const { return currentPresence().iconName(); } QString GlobalPresence::currentPresenceName() const { return currentPresence().displayString(); } GlobalPresence::ConnectionPresenceType GlobalPresence::currentPresenceType() const { KTp::Presence p = currentPresence(); switch(p.type()) { case Tp::ConnectionPresenceTypeAvailable: return GlobalPresence::Available; case Tp::ConnectionPresenceTypeBusy: return GlobalPresence::Busy; case Tp::ConnectionPresenceTypeAway: return GlobalPresence::Away; case Tp::ConnectionPresenceTypeExtendedAway: return GlobalPresence::ExtendedAway; case Tp::ConnectionPresenceTypeHidden: return GlobalPresence::Hidden; case Tp::ConnectionPresenceTypeOffline: return GlobalPresence::Offline; default: return GlobalPresence::Unknown; } } Presence GlobalPresence::requestedPresence() const { return m_requestedPresence; } QString GlobalPresence::requestedPresenceName() const { return m_requestedPresence.displayString(); } bool GlobalPresence::isChangingPresence() const { return connectionStatus() == Tp::ConnectionStatusConnecting; } void GlobalPresence::setPresence(const KTp::Presence &presence) { if (m_enabledAccounts.isNull()) { qCWarning(KTP_COMMONINTERNALS) << "Requested presence change on empty accounts set"; return; } Q_FOREACH(const Tp::AccountPtr &account, m_enabledAccounts->accounts()) { account->setRequestedPresence(presence); } } void GlobalPresence::setPresence(GlobalPresence::ConnectionPresenceType p, QString message) { switch (p) { case GlobalPresence::Available: setPresence(Tp::Presence::available(message)); break; case GlobalPresence::Busy: setPresence(Tp::Presence::busy(message)); break; case GlobalPresence::Away: setPresence(Tp::Presence::away(message)); break; case GlobalPresence::ExtendedAway: setPresence(Tp::Presence::xa(message)); break; case GlobalPresence::Hidden: setPresence(Tp::Presence::hidden(message)); break; case GlobalPresence::Offline: setPresence(Tp::Presence::offline(message)); break; default: qCDebug(KTP_COMMONINTERNALS) << "You should not be here!"; } } void GlobalPresence::onAccountAdded(const Tp::AccountPtr &account) { connect(account.data(), SIGNAL(connectionStatusChanged(Tp::ConnectionStatus)), SLOT(onConnectionStatusChanged())); connect(account.data(), SIGNAL(requestedPresenceChanged(Tp::Presence)), SLOT(onRequestedPresenceChanged())); connect(account.data(), SIGNAL(currentPresenceChanged(Tp::Presence)), SLOT(onCurrentPresenceChanged())); Q_EMIT enabledAccountsChanged(); } void GlobalPresence::onCurrentPresenceChanged() { /* basic idea of choosing global presence it to make it reflects the presence * over all accounts, usually this is used to indicates user the whole system * status. * * If there isn't any account, currentPresence should be offline, since there is nothing * online. * If there's only one account, then currentPresence should represent the presence * of this account. * If there're more than one accounts, the situation is more complicated. * There can be some accounts is still connecting (thus it's offline), and there can be * some accounts doesn't support the presence you're choosing. The user-chosen presence * priority will be higher than standard presence order. * * Example: * user choose to be online, 1 account online, 1 account offline, current presence * should be online, since online priority is higher than offline. * user chooses a presence supported by part of the account, current presence will be * the one chosen by user, to indicate there is at least one account supports it. * user choose a presence supported by no account, current presence will be chosen * from all accounts based on priority, and it also indicates there is no account support * the user-chosen presence. */ Tp::Presence highestCurrentPresence = Tp::Presence::offline(); Q_FOREACH(const Tp::AccountPtr &account, m_enabledAccounts->accounts()) { if (account->currentPresence().type() == m_requestedPresence.type()) { highestCurrentPresence = account->currentPresence(); break; } if (Presence::sortPriority(account->currentPresence().type()) < Presence::sortPriority(highestCurrentPresence.type())) { highestCurrentPresence = account->currentPresence(); } } qCDebug(KTP_COMMONINTERNALS) << "Current presence changed"; if (highestCurrentPresence.type() != m_currentPresence.type() || highestCurrentPresence.status() != m_currentPresence.status() || highestCurrentPresence.statusMessage() != m_currentPresence.statusMessage()) { m_currentPresence = Presence(highestCurrentPresence); Q_EMIT currentPresenceChanged(m_currentPresence); } onChangingPresence(); } void GlobalPresence::onRequestedPresenceChanged() { Tp::Presence highestRequestedPresence = Tp::Presence::offline(); Q_FOREACH(const Tp::AccountPtr &account, m_enabledAccounts->accounts()) { if (Presence::sortPriority(account->requestedPresence().type()) < Presence::sortPriority(highestRequestedPresence.type())) { highestRequestedPresence = account->requestedPresence(); } } if (highestRequestedPresence.type() != m_requestedPresence.type() || highestRequestedPresence.status() != m_requestedPresence.status() || highestRequestedPresence.statusMessage() != m_requestedPresence.statusMessage()) { m_requestedPresence = Presence(highestRequestedPresence); // current presence priority is affected by requested presence onCurrentPresenceChanged(); Q_EMIT requestedPresenceChanged(m_requestedPresence); } onChangingPresence(); } void GlobalPresence::onChangingPresence() { bool isChangingPresence = false; Q_FOREACH(const Tp::AccountPtr &account, m_enabledAccounts->accounts()) { if (account->requestedPresence().type() != account->currentPresence().type()) { isChangingPresence = true; } } if (isChangingPresence != m_changingPresence) { m_changingPresence = isChangingPresence; Q_EMIT changingPresence(m_changingPresence); } } void GlobalPresence::onConnectionStatusChanged() { Tp::ConnectionStatus connectionStatus = Tp::ConnectionStatusDisconnected; Q_FOREACH(const Tp::AccountPtr &account, m_enabledAccounts->accounts()) { switch (account->connectionStatus()) { case Tp::ConnectionStatusConnecting: //connecting is the highest state, use this always connectionStatus = Tp::ConnectionStatusConnecting; break; case Tp::ConnectionStatusConnected: //only set to connected if we're not at connecting if (connectionStatus == Tp::ConnectionStatusDisconnected) { connectionStatus = Tp::ConnectionStatusConnected; } break; default: break; } } if (connectionStatus != m_connectionStatus) { m_connectionStatus = connectionStatus; Q_EMIT connectionStatusChanged(m_connectionStatus); } } bool GlobalPresence::hasEnabledAccounts() const { if (m_enabledAccounts->accounts().isEmpty()) { return false; } return true; } void GlobalPresence::saveCurrentPresence() { qCDebug(KTP_COMMONINTERNALS) << "Saving presence with message:" << m_currentPresence.statusMessage(); m_savedPresence = m_currentPresence; } void GlobalPresence::restoreSavedPresence() { qCDebug(KTP_COMMONINTERNALS) << m_savedPresence.statusMessage(); setPresence(m_savedPresence); } Tp::AccountSetPtr GlobalPresence::onlineAccounts() const { return m_onlineAccounts; } } #include "global-presence.moc" <commit_msg>Fix crash when m_enabledAccounts is still null.<commit_after>/* * Global Presence - wraps calls to set and get presence for all accounts. * * Copyright (C) 2011 David Edmundson <[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 St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "global-presence.h" #include "presence.h" #include <TelepathyQt/AccountSet> #include <TelepathyQt/Account> #include <TelepathyQt/PendingReady> #include "ktp-debug.h" namespace KTp { GlobalPresence::GlobalPresence(QObject *parent) : QObject(parent), m_connectionStatus(Tp::ConnectionStatusDisconnected), m_changingPresence(false) { Tp::Presence unknown; unknown.setStatus(Tp::ConnectionPresenceTypeUnknown, QLatin1String("unknown"), QString()); m_requestedPresence = KTp::Presence(unknown); m_currentPresence = KTp::Presence(unknown); } void GlobalPresence::setAccountManager(const Tp::AccountManagerPtr &accountManager) { if (! accountManager->isReady()) { qCWarning(KTP_COMMONINTERNALS) << "GlobalPresence used with unready account manager"; } m_enabledAccounts = accountManager->enabledAccounts(); m_onlineAccounts = accountManager->onlineAccounts(); Q_FOREACH(const Tp::AccountPtr &account, m_enabledAccounts->accounts()) { onAccountAdded(account); } onCurrentPresenceChanged(); onRequestedPresenceChanged(); onChangingPresence(); onConnectionStatusChanged(); connect(m_enabledAccounts.data(), SIGNAL(accountAdded(Tp::AccountPtr)), SLOT(onAccountAdded(Tp::AccountPtr))); connect(m_enabledAccounts.data(), SIGNAL(accountRemoved(Tp::AccountPtr)), this, SIGNAL(enabledAccountsChanged())); } void GlobalPresence::addAccountManager(const Tp::AccountManagerPtr &accountManager) { m_accountManager = accountManager; connect(m_accountManager->becomeReady(), SIGNAL(finished(Tp::PendingOperation*)), this, SLOT(onAccountManagerReady(Tp::PendingOperation*))); } Tp::AccountManagerPtr GlobalPresence::accountManager() const { return m_accountManager; } void GlobalPresence::onAccountManagerReady(Tp::PendingOperation* op) { if (op->isError()) { qCDebug(KTP_COMMONINTERNALS) << op->errorName(); qCDebug(KTP_COMMONINTERNALS) << op->errorMessage(); //TODO: Create signal to send to client qCDebug(KTP_COMMONINTERNALS) << "Something unexpected happened to the core part of your Instant Messaging system " << "and it couldn't be initialized. Try restarting the client."; return; } setAccountManager(m_accountManager); Q_EMIT(accountManagerReady()); } Tp::ConnectionStatus GlobalPresence::connectionStatus() const { return m_connectionStatus; } Presence GlobalPresence::currentPresence() const { return m_currentPresence; } QString GlobalPresence::currentPresenceMessage() const { KTp::Presence p = currentPresence(); return p.statusMessage(); } QIcon GlobalPresence::currentPresenceIcon() const { return currentPresence().icon(); } QString GlobalPresence::currentPresenceIconName() const { return currentPresence().iconName(); } QString GlobalPresence::currentPresenceName() const { return currentPresence().displayString(); } GlobalPresence::ConnectionPresenceType GlobalPresence::currentPresenceType() const { KTp::Presence p = currentPresence(); switch(p.type()) { case Tp::ConnectionPresenceTypeAvailable: return GlobalPresence::Available; case Tp::ConnectionPresenceTypeBusy: return GlobalPresence::Busy; case Tp::ConnectionPresenceTypeAway: return GlobalPresence::Away; case Tp::ConnectionPresenceTypeExtendedAway: return GlobalPresence::ExtendedAway; case Tp::ConnectionPresenceTypeHidden: return GlobalPresence::Hidden; case Tp::ConnectionPresenceTypeOffline: return GlobalPresence::Offline; default: return GlobalPresence::Unknown; } } Presence GlobalPresence::requestedPresence() const { return m_requestedPresence; } QString GlobalPresence::requestedPresenceName() const { return m_requestedPresence.displayString(); } bool GlobalPresence::isChangingPresence() const { return connectionStatus() == Tp::ConnectionStatusConnecting; } void GlobalPresence::setPresence(const KTp::Presence &presence) { if (m_enabledAccounts.isNull()) { qCWarning(KTP_COMMONINTERNALS) << "Requested presence change on empty accounts set"; return; } Q_FOREACH(const Tp::AccountPtr &account, m_enabledAccounts->accounts()) { account->setRequestedPresence(presence); } } void GlobalPresence::setPresence(GlobalPresence::ConnectionPresenceType p, QString message) { switch (p) { case GlobalPresence::Available: setPresence(Tp::Presence::available(message)); break; case GlobalPresence::Busy: setPresence(Tp::Presence::busy(message)); break; case GlobalPresence::Away: setPresence(Tp::Presence::away(message)); break; case GlobalPresence::ExtendedAway: setPresence(Tp::Presence::xa(message)); break; case GlobalPresence::Hidden: setPresence(Tp::Presence::hidden(message)); break; case GlobalPresence::Offline: setPresence(Tp::Presence::offline(message)); break; default: qCDebug(KTP_COMMONINTERNALS) << "You should not be here!"; } } void GlobalPresence::onAccountAdded(const Tp::AccountPtr &account) { connect(account.data(), SIGNAL(connectionStatusChanged(Tp::ConnectionStatus)), SLOT(onConnectionStatusChanged())); connect(account.data(), SIGNAL(requestedPresenceChanged(Tp::Presence)), SLOT(onRequestedPresenceChanged())); connect(account.data(), SIGNAL(currentPresenceChanged(Tp::Presence)), SLOT(onCurrentPresenceChanged())); Q_EMIT enabledAccountsChanged(); } void GlobalPresence::onCurrentPresenceChanged() { /* basic idea of choosing global presence it to make it reflects the presence * over all accounts, usually this is used to indicates user the whole system * status. * * If there isn't any account, currentPresence should be offline, since there is nothing * online. * If there's only one account, then currentPresence should represent the presence * of this account. * If there're more than one accounts, the situation is more complicated. * There can be some accounts is still connecting (thus it's offline), and there can be * some accounts doesn't support the presence you're choosing. The user-chosen presence * priority will be higher than standard presence order. * * Example: * user choose to be online, 1 account online, 1 account offline, current presence * should be online, since online priority is higher than offline. * user chooses a presence supported by part of the account, current presence will be * the one chosen by user, to indicate there is at least one account supports it. * user choose a presence supported by no account, current presence will be chosen * from all accounts based on priority, and it also indicates there is no account support * the user-chosen presence. */ Tp::Presence highestCurrentPresence = Tp::Presence::offline(); Q_FOREACH(const Tp::AccountPtr &account, m_enabledAccounts->accounts()) { if (account->currentPresence().type() == m_requestedPresence.type()) { highestCurrentPresence = account->currentPresence(); break; } if (Presence::sortPriority(account->currentPresence().type()) < Presence::sortPriority(highestCurrentPresence.type())) { highestCurrentPresence = account->currentPresence(); } } qCDebug(KTP_COMMONINTERNALS) << "Current presence changed"; if (highestCurrentPresence.type() != m_currentPresence.type() || highestCurrentPresence.status() != m_currentPresence.status() || highestCurrentPresence.statusMessage() != m_currentPresence.statusMessage()) { m_currentPresence = Presence(highestCurrentPresence); Q_EMIT currentPresenceChanged(m_currentPresence); } onChangingPresence(); } void GlobalPresence::onRequestedPresenceChanged() { Tp::Presence highestRequestedPresence = Tp::Presence::offline(); Q_FOREACH(const Tp::AccountPtr &account, m_enabledAccounts->accounts()) { if (Presence::sortPriority(account->requestedPresence().type()) < Presence::sortPriority(highestRequestedPresence.type())) { highestRequestedPresence = account->requestedPresence(); } } if (highestRequestedPresence.type() != m_requestedPresence.type() || highestRequestedPresence.status() != m_requestedPresence.status() || highestRequestedPresence.statusMessage() != m_requestedPresence.statusMessage()) { m_requestedPresence = Presence(highestRequestedPresence); // current presence priority is affected by requested presence onCurrentPresenceChanged(); Q_EMIT requestedPresenceChanged(m_requestedPresence); } onChangingPresence(); } void GlobalPresence::onChangingPresence() { bool isChangingPresence = false; Q_FOREACH(const Tp::AccountPtr &account, m_enabledAccounts->accounts()) { if (account->requestedPresence().type() != account->currentPresence().type()) { isChangingPresence = true; } } if (isChangingPresence != m_changingPresence) { m_changingPresence = isChangingPresence; Q_EMIT changingPresence(m_changingPresence); } } void GlobalPresence::onConnectionStatusChanged() { Tp::ConnectionStatus connectionStatus = Tp::ConnectionStatusDisconnected; Q_FOREACH(const Tp::AccountPtr &account, m_enabledAccounts->accounts()) { switch (account->connectionStatus()) { case Tp::ConnectionStatusConnecting: //connecting is the highest state, use this always connectionStatus = Tp::ConnectionStatusConnecting; break; case Tp::ConnectionStatusConnected: //only set to connected if we're not at connecting if (connectionStatus == Tp::ConnectionStatusDisconnected) { connectionStatus = Tp::ConnectionStatusConnected; } break; default: break; } } if (connectionStatus != m_connectionStatus) { m_connectionStatus = connectionStatus; Q_EMIT connectionStatusChanged(m_connectionStatus); } } bool GlobalPresence::hasEnabledAccounts() const { if (m_enabledAccounts.isNull() || m_enabledAccounts->accounts().isEmpty()) { return false; } return true; } void GlobalPresence::saveCurrentPresence() { qCDebug(KTP_COMMONINTERNALS) << "Saving presence with message:" << m_currentPresence.statusMessage(); m_savedPresence = m_currentPresence; } void GlobalPresence::restoreSavedPresence() { qCDebug(KTP_COMMONINTERNALS) << m_savedPresence.statusMessage(); setPresence(m_savedPresence); } Tp::AccountSetPtr GlobalPresence::onlineAccounts() const { return m_onlineAccounts; } } #include "global-presence.moc" <|endoftext|>
<commit_before>#include <Utilities/Common.h> #include <string> #include <iostream> #include <fstream> #include <vector> #include <utility> using namespace std; struct coord { word x; word y; }; class grid { word width; word height; coord start; coord end; vector<vector<word>> cells; vector<coord> get_neighbors(coord c); void walk(coord next, word previous_lowest_cost); public: grid(istream& stream); void print_input(ostream& stream); void print_output(ostream& stream); word find_path(); }; grid::grid(istream& stream) { stream >> this->width >> this->height; stream >> this->start.x >> this->start.y; stream >> this->end.x >> this->end.y; this->cells.resize(this->width); for (word x = 0; x < this->width; x++) this->cells[x].resize(this->height); for (word y = 0; y < this->height; y++) for (word x = 0; x < this->width; x++) stream >> this->cells[x][y]; } void grid::print_input(ostream& stream) { for (word y = 0; y < this->height; y++) { for (word x = 0; x < this->width; x++) stream << this->cells[x][y] << " "; stream << endl; } } void grid::print_output(ostream& stream) { } vector<coord> grid::get_neighbors(coord c) { vector<coord> neighbors; if (c.x == 0) { neighbors.push_back(coord { 1, 0 }); } else if (c.x == this->width - 1) { neighbors.push_back(coord { this->width - 2, 0 }); } else { neighbors.push_back(coord { c.x - 1, c.y }); neighbors.push_back(coord { c.x + 1, c.y }); } if (c.y == 0) { neighbors.push_back(coord { 0, 1 }); } else if (c.y == this->height - 1) { neighbors.push_back(coord { 0, this->height - 2 }); } else { neighbors.push_back(coord { c.x, c.y - 1 }); neighbors.push_back(coord { c.x, c.y + 1 }); } return neighbors; } word grid::find_path() { this->walk(this->start, 0); return 0; } void grid::walk(coord current, word previous_lowest_cost) { auto neighbors = this->get_neighbors(current); auto current_cost = this->cells[current.x][current.y]; word lowest_cost = 0; for (auto i : neighbors) { auto& neighbor_cost = this->cells[i.x][i.y]; if (neighbor_cost != 0) neighbor_cost += current_cost; if (neighbor_cost < lowest_cost) lowest_cost = neighbor_cost; } } int main() { string path; cout << "Filename: "; cin >> path; ifstream file(path); grid g(file); auto cost = g.find_path(); cout << "Input: " << endl; g.print_input(cout); cout << "Output: " << endl; cout << "Cost: " << cost << endl; g.print_output(cout); return 0; } <commit_msg>Updated a dependency name.<commit_after>#include <ArkeIndustries.CPPUtilities/Common.h> #include <string> #include <iostream> #include <fstream> #include <vector> #include <utility> using namespace std; struct coord { word x; word y; }; class grid { word width; word height; coord start; coord end; vector<vector<word>> cells; vector<coord> get_neighbors(coord c); void walk(coord next, word previous_lowest_cost); public: grid(istream& stream); void print_input(ostream& stream); void print_output(ostream& stream); word find_path(); }; grid::grid(istream& stream) { stream >> this->width >> this->height; stream >> this->start.x >> this->start.y; stream >> this->end.x >> this->end.y; this->cells.resize(this->width); for (word x = 0; x < this->width; x++) this->cells[x].resize(this->height); for (word y = 0; y < this->height; y++) for (word x = 0; x < this->width; x++) stream >> this->cells[x][y]; } void grid::print_input(ostream& stream) { for (word y = 0; y < this->height; y++) { for (word x = 0; x < this->width; x++) stream << this->cells[x][y] << " "; stream << endl; } } void grid::print_output(ostream& stream) { } vector<coord> grid::get_neighbors(coord c) { vector<coord> neighbors; if (c.x == 0) { neighbors.push_back(coord { 1, 0 }); } else if (c.x == this->width - 1) { neighbors.push_back(coord { this->width - 2, 0 }); } else { neighbors.push_back(coord { c.x - 1, c.y }); neighbors.push_back(coord { c.x + 1, c.y }); } if (c.y == 0) { neighbors.push_back(coord { 0, 1 }); } else if (c.y == this->height - 1) { neighbors.push_back(coord { 0, this->height - 2 }); } else { neighbors.push_back(coord { c.x, c.y - 1 }); neighbors.push_back(coord { c.x, c.y + 1 }); } return neighbors; } word grid::find_path() { this->walk(this->start, 0); return 0; } void grid::walk(coord current, word previous_lowest_cost) { auto neighbors = this->get_neighbors(current); auto current_cost = this->cells[current.x][current.y]; word lowest_cost = 0; for (auto i : neighbors) { auto& neighbor_cost = this->cells[i.x][i.y]; if (neighbor_cost != 0) neighbor_cost += current_cost; if (neighbor_cost < lowest_cost) lowest_cost = neighbor_cost; } } int main() { string path; cout << "Filename: "; cin >> path; ifstream file(path); grid g(file); auto cost = g.find_path(); cout << "Input: " << endl; g.print_input(cout); cout << "Output: " << endl; cout << "Cost: " << cost << endl; g.print_output(cout); return 0; } <|endoftext|>
<commit_before>#include "Ruby.h" #include "RubyObject.h" #include "common.h" #include <cstring> #include <iostream> using namespace std; using namespace v8; Persistent<Function> Ruby::s_getCtor; VALUE Ruby::BLOCK_WRAPPER_CLASS; void Ruby::Init(Handle<Object> module) { int argc = 0; char** argv = NULL; // TODO: Do we need to call this? ruby_sysinit(&argc, &argv); RUBY_INIT_STACK; ruby_init(); ruby_init_loadpath(); BLOCK_WRAPPER_CLASS = rb_define_class("BlockWrapper", rb_cObject); node::AtExit(Cleanup); module->Set(NanNew<String>("exports"), NanNew<FunctionTemplate>(New)->GetFunction()); } void Ruby::Cleanup(void*) { log("Cleaning up!" << endl); RubyObject::Cleanup(); ruby_cleanup(0); } NAN_METHOD(Ruby::New) { NanScope(); assert(args[0]->IsFunction()); NanAssignPersistent(s_getCtor, args[0].As<Function>()); Local<Object> bindings = NanNew<Object>(); NODE_SET_METHOD(bindings, "_getClass", GetClass); NODE_SET_METHOD(bindings, "_gcStart", GCStart); NODE_SET_METHOD(bindings, "_defineClass", DefineClass); NODE_SET_METHOD(bindings, "require", Require); NODE_SET_METHOD(bindings, "eval", Eval); // TODO: Right name? NODE_SET_METHOD(bindings, "getFunction", GetFunction); // TODO: Maybe we should load the constants here and place them in an object? NODE_SET_METHOD(bindings, "getConstant", GetConstant); NanReturnValue(bindings); } Local<Function> Ruby::GetCtor(Local<Function> rubyClass) { NanEscapableScope(); Local<Function> getCtor = NanNew<Function>(s_getCtor); Handle<Value> argv[] = { rubyClass }; return NanEscapeScope(NanMakeCallback(NanGetCurrentContext()->Global(), getCtor, 1, argv).As<Function>()); } struct ConstGetter { ConstGetter(Handle<Value> nv) : nameVal(nv) {} VALUE operator()() const { NanScope(); Local<String> constName = nameVal->ToString(); String::Utf8Value constStr(constName); ID id; VALUE mod; const char* split = std::strstr(*constStr, "::"); if (split) { id = rb_intern(split + 2); mod = rb_const_get(rb_cObject, rb_intern2(*constStr, split - *constStr)); } else { id = rb_intern2(*constStr, constStr.length()); mod = rb_cObject; } return rb_const_get(mod, id); } Handle<Value> nameVal; }; // TODO: Should/could we combine this with RubyObject::GetClass? NAN_METHOD(Ruby::GetClass) { NanScope(); VALUE klass; SAFE_RUBY_CALL(klass, ConstGetter(args[0])); if (TYPE(klass) != T_CLASS) { std::string msg(*String::Utf8Value(args[0])); msg.append(" is not a class"); // TODO: TypeError? NanThrowError(msg.c_str()); NanReturnUndefined(); } NanReturnValue(RubyObject::GetClass(klass)); } NAN_METHOD(Ruby::GCStart) { NanScope(); rb_gc_start(); NanReturnUndefined(); } struct ClassDefiner { ClassDefiner(Handle<Value> nv, VALUE s) : nameVal(nv), super(s) {} VALUE operator()() const { NanScope(); Local<String> className = nameVal->ToString(); return rb_define_class(*String::Utf8Value(className), super); } Handle<Value> nameVal; VALUE super; }; NAN_METHOD(Ruby::DefineClass) { NanScope(); Local<String> name = args[0]->ToString(); log("Inherit called for " << *String::Utf8Value(name) << endl); VALUE super; SAFE_RUBY_CALL(super, ConstGetter(args[1])); VALUE klass; SAFE_RUBY_CALL(klass, ClassDefiner(args[0], super)); NanReturnValue(RubyObject::GetClass(klass)); } struct RequireCaller { RequireCaller(const char* n) : name(n) {} VALUE operator()() const { return rb_require(name); } const char* name; }; NAN_METHOD(Ruby::Require) { NanScope(); Local<String> name = args[0]->ToString(); VALUE res; SAFE_RUBY_CALL(res, RequireCaller(*String::Utf8Value(name))); NanReturnValue(rubyToV8(res)); } struct EvalCaller { EvalCaller(const char* s) : str(s) {} VALUE operator()() const { return rb_eval_string(str); } const char* str; }; NAN_METHOD(Ruby::Eval) { NanScope(); Local<String> str = args[0]->ToString(); VALUE res; SAFE_RUBY_CALL(res, EvalCaller(*String::Utf8Value(str))); NanReturnValue(rubyToV8(res)); } // TODO: Can this be combined with RubyObject::CallMethod? Maybe rename? NAN_METHOD(CallMethod) { NanScope(); NanReturnValue(CallRubyFromV8(rb_cObject, args)); } // TODO: Should this throw immediately if the function doesnt exist? NAN_METHOD(Ruby::GetFunction) { NanScope(); Local<String> name = args[0]->ToString(); ID methodID = rb_intern(*String::Utf8Value(name)); Local<Function> func = NanNew<FunctionTemplate>(CallMethod, EXTERNAL_WRAP((void*)methodID))->GetFunction(); func->SetName(name); NanReturnValue(func); } NAN_METHOD(Ruby::GetConstant) { NanScope(); VALUE constant; SAFE_RUBY_CALL(constant, ConstGetter(args[0])); // TODO: Should we allow getting classes this way? Maybe throw an exception? NanReturnValue(rubyToV8(constant)); } <commit_msg>Properly initialize Ruby<commit_after>#include "Ruby.h" #include "RubyObject.h" #include "common.h" #include <cstring> #include <iostream> using namespace std; using namespace v8; Persistent<Function> Ruby::s_getCtor; VALUE Ruby::BLOCK_WRAPPER_CLASS; void Ruby::Init(Handle<Object> module) { static char* argv[] = { (char*)"norby", (char*)"-e", (char*)"" }; RUBY_INIT_STACK; ruby_init(); ruby_options(3, argv); BLOCK_WRAPPER_CLASS = rb_define_class("BlockWrapper", rb_cObject); node::AtExit(Cleanup); module->Set(NanNew<String>("exports"), NanNew<FunctionTemplate>(New)->GetFunction()); } void Ruby::Cleanup(void*) { log("Cleaning up!" << endl); RubyObject::Cleanup(); ruby_cleanup(0); } NAN_METHOD(Ruby::New) { NanScope(); assert(args[0]->IsFunction()); NanAssignPersistent(s_getCtor, args[0].As<Function>()); Local<Object> bindings = NanNew<Object>(); NODE_SET_METHOD(bindings, "_getClass", GetClass); NODE_SET_METHOD(bindings, "_gcStart", GCStart); NODE_SET_METHOD(bindings, "_defineClass", DefineClass); NODE_SET_METHOD(bindings, "require", Require); NODE_SET_METHOD(bindings, "eval", Eval); // TODO: Right name? NODE_SET_METHOD(bindings, "getFunction", GetFunction); // TODO: Maybe we should load the constants here and place them in an object? NODE_SET_METHOD(bindings, "getConstant", GetConstant); NanReturnValue(bindings); } Local<Function> Ruby::GetCtor(Local<Function> rubyClass) { NanEscapableScope(); Local<Function> getCtor = NanNew<Function>(s_getCtor); Handle<Value> argv[] = { rubyClass }; return NanEscapeScope(NanMakeCallback(NanGetCurrentContext()->Global(), getCtor, 1, argv).As<Function>()); } struct ConstGetter { ConstGetter(Handle<Value> nv) : nameVal(nv) {} VALUE operator()() const { NanScope(); Local<String> constName = nameVal->ToString(); String::Utf8Value constStr(constName); ID id; VALUE mod; const char* split = std::strstr(*constStr, "::"); if (split) { id = rb_intern(split + 2); mod = rb_const_get(rb_cObject, rb_intern2(*constStr, split - *constStr)); } else { id = rb_intern2(*constStr, constStr.length()); mod = rb_cObject; } return rb_const_get(mod, id); } Handle<Value> nameVal; }; // TODO: Should/could we combine this with RubyObject::GetClass? NAN_METHOD(Ruby::GetClass) { NanScope(); VALUE klass; SAFE_RUBY_CALL(klass, ConstGetter(args[0])); if (TYPE(klass) != T_CLASS) { std::string msg(*String::Utf8Value(args[0])); msg.append(" is not a class"); // TODO: TypeError? NanThrowError(msg.c_str()); NanReturnUndefined(); } NanReturnValue(RubyObject::GetClass(klass)); } NAN_METHOD(Ruby::GCStart) { NanScope(); rb_gc_start(); NanReturnUndefined(); } struct ClassDefiner { ClassDefiner(Handle<Value> nv, VALUE s) : nameVal(nv), super(s) {} VALUE operator()() const { NanScope(); Local<String> className = nameVal->ToString(); return rb_define_class(*String::Utf8Value(className), super); } Handle<Value> nameVal; VALUE super; }; NAN_METHOD(Ruby::DefineClass) { NanScope(); Local<String> name = args[0]->ToString(); log("Inherit called for " << *String::Utf8Value(name) << endl); VALUE super; SAFE_RUBY_CALL(super, ConstGetter(args[1])); VALUE klass; SAFE_RUBY_CALL(klass, ClassDefiner(args[0], super)); NanReturnValue(RubyObject::GetClass(klass)); } struct RequireCaller { RequireCaller(const char* n) : name(n) {} VALUE operator()() const { return rb_require(name); } const char* name; }; NAN_METHOD(Ruby::Require) { NanScope(); Local<String> name = args[0]->ToString(); VALUE res; SAFE_RUBY_CALL(res, RequireCaller(*String::Utf8Value(name))); NanReturnValue(rubyToV8(res)); } struct EvalCaller { EvalCaller(const char* s) : str(s) {} VALUE operator()() const { return rb_eval_string(str); } const char* str; }; NAN_METHOD(Ruby::Eval) { NanScope(); Local<String> str = args[0]->ToString(); VALUE res; SAFE_RUBY_CALL(res, EvalCaller(*String::Utf8Value(str))); NanReturnValue(rubyToV8(res)); } // TODO: Can this be combined with RubyObject::CallMethod? Maybe rename? NAN_METHOD(CallMethod) { NanScope(); NanReturnValue(CallRubyFromV8(rb_cObject, args)); } // TODO: Should this throw immediately if the function doesnt exist? NAN_METHOD(Ruby::GetFunction) { NanScope(); Local<String> name = args[0]->ToString(); ID methodID = rb_intern(*String::Utf8Value(name)); Local<Function> func = NanNew<FunctionTemplate>(CallMethod, EXTERNAL_WRAP((void*)methodID))->GetFunction(); func->SetName(name); NanReturnValue(func); } NAN_METHOD(Ruby::GetConstant) { NanScope(); VALUE constant; SAFE_RUBY_CALL(constant, ConstGetter(args[0])); // TODO: Should we allow getting classes this way? Maybe throw an exception? NanReturnValue(rubyToV8(constant)); } <|endoftext|>
<commit_before>//------------------------------------------------------------------------------ // main.cpp // Entry point for the primary driver program. // // File is under the MIT license; see LICENSE for details //------------------------------------------------------------------------------ #include "compilation/Compilation.h" #include "parsing/SyntaxTree.h" #include "CLI11.hpp" #include "json.hpp" using namespace slang; int main(int argc, char** argv) try { std::vector<std::string> sourceFiles; CLI::App cmd("SystemVerilog compiler"); cmd.add_option("files", sourceFiles, "Source files to compile"); try { cmd.parse(argc, argv); } catch (const CLI::ParseError& e) { return cmd.exit(e); } // Initialize the source manager. SourceManager sourceManager; // Build the compilation out of each source file. Compilation compilation; bool anyErrors = false; for (const std::string& file : sourceFiles) { std::shared_ptr<SyntaxTree> tree = SyntaxTree::fromFile(file, sourceManager); if (!tree) { printf("error: no such file or directory: '%s'\n", file.c_str()); anyErrors = true; continue; } compilation.addSyntaxTree(std::move(tree)); } if (compilation.getSyntaxTrees().empty()) { printf("error: no input files\n"); return 1; } // Report diagnostics. Diagnostics diagnostics = compilation.getAllDiagnostics(); DiagnosticWriter writer(sourceManager); printf("%s\n", writer.report(diagnostics).c_str()); return !anyErrors && diagnostics.empty() ? 0 : 1; } catch (const std::exception& e) { printf("internal compiler error (exception): %s\n", e.what()); return 2; }<commit_msg>Expand driver options, add mode to print preprocessed output<commit_after>//------------------------------------------------------------------------------ // main.cpp // Entry point for the primary driver program. // // File is under the MIT license; see LICENSE for details //------------------------------------------------------------------------------ #include "compilation/Compilation.h" #include "parsing/SyntaxTree.h" #include "CLI11.hpp" #include "json.hpp" using namespace slang; bool runPreprocessor(SourceManager& sourceManager, const Bag& options, const std::vector<SourceBuffer>& buffers) { BumpAllocator alloc; DiagnosticWriter writer(sourceManager); bool success = true; for (const SourceBuffer& buffer : buffers) { Diagnostics diagnostics; Preprocessor preprocessor(sourceManager, alloc, diagnostics, options); preprocessor.pushSource(buffer); SmallVectorSized<char, 32> output; while (true) { Token token = preprocessor.next(); token.writeTo(output, SyntaxToStringFlags::IncludePreprocessed | SyntaxToStringFlags::IncludeTrivia); if (token.kind == TokenKind::EndOfFile) break; } if (diagnostics.empty()) printf("%s:\n", std::string(sourceManager.getRawFileName(buffer.id)).c_str()); else { printf("%s", writer.report(diagnostics).c_str()); success = false; } printf("==============================\n%s\n", std::string(output.begin(), output.size()).c_str()); } return success; } bool runCompiler(SourceManager& sourceManager, const Bag& options, const std::vector<SourceBuffer>& buffers) { Compilation compilation; for (const SourceBuffer& buffer : buffers) compilation.addSyntaxTree(SyntaxTree::fromBuffer(buffer, sourceManager, options)); Diagnostics diagnostics = compilation.getAllDiagnostics(); DiagnosticWriter writer(sourceManager); printf("%s\n", writer.report(diagnostics).c_str()); return diagnostics.empty(); } int main(int argc, char** argv) try { std::vector<std::string> sourceFiles; std::vector<std::string> includeDirs; std::vector<std::string> includeSystemDirs; std::vector<std::string> defines; std::vector<std::string> undefines; bool onlyPreprocess; CLI::App cmd("SystemVerilog compiler"); cmd.add_option("files", sourceFiles, "Source files to compile"); cmd.add_option("-I,--include-directory", includeDirs, "Additional include search paths"); cmd.add_option("--include-system-directory", includeSystemDirs, "Additional system include search paths"); cmd.add_option("-D,--define-macro", defines, "Define <macro>=<value> (or 1 if <value> ommitted) in all source files"); cmd.add_option("-U,--undefine-macro", undefines, "Undefine macro name at the start of all source files"); cmd.add_flag("-E,--preprocess", onlyPreprocess, "Only run the preprocessor (and print preprocessed files to stdout)"); try { cmd.parse(argc, argv); } catch (const CLI::ParseError& e) { return cmd.exit(e); } SourceManager sourceManager; for (const std::string& dir : includeDirs) sourceManager.addUserDirectory(string_view(dir)); for (const std::string& dir : includeSystemDirs) sourceManager.addSystemDirectory(string_view(dir)); PreprocessorOptions ppoptions; ppoptions.predefines = defines; ppoptions.undefines = undefines; ppoptions.predefineSource = "<command-line>"; Bag options; options.add(ppoptions); bool anyErrors = false; std::vector<SourceBuffer> buffers; for (const std::string& file : sourceFiles) { SourceBuffer buffer = sourceManager.readSource(file); if (!buffer) { printf("error: no such file or directory: '%s'\n", file.c_str()); anyErrors = true; continue; } buffers.push_back(buffer); } if (buffers.empty()) { printf("error: no input files\n"); return 1; } if (onlyPreprocess) anyErrors |= !runPreprocessor(sourceManager, options, buffers); else anyErrors |= !runCompiler(sourceManager, options, buffers); return anyErrors ? 1 : 0; } catch (const std::exception& e) { printf("internal compiler error (exception): %s\n", e.what()); return 2; }<|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////// // taskwarrior - a command line task list manager. // // Copyright 2006 - 2011, Paul Beckingham, Federico Hernandez. // All rights reserved. // // 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 <iostream> // TODO Remove. #include <Context.h> #include <text.h> #include <TDB2.h> extern Context context; //////////////////////////////////////////////////////////////////////////////// TF2::TF2 () : _read_only (false) , _dirty (false) , _loaded_tasks (false) , _loaded_lines (false) , _loaded_contents (false) , _contents ("") { } //////////////////////////////////////////////////////////////////////////////// TF2::~TF2 () { } //////////////////////////////////////////////////////////////////////////////// void TF2::target (const std::string& f) { _file = File (f); _read_only = ! _file.writable (); // std::cout << "# TF2::target " << f << "\n"; } //////////////////////////////////////////////////////////////////////////////// const std::vector <Task>& TF2::get_tasks () { // std::cout << "# TF2::get_tasks " << _file.data << "\n"; if (! _loaded_tasks) load_tasks (); return _tasks; } //////////////////////////////////////////////////////////////////////////////// const std::vector <std::string>& TF2::get_lines () { // std::cout << "# TF2::get_lines " << _file.data << "\n"; if (! _loaded_lines) load_lines (); return _lines; } //////////////////////////////////////////////////////////////////////////////// const std::string& TF2::get_contents () { // std::cout << "# TF2::get_contents " << _file.data << "\n"; if (! _loaded_contents) load_contents (); return _contents; } //////////////////////////////////////////////////////////////////////////////// void TF2::add_task (const Task& task) { // std::cout << "# TF2::add_task " << _file.data << "\n"; _tasks.push_back (task); // For subsequent queries _added_tasks.push_back (task); // For commit/synch _dirty = true; } //////////////////////////////////////////////////////////////////////////////// void TF2::modify_task (const Task& task) { // std::cout << "# TF2::modify_task " << _file.data << "\n"; // Modify in-place. std::vector <Task>::iterator i; for (i = _tasks.begin (); i != _tasks.end (); ++i) { if (i->get ("uuid") == task.get ("uuid")) { *i = task; break; } } _modified_tasks.push_back (task); _dirty = true; } //////////////////////////////////////////////////////////////////////////////// void TF2::add_line (const std::string& line) { // std::cout << "# TF2::add_line " << _file.data << "\n"; _added_lines.push_back (line); _dirty = true; } //////////////////////////////////////////////////////////////////////////////// // This is so that synch.key can just overwrite and not grow. void TF2::clear_lines () { // std::cout << "# TF2::clear_lines " << _file.data << "\n"; _lines.clear (); _dirty = true; } //////////////////////////////////////////////////////////////////////////////// // Top-down recomposition. void TF2::commit () { // std::cout << "# TF2::commit " << _file.data << "\n"; // The _dirty flag indicates that the file needs to be written. if (_dirty) { // Special case: added but no modified means just append to the file. if (!_modified_tasks.size () && (_added_tasks.size () || _added_lines.size ())) { if (_file.open ()) { if (context.config.getBoolean ("locking")) _file.lock (); // Write out all the added tasks. std::vector <Task>::iterator task; for (task = _added_tasks.begin (); task != _added_tasks.end (); ++task) { _file.append (task->composeF4 ()); } _added_tasks.clear (); // Write out all the added lines. std::vector <std::string>::iterator line; for (line = _added_lines.begin (); line != _added_lines.end (); ++line) { _file.append (*line); } _added_lines.clear (); _file.close (); } } else { // TODO _file.truncate (); // TODO only write out _tasks, because any deltas have already been applied. // TODO append _added_lines. } _dirty = false; } // --------------------------- old implementation ------------------------- /* // Load the lowest form, to allow if (_dirty) { load_contents (); if (_modified_tasks.size ()) { std::map <std::string, Task> modified; std::vector <Task>::iterator it; for (it = _modified_tasks.begin (); it != _modified_tasks.end (); ++it) modified[it->get ("uuid")] = *it; // for (it = _ _modified_tasks.clear (); } if (_added_tasks.size ()) { std::vector <Task>::iterator it; for (it = _added_tasks.begin (); it != _added_tasks.end (); ++it) _lines.push_back (it->composeF4 ()); _added_tasks.clear (); } if (_added_lines.size ()) { //_lines += _added_lines; _added_lines.clear (); } // TODO This clobbers minimal case. _contents = ""; // TODO Verify no resize. join (_contents, "\n", _lines); _file.write (_contents); _dirty = false; } */ } //////////////////////////////////////////////////////////////////////////////// void TF2::load_tasks () { // std::cout << "# TF2::load_tasks " << _file.data << "\n"; if (! _loaded_lines) load_lines (); int id = 1; int line_number = 0; try { std::vector <std::string>::iterator i; for (i = _lines.begin (); i != _lines.end (); ++i) { ++line_number; Task task (*i); // Only set an ID for live tasks. Task::status status = task.getStatus (); if (status != Task::deleted && status != Task::completed) task.id = id++; _tasks.push_back (task); // Maintain mapping for ease of link/dependency resolution. // Note that this mapping is not restricted by the filter, and is // therefore a complete set. if (task.id) { _I2U[task.id] = task.get ("uuid"); _U2I[task.get ("uuid")] = task.id; } } _loaded_tasks = true; } catch (std::string& e) { throw e + format (" in {1} at line {2}", _file.data, line_number); } } //////////////////////////////////////////////////////////////////////////////// void TF2::load_lines () { // std::cout << "# TF2::load_lines " << _file.data << "\n"; if (! _loaded_contents) load_contents (); split_minimal (_lines, _contents, '\n'); _loaded_lines = true; } //////////////////////////////////////////////////////////////////////////////// void TF2::load_contents () { // std::cout << "# TF2::load_contents " << _file.data << "\n"; _contents = ""; if (_file.open ()) { if (context.config.getBoolean ("locking")) _file.lock (); _file.read (_contents); _loaded_contents = true; } // TODO Error handling? } //////////////////////////////////////////////////////////////////////////////// std::string TF2::uuid (int id) { if (! _loaded_tasks) load_tasks (); std::map <int, std::string>::const_iterator i; if ((i = _I2U.find (id)) != _I2U.end ()) return i->second; return ""; } //////////////////////////////////////////////////////////////////////////////// int TF2::id (const std::string& uuid) { if (! _loaded_tasks) load_tasks (); std::map <std::string, int>::const_iterator i; if ((i = _U2I.find (uuid)) != _U2I.end ()) return i->second; return 0; } //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// TDB2::TDB2 () : _location ("") , _id (1) { } //////////////////////////////////////////////////////////////////////////////// // Deliberately no file writes on destruct. TDB2::commit should have been // already called, if data is to be preserved. TDB2::~TDB2 () { } //////////////////////////////////////////////////////////////////////////////// // Once a location is known, the files can be set up. Note that they are not // read. void TDB2::set_location (const std::string& location) { // std::cout << "# TDB2::set_location " << location << "\n"; _location = location; pending.target (location + "/pending.data"); completed.target (location + "/completed.data"); undo.target (location + "/undo.data"); backlog.target (location + "/backlog.data"); synch_key.target (location + "/synch.key"); } //////////////////////////////////////////////////////////////////////////////// // Add the new task to the appropriate file. void TDB2::add (const Task& task) { // std::cout << "# TDB2::add\n"; std::string status = task.get ("status"); if (status == "completed" || status == "deleted") completed.add_task (task); else pending.add_task (task); backlog.add_task (task); } //////////////////////////////////////////////////////////////////////////////// void TDB2::modify (const Task& task) { // std::cout << "# TDB2::modify\n"; std::string status = task.get ("status"); if (status == "completed" || status == "deleted") completed.modify_task (task); else pending.modify_task (task); backlog.modify_task (task); } //////////////////////////////////////////////////////////////////////////////// void TDB2::commit () { dump (); // std::cout << "# TDB2::commit\n"; pending.commit (); completed.commit (); undo.commit (); backlog.commit (); synch_key.commit (); dump (); } //////////////////////////////////////////////////////////////////////////////// // Scans the pending tasks for any that are completed or deleted, and if so, // moves them to the completed.data file. Returns a count of tasks moved. // Now reverts expired waiting tasks to pending. // Now cleans up dangling dependencies. int TDB2::gc () { // std::cout << "# TDB2::gc\n"; /* pending.load_tasks completed.load_tasks for each pending if status == completed || status == deleted pending.remove completed.add if status == waiting && wait < now status = pending wait.clear for each completed if status == pending || status == waiting completed.remove pending.add */ // TODO Remove dangling dependencies // TODO Wake up expired waiting tasks return 0; } //////////////////////////////////////////////////////////////////////////////// // Next ID is that of the last pending task plus one. int TDB2::next_id () { if (! pending._loaded_tasks) pending.load_tasks (); _id = pending._tasks.back ().id + 1; return _id++; } //////////////////////////////////////////////////////////////////////////////// // // File RW State Tasks + - ~ lines + - Bytes // -------------- -- ----- ----- - - - ----- - - ----- // pending.data rw clean 123t +2t -1t ~1t // completed.data rw clean 123t +2t ~1t // undo.data rw clean 123t +2t ~1t // backlog.data rw clean 123t +2t ~1t // synch-key.data rw clean 123b // void TDB2::dump () { if (context.config.getBoolean ("debug")) { ViewText view; view.width (context.getWidth ()); view.add (Column::factory ("string", "File")); view.add (Column::factory ("string.right", "RW")); view.add (Column::factory ("string.right", "State")); view.add (Column::factory ("string.right", "Tasks")); view.add (Column::factory ("string.right", "+")); view.add (Column::factory ("string.right", "~")); view.add (Column::factory ("string.right", "Lines")); view.add (Column::factory ("string.right", "+")); view.add (Column::factory ("string.right", "Bytes")); dump_file (view, "pending.data", pending); dump_file (view, "completed.data", completed); dump_file (view, "undo.data", undo); dump_file (view, "backlog.data", backlog); dump_file (view, "synch_key.data", synch_key); context.debug (view.render ()); } } //////////////////////////////////////////////////////////////////////////////// void TDB2::dump_file (ViewText& view, const std::string& label, TF2& tf) { int row = view.addRow (); view.set (row, 0, label); view.set (row, 1, std::string (tf._file.readable () ? "r" : "-") + std::string (tf._file.writable () ? "w" : "-")); view.set (row, 2, tf._dirty ? "dirty" : "clean"); view.set (row, 3, tf._loaded_tasks ? (format ((int)tf._tasks.size ())) : "-"); view.set (row, 4, (int)tf._added_tasks.size ()); view.set (row, 5, (int)tf._modified_tasks.size ()); view.set (row, 6, tf._loaded_lines ? (format ((int)tf._lines.size ())) : "-"); view.set (row, 7, (int)tf._added_lines.size ()); view.set (row, 8, tf._loaded_contents ? (format ((int)tf._contents.size ())) : "-"); } //////////////////////////////////////////////////////////////////////////////// <commit_msg>TDB2 - Timing<commit_after>//////////////////////////////////////////////////////////////////////////////// // taskwarrior - a command line task list manager. // // Copyright 2006 - 2011, Paul Beckingham, Federico Hernandez. // All rights reserved. // // 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 <iostream> // TODO Remove. #include <Context.h> #include <Timer.h> #include <text.h> #include <TDB2.h> extern Context context; //////////////////////////////////////////////////////////////////////////////// TF2::TF2 () : _read_only (false) , _dirty (false) , _loaded_tasks (false) , _loaded_lines (false) , _loaded_contents (false) , _contents ("") { } //////////////////////////////////////////////////////////////////////////////// TF2::~TF2 () { } //////////////////////////////////////////////////////////////////////////////// void TF2::target (const std::string& f) { _file = File (f); _read_only = ! _file.writable (); // std::cout << "# TF2::target " << f << "\n"; } //////////////////////////////////////////////////////////////////////////////// const std::vector <Task>& TF2::get_tasks () { // std::cout << "# TF2::get_tasks " << _file.data << "\n"; Timer timer ("TF2::get_tasks " + _file.data); if (! _loaded_tasks) load_tasks (); return _tasks; } //////////////////////////////////////////////////////////////////////////////// const std::vector <std::string>& TF2::get_lines () { // std::cout << "# TF2::get_lines " << _file.data << "\n"; if (! _loaded_lines) load_lines (); return _lines; } //////////////////////////////////////////////////////////////////////////////// const std::string& TF2::get_contents () { // std::cout << "# TF2::get_contents " << _file.data << "\n"; if (! _loaded_contents) load_contents (); return _contents; } //////////////////////////////////////////////////////////////////////////////// void TF2::add_task (const Task& task) { // std::cout << "# TF2::add_task " << _file.data << "\n"; _tasks.push_back (task); // For subsequent queries _added_tasks.push_back (task); // For commit/synch _dirty = true; } //////////////////////////////////////////////////////////////////////////////// void TF2::modify_task (const Task& task) { // std::cout << "# TF2::modify_task " << _file.data << "\n"; // Modify in-place. std::vector <Task>::iterator i; for (i = _tasks.begin (); i != _tasks.end (); ++i) { if (i->get ("uuid") == task.get ("uuid")) { *i = task; break; } } _modified_tasks.push_back (task); _dirty = true; } //////////////////////////////////////////////////////////////////////////////// void TF2::add_line (const std::string& line) { // std::cout << "# TF2::add_line " << _file.data << "\n"; _added_lines.push_back (line); _dirty = true; } //////////////////////////////////////////////////////////////////////////////// // This is so that synch.key can just overwrite and not grow. void TF2::clear_lines () { // std::cout << "# TF2::clear_lines " << _file.data << "\n"; _lines.clear (); _dirty = true; } //////////////////////////////////////////////////////////////////////////////// // Top-down recomposition. void TF2::commit () { // std::cout << "# TF2::commit " << _file.data << "\n"; // The _dirty flag indicates that the file needs to be written. if (_dirty) { // Special case: added but no modified means just append to the file. if (!_modified_tasks.size () && (_added_tasks.size () || _added_lines.size ())) { if (_file.open ()) { if (context.config.getBoolean ("locking")) _file.lock (); // Write out all the added tasks. std::vector <Task>::iterator task; for (task = _added_tasks.begin (); task != _added_tasks.end (); ++task) { _file.append (task->composeF4 ()); } _added_tasks.clear (); // Write out all the added lines. std::vector <std::string>::iterator line; for (line = _added_lines.begin (); line != _added_lines.end (); ++line) { _file.append (*line); } _added_lines.clear (); _file.close (); } } else { // TODO _file.truncate (); // TODO only write out _tasks, because any deltas have already been applied. // TODO append _added_lines. } _dirty = false; } // --------------------------- old implementation ------------------------- /* // Load the lowest form, to allow if (_dirty) { load_contents (); if (_modified_tasks.size ()) { std::map <std::string, Task> modified; std::vector <Task>::iterator it; for (it = _modified_tasks.begin (); it != _modified_tasks.end (); ++it) modified[it->get ("uuid")] = *it; // for (it = _ _modified_tasks.clear (); } if (_added_tasks.size ()) { std::vector <Task>::iterator it; for (it = _added_tasks.begin (); it != _added_tasks.end (); ++it) _lines.push_back (it->composeF4 ()); _added_tasks.clear (); } if (_added_lines.size ()) { //_lines += _added_lines; _added_lines.clear (); } // TODO This clobbers minimal case. _contents = ""; // TODO Verify no resize. join (_contents, "\n", _lines); _file.write (_contents); _dirty = false; } */ } //////////////////////////////////////////////////////////////////////////////// void TF2::load_tasks () { // std::cout << "# TF2::load_tasks " << _file.data << "\n"; if (! _loaded_lines) load_lines (); int id = 1; int line_number = 0; try { std::vector <std::string>::iterator i; for (i = _lines.begin (); i != _lines.end (); ++i) { ++line_number; Task task (*i); // Only set an ID for live tasks. Task::status status = task.getStatus (); if (status != Task::deleted && status != Task::completed) task.id = id++; _tasks.push_back (task); // Maintain mapping for ease of link/dependency resolution. // Note that this mapping is not restricted by the filter, and is // therefore a complete set. if (task.id) { _I2U[task.id] = task.get ("uuid"); _U2I[task.get ("uuid")] = task.id; } } _loaded_tasks = true; } catch (std::string& e) { throw e + format (" in {1} at line {2}", _file.data, line_number); } } //////////////////////////////////////////////////////////////////////////////// void TF2::load_lines () { // std::cout << "# TF2::load_lines " << _file.data << "\n"; if (! _loaded_contents) load_contents (); split_minimal (_lines, _contents, '\n'); _loaded_lines = true; } //////////////////////////////////////////////////////////////////////////////// void TF2::load_contents () { // std::cout << "# TF2::load_contents " << _file.data << "\n"; _contents = ""; if (_file.open ()) { if (context.config.getBoolean ("locking")) _file.lock (); _file.read (_contents); _loaded_contents = true; } // TODO Error handling? } //////////////////////////////////////////////////////////////////////////////// std::string TF2::uuid (int id) { if (! _loaded_tasks) load_tasks (); std::map <int, std::string>::const_iterator i; if ((i = _I2U.find (id)) != _I2U.end ()) return i->second; return ""; } //////////////////////////////////////////////////////////////////////////////// int TF2::id (const std::string& uuid) { if (! _loaded_tasks) load_tasks (); std::map <std::string, int>::const_iterator i; if ((i = _U2I.find (uuid)) != _U2I.end ()) return i->second; return 0; } //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// TDB2::TDB2 () : _location ("") , _id (1) { } //////////////////////////////////////////////////////////////////////////////// // Deliberately no file writes on destruct. TDB2::commit should have been // already called, if data is to be preserved. TDB2::~TDB2 () { } //////////////////////////////////////////////////////////////////////////////// // Once a location is known, the files can be set up. Note that they are not // read. void TDB2::set_location (const std::string& location) { // std::cout << "# TDB2::set_location " << location << "\n"; _location = location; pending.target (location + "/pending.data"); completed.target (location + "/completed.data"); undo.target (location + "/undo.data"); backlog.target (location + "/backlog.data"); synch_key.target (location + "/synch.key"); } //////////////////////////////////////////////////////////////////////////////// // Add the new task to the appropriate file. void TDB2::add (const Task& task) { // std::cout << "# TDB2::add\n"; std::string status = task.get ("status"); if (status == "completed" || status == "deleted") completed.add_task (task); else pending.add_task (task); backlog.add_task (task); } //////////////////////////////////////////////////////////////////////////////// void TDB2::modify (const Task& task) { // std::cout << "# TDB2::modify\n"; std::string status = task.get ("status"); if (status == "completed" || status == "deleted") completed.modify_task (task); else pending.modify_task (task); backlog.modify_task (task); } //////////////////////////////////////////////////////////////////////////////// void TDB2::commit () { dump (); Timer timer ("TDB2::commit"); pending.commit (); completed.commit (); undo.commit (); backlog.commit (); synch_key.commit (); dump (); } //////////////////////////////////////////////////////////////////////////////// // Scans the pending tasks for any that are completed or deleted, and if so, // moves them to the completed.data file. Returns a count of tasks moved. // Now reverts expired waiting tasks to pending. // Now cleans up dangling dependencies. int TDB2::gc () { Timer timer ("TDB2::gc"); /* pending.load_tasks completed.load_tasks for each pending if status == completed || status == deleted pending.remove completed.add if status == waiting && wait < now status = pending wait.clear for each completed if status == pending || status == waiting completed.remove pending.add */ // TODO Remove dangling dependencies // TODO Wake up expired waiting tasks return 0; } //////////////////////////////////////////////////////////////////////////////// // Next ID is that of the last pending task plus one. int TDB2::next_id () { if (! pending._loaded_tasks) pending.load_tasks (); _id = pending._tasks.back ().id + 1; return _id++; } //////////////////////////////////////////////////////////////////////////////// // // File RW State Tasks + - ~ lines + - Bytes // -------------- -- ----- ----- - - - ----- - - ----- // pending.data rw clean 123t +2t -1t ~1t // completed.data rw clean 123t +2t ~1t // undo.data rw clean 123t +2t ~1t // backlog.data rw clean 123t +2t ~1t // synch-key.data rw clean 123b // void TDB2::dump () { if (context.config.getBoolean ("debug")) { ViewText view; view.width (context.getWidth ()); view.add (Column::factory ("string", "File")); view.add (Column::factory ("string.right", "RW")); view.add (Column::factory ("string.right", "State")); view.add (Column::factory ("string.right", "Tasks")); view.add (Column::factory ("string.right", "+")); view.add (Column::factory ("string.right", "~")); view.add (Column::factory ("string.right", "Lines")); view.add (Column::factory ("string.right", "+")); view.add (Column::factory ("string.right", "Bytes")); dump_file (view, "pending.data", pending); dump_file (view, "completed.data", completed); dump_file (view, "undo.data", undo); dump_file (view, "backlog.data", backlog); dump_file (view, "synch_key.data", synch_key); context.debug (view.render ()); } } //////////////////////////////////////////////////////////////////////////////// void TDB2::dump_file (ViewText& view, const std::string& label, TF2& tf) { int row = view.addRow (); view.set (row, 0, label); view.set (row, 1, std::string (tf._file.readable () ? "r" : "-") + std::string (tf._file.writable () ? "w" : "-")); view.set (row, 2, tf._dirty ? "dirty" : "clean"); view.set (row, 3, tf._loaded_tasks ? (format ((int)tf._tasks.size ())) : "-"); view.set (row, 4, (int)tf._added_tasks.size ()); view.set (row, 5, (int)tf._modified_tasks.size ()); view.set (row, 6, tf._loaded_lines ? (format ((int)tf._lines.size ())) : "-"); view.set (row, 7, (int)tf._added_lines.size ()); view.set (row, 8, tf._loaded_contents ? (format ((int)tf._contents.size ())) : "-"); } //////////////////////////////////////////////////////////////////////////////// <|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 Assistant 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 "qhelpprojectdata_p.h" #include <QtCore/QCoreApplication> #include <QtCore/QDir> #include <QtCore/QFileInfo> #include <QtCore/QStack> #include <QtCore/QMap> #include <QtCore/QRegExp> #include <QtCore/QVariant> #include <QtXml/QXmlStreamReader> QT_BEGIN_NAMESPACE class QHelpProjectDataPrivate : public QXmlStreamReader { public: void readData(const QByteArray &contents); QString virtualFolder; QString namespaceName; QString rootPath; QStringList fileList; QList<QHelpDataCustomFilter> customFilterList; QList<QHelpDataFilterSection> filterSectionList; QMap<QString, QVariant> metaData; QString errorMsg; private: void readProject(); void readCustomFilter(); void readFilterSection(); void readTOC(); void readKeywords(); void readFiles(); void raiseUnknownTokenError(); void addMatchingFiles(const QString &pattern); QMap<QString, QStringList> dirEntriesCache; }; void QHelpProjectDataPrivate::raiseUnknownTokenError() { raiseError(QCoreApplication::translate("QHelpProject", "Unknown token.")); } void QHelpProjectDataPrivate::readData(const QByteArray &contents) { addData(contents); while (!atEnd()) { readNext(); if (isStartElement()) { if (name() == QLatin1String("QtHelpProject") && attributes().value(QLatin1String("version")) == QLatin1String("1.0")) readProject(); else raiseError(QCoreApplication::translate("QHelpProject", "Unknown token. Expected \"QtHelpProject\"!")); } } if (hasError()) { raiseError(QCoreApplication::translate("QHelpProject", "Error in line %1: %2").arg(lineNumber()) .arg(errorString())); } } void QHelpProjectDataPrivate::readProject() { while (!atEnd()) { readNext(); if (isStartElement()) { if (name() == QLatin1String("virtualFolder")) { virtualFolder = readElementText(); if (virtualFolder.contains(QLatin1String("/"))) raiseError(QCoreApplication::translate("QHelpProject", "A virtual folder must not contain " "a \'/\' character!")); } else if (name() == QLatin1String("namespace")) { namespaceName = readElementText(); if (namespaceName.contains(QLatin1String("/"))) raiseError(QCoreApplication::translate("QHelpProject", "A namespace must not contain a " "\'/\' character!")); } else if (name() == QLatin1String("customFilter")) { readCustomFilter(); } else if (name() == QLatin1String("filterSection")) { readFilterSection(); } else if (name() == QLatin1String("metaData")) { QString n = attributes().value(QLatin1String("name")).toString(); if (!metaData.contains(n)) metaData[n] = attributes().value(QLatin1String("value")).toString(); else metaData.insert(n, attributes(). value(QLatin1String("value")).toString()); } else { raiseUnknownTokenError(); } } else if (isEndElement() && name() == QLatin1String("QtHelpProject")) { if (namespaceName.isEmpty()) raiseError(QCoreApplication::translate("QHelpProject", "Missing namespace in QtHelpProject.")); else if (virtualFolder.isEmpty()) raiseError(QCoreApplication::translate("QHelpProject", "Missing virtual folder in QtHelpProject")); break; } } } void QHelpProjectDataPrivate::readCustomFilter() { QHelpDataCustomFilter filter; filter.name = attributes().value(QLatin1String("name")).toString(); while (!atEnd()) { readNext(); if (isStartElement()) { if (name() == QLatin1String("filterAttribute")) filter.filterAttributes.append(readElementText()); else raiseUnknownTokenError(); } else if (isEndElement() && name() == QLatin1String("customFilter")) { break; } } customFilterList.append(filter); } void QHelpProjectDataPrivate::readFilterSection() { filterSectionList.append(QHelpDataFilterSection()); while (!atEnd()) { readNext(); if (isStartElement()) { if (name() == QLatin1String("filterAttribute")) filterSectionList.last().addFilterAttribute(readElementText()); else if (name() == QLatin1String("toc")) readTOC(); else if (name() == QLatin1String("keywords")) readKeywords(); else if (name() == QLatin1String("files")) readFiles(); else raiseUnknownTokenError(); } else if (isEndElement() && name() == QLatin1String("filterSection")) { break; } } } void QHelpProjectDataPrivate::readTOC() { QStack<QHelpDataContentItem*> contentStack; QHelpDataContentItem *itm = 0; while (!atEnd()) { readNext(); if (isStartElement()) { if (name() == QLatin1String("section")) { QString title = attributes().value(QLatin1String("title")).toString(); QString ref = attributes().value(QLatin1String("ref")).toString(); if (contentStack.isEmpty()) { itm = new QHelpDataContentItem(0, title, ref); filterSectionList.last().addContent(itm); } else { itm = new QHelpDataContentItem(contentStack.top(), title, ref); } contentStack.push(itm); } else { raiseUnknownTokenError(); } } else if (isEndElement()) { if (name() == QLatin1String("section")) { contentStack.pop(); continue; } else if (name() == QLatin1String("toc") && contentStack.isEmpty()) { break; } else { raiseUnknownTokenError(); } } } } void QHelpProjectDataPrivate::readKeywords() { while (!atEnd()) { readNext(); if (isStartElement()) { if (name() == QLatin1String("keyword")) { if (attributes().value(QLatin1String("ref")).toString().isEmpty() || (attributes().value(QLatin1String("name")).toString().isEmpty() && attributes().value(QLatin1String("id")).toString().isEmpty())) raiseError(QCoreApplication::translate("QHelpProject", "Missing attribute in keyword at line %1.") .arg(lineNumber())); filterSectionList.last() .addIndex(QHelpDataIndexItem(attributes(). value(QLatin1String("name")).toString(), attributes().value(QLatin1String("id")).toString(), attributes().value(QLatin1String("ref")).toString())); } else { raiseUnknownTokenError(); } } else if (isEndElement()) { if (name() == QLatin1String("keyword")) continue; else if (name() == QLatin1String("keywords")) break; else raiseUnknownTokenError(); } } } void QHelpProjectDataPrivate::readFiles() { while (!atEnd()) { readNext(); if (isStartElement()) { if (name() == QLatin1String("file")) addMatchingFiles(readElementText()); else raiseUnknownTokenError(); } else if (isEndElement()) { if (name() == QLatin1String("file")) continue; else if (name() == QLatin1String("files")) break; else raiseUnknownTokenError(); } } } // Expand file pattern and add matches into list. If the pattern does not match // any files, insert the pattern itself so the QHelpGenerator will emit a // meaningful warning later. void QHelpProjectDataPrivate::addMatchingFiles(const QString &pattern) { // The pattern matching is expensive, so we skip it if no // wildcard symbols occur in the string. if (!pattern.contains('?') && !pattern.contains('*') && !pattern.contains('[') && !pattern.contains(']')) { filterSectionList.last().addFile(pattern); return; } QFileInfo fileInfo(rootPath + '/' + pattern); const QDir &dir = fileInfo.dir(); const QString &path = dir.canonicalPath(); // QDir::entryList() is expensive, so we cache the results. QMap<QString, QStringList>::ConstIterator it = dirEntriesCache.find(path); const QStringList &entries = it != dirEntriesCache.constEnd() ? it.value() : dir.entryList(QDir::Files); if (it == dirEntriesCache.constEnd()) dirEntriesCache.insert(path, entries); bool matchFound = false; #ifdef Q_OS_WIN Qt::CaseSensitivity cs = Qt::CaseInsensitive; #else Qt::CaseSensitivity cs = Qt::CaseSensitive; #endif QRegExp regExp(fileInfo.fileName(), cs, QRegExp::Wildcard); foreach (const QString &file, entries) { if (regExp.exactMatch(file)) { matchFound = true; filterSectionList.last(). addFile(QFileInfo(pattern).dir().path() + '/' + file); } } if (!matchFound) filterSectionList.last().addFile(pattern); } /*! \internal \class QHelpProjectData \since 4.4 \brief The QHelpProjectData class stores all information found in a Qt help project file. The structure is filled with data by calling readData(). The specified file has to have the Qt help project file format in order to be read successfully. Possible reading errors can be retrieved by calling errorMessage(). */ /*! Constructs a Qt help project data structure. */ QHelpProjectData::QHelpProjectData() { d = new QHelpProjectDataPrivate; } /*! Destroys the help project data. */ QHelpProjectData::~QHelpProjectData() { delete d; } /*! Reads the file \a fileName and stores the help data. The file has to have the Qt help project file format. Returns true if the file was successfully read, otherwise false. \sa errorMessage() */ bool QHelpProjectData::readData(const QString &fileName) { d->rootPath = QFileInfo(fileName).absolutePath(); QFile file(fileName); if (!file.open(QIODevice::ReadOnly)) { d->errorMsg = QCoreApplication::translate("QHelpProject", "The input file %1 could not be opened!").arg(fileName); return false; } d->readData(file.readAll()); return !d->hasError(); } /*! Returns an error message if the reading of the Qt help project file failed. Otherwise, an empty QString is returned. \sa readData() */ QString QHelpProjectData::errorMessage() const { if (d->hasError()) return d->errorString(); return d->errorMsg; } /*! \internal */ QString QHelpProjectData::namespaceName() const { return d->namespaceName; } /*! \internal */ QString QHelpProjectData::virtualFolder() const { return d->virtualFolder; } /*! \internal */ QList<QHelpDataCustomFilter> QHelpProjectData::customFilters() const { return d->customFilterList; } /*! \internal */ QList<QHelpDataFilterSection> QHelpProjectData::filterSections() const { return d->filterSectionList; } /*! \internal */ QMap<QString, QVariant> QHelpProjectData::metaData() const { return d->metaData; } /*! \internal */ QString QHelpProjectData::rootPath() const { return d->rootPath; } QT_END_NAMESPACE <commit_msg>Assistant: Check namespace and virtual folder syntax of help projects.<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 Assistant 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 "qhelpprojectdata_p.h" #include <QtCore/QCoreApplication> #include <QtCore/QDir> #include <QtCore/QFileInfo> #include <QtCore/QStack> #include <QtCore/QMap> #include <QtCore/QRegExp> #include <QtCore/QUrl> #include <QtCore/QVariant> #include <QtXml/QXmlStreamReader> QT_BEGIN_NAMESPACE class QHelpProjectDataPrivate : public QXmlStreamReader { public: void readData(const QByteArray &contents); QString virtualFolder; QString namespaceName; QString rootPath; QStringList fileList; QList<QHelpDataCustomFilter> customFilterList; QList<QHelpDataFilterSection> filterSectionList; QMap<QString, QVariant> metaData; QString errorMsg; private: void readProject(); void readCustomFilter(); void readFilterSection(); void readTOC(); void readKeywords(); void readFiles(); void raiseUnknownTokenError(); void addMatchingFiles(const QString &pattern); bool hasValidSyntax(const QString &nameSpace, const QString &vFolder) const; QMap<QString, QStringList> dirEntriesCache; }; void QHelpProjectDataPrivate::raiseUnknownTokenError() { raiseError(QCoreApplication::translate("QHelpProject", "Unknown token.")); } void QHelpProjectDataPrivate::readData(const QByteArray &contents) { addData(contents); while (!atEnd()) { readNext(); if (isStartElement()) { if (name() == QLatin1String("QtHelpProject") && attributes().value(QLatin1String("version")) == QLatin1String("1.0")) readProject(); else raiseError(QCoreApplication::translate("QHelpProject", "Unknown token. Expected \"QtHelpProject\"!")); } } if (hasError()) { raiseError(QCoreApplication::translate("QHelpProject", "Error in line %1: %2").arg(lineNumber()) .arg(errorString())); } } void QHelpProjectDataPrivate::readProject() { while (!atEnd()) { readNext(); if (isStartElement()) { if (name() == QLatin1String("virtualFolder")) { virtualFolder = readElementText(); if (!hasValidSyntax(QLatin1String("test"), virtualFolder)) raiseError(QCoreApplication::translate("QHelpProject", "Virtual folder has invalid syntax.")); } else if (name() == QLatin1String("namespace")) { namespaceName = readElementText(); if (!hasValidSyntax(namespaceName, QLatin1String("test"))) raiseError(QCoreApplication::translate("QHelpProject", "Namespace has invalid syntax.")); } else if (name() == QLatin1String("customFilter")) { readCustomFilter(); } else if (name() == QLatin1String("filterSection")) { readFilterSection(); } else if (name() == QLatin1String("metaData")) { QString n = attributes().value(QLatin1String("name")).toString(); if (!metaData.contains(n)) metaData[n] = attributes().value(QLatin1String("value")).toString(); else metaData.insert(n, attributes(). value(QLatin1String("value")).toString()); } else { raiseUnknownTokenError(); } } else if (isEndElement() && name() == QLatin1String("QtHelpProject")) { if (namespaceName.isEmpty()) raiseError(QCoreApplication::translate("QHelpProject", "Missing namespace in QtHelpProject.")); else if (virtualFolder.isEmpty()) raiseError(QCoreApplication::translate("QHelpProject", "Missing virtual folder in QtHelpProject")); break; } } } void QHelpProjectDataPrivate::readCustomFilter() { QHelpDataCustomFilter filter; filter.name = attributes().value(QLatin1String("name")).toString(); while (!atEnd()) { readNext(); if (isStartElement()) { if (name() == QLatin1String("filterAttribute")) filter.filterAttributes.append(readElementText()); else raiseUnknownTokenError(); } else if (isEndElement() && name() == QLatin1String("customFilter")) { break; } } customFilterList.append(filter); } void QHelpProjectDataPrivate::readFilterSection() { filterSectionList.append(QHelpDataFilterSection()); while (!atEnd()) { readNext(); if (isStartElement()) { if (name() == QLatin1String("filterAttribute")) filterSectionList.last().addFilterAttribute(readElementText()); else if (name() == QLatin1String("toc")) readTOC(); else if (name() == QLatin1String("keywords")) readKeywords(); else if (name() == QLatin1String("files")) readFiles(); else raiseUnknownTokenError(); } else if (isEndElement() && name() == QLatin1String("filterSection")) { break; } } } void QHelpProjectDataPrivate::readTOC() { QStack<QHelpDataContentItem*> contentStack; QHelpDataContentItem *itm = 0; while (!atEnd()) { readNext(); if (isStartElement()) { if (name() == QLatin1String("section")) { QString title = attributes().value(QLatin1String("title")).toString(); QString ref = attributes().value(QLatin1String("ref")).toString(); if (contentStack.isEmpty()) { itm = new QHelpDataContentItem(0, title, ref); filterSectionList.last().addContent(itm); } else { itm = new QHelpDataContentItem(contentStack.top(), title, ref); } contentStack.push(itm); } else { raiseUnknownTokenError(); } } else if (isEndElement()) { if (name() == QLatin1String("section")) { contentStack.pop(); continue; } else if (name() == QLatin1String("toc") && contentStack.isEmpty()) { break; } else { raiseUnknownTokenError(); } } } } void QHelpProjectDataPrivate::readKeywords() { while (!atEnd()) { readNext(); if (isStartElement()) { if (name() == QLatin1String("keyword")) { if (attributes().value(QLatin1String("ref")).toString().isEmpty() || (attributes().value(QLatin1String("name")).toString().isEmpty() && attributes().value(QLatin1String("id")).toString().isEmpty())) raiseError(QCoreApplication::translate("QHelpProject", "Missing attribute in keyword at line %1.") .arg(lineNumber())); filterSectionList.last() .addIndex(QHelpDataIndexItem(attributes(). value(QLatin1String("name")).toString(), attributes().value(QLatin1String("id")).toString(), attributes().value(QLatin1String("ref")).toString())); } else { raiseUnknownTokenError(); } } else if (isEndElement()) { if (name() == QLatin1String("keyword")) continue; else if (name() == QLatin1String("keywords")) break; else raiseUnknownTokenError(); } } } void QHelpProjectDataPrivate::readFiles() { while (!atEnd()) { readNext(); if (isStartElement()) { if (name() == QLatin1String("file")) addMatchingFiles(readElementText()); else raiseUnknownTokenError(); } else if (isEndElement()) { if (name() == QLatin1String("file")) continue; else if (name() == QLatin1String("files")) break; else raiseUnknownTokenError(); } } } // Expand file pattern and add matches into list. If the pattern does not match // any files, insert the pattern itself so the QHelpGenerator will emit a // meaningful warning later. void QHelpProjectDataPrivate::addMatchingFiles(const QString &pattern) { // The pattern matching is expensive, so we skip it if no // wildcard symbols occur in the string. if (!pattern.contains('?') && !pattern.contains('*') && !pattern.contains('[') && !pattern.contains(']')) { filterSectionList.last().addFile(pattern); return; } QFileInfo fileInfo(rootPath + '/' + pattern); const QDir &dir = fileInfo.dir(); const QString &path = dir.canonicalPath(); // QDir::entryList() is expensive, so we cache the results. QMap<QString, QStringList>::ConstIterator it = dirEntriesCache.find(path); const QStringList &entries = it != dirEntriesCache.constEnd() ? it.value() : dir.entryList(QDir::Files); if (it == dirEntriesCache.constEnd()) dirEntriesCache.insert(path, entries); bool matchFound = false; #ifdef Q_OS_WIN Qt::CaseSensitivity cs = Qt::CaseInsensitive; #else Qt::CaseSensitivity cs = Qt::CaseSensitive; #endif QRegExp regExp(fileInfo.fileName(), cs, QRegExp::Wildcard); foreach (const QString &file, entries) { if (regExp.exactMatch(file)) { matchFound = true; filterSectionList.last(). addFile(QFileInfo(pattern).dir().path() + '/' + file); } } if (!matchFound) filterSectionList.last().addFile(pattern); } bool QHelpProjectDataPrivate::hasValidSyntax(const QString &nameSpace, const QString &vFolder) const { const QLatin1Char slash('/'); if (nameSpace.contains(slash) || vFolder.contains(slash)) return false; QUrl url; const QLatin1String scheme("qthelp"); url.setScheme(scheme); url.setHost(nameSpace); url.setPath(vFolder); const QString expectedUrl(scheme + QLatin1String("://") + nameSpace + slash + vFolder); return url.isValid() && url.toString() == expectedUrl; } /*! \internal \class QHelpProjectData \since 4.4 \brief The QHelpProjectData class stores all information found in a Qt help project file. The structure is filled with data by calling readData(). The specified file has to have the Qt help project file format in order to be read successfully. Possible reading errors can be retrieved by calling errorMessage(). */ /*! Constructs a Qt help project data structure. */ QHelpProjectData::QHelpProjectData() { d = new QHelpProjectDataPrivate; } /*! Destroys the help project data. */ QHelpProjectData::~QHelpProjectData() { delete d; } /*! Reads the file \a fileName and stores the help data. The file has to have the Qt help project file format. Returns true if the file was successfully read, otherwise false. \sa errorMessage() */ bool QHelpProjectData::readData(const QString &fileName) { d->rootPath = QFileInfo(fileName).absolutePath(); QFile file(fileName); if (!file.open(QIODevice::ReadOnly)) { d->errorMsg = QCoreApplication::translate("QHelpProject", "The input file %1 could not be opened!").arg(fileName); return false; } d->readData(file.readAll()); return !d->hasError(); } /*! Returns an error message if the reading of the Qt help project file failed. Otherwise, an empty QString is returned. \sa readData() */ QString QHelpProjectData::errorMessage() const { if (d->hasError()) return d->errorString(); return d->errorMsg; } /*! \internal */ QString QHelpProjectData::namespaceName() const { return d->namespaceName; } /*! \internal */ QString QHelpProjectData::virtualFolder() const { return d->virtualFolder; } /*! \internal */ QList<QHelpDataCustomFilter> QHelpProjectData::customFilters() const { return d->customFilterList; } /*! \internal */ QList<QHelpDataFilterSection> QHelpProjectData::filterSections() const { return d->filterSectionList; } /*! \internal */ QMap<QString, QVariant> QHelpProjectData::metaData() const { return d->metaData; } /*! \internal */ QString QHelpProjectData::rootPath() const { return d->rootPath; } QT_END_NAMESPACE <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: pcrservices.cxx,v $ * * $Revision: 1.1 $ * * last change: $Author: fs $ $Date: 2001-01-12 11:30:30 $ * * 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 EXPRESS 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 _EXTENSIONS_PROPCTRLR_MODULEPRC_HXX_ #include "modulepcr.hxx" #endif //--------------------------------------------------------------------------------------- using namespace ::rtl; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::registry; //--------------------------------------------------------------------------------------- extern "C" void SAL_CALL createRegistryInfo_OPropertyBrowserController(); //--------------------------------------------------------------------------------------- extern "C" void SAL_CALL pcr_createRegistryInfo() { static sal_Bool s_bInit = sal_False; if (!s_bInit) { createRegistryInfo_OPropertyBrowserController(); s_bInit = sal_True; } } //--------------------------------------------------------------------------------------- extern "C" void SAL_CALL component_getImplementationEnvironment( const sal_Char **ppEnvTypeName, uno_Environment **ppEnv ) { pcr_createRegistryInfo(); *ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME; } //--------------------------------------------------------------------------------------- extern "C" sal_Bool SAL_CALL component_writeInfo( void* pServiceManager, void* pRegistryKey ) { if (pRegistryKey) try { return ::pcr::OModule::writeComponentInfos( static_cast<XMultiServiceFactory*>(pServiceManager), static_cast<XRegistryKey*>(pRegistryKey)); } catch (InvalidRegistryException& ) { OSL_ASSERT("pcr::component_writeInfo: could not create a registry key (InvalidRegistryException) !"); } return sal_False; } //--------------------------------------------------------------------------------------- extern "C" void* SAL_CALL component_getFactory( const sal_Char* pImplementationName, void* pServiceManager, void* pRegistryKey) { Reference< XInterface > xRet; if (pServiceManager && pImplementationName) { xRet = ::pcr::OModule::getComponentFactory( ::rtl::OUString::createFromAscii(pImplementationName), static_cast< XMultiServiceFactory* >(pServiceManager)); } if (xRet.is()) xRet->acquire(); return xRet.get(); }; /************************************************************************* * history: * $Log: not supported by cvs2svn $ * * Revision 1.0 11.01.01 09:14:45 fs ************************************************************************/ <commit_msg>#86096# pcr_createRegistryInfo_OControlFontDialog (new service in this module)<commit_after>/************************************************************************* * * $RCSfile: pcrservices.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: fs $ $Date: 2001-06-11 11:33:45 $ * * 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 EXPRESS 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 _EXTENSIONS_PROPCTRLR_MODULEPRC_HXX_ #include "modulepcr.hxx" #endif //--------------------------------------------------------------------------------------- using namespace ::rtl; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::registry; //--------------------------------------------------------------------------------------- extern "C" void SAL_CALL createRegistryInfo_OPropertyBrowserController(); extern "C" void SAL_CALL createRegistryInfo_OControlFontDialog(); //--------------------------------------------------------------------------------------- extern "C" void SAL_CALL dbi_initializeModule() { static sal_Bool s_bInit = sal_False; if (!s_bInit) { createRegistryInfo_OPropertyBrowserController(); createRegistryInfo_OControlFontDialog(); ::pcr::OModule::setResourceFilePrefix("pcr"); s_bInit = sal_True; } } //--------------------------------------------------------------------------------------- extern "C" void SAL_CALL component_getImplementationEnvironment( const sal_Char **ppEnvTypeName, uno_Environment **ppEnv ) { dbi_initializeModule(); *ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME; } //--------------------------------------------------------------------------------------- extern "C" sal_Bool SAL_CALL component_writeInfo( void* pServiceManager, void* pRegistryKey ) { if (pRegistryKey) try { return ::pcr::OModule::writeComponentInfos( static_cast<XMultiServiceFactory*>(pServiceManager), static_cast<XRegistryKey*>(pRegistryKey)); } catch (InvalidRegistryException& ) { OSL_ASSERT("pcr::component_writeInfo: could not create a registry key (InvalidRegistryException) !"); } return sal_False; } //--------------------------------------------------------------------------------------- extern "C" void* SAL_CALL component_getFactory( const sal_Char* pImplementationName, void* pServiceManager, void* pRegistryKey) { Reference< XInterface > xRet; if (pServiceManager && pImplementationName) { xRet = ::pcr::OModule::getComponentFactory( ::rtl::OUString::createFromAscii(pImplementationName), static_cast< XMultiServiceFactory* >(pServiceManager)); } if (xRet.is()) xRet->acquire(); return xRet.get(); }; /************************************************************************* * history: * $Log: not supported by cvs2svn $ * Revision 1.1 2001/01/12 11:30:30 fs * initial checkin - outsourced the form property browser * * * Revision 1.0 11.01.01 09:14:45 fs ************************************************************************/ <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: usercontrol.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2005-09-08 20:32:19 $ * * 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 _EXTENSIONS_PROPCTRLR_USERCONTROL_HXX_ #define _EXTENSIONS_PROPCTRLR_USERCONTROL_HXX_ #ifndef _EXTENSIONS_PROPCTRLR_COMMONCONTROL_HXX_ #include "commoncontrol.hxx" #endif #define _ZFORLIST_DECLARE_TABLE #ifndef _FMTFIELD_HXX_ #include <svtools/fmtfield.hxx> #endif #ifndef SVTOOLS_FILEURLBOX_HXX #include <svtools/fileurlbox.hxx> #endif #ifndef _EXTENSIONS_PROPCTRLR_STANDARDCONTROL_HXX_ #include "standardcontrol.hxx" #endif class SvNumberFormatsSupplierObj; //............................................................................ namespace pcr { //............................................................................ //======================================================================== //= OFormatDescriptionControl //======================================================================== class OFormatDescriptionControl : public OCommonBehaviourControl, FormattedField { protected: virtual long PreNotify( NotifyEvent& rNEvt ); public: OFormatDescriptionControl( Window* pParent, WinBits nWinStyle = WB_TABSTOP); virtual void SetProperty(const ::rtl::OUString &rString,sal_Bool bIsUnknown=sal_False); virtual ::rtl::OUString GetProperty()const; virtual void SetFormatSupplier(const SvNumberFormatsSupplierObj* pSupplier); }; //======================================================================== //= FormatDescription //======================================================================== struct FormatDescription { SvNumberFormatsSupplierObj* pSupplier; sal_Int32 nKey; }; //======================================================================== //= OFormattedNumericControl //======================================================================== class OFormattedNumericControl : public OCommonBehaviourControl, FormattedField { sal_Int32 m_nLastDecimalDigits; protected: virtual long PreNotify( NotifyEvent& rNEvt ); public: OFormattedNumericControl( Window* pParent, WinBits nWinStyle = WB_TABSTOP); ~OFormattedNumericControl(); virtual void SetProperty(const ::rtl::OUString &rString,sal_Bool bIsUnknown=sal_False); virtual ::rtl::OUString GetProperty()const; virtual void SetFormatDescription(const FormatDescription& rDesc); // make some FormattedField methods available virtual void SetDecimalDigits(sal_uInt16 nPrecision) { FormattedField::SetDecimalDigits(nPrecision); m_nLastDecimalDigits = nPrecision; } virtual void SetDefaultValue(double dDef) { FormattedField::SetDefaultValue(dDef); } virtual void EnableEmptyField(sal_Bool bEnable) { FormattedField::EnableEmptyField(bEnable); } virtual void SetThousandsSep(sal_Bool bEnable) { FormattedField::SetThousandsSep(bEnable); } }; //======================================================================== //= OFileUrlControl //======================================================================== typedef ::svt::FileURLBox OFileUrlControl_Base; class OFileUrlControl : public OCommonBehaviourControl, OFileUrlControl_Base { protected: virtual long PreNotify( NotifyEvent& rNEvt ); public: OFileUrlControl( Window* pParent, WinBits nWinStyle = WB_TABSTOP); ~OFileUrlControl(); virtual void SetProperty( const ::rtl::OUString& _rString, sal_Bool bIsUnknown = sal_False ); virtual ::rtl::OUString GetProperty() const; void SetBaseURL( const String& _rURL ) { OFileUrlControl_Base::SetBaseURL( _rURL ); } }; //======================================================================== //= TimeDurationInput //======================================================================== class TimeDurationInput : public ONumericControl { public: TimeDurationInput( ::Window* pParent, WinBits nWinStyle = WB_TABSTOP); ~TimeDurationInput(); protected: virtual void CustomConvert(); }; //............................................................................ } // namespace pcr //............................................................................ #endif // _EXTENSIONS_PROPCTRLR_USERCONTROL_HXX_ <commit_msg>INTEGRATION: CWS pbrwuno (1.3.294); FILE MERGED 2005/10/05 07:14:42 fs 1.3.294.3: RESYNC: (1.3-1.4); FILE MERGED 2005/09/05 07:41:56 fs 1.3.294.2: #i53095# phase 3, part 1: introduced XPropertyControl and relatives, describing one control in the ObjectInspector, responsible for one property known issues: - rebuildPropertyUI can cause problems now: If the user clicks into the control for property A, which causes property B to be committed, which causes the UI for property A to be rebuilt, then this will crash currently. Reason: rebuildPropertyUI now synchronously replaces the VCL-Window of the rebuilt control, which is exactly the one which is still in some MouseButtonDown-handler. possible solutions: - see if rebuiltPropertyUI can be obsoleted - handlers should be able to just obtain the XPropertyControl from the PropertyUI, and re-initialize the control. Shouldn't they?` - make one of the steps in the chain (mouse-click, handler-call, rebuildPropertyUI-callback) asynchronous. 2005/08/09 14:00:09 fs 1.3.294.1: #i53095# phase 1: - don't use strings to transver values between controls and introspectee, but Anys - first version of a dedicated property handler for form-component-related properties (not yet completed) known regressions over previous phase: - handlers for events not yet implemented, thus some assertions - click handlers for form-component-related properties do not yet work, thus the browse buttons mostly do not work<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: usercontrol.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: vg $ $Date: 2006-03-14 11:34:36 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _EXTENSIONS_PROPCTRLR_USERCONTROL_HXX_ #define _EXTENSIONS_PROPCTRLR_USERCONTROL_HXX_ #ifndef _EXTENSIONS_PROPCTRLR_COMMONCONTROL_HXX_ #include "commoncontrol.hxx" #endif #define _ZFORLIST_DECLARE_TABLE #ifndef _FMTFIELD_HXX_ #include <svtools/fmtfield.hxx> #endif #ifndef SVTOOLS_FILEURLBOX_HXX #include <svtools/fileurlbox.hxx> #endif #ifndef _EXTENSIONS_PROPCTRLR_STANDARDCONTROL_HXX_ #include "standardcontrol.hxx" #endif class SvNumberFormatsSupplierObj; //............................................................................ namespace pcr { //............................................................................ //======================================================================== //= NumberFormatSampleField //======================================================================== class NumberFormatSampleField : public ControlWindow< FormattedField > { private: typedef ControlWindow< FormattedField > BaseClass; public: NumberFormatSampleField( Window* _pParent, WinBits _nStyle ) :BaseClass( _pParent, _nStyle ) { } void SetFormatSupplier( const SvNumberFormatsSupplierObj* pSupplier ); protected: virtual long PreNotify( NotifyEvent& rNEvt ); }; //======================================================================== //= OFormatSampleControl //======================================================================== typedef CommonBehaviourControl< ::com::sun::star::inspection::XPropertyControl, NumberFormatSampleField > OFormatSampleControl_Base; class OFormatSampleControl : public OFormatSampleControl_Base { public: OFormatSampleControl( Window* pParent, WinBits nWinStyle ); // XPropertyControl virtual ::com::sun::star::uno::Any SAL_CALL getValue() throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setValue( const ::com::sun::star::uno::Any& _value ) throw (::com::sun::star::beans::IllegalTypeException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Type SAL_CALL getValueType() throw (::com::sun::star::uno::RuntimeException); inline void SetFormatSupplier( const SvNumberFormatsSupplierObj* _pSupplier ) { getTypedControlWindow()->SetFormatSupplier( _pSupplier ); } }; //======================================================================== //= FormatDescription //======================================================================== struct FormatDescription { SvNumberFormatsSupplierObj* pSupplier; sal_Int32 nKey; }; //======================================================================== //= OFormattedNumericControl //======================================================================== typedef CommonBehaviourControl< ::com::sun::star::inspection::XPropertyControl, ControlWindow< FormattedField > > OFormattedNumericControl_Base; class OFormattedNumericControl : public OFormattedNumericControl_Base { private: sal_Int32 m_nLastDecimalDigits; public: OFormattedNumericControl( Window* pParent, WinBits nWinStyle = WB_TABSTOP); // XPropertyControl virtual ::com::sun::star::uno::Any SAL_CALL getValue() throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setValue( const ::com::sun::star::uno::Any& _value ) throw (::com::sun::star::beans::IllegalTypeException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Type SAL_CALL getValueType() throw (::com::sun::star::uno::RuntimeException); void SetFormatDescription( const FormatDescription& rDesc ); // make some FormattedField methods available void SetDecimalDigits(sal_uInt16 nPrecision) { getTypedControlWindow()->SetDecimalDigits(nPrecision); m_nLastDecimalDigits = nPrecision; } void SetDefaultValue(double dDef) { getTypedControlWindow()->SetDefaultValue(dDef); } void EnableEmptyField(sal_Bool bEnable) { getTypedControlWindow()->EnableEmptyField(bEnable); } void SetThousandsSep(sal_Bool bEnable) { getTypedControlWindow()->SetThousandsSep(bEnable); } protected: ~OFormattedNumericControl(); }; //======================================================================== //= OFileUrlControl //======================================================================== typedef CommonBehaviourControl< ::com::sun::star::inspection::XPropertyControl, ControlWindow< ::svt::FileURLBox > > OFileUrlControl_Base; class OFileUrlControl : public OFileUrlControl_Base { public: OFileUrlControl( Window* pParent, WinBits nWinStyle ); // XPropertyControl virtual ::com::sun::star::uno::Any SAL_CALL getValue() throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setValue( const ::com::sun::star::uno::Any& _value ) throw (::com::sun::star::beans::IllegalTypeException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Type SAL_CALL getValueType() throw (::com::sun::star::uno::RuntimeException); protected: ~OFileUrlControl(); }; //======================================================================== //= OTimeDurationControl //======================================================================== class OTimeDurationControl : public ONumericControl { public: OTimeDurationControl( ::Window* pParent, WinBits nWinStyle ); ~OTimeDurationControl(); private: DECL_LINK( OnCustomConvert, MetricField* ); }; //............................................................................ } // namespace pcr //............................................................................ #endif // _EXTENSIONS_PROPCTRLR_USERCONTROL_HXX_ <|endoftext|>
<commit_before>/* * Copyright (c) 2004-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #include "TunIntf.h" extern "C" { #include <sys/types.h> #include <sys/stat.h> #include <sys/ioctl.h> #include <fcntl.h> #include <linux/if.h> #include <linux/if_tun.h> #include <netlink/route/link.h> } #include "fboss/agent/RxPacket.h" #include "fboss/agent/SwSwitch.h" #include "fboss/agent/SysError.h" #include "fboss/agent/TxPacket.h" #include "fboss/agent/packet/EthHdr.h" #include <folly/io/async/EventBase.h> #include <folly/io/async/EventHandler.h> namespace facebook { namespace fboss { namespace { const std::string kTunIntfPrefix = "front"; const std::string kTunDev = "/dev/net/tun"; // Max packets to be processed which are received from host const int kMaxSentOneTime = 16; } // anonymous namespace TunIntf::TunIntf( SwSwitch *sw, folly::EventBase *evb, InterfaceID ifID, int ifIndex, int mtu) : folly::EventHandler(evb), sw_(sw), name_(createTunIntfName(ifID)), ifID_(ifID), ifIndex_(ifIndex), mtu_(mtu) { DCHECK(sw) << "NULL pointer to SwSwitch."; DCHECK(evb) << "NULL pointer to EventBase"; openFD(); SCOPE_FAIL { closeFD(); }; LOG(INFO) << "Added interface " << name_ << " with fd " << fd_ << " @ index " << ifIndex_; } TunIntf::TunIntf( SwSwitch *sw, folly::EventBase *evb, InterfaceID ifID, const Interface::Addresses& addr, int mtu) : folly::EventHandler(evb), sw_(sw), name_(createTunIntfName(ifID)), ifID_(ifID), addrs_(addr), mtu_(mtu) { DCHECK(sw) << "NULL pointer to SwSwitch."; DCHECK(evb) << "NULL pointer to EventBase"; // Open Tun interface FD for socket-IO openFD(); SCOPE_FAIL { closeFD(); }; // Make the Tun interface persistent, so that the network sessions from the // application (i.e. BGP) will not be reset if controller restarts auto ret = ioctl(fd_, TUNSETPERSIST, 1); sysCheckError(ret, "Failed to set persist interface ", name_); // TODO: if needed, we can adjust send buffer size, TUNSETSNDBUF auto sock = nl_socket_alloc(); if (!sock) { throw SysError(errno, "failed to open libnl socket"); } SCOPE_EXIT { nl_socket_free(sock); }; // Connect netlink socket. ret = nl_connect(sock, NETLINK_ROUTE); sysCheckError(ret, "failed to connect", nl_geterror(ret)); SCOPE_EXIT { nl_close(sock); }; // Allocate cache nl_cache *cache = nullptr; ret = rtnl_link_alloc_cache(sock, AF_UNSPEC, &cache); sysCheckError(ret, "failed to get all links: error: ", nl_geterror(ret)); SCOPE_EXIT { nl_cache_free(cache); }; // Extract ifIndex ifIndex_ = rtnl_link_name2i(cache, name_.c_str()); if (ifIndex_ <= 0) { FbossError("Got invalid value ", ifIndex_, " for Tun interface ", name_); } LOG(INFO) << "Created interface " << name_ << " with fd " << fd_ << " @ index " << ifIndex_; } TunIntf::~TunIntf() { stop(); // We must have a valid fd to TunIntf CHECK_NE(fd_, -1); // Delete interface if need be if (toDelete_) { auto ret = ioctl(fd_, TUNSETPERSIST, 0); sysLogError(ret, "Failed to unset persist interface ", name_); } // Close FD. This will delete the interface if TUNSETPERSIST is not on closeFD(); LOG(INFO) << (toDelete_ ? "Delete" : "Detach") << " interface " << name_; } bool TunIntf::isTunIntfName(std::string const& ifName) { return ifName.find(kTunIntfPrefix) == 0; } std::string TunIntf::createTunIntfName(InterfaceID ifID) { return folly::sformat("{}{}", kTunIntfPrefix, folly::to<std::string>(ifID)); } InterfaceID TunIntf::getIDFromTunIntfName(std::string const& ifName) { if (not isTunIntfName(ifName)) { throw FbossError(ifName, " is not a valid tun interface"); } return InterfaceID(atoi(ifName.substr(kTunIntfPrefix.size()).c_str())); } void TunIntf::stop() { unregisterHandler(); } void TunIntf::start() { if (fd_ != -1 && !isHandlerRegistered()) { changeHandlerFD(fd_); registerHandler(folly::EventHandler::READ | folly::EventHandler::PERSIST); } } void TunIntf::openFD() { fd_ = open(kTunDev.c_str(), O_RDWR); sysCheckError(fd_, "Cannot open ", kTunDev.c_str()); SCOPE_FAIL { closeFD(); }; struct ifreq ifr; memset(&ifr, 0, sizeof(ifr)); // Flags: IFF_TUN - TUN device (no Ethernet headers) // IFF_NO_PI - Do not provide packet information ifr.ifr_flags = IFF_TUN|IFF_NO_PI; bzero(ifr.ifr_name, sizeof(ifr.ifr_name)); size_t len = std::min(name_.size(), sizeof(ifr.ifr_name)); memmove(ifr.ifr_name, name_.c_str(), len); auto ret = ioctl(fd_, TUNSETIFF, (void *) &ifr); sysCheckError(ret, "Failed to create/attach interface ", name_); // Set configured MTU setMtu(mtu_); // make fd non-blocking auto flags = fcntl(fd_, F_GETFL); sysCheckError(flags, "Failed to get flags from fd ", fd_); flags |= O_NONBLOCK; ret = fcntl(fd_, F_SETFL, flags); sysCheckError(ret, "Failed to set non-blocking flags ", flags, " to fd ", fd_); flags = fcntl(fd_, F_GETFD); sysCheckError(flags, "Failed to get flags from fd ", fd_); flags |= FD_CLOEXEC; ret = fcntl(fd_, F_SETFD, flags); sysCheckError(ret, "Failed to set close-on-exec flags ", flags, " to fd ", fd_); LOG(INFO) << "Create/attach to tun interface " << name_ << " @ fd " << fd_; } void TunIntf::closeFD() noexcept { auto ret = close(fd_); sysLogError(ret, "Failed to close fd ", fd_, " for interface ", name_); if (ret == 0) { LOG(INFO) << "Closed fd " << fd_ << " for interface " << name_; fd_ = -1; } } void TunIntf::addAddress(const folly::IPAddress& addr, uint8_t mask) { auto ret = addrs_.emplace(addr, mask); if (!ret.second) { throw FbossError("Duplication interface address ", addr, "/", static_cast<int>(mask), " for interface ", name_, " @ index", ifIndex_); } VLOG(3) << "Added address " << addr.str() << "/" << static_cast<int>(mask) << " to interface " << name_ << " @ index " << ifIndex_; } void TunIntf::setMtu(int mtu) { mtu_ = mtu; auto sock = socket(PF_INET, SOCK_DGRAM, 0); sysCheckError(sock, "Failed to open socket"); struct ifreq ifr; size_t len = std::min(name_.size(), sizeof(ifr.ifr_name)); memset(&ifr, 0, sizeof(ifr)); memmove(ifr.ifr_name, name_.c_str(), len); ifr.ifr_mtu = mtu_; auto ret = ioctl(sock, SIOCSIFMTU, (void*)&ifr); close(sock); sysCheckError(ret, "Failed to set MTU ", ifr.ifr_mtu, " to fd ", fd_, " errno = ", errno); VLOG(3) << "Set tun " << name_ << " MTU to " << mtu; } void TunIntf::handlerReady(uint16_t events) noexcept { CHECK(fd_ != -1); // Since this is L3 packet size, we should also reserve some space for L2 // header, which is 18 bytes (including one vlan tag) int sent = 0; int dropped = 0; uint64_t bytes = 0; bool fdFail = false; try { while (sent + dropped < kMaxSentOneTime) { std::unique_ptr<TxPacket> pkt; pkt = sw_->allocateL3TxPacket(mtu_); auto buf = pkt->buf(); int ret = 0; do { ret = read(fd_, buf->writableTail(), buf->tailroom()); } while (ret == -1 && errno == EINTR); if (ret < 0) { if (errno != EAGAIN) { sysLogError(ret, "Failed to read on ", fd_); // Cannot continue read on this fd fdFail = true; } break; } else if (ret == 0) { // Nothing to read. It shall not happen as the fd is non-blocking. // Just add this case to be safe. Adding DCHECK for sanity checking // in debug mode. DCHECK(false) << "Unexpected event. Nothing to read."; break; } else if (ret > buf->tailroom()) { // The pkt is larger than the buffer. We don't have complete packet. // It shall not happen unless the MTU is mis-match. Drop the packet. LOG(ERROR) << "Too large packet (" << ret << " > " << buf->tailroom() << ") received from host. Drop the packet."; ++dropped; } else { bytes += ret; buf->append(ret); sw_->sendL3Packet(RouterID(0), std::move(pkt)); ++sent; } } // while } catch (const std::exception& ex) { LOG(ERROR) << "Hit some error when forwarding packets :" << folly::exceptionStr(ex); } if (fdFail) { unregisterHandler(); } VLOG(4) << "Forwarded " << sent << " packets (" << bytes << " bytes) from host @ fd " << fd_ << " for interface " << name_ << " dropped:" << dropped; } bool TunIntf::sendPacketToHost(std::unique_ptr<RxPacket> pkt) { CHECK(fd_ != -1); const int l2Len = EthHdr::SIZE; auto buf = pkt->buf(); if (buf->length() <= l2Len) { LOG(ERROR) << "Received a too small packet with length " << buf->length(); return false; } // skip L2 header buf->trimStart(l2Len); int ret = 0; do { ret = write(fd_, buf->data(), buf->length()); } while (ret == -1 && errno == EINTR); if (ret < 0) { sysLogError(ret, "Failed to send packet to host from Interface ", ifID_); return false; } else if (ret < buf->length()) { LOG(ERROR) << "Failed to send full packet to host from Interface " << ifID_ << ". " << ret << " bytes sent instead of " << buf->length(); return false; } VLOG(4) << "Send packet (" << ret << " bytes) to host from Interface " << ifID_; return true; } }} // namespace facebook::fboss <commit_msg>Rename tun interfaces with `fboss` prefix<commit_after>/* * Copyright (c) 2004-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #include "TunIntf.h" extern "C" { #include <sys/types.h> #include <sys/stat.h> #include <sys/ioctl.h> #include <fcntl.h> #include <linux/if.h> #include <linux/if_tun.h> #include <netlink/route/link.h> } #include "fboss/agent/RxPacket.h" #include "fboss/agent/SwSwitch.h" #include "fboss/agent/SysError.h" #include "fboss/agent/TxPacket.h" #include "fboss/agent/packet/EthHdr.h" #include <folly/io/async/EventBase.h> #include <folly/io/async/EventHandler.h> namespace facebook { namespace fboss { namespace { const std::string kTunIntfPrefix = "fboss"; const std::string kTunDev = "/dev/net/tun"; // Max packets to be processed which are received from host const int kMaxSentOneTime = 16; } // anonymous namespace TunIntf::TunIntf( SwSwitch *sw, folly::EventBase *evb, InterfaceID ifID, int ifIndex, int mtu) : folly::EventHandler(evb), sw_(sw), name_(createTunIntfName(ifID)), ifID_(ifID), ifIndex_(ifIndex), mtu_(mtu) { DCHECK(sw) << "NULL pointer to SwSwitch."; DCHECK(evb) << "NULL pointer to EventBase"; openFD(); SCOPE_FAIL { closeFD(); }; LOG(INFO) << "Added interface " << name_ << " with fd " << fd_ << " @ index " << ifIndex_; } TunIntf::TunIntf( SwSwitch *sw, folly::EventBase *evb, InterfaceID ifID, const Interface::Addresses& addr, int mtu) : folly::EventHandler(evb), sw_(sw), name_(createTunIntfName(ifID)), ifID_(ifID), addrs_(addr), mtu_(mtu) { DCHECK(sw) << "NULL pointer to SwSwitch."; DCHECK(evb) << "NULL pointer to EventBase"; // Open Tun interface FD for socket-IO openFD(); SCOPE_FAIL { closeFD(); }; // Make the Tun interface persistent, so that the network sessions from the // application (i.e. BGP) will not be reset if controller restarts auto ret = ioctl(fd_, TUNSETPERSIST, 1); sysCheckError(ret, "Failed to set persist interface ", name_); // TODO: if needed, we can adjust send buffer size, TUNSETSNDBUF auto sock = nl_socket_alloc(); if (!sock) { throw SysError(errno, "failed to open libnl socket"); } SCOPE_EXIT { nl_socket_free(sock); }; // Connect netlink socket. ret = nl_connect(sock, NETLINK_ROUTE); sysCheckError(ret, "failed to connect", nl_geterror(ret)); SCOPE_EXIT { nl_close(sock); }; // Allocate cache nl_cache *cache = nullptr; ret = rtnl_link_alloc_cache(sock, AF_UNSPEC, &cache); sysCheckError(ret, "failed to get all links: error: ", nl_geterror(ret)); SCOPE_EXIT { nl_cache_free(cache); }; // Extract ifIndex ifIndex_ = rtnl_link_name2i(cache, name_.c_str()); if (ifIndex_ <= 0) { FbossError("Got invalid value ", ifIndex_, " for Tun interface ", name_); } LOG(INFO) << "Created interface " << name_ << " with fd " << fd_ << " @ index " << ifIndex_; } TunIntf::~TunIntf() { stop(); // We must have a valid fd to TunIntf CHECK_NE(fd_, -1); // Delete interface if need be if (toDelete_) { auto ret = ioctl(fd_, TUNSETPERSIST, 0); sysLogError(ret, "Failed to unset persist interface ", name_); } // Close FD. This will delete the interface if TUNSETPERSIST is not on closeFD(); LOG(INFO) << (toDelete_ ? "Delete" : "Detach") << " interface " << name_; } bool TunIntf::isTunIntfName(std::string const& ifName) { // Special case to handle old front0 interface. // XXX: Delete this case after 6 months (atleast one full rollout). 08-27-2016 if (ifName == "front0") { return true; } return ifName.find(kTunIntfPrefix) == 0; } std::string TunIntf::createTunIntfName(InterfaceID ifID) { // Special case to handle old front0 interface. // XXX: Delete this case after 6 months (atleast one full rollout). 08-27-2016 if (ifID == InterfaceID(0)) { return "front0"; } return folly::sformat("{}{}", kTunIntfPrefix, folly::to<std::string>(ifID)); } InterfaceID TunIntf::getIDFromTunIntfName(std::string const& ifName) { if (not isTunIntfName(ifName)) { throw FbossError(ifName, " is not a valid tun interface"); } // Special case to handle old front0 interface. // XXX: Delete this case after 6 months (atleast one full rollout). 08-27-2016 if (ifName == "front0") { return InterfaceID(0); } return InterfaceID(atoi(ifName.substr(kTunIntfPrefix.size()).c_str())); } void TunIntf::stop() { unregisterHandler(); } void TunIntf::start() { if (fd_ != -1 && !isHandlerRegistered()) { changeHandlerFD(fd_); registerHandler(folly::EventHandler::READ | folly::EventHandler::PERSIST); } } void TunIntf::openFD() { fd_ = open(kTunDev.c_str(), O_RDWR); sysCheckError(fd_, "Cannot open ", kTunDev.c_str()); SCOPE_FAIL { closeFD(); }; struct ifreq ifr; memset(&ifr, 0, sizeof(ifr)); // Flags: IFF_TUN - TUN device (no Ethernet headers) // IFF_NO_PI - Do not provide packet information ifr.ifr_flags = IFF_TUN|IFF_NO_PI; bzero(ifr.ifr_name, sizeof(ifr.ifr_name)); size_t len = std::min(name_.size(), sizeof(ifr.ifr_name)); memmove(ifr.ifr_name, name_.c_str(), len); auto ret = ioctl(fd_, TUNSETIFF, (void *) &ifr); sysCheckError(ret, "Failed to create/attach interface ", name_); // Set configured MTU setMtu(mtu_); // make fd non-blocking auto flags = fcntl(fd_, F_GETFL); sysCheckError(flags, "Failed to get flags from fd ", fd_); flags |= O_NONBLOCK; ret = fcntl(fd_, F_SETFL, flags); sysCheckError(ret, "Failed to set non-blocking flags ", flags, " to fd ", fd_); flags = fcntl(fd_, F_GETFD); sysCheckError(flags, "Failed to get flags from fd ", fd_); flags |= FD_CLOEXEC; ret = fcntl(fd_, F_SETFD, flags); sysCheckError(ret, "Failed to set close-on-exec flags ", flags, " to fd ", fd_); LOG(INFO) << "Create/attach to tun interface " << name_ << " @ fd " << fd_; } void TunIntf::closeFD() noexcept { auto ret = close(fd_); sysLogError(ret, "Failed to close fd ", fd_, " for interface ", name_); if (ret == 0) { LOG(INFO) << "Closed fd " << fd_ << " for interface " << name_; fd_ = -1; } } void TunIntf::addAddress(const folly::IPAddress& addr, uint8_t mask) { auto ret = addrs_.emplace(addr, mask); if (!ret.second) { throw FbossError("Duplication interface address ", addr, "/", static_cast<int>(mask), " for interface ", name_, " @ index", ifIndex_); } VLOG(3) << "Added address " << addr.str() << "/" << static_cast<int>(mask) << " to interface " << name_ << " @ index " << ifIndex_; } void TunIntf::setMtu(int mtu) { mtu_ = mtu; auto sock = socket(PF_INET, SOCK_DGRAM, 0); sysCheckError(sock, "Failed to open socket"); struct ifreq ifr; size_t len = std::min(name_.size(), sizeof(ifr.ifr_name)); memset(&ifr, 0, sizeof(ifr)); memmove(ifr.ifr_name, name_.c_str(), len); ifr.ifr_mtu = mtu_; auto ret = ioctl(sock, SIOCSIFMTU, (void*)&ifr); close(sock); sysCheckError(ret, "Failed to set MTU ", ifr.ifr_mtu, " to fd ", fd_, " errno = ", errno); VLOG(3) << "Set tun " << name_ << " MTU to " << mtu; } void TunIntf::handlerReady(uint16_t events) noexcept { CHECK(fd_ != -1); // Since this is L3 packet size, we should also reserve some space for L2 // header, which is 18 bytes (including one vlan tag) int sent = 0; int dropped = 0; uint64_t bytes = 0; bool fdFail = false; try { while (sent + dropped < kMaxSentOneTime) { std::unique_ptr<TxPacket> pkt; pkt = sw_->allocateL3TxPacket(mtu_); auto buf = pkt->buf(); int ret = 0; do { ret = read(fd_, buf->writableTail(), buf->tailroom()); } while (ret == -1 && errno == EINTR); if (ret < 0) { if (errno != EAGAIN) { sysLogError(ret, "Failed to read on ", fd_); // Cannot continue read on this fd fdFail = true; } break; } else if (ret == 0) { // Nothing to read. It shall not happen as the fd is non-blocking. // Just add this case to be safe. Adding DCHECK for sanity checking // in debug mode. DCHECK(false) << "Unexpected event. Nothing to read."; break; } else if (ret > buf->tailroom()) { // The pkt is larger than the buffer. We don't have complete packet. // It shall not happen unless the MTU is mis-match. Drop the packet. LOG(ERROR) << "Too large packet (" << ret << " > " << buf->tailroom() << ") received from host. Drop the packet."; ++dropped; } else { bytes += ret; buf->append(ret); sw_->sendL3Packet(RouterID(0), std::move(pkt)); ++sent; } } // while } catch (const std::exception& ex) { LOG(ERROR) << "Hit some error when forwarding packets :" << folly::exceptionStr(ex); } if (fdFail) { unregisterHandler(); } VLOG(4) << "Forwarded " << sent << " packets (" << bytes << " bytes) from host @ fd " << fd_ << " for interface " << name_ << " dropped:" << dropped; } bool TunIntf::sendPacketToHost(std::unique_ptr<RxPacket> pkt) { CHECK(fd_ != -1); const int l2Len = EthHdr::SIZE; auto buf = pkt->buf(); if (buf->length() <= l2Len) { LOG(ERROR) << "Received a too small packet with length " << buf->length(); return false; } // skip L2 header buf->trimStart(l2Len); int ret = 0; do { ret = write(fd_, buf->data(), buf->length()); } while (ret == -1 && errno == EINTR); if (ret < 0) { sysLogError(ret, "Failed to send packet to host from Interface ", ifID_); return false; } else if (ret < buf->length()) { LOG(ERROR) << "Failed to send full packet to host from Interface " << ifID_ << ". " << ret << " bytes sent instead of " << buf->length(); return false; } VLOG(4) << "Send packet (" << ret << " bytes) to host from Interface " << ifID_; return true; } }} // namespace facebook::fboss <|endoftext|>
<commit_before>/* FUSE: Filesystem in Userspace Copyright (C) 2001-2007 Miklos Szeredi <[email protected]> This program can be distributed under the terms of the GNU GPL. See the file COPYING. gcc -Wall `pkg-config fuse --cflags --libs` fusexmp.c -o fusexmp */ #define FUSE_USE_VERSION 26 #ifdef HAVE_CONFIG_H #include <config.h> #endif #ifdef linux /* For pread()/pwrite() */ #define _XOPEN_SOURCE 500 #endif #include <fuse.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <fcntl.h> #include <dirent.h> #include <errno.h> #include <sys/time.h> #ifdef HAVE_SETXATTR #include <sys/xattr.h> #endif // Non-FUSE includes #include <vector> #include <iostream> #include <fstream> #include <boost/filesystem.hpp> #include "serverconnection.hpp" #include <sys/types.h> /************** * GLOBALS * ***********/ static std::vector<ServerConnection> connections; static int agfs_getattr(const char *path, struct stat *stbuf) { memset(stbuf, 0, sizeof(struct stat)); agerr_t err = 0; if (connections.size() > 0) { std::pair<struct stat, agerr_t> retVal{connections.front().getattr(path)}; (*stbuf) = std::get<0>(retVal); err = std::get<1>(retVal); } return -err; } static int agfs_access(const char *path, int mask) { int res; res = access(path, mask); if (res == -1) return -errno; return 0; } static int agfs_readlink(const char *path, char *buf, size_t size) { int res; res = readlink(path, buf, size - 1); if (res == -1) return -errno; buf[res] = '\0'; return 0; } static int agfs_readdir(const char *path, void *buf, fuse_fill_dir_t filler, off_t offset, struct fuse_file_info *fi) { DIR *dp; struct dirent *de; (void) offset; (void) fi; dp = opendir(path); if (dp == NULL) return -errno; while ((de = readdir(dp)) != NULL) { struct stat st; memset(&st, 0, sizeof(st)); st.st_ino = de->d_ino; st.st_mode = de->d_type << 12; if (filler(buf, de->d_name, &st, 0)) break; } closedir(dp); return 0; } static int agfs_mknod(const char *path, mode_t mode, dev_t rdev) { int res; /* On Linux this could just be 'mknod(path, mode, rdev)' but this is more portable */ if (S_ISREG(mode)) { res = open(path, O_CREAT | O_EXCL | O_WRONLY, mode); if (res >= 0) res = close(res); } else if (S_ISFIFO(mode)) res = mkfifo(path, mode); else res = mknod(path, mode, rdev); if (res == -1) return -errno; return 0; } static int agfs_mkdir(const char *path, mode_t mode) { int res; res = mkdir(path, mode); if (res == -1) return -errno; return 0; } static int agfs_unlink(const char *path) { int res; res = unlink(path); if (res == -1) return -errno; return 0; } static int agfs_rmdir(const char *path) { int res; res = rmdir(path); if (res == -1) return -errno; return 0; } static int agfs_symlink(const char *to, const char *from) { int res; res = symlink(to, from); if (res == -1) return -errno; return 0; } static int agfs_rename(const char *from, const char *to) { int res; res = rename(from, to); if (res == -1) return -errno; return 0; } static int agfs_link(const char *from, const char *to) { int res; res = link(from, to); if (res == -1) return -errno; return 0; } static int agfs_chmod(const char *path, mode_t mode) { int res; res = chmod(path, mode); if (res == -1) return -errno; return 0; } static int agfs_chown(const char *path, uid_t uid, gid_t gid) { int res; res = lchown(path, uid, gid); if (res == -1) return -errno; return 0; } static int agfs_truncate(const char *path, off_t size) { int res; res = truncate(path, size); if (res == -1) return -errno; return 0; } static int agfs_utimens(const char *path, const struct timespec ts[2]) { int res; struct timeval tv[2]; tv[0].tv_sec = ts[0].tv_sec; tv[0].tv_usec = ts[0].tv_nsec / 1000; tv[1].tv_sec = ts[1].tv_sec; tv[1].tv_usec = ts[1].tv_nsec / 1000; res = utimes(path, tv); if (res == -1) return -errno; return 0; } static int agfs_open(const char *path, struct fuse_file_info *fi) { int res; res = open(path, fi->flags); if (res == -1) return -errno; close(res); return 0; } static int agfs_read(const char *path, char *buf, size_t size, off_t offset, struct fuse_file_info *fi) { int fd; int res; (void) fi; fd = open(path, O_RDONLY); if (fd == -1) return -errno; res = pread(fd, buf, size, offset); if (res == -1) res = -errno; close(fd); return res; } static int agfs_write(const char *path, const char *buf, size_t size, off_t offset, struct fuse_file_info *fi) { int fd; int res; (void) fi; fd = open(path, O_WRONLY); if (fd == -1) return -errno; res = pwrite(fd, buf, size, offset); if (res == -1) res = -errno; close(fd); return res; } static int agfs_statfs(const char *path, struct statvfs *stbuf) { int res; res = statvfs(path, stbuf); if (res == -1) return -errno; return 0; } static int agfs_release(const char *path, struct fuse_file_info *fi) { /* Just a stub. This method is optional and can safely be left unimplemented */ (void) path; (void) fi; return 0; } static int agfs_fsync(const char *path, int isdatasync, struct fuse_file_info *fi) { /* Just a stub. This method is optional and can safely be left unimplemented */ (void) path; (void) isdatasync; (void) fi; return 0; } #ifdef HAVE_SETXATTR /* xattr operations are optional and can safely be left unimplemented */ static int agfs_setxattr(const char *path, const char *name, const char *value, size_t size, int flags) { int res = lsetxattr(path, name, value, size, flags); if (res == -1) return -errno; return 0; } static int agfs_getxattr(const char *path, const char *name, char *value, size_t size) { int res = lgetxattr(path, name, value, size); if (res == -1) return -errno; return res; } static int agfs_listxattr(const char *path, char *list, size_t size) { int res = llistxattr(path, list, size); if (res == -1) return -errno; return res; } static int agfs_removexattr(const char *path, const char *name) { int res = lremovexattr(path, name); if (res == -1) return -errno; return 0; } #endif /* HAVE_SETXATTR */ static struct fuse_operations agfs_oper = { .getattr= agfs_getattr, .access= agfs_access, .readlink= agfs_readlink, .readdir= agfs_readdir, .mknod= agfs_mknod, .mkdir= agfs_mkdir, .symlink= agfs_symlink, .unlink= agfs_unlink, .rmdir= agfs_rmdir, .rename= agfs_rename, .link= agfs_link, .chmod= agfs_chmod, .chown= agfs_chown, .truncate= agfs_truncate, .utimens= agfs_utimens, .open= agfs_open, .read= agfs_read, .write= agfs_write, .statfs= agfs_statfs, .release= agfs_release, .fsync= agfs_fsync, #ifdef HAVE_SETXATTR .setxattr= agfs_setxattr, .getxattr= agfs_getxattr, .listxattr= agfs_listxattr, .removexattr= agfs_removexattr, #endif }; /************************************ * OPTIONS PROCESSING (Not working) * ************************************/ /*struct agfs_config { char* instanceFile; }; enum { KEY_HELP, KEY_VERSION, }; #define AGFS_OPT(t, p, v) { t, offsetof(struct agfs_config, p), v } static struct fuse_opt agfs_opts[] = { AGFS_OPT("-i %s", instanceFile, 0), AGFS_OPT("--instance=%s", instanceFile, 0), AGFS_OPT("instance=%s", instanceFile, 0), FUSE_OPT_KEY("-V", KEY_VERSION), FUSE_OPT_KEY("--version", KEY_VERSION), FUSE_OPT_KEY("-h", KEY_HELP), FUSE_OPT_KEY("--help", KEY_HELP), FUSE_OPT_END }; #define PACKAGE_VERSION "0.0.0 beta" static int agfs_opt_proc(void *data, const char *arg, int key, struct fuse_args *outargs) { switch (key) { case KEY_HELP: fprintf(stderr, "usage: %s mountpoint [options]\n" "\n" "general options:\n" " -o opt,[opt...] mount options\n" " -h --help print help\n" " -V --version print version\n" "\n" "agfs options:\n" " -o instance=STRING\n" " -i STRING same as '-o instance=STRING'\n" " --instance=STRING same as -i STRING'\n\n" , outargs->argv[0]); fuse_opt_add_arg(outargs, "-ho"); fuse_main(outargs->argc, outargs->argv, &agfs_oper, NULL); exit(1); case KEY_VERSION: fprintf(stderr, "agfs version %s\n", PACKAGE_VERSION); fuse_opt_add_arg(outargs, "--version"); fuse_main(outargs->argc, outargs->argv, &agfs_oper, NULL); exit(0); } return 1; }*/ static const boost::filesystem::path KEYDIRPATH(".agfs"); static const std::string EXTENSION(".agkey"); using namespace boost::filesystem; int main(int argc, char *argv[]) { path homeDir{getenv("HOME")}; homeDir /= KEYDIRPATH; if(!exists(homeDir)) { std::cerr << "Could not find key directory: ~/.agfs" << std::endl; exit(1); } directory_iterator end_itr; // default construction yields past-the-end for ( directory_iterator itr( homeDir ); itr != end_itr; ++itr ) { if( is_regular_file(*itr) ) { if( extension(itr->path()) == EXTENSION) { std::cout << "Found keyfile: " << itr->path() << std::endl; std::fstream keyfile; keyfile.open(itr->path().native(), std::fstream::in); if(keyfile.is_open()) { std::cout << "Opened keyfile" << std::endl; std::string hostname, port, key; keyfile >> hostname; keyfile >> port; keyfile >> key; connections.push_back(ServerConnection(hostname, port, key)); } keyfile.close(); } } } return fuse_main(argc, argv, &agfs_oper, NULL); } <commit_msg>Modified the fuse_operations struct to eliminate the annoying warnings on compilation<commit_after>/* FUSE: Filesystem in Userspace Copyright (C) 2001-2007 Miklos Szeredi <[email protected]> This program can be distributed under the terms of the GNU GPL. See the file COPYING. gcc -Wall `pkg-config fuse --cflags --libs` fusexmp.c -o fusexmp */ #define FUSE_USE_VERSION 26 #ifdef HAVE_CONFIG_H #include <config.h> #endif #ifdef linux /* For pread()/pwrite() */ #define _XOPEN_SOURCE 500 #endif #include <fuse.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <fcntl.h> #include <dirent.h> #include <errno.h> #include <sys/time.h> #ifdef HAVE_SETXATTR #include <sys/xattr.h> #endif // Non-FUSE includes #include <vector> #include <iostream> #include <fstream> #include <boost/filesystem.hpp> #include "serverconnection.hpp" #include <sys/types.h> /************** * GLOBALS * ***********/ static std::vector<ServerConnection> connections; static int agfs_getattr(const char *path, struct stat *stbuf) { memset(stbuf, 0, sizeof(struct stat)); agerr_t err = 0; if (connections.size() > 0) { std::pair<struct stat, agerr_t> retVal{connections.front().getattr(path)}; (*stbuf) = std::get<0>(retVal); err = std::get<1>(retVal); } return -err; } static int agfs_access(const char *path, int mask) { int res; res = access(path, mask); if (res == -1) return -errno; return 0; } static int agfs_readlink(const char *path, char *buf, size_t size) { int res; res = readlink(path, buf, size - 1); if (res == -1) return -errno; buf[res] = '\0'; return 0; } static int agfs_readdir(const char *path, void *buf, fuse_fill_dir_t filler, off_t offset, struct fuse_file_info *fi) { DIR *dp; struct dirent *de; (void) offset; (void) fi; dp = opendir(path); if (dp == NULL) return -errno; while ((de = readdir(dp)) != NULL) { struct stat st; memset(&st, 0, sizeof(st)); st.st_ino = de->d_ino; st.st_mode = de->d_type << 12; if (filler(buf, de->d_name, &st, 0)) break; } closedir(dp); return 0; } static int agfs_mknod(const char *path, mode_t mode, dev_t rdev) { int res; /* On Linux this could just be 'mknod(path, mode, rdev)' but this is more portable */ if (S_ISREG(mode)) { res = open(path, O_CREAT | O_EXCL | O_WRONLY, mode); if (res >= 0) res = close(res); } else if (S_ISFIFO(mode)) res = mkfifo(path, mode); else res = mknod(path, mode, rdev); if (res == -1) return -errno; return 0; } static int agfs_mkdir(const char *path, mode_t mode) { int res; res = mkdir(path, mode); if (res == -1) return -errno; return 0; } static int agfs_unlink(const char *path) { int res; res = unlink(path); if (res == -1) return -errno; return 0; } static int agfs_rmdir(const char *path) { int res; res = rmdir(path); if (res == -1) return -errno; return 0; } static int agfs_symlink(const char *to, const char *from) { int res; res = symlink(to, from); if (res == -1) return -errno; return 0; } static int agfs_rename(const char *from, const char *to) { int res; res = rename(from, to); if (res == -1) return -errno; return 0; } static int agfs_link(const char *from, const char *to) { int res; res = link(from, to); if (res == -1) return -errno; return 0; } static int agfs_chmod(const char *path, mode_t mode) { int res; res = chmod(path, mode); if (res == -1) return -errno; return 0; } static int agfs_chown(const char *path, uid_t uid, gid_t gid) { int res; res = lchown(path, uid, gid); if (res == -1) return -errno; return 0; } static int agfs_truncate(const char *path, off_t size) { int res; res = truncate(path, size); if (res == -1) return -errno; return 0; } static int agfs_utimens(const char *path, const struct timespec ts[2]) { int res; struct timeval tv[2]; tv[0].tv_sec = ts[0].tv_sec; tv[0].tv_usec = ts[0].tv_nsec / 1000; tv[1].tv_sec = ts[1].tv_sec; tv[1].tv_usec = ts[1].tv_nsec / 1000; res = utimes(path, tv); if (res == -1) return -errno; return 0; } static int agfs_open(const char *path, struct fuse_file_info *fi) { int res; res = open(path, fi->flags); if (res == -1) return -errno; close(res); return 0; } static int agfs_read(const char *path, char *buf, size_t size, off_t offset, struct fuse_file_info *fi) { int fd; int res; (void) fi; fd = open(path, O_RDONLY); if (fd == -1) return -errno; res = pread(fd, buf, size, offset); if (res == -1) res = -errno; close(fd); return res; } static int agfs_write(const char *path, const char *buf, size_t size, off_t offset, struct fuse_file_info *fi) { int fd; int res; (void) fi; fd = open(path, O_WRONLY); if (fd == -1) return -errno; res = pwrite(fd, buf, size, offset); if (res == -1) res = -errno; close(fd); return res; } static int agfs_statfs(const char *path, struct statvfs *stbuf) { int res; res = statvfs(path, stbuf); if (res == -1) return -errno; return 0; } static int agfs_release(const char *path, struct fuse_file_info *fi) { /* Just a stub. This method is optional and can safely be left unimplemented */ (void) path; (void) fi; return 0; } static int agfs_fsync(const char *path, int isdatasync, struct fuse_file_info *fi) { /* Just a stub. This method is optional and can safely be left unimplemented */ (void) path; (void) isdatasync; (void) fi; return 0; } #ifdef HAVE_SETXATTR /* xattr operations are optional and can safely be left unimplemented */ static int agfs_setxattr(const char *path, const char *name, const char *value, size_t size, int flags) { int res = lsetxattr(path, name, value, size, flags); if (res == -1) return -errno; return 0; } static int agfs_getxattr(const char *path, const char *name, char *value, size_t size) { int res = lgetxattr(path, name, value, size); if (res == -1) return -errno; return res; } static int agfs_listxattr(const char *path, char *list, size_t size) { int res = llistxattr(path, list, size); if (res == -1) return -errno; return res; } static int agfs_removexattr(const char *path, const char *name) { int res = lremovexattr(path, name); if (res == -1) return -errno; return 0; } #endif /* HAVE_SETXATTR */ /************************************ * OPTIONS PROCESSING (Not working) * ************************************/ /*struct agfs_config { char* instanceFile; }; enum { KEY_HELP, KEY_VERSION, }; #define AGFS_OPT(t, p, v) { t, offsetof(struct agfs_config, p), v } static struct fuse_opt agfs_opts[] = { AGFS_OPT("-i %s", instanceFile, 0), AGFS_OPT("--instance=%s", instanceFile, 0), AGFS_OPT("instance=%s", instanceFile, 0), FUSE_OPT_KEY("-V", KEY_VERSION), FUSE_OPT_KEY("--version", KEY_VERSION), FUSE_OPT_KEY("-h", KEY_HELP), FUSE_OPT_KEY("--help", KEY_HELP), FUSE_OPT_END }; #define PACKAGE_VERSION "0.0.0 beta" static int agfs_opt_proc(void *data, const char *arg, int key, struct fuse_args *outargs) { switch (key) { case KEY_HELP: fprintf(stderr, "usage: %s mountpoint [options]\n" "\n" "general options:\n" " -o opt,[opt...] mount options\n" " -h --help print help\n" " -V --version print version\n" "\n" "agfs options:\n" " -o instance=STRING\n" " -i STRING same as '-o instance=STRING'\n" " --instance=STRING same as -i STRING'\n\n" , outargs->argv[0]); fuse_opt_add_arg(outargs, "-ho"); fuse_main(outargs->argc, outargs->argv, &agfs_oper, NULL); exit(1); case KEY_VERSION: fprintf(stderr, "agfs version %s\n", PACKAGE_VERSION); fuse_opt_add_arg(outargs, "--version"); fuse_main(outargs->argc, outargs->argv, &agfs_oper, NULL); exit(0); } return 1; }*/ static const boost::filesystem::path KEYDIRPATH(".agfs"); static const std::string EXTENSION(".agkey"); using namespace boost::filesystem; static struct fuse_operations agfs_oper; int main(int argc, char *argv[]) { path homeDir{getenv("HOME")}; homeDir /= KEYDIRPATH; if(!exists(homeDir)) { std::cerr << "Could not find key directory: ~/.agfs" << std::endl; exit(1); } directory_iterator end_itr; // default construction yields past-the-end for ( directory_iterator itr( homeDir ); itr != end_itr; ++itr ) { if( is_regular_file(*itr) ) { if( extension(itr->path()) == EXTENSION) { std::cout << "Found keyfile: " << itr->path() << std::endl; std::fstream keyfile; keyfile.open(itr->path().native(), std::fstream::in); if(keyfile.is_open()) { std::cout << "Opened keyfile" << std::endl; std::string hostname, port, key; keyfile >> hostname; keyfile >> port; keyfile >> key; connections.push_back(ServerConnection(hostname, port, key)); } keyfile.close(); } } } memset(&agfs_oper, 0, sizeof(struct fuse_operations)); agfs_oper.getattr= agfs_getattr; agfs_oper.access= agfs_access; agfs_oper.readlink= agfs_readlink; agfs_oper.readdir= agfs_readdir; agfs_oper.mknod= agfs_mknod; agfs_oper.mkdir= agfs_mkdir; agfs_oper.symlink= agfs_symlink; agfs_oper.unlink= agfs_unlink; agfs_oper.rmdir= agfs_rmdir; agfs_oper.rename= agfs_rename; agfs_oper.link= agfs_link; agfs_oper.chmod= agfs_chmod; agfs_oper.chown= agfs_chown; agfs_oper.truncate= agfs_truncate; agfs_oper.utimens= agfs_utimens; agfs_oper.open= agfs_open; agfs_oper.read= agfs_read; agfs_oper.write= agfs_write; agfs_oper.statfs= agfs_statfs; agfs_oper.release= agfs_release; agfs_oper.fsync= agfs_fsync; #ifdef HAVE_SETXATTR agfs_oper.setxattr= agfs_setxattr; agfs_oper.getxattr= agfs_getxattr; agfs_oper.listxattr= agfs_listxattr; agfs_oper.removexattr= agfs_removexattr; #endif return fuse_main(argc, argv, &agfs_oper, NULL); } <|endoftext|>
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Bitsend developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "core.h" #include "util.h" #include "main.h" #include "uint256.h" std::string COutPoint::ToString() const { return strprintf("COutPoint(%s, %u)", hash.ToString().substr(0,64), n); } void COutPoint::print() const { LogPrintf("%s\n", ToString()); } CTxIn::CTxIn(COutPoint prevoutIn, CScript scriptSigIn, unsigned int nSequenceIn) { prevout = prevoutIn; scriptSig = scriptSigIn; nSequence = nSequenceIn; } CTxIn::CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn, unsigned int nSequenceIn) { prevout = COutPoint(hashPrevTx, nOut); scriptSig = scriptSigIn; nSequence = nSequenceIn; } std::string CTxIn::ToString() const { std::string str; str += "CTxIn("; str += prevout.ToString(); if (prevout.IsNull()) str += strprintf(", coinbase %s", HexStr(scriptSig)); else str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24)); if (nSequence != std::numeric_limits<unsigned int>::max()) str += strprintf(", nSequence=%u", nSequence); str += ")"; return str; } void CTxIn::print() const { LogPrintf("%s\n", ToString()); } CTxOut::CTxOut(int64_t nValueIn, CScript scriptPubKeyIn) { nValue = nValueIn; nRounds = -10; // an initial value, should be no way to get this by calculations scriptPubKey = scriptPubKeyIn; } uint256 CTxOut::GetHash() const { return SerializeHash(*this); } std::string CTxOut::ToString() const { return strprintf("CTxOut(nValue=%d.%08d, scriptPubKey=%s)", nValue / COIN, nValue % COIN, scriptPubKey.ToString().substr(0,30)); } void CTxOut::print() const { LogPrintf("%s\n", ToString()); } uint256 CTransaction::GetHash() const { return SerializeHash(*this); } bool CTransaction::IsNewerThan(const CTransaction& old) const { if (vin.size() != old.vin.size()) return false; for (unsigned int i = 0; i < vin.size(); i++) if (vin[i].prevout != old.vin[i].prevout) return false; bool fNewer = false; unsigned int nLowest = std::numeric_limits<unsigned int>::max(); for (unsigned int i = 0; i < vin.size(); i++) { if (vin[i].nSequence != old.vin[i].nSequence) { if (vin[i].nSequence <= nLowest) { fNewer = false; nLowest = vin[i].nSequence; } if (old.vin[i].nSequence < nLowest) { fNewer = true; nLowest = old.vin[i].nSequence; } } } return fNewer; } int64_t CTransaction::GetValueOut() const { int64_t nValueOut = 0; BOOST_FOREACH(const CTxOut& txout, vout) { nValueOut += txout.nValue; if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut)) throw std::runtime_error("CTransaction::GetValueOut() : value out of range"); } return nValueOut; } double CTransaction::ComputePriority(double dPriorityInputs, unsigned int nTxSize) const { // In order to avoid disincentivizing cleaning up the UTXO set we don't count // the constant overhead for each txin and up to 110 bytes of scriptSig (which // is enough to cover a compressed pubkey p2sh redemption) for priority. // Providing any more cleanup incentive than making additional inputs free would // risk encouraging people to create junk outputs to redeem later. if (nTxSize == 0) nTxSize = ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION); BOOST_FOREACH(const CTxIn& txin, vin) { unsigned int offset = 41U + std::min(110U, (unsigned int)txin.scriptSig.size()); if (nTxSize > offset) nTxSize -= offset; } if (nTxSize == 0) return 0.0; return dPriorityInputs / nTxSize; } std::string CTransaction::ToString() const { std::string str; str += strprintf("CTransaction(hash=%s, ver=%d, vin.size=%u, vout.size=%u, nLockTime=%u)\n", GetHash().ToString().substr(0,10), nVersion, vin.size(), vout.size(), nLockTime); for (unsigned int i = 0; i < vin.size(); i++) str += " " + vin[i].ToString() + "\n"; for (unsigned int i = 0; i < vout.size(); i++) str += " " + vout[i].ToString() + "\n"; return str; } void CTransaction::print() const { LogPrintf("%s", ToString()); } // Amount compression: // * If the amount is 0, output 0 // * first, divide the amount (in base units) by the largest power of 10 possible; call the exponent e (e is max 9) // * if e<9, the last digit of the resulting number cannot be 0; store it as d, and drop it (divide by 10) // * call the result n // * output 1 + 10*(9*n + d - 1) + e // * if e==9, we only know the resulting number is not zero, so output 1 + 10*(n - 1) + 9 // (this is decodable, as d is in [1-9] and e is in [0-9]) uint64_t CTxOutCompressor::CompressAmount(uint64_t n) { if (n == 0) return 0; int e = 0; while (((n % 10) == 0) && e < 9) { n /= 10; e++; } if (e < 9) { int d = (n % 10); assert(d >= 1 && d <= 9); n /= 10; return 1 + (n*9 + d - 1)*10 + e; } else { return 1 + (n - 1)*10 + 9; } } uint64_t CTxOutCompressor::DecompressAmount(uint64_t x) { // x = 0 OR x = 1+10*(9*n + d - 1) + e OR x = 1+10*(n - 1) + 9 if (x == 0) return 0; x--; // x = 10*(9*n + d - 1) + e int e = x % 10; x /= 10; uint64_t n = 0; if (e < 9) { // x = 9*n + d - 1 int d = (x % 9) + 1; x /= 9; // x = n n = x*10 + d; } else { n = x+1; } while (e) { n *= 10; e--; } return n; } /*uint256 CBlockHeader::GetHash() const { CChain a1; int nHeight= a1.Height(); //pblock->LastHeight = pindexPrev->nHeight; if (nHeight <=10){ return HashX11(BEGIN(nVersion), END(nNonce)); } else { return HashX17(BEGIN(nVersion), END(nNonce)); } }*/ /*uint256 CBlockHeader::GetHash() const{ if (LastHeight>=15){ return HashX11(BEGIN(nVersion), END(nNonce)); } else { return HashX17(BEGIN(nVersion), END(nNonce)); } }*/ uint256 CBlockHeader::GetHashX11() const { return HashX11(BEGIN(nVersion), END(nNonce)); } uint256 CBlock::BuildMerkleTree() const { vMerkleTree.clear(); BOOST_FOREACH(const CTransaction& tx, vtx) vMerkleTree.push_back(tx.GetHash()); int j = 0; for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2) { for (int i = 0; i < nSize; i += 2) { int i2 = std::min(i+1, nSize-1); vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]), BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2]))); } j += nSize; } return (vMerkleTree.empty() ? 0 : vMerkleTree.back()); } std::vector<uint256> CBlock::GetMerkleBranch(int nIndex) const { if (vMerkleTree.empty()) BuildMerkleTree(); std::vector<uint256> vMerkleBranch; int j = 0; for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2) { int i = std::min(nIndex^1, nSize-1); vMerkleBranch.push_back(vMerkleTree[j+i]); nIndex >>= 1; j += nSize; } return vMerkleBranch; } uint256 CBlock::CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex) { if (nIndex == -1) return 0; BOOST_FOREACH(const uint256& otherside, vMerkleBranch) { if (nIndex & 1) hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash)); else hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside)); nIndex >>= 1; } return hash; } void CBlock::print() const { //GetHashX11().ToString(), LogPrintf("CBlock(hash=disable, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%u)\n", nVersion, hashPrevBlock.ToString(), hashMerkleRoot.ToString(), nTime, nBits, nNonce, vtx.size()); for (unsigned int i = 0; i < vtx.size(); i++) { LogPrintf(" "); vtx[i].print(); } LogPrintf(" vMerkleTree: "); for (unsigned int i = 0; i < vMerkleTree.size(); i++) LogPrintf("%s ", vMerkleTree[i].ToString()); LogPrintf("\n"); } <commit_msg>Revert "New way from line 229 to 36"<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Bitsend developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "core.h" #include "util.h" #include "main.h" #include "uint256.h" std::string COutPoint::ToString() const { return strprintf("COutPoint(%s, %u)", hash.ToString().substr(0,64), n); } void COutPoint::print() const { LogPrintf("%s\n", ToString()); } CTxIn::CTxIn(COutPoint prevoutIn, CScript scriptSigIn, unsigned int nSequenceIn) { prevout = prevoutIn; scriptSig = scriptSigIn; nSequence = nSequenceIn; } CTxIn::CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn, unsigned int nSequenceIn) { prevout = COutPoint(hashPrevTx, nOut); scriptSig = scriptSigIn; nSequence = nSequenceIn; } std::string CTxIn::ToString() const { std::string str; str += "CTxIn("; str += prevout.ToString(); if (prevout.IsNull()) str += strprintf(", coinbase %s", HexStr(scriptSig)); else str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24)); if (nSequence != std::numeric_limits<unsigned int>::max()) str += strprintf(", nSequence=%u", nSequence); str += ")"; return str; } void CTxIn::print() const { LogPrintf("%s\n", ToString()); } CTxOut::CTxOut(int64_t nValueIn, CScript scriptPubKeyIn) { nValue = nValueIn; nRounds = -10; // an initial value, should be no way to get this by calculations scriptPubKey = scriptPubKeyIn; } uint256 CTxOut::GetHash() const { return SerializeHash(*this); } std::string CTxOut::ToString() const { return strprintf("CTxOut(nValue=%d.%08d, scriptPubKey=%s)", nValue / COIN, nValue % COIN, scriptPubKey.ToString().substr(0,30)); } void CTxOut::print() const { LogPrintf("%s\n", ToString()); } uint256 CTransaction::GetHash() const { return SerializeHash(*this); } bool CTransaction::IsNewerThan(const CTransaction& old) const { if (vin.size() != old.vin.size()) return false; for (unsigned int i = 0; i < vin.size(); i++) if (vin[i].prevout != old.vin[i].prevout) return false; bool fNewer = false; unsigned int nLowest = std::numeric_limits<unsigned int>::max(); for (unsigned int i = 0; i < vin.size(); i++) { if (vin[i].nSequence != old.vin[i].nSequence) { if (vin[i].nSequence <= nLowest) { fNewer = false; nLowest = vin[i].nSequence; } if (old.vin[i].nSequence < nLowest) { fNewer = true; nLowest = old.vin[i].nSequence; } } } return fNewer; } int64_t CTransaction::GetValueOut() const { int64_t nValueOut = 0; BOOST_FOREACH(const CTxOut& txout, vout) { nValueOut += txout.nValue; if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut)) throw std::runtime_error("CTransaction::GetValueOut() : value out of range"); } return nValueOut; } double CTransaction::ComputePriority(double dPriorityInputs, unsigned int nTxSize) const { // In order to avoid disincentivizing cleaning up the UTXO set we don't count // the constant overhead for each txin and up to 110 bytes of scriptSig (which // is enough to cover a compressed pubkey p2sh redemption) for priority. // Providing any more cleanup incentive than making additional inputs free would // risk encouraging people to create junk outputs to redeem later. if (nTxSize == 0) nTxSize = ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION); BOOST_FOREACH(const CTxIn& txin, vin) { unsigned int offset = 41U + std::min(110U, (unsigned int)txin.scriptSig.size()); if (nTxSize > offset) nTxSize -= offset; } if (nTxSize == 0) return 0.0; return dPriorityInputs / nTxSize; } std::string CTransaction::ToString() const { std::string str; str += strprintf("CTransaction(hash=%s, ver=%d, vin.size=%u, vout.size=%u, nLockTime=%u)\n", GetHash().ToString().substr(0,10), nVersion, vin.size(), vout.size(), nLockTime); for (unsigned int i = 0; i < vin.size(); i++) str += " " + vin[i].ToString() + "\n"; for (unsigned int i = 0; i < vout.size(); i++) str += " " + vout[i].ToString() + "\n"; return str; } void CTransaction::print() const { LogPrintf("%s", ToString()); } // Amount compression: // * If the amount is 0, output 0 // * first, divide the amount (in base units) by the largest power of 10 possible; call the exponent e (e is max 9) // * if e<9, the last digit of the resulting number cannot be 0; store it as d, and drop it (divide by 10) // * call the result n // * output 1 + 10*(9*n + d - 1) + e // * if e==9, we only know the resulting number is not zero, so output 1 + 10*(n - 1) + 9 // (this is decodable, as d is in [1-9] and e is in [0-9]) uint64_t CTxOutCompressor::CompressAmount(uint64_t n) { if (n == 0) return 0; int e = 0; while (((n % 10) == 0) && e < 9) { n /= 10; e++; } if (e < 9) { int d = (n % 10); assert(d >= 1 && d <= 9); n /= 10; return 1 + (n*9 + d - 1)*10 + e; } else { return 1 + (n - 1)*10 + 9; } } uint64_t CTxOutCompressor::DecompressAmount(uint64_t x) { // x = 0 OR x = 1+10*(9*n + d - 1) + e OR x = 1+10*(n - 1) + 9 if (x == 0) return 0; x--; // x = 10*(9*n + d - 1) + e int e = x % 10; x /= 10; uint64_t n = 0; if (e < 9) { // x = 9*n + d - 1 int d = (x % 9) + 1; x /= 9; // x = n n = x*10 + d; } else { n = x+1; } while (e) { n *= 10; e--; } return n; } /*uint256 CBlockHeader::GetHash() const { CChain a1; int nHeight= a1.Height(); //pblock->LastHeight = pindexPrev->nHeight; if (nHeight <=10){ return HashX11(BEGIN(nVersion), END(nNonce)); } else { return HashX17(BEGIN(nVersion), END(nNonce)); } }*/ uint256 CBlockHeader::GetHashX11() const { return HashX11(BEGIN(nVersion), END(nNonce)); } uint256 CBlock::BuildMerkleTree() const { vMerkleTree.clear(); BOOST_FOREACH(const CTransaction& tx, vtx) vMerkleTree.push_back(tx.GetHash()); int j = 0; for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2) { for (int i = 0; i < nSize; i += 2) { int i2 = std::min(i+1, nSize-1); vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]), BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2]))); } j += nSize; } return (vMerkleTree.empty() ? 0 : vMerkleTree.back()); } std::vector<uint256> CBlock::GetMerkleBranch(int nIndex) const { if (vMerkleTree.empty()) BuildMerkleTree(); std::vector<uint256> vMerkleBranch; int j = 0; for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2) { int i = std::min(nIndex^1, nSize-1); vMerkleBranch.push_back(vMerkleTree[j+i]); nIndex >>= 1; j += nSize; } return vMerkleBranch; } uint256 CBlock::CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex) { if (nIndex == -1) return 0; BOOST_FOREACH(const uint256& otherside, vMerkleBranch) { if (nIndex & 1) hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash)); else hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside)); nIndex >>= 1; } return hash; } void CBlock::print() const { //GetHashX11().ToString(), LogPrintf("CBlock(hash=disable, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%u)\n", nVersion, hashPrevBlock.ToString(), hashMerkleRoot.ToString(), nTime, nBits, nNonce, vtx.size()); for (unsigned int i = 0; i < vtx.size(); i++) { LogPrintf(" "); vtx[i].print(); } LogPrintf(" vMerkleTree: "); for (unsigned int i = 0; i < vMerkleTree.size(); i++) LogPrintf("%s ", vMerkleTree[i].ToString()); LogPrintf("\n"); } <|endoftext|>
<commit_before>// ----------------------------------------------------------------------------- // // MIT License // // Copyright (c) 2016 Alberto Sola // // 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 "date.hpp" #include <iostream> char Date::separator = '/'; // ----------------------------------------------------------------------------- Date::Date(){ set_date(0,0,0); } // ----------------------------------------------------------------------------- Date::Date(const std::string & date){ set_from_str(date); } // ----------------------------------------------------------------------------- void Date::set_date(short int iday, short int imonth, int iyear){ day = iday; month = imonth; year = iyear; } // ----------------------------------------------------------------------------- short int Date::get_day() const{ return day; } // ----------------------------------------------------------------------------- short int Date::get_month() const{ return month; } // ----------------------------------------------------------------------------- int Date::get_year() const{ return year; } // ----------------------------------------------------------------------------- void Date::set_day(short int iday){ day = iday; } // ----------------------------------------------------------------------------- void Date::set_month(short int imonth){ month = imonth; } // ----------------------------------------------------------------------------- void Date::set_year(int iyear){ year = iyear; } // ----------------------------------------------------------------------------- void Date::set_current(){ const int BASE_YEAR = 1900; std::time_t time_ = std::time(nullptr); std::tm * current_time = std::localtime(&time_); day = current_time->tm_mday; month = current_time->tm_mon; year = BASE_YEAR + current_time->tm_year; } // ----------------------------------------------------------------------------- void Date::set_from_str(const std::string & date){ //TODO: improve std::vector<std::string> date_parts; std::string word = ""; for( auto c: date ){ if( c == separator ){ date_parts.push_back(word); word = ""; } else word += c; } date_parts.push_back(word); day = std::stoi(date_parts[0]); month = std::stoi(date_parts[1]); year = std::stoi(date_parts[2]); } // ----------------------------------------------------------------------------- std::string Date::to_str() const{ std::string date = ""; date += std::to_string(day); date += separator; date += std::to_string(month); date += separator; date += std::to_string(year); return date; } // ----------------------------------------------------------------------------- bool Date::empty() const{ return day == 0 || month == 0 || year == 0; } // ----------------------------------------------------------------------------- Date & Date::operator=(const Date & date){ day = date.day; month = date.month; year = date.year; return (*this); } // ----------------------------------------------------------------------------- <commit_msg>Month bug fixed.<commit_after>// ----------------------------------------------------------------------------- // // MIT License // // Copyright (c) 2016 Alberto Sola // // 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 "date.hpp" #include <iostream> char Date::separator = '/'; // ----------------------------------------------------------------------------- Date::Date(){ set_date(0,0,0); } // ----------------------------------------------------------------------------- Date::Date(const std::string & date){ set_from_str(date); } // ----------------------------------------------------------------------------- void Date::set_date(short int iday, short int imonth, int iyear){ day = iday; month = imonth; year = iyear; } // ----------------------------------------------------------------------------- short int Date::get_day() const{ return day; } // ----------------------------------------------------------------------------- short int Date::get_month() const{ return month; } // ----------------------------------------------------------------------------- int Date::get_year() const{ return year; } // ----------------------------------------------------------------------------- void Date::set_day(short int iday){ day = iday; } // ----------------------------------------------------------------------------- void Date::set_month(short int imonth){ month = imonth; } // ----------------------------------------------------------------------------- void Date::set_year(int iyear){ year = iyear; } // ----------------------------------------------------------------------------- void Date::set_current(){ const int BASE_YEAR = 1900; std::time_t time_ = std::time(nullptr); std::tm * current_time = std::localtime(&time_); day = current_time->tm_mday; month = current_time->tm_mon + 1; year = BASE_YEAR + current_time->tm_year; } // ----------------------------------------------------------------------------- void Date::set_from_str(const std::string & date){ //TODO: improve std::vector<std::string> date_parts; std::string word = ""; for( auto c: date ){ if( c == separator ){ date_parts.push_back(word); word = ""; } else word += c; } date_parts.push_back(word); day = std::stoi(date_parts[0]); month = std::stoi(date_parts[1]); year = std::stoi(date_parts[2]); } // ----------------------------------------------------------------------------- std::string Date::to_str() const{ std::string date = ""; date += std::to_string(day); date += separator; date += std::to_string(month); date += separator; date += std::to_string(year); return date; } // ----------------------------------------------------------------------------- bool Date::empty() const{ return day == 0 || month == 0 || year == 0; } // ----------------------------------------------------------------------------- Date & Date::operator=(const Date & date){ day = date.day; month = date.month; year = date.year; return (*this); } // ----------------------------------------------------------------------------- <|endoftext|>
<commit_before> #define DECLSPEC_EXPORT __declspec(dllexport) #define WINAPI __stdcall #include <ctime> #include "tetris_core.h" #include "random.h" #include "search_simple.h" #include "ai_easy.h" #include "rule_st.h" //for https://misakamm.com/blog/504 m_tetris::TetrisEngine<rule_st::TetrisRule, ai_easy::AI,search_simple::Search> tetris_ai; extern "C" void attach_init() { ege::mtsrand(unsigned int(time(nullptr))); } //AI֣ʾڽ extern "C" DECLSPEC_EXPORT char const *WINAPI Name() { static std::string name = "ai demo (random)"; return name.c_str(); } namespace demo { using namespace m_tetris; double eval(TetrisNode const *node, TetrisMap const &map, TetrisMap const &src_map, size_t clear) { return clear * 100 + ege::mtdrand() * 100; } } /* * path ڽղ̲أַ * 'l': һ * 'r': һ * 'd': һ * 'L': Ƶͷ * 'R': Ƶͷ * 'D': Ƶףճϣɼƶ * 'z': ʱת * 'c': ˳ʱת * ַĩβҪ'\0'ʾزӲ䣩 * * ֧·Ҫ˺ֻʹһĻɾ */ extern "C" DECLSPEC_EXPORT int WINAPI AIPath(int boardW, int boardH, char board[], char curPiece, int curX, int curY, int curR, char nextPiece, char path[]) { if(!tetris_ai.prepare(boardW, boardH)) { return 0; } tetris_ai.ai_config()->eval_func = demo::eval; tetris_ai.ai_config()->str_name = "Demo Random AI"; m_tetris::TetrisMap map(boardW, boardH); for(int y = 0, add = 0; y < boardH; ++y, add += boardW) { for(int x = 0; x < boardW; ++x) { if(board[x + add] == '1') { map.top[x] = map.roof = y + 1; map.row[y] |= 1 << x; ++map.count; } } } m_tetris::TetrisBlockStatus status(curPiece, curX - 1, curY - 1, curR - 1); size_t next_length = nextPiece == ' ' ? 0 : 1; m_tetris::TetrisNode const *node = tetris_ai.get(status); auto target = tetris_ai.run(map, node, &nextPiece, next_length, 49).target; if(target != nullptr) { std::vector<char> ai_path = tetris_ai.make_path(node, target, map); memcpy(path, ai_path.data(), ai_path.size()); path[ai_path.size()] = '\0'; } return 0; } <commit_msg>demo调整<commit_after> #define DECLSPEC_EXPORT __declspec(dllexport) #define WINAPI __stdcall #include <ctime> #include "tetris_core.h" #include "random.h" #include "search_simple.h" #include "ai_easy.h" #include "rule_st.h" //for https://misakamm.com/blog/504 m_tetris::TetrisEngine<rule_st::TetrisRule, ai_easy::AI,search_simple::Search> tetris_ai; extern "C" void attach_init() { ege::mtsrand(unsigned int(time(nullptr))); } //AI֣ʾڽ extern "C" DECLSPEC_EXPORT char const *WINAPI Name() { static std::string name = tetris_ai.ai_name(); return name.c_str(); } namespace demo { using namespace m_tetris; double eval(TetrisNode const *node, TetrisMap const &map, TetrisMap const &src_map, size_t clear) { return clear * 100 + ege::mtdrand() * 100; } } /* * path ڽղ̲أַ * 'l': һ * 'r': һ * 'd': һ * 'L': Ƶͷ * 'R': Ƶͷ * 'D': Ƶףճϣɼƶ * 'z': ʱת * 'c': ˳ʱת * ַĩβҪ'\0'ʾزӲ䣩 * * ֧·Ҫ˺ֻʹһĻɾ */ extern "C" DECLSPEC_EXPORT int WINAPI AIPath(int boardW, int boardH, char board[], char curPiece, int curX, int curY, int curR, char nextPiece, char path[]) { if(!tetris_ai.prepare(boardW, boardH)) { return 0; } tetris_ai.ai_config()->eval_func = demo::eval; tetris_ai.ai_config()->str_name = "Demo Random AI"; m_tetris::TetrisMap map(boardW, boardH); for(int y = 0, add = 0; y < boardH; ++y, add += boardW) { for(int x = 0; x < boardW; ++x) { if(board[x + add] == '1') { map.top[x] = map.roof = y + 1; map.row[y] |= 1 << x; ++map.count; } } } m_tetris::TetrisBlockStatus status(curPiece, curX - 1, curY - 1, curR - 1); size_t next_length = nextPiece == ' ' ? 0 : 1; m_tetris::TetrisNode const *node = tetris_ai.get(status); auto target = tetris_ai.run(map, node, &nextPiece, next_length, 49).target; if(target != nullptr) { std::vector<char> ai_path = tetris_ai.make_path(node, target, map); memcpy(path, ai_path.data(), ai_path.size()); path[ai_path.size()] = '\0'; } return 0; } <|endoftext|>
<commit_before>#include <algorithm> #include "draw.hpp" #include "logics.hpp" SDL_Renderer * _render = NULL; void draw_init( SDL_Renderer * render ) { _render = render; } Uint32 get_coloru( void ) { Uint8 r, g, b; SDL_GetRenderDrawColor( _render, &r, &g, &b, NULL ); return ( r << 16 ) + ( g << 8 ) + b; } int set_coloru( Uint32 color ) { Uint8 r, ro, g, go, b, bo, ao; r = ( color >> 16 ); g = ( ( color >> 8 ) & 0xff ); b = ( color & 0xff ); SDL_GetRenderDrawColor( _render, &ro, &go, &bo, &ao ); return SDL_SetRenderDrawColor( _render, r, g, b, 0xff ); } int set_color3u( Uint8 red, Uint8 green, Uint8 blue ) { Uint8 ro, go, bo, ao; SDL_GetRenderDrawColor( _render, &ro, &go, &bo, &ao ); return SDL_SetRenderDrawColor( _render, red, green, blue, 0xff ); } int set_color4u( Uint8 red, Uint8 green, Uint8 blue, Uint8 alpha ) { Uint8 ro, go, bo, ao; SDL_GetRenderDrawColor( _render, &ro, &go, &bo, &ao ); return SDL_SetRenderDrawColor( _render, red, green, blue, alpha ); } int draw_aaline( int x1, int y1, int x2, int y2 ) { Uint32 intshift, erracc, erradj, erracctmp, wgt; int dx, dy, tmp, xdir, y0p1, x0pxdir, result; Sint32 xx0, yy0, xx1, yy1; Uint8 r, g, b, a; result = SDL_GetRenderDrawColor( _render, &r, &g, &b, &a ); xx0 = x1; yy0 = y1; xx1 = x2; yy1 = y2; if ( yy0 > yy1 ) { tmp = yy0; yy0 = yy1; yy1 = tmp; tmp = xx0; xx0 = xx1; xx1 = tmp; } dx = xx1 - xx0; dy = yy1 - yy0; if ( dx == 0 || dy == 0 ) { return SDL_RenderDrawLine( _render, x1, y1, x2, y2 ); } xdir = 1; if ( dx < 0 ) { xdir = -1; dx = -dx; } erracc = 0; intshift = 24; result |= set_color3u( r, g, b ); result |= SDL_RenderDrawPoint( _render, x1, y1 ); if ( dy > dx ) { erradj = ( ( dx << 16 ) / dy ) << 16; x0pxdir = xx0 + xdir; while ( --dy ) { erracctmp = erracc; erracc += erradj; if ( erracc <= erracctmp ) { xx0 = x0pxdir; x0pxdir += xdir; } yy0++; wgt = ( erracc >> intshift ) & 255; result |= set_color4u( r, g, b, 255 - wgt ); result |= SDL_RenderDrawPoint( _render, xx0, yy0 ); result |= set_color4u( r, g, b, wgt ); result |= SDL_RenderDrawPoint( _render, x0pxdir, yy0 ); } } else { erradj = ( ( dy << 16 ) / dx ) << 16; y0p1 = yy0 + 1; while ( --dx ) { erracctmp = erracc; erracc += erradj; if ( erracc <= erracctmp ) { yy0 = y0p1; y0p1++; } xx0 += xdir; wgt = ( erracc >> intshift ) & 255; result |= set_color4u( r, g, b, 255 - wgt ); result |= SDL_RenderDrawPoint( _render, xx0, yy0 ); result |= set_color4u( r, g, b, wgt ); result |= SDL_RenderDrawPoint( _render, xx0, y0p1 ); } } return result; } void draw_path(vec3s n, SDL_Point center, std::vector<vec3s> vs) { // отрисовываем путь // пока без проверки невидимых линий SDL_Point prev; bool pe = false; for ( auto v: vs ) { if ( visible ( n, v ) ) { SDL_Point cur = surf_to_screen( n, v, center); if ( pe ) draw_aaline( prev.x, prev.y, cur.x, cur.y ); prev = cur; pe = true; } else pe = false; } } void draw_sphere( vec3s n, SDL_Point center, float R, field & f ) { Uint32 color = get_coloru(); // отрисуем все клетки для теста set_color3u(255, 0, 255); for ( size_t i = 0; i < f.f.size(); i++ ) { for ( size_t j = 0; j < f.f[i].size(); j++ ) { if ( f.f[i][j] ) { auto cc = cell_contour( { (int)i, (int)j }, f, 32 ); SDL_Point sc[cc.size()]; for (std::size_t i = 0; i < cc.size(); ++i) { cc[i].r = R; sc[i] = surf_to_screen( n, cc[i], center); } if ( n * cc[0] >= 0 ) { // так не видно косяков // if ( visible( n, cc[0] ) ) { draw_filled_polygon( sc, 32 ); } } } } set_coloru( color ); // набор точек от 0 до 2pi int size = 65; std::vector<vec3s> v(size); for (int i = 0; i < size; ++i) { v[i].r = R; v[i].theta = 2 * M_PI * i / (size - 1); } // меридианы for ( unsigned int i = 0; i < f.width; ++i ) { float p = i * 2 * M_PI / f.width; for (int i = 0; i < size; ++i) {v[i].phi = p;}; draw_path( n, center, v); } for (int i = 0; i < size; ++i) {v[i].phi = 2 * M_PI * i / (size - 1);} // широты for ( unsigned int i = 1; i < f.height; ++i ) { float p = i * M_PI / f.height; for (int i = 0; i < size; ++i) {v[i].theta = p;}; draw_path( n, center, v); } // оси координат (для проверки корректности отрисовки) set_color3u(255, 0, 0); draw_path( n, center, {{0,0,0}, {1.2f*R, M_PI/2, 0}}); set_color3u(0, 255, 0); draw_path( n, center, {{0,0,0}, {1.2f*R, M_PI/2, M_PI / 2}}); set_color3u(0, 0, 255); draw_path( n, center, {{0,0,0}, {1.2f*R, 0, 0}}); } int draw_filled_polygon( const SDL_Point* vs, const int n ) { int min_y, max_y, result, counts; int ind1, ind2, x1, x2, y1, y2; int * polygons = new int [n]; int xa, xb; if ( vs == nullptr || n < 3 ) { return -1; } // нужно тестирование min_y = std::min_element( vs, vs + n, [](const SDL_Point & a, const SDL_Point & b) { return a.y < b.y; } ) -> y; max_y = std::max_element( vs, vs + n, [](const SDL_Point & a, const SDL_Point & b) { return a.y < b.y; } ) -> y; result = 0; for ( int y = min_y; y < max_y; y++ ) { counts = 0; for ( int i = 0; i < n; i++ ) { if ( !i ) { ind1 = n - 1; ind2 = 0; } else { ind1 = i - 1; ind2 = i; } y1 = vs[ind1].y; y2 = vs[ind2].y; if ( y1 < y2 ) { x1 = vs[ind1].x; x2 = vs[ind2].x; } else if ( y1 > y2 ) { y2 = vs[ind1].y; y1 = vs[ind2].y; x2 = vs[ind1].x; x1 = vs[ind2].x; } else { continue; } if ( ( ( y >= y1 ) && ( y < y2 ) ) || ( ( y == max_y ) && ( y > y1 ) && ( y <= y2 ) ) ) { polygons[counts++] = ( ( 65536 * ( y - y1 ) ) / ( y2 - y1 ) ) * ( x2 - x1 ) + ( 65536 * x1 ); } } std::sort( polygons, polygons + counts ); result = 0; for ( int i = 0; i < counts; i += 2 ) { xa = polygons[i+0] + 1; xb = polygons[i+1] - 1; xa = ( xa >> 16 ) + ( ( xa & 32768 ) >> 15 ); xb = ( xb >> 16 ) + ( ( xb & 32768 ) >> 15 ); result |= SDL_RenderDrawLine( _render, xa, y, xb, y ); } } delete[] polygons; return result; } <commit_msg>[fix] working with visible<commit_after>#include <algorithm> #include "draw.hpp" #include "logics.hpp" SDL_Renderer * _render = NULL; void draw_init( SDL_Renderer * render ) { _render = render; } Uint32 get_coloru( void ) { Uint8 r, g, b; SDL_GetRenderDrawColor( _render, &r, &g, &b, NULL ); return ( r << 16 ) + ( g << 8 ) + b; } int set_coloru( Uint32 color ) { Uint8 r, ro, g, go, b, bo, ao; r = ( color >> 16 ); g = ( ( color >> 8 ) & 0xff ); b = ( color & 0xff ); SDL_GetRenderDrawColor( _render, &ro, &go, &bo, &ao ); return SDL_SetRenderDrawColor( _render, r, g, b, 0xff ); } int set_color3u( Uint8 red, Uint8 green, Uint8 blue ) { Uint8 ro, go, bo, ao; SDL_GetRenderDrawColor( _render, &ro, &go, &bo, &ao ); return SDL_SetRenderDrawColor( _render, red, green, blue, 0xff ); } int set_color4u( Uint8 red, Uint8 green, Uint8 blue, Uint8 alpha ) { Uint8 ro, go, bo, ao; SDL_GetRenderDrawColor( _render, &ro, &go, &bo, &ao ); return SDL_SetRenderDrawColor( _render, red, green, blue, alpha ); } int draw_aaline( int x1, int y1, int x2, int y2 ) { Uint32 intshift, erracc, erradj, erracctmp, wgt; int dx, dy, tmp, xdir, y0p1, x0pxdir, result; Sint32 xx0, yy0, xx1, yy1; Uint8 r, g, b, a; result = SDL_GetRenderDrawColor( _render, &r, &g, &b, &a ); xx0 = x1; yy0 = y1; xx1 = x2; yy1 = y2; if ( yy0 > yy1 ) { tmp = yy0; yy0 = yy1; yy1 = tmp; tmp = xx0; xx0 = xx1; xx1 = tmp; } dx = xx1 - xx0; dy = yy1 - yy0; if ( dx == 0 || dy == 0 ) { return SDL_RenderDrawLine( _render, x1, y1, x2, y2 ); } xdir = 1; if ( dx < 0 ) { xdir = -1; dx = -dx; } erracc = 0; intshift = 24; result |= set_color3u( r, g, b ); result |= SDL_RenderDrawPoint( _render, x1, y1 ); if ( dy > dx ) { erradj = ( ( dx << 16 ) / dy ) << 16; x0pxdir = xx0 + xdir; while ( --dy ) { erracctmp = erracc; erracc += erradj; if ( erracc <= erracctmp ) { xx0 = x0pxdir; x0pxdir += xdir; } yy0++; wgt = ( erracc >> intshift ) & 255; result |= set_color4u( r, g, b, 255 - wgt ); result |= SDL_RenderDrawPoint( _render, xx0, yy0 ); result |= set_color4u( r, g, b, wgt ); result |= SDL_RenderDrawPoint( _render, x0pxdir, yy0 ); } } else { erradj = ( ( dy << 16 ) / dx ) << 16; y0p1 = yy0 + 1; while ( --dx ) { erracctmp = erracc; erracc += erradj; if ( erracc <= erracctmp ) { yy0 = y0p1; y0p1++; } xx0 += xdir; wgt = ( erracc >> intshift ) & 255; result |= set_color4u( r, g, b, 255 - wgt ); result |= SDL_RenderDrawPoint( _render, xx0, yy0 ); result |= set_color4u( r, g, b, wgt ); result |= SDL_RenderDrawPoint( _render, xx0, y0p1 ); } } return result; } void draw_path(vec3s n, SDL_Point center, std::vector<vec3s> vs) { // отрисовываем путь // пока без проверки невидимых линий SDL_Point prev; bool pe = false; for ( auto v: vs ) { if ( visible ( n, v ) ) { SDL_Point cur = surf_to_screen( n, v, center); if ( pe ) draw_aaline( prev.x, prev.y, cur.x, cur.y ); prev = cur; pe = true; } else pe = false; } } void draw_sphere( vec3s n, SDL_Point center, float R, field & f ) { Uint32 color = get_coloru(); // отрисуем все клетки для теста set_color3u(255, 0, 255); for ( size_t i = 0; i < f.f.size(); i++ ) { for ( size_t j = 0; j < f.f[i].size(); j++ ) { if ( f.f[i][j] ) { auto cc = cell_contour( { (int)i, (int)j }, f, 32 ); if ( n * cc[0] >= 0 ) { // так не видно косяков // if ( visible( n, cc[0] ) ) { SDL_Point sc[cc.size()]; for (std::size_t i = 0; i < cc.size(); ++i) { cc[i].r = R; sc[i] = surf_to_screen( n, cc[i], center); } draw_filled_polygon( sc, 32 ); } } } } set_coloru( color ); // набор точек от 0 до 2pi int size = 65; std::vector<vec3s> v(size); for (int i = 0; i < size; ++i) { v[i].r = R; v[i].theta = 2 * M_PI * i / (size - 1); } // меридианы for ( unsigned int i = 0; i < f.width; ++i ) { float p = i * 2 * M_PI / f.width; for (int i = 0; i < size; ++i) {v[i].phi = p;}; draw_path( n, center, v); } for (int i = 0; i < size; ++i) {v[i].phi = 2 * M_PI * i / (size - 1);} // широты for ( unsigned int i = 1; i < f.height; ++i ) { float p = i * M_PI / f.height; for (int i = 0; i < size; ++i) {v[i].theta = p;}; draw_path( n, center, v); } // оси координат (для проверки корректности отрисовки) set_color3u(255, 0, 0); draw_path( n, center, {{0,0,0}, {1.2f*R, M_PI/2, 0}}); set_color3u(0, 255, 0); draw_path( n, center, {{0,0,0}, {1.2f*R, M_PI/2, M_PI / 2}}); set_color3u(0, 0, 255); draw_path( n, center, {{0,0,0}, {1.2f*R, 0, 0}}); } int draw_filled_polygon( const SDL_Point* vs, const int n ) { int min_y, max_y, result, counts; int ind1, ind2, x1, x2, y1, y2; int * polygons = new int [n]; int xa, xb; if ( vs == nullptr || n < 3 ) { return -1; } // нужно тестирование min_y = std::min_element( vs, vs + n, [](const SDL_Point & a, const SDL_Point & b) { return a.y < b.y; } ) -> y; max_y = std::max_element( vs, vs + n, [](const SDL_Point & a, const SDL_Point & b) { return a.y < b.y; } ) -> y; result = 0; for ( int y = min_y; y < max_y; y++ ) { counts = 0; for ( int i = 0; i < n; i++ ) { if ( !i ) { ind1 = n - 1; ind2 = 0; } else { ind1 = i - 1; ind2 = i; } y1 = vs[ind1].y; y2 = vs[ind2].y; if ( y1 < y2 ) { x1 = vs[ind1].x; x2 = vs[ind2].x; } else if ( y1 > y2 ) { y2 = vs[ind1].y; y1 = vs[ind2].y; x2 = vs[ind1].x; x1 = vs[ind2].x; } else { continue; } if ( ( ( y >= y1 ) && ( y < y2 ) ) || ( ( y == max_y ) && ( y > y1 ) && ( y <= y2 ) ) ) { polygons[counts++] = ( ( 65536 * ( y - y1 ) ) / ( y2 - y1 ) ) * ( x2 - x1 ) + ( 65536 * x1 ); } } std::sort( polygons, polygons + counts ); result = 0; for ( int i = 0; i < counts; i += 2 ) { xa = polygons[i+0] + 1; xb = polygons[i+1] - 1; xa = ( xa >> 16 ) + ( ( xa & 32768 ) >> 15 ); xb = ( xb >> 16 ) + ( ( xb & 32768 ) >> 15 ); result |= SDL_RenderDrawLine( _render, xa, y, xb, y ); } } delete[] polygons; return result; } <|endoftext|>
<commit_before>#include <stdio.h> #include <limits.h> #include <string.h> #include <unistd.h> #include <string> #include "globals.h" #include "profiler.h" #include "stacktraces.h" static Profiler *prof; FILE *Globals::OutFile; void JNICALL OnThreadStart(jvmtiEnv *jvmti_env, JNIEnv *jni_env, jthread thread) { IMPLICITLY_USE(jvmti_env); IMPLICITLY_USE(thread); Accessors::SetCurrentJniEnv(jni_env); } void JNICALL OnThreadEnd(jvmtiEnv *jvmti_env, JNIEnv *jni_env, jthread thread) { IMPLICITLY_USE(jvmti_env); IMPLICITLY_USE(jni_env); IMPLICITLY_USE(thread); } // This has to be here, or the VM turns off class loading events. // And AsyncGetCallTrace needs class loading events to be turned on! void JNICALL OnClassLoad(jvmtiEnv *jvmti_env, JNIEnv *jni_env, jthread thread, jclass klass) { IMPLICITLY_USE(jvmti_env); IMPLICITLY_USE(jni_env); IMPLICITLY_USE(thread); IMPLICITLY_USE(klass); } // Calls GetClassMethods on a given class to force the creation of // jmethodIDs of it. void CreateJMethodIDsForClass(jvmtiEnv *jvmti, jclass klass) { jint method_count; JvmtiScopedPtr<jmethodID> methods(jvmti); jvmtiError e = jvmti->GetClassMethods(klass, &method_count, methods.GetRef()); if (e != JVMTI_ERROR_NONE && e != JVMTI_ERROR_CLASS_NOT_PREPARED) { // JVMTI_ERROR_CLASS_NOT_PREPARED is okay because some classes may // be loaded but not prepared at this point. JvmtiScopedPtr<char> ksig(jvmti); JVMTI_ERROR((jvmti->GetClassSignature(klass, ksig.GetRef(), NULL))); fprintf( stderr, "Failed to create method IDs for methods in class %s with error %d ", ksig.Get(), e); } } void JNICALL OnVMInit(jvmtiEnv *jvmti, JNIEnv *jni_env, jthread thread) { IMPLICITLY_USE(thread); IMPLICITLY_USE(jni_env); // Forces the creation of jmethodIDs of the classes that had already // been loaded (eg java.lang.Object, java.lang.ClassLoader) and // OnClassPrepare() misses. jint class_count; JvmtiScopedPtr<jclass> classes(jvmti); JVMTI_ERROR((jvmti->GetLoadedClasses(&class_count, classes.GetRef()))); jclass *classList = classes.Get(); for (int i = 0; i < class_count; ++i) { jclass klass = classList[i]; CreateJMethodIDsForClass(jvmti, klass); } prof->Start(); } void JNICALL OnClassPrepare(jvmtiEnv *jvmti_env, JNIEnv *jni_env, jthread thread, jclass klass) { IMPLICITLY_USE(jni_env); IMPLICITLY_USE(thread); // We need to do this to "prime the pump", as it were -- make sure // that all of the methodIDs have been initialized internally, for // AsyncGetCallTrace. I imagine it slows down class loading a mite, // but honestly, how fast does class loading have to be? CreateJMethodIDsForClass(jvmti_env, klass); } void JNICALL OnVMDeath(jvmtiEnv *jvmti_env, JNIEnv *jni_env) { IMPLICITLY_USE(jvmti_env); IMPLICITLY_USE(jni_env); prof->Stop(); prof->DumpToFile(Globals::OutFile); } static bool PrepareJvmti(jvmtiEnv *jvmti) { // Set the list of permissions to do the various internal VM things // we want to do. jvmtiCapabilities caps; memset(&caps, 0, sizeof(caps)); caps.can_generate_all_class_hook_events = 1; caps.can_get_source_file_name = 1; caps.can_get_line_numbers = 1; caps.can_get_bytecodes = 1; caps.can_get_constant_pool = 1; jvmtiCapabilities all_caps; int error; if (JVMTI_ERROR_NONE == (error = jvmti->GetPotentialCapabilities(&all_caps))) { // This makes sure that if we need a capability, it is one of the // potential capabilities. The technique isn't wonderful, but it // is compact and as likely to be compatible between versions as // anything else. char *has = reinterpret_cast<char *>(&all_caps); const char *should_have = reinterpret_cast<const char *>(&caps); for (int i = 0; i < sizeof(all_caps); i++) { if ((should_have[i] != 0) && (has[i] == 0)) { return false; } } // This adds the capabilities. if ((error = jvmti->AddCapabilities(&caps)) != JVMTI_ERROR_NONE) { fprintf(stderr, "Failed to add capabilities with error %d\n", error); return false; } } return true; } static bool RegisterJvmti(jvmtiEnv *jvmti) { // Create the list of callbacks to be called on given events. jvmtiEventCallbacks *callbacks = new jvmtiEventCallbacks(); memset(callbacks, 0, sizeof(jvmtiEventCallbacks)); callbacks->ThreadStart = &OnThreadStart; callbacks->ThreadEnd = &OnThreadEnd; callbacks->VMInit = &OnVMInit; callbacks->VMDeath = &OnVMDeath; callbacks->ClassLoad = &OnClassLoad; callbacks->ClassPrepare = &OnClassPrepare; JVMTI_ERROR_1( (jvmti->SetEventCallbacks(callbacks, sizeof(jvmtiEventCallbacks))), false); jvmtiEvent events[] = {JVMTI_EVENT_CLASS_LOAD, JVMTI_EVENT_CLASS_PREPARE, JVMTI_EVENT_THREAD_END, JVMTI_EVENT_THREAD_START, JVMTI_EVENT_VM_DEATH, JVMTI_EVENT_VM_INIT}; size_t num_events = sizeof(events) / sizeof(jvmtiEvent); // Enable the callbacks to be triggered when the events occur. // Events are enumerated in jvmstatagent.h for (int i = 0; i < num_events; i++) { JVMTI_ERROR_1( (jvmti->SetEventNotificationMode(JVMTI_ENABLE, events[i], NULL)), false); } return true; } #define POSITIVE(x) (static_cast<size_t>(x > 0 ? x : 0)) static void SetFileFromOption(char *equals) { char *name_begin = equals + 1; char *name_end; if ((name_end = strchr(equals, ',')) == NULL) { name_end = equals + strlen(equals); } size_t len = POSITIVE(name_end - name_begin); char *file_name = new char[len]; strncpy(file_name, name_begin, len); if (strcmp(file_name, "stderr") == 0) { Globals::OutFile = stderr; } else if (strcmp(file_name, "stdout") == 0) { Globals::OutFile = stdout; } else { Globals::OutFile = fopen(file_name, "w+"); if (Globals::OutFile == NULL) { fprintf(stderr, "Could not open file %s: ", file_name); perror(NULL); exit(1); } } delete[] file_name; } static void ParseArguments(char *options) { char *key = options; for (char *next = options; next != NULL; next = strchr((key = next + 1), ',')) { char *equals = strchr(key, '='); if (equals == NULL) { fprintf(stderr, "No value for key %s\n", key); continue; } if (strncmp(key, "file", POSITIVE(equals - key)) == 0) { SetFileFromOption(equals); } } if (Globals::OutFile == NULL) { char path[PATH_MAX]; if (getcwd(path, PATH_MAX) == NULL) { fprintf(stderr, "cwd too long?\n"); exit(0); } size_t pathlen = strlen(path); strncat(path, "/", PATH_MAX - (pathlen++)); strncat(path, kDefaultOutFile, PATH_MAX - pathlen); Globals::OutFile = fopen(path, "w+"); } } AGENTEXPORT jint JNICALL Agent_OnLoad(JavaVM *vm, char *options, void *reserved) { IMPLICITLY_USE(reserved); int err; jvmtiEnv *jvmti; ParseArguments(options); Accessors::Init(); if ((err = (vm->GetEnv(reinterpret_cast<void **>(&jvmti), JVMTI_VERSION))) != JNI_OK) { fprintf(stderr, "JNI Error %d\n", err); return 1; } if (!PrepareJvmti(jvmti)) { fprintf(stderr, "Failed to initialize JVMTI. Continuing...\n"); return 0; } if (!RegisterJvmti(jvmti)) { fprintf(stderr, "Failed to enable JVMTI events. Continuing...\n"); // We fail hard here because we may have failed in the middle of // registering callbacks, which will leave the system in an // inconsistent state. return 1; } Asgct::SetAsgct(Accessors::GetJvmFunction<ASGCTType>("AsyncGetCallTrace")); prof = new Profiler(jvmti); return 0; } AGENTEXPORT void JNICALL Agent_OnUnload(JavaVM *vm) { IMPLICITLY_USE(vm); Accessors::Destroy(); } <commit_msg>fix bug: when using with hadoop profile, filename get garbled<commit_after>#include <stdio.h> #include <limits.h> #include <string.h> #include <unistd.h> #include <string> #include "globals.h" #include "profiler.h" #include "stacktraces.h" static Profiler *prof; FILE *Globals::OutFile; void JNICALL OnThreadStart(jvmtiEnv *jvmti_env, JNIEnv *jni_env, jthread thread) { IMPLICITLY_USE(jvmti_env); IMPLICITLY_USE(thread); Accessors::SetCurrentJniEnv(jni_env); } void JNICALL OnThreadEnd(jvmtiEnv *jvmti_env, JNIEnv *jni_env, jthread thread) { IMPLICITLY_USE(jvmti_env); IMPLICITLY_USE(jni_env); IMPLICITLY_USE(thread); } // This has to be here, or the VM turns off class loading events. // And AsyncGetCallTrace needs class loading events to be turned on! void JNICALL OnClassLoad(jvmtiEnv *jvmti_env, JNIEnv *jni_env, jthread thread, jclass klass) { IMPLICITLY_USE(jvmti_env); IMPLICITLY_USE(jni_env); IMPLICITLY_USE(thread); IMPLICITLY_USE(klass); } // Calls GetClassMethods on a given class to force the creation of // jmethodIDs of it. void CreateJMethodIDsForClass(jvmtiEnv *jvmti, jclass klass) { jint method_count; JvmtiScopedPtr<jmethodID> methods(jvmti); jvmtiError e = jvmti->GetClassMethods(klass, &method_count, methods.GetRef()); if (e != JVMTI_ERROR_NONE && e != JVMTI_ERROR_CLASS_NOT_PREPARED) { // JVMTI_ERROR_CLASS_NOT_PREPARED is okay because some classes may // be loaded but not prepared at this point. JvmtiScopedPtr<char> ksig(jvmti); JVMTI_ERROR((jvmti->GetClassSignature(klass, ksig.GetRef(), NULL))); fprintf( stderr, "Failed to create method IDs for methods in class %s with error %d ", ksig.Get(), e); } } void JNICALL OnVMInit(jvmtiEnv *jvmti, JNIEnv *jni_env, jthread thread) { IMPLICITLY_USE(thread); IMPLICITLY_USE(jni_env); // Forces the creation of jmethodIDs of the classes that had already // been loaded (eg java.lang.Object, java.lang.ClassLoader) and // OnClassPrepare() misses. jint class_count; JvmtiScopedPtr<jclass> classes(jvmti); JVMTI_ERROR((jvmti->GetLoadedClasses(&class_count, classes.GetRef()))); jclass *classList = classes.Get(); for (int i = 0; i < class_count; ++i) { jclass klass = classList[i]; CreateJMethodIDsForClass(jvmti, klass); } prof->Start(); } void JNICALL OnClassPrepare(jvmtiEnv *jvmti_env, JNIEnv *jni_env, jthread thread, jclass klass) { IMPLICITLY_USE(jni_env); IMPLICITLY_USE(thread); // We need to do this to "prime the pump", as it were -- make sure // that all of the methodIDs have been initialized internally, for // AsyncGetCallTrace. I imagine it slows down class loading a mite, // but honestly, how fast does class loading have to be? CreateJMethodIDsForClass(jvmti_env, klass); } void JNICALL OnVMDeath(jvmtiEnv *jvmti_env, JNIEnv *jni_env) { IMPLICITLY_USE(jvmti_env); IMPLICITLY_USE(jni_env); prof->Stop(); prof->DumpToFile(Globals::OutFile); } static bool PrepareJvmti(jvmtiEnv *jvmti) { // Set the list of permissions to do the various internal VM things // we want to do. jvmtiCapabilities caps; memset(&caps, 0, sizeof(caps)); caps.can_generate_all_class_hook_events = 1; caps.can_get_source_file_name = 1; caps.can_get_line_numbers = 1; caps.can_get_bytecodes = 1; caps.can_get_constant_pool = 1; jvmtiCapabilities all_caps; int error; if (JVMTI_ERROR_NONE == (error = jvmti->GetPotentialCapabilities(&all_caps))) { // This makes sure that if we need a capability, it is one of the // potential capabilities. The technique isn't wonderful, but it // is compact and as likely to be compatible between versions as // anything else. char *has = reinterpret_cast<char *>(&all_caps); const char *should_have = reinterpret_cast<const char *>(&caps); for (int i = 0; i < sizeof(all_caps); i++) { if ((should_have[i] != 0) && (has[i] == 0)) { return false; } } // This adds the capabilities. if ((error = jvmti->AddCapabilities(&caps)) != JVMTI_ERROR_NONE) { fprintf(stderr, "Failed to add capabilities with error %d\n", error); return false; } } return true; } static bool RegisterJvmti(jvmtiEnv *jvmti) { // Create the list of callbacks to be called on given events. jvmtiEventCallbacks *callbacks = new jvmtiEventCallbacks(); memset(callbacks, 0, sizeof(jvmtiEventCallbacks)); callbacks->ThreadStart = &OnThreadStart; callbacks->ThreadEnd = &OnThreadEnd; callbacks->VMInit = &OnVMInit; callbacks->VMDeath = &OnVMDeath; callbacks->ClassLoad = &OnClassLoad; callbacks->ClassPrepare = &OnClassPrepare; JVMTI_ERROR_1( (jvmti->SetEventCallbacks(callbacks, sizeof(jvmtiEventCallbacks))), false); jvmtiEvent events[] = {JVMTI_EVENT_CLASS_LOAD, JVMTI_EVENT_CLASS_PREPARE, JVMTI_EVENT_THREAD_END, JVMTI_EVENT_THREAD_START, JVMTI_EVENT_VM_DEATH, JVMTI_EVENT_VM_INIT}; size_t num_events = sizeof(events) / sizeof(jvmtiEvent); // Enable the callbacks to be triggered when the events occur. // Events are enumerated in jvmstatagent.h for (int i = 0; i < num_events; i++) { JVMTI_ERROR_1( (jvmti->SetEventNotificationMode(JVMTI_ENABLE, events[i], NULL)), false); } return true; } #define POSITIVE(x) (static_cast<size_t>(x > 0 ? x : 0)) static void SetFileFromOption(char *equals) { char *name_begin = equals + 1; char *name_end; if ((name_end = strchr(equals, ',')) == NULL) { name_end = equals + strlen(equals); } size_t len = POSITIVE(name_end - name_begin); char *file_name = new char[len]; for(int i = 0; i < len; ++i){ file_name[i] = '\0'; } strcpy(file_name, name_begin); if (strcmp(file_name, "stderr") == 0) { Globals::OutFile = stderr; } else if (strcmp(file_name, "stdout") == 0) { Globals::OutFile = stdout; } else { Globals::OutFile = fopen(file_name, "w+"); if (Globals::OutFile == NULL) { fprintf(stderr, "Could not open file %s: ", file_name); perror(NULL); exit(1); } } delete[] file_name; } static void ParseArguments(char *options) { char *key = options; for (char *next = options; next != NULL; next = strchr((key = next + 1), ',')) { char *equals = strchr(key, '='); if (equals == NULL) { fprintf(stderr, "No value for key %s\n", key); continue; } if (strncmp(key, "file", POSITIVE(equals - key)) == 0) { SetFileFromOption(equals); } } if (Globals::OutFile == NULL) { char path[PATH_MAX]; if (getcwd(path, PATH_MAX) == NULL) { fprintf(stderr, "cwd too long?\n"); exit(0); } size_t pathlen = strlen(path); strncat(path, "/", PATH_MAX - (pathlen++)); strncat(path, kDefaultOutFile, PATH_MAX - pathlen); Globals::OutFile = fopen(path, "w+"); } } AGENTEXPORT jint JNICALL Agent_OnLoad(JavaVM *vm, char *options, void *reserved) { IMPLICITLY_USE(reserved); int err; jvmtiEnv *jvmti; ParseArguments(options); Accessors::Init(); if ((err = (vm->GetEnv(reinterpret_cast<void **>(&jvmti), JVMTI_VERSION))) != JNI_OK) { fprintf(stderr, "JNI Error %d\n", err); return 1; } if (!PrepareJvmti(jvmti)) { fprintf(stderr, "Failed to initialize JVMTI. Continuing...\n"); return 0; } if (!RegisterJvmti(jvmti)) { fprintf(stderr, "Failed to enable JVMTI events. Continuing...\n"); // We fail hard here because we may have failed in the middle of // registering callbacks, which will leave the system in an // inconsistent state. return 1; } Asgct::SetAsgct(Accessors::GetJvmFunction<ASGCTType>("AsyncGetCallTrace")); prof = new Profiler(jvmti); return 0; } AGENTEXPORT void JNICALL Agent_OnUnload(JavaVM *vm) { IMPLICITLY_USE(vm); Accessors::Destroy(); } <|endoftext|>
<commit_before>#include "eval.h" #include <cmath> #include <vector> uint64_t primitive_polynomial(unsigned degree) { static const std::vector<uint64_t> primitive_polynomials( { 0, 0x3, 0x7, 0xb, 0x13, 0x25, 0x43 }); return primitive_polynomials.at(degree); } static double sigma(const double eb_n0, const double R) { return 1.0f / sqrt((2 * R * pow(10, eb_n0 / 10.0))); } std::tuple<std::vector<int>, std::vector<float>, unsigned> pzg_wrapper(const bch &code, const std::vector<float> &b) { std::vector<int> hard; hard.reserve(b.size()); std::transform(std::cbegin(b), std::cend(b), std::back_inserter(hard), [](const auto &bit) { return bit < 0; }); auto b_corr = code.correct_peterson(hard); return std::make_tuple(b_corr, std::vector<float>(), 0); } std::tuple<std::vector<int>, std::vector<float>, unsigned> bm_wrapper(const bch &code, const std::vector<float> &b) { std::vector<int> hard; hard.reserve(b.size()); std::transform(std::cbegin(b), std::cend(b), std::back_inserter(hard), [](const auto &bit) { return bit < 0; }); auto b_corr = code.correct_bm(hard); return std::make_tuple(b_corr, std::vector<float>(), 0); } std::tuple<std::vector<int>, std::vector<float>, unsigned> uncoded(const std::vector<float> &b) { std::vector<int> hard; hard.reserve(b.size()); std::transform(std::cbegin(b), std::cend(b), std::back_inserter(hard), [](const auto &bit) { return bit < 0; }); return std::make_tuple(hard, std::vector<float>(), 0); } std::string eval_object::header() { return "reconstruction_failures " "reconstruction_errors " "wer " "fk_rate " "ber " "wer "; } std::ostream &operator<<(std::ostream &os, const eval_object &e) { os << std::scientific; const double samples_ = e.samples; os << std::setprecision(12) << e.reconstruction_failures / samples_ << " "; os << std::setprecision(12) << e.reconstruction_errors / samples_ << " "; const auto wrong_words = e.reconstruction_failures + e.reconstruction_errors; os << std::setprecision(12) << wrong_words / samples_ << " "; os << std::setprecision(12) << e.fk_corr / samples_ << " "; os << std::setprecision(12) << e.bit_errors / (samples_ * e.n); return os; } double eval_object::ber() const { return bit_errors / (double)(samples * n); } double eval_object::wer() const { return word_errors / (double)(samples); } eval_object evaluate(std::mt19937_64 &generator, const decoder_t &decoder, const size_t samples, const float eb_n0, const unsigned n, const unsigned l, const unsigned fk) { const float R = (float)l / n; unsigned reconstruction_failures = 0; unsigned reconstruction_errors = 0; unsigned fk_corr = 0; unsigned bit_errors = 0; unsigned word_errors = 0; std::vector<float> b(n); std::normal_distribution<float> random(1.0, sigma(eb_n0, R)); auto noise_gen = std::bind(std::ref(random), std::ref(generator)); for (size_t sample = 0; sample < samples; sample++) { std::generate(std::begin(b), std::end(b), noise_gen); try { auto result = decoder(b); const auto &b_corr = std::get<0>(result); auto wrong_bits = std::count_if(std::cbegin(b_corr), std::cend(b_corr), [](const auto &bit) { return bit != 0; }); if (wrong_bits) { reconstruction_errors++; bit_errors += wrong_bits; word_errors++; } else { auto d = std::count_if(std::cbegin(b), std::cend(b), [](const auto &bit) { return bit < 0; }); if (d > fk) fk_corr++; } } catch (const decoding_failure &) { reconstruction_failures++; bit_errors += n; word_errors++; } } return { eb_n0, reconstruction_failures, reconstruction_errors, fk_corr, bit_errors, word_errors, samples, n }; } <commit_msg>use ber and wer function in operator<<<commit_after>#include "eval.h" #include <cmath> #include <vector> uint64_t primitive_polynomial(unsigned degree) { static const std::vector<uint64_t> primitive_polynomials( { 0, 0x3, 0x7, 0xb, 0x13, 0x25, 0x43 }); return primitive_polynomials.at(degree); } static double sigma(const double eb_n0, const double R) { return 1.0f / sqrt((2 * R * pow(10, eb_n0 / 10.0))); } std::tuple<std::vector<int>, std::vector<float>, unsigned> pzg_wrapper(const bch &code, const std::vector<float> &b) { std::vector<int> hard; hard.reserve(b.size()); std::transform(std::cbegin(b), std::cend(b), std::back_inserter(hard), [](const auto &bit) { return bit < 0; }); auto b_corr = code.correct_peterson(hard); return std::make_tuple(b_corr, std::vector<float>(), 0); } std::tuple<std::vector<int>, std::vector<float>, unsigned> bm_wrapper(const bch &code, const std::vector<float> &b) { std::vector<int> hard; hard.reserve(b.size()); std::transform(std::cbegin(b), std::cend(b), std::back_inserter(hard), [](const auto &bit) { return bit < 0; }); auto b_corr = code.correct_bm(hard); return std::make_tuple(b_corr, std::vector<float>(), 0); } std::tuple<std::vector<int>, std::vector<float>, unsigned> uncoded(const std::vector<float> &b) { std::vector<int> hard; hard.reserve(b.size()); std::transform(std::cbegin(b), std::cend(b), std::back_inserter(hard), [](const auto &bit) { return bit < 0; }); return std::make_tuple(hard, std::vector<float>(), 0); } std::string eval_object::header() { return "reconstruction_failures " "reconstruction_errors " "wer " "fk_rate " "ber " "wer "; } std::ostream &operator<<(std::ostream &os, const eval_object &e) { os << std::scientific; const double samples_ = e.samples; os << std::setprecision(12) << e.reconstruction_failures / samples_ << " "; os << std::setprecision(12) << e.reconstruction_errors / samples_ << " "; const auto wrong_words = e.reconstruction_failures + e.reconstruction_errors; os << std::setprecision(12) << wrong_words / samples_ << " "; os << std::setprecision(12) << e.fk_corr / samples_ << " "; os << std::setprecision(12) << e.ber() << " "; os << std::setprecision(12) << e.wer(); return os; } double eval_object::ber() const { return bit_errors / (double)(samples * n); } double eval_object::wer() const { return word_errors / (double)(samples); } eval_object evaluate(std::mt19937_64 &generator, const decoder_t &decoder, const size_t samples, const float eb_n0, const unsigned n, const unsigned l, const unsigned fk) { const float R = (float)l / n; unsigned reconstruction_failures = 0; unsigned reconstruction_errors = 0; unsigned fk_corr = 0; unsigned bit_errors = 0; unsigned word_errors = 0; std::vector<float> b(n); std::normal_distribution<float> random(1.0, sigma(eb_n0, R)); auto noise_gen = std::bind(std::ref(random), std::ref(generator)); for (size_t sample = 0; sample < samples; sample++) { std::generate(std::begin(b), std::end(b), noise_gen); try { auto result = decoder(b); const auto &b_corr = std::get<0>(result); auto wrong_bits = std::count_if(std::cbegin(b_corr), std::cend(b_corr), [](const auto &bit) { return bit != 0; }); if (wrong_bits) { reconstruction_errors++; bit_errors += wrong_bits; word_errors++; } else { auto d = std::count_if(std::cbegin(b), std::cend(b), [](const auto &bit) { return bit < 0; }); if (d > fk) fk_corr++; } } catch (const decoding_failure &) { reconstruction_failures++; bit_errors += n; word_errors++; } } return { eb_n0, reconstruction_failures, reconstruction_errors, fk_corr, bit_errors, word_errors, samples, n }; } <|endoftext|>
<commit_before>/* Copyright (c) 2003, Arvid Norberg 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 author 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 <boost/filesystem/operations.hpp> #include "libtorrent/file.hpp" #include <sstream> #ifdef WIN32 #include <io.h> #include <fcntl.h> #include <sys/stat.h> #include <sys/types.h> typedef int mode_t; #else #define _FILE_OFFSET_BITS 64 #include <unistd.h> #include <fcntl.h> #include <sys/stat.h> #include <sys/types.h> #endif #ifndef O_BINARY #define O_BINARY 0 #endif #ifndef O_RANDOM #define O_RANDOM 0 #endif namespace fs = boost::filesystem; namespace { enum { mode_in = 1, mode_out = 2 }; mode_t map_open_mode(int m) { // if (m == (mode_in | mode_out)) return O_RDWR | O_BINARY; if (m == mode_out) return O_WRONLY | O_CREAT | O_BINARY | O_RANDOM; if (m == mode_in) return O_RDONLY | O_BINARY | O_RANDOM; assert(false); return 0; } } namespace libtorrent { const file::open_mode file::in(mode_in); const file::open_mode file::out(mode_out); const file::seek_mode file::begin(1); const file::seek_mode file::end(2); struct file::impl { impl() : m_fd(-1) , m_open_mode(0) {} impl(fs::path const& path, int mode) : m_fd(-1) , m_open_mode(0) { open(path, mode); } ~impl() { close(); } void open(fs::path const& path, int mode) { close(); m_fd = ::open( path.native_file_string().c_str() , map_open_mode(mode) , S_IREAD | S_IWRITE); if (m_fd == -1) { std::stringstream msg; msg << "open failed: '" << path.native_file_string() << "'. " << strerror(errno); throw file_error(msg.str()); } m_open_mode = mode; } void close() { if (m_fd == -1) return; std::stringstream str; str << "fd: " << m_fd << "\n"; ::close(m_fd); m_fd = -1; m_open_mode = 0; } size_type read(char* buf, size_type num_bytes) { assert(m_open_mode == mode_in); assert(m_fd != -1); size_type ret = ::read(m_fd, buf, num_bytes); if (ret == -1) { std::stringstream msg; msg << "read failed: " << strerror(errno); throw file_error(msg.str()); } return ret; } size_type write(const char* buf, size_type num_bytes) { assert(m_open_mode == mode_out); assert(m_fd != -1); size_type ret = ::write(m_fd, buf, num_bytes); if (ret == -1) { std::stringstream msg; msg << "write failed: " << strerror(errno); throw file_error(msg.str()); } return ret; } void seek(size_type offset, int m) { assert(m_open_mode); assert(m_fd != -1); int seekdir = (m == 1)?SEEK_SET:SEEK_END; #ifdef WIN32 size_type ret = _lseeki64(m_fd, offset, seekdir); #else size_type ret = lseek(m_fd, offset, seekdir); #endif // For some strange reason this fails // on win32. Use windows specific file // wrapper instead. if (ret == -1) { std::stringstream msg; msg << "seek failed: '" << strerror(errno) << "' fd: " << m_fd << " offset: " << offset << " seekdir: " << seekdir; throw file_error(msg.str()); } } size_type tell() { assert(m_open_mode); assert(m_fd != -1); #ifdef WIN32 return _telli64(m_fd); #else return lseek(m_fd, 0, SEEK_CUR); #endif } int m_fd; int m_open_mode; }; // pimpl forwardings file::file() : m_impl(new impl()) {} file::file(boost::filesystem::path const& p, file::open_mode m) : m_impl(new impl(p, m.m_mask)) {} file::~file() {} void file::open(boost::filesystem::path const& p, file::open_mode m) { m_impl->open(p, m.m_mask); } void file::close() { m_impl->close(); } size_type file::write(const char* buf, size_type num_bytes) { return m_impl->write(buf, num_bytes); } size_type file::read(char* buf, size_type num_bytes) { return m_impl->read(buf, num_bytes); } void file::seek(size_type pos, file::seek_mode m) { m_impl->seek(pos, m.m_val); } size_type file::tell() { return m_impl->tell(); } } <commit_msg>*** empty log message ***<commit_after>/* Copyright (c) 2003, Arvid Norberg 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 author 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 <boost/filesystem/operations.hpp> #include "libtorrent/file.hpp" #include <sstream> #ifdef WIN32 #include <io.h> #include <fcntl.h> #include <sys/stat.h> #include <sys/types.h> #ifndef _MODE_T_ typedef int mode_t; #endif #else #define _FILE_OFFSET_BITS 64 #include <unistd.h> #include <fcntl.h> #include <sys/stat.h> #include <sys/types.h> #endif #ifndef O_BINARY #define O_BINARY 0 #endif #ifndef O_RANDOM #define O_RANDOM 0 #endif namespace fs = boost::filesystem; namespace { enum { mode_in = 1, mode_out = 2 }; mode_t map_open_mode(int m) { // if (m == (mode_in | mode_out)) return O_RDWR | O_BINARY; if (m == mode_out) return O_WRONLY | O_CREAT | O_BINARY | O_RANDOM; if (m == mode_in) return O_RDONLY | O_BINARY | O_RANDOM; assert(false); return 0; } } namespace libtorrent { const file::open_mode file::in(mode_in); const file::open_mode file::out(mode_out); const file::seek_mode file::begin(1); const file::seek_mode file::end(2); struct file::impl { impl() : m_fd(-1) , m_open_mode(0) {} impl(fs::path const& path, int mode) : m_fd(-1) , m_open_mode(0) { open(path, mode); } ~impl() { close(); } void open(fs::path const& path, int mode) { close(); m_fd = ::open( path.native_file_string().c_str() , map_open_mode(mode) , S_IREAD | S_IWRITE); if (m_fd == -1) { std::stringstream msg; msg << "open failed: '" << path.native_file_string() << "'. " << strerror(errno); throw file_error(msg.str()); } m_open_mode = mode; } void close() { if (m_fd == -1) return; std::stringstream str; str << "fd: " << m_fd << "\n"; ::close(m_fd); m_fd = -1; m_open_mode = 0; } size_type read(char* buf, size_type num_bytes) { assert(m_open_mode == mode_in); assert(m_fd != -1); size_type ret = ::read(m_fd, buf, num_bytes); if (ret == -1) { std::stringstream msg; msg << "read failed: " << strerror(errno); throw file_error(msg.str()); } return ret; } size_type write(const char* buf, size_type num_bytes) { assert(m_open_mode == mode_out); assert(m_fd != -1); size_type ret = ::write(m_fd, buf, num_bytes); if (ret == -1) { std::stringstream msg; msg << "write failed: " << strerror(errno); throw file_error(msg.str()); } return ret; } void seek(size_type offset, int m) { assert(m_open_mode); assert(m_fd != -1); int seekdir = (m == 1)?SEEK_SET:SEEK_END; #ifdef WIN32 size_type ret = _lseeki64(m_fd, offset, seekdir); #else size_type ret = lseek(m_fd, offset, seekdir); #endif // For some strange reason this fails // on win32. Use windows specific file // wrapper instead. if (ret == -1) { std::stringstream msg; msg << "seek failed: '" << strerror(errno) << "' fd: " << m_fd << " offset: " << offset << " seekdir: " << seekdir; throw file_error(msg.str()); } } size_type tell() { assert(m_open_mode); assert(m_fd != -1); #ifdef WIN32 return _telli64(m_fd); #else return lseek(m_fd, 0, SEEK_CUR); #endif } int m_fd; int m_open_mode; }; // pimpl forwardings file::file() : m_impl(new impl()) {} file::file(boost::filesystem::path const& p, file::open_mode m) : m_impl(new impl(p, m.m_mask)) {} file::~file() {} void file::open(boost::filesystem::path const& p, file::open_mode m) { m_impl->open(p, m.m_mask); } void file::close() { m_impl->close(); } size_type file::write(const char* buf, size_type num_bytes) { return m_impl->write(buf, num_bytes); } size_type file::read(char* buf, size_type num_bytes) { return m_impl->read(buf, num_bytes); } void file::seek(size_type pos, file::seek_mode m) { m_impl->seek(pos, m.m_val); } size_type file::tell() { return m_impl->tell(); } } <|endoftext|>
<commit_before>/*! * @file File game.cpp * @brief Implementation of the class of game actions * * The class implemented provides the flow of the game * * @sa game.hpp * * @warning All variables are initialized */ #include <SDL2/SDL.h> #include <SDL2/SDL_image.h> #include <SDL2/SDL_mixer.h> #include <SDL2/SDL_ttf.h> #include <cstdlib> #include <ctime> #include <algorithm> #include <functional> #include <map> #include <vector> #include <game.hpp> #include <gameException.hpp> #include <inputManager.hpp> #include <resources.hpp> #include <state.hpp> Game* Game::instance = NULL; /*! @fn Game::Game(string title,int width,int height):frameStart{0},dt{0},winSize{(float)width,(float)height} @brief This is a constructor @param title @param width @param height @warning Method that requires review of comment */ Game::Game(string title, int width, int height):frameStart{0},deltatime{0},windowSize{ (float)width,(float)height} { srand(time(NULL)); if (instance) { cerr << "Erro, mais de uma instancia de 'Game' instanciada, o programa ira encerrar agora" << endl; exit(EXIT_FAILURE); } else { //Nothing to do } instance = this; // Check all SDL outputs and if can't be initialize display a error messege bool success = SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER) == 0; if (!success) { string error_msg(error_messege = SDL_GetError()); error_messege = "Could not initialize SDL:\n" + error_messege; throw GameException(error_messege); } // Initialize image module and check if process went OK map<int, string> code_name_map = {{IMAGE_INIT_TIF, "tif"}, {IMAGE_INIT_JPG, "jpg"}, {IMAGE_INIT_PNG, "png"}}; vector<int> image_formats{IMAGE_INIT_TIF, IMAGE_INIT_JPG, IMAGE_INIT_PNG}; // Initialize image module or between all desired formats int image_settings = accumulate(image_formats.begin(), image_formats.end(), 0, [](const int &a, const int &b) { return a | b; } ); int res = IMAGE_Init(image_settings); /* Check the possibility initialize image library and return the error messege for ever type */ if (image_settings != res) { string error_messege_main = SDL_GetError(); string error_messege = "Could not initiazlie image libary for type:"; for (auto format : image_formats) if ((format & res) == 0) { error_messege += code_name_map[format]; } error_messege += "\n"; error_messege = error_messege_main + error_messege; throw GameException(error_messege); } int audio_modules = MIX_INIT_OGG; res = Mix_Init(audio_modules); /* Check the possibility initiation of SDL audio and return a error messege if its necessary */ if (res != audio_modules) { if ((MIX_INIT_OGG & res ) == 0 ){ cerr << "OGG flag not in res!" << endl; } if ((MIX_INIT_MP3 & res ) == 0 ){ cerr << "MP3 flag not in res!" << endl; } throw GameException("Problem when initiating SDL audio!"); } res = Mix_OpenAudio(MIX_DEFAULT_FREQUENCY, MIX_DEFAULT_FORMAT, MIX_DEFAULT_CHANNELS, 1024); if (res != 0){ throw GameException("Problem when initiating SDL audio!"); } res = TTF_Init(); if (res != 0){ cerr << "Could not initialize TTF module!" << endl; } // Creating the window that will contain the game interface window = SDL_CreateWindow(title.c_str(), SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, width, height, SDL_WINDOW_FULLSCREEN); if (!window){ throw GameException("Window nao foi carregada)!"); } renderer = SDL_CreateRenderer(window,-1,SDL_RENDERER_ACCELERATED); if (!renderer){ throw GameException("Erro ao instanciar renderizador da SDL!"); } storedState = nullptr; SDL_SetRenderDrawBlendMode(GAMERENDER, SDL_BLENDMODE_BLEND); }; /*! @fn Game::~Game() @brief This is a destructor @warning Method that requires review of comment */ Game::~Game() { while (stateStack.size()) { delete stateStack.top().get(); stateStack.pop(); } if (storedState) { delete storedState; } Resources::ClearImages(); Resources::ClearMusics(); Resources::ClearFonts(); TTF_Quit(); Mix_CloseAudio(); Mix_Quit(); IMAGE_Quit(); SDL_DestroyRenderer(renderer); SDL_DestroyWindow(window); SDL_Quit(); } /*! @fn Game& Game::GetInstance() @brief Create a instance of class Game @return Returns a instance of Game @warning Method that requires review of comment */ Game& Game::GetInstance() { return (*instance); } /*! @fn State& Game::GetCurrentState() @brief Verify the current object state @return state @warning Method that requires review of comment */ State& Game::GetCurrentState() { return (*stateStack.top()); } /*! @fn void Game::Run() @brief @param @return @warning Method that requires review of comment */ SDL_Renderer* Game::GetRenderer() { return renderer; } /*! @fn void Game::Push(State* state) @brief Swapping the object state @param state @return The execution of this method returns no value @warning Method that requires review of comment */ void Game::Push(State* state) { if (storedState){ delete storedState; } storedState=state; } /*! @fn void Game::Run() @brief @param @return The execution of this method returns no value @warning Method that requires review of comment */ void Game::Run() { if (storedState) { stateStack.push(unique_ptr<State>(storedState)); storedState=nullptr; GetCurrentState().Begin(); } while (!stateStack.empty()) { CalculateDeltaTime(); // Update the state of the game elements and set it INPUT.input_event_handler(deltatime); //if (INPUT.KeyPress(KEY_F(11))) SwitchWindowMode(); GetCurrentState().update(deltatime); GetCurrentState().render(); SDL_RenderPresent(renderer); if (GetCurrentState().get_quit_requested()) { break; } /* If the user press Pause button the system change the status to paused or press End button stop the game and reset */ if (GetCurrentState().PopRequested()) { GetCurrentState().Pause(); GetCurrentState().End(); stateStack.pop(); Resources::game_clear_images(); Resources::game_clear_musics(); Resources::game_clear_fonts(); if (stateStack.size()) { GetCurrentState().Resume(); } } if (storedState) { GetCurrentState().Pause(); stateStack.push(unique_ptr<State>(storedState)); storedState=nullptr; GetCurrentState().Begin(); } SDL_Delay(17); } while (stateStack.size()) { GetCurrentState().End(); stateStack.pop(); } } float Game::GetDeltaTime() { return deltatime; } /*! @fn void Game::CalculateDeltaTime() @brief @return The execution of this method returns no value @warning Method that requires review of comment */ void Game::CalculateDeltaTime() { unsigned int tmp = frameStart; //Define the response time of a frame frameStart = SDL_GetTicks(); deltatime = max((frameStart - tmp) / 1000.0, 0.001); } /*! @fn void Game::SwitchWindowMode() @brief @return The execution of this method returns no value @warning Method that requires review of comment */ void Game::SwitchWindowMode() { // Method body its empty } <commit_msg>Inserting elses in game.cpp<commit_after>/*! * @file File game.cpp * @brief Implementation of the class of game actions * * The class implemented provides the flow of the game * * @sa game.hpp * * @warning All variables are initialized */ #include <SDL2/SDL.h> #include <SDL2/SDL_image.h> #include <SDL2/SDL_mixer.h> #include <SDL2/SDL_ttf.h> #include <cstdlib> #include <ctime> #include <algorithm> #include <functional> #include <map> #include <vector> #include <game.hpp> #include <gameException.hpp> #include <inputManager.hpp> #include <resources.hpp> #include <state.hpp> Game* Game::instance = NULL; /*! @fn Game::Game(string title,int width,int height):frameStart{0},dt{0},winSize{(float)width,(float)height} @brief This is a constructor @param title @param width @param height @warning Method that requires review of comment */ Game::Game(string title, int width, int height):frameStart{0},deltatime{0},windowSize{ (float)width,(float)height} { srand(time(NULL)); if (instance) { cerr << "Erro, mais de uma instancia de 'Game' instanciada, o programa ira encerrar agora" << endl; exit(EXIT_FAILURE); } else { //Nothing to do } instance = this; // Check all SDL outputs and if can't be initialize display a error messege bool success = SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER) == 0; if (!success) { string error_msg(error_messege = SDL_GetError()); error_messege = "Could not initialize SDL:\n" + error_messege; throw GameException(error_messege); } else { //Nothing to do } // Initialize image module and check if process went OK map<int, string> code_name_map = {{IMAGE_INIT_TIF, "tif"}, {IMAGE_INIT_JPG, "jpg"}, {IMAGE_INIT_PNG, "png"}}; vector<int> image_formats{IMAGE_INIT_TIF, IMAGE_INIT_JPG, IMAGE_INIT_PNG}; // Initialize image module or between all desired formats int image_settings = accumulate(image_formats.begin(), image_formats.end(), 0, [](const int &a, const int &b) { return a | b; } ); int res = IMAGE_Init(image_settings); /* Check the possibility initialize image library and return the error messege for ever type */ if (image_settings != res) { string error_messege_main = SDL_GetError(); string error_messege = "Could not initiazlie image libary for type:"; for (auto format : image_formats) { if ((format & res) == 0) { error_messege += code_name_map[format]; } else { //Nothing to do } } error_messege += "\n"; error_messege = error_messege_main + error_messege; throw GameException(error_messege); } else { //Nothing to do } int audio_modules = MIX_INIT_OGG; res = Mix_Init(audio_modules); /* Check the possibility initiation of SDL audio and return a error messege if its necessary */ if (res != audio_modules) { throw GameException("Problem when initiating SDL audio!"); if ((MIX_INIT_OGG & res ) == 0 ){ cerr << "OGG flag not in res!" << endl; } else { //Nothing to do } if ((MIX_INIT_MP3 & res ) == 0 ){ cerr << "MP3 flag not in res!" << endl; } } res = Mix_OpenAudio(MIX_DEFAULT_FREQUENCY, MIX_DEFAULT_FORMAT, MIX_DEFAULT_CHANNELS, 1024); if (res != 0){ throw GameException("Problem when initiating SDL audio!"); } res = TTF_Init(); if (res != 0){ cerr << "Could not initialize TTF module!" << endl; } // Creating the window that will contain the game interface window = SDL_CreateWindow(title.c_str(), SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, width, height, SDL_WINDOW_FULLSCREEN); if (!window){ throw GameException("Window nao foi carregada)!"); } renderer = SDL_CreateRenderer(window,-1,SDL_RENDERER_ACCELERATED); if (!renderer){ throw GameException("Erro ao instanciar renderizador da SDL!"); } storedState = nullptr; SDL_SetRenderDrawBlendMode(GAMERENDER, SDL_BLENDMODE_BLEND); }; /*! @fn Game::~Game() @brief This is a destructor @warning Method that requires review of comment */ Game::~Game() { while (stateStack.size()) { delete stateStack.top().get(); stateStack.pop(); } if (storedState) { delete storedState; } Resources::ClearImages(); Resources::ClearMusics(); Resources::ClearFonts(); TTF_Quit(); Mix_CloseAudio(); Mix_Quit(); IMAGE_Quit(); SDL_DestroyRenderer(renderer); SDL_DestroyWindow(window); SDL_Quit(); } /*! @fn Game& Game::GetInstance() @brief Create a instance of class Game @return Returns a instance of Game @warning Method that requires review of comment */ Game& Game::GetInstance() { return (*instance); } /*! @fn State& Game::GetCurrentState() @brief Verify the current object state @return state @warning Method that requires review of comment */ State& Game::GetCurrentState() { return (*stateStack.top()); } /*! @fn void Game::Run() @brief @param @return @warning Method that requires review of comment */ SDL_Renderer* Game::GetRenderer() { return renderer; } /*! @fn void Game::Push(State* state) @brief Swapping the object state @param state @return The execution of this method returns no value @warning Method that requires review of comment */ void Game::Push(State* state) { if (storedState){ delete storedState; } storedState=state; } /*! @fn void Game::Run() @brief @param @return The execution of this method returns no value @warning Method that requires review of comment */ void Game::Run() { if (storedState) { stateStack.push(unique_ptr<State>(storedState)); storedState=nullptr; GetCurrentState().Begin(); } while (!stateStack.empty()) { CalculateDeltaTime(); // Update the state of the game elements and set it INPUT.input_event_handler(deltatime); //if (INPUT.KeyPress(KEY_F(11))) SwitchWindowMode(); GetCurrentState().update(deltatime); GetCurrentState().render(); SDL_RenderPresent(renderer); if (GetCurrentState().get_quit_requested()) { break; } /* If the user press Pause button the system change the status to paused or press End button stop the game and reset */ if (GetCurrentState().PopRequested()) { GetCurrentState().Pause(); GetCurrentState().End(); stateStack.pop(); Resources::game_clear_images(); Resources::game_clear_musics(); Resources::game_clear_fonts(); if (stateStack.size()) { GetCurrentState().Resume(); } } if (storedState) { GetCurrentState().Pause(); stateStack.push(unique_ptr<State>(storedState)); storedState=nullptr; GetCurrentState().Begin(); } SDL_Delay(17); } while (stateStack.size()) { GetCurrentState().End(); stateStack.pop(); } } float Game::GetDeltaTime() { return deltatime; } /*! @fn void Game::CalculateDeltaTime() @brief @return The execution of this method returns no value @warning Method that requires review of comment */ void Game::CalculateDeltaTime() { unsigned int tmp = frameStart; //Define the response time of a frame frameStart = SDL_GetTicks(); deltatime = max((frameStart - tmp) / 1000.0, 0.001); } /*! @fn void Game::SwitchWindowMode() @brief @return The execution of this method returns no value @warning Method that requires review of comment */ void Game::SwitchWindowMode() { // Method body its empty } <|endoftext|>
<commit_before>// // Created by Artur Troian on 1/21/17. // #include <jwtpp/crypto.hpp> #include <openssl/hmac.h> #include <jwtpp/b64.hpp> namespace jwt { hmac::hmac(jwt::alg alg, const std::string &secret) : crypto(alg) , secret_(secret) { if (alg != jwt::alg::HS256 && alg != jwt::alg::HS384 && alg != jwt::alg::HS512) { throw std::invalid_argument("Invalid algorithm"); } if (secret.empty()) { throw std::invalid_argument("Invalid secret"); } } hmac::~hmac() { // clear out secret std::memset((void *)secret_.data(), 0 , secret_.length()); } std::string hmac::sign(const std::string &data) { if (data.empty()) { throw std::invalid_argument("Data is empty"); } std::string sig; const EVP_MD *alg; switch (alg_) { case jwt::alg::HS256: alg = EVP_sha256(); break; case jwt::alg::HS384: alg = EVP_sha384(); break; case jwt::alg::HS512: alg = EVP_sha512(); break; default: // Should never happen throw std::runtime_error("Invalid alg"); } uint32_t size; HMAC(alg, secret_.data(), secret_.length(), (const uint8_t *) data.c_str(), data.size(), nullptr, &size); std::shared_ptr<uint8_t> res = std::shared_ptr<uint8_t>(new uint8_t[size], std::default_delete<uint8_t[]>()); HMAC(alg, secret_.data(), secret_.length(), (const uint8_t *) data.c_str(), data.size(), res.get(), &size); b64::encode(sig, res.get(), size); return sig; } bool hmac::verify(const std::string &data, const std::string &sig) { return sig == sign(data); } } // namespace jwt <commit_msg>Fix memset for linux gcc<commit_after>// // Created by Artur Troian on 1/21/17. // #include <cstring> #include <jwtpp/crypto.hpp> #include <openssl/hmac.h> #include <jwtpp/b64.hpp> namespace jwt { hmac::hmac(jwt::alg alg, const std::string &secret) : crypto(alg) , secret_(secret) { if (alg != jwt::alg::HS256 && alg != jwt::alg::HS384 && alg != jwt::alg::HS512) { throw std::invalid_argument("Invalid algorithm"); } if (secret.empty()) { throw std::invalid_argument("Invalid secret"); } } hmac::~hmac() { // clear out secret std::memset((void *)secret_.data(), 0 , secret_.length()); } std::string hmac::sign(const std::string &data) { if (data.empty()) { throw std::invalid_argument("Data is empty"); } std::string sig; const EVP_MD *alg; switch (alg_) { case jwt::alg::HS256: alg = EVP_sha256(); break; case jwt::alg::HS384: alg = EVP_sha384(); break; case jwt::alg::HS512: alg = EVP_sha512(); break; default: // Should never happen throw std::runtime_error("Invalid alg"); } uint32_t size; HMAC(alg, secret_.data(), secret_.length(), (const uint8_t *) data.c_str(), data.size(), nullptr, &size); std::shared_ptr<uint8_t> res = std::shared_ptr<uint8_t>(new uint8_t[size], std::default_delete<uint8_t[]>()); HMAC(alg, secret_.data(), secret_.length(), (const uint8_t *) data.c_str(), data.size(), res.get(), &size); b64::encode(sig, res.get(), size); return sig; } bool hmac::verify(const std::string &data, const std::string &sig) { return sig == sign(data); } } // namespace jwt <|endoftext|>
<commit_before>#include "html.h" #include "types.h" #include "html_tag.h" void litehtml::trim(tstring &s) { tstring::size_type pos = s.find_first_not_of(_t(" \n\r\t")); if(pos != tstring::npos) { s.erase(s.begin(), s.begin() + pos); } pos = s.find_last_not_of(_t(" \n\r\t")); if(pos != tstring::npos) { s.erase(s.begin() + pos + 1, s.end()); } } void litehtml::lcase(tstring &s) { for(tstring::iterator i = s.begin(); i != s.end(); i++) { (*i) = t_tolower(*i); } } litehtml::tstring::size_type litehtml::find_close_bracket(const tstring &s, tstring::size_type off, tchar_t open_b, tchar_t close_b) { int cnt = 0; for(tstring::size_type i = off; i < s.length(); i++) { if(s[i] == open_b) { cnt++; } else if(s[i] == close_b) { cnt--; if(!cnt) { return i; } } } return tstring::npos; } int litehtml::value_index( const tstring& val, const tstring& strings, int defValue, tchar_t delim ) { if(val.empty() || strings.empty() || !delim) { return defValue; } int idx = 0; tstring::size_type delim_start = 0; tstring::size_type delim_end = strings.find(delim, delim_start); tstring::size_type item_len = 0; while(true) { if(delim_end == tstring::npos) { item_len = strings.length() - delim_start; } else { item_len = delim_end - delim_start; } if(item_len == val.length()) { if(val == strings.substr(delim_start, item_len)) { return idx; } } idx++; delim_start = delim_end; if(delim_start == tstring::npos) break; delim_start++; if(delim_start == strings.length()) break; delim_end = strings.find(delim, delim_start); } return defValue; } bool litehtml::value_in_list( const tstring& val, const tstring& strings, tchar_t delim ) { int idx = value_index(val, strings, -1, delim); if(idx >= 0) { return true; } return false; } void litehtml::split_string(const tstring& str, string_vector& tokens, const tstring& delims, const tstring& delims_preserve, const tstring& quote) { if(str.empty() || (delims.empty() && delims_preserve.empty())) { return; } tstring all_delims = delims + delims_preserve + quote; tstring::size_type token_start = 0; tstring::size_type token_end = str.find_first_of(all_delims, token_start); tstring::size_type token_len = 0; tstring token; while(true) { while( token_end != tstring::npos && quote.find_first_of(str[token_end]) != tstring::npos ) { if(str[token_end] == _t('(')) { token_end = find_close_bracket(str, token_end, _t('('), _t(')')); } else if(str[token_end] == _t('[')) { token_end = find_close_bracket(str, token_end, _t('['), _t(']')); } else if(str[token_end] == _t('{')) { token_end = find_close_bracket(str, token_end, _t('{'), _t('}')); } else { token_end = str.find_first_of(str[token_end], token_end + 1); } if(token_end != tstring::npos) { token_end = str.find_first_of(all_delims, token_end + 1); } } if(token_end == tstring::npos) { token_len = tstring::npos; } else { token_len = token_end - token_start; } token = str.substr(token_start, token_len); if(!token.empty()) { tokens.push_back( token ); } if(token_end != tstring::npos && !delims_preserve.empty() && delims_preserve.find_first_of(str[token_end]) != tstring::npos) { tokens.push_back( str.substr(token_end, 1) ); } token_start = token_end; if(token_start == tstring::npos) break; token_start++; if(token_start == str.length()) break; token_end = str.find_first_of(all_delims, token_start); } } void litehtml::join_string(tstring& str, const string_vector& tokens, const tstring& delims) { tstringstream ss; for(size_t i=0; i<tokens.size(); ++i) { if(i != 0) { ss << delims; } ss << tokens[i]; } str = ss.str(); } <commit_msg>Custom 'strtod' implementation.<commit_after>#include "html.h" #include "types.h" #include "html_tag.h" void litehtml::trim(tstring &s) { tstring::size_type pos = s.find_first_not_of(_t(" \n\r\t")); if(pos != tstring::npos) { s.erase(s.begin(), s.begin() + pos); } pos = s.find_last_not_of(_t(" \n\r\t")); if(pos != tstring::npos) { s.erase(s.begin() + pos + 1, s.end()); } } void litehtml::lcase(tstring &s) { for(tstring::iterator i = s.begin(); i != s.end(); i++) { (*i) = t_tolower(*i); } } litehtml::tstring::size_type litehtml::find_close_bracket(const tstring &s, tstring::size_type off, tchar_t open_b, tchar_t close_b) { int cnt = 0; for(tstring::size_type i = off; i < s.length(); i++) { if(s[i] == open_b) { cnt++; } else if(s[i] == close_b) { cnt--; if(!cnt) { return i; } } } return tstring::npos; } int litehtml::value_index( const tstring& val, const tstring& strings, int defValue, tchar_t delim ) { if(val.empty() || strings.empty() || !delim) { return defValue; } int idx = 0; tstring::size_type delim_start = 0; tstring::size_type delim_end = strings.find(delim, delim_start); tstring::size_type item_len = 0; while(true) { if(delim_end == tstring::npos) { item_len = strings.length() - delim_start; } else { item_len = delim_end - delim_start; } if(item_len == val.length()) { if(val == strings.substr(delim_start, item_len)) { return idx; } } idx++; delim_start = delim_end; if(delim_start == tstring::npos) break; delim_start++; if(delim_start == strings.length()) break; delim_end = strings.find(delim, delim_start); } return defValue; } bool litehtml::value_in_list( const tstring& val, const tstring& strings, tchar_t delim ) { int idx = value_index(val, strings, -1, delim); if(idx >= 0) { return true; } return false; } void litehtml::split_string(const tstring& str, string_vector& tokens, const tstring& delims, const tstring& delims_preserve, const tstring& quote) { if(str.empty() || (delims.empty() && delims_preserve.empty())) { return; } tstring all_delims = delims + delims_preserve + quote; tstring::size_type token_start = 0; tstring::size_type token_end = str.find_first_of(all_delims, token_start); tstring::size_type token_len = 0; tstring token; while(true) { while( token_end != tstring::npos && quote.find_first_of(str[token_end]) != tstring::npos ) { if(str[token_end] == _t('(')) { token_end = find_close_bracket(str, token_end, _t('('), _t(')')); } else if(str[token_end] == _t('[')) { token_end = find_close_bracket(str, token_end, _t('['), _t(']')); } else if(str[token_end] == _t('{')) { token_end = find_close_bracket(str, token_end, _t('{'), _t('}')); } else { token_end = str.find_first_of(str[token_end], token_end + 1); } if(token_end != tstring::npos) { token_end = str.find_first_of(all_delims, token_end + 1); } } if(token_end == tstring::npos) { token_len = tstring::npos; } else { token_len = token_end - token_start; } token = str.substr(token_start, token_len); if(!token.empty()) { tokens.push_back( token ); } if(token_end != tstring::npos && !delims_preserve.empty() && delims_preserve.find_first_of(str[token_end]) != tstring::npos) { tokens.push_back( str.substr(token_end, 1) ); } token_start = token_end; if(token_start == tstring::npos) break; token_start++; if(token_start == str.length()) break; token_end = str.find_first_of(all_delims, token_start); } } void litehtml::join_string(tstring& str, const string_vector& tokens, const tstring& delims) { tstringstream ss; for(size_t i=0; i<tokens.size(); ++i) { if(i != 0) { ss << delims; } ss << tokens[i]; } str = ss.str(); } double litehtml::strtod(const char *nptr, char **endptr) { tstring num; tstring dec; const char *p; double val = 0; bool neg; double f; int i; p = nptr; if (*p == '+') { neg = false; p++; } else if (*p == '-') { neg = true; p++; } while (*p) { if (*p == '.' || !t_isdigit(*p)) break; num += *p++; } f = 1.0; for (i = num.length() - 1; i >= 0; i--) { val += (num[i] - '0') * f; f *= 10.0; } if (*p == '.') { p++; while(*p) { if (!t_isdigit(*p)) break; dec += *p++; } f = 1.0; for (i = 0; i < dec.length(); i++) { f /= 10.0; val += (dec[i] - '0') * f; } } if (endptr) *endptr = (char *)p; return neg ? (-val) : val; } <|endoftext|>
<commit_before>#include"ics3/ics3.hpp" #include"core.hpp" #include"ics3/eeprom.hpp" #include"ics3/parameter.hpp" #include"ics3/id.hpp" static inline ics::Angle::rawType getReceiveAngle(const ics::Core::Container& rx) noexcept { return static_cast<ics::Angle::rawType>((rx[4] << 7) | rx[5]); } ics::ICS3::ICS3(const std::string& path, const Baudrate& baudrate) : core {Core::getCore(path, baudrate.getSpeed())} {} ics::Angle ics::ICS3::move(const ID& id, Angle angle) { static Core::Container tx(3), rx(6); // cache for runtime speed const uint16_t send {angle.getRaw()}; tx[0] = 0x80 | id.get(); tx[1] = 0x7F & (send >> 7); tx[2] = 0x7F & send; core->communicate(tx, rx); // throw std::runtime_error angle.rawData = getReceiveAngle(rx); // avoid invalid check. need friend return angle; } ics::Angle ics::ICS3::free(const ID& id, Angle unit) { static Core::Container tx(3), rx(6); // cache for runtime speed tx[0] = 0x80 | id.get(); // tx[1] == tx[2] == 0 core->communicate(tx, rx); // throw std::runtime_error unit.rawData = getReceiveAngle(rx); // avoid invalid check. need friend return unit; } ics::Parameter ics::ICS3::get(const ID& id, const Parameter& type) { Core::Container tx(2), rx(5); tx[0] = 0xA0 | id.get(); tx[1] = type.getSubcommand(); core->communicate(tx, rx); // throw std::runtime_error return Parameter::newParameter(type, rx[4]); } void ics::ICS3::set(const ID& id, const Parameter& param) { Core::Container tx(3), rx(6); tx[0] = 0xC0 | id.get(); tx[1] = param.getSubcommand(); tx[2] = param.get(); core->communicate(tx, rx); // throw std::runtime_error } ics::EepRom ics::ICS3::getRom(const ID& id) { Core::Container tx(2), rx(68); tx[0] = 0xA0 | id.get(); // tx[1] == 0 core->communicate(tx, rx); // throw std::runtime_error std::array<uint8_t, 64> romData; std::copy(rx.cbegin() + 4, rx.cend(), romData.begin()); return EepRom {romData}; // need friend } void ics::ICS3::setRom(const ID& id, const EepRom& rom) { Core::Container tx(66), rx(68); tx[0] = 0xC0 | id.get(); // tx[1] == 0 rom.write(tx.begin() + 2); core->communicate(tx, rx); // throw std::runtime_error } ics::ID ics::ICS3::getID() { const Core::IDContainerTx tx {0xFF, 0x00, 0x00, 0x00}; Core::IDContainerRx rx; core->communicateID(tx, rx); return ID {static_cast<uint8_t>(0x1F & rx[4])}; } void ics::ICS3::setID(const ID& id) { auto cmd = static_cast<Core::value>(0xE0 | id.get()); const Core::IDContainerTx tx {cmd, 1, 1, 1}; Core::IDContainerRx rx; core->communicateID(tx, rx); } <commit_msg>Use constexpr on array<commit_after>#include"ics3/ics3.hpp" #include"core.hpp" #include"ics3/eeprom.hpp" #include"ics3/parameter.hpp" #include"ics3/id.hpp" static inline ics::Angle::rawType getReceiveAngle(const ics::Core::Container& rx) noexcept { return static_cast<ics::Angle::rawType>((rx[4] << 7) | rx[5]); } ics::ICS3::ICS3(const std::string& path, const Baudrate& baudrate) : core {Core::getCore(path, baudrate.getSpeed())} {} ics::Angle ics::ICS3::move(const ID& id, Angle angle) { static Core::Container tx(3), rx(6); // cache for runtime speed const uint16_t send {angle.getRaw()}; tx[0] = 0x80 | id.get(); tx[1] = 0x7F & (send >> 7); tx[2] = 0x7F & send; core->communicate(tx, rx); // throw std::runtime_error angle.rawData = getReceiveAngle(rx); // avoid invalid check. need friend return angle; } ics::Angle ics::ICS3::free(const ID& id, Angle unit) { static Core::Container tx(3), rx(6); // cache for runtime speed tx[0] = 0x80 | id.get(); // tx[1] == tx[2] == 0 core->communicate(tx, rx); // throw std::runtime_error unit.rawData = getReceiveAngle(rx); // avoid invalid check. need friend return unit; } ics::Parameter ics::ICS3::get(const ID& id, const Parameter& type) { Core::Container tx(2), rx(5); tx[0] = 0xA0 | id.get(); tx[1] = type.getSubcommand(); core->communicate(tx, rx); // throw std::runtime_error return Parameter::newParameter(type, rx[4]); } void ics::ICS3::set(const ID& id, const Parameter& param) { Core::Container tx(3), rx(6); tx[0] = 0xC0 | id.get(); tx[1] = param.getSubcommand(); tx[2] = param.get(); core->communicate(tx, rx); // throw std::runtime_error } ics::EepRom ics::ICS3::getRom(const ID& id) { Core::Container tx(2), rx(68); tx[0] = 0xA0 | id.get(); // tx[1] == 0 core->communicate(tx, rx); // throw std::runtime_error std::array<uint8_t, 64> romData; std::copy(rx.cbegin() + 4, rx.cend(), romData.begin()); return EepRom {romData}; // need friend } void ics::ICS3::setRom(const ID& id, const EepRom& rom) { Core::Container tx(66), rx(68); tx[0] = 0xC0 | id.get(); // tx[1] == 0 rom.write(tx.begin() + 2); core->communicate(tx, rx); // throw std::runtime_error } ics::ID ics::ICS3::getID() { constexpr Core::IDContainerTx tx {0xFF, 0x00, 0x00, 0x00}; Core::IDContainerRx rx; core->communicateID(tx, rx); return ID {static_cast<uint8_t>(0x1F & rx[4])}; } void ics::ICS3::setID(const ID& id) { auto cmd = static_cast<Core::value>(0xE0 | id.get()); const Core::IDContainerTx tx {cmd, 1, 1, 1}; Core::IDContainerRx rx; core->communicateID(tx, rx); } <|endoftext|>
<commit_before>//===- ICF.cpp ------------------------------------------------------------===// // // The LLVM Linker // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Identical Code Folding is a feature to merge sections not by name (which // is regular comdat handling) but by contents. If two non-writable sections // have the same data, relocations, attributes, etc., then the two // are considered identical and merged by the linker. This optimization // makes outputs smaller. // // ICF is theoretically a problem of reducing graphs by merging as many // identical subgraphs as possible if we consider sections as vertices and // relocations as edges. It may sound simple, but it is a bit more // complicated than you might think. The order of processing sections // matters because merging two sections can make other sections, whose // relocations now point to the same section, mergeable. Graphs may contain // cycles. We need a sophisticated algorithm to do this properly and // efficiently. // // What we do in this file is this. We split sections into groups. Sections // in the same group are considered identical. // // We begin by optimistically putting all sections into a single equivalence // class. Then we apply a series of checks that split this initial // equivalence class into more and more refined equivalence classes based on // the properties by which a section can be distinguished. // // We begin by checking that the section contents and flags are the // same. This only needs to be done once since these properties don't depend // on the current equivalence class assignment. // // Then we split the equivalence classes based on checking that their // relocations are the same, where relocation targets are compared by their // equivalence class, not the concrete section. This may need to be done // multiple times because as the equivalence classes are refined, two // sections that had a relocation target in the same equivalence class may // now target different equivalence classes, and hence these two sections // must be put in different equivalence classes (whereas in the previous // iteration they were not since the relocation target was the same.) // // Our algorithm is smart enough to merge the following mutually-recursive // functions. // // void foo() { bar(); } // void bar() { foo(); } // // This algorithm is so-called "optimistic" algorithm described in // http://research.google.com/pubs/pub36912.html. (Note that what GNU // gold implemented is different from the optimistic algorithm.) // //===----------------------------------------------------------------------===// #include "ICF.h" #include "Config.h" #include "OutputSections.h" #include "SymbolTable.h" #include "llvm/ADT/Hashing.h" #include "llvm/Object/ELF.h" #include "llvm/Support/ELF.h" #include "llvm/Support/raw_ostream.h" #include <algorithm> using namespace lld; using namespace lld::elf; using namespace llvm; using namespace llvm::ELF; using namespace llvm::object; namespace lld { namespace elf { template <class ELFT> class ICF { typedef typename ELFT::Shdr Elf_Shdr; typedef typename ELFT::Sym Elf_Sym; typedef typename ELFT::uint uintX_t; typedef Elf_Rel_Impl<ELFT, false> Elf_Rel; using Comparator = std::function<bool(const InputSection<ELFT> *, const InputSection<ELFT> *)>; public: void run(); private: uint64_t NextId = 1; static void setLive(SymbolTable<ELFT> *S); static uint64_t relSize(InputSection<ELFT> *S); static uint64_t getHash(InputSection<ELFT> *S); static bool isEligible(InputSectionBase<ELFT> *Sec); static std::vector<InputSection<ELFT> *> getSections(); void segregate(InputSection<ELFT> **Begin, InputSection<ELFT> **End, Comparator Eq); void forEachGroup(std::vector<InputSection<ELFT> *> &V, Comparator Eq); template <class RelTy> static bool relocationEq(ArrayRef<RelTy> RA, ArrayRef<RelTy> RB); template <class RelTy> static bool variableEq(const InputSection<ELFT> *A, ArrayRef<RelTy> RA, const InputSection<ELFT> *B, ArrayRef<RelTy> RB); static bool equalsConstant(const InputSection<ELFT> *A, const InputSection<ELFT> *B); static bool equalsVariable(const InputSection<ELFT> *A, const InputSection<ELFT> *B); }; } } // Returns a hash value for S. Note that the information about // relocation targets is not included in the hash value. template <class ELFT> uint64_t ICF<ELFT>::getHash(InputSection<ELFT> *S) { return hash_combine(S->Flags, S->getSize(), S->NumRelocations); } // Returns true if Sec is subject of ICF. template <class ELFT> bool ICF<ELFT>::isEligible(InputSectionBase<ELFT> *Sec) { if (!Sec->Live) return false; auto *S = dyn_cast<InputSection<ELFT>>(Sec); if (!S) return false; // .init and .fini contains instructions that must be executed to // initialize and finalize the process. They cannot and should not // be merged. StringRef Name = S->Name; if (Name == ".init" || Name == ".fini") return false; return (S->Flags & SHF_ALLOC) && !(S->Flags & SHF_WRITE); } template <class ELFT> std::vector<InputSection<ELFT> *> ICF<ELFT>::getSections() { std::vector<InputSection<ELFT> *> V; for (InputSectionBase<ELFT> *S : Symtab<ELFT>::X->Sections) if (isEligible(S)) V.push_back(cast<InputSection<ELFT>>(S)); return V; } // All sections between Begin and End must have the same group ID before // you call this function. This function compare sections between Begin // and End using Eq and assign new group IDs for new groups. template <class ELFT> void ICF<ELFT>::segregate(InputSection<ELFT> **Begin, InputSection<ELFT> **End, Comparator Eq) { // This loop rearranges [Begin, End) so that all sections that are // equal in terms of Eq are contiguous. The algorithm is quadratic in // the worst case, but that is not an issue in practice because the // number of distinct sections in [Begin, End) is usually very small. InputSection<ELFT> **I = Begin; for (;;) { InputSection<ELFT> *Head = *I; auto Bound = std::stable_partition( I + 1, End, [&](InputSection<ELFT> *S) { return Eq(Head, S); }); if (Bound == End) return; uint64_t Id = NextId++; for (; I != Bound; ++I) (*I)->GroupId = Id; } } template <class ELFT> void ICF<ELFT>::forEachGroup(std::vector<InputSection<ELFT> *> &V, Comparator Eq) { for (InputSection<ELFT> **I = V.data(), **E = I + V.size(); I != E;) { InputSection<ELFT> *Head = *I; auto Bound = std::find_if(I + 1, E, [&](InputSection<ELFT> *S) { return S->GroupId != Head->GroupId; }); segregate(I, Bound, Eq); I = Bound; } } // Compare two lists of relocations. template <class ELFT> template <class RelTy> bool ICF<ELFT>::relocationEq(ArrayRef<RelTy> RelsA, ArrayRef<RelTy> RelsB) { auto Eq = [](const RelTy &A, const RelTy &B) { return A.r_offset == B.r_offset && A.getType(Config->Mips64EL) == B.getType(Config->Mips64EL) && getAddend<ELFT>(A) == getAddend<ELFT>(B); }; return RelsA.size() == RelsB.size() && std::equal(RelsA.begin(), RelsA.end(), RelsB.begin(), Eq); } // Compare "non-moving" part of two InputSections, namely everything // except relocation targets. template <class ELFT> bool ICF<ELFT>::equalsConstant(const InputSection<ELFT> *A, const InputSection<ELFT> *B) { if (A->NumRelocations != B->NumRelocations) return false; if (A->AreRelocsRela) { if (!relocationEq(A->relas(), B->relas())) return false; } else { if (!relocationEq(A->rels(), B->rels())) return false; } return A->Flags == B->Flags && A->getSize() == B->getSize() && A->Data == B->Data; } template <class ELFT> template <class RelTy> bool ICF<ELFT>::variableEq(const InputSection<ELFT> *A, ArrayRef<RelTy> RelsA, const InputSection<ELFT> *B, ArrayRef<RelTy> RelsB) { auto Eq = [&](const RelTy &RA, const RelTy &RB) { SymbolBody &SA = A->File->getRelocTargetSym(RA); SymbolBody &SB = B->File->getRelocTargetSym(RB); if (&SA == &SB) return true; // Or, the symbols should be pointing to the same section // in terms of the group ID. auto *DA = dyn_cast<DefinedRegular<ELFT>>(&SA); auto *DB = dyn_cast<DefinedRegular<ELFT>>(&SB); if (!DA || !DB) return false; if (DA->Value != DB->Value) return false; InputSection<ELFT> *X = dyn_cast<InputSection<ELFT>>(DA->Section); InputSection<ELFT> *Y = dyn_cast<InputSection<ELFT>>(DB->Section); return X && Y && X->GroupId && X->GroupId == Y->GroupId; }; return std::equal(RelsA.begin(), RelsA.end(), RelsB.begin(), Eq); } // Compare "moving" part of two InputSections, namely relocation targets. template <class ELFT> bool ICF<ELFT>::equalsVariable(const InputSection<ELFT> *A, const InputSection<ELFT> *B) { if (A->AreRelocsRela) return variableEq(A, A->relas(), B, B->relas()); return variableEq(A, A->rels(), B, B->rels()); } // The main function of ICF. template <class ELFT> void ICF<ELFT>::run() { // Initially, we use hash values as section group IDs. Therefore, // if two sections have the same ID, they are likely (but not // guaranteed) to have the same static contents in terms of ICF. std::vector<InputSection<ELFT> *> V = getSections(); for (InputSection<ELFT> *S : V) // Set MSB on to avoid collisions with serial group IDs S->GroupId = getHash(S) | (uint64_t(1) << 63); // From now on, sections in V are ordered so that sections in // the same group are consecutive in the vector. std::stable_sort(V.begin(), V.end(), [](InputSection<ELFT> *A, InputSection<ELFT> *B) { if (A->GroupId != B->GroupId) return A->GroupId < B->GroupId; // Within a group, put the highest alignment // requirement first, so that's the one we'll keep. return B->Alignment < A->Alignment; }); // Compare static contents and assign unique IDs for each static content. forEachGroup(V, equalsConstant); // Split groups by comparing relocations until we get a convergence. int Cnt = 1; for (;;) { ++Cnt; uint64_t Id = NextId; forEachGroup(V, equalsVariable); if (Id == NextId) break; } log("ICF needed " + Twine(Cnt) + " iterations."); // Merge sections in the same group. for (auto I = V.begin(), E = V.end(); I != E;) { InputSection<ELFT> *Head = *I++; auto Bound = std::find_if(I, E, [&](InputSection<ELFT> *S) { return Head->GroupId != S->GroupId; }); if (I == Bound) continue; log("selected " + Head->Name); while (I != Bound) { InputSection<ELFT> *S = *I++; log(" removed " + S->Name); Head->replace(S); } } } // ICF entry point function. template <class ELFT> void elf::doIcf() { ICF<ELFT>().run(); } template void elf::doIcf<ELF32LE>(); template void elf::doIcf<ELF32BE>(); template void elf::doIcf<ELF64LE>(); template void elf::doIcf<ELF64BE>(); <commit_msg>Refactor ICF.<commit_after>//===- ICF.cpp ------------------------------------------------------------===// // // The LLVM Linker // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Identical Code Folding is a feature to merge sections not by name (which // is regular comdat handling) but by contents. If two non-writable sections // have the same data, relocations, attributes, etc., then the two // are considered identical and merged by the linker. This optimization // makes outputs smaller. // // ICF is theoretically a problem of reducing graphs by merging as many // identical subgraphs as possible if we consider sections as vertices and // relocations as edges. It may sound simple, but it is a bit more // complicated than you might think. The order of processing sections // matters because merging two sections can make other sections, whose // relocations now point to the same section, mergeable. Graphs may contain // cycles. We need a sophisticated algorithm to do this properly and // efficiently. // // What we do in this file is this. We split sections into groups. Sections // in the same group are considered identical. // // We begin by optimistically putting all sections into a single equivalence // class. Then we apply a series of checks that split this initial // equivalence class into more and more refined equivalence classes based on // the properties by which a section can be distinguished. // // We begin by checking that the section contents and flags are the // same. This only needs to be done once since these properties don't depend // on the current equivalence class assignment. // // Then we split the equivalence classes based on checking that their // relocations are the same, where relocation targets are compared by their // equivalence class, not the concrete section. This may need to be done // multiple times because as the equivalence classes are refined, two // sections that had a relocation target in the same equivalence class may // now target different equivalence classes, and hence these two sections // must be put in different equivalence classes (whereas in the previous // iteration they were not since the relocation target was the same.) // // Our algorithm is smart enough to merge the following mutually-recursive // functions. // // void foo() { bar(); } // void bar() { foo(); } // // This algorithm is so-called "optimistic" algorithm described in // http://research.google.com/pubs/pub36912.html. (Note that what GNU // gold implemented is different from the optimistic algorithm.) // //===----------------------------------------------------------------------===// #include "ICF.h" #include "Config.h" #include "OutputSections.h" #include "SymbolTable.h" #include "llvm/ADT/Hashing.h" #include "llvm/Object/ELF.h" #include "llvm/Support/ELF.h" #include "llvm/Support/raw_ostream.h" #include <algorithm> using namespace lld; using namespace lld::elf; using namespace llvm; using namespace llvm::ELF; using namespace llvm::object; namespace lld { namespace elf { template <class ELFT> class ICF { typedef typename ELFT::Shdr Elf_Shdr; typedef typename ELFT::Sym Elf_Sym; typedef typename ELFT::uint uintX_t; typedef Elf_Rel_Impl<ELFT, false> Elf_Rel; using Comparator = std::function<bool(const InputSection<ELFT> *, const InputSection<ELFT> *)>; public: void run(); private: uint64_t NextId = 1; static void setLive(SymbolTable<ELFT> *S); static uint64_t relSize(InputSection<ELFT> *S); static uint64_t getHash(InputSection<ELFT> *S); static bool isEligible(InputSectionBase<ELFT> *Sec); static std::vector<InputSection<ELFT> *> getSections(); void segregate(MutableArrayRef<InputSection<ELFT> *> Arr, Comparator Eq); void forEachGroup(std::vector<InputSection<ELFT> *> &V, std::function<void(MutableArrayRef<InputSection<ELFT> *>)> Fn); template <class RelTy> static bool relocationEq(ArrayRef<RelTy> RA, ArrayRef<RelTy> RB); template <class RelTy> static bool variableEq(const InputSection<ELFT> *A, ArrayRef<RelTy> RA, const InputSection<ELFT> *B, ArrayRef<RelTy> RB); static bool equalsConstant(const InputSection<ELFT> *A, const InputSection<ELFT> *B); static bool equalsVariable(const InputSection<ELFT> *A, const InputSection<ELFT> *B); }; } } // Returns a hash value for S. Note that the information about // relocation targets is not included in the hash value. template <class ELFT> uint64_t ICF<ELFT>::getHash(InputSection<ELFT> *S) { return hash_combine(S->Flags, S->getSize(), S->NumRelocations); } // Returns true if Sec is subject of ICF. template <class ELFT> bool ICF<ELFT>::isEligible(InputSectionBase<ELFT> *Sec) { if (!Sec->Live) return false; auto *S = dyn_cast<InputSection<ELFT>>(Sec); if (!S) return false; // .init and .fini contains instructions that must be executed to // initialize and finalize the process. They cannot and should not // be merged. StringRef Name = S->Name; if (Name == ".init" || Name == ".fini") return false; return (S->Flags & SHF_ALLOC) && !(S->Flags & SHF_WRITE); } template <class ELFT> std::vector<InputSection<ELFT> *> ICF<ELFT>::getSections() { std::vector<InputSection<ELFT> *> V; for (InputSectionBase<ELFT> *S : Symtab<ELFT>::X->Sections) if (isEligible(S)) V.push_back(cast<InputSection<ELFT>>(S)); return V; } // All sections between Begin and End must have the same group ID before // you call this function. This function compare sections between Begin // and End using Eq and assign new group IDs for new groups. template <class ELFT> void ICF<ELFT>::segregate(MutableArrayRef<InputSection<ELFT> *> Arr, Comparator Eq) { // This loop rearranges [Begin, End) so that all sections that are // equal in terms of Eq are contiguous. The algorithm is quadratic in // the worst case, but that is not an issue in practice because the // number of distinct sections in [Begin, End) is usually very small. InputSection<ELFT> **I = Arr.begin(); for (;;) { InputSection<ELFT> *Head = *I; auto Bound = std::stable_partition( I + 1, Arr.end(), [&](InputSection<ELFT> *S) { return Eq(Head, S); }); if (Bound == Arr.end()) return; uint64_t Id = NextId++; for (; I != Bound; ++I) (*I)->GroupId = Id; } } template <class ELFT> void ICF<ELFT>::forEachGroup( std::vector<InputSection<ELFT> *> &V, std::function<void(MutableArrayRef<InputSection<ELFT> *>)> Fn) { for (InputSection<ELFT> **I = V.data(), **E = I + V.size(); I != E;) { InputSection<ELFT> *Head = *I; auto Bound = std::find_if(I + 1, E, [&](InputSection<ELFT> *S) { return S->GroupId != Head->GroupId; }); Fn({I, Bound}); I = Bound; } } // Compare two lists of relocations. template <class ELFT> template <class RelTy> bool ICF<ELFT>::relocationEq(ArrayRef<RelTy> RelsA, ArrayRef<RelTy> RelsB) { auto Eq = [](const RelTy &A, const RelTy &B) { return A.r_offset == B.r_offset && A.getType(Config->Mips64EL) == B.getType(Config->Mips64EL) && getAddend<ELFT>(A) == getAddend<ELFT>(B); }; return RelsA.size() == RelsB.size() && std::equal(RelsA.begin(), RelsA.end(), RelsB.begin(), Eq); } // Compare "non-moving" part of two InputSections, namely everything // except relocation targets. template <class ELFT> bool ICF<ELFT>::equalsConstant(const InputSection<ELFT> *A, const InputSection<ELFT> *B) { if (A->NumRelocations != B->NumRelocations) return false; if (A->AreRelocsRela) { if (!relocationEq(A->relas(), B->relas())) return false; } else { if (!relocationEq(A->rels(), B->rels())) return false; } return A->Flags == B->Flags && A->getSize() == B->getSize() && A->Data == B->Data; } template <class ELFT> template <class RelTy> bool ICF<ELFT>::variableEq(const InputSection<ELFT> *A, ArrayRef<RelTy> RelsA, const InputSection<ELFT> *B, ArrayRef<RelTy> RelsB) { auto Eq = [&](const RelTy &RA, const RelTy &RB) { SymbolBody &SA = A->File->getRelocTargetSym(RA); SymbolBody &SB = B->File->getRelocTargetSym(RB); if (&SA == &SB) return true; // Or, the symbols should be pointing to the same section // in terms of the group ID. auto *DA = dyn_cast<DefinedRegular<ELFT>>(&SA); auto *DB = dyn_cast<DefinedRegular<ELFT>>(&SB); if (!DA || !DB) return false; if (DA->Value != DB->Value) return false; InputSection<ELFT> *X = dyn_cast<InputSection<ELFT>>(DA->Section); InputSection<ELFT> *Y = dyn_cast<InputSection<ELFT>>(DB->Section); return X && Y && X->GroupId && X->GroupId == Y->GroupId; }; return std::equal(RelsA.begin(), RelsA.end(), RelsB.begin(), Eq); } // Compare "moving" part of two InputSections, namely relocation targets. template <class ELFT> bool ICF<ELFT>::equalsVariable(const InputSection<ELFT> *A, const InputSection<ELFT> *B) { if (A->AreRelocsRela) return variableEq(A, A->relas(), B, B->relas()); return variableEq(A, A->rels(), B, B->rels()); } // The main function of ICF. template <class ELFT> void ICF<ELFT>::run() { // Initially, we use hash values as section group IDs. Therefore, // if two sections have the same ID, they are likely (but not // guaranteed) to have the same static contents in terms of ICF. std::vector<InputSection<ELFT> *> Sections = getSections(); for (InputSection<ELFT> *S : Sections) // Set MSB on to avoid collisions with serial group IDs S->GroupId = getHash(S) | (uint64_t(1) << 63); // From now on, sections in V are ordered so that sections in // the same group are consecutive in the vector. std::stable_sort(Sections.begin(), Sections.end(), [](InputSection<ELFT> *A, InputSection<ELFT> *B) { if (A->GroupId != B->GroupId) return A->GroupId < B->GroupId; // Within a group, put the highest alignment // requirement first, so that's the one we'll keep. return B->Alignment < A->Alignment; }); // Compare static contents and assign unique IDs for each static content. forEachGroup(Sections, [&](MutableArrayRef<InputSection<ELFT> *> V) { segregate(V, equalsConstant); }); // Split groups by comparing relocations until we get a convergence. int Cnt = 1; for (;;) { ++Cnt; uint64_t Id = NextId; forEachGroup(Sections, [&](MutableArrayRef<InputSection<ELFT> *> V) { segregate(V, equalsVariable); }); if (Id == NextId) break; } log("ICF needed " + Twine(Cnt) + " iterations."); // Merge sections in the same group. forEachGroup(Sections, [&](MutableArrayRef<InputSection<ELFT> *> V) { InputSection<ELFT> *Head = V[0]; log("selected " + Head->Name); for (InputSection<ELFT> *S : V.slice(1)) { log(" removed " + S->Name); Head->replace(S); } }); } // ICF entry point function. template <class ELFT> void elf::doIcf() { ICF<ELFT>().run(); } template void elf::doIcf<ELF32LE>(); template void elf::doIcf<ELF32BE>(); template void elf::doIcf<ELF64LE>(); template void elf::doIcf<ELF64BE>(); <|endoftext|>
<commit_before>#include <allegro.h> #ifdef ALLEGRO_WINDOWS #include <winalleg.h> #endif #ifndef ALLEGRO_WINDOWS #include <signal.h> #include <string.h> #endif /* don't be a boring tuna */ #warning you are ugly #include "globals.h" #include "init.h" #include <pthread.h> #include "network/network.h" #include <ostream> #include "dumb/include/dumb.h" #include "dumb/include/aldumb.h" #include "loadpng/loadpng.h" #include "util/bitmap.h" #include "util/funcs.h" #include "configuration.h" #include "script/script.h" #include "music.h" using namespace std; volatile int Global::speed_counter = 0; volatile int Global::second_counter = 0; /* the original engine was running at 90 ticks per second, but we dont * need to render that fast, so TICS_PER_SECOND is really fps and * LOGIC_MULTIPLIER will be used to adjust the speed counter to its * original value. */ const int Global::TICS_PER_SECOND = 40; const double Global::LOGIC_MULTIPLIER = (double) 90 / (double) Global::TICS_PER_SECOND; pthread_mutex_t Global::loading_screen_mutex; bool Global::done_loading = false; const int Global::WINDOWED = GFX_AUTODETECT_WINDOWED; const int Global::FULLSCREEN = GFX_AUTODETECT_FULLSCREEN; /* game counter, controls FPS */ void inc_speed_counter(){ /* probably put input polling here, InputManager::poll() */ Global::speed_counter += 1; } END_OF_FUNCTION( inc_speed_counter ); /* if you need to count seconds for some reason.. */ void inc_second_counter() { Global::second_counter += 1; } END_OF_FUNCTION( inc_second_counter ); #ifndef ALLEGRO_WINDOWS static void handleSigSegV(int i, siginfo_t * sig, void * data){ const char * message = "Bug! Caught a memory violation. Shutting down..\n"; int dont_care = write(1, message, 48); dont_care = dont_care; // Global::shutdown_message = "Bug! Caught a memory violation. Shutting down.."; Bitmap::setGfxModeText(); allegro_exit(); /* write to a log file or something because sigsegv shouldn't * normally happen. */ exit(1); } #else #endif /* catch a socket being closed prematurely on unix */ #ifndef ALLEGRO_WINDOWS static void handleSigPipe( int i, siginfo_t * sig, void * data ){ } /* static void handleSigUsr1( int i, siginfo_t * sig, void * data ){ pthread_exit( NULL ); } */ #endif static void registerSignals(){ #ifndef ALLEGRO_WINDOWS struct sigaction action; memset( &action, 0, sizeof(struct sigaction) ); action.sa_sigaction = handleSigPipe; sigaction( SIGPIPE, &action, NULL ); memset( &action, 0, sizeof(struct sigaction) ); action.sa_sigaction = handleSigSegV; sigaction( SIGSEGV, &action, NULL ); /* action.sa_sigaction = handleSigUsr1; sigaction( SIGUSR1, &action, NULL ); */ #endif } /* should probably call the janitor here or something */ static void close_paintown(){ Music::pause(); Bitmap::setGfxModeText(); allegro_exit(); exit(0); } END_OF_FUNCTION(close_paintown) bool Global::init( int gfx ){ ostream & out = Global::debug( 0 ); out << "-- BEGIN init --" << endl; out << "Data path is " << Util::getDataPath() << endl; out << "Paintown version " << Global::getVersionString() << endl; out << "Allegro version: " << ALLEGRO_VERSION_STR << endl; out <<"Allegro init: "<<allegro_init()<<endl; out <<"Install timer: "<<install_timer()<<endl; set_volume_per_voice( 0 ); out<<"Install sound: "<<install_sound( DIGI_AUTODETECT, MIDI_NONE, "" )<<endl; /* png */ loadpng_init(); Bitmap::SCALE_X = GFX_X; Bitmap::SCALE_Y = GFX_Y; Configuration::loadConfigurations(); const int sx = Configuration::getScreenWidth(); const int sy = Configuration::getScreenHeight(); out<<"Install keyboard: "<<install_keyboard()<<endl; out<<"Install mouse: "<<install_mouse()<<endl; out<<"Install joystick: "<<install_joystick(JOY_TYPE_AUTODETECT)<<endl; /* 16 bit color depth */ set_color_depth( 16 ); /* set up the screen */ out<<"Set gfx mode: " << Bitmap::setGraphicsMode( gfx, sx, sy ) <<endl; LOCK_VARIABLE( speed_counter ); LOCK_VARIABLE( second_counter ); LOCK_FUNCTION( (void *)inc_speed_counter ); LOCK_FUNCTION( (void *)inc_second_counter ); /* set up the timers */ out<<"Install game timer: "<<install_int_ex( inc_speed_counter, BPS_TO_TIMER( TICS_PER_SECOND ) )<<endl; out<<"Install second timer: "<<install_int_ex( inc_second_counter, BPS_TO_TIMER( 1 ) )<<endl; out << "Initialize random number generator" << endl; /* initialize random number generator */ srand( time( NULL ) ); /* keep running in the background */ set_display_switch_mode(SWITCH_BACKGROUND); /* close window when the X is pressed */ LOCK_FUNCTION(close_paintown); set_close_button_callback(close_paintown); /* music */ atexit( &dumb_exit ); atexit( Network::closeAll ); dumb_register_packfiles(); registerSignals(); out << "Initialize network" << endl; Network::init(); /* this mutex is used to show the loading screen while the game loads */ pthread_mutex_init( &Global::loading_screen_mutex, NULL ); out<<"-- END init --"<<endl; return true; } <commit_msg>print build time<commit_after>#include <allegro.h> #ifdef ALLEGRO_WINDOWS #include <winalleg.h> #endif #ifndef ALLEGRO_WINDOWS #include <signal.h> #include <string.h> #endif /* don't be a boring tuna */ #warning you are ugly #include "globals.h" #include "init.h" #include <pthread.h> #include "network/network.h" #include <ostream> #include "dumb/include/dumb.h" #include "dumb/include/aldumb.h" #include "loadpng/loadpng.h" #include "util/bitmap.h" #include "util/funcs.h" #include "configuration.h" #include "script/script.h" #include "music.h" using namespace std; volatile int Global::speed_counter = 0; volatile int Global::second_counter = 0; /* the original engine was running at 90 ticks per second, but we dont * need to render that fast, so TICS_PER_SECOND is really fps and * LOGIC_MULTIPLIER will be used to adjust the speed counter to its * original value. */ const int Global::TICS_PER_SECOND = 40; const double Global::LOGIC_MULTIPLIER = (double) 90 / (double) Global::TICS_PER_SECOND; pthread_mutex_t Global::loading_screen_mutex; bool Global::done_loading = false; const int Global::WINDOWED = GFX_AUTODETECT_WINDOWED; const int Global::FULLSCREEN = GFX_AUTODETECT_FULLSCREEN; /* game counter, controls FPS */ void inc_speed_counter(){ /* probably put input polling here, InputManager::poll() */ Global::speed_counter += 1; } END_OF_FUNCTION( inc_speed_counter ); /* if you need to count seconds for some reason.. */ void inc_second_counter() { Global::second_counter += 1; } END_OF_FUNCTION( inc_second_counter ); #ifndef ALLEGRO_WINDOWS static void handleSigSegV(int i, siginfo_t * sig, void * data){ const char * message = "Bug! Caught a memory violation. Shutting down..\n"; int dont_care = write(1, message, 48); dont_care = dont_care; // Global::shutdown_message = "Bug! Caught a memory violation. Shutting down.."; Bitmap::setGfxModeText(); allegro_exit(); /* write to a log file or something because sigsegv shouldn't * normally happen. */ exit(1); } #else #endif /* catch a socket being closed prematurely on unix */ #ifndef ALLEGRO_WINDOWS static void handleSigPipe( int i, siginfo_t * sig, void * data ){ } /* static void handleSigUsr1( int i, siginfo_t * sig, void * data ){ pthread_exit( NULL ); } */ #endif static void registerSignals(){ #ifndef ALLEGRO_WINDOWS struct sigaction action; memset( &action, 0, sizeof(struct sigaction) ); action.sa_sigaction = handleSigPipe; sigaction( SIGPIPE, &action, NULL ); memset( &action, 0, sizeof(struct sigaction) ); action.sa_sigaction = handleSigSegV; sigaction( SIGSEGV, &action, NULL ); /* action.sa_sigaction = handleSigUsr1; sigaction( SIGUSR1, &action, NULL ); */ #endif } /* should probably call the janitor here or something */ static void close_paintown(){ Music::pause(); Bitmap::setGfxModeText(); allegro_exit(); exit(0); } END_OF_FUNCTION(close_paintown) bool Global::init( int gfx ){ ostream & out = Global::debug( 0 ); out << "-- BEGIN init --" << endl; out << "Data path is " << Util::getDataPath() << endl; out << "Paintown version " << Global::getVersionString() << endl; out << "Build date " << __DATE__ << " " << __TIME__ << endl; out << "Allegro version: " << ALLEGRO_VERSION_STR << endl; out <<"Allegro init: "<<allegro_init()<<endl; out <<"Install timer: "<<install_timer()<<endl; set_volume_per_voice( 0 ); out<<"Install sound: "<<install_sound( DIGI_AUTODETECT, MIDI_NONE, "" )<<endl; /* png */ loadpng_init(); Bitmap::SCALE_X = GFX_X; Bitmap::SCALE_Y = GFX_Y; Configuration::loadConfigurations(); const int sx = Configuration::getScreenWidth(); const int sy = Configuration::getScreenHeight(); out<<"Install keyboard: "<<install_keyboard()<<endl; out<<"Install mouse: "<<install_mouse()<<endl; out<<"Install joystick: "<<install_joystick(JOY_TYPE_AUTODETECT)<<endl; /* 16 bit color depth */ set_color_depth( 16 ); /* set up the screen */ out<<"Set gfx mode: " << Bitmap::setGraphicsMode( gfx, sx, sy ) <<endl; LOCK_VARIABLE( speed_counter ); LOCK_VARIABLE( second_counter ); LOCK_FUNCTION( (void *)inc_speed_counter ); LOCK_FUNCTION( (void *)inc_second_counter ); /* set up the timers */ out<<"Install game timer: "<<install_int_ex( inc_speed_counter, BPS_TO_TIMER( TICS_PER_SECOND ) )<<endl; out<<"Install second timer: "<<install_int_ex( inc_second_counter, BPS_TO_TIMER( 1 ) )<<endl; out << "Initialize random number generator" << endl; /* initialize random number generator */ srand( time( NULL ) ); /* keep running in the background */ set_display_switch_mode(SWITCH_BACKGROUND); /* close window when the X is pressed */ LOCK_FUNCTION(close_paintown); set_close_button_callback(close_paintown); /* music */ atexit( &dumb_exit ); atexit( Network::closeAll ); dumb_register_packfiles(); registerSignals(); out << "Initialize network" << endl; Network::init(); /* this mutex is used to show the loading screen while the game loads */ pthread_mutex_init( &Global::loading_screen_mutex, NULL ); out<<"-- END init --"<<endl; return true; } <|endoftext|>
<commit_before>#include <cstdio> #include <stdlib.h> #include <string.h> #if defined(__NODE_V0_11_OR_12__) || defined(__NODE_GE_V4__) #include <fcntl.h> #endif //#ifdef __POSIX__ #include <unistd.h> /*#else #include <process.h> #endif*/ #include <nan.h> using v8::Array; using v8::FunctionTemplate; using v8::Handle; using v8::Integer; using v8::Local; using v8::Object; using v8::String; static int clear_cloexec (int desc) { int flags = fcntl (desc, F_GETFD, 0); if (flags < 0) return flags; //return if reading failed flags &= ~FD_CLOEXEC; //clear FD_CLOEXEC bit return fcntl (desc, F_SETFD, flags); } static int do_exec(char *argv[]) { clear_cloexec(0); //stdin clear_cloexec(1); //stdout clear_cloexec(2); //stderr return execvp(argv[0], argv); } NAN_METHOD(kexec) { Nan::HandleScope scope; /* * Steve Blott: 17 Jan, 2014 * Temporary comment by way of explanation... * To be deleted. * * With a single argument: * - pass it to execvp as "sh -c 'args[0]'" * - this is the existing usage * * With exactly two arguments: * - the first is the command name * - the second is an array of arguments * ...as in process.child_process.spawn() * * This approach is not great, but it allows the established usage to * coexist with direct execvp-usage, and avoids making any changes to the * established API. */ if ( 1 == info.Length() && info[0]->IsString() ) { String::Utf8Value str(info[0]); char* argv[] = { const_cast<char *>("/bin/sh"), const_cast<char *>("-c"), *str, NULL}; int err = do_exec(argv); info.GetReturnValue().Set(Nan::New<Integer>(err)); } if ( 2 == info.Length() && info[0]->IsString() && info[1]->IsArray() ) { String::Utf8Value str(info[0]); // Substantially copied from: // https://github.com/joyent/node/blob/2944e03/src/node_child_process.cc#L92-104 Local<Array> argv_handle = Local<Array>::Cast(info[1]); int argc = argv_handle->Length(); int argv_length = argc + 1 + 1; char **argv = new char*[argv_length]; argv[0] = *str; argv[argv_length-1] = NULL; for (int i = 0; i < argc; i++) { String::Utf8Value arg(argv_handle->Get(Nan::New<Integer>(i))->ToString()); argv[i+1] = strdup(*arg); } int err = do_exec(argv); // Failed...! // FIXME: It might be better to raise an exception here. for (int i = 0; i < argc; i++) free(argv[i+1]); delete [] argv; info.GetReturnValue().Set(Nan::New<Integer>(err)); } return Nan::ThrowTypeError("kexec: invalid arguments"); } #define EXPORT(name, symbol) exports->Set( \ Nan::New<String>(name).ToLocalChecked(), \ Nan::New<FunctionTemplate>(symbol)->GetFunction() \ ) void init (Handle<Object> exports) { EXPORT("kexec", kexec); } NODE_MODULE(kexec, init); <commit_msg>Remove unnecessary handle scope<commit_after>#include <cstdio> #include <stdlib.h> #include <string.h> #if defined(__NODE_V0_11_OR_12__) || defined(__NODE_GE_V4__) #include <fcntl.h> #endif //#ifdef __POSIX__ #include <unistd.h> /*#else #include <process.h> #endif*/ #include <nan.h> using v8::Array; using v8::FunctionTemplate; using v8::Handle; using v8::Integer; using v8::Local; using v8::Object; using v8::String; static int clear_cloexec (int desc) { int flags = fcntl (desc, F_GETFD, 0); if (flags < 0) return flags; //return if reading failed flags &= ~FD_CLOEXEC; //clear FD_CLOEXEC bit return fcntl (desc, F_SETFD, flags); } static int do_exec(char *argv[]) { clear_cloexec(0); //stdin clear_cloexec(1); //stdout clear_cloexec(2); //stderr return execvp(argv[0], argv); } NAN_METHOD(kexec) { /* * Steve Blott: 17 Jan, 2014 * Temporary comment by way of explanation... * To be deleted. * * With a single argument: * - pass it to execvp as "sh -c 'args[0]'" * - this is the existing usage * * With exactly two arguments: * - the first is the command name * - the second is an array of arguments * ...as in process.child_process.spawn() * * This approach is not great, but it allows the established usage to * coexist with direct execvp-usage, and avoids making any changes to the * established API. */ if ( 1 == info.Length() && info[0]->IsString() ) { String::Utf8Value str(info[0]); char* argv[] = { const_cast<char *>("/bin/sh"), const_cast<char *>("-c"), *str, NULL}; int err = do_exec(argv); info.GetReturnValue().Set(Nan::New<Integer>(err)); } if ( 2 == info.Length() && info[0]->IsString() && info[1]->IsArray() ) { String::Utf8Value str(info[0]); // Substantially copied from: // https://github.com/joyent/node/blob/2944e03/src/node_child_process.cc#L92-104 Local<Array> argv_handle = Local<Array>::Cast(info[1]); int argc = argv_handle->Length(); int argv_length = argc + 1 + 1; char **argv = new char*[argv_length]; argv[0] = *str; argv[argv_length-1] = NULL; for (int i = 0; i < argc; i++) { String::Utf8Value arg(argv_handle->Get(Nan::New<Integer>(i))->ToString()); argv[i+1] = strdup(*arg); } int err = do_exec(argv); // Failed...! // FIXME: It might be better to raise an exception here. for (int i = 0; i < argc; i++) free(argv[i+1]); delete [] argv; info.GetReturnValue().Set(Nan::New<Integer>(err)); } return Nan::ThrowTypeError("kexec: invalid arguments"); } #define EXPORT(name, symbol) exports->Set( \ Nan::New<String>(name).ToLocalChecked(), \ Nan::New<FunctionTemplate>(symbol)->GetFunction() \ ) void init (Handle<Object> exports) { EXPORT("kexec", kexec); } NODE_MODULE(kexec, init); <|endoftext|>
<commit_before>//stl list //载入头文件 #include <iostream> #include <list> using namespace std; typedef struct { char name[21]; int id; } note ; int main(int argc, char const *argv[]) { //建立 list<int> L0; // 空链表 list<int> L1(9); // 建一个含一个元素的链表 list<int> L2(5,1); // 建一个多个个元素的链表 list<int> L3(L2); // 复制L2的元素,重新建立一个链表 list<int> L4(L0.begin(), L0.end());//建一个含L0一个区域的链表 //其他元素类型的链表 list<double> Ld; list<note> Lu; //链表操作 //一个链表 list<int> l; //在链表头部插入元素 l.push_front(1); //尾部 l.push_back(2); return 0; }<commit_msg>update list<commit_after>//stl list //载入头文件 #include <iostream> #include <list> using namespace std; typedef struct { char name[21]; int id; } note ; int main(int argc, char const *argv[]) { //建立 list<int> L0; // 空链表 list<int> L1(9); // 建一个含一个元素的链表 list<int> L2(5,1); // 建一个多个个元素的链表 list<int> L3(L2); // 复制L2的元素,重新建立一个链表 list<int> L4(L0.begin(), L0.end());//建一个含L0一个区域的链表 //其他元素类型的链表 list<double> Ld; list<note> Lu; //链表操作 //一个链表 list<int> l; //在链表头部插入元素 l.push_front(1); //尾部 l.push_back(2); //返回第一个元素的引用 int n= l.front() // = 1 //返回最后一元素的引用 n = l.back() // = 2 //返回第一个元素的迭代器(iterator) list<int>::iterator it = l.begin(); // *it = 1 //返回最后一个元素的下一位置的指针(list为空时end()=begin()) it = l.end(); return 0; }<|endoftext|>
<commit_before>/* * main.cpp * Copyright (c) 2015 Markus Himmel. All rights reserved. * Distributed under the terms of the MIT license. */ #include <algorithm> #include <iostream> #include <String.h> #include <Directory.h> #include "BookmarksTree.h" #include "BookmarksFormat.h" int helpMessage(int code, BookmarksOutput* a, BookmarksInput* b) { delete a; delete b; std::cout << "Converts browser bookmarks between a selection of formats." << std::endl << std::endl << "Usage: bookmarkconverter -f [format] [inputpath]" << " [outputpath]" << std::endl << " bookmarkconverter --webpositive-import -f [format]" << " [outputpath]" << std::endl << " bookmarkconverter --qupzilla-import -f [format]" << " [outputpath]" << std::endl << " bookmarkconverter --help" << std::endl << std::endl << " format " << "The destination format (HTML, CHROME, WEBPOSITIVE)" << std::endl; return code; } int main(int argc, char* argv[]) { BookmarksOutput* output = NULL; BookmarksInput* input = NULL; int curarg = 0, curpath = 0;; BString paths[2]; while (curarg + 1 < argc) { curarg++; BString current(argv[curarg]); if (current == "-h" || current == "--help") return helpMessage(0, output, input); else if (current == "-f" || current == "--format") { if (curarg == argc - 1) return helpMessage(1, output, input); else { curarg++; BString format(argv[curarg]); if (format.ICompare("html") == 0) output = new HTMLOutput(); else if (format.ICompare("chrome") == 0) output = new ChromeOutput(); else if (format.ICompare("webpositive") == 0) output = new BeOutput(); else if (format.ICompare("qupzilla") == 0) output = new QupZillaOutput(); else return helpMessage(2, output, input); } } else if (current == "--webpositive-import") { input = new BeInput(); paths[0] = ""; curpath = std::max(curpath, 1); } else if (current == "--qupzilla-import") { input = new QupZillaInput(); paths[0] = ""; curpath = std::max(curpath, 1); } else if (curpath >= 2) return helpMessage(5, output, input); else paths[curpath++] = argv[curarg]; } if (input == NULL) { BDirectory test(paths[0].String()); input = (test.InitCheck() == B_OK) ? new BeInput() : new QupZillaInput(); } if (output == NULL) return helpMessage(4, output, input); BookmarksEntry* read = input->Input(paths[0].String()); if (read != NULL) output->Output(read, paths[1].String()); else std::cerr << "There was an error reading the input" << std::endl; delete input; delete output; return 0; } <commit_msg>Add missing output format in the help message<commit_after>/* * main.cpp * Copyright (c) 2015 Markus Himmel. All rights reserved. * Distributed under the terms of the MIT license. */ #include <algorithm> #include <iostream> #include <String.h> #include <Directory.h> #include "BookmarksTree.h" #include "BookmarksFormat.h" int helpMessage(int code, BookmarksOutput* a, BookmarksInput* b) { delete a; delete b; std::cout << "Converts browser bookmarks between a selection of formats." << std::endl << std::endl << "Usage: bookmarkconverter -f [format] [inputpath]" << " [outputpath]" << std::endl << " bookmarkconverter --webpositive-import -f [format]" << " [outputpath]" << std::endl << " bookmarkconverter --qupzilla-import -f [format]" << " [outputpath]" << std::endl << " bookmarkconverter --help" << std::endl << std::endl << " format " << "The destination format (HTML, CHROME, WEBPOSITIVE, " << "QUPZILLA)" << std::endl; return code; } int main(int argc, char* argv[]) { BookmarksOutput* output = NULL; BookmarksInput* input = NULL; int curarg = 0, curpath = 0;; BString paths[2]; while (curarg + 1 < argc) { curarg++; BString current(argv[curarg]); if (current == "-h" || current == "--help") return helpMessage(0, output, input); else if (current == "-f" || current == "--format") { if (curarg == argc - 1) return helpMessage(1, output, input); else { curarg++; BString format(argv[curarg]); if (format.ICompare("html") == 0) output = new HTMLOutput(); else if (format.ICompare("chrome") == 0) output = new ChromeOutput(); else if (format.ICompare("webpositive") == 0) output = new BeOutput(); else if (format.ICompare("qupzilla") == 0) output = new QupZillaOutput(); else return helpMessage(2, output, input); } } else if (current == "--webpositive-import") { input = new BeInput(); paths[0] = ""; curpath = std::max(curpath, 1); } else if (current == "--qupzilla-import") { input = new QupZillaInput(); paths[0] = ""; curpath = std::max(curpath, 1); } else if (curpath >= 2) return helpMessage(5, output, input); else paths[curpath++] = argv[curarg]; } if (input == NULL) { BDirectory test(paths[0].String()); input = (test.InitCheck() == B_OK) ? new BeInput() : new QupZillaInput(); } if (output == NULL) return helpMessage(4, output, input); BookmarksEntry* read = input->Input(paths[0].String()); if (read != NULL) output->Output(read, paths[1].String()); else std::cerr << "There was an error reading the input" << std::endl; delete input; delete output; return 0; } <|endoftext|>
<commit_before>#include <iostream> #include <cstddef> #include <time.h> #include "StackAllocator.h" /* void test_primitives(Allocator &allocator){ std::cout << "\tTEST_PRIMITIVES_TYPES" << std::endl; allocator.Allocate(sizeof(int), alignof(int)); // 4 -> 4 allocator.Allocate(sizeof(bool), alignof(bool)); // 1 -> 5 // 3 -> 8 allocator.Allocate(sizeof(int), alignof(int)); // 4 -> 12 // 4 -> 16 allocator.Allocate(sizeof(double), alignof(double)); // 8 -> 24 allocator.Allocate(sizeof(char), alignof(char)); // 1 -> 25 // 3 -> 28 allocator.Allocate(sizeof(int), alignof(int)); // 4 -> 32 allocator.Reset(); std::cout << std::endl; } void test_primitives_unaligned(Allocator &allocator){ std::cout << "\tTEST_PRIMITIVES_TYPES_UNALIGNED" << std::endl; allocator.Allocate(sizeof(int)); // 4 -> 4 allocator.Allocate(sizeof(bool)); // 1 -> 5 // 0 -> 5 allocator.Allocate(sizeof(int)); // 4 -> 9 allocator.Allocate(sizeof(double)); // 8 -> 17 allocator.Allocate(sizeof(char)); // 1 -> 18 // 0 -> 18 allocator.Allocate(sizeof(int)); // 4 -> 22 allocator.Reset(); std::cout << std::endl; } void test_structs(Allocator &allocator){ std::cout << "\tTEST_CUSTOM_TYPES" << std::endl; allocator.Allocate(sizeof(bar), alignof(bar)); // 16 -> 16 allocator.Allocate(sizeof(foo), alignof(foo)); // 16 -> 32 allocator.Allocate(sizeof(baz), alignof(baz)); // 4 -> 36 allocator.Allocate(sizeof(bool), alignof(bool)); // 1 -> 37 // 3 -> 40 allocator.Allocate(sizeof(foo3), alignof(foo3)); // 8 -> 48 allocator.Reset(); std::cout << std::endl; } void test_structs_unaligned(Allocator &allocator){ std::cout << "\tTEST_CUSTOM_TYPES_UNALIGNED" << std::endl; allocator.Allocate(sizeof(bar), 0); // 16 -> 16 allocator.Allocate(sizeof(foo), 0); // 16 -> 32 allocator.Allocate(sizeof(baz), 0); // 4 -> 36 allocator.Allocate(sizeof(bool), 0); // 1 -> 37 // 0 -> 37 allocator.Allocate(sizeof(foo3), 0); // 8 -> 45 allocator.Reset(); std::cout << std::endl; } void test_linear_allocator(){ std::cout << "TEST_LINEAR_ALLOCATOR" << std::endl; LinearAllocator linearAllocator(100); test_primitives(linearAllocator); test_structs(linearAllocator); test_primitives_unaligned(linearAllocator); test_structs_unaligned(linearAllocator); } void test_stack_allocator_primitives(StackAllocator &stackAllocator){ std::cout << "\tTEST_PRIMITIVES_TYPES" << std::endl; stackAllocator.Allocate(sizeof(bool), alignof(bool)); // 1 -> 1 // 3 -> 4 stackAllocator.Allocate(sizeof(baz), alignof(baz)); // 4 -> 8 stackAllocator.Allocate(sizeof(int), alignof(int)); // 4 -> 12 std::cout << std::endl; stackAllocator.Free(nullptr, sizeof(int)); // 4 -> 8 stackAllocator.Free(nullptr, sizeof(baz)); // 8 -> 4(3) -> 1 // 7 -> 8 stackAllocator.Allocate(sizeof(double), alignof(double)); // 8 -> 16 stackAllocator.Reset(); } void test_stack_allocator(){ std::cout << "TEST_STACK_ALLOCATOR" << std::endl; StackAllocator stackAllocator(100); //test_primitives(stackAllocator); //test_structs(stackAllocator); //test_primitives_unaligned(stackAllocator); //test_structs_unaligned(stackAllocator); test_stack_allocator_primitives(stackAllocator); } */ struct foo { char *p; /* 8 bytes */ char c; /* 1 byte */ }; struct bar { int a; // 4 bool b; // 1 -> 5 // 3 -> 8 int c; // 4 -> 12 bool d; // 1 -> 13 bool e; // 1 -> 14 // 2 -> 16 }; struct bar2 { int a; // 4 int c; // 4 -> 8 bool b; // 1 -> 9 bool d; bool e; // 3 -> 12 }; struct foo3 { int i; /* 4 byte */ char c; /* 1 bytes */ bool b; /* 1 bytes */ // 2 bytes }; struct foo2 { char c; /* 1 byte */ char *p; /* 8 bytes */ }; struct baz { short s; /* 2 bytes */ char c; /* 1 byte */ }; void setTimer(timespec& timer){ clock_gettime(CLOCK_REALTIME, &timer); } timespec diff(timespec &start, timespec &end) { timespec temp; if ((end.tv_nsec-start.tv_nsec)<0) { temp.tv_sec = end.tv_sec-start.tv_sec-1; temp.tv_nsec = 1e9+end.tv_nsec-start.tv_nsec; } else { temp.tv_sec = end.tv_sec-start.tv_sec; temp.tv_nsec = end.tv_nsec-start.tv_nsec; } return temp; } void print_benchmark_stats(const timespec& elapsed_time, const int& memory_used, const int&memory_wasted, const int max_operations){ double time_sec = (double) elapsed_time.tv_sec; double time_nsec = (double) elapsed_time.tv_nsec; double time_msec = (time_sec * 1000) + (time_nsec / 1000000); std::cout << std::endl; std::cout << "\tSTATS:" << std::endl; std::cout << "\t\tOperations: \t" << max_operations << std::endl; std::cout << "\t\tTime elapsed: \t" << time_msec << " ms" << std::endl; std::cout << "\t\tOp per sec: \t" << (max_operations / 1e3) / time_msec << " mops/ms" << std::endl; std::cout << "\t\tTimer per op: \t" << time_msec/(max_operations / 1e3) << " ms/mops" << std::endl; //std::cout << "\t\tMemory used: \t" << memory_used << " bytes" << std::endl; //std::cout << "\t\tMemory wasted: \t" << memory_wasted << " bytes\t" << ((float) memory_wasted / memory_used) * 100 << " %" << std::endl; std::cout << std::endl; } void benchmark_stack(long MAX_OPERATIONS = 1e4){ timespec start, end; std::cout << "BENCHMARK STACK ALLOCATOR: START" << std::endl; setTimer(start); StackAllocator stackAllocator(1e10); int operations = 0; while(operations < MAX_OPERATIONS){ stackAllocator.Allocate(sizeof(int), alignof(int)); // 4 -> 4 stackAllocator.Allocate(sizeof(bool), alignof(bool)); // 1 -> 5 // 3 -> 8 stackAllocator.Allocate(sizeof(foo), alignof(foo)); // 16 -> 24 ++operations; } setTimer(end); const timespec elapsed_time = diff(start, end); const std::size_t memory_used = 0; const std::size_t memory_wasted = 0; stackAllocator.Reset(); print_benchmark_stats(elapsed_time, memory_used, memory_wasted, MAX_OPERATIONS); std::cout << "BENCHMARK STACK ALLOCATOR: END" << std::endl; } void benchmark_malloc(long MAX_OPERATIONS = 1e4){ timespec start, end; std::cout << "BENCHMARK MALLOC ALLOCATOR: START" << std::endl; setTimer(start); int operations = 0; srand (1); while(operations < MAX_OPERATIONS){ malloc(sizeof(int)); malloc(sizeof(bool)); malloc(sizeof(foo)); ++operations; } setTimer(end); const timespec elapsed_time = diff(start, end); const std::size_t memory_used = 0; const std::size_t memory_wasted = 0; print_benchmark_stats(elapsed_time, memory_used, memory_wasted, MAX_OPERATIONS); std::cout << "BENCHMARK MALLOC ALLOCATOR: END" << std::endl; } /* TODO 1- Deinterface 2- benchmark free (3pointers) 3- move to utils file? */ int main(){ //benchmark_stack(1e7); benchmark_malloc(1e7); return 1; } <commit_msg>Added benchmark to measure time performance executing free operations.<commit_after>#include <iostream> #include <cstddef> #include <time.h> #include "StackAllocator.h" /* void test_primitives(Allocator &allocator){ std::cout << "\tTEST_PRIMITIVES_TYPES" << std::endl; allocator.Allocate(sizeof(int), alignof(int)); // 4 -> 4 allocator.Allocate(sizeof(bool), alignof(bool)); // 1 -> 5 // 3 -> 8 allocator.Allocate(sizeof(int), alignof(int)); // 4 -> 12 // 4 -> 16 allocator.Allocate(sizeof(double), alignof(double)); // 8 -> 24 allocator.Allocate(sizeof(char), alignof(char)); // 1 -> 25 // 3 -> 28 allocator.Allocate(sizeof(int), alignof(int)); // 4 -> 32 allocator.Reset(); std::cout << std::endl; } void test_primitives_unaligned(Allocator &allocator){ std::cout << "\tTEST_PRIMITIVES_TYPES_UNALIGNED" << std::endl; allocator.Allocate(sizeof(int)); // 4 -> 4 allocator.Allocate(sizeof(bool)); // 1 -> 5 // 0 -> 5 allocator.Allocate(sizeof(int)); // 4 -> 9 allocator.Allocate(sizeof(double)); // 8 -> 17 allocator.Allocate(sizeof(char)); // 1 -> 18 // 0 -> 18 allocator.Allocate(sizeof(int)); // 4 -> 22 allocator.Reset(); std::cout << std::endl; } void test_structs(Allocator &allocator){ std::cout << "\tTEST_CUSTOM_TYPES" << std::endl; allocator.Allocate(sizeof(bar), alignof(bar)); // 16 -> 16 allocator.Allocate(sizeof(foo), alignof(foo)); // 16 -> 32 allocator.Allocate(sizeof(baz), alignof(baz)); // 4 -> 36 allocator.Allocate(sizeof(bool), alignof(bool)); // 1 -> 37 // 3 -> 40 allocator.Allocate(sizeof(foo3), alignof(foo3)); // 8 -> 48 allocator.Reset(); std::cout << std::endl; } void test_structs_unaligned(Allocator &allocator){ std::cout << "\tTEST_CUSTOM_TYPES_UNALIGNED" << std::endl; allocator.Allocate(sizeof(bar), 0); // 16 -> 16 allocator.Allocate(sizeof(foo), 0); // 16 -> 32 allocator.Allocate(sizeof(baz), 0); // 4 -> 36 allocator.Allocate(sizeof(bool), 0); // 1 -> 37 // 0 -> 37 allocator.Allocate(sizeof(foo3), 0); // 8 -> 45 allocator.Reset(); std::cout << std::endl; } void test_linear_allocator(){ std::cout << "TEST_LINEAR_ALLOCATOR" << std::endl; LinearAllocator linearAllocator(100); test_primitives(linearAllocator); test_structs(linearAllocator); test_primitives_unaligned(linearAllocator); test_structs_unaligned(linearAllocator); } void test_stack_allocator_primitives(StackAllocator &stackAllocator){ std::cout << "\tTEST_PRIMITIVES_TYPES" << std::endl; stackAllocator.Allocate(sizeof(bool), alignof(bool)); // 1 -> 1 // 3 -> 4 stackAllocator.Allocate(sizeof(baz), alignof(baz)); // 4 -> 8 stackAllocator.Allocate(sizeof(int), alignof(int)); // 4 -> 12 std::cout << std::endl; stackAllocator.Free(nullptr, sizeof(int)); // 4 -> 8 stackAllocator.Free(nullptr, sizeof(baz)); // 8 -> 4(3) -> 1 // 7 -> 8 stackAllocator.Allocate(sizeof(double), alignof(double)); // 8 -> 16 stackAllocator.Reset(); } void test_stack_allocator(){ std::cout << "TEST_STACK_ALLOCATOR" << std::endl; StackAllocator stackAllocator(100); //test_primitives(stackAllocator); //test_structs(stackAllocator); //test_primitives_unaligned(stackAllocator); //test_structs_unaligned(stackAllocator); test_stack_allocator_primitives(stackAllocator); } */ struct foo { char *p; /* 8 bytes */ char c; /* 1 byte */ }; struct bar { int a; // 4 bool b; // 1 -> 5 // 3 -> 8 int c; // 4 -> 12 bool d; // 1 -> 13 bool e; // 1 -> 14 // 2 -> 16 }; struct bar2 { int a; // 4 int c; // 4 -> 8 bool b; // 1 -> 9 bool d; bool e; // 3 -> 12 }; struct foo3 { int i; /* 4 byte */ char c; /* 1 bytes */ bool b; /* 1 bytes */ // 2 bytes }; struct foo2 { char c; /* 1 byte */ char *p; /* 8 bytes */ }; struct baz { short s; /* 2 bytes */ char c; /* 1 byte */ }; void setTimer(timespec& timer){ clock_gettime(CLOCK_REALTIME, &timer); } timespec diff(timespec &start, timespec &end) { timespec temp; if ((end.tv_nsec-start.tv_nsec)<0) { temp.tv_sec = end.tv_sec-start.tv_sec-1; temp.tv_nsec = 1e9+end.tv_nsec-start.tv_nsec; } else { temp.tv_sec = end.tv_sec-start.tv_sec; temp.tv_nsec = end.tv_nsec-start.tv_nsec; } return temp; } void print_benchmark_stats(const timespec& elapsed_time, const int& memory_used, const int&memory_wasted, const int max_operations){ double time_sec = (double) elapsed_time.tv_sec; double time_nsec = (double) elapsed_time.tv_nsec; double time_msec = (time_sec * 1000) + (time_nsec / 1000000); std::cout << std::endl; std::cout << "\tSTATS:" << std::endl; std::cout << "\t\tOperations: \t" << max_operations << std::endl; std::cout << "\t\tTime elapsed: \t" << time_msec << " ms" << std::endl; std::cout << "\t\tOp per sec: \t" << (max_operations / 1e3) / time_msec << " mops/ms" << std::endl; std::cout << "\t\tTimer per op: \t" << time_msec/(max_operations / 1e3) << " ms/mops" << std::endl; //std::cout << "\t\tMemory used: \t" << memory_used << " bytes" << std::endl; //std::cout << "\t\tMemory wasted: \t" << memory_wasted << " bytes\t" << ((float) memory_wasted / memory_used) * 100 << " %" << std::endl; std::cout << std::endl; } void benchmark_stack_allocate(long MAX_OPERATIONS = 1e4){ timespec start, end; std::cout << "BENCHMARK STACK A: START" << std::endl; setTimer(start); StackAllocator stackAllocator(1e10); int operations = 0; while(operations < MAX_OPERATIONS){ stackAllocator.Allocate(sizeof(int), alignof(int)); // 4 -> 4 stackAllocator.Allocate(sizeof(bool), alignof(bool)); // 1 -> 5 // 3 -> 8 stackAllocator.Allocate(sizeof(foo), alignof(foo)); // 16 -> 24 ++operations; } setTimer(end); const timespec elapsed_time = diff(start, end); const std::size_t memory_used = 0; const std::size_t memory_wasted = 0; stackAllocator.Reset(); print_benchmark_stats(elapsed_time, memory_used, memory_wasted, MAX_OPERATIONS); std::cout << "BENCHMARK STACK A: END" << std::endl; } void benchmark_stack_allocate_free(long MAX_OPERATIONS = 1e4){ timespec start, end; std::cout << "BENCHMARK STACK A/F: START" << std::endl; setTimer(start); StackAllocator stackAllocator(1e10); int operations = 0; bool allocate = true; while(operations < MAX_OPERATIONS){ if (allocate) { stackAllocator.Allocate(sizeof(int), alignof(int)); // 4 -> 4 stackAllocator.Allocate(sizeof(bool), alignof(bool)); // 1 -> 5 // 3 -> 8 stackAllocator.Allocate(sizeof(foo), alignof(foo)); // 16 -> 24 allocate = false; }else { stackAllocator.Free(nullptr, sizeof(foo)); stackAllocator.Free(nullptr, sizeof(bool)); stackAllocator.Free(nullptr, sizeof(int)); allocate = true; } ++operations; } setTimer(end); const timespec elapsed_time = diff(start, end); const std::size_t memory_used = 0; const std::size_t memory_wasted = 0; stackAllocator.Reset(); print_benchmark_stats(elapsed_time, memory_used, memory_wasted, MAX_OPERATIONS); std::cout << "BENCHMARK STACK A/F: END" << std::endl; } void benchmark_malloc_allocate(long MAX_OPERATIONS = 1e4){ timespec start, end; std::cout << "BENCHMARK MALLOC A: START" << std::endl; setTimer(start); int operations = 0; srand (1); while(operations < MAX_OPERATIONS){ malloc(sizeof(int)); malloc(sizeof(bool)); malloc(sizeof(foo)); ++operations; } setTimer(end); const timespec elapsed_time = diff(start, end); const std::size_t memory_used = 0; const std::size_t memory_wasted = 0; print_benchmark_stats(elapsed_time, memory_used, memory_wasted, MAX_OPERATIONS); std::cout << "BENCHMARK MALLOC A: END" << std::endl; } void benchmark_malloc_allocate_free(long MAX_OPERATIONS = 1e4){ timespec start, end; std::cout << "BENCHMARK MALLOC A/F: START" << std::endl; setTimer(start); int operations = 0; bool allocate = true; int * i; bool * b; foo * f; while(operations < MAX_OPERATIONS){ if (allocate){ i = (int*) malloc(sizeof(int)); b = (bool*) malloc(sizeof(bool)); f = (foo*) malloc(sizeof(foo)); allocate = false; }else { free(f); free(b); free(i); allocate = true; } ++operations; } setTimer(end); const timespec elapsed_time = diff(start, end); const std::size_t memory_used = 0; const std::size_t memory_wasted = 0; print_benchmark_stats(elapsed_time, memory_used, memory_wasted, MAX_OPERATIONS); std::cout << "BENCHMARK MALLOC A/F: END" << std::endl; } /* TODO 1- Deinterface 2- Stack/Linear ->Calculate padding (Aligned allocators interface?) 2- benchmark free (3pointers) 3- read values (check speed) 4- move to utils file? */ int main(){ benchmark_stack_allocate_free(1e8); benchmark_malloc_allocate_free(1e8); return 1; } <|endoftext|>
<commit_before>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* main.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: kchetty <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2016/11/28 08:34:50 by kchetty #+# #+# */ /* Updated: 2016/12/09 10:01:59 by kchetty ### ########.fr */ /* */ /* ************************************************************************** */ #include "gomoku.h" void draw_screen(int dim, t_global *g) { int x,y; int win_y, win_x; int tmp = 9; getmaxyx(stdscr, win_y, win_x); mvwprintw(g->the_board, 2, 2, "teh x: %d AND WIN_Y: %d\n ", win_x ,win_y); for(y = 0; y < dim; y++) { for(x = 0; x < dim; x++) { if (x == 0) mvwprintw(g->the_board, tmp, ((win_x / 2) - (77 / 2)), " ---"); else wprintw(g->the_board, " ---"); } wprintw(g->the_board, "\n"); tmp++; for(x = 0; x < dim; x++) { if (x == 0) mvwprintw(g->the_board, tmp, ((win_x / 2) - (77 / 2)), "| "); else wprintw(g->the_board, "| "); } tmp++; if(x == dim) wprintw(g->the_board, "|\n"); else wprintw(g->the_board, "\n"); } for(x = 0; x < dim; x++) { if (x == 0) mvwprintw(g->the_board, tmp , ((win_x / 2) - (77 / 2)), " ---"); else wprintw(g->the_board, " ---"); } wprintw(g->the_board, "\n"); wrefresh(g->the_board); } void redraw_stuff(t_global *g) { int y = 0, x = 0; int win_y, win_x; getmaxyx(g->the_board, win_y, win_x); start_color(); win_y -= win_y; wmove(g->the_board, y*2+10, x*4 + ((win_x / 2) - (77 / 2)) + 2); for (y = 0; y < 19; y++) { for (x = 0; x < 19; x++) { if (g->board->get(x, y) == 0) { init_color(COLOR_RED, 700,0, 700); init_pair(1, COLOR_RED, COLOR_BLACK); wattron(g->the_board, COLOR_PAIR(1)); mvwprintw(g->the_board, y*2+10,x*4+ ((win_x / 2) - (77 / 2)) + 2, "X"); wattroff(g->the_board, COLOR_PAIR(1)); } else if (g->board->get(x, y) == 1) { init_color(COLOR_CYAN, 700, 100, 0); init_pair(6, COLOR_CYAN, COLOR_BLACK); wattron(g->the_board, COLOR_PAIR(6)); mvwprintw(g->the_board, y*2+10, x*4+ ((win_x / 2) - (77 / 2)) + 2, "O"); wattroff(g->the_board ,COLOR_PAIR(6)); } } } wrefresh(g->the_board); } int keyhook(int dim, int player, t_global *g) { int win_y, win_x; getmaxyx(g->the_board, win_y, win_x); win_y -= win_y; mvwprintw(g->the_board, dim * 2 + 17, ((win_x - 24) / 2), "Make you move: Player %c ",player==0 ? 'X' : 'O'); wmove(g->the_board, g->y*2+10, g->x*4 + ((win_x / 2) - (77 / 2)) + 2); wrefresh(g->the_board); noecho(); switch(wgetch(g->the_board)) { case KEY_UP: if(g->y > 0) g->y--; return(-2); case KEY_LEFT: if(g->x > 0) g->x--; return(-2); case KEY_RIGHT: if(g->x < dim-1) g->x++; return(-2); case KEY_DOWN: if(g->y < dim-1) g->y++; return(-2); case '\n': echo(); wrefresh(g->the_board); start_color(); if (player == 0) { if (g->board->set_x(g->x, g->y)) { //init_color(COLOR_RED, 700,0, 100); init_pair(1, COLOR_RED, COLOR_BLACK); wattron(g->the_board, COLOR_PAIR(1)); mvwprintw(g->the_board, g->y*2+10,g->x*4+ ((win_x / 2) - (77 / 2)) + 2, "X"); wattroff(g->the_board, COLOR_PAIR(1)); return (1); } else return (-3); } else { if (g->board->set_o(g->x, g->y)) { //init_color(COLOR_CYAN, 700, 100, 0); init_pair(6, COLOR_CYAN, COLOR_BLACK); wattron(g->the_board, COLOR_PAIR(6)); mvwprintw(g->the_board, g->y*2+10,g->x*4+ ((win_x / 2) - (77 / 2)) + 2, "O"); wattroff(g->the_board ,COLOR_PAIR(6)); return (1); } else return (-3); } break; case 'q': return(-1); default: return(-2); break; } wmove(g->the_board, g->y*2+10,g->x*4+((win_x - 80) / 2) + 2); wrefresh(g->the_board); return(0); } void draw_borders(WINDOW *screen) { int x, y, i; getmaxyx(screen, y, x); // 4 corners mvwprintw(screen, 0, 0, "+"); mvwprintw(screen, y - 1, 0, "+"); mvwprintw(screen, 0, x - 1, "+"); mvwprintw(screen, y - 1, x - 1, "+"); // sides for (i = 1; i < (y - 1); i++) { mvwprintw(screen, i, 0, "|"); mvwprintw(screen, i, x - 1, "|"); } // top and bottom for (i = 1; i < (x - 1); i++) { mvwprintw(screen, 0, i, "-"); mvwprintw(screen, y - 1, i, "-"); } wrefresh(screen); } void create_menu() { int max_x, max_y; getmaxyx(stdscr, max_y, max_x); WINDOW *menu = newwin(max_y, max_x, 0, 0); start_color(); draw_borders(menu); mvwprintw(menu, 2, ((max_x - 80) / 2) + 2, " GGGGGGGGGGGGG kkkkkkkk\n" " GGG::::::::::::G k::::::k\n" "GG:::::::::::::::G k::::::k\n" "G:::::GGGGGGGG::::G k::::::k\n" "G:::::G GGGGGG ooooooooooo mmmmmmm mmmmmmm ooooooooooo k:::::k kkkkkkkuuuuuu uuuuuu\n" "G:::::G oo:::::::::::oo mm:::::::m m:::::::mm oo:::::::::::oo k:::::k k:::::k u::::u u::::u\n" "G:::::G o:::::::::::::::om::::::::::mm::::::::::mo:::::::::::::::o k:::::k k:::::k u::::u u::::u\n" "G:::::G GGGGGGGGGGo:::::ooooo:::::om::::::::::::::::::::::mo:::::ooooo:::::o k:::::k k:::::k u::::u u::::u\n" "G:::::G G::::::::Go::::o o::::om:::::mmm::::::mmm:::::mo::::o o::::o k::::::k:::::k u::::u u::::u\n" "G:::::G GGGGG::::Go::::o o::::om::::m m::::m m::::mo::::o o::::o k:::::::::::k u::::u u::::u\n" "G:::::G G::::Go::::o o::::om::::m m::::m m::::mo::::o o::::o k:::::::::::k u::::u u::::u\n" " G:::::G G::::Go::::o o::::om::::m m::::m m::::mo::::o o::::o k::::::k:::::k u:::::uuuu:::::u\n" "G:::::GGGGGGGG::::Go:::::ooooo:::::om::::m m::::m m::::mo:::::ooooo:::::ok::::::k k:::::k u:::::::::::::::uu\n" "GG:::::::::::::::Go:::::::::::::::om::::m m::::m m::::mo:::::::::::::::ok::::::k k:::::k u:::::::::::::::u\n" "GGG::::::GGG:::G oo:::::::::::oo m::::m m::::m m::::m oo:::::::::::oo k::::::k k:::::k uu::::::::uu:::u\n" "GGGGGG GGGG ooooooooooo mmmmmm mmmmmm mmmmmm ooooooooooo kkkkkkkk kkkkkkk uuuuuuuu uuuu\n"); while (1) wrefresh(menu); } void init(t_global *g) { g->x = 0; g->y = 0; g->board = new board_class(); initscr(); noecho(); cbreak(); } int main() { t_global g; int dim,rtn,player = 0; int parent_x = 0, parent_y = 0, new_x, new_y; init(&g); //create_menu(); //get our maximun window dimensions getmaxyx(stdscr, parent_y, parent_x); g.header = newwin(((parent_y / 4)), parent_x, 0, 0); g.the_board = newwin(parent_y - (parent_y / 4) + 1, parent_x, (parent_y / 4) - 1, 0); wclear(g.the_board); draw_borders(g.header); draw_borders(g.the_board); keypad(g.the_board,TRUE); dim = 19; draw_screen(dim, &g); while (1) { getmaxyx(stdscr, new_y, new_x); if (new_y != parent_y || new_x != parent_x) { parent_x = new_x; parent_y = new_y; wresize(g.header, ((new_y / 4)), new_x); mvwin(g.header, 0, 0); wresize(g.the_board, new_y - (new_y / 4) + 1, new_x); mvwin(g.the_board, (new_y / 4) - 1, 0); wclear(stdscr); wclear(g.the_board); wclear(g.header); //draw_borders(g.the_board); draw_borders(g.header); draw_screen(dim, &g); redraw_stuff(&g); } if((rtn=keyhook(dim,player, &g))==-1) break; if(rtn == 1) { if (g.board->check_win(player)) break ; player=!player; } if (rtn == -3) { move(dim * 2 + 4, 0); printw("Invalid Move"); } } delwin(g.the_board); delwin(g.header); endwin(); printf("HAHAHAHAHA SOMEONE WON"); return (0); } <commit_msg>resizing works<commit_after>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* main.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: kchetty <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2016/11/28 08:34:50 by kchetty #+# #+# */ /* Updated: 2016/12/09 10:37:08 by kchetty ### ########.fr */ /* */ /* ************************************************************************** */ #include "gomoku.h" void draw_screen(int dim, t_global *g) { int x,y; int win_y, win_x; int tmp; getmaxyx(g->the_board, win_y, win_x); tmp = ((win_y / 2) - (38 / 2)); mvwprintw(g->the_board, 2, 2, "teh x: %d AND WIN_Y: %d\n ", win_x ,win_y); for(y = 0; y < dim; y++) { for(x = 0; x < dim; x++) { if (x == 0) mvwprintw(g->the_board, tmp, ((win_x / 2) - (77 / 2)), " ---"); else wprintw(g->the_board, " ---"); } wprintw(g->the_board, "\n"); tmp++; for(x = 0; x < dim; x++) { if (x == 0) mvwprintw(g->the_board, tmp, ((win_x / 2) - (77 / 2)), "| "); else wprintw(g->the_board, "| "); } tmp++; if(x == dim) wprintw(g->the_board, "|\n"); else wprintw(g->the_board, "\n"); } for(x = 0; x < dim; x++) { if (x == 0) mvwprintw(g->the_board, tmp , ((win_x / 2) - (77 / 2)), " ---"); else wprintw(g->the_board, " ---"); } wprintw(g->the_board, "\n"); wrefresh(g->the_board); } void redraw_stuff(t_global *g) { int y = 0, x = 0; int win_y, win_x; getmaxyx(g->the_board, win_y, win_x); start_color(); win_y -= win_y; wmove(g->the_board, y*2+((win_y / 2) - (38 / 2)) + 1, x*4 + ((win_x / 2) - (77 / 2)) + 2); for (y = 0; y < 19; y++) { for (x = 0; x < 19; x++) { if (g->board->get(x, y) == 0) { init_color(COLOR_RED, 700,0, 700); init_pair(1, COLOR_RED, COLOR_BLACK); wattron(g->the_board, COLOR_PAIR(1)); mvwprintw(g->the_board, y * 2 + ((win_y / 2) - (38 / 2)) + 1, x * 4 + ((win_x / 2) - (77 / 2)) + 2, "X"); wattroff(g->the_board, COLOR_PAIR(1)); } else if (g->board->get(x, y) == 1) { init_color(COLOR_CYAN, 700, 100, 0); init_pair(6, COLOR_CYAN, COLOR_BLACK); wattron(g->the_board, COLOR_PAIR(6)); mvwprintw(g->the_board, y*2+ ((win_y / 2) - (38 / 2)) + 1, x*4+ ((win_x / 2) - (77 / 2)) + 2, "O"); wattroff(g->the_board ,COLOR_PAIR(6)); } } } wrefresh(g->the_board); } int keyhook(int dim, int player, t_global *g) { int win_y, win_x; getmaxyx(g->the_board, win_y, win_x); //win_y -= win_y; mvwprintw(g->the_board, win_y, ((win_x / 2) - (23 / 2)), "Make you move: Player %c ",player==0 ? 'X' : 'O'); wmove(g->the_board, g->y*2+((win_y / 2) - (38 / 2)) + 1, g->x*4 + ((win_x / 2) - (77 / 2)) + 2); wrefresh(g->the_board); noecho(); switch(wgetch(g->the_board)) { case KEY_UP: if(g->y > 0) g->y--; return(-2); case KEY_LEFT: if(g->x > 0) g->x--; return(-2); case KEY_RIGHT: if(g->x < dim-1) g->x++; return(-2); case KEY_DOWN: if(g->y < dim-1) g->y++; return(-2); case '\n': echo(); wrefresh(g->the_board); start_color(); if (player == 0) { if (g->board->set_x(g->x, g->y)) { //init_color(COLOR_RED, 700,0, 100); init_pair(1, COLOR_RED, COLOR_BLACK); wattron(g->the_board, COLOR_PAIR(1)); mvwprintw(g->the_board, g->y*2+((win_y / 2) - (38 / 2)) + 1,g->x*4+ ((win_x / 2) - (77 / 2)) + 2, "X"); wattroff(g->the_board, COLOR_PAIR(1)); return (1); } else return (-3); } else { if (g->board->set_o(g->x, g->y)) { //init_color(COLOR_CYAN, 700, 100, 0); init_pair(6, COLOR_CYAN, COLOR_BLACK); wattron(g->the_board, COLOR_PAIR(6)); mvwprintw(g->the_board, g->y*2+((win_y / 2) - (38 / 2)) + 1,g->x*4+ ((win_x / 2) - (77 / 2)) + 2, "O"); wattroff(g->the_board ,COLOR_PAIR(6)); return (1); } else return (-3); } break; case 'q': return(-1); default: return(-2); break; } wmove(g->the_board, g->y*2+((win_y / 2) - (38 / 2)) + 1, g->x*4+((win_x - 80) / 2) + 2); wrefresh(g->the_board); return(0); } void draw_borders(WINDOW *screen) { int x, y, i; getmaxyx(screen, y, x); // 4 corners mvwprintw(screen, 0, 0, "+"); mvwprintw(screen, y - 1, 0, "+"); mvwprintw(screen, 0, x - 1, "+"); mvwprintw(screen, y - 1, x - 1, "+"); // sides for (i = 1; i < (y - 1); i++) { mvwprintw(screen, i, 0, "|"); mvwprintw(screen, i, x - 1, "|"); } // top and bottom for (i = 1; i < (x - 1); i++) { mvwprintw(screen, 0, i, "-"); mvwprintw(screen, y - 1, i, "-"); } wrefresh(screen); } void create_menu() { int max_x, max_y; getmaxyx(stdscr, max_y, max_x); WINDOW *menu = newwin(max_y, max_x, 0, 0); start_color(); draw_borders(menu); mvwprintw(menu, 2, ((max_x - 80) / 2) + 2, " GGGGGGGGGGGGG kkkkkkkk\n" " GGG::::::::::::G k::::::k\n" "GG:::::::::::::::G k::::::k\n" "G:::::GGGGGGGG::::G k::::::k\n" "G:::::G GGGGGG ooooooooooo mmmmmmm mmmmmmm ooooooooooo k:::::k kkkkkkkuuuuuu uuuuuu\n" "G:::::G oo:::::::::::oo mm:::::::m m:::::::mm oo:::::::::::oo k:::::k k:::::k u::::u u::::u\n" "G:::::G o:::::::::::::::om::::::::::mm::::::::::mo:::::::::::::::o k:::::k k:::::k u::::u u::::u\n" "G:::::G GGGGGGGGGGo:::::ooooo:::::om::::::::::::::::::::::mo:::::ooooo:::::o k:::::k k:::::k u::::u u::::u\n" "G:::::G G::::::::Go::::o o::::om:::::mmm::::::mmm:::::mo::::o o::::o k::::::k:::::k u::::u u::::u\n" "G:::::G GGGGG::::Go::::o o::::om::::m m::::m m::::mo::::o o::::o k:::::::::::k u::::u u::::u\n" "G:::::G G::::Go::::o o::::om::::m m::::m m::::mo::::o o::::o k:::::::::::k u::::u u::::u\n" " G:::::G G::::Go::::o o::::om::::m m::::m m::::mo::::o o::::o k::::::k:::::k u:::::uuuu:::::u\n" "G:::::GGGGGGGG::::Go:::::ooooo:::::om::::m m::::m m::::mo:::::ooooo:::::ok::::::k k:::::k u:::::::::::::::uu\n" "GG:::::::::::::::Go:::::::::::::::om::::m m::::m m::::mo:::::::::::::::ok::::::k k:::::k u:::::::::::::::u\n" "GGG::::::GGG:::G oo:::::::::::oo m::::m m::::m m::::m oo:::::::::::oo k::::::k k:::::k uu::::::::uu:::u\n" "GGGGGG GGGG ooooooooooo mmmmmm mmmmmm mmmmmm ooooooooooo kkkkkkkk kkkkkkk uuuuuuuu uuuu\n"); while (1) wrefresh(menu); } void init(t_global *g) { g->x = 0; g->y = 0; g->board = new board_class(); initscr(); noecho(); cbreak(); } int main() { t_global g; int dim,rtn,player = 0; int parent_x = 0, parent_y = 0, new_x, new_y; init(&g); //create_menu(); //get our maximun window dimensions getmaxyx(stdscr, parent_y, parent_x); g.header = newwin(((parent_y / 4)), parent_x, 0, 0); g.the_board = newwin(parent_y - (parent_y / 4) + 1, parent_x, (parent_y / 4) - 1, 0); wclear(g.the_board); draw_borders(g.header); draw_borders(g.the_board); keypad(g.the_board,TRUE); dim = 19; draw_screen(dim, &g); while (1) { getmaxyx(stdscr, new_y, new_x); if (new_y != parent_y || new_x != parent_x) { parent_x = new_x; parent_y = new_y; wresize(g.header, ((new_y / 4)), new_x); mvwin(g.header, 0, 0); wresize(g.the_board, new_y - (new_y / 4) + 1, new_x); mvwin(g.the_board, (new_y / 4) - 1, 0); wclear(stdscr); wclear(g.the_board); wclear(g.header); draw_borders(g.the_board); draw_borders(g.header); draw_screen(dim, &g); redraw_stuff(&g); } if((rtn=keyhook(dim,player, &g))==-1) break; if(rtn == 1) { if (g.board->check_win(player)) break ; player=!player; } if (rtn == -3) { move(dim * 2 + 4, 0); printw("Invalid Move"); } } delwin(g.the_board); delwin(g.header); endwin(); printf("HAHAHAHAHA SOMEONE WON"); return (0); } <|endoftext|>
<commit_before>/** * @file Cosa/Driver/NEXA.cpp * @version 1.0 * * @section License * Copyright (C) 2013, Mikael Patel * * 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 * * This file is part of the Arduino Che Cosa project. */ #include "Cosa/Driver/NEXA.hh" #include "Cosa/RTC.hh" #include "Cosa/Watchdog.hh" IOStream& operator<<(IOStream& outs, NEXA::code_t code) { outs << PSTR("house = ") << code.house << PSTR(", group = ") << code.group << PSTR(", device = ") << code.device << PSTR(", on/off = ") << code.onoff; return (outs); } void NEXA::Receiver::on_interrupt(uint16_t arg) { // Check start condition if (m_start == 0L) { if (is_clear()) return; m_start = RTC::micros(); m_ix = 0; return; } // Calculate the pulse width (both low and high) and check against threshold uint32_t stop = RTC::micros(); uint32_t us = (stop - m_start); m_start = stop; if (us < LOW_THRESHOLD || us > HIGH_THRESHOLD) goto exception; m_sample[m_ix & IX_MASK] = us; m_ix += 1; // Decode every four pulses to a bit if ((m_ix & IX_MASK) == 0) { int8_t bit = decode_bit(); if (bit < 0) goto exception; m_code = (m_code << 1) | bit; } if (m_ix != IX_MAX) return; // And when all samples have been read push an event Event::push(Event::RECEIVE_COMPLETED_TYPE, this); exception: m_start = 0L; } int8_t NEXA::Receiver::decode_bit() { uint8_t bit; // The pedantic version checks even the first pulse. This could be removed bit = ((m_sample[0] < BIT_THRESHOLD) << 1) | (m_sample[1] < BIT_THRESHOLD); if (bit < 2) return (-1); // The second pulse has the actual transmitted bit bit = ((m_sample[2] < BIT_THRESHOLD) << 1) | (m_sample[3] < BIT_THRESHOLD); if (bit < 2) return (-1); // And map back to a bit (2 => 0, 3 => 1) return (bit > 2); } void NEXA::Receiver::attach(Listener& device) { device.m_next = m_first; m_first = &device; } void NEXA::Receiver::detach(Listener& device) { if (m_first != 0) { if (m_first == &device) { m_first = device.m_next; } else { Listener* d; for (d = m_first; (d->m_next != 0) && (d->m_next != &device); d = d->m_next); if (d->m_next == 0) return; d->m_next = device.m_next; } } device.m_next = 0; } void NEXA::Receiver::dispatch() { code_t cmd = m_code; for (Listener* device = m_first; device != 0; device = device->m_next) if (cmd == device->m_unit) { device->on_change(cmd.onoff); if (!cmd.group) return; } } void NEXA::Receiver::recv(code_t& cmd) { uint32_t start, stop; int32_t bits = 0L; uint16_t us; uint16_t ix; do { // Wait for the start condition while (is_low()); stop = RTC::micros(); // Collect the samples; high followed by low pulse ix = 0; while (ix < IX_MAX) { // Capture length of high period start = stop; while (is_high()); stop = RTC::micros(); us = stop - start; if (us < LOW_THRESHOLD || us > HIGH_THRESHOLD) break; m_sample[ix & IX_MASK] = us; ix += 1; // Capture length of low period start = stop; while (is_low()); stop = RTC::micros(); us = stop - start; if (us < LOW_THRESHOLD || us > HIGH_THRESHOLD) break; m_sample[ix & IX_MASK] = us; ix += 1; // Decode every four samples to a code bit if ((ix & IX_MASK) == 0) { int8_t bit = decode_bit(); if (bit < 0) break; bits = (bits << 1) | bit; } } } while (ix != IX_MAX); m_code = bits; cmd = bits; } void NEXA::Transmitter::send_code(code_t cmd, int8_t onoff, uint8_t mode) { // Send the code four times with a pause between each for (uint8_t i = 0; i < SEND_CODE_MAX; i++) { const uint8_t BITS_MAX = 32; const uint8_t ONOFF_POS = 27; int32_t bits = cmd.as_long; // Send start pulse with extended delay, code bits and stop pulse send_pulse(0); DELAY(START); for (uint8_t j = 0; j < BITS_MAX; j++) { // Check for dim level (-1..-15) if ((j == ONOFF_POS) && (onoff < 0)) { send_pulse(0); send_pulse(0); } else send_bit(bits < 0); bits <<= 1; } // Check for dim level transmission; level encoded as -1..-15 if (onoff < 0) { int8_t level = (-onoff) << 4; for (uint8_t j = 0; j < 4; j++) { send_bit(level < 0); level <<= 1; } } send_pulse(0); // Wait for the transmission of the code uint32_t start = RTC::millis(); while ((RTC::millis() - start) < PAUSE) Power::sleep(mode); } } <commit_msg>Fixed missing null assignment after detach().<commit_after>/** * @file Cosa/Driver/NEXA.cpp * @version 1.0 * * @section License * Copyright (C) 2013, Mikael Patel * * 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 * * This file is part of the Arduino Che Cosa project. */ #include "Cosa/Driver/NEXA.hh" #include "Cosa/RTC.hh" #include "Cosa/Watchdog.hh" IOStream& operator<<(IOStream& outs, NEXA::code_t code) { outs << PSTR("house = ") << code.house << PSTR(", group = ") << code.group << PSTR(", device = ") << code.device << PSTR(", on/off = ") << code.onoff; return (outs); } void NEXA::Receiver::on_interrupt(uint16_t arg) { // Check start condition if (m_start == 0L) { if (is_clear()) return; m_start = RTC::micros(); m_ix = 0; return; } // Calculate the pulse width (both low and high) and check against threshold uint32_t stop = RTC::micros(); uint32_t us = (stop - m_start); m_start = stop; if (us < LOW_THRESHOLD || us > HIGH_THRESHOLD) goto exception; m_sample[m_ix & IX_MASK] = us; m_ix += 1; // Decode every four pulses to a bit if ((m_ix & IX_MASK) == 0) { int8_t bit = decode_bit(); if (bit < 0) goto exception; m_code = (m_code << 1) | bit; } if (m_ix != IX_MAX) return; // And when all samples have been read push an event Event::push(Event::RECEIVE_COMPLETED_TYPE, this); exception: m_start = 0L; } int8_t NEXA::Receiver::decode_bit() { uint8_t bit; // The pedantic version checks even the first pulse. This could be removed bit = ((m_sample[0] < BIT_THRESHOLD) << 1) | (m_sample[1] < BIT_THRESHOLD); if (bit < 2) return (-1); // The second pulse has the actual transmitted bit bit = ((m_sample[2] < BIT_THRESHOLD) << 1) | (m_sample[3] < BIT_THRESHOLD); if (bit < 2) return (-1); // And map back to a bit (2 => 0, 3 => 1) return (bit > 2); } void NEXA::Receiver::attach(Listener& device) { device.m_next = m_first; m_first = &device; } void NEXA::Receiver::detach(Listener& device) { if (m_first != 0) { if (m_first == &device) { m_first = device.m_next; } else { Listener* d; for (d = m_first; (d->m_next != 0) && (d->m_next != &device); d = d->m_next); if (d->m_next != 0) d->m_next = device.m_next; } } device.m_next = 0; } void NEXA::Receiver::dispatch() { code_t cmd = m_code; for (Listener* device = m_first; device != 0; device = device->m_next) if (cmd == device->m_unit) { device->on_change(cmd.onoff); if (!cmd.group) return; } } void NEXA::Receiver::recv(code_t& cmd) { uint32_t start, stop; int32_t bits = 0L; uint16_t us; uint16_t ix; do { // Wait for the start condition while (is_low()); stop = RTC::micros(); // Collect the samples; high followed by low pulse ix = 0; while (ix < IX_MAX) { // Capture length of high period start = stop; while (is_high()); stop = RTC::micros(); us = stop - start; if (us < LOW_THRESHOLD || us > HIGH_THRESHOLD) break; m_sample[ix & IX_MASK] = us; ix += 1; // Capture length of low period start = stop; while (is_low()); stop = RTC::micros(); us = stop - start; if (us < LOW_THRESHOLD || us > HIGH_THRESHOLD) break; m_sample[ix & IX_MASK] = us; ix += 1; // Decode every four samples to a code bit if ((ix & IX_MASK) == 0) { int8_t bit = decode_bit(); if (bit < 0) break; bits = (bits << 1) | bit; } } } while (ix != IX_MAX); m_code = bits; cmd = bits; } void NEXA::Transmitter::send_code(code_t cmd, int8_t onoff, uint8_t mode) { // Send the code four times with a pause between each for (uint8_t i = 0; i < SEND_CODE_MAX; i++) { const uint8_t BITS_MAX = 32; const uint8_t ONOFF_POS = 27; int32_t bits = cmd.as_long; // Send start pulse with extended delay, code bits and stop pulse send_pulse(0); DELAY(START); for (uint8_t j = 0; j < BITS_MAX; j++) { // Check for dim level (-1..-15) if ((j == ONOFF_POS) && (onoff < 0)) { send_pulse(0); send_pulse(0); } else send_bit(bits < 0); bits <<= 1; } // Check for dim level transmission; level encoded as -1..-15 if (onoff < 0) { int8_t level = (-onoff) << 4; for (uint8_t j = 0; j < 4; j++) { send_bit(level < 0); level <<= 1; } } send_pulse(0); // Wait for the transmission of the code uint32_t start = RTC::millis(); while ((RTC::millis() - start) < PAUSE) Power::sleep(mode); } } <|endoftext|>
<commit_before>/* * (c) Copyright Ascensio System SIA 2010-2019 * * This program is a free software product. You can redistribute it and/or * modify it under the terms of the GNU Affero General Public License (AGPL) * version 3 as published by the Free Software Foundation. In accordance with * Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect * that Ascensio System SIA expressly excludes the warranty of non-infringement * of any third-party rights. * * This program is distributed WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For * details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html * * You can contact Ascensio System SIA at 20A-12 Ernesta Birznieka-Upisha * street, Riga, Latvia, EU, LV-1050. * * The interactive user interfaces in modified source and object code versions * of the Program must display Appropriate Legal Notices, as required under * Section 5 of the GNU AGPL version 3. * * Pursuant to Section 7(b) of the License you must retain the original Product * logo when distributing the program. Pursuant to Section 7(e) we decline to * grant you any rights under trademark law for use of our trademarks. * * All the Product's GUI elements, including illustrations and icon sets, as * well as technical writing content are licensed under the terms of the * Creative Commons Attribution-ShareAlike 4.0 International. See the License * terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode * */ #include "ApplicationFontsWorker.h" #include "application_generate_fonts.h" #define ONLYOFFICE_FONTS_VERSION_ 5 CApplicationFontsWorker::CApplicationFontsWorker() { m_bIsUseSystemFonts = true; m_bIsNeedThumbnails = true; m_bIsUseOpenType = true; m_bIsUseAllVersions = false; } CApplicationFontsWorker::~CApplicationFontsWorker() { } NSFonts::IApplicationFonts* CApplicationFontsWorker::Check() { if (m_sDirectory.empty()) return NULL; std::wstring strAllFontsJSPath = m_sDirectory + L"/AllFonts.js"; std::wstring strFontsSelectionBin = m_sDirectory + L"/font_selection.bin"; std::vector<std::string> strFonts; std::wstring strFontsCheckPath = m_sDirectory + L"/fonts.log"; if (true) { NSFile::CFileBinary oFile; if (oFile.OpenFile(strFontsCheckPath)) { int nSize = oFile.GetFileSize(); char* pBuffer = new char[nSize]; DWORD dwReaden = 0; oFile.ReadFile((BYTE*)pBuffer, nSize, dwReaden); oFile.CloseFile(); int nStart = 0; int nCur = nStart; for (; nCur < nSize; ++nCur) { if (pBuffer[nCur] == '\n') { int nEnd = nCur - 1; if (nEnd > nStart) { std::string s(pBuffer + nStart, nEnd - nStart + 1); strFonts.push_back(s); } nStart = nCur + 1; } } delete[] pBuffer; } #ifdef ONLYOFFICE_FONTS_VERSION_ if (0 != strFonts.size()) { // check version!!! std::string sOO_Version = strFonts[0]; if (0 != sOO_Version.find("ONLYOFFICE_FONTS_VERSION_")) { strFonts.clear(); } else { std::string sVersion = sOO_Version.substr(25); int nVersion = std::stoi(sVersion); if (nVersion != ONLYOFFICE_FONTS_VERSION_) strFonts.clear(); else strFonts.erase(strFonts.begin()); } } #endif } NSFonts::IApplicationFonts* pApplicationF = NSFonts::NSApplication::Create(); std::vector<std::wstring> strFontsW_Cur; if (m_bIsUseSystemFonts) strFontsW_Cur = pApplicationF->GetSetupFontFiles(); for (std::vector<std::wstring>::iterator i = m_arAdditionalFolders.begin(); i != m_arAdditionalFolders.end(); i++) { NSDirectory::GetFiles2(*i, strFontsW_Cur, true); } std::sort(strFontsW_Cur.begin(), strFontsW_Cur.end()); bool bIsEqual = true; if (strFonts.size() != strFontsW_Cur.size()) bIsEqual = false; if (bIsEqual) { int nCount = (int)strFonts.size(); for (int i = 0; i < nCount; ++i) { if (strFonts[i] != NSFile::CUtf8Converter::GetUtf8StringFromUnicode2(strFontsW_Cur[i].c_str(), strFontsW_Cur[i].length())) { bIsEqual = false; break; } } } if (bIsEqual) { if (!NSFile::CFileBinary::Exists(strFontsSelectionBin)) bIsEqual = false; } if (!bIsEqual) { if (NSFile::CFileBinary::Exists(strFontsCheckPath)) NSFile::CFileBinary::Remove(strFontsCheckPath); if (NSFile::CFileBinary::Exists(strAllFontsJSPath)) NSFile::CFileBinary::Remove(strAllFontsJSPath); if (NSFile::CFileBinary::Exists(strFontsSelectionBin)) NSFile::CFileBinary::Remove(strFontsSelectionBin); if (NSFile::CFileBinary::Exists(m_sDirectory + L"/fonts_thumbnail.png")) NSFile::CFileBinary::Remove(m_sDirectory + L"/fonts_thumbnail.png"); if (NSFile::CFileBinary::Exists(m_sDirectory + L"/[email protected]")) NSFile::CFileBinary::Remove(m_sDirectory + L"/[email protected]"); int nFlag = 3; if (!m_bIsUseOpenType) nFlag = 2; pApplicationF->InitializeFromArrayFiles(strFontsW_Cur, nFlag); NSCommon::SaveAllFontsJS(pApplicationF, strAllFontsJSPath, m_bIsNeedThumbnails ? m_sDirectory : L"", strFontsSelectionBin); if (m_bIsUseAllVersions) { NSCommon::SaveAllFontsJS(pApplicationF, strAllFontsJSPath + L".1", L"", L"", 0); } } NSFile::CFileBinary oFile; oFile.CreateFileW(strFontsCheckPath); #ifdef ONLYOFFICE_FONTS_VERSION_ oFile.WriteStringUTF8(L"ONLYOFFICE_FONTS_VERSION_"); oFile.WriteStringUTF8(std::to_wstring(ONLYOFFICE_FONTS_VERSION_)); oFile.WriteFile((BYTE*)"\n", 1); #endif int nCount = (int)strFontsW_Cur.size(); for (int i = 0; i < nCount; ++i) { oFile.WriteStringUTF8(strFontsW_Cur[i]); oFile.WriteFile((BYTE*)"\n", 1); } oFile.CloseFile(); pApplicationF->Release(); pApplicationF = NSFonts::NSApplication::Create(); pApplicationF->InitializeFromFolder(m_sDirectory); return pApplicationF; } std::string CApplicationFontsWorker::GetAllFonts() { std::string sAllFonts = ""; NSFile::CFileBinary::ReadAllTextUtf8A(m_sDirectory + L"/AllFonts.js", sAllFonts); return sAllFonts; } std::vector<std::wstring> CApplicationFontsWorker::GetFontNames(NSFonts::IApplicationFonts* pFonts) { std::vector<std::wstring> arNames; if (!pFonts || !pFonts->GetList()) return arNames; std::vector<NSFonts::CFontInfo*>* arInfos = pFonts->GetList()->GetFonts(); std::map<std::wstring, bool> map; for (std::vector<NSFonts::CFontInfo*>::iterator iter = arInfos->begin(); iter != arInfos->end(); iter++) { if (map.find((*iter)->m_wsFontName) == map.end()) arNames.push_back((*iter)->m_wsFontName); } std::sort(arNames.begin(), arNames.end()); return arNames; } std::vector<std::wstring> CApplicationFontsWorker::GetFontNamesWithExcludes(NSFonts::IApplicationFonts* pFonts, std::vector<std::wstring> excludes) { std::vector<std::wstring> arNames; if (!pFonts || !pFonts->GetList()) return arNames; std::vector<NSFonts::CFontInfo*>* arInfos = pFonts->GetList()->GetFonts(); std::map<std::wstring, bool> map; for (std::vector<NSFonts::CFontInfo*>::iterator iter = arInfos->begin(); iter != arInfos->end(); iter++) { std::wstring fontName = (*iter)->m_wsFontName; bool isExclude = false; for (size_t i = 0; i < excludes.size(); ++i) { if (fontName.find(excludes[i]) != std::string::npos) { isExclude = true; break; } } if (isExclude) { continue; } if (map.find(fontName) == map.end()) { arNames.push_back(fontName); map[fontName] = true; } } std::sort(arNames.begin(), arNames.end()); return arNames; } <commit_msg>Fix sysyem fonts checker<commit_after>/* * (c) Copyright Ascensio System SIA 2010-2019 * * This program is a free software product. You can redistribute it and/or * modify it under the terms of the GNU Affero General Public License (AGPL) * version 3 as published by the Free Software Foundation. In accordance with * Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect * that Ascensio System SIA expressly excludes the warranty of non-infringement * of any third-party rights. * * This program is distributed WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For * details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html * * You can contact Ascensio System SIA at 20A-12 Ernesta Birznieka-Upisha * street, Riga, Latvia, EU, LV-1050. * * The interactive user interfaces in modified source and object code versions * of the Program must display Appropriate Legal Notices, as required under * Section 5 of the GNU AGPL version 3. * * Pursuant to Section 7(b) of the License you must retain the original Product * logo when distributing the program. Pursuant to Section 7(e) we decline to * grant you any rights under trademark law for use of our trademarks. * * All the Product's GUI elements, including illustrations and icon sets, as * well as technical writing content are licensed under the terms of the * Creative Commons Attribution-ShareAlike 4.0 International. See the License * terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode * */ #include "ApplicationFontsWorker.h" #include "application_generate_fonts.h" #define ONLYOFFICE_FONTS_VERSION_ 5 CApplicationFontsWorker::CApplicationFontsWorker() { m_bIsUseSystemFonts = true; m_bIsNeedThumbnails = true; m_bIsUseOpenType = true; m_bIsUseAllVersions = false; } CApplicationFontsWorker::~CApplicationFontsWorker() { } NSFonts::IApplicationFonts* CApplicationFontsWorker::Check() { if (m_sDirectory.empty()) return NULL; std::wstring strAllFontsJSPath = m_sDirectory + L"/AllFonts.js"; std::wstring strFontsSelectionBin = m_sDirectory + L"/font_selection.bin"; std::vector<std::string> strFonts; std::wstring strFontsCheckPath = m_sDirectory + L"/fonts.log"; if (true) { NSFile::CFileBinary oFile; if (oFile.OpenFile(strFontsCheckPath)) { int nSize = oFile.GetFileSize(); char* pBuffer = new char[nSize]; DWORD dwReaden = 0; oFile.ReadFile((BYTE*)pBuffer, nSize, dwReaden); oFile.CloseFile(); int nStart = 0; int nCur = nStart; for (; nCur < nSize; ++nCur) { if (pBuffer[nCur] == '\n') { int nEnd = nCur - 1; if (nEnd > nStart) { std::string s(pBuffer + nStart, nEnd - nStart + 1); strFonts.push_back(s); } nStart = nCur + 1; } } delete[] pBuffer; } #ifdef ONLYOFFICE_FONTS_VERSION_ if (0 != strFonts.size()) { // check version!!! std::string sOO_Version = strFonts[0]; if (0 != sOO_Version.find("ONLYOFFICE_FONTS_VERSION_")) { strFonts.clear(); } else { std::string sVersion = sOO_Version.substr(25); int nVersion = std::stoi(sVersion); if (nVersion != ONLYOFFICE_FONTS_VERSION_) strFonts.clear(); else strFonts.erase(strFonts.begin()); } } #endif } NSFonts::IApplicationFonts* pApplicationF = NSFonts::NSApplication::Create(); std::vector<std::wstring> strFontsW_Cur; if (m_bIsUseSystemFonts) strFontsW_Cur = pApplicationF->GetSetupFontFiles(); for (std::vector<std::wstring>::iterator i = m_arAdditionalFolders.begin(); i != m_arAdditionalFolders.end(); i++) { NSDirectory::GetFiles2(*i, strFontsW_Cur, true); } std::sort(strFontsW_Cur.begin(), strFontsW_Cur.end()); bool bIsEqual = true; if (strFonts.size() != strFontsW_Cur.size()) bIsEqual = false; if (bIsEqual) { int nCount = (int)strFonts.size(); for (int i = 0; i < nCount; ++i) { if (strFonts[i] != NSFile::CUtf8Converter::GetUtf8StringFromUnicode2(strFontsW_Cur[i].c_str(), strFontsW_Cur[i].length())) { bIsEqual = false; break; } } } if (bIsEqual) { if (!NSFile::CFileBinary::Exists(strFontsSelectionBin)) bIsEqual = false; } if (!bIsEqual) { if (NSFile::CFileBinary::Exists(strFontsCheckPath)) NSFile::CFileBinary::Remove(strFontsCheckPath); if (NSFile::CFileBinary::Exists(strAllFontsJSPath)) NSFile::CFileBinary::Remove(strAllFontsJSPath); if (NSFile::CFileBinary::Exists(strFontsSelectionBin)) NSFile::CFileBinary::Remove(strFontsSelectionBin); if (NSFile::CFileBinary::Exists(m_sDirectory + L"/fonts_thumbnail.png")) NSFile::CFileBinary::Remove(m_sDirectory + L"/fonts_thumbnail.png"); if (NSFile::CFileBinary::Exists(m_sDirectory + L"/[email protected]")) NSFile::CFileBinary::Remove(m_sDirectory + L"/[email protected]"); int nFlag = 3; if (!m_bIsUseOpenType) nFlag = 2; NSStringUtils::CStringBuilder oFontsLog; #ifdef ONLYOFFICE_FONTS_VERSION_ oFontsLog.WriteString(L"ONLYOFFICE_FONTS_VERSION_"); oFontsLog.WriteString(std::to_wstring(ONLYOFFICE_FONTS_VERSION_)); oFontsLog.WriteString(L"\n"); #endif int nCount = (int)strFontsW_Cur.size(); for (int i = 0; i < nCount; ++i) { oFontsLog.WriteString(strFontsW_Cur[i]); oFontsLog.WriteString(L"\n"); } pApplicationF->InitializeFromArrayFiles(strFontsW_Cur, nFlag); NSCommon::SaveAllFontsJS(pApplicationF, strAllFontsJSPath, m_bIsNeedThumbnails ? m_sDirectory : L"", strFontsSelectionBin); if (m_bIsUseAllVersions) { NSCommon::SaveAllFontsJS(pApplicationF, strAllFontsJSPath + L".1", L"", L"", 0); } NSFile::CFileBinary::SaveToFile(strFontsCheckPath, oFontsLog.GetData()); } pApplicationF->Release(); pApplicationF = NSFonts::NSApplication::Create(); pApplicationF->InitializeFromFolder(m_sDirectory); return pApplicationF; } std::string CApplicationFontsWorker::GetAllFonts() { std::string sAllFonts = ""; NSFile::CFileBinary::ReadAllTextUtf8A(m_sDirectory + L"/AllFonts.js", sAllFonts); return sAllFonts; } std::vector<std::wstring> CApplicationFontsWorker::GetFontNames(NSFonts::IApplicationFonts* pFonts) { std::vector<std::wstring> arNames; if (!pFonts || !pFonts->GetList()) return arNames; std::vector<NSFonts::CFontInfo*>* arInfos = pFonts->GetList()->GetFonts(); std::map<std::wstring, bool> map; for (std::vector<NSFonts::CFontInfo*>::iterator iter = arInfos->begin(); iter != arInfos->end(); iter++) { if (map.find((*iter)->m_wsFontName) == map.end()) arNames.push_back((*iter)->m_wsFontName); } std::sort(arNames.begin(), arNames.end()); return arNames; } std::vector<std::wstring> CApplicationFontsWorker::GetFontNamesWithExcludes(NSFonts::IApplicationFonts* pFonts, std::vector<std::wstring> excludes) { std::vector<std::wstring> arNames; if (!pFonts || !pFonts->GetList()) return arNames; std::vector<NSFonts::CFontInfo*>* arInfos = pFonts->GetList()->GetFonts(); std::map<std::wstring, bool> map; for (std::vector<NSFonts::CFontInfo*>::iterator iter = arInfos->begin(); iter != arInfos->end(); iter++) { std::wstring fontName = (*iter)->m_wsFontName; bool isExclude = false; for (size_t i = 0; i < excludes.size(); ++i) { if (fontName.find(excludes[i]) != std::string::npos) { isExclude = true; break; } } if (isExclude) { continue; } if (map.find(fontName) == map.end()) { arNames.push_back(fontName); map[fontName] = true; } } std::sort(arNames.begin(), arNames.end()); return arNames; } <|endoftext|>
<commit_before>#include <iostream> #include <mutex> #include <queue> #include <thread> #include <tuple> #include <condition_variable> #include "input_file_reader.hpp" #include "minimize.hpp" #include "comparator.hpp" #include "result.hpp" // mutex for shared resources static std::mutex g_resource_mutex; // mutex for result vector static std::mutex g_result_mutex; // global queue with two pointers to the sequences // they are compared directly if the both sequence lengths are small enough static std::queue<std::tuple<uint32_t, OLC::Sequence*, uint32_t, OLC::Sequence*>> g_sequence_pairs; // global queue with two pointers to vectors of minimizers // we use this instead if the sequences are too long static std::queue<std::tuple<uint32_t, std::vector<OLC::Minimizer>*, uint32_t, std::vector<OLC::Minimizer>*>> g_minimizer_pairs; // global vector with results static std::vector<OLC::Result*> g_results; void worker() { while(true) { // Get the task and remove it from the pool uint32_t first_read_number; OLC::Sequence* first_sequence; std::vector<OLC::Minimizer>* first_minimizer; uint32_t second_read_number; OLC::Sequence* second_sequence; std::vector<OLC::Minimizer>* second_minimizer; { std::lock_guard<std::mutex> resource_lock(g_resource_mutex); if (g_sequence_pairs.empty()) return; std::tie(first_read_number, first_sequence, second_read_number, second_sequence) = g_sequence_pairs.front(); g_sequence_pairs.pop(); std::tie(first_read_number, first_minimizer, second_read_number, second_minimizer) = g_minimizer_pairs.front(); g_minimizer_pairs.pop(); } // Pull out the wrapped nucleotide vectors const std::vector<OLC::Nucleotide> nucleotides1 = first_sequence->getNucleotides()->getSequence(); const std::vector<OLC::Nucleotide> nucleotides2 = second_sequence->getNucleotides()->getSequence(); // If small enough, no need to use minimizers if (nucleotides1.size() < 20000 && nucleotides2.size() < 20000) { const OLC::Overlap overlap = compare(nucleotides1, nucleotides2); const uint32_t overlapFirstEnd = overlap.getEndFirst(); const uint32_t overlapSecondEnd = overlap.getEndSecond(); const uint32_t overlapFirstStart = overlap.getStartFirst(); const uint32_t overlapSecondStart = overlap.getStartSecond(); const uint32_t overlapLength = overlapFirstEnd - overlapFirstStart + 1; int32_t ahang = overlapFirstStart; int32_t bhang = nucleotides2.size() - overlapSecondEnd; if (overlapSecondStart > overlapFirstStart) ahang *= -1; if (nucleotides1.size() > overlapSecondEnd) bhang *= -1; OLC::Result* result = new OLC::Result(first_read_number, second_read_number, overlapLength, ahang, bhang); { std::lock_guard<std::mutex> result_lock(g_result_mutex); g_results.push_back(result); } } else { } } } int main(int argc, char** argv) { std::ios_base::sync_with_stdio(false); if (argc != 3) { std::cout << "Usage: " << argv[0] << " <minimum overlap length L> <FASTQ or FASTA file>\n"; return 1; } // file with the data const std::string file = std::string(argv[2]); // L is the minimum overlap length const uint32_t L = std::stoi(argv[1]); // window size const uint32_t w = (L + 1) / 2; // size of the k-mer const uint32_t k = (L + 1) / 2; // read phase OLC::InputFileReader reader(file); const std::vector<OLC::Sequence*> sequences = reader.readSequences(); std::vector<std::vector<OLC::Minimizer>> minimizers; for (size_t i = 0; i < sequences.size(); ++i) { const auto sequence = sequences[i]->getNucleotides()->getSequence(); // calculate minimizers - both interior and end minimizers minimizers.push_back(minimize(sequence, w, k)); } // generate tasks so we can do this in parallel if possible std::queue<std::tuple<uint32_t, uint32_t>> tasks; for (uint32_t i = 0; i < sequences.size(); ++i) { for (uint32_t j = i + 1; j < sequences.size(); ++j) { g_sequence_pairs.emplace(i, sequences[i], j, sequences[j]); g_minimizer_pairs.emplace(i, &minimizers[i], j, &minimizers[j]); } } // use concurrent minimizer matching std::vector<std::thread> threads(std::thread::hardware_concurrency()); for (uint8_t i = 0; i < threads.size(); ++i) threads[i] = std::thread(worker); for (uint8_t i = 0; i < threads.size(); ++i) threads[i].join(); // cleanup for (size_t i = 0; i < sequences.size(); ++i) delete sequences[i]; for (size_t i = 0; i < g_results.size(); ++i) delete g_results[i]; return 0; } <commit_msg>main: print out results and fix read identifiers<commit_after>#include <iostream> #include <mutex> #include <queue> #include <thread> #include <tuple> #include <condition_variable> #include "input_file_reader.hpp" #include "minimize.hpp" #include "comparator.hpp" #include "result.hpp" // mutex for shared resources static std::mutex g_resource_mutex; // mutex for result vector static std::mutex g_result_mutex; // global queue with two pointers to the sequences // they are compared directly if the both sequence lengths are small enough static std::queue<std::tuple<uint32_t, OLC::Sequence*, uint32_t, OLC::Sequence*>> g_sequence_pairs; // global queue with two pointers to vectors of minimizers // we use this instead if the sequences are too long static std::queue<std::tuple<uint32_t, std::vector<OLC::Minimizer>*, uint32_t, std::vector<OLC::Minimizer>*>> g_minimizer_pairs; // global vector with results static std::vector<OLC::Result*> g_results; void worker() { while(true) { // Get the task and remove it from the pool uint32_t first_read_number; OLC::Sequence* first_sequence; std::vector<OLC::Minimizer>* first_minimizer; uint32_t second_read_number; OLC::Sequence* second_sequence; std::vector<OLC::Minimizer>* second_minimizer; { std::lock_guard<std::mutex> resource_lock(g_resource_mutex); if (g_sequence_pairs.empty()) return; std::tie(first_read_number, first_sequence, second_read_number, second_sequence) = g_sequence_pairs.front(); g_sequence_pairs.pop(); std::tie(first_read_number, first_minimizer, second_read_number, second_minimizer) = g_minimizer_pairs.front(); g_minimizer_pairs.pop(); } // Pull out the wrapped nucleotide vectors const std::vector<OLC::Nucleotide> nucleotides1 = first_sequence->getNucleotides()->getSequence(); const std::vector<OLC::Nucleotide> nucleotides2 = second_sequence->getNucleotides()->getSequence(); // If small enough, no need to use minimizers if (nucleotides1.size() < 20000 && nucleotides2.size() < 20000) { const OLC::Overlap overlap = compare(nucleotides1, nucleotides2); const uint32_t overlapFirstEnd = overlap.getEndFirst(); const uint32_t overlapSecondEnd = overlap.getEndSecond(); const uint32_t overlapFirstStart = overlap.getStartFirst(); const uint32_t overlapSecondStart = overlap.getStartSecond(); const uint32_t overlapLength = overlapFirstEnd - overlapFirstStart + 1; int32_t ahang = overlapFirstStart; int32_t bhang = nucleotides2.size() - overlapSecondEnd; if (overlapSecondStart > overlapFirstStart) ahang *= -1; if (nucleotides1.size() > overlapSecondEnd) bhang *= -1; OLC::Result* result = new OLC::Result(first_read_number, second_read_number, overlapLength, ahang, bhang); { std::lock_guard<std::mutex> result_lock(g_result_mutex); g_results.push_back(result); } } else { } } } int main(int argc, char** argv) { std::ios_base::sync_with_stdio(false); if (argc != 3) { std::cout << "Usage: " << argv[0] << " <minimum overlap length L> <FASTQ or FASTA file>\n"; return 1; } // file with the data const std::string file = std::string(argv[2]); // L is the minimum overlap length const uint32_t L = std::stoi(argv[1]); // window size const uint32_t w = (L + 1) / 2; // size of the k-mer const uint32_t k = (L + 1) / 2; // read phase OLC::InputFileReader reader(file); const std::vector<OLC::Sequence*> sequences = reader.readSequences(); std::vector<std::vector<OLC::Minimizer>> minimizers; for (size_t i = 0; i < sequences.size(); ++i) { const auto sequence = sequences[i]->getNucleotides()->getSequence(); // calculate minimizers - both interior and end minimizers minimizers.push_back(minimize(sequence, w, k)); } // generate tasks so we can do this in parallel if possible std::queue<std::tuple<uint32_t, uint32_t>> tasks; for (uint32_t i = 0; i < sequences.size(); ++i) { for (uint32_t j = i + 1; j < sequences.size(); ++j) { g_sequence_pairs.emplace(i + 1, sequences[i], j + 1, sequences[j]); g_minimizer_pairs.emplace(i + 1, &minimizers[i], j + 1, &minimizers[j]); } } // use concurrent minimizer matching std::vector<std::thread> threads(std::thread::hardware_concurrency()); for (uint8_t i = 0; i < threads.size(); ++i) threads[i] = std::thread(worker); for (uint8_t i = 0; i < threads.size(); ++i) threads[i].join(); for (size_t i = 0; i < g_results.size(); ++i) { auto identifiers = g_results[i]->getIdentifiers(); std::cout << "Found overlap with length of " << g_results[i]->getLength() << " between " << std::get<0>(identifiers) << " and " << std::get<1>(identifiers) << "\n"; } // cleanup for (size_t i = 0; i < sequences.size(); ++i) delete sequences[i]; for (size_t i = 0; i < g_results.size(); ++i) delete g_results[i]; return 0; } <|endoftext|>
<commit_before>//.............................................................................. // // This file is part of the Doxyrest toolkit. // // Doxyrest is distributed under the MIT license. // For details see accompanying license.txt file, // the public copy of which is also available at: // http://tibbo.com/downloads/archive/doxyrest/license.txt // //.............................................................................. #include "pch.h" #include "CmdLine.h" #include "DoxyXmlParser.h" #include "Module.h" #include "Generator.h" #include "version.h" #define _PRINT_USAGE_IF_NO_ARGUMENTS 1 #define _PRINT_MODULE 0 //.............................................................................. void printVersion () { printf ( "doxyrest v%d.%d.%d (%s%s)\n", VERSION_MAJOR, VERSION_MINOR, VERSION_REVISION, AXL_CPU_STRING, AXL_DEBUG_SUFFIX ); } void printUsage () { printVersion (); sl::String helpString = CmdLineSwitchTable::getHelpString (); printf ("Usage: doxyrest <doxygen-index.xml> <options>...\n%s", helpString.sz ()); } #if _PRINT_MODULE inline void printIndent (size_t indent) { for (size_t i = 0; i < indent; i++) printf (" "); } void printDocBlock ( DocBlock const* block, size_t indent, size_t level ) { printIndent (indent); sl::Iterator <DocBlock> it; switch (block->m_blockKind) { case DocBlockKind_Paragraph: if (!block->m_title.isEmpty ()) { printf ("\\paragraph %s\n", block->m_title.sz ()); printIndent (indent); } else { printf ("\\paragraph\n"); printIndent (indent); } printf ("%s\n", ((DocParagraphBlock*) block)->m_plainText.sz ()); break; case DocBlockKind_Section: if (!block->m_title.isEmpty ()) printf ("\\sect%d %s\n", level, block->m_title.sz ()); else printf ("\\sect%d\n", level); it = ((DocSectionBlock*) block)->m_childBlockList.getHead (); for (; it; it++) printDocBlock (*it, indent + 1, level + 1); break; case DocBlockKind_Internal: printf ("\\internal\n"); it = ((DocSectionBlock*) block)->m_childBlockList.getHead (); for (; it; it++) printDocBlock (*it, indent + 1, level + 1); break; } } void printDescription ( Description const* description, size_t indent ) { if (!description->m_title.isEmpty ()) { printIndent (indent); printf ("\\title %s\n", description->m_title.sz ()); } sl::Iterator <DocBlock> it = description->m_docBlockList.getHead (); for (; it; it++) printDocBlock (*it, indent, 1); } void printEnumValue (EnumValue* enumValue) { printf ( " enumValue\n" " name: %s\n" " initializer: %s\n", enumValue->m_name.sz (), enumValue->m_initializer.m_plainText.sz () ); if (!enumValue->m_briefDescription.isEmpty ()) { printf (" briefDescription\n"); printDescription (&enumValue->m_briefDescription, 3); } if (!enumValue->m_detailedDescription.isEmpty ()) { printf (" detailedDescription\n"); printDescription (&enumValue->m_detailedDescription, 3); } } void printEnumValueList (const sl::ConstList <EnumValue>& list) { sl::Iterator <EnumValue> it = list.getHead (); for (; it; it++) printEnumValue (*it); } void printParam (Param* param) { printf ( " param\n" " declarationName: %s\n" " definitionName: %s\n" " type: %s\n" " array: %s\n" " defaultValue: %s\n" " typeConstraint: %s\n", param->m_declarationName.sz (), param->m_definitionName.sz (), param->m_type.m_plainText.sz (), param->m_array.sz (), param->m_defaultValue.m_plainText.sz (), param->m_typeConstraint.m_plainText.sz () ); if (!param->m_briefDescription.isEmpty ()) { printf (" briefDescription\n"); printDescription (&param->m_briefDescription, 3); } } void printParamList (const sl::ConstList <Param>& list) { sl::Iterator <Param> it = list.getHead (); for (; it; it++) printParam (*it); } void printMember(Member* member) { printf ( "%s %s\n" " id: %s\n" " type: %s\n" " definition: %s\n" " argString: %s\n" " bitField: %s\n" " initializer: %s\n" " exceptions: %s\n" " flags: %s\n", getMemberKindString (member->m_memberKind), member->m_name.sz (), member->m_id.sz (), member->m_type.m_plainText.sz (), member->m_definition.sz (), member->m_argString.sz (), member->m_bitField.sz (), member->m_initializer.m_plainText.sz (), member->m_exceptions.m_plainText.sz (), getProtectionKindString (member->m_protectionKind), getVirtualKindString (member->m_virtualKind), getMemberFlagString (member->m_flags).sz () ); if (!member->m_briefDescription.isEmpty ()) { printf (" briefDescription\n"); printDescription (&member->m_briefDescription, 2); } if (!member->m_detailedDescription.isEmpty ()) { printf (" detailedDescription\n"); printDescription (&member->m_detailedDescription, 2); } if (!member->m_detailedDescription.isEmpty ()) { printf (" inBodyDescription\n"); printDescription (&member->m_inBodyDescription, 2); } if (member->m_memberKind == MemberKind_Enum) { printf (" enumMembers {\n"); sl::Iterator <EnumValue> it = member->m_enumValueList.getHead (); for (; it; it++) printEnumValue (*it); printf (" }\n"); } if (!member->m_templateParamList.isEmpty ()) { printf (" templateParamList <\n"); printParamList (member->m_templateParamList); printf (" >\n"); } if (!member->m_paramList.isEmpty ()) { printf (" paramList (\n"); printParamList (member->m_paramList); printf (" )\n"); } } void printMemberList (const sl::ConstList <Member>& list) { sl::Iterator <Member> it = list.getHead (); for (; it; it++) printMember (*it); } void printMemberArray (const sl::Array <Member*>& array) { size_t count = array.getCount (); for (size_t i = 0; i < count; i++) printMember (array [i]); } void printCompound (Compound* compound) { printf ( "%s %s\n" " id: %s\n" " title: %s\n" " language: %s\n" " protection: %s\n" " isFinal: %s\n" " isSealed: %s\n" " isAbstract: %s\n", getCompoundKindString (compound->m_compoundKind), compound->m_name.sz (), compound->m_id.sz (), compound->m_title.sz (), getLanguageKindString (compound->m_languageKind), getProtectionKindString (compound->m_protectionKind), compound->m_isFinal ? "yes" : "no", compound->m_isSealed ? "yes" : "no", compound->m_isAbstract ? "yes" : "no" ); if (!compound->m_briefDescription.isEmpty ()) { printf (" briefDescription\n"); printDescription (&compound->m_briefDescription, 2); } if (!compound->m_detailedDescription.isEmpty ()) { printf (" detailedDescription\n"); printDescription (&compound->m_detailedDescription, 2); } sl::Iterator <Member> it = compound->m_memberList.getHead (); for (; it; it++) printMember (*it); printf ("\n"); } void printNamespaceContents (NamespaceContents* nspace); void printNamespaceArray (const sl::Array <Namespace*>& array) { size_t count = array.getCount (); for (size_t i = 0; i < count; i++) { Namespace* nspace = array [i]; printf ("namespace %s {\n", nspace->m_compound->m_name.sz ()); printNamespaceContents (nspace); printf ("} // namespace %s {\n", nspace->m_compound->m_name.sz ()); } } void printNamespaceContents (NamespaceContents* nspace) { if (!nspace->m_namespaceArray.isEmpty ()) { printf ("NAMESPACES\n"); printNamespaceArray (nspace->m_namespaceArray); } if (!nspace->m_enumArray.isEmpty ()) { printf ("ENUMS\n"); printMemberArray (nspace->m_enumArray); } if (!nspace->m_structArray.isEmpty ()) { printf ("STRUCTS\n"); printNamespaceArray (nspace->m_structArray); } if (!nspace->m_unionArray.isEmpty ()) { printf ("UNIONS\n"); printNamespaceArray (nspace->m_unionArray); } if (!nspace->m_classArray.isEmpty ()) { printf ("CLASSES\n"); printNamespaceArray (nspace->m_classArray); } if (!nspace->m_typedefArray.isEmpty ()) { printf ("TYPEDEFS\n"); printMemberArray (nspace->m_typedefArray); } if (!nspace->m_variableArray.isEmpty ()) { printf ("VARIABLES\n"); printMemberArray (nspace->m_variableArray); } if (!nspace->m_functionArray.isEmpty ()) { printf ("FUNCTIONS\n"); printMemberArray (nspace->m_functionArray); } if (!nspace->m_propertyArray.isEmpty ()) { printf ("PROPERTIES\n"); printMemberArray (nspace->m_propertyArray); } if (!nspace->m_eventArray.isEmpty ()) { printf ("EVENTS\n"); printMemberArray (nspace->m_eventArray); } if (!nspace->m_aliasArray.isEmpty ()) { printf ("ALIASES\n"); printMemberArray (nspace->m_aliasArray); } } #endif int run (CmdLine* cmdLine) { bool result; Module module; GlobalNamespace globalNamespace; DoxyXmlParser parser; Generator generator (cmdLine); printf ("parsing...\n"); result = parser.parseFile (&module, cmdLine->m_inputFileName) && globalNamespace.build (&module, cmdLine->m_protectionFilter); if (!result) { printf ("error: %s\n", err::getLastErrorDescription ().sz ()); return -1; } printf ("generating...\n"); result = generator.generate ( &module, &globalNamespace, cmdLine->m_outputFileName, cmdLine->m_frameFileName ); if (!result) { printf ("error: %s\n", err::getLastErrorDescription ().sz ()); return -1; } #if _PRINT_MODULE printf ("namespace :: {\n"); printNamespaceContents (&globalNamespace); printf ("} // namespace :: {\n"); #endif return 0; } //.............................................................................. #if (_AXL_OS_WIN) int wmain ( int argc, wchar_t* argv [] ) #else int main ( int argc, char* argv [] ) #endif { int result; xml::registerExpatErrorProvider (); lex::registerParseErrorProvider (); CmdLine cmdLine; CmdLineParser parser (&cmdLine); #if _PRINT_USAGE_IF_NO_ARGUMENTS if (argc < 2) { printUsage (); return 0; } #endif result = parser.parse (argc, argv); if (!result) { printf ("error parsing command line: %s\n", err::getLastErrorDescription ().sz ()); return -1; } result = 0; if (cmdLine.m_flags & CmdLineFlag_Help) printUsage (); else if (cmdLine.m_flags & CmdLineFlag_Version) printVersion (); else result = run (&cmdLine); return result; } //.............................................................................. <commit_msg>[doxyrest] set axl tag<commit_after>//.............................................................................. // // This file is part of the Doxyrest toolkit. // // Doxyrest is distributed under the MIT license. // For details see accompanying license.txt file, // the public copy of which is also available at: // http://tibbo.com/downloads/archive/doxyrest/license.txt // //.............................................................................. #include "pch.h" #include "CmdLine.h" #include "DoxyXmlParser.h" #include "Module.h" #include "Generator.h" #include "version.h" #define _PRINT_USAGE_IF_NO_ARGUMENTS 1 #define _PRINT_MODULE 0 //.............................................................................. void printVersion () { printf ( "doxyrest v%d.%d.%d (%s%s)\n", VERSION_MAJOR, VERSION_MINOR, VERSION_REVISION, AXL_CPU_STRING, AXL_DEBUG_SUFFIX ); } void printUsage () { printVersion (); sl::String helpString = CmdLineSwitchTable::getHelpString (); printf ("Usage: doxyrest <doxygen-index.xml> <options>...\n%s", helpString.sz ()); } #if _PRINT_MODULE inline void printIndent (size_t indent) { for (size_t i = 0; i < indent; i++) printf (" "); } void printDocBlock ( DocBlock const* block, size_t indent, size_t level ) { printIndent (indent); sl::Iterator <DocBlock> it; switch (block->m_blockKind) { case DocBlockKind_Paragraph: if (!block->m_title.isEmpty ()) { printf ("\\paragraph %s\n", block->m_title.sz ()); printIndent (indent); } else { printf ("\\paragraph\n"); printIndent (indent); } printf ("%s\n", ((DocParagraphBlock*) block)->m_plainText.sz ()); break; case DocBlockKind_Section: if (!block->m_title.isEmpty ()) printf ("\\sect%d %s\n", level, block->m_title.sz ()); else printf ("\\sect%d\n", level); it = ((DocSectionBlock*) block)->m_childBlockList.getHead (); for (; it; it++) printDocBlock (*it, indent + 1, level + 1); break; case DocBlockKind_Internal: printf ("\\internal\n"); it = ((DocSectionBlock*) block)->m_childBlockList.getHead (); for (; it; it++) printDocBlock (*it, indent + 1, level + 1); break; } } void printDescription ( Description const* description, size_t indent ) { if (!description->m_title.isEmpty ()) { printIndent (indent); printf ("\\title %s\n", description->m_title.sz ()); } sl::Iterator <DocBlock> it = description->m_docBlockList.getHead (); for (; it; it++) printDocBlock (*it, indent, 1); } void printEnumValue (EnumValue* enumValue) { printf ( " enumValue\n" " name: %s\n" " initializer: %s\n", enumValue->m_name.sz (), enumValue->m_initializer.m_plainText.sz () ); if (!enumValue->m_briefDescription.isEmpty ()) { printf (" briefDescription\n"); printDescription (&enumValue->m_briefDescription, 3); } if (!enumValue->m_detailedDescription.isEmpty ()) { printf (" detailedDescription\n"); printDescription (&enumValue->m_detailedDescription, 3); } } void printEnumValueList (const sl::ConstList <EnumValue>& list) { sl::Iterator <EnumValue> it = list.getHead (); for (; it; it++) printEnumValue (*it); } void printParam (Param* param) { printf ( " param\n" " declarationName: %s\n" " definitionName: %s\n" " type: %s\n" " array: %s\n" " defaultValue: %s\n" " typeConstraint: %s\n", param->m_declarationName.sz (), param->m_definitionName.sz (), param->m_type.m_plainText.sz (), param->m_array.sz (), param->m_defaultValue.m_plainText.sz (), param->m_typeConstraint.m_plainText.sz () ); if (!param->m_briefDescription.isEmpty ()) { printf (" briefDescription\n"); printDescription (&param->m_briefDescription, 3); } } void printParamList (const sl::ConstList <Param>& list) { sl::Iterator <Param> it = list.getHead (); for (; it; it++) printParam (*it); } void printMember(Member* member) { printf ( "%s %s\n" " id: %s\n" " type: %s\n" " definition: %s\n" " argString: %s\n" " bitField: %s\n" " initializer: %s\n" " exceptions: %s\n" " flags: %s\n", getMemberKindString (member->m_memberKind), member->m_name.sz (), member->m_id.sz (), member->m_type.m_plainText.sz (), member->m_definition.sz (), member->m_argString.sz (), member->m_bitField.sz (), member->m_initializer.m_plainText.sz (), member->m_exceptions.m_plainText.sz (), getProtectionKindString (member->m_protectionKind), getVirtualKindString (member->m_virtualKind), getMemberFlagString (member->m_flags).sz () ); if (!member->m_briefDescription.isEmpty ()) { printf (" briefDescription\n"); printDescription (&member->m_briefDescription, 2); } if (!member->m_detailedDescription.isEmpty ()) { printf (" detailedDescription\n"); printDescription (&member->m_detailedDescription, 2); } if (!member->m_detailedDescription.isEmpty ()) { printf (" inBodyDescription\n"); printDescription (&member->m_inBodyDescription, 2); } if (member->m_memberKind == MemberKind_Enum) { printf (" enumMembers {\n"); sl::Iterator <EnumValue> it = member->m_enumValueList.getHead (); for (; it; it++) printEnumValue (*it); printf (" }\n"); } if (!member->m_templateParamList.isEmpty ()) { printf (" templateParamList <\n"); printParamList (member->m_templateParamList); printf (" >\n"); } if (!member->m_paramList.isEmpty ()) { printf (" paramList (\n"); printParamList (member->m_paramList); printf (" )\n"); } } void printMemberList (const sl::ConstList <Member>& list) { sl::Iterator <Member> it = list.getHead (); for (; it; it++) printMember (*it); } void printMemberArray (const sl::Array <Member*>& array) { size_t count = array.getCount (); for (size_t i = 0; i < count; i++) printMember (array [i]); } void printCompound (Compound* compound) { printf ( "%s %s\n" " id: %s\n" " title: %s\n" " language: %s\n" " protection: %s\n" " isFinal: %s\n" " isSealed: %s\n" " isAbstract: %s\n", getCompoundKindString (compound->m_compoundKind), compound->m_name.sz (), compound->m_id.sz (), compound->m_title.sz (), getLanguageKindString (compound->m_languageKind), getProtectionKindString (compound->m_protectionKind), compound->m_isFinal ? "yes" : "no", compound->m_isSealed ? "yes" : "no", compound->m_isAbstract ? "yes" : "no" ); if (!compound->m_briefDescription.isEmpty ()) { printf (" briefDescription\n"); printDescription (&compound->m_briefDescription, 2); } if (!compound->m_detailedDescription.isEmpty ()) { printf (" detailedDescription\n"); printDescription (&compound->m_detailedDescription, 2); } sl::Iterator <Member> it = compound->m_memberList.getHead (); for (; it; it++) printMember (*it); printf ("\n"); } void printNamespaceContents (NamespaceContents* nspace); void printNamespaceArray (const sl::Array <Namespace*>& array) { size_t count = array.getCount (); for (size_t i = 0; i < count; i++) { Namespace* nspace = array [i]; printf ("namespace %s {\n", nspace->m_compound->m_name.sz ()); printNamespaceContents (nspace); printf ("} // namespace %s {\n", nspace->m_compound->m_name.sz ()); } } void printNamespaceContents (NamespaceContents* nspace) { if (!nspace->m_namespaceArray.isEmpty ()) { printf ("NAMESPACES\n"); printNamespaceArray (nspace->m_namespaceArray); } if (!nspace->m_enumArray.isEmpty ()) { printf ("ENUMS\n"); printMemberArray (nspace->m_enumArray); } if (!nspace->m_structArray.isEmpty ()) { printf ("STRUCTS\n"); printNamespaceArray (nspace->m_structArray); } if (!nspace->m_unionArray.isEmpty ()) { printf ("UNIONS\n"); printNamespaceArray (nspace->m_unionArray); } if (!nspace->m_classArray.isEmpty ()) { printf ("CLASSES\n"); printNamespaceArray (nspace->m_classArray); } if (!nspace->m_typedefArray.isEmpty ()) { printf ("TYPEDEFS\n"); printMemberArray (nspace->m_typedefArray); } if (!nspace->m_variableArray.isEmpty ()) { printf ("VARIABLES\n"); printMemberArray (nspace->m_variableArray); } if (!nspace->m_functionArray.isEmpty ()) { printf ("FUNCTIONS\n"); printMemberArray (nspace->m_functionArray); } if (!nspace->m_propertyArray.isEmpty ()) { printf ("PROPERTIES\n"); printMemberArray (nspace->m_propertyArray); } if (!nspace->m_eventArray.isEmpty ()) { printf ("EVENTS\n"); printMemberArray (nspace->m_eventArray); } if (!nspace->m_aliasArray.isEmpty ()) { printf ("ALIASES\n"); printMemberArray (nspace->m_aliasArray); } } #endif int run (CmdLine* cmdLine) { bool result; Module module; GlobalNamespace globalNamespace; DoxyXmlParser parser; Generator generator (cmdLine); printf ("parsing...\n"); result = parser.parseFile (&module, cmdLine->m_inputFileName) && globalNamespace.build (&module, cmdLine->m_protectionFilter); if (!result) { printf ("error: %s\n", err::getLastErrorDescription ().sz ()); return -1; } printf ("generating...\n"); result = generator.generate ( &module, &globalNamespace, cmdLine->m_outputFileName, cmdLine->m_frameFileName ); if (!result) { printf ("error: %s\n", err::getLastErrorDescription ().sz ()); return -1; } #if _PRINT_MODULE printf ("namespace :: {\n"); printNamespaceContents (&globalNamespace); printf ("} // namespace :: {\n"); #endif return 0; } //.............................................................................. #if (_AXL_OS_WIN) int wmain ( int argc, wchar_t* argv [] ) #else int main ( int argc, char* argv [] ) #endif { int result; g::getModule ()->setTag ("doxyrest"); xml::registerExpatErrorProvider (); lex::registerParseErrorProvider (); CmdLine cmdLine; CmdLineParser parser (&cmdLine); #if _PRINT_USAGE_IF_NO_ARGUMENTS if (argc < 2) { printUsage (); return 0; } #endif result = parser.parse (argc, argv); if (!result) { printf ("error parsing command line: %s\n", err::getLastErrorDescription ().sz ()); return -1; } result = 0; if (cmdLine.m_flags & CmdLineFlag_Help) printUsage (); else if (cmdLine.m_flags & CmdLineFlag_Version) printVersion (); else result = run (&cmdLine); return result; } //.............................................................................. <|endoftext|>
<commit_before>#include <vector> #include <iostream> #include <utility> // std::pair<T,U> #include <pthread.h> #include <algorithm> #include <cmath> #include "utils.hpp" int shortest_path_dist(std::vector< std::vector<int> > dist, std::vector< std::vector<double> > pheromones); void* does_work(void *ptr); //////global int problemSize =0; //int threadCount = 24; std::vector<std::vector<int> > results; std::vector<int> wholeCost; std::vector< std::vector<int> > Distance; std::vector<std::vector<double> > Pher; //std::vector int main(int argc, char** argv) { if (argc < 2) { std::cerr << "I needs a file dammit!" << std::endl; return 1; } // well what now? // something about an algorithm... // oh yes! i think i need to build the distance and pheromones array // call shortest path with itthr_count // then print out the answer std::string fileName(argv[1]); std::vector< std::vector<int> > dist = read_the_file(fileName);// returns a filled distance vector std::vector<std::vector<double> > pheromones = setup_pheromones(dist); // returns a filled pheromone vector problemSize = (dist.size() * dist[0].size())/2; for(int i =0; i < ANTCOUNT; i++) { std::vector<int> temp; results.push_back(temp); wholeCost.push_back(0); } // start time int answer = shortest_path_dist(dist, pheromones); // end time std::cout << answer << std::endl; } // this algorithm has a structure similar to floyds // so look there for inspiration // note: a thread pool is the sort of thing desired int shortest_path_dist(std::vector< std::vector<int> > dist, std::vector< std::vector<double> > pheromones) { std::vector<pthread_t> cur; for(int i = 0; i < GENERATIONS; i++) { for(int i = 0;i < ANTCOUNT; i++) { int * ii = new int(i); pthread_t temp; pthread_create(&temp, NULL, does_work,(void*)ii); cur.push_back(temp); } while(!cur.empty()) { pthread_join(cur.back(),NULL); cur.pop_back(); } cur.clear(); //global update for(int i =0; i < cur.size();i++) cur[i] = 0; } // start all needed threads // for each iteration // for each ant : IN PARALLEL // initialize the ant // share distance and pheromone graph for the thread // while a tour is not finished // choose the next city (eq 1,2) // atomic: local pheromone update (eq 3) // after reading the paper (pg 3-4), it may be possible to drop this with minimal adverse affect, we will have to time with and without // end while // end of ant's travel // atomic: global pheromone update (eq 4) // terminate the thread, release resources //} // barrier: all ants //} // end of iteration } void *does_work(void *ptr) { int pos = 0; int antDist = 0; int id = *((int *)ptr); //std::vector<double> res; std::vector<int> history; while(history.size() < problemSize) { //res.clear(); //for(int i =0;i < problemSize; i++) //{ // res.push_back(0.0); //} double choice = ((double) rand() / (RAND_MAX)) + 1; double max = 0; int maxIndex =0; if(choice < Q0){ // expliait for(int i =0; i< problemSize; i++) { if(std::find(history.begin(), history.end(), i) != history.end()) continue; double temp = Pher[pos][i] / pow(Distance[pos][i],BETA) ; if( temp > max) { max =temp; maxIndex = i; } } } else //we expolore { } Pher[pos][maxIndex] = eq3(Pher[pos][maxIndex],problemSize); antDist += Distance[pos][maxIndex]; pos = maxIndex; history.push_back(maxIndex); } results[id] = history; wholeCost[id] = antDist; } <commit_msg>I does work....<commit_after>#include <vector> #include <iostream> #include <utility> // std::pair<T,U> #include <pthread.h> #include <algorithm> #include <cmath> #include "utils.hpp" int shortest_path_dist(std::vector< std::vector<int> > dist, std::vector< std::vector<double> > pheromones); void* does_work(void *ptr); //////global int problemSize =0; //int threadCount = 24; std::vector<std::vector<int> > results; std::vector<int> wholeCost; std::vector< std::vector<int> > Distance; std::vector<std::vector<double> > Pher; std::vector<int> Locations; int main(int argc, char** argv) { if (argc < 2) { std::cerr << "I needs a file dammit!" << std::endl; return 1; } // well what now? // something about an algorithm... // oh yes! i think i need to build the distance and pheromones array // call shortest path with itthr_count // then print out the answer std::string fileName(argv[1]); std::vector< std::vector<int> > dist = read_the_file(fileName);// returns a filled distance vector std::vector<std::vector<double> > pheromones = setup_pheromones(dist); // returns a filled pheromone vector problemSize = (dist.size() * dist[0].size())/2; for(int i =0; i < ANTCOUNT; i++) { std::vector<int> temp; Locations.push_back(i); results.push_back(temp); wholeCost.push_back(0); } // start time int answer = shortest_path_dist(dist, pheromones); // end time std::cout << answer << std::endl; } // this algorithm has a structure similar to floyds // so look there for inspiration // note: a thread pool is the sort of thing desired int shortest_path_dist(std::vector< std::vector<int> > dist, std::vector< std::vector<double> > pheromones) { std::vector<pthread_t> cur; for(int i = 0; i < GENERATIONS; i++) { for(int i = 0;i < ANTCOUNT; i++) { int * ii = new int(i); pthread_t temp; pthread_create(&temp, NULL, does_work,(void*)ii); cur.push_back(temp); } while(!cur.empty()) { pthread_join(cur.back(),NULL); cur.pop_back(); } cur.clear(); //global update for(int i =0; i < cur.size();i++) cur[i] = 0; } // start all needed threads // for each iteration // for each ant : IN PARALLEL // initialize the ant // share distance and pheromone graph for the thread // while a tour is not finished // choose the next city (eq 1,2) // atomic: local pheromone update (eq 3) // after reading the paper (pg 3-4), it may be possible to drop this with minimal adverse affect, we will have to time with and without // end while // end of ant's travel // atomic: global pheromone update (eq 4) // terminate the thread, release resources //} // barrier: all ants //} // end of iteration } void *does_work(void *ptr) { int pos = 0; int antDist = 0; int id = *((int *)ptr); //std::vector<double> res; std::vector<int> history; std::vector<int> unvisited = Locations; while(history.size() < problemSize) { //res.clear(); //for(int i =0;i < problemSize; i++) //{ // res.push_back(0.0); //} double choice = ((double) rand() / (RAND_MAX)) + 1; double choice2 = ((double) rand() / (RAND_MAX)) + 1; double max = 0; int maxIndex =0; if(choice < Q0){ // expliait for(int i =0; i< problemSize; i++) { if(std::find(history.begin(), history.end(), i) != history.end()) continue; double temp = Pher[pos][i] / pow(Distance[pos][i], BETA) ; if( temp > max) { max =temp; maxIndex = i; } } } else //we expolore { std::vector cho = eq2(Distance, Pher, unvisited, pos); maxIndex = eq2_helper(cho,choice2); max = Pher[pos][maxIndex] / pow(Distance[pos][maxIndex], BETA); } Pher[pos][maxIndex] = eq3(Pher[pos][maxIndex],problemSize); antDist += Distance[pos][maxIndex]; pos = maxIndex; history.push_back(maxIndex); int temp = std::find(unvisited.begin(),unvisited.end(),maxIndex); unvisited.erase(unvisited.begin() + temp); } results[id] = history; wholeCost[id] = antDist; } <|endoftext|>
<commit_before> #include <QtWidgets/QVBoxLayout> #include <QtWidgets/QGridLayout> #include <QtWidgets/QMessageBox> #include <QtWidgets/QStatusBar> #include <QtCore/QDir> #include <QtCore/QFile> #include <QtCore/QTextStream> #include <QtCore/QIODevice> #include <QtGui/QPalette> #include <QtGui/QColor> #include <QtGui/QGuiApplication> #include <QtGui/QClipboard> #include "dwr.h" #include "main-window.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) { this->mainWidget = new QWidget(); this->setCentralWidget(this->mainWidget); this->initWidgets(); this->initStatus(); this->layout(); this->initSlots(); this->loadConfig(); } void MainWindow::initStatus() { QStatusBar *status = this->statusBar(); status->showMessage("Ready"); QPalette palette = this->palette(); palette.setColor(QPalette::Background, Qt::lightGray); palette.setColor(QPalette::Foreground, Qt::black); status->setPalette(palette); status->setAutoFillBackground(true); } void MainWindow::initWidgets() { this->romFile = new FileEntry(this); this->outputDir = new DirEntry(this); this->seed = new SeedEntry(this); this->flags = new FlagEntry(this); chests = new CheckBox('C', "Shuffle Chests && Search Items", this); shops = new CheckBox('W', "Randomize Weapon Shops", this); deathNecklace = new CheckBox('D', "Enable Death Necklace", this); speedHacks = new CheckBox('H', "Enable Speed Hacks", this); growth = new CheckBox('G', "Randomize Growth", this); spells = new CheckBox('M', "Randomize Spell Learning", this); attack = new CheckBox('P', "Randomize Enemy Attacks", this); zones = new CheckBox('Z', "Randomize Zones", this); musicShuffle = new CheckBox('K', "Shuffle Music", this); musicDisable = new CheckBox('Q', "Disable Music", this); copyChecksum = new CheckBox(NO_FLAG, "Copy Checksum to Clipboard", this); this->levelSpeed = new LevelComboBox(this); this->goButton = new QPushButton("Randomize!", this); } void MainWindow::initSlots() { connect(this->flags, SIGNAL(textEdited(QString)), this, SLOT(handleFlags())); connect(this->chests, SIGNAL(clicked()), this, SLOT(handleCheckBox())); connect(this->shops, SIGNAL(clicked()), this, SLOT(handleCheckBox())); connect(this->deathNecklace,SIGNAL(clicked()), this, SLOT(handleCheckBox())); connect(this->speedHacks, SIGNAL(clicked()), this, SLOT(handleCheckBox())); connect(this->growth, SIGNAL(clicked()), this, SLOT(handleCheckBox())); connect(this->spells, SIGNAL(clicked()), this, SLOT(handleCheckBox())); connect(this->attack, SIGNAL(clicked()), this, SLOT(handleCheckBox())); connect(this->zones, SIGNAL(clicked()), this, SLOT(handleCheckBox())); connect(this->musicShuffle, SIGNAL(clicked()), this, SLOT(handleCheckBox())); connect(this->musicDisable, SIGNAL(clicked()), this, SLOT(handleCheckBox())); connect(this->copyChecksum, SIGNAL(clicked()), this, SLOT(handleCheckBox())); connect(this->levelSpeed, SIGNAL(activated(int)), this, SLOT(handleCheckBox())); connect(this->goButton, SIGNAL(clicked()), this, SLOT(handleButton())); } void MainWindow::layout() { QVBoxLayout *vbox; QGridLayout *grid; vbox = new QVBoxLayout(); grid = new QGridLayout(); grid->addWidget(this->romFile, 0, 0, 0); grid->addWidget(this->outputDir, 0, 1, 0); grid->addWidget(this->seed, 1, 0, 0); grid->addWidget(this->flags, 1, 1, 0); vbox->addLayout(grid); grid = new QGridLayout(); vbox->addLayout(grid); grid->addWidget(this->chests, 0, 0, 0); grid->addWidget(this->shops, 1, 0, 0); grid->addWidget(this->zones, 2, 0, 0); grid->addWidget(this->growth, 0, 1, 0); grid->addWidget(this->spells, 1, 1, 0); grid->addWidget(this->attack, 2, 1, 0); grid->addWidget(this->copyChecksum, 3, 1, 0); grid->addWidget(this->deathNecklace, 0, 2, 0); grid->addWidget(this->speedHacks, 1, 2, 0); grid->addWidget(this->musicShuffle, 2, 2, 0); grid->addWidget(this->musicDisable, 3, 2, 0); grid->addWidget(new QLabel("Leveling Speed", this), 6, 0, 0); grid->addWidget(this->levelSpeed, 7, 0, 0); grid->addWidget(this->goButton, 8, 2, 0); this->mainWidget->setLayout(vbox); this->copyChecksum->hide(); } QString MainWindow::getOptions() { std::string flags = std::string() + this->chests->getFlag() + this->shops->getFlag() + this->deathNecklace->getFlag() + this->speedHacks->getFlag() + this->growth->getFlag() + this->spells->getFlag() + this->attack->getFlag() + this->zones->getFlag() + this->musicShuffle->getFlag() + this->musicDisable->getFlag() + this->copyChecksum->getFlag() + this->levelSpeed->getFlag(); std::sort(flags.begin(), flags.end()); std::replace(flags.begin(), flags.end(), NO_FLAG, '\0'); return QString(flags.c_str()); } void MainWindow::setOptions(QString flags) { this->chests->updateState(flags); this->shops->updateState(flags); this->deathNecklace->updateState(flags); this->speedHacks->updateState(flags); this->growth->updateState(flags); this->spells->updateState(flags); this->attack->updateState(flags); this->zones->updateState(flags); this->musicShuffle->updateState(flags); this->musicDisable->updateState(flags); this->copyChecksum->updateState(flags); this->levelSpeed->updateState(flags); } QString MainWindow::getFlags() { std::string flags = this->flags->text().toStdString(); std::sort(flags.begin(), flags.end()); return QString::fromStdString(flags); } void MainWindow::setFlags(QString flags) { this->flags->setText(flags); } void MainWindow::handleCheckBox() { QString flags = this->getOptions(); this->setFlags(flags); } void MainWindow::handleComboBox(int index) { this->handleCheckBox(); } void MainWindow::handleFlags() { QString flags = this->getFlags(); this->setOptions(flags); } void MainWindow::handleButton() { char flags[64], checksum[64]; QString flagStr = this->getFlags(); strncpy(flags, flagStr.toLatin1().constData(), 64); uint64_t seed = this->seed->getSeed(); std::string inputFile = this->romFile->text().toLatin1().constData(); std::string outputDir = this->outputDir->text().toLatin1().constData(); uint64_t crc = dwr_randomize(inputFile.c_str(), seed, flags, outputDir.c_str()); if (crc) { sprintf(checksum, "Checksum: %016" PRIx64, crc); QGuiApplication::clipboard()->setText(checksum); this->statusBar()->showMessage("Checksum copied to clipboard", 3000); QMessageBox::information(this, "Success!", "The new ROM has been created."); } else { QMessageBox::critical(this, "Failed", "An error occurred and" "the ROM could not be created."); } this->saveConfig(); } bool MainWindow::saveConfig() { QFile configFile(QDir::homePath() + "/.config/dwrandomizer2.conf"); if (!configFile.open(QIODevice::WriteOnly | QIODevice::Text)) { printf("Failed to save configuration.\n"); return false; } QTextStream out(&configFile); out << this->romFile->text() << endl; out << this->outputDir->text() << endl; out << this->getFlags() << endl; return true; } bool MainWindow::loadConfig() { char tmp[1024]; qint64 read; QFile configFile(QDir::homePath() + "/.config/dwrandomizer2.conf"); if (!configFile.open(QIODevice::ReadOnly | QIODevice::Text)) { printf("Failed to load configuration.\n"); return false; } read = configFile.readLine(tmp, 1024); tmp[read - 1] = '\0'; this->romFile->setText(tmp); if (configFile.atEnd()) { return false; } read = configFile.readLine(tmp, 1024); tmp[read - 1] = '\0'; this->outputDir->setText(tmp); if (configFile.atEnd()) { return false; } read = configFile.readLine(tmp, 1024); tmp[read - 1] = '\0'; this->setFlags(tmp); this->setOptions(tmp); return true; } <commit_msg>Config directory is now created if missing<commit_after> #include <QtWidgets/QVBoxLayout> #include <QtWidgets/QGridLayout> #include <QtWidgets/QMessageBox> #include <QtWidgets/QStatusBar> #include <QtCore/QDir> #include <QtCore/QFile> #include <QtCore/QTextStream> #include <QtCore/QIODevice> #include <QtGui/QPalette> #include <QtGui/QColor> #include <QtGui/QGuiApplication> #include <QtGui/QClipboard> #include "dwr.h" #include "main-window.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) { this->mainWidget = new QWidget(); this->setCentralWidget(this->mainWidget); this->initWidgets(); this->initStatus(); this->layout(); this->initSlots(); this->loadConfig(); } void MainWindow::initStatus() { QStatusBar *status = this->statusBar(); status->showMessage("Ready"); QPalette palette = this->palette(); palette.setColor(QPalette::Background, Qt::lightGray); palette.setColor(QPalette::Foreground, Qt::black); status->setPalette(palette); status->setAutoFillBackground(true); } void MainWindow::initWidgets() { this->romFile = new FileEntry(this); this->outputDir = new DirEntry(this); this->seed = new SeedEntry(this); this->flags = new FlagEntry(this); chests = new CheckBox('C', "Shuffle Chests && Search Items", this); shops = new CheckBox('W', "Randomize Weapon Shops", this); deathNecklace = new CheckBox('D', "Enable Death Necklace", this); speedHacks = new CheckBox('H', "Enable Speed Hacks", this); growth = new CheckBox('G', "Randomize Growth", this); spells = new CheckBox('M', "Randomize Spell Learning", this); attack = new CheckBox('P', "Randomize Enemy Attacks", this); zones = new CheckBox('Z', "Randomize Zones", this); musicShuffle = new CheckBox('K', "Shuffle Music", this); musicDisable = new CheckBox('Q', "Disable Music", this); copyChecksum = new CheckBox(NO_FLAG, "Copy Checksum to Clipboard", this); this->levelSpeed = new LevelComboBox(this); this->goButton = new QPushButton("Randomize!", this); } void MainWindow::initSlots() { connect(this->flags, SIGNAL(textEdited(QString)), this, SLOT(handleFlags())); connect(this->chests, SIGNAL(clicked()), this, SLOT(handleCheckBox())); connect(this->shops, SIGNAL(clicked()), this, SLOT(handleCheckBox())); connect(this->deathNecklace,SIGNAL(clicked()), this, SLOT(handleCheckBox())); connect(this->speedHacks, SIGNAL(clicked()), this, SLOT(handleCheckBox())); connect(this->growth, SIGNAL(clicked()), this, SLOT(handleCheckBox())); connect(this->spells, SIGNAL(clicked()), this, SLOT(handleCheckBox())); connect(this->attack, SIGNAL(clicked()), this, SLOT(handleCheckBox())); connect(this->zones, SIGNAL(clicked()), this, SLOT(handleCheckBox())); connect(this->musicShuffle, SIGNAL(clicked()), this, SLOT(handleCheckBox())); connect(this->musicDisable, SIGNAL(clicked()), this, SLOT(handleCheckBox())); connect(this->copyChecksum, SIGNAL(clicked()), this, SLOT(handleCheckBox())); connect(this->levelSpeed, SIGNAL(activated(int)), this, SLOT(handleCheckBox())); connect(this->goButton, SIGNAL(clicked()), this, SLOT(handleButton())); } void MainWindow::layout() { QVBoxLayout *vbox; QGridLayout *grid; vbox = new QVBoxLayout(); grid = new QGridLayout(); grid->addWidget(this->romFile, 0, 0, 0); grid->addWidget(this->outputDir, 0, 1, 0); grid->addWidget(this->seed, 1, 0, 0); grid->addWidget(this->flags, 1, 1, 0); vbox->addLayout(grid); grid = new QGridLayout(); vbox->addLayout(grid); grid->addWidget(this->chests, 0, 0, 0); grid->addWidget(this->shops, 1, 0, 0); grid->addWidget(this->zones, 2, 0, 0); grid->addWidget(this->growth, 0, 1, 0); grid->addWidget(this->spells, 1, 1, 0); grid->addWidget(this->attack, 2, 1, 0); grid->addWidget(this->copyChecksum, 3, 1, 0); grid->addWidget(this->deathNecklace, 0, 2, 0); grid->addWidget(this->speedHacks, 1, 2, 0); grid->addWidget(this->musicShuffle, 2, 2, 0); grid->addWidget(this->musicDisable, 3, 2, 0); grid->addWidget(new QLabel("Leveling Speed", this), 6, 0, 0); grid->addWidget(this->levelSpeed, 7, 0, 0); grid->addWidget(this->goButton, 8, 2, 0); this->mainWidget->setLayout(vbox); this->copyChecksum->hide(); } QString MainWindow::getOptions() { std::string flags = std::string() + this->chests->getFlag() + this->shops->getFlag() + this->deathNecklace->getFlag() + this->speedHacks->getFlag() + this->growth->getFlag() + this->spells->getFlag() + this->attack->getFlag() + this->zones->getFlag() + this->musicShuffle->getFlag() + this->musicDisable->getFlag() + this->copyChecksum->getFlag() + this->levelSpeed->getFlag(); std::sort(flags.begin(), flags.end()); std::replace(flags.begin(), flags.end(), NO_FLAG, '\0'); return QString(flags.c_str()); } void MainWindow::setOptions(QString flags) { this->chests->updateState(flags); this->shops->updateState(flags); this->deathNecklace->updateState(flags); this->speedHacks->updateState(flags); this->growth->updateState(flags); this->spells->updateState(flags); this->attack->updateState(flags); this->zones->updateState(flags); this->musicShuffle->updateState(flags); this->musicDisable->updateState(flags); this->copyChecksum->updateState(flags); this->levelSpeed->updateState(flags); } QString MainWindow::getFlags() { std::string flags = this->flags->text().toStdString(); std::sort(flags.begin(), flags.end()); return QString::fromStdString(flags); } void MainWindow::setFlags(QString flags) { this->flags->setText(flags); } void MainWindow::handleCheckBox() { QString flags = this->getOptions(); this->setFlags(flags); } void MainWindow::handleComboBox(int index) { this->handleCheckBox(); } void MainWindow::handleFlags() { QString flags = this->getFlags(); this->setOptions(flags); } void MainWindow::handleButton() { char flags[64], checksum[64]; QString flagStr = this->getFlags(); strncpy(flags, flagStr.toLatin1().constData(), 64); uint64_t seed = this->seed->getSeed(); std::string inputFile = this->romFile->text().toLatin1().constData(); std::string outputDir = this->outputDir->text().toLatin1().constData(); uint64_t crc = dwr_randomize(inputFile.c_str(), seed, flags, outputDir.c_str()); if (crc) { sprintf(checksum, "Checksum: %016" PRIx64, crc); QGuiApplication::clipboard()->setText(checksum); this->statusBar()->showMessage("Checksum copied to clipboard", 3000); QMessageBox::information(this, "Success!", "The new ROM has been created."); } else { QMessageBox::critical(this, "Failed", "An error occurred and" "the ROM could not be created."); } this->saveConfig(); } bool MainWindow::saveConfig() { QDir configDir(""); if (!configDir.exists(QDir::homePath() + "/.config/")){ configDir.mkdir(QDir::homePath() + "/.config/"); } QFile configFile(QDir::homePath() + "/.config/dwrandomizer2.conf"); if (!configFile.open(QIODevice::WriteOnly | QIODevice::Text)) { printf("Failed to save configuration.\n"); return false; } QTextStream out(&configFile); out << this->romFile->text() << endl; out << this->outputDir->text() << endl; out << this->getFlags() << endl; return true; } bool MainWindow::loadConfig() { char tmp[1024]; qint64 read; QFile configFile(QDir::homePath() + "/.config/dwrandomizer2.conf"); if (!configFile.open(QIODevice::ReadOnly | QIODevice::Text)) { printf("Failed to load configuration.\n"); return false; } read = configFile.readLine(tmp, 1024); tmp[read - 1] = '\0'; this->romFile->setText(tmp); if (configFile.atEnd()) { return false; } read = configFile.readLine(tmp, 1024); tmp[read - 1] = '\0'; this->outputDir->setText(tmp); if (configFile.atEnd()) { return false; } read = configFile.readLine(tmp, 1024); tmp[read - 1] = '\0'; this->setFlags(tmp); this->setOptions(tmp); return true; } <|endoftext|>
<commit_before>// This Source Code Form is licensed MPL-2.0: http://mozilla.org/MPL/2.0 #include "paintwidgets.hh" #include "factory.hh" #include "painter.hh" #define CHECK_CAIRO_STATUS(status) do { \ cairo_status_t ___s = (status); \ if (___s != CAIRO_STATUS_SUCCESS) \ RAPICORN_DIAG ("%s: %s", cairo_status_to_string (___s), #status); \ } while (0) namespace Rapicorn { // == ArrowImpl == ArrowImpl::ArrowImpl() : dir_ (Direction::RIGHT) {} ArrowImpl::~ArrowImpl() {} Direction ArrowImpl::arrow_dir () const { return dir_; } void ArrowImpl::arrow_dir (Direction dir) { dir_ = dir; expose(); changed ("arrow_dir"); } static DataKey<SizePolicy> size_policy_key; SizePolicy ArrowImpl::size_policy () const { SizePolicy spol = get_data (&size_policy_key); return spol; } void ArrowImpl::size_policy (SizePolicy spol) { if (spol == 0) delete_data (&size_policy_key); else set_data (&size_policy_key, spol); invalidate_size(); changed ("size_policy"); } void ArrowImpl::size_request (Requisition &requisition) { requisition.width = 3; requisition.height = 3; } void ArrowImpl::size_allocate (Allocation area, bool changed) { SizePolicy spol = size_policy(); if (spol == SizePolicy::WIDTH_FROM_HEIGHT) tune_requisition (area.height, -1); else if (spol == SizePolicy::HEIGHT_FROM_WIDTH) tune_requisition (-1, area.width); } void ArrowImpl::render (RenderContext &rcontext) { IRect ia = allocation(); int x = ia.x, y = ia.y, width = ia.width, height = ia.height; if (width >= 2 && height >= 2) { cairo_t *cr = cairo_context (rcontext); CPainter painter (cr); painter.draw_dir_arrow (x, y, width, height, foreground(), dir_); } } static const WidgetFactory<ArrowImpl> arrow_factory ("Rapicorn::Arrow"); // == DotGrid == DotGridImpl::DotGridImpl() : normal_dot_ (DrawFrame::IN), active_dot_ (DrawFrame::IN), n_hdots_ (1), n_vdots_ (1), right_padding_dots_ (0), top_padding_dots_ (0), left_padding_dots_ (0), bottom_padding_dots_ (0) {} DotGridImpl::~DotGridImpl() {} DrawFrame DotGridImpl::dot_type () const { RAPICORN_ASSERT_UNREACHED(); } void DotGridImpl::dot_type (DrawFrame ft) { normal_dot (ft); active_dot (ft); } DrawFrame DotGridImpl::current_dot () { return ancestry_active() ? active_dot() : normal_dot(); } static inline int u31 (int v) { return CLAMP (v, 0, INT_MAX); } void DotGridImpl::active_dot (DrawFrame ft) { active_dot_ = ft; expose(); changed ("active_dot"); } DrawFrame DotGridImpl::active_dot () const { return active_dot_; } void DotGridImpl::normal_dot (DrawFrame ft) { normal_dot_ = ft; expose(); changed ("normal_dot"); } DrawFrame DotGridImpl::normal_dot () const { return normal_dot_; } void DotGridImpl::n_hdots (int num) { n_hdots_ = u31 (num); expose(); changed ("n_hdots"); } int DotGridImpl::n_hdots () const { return n_hdots_; } void DotGridImpl::n_vdots (int num) { n_vdots_ = u31 (num); expose(); changed ("n_vdots"); } int DotGridImpl::n_vdots () const { return n_vdots_; } int DotGridImpl::right_padding_dots () const { return right_padding_dots_; } void DotGridImpl::right_padding_dots (int c) { right_padding_dots_ = u31 (c); expose(); changed ("right_padding_dots"); } int DotGridImpl::top_padding_dots () const { return top_padding_dots_; } void DotGridImpl::top_padding_dots (int c) { top_padding_dots_ = u31 (c); expose(); changed ("top_padding_dots"); } int DotGridImpl::left_padding_dots () const { return left_padding_dots_; } void DotGridImpl::left_padding_dots (int c) { left_padding_dots_ = u31 (c); expose(); changed ("left_padding_dots"); } int DotGridImpl::bottom_padding_dots () const { return bottom_padding_dots_; } void DotGridImpl::bottom_padding_dots (int c) { bottom_padding_dots_ = u31 (c); expose(); changed ("bottom_padding_dots"); } void DotGridImpl::size_request (Requisition &requisition) { const uint ythick = 1, xthick = 1; requisition.width = n_hdots_ * (xthick + xthick) + MAX (n_hdots_ - 1, 0) * xthick; requisition.height = n_vdots_ * (ythick + ythick) + MAX (n_vdots_ - 1, 0) * ythick; requisition.width += (right_padding_dots_ + left_padding_dots_) * 3 * xthick; requisition.height += (top_padding_dots_ + bottom_padding_dots_) * 3 * ythick; } void DotGridImpl::size_allocate (Allocation area, bool changed) {} void DotGridImpl::render (RenderContext &rcontext) { const int ythick = 1, xthick = 1; int n_hdots = n_hdots_, n_vdots = n_vdots_; const IRect ia = allocation(); int x = ia.x, y = ia.y, width = ia.width, height = ia.height; const int rq_width = n_hdots_ * (xthick + xthick) + MAX (n_hdots - 1, 0) * xthick; const int rq_height = n_vdots_ * (ythick + ythick) + MAX (n_vdots - 1, 0) * ythick; /* split up extra width */ const uint hpadding = right_padding_dots_ + left_padding_dots_; const double halign = hpadding ? left_padding_dots_ * 1.0 / hpadding : 0.5; if (rq_width < width) x += ifloor ((width - rq_width) * halign); /* split up extra height */ const uint vpadding = top_padding_dots_ + bottom_padding_dots_; const double valign = vpadding ? bottom_padding_dots_ * 1.0 / vpadding : 0.5; if (rq_height < height) y += ifloor ((height - rq_height) * valign); /* draw dots */ if (width >= 2 * xthick && height >= 2 * ythick && n_hdots && n_vdots) { /* limit n_hdots */ if (rq_width > width) { const int w = width - 2 * xthick; // dot1 n_hdots = 1 + w / (3 * xthick); } /* limit n_vdots */ if (rq_height > height) { const int h = height - 2 * ythick; // dot1 n_vdots = 1 + h / (3 * ythick); } cairo_t *cr = cairo_context (rcontext); CPainter rp (cr); for (int j = 0; j < n_vdots; j++) { int xtmp = 0; for (int i = 0; i < n_hdots; i++) { rp.draw_shaded_rect (x + xtmp, y + 2 * ythick - 1, dark_shadow(), x + xtmp + 2 * xthick - 1, y, light_glint()); xtmp += 3 * xthick; } y += 3 * ythick; } } } static const WidgetFactory<DotGridImpl> dot_grid_factory ("Rapicorn::DotGrid"); // == DrawableImpl == DrawableImpl::DrawableImpl() : x_ (0), y_ (0) {} void DrawableImpl::size_request (Requisition &requisition) { requisition.width = 320; requisition.height = 200; } void DrawableImpl::size_allocate (Allocation area, bool changed) { if (false) // clear out, can lead to flicker { pixbuf_ = Pixbuf(); x_ = 0; y_ = 0; } sig_redraw.emit (area.x, area.y, area.width, area.height); } void DrawableImpl::draw_rect (int x, int y, const Pixbuf &pixbuf) { const Allocation &area = allocation(); const size_t rowstride = pixbuf.width(); if (x >= area.x && y >= area.y && x + pixbuf.width() <= area.x + area.width && y + pixbuf.height() <= area.y + area.height && rowstride * pixbuf.height() <= pixbuf.pixels.size()) { x_ = x; y_ = y; pixbuf_ = pixbuf; } else if (pixbuf_.width() > 0) { pixbuf_ = Pixbuf(); x_ = 0; y_ = 0; } invalidate_content(); } void DrawableImpl::render (RenderContext &rcontext) { const uint size = 10; const Allocation &area = allocation(); cairo_t *cr = cairo_context (rcontext); // checkerboard pattern if (true) { cairo_save (cr); cairo_surface_t *ps = cairo_surface_create_similar (cairo_get_target (cr), CAIRO_CONTENT_COLOR, 2 * size, 2 * size); cairo_t *pc = cairo_create (ps); cairo_set_source_rgb (pc, 1.0, 1.0, 1.0); cairo_rectangle (pc, 0, 0, size, size); cairo_rectangle (pc, size, size, size, size); cairo_fill (pc); cairo_set_source_rgb (pc, 0.9, 0.9, 0.9); cairo_rectangle (pc, 0, size, size, size); cairo_rectangle (pc, size, 0, size, size); cairo_fill (pc); cairo_destroy (pc); cairo_pattern_t *pat = cairo_pattern_create_for_surface (ps); cairo_surface_destroy (ps); cairo_pattern_set_extend (pat, CAIRO_EXTEND_REPEAT); // render pattern cairo_rectangle (cr, area.x, area.y, area.width, area.height); cairo_clip (cr); cairo_translate (cr, area.x, area.y + area.height); cairo_set_source (cr, pat); cairo_paint (cr); cairo_pattern_destroy (pat); cairo_restore (cr); } // handle user draw if (pixbuf_.width() > 0 && pixbuf_.height() > 0) { const int rowstride = pixbuf_.width(); cairo_surface_t *surface = cairo_image_surface_create_for_data ((uint8*) pixbuf_.pixels.data(), CAIRO_FORMAT_ARGB32, pixbuf_.width(), pixbuf_.height(), rowstride * 4); CHECK_CAIRO_STATUS (cairo_surface_status (surface)); cairo_set_source_surface (cr, surface, x_, y_); cairo_paint (cr); cairo_surface_destroy (surface); } } static const WidgetFactory<DrawableImpl> drawable_factory ("Rapicorn::Drawable"); } // Rapicorn <commit_msg>UI: paintwidgets.cc: use CAIRO_CHECK_STATUS()<commit_after>// This Source Code Form is licensed MPL-2.0: http://mozilla.org/MPL/2.0 #include "paintwidgets.hh" #include "factory.hh" #include "painter.hh" #include "rcore/cairoutils.hh" namespace Rapicorn { // == ArrowImpl == ArrowImpl::ArrowImpl() : dir_ (Direction::RIGHT) {} ArrowImpl::~ArrowImpl() {} Direction ArrowImpl::arrow_dir () const { return dir_; } void ArrowImpl::arrow_dir (Direction dir) { dir_ = dir; expose(); changed ("arrow_dir"); } static DataKey<SizePolicy> size_policy_key; SizePolicy ArrowImpl::size_policy () const { SizePolicy spol = get_data (&size_policy_key); return spol; } void ArrowImpl::size_policy (SizePolicy spol) { if (spol == 0) delete_data (&size_policy_key); else set_data (&size_policy_key, spol); invalidate_size(); changed ("size_policy"); } void ArrowImpl::size_request (Requisition &requisition) { requisition.width = 3; requisition.height = 3; } void ArrowImpl::size_allocate (Allocation area, bool changed) { SizePolicy spol = size_policy(); if (spol == SizePolicy::WIDTH_FROM_HEIGHT) tune_requisition (area.height, -1); else if (spol == SizePolicy::HEIGHT_FROM_WIDTH) tune_requisition (-1, area.width); } void ArrowImpl::render (RenderContext &rcontext) { IRect ia = allocation(); int x = ia.x, y = ia.y, width = ia.width, height = ia.height; if (width >= 2 && height >= 2) { cairo_t *cr = cairo_context (rcontext); CPainter painter (cr); painter.draw_dir_arrow (x, y, width, height, foreground(), dir_); } } static const WidgetFactory<ArrowImpl> arrow_factory ("Rapicorn::Arrow"); // == DotGrid == DotGridImpl::DotGridImpl() : normal_dot_ (DrawFrame::IN), active_dot_ (DrawFrame::IN), n_hdots_ (1), n_vdots_ (1), right_padding_dots_ (0), top_padding_dots_ (0), left_padding_dots_ (0), bottom_padding_dots_ (0) {} DotGridImpl::~DotGridImpl() {} DrawFrame DotGridImpl::dot_type () const { RAPICORN_ASSERT_UNREACHED(); } void DotGridImpl::dot_type (DrawFrame ft) { normal_dot (ft); active_dot (ft); } DrawFrame DotGridImpl::current_dot () { return ancestry_active() ? active_dot() : normal_dot(); } static inline int u31 (int v) { return CLAMP (v, 0, INT_MAX); } void DotGridImpl::active_dot (DrawFrame ft) { active_dot_ = ft; expose(); changed ("active_dot"); } DrawFrame DotGridImpl::active_dot () const { return active_dot_; } void DotGridImpl::normal_dot (DrawFrame ft) { normal_dot_ = ft; expose(); changed ("normal_dot"); } DrawFrame DotGridImpl::normal_dot () const { return normal_dot_; } void DotGridImpl::n_hdots (int num) { n_hdots_ = u31 (num); expose(); changed ("n_hdots"); } int DotGridImpl::n_hdots () const { return n_hdots_; } void DotGridImpl::n_vdots (int num) { n_vdots_ = u31 (num); expose(); changed ("n_vdots"); } int DotGridImpl::n_vdots () const { return n_vdots_; } int DotGridImpl::right_padding_dots () const { return right_padding_dots_; } void DotGridImpl::right_padding_dots (int c) { right_padding_dots_ = u31 (c); expose(); changed ("right_padding_dots"); } int DotGridImpl::top_padding_dots () const { return top_padding_dots_; } void DotGridImpl::top_padding_dots (int c) { top_padding_dots_ = u31 (c); expose(); changed ("top_padding_dots"); } int DotGridImpl::left_padding_dots () const { return left_padding_dots_; } void DotGridImpl::left_padding_dots (int c) { left_padding_dots_ = u31 (c); expose(); changed ("left_padding_dots"); } int DotGridImpl::bottom_padding_dots () const { return bottom_padding_dots_; } void DotGridImpl::bottom_padding_dots (int c) { bottom_padding_dots_ = u31 (c); expose(); changed ("bottom_padding_dots"); } void DotGridImpl::size_request (Requisition &requisition) { const uint ythick = 1, xthick = 1; requisition.width = n_hdots_ * (xthick + xthick) + MAX (n_hdots_ - 1, 0) * xthick; requisition.height = n_vdots_ * (ythick + ythick) + MAX (n_vdots_ - 1, 0) * ythick; requisition.width += (right_padding_dots_ + left_padding_dots_) * 3 * xthick; requisition.height += (top_padding_dots_ + bottom_padding_dots_) * 3 * ythick; } void DotGridImpl::size_allocate (Allocation area, bool changed) {} void DotGridImpl::render (RenderContext &rcontext) { const int ythick = 1, xthick = 1; int n_hdots = n_hdots_, n_vdots = n_vdots_; const IRect ia = allocation(); int x = ia.x, y = ia.y, width = ia.width, height = ia.height; const int rq_width = n_hdots_ * (xthick + xthick) + MAX (n_hdots - 1, 0) * xthick; const int rq_height = n_vdots_ * (ythick + ythick) + MAX (n_vdots - 1, 0) * ythick; /* split up extra width */ const uint hpadding = right_padding_dots_ + left_padding_dots_; const double halign = hpadding ? left_padding_dots_ * 1.0 / hpadding : 0.5; if (rq_width < width) x += ifloor ((width - rq_width) * halign); /* split up extra height */ const uint vpadding = top_padding_dots_ + bottom_padding_dots_; const double valign = vpadding ? bottom_padding_dots_ * 1.0 / vpadding : 0.5; if (rq_height < height) y += ifloor ((height - rq_height) * valign); /* draw dots */ if (width >= 2 * xthick && height >= 2 * ythick && n_hdots && n_vdots) { /* limit n_hdots */ if (rq_width > width) { const int w = width - 2 * xthick; // dot1 n_hdots = 1 + w / (3 * xthick); } /* limit n_vdots */ if (rq_height > height) { const int h = height - 2 * ythick; // dot1 n_vdots = 1 + h / (3 * ythick); } cairo_t *cr = cairo_context (rcontext); CPainter rp (cr); for (int j = 0; j < n_vdots; j++) { int xtmp = 0; for (int i = 0; i < n_hdots; i++) { rp.draw_shaded_rect (x + xtmp, y + 2 * ythick - 1, dark_shadow(), x + xtmp + 2 * xthick - 1, y, light_glint()); xtmp += 3 * xthick; } y += 3 * ythick; } } } static const WidgetFactory<DotGridImpl> dot_grid_factory ("Rapicorn::DotGrid"); // == DrawableImpl == DrawableImpl::DrawableImpl() : x_ (0), y_ (0) {} void DrawableImpl::size_request (Requisition &requisition) { requisition.width = 320; requisition.height = 200; } void DrawableImpl::size_allocate (Allocation area, bool changed) { if (false) // clear out, can lead to flicker { pixbuf_ = Pixbuf(); x_ = 0; y_ = 0; } sig_redraw.emit (area.x, area.y, area.width, area.height); } void DrawableImpl::draw_rect (int x, int y, const Pixbuf &pixbuf) { const Allocation &area = allocation(); const size_t rowstride = pixbuf.width(); if (x >= area.x && y >= area.y && x + pixbuf.width() <= area.x + area.width && y + pixbuf.height() <= area.y + area.height && rowstride * pixbuf.height() <= pixbuf.pixels.size()) { x_ = x; y_ = y; pixbuf_ = pixbuf; } else if (pixbuf_.width() > 0) { pixbuf_ = Pixbuf(); x_ = 0; y_ = 0; } invalidate_content(); } void DrawableImpl::render (RenderContext &rcontext) { const uint size = 10; const Allocation &area = allocation(); cairo_t *cr = cairo_context (rcontext); // checkerboard pattern if (true) { cairo_save (cr); cairo_surface_t *ps = cairo_surface_create_similar (cairo_get_target (cr), CAIRO_CONTENT_COLOR, 2 * size, 2 * size); cairo_t *pc = cairo_create (ps); cairo_set_source_rgb (pc, 1.0, 1.0, 1.0); cairo_rectangle (pc, 0, 0, size, size); cairo_rectangle (pc, size, size, size, size); cairo_fill (pc); cairo_set_source_rgb (pc, 0.9, 0.9, 0.9); cairo_rectangle (pc, 0, size, size, size); cairo_rectangle (pc, size, 0, size, size); cairo_fill (pc); cairo_destroy (pc); cairo_pattern_t *pat = cairo_pattern_create_for_surface (ps); cairo_surface_destroy (ps); cairo_pattern_set_extend (pat, CAIRO_EXTEND_REPEAT); // render pattern cairo_rectangle (cr, area.x, area.y, area.width, area.height); cairo_clip (cr); cairo_translate (cr, area.x, area.y + area.height); cairo_set_source (cr, pat); cairo_paint (cr); cairo_pattern_destroy (pat); cairo_restore (cr); } // handle user draw if (pixbuf_.width() > 0 && pixbuf_.height() > 0) { const int rowstride = pixbuf_.width(); cairo_surface_t *surface = cairo_image_surface_create_for_data ((uint8*) pixbuf_.pixels.data(), CAIRO_FORMAT_ARGB32, pixbuf_.width(), pixbuf_.height(), rowstride * 4); CAIRO_CHECK_STATUS (cairo_surface_status (surface)); cairo_set_source_surface (cr, surface, x_, y_); cairo_paint (cr); cairo_surface_destroy (surface); } } static const WidgetFactory<DrawableImpl> drawable_factory ("Rapicorn::Drawable"); } // Rapicorn <|endoftext|>
<commit_before>#include <stdio.h> #include <stdlib.h> #include <string.h> #include <signal.h> #include <iostream> #include <sys/stat.h> #include <sys/types.h> #include <sys/time.h> #include <unistd.h> #include <errno.h> #include <fcntl.h> #include <syslog.h> #include <QtCore> #include <QFile> #include <QString> #include "server/websocketserver.h" #include "prepare_tmp_deb_package.h" int main(int argc, char** argv) { QCoreApplication a(argc, argv); QCommandLineParser parser; parser.setApplicationDescription("freehackquest-backend"); parser.addHelpOption(); QCommandLineOption versionOption(QStringList() << "v" << "version", QCoreApplication::translate("main", "Version")); parser.addOption(versionOption); QCommandLineOption prepareDebOption(QStringList() << "pd" << "prepare-deb", QCoreApplication::translate("main", "Prepare Deb Package")); parser.addOption(prepareDebOption); parser.process(a); bool version = parser.isSet(versionOption); if(version){ std::cout << PrepareTmpDebPackage::version().toStdString() << "\n"; return 0; } bool prepare_deb = parser.isSet(prepareDebOption); if(prepare_deb){ PrepareTmpDebPackage::prepare("","tmpdeb"); return 0; } if(!QFile::exists("/etc/freehackquest-backend/conf.ini")){ qDebug() << "Not found /etc/freehackquest-backend/conf.ini"; return 0; } QThreadPool::globalInstance()->setMaxThreadCount(5); WebSocketServer *pServer = new WebSocketServer(); QObject::connect(pServer, &WebSocketServer::closed, &a, &QCoreApplication::quit); // TODO redesign to check config QSqlDatabase *db = pServer->database(); if (!db->open()){ return -1; } return a.exec(); } <commit_msg>Fixed compile error<commit_after>#include <stdio.h> #include <stdlib.h> #include <string.h> #include <signal.h> #include <iostream> #include <sys/stat.h> #include <sys/types.h> #include <sys/time.h> #include <unistd.h> #include <errno.h> #include <fcntl.h> #include <syslog.h> #include <QtCore> #include <QFile> #include <QString> #include <websocketserver.h> #include "prepare_tmp_deb_package.h" int main(int argc, char** argv) { QCoreApplication a(argc, argv); QCommandLineParser parser; parser.setApplicationDescription("freehackquest-backend"); parser.addHelpOption(); QCommandLineOption versionOption(QStringList() << "v" << "version", QCoreApplication::translate("main", "Version")); parser.addOption(versionOption); QCommandLineOption prepareDebOption(QStringList() << "pd" << "prepare-deb", QCoreApplication::translate("main", "Prepare Deb Package")); parser.addOption(prepareDebOption); parser.process(a); bool version = parser.isSet(versionOption); if(version){ std::cout << PrepareTmpDebPackage::version().toStdString() << "\n"; return 0; } bool prepare_deb = parser.isSet(prepareDebOption); if(prepare_deb){ PrepareTmpDebPackage::prepare("","tmpdeb"); return 0; } if(!QFile::exists("/etc/freehackquest-backend/conf.ini")){ qDebug() << "Not found /etc/freehackquest-backend/conf.ini"; return 0; } QThreadPool::globalInstance()->setMaxThreadCount(5); WebSocketServer *pServer = new WebSocketServer(); QObject::connect(pServer, &WebSocketServer::closed, &a, &QCoreApplication::quit); // TODO redesign to check config QSqlDatabase *db = pServer->database(); if (!db->open()){ return -1; } return a.exec(); } <|endoftext|>
<commit_before>#include "mainwindow.h" #include <QApplication> #include <QSplashScreen> #include <QTimer> #define SPLASH int main(int argc, char *argv[]) { QApplication a(argc, argv); #ifdef SPLASH QImage img(":/icons/splashscreen.png"); QPixmap pixmap = QPixmap::fromImage(img); QSplashScreen splash(pixmap, Qt::WindowStaysOnTopHint); splash.show(); a.processEvents(); #endif MainWindow w; #ifdef SPLASH w.hide(); QTimer::singleShot(2500, &splash, SLOT(close())); QTimer::singleShot(1500, &w, SLOT(unhide())); #else w.show(); #endif return a.exec(); } <commit_msg>Splashscreen: Faster unhidding of main window.<commit_after>#include "mainwindow.h" #include <QApplication> #include <QSplashScreen> #include <QTimer> #define SPLASH int main(int argc, char *argv[]) { QApplication a(argc, argv); #ifdef SPLASH QImage img(":/icons/splashscreen.png"); QPixmap pixmap = QPixmap::fromImage(img); QSplashScreen splash(pixmap, Qt::WindowStaysOnTopHint); splash.show(); a.processEvents(); #endif MainWindow w; #ifdef SPLASH w.hide(); QTimer::singleShot(2500, &splash, SLOT(close())); QTimer::singleShot(500, &w, SLOT(unhide())); #else w.show(); #endif return a.exec(); } <|endoftext|>
<commit_before>/* * Copyright (C) 2003 Hans Karlsson <[email protected]> * Copyright (C) 2003-2004 Adam Geitgey <[email protected]> * Copyright (c) 2005 Ryan Nickell <[email protected]> * * This file is part of SuperKaramba. * * SuperKaramba 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. * * SuperKaramba 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 SuperKaramba; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA ****************************************************************************/ #include "karambaapp.h" #include "karambasessionmanaged.h" #include "python/karamba.h" #include "config-superkaramba.h" #include <stdlib.h> #include <KLocale> #include <KConfig> #include <KDebug> #include <KStandardDirs> #include <KCmdLineArgs> #include <KAboutData> #include <KWindowSystem> #include <X11/extensions/Xrender.h> static const char *description = I18N_NOOP("A KDE Eye-candy Application"); static const char *version = "0.50"; int main(int argc, char **argv) { Display *dpy = XOpenDisplay(0); // open default display if (!dpy) { kWarning() << "Cannot connect to the X server"; exit(1); } Colormap colormap = 0; Visual *visual = 0; if (KWindowSystem::compositingActive()) { int screen = DefaultScreen(dpy); int eventBase, errorBase; if (XRenderQueryExtension(dpy, &eventBase, &errorBase)) { int nvi; XVisualInfo templ; templ.screen = screen; templ.depth = 32; templ.c_class = TrueColor; XVisualInfo *xvi = XGetVisualInfo(dpy, VisualScreenMask | VisualDepthMask | VisualClassMask, &templ, &nvi); for (int i = 0; i < nvi; ++i) { XRenderPictFormat *format = XRenderFindVisualFormat(dpy, xvi[i].visual); if (format->type == PictTypeDirect && format->direct.alphaMask) { visual = xvi[i].visual; colormap = XCreateColormap(dpy, RootWindow(dpy, screen), visual, AllocNone); break; } } } } KAboutData about("superkaramba", 0, ki18n("SuperKaramba"), version, ki18n(description), KAboutData::License_GPL, ki18n("(c) 2003-2007 The SuperKaramba developers")); about.addAuthor(ki18n("Adam Geitgey"), KLocalizedString(), "[email protected]"); about.addAuthor(ki18n("Hans Karlsson"), KLocalizedString(), "[email protected]"); about.addAuthor(ki18n("Ryan Nickell"), KLocalizedString(), "[email protected]"); about.addAuthor(ki18n("Petri Damstén"), KLocalizedString(), "[email protected]"); about.addAuthor(ki18n("Alexander Wiedenbruch"), KLocalizedString(), "[email protected]"); about.addAuthor(ki18n("Luke Kenneth Casson Leighton"), KLocalizedString(), "[email protected]"); about.addCredit(ki18n("Sebastian Sauer"), ki18n("Work on Kross, tutorials and examples"), "[email protected]"); KCmdLineArgs::init(argc, argv, &about); KCmdLineOptions options; // { "+[URL]", I18N_NOOP( "Document to open" ), 0 }, // { "!nosystray", I18N_NOOP("Disable systray icon"), 0 }, #ifdef PYTHON_INCLUDE_PATH options.add("usefallback", ki18n("Use the original python bindings as scripting backend. Off by default.")); #endif options.add("+file", ki18n("A required argument 'file'")); KCmdLineArgs::addCmdLineOptions(options); KarambaApplication::addCmdLineOptions(); KarambaSessionManaged ksm; if (!KarambaApplication::start()) { fprintf(stderr, "SuperKaramba is already running!\n"); exit(0); } #ifdef PYTHON_INCLUDE_PATH bool noUseKross = false; KCmdLineArgs *args = KCmdLineArgs::parsedArgs(); if (args->isSet("usefallback")) { noUseKross = true; kDebug() << "Using fallback python scripting backend!" ; } #endif KarambaApplication app(dpy, Qt::HANDLE(visual), Qt::HANDLE(colormap)); app.setupSysTray(&about); int ret = 0; #ifdef PYTHON_INCLUDE_PATH if (noUseKross) { KarambaPython::initPython(); } #endif ret = app.exec(); #ifdef PYTHON_INCLUDE_PATH if (noUseKross) { KarambaPython::shutdownPython(); } #endif return ret; } <commit_msg>Updating the version number and adding link to homepage on utils.kde.org<commit_after>/* * Copyright (C) 2003 Hans Karlsson <[email protected]> * Copyright (C) 2003-2004 Adam Geitgey <[email protected]> * Copyright (c) 2005 Ryan Nickell <[email protected]> * * This file is part of SuperKaramba. * * SuperKaramba 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. * * SuperKaramba 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 SuperKaramba; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA ****************************************************************************/ #include "karambaapp.h" #include "karambasessionmanaged.h" #include "python/karamba.h" #include "config-superkaramba.h" #include <stdlib.h> #include <KLocale> #include <KConfig> #include <KDebug> #include <KStandardDirs> #include <KCmdLineArgs> #include <KAboutData> #include <KWindowSystem> #include <X11/extensions/Xrender.h> static const char *description = I18N_NOOP("A KDE Eye-candy Application"); static const char *version = "0.52"; int main(int argc, char **argv) { Display *dpy = XOpenDisplay(0); // open default display if (!dpy) { kWarning() << "Cannot connect to the X server"; exit(1); } Colormap colormap = 0; Visual *visual = 0; if (KWindowSystem::compositingActive()) { int screen = DefaultScreen(dpy); int eventBase, errorBase; if (XRenderQueryExtension(dpy, &eventBase, &errorBase)) { int nvi; XVisualInfo templ; templ.screen = screen; templ.depth = 32; templ.c_class = TrueColor; XVisualInfo *xvi = XGetVisualInfo(dpy, VisualScreenMask | VisualDepthMask | VisualClassMask, &templ, &nvi); for (int i = 0; i < nvi; ++i) { XRenderPictFormat *format = XRenderFindVisualFormat(dpy, xvi[i].visual); if (format->type == PictTypeDirect && format->direct.alphaMask) { visual = xvi[i].visual; colormap = XCreateColormap(dpy, RootWindow(dpy, screen), visual, AllocNone); break; } } } } KAboutData about("superkaramba", 0, ki18n("SuperKaramba"), version, ki18n(description), KAboutData::License_GPL, ki18n("(c) 2003-2007 The SuperKaramba developers"), KLocalizedString(), "http://utils.kde.org/projects/superkaramba"); about.addAuthor(ki18n("Adam Geitgey"), KLocalizedString(), "[email protected]"); about.addAuthor(ki18n("Hans Karlsson"), KLocalizedString(), "[email protected]"); about.addAuthor(ki18n("Ryan Nickell"), KLocalizedString(), "[email protected]"); about.addAuthor(ki18n("Petri Damstén"), KLocalizedString(), "[email protected]"); about.addAuthor(ki18n("Alexander Wiedenbruch"), KLocalizedString(), "[email protected]"); about.addAuthor(ki18n("Luke Kenneth Casson Leighton"), KLocalizedString(), "[email protected]"); about.addCredit(ki18n("Sebastian Sauer"), ki18n("Work on Kross, tutorials and examples"), "[email protected]"); KCmdLineArgs::init(argc, argv, &about); KCmdLineOptions options; // { "+[URL]", I18N_NOOP( "Document to open" ), 0 }, // { "!nosystray", I18N_NOOP("Disable systray icon"), 0 }, #ifdef PYTHON_INCLUDE_PATH options.add("usefallback", ki18n("Use the original python bindings as scripting backend. Off by default.")); #endif options.add("+file", ki18n("A required argument 'file'")); KCmdLineArgs::addCmdLineOptions(options); KarambaApplication::addCmdLineOptions(); KarambaSessionManaged ksm; if (!KarambaApplication::start()) { fprintf(stderr, "SuperKaramba is already running!\n"); exit(0); } #ifdef PYTHON_INCLUDE_PATH bool noUseKross = false; KCmdLineArgs *args = KCmdLineArgs::parsedArgs(); if (args->isSet("usefallback")) { noUseKross = true; kDebug() << "Using fallback python scripting backend!" ; } #endif KarambaApplication app(dpy, Qt::HANDLE(visual), Qt::HANDLE(colormap)); app.setupSysTray(&about); int ret = 0; #ifdef PYTHON_INCLUDE_PATH if (noUseKross) { KarambaPython::initPython(); } #endif ret = app.exec(); #ifdef PYTHON_INCLUDE_PATH if (noUseKross) { KarambaPython::shutdownPython(); } #endif return ret; } <|endoftext|>
<commit_before>#include <AppConfig.h> // #include <modules/juce_audio_basics/juce_audio_basics.h> // #include <modules/juce_audio_devices/juce_audio_devices.h> // #include <modules/juce_audio_formats/juce_audio_formats.h> // #include <modules/juce_audio_processors/juce_audio_processors.h> #include <modules/juce_core/juce_core.h> // #include <modules/juce_cryptography/juce_cryptography.h> // #include <modules/juce_data_structures/juce_data_structures.h> // #include <modules/juce_events/juce_events.h> // #include <modules/juce_graphics/juce_graphics.h> #include <modules/juce_gui_basics/juce_gui_basics.h> // #include <modules/juce_gui_extra/juce_gui_extra.h> // #include <modules/juce_opengl/juce_opengl.h> // #include <modules/juce_video/juce_video.h> #include <base/base.hpp> using namespace juce; using namespace granite; namespace ProjectInfo { const char* const projectName = "Kiwano"; const char* const versionString = "0.1"; const int versionNumber = 0x10000; } class playlist : public Component, public FileDragAndDropTarget { struct playlistModel : public ListBoxModel { StringArray entries; int getNumRows() override { return entries.size(); } void paintListBoxItem(int rowNumber, Graphics& g, int width, int height, bool rowIsSelected) override { if (rowIsSelected) g.fillAll(Colours::lightblue); g.setColour(Colours::black); g.setFont(height * 0.7f); g.drawText(entries[rowNumber], 5, 0, width, height, Justification::centredLeft, true); } }; ListBox box; playlistModel model; JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(playlist); public: playlist() : box("playlist-box", nullptr) { setName("playlist"); box.setModel(&model); box.setMultipleSelectionEnabled(true); addAndMakeVisible(box); } void resized() override { box.setBounds(getLocalBounds().reduced(0)); } bool isInterestedInFileDrag(const StringArray& /*files*/) override { return true; } void fileDragEnter(const StringArray& /*files*/, int /*x*/, int /*y*/) override { repaint(); } void fileDragMove (const StringArray& /*files*/, int /*x*/, int /*y*/) override {} void fileDragExit (const StringArray& /*files*/) override { repaint(); } void filesDropped (const StringArray& files, int /*x*/, int /*y*/) override { model.entries.addArray(files); box.updateContent(); repaint(); } }; class tabs : public TabbedComponent { public: tabs() : TabbedComponent(TabbedButtonBar::TabsAtTop) { addTab("Menus", getRandomTabBackgroundColour(), new playlist(), true); addTab("Buttons", getRandomTabBackgroundColour(), new playlist(), true); } static Colour getRandomTabBackgroundColour() { return Colour(Random::getSystemRandom().nextFloat(), 0.1f, 0.97f, 1.0f); } }; class layout : public Component { StretchableLayoutManager l; StretchableLayoutResizerBar rb; std::vector<Component *> components; public: layout(Component *c1, Component *c2) : rb(&l, 1, false) { setOpaque(true); addAndMakeVisible(rb); addAndMakeVisible(c1); addAndMakeVisible(c2); components.push_back(c1); components.push_back(&rb); components.push_back(c2); components.push_back(nullptr); l.setItemLayout(0, -0.1, -0.9, -0.5); l.setItemLayout(1, 5, 5, 5); l.setItemLayout(2, -0.1, -0.9, -0.5); } void paint(Graphics &g) override { g.setColour(Colour::greyLevel(0.2f)); g.fillAll(); } void resized() { Rectangle<int> r(getLocalBounds().reduced(4)); l.layOutComponents(components.data(), 3, r.getX(), r.getY(), r.getWidth(), r.getHeight(), true, true); } }; class KiwanoApplication : public JUCEApplication { class MainWindow : public DocumentWindow { layout l; JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(MainWindow) public: MainWindow(String name) : DocumentWindow(name, Colours::lightgrey, DocumentWindow::allButtons), l(new tabs(), new tabs()) { setContentOwned(&l, false); setSize(800, 600); setVisible(true); setUsingNativeTitleBar(true); setResizable(true, true); } void closeButtonPressed() override { JUCEApplication::getInstance()->systemRequestedQuit(); } }; ScopedPointer<MainWindow> mainWindow; public: KiwanoApplication() {} const String getApplicationName() override { return ProjectInfo::projectName; } const String getApplicationVersion() override { return ProjectInfo::versionString; } bool moreThanOneInstanceAllowed() override { return false; } void initialise(const String& commandLine) override { mainWindow = new MainWindow(getApplicationName()); } void shutdown() override { mainWindow = nullptr; } void systemRequestedQuit() override { quit(); } void anotherInstanceStarted (const String& commandLine) override { } }; START_JUCE_APPLICATION(KiwanoApplication) <commit_msg>+ GLISP integration<commit_after>#include <AppConfig.h> // #include <modules/juce_audio_basics/juce_audio_basics.h> // #include <modules/juce_audio_devices/juce_audio_devices.h> // #include <modules/juce_audio_formats/juce_audio_formats.h> // #include <modules/juce_audio_processors/juce_audio_processors.h> #include <modules/juce_core/juce_core.h> // #include <modules/juce_cryptography/juce_cryptography.h> // #include <modules/juce_data_structures/juce_data_structures.h> // #include <modules/juce_events/juce_events.h> // #include <modules/juce_graphics/juce_graphics.h> #include <modules/juce_gui_basics/juce_gui_basics.h> // #include <modules/juce_gui_extra/juce_gui_extra.h> // #include <modules/juce_opengl/juce_opengl.h> // #include <modules/juce_video/juce_video.h> #include <base/base.hpp> #include <memory> using namespace juce; using namespace granite; namespace ProjectInfo { const char* const projectName = "Kiwano"; const char* const versionString = "0.1"; const int versionNumber = 0x10000; } class playlist : public Component, public FileDragAndDropTarget { struct playlistModel : public ListBoxModel { StringArray entries; int getNumRows() override { return entries.size(); } void paintListBoxItem(int rowNumber, Graphics& g, int width, int height, bool rowIsSelected) override { if (rowIsSelected) g.fillAll(Colours::lightblue); g.setColour(Colours::black); g.setFont(height * 0.7f); g.drawText(entries[rowNumber], 5, 0, width, height, Justification::centredLeft, true); } }; ListBox box; playlistModel model; JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(playlist); public: playlist() : box("playlist-box", nullptr) { setName("playlist"); box.setModel(&model); box.setMultipleSelectionEnabled(true); addAndMakeVisible(box); } void resized() override { box.setBounds(getLocalBounds().reduced(0)); } bool isInterestedInFileDrag(const StringArray& /*files*/) override { return true; } void fileDragEnter(const StringArray& /*files*/, int /*x*/, int /*y*/) override { repaint(); } void fileDragMove (const StringArray& /*files*/, int /*x*/, int /*y*/) override {} void fileDragExit (const StringArray& /*files*/) override { repaint(); } void filesDropped (const StringArray& files, int /*x*/, int /*y*/) override { model.entries.addArray(files); box.updateContent(); repaint(); } }; class tabs : public TabbedComponent { public: tabs() : TabbedComponent(TabbedButtonBar::TabsAtTop) { addTab("Menus", getRandomTabBackgroundColour(), new playlist(), true); addTab("Buttons", getRandomTabBackgroundColour(), new playlist(), true); } static Colour getRandomTabBackgroundColour() { return Colour(Random::getSystemRandom().nextFloat(), 0.1f, 0.97f, 1.0f); } }; class layout : public Component { StretchableLayoutManager l; std::vector<std::unique_ptr<Component>> components; std::vector<Component*> lc; bool horizontal; public: layout(bool _horizontal) : horizontal(_horizontal){ setOpaque(true); } void paint(Graphics &g) override { g.setColour(Colour::greyLevel(0.2f)); g.fillAll(); } void resized() override { juce::Rectangle<int> r(getLocalBounds()); l.layOutComponents(lc.data(), lc.size(), r.getX(), r.getY(), r.getWidth(), r.getHeight(), !horizontal, true); } void addSplitter() { if (lc.size() > 0) { l.setItemLayout(lc.size(), 5, 5, 5); components.push_back(std::make_unique<StretchableLayoutResizerBar>(&l, lc.size(), horizontal)); lc.push_back(components.back().get()); addAndMakeVisible(components.back().get()); } } void addComponent(Component *c, double minimum, double maximum, double preferred) { l.setItemLayout(lc.size(), minimum, maximum, preferred); lc.push_back(c); addAndMakeVisible(c); } }; class interpreter : public Component, public TextEditor::Listener { base::lisp &gl; TextEditor te; public: interpreter(base::lisp &glisp) : gl(glisp) { te.setMultiLine(true); te.setReturnKeyStartsNewLine(false); te.setTabKeyUsedAsCharacter(false); te.setReadOnly(false); te.setCaretVisible(true); te.addListener(this); addAndMakeVisible(te); } ~interpreter() {} void resized() override { te.setBounds(getLocalBounds()); } void textEditorTextChanged(TextEditor&) override {} void textEditorEscapeKeyPressed(TextEditor&) override {} void textEditorFocusLost(TextEditor&) override {} void textEditorReturnKeyPressed(TextEditor&) override { // get line te.moveCaretToStartOfLine(false); int begin = te.getCaretPosition(); te.moveCaretToEndOfLine(false); String t = te.getTextInRange(Range<int>(begin, te.getCaretPosition())); // execute code and print result std::string r = gl.eval(t.toStdString()); te.insertTextAtCaret("\n > "); te.insertTextAtCaret(r); te.insertTextAtCaret("\n"); } }; class user_interface : public Component { std::map<std::string, std::unique_ptr<Component>> components; Component *mainComponent; base::lisp &gl; public: user_interface(base::lisp &glisp) : mainComponent(nullptr), gl(glisp) {} ~user_interface() {} void resized() override { if (mainComponent) mainComponent->setBounds(getLocalBounds()); } // (set-main-component name) base::cell_t set_main_component(base::cell_t c, base::cells_t &ret) { const auto &name = c + 1; auto cc = components.find(name->s); if (cc != components.end()) { mainComponent = cc->second.get(); addAndMakeVisible(mainComponent); mainComponent->setBounds(getLocalBounds()); } return c; } // (refresh-interface) base::cell_t refresh_interface(base::cell_t c, base::cells_t &ret) { if (mainComponent) mainComponent->resized(); return c; } // (create-playlist name) base::cell_t create_playlist(base::cell_t c, base::cells_t &ret) { // TODO: error reporting const auto &name = c + 1; if (components.find(name->s) == components.end()) { components.insert(std::make_pair(name->s, std::make_unique<playlist>())); } return c; } // (create-layout name (bool)horizontal (bool)splitter) base::cell_t create_layout(base::cell_t c, base::cells_t &ret) { const auto &name = c + 1; const auto &horizontal = c + 2; if (components.find(name->s) == components.end()) { components.insert(std::make_pair(name->s, std::make_unique<layout>(horizontal->s != "nil"))); } return c; // TODO: returning quoted ID } // (create-interpreter name) base::cell_t create_interpreter(base::cell_t c, base::cells_t &ret) { const auto &name = c + 1; if (components.find(name->s) == components.end()) { components.insert(std::make_pair(name->s, std::make_unique<interpreter>(gl))); } return c; } // (layout-add-component layout-id component-id (float)min (float)max (float)preffered) base::cell_t layout_add_component(base::cell_t c, base::cells_t &ret) { // TODO: expected format: list of 5, id, id, float, float, float const auto &lname = c + 1; const auto &cname = c + 2; auto l = components.find(lname->s); auto com = components.find(cname->s); if (l != components.end() && com != components.end()) { const auto &minimum = c + 3; const auto &maximum = c + 4; const auto &preferred = c + 5; layout *lay = reinterpret_cast<layout*>(l->second.get()); lay->addComponent(com->second.get(), (double)minimum->f, (double)maximum->f, (double)preferred->f); } return c; } // (layout-add-splitter layout-id) base::cell_t layout_add_splitter(base::cell_t c, base::cells_t &ret) { const auto &lname = c + 1; auto l = components.find(lname->s); if (l != components.end()) { layout *lay = reinterpret_cast<layout*>(l->second.get()); lay->addSplitter(); } return c; } }; class KiwanoApplication : public JUCEApplication { class MainWindow : public DocumentWindow { user_interface itf; base::lisp gl; JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(MainWindow) public: MainWindow(String name) : DocumentWindow(name, Colours::lightgrey, DocumentWindow::allButtons), itf(gl) { setContentOwned(&itf, false); setSize(800, 600); setTopLeftPosition(200, 200); setVisible(true); setUsingNativeTitleBar(true); setResizable(true, true); // initialize GLISP using namespace std::placeholders; gl.init(); gl.addProcedure("create-playlist", std::bind(&user_interface::create_playlist, &itf, _1, _2)); gl.addProcedure("create-layout", std::bind(&user_interface::create_layout, &itf, _1, _2)); gl.addProcedure("layout-add-component", std::bind(&user_interface::layout_add_component, &itf, _1, _2)); gl.addProcedure("layout-add-splitter", std::bind(&user_interface::layout_add_splitter, &itf, _1, _2)); gl.addProcedure("set-main-component", std::bind(&user_interface::set_main_component, &itf, _1, _2)); gl.addProcedure("create-interpreter", std::bind(&user_interface::create_interpreter, &itf, _1, _2)); gl.addProcedure("refresh-interface", std::bind(&user_interface::refresh_interface, &itf, _1, _2)); gl.eval("(create-playlist 'p1)"); gl.eval("(create-playlist 'p2)"); gl.eval("(create-layout 'l1 t)"); gl.eval("(layout-add-component 'l1 'p1 -0.1 -0.9 -0.5)"); gl.eval("(layout-add-splitter 'l1)"); gl.eval("(layout-add-component 'l1 'p2 -0.1 -0.9 -0.5)"); gl.eval("(create-layout 'l2 nil)"); gl.eval("(create-interpreter 'int1)"); gl.eval("(layout-add-component 'l2 'int1 50.0 100.0 50.0)"); gl.eval("(layout-add-splitter 'l2)"); gl.eval("(layout-add-component 'l2 'l1 -0.1 -1.0 -0.9)"); gl.eval("(set-main-component 'l2)"); } void closeButtonPressed() override { gl.close(); JUCEApplication::getInstance()->systemRequestedQuit(); } }; ScopedPointer<MainWindow> mainWindow; public: KiwanoApplication() {} const String getApplicationName() override { return ProjectInfo::projectName; } const String getApplicationVersion() override { return ProjectInfo::versionString; } bool moreThanOneInstanceAllowed() override { return false; } void initialise(const String& commandLine) override { mainWindow = new MainWindow(getApplicationName()); } void shutdown() override { mainWindow = nullptr; } void systemRequestedQuit() override { quit(); } void anotherInstanceStarted (const String& commandLine) override { } }; START_JUCE_APPLICATION(KiwanoApplication) <|endoftext|>
<commit_before>/****************************************************************************** * Fake Frog * * An Arduino-based project to build a frog-shaped temperature logger. * * Author: David Lougheed. Copyright 2017. * ******************************************************************************/ #define VERSION "0.1.0" // Includes #include <Arduino.h> #include <Wire.h> #include <LiquidCrystal.h> #include <SD.h> #include <RTClib.h> // Compile-Time Settings #define SERIAL_LOGGING true // Log to the serial display for debug. #define FILE_LOGGING true // Log to file on SD card. (recommended) #define DISPLAY_ENABLED true // Show menus and information on an LCD. #define NUM_SAMPLES 10 // Samples get averaged to reduce noise. #define SAMPLE_DELAY 10 // Milliseconds between samples. #define READING_INTERVAL 60 // Seconds between readings. // Hardware Settings // - The data logging shield uses A4, A5, and digital pins 10, 11, 12, and 13. #define NUM_THERMISTORS 4 #define THERMISTOR_1_PIN 0 // Analog pin #define THERMISTOR_2_PIN 1 // Analog pin #define THERMISTOR_3_PIN 2 // Analog pin #define THERMISTOR_4_PIN 3 // Analog pin const uint8_t thermistor_pins[NUM_THERMISTORS] = { THERMISTOR_1_PIN, THERMISTOR_2_PIN, THERMISTOR_3_PIN, THERMISTOR_4_PIN }; #define THERMISTOR_SERIES_RES 10000 #define THERMISTOR_RES_NOM 10000 // Nominal resistance, R0. #define THERMISTOR_B_COEFF 3950 // Beta coefficient of the thermistor. #define THERMISTOR_TEMP_NOM 25 // Nominal temperature of R0. #define BUTTON_1_PIN 2 #define BUTTON_2_PIN 3 #define SD_CARD_PIN 10 #define RTC_PIN_1 A4 // Analog pin #define RTC_PIN_2 A5 // Analog pin #define LCD_PIN_RS 4 #define LCD_PIN_EN 5 #define LCD_PIN_DB4 6 #define LCD_PIN_DB5 7 #define LCD_PIN_DB6 8 #define LCD_PIN_DB7 9 #define LCD_ROWS 2 #define LCD_COLUMNS 16 #define RTC_TYPE RTC_PCF8523 // Other Compile-Time Constants #define MAX_LOG_FILES 1000 #define MAX_DATA_FILES 1000 // Globals bool serial_logging_started = false; // - Files File log_file; File data_file; // - Hardware Objects RTC_TYPE rtc; LiquidCrystal* lcd; // - Data Point Variables // (to save memory, use global data point variables) DateTime now; char formatted_timestamp[] = "0000-00-00T00:00:00"; char* data_file_entry_buffer = (char*) malloc(sizeof(char) * 50); char temperature_string[4][8]; double latest_resistance[4]; double latest_temperature[4]; /* DISPLAY MODES (ALL WITH LOGGING) 0: Idle 1: Information (RAM free) 2: RTC Editor */ uint8_t display_mode = 0; uint16_t i, z; // 16-bit iterator uint8_t timer = 0; // Counts seconds uint32_t milli_timer = 0; // Counts time taken to do a loop uint32_t uptime = 0; uint8_t cursor = 0; // Maximum: 31 (second row, last column) bool button_1 = false; bool button_2 = false; // Utility Methods // Determine amount of free RAM. // - Retrieved 2017-05-19 (https://playground.arduino.cc/Code/AvailableMemory) int freeRAM() { extern int __heap_start, *__brkval; int v; return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval); } // Log a generic message. void log(const char* msg, bool with_newline = true) { if (SERIAL_LOGGING) { if(!serial_logging_started) { Serial.begin(9600); Serial.println(); serial_logging_started = true; } if (with_newline) { Serial.println(msg); } else { Serial.print(msg); } } if (FILE_LOGGING) { if (log_file) { if (with_newline) { log_file.println(msg); } else { log_file.print(msg); } } } } // Flush various logging buffers. void log_flush() { if (SERIAL_LOGGING) { Serial.flush(); } if (FILE_LOGGING) { log_file.flush(); } } // Log an error message. Uses standard log method, then hangs forever. void log_error(const char* msg, bool with_newline = true) { log(msg, with_newline); log_flush(); while (true); // Loop forever } // Update the LCD to display latest values for the set display mode. void update_display() { if (DISPLAY_ENABLED && lcd) { lcd->clear(); cursor = 0; switch (display_mode) { case 1: // Information lcd->print("Free RAM: "); lcd->print(freeRAM(), 10); lcd->noBlink(); break; case 2: // RTC Editor lcd->print("TBD"); lcd->setCursor(0, 0); lcd->blink(); break; case 0: // Idle default: lcd->noBlink(); break; } } } // Switch the display mode, triggering a display update. void switch_display_mode(uint8_t m) { display_mode = m % 3; update_display(); } // Data Methods // Update the global formatted timestamp string with the contents of 'now'. void update_formatted_timestamp() { sprintf(formatted_timestamp, "%04u-%02u-%02uT%02u:%02u:%02u", now.year(), now.month(), now.day(), now.hour(), now.minute(), now.second()); } double resistance_to_temperature(double resistance) { // Formula: T = 1/(1/B * ln(R/R_0) + (1/T0)) - 273.15 (celcius) return 1 / ((log(resistance / THERMISTOR_RES_NOM) / THERMISTOR_B_COEFF) + 1 / (THERMISTOR_TEMP_NOM + 273.15)) - 273.15; } void take_reading(uint8_t t) { now = rtc.now(); latest_resistance[t] = 0; for (i = 0; i < NUM_SAMPLES; i++) { latest_resistance[t] += (double) analogRead(thermistor_pins[t]); delay(SAMPLE_DELAY); } // Formulas: R = sr / (1023 / mean_of_samples - 1) // sr = thermistor series resistance latest_resistance[t] = THERMISTOR_SERIES_RES / (1023 / (latest_resistance[t] / NUM_SAMPLES) - 1); // Resistance latest_temperature[t] = resistance_to_temperature(latest_resistance[t]); // TODO: Error calculations } void save_reading_to_card() { if (data_file) { update_formatted_timestamp(); for (i = 0; i < NUM_THERMISTORS; i++) { dtostrf(latest_temperature[i], 5, 2, temperature_string[i]); } log("Took reading: ", false); log(formatted_timestamp, false); log(",", false); log(temperature_string[0], false); log(",", false); log(temperature_string[1], false); log(",", false); log(temperature_string[2], false); log(",", false); log(temperature_string[3]); log_flush(); data_file.print(formatted_timestamp); data_file.print(","); data_file.print(temperature_string[0]); data_file.print(","); data_file.print(temperature_string[1]); data_file.print(","); data_file.print(temperature_string[2]); data_file.print(","); data_file.println(temperature_string[3]); // data_file.println(data_file_entry_buffer); data_file.flush(); } } // Main Methods void setup() { // SET UP EXTERNAL ANALOG VOLTAGE REFERENCE // Typically from 3.3V Arduino supply. This reduces the voltage noise seen // from reading analog values. analogReference(EXTERNAL); // INITIALIZE SD CARD log("Initializing SD card... ", false); pinMode(SD_CARD_PIN, OUTPUT); if (!SD.begin()) { log_error("Failed."); } log("Done."); // SET UP LOG FILE if (FILE_LOGGING) { log("Creating log file... ", false); char log_file_name[] = "log_000.txt"; for (i = 0; i < MAX_LOG_FILES; i++) { // Increment until we can find a log file slot. // Need to add 48 to get ASCII number characters. log_file_name[4] = i / 100 + 48; log_file_name[5] = i / 10 % 10 + 48; log_file_name[6] = i % 10 + 48; if (!SD.exists(log_file_name)) { log_file = SD.open(log_file_name, FILE_WRITE); break; } } if (log_file) { log("Done."); } else { log_error("Failed."); } } // SET UP RTC log("Initializing RTC... ", false); Wire.begin(); if (!rtc.begin()) { log_error("Failed."); } log("Done."); // INPUT RTC TIME if (SERIAL_LOGGING) { uint16_t year; uint8_t month, day, hour, minute, second; Serial.print("Change clock? (y/n) "); while (Serial.available() < 1); Serial.println(); if (Serial.read() == 'y') { Serial.println(); Serial.print("Enter Year: "); while (Serial.available() < 4); year += (Serial.read() - 48) * 1000; year += (Serial.read() - 48) * 100; year += (Serial.read() - 48) * 10; year += (Serial.read() - 48); Serial.println(year); Serial.print("Enter Month: "); while (Serial.available() < 2); month += (Serial.read() - 48) * 10; month += (Serial.read() - 48); Serial.println(month); Serial.print("Enter Day: "); while (Serial.available() < 2); day += (Serial.read() - 48) * 10; day += (Serial.read() - 48); Serial.println(day); Serial.print("Enter Hour: "); while (Serial.available() < 2); hour += (Serial.read() - 48) * 10; hour += (Serial.read() - 48); Serial.println(hour); Serial.print("Enter Minute: "); while (Serial.available() < 2); minute += (Serial.read() - 48) * 10; minute += (Serial.read() - 48); Serial.println(minute); Serial.print("Enter Second: "); while (Serial.available() < 2); second += (Serial.read() - 48) * 10; second += (Serial.read() - 48); Serial.println(second); rtc.adjust(DateTime(year, month, day, hour, minute, second)); } } // SET UP DATA FILE log("Creating data file... ", false); char data_file_name[] = "dat_000.csv"; for (i = 0; i < MAX_DATA_FILES; i++) { // Increment until we can find a data file slot. // Need to add 48 to get ASCII digit characters. data_file_name[4] = i / 100 + 48; data_file_name[5] = i / 10 % 10 + 48; data_file_name[6] = i % 10 + 48; if (!SD.exists(data_file_name)) { data_file = SD.open(data_file_name, FILE_WRITE); break; } } if (data_file) { log("Done."); } else { log_error("Failed."); } // PRINT DATA FILE CSV HEADERS data_file.println("Timestamp,Temp1,Temp2,Temp3,Temp4"); data_file.flush(); // SET UP LCD if (DISPLAY_ENABLED) { lcd = new LiquidCrystal(LCD_PIN_RS, LCD_PIN_EN, LCD_PIN_DB4, LCD_PIN_DB5, LCD_PIN_DB6, LCD_PIN_DB7); lcd->begin(LCD_COLUMNS, LCD_ROWS); update_display(); } // SET UP BUTTONS pinMode(BUTTON_1_PIN, INPUT); pinMode(BUTTON_2_PIN, INPUT); // Finished everything! now = rtc.now(); update_formatted_timestamp(); log("Data logger started at ", false); log(formatted_timestamp, false); log(". Software version: ", false); log(VERSION); log_flush(); } void loop() { // Time the loop to make sure it runs rounded to the nearest second. milli_timer = millis(); if (timer >= READING_INTERVAL) { timer = 0; for (z = 0; z < NUM_THERMISTORS; z++) { // Loop through all thermistors take_reading(z); } save_reading_to_card(); } button_1 = digitalRead(BUTTON_1_PIN); button_2 = digitalRead(BUTTON_2_PIN); if (button_1 && button_2) { switch_display_mode(++display_mode); } else if (button_1) { } else if (button_2) { cursor = (cursor + 1) % 32; lcd->setCursor(cursor % 16, cursor > 15 ? 1 : 0); } milli_timer = millis() - milli_timer; while (milli_timer >= 1000) { // Prevent an integer overflow error by making sure milli_timer < 1000 timer++; // An extra second has occurred - don't let it slip away! milli_timer -= 1000; } timer++; uptime++; delay(1000 - milli_timer); // (Ideally) 1 second between loops } <commit_msg>Remove vestiges of sprintf method of data file output.<commit_after>/****************************************************************************** * Fake Frog * * An Arduino-based project to build a frog-shaped temperature logger. * * Author: David Lougheed. Copyright 2017. * ******************************************************************************/ #define VERSION "0.1.0" // Includes #include <Arduino.h> #include <Wire.h> #include <LiquidCrystal.h> #include <SD.h> #include <RTClib.h> // Compile-Time Settings #define SERIAL_LOGGING true // Log to the serial display for debug. #define FILE_LOGGING true // Log to file on SD card. (recommended) #define DISPLAY_ENABLED true // Show menus and information on an LCD. #define NUM_SAMPLES 10 // Samples get averaged to reduce noise. #define SAMPLE_DELAY 10 // Milliseconds between samples. #define READING_INTERVAL 60 // Seconds between readings. // Hardware Settings // - The data logging shield uses A4, A5, and digital pins 10, 11, 12, and 13. #define NUM_THERMISTORS 4 #define THERMISTOR_1_PIN 0 // Analog pin #define THERMISTOR_2_PIN 1 // Analog pin #define THERMISTOR_3_PIN 2 // Analog pin #define THERMISTOR_4_PIN 3 // Analog pin const uint8_t thermistor_pins[NUM_THERMISTORS] = { THERMISTOR_1_PIN, THERMISTOR_2_PIN, THERMISTOR_3_PIN, THERMISTOR_4_PIN }; #define THERMISTOR_SERIES_RES 10000 #define THERMISTOR_RES_NOM 10000 // Nominal resistance, R0. #define THERMISTOR_B_COEFF 3950 // Beta coefficient of the thermistor. #define THERMISTOR_TEMP_NOM 25 // Nominal temperature of R0. #define BUTTON_1_PIN 2 #define BUTTON_2_PIN 3 #define SD_CARD_PIN 10 #define RTC_PIN_1 A4 // Analog pin #define RTC_PIN_2 A5 // Analog pin #define LCD_PIN_RS 4 #define LCD_PIN_EN 5 #define LCD_PIN_DB4 6 #define LCD_PIN_DB5 7 #define LCD_PIN_DB6 8 #define LCD_PIN_DB7 9 #define LCD_ROWS 2 #define LCD_COLUMNS 16 #define RTC_TYPE RTC_PCF8523 // Other Compile-Time Constants #define MAX_LOG_FILES 1000 #define MAX_DATA_FILES 1000 // Globals bool serial_logging_started = false; // - Files File log_file; File data_file; // - Hardware Objects RTC_TYPE rtc; LiquidCrystal* lcd; // - Data Point Variables // (to save memory, use global data point variables) DateTime now; char formatted_timestamp[] = "0000-00-00T00:00:00"; char temperature_string[4][8]; double latest_resistance[4]; double latest_temperature[4]; /* DISPLAY MODES (ALL WITH LOGGING) 0: Idle 1: Information (RAM free) 2: RTC Editor */ uint8_t display_mode = 0; uint16_t i, z; // 16-bit iterator uint8_t timer = 0; // Counts seconds uint32_t milli_timer = 0; // Counts time taken to do a loop uint32_t uptime = 0; uint8_t cursor = 0; // Maximum: 31 (second row, last column) bool button_1 = false; bool button_2 = false; // Utility Methods // Determine amount of free RAM. // - Retrieved 2017-05-19 (https://playground.arduino.cc/Code/AvailableMemory) int freeRAM() { extern int __heap_start, *__brkval; int v; return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval); } // Log a generic message. void log(const char* msg, bool with_newline = true) { if (SERIAL_LOGGING) { if(!serial_logging_started) { Serial.begin(9600); Serial.println(); serial_logging_started = true; } if (with_newline) { Serial.println(msg); } else { Serial.print(msg); } } if (FILE_LOGGING) { if (log_file) { if (with_newline) { log_file.println(msg); } else { log_file.print(msg); } } } } // Flush various logging buffers. void log_flush() { if (SERIAL_LOGGING) { Serial.flush(); } if (FILE_LOGGING) { log_file.flush(); } } // Log an error message. Uses standard log method, then hangs forever. void log_error(const char* msg, bool with_newline = true) { log(msg, with_newline); log_flush(); while (true); // Loop forever } // Update the LCD to display latest values for the set display mode. void update_display() { if (DISPLAY_ENABLED && lcd) { lcd->clear(); cursor = 0; switch (display_mode) { case 1: // Information lcd->print("Free RAM: "); lcd->print(freeRAM(), 10); lcd->noBlink(); break; case 2: // RTC Editor lcd->print("TBD"); lcd->setCursor(0, 0); lcd->blink(); break; case 0: // Idle default: lcd->noBlink(); break; } } } // Switch the display mode, triggering a display update. void switch_display_mode(uint8_t m) { display_mode = m % 3; update_display(); } // Data Methods // Update the global formatted timestamp string with the contents of 'now'. void update_formatted_timestamp() { sprintf(formatted_timestamp, "%04u-%02u-%02uT%02u:%02u:%02u", now.year(), now.month(), now.day(), now.hour(), now.minute(), now.second()); } double resistance_to_temperature(double resistance) { // Formula: T = 1/(1/B * ln(R/R_0) + (1/T0)) - 273.15 (celcius) return 1 / ((log(resistance / THERMISTOR_RES_NOM) / THERMISTOR_B_COEFF) + 1 / (THERMISTOR_TEMP_NOM + 273.15)) - 273.15; } void take_reading(uint8_t t) { now = rtc.now(); latest_resistance[t] = 0; for (i = 0; i < NUM_SAMPLES; i++) { latest_resistance[t] += (double) analogRead(thermistor_pins[t]); delay(SAMPLE_DELAY); } // Formulas: R = sr / (1023 / mean_of_samples - 1) // sr = thermistor series resistance latest_resistance[t] = THERMISTOR_SERIES_RES / (1023 / (latest_resistance[t] / NUM_SAMPLES) - 1); // Resistance latest_temperature[t] = resistance_to_temperature(latest_resistance[t]); // TODO: Error calculations } void save_reading_to_card() { if (data_file) { update_formatted_timestamp(); for (i = 0; i < NUM_THERMISTORS; i++) { dtostrf(latest_temperature[i], 5, 2, temperature_string[i]); } log("Took reading: ", false); log(formatted_timestamp, false); log(",", false); log(temperature_string[0], false); log(",", false); log(temperature_string[1], false); log(",", false); log(temperature_string[2], false); log(",", false); log(temperature_string[3]); log_flush(); data_file.print(formatted_timestamp); data_file.print(","); data_file.print(temperature_string[0]); data_file.print(","); data_file.print(temperature_string[1]); data_file.print(","); data_file.print(temperature_string[2]); data_file.print(","); data_file.println(temperature_string[3]); data_file.flush(); } } // Main Methods void setup() { // SET UP EXTERNAL ANALOG VOLTAGE REFERENCE // Typically from 3.3V Arduino supply. This reduces the voltage noise seen // from reading analog values. analogReference(EXTERNAL); // INITIALIZE SD CARD log("Initializing SD card... ", false); pinMode(SD_CARD_PIN, OUTPUT); if (!SD.begin()) { log_error("Failed."); } log("Done."); // SET UP LOG FILE if (FILE_LOGGING) { log("Creating log file... ", false); char log_file_name[] = "log_000.txt"; for (i = 0; i < MAX_LOG_FILES; i++) { // Increment until we can find a log file slot. // Need to add 48 to get ASCII number characters. log_file_name[4] = i / 100 + 48; log_file_name[5] = i / 10 % 10 + 48; log_file_name[6] = i % 10 + 48; if (!SD.exists(log_file_name)) { log_file = SD.open(log_file_name, FILE_WRITE); break; } } if (log_file) { log("Done."); } else { log_error("Failed."); } } // SET UP RTC log("Initializing RTC... ", false); Wire.begin(); if (!rtc.begin()) { log_error("Failed."); } log("Done."); // INPUT RTC TIME if (SERIAL_LOGGING) { uint16_t year; uint8_t month, day, hour, minute, second; Serial.print("Change clock? (y/n) "); while (Serial.available() < 1); Serial.println(); if (Serial.read() == 'y') { Serial.println(); Serial.print("Enter Year: "); while (Serial.available() < 4); year += (Serial.read() - 48) * 1000; year += (Serial.read() - 48) * 100; year += (Serial.read() - 48) * 10; year += (Serial.read() - 48); Serial.println(year); Serial.print("Enter Month: "); while (Serial.available() < 2); month += (Serial.read() - 48) * 10; month += (Serial.read() - 48); Serial.println(month); Serial.print("Enter Day: "); while (Serial.available() < 2); day += (Serial.read() - 48) * 10; day += (Serial.read() - 48); Serial.println(day); Serial.print("Enter Hour: "); while (Serial.available() < 2); hour += (Serial.read() - 48) * 10; hour += (Serial.read() - 48); Serial.println(hour); Serial.print("Enter Minute: "); while (Serial.available() < 2); minute += (Serial.read() - 48) * 10; minute += (Serial.read() - 48); Serial.println(minute); Serial.print("Enter Second: "); while (Serial.available() < 2); second += (Serial.read() - 48) * 10; second += (Serial.read() - 48); Serial.println(second); rtc.adjust(DateTime(year, month, day, hour, minute, second)); } } // SET UP DATA FILE log("Creating data file... ", false); char data_file_name[] = "dat_000.csv"; for (i = 0; i < MAX_DATA_FILES; i++) { // Increment until we can find a data file slot. // Need to add 48 to get ASCII digit characters. data_file_name[4] = i / 100 + 48; data_file_name[5] = i / 10 % 10 + 48; data_file_name[6] = i % 10 + 48; if (!SD.exists(data_file_name)) { data_file = SD.open(data_file_name, FILE_WRITE); break; } } if (data_file) { log("Done."); } else { log_error("Failed."); } // PRINT DATA FILE CSV HEADERS data_file.println("Timestamp,Temp1,Temp2,Temp3,Temp4"); data_file.flush(); // SET UP LCD if (DISPLAY_ENABLED) { lcd = new LiquidCrystal(LCD_PIN_RS, LCD_PIN_EN, LCD_PIN_DB4, LCD_PIN_DB5, LCD_PIN_DB6, LCD_PIN_DB7); lcd->begin(LCD_COLUMNS, LCD_ROWS); update_display(); } // SET UP BUTTONS pinMode(BUTTON_1_PIN, INPUT); pinMode(BUTTON_2_PIN, INPUT); // Finished everything! now = rtc.now(); update_formatted_timestamp(); log("Data logger started at ", false); log(formatted_timestamp, false); log(". Software version: ", false); log(VERSION); log_flush(); } void loop() { // Time the loop to make sure it runs rounded to the nearest second. milli_timer = millis(); if (timer >= READING_INTERVAL) { timer = 0; for (z = 0; z < NUM_THERMISTORS; z++) { // Loop through all thermistors take_reading(z); } save_reading_to_card(); } button_1 = digitalRead(BUTTON_1_PIN); button_2 = digitalRead(BUTTON_2_PIN); if (button_1 && button_2) { switch_display_mode(++display_mode); } else if (button_1) { } else if (button_2) { cursor = (cursor + 1) % 32; lcd->setCursor(cursor % 16, cursor > 15 ? 1 : 0); } milli_timer = millis() - milli_timer; while (milli_timer >= 1000) { // Prevent an integer overflow error by making sure milli_timer < 1000 timer++; // An extra second has occurred - don't let it slip away! milli_timer -= 1000; } timer++; uptime++; delay(1000 - milli_timer); // (Ideally) 1 second between loops } <|endoftext|>
<commit_before>// Copyright 2016 Ilya Albrekht // // 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 <stdio.h> #include <stdlib.h> #include <string.h> #include <err.h> #include <time.h> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <errno.h> #include <string> #include <iostream> #include <fstream> #include <sstream> #include <vector> #include <memory> #include "cal.h" #include "net.h" #include "channel.h" #include "gpio.h" #include "log.h" #include <signal.h> #include "ArduinoJson/ArduinoJson.hpp" /* #include <libical/ical.h> #include "libical/icalproperty_cxx.h" #include "libical/vcomponent_cxx.h" #include "libical/icalrecur.h" */ // Time after which to check if any of the valves are active (sec) #define CHECK_TIME 10 // Time to update calendar info from the internet (sec) #define UPDATE_TIME (60*60) //// TODO List // * Extract cal for a week using namespace std; using namespace LibICal; // Global variables int g_DebugLevel=6; std::vector<shared_ptr<channel_t>> valves; // Signal handlers void sighandler_stop(int id) { for(auto &v: valves) v.reset(); exit(0); } #define PIN_LED_ACTIVE 4 void ParseOptions(int argc, char* argv[]) { int i=1; for(; i<argc; i++) { if(strcmp("--debug", argv[i]) == 0) { g_DebugLevel = 7; DEBUG_PRINT(LOG_INFO, "Debug print enabled"); } // Run channel <CH> for <N> minutes // must be last one in the list if(strcmp("--run", argv[i]) == 0) { if( argc < i+2 ) { cerr << "Invalid number of arguments\n"; exit(-1); } int ch = atoi( argv[i+1] ); int t = atoi( argv[i+2] ); DEBUG_PRINT(LOG_INFO, "Start channel " << ch << " for " << t << " minutes" ); GpioRelay *R = new GpioRelay(ch); R->Start(); sleep(t*60); R->Stop(); delete R; exit(0); } } } int main(int argc, char* argv[]) { ParseOptions(argc, argv); // Register signals signal(SIGINT, sighandler_stop); signal(SIGKILL, sighandler_stop); signal(SIGTERM, sighandler_stop); // Load configuration and create { ifstream cf("config.json"); string config_str((std::istreambuf_iterator<char>(cf)), std::istreambuf_iterator<char>()); cf.close(); StaticJsonBuffer<512> jbuf; JsonObject& root = jbuf.parseObject(config_str); if(!root.success()) { DEBUG_PRINT(LOG_WARNING, "Error parsing config.json"); exit(-1); } int n_s = root["schedule"].size(); DEBUG_PRINT(LOG_INFO, "Loading schedule configuration (ch# " << n_s << ")" ); for(int i=0; i<n_s; ++i) { if(root["schedule"][i]["type"] == string("ical")) { DEBUG_PRINT(LOG_INFO, " - ical, gpio " << root["schedule"][i]["igpo"][0]); // Adding ical type schedule //cout << root["schedule"][i]["url"] << endl; string gpio_id = root["schedule"][i]["igpo"][0]; shared_ptr<channel_t> vt(new channel_t(root["schedule"][i]["url"],std::stoi(gpio_id)) ); //cout << "$ filename " << vt->get_cache_filename() << endl; if(!vt->load_cached(UPDATE_TIME)) { //cout << "Load from web\n"; vt->load_from_url(); } valves.push_back(vt); } } } time_t last_reload = time(0); //-2*UPDATE_TIME; // Hack to force the reload on the first iteration // Enter into work loop while(true) { bool to_reload; if( to_reload = (time(0) - last_reload) > UPDATE_TIME ) last_reload = time(0); for( auto &vt : valves) { if(to_reload) { int err; if(err=vt->load_from_url() !=NET_SUCCESS) { DEBUG_PRINT(LOG_INFO, "ERROR: Error loading ical" ); } } DEBUG_PRINT(LOG_INFO, "INFO: update status"); if(vt->vc.IsActive() != vt->gpio.GetStatus()) vt->gpio.SetStatus(vt->vc.IsActive()); } sleep(CHECK_TIME); } return 0; } <commit_msg>Help message added<commit_after>// Copyright 2016 Ilya Albrekht // // 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 <stdio.h> #include <stdlib.h> #include <string.h> #include <err.h> #include <time.h> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <errno.h> #include <string> #include <iostream> #include <fstream> #include <sstream> #include <vector> #include <memory> #include "cal.h" #include "net.h" #include "channel.h" #include "gpio.h" #include "log.h" #include <signal.h> #include "ArduinoJson/ArduinoJson.hpp" /* #include <libical/ical.h> #include "libical/icalproperty_cxx.h" #include "libical/vcomponent_cxx.h" #include "libical/icalrecur.h" */ // Time after which to check if any of the valves are active (sec) #define CHECK_TIME 10 // Time to update calendar info from the internet (sec) #define UPDATE_TIME (60*60) //// TODO List // * Extract cal for a week using namespace std; using namespace LibICal; // Global variables int g_DebugLevel=6; std::vector<shared_ptr<channel_t>> valves; // Signal handlers void sighandler_stop(int id) { for(auto &v: valves) v.reset(); exit(0); } #define PIN_LED_ACTIVE 4 void ParseOptions(int argc, char* argv[]) { int i=1; for(; i<argc; i++) { if( strcmp("--help", argv[i]) == 0 ) { printf("IoT scheduler by Ilya Albrekht\n"); printf(" --debug Enable debug level output\n"); printf(" --run <C> <N> Turn on channel C for N minutes\n"); printf(" --daemon -D Run as daemon\n"); exit(0); } } for(i=1; i<argc; i++) { if(strcmp("--debug", argv[i]) == 0) { g_DebugLevel = 7; DEBUG_PRINT(LOG_INFO, "Debug print enabled"); } // Run channel <CH> for <N> minutes // must be last one in the list if(strcmp("--run", argv[i]) == 0) { if( argc < i+2 ) { cerr << "Invalid number of arguments\n"; exit(-1); } int ch = atoi( argv[i+1] ); int t = atoi( argv[i+2] ); DEBUG_PRINT(LOG_INFO, "Start channel " << ch << " for " << t << " minutes" ); GpioRelay *R = new GpioRelay(ch); R->Start(); sleep(t*60); R->Stop(); delete R; exit(0); } } } int main(int argc, char* argv[]) { ParseOptions(argc, argv); // Register signals signal(SIGINT, sighandler_stop); signal(SIGKILL, sighandler_stop); signal(SIGTERM, sighandler_stop); // Load configuration and create { ifstream cf("config.json"); string config_str((std::istreambuf_iterator<char>(cf)), std::istreambuf_iterator<char>()); cf.close(); StaticJsonBuffer<512> jbuf; JsonObject& root = jbuf.parseObject(config_str); if(!root.success()) { DEBUG_PRINT(LOG_WARNING, "Error parsing config.json"); exit(-1); } int n_s = root["schedule"].size(); DEBUG_PRINT(LOG_INFO, "Loading schedule configuration (ch# " << n_s << ")" ); for(int i=0; i<n_s; ++i) { if(root["schedule"][i]["type"] == string("ical")) { DEBUG_PRINT(LOG_INFO, " - ical, gpio " << root["schedule"][i]["igpo"][0]); // Adding ical type schedule //cout << root["schedule"][i]["url"] << endl; string gpio_id = root["schedule"][i]["igpo"][0]; shared_ptr<channel_t> vt(new channel_t(root["schedule"][i]["url"],std::stoi(gpio_id)) ); //cout << "$ filename " << vt->get_cache_filename() << endl; if(!vt->load_cached(UPDATE_TIME)) { //cout << "Load from web\n"; vt->load_from_url(); } valves.push_back(vt); } } } time_t last_reload = time(0); //-2*UPDATE_TIME; // Hack to force the reload on the first iteration // Enter into work loop while(true) { bool to_reload; if( to_reload = (time(0) - last_reload) > UPDATE_TIME ) last_reload = time(0); for( auto &vt : valves) { if(to_reload) { int err; if(err=vt->load_from_url() !=NET_SUCCESS) { DEBUG_PRINT(LOG_INFO, "ERROR: Error loading ical" ); } } DEBUG_PRINT(LOG_INFO, "INFO: update status"); if(vt->vc.IsActive() != vt->gpio.GetStatus()) vt->gpio.SetStatus(vt->vc.IsActive()); } sleep(CHECK_TIME); } return 0; } <|endoftext|>
<commit_before> #include "Globals.h" // NOTE: MSVC stupidness requires this to be the same across all modules #include "Root.h" #include <exception> #include <csignal> #include <stdlib.h> #ifdef _MSC_VER #include <dbghelp.h> #endif // _MSC_VER #include "OSSupport/StackTrace.h" bool cRoot::m_TerminateEventRaised = false; // If something has told the server to stop; checked periodically in cRoot static bool g_ServerTerminated = false; // Set to true when the server terminates, so our CTRL handler can then tell the OS to close the console /** If set to true, the protocols will log each player's incoming (C->S) communication to a per-connection logfile */ bool g_ShouldLogCommIn; /** If set to true, the protocols will log each player's outgoing (S->C) communication to a per-connection logfile */ bool g_ShouldLogCommOut; /// If defined, a thorough leak finder will be used (debug MSVC only); leaks will be output to the Output window // _X 2014_02_20: Disabled for canon repo, it makes the debug version too slow in MSVC2013 // and we haven't had a memory leak for over a year anyway. // #define ENABLE_LEAK_FINDER #if defined(_MSC_VER) && defined(_DEBUG) && defined(ENABLE_LEAK_FINDER) #pragma warning(push) #pragma warning(disable:4100) #include "LeakFinder.h" #pragma warning(pop) #endif void NonCtrlHandler(int a_Signal) { LOGD("Terminate event raised from std::signal"); cRoot::m_TerminateEventRaised = true; switch (a_Signal) { case SIGSEGV: { std::signal(SIGSEGV, SIG_DFL); LOGERROR(" D: | MCServer has encountered an error and needs to close"); LOGERROR("Details | SIGSEGV: Segmentation fault"); PrintStackTrace(); abort(); } case SIGABRT: #ifdef SIGABRT_COMPAT case SIGABRT_COMPAT: #endif { std::signal(a_Signal, SIG_DFL); LOGERROR(" D: | MCServer has encountered an error and needs to close"); LOGERROR("Details | SIGABRT: Server self-terminated due to an internal fault"); PrintStackTrace(); abort(); } case SIGINT: case SIGTERM: { std::signal(a_Signal, SIG_IGN); // Server is shutting down, wait for it... break; } default: break; } } #if defined(_WIN32) && !defined(_WIN64) && defined(_MSC_VER) //////////////////////////////////////////////////////////////////////////////// // Windows 32-bit stuff: when the server crashes, create a "dump file" containing the callstack of each thread and some variables; let the user send us that crash file for analysis typedef BOOL (WINAPI *pMiniDumpWriteDump)( HANDLE hProcess, DWORD ProcessId, HANDLE hFile, MINIDUMP_TYPE DumpType, PMINIDUMP_EXCEPTION_INFORMATION ExceptionParam, PMINIDUMP_USER_STREAM_INFORMATION UserStreamParam, PMINIDUMP_CALLBACK_INFORMATION CallbackParam ); pMiniDumpWriteDump g_WriteMiniDump; // The function in dbghlp DLL that creates dump files char g_DumpFileName[MAX_PATH]; // Filename of the dump file; hes to be created before the dump handler kicks in char g_ExceptionStack[128 * 1024]; // Substitute stack, just in case the handler kicks in because of "insufficient stack space" MINIDUMP_TYPE g_DumpFlags = MiniDumpNormal; // By default dump only the stack and some helpers /** This function gets called just before the "program executed an illegal instruction and will be terminated" or similar. Its purpose is to create the crashdump using the dbghlp DLLs */ LONG WINAPI LastChanceExceptionFilter(__in struct _EXCEPTION_POINTERS * a_ExceptionInfo) { char * newStack = &g_ExceptionStack[sizeof(g_ExceptionStack)]; char * oldStack; // Use the substitute stack: // This code is the reason why we don't support 64-bit (yet) _asm { mov oldStack, esp mov esp, newStack } MINIDUMP_EXCEPTION_INFORMATION ExcInformation; ExcInformation.ThreadId = GetCurrentThreadId(); ExcInformation.ExceptionPointers = a_ExceptionInfo; ExcInformation.ClientPointers = 0; // Write the dump file: HANDLE dumpFile = CreateFile(g_DumpFileName, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); g_WriteMiniDump(GetCurrentProcess(), GetCurrentProcessId(), dumpFile, g_DumpFlags, (a_ExceptionInfo) ? &ExcInformation : nullptr, nullptr, nullptr); CloseHandle(dumpFile); // Print the stack trace for the basic debugging: PrintStackTrace(); // Revert to old stack: _asm { mov esp, oldStack } return 0; } #endif // _WIN32 && !_WIN64 #ifdef _WIN32 // Handle CTRL events in windows, including console window close BOOL CtrlHandler(DWORD fdwCtrlType) { cRoot::m_TerminateEventRaised = true; LOGD("Terminate event raised from the Windows CtrlHandler"); if (fdwCtrlType == CTRL_CLOSE_EVENT) // Console window closed via 'x' button, Windows will try to close immediately, therefore... { while (!g_ServerTerminated) { cSleep::MilliSleep(100); } // Delay as much as possible to try to get the server to shut down cleanly } return TRUE; } #endif //////////////////////////////////////////////////////////////////////////////// // main: int main( int argc, char **argv) { UNUSED(argc); UNUSED(argv); #if defined(_MSC_VER) && defined(_DEBUG) && defined(ENABLE_LEAK_FINDER) InitLeakFinder(); #endif // Magic code to produce dump-files on Windows if the server crashes: #if defined(_WIN32) && !defined(_WIN64) && defined(_MSC_VER) HINSTANCE hDbgHelp = LoadLibrary("DBGHELP.DLL"); g_WriteMiniDump = (pMiniDumpWriteDump)GetProcAddress(hDbgHelp, "MiniDumpWriteDump"); if (g_WriteMiniDump != nullptr) { _snprintf_s(g_DumpFileName, ARRAYCOUNT(g_DumpFileName), _TRUNCATE, "crash_mcs_%x.dmp", GetCurrentProcessId()); SetUnhandledExceptionFilter(LastChanceExceptionFilter); // Parse arguments for minidump flags: for (int i = 0; i < argc; i++) { if (_stricmp(argv[i], "/cdg") == 0) { // Add globals to the dump g_DumpFlags = (MINIDUMP_TYPE)(g_DumpFlags | MiniDumpWithDataSegs); } else if (_stricmp(argv[i], "/cdf") == 0) { // Add full memory to the dump (HUUUGE file) g_DumpFlags = (MINIDUMP_TYPE)(g_DumpFlags | MiniDumpWithFullMemory); } } // for i - argv[] } #endif // _WIN32 && !_WIN64 // End of dump-file magic #ifdef _WIN32 if (!SetConsoleCtrlHandler((PHANDLER_ROUTINE)CtrlHandler, TRUE)) { LOGERROR("Could not install the Windows CTRL handler!"); } #endif #if defined(_DEBUG) && defined(_MSC_VER) _CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF); // _X: The simple built-in CRT leak finder - simply break when allocating the Nth block ({N} is listed in the leak output) // Only useful when the leak is in the same sequence all the time // _CrtSetBreakAlloc(85950); #endif // _DEBUG && _MSC_VER #ifndef _DEBUG std::signal(SIGSEGV, NonCtrlHandler); std::signal(SIGTERM, NonCtrlHandler); std::signal(SIGINT, NonCtrlHandler); std::signal(SIGABRT, NonCtrlHandler); #ifdef SIGABRT_COMPAT std::signal(SIGABRT_COMPAT, NonCtrlHandler); #endif // SIGABRT_COMPAT #endif // DEBUG: test the dumpfile creation: // *((int *)0) = 0; // Check if comm logging is to be enabled: for (int i = 0; i < argc; i++) { AString Arg(argv[i]); if ( (NoCaseCompare(Arg, "/commlog") == 0) || (NoCaseCompare(Arg, "/logcomm") == 0) ) { g_ShouldLogCommIn = true; g_ShouldLogCommOut = true; } else if ( (NoCaseCompare(Arg, "/commlogin") == 0) || (NoCaseCompare(Arg, "/comminlog") == 0) || (NoCaseCompare(Arg, "/logcommin") == 0) ) { g_ShouldLogCommIn = true; } else if ( (NoCaseCompare(Arg, "/commlogout") == 0) || (NoCaseCompare(Arg, "/commoutlog") == 0) || (NoCaseCompare(Arg, "/logcommout") == 0) ) { g_ShouldLogCommOut = true; } else if (NoCaseCompare(Arg, "nooutbuf") == 0) { setvbuf(stdout, nullptr, _IONBF, 0); } } // for i - argv[] cLogger::InitiateMultithreading(); #if !defined(ANDROID_NDK) try #endif { cRoot Root; Root.Start(); } #if !defined(ANDROID_NDK) catch (std::exception & e) { LOGERROR("Standard exception: %s", e.what()); } catch (...) { LOGERROR("Unknown exception!"); } #endif #if defined(_MSC_VER) && defined(_DEBUG) && defined(ENABLE_LEAK_FINDER) DeinitLeakFinder(); #endif g_ServerTerminated = true; return EXIT_SUCCESS; } <commit_msg>Removed unneeded include.<commit_after> #include "Globals.h" // NOTE: MSVC stupidness requires this to be the same across all modules #include "Root.h" #include <exception> #include <csignal> #include <stdlib.h> #ifdef _MSC_VER #include <dbghelp.h> #endif // _MSC_VER bool cRoot::m_TerminateEventRaised = false; // If something has told the server to stop; checked periodically in cRoot static bool g_ServerTerminated = false; // Set to true when the server terminates, so our CTRL handler can then tell the OS to close the console /** If set to true, the protocols will log each player's incoming (C->S) communication to a per-connection logfile */ bool g_ShouldLogCommIn; /** If set to true, the protocols will log each player's outgoing (S->C) communication to a per-connection logfile */ bool g_ShouldLogCommOut; /// If defined, a thorough leak finder will be used (debug MSVC only); leaks will be output to the Output window // _X 2014_02_20: Disabled for canon repo, it makes the debug version too slow in MSVC2013 // and we haven't had a memory leak for over a year anyway. // #define ENABLE_LEAK_FINDER #if defined(_MSC_VER) && defined(_DEBUG) && defined(ENABLE_LEAK_FINDER) #pragma warning(push) #pragma warning(disable:4100) #include "LeakFinder.h" #pragma warning(pop) #endif void NonCtrlHandler(int a_Signal) { LOGD("Terminate event raised from std::signal"); cRoot::m_TerminateEventRaised = true; switch (a_Signal) { case SIGSEGV: { std::signal(SIGSEGV, SIG_DFL); LOGERROR(" D: | MCServer has encountered an error and needs to close"); LOGERROR("Details | SIGSEGV: Segmentation fault"); PrintStackTrace(); abort(); } case SIGABRT: #ifdef SIGABRT_COMPAT case SIGABRT_COMPAT: #endif { std::signal(a_Signal, SIG_DFL); LOGERROR(" D: | MCServer has encountered an error and needs to close"); LOGERROR("Details | SIGABRT: Server self-terminated due to an internal fault"); PrintStackTrace(); abort(); } case SIGINT: case SIGTERM: { std::signal(a_Signal, SIG_IGN); // Server is shutting down, wait for it... break; } default: break; } } #if defined(_WIN32) && !defined(_WIN64) && defined(_MSC_VER) //////////////////////////////////////////////////////////////////////////////// // Windows 32-bit stuff: when the server crashes, create a "dump file" containing the callstack of each thread and some variables; let the user send us that crash file for analysis typedef BOOL (WINAPI *pMiniDumpWriteDump)( HANDLE hProcess, DWORD ProcessId, HANDLE hFile, MINIDUMP_TYPE DumpType, PMINIDUMP_EXCEPTION_INFORMATION ExceptionParam, PMINIDUMP_USER_STREAM_INFORMATION UserStreamParam, PMINIDUMP_CALLBACK_INFORMATION CallbackParam ); pMiniDumpWriteDump g_WriteMiniDump; // The function in dbghlp DLL that creates dump files char g_DumpFileName[MAX_PATH]; // Filename of the dump file; hes to be created before the dump handler kicks in char g_ExceptionStack[128 * 1024]; // Substitute stack, just in case the handler kicks in because of "insufficient stack space" MINIDUMP_TYPE g_DumpFlags = MiniDumpNormal; // By default dump only the stack and some helpers /** This function gets called just before the "program executed an illegal instruction and will be terminated" or similar. Its purpose is to create the crashdump using the dbghlp DLLs */ LONG WINAPI LastChanceExceptionFilter(__in struct _EXCEPTION_POINTERS * a_ExceptionInfo) { char * newStack = &g_ExceptionStack[sizeof(g_ExceptionStack)]; char * oldStack; // Use the substitute stack: // This code is the reason why we don't support 64-bit (yet) _asm { mov oldStack, esp mov esp, newStack } MINIDUMP_EXCEPTION_INFORMATION ExcInformation; ExcInformation.ThreadId = GetCurrentThreadId(); ExcInformation.ExceptionPointers = a_ExceptionInfo; ExcInformation.ClientPointers = 0; // Write the dump file: HANDLE dumpFile = CreateFile(g_DumpFileName, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); g_WriteMiniDump(GetCurrentProcess(), GetCurrentProcessId(), dumpFile, g_DumpFlags, (a_ExceptionInfo) ? &ExcInformation : nullptr, nullptr, nullptr); CloseHandle(dumpFile); // Print the stack trace for the basic debugging: PrintStackTrace(); // Revert to old stack: _asm { mov esp, oldStack } return 0; } #endif // _WIN32 && !_WIN64 #ifdef _WIN32 // Handle CTRL events in windows, including console window close BOOL CtrlHandler(DWORD fdwCtrlType) { cRoot::m_TerminateEventRaised = true; LOGD("Terminate event raised from the Windows CtrlHandler"); if (fdwCtrlType == CTRL_CLOSE_EVENT) // Console window closed via 'x' button, Windows will try to close immediately, therefore... { while (!g_ServerTerminated) { cSleep::MilliSleep(100); } // Delay as much as possible to try to get the server to shut down cleanly } return TRUE; } #endif //////////////////////////////////////////////////////////////////////////////// // main: int main( int argc, char **argv) { UNUSED(argc); UNUSED(argv); #if defined(_MSC_VER) && defined(_DEBUG) && defined(ENABLE_LEAK_FINDER) InitLeakFinder(); #endif // Magic code to produce dump-files on Windows if the server crashes: #if defined(_WIN32) && !defined(_WIN64) && defined(_MSC_VER) HINSTANCE hDbgHelp = LoadLibrary("DBGHELP.DLL"); g_WriteMiniDump = (pMiniDumpWriteDump)GetProcAddress(hDbgHelp, "MiniDumpWriteDump"); if (g_WriteMiniDump != nullptr) { _snprintf_s(g_DumpFileName, ARRAYCOUNT(g_DumpFileName), _TRUNCATE, "crash_mcs_%x.dmp", GetCurrentProcessId()); SetUnhandledExceptionFilter(LastChanceExceptionFilter); // Parse arguments for minidump flags: for (int i = 0; i < argc; i++) { if (_stricmp(argv[i], "/cdg") == 0) { // Add globals to the dump g_DumpFlags = (MINIDUMP_TYPE)(g_DumpFlags | MiniDumpWithDataSegs); } else if (_stricmp(argv[i], "/cdf") == 0) { // Add full memory to the dump (HUUUGE file) g_DumpFlags = (MINIDUMP_TYPE)(g_DumpFlags | MiniDumpWithFullMemory); } } // for i - argv[] } #endif // _WIN32 && !_WIN64 // End of dump-file magic #ifdef _WIN32 if (!SetConsoleCtrlHandler((PHANDLER_ROUTINE)CtrlHandler, TRUE)) { LOGERROR("Could not install the Windows CTRL handler!"); } #endif #if defined(_DEBUG) && defined(_MSC_VER) _CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF); // _X: The simple built-in CRT leak finder - simply break when allocating the Nth block ({N} is listed in the leak output) // Only useful when the leak is in the same sequence all the time // _CrtSetBreakAlloc(85950); #endif // _DEBUG && _MSC_VER #ifndef _DEBUG std::signal(SIGSEGV, NonCtrlHandler); std::signal(SIGTERM, NonCtrlHandler); std::signal(SIGINT, NonCtrlHandler); std::signal(SIGABRT, NonCtrlHandler); #ifdef SIGABRT_COMPAT std::signal(SIGABRT_COMPAT, NonCtrlHandler); #endif // SIGABRT_COMPAT #endif // DEBUG: test the dumpfile creation: // *((int *)0) = 0; // Check if comm logging is to be enabled: for (int i = 0; i < argc; i++) { AString Arg(argv[i]); if ( (NoCaseCompare(Arg, "/commlog") == 0) || (NoCaseCompare(Arg, "/logcomm") == 0) ) { g_ShouldLogCommIn = true; g_ShouldLogCommOut = true; } else if ( (NoCaseCompare(Arg, "/commlogin") == 0) || (NoCaseCompare(Arg, "/comminlog") == 0) || (NoCaseCompare(Arg, "/logcommin") == 0) ) { g_ShouldLogCommIn = true; } else if ( (NoCaseCompare(Arg, "/commlogout") == 0) || (NoCaseCompare(Arg, "/commoutlog") == 0) || (NoCaseCompare(Arg, "/logcommout") == 0) ) { g_ShouldLogCommOut = true; } else if (NoCaseCompare(Arg, "nooutbuf") == 0) { setvbuf(stdout, nullptr, _IONBF, 0); } } // for i - argv[] cLogger::InitiateMultithreading(); #if !defined(ANDROID_NDK) try #endif { cRoot Root; Root.Start(); } #if !defined(ANDROID_NDK) catch (std::exception & e) { LOGERROR("Standard exception: %s", e.what()); } catch (...) { LOGERROR("Unknown exception!"); } #endif #if defined(_MSC_VER) && defined(_DEBUG) && defined(ENABLE_LEAK_FINDER) DeinitLeakFinder(); #endif g_ServerTerminated = true; return EXIT_SUCCESS; } <|endoftext|>
<commit_before>#pragma once #include "../abstract_kernel.hpp" #include "parameter_result_cache.hpp" #include <chrono> namespace autotune { template <typename R, typename... Args> class with_tests { private: std::function<bool(R)> t; public: void setup_test(std::function<bool(R)> t_) { t = t_; }; bool has_test() { return t ? true : false; } bool test(R r) { return t(r); }; }; template <typename R, typename... Args> class without_tests {}; template <typename parameter_interface, typename R, typename... Args> class abstract_tuner : public std::conditional<!std::is_same<R, void>::value, with_tests<R, Args...>, without_tests<R, Args...>>::type { protected: autotune::abstract_kernel<R, cppjit::detail::pack<Args...>> &f; parameter_interface parameters; parameter_value_set optimal_parameter_values; double optimal_duration; bool verbose; bool do_measurement; bool do_write_header; std::ofstream scenario_kernel_duration_file; std::ofstream scenario_compile_duration_file; parameter_result_cache<parameter_interface> result_cache; std::function<void(parameter_interface &)> parameter_adjustment_functor; std::function<void(parameter_interface &, const parameter_value_set &)> extended_parameter_adjustment_functor; size_t repetitions = 1; public: abstract_tuner(autotune::abstract_kernel<R, cppjit::detail::pack<Args...>> &f, parameter_interface &parameters) : f(f), parameters(parameters), optimal_duration(-1.0), verbose(false), do_measurement(false), do_write_header(true) {} double evaluate(bool &did_eval, Args &... args) { if (!result_cache.contains(parameters)) { result_cache.insert(parameters); } else { did_eval = false; if (verbose) { std::cout << "------ skipped eval ------" << std::endl; parameters.print_values(); std::cout << "--------------------------" << std::endl; } return std::numeric_limits<double>::max(); } parameter_interface original_parameters = parameters; if (parameter_adjustment_functor || extended_parameter_adjustment_functor) { if (verbose) { std::cout << "------ parameters pre-adjustment ------" << std::endl; parameters.print_values(); std::cout << "--------------------------" << std::endl; } if (parameter_adjustment_functor) parameter_adjustment_functor(parameters); else if (extended_parameter_adjustment_functor) extended_parameter_adjustment_functor(parameters, f.get_parameter_values()); } parameter_value_set parameter_values = f.get_parameter_values(); for (size_t parameter_index = 0; parameter_index < parameters.size(); parameter_index++) { auto &p = parameters[parameter_index]; parameter_values[p->get_name()] = p->get_value(); } if (!f.precompile_validate_parameters(parameter_values)) { if (verbose) { std::cout << "------ invalidated eval (precompile) ------" << std::endl; parameters.print_values(); std::cout << "--------------------------" << std::endl; } did_eval = false; return std::numeric_limits<double>::max(); } else { if (verbose) { std::cout << "parameter combination passed precompile check" << std::endl; } } f.set_parameter_values(parameter_values); if (do_measurement && do_write_header) { this->write_header(); do_write_header = false; } did_eval = true; if (verbose) { std::cout << "------ begin eval ------" << std::endl; //parameters.print_values(); print_parameter_values(parameter_values); } f.create_parameter_file(); auto start_compile = std::chrono::high_resolution_clock::now(); f.compile(); auto end_compile = std::chrono::high_resolution_clock::now(); std::chrono::duration<double> duration_compile = end_compile - start_compile; if (!f.is_valid_parameter_combination()) { if (verbose) { std::cout << "invalid parameter combination encountered" << std::endl; } did_eval = false; return std::numeric_limits<double>::max(); } else { if (verbose) { std::cout << "parameter combination is valid" << std::endl; } } auto start = std::chrono::high_resolution_clock::now(); // call kernel, discard possibly returned values if constexpr(!std::is_same<R, void>::value) { if (this->has_test()) { for (size_t i = 0; i < repetitions; i++) { bool test_ok = this->test(f(args...)); if (!test_ok) { if (verbose) { std::cout << "warning: test for combination failed!" << std::endl; } return std::numeric_limits<double>::max(); } else { if (verbose) { std::cout << "test for combination passed" << std::endl; } } } } else { for (size_t i = 0; i < repetitions; i++) { f(args...); } } } else { for (size_t i = 0; i < repetitions; i++) { f(args...); } } auto end = std::chrono::high_resolution_clock::now(); std::chrono::duration<double> duration = end - start; if (verbose) { if (f.has_kernel_duration_functor()) { std::cout << "internal duration: " << f.get_internal_kernel_duration() << std::endl; if (repetitions > 1) { std::cout << "internal duration per repetition: " << (f.get_internal_kernel_duration() / static_cast<double>(repetitions)) << std::endl; } std::cout << "(duration tuner: " << duration.count() << "s)" << std::endl; if (repetitions > 1) { std::cout << "(duration tuner per repetition: " << (duration.count() / static_cast<double>(repetitions)) << "s)" << std::endl; } } else { std::cout << "duration: " << duration.count() << "s" << std::endl; if (repetitions > 1) { std::cout << "duration tuner per reptition: " << (duration.count() / static_cast<double>(repetitions)) << "s" << std::endl; } std::cout << "------- end eval -------" << std::endl; } } if (parameter_adjustment_functor || extended_parameter_adjustment_functor) { parameters = original_parameters; } double final_duration; if (f.has_kernel_duration_functor()) { if (do_measurement) { this->write_measurement(f.get_internal_kernel_duration(), duration_compile.count()); } final_duration = f.get_internal_kernel_duration(); } else { if (do_measurement) { this->write_measurement(duration.count(), duration_compile.count()); } final_duration = duration.count(); } if (optimal_duration < 0.0 || final_duration < optimal_duration) { optimal_duration = final_duration; optimal_parameter_values = parameter_values; } return final_duration; } const parameter_value_set& get_optimal_parameter_values() const { if (optimal_duration < 0.0) return f.get_parameter_values(); else return optimal_parameter_values; } void report(const std::string &message, double duration, parameter_interface &parameters) { std::cout << message << "; duration: " << duration << std::endl; parameters.print_values(); } void set_verbose(bool verbose) { this->verbose = verbose; } void report_verbose(const std::string &message, double duration, parameter_interface &parameters) { if (verbose) { report(message, duration, parameters); } } void write_header() { const parameter_value_set &parameter_values = f.get_parameter_values(); bool first = true; for (auto &p : parameter_values) { if (!first) { scenario_kernel_duration_file << ", "; scenario_compile_duration_file << ", "; } else { first = false; } scenario_kernel_duration_file << p.first; scenario_compile_duration_file << p.first; } scenario_kernel_duration_file << ", " << "duration" << std::endl; scenario_compile_duration_file << ", " << "duration" << std::endl; } void write_measurement(double duration_kernel_s, double duration_compile_s) { const parameter_value_set &parameter_values = f.get_parameter_values(); bool first = true; for (auto &p : parameter_values) { if (!first) { scenario_kernel_duration_file << ", "; scenario_compile_duration_file << ", "; } else { first = false; } scenario_kernel_duration_file << p.second; scenario_compile_duration_file << p.second; } scenario_kernel_duration_file << ", " << duration_kernel_s << std::endl; scenario_compile_duration_file << ", " << duration_compile_s << std::endl; } void set_write_measurement(const std::string &scenario_name) { if (do_measurement) { if (scenario_kernel_duration_file.is_open()) { scenario_kernel_duration_file.close(); } if (scenario_compile_duration_file.is_open()) { scenario_compile_duration_file.close(); } } do_measurement = true; do_write_header = true; scenario_kernel_duration_file.open(scenario_name + "_kernel_duration.csv"); scenario_compile_duration_file.open(scenario_name + "_compile_duration.csv"); } void set_parameter_adjustment_functor( std::function<void(parameter_interface &)> parameter_adjustment_functor) { this->parameter_adjustment_functor = parameter_adjustment_functor; this->extended_parameter_adjustment_functor = nullptr; } void set_parameter_adjustment_functor( std::function<void(parameter_interface &, const parameter_value_set &)> parameter_adjustment_functor) { this->extended_parameter_adjustment_functor = parameter_adjustment_functor; this->parameter_adjustment_functor = [this](parameter_interface &parameters) -> void { this->extended_parameter_adjustment_functor(parameters, this->f.get_parameter_values()); }; } // execute kernel multiple times to average across the result void set_repetitions(size_t repetitions) { this->repetitions = repetitions; } }; } // namespace autotune <commit_msg>added additional verbose info to abstract_tuner eval<commit_after>#pragma once #include "../abstract_kernel.hpp" #include "parameter_result_cache.hpp" #include <chrono> namespace autotune { template <typename R, typename... Args> class with_tests { private: std::function<bool(R)> t; public: void setup_test(std::function<bool(R)> t_) { t = t_; }; bool has_test() { return t ? true : false; } bool test(R r) { return t(r); }; }; template <typename R, typename... Args> class without_tests {}; template <typename parameter_interface, typename R, typename... Args> class abstract_tuner : public std::conditional<!std::is_same<R, void>::value, with_tests<R, Args...>, without_tests<R, Args...>>::type { protected: autotune::abstract_kernel<R, cppjit::detail::pack<Args...>> &f; parameter_interface parameters; parameter_value_set optimal_parameter_values; double optimal_duration; bool verbose; bool do_measurement; bool do_write_header; std::ofstream scenario_kernel_duration_file; std::ofstream scenario_compile_duration_file; parameter_result_cache<parameter_interface> result_cache; std::function<void(parameter_interface &)> parameter_adjustment_functor; std::function<void(parameter_interface &, const parameter_value_set &)> extended_parameter_adjustment_functor; size_t repetitions = 1; public: abstract_tuner(autotune::abstract_kernel<R, cppjit::detail::pack<Args...>> &f, parameter_interface &parameters) : f(f), parameters(parameters), optimal_duration(-1.0), verbose(false), do_measurement(false), do_write_header(true) {} double evaluate(bool &did_eval, Args &... args) { if (verbose) { parameter_value_set parameter_values = f.get_parameter_values(); for (size_t parameter_index = 0; parameter_index < parameters.size(); parameter_index++) { auto &p = parameters[parameter_index]; parameter_values[p->get_name()] = p->get_value(); } std::cout << "------ try eval ------" << std::endl; //parameters.print_values(); print_parameter_values(parameter_values); } if (!result_cache.contains(parameters)) { result_cache.insert(parameters); } else { did_eval = false; if (verbose) { std::cout << "------ skipped eval ------" << std::endl; parameters.print_values(); std::cout << "--------------------------" << std::endl; } return std::numeric_limits<double>::max(); } parameter_interface original_parameters = parameters; if (parameter_adjustment_functor || extended_parameter_adjustment_functor) { if (verbose) { std::cout << "------ parameters pre-adjustment ------" << std::endl; parameters.print_values(); std::cout << "--------------------------" << std::endl; } if (parameter_adjustment_functor) parameter_adjustment_functor(parameters); else if (extended_parameter_adjustment_functor) extended_parameter_adjustment_functor(parameters, f.get_parameter_values()); } parameter_value_set parameter_values = f.get_parameter_values(); for (size_t parameter_index = 0; parameter_index < parameters.size(); parameter_index++) { auto &p = parameters[parameter_index]; parameter_values[p->get_name()] = p->get_value(); } if (!f.precompile_validate_parameters(parameter_values)) { if (verbose) { std::cout << "------ invalidated eval (precompile) ------" << std::endl; parameters.print_values(); std::cout << "--------------------------" << std::endl; } did_eval = false; return std::numeric_limits<double>::max(); } else { if (verbose) { std::cout << "parameter combination passed precompile check" << std::endl; } } f.set_parameter_values(parameter_values); if (do_measurement && do_write_header) { this->write_header(); do_write_header = false; } did_eval = true; if (verbose) { std::cout << "------ begin eval ------" << std::endl; //parameters.print_values(); print_parameter_values(parameter_values); } f.create_parameter_file(); auto start_compile = std::chrono::high_resolution_clock::now(); f.compile(); auto end_compile = std::chrono::high_resolution_clock::now(); std::chrono::duration<double> duration_compile = end_compile - start_compile; if (!f.is_valid_parameter_combination()) { if (verbose) { std::cout << "invalid parameter combination encountered" << std::endl; } did_eval = false; return std::numeric_limits<double>::max(); } else { if (verbose) { std::cout << "parameter combination is valid" << std::endl; } } auto start = std::chrono::high_resolution_clock::now(); // call kernel, discard possibly returned values if constexpr(!std::is_same<R, void>::value) { if (this->has_test()) { for (size_t i = 0; i < repetitions; i++) { bool test_ok = this->test(f(args...)); if (!test_ok) { if (verbose) { std::cout << "warning: test for combination failed!" << std::endl; } return std::numeric_limits<double>::max(); } else { if (verbose) { std::cout << "test for combination passed" << std::endl; } } } } else { for (size_t i = 0; i < repetitions; i++) { f(args...); } } } else { for (size_t i = 0; i < repetitions; i++) { f(args...); } } auto end = std::chrono::high_resolution_clock::now(); std::chrono::duration<double> duration = end - start; if (verbose) { if (f.has_kernel_duration_functor()) { std::cout << "internal duration: " << f.get_internal_kernel_duration() << std::endl; if (repetitions > 1) { std::cout << "internal duration per repetition: " << (f.get_internal_kernel_duration() / static_cast<double>(repetitions)) << std::endl; } std::cout << "(duration tuner: " << duration.count() << "s)" << std::endl; if (repetitions > 1) { std::cout << "(duration tuner per repetition: " << (duration.count() / static_cast<double>(repetitions)) << "s)" << std::endl; } } else { std::cout << "duration: " << duration.count() << "s" << std::endl; if (repetitions > 1) { std::cout << "duration tuner per reptition: " << (duration.count() / static_cast<double>(repetitions)) << "s" << std::endl; } std::cout << "------- end eval -------" << std::endl; } } if (parameter_adjustment_functor || extended_parameter_adjustment_functor) { parameters = original_parameters; } double final_duration; if (f.has_kernel_duration_functor()) { if (do_measurement) { this->write_measurement(f.get_internal_kernel_duration(), duration_compile.count()); } final_duration = f.get_internal_kernel_duration(); } else { if (do_measurement) { this->write_measurement(duration.count(), duration_compile.count()); } final_duration = duration.count(); } if (optimal_duration < 0.0 || final_duration < optimal_duration) { optimal_duration = final_duration; optimal_parameter_values = parameter_values; } return final_duration; } const parameter_value_set& get_optimal_parameter_values() const { if (optimal_duration < 0.0) return f.get_parameter_values(); else return optimal_parameter_values; } void report(const std::string &message, double duration, parameter_interface &parameters) { std::cout << message << "; duration: " << duration << std::endl; parameters.print_values(); } void set_verbose(bool verbose) { this->verbose = verbose; } void report_verbose(const std::string &message, double duration, parameter_interface &parameters) { if (verbose) { report(message, duration, parameters); } } void write_header() { const parameter_value_set &parameter_values = f.get_parameter_values(); bool first = true; for (auto &p : parameter_values) { if (!first) { scenario_kernel_duration_file << ", "; scenario_compile_duration_file << ", "; } else { first = false; } scenario_kernel_duration_file << p.first; scenario_compile_duration_file << p.first; } scenario_kernel_duration_file << ", " << "duration" << std::endl; scenario_compile_duration_file << ", " << "duration" << std::endl; } void write_measurement(double duration_kernel_s, double duration_compile_s) { const parameter_value_set &parameter_values = f.get_parameter_values(); bool first = true; for (auto &p : parameter_values) { if (!first) { scenario_kernel_duration_file << ", "; scenario_compile_duration_file << ", "; } else { first = false; } scenario_kernel_duration_file << p.second; scenario_compile_duration_file << p.second; } scenario_kernel_duration_file << ", " << duration_kernel_s << std::endl; scenario_compile_duration_file << ", " << duration_compile_s << std::endl; } void set_write_measurement(const std::string &scenario_name) { if (do_measurement) { if (scenario_kernel_duration_file.is_open()) { scenario_kernel_duration_file.close(); } if (scenario_compile_duration_file.is_open()) { scenario_compile_duration_file.close(); } } do_measurement = true; do_write_header = true; scenario_kernel_duration_file.open(scenario_name + "_kernel_duration.csv"); scenario_compile_duration_file.open(scenario_name + "_compile_duration.csv"); } void set_parameter_adjustment_functor( std::function<void(parameter_interface &)> parameter_adjustment_functor) { this->parameter_adjustment_functor = parameter_adjustment_functor; this->extended_parameter_adjustment_functor = nullptr; } void set_parameter_adjustment_functor( std::function<void(parameter_interface &, const parameter_value_set &)> parameter_adjustment_functor) { this->extended_parameter_adjustment_functor = parameter_adjustment_functor; this->parameter_adjustment_functor = [this](parameter_interface &parameters) -> void { this->extended_parameter_adjustment_functor(parameters, this->f.get_parameter_values()); }; } // execute kernel multiple times to average across the result void set_repetitions(size_t repetitions) { this->repetitions = repetitions; } }; } // namespace autotune <|endoftext|>
<commit_before>#pragma once #include "depthai-shared/utility/Serialization.hpp" #include "tl/optional.hpp" // tl::optional serialization for nlohmann json // partial specialization (full specialization works too) namespace nlohmann { template <typename T> struct adl_serializer<tl::optional<T>> { static void to_json(json& j, const tl::optional<T>& opt) { // NOLINT this is a specialization, naming conventions don't apply if(opt == tl::nullopt) { j = nullptr; } else { j = *opt; // this will call adl_serializer<T>::to_json which will // find the free function to_json in T's namespace! } } static void from_json(const json& j, tl::optional<T>& opt) { // NOLINT this is a specialization, naming conventions don't apply if(j.is_null()) { opt = tl::nullopt; } else { opt = j.get<T>(); // same as above, but with // adl_serializer<T>::from_json } } }; } // namespace nlohmann // tl::optional serialization for libnop namespace nop { // // Optional<T> encoding formats: // // Empty Optional<T>: // // +-----+ // | NIL | // +-----+ // // Non-empty Optional<T> // // +---//----+ // | ELEMENT | // +---//----+ // // Element must be a valid encoding of type T. // template <typename T> struct Encoding<tl::optional<T>> : EncodingIO<tl::optional<T>> { using Type = tl::optional<T>; static constexpr EncodingByte Prefix(const Type& value) { return value ? Encoding<T>::Prefix(*value) : EncodingByte::Nil; } static constexpr std::size_t Size(const Type& value) { return value ? Encoding<T>::Size(*value) : BaseEncodingSize(EncodingByte::Nil); } static constexpr bool Match(EncodingByte prefix) { return prefix == EncodingByte::Nil || Encoding<T>::Match(prefix); } template <typename Writer> static constexpr Status<void> WritePayload(EncodingByte prefix, const Type& value, Writer* writer) { if(value) { return Encoding<T>::WritePayload(prefix, *value, writer); } else { return {}; } } template <typename Reader> static constexpr Status<void> ReadPayload(EncodingByte prefix, Type* value, Reader* reader) { if(prefix == EncodingByte::Nil) { value->reset(); } else { T temp; auto status = Encoding<T>::ReadPayload(prefix, &temp, reader); if(!status) return status; *value = std::move(temp); } return {}; } }; } // namespace nop<commit_msg>Updated libnop optional<commit_after>#pragma once #include "depthai-shared/utility/Serialization.hpp" #include "tl/optional.hpp" // tl::optional serialization for nlohmann json // partial specialization (full specialization works too) namespace nlohmann { template <typename T> struct adl_serializer<tl::optional<T>> { static void to_json(json& j, const tl::optional<T>& opt) { // NOLINT this is a specialization, naming conventions don't apply if(opt == tl::nullopt) { j = nullptr; } else { j = *opt; // this will call adl_serializer<T>::to_json which will // find the free function to_json in T's namespace! } } static void from_json(const json& j, tl::optional<T>& opt) { // NOLINT this is a specialization, naming conventions don't apply if(j.is_null()) { opt = tl::nullopt; } else { opt = j.get<T>(); // same as above, but with // adl_serializer<T>::from_json } } }; } // namespace nlohmann // tl::optional serialization for libnop namespace nop { // // Optional<T> encoding formats: // // Empty Optional<T>: // // +-----+ // | NIL | // +-----+ // // Non-empty Optional<T> // // +---//----+ // | ELEMENT | // +---//----+ // // Element must be a valid encoding of type T. // template <typename T> struct Encoding<tl::optional<T>> : EncodingIO<tl::optional<T>> { using Type = tl::optional<T>; static constexpr EncodingByte Prefix(const Type& value) { return value ? Encoding<T>::Prefix(*value) : EncodingByte::Empty; } static constexpr std::size_t Size(const Type& value) { return value ? Encoding<T>::Size(*value) : BaseEncodingSize(EncodingByte::Empty); } static constexpr bool Match(EncodingByte prefix) { return prefix == EncodingByte::Empty || Encoding<T>::Match(prefix); } template <typename Writer> static constexpr Status<void> WritePayload(EncodingByte prefix, const Type& value, Writer* writer) { if(value) { return Encoding<T>::WritePayload(prefix, *value, writer); } else { return {}; } } template <typename Reader> static constexpr Status<void> ReadPayload(EncodingByte prefix, Type* value, Reader* reader) { if(prefix == EncodingByte::Empty) { value->reset(); } else { T temp; auto status = Encoding<T>::ReadPayload(prefix, &temp, reader); if(!status) return status; *value = std::move(temp); } return {}; } }; } // namespace nop<|endoftext|>
<commit_before>// // DihedralIsometry.cpp // GroupTheory // // Created by Donald Pinckney on 11/16/15. // Copyright © 2015 Donald Pinckney. All rights reserved. // #include "DihedralIsometry.h" int rotationMod(int rotationIndex, int mod) { int mult = abs(rotationIndex) / mod + 1; return (rotationIndex + mult*mod) % mod; } // NOTE: THIS ALLOCATES MEMORY! YOU MUST CALL DELETE WHEN DONE. DihedralIsometry *DihedralIsometry::compose(const DihedralIsometry &x, const DihedralIsometry &y) { bool reflects = x.reflects != y.reflects; int rotationIndex; if(x.reflects) { rotationIndex = x.rotationIndex - y.rotationIndex; } else { rotationIndex = x.rotationIndex + y.rotationIndex; } rotationIndex = rotationMod(rotationIndex, x.n); DihedralIsometry *iso = new DihedralIsometry(x.n, reflects, rotationIndex); return iso; } // NOTE: THIS ALLOCATES MEMORY! YOU MUST CALL DELETE WHEN DONE. DihedralIsometry *DihedralIsometry::generateIsometries(unsigned int n, unsigned int *count) { *count = 2*n; DihedralIsometry *isos = new DihedralIsometry[*count]; for (unsigned int i = 0; i < n; i++) { isos[i].n = n; isos[i].reflects = false; isos[i].rotationIndex = i; isos[i + n].n = n; isos[i + n].reflects = true; isos[i + n].rotationIndex = i; } return isos; } bool operator==(const DihedralIsometry &lhs, const DihedralIsometry &rhs) { return lhs.n == rhs.n && lhs.reflects == rhs.reflects && lhs.rotationIndex == rhs.rotationIndex; } bool operator!=(const DihedralIsometry &lhs, const DihedralIsometry &rhs) { return !(lhs == rhs); } std::ostream & operator<<(std::ostream &lhs, const DihedralIsometry &rhs) { if(rhs.rotationIndex == 0 && rhs.reflects == false) { lhs << "1"; } else if(rhs.rotationIndex != 0) { lhs << "x^" << rhs.rotationIndex; } lhs << (rhs.reflects ? "y" : ""); return lhs; } <commit_msg>Added proper include<commit_after>// // DihedralIsometry.cpp // GroupTheory // // Created by Donald Pinckney on 11/16/15. // Copyright © 2015 Donald Pinckney. All rights reserved. // #include "DihedralIsometry.h" #include <stdlib.h> int rotationMod(int rotationIndex, int mod) { int mult = abs(rotationIndex) / mod + 1; return (rotationIndex + mult*mod) % mod; } // NOTE: THIS ALLOCATES MEMORY! YOU MUST CALL DELETE WHEN DONE. DihedralIsometry *DihedralIsometry::compose(const DihedralIsometry &x, const DihedralIsometry &y) { bool reflects = x.reflects != y.reflects; int rotationIndex; if(x.reflects) { rotationIndex = x.rotationIndex - y.rotationIndex; } else { rotationIndex = x.rotationIndex + y.rotationIndex; } rotationIndex = rotationMod(rotationIndex, x.n); DihedralIsometry *iso = new DihedralIsometry(x.n, reflects, rotationIndex); return iso; } // NOTE: THIS ALLOCATES MEMORY! YOU MUST CALL DELETE WHEN DONE. DihedralIsometry *DihedralIsometry::generateIsometries(unsigned int n, unsigned int *count) { *count = 2*n; DihedralIsometry *isos = new DihedralIsometry[*count]; for (unsigned int i = 0; i < n; i++) { isos[i].n = n; isos[i].reflects = false; isos[i].rotationIndex = i; isos[i + n].n = n; isos[i + n].reflects = true; isos[i + n].rotationIndex = i; } return isos; } bool operator==(const DihedralIsometry &lhs, const DihedralIsometry &rhs) { return lhs.n == rhs.n && lhs.reflects == rhs.reflects && lhs.rotationIndex == rhs.rotationIndex; } bool operator!=(const DihedralIsometry &lhs, const DihedralIsometry &rhs) { return !(lhs == rhs); } std::ostream & operator<<(std::ostream &lhs, const DihedralIsometry &rhs) { if(rhs.rotationIndex == 0 && rhs.reflects == false) { lhs << "1"; } else if(rhs.rotationIndex != 0) { lhs << "x^" << rhs.rotationIndex; } lhs << (rhs.reflects ? "y" : ""); return lhs; } <|endoftext|>
<commit_before>// Copyright 2016 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 "flutter/content_handler/application_controller_impl.h" #include <utility> #include "apps/modular/lib/app/connect.h" #include "flutter/content_handler/app.h" #include "flutter/content_handler/runtime_holder.h" #include "lib/ftl/logging.h" #include "lib/mtl/vmo/vector.h" namespace flutter_runner { ApplicationControllerImpl::ApplicationControllerImpl( App* app, modular::ApplicationPackagePtr application, modular::ApplicationStartupInfoPtr startup_info, fidl::InterfaceRequest<modular::ApplicationController> controller) : app_(app), binding_(this) { if (controller.is_pending()) { binding_.Bind(std::move(controller)); binding_.set_connection_error_handler([this] { app_->Destroy(this); // |this| has been deleted at this point. }); } std::vector<char> bundle; if (!mtl::VectorFromVmo(std::move(application->data), &bundle)) { FTL_LOG(ERROR) << "Failed to receive bundle."; return; } // TODO(abarth): The Dart code should end up with outgoing_services. if (startup_info->outgoing_services.is_pending()) { service_provider_bindings_.AddBinding( this, std::move(startup_info->outgoing_services)); } url_ = startup_info->url; runtime_holder_.reset(new RuntimeHolder()); // TODO(abarth): The Dart code should end up with environment_services. runtime_holder_->Init(modular::ServiceProviderPtr::Create( std::move(startup_info->environment_services)), std::move(bundle)); } ApplicationControllerImpl::~ApplicationControllerImpl() = default; void ApplicationControllerImpl::Kill(const KillCallback& callback) { runtime_holder_.reset(); app_->Destroy(this); // |this| has been deleted at this point. } void ApplicationControllerImpl::Detach() { binding_.set_connection_error_handler(ftl::Closure()); } void ApplicationControllerImpl::ConnectToService( const fidl::String& service_name, mx::channel client_handle) { if (service_name == mozart::ViewProvider::Name_) { view_provider_bindings_.AddBinding( this, fidl::InterfaceRequest<mozart::ViewProvider>(std::move(client_handle))); } } void ApplicationControllerImpl::CreateView( fidl::InterfaceRequest<mozart::ViewOwner> view_owner_request, fidl::InterfaceRequest<modular::ServiceProvider> services) { runtime_holder_->CreateView(url_, std::move(view_owner_request), std::move(services)); } } // namespace flutter_runner <commit_msg>Update to new way of passing application environment. (#3209)<commit_after>// Copyright 2016 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 "flutter/content_handler/application_controller_impl.h" #include <utility> #include "apps/modular/lib/app/connect.h" #include "flutter/content_handler/app.h" #include "flutter/content_handler/runtime_holder.h" #include "lib/ftl/logging.h" #include "lib/mtl/vmo/vector.h" namespace flutter_runner { ApplicationControllerImpl::ApplicationControllerImpl( App* app, modular::ApplicationPackagePtr application, modular::ApplicationStartupInfoPtr startup_info, fidl::InterfaceRequest<modular::ApplicationController> controller) : app_(app), binding_(this) { if (controller.is_pending()) { binding_.Bind(std::move(controller)); binding_.set_connection_error_handler([this] { app_->Destroy(this); // |this| has been deleted at this point. }); } std::vector<char> bundle; if (!mtl::VectorFromVmo(std::move(application->data), &bundle)) { FTL_LOG(ERROR) << "Failed to receive bundle."; return; } // TODO(abarth): The Dart code should end up with outgoing_services. if (startup_info->outgoing_services) { service_provider_bindings_.AddBinding( this, std::move(startup_info->outgoing_services)); } url_ = startup_info->url; runtime_holder_.reset(new RuntimeHolder()); // TODO(abarth): The Dart code should end up with environment. modular::ServiceProviderPtr environment_services; modular::ApplicationEnvironmentPtr::Create( std::move(startup_info->environment)) ->GetServices(GetProxy(&environment_services)); runtime_holder_->Init(std::move(environment_services), std::move(bundle)); } ApplicationControllerImpl::~ApplicationControllerImpl() = default; void ApplicationControllerImpl::Kill(const KillCallback& callback) { runtime_holder_.reset(); app_->Destroy(this); // |this| has been deleted at this point. } void ApplicationControllerImpl::Detach() { binding_.set_connection_error_handler(ftl::Closure()); } void ApplicationControllerImpl::ConnectToService( const fidl::String& service_name, mx::channel client_handle) { if (service_name == mozart::ViewProvider::Name_) { view_provider_bindings_.AddBinding( this, fidl::InterfaceRequest<mozart::ViewProvider>(std::move(client_handle))); } } void ApplicationControllerImpl::CreateView( fidl::InterfaceRequest<mozart::ViewOwner> view_owner_request, fidl::InterfaceRequest<modular::ServiceProvider> services) { runtime_holder_->CreateView(url_, std::move(view_owner_request), std::move(services)); } } // namespace flutter_runner <|endoftext|>
<commit_before> #include <cstdio> #include "main.h" class A { public: int a() { } }; <commit_msg>remove duplicated include directives.<commit_after> #include "main.h" class A { public: int a() { } }; <|endoftext|>
<commit_before>// Copyright (c) 2017 Pierre Moreau // // 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 <cstring> #include <iostream> #include <vector> #include "source/spirv_target_env.h" #include "spirv-tools/libspirv.hpp" #include "spirv-tools/linker.hpp" #include "tools/io.h" void print_usage(char* argv0) { printf( R"(%s - Link SPIR-V binary files together. USAGE: %s [options] <filename> [<filename> ...] The SPIR-V binaries are read from the different <filename>. NOTE: The linker is a work in progress. Options: -h, --help Print this help. -o Name of the resulting linked SPIR-V binary. --create-library Link the binaries into a library, keeping all exported symbols. --version Display linker version information --target-env {vulkan1.0|spv1.0|spv1.1|spv1.2|opencl2.1|opencl2.2} Use Vulkan1.0/SPIR-V1.0/SPIR-V1.1/SPIR-V1.2/OpenCL-2.1/OpenCL2.2 validation rules. )", argv0, argv0); } int main(int argc, char** argv) { std::vector<const char*> inFiles; const char* outFile = nullptr; spv_target_env target_env = SPV_ENV_UNIVERSAL_1_0; spvtools::LinkerOptions options; bool continue_processing = true; int return_code = 0; for (int argi = 1; continue_processing && argi < argc; ++argi) { const char* cur_arg = argv[argi]; if ('-' == cur_arg[0]) { if (0 == strcmp(cur_arg, "-o")) { if (argi + 1 < argc) { if (!outFile) { outFile = argv[++argi]; } else { fprintf(stderr, "error: More than one output file specified\n"); continue_processing = false; return_code = 1; } } else { fprintf(stderr, "error: Missing argument to %s\n", cur_arg); continue_processing = false; return_code = 1; } } else if (0 == strcmp(cur_arg, "--create-library")) { options.SetCreateLibrary(true); } else if (0 == strcmp(cur_arg, "--version")) { printf("%s\n", spvSoftwareVersionDetailsString()); // TODO(dneto): Add OpenCL 2.2 at least. printf("Targets:\n %s\n %s\n %s\n", spvTargetEnvDescription(SPV_ENV_UNIVERSAL_1_1), spvTargetEnvDescription(SPV_ENV_VULKAN_1_0), spvTargetEnvDescription(SPV_ENV_UNIVERSAL_1_2)); continue_processing = false; return_code = 0; } else if (0 == strcmp(cur_arg, "--help") || 0 == strcmp(cur_arg, "-h")) { print_usage(argv[0]); continue_processing = false; return_code = 0; } else if (0 == strcmp(cur_arg, "--target-env")) { if (argi + 1 < argc) { const auto env_str = argv[++argi]; if (!spvParseTargetEnv(env_str, &target_env)) { fprintf(stderr, "error: Unrecognized target env: %s\n", env_str); continue_processing = false; return_code = 1; } } else { fprintf(stderr, "error: Missing argument to --target-env\n"); continue_processing = false; return_code = 1; } } } else { inFiles.push_back(cur_arg); } } // Exit if command line parsing was not successful. if (!continue_processing) { return return_code; } if (inFiles.empty()) { fprintf(stderr, "error: No input file specified\n"); return 1; } std::vector<std::vector<uint32_t>> contents(inFiles.size()); for (size_t i = 0u; i < inFiles.size(); ++i) { if (!ReadFile<uint32_t>(inFiles[i], "rb", &contents[i])) return 1; } spvtools::Linker linker(target_env); linker.SetMessageConsumer([](spv_message_level_t level, const char*, const spv_position_t& position, const char* message) { switch (level) { case SPV_MSG_FATAL: case SPV_MSG_INTERNAL_ERROR: case SPV_MSG_ERROR: std::cerr << "error: " << position.index << ": " << message << std::endl; break; case SPV_MSG_WARNING: std::cout << "warning: " << position.index << ": " << message << std::endl; break; case SPV_MSG_INFO: std::cout << "info: " << position.index << ": " << message << std::endl; break; default: break; } }); std::vector<uint32_t> linkingResult; bool succeed = linker.Link(contents, linkingResult, options); if (!WriteFile<uint32_t>(outFile, "wb", linkingResult.data(), linkingResult.size())) return 1; return !succeed; } <commit_msg>Linker: Fix incorrect exit status.<commit_after>// Copyright (c) 2017 Pierre Moreau // // 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 <cstring> #include <iostream> #include <vector> #include "source/spirv_target_env.h" #include "spirv-tools/libspirv.hpp" #include "spirv-tools/linker.hpp" #include "tools/io.h" void print_usage(char* argv0) { printf( R"(%s - Link SPIR-V binary files together. USAGE: %s [options] <filename> [<filename> ...] The SPIR-V binaries are read from the different <filename>. NOTE: The linker is a work in progress. Options: -h, --help Print this help. -o Name of the resulting linked SPIR-V binary. --create-library Link the binaries into a library, keeping all exported symbols. --version Display linker version information --target-env {vulkan1.0|spv1.0|spv1.1|spv1.2|opencl2.1|opencl2.2} Use Vulkan1.0/SPIR-V1.0/SPIR-V1.1/SPIR-V1.2/OpenCL-2.1/OpenCL2.2 validation rules. )", argv0, argv0); } int main(int argc, char** argv) { std::vector<const char*> inFiles; const char* outFile = nullptr; spv_target_env target_env = SPV_ENV_UNIVERSAL_1_0; spvtools::LinkerOptions options; bool continue_processing = true; int return_code = 0; for (int argi = 1; continue_processing && argi < argc; ++argi) { const char* cur_arg = argv[argi]; if ('-' == cur_arg[0]) { if (0 == strcmp(cur_arg, "-o")) { if (argi + 1 < argc) { if (!outFile) { outFile = argv[++argi]; } else { fprintf(stderr, "error: More than one output file specified\n"); continue_processing = false; return_code = 1; } } else { fprintf(stderr, "error: Missing argument to %s\n", cur_arg); continue_processing = false; return_code = 1; } } else if (0 == strcmp(cur_arg, "--create-library")) { options.SetCreateLibrary(true); } else if (0 == strcmp(cur_arg, "--version")) { printf("%s\n", spvSoftwareVersionDetailsString()); // TODO(dneto): Add OpenCL 2.2 at least. printf("Targets:\n %s\n %s\n %s\n", spvTargetEnvDescription(SPV_ENV_UNIVERSAL_1_1), spvTargetEnvDescription(SPV_ENV_VULKAN_1_0), spvTargetEnvDescription(SPV_ENV_UNIVERSAL_1_2)); continue_processing = false; return_code = 0; } else if (0 == strcmp(cur_arg, "--help") || 0 == strcmp(cur_arg, "-h")) { print_usage(argv[0]); continue_processing = false; return_code = 0; } else if (0 == strcmp(cur_arg, "--target-env")) { if (argi + 1 < argc) { const auto env_str = argv[++argi]; if (!spvParseTargetEnv(env_str, &target_env)) { fprintf(stderr, "error: Unrecognized target env: %s\n", env_str); continue_processing = false; return_code = 1; } } else { fprintf(stderr, "error: Missing argument to --target-env\n"); continue_processing = false; return_code = 1; } } } else { inFiles.push_back(cur_arg); } } // Exit if command line parsing was not successful. if (!continue_processing) { return return_code; } if (inFiles.empty()) { fprintf(stderr, "error: No input file specified\n"); return 1; } std::vector<std::vector<uint32_t>> contents(inFiles.size()); for (size_t i = 0u; i < inFiles.size(); ++i) { if (!ReadFile<uint32_t>(inFiles[i], "rb", &contents[i])) return 1; } spvtools::Linker linker(target_env); linker.SetMessageConsumer([](spv_message_level_t level, const char*, const spv_position_t& position, const char* message) { switch (level) { case SPV_MSG_FATAL: case SPV_MSG_INTERNAL_ERROR: case SPV_MSG_ERROR: std::cerr << "error: " << position.index << ": " << message << std::endl; break; case SPV_MSG_WARNING: std::cout << "warning: " << position.index << ": " << message << std::endl; break; case SPV_MSG_INFO: std::cout << "info: " << position.index << ": " << message << std::endl; break; default: break; } }); std::vector<uint32_t> linkingResult; spv_result_t status = linker.Link(contents, linkingResult, options); if (!WriteFile<uint32_t>(outFile, "wb", linkingResult.data(), linkingResult.size())) return 1; return status == SPV_SUCCESS ? 0 : 1; } <|endoftext|>
<commit_before>#pragma once namespace ODLib { /// <summary> /// Singleton template class. /// </summary> /// <typeparam name="T">The type of the singleton.</typeparam> template<typename T> class Singleton { public: /// <summary> /// Construct the class. /// </summary> /// <returns>The instance of the class.</returns> template<typename... Args> static T* Construct(Args&& ...args) { std::call_once(m_constructFlag, [&]() { m_instance = new T(std::forward<Args>(args)...); std::atexit(Release); }); return m_instance; } /// <summary> /// Get the instance of the singleton, construct it if needed. /// </summary> /// <returns>The instance of the class.</returns> static T* GetInstance() { if (IsReleased() == true) { return Construct(); } return m_instance; } /// <summary> /// Check if the singleton is released. /// </summary> /// <returns>true if it is released, false otherwise.</returns> static const bool IsReleased() { return m_instance == nullptr; } /// <summary> /// Release the singleton. /// </summary> static void Release() { if (IsReleased() == false) { std::call_once(m_releaseFlag, [&]() { delete m_instance; m_instance = nullptr; }); } } protected: Singleton() = default; virtual ~Singleton() = default; private: Singleton(Singleton const&) = delete; Singleton& operator=(Singleton const&) = delete; static T* m_instance; static std::once_flag m_constructFlag; static std::once_flag m_releaseFlag; }; template<typename T> T* Singleton<T>::m_instance = nullptr; template<typename T> std::once_flag Singleton<T>::m_constructFlag; template<typename T> std::once_flag Singleton<T>::m_releaseFlag; }<commit_msg>Don't allow move for "Singleton" class<commit_after>#pragma once namespace ODLib { /// <summary> /// Singleton template class. /// </summary> /// <typeparam name="T">The type of the singleton.</typeparam> template<typename T> class Singleton { public: /// <summary> /// Construct the class. /// </summary> /// <returns>The instance of the class.</returns> template<typename... Args> static T* Construct(Args&& ...args) { std::call_once(m_constructFlag, [&]() { m_instance = new T(std::forward<Args>(args)...); std::atexit(Release); }); return m_instance; } /// <summary> /// Get the instance of the singleton, construct it if needed. /// </summary> /// <returns>The instance of the class.</returns> static T* GetInstance() { if (IsReleased() == true) { return Construct(); } return m_instance; } /// <summary> /// Check if the singleton is released. /// </summary> /// <returns>true if it is released, false otherwise.</returns> static const bool IsReleased() { return m_instance == nullptr; } /// <summary> /// Release the singleton. /// </summary> static void Release() { if (IsReleased() == false) { std::call_once(m_releaseFlag, [&]() { delete m_instance; m_instance = nullptr; }); } } protected: Singleton() = default; virtual ~Singleton() = default; private: Singleton(const Singleton&) = delete; Singleton(Singleton&&) = delete; Singleton& operator=(const Singleton&) = delete; Singleton& operator=(Singleton&&) = delete; static T* m_instance; static std::once_flag m_constructFlag; static std::once_flag m_releaseFlag; }; template<typename T> T* Singleton<T>::m_instance = nullptr; template<typename T> std::once_flag Singleton<T>::m_constructFlag; template<typename T> std::once_flag Singleton<T>::m_releaseFlag; }<|endoftext|>
<commit_before>/* The MIT License (MIT) Copyright (c) 2013 Daniel Mansfield 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 <iostream> #include <string> #include <vector> #include <list> #include <utility> #include <cstdlib> #include <ctime> #include "atlas.hpp" #include "item.hpp" #include "weapon.hpp" #include "armour.hpp" #include "inventory.hpp" #include "creature.hpp" #include "dialogue.hpp" #include "area.hpp" #include "battle.hpp" // New character menu Creature dialogue_newchar(); // Character information menu, displays the items the player has, their // current stats etc. void dialogue_menu(Creature& player); int main(void) { std::vector<Creature> creatureAtlas; std::vector<Item> itemAtlas; std::vector<Weapon> weaponAtlas; std::vector<Armour> armourAtlas; std::vector<Area> areaAtlas; Creature player; // Build the atlases buildatlas_creature(creatureAtlas); buildatlas_item(itemAtlas); buildatlas_weapon(weaponAtlas); buildatlas_armour(armourAtlas); buildatlas_area(areaAtlas, itemAtlas, weaponAtlas, armourAtlas, creatureAtlas); // Seed the random number generator with the system time, so the // random numbers produced by rand() will be different each time srand(time(NULL)); // Main game menu dialogue int result = Dialogue( "Welcome!", {"New Game"}).activate(); switch(result) { case 1: player = dialogue_newchar(); break; default: return 0; break; } // Set the current area to be the first area in the atlas, essentially // placing the player there upon game start Area* currentArea = &(areaAtlas[0]); // Play the game until a function breaks the loop and closes it while(1) { // If the player has died then inform them as such and close // the program if(player.health <= 0) { std::cout << "\t----YOU DIED----\n Game Over\n"; return 0; } // If the area the player is in has any creatures inside it, // then begin a battle with the last creature in the list // before moving on the next one. This makes the creature // list act like a stack if(currentArea->creatures.size() > 0) { for(int i = currentArea->creatures.size() - 1; i >= 0; --i) { Battle(&player, currentArea->creatures[i]).run(); // Remove the creature from the area. This is fine to do // because if the player wins the creature will not respawn, // and if the creature wins the player isn't around to see it // (This does break the 'non-mutable' feature of the atlases, // but doing so saves a lot of memory, as we don't need to keep // two versions of each area) currentArea->creatures.pop_back(); } } // Activate the current area's dialogue result = currentArea->dialogue.activate(); // These could be moved inside of the area code using an event // style system, but that allows for much less flexibility with // what happens in each area. Since we're defining the areas in // code anyway, sticking with this isn't too much of a problem, // and it keeps things easy to understand if(currentArea == &(areaAtlas[0])) { switch(result) { // Open the menu case 0: dialogue_menu(player); break; case 1: // Move to area 1 currentArea = &(areaAtlas[1]); break; case 2: // Search the area currentArea->search(player); break; default: break; } } else if(currentArea == &(areaAtlas[1])) { switch(result) { // Open the menu case 0: dialogue_menu(player); break; // Move to area 0 case 1: currentArea = &(areaAtlas[0]); break; // Search the area case 2: currentArea->search(player); break; default: break; } } } return 0; } // Create a new character Creature dialogue_newchar() { // Ask for a name and class // Name does not use a dialogue since dialogues only request options, // not string input. Could be generalised into its own TextInput // class, but not really necessary std::cout << "Choose your name" << std::endl; std::string name; std::cin >> name; int result = Dialogue( "Choose your class", {"Fighter", "Rogue"}).activate(); switch(result) { // Fighter class favours health and strength case 1: return Creature(name, 35, 20, 10, 5, 10.0, 1, "Fighter"); break; // Rogue class favours dexterity and hit rate case 2: return Creature(name, 30, 5, 10, 20, 15.0, 1, "Fighter"); break; // Default case that should never happen, but it's good to be safe default: return Creature(name, 30, 10, 10, 10, 10.0, 1, "Adventurer"); break; } } void dialogue_menu(Creature& player) { // Output the menu int result = Dialogue( "Menu\n====", {"Items", "Equipment", "Character"}).activate(); switch(result) { // Print the items that the player owns case 1: std::cout << "Items\n=====\n"; player.inventory.print(); std::cout << "----------------\n"; break; // Print the equipment that the player is wearing (if they are // wearing anything) and then ask if they want to equip a weapon // or some armour case 2: { std::cout << "Equipment\n=========\n"; std::cout << "Head: " << (player.equippedArmour[Armour::Slot::HEAD] != nullptr ? player.equippedArmour[Armour::Slot::HEAD]->name : "Nothing") << std::endl; std::cout << "Torso: " << (player.equippedArmour[Armour::Slot::TORSO] != nullptr ? player.equippedArmour[Armour::Slot::TORSO]->name : "Nothing") << std::endl; std::cout << "Legs: " << (player.equippedArmour[Armour::Slot::LEGS] != nullptr ? player.equippedArmour[Armour::Slot::LEGS]->name : "Nothing") << std::endl; std::cout << "Weapon: " << (player.equippedWeapon != nullptr ? player.equippedWeapon->name : "Nothing") << std::endl; int result2 = Dialogue( "", {"Equip Armour", "Equip Weapon", "Close"}).activate(); // Equipping armour if(result2 == 1) { int userInput = 0; // Cannot equip armour if they do not have any // Print a list of the armour and retrieve the amount // of armour in one go int numItems = player.inventory.print_armour(true); if(numItems == 0) break; while(!userInput) { // Choose a piece of armour to equip std::cout << "Equip which item?" << std::endl; std::cin >> userInput; // Equipment is numbered but is stored in a list, // so the number must be converted into a list element if(userInput >= 1 && userInput <= numItems) { int i = 1; for(auto it : player.inventory.armour) { if(i++ == userInput) { // Equip the armour if it is found player.equipArmour(it.first); break; } } } } } // Equip a weapon, using the same algorithms as for armour else if(result2 == 2) { int userInput = 0; int numItems = player.inventory.print_weapons(true); if(numItems == 0) break; while(!userInput) { std::cout << "Equip which item?" << std::endl; std::cin >> userInput; if(userInput >= 1 && userInput <= numItems) { int i = 1; for(auto it : player.inventory.weapons) { if(i++ == userInput) { player.equipWeapon(it.first); break; } } } } } std::cout << "----------------\n"; break; } // Output the character information, including name, class (if // they have one), stats, level, and experience case 3: std::cout << "Character\n=========\n"; std::cout << player.name; if(player.className != "") std::cout << " the " << player.className; std::cout << std::endl; std::cout << "HP: " << player.health << " / " << player.maxHealth << std::endl; std::cout << "Str: " << player.str << std::endl; std::cout << "End: " << player.end << std::endl; std::cout << "Dex: " << player.dex << std::endl; std::cout << "Lvl: " << player.level << " (" << player.exp; std::cout << " / " << player.expToLevel(player.level+1) << ")" << std::endl; std::cout << "----------------\n"; break; default: break; } return; } <commit_msg>Simplified area menu handling by moving the menu<commit_after>/* The MIT License (MIT) Copyright (c) 2013 Daniel Mansfield 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 <iostream> #include <string> #include <vector> #include <list> #include <utility> #include <cstdlib> #include <ctime> #include "atlas.hpp" #include "item.hpp" #include "weapon.hpp" #include "armour.hpp" #include "inventory.hpp" #include "creature.hpp" #include "dialogue.hpp" #include "area.hpp" #include "battle.hpp" // New character menu Creature dialogue_newchar(); // Character information menu, displays the items the player has, their // current stats etc. void dialogue_menu(Creature& player); int main(void) { std::vector<Creature> creatureAtlas; std::vector<Item> itemAtlas; std::vector<Weapon> weaponAtlas; std::vector<Armour> armourAtlas; std::vector<Area> areaAtlas; Creature player; // Build the atlases buildatlas_creature(creatureAtlas); buildatlas_item(itemAtlas); buildatlas_weapon(weaponAtlas); buildatlas_armour(armourAtlas); buildatlas_area(areaAtlas, itemAtlas, weaponAtlas, armourAtlas, creatureAtlas); // Seed the random number generator with the system time, so the // random numbers produced by rand() will be different each time srand(time(NULL)); // Main game menu dialogue int result = Dialogue( "Welcome!", {"New Game"}).activate(); switch(result) { case 1: player = dialogue_newchar(); break; default: return 0; break; } // Set the current area to be the first area in the atlas, essentially // placing the player there upon game start Area* currentArea = &(areaAtlas[0]); // Play the game until a function breaks the loop and closes it while(1) { // If the player has died then inform them as such and close // the program if(player.health <= 0) { std::cout << "\t----YOU DIED----\n Game Over\n"; return 0; } // If the area the player is in has any creatures inside it, // then begin a battle with the last creature in the list // before moving on the next one. This makes the creature // list act like a stack if(currentArea->creatures.size() > 0) { for(int i = currentArea->creatures.size() - 1; i >= 0; --i) { Battle(&player, currentArea->creatures[i]).run(); // Remove the creature from the area. This is fine to do // because if the player wins the creature will not respawn, // and if the creature wins the player isn't around to see it // (This does break the 'non-mutable' feature of the atlases, // but doing so saves a lot of memory, as we don't need to keep // two versions of each area) currentArea->creatures.pop_back(); } } // Activate the current area's dialogue result = currentArea->dialogue.activate(); // These could be moved inside of the area code using an event // style system, but that allows for much less flexibility with // what happens in each area. Since we're defining the areas in // code anyway, sticking with this isn't too much of a problem, // and it keeps things easy to understand if(result == 0) { // Open the menu dialogue_menu(player); continue; } if(currentArea == &(areaAtlas[0])) { switch(result) { case 1: // Move to area 1 currentArea = &(areaAtlas[1]); break; case 2: // Search the area currentArea->search(player); break; default: break; } } else if(currentArea == &(areaAtlas[1])) { switch(result) { // Move to area 0 case 1: currentArea = &(areaAtlas[0]); break; // Search the area case 2: currentArea->search(player); break; default: break; } } } return 0; } // Create a new character Creature dialogue_newchar() { // Ask for a name and class // Name does not use a dialogue since dialogues only request options, // not string input. Could be generalised into its own TextInput // class, but not really necessary std::cout << "Choose your name" << std::endl; std::string name; std::cin >> name; int result = Dialogue( "Choose your class", {"Fighter", "Rogue"}).activate(); switch(result) { // Fighter class favours health and strength case 1: return Creature(name, 35, 20, 10, 5, 10.0, 1, "Fighter"); break; // Rogue class favours dexterity and hit rate case 2: return Creature(name, 30, 5, 10, 20, 15.0, 1, "Fighter"); break; // Default case that should never happen, but it's good to be safe default: return Creature(name, 30, 10, 10, 10, 10.0, 1, "Adventurer"); break; } } void dialogue_menu(Creature& player) { // Output the menu int result = Dialogue( "Menu\n====", {"Items", "Equipment", "Character"}).activate(); switch(result) { // Print the items that the player owns case 1: std::cout << "Items\n=====\n"; player.inventory.print(); std::cout << "----------------\n"; break; // Print the equipment that the player is wearing (if they are // wearing anything) and then ask if they want to equip a weapon // or some armour case 2: { std::cout << "Equipment\n=========\n"; std::cout << "Head: " << (player.equippedArmour[Armour::Slot::HEAD] != nullptr ? player.equippedArmour[Armour::Slot::HEAD]->name : "Nothing") << std::endl; std::cout << "Torso: " << (player.equippedArmour[Armour::Slot::TORSO] != nullptr ? player.equippedArmour[Armour::Slot::TORSO]->name : "Nothing") << std::endl; std::cout << "Legs: " << (player.equippedArmour[Armour::Slot::LEGS] != nullptr ? player.equippedArmour[Armour::Slot::LEGS]->name : "Nothing") << std::endl; std::cout << "Weapon: " << (player.equippedWeapon != nullptr ? player.equippedWeapon->name : "Nothing") << std::endl; int result2 = Dialogue( "", {"Equip Armour", "Equip Weapon", "Close"}).activate(); // Equipping armour if(result2 == 1) { int userInput = 0; // Cannot equip armour if they do not have any // Print a list of the armour and retrieve the amount // of armour in one go int numItems = player.inventory.print_armour(true); if(numItems == 0) break; while(!userInput) { // Choose a piece of armour to equip std::cout << "Equip which item?" << std::endl; std::cin >> userInput; // Equipment is numbered but is stored in a list, // so the number must be converted into a list element if(userInput >= 1 && userInput <= numItems) { int i = 1; for(auto it : player.inventory.armour) { if(i++ == userInput) { // Equip the armour if it is found player.equipArmour(it.first); break; } } } } } // Equip a weapon, using the same algorithms as for armour else if(result2 == 2) { int userInput = 0; int numItems = player.inventory.print_weapons(true); if(numItems == 0) break; while(!userInput) { std::cout << "Equip which item?" << std::endl; std::cin >> userInput; if(userInput >= 1 && userInput <= numItems) { int i = 1; for(auto it : player.inventory.weapons) { if(i++ == userInput) { player.equipWeapon(it.first); break; } } } } } std::cout << "----------------\n"; break; } // Output the character information, including name, class (if // they have one), stats, level, and experience case 3: std::cout << "Character\n=========\n"; std::cout << player.name; if(player.className != "") std::cout << " the " << player.className; std::cout << std::endl; std::cout << "HP: " << player.health << " / " << player.maxHealth << std::endl; std::cout << "Str: " << player.str << std::endl; std::cout << "End: " << player.end << std::endl; std::cout << "Dex: " << player.dex << std::endl; std::cout << "Lvl: " << player.level << " (" << player.exp; std::cout << " / " << player.expToLevel(player.level+1) << ")" << std::endl; std::cout << "----------------\n"; break; default: break; } return; } <|endoftext|>
<commit_before>#include <stdexcept> #include <limits> #include <algorithm> #include <array> #include <memory> #include <iomanip> #include <string> #include <sstream> #include <iostream> #include <fstream> #include <vector> #include <sys/stat.h> #include <cerrno> #include <cstring> #include <system_error> #include <openssl/md5.h> #include <openssl/sha.h> #include <openssl/evp.h> #include <stdio.h> #include <stdlib.h> #include <sys/mman.h> #include <fcntl.h> #include <string.h> #include "curleasy.h" const std::string version("0.1.0"); const std::string listing("http://nwn.efupw.com/rootdir/index.dat"); const std::string patch_dir("http://nwn.efupw.com/rootdir/patch/"); const std::string file_checksum(const std::string &path); std::vector<std::string> &split(const std::string &s, char delim, std::vector<std::string> &elems) { std::stringstream ss(s); std::string item; while (std::getline(ss, item, delim)) { elems.push_back(item); } return elems; } std::vector<std::string> split(const std::string &s, char delim) { std::vector<std::string> elems; return split(s, delim, elems); } class Target { public: enum class Status { Nonexistent, Outdated, Current }; explicit Target(const std::string &name, const std::string &checksum): m_name(name.find_first_of('/') == std::string::npos ? name : name, name.find_first_of('/') + 1, name.size() - 1), m_checksum(checksum) {} std::string name() const { return m_name; } const std::string checksum() const { return m_checksum; } void fetch() { std::cout << "Statting target " << name() << "..."; std::string path; std::fstream fs(name(), std::ios_base::in); if (!fs.good()) { fs.close(); std::cout << " doesn't exist, creating new." << std::endl; auto elems = split(name(), '/'); for (size_t i = 0, k = elems.size(); i < k; ++i) { const std::string &s(elems[i]); if (s.size() && s != ".") { path.append((i > 0 ? "/" : "") + s); // i indicates a directory. if (i < k - 1) { auto status = mkdir(path.c_str(), S_IRWXU); if (status == -1) { std::error_code err(errno, std::generic_category()); if (err != std::errc::file_exists) { std::cout << "error making dir: " << path << ": " << err.message() << std::endl; } } } } } fs.open(path, std::ios_base::out); if (!fs.good()) { fs.close(); std::cout << "Failed to create file: " << path << std::endl; } else { fs.close(); do_fetch(); return; } } if (fs.good()) { fs.close(); if (status() == Status::Current) { std::cout << " already up to date." << std::endl; } else { std::cout << " outdated, downloading new." << std::endl; do_fetch(); } } } Status status() { std::ifstream is(name()); if (!is.good()) { return Status::Nonexistent; } is.close(); auto calcsum(file_checksum(name())); if (calcsum == checksum()) { return Status::Current; } else { return Status::Outdated; } } private: void do_fetch() { std::string s; std::string url(patch_dir + name()); CurlEasy curl(url); curl.write_to(s); curl.perform(); std::ofstream ofs(name()); if (ofs.good()) { ofs << s; ofs.close(); std::cout << "Finished downloading " << name() << std::endl; } else { std::cout << "Couldn't write to " << name() << std::endl; } } std::string m_name; std::string m_checksum; }; std::ostream& operator<<(std::ostream &os, const Target &t) { return os << "name: " << t.name() << ", checksum: " << t.checksum(); } const std::string file_checksum(const std::string &path) { #ifdef md_md5 auto md = EVP_md5(); const int md_len = MD5_DIGEST_LENGTH; #else auto md = EVP_sha1(); const int md_len = SHA_DIGEST_LENGTH; #endif std::array<unsigned char, md_len> result; EVP_MD_CTX *mdctx = nullptr; std::ifstream is(path, std::ifstream::binary); if (!is.good()) { std::cout << "Couldn't open file " << path << " for checksumming." << std::endl; return std::string(); } const int length = 8192; std::array<unsigned char, length> buffer; auto buf = reinterpret_cast<char *>(buffer.data()); mdctx = EVP_MD_CTX_create(); int status = EVP_DigestInit_ex(mdctx, md, nullptr); while (status && is) { is.read(buf, length); status = EVP_DigestUpdate(mdctx, buffer.data(), is.gcount()); } status = EVP_DigestFinal_ex(mdctx, result.data(), nullptr); EVP_MD_CTX_destroy(mdctx); std::stringstream calcsum; calcsum << std::setfill('0'); for (unsigned char c : result) { calcsum << std::hex << std::setw(2) << static_cast<unsigned int>(c); } /* std::for_each(std::begin(result), std::end(result), [&calcsum](unsigned char c) { calcsum << std::hex << std::setw(2) << static_cast<unsigned int>(c); }); */ return calcsum.str(); } namespace Options { bool version(const std::string &val) { return val == "version"; } bool update_path(const std::string &val) { return val == "update path"; } }; bool confirm() { char c; do { std::cin >> c; std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); c = tolower(c); } while (c != 'y' && c != 'n'); return c == 'y'; } class EfuLauncher { public: explicit EfuLauncher(const std::string path, const std::string update_check): m_path(path), m_update_check(update_check), m_has_update(false) {} bool has_update() { if (m_has_update) { return m_has_update; } std::string fetch; CurlEasy curl(m_update_check.c_str()); curl.write_to(fetch); curl.perform(); std::vector<std::string> lines(split(fetch, '\n')); fetch.clear(); for (auto beg = std::begin(lines), end = std::end(lines); beg != end; ++beg) { auto keyvals(split(*beg, '=')); if (keyvals.size() != 2) { std::cerr << "Malformed option: " + *beg + ", aborting launcher update check." << std::endl; return m_has_update = false; } if (Options::version(keyvals[0])) { const std::string version_test(keyvals[1]); m_has_update = version_test != version; } else if (Options::update_path(keyvals[0])) { m_update_path = keyvals[1]; } } return m_has_update; } bool get_update() { if (!m_has_update || m_update_path.empty()) { return m_has_update = false; } return !(m_has_update = false); } void stat_targets() { std::string fetch; CurlEasy curl(listing); curl.write_to(fetch); curl.perform(); auto lines(split(fetch, '\n')); std::vector<Target> new_targets, old_targets; for (auto beg = std::begin(lines), end = std::end(lines); beg != end; ++beg) { auto data(split(*beg, '@')); Target t(data[0], data[data.size() - 1]); auto status = t.status(); if (status == Target::Status::Nonexistent) { new_targets.push_back(std::move(t)); } else if (status == Target::Status::Outdated) { old_targets.push_back(std::move(t)); } } if (new_targets.size()) { std::cout << "New targets: " << new_targets.size() << std::endl; for (auto &t : new_targets) { std::cout << "- " << t.name() << std::endl; } } else { std::cout << "No new targets." << std::endl; } if (old_targets.size()) { std::cout << "Outdated targets: " << old_targets.size() << std::endl; for (auto &t : old_targets) { std::cout << "- " << t.name() << std::endl; } } else { std::cout << "No targets out of date." << std::endl; } #ifndef DEBUG for (auto &t : new_targets) { t.fetch(); } for (auto &t : old_targets) { t.fetch(); } #endif } private: const std::string path() const { return m_path; } const std::string m_path; const std::string m_update_check; std::string m_update_path; bool m_has_update; }; int main(int argc, char *argv[]) { CurlGlobalInit curl_global; EfuLauncher l(argv[0], "https://raw.github.com/commonquail/efulauncher/"\ "master/versioncheck"); if (l.has_update()) { std::cout << "A new version of the launcher is available."\ " Would you like to download it (y/n)?" << std::endl; bool download(confirm()); if (!download) { std::cout << "It is strongly recommended to always use"\ " the latest launcher. Would you like to download it (y/n)?" << std::endl; download = confirm(); } if (download) { // Download. std::cout << "Downloading new launcher..." << std::endl; if (l.get_update()) { std::cout << "Done. Please extract and run the new launcher." << std::endl; } return 0; } } l.stat_targets(); return 0; } <commit_msg>Move directory creation to free function.<commit_after>#include <stdexcept> #include <limits> #include <algorithm> #include <array> #include <memory> #include <iomanip> #include <string> #include <sstream> #include <iostream> #include <fstream> #include <vector> #include <sys/stat.h> #include <cerrno> #include <cstring> #include <system_error> #include <openssl/md5.h> #include <openssl/sha.h> #include <openssl/evp.h> #include <stdio.h> #include <stdlib.h> #include <sys/mman.h> #include <fcntl.h> #include <string.h> #include "curleasy.h" const std::string version("0.1.0"); const std::string listing("http://nwn.efupw.com/rootdir/index.dat"); const std::string patch_dir("http://nwn.efupw.com/rootdir/patch/"); const std::string file_checksum(const std::string &path); std::vector<std::string> &split(const std::string &s, char delim, std::vector<std::string> &elems) { std::stringstream ss(s); std::string item; while (std::getline(ss, item, delim)) { elems.push_back(item); } return elems; } std::vector<std::string> split(const std::string &s, char delim) { std::vector<std::string> elems; return split(s, delim, elems); } void make_dir(const std::string &path) { auto elems = split(path, '/'); std::string descend; for (size_t i = 0, k = elems.size() - 1; i < k; ++i) { const std::string &s(elems[i]); if (s.size() && s != ".") { descend.append((i > 0 ? "/" : "") + s); auto status = mkdir(descend.c_str(), S_IRWXU); if (status == -1) { std::error_code err(errno, std::generic_category()); if (err != std::errc::file_exists) { std::cout << "error making dir: " << descend << ": " << err.message() << std::endl; } } } } } class Target { public: enum class Status { Nonexistent, Outdated, Current }; explicit Target(const std::string &name, const std::string &checksum): m_name(name.find_first_of('/') == std::string::npos ? name : name, name.find_first_of('/') + 1, name.size() - 1), m_checksum(checksum) {} std::string name() const { return m_name; } const std::string checksum() const { return m_checksum; } void fetch() { std::cout << "Statting target " << name() << "..."; std::fstream fs(name(), std::ios_base::in); if (!fs.good()) { fs.close(); std::cout << " doesn't exist, creating new." << std::endl; make_dir(name()); fs.open(name(), std::ios_base::out); if (!fs.good()) { fs.close(); std::cout << "Failed to create file: " << name() << std::endl; } else { fs.close(); do_fetch(); return; } } if (fs.good()) { fs.close(); if (status() == Status::Current) { std::cout << " already up to date." << std::endl; } else { std::cout << " outdated, downloading new." << std::endl; do_fetch(); } } } Status status() { std::ifstream is(name()); if (!is.good()) { return Status::Nonexistent; } is.close(); auto calcsum(file_checksum(name())); if (calcsum == checksum()) { return Status::Current; } else { return Status::Outdated; } } private: void do_fetch() { std::string s; std::string url(patch_dir + name()); CurlEasy curl(url); curl.write_to(s); curl.perform(); std::ofstream ofs(name()); if (ofs.good()) { ofs << s; ofs.close(); std::cout << "Finished downloading " << name() << std::endl; } else { std::cout << "Couldn't write to " << name() << std::endl; } } std::string m_name; std::string m_checksum; }; std::ostream& operator<<(std::ostream &os, const Target &t) { return os << "name: " << t.name() << ", checksum: " << t.checksum(); } const std::string file_checksum(const std::string &path) { #ifdef md_md5 auto md = EVP_md5(); const int md_len = MD5_DIGEST_LENGTH; #else auto md = EVP_sha1(); const int md_len = SHA_DIGEST_LENGTH; #endif std::array<unsigned char, md_len> result; EVP_MD_CTX *mdctx = nullptr; std::ifstream is(path, std::ifstream::binary); if (!is.good()) { std::cout << "Couldn't open file " << path << " for checksumming." << std::endl; return std::string(); } const int length = 8192; std::array<unsigned char, length> buffer; auto buf = reinterpret_cast<char *>(buffer.data()); mdctx = EVP_MD_CTX_create(); int status = EVP_DigestInit_ex(mdctx, md, nullptr); while (status && is) { is.read(buf, length); status = EVP_DigestUpdate(mdctx, buffer.data(), is.gcount()); } status = EVP_DigestFinal_ex(mdctx, result.data(), nullptr); EVP_MD_CTX_destroy(mdctx); std::stringstream calcsum; calcsum << std::setfill('0'); for (unsigned char c : result) { calcsum << std::hex << std::setw(2) << static_cast<unsigned int>(c); } /* std::for_each(std::begin(result), std::end(result), [&calcsum](unsigned char c) { calcsum << std::hex << std::setw(2) << static_cast<unsigned int>(c); }); */ return calcsum.str(); } namespace Options { bool version(const std::string &val) { return val == "version"; } bool update_path(const std::string &val) { return val == "update path"; } }; bool confirm() { char c; do { std::cin >> c; std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); c = tolower(c); } while (c != 'y' && c != 'n'); return c == 'y'; } class EfuLauncher { public: explicit EfuLauncher(const std::string path, const std::string update_check): m_path(path), m_update_check(update_check), m_has_update(false) {} bool has_update() { if (m_has_update) { return m_has_update; } std::string fetch; CurlEasy curl(m_update_check.c_str()); curl.write_to(fetch); curl.perform(); std::vector<std::string> lines(split(fetch, '\n')); fetch.clear(); for (auto beg = std::begin(lines), end = std::end(lines); beg != end; ++beg) { auto keyvals(split(*beg, '=')); if (keyvals.size() != 2) { std::cerr << "Malformed option: " + *beg + ", aborting launcher update check." << std::endl; return m_has_update = false; } if (Options::version(keyvals[0])) { const std::string version_test(keyvals[1]); m_has_update = version_test != version; } else if (Options::update_path(keyvals[0])) { m_update_path = keyvals[1]; } } return m_has_update; } bool get_update() { if (!m_has_update || m_update_path.empty()) { return m_has_update = false; } return !(m_has_update = false); } void stat_targets() { std::string fetch; CurlEasy curl(listing); curl.write_to(fetch); curl.perform(); auto lines(split(fetch, '\n')); std::vector<Target> new_targets, old_targets; for (auto beg = std::begin(lines), end = std::end(lines); beg != end; ++beg) { auto data(split(*beg, '@')); Target t(data[0], data[data.size() - 1]); auto status = t.status(); if (status == Target::Status::Nonexistent) { new_targets.push_back(std::move(t)); } else if (status == Target::Status::Outdated) { old_targets.push_back(std::move(t)); } } if (new_targets.size()) { std::cout << "New targets: " << new_targets.size() << std::endl; for (auto &t : new_targets) { std::cout << "- " << t.name() << std::endl; } } else { std::cout << "No new targets." << std::endl; } if (old_targets.size()) { std::cout << "Outdated targets: " << old_targets.size() << std::endl; for (auto &t : old_targets) { std::cout << "- " << t.name() << std::endl; } } else { std::cout << "No targets out of date." << std::endl; } #ifndef DEBUG for (auto &t : new_targets) { t.fetch(); } for (auto &t : old_targets) { t.fetch(); } #endif } private: const std::string path() const { return m_path; } const std::string m_path; const std::string m_update_check; std::string m_update_path; bool m_has_update; }; int main(int argc, char *argv[]) { CurlGlobalInit curl_global; EfuLauncher l(argv[0], "https://raw.github.com/commonquail/efulauncher/"\ "master/versioncheck"); if (l.has_update()) { std::cout << "A new version of the launcher is available."\ " Would you like to download it (y/n)?" << std::endl; bool download(confirm()); if (!download) { std::cout << "It is strongly recommended to always use"\ " the latest launcher. Would you like to download it (y/n)?" << std::endl; download = confirm(); } if (download) { // Download. std::cout << "Downloading new launcher..." << std::endl; if (l.get_update()) { std::cout << "Done. Please extract and run the new launcher." << std::endl; } return 0; } } l.stat_targets(); return 0; } <|endoftext|>