text
stringlengths 54
60.6k
|
---|
<commit_before>/******************************************************************************
* Copyright (c) 2014, Pete Gadomski ([email protected])
*
* 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 Hobu, Inc. or Flaxen Geo Consulting 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 <pdal/pdal_test_main.hpp>
#include <pdal/Writer.hpp>
#include <pdal/StageFactory.hpp>
#include <pdal/util/Algorithm.hpp>
#include "Support.hpp"
#include "Pgtest-Support.hpp"
#include "../io/PgCommon.hpp"
using namespace pdal;
namespace { // anonymous
std::string getTestConnBase()
{
std::string s;
if ( ! testDbPort.empty() )
s += " port='" + testDbPort + "'";
if ( ! testDbHost.empty() )
s += " host='" + testDbHost + "'";
if ( ! testDbUser.empty() )
s += " user='" + testDbUser + "'";
return s;
}
std::string getConnectionString(const std::string& dbname)
{
return getTestConnBase() + " dbname='" + dbname + "'";
}
std::string getTestDBTempConn()
{
return getConnectionString(testDbTempname);
}
std::string getMasterDBConn()
{
return getConnectionString(testDbName);
}
} // anonymous namespace
Options getDbOptions()
{
Options options;
options.add(Option("connection", getTestDBTempConn()));
options.add(Option("table", "pdal-\"test\"-table")); // intentional quotes
options.add(Option("column", "p\"a")); // intentional quotes
options.add(Option("srid", "4326"));
options.add(Option("capacity", "10000"));
return options;
}
class PgpointcloudWriterTest : public testing::Test
{
public:
PgpointcloudWriterTest() : m_masterConnection(0), m_testConnection(0),
m_bSkipTests(false) {};
protected:
virtual void SetUp()
{
std::string connstr = getMasterDBConn();
m_masterConnection = pg_connect( connstr );
m_testConnection = NULL;
// Silence those pesky notices
executeOnMasterDb("SET client_min_messages TO WARNING");
dropTestDb();
std::stringstream createDbSql;
createDbSql << "CREATE DATABASE " <<
testDbTempname << " TEMPLATE template0";
try
{
executeOnMasterDb(createDbSql.str());
}
catch( const pdal_error& error )
{
m_bSkipTests = true;
return;
}
m_testConnection = pg_connect( getTestDBTempConn() );
try
{
executeOnTestDb("CREATE EXTENSION pointcloud");
}
catch( const pdal_error& error )
{
m_bSkipTests = true;
return;
}
}
void executeOnTestDb(const std::string& sql)
{
pg_execute(m_testConnection, sql);
}
virtual void TearDown()
{
if (!m_testConnection || !m_masterConnection) return;
if (m_testConnection)
{
PQfinish(m_testConnection);
}
dropTestDb();
if (m_masterConnection)
{
PQfinish(m_masterConnection);
}
}
bool shouldSkipTests() const { return m_bSkipTests; }
private:
void executeOnMasterDb(const std::string& sql)
{
pg_execute(m_masterConnection, sql);
}
void execute(PGconn* connection, const std::string& sql)
{
pg_execute(connection, sql);
}
void dropTestDb()
{
std::stringstream dropDbSql;
dropDbSql << "DROP DATABASE IF EXISTS " << testDbTempname;
executeOnMasterDb(dropDbSql.str());
}
PGconn* m_masterConnection;
PGconn* m_testConnection;
bool m_bSkipTests;
};
namespace
{
void optionsWrite(const Options& writerOps)
{
StageFactory f;
std::unique_ptr<Stage> writer(f.createStage("writers.pgpointcloud"));
std::unique_ptr<Stage> reader(f.createStage("readers.las"));
EXPECT_TRUE(writer.get());
EXPECT_TRUE(reader.get());
if (!writer.get() || !reader.get())
return;
const std::string file(Support::datapath("las/1.2-with-color.las"));
Options options;
options.add("filename", file);
reader->setOptions(options);
writer->setOptions(writerOps);
writer->setInput(*reader);
PointTable table;
writer->prepare(table);
PointViewSet written = writer->execute(table);
point_count_t count(0);
for(auto i = written.begin(); i != written.end(); ++i)
count += (*i)->size();
EXPECT_EQ(written.size(), 1U);
EXPECT_EQ(count, 1065U);
}
} // unnamed namespace
TEST_F(PgpointcloudWriterTest, write)
{
if (shouldSkipTests())
{
return;
}
optionsWrite(getDbOptions());
}
TEST_F(PgpointcloudWriterTest, writeScaled)
{
if (shouldSkipTests())
{
return;
}
Options ops = getDbOptions();
ops.add("scale_x", .01);
ops.add("scale_y", .01);
ops.add("scale_z", .01);
optionsWrite(ops);
}
TEST_F(PgpointcloudWriterTest, writeXYZ)
{
if (shouldSkipTests())
{
return;
}
Options ops = getDbOptions();
ops.add("output_dims", "X,Y,Z");
optionsWrite(ops);
PointTable table;
std::unique_ptr<Stage> reader(
StageFactory().createStage("readers.pgpointcloud"));
reader->setOptions(getDbOptions());
reader->prepare(table);
Dimension::IdList dims = table.layout()->dims();
EXPECT_EQ(dims.size(), (size_t)3);
EXPECT_TRUE(Utils::contains(dims, Dimension::Id::X));
EXPECT_TRUE(Utils::contains(dims, Dimension::Id::Y));
EXPECT_TRUE(Utils::contains(dims, Dimension::Id::Z));
}
TEST_F(PgpointcloudWriterTest, writetNoPointcloudExtension)
{
if (shouldSkipTests())
{
return;
}
StageFactory f;
std::unique_ptr<Stage> writer(f.createStage("writers.pgpointcloud"));
EXPECT_TRUE(writer.get());
executeOnTestDb("DROP EXTENSION pointcloud");
const std::string file(Support::datapath("las/1.2-with-color.las"));
const Option opt_filename("filename", file);
std::unique_ptr<Stage> reader(f.createStage("readers.las"));
EXPECT_TRUE(reader.get());
Options options;
options.add(opt_filename);
reader->setOptions(options);
writer->setOptions(getDbOptions());
writer->setInput(*reader);
PointTable table;
writer->prepare(table);
EXPECT_THROW(writer->execute(table), pdal_error);
}
<commit_msg>make test table name start with a number to simulate #1098<commit_after>/******************************************************************************
* Copyright (c) 2014, Pete Gadomski ([email protected])
*
* 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 Hobu, Inc. or Flaxen Geo Consulting 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 <pdal/pdal_test_main.hpp>
#include <pdal/Writer.hpp>
#include <pdal/StageFactory.hpp>
#include <pdal/util/Algorithm.hpp>
#include "Support.hpp"
#include "Pgtest-Support.hpp"
#include "../io/PgCommon.hpp"
using namespace pdal;
namespace { // anonymous
std::string getTestConnBase()
{
std::string s;
if ( ! testDbPort.empty() )
s += " port='" + testDbPort + "'";
if ( ! testDbHost.empty() )
s += " host='" + testDbHost + "'";
if ( ! testDbUser.empty() )
s += " user='" + testDbUser + "'";
return s;
}
std::string getConnectionString(const std::string& dbname)
{
return getTestConnBase() + " dbname='" + dbname + "'";
}
std::string getTestDBTempConn()
{
return getConnectionString(testDbTempname);
}
std::string getMasterDBConn()
{
return getConnectionString(testDbName);
}
} // anonymous namespace
Options getDbOptions()
{
Options options;
options.add(Option("connection", getTestDBTempConn()));
options.add(Option("table", "4dal-\"test\"-table")); // intentional quotes
options.add(Option("column", "p\"a")); // intentional quotes
options.add(Option("srid", "4326"));
options.add(Option("capacity", "10000"));
return options;
}
class PgpointcloudWriterTest : public testing::Test
{
public:
PgpointcloudWriterTest() : m_masterConnection(0), m_testConnection(0),
m_bSkipTests(false) {};
protected:
virtual void SetUp()
{
std::string connstr = getMasterDBConn();
m_masterConnection = pg_connect( connstr );
m_testConnection = NULL;
// Silence those pesky notices
executeOnMasterDb("SET client_min_messages TO WARNING");
dropTestDb();
std::stringstream createDbSql;
createDbSql << "CREATE DATABASE " <<
testDbTempname << " TEMPLATE template0";
try
{
executeOnMasterDb(createDbSql.str());
}
catch( const pdal_error& error )
{
m_bSkipTests = true;
return;
}
m_testConnection = pg_connect( getTestDBTempConn() );
try
{
executeOnTestDb("CREATE EXTENSION pointcloud");
}
catch( const pdal_error& error )
{
m_bSkipTests = true;
return;
}
}
void executeOnTestDb(const std::string& sql)
{
pg_execute(m_testConnection, sql);
}
virtual void TearDown()
{
if (!m_testConnection || !m_masterConnection) return;
if (m_testConnection)
{
PQfinish(m_testConnection);
}
dropTestDb();
if (m_masterConnection)
{
PQfinish(m_masterConnection);
}
}
bool shouldSkipTests() const { return m_bSkipTests; }
private:
void executeOnMasterDb(const std::string& sql)
{
pg_execute(m_masterConnection, sql);
}
void execute(PGconn* connection, const std::string& sql)
{
pg_execute(connection, sql);
}
void dropTestDb()
{
std::stringstream dropDbSql;
dropDbSql << "DROP DATABASE IF EXISTS " << testDbTempname;
executeOnMasterDb(dropDbSql.str());
}
PGconn* m_masterConnection;
PGconn* m_testConnection;
bool m_bSkipTests;
};
namespace
{
void optionsWrite(const Options& writerOps)
{
StageFactory f;
std::unique_ptr<Stage> writer(f.createStage("writers.pgpointcloud"));
std::unique_ptr<Stage> reader(f.createStage("readers.las"));
EXPECT_TRUE(writer.get());
EXPECT_TRUE(reader.get());
if (!writer.get() || !reader.get())
return;
const std::string file(Support::datapath("las/1.2-with-color.las"));
Options options;
options.add("filename", file);
reader->setOptions(options);
writer->setOptions(writerOps);
writer->setInput(*reader);
PointTable table;
writer->prepare(table);
PointViewSet written = writer->execute(table);
point_count_t count(0);
for(auto i = written.begin(); i != written.end(); ++i)
count += (*i)->size();
EXPECT_EQ(written.size(), 1U);
EXPECT_EQ(count, 1065U);
}
} // unnamed namespace
TEST_F(PgpointcloudWriterTest, write)
{
if (shouldSkipTests())
{
return;
}
optionsWrite(getDbOptions());
}
TEST_F(PgpointcloudWriterTest, writeScaled)
{
if (shouldSkipTests())
{
return;
}
Options ops = getDbOptions();
ops.add("scale_x", .01);
ops.add("scale_y", .01);
ops.add("scale_z", .01);
optionsWrite(ops);
}
TEST_F(PgpointcloudWriterTest, writeXYZ)
{
if (shouldSkipTests())
{
return;
}
Options ops = getDbOptions();
ops.add("output_dims", "X,Y,Z");
optionsWrite(ops);
PointTable table;
std::unique_ptr<Stage> reader(
StageFactory().createStage("readers.pgpointcloud"));
reader->setOptions(getDbOptions());
reader->prepare(table);
Dimension::IdList dims = table.layout()->dims();
EXPECT_EQ(dims.size(), (size_t)3);
EXPECT_TRUE(Utils::contains(dims, Dimension::Id::X));
EXPECT_TRUE(Utils::contains(dims, Dimension::Id::Y));
EXPECT_TRUE(Utils::contains(dims, Dimension::Id::Z));
}
TEST_F(PgpointcloudWriterTest, writetNoPointcloudExtension)
{
if (shouldSkipTests())
{
return;
}
StageFactory f;
std::unique_ptr<Stage> writer(f.createStage("writers.pgpointcloud"));
EXPECT_TRUE(writer.get());
executeOnTestDb("DROP EXTENSION pointcloud");
const std::string file(Support::datapath("las/1.2-with-color.las"));
const Option opt_filename("filename", file);
std::unique_ptr<Stage> reader(f.createStage("readers.las"));
EXPECT_TRUE(reader.get());
Options options;
options.add(opt_filename);
reader->setOptions(options);
writer->setOptions(getDbOptions());
writer->setInput(*reader);
PointTable table;
writer->prepare(table);
EXPECT_THROW(writer->execute(table), pdal_error);
}
<|endoftext|> |
<commit_before>#ifndef CONTROLLER_HPP
#define CONTROLLER_HPP
#include "Position6DOF.hpp"
#include "MovementQuadruple.hpp"
#include "Formation.hpp"
#include "ros/ros.h"
//Ros messages/services
#include "api_application/MoveFormation.h" // ? (D)
#include "../matlab/Vector.h"
#include "../matlab/TrackingArea.h"
#include "control_application/quadcopter_movement.h" // ? (D)
#include "api_application/SetFormation.h"
#include "api_application/Message.h"
#include "api_application/Announce.h"
#include "api_application/System.h"
#include "quadcopter_application/find_all.h"
#include "quadcopter_application/blink.h"
#include "quadcopter_application/quadcopter_status.h"
#include "control_application/BuildFormation.h"
#include "control_application/Shutdown.h"
//#include "control_application/SetQuadcopters.h"
#include "../position/IPositionReceiver.hpp"
#include <time.h>
#include <stdio.h>
#include <unistd.h>
#include <math.h>
#include <string>
#include <vector>
#include <pthread.h>
#include <list>
#include "Mutex.hpp"
#include <cmath>
#include <time.h>
#include <sstream>
#include <boost/bind.hpp>
#define THRUST_MIN 10001
#define THRUST_STAND_STILL 18001
#define THRUST_START 22000
#define THRUST_DECLINE 20000
#define THRUST_STEP 50
#define ROLL_STEP 2
#define PITCH_STEP 2
#define INVALID -1
//TODO 100% = 1?
#define LOW_BATTERY 0.05
//In seconds
#define TIME_UPDATED 1
/* For calculateMovement */
#define CALCULATE_NONE 0 // Unset
#define CALCULATE_START 1
#define CALCULATE_STABILIZE 2
#define CALCULATE_HOLD 3
#define CALCULATE_MOVE 4
#define CALCULATE_ACTIVATED 6 // QC ready to receive data from quadcoptermodul
/* Used for lists */
#define MAX_NUMBER_QUADCOPTER 10
#define POS_CHECK (current[0] != target[0]) || (current[1] != target[1]) || (current[2] != target[2])
class Controller : public IPositionReceiver {
//class Controller {
public:
Controller();
/* Initializing */
void initialize();
/* Movement and Positioning */
void convertMovement(double* const vector);
Position6DOF* getTargetPosition();
void setTargetPosition();
void updatePositions(std::vector<Vector> positions, std::vector<int> ids, std::vector<int> updates);
void sendMovement();
void sendMovementAll();
void calculateMovement();
void reachTrackedArea(std::vector<int> ids);
/* Formation also services*/
bool buildFormation(control_application::BuildFormation::Request &req, control_application::BuildFormation::Response &res);
void shutdownFormation();
/* Service to set Quadcopter IDs*/
bool setQuadcopters(control_application::SetQuadcopters::Request &req, control_application::SetQuadcopters::Response &res);
bool shutdown(control_application::Shutdown::Request &req, control_application::Shutdown::Response &res);
bool checkInput();
void emergencyRoutine(std::string message);
void moveUp(std::vector<int> ids);
void moveUpNoArg();
protected:
//Callbacks for Ros subscriber
void MoveFormationCallback(const api_application::MoveFormation::ConstPtr& msg);
void SetFormationCallback(const api_application::SetFormation::ConstPtr& msg);
void QuadStatusCallback(const quadcopter_application::quadcopter_status::ConstPtr& msg, int topicNr);
void SystemCallback(const api_application::System::ConstPtr& msg);
void stopReachTrackedArea();
private:
/* */
/* Position */
//std::vector<Position6DOF> targetPosition;
//std::vector<Position6DOF> currentPosition;
//std::vector<rpy-values> sentMovement;
//TODO Where are those lists filled/ updated? FIFO? Latest element last?
//TODO Include time somehow or how do we check if there hasn't been any input?
std::list<std::vector<Position6DOF> > listPositions;
std::list<std::vector<Position6DOF> > listTargets;
std::list<std::vector<Position6DOF> > listSendTargets;
/* Identification of Quadcopters */
//Receive data over ROS
Formation formation;
//TODO needs to be with service find all
int totalAmount;
int amount;
std::list<float[3]> formationMovement;
time_t lastFormationMovement;
time_t lastCurrent;
unsigned int senderID;
//TODO Set area
TrackingArea trackingArea;
//Mapping of int id to string id/ hardware id qc[id][uri/hardware id]
//std::vector<std::string> quadcopters;
//Mapping of quadcopter global id
std::vector<unsigned int> quadcopters;
/* Set data */
int thrust;
float pitch, roll, yawrate;
std::vector<MovementQuadruple> movementAll;
/* Received data */
int id;
std::vector<float> pitch_stab;
std::vector<float> roll_stab;
std::vector<float> yaw_stab;
std::vector<unsigned int> thrust_stab;
std::vector<float> battery_status;
int startProcess;
std::vector<std::string> idString;
std::vector<int> idsToGetTracked;
//Control variables
//Array of tracked quadcopters
std::vector<bool> tracked;
//Set when we are in the shutdown process
bool shutdownStarted;
bool getTracked;
bool receiveQuadcopters;
/* Mutex */
Mutex curPosMutex;
Mutex tarPosMutex;
Mutex shutdownMutex;
Mutex formMovMutex;
Mutex listPositionsMutex;
Mutex getTrackedMutex;
/* Threads */
pthread_t tCalc;
pthread_t tSend;
pthread_t tGetTracked;
/**
* NodeHandle is the main access point to communications with the ROS system.
* The first NodeHandle constructed will fully initialize this node, and the last
* NodeHandle destructed will close down the node.
*/
ros::NodeHandle n;
//Subscriber
//Subscriber for the MoveFormation data
ros::Subscriber MoveFormation_sub;
//Subscriber for Formation data from API
ros::Subscriber SetFormation_sub;
//Subscriber for Quadcopter data from QuadcopterModul
//ros::Subscriber QuadStatus_sub;
std::vector<ros::Subscriber> QuadStatus_sub;
//Subscriber to System topic (Sends the start and end of the system)
ros::Subscriber System_sub;
/* Publisher */
//Publisher for the Movement data of the Quadcopts (1000 is the max. buffered messages)
//ros::Publisher Movement_pub;
std::vector<ros::Publisher> Movement_pub;
//Publisher for Message to API
ros::Publisher Message_pub;
/* Services */
//Service for building formation
ros::ServiceServer BuildForm_srv;
//Service for shutingdown formation
ros::ServiceServer Shutdown_srv;
//Service for setting the quadcopter ids
ros::ServiceServer QuadID_srv;
//Clients
ros::ServiceClient FindAll_client;
ros::ServiceClient Blink_client;
ros::ServiceClient Announce_client;
};
#endif // CONTROLLER_HPP
<commit_msg>Adding variable for calculateMovement-switch<commit_after>#ifndef CONTROLLER_HPP
#define CONTROLLER_HPP
#include "Position6DOF.hpp"
#include "MovementQuadruple.hpp"
#include "Formation.hpp"
#include "ros/ros.h"
//Ros messages/services
#include "api_application/MoveFormation.h" // ? (D)
#include "../matlab/Vector.h"
#include "../matlab/TrackingArea.h"
#include "control_application/quadcopter_movement.h" // ? (D)
#include "api_application/SetFormation.h"
#include "api_application/Message.h"
#include "api_application/Announce.h"
#include "api_application/System.h"
#include "quadcopter_application/find_all.h"
#include "quadcopter_application/blink.h"
#include "quadcopter_application/quadcopter_status.h"
#include "control_application/BuildFormation.h"
#include "control_application/Shutdown.h"
//#include "control_application/SetQuadcopters.h"
#include "../position/IPositionReceiver.hpp"
#include <time.h>
#include <stdio.h>
#include <unistd.h>
#include <math.h>
#include <string>
#include <vector>
#include <pthread.h>
#include <list>
#include "Mutex.hpp"
#include <cmath>
#include <time.h>
#include <sstream>
#include <boost/bind.hpp>
#define THRUST_MIN 10001
#define THRUST_STAND_STILL 18001
#define THRUST_START 22000
#define THRUST_DECLINE 20000
#define THRUST_STEP 50
#define ROLL_STEP 2
#define PITCH_STEP 2
#define INVALID -1
//TODO 100% = 1?
#define LOW_BATTERY 0.05
//In seconds
#define TIME_UPDATED 1
/* For calculateMovement */
#define CALCULATE_NONE 0 // Unset
#define CALCULATE_START 1
#define CALCULATE_STABILIZE 2
#define CALCULATE_HOLD 3
#define CALCULATE_MOVE 4
#define CALCULATE_ACTIVATED 6 // QC ready to receive data from quadcoptermodul
/* Used for lists */
#define MAX_NUMBER_QUADCOPTER 10
#define POS_CHECK (current[0] != target[0]) || (current[1] != target[1]) || (current[2] != target[2])
class Controller : public IPositionReceiver {
//class Controller {
public:
Controller();
/* Initializing */
void initialize();
/* Movement and Positioning */
void convertMovement(double* const vector);
Position6DOF* getTargetPosition();
void setTargetPosition();
void updatePositions(std::vector<Vector> positions, std::vector<int> ids, std::vector<int> updates);
void sendMovement();
void sendMovementAll();
void calculateMovement();
void reachTrackedArea(std::vector<int> ids);
/* Formation also services*/
bool buildFormation(control_application::BuildFormation::Request &req, control_application::BuildFormation::Response &res);
void shutdownFormation();
/* Service to set Quadcopter IDs*/
bool setQuadcopters(control_application::SetQuadcopters::Request &req, control_application::SetQuadcopters::Response &res);
bool shutdown(control_application::Shutdown::Request &req, control_application::Shutdown::Response &res);
bool checkInput();
void emergencyRoutine(std::string message);
void moveUp(std::vector<int> ids);
void moveUpNoArg();
protected:
//Callbacks for Ros subscriber
void MoveFormationCallback(const api_application::MoveFormation::ConstPtr& msg);
void SetFormationCallback(const api_application::SetFormation::ConstPtr& msg);
void QuadStatusCallback(const quadcopter_application::quadcopter_status::ConstPtr& msg, int topicNr);
void SystemCallback(const api_application::System::ConstPtr& msg);
void stopReachTrackedArea();
private:
/* */
/* Position */
//std::vector<Position6DOF> targetPosition;
//std::vector<Position6DOF> currentPosition;
//std::vector<rpy-values> sentMovement;
//TODO Where are those lists filled/ updated? FIFO? Latest element last?
//TODO Include time somehow or how do we check if there hasn't been any input?
std::list<std::vector<Position6DOF> > listPositions;
std::list<std::vector<Position6DOF> > listTargets;
std::list<std::vector<Position6DOF> > listSendTargets;
/* Identification of Quadcopters */
//Receive data over ROS
Formation formation;
//TODO needs to be with service find all
int totalAmount;
int amount;
std::list<float[3]> formationMovement;
time_t lastFormationMovement;
time_t lastCurrent;
unsigned int senderID;
//TODO Set area
TrackingArea trackingArea;
//Mapping of int id to string id/ hardware id qc[id][uri/hardware id]
//std::vector<std::string> quadcopters;
//Mapping of quadcopter global id
std::vector<unsigned int> quadcopters;
/* For calculateMovement, using local id from mapping before. */
std::vector<unsigned int> quadcopterMovementStatus;
/* Set data */
int thrust;
float pitch, roll, yawrate;
std::vector<MovementQuadruple> movementAll;
/* Received data */
int id;
std::vector<float> pitch_stab;
std::vector<float> roll_stab;
std::vector<float> yaw_stab;
std::vector<unsigned int> thrust_stab;
std::vector<float> battery_status;
int startProcess;
std::vector<std::string> idString;
std::vector<int> idsToGetTracked;
//Control variables
//Array of tracked quadcopters
std::vector<bool> tracked;
//Set when we are in the shutdown process
bool shutdownStarted;
bool getTracked;
bool receiveQuadcopters;
/* Mutex */
Mutex curPosMutex;
Mutex tarPosMutex;
Mutex shutdownMutex;
Mutex formMovMutex;
Mutex listPositionsMutex;
Mutex getTrackedMutex;
/* Threads */
pthread_t tCalc;
pthread_t tSend;
pthread_t tGetTracked;
/**
* NodeHandle is the main access point to communications with the ROS system.
* The first NodeHandle constructed will fully initialize this node, and the last
* NodeHandle destructed will close down the node.
*/
ros::NodeHandle n;
//Subscriber
//Subscriber for the MoveFormation data
ros::Subscriber MoveFormation_sub;
//Subscriber for Formation data from API
ros::Subscriber SetFormation_sub;
//Subscriber for Quadcopter data from QuadcopterModul
//ros::Subscriber QuadStatus_sub;
std::vector<ros::Subscriber> QuadStatus_sub;
//Subscriber to System topic (Sends the start and end of the system)
ros::Subscriber System_sub;
/* Publisher */
//Publisher for the Movement data of the Quadcopts (1000 is the max. buffered messages)
//ros::Publisher Movement_pub;
std::vector<ros::Publisher> Movement_pub;
//Publisher for Message to API
ros::Publisher Message_pub;
/* Services */
//Service for building formation
ros::ServiceServer BuildForm_srv;
//Service for shutingdown formation
ros::ServiceServer Shutdown_srv;
//Service for setting the quadcopter ids
ros::ServiceServer QuadID_srv;
//Clients
ros::ServiceClient FindAll_client;
ros::ServiceClient Blink_client;
ros::ServiceClient Announce_client;
};
#endif // CONTROLLER_HPP
<|endoftext|> |
<commit_before>/*
SWARM
Copyright (C) 2012-2020 Torbjorn Rognes and Frederic Mahe
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Contact: Torbjorn Rognes <[email protected]>,
Department of Informatics, University of Oslo,
PO Box 1080 Blindern, NO-0316 Oslo, Norway
*/
#include "swarm.h"
void pushop(char newop, char ** cigarendp, char * op, int * count);
void finishop(char ** cigarendp, char * op, int * count);
void pushop(char newop, char ** cigarendp, char * op, int * count)
{
constexpr unsigned int buffer_length {25};
if (newop == *op) {
(*count)++;
}
else
{
*--*cigarendp = *op;
if (*count > 1)
{
char buf[buffer_length];
int len = snprintf(buf, buffer_length, "%d", *count);
assert(len >= 0);
*cigarendp -= len;
memcpy(*cigarendp, buf, static_cast<size_t>(len));
}
*op = newop;
*count = 1;
}
}
void finishop(char ** cigarendp, char * op, int * count)
{
constexpr unsigned int buffer_length {25};
if ((op != nullptr) && (count != nullptr))
{
*--*cigarendp = *op;
if (*count > 1)
{
char buf[buffer_length];
int len = snprintf(buf, buffer_length, "%d", *count);
assert(len >= 0);
*cigarendp -= len;
memcpy(*cigarendp, buf, static_cast<size_t>(len));
}
*op = 0;
*count = 0;
}
}
const unsigned char maskup = 1;
const unsigned char maskleft = 2;
const unsigned char maskextup = 4;
const unsigned char maskextleft = 8;
/*
Needleman/Wunsch/Sellers aligner
finds a global alignment with minimum cost
there should be positive costs/penalties for gaps and for mismatches
matches should have zero cost (0)
alignment priority when backtracking (from lower right corner):
1. left/insert/e (gap in query sequence (qseq))
2. align/diag/h (match/mismatch)
3. up/delete/f (gap in database sequence (dseq))
qseq: the reference/query/upper/vertical/from sequence
dseq: the sample/database/lower/horisontal/to sequence
typical costs:
match: 0
mismatch: 3
gapopen: 4
gapextend: 3
input
dseq: pointer to start of database sequence
dend: pointer after database sequence
qseq: pointer to start of query sequence
qend: pointer after database sequence
score_matrix: 32x32 matrix of longs with scores for aligning two symbols
gapopen: positive number indicating penalty for opening a gap of length zero
gapextend: positive number indicating penalty for extending a gap
output
nwscore: the global alignment score
nwdiff: number of non-identical nucleotides in one optimal global alignment
nwalignmentlength: the length of one optimal alignment
nwalignment: cigar string with one optimal alignment
*/
void nw(char * dseq,
int64_t dlen,
char * qseq,
int64_t qlen,
int64_t * score_matrix,
int64_t gapopen,
int64_t gapextend,
int64_t * nwscore,
int64_t * nwdiff,
int64_t * nwalignmentlength,
char ** nwalignment,
unsigned char * dir,
int64_t * hearray,
uint64_t queryno,
uint64_t dbseqno)
{
/* dir must point to at least qlen*dlen bytes of allocated memory
hearray must point to at least 2*qlen longs of allocated memory
(8*qlen bytes) */
constexpr unsigned int multiplier {5};
int64_t n {0};
int64_t e {0};
memset(dir, 0, static_cast<size_t>(qlen * dlen));
int64_t i {0};
int64_t j {0};
for(auto i = 0L; i < qlen; i++)
{
hearray[2*i] = 1 * gapopen + (i+1) * gapextend; // H (N)
hearray[2*i+1] = 2 * gapopen + (i+2) * gapextend; // E
}
for(auto j = 0L; j < dlen; j++)
{
int64_t * hep {nullptr};
hep = hearray;
int64_t f = 2 * gapopen + (j+2) * gapextend;
int64_t h = (j == 0) ? 0 : (gapopen + j * gapextend);
for(auto i = 0L; i < qlen; i++)
{
int64_t index = qlen * j + i;
n = *hep;
e = *(hep+1);
h += score_matrix
[((nt_extract(dseq, static_cast<uint64_t>(j)) + 1) << multiplier)
+(nt_extract(qseq, static_cast<uint64_t>(i)) + 1)];
dir[index] |= (f < h ? maskup : 0);
h = MIN(h, f);
h = MIN(h, e);
dir[index] |= (e == h ? maskleft : 0);
*hep = h;
h += gapopen + gapextend;
e += gapextend;
f += gapextend;
dir[index] |= (f < h ? maskextup : 0);
dir[index] |= (e < h ? maskextleft : 0);
f = MIN(h,f);
e = MIN(h,e);
*(hep+1) = e;
h = n;
hep += 2;
}
}
int64_t dist = hearray[2 * qlen - 2];
/* backtrack: count differences and save alignment in cigar string */
int64_t score {0};
int64_t alength {0};
int64_t matches {0};
char * cigar = static_cast<char *>(xmalloc
(static_cast<size_t>(qlen + dlen + 1)));
char * cigarend {cigar + qlen + dlen + 1};
char op {0};
int count {0};
*(--cigarend) = 0;
i = qlen;
j = dlen;
while ((i>0) && (j>0))
{
int d = dir[qlen*(j-1)+(i-1)];
alength++;
if ((op == 'I') && ((d & maskextleft) != 0))
{
score += gapextend;
j--;
pushop('I', &cigarend, &op, &count);
}
else if ((op == 'D') && ((d & maskextup) != 0))
{
score += gapextend;
i--;
pushop('D', &cigarend, &op, &count);
}
else if ((d & maskleft) != 0)
{
score += gapextend;
if (op != 'I') {
score += gapopen;
}
j--;
pushop('I', &cigarend, &op, &count);
}
else if ((d & maskup) != 0)
{
score += gapextend;
if (op != 'D') {
score += gapopen;
}
i--;
pushop('D', &cigarend, &op, &count);
}
else
{
score += score_matrix
[((nt_extract(dseq, static_cast<uint64_t>(j - 1)) + 1) << multiplier)
+(nt_extract(qseq, static_cast<uint64_t>(i - 1)) + 1)];
if (nt_extract(qseq, static_cast<uint64_t>(i - 1)) ==
nt_extract(dseq, static_cast<uint64_t>(j - 1))) {
matches++;
}
i--;
j--;
pushop('M', &cigarend, &op, &count);
}
}
while(i>0)
{
alength++;
score += gapextend;
if (op != 'D') {
score += gapopen;
}
i--;
pushop('D', &cigarend, &op, &count);
}
while(j>0)
{
alength++;
score += gapextend;
if (op != 'I') {
score += gapopen;
}
j--;
pushop('I', &cigarend, &op, &count);
}
finishop(&cigarend, &op, &count);
/* move and reallocate cigar */
auto cigaralloc = static_cast<size_t>(cigar + qlen + dlen - cigarend + 1);
memmove(cigar, cigarend, cigaralloc);
cigar = static_cast<char*>(xrealloc(cigar, cigaralloc));
* nwscore = dist;
* nwdiff = alength - matches;
* nwalignmentlength = alength;
* nwalignment = cigar;
assert(score == dist);
#if 0
if (score != dist)
{
fprintf(stderr,
"WARNING: Error with query no %" PRIu64 " and db sequence no %" PRIu64 ":\n",
queryno, dbseqno);
fprintf(stderr,
"Initial and recomputed alignment score disagreement: %" PRId64 " %" PRId64 "\n",
dist, score);
fprintf(stderr, "Alignment: %s\n", cigar);
}
#else
(void) queryno;
(void) dbseqno;
#endif
}
<commit_msg>fix warning: declaration shadows a local variable<commit_after>/*
SWARM
Copyright (C) 2012-2020 Torbjorn Rognes and Frederic Mahe
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Contact: Torbjorn Rognes <[email protected]>,
Department of Informatics, University of Oslo,
PO Box 1080 Blindern, NO-0316 Oslo, Norway
*/
#include "swarm.h"
void pushop(char newop, char ** cigarendp, char * op, int * count);
void finishop(char ** cigarendp, char * op, int * count);
void pushop(char newop, char ** cigarendp, char * op, int * count)
{
constexpr unsigned int buffer_length {25};
if (newop == *op) {
(*count)++;
}
else
{
*--*cigarendp = *op;
if (*count > 1)
{
char buf[buffer_length];
int len = snprintf(buf, buffer_length, "%d", *count);
assert(len >= 0);
*cigarendp -= len;
memcpy(*cigarendp, buf, static_cast<size_t>(len));
}
*op = newop;
*count = 1;
}
}
void finishop(char ** cigarendp, char * op, int * count)
{
constexpr unsigned int buffer_length {25};
if ((op != nullptr) && (count != nullptr))
{
*--*cigarendp = *op;
if (*count > 1)
{
char buf[buffer_length];
int len = snprintf(buf, buffer_length, "%d", *count);
assert(len >= 0);
*cigarendp -= len;
memcpy(*cigarendp, buf, static_cast<size_t>(len));
}
*op = 0;
*count = 0;
}
}
const unsigned char maskup = 1;
const unsigned char maskleft = 2;
const unsigned char maskextup = 4;
const unsigned char maskextleft = 8;
/*
Needleman/Wunsch/Sellers aligner
finds a global alignment with minimum cost
there should be positive costs/penalties for gaps and for mismatches
matches should have zero cost (0)
alignment priority when backtracking (from lower right corner):
1. left/insert/e (gap in query sequence (qseq))
2. align/diag/h (match/mismatch)
3. up/delete/f (gap in database sequence (dseq))
qseq: the reference/query/upper/vertical/from sequence
dseq: the sample/database/lower/horisontal/to sequence
typical costs:
match: 0
mismatch: 3
gapopen: 4
gapextend: 3
input
dseq: pointer to start of database sequence
dend: pointer after database sequence
qseq: pointer to start of query sequence
qend: pointer after database sequence
score_matrix: 32x32 matrix of longs with scores for aligning two symbols
gapopen: positive number indicating penalty for opening a gap of length zero
gapextend: positive number indicating penalty for extending a gap
output
nwscore: the global alignment score
nwdiff: number of non-identical nucleotides in one optimal global alignment
nwalignmentlength: the length of one optimal alignment
nwalignment: cigar string with one optimal alignment
*/
void nw(char * dseq,
int64_t dlen,
char * qseq,
int64_t qlen,
int64_t * score_matrix,
int64_t gapopen,
int64_t gapextend,
int64_t * nwscore,
int64_t * nwdiff,
int64_t * nwalignmentlength,
char ** nwalignment,
unsigned char * dir,
int64_t * hearray,
uint64_t queryno,
uint64_t dbseqno)
{
/* dir must point to at least qlen*dlen bytes of allocated memory
hearray must point to at least 2*qlen longs of allocated memory
(8*qlen bytes) */
constexpr unsigned int multiplier {5};
int64_t n {0};
int64_t e {0};
memset(dir, 0, static_cast<size_t>(qlen * dlen));
for(auto i = 0L; i < qlen; i++)
{
hearray[2 * i] = 1 * gapopen + (i + 1) * gapextend; // H (N)
hearray[2 * i + 1] = 2 * gapopen + (i + 2) * gapextend; // E
}
for(auto j = 0L; j < dlen; j++)
{
int64_t * hep {nullptr};
hep = hearray;
int64_t f = 2 * gapopen + (j+2) * gapextend;
int64_t h = (j == 0) ? 0 : (gapopen + j * gapextend);
for(auto i = 0L; i < qlen; i++)
{
int64_t index = qlen * j + i;
n = *hep;
e = *(hep+1);
h += score_matrix
[((nt_extract(dseq, static_cast<uint64_t>(j)) + 1) << multiplier)
+(nt_extract(qseq, static_cast<uint64_t>(i)) + 1)];
dir[index] |= (f < h ? maskup : 0);
h = MIN(h, f);
h = MIN(h, e);
dir[index] |= (e == h ? maskleft : 0);
*hep = h;
h += gapopen + gapextend;
e += gapextend;
f += gapextend;
dir[index] |= (f < h ? maskextup : 0);
dir[index] |= (e < h ? maskextleft : 0);
f = MIN(h,f);
e = MIN(h,e);
*(hep+1) = e;
h = n;
hep += 2;
}
}
int64_t dist = hearray[2 * qlen - 2];
/* backtrack: count differences and save alignment in cigar string */
int64_t score {0};
int64_t alength {0};
int64_t matches {0};
char * cigar = static_cast<char *>(xmalloc
(static_cast<size_t>(qlen + dlen + 1)));
char * cigarend {cigar + qlen + dlen + 1};
char op {0};
int count {0};
*(--cigarend) = 0;
int64_t i = qlen;
int64_t j = dlen;
while ((i>0) && (j>0))
{
int d = dir[qlen*(j-1)+(i-1)];
alength++;
if ((op == 'I') && ((d & maskextleft) != 0))
{
score += gapextend;
j--;
pushop('I', &cigarend, &op, &count);
}
else if ((op == 'D') && ((d & maskextup) != 0))
{
score += gapextend;
i--;
pushop('D', &cigarend, &op, &count);
}
else if ((d & maskleft) != 0)
{
score += gapextend;
if (op != 'I') {
score += gapopen;
}
j--;
pushop('I', &cigarend, &op, &count);
}
else if ((d & maskup) != 0)
{
score += gapextend;
if (op != 'D') {
score += gapopen;
}
i--;
pushop('D', &cigarend, &op, &count);
}
else
{
score += score_matrix
[((nt_extract(dseq, static_cast<uint64_t>(j - 1)) + 1) << multiplier)
+(nt_extract(qseq, static_cast<uint64_t>(i - 1)) + 1)];
if (nt_extract(qseq, static_cast<uint64_t>(i - 1)) ==
nt_extract(dseq, static_cast<uint64_t>(j - 1))) {
matches++;
}
i--;
j--;
pushop('M', &cigarend, &op, &count);
}
}
while(i>0)
{
alength++;
score += gapextend;
if (op != 'D') {
score += gapopen;
}
i--;
pushop('D', &cigarend, &op, &count);
}
while(j>0)
{
alength++;
score += gapextend;
if (op != 'I') {
score += gapopen;
}
j--;
pushop('I', &cigarend, &op, &count);
}
finishop(&cigarend, &op, &count);
/* move and reallocate cigar */
auto cigaralloc = static_cast<size_t>(cigar + qlen + dlen - cigarend + 1);
memmove(cigar, cigarend, cigaralloc);
cigar = static_cast<char*>(xrealloc(cigar, cigaralloc));
* nwscore = dist;
* nwdiff = alength - matches;
* nwalignmentlength = alength;
* nwalignment = cigar;
assert(score == dist);
#if 0
if (score != dist)
{
fprintf(stderr,
"WARNING: Error with query no %" PRIu64 " and db sequence no %" PRIu64 ":\n",
queryno, dbseqno);
fprintf(stderr,
"Initial and recomputed alignment score disagreement: %" PRId64 " %" PRId64 "\n",
dist, score);
fprintf(stderr, "Alignment: %s\n", cigar);
}
#else
(void) queryno;
(void) dbseqno;
#endif
}
<|endoftext|> |
<commit_before><commit_msg>#i110213# - setup master password container on demand.<commit_after><|endoftext|> |
<commit_before><commit_msg>Specify iteration limit for Kinsol<commit_after><|endoftext|> |
<commit_before><commit_msg>Update camera<commit_after><|endoftext|> |
<commit_before>#ifndef STAN_MATH_REV_CORE_HPP
#define STAN_MATH_REV_CORE_HPP
#include <stan/math/rev/core/accumulate_adjoints.hpp>
#include <stan/math/rev/core/arena_allocator.hpp>
#include <stan/math/rev/core/arena_matrix.hpp>
#include <stan/math/rev/core/autodiffstackstorage.hpp>
#include <stan/math/rev/core/build_vari_array.hpp>
#include <stan/math/rev/core/chainable_alloc.hpp>
#include <stan/math/rev/core/chainable_object.hpp>
#include <stan/math/rev/core/chainablestack.hpp>
#include <stan/math/rev/core/count_vars.hpp>
#include <stan/math/rev/core/callback_vari.hpp>
#include <stan/math/rev/core/init_chainablestack.hpp>
#include <stan/math/rev/core/std_iterator_traits.hpp>
#include <stan/math/rev/core/ddv_vari.hpp>
#include <stan/math/rev/core/deep_copy_vars.hpp>
#include <stan/math/rev/core/dv_vari.hpp>
#include <stan/math/rev/core/dvd_vari.hpp>
#include <stan/math/rev/core/dvv_vari.hpp>
#include <stan/math/rev/core/Eigen_NumTraits.hpp>
#include <stan/math/rev/core/empty_nested.hpp>
#include <stan/math/rev/core/gevv_vvv_vari.hpp>
#include <stan/math/rev/core/grad.hpp>
#include <stan/math/rev/core/nested_rev_autodiff.hpp>
#include <stan/math/rev/core/matrix_vari.hpp>
#include <stan/math/rev/core/nested_size.hpp>
#include <stan/math/rev/core/operator_addition.hpp>
#include <stan/math/rev/core/operator_divide_equal.hpp>
#include <stan/math/rev/core/operator_division.hpp>
#include <stan/math/rev/core/operator_equal.hpp>
#include <stan/math/rev/core/operator_greater_than.hpp>
#include <stan/math/rev/core/operator_greater_than_or_equal.hpp>
#include <stan/math/rev/core/operator_less_than.hpp>
#include <stan/math/rev/core/operator_less_than_or_equal.hpp>
#include <stan/math/rev/core/operator_logical_and.hpp>
#include <stan/math/rev/core/operator_logical_or.hpp>
#include <stan/math/rev/core/operator_minus_equal.hpp>
#include <stan/math/rev/core/operator_multiplication.hpp>
#include <stan/math/rev/core/operator_multiply_equal.hpp>
#include <stan/math/rev/core/operator_not_equal.hpp>
#include <stan/math/rev/core/operator_plus_equal.hpp>
#include <stan/math/rev/core/operator_subtraction.hpp>
#include <stan/math/rev/core/operator_unary_decrement.hpp>
#include <stan/math/rev/core/operator_unary_increment.hpp>
#include <stan/math/rev/core/operator_unary_negative.hpp>
#include <stan/math/rev/core/operator_unary_not.hpp>
#include <stan/math/rev/core/operator_unary_plus.hpp>
#include <stan/math/rev/core/precomp_vv_vari.hpp>
#include <stan/math/rev/core/precomp_vvv_vari.hpp>
#include <stan/math/rev/core/precomputed_gradients.hpp>
#include <stan/math/rev/core/print_stack.hpp>
#include <stan/math/rev/core/profiling.hpp>
#include <stan/math/rev/core/read_var.hpp>
#include <stan/math/rev/core/recover_memory.hpp>
#include <stan/math/rev/core/recover_memory_nested.hpp>
#include <stan/math/rev/core/scoped_chainablestack.hpp>
#include <stan/math/rev/core/set_zero_all_adjoints.hpp>
#include <stan/math/rev/core/set_zero_all_adjoints_nested.hpp>
#include <stan/math/rev/core/start_nested.hpp>
#include <stan/math/rev/core/std_complex.hpp>
#include <stan/math/rev/core/std_isinf.hpp>
#include <stan/math/rev/core/std_isnan.hpp>
#include <stan/math/rev/core/std_numeric_limits.hpp>
#include <stan/math/rev/core/stored_gradient_vari.hpp>
#include <stan/math/rev/core/typedefs.hpp>
#include <stan/math/rev/core/v_vari.hpp>
#include <stan/math/rev/core/var.hpp>
#include <stan/math/rev/core/vari.hpp>
#include <stan/math/rev/core/vd_vari.hpp>
#include <stan/math/rev/core/vdd_vari.hpp>
#include <stan/math/rev/core/vdv_vari.hpp>
#include <stan/math/rev/core/vector_vari.hpp>
#include <stan/math/rev/core/vv_vari.hpp>
#include <stan/math/rev/core/vvd_vari.hpp>
#include <stan/math/rev/core/vvv_vari.hpp>
#include <stan/math/rev/core/save_varis.hpp>
#include <stan/math/rev/core/zero_adjoints.hpp>
#endif
<commit_msg>cleanup core<commit_after>#ifndef STAN_MATH_REV_CORE_HPP
#define STAN_MATH_REV_CORE_HPP
#include <stan/math/rev/core/accumulate_adjoints.hpp>
#include <stan/math/rev/core/arena_allocator.hpp>
#include <stan/math/rev/core/arena_matrix.hpp>
#include <stan/math/rev/core/autodiffstackstorage.hpp>
#include <stan/math/rev/core/build_vari_array.hpp>
#include <stan/math/rev/core/chainable_alloc.hpp>
#include <stan/math/rev/core/chainable_object.hpp>
#include <stan/math/rev/core/chainablestack.hpp>
#include <stan/math/rev/core/count_vars.hpp>
#include <stan/math/rev/core/callback_vari.hpp>
#include <stan/math/rev/core/init_chainablestack.hpp>
#include <stan/math/rev/core/std_iterator_traits.hpp>
#include <stan/math/rev/core/ddv_vari.hpp>
#include <stan/math/rev/core/deep_copy_vars.hpp>
#include <stan/math/rev/core/dv_vari.hpp>
#include <stan/math/rev/core/dvd_vari.hpp>
#include <stan/math/rev/core/dvv_vari.hpp>
#include <stan/math/rev/core/Eigen_NumTraits.hpp>
#include <stan/math/rev/core/empty_nested.hpp>
#include <stan/math/rev/core/gevv_vvv_vari.hpp>
#include <stan/math/rev/core/grad.hpp>
#include <stan/math/rev/core/nested_rev_autodiff.hpp>
#include <stan/math/rev/core/matrix_vari.hpp>
#include <stan/math/rev/core/nested_size.hpp>
#include <stan/math/rev/core/operator_addition.hpp>
#include <stan/math/rev/core/operator_divide_equal.hpp>
#include <stan/math/rev/core/operator_division.hpp>
#include <stan/math/rev/core/operator_equal.hpp>
#include <stan/math/rev/core/operator_greater_than.hpp>
#include <stan/math/rev/core/operator_greater_than_or_equal.hpp>
#include <stan/math/rev/core/operator_less_than.hpp>
#include <stan/math/rev/core/operator_less_than_or_equal.hpp>
#include <stan/math/rev/core/operator_logical_and.hpp>
#include <stan/math/rev/core/operator_logical_or.hpp>
#include <stan/math/rev/core/operator_minus_equal.hpp>
#include <stan/math/rev/core/operator_multiplication.hpp>
#include <stan/math/rev/core/operator_multiply_equal.hpp>
#include <stan/math/rev/core/operator_not_equal.hpp>
#include <stan/math/rev/core/operator_plus_equal.hpp>
#include <stan/math/rev/core/operator_subtraction.hpp>
#include <stan/math/rev/core/operator_unary_decrement.hpp>
#include <stan/math/rev/core/operator_unary_increment.hpp>
#include <stan/math/rev/core/operator_unary_negative.hpp>
#include <stan/math/rev/core/operator_unary_not.hpp>
#include <stan/math/rev/core/operator_unary_plus.hpp>
#include <stan/math/rev/core/precomp_vv_vari.hpp>
#include <stan/math/rev/core/precomp_vvv_vari.hpp>
#include <stan/math/rev/core/precomputed_gradients.hpp>
#include <stan/math/rev/core/print_stack.hpp>
#include <stan/math/rev/core/profiling.hpp>
#include <stan/math/rev/core/read_var.hpp>
#include <stan/math/rev/core/recover_memory.hpp>
#include <stan/math/rev/core/recover_memory_nested.hpp>
#include <stan/math/rev/core/scoped_chainablestack.hpp>
#include <stan/math/rev/core/set_zero_all_adjoints.hpp>
#include <stan/math/rev/core/set_zero_all_adjoints_nested.hpp>
#include <stan/math/rev/core/start_nested.hpp>
#include <stan/math/rev/core/std_complex.hpp>
#include <stan/math/rev/core/std_isinf.hpp>
#include <stan/math/rev/core/std_isnan.hpp>
#include <stan/math/rev/core/std_numeric_limits.hpp>
#include <stan/math/rev/core/stored_gradient_vari.hpp>
#include <stan/math/rev/core/typedefs.hpp>
#include <stan/math/rev/core/var.hpp>
#include <stan/math/rev/core/vari.hpp>
#include <stan/math/rev/core/vd_vari.hpp>
#include <stan/math/rev/core/vdd_vari.hpp>
#include <stan/math/rev/core/vdv_vari.hpp>
#include <stan/math/rev/core/vector_vari.hpp>
#include <stan/math/rev/core/vv_vari.hpp>
#include <stan/math/rev/core/vvd_vari.hpp>
#include <stan/math/rev/core/vvv_vari.hpp>
#include <stan/math/rev/core/save_varis.hpp>
#include <stan/math/rev/core/zero_adjoints.hpp>
#endif
<|endoftext|> |
<commit_before>
#include "boxed.h"
#include "function.h"
#include "closure.h"
#include "gi.h"
#include "gobject.h"
#include "util.h"
#include "value.h"
using v8::Array;
using v8::External;
using v8::Function;
using v8::FunctionTemplate;
using v8::Local;
using v8::Number;
using v8::Object;
using v8::String;
using v8::Persistent;
using Nan::New;
using Nan::FunctionCallbackInfo;
using Nan::WeakCallbackType;
namespace GNodeJS {
static void GObjectDestroyed(const v8::WeakCallbackInfo<GObject> &data);
static Local<FunctionTemplate> GetClassTemplateFromGI(GIBaseInfo *info);
static bool InitGParameterFromProperty(GParameter *parameter,
void *klass,
Local<String> name,
Local<Value> value) {
// XXX js->c name conversion
String::Utf8Value name_str (name);
GParamSpec *pspec = g_object_class_find_property (G_OBJECT_CLASS (klass), *name_str);
if (pspec == NULL)
return false;
parameter->name = pspec->name;
g_value_init (¶meter->value, G_PARAM_SPEC_VALUE_TYPE (pspec));
V8ToGValue (¶meter->value, value);
return true;
}
static bool InitGParametersFromProperty(GParameter **parameters_p,
int *n_parameters_p,
void *klass,
Local<Object> property_hash) {
Local<Array> properties = property_hash->GetOwnPropertyNames ();
int n_parameters = properties->Length ();
GParameter *parameters = g_new0 (GParameter, n_parameters);
for (int i = 0; i < n_parameters; i++) {
Local<Value> name = properties->Get (i);
Local<Value> value = property_hash->Get (name);
if (!InitGParameterFromProperty (¶meters[i], klass, name->ToString (), value))
return false;
}
*parameters_p = parameters;
*n_parameters_p = n_parameters;
return true;
}
static void ToggleNotify(gpointer user_data, GObject *gobject, gboolean toggle_down) {
void *data = g_object_get_qdata (gobject, GNodeJS::object_quark());
g_assert (data != NULL);
auto *persistent = (Persistent<Object> *) data;
if (toggle_down) {
/* We're dropping from 2 refs to 1 ref. We are the last holder. Make
* sure that that our weak ref is installed. */
persistent->SetWeak (gobject, GObjectDestroyed, v8::WeakCallbackType::kParameter);
} else {
/* We're going from 1 ref to 2 refs. We can't let our wrapper be
* collected, so make sure that our reference is persistent */
persistent->ClearWeak ();
}
}
static void AssociateGObject(Isolate *isolate, Local<Object> object, GObject *gobject) {
object->SetAlignedPointerInInternalField (0, gobject);
g_object_ref_sink (gobject);
g_object_add_toggle_ref (gobject, ToggleNotify, NULL);
Persistent<Object> *persistent = new Persistent<Object>(isolate, object);
g_object_set_qdata (gobject, GNodeJS::object_quark(), persistent);
}
static void GObjectConstructor(const FunctionCallbackInfo<Value> &args) {
Isolate *isolate = args.GetIsolate ();
/* The flow of this function is a bit twisty.
* There's two cases for when this code is called:
* user code doing `new Gtk.Widget({ ... })`, and
* internal code as part of WrapperFromGObject, where
* the constructor is called with one external. */
if (!args.IsConstructCall ()) {
Nan::ThrowTypeError("Not a construct call.");
return;
}
Local<Object> self = args.This ();
if (args[0]->IsExternal ()) {
/* The External case. This is how WrapperFromGObject is called. */
void *data = External::Cast (*args[0])->Value ();
GObject *gobject = G_OBJECT (data);
AssociateGObject (isolate, self, gobject);
} else {
/* User code calling `new Gtk.Widget({ ... })` */
GObject *gobject;
GIBaseInfo *info = (GIBaseInfo *) External::Cast (*args.Data ())->Value ();
GType gtype = g_registered_type_info_get_g_type ((GIRegisteredTypeInfo *) info);
void *klass = g_type_class_ref (gtype);
GParameter *parameters = NULL;
int n_parameters = 0;
if (args[0]->IsObject ()) {
Local<Object> property_hash = args[0]->ToObject ();
if (!InitGParametersFromProperty (¶meters, &n_parameters, klass, property_hash)) {
Nan::ThrowError("GObjectConstructor: Unable to make GParameters.");
goto out;
}
}
gobject = (GObject *) g_object_newv (gtype, n_parameters, parameters);
AssociateGObject (isolate, self, gobject);
out:
g_free (parameters);
g_type_class_unref (klass);
}
}
static void GObjectDestroyed(const v8::WeakCallbackInfo<GObject> &data) {
GObject *gobject = data.GetParameter ();
void *type_data = g_object_get_qdata (gobject, GNodeJS::object_quark());
assert (type_data != NULL);
Persistent<Object> *persistent = (Persistent<Object> *) type_data;
delete persistent;
/* We're destroying the wrapper object, so make sure to clear out
* the qdata that points back to us. */
g_object_set_qdata (gobject, GNodeJS::object_quark(), NULL);
g_object_unref (gobject);
}
static void SignalConnectInternal(const Nan::FunctionCallbackInfo<v8::Value> &args, bool after) {
Isolate *isolate = args.GetIsolate ();
GObject *gobject = GObjectFromWrapper (args.This ());
if (!(args[0]->IsString() || args[0]->IsNumber())) {
Nan::ThrowTypeError("Signal ID invalid.");
return;
}
if (!args[1]->IsFunction()) {
Nan::ThrowTypeError("Signal callback is not a function.");
return;
}
String::Utf8Value signal_name (args[0]->ToString ());
Local<Function> callback = args[1].As<Function>();
GClosure *gclosure = MakeClosure (isolate, callback);
// TODO return some sort of cancellation handle?
// e.g.: return { disposable: function () {...}, signal_id: ID };
ulong handler_id = g_signal_connect_closure (gobject, *signal_name, gclosure, after);
args.GetReturnValue().Set((double)handler_id);
}
NAN_METHOD(SignalConnect) {
SignalConnectInternal(info, false);
}
static void GObjectToString(const Nan::FunctionCallbackInfo<v8::Value> &info) {
Local<Object> self = info.This();
GObject* g_object = GNodeJS::GObjectFromWrapper(self);
GType type = G_OBJECT_TYPE (g_object);
const char* typeName = g_type_name(type);
char *className = *String::Utf8Value(self->GetConstructorName());
void *address = self->GetAlignedPointerFromInternalField(0);
char *str = g_strdup_printf(
"[%s:%s %#zx]", typeName, className, (unsigned long)address);
info.GetReturnValue().Set(UTF8(str));
g_free(str);
}
static Local<FunctionTemplate> GetBaseClassTemplate() {
static int count = 0;
g_warning("GetBaseClassTemplate called (%i)", count);
count++;
auto tpl = New<FunctionTemplate> ();
Nan::SetPrototypeMethod(tpl, "on", SignalConnect);
Nan::SetPrototypeMethod(tpl, "connect", SignalConnect);
Nan::SetPrototypeMethod(tpl, "addEventListener", SignalConnect);
Nan::SetPrototypeMethod(tpl, "toString",
[](const Nan::FunctionCallbackInfo<v8::Value>& info) -> void {
char *str = *String::Utf8Value(info.This()->GetConstructorName());
info.GetReturnValue().Set(UTF8(str));
});
return tpl;
}
static Local<FunctionTemplate> NewClassTemplate (GIBaseInfo *info) {
const GType gtype = g_registered_type_info_get_g_type (info);
g_assert(gtype != G_TYPE_NONE);
const char *class_name = g_type_name (gtype);
auto tpl = New<FunctionTemplate> (GObjectConstructor, New<External> (info));
//tpl->Set (UTF8("gtype"), New((double)gtype));
Nan::SetTemplate(tpl, "gtype", New((double)gtype));
tpl->SetClassName (UTF8(class_name));
tpl->InstanceTemplate()->SetInternalFieldCount(1);
GIObjectInfo *parent_info = g_object_info_get_parent (info);
if (parent_info) {
auto parent_tpl = GetClassTemplateFromGI ((GIBaseInfo *) parent_info);
tpl->Inherit(parent_tpl);
} else {
tpl->Inherit(GetBaseClassTemplate());
}
return tpl;
}
static Local<FunctionTemplate> GetClassTemplate(GType gtype) {
// GIBaseInfo *info,
void *data = g_type_get_qdata (gtype, GNodeJS::template_quark());
if (data) {
auto *persistent = (Persistent<FunctionTemplate> *) data;
auto tpl = New<FunctionTemplate> (*persistent);
return tpl;
} else {
GIBaseInfo *gi_info = g_irepository_find_by_gtype(NULL, gtype);
auto tpl = NewClassTemplate(gi_info);
auto *persistent = new Persistent<FunctionTemplate>(Isolate::GetCurrent(), tpl);
persistent->SetWeak (
g_base_info_ref (gi_info),
GNodeJS::ClassDestroyed,
WeakCallbackType::kParameter);
g_type_set_qdata(gtype, GNodeJS::template_quark(), persistent);
return tpl;
}
}
static Local<FunctionTemplate> GetClassTemplateFromGI(GIBaseInfo *info) {
GType gtype = g_registered_type_info_get_g_type ((GIRegisteredTypeInfo *) info);
return GetClassTemplate(gtype);
}
Local<Function> MakeClass(GIBaseInfo *info) {
auto tpl = GetClassTemplateFromGI (info);
return tpl->GetFunction ();
}
Local<Value> WrapperFromGObject(GObject *gobject) {
if (gobject == NULL)
return Nan::Null();
void *data = g_object_get_qdata (gobject, GNodeJS::object_quark());
if (data) {
/* Easy case: we already have an object. */
auto *persistent = (Persistent<Object> *) data;
auto obj = New<Object> (*persistent);
return obj;
} else {
GType gtype = G_OBJECT_TYPE(gobject);
g_type_ensure(gtype); //void *klass = g_type_class_ref (type);
auto tpl = GetClassTemplate(gtype);
Local<Function> constructor = tpl->GetFunction ();
Local<Value> gobject_external = New<External> (gobject);
Local<Value> args[] = { gobject_external };
Local<Object> obj = constructor->NewInstance (1, args);
return obj;
}
}
GObject * GObjectFromWrapper(Local<Value> value) {
Local<Object> object = value->ToObject ();
void *ptr = object->GetAlignedPointerFromInternalField (0);
GObject *gobject = G_OBJECT (ptr);
return gobject;
}
};
<commit_msg>use "info" argument-name in GObjectCOnstructor<commit_after>
#include "boxed.h"
#include "function.h"
#include "closure.h"
#include "gi.h"
#include "gobject.h"
#include "util.h"
#include "value.h"
using v8::Array;
using v8::External;
using v8::Function;
using v8::FunctionTemplate;
using v8::Local;
using v8::Number;
using v8::Object;
using v8::String;
using v8::Persistent;
using Nan::New;
using Nan::FunctionCallbackInfo;
using Nan::WeakCallbackType;
namespace GNodeJS {
static void GObjectDestroyed(const v8::WeakCallbackInfo<GObject> &data);
static Local<FunctionTemplate> GetClassTemplateFromGI(GIBaseInfo *info);
static bool InitGParameterFromProperty(GParameter *parameter,
void *klass,
Local<String> name,
Local<Value> value) {
// XXX js->c name conversion
String::Utf8Value name_str (name);
GParamSpec *pspec = g_object_class_find_property (G_OBJECT_CLASS (klass), *name_str);
if (pspec == NULL)
return false;
parameter->name = pspec->name;
g_value_init (¶meter->value, G_PARAM_SPEC_VALUE_TYPE (pspec));
V8ToGValue (¶meter->value, value);
return true;
}
static bool InitGParametersFromProperty(GParameter **parameters_p,
int *n_parameters_p,
void *klass,
Local<Object> property_hash) {
Local<Array> properties = property_hash->GetOwnPropertyNames ();
int n_parameters = properties->Length ();
GParameter *parameters = g_new0 (GParameter, n_parameters);
for (int i = 0; i < n_parameters; i++) {
Local<Value> name = properties->Get (i);
Local<Value> value = property_hash->Get (name);
if (!InitGParameterFromProperty (¶meters[i], klass, name->ToString (), value))
return false;
}
*parameters_p = parameters;
*n_parameters_p = n_parameters;
return true;
}
static void ToggleNotify(gpointer user_data, GObject *gobject, gboolean toggle_down) {
void *data = g_object_get_qdata (gobject, GNodeJS::object_quark());
g_assert (data != NULL);
auto *persistent = (Persistent<Object> *) data;
if (toggle_down) {
/* We're dropping from 2 refs to 1 ref. We are the last holder. Make
* sure that that our weak ref is installed. */
persistent->SetWeak (gobject, GObjectDestroyed, v8::WeakCallbackType::kParameter);
} else {
/* We're going from 1 ref to 2 refs. We can't let our wrapper be
* collected, so make sure that our reference is persistent */
persistent->ClearWeak ();
}
}
static void AssociateGObject(Isolate *isolate, Local<Object> object, GObject *gobject) {
object->SetAlignedPointerInInternalField (0, gobject);
g_object_ref_sink (gobject);
g_object_add_toggle_ref (gobject, ToggleNotify, NULL);
Persistent<Object> *persistent = new Persistent<Object>(isolate, object);
g_object_set_qdata (gobject, GNodeJS::object_quark(), persistent);
}
static void GObjectConstructor(const FunctionCallbackInfo<Value> &info) {
Isolate *isolate = info.GetIsolate ();
/* The flow of this function is a bit twisty.
* There's two cases for when this code is called:
* user code doing `new Gtk.Widget({ ... })`, and
* internal code as part of WrapperFromGObject, where
* the constructor is called with one external. */
if (!info.IsConstructCall ()) {
Nan::ThrowTypeError("Not a construct call.");
return;
}
Local<Object> self = info.This ();
if (info[0]->IsExternal ()) {
/* The External case. This is how WrapperFromGObject is called. */
void *data = External::Cast (*info[0])->Value ();
GObject *gobject = G_OBJECT (data);
AssociateGObject (isolate, self, gobject);
} else {
/* User code calling `new Gtk.Widget({ ... })` */
GObject *gobject;
GIBaseInfo *gi_info = (GIBaseInfo *) External::Cast (*info.Data ())->Value ();
GType gtype = g_registered_type_info_get_g_type ((GIRegisteredTypeInfo *) gi_info);
void *klass = g_type_class_ref (gtype);
GParameter *parameters = NULL;
int n_parameters = 0;
if (info[0]->IsObject ()) {
Local<Object> property_hash = info[0]->ToObject ();
if (!InitGParametersFromProperty (¶meters, &n_parameters, klass, property_hash)) {
Nan::ThrowError("GObjectConstructor: Unable to make GParameters.");
goto out;
}
}
gobject = (GObject *) g_object_newv (gtype, n_parameters, parameters);
AssociateGObject (isolate, self, gobject);
out:
g_free (parameters);
g_type_class_unref (klass);
}
}
static void GObjectDestroyed(const v8::WeakCallbackInfo<GObject> &data) {
GObject *gobject = data.GetParameter ();
void *type_data = g_object_get_qdata (gobject, GNodeJS::object_quark());
assert (type_data != NULL);
Persistent<Object> *persistent = (Persistent<Object> *) type_data;
delete persistent;
/* We're destroying the wrapper object, so make sure to clear out
* the qdata that points back to us. */
g_object_set_qdata (gobject, GNodeJS::object_quark(), NULL);
g_object_unref (gobject);
}
static void SignalConnectInternal(const Nan::FunctionCallbackInfo<v8::Value> &args, bool after) {
Isolate *isolate = args.GetIsolate ();
GObject *gobject = GObjectFromWrapper (args.This ());
if (!(args[0]->IsString() || args[0]->IsNumber())) {
Nan::ThrowTypeError("Signal ID invalid.");
return;
}
if (!args[1]->IsFunction()) {
Nan::ThrowTypeError("Signal callback is not a function.");
return;
}
String::Utf8Value signal_name (args[0]->ToString ());
Local<Function> callback = args[1].As<Function>();
GClosure *gclosure = MakeClosure (isolate, callback);
// TODO return some sort of cancellation handle?
// e.g.: return { disposable: function () {...}, signal_id: ID };
ulong handler_id = g_signal_connect_closure (gobject, *signal_name, gclosure, after);
args.GetReturnValue().Set((double)handler_id);
}
NAN_METHOD(SignalConnect) {
SignalConnectInternal(info, false);
}
static void GObjectToString(const Nan::FunctionCallbackInfo<v8::Value> &info) {
Local<Object> self = info.This();
GObject* g_object = GNodeJS::GObjectFromWrapper(self);
GType type = G_OBJECT_TYPE (g_object);
const char* typeName = g_type_name(type);
char *className = *String::Utf8Value(self->GetConstructorName());
void *address = self->GetAlignedPointerFromInternalField(0);
char *str = g_strdup_printf(
"[%s:%s %#zx]", typeName, className, (unsigned long)address);
info.GetReturnValue().Set(UTF8(str));
g_free(str);
}
static Local<FunctionTemplate> GetBaseClassTemplate() {
static int count = 0;
g_warning("GetBaseClassTemplate called (%i)", count);
count++;
auto tpl = New<FunctionTemplate> ();
Nan::SetPrototypeMethod(tpl, "on", SignalConnect);
Nan::SetPrototypeMethod(tpl, "connect", SignalConnect);
Nan::SetPrototypeMethod(tpl, "addEventListener", SignalConnect);
Nan::SetPrototypeMethod(tpl, "toString",
[](const Nan::FunctionCallbackInfo<v8::Value>& info) -> void {
char *str = *String::Utf8Value(info.This()->GetConstructorName());
info.GetReturnValue().Set(UTF8(str));
});
return tpl;
}
static Local<FunctionTemplate> NewClassTemplate (GIBaseInfo *info) {
const GType gtype = g_registered_type_info_get_g_type (info);
g_assert(gtype != G_TYPE_NONE);
const char *class_name = g_type_name (gtype);
auto tpl = New<FunctionTemplate> (GObjectConstructor, New<External> (info));
//tpl->Set (UTF8("gtype"), New((double)gtype));
Nan::SetTemplate(tpl, "gtype", New((double)gtype));
tpl->SetClassName (UTF8(class_name));
tpl->InstanceTemplate()->SetInternalFieldCount(1);
GIObjectInfo *parent_info = g_object_info_get_parent (info);
if (parent_info) {
auto parent_tpl = GetClassTemplateFromGI ((GIBaseInfo *) parent_info);
tpl->Inherit(parent_tpl);
} else {
tpl->Inherit(GetBaseClassTemplate());
}
return tpl;
}
static Local<FunctionTemplate> GetClassTemplate(GType gtype) {
// GIBaseInfo *info,
void *data = g_type_get_qdata (gtype, GNodeJS::template_quark());
if (data) {
auto *persistent = (Persistent<FunctionTemplate> *) data;
auto tpl = New<FunctionTemplate> (*persistent);
return tpl;
} else {
GIBaseInfo *gi_info = g_irepository_find_by_gtype(NULL, gtype);
auto tpl = NewClassTemplate(gi_info);
auto *persistent = new Persistent<FunctionTemplate>(Isolate::GetCurrent(), tpl);
persistent->SetWeak (
g_base_info_ref (gi_info),
GNodeJS::ClassDestroyed,
WeakCallbackType::kParameter);
g_type_set_qdata(gtype, GNodeJS::template_quark(), persistent);
return tpl;
}
}
static Local<FunctionTemplate> GetClassTemplateFromGI(GIBaseInfo *info) {
GType gtype = g_registered_type_info_get_g_type ((GIRegisteredTypeInfo *) info);
return GetClassTemplate(gtype);
}
Local<Function> MakeClass(GIBaseInfo *info) {
auto tpl = GetClassTemplateFromGI (info);
return tpl->GetFunction ();
}
Local<Value> WrapperFromGObject(GObject *gobject) {
if (gobject == NULL)
return Nan::Null();
void *data = g_object_get_qdata (gobject, GNodeJS::object_quark());
if (data) {
/* Easy case: we already have an object. */
auto *persistent = (Persistent<Object> *) data;
auto obj = New<Object> (*persistent);
return obj;
} else {
GType gtype = G_OBJECT_TYPE(gobject);
g_type_ensure(gtype); //void *klass = g_type_class_ref (type);
auto tpl = GetClassTemplate(gtype);
Local<Function> constructor = tpl->GetFunction ();
Local<Value> gobject_external = New<External> (gobject);
Local<Value> args[] = { gobject_external };
Local<Object> obj = constructor->NewInstance (1, args);
return obj;
}
}
GObject * GObjectFromWrapper(Local<Value> value) {
Local<Object> object = value->ToObject ();
void *ptr = object->GetAlignedPointerFromInternalField (0);
GObject *gobject = G_OBJECT (ptr);
return gobject;
}
};
<|endoftext|> |
<commit_before>/**
* @file rectangle_tree_impl.hpp
* @author Andrew Wells
*
* Implementation of generalized rectangle tree.
*/
#ifndef __MLPACK_CORE_TREE_RECTANGLE_TREE_RECTANGLE_TREE_IMPL_HPP
#define __MLPACK_CORE_TREE_RECTANGLE_TREE_RECTANGLE_TREE_IMPL_HPP
// In case it wasn't included already for some reason.
#include "rectangle_tree.hpp"
#include <mlpack/core/util/cli.hpp>
#include <mlpack/core/util/log.hpp>
#include <mlpack/core/util/string_util.hpp>
namespace mlpack {
namespace tree {
template<typename SplitType,
typename DescentType,
typename StatisticType,
typename MatType>
RectangleTree<SplitType, DescentType, StatisticType, MatType>::RectangleTree(
MatType& data,
const size_t maxLeafSize = 20,
const size_t minLeafSize = 6,
const size_t maxNumChildren = 4,
const size_t minNumChildren = 0,
const size_t firstDataIndex = 0):
maxNumChildren(maxNumChildren),
minNumChildren(minNumChildren),
numChildren(0),
children(maxNumChildren+1), // Add one to make splitting the node simpler
parent(NULL),
begin(0),
count(0),
maxLeafSize(maxLeafSize),
minLeafSize(minLeafSize),
bound(data.n_rows),
parentDistance(0),
dataset(new MatType(data.n_rows, static_cast<int>(maxLeafSize)+1)) // Add one to make splitting the node simpler
{
stat = StatisticType(*this);
std::cout << ToString() << std::endl;
// For now, just insert the points in order.
RectangleTree* root = this;
//for(int i = firstDataIndex; i < 57; i++) { // 56,57 are the bound for where it works/breaks
for(int i = firstDataIndex; i < data.n_rows; i++) {
std::cout << "inserting point number: " << i << std::endl;
root->InsertPoint(data.col(i));
std::cout << "finished inserting point number: " << i << std::endl;
std::cout << ToString() << std::endl;
}
}
template<typename SplitType,
typename DescentType,
typename StatisticType,
typename MatType>
RectangleTree<SplitType, DescentType, StatisticType, MatType>::RectangleTree(
RectangleTree<SplitType, DescentType, StatisticType, MatType>* parentNode):
maxNumChildren(parentNode->MaxNumChildren()),
minNumChildren(parentNode->MinNumChildren()),
numChildren(0),
children(maxNumChildren+1),
parent(parentNode),
begin(0),
count(0),
maxLeafSize(parentNode->MaxLeafSize()),
minLeafSize(parentNode->MinLeafSize()),
bound(parentNode->Bound().Dim()),
parentDistance(0),
dataset(new MatType(static_cast<int>(parentNode->Bound().Dim()), static_cast<int>(maxLeafSize)+1)) // Add one to make splitting the node simpler
{
stat = StatisticType(*this);
}
/**
* Deletes this node, deallocating the memory for the children and calling
* their destructors in turn. This will invalidate any pointers or references
* to any nodes which are children of this one.
*/
template<typename SplitType,
typename DescentType,
typename StatisticType,
typename MatType>
RectangleTree<SplitType, DescentType, StatisticType, MatType>::
~RectangleTree()
{
//LEAK MEMORY
for(int i = 0; i < numChildren; i++) {
delete children[i];
}
delete dataset;
}
/**
* Deletes this node but leaves the children untouched. Needed for when we
* split nodes and remove nodes (inserting and deleting points).
*/
template<typename SplitType,
typename DescentType,
typename StatisticType,
typename MatType>
void RectangleTree<SplitType, DescentType, StatisticType, MatType>::
softDelete()
{
/* do nothing. I'm not sure how to handle this yet, so for now, we will leak memory */
}
/**
* Recurse through the tree and insert the point at the leaf node chosen
* by the heuristic.
*/
template<typename SplitType,
typename DescentType,
typename StatisticType,
typename MatType>
void RectangleTree<SplitType, DescentType, StatisticType, MatType>::
InsertPoint(const arma::vec& point)
{
std::cout << "insert point called" << std::endl;
// Expand the bound regardless of whether it is a leaf node.
bound |= point;
// If this is a leaf node, we stop here and add the point.
if(numChildren == 0) {
std::cout << "count = " << count << std::endl;
dataset->col(count++) = point;
SplitNode();
return;
}
// If it is not a leaf node, we use the DescentHeuristic to choose a child
// to which we recurse.
double minScore = DescentType::EvalNode(children[0]->Bound(), point);
int bestIndex = 0;
for(int i = 1; i < numChildren; i++) {
double score = DescentType::EvalNode(children[i]->Bound(), point);
if(score < minScore) {
minScore = score;
bestIndex = i;
}
}
children[bestIndex]->InsertPoint(point);
}
template<typename SplitType,
typename DescentType,
typename StatisticType,
typename MatType>
size_t RectangleTree<SplitType, DescentType, StatisticType, MatType>::
TreeSize() const
{
int n = 0;
for(int i = 0; i < numChildren; i++) {
n += children[i]->TreeSize();
}
return n + 1; // we add one for this node
}
template<typename SplitType,
typename DescentType,
typename StatisticType,
typename MatType>
size_t RectangleTree<SplitType, DescentType, StatisticType, MatType>::
TreeDepth() const
{
/* Because R trees are balanced, we could simplify this. However, X trees are not
guaranteed to be balanced so I keep it as is: */
// Recursively count the depth of each subtree. The plus one is
// because we have to count this node, too.
int maxSubDepth = 0;
for(int i = 0; i < numChildren; i++) {
int d = children[i]->TreeDepth();
if(d > maxSubDepth)
maxSubDepth = d;
}
return maxSubDepth + 1;
}
template<typename SplitType,
typename DescentType,
typename StatisticType,
typename MatType>
inline bool RectangleTree<SplitType, DescentType, StatisticType, MatType>::
IsLeaf() const
{
return numChildren == 0;
}
/**
* Return a bound on the furthest point in the node form the centroid.
* This returns 0 unless the node is a leaf.
*/
template<typename SplitType,
typename DescentType,
typename StatisticType,
typename MatType>
inline double RectangleTree<SplitType, DescentType, StatisticType, MatType>::
FurthestPointDistance() const
{
if(!IsLeaf())
return 0.0;
// Otherwise return the distance from the centroid to a corner of the bound.
return 0.5 * bound.Diameter();
}
/**
* Return the furthest possible descendant distance. This returns the maximum
* distance from the centroid to the edge of the bound and not the empirical
* quantity which is the actual furthest descendant distance. So the actual
* furthest descendant distance may be less than what this method returns (but
* it will never be greater than this).
*/
template<typename SplitType,
typename DescentType,
typename StatisticType,
typename MatType>
inline double RectangleTree<SplitType, DescentType, StatisticType, MatType>::
FurthestDescendantDistance() const
{
return furthestDescendantDistance;
}
/**
* Return the number of points contained in this node. Zero if it is a non-leaf node.
*/
template<typename SplitType,
typename DescentType,
typename StatisticType,
typename MatType>
inline size_t RectangleTree<SplitType, DescentType, StatisticType, MatType>::
NumPoints() const
{
if(numChildren != 0) // This is not a leaf node.
return 0;
return count;
}
/**
* Return the number of descendants contained in this node. MEANINIGLESS AS IT CURRENTLY STANDS.
* USE NumPoints() INSTEAD.
*/
template<typename SplitType,
typename DescentType,
typename StatisticType,
typename MatType>
inline size_t RectangleTree<SplitType, DescentType, StatisticType, MatType>::
NumDescendants() const
{
return count;
}
/**
* Return the index of a particular descendant contained in this node. SEE OTHER WARNINGS
*/
template<typename SplitType,
typename DescentType,
typename StatisticType,
typename MatType>
inline size_t RectangleTree<SplitType, DescentType, StatisticType, MatType>::
Descendant(const size_t index) const
{
return (begin + index);
}
/**
* Return the index of a particular point contained in this node. SEE OTHER WARNINGS
*/
template<typename SplitType,
typename DescentType,
typename StatisticType,
typename MatType>
inline size_t RectangleTree<SplitType, DescentType, StatisticType, MatType>::
Point(const size_t index) const
{
return (begin + index);
}
/**
* Return the last point in the tree. SINCE THE TREE STORES DATA SEPARATELY IN EACH LEAF
* THIS IS CURRENTLY MEANINGLESS.
*/
template<typename SplitType,
typename DescentType,
typename StatisticType,
typename MatType>
inline size_t RectangleTree<SplitType, DescentType, StatisticType, MatType>::End() const
{
if(numChildren)
return begin + count;
return children[numChildren-1]->End();
}
//have functions for returning the list of modified indices if we end up doing it that way.
/**
* Split the tree. This calls the SplitType code to split a node. This method should only
* be called on a leaf node.
*/
template<typename SplitType,
typename DescentType,
typename StatisticType,
typename MatType>
void RectangleTree<SplitType, DescentType, StatisticType, MatType>::SplitNode()
{
// This should always be a leaf node. When we need to split other nodes,
// the split will be called from here but will take place in the SplitType code.
assert(numChildren == 0);
// Check to see if we are full.
if(count < maxLeafSize)
return; // We don't need to split.
std::cout << "we are actually splitting the node." << std::endl;
// If we are full, then we need to split (or at least try). The SplitType takes
// care of this and of moving up the tree if necessary.
SplitType::SplitLeafNode(this);
std::cout << "we finished actually splitting the node." << std::endl;
std::cout << ToString() << std::endl;
}
/**
* Returns a string representation of this object.
*/
template<typename SplitType,
typename DescentType,
typename StatisticType,
typename MatType>
std::string RectangleTree<SplitType, DescentType, StatisticType, MatType>::ToString() const
{
std::ostringstream convert;
convert << "RectangleTree [" << this << "]" << std::endl;
convert << " First point: " << begin << std::endl;
convert << " Number of descendants: " << numChildren << std::endl;
convert << " Number of points: " << count << std::endl;
convert << " Bound: " << std::endl;
convert << mlpack::util::Indent(bound.ToString(), 2);
convert << " Statistic: " << std::endl;
//convert << mlpack::util::Indent(stat.ToString(), 2);
convert << " Max leaf size: " << maxLeafSize << std::endl;
convert << " Min leaf size: " << minLeafSize << std::endl;
convert << " Max num of children: " << maxNumChildren << std::endl;
convert << " Min num of children: " << minNumChildren << std::endl;
convert << " Parent address: " << parent << std::endl;
// How many levels should we print? This will print the root and it's children.
if(parent == NULL || parent->Parent() == NULL) {
for(int i = 0; i < numChildren; i++) {
convert << children[i]->ToString();
}
}
return convert.str();
}
}; //namespace tree
}; //namespace mlpack
#endif
<commit_msg>bug fix. had n_rows when I needed n_cols<commit_after>/**
* @file rectangle_tree_impl.hpp
* @author Andrew Wells
*
* Implementation of generalized rectangle tree.
*/
#ifndef __MLPACK_CORE_TREE_RECTANGLE_TREE_RECTANGLE_TREE_IMPL_HPP
#define __MLPACK_CORE_TREE_RECTANGLE_TREE_RECTANGLE_TREE_IMPL_HPP
// In case it wasn't included already for some reason.
#include "rectangle_tree.hpp"
#include <mlpack/core/util/cli.hpp>
#include <mlpack/core/util/log.hpp>
#include <mlpack/core/util/string_util.hpp>
namespace mlpack {
namespace tree {
template<typename SplitType,
typename DescentType,
typename StatisticType,
typename MatType>
RectangleTree<SplitType, DescentType, StatisticType, MatType>::RectangleTree(
MatType& data,
const size_t maxLeafSize = 20,
const size_t minLeafSize = 6,
const size_t maxNumChildren = 4,
const size_t minNumChildren = 0,
const size_t firstDataIndex = 0):
maxNumChildren(maxNumChildren),
minNumChildren(minNumChildren),
numChildren(0),
children(maxNumChildren+1), // Add one to make splitting the node simpler
parent(NULL),
begin(0),
count(0),
maxLeafSize(maxLeafSize),
minLeafSize(minLeafSize),
bound(data.n_rows),
parentDistance(0),
dataset(new MatType(data.n_rows, static_cast<int>(maxLeafSize)+1)) // Add one to make splitting the node simpler
{
stat = StatisticType(*this);
std::cout << ToString() << std::endl;
// For now, just insert the points in order.
RectangleTree* root = this;
//for(int i = firstDataIndex; i < 57; i++) { // 56,57 are the bound for where it works/breaks
for(int i = firstDataIndex; i < data.n_cols; i++) {
std::cout << "inserting point number: " << i << std::endl;
root->InsertPoint(data.col(i));
std::cout << "finished inserting point number: " << i << std::endl;
std::cout << ToString() << std::endl;
}
}
template<typename SplitType,
typename DescentType,
typename StatisticType,
typename MatType>
RectangleTree<SplitType, DescentType, StatisticType, MatType>::RectangleTree(
RectangleTree<SplitType, DescentType, StatisticType, MatType>* parentNode):
maxNumChildren(parentNode->MaxNumChildren()),
minNumChildren(parentNode->MinNumChildren()),
numChildren(0),
children(maxNumChildren+1),
parent(parentNode),
begin(0),
count(0),
maxLeafSize(parentNode->MaxLeafSize()),
minLeafSize(parentNode->MinLeafSize()),
bound(parentNode->Bound().Dim()),
parentDistance(0),
dataset(new MatType(static_cast<int>(parentNode->Bound().Dim()), static_cast<int>(maxLeafSize)+1)) // Add one to make splitting the node simpler
{
stat = StatisticType(*this);
}
/**
* Deletes this node, deallocating the memory for the children and calling
* their destructors in turn. This will invalidate any pointers or references
* to any nodes which are children of this one.
*/
template<typename SplitType,
typename DescentType,
typename StatisticType,
typename MatType>
RectangleTree<SplitType, DescentType, StatisticType, MatType>::
~RectangleTree()
{
//LEAK MEMORY
for(int i = 0; i < numChildren; i++) {
delete children[i];
}
delete dataset;
}
/**
* Deletes this node but leaves the children untouched. Needed for when we
* split nodes and remove nodes (inserting and deleting points).
*/
template<typename SplitType,
typename DescentType,
typename StatisticType,
typename MatType>
void RectangleTree<SplitType, DescentType, StatisticType, MatType>::
softDelete()
{
/* do nothing. I'm not sure how to handle this yet, so for now, we will leak memory */
}
/**
* Recurse through the tree and insert the point at the leaf node chosen
* by the heuristic.
*/
template<typename SplitType,
typename DescentType,
typename StatisticType,
typename MatType>
void RectangleTree<SplitType, DescentType, StatisticType, MatType>::
InsertPoint(const arma::vec& point)
{
std::cout << "insert point called" << std::endl;
// Expand the bound regardless of whether it is a leaf node.
bound |= point;
// If this is a leaf node, we stop here and add the point.
if(numChildren == 0) {
std::cout << "count = " << count << std::endl;
dataset->col(count++) = point;
SplitNode();
return;
}
// If it is not a leaf node, we use the DescentHeuristic to choose a child
// to which we recurse.
double minScore = DescentType::EvalNode(children[0]->Bound(), point);
int bestIndex = 0;
for(int i = 1; i < numChildren; i++) {
double score = DescentType::EvalNode(children[i]->Bound(), point);
if(score < minScore) {
minScore = score;
bestIndex = i;
}
}
children[bestIndex]->InsertPoint(point);
}
template<typename SplitType,
typename DescentType,
typename StatisticType,
typename MatType>
size_t RectangleTree<SplitType, DescentType, StatisticType, MatType>::
TreeSize() const
{
int n = 0;
for(int i = 0; i < numChildren; i++) {
n += children[i]->TreeSize();
}
return n + 1; // we add one for this node
}
template<typename SplitType,
typename DescentType,
typename StatisticType,
typename MatType>
size_t RectangleTree<SplitType, DescentType, StatisticType, MatType>::
TreeDepth() const
{
/* Because R trees are balanced, we could simplify this. However, X trees are not
guaranteed to be balanced so I keep it as is: */
// Recursively count the depth of each subtree. The plus one is
// because we have to count this node, too.
int maxSubDepth = 0;
for(int i = 0; i < numChildren; i++) {
int d = children[i]->TreeDepth();
if(d > maxSubDepth)
maxSubDepth = d;
}
return maxSubDepth + 1;
}
template<typename SplitType,
typename DescentType,
typename StatisticType,
typename MatType>
inline bool RectangleTree<SplitType, DescentType, StatisticType, MatType>::
IsLeaf() const
{
return numChildren == 0;
}
/**
* Return a bound on the furthest point in the node form the centroid.
* This returns 0 unless the node is a leaf.
*/
template<typename SplitType,
typename DescentType,
typename StatisticType,
typename MatType>
inline double RectangleTree<SplitType, DescentType, StatisticType, MatType>::
FurthestPointDistance() const
{
if(!IsLeaf())
return 0.0;
// Otherwise return the distance from the centroid to a corner of the bound.
return 0.5 * bound.Diameter();
}
/**
* Return the furthest possible descendant distance. This returns the maximum
* distance from the centroid to the edge of the bound and not the empirical
* quantity which is the actual furthest descendant distance. So the actual
* furthest descendant distance may be less than what this method returns (but
* it will never be greater than this).
*/
template<typename SplitType,
typename DescentType,
typename StatisticType,
typename MatType>
inline double RectangleTree<SplitType, DescentType, StatisticType, MatType>::
FurthestDescendantDistance() const
{
return furthestDescendantDistance;
}
/**
* Return the number of points contained in this node. Zero if it is a non-leaf node.
*/
template<typename SplitType,
typename DescentType,
typename StatisticType,
typename MatType>
inline size_t RectangleTree<SplitType, DescentType, StatisticType, MatType>::
NumPoints() const
{
if(numChildren != 0) // This is not a leaf node.
return 0;
return count;
}
/**
* Return the number of descendants contained in this node. MEANINIGLESS AS IT CURRENTLY STANDS.
* USE NumPoints() INSTEAD.
*/
template<typename SplitType,
typename DescentType,
typename StatisticType,
typename MatType>
inline size_t RectangleTree<SplitType, DescentType, StatisticType, MatType>::
NumDescendants() const
{
return count;
}
/**
* Return the index of a particular descendant contained in this node. SEE OTHER WARNINGS
*/
template<typename SplitType,
typename DescentType,
typename StatisticType,
typename MatType>
inline size_t RectangleTree<SplitType, DescentType, StatisticType, MatType>::
Descendant(const size_t index) const
{
return (begin + index);
}
/**
* Return the index of a particular point contained in this node. SEE OTHER WARNINGS
*/
template<typename SplitType,
typename DescentType,
typename StatisticType,
typename MatType>
inline size_t RectangleTree<SplitType, DescentType, StatisticType, MatType>::
Point(const size_t index) const
{
return (begin + index);
}
/**
* Return the last point in the tree. SINCE THE TREE STORES DATA SEPARATELY IN EACH LEAF
* THIS IS CURRENTLY MEANINGLESS.
*/
template<typename SplitType,
typename DescentType,
typename StatisticType,
typename MatType>
inline size_t RectangleTree<SplitType, DescentType, StatisticType, MatType>::End() const
{
if(numChildren)
return begin + count;
return children[numChildren-1]->End();
}
//have functions for returning the list of modified indices if we end up doing it that way.
/**
* Split the tree. This calls the SplitType code to split a node. This method should only
* be called on a leaf node.
*/
template<typename SplitType,
typename DescentType,
typename StatisticType,
typename MatType>
void RectangleTree<SplitType, DescentType, StatisticType, MatType>::SplitNode()
{
// This should always be a leaf node. When we need to split other nodes,
// the split will be called from here but will take place in the SplitType code.
assert(numChildren == 0);
// Check to see if we are full.
if(count < maxLeafSize)
return; // We don't need to split.
std::cout << "we are actually splitting the node." << std::endl;
// If we are full, then we need to split (or at least try). The SplitType takes
// care of this and of moving up the tree if necessary.
SplitType::SplitLeafNode(this);
std::cout << "we finished actually splitting the node." << std::endl;
std::cout << ToString() << std::endl;
}
/**
* Returns a string representation of this object.
*/
template<typename SplitType,
typename DescentType,
typename StatisticType,
typename MatType>
std::string RectangleTree<SplitType, DescentType, StatisticType, MatType>::ToString() const
{
std::ostringstream convert;
convert << "RectangleTree [" << this << "]" << std::endl;
convert << " First point: " << begin << std::endl;
convert << " Number of descendants: " << numChildren << std::endl;
convert << " Number of points: " << count << std::endl;
convert << " Bound: " << std::endl;
convert << mlpack::util::Indent(bound.ToString(), 2);
convert << " Statistic: " << std::endl;
//convert << mlpack::util::Indent(stat.ToString(), 2);
convert << " Max leaf size: " << maxLeafSize << std::endl;
convert << " Min leaf size: " << minLeafSize << std::endl;
convert << " Max num of children: " << maxNumChildren << std::endl;
convert << " Min num of children: " << minNumChildren << std::endl;
convert << " Parent address: " << parent << std::endl;
// How many levels should we print? This will print the root and it's children.
if(parent == NULL || parent->Parent() == NULL) {
for(int i = 0; i < numChildren; i++) {
convert << children[i]->ToString();
}
}
return convert.str();
}
}; //namespace tree
}; //namespace mlpack
#endif
<|endoftext|> |
<commit_before>#include <nds.h>
#include <maxmod9.h>
#include <stdio.h>
#include "ball.h"
#include "geometry.h"
#include "player.h"
#include "stats.h"
// Audio
#include "soundbank.h"
#include "soundbank_bin.h"
// Methods
void initBall(ball *b) {
b->speed = 2;
b->box.pos.x = 100;
b->box.pos.y = 30;
b->box.width = 10;
b->box.height = 10;
b->direction.x = 1;
b->direction.y = 1;
// SFX_WALL
b->sfx_wall.id = SFX_WALL;
b->sfx_wall.rate = 1024;
b->sfx_wall.handle = 0;
b->sfx_wall.volume = 255;
b->sfx_wall.panning = 128;
// SFX_PANEL
b->sfx_panel.id = SFX_PANEL;
b->sfx_panel.rate = 1024;
b->sfx_panel.handle = 0;
b->sfx_panel.volume = 255;
b->sfx_panel.panning = 128;
// SFX_READY
b->sfx_scoring.id = SFX_READY;
b->sfx_scoring.rate = 1024;
b->sfx_scoring.handle = 0;
b->sfx_scoring.volume = 255;
b->sfx_scoring.panning = 128;
}
/**
* @param ball b
* @return void
*/
void moveBall(ball *b, player *p1, player *p2, scoreBox *sBox) {
b->box.pos.x += b->direction.x * b->speed;
b->box.pos.y += b->direction.y * b->speed;
bool hitLeftPaddle = intersect(b->box, p1->box);
bool hitRightPaddle = intersect(b->box, p2->box);
// horizontal collision
if (b->box.pos.x <= 0) {
scoring(1, b, sBox);
} else if (b->box.pos.x + b->box.width >= SCREEN_WIDTH) {
scoring(0, b, sBox);
} else if (hitLeftPaddle || hitRightPaddle) {
// calculate relative position to player box, then set direction according to that relative position
// if relative position is low (i.e. closer to 0, the ball hit the paddle early),
// then the ball goes back in the direction it came from
// if relative position is high (i.e. closer to 1, the ball hit the paddle late),
// then the ball bounces off the paddle, going off in the other direction
// if relative position is around 0.5 (i.e. the ball hit the paddle in the middle),
// then the ball goes back from the middle of the paddle
float relativePos;
if (hitLeftPaddle) {
// player 1
relativePos = (b->box.pos.y - p1->box.pos.y) / (p1->box.height);
} else {
// player 2
relativePos = (b->box.pos.y - p2->box.pos.y) / (p2->box.height);
}
// y is negative, so the ball is flying up: reverse relative position
if (b->direction.y < 0) {
relativePos = 1 - relativePos;
}
// new x direction, reverse the sign
b->direction.x *= -1;
// new y direction, keep the sign
b->direction.y = (b->direction.y > 0) ? 1 : -1;
b->direction.y *= 0.5 - 1.5 * relativePos;
// position ball so that it does not intersect the paddles anymore
if (hitLeftPaddle) {
b->box.pos.x = p1->box.pos.x + p1->box.width;
} else {
b->box.pos.x = p2->box.pos.x - b->box.width;
}
// sound effect
mmEffect( SFX_PANEL );
mmEffectEx( &b->sfx_panel );
}
// vertical collision
if (b->box.pos.y <= 0 || b->box.pos.y + b->box.height >= SCREEN_HEIGHT) {
b->direction.y *= -1;
mmEffect( SFX_WALL );
mmEffectEx( &b->sfx_wall );
}
// Updating sprite position
b->sprite->x = (int)b->box.pos.x;
b->sprite->y = (int)b->box.pos.y;
}
void scoring(int player, ball *b, scoreBox *sBox) {
b->box.pos.x = SCREEN_WIDTH / 2;
b->box.pos.y = SCREEN_HEIGHT / 2;
b->direction.x = (b->direction.x > 0) ? -1 : 1;
b->direction.y = 1;
countPoint(sBox, player);
mmEffectEx( &b->sfx_scoring );
mmEffect( SFX_READY );
}
<commit_msg>Revert "konvex -> konkav"<commit_after>#include <nds.h>
#include <maxmod9.h>
#include <stdio.h>
#include "ball.h"
#include "geometry.h"
#include "player.h"
#include "stats.h"
// Audio
#include "soundbank.h"
#include "soundbank_bin.h"
// Methods
void initBall(ball *b) {
b->speed = 2;
b->box.pos.x = 100;
b->box.pos.y = 30;
b->box.width = 10;
b->box.height = 10;
b->direction.x = 1;
b->direction.y = 1;
// SFX_WALL
b->sfx_wall.id = SFX_WALL;
b->sfx_wall.rate = 1024;
b->sfx_wall.handle = 0;
b->sfx_wall.volume = 255;
b->sfx_wall.panning = 128;
// SFX_PANEL
b->sfx_panel.id = SFX_PANEL;
b->sfx_panel.rate = 1024;
b->sfx_panel.handle = 0;
b->sfx_panel.volume = 255;
b->sfx_panel.panning = 128;
// SFX_READY
b->sfx_scoring.id = SFX_READY;
b->sfx_scoring.rate = 1024;
b->sfx_scoring.handle = 0;
b->sfx_scoring.volume = 255;
b->sfx_scoring.panning = 128;
}
/**
* @param ball b
* @return void
*/
void moveBall(ball *b, player *p1, player *p2, scoreBox *sBox) {
b->box.pos.x += b->direction.x * b->speed;
b->box.pos.y += b->direction.y * b->speed;
bool hitLeftPaddle = intersect(b->box, p1->box);
bool hitRightPaddle = intersect(b->box, p2->box);
// horizontal collision
if (b->box.pos.x <= 0) {
scoring(1, b, sBox);
} else if (b->box.pos.x + b->box.width >= SCREEN_WIDTH) {
scoring(0, b, sBox);
} else if (hitLeftPaddle || hitRightPaddle) {
// calculate relative position to player box, then set direction according to that relative position
// if relative position is low (i.e. closer to 0, the ball hit the paddle early),
// then the ball goes back in the direction it came from
// if relative position is high (i.e. closer to 1, the ball hit the paddle late),
// then the ball bounces off the paddle, going off in the other direction
// if relative position is around 0.5 (i.e. the ball hit the paddle in the middle),
// then the ball goes back from the middle of the paddle
float relativePos;
if (hitLeftPaddle) {
// player 1
relativePos = (b->box.pos.y - p1->box.pos.y) / (p1->box.height);
} else {
// player 2
relativePos = (b->box.pos.y - p2->box.pos.y) / (p2->box.height);
}
// y is negative, so the ball is flying up: reverse relative position
if (b->direction.y < 0) {
relativePos = 1 - relativePos;
}
// new x direction, reverse the sign
b->direction.x *= -1;
// new y direction, keep the sign
b->direction.y = (b->direction.y > 0) ? 1 : -1;
b->direction.y *= -0.5 + 1.5 * relativePos;
// position ball so that it does not intersect the paddles anymore
if (hitLeftPaddle) {
b->box.pos.x = p1->box.pos.x + p1->box.width;
} else {
b->box.pos.x = p2->box.pos.x - b->box.width;
}
// sound effect
mmEffect( SFX_PANEL );
mmEffectEx( &b->sfx_panel );
}
// vertical collision
if (b->box.pos.y <= 0 || b->box.pos.y + b->box.height >= SCREEN_HEIGHT) {
b->direction.y *= -1;
mmEffect( SFX_WALL );
mmEffectEx( &b->sfx_wall );
}
// Updating sprite position
b->sprite->x = (int)b->box.pos.x;
b->sprite->y = (int)b->box.pos.y;
}
void scoring(int player, ball *b, scoreBox *sBox) {
b->box.pos.x = SCREEN_WIDTH / 2;
b->box.pos.y = SCREEN_HEIGHT / 2;
b->direction.x = (b->direction.x > 0) ? -1 : 1;
b->direction.y = 1;
countPoint(sBox, player);
mmEffectEx( &b->sfx_scoring );
mmEffect( SFX_READY );
}
<|endoftext|> |
<commit_before>//
// Created by pkanev on 4/24/2017.
//
#include <NativeScriptAssert.h>
#include "v8-dom-agent-impl.h"
#include <ArgConverter.h>
#include <Runtime.h>
#include <v8_inspector/src/inspector/utils/v8-inspector-common.h>
namespace v8_inspector {
using tns::Runtime;
using tns::ArgConverter;
namespace DOMAgentState {
static const char domEnabled[] = "domEnabled";
}
V8DOMAgentImpl::V8DOMAgentImpl(V8InspectorSessionImpl* session,
protocol::FrontendChannel* frontendChannel,
protocol::DictionaryValue* state)
: m_session(session),
m_frontend(frontendChannel),
m_state(state),
m_enabled(false) {
Instance = this;
}
V8DOMAgentImpl::~V8DOMAgentImpl() { }
void V8DOMAgentImpl::enable(ErrorString*) {
if (m_enabled) {
return;
}
m_state->setBoolean(DOMAgentState::domEnabled, true);
m_enabled = true;
}
void V8DOMAgentImpl::disable(ErrorString*) {
if (!m_enabled) {
return;
}
m_state->setBoolean(DOMAgentState::domEnabled, false);
m_enabled = false;
}
void V8DOMAgentImpl::getDocument(ErrorString* errorString, std::unique_ptr<protocol::DOM::Node>* out_root) {
std::unique_ptr<protocol::DOM::Node> defaultNode = protocol::DOM::Node::create()
.setNodeId(0)
.setNodeType(9)
.setNodeName("Frame")
.setLocalName("Frame")
.setNodeValue("")
.build();
std::string getDocumentFunctionString = "getDocument";
// TODO: Pete: Find a better way to get a hold of the isolate
auto isolate = v8::Isolate::GetCurrent();
auto context = isolate->GetCurrentContext();
auto global = context->Global();
auto globalInspectorObject = utils::Common::getGlobalInspectorObject(isolate);
if (!globalInspectorObject.IsEmpty()) {
auto getDocument = globalInspectorObject->Get(ArgConverter::ConvertToV8String(isolate, getDocumentFunctionString));
if (!getDocument.IsEmpty() && getDocument->IsFunction()) {
auto getDocumentFunc = getDocument.As<v8::Function>();
v8::Local<v8::Value> args[] = { };
v8::TryCatch tc;
auto maybeResult = getDocumentFunc->Call(context, global, 0, args);
if (tc.HasCaught()) {
*errorString = utils::Common::getJSCallErrorMessage(getDocumentFunctionString, tc.Message()->Get()).c_str();
*out_root = std::move(defaultNode);
return;
}
v8::Local<v8::Value> outResult;
if (maybeResult.ToLocal(&outResult)) {
auto resultString = ArgConverter::ConvertToUtf16String(outResult->ToString());
auto resultUtf16Data = resultString.data();
auto resultJson = protocol::parseJSON(String16((const uint16_t*) resultUtf16Data));
protocol::ErrorSupport errorSupport;
auto domNode = protocol::DOM::Node::parse(resultJson.get(), &errorSupport);
auto errorSupportString = errorSupport.errors().utf8();
*errorString = errorSupportString.c_str();
if (!errorSupportString.empty()) {
auto errorMessage = "Error while parsing debug `DOM Node` object. ";
DEBUG_WRITE_FORCE("JS Error: %s", errorMessage, errorSupportString.c_str());
} else {
*out_root = std::move(domNode);
return;
}
} else {
*errorString = "Didn't get a proper result from __getDocument call. Returning empty visual tree.";
}
}
}
*out_root = std::move(defaultNode);
}
void V8DOMAgentImpl::removeNode(ErrorString* errorString, int in_nodeId) {
std::string removeNodeFunctionString = "removeNode";
// TODO: Pete: Find a better way to get a hold of the isolate
auto isolate = v8::Isolate::GetCurrent();
auto context = isolate->GetCurrentContext();
auto global = context->Global();
auto globalInspectorObject = utils::Common::getGlobalInspectorObject(isolate);
if (!globalInspectorObject.IsEmpty()) {
auto removeNode = globalInspectorObject->Get(ArgConverter::ConvertToV8String(isolate, removeNodeFunctionString));
if (!removeNode.IsEmpty() && removeNode->IsFunction()) {
auto removeNodeFunc = removeNode.As<v8::Function>();
v8::Local<v8::Value> args[] = { v8::Number::New(isolate, in_nodeId) };
v8::TryCatch tc;
removeNodeFunc->Call(context, global, 1, args);
if (tc.HasCaught()) {
*errorString = utils::Common::getJSCallErrorMessage(removeNodeFunctionString, tc.Message()->Get()).c_str();
}
return;
}
}
*errorString = "Couldn't remove the selected DOMNode from the visual tree.";
}
// Pete: return empty resolved object - prevents crashes when opening the 'properties', 'event listeners' tabs
// Not supported
void V8DOMAgentImpl::resolveNode(ErrorString*, int in_nodeId, const Maybe<String>& in_objectGroup, std::unique_ptr<protocol::Runtime::RemoteObject>* out_object) {
auto resolvedNode = protocol::Runtime::RemoteObject::create()
.setType("View")
.build();
*out_object = std::move(resolvedNode);
}
void V8DOMAgentImpl::setAttributeValue(ErrorString* errorString, int in_nodeId, const String& in_name,
const String& in_value) {
// Irrelevant
}
void V8DOMAgentImpl::setAttributesAsText(ErrorString* errorString, int in_nodeId, const String& in_text,
const Maybe<String>& in_name) {
// call modules' View class methods to modify view's attribute
// TODO: Pete: Find a better way to get a hold of the isolate
std::string setAttributeAsTextFunctionString = "setAttributeAsText";
auto isolate = v8::Isolate::GetCurrent();
auto context = isolate->GetCurrentContext();
auto global = context->Global();
auto globalInspectorObject = utils::Common::getGlobalInspectorObject(isolate);
if (!globalInspectorObject.IsEmpty()) {
auto setAttributeAsText = globalInspectorObject->Get(ArgConverter::ConvertToV8String(isolate, setAttributeAsTextFunctionString));
if (!setAttributeAsText.IsEmpty() && setAttributeAsText->IsFunction()) {
auto setAttributeAsTextFunc = setAttributeAsText.As<v8::Function>();
// TODO: Pete: Setting the content to contain utf-16 characters will still output garbage
v8::Local<v8::Value> args[] = {
v8::Number::New(isolate, in_nodeId),
v8_inspector::toV8String(isolate, in_text),
v8_inspector::toV8String(isolate, in_name.fromJust())
};
v8::TryCatch tc;
setAttributeAsTextFunc->Call(context, global, 3, args);
if (tc.HasCaught()) {
*errorString = utils::Common::getJSCallErrorMessage(setAttributeAsTextFunctionString, tc.Message()->Get()).c_str();
}
return;
}
}
}
void V8DOMAgentImpl::removeAttribute(ErrorString* errorString, int in_nodeId, const String& in_name) {
// Irrelevant
}
// Not supported
void V8DOMAgentImpl::performSearch(ErrorString*, const String& in_query,
const Maybe<protocol::Array<int>>& in_nodeIds,
String* out_searchId, int* out_resultCount) {
}
// Not supported
void V8DOMAgentImpl::getSearchResults(ErrorString*, const String& in_searchId, int in_fromIndex,
int in_toIndex,
std::unique_ptr<protocol::Array<int>>* out_nodeIds) {
}
// Not supported
void V8DOMAgentImpl::discardSearchResults(ErrorString*, const String& in_searchId) {
}
V8DOMAgentImpl* V8DOMAgentImpl::Instance = 0;
}
<commit_msg>fix(devtools): if Elements tab is empty, try to repopulate on consecutive opening<commit_after>//
// Created by pkanev on 4/24/2017.
//
#include <NativeScriptAssert.h>
#include "v8-dom-agent-impl.h"
#include <ArgConverter.h>
#include <Runtime.h>
#include <v8_inspector/src/inspector/utils/v8-inspector-common.h>
namespace v8_inspector {
using tns::Runtime;
using tns::ArgConverter;
namespace DOMAgentState {
static const char domEnabled[] = "domEnabled";
}
V8DOMAgentImpl::V8DOMAgentImpl(V8InspectorSessionImpl* session,
protocol::FrontendChannel* frontendChannel,
protocol::DictionaryValue* state)
: m_session(session),
m_frontend(frontendChannel),
m_state(state),
m_enabled(false) {
Instance = this;
}
V8DOMAgentImpl::~V8DOMAgentImpl() { }
void V8DOMAgentImpl::enable(ErrorString*) {
if (m_enabled) {
return;
}
m_state->setBoolean(DOMAgentState::domEnabled, true);
m_enabled = true;
}
void V8DOMAgentImpl::disable(ErrorString*) {
if (!m_enabled) {
return;
}
m_state->setBoolean(DOMAgentState::domEnabled, false);
m_enabled = false;
}
void V8DOMAgentImpl::getDocument(ErrorString* errorString, std::unique_ptr<protocol::DOM::Node>* out_root) {
std::string getDocumentFunctionString = "getDocument";
// TODO: Pete: Find a better way to get a hold of the isolate
auto isolate = v8::Isolate::GetCurrent();
auto context = isolate->GetCurrentContext();
auto global = context->Global();
auto globalInspectorObject = utils::Common::getGlobalInspectorObject(isolate);
if (!globalInspectorObject.IsEmpty()) {
auto getDocument = globalInspectorObject->Get(ArgConverter::ConvertToV8String(isolate, getDocumentFunctionString));
if (!getDocument.IsEmpty() && getDocument->IsFunction()) {
auto getDocumentFunc = getDocument.As<v8::Function>();
v8::Local<v8::Value> args[] = { };
v8::TryCatch tc;
auto maybeResult = getDocumentFunc->Call(context, global, 0, args);
if (tc.HasCaught()) {
*errorString = utils::Common::getJSCallErrorMessage(getDocumentFunctionString, tc.Message()->Get()).c_str();
return;
}
v8::Local<v8::Value> outResult;
if (maybeResult.ToLocal(&outResult)) {
auto resultString = ArgConverter::ConvertToUtf16String(outResult->ToString());
auto resultUtf16Data = resultString.data();
auto resultJson = protocol::parseJSON(String16((const uint16_t*) resultUtf16Data));
protocol::ErrorSupport errorSupport;
auto domNode = protocol::DOM::Node::parse(resultJson.get(), &errorSupport);
auto errorSupportString = errorSupport.errors().utf8();
*errorString = errorSupportString.c_str();
if (!errorSupportString.empty()) {
auto errorMessage = "Error while parsing debug `DOM Node` object. ";
DEBUG_WRITE_FORCE("JS Error: %s", errorMessage, errorSupportString.c_str());
*errorString = errorSupportString.c_str();
} else {
*out_root = std::move(domNode);
return;
}
} else {
*errorString = "Didn't get a proper result from __getDocument call. Returning empty visual tree.";
}
}
}
*errorString = "getDocument function not available on the global object.";
}
void V8DOMAgentImpl::removeNode(ErrorString* errorString, int in_nodeId) {
std::string removeNodeFunctionString = "removeNode";
// TODO: Pete: Find a better way to get a hold of the isolate
auto isolate = v8::Isolate::GetCurrent();
auto context = isolate->GetCurrentContext();
auto global = context->Global();
auto globalInspectorObject = utils::Common::getGlobalInspectorObject(isolate);
if (!globalInspectorObject.IsEmpty()) {
auto removeNode = globalInspectorObject->Get(ArgConverter::ConvertToV8String(isolate, removeNodeFunctionString));
if (!removeNode.IsEmpty() && removeNode->IsFunction()) {
auto removeNodeFunc = removeNode.As<v8::Function>();
v8::Local<v8::Value> args[] = { v8::Number::New(isolate, in_nodeId) };
v8::TryCatch tc;
removeNodeFunc->Call(context, global, 1, args);
if (tc.HasCaught()) {
*errorString = utils::Common::getJSCallErrorMessage(removeNodeFunctionString, tc.Message()->Get()).c_str();
}
return;
}
}
*errorString = "Couldn't remove the selected DOMNode from the visual tree.";
}
// Pete: return empty resolved object - prevents crashes when opening the 'properties', 'event listeners' tabs
// Not supported
void V8DOMAgentImpl::resolveNode(ErrorString*, int in_nodeId, const Maybe<String>& in_objectGroup, std::unique_ptr<protocol::Runtime::RemoteObject>* out_object) {
auto resolvedNode = protocol::Runtime::RemoteObject::create()
.setType("View")
.build();
*out_object = std::move(resolvedNode);
}
void V8DOMAgentImpl::setAttributeValue(ErrorString* errorString, int in_nodeId, const String& in_name,
const String& in_value) {
// Irrelevant
}
void V8DOMAgentImpl::setAttributesAsText(ErrorString* errorString, int in_nodeId, const String& in_text,
const Maybe<String>& in_name) {
// call modules' View class methods to modify view's attribute
// TODO: Pete: Find a better way to get a hold of the isolate
std::string setAttributeAsTextFunctionString = "setAttributeAsText";
auto isolate = v8::Isolate::GetCurrent();
auto context = isolate->GetCurrentContext();
auto global = context->Global();
auto globalInspectorObject = utils::Common::getGlobalInspectorObject(isolate);
if (!globalInspectorObject.IsEmpty()) {
auto setAttributeAsText = globalInspectorObject->Get(ArgConverter::ConvertToV8String(isolate, setAttributeAsTextFunctionString));
if (!setAttributeAsText.IsEmpty() && setAttributeAsText->IsFunction()) {
auto setAttributeAsTextFunc = setAttributeAsText.As<v8::Function>();
// TODO: Pete: Setting the content to contain utf-16 characters will still output garbage
v8::Local<v8::Value> args[] = {
v8::Number::New(isolate, in_nodeId),
v8_inspector::toV8String(isolate, in_text),
v8_inspector::toV8String(isolate, in_name.fromJust())
};
v8::TryCatch tc;
setAttributeAsTextFunc->Call(context, global, 3, args);
if (tc.HasCaught()) {
*errorString = utils::Common::getJSCallErrorMessage(setAttributeAsTextFunctionString, tc.Message()->Get()).c_str();
}
return;
}
}
}
void V8DOMAgentImpl::removeAttribute(ErrorString* errorString, int in_nodeId, const String& in_name) {
// Irrelevant
}
// Not supported
void V8DOMAgentImpl::performSearch(ErrorString*, const String& in_query,
const Maybe<protocol::Array<int>>& in_nodeIds,
String* out_searchId, int* out_resultCount) {
}
// Not supported
void V8DOMAgentImpl::getSearchResults(ErrorString*, const String& in_searchId, int in_fromIndex,
int in_toIndex,
std::unique_ptr<protocol::Array<int>>* out_nodeIds) {
}
// Not supported
void V8DOMAgentImpl::discardSearchResults(ErrorString*, const String& in_searchId) {
}
V8DOMAgentImpl* V8DOMAgentImpl::Instance = 0;
}
<|endoftext|> |
<commit_before>// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <sys/mount.h>
#include <glog/logging.h>
#include <process/future.hpp>
#include <process/id.hpp>
#include <stout/foreach.hpp>
#include <stout/fs.hpp>
#include <stout/option.hpp>
#include <stout/path.hpp>
#include <stout/stringify.hpp>
#include <stout/strings.hpp>
#include <stout/os/exists.hpp>
#include <stout/os/mkdir.hpp>
#include <stout/os/stat.hpp>
#include <stout/os/touch.hpp>
#include "common/validation.hpp"
#ifdef __linux__
#include "linux/fs.hpp"
#endif // __linux__
#include "slave/containerizer/mesos/isolators/volume/sandbox_path.hpp"
using std::string;
using std::vector;
using process::ErrnoFailure;
using process::Failure;
using process::Future;
using process::Owned;
using mesos::slave::ContainerClass;
using mesos::slave::ContainerConfig;
using mesos::slave::ContainerLaunchInfo;
using mesos::slave::ContainerMountInfo;
using mesos::slave::ContainerState;
using mesos::slave::Isolator;
namespace mesos {
namespace internal {
namespace slave {
Try<Isolator*> VolumeSandboxPathIsolatorProcess::create(
const Flags& flags)
{
bool bindMountSupported = false;
if (flags.launcher == "linux" &&
strings::contains(flags.isolation, "filesystem/linux")) {
bindMountSupported = true;
}
Owned<MesosIsolatorProcess> process(
new VolumeSandboxPathIsolatorProcess(flags, bindMountSupported));
return new MesosIsolator(process);
}
VolumeSandboxPathIsolatorProcess::VolumeSandboxPathIsolatorProcess(
const Flags& _flags,
bool _bindMountSupported)
: ProcessBase(process::ID::generate("volume-sandbox-path-isolator")),
flags(_flags),
bindMountSupported(_bindMountSupported) {}
VolumeSandboxPathIsolatorProcess::~VolumeSandboxPathIsolatorProcess() {}
bool VolumeSandboxPathIsolatorProcess::supportsNesting()
{
return true;
}
bool VolumeSandboxPathIsolatorProcess::supportsStandalone()
{
return true;
}
Future<Nothing> VolumeSandboxPathIsolatorProcess::recover(
const vector<ContainerState>& states,
const hashset<ContainerID>& orphans)
{
foreach (const ContainerState& state, states) {
sandboxes[state.container_id()] = state.directory();
}
return Nothing();
}
Future<Option<ContainerLaunchInfo>> VolumeSandboxPathIsolatorProcess::prepare(
const ContainerID& containerId,
const ContainerConfig& containerConfig)
{
// Remember the sandbox location for each container (including
// nested). This information is important for looking up sandbox
// locations for parent containers.
sandboxes[containerId] = containerConfig.directory();
if (!containerConfig.has_container_info()) {
return None();
}
const ContainerInfo& containerInfo = containerConfig.container_info();
if (containerInfo.type() != ContainerInfo::MESOS) {
return Failure("Only support MESOS containers");
}
if (!bindMountSupported && containerConfig.has_rootfs()) {
return Failure(
"The 'linux' launcher and 'filesystem/linux' isolator must be "
"enabled to change the rootfs and bind mount");
}
ContainerLaunchInfo launchInfo;
foreach (const Volume& volume, containerInfo.volumes()) {
// NOTE: The validation here is for backwards compatibility. For
// example, if an old master (no validation code) is used to
// launch a task with a volume.
Option<Error> error = common::validation::validateVolume(volume);
if (error.isSome()) {
return Failure("Invalid volume: " + error->message);
}
Option<Volume::Source::SandboxPath> sandboxPath;
// NOTE: This is the legacy way of specifying the Volume. The
// 'host_path' can be relative in legacy mode, representing
// SANDBOX_PATH volumes.
if (volume.has_host_path() &&
!path::absolute(volume.host_path())) {
sandboxPath = Volume::Source::SandboxPath();
sandboxPath->set_type(Volume::Source::SandboxPath::SELF);
sandboxPath->set_path(volume.host_path());
}
if (volume.has_source() &&
volume.source().has_type() &&
volume.source().type() == Volume::Source::SANDBOX_PATH) {
CHECK(volume.source().has_sandbox_path());
if (path::absolute(volume.source().sandbox_path().path())) {
return Failure(
"Path '" + volume.source().sandbox_path().path() + "' "
"in SANDBOX_PATH volume is absolute");
}
sandboxPath = volume.source().sandbox_path();
}
if (sandboxPath.isNone()) {
continue;
}
if (containerConfig.has_container_class() &&
containerConfig.container_class() == ContainerClass::DEBUG) {
return Failure(
"SANDBOX_PATH volume is not supported for DEBUG containers");
}
if (!bindMountSupported && path::absolute(volume.container_path())) {
return Failure(
"The 'linux' launcher and 'filesystem/linux' isolator "
"must be enabled to support SANDBOX_PATH volume with "
"absolute container path");
}
// TODO(jieyu): We need to check that source resolves under the
// work directory because a user can potentially use a container
// path like '../../abc'.
if (!sandboxPath->has_type()) {
return Failure("Unknown SANDBOX_PATH volume type");
}
// Prepare the source.
string source;
string sourceRoot; // The parent directory of 'source'.
switch (sandboxPath->type()) {
case Volume::Source::SandboxPath::SELF:
// NOTE: For this case, the user can simply create a symlink
// in its sandbox. No need for a volume.
if (!path::absolute(volume.container_path())) {
return Failure(
"'container_path' is relative for "
"SANDBOX_PATH volume SELF type");
}
sourceRoot = containerConfig.directory();
source = path::join(sourceRoot, sandboxPath->path());
break;
case Volume::Source::SandboxPath::PARENT:
if (!containerId.has_parent()) {
return Failure(
"SANDBOX_PATH volume PARENT type "
"only works for nested container");
}
if (!sandboxes.contains(containerId.parent())) {
return Failure(
"Failed to locate the sandbox for the parent container");
}
sourceRoot = sandboxes[containerId.parent()];
source = path::join(sourceRoot, sandboxPath->path());
break;
default:
return Failure("Unknown SANDBOX_PATH volume type");
}
// NOTE: Chown should be avoided if the 'source' directory already
// exists because it may be owned by some other user and should
// not be mutated.
if (!os::exists(source)) {
Try<Nothing> mkdir = os::mkdir(source);
if (mkdir.isError()) {
return Failure(
"Failed to create the directory '" + source + "' "
"in the sandbox: " + mkdir.error());
}
// Get 'sourceRoot''s user and group info for the source path.
struct stat s;
if (::stat(sourceRoot.c_str(), &s) < 0) {
return ErrnoFailure("Failed to stat '" + sourceRoot + "'");
}
LOG(INFO) << "Changing the ownership of the SANDBOX_PATH volume at '"
<< source << "' with UID " << s.st_uid << " and GID "
<< s.st_gid;
Try<Nothing> chown = os::chown(s.st_uid, s.st_gid, source, false);
if (chown.isError()) {
return Failure(
"Failed to change the ownership of the SANDBOX_PATH volume at '" +
source + "' with UID " + stringify(s.st_uid) + " and GID " +
stringify(s.st_gid) + ": " + chown.error());
}
}
// Prepare the target.
string target;
if (path::absolute(volume.container_path())) {
CHECK(bindMountSupported);
if (containerConfig.has_rootfs()) {
target = path::join(
containerConfig.rootfs(),
volume.container_path());
if (os::stat::isdir(source)) {
Try<Nothing> mkdir = os::mkdir(target);
if (mkdir.isError()) {
return Failure(
"Failed to create the mount point at "
"'" + target + "': " + mkdir.error());
}
} else {
// The file (regular file or device file) bind mount case.
Try<Nothing> mkdir = os::mkdir(Path(target).dirname());
if (mkdir.isError()) {
return Failure(
"Failed to create directory "
"'" + Path(target).dirname() + "' "
"for the mount point: " + mkdir.error());
}
Try<Nothing> touch = os::touch(target);
if (touch.isError()) {
return Failure(
"Failed to touch the mount point at "
"'" + target + "': " + touch.error());
}
}
} else {
target = volume.container_path();
// An absolute 'container_path' must already exist if the
// container rootfs is the same as the host. This is because
// we want to avoid creating mount points outside the work
// directory in the host filesystem.
if (!os::exists(target)) {
return Failure(
"Mount point '" + target + "' is an absolute path. "
"It must exist if the container shares the host filesystem");
}
}
// TODO(jieyu): We need to check that target resolves under
// 'rootfs' because a user can potentially use a container path
// like '/../../abc'.
} else {
CHECK_EQ(Volume::Source::SandboxPath::PARENT, sandboxPath->type());
if (containerConfig.has_rootfs()) {
target = path::join(
containerConfig.rootfs(),
flags.sandbox_directory,
volume.container_path());
} else {
target = path::join(
containerConfig.directory(),
volume.container_path());
}
// Create the mount point if bind mount is used.
// NOTE: We cannot create the mount point at 'target' if
// container has rootfs defined. The bind mount of the sandbox
// will hide what's inside 'target'. So we should always create
// the mount point in the sandbox.
if (bindMountSupported) {
const string mountPoint = path::join(
containerConfig.directory(),
volume.container_path());
if (os::stat::isdir(source)) {
Try<Nothing> mkdir = os::mkdir(mountPoint);
if (mkdir.isError()) {
return Failure(
"Failed to create the mount point at "
"'" + mountPoint + "': " + mkdir.error());
}
} else {
// The file (regular file or device file) bind mount case.
Try<Nothing> mkdir = os::mkdir(Path(mountPoint).dirname());
if (mkdir.isError()) {
return Failure(
"Failed to create the directory "
"'" + Path(mountPoint).dirname() + "' "
"for the mount point: " + mkdir.error());
}
Try<Nothing> touch = os::touch(mountPoint);
if (touch.isError()) {
return Failure(
"Failed to touch the mount point at "
"'" + mountPoint+ "': " + touch.error());
}
}
}
}
if (bindMountSupported) {
#ifdef __linux__
LOG(INFO) << "Mounting SANDBOX_PATH volume from "
<< "'" << source << "' to '" << target << "' "
<< "for container " << containerId;
ContainerMountInfo* mount = launchInfo.add_mounts();
mount->set_source(source);
mount->set_target(target);
mount->set_flags(MS_BIND | MS_REC);
#endif // __linux__
} else {
LOG(INFO) << "Linking SANDBOX_PATH volume from "
<< "'" << source << "' to '" << target << "' "
<< "for container " << containerId;
Try<Nothing> symlink = ::fs::symlink(source, target);
if (symlink.isError()) {
return Failure(
"Failed to symlink '" + source + "' -> '" + target + "'"
": " + symlink.error());
}
}
}
return launchInfo;
}
Future<Nothing> VolumeSandboxPathIsolatorProcess::cleanup(
const ContainerID& containerId)
{
// Remove the current container's sandbox path from `sandboxes`.
sandboxes.erase(containerId);
return Nothing();
}
} // namespace slave {
} // namespace internal {
} // namespace mesos {
<commit_msg>Updated `volume/sandbox_path` isolator to honor volume mode.<commit_after>// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <sys/mount.h>
#include <glog/logging.h>
#include <process/future.hpp>
#include <process/id.hpp>
#include <stout/foreach.hpp>
#include <stout/fs.hpp>
#include <stout/option.hpp>
#include <stout/path.hpp>
#include <stout/stringify.hpp>
#include <stout/strings.hpp>
#include <stout/os/exists.hpp>
#include <stout/os/mkdir.hpp>
#include <stout/os/stat.hpp>
#include <stout/os/touch.hpp>
#include "common/validation.hpp"
#ifdef __linux__
#include "linux/fs.hpp"
#endif // __linux__
#include "slave/containerizer/mesos/isolators/volume/sandbox_path.hpp"
using std::string;
using std::vector;
using process::ErrnoFailure;
using process::Failure;
using process::Future;
using process::Owned;
using mesos::slave::ContainerClass;
using mesos::slave::ContainerConfig;
using mesos::slave::ContainerLaunchInfo;
using mesos::slave::ContainerMountInfo;
using mesos::slave::ContainerState;
using mesos::slave::Isolator;
namespace mesos {
namespace internal {
namespace slave {
Try<Isolator*> VolumeSandboxPathIsolatorProcess::create(
const Flags& flags)
{
bool bindMountSupported = false;
if (flags.launcher == "linux" &&
strings::contains(flags.isolation, "filesystem/linux")) {
bindMountSupported = true;
}
Owned<MesosIsolatorProcess> process(
new VolumeSandboxPathIsolatorProcess(flags, bindMountSupported));
return new MesosIsolator(process);
}
VolumeSandboxPathIsolatorProcess::VolumeSandboxPathIsolatorProcess(
const Flags& _flags,
bool _bindMountSupported)
: ProcessBase(process::ID::generate("volume-sandbox-path-isolator")),
flags(_flags),
bindMountSupported(_bindMountSupported) {}
VolumeSandboxPathIsolatorProcess::~VolumeSandboxPathIsolatorProcess() {}
bool VolumeSandboxPathIsolatorProcess::supportsNesting()
{
return true;
}
bool VolumeSandboxPathIsolatorProcess::supportsStandalone()
{
return true;
}
Future<Nothing> VolumeSandboxPathIsolatorProcess::recover(
const vector<ContainerState>& states,
const hashset<ContainerID>& orphans)
{
foreach (const ContainerState& state, states) {
sandboxes[state.container_id()] = state.directory();
}
return Nothing();
}
Future<Option<ContainerLaunchInfo>> VolumeSandboxPathIsolatorProcess::prepare(
const ContainerID& containerId,
const ContainerConfig& containerConfig)
{
// Remember the sandbox location for each container (including
// nested). This information is important for looking up sandbox
// locations for parent containers.
sandboxes[containerId] = containerConfig.directory();
if (!containerConfig.has_container_info()) {
return None();
}
const ContainerInfo& containerInfo = containerConfig.container_info();
if (containerInfo.type() != ContainerInfo::MESOS) {
return Failure("Only support MESOS containers");
}
if (!bindMountSupported && containerConfig.has_rootfs()) {
return Failure(
"The 'linux' launcher and 'filesystem/linux' isolator must be "
"enabled to change the rootfs and bind mount");
}
ContainerLaunchInfo launchInfo;
foreach (const Volume& volume, containerInfo.volumes()) {
// NOTE: The validation here is for backwards compatibility. For
// example, if an old master (no validation code) is used to
// launch a task with a volume.
Option<Error> error = common::validation::validateVolume(volume);
if (error.isSome()) {
return Failure("Invalid volume: " + error->message);
}
Option<Volume::Source::SandboxPath> sandboxPath;
// NOTE: This is the legacy way of specifying the Volume. The
// 'host_path' can be relative in legacy mode, representing
// SANDBOX_PATH volumes.
if (volume.has_host_path() &&
!path::absolute(volume.host_path())) {
sandboxPath = Volume::Source::SandboxPath();
sandboxPath->set_type(Volume::Source::SandboxPath::SELF);
sandboxPath->set_path(volume.host_path());
}
if (volume.has_source() &&
volume.source().has_type() &&
volume.source().type() == Volume::Source::SANDBOX_PATH) {
CHECK(volume.source().has_sandbox_path());
if (path::absolute(volume.source().sandbox_path().path())) {
return Failure(
"Path '" + volume.source().sandbox_path().path() + "' "
"in SANDBOX_PATH volume is absolute");
}
sandboxPath = volume.source().sandbox_path();
}
if (sandboxPath.isNone()) {
continue;
}
if (containerConfig.has_container_class() &&
containerConfig.container_class() == ContainerClass::DEBUG) {
return Failure(
"SANDBOX_PATH volume is not supported for DEBUG containers");
}
if (!bindMountSupported && path::absolute(volume.container_path())) {
return Failure(
"The 'linux' launcher and 'filesystem/linux' isolator "
"must be enabled to support SANDBOX_PATH volume with "
"absolute container path");
}
// TODO(jieyu): We need to check that source resolves under the
// work directory because a user can potentially use a container
// path like '../../abc'.
if (!sandboxPath->has_type()) {
return Failure("Unknown SANDBOX_PATH volume type");
}
// Prepare the source.
string source;
string sourceRoot; // The parent directory of 'source'.
switch (sandboxPath->type()) {
case Volume::Source::SandboxPath::SELF:
// NOTE: For this case, the user can simply create a symlink
// in its sandbox. No need for a volume.
if (!path::absolute(volume.container_path())) {
return Failure(
"'container_path' is relative for "
"SANDBOX_PATH volume SELF type");
}
sourceRoot = containerConfig.directory();
source = path::join(sourceRoot, sandboxPath->path());
break;
case Volume::Source::SandboxPath::PARENT:
if (!containerId.has_parent()) {
return Failure(
"SANDBOX_PATH volume PARENT type "
"only works for nested container");
}
if (!sandboxes.contains(containerId.parent())) {
return Failure(
"Failed to locate the sandbox for the parent container");
}
sourceRoot = sandboxes[containerId.parent()];
source = path::join(sourceRoot, sandboxPath->path());
break;
default:
return Failure("Unknown SANDBOX_PATH volume type");
}
// NOTE: Chown should be avoided if the 'source' directory already
// exists because it may be owned by some other user and should
// not be mutated.
if (!os::exists(source)) {
Try<Nothing> mkdir = os::mkdir(source);
if (mkdir.isError()) {
return Failure(
"Failed to create the directory '" + source + "' "
"in the sandbox: " + mkdir.error());
}
// Get 'sourceRoot''s user and group info for the source path.
struct stat s;
if (::stat(sourceRoot.c_str(), &s) < 0) {
return ErrnoFailure("Failed to stat '" + sourceRoot + "'");
}
LOG(INFO) << "Changing the ownership of the SANDBOX_PATH volume at '"
<< source << "' with UID " << s.st_uid << " and GID "
<< s.st_gid;
Try<Nothing> chown = os::chown(s.st_uid, s.st_gid, source, false);
if (chown.isError()) {
return Failure(
"Failed to change the ownership of the SANDBOX_PATH volume at '" +
source + "' with UID " + stringify(s.st_uid) + " and GID " +
stringify(s.st_gid) + ": " + chown.error());
}
}
// Prepare the target.
string target;
if (path::absolute(volume.container_path())) {
CHECK(bindMountSupported);
if (containerConfig.has_rootfs()) {
target = path::join(
containerConfig.rootfs(),
volume.container_path());
if (os::stat::isdir(source)) {
Try<Nothing> mkdir = os::mkdir(target);
if (mkdir.isError()) {
return Failure(
"Failed to create the mount point at "
"'" + target + "': " + mkdir.error());
}
} else {
// The file (regular file or device file) bind mount case.
Try<Nothing> mkdir = os::mkdir(Path(target).dirname());
if (mkdir.isError()) {
return Failure(
"Failed to create directory "
"'" + Path(target).dirname() + "' "
"for the mount point: " + mkdir.error());
}
Try<Nothing> touch = os::touch(target);
if (touch.isError()) {
return Failure(
"Failed to touch the mount point at "
"'" + target + "': " + touch.error());
}
}
} else {
target = volume.container_path();
// An absolute 'container_path' must already exist if the
// container rootfs is the same as the host. This is because
// we want to avoid creating mount points outside the work
// directory in the host filesystem.
if (!os::exists(target)) {
return Failure(
"Mount point '" + target + "' is an absolute path. "
"It must exist if the container shares the host filesystem");
}
}
// TODO(jieyu): We need to check that target resolves under
// 'rootfs' because a user can potentially use a container path
// like '/../../abc'.
} else {
CHECK_EQ(Volume::Source::SandboxPath::PARENT, sandboxPath->type());
if (containerConfig.has_rootfs()) {
target = path::join(
containerConfig.rootfs(),
flags.sandbox_directory,
volume.container_path());
} else {
target = path::join(
containerConfig.directory(),
volume.container_path());
}
// Create the mount point if bind mount is used.
// NOTE: We cannot create the mount point at 'target' if
// container has rootfs defined. The bind mount of the sandbox
// will hide what's inside 'target'. So we should always create
// the mount point in the sandbox.
if (bindMountSupported) {
const string mountPoint = path::join(
containerConfig.directory(),
volume.container_path());
if (os::stat::isdir(source)) {
Try<Nothing> mkdir = os::mkdir(mountPoint);
if (mkdir.isError()) {
return Failure(
"Failed to create the mount point at "
"'" + mountPoint + "': " + mkdir.error());
}
} else {
// The file (regular file or device file) bind mount case.
Try<Nothing> mkdir = os::mkdir(Path(mountPoint).dirname());
if (mkdir.isError()) {
return Failure(
"Failed to create the directory "
"'" + Path(mountPoint).dirname() + "' "
"for the mount point: " + mkdir.error());
}
Try<Nothing> touch = os::touch(mountPoint);
if (touch.isError()) {
return Failure(
"Failed to touch the mount point at "
"'" + mountPoint+ "': " + touch.error());
}
}
}
}
if (bindMountSupported) {
#ifdef __linux__
LOG(INFO) << "Mounting SANDBOX_PATH volume from "
<< "'" << source << "' to '" << target << "' "
<< "for container " << containerId;
ContainerMountInfo* mount = launchInfo.add_mounts();
mount->set_source(source);
mount->set_target(target);
mount->set_flags(MS_BIND | MS_REC);
// If the mount needs to be read-only, do a remount.
if (volume.mode() == Volume::RO) {
mount = launchInfo.add_mounts();
mount->set_target(target);
mount->set_flags(MS_BIND | MS_RDONLY | MS_REMOUNT);
}
#endif // __linux__
} else {
LOG(INFO) << "Linking SANDBOX_PATH volume from "
<< "'" << source << "' to '" << target << "' "
<< "for container " << containerId;
// NOTE: We cannot enforce read-only access given the symlink without
// changing the source so we just log a warning here.
if (volume.mode() == Volume::RO) {
LOG(WARNING) << "Allowing read-write access to read-only volume '"
<< source << "' of container " << containerId;
}
Try<Nothing> symlink = ::fs::symlink(source, target);
if (symlink.isError()) {
return Failure(
"Failed to symlink '" + source + "' -> '" + target + "'"
": " + symlink.error());
}
}
}
return launchInfo;
}
Future<Nothing> VolumeSandboxPathIsolatorProcess::cleanup(
const ContainerID& containerId)
{
// Remove the current container's sandbox path from `sandboxes`.
sandboxes.erase(containerId);
return Nothing();
}
} // namespace slave {
} // namespace internal {
} // namespace mesos {
<|endoftext|> |
<commit_before>/* mbed Microcontroller Library
* Copyright (c) 2006-2015 ARM Limited
*
* 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 "mbed.h"
#include "ble/BLE.h"
#include "ble-blocktransfer/BlockTransferService.h"
#include "voytalk/Voytalk.h"
/*****************************************************************************/
/* Configuration */
/*****************************************************************************/
// set device name
const char DEVICE_NAME[] = "Testoy";
// set TX power
#ifndef CFG_BLE_TX_POWER_LEVEL
#define CFG_BLE_TX_POWER_LEVEL 0
#endif
// control debug output
#if 1
#define DEBUGOUT(...) { printf(__VA_ARGS__); }
#else
#define DEBUGOUT(...) /* nothing */
#endif // DEBUGOUT
/*****************************************************************************/
/* Voytalk short UUID */
const UUID uuid(0xFE8E);
/* Voytalk states */
typedef enum {
FLAG_CONNECTED = 0x01,
FLAG_PROVISIONED = 0x02,
} flags_t;
static volatile uint8_t state;
/*****************************************************************************/
/* Global variables used by the test app */
/*****************************************************************************/
// BLE_API ble device
BLE ble;
// Transfer large blocks of data on platforms without Fragmentation-And-Recombination
BlockTransferService bts;
// Voytalk handling
VoytalkRouter router(DEVICE_NAME);
// buffer for sending and receiving data
SharedPointer<Block> writeBlock;
uint8_t readBuffer[1000];
BlockStatic readBlock(readBuffer, sizeof(readBuffer));
// wifi parameters
std::string ssid_string;
std::string key_string;
// Compatibility function
void signalReady();
/*****************************************************************************/
/* Functions for handling debug output */
/*****************************************************************************/
/*
Functions called when BLE device connects and disconnects.
*/
void whenConnected(const Gap::ConnectionCallbackParams_t* params)
{
(void) params;
DEBUGOUT("main: Connected: %d %d %d\r\n", params->connectionParams->minConnectionInterval,
params->connectionParams->maxConnectionInterval,
params->connectionParams->slaveLatency);
// change state in main application
state |= FLAG_CONNECTED;
// change state inside Voytalk hub
router.setStateMask(state);
}
void whenDisconnected(const Gap::DisconnectionCallbackParams_t*)
{
DEBUGOUT("main: Disconnected!\r\n");
DEBUGOUT("main: Restarting the advertising process\r\n");
ble.gap().startAdvertising();
// change state in main application
state &= ~FLAG_CONNECTED;
// change state inside Voytalk hub
router.setStateMask(state);
}
/*****************************************************************************/
/* BlockTransfer callbacks for sending and receiving data */
/*****************************************************************************/
/*
Function called when signaling client that new data is ready to be read.
*/
void blockServerSendNotification()
{
DEBUGOUT("main: notify read updated\r\n");
bts.updateCharacteristicValue((uint8_t*)"", 0);
}
/*
Function called when device receives a read request over BLE.
*/
SharedPointer<Block> blockServerReadHandler(uint32_t offset)
{
DEBUGOUT("main: block read\r\n");
(void) offset;
return SharedPointer<Block>(new BlockStatic(readBlock));
}
/*
Function called when data has been written over BLE.
*/
void blockServerWriteHandler(SharedPointer<Block> block)
{
DEBUGOUT("main: block write\r\n");
/*
Process received data, assuming it is CBOR encoded.
Any output generated will be written to the readBlock.
*/
router.processCBOR((BlockStatic*) block.get(), &readBlock);
/*
If the readBlock length is non-zero it means a reply has been generated.
*/
if (readBlock.getLength() > 0)
{
signalReady();
}
}
/*****************************************************************************/
/* Voytalk Wifi example */
/*****************************************************************************/
/*
Callback function for constructing wifi intent.
*/
void wifiIntentConstruction(VTRequest& req, VTResponse& res)
{
DEBUGOUT("main: wifi intent construction\r\n");
/* create intent using generated endpoint and constraint set */
VTIntent intent("com.arm.connectivity.wifi");
intent.knownParameters("/networks");
intent.endpoint("/wifi");
res.write(intent);
}
void wifiIntentInvocation(VTRequest& req, VTResponse& res, VoytalkRouter::done_t done)
{
DEBUGOUT("main: wifi invocation\r\n");
VTIntentInvocation invocation(req.getBody());
/////////////////////////////////////////
// retrieve parameters
invocation.getParameters().find("ssid").getString(ssid_string);
invocation.getParameters().find("key").getString(key_string);
/////////////////////////////////////////
// create coda
// Read ID from invocation. ID is returned in coda response.
uint32_t invocationID = invocation.getID();
VTCoda coda(invocationID);
coda.success(true);
res.write(coda);
done(200);
// change state in main application
state |= FLAG_PROVISIONED;
// change state inside Voytalk hub
router.setStateMask(state);
}
/*****************************************************************************/
/* Reset device example */
/*****************************************************************************/
void resetIntentConstruction(VTRequest& req, VTResponse& res)
{
DEBUGOUT("main: reset intent construction\r\n");
/* create intent using generated endpoint and constraint set */
VTIntent intent("com.arm.reset");
intent.endpoint("/reset");
res.write(intent);
}
void resetIntentInvocation(VTRequest& req, VTResponse& res, VoytalkRouter::done_t done)
{
DEBUGOUT("main: reset invocation\r\n");
VTIntentInvocation invocation(req.getBody());
// print object tree
invocation.getParameters().print();
ssid_string = "";
key_string = "";
// Read ID from invocation. ID is returned in coda response.
VTCoda coda(invocation.getID());
coda.success(true);
res.write(coda);
done(200);
// change state in main application
state &= ~FLAG_PROVISIONED;
// change state inside Voytalk hub
router.setStateMask(state);
}
/*****************************************************************************/
/* Voytalk complex example */
/*****************************************************************************/
/*
Callback functions for the example intent.
*/
void exampleIntentConstruction(VTRequest& req, VTResponse& res)
{
DEBUGOUT("main: complex example intent construction\r\n");
/* create intent */
VTIntent intent("com.arm.examples.complex");
intent.endpoint("/examples/complex");
res.write(intent);
}
/*****************************************************************************/
/* Voytalk custom example */
/*****************************************************************************/
void customIntentConstruction(VTRequest& req, VTResponse& res)
{
DEBUGOUT("main: custom intent construction\r\n");
/* create intent using generated endpoint and constraint set */
VTIntent intent("com.arm.examples.custom");
intent.endpoint("/custom");
intent.constraints()
.title("Hello!")
.description("This is the description")
.addConstraint("test",
VTConstraint(VTConstraint::TypeString)
.title("Test")
.defaultValue("default goes here")
)
.addConstraint("test2",
VTConstraint(VTConstraint::TypeString)
.title("Other test")
.defaultValue("default goes here")
);
res.write(intent);
}
void printingIntentInvocation(VTRequest& req, VTResponse& res, VoytalkRouter::done_t done)
{
DEBUGOUT("main: invocation receieved \r\n");
VTIntentInvocation invocation(req.getBody());
// print object tree
invocation.getParameters().print();
VTCoda coda(invocation.getID());
coda.success(true);
res.write(coda);
done(200);
}
void networkListResource(VTRequest& req, VTResponse& res, VoytalkRouter::done_t done)
{
DEBUGOUT("listing network resources");
VoytalkKnownParameters parameters(res, 2);
parameters.parameter("com.arm.connectivity.wifi", 50)
.map(2)
.key("ssid").value("iWifi")
.key("key").value("supersecurepassword");
parameters.parameter("com.arm.connectivity.wifi", 20)
.map(2)
.key("ssid").value("yoWifi")
.key("key").value("securepasswordinit");
done(200);
}
/*****************************************************************************/
/* main */
/*****************************************************************************/
void app_start(int, char *[])
{
/*
Register Voytalk intents in the hub.
First parameter is the callback function for intent generation.
Second is the callback function for when the intent is invoked.
Third parameter is a bitmap for grouping intents together.
*/
// Wifi provisioning intent
router.registerIntent(wifiIntentConstruction,
FLAG_CONNECTED | FLAG_PROVISIONED);
// reset intent
router.registerIntent(resetIntentConstruction,
FLAG_PROVISIONED);
// custom intent
router.registerIntent(customIntentConstruction,
FLAG_CONNECTED | FLAG_PROVISIONED);
// example intent
router.registerIntent(exampleIntentConstruction,
FLAG_CONNECTED | FLAG_PROVISIONED);
/*
Set the current state mask.
Mask is AND'ed with each intent's bitmap and only intents with non-zero
results are displayed and can be invoked.
*/
router.setStateMask(0);
/*
Define some resource callbacks
*/
router.get("/networks", networkListResource);
router.post("/wifi", wifiIntentInvocation);
router.post("/reset", resetIntentInvocation);
router.post("/custom", printingIntentInvocation);
router.post("/examples/complex", printingIntentInvocation);
/*************************************************************************/
/*************************************************************************/
/* bluetooth le */
ble.init();
// status callback functions
ble.gap().onConnection(whenConnected);
ble.gap().onDisconnection(whenDisconnected);
/* construct advertising beacon */
ble.gap().accumulateAdvertisingPayload(GapAdvertisingData::BREDR_NOT_SUPPORTED|GapAdvertisingData::LE_GENERAL_DISCOVERABLE);
ble.gap().accumulateAdvertisingPayload(GapAdvertisingData::SHORTENED_LOCAL_NAME, (const uint8_t *) DEVICE_NAME, sizeof(DEVICE_NAME) - 1);
ble.gap().accumulateAdvertisingPayload(GapAdvertisingData::COMPLETE_LIST_16BIT_SERVICE_IDS, uuid.getBaseUUID(), uuid.getLen());
ble.gap().accumulateAdvertisingPayloadTxPower(CFG_BLE_TX_POWER_LEVEL);
ble.gap().setAdvertisingType(GapAdvertisingParams::ADV_CONNECTABLE_UNDIRECTED);
ble.gap().setAdvertisingInterval(1000); /* 1s; in multiples of 0.625ms. */
// set TX power
ble.gap().setTxPower(CFG_BLE_TX_POWER_LEVEL);
// Apple uses device name instead of beacon name
ble.gap().setDeviceName((const uint8_t*) DEVICE_NAME);
/*************************************************************************/
/*************************************************************************/
// setup block transfer service
// add service using ble device, responding to uuid, and without encryption
bts.init(uuid, SecurityManager::SECURITY_MODE_ENCRYPTION_OPEN_LINK);
// set callback functions for the BlockTransfer service
bts.setWriteAuthorizationCallback(blockServerWriteHandler);
bts.setReadAuthorizationCallback(blockServerReadHandler);
// ble setup complete - start advertising
ble.gap().startAdvertising();
printf("Voytalk Test: %s %s\r\n", __DATE__, __TIME__);
}
/*****************************************************************************/
/* Compatibility */
/*****************************************************************************/
#if defined(YOTTA_MINAR_VERSION_STRING)
/*********************************************************/
/* Build for mbed OS */
/*********************************************************/
void signalReady()
{
minar::Scheduler::postCallback(blockServerSendNotification);
}
#else
/*********************************************************/
/* Build for mbed Classic */
/*********************************************************/
bool sendNotification = false;
void signalReady()
{
sendNotification = true;
}
int main(void)
{
app_start(0, NULL);
for(;;)
{
// send notification outside of interrupt context
if (sendNotification)
{
sendNotification = false;
blockServerSendNotification();
}
ble.waitForEvent();
}
}
#endif
<commit_msg>use middleware support<commit_after>/* mbed Microcontroller Library
* Copyright (c) 2006-2015 ARM Limited
*
* 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 "mbed.h"
#include "ble/BLE.h"
#include "ble-blocktransfer/BlockTransferService.h"
#include "voytalk/Voytalk.h"
/*****************************************************************************/
/* Configuration */
/*****************************************************************************/
// set device name
const char DEVICE_NAME[] = "Testoy";
// set TX power
#ifndef CFG_BLE_TX_POWER_LEVEL
#define CFG_BLE_TX_POWER_LEVEL 0
#endif
// control debug output
#if 1
#define DEBUGOUT(...) { printf(__VA_ARGS__); }
#else
#define DEBUGOUT(...) /* nothing */
#endif // DEBUGOUT
/*****************************************************************************/
/* Voytalk short UUID */
const UUID uuid(0xFE8E);
/* Voytalk states */
typedef enum {
FLAG_CONNECTED = 0x01,
FLAG_PROVISIONED = 0x02,
} flags_t;
static volatile uint8_t state;
/*****************************************************************************/
/* Global variables used by the test app */
/*****************************************************************************/
// BLE_API ble device
BLE ble;
// Transfer large blocks of data on platforms without Fragmentation-And-Recombination
BlockTransferService bts;
// Voytalk handling
VoytalkRouter router(DEVICE_NAME);
// buffer for sending and receiving data
SharedPointer<Block> writeBlock;
uint8_t readBuffer[1000];
BlockStatic readBlock(readBuffer, sizeof(readBuffer));
// wifi parameters
std::string ssid_string;
std::string key_string;
// Compatibility function
void signalReady();
/*****************************************************************************/
/* Functions for handling debug output */
/*****************************************************************************/
/*
Functions called when BLE device connects and disconnects.
*/
void whenConnected(const Gap::ConnectionCallbackParams_t* params)
{
(void) params;
DEBUGOUT("main: Connected: %d %d %d\r\n", params->connectionParams->minConnectionInterval,
params->connectionParams->maxConnectionInterval,
params->connectionParams->slaveLatency);
// change state in main application
state |= FLAG_CONNECTED;
// change state inside Voytalk hub
router.setStateMask(state);
}
void whenDisconnected(const Gap::DisconnectionCallbackParams_t*)
{
DEBUGOUT("main: Disconnected!\r\n");
DEBUGOUT("main: Restarting the advertising process\r\n");
ble.gap().startAdvertising();
// change state in main application
state &= ~FLAG_CONNECTED;
// change state inside Voytalk hub
router.setStateMask(state);
}
/*****************************************************************************/
/* BlockTransfer callbacks for sending and receiving data */
/*****************************************************************************/
/*
Function called when signaling client that new data is ready to be read.
*/
void blockServerSendNotification()
{
DEBUGOUT("main: notify read updated\r\n");
bts.updateCharacteristicValue((uint8_t*)"", 0);
}
/*
Function called when device receives a read request over BLE.
*/
SharedPointer<Block> blockServerReadHandler(uint32_t offset)
{
DEBUGOUT("main: block read\r\n");
(void) offset;
return SharedPointer<Block>(new BlockStatic(readBlock));
}
/*
Function called when data has been written over BLE.
*/
void blockServerWriteHandler(SharedPointer<Block> block)
{
DEBUGOUT("main: block write\r\n");
/*
Process received data, assuming it is CBOR encoded.
Any output generated will be written to the readBlock.
*/
router.processCBOR((BlockStatic*) block.get(), &readBlock);
/*
If the readBlock length is non-zero it means a reply has been generated.
*/
if (readBlock.getLength() > 0)
{
signalReady();
}
}
/*****************************************************************************/
/* Voytalk Wifi example */
/*****************************************************************************/
/*
Callback function for constructing wifi intent.
*/
void wifiIntentConstruction(VTRequest& req, VTResponse& res)
{
DEBUGOUT("main: wifi intent construction\r\n");
/* create intent using generated endpoint and constraint set */
VTIntent intent("com.arm.connectivity.wifi");
intent.knownParameters("/networks")
.endpoint("/wifi");
res.write(intent);
}
/*****************************************************************************/
/* Reset device example */
/*****************************************************************************/
void resetIntentConstruction(VTRequest& req, VTResponse& res)
{
DEBUGOUT("main: reset intent construction\r\n");
/* create intent using generated endpoint and constraint set */
VTIntent intent("com.arm.reset");
intent.endpoint("/reset");
res.write(intent);
}
/*****************************************************************************/
/* Voytalk complex example */
/*****************************************************************************/
/*
Callback functions for the example intent.
*/
void exampleIntentConstruction(VTRequest& req, VTResponse& res)
{
DEBUGOUT("main: complex example intent construction\r\n");
/* create intent */
VTIntent intent("com.arm.examples.complex");
intent.endpoint("/examples/complex");
res.write(intent);
}
/*****************************************************************************/
/* Voytalk custom example */
/*****************************************************************************/
void customIntentConstruction(VTRequest& req, VTResponse& res)
{
DEBUGOUT("main: custom intent construction\r\n");
/* create intent using generated endpoint and constraint set */
VTIntent intent("com.arm.examples.custom");
intent.endpoint("/custom")
.constraints()
.title("Hello!")
.description("This is the description")
.addConstraint("test",
VTConstraint(VTConstraint::TypeString)
.title("Test")
.defaultValue("default goes here")
)
.addConstraint("test2",
VTConstraint(VTConstraint::TypeString)
.title("Other test")
.defaultValue("default goes here")
);
res.write(intent);
}
/*****************************************************************************/
/* Middleware for actually doing stuff */
/*****************************************************************************/
void printInvocation(VTRequest& req, VTResponse& res, VoytalkRouter::done_t done)
{
VTIntentInvocation invocation(req.getBody());
invocation.getParameters().print();
}
void saveWifi(VTRequest& req, VTResponse& res, VoytalkRouter::done_t done)
{
DEBUGOUT("main: saving wifi details\r\n");
VTIntentInvocation invocation(req.getBody());
invocation.getParameters().find("ssid").getString(ssid_string);
invocation.getParameters().find("key").getString(key_string);
// change state in main application
state |= FLAG_PROVISIONED;
// change state inside Voytalk hub
router.setStateMask(state);
}
void resetDevice(VTRequest& req, VTResponse& res, VoytalkRouter::done_t done)
{
DEBUGOUT("main: reset device\r\n");
ssid_string = "";
key_string = "";
// change state in main application
state &= ~FLAG_PROVISIONED;
// change state inside Voytalk hub
router.setStateMask(state);
}
void sendSuccess(VTRequest& req, VTResponse& res, VoytalkRouter::done_t done)
{
VTIntentInvocation invocation(req.getBody());
VTCoda coda(invocation.getID());
coda.success(true);
res.write(coda);
done(200);
}
void networkList(VTRequest& req, VTResponse& res, VoytalkRouter::done_t done)
{
DEBUGOUT("listing network resources");
VoytalkKnownParameters parameters(res, 2);
parameters.parameter("com.arm.connectivity.wifi", 50)
.map(2)
.key("ssid").value("miWifi")
.key("key").value("supersecurepassword");
parameters.parameter("com.arm.connectivity.wifi", 20)
.map(2)
.key("ssid").value("yoWifi")
.key("key").value("securepasswordinit");
done(200);
}
/*****************************************************************************/
/* main */
/*****************************************************************************/
void app_start(int, char *[])
{
/*
Register Voytalk intents in the hub.
First parameter is the callback function for intent generation.
Second parameter is a bitmap for grouping intents together.
*/
// Wifi provisioning intent
router.registerIntent(wifiIntentConstruction,
FLAG_CONNECTED | FLAG_PROVISIONED);
// reset intent
router.registerIntent(resetIntentConstruction,
FLAG_PROVISIONED);
// custom intent
//router.registerIntent(customIntentConstruction,
// FLAG_CONNECTED | FLAG_PROVISIONED);
// example intent
router.registerIntent(exampleIntentConstruction,
FLAG_CONNECTED | FLAG_PROVISIONED);
/*
Set the current state mask.
Mask is AND'ed with each intent's bitmap and only intents with non-zero
results are displayed and can be invoked.
*/
router.setStateMask(0);
/*
Define some resource callbacks
*/
router.get("/networks", networkList, NULL);
router.post("/wifi", printInvocation, saveWifi, sendSuccess, NULL);
router.post("/reset", printInvocation, resetDevice, sendSuccess, NULL);
router.post("/custom", printInvocation, sendSuccess, NULL);
router.post("/examples/complex", printInvocation, sendSuccess, NULL);
/*************************************************************************/
/*************************************************************************/
/* bluetooth le */
ble.init();
// status callback functions
ble.gap().onConnection(whenConnected);
ble.gap().onDisconnection(whenDisconnected);
/* construct advertising beacon */
ble.gap().accumulateAdvertisingPayload(GapAdvertisingData::BREDR_NOT_SUPPORTED|GapAdvertisingData::LE_GENERAL_DISCOVERABLE);
ble.gap().accumulateAdvertisingPayload(GapAdvertisingData::SHORTENED_LOCAL_NAME, (const uint8_t *) DEVICE_NAME, sizeof(DEVICE_NAME) - 1);
ble.gap().accumulateAdvertisingPayload(GapAdvertisingData::COMPLETE_LIST_16BIT_SERVICE_IDS, uuid.getBaseUUID(), uuid.getLen());
ble.gap().accumulateAdvertisingPayloadTxPower(CFG_BLE_TX_POWER_LEVEL);
ble.gap().setAdvertisingType(GapAdvertisingParams::ADV_CONNECTABLE_UNDIRECTED);
ble.gap().setAdvertisingInterval(1000); /* 1s; in multiples of 0.625ms. */
// set TX power
ble.gap().setTxPower(CFG_BLE_TX_POWER_LEVEL);
// Apple uses device name instead of beacon name
ble.gap().setDeviceName((const uint8_t*) DEVICE_NAME);
/*************************************************************************/
/*************************************************************************/
// setup block transfer service
// add service using ble device, responding to uuid, and without encryption
bts.init(uuid, SecurityManager::SECURITY_MODE_ENCRYPTION_OPEN_LINK);
// set callback functions for the BlockTransfer service
bts.setWriteAuthorizationCallback(blockServerWriteHandler);
bts.setReadAuthorizationCallback(blockServerReadHandler);
// ble setup complete - start advertising
ble.gap().startAdvertising();
printf("Voytalk Test: %s %s\r\n", __DATE__, __TIME__);
}
/*****************************************************************************/
/* Compatibility */
/*****************************************************************************/
#if defined(YOTTA_MINAR_VERSION_STRING)
/*********************************************************/
/* Build for mbed OS */
/*********************************************************/
void signalReady()
{
minar::Scheduler::postCallback(blockServerSendNotification);
}
#else
/*********************************************************/
/* Build for mbed Classic */
/*********************************************************/
bool sendNotification = false;
void signalReady()
{
sendNotification = true;
}
int main(void)
{
app_start(0, NULL);
for(;;)
{
// send notification outside of interrupt context
if (sendNotification)
{
sendNotification = false;
blockServerSendNotification();
}
ble.waitForEvent();
}
}
#endif
<|endoftext|> |
<commit_before>/*
The MIT License (MIT)
Copyright (c) 2016 British Broadcasting Corporation.
This software is provided by Lancaster University by arrangement with the BBC.
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 "MicroBit.h"
#include "MicroBitUARTService.h"
#include "EventLookup.h"
MicroBit uBit;
MicroBitUARTService *uart;
MicroBitSerial *serial;
void onGesture(MicroBitEvent e) {
ManagedString Event = lookupGesture(uBit, e.value);
ManagedString ShortEvent = lookupGesture(uBit, e.value, true);
if (e.value != MICROBIT_ACCELEROMETER_EVT_NONE) {
uBit.display.printAsync(ShortEvent);
serial->send(Event);
}
}
int main()
{
// Initialise the micro:bit runtime.
uBit.init();
uart = new MicroBitUARTService(*uBit.ble, 32, 32);
serial = new MicroBitSerial(USBTX, USBRX);
uBit.messageBus.listen(MICROBIT_ID_GESTURE, MICROBIT_EVT_ANY, onGesture);
while(1)
{
uBit.sleep(100);
}
// If main exits, there may still be other fibers running or registered Event handlers etc.
// Simply release this fiber, which will mean we enter the scheduler. Worse case, we then
// sit in the idle task forever, in a power efficient sleep.
release_fiber();
}
<commit_msg>license comment<commit_after>/*
TODO - add licensing
Copyright (c) 2016 Will Lovett
*/
#include "MicroBit.h"
#include "MicroBitUARTService.h"
#include "EventLookup.h"
MicroBit uBit;
MicroBitUARTService *uart;
MicroBitSerial *serial;
void onGesture(MicroBitEvent e) {
ManagedString Event = lookupGesture(uBit, e.value);
ManagedString ShortEvent = lookupGesture(uBit, e.value, true);
if (e.value != MICROBIT_ACCELEROMETER_EVT_NONE) {
uBit.display.printAsync(ShortEvent);
serial->send(Event);
}
}
int main()
{
// Initialise the micro:bit runtime.
uBit.init();
uart = new MicroBitUARTService(*uBit.ble, 32, 32);
serial = new MicroBitSerial(USBTX, USBRX);
uBit.messageBus.listen(MICROBIT_ID_GESTURE, MICROBIT_EVT_ANY, onGesture);
while(1)
{
uBit.sleep(100);
}
// If main exits, there may still be other fibers running or registered Event handlers etc.
// Simply release this fiber, which will mean we enter the scheduler. Worse case, we then
// sit in the idle task forever, in a power efficient sleep.
release_fiber();
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <string>
#include "TrelScript.h"
///////////////////////////////////////////////////////////
// Main function //
///////////////////////////////////////////////////////////
int main()
{
TrelScript *ts = new TrelScript("testfile.trole");
ts->runScript();
delete ts;
std::cout << "Press enter to exit.";
std::cin.get();
return 0;
}<commit_msg>can now load scripts from the command line<commit_after>#include <iostream>
#include <string>
#include "TrelScript.h"
///////////////////////////////////////////////////////////
// Main function //
///////////////////////////////////////////////////////////
int main(int argc, char **argv)
{
std::string filename = "testfile.trole";
if(argc > 0)
{
if(argv[1] != NULL)
filename = argv[1];
}
TrelScript *ts = new TrelScript(filename);
ts->runScript();
delete ts;
std::cout << "Press enter to exit.";
std::cin.get();
return 0;
}<|endoftext|> |
<commit_before>#include <iostream>
#include <string>
#include "TrelScript.h"
///////////////////////////////////////////////////////////
// Main function //
///////////////////////////////////////////////////////////
int main()
{
TrelScript *ts = new TrelScript();
ts->runScript();
system("pause");
return 0;
}<commit_msg>now actually loads a file, no more memory leaks<commit_after>#include <iostream>
#include <string>
#include "TrelScript.h"
///////////////////////////////////////////////////////////
// Main function //
///////////////////////////////////////////////////////////
int main()
{
TrelScript *ts = new TrelScript("testfile.trole");
ts->runScript();
delete ts;
system("pause");
return 0;
}<|endoftext|> |
<commit_before>#include <ctrcommon/common.hpp>
#include <sstream>
#include <iomanip>
#include <stdio.h>
typedef enum {
INSTALL,
DELETE
} Mode;
int main(int argc, char **argv) {
if(!platform_init()) {
return 0;
}
std::vector<std::string> extensions;
extensions.push_back("cia");
MediaType destination = SD;
Mode mode = INSTALL;
bool netInstall = false;
u64 freeSpace = fs_get_free_space(destination);
auto onLoop = [&]() {
bool breakLoop = false;
if(input_is_pressed(BUTTON_L)) {
if(destination == SD) {
destination = NAND;
} else {
destination = SD;
}
freeSpace = fs_get_free_space(destination);
if(mode == DELETE) {
breakLoop = true;
}
}
if(input_is_pressed(BUTTON_R)) {
if(mode == INSTALL) {
mode = DELETE;
} else {
mode = INSTALL;
}
breakLoop = true;
}
if(input_is_pressed(BUTTON_Y)) {
netInstall = true;
breakLoop = true;
}
std::stringstream stream;
stream << "Free Space: " << freeSpace << " bytes (" << std::fixed << std::setprecision(2) << freeSpace / 1024.0f / 1024.0f << "MB)" << "\n";
stream << "Destination: " << (destination == NAND ? "NAND" : "SD") << ", Mode: " << (mode == INSTALL ? "Install" : "Delete") << "\n";
stream << "L - Switch Destination, R - Switch Mode" << "\n";
stream << "Y - Receive an app over the network" << "\n";
std::string str = stream.str();
screen_draw_string(str, (screen_get_width() - screen_get_str_width(str)) / 2, screen_get_height() - 4 - screen_get_str_height(str), 255, 255, 255);
return breakLoop;
};
auto onProgress = [&](int progress) {
ui_display_progress(TOP_SCREEN, "Installing", "Press B to cancel.", true, progress);
input_poll();
return !input_is_pressed(BUTTON_B);
};
while(platform_is_running()) {
std::string targetInstall;
App targetDelete;
bool obtained = false;
if(mode == INSTALL) {
obtained = ui_select_file(&targetInstall, "sdmc:", extensions, [&](bool inRoot) {
return onLoop();
});
} else if(mode == DELETE) {
obtained = ui_select_app(&targetDelete, destination, onLoop);
}
if(netInstall) {
netInstall = false;
screen_clear_buffers(BOTTOM_SCREEN, 0, 0, 0);
RemoteFile file = ui_accept_remote_file(TOP_SCREEN);
if(file.fd == NULL) {
continue;
}
std::stringstream confirmStream;
confirmStream << "Install the received application?" << "\n";
confirmStream << "Size: " << file.fileSize << " bytes (" << std::fixed << std::setprecision(2) << file.fileSize / 1024.0f / 1024.0f << "MB)" << "\n";
if(ui_prompt(TOP_SCREEN, confirmStream.str(), true)) {
AppResult ret = app_install(destination, file.fd, file.fileSize, onProgress);
std::stringstream resultMsg;
if(mode == INSTALL) {
resultMsg << "Install ";
} else if(mode == DELETE) {
resultMsg << "Delete ";
}
if(ret == APP_SUCCESS) {
resultMsg << "succeeded!";
} else {
resultMsg << "failed!" << "\n";
resultMsg << app_get_result_string(ret) << "\n";
}
ui_prompt(TOP_SCREEN, resultMsg.str(), false);
}
fclose(file.fd);
continue;
}
if(obtained) {
std::stringstream prompt;
if(mode == INSTALL) {
prompt << "Install ";
} else if(mode == DELETE) {
prompt << "Delete ";
}
prompt << "the selected title?";
if(ui_prompt(TOP_SCREEN, prompt.str(), true)) {
AppResult ret = APP_SUCCESS;
if(mode == INSTALL) {
ret = app_install_file(destination, targetInstall, onProgress);
} else if(mode == DELETE) {
ui_display_message(TOP_SCREEN, "Deleting title...");
ret = app_delete(targetDelete);
}
std::stringstream resultMsg;
if(mode == INSTALL) {
resultMsg << "Install ";
} else if(mode == DELETE) {
resultMsg << "Delete ";
}
if(ret == APP_SUCCESS) {
resultMsg << "succeeded!";
} else {
resultMsg << "failed!" << "\n";
resultMsg << app_get_result_string(ret) << "\n";
}
ui_prompt(TOP_SCREEN, resultMsg.str(), false);
freeSpace = fs_get_free_space(destination);
}
}
}
platform_cleanup();
return 0;
}
<commit_msg>Update for ctrcommon changes.<commit_after>#include <ctrcommon/input.hpp>
#include <ctrcommon/platform.hpp>
#include <ctrcommon/ui.hpp>
#include <sstream>
#include <iomanip>
#include <stdio.h>
typedef enum {
INSTALL,
DELETE
} Mode;
int main(int argc, char **argv) {
if(!platform_init()) {
return 0;
}
std::vector<std::string> extensions;
extensions.push_back("cia");
MediaType destination = SD;
Mode mode = INSTALL;
bool netInstall = false;
u64 freeSpace = fs_get_free_space(destination);
auto onLoop = [&]() {
bool breakLoop = false;
if(input_is_pressed(BUTTON_L)) {
if(destination == SD) {
destination = NAND;
} else {
destination = SD;
}
freeSpace = fs_get_free_space(destination);
if(mode == DELETE) {
breakLoop = true;
}
}
if(input_is_pressed(BUTTON_R)) {
if(mode == INSTALL) {
mode = DELETE;
} else {
mode = INSTALL;
}
breakLoop = true;
}
if(input_is_pressed(BUTTON_Y)) {
netInstall = true;
breakLoop = true;
}
std::stringstream stream;
stream << "Free Space: " << freeSpace << " bytes (" << std::fixed << std::setprecision(2) << freeSpace / 1024.0f / 1024.0f << "MB)" << "\n";
stream << "Destination: " << (destination == NAND ? "NAND" : "SD") << ", Mode: " << (mode == INSTALL ? "Install" : "Delete") << "\n";
stream << "L - Switch Destination, R - Switch Mode" << "\n";
stream << "Y - Receive an app over the network" << "\n";
std::string str = stream.str();
screen_draw_string(str, (screen_get_width() - screen_get_str_width(str)) / 2, screen_get_height() - 4 - screen_get_str_height(str), 255, 255, 255);
return breakLoop;
};
auto onProgress = [&](int progress) {
ui_display_progress(TOP_SCREEN, "Installing", "Press B to cancel.", true, progress);
input_poll();
return !input_is_pressed(BUTTON_B);
};
while(platform_is_running()) {
std::string targetInstall;
App targetDelete;
bool obtained = false;
if(mode == INSTALL) {
obtained = ui_select_file(&targetInstall, "sdmc:", extensions, [&](bool inRoot) {
return onLoop();
});
} else if(mode == DELETE) {
obtained = ui_select_app(&targetDelete, destination, onLoop);
}
if(netInstall) {
netInstall = false;
screen_clear_buffers(BOTTOM_SCREEN, 0, 0, 0);
RemoteFile file = ui_accept_remote_file(TOP_SCREEN);
if(file.fd == NULL) {
continue;
}
std::stringstream confirmStream;
confirmStream << "Install the received application?" << "\n";
confirmStream << "Size: " << file.fileSize << " bytes (" << std::fixed << std::setprecision(2) << file.fileSize / 1024.0f / 1024.0f << "MB)" << "\n";
if(ui_prompt(TOP_SCREEN, confirmStream.str(), true)) {
AppResult ret = app_install(destination, file.fd, file.fileSize, onProgress);
std::stringstream resultMsg;
if(mode == INSTALL) {
resultMsg << "Install ";
} else if(mode == DELETE) {
resultMsg << "Delete ";
}
if(ret == APP_SUCCESS) {
resultMsg << "succeeded!";
} else {
resultMsg << "failed!" << "\n";
resultMsg << app_get_result_string(ret) << "\n";
}
ui_prompt(TOP_SCREEN, resultMsg.str(), false);
}
fclose(file.fd);
continue;
}
if(obtained) {
std::stringstream prompt;
if(mode == INSTALL) {
prompt << "Install ";
} else if(mode == DELETE) {
prompt << "Delete ";
}
prompt << "the selected title?";
if(ui_prompt(TOP_SCREEN, prompt.str(), true)) {
AppResult ret = APP_SUCCESS;
if(mode == INSTALL) {
ret = app_install_file(destination, targetInstall, onProgress);
} else if(mode == DELETE) {
ui_display_message(TOP_SCREEN, "Deleting title...");
ret = app_delete(targetDelete);
}
std::stringstream resultMsg;
if(mode == INSTALL) {
resultMsg << "Install ";
} else if(mode == DELETE) {
resultMsg << "Delete ";
}
if(ret == APP_SUCCESS) {
resultMsg << "succeeded!";
} else {
resultMsg << "failed!" << "\n";
resultMsg << app_get_result_string(ret) << "\n";
}
ui_prompt(TOP_SCREEN, resultMsg.str(), false);
freeSpace = fs_get_free_space(destination);
}
}
}
platform_cleanup();
return 0;
}
<|endoftext|> |
<commit_before>#ifdef PIXELBOOST_PLATFORM_ANDROID
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <ifaddrs.h>
#include "pixelboost/network/networkHelpers.h"
namespace pb
{
namespace NetworkHelpers
{
std::string GetWifiAddress()
{
return "";
}
}
}
#endif<commit_msg>Fix Android compile error<commit_after>#ifdef PIXELBOOST_PLATFORM_ANDROID
#include "pixelboost/network/networkHelpers.h"
namespace pb
{
namespace NetworkHelpers
{
std::string GetWifiAddress()
{
return "";
}
}
}
#endif<|endoftext|> |
<commit_before>/***************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2008 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Qt Software Information ([email protected])
**
**
** Non-Open Source Usage
**
** Licensees may use this file in accordance with the Qt Beta Version
** License Agreement, Agreement version 2.2 provided with the Software or,
** alternatively, in accordance with the terms contained in a written
** agreement between you and Nokia.
**
** GNU General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU General
** Public License versions 2.0 or 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the packaging
** of this file. Please review the following information to ensure GNU
** General Public Licensing requirements will be met:
**
** http://www.fsf.org/licensing/licenses/info/GPLv2.html and
** http://www.gnu.org/copyleft/gpl.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt GPL Exception
** version 1.2, included in the file GPL_EXCEPTION.txt in this package.
**
***************************************************************************/
#include "stackededitorgroup.h"
#include "editormanager.h"
#include "coreimpl.h"
#include <utils/qtcassert.h>
#include <QtCore/QDebug>
#include <QtCore/QDir>
#include <QtCore/QFileInfo>
#include <QtCore/QMimeData>
#include <QtGui/QApplication>
#include <QtGui/QComboBox>
#include <QtGui/QHBoxLayout>
#include <QtGui/QLabel>
#include <QtGui/QMouseEvent>
#include <QtGui/QPainter>
#include <QtGui/QStackedWidget>
#include <QtGui/QStyle>
#include <QtGui/QStyleOption>
#include <QtGui/QToolBar>
#include <QtGui/QToolButton>
#ifdef Q_WS_MAC
#include <qmacstyle_mac.h>
#endif
Q_DECLARE_METATYPE(Core::IEditor *)
using namespace Core;
using namespace Core::Internal;
StackedEditorGroup::StackedEditorGroup(QWidget *parent) :
EditorGroup(parent),
m_toplevel(new QWidget),
m_toolBar(new QWidget),
m_container(new QStackedWidget(this)),
m_editorList(new QComboBox),
m_closeButton(new QToolButton),
m_lockButton(new QToolButton),
m_defaultToolBar(new QToolBar(this)),
m_infoWidget(new QFrame(this)),
m_editorForInfoWidget(0)
{
QVBoxLayout *tl = new QVBoxLayout(m_toplevel);
tl->setSpacing(0);
tl->setMargin(0);
{
m_editorList->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
m_editorList->setMinimumContentsLength(20);
m_proxyModel.setSourceModel(model());
m_proxyModel.sort(0);
m_editorList->setModel(&m_proxyModel);
m_editorList->setMaxVisibleItems(40);
QToolBar *editorListToolBar = new QToolBar;
editorListToolBar->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Ignored);
editorListToolBar->addWidget(m_editorList);
m_defaultToolBar->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum);
m_activeToolBar = m_defaultToolBar;
QHBoxLayout *toolBarLayout = new QHBoxLayout;
toolBarLayout->setMargin(0);
toolBarLayout->setSpacing(0);
toolBarLayout->addWidget(m_defaultToolBar);
m_toolBar->setLayout(toolBarLayout);
m_lockButton->setAutoRaise(true);
m_lockButton->setProperty("type", QLatin1String("dockbutton"));
m_closeButton->setAutoRaise(true);
m_closeButton->setIcon(QIcon(":/qworkbench/images/closebutton.png"));
m_closeButton->setProperty("type", QLatin1String("dockbutton"));
QToolBar *rightToolBar = new QToolBar;
rightToolBar->setLayoutDirection(Qt::RightToLeft);
rightToolBar->addWidget(m_closeButton);
rightToolBar->addWidget(m_lockButton);
QHBoxLayout *toplayout = new QHBoxLayout;
toplayout->setSpacing(0);
toplayout->setMargin(0);
toplayout->addWidget(editorListToolBar);
toplayout->addWidget(m_toolBar, 1); // Custom toolbar stretches
toplayout->addWidget(rightToolBar);
QWidget *top = new QWidget;
QVBoxLayout *vlayout = new QVBoxLayout(top);
vlayout->setSpacing(0);
vlayout->setMargin(0);
vlayout->addLayout(toplayout);
tl->addWidget(top);
connect(m_editorList, SIGNAL(currentIndexChanged(int)), this, SLOT(listSelectionChanged(int)));
connect(m_lockButton, SIGNAL(clicked()), this, SLOT(makeEditorWritable()));
connect(m_closeButton, SIGNAL(clicked()), this, SLOT(sendCloseRequest()));
}
{
m_infoWidget->setFrameStyle(QFrame::Panel | QFrame::Raised);
m_infoWidget->setLineWidth(1);
m_infoWidget->setForegroundRole(QPalette::ToolTipText);
m_infoWidget->setBackgroundRole(QPalette::ToolTipBase);
m_infoWidget->setAutoFillBackground(true);
QHBoxLayout *hbox = new QHBoxLayout(m_infoWidget);
hbox->setMargin(2);
m_infoWidgetLabel = new QLabel("Placeholder");
m_infoWidgetLabel->setForegroundRole(QPalette::ToolTipText);
hbox->addWidget(m_infoWidgetLabel);
hbox->addStretch(1);
m_infoWidgetButton = new QToolButton;
m_infoWidgetButton->setText(tr("Placeholder"));
hbox->addWidget(m_infoWidgetButton);
QToolButton *closeButton = new QToolButton;
closeButton->setAutoRaise(true);
closeButton->setIcon(QIcon(":/qworkbench/images/clear.png"));
closeButton->setToolTip(tr("Close"));
connect(closeButton, SIGNAL(clicked()), m_infoWidget, SLOT(hide()));
hbox->addWidget(closeButton);
tl->addWidget(m_infoWidget);
}
tl->addWidget(m_container);
QHBoxLayout *l = new QHBoxLayout;
l->setSpacing(0);
l->setMargin(0);
l->addWidget(m_toplevel);
setLayout(l);
m_toplevel->setVisible(false);
}
void StackedEditorGroup::showEditorInfoBar(const QString &kind,
const QString &infoText,
const QString &buttonText,
QObject *object, const char *member)
{
m_infoWidgetKind = kind;
m_infoWidgetLabel->setText(infoText);
m_infoWidgetButton->setText(buttonText);
m_infoWidgetButton->disconnect();
if (object && member)
connect(m_infoWidgetButton, SIGNAL(clicked()), object, member);
m_infoWidget->setVisible(true);
m_editorForInfoWidget = currentEditor();
}
void StackedEditorGroup::hideEditorInfoBar(const QString &kind)
{
if (kind == m_infoWidgetKind)
m_infoWidget->setVisible(false);
}
StackedEditorGroup::~StackedEditorGroup()
{
}
void StackedEditorGroup::focusInEvent(QFocusEvent *e)
{
if (m_container->count() > 0) {
setEditorFocus(m_container->currentIndex());
} else {
EditorGroup::focusInEvent(e);
}
}
void StackedEditorGroup::setEditorFocus(int index)
{
QWidget *w = m_container->widget(index);
w->setFocus();
}
void StackedEditorGroup::addEditor(IEditor *editor)
{
insertEditor(editorCount(), editor);
}
void StackedEditorGroup::insertEditor(int index, IEditor *editor)
{
EditorGroup::insertEditor(index, editor);
if (m_container->indexOf(editor->widget()) != -1)
return;
m_container->insertWidget(index, editor->widget());
m_widgetEditorMap.insert(editor->widget(), editor);
QToolBar *toolBar = editor->toolBar();
if (toolBar)
m_toolBar->layout()->addWidget(toolBar);
connect(editor, SIGNAL(changed()), this, SLOT(updateEditorStatus()));
updateEditorStatus(editor);
updateToolBar(editor);
emit editorAdded(editor);
}
void StackedEditorGroup::sendCloseRequest()
{
emit closeRequested(currentEditor());
}
void StackedEditorGroup::removeEditor(IEditor *editor)
{
QTC_ASSERT(editor, return);
EditorGroup::removeEditor(editor);
const int index = m_container->indexOf(editor->widget());
if (index != -1) {
m_container->removeWidget(editor->widget());
m_widgetEditorMap.remove(editor->widget());
editor->widget()->setParent(0);
disconnect(editor, SIGNAL(changed()), this, SLOT(updateEditorStatus()));
QToolBar *toolBar = editor->toolBar();
if (toolBar != 0) {
if (m_activeToolBar == toolBar) {
m_activeToolBar = m_defaultToolBar;
m_activeToolBar->setVisible(true);
}
m_toolBar->layout()->removeWidget(toolBar);
toolBar->setVisible(false);
toolBar->setParent(0);
}
if (m_container->count() == 0) {
m_toplevel->setVisible(false);
setFocus();
}
emit editorRemoved(editor);
}
}
IEditor *StackedEditorGroup::currentEditor() const
{
if (m_container->count() > 0)
return m_widgetEditorMap.value(m_container->currentWidget());
return 0;
}
void StackedEditorGroup::setCurrentEditor(IEditor *editor)
{
if (!editor || m_container->count() <= 0
|| m_container->indexOf(editor->widget()) == -1)
return;
m_toplevel->setVisible(true);
const int idx = m_container->indexOf(editor->widget());
QTC_ASSERT(idx >= 0, return);
if (m_container->currentIndex() != idx) {
m_container->setCurrentIndex(idx);
const bool block = m_editorList->blockSignals(true);
m_editorList->setCurrentIndex(indexOf(editor));
m_editorList->blockSignals(block);
updateEditorStatus(editor);
updateToolBar(editor);
}
setEditorFocus(idx);
if (editor != m_editorForInfoWidget) {
m_infoWidget->hide();
m_editorForInfoWidget = 0;
}
}
void StackedEditorGroup::updateEditorStatus(IEditor *editor)
{
if (!editor)
editor = qobject_cast<IEditor *>(sender());
QTC_ASSERT(editor, return);
static const QIcon lockedIcon(QLatin1String(":/qworkbench/images/locked.png"));
static const QIcon unlockedIcon(QLatin1String(":/qworkbench/images/unlocked.png"));
if (editor->file()->isReadOnly()) {
m_lockButton->setIcon(lockedIcon);
m_lockButton->setEnabled(!editor->file()->fileName().isEmpty());
m_lockButton->setToolTip(tr("Make writable"));
} else {
m_lockButton->setIcon(unlockedIcon);
m_lockButton->setEnabled(false);
m_lockButton->setToolTip(tr("File is writable"));
}
if (currentEditor() == editor)
m_editorList->setToolTip(model()->data(model()->indexOf(editor), Qt::ToolTipRole).toString());
model()->emitDataChanged(editor);
}
void StackedEditorGroup::updateToolBar(IEditor *editor)
{
QToolBar *toolBar = editor->toolBar();
if (!toolBar)
toolBar = m_defaultToolBar;
if (m_activeToolBar == toolBar)
return;
m_activeToolBar->setVisible(false);
toolBar->setVisible(true);
m_activeToolBar = toolBar;
}
int StackedEditorGroup::editorCount() const
{
return model()->editors().count();
}
QList<IEditor *> StackedEditorGroup::editors() const
{
QAbstractItemModel *model = m_editorList->model();
QList<IEditor*> output;
int rows = model->rowCount();
for (int i = 0; i < rows; ++i)
output.append(model->data(model->index(i, 0), Qt::UserRole).value<IEditor*>());
return output;
}
QList<IEditor *> StackedEditorGroup::editorsInNaturalOrder() const
{
return model()->editors();
}
void StackedEditorGroup::makeEditorWritable()
{
CoreImpl::instance()->editorManager()->makeEditorWritable(currentEditor());
}
void StackedEditorGroup::listSelectionChanged(int index)
{
QAbstractItemModel *model = m_editorList->model();
setCurrentEditor(model->data(model->index(index, 0), Qt::UserRole).value<IEditor*>());
}
int StackedEditorGroup::indexOf(IEditor *editor)
{
QAbstractItemModel *model = m_editorList->model();
int rows = model->rowCount();
for (int i = 0; i < rows; ++i) {
if (editor == model->data(model->index(i, 0), Qt::UserRole).value<IEditor*>())
return i;
}
QTC_ASSERT(false, /**/);
return 0;
}
<commit_msg>fix show on split<commit_after>/***************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2008 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Qt Software Information ([email protected])
**
**
** Non-Open Source Usage
**
** Licensees may use this file in accordance with the Qt Beta Version
** License Agreement, Agreement version 2.2 provided with the Software or,
** alternatively, in accordance with the terms contained in a written
** agreement between you and Nokia.
**
** GNU General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU General
** Public License versions 2.0 or 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the packaging
** of this file. Please review the following information to ensure GNU
** General Public Licensing requirements will be met:
**
** http://www.fsf.org/licensing/licenses/info/GPLv2.html and
** http://www.gnu.org/copyleft/gpl.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt GPL Exception
** version 1.2, included in the file GPL_EXCEPTION.txt in this package.
**
***************************************************************************/
#include "stackededitorgroup.h"
#include "editormanager.h"
#include "coreimpl.h"
#include <utils/qtcassert.h>
#include <QtCore/QDebug>
#include <QtCore/QDir>
#include <QtCore/QFileInfo>
#include <QtCore/QMimeData>
#include <QtGui/QApplication>
#include <QtGui/QComboBox>
#include <QtGui/QHBoxLayout>
#include <QtGui/QLabel>
#include <QtGui/QMouseEvent>
#include <QtGui/QPainter>
#include <QtGui/QStackedWidget>
#include <QtGui/QStyle>
#include <QtGui/QStyleOption>
#include <QtGui/QToolBar>
#include <QtGui/QToolButton>
#ifdef Q_WS_MAC
#include <qmacstyle_mac.h>
#endif
Q_DECLARE_METATYPE(Core::IEditor *)
using namespace Core;
using namespace Core::Internal;
StackedEditorGroup::StackedEditorGroup(QWidget *parent) :
EditorGroup(parent),
m_toplevel(new QWidget),
m_toolBar(new QWidget),
m_container(new QStackedWidget(this)),
m_editorList(new QComboBox),
m_closeButton(new QToolButton),
m_lockButton(new QToolButton),
m_defaultToolBar(new QToolBar(this)),
m_infoWidget(new QFrame(this)),
m_editorForInfoWidget(0)
{
QVBoxLayout *tl = new QVBoxLayout(m_toplevel);
tl->setSpacing(0);
tl->setMargin(0);
{
m_editorList->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
m_editorList->setMinimumContentsLength(20);
m_proxyModel.setSourceModel(model());
m_proxyModel.sort(0);
m_editorList->setModel(&m_proxyModel);
m_editorList->setMaxVisibleItems(40);
QToolBar *editorListToolBar = new QToolBar;
editorListToolBar->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Ignored);
editorListToolBar->addWidget(m_editorList);
m_defaultToolBar->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum);
m_activeToolBar = m_defaultToolBar;
QHBoxLayout *toolBarLayout = new QHBoxLayout;
toolBarLayout->setMargin(0);
toolBarLayout->setSpacing(0);
toolBarLayout->addWidget(m_defaultToolBar);
m_toolBar->setLayout(toolBarLayout);
m_lockButton->setAutoRaise(true);
m_lockButton->setProperty("type", QLatin1String("dockbutton"));
m_closeButton->setAutoRaise(true);
m_closeButton->setIcon(QIcon(":/qworkbench/images/closebutton.png"));
m_closeButton->setProperty("type", QLatin1String("dockbutton"));
QToolBar *rightToolBar = new QToolBar;
rightToolBar->setLayoutDirection(Qt::RightToLeft);
rightToolBar->addWidget(m_closeButton);
rightToolBar->addWidget(m_lockButton);
QHBoxLayout *toplayout = new QHBoxLayout;
toplayout->setSpacing(0);
toplayout->setMargin(0);
toplayout->addWidget(editorListToolBar);
toplayout->addWidget(m_toolBar, 1); // Custom toolbar stretches
toplayout->addWidget(rightToolBar);
QWidget *top = new QWidget;
QVBoxLayout *vlayout = new QVBoxLayout(top);
vlayout->setSpacing(0);
vlayout->setMargin(0);
vlayout->addLayout(toplayout);
tl->addWidget(top);
connect(m_editorList, SIGNAL(currentIndexChanged(int)), this, SLOT(listSelectionChanged(int)));
connect(m_lockButton, SIGNAL(clicked()), this, SLOT(makeEditorWritable()));
connect(m_closeButton, SIGNAL(clicked()), this, SLOT(sendCloseRequest()));
}
{
m_infoWidget->setFrameStyle(QFrame::Panel | QFrame::Raised);
m_infoWidget->setLineWidth(1);
m_infoWidget->setForegroundRole(QPalette::ToolTipText);
m_infoWidget->setBackgroundRole(QPalette::ToolTipBase);
m_infoWidget->setAutoFillBackground(true);
QHBoxLayout *hbox = new QHBoxLayout(m_infoWidget);
hbox->setMargin(2);
m_infoWidgetLabel = new QLabel("Placeholder");
m_infoWidgetLabel->setForegroundRole(QPalette::ToolTipText);
hbox->addWidget(m_infoWidgetLabel);
hbox->addStretch(1);
m_infoWidgetButton = new QToolButton;
m_infoWidgetButton->setText(tr("Placeholder"));
hbox->addWidget(m_infoWidgetButton);
QToolButton *closeButton = new QToolButton;
closeButton->setAutoRaise(true);
closeButton->setIcon(QIcon(":/qworkbench/images/clear.png"));
closeButton->setToolTip(tr("Close"));
connect(closeButton, SIGNAL(clicked()), m_infoWidget, SLOT(hide()));
hbox->addWidget(closeButton);
m_infoWidget->setVisible(false);
tl->addWidget(m_infoWidget);
}
tl->addWidget(m_container);
QHBoxLayout *l = new QHBoxLayout;
l->setSpacing(0);
l->setMargin(0);
l->addWidget(m_toplevel);
setLayout(l);
}
void StackedEditorGroup::showEditorInfoBar(const QString &kind,
const QString &infoText,
const QString &buttonText,
QObject *object, const char *member)
{
m_infoWidgetKind = kind;
m_infoWidgetLabel->setText(infoText);
m_infoWidgetButton->setText(buttonText);
m_infoWidgetButton->disconnect();
if (object && member)
connect(m_infoWidgetButton, SIGNAL(clicked()), object, member);
m_infoWidget->setVisible(true);
m_editorForInfoWidget = currentEditor();
}
void StackedEditorGroup::hideEditorInfoBar(const QString &kind)
{
if (kind == m_infoWidgetKind)
m_infoWidget->setVisible(false);
}
StackedEditorGroup::~StackedEditorGroup()
{
}
void StackedEditorGroup::focusInEvent(QFocusEvent *e)
{
if (m_container->count() > 0) {
setEditorFocus(m_container->currentIndex());
} else {
EditorGroup::focusInEvent(e);
}
}
void StackedEditorGroup::setEditorFocus(int index)
{
QWidget *w = m_container->widget(index);
w->setFocus();
}
void StackedEditorGroup::addEditor(IEditor *editor)
{
insertEditor(editorCount(), editor);
}
void StackedEditorGroup::insertEditor(int index, IEditor *editor)
{
EditorGroup::insertEditor(index, editor);
if (m_container->indexOf(editor->widget()) != -1)
return;
m_container->insertWidget(index, editor->widget());
m_widgetEditorMap.insert(editor->widget(), editor);
QToolBar *toolBar = editor->toolBar();
if (toolBar)
m_toolBar->layout()->addWidget(toolBar);
connect(editor, SIGNAL(changed()), this, SLOT(updateEditorStatus()));
updateEditorStatus(editor);
updateToolBar(editor);
emit editorAdded(editor);
}
void StackedEditorGroup::sendCloseRequest()
{
emit closeRequested(currentEditor());
}
void StackedEditorGroup::removeEditor(IEditor *editor)
{
QTC_ASSERT(editor, return);
EditorGroup::removeEditor(editor);
const int index = m_container->indexOf(editor->widget());
if (index != -1) {
m_container->removeWidget(editor->widget());
m_widgetEditorMap.remove(editor->widget());
editor->widget()->setParent(0);
disconnect(editor, SIGNAL(changed()), this, SLOT(updateEditorStatus()));
QToolBar *toolBar = editor->toolBar();
if (toolBar != 0) {
if (m_activeToolBar == toolBar) {
m_activeToolBar = m_defaultToolBar;
m_activeToolBar->setVisible(true);
}
m_toolBar->layout()->removeWidget(toolBar);
toolBar->setVisible(false);
toolBar->setParent(0);
}
emit editorRemoved(editor);
}
}
IEditor *StackedEditorGroup::currentEditor() const
{
if (m_container->count() > 0)
return m_widgetEditorMap.value(m_container->currentWidget());
return 0;
}
void StackedEditorGroup::setCurrentEditor(IEditor *editor)
{
if (!editor || m_container->count() <= 0
|| m_container->indexOf(editor->widget()) == -1)
return;
const int idx = m_container->indexOf(editor->widget());
QTC_ASSERT(idx >= 0, return);
if (m_container->currentIndex() != idx) {
m_container->setCurrentIndex(idx);
const bool block = m_editorList->blockSignals(true);
m_editorList->setCurrentIndex(indexOf(editor));
m_editorList->blockSignals(block);
updateEditorStatus(editor);
updateToolBar(editor);
}
setEditorFocus(idx);
if (editor != m_editorForInfoWidget) {
m_infoWidget->hide();
m_editorForInfoWidget = 0;
}
}
void StackedEditorGroup::updateEditorStatus(IEditor *editor)
{
if (!editor)
editor = qobject_cast<IEditor *>(sender());
QTC_ASSERT(editor, return);
static const QIcon lockedIcon(QLatin1String(":/qworkbench/images/locked.png"));
static const QIcon unlockedIcon(QLatin1String(":/qworkbench/images/unlocked.png"));
if (editor->file()->isReadOnly()) {
m_lockButton->setIcon(lockedIcon);
m_lockButton->setEnabled(!editor->file()->fileName().isEmpty());
m_lockButton->setToolTip(tr("Make writable"));
} else {
m_lockButton->setIcon(unlockedIcon);
m_lockButton->setEnabled(false);
m_lockButton->setToolTip(tr("File is writable"));
}
if (currentEditor() == editor)
m_editorList->setToolTip(model()->data(model()->indexOf(editor), Qt::ToolTipRole).toString());
model()->emitDataChanged(editor);
}
void StackedEditorGroup::updateToolBar(IEditor *editor)
{
QToolBar *toolBar = editor->toolBar();
if (!toolBar)
toolBar = m_defaultToolBar;
if (m_activeToolBar == toolBar)
return;
m_activeToolBar->setVisible(false);
toolBar->setVisible(true);
m_activeToolBar = toolBar;
}
int StackedEditorGroup::editorCount() const
{
return model()->editors().count();
}
QList<IEditor *> StackedEditorGroup::editors() const
{
QAbstractItemModel *model = m_editorList->model();
QList<IEditor*> output;
int rows = model->rowCount();
for (int i = 0; i < rows; ++i)
output.append(model->data(model->index(i, 0), Qt::UserRole).value<IEditor*>());
return output;
}
QList<IEditor *> StackedEditorGroup::editorsInNaturalOrder() const
{
return model()->editors();
}
void StackedEditorGroup::makeEditorWritable()
{
CoreImpl::instance()->editorManager()->makeEditorWritable(currentEditor());
}
void StackedEditorGroup::listSelectionChanged(int index)
{
QAbstractItemModel *model = m_editorList->model();
setCurrentEditor(model->data(model->index(index, 0), Qt::UserRole).value<IEditor*>());
}
int StackedEditorGroup::indexOf(IEditor *editor)
{
QAbstractItemModel *model = m_editorList->model();
int rows = model->rowCount();
for (int i = 0; i < rows; ++i) {
if (editor == model->data(model->index(i, 0), Qt::UserRole).value<IEditor*>())
return i;
}
QTC_ASSERT(false, /**/);
return 0;
}
<|endoftext|> |
<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation ([email protected])
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/
#include "buildsettingspropertiespage.h"
#include "buildstep.h"
#include "buildstepspage.h"
#include "project.h"
#include "buildconfiguration.h"
#include <coreplugin/coreconstants.h>
#include <extensionsystem/pluginmanager.h>
#include <utils/qtcassert.h>
#include <QtCore/QMargins>
#include <QtCore/QTimer>
#include <QtGui/QApplication>
#include <QtGui/QComboBox>
#include <QtGui/QInputDialog>
#include <QtGui/QLabel>
#include <QtGui/QMenu>
#include <QtGui/QPushButton>
#include <QtGui/QVBoxLayout>
using namespace ProjectExplorer;
using namespace ProjectExplorer::Internal;
///
// BuildSettingsPanelFactory
///
bool BuildSettingsPanelFactory::supports(Project *project)
{
return project->hasBuildSettings();
}
IPropertiesPanel *BuildSettingsPanelFactory::createPanel(Project *project)
{
return new BuildSettingsPanel(project);
}
///
// BuildSettingsPanel
///
BuildSettingsPanel::BuildSettingsPanel(Project *project) :
m_widget(new BuildSettingsWidget(project)),
m_icon(":/projectexplorer/images/rebuild.png")
{
}
BuildSettingsPanel::~BuildSettingsPanel()
{
delete m_widget;
}
QString BuildSettingsPanel::name() const
{
return QApplication::tr("Build Settings");
}
QWidget *BuildSettingsPanel::widget() const
{
return m_widget;
}
QIcon BuildSettingsPanel::icon() const
{
return m_icon;
}
///
// BuildSettingsWidget
///
BuildSettingsWidget::~BuildSettingsWidget()
{
clear();
}
BuildSettingsWidget::BuildSettingsWidget(Project *project) :
m_project(project),
m_buildConfiguration(0),
m_leftMargin(0)
{
// Provide some time for our contentsmargins to get updated:
QTimer::singleShot(0, this, SLOT(init()));
}
void BuildSettingsWidget::init()
{
QMargins margins(contentsMargins());
m_leftMargin = margins.left();
margins.setLeft(0);
setContentsMargins(margins);
QVBoxLayout *vbox = new QVBoxLayout(this);
vbox->setContentsMargins(0, 0, 0, 0);
{ // Edit Build Configuration row
QHBoxLayout *hbox = new QHBoxLayout();
hbox->setContentsMargins(m_leftMargin, 0, 0, 0);
hbox->addWidget(new QLabel(tr("Edit Build Configuration:"), this));
m_buildConfigurationComboBox = new QComboBox(this);
m_buildConfigurationComboBox->setSizeAdjustPolicy(QComboBox::AdjustToContents);
hbox->addWidget(m_buildConfigurationComboBox);
m_addButton = new QPushButton(this);
m_addButton->setText(tr("Add"));
m_addButton->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
hbox->addWidget(m_addButton);
m_addButtonMenu = new QMenu(this);
m_addButton->setMenu(m_addButtonMenu);
m_removeButton = new QPushButton(this);
m_removeButton->setText(tr("Remove"));
m_removeButton->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
hbox->addWidget(m_removeButton);
hbox->addSpacerItem(new QSpacerItem(0, 0, QSizePolicy::Expanding, QSizePolicy::Fixed));
vbox->addLayout(hbox);
}
m_makeActiveLabel = new QLabel(this);
m_makeActiveLabel->setVisible(false);
vbox->addWidget(m_makeActiveLabel);
m_buildConfiguration = m_project->activeBuildConfiguration();
connect(m_makeActiveLabel, SIGNAL(linkActivated(QString)),
this, SLOT(makeActive()));
connect(m_buildConfigurationComboBox, SIGNAL(currentIndexChanged(int)),
this, SLOT(currentIndexChanged(int)));
connect(m_removeButton, SIGNAL(clicked()),
this, SLOT(deleteConfiguration()));
// TODO update on displayNameChange
// connect(m_project, SIGNAL(buildConfigurationDisplayNameChanged(const QString &)),
// this, SLOT(buildConfigurationDisplayNameChanged(const QString &)));
connect(m_project, SIGNAL(activeBuildConfigurationChanged()),
this, SLOT(checkMakeActiveLabel()));
if (m_project->buildConfigurationFactory())
connect(m_project->buildConfigurationFactory(), SIGNAL(availableCreationTypesChanged()), SLOT(updateAddButtonMenu()));
updateAddButtonMenu();
updateBuildSettings();
}
void BuildSettingsWidget::addSubWidget(const QString &name, QWidget *widget)
{
widget->setContentsMargins(m_leftMargin, 10, 0, 0);
QLabel *label = new QLabel(this);
label->setText(name);
QFont f = label->font();
f.setBold(true);
f.setPointSizeF(f.pointSizeF() * 1.2);
label->setFont(f);
label->setContentsMargins(m_leftMargin, 10, 0, 0);
layout()->addWidget(label);
layout()->addWidget(widget);
m_labels.append(label);
m_subWidgets.append(widget);
}
void BuildSettingsWidget::clear()
{
qDeleteAll(m_subWidgets);
m_subWidgets.clear();
qDeleteAll(m_labels);
m_labels.clear();
}
QList<QWidget *> BuildSettingsWidget::subWidgets() const
{
return m_subWidgets;
}
void BuildSettingsWidget::makeActive()
{
m_project->setActiveBuildConfiguration(m_buildConfiguration);
}
void BuildSettingsWidget::updateAddButtonMenu()
{
m_addButtonMenu->clear();
m_addButtonMenu->addAction(tr("&Clone Selected"),
this, SLOT(cloneConfiguration()));
IBuildConfigurationFactory *factory = m_project->buildConfigurationFactory();
if (factory) {
foreach (const QString &type, factory->availableCreationTypes()) {
QAction *action = m_addButtonMenu->addAction(factory->displayNameForType(type), this, SLOT(createConfiguration()));
action->setData(type);
}
}
}
void BuildSettingsWidget::updateBuildSettings()
{
// TODO save position, entry from combbox
// Delete old tree items
bool blocked = m_buildConfigurationComboBox->blockSignals(true);
m_buildConfigurationComboBox->clear();
clear();
// update buttons
m_removeButton->setEnabled(m_project->buildConfigurations().size() > 1);
// Add pages
BuildConfigWidget *generalConfigWidget = m_project->createConfigWidget();
addSubWidget(generalConfigWidget->displayName(), generalConfigWidget);
addSubWidget(tr("Build Steps"), new BuildStepsPage(m_project, false));
addSubWidget(tr("Clean Steps"), new BuildStepsPage(m_project, true));
QList<BuildConfigWidget *> subConfigWidgets = m_project->subConfigWidgets();
foreach (BuildConfigWidget *subConfigWidget, subConfigWidgets)
addSubWidget(subConfigWidget->displayName(), subConfigWidget);
// Add tree items
foreach (BuildConfiguration *bc, m_project->buildConfigurations()) {
m_buildConfigurationComboBox->addItem(bc->displayName(), QVariant::fromValue<BuildConfiguration *>(bc));
if (bc == m_buildConfiguration)
m_buildConfigurationComboBox->setCurrentIndex(m_buildConfigurationComboBox->count() - 1);
}
m_buildConfigurationComboBox->blockSignals(blocked);
// TODO Restore position, entry from combbox
// TODO? select entry from combobox ?
activeBuildConfigurationChanged();
}
void BuildSettingsWidget::currentIndexChanged(int index)
{
m_buildConfiguration = m_buildConfigurationComboBox->itemData(index).value<BuildConfiguration *>();
activeBuildConfigurationChanged();
}
void BuildSettingsWidget::activeBuildConfigurationChanged()
{
for (int i = 0; i < m_buildConfigurationComboBox->count(); ++i) {
if (m_buildConfigurationComboBox->itemData(i).value<BuildConfiguration *>() == m_buildConfiguration) {
m_buildConfigurationComboBox->setCurrentIndex(i);
break;
}
}
foreach (QWidget *widget, subWidgets()) {
if (BuildConfigWidget *buildStepWidget = qobject_cast<BuildConfigWidget*>(widget)) {
buildStepWidget->init(m_buildConfiguration);
}
}
checkMakeActiveLabel();
}
void BuildSettingsWidget::checkMakeActiveLabel()
{
m_makeActiveLabel->setVisible(false);
if (!m_project->activeBuildConfiguration() || m_project->activeBuildConfiguration() != m_buildConfiguration) {
m_makeActiveLabel->setText(tr("<a href=\"#\">Make %1 active.</a>").arg(m_buildConfiguration->displayName()));
m_makeActiveLabel->setVisible(true);
}
}
void BuildSettingsWidget::createConfiguration()
{
QAction *action = qobject_cast<QAction *>(sender());
const QString &type = action->data().toString();
BuildConfiguration *bc = m_project->buildConfigurationFactory()->create(type);
if (bc) {
m_buildConfiguration = bc;
updateBuildSettings();
}
}
void BuildSettingsWidget::cloneConfiguration()
{
const int index = m_buildConfigurationComboBox->currentIndex();
BuildConfiguration *bc = m_buildConfigurationComboBox->itemData(index).value<BuildConfiguration *>();
cloneConfiguration(bc);
}
void BuildSettingsWidget::deleteConfiguration()
{
const int index = m_buildConfigurationComboBox->currentIndex();
BuildConfiguration *bc = m_buildConfigurationComboBox->itemData(index).value<BuildConfiguration *>();
deleteConfiguration(bc);
}
void BuildSettingsWidget::cloneConfiguration(BuildConfiguration *sourceConfiguration)
{
if (!sourceConfiguration)
return;
QString newDisplayName(QInputDialog::getText(this, tr("Clone configuration"), tr("New Configuration Name:")));
if (newDisplayName.isEmpty())
return;
QStringList buildConfigurationDisplayNames;
foreach(BuildConfiguration *bc, m_project->buildConfigurations())
buildConfigurationDisplayNames << bc->displayName();
newDisplayName = Project::makeUnique(newDisplayName, buildConfigurationDisplayNames);
m_buildConfiguration = m_project->buildConfigurationFactory()->clone(sourceConfiguration);
m_buildConfiguration->setDisplayName(newDisplayName);
m_project->addBuildConfiguration(m_buildConfiguration);
updateBuildSettings();
}
void BuildSettingsWidget::deleteConfiguration(BuildConfiguration *deleteConfiguration)
{
if (!deleteConfiguration || m_project->buildConfigurations().size() <= 1)
return;
if (m_project->activeBuildConfiguration() == deleteConfiguration) {
foreach (BuildConfiguration *bc, m_project->buildConfigurations()) {
if (bc != deleteConfiguration) {
m_project->setActiveBuildConfiguration(bc);
break;
}
}
}
if (m_buildConfiguration == deleteConfiguration) {
foreach (BuildConfiguration *bc, m_project->buildConfigurations()) {
if (bc != deleteConfiguration) {
m_buildConfiguration = bc;
break;
}
}
}
m_project->removeBuildConfiguration(deleteConfiguration);
updateBuildSettings();
}
<commit_msg>Move "make active" label to proper location.<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation ([email protected])
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/
#include "buildsettingspropertiespage.h"
#include "buildstep.h"
#include "buildstepspage.h"
#include "project.h"
#include "buildconfiguration.h"
#include <coreplugin/coreconstants.h>
#include <extensionsystem/pluginmanager.h>
#include <utils/qtcassert.h>
#include <QtCore/QMargins>
#include <QtCore/QTimer>
#include <QtGui/QApplication>
#include <QtGui/QComboBox>
#include <QtGui/QInputDialog>
#include <QtGui/QLabel>
#include <QtGui/QMenu>
#include <QtGui/QPushButton>
#include <QtGui/QVBoxLayout>
using namespace ProjectExplorer;
using namespace ProjectExplorer::Internal;
///
// BuildSettingsPanelFactory
///
bool BuildSettingsPanelFactory::supports(Project *project)
{
return project->hasBuildSettings();
}
IPropertiesPanel *BuildSettingsPanelFactory::createPanel(Project *project)
{
return new BuildSettingsPanel(project);
}
///
// BuildSettingsPanel
///
BuildSettingsPanel::BuildSettingsPanel(Project *project) :
m_widget(new BuildSettingsWidget(project)),
m_icon(":/projectexplorer/images/rebuild.png")
{
}
BuildSettingsPanel::~BuildSettingsPanel()
{
delete m_widget;
}
QString BuildSettingsPanel::name() const
{
return QApplication::tr("Build Settings");
}
QWidget *BuildSettingsPanel::widget() const
{
return m_widget;
}
QIcon BuildSettingsPanel::icon() const
{
return m_icon;
}
///
// BuildSettingsWidget
///
BuildSettingsWidget::~BuildSettingsWidget()
{
clear();
}
BuildSettingsWidget::BuildSettingsWidget(Project *project) :
m_project(project),
m_buildConfiguration(0),
m_leftMargin(0)
{
// Provide some time for our contentsmargins to get updated:
QTimer::singleShot(0, this, SLOT(init()));
}
void BuildSettingsWidget::init()
{
QMargins margins(contentsMargins());
m_leftMargin = margins.left();
margins.setLeft(0);
setContentsMargins(margins);
QVBoxLayout *vbox = new QVBoxLayout(this);
vbox->setContentsMargins(0, 0, 0, 0);
{ // Edit Build Configuration row
QHBoxLayout *hbox = new QHBoxLayout();
hbox->setContentsMargins(m_leftMargin, 0, 0, 0);
hbox->addWidget(new QLabel(tr("Edit Build Configuration:"), this));
m_buildConfigurationComboBox = new QComboBox(this);
m_buildConfigurationComboBox->setSizeAdjustPolicy(QComboBox::AdjustToContents);
hbox->addWidget(m_buildConfigurationComboBox);
m_addButton = new QPushButton(this);
m_addButton->setText(tr("Add"));
m_addButton->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
hbox->addWidget(m_addButton);
m_addButtonMenu = new QMenu(this);
m_addButton->setMenu(m_addButtonMenu);
m_removeButton = new QPushButton(this);
m_removeButton->setText(tr("Remove"));
m_removeButton->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
hbox->addWidget(m_removeButton);
hbox->addSpacerItem(new QSpacerItem(0, 0, QSizePolicy::Expanding, QSizePolicy::Fixed));
vbox->addLayout(hbox);
}
m_makeActiveLabel = new QLabel(this);
m_makeActiveLabel->setContentsMargins(m_leftMargin, 4, 0, 4);
m_makeActiveLabel->setVisible(false);
vbox->addWidget(m_makeActiveLabel);
m_buildConfiguration = m_project->activeBuildConfiguration();
connect(m_makeActiveLabel, SIGNAL(linkActivated(QString)),
this, SLOT(makeActive()));
connect(m_buildConfigurationComboBox, SIGNAL(currentIndexChanged(int)),
this, SLOT(currentIndexChanged(int)));
connect(m_removeButton, SIGNAL(clicked()),
this, SLOT(deleteConfiguration()));
// TODO update on displayNameChange
// connect(m_project, SIGNAL(buildConfigurationDisplayNameChanged(const QString &)),
// this, SLOT(buildConfigurationDisplayNameChanged(const QString &)));
connect(m_project, SIGNAL(activeBuildConfigurationChanged()),
this, SLOT(checkMakeActiveLabel()));
if (m_project->buildConfigurationFactory())
connect(m_project->buildConfigurationFactory(), SIGNAL(availableCreationTypesChanged()), SLOT(updateAddButtonMenu()));
updateAddButtonMenu();
updateBuildSettings();
}
void BuildSettingsWidget::addSubWidget(const QString &name, QWidget *widget)
{
widget->setContentsMargins(m_leftMargin, 10, 0, 0);
QLabel *label = new QLabel(this);
label->setText(name);
QFont f = label->font();
f.setBold(true);
f.setPointSizeF(f.pointSizeF() * 1.2);
label->setFont(f);
label->setContentsMargins(m_leftMargin, 10, 0, 0);
layout()->addWidget(label);
layout()->addWidget(widget);
m_labels.append(label);
m_subWidgets.append(widget);
}
void BuildSettingsWidget::clear()
{
qDeleteAll(m_subWidgets);
m_subWidgets.clear();
qDeleteAll(m_labels);
m_labels.clear();
}
QList<QWidget *> BuildSettingsWidget::subWidgets() const
{
return m_subWidgets;
}
void BuildSettingsWidget::makeActive()
{
m_project->setActiveBuildConfiguration(m_buildConfiguration);
}
void BuildSettingsWidget::updateAddButtonMenu()
{
m_addButtonMenu->clear();
m_addButtonMenu->addAction(tr("&Clone Selected"),
this, SLOT(cloneConfiguration()));
IBuildConfigurationFactory *factory = m_project->buildConfigurationFactory();
if (factory) {
foreach (const QString &type, factory->availableCreationTypes()) {
QAction *action = m_addButtonMenu->addAction(factory->displayNameForType(type), this, SLOT(createConfiguration()));
action->setData(type);
}
}
}
void BuildSettingsWidget::updateBuildSettings()
{
// TODO save position, entry from combbox
// Delete old tree items
bool blocked = m_buildConfigurationComboBox->blockSignals(true);
m_buildConfigurationComboBox->clear();
clear();
// update buttons
m_removeButton->setEnabled(m_project->buildConfigurations().size() > 1);
// Add pages
BuildConfigWidget *generalConfigWidget = m_project->createConfigWidget();
addSubWidget(generalConfigWidget->displayName(), generalConfigWidget);
addSubWidget(tr("Build Steps"), new BuildStepsPage(m_project, false));
addSubWidget(tr("Clean Steps"), new BuildStepsPage(m_project, true));
QList<BuildConfigWidget *> subConfigWidgets = m_project->subConfigWidgets();
foreach (BuildConfigWidget *subConfigWidget, subConfigWidgets)
addSubWidget(subConfigWidget->displayName(), subConfigWidget);
// Add tree items
foreach (BuildConfiguration *bc, m_project->buildConfigurations()) {
m_buildConfigurationComboBox->addItem(bc->displayName(), QVariant::fromValue<BuildConfiguration *>(bc));
if (bc == m_buildConfiguration)
m_buildConfigurationComboBox->setCurrentIndex(m_buildConfigurationComboBox->count() - 1);
}
m_buildConfigurationComboBox->blockSignals(blocked);
// TODO Restore position, entry from combbox
// TODO? select entry from combobox ?
activeBuildConfigurationChanged();
}
void BuildSettingsWidget::currentIndexChanged(int index)
{
m_buildConfiguration = m_buildConfigurationComboBox->itemData(index).value<BuildConfiguration *>();
activeBuildConfigurationChanged();
}
void BuildSettingsWidget::activeBuildConfigurationChanged()
{
for (int i = 0; i < m_buildConfigurationComboBox->count(); ++i) {
if (m_buildConfigurationComboBox->itemData(i).value<BuildConfiguration *>() == m_buildConfiguration) {
m_buildConfigurationComboBox->setCurrentIndex(i);
break;
}
}
foreach (QWidget *widget, subWidgets()) {
if (BuildConfigWidget *buildStepWidget = qobject_cast<BuildConfigWidget*>(widget)) {
buildStepWidget->init(m_buildConfiguration);
}
}
checkMakeActiveLabel();
}
void BuildSettingsWidget::checkMakeActiveLabel()
{
m_makeActiveLabel->setVisible(false);
if (!m_project->activeBuildConfiguration() || m_project->activeBuildConfiguration() != m_buildConfiguration) {
m_makeActiveLabel->setText(tr("<a href=\"#\">Make %1 active.</a>").arg(m_buildConfiguration->displayName()));
m_makeActiveLabel->setVisible(true);
}
}
void BuildSettingsWidget::createConfiguration()
{
QAction *action = qobject_cast<QAction *>(sender());
const QString &type = action->data().toString();
BuildConfiguration *bc = m_project->buildConfigurationFactory()->create(type);
if (bc) {
m_buildConfiguration = bc;
updateBuildSettings();
}
}
void BuildSettingsWidget::cloneConfiguration()
{
const int index = m_buildConfigurationComboBox->currentIndex();
BuildConfiguration *bc = m_buildConfigurationComboBox->itemData(index).value<BuildConfiguration *>();
cloneConfiguration(bc);
}
void BuildSettingsWidget::deleteConfiguration()
{
const int index = m_buildConfigurationComboBox->currentIndex();
BuildConfiguration *bc = m_buildConfigurationComboBox->itemData(index).value<BuildConfiguration *>();
deleteConfiguration(bc);
}
void BuildSettingsWidget::cloneConfiguration(BuildConfiguration *sourceConfiguration)
{
if (!sourceConfiguration)
return;
QString newDisplayName(QInputDialog::getText(this, tr("Clone configuration"), tr("New Configuration Name:")));
if (newDisplayName.isEmpty())
return;
QStringList buildConfigurationDisplayNames;
foreach(BuildConfiguration *bc, m_project->buildConfigurations())
buildConfigurationDisplayNames << bc->displayName();
newDisplayName = Project::makeUnique(newDisplayName, buildConfigurationDisplayNames);
m_buildConfiguration = m_project->buildConfigurationFactory()->clone(sourceConfiguration);
m_buildConfiguration->setDisplayName(newDisplayName);
m_project->addBuildConfiguration(m_buildConfiguration);
updateBuildSettings();
}
void BuildSettingsWidget::deleteConfiguration(BuildConfiguration *deleteConfiguration)
{
if (!deleteConfiguration || m_project->buildConfigurations().size() <= 1)
return;
if (m_project->activeBuildConfiguration() == deleteConfiguration) {
foreach (BuildConfiguration *bc, m_project->buildConfigurations()) {
if (bc != deleteConfiguration) {
m_project->setActiveBuildConfiguration(bc);
break;
}
}
}
if (m_buildConfiguration == deleteConfiguration) {
foreach (BuildConfiguration *bc, m_project->buildConfigurations()) {
if (bc != deleteConfiguration) {
m_buildConfiguration = bc;
break;
}
}
}
m_project->removeBuildConfiguration(deleteConfiguration);
updateBuildSettings();
}
<|endoftext|> |
<commit_before>
#include "obj_to_vertex_array.h"
#include <limits>
#include <map>
#include <scm/core/utilities/foreach.h>
namespace {
struct obj_vert_index
{
unsigned _v;
unsigned _t;
unsigned _n;
obj_vert_index(unsigned v, unsigned t, unsigned n) : _v(v), _t(t), _n(n) {}
// lexicographic compare of the index vector
bool operator<(const obj_vert_index& rhs) const {
if (_v == rhs._v && _t == rhs._t) return (_n < rhs._n);
if (_v == rhs._v) return (_t < rhs._t);
return (_v < rhs._v);
}
}; // struct obj_vert_index
} // namespace
namespace scm {
namespace data {
bool generate_vertex_buffer(const wavefront_model& in_obj,
vertexbuffer_data& out_data,
bool interleave_arrays)
{
if (interleave_arrays) {
return (false);
}
typedef std::map<obj_vert_index, unsigned> index_mapping;
typedef index_mapping::value_type index_value;
index_mapping indices;
wavefront_model::object_container::const_iterator cur_obj_it;
wavefront_object::group_container::const_iterator cur_grp_it;
unsigned index_buf_size = 0;
// first pass
// find out the size of our new arrays and reorder the indices
out_data._index_arrays.reserve(in_obj._objects.size());
out_data._index_array_counts.reserve(in_obj._objects.size());
foreach (const wavefront_object& wf_obj, in_obj._objects) {
foreach (const wavefront_object_group& wf_obj_grp, wf_obj._groups) {
out_data._index_array_counts.push_back(3 * static_cast<unsigned>(wf_obj_grp._num_tri_faces));
wavefront_model::material_container::const_iterator mat = in_obj._materials.find(wf_obj_grp._material_name);
if (mat != in_obj._materials.end()) {
out_data._materials.push_back(mat->second);
}
else {
out_data._materials.push_back(wavefront_material());
}
}
}
vertexbuffer_data::index_counts_container::iterator cur_index_count = out_data._index_array_counts.begin();
unsigned new_index = 0;
unsigned iarray_index = 0;
foreach (const wavefront_object& wf_obj, in_obj._objects) {
foreach (const wavefront_object_group& wf_obj_grp, wf_obj._groups) {
iarray_index = 0;
// initialize index array
out_data._index_arrays.push_back(boost::shared_array<core::uint32_t>());
vertexbuffer_data::index_array_container::value_type& cur_index_array = out_data._index_arrays.back();
cur_index_array.reset(new core::uint32_t[*cur_index_count]);
// initialize bbox
out_data._bboxes.push_back(aabbox());
vertexbuffer_data::bbox_container::value_type& cur_bbox = out_data._bboxes.back();
cur_bbox._min = math::vec3f_t((std::numeric_limits<math::vec3f_t::component_type>::max)());
cur_bbox._max = math::vec3f_t((std::numeric_limits<math::vec3f_t::component_type>::min)());
for (unsigned i = 0; i < wf_obj_grp._num_tri_faces; ++i) {
const wavefront_object_triangle_face& cur_face = wf_obj_grp._tri_faces[i];
for (unsigned k = 0; k < 3; ++k) {
obj_vert_index cur_index(cur_face._vertices[k],
in_obj._num_tex_coords != 0 ? cur_face._tex_coords[k] : 0,
in_obj._num_normals != 0 ? cur_face._normals[k] : 0);
// update bounding box
const math::vec3f_t& cur_vert = in_obj._vertices[cur_index._v];
for (unsigned c = 0; c < 3; ++c) {
cur_bbox._min.vec_array[c] = cur_vert.vec_array[c] < cur_bbox._min.vec_array[c] ? cur_vert.vec_array[c] : cur_bbox._min.vec_array[c];
cur_bbox._max.vec_array[c] = cur_vert.vec_array[c] > cur_bbox._max.vec_array[c] ? cur_vert.vec_array[c] : cur_bbox._max.vec_array[c];
}
// check index mapping
index_mapping::const_iterator prev_it = indices.find(cur_index);
if (prev_it == indices.end()) {
indices.insert(index_value(cur_index, new_index));
cur_index_array[iarray_index] = new_index;
++new_index;
}
else {
cur_index_array[iarray_index] = prev_it->second;
}
++iarray_index;
}
}
++cur_index_count;
}
}
// second pass
// copy vertex data according to new indices
std::size_t array_size = 3 * indices.size();
if (in_obj._num_normals != 0) {
array_size += 3 * indices.size();
out_data._normals_offset = 3 * indices.size();
}
else {
out_data._normals_offset = 0;
}
if (in_obj._num_tex_coords != 0) {
array_size += 2 * indices.size();
out_data._texcoords_offset = out_data._normals_offset + 3 * indices.size();
}
else {
out_data._texcoords_offset = 0;
}
out_data._vert_array_count = indices.size();
out_data._vert_array.reset(new float[array_size]);
unsigned varray_index = 0;
for (index_mapping::const_iterator ind_it = indices.begin();
ind_it != indices.end();
++ind_it) {
const obj_vert_index& cur_index = ind_it->first;
varray_index = ind_it->second;
memcpy(out_data._vert_array.get() + varray_index * 3,
in_obj._vertices[cur_index._v - 1].vec_array,
3 * sizeof(float));
if (out_data._normals_offset) {
memcpy(out_data._vert_array.get() + varray_index * 3
+ out_data._normals_offset,
in_obj._normals[cur_index._n - 1].vec_array,
3 * sizeof(float));
}
if (out_data._texcoords_offset) {
memcpy(out_data._vert_array.get() + varray_index * 2
+ out_data._texcoords_offset,
in_obj._tex_coords[cur_index._t - 1].vec_array,
2 * sizeof(float));
}
}
return (true);
}
} // namespace data
} // namespace scm
<commit_msg>bugfix in obj vbo generator<commit_after>
#include "obj_to_vertex_array.h"
#include <limits>
#include <map>
#include <scm/core/utilities/foreach.h>
namespace {
struct obj_vert_index
{
unsigned _v;
unsigned _t;
unsigned _n;
obj_vert_index(unsigned v, unsigned t, unsigned n) : _v(v), _t(t), _n(n) {}
// lexicographic compare of the index vector
bool operator<(const obj_vert_index& rhs) const {
if (_v == rhs._v && _t == rhs._t) return (_n < rhs._n);
if (_v == rhs._v) return (_t < rhs._t);
return (_v < rhs._v);
}
}; // struct obj_vert_index
} // namespace
namespace scm {
namespace data {
bool generate_vertex_buffer(const wavefront_model& in_obj,
vertexbuffer_data& out_data,
bool interleave_arrays)
{
if (interleave_arrays) {
return (false);
}
typedef std::map<obj_vert_index, unsigned> index_mapping;
typedef index_mapping::value_type index_value;
index_mapping indices;
wavefront_model::object_container::const_iterator cur_obj_it;
wavefront_object::group_container::const_iterator cur_grp_it;
unsigned index_buf_size = 0;
// first pass
// find out the size of our new arrays and reorder the indices
out_data._index_arrays.reserve(in_obj._objects.size());
out_data._index_array_counts.reserve(in_obj._objects.size());
foreach (const wavefront_object& wf_obj, in_obj._objects) {
foreach (const wavefront_object_group& wf_obj_grp, wf_obj._groups) {
out_data._index_array_counts.push_back(3 * static_cast<unsigned>(wf_obj_grp._num_tri_faces));
wavefront_model::material_container::const_iterator mat = in_obj._materials.find(wf_obj_grp._material_name);
if (mat != in_obj._materials.end()) {
out_data._materials.push_back(mat->second);
}
else {
out_data._materials.push_back(wavefront_material());
}
}
}
vertexbuffer_data::index_counts_container::iterator cur_index_count = out_data._index_array_counts.begin();
unsigned new_index = 0;
unsigned iarray_index = 0;
foreach (const wavefront_object& wf_obj, in_obj._objects) {
foreach (const wavefront_object_group& wf_obj_grp, wf_obj._groups) {
iarray_index = 0;
// initialize index array
out_data._index_arrays.push_back(boost::shared_array<core::uint32_t>());
vertexbuffer_data::index_array_container::value_type& cur_index_array = out_data._index_arrays.back();
cur_index_array.reset(new core::uint32_t[*cur_index_count]);
// initialize bbox
out_data._bboxes.push_back(aabbox());
vertexbuffer_data::bbox_container::value_type& cur_bbox = out_data._bboxes.back();
cur_bbox._min = math::vec3f_t((std::numeric_limits<math::vec3f_t::component_type>::max)());
cur_bbox._max = math::vec3f_t((std::numeric_limits<math::vec3f_t::component_type>::min)());
for (unsigned i = 0; i < wf_obj_grp._num_tri_faces; ++i) {
const wavefront_object_triangle_face& cur_face = wf_obj_grp._tri_faces[i];
for (unsigned k = 0; k < 3; ++k) {
obj_vert_index cur_index(cur_face._vertices[k],
in_obj._num_tex_coords != 0 ? cur_face._tex_coords[k] : 0,
in_obj._num_normals != 0 ? cur_face._normals[k] : 0);
// update bounding box
const math::vec3f_t& cur_vert = in_obj._vertices[cur_index._v - 1];
for (unsigned c = 0; c < 3; ++c) {
cur_bbox._min.vec_array[c] = cur_vert.vec_array[c] < cur_bbox._min.vec_array[c] ? cur_vert.vec_array[c] : cur_bbox._min.vec_array[c];
cur_bbox._max.vec_array[c] = cur_vert.vec_array[c] > cur_bbox._max.vec_array[c] ? cur_vert.vec_array[c] : cur_bbox._max.vec_array[c];
}
// check index mapping
index_mapping::const_iterator prev_it = indices.find(cur_index);
if (prev_it == indices.end()) {
indices.insert(index_value(cur_index, new_index));
cur_index_array[iarray_index] = new_index;
++new_index;
}
else {
cur_index_array[iarray_index] = prev_it->second;
}
++iarray_index;
}
}
++cur_index_count;
}
}
// second pass
// copy vertex data according to new indices
std::size_t array_size = 3 * indices.size();
if (in_obj._num_normals != 0) {
array_size += 3 * indices.size();
out_data._normals_offset = 3 * indices.size();
}
else {
out_data._normals_offset = 0;
}
if (in_obj._num_tex_coords != 0) {
array_size += 2 * indices.size();
out_data._texcoords_offset = out_data._normals_offset + 3 * indices.size();
}
else {
out_data._texcoords_offset = 0;
}
out_data._vert_array_count = indices.size();
out_data._vert_array.reset(new float[array_size]);
unsigned varray_index = 0;
for (index_mapping::const_iterator ind_it = indices.begin();
ind_it != indices.end();
++ind_it) {
const obj_vert_index& cur_index = ind_it->first;
varray_index = ind_it->second;
memcpy(out_data._vert_array.get() + varray_index * 3,
in_obj._vertices[cur_index._v - 1].vec_array,
3 * sizeof(float));
if (out_data._normals_offset) {
memcpy(out_data._vert_array.get() + varray_index * 3
+ out_data._normals_offset,
in_obj._normals[cur_index._n - 1].vec_array,
3 * sizeof(float));
}
if (out_data._texcoords_offset) {
memcpy(out_data._vert_array.get() + varray_index * 2
+ out_data._texcoords_offset,
in_obj._tex_coords[cur_index._t - 1].vec_array,
2 * sizeof(float));
}
}
return (true);
}
} // namespace data
} // namespace scm
<|endoftext|> |
<commit_before>//===--- XpcTracing.cpp ---------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#include "sourcekitd/XpcTracing.h"
#include "swift/Frontend/Frontend.h"
#include "llvm/Support/TimeValue.h"
#include "llvm/Support/YAMLTraits.h"
#include <xpc/xpc.h>
using namespace sourcekitd;
using namespace sourcekitd::trace;
using namespace llvm;
//===----------------------------------------------------------------------===//
// General
//===----------------------------------------------------------------------===//
static std::atomic<uint64_t> operation_id(0);
static uint64_t tracing_session = llvm::sys::TimeValue::now().msec();
uint64_t trace::getTracingSession() {
return tracing_session;
}
static void append(xpc_object_t Contents, uint64_t Value) {
xpc_array_set_uint64(Contents, XPC_ARRAY_APPEND, Value);
}
static void append(xpc_object_t Contents, ActionKind Value) {
append(Contents, static_cast<uint64_t>(Value));
}
static void append(xpc_object_t Contents, OperationKind Value) {
append(Contents, static_cast<uint64_t>(Value));
}
static void append(xpc_object_t Contents, llvm::StringRef Value) {
xpc_array_set_string(Contents, XPC_ARRAY_APPEND, Value.data());
}
static void append(xpc_object_t Contents, const StringPairs &Files) {
append(Contents, Files.size());
std::for_each(Files.begin(), Files.end(),
[&] (const std::pair<std::string, std::string> &File) {
append(Contents, File.first);
append(Contents, File.second);
});
}
template <typename U>
struct llvm::yaml::SequenceTraits<std::vector<U>> {
static size_t size(IO &Io, std::vector<U> &Vector) {
return Vector.size();
}
static U &element(IO &Io, std::vector<U> &Vector, size_t Index) {
return Vector[Index];
}
};
template <>
struct llvm::yaml::MappingTraits<SwiftArguments> {
static void mapping(IO &Io, SwiftArguments &Args) {
Io.mapOptional("PrimaryFile", Args.PrimaryFile, std::string());
Io.mapRequired("CompilerArgs", Args.Args);
}
};
static std::string serializeCompilerArguments(const SwiftArguments &Args) {
// Serialize compiler instance
std::string OptionsAsYaml;
llvm::raw_string_ostream OptionsStream(OptionsAsYaml);
llvm::yaml::Output YamlOutput(OptionsStream);
YamlOutput << const_cast<SwiftArguments &>(Args);
OptionsStream.flush();
return OptionsAsYaml;
}
//===----------------------------------------------------------------------===//
// Trace consumer
//===----------------------------------------------------------------------===//
class XpcTraceConsumer : public SourceKit::trace::TraceConsumer {
public:
virtual ~XpcTraceConsumer() = default;
// Operation previously started with startXXX has finished
virtual void operationFinished(uint64_t OpId) override;
// Trace start of SourceKit operation
virtual void operationStarted(uint64_t OpId, OperationKind OpKind,
const SwiftInvocation &Inv,
const StringPairs &OpArgs) override;
};
// Trace start of SourceKit operation
void XpcTraceConsumer::operationStarted(uint64_t OpId,
OperationKind OpKind,
const SwiftInvocation &Inv,
const StringPairs &OpArgs) {
xpc_object_t Contents = xpc_array_create(nullptr, 0);
append(Contents, ActionKind::OperationStarted);
append(Contents, OpId);
append(Contents, OpKind);
append(Contents, serializeCompilerArguments(Inv.Args));
append(Contents, Inv.Files);
append(Contents, OpArgs);
trace::sendTraceMessage(Contents);
}
// Operation previously started with startXXX has finished
void XpcTraceConsumer::operationFinished(uint64_t OpId) {
xpc_object_t Contents = xpc_array_create(nullptr, 0);
append(Contents, trace::ActionKind::OperationFinished);
append(Contents, OpId);
trace::sendTraceMessage(Contents);
}
static XpcTraceConsumer Instance;
void trace::initialize() {
SourceKit::trace::registerConsumer(&Instance);
}
<commit_msg>[sourcekit] Remove unused variable to silence warning<commit_after>//===--- XpcTracing.cpp ---------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#include "sourcekitd/XpcTracing.h"
#include "swift/Frontend/Frontend.h"
#include "llvm/Support/TimeValue.h"
#include "llvm/Support/YAMLTraits.h"
#include <xpc/xpc.h>
using namespace sourcekitd;
using namespace sourcekitd::trace;
using namespace llvm;
//===----------------------------------------------------------------------===//
// General
//===----------------------------------------------------------------------===//
static uint64_t tracing_session = llvm::sys::TimeValue::now().msec();
uint64_t trace::getTracingSession() {
return tracing_session;
}
static void append(xpc_object_t Contents, uint64_t Value) {
xpc_array_set_uint64(Contents, XPC_ARRAY_APPEND, Value);
}
static void append(xpc_object_t Contents, ActionKind Value) {
append(Contents, static_cast<uint64_t>(Value));
}
static void append(xpc_object_t Contents, OperationKind Value) {
append(Contents, static_cast<uint64_t>(Value));
}
static void append(xpc_object_t Contents, llvm::StringRef Value) {
xpc_array_set_string(Contents, XPC_ARRAY_APPEND, Value.data());
}
static void append(xpc_object_t Contents, const StringPairs &Files) {
append(Contents, Files.size());
std::for_each(Files.begin(), Files.end(),
[&] (const std::pair<std::string, std::string> &File) {
append(Contents, File.first);
append(Contents, File.second);
});
}
template <typename U>
struct llvm::yaml::SequenceTraits<std::vector<U>> {
static size_t size(IO &Io, std::vector<U> &Vector) {
return Vector.size();
}
static U &element(IO &Io, std::vector<U> &Vector, size_t Index) {
return Vector[Index];
}
};
template <>
struct llvm::yaml::MappingTraits<SwiftArguments> {
static void mapping(IO &Io, SwiftArguments &Args) {
Io.mapOptional("PrimaryFile", Args.PrimaryFile, std::string());
Io.mapRequired("CompilerArgs", Args.Args);
}
};
static std::string serializeCompilerArguments(const SwiftArguments &Args) {
// Serialize compiler instance
std::string OptionsAsYaml;
llvm::raw_string_ostream OptionsStream(OptionsAsYaml);
llvm::yaml::Output YamlOutput(OptionsStream);
YamlOutput << const_cast<SwiftArguments &>(Args);
OptionsStream.flush();
return OptionsAsYaml;
}
//===----------------------------------------------------------------------===//
// Trace consumer
//===----------------------------------------------------------------------===//
class XpcTraceConsumer : public SourceKit::trace::TraceConsumer {
public:
virtual ~XpcTraceConsumer() = default;
// Operation previously started with startXXX has finished
virtual void operationFinished(uint64_t OpId) override;
// Trace start of SourceKit operation
virtual void operationStarted(uint64_t OpId, OperationKind OpKind,
const SwiftInvocation &Inv,
const StringPairs &OpArgs) override;
};
// Trace start of SourceKit operation
void XpcTraceConsumer::operationStarted(uint64_t OpId,
OperationKind OpKind,
const SwiftInvocation &Inv,
const StringPairs &OpArgs) {
xpc_object_t Contents = xpc_array_create(nullptr, 0);
append(Contents, ActionKind::OperationStarted);
append(Contents, OpId);
append(Contents, OpKind);
append(Contents, serializeCompilerArguments(Inv.Args));
append(Contents, Inv.Files);
append(Contents, OpArgs);
trace::sendTraceMessage(Contents);
}
// Operation previously started with startXXX has finished
void XpcTraceConsumer::operationFinished(uint64_t OpId) {
xpc_object_t Contents = xpc_array_create(nullptr, 0);
append(Contents, trace::ActionKind::OperationFinished);
append(Contents, OpId);
trace::sendTraceMessage(Contents);
}
static XpcTraceConsumer Instance;
void trace::initialize() {
SourceKit::trace::registerConsumer(&Instance);
}
<|endoftext|> |
<commit_before>// -----------------------------------------------------------------------
// pion-common: a collection of common libraries used by the Pion Platform
// -----------------------------------------------------------------------
// Copyright (C) 2007 Atomic Labs, Inc. (http://www.atomiclabs.com)
//
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file COPYING or copy at http://www.boost.org/LICENSE_1_0.txt
//
#ifndef __PION_PIONHASHMAP_HEADER__
#define __PION_PIONHASHMAP_HEADER__
#include <boost/functional/hash.hpp>
#include <pion/PionConfig.hpp>
#if defined(PION_HAVE_UNORDERED_MAP)
#include <unordered_map>
#define PION_HASH_MAP std::tr1::unordered_map
#define PION_HASH_MULTIMAP std::tr1::unordered_multimap
#define PION_HASH_STRING boost::hash<std::string>
#elif defined(PION_HAVE_EXT_HASH_MAP)
#if __GNUC__ >= 3
#include <ext/hash_map>
#define PION_HASH_MAP __gnu_cxx::hash_map
#define PION_HASH_MULTIMAP __gnu_cxx::hash_multimap
#else
#include <ext/hash_map>
#define PION_HASH_MAP hash_map
#define PION_HASH_MULTIMAP hash_multimap
#endif
#define PION_HASH_STRING boost::hash<std::string>
#elif defined(PION_HAVE_HASH_MAP)
#include <hash_map>
#ifdef _MSC_VER
#define PION_HASH_MAP stdext::hash_map
#define PION_HASH_MULTIMAP stdext::hash_multimap
#define PION_HASH_STRING stdext::hash_compare<std::string, std::less<std::string> >
#else
#define PION_HASH_MAP hash_map
#define PION_HASH_MULTIMAP hash_multimap
#define PION_HASH_STRING boost::hash<std::string>
#endif
#endif
#endif
<commit_msg>Added new macro PION_HASH(TYPE), a generalization of PION_HASH_STRING.<commit_after>// -----------------------------------------------------------------------
// pion-common: a collection of common libraries used by the Pion Platform
// -----------------------------------------------------------------------
// Copyright (C) 2007 Atomic Labs, Inc. (http://www.atomiclabs.com)
//
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file COPYING or copy at http://www.boost.org/LICENSE_1_0.txt
//
#ifndef __PION_PIONHASHMAP_HEADER__
#define __PION_PIONHASHMAP_HEADER__
#include <boost/functional/hash.hpp>
#include <pion/PionConfig.hpp>
#if defined(PION_HAVE_UNORDERED_MAP)
#include <unordered_map>
#define PION_HASH_MAP std::tr1::unordered_map
#define PION_HASH_MULTIMAP std::tr1::unordered_multimap
#define PION_HASH_STRING boost::hash<std::string>
#define PION_HASH(TYPE) boost::hash<TYPE>
#elif defined(PION_HAVE_EXT_HASH_MAP)
#if __GNUC__ >= 3
#include <ext/hash_map>
#define PION_HASH_MAP __gnu_cxx::hash_map
#define PION_HASH_MULTIMAP __gnu_cxx::hash_multimap
#else
#include <ext/hash_map>
#define PION_HASH_MAP hash_map
#define PION_HASH_MULTIMAP hash_multimap
#endif
#define PION_HASH_STRING boost::hash<std::string>
#define PION_HASH(TYPE) boost::hash<TYPE>
#elif defined(PION_HAVE_HASH_MAP)
#include <hash_map>
#ifdef _MSC_VER
#define PION_HASH_MAP stdext::hash_map
#define PION_HASH_MULTIMAP stdext::hash_multimap
#define PION_HASH_STRING stdext::hash_compare<std::string, std::less<std::string> >
#define PION_HASH(TYPE) stdext::hash_compare<TYPE, std::less<TYPE> >
#else
#define PION_HASH_MAP hash_map
#define PION_HASH_MULTIMAP hash_multimap
#define PION_HASH_STRING boost::hash<std::string>
#define PION_HASH(TYPE) boost::hash<TYPE>
#endif
#endif
#endif
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2019 ScyllaDB
*
* Modified by ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#include "service/storage_proxy.hh"
#include "service/paxos/proposal.hh"
#include "service/paxos/paxos_state.hh"
#include "db/system_keyspace.hh"
#include "schema_registry.hh"
#include "database.hh"
#include "service/storage_service.hh"
#include <utils/error_injection.hh>
namespace service::paxos {
logging::logger paxos_state::logger("paxos");
thread_local paxos_state::key_lock_map paxos_state::_paxos_table_lock;
thread_local paxos_state::key_lock_map paxos_state::_coordinator_lock;
paxos_state::key_lock_map::semaphore& paxos_state::key_lock_map::get_semaphore_for_key(const dht::token& key) {
return _locks.try_emplace(key, 1).first->second;
}
void paxos_state::key_lock_map::release_semaphore_for_key(const dht::token& key) {
auto it = _locks.find(key);
if (it != _locks.end() && (*it).second.current() == 1) {
_locks.erase(it);
}
}
future<prepare_response> paxos_state::prepare(tracing::trace_state_ptr tr_state, schema_ptr schema,
const query::read_command& cmd, const partition_key& key, utils::UUID ballot,
bool only_digest, query::digest_algorithm da, clock_type::time_point timeout) {
dht::token token = dht::get_token(*schema, key);
utils::latency_counter lc;
lc.start();
return with_locked_key(token, timeout, [&cmd, token, &key, ballot, tr_state, schema, only_digest, da, timeout] () mutable {
// When preparing, we need to use the same time as "now" (that's the time we use to decide if something
// is expired or not) across nodes, otherwise we may have a window where a Most Recent Decision shows up
// on some replica and not others during a new proposal (in storage_proxy::begin_and_repair_paxos()), and no
// amount of re-submit will fix this (because the node on which the commit has expired will have a
// tombstone that hides any re-submit). See CASSANDRA-12043 for details.
auto now_in_sec = utils::UUID_gen::unix_timestamp_in_sec(ballot);
return utils::get_local_injector().inject("paxos_state_prepare_timeout", timeout).then([&key, schema, now_in_sec, timeout] {
return db::system_keyspace::load_paxos_state(key, schema, gc_clock::time_point(now_in_sec), timeout);
}).then([&cmd, token = std::move(token), &key, ballot, tr_state, schema, only_digest, da, timeout] (paxos_state state) {
// If received ballot is newer that the one we already accepted it has to be accepted as well,
// but we will return the previously accepted proposal so that the new coordinator will use it instead of
// its own.
if (ballot.timestamp() > state._promised_ballot.timestamp()) {
logger.debug("Promising ballot {}", ballot);
tracing::trace(tr_state, "Promising ballot {}", ballot);
auto f1 = futurize_invoke(db::system_keyspace::save_paxos_promise, *schema, std::ref(key), ballot, timeout);
auto f2 = futurize_invoke([&] {
return do_with(dht::partition_range_vector({dht::partition_range::make_singular({token, key})}),
[tr_state, schema, &cmd, only_digest, da, timeout] (const dht::partition_range_vector& prv) {
return get_local_storage_proxy().get_db().local().query(schema, cmd,
{only_digest ? query::result_request::only_digest : query::result_request::result_and_digest, da},
prv, tr_state, query::result_memory_limiter::maximum_result_size, timeout);
});
});
return when_all(std::move(f1), std::move(f2)).then([state = std::move(state), only_digest] (auto t) {
auto&& f1 = std::get<0>(t);
auto&& f2 = std::get<1>(t);
if (f1.failed()) {
// Failed to save promise. Nothing we can do but throw.
return make_exception_future<prepare_response>(f1.get_exception());
}
std::optional<std::variant<foreign_ptr<lw_shared_ptr<query::result>>, query::result_digest>> data_or_digest;
// Silently ignore any errors querying the current value as the caller is prepared to fall back
// on querying it by itself in case it's missing in the response.
if (!f2.failed()) {
auto&& [result, hit_rate] = f2.get();
if (only_digest) {
data_or_digest = *result->digest();
} else {
data_or_digest = std::move(make_foreign(std::move(result)));
}
}
return make_ready_future<prepare_response>(prepare_response(promise(std::move(state._accepted_proposal),
std::move(state._most_recent_commit), std::move(data_or_digest))));
});
} else {
logger.debug("Promise rejected; {} is not sufficiently newer than {}", ballot, state._promised_ballot);
tracing::trace(tr_state, "Promise rejected; {} is not sufficiently newer than {}", ballot, state._promised_ballot);
// Return the currently promised ballot (rather than, e.g., the ballot of the last
// accepted proposal) so the coordinator can make sure it uses a newer ballot next
// time (#5667).
return make_ready_future<prepare_response>(prepare_response(std::move(state._promised_ballot)));
}
});
}).finally([schema, lc] () mutable {
auto& stats = get_local_storage_proxy().get_db().local().find_column_family(schema).get_stats();
stats.cas_prepare.mark(lc.stop().latency());
if (lc.is_start()) {
stats.estimated_cas_prepare.add(lc.latency(), stats.cas_prepare.hist.count);
}
});
}
future<bool> paxos_state::accept(tracing::trace_state_ptr tr_state, schema_ptr schema, dht::token token, const proposal& proposal,
clock_type::time_point timeout) {
utils::latency_counter lc;
lc.start();
return with_locked_key(token, timeout, [proposal = std::move(proposal), schema, tr_state, timeout] () mutable {
auto now_in_sec = utils::UUID_gen::unix_timestamp_in_sec(proposal.ballot);
auto f = db::system_keyspace::load_paxos_state(proposal.update.decorated_key(*schema).key(), schema,
gc_clock::time_point(now_in_sec), timeout);
return f.then([proposal = std::move(proposal), tr_state, schema, timeout] (paxos_state state) {
return utils::get_local_injector().inject("paxos_state_accept_timeout", timeout).then(
[proposal = std::move(proposal), state = std::move(state), tr_state, schema, timeout] {
// Accept the proposal if we promised to accept it or the proposal is newer than the one we promised.
// Otherwise the proposal was cutoff by another Paxos proposer and has to be rejected.
if (proposal.ballot == state._promised_ballot || proposal.ballot.timestamp() > state._promised_ballot.timestamp()) {
logger.debug("Accepting proposal {}", proposal);
tracing::trace(tr_state, "Accepting proposal {}", proposal);
return db::system_keyspace::save_paxos_proposal(*schema, proposal, timeout).then([] {
return true;
});
} else {
logger.debug("Rejecting proposal for {} because in_progress is now {}", proposal, state._promised_ballot);
tracing::trace(tr_state, "Rejecting proposal for {} because in_progress is now {}", proposal, state._promised_ballot);
return make_ready_future<bool>(false);
}
});
});
}).finally([schema, lc] () mutable {
auto& stats = get_local_storage_proxy().get_db().local().find_column_family(schema).get_stats();
stats.cas_accept.mark(lc.stop().latency());
if (lc.is_start()) {
stats.estimated_cas_accept.add(lc.latency(), stats.cas_accept.hist.count);
}
});
}
future<> paxos_state::learn(schema_ptr schema, proposal decision, clock_type::time_point timeout,
tracing::trace_state_ptr tr_state) {
utils::latency_counter lc;
lc.start();
return do_with(std::move(decision), [tr_state = std::move(tr_state), schema, timeout] (proposal& decision) {
auto f = utils::get_local_injector().inject("paxos_state_learn_timeout", timeout);
table& cf = get_local_storage_proxy().get_db().local().find_column_family(schema);
db_clock::time_point t = cf.get_truncation_record();
auto truncated_at = std::chrono::duration_cast<std::chrono::milliseconds>(t.time_since_epoch()).count();
// When saving a decision, also delete the last accepted proposal. This is just an
// optimization to save space.
// Even though there is no guarantee we will see decisions in the right order,
// because messages can get delayed, so this decision can be older than our current most
// recent accepted proposal/committed decision, saving it is always safe due to column timestamps.
// Since the mutation uses the decision ballot timestamp, if cell timestmap of any current cell
// is strictly greater than the decision one, saving the decision will not erase it.
//
// The table may have been truncated since the proposal was initiated. In that case, we
// don't want to perform the mutation and potentially resurrect truncated data.
if (utils::UUID_gen::unix_timestamp(decision.ballot) >= truncated_at) {
f = f.then([schema, &decision, timeout, tr_state] {
logger.debug("Committing decision {}", decision);
tracing::trace(tr_state, "Committing decision {}", decision);
return get_local_storage_proxy().mutate_locally(schema, decision.update, db::commitlog::force_sync::yes, timeout);
});
} else {
logger.debug("Not committing decision {} as ballot timestamp predates last truncation time", decision);
tracing::trace(tr_state, "Not committing decision {} as ballot timestamp predates last truncation time", decision);
}
return f.then([&decision, schema, timeout] {
// We don't need to lock the partition key if there is no gap between loading paxos
// state and saving it, and here we're just blindly updating.
return db::system_keyspace::save_paxos_decision(*schema, decision, timeout);
});
}).finally([schema, lc] () mutable {
auto& stats = get_local_storage_proxy().get_db().local().find_column_family(schema).get_stats();
stats.cas_learn.mark(lc.stop().latency());
if (lc.is_start()) {
stats.estimated_cas_learn.add(lc.latency(), stats.cas_learn.hist.count);
}
});
}
future<> paxos_state::prune(schema_ptr schema, const partition_key& key, utils::UUID ballot, clock_type::time_point timeout,
tracing::trace_state_ptr tr_state) {
logger.debug("Delete paxos state for ballot {}", ballot);
tracing::trace(tr_state, "Delete paxos state for ballot {}", ballot);
return db::system_keyspace::delete_paxos_decision(*schema, key, ballot, timeout);
}
} // end of namespace "service::paxos"
<commit_msg>lwt: do not copy proposal in paxos_state::accept<commit_after>/*
* Copyright (C) 2019 ScyllaDB
*
* Modified by ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#include "service/storage_proxy.hh"
#include "service/paxos/proposal.hh"
#include "service/paxos/paxos_state.hh"
#include "db/system_keyspace.hh"
#include "schema_registry.hh"
#include "database.hh"
#include "service/storage_service.hh"
#include <utils/error_injection.hh>
namespace service::paxos {
logging::logger paxos_state::logger("paxos");
thread_local paxos_state::key_lock_map paxos_state::_paxos_table_lock;
thread_local paxos_state::key_lock_map paxos_state::_coordinator_lock;
paxos_state::key_lock_map::semaphore& paxos_state::key_lock_map::get_semaphore_for_key(const dht::token& key) {
return _locks.try_emplace(key, 1).first->second;
}
void paxos_state::key_lock_map::release_semaphore_for_key(const dht::token& key) {
auto it = _locks.find(key);
if (it != _locks.end() && (*it).second.current() == 1) {
_locks.erase(it);
}
}
future<prepare_response> paxos_state::prepare(tracing::trace_state_ptr tr_state, schema_ptr schema,
const query::read_command& cmd, const partition_key& key, utils::UUID ballot,
bool only_digest, query::digest_algorithm da, clock_type::time_point timeout) {
dht::token token = dht::get_token(*schema, key);
utils::latency_counter lc;
lc.start();
return with_locked_key(token, timeout, [&cmd, token, &key, ballot, tr_state, schema, only_digest, da, timeout] () mutable {
// When preparing, we need to use the same time as "now" (that's the time we use to decide if something
// is expired or not) across nodes, otherwise we may have a window where a Most Recent Decision shows up
// on some replica and not others during a new proposal (in storage_proxy::begin_and_repair_paxos()), and no
// amount of re-submit will fix this (because the node on which the commit has expired will have a
// tombstone that hides any re-submit). See CASSANDRA-12043 for details.
auto now_in_sec = utils::UUID_gen::unix_timestamp_in_sec(ballot);
return utils::get_local_injector().inject("paxos_state_prepare_timeout", timeout).then([&key, schema, now_in_sec, timeout] {
return db::system_keyspace::load_paxos_state(key, schema, gc_clock::time_point(now_in_sec), timeout);
}).then([&cmd, token = std::move(token), &key, ballot, tr_state, schema, only_digest, da, timeout] (paxos_state state) {
// If received ballot is newer that the one we already accepted it has to be accepted as well,
// but we will return the previously accepted proposal so that the new coordinator will use it instead of
// its own.
if (ballot.timestamp() > state._promised_ballot.timestamp()) {
logger.debug("Promising ballot {}", ballot);
tracing::trace(tr_state, "Promising ballot {}", ballot);
auto f1 = futurize_invoke(db::system_keyspace::save_paxos_promise, *schema, std::ref(key), ballot, timeout);
auto f2 = futurize_invoke([&] {
return do_with(dht::partition_range_vector({dht::partition_range::make_singular({token, key})}),
[tr_state, schema, &cmd, only_digest, da, timeout] (const dht::partition_range_vector& prv) {
return get_local_storage_proxy().get_db().local().query(schema, cmd,
{only_digest ? query::result_request::only_digest : query::result_request::result_and_digest, da},
prv, tr_state, query::result_memory_limiter::maximum_result_size, timeout);
});
});
return when_all(std::move(f1), std::move(f2)).then([state = std::move(state), only_digest] (auto t) {
auto&& f1 = std::get<0>(t);
auto&& f2 = std::get<1>(t);
if (f1.failed()) {
// Failed to save promise. Nothing we can do but throw.
return make_exception_future<prepare_response>(f1.get_exception());
}
std::optional<std::variant<foreign_ptr<lw_shared_ptr<query::result>>, query::result_digest>> data_or_digest;
// Silently ignore any errors querying the current value as the caller is prepared to fall back
// on querying it by itself in case it's missing in the response.
if (!f2.failed()) {
auto&& [result, hit_rate] = f2.get();
if (only_digest) {
data_or_digest = *result->digest();
} else {
data_or_digest = std::move(make_foreign(std::move(result)));
}
}
return make_ready_future<prepare_response>(prepare_response(promise(std::move(state._accepted_proposal),
std::move(state._most_recent_commit), std::move(data_or_digest))));
});
} else {
logger.debug("Promise rejected; {} is not sufficiently newer than {}", ballot, state._promised_ballot);
tracing::trace(tr_state, "Promise rejected; {} is not sufficiently newer than {}", ballot, state._promised_ballot);
// Return the currently promised ballot (rather than, e.g., the ballot of the last
// accepted proposal) so the coordinator can make sure it uses a newer ballot next
// time (#5667).
return make_ready_future<prepare_response>(prepare_response(std::move(state._promised_ballot)));
}
});
}).finally([schema, lc] () mutable {
auto& stats = get_local_storage_proxy().get_db().local().find_column_family(schema).get_stats();
stats.cas_prepare.mark(lc.stop().latency());
if (lc.is_start()) {
stats.estimated_cas_prepare.add(lc.latency(), stats.cas_prepare.hist.count);
}
});
}
future<bool> paxos_state::accept(tracing::trace_state_ptr tr_state, schema_ptr schema, dht::token token, const proposal& proposal,
clock_type::time_point timeout) {
utils::latency_counter lc;
lc.start();
return with_locked_key(token, timeout, [&proposal, schema, tr_state, timeout] () mutable {
auto now_in_sec = utils::UUID_gen::unix_timestamp_in_sec(proposal.ballot);
auto f = db::system_keyspace::load_paxos_state(proposal.update.decorated_key(*schema).key(), schema,
gc_clock::time_point(now_in_sec), timeout);
return f.then([&proposal, tr_state, schema, timeout] (paxos_state state) {
return utils::get_local_injector().inject("paxos_state_accept_timeout", timeout).then(
[&proposal, state = std::move(state), tr_state, schema, timeout] {
// Accept the proposal if we promised to accept it or the proposal is newer than the one we promised.
// Otherwise the proposal was cutoff by another Paxos proposer and has to be rejected.
if (proposal.ballot == state._promised_ballot || proposal.ballot.timestamp() > state._promised_ballot.timestamp()) {
logger.debug("Accepting proposal {}", proposal);
tracing::trace(tr_state, "Accepting proposal {}", proposal);
return db::system_keyspace::save_paxos_proposal(*schema, proposal, timeout).then([] {
return true;
});
} else {
logger.debug("Rejecting proposal for {} because in_progress is now {}", proposal, state._promised_ballot);
tracing::trace(tr_state, "Rejecting proposal for {} because in_progress is now {}", proposal, state._promised_ballot);
return make_ready_future<bool>(false);
}
});
});
}).finally([schema, lc] () mutable {
auto& stats = get_local_storage_proxy().get_db().local().find_column_family(schema).get_stats();
stats.cas_accept.mark(lc.stop().latency());
if (lc.is_start()) {
stats.estimated_cas_accept.add(lc.latency(), stats.cas_accept.hist.count);
}
});
}
future<> paxos_state::learn(schema_ptr schema, proposal decision, clock_type::time_point timeout,
tracing::trace_state_ptr tr_state) {
utils::latency_counter lc;
lc.start();
return do_with(std::move(decision), [tr_state = std::move(tr_state), schema, timeout] (proposal& decision) {
auto f = utils::get_local_injector().inject("paxos_state_learn_timeout", timeout);
table& cf = get_local_storage_proxy().get_db().local().find_column_family(schema);
db_clock::time_point t = cf.get_truncation_record();
auto truncated_at = std::chrono::duration_cast<std::chrono::milliseconds>(t.time_since_epoch()).count();
// When saving a decision, also delete the last accepted proposal. This is just an
// optimization to save space.
// Even though there is no guarantee we will see decisions in the right order,
// because messages can get delayed, so this decision can be older than our current most
// recent accepted proposal/committed decision, saving it is always safe due to column timestamps.
// Since the mutation uses the decision ballot timestamp, if cell timestmap of any current cell
// is strictly greater than the decision one, saving the decision will not erase it.
//
// The table may have been truncated since the proposal was initiated. In that case, we
// don't want to perform the mutation and potentially resurrect truncated data.
if (utils::UUID_gen::unix_timestamp(decision.ballot) >= truncated_at) {
f = f.then([schema, &decision, timeout, tr_state] {
logger.debug("Committing decision {}", decision);
tracing::trace(tr_state, "Committing decision {}", decision);
return get_local_storage_proxy().mutate_locally(schema, decision.update, db::commitlog::force_sync::yes, timeout);
});
} else {
logger.debug("Not committing decision {} as ballot timestamp predates last truncation time", decision);
tracing::trace(tr_state, "Not committing decision {} as ballot timestamp predates last truncation time", decision);
}
return f.then([&decision, schema, timeout] {
// We don't need to lock the partition key if there is no gap between loading paxos
// state and saving it, and here we're just blindly updating.
return db::system_keyspace::save_paxos_decision(*schema, decision, timeout);
});
}).finally([schema, lc] () mutable {
auto& stats = get_local_storage_proxy().get_db().local().find_column_family(schema).get_stats();
stats.cas_learn.mark(lc.stop().latency());
if (lc.is_start()) {
stats.estimated_cas_learn.add(lc.latency(), stats.cas_learn.hist.count);
}
});
}
future<> paxos_state::prune(schema_ptr schema, const partition_key& key, utils::UUID ballot, clock_type::time_point timeout,
tracing::trace_state_ptr tr_state) {
logger.debug("Delete paxos state for ballot {}", ballot);
tracing::trace(tr_state, "Delete paxos state for ballot {}", ballot);
return db::system_keyspace::delete_paxos_decision(*schema, key, ballot, timeout);
}
} // end of namespace "service::paxos"
<|endoftext|> |
<commit_before>void k_print_line(const char* string);
void k_print(const char* string);
extern "C"
void __attribute__ ((section ("main_section"))) kernel_main(){
k_print_line("hello, world!");
return;
}
typedef unsigned int uint8_t __attribute__((__mode__(__QI__)));
typedef unsigned int uint16_t __attribute__ ((__mode__ (__HI__)));
enum vga_color {
BLACK = 0,
BLUE = 1,
GREEN = 2,
CYAN = 3,
RED = 4,
MAGENTA = 5,
BROWN = 6,
LIGHT_GREY = 7,
DARK_GREY = 8,
LIGHT_BLUE = 9,
LIGHT_GREEN = 10,
LIGHT_CYAN = 11,
LIGHT_RED = 12,
LIGHT_MAGENTA = 13,
LIGHT_BROWN = 14,
WHITE = 15,
};
long current_line = 0;
long current_column = 0;
uint8_t make_color(vga_color fg, vga_color bg){
return fg | bg << 4;
}
uint16_t make_vga_entry(char c, uint8_t color){
uint16_t c16 = c;
uint16_t color16 = color;
return c16 | color16 << 8;
}
void k_print_line(const char* string){
k_print(string);
current_column = 0;
++current_line;
}
void k_print(const char* string){
uint16_t* vga_buffer = (uint16_t*) 0x0B8000;
for(int i = 0; string[i] != 0; ++i){
vga_buffer[current_line * 80 + current_column] = make_vga_entry(string[i], make_color(WHITE, BLACK));
++current_column;
}
return;
}
<commit_msg>Output more lines<commit_after>void k_print_line(const char* string);
void k_print(const char* string);
extern "C"
void __attribute__ ((section ("main_section"))) kernel_main(){
k_print_line("hello, ");
k_print_line(" world!");
return;
}
typedef unsigned int uint8_t __attribute__((__mode__(__QI__)));
typedef unsigned int uint16_t __attribute__ ((__mode__ (__HI__)));
enum vga_color {
BLACK = 0,
BLUE = 1,
GREEN = 2,
CYAN = 3,
RED = 4,
MAGENTA = 5,
BROWN = 6,
LIGHT_GREY = 7,
DARK_GREY = 8,
LIGHT_BLUE = 9,
LIGHT_GREEN = 10,
LIGHT_CYAN = 11,
LIGHT_RED = 12,
LIGHT_MAGENTA = 13,
LIGHT_BROWN = 14,
WHITE = 15,
};
long current_line = 0;
long current_column = 0;
uint8_t make_color(vga_color fg, vga_color bg){
return fg | bg << 4;
}
uint16_t make_vga_entry(char c, uint8_t color){
uint16_t c16 = c;
uint16_t color16 = color;
return c16 | color16 << 8;
}
void k_print_line(const char* string){
k_print(string);
current_column = 0;
++current_line;
}
void k_print(const char* string){
uint16_t* vga_buffer = (uint16_t*) 0x0B8000;
for(int i = 0; string[i] != 0; ++i){
vga_buffer[current_line * 80 + current_column] = make_vga_entry(string[i], make_color(WHITE, BLACK));
++current_column;
}
return;
}
<|endoftext|> |
<commit_before>/*=========================================================================
Library: CTK
Copyright (c) Isomics Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0.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.
=========================================================================*/
// Qt includes
#include <QApplication>
#include <QTreeView>
#include <QSettings>
#include <QDir>
// CTK Core
#include <ctkDICOMDatabase.h>
// CTK widget includes
#include <ctkDICOMQueryRetrieveWidget.h>
// Logger
#include "ctkLogger.h"
// STD includes
#include <iostream>
int main(int argc, char** argv)
{
ctkLogger::configure();
QApplication app(argc, argv);
app.setOrganizationName("commontk");
app.setOrganizationDomain("commontk.org");
app.setApplicationName("ctkDICOMQueryRetrieve");
QSettings settings;
QString databaseDirectory;
// set up the database
if (argc > 1)
{
QString directory(argv[1]);
settings.setValue("DatabaseDirectory", directory);
settings.sync();
}
if ( settings.value("DatabaseDirectory", "") == "" )
{
databaseDirectory = QString("./ctkDICOM-Database");
std::cerr << "No DatabaseDirectory on command line or in settings. Using \"" << databaseDirectory.toLatin1().data() << "\".\n";
} else
{
databaseDirectory = settings.value("DatabaseDirectory", "").toString();
}
QDir qdir(databaseDirectory);
if ( !qdir.exists(databaseDirectory) )
{
if ( !qdir.mkpath(databaseDirectory) )
{
std::cerr << "Could not create database directory \"" << databaseDirectory.toLatin1().data() << "\".\n";
return EXIT_FAILURE;
}
}
QString databaseFileName = databaseDirectory + QString("/ctkDICOM.sql");
QSharedPointer<ctkDICOMDatabase> dicomDatabase = QSharedPointer<ctkDICOMDatabase> (new ctkDICOMDatabase);
dicomDatabase->openDatabase(databaseFileName);
ctkDICOMQueryRetrieveWidget queryRetrieve;
queryRetrieve.setRetrieveDatabase(dicomDatabase);
queryRetrieve.show();
queryRetrieve.raise();
return app.exec();
}
<commit_msg>Enabled DCMTK debug logging to better debug DICOM networking.<commit_after>/*=========================================================================
Library: CTK
Copyright (c) Isomics Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0.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.
=========================================================================*/
// Qt includes
#include <QApplication>
#include <QTreeView>
#include <QSettings>
#include <QDir>
// CTK Core
#include <ctkDICOMDatabase.h>
// CTK widget includes
#include <ctkDICOMQueryRetrieveWidget.h>
// Logger
#include "ctkLogger.h"
#include "dcmtk/oflog/oflog.h"
// STD includes
#include <iostream>
int main(int argc, char** argv)
{
ctkLogger::configure();
// Set the DCMTK log level to debug
dcmtk::log4cplus::Logger rootLogger = dcmtk::log4cplus::Logger::getRoot();
rootLogger.setLogLevel(dcmtk::log4cplus::DEBUG_LOG_LEVEL);
QApplication app(argc, argv);
app.setOrganizationName("commontk");
app.setOrganizationDomain("commontk.org");
app.setApplicationName("ctkDICOMQueryRetrieve");
QSettings settings;
QString databaseDirectory;
// set up the database
if (argc > 1)
{
QString directory(argv[1]);
settings.setValue("DatabaseDirectory", directory);
settings.sync();
}
if ( settings.value("DatabaseDirectory", "") == "" )
{
databaseDirectory = QString("./ctkDICOM-Database");
std::cerr << "No DatabaseDirectory on command line or in settings. Using \"" << databaseDirectory.toLatin1().data() << "\".\n";
} else
{
databaseDirectory = settings.value("DatabaseDirectory", "").toString();
}
QDir qdir(databaseDirectory);
if ( !qdir.exists(databaseDirectory) )
{
if ( !qdir.mkpath(databaseDirectory) )
{
std::cerr << "Could not create database directory \"" << databaseDirectory.toLatin1().data() << "\".\n";
return EXIT_FAILURE;
}
}
QString databaseFileName = databaseDirectory + QString("/ctkDICOM.sql");
QSharedPointer<ctkDICOMDatabase> dicomDatabase = QSharedPointer<ctkDICOMDatabase> (new ctkDICOMDatabase);
dicomDatabase->openDatabase(databaseFileName);
ctkDICOMQueryRetrieveWidget queryRetrieve;
queryRetrieve.setRetrieveDatabase(dicomDatabase);
queryRetrieve.show();
queryRetrieve.raise();
return app.exec();
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: viewobjectcontactofsdrmediaobj.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2005-09-08 20:02:00 $
*
* 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 _SDR_CONTACT_VIEWOBJECTCONTACTOFSDRMEDIAOBJ_HXX
#define _SDR_CONTACT_VIEWOBJECTCONTACTOFSDRMEDIAOBJ_HXX
#ifndef _SDR_CONTACT_VIEWOBJECTCONTACT_HXX
#include <svx/sdr/contact/viewobjectcontact.hxx>
#endif
namespace avmedia { class MediaItem; }
namespace sdr
{
namespace contact
{
class SdrMediaWindow;
class ViewObjectContactOfSdrMediaObj : public ViewObjectContact
{
public:
ViewObjectContactOfSdrMediaObj( ObjectContact& rObjectContact,
ViewContact& rViewContact,
const ::avmedia::MediaItem& rMediaItem );
// The destructor. When PrepareDelete() was not called before (see there)
// warnings will be generated in debug version if there are still contacts
// existing.
virtual ~ViewObjectContactOfSdrMediaObj();
public:
Window* getWindow() const;
bool hasPreferredSize() const;
Size getPreferredSize() const;
void updateMediaItem( ::avmedia::MediaItem& rItem ) const;
void executeMediaItem( const ::avmedia::MediaItem& rItem );
protected:
// Prepare deletion of this object. This needs to be called always
// before really deleting this objects. This is necessary since in a c++
// destructor no virtual function calls are allowed. To avoid this problem,
// it is required to first call PrepareDelete().
virtual void PrepareDelete();
// Paint this object. This is before evtl. SubObjects get painted. This method
// needs to set the flag mbIsPainted and mbIsInvalidated and to set the
// maPaintedRectangle member. This information is later used for invalidates
// and repaints.
virtual void PaintObject(DisplayInfo& rDisplayInfo);
private:
::sdr::contact::SdrMediaWindow* mpMediaWindow;
};
} // end of namespace contact
} // end of namespace sdr
//////////////////////////////////////////////////////////////////////////////
#endif // _SDR_CONTACT_VIEWOBJECTCONTACTOFSDRMEDIAOBJ_HXX
<commit_msg>INTEGRATION: CWS aw024 (1.3.76); FILE MERGED 2005/09/18 01:39:50 aw 1.3.76.2: RESYNC: (1.3-1.4); FILE MERGED 2005/05/19 12:30:05 aw 1.3.76.1: #i39529#<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: viewobjectcontactofsdrmediaobj.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: ihi $ $Date: 2006-11-14 13:05:53 $
*
* 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 _SDR_CONTACT_VIEWOBJECTCONTACTOFSDRMEDIAOBJ_HXX
#define _SDR_CONTACT_VIEWOBJECTCONTACTOFSDRMEDIAOBJ_HXX
#ifndef _SDR_CONTACT_VIEWOBJECTCONTACT_HXX
#include <svx/sdr/contact/viewobjectcontact.hxx>
#endif
namespace avmedia { class MediaItem; }
class Window;
namespace sdr
{
namespace contact
{
class SdrMediaWindow;
class ViewObjectContactOfSdrMediaObj : public ViewObjectContact
{
public:
ViewObjectContactOfSdrMediaObj( ObjectContact& rObjectContact,
ViewContact& rViewContact,
const ::avmedia::MediaItem& rMediaItem );
// The destructor. When PrepareDelete() was not called before (see there)
// warnings will be generated in debug version if there are still contacts
// existing.
virtual ~ViewObjectContactOfSdrMediaObj();
public:
Window* getWindow() const;
bool hasPreferredSize() const;
Size getPreferredSize() const;
void updateMediaItem( ::avmedia::MediaItem& rItem ) const;
void executeMediaItem( const ::avmedia::MediaItem& rItem );
protected:
// Prepare deletion of this object. This needs to be called always
// before really deleting this objects. This is necessary since in a c++
// destructor no virtual function calls are allowed. To avoid this problem,
// it is required to first call PrepareDelete().
virtual void PrepareDelete();
// Paint this object. This is before evtl. SubObjects get painted. This method
// needs to set the flag mbIsPainted and mbIsInvalidated and to set the
// maPaintedRectangle member. This information is later used for invalidates
// and repaints.
virtual void PaintObject(DisplayInfo& rDisplayInfo);
private:
::sdr::contact::SdrMediaWindow* mpMediaWindow;
};
} // end of namespace contact
} // end of namespace sdr
//////////////////////////////////////////////////////////////////////////////
#endif // _SDR_CONTACT_VIEWOBJECTCONTACTOFSDRMEDIAOBJ_HXX
<|endoftext|> |
<commit_before>#pragma once
/*
** Copyright (C) 2012 Aldebaran Robotics
** See COPYING for the license
*/
#ifndef _QITYPE_DETAILS_TYPETUPLE_HXX_
#define _QITYPE_DETAILS_TYPETUPLE_HXX_
#include <qi/preproc.hpp>
namespace qi
{
namespace detail {
template<typename T> void setFromStorage(T& ref, void* storage)
{
ref = *(T*)typeOf<T>()->ptrFromStorage(&storage);
}
}
}
#define QI_TYPE_STRUCT_DECLARE(name) \
namespace qi { \
template<> struct TypeImpl<name>: public TypeTuple \
{ \
public: \
virtual std::vector<Type*> memberTypes(); \
virtual void* get(void* storage, unsigned int index); \
virtual void set(void** storage, unsigned int index, void* valStorage); \
_QI_BOUNCE_TYPE_METHODS(DefaultTypeImplMethods<name>); \
}; }
#define __QI_TUPLE_TYPE(_, what, field) res.push_back(typeOf(ptr->field));
#define __QI_TUPLE_GET(_, what, field) if (i == index) return typeOf(ptr->field)->initializeStorage(&ptr->field); i++;
#define __QI_TUPLE_SET(_, what, field) if (i == index) detail::setFromStorage(ptr->field, valueStorage); i++;
#define __QI_TYPE_STRUCT_IMPLEMENT(name, inl, onSet, ...) \
namespace qi { \
inl std::vector<Type*> TypeImpl<name>::memberTypes() \
{ \
name* ptr = 0; \
std::vector<Type*> res; \
QI_VAARGS_APPLY(__QI_TUPLE_TYPE, _, __VA_ARGS__); \
return res; \
} \
inl void* TypeImpl<name>::get(void* storage, unsigned int index) \
{ \
unsigned int i = 0; \
name* ptr = (name*)ptrFromStorage(&storage); \
QI_VAARGS_APPLY(__QI_TUPLE_GET, _, __VA_ARGS__); \
return 0; \
} \
inl void TypeImpl<name>::set(void** storage, unsigned int index, void* valueStorage)\
{ \
unsigned int i=0; \
name* ptr = (name*)ptrFromStorage(storage); \
QI_VAARGS_APPLY(__QI_TUPLE_SET, _, __VA_ARGS__); \
onSet \
}\
}
/// Allow the QI_TYPE_STRUCT macro and variants to access private members
#define QI_TYPE_STRUCT_PRIVATE_ACCESS(name) \
friend class qi::TypeImpl<name>;
/** Declare a simple struct to the type system.
* First argument is the structure name. Remaining arguments are the structure
* fields.
* This macro must be called outside any namespace.
* This macro should be called in the header file defining the structure 'name',
* or in a header included by all source files using the structure.
* See QI_TYPE_STRUCT_REGISTER for a similar macro that can be called from a
* single source file.
*/
#define QI_TYPE_STRUCT(name, ...) \
QI_TYPE_STRUCT_DECLARE(name) \
__QI_TYPE_STRUCT_IMPLEMENT(name, inline, /**/, __VA_ARGS__)
/** Similar to QI_TYPE_STRUCT, but evaluates 'onSet' after writting to an instance.
* The instance is accessible through the variable 'ptr'.
*/
#define QI_TYPE_STRUCT_EX(name, onSet, ...) \
QI_TYPE_STRUCT_DECLARE(name) \
__QI_TYPE_STRUCT_IMPLEMENT(name, inline, onSet, __VA_ARGS__)
#define QI_TYPE_STRUCT_IMPLEMENT(name, ...) \
__QI_TYPE_STRUCT_IMPLEMENT(name, /**/, /**/, __VA_ARGS__)
/** Similar to QI_TYPE_STRUCT, but using the runtime factory instead of the
* compile-time template.
*
*/
#define QI_TYPE_STRUCT_REGISTER(name, ...) \
namespace _qi_ { \
QI_TYPE_STRUCT(name, __VA_ARGS__); \
} \
QI_TYPE_REGISTER_CUSTOM(name, _qi_::qi::TypeImpl<name>)
/** Declares that name is equivalent to type bounceTo, and that instances
* can be converted using the conversion function with signature 'bounceTo* (name*)'.
* This macro should be called in a header included by all code using the 'name'
* class.
* See QI_TYPE_STRUCT_BOUNCE_REGISTER for a similar macro that can be called from a
* single source file.
*/
#define QI_TYPE_STRUCT_BOUNCE(name, bounceTo, conversion) \
namespace qi { \
template<> class TypeImpl<name>: public ::qi::TypeTupleBouncer<name, bounceTo> \
{ \
public: \
void adaptStorage(void** storage, void** adapted) \
{ \
name* ptr = (name*)ptrFromStorage(storage); \
bounceTo * tptr = conversion(ptr); \
*adapted = bounceType()->initializeStorage(tptr); \
} \
};}
/** Similar to QI_TYPE_STRUCT_BOUNCE, but using the runtime factory instead of the
* compile-time template.
*/
#define QI_TYPE_STRUCT_BOUNCE_REGISTER(name, bounceTo, conversion) \
namespace _qi_ { \
QI_TYPE_STRUCT_BOUNCE(name, bounceTo, conversion); \
} \
QI_TYPE_REGISTER_CUSTOM(name, _qi_::qi::TypeImpl<name>)
namespace qi {
template<typename T, typename TO> class TypeTupleBouncer: public TypeTuple
{
public:
TypeTuple* bounceType()
{
static Type* result = 0;
if (!result)
result = typeOf<TO>();
return static_cast<TypeTuple*>(result);
}
virtual void adaptStorage(void** storage, void** adapted) = 0;
typedef DefaultTypeImplMethods<T> Methods;
virtual std::vector<Type*> memberTypes()
{
return bounceType()->memberTypes();
}
virtual void* get(void* storage, unsigned int index)
{
void* astorage;
adaptStorage(&storage, &astorage);
return bounceType()->get(astorage, index);
}
virtual void set(void** storage, unsigned int index, void* valStorage)
{
void* astorage;
adaptStorage(storage, &astorage);
bounceType()->set(&astorage, index, valStorage);
}
_QI_BOUNCE_TYPE_METHODS(Methods);
};
template<typename F, typename S>
class TypeImpl<std::pair<F, S> >: public TypeTuple
{
public:
typedef DefaultTypeImplMethods<std::pair<F, S> > Methods;
typedef typename std::pair<F, S> BackendType;
std::vector<Type*> memberTypes()
{
static std::vector<Type*>* result=0;
if (!result)
{
result = new std::vector<Type*>();
result->push_back(typeOf<F>());
result->push_back(typeOf<S>());
}
return *result;
}
void* get(void* storage, unsigned int index)
{
BackendType* ptr = (BackendType*)ptrFromStorage(&storage);
// Will work if F or S are references
if (!index)
return typeOf<F>()->initializeStorage(const_cast<void*>((void*)&ptr->first));
else
return typeOf<S>()->initializeStorage(const_cast<void*>((void*)&ptr->second));
}
void set(void** storage, unsigned int index, void* valStorage)
{
BackendType* ptr = (BackendType*)ptrFromStorage(storage);
if (!index)
detail::TypeManagerDefault<F>::copy(const_cast<void*>((void*)&ptr->first), typeOf<F>()->ptrFromStorage(&valStorage));
else
detail::TypeManagerDefault<S>::copy(const_cast<void*>((void*)&ptr->second), typeOf<S>()->ptrFromStorage(&valStorage));
}
_QI_BOUNCE_TYPE_METHODS(Methods);
};
}
#endif // _QITYPE_DETAILS_TYPETUPLE_HXX_
<commit_msg>QI_TYPE_STRUCT_REGISTER: fix by not assuming we are in ns qi in dependant macros.<commit_after>#pragma once
/*
** Copyright (C) 2012 Aldebaran Robotics
** See COPYING for the license
*/
#ifndef _QITYPE_DETAILS_TYPETUPLE_HXX_
#define _QITYPE_DETAILS_TYPETUPLE_HXX_
#include <qi/preproc.hpp>
namespace qi
{
namespace detail {
template<typename T> void setFromStorage(T& ref, void* storage)
{
ref = *(T*)typeOf<T>()->ptrFromStorage(&storage);
}
}
}
#define QI_TYPE_STRUCT_DECLARE(name) \
namespace qi { \
template<> struct TypeImpl<name>: public ::qi::TypeTuple \
{ \
public: \
virtual std::vector< ::qi::Type*> memberTypes(); \
virtual void* get(void* storage, unsigned int index); \
virtual void set(void** storage, unsigned int index, void* valStorage); \
_QI_BOUNCE_TYPE_METHODS(::qi::DefaultTypeImplMethods<name>); \
}; }
#define __QI_TUPLE_TYPE(_, what, field) res.push_back(::qi::typeOf(ptr->field));
#define __QI_TUPLE_GET(_, what, field) if (i == index) return ::qi::typeOf(ptr->field)->initializeStorage(&ptr->field); i++;
#define __QI_TUPLE_SET(_, what, field) if (i == index) ::qi::detail::setFromStorage(ptr->field, valueStorage); i++;
#define __QI_TYPE_STRUCT_IMPLEMENT(name, inl, onSet, ...) \
namespace qi { \
inl std::vector< ::qi::Type*> TypeImpl<name>::memberTypes() \
{ \
name* ptr = 0; \
std::vector< ::qi::Type*> res; \
QI_VAARGS_APPLY(__QI_TUPLE_TYPE, _, __VA_ARGS__); \
return res; \
} \
inl void* TypeImpl<name>::get(void* storage, unsigned int index) \
{ \
unsigned int i = 0; \
name* ptr = (name*)ptrFromStorage(&storage); \
QI_VAARGS_APPLY(__QI_TUPLE_GET, _, __VA_ARGS__); \
return 0; \
} \
inl void TypeImpl<name>::set(void** storage, unsigned int index, void* valueStorage)\
{ \
unsigned int i=0; \
name* ptr = (name*)ptrFromStorage(storage); \
QI_VAARGS_APPLY(__QI_TUPLE_SET, _, __VA_ARGS__); \
onSet \
}\
}
/// Allow the QI_TYPE_STRUCT macro and variants to access private members
#define QI_TYPE_STRUCT_PRIVATE_ACCESS(name) \
friend class qi::TypeImpl<name>;
/** Declare a simple struct to the type system.
* First argument is the structure name. Remaining arguments are the structure
* fields.
* This macro must be called outside any namespace.
* This macro should be called in the header file defining the structure 'name',
* or in a header included by all source files using the structure.
* See QI_TYPE_STRUCT_REGISTER for a similar macro that can be called from a
* single source file.
*/
#define QI_TYPE_STRUCT(name, ...) \
QI_TYPE_STRUCT_DECLARE(name) \
__QI_TYPE_STRUCT_IMPLEMENT(name, inline, /**/, __VA_ARGS__)
/** Similar to QI_TYPE_STRUCT, but evaluates 'onSet' after writting to an instance.
* The instance is accessible through the variable 'ptr'.
*/
#define QI_TYPE_STRUCT_EX(name, onSet, ...) \
QI_TYPE_STRUCT_DECLARE(name) \
__QI_TYPE_STRUCT_IMPLEMENT(name, inline, onSet, __VA_ARGS__)
#define QI_TYPE_STRUCT_IMPLEMENT(name, ...) \
__QI_TYPE_STRUCT_IMPLEMENT(name, /**/, /**/, __VA_ARGS__)
/** Similar to QI_TYPE_STRUCT, but using the runtime factory instead of the
* compile-time template.
*
*/
#define QI_TYPE_STRUCT_REGISTER(name, ...) \
namespace _qi_ { \
QI_TYPE_STRUCT(name, __VA_ARGS__); \
} \
QI_TYPE_REGISTER_CUSTOM(name, _qi_::qi::TypeImpl<name>)
/** Declares that name is equivalent to type bounceTo, and that instances
* can be converted using the conversion function with signature 'bounceTo* (name*)'.
* This macro should be called in a header included by all code using the 'name'
* class.
* See QI_TYPE_STRUCT_BOUNCE_REGISTER for a similar macro that can be called from a
* single source file.
*/
#define QI_TYPE_STRUCT_BOUNCE(name, bounceTo, conversion) \
namespace qi { \
template<> class TypeImpl<name>: public ::qi::TypeTupleBouncer<name, bounceTo> \
{ \
public: \
void adaptStorage(void** storage, void** adapted) \
{ \
name* ptr = (name*)ptrFromStorage(storage); \
bounceTo * tptr = conversion(ptr); \
*adapted = bounceType()->initializeStorage(tptr); \
} \
};}
/** Similar to QI_TYPE_STRUCT_BOUNCE, but using the runtime factory instead of the
* compile-time template.
*/
#define QI_TYPE_STRUCT_BOUNCE_REGISTER(name, bounceTo, conversion) \
namespace _qi_ { \
QI_TYPE_STRUCT_BOUNCE(name, bounceTo, conversion); \
} \
QI_TYPE_REGISTER_CUSTOM(name, _qi_::qi::TypeImpl<name>)
namespace qi {
template<typename T, typename TO> class TypeTupleBouncer: public TypeTuple
{
public:
TypeTuple* bounceType()
{
static Type* result = 0;
if (!result)
result = typeOf<TO>();
return static_cast<TypeTuple*>(result);
}
virtual void adaptStorage(void** storage, void** adapted) = 0;
typedef DefaultTypeImplMethods<T> Methods;
virtual std::vector<Type*> memberTypes()
{
return bounceType()->memberTypes();
}
virtual void* get(void* storage, unsigned int index)
{
void* astorage;
adaptStorage(&storage, &astorage);
return bounceType()->get(astorage, index);
}
virtual void set(void** storage, unsigned int index, void* valStorage)
{
void* astorage;
adaptStorage(storage, &astorage);
bounceType()->set(&astorage, index, valStorage);
}
_QI_BOUNCE_TYPE_METHODS(Methods);
};
template<typename F, typename S>
class TypeImpl<std::pair<F, S> >: public TypeTuple
{
public:
typedef DefaultTypeImplMethods<std::pair<F, S> > Methods;
typedef typename std::pair<F, S> BackendType;
std::vector<Type*> memberTypes()
{
static std::vector<Type*>* result=0;
if (!result)
{
result = new std::vector<Type*>();
result->push_back(typeOf<F>());
result->push_back(typeOf<S>());
}
return *result;
}
void* get(void* storage, unsigned int index)
{
BackendType* ptr = (BackendType*)ptrFromStorage(&storage);
// Will work if F or S are references
if (!index)
return typeOf<F>()->initializeStorage(const_cast<void*>((void*)&ptr->first));
else
return typeOf<S>()->initializeStorage(const_cast<void*>((void*)&ptr->second));
}
void set(void** storage, unsigned int index, void* valStorage)
{
BackendType* ptr = (BackendType*)ptrFromStorage(storage);
if (!index)
detail::TypeManagerDefault<F>::copy(const_cast<void*>((void*)&ptr->first), typeOf<F>()->ptrFromStorage(&valStorage));
else
detail::TypeManagerDefault<S>::copy(const_cast<void*>((void*)&ptr->second), typeOf<S>()->ptrFromStorage(&valStorage));
}
_QI_BOUNCE_TYPE_METHODS(Methods);
};
}
#endif // _QITYPE_DETAILS_TYPETUPLE_HXX_
<|endoftext|> |
<commit_before>#include "forumreader.h"
#include "website_backend/gumboparserimpl.h"
#include "common/filedownloader.h"
namespace {
template <typename T>
void dumpFutureObj(QFuture<T> future, QString name)
{
#ifdef RBR_PRINT_DEBUG_OUTPUT
qDebug() << "----------------------------------------------------";
qDebug() << "Future name:" << name;
qDebug() << "Future is started:" << future.isStarted();
qDebug() << "Future is running:" << future.isRunning();
qDebug() << "Future is finished:" << future.isFinished();
qDebug() << "Future is paused:" << future.isPaused();
qDebug() << "Future is canceled:" << future.isCanceled();
qDebug() << "Future has result:" << future.isResultReadyAt(0);
qDebug() << "----------------------------------------------------";
#else
Q_UNUSED(future);
Q_UNUSED(name);
#endif
}
}
ForumReader::ForumReader() :
m_forumPageCountWatcher(),
m_forumPageParserWatcher(),
m_pagePosts(),
m_pageCount(0),
m_pageNo(0),
m_lastError(ResultCode::Ok)
{
connect(&m_downloader, &FileDownloader::downloadProgress, this, &ForumReader::onForumPageDownloadProgress);
connect(&m_downloader, &FileDownloader::downloadFinished, this, &ForumReader::onForumPageDownloaded);
connect(&m_downloader, &FileDownloader::downloadFailed, this, &ForumReader::onForumPageDownloadFailed);
connect(&m_forumPageCountWatcher, &IntFutureWatcher::finished, this, &ForumReader::onForumPageCountParsed);
connect(&m_forumPageCountWatcher, &IntFutureWatcher::canceled, this, &ForumReader::onForumPageCountParsingCanceled);
connect(&m_forumPageParserWatcher, &ParserFutureWatcher::finished, this, &ForumReader::onForumPageParsed);
connect(&m_forumPageParserWatcher, &ParserFutureWatcher::canceled, this, &ForumReader::onForumPageParsingCanceled);
}
ForumReader::~ForumReader()
{
}
QString ForumReader::applicationDirPath() const
{
QString result = qApp->applicationDirPath();
if (!result.endsWith("/")) result += "/";
return result;
}
QUrl ForumReader::convertToUrl(QString urlStr) const
{
return QUrl(urlStr);
}
#ifdef FORUM_READER_SYNC_API
int ForumReader::parsePageCount(QString urlStr)
{
// Cleanup
m_pagePosts.clear();
m_pageCount = 0;
// 1) Download the first forum web page
QByteArray htmlRawData;
if (!FileDownloader::downloadUrl(urlStr, htmlRawData)) { Q_ASSERT(0); return 0; }
// 2) Parse the page HTML to get the page number
BankiRuForum::ForumPageParser fpp;
int resultFpp = fpp.getPageCount(htmlRawData, m_pageCount);
Q_ASSERT(resultFpp == 0); if (resultFpp != 0) { m_pageCount = 0; return 0; }
return m_pageCount;
}
bool ForumReader::parseForumPage(QString urlStr, int pageNo)
{
// Cleanup
m_pagePosts.clear();
m_pageCount = 0;
m_pageNo = pageNo;
// 1) Download the first forum web page
QByteArray htmlRawData;
if (!FileDownloader::downloadUrl(urlStr, htmlRawData)) { Q_ASSERT(0); return false; }
// 2) Parse the page HTML to get the page number
BankiRuForum::ForumPageParser fpp;
int resultFpp = fpp.getPageCount(htmlRawData, m_pageCount);
Q_ASSERT(resultFpp == 0); if (resultFpp != 0) { m_pageCount = 0; return false; }
// 3) Parse the page HTML to get the page user posts
resultFpp = fpp.getPagePosts(htmlRawData, m_pagePosts);
Q_ASSERT(resultFpp == 0); if (resultFpp != 0) { m_pagePosts.clear(); return false; }
return true;
}
#endif
namespace {
int parsePageCountAsync(QString urlStr)
{
int result = 0;
// 1) Download the first forum web page
QByteArray htmlRawData;
if (!FileDownloader::downloadUrl(urlStr, htmlRawData))
{
Q_ASSERT(0);
return result;
}
// 2) Parse the page HTML to get the page number
BankiRuForum::ForumPageParser fpp;
ResultCode resultFpp = fpp.getPageCount(htmlRawData, result);
if (resultFpp != ResultCode::Ok)
{
Q_ASSERT(0);
result = 0;
return result;
}
return result;
}
}
void ForumReader::startPageCountAsync(QString urlStr)
{
dumpFutureObj(m_forumPageCountWatcher.future(), "m_forumPageCountWatcher");
// Wait for previous operation finish (if any)
// NOTE: QtConcurrent::run() return future that cannot be canceled
//m_forumPageCountWatcher.cancel();
m_forumPageCountWatcher.waitForFinished();
auto forumPageCountFuture = QtConcurrent::run(std::bind(parsePageCountAsync, urlStr));
m_forumPageCountWatcher.setFuture(forumPageCountFuture);
}
namespace {
// NOTE: QtConcurrent require to return collection; return result code will be much more straightforward to reader
BankiRuForum::UserPosts parsePageAsync(QByteArray rawHtmlData, int& pageCount, ResultCode& errorCode)
{
BankiRuForum::UserPosts result;
errorCode = ResultCode::Ok;
// 2) Parse the page HTML to get the page number
BankiRuForum::ForumPageParser fpp;
errorCode = fpp.getPageCount(rawHtmlData, pageCount);
if (errorCode != ResultCode::Ok)
{
Q_ASSERT(0);
return result;
}
// 3) Parse the page HTML to get the page user posts
errorCode = fpp.getPagePosts(rawHtmlData, result);
if (errorCode != ResultCode::Ok)
{
Q_ASSERT(0);
return result;
}
return result;
}
}
void ForumReader::startPageParseAsync(QString urlStr, int pageNo)
{
dumpFutureObj(m_forumPageParserWatcher.future(), "m_forumPageParserWatcher");
// Cleanup
m_pagePosts.clear();
// FIXME: implement updatePageNumber() method and call it here
// m_pageCount = 0;
m_pageNo = pageNo;
m_downloader.startDownloadAsync(urlStr);
// FIXME: a better way? server don't return Content-Length header;
// a HTML page size is unknown, and the only way to get it - download the entire page;
// however we know forum HTML page average size - it is around 400 Kb
emit pageContentParseProgressRange(0, 400000);
}
void ForumReader::onForumPageCountParsed()
{
dumpFutureObj(m_forumPageCountWatcher.future(), "m_forumPageCountWatcher");
int pageCount = m_forumPageCountWatcher.result();
Q_ASSERT(pageCount > 0);
m_pageCount = pageCount;
emit pageCountParsed(pageCount);
}
void ForumReader::onForumPageCountParsingCanceled()
{
Q_ASSERT_X(0, Q_FUNC_INFO, "QtConcurrent::run result cannot be canceled");
}
void ForumReader::onForumPageDownloadProgress(qint64 bytesReceived, qint64 bytesTotal)
{
// qDebug() << Q_FUNC_INFO << bytesReceived << "/" << bytesTotal;
// NOTE: currently banki.ru server don't return Content-Length header
Q_ASSERT(bytesTotal <= 0);
// NOTE: HTML page size should not exceed 2^32 bytes, i hope :)
emit pageContentParseProgress((int)bytesReceived);
}
void ForumReader::onForumPageDownloaded()
{
m_pageData = m_downloader.downloadedData();
Q_ASSERT(!m_pageData.isEmpty());
// Wait for previous operation finish (if any)
// NOTE: QtConcurrent::run() return future that cannot be canceled
//m_forumPageParserWatcher.cancel();
m_forumPageParserWatcher.waitForFinished();
auto forumPageParseFuture = QtConcurrent::run(
std::bind(parsePageAsync, m_pageData, std::ref(m_pageCount), std::ref(m_lastError)));
m_forumPageParserWatcher.setFuture(forumPageParseFuture);
}
void ForumReader::onForumPageDownloadFailed(ResultCode code)
{
// FIXME: implement
}
void ForumReader::onForumPageParsed()
{
dumpFutureObj(m_forumPageParserWatcher.future(), "m_forumPageParserWatcher");
m_pagePosts = m_forumPageParserWatcher.result();
emit pageContentParsed(m_pageNo);
}
void ForumReader::onForumPageParsingCanceled()
{
Q_ASSERT_X(0, Q_FUNC_INFO, "QFuture returned by QtConcurrent::run() cannot be canceled");
}
// ----------------------------------------------------------------------------------------------------------------------------------------
int ForumReader::pageCount() const
{
return m_pageCount;
}
int ForumReader::postCount() const
{
return m_pagePosts.size();
}
QString ForumReader::postAuthorQml(int index) const
{
Q_ASSERT(index >= 0 && index < m_pagePosts.size());
return m_pagePosts[index].first.getQmlString(qrand());
}
int ForumReader::postAvatarMaxWidth() const
{
int maxWidth = 100;
for(int i = 0; i < m_pagePosts.size(); ++i)
{
if (m_pagePosts[i].first.m_userAvatar.isNull()) continue;
int width = m_pagePosts[i].first.m_userAvatar->m_width;
if(width > maxWidth) maxWidth = width;
}
return maxWidth;
}
QDateTime ForumReader::postDateTime(int index) const
{
Q_ASSERT(index >= 0 && index < m_pagePosts.size());
return m_pagePosts[index].second.m_date;
}
QString ForumReader::postText(int index) const
{
Q_ASSERT(index >= 0 && index < m_pagePosts.size());
if (m_pagePosts[index].second.m_data.empty()) return QString();
return m_pagePosts[index].second.getQmlString(qrand());
}
QString ForumReader::postLastEdit(int index) const
{
Q_ASSERT(index >= 0 && index < m_pagePosts.size());
return m_pagePosts[index].second.m_lastEdit;
}
int ForumReader::postLikeCount(int index) const
{
Q_ASSERT(index >= 0 && index < m_pagePosts.size());
return m_pagePosts[index].second.m_likeCounter;
}
QString ForumReader::postAuthorSignature(int index) const
{
Q_ASSERT(index >= 0 && index < m_pagePosts.size());
return m_pagePosts[index].second.m_userSignature;
}
<commit_msg>QML frontend: the last warning was fixed<commit_after>#include "forumreader.h"
#include "website_backend/gumboparserimpl.h"
#include "common/filedownloader.h"
namespace {
template <typename T>
void dumpFutureObj(QFuture<T> future, QString name)
{
#ifdef RBR_PRINT_DEBUG_OUTPUT
qDebug() << "----------------------------------------------------";
qDebug() << "Future name:" << name;
qDebug() << "Future is started:" << future.isStarted();
qDebug() << "Future is running:" << future.isRunning();
qDebug() << "Future is finished:" << future.isFinished();
qDebug() << "Future is paused:" << future.isPaused();
qDebug() << "Future is canceled:" << future.isCanceled();
qDebug() << "Future has result:" << future.isResultReadyAt(0);
qDebug() << "----------------------------------------------------";
#else
Q_UNUSED(future);
Q_UNUSED(name);
#endif
}
}
ForumReader::ForumReader() :
m_forumPageCountWatcher(),
m_forumPageParserWatcher(),
m_pagePosts(),
m_pageCount(0),
m_pageNo(0),
m_lastError(ResultCode::Ok)
{
connect(&m_downloader, &FileDownloader::downloadProgress, this, &ForumReader::onForumPageDownloadProgress);
connect(&m_downloader, &FileDownloader::downloadFinished, this, &ForumReader::onForumPageDownloaded);
connect(&m_downloader, &FileDownloader::downloadFailed, this, &ForumReader::onForumPageDownloadFailed);
connect(&m_forumPageCountWatcher, &IntFutureWatcher::finished, this, &ForumReader::onForumPageCountParsed);
connect(&m_forumPageCountWatcher, &IntFutureWatcher::canceled, this, &ForumReader::onForumPageCountParsingCanceled);
connect(&m_forumPageParserWatcher, &ParserFutureWatcher::finished, this, &ForumReader::onForumPageParsed);
connect(&m_forumPageParserWatcher, &ParserFutureWatcher::canceled, this, &ForumReader::onForumPageParsingCanceled);
}
ForumReader::~ForumReader()
{
}
QString ForumReader::applicationDirPath() const
{
QString result = qApp->applicationDirPath();
if (!result.endsWith("/")) result += "/";
return result;
}
QUrl ForumReader::convertToUrl(QString urlStr) const
{
return QUrl(urlStr);
}
#ifdef FORUM_READER_SYNC_API
int ForumReader::parsePageCount(QString urlStr)
{
// Cleanup
m_pagePosts.clear();
m_pageCount = 0;
// 1) Download the first forum web page
QByteArray htmlRawData;
if (!FileDownloader::downloadUrl(urlStr, htmlRawData)) { Q_ASSERT(0); return 0; }
// 2) Parse the page HTML to get the page number
BankiRuForum::ForumPageParser fpp;
int resultFpp = fpp.getPageCount(htmlRawData, m_pageCount);
Q_ASSERT(resultFpp == 0); if (resultFpp != 0) { m_pageCount = 0; return 0; }
return m_pageCount;
}
bool ForumReader::parseForumPage(QString urlStr, int pageNo)
{
// Cleanup
m_pagePosts.clear();
m_pageCount = 0;
m_pageNo = pageNo;
// 1) Download the first forum web page
QByteArray htmlRawData;
if (!FileDownloader::downloadUrl(urlStr, htmlRawData)) { Q_ASSERT(0); return false; }
// 2) Parse the page HTML to get the page number
BankiRuForum::ForumPageParser fpp;
int resultFpp = fpp.getPageCount(htmlRawData, m_pageCount);
Q_ASSERT(resultFpp == 0); if (resultFpp != 0) { m_pageCount = 0; return false; }
// 3) Parse the page HTML to get the page user posts
resultFpp = fpp.getPagePosts(htmlRawData, m_pagePosts);
Q_ASSERT(resultFpp == 0); if (resultFpp != 0) { m_pagePosts.clear(); return false; }
return true;
}
#endif
namespace {
int parsePageCountAsync(QString urlStr)
{
int result = 0;
// 1) Download the first forum web page
QByteArray htmlRawData;
if (!FileDownloader::downloadUrl(urlStr, htmlRawData))
{
Q_ASSERT(0);
return result;
}
// 2) Parse the page HTML to get the page number
BankiRuForum::ForumPageParser fpp;
ResultCode resultFpp = fpp.getPageCount(htmlRawData, result);
if (resultFpp != ResultCode::Ok)
{
Q_ASSERT(0);
result = 0;
return result;
}
return result;
}
}
void ForumReader::startPageCountAsync(QString urlStr)
{
dumpFutureObj(m_forumPageCountWatcher.future(), "m_forumPageCountWatcher");
// Wait for previous operation finish (if any)
// NOTE: QtConcurrent::run() return future that cannot be canceled
//m_forumPageCountWatcher.cancel();
m_forumPageCountWatcher.waitForFinished();
auto forumPageCountFuture = QtConcurrent::run(std::bind(parsePageCountAsync, urlStr));
m_forumPageCountWatcher.setFuture(forumPageCountFuture);
}
namespace {
// NOTE: QtConcurrent require to return collection; return result code will be much more straightforward to reader
BankiRuForum::UserPosts parsePageAsync(QByteArray rawHtmlData, int& pageCount, ResultCode& errorCode)
{
BankiRuForum::UserPosts result;
errorCode = ResultCode::Ok;
// 2) Parse the page HTML to get the page number
BankiRuForum::ForumPageParser fpp;
errorCode = fpp.getPageCount(rawHtmlData, pageCount);
if (errorCode != ResultCode::Ok)
{
Q_ASSERT(0);
return result;
}
// 3) Parse the page HTML to get the page user posts
errorCode = fpp.getPagePosts(rawHtmlData, result);
if (errorCode != ResultCode::Ok)
{
Q_ASSERT(0);
return result;
}
return result;
}
}
void ForumReader::startPageParseAsync(QString urlStr, int pageNo)
{
dumpFutureObj(m_forumPageParserWatcher.future(), "m_forumPageParserWatcher");
// Cleanup
m_pagePosts.clear();
// FIXME: implement updatePageNumber() method and call it here
// m_pageCount = 0;
m_pageNo = pageNo;
m_downloader.startDownloadAsync(urlStr);
// FIXME: a better way? server don't return Content-Length header;
// a HTML page size is unknown, and the only way to get it - download the entire page;
// however we know forum HTML page average size - it is around 400 Kb
emit pageContentParseProgressRange(0, 400000);
}
void ForumReader::onForumPageCountParsed()
{
dumpFutureObj(m_forumPageCountWatcher.future(), "m_forumPageCountWatcher");
int pageCount = m_forumPageCountWatcher.result();
Q_ASSERT(pageCount > 0);
m_pageCount = pageCount;
emit pageCountParsed(pageCount);
}
void ForumReader::onForumPageCountParsingCanceled()
{
Q_ASSERT_X(0, Q_FUNC_INFO, "QtConcurrent::run result cannot be canceled");
}
void ForumReader::onForumPageDownloadProgress(qint64 bytesReceived, qint64 bytesTotal)
{
// qDebug() << Q_FUNC_INFO << bytesReceived << "/" << bytesTotal;
// NOTE: currently banki.ru server don't return Content-Length header
Q_ASSERT(bytesTotal <= 0);
// NOTE: HTML page size should not exceed 2^32 bytes, i hope :)
emit pageContentParseProgress((int)bytesReceived);
}
void ForumReader::onForumPageDownloaded()
{
m_pageData = m_downloader.downloadedData();
Q_ASSERT(!m_pageData.isEmpty());
// Wait for previous operation finish (if any)
// NOTE: QtConcurrent::run() return future that cannot be canceled
//m_forumPageParserWatcher.cancel();
m_forumPageParserWatcher.waitForFinished();
auto forumPageParseFuture = QtConcurrent::run(
std::bind(parsePageAsync, m_pageData, std::ref(m_pageCount), std::ref(m_lastError)));
m_forumPageParserWatcher.setFuture(forumPageParseFuture);
}
void ForumReader::onForumPageDownloadFailed(ResultCode code)
{
// FIXME: implement
Q_UNUSED(code);
}
void ForumReader::onForumPageParsed()
{
dumpFutureObj(m_forumPageParserWatcher.future(), "m_forumPageParserWatcher");
m_pagePosts = m_forumPageParserWatcher.result();
emit pageContentParsed(m_pageNo);
}
void ForumReader::onForumPageParsingCanceled()
{
Q_ASSERT_X(0, Q_FUNC_INFO, "QFuture returned by QtConcurrent::run() cannot be canceled");
}
// ----------------------------------------------------------------------------------------------------------------------------------------
int ForumReader::pageCount() const
{
return m_pageCount;
}
int ForumReader::postCount() const
{
return m_pagePosts.size();
}
QString ForumReader::postAuthorQml(int index) const
{
Q_ASSERT(index >= 0 && index < m_pagePosts.size());
return m_pagePosts[index].first.getQmlString(qrand());
}
int ForumReader::postAvatarMaxWidth() const
{
int maxWidth = 100;
for(int i = 0; i < m_pagePosts.size(); ++i)
{
if (m_pagePosts[i].first.m_userAvatar.isNull()) continue;
int width = m_pagePosts[i].first.m_userAvatar->m_width;
if(width > maxWidth) maxWidth = width;
}
return maxWidth;
}
QDateTime ForumReader::postDateTime(int index) const
{
Q_ASSERT(index >= 0 && index < m_pagePosts.size());
return m_pagePosts[index].second.m_date;
}
QString ForumReader::postText(int index) const
{
Q_ASSERT(index >= 0 && index < m_pagePosts.size());
if (m_pagePosts[index].second.m_data.empty()) return QString();
return m_pagePosts[index].second.getQmlString(qrand());
}
QString ForumReader::postLastEdit(int index) const
{
Q_ASSERT(index >= 0 && index < m_pagePosts.size());
return m_pagePosts[index].second.m_lastEdit;
}
int ForumReader::postLikeCount(int index) const
{
Q_ASSERT(index >= 0 && index < m_pagePosts.size());
return m_pagePosts[index].second.m_likeCounter;
}
QString ForumReader::postAuthorSignature(int index) const
{
Q_ASSERT(index >= 0 && index < m_pagePosts.size());
return m_pagePosts[index].second.m_userSignature;
}
<|endoftext|> |
<commit_before>/*****************************************************************************
* Copyright 2013 - 2015 Yichao Yu <[email protected]> *
* *
* This program 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) version 3, or any later version accepted *
* by the membership of KDE e.V. (or its successor approved by the *
* membership of KDE e.V.), which shall act as a proxy defined in *
* Section 6 of version 3 of the license. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* 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, *
* see <http://www.gnu.org/licenses/>. *
*****************************************************************************/
#include "qtcurve_plugin.h"
#include "qtcurve.h"
#include "config-qt5.h"
#include <qtcurve-utils/qtprops.h>
#include <qtcurve-utils/x11shadow.h>
#include <qtcurve-utils/x11blur.h>
#include <QApplication>
#ifdef Qt5X11Extras_FOUND
# include <qtcurve-utils/x11base.h>
# include <QX11Info>
#endif
#ifdef QTC_QT5_ENABLE_QTQUICK2
# include <QQuickWindow>
# include <QQuickItem>
#endif
#include <QDebug>
#include <qtcurve-utils/log.h>
namespace QtCurve {
__attribute__((hot)) static void
polishQuickControl(QObject *obj)
{
#ifdef QTC_QT5_ENABLE_QTQUICK2
if (QQuickWindow *window = qobject_cast<QQuickWindow*>(obj)) {
// QtQuickControl support
// This is still VERY experimental.
// Need a lot more testing and refactoring.
if (Style *style = getStyle(qApp)) {
if (window->inherits("QQuickPopupWindow")) {
if (window->inherits("QQuickMenuPopupWindow")) {
window->setColor(QColor(0, 0, 0, 0));
}
qtcX11ShadowInstall(window->winId());
} else {
QColor color = window->color();
int opacity = style->options().bgndOpacity;
if (color.alpha() == 255 && opacity != 100) {
qreal opacityF = opacity / 100.0;
window->setColor(QColor::fromRgbF(color.redF() * opacityF,
color.greenF() * opacityF,
color.blueF() * opacityF,
opacityF));
qtcX11BlurTrigger(window->winId(), true, 0, nullptr);
}
}
}
} else if (QQuickItem *item = qobject_cast<QQuickItem*>(obj)) {
if (QQuickWindow *window = item->window()) {
if (getStyle(qApp)) {
window->setColor(QColor(0, 0, 0, 0));
qtcX11BlurTrigger(window->winId(), true, 0, nullptr);
}
}
}
#else
QTC_UNUSED(obj);
#endif
}
__attribute__((hot)) static bool
qtcEventCallback(void **cbdata)
{
QObject *receiver = (QObject*)cbdata[0];
QTC_RET_IF_FAIL(receiver, false);
QEvent *event = (QEvent*)cbdata[1];
if (qtcUnlikely(event->type() == QEvent::DynamicPropertyChange)) {
QDynamicPropertyChangeEvent *prop_event =
static_cast<QDynamicPropertyChangeEvent*>(event);
// eat the property change events from ourselves
if (prop_event->propertyName() == QTC_PROP_NAME) {
return true;
}
}
QWidget *widget = qtcToWidget(receiver);
if (qtcUnlikely(widget && !qtcGetWid(widget))) {
if (Style *style = getStyle(widget)) {
style->prePolish(widget);
}
} else if (widget && event->type() == QEvent::UpdateRequest) {
QtcQWidgetProps props(widget);
props->opacity = 100;
} else {
polishQuickControl(receiver);
}
return false;
}
static StylePlugin *firstPlInstance = nullptr;
static QList<Style*> *styleInstances = nullptr;
QStyle*
StylePlugin::create(const QString &key)
{
if (!firstPlInstance) {
firstPlInstance = this;
styleInstances = &m_styleInstances;
}
init();
Style *qtc;
if (key.toLower() == "qtcurve") {
qtc = new Style;
qtc->m_plugin = this;
// keep track of all style instances we allocate, for instance
// for KLineEdit widgets which apparently insist on overriding
// certain things (cf. KLineEditStyle). We want to be able to
// delete those instances as properly and as early as
// possible during the global destruction phase.
m_styleInstances << qtc;
} else {
qtc = nullptr;
}
return qtc;
}
void StylePlugin::unregisterCallback()
{
if (m_eventNotifyCallbackInstalled) {
qtcInfo("Unregistering the event notify callback (for plugin %p)\n", this);
QInternal::unregisterCallback(QInternal::EventNotifyCallback,
qtcEventCallback);
m_eventNotifyCallbackInstalled = false;
}
}
StylePlugin::~StylePlugin()
{
qtcInfo("Deleting QtCurve plugin (%p)\n", this);
if (!m_styleInstances.isEmpty()) {
qtcWarn("there remain(s) %d Style instance(s)\n", m_styleInstances.count());
foreach (Style *that, m_styleInstances) {
// don't let ~Style() touch m_styleInstances from here.
that->m_plugin = nullptr;
// each instance should already have disconnected from the D-Bus
// and disconnected from receiving select signals.
delete that;
}
m_styleInstances.clear();
}
if (firstPlInstance == this) {
firstPlInstance = nullptr;
styleInstances = nullptr;
}
}
void
StylePlugin::init()
{
std::call_once(m_ref_flag, [this] {
QInternal::registerCallback(QInternal::EventNotifyCallback,
qtcEventCallback);
m_eventNotifyCallbackInstalled = true;
if (QCoreApplication::instance()) {
connect(QCoreApplication::instance(), &QCoreApplication::aboutToQuit, this, &StylePlugin::unregisterCallback);
}
#ifdef QTC_QT5_ENABLE_QTQUICK2
QQuickWindow::setDefaultAlphaBuffer(true);
#endif
#ifdef Qt5X11Extras_FOUND
if (qApp->platformName() == "xcb") {
qtcX11InitXcb(QX11Info::connection(), QX11Info::appScreen());
}
#endif
});
}
__attribute__((constructor)) int atLibOpen()
{
qtcDebug("Opening QtCurve\n");
return 0;
}
__attribute__((destructor)) int atLibClose()
{
qtcInfo("Closing QtCurve\n");
if (firstPlInstance) {
qtcInfo("Plugin instance %p still open with %d open Style instance(s)\n",
firstPlInstance, styleInstances->count());
}
return 0;
}
}
<commit_msg>Don't delete existing style instances from the plugin dtor if parented.<commit_after>/*****************************************************************************
* Copyright 2013 - 2015 Yichao Yu <[email protected]> *
* *
* This program 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) version 3, or any later version accepted *
* by the membership of KDE e.V. (or its successor approved by the *
* membership of KDE e.V.), which shall act as a proxy defined in *
* Section 6 of version 3 of the license. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* 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, *
* see <http://www.gnu.org/licenses/>. *
*****************************************************************************/
#include "qtcurve_plugin.h"
#include "qtcurve.h"
#include "config-qt5.h"
#include <qtcurve-utils/qtprops.h>
#include <qtcurve-utils/x11shadow.h>
#include <qtcurve-utils/x11blur.h>
#include <QApplication>
#ifdef Qt5X11Extras_FOUND
# include <qtcurve-utils/x11base.h>
# include <QX11Info>
#endif
#ifdef QTC_QT5_ENABLE_QTQUICK2
# include <QQuickWindow>
# include <QQuickItem>
#endif
#include <QDebug>
#include <qtcurve-utils/log.h>
namespace QtCurve {
__attribute__((hot)) static void
polishQuickControl(QObject *obj)
{
#ifdef QTC_QT5_ENABLE_QTQUICK2
if (QQuickWindow *window = qobject_cast<QQuickWindow*>(obj)) {
// QtQuickControl support
// This is still VERY experimental.
// Need a lot more testing and refactoring.
if (Style *style = getStyle(qApp)) {
if (window->inherits("QQuickPopupWindow")) {
if (window->inherits("QQuickMenuPopupWindow")) {
window->setColor(QColor(0, 0, 0, 0));
}
qtcX11ShadowInstall(window->winId());
} else {
QColor color = window->color();
int opacity = style->options().bgndOpacity;
if (color.alpha() == 255 && opacity != 100) {
qreal opacityF = opacity / 100.0;
window->setColor(QColor::fromRgbF(color.redF() * opacityF,
color.greenF() * opacityF,
color.blueF() * opacityF,
opacityF));
qtcX11BlurTrigger(window->winId(), true, 0, nullptr);
}
}
}
} else if (QQuickItem *item = qobject_cast<QQuickItem*>(obj)) {
if (QQuickWindow *window = item->window()) {
if (getStyle(qApp)) {
window->setColor(QColor(0, 0, 0, 0));
qtcX11BlurTrigger(window->winId(), true, 0, nullptr);
}
}
}
#else
QTC_UNUSED(obj);
#endif
}
__attribute__((hot)) static bool
qtcEventCallback(void **cbdata)
{
QObject *receiver = (QObject*)cbdata[0];
QTC_RET_IF_FAIL(receiver, false);
QEvent *event = (QEvent*)cbdata[1];
if (qtcUnlikely(event->type() == QEvent::DynamicPropertyChange)) {
QDynamicPropertyChangeEvent *prop_event =
static_cast<QDynamicPropertyChangeEvent*>(event);
// eat the property change events from ourselves
if (prop_event->propertyName() == QTC_PROP_NAME) {
return true;
}
}
QWidget *widget = qtcToWidget(receiver);
if (qtcUnlikely(widget && !qtcGetWid(widget))) {
if (Style *style = getStyle(widget)) {
style->prePolish(widget);
}
} else if (widget && event->type() == QEvent::UpdateRequest) {
QtcQWidgetProps props(widget);
props->opacity = 100;
} else {
polishQuickControl(receiver);
}
return false;
}
static StylePlugin *firstPlInstance = nullptr;
static QList<Style*> *styleInstances = nullptr;
QStyle*
StylePlugin::create(const QString &key)
{
if (!firstPlInstance) {
firstPlInstance = this;
styleInstances = &m_styleInstances;
}
init();
Style *qtc;
if (key.toLower() == "qtcurve") {
qtc = new Style;
qtc->m_plugin = this;
// keep track of all style instances we allocate, for instance
// for KLineEdit widgets which apparently insist on overriding
// certain things (cf. KLineEditStyle). We want to be able to
// delete those instances as properly and as early as
// possible during the global destruction phase.
m_styleInstances << qtc;
} else {
qtc = nullptr;
}
return qtc;
}
void StylePlugin::unregisterCallback()
{
if (m_eventNotifyCallbackInstalled) {
qtcInfo("Unregistering the event notify callback (for plugin %p)\n", this);
QInternal::unregisterCallback(QInternal::EventNotifyCallback,
qtcEventCallback);
m_eventNotifyCallbackInstalled = false;
}
}
StylePlugin::~StylePlugin()
{
qtcInfo("Deleting QtCurve plugin (%p)\n", this);
if (!m_styleInstances.isEmpty()) {
qtcWarn("there remain(s) %d Style instance(s)\n", m_styleInstances.count());
foreach (Style *that, m_styleInstances) {
// don't let ~Style() touch m_styleInstances from here.
that->m_plugin = nullptr;
// each instance should already have disconnected from the D-Bus
// and disconnected from receiving select signals.
if (!that->parent()) {
delete that;
} else {
qtcDebug("Ignoring Style instance %p with parent %p\n", that, that->parent());
}
}
m_styleInstances.clear();
}
if (firstPlInstance == this) {
firstPlInstance = nullptr;
styleInstances = nullptr;
}
}
void
StylePlugin::init()
{
std::call_once(m_ref_flag, [this] {
QInternal::registerCallback(QInternal::EventNotifyCallback,
qtcEventCallback);
m_eventNotifyCallbackInstalled = true;
if (QCoreApplication::instance()) {
connect(QCoreApplication::instance(), &QCoreApplication::aboutToQuit, this, &StylePlugin::unregisterCallback);
}
#ifdef QTC_QT5_ENABLE_QTQUICK2
QQuickWindow::setDefaultAlphaBuffer(true);
#endif
#ifdef Qt5X11Extras_FOUND
if (qApp->platformName() == "xcb") {
qtcX11InitXcb(QX11Info::connection(), QX11Info::appScreen());
}
#endif
});
}
__attribute__((constructor)) int atLibOpen()
{
qtcDebug("Opening QtCurve\n");
return 0;
}
__attribute__((destructor)) int atLibClose()
{
qtcInfo("Closing QtCurve\n");
if (firstPlInstance) {
qtcInfo("Plugin instance %p still open with %d open Style instance(s)\n",
firstPlInstance, styleInstances->count());
}
return 0;
}
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: BoolSPts.cc
Language: C++
Date: $Date$
Version: $Revision$
This file is part of the Visualization Toolkit. No part of this file
or its contents may be copied, reproduced or altered in any way
without the express written consent of the authors.
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994
=========================================================================*/
#include "BoolSPts.hh"
// Description:
// Construct with sample resolution of (50,50,50) and automatic
// computation of sample bounds. Initial boolean operation is union.
vtkBooleanStructuredPoints::vtkBooleanStructuredPoints()
{
this->SampleDimensions[0] = 50;
this->SampleDimensions[1] = 50;
this->SampleDimensions[2] = 50;
this->ModelBounds[0] = 0.0;
this->ModelBounds[1] = 0.0;
this->ModelBounds[2] = 0.0;
this->ModelBounds[3] = 0.0;
this->ModelBounds[4] = 0.0;
this->ModelBounds[5] = 0.0;
this->OperationType = UNION_OPERATOR;
// this->Operator = this->Union;
}
vtkBooleanStructuredPoints::~vtkBooleanStructuredPoints()
{
}
unsigned long int vtkBooleanStructuredPoints::GetMTime()
{
unsigned long dtime = this->vtkStructuredPoints::GetMTime();
unsigned long ftime = this->vtkFilter::_GetMTime();
return (dtime > ftime ? dtime : ftime);
}
// Description:
// Add another structured point set to the list of objects to boolean.
void vtkBooleanStructuredPoints::AddInput(vtkStructuredPoints *sp)
{
if ( ! this->InputList.IsItemPresent(sp) )
{
this->Modified();
this->InputList.AddItem(sp);
}
}
// Description:
// Remove an object from the list of objects to boolean.
void vtkBooleanStructuredPoints::RemoveInput(vtkStructuredPoints *sp)
{
if ( this->InputList.IsItemPresent(sp) )
{
this->Modified();
this->InputList.RemoveItem(sp);
}
}
void vtkBooleanStructuredPoints::Update()
{
unsigned long int mtime, dsMtime;
vtkDataSet *ds;
// make sure input is available
if ( this->InputList.GetNumberOfItems() < 1 ) return;
// prevent chasing our tail
if (this->Updating) return;
this->Updating = 1;
for (mtime=0, this->InputList.InitTraversal(); ds = this->InputList.GetNextItem(); )
{
ds->Update();
dsMtime = ds->GetMTime();
if ( dsMtime > mtime ) mtime = dsMtime;
}
this->Updating = 0;
if (mtime > this->GetMTime() || this->GetMTime() > this->ExecuteTime ||
this->GetDataReleased() )
{
if ( this->StartMethod ) (*this->StartMethod)(this->StartMethodArg);
this->Execute();
this->ExecuteTime.Modified();
this->SetDataReleased(0);
if ( this->EndMethod ) (*this->EndMethod)(this->EndMethodArg);
}
for (this->InputList.InitTraversal(); ds = this->InputList.GetNextItem(); )
if ( ds->ShouldIReleaseData() ) ds->ReleaseData();
}
// Initialize object prior to performing Boolean operations
void vtkBooleanStructuredPoints::InitializeBoolean()
{
vtkScalars *inScalars=NULL;
vtkScalars *newScalars;
vtkStructuredPoints *sp;
float *bounds;
int numPts;
int i, j;
this->Initialize();
this->SetDimensions(this->SampleDimensions);
numPts = this->GetNumberOfPoints();
// If ModelBounds unset, use input, else punt
if ( this->ModelBounds[0] >= this->ModelBounds[1] ||
this->ModelBounds[2] >= this->ModelBounds[3] ||
this->ModelBounds[4] >= this->ModelBounds[5] )
{
if ( this->InputList.GetNumberOfItems() > 0 )
{
this->ModelBounds[0] = this->ModelBounds[2] = this->ModelBounds[4] = LARGE_FLOAT;
this->ModelBounds[1] = this->ModelBounds[3] = this->ModelBounds[5] = -LARGE_FLOAT;
for ( this->InputList.InitTraversal(); sp = this->InputList.GetNextItem(); )
{
bounds = sp->GetBounds();
for (j=0; j < 3; j++)
{
if ( bounds[2*j] < this->ModelBounds[2*j] )
this->ModelBounds[2*j] = bounds[2*j];
if ( bounds[2*j+1] > this->ModelBounds[2*j+1] )
this->ModelBounds[2*j+1] = bounds[2*j+1];
}
}
}
else
{
this->ModelBounds[0] = this->ModelBounds[2] = this->ModelBounds[4] = 0.0;
this->ModelBounds[1] = this->ModelBounds[3] = this->ModelBounds[5] = 1000.0;
}
}
// Update origin and aspect ratio
for (i=0; i<3; i++)
{
this->Origin[i] = this->ModelBounds[2*i];
this->AspectRatio[i] = (this->ModelBounds[2*i+1] - this->ModelBounds[2*i])
/ (this->SampleDimensions[i] - 1);
}
// Create output scalar (same type as input)
if ( this->InputList.GetNumberOfItems() > 0 )
{
this->InputList.InitTraversal(); sp = this->InputList.GetNextItem();
inScalars = sp->GetPointData()->GetScalars();
}
if ( inScalars != NULL )
{
newScalars = inScalars->MakeObject(numPts); //copy
}
else
{
newScalars = new vtkFloatScalars(numPts);
}
this->PointData.SetScalars(newScalars);
newScalars->Delete();
}
// Perform Boolean operations on input volumes
void vtkBooleanStructuredPoints::Execute()
{
vtkStructuredPoints *sp;
this->InitializeBoolean();
for ( this->InputList.InitTraversal(); sp = this->InputList.GetNextItem(); )
{
this->Append(sp);
}
}
// Description:
// Perform Boolean operations by appending to current output data.
void vtkBooleanStructuredPoints::Append(vtkStructuredPoints *sp)
{
vtkScalars *currentScalars, *inScalars;
float *in_bounds;
float *dest_bounds;
int i,j,k;
float *in_aspect;
float in_x,in_y,in_z;
int in_i,in_j,in_k;
int in_kval,in_jval;
int dest_kval,dest_jval;
int *in_dimensions;
if ( (currentScalars = this->PointData.GetScalars()) == NULL )
{
this->InitializeBoolean();
currentScalars = this->PointData.GetScalars();
}
inScalars = sp->GetPointData()->GetScalars();
in_bounds = sp->GetBounds();
dest_bounds = this->GetModelBounds();
in_aspect = sp->GetAspectRatio();
in_dimensions = sp->GetDimensions();
// now perform operation on data
switch (this->OperationType)
{
case UNION_OPERATOR :
{
// for each cell
for (k = 0; k < this->SampleDimensions[2]; k++)
{
in_z = dest_bounds[4] + k*this->AspectRatio[2];
in_k = int ((float)(in_z - in_bounds[4])/in_aspect[2]);
if ((in_k >= 0)&&(in_k < in_dimensions[2]))
{
in_kval = in_k*in_dimensions[0]*in_dimensions[1];
dest_kval = k*this->SampleDimensions[0]*this->SampleDimensions[1];
for (j = 0; j < this->SampleDimensions[1]; j++)
{
in_y = dest_bounds[2] + j*this->AspectRatio[1];
in_j = (int) ((float)(in_y - in_bounds[2])/in_aspect[1]);
if ((in_j >= 0)&&(in_j < in_dimensions[1]))
{
in_jval = in_j*in_dimensions[0];
dest_jval = j*this->SampleDimensions[0];
for (i = 0; i < this->SampleDimensions[0]; i++)
{
in_x = dest_bounds[0] + i*this->AspectRatio[0];
in_i = (int) ((float)(in_x - in_bounds[0])/in_aspect[0]);
if ((in_i >= 0)&&(in_i < in_dimensions[0]))
{
if (inScalars->GetScalar(in_kval+in_jval+in_i))
{
currentScalars->SetScalar(dest_kval + dest_jval+i,1);
}
}
}
}
}
}
}
}
break;
}
}
// Description:
// Set the i-j-k dimensions on which to perform boolean operation.
void vtkBooleanStructuredPoints::SetSampleDimensions(int i, int j, int k)
{
int dim[3];
dim[0] = i;
dim[1] = j;
dim[2] = k;
this->SetSampleDimensions(dim);
}
void vtkBooleanStructuredPoints::SetSampleDimensions(int dim[3])
{
int i;
vtkDebugMacro(<< " setting SampleDimensions to (" << dim[0] << "," << dim[1] << "," << dim[2] << ")");
if ( dim[0] != this->SampleDimensions[0] || dim[1] != SampleDimensions[1] ||
dim[2] != SampleDimensions[2] )
{
if ( dim[0]<0 || dim[1]<0 || dim[2]<0 )
{
vtkErrorMacro (<< "Bad Sample Dimensions, retaining previous values");
return;
}
for ( i=0; i<3; i++) this->SampleDimensions[i] = dim[i];
this->Modified();
}
}
// Description:
// Set the size of the volume oon which to perform the sampling.
void vtkBooleanStructuredPoints::SetModelBounds(float *bounds)
{
vtkBooleanStructuredPoints::SetModelBounds(bounds[0], bounds[1], bounds[2], bounds[3], bounds[4], bounds[5]);
}
void vtkBooleanStructuredPoints::SetModelBounds(float xmin, float xmax, float ymin, float ymax, float zmin, float zmax)
{
if (this->ModelBounds[0] != xmin || this->ModelBounds[1] != xmax ||
this->ModelBounds[2] != ymin || this->ModelBounds[3] != ymax ||
this->ModelBounds[4] != zmin || this->ModelBounds[5] != zmax )
{
float length;
this->Modified();
this->ModelBounds[0] = xmin;
this->ModelBounds[1] = xmax;
this->ModelBounds[2] = ymin;
this->ModelBounds[3] = ymax;
this->ModelBounds[4] = zmin;
this->ModelBounds[5] = zmax;
this->Origin[0] = xmin;
this->Origin[1] = ymin;
this->Origin[2] = zmin;
if ( (length = xmax - xmin) == 0.0 ) length = 1.0;
this->AspectRatio[0] = 1.0;
this->AspectRatio[1] = (ymax - ymin) / length;
this->AspectRatio[2] = (zmax - zmin) / length;
}
}
int vtkBooleanStructuredPoints::GetDataReleased()
{
return this->DataReleased;
}
void vtkBooleanStructuredPoints::SetDataReleased(int flag)
{
this->DataReleased = flag;
}
void vtkBooleanStructuredPoints::PrintSelf(ostream& os, vtkIndent indent)
{
vtkStructuredPoints::PrintSelf(os,indent);
vtkFilter::_PrintSelf(os,indent);
os << indent << "Input DataSets:\n";
this->InputList.PrintSelf(os,indent.GetNextIndent());
}
<commit_msg>ENH: Made variable names consistent.<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: BoolSPts.cc
Language: C++
Date: $Date$
Version: $Revision$
This file is part of the Visualization Toolkit. No part of this file
or its contents may be copied, reproduced or altered in any way
without the express written consent of the authors.
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994
=========================================================================*/
#include "BoolSPts.hh"
// Description:
// Construct with sample resolution of (50,50,50) and automatic
// computation of sample bounds. Initial boolean operation is union.
vtkBooleanStructuredPoints::vtkBooleanStructuredPoints()
{
this->SampleDimensions[0] = 50;
this->SampleDimensions[1] = 50;
this->SampleDimensions[2] = 50;
this->ModelBounds[0] = 0.0;
this->ModelBounds[1] = 0.0;
this->ModelBounds[2] = 0.0;
this->ModelBounds[3] = 0.0;
this->ModelBounds[4] = 0.0;
this->ModelBounds[5] = 0.0;
this->OperationType = UNION_OPERATOR;
// this->Operator = this->Union;
}
vtkBooleanStructuredPoints::~vtkBooleanStructuredPoints()
{
}
unsigned long int vtkBooleanStructuredPoints::GetMTime()
{
unsigned long dtime = this->vtkStructuredPoints::GetMTime();
unsigned long ftime = this->vtkFilter::_GetMTime();
return (dtime > ftime ? dtime : ftime);
}
// Description:
// Add another structured point set to the list of objects to boolean.
void vtkBooleanStructuredPoints::AddInput(vtkStructuredPoints *sp)
{
if ( ! this->InputList.IsItemPresent(sp) )
{
this->Modified();
this->InputList.AddItem(sp);
}
}
// Description:
// Remove an object from the list of objects to boolean.
void vtkBooleanStructuredPoints::RemoveInput(vtkStructuredPoints *sp)
{
if ( this->InputList.IsItemPresent(sp) )
{
this->Modified();
this->InputList.RemoveItem(sp);
}
}
void vtkBooleanStructuredPoints::Update()
{
unsigned long int mtime, dsMtime;
vtkDataSet *ds;
// make sure input is available
if ( this->InputList.GetNumberOfItems() < 1 ) return;
// prevent chasing our tail
if (this->Updating) return;
this->Updating = 1;
for (mtime=0, this->InputList.InitTraversal(); ds = this->InputList.GetNextItem(); )
{
ds->Update();
dsMtime = ds->GetMTime();
if ( dsMtime > mtime ) mtime = dsMtime;
}
this->Updating = 0;
if (mtime > this->GetMTime() || this->GetMTime() > this->ExecuteTime ||
this->GetDataReleased() )
{
if ( this->StartMethod ) (*this->StartMethod)(this->StartMethodArg);
this->Execute();
this->ExecuteTime.Modified();
this->SetDataReleased(0);
if ( this->EndMethod ) (*this->EndMethod)(this->EndMethodArg);
}
for (this->InputList.InitTraversal(); ds = this->InputList.GetNextItem(); )
if ( ds->ShouldIReleaseData() ) ds->ReleaseData();
}
// Initialize object prior to performing Boolean operations
void vtkBooleanStructuredPoints::InitializeBoolean()
{
vtkScalars *inScalars=NULL;
vtkScalars *newScalars;
vtkStructuredPoints *sp;
float *bounds;
int numPts;
int i, j;
this->Initialize();
this->SetDimensions(this->SampleDimensions);
numPts = this->GetNumberOfPoints();
// If ModelBounds unset, use input, else punt
if ( this->ModelBounds[0] >= this->ModelBounds[1] ||
this->ModelBounds[2] >= this->ModelBounds[3] ||
this->ModelBounds[4] >= this->ModelBounds[5] )
{
if ( this->InputList.GetNumberOfItems() > 0 )
{
this->ModelBounds[0] = this->ModelBounds[2] = this->ModelBounds[4] = LARGE_FLOAT;
this->ModelBounds[1] = this->ModelBounds[3] = this->ModelBounds[5] = -LARGE_FLOAT;
for ( this->InputList.InitTraversal(); sp = this->InputList.GetNextItem(); )
{
bounds = sp->GetBounds();
for (j=0; j < 3; j++)
{
if ( bounds[2*j] < this->ModelBounds[2*j] )
this->ModelBounds[2*j] = bounds[2*j];
if ( bounds[2*j+1] > this->ModelBounds[2*j+1] )
this->ModelBounds[2*j+1] = bounds[2*j+1];
}
}
}
else
{
this->ModelBounds[0] = this->ModelBounds[2] = this->ModelBounds[4] = 0.0;
this->ModelBounds[1] = this->ModelBounds[3] = this->ModelBounds[5] = 1000.0;
}
}
// Update origin and aspect ratio
for (i=0; i<3; i++)
{
this->Origin[i] = this->ModelBounds[2*i];
this->AspectRatio[i] = (this->ModelBounds[2*i+1] - this->ModelBounds[2*i])
/ (this->SampleDimensions[i] - 1);
}
// Create output scalar (same type as input)
if ( this->InputList.GetNumberOfItems() > 0 )
{
this->InputList.InitTraversal(); sp = this->InputList.GetNextItem();
inScalars = sp->GetPointData()->GetScalars();
}
if ( inScalars != NULL )
{
newScalars = inScalars->MakeObject(numPts); //copy
}
else
{
newScalars = new vtkFloatScalars(numPts);
}
this->PointData.SetScalars(newScalars);
newScalars->Delete();
}
// Perform Boolean operations on input volumes
void vtkBooleanStructuredPoints::Execute()
{
vtkStructuredPoints *sp;
this->InitializeBoolean();
for ( this->InputList.InitTraversal(); sp = this->InputList.GetNextItem(); )
{
this->Append(sp);
}
}
// Description:
// Perform Boolean operations by appending to current output data.
void vtkBooleanStructuredPoints::Append(vtkStructuredPoints *sp)
{
vtkScalars *currentScalars, *inScalars;
float *inBounds;
float *destBounds;
int i,j,k;
float *in_aspect;
float inX,inY,inZ;
int inI,inJ,inK;
int inKval,inJval;
int destKval,destJval;
int *inDimensions;
if ( (currentScalars = this->PointData.GetScalars()) == NULL )
{
this->InitializeBoolean();
currentScalars = this->PointData.GetScalars();
}
inScalars = sp->GetPointData()->GetScalars();
inBounds = sp->GetBounds();
destBounds = this->GetModelBounds();
in_aspect = sp->GetAspectRatio();
inDimensions = sp->GetDimensions();
// now perform operation on data
switch (this->OperationType)
{
case UNION_OPERATOR :
{
// for each cell
for (k = 0; k < this->SampleDimensions[2]; k++)
{
inZ = destBounds[4] + k*this->AspectRatio[2];
inK = int ((float)(inZ - inBounds[4])/in_aspect[2]);
if ((inK >= 0)&&(inK < inDimensions[2]))
{
inKval = inK*inDimensions[0]*inDimensions[1];
destKval = k*this->SampleDimensions[0]*this->SampleDimensions[1];
for (j = 0; j < this->SampleDimensions[1]; j++)
{
inY = destBounds[2] + j*this->AspectRatio[1];
inJ = (int) ((float)(inY - inBounds[2])/in_aspect[1]);
if ((inJ >= 0)&&(inJ < inDimensions[1]))
{
inJval = inJ*inDimensions[0];
destJval = j*this->SampleDimensions[0];
for (i = 0; i < this->SampleDimensions[0]; i++)
{
inX = destBounds[0] + i*this->AspectRatio[0];
inI = (int) ((float)(inX - inBounds[0])/in_aspect[0]);
if ((inI >= 0)&&(inI < inDimensions[0]))
{
if (inScalars->GetScalar(inKval+inJval+inI))
{
currentScalars->SetScalar(destKval + destJval+i,1);
}
}
}
}
}
}
}
}
break;
}
}
// Description:
// Set the i-j-k dimensions on which to perform boolean operation.
void vtkBooleanStructuredPoints::SetSampleDimensions(int i, int j, int k)
{
int dim[3];
dim[0] = i;
dim[1] = j;
dim[2] = k;
this->SetSampleDimensions(dim);
}
void vtkBooleanStructuredPoints::SetSampleDimensions(int dim[3])
{
int i;
vtkDebugMacro(<< " setting SampleDimensions to (" << dim[0] << "," << dim[1] << "," << dim[2] << ")");
if ( dim[0] != this->SampleDimensions[0] || dim[1] != SampleDimensions[1] ||
dim[2] != SampleDimensions[2] )
{
if ( dim[0]<0 || dim[1]<0 || dim[2]<0 )
{
vtkErrorMacro (<< "Bad Sample Dimensions, retaining previous values");
return;
}
for ( i=0; i<3; i++) this->SampleDimensions[i] = dim[i];
this->Modified();
}
}
// Description:
// Set the size of the volume on which to perform the sampling.
void vtkBooleanStructuredPoints::SetModelBounds(float *bounds)
{
vtkBooleanStructuredPoints::SetModelBounds(bounds[0], bounds[1], bounds[2], bounds[3], bounds[4], bounds[5]);
}
void vtkBooleanStructuredPoints::SetModelBounds(float xmin, float xmax, float ymin, float ymax, float zmin, float zmax)
{
if (this->ModelBounds[0] != xmin || this->ModelBounds[1] != xmax ||
this->ModelBounds[2] != ymin || this->ModelBounds[3] != ymax ||
this->ModelBounds[4] != zmin || this->ModelBounds[5] != zmax )
{
float length;
this->Modified();
this->ModelBounds[0] = xmin;
this->ModelBounds[1] = xmax;
this->ModelBounds[2] = ymin;
this->ModelBounds[3] = ymax;
this->ModelBounds[4] = zmin;
this->ModelBounds[5] = zmax;
this->Origin[0] = xmin;
this->Origin[1] = ymin;
this->Origin[2] = zmin;
if ( (length = xmax - xmin) == 0.0 ) length = 1.0;
this->AspectRatio[0] = 1.0;
this->AspectRatio[1] = (ymax - ymin) / length;
this->AspectRatio[2] = (zmax - zmin) / length;
}
}
int vtkBooleanStructuredPoints::GetDataReleased()
{
return this->DataReleased;
}
void vtkBooleanStructuredPoints::SetDataReleased(int flag)
{
this->DataReleased = flag;
}
void vtkBooleanStructuredPoints::PrintSelf(ostream& os, vtkIndent indent)
{
vtkStructuredPoints::PrintSelf(os,indent);
vtkFilter::_PrintSelf(os,indent);
os << indent << "Input DataSets:\n";
this->InputList.PrintSelf(os,indent.GetNextIndent());
}
<|endoftext|> |
<commit_before>/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/common_runtime/immutable_executor_state.h"
#include "absl/memory/memory.h"
#include "tensorflow/core/framework/function.h"
#include "tensorflow/core/framework/metrics.h"
#include "tensorflow/core/framework/node_def_util.h"
#include "tensorflow/core/graph/edgeset.h"
#include "tensorflow/core/graph/graph.h"
#include "tensorflow/core/graph/graph_node_util.h"
#include "tensorflow/core/platform/errors.h"
#include "tensorflow/core/platform/logging.h"
namespace tensorflow {
namespace {
bool IsInitializationOp(const Node* node) {
return node->op_def().allows_uninitialized_input();
}
} // namespace
ImmutableExecutorState::~ImmutableExecutorState() {
for (int32_t i = 0; i < gview_.num_nodes(); i++) {
NodeItem* item = gview_.node(i);
if (item != nullptr) {
params_.delete_kernel(item->kernel);
}
}
}
namespace {
void GetMaxPendingCounts(const Node* n, size_t* max_pending,
size_t* max_dead_count) {
const size_t num_in_edges = n->in_edges().size();
size_t initial_count;
if (IsMerge(n)) {
// merge waits all control inputs so we initialize the pending
// count to be the number of control edges.
int32_t num_control_edges = 0;
for (const Edge* edge : n->in_edges()) {
if (edge->IsControlEdge()) {
num_control_edges++;
}
}
// Use bit 0 to indicate if we are waiting for a ready live data input.
initial_count = 1 + (num_control_edges << 1);
} else {
initial_count = num_in_edges;
}
*max_pending = initial_count;
*max_dead_count = num_in_edges;
}
} // namespace
ImmutableExecutorState::FrameInfo* ImmutableExecutorState::EnsureFrameInfo(
const string& fname) {
auto iter = frame_info_.find(fname);
if (iter != frame_info_.end()) {
return iter->second.get();
} else {
auto frame_info = absl::make_unique<FrameInfo>(fname);
absl::string_view fname_view = frame_info->name;
auto emplace_result =
frame_info_.emplace(fname_view, std::move(frame_info));
return emplace_result.first->second.get();
}
}
Status ImmutableExecutorState::Initialize(const Graph& graph) {
TF_RETURN_IF_ERROR(gview_.Initialize(&graph));
// Build the information about frames in this subgraph.
ControlFlowInfo cf_info;
TF_RETURN_IF_ERROR(BuildControlFlowInfo(&graph, &cf_info));
for (auto& it : cf_info.unique_frame_names) {
EnsureFrameInfo(it)->nodes =
absl::make_unique<std::vector<const NodeItem*>>();
}
root_frame_info_ = frame_info_[""].get();
pending_ids_.resize(gview_.num_nodes());
// Preprocess every node in the graph to create an instance of op
// kernel for each node.
requires_control_flow_ = false;
for (const Node* n : graph.nodes()) {
if (IsSink(n)) continue;
if (IsSwitch(n) || IsMerge(n) || IsEnter(n) || IsExit(n)) {
requires_control_flow_ = true;
} else if (IsRecv(n)) {
// A Recv node from a different device may produce dead tensors from
// non-local control-flow nodes.
//
// TODO(mrry): Track whether control flow was present in the
// pre-partitioned graph, and enable the caller (e.g.
// `DirectSession`) to relax this constraint.
string send_device;
string recv_device;
TF_RETURN_IF_ERROR(GetNodeAttr(n->attrs(), "send_device", &send_device));
TF_RETURN_IF_ERROR(GetNodeAttr(n->attrs(), "recv_device", &recv_device));
if (send_device != recv_device) {
requires_control_flow_ = true;
}
}
const int id = n->id();
const string& frame_name = cf_info.frame_names[id];
FrameInfo* frame_info = EnsureFrameInfo(frame_name);
NodeItem* item = gview_.node(id);
item->node_id = id;
item->input_start = frame_info->total_inputs;
frame_info->total_inputs += n->num_inputs();
Status s = params_.create_kernel(n->properties(), &item->kernel);
if (!s.ok()) {
item->kernel = nullptr;
s = AttachDef(s, *n);
return s;
}
CHECK(item->kernel);
item->kernel_is_async = (item->kernel->AsAsync() != nullptr);
item->is_merge = IsMerge(n);
item->is_any_consumer_merge_or_control_trigger = false;
for (const Node* consumer : n->out_nodes()) {
if (IsMerge(consumer) || IsControlTrigger(consumer)) {
item->is_any_consumer_merge_or_control_trigger = true;
break;
}
}
const Tensor* const_tensor = item->kernel->const_tensor();
if (const_tensor) {
// Hold onto a shallow copy of the constant tensor in `*this` so that the
// reference count does not drop to 1. This prevents the constant tensor
// from being forwarded, and its buffer reused.
const_tensors_.emplace_back(*const_tensor);
}
item->const_tensor = const_tensor;
item->is_noop = (item->kernel->type_string_view() == "NoOp");
item->is_enter = IsEnter(n);
if (item->is_enter) {
bool is_constant_enter;
TF_RETURN_IF_ERROR(
GetNodeAttr(n->attrs(), "is_constant", &is_constant_enter));
item->is_constant_enter = is_constant_enter;
string frame_name;
TF_RETURN_IF_ERROR(GetNodeAttr(n->attrs(), "frame_name", &frame_name));
FrameInfo* frame_info = frame_info_[frame_name].get();
int parallel_iterations;
TF_RETURN_IF_ERROR(
GetNodeAttr(n->attrs(), "parallel_iterations", ¶llel_iterations));
if (frame_info->parallel_iterations == -1) {
frame_info->parallel_iterations = parallel_iterations;
} else if (frame_info->parallel_iterations != parallel_iterations) {
LOG(WARNING) << "Loop frame \"" << frame_name
<< "\" had two different values for parallel_iterations: "
<< frame_info->parallel_iterations << " vs. "
<< parallel_iterations << ".";
}
if (enter_frame_info_.size() <= id) {
enter_frame_info_.resize(id + 1);
}
enter_frame_info_[id] = frame_info;
} else {
item->is_constant_enter = false;
}
item->is_exit = IsExit(n);
item->is_control_trigger = IsControlTrigger(n);
item->is_source = IsSource(n);
item->is_enter_exit_or_next_iter =
(IsEnter(n) || IsExit(n) || IsNextIteration(n));
item->is_transfer_node = IsTransferNode(n);
item->is_initialization_op = IsInitializationOp(n);
item->is_recv_or_switch = IsRecv(n) || IsSwitch(n);
item->is_next_iteration = IsNextIteration(n);
item->is_distributed_communication = IsDistributedCommunication(n);
// Compute the maximum values we'll store for this node in the
// pending counts data structure, and allocate a handle in
// that frame's pending counts data structure that has enough
// space to store these maximal count values.
size_t max_pending, max_dead;
GetMaxPendingCounts(n, &max_pending, &max_dead);
pending_ids_[id] =
frame_info->pending_counts_layout.CreateHandle(max_pending, max_dead);
// See if this node is a root node, and if so, add item to root_nodes_.
if (n->in_edges().empty()) {
root_nodes_.push_back(item);
}
// Initialize static information about the frames in the graph.
frame_info->nodes->push_back(item);
if (item->is_enter) {
string enter_name;
TF_RETURN_IF_ERROR(GetNodeAttr(n->attrs(), "frame_name", &enter_name));
EnsureFrameInfo(enter_name)->input_count++;
}
// Record information about whether each output of the op is used.
std::unique_ptr<bool[]> outputs_required(new bool[n->num_outputs()]);
std::fill(&outputs_required[0], &outputs_required[n->num_outputs()], false);
int32_t unused_outputs = n->num_outputs();
for (const Edge* e : n->out_edges()) {
if (IsSink(e->dst())) continue;
if (e->src_output() >= 0) {
if (!outputs_required[e->src_output()]) {
--unused_outputs;
outputs_required[e->src_output()] = true;
}
}
}
if (unused_outputs > 0) {
for (int i = 0; i < n->num_outputs(); ++i) {
if (!outputs_required[i]) {
metrics::RecordUnusedOutput(n->type_string());
}
}
item->outputs_required = std::move(outputs_required);
}
}
// Rewrite each `EdgeInfo::input_slot` member to refer directly to the input
// location.
for (const Node* n : graph.nodes()) {
if (IsSink(n)) continue;
const int id = n->id();
NodeItem* item = gview_.node(id);
for (EdgeInfo& e : item->mutable_output_edges()) {
const int dst_id = e.dst_id;
NodeItem* dst_item = gview_.node(dst_id);
e.input_slot += dst_item->input_start;
}
}
// Initialize PendingCounts only after pending_ids_[node.id] is initialized
// for all nodes.
InitializePending(&graph, cf_info);
return gview_.SetAllocAttrs(&graph, params_.device);
}
namespace {
// If a Node has been marked to use a ScopedAllocator x for output i, then
// sc_attr will contain the subsequence (i, x) at an even offset. This function
// extracts and transfers that ScopedAllocator id to alloc_attr. For now, we
// only allow one ScopedAllocator use per Node.
bool ExtractScopedAllocatorAttr(const std::vector<int>& sc_attr,
int output_index,
AllocatorAttributes* alloc_attr) {
DCHECK_LE(2, sc_attr.size());
for (int i = 0; i < sc_attr.size(); i += 2) {
if (sc_attr[i] == output_index) {
CHECK_EQ(alloc_attr->scope_id, 0);
alloc_attr->scope_id = sc_attr[i + 1];
return true;
}
}
return false;
}
} // namespace
Status ImmutableExecutorState::BuildControlFlowInfo(const Graph* g,
ControlFlowInfo* cf_info) {
const int num_nodes = g->num_node_ids();
cf_info->frame_names.resize(num_nodes);
std::vector<Node*> parent_nodes;
parent_nodes.resize(num_nodes);
std::vector<bool> visited;
visited.resize(num_nodes);
string frame_name;
std::deque<Node*> ready;
// Initialize with the root nodes.
for (Node* n : g->nodes()) {
if (n->in_edges().empty()) {
visited[n->id()] = true;
cf_info->unique_frame_names.insert(frame_name);
ready.push_back(n);
}
}
while (!ready.empty()) {
Node* curr_node = ready.front();
int curr_id = curr_node->id();
ready.pop_front();
Node* parent = nullptr;
if (IsEnter(curr_node)) {
// Enter a child frame.
TF_RETURN_IF_ERROR(
GetNodeAttr(curr_node->attrs(), "frame_name", &frame_name));
parent = curr_node;
} else if (IsExit(curr_node)) {
// Exit to the parent frame.
parent = parent_nodes[curr_id];
if (!parent) {
return errors::InvalidArgument(
"Invalid Exit op: Cannot find a corresponding Enter op.");
}
frame_name = cf_info->frame_names[parent->id()];
parent = parent_nodes[parent->id()];
} else {
parent = parent_nodes[curr_id];
frame_name = cf_info->frame_names[curr_id];
}
for (const Edge* out_edge : curr_node->out_edges()) {
Node* out = out_edge->dst();
if (IsSink(out)) continue;
const int out_id = out->id();
// Add to ready queue if not visited.
bool is_visited = visited[out_id];
if (!is_visited) {
ready.push_back(out);
visited[out_id] = true;
// Process the node 'out'.
cf_info->frame_names[out_id] = frame_name;
parent_nodes[out_id] = parent;
cf_info->unique_frame_names.insert(frame_name);
}
}
}
return Status::OK();
}
void ImmutableExecutorState::InitializePending(const Graph* graph,
const ControlFlowInfo& cf_info) {
for (auto& it : cf_info.unique_frame_names) {
FrameInfo* finfo = EnsureFrameInfo(it);
DCHECK_EQ(finfo->pending_counts.get(), nullptr);
finfo->pending_counts =
absl::make_unique<PendingCounts>(finfo->pending_counts_layout);
}
if (!requires_control_flow_) {
atomic_pending_counts_.reset(new std::atomic<int32>[gview_.num_nodes()]);
std::fill(atomic_pending_counts_.get(),
atomic_pending_counts_.get() + gview_.num_nodes(), 0);
}
for (const Node* n : graph->nodes()) {
if (IsSink(n)) continue;
const int id = n->id();
const string& name = cf_info.frame_names[id];
size_t max_pending, max_dead;
GetMaxPendingCounts(n, &max_pending, &max_dead);
auto& counts = EnsureFrameInfo(name)->pending_counts;
counts->set_initial_count(pending_ids_[id], max_pending);
if (!requires_control_flow_) {
atomic_pending_counts_[id] = max_pending;
}
}
}
} // namespace tensorflow
<commit_msg>Fix memory leak when a graph node is invalid.<commit_after>/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/common_runtime/immutable_executor_state.h"
#include "absl/memory/memory.h"
#include "tensorflow/core/framework/function.h"
#include "tensorflow/core/framework/metrics.h"
#include "tensorflow/core/framework/node_def_util.h"
#include "tensorflow/core/graph/edgeset.h"
#include "tensorflow/core/graph/graph.h"
#include "tensorflow/core/graph/graph_node_util.h"
#include "tensorflow/core/platform/errors.h"
#include "tensorflow/core/platform/logging.h"
namespace tensorflow {
namespace {
bool IsInitializationOp(const Node* node) {
return node->op_def().allows_uninitialized_input();
}
} // namespace
ImmutableExecutorState::~ImmutableExecutorState() {
for (int32_t i = 0; i < gview_.num_nodes(); i++) {
NodeItem* item = gview_.node(i);
if (item != nullptr) {
params_.delete_kernel(item->kernel);
}
}
}
namespace {
void GetMaxPendingCounts(const Node* n, size_t* max_pending,
size_t* max_dead_count) {
const size_t num_in_edges = n->in_edges().size();
size_t initial_count;
if (IsMerge(n)) {
// merge waits all control inputs so we initialize the pending
// count to be the number of control edges.
int32_t num_control_edges = 0;
for (const Edge* edge : n->in_edges()) {
if (edge->IsControlEdge()) {
num_control_edges++;
}
}
// Use bit 0 to indicate if we are waiting for a ready live data input.
initial_count = 1 + (num_control_edges << 1);
} else {
initial_count = num_in_edges;
}
*max_pending = initial_count;
*max_dead_count = num_in_edges;
}
} // namespace
ImmutableExecutorState::FrameInfo* ImmutableExecutorState::EnsureFrameInfo(
const string& fname) {
auto iter = frame_info_.find(fname);
if (iter != frame_info_.end()) {
return iter->second.get();
} else {
auto frame_info = absl::make_unique<FrameInfo>(fname);
absl::string_view fname_view = frame_info->name;
auto emplace_result =
frame_info_.emplace(fname_view, std::move(frame_info));
return emplace_result.first->second.get();
}
}
Status ImmutableExecutorState::Initialize(const Graph& graph) {
TF_RETURN_IF_ERROR(gview_.Initialize(&graph));
// Build the information about frames in this subgraph.
ControlFlowInfo cf_info;
TF_RETURN_IF_ERROR(BuildControlFlowInfo(&graph, &cf_info));
for (auto& it : cf_info.unique_frame_names) {
EnsureFrameInfo(it)->nodes =
absl::make_unique<std::vector<const NodeItem*>>();
}
root_frame_info_ = frame_info_[""].get();
pending_ids_.resize(gview_.num_nodes());
// Preprocess every node in the graph to create an instance of op
// kernel for each node.
requires_control_flow_ = false;
for (const Node* n : graph.nodes()) {
if (IsSink(n)) continue;
if (IsSwitch(n) || IsMerge(n) || IsEnter(n) || IsExit(n)) {
requires_control_flow_ = true;
} else if (IsRecv(n)) {
// A Recv node from a different device may produce dead tensors from
// non-local control-flow nodes.
//
// TODO(mrry): Track whether control flow was present in the
// pre-partitioned graph, and enable the caller (e.g.
// `DirectSession`) to relax this constraint.
string send_device;
string recv_device;
TF_RETURN_IF_ERROR(GetNodeAttr(n->attrs(), "send_device", &send_device));
TF_RETURN_IF_ERROR(GetNodeAttr(n->attrs(), "recv_device", &recv_device));
if (send_device != recv_device) {
requires_control_flow_ = true;
}
}
const int id = n->id();
const string& frame_name = cf_info.frame_names[id];
FrameInfo* frame_info = EnsureFrameInfo(frame_name);
NodeItem* item = gview_.node(id);
item->node_id = id;
item->input_start = frame_info->total_inputs;
frame_info->total_inputs += n->num_inputs();
Status s = params_.create_kernel(n->properties(), &item->kernel);
if (!s.ok()) {
params_.delete_kernel(item->kernel);
item->kernel = nullptr;
s = AttachDef(s, *n);
return s;
}
CHECK(item->kernel);
item->kernel_is_async = (item->kernel->AsAsync() != nullptr);
item->is_merge = IsMerge(n);
item->is_any_consumer_merge_or_control_trigger = false;
for (const Node* consumer : n->out_nodes()) {
if (IsMerge(consumer) || IsControlTrigger(consumer)) {
item->is_any_consumer_merge_or_control_trigger = true;
break;
}
}
const Tensor* const_tensor = item->kernel->const_tensor();
if (const_tensor) {
// Hold onto a shallow copy of the constant tensor in `*this` so that the
// reference count does not drop to 1. This prevents the constant tensor
// from being forwarded, and its buffer reused.
const_tensors_.emplace_back(*const_tensor);
}
item->const_tensor = const_tensor;
item->is_noop = (item->kernel->type_string_view() == "NoOp");
item->is_enter = IsEnter(n);
if (item->is_enter) {
bool is_constant_enter;
TF_RETURN_IF_ERROR(
GetNodeAttr(n->attrs(), "is_constant", &is_constant_enter));
item->is_constant_enter = is_constant_enter;
string frame_name;
TF_RETURN_IF_ERROR(GetNodeAttr(n->attrs(), "frame_name", &frame_name));
FrameInfo* frame_info = frame_info_[frame_name].get();
int parallel_iterations;
TF_RETURN_IF_ERROR(
GetNodeAttr(n->attrs(), "parallel_iterations", ¶llel_iterations));
if (frame_info->parallel_iterations == -1) {
frame_info->parallel_iterations = parallel_iterations;
} else if (frame_info->parallel_iterations != parallel_iterations) {
LOG(WARNING) << "Loop frame \"" << frame_name
<< "\" had two different values for parallel_iterations: "
<< frame_info->parallel_iterations << " vs. "
<< parallel_iterations << ".";
}
if (enter_frame_info_.size() <= id) {
enter_frame_info_.resize(id + 1);
}
enter_frame_info_[id] = frame_info;
} else {
item->is_constant_enter = false;
}
item->is_exit = IsExit(n);
item->is_control_trigger = IsControlTrigger(n);
item->is_source = IsSource(n);
item->is_enter_exit_or_next_iter =
(IsEnter(n) || IsExit(n) || IsNextIteration(n));
item->is_transfer_node = IsTransferNode(n);
item->is_initialization_op = IsInitializationOp(n);
item->is_recv_or_switch = IsRecv(n) || IsSwitch(n);
item->is_next_iteration = IsNextIteration(n);
item->is_distributed_communication = IsDistributedCommunication(n);
// Compute the maximum values we'll store for this node in the
// pending counts data structure, and allocate a handle in
// that frame's pending counts data structure that has enough
// space to store these maximal count values.
size_t max_pending, max_dead;
GetMaxPendingCounts(n, &max_pending, &max_dead);
pending_ids_[id] =
frame_info->pending_counts_layout.CreateHandle(max_pending, max_dead);
// See if this node is a root node, and if so, add item to root_nodes_.
if (n->in_edges().empty()) {
root_nodes_.push_back(item);
}
// Initialize static information about the frames in the graph.
frame_info->nodes->push_back(item);
if (item->is_enter) {
string enter_name;
TF_RETURN_IF_ERROR(GetNodeAttr(n->attrs(), "frame_name", &enter_name));
EnsureFrameInfo(enter_name)->input_count++;
}
// Record information about whether each output of the op is used.
std::unique_ptr<bool[]> outputs_required(new bool[n->num_outputs()]);
std::fill(&outputs_required[0], &outputs_required[n->num_outputs()], false);
int32_t unused_outputs = n->num_outputs();
for (const Edge* e : n->out_edges()) {
if (IsSink(e->dst())) continue;
if (e->src_output() >= 0) {
if (!outputs_required[e->src_output()]) {
--unused_outputs;
outputs_required[e->src_output()] = true;
}
}
}
if (unused_outputs > 0) {
for (int i = 0; i < n->num_outputs(); ++i) {
if (!outputs_required[i]) {
metrics::RecordUnusedOutput(n->type_string());
}
}
item->outputs_required = std::move(outputs_required);
}
}
// Rewrite each `EdgeInfo::input_slot` member to refer directly to the input
// location.
for (const Node* n : graph.nodes()) {
if (IsSink(n)) continue;
const int id = n->id();
NodeItem* item = gview_.node(id);
for (EdgeInfo& e : item->mutable_output_edges()) {
const int dst_id = e.dst_id;
NodeItem* dst_item = gview_.node(dst_id);
e.input_slot += dst_item->input_start;
}
}
// Initialize PendingCounts only after pending_ids_[node.id] is initialized
// for all nodes.
InitializePending(&graph, cf_info);
return gview_.SetAllocAttrs(&graph, params_.device);
}
namespace {
// If a Node has been marked to use a ScopedAllocator x for output i, then
// sc_attr will contain the subsequence (i, x) at an even offset. This function
// extracts and transfers that ScopedAllocator id to alloc_attr. For now, we
// only allow one ScopedAllocator use per Node.
bool ExtractScopedAllocatorAttr(const std::vector<int>& sc_attr,
int output_index,
AllocatorAttributes* alloc_attr) {
DCHECK_LE(2, sc_attr.size());
for (int i = 0; i < sc_attr.size(); i += 2) {
if (sc_attr[i] == output_index) {
CHECK_EQ(alloc_attr->scope_id, 0);
alloc_attr->scope_id = sc_attr[i + 1];
return true;
}
}
return false;
}
} // namespace
Status ImmutableExecutorState::BuildControlFlowInfo(const Graph* g,
ControlFlowInfo* cf_info) {
const int num_nodes = g->num_node_ids();
cf_info->frame_names.resize(num_nodes);
std::vector<Node*> parent_nodes;
parent_nodes.resize(num_nodes);
std::vector<bool> visited;
visited.resize(num_nodes);
string frame_name;
std::deque<Node*> ready;
// Initialize with the root nodes.
for (Node* n : g->nodes()) {
if (n->in_edges().empty()) {
visited[n->id()] = true;
cf_info->unique_frame_names.insert(frame_name);
ready.push_back(n);
}
}
while (!ready.empty()) {
Node* curr_node = ready.front();
int curr_id = curr_node->id();
ready.pop_front();
Node* parent = nullptr;
if (IsEnter(curr_node)) {
// Enter a child frame.
TF_RETURN_IF_ERROR(
GetNodeAttr(curr_node->attrs(), "frame_name", &frame_name));
parent = curr_node;
} else if (IsExit(curr_node)) {
// Exit to the parent frame.
parent = parent_nodes[curr_id];
if (!parent) {
return errors::InvalidArgument(
"Invalid Exit op: Cannot find a corresponding Enter op.");
}
frame_name = cf_info->frame_names[parent->id()];
parent = parent_nodes[parent->id()];
} else {
parent = parent_nodes[curr_id];
frame_name = cf_info->frame_names[curr_id];
}
for (const Edge* out_edge : curr_node->out_edges()) {
Node* out = out_edge->dst();
if (IsSink(out)) continue;
const int out_id = out->id();
// Add to ready queue if not visited.
bool is_visited = visited[out_id];
if (!is_visited) {
ready.push_back(out);
visited[out_id] = true;
// Process the node 'out'.
cf_info->frame_names[out_id] = frame_name;
parent_nodes[out_id] = parent;
cf_info->unique_frame_names.insert(frame_name);
}
}
}
return Status::OK();
}
void ImmutableExecutorState::InitializePending(const Graph* graph,
const ControlFlowInfo& cf_info) {
for (auto& it : cf_info.unique_frame_names) {
FrameInfo* finfo = EnsureFrameInfo(it);
DCHECK_EQ(finfo->pending_counts.get(), nullptr);
finfo->pending_counts =
absl::make_unique<PendingCounts>(finfo->pending_counts_layout);
}
if (!requires_control_flow_) {
atomic_pending_counts_.reset(new std::atomic<int32>[gview_.num_nodes()]);
std::fill(atomic_pending_counts_.get(),
atomic_pending_counts_.get() + gview_.num_nodes(), 0);
}
for (const Node* n : graph->nodes()) {
if (IsSink(n)) continue;
const int id = n->id();
const string& name = cf_info.frame_names[id];
size_t max_pending, max_dead;
GetMaxPendingCounts(n, &max_pending, &max_dead);
auto& counts = EnsureFrameInfo(name)->pending_counts;
counts->set_initial_count(pending_ids_[id], max_pending);
if (!requires_control_flow_) {
atomic_pending_counts_[id] = max_pending;
}
}
}
} // namespace tensorflow
<|endoftext|> |
<commit_before>/* Copyright 2016 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#if TENSORFLOW_USE_SYCL
#define EIGEN_USE_SYCL
#include "tensorflow/core/common_runtime/sycl/sycl_device_context.h"
#include "tensorflow/core/common_runtime/dma_helper.h"
#define EIGEN_USE_SYCL
#include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor"
namespace tensorflow {
void SYCLDeviceContext::CopyCPUTensorToDevice(const Tensor *cpu_tensor,
Device *device,
Tensor *device_tensor,
StatusCallback done) const {
const int64 total_bytes = cpu_tensor->TotalBytes();
if (total_bytes > 0) {
const void *src_ptr = DMAHelper::base(cpu_tensor);
void *dst_ptr = DMAHelper::base(device_tensor);
switch (cpu_tensor->dtype()) {
case DT_FLOAT:
device->eigen_sycl_device()->memcpyHostToDevice(
static_cast<float *>(dst_ptr), static_cast<const float *>(src_ptr),
total_bytes);
break;
case DT_DOUBLE:
device->eigen_sycl_device()->memcpyHostToDevice(
static_cast<double *>(dst_ptr), static_cast<const double *>(src_ptr),
total_bytes);
break;
case DT_INT32:
device->eigen_sycl_device()->memcpyHostToDevice(
static_cast<int32 *>(dst_ptr), static_cast<const int32 *>(src_ptr),
total_bytes);
break;
case DT_INT64:
device->eigen_sycl_device()->memcpyHostToDevice(
static_cast<int64 *>(dst_ptr), static_cast<const int64 *>(src_ptr),
total_bytes);
break;
case DT_HALF:
device->eigen_sycl_device()->memcpyHostToDevice(
static_cast<Eigen::half *>(dst_ptr),
static_cast<const Eigen::half *>(src_ptr), total_bytes);
break;
case DT_COMPLEX64:
device->eigen_sycl_device()->memcpyHostToDevice(
static_cast<std::complex<float> *>(dst_ptr),
static_cast<const std::complex<float> *>(src_ptr), total_bytes);
break;
case DT_COMPLEX128:
device->eigen_sycl_device()->memcpyHostToDevice(
static_cast<std::complex<double> *>(dst_ptr),
static_cast<const std::complex<double> *>(src_ptr), total_bytes);
break;
case DT_INT8:
device->eigen_sycl_device()->memcpyHostToDevice(
static_cast<int8 *>(dst_ptr), static_cast<const int8 *>(src_ptr),
total_bytes);
break;
case DT_INT16:
device->eigen_sycl_device()->memcpyHostToDevice(
static_cast<int16 *>(dst_ptr), static_cast<const int16 *>(src_ptr),
total_bytes);
break;
case DT_UINT8:
device->eigen_sycl_device()->memcpyHostToDevice(
static_cast<uint8 *>(dst_ptr), static_cast<const uint8 *>(src_ptr),
total_bytes);
break;
case DT_UINT16:
device->eigen_sycl_device()->memcpyHostToDevice(
static_cast<uint16 *>(dst_ptr), static_cast<const uint16 *>(src_ptr),
total_bytes);
break;
default:
assert(false && "unsupported type");
}
}
done(Status::OK());
}
void SYCLDeviceContext::CopyDeviceTensorToCPU(const Tensor *device_tensor,
StringPiece edge_name,
Device *device,
Tensor *cpu_tensor,
StatusCallback done) {
const int64 total_bytes = device_tensor->TotalBytes();
if (total_bytes > 0) {
device->eigen_sycl_device()->deallocate_all();
const void* src_ptr = DMAHelper::base(device_tensor);
void* dst_ptr = DMAHelper::base(cpu_tensor);
switch (device_tensor->dtype()) {
case DT_FLOAT:
device->eigen_sycl_device()->memcpyDeviceToHost(
static_cast<float *>(dst_ptr), static_cast<const float *>(src_ptr),
total_bytes);
break;
case DT_DOUBLE:
device->eigen_sycl_device()->memcpyDeviceToHost(
static_cast<double *>(dst_ptr), static_cast<const double *>(src_ptr),
total_bytes);
break;
case DT_INT32:
device->eigen_sycl_device()->memcpyDeviceToHost(
static_cast<int32 *>(dst_ptr), static_cast<const int32 *>(src_ptr),
total_bytes);
break;
case DT_INT64:
device->eigen_sycl_device()->memcpyDeviceToHost(
static_cast<int64 *>(dst_ptr), static_cast<const int64 *>(src_ptr),
total_bytes);
break;
case DT_HALF:
device->eigen_sycl_device()->memcpyDeviceToHost(
static_cast<Eigen::half *>(dst_ptr),
static_cast<const Eigen::half *>(src_ptr), total_bytes);
break;
case DT_COMPLEX64:
device->eigen_sycl_device()->memcpyDeviceToHost(
static_cast<std::complex<float> *>(dst_ptr),
static_cast<const std::complex<float> *>(src_ptr), total_bytes);
break;
case DT_COMPLEX128:
device->eigen_sycl_device()->memcpyDeviceToHost(
static_cast<std::complex<double> *>(dst_ptr),
static_cast<const std::complex<double> *>(src_ptr), total_bytes);
break;
case DT_INT8:
device->eigen_sycl_device()->memcpyDeviceToHost(
static_cast<int8 *>(dst_ptr), static_cast<const int8 *>(src_ptr),
total_bytes);
break;
case DT_INT16:
device->eigen_sycl_device()->memcpyDeviceToHost(
static_cast<int16 *>(dst_ptr), static_cast<const int16 *>(src_ptr),
total_bytes);
break;
case DT_UINT8:
device->eigen_sycl_device()->memcpyDeviceToHost(
static_cast<uint8 *>(dst_ptr), static_cast<const uint8 *>(src_ptr),
total_bytes);
break;
case DT_UINT16:
device->eigen_sycl_device()->memcpyDeviceToHost(
static_cast<uint16 *>(dst_ptr), static_cast<const uint16 *>(src_ptr),
total_bytes);
break;
default:
assert(false && "unsupported type");
}
}
done(Status::OK());
}
} // namespace tensorflow
#endif // TENSORFLOW_USE_SYCL
<commit_msg>Added support for boolean values on OpenCL devices<commit_after>/* Copyright 2016 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#if TENSORFLOW_USE_SYCL
#define EIGEN_USE_SYCL
#include "tensorflow/core/common_runtime/sycl/sycl_device_context.h"
#include "tensorflow/core/common_runtime/dma_helper.h"
#define EIGEN_USE_SYCL
#include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor"
namespace tensorflow {
void SYCLDeviceContext::CopyCPUTensorToDevice(const Tensor *cpu_tensor,
Device *device,
Tensor *device_tensor,
StatusCallback done) const {
const int64 total_bytes = cpu_tensor->TotalBytes();
if (total_bytes > 0) {
const void *src_ptr = DMAHelper::base(cpu_tensor);
void *dst_ptr = DMAHelper::base(device_tensor);
switch (cpu_tensor->dtype()) {
case DT_FLOAT:
device->eigen_sycl_device()->memcpyHostToDevice(
static_cast<float *>(dst_ptr), static_cast<const float *>(src_ptr),
total_bytes);
break;
case DT_DOUBLE:
device->eigen_sycl_device()->memcpyHostToDevice(
static_cast<double *>(dst_ptr), static_cast<const double *>(src_ptr),
total_bytes);
break;
case DT_INT32:
device->eigen_sycl_device()->memcpyHostToDevice(
static_cast<int32 *>(dst_ptr), static_cast<const int32 *>(src_ptr),
total_bytes);
break;
case DT_INT64:
device->eigen_sycl_device()->memcpyHostToDevice(
static_cast<int64 *>(dst_ptr), static_cast<const int64 *>(src_ptr),
total_bytes);
break;
case DT_HALF:
device->eigen_sycl_device()->memcpyHostToDevice(
static_cast<Eigen::half *>(dst_ptr),
static_cast<const Eigen::half *>(src_ptr), total_bytes);
break;
case DT_COMPLEX64:
device->eigen_sycl_device()->memcpyHostToDevice(
static_cast<std::complex<float> *>(dst_ptr),
static_cast<const std::complex<float> *>(src_ptr), total_bytes);
break;
case DT_COMPLEX128:
device->eigen_sycl_device()->memcpyHostToDevice(
static_cast<std::complex<double> *>(dst_ptr),
static_cast<const std::complex<double> *>(src_ptr), total_bytes);
break;
case DT_INT8:
device->eigen_sycl_device()->memcpyHostToDevice(
static_cast<int8 *>(dst_ptr), static_cast<const int8 *>(src_ptr),
total_bytes);
break;
case DT_INT16:
device->eigen_sycl_device()->memcpyHostToDevice(
static_cast<int16 *>(dst_ptr), static_cast<const int16 *>(src_ptr),
total_bytes);
break;
case DT_UINT8:
device->eigen_sycl_device()->memcpyHostToDevice(
static_cast<uint8 *>(dst_ptr), static_cast<const uint8 *>(src_ptr),
total_bytes);
break;
case DT_UINT16:
device->eigen_sycl_device()->memcpyHostToDevice(
static_cast<uint16 *>(dst_ptr), static_cast<const uint16 *>(src_ptr),
total_bytes);
break;
case DT_BOOL:
device->eigen_sycl_device()->memcpyHostToDevice(
static_cast<bool *>(dst_ptr), static_cast<const bool *>(src_ptr),
total_bytes);
break;
default:
assert(false && "unsupported type");
}
}
done(Status::OK());
}
void SYCLDeviceContext::CopyDeviceTensorToCPU(const Tensor *device_tensor,
StringPiece edge_name,
Device *device,
Tensor *cpu_tensor,
StatusCallback done) {
const int64 total_bytes = device_tensor->TotalBytes();
if (total_bytes > 0) {
device->eigen_sycl_device()->deallocate_all();
const void* src_ptr = DMAHelper::base(device_tensor);
void* dst_ptr = DMAHelper::base(cpu_tensor);
switch (device_tensor->dtype()) {
case DT_FLOAT:
device->eigen_sycl_device()->memcpyDeviceToHost(
static_cast<float *>(dst_ptr), static_cast<const float *>(src_ptr),
total_bytes);
break;
case DT_DOUBLE:
device->eigen_sycl_device()->memcpyDeviceToHost(
static_cast<double *>(dst_ptr), static_cast<const double *>(src_ptr),
total_bytes);
break;
case DT_INT32:
device->eigen_sycl_device()->memcpyDeviceToHost(
static_cast<int32 *>(dst_ptr), static_cast<const int32 *>(src_ptr),
total_bytes);
break;
case DT_INT64:
device->eigen_sycl_device()->memcpyDeviceToHost(
static_cast<int64 *>(dst_ptr), static_cast<const int64 *>(src_ptr),
total_bytes);
break;
case DT_HALF:
device->eigen_sycl_device()->memcpyDeviceToHost(
static_cast<Eigen::half *>(dst_ptr),
static_cast<const Eigen::half *>(src_ptr), total_bytes);
break;
case DT_COMPLEX64:
device->eigen_sycl_device()->memcpyDeviceToHost(
static_cast<std::complex<float> *>(dst_ptr),
static_cast<const std::complex<float> *>(src_ptr), total_bytes);
break;
case DT_COMPLEX128:
device->eigen_sycl_device()->memcpyDeviceToHost(
static_cast<std::complex<double> *>(dst_ptr),
static_cast<const std::complex<double> *>(src_ptr), total_bytes);
break;
case DT_INT8:
device->eigen_sycl_device()->memcpyDeviceToHost(
static_cast<int8 *>(dst_ptr), static_cast<const int8 *>(src_ptr),
total_bytes);
break;
case DT_INT16:
device->eigen_sycl_device()->memcpyDeviceToHost(
static_cast<int16 *>(dst_ptr), static_cast<const int16 *>(src_ptr),
total_bytes);
break;
case DT_UINT8:
device->eigen_sycl_device()->memcpyDeviceToHost(
static_cast<uint8 *>(dst_ptr), static_cast<const uint8 *>(src_ptr),
total_bytes);
break;
case DT_UINT16:
device->eigen_sycl_device()->memcpyDeviceToHost(
static_cast<uint16 *>(dst_ptr), static_cast<const uint16 *>(src_ptr),
total_bytes);
break;
case DT_BOOL:
device->eigen_sycl_device()->memcpyDeviceToHost(
static_cast<bool *>(dst_ptr), static_cast<const bool *>(src_ptr),
total_bytes);
break;
default:
assert(false && "unsupported type");
}
}
done(Status::OK());
}
} // namespace tensorflow
#endif // TENSORFLOW_USE_SYCL
<|endoftext|> |
<commit_before>/**
* @file CSIEnder.hh
* @author Paul Tagliamonte <[email protected]>
* @license MIT
* @created Tue Nov 8 14:20:09 UTC 2011
*/
#include <iostream>
#include "StateMachine.hh"
#include "CSIEnder.hh"
#include "CSIValue.hh"
void CSIEnder::feed( char c ) {
}
void CSIEnder::enter() {
for (
unsigned int i = 0;
i < ansi_state_CSIValue_parsed_ints.size();
++i
) {
std::cout << ansi_state_CSIValue_parsed_ints.at(i) << ", " << std::endl;
}
}
void CSIEnder::exit() {
}
CSIEnder ansi_state_CSIEnder;
<commit_msg>implementing the ender a bit<commit_after>/**
* @file CSIEnder.hh
* @author Paul Tagliamonte <[email protected]>
* @license MIT
* @created Tue Nov 8 14:20:09 UTC 2011
*/
#include <iostream>
#include "StateMachine.hh"
#include "Exception.hh"
#include "InvalidState.hh"
#include "CSIEnder.hh"
#include "CSIValue.hh"
#include "ANSIEntry.hh"
/* Some wikipedia background:
* The final byte is technically any character in the range 64 to 126
* (hex 0x40 to 0x7e, ASCII @ to ~), and may be modified extended with leading
* intermediate bytes in the range 32 to 47 (hex 0x20 to 0x2f). */
void CSIEnder::feed( char c ) {
/* XXX: Implement leading bytes correctly */
if ( c >= 64 && c <= 126 ) {
/* We've parsed well */
ansi_next_state = &ansi_state_ANSIEntry;
} else {
ansi_next_state = &ansi_state_InvalidState;
throw new InvalidSequence();
}
}
void CSIEnder::enter() {}
void CSIEnder::exit() {}
CSIEnder ansi_state_CSIEnder;
<|endoftext|> |
<commit_before>#include "Channel.hpp"
#include "Message.hpp"
#include "Network.hpp"
#include "PawnDispatcher.hpp"
#include "Logger.hpp"
#include "Guild.hpp"
#include "utils.hpp"
#include "fmt/format.h"
#undef SendMessage // Windows at its finest
Channel::Channel(ChannelId_t pawn_id, json const &data, GuildId_t guild_id) :
m_PawnId(pawn_id)
{
std::underlying_type<Type>::type type;
if (!utils::TryGetJsonValue(data, type, "type")
|| !utils::TryGetJsonValue(data, m_Id, "id"))
{
Logger::Get()->Log(LogLevel::ERROR,
"invalid JSON: expected \"type\" and \"id\" in \"{}\"", data.dump());
return;
}
m_Type = static_cast<Type>(type);
if (m_Type != Type::DM && m_Type != Type::GROUP_DM)
{
if (guild_id != 0)
{
m_GuildId = guild_id;
}
else
{
std::string guild_id_str;
if (utils::TryGetJsonValue(data, guild_id_str, "guild_id"))
{
Guild_t const &guild = GuildManager::Get()->FindGuildById(guild_id_str);
m_GuildId = guild->GetPawnId();
guild->AddChannel(pawn_id);
}
else
{
Logger::Get()->Log(LogLevel::ERROR,
"invalid JSON: expected \"guild_id\" in \"{}\"", data.dump());
}
}
Snowflake_t parent_id_str;
utils::TryGetJsonValue(data, m_Name, "name");
utils::TryGetJsonValue(data, m_Topic, "topic");
utils::TryGetJsonValue(data, m_Position, "position");
utils::TryGetJsonValue(data, m_IsNsfw, "nsfw");
utils::TryGetJsonValue(data, parent_id_str, "parent_id");
Channel_t const &channel = ChannelManager::Get()->FindChannelById(parent_id_str);
m_ParentId = channel ? channel->GetPawnId() : INVALID_CHANNEL_ID;
}
}
void Channel::SendMessage(std::string &&msg, pawn_cb::Callback_t &&cb)
{
json data = {
{ "content", std::move(msg) }
};
std::string json_str;
if (!utils::TryDumpJson(data, json_str))
Logger::Get()->Log(LogLevel::ERROR, "can't serialize JSON: {}", json_str);
Http::ResponseCb_t response_cb;
if (cb)
{
response_cb = [cb](Http::Response response)
{
Logger::Get()->Log(LogLevel::DEBUG,
"channel message create response: status {}; body: {}; add: {}",
response.status, response.body, response.additional_data);
if (response.status / 100 == 2) // success
{
auto msg_json = json::parse(response.body);
PawnDispatcher::Get()->Dispatch([cb, msg_json]() mutable
{
auto msg = MessageManager::Get()->Create(msg_json);
if (msg != INVALID_MESSAGE_ID)
{
MessageManager::Get()->SetCreatedMessageId(msg);
cb->Execute();
MessageManager::Get()->SetCreatedMessageId(INVALID_MESSAGE_ID);
MessageManager::Get()->Delete(msg);
}
});
}
};
}
Network::Get()->Http().Post(fmt::format("/channels/{:s}/messages", GetId()), json_str,
std::move(response_cb));
}
void Channel::SetChannelName(std::string const &name)
{
json data = {
{ "name", name }
};
std::string json_str;
if (!utils::TryDumpJson(data, json_str))
Logger::Get()->Log(LogLevel::ERROR, "can't serialize JSON: {}", json_str);
Network::Get()->Http().Patch(fmt::format("/channels/{:s}", GetId()), json_str);
}
void Channel::SetChannelTopic(std::string const &topic)
{
json data = {
{ "topic", topic }
};
std::string json_str;
if (!utils::TryDumpJson(data, json_str))
Logger::Get()->Log(LogLevel::ERROR, "can't serialize JSON: {}", json_str);
Network::Get()->Http().Patch(fmt::format("/channels/{:s}", GetId()), json_str);
}
void Channel::SetChannelPosition(int const position)
{
json data = {
{ "position", position }
};
std::string json_str;
if (!utils::TryDumpJson(data, json_str))
Logger::Get()->Log(LogLevel::ERROR, "can't serialize JSON: {}", json_str);
Network::Get()->Http().Patch(fmt::format("/channels/{:s}", GetId()), json_str);
}
void Channel::SetChannelNsfw(bool const is_nsfw)
{
json data = {
{ "nsfw", is_nsfw }
};
std::string json_str;
if (!utils::TryDumpJson(data, json_str))
Logger::Get()->Log(LogLevel::ERROR, "can't serialize JSON: {}", json_str);
Network::Get()->Http().Patch(fmt::format("/channels/{:s}", GetId()), json_str);
}
void Channel::SetChannelParentCategory(Channel_t const &parent)
{
if (parent->GetType() != Type::GUILD_CATEGORY)
return;
json data = {
{ "parent_id", parent->GetId() }
};
std::string json_str;
if (!utils::TryDumpJson(data, json_str))
Logger::Get()->Log(LogLevel::ERROR, "can't serialize JSON: {}", json_str);
Network::Get()->Http().Patch(fmt::format("/channels/{:s}", GetId()), json_str);
}
void Channel::DeleteChannel()
{
Network::Get()->Http().Delete(fmt::format("/channels/{:s}", GetId()));
}
void ChannelManager::Initialize()
{
assert(m_Initialized != m_InitValue);
Network::Get()->WebSocket().RegisterEvent(WebSocket::Event::CHANNEL_CREATE, [](json const &data)
{
PawnDispatcher::Get()->Dispatch([data]() mutable
{
auto const channel_id = ChannelManager::Get()->AddChannel(data);
if (channel_id == INVALID_CHANNEL_ID)
return;
// forward DCC_OnChannelCreate(DCC_Channel:channel);
pawn_cb::Error error;
pawn_cb::Callback::CallFirst(error, "DCC_OnChannelCreate", channel_id);
});
});
Network::Get()->WebSocket().RegisterEvent(WebSocket::Event::CHANNEL_UPDATE, [](json const &data)
{
ChannelManager::Get()->UpdateChannel(data);
});
Network::Get()->WebSocket().RegisterEvent(WebSocket::Event::CHANNEL_DELETE, [](json const &data)
{
ChannelManager::Get()->DeleteChannel(data);
});
Network::Get()->WebSocket().RegisterEvent(WebSocket::Event::READY, [this](json const &data)
{
static const char *PRIVATE_CHANNEL_KEY = "private_channels";
if (utils::IsValidJson(data, PRIVATE_CHANNEL_KEY, json::value_t::array))
{
for (auto const &c : data.at(PRIVATE_CHANNEL_KEY))
AddChannel(c);
}
else
{
Logger::Get()->Log(LogLevel::ERROR,
"invalid JSON: expected \"{}\" in \"{}\"", PRIVATE_CHANNEL_KEY, data.dump());
}
m_Initialized++;
});
}
bool ChannelManager::IsInitialized()
{
return m_Initialized == m_InitValue;
}
bool ChannelManager::CreateGuildChannel(Guild_t const &guild,
std::string const &name, Channel::Type type, pawn_cb::Callback_t &&cb)
{
json data = {
{ "name", name },
{ "type", static_cast<int>(type) }
};
std::string json_str;
if (!utils::TryDumpJson(data, json_str))
{
Logger::Get()->Log(LogLevel::ERROR, "can't serialize JSON: {}", json_str);
return false;
}
Network::Get()->Http().Post(fmt::format("/guilds/{:s}/channels", guild->GetId()), json_str,
[this, cb](Http::Response r)
{
Logger::Get()->Log(LogLevel::DEBUG,
"channel create response: status {}; body: {}; add: {}",
r.status, r.body, r.additional_data);
if (r.status / 100 == 2) // success
{
auto const channel_id = ChannelManager::Get()->AddChannel(json::parse(r.body));
if (channel_id == INVALID_CHANNEL_ID)
return;
if (cb)
{
PawnDispatcher::Get()->Dispatch([=]()
{
m_CreatedChannelId = channel_id;
cb->Execute();
m_CreatedChannelId = INVALID_CHANNEL_ID;
});
}
}
});
return true;
}
ChannelId_t ChannelManager::AddChannel(json const &data, GuildId_t guild_id/* = 0*/)
{
Snowflake_t sfid;
if (!utils::TryGetJsonValue(data, sfid, "id"))
{
Logger::Get()->Log(LogLevel::ERROR,
"invalid JSON: expected \"id\" in \"{}\"", data.dump());
return INVALID_CHANNEL_ID;
}
Channel_t const &channel = FindChannelById(sfid);
if (channel)
return channel->GetPawnId(); // channel already exists
ChannelId_t id = 1;
while (m_Channels.find(id) != m_Channels.end())
++id;
if (!m_Channels.emplace(id, Channel_t(new Channel(id, data, guild_id))).second)
{
Logger::Get()->Log(LogLevel::ERROR,
"can't create channel: duplicate key '{}'", id);
return INVALID_CHANNEL_ID;
}
Logger::Get()->Log(LogLevel::INFO, "successfully added channel with id '{}'", id);
return id;
}
void ChannelManager::UpdateChannel(json const &data)
{
Snowflake_t sfid;
if (!utils::TryGetJsonValue(data, sfid, "id"))
{
Logger::Get()->Log(LogLevel::ERROR,
"invalid JSON: expected \"id\" in \"{}\"", data.dump());
return;
}
std::string name, topic;
int position;
bool is_nsfw;
bool
update_name = utils::TryGetJsonValue(data, name, "name"),
update_topic = utils::TryGetJsonValue(data, topic, "topic"),
update_position = utils::TryGetJsonValue(data, position, "position"),
update_nsfw = utils::TryGetJsonValue(data, is_nsfw, "nsfw");
PawnDispatcher::Get()->Dispatch([=]()
{
Channel_t const &channel = FindChannelById(sfid);
if (!channel)
{
Logger::Get()->Log(LogLevel::ERROR,
"can't update channel: channel id \"{}\" not cached", sfid);
return;
}
if (update_name && !name.empty())
channel->m_Name = name;
if (update_topic && !topic.empty())
channel->m_Topic = topic;
if (update_position)
channel->m_Position = position;
if (update_nsfw)
channel->m_IsNsfw = is_nsfw;
// forward DCC_OnChannelUpdate(DCC_Channel:channel);
pawn_cb::Error error;
pawn_cb::Callback::CallFirst(error, "DCC_OnChannelUpdate", channel->GetPawnId());
});
}
void ChannelManager::DeleteChannel(json const &data)
{
Snowflake_t sfid;
if (!utils::TryGetJsonValue(data, sfid, "id"))
{
Logger::Get()->Log(LogLevel::ERROR,
"invalid JSON: expected \"id\" in \"{}\"", data.dump());
return;
}
PawnDispatcher::Get()->Dispatch([this, sfid]()
{
Channel_t const &channel = FindChannelById(sfid);
if (!channel)
{
Logger::Get()->Log(LogLevel::ERROR,
"can't delete channel: channel id \"{}\" not cached", sfid);
return;
}
// forward DCC_OnChannelDelete(DCC_Channel:channel);
pawn_cb::Error error;
pawn_cb::Callback::CallFirst(error, "DCC_OnChannelDelete", channel->GetPawnId());
Guild_t const &guild = GuildManager::Get()->FindGuild(channel->GetGuildId());
if (guild)
guild->RemoveChannel(channel->GetPawnId());
m_Channels.erase(channel->GetPawnId());
});
}
Channel_t const &ChannelManager::FindChannel(ChannelId_t id)
{
static Channel_t invalid_channel;
auto it = m_Channels.find(id);
if (it == m_Channels.end())
return invalid_channel;
return it->second;
}
Channel_t const &ChannelManager::FindChannelByName(std::string const &name)
{
static Channel_t invalid_channel;
for (auto const &c : m_Channels)
{
Channel_t const &channel = c.second;
if (channel->GetName().compare(name) == 0)
return channel;
}
return invalid_channel;
}
Channel_t const &ChannelManager::FindChannelById(Snowflake_t const &sfid)
{
static Channel_t invalid_channel;
for (auto const &c : m_Channels)
{
Channel_t const &channel = c.second;
if (channel->GetId().compare(sfid) == 0)
return channel;
}
return invalid_channel;
}
<commit_msg>Fix channel updating on null values, rewrite updating & CHANNEL_UPDATE<commit_after>#include "Channel.hpp"
#include "Message.hpp"
#include "Network.hpp"
#include "PawnDispatcher.hpp"
#include "Logger.hpp"
#include "Guild.hpp"
#include "utils.hpp"
#include "fmt/format.h"
#undef SendMessage // Windows at its finest
Channel::Channel(ChannelId_t pawn_id, json const &data, GuildId_t guild_id) :
m_PawnId(pawn_id)
{
std::underlying_type<Type>::type type;
if (!utils::TryGetJsonValue(data, type, "type")
|| !utils::TryGetJsonValue(data, m_Id, "id"))
{
Logger::Get()->Log(LogLevel::ERROR,
"invalid JSON: expected \"type\" and \"id\" in \"{}\"", data.dump());
return;
}
m_Type = static_cast<Type>(type);
if (m_Type < Type::DM)
{
if (guild_id != 0)
{
m_GuildId = guild_id;
}
else
{
std::string guild_id_str;
if (utils::TryGetJsonValue(data, guild_id_str, "guild_id"))
{
Guild_t const &guild = GuildManager::Get()->FindGuildById(guild_id_str);
m_GuildId = guild->GetPawnId();
guild->AddChannel(pawn_id);
}
else
{
Logger::Get()->Log(LogLevel::ERROR,
"invalid JSON: expected \"guild_id\" in \"{}\"", data.dump());
}
}
Update(data);
}
}
void Channel::Update(json const &data)
{
std::string name, topic;
int position;
bool is_nsfw;
Snowflake_t parent_id;
bool
update_name = utils::TryGetJsonValue(data, name, "name"),
update_topic = utils::TryGetJsonValue(data, topic, "topic"),
update_position = utils::TryGetJsonValue(data, position, "position"),
update_nsfw = utils::TryGetJsonValue(data, is_nsfw, "nsfw"),
update_parent_id = utils::TryGetJsonValue(data, parent_id, "parent_id");
if (update_name)
m_Name = name;
if (update_topic)
m_Topic = topic;
if (update_position)
m_Position = position;
if (update_nsfw)
m_IsNsfw = is_nsfw;
if (update_parent_id)
{
Channel_t const &channel = ChannelManager::Get()->FindChannelById(parent_id);
m_ParentId = channel ? channel->GetPawnId() : INVALID_CHANNEL_ID;
}
}
void Channel::SendMessage(std::string &&msg, pawn_cb::Callback_t &&cb)
{
json data = {
{ "content", std::move(msg) }
};
std::string json_str;
if (!utils::TryDumpJson(data, json_str))
Logger::Get()->Log(LogLevel::ERROR, "can't serialize JSON: {}", json_str);
Http::ResponseCb_t response_cb;
if (cb)
{
response_cb = [cb](Http::Response response)
{
Logger::Get()->Log(LogLevel::DEBUG,
"channel message create response: status {}; body: {}; add: {}",
response.status, response.body, response.additional_data);
if (response.status / 100 == 2) // success
{
auto msg_json = json::parse(response.body);
PawnDispatcher::Get()->Dispatch([cb, msg_json]() mutable
{
auto msg = MessageManager::Get()->Create(msg_json);
if (msg != INVALID_MESSAGE_ID)
{
MessageManager::Get()->SetCreatedMessageId(msg);
cb->Execute();
MessageManager::Get()->SetCreatedMessageId(INVALID_MESSAGE_ID);
MessageManager::Get()->Delete(msg);
}
});
}
};
}
Network::Get()->Http().Post(fmt::format("/channels/{:s}/messages", GetId()), json_str,
std::move(response_cb));
}
void Channel::SetChannelName(std::string const &name)
{
json data = {
{ "name", name }
};
std::string json_str;
if (!utils::TryDumpJson(data, json_str))
Logger::Get()->Log(LogLevel::ERROR, "can't serialize JSON: {}", json_str);
Network::Get()->Http().Patch(fmt::format("/channels/{:s}", GetId()), json_str);
}
void Channel::SetChannelTopic(std::string const &topic)
{
json data = {
{ "topic", topic }
};
std::string json_str;
if (!utils::TryDumpJson(data, json_str))
Logger::Get()->Log(LogLevel::ERROR, "can't serialize JSON: {}", json_str);
Network::Get()->Http().Patch(fmt::format("/channels/{:s}", GetId()), json_str);
}
void Channel::SetChannelPosition(int const position)
{
json data = {
{ "position", position }
};
std::string json_str;
if (!utils::TryDumpJson(data, json_str))
Logger::Get()->Log(LogLevel::ERROR, "can't serialize JSON: {}", json_str);
Network::Get()->Http().Patch(fmt::format("/channels/{:s}", GetId()), json_str);
}
void Channel::SetChannelNsfw(bool const is_nsfw)
{
json data = {
{ "nsfw", is_nsfw }
};
std::string json_str;
if (!utils::TryDumpJson(data, json_str))
Logger::Get()->Log(LogLevel::ERROR, "can't serialize JSON: {}", json_str);
Network::Get()->Http().Patch(fmt::format("/channels/{:s}", GetId()), json_str);
}
void Channel::SetChannelParentCategory(Channel_t const &parent)
{
if (parent->GetType() != Type::GUILD_CATEGORY)
return;
json data = {
{ "parent_id", parent->GetId() }
};
std::string json_str;
if (!utils::TryDumpJson(data, json_str))
Logger::Get()->Log(LogLevel::ERROR, "can't serialize JSON: {}", json_str);
Network::Get()->Http().Patch(fmt::format("/channels/{:s}", GetId()), json_str);
}
void Channel::DeleteChannel()
{
Network::Get()->Http().Delete(fmt::format("/channels/{:s}", GetId()));
}
void ChannelManager::Initialize()
{
assert(m_Initialized != m_InitValue);
Network::Get()->WebSocket().RegisterEvent(WebSocket::Event::CHANNEL_CREATE, [](json const &data)
{
PawnDispatcher::Get()->Dispatch([data]() mutable
{
auto const channel_id = ChannelManager::Get()->AddChannel(data);
if (channel_id == INVALID_CHANNEL_ID)
return;
// forward DCC_OnChannelCreate(DCC_Channel:channel);
pawn_cb::Error error;
pawn_cb::Callback::CallFirst(error, "DCC_OnChannelCreate", channel_id);
});
});
Network::Get()->WebSocket().RegisterEvent(WebSocket::Event::CHANNEL_UPDATE, [](json const &data)
{
Snowflake_t sfid;
if (!utils::TryGetJsonValue(data, sfid, "id"))
{
Logger::Get()->Log(LogLevel::ERROR,
"invalid JSON: expected \"id\" in \"{}\"", data.dump());
return;
}
Channel_t const &channel = ChannelManager::Get()->FindChannelById(sfid);
if (!channel)
{
Logger::Get()->Log(LogLevel::ERROR,
"can't update channel: channel id \"{}\" not cached", sfid);
return;
}
channel->Update(data);
ChannelId_t const &pawnId = channel->GetPawnId();
PawnDispatcher::Get()->Dispatch([pawnId]() mutable
{
// forward DCC_OnChannelUpdate(DCC_Channel:channel);
pawn_cb::Error error;
pawn_cb::Callback::CallFirst(error, "DCC_OnChannelUpdate", pawnId);
});
});
Network::Get()->WebSocket().RegisterEvent(WebSocket::Event::CHANNEL_DELETE, [](json const &data)
{
ChannelManager::Get()->DeleteChannel(data);
});
Network::Get()->WebSocket().RegisterEvent(WebSocket::Event::READY, [this](json const &data)
{
static const char *PRIVATE_CHANNEL_KEY = "private_channels";
if (utils::IsValidJson(data, PRIVATE_CHANNEL_KEY, json::value_t::array))
{
for (auto const &c : data.at(PRIVATE_CHANNEL_KEY))
AddChannel(c);
}
else
{
Logger::Get()->Log(LogLevel::ERROR,
"invalid JSON: expected \"{}\" in \"{}\"", PRIVATE_CHANNEL_KEY, data.dump());
}
m_Initialized++;
});
}
bool ChannelManager::IsInitialized()
{
return m_Initialized == m_InitValue;
}
bool ChannelManager::CreateGuildChannel(Guild_t const &guild,
std::string const &name, Channel::Type type, pawn_cb::Callback_t &&cb)
{
json data = {
{ "name", name },
{ "type", static_cast<int>(type) }
};
std::string json_str;
if (!utils::TryDumpJson(data, json_str))
{
Logger::Get()->Log(LogLevel::ERROR, "can't serialize JSON: {}", json_str);
return false;
}
Network::Get()->Http().Post(fmt::format("/guilds/{:s}/channels", guild->GetId()), json_str,
[this, cb](Http::Response r)
{
Logger::Get()->Log(LogLevel::DEBUG,
"channel create response: status {}; body: {}; add: {}",
r.status, r.body, r.additional_data);
if (r.status / 100 == 2) // success
{
auto const channel_id = ChannelManager::Get()->AddChannel(json::parse(r.body));
if (channel_id == INVALID_CHANNEL_ID)
return;
if (cb)
{
PawnDispatcher::Get()->Dispatch([=]()
{
m_CreatedChannelId = channel_id;
cb->Execute();
m_CreatedChannelId = INVALID_CHANNEL_ID;
});
}
}
});
return true;
}
ChannelId_t ChannelManager::AddChannel(json const &data, GuildId_t guild_id/* = 0*/)
{
Snowflake_t sfid;
if (!utils::TryGetJsonValue(data, sfid, "id"))
{
Logger::Get()->Log(LogLevel::ERROR,
"invalid JSON: expected \"id\" in \"{}\"", data.dump());
return INVALID_CHANNEL_ID;
}
Channel_t const &channel = FindChannelById(sfid);
if (channel)
return channel->GetPawnId(); // channel already exists
ChannelId_t id = 1;
while (m_Channels.find(id) != m_Channels.end())
++id;
if (!m_Channels.emplace(id, Channel_t(new Channel(id, data, guild_id))).second)
{
Logger::Get()->Log(LogLevel::ERROR,
"can't create channel: duplicate key '{}'", id);
return INVALID_CHANNEL_ID;
}
Logger::Get()->Log(LogLevel::INFO, "successfully added channel with id '{}'", id);
return id;
}
void ChannelManager::DeleteChannel(json const &data)
{
Snowflake_t sfid;
if (!utils::TryGetJsonValue(data, sfid, "id"))
{
Logger::Get()->Log(LogLevel::ERROR,
"invalid JSON: expected \"id\" in \"{}\"", data.dump());
return;
}
PawnDispatcher::Get()->Dispatch([this, sfid]()
{
Channel_t const &channel = FindChannelById(sfid);
if (!channel)
{
Logger::Get()->Log(LogLevel::ERROR,
"can't delete channel: channel id \"{}\" not cached", sfid);
return;
}
// forward DCC_OnChannelDelete(DCC_Channel:channel);
pawn_cb::Error error;
pawn_cb::Callback::CallFirst(error, "DCC_OnChannelDelete", channel->GetPawnId());
Guild_t const &guild = GuildManager::Get()->FindGuild(channel->GetGuildId());
if (guild)
guild->RemoveChannel(channel->GetPawnId());
m_Channels.erase(channel->GetPawnId());
});
}
Channel_t const &ChannelManager::FindChannel(ChannelId_t id)
{
static Channel_t invalid_channel;
auto it = m_Channels.find(id);
if (it == m_Channels.end())
return invalid_channel;
return it->second;
}
Channel_t const &ChannelManager::FindChannelByName(std::string const &name)
{
static Channel_t invalid_channel;
for (auto const &c : m_Channels)
{
Channel_t const &channel = c.second;
if (channel->GetName().compare(name) == 0)
return channel;
}
return invalid_channel;
}
Channel_t const &ChannelManager::FindChannelById(Snowflake_t const &sfid)
{
static Channel_t invalid_channel;
for (auto const &c : m_Channels)
{
Channel_t const &channel = c.second;
if (channel->GetId().compare(sfid) == 0)
return channel;
}
return invalid_channel;
}
<|endoftext|> |
<commit_before>
/*
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1
*
* ``The contents of this file are subject to the Mozilla Public 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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations
* under the License.
*
* The Original Code is SimpleAmqpClient for RabbitMQ.
*
* The Initial Developer of the Original Code is Alan Antonuk.
* Original code is Copyright (C) Alan Antonuk.
*
* All Rights Reserved.
*
* Contributor(s): ______________________________________.
*
* Alternatively, the contents of this file may be used under the terms
* of the GNU General Public License Version 2 or later (the "GPL"), in
* which case the provisions of the GPL are applicable instead of those
* above. If you wish to allow use of your version of this file only
* under the terms of the GPL, and not to allow others to use your
* version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the
* notice and other provisions required by the GPL. If you do not
* delete the provisions above, a recipient may use your version of
* this file under the terms of any one of the MPL or the GPL.
*
* ***** END LICENSE BLOCK *****
*/
#include "SimpleAmqpClient/Channel.h"
#include "SimpleAmqpClient/Util.h"
#include "config.h"
#include <amqp_framing.h>
#include <stdexcept>
#include <boost/cstdint.hpp>
#include <boost/limits.hpp>
// This will get us the posix version of strerror_r() on linux
#define _XOPEN_SOURCE 600
#include <string.h>
#include <sys/types.h>
#include <errno.h>
#ifdef HAVE_SYS_SOCKET_H
# include <sys/socket.h>
#endif
#ifdef HAVE_WINSOCK2_H
# include <WinSock2.h>
#endif
#include <time.h>
// Win32 headers seem to define this annoyingly...
#ifdef max
# undef max
#endif
namespace AmqpClient {
const amqp_table_t Channel::EMPTY_TABLE = { 0, NULL };
const std::string Channel::EXCHANGE_TYPE_DIRECT("amq.direct");
const std::string Channel::EXCHANGE_TYPE_FANOUT("fanout");
const std::string Channel::EXCHANGE_TYPE_TOPIC("topic");
Channel::Channel(const std::string& host,
int port,
const std::string& username,
const std::string& password,
const std::string& vhost,
int frame_max) :
m_channel(DEFAULT_CHANNEL)
{
m_connection = amqp_new_connection();
int sock = amqp_open_socket(host.c_str(), port);
Util::CheckForError(sock, "Channel::Channel amqp_open_socket");
amqp_set_sockfd(m_connection, sock);
Util::CheckRpcReply(amqp_login(m_connection, vhost.c_str(), 2,
frame_max, BROKER_HEARTBEAT, AMQP_SASL_METHOD_PLAIN,
username.c_str(), password.c_str()), "Amqp Login");
amqp_channel_open(m_connection, m_channel);
Util::CheckLastRpcReply(m_connection, "Channel::Channel creating default channel");
}
Channel::~Channel()
{
amqp_channel_close(m_connection, m_channel, AMQP_REPLY_SUCCESS);
amqp_connection_close(m_connection, AMQP_REPLY_SUCCESS);
amqp_destroy_connection(m_connection);
}
void Channel::DeclareExchange(const std::string& exchange_name,
const std::string& exchange_type,
bool passive,
bool durable,
bool auto_delete)
{
amqp_exchange_declare(m_connection, m_channel,
amqp_cstring_bytes(exchange_name.c_str()),
amqp_cstring_bytes(exchange_type.c_str()),
passive,
durable,
EMPTY_TABLE);
Util::CheckLastRpcReply(m_connection, "Declaring exchange");
}
void Channel::DeleteExchange(const std::string& exchange_name,
bool if_unused,
bool nowait)
{
amqp_method_number_t replies[2] = { AMQP_EXCHANGE_DELETE_OK_METHOD, 0 };
amqp_exchange_delete_t req;
req.exchange = amqp_cstring_bytes(exchange_name.c_str());
req.if_unused = if_unused;
req.nowait = nowait;
Util::CheckRpcReply(amqp_simple_rpc(m_connection, m_channel,
AMQP_EXCHANGE_DELETE_METHOD,
replies, &req), "Delete Exchange");
}
std::string Channel::DeclareQueue(const std::string& queue_name,
bool passive,
bool durable,
bool exclusive,
bool auto_delete)
{
amqp_queue_declare_ok_t* queue_declare =
amqp_queue_declare(m_connection, m_channel,
amqp_cstring_bytes(queue_name.c_str()),
passive,
durable,
exclusive,
auto_delete,
EMPTY_TABLE);
Util::CheckLastRpcReply(m_connection, "Declaring queue");
return std::string((char*)queue_declare->queue.bytes,
queue_declare->queue.len);
}
void Channel::DeleteQueue(const std::string& queue_name,
bool if_unused,
bool if_empty)
{
amqp_queue_delete(m_connection, m_channel,
amqp_cstring_bytes(queue_name.c_str()),
if_unused,
if_empty);
Util::CheckLastRpcReply(m_connection, "Deleting Queue");
}
void Channel::BindQueue(const std::string& queue_name,
const std::string& exchange_name,
const std::string& routing_key)
{
amqp_queue_bind(m_connection, m_channel,
amqp_cstring_bytes(queue_name.c_str()),
amqp_cstring_bytes(exchange_name.c_str()),
amqp_cstring_bytes(routing_key.c_str()),
EMPTY_TABLE);
Util::CheckLastRpcReply(m_connection, "Binding queue");
}
void Channel::UnbindQueue(const std::string& queue_name,
const std::string& exchange_name,
const std::string& binding_key)
{
amqp_queue_unbind(m_connection, m_channel,
amqp_cstring_bytes(queue_name.c_str()),
amqp_cstring_bytes(exchange_name.c_str()),
amqp_cstring_bytes(binding_key.c_str()),
EMPTY_TABLE);
Util::CheckLastRpcReply(m_connection, "Unbinding queue");
}
void Channel::BasicAck(const BasicMessage::ptr_t message)
{
BasicAck(message->DeliveryTag());
}
void Channel::BasicAck(uint64_t delivery_tag)
{
Util::CheckForError(amqp_basic_ack(m_connection, m_channel,
delivery_tag,
false), "Ack");
}
void Channel::BasicPublish(const std::string& exchange_name,
const std::string& routing_key,
const BasicMessage::ptr_t message,
bool mandatory,
bool immediate)
{
amqp_basic_publish(m_connection, m_channel,
amqp_cstring_bytes(exchange_name.c_str()),
amqp_cstring_bytes(routing_key.c_str()),
mandatory,
immediate,
message->getAmqpProperties(),
message->getAmqpBody());
Util::CheckLastRpcReply(m_connection, "Publishing to queue");
}
void Channel::BasicConsume(const std::string& queue,
const std::string& consumer_tag,
bool no_local,
bool no_ack,
bool exclusive)
{
amqp_basic_consume(m_connection, m_channel,
amqp_cstring_bytes(queue.c_str()),
amqp_cstring_bytes(consumer_tag.c_str()),
no_local,
no_ack,
exclusive,
EMPTY_TABLE);
Util::CheckLastRpcReply(m_connection, "Basic Consume");
}
void Channel::BasicCancel(const std::string& consumer_tag)
{
amqp_method_number_t replies[2] = { AMQP_BASIC_CANCEL_OK_METHOD, 0 };
amqp_basic_cancel_t req;
req.consumer_tag = amqp_cstring_bytes(consumer_tag.c_str());
req.nowait = 0;
Util::CheckRpcReply(amqp_simple_rpc(m_connection, m_channel,
AMQP_BASIC_CANCEL_METHOD,
replies, &req), "Basic Cancel");
}
BasicMessage::ptr_t Channel::BasicConsumeMessage()
{
BasicMessage::ptr_t returnval;
BasicConsumeMessage(returnval, 0);
return returnval;
}
bool Channel::BasicConsumeMessage(BasicMessage::ptr_t& message, int timeout)
{
int socketno = amqp_get_sockfd(m_connection);
struct timeval tv_timeout;
memset(&tv_timeout, 0, sizeof(tv_timeout));
tv_timeout.tv_sec = timeout;
struct timeval tv_zero;
memset(&tv_zero, 0, sizeof(tv_zero));
tv_zero.tv_sec = 0;
while (true)
{
amqp_frame_t frame;
amqp_maybe_release_buffers(m_connection);
// Possibly set a timeout on receiving
// We only do this on the first frame otherwise we'd confuse
// This function if it immediately turns around and gets called again
if (timeout > 0)
{
if (setsockopt(socketno, SOL_SOCKET, SO_RCVTIMEO, (char*)&tv_timeout, sizeof(tv_timeout)))
{
std::string error_string("Setting socket timeout failed (setsockopt) ");
#ifdef HAVE_STRERROR_S
const int BUFFER_LENGTH = 256;
char error_string_buffer[BUFFER_LENGTH] = {0};
strerror_s(error_string_buffer, errno);
error_string += error_string_buffer;
#elif defined(HAVE_STRERROR_R)
const int BUFFER_LENGTH = 256;
char error_string_buffer[BUFFER_LENGTH] = {0};
strerror_r(errno, error_string_buffer, BUFFER_LENGTH);
error_string += error_string_buffer;
#else
error_string += strerror(errno);
#endif
throw std::runtime_error(error_string.c_str());
}
}
int ret = amqp_simple_wait_frame(m_connection, &frame);
// Save errno as it might be overwritten by setsockopt
int errno_save = errno;
setsockopt(socketno, SOL_SOCKET, SO_RCVTIMEO, (char*)&tv_zero, sizeof(tv_zero));
if (ret != 0)
{
#ifdef HAVE_WINSOCK2_H
int wsa_err = (-ret) & ~(1 << 29);
if (wsa_err == WSAETIMEDOUT)
{
return false;
}
#else // HAVE_WINSOCK2_H
// Interrupted system call, just loop around and try it again
if (errno_save == EINTR)
{
continue;
}
else if (errno_save == EAGAIN || errno_save == EWOULDBLOCK)
{
return false;
}
#endif
}
Util::CheckForError(ret, "Consume Message: method frame");
if (frame.frame_type != AMQP_FRAME_METHOD || frame.payload.method.id != AMQP_BASIC_DELIVER_METHOD)
continue;
amqp_basic_deliver_t* deliver_method = reinterpret_cast<amqp_basic_deliver_t*>(frame.payload.method.decoded);
// Wait for frame #2, the header frame which contains body size
Util::CheckForError(amqp_simple_wait_frame(m_connection, &frame), "Consume Message: header frame");
if (frame.frame_type != AMQP_FRAME_HEADER)
throw std::runtime_error("Channel::BasicConsumeMessage: receieved unexpected frame type (was expected AMQP_FRAME_HEADER)");
amqp_basic_properties_t* properties = reinterpret_cast<amqp_basic_properties_t*>(frame.payload.properties.decoded);
size_t body_size = frame.payload.properties.body_size;
size_t received_size = 0;
amqp_bytes_t body = amqp_bytes_malloc(body_size);
// frame #3 and up:
while (received_size < body_size)
{
Util::CheckForError(amqp_simple_wait_frame(m_connection, &frame), "Consume Message: body frame");
if (frame.frame_type != AMQP_FRAME_BODY)
throw std::runtime_error("Channel::BasicConsumeMessge: received unexpected frame type (was expecting AMQP_FRAME_BODY)");
void* body_ptr = reinterpret_cast<char*>(body.bytes) + received_size;
memcpy(body_ptr, frame.payload.body_fragment.bytes, frame.payload.body_fragment.len);
received_size += frame.payload.body_fragment.len;
}
message = BasicMessage::Create(body, properties, deliver_method->delivery_tag);
return true;
}
}
void Channel::ResetChannel()
{
Util::CheckRpcReply(amqp_channel_close(m_connection, m_channel, AMQP_REPLY_SUCCESS), "ResetChannel: closing channel");
m_channel = (m_channel + 1) % std::numeric_limits<uint16_t>::max();
amqp_channel_open(m_connection, m_channel);
Util::CheckLastRpcReply(m_connection, "ResetChannel: opening channel");
}
} // namespace AmqpClient
<commit_msg>Pass the correct arguments to setsockopt on Win32<commit_after>
/*
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1
*
* ``The contents of this file are subject to the Mozilla Public 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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations
* under the License.
*
* The Original Code is SimpleAmqpClient for RabbitMQ.
*
* The Initial Developer of the Original Code is Alan Antonuk.
* Original code is Copyright (C) Alan Antonuk.
*
* All Rights Reserved.
*
* Contributor(s): ______________________________________.
*
* Alternatively, the contents of this file may be used under the terms
* of the GNU General Public License Version 2 or later (the "GPL"), in
* which case the provisions of the GPL are applicable instead of those
* above. If you wish to allow use of your version of this file only
* under the terms of the GPL, and not to allow others to use your
* version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the
* notice and other provisions required by the GPL. If you do not
* delete the provisions above, a recipient may use your version of
* this file under the terms of any one of the MPL or the GPL.
*
* ***** END LICENSE BLOCK *****
*/
#include "SimpleAmqpClient/Channel.h"
#include "SimpleAmqpClient/Util.h"
#include "config.h"
#include <amqp_framing.h>
#include <stdexcept>
#include <boost/cstdint.hpp>
#include <boost/limits.hpp>
// This will get us the posix version of strerror_r() on linux
#define _XOPEN_SOURCE 600
#include <string.h>
#include <sys/types.h>
#include <errno.h>
#ifdef HAVE_SYS_SOCKET_H
# include <sys/socket.h>
#endif
#ifdef HAVE_WINSOCK2_H
# include <WinSock2.h>
#endif
#include <time.h>
// Win32 headers seem to define this annoyingly...
#ifdef max
# undef max
#endif
namespace AmqpClient {
const amqp_table_t Channel::EMPTY_TABLE = { 0, NULL };
const std::string Channel::EXCHANGE_TYPE_DIRECT("amq.direct");
const std::string Channel::EXCHANGE_TYPE_FANOUT("fanout");
const std::string Channel::EXCHANGE_TYPE_TOPIC("topic");
Channel::Channel(const std::string& host,
int port,
const std::string& username,
const std::string& password,
const std::string& vhost,
int frame_max) :
m_channel(DEFAULT_CHANNEL)
{
m_connection = amqp_new_connection();
int sock = amqp_open_socket(host.c_str(), port);
Util::CheckForError(sock, "Channel::Channel amqp_open_socket");
amqp_set_sockfd(m_connection, sock);
Util::CheckRpcReply(amqp_login(m_connection, vhost.c_str(), 2,
frame_max, BROKER_HEARTBEAT, AMQP_SASL_METHOD_PLAIN,
username.c_str(), password.c_str()), "Amqp Login");
amqp_channel_open(m_connection, m_channel);
Util::CheckLastRpcReply(m_connection, "Channel::Channel creating default channel");
}
Channel::~Channel()
{
amqp_channel_close(m_connection, m_channel, AMQP_REPLY_SUCCESS);
amqp_connection_close(m_connection, AMQP_REPLY_SUCCESS);
amqp_destroy_connection(m_connection);
}
void Channel::DeclareExchange(const std::string& exchange_name,
const std::string& exchange_type,
bool passive,
bool durable,
bool auto_delete)
{
amqp_exchange_declare(m_connection, m_channel,
amqp_cstring_bytes(exchange_name.c_str()),
amqp_cstring_bytes(exchange_type.c_str()),
passive,
durable,
EMPTY_TABLE);
Util::CheckLastRpcReply(m_connection, "Declaring exchange");
}
void Channel::DeleteExchange(const std::string& exchange_name,
bool if_unused,
bool nowait)
{
amqp_method_number_t replies[2] = { AMQP_EXCHANGE_DELETE_OK_METHOD, 0 };
amqp_exchange_delete_t req;
req.exchange = amqp_cstring_bytes(exchange_name.c_str());
req.if_unused = if_unused;
req.nowait = nowait;
Util::CheckRpcReply(amqp_simple_rpc(m_connection, m_channel,
AMQP_EXCHANGE_DELETE_METHOD,
replies, &req), "Delete Exchange");
}
std::string Channel::DeclareQueue(const std::string& queue_name,
bool passive,
bool durable,
bool exclusive,
bool auto_delete)
{
amqp_queue_declare_ok_t* queue_declare =
amqp_queue_declare(m_connection, m_channel,
amqp_cstring_bytes(queue_name.c_str()),
passive,
durable,
exclusive,
auto_delete,
EMPTY_TABLE);
Util::CheckLastRpcReply(m_connection, "Declaring queue");
return std::string((char*)queue_declare->queue.bytes,
queue_declare->queue.len);
}
void Channel::DeleteQueue(const std::string& queue_name,
bool if_unused,
bool if_empty)
{
amqp_queue_delete(m_connection, m_channel,
amqp_cstring_bytes(queue_name.c_str()),
if_unused,
if_empty);
Util::CheckLastRpcReply(m_connection, "Deleting Queue");
}
void Channel::BindQueue(const std::string& queue_name,
const std::string& exchange_name,
const std::string& routing_key)
{
amqp_queue_bind(m_connection, m_channel,
amqp_cstring_bytes(queue_name.c_str()),
amqp_cstring_bytes(exchange_name.c_str()),
amqp_cstring_bytes(routing_key.c_str()),
EMPTY_TABLE);
Util::CheckLastRpcReply(m_connection, "Binding queue");
}
void Channel::UnbindQueue(const std::string& queue_name,
const std::string& exchange_name,
const std::string& binding_key)
{
amqp_queue_unbind(m_connection, m_channel,
amqp_cstring_bytes(queue_name.c_str()),
amqp_cstring_bytes(exchange_name.c_str()),
amqp_cstring_bytes(binding_key.c_str()),
EMPTY_TABLE);
Util::CheckLastRpcReply(m_connection, "Unbinding queue");
}
void Channel::BasicAck(const BasicMessage::ptr_t message)
{
BasicAck(message->DeliveryTag());
}
void Channel::BasicAck(uint64_t delivery_tag)
{
Util::CheckForError(amqp_basic_ack(m_connection, m_channel,
delivery_tag,
false), "Ack");
}
void Channel::BasicPublish(const std::string& exchange_name,
const std::string& routing_key,
const BasicMessage::ptr_t message,
bool mandatory,
bool immediate)
{
amqp_basic_publish(m_connection, m_channel,
amqp_cstring_bytes(exchange_name.c_str()),
amqp_cstring_bytes(routing_key.c_str()),
mandatory,
immediate,
message->getAmqpProperties(),
message->getAmqpBody());
Util::CheckLastRpcReply(m_connection, "Publishing to queue");
}
void Channel::BasicConsume(const std::string& queue,
const std::string& consumer_tag,
bool no_local,
bool no_ack,
bool exclusive)
{
amqp_basic_consume(m_connection, m_channel,
amqp_cstring_bytes(queue.c_str()),
amqp_cstring_bytes(consumer_tag.c_str()),
no_local,
no_ack,
exclusive,
EMPTY_TABLE);
Util::CheckLastRpcReply(m_connection, "Basic Consume");
}
void Channel::BasicCancel(const std::string& consumer_tag)
{
amqp_method_number_t replies[2] = { AMQP_BASIC_CANCEL_OK_METHOD, 0 };
amqp_basic_cancel_t req;
req.consumer_tag = amqp_cstring_bytes(consumer_tag.c_str());
req.nowait = 0;
Util::CheckRpcReply(amqp_simple_rpc(m_connection, m_channel,
AMQP_BASIC_CANCEL_METHOD,
replies, &req), "Basic Cancel");
}
BasicMessage::ptr_t Channel::BasicConsumeMessage()
{
BasicMessage::ptr_t returnval;
BasicConsumeMessage(returnval, 0);
return returnval;
}
bool Channel::BasicConsumeMessage(BasicMessage::ptr_t& message, int timeout)
{
int socketno = amqp_get_sockfd(m_connection);
#ifdef HAVE_WINSOCK2_H
// Timeouts on Winsock are a DWORD, and are in MS
uint32_t tv_timeout = timeout * 1000;
uint32_t tv_zero = 0;
#else
struct timeval tv_timeout;
memset(&tv_timeout, 0, sizeof(tv_timeout));
tv_timeout.tv_sec = timeout;
struct timeval tv_zero;
memset(&tv_zero, 0, sizeof(tv_zero));
tv_zero.tv_sec = 0;
#endif
while (true)
{
amqp_frame_t frame;
amqp_maybe_release_buffers(m_connection);
// Possibly set a timeout on receiving
// We only do this on the first frame otherwise we'd confuse
// This function if it immediately turns around and gets called again
if (timeout > 0)
{
if (setsockopt(socketno, SOL_SOCKET, SO_RCVTIMEO, (char*)&tv_timeout, sizeof(tv_timeout)))
{
std::string error_string("Setting socket timeout failed (setsockopt) ");
#ifdef HAVE_STRERROR_S
const int BUFFER_LENGTH = 256;
char error_string_buffer[BUFFER_LENGTH] = {0};
strerror_s(error_string_buffer, errno);
error_string += error_string_buffer;
#elif defined(HAVE_STRERROR_R)
const int BUFFER_LENGTH = 256;
char error_string_buffer[BUFFER_LENGTH] = {0};
strerror_r(errno, error_string_buffer, BUFFER_LENGTH);
error_string += error_string_buffer;
#else
error_string += strerror(errno);
#endif
throw std::runtime_error(error_string.c_str());
}
}
int ret = amqp_simple_wait_frame(m_connection, &frame);
// Save errno as it might be overwritten by setsockopt
int errno_save = errno;
setsockopt(socketno, SOL_SOCKET, SO_RCVTIMEO, (char*)&tv_zero, sizeof(tv_zero));
if (ret != 0)
{
#ifdef HAVE_WINSOCK2_H
int wsa_err = (-ret) & ~(1 << 29);
if (wsa_err == WSAETIMEDOUT)
{
return false;
}
#else // HAVE_WINSOCK2_H
// Interrupted system call, just loop around and try it again
if (errno_save == EINTR)
{
continue;
}
else if (errno_save == EAGAIN || errno_save == EWOULDBLOCK)
{
return false;
}
#endif
}
Util::CheckForError(ret, "Consume Message: method frame");
if (frame.frame_type != AMQP_FRAME_METHOD || frame.payload.method.id != AMQP_BASIC_DELIVER_METHOD)
continue;
amqp_basic_deliver_t* deliver_method = reinterpret_cast<amqp_basic_deliver_t*>(frame.payload.method.decoded);
// Wait for frame #2, the header frame which contains body size
Util::CheckForError(amqp_simple_wait_frame(m_connection, &frame), "Consume Message: header frame");
if (frame.frame_type != AMQP_FRAME_HEADER)
throw std::runtime_error("Channel::BasicConsumeMessage: receieved unexpected frame type (was expected AMQP_FRAME_HEADER)");
amqp_basic_properties_t* properties = reinterpret_cast<amqp_basic_properties_t*>(frame.payload.properties.decoded);
size_t body_size = frame.payload.properties.body_size;
size_t received_size = 0;
amqp_bytes_t body = amqp_bytes_malloc(body_size);
// frame #3 and up:
while (received_size < body_size)
{
Util::CheckForError(amqp_simple_wait_frame(m_connection, &frame), "Consume Message: body frame");
if (frame.frame_type != AMQP_FRAME_BODY)
throw std::runtime_error("Channel::BasicConsumeMessge: received unexpected frame type (was expecting AMQP_FRAME_BODY)");
void* body_ptr = reinterpret_cast<char*>(body.bytes) + received_size;
memcpy(body_ptr, frame.payload.body_fragment.bytes, frame.payload.body_fragment.len);
received_size += frame.payload.body_fragment.len;
}
message = BasicMessage::Create(body, properties, deliver_method->delivery_tag);
return true;
}
}
void Channel::ResetChannel()
{
Util::CheckRpcReply(amqp_channel_close(m_connection, m_channel, AMQP_REPLY_SUCCESS), "ResetChannel: closing channel");
m_channel = (m_channel + 1) % std::numeric_limits<uint16_t>::max();
amqp_channel_open(m_connection, m_channel);
Util::CheckLastRpcReply(m_connection, "ResetChannel: opening channel");
}
} // namespace AmqpClient
<|endoftext|> |
<commit_before>#include "CryFuse.h"
#include <sys/types.h>
#include <sys/time.h>
#include <dirent.h>
#include <cassert>
#include "cryfs_lib/CryNode.h"
#include "cryfs_lib/CryErrnoException.h"
#define UNUSED(expr) (void)(expr)
using fusepp::path;
namespace cryfs {
CryFuse::CryFuse(CryDevice *device)
:_device(device) {
}
int CryFuse::getattr(const path &path, struct stat *stbuf) {
try {
_device->lstat(path, stbuf);
return 0;
} catch(cryfs::CryErrnoException &e) {
return -e.getErrno();
}
}
int CryFuse::fgetattr(const path &path, struct stat *stbuf, fuse_file_info *fileinfo) {
//printf("fgetattr(%s, _, _)\n", path.c_str());
// On FreeBSD, trying to do anything with the mountpoint ends up
// opening it, and then using the FD for an fgetattr. So in the
// special case of a path of "/", I need to do a getattr on the
// underlying root directory instead of doing the fgetattr().
// TODO Check if necessary
if (path.native() == "/") {
return getattr(path, stbuf);
}
try {
_device->fstat(fileinfo->fh, stbuf);
return 0;
} catch(cryfs::CryErrnoException &e) {
return -e.getErrno();
}
}
//TODO
int CryFuse::readlink(const path &path, char *buf, size_t size) {
//printf("readlink(%s, _, %zu)\n", path.c_str(), size);
auto real_path = _device->RootDir() / path;
//size-1, because the fuse readlink() function includes the null terminating byte in the buffer size,
//but the posix version does not and also doesn't append one.
int real_size = ::readlink(real_path.c_str(), buf, size-1);
if (real_size < 0) {
return -errno;
}
//Terminate the string
buf[real_size] = '\0';
return 0;
}
int CryFuse::mknod(const path &path, mode_t mode, dev_t rdev) {
UNUSED(rdev);
UNUSED(mode);
UNUSED(path);
printf("Called non-implemented mknod(%s, %d, _)\n", path.c_str(), mode);
return 0;
}
int CryFuse::mkdir(const path &path, mode_t mode) {
//printf("mkdir(%s, %d)\n", path.c_str(), mode);
try {
_device->mkdir(path, mode);
return 0;
} catch(cryfs::CryErrnoException &e) {
return -e.getErrno();
}
}
int CryFuse::unlink(const path &path) {
//printf("unlink(%s)\n", path.c_str());
try {
_device->unlink(path);
return 0;
} catch(cryfs::CryErrnoException &e) {
return -e.getErrno();
}
}
int CryFuse::rmdir(const path &path) {
try {
_device->rmdir(path);
return 0;
} catch(cryfs::CryErrnoException &e) {
return -e.getErrno();
}
}
//TODO
int CryFuse::symlink(const path &from, const path &to) {
printf("NOT IMPLEMENTED: symlink(%s, %s)\n", from.c_str(), to.c_str());
//auto real_from = _device->RootDir() / from;
//auto real_to = _device->RootDir() / to;
//int retstat = ::symlink(real_from.c_str(), real_to.c_str());
//return errcode_map(retstat);
return ENOSYS;
}
int CryFuse::rename(const path &from, const path &to) {
//printf("rename(%s, %s)\n", from.c_str(), to.c_str());
try {
_device->rename(from, to);
return 0;
} catch(cryfs::CryErrnoException &e) {
return -e.getErrno();
}
}
//TODO
int CryFuse::link(const path &from, const path &to) {
printf("NOT IMPLEMENTED: link(%s, %s)\n", from.c_str(), to.c_str());
//auto real_from = _device->RootDir() / from;
//auto real_to = _device->RootDir() / to;
//int retstat = ::link(real_from.c_str(), real_to.c_str());
//return errcode_map(retstat);
return ENOSYS;
}
//TODO
int CryFuse::chmod(const path &path, mode_t mode) {
printf("NOT IMPLEMENTED: chmod(%s, %d)\n", path.c_str(), mode);
//auto real_path = _device->RootDir() / path;
//int retstat = ::chmod(real_path.c_str(), mode);
//return errcode_map(retstat);
return ENOSYS;
}
//TODO
int CryFuse::chown(const path &path, uid_t uid, gid_t gid) {
printf("NOT IMPLEMENTED: chown(%s, %d, %d)\n", path.c_str(), uid, gid);
//auto real_path = _device->RootDir() / path;
//int retstat = ::chown(real_path.c_str(), uid, gid);
//return errcode_map(retstat);
return ENOSYS;
}
int CryFuse::truncate(const path &path, off_t size) {
//printf("truncate(%s, %zu)\n", path.c_str(), size);
try {
_device->truncate(path, size);
return 0;
} catch (CryErrnoException &e) {
return -e.getErrno();
}
}
int CryFuse::ftruncate(const path &path, off_t size, fuse_file_info *fileinfo) {
//printf("ftruncate(%s, %zu, _)\n", path.c_str(), size);
UNUSED(path);
try {
_device->ftruncate(fileinfo->fh, size);
return 0;
} catch (CryErrnoException &e) {
return -e.getErrno();
}
}
//TODO
int CryFuse::utimens(const path &path, const timespec times[2]) {
//printf("utimens(%s, _)\n", path.c_str());
try {
_device->utimens(path, times);
return 0;
} catch (CryErrnoException &e) {
return -e.getErrno();
}
}
int CryFuse::open(const path &path, fuse_file_info *fileinfo) {
//printf("open(%s, _)\n", path.c_str());
try {
fileinfo->fh = _device->openFile(path, fileinfo->flags);
return 0;
} catch (CryErrnoException &e) {
return -e.getErrno();
}
}
int CryFuse::release(const path &path, fuse_file_info *fileinfo) {
//printf("release(%s, _)\n", path.c_str());
UNUSED(path);
try {
_device->closeFile(fileinfo->fh);
return 0;
} catch (CryErrnoException &e) {
return -e.getErrno();
}
}
int CryFuse::read(const path &path, char *buf, size_t size, off_t offset, fuse_file_info *fileinfo) {
//printf("read(%s, _, %zu, %zu, _)\n", path.c_str(), size, offset);
UNUSED(path);
try {
//printf("Reading from file %d\n", fileinfo->fh);
//fflush(stdout);
return _device->read(fileinfo->fh, buf, size, offset);
} catch (CryErrnoException &e) {
return -e.getErrno();
}
}
int CryFuse::write(const path &path, const char *buf, size_t size, off_t offset, fuse_file_info *fileinfo) {
//printf("write(%s, _, %zu, %zu, _)\n", path.c_str(), size, offset);
UNUSED(path);
try {
_device->write(fileinfo->fh, buf, size, offset);
return size;
} catch (CryErrnoException &e) {
return -e.getErrno();
}
}
//TODO
int CryFuse::statfs(const path &path, struct statvfs *fsstat) {
//printf("statfs(%s, _)\n", path.c_str());
try {
_device->statfs(path, fsstat);
return 0;
} catch (CryErrnoException &e) {
return -e.getErrno();
}
}
//TODO
int CryFuse::flush(const path &path, fuse_file_info *fileinfo) {
//printf("Called non-implemented flush(%s, _)\n", path.c_str());
UNUSED(path);
UNUSED(fileinfo);
return 0;
}
int CryFuse::fsync(const path &path, int datasync, fuse_file_info *fileinfo) {
//printf("fsync(%s, %d, _)\n", path.c_str(), datasync);
UNUSED(path);
try {
if (datasync) {
_device->fdatasync(fileinfo->fh);
} else {
_device->fsync(fileinfo->fh);
}
return 0;
} catch (CryErrnoException &e) {
return -e.getErrno();
}
}
int CryFuse::opendir(const path &path, fuse_file_info *fileinfo) {
//printf("opendir(%s, _)\n", path.c_str());
try {
fileinfo->fh = _device->openDir(path);
return 0;
} catch(CryErrnoException &e) {
return -e.getErrno();
}
}
int CryFuse::readdir(const path &path, void *buf, fuse_fill_dir_t filler, off_t offset, fuse_file_info *fileinfo) {
UNUSED(path);
//printf("readdir(%s, _, _, %zu, _)\n", path.c_str(), offset);
UNUSED(offset);
try {
auto entries = _device->readDir(fileinfo->fh);
for (const auto &entry : *entries) {
//TODO Also give file attributes (third param of filler)
if (filler(buf, entry.c_str(), nullptr, 0) != 0) {
return -ENOMEM;
}
}
return 0;
} catch (CryErrnoException &e) {
return -e.getErrno();
}
}
int CryFuse::releasedir(const path &path, fuse_file_info *fileinfo) {
//printf("releasedir(%s, _)\n", path.c_str());
UNUSED(path);
try {
_device->closeDir(fileinfo->fh);
return 0;
} catch (CryErrnoException &e) {
return -e.getErrno();
}
}
//TODO
int CryFuse::fsyncdir(const path &path, int datasync, fuse_file_info *fileinfo) {
UNUSED(fileinfo);
UNUSED(datasync);
UNUSED(path);
//printf("Called non-implemented fsyncdir(%s, %d, _)\n", path.c_str(), datasync);
return 0;
}
void CryFuse::init(fuse_conn_info *conn) {
UNUSED(conn);
//printf("init()\n");
}
void CryFuse::destroy() {
//printf("destroy()\n");
}
int CryFuse::access(const path &path, int mask) {
//printf("access(%s, %d)\n", path.c_str(), mask);
try {
_device->access(path, mask);
return 0;
} catch (CryErrnoException &e) {
return -e.getErrno();
}
}
int CryFuse::create(const path &path, mode_t mode, fuse_file_info *fileinfo) {
//printf("create(%s, %d, _)\n", path.c_str(), mode);
try {
fileinfo->fh = _device->createAndOpenFile(path, mode);
return 0;
} catch (CryErrnoException &e) {
return -e.getErrno();
}
}
} /* namespace cryfs */
<commit_msg>Fix error code<commit_after>#include "CryFuse.h"
#include <sys/types.h>
#include <sys/time.h>
#include <dirent.h>
#include <cassert>
#include "cryfs_lib/CryNode.h"
#include "cryfs_lib/CryErrnoException.h"
#define UNUSED(expr) (void)(expr)
using fusepp::path;
namespace cryfs {
CryFuse::CryFuse(CryDevice *device)
:_device(device) {
}
int CryFuse::getattr(const path &path, struct stat *stbuf) {
try {
_device->lstat(path, stbuf);
return 0;
} catch(cryfs::CryErrnoException &e) {
return -e.getErrno();
}
}
int CryFuse::fgetattr(const path &path, struct stat *stbuf, fuse_file_info *fileinfo) {
//printf("fgetattr(%s, _, _)\n", path.c_str());
// On FreeBSD, trying to do anything with the mountpoint ends up
// opening it, and then using the FD for an fgetattr. So in the
// special case of a path of "/", I need to do a getattr on the
// underlying root directory instead of doing the fgetattr().
// TODO Check if necessary
if (path.native() == "/") {
return getattr(path, stbuf);
}
try {
_device->fstat(fileinfo->fh, stbuf);
return 0;
} catch(cryfs::CryErrnoException &e) {
return -e.getErrno();
}
}
//TODO
int CryFuse::readlink(const path &path, char *buf, size_t size) {
//printf("readlink(%s, _, %zu)\n", path.c_str(), size);
auto real_path = _device->RootDir() / path;
//size-1, because the fuse readlink() function includes the null terminating byte in the buffer size,
//but the posix version does not and also doesn't append one.
int real_size = ::readlink(real_path.c_str(), buf, size-1);
if (real_size < 0) {
return -errno;
}
//Terminate the string
buf[real_size] = '\0';
return 0;
}
int CryFuse::mknod(const path &path, mode_t mode, dev_t rdev) {
UNUSED(rdev);
UNUSED(mode);
UNUSED(path);
printf("Called non-implemented mknod(%s, %d, _)\n", path.c_str(), mode);
return ENOSYS;
}
int CryFuse::mkdir(const path &path, mode_t mode) {
//printf("mkdir(%s, %d)\n", path.c_str(), mode);
try {
_device->mkdir(path, mode);
return 0;
} catch(cryfs::CryErrnoException &e) {
return -e.getErrno();
}
}
int CryFuse::unlink(const path &path) {
//printf("unlink(%s)\n", path.c_str());
try {
_device->unlink(path);
return 0;
} catch(cryfs::CryErrnoException &e) {
return -e.getErrno();
}
}
int CryFuse::rmdir(const path &path) {
try {
_device->rmdir(path);
return 0;
} catch(cryfs::CryErrnoException &e) {
return -e.getErrno();
}
}
//TODO
int CryFuse::symlink(const path &from, const path &to) {
printf("NOT IMPLEMENTED: symlink(%s, %s)\n", from.c_str(), to.c_str());
//auto real_from = _device->RootDir() / from;
//auto real_to = _device->RootDir() / to;
//int retstat = ::symlink(real_from.c_str(), real_to.c_str());
//return errcode_map(retstat);
return ENOSYS;
}
int CryFuse::rename(const path &from, const path &to) {
//printf("rename(%s, %s)\n", from.c_str(), to.c_str());
try {
_device->rename(from, to);
return 0;
} catch(cryfs::CryErrnoException &e) {
return -e.getErrno();
}
}
//TODO
int CryFuse::link(const path &from, const path &to) {
printf("NOT IMPLEMENTED: link(%s, %s)\n", from.c_str(), to.c_str());
//auto real_from = _device->RootDir() / from;
//auto real_to = _device->RootDir() / to;
//int retstat = ::link(real_from.c_str(), real_to.c_str());
//return errcode_map(retstat);
return ENOSYS;
}
//TODO
int CryFuse::chmod(const path &path, mode_t mode) {
printf("NOT IMPLEMENTED: chmod(%s, %d)\n", path.c_str(), mode);
//auto real_path = _device->RootDir() / path;
//int retstat = ::chmod(real_path.c_str(), mode);
//return errcode_map(retstat);
return ENOSYS;
}
//TODO
int CryFuse::chown(const path &path, uid_t uid, gid_t gid) {
printf("NOT IMPLEMENTED: chown(%s, %d, %d)\n", path.c_str(), uid, gid);
//auto real_path = _device->RootDir() / path;
//int retstat = ::chown(real_path.c_str(), uid, gid);
//return errcode_map(retstat);
return ENOSYS;
}
int CryFuse::truncate(const path &path, off_t size) {
//printf("truncate(%s, %zu)\n", path.c_str(), size);
try {
_device->truncate(path, size);
return 0;
} catch (CryErrnoException &e) {
return -e.getErrno();
}
}
int CryFuse::ftruncate(const path &path, off_t size, fuse_file_info *fileinfo) {
//printf("ftruncate(%s, %zu, _)\n", path.c_str(), size);
UNUSED(path);
try {
_device->ftruncate(fileinfo->fh, size);
return 0;
} catch (CryErrnoException &e) {
return -e.getErrno();
}
}
//TODO
int CryFuse::utimens(const path &path, const timespec times[2]) {
//printf("utimens(%s, _)\n", path.c_str());
try {
_device->utimens(path, times);
return 0;
} catch (CryErrnoException &e) {
return -e.getErrno();
}
}
int CryFuse::open(const path &path, fuse_file_info *fileinfo) {
//printf("open(%s, _)\n", path.c_str());
try {
fileinfo->fh = _device->openFile(path, fileinfo->flags);
return 0;
} catch (CryErrnoException &e) {
return -e.getErrno();
}
}
int CryFuse::release(const path &path, fuse_file_info *fileinfo) {
//printf("release(%s, _)\n", path.c_str());
UNUSED(path);
try {
_device->closeFile(fileinfo->fh);
return 0;
} catch (CryErrnoException &e) {
return -e.getErrno();
}
}
int CryFuse::read(const path &path, char *buf, size_t size, off_t offset, fuse_file_info *fileinfo) {
//printf("read(%s, _, %zu, %zu, _)\n", path.c_str(), size, offset);
UNUSED(path);
try {
//printf("Reading from file %d\n", fileinfo->fh);
//fflush(stdout);
return _device->read(fileinfo->fh, buf, size, offset);
} catch (CryErrnoException &e) {
return -e.getErrno();
}
}
int CryFuse::write(const path &path, const char *buf, size_t size, off_t offset, fuse_file_info *fileinfo) {
//printf("write(%s, _, %zu, %zu, _)\n", path.c_str(), size, offset);
UNUSED(path);
try {
_device->write(fileinfo->fh, buf, size, offset);
return size;
} catch (CryErrnoException &e) {
return -e.getErrno();
}
}
//TODO
int CryFuse::statfs(const path &path, struct statvfs *fsstat) {
//printf("statfs(%s, _)\n", path.c_str());
try {
_device->statfs(path, fsstat);
return 0;
} catch (CryErrnoException &e) {
return -e.getErrno();
}
}
//TODO
int CryFuse::flush(const path &path, fuse_file_info *fileinfo) {
//printf("Called non-implemented flush(%s, _)\n", path.c_str());
UNUSED(path);
UNUSED(fileinfo);
return 0;
}
int CryFuse::fsync(const path &path, int datasync, fuse_file_info *fileinfo) {
//printf("fsync(%s, %d, _)\n", path.c_str(), datasync);
UNUSED(path);
try {
if (datasync) {
_device->fdatasync(fileinfo->fh);
} else {
_device->fsync(fileinfo->fh);
}
return 0;
} catch (CryErrnoException &e) {
return -e.getErrno();
}
}
int CryFuse::opendir(const path &path, fuse_file_info *fileinfo) {
//printf("opendir(%s, _)\n", path.c_str());
try {
fileinfo->fh = _device->openDir(path);
return 0;
} catch(CryErrnoException &e) {
return -e.getErrno();
}
}
int CryFuse::readdir(const path &path, void *buf, fuse_fill_dir_t filler, off_t offset, fuse_file_info *fileinfo) {
UNUSED(path);
//printf("readdir(%s, _, _, %zu, _)\n", path.c_str(), offset);
UNUSED(offset);
try {
auto entries = _device->readDir(fileinfo->fh);
for (const auto &entry : *entries) {
//TODO Also give file attributes (third param of filler)
if (filler(buf, entry.c_str(), nullptr, 0) != 0) {
return -ENOMEM;
}
}
return 0;
} catch (CryErrnoException &e) {
return -e.getErrno();
}
}
int CryFuse::releasedir(const path &path, fuse_file_info *fileinfo) {
//printf("releasedir(%s, _)\n", path.c_str());
UNUSED(path);
try {
_device->closeDir(fileinfo->fh);
return 0;
} catch (CryErrnoException &e) {
return -e.getErrno();
}
}
//TODO
int CryFuse::fsyncdir(const path &path, int datasync, fuse_file_info *fileinfo) {
UNUSED(fileinfo);
UNUSED(datasync);
UNUSED(path);
//printf("Called non-implemented fsyncdir(%s, %d, _)\n", path.c_str(), datasync);
return 0;
}
void CryFuse::init(fuse_conn_info *conn) {
UNUSED(conn);
//printf("init()\n");
}
void CryFuse::destroy() {
//printf("destroy()\n");
}
int CryFuse::access(const path &path, int mask) {
//printf("access(%s, %d)\n", path.c_str(), mask);
try {
_device->access(path, mask);
return 0;
} catch (CryErrnoException &e) {
return -e.getErrno();
}
}
int CryFuse::create(const path &path, mode_t mode, fuse_file_info *fileinfo) {
//printf("create(%s, %d, _)\n", path.c_str(), mode);
try {
fileinfo->fh = _device->createAndOpenFile(path, mode);
return 0;
} catch (CryErrnoException &e) {
return -e.getErrno();
}
}
} /* namespace cryfs */
<|endoftext|> |
<commit_before>#include "CryFuse.h"
#include <sys/types.h>
#include <sys/time.h>
#include <dirent.h>
#include <cassert>
#include "cryfs_lib/CryNode.h"
#include "cryfs_lib/CryErrnoException.h"
#define UNUSED(expr) (void)(expr)
using fusepp::path;
namespace cryfs {
namespace {
int errcode_map(int exit_status) {
if (exit_status < 0) {
return -errno;
}
return exit_status;
}
}
CryFuse::CryFuse(CryDevice *device)
:_device(device) {
}
int CryFuse::getattr(const path &path, struct stat *stbuf) {
try {
_device->lstat(path, stbuf);
return 0;
} catch(cryfs::CryErrnoException &e) {
return -e.getErrno();
}
}
int CryFuse::fgetattr(const path &path, struct stat *stbuf, fuse_file_info *fileinfo) {
//printf("fgetattr(%s, _, _)\n", path.c_str());
// On FreeBSD, trying to do anything with the mountpoint ends up
// opening it, and then using the FD for an fgetattr. So in the
// special case of a path of "/", I need to do a getattr on the
// underlying root directory instead of doing the fgetattr().
if (path.native() == "/") {
return getattr(path, stbuf);
}
try {
_device->fstat(fileinfo->fh, stbuf);
return 0;
} catch(cryfs::CryErrnoException &e) {
return -e.getErrno();
}
}
int CryFuse::readlink(const path &path, char *buf, size_t size) {
//printf("readlink(%s, _, %zu)\n", path.c_str(), size);
auto real_path = _device->RootDir() / path;
//size-1, because the fuse readlink() function includes the null terminating byte in the buffer size,
//but the posix version does not and also doesn't append one.
int real_size = ::readlink(real_path.c_str(), buf, size-1);
if (real_size < 0) {
return -errno;
}
//Terminate the string
buf[real_size] = '\0';
return 0;
}
int CryFuse::mknod(const path &path, mode_t mode, dev_t rdev) {
UNUSED(rdev);
UNUSED(mode);
UNUSED(path);
printf("Called non-implemented mknod(%s, %d, _)\n", path.c_str(), mode);
return 0;
}
int CryFuse::mkdir(const path &path, mode_t mode) {
//printf("mkdir(%s, %d)\n", path.c_str(), mode);
auto real_path = _device->RootDir() / path;
int retstat = ::mkdir(real_path.c_str(), mode);
return errcode_map(retstat);
}
int CryFuse::unlink(const path &path) {
//printf("unlink(%s)\n", path.c_str());
auto real_path = _device->RootDir() / path;
int retstat = ::unlink(real_path.c_str());
return errcode_map(retstat);
}
int CryFuse::rmdir(const path &path) {
//printf("rmdir(%s)\n", path.c_str());
auto real_path = _device->RootDir() / path;
int retstat = ::rmdir(real_path.c_str());
return errcode_map(retstat);
}
int CryFuse::symlink(const path &from, const path &to) {
//printf("symlink(%s, %s)\n", from.c_str(), to.c_str());
auto real_from = _device->RootDir() / from;
auto real_to = _device->RootDir() / to;
int retstat = ::symlink(real_from.c_str(), real_to.c_str());
return errcode_map(retstat);
}
int CryFuse::rename(const path &from, const path &to) {
//printf("rename(%s, %s)\n", from.c_str(), to.c_str());
auto real_from = _device->RootDir() / from;
auto real_to = _device->RootDir() / to;
int retstat = ::rename(real_from.c_str(), real_to.c_str());
return errcode_map(retstat);
}
int CryFuse::link(const path &from, const path &to) {
//printf("link(%s, %s)\n", from.c_str(), to.c_str());
auto real_from = _device->RootDir() / from;
auto real_to = _device->RootDir() / to;
int retstat = ::link(real_from.c_str(), real_to.c_str());
return errcode_map(retstat);
}
int CryFuse::chmod(const path &path, mode_t mode) {
//printf("chmod(%s, %d)\n", path.c_str(), mode);
auto real_path = _device->RootDir() / path;
int retstat = ::chmod(real_path.c_str(), mode);
return errcode_map(retstat);
}
int CryFuse::chown(const path &path, uid_t uid, gid_t gid) {
//printf("chown(%s, %d, %d)\n", path.c_str(), uid, gid);
auto real_path = _device->RootDir() / path;
int retstat = ::chown(real_path.c_str(), uid, gid);
return errcode_map(retstat);
}
int CryFuse::truncate(const path &path, off_t size) {
//printf("truncate(%s, %zu)\n", path.c_str(), size);
auto real_path = _device->RootDir() / path;
int retstat = ::truncate(real_path.c_str(), size);
return errcode_map(retstat);
}
int CryFuse::ftruncate(const path &path, off_t size, fuse_file_info *fileinfo) {
//printf("ftruncate(%s, %zu, _)\n", path.c_str(), size);
UNUSED(path);
int retstat = ::ftruncate(fileinfo->fh, size);
return errcode_map(retstat);
}
int CryFuse::utimens(const path &path, const timespec times[2]) {
//printf("utimens(%s, _)\n", path.c_str());
auto real_path = _device->RootDir() / path;
struct timeval tv[2];
tv[0].tv_sec = times[0].tv_sec;
tv[0].tv_usec = times[0].tv_nsec / 1000;
tv[1].tv_sec = times[1].tv_sec;
tv[1].tv_usec = times[1].tv_nsec / 1000;
int retstat = ::lutimes(real_path.c_str(), tv);
return errcode_map(retstat);
}
int CryFuse::open(const path &path, fuse_file_info *fileinfo) {
//printf("open(%s, _)\n", path.c_str());
auto real_path = _device->RootDir() / path;
int fd = ::open(real_path.c_str(), fileinfo->flags);
if (fd < 0) {
return -errno;
}
fileinfo->fh = fd;
return 0;
}
int CryFuse::release(const path &path, fuse_file_info *fileinfo) {
//printf("release(%s, _)\n", path.c_str());
UNUSED(path);
int retstat = ::close(fileinfo->fh);
return errcode_map(retstat);
}
int CryFuse::read(const path &path, char *buf, size_t size, off_t offset, fuse_file_info *fileinfo) {
//printf("read(%s, _, %zu, %zu, _)\n", path.c_str(), size, offset);
UNUSED(path);
int retstat = ::pread(fileinfo->fh, buf, size, offset);
return errcode_map(retstat);
}
int CryFuse::write(const path &path, const char *buf, size_t size, off_t offset, fuse_file_info *fileinfo) {
//printf("write(%s, _, %zu, %zu, _)\n", path.c_str(), size, offset);
UNUSED(path);
int retstat = ::pwrite(fileinfo->fh, buf, size, offset);
return errcode_map(retstat);
}
int CryFuse::statfs(const path &path, struct statvfs *fsstat) {
//printf("statfs(%s, _)\n", path.c_str());
auto real_path = _device->RootDir() / path;
int retstat = ::statvfs(real_path.c_str(), fsstat);
return errcode_map(retstat);
}
int CryFuse::flush(const path &path, fuse_file_info *fileinfo) {
//printf("Called non-implemented flush(%s, _)\n", path.c_str());
UNUSED(path);
UNUSED(fileinfo);
return 0;
}
int CryFuse::fsync(const path &path, int datasync, fuse_file_info *fileinfo) {
//printf("fsync(%s, %d, _)\n", path.c_str(), datasync);
UNUSED(path);
int retstat = 0;
if (datasync) {
retstat = ::fdatasync(fileinfo->fh);
} else {
retstat = ::fsync(fileinfo->fh);
}
return errcode_map(retstat);
}
int CryFuse::opendir(const path &path, fuse_file_info *fileinfo) {
//printf("opendir(%s, _)\n", path.c_str());
auto real_path = _device->RootDir() / path;
DIR *dp = ::opendir(real_path.c_str());
if (dp == nullptr) {
return -errno;
}
fileinfo->fh = (intptr_t)dp;
return 0;
}
int CryFuse::readdir(const path &path, void *buf, fuse_fill_dir_t filler, off_t offset, fuse_file_info *fileinfo) {
//printf("readdir(%s, _, _, %zu, _)\n", path.c_str(), offset);
UNUSED(offset);
auto real_path = _device->RootDir() / path;
DIR *dp = (DIR*)(uintptr_t)fileinfo->fh;
struct dirent *de = ::readdir(dp);
if (de == nullptr) {
return -errno;
}
do {
if (filler(buf, de->d_name, nullptr, 0) != 0) {
return -ENOMEM;
}
} while ((de = ::readdir(dp)) != nullptr);
return 0;
}
int CryFuse::releasedir(const path &path, fuse_file_info *fileinfo) {
//printf("releasedir(%s, _)\n", path.c_str());
UNUSED(path);
int retstat = closedir((DIR*)(uintptr_t)fileinfo->fh);
return errcode_map(retstat);
}
int CryFuse::fsyncdir(const path &path, int datasync, fuse_file_info *fileinfo) {
UNUSED(fileinfo);
UNUSED(datasync);
UNUSED(path);
//printf("Called non-implemented fsyncdir(%s, %d, _)\n", path.c_str(), datasync);
return 0;
}
void CryFuse::init(fuse_conn_info *conn) {
UNUSED(conn);
//printf("init()\n");
}
void CryFuse::destroy() {
//printf("destroy()\n");
}
int CryFuse::access(const path &path, int mask) {
//printf("access(%s, %d)\n", path.c_str(), mask);
auto real_path = _device->RootDir() / path;
int retstat = ::access(real_path.c_str(), mask);
return errcode_map(retstat);
}
int CryFuse::create(const path &path, mode_t mode, fuse_file_info *fileinfo) {
//printf("create(%s, %d, _)\n", path.c_str(), mode);
auto real_path = _device->RootDir() / path;
int fd = ::creat(real_path.c_str(), mode);
if (fd < 0) {
return -errno;
}
fileinfo->fh = fd;
return 0;
}
} /* namespace cryfs */
<commit_msg>Implemented file operations using our class hierarchy<commit_after>#include "CryFuse.h"
#include <sys/types.h>
#include <sys/time.h>
#include <dirent.h>
#include <cassert>
#include "cryfs_lib/CryNode.h"
#include "cryfs_lib/CryErrnoException.h"
#define UNUSED(expr) (void)(expr)
using fusepp::path;
namespace cryfs {
namespace {
int errcode_map(int exit_status) {
if (exit_status < 0) {
return -errno;
}
return exit_status;
}
}
CryFuse::CryFuse(CryDevice *device)
:_device(device) {
}
int CryFuse::getattr(const path &path, struct stat *stbuf) {
try {
_device->lstat(path, stbuf);
return 0;
} catch(cryfs::CryErrnoException &e) {
return -e.getErrno();
}
}
int CryFuse::fgetattr(const path &path, struct stat *stbuf, fuse_file_info *fileinfo) {
//printf("fgetattr(%s, _, _)\n", path.c_str());
// On FreeBSD, trying to do anything with the mountpoint ends up
// opening it, and then using the FD for an fgetattr. So in the
// special case of a path of "/", I need to do a getattr on the
// underlying root directory instead of doing the fgetattr().
// TODO Check if necessary
if (path.native() == "/") {
return getattr(path, stbuf);
}
try {
_device->fstat(fileinfo->fh, stbuf);
return 0;
} catch(cryfs::CryErrnoException &e) {
return -e.getErrno();
}
}
//TODO
int CryFuse::readlink(const path &path, char *buf, size_t size) {
//printf("readlink(%s, _, %zu)\n", path.c_str(), size);
auto real_path = _device->RootDir() / path;
//size-1, because the fuse readlink() function includes the null terminating byte in the buffer size,
//but the posix version does not and also doesn't append one.
int real_size = ::readlink(real_path.c_str(), buf, size-1);
if (real_size < 0) {
return -errno;
}
//Terminate the string
buf[real_size] = '\0';
return 0;
}
int CryFuse::mknod(const path &path, mode_t mode, dev_t rdev) {
UNUSED(rdev);
UNUSED(mode);
UNUSED(path);
printf("Called non-implemented mknod(%s, %d, _)\n", path.c_str(), mode);
return 0;
}
//TODO
int CryFuse::mkdir(const path &path, mode_t mode) {
//printf("mkdir(%s, %d)\n", path.c_str(), mode);
auto real_path = _device->RootDir() / path;
int retstat = ::mkdir(real_path.c_str(), mode);
return errcode_map(retstat);
}
//TODO
int CryFuse::unlink(const path &path) {
//printf("unlink(%s)\n", path.c_str());
auto real_path = _device->RootDir() / path;
int retstat = ::unlink(real_path.c_str());
return errcode_map(retstat);
}
//TODO
int CryFuse::rmdir(const path &path) {
//printf("rmdir(%s)\n", path.c_str());
auto real_path = _device->RootDir() / path;
int retstat = ::rmdir(real_path.c_str());
return errcode_map(retstat);
}
//TODO
int CryFuse::symlink(const path &from, const path &to) {
//printf("symlink(%s, %s)\n", from.c_str(), to.c_str());
auto real_from = _device->RootDir() / from;
auto real_to = _device->RootDir() / to;
int retstat = ::symlink(real_from.c_str(), real_to.c_str());
return errcode_map(retstat);
}
//TODO
int CryFuse::rename(const path &from, const path &to) {
//printf("rename(%s, %s)\n", from.c_str(), to.c_str());
auto real_from = _device->RootDir() / from;
auto real_to = _device->RootDir() / to;
int retstat = ::rename(real_from.c_str(), real_to.c_str());
return errcode_map(retstat);
}
//TODO
int CryFuse::link(const path &from, const path &to) {
//printf("link(%s, %s)\n", from.c_str(), to.c_str());
auto real_from = _device->RootDir() / from;
auto real_to = _device->RootDir() / to;
int retstat = ::link(real_from.c_str(), real_to.c_str());
return errcode_map(retstat);
}
//TODO
int CryFuse::chmod(const path &path, mode_t mode) {
//printf("chmod(%s, %d)\n", path.c_str(), mode);
auto real_path = _device->RootDir() / path;
int retstat = ::chmod(real_path.c_str(), mode);
return errcode_map(retstat);
}
//TODO
int CryFuse::chown(const path &path, uid_t uid, gid_t gid) {
//printf("chown(%s, %d, %d)\n", path.c_str(), uid, gid);
auto real_path = _device->RootDir() / path;
int retstat = ::chown(real_path.c_str(), uid, gid);
return errcode_map(retstat);
}
int CryFuse::truncate(const path &path, off_t size) {
//printf("truncate(%s, %zu)\n", path.c_str(), size);
try {
_device->truncate(path, size);
return 0;
} catch (CryErrnoException &e) {
return -e.getErrno();
}
}
int CryFuse::ftruncate(const path &path, off_t size, fuse_file_info *fileinfo) {
//printf("ftruncate(%s, %zu, _)\n", path.c_str(), size);
UNUSED(path);
try {
_device->ftruncate(fileinfo->fh, size);
return 0;
} catch (CryErrnoException &e) {
return -e.getErrno();
}
}
//TODO
int CryFuse::utimens(const path &path, const timespec times[2]) {
//printf("utimens(%s, _)\n", path.c_str());
auto real_path = _device->RootDir() / path;
struct timeval tv[2];
tv[0].tv_sec = times[0].tv_sec;
tv[0].tv_usec = times[0].tv_nsec / 1000;
tv[1].tv_sec = times[1].tv_sec;
tv[1].tv_usec = times[1].tv_nsec / 1000;
int retstat = ::lutimes(real_path.c_str(), tv);
return errcode_map(retstat);
}
int CryFuse::open(const path &path, fuse_file_info *fileinfo) {
//printf("open(%s, _)\n", path.c_str());
try {
fileinfo->fh = _device->openFile(path, fileinfo->flags);
return 0;
} catch (CryErrnoException &e) {
return -e.getErrno();
}
}
int CryFuse::release(const path &path, fuse_file_info *fileinfo) {
//printf("release(%s, _)\n", path.c_str());
UNUSED(path);
try {
_device->closeFile(fileinfo->fh);
return 0;
} catch (CryErrnoException &e) {
return -e.getErrno();
}
}
int CryFuse::read(const path &path, char *buf, size_t size, off_t offset, fuse_file_info *fileinfo) {
//printf("read(%s, _, %zu, %zu, _)\n", path.c_str(), size, offset);
UNUSED(path);
try {
_device->read(fileinfo->fh, buf, size, offset);
return 0;
} catch (CryErrnoException &e) {
return -e.getErrno();
}
}
int CryFuse::write(const path &path, const char *buf, size_t size, off_t offset, fuse_file_info *fileinfo) {
//printf("write(%s, _, %zu, %zu, _)\n", path.c_str(), size, offset);
UNUSED(path);
try {
_device->write(fileinfo->fh, buf, size, offset);
return 0;
} catch (CryErrnoException &e) {
return -e.getErrno();
}
}
//TODO
int CryFuse::statfs(const path &path, struct statvfs *fsstat) {
//printf("statfs(%s, _)\n", path.c_str());
auto real_path = _device->RootDir() / path;
int retstat = ::statvfs(real_path.c_str(), fsstat);
return errcode_map(retstat);
}
//TODO
int CryFuse::flush(const path &path, fuse_file_info *fileinfo) {
//printf("Called non-implemented flush(%s, _)\n", path.c_str());
UNUSED(path);
UNUSED(fileinfo);
return 0;
}
int CryFuse::fsync(const path &path, int datasync, fuse_file_info *fileinfo) {
//printf("fsync(%s, %d, _)\n", path.c_str(), datasync);
UNUSED(path);
try {
if (datasync) {
_device->fdatasync(fileinfo->fh);
} else {
_device->fsync(fileinfo->fh);
}
return 0;
} catch (CryErrnoException &e) {
return -e.getErrno();
}
}
//TODO
int CryFuse::opendir(const path &path, fuse_file_info *fileinfo) {
//printf("opendir(%s, _)\n", path.c_str());
auto real_path = _device->RootDir() / path;
DIR *dp = ::opendir(real_path.c_str());
if (dp == nullptr) {
return -errno;
}
fileinfo->fh = (intptr_t)dp;
return 0;
}
//TODO
int CryFuse::readdir(const path &path, void *buf, fuse_fill_dir_t filler, off_t offset, fuse_file_info *fileinfo) {
//printf("readdir(%s, _, _, %zu, _)\n", path.c_str(), offset);
UNUSED(offset);
auto real_path = _device->RootDir() / path;
DIR *dp = (DIR*)(uintptr_t)fileinfo->fh;
struct dirent *de = ::readdir(dp);
if (de == nullptr) {
return -errno;
}
do {
if (filler(buf, de->d_name, nullptr, 0) != 0) {
return -ENOMEM;
}
} while ((de = ::readdir(dp)) != nullptr);
return 0;
}
//TODO
int CryFuse::releasedir(const path &path, fuse_file_info *fileinfo) {
//printf("releasedir(%s, _)\n", path.c_str());
UNUSED(path);
int retstat = closedir((DIR*)(uintptr_t)fileinfo->fh);
return errcode_map(retstat);
}
//TODO
int CryFuse::fsyncdir(const path &path, int datasync, fuse_file_info *fileinfo) {
UNUSED(fileinfo);
UNUSED(datasync);
UNUSED(path);
//printf("Called non-implemented fsyncdir(%s, %d, _)\n", path.c_str(), datasync);
return 0;
}
void CryFuse::init(fuse_conn_info *conn) {
UNUSED(conn);
//printf("init()\n");
}
void CryFuse::destroy() {
//printf("destroy()\n");
}
int CryFuse::access(const path &path, int mask) {
//printf("access(%s, %d)\n", path.c_str(), mask);
try {
_device->access(path, mask);
return 0;
} catch (CryErrnoException &e) {
return -e.getErrno();
}
}
int CryFuse::create(const path &path, mode_t mode, fuse_file_info *fileinfo) {
//printf("create(%s, %d, _)\n", path.c_str(), mode);
try {
fileinfo->fh = _device->createFile(path, mode);
return 0;
} catch (CryErrnoException &e) {
return -e.getErrno();
}
}
} /* namespace cryfs */
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Library
Module: Cylinder.cc
Language: C++
Date: $Date$
Version: $Revision$
This file is part of the Visualization Library. No part of this file
or its contents may be copied, reproduced or altered in any way
without the express written consent of the authors.
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994
=========================================================================*/
#include "Cylinder.hh"
// Description
// Construct cylinder with height of 1.0 and radius of 0.5.
vlCylinder::vlCylinder()
{
this->Height = 1.0;
this->Radius = 0.5;
}
// Description
// Evaluate cylinder equation R^2 - ((x-x0)^2 + (y-y0)^2 + (z-z0)^2) = 0.
float vlCylinder::EvaluateFunction(float x[3])
{
return 0;
}
// Description
// Evaluate cylinder function gradient.
void vlCylinder::EvaluateGradient(float x[3], float g[3])
{
}
void vlCylinder::PrintSelf(ostream& os, vlIndent indent)
{
vlImplicitFunction::PrintSelf(os,indent);
os << indent << "Height: " << this->Height << "\n";
os << indent << "Radius: " << this->Radius << "\n";
}
<commit_msg>ENH: Final definition.<commit_after>/*=========================================================================
Program: Visualization Library
Module: Cylinder.cc
Language: C++
Date: $Date$
Version: $Revision$
This file is part of the Visualization Library. No part of this file
or its contents may be copied, reproduced or altered in any way
without the express written consent of the authors.
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994
=========================================================================*/
#include "Cylinder.hh"
// Description
// Construct cylinder radius of 0.5.
vlCylinder::vlCylinder()
{
this->Radius = 0.5;
}
// Description
// Evaluate cylinder equation R^2 - ((x-x0)^2 + (y-y0)^2 + (z-z0)^2) = 0.
float vlCylinder::EvaluateFunction(float x[3])
{
return 0;
}
// Description
// Evaluate cylinder function gradient.
void vlCylinder::EvaluateGradient(float x[3], float g[3])
{
}
void vlCylinder::PrintSelf(ostream& os, vlIndent indent)
{
vlImplicitFunction::PrintSelf(os,indent);
os << indent << "Radius: " << this->Radius << "\n";
}
<|endoftext|> |
<commit_before>///////////////////////////////////////////////////////////////////////////////
// BOSSA
//
// Copyright (c) 2011-2012, ShumaTech
// 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 <organization> 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 <COPYRIGHT HOLDER> 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 <string>
#include <exception>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include "Flasher.h"
using namespace std;
void
Flasher::progressBar(int num, int div)
{
int ticks;
int bars = 30;
printf("\r[");
ticks = num * bars / div;
while (ticks-- > 0)
{
putchar('=');
bars--;
}
while (bars-- > 0)
{
putchar(' ');
}
printf("] %d%% (%d/%d pages)", num * 100 / div, num, div);
fflush(stdout);
}
void
Flasher::erase()
{
printf("Erase flash\n");
_flash->eraseAll();
_flash->eraseAuto(false);
}
void
Flasher::write(const char* filename)
{
FILE* infile;
uint32_t pageSize = _flash->pageSize();
uint32_t pageNum = 0;
uint32_t numPages;
long fsize;
size_t fbytes;
infile = fopen(filename, "rb");
if (!infile)
throw FileOpenError(errno);
try
{
if (fseek(infile, 0, SEEK_END) != 0 ||
(fsize = ftell(infile)) < 0)
throw FileIoError(errno);
rewind(infile);
numPages = (fsize + pageSize - 1) / pageSize;
if (numPages > _flash->numPages())
throw FileSizeError();
printf("Write %ld bytes to flash (%u pages)\n", fsize, numPages);
if (_flash->isWriteBufferAvailable()) {
// If multi-page write is available....
const uint32_t BLK_SIZE = 4096;
uint32_t offset = 0;
uint8_t buffer[BLK_SIZE];
memset(buffer, 0, BLK_SIZE);
while ((fbytes = fread(buffer, 1, BLK_SIZE, infile)) > 0)
{
if (fbytes < BLK_SIZE) {
// Ceil to nearest pagesize
fbytes = (fbytes + pageSize - 1) / pageSize * pageSize;
}
_flash->loadBuffer(buffer, fbytes);
_flash->writeBuffer(offset, fbytes);
offset += fbytes;
progressBar(offset/pageSize, numPages);
memset(buffer, 0, BLK_SIZE);
}
} else {
// ...otherwise go with the legacy slow method
uint8_t buffer[pageSize];
while ((fbytes = fread(buffer, 1, pageSize, infile)) > 0)
{
// print once every 10%
if ((pageNum % (numPages/10)) == 0)
progressBar(pageNum, numPages);
_flash->loadBuffer(buffer, fbytes);
_flash->writePage(pageNum);
pageNum++;
if (pageNum == numPages || fbytes != pageSize)
break;
}
progressBar(pageNum, numPages);
}
printf("\n");
}
catch(...)
{
fclose(infile);
throw;
}
fclose(infile);
}
bool
Flasher::verify(const char* filename)
{
FILE* infile;
uint32_t pageSize = _flash->pageSize();
uint8_t bufferA[pageSize];
uint8_t bufferB[pageSize];
uint32_t pageNum = 0;
uint32_t numPages;
uint32_t byteErrors = 0;
uint32_t pageErrors = 0;
uint32_t totalErrors = 0;
long fsize;
size_t fbytes;
infile = fopen(filename, "rb");
if (!infile)
throw FileOpenError(errno);
if (fseek(infile, 0, SEEK_END) != 0 || (fsize = ftell(infile)) < 0)
throw FileIoError(errno);
rewind(infile);
// If checksum buffer is available, use it...
if (_flash->isChecksumBufferAvailable()) {
bool failed = false;
try
{
printf("Verify %ld bytes of flash with checksum.\n", fsize);
// Perform checksum every 4096 bytes
uint32_t BLK_SIZE = 4096;
uint8_t buffer[BLK_SIZE];
uint32_t offset = 0;
while ((fbytes = fread(buffer, 1, BLK_SIZE, infile)) > 0) {
uint32_t i;
uint16_t crc = 0;
for (i=0; i<fbytes; i++)
crc = _flash->crc16AddByte(buffer[i], crc);
uint16_t flashCrc = _flash->checksumBuffer(offset, fbytes);
offset += fbytes;
if (crc != flashCrc) {
failed = true;
break;
}
}
}
catch(...)
{
fclose(infile);
throw;
}
fclose(infile);
if (failed)
{
printf("Verify failed\n");
return false;
}
printf("Verify successful\n");
return true;
}
// ...otherwise go with the slow legacy method...
try
{
numPages = (fsize + pageSize - 1) / pageSize;
if (numPages > _flash->numPages())
throw FileSizeError();
printf("Verify %ld bytes of flash\n", fsize);
while ((fbytes = fread(bufferA, 1, pageSize, infile)) > 0)
{
// print once every 10%
if ((pageNum % (numPages/10)) == 0)
progressBar(pageNum, numPages);
_flash->readPage(pageNum, bufferB);
byteErrors = 0;
for (uint32_t i = 0; i < fbytes; i++)
{
if (bufferA[i] != bufferB[i])
byteErrors++;
}
if (byteErrors != 0)
{
pageErrors++;
totalErrors += byteErrors;
}
pageNum++;
if (pageNum == numPages || fbytes != pageSize)
break;
}
progressBar(pageNum, numPages);
printf("\n");
}
catch(...)
{
fclose(infile);
throw;
}
fclose(infile);
if (byteErrors != 0)
{
printf("Verify failed\n");
printf("Page errors: %d\n", pageErrors);
printf("Byte errors: %d\n", totalErrors);
return false;
}
printf("Verify successful\n");
return true;
}
void
Flasher::read(const char* filename, long fsize)
{
FILE* outfile;
uint32_t pageSize = _flash->pageSize();
uint8_t buffer[pageSize];
uint32_t pageNum = 0;
uint32_t numPages;
size_t fbytes;
if (fsize == 0)
fsize = pageSize * _flash->numPages();
outfile = fopen(filename, "wb");
if (!outfile)
throw FileOpenError(errno);
try
{
numPages = (fsize + pageSize - 1) / pageSize;
if (numPages > _flash->numPages())
throw FileSizeError();
printf("Read %ld bytes from flash\n", fsize);
for (pageNum = 0; pageNum < numPages; pageNum++)
{
// updated from one print per 10 pages to one per 10 percent
if ((pageNum < 10) || (pageNum % (numPages/10) == 0))
progressBar(pageNum, numPages);
_flash->readPage(pageNum, buffer);
if (pageNum == numPages - 1 && fsize % pageSize > 0)
pageSize = fsize % pageSize;
fbytes = fwrite(buffer, 1, pageSize, outfile);
if (fbytes != pageSize)
throw FileShortError();
}
progressBar(pageNum, numPages);
printf("\n");
}
catch(...)
{
fclose(outfile);
throw;
}
fclose(outfile);
}
void
Flasher::lock(string& regionArg, bool enable)
{
if (regionArg.empty())
{
printf("%s all regions\n", enable ? "Lock" : "Unlock");
if (enable)
_flash->lockAll();
else
_flash->unlockAll();
}
else
{
size_t pos = 0;
size_t delim;
uint32_t region;
string sub;
do
{
delim = regionArg.find(',', pos);
sub = regionArg.substr(pos, delim - pos);
region = strtol(sub.c_str(), NULL, 0);
printf("%s region %d\n", enable ? "Lock" : "Unlock", region);
_flash->setLockRegion(region, enable);
pos = delim + 1;
} while (delim != string::npos);
}
}
void
Flasher::info(Samba& samba)
{
bool first;
printf("Device : %s\n", _flash->name().c_str());
printf("Chip ID : %08x\n", samba.chipId());
printf("Version : %s\n", samba.version().c_str());
printf("Address : %d\n", _flash->address());
printf("Pages : %d\n", _flash->numPages());
printf("Page Size : %d bytes\n", _flash->pageSize());
printf("Total Size : %dKB\n", _flash->numPages() * _flash->pageSize() / 1024);
printf("Planes : %d\n", _flash->numPlanes());
printf("Lock Regions : %d\n", _flash->lockRegions());
printf("Locked : ");
first = true;
for (uint32_t region = 0; region < _flash->lockRegions(); region++)
{
if (_flash->getLockRegion(region))
{
printf("%s%d", first ? "" : ",", region);
first = false;
}
}
printf("%s\n", first ? "none" : "");
printf("Security : %s\n", _flash->getSecurity() ? "true" : "false");
if (_flash->canBootFlash())
printf("Boot Flash : %s\n", _flash->getBootFlash() ? "true" : "false");
if (_flash->canBod())
printf("BOD : %s\n", _flash->getBod() ? "true" : "false");
if (_flash->canBor())
printf("BOR : %s\n", _flash->getBor() ? "true" : "false");
if (samba.isChipEraseAvailable())
printf("Arduino : FAST_CHIP_ERASE\n");
if (samba.isWriteBufferAvailable())
printf("Arduino : FAST_MULTI_PAGE_WRITE\n");
if (samba.isChecksumBufferAvailable())
printf("Arduino : CAN_CHECKSUM_MEMORY_BUFFER\n");
}
<commit_msg>Fix division by zero<commit_after>///////////////////////////////////////////////////////////////////////////////
// BOSSA
//
// Copyright (c) 2011-2012, ShumaTech
// 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 <organization> 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 <COPYRIGHT HOLDER> 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 <string>
#include <exception>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include "Flasher.h"
using namespace std;
void
Flasher::progressBar(int num, int div)
{
int ticks;
int bars = 30;
printf("\r[");
ticks = num * bars / div;
while (ticks-- > 0)
{
putchar('=');
bars--;
}
while (bars-- > 0)
{
putchar(' ');
}
printf("] %d%% (%d/%d pages)", num * 100 / div, num, div);
fflush(stdout);
}
void
Flasher::erase()
{
printf("Erase flash\n");
_flash->eraseAll();
_flash->eraseAuto(false);
}
void
Flasher::write(const char* filename)
{
FILE* infile;
uint32_t pageSize = _flash->pageSize();
uint32_t pageNum = 0;
uint32_t numPages;
long fsize;
size_t fbytes;
infile = fopen(filename, "rb");
if (!infile)
throw FileOpenError(errno);
try
{
if (fseek(infile, 0, SEEK_END) != 0 ||
(fsize = ftell(infile)) < 0)
throw FileIoError(errno);
rewind(infile);
numPages = (fsize + pageSize - 1) / pageSize;
if (numPages > _flash->numPages())
throw FileSizeError();
printf("Write %ld bytes to flash (%u pages)\n", fsize, numPages);
if (_flash->isWriteBufferAvailable()) {
// If multi-page write is available....
const uint32_t BLK_SIZE = 4096;
uint32_t offset = 0;
uint8_t buffer[BLK_SIZE];
memset(buffer, 0, BLK_SIZE);
while ((fbytes = fread(buffer, 1, BLK_SIZE, infile)) > 0)
{
if (fbytes < BLK_SIZE) {
// Ceil to nearest pagesize
fbytes = (fbytes + pageSize - 1) / pageSize * pageSize;
}
_flash->loadBuffer(buffer, fbytes);
_flash->writeBuffer(offset, fbytes);
offset += fbytes;
progressBar(offset/pageSize, numPages);
memset(buffer, 0, BLK_SIZE);
}
} else {
// ...otherwise go with the legacy slow method
uint8_t buffer[pageSize];
const uint32_t divisor = (numPages / 10) ? (numPages / 10) : 1;
while ((fbytes = fread(buffer, 1, pageSize, infile)) > 0)
{
if ((pageNum % divisor) == 0)
progressBar(pageNum, numPages);
_flash->loadBuffer(buffer, fbytes);
_flash->writePage(pageNum);
pageNum++;
if (pageNum == numPages || fbytes != pageSize)
break;
}
progressBar(pageNum, numPages);
}
printf("\n");
}
catch(...)
{
fclose(infile);
throw;
}
fclose(infile);
}
bool
Flasher::verify(const char* filename)
{
FILE* infile;
uint32_t pageSize = _flash->pageSize();
uint8_t bufferA[pageSize];
uint8_t bufferB[pageSize];
uint32_t pageNum = 0;
uint32_t numPages;
uint32_t byteErrors = 0;
uint32_t pageErrors = 0;
uint32_t totalErrors = 0;
long fsize;
size_t fbytes;
infile = fopen(filename, "rb");
if (!infile)
throw FileOpenError(errno);
if (fseek(infile, 0, SEEK_END) != 0 || (fsize = ftell(infile)) < 0)
throw FileIoError(errno);
rewind(infile);
// If checksum buffer is available, use it...
if (_flash->isChecksumBufferAvailable()) {
bool failed = false;
try
{
printf("Verify %ld bytes of flash with checksum.\n", fsize);
// Perform checksum every 4096 bytes
uint32_t BLK_SIZE = 4096;
uint8_t buffer[BLK_SIZE];
uint32_t offset = 0;
while ((fbytes = fread(buffer, 1, BLK_SIZE, infile)) > 0) {
uint32_t i;
uint16_t crc = 0;
for (i=0; i<fbytes; i++)
crc = _flash->crc16AddByte(buffer[i], crc);
uint16_t flashCrc = _flash->checksumBuffer(offset, fbytes);
offset += fbytes;
if (crc != flashCrc) {
failed = true;
break;
}
}
}
catch(...)
{
fclose(infile);
throw;
}
fclose(infile);
if (failed)
{
printf("Verify failed\n");
return false;
}
printf("Verify successful\n");
return true;
}
// ...otherwise go with the slow legacy method...
try
{
numPages = (fsize + pageSize - 1) / pageSize;
if (numPages > _flash->numPages())
throw FileSizeError();
printf("Verify %ld bytes of flash\n", fsize);
const uint32_t divisor = (numPages / 10) ? (numPages / 10) : 1;
while ((fbytes = fread(bufferA, 1, pageSize, infile)) > 0)
{
if ((pageNum % divisor) == 0)
progressBar(pageNum, numPages);
_flash->readPage(pageNum, bufferB);
byteErrors = 0;
for (uint32_t i = 0; i < fbytes; i++)
{
if (bufferA[i] != bufferB[i])
byteErrors++;
}
if (byteErrors != 0)
{
pageErrors++;
totalErrors += byteErrors;
}
pageNum++;
if (pageNum == numPages || fbytes != pageSize)
break;
}
progressBar(pageNum, numPages);
printf("\n");
}
catch(...)
{
fclose(infile);
throw;
}
fclose(infile);
if (byteErrors != 0)
{
printf("Verify failed\n");
printf("Page errors: %d\n", pageErrors);
printf("Byte errors: %d\n", totalErrors);
return false;
}
printf("Verify successful\n");
return true;
}
void
Flasher::read(const char* filename, long fsize)
{
FILE* outfile;
uint32_t pageSize = _flash->pageSize();
uint8_t buffer[pageSize];
uint32_t pageNum = 0;
uint32_t numPages;
size_t fbytes;
if (fsize == 0)
fsize = pageSize * _flash->numPages();
outfile = fopen(filename, "wb");
if (!outfile)
throw FileOpenError(errno);
try
{
numPages = (fsize + pageSize - 1) / pageSize;
if (numPages > _flash->numPages())
throw FileSizeError();
printf("Read %ld bytes from flash\n", fsize);
for (pageNum = 0; pageNum < numPages; pageNum++)
{
// updated from one print per 10 pages to one per 10 percent
if ((pageNum < 10) || (pageNum % (numPages/10) == 0))
progressBar(pageNum, numPages);
_flash->readPage(pageNum, buffer);
if (pageNum == numPages - 1 && fsize % pageSize > 0)
pageSize = fsize % pageSize;
fbytes = fwrite(buffer, 1, pageSize, outfile);
if (fbytes != pageSize)
throw FileShortError();
}
progressBar(pageNum, numPages);
printf("\n");
}
catch(...)
{
fclose(outfile);
throw;
}
fclose(outfile);
}
void
Flasher::lock(string& regionArg, bool enable)
{
if (regionArg.empty())
{
printf("%s all regions\n", enable ? "Lock" : "Unlock");
if (enable)
_flash->lockAll();
else
_flash->unlockAll();
}
else
{
size_t pos = 0;
size_t delim;
uint32_t region;
string sub;
do
{
delim = regionArg.find(',', pos);
sub = regionArg.substr(pos, delim - pos);
region = strtol(sub.c_str(), NULL, 0);
printf("%s region %d\n", enable ? "Lock" : "Unlock", region);
_flash->setLockRegion(region, enable);
pos = delim + 1;
} while (delim != string::npos);
}
}
void
Flasher::info(Samba& samba)
{
bool first;
printf("Device : %s\n", _flash->name().c_str());
printf("Chip ID : %08x\n", samba.chipId());
printf("Version : %s\n", samba.version().c_str());
printf("Address : %d\n", _flash->address());
printf("Pages : %d\n", _flash->numPages());
printf("Page Size : %d bytes\n", _flash->pageSize());
printf("Total Size : %dKB\n", _flash->numPages() * _flash->pageSize() / 1024);
printf("Planes : %d\n", _flash->numPlanes());
printf("Lock Regions : %d\n", _flash->lockRegions());
printf("Locked : ");
first = true;
for (uint32_t region = 0; region < _flash->lockRegions(); region++)
{
if (_flash->getLockRegion(region))
{
printf("%s%d", first ? "" : ",", region);
first = false;
}
}
printf("%s\n", first ? "none" : "");
printf("Security : %s\n", _flash->getSecurity() ? "true" : "false");
if (_flash->canBootFlash())
printf("Boot Flash : %s\n", _flash->getBootFlash() ? "true" : "false");
if (_flash->canBod())
printf("BOD : %s\n", _flash->getBod() ? "true" : "false");
if (_flash->canBor())
printf("BOR : %s\n", _flash->getBor() ? "true" : "false");
if (samba.isChipEraseAvailable())
printf("Arduino : FAST_CHIP_ERASE\n");
if (samba.isWriteBufferAvailable())
printf("Arduino : FAST_MULTI_PAGE_WRITE\n");
if (samba.isChecksumBufferAvailable())
printf("Arduino : CAN_CHECKSUM_MEMORY_BUFFER\n");
}
<|endoftext|> |
<commit_before>#ifdef STAN_OPENCL
#include <stan/math/prim/mat.hpp>
#include <gtest/gtest.h>
#include <CL/cl.hpp>
TEST(MathMatrix, kernel_initialize) {
stan::math::get_context();
cl::Kernel kernel_transpose = stan::math::get_kernel("transpose");
EXPECT_NO_THROW(cl::Kernel kernel_transpose
= stan::math::get_kernel("transpose"));
EXPECT_NO_THROW(cl::Kernel kernel_copy = stan::math::get_kernel("copy"));
EXPECT_NO_THROW(cl::Kernel kernel_zeros = stan::math::get_kernel("zeros"));
EXPECT_NO_THROW(cl::Kernel kernel_identity
= stan::math::get_kernel("identity"));
EXPECT_NO_THROW(cl::Kernel kernel_copy_triangular
= stan::math::get_kernel("copy_triangular"));
EXPECT_NO_THROW(cl::Kernel kernel_scalar_copy_triangular_transposed
= stan::math::get_kernel("copy_triangular_transposed"));
EXPECT_NO_THROW(cl::Kernel kernel_add = stan::math::get_kernel("add"));
EXPECT_NO_THROW(cl::Kernel kernel_subtract
= stan::math::get_kernel("subtract"));
EXPECT_NO_THROW(cl::Kernel kernel_copy_submatrix
= stan::math::get_kernel("copy_submatrix"));
EXPECT_NO_THROW(cl::Kernel kernel_scalar_mul_diagonal
= stan::math::get_kernel("scalar_mul_diagonal"));
EXPECT_NO_THROW(cl::Kernel kernel_scalar_mul
= stan::math::get_kernel("scalar_mul"));
EXPECT_NO_THROW(cl::Kernel kernel_basic_multiply
= stan::math::get_kernel("basic_multiply"));
EXPECT_NO_THROW(cl::Kernel kernel_multiply_self_transposed
= stan::math::get_kernel("multiply_self_transposed"));
EXPECT_NO_THROW(cl::Kernel kernel_lower_tri_inv_step1
= stan::math::get_kernel("lower_tri_inv_step1"));
EXPECT_NO_THROW(cl::Kernel kernel_lower_tri_inv_step2
= stan::math::get_kernel("lower_tri_inv_step2"));
EXPECT_NO_THROW(cl::Kernel kernel_lower_tri_inv_step3
= stan::math::get_kernel("lower_tri_inv_step3"));
EXPECT_NO_THROW(cl::Kernel kernel_chol_block
= stan::math::get_kernel("cholesky_block"));
EXPECT_NO_THROW(cl::Kernel kernel_check_nan
= stan::math::get_kernel("check_nan"));
EXPECT_NO_THROW(cl::Kernel kernel_check_diagonal_zeros
= stan::math::get_kernel("check_diagonal_zeros"));
EXPECT_NO_THROW(cl::Kernel kernel_check_symmetric
= stan::math::get_kernel("check_symmetric"));
}
#else
#include <gtest/gtest.h>
TEST(MathMatrix, kernel_initializeDummy) { EXPECT_NO_THROW(); }
#endif
<commit_msg>[Jenkins] auto-formatting by clang-format version 5.0.1-svn319952-1~exp1 (branches/release_50)<commit_after>#ifdef STAN_OPENCL
#include <stan/math/prim/mat.hpp>
#include <gtest/gtest.h>
#include <CL/cl.hpp>
TEST(MathMatrix, kernel_initialize) {
stan::math::get_context();
cl::Kernel kernel_transpose = stan::math::get_kernel("transpose");
EXPECT_NO_THROW(cl::Kernel kernel_transpose
= stan::math::get_kernel("transpose"));
EXPECT_NO_THROW(cl::Kernel kernel_copy = stan::math::get_kernel("copy"));
EXPECT_NO_THROW(cl::Kernel kernel_zeros = stan::math::get_kernel("zeros"));
EXPECT_NO_THROW(cl::Kernel kernel_identity
= stan::math::get_kernel("identity"));
EXPECT_NO_THROW(cl::Kernel kernel_copy_triangular
= stan::math::get_kernel("copy_triangular"));
EXPECT_NO_THROW(cl::Kernel kernel_scalar_copy_triangular_transposed
= stan::math::get_kernel("copy_triangular_transposed"));
EXPECT_NO_THROW(cl::Kernel kernel_add = stan::math::get_kernel("add"));
EXPECT_NO_THROW(cl::Kernel kernel_subtract
= stan::math::get_kernel("subtract"));
EXPECT_NO_THROW(cl::Kernel kernel_copy_submatrix
= stan::math::get_kernel("copy_submatrix"));
EXPECT_NO_THROW(cl::Kernel kernel_scalar_mul_diagonal
= stan::math::get_kernel("scalar_mul_diagonal"));
EXPECT_NO_THROW(cl::Kernel kernel_scalar_mul
= stan::math::get_kernel("scalar_mul"));
EXPECT_NO_THROW(cl::Kernel kernel_basic_multiply
= stan::math::get_kernel("basic_multiply"));
EXPECT_NO_THROW(cl::Kernel kernel_multiply_self_transposed
= stan::math::get_kernel("multiply_self_transposed"));
EXPECT_NO_THROW(cl::Kernel kernel_lower_tri_inv_step1
= stan::math::get_kernel("lower_tri_inv_step1"));
EXPECT_NO_THROW(cl::Kernel kernel_lower_tri_inv_step2
= stan::math::get_kernel("lower_tri_inv_step2"));
EXPECT_NO_THROW(cl::Kernel kernel_lower_tri_inv_step3
= stan::math::get_kernel("lower_tri_inv_step3"));
EXPECT_NO_THROW(cl::Kernel kernel_chol_block
= stan::math::get_kernel("cholesky_block"));
EXPECT_NO_THROW(cl::Kernel kernel_check_nan
= stan::math::get_kernel("check_nan"));
EXPECT_NO_THROW(cl::Kernel kernel_check_diagonal_zeros
= stan::math::get_kernel("check_diagonal_zeros"));
EXPECT_NO_THROW(cl::Kernel kernel_check_symmetric
= stan::math::get_kernel("check_symmetric"));
}
#else
#include <gtest/gtest.h>
TEST(MathMatrix, kernel_initializeDummy) { EXPECT_NO_THROW(); }
#endif
<|endoftext|> |
<commit_before>/* Copyright (c) 2016, Fengping Bao <[email protected]>
*
* 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" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "HPacker.h"
#include "hpack_huffman_table.h"
#include <math.h>
namespace hpack {
static char *huffDecodeBits(char *dst, uint8_t bits, uint8_t *state, bool *ending) {
const auto &entry = huff_decode_table[*state][bits];
if ((entry.flags & NGHTTP2_HUFF_FAIL) != 0)
return nullptr;
if ((entry.flags & NGHTTP2_HUFF_SYM) != 0)
*dst++ = entry.sym;
*state = entry.state;
*ending = (entry.flags & NGHTTP2_HUFF_ACCEPTED) != 0;
return dst;
}
static int huffDecode(const uint8_t *src, size_t len, std::string &str) {
uint8_t state = 0;
bool ending = false;
const uint8_t *src_end = src + len;
std::vector<char> sbuf;
sbuf.resize(2*len);
char *ptr = &sbuf[0];
for (; src != src_end; ++src) {
if ((ptr = huffDecodeBits(ptr, *src >> 4, &state, &ending)) == nullptr)
return -1;
if ((ptr = huffDecodeBits(ptr, *src & 0xf, &state, &ending)) == nullptr)
return -1;
}
if (!ending) {
return -1;
}
int slen = int(ptr - &sbuf[0]);
str.assign(&sbuf[0], slen);
return slen;
}
static int huffEncode(const std::string &str, uint8_t *buf, size_t len) {
uint8_t *ptr = buf;
const uint8_t *end = buf + len;
const char* src = str.c_str();
const char* src_end = src + str.length();
uint64_t current = 0;
uint32_t n = 0;
for (; src != src_end;) {
const auto &sym = huff_sym_table[*src++];
uint32_t code = sym.code;
uint32_t nbits = sym.nbits;
current <<= nbits;
current |= code;
n += nbits;
while (n >= 8) {
n -= 8;
*ptr++ = current >> n;
}
}
if (n > 0) {
current <<= (8 - n);
current |= (0xFF >> n);
*ptr++ = current;
}
return int(ptr - buf);
}
static uint32_t huffEncodeLength(const std::string &str)
{
uint32_t len = 0;
for (char c : str) {
len += huff_sym_table[c].nbits;
}
return (len + 7) >> 3;
}
static int encodeInteger(uint8_t N, uint64_t I, uint8_t *buf, size_t len) {
uint8_t *ptr = buf;
const uint8_t *end = buf + len;
if (ptr == end) {
return -1;
}
uint8_t NF = (1 << N) - 1;
if (I < NF) {
*ptr &= NF ^ 0xFF;
*ptr |= I;
return 1;
}
*ptr++ |= NF;
I -= NF;
while (ptr < end && I >= 128) {
*ptr++ = I % 128 + 128;
I /= 128;
}
if (ptr == end) {
return -1;
}
*ptr++ = I;
return int(ptr - buf);
}
static int encodeString(const std::string &str, uint8_t *buf, size_t len) {
uint8_t *ptr = buf;
uint8_t *end = buf + len;
int slen = int(str.length());
int hlen = huffEncodeLength(str);
if (hlen < slen) {
*ptr = 0x80;
int ret = encodeInteger(7, hlen, ptr, end - ptr);
if (ret <= 0) {
return -1;
}
ptr += ret;
ret = huffEncode(str, ptr, end - ptr);
if (ret < 0) {
return -1;
}
ptr += ret;
} else {
*ptr = 0;
int ret = encodeInteger(7, slen, ptr, end - ptr);
if (ret <= 0) {
return -1;
}
ptr += ret;
if (end - ptr < str.length()) {
return -1;
}
memcpy(ptr, str.c_str(), str.length());
ptr += str.length();
}
return int(ptr - buf);
}
static int decodeInteger(uint8_t N, const uint8_t *buf, size_t len, uint64_t &I) {
if (N > 8) {
return -1;
}
const uint8_t *ptr = buf;
const uint8_t *end = buf + len;
if (ptr == end) {
return -1;
}
uint8_t NF = (1 << N) - 1;
uint8_t prefix = (*ptr++) & NF;
if (prefix < NF) {
I = prefix;
return 1;
}
if (ptr == end) {
return -1;
}
int m = 0;
uint64_t u64 = prefix;
uint8_t b = 0;
do {
b = *ptr++;
u64 += (b & 127) * pow(2, m);
m += 7;
} while (ptr < end && (b & 128));
if (ptr == end && (b & 128)) {
return -1;
}
I = u64;
return int(ptr - buf);
}
static int decodeString(const uint8_t *buf, size_t len, std::string &str)
{
const uint8_t *ptr = buf;
const uint8_t *end = buf + len;
if (ptr == end) {
return -1;
}
bool H = *ptr & 0x80;
uint64_t slen = 0;
int ret = decodeInteger(7, ptr, end - ptr, slen);
if (ret <= 0) {
return -1;
}
ptr += ret;
if ( slen > end - ptr) {
return -1;
}
if (H) {
if(huffDecode(ptr, slen, str) < 0) {
return -1;
}
} else {
str.assign((const char*)ptr, slen);
}
ptr += slen;
return int(ptr - buf);
}
enum class PrefixType {
INDEXED_HEADER,
LITERAL_HEADER_WITH_INDEXING,
LITERAL_HEADER_WITHOUT_INDEXING,
TABLE_SIZE_UPDATE
};
static int decodePrefix(const uint8_t *buf, size_t len, PrefixType &type, uint64_t &I) {
const uint8_t *ptr = buf;
const uint8_t *end = buf + len;
uint8_t N = 0;
if (*ptr & 0x80) {
N = 7;
type = PrefixType::INDEXED_HEADER;
} else if (*ptr & 0x40) {
N = 6;
type = PrefixType::LITERAL_HEADER_WITH_INDEXING;
} else if (*ptr & 0x20) {
N = 5;
type = PrefixType::TABLE_SIZE_UPDATE;
} else {
N = 4;
type = PrefixType::LITERAL_HEADER_WITHOUT_INDEXING;
}
int ret = decodeInteger(N, ptr, end - ptr, I);
if (ret <= 0) {
return -1;
}
ptr += ret;
return int(ptr - buf);
}
HPacker::IndexingType HPacker::getIndexingType(const std::string &name, const std::string &value)
{
if (query_cb_) {
return query_cb_(name, value);
}
if (name == "cookie" || name == ":authority" || name == "user-agent" || name == "pragma") {
return IndexingType::ALL;
}
return IndexingType::NONE;
}
int HPacker::encodeSizeUpdate(int sz, uint8_t *buf, size_t len)
{
uint8_t *ptr = buf;
const uint8_t *end = buf + len;
*ptr = 0x20;
int ret = encodeInteger(5, sz, ptr, end - ptr);
if (ret <= 0) {
return -1;
}
ptr += ret;
return int(ptr - buf);
}
int HPacker::encodeHeader(const std::string &name, const std::string &value, uint8_t *buf, size_t len)
{
uint8_t *ptr = buf;
const uint8_t *end = buf + len;
bool valueIndexed = false;
int index = table_.getIndex(name, value, valueIndexed);
bool addToTable = false;
if (index != -1) {
uint8_t N = 0;
if (valueIndexed) { // name and value indexed
*ptr = 0x80;
N = 7;
} else { // name indexed
IndexingType idxType = getIndexingType(name, value);
if (idxType == IndexingType::ALL) {
*ptr = 0x40;
N = 6;
addToTable = true;
} else {
*ptr = 0x10;
N = 4;
}
}
// encode prefix Bits
int ret = encodeInteger(N, index, ptr, end - ptr);
if (ret <= 0) {
return -1;
}
ptr += ret;
if (!valueIndexed) {
ret = encodeString(value, ptr, end - ptr);
if (ret <= 0) {
return -1;
}
ptr += ret;
}
} else {
IndexingType idxType = getIndexingType(name, value);
if (idxType == IndexingType::ALL) {
*ptr++ = 0x40;
addToTable = true;
} else {
*ptr++ = 0x10;
}
int ret = encodeString(name, ptr, end - ptr);
if (ret <= 0) {
return -1;
}
ptr += ret;
ret = encodeString(value, ptr, end - ptr);
if (ret <= 0) {
return -1;
}
ptr += ret;
}
if (addToTable) {
table_.addHeader(name, value);
}
return int(ptr - buf);
}
int HPacker::encode(const KeyValueVector &headers, uint8_t *buf, size_t len) {
table_.setMode(true);
uint8_t *ptr = buf;
const uint8_t *end = buf + len;
if (updateTableSize_) {
updateTableSize_ = false;
int ret = encodeSizeUpdate(int(table_.getLimitSize()), ptr, end - ptr);
if (ret <= 0) {
return -1;
}
ptr += ret;
}
for (const auto &hdr : headers) {
int ret = encodeHeader(hdr.first, hdr.second, ptr, end - ptr);
if (ret <= 0) {
return -1;
}
ptr += ret;
}
return int(ptr - buf);
}
int HPacker::decode(const uint8_t *buf, size_t len, KeyValueVector &headers) {
table_.setMode(false);
const uint8_t *ptr = buf;
const uint8_t *end = buf + len;
headers.clear();
while (ptr < end) {
std::string name;
std::string value;
PrefixType type;
uint64_t I = 0;
int ret = decodePrefix(ptr, end - ptr, type, I);
if (ret <= 0) {
return -1;
}
ptr += ret;
if (PrefixType::INDEXED_HEADER == type) {
if (!table_.getIndexedName(int(I), name) || !table_.getIndexedValue(int(I), value)) {
return -1;
}
} else if (PrefixType::LITERAL_HEADER_WITH_INDEXING == type ||
PrefixType::LITERAL_HEADER_WITHOUT_INDEXING == type) {
if (0 == I) {
ret = decodeString(ptr, end - ptr, name);
if (ret <= 0) {
return -1;
}
ptr += ret;
} else if (!table_.getIndexedName(int(I), name)) {
return -1;
}
ret = decodeString(ptr, end - ptr, value);
if (ret <= 0) {
return -1;
}
ptr += ret;
if (PrefixType::LITERAL_HEADER_WITH_INDEXING == type) {
table_.addHeader(name, value);
}
} else if (PrefixType::TABLE_SIZE_UPDATE == type) {
if (I > table_.getMaxSize()) {
return -1;
}
table_.updateLimitSize(I);
continue;
}
headers.emplace_back(std::make_pair(name, value));
}
return int(len);
}
} // namespace hpack
<commit_msg>fix build failure on linux<commit_after>/* Copyright (c) 2016, Fengping Bao <[email protected]>
*
* 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" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "HPacker.h"
#include "hpack_huffman_table.h"
#include <math.h>
#include <string.h> // for memcpy
namespace hpack {
static char *huffDecodeBits(char *dst, uint8_t bits, uint8_t *state, bool *ending) {
const auto &entry = huff_decode_table[*state][bits];
if ((entry.flags & NGHTTP2_HUFF_FAIL) != 0)
return nullptr;
if ((entry.flags & NGHTTP2_HUFF_SYM) != 0)
*dst++ = entry.sym;
*state = entry.state;
*ending = (entry.flags & NGHTTP2_HUFF_ACCEPTED) != 0;
return dst;
}
static int huffDecode(const uint8_t *src, size_t len, std::string &str) {
uint8_t state = 0;
bool ending = false;
const uint8_t *src_end = src + len;
std::vector<char> sbuf;
sbuf.resize(2*len);
char *ptr = &sbuf[0];
for (; src != src_end; ++src) {
if ((ptr = huffDecodeBits(ptr, *src >> 4, &state, &ending)) == nullptr)
return -1;
if ((ptr = huffDecodeBits(ptr, *src & 0xf, &state, &ending)) == nullptr)
return -1;
}
if (!ending) {
return -1;
}
int slen = int(ptr - &sbuf[0]);
str.assign(&sbuf[0], slen);
return slen;
}
static int huffEncode(const std::string &str, uint8_t *buf, size_t len) {
uint8_t *ptr = buf;
const uint8_t *end = buf + len;
const char* src = str.c_str();
const char* src_end = src + str.length();
uint64_t current = 0;
uint32_t n = 0;
for (; src != src_end;) {
const auto &sym = huff_sym_table[*src++];
uint32_t code = sym.code;
uint32_t nbits = sym.nbits;
current <<= nbits;
current |= code;
n += nbits;
while (n >= 8) {
n -= 8;
*ptr++ = current >> n;
}
}
if (n > 0) {
current <<= (8 - n);
current |= (0xFF >> n);
*ptr++ = current;
}
return int(ptr - buf);
}
static uint32_t huffEncodeLength(const std::string &str)
{
uint32_t len = 0;
for (char c : str) {
len += huff_sym_table[c].nbits;
}
return (len + 7) >> 3;
}
static int encodeInteger(uint8_t N, uint64_t I, uint8_t *buf, size_t len) {
uint8_t *ptr = buf;
const uint8_t *end = buf + len;
if (ptr == end) {
return -1;
}
uint8_t NF = (1 << N) - 1;
if (I < NF) {
*ptr &= NF ^ 0xFF;
*ptr |= I;
return 1;
}
*ptr++ |= NF;
I -= NF;
while (ptr < end && I >= 128) {
*ptr++ = I % 128 + 128;
I /= 128;
}
if (ptr == end) {
return -1;
}
*ptr++ = I;
return int(ptr - buf);
}
static int encodeString(const std::string &str, uint8_t *buf, size_t len) {
uint8_t *ptr = buf;
uint8_t *end = buf + len;
int slen = int(str.length());
int hlen = huffEncodeLength(str);
if (hlen < slen) {
*ptr = 0x80;
int ret = encodeInteger(7, hlen, ptr, end - ptr);
if (ret <= 0) {
return -1;
}
ptr += ret;
ret = huffEncode(str, ptr, end - ptr);
if (ret < 0) {
return -1;
}
ptr += ret;
} else {
*ptr = 0;
int ret = encodeInteger(7, slen, ptr, end - ptr);
if (ret <= 0) {
return -1;
}
ptr += ret;
if (end - ptr < str.length()) {
return -1;
}
memcpy(ptr, str.c_str(), str.length());
ptr += str.length();
}
return int(ptr - buf);
}
static int decodeInteger(uint8_t N, const uint8_t *buf, size_t len, uint64_t &I) {
if (N > 8) {
return -1;
}
const uint8_t *ptr = buf;
const uint8_t *end = buf + len;
if (ptr == end) {
return -1;
}
uint8_t NF = (1 << N) - 1;
uint8_t prefix = (*ptr++) & NF;
if (prefix < NF) {
I = prefix;
return 1;
}
if (ptr == end) {
return -1;
}
int m = 0;
uint64_t u64 = prefix;
uint8_t b = 0;
do {
b = *ptr++;
u64 += (b & 127) * pow(2, m);
m += 7;
} while (ptr < end && (b & 128));
if (ptr == end && (b & 128)) {
return -1;
}
I = u64;
return int(ptr - buf);
}
static int decodeString(const uint8_t *buf, size_t len, std::string &str)
{
const uint8_t *ptr = buf;
const uint8_t *end = buf + len;
if (ptr == end) {
return -1;
}
bool H = *ptr & 0x80;
uint64_t slen = 0;
int ret = decodeInteger(7, ptr, end - ptr, slen);
if (ret <= 0) {
return -1;
}
ptr += ret;
if ( slen > end - ptr) {
return -1;
}
if (H) {
if(huffDecode(ptr, slen, str) < 0) {
return -1;
}
} else {
str.assign((const char*)ptr, slen);
}
ptr += slen;
return int(ptr - buf);
}
enum class PrefixType {
INDEXED_HEADER,
LITERAL_HEADER_WITH_INDEXING,
LITERAL_HEADER_WITHOUT_INDEXING,
TABLE_SIZE_UPDATE
};
static int decodePrefix(const uint8_t *buf, size_t len, PrefixType &type, uint64_t &I) {
const uint8_t *ptr = buf;
const uint8_t *end = buf + len;
uint8_t N = 0;
if (*ptr & 0x80) {
N = 7;
type = PrefixType::INDEXED_HEADER;
} else if (*ptr & 0x40) {
N = 6;
type = PrefixType::LITERAL_HEADER_WITH_INDEXING;
} else if (*ptr & 0x20) {
N = 5;
type = PrefixType::TABLE_SIZE_UPDATE;
} else {
N = 4;
type = PrefixType::LITERAL_HEADER_WITHOUT_INDEXING;
}
int ret = decodeInteger(N, ptr, end - ptr, I);
if (ret <= 0) {
return -1;
}
ptr += ret;
return int(ptr - buf);
}
HPacker::IndexingType HPacker::getIndexingType(const std::string &name, const std::string &value)
{
if (query_cb_) {
return query_cb_(name, value);
}
if (name == "cookie" || name == ":authority" || name == "user-agent" || name == "pragma") {
return IndexingType::ALL;
}
return IndexingType::NONE;
}
int HPacker::encodeSizeUpdate(int sz, uint8_t *buf, size_t len)
{
uint8_t *ptr = buf;
const uint8_t *end = buf + len;
*ptr = 0x20;
int ret = encodeInteger(5, sz, ptr, end - ptr);
if (ret <= 0) {
return -1;
}
ptr += ret;
return int(ptr - buf);
}
int HPacker::encodeHeader(const std::string &name, const std::string &value, uint8_t *buf, size_t len)
{
uint8_t *ptr = buf;
const uint8_t *end = buf + len;
bool valueIndexed = false;
int index = table_.getIndex(name, value, valueIndexed);
bool addToTable = false;
if (index != -1) {
uint8_t N = 0;
if (valueIndexed) { // name and value indexed
*ptr = 0x80;
N = 7;
} else { // name indexed
IndexingType idxType = getIndexingType(name, value);
if (idxType == IndexingType::ALL) {
*ptr = 0x40;
N = 6;
addToTable = true;
} else {
*ptr = 0x10;
N = 4;
}
}
// encode prefix Bits
int ret = encodeInteger(N, index, ptr, end - ptr);
if (ret <= 0) {
return -1;
}
ptr += ret;
if (!valueIndexed) {
ret = encodeString(value, ptr, end - ptr);
if (ret <= 0) {
return -1;
}
ptr += ret;
}
} else {
IndexingType idxType = getIndexingType(name, value);
if (idxType == IndexingType::ALL) {
*ptr++ = 0x40;
addToTable = true;
} else {
*ptr++ = 0x10;
}
int ret = encodeString(name, ptr, end - ptr);
if (ret <= 0) {
return -1;
}
ptr += ret;
ret = encodeString(value, ptr, end - ptr);
if (ret <= 0) {
return -1;
}
ptr += ret;
}
if (addToTable) {
table_.addHeader(name, value);
}
return int(ptr - buf);
}
int HPacker::encode(const KeyValueVector &headers, uint8_t *buf, size_t len) {
table_.setMode(true);
uint8_t *ptr = buf;
const uint8_t *end = buf + len;
if (updateTableSize_) {
updateTableSize_ = false;
int ret = encodeSizeUpdate(int(table_.getLimitSize()), ptr, end - ptr);
if (ret <= 0) {
return -1;
}
ptr += ret;
}
for (const auto &hdr : headers) {
int ret = encodeHeader(hdr.first, hdr.second, ptr, end - ptr);
if (ret <= 0) {
return -1;
}
ptr += ret;
}
return int(ptr - buf);
}
int HPacker::decode(const uint8_t *buf, size_t len, KeyValueVector &headers) {
table_.setMode(false);
const uint8_t *ptr = buf;
const uint8_t *end = buf + len;
headers.clear();
while (ptr < end) {
std::string name;
std::string value;
PrefixType type;
uint64_t I = 0;
int ret = decodePrefix(ptr, end - ptr, type, I);
if (ret <= 0) {
return -1;
}
ptr += ret;
if (PrefixType::INDEXED_HEADER == type) {
if (!table_.getIndexedName(int(I), name) || !table_.getIndexedValue(int(I), value)) {
return -1;
}
} else if (PrefixType::LITERAL_HEADER_WITH_INDEXING == type ||
PrefixType::LITERAL_HEADER_WITHOUT_INDEXING == type) {
if (0 == I) {
ret = decodeString(ptr, end - ptr, name);
if (ret <= 0) {
return -1;
}
ptr += ret;
} else if (!table_.getIndexedName(int(I), name)) {
return -1;
}
ret = decodeString(ptr, end - ptr, value);
if (ret <= 0) {
return -1;
}
ptr += ret;
if (PrefixType::LITERAL_HEADER_WITH_INDEXING == type) {
table_.addHeader(name, value);
}
} else if (PrefixType::TABLE_SIZE_UPDATE == type) {
if (I > table_.getMaxSize()) {
return -1;
}
table_.updateLimitSize(I);
continue;
}
headers.emplace_back(std::make_pair(name, value));
}
return int(len);
}
} // namespace hpack
<|endoftext|> |
<commit_before>/*
Flexisip, a flexible SIP proxy server with media capabilities.
Copyright (C) 2014 Belledonne Communications SARL.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "monitor.hh"
#include "configmanager.hh"
using namespace std;
Monitor::Init Monitor::sInit;
const string Monitor::PYTHON_INTERPRETOR = "/usr/bin/python2";
const string Monitor::SCRIPT_PATH = "/home/francois/projects/flexisip/flexisip_monitor/flexisip_monitor.py";
Monitor::Init::Init() {
ConfigItemDescriptor items[] = {
{ Boolean , "enable" , "Enable or disable the Flexisip monitor daemon", "false" },
{ StringList, "identities" , "List of SIP identities which will be used to test the Flexisip nodes. There must be exactly as many SIP identities as Flexisip nodes", ""},
{ Integer , "test-interval", "Time between two consecutive tests", "30"},
{ String , "logfile" , "Path to the log file", "/etc/flexisip/flexisip_monitor.log"},
{ Integer , "switch-port" , "Port to open/close folowing the test succeed or not", "12345"},
config_item_end
};
GenericStruct *s = new GenericStruct("monitor", "Flexisip monitor parameters", 0);
GenericManager::get()->getRoot()->addChild(s);
s->addChildrenValues(items);
}
void Monitor::exec(int socket) {
GenericStruct *monitorParams;
try{
monitorParams = GenericManager::get()->getRoot()->get<GenericStruct>("monitor");
}catch(FlexisipException &e) {
LOGE(e.str().c_str());
exit(-1);
}
string interval = monitorParams->get<ConfigValue>("test-interval")->get();
string logfile = monitorParams->get<ConfigString>("logfile")->read();
string port = monitorParams->get<ConfigValue>("switch-port")->get();
GenericStruct *authParams;
try{
authParams = GenericManager::get()->getRoot()->get<GenericStruct>("module::Authentication");
}catch(FlexisipException &e){
LOGE(e.str().c_str());
exit(-1);
}
list<string> identities = monitorParams->get<ConfigStringList>("identities")->read();
list<string> trustedHosts = authParams->get<ConfigStringList>("trusted-hosts")->read();
if(identities.size() != trustedHosts.size()) {
LOGE("Flexisip monitor: there is not as many SIP indentities as trusted-hosts");
exit(-1);
}
list<string> proxyConfigs;
list<string>::const_iterator itI;
list<string>::const_iterator itH;
for(itI = identities.cbegin(), itH = trustedHosts.cbegin();
itI != identities.cend();
itI++, itH++) {
string proxyURI = string("sip:") + itH->data() + string(";transport=tls");
string proxyConfig = itI->data() + string("/") + proxyURI;
proxyConfigs.push_back(proxyConfig);
}
char **args = new char *[proxyConfigs.size() + 9];
args[0] = strdup(PYTHON_INTERPRETOR.c_str());
args[1] = strdup(SCRIPT_PATH.c_str());
args[2] = strdup("--interval");
args[3] = strdup(interval.c_str());
args[4] = strdup("--log");
args[5] = strdup(logfile.c_str());
args[6] = strdup("--port");
args[7] = strdup(port.c_str());
int i=6;
for(string proxyConfig : proxyConfigs) {
args[i] = strdup(proxyConfig.c_str());
i++;
}
args[i] = NULL;
if(write(socket, "ok", 3) == -1) {
exit(-1);
}
close(socket);
execvp(args[0], args);
}
<commit_msg>Fix conf reading issue<commit_after>/*
Flexisip, a flexible SIP proxy server with media capabilities.
Copyright (C) 2014 Belledonne Communications SARL.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "monitor.hh"
#include "configmanager.hh"
#include "agent.hh"
using namespace std;
Monitor::Init Monitor::sInit;
const string Monitor::PYTHON_INTERPRETOR = "/usr/bin/python2";
const string Monitor::SCRIPT_PATH = "/home/francois/projects/flexisip/flexisip_monitor/flexisip_monitor.py";
Monitor::Init::Init() {
ConfigItemDescriptor items[] = {
{ Boolean , "enable" , "Enable or disable the Flexisip monitor daemon", "false" },
{ StringList, "identities" , "List of SIP identities which will be used to test the Flexisip nodes. There must be exactly as many SIP identities as Flexisip nodes", ""},
{ Integer , "test-interval", "Time between two consecutive tests", "30"},
{ String , "logfile" , "Path to the log file", "/etc/flexisip/flexisip_monitor.log"},
{ Integer , "switch-port" , "Port to open/close folowing the test succeed or not", "12345"},
config_item_end
};
GenericStruct *s = new GenericStruct("monitor", "Flexisip monitor parameters", 0);
GenericManager::get()->getRoot()->addChild(s);
s->addChildrenValues(items);
}
void Monitor::exec(int socket) {
// Create a temporary agent to load all modules
su_root_t *root = NULL;
shared_ptr<Agent> a = make_shared<Agent>(root);
GenericManager::get()->loadStrict();
GenericStruct *monitorParams = GenericManager::get()->getRoot()->get<GenericStruct>("monitor");
string interval = monitorParams->get<ConfigValue>("test-interval")->get();
string logfile = monitorParams->get<ConfigString>("logfile")->read();
string port = monitorParams->get<ConfigValue>("switch-port")->get();
GenericStruct *authParams = GenericManager::get()->getRoot()->get<GenericStruct>("module::Authentication");
list<string> trustedHosts = authParams->get<ConfigStringList>("trusted-hosts")->read();
list<string> identities = monitorParams->get<ConfigStringList>("identities")->read();
if(identities.size() != trustedHosts.size()) {
LOGE("Flexisip monitor: there is not as many SIP indentities as trusted-hosts");
exit(-1);
}
list<string> proxyConfigs;
list<string>::const_iterator itI;
list<string>::const_iterator itH;
for(itI = identities.cbegin(), itH = trustedHosts.cbegin();
itI != identities.cend();
itI++, itH++) {
string proxyURI = string("sip:") + itH->data() + string(";transport=tls");
string proxyConfig = itI->data() + string("/") + proxyURI;
proxyConfigs.push_back(proxyConfig);
}
char **args = new char *[proxyConfigs.size() + 9];
args[0] = strdup(PYTHON_INTERPRETOR.c_str());
args[1] = strdup(SCRIPT_PATH.c_str());
args[2] = strdup("--interval");
args[3] = strdup(interval.c_str());
args[4] = strdup("--log");
args[5] = strdup(logfile.c_str());
args[6] = strdup("--port");
args[7] = strdup(port.c_str());
int i=6;
for(string proxyConfig : proxyConfigs) {
args[i] = strdup(proxyConfig.c_str());
i++;
}
args[i] = NULL;
if(write(socket, "ok", 3) == -1) {
exit(-1);
}
close(socket);
execvp(args[0], args);
}
<|endoftext|> |
<commit_before>/*
* A wrapper for hstock/stock that allows multiple users of one
* stock_item.
*
* author: Max Kellermann <[email protected]>
*/
#include "mstock.h"
#include "hstock.h"
#include "stock.h"
#include "hashmap.h"
#include "pool.h"
#include "lease.h"
#include <daemon/log.h>
#include <map>
#include <list>
#include <string>
#include <assert.h>
struct mstock {};
class MultiStock : public mstock {
class Domain;
typedef std::map<std::string, Domain> DomainMap;
class Domain {
class Item;
typedef std::list<Item> ItemList;
class Item {
struct Lease : list_head {
static const struct lease lease;
const ItemList::iterator item;
Lease(ItemList::iterator _item):item(_item) {}
void Release(bool _reuse) {
item->DeleteLease(this, _reuse);
}
static void Release(bool reuse, void *ctx) {
((Lease *)ctx)->Release(reuse);
}
};
const DomainMap::iterator domain;
const unsigned max_leases;
stock_item &item;
unsigned n_leases;
list_head leases;
bool reuse;
public:
Item(DomainMap::iterator _domain, unsigned _max_leases,
stock_item &_item)
:domain(_domain), max_leases(_max_leases), item(_item),
n_leases(0), reuse(true) {
list_init(&leases);
}
Item(const Item &) = delete;
~Item() {
assert(n_leases == 0);
assert(list_empty(&leases));
domain->second.Put(domain->first.c_str(), item, reuse);
}
bool IsFull() const {
return n_leases >= max_leases;
}
bool CanUse() const {
return reuse && !IsFull();
}
private:
Lease &AddLease(ItemList::iterator i) {
assert(&*i == this);
++n_leases;
Lease *lease = new Lease(i);
list_add(lease, &leases);
return *lease;
}
public:
void AddLease(ItemList::iterator i,
const stock_get_handler &handler, void *ctx,
struct lease_ref &lease_ref) {
assert(&*i == this);
Lease &lease = AddLease(i);
lease_ref_set(&lease_ref, &Lease::lease, &lease);
handler.ready(&item, ctx);
}
stock_item *AddLease(ItemList::iterator i,
struct lease_ref &lease_ref) {
assert(&*i == this);
Lease &lease = AddLease(i);
lease_ref_set(&lease_ref, &Lease::lease, &lease);
return &item;
}
void DeleteLease(Lease *lease, bool _reuse) {
reuse &= _reuse;
auto ii = lease->item;
assert(n_leases > 0);
list_remove(lease);
delete lease;
--n_leases;
if (n_leases == 0)
domain->second.DeleteItem(ii);
}
};
MultiStock &stock;
struct pool *pool;
ItemList items;
public:
Domain(MultiStock &_stock, struct pool *_pool)
:stock(_stock), pool(_pool) {
}
Domain(Domain &&other)
:stock(other.stock), pool(other.pool) {
assert(other.items.empty());
other.pool = nullptr;
}
Domain(const Domain &) = delete;
~Domain() {
assert(items.empty());
if (pool != nullptr)
pool_unref(pool);
}
ItemList::iterator FindUsableItem() {
for (auto i = items.begin(), end = items.end(); i != end; ++i)
if (i->CanUse())
return i;
return items.end();
}
ItemList::iterator AddItem(DomainMap::iterator di,
unsigned max_leases,
stock_item &si) {
assert(&di->second == this);
items.emplace_front(di, max_leases, si);
return items.begin();
}
stock_item *GetNow(DomainMap::iterator di,
struct pool *caller_pool,
const char *uri, void *info,
unsigned max_leases,
struct lease_ref &lease_ref,
GError **error_r);
void DeleteItem(ItemList::iterator &ii) {
ii = items.erase(ii);
}
void Put(const char *uri, stock_item &item, bool reuse) {
stock.Put(uri, item, reuse);
}
};
struct pool *pool;
DomainMap domains;
struct hstock *hstock;
public:
MultiStock(struct pool *_pool, struct hstock *_hstock)
:pool(pool_new_libc(_pool, "mstock")),
hstock(_hstock) {}
MultiStock(const MultiStock &) = delete;
~MultiStock() {
hstock_free(hstock);
pool_unref(pool);
}
void AddStats(stock_stats &data) const {
hstock_add_stats(hstock, &data);
}
stock_item *GetNow(struct pool *caller_pool, const char *uri, void *info,
unsigned max_leases,
struct lease_ref &lease_ref,
GError **error_r);
void Put(const char *uri, stock_item &item, bool reuse) {
hstock_put(hstock, uri, &item, !reuse);
}
};
const lease MultiStock::Domain::Item::Lease::lease = {
Release,
};
stock_item *
MultiStock::Domain::GetNow(DomainMap::iterator di,
struct pool *caller_pool,
const char *uri, void *info,
unsigned max_leases,
struct lease_ref &lease_ref,
GError **error_r)
{
auto i = FindUsableItem();
if (i == items.end()) {
stock_item *item =
hstock_get_now(stock.hstock, caller_pool, uri, info,
error_r);
items.emplace_front(di, max_leases, *item);
i = items.begin();
}
return i->AddLease(i, lease_ref);
}
inline stock_item *
MultiStock::GetNow(struct pool *caller_pool, const char *uri, void *info,
unsigned max_leases,
struct lease_ref &lease_ref,
GError **error_r)
{
struct pool *domain_pool = pool_new_libc(pool, "mstock_domain");
auto di = domains.insert(std::make_pair(uri, Domain(*this, domain_pool)))
.first;
return di->second.GetNow(di, caller_pool, uri, info, max_leases,
lease_ref, error_r);
}
/*
* constructor
*
*/
struct mstock *
mstock_new(struct pool *pool, struct hstock *hstock)
{
return new MultiStock(pool, hstock);
}
void
mstock_free(struct mstock *_m)
{
MultiStock *m = (MultiStock *)_m;
delete m;
}
void
mstock_add_stats(const struct mstock *_m, stock_stats *data)
{
const MultiStock &m = *(const MultiStock *)_m;
m.AddStats(*data);
}
struct stock_item *
mstock_get_now(struct mstock *_m, struct pool *caller_pool,
const char *uri, void *info, unsigned max_leases,
struct lease_ref *lease_ref,
GError **error_r)
{
MultiStock &m = *(MultiStock *)_m;
return m.GetNow(caller_pool, uri, info, max_leases,
*lease_ref, error_r);
}
<commit_msg>mstock: use class boost::intrusive::list instead of struct list_head<commit_after>/*
* A wrapper for hstock/stock that allows multiple users of one
* stock_item.
*
* author: Max Kellermann <[email protected]>
*/
#include "mstock.h"
#include "hstock.h"
#include "stock.h"
#include "hashmap.h"
#include "pool.h"
#include "lease.h"
#include <daemon/log.h>
#include <boost/intrusive/list.hpp>
#include <map>
#include <list>
#include <string>
#include <assert.h>
struct mstock {};
class MultiStock : public mstock {
class Domain;
typedef std::map<std::string, Domain> DomainMap;
class Domain {
class Item;
typedef std::list<Item> ItemList;
class Item {
struct Lease {
static constexpr auto link_mode = boost::intrusive::normal_link;
typedef boost::intrusive::link_mode<link_mode> LinkMode;
typedef boost::intrusive::list_member_hook<LinkMode> SiblingsListHook;
SiblingsListHook siblings;
typedef boost::intrusive::member_hook<Lease,
Lease::SiblingsListHook,
&Lease::siblings> SiblingsListMemberHook;
static const struct lease lease;
const ItemList::iterator item;
Lease(ItemList::iterator _item):item(_item) {}
void Release(bool _reuse) {
item->DeleteLease(this, _reuse);
}
static void Release(bool reuse, void *ctx) {
((Lease *)ctx)->Release(reuse);
}
static void Dispose(Lease *l) {
delete l;
}
};
const DomainMap::iterator domain;
const unsigned max_leases;
stock_item &item;
boost::intrusive::list<Lease, Lease::SiblingsListMemberHook,
boost::intrusive::constant_time_size<true>> leases;
bool reuse;
public:
Item(DomainMap::iterator _domain, unsigned _max_leases,
stock_item &_item)
:domain(_domain), max_leases(_max_leases), item(_item),
reuse(true) {
}
Item(const Item &) = delete;
~Item() {
assert(leases.empty());
domain->second.Put(domain->first.c_str(), item, reuse);
}
bool IsFull() const {
return leases.size() >= max_leases;
}
bool CanUse() const {
return reuse && !IsFull();
}
private:
Lease &AddLease(ItemList::iterator i) {
assert(&*i == this);
Lease *lease = new Lease(i);
leases.push_front(*lease);
return *lease;
}
public:
void AddLease(ItemList::iterator i,
const stock_get_handler &handler, void *ctx,
struct lease_ref &lease_ref) {
assert(&*i == this);
Lease &lease = AddLease(i);
lease_ref_set(&lease_ref, &Lease::lease, &lease);
handler.ready(&item, ctx);
}
stock_item *AddLease(ItemList::iterator i,
struct lease_ref &lease_ref) {
assert(&*i == this);
Lease &lease = AddLease(i);
lease_ref_set(&lease_ref, &Lease::lease, &lease);
return &item;
}
void DeleteLease(Lease *lease, bool _reuse) {
reuse &= _reuse;
auto ii = lease->item;
assert(!leases.empty());
leases.erase_and_dispose(leases.iterator_to(*lease),
Lease::Dispose);
if (leases.empty())
domain->second.DeleteItem(ii);
}
};
MultiStock &stock;
struct pool *pool;
ItemList items;
public:
Domain(MultiStock &_stock, struct pool *_pool)
:stock(_stock), pool(_pool) {
}
Domain(Domain &&other)
:stock(other.stock), pool(other.pool) {
assert(other.items.empty());
other.pool = nullptr;
}
Domain(const Domain &) = delete;
~Domain() {
assert(items.empty());
if (pool != nullptr)
pool_unref(pool);
}
ItemList::iterator FindUsableItem() {
for (auto i = items.begin(), end = items.end(); i != end; ++i)
if (i->CanUse())
return i;
return items.end();
}
ItemList::iterator AddItem(DomainMap::iterator di,
unsigned max_leases,
stock_item &si) {
assert(&di->second == this);
items.emplace_front(di, max_leases, si);
return items.begin();
}
stock_item *GetNow(DomainMap::iterator di,
struct pool *caller_pool,
const char *uri, void *info,
unsigned max_leases,
struct lease_ref &lease_ref,
GError **error_r);
void DeleteItem(ItemList::iterator &ii) {
ii = items.erase(ii);
}
void Put(const char *uri, stock_item &item, bool reuse) {
stock.Put(uri, item, reuse);
}
};
struct pool *pool;
DomainMap domains;
struct hstock *hstock;
public:
MultiStock(struct pool *_pool, struct hstock *_hstock)
:pool(pool_new_libc(_pool, "mstock")),
hstock(_hstock) {}
MultiStock(const MultiStock &) = delete;
~MultiStock() {
hstock_free(hstock);
pool_unref(pool);
}
void AddStats(stock_stats &data) const {
hstock_add_stats(hstock, &data);
}
stock_item *GetNow(struct pool *caller_pool, const char *uri, void *info,
unsigned max_leases,
struct lease_ref &lease_ref,
GError **error_r);
void Put(const char *uri, stock_item &item, bool reuse) {
hstock_put(hstock, uri, &item, !reuse);
}
};
const lease MultiStock::Domain::Item::Lease::lease = {
Release,
};
stock_item *
MultiStock::Domain::GetNow(DomainMap::iterator di,
struct pool *caller_pool,
const char *uri, void *info,
unsigned max_leases,
struct lease_ref &lease_ref,
GError **error_r)
{
auto i = FindUsableItem();
if (i == items.end()) {
stock_item *item =
hstock_get_now(stock.hstock, caller_pool, uri, info,
error_r);
items.emplace_front(di, max_leases, *item);
i = items.begin();
}
return i->AddLease(i, lease_ref);
}
inline stock_item *
MultiStock::GetNow(struct pool *caller_pool, const char *uri, void *info,
unsigned max_leases,
struct lease_ref &lease_ref,
GError **error_r)
{
struct pool *domain_pool = pool_new_libc(pool, "mstock_domain");
auto di = domains.insert(std::make_pair(uri, Domain(*this, domain_pool)))
.first;
return di->second.GetNow(di, caller_pool, uri, info, max_leases,
lease_ref, error_r);
}
/*
* constructor
*
*/
struct mstock *
mstock_new(struct pool *pool, struct hstock *hstock)
{
return new MultiStock(pool, hstock);
}
void
mstock_free(struct mstock *_m)
{
MultiStock *m = (MultiStock *)_m;
delete m;
}
void
mstock_add_stats(const struct mstock *_m, stock_stats *data)
{
const MultiStock &m = *(const MultiStock *)_m;
m.AddStats(*data);
}
struct stock_item *
mstock_get_now(struct mstock *_m, struct pool *caller_pool,
const char *uri, void *info, unsigned max_leases,
struct lease_ref *lease_ref,
GError **error_r)
{
MultiStock &m = *(MultiStock *)_m;
return m.GetNow(caller_pool, uri, info, max_leases,
*lease_ref, error_r);
}
<|endoftext|> |
<commit_before>/*
** NDS 2SF utility class.
*/
#ifdef _WIN32
#define ZLIB_WINAPI
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <string>
#include <sstream>
#include <map>
#include <zlib.h>
#include "nds2sf.h"
#include "cbyteio.h"
#include "cpath.h"
#ifdef _WIN32
#define NOMINMAX
#include <windows.h>
#include <sys/stat.h>
#include <direct.h>
#else
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#define _chdir(s) chdir((s))
#define _mkdir(s) mkdir((s), 0777)
#define _rmdir(s) rmdir((s))
#endif
void NDS2SF::put_2sf_exe_header(uint8_t *exe, uint32_t load_offset, uint32_t rom_size)
{
mput4l(load_offset, &exe[0]);
mput4l(rom_size, &exe[4]);
}
bool NDS2SF::exe2sf(const std::string& nds2sf_path, uint8_t *exe, size_t exe_size)
{
std::map<std::string, std::string> tags;
return exe2sf(nds2sf_path, exe, exe_size, tags);
}
#define CHUNK 16384
bool NDS2SF::exe2sf(const std::string& nds2sf_path, uint8_t *exe, size_t exe_size, std::map<std::string, std::string>& tags)
{
FILE *nds2sf_file = NULL;
z_stream z;
uint8_t zbuf[CHUNK];
uLong zcrc;
uLong zlen;
int zflush;
int zret;
// check exe size
if (exe_size > MAX_NDS2SF_EXE_SIZE)
{
return false;
}
// open output file
nds2sf_file = fopen(nds2sf_path.c_str(), "wb");
if (nds2sf_file == NULL)
{
return false;
}
// write PSF header
// (EXE length and CRC will be set later)
fwrite(PSF_SIGNATURE, strlen(PSF_SIGNATURE), 1, nds2sf_file);
fputc(NDS2SF_PSF_VERSION, nds2sf_file);
fput4l(0, nds2sf_file);
fput4l(0, nds2sf_file);
fput4l(0, nds2sf_file);
// init compression
z.zalloc = Z_NULL;
z.zfree = Z_NULL;
z.opaque = Z_NULL;
if (deflateInit(&z, Z_BEST_COMPRESSION) != Z_OK)
{
return false;
}
// compress exe
z.next_in = exe;
z.avail_in = (uInt) exe_size;
z.next_out = zbuf;
z.avail_out = CHUNK;
zcrc = crc32(0L, Z_NULL, 0);
do
{
if (z.avail_in == 0)
{
zflush = Z_FINISH;
}
else
{
zflush = Z_NO_FLUSH;
}
// compress
zret = deflate(&z, zflush);
if (zret != Z_STREAM_END && zret != Z_OK)
{
deflateEnd(&z);
fclose(nds2sf_file);
return false;
}
// write compressed data
zlen = CHUNK - z.avail_out;
if (zlen != 0)
{
if (fwrite(zbuf, zlen, 1, nds2sf_file) != 1)
{
deflateEnd(&z);
fclose(nds2sf_file);
return false;
}
zcrc = crc32(zcrc, zbuf, zlen);
}
// give space for next chunk
z.next_out = zbuf;
z.avail_out = CHUNK;
} while (zret != Z_STREAM_END);
// set EXE info to PSF header
fseek(nds2sf_file, 8, SEEK_SET);
fput4l(z.total_out, nds2sf_file);
fput4l(zcrc, nds2sf_file);
fseek(nds2sf_file, 0, SEEK_END);
// end compression
deflateEnd(&z);
// write tags
if (!tags.empty())
{
fwrite(PSF_TAG_SIGNATURE, strlen(PSF_TAG_SIGNATURE), 1, nds2sf_file);
for (std::map<std::string, std::string>::iterator it = tags.begin(); it != tags.end(); ++it)
{
const std::string& key = it->first;
const std::string& value = it->second;
std::istringstream value_reader(value);
std::string line;
// process for each lines
while (std::getline(value_reader, line))
{
if (fprintf(nds2sf_file, "%s=%s\n", key.c_str(), line.c_str()) < 0)
{
fclose(nds2sf_file);
return false;
}
}
}
}
fclose(nds2sf_file);
return true;
}
bool NDS2SF::exe2sf_file(const std::string& nds_path, const std::string& nds2sf_path)
{
off_t rom_size_off = path_getfilesize(nds_path.c_str());
if (rom_size_off == -1) {
return false;
}
if (rom_size_off > MAX_NDS_ROM_SIZE) {
return false;
}
uint32_t rom_size = (uint32_t)rom_size_off;
FILE * rom_file = fopen(nds_path.c_str(), "rb");
if (rom_file == NULL) {
return false;
}
uint8_t * exe = new uint8_t[NDS2SF_EXE_HEADER_SIZE + rom_size];
if (exe == NULL) {
fclose(rom_file);
return false;
}
put_2sf_exe_header(exe, 0, rom_size);
if (fread(&exe[NDS2SF_EXE_HEADER_SIZE], 1, rom_size, rom_file) != rom_size) {
delete[] exe;
fclose(rom_file);
return false;
}
if (!exe2sf(nds2sf_path, exe, NDS2SF_EXE_HEADER_SIZE + rom_size)) {
delete[] exe;
fclose(rom_file);
return false;
}
delete[] exe;
fclose(rom_file);
return true;
}
bool NDS2SF::make_mini2sf(const std::string& nds2sf_path, uint32_t address, size_t size, uint32_t num, std::map<std::string, std::string>& tags)
{
uint8_t exe[NDS2SF_EXE_HEADER_SIZE + 4];
// limit size
if (size > 4)
{
return false;
}
// make exe
put_2sf_exe_header(exe, address, (uint32_t)size);
mput4l(num, &exe[NDS2SF_EXE_HEADER_SIZE]);
// write mini2sf file
return exe2sf(nds2sf_path, exe, NDS2SF_EXE_HEADER_SIZE + size, tags);
}
<commit_msg>Increase the size limit<commit_after>/*
** NDS 2SF utility class.
*/
#ifdef _WIN32
#define ZLIB_WINAPI
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <string>
#include <sstream>
#include <map>
#include <zlib.h>
#include "nds2sf.h"
#include "cbyteio.h"
#include "cpath.h"
#ifdef _WIN32
#define NOMINMAX
#include <windows.h>
#include <sys/stat.h>
#include <direct.h>
#else
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#define _chdir(s) chdir((s))
#define _mkdir(s) mkdir((s), 0777)
#define _rmdir(s) rmdir((s))
#endif
void NDS2SF::put_2sf_exe_header(uint8_t *exe, uint32_t load_offset, uint32_t rom_size)
{
mput4l(load_offset, &exe[0]);
mput4l(rom_size, &exe[4]);
}
bool NDS2SF::exe2sf(const std::string& nds2sf_path, uint8_t *exe, size_t exe_size)
{
std::map<std::string, std::string> tags;
return exe2sf(nds2sf_path, exe, exe_size, tags);
}
#define CHUNK 16384
bool NDS2SF::exe2sf(const std::string& nds2sf_path, uint8_t *exe, size_t exe_size, std::map<std::string, std::string>& tags)
{
FILE *nds2sf_file = NULL;
z_stream z;
uint8_t zbuf[CHUNK];
uLong zcrc;
uLong zlen;
int zflush;
int zret;
// check exe size
if (exe_size > MAX_NDS2SF_EXE_SIZE)
{
return false;
}
// open output file
nds2sf_file = fopen(nds2sf_path.c_str(), "wb");
if (nds2sf_file == NULL)
{
return false;
}
// write PSF header
// (EXE length and CRC will be set later)
fwrite(PSF_SIGNATURE, strlen(PSF_SIGNATURE), 1, nds2sf_file);
fputc(NDS2SF_PSF_VERSION, nds2sf_file);
fput4l(0, nds2sf_file);
fput4l(0, nds2sf_file);
fput4l(0, nds2sf_file);
// init compression
z.zalloc = Z_NULL;
z.zfree = Z_NULL;
z.opaque = Z_NULL;
if (deflateInit(&z, Z_BEST_COMPRESSION) != Z_OK)
{
return false;
}
// compress exe
z.next_in = exe;
z.avail_in = (uInt) exe_size;
z.next_out = zbuf;
z.avail_out = CHUNK;
zcrc = crc32(0L, Z_NULL, 0);
do
{
if (z.avail_in == 0)
{
zflush = Z_FINISH;
}
else
{
zflush = Z_NO_FLUSH;
}
// compress
zret = deflate(&z, zflush);
if (zret != Z_STREAM_END && zret != Z_OK)
{
deflateEnd(&z);
fclose(nds2sf_file);
return false;
}
// write compressed data
zlen = CHUNK - z.avail_out;
if (zlen != 0)
{
if (fwrite(zbuf, zlen, 1, nds2sf_file) != 1)
{
deflateEnd(&z);
fclose(nds2sf_file);
return false;
}
zcrc = crc32(zcrc, zbuf, zlen);
}
// give space for next chunk
z.next_out = zbuf;
z.avail_out = CHUNK;
} while (zret != Z_STREAM_END);
// set EXE info to PSF header
fseek(nds2sf_file, 8, SEEK_SET);
fput4l(z.total_out, nds2sf_file);
fput4l(zcrc, nds2sf_file);
fseek(nds2sf_file, 0, SEEK_END);
// end compression
deflateEnd(&z);
// write tags
if (!tags.empty())
{
fwrite(PSF_TAG_SIGNATURE, strlen(PSF_TAG_SIGNATURE), 1, nds2sf_file);
for (std::map<std::string, std::string>::iterator it = tags.begin(); it != tags.end(); ++it)
{
const std::string& key = it->first;
const std::string& value = it->second;
std::istringstream value_reader(value);
std::string line;
// process for each lines
while (std::getline(value_reader, line))
{
if (fprintf(nds2sf_file, "%s=%s\n", key.c_str(), line.c_str()) < 0)
{
fclose(nds2sf_file);
return false;
}
}
}
}
fclose(nds2sf_file);
return true;
}
bool NDS2SF::exe2sf_file(const std::string& nds_path, const std::string& nds2sf_path)
{
off_t rom_size_off = path_getfilesize(nds_path.c_str());
if (rom_size_off == -1) {
return false;
}
if (rom_size_off > MAX_NDS_ROM_SIZE) {
return false;
}
uint32_t rom_size = (uint32_t)rom_size_off;
FILE * rom_file = fopen(nds_path.c_str(), "rb");
if (rom_file == NULL) {
return false;
}
uint8_t * exe = new uint8_t[NDS2SF_EXE_HEADER_SIZE + rom_size];
if (exe == NULL) {
fclose(rom_file);
return false;
}
put_2sf_exe_header(exe, 0, rom_size);
if (fread(&exe[NDS2SF_EXE_HEADER_SIZE], 1, rom_size, rom_file) != rom_size) {
delete[] exe;
fclose(rom_file);
return false;
}
if (!exe2sf(nds2sf_path, exe, NDS2SF_EXE_HEADER_SIZE + rom_size)) {
delete[] exe;
fclose(rom_file);
return false;
}
delete[] exe;
fclose(rom_file);
return true;
}
bool NDS2SF::make_mini2sf(const std::string& nds2sf_path, uint32_t address, size_t size, uint32_t num, std::map<std::string, std::string>& tags)
{
uint8_t exe[NDS2SF_EXE_HEADER_SIZE + 256];
memset(exe, 0, NDS2SF_EXE_HEADER_SIZE + 256);
// limit size
if (size > 256)
{
return false;
}
// make exe
put_2sf_exe_header(exe, address, (uint32_t)size);
mput4l(num, &exe[NDS2SF_EXE_HEADER_SIZE]);
// write mini2sf file
return exe2sf(nds2sf_path, exe, NDS2SF_EXE_HEADER_SIZE + size, tags);
}
<|endoftext|> |
<commit_before>// [[Rcpp::depends(RcppArmadillo)]]
#include <RcppArmadillo.h>
#include <Rmath.h>
#include <vector>
#include <cassert>
#include "vmat.h"
#include "gmat.h"
#include "DataPairs.h"
#include "quadrule.h"
#include "pn.h"
#include "functions.h"
using namespace Rcpp;
using namespace arma;
using namespace std;
const double twopi = 2*datum::pi;
/////////////////////////////////////////////////////////////////////////////////////////////////
/* Full loglikelihood */
double loglikfull(unsigned row, DataPairs &data, const gmat &sigmaMarg, const gmat &sigmaJoint, const gmat &sigmaMargCond, vmat sigmaU, vec u, bool full=1){
data.pi_gen(row, u); // Estimation of pi based on u
irowvec causes = data.causes_get(row); // Failure causes for pair in question
double res = 0; // Initialising output (loglik contribution)
if ((causes(0) > 0) & (causes(1) > 0)){
/* Both individuals experience failure */
res = logdF2(row, causes, data, sigmaJoint, u);
}
else if((causes(0) <= 0) & (causes(1) <= 0)){
/* Neither individual experience failure */
if ((causes(0) < 0) & (causes(1) < 0)){
// Full follow-up for both individuals
for (unsigned i=1; i<=2; i++){ // Over individuals
double lik = 1;
for (unsigned j=1; j<=data.ncauses; j++){ // Over failure causes
double prob = F1(row, j, i, data);
lik -= prob;
}
res += log(lik);
}
}
else if (((causes(0) < 0) & (causes(1) == 0)) | ((causes(0) == 0) & (causes(1) < 0))){
// Full follow-up for only one individual
for (unsigned i=1; i<=2; i++){ // Over individuals
double lik = 1;
for (unsigned j=1; j<=data.ncauses; j++){ // Over failure causes
if (causes(i-1) < 0){
double prob = F1(row, j, i, data);
lik -= prob;
}
else {
double prob = F1(row, j, i, data, sigmaMarg, u);
lik -= prob;
}
}
res += log(lik);
}
}
else {
// Full follow-up for neither individual
double lik = 1;
// Marginal probabilities
for (unsigned i=1; i<=2; i++){ // Over individuals
for (unsigned j=1; j<=data.ncauses; j++){ // Over failure causes
double prob = F1(row, j, i, data, sigmaMarg, u);
lik -= prob; // Subtracting
}
}
// Bivariate probabilities
for (unsigned k=1; k<=data.ncauses; k++){ // Over failure causes
for (unsigned l=1; l<=data.ncauses; l++){
irowvec vcauses(2);
vcauses(0) = k; vcauses(1) = l;
double prob = F2(row, vcauses, data, sigmaJoint, u);
lik += prob; // Adding
}
}
res = log(lik);
}
}
else {
/* One individual experiences failure the other does not */
for (unsigned i=1; i<=2; i++){ // Over individuals
unsigned cause = causes(i-1);
if (cause > 0){
// Marginal probability of failure
res += logdF1(row, cause, i, data, sigmaMarg, u);
}
else {
// Marginal probability of no failure
unsigned cond_cause;
if (i==1){
cond_cause = causes(1);
}
else {
cond_cause = causes(0);
}
for (unsigned j=1; j<=data.ncauses; j++){ // Over failure causes
double lik = 1;
if (cause < 0){
// Unconditional
double prob = F1(row, j, i, data);
lik -= prob;
}
else {
// Conditional
double prob = F1(row, j, i, cond_cause, data, sigmaMargCond, u);
lik -= prob;
}
res += log(lik);
}
}
}
}
/* Contribution from u */
if (full){
vmat sig = sigmaU; // Variance-covariance matrix of u
double inner = as_scalar(u*sig.inv*u.t());
// PDF of u
double logpdfu = log(pow(twopi,-(data.ncauses/2))) + sig.loginvsqdet - 0.5*inner;
// Adding to the loglik
res += logpdfu;
}
/* Return */
return(res);
}
/////////////////////////////////////////////////////////////////////////////////////////////////
/* Score function of full loglikelihood */
rowvec Dloglikfull(unsigned row, DataPairs &data, const gmat &sigmaMarg, const gmat &sigmaJoint, const gmat &sigmaMargCond, vmat sigmaU, vec u, bool full=1){
/* Estimation of pi, dpidu and dlogpidu */
data.pi_gen(row, u);
data.dpidu_gen(row, u);
data.dlogpidu_gen(row, u);
irowvec causes = data.causes_get(row); // Failure causes for pair in question
rowvec res = zeros<rowvec>(data.ncauses); // Initialising output (score contribution)
if ((causes(0) > 0) & (causes(1) > 0)){
/* Both individuals experience failure */
res = dlogdF2du(row, causes, data, sigmaJoint, u);
}
else if((causes(0) <= 0) & (causes(1) <= 0)){
/* Neither individual experience failure */
if ((causes(0) < 0) & (causes(1) < 0)){
// Full follow-up for both individuals
for (unsigned i=1; i<=2; i++){ // Over individuals
double lik = 1;
rowvec likdu = zeros<rowvec>(data.ncauses);
for (unsigned j=1; j<=data.ncauses; j++){ // Over failure causes
double prob = F1(row, j, i, data);
rowvec probdu = dF1du(row, j, i, data);
lik -= prob;
likdu -= probdu;
}
res += (1/lik)*likdu;
}
}
else if (((causes(0) < 0) & (causes(1) == 0)) | ((causes(0) == 0) & (causes(1) < 0))){
// Full follow-up for only one individual
for (unsigned i=1; i<=2; i++){ // Over individuals
double lik = 1;
rowvec likdu = zeros<rowvec>(data.ncauses);
for (unsigned j=1; j<=data.ncauses; j++){ // Over failure causes
if (causes(i-1) < 0){
double prob = F1(row, j, i, data);
rowvec probdu = dF1du(row, j, i, data);
lik -= prob;
likdu -= probdu;
}
else {
double prob = F1(row, j, i, data, sigmaMarg, u);
rowvec probdu = dF1du(row, j, i, data, sigmaMarg, u);
lik -= prob;
likdu -= probdu;
}
}
res += (1/lik)*likdu;
}
}
else {
// Full follow-up for neither individual
double lik = 1;
rowvec likdu = zeros<rowvec>(data.ncauses);
// Marginal probabilities
for (unsigned i=1; i<=2; i++){ // Over individuals
for (unsigned j=1; j<=data.ncauses; j++){ // Over failure causes
double prob = F1(row, j, i, data, sigmaMarg, u);
rowvec probdu = dF1du(row, j, i, data, sigmaMarg, u);
lik -= prob; // Subtracting
likdu -= probdu;
}
}
// Bivariate probabilities
for (unsigned k=1; k<=data.ncauses; k++){ // Over failure causes
for (unsigned l=1; l<=data.ncauses; l++){
irowvec vcauses(2);
vcauses(0) = k; vcauses(1) = l;
double prob = F2(row, vcauses, data, sigmaJoint, u);
rowvec probdu = dF2du(row, vcauses, data, sigmaJoint, u);
lik += prob; // Adding
likdu += probdu;
}
}
res = (1/lik)*likdu;
}
}
else {
/* One individual experiences failure the other does not */
for (unsigned i=1; i<=2; i++){ // Over individuals
unsigned cause = causes(i-1);
if (cause > 0){
// Marginal probability of failure
res += dlogdF1du(row, cause, i, data, sigmaMarg, u);
}
else {
// Marginal probability of no failure
unsigned cond_cause;
if (i==1){
cond_cause = causes(1);
}
else {
cond_cause = causes(0);
}
for (unsigned j=1; j<=data.ncauses; j++){ // Over failure causes
double lik = 1;
rowvec likdu = zeros<rowvec>(data.ncauses);
if (cause < 0){ // Uncondtional
double prob = F1(row, j, i, data);
rowvec probdu = dF1du(row, j, i, data);
lik -= prob;
likdu -= probdu;
}
else { // Conditional
double prob = F1(row, j, i, cond_cause, data, sigmaMargCond, u);
rowvec probdu = dF1du(row, j, i, cond_cause, data, sigmaMargCond, u);
lik -= prob;
likdu -= probdu;
}
res += (1/lik)*likdu;
}
}
}
}
/* Contribution from u */
if (full){
vmat sig = sigmaU; // Variance-covariance matrix etc. of u
// Adding to the score
res += -u.t()*sig.inv;
};
return(res);
}
/////////////////////////////////////////////////////////////////////////////
// FOR TESTING
double loglikout(unsigned row, mat sigma, vec u, int ncauses, imat causes, mat alpha, mat dalpha, mat beta, mat gamma){
// Initialising gmats of sigma (Joint, Cond)
gmat sigmaJoint = gmat(ncauses, ncauses);
gmat sigmaCond = gmat(ncauses, ncauses);
// Vectors for extracting rows and columns from sigma
uvec rcJ(2); /* for joint */
uvec rc1(1); /* for conditional */
uvec rc2(ncauses+1); /* for conditional */
uvec rcu(ncauses);
for (int h=0; h<ncauses; h++){
rcu(h) = ncauses + h;
};
// Estimating and setting vmats sigmaJoint
for (int h=0; h<ncauses; h++){
for (int i=0; i<ncauses; i++){
rcJ(0)=h;
rcJ(1)=ncauses+i;
vmat x = vmat(sigma, rcJ, rcu);
sigmaJoint.set(h,i,x);
};
};
// Estimating and setting vmats of sigmaCond
for (int h=0; h<ncauses; h++){
for (int i=0; i<ncauses; i++){
rc1(1) = h;
rc2(0) = i;
for (int j=0; j<ncauses; j++){
rc2(j+1) = rcu(j);
};
vmat x = vmat(sigma, rc1, rc2);
sigmaCond.set(h,i,x);
};
};
// vmat of the us
mat matU = sigma.submat(rcu,rcu);
vmat sigmaU = vmat(matU);
// Generating DataPairs
DataPairs data = DataPairs(int ncauses, imat causes, mat alpha, mat dalpha, mat beta, mat gamma);
// Estimating likelihood contribution
double loglik = loglikfull(unsigned row, DataPairs data, gmat sigmaJoint, gmat sigmaCond, vmat sigmaU, vec u, bool full=1);
// Return
return loglik;
};
//rowvec Dloglikout(unsigned row, mat sigma, mat data, vec u){
// Generating gmats of sigma (Marg, Joint, MargCond, sigU)
// Generating DataPairs
// Estimating score contribution
// rowvec score = Dloglikfull(unsigned row, DataPairs data, gmat sigmaJoint, gmat sigmaMargCond, vmat sigmaU, vec u, bool full=1);
// Return
// return score;
//};
<commit_msg>testing<commit_after>// [[Rcpp::depends(RcppArmadillo)]]
#include <RcppArmadillo.h>
#include <Rmath.h>
#include <vector>
#include <cassert>
#include "vmat.h"
#include "gmat.h"
#include "DataPairs.h"
#include "quadrule.h"
#include "pn.h"
#include "functions.h"
using namespace Rcpp;
using namespace arma;
using namespace std;
const double twopi = 2*datum::pi;
/////////////////////////////////////////////////////////////////////////////////////////////////
/* Full loglikelihood */
double loglikfull(unsigned row, DataPairs &data, const gmat &sigmaMarg, const gmat &sigmaJoint, const gmat &sigmaMargCond, vmat sigmaU, vec u, bool full=1){
data.pi_gen(row, u); // Estimation of pi based on u
irowvec causes = data.causes_get(row); // Failure causes for pair in question
double res = 0; // Initialising output (loglik contribution)
if ((causes(0) > 0) & (causes(1) > 0)){
/* Both individuals experience failure */
res = logdF2(row, causes, data, sigmaJoint, u);
}
else if((causes(0) <= 0) & (causes(1) <= 0)){
/* Neither individual experience failure */
if ((causes(0) < 0) & (causes(1) < 0)){
// Full follow-up for both individuals
for (unsigned i=1; i<=2; i++){ // Over individuals
double lik = 1;
for (unsigned j=1; j<=data.ncauses; j++){ // Over failure causes
double prob = F1(row, j, i, data);
lik -= prob;
}
res += log(lik);
}
}
else if (((causes(0) < 0) & (causes(1) == 0)) | ((causes(0) == 0) & (causes(1) < 0))){
// Full follow-up for only one individual
for (unsigned i=1; i<=2; i++){ // Over individuals
double lik = 1;
for (unsigned j=1; j<=data.ncauses; j++){ // Over failure causes
if (causes(i-1) < 0){
double prob = F1(row, j, i, data);
lik -= prob;
}
else {
double prob = F1(row, j, i, data, sigmaMarg, u);
lik -= prob;
}
}
res += log(lik);
}
}
else {
// Full follow-up for neither individual
double lik = 1;
// Marginal probabilities
for (unsigned i=1; i<=2; i++){ // Over individuals
for (unsigned j=1; j<=data.ncauses; j++){ // Over failure causes
double prob = F1(row, j, i, data, sigmaMarg, u);
lik -= prob; // Subtracting
}
}
// Bivariate probabilities
for (unsigned k=1; k<=data.ncauses; k++){ // Over failure causes
for (unsigned l=1; l<=data.ncauses; l++){
irowvec vcauses(2);
vcauses(0) = k; vcauses(1) = l;
double prob = F2(row, vcauses, data, sigmaJoint, u);
lik += prob; // Adding
}
}
res = log(lik);
}
}
else {
/* One individual experiences failure the other does not */
for (unsigned i=1; i<=2; i++){ // Over individuals
unsigned cause = causes(i-1);
if (cause > 0){
// Marginal probability of failure
res += logdF1(row, cause, i, data, sigmaMarg, u);
}
else {
// Marginal probability of no failure
unsigned cond_cause;
if (i==1){
cond_cause = causes(1);
}
else {
cond_cause = causes(0);
}
for (unsigned j=1; j<=data.ncauses; j++){ // Over failure causes
double lik = 1;
if (cause < 0){
// Unconditional
double prob = F1(row, j, i, data);
lik -= prob;
}
else {
// Conditional
double prob = F1(row, j, i, cond_cause, data, sigmaMargCond, u);
lik -= prob;
}
res += log(lik);
}
}
}
}
/* Contribution from u */
if (full){
vmat sig = sigmaU; // Variance-covariance matrix of u
double inner = as_scalar(u*sig.inv*u.t());
// PDF of u
double logpdfu = log(pow(twopi,-(data.ncauses/2))) + sig.loginvsqdet - 0.5*inner;
// Adding to the loglik
res += logpdfu;
}
/* Return */
return(res);
}
/////////////////////////////////////////////////////////////////////////////////////////////////
/* Score function of full loglikelihood */
rowvec Dloglikfull(unsigned row, DataPairs &data, const gmat &sigmaMarg, const gmat &sigmaJoint, const gmat &sigmaMargCond, vmat sigmaU, vec u, bool full=1){
/* Estimation of pi, dpidu and dlogpidu */
data.pi_gen(row, u);
data.dpidu_gen(row, u);
data.dlogpidu_gen(row, u);
irowvec causes = data.causes_get(row); // Failure causes for pair in question
rowvec res = zeros<rowvec>(data.ncauses); // Initialising output (score contribution)
if ((causes(0) > 0) & (causes(1) > 0)){
/* Both individuals experience failure */
res = dlogdF2du(row, causes, data, sigmaJoint, u);
}
else if((causes(0) <= 0) & (causes(1) <= 0)){
/* Neither individual experience failure */
if ((causes(0) < 0) & (causes(1) < 0)){
// Full follow-up for both individuals
for (unsigned i=1; i<=2; i++){ // Over individuals
double lik = 1;
rowvec likdu = zeros<rowvec>(data.ncauses);
for (unsigned j=1; j<=data.ncauses; j++){ // Over failure causes
double prob = F1(row, j, i, data);
rowvec probdu = dF1du(row, j, i, data);
lik -= prob;
likdu -= probdu;
}
res += (1/lik)*likdu;
}
}
else if (((causes(0) < 0) & (causes(1) == 0)) | ((causes(0) == 0) & (causes(1) < 0))){
// Full follow-up for only one individual
for (unsigned i=1; i<=2; i++){ // Over individuals
double lik = 1;
rowvec likdu = zeros<rowvec>(data.ncauses);
for (unsigned j=1; j<=data.ncauses; j++){ // Over failure causes
if (causes(i-1) < 0){
double prob = F1(row, j, i, data);
rowvec probdu = dF1du(row, j, i, data);
lik -= prob;
likdu -= probdu;
}
else {
double prob = F1(row, j, i, data, sigmaMarg, u);
rowvec probdu = dF1du(row, j, i, data, sigmaMarg, u);
lik -= prob;
likdu -= probdu;
}
}
res += (1/lik)*likdu;
}
}
else {
// Full follow-up for neither individual
double lik = 1;
rowvec likdu = zeros<rowvec>(data.ncauses);
// Marginal probabilities
for (unsigned i=1; i<=2; i++){ // Over individuals
for (unsigned j=1; j<=data.ncauses; j++){ // Over failure causes
double prob = F1(row, j, i, data, sigmaMarg, u);
rowvec probdu = dF1du(row, j, i, data, sigmaMarg, u);
lik -= prob; // Subtracting
likdu -= probdu;
}
}
// Bivariate probabilities
for (unsigned k=1; k<=data.ncauses; k++){ // Over failure causes
for (unsigned l=1; l<=data.ncauses; l++){
irowvec vcauses(2);
vcauses(0) = k; vcauses(1) = l;
double prob = F2(row, vcauses, data, sigmaJoint, u);
rowvec probdu = dF2du(row, vcauses, data, sigmaJoint, u);
lik += prob; // Adding
likdu += probdu;
}
}
res = (1/lik)*likdu;
}
}
else {
/* One individual experiences failure the other does not */
for (unsigned i=1; i<=2; i++){ // Over individuals
unsigned cause = causes(i-1);
if (cause > 0){
// Marginal probability of failure
res += dlogdF1du(row, cause, i, data, sigmaMarg, u);
}
else {
// Marginal probability of no failure
unsigned cond_cause;
if (i==1){
cond_cause = causes(1);
}
else {
cond_cause = causes(0);
}
for (unsigned j=1; j<=data.ncauses; j++){ // Over failure causes
double lik = 1;
rowvec likdu = zeros<rowvec>(data.ncauses);
if (cause < 0){ // Uncondtional
double prob = F1(row, j, i, data);
rowvec probdu = dF1du(row, j, i, data);
lik -= prob;
likdu -= probdu;
}
else { // Conditional
double prob = F1(row, j, i, cond_cause, data, sigmaMargCond, u);
rowvec probdu = dF1du(row, j, i, cond_cause, data, sigmaMargCond, u);
lik -= prob;
likdu -= probdu;
}
res += (1/lik)*likdu;
}
}
}
}
/* Contribution from u */
if (full){
vmat sig = sigmaU; // Variance-covariance matrix etc. of u
// Adding to the score
res += -u.t()*sig.inv;
};
return(res);
}
/////////////////////////////////////////////////////////////////////////////
// FOR TESTING
double loglikout(unsigned row, mat sigma, vec u, int ncauses, imat causes, mat alpha, mat dalpha, mat beta, mat gamma){
// Initialising gmats of sigma (Joint, Cond)
gmat sigmaJoint = gmat(ncauses, ncauses);
gmat sigmaCond = gmat(ncauses, ncauses);
// Vectors for extracting rows and columns from sigma
uvec rcJ(2); /* for joint */
uvec rc1(1); /* for conditional */
uvec rc2(ncauses+1); /* for conditional */
uvec rcu(ncauses);
for (int h=0; h<ncauses; h++){
rcu(h) = ncauses + h;
};
// Estimating and setting vmats sigmaJoint
for (int h=0; h<ncauses; h++){
for (int i=0; i<ncauses; i++){
rcJ(0)=h;
rcJ(1)=ncauses+i;
vmat x = vmat(sigma, rcJ, rcu);
sigmaJoint.set(h,i,x);
};
};
// Estimating and setting vmats of sigmaCond
for (int h=0; h<ncauses; h++){
for (int i=0; i<ncauses; i++){
rc1(1) = h;
rc2(0) = i;
for (int j=0; j<ncauses; j++){
rc2(j+1) = rcu(j);
};
vmat x = vmat(sigma, rc1, rc2);
sigmaCond.set(h,i,x);
};
};
// vmat of the us
mat matU = sigma.submat(rcu,rcu);x
vmat sigmaU = vmat(matU);
// Generating DataPairs
DataPairs data = DataPairs(ncauses, causes, alpha, dalpha, beta, gamma);
// Estimating likelihood contribution
double loglik = loglikfull(unsigned row, data, sigmaJoint, sigmaCond, sigmaU, u, bool full=1);
// Return
return loglik;
};
//rowvec Dloglikout(unsigned row, mat sigma, mat data, vec u){
// Generating gmats of sigma (Marg, Joint, MargCond, sigU)
// Generating DataPairs
// Estimating score contribution
// rowvec score = Dloglikfull(unsigned row, DataPairs data, gmat sigmaJoint, gmat sigmaMargCond, vmat sigmaU, vec u, bool full=1);
// Return
// return score;
//};
<|endoftext|> |
<commit_before>#include "NTClient.h"
using namespace std;
NTClient::NTClient(int _wpm, double _accuracy) {
typeIntervalMS = 12000 / _wpm;
wpm = _wpm;
accuracy = _accuracy;
firstConnect = true;
connected = false;
finished = false;
lessonLen = 0;
log = new NTLogger("(Not logged in)");
wsh = nullptr;
racesCompleted = 0;
rIdx = 0;
eIdx = 0;
}
NTClient::~NTClient() {
if (log != nullptr) {
delete log;
log = nullptr;
}
if (wsh != nullptr) {
delete wsh;
wsh = nullptr;
}
}
bool NTClient::login(string username, string password) {
log->type(LOG_HTTP);
log->wr("Logging into the NitroType account...\n");
log->setUsername(username);
uname = username;
pword = password;
bool ret = true;
string data = string("username=");
data += uname;
data += "&password=";
data += pword;
data += "&adb=1&tz=America%2FChicago"; // No need to have anything other than Chicago timezone
httplib::SSLClient loginReq(NITROTYPE_HOSTNAME, HTTPS_PORT);
shared_ptr<httplib::Response> res = loginReq.post(NT_LOGIN_ENDPOINT, data, "application/x-www-form-urlencoded; charset=UTF-8");
if (res) {
bool foundLoginCookie = false;
for (int i = 0; i < res->cookies.size(); ++i) {
string cookie = res->cookies.at(i);
addCookie(Utils::extractCKey(cookie), Utils::extractCValue(cookie));
if (cookie.find("ntuserrem=") == 0) {
foundLoginCookie = true;
token = Utils::extractCValue(cookie);
log->type(LOG_HTTP);
log->wr("Resolved ntuserrem login token.\n");
// addCookie("ntuserrem", token);
}
}
if (!foundLoginCookie) {
ret = false;
log->type(LOG_HTTP);
log->wr("Unable to locate the login cookie. Maybe try a different account?\n");
}
} else {
ret = false;
log->type(LOG_HTTP);
log->wr("Login request failed. This might be a network issue. Maybe try resetting your internet connection?\n");
}
if (ret == false) {
log->type(LOG_HTTP);
log->wr("Failed to log in.\n");
} else {
bool success = getPrimusSID();
if (!success) return false;
}
return ret;
}
bool NTClient::connect() {
wsh = new Hub();
time_t tnow = time(0);
rawCookieStr = Utils::stringifyCookies(&cookies);
stringstream uristream;
uristream << "wss://realtime1.nitrotype.com:443/realtime/?_primuscb=" << tnow << "-0&EIO=3&transport=websocket&sid=" << primusSid << "&t=" << tnow << "&b64=1";
string wsURI = uristream.str();
log->type(LOG_CONN);
log->wr("Attempting to connect to the NitroType realtime server...\n");
if (firstConnect) {
addListeners();
}
// cout << "Cookies: " << rawCookieStr << endl << endl;
// Create override headers
customHeaders["Cookie"] = rawCookieStr;
customHeaders["Origin"] = "https://www.nitrotype.com";
customHeaders["User-Agent"] = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/55.0.2883.87 Chrome/55.0.2883.87 Safari/537.36";
// customHeaders["Host"] = "realtime1.nitrotype.com";
wsh->connect(wsURI, (void*)this, customHeaders, 7000);
// wsh->connect(wsURI);
if (firstConnect) {
wsh->run();
firstConnect = false;
}
return true;
}
void NTClient::addCookie(string key, string val) {
SPair sp = SPair(key, val);
cookies.push_back(sp);
}
bool NTClient::getPrimusSID() {
time_t tnow = time(0);
log->type(LOG_HTTP);
log->wr("Resolving Primus SID...\n");
rawCookieStr = Utils::stringifyCookies(&cookies);
stringstream squery;
squery << "?_primuscb=" << tnow << "-0&EIO=3&transport=polling&t=" << tnow << "-0&b64=1";
string queryStr = squery.str();
httplib::SSLClient loginReq(NT_REALTIME_HOST, HTTPS_PORT);
string path = NT_PRIMUS_ENDPOINT + queryStr;
shared_ptr<httplib::Response> res = loginReq.get(path.c_str(), rawCookieStr.c_str());
if (res) {
json jres = json::parse(res->body.substr(4, res->body.length()));
primusSid = jres["sid"];
log->type(LOG_HTTP);
log->wr("Resolved Primus SID successfully.\n");
// addCookie("io", primusSid);
} else {
cout << "Error retrieving primus handshake data.\n";
return false;
}
return true;
}
string NTClient::getJoinPacket(int avgSpeed) {
json p = {
{"stream", "race"},
{"msg", "join"},
{"payload", {
{"avgSpeed", avgSpeed},
{"debugging", false},
{"music", "standard"},
{"track", "forest"},
{"update", 3417}
}}
};
return "4" + p.dump();
}
void NTClient::addListeners() {
assert(wsh != nullptr);
wsh->onError([this](void* udata) {
log->type(LOG_CONN);
log->wr("WebSocket connection error. Firing disconn event.\n");
onDisconnection();
});
wsh->onConnection([this](WebSocket<CLIENT>* wsocket, HttpRequest req) {
log->type(LOG_CONN);
log->wr("Established a WebSocket connection with the realtime server.\n");
onConnection(wsocket, req);
});
wsh->onDisconnection([this](WebSocket<CLIENT>* wsocket, int code, char* msg, size_t len) {
log->type(LOG_CONN);
log->wr("Disconnected from the realtime server.\n");
onDisconnection();
});
wsh->onMessage([this](WebSocket<CLIENT>* ws, char* msg, size_t len, OpCode opCode) {
onMessage(ws, msg, len, opCode);
});
}
void NTClient::onDisconnection(void) {
/*
cout << "Disconn message: " << string(msg, len) << endl;
cout << "Disconn code: " << code << endl;
*/
log->type(LOG_CONN);
log->wr("Reconnecting to the realtime server...\n");
getPrimusSID();
rawCookieStr = Utils::stringifyCookies(&cookies);
stringstream uristream;
uristream << "wss://realtime1.nitrotype.com:443/realtime/?_primuscb=" << time(0) << "-0&EIO=3&transport=websocket&sid=" << primusSid << "&t=" << time(0) << "&b64=1";
string wsURI = uristream.str();
wsh->connect(wsURI, (void*)this, customHeaders, 7000);
}
void NTClient::handleData(WebSocket<CLIENT>* ws, json* j) {
// Uncomment to dump all raw JSON packets
// cout << "Recieved json data:" << endl << j->dump(4) << endl;
if (j->operator[]("msg") == "setup") {
log->type(LOG_RACE);
log->wr("I joined a new race.\n");
recievedEndPacket = false;
rIdx = 0;
eIdx = 0;
finished = false;
} else if (j->operator[]("msg") == "joined") {
string joinedName = j->operator[]("payload")["profile"]["username"];
string dispName;
try {
dispName = j->operator[]("payload")["profile"]["displayName"];
} catch (const exception& e) {
dispName = "[None]";
}
log->type(LOG_RACE);
if (joinedName == "bot") {
log->wr("Bot user '");
log->wrs(dispName);
log->wrs("' joined the race.\n");
} else {
log->wr("Human user '");
log->wrs(joinedName);
log->wrs("' joined the race.\n");
}
} else if (j->operator[]("msg") == "status" && j->operator[]("payload")["status"] == "countdown") {
lastRaceStart = time(0);
log->type(LOG_RACE);
log->wr("The race has started.\n");
lesson = j->operator[]("payload")["l"];
lessonLen = lesson.length();
log->type(LOG_INFO);
log->wr("Lesson length: ");
log->operator<<(lessonLen);
log->ln();
this_thread::sleep_for(chrono::milliseconds(50));
type(ws);
} else if (j->operator[]("msg") == "update" &&
j->operator[]("payload")["racers"][0] != nullptr &&
j->operator[]("payload")["racers"][0]["r"] != nullptr) {
// Race has finished for a client
if (recievedEndPacket == false) {
// Ensures its this client
recievedEndPacket = true;
handleRaceFinish(ws);
}
}
}
void NTClient::onMessage(WebSocket<CLIENT>* ws, char* msg, size_t len, OpCode opCode) {
if (opCode != OpCode::TEXT) {
cout << "The realtime server did not send a text packet for some reason, ignoring.\n";
return;
}
string smsg = string(msg, len);
if (smsg == "3probe") {
// Response to initial connection probe
ws->send("5", OpCode::TEXT);
// Join packet
this_thread::sleep_for(chrono::seconds(1));
string joinTo = getJoinPacket(20); // 20 WPM just to test
ws->send(joinTo.c_str(), OpCode::TEXT);
} else if (smsg.length() > 2 && smsg[0] == '4' && smsg[1] == '{') {
string rawJData = smsg.substr(1, smsg.length());
json jdata;
try {
jdata = json::parse(rawJData);
} catch (const exception& e) {
// Some error parsing real race data, something must be wrong
cout << "There was an issue parsing server data: " << e.what() << endl;
return;
}
handleData(ws, &jdata);
} else {
cout << "Recieved unknown WebSocket message: '" << smsg << "'\n";
}
}
void NTClient::onConnection(WebSocket<CLIENT>* wsocket, HttpRequest req) {
// Send a probe, which is required for connection
wsocket->send("2probe", OpCode::TEXT);
}
void NTClient::sendTypePacket(WebSocket<CLIENT>* ws, int idx, string typeType) {
json p = {
{"stream", "race"},
{"msg", "update"},
{"payload", {}}
};
p["payload"][typeType] = idx;
string packet = "4" + p.dump();
// cout << "Packet: " << packet << endl;
ws->send(packet.c_str(), OpCode::TEXT);
}
void NTClient::type(WebSocket<CLIENT>* ws) {
if (rIdx > lessonLen) {
// All characters have been typed
if (!finished) {
handleRaceFinish(ws);
}
return;
}
int low = typeIntervalMS - 15;
int high = typeIntervalMS + 15;
bool isRight = Utils::randBool(accuracy);
int sleepFor = Utils::randInt(low, high);
if (low < 10) {
low = Utils::randInt(9, 12);
}
if (rIdx % 25 == 0) { // Display info every 25 characters
// Log race updated
log->type(LOG_INFO);
log->wr("I have finished ");
log->operator<<((((double)rIdx) / ((double)lessonLen)) * 100.00);
log->wrs("% of the race (");
log->operator<<((int)rIdx);
log->wrs(" / ");
log->operator<<((int)lessonLen);
log->wrs(" characters at ");
log->operator<<((int)wpm);
log->wrs(" WPM)");
log->ln();
}
if (!isRight) {
++eIdx;
sendTypePacket(ws, eIdx, "e");
}
++rIdx;
sendTypePacket(ws, rIdx, "t");
// cout << "rIdx " << rIdx << ", eIdx: " << eIdx << ", isRight: " << isRight << ", sleepFor: " << sleepFor << endl;
this_thread::sleep_for(chrono::milliseconds(sleepFor));
type(ws); // Call the function until the lesson has been "typed"
}
void NTClient::handleRaceFinish(WebSocket<CLIENT>* ws) {
finished = true;
racesCompleted++;
int raceCompleteTime = time(0) - lastRaceStart;
rIdx = 0;
eIdx = 0;
log->type(LOG_RACE);
log->wr("The race has finished.\n");
log->type(LOG_INFO);
log->wr("The race took ");
log->operator<<(raceCompleteTime);
log->wrs(" seconds to complete. Waiting 5 seconds before the next race.\n");
log->type(LOG_RACE);
log->wr("I have completed ");
log->operator<<(racesCompleted);
log->wrs(" race(s).\n");
this_thread::sleep_for(chrono::seconds(5));
log->type(LOG_CONN);
log->wr("Closing WebSocket...\n");
ws->close();
}<commit_msg>Properly handle all JSON parsing issues<commit_after>#include "NTClient.h"
using namespace std;
NTClient::NTClient(int _wpm, double _accuracy) {
typeIntervalMS = 12000 / _wpm;
wpm = _wpm;
accuracy = _accuracy;
firstConnect = true;
connected = false;
finished = false;
lessonLen = 0;
log = new NTLogger("(Not logged in)");
wsh = nullptr;
racesCompleted = 0;
rIdx = 0;
eIdx = 0;
}
NTClient::~NTClient() {
if (log != nullptr) {
delete log;
log = nullptr;
}
if (wsh != nullptr) {
delete wsh;
wsh = nullptr;
}
}
bool NTClient::login(string username, string password) {
log->type(LOG_HTTP);
log->wr("Logging into the NitroType account...\n");
log->setUsername(username);
uname = username;
pword = password;
bool ret = true;
string data = string("username=");
data += uname;
data += "&password=";
data += pword;
data += "&adb=1&tz=America%2FChicago"; // No need to have anything other than Chicago timezone
httplib::SSLClient loginReq(NITROTYPE_HOSTNAME, HTTPS_PORT);
shared_ptr<httplib::Response> res = loginReq.post(NT_LOGIN_ENDPOINT, data, "application/x-www-form-urlencoded; charset=UTF-8");
if (res) {
bool foundLoginCookie = false;
for (int i = 0; i < res->cookies.size(); ++i) {
string cookie = res->cookies.at(i);
addCookie(Utils::extractCKey(cookie), Utils::extractCValue(cookie));
if (cookie.find("ntuserrem=") == 0) {
foundLoginCookie = true;
token = Utils::extractCValue(cookie);
log->type(LOG_HTTP);
log->wr("Resolved ntuserrem login token.\n");
// addCookie("ntuserrem", token);
}
}
if (!foundLoginCookie) {
ret = false;
log->type(LOG_HTTP);
log->wr("Unable to locate the login cookie. Maybe try a different account?\n");
}
} else {
ret = false;
log->type(LOG_HTTP);
log->wr("Login request failed. This might be a network issue. Maybe try resetting your internet connection?\n");
}
if (ret == false) {
log->type(LOG_HTTP);
log->wr("Failed to log in.\n");
} else {
bool success = getPrimusSID();
if (!success) return false;
}
return ret;
}
bool NTClient::connect() {
wsh = new Hub();
time_t tnow = time(0);
rawCookieStr = Utils::stringifyCookies(&cookies);
stringstream uristream;
uristream << "wss://realtime1.nitrotype.com:443/realtime/?_primuscb=" << tnow << "-0&EIO=3&transport=websocket&sid=" << primusSid << "&t=" << tnow << "&b64=1";
string wsURI = uristream.str();
log->type(LOG_CONN);
log->wr("Attempting to connect to the NitroType realtime server...\n");
if (firstConnect) {
addListeners();
}
// cout << "Cookies: " << rawCookieStr << endl << endl;
// Create override headers
customHeaders["Cookie"] = rawCookieStr;
customHeaders["Origin"] = "https://www.nitrotype.com";
customHeaders["User-Agent"] = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/55.0.2883.87 Chrome/55.0.2883.87 Safari/537.36";
// customHeaders["Host"] = "realtime1.nitrotype.com";
wsh->connect(wsURI, (void*)this, customHeaders, 7000);
// wsh->connect(wsURI);
if (firstConnect) {
wsh->run();
firstConnect = false;
}
return true;
}
void NTClient::addCookie(string key, string val) {
SPair sp = SPair(key, val);
cookies.push_back(sp);
}
bool NTClient::getPrimusSID() {
time_t tnow = time(0);
log->type(LOG_HTTP);
log->wr("Resolving Primus SID...\n");
rawCookieStr = Utils::stringifyCookies(&cookies);
stringstream squery;
squery << "?_primuscb=" << tnow << "-0&EIO=3&transport=polling&t=" << tnow << "-0&b64=1";
string queryStr = squery.str();
httplib::SSLClient loginReq(NT_REALTIME_HOST, HTTPS_PORT);
string path = NT_PRIMUS_ENDPOINT + queryStr;
shared_ptr<httplib::Response> res = loginReq.get(path.c_str(), rawCookieStr.c_str());
if (res) {
try {
json jres = json::parse(res->body.substr(4, res->body.length()));
} catch (const exception& e) {
log->type(LOG_HTTP);
log->wr("There was an issue parsing Primus polling info. Retrying.\n");
return getPrimusSID();
}
primusSid = jres["sid"];
log->type(LOG_HTTP);
log->wr("Resolved Primus SID successfully.\n");
// addCookie("io", primusSid);
} else {
cout << "Error retrieving primus handshake data.\n";
return false;
}
return true;
}
string NTClient::getJoinPacket(int avgSpeed) {
json p = {
{"stream", "race"},
{"msg", "join"},
{"payload", {
{"avgSpeed", avgSpeed},
{"debugging", false},
{"music", "standard"},
{"track", "forest"},
{"update", 3417}
}}
};
return "4" + p.dump();
}
void NTClient::addListeners() {
assert(wsh != nullptr);
wsh->onError([this](void* udata) {
log->type(LOG_CONN);
log->wr("WebSocket connection error. Firing disconn event.\n");
onDisconnection();
});
wsh->onConnection([this](WebSocket<CLIENT>* wsocket, HttpRequest req) {
log->type(LOG_CONN);
log->wr("Established a WebSocket connection with the realtime server.\n");
onConnection(wsocket, req);
});
wsh->onDisconnection([this](WebSocket<CLIENT>* wsocket, int code, char* msg, size_t len) {
log->type(LOG_CONN);
log->wr("Disconnected from the realtime server.\n");
onDisconnection();
});
wsh->onMessage([this](WebSocket<CLIENT>* ws, char* msg, size_t len, OpCode opCode) {
onMessage(ws, msg, len, opCode);
});
}
void NTClient::onDisconnection(void) {
/*
cout << "Disconn message: " << string(msg, len) << endl;
cout << "Disconn code: " << code << endl;
*/
log->type(LOG_CONN);
log->wr("Reconnecting to the realtime server...\n");
getPrimusSID();
rawCookieStr = Utils::stringifyCookies(&cookies);
stringstream uristream;
uristream << "wss://realtime1.nitrotype.com:443/realtime/?_primuscb=" << time(0) << "-0&EIO=3&transport=websocket&sid=" << primusSid << "&t=" << time(0) << "&b64=1";
string wsURI = uristream.str();
wsh->connect(wsURI, (void*)this, customHeaders, 7000);
}
void NTClient::handleData(WebSocket<CLIENT>* ws, json* j) {
// Uncomment to dump all raw JSON packets
// cout << "Recieved json data:" << endl << j->dump(4) << endl;
if (j->operator[]("msg") == "setup") {
log->type(LOG_RACE);
log->wr("I joined a new race.\n");
recievedEndPacket = false;
rIdx = 0;
eIdx = 0;
finished = false;
} else if (j->operator[]("msg") == "joined") {
string joinedName = j->operator[]("payload")["profile"]["username"];
string dispName;
try {
dispName = j->operator[]("payload")["profile"]["displayName"];
} catch (const exception& e) {
dispName = "[None]";
}
log->type(LOG_RACE);
if (joinedName == "bot") {
log->wr("Bot user '");
log->wrs(dispName);
log->wrs("' joined the race.\n");
} else {
log->wr("Human user '");
log->wrs(joinedName);
log->wrs("' joined the race.\n");
}
} else if (j->operator[]("msg") == "status" && j->operator[]("payload")["status"] == "countdown") {
lastRaceStart = time(0);
log->type(LOG_RACE);
log->wr("The race has started.\n");
lesson = j->operator[]("payload")["l"];
lessonLen = lesson.length();
log->type(LOG_INFO);
log->wr("Lesson length: ");
log->operator<<(lessonLen);
log->ln();
this_thread::sleep_for(chrono::milliseconds(50));
type(ws);
} else if (j->operator[]("msg") == "update" &&
j->operator[]("payload")["racers"][0] != nullptr &&
j->operator[]("payload")["racers"][0]["r"] != nullptr) {
// Race has finished for a client
if (recievedEndPacket == false) {
// Ensures its this client
recievedEndPacket = true;
handleRaceFinish(ws);
}
}
}
void NTClient::onMessage(WebSocket<CLIENT>* ws, char* msg, size_t len, OpCode opCode) {
if (opCode != OpCode::TEXT) {
cout << "The realtime server did not send a text packet for some reason, ignoring.\n";
return;
}
string smsg = string(msg, len);
if (smsg == "3probe") {
// Response to initial connection probe
ws->send("5", OpCode::TEXT);
// Join packet
this_thread::sleep_for(chrono::seconds(1));
string joinTo = getJoinPacket(20); // 20 WPM just to test
ws->send(joinTo.c_str(), OpCode::TEXT);
} else if (smsg.length() > 2 && smsg[0] == '4' && smsg[1] == '{') {
string rawJData = smsg.substr(1, smsg.length());
json jdata;
try {
jdata = json::parse(rawJData);
} catch (const exception& e) {
// Some error parsing real race data, something must be wrong
cout << "There was an issue parsing server data: " << e.what() << ", ignoring it." << endl;
return;
}
handleData(ws, &jdata);
} else {
cout << "Recieved unknown WebSocket message: '" << smsg << "'\n";
}
}
void NTClient::onConnection(WebSocket<CLIENT>* wsocket, HttpRequest req) {
// Send a probe, which is required for connection
wsocket->send("2probe", OpCode::TEXT);
}
void NTClient::sendTypePacket(WebSocket<CLIENT>* ws, int idx, string typeType) {
json p = {
{"stream", "race"},
{"msg", "update"},
{"payload", {}}
};
p["payload"][typeType] = idx;
string packet = "4" + p.dump();
// cout << "Packet: " << packet << endl;
ws->send(packet.c_str(), OpCode::TEXT);
}
void NTClient::type(WebSocket<CLIENT>* ws) {
if (rIdx > lessonLen) {
// All characters have been typed
if (!finished) {
handleRaceFinish(ws);
}
return;
}
int low = typeIntervalMS - 15;
int high = typeIntervalMS + 15;
bool isRight = Utils::randBool(accuracy);
int sleepFor = Utils::randInt(low, high);
if (low < 10) {
low = Utils::randInt(9, 12);
}
if (rIdx % 25 == 0) { // Display info every 25 characters
// Log race updated
log->type(LOG_INFO);
log->wr("I have finished ");
log->operator<<((((double)rIdx) / ((double)lessonLen)) * 100.00);
log->wrs("% of the race (");
log->operator<<((int)rIdx);
log->wrs(" / ");
log->operator<<((int)lessonLen);
log->wrs(" characters at ");
log->operator<<((int)wpm);
log->wrs(" WPM)");
log->ln();
}
if (!isRight) {
++eIdx;
sendTypePacket(ws, eIdx, "e");
}
++rIdx;
sendTypePacket(ws, rIdx, "t");
// cout << "rIdx " << rIdx << ", eIdx: " << eIdx << ", isRight: " << isRight << ", sleepFor: " << sleepFor << endl;
this_thread::sleep_for(chrono::milliseconds(sleepFor));
type(ws); // Call the function until the lesson has been "typed"
}
void NTClient::handleRaceFinish(WebSocket<CLIENT>* ws) {
finished = true;
racesCompleted++;
int raceCompleteTime = time(0) - lastRaceStart;
rIdx = 0;
eIdx = 0;
log->type(LOG_RACE);
log->wr("The race has finished.\n");
log->type(LOG_INFO);
log->wr("The race took ");
log->operator<<(raceCompleteTime);
log->wrs(" seconds to complete. Waiting 5 seconds before the next race.\n");
log->type(LOG_RACE);
log->wr("I have completed ");
log->operator<<(racesCompleted);
log->wrs(" race(s).\n");
this_thread::sleep_for(chrono::seconds(5));
log->type(LOG_CONN);
log->wr("Closing WebSocket...\n");
ws->close();
}<|endoftext|> |
<commit_before>/*
Copyright (c) 2012 Stuart Walsh
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 <fnmatch.h>
#include "stdinc.h"
#include "nuhmask.h"
NuhMask::NuhMask()
{
Logging::trace << "Created NuhMask: " << this << Logging::endl;
}
NuhMask::NuhMask(const string& mask)
{
parse_mask(mask);
}
NuhMask::~NuhMask()
{
Logging::trace << "Destroyed NuhMask: " << this << Logging::endl;
}
void NuhMask::parse_mask(const string& mask)
{
full_mask = mask;
size_t pos, last;
last = pos = mask.find_first_of('!');
if(pos == string::npos || pos == 0)
name = "*";
else
name = mask.substr(0, pos).c_str();
if(last == string::npos)
last = 0;
else
last++;
pos = mask.find_first_of('@', last);
if(pos == string::npos || pos == last)
username = "*";
else
username = mask.substr(last, pos - last).c_str();
last = pos;
if(last == string::npos)
last = 0;
else
last++;
host = mask.substr(last, pos - last);
if(host.empty())
host = "*";
}
string NuhMask::str() const
{
stringstream ss;
ss << name << "!" << username << "@" << host;
return ss.str();
}
bool NuhMask::match(const NuhMask& right)
{
std::string spat(this->str());
std::transform(spat.begin(), spat.end(), spat.begin(), to_upper);
const char *pat = spat.c_str();
std::string sdet(right.str());
std::transform(sdet.begin(), sdet.end(), sdet.begin(), to_upper);
const char *det = sdet.c_str();
int ret = fnmatch(pat, det, FNM_NOESCAPE | FNM_CASEFOLD);
bool ismatch = ret == 0 ? true : false;
Logging::debug << "NuhMask " << det << " ";
if(ismatch)
Logging::debug << "Matched";
else
Logging::debug << "No Match";
Logging::debug << " " << pat << Logging::endl;
return ismatch;
}
bool NuhMask::match(const ClientPtr right)
{
NuhMask r(right->str().c_str());
return this->match(r);
}
<commit_msg>win32ify nuhmask::match<commit_after>/*
Copyright (c) 2012 Stuart Walsh
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 "stdinc.h"
#include "nuhmask.h"
#ifndef _WIN32
#include <fnmatch.h>
#else
#include <shlwapi.h>
#pragma comment(lib,"shlwapi.lib");
#endif
NuhMask::NuhMask()
{
Logging::trace << "Created NuhMask: " << this << Logging::endl;
}
NuhMask::NuhMask(const string& mask)
{
parse_mask(mask);
}
NuhMask::~NuhMask()
{
Logging::trace << "Destroyed NuhMask: " << this << Logging::endl;
}
void NuhMask::parse_mask(const string& mask)
{
full_mask = mask;
size_t pos, last;
last = pos = mask.find_first_of('!');
if(pos == string::npos || pos == 0)
name = "*";
else
name = mask.substr(0, pos).c_str();
if(last == string::npos)
last = 0;
else
last++;
pos = mask.find_first_of('@', last);
if(pos == string::npos || pos == last)
username = "*";
else
username = mask.substr(last, pos - last).c_str();
last = pos;
if(last == string::npos)
last = 0;
else
last++;
host = mask.substr(last, pos - last);
if(host.empty())
host = "*";
}
string NuhMask::str() const
{
stringstream ss;
ss << name << "!" << username << "@" << host;
return ss.str();
}
bool NuhMask::match(const NuhMask& right)
{
std::string spat(this->str());
std::transform(spat.begin(), spat.end(), spat.begin(), to_upper);
const char *pat = spat.c_str();
std::string sdet(right.str());
std::transform(sdet.begin(), sdet.end(), sdet.begin(), to_upper);
const char *det = sdet.c_str();
#ifndef _WIN32
int ret = fnmatch(pat, det, FNM_NOESCAPE | FNM_CASEFOLD);
#else
int ret = !PathMatchSpec(det, pat);
#endif
bool ismatch = ret == 0 ? true : false;
Logging::debug << "NuhMask " << det << " ";
if(ismatch)
Logging::debug << "Matched";
else
Logging::debug << "No Match";
Logging::debug << " " << pat << Logging::endl;
return ismatch;
}
bool NuhMask::match(const ClientPtr right)
{
NuhMask r(right->str().c_str());
return this->match(r);
}
<|endoftext|> |
<commit_before>//
// Created by Malachi Burke on 11/12/17.
//
#include <catch.hpp>
#include "../mc/pipeline.h"
using namespace moducom::pipeline;
using namespace moducom::pipeline::experimental;
using namespace moducom::pipeline::layer3;
using namespace moducom::pipeline::layer3::experimental;
TEST_CASE("Pipeline basic tests", "[pipeline]")
{
SECTION("1")
{
MemoryChunk chunk;
SimpleBufferedPipeline p(chunk);
}
SECTION("experimental")
{
uint8_t buffer[128];
MemoryChunk _chunk(buffer, 128);
BufferProviderPipeline p(_chunk);
MemoryChunk* chunk = NULLPTR;
if(p.get_buffer(&chunk))
{
sprintf((char*)chunk->data, "Hello World");
PipelineMessage::CopiedStatus copied_status;
MemoryChunk chunk2 = p.advance(100, copied_status);
}
}
}<commit_msg>Experimental pseudo code<commit_after>//
// Created by Malachi Burke on 11/12/17.
//
#include <catch.hpp>
#include "../mc/pipeline.h"
using namespace moducom::pipeline;
using namespace moducom::pipeline::experimental;
using namespace moducom::pipeline::layer3;
using namespace moducom::pipeline::layer3::experimental;
TEST_CASE("Pipeline basic tests", "[pipeline]")
{
SECTION("1")
{
MemoryChunk chunk;
SimpleBufferedPipeline p(chunk);
}
SECTION("experimental")
{
uint8_t buffer[128];
MemoryChunk _chunk(buffer, 128);
BufferProviderPipeline p(_chunk);
MemoryChunk* chunk = NULLPTR;
if(p.get_buffer(&chunk))
{
sprintf((char*)chunk->data, "Hello World");
PipelineMessage::CopiedStatus copied_status;
MemoryChunk chunk2 = p.advance(100, copied_status);
}
#ifdef IDEALIZED
PipelineType p;
PipelineMessageWrapper<default_boundary_number> msg;
size_t len = sprintf(msg, "Hello");
// bump forward and notify interested parties
msg.advance(len, boundary_number);
// this should auto advance
msg << "Hello Again" << endl;
msg.boundary();
#endif
}
}<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: ZipEnumeration.cxx,v $
*
* $Revision: 1.12 $
*
* last change: $Author: rt $ $Date: 2005-09-08 16:15:15 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _ZIP_ENUMERATION_HXX
#include <ZipEnumeration.hxx>
#endif
/** Provides an Enumeration over the contents of a Zip file */
ZipEnumeration::ZipEnumeration( EntryHash & rNewEntryHash)
: rEntryHash(rNewEntryHash)
, aIterator(rEntryHash.begin())
{
}
ZipEnumeration::~ZipEnumeration( void )
{
}
sal_Bool SAL_CALL ZipEnumeration::hasMoreElements()
{
return (aIterator != rEntryHash.end());
}
const ZipEntry* SAL_CALL ZipEnumeration::nextElement()
{
if (aIterator != rEntryHash.end())
return &((*aIterator++).second);
else
return NULL;
}
<commit_msg>INTEGRATION: CWS pchfix02 (1.12.44); FILE MERGED 2006/09/01 17:32:42 kaib 1.12.44.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: ZipEnumeration.cxx,v $
*
* $Revision: 1.13 $
*
* last change: $Author: obo $ $Date: 2006-09-17 17:28:02 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_package.hxx"
#ifndef _ZIP_ENUMERATION_HXX
#include <ZipEnumeration.hxx>
#endif
/** Provides an Enumeration over the contents of a Zip file */
ZipEnumeration::ZipEnumeration( EntryHash & rNewEntryHash)
: rEntryHash(rNewEntryHash)
, aIterator(rEntryHash.begin())
{
}
ZipEnumeration::~ZipEnumeration( void )
{
}
sal_Bool SAL_CALL ZipEnumeration::hasMoreElements()
{
return (aIterator != rEntryHash.end());
}
const ZipEntry* SAL_CALL ZipEnumeration::nextElement()
{
if (aIterator != rEntryHash.end())
return &((*aIterator++).second);
else
return NULL;
}
<|endoftext|> |
<commit_before>/**
* ofxCsv.cpp
* Inspired and based on Ben Fry's [table class](http://benfry.com/writing/map/Table.pde)
*
*
* The MIT License
*
* Copyright (c) 2011-2012 Paul Vollmer, http://www.wng.cc
*
* 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.
*
*
* @testet_oF 0.07
* @testet_plattform MacOs 10.6
* ??? Win
* ??? Linux
* @dependencies
* @modified 2012.05.06
* @version 0.1.2b
*/
#include "ofxCsv.h"
namespace wng {
/**
* A Constructor, usually called to initialize and start the class.
*/
ofxCsv::ofxCsv(){
}
/**
* Load a CSV File.
*
* @param path
* Set the File path.
* @param separator
* Set the Separator to split CSV File.
* @param comments
* Set the Comments sign.
*/
void ofxCsv::loadFile(string path, string separator, string comments){
// Save Filepath, Separator and Comments to variables.
filePath = path;
fileSeparator = separator;
fileComments = comments;
#ifdef OFXCSV_LOG
ofLog() << "[ofxCsv] loadFile";
ofLog() << " filePath: " << filePath;
ofLog() << " fileSeparator: " << fileSeparator;
ofLog() << " fileComments: " << fileComments;
#endif
// Declare a File Stream.
ifstream fileIn;
// Open your text File:
fileIn.open(path.c_str());
// Check if File is open.
if(fileIn.is_open()) {
int lineCount = 0;
vector<string> rows;
while(fileIn != NULL) {
string temp;
getline(fileIn, temp);
// Skip empty lines.
if(temp.length() == 0) {
//cout << "Skip empty line no: " << lineCount << endl;
}
// Skip Comment lines.
else if(ofToString(temp[0]) == comments) {
//cout << "Skip Comment line no: " << lineCount << endl;
} else {
rows.push_back(temp);
// Split row into cols.
vector<string> cols = ofSplitString(rows[lineCount], ",");
// Write the string to data.
data.push_back(cols);
// Erase remaining elements.
cols.erase(cols.begin(), cols.end());
//cout << "cols: After erasing all elements, vector integers " << (cols.empty() ? "is" : "is not" ) << " empty" << endl;
lineCount++;
}
}
// Save the Number of Rows.
numRows = rows.size();
// Erase remaining elements.
rows.erase(rows.begin(), rows.end());
//cout << "rows: After erasing all elements, vector integers " << (rows.empty() ? "is" : "is not" ) << " empty" << endl;
// If File cannot opening, print a message to console.
} else {
cerr << "[ofxCsv] Error opening " << path << ".\n";
}
}
/**
* Load a CSV File.
* The default Comment sign is "#".
*
* @param path
* Set the file path.
* @param separator
* Set the Separator to split CSV file.
*/
void ofxCsv::loadFile(string path, string separator){
loadFile(path, separator, "#");
}
/**
* Load a CSV File.
* The default Separator is ",".
* The default Comment sign is "#".
*
* @param path
* Set the file path.
*/
void ofxCsv::loadFile(string path){
loadFile(path, ",", "#");
}
/**
* saveFile
*
* @param path
* Set the file path.
* @param separator
* Set the Separator to split CSV file.
* @param comments
* Set the Comments sign.
*/
void ofxCsv::saveFile(string path, string separator, string comments){
createFile(path);
ofstream myfile;
myfile.open(path.c_str());
if(myfile.is_open()){
// Write data to file.
for(int i=0; i<numRows; i++){
for(int j=0; j<data[i].size(); j++){
myfile << data[i][j] << separator;
if(j==(data[i].size()-1)){
myfile << "\n";
}
}
}
myfile.close();
//cout << "Open file" << endl;
} else {
//cout << "Unable to open file" << endl;
}
}
/**
* saveFile
*
* @param path
* Set the file path.
* @param separator
* Set the Separator to split Csv file.
*/
void ofxCsv::saveFile(string path, string separator) {
//createFile(path);
saveFile(path, separator, fileComments);
}
/**
* saveFile
*
* @param path
* Set the file path.
*/
void ofxCsv::saveFile(string path) {
//createFile(path);
saveFile(path, fileSeparator, fileComments);
}
/**
* Save file.
*/
void ofxCsv::saveFile() {
saveFile(filePath, fileSeparator, fileComments);
}
/**
* createFile
*
* @param path
* Set the File Path.
*/
void ofxCsv::createFile(string path){
FILE * pFile;
pFile = fopen (path.c_str(),"w");
if (pFile!=NULL) {
//fputs ("fopen example",pFile);
fclose (pFile);
}
}
/**
* loadFromString
*
* @param s
* String Input.
* @param separator
* Set the Separator to split CSV string.
*/
vector<string> ofxCsv::getFromString(string csv, string separator){
vector<string> cols = ofSplitString(csv, separator);
return cols;
}
/**
* loadFromString
*
* @param s
* String Input.
*/
vector<string> ofxCsv::getFromString(string csv){
getFromString(csv, ",");
}
/**
* Get the Integer of a specific row and column.
*
* @param row
* row number
* @param col
* column number
* @return integer
*/
int ofxCsv::getInt(int row, int col){
return ofToInt(data[row][col]);//temp;
}
/**
* Get the Float of a specific row and column.
*
* @param row
* row number
* @param col
* column number
* @return float
*/
float ofxCsv::getFloat(int row, int col){
return ofToFloat(data[row][col]);//temp;
}
/**
* Get the String of a specific row and column.
*
* @param row
* row number
* @param col
* column number
* @return float
*/
string ofxCsv::getString(int row, int col){
return data[row][col];
}
/**
* Get the Boolean of a specific row and column.
*
* @param row
* row number
* @param col
* column number
* @return bool
*/
bool ofxCsv::getBool(int row, int col){
return ofToBool(data[row][col]);
}
/**
* Set a specific Integer to a new value.
*
* @param row
* row number
* @param col
* column number
* @param what
* new Integer
*/
void ofxCsv::setInt(int row, int col, int what){
data[row][col] = ofToString(what);
}
/**
* Set a specific Float to a new value.
*
* @param row
* row number
* @param col
* column number
* @param what
* new row Float
*/
void ofxCsv::setFloat(int row, int col, float what){
data[row][col] = ofToString(what);
}
/**
* Set a specific String to a new value.
*
* @param row
* row number
* @param col
* column number
* @param what
* new row String
*/
void ofxCsv::setString(int row, int col, string what){
data[row][col] = ofToString(what);
}
/**
* setBool
* set a specific Boolean to a new value.
*
* @param row
* row number
* @param col
* column number
* @param what
* new row Boolean
*/
void ofxCsv::setBool(int row, int col, bool what){
data[row][col] = ofToString(what);
}
}
<commit_msg>Added missing return statement<commit_after>/**
* ofxCsv.cpp
* Inspired and based on Ben Fry's [table class](http://benfry.com/writing/map/Table.pde)
*
*
* The MIT License
*
* Copyright (c) 2011-2012 Paul Vollmer, http://www.wng.cc
*
* 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.
*
*
* @testet_oF 0.07
* @testet_plattform MacOs 10.6
* ??? Win
* ??? Linux
* @dependencies
* @modified 2012.05.06
* @version 0.1.2b
*/
#include "ofxCsv.h"
namespace wng {
/**
* A Constructor, usually called to initialize and start the class.
*/
ofxCsv::ofxCsv(){
}
/**
* Load a CSV File.
*
* @param path
* Set the File path.
* @param separator
* Set the Separator to split CSV File.
* @param comments
* Set the Comments sign.
*/
void ofxCsv::loadFile(string path, string separator, string comments){
// Save Filepath, Separator and Comments to variables.
filePath = path;
fileSeparator = separator;
fileComments = comments;
#ifdef OFXCSV_LOG
ofLog() << "[ofxCsv] loadFile";
ofLog() << " filePath: " << filePath;
ofLog() << " fileSeparator: " << fileSeparator;
ofLog() << " fileComments: " << fileComments;
#endif
// Declare a File Stream.
ifstream fileIn;
// Open your text File:
fileIn.open(path.c_str());
// Check if File is open.
if(fileIn.is_open()) {
int lineCount = 0;
vector<string> rows;
while(fileIn != NULL) {
string temp;
getline(fileIn, temp);
// Skip empty lines.
if(temp.length() == 0) {
//cout << "Skip empty line no: " << lineCount << endl;
}
// Skip Comment lines.
else if(ofToString(temp[0]) == comments) {
//cout << "Skip Comment line no: " << lineCount << endl;
} else {
rows.push_back(temp);
// Split row into cols.
vector<string> cols = ofSplitString(rows[lineCount], ",");
// Write the string to data.
data.push_back(cols);
// Erase remaining elements.
cols.erase(cols.begin(), cols.end());
//cout << "cols: After erasing all elements, vector integers " << (cols.empty() ? "is" : "is not" ) << " empty" << endl;
lineCount++;
}
}
// Save the Number of Rows.
numRows = rows.size();
// Erase remaining elements.
rows.erase(rows.begin(), rows.end());
//cout << "rows: After erasing all elements, vector integers " << (rows.empty() ? "is" : "is not" ) << " empty" << endl;
// If File cannot opening, print a message to console.
} else {
cerr << "[ofxCsv] Error opening " << path << ".\n";
}
}
/**
* Load a CSV File.
* The default Comment sign is "#".
*
* @param path
* Set the file path.
* @param separator
* Set the Separator to split CSV file.
*/
void ofxCsv::loadFile(string path, string separator){
loadFile(path, separator, "#");
}
/**
* Load a CSV File.
* The default Separator is ",".
* The default Comment sign is "#".
*
* @param path
* Set the file path.
*/
void ofxCsv::loadFile(string path){
loadFile(path, ",", "#");
}
/**
* saveFile
*
* @param path
* Set the file path.
* @param separator
* Set the Separator to split CSV file.
* @param comments
* Set the Comments sign.
*/
void ofxCsv::saveFile(string path, string separator, string comments){
createFile(path);
ofstream myfile;
myfile.open(path.c_str());
if(myfile.is_open()){
// Write data to file.
for(int i=0; i<numRows; i++){
for(int j=0; j<data[i].size(); j++){
myfile << data[i][j] << separator;
if(j==(data[i].size()-1)){
myfile << "\n";
}
}
}
myfile.close();
//cout << "Open file" << endl;
} else {
//cout << "Unable to open file" << endl;
}
}
/**
* saveFile
*
* @param path
* Set the file path.
* @param separator
* Set the Separator to split Csv file.
*/
void ofxCsv::saveFile(string path, string separator) {
//createFile(path);
saveFile(path, separator, fileComments);
}
/**
* saveFile
*
* @param path
* Set the file path.
*/
void ofxCsv::saveFile(string path) {
//createFile(path);
saveFile(path, fileSeparator, fileComments);
}
/**
* Save file.
*/
void ofxCsv::saveFile() {
saveFile(filePath, fileSeparator, fileComments);
}
/**
* createFile
*
* @param path
* Set the File Path.
*/
void ofxCsv::createFile(string path){
FILE * pFile;
pFile = fopen (path.c_str(),"w");
if (pFile!=NULL) {
//fputs ("fopen example",pFile);
fclose (pFile);
}
}
/**
* loadFromString
*
* @param s
* String Input.
* @param separator
* Set the Separator to split CSV string.
*/
vector<string> ofxCsv::getFromString(string csv, string separator){
vector<string> cols = ofSplitString(csv, separator);
return cols;
}
/**
* loadFromString
*
* @param s
* String Input.
*/
vector<string> ofxCsv::getFromString(string csv){
return getFromString(csv, ",");
}
/**
* Get the Integer of a specific row and column.
*
* @param row
* row number
* @param col
* column number
* @return integer
*/
int ofxCsv::getInt(int row, int col){
return ofToInt(data[row][col]);//temp;
}
/**
* Get the Float of a specific row and column.
*
* @param row
* row number
* @param col
* column number
* @return float
*/
float ofxCsv::getFloat(int row, int col){
return ofToFloat(data[row][col]);//temp;
}
/**
* Get the String of a specific row and column.
*
* @param row
* row number
* @param col
* column number
* @return float
*/
string ofxCsv::getString(int row, int col){
return data[row][col];
}
/**
* Get the Boolean of a specific row and column.
*
* @param row
* row number
* @param col
* column number
* @return bool
*/
bool ofxCsv::getBool(int row, int col){
return ofToBool(data[row][col]);
}
/**
* Set a specific Integer to a new value.
*
* @param row
* row number
* @param col
* column number
* @param what
* new Integer
*/
void ofxCsv::setInt(int row, int col, int what){
data[row][col] = ofToString(what);
}
/**
* Set a specific Float to a new value.
*
* @param row
* row number
* @param col
* column number
* @param what
* new row Float
*/
void ofxCsv::setFloat(int row, int col, float what){
data[row][col] = ofToString(what);
}
/**
* Set a specific String to a new value.
*
* @param row
* row number
* @param col
* column number
* @param what
* new row String
*/
void ofxCsv::setString(int row, int col, string what){
data[row][col] = ofToString(what);
}
/**
* setBool
* set a specific Boolean to a new value.
*
* @param row
* row number
* @param col
* column number
* @param what
* new row Boolean
*/
void ofxCsv::setBool(int row, int col, bool what){
data[row][col] = ofToString(what);
}
}
<|endoftext|> |
<commit_before>#include "../utils/parameter_parser.h"
#include "gtest/gtest.h"
#include <tuple>
TEST(ParserTest,StreamerParserSuccess) {
int size;
const char *file;
bool valid = false;
const char *testArguments[] = {"../sim_datastreamer", "-s", "42", "path/to/file/file"};
int argc = 4;
std::tie(file,size,std::ignore, std::ignore,valid) = taylortrack::utils::ParameterParser::parse_streamer(argc,testArguments);
ASSERT_TRUE(valid);
ASSERT_EQ(size,42);
ASSERT_EQ(file,"path/to/file/file");
}
TEST(ParserTest,StramerParserNoLenght) {
int size, argc = 2;
const char *file;
bool valid;
const char *testArguments[] = {"../sim_datastreamer","path/to/file/file"};
std::tie(file,size,std::ignore, std::ignore,valid) = taylortrack::utils::ParameterParser::parse_streamer(argc,testArguments);
ASSERT_TRUE(valid);
ASSERT_EQ(size,0);
ASSERT_EQ(file,"path/to/file/file");
}
TEST(ParserTest, InvalidParameter) {
int size, argc = 2;
const char *file;
bool valid;
const char *testArguments[] = {"./sim_datastreamer","-s"};
std::tie(std::ignore,std::ignore,std::ignore, std::ignore,valid) = taylortrack::utils::ParameterParser::parse_streamer(argc,testArguments);
ASSERT_FALSE(valid);
}
TEST(ParserTest, InvalidParameterName) {
int argc = 2;
const char *testArguments[] = {"./sim_datastreamer","-"};
bool valid=false;
std::tie(std::ignore,std::ignore,std::ignore, std::ignore,valid) = taylortrack::utils::ParameterParser::parse_streamer(argc,testArguments);
ASSERT_FALSE(valid);
}
/*TEST(ParserTest, InvalidParameterName) {
int argc = 2;
const char *testArguments[] = {"./sim_datastreamer","-"};
bool valid=false;
std::tie(std::ignore,std::ignore,std::ignore, std::ignore,valid) = taylortrack::utils::ParameterParser::parse_streamer(argc,testArguments);
ASSERT_FALSE(valid);
}*/<commit_msg>expanded parameter parser tests<commit_after>#include "../utils/parameter_parser.h"
#include "gtest/gtest.h"
#include <tuple>
TEST(ParserTest,StreamerParserSuccess) {
int size;
const char *file;
bool valid = false;
const char *testArguments[] = {"../sim_datastreamer", "-s", "42", "path/to/file/file"};
int argc = 4;
std::tie(file,size,std::ignore, std::ignore,valid) = taylortrack::utils::ParameterParser::parse_streamer(argc,testArguments);
ASSERT_TRUE(valid);
ASSERT_EQ(size,42);
ASSERT_EQ(file,"path/to/file/file");
}
TEST(ParserTest,SetOutportTest) {
const char *testArguments[] = {"../sim_datastreamer", "-o", "/taylortest", "path/to/file/file"};
int argc = 4;
bool valid = false;
const char* outport;
const char *file;
std::tie(file,std::ignore,outport, std::ignore,valid) = taylortrack::utils::ParameterParser::parse_streamer(argc,testArguments);
ASSERT_TRUE(valid);
ASSERT_EQ(outport, "/taylortest");
ASSERT_EQ(file,"path/to/file/file");
}
TEST(ParserTest,SetInportTest) {
const char *testArguments[] = {"../sim_datastreamer", "-i", "/taylortest", "path/to/file/file"};
int argc = 4;
bool valid = false;
const char* inport;
const char *file;
std::tie(file,std::ignore,std::ignore, inport,valid) = taylortrack::utils::ParameterParser::parse_streamer(argc,testArguments);
ASSERT_TRUE(valid);
ASSERT_EQ(inport, "/taylortest");
ASSERT_EQ(file,"path/to/file/file");
}
TEST(ParserTest,StramerParserNoLenght) {
int size, argc = 2;
const char *file;
bool valid;
const char *testArguments[] = {"../sim_datastreamer","path/to/file/file"};
std::tie(file,size,std::ignore, std::ignore,valid) = taylortrack::utils::ParameterParser::parse_streamer(argc,testArguments);
ASSERT_TRUE(valid);
ASSERT_EQ(size,0);
ASSERT_EQ(file,"path/to/file/file");
}
TEST(ParserTest, InvalidParameter) {
int size, argc = 2;
const char *file;
bool valid;
const char *testArguments[] = {"./sim_datastreamer","-s"};
std::tie(std::ignore,std::ignore,std::ignore, std::ignore,valid) = taylortrack::utils::ParameterParser::parse_streamer(argc,testArguments);
ASSERT_FALSE(valid);
}
TEST(ParserTest, InvalidParameterOutport) {
int size, argc = 2;
const char *file;
bool valid;
const char *testArguments[] = {"./sim_datastreamer","-o"};
std::tie(std::ignore,std::ignore,std::ignore, std::ignore,valid) = taylortrack::utils::ParameterParser::parse_streamer(argc,testArguments);
ASSERT_FALSE(valid);
}
TEST(ParserTest, InvalidParameterInport) {
int size, argc = 2;
const char *file;
bool valid;
const char *testArguments[] = {"./sim_datastreamer","-i"};
std::tie(std::ignore,std::ignore,std::ignore, std::ignore,valid) = taylortrack::utils::ParameterParser::parse_streamer(argc,testArguments);
ASSERT_FALSE(valid);
}
TEST(ParserTest, InvalidParameterName) {
int argc = 2;
const char *testArguments[] = {"./sim_datastreamer","-"};
bool valid=false;
std::tie(std::ignore,std::ignore,std::ignore, std::ignore,valid) = taylortrack::utils::ParameterParser::parse_streamer(argc,testArguments);
ASSERT_FALSE(valid);
}
/*TEST(ParserTest, InvalidParameterName) {
int argc = 2;
const char *testArguments[] = {"./sim_datastreamer","-"};
bool valid=false;
std::tie(std::ignore,std::ignore,std::ignore, std::ignore,valid) = taylortrack::utils::ParameterParser::parse_streamer(argc,testArguments);
ASSERT_FALSE(valid);
}*/<|endoftext|> |
<commit_before>#include <blackhole/macro.hpp>
#include "global.hpp"
#include "mocks/logger.hpp"
using namespace blackhole;
TEST(Macro, OpensInvalidLogRecordAndNotPush) {
log::record_t record;
mock::verbose_log_t<level> log;
EXPECT_CALL(log, open_record(level::debug))
.Times(1)
.WillOnce(Return(record));
EXPECT_CALL(log, push(_))
.Times(0);
BH_LOG(log, level::debug, "message");
}
struct ExtractMessageAttributeAction {
std::string& actual;
void operator ()(log::record_t record) const {
actual = record.extract<std::string>("message");
}
};
TEST(Macro, OpensValidRecordAndPush) {
log::record_t record;
record.insert(attribute::make("attr1", "value1"));
mock::verbose_log_t<level> log;
EXPECT_CALL(log, open_record(level::debug))
.Times(1)
.WillOnce(Return(record));
std::string actual;
ExtractMessageAttributeAction action { actual };
EXPECT_CALL(log, push(_))
.Times(1)
.WillOnce(WithArg<0>(Invoke(action)));
BH_LOG(log, level::debug, "value");
EXPECT_EQ("value", actual);
}
TEST(Macro, FormatMessageWithPrintfStyle) {
log::record_t record;
record.insert(attribute::make("attr1", "value1"));
mock::verbose_log_t<level> log;
EXPECT_CALL(log, open_record(level::debug))
.Times(1)
.WillOnce(Return(record));
std::string actual;
ExtractMessageAttributeAction action { actual };
EXPECT_CALL(log, push(_))
.Times(1)
.WillOnce(WithArg<0>(Invoke(action)));
BH_LOG(log, level::debug, "value [%d]: %s - okay", 100500, "blah");
EXPECT_EQ("value [100500]: blah - okay", actual);
}
struct ExtractAttributesAction {
struct pack_t {
std::string message;
int value;
std::string reason;
timeval timestamp;
};
pack_t& actual;
void operator ()(log::record_t record) const {
actual.message = record.extract<std::string>("message");
actual.value = record.extract<int>("value");
actual.reason = record.extract<std::string>("reason");
actual.timestamp = record.extract<timeval>("timestamp");
}
};
TEST(Macro, FormatMessageWithAttributes) {
log::record_t record;
record.insert(attribute::make("attr1", "value1"));
mock::verbose_log_t<level> log;
EXPECT_CALL(log, open_record(level::debug))
.Times(1)
.WillOnce(Return(record));
ExtractAttributesAction::pack_t actual;
ExtractAttributesAction action { actual };
EXPECT_CALL(log, push(_))
.Times(1)
.WillOnce(WithArg<0>(Invoke(action)));
BH_LOG(log, level::debug, "message")(
attribute::make("value", 42),
attribute::make("reason", "42"),
keyword::timestamp() = timeval{ 100500, 0 }
);
EXPECT_EQ("message", actual.message);
EXPECT_EQ(42, actual.value);
EXPECT_EQ("42", actual.reason);
EXPECT_EQ(100500, actual.timestamp.tv_sec);
}
TEST(Macro, FormatMessageWithPrintfStyleWithAttributes) {
log::record_t record;
record.insert(attribute::make("attr1", "value1"));
mock::verbose_log_t<level> log;
EXPECT_CALL(log, open_record(level::debug))
.Times(1)
.WillOnce(Return(record));
ExtractAttributesAction::pack_t actual;
ExtractAttributesAction action { actual };
EXPECT_CALL(log, push(_))
.Times(1)
.WillOnce(WithArg<0>(Invoke(action)));
BH_LOG(log, level::debug, "value [%d]: %s - okay", 100500, "blah")(
attribute::make("value", 42),
attribute::make("reason", "42"),
keyword::timestamp() = timeval{ 100500, 0 }
);
EXPECT_EQ("value [100500]: blah - okay", actual.message);
EXPECT_EQ(42, actual.value);
EXPECT_EQ("42", actual.reason);
EXPECT_EQ(100500, actual.timestamp.tv_sec);
}
namespace blackhole {
namespace format {
namespace message {
template<>
struct insitu<keyword::tag::severity_t<level>> {
static inline std::ostream& execute(std::ostream& stream, level lvl) {
static std::string DESCRIPTIONS[] = {
"DEBUG",
"INFO ",
"WARN ",
"ERROR"
};
std::size_t lvl_ = static_cast<std::size_t>(lvl);
if (lvl_ < sizeof(DESCRIPTIONS) / sizeof(DESCRIPTIONS[0])) {
stream << DESCRIPTIONS[lvl_];
} else {
stream << lvl_;
}
return stream;
}
};
} // namespace message
} // namespace format
} // namespace blackhole
TEST(Macro, SpecificKeywordMessageFormatting) {
log::record_t record;
record.insert(keyword::severity<level>() = level::debug);
mock::verbose_log_t<level> log;
EXPECT_CALL(log, open_record(level::debug))
.Times(1)
.WillOnce(Return(record));
std::string actual;
ExtractMessageAttributeAction action { actual };
EXPECT_CALL(log, push(_))
.Times(1)
.WillOnce(WithArg<0>(Invoke(action)));
BH_LOG(log, level::debug, "value: %s", keyword::severity<level>());
EXPECT_EQ("value: DEBUG", actual);
}
struct EmplaceCheckExtractAttributesAction {
struct pack_t {
std::string message;
int value;
std::string reason;
};
pack_t& actual;
void operator ()(log::record_t record) const {
actual.message = record.extract<std::string>("message");
actual.value = record.extract<int>("value");
actual.reason = record.extract<std::string>("reason");
}
};
TEST(Macro, EmplaceAttributes) {
log::record_t record;
record.insert(attribute::make("attr1", "value1"));
mock::verbose_log_t<level> log;
EXPECT_CALL(log, open_record(level::debug))
.Times(1)
.WillOnce(Return(record));
EmplaceCheckExtractAttributesAction::pack_t actual;
EmplaceCheckExtractAttributesAction action { actual };
EXPECT_CALL(log, push(_))
.Times(1)
.WillOnce(WithArg<0>(Invoke(action)));
BH_LOG(log, level::debug, "message")(
"value", 42,
"reason", "42"
);
EXPECT_EQ("message", actual.message);
EXPECT_EQ(42, actual.value);
EXPECT_EQ("42", actual.reason);
}
namespace testing {
struct streamable_value_t {
std::string message;
int value;
friend std::ostream& operator<<(std::ostream& stream, const streamable_value_t& value) {
stream << "['" << value.message << "', " << value.value << "]";
return stream;
}
};
} // namespace testing
struct ExtractStreamableValueAttributesAction {
struct pack_t {
std::string message;
std::string value;
};
pack_t& actual;
void operator()(const log::record_t& record) const {
actual.message = record.extract<std::string>("message");
actual.value = record.extract<std::string>("value");
}
};
TEST(Macro, UsingStreamOperatorIfNoImplicitConversionAvailable) {
static_assert(traits::supports::stream_push<streamable_value_t>::value,
"`streamable_value_t` must support stream push operator<<");
streamable_value_t value = { "42", 42 };
log::record_t record;
record.insert(attribute::make("attr1", "value1"));
mock::verbose_log_t<level> log;
EXPECT_CALL(log, open_record(level::debug))
.Times(1)
.WillOnce(Return(record));
ExtractStreamableValueAttributesAction::pack_t actual;
ExtractStreamableValueAttributesAction action { actual };
EXPECT_CALL(log, push(_))
.Times(1)
.WillOnce(WithArg<0>(Invoke(action)));
BH_LOG(log, level::debug, "message")("value", value);
EXPECT_EQ("message", actual.message);
EXPECT_EQ("['42', 42]", actual.value);
}
TEST(Macro, InitializerListAttributes) {
log::record_t record;
record.insert(attribute::make("attr1", "value1"));
mock::verbose_log_t<level> log;
EXPECT_CALL(log, open_record(level::debug))
.Times(1)
.WillOnce(Return(record));
ExtractStreamableValueAttributesAction::pack_t actual;
ExtractStreamableValueAttributesAction action { actual };
EXPECT_CALL(log, push(_))
.Times(1)
.WillOnce(WithArg<0>(Invoke(action)));
BH_LOG(log, level::debug, "message")(attribute::list({
{"value", "42"}
}));
EXPECT_EQ("message", actual.message);
EXPECT_EQ("42", actual.value);
}
namespace RecursiveAttributeFeeders {
struct action_t {
struct pack_t {
std::string message;
std::string value;
int nested;
};
pack_t& actual;
void operator()(const log::record_t& record) const {
actual.message = record.extract<std::string>("message");
actual.value = record.extract<std::string>("value");
actual.nested = record.extract<int>("nested");
}
};
} // namespace RecursiveAttributeFeeders
TEST(Macro, RecursiveAttributeFeeders) {
log::record_t record;
record.insert(attribute::make("attr1", "value1"));
mock::verbose_log_t<level> log;
EXPECT_CALL(log, open_record(level::debug))
.Times(1)
.WillOnce(Return(record));
RecursiveAttributeFeeders::action_t::pack_t actual;
RecursiveAttributeFeeders::action_t action { actual };
EXPECT_CALL(log, push(_))
.Times(1)
.WillOnce(WithArg<0>(Invoke(action)));
BH_LOG(log, level::debug, "message")("value", "42")("nested", 42);
EXPECT_EQ("message", actual.message);
EXPECT_EQ("42", actual.value);
EXPECT_EQ(42, actual.nested);
}
<commit_msg>[Code Style] Style.<commit_after>#include <blackhole/macro.hpp>
#include "global.hpp"
#include "mocks/logger.hpp"
using namespace blackhole;
TEST(Macro, OpensInvalidLogRecordAndNotPush) {
log::record_t record;
mock::verbose_log_t<level> log;
EXPECT_CALL(log, open_record(level::debug))
.Times(1)
.WillOnce(Return(record));
EXPECT_CALL(log, push(_))
.Times(0);
BH_LOG(log, level::debug, "message");
}
struct ExtractMessageAttributeAction {
std::string& actual;
void operator()(log::record_t record) const {
actual = record.extract<std::string>("message");
}
};
TEST(Macro, OpensValidRecordAndPush) {
log::record_t record;
record.insert(attribute::make("attr1", "value1"));
mock::verbose_log_t<level> log;
EXPECT_CALL(log, open_record(level::debug))
.Times(1)
.WillOnce(Return(record));
std::string actual;
ExtractMessageAttributeAction action { actual };
EXPECT_CALL(log, push(_))
.Times(1)
.WillOnce(WithArg<0>(Invoke(action)));
BH_LOG(log, level::debug, "value");
EXPECT_EQ("value", actual);
}
TEST(Macro, FormatMessageWithPrintfStyle) {
log::record_t record;
record.insert(attribute::make("attr1", "value1"));
mock::verbose_log_t<level> log;
EXPECT_CALL(log, open_record(level::debug))
.Times(1)
.WillOnce(Return(record));
std::string actual;
ExtractMessageAttributeAction action { actual };
EXPECT_CALL(log, push(_))
.Times(1)
.WillOnce(WithArg<0>(Invoke(action)));
BH_LOG(log, level::debug, "value [%d]: %s - okay", 100500, "blah");
EXPECT_EQ("value [100500]: blah - okay", actual);
}
struct ExtractAttributesAction {
struct pack_t {
std::string message;
int value;
std::string reason;
timeval timestamp;
};
pack_t& actual;
void operator ()(log::record_t record) const {
actual.message = record.extract<std::string>("message");
actual.value = record.extract<int>("value");
actual.reason = record.extract<std::string>("reason");
actual.timestamp = record.extract<timeval>("timestamp");
}
};
TEST(Macro, FormatMessageWithAttributes) {
log::record_t record;
record.insert(attribute::make("attr1", "value1"));
mock::verbose_log_t<level> log;
EXPECT_CALL(log, open_record(level::debug))
.Times(1)
.WillOnce(Return(record));
ExtractAttributesAction::pack_t actual;
ExtractAttributesAction action { actual };
EXPECT_CALL(log, push(_))
.Times(1)
.WillOnce(WithArg<0>(Invoke(action)));
BH_LOG(log, level::debug, "message")(
attribute::make("value", 42),
attribute::make("reason", "42"),
keyword::timestamp() = timeval{ 100500, 0 }
);
EXPECT_EQ("message", actual.message);
EXPECT_EQ(42, actual.value);
EXPECT_EQ("42", actual.reason);
EXPECT_EQ(100500, actual.timestamp.tv_sec);
}
TEST(Macro, FormatMessageWithPrintfStyleWithAttributes) {
log::record_t record;
record.insert(attribute::make("attr1", "value1"));
mock::verbose_log_t<level> log;
EXPECT_CALL(log, open_record(level::debug))
.Times(1)
.WillOnce(Return(record));
ExtractAttributesAction::pack_t actual;
ExtractAttributesAction action { actual };
EXPECT_CALL(log, push(_))
.Times(1)
.WillOnce(WithArg<0>(Invoke(action)));
BH_LOG(log, level::debug, "value [%d]: %s - okay", 100500, "blah")(
attribute::make("value", 42),
attribute::make("reason", "42"),
keyword::timestamp() = timeval{ 100500, 0 }
);
EXPECT_EQ("value [100500]: blah - okay", actual.message);
EXPECT_EQ(42, actual.value);
EXPECT_EQ("42", actual.reason);
EXPECT_EQ(100500, actual.timestamp.tv_sec);
}
namespace blackhole {
namespace format {
namespace message {
template<>
struct insitu<keyword::tag::severity_t<level>> {
static inline std::ostream& execute(std::ostream& stream, level lvl) {
static std::string DESCRIPTIONS[] = {
"DEBUG",
"INFO ",
"WARN ",
"ERROR"
};
std::size_t lvl_ = static_cast<std::size_t>(lvl);
if (lvl_ < sizeof(DESCRIPTIONS) / sizeof(DESCRIPTIONS[0])) {
stream << DESCRIPTIONS[lvl_];
} else {
stream << lvl_;
}
return stream;
}
};
} // namespace message
} // namespace format
} // namespace blackhole
TEST(Macro, SpecificKeywordMessageFormatting) {
log::record_t record;
record.insert(keyword::severity<level>() = level::debug);
mock::verbose_log_t<level> log;
EXPECT_CALL(log, open_record(level::debug))
.Times(1)
.WillOnce(Return(record));
std::string actual;
ExtractMessageAttributeAction action { actual };
EXPECT_CALL(log, push(_))
.Times(1)
.WillOnce(WithArg<0>(Invoke(action)));
BH_LOG(log, level::debug, "value: %s", keyword::severity<level>());
EXPECT_EQ("value: DEBUG", actual);
}
struct EmplaceCheckExtractAttributesAction {
struct pack_t {
std::string message;
int value;
std::string reason;
};
pack_t& actual;
void operator ()(log::record_t record) const {
actual.message = record.extract<std::string>("message");
actual.value = record.extract<int>("value");
actual.reason = record.extract<std::string>("reason");
}
};
TEST(Macro, EmplaceAttributes) {
log::record_t record;
record.insert(attribute::make("attr1", "value1"));
mock::verbose_log_t<level> log;
EXPECT_CALL(log, open_record(level::debug))
.Times(1)
.WillOnce(Return(record));
EmplaceCheckExtractAttributesAction::pack_t actual;
EmplaceCheckExtractAttributesAction action { actual };
EXPECT_CALL(log, push(_))
.Times(1)
.WillOnce(WithArg<0>(Invoke(action)));
BH_LOG(log, level::debug, "message")(
"value", 42,
"reason", "42"
);
EXPECT_EQ("message", actual.message);
EXPECT_EQ(42, actual.value);
EXPECT_EQ("42", actual.reason);
}
namespace testing {
struct streamable_value_t {
std::string message;
int value;
friend std::ostream& operator<<(std::ostream& stream, const streamable_value_t& value) {
stream << "['" << value.message << "', " << value.value << "]";
return stream;
}
};
} // namespace testing
struct ExtractStreamableValueAttributesAction {
struct pack_t {
std::string message;
std::string value;
};
pack_t& actual;
void operator()(const log::record_t& record) const {
actual.message = record.extract<std::string>("message");
actual.value = record.extract<std::string>("value");
}
};
TEST(Macro, UsingStreamOperatorIfNoImplicitConversionAvailable) {
static_assert(traits::supports::stream_push<streamable_value_t>::value,
"`streamable_value_t` must support stream push operator<<");
streamable_value_t value = { "42", 42 };
log::record_t record;
record.insert(attribute::make("attr1", "value1"));
mock::verbose_log_t<level> log;
EXPECT_CALL(log, open_record(level::debug))
.Times(1)
.WillOnce(Return(record));
ExtractStreamableValueAttributesAction::pack_t actual;
ExtractStreamableValueAttributesAction action { actual };
EXPECT_CALL(log, push(_))
.Times(1)
.WillOnce(WithArg<0>(Invoke(action)));
BH_LOG(log, level::debug, "message")("value", value);
EXPECT_EQ("message", actual.message);
EXPECT_EQ("['42', 42]", actual.value);
}
TEST(Macro, InitializerListAttributes) {
log::record_t record;
record.insert(attribute::make("attr1", "value1"));
mock::verbose_log_t<level> log;
EXPECT_CALL(log, open_record(level::debug))
.Times(1)
.WillOnce(Return(record));
ExtractStreamableValueAttributesAction::pack_t actual;
ExtractStreamableValueAttributesAction action { actual };
EXPECT_CALL(log, push(_))
.Times(1)
.WillOnce(WithArg<0>(Invoke(action)));
BH_LOG(log, level::debug, "message")(attribute::list({
{"value", "42"}
}));
EXPECT_EQ("message", actual.message);
EXPECT_EQ("42", actual.value);
}
namespace RecursiveAttributeFeeders {
struct action_t {
struct pack_t {
std::string message;
std::string value;
int nested;
};
pack_t& actual;
void operator()(const log::record_t& record) const {
actual.message = record.extract<std::string>("message");
actual.value = record.extract<std::string>("value");
actual.nested = record.extract<int>("nested");
}
};
} // namespace RecursiveAttributeFeeders
TEST(Macro, RecursiveAttributeFeeders) {
log::record_t record;
record.insert(attribute::make("attr1", "value1"));
mock::verbose_log_t<level> log;
EXPECT_CALL(log, open_record(level::debug))
.Times(1)
.WillOnce(Return(record));
RecursiveAttributeFeeders::action_t::pack_t actual;
RecursiveAttributeFeeders::action_t action { actual };
EXPECT_CALL(log, push(_))
.Times(1)
.WillOnce(WithArg<0>(Invoke(action)));
BH_LOG(log, level::debug, "message")("value", "42")("nested", 42);
EXPECT_EQ("message", actual.message);
EXPECT_EQ("42", actual.value);
EXPECT_EQ(42, actual.nested);
}
<|endoftext|> |
<commit_before>// Plugins.cpp
// Copyright (c) 2009, Dan Heeks
// This program is released under the BSD license. See the file COPYING for details.
#include "stdafx.h"
#include "Plugins.h"
#include "HeeksConfig.h"
enum
{
ID_BUTTON_ADD,
ID_BUTTON_EDIT,
ID_BUTTON_REMOVE,
ID_BUTTON_PLUGIN_BROWSE,
ID_LISTBOX_CONTROL
};
BEGIN_EVENT_TABLE( CPluginItemDialog, wxDialog )
EVT_BUTTON( ID_BUTTON_PLUGIN_BROWSE, CPluginItemDialog::OnButtonBrowse )
EVT_BUTTON( wxID_OK, CPluginItemDialog::OnButtonOK )
EVT_BUTTON( wxID_CANCEL, CPluginItemDialog::OnButtonCancel )
END_EVENT_TABLE()
CPluginItemDialog::CPluginItemDialog(wxWindow *parent, const wxString& title, PluginData& pd):wxDialog(parent, wxID_ANY, title, wxDefaultPosition, wxDefaultSize, wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER)
{
m_pd = &pd;
m_panel = new wxPanel(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL);
// create buttons
wxButton *button1 = new wxButton(m_panel, wxID_OK);
wxButton *button2 = new wxButton(m_panel, wxID_CANCEL);
wxBoxSizer *mainsizer = new wxBoxSizer( wxVERTICAL );
wxFlexGridSizer *gridsizer = new wxFlexGridSizer(3, 5, 5);
gridsizer->Add(new wxStaticText(m_panel, wxID_ANY, _("Name")), wxSizerFlags().Align(wxALIGN_CENTER_VERTICAL));
m_name_text_ctrl = new wxTextCtrl(m_panel, wxID_ANY, pd.name);
gridsizer->Add(m_name_text_ctrl, wxSizerFlags().Align(wxALIGN_CENTER_VERTICAL).Expand());
gridsizer->Add(new wxStaticText(m_panel, wxID_ANY, _T("")), wxSizerFlags().Align(wxALIGN_CENTER_VERTICAL));
gridsizer->Add(new wxStaticText(m_panel, wxID_ANY, _("File Path")), wxSizerFlags().Align(wxALIGN_CENTER_VERTICAL));
m_path_text_ctrl = new wxTextCtrl(m_panel, wxID_ANY, pd.path, wxDefaultPosition, wxSize(400, 0));
gridsizer->Add(m_path_text_ctrl, wxSizerFlags().Align(wxALIGN_CENTER_VERTICAL).Expand());
wxButton* browse_button = new wxButton(m_panel, ID_BUTTON_PLUGIN_BROWSE, _T("..."));
gridsizer->Add(browse_button, wxSizerFlags().Align(wxALIGN_CENTER_VERTICAL));
if(pd.hard_coded)
{
// don't allow editing of hard coded plugins
m_name_text_ctrl->Enable(false);
m_path_text_ctrl->Enable(false);
browse_button->Enable(false);
}
gridsizer->AddGrowableCol(1, 1);
wxBoxSizer *bottomsizer = new wxBoxSizer( wxHORIZONTAL );
bottomsizer->Add( button1, 0, wxALL, 10 );
bottomsizer->Add( button2, 0, wxALL, 10 );
mainsizer->Add( gridsizer, wxSizerFlags().Align(wxALIGN_CENTER).Border(wxALL, 10).Expand() );
mainsizer->Add( bottomsizer, wxSizerFlags().Align(wxALIGN_CENTER) );
// tell frame to make use of sizer (or constraints, if any)
m_panel->SetAutoLayout( true );
m_panel->SetSizer( mainsizer );
#ifndef __WXWINCE__
// don't allow frame to get smaller than what the sizers tell ye
mainsizer->SetSizeHints( this );
#endif
Show(true);
}
void CPluginItemDialog::OnButtonOK(wxCommandEvent& event)
{
// it must have a name
if(m_name_text_ctrl->GetValue().Len() == 0)
{
wxMessageBox(_("Plugin must have a name!"));
m_name_text_ctrl->SetFocus();
return;
}
// it must have a file path
if(m_path_text_ctrl->GetValue().Len() == 0)
{
wxMessageBox(_("No file specified!"));
m_path_text_ctrl->SetFocus();
return;
}
m_pd->name = m_name_text_ctrl->GetValue();
m_pd->path = m_path_text_ctrl->GetValue();
EndModal(wxID_OK);
}
void CPluginItemDialog::OnButtonCancel(wxCommandEvent& event)
{
EndModal(wxID_CANCEL);
}
void CPluginItemDialog::OnButtonBrowse(wxCommandEvent& event)
{
#ifdef WIN32
wxString ext_str(_T("*.dll"));
#else
wxString ext_str(_T("*.so*"));
#endif
wxString wildcard_string = wxString(_("shared library files")) + _T(" |") + ext_str;
wxFileDialog dialog(this, _("Choose shared library file"), wxEmptyString, wxEmptyString, wildcard_string);
dialog.CentreOnParent();
if (dialog.ShowModal() == wxID_OK)
{
m_path_text_ctrl->SetValue(dialog.GetPath());
}
}
BEGIN_EVENT_TABLE( CPluginsDialog, wxDialog )
EVT_BUTTON( ID_BUTTON_ADD, CPluginsDialog::OnButtonAdd )
EVT_BUTTON( ID_BUTTON_EDIT, CPluginsDialog::OnButtonEdit )
EVT_UPDATE_UI(ID_BUTTON_EDIT, CPluginsDialog::OnUpdateEdit)
EVT_BUTTON( ID_BUTTON_REMOVE, CPluginsDialog::OnButtonRemove )
EVT_UPDATE_UI(ID_BUTTON_REMOVE, CPluginsDialog::OnUpdateRemove)
EVT_BUTTON( wxID_OK, CPluginsDialog::OnButtonOK )
EVT_BUTTON( wxID_CANCEL, CPluginsDialog::OnButtonCancel )
EVT_LISTBOX_DCLICK(ID_LISTBOX_CONTROL, CPluginsDialog::OnListboxDblClick)
END_EVENT_TABLE()
CPluginsDialog::CPluginsDialog(wxWindow *parent):wxDialog(parent, wxID_ANY, _("HeeksCAD plugin libraries"), wxDefaultPosition, wxDefaultSize, wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER)
{
// make a panel with some controls
m_panel = new wxPanel(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL);
ReadPluginsList(m_plugins);
CreateCheckListbox();
// create buttons
wxButton *button1 = new wxButton(m_panel, ID_BUTTON_ADD, _("New"));
wxButton *button2 = new wxButton(m_panel, ID_BUTTON_EDIT, _("Edit"));
wxButton *button3 = new wxButton(m_panel, ID_BUTTON_REMOVE, _("Delete"));
wxButton *button4 = new wxButton(m_panel, wxID_OK);
wxButton *button5 = new wxButton(m_panel, wxID_CANCEL);
wxBoxSizer *mainsizer = new wxBoxSizer( wxVERTICAL );
mainsizer->Add( m_pListBox, 1, wxGROW|wxALL, 10 );
wxBoxSizer *bottomsizer = new wxBoxSizer( wxHORIZONTAL );
bottomsizer->Add( button1, 0, wxALL, 10 );
bottomsizer->Add( button2, 0, wxALL, 10 );
bottomsizer->Add( button3, 0, wxALL, 10 );
bottomsizer->Add( button4, 0, wxALL, 10 );
bottomsizer->Add( button5, 0, wxALL, 10 );
mainsizer->Add( bottomsizer, 0, wxCENTER );
// tell frame to make use of sizer (or constraints, if any)
m_panel->SetAutoLayout( true );
m_panel->SetSizer( mainsizer );
#ifndef __WXWINCE__
// don't allow frame to get smaller than what the sizers tell ye
mainsizer->SetSizeHints( this );
#endif
Show(true);
}
void ReadPluginsList(std::list<PluginData> &plugins)
{
plugins.clear();
::wxSetWorkingDirectory(wxGetApp().GetExeFolder());
HeeksConfig plugins_config;
plugins_config.SetPath(_T("/plugins"));
wxString key;
long Index;
wxString str;
bool entry_found = false;
entry_found = plugins_config.GetFirstEntry(key, Index);
while(entry_found)
{
plugins_config.Read(key, &str);
PluginData pd;
if(str[0] == '#')
{
str = str.Mid(1);
pd.enabled = false;
}
else
{
pd.enabled = true;
}
pd.name = key;
pd.path = str;
plugins.push_back(pd);
entry_found = plugins_config.GetNextEntry(key, Index);
}
#ifdef ADDWIREPLUGIN_DEBUG
{
PluginData pd;
pd.enabled = true;
pd.hard_coded = true;
pd.name = _T("WireHeeksCAD");
pd.path = _T("$(SLDWORKSPATH)/p4c/bin/WireHeeksCADd.dll");
plugins.push_back(pd);
}
#endif
#ifdef ADDWIREPLUGIN
{
PluginData pd;
pd.enabled = true;
pd.hard_coded = true;
pd.name = _T("WireHeeksCAD");
pd.path = _T("..\Release\p2c\bin\WireHeeksCAD.dll");
plugins.push_back(pd);
}
#endif
}
void CPluginsDialog::CreateCheckListbox(long flags)
{
wxString *astrChoices = new wxString[m_plugins.size()];
unsigned int ui = 0;
for ( std::list<PluginData>::iterator It = m_plugins.begin(); It != m_plugins.end(); It++, ui++ )
{
PluginData &pd = *It;
astrChoices[ui] = pd.name;
}
m_pListBox = new wxCheckListBox
(
m_panel, // parent
ID_LISTBOX_CONTROL, // control id
wxPoint(10, 10), // listbox poistion
wxSize(400, 100), // listbox size
m_plugins.size(), // number of strings
astrChoices, // array of strings
flags
);
delete [] astrChoices;
ui = 0;
for ( std::list<PluginData>::iterator It = m_plugins.begin(); It != m_plugins.end(); It++, ui++ )
{
PluginData &pd = *It;
if(pd.enabled)m_pListBox->Check(ui);
}
}
void CPluginsDialog::EditSelected(unsigned int selection)
{
unsigned int ui = 0;
for ( std::list<PluginData>::iterator It = m_plugins.begin(); It != m_plugins.end(); It++, ui++ )
{
if(ui == selection)
{
PluginData &pd = *It;
CPluginItemDialog dlg(this, _("Add New Plugin"), pd);
if(dlg.ShowModal() == wxID_OK)
{
// updata the check list
delete m_pListBox;
CreateCheckListbox();
}
}
}
}
void CPluginsDialog::OnButtonAdd(wxCommandEvent& event)
{
PluginData pd;
CPluginItemDialog dlg(this, _("Add New Plugin"), pd);
if(dlg.ShowModal() == wxID_OK)
{
// add the new item
m_plugins.push_back(pd);
// updata the check list
delete m_pListBox;
CreateCheckListbox();
}
}
void CPluginsDialog::OnButtonEdit(wxCommandEvent& event)
{
unsigned int selection = m_pListBox->GetSelection();
EditSelected(selection);
}
void CPluginsDialog::OnUpdateEdit( wxUpdateUIEvent& event )
{
event.Enable(m_pListBox->GetSelection() >= 0);
}
void CPluginsDialog::OnUpdateRemove( wxUpdateUIEvent& event )
{
event.Enable(m_pListBox->GetSelection() >= 0);
}
void CPluginsDialog::OnButtonRemove(wxCommandEvent& event)
{
unsigned int selection = m_pListBox->GetSelection();
unsigned int ui = 0;
for ( std::list<PluginData>::iterator It = m_plugins.begin(); It != m_plugins.end(); It++, ui++ )
{
if(ui == selection)
{
m_plugins.erase(It);
// updata the check list
delete m_pListBox;
CreateCheckListbox();
break;
}
}
}
void CPluginsDialog::OnButtonOK(wxCommandEvent& event)
{
::wxSetWorkingDirectory(wxGetApp().GetExeFolder());
HeeksConfig plugins_config;
plugins_config.DeleteGroup(_T("plugins"));
plugins_config.SetPath(_T("/plugins"));
unsigned int ui = 0;
for ( std::list<PluginData>::iterator It = m_plugins.begin(); It != m_plugins.end(); It++, ui++ )
{
PluginData &pd = *It;
if(pd.hard_coded)continue;
pd.enabled = m_pListBox->IsChecked(ui);
wxString value = pd.path;
if(!(pd.enabled))value.Prepend(_T("#"));
plugins_config.Write(pd.name, value);
}
EndModal(wxID_OK);
}
void CPluginsDialog::OnButtonCancel(wxCommandEvent& event)
{
EndModal(wxID_CANCEL);
}
void CPluginsDialog::OnListboxDblClick(wxCommandEvent& WXUNUSED(event))
{
int selection = m_pListBox->GetSelection();
EditSelected(selection);
}
<commit_msg>I've changed my customers dll path to a sample one; you don't need my actual code here.<commit_after>// Plugins.cpp
// Copyright (c) 2009, Dan Heeks
// This program is released under the BSD license. See the file COPYING for details.
#include "stdafx.h"
#include "Plugins.h"
#include "HeeksConfig.h"
enum
{
ID_BUTTON_ADD,
ID_BUTTON_EDIT,
ID_BUTTON_REMOVE,
ID_BUTTON_PLUGIN_BROWSE,
ID_LISTBOX_CONTROL
};
BEGIN_EVENT_TABLE( CPluginItemDialog, wxDialog )
EVT_BUTTON( ID_BUTTON_PLUGIN_BROWSE, CPluginItemDialog::OnButtonBrowse )
EVT_BUTTON( wxID_OK, CPluginItemDialog::OnButtonOK )
EVT_BUTTON( wxID_CANCEL, CPluginItemDialog::OnButtonCancel )
END_EVENT_TABLE()
CPluginItemDialog::CPluginItemDialog(wxWindow *parent, const wxString& title, PluginData& pd):wxDialog(parent, wxID_ANY, title, wxDefaultPosition, wxDefaultSize, wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER)
{
m_pd = &pd;
m_panel = new wxPanel(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL);
// create buttons
wxButton *button1 = new wxButton(m_panel, wxID_OK);
wxButton *button2 = new wxButton(m_panel, wxID_CANCEL);
wxBoxSizer *mainsizer = new wxBoxSizer( wxVERTICAL );
wxFlexGridSizer *gridsizer = new wxFlexGridSizer(3, 5, 5);
gridsizer->Add(new wxStaticText(m_panel, wxID_ANY, _("Name")), wxSizerFlags().Align(wxALIGN_CENTER_VERTICAL));
m_name_text_ctrl = new wxTextCtrl(m_panel, wxID_ANY, pd.name);
gridsizer->Add(m_name_text_ctrl, wxSizerFlags().Align(wxALIGN_CENTER_VERTICAL).Expand());
gridsizer->Add(new wxStaticText(m_panel, wxID_ANY, _T("")), wxSizerFlags().Align(wxALIGN_CENTER_VERTICAL));
gridsizer->Add(new wxStaticText(m_panel, wxID_ANY, _("File Path")), wxSizerFlags().Align(wxALIGN_CENTER_VERTICAL));
m_path_text_ctrl = new wxTextCtrl(m_panel, wxID_ANY, pd.path, wxDefaultPosition, wxSize(400, 0));
gridsizer->Add(m_path_text_ctrl, wxSizerFlags().Align(wxALIGN_CENTER_VERTICAL).Expand());
wxButton* browse_button = new wxButton(m_panel, ID_BUTTON_PLUGIN_BROWSE, _T("..."));
gridsizer->Add(browse_button, wxSizerFlags().Align(wxALIGN_CENTER_VERTICAL));
if(pd.hard_coded)
{
// don't allow editing of hard coded plugins
m_name_text_ctrl->Enable(false);
m_path_text_ctrl->Enable(false);
browse_button->Enable(false);
}
gridsizer->AddGrowableCol(1, 1);
wxBoxSizer *bottomsizer = new wxBoxSizer( wxHORIZONTAL );
bottomsizer->Add( button1, 0, wxALL, 10 );
bottomsizer->Add( button2, 0, wxALL, 10 );
mainsizer->Add( gridsizer, wxSizerFlags().Align(wxALIGN_CENTER).Border(wxALL, 10).Expand() );
mainsizer->Add( bottomsizer, wxSizerFlags().Align(wxALIGN_CENTER) );
// tell frame to make use of sizer (or constraints, if any)
m_panel->SetAutoLayout( true );
m_panel->SetSizer( mainsizer );
#ifndef __WXWINCE__
// don't allow frame to get smaller than what the sizers tell ye
mainsizer->SetSizeHints( this );
#endif
Show(true);
}
void CPluginItemDialog::OnButtonOK(wxCommandEvent& event)
{
// it must have a name
if(m_name_text_ctrl->GetValue().Len() == 0)
{
wxMessageBox(_("Plugin must have a name!"));
m_name_text_ctrl->SetFocus();
return;
}
// it must have a file path
if(m_path_text_ctrl->GetValue().Len() == 0)
{
wxMessageBox(_("No file specified!"));
m_path_text_ctrl->SetFocus();
return;
}
m_pd->name = m_name_text_ctrl->GetValue();
m_pd->path = m_path_text_ctrl->GetValue();
EndModal(wxID_OK);
}
void CPluginItemDialog::OnButtonCancel(wxCommandEvent& event)
{
EndModal(wxID_CANCEL);
}
void CPluginItemDialog::OnButtonBrowse(wxCommandEvent& event)
{
#ifdef WIN32
wxString ext_str(_T("*.dll"));
#else
wxString ext_str(_T("*.so*"));
#endif
wxString wildcard_string = wxString(_("shared library files")) + _T(" |") + ext_str;
wxFileDialog dialog(this, _("Choose shared library file"), wxEmptyString, wxEmptyString, wildcard_string);
dialog.CentreOnParent();
if (dialog.ShowModal() == wxID_OK)
{
m_path_text_ctrl->SetValue(dialog.GetPath());
}
}
BEGIN_EVENT_TABLE( CPluginsDialog, wxDialog )
EVT_BUTTON( ID_BUTTON_ADD, CPluginsDialog::OnButtonAdd )
EVT_BUTTON( ID_BUTTON_EDIT, CPluginsDialog::OnButtonEdit )
EVT_UPDATE_UI(ID_BUTTON_EDIT, CPluginsDialog::OnUpdateEdit)
EVT_BUTTON( ID_BUTTON_REMOVE, CPluginsDialog::OnButtonRemove )
EVT_UPDATE_UI(ID_BUTTON_REMOVE, CPluginsDialog::OnUpdateRemove)
EVT_BUTTON( wxID_OK, CPluginsDialog::OnButtonOK )
EVT_BUTTON( wxID_CANCEL, CPluginsDialog::OnButtonCancel )
EVT_LISTBOX_DCLICK(ID_LISTBOX_CONTROL, CPluginsDialog::OnListboxDblClick)
END_EVENT_TABLE()
CPluginsDialog::CPluginsDialog(wxWindow *parent):wxDialog(parent, wxID_ANY, _("HeeksCAD plugin libraries"), wxDefaultPosition, wxDefaultSize, wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER)
{
// make a panel with some controls
m_panel = new wxPanel(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL);
ReadPluginsList(m_plugins);
CreateCheckListbox();
// create buttons
wxButton *button1 = new wxButton(m_panel, ID_BUTTON_ADD, _("New"));
wxButton *button2 = new wxButton(m_panel, ID_BUTTON_EDIT, _("Edit"));
wxButton *button3 = new wxButton(m_panel, ID_BUTTON_REMOVE, _("Delete"));
wxButton *button4 = new wxButton(m_panel, wxID_OK);
wxButton *button5 = new wxButton(m_panel, wxID_CANCEL);
wxBoxSizer *mainsizer = new wxBoxSizer( wxVERTICAL );
mainsizer->Add( m_pListBox, 1, wxGROW|wxALL, 10 );
wxBoxSizer *bottomsizer = new wxBoxSizer( wxHORIZONTAL );
bottomsizer->Add( button1, 0, wxALL, 10 );
bottomsizer->Add( button2, 0, wxALL, 10 );
bottomsizer->Add( button3, 0, wxALL, 10 );
bottomsizer->Add( button4, 0, wxALL, 10 );
bottomsizer->Add( button5, 0, wxALL, 10 );
mainsizer->Add( bottomsizer, 0, wxCENTER );
// tell frame to make use of sizer (or constraints, if any)
m_panel->SetAutoLayout( true );
m_panel->SetSizer( mainsizer );
#ifndef __WXWINCE__
// don't allow frame to get smaller than what the sizers tell ye
mainsizer->SetSizeHints( this );
#endif
Show(true);
}
void ReadPluginsList(std::list<PluginData> &plugins)
{
plugins.clear();
::wxSetWorkingDirectory(wxGetApp().GetExeFolder());
HeeksConfig plugins_config;
plugins_config.SetPath(_T("/plugins"));
wxString key;
long Index;
wxString str;
bool entry_found = false;
entry_found = plugins_config.GetFirstEntry(key, Index);
while(entry_found)
{
plugins_config.Read(key, &str);
PluginData pd;
if(str[0] == '#')
{
str = str.Mid(1);
pd.enabled = false;
}
else
{
pd.enabled = true;
}
pd.name = key;
pd.path = str;
plugins.push_back(pd);
entry_found = plugins_config.GetNextEntry(key, Index);
}
// add code to always start your dll here.
#ifdef MY_OWN_HARDCODED_PLUGIN
{
PluginData pd;
pd.enabled = true;
pd.hard_coded = true;
pd.name = _T("MyPlugin");
pd.path = _T("$(MYEXEPATH)/mypluing/PluginForHeeksCAD.dll");
plugins.push_back(pd);
}
#endif
}
void CPluginsDialog::CreateCheckListbox(long flags)
{
wxString *astrChoices = new wxString[m_plugins.size()];
unsigned int ui = 0;
for ( std::list<PluginData>::iterator It = m_plugins.begin(); It != m_plugins.end(); It++, ui++ )
{
PluginData &pd = *It;
astrChoices[ui] = pd.name;
}
m_pListBox = new wxCheckListBox
(
m_panel, // parent
ID_LISTBOX_CONTROL, // control id
wxPoint(10, 10), // listbox poistion
wxSize(400, 100), // listbox size
m_plugins.size(), // number of strings
astrChoices, // array of strings
flags
);
delete [] astrChoices;
ui = 0;
for ( std::list<PluginData>::iterator It = m_plugins.begin(); It != m_plugins.end(); It++, ui++ )
{
PluginData &pd = *It;
if(pd.enabled)m_pListBox->Check(ui);
}
}
void CPluginsDialog::EditSelected(unsigned int selection)
{
unsigned int ui = 0;
for ( std::list<PluginData>::iterator It = m_plugins.begin(); It != m_plugins.end(); It++, ui++ )
{
if(ui == selection)
{
PluginData &pd = *It;
CPluginItemDialog dlg(this, _("Add New Plugin"), pd);
if(dlg.ShowModal() == wxID_OK)
{
// updata the check list
delete m_pListBox;
CreateCheckListbox();
}
}
}
}
void CPluginsDialog::OnButtonAdd(wxCommandEvent& event)
{
PluginData pd;
CPluginItemDialog dlg(this, _("Add New Plugin"), pd);
if(dlg.ShowModal() == wxID_OK)
{
// add the new item
m_plugins.push_back(pd);
// updata the check list
delete m_pListBox;
CreateCheckListbox();
}
}
void CPluginsDialog::OnButtonEdit(wxCommandEvent& event)
{
unsigned int selection = m_pListBox->GetSelection();
EditSelected(selection);
}
void CPluginsDialog::OnUpdateEdit( wxUpdateUIEvent& event )
{
event.Enable(m_pListBox->GetSelection() >= 0);
}
void CPluginsDialog::OnUpdateRemove( wxUpdateUIEvent& event )
{
event.Enable(m_pListBox->GetSelection() >= 0);
}
void CPluginsDialog::OnButtonRemove(wxCommandEvent& event)
{
unsigned int selection = m_pListBox->GetSelection();
unsigned int ui = 0;
for ( std::list<PluginData>::iterator It = m_plugins.begin(); It != m_plugins.end(); It++, ui++ )
{
if(ui == selection)
{
m_plugins.erase(It);
// updata the check list
delete m_pListBox;
CreateCheckListbox();
break;
}
}
}
void CPluginsDialog::OnButtonOK(wxCommandEvent& event)
{
::wxSetWorkingDirectory(wxGetApp().GetExeFolder());
HeeksConfig plugins_config;
plugins_config.DeleteGroup(_T("plugins"));
plugins_config.SetPath(_T("/plugins"));
unsigned int ui = 0;
for ( std::list<PluginData>::iterator It = m_plugins.begin(); It != m_plugins.end(); It++, ui++ )
{
PluginData &pd = *It;
if(pd.hard_coded)continue;
pd.enabled = m_pListBox->IsChecked(ui);
wxString value = pd.path;
if(!(pd.enabled))value.Prepend(_T("#"));
plugins_config.Write(pd.name, value);
}
EndModal(wxID_OK);
}
void CPluginsDialog::OnButtonCancel(wxCommandEvent& event)
{
EndModal(wxID_CANCEL);
}
void CPluginsDialog::OnListboxDblClick(wxCommandEvent& WXUNUSED(event))
{
int selection = m_pListBox->GetSelection();
EditSelected(selection);
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <cmath>
#include "bond_angle.h"
using namespace std;
double ex_ji(double x_j, double x_i, double R_ji) {
return ((-(x_j-x_i))/R_ji);
}
double ey_ji(double y_j, double y_i, double R_ji) {
return ((-(y_j-y_i))/R_ji);
}
double ez_ji(double z_j, double z_i, double R_ji) {
return ((-(z_j-z_i))/R_ji);
}
double ex_jk(double x_j, double x_k, double R_jk) {
return ((-(x_j-x_k))/R_jk);
}
double ey_jk(double y_j, double y_k, double R_jk) {
return ((-(y_j-y_k))/R_jk);
}
double ez_jk(double z_j, double z_k, double R_jk) {
return ((-(z_j-z_k))/R_jk);
}
double ex_kl(double x_k, double x_l, double R_kl) {
return ((-(x_k-x_l))/R_kl);
}
double ey_kl(double y_k, double y_l, double R_kl) {
return ((-(y_k-y_l))/R_kl);
}
double ez_kl(double z_k, double z_l, double R_kl) {
return ((-(z_k-z_l))/R_kl);
}
double phi_ijk(double ex_ji, double ey_ji, double ez_ji, double ex_jk, double ey_jk, double ez_jk) {
return acos((ex_ji)*(ex_jk)+(ey_ji)*(ey_jk)+(ez_ji)*(ez_jk));
}
double phi_jkl(double ex_kj, double ey_kj, double ez_kj, double ex_kl, double ey_kl, double ez_kl) {
return acos((ex_kj)*(ex_kl)+(ey_kj)*(ey_kl)+(ez_kj)*(ez_kl));
}
<commit_msg>added fstream<commit_after>#include <iostream>
#include <cmath>
#include <fstream>
#include "bond_angle.h"
using namespace std;
double ex_ji(double x_j, double x_i, double R_ji) {
return ((-(x_j-x_i))/R_ji);
}
double ey_ji(double y_j, double y_i, double R_ji) {
return ((-(y_j-y_i))/R_ji);
}
double ez_ji(double z_j, double z_i, double R_ji) {
return ((-(z_j-z_i))/R_ji);
}
double ex_jk(double x_j, double x_k, double R_jk) {
return ((-(x_j-x_k))/R_jk);
}
double ey_jk(double y_j, double y_k, double R_jk) {
return ((-(y_j-y_k))/R_jk);
}
double ez_jk(double z_j, double z_k, double R_jk) {
return ((-(z_j-z_k))/R_jk);
}
double ex_kl(double x_k, double x_l, double R_kl) {
return ((-(x_k-x_l))/R_kl);
}
double ey_kl(double y_k, double y_l, double R_kl) {
return ((-(y_k-y_l))/R_kl);
}
double ez_kl(double z_k, double z_l, double R_kl) {
return ((-(z_k-z_l))/R_kl);
}
double phi_ijk(double ex_ji, double ey_ji, double ez_ji, double ex_jk, double ey_jk, double ez_jk) {
return acos((ex_ji)*(ex_jk)+(ey_ji)*(ey_jk)+(ez_ji)*(ez_jk));
}
double phi_jkl(double ex_kj, double ey_kj, double ez_kj, double ex_kl, double ey_kl, double ez_kl) {
return acos((ex_kj)*(ex_kl)+(ey_kj)*(ey_kl)+(ez_kj)*(ez_kl));
}
<|endoftext|> |
<commit_before>#include "../group_flux_checker_sequential.h"
#include <memory>
#include <deal.II/lac/petsc_parallel_vector.h>
#include "../../test_helpers/gmock_wrapper.h"
#include "flux_checker_mock.h"
class GroupFluxCheckerSequentialTest : public ::testing::Test {
protected:
std::unique_ptr<bart::convergence::FluxCheckerI> tester_ptr;
std::unique_ptr<bart::convergence::FluxCheckerMock> tester_mock;
void SetUp() override;
void MocksToPointers() {
tester_ptr = std::move(tester_mock);
};
};
void GroupFluxCheckerSequentialTest::SetUp() {
tester_mock = std::make_unique<bart::convergence::FluxCheckerMock>();
}
// Tests where there are no mock calls
class GroupFluxCheckerSeqTestEmptyMock : public GroupFluxCheckerSequentialTest {
protected:
bart::convergence::GroupFluxCheckerSequential sequential_tester;
void SetUp() override {
MocksToPointers();
sequential_tester.ProvideChecker(tester_ptr);
}
};
TEST_F(GroupFluxCheckerSeqTestEmptyMock, Constructor) {
EXPECT_EQ(tester_ptr, nullptr);
}
TEST_F(GroupFluxCheckerSeqTestEmptyMock, DifferentGroupSizes) {
EXPECT_TRUE(true);
}
<commit_msg>added tests for different group sizes throwing error<commit_after>#include "../group_flux_checker_sequential.h"
#include <memory>
#include <deal.II/lac/petsc_parallel_vector.h>
#include "../../test_helpers/test_helper_functions.h"
#include "../../test_helpers/gmock_wrapper.h"
#include "flux_checker_mock.h"
class GroupFluxCheckerSequentialTest : public ::testing::Test {
protected:
std::unique_ptr<bart::convergence::FluxCheckerI> tester_ptr;
std::unique_ptr<bart::convergence::FluxCheckerMock> tester_mock;
bart::data::GroupFluxes current;
bart::data::GroupFluxes previous;
void SetUp() override;
void FillGroupFluxes(bart::data::GroupFluxes &to_fill, int n_groups);
void MocksToPointers() {
tester_ptr = std::move(tester_mock);
};
};
void GroupFluxCheckerSequentialTest::FillGroupFluxes(
bart::data::GroupFluxes &to_fill, int n_groups) {
for (int i = 0; i < n_groups; ++i) {
bart::data::Flux flux;
flux.reinit(MPI_COMM_WORLD, 5, 5);
auto random_vector = btest::RandomVector(5, 0, 2);
for (unsigned int j = 0; j < flux.size(); ++j)
flux(j) = random_vector[j];
flux.compress(dealii::VectorOperation::values::insert);
to_fill[i] = flux;
}
}
void GroupFluxCheckerSequentialTest::SetUp() {
tester_mock = std::make_unique<bart::convergence::FluxCheckerMock>();
}
// Tests where there are no mock calls
class GroupFluxCheckerSeqTestEmptyMock : public GroupFluxCheckerSequentialTest {
protected:
bart::convergence::GroupFluxCheckerSequential sequential_tester;
void SetUp() override {
MocksToPointers();
sequential_tester.ProvideChecker(tester_ptr);
}
};
TEST_F(GroupFluxCheckerSeqTestEmptyMock, Constructor) {
EXPECT_EQ(tester_ptr, nullptr);
}
TEST_F(GroupFluxCheckerSeqTestEmptyMock, EmptyGroups) {
EXPECT_ANY_THROW(sequential_tester.isConverged(current, previous));
}
TEST_F(GroupFluxCheckerSeqTestEmptyMock, DifferentGroupSizes) {
FillGroupFluxes(current, 5);
FillGroupFluxes(previous, 4);
EXPECT_ANY_THROW(sequential_tester.isConverged(current, previous));
}
<|endoftext|> |
<commit_before>#include "output.h"
#include "astprinter.h"
#include "options.h"
#include "sourcebuffer.h"
static void error(const QString& err)
{
QTextStream out(stderr);
out << err;
out.flush();
exit(EXIT_FAILURE);
}
Output::Output(SourceBuffer* source)
: m_source(source)
{
}
void Output::write(const QString& llvmIR)
{
QString file = Options::instance()->outputFile();
QString type = Options::instance()->outputType();
if (type == "ast") {
QTextStream out(stdout);
QFile f(file);
if (!file.isEmpty()) {
if (f.open(QIODevice::WriteOnly))
out.setDevice(&f);
}
f.close();
ASTPrinter printer(m_source, &out);
printer.walk();
} else if (type == "llvm") {
if (file.isEmpty()) {
QTextStream out(stdout);
out << llvmIR;
out.flush();
} else {
QFile f(file);
if (f.open(QIODevice::WriteOnly)) {
QTextStream out(&f);
out << llvmIR;
out.flush();
f.close();
} else {
error(QString("can not write to file $0").arg(file));
}
}
} else if (type == "obj") {
if (file.isEmpty()) {
QFileInfo info(m_source->name());
file = info.dir().path() + QDir::separator() + info.baseName() + ".o";
}
QProcess config;
config.setProgram("llvm-config");
config.setArguments(QStringList() << "--bindir");
config.start(QIODevice::ReadOnly);
if (!config.waitForFinished())
error("could not find llvm-config tool");
QString bindir = config.readAllStandardOutput();
bindir.remove('\n');
QProcess llc;
llc.setProgram(bindir + QDir::separator() + "llc");
llc.setArguments(QStringList() << "-filetype=obj");
llc.start();
if (!llc.waitForStarted())
error("could not start llc tool");
llc.write(llvmIR.toLatin1());
llc.waitForBytesWritten();
llc.closeWriteChannel();
if (!llc.waitForFinished())
error("llc tool crashed");
QByteArray err = llc.readAllStandardError();
if (!err.isEmpty())
error("llc tool exited with error");
QByteArray output = llc.readAllStandardOutput();
QFile f(file);
if (f.open(QIODevice::WriteOnly)) {
f.write(output);
f.flush();
f.close();
} else {
error(QString("can not write to file $0").arg(file));
}
}
}
<commit_msg>Append a newline to the error message for llc output<commit_after>#include "output.h"
#include "astprinter.h"
#include "options.h"
#include "sourcebuffer.h"
static void error(const QString& err)
{
QTextStream out(stderr);
out << err << '\n';
out.flush();
exit(EXIT_FAILURE);
}
Output::Output(SourceBuffer* source)
: m_source(source)
{
}
void Output::write(const QString& llvmIR)
{
QString file = Options::instance()->outputFile();
QString type = Options::instance()->outputType();
if (type == "ast") {
QTextStream out(stdout);
QFile f(file);
if (!file.isEmpty()) {
if (f.open(QIODevice::WriteOnly))
out.setDevice(&f);
}
f.close();
ASTPrinter printer(m_source, &out);
printer.walk();
} else if (type == "llvm") {
if (file.isEmpty()) {
QTextStream out(stdout);
out << llvmIR;
out.flush();
} else {
QFile f(file);
if (f.open(QIODevice::WriteOnly)) {
QTextStream out(&f);
out << llvmIR;
out.flush();
f.close();
} else {
error(QString("can not write to file $0").arg(file));
}
}
} else if (type == "obj") {
if (file.isEmpty()) {
QFileInfo info(m_source->name());
file = info.dir().path() + QDir::separator() + info.baseName() + ".o";
}
QProcess config;
config.setProgram("llvm-config");
config.setArguments(QStringList() << "--bindir");
config.start(QIODevice::ReadOnly);
if (!config.waitForFinished())
error("could not find llvm-config tool");
QString bindir = config.readAllStandardOutput();
bindir.remove('\n');
QProcess llc;
llc.setProgram(bindir + QDir::separator() + "llc");
llc.setArguments(QStringList() << "-filetype=obj");
llc.start();
if (!llc.waitForStarted())
error("could not start llc tool");
llc.write(llvmIR.toLatin1());
llc.waitForBytesWritten();
llc.closeWriteChannel();
if (!llc.waitForFinished())
error("llc tool crashed");
QByteArray err = llc.readAllStandardError();
if (!err.isEmpty())
error("llc tool exited with error");
QByteArray output = llc.readAllStandardOutput();
QFile f(file);
if (f.open(QIODevice::WriteOnly)) {
f.write(output);
f.flush();
f.close();
} else {
error(QString("can not write to file $0").arg(file));
}
}
}
<|endoftext|> |
<commit_before><commit_msg>just testing<commit_after>#include <iostream>
#include <string>
#include <stdio.h>
#include "game.h"
#include "game_title.h"
void start_game(){
cout << " hello you haave reached the right place high five5 " << endl;
}<|endoftext|> |
<commit_before>#include "z2h/token.hpp"
#include "z2h/parser.hpp"
#include "ast.hpp"
#include "parser.h"
#include "bindpower.h"
#include "exceptions.h"
#include <map>
#include <vector>
#include <boost/regex.hpp>
#include <iostream>
namespace sota {
std::vector<z2h::Ast *> SotaParser::Expressions(z2h::Symbol *end) {
std::vector<z2h::Ast *> expressions;
auto *eoe = symbolmap[SymbolType::EndOfExpression];
auto *la1 = this->LookAhead1();
while (end != la1->symbol) {
auto *expression = this->Expression();
expressions.push_back(expression);
this->Consume(eoe);
la1 = this->LookAhead1();
}
return expressions;
}
std::vector<z2h::Ast *> SotaParser::Statements(z2h::Symbol *end) {
std::vector<z2h::Ast *> statements;
return statements;
}
// scanners
z2h::Token * SotaParser::SkippingScanner(z2h::Symbol *symbol, const std::string &source, size_t position) {
auto *token = RegexScanner(symbol, source, position);
if (token)
token->skip = true;
return token;
}
z2h::Token * SotaParser::RegexScanner(z2h::Symbol *symbol, const std::string &source, size_t position) {
z2h::Token *token = nullptr;
auto pattern = symbol->pattern;
boost::smatch matches;
boost::regex re("^(" + pattern + ")");
if (boost::regex_search(source, matches, re)) {
auto match = matches[0];
token = new z2h::Token(symbol, match, position, match.length(), false);
}
return token;
}
z2h::Token * SotaParser::LiteralScanner(z2h::Symbol *symbol, const std::string &source, size_t position) {
auto pattern = symbol->pattern;
auto patternSize = pattern.size();
if (source.size() >= patternSize && source.compare(0, patternSize, pattern) == 0) {
return new z2h::Token(symbol, pattern, position, patternSize, false);
}
return nullptr;
}
z2h::Token * SotaParser::EosScanner(z2h::Symbol *symbol, const std::string &source, size_t position) {
if (!nesting.size()) {
return RegexScanner(symbol, source, position);
}
return nullptr;
}
z2h::Token * SotaParser::EoeScanner(z2h::Symbol *symbol, const std::string &source, size_t position) {
if (nesting.size()) {
}
return RegexScanner(symbol, source, position);
}
z2h::Token * SotaParser::DentingScanner(z2h::Symbol *symbol, const std::string &source, size_t position) {
return nullptr;
}
// std parsing functions
z2h::Ast * SotaParser::NullptrStd() {
return nullptr;
}
// nud parsing functions
z2h::Ast * SotaParser::NullptrNud(z2h::Token *token) {
return nullptr;
}
z2h::Ast * SotaParser::EndOfFileNud(z2h::Token *token) {
return nullptr;
}
z2h::Ast * SotaParser::NewlineNud(z2h::Token *token) {
std::cout << "newline" << std::endl;
return new NewlineAst(token);
}
z2h::Ast * SotaParser::NumberNud(z2h::Token *token) {
return new NumberAst(token);
}
z2h::Ast * SotaParser::IdentifierNud(z2h::Token *token) {
return new IdentifierAst(token);
}
z2h::Ast * SotaParser::PrefixNud(z2h::Token *token) {
z2h::Ast *right = Expression(BindPower::Unary);
return new PrefixAst(token, right);
}
z2h::Ast * SotaParser::ParensNud(z2h::Token *token) {
auto rp = symbolmap[SymbolType::RightParen];
auto expressions = this->Expressions(rp);
this->Consume(rp);
z2h::Ast *ast = new ExpressionsAst(expressions);
return ast;
}
z2h::Ast * SotaParser::IfThenElifElseNud(z2h::Token *token) {
return nullptr;
}
// led parsing functions
z2h::Ast * SotaParser::NullptrLed(z2h::Ast *left, z2h::Token *token) {
return nullptr;
}
z2h::Ast * SotaParser::EndOfFileLed(z2h::Ast *left, z2h::Token *token) {
return left;
}
z2h::Ast * SotaParser::ComparisonLed(z2h::Ast *left, z2h::Token *token) {
return nullptr;
}
z2h::Ast * SotaParser::InfixLed(z2h::Ast *left, z2h::Token *token) {
z2h::Ast *right = Expression(token->symbol->lbp);
return new InfixAst(token, left, right);
}
z2h::Ast * SotaParser::PostfixLed(z2h::Ast *left, z2h::Token *token) {
return nullptr;
}
z2h::Ast * SotaParser::AssignLed(z2h::Ast *left, z2h::Token *token) {
//size_t distance = 1;
//auto *la1 = this->LookAhead(distance);
z2h::Ast *right = this->Expression(token->symbol->lbp);
return new AssignAst(token, left, right);
}
z2h::Ast * SotaParser::FuncLed(z2h::Ast *left, z2h::Token *token) {
std::cout << "FuncLed: token=" << *token << std::endl;
return nullptr;
}
z2h::Ast * SotaParser::RegexLed(z2h::Ast *left, z2h::Token *token) {
return nullptr;
}
z2h::Ast * SotaParser::CallLed(z2h::Ast *left, z2h::Token *token) {
return nullptr;
}
z2h::Ast * SotaParser::TernaryLed(z2h::Ast *left, z2h::Token *token) {
auto action = Expression();
auto pair = ConditionalAst::Pair(left, action);
auto expected = symbolmap[SotaParser::SymbolType::Colon];
if (nullptr == Consume(expected))
throw SotaException(__FILE__, __LINE__, "colon : expected");
auto defaultAction = Expression();
return new ConditionalAst(token, {pair}, defaultAction);
}
z2h::Ast * SotaParser::IfThenElseLed(z2h::Ast *left, z2h::Token *token) {
auto predicate = Expression();
auto pair = ConditionalAst::Pair(predicate, left);
auto expected = symbolmap[SotaParser::SymbolType::Else];
if (nullptr == Consume(expected))
throw SotaException(__FILE__, __LINE__, "else expected");
auto defaultAction = Expression();
return new ConditionalAst(token, {pair}, defaultAction);
}
SotaParser::SotaParser() {
#define T(k,p,b,s,t,n,l) { SymbolType::k, new z2h::Symbol(SymbolType::k, b, p, SCAN(s), STD(t), NUD(n), LED(l) ) },
symbolmap = {
SYMBOLS
};
#undef T
}
std::exception SotaParser::Exception(const char *file, size_t line, const std::string &message) {
return SotaException(file, line, message);
}
std::vector<z2h::Symbol *> SotaParser::Symbols() {
std::vector<z2h::Symbol *> symbols;
for (auto kvp : symbolmap) {
symbols.push_back(kvp.second);
}
return symbols;
}
}
<commit_msg>added logic after Consuming symbols... -sai<commit_after>#include "z2h/token.hpp"
#include "z2h/parser.hpp"
#include "ast.hpp"
#include "parser.h"
#include "bindpower.h"
#include "exceptions.h"
#include <map>
#include <vector>
#include <boost/regex.hpp>
#include <iostream>
namespace sota {
std::vector<z2h::Ast *> SotaParser::Expressions(z2h::Symbol *end) {
std::vector<z2h::Ast *> expressions;
auto *eoe = symbolmap[SymbolType::EndOfExpression];
auto *la1 = this->LookAhead1();
while (end != la1->symbol) {
auto *expression = this->Expression();
expressions.push_back(expression);
if (!this->Consume(eoe)) {
break;
}
la1 = this->LookAhead1();
}
return expressions;
}
std::vector<z2h::Ast *> SotaParser::Statements(z2h::Symbol *end) {
std::vector<z2h::Ast *> statements;
return statements;
}
// scanners
z2h::Token * SotaParser::SkippingScanner(z2h::Symbol *symbol, const std::string &source, size_t position) {
auto *token = RegexScanner(symbol, source, position);
if (token)
token->skip = true;
return token;
}
z2h::Token * SotaParser::RegexScanner(z2h::Symbol *symbol, const std::string &source, size_t position) {
z2h::Token *token = nullptr;
auto pattern = symbol->pattern;
boost::smatch matches;
boost::regex re("^(" + pattern + ")");
if (boost::regex_search(source, matches, re)) {
auto match = matches[0];
token = new z2h::Token(symbol, match, position, match.length(), false);
}
return token;
}
z2h::Token * SotaParser::LiteralScanner(z2h::Symbol *symbol, const std::string &source, size_t position) {
auto pattern = symbol->pattern;
auto patternSize = pattern.size();
if (source.size() >= patternSize && source.compare(0, patternSize, pattern) == 0) {
return new z2h::Token(symbol, pattern, position, patternSize, false);
}
return nullptr;
}
z2h::Token * SotaParser::EosScanner(z2h::Symbol *symbol, const std::string &source, size_t position) {
if (!nesting.size()) {
return RegexScanner(symbol, source, position);
}
return nullptr;
}
z2h::Token * SotaParser::EoeScanner(z2h::Symbol *symbol, const std::string &source, size_t position) {
if (nesting.size()) {
}
return RegexScanner(symbol, source, position);
}
z2h::Token * SotaParser::DentingScanner(z2h::Symbol *symbol, const std::string &source, size_t position) {
return nullptr;
}
// std parsing functions
z2h::Ast * SotaParser::NullptrStd() {
return nullptr;
}
// nud parsing functions
z2h::Ast * SotaParser::NullptrNud(z2h::Token *token) {
return nullptr;
}
z2h::Ast * SotaParser::EndOfFileNud(z2h::Token *token) {
return nullptr;
}
z2h::Ast * SotaParser::NewlineNud(z2h::Token *token) {
std::cout << "newline" << std::endl;
return new NewlineAst(token);
}
z2h::Ast * SotaParser::NumberNud(z2h::Token *token) {
return new NumberAst(token);
}
z2h::Ast * SotaParser::IdentifierNud(z2h::Token *token) {
return new IdentifierAst(token);
}
z2h::Ast * SotaParser::PrefixNud(z2h::Token *token) {
z2h::Ast *right = Expression(BindPower::Unary);
return new PrefixAst(token, right);
}
z2h::Ast * SotaParser::ParensNud(z2h::Token *token) {
auto rp = symbolmap[SymbolType::RightParen];
auto expressions = this->Expressions(rp);
if (!this->Consume(rp)) {
std::cout << "RightParen not consumed" << std::endl;
}
z2h::Ast *ast = new ExpressionsAst(expressions);
return ast;
}
z2h::Ast * SotaParser::IfThenElifElseNud(z2h::Token *token) {
return nullptr;
}
// led parsing functions
z2h::Ast * SotaParser::NullptrLed(z2h::Ast *left, z2h::Token *token) {
return nullptr;
}
z2h::Ast * SotaParser::EndOfFileLed(z2h::Ast *left, z2h::Token *token) {
return left;
}
z2h::Ast * SotaParser::ComparisonLed(z2h::Ast *left, z2h::Token *token) {
return nullptr;
}
z2h::Ast * SotaParser::InfixLed(z2h::Ast *left, z2h::Token *token) {
z2h::Ast *right = Expression(token->symbol->lbp);
return new InfixAst(token, left, right);
}
z2h::Ast * SotaParser::PostfixLed(z2h::Ast *left, z2h::Token *token) {
return nullptr;
}
z2h::Ast * SotaParser::AssignLed(z2h::Ast *left, z2h::Token *token) {
//size_t distance = 1;
//auto *la1 = this->LookAhead(distance);
z2h::Ast *right = this->Expression(token->symbol->lbp);
return new AssignAst(token, left, right);
}
z2h::Ast * SotaParser::FuncLed(z2h::Ast *left, z2h::Token *token) {
std::cout << "FuncLed: token=" << *token << std::endl;
return nullptr;
}
z2h::Ast * SotaParser::RegexLed(z2h::Ast *left, z2h::Token *token) {
return nullptr;
}
z2h::Ast * SotaParser::CallLed(z2h::Ast *left, z2h::Token *token) {
return nullptr;
}
z2h::Ast * SotaParser::TernaryLed(z2h::Ast *left, z2h::Token *token) {
auto action = Expression();
auto pair = ConditionalAst::Pair(left, action);
auto expected = symbolmap[SotaParser::SymbolType::Colon];
if (nullptr == Consume(expected))
throw SotaException(__FILE__, __LINE__, "colon : expected");
auto defaultAction = Expression();
return new ConditionalAst(token, {pair}, defaultAction);
}
z2h::Ast * SotaParser::IfThenElseLed(z2h::Ast *left, z2h::Token *token) {
auto predicate = Expression();
auto pair = ConditionalAst::Pair(predicate, left);
auto expected = symbolmap[SotaParser::SymbolType::Else];
if (nullptr == Consume(expected))
throw SotaException(__FILE__, __LINE__, "else expected");
auto defaultAction = Expression();
return new ConditionalAst(token, {pair}, defaultAction);
}
SotaParser::SotaParser() {
#define T(k,p,b,s,t,n,l) { SymbolType::k, new z2h::Symbol(SymbolType::k, b, p, SCAN(s), STD(t), NUD(n), LED(l) ) },
symbolmap = {
SYMBOLS
};
#undef T
}
std::exception SotaParser::Exception(const char *file, size_t line, const std::string &message) {
return SotaException(file, line, message);
}
std::vector<z2h::Symbol *> SotaParser::Symbols() {
std::vector<z2h::Symbol *> symbols;
for (auto kvp : symbolmap) {
symbols.push_back(kvp.second);
}
return symbols;
}
}
<|endoftext|> |
<commit_before>#include "mainwindow.h"
#include <QPen>
#include <QGraphicsRectItem>
#include <QGraphicsEllipseItem>
#include <QDebug>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
{
// specify app window geometry. 1920x1080 screen rez yields a 0.56 pixel ratio
setGeometry(56,100,600,600);
// set up the scene
// traditionally, member objects start with the letter 'm'
mGraphicsScene = new QGraphicsScene(0, 0, 400, 400);
// set up the view
mGraphicsView = new QGraphicsView(mGraphicsScene, this);
mGraphicsView->setGeometry(0, 0, 600, 600);
mGraphicsView->setViewportUpdateMode(QGraphicsView::BoundingRectViewportUpdate);
mGraphicsView->setDragMode(QGraphicsView::ScrollHandDrag);
// add a blue box that is the size of the scene
QPen pen;
pen.setColor(QColor(Qt::blue));
pen.setWidth(2);
mGraphicsScene->addRect(0, 0, mGraphicsScene->width(), mGraphicsScene->height(), pen);
// these ints will go out of scope after constructor is called because they are not
// defined in the mainwindow class declaration of the mainwindow.h file:
int x = 100, y = 100, w = 10, h = 10;
// add a black circle known as mEllipseItem to the scene
mEllipseItem = new QGraphicsEllipseItem(x,y,w,h);
pen.setColor(QColor(Qt::black));
pen.setWidth(1);
mEllipseItem->setPen(pen);
mGraphicsScene->addItem(mEllipseItem);
// how often we update the scene, in milliseconds:
mUpdateIntervalMS = 60;
// start the signal/slot timer, which invokes gameTick() every mUpdateIntervalMS milliseconds
startGameLoopTimer();
}
MainWindow::~MainWindow()
{
// this is the destructor code for the MainWindow object
if (mGraphicsView != NULL)
{
delete mGraphicsView;
mGraphicsView = NULL;
}
if (mGraphicsScene != NULL)
{
delete mGraphicsScene;
mGraphicsScene = NULL;
}
}
void MainWindow::startGameLoopTimer()
{
// associate the signal timeout() to the slot gameTick(), and start our update timer
QObject::connect(&mTimer, SIGNAL(timeout()), this, SLOT(gameTick()));
mTimer.start(mUpdateIntervalMS);
}
void MainWindow::gameTick()
{
// this code makes whatever changes to the scene you want to make, every gametick.
// if you want to change what the animation does, you can do that here, or add new
// functions (methods) and call them from here.
// Change this code to make the circle stay within the blue box! :-D You could have
// the circle just stop moving when it reaches the edge of the scene at x,y == 400,400
// or you could make the circle change direction somehow when x or y get outside of
// the range of 0 to 400. Or think of some other way the circle should move!
// you can uncomment the following line to produce console output every gametick.
//qDebug() << "MainWindow::gameTick(): invoked\n";
// ...this will generate around 16 messages per second at 60ms gametick.
mEllipseItem->setX(mEllipseItem->x()+1);
mEllipseItem->setY(mEllipseItem->y()+1);
mGraphicsScene->advance();
}
<commit_msg>most of the important code is in this file<commit_after>#include "mainwindow.h"
#include <QPen>
#include <QGraphicsRectItem>
#include <QGraphicsEllipseItem>
#include <QDebug>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
{
// specify app window geometry. 1920x1080 screen rez yields a 0.56 pixel ratio
setGeometry(56,100,600,600);
// set up the scene
// traditionally, member objects start with the letter 'm'
mGraphicsScene = new QGraphicsScene(0, 0, 400, 400);
// set up the view
mGraphicsView = new QGraphicsView(mGraphicsScene, this);
mGraphicsView->setGeometry(0, 0, 600, 600);
mGraphicsView->setViewportUpdateMode(QGraphicsView::BoundingRectViewportUpdate);
mGraphicsView->setDragMode(QGraphicsView::ScrollHandDrag);
// add a blue box that is the size of the scene
QPen pen;
pen.setColor(QColor(Qt::blue));
pen.setWidth(2);
mGraphicsScene->addRect(0, 0, mGraphicsScene->width(), mGraphicsScene->height(), pen);
// these ints will go out of scope after constructor is called because they are not
// defined in the mainwindow class declaration of the mainwindow.h file:
int x = 100, y = 100, w = 10, h = 10;
// add a black circle known as mEllipseItem to the scene
mEllipseItem = new QGraphicsEllipseItem(x,y,w,h);
pen.setColor(QColor(Qt::black));
pen.setWidth(1);
mEllipseItem->setPen(pen);
mGraphicsScene->addItem(mEllipseItem);
// how often we update the scene, in milliseconds:
mUpdateIntervalMS = 60;
// start the signal/slot timer, which invokes gameTick() every mUpdateIntervalMS milliseconds
startGameLoopTimer();
}
MainWindow::~MainWindow()
{
// this is the destructor code for the MainWindow object
if (mGraphicsView != NULL)
{
delete mGraphicsView;
mGraphicsView = NULL;
}
if (mGraphicsScene != NULL)
{
delete mGraphicsScene;
mGraphicsScene = NULL;
}
}
void MainWindow::startGameLoopTimer()
{
// associate the signal timeout() to the slot gameTick(), and start our update timer
QObject::connect(&mTimer, SIGNAL(timeout()), this, SLOT(gameTick()));
mTimer.start(mUpdateIntervalMS);
}
void MainWindow::gameTick()
{
// this code makes whatever changes to the scene you want to make, every gametick.
// if you want to change what the animation does, you can do that here, or add new
// functions (methods) and call them from here.
// Change this code to make the circle stay within the blue box! :-D You could have
// the circle just stop moving when it reaches the edge of the scene at x,y == 400,400
// or you could make the circle change direction somehow when x or y get outside of
// the range of 0 to 400. Or think of some other way the circle should move!
// you can uncomment the following line to produce console output every gametick.
//qDebug() << "MainWindow::gameTick(): invoked\n";
// ...this will generate around 16 messages per second at 60ms gametick.
mEllipseItem->setX(mEllipseItem->x()+1);
mEllipseItem->setY(mEllipseItem->y()+1);
mGraphicsScene->advance();
}
<|endoftext|> |
<commit_before>/*
* Call the translation server.
*
* author: Max Kellermann <[email protected]>
*/
#include "translate_client.hxx"
#include "translate_quark.hxx"
#include "translate_parser.hxx"
#include "translate_request.hxx"
#include "TranslateHandler.hxx"
#include "buffered_socket.hxx"
#include "please.hxx"
#include "growing_buffer.hxx"
#include "stopwatch.hxx"
#include "GException.hxx"
#include "gerrno.h"
#include "pool.hxx"
#include "util/Cancellable.hxx"
#include "util/RuntimeError.hxx"
#include <socket/address.h>
#include <glib.h>
#include <stdexcept>
#include <assert.h>
#include <string.h>
#include <errno.h>
static const uint8_t PROTOCOL_VERSION = 3;
struct TranslateClient final : Cancellable {
struct pool &pool;
Stopwatch *const stopwatch;
BufferedSocket socket;
struct lease_ref lease_ref;
/** the marshalled translate request */
GrowingBufferReader request_buffer;
GrowingBufferReader request;
const TranslateHandler &handler;
void *handler_ctx;
TranslateParser parser;
TranslateClient(struct pool &p, EventLoop &event_loop,
int fd, Lease &lease,
const TranslateRequest &request2,
GrowingBuffer &&_request,
const TranslateHandler &_handler, void *_ctx,
CancellablePointer &cancel_ptr);
void ReleaseSocket(bool reuse);
void Release(bool reuse);
void Fail(GError *error);
BufferedResult Feed(const uint8_t *data, size_t length);
/* virtual methods from class Cancellable */
void Cancel() override {
stopwatch_event(stopwatch, "cancel");
Release(false);
}
};
static constexpr struct timeval translate_read_timeout = {
.tv_sec = 60,
.tv_usec = 0,
};
static constexpr struct timeval translate_write_timeout = {
.tv_sec = 10,
.tv_usec = 0,
};
void
TranslateClient::ReleaseSocket(bool reuse)
{
assert(socket.IsConnected());
stopwatch_dump(stopwatch);
socket.Abandon();
socket.Destroy();
p_lease_release(lease_ref, reuse, pool);
}
/**
* Release resources held by this object: the event object, the socket
* lease, and the pool reference.
*/
void
TranslateClient::Release(bool reuse)
{
ReleaseSocket(reuse);
pool_unref(&pool);
}
void
TranslateClient::Fail(GError *error)
{
stopwatch_event(stopwatch, "error");
ReleaseSocket(false);
handler.error(error, handler_ctx);
pool_unref(&pool);
}
/*
* request marshalling
*
*/
static void
write_packet_n(GrowingBuffer *gb, uint16_t command,
const void *payload, size_t length)
{
static struct beng_translation_header header;
if (length >= 0xffff)
throw FormatRuntimeError("payload for translate command %u too large",
command);
header.length = (uint16_t)length;
header.command = command;
gb->Write(&header, sizeof(header));
if (length > 0)
gb->Write(payload, length);
}
static void
write_packet(GrowingBuffer *gb, uint16_t command, const char *payload)
{
write_packet_n(gb, command, payload,
payload != nullptr ? strlen(payload) : 0);
}
template<typename T>
static void
write_buffer(GrowingBuffer *gb, uint16_t command,
ConstBuffer<T> buffer)
{
auto b = buffer.ToVoid();
write_packet_n(gb, command, b.data, b.size);
}
/**
* Forward the command to write_packet() only if #payload is not nullptr.
*/
static void
write_optional_packet(GrowingBuffer *gb, uint16_t command, const char *payload)
{
if (payload != nullptr)
write_packet(gb, command, payload);
}
template<typename T>
static void
write_optional_buffer(GrowingBuffer *gb, uint16_t command,
ConstBuffer<T> buffer)
{
if (!buffer.IsNull())
write_buffer(gb, command, buffer);
}
static void
write_short(GrowingBuffer *gb, uint16_t command, uint16_t payload)
{
write_packet_n(gb, command, &payload, sizeof(payload));
}
static void
write_sockaddr(GrowingBuffer *gb,
uint16_t command, uint16_t command_string,
SocketAddress address)
{
assert(!address.IsNull());
char address_string[1024];
write_packet_n(gb, command,
address.GetAddress(), address.GetSize());
if (socket_address_to_string(address_string, sizeof(address_string),
address.GetAddress(), address.GetSize()))
write_packet(gb, command_string, address_string);
}
static void
write_optional_sockaddr(GrowingBuffer *gb,
uint16_t command, uint16_t command_string,
SocketAddress address)
{
if (!address.IsNull())
write_sockaddr(gb, command, command_string, address);
}
static GrowingBuffer
marshal_request(struct pool &pool, const TranslateRequest &request)
{
GrowingBuffer gb(pool, 512);
write_packet_n(&gb, TRANSLATE_BEGIN,
&PROTOCOL_VERSION, sizeof(PROTOCOL_VERSION));
write_optional_buffer(&gb, TRANSLATE_ERROR_DOCUMENT,
request.error_document);
if (request.error_document_status != 0)
write_short(&gb, TRANSLATE_STATUS,
request.error_document_status);
write_optional_packet(&gb, TRANSLATE_LISTENER_TAG,
request.listener_tag);
write_optional_sockaddr(&gb, TRANSLATE_LOCAL_ADDRESS,
TRANSLATE_LOCAL_ADDRESS_STRING,
request.local_address);
write_optional_packet(&gb, TRANSLATE_REMOTE_HOST,
request.remote_host);
write_optional_packet(&gb, TRANSLATE_HOST, request.host);
write_optional_packet(&gb, TRANSLATE_USER_AGENT, request.user_agent);
write_optional_packet(&gb, TRANSLATE_UA_CLASS, request.ua_class);
write_optional_packet(&gb, TRANSLATE_LANGUAGE, request.accept_language);
write_optional_packet(&gb, TRANSLATE_AUTHORIZATION, request.authorization);
write_optional_packet(&gb, TRANSLATE_URI, request.uri);
write_optional_packet(&gb, TRANSLATE_ARGS, request.args);
write_optional_packet(&gb, TRANSLATE_QUERY_STRING, request.query_string);
write_optional_packet(&gb, TRANSLATE_WIDGET_TYPE, request.widget_type);
write_optional_buffer(&gb, TRANSLATE_SESSION, request.session);
write_optional_buffer(&gb, TRANSLATE_INTERNAL_REDIRECT,
request.internal_redirect);
write_optional_buffer(&gb, TRANSLATE_CHECK, request.check);
write_optional_buffer(&gb, TRANSLATE_AUTH, request.auth);
write_optional_buffer(&gb, TRANSLATE_WANT_FULL_URI, request.want_full_uri);
write_optional_buffer(&gb, TRANSLATE_WANT, request.want);
write_optional_buffer(&gb, TRANSLATE_FILE_NOT_FOUND,
request.file_not_found);
write_optional_buffer(&gb, TRANSLATE_CONTENT_TYPE_LOOKUP,
request.content_type_lookup);
write_optional_packet(&gb, TRANSLATE_SUFFIX, request.suffix);
write_optional_buffer(&gb, TRANSLATE_ENOTDIR, request.enotdir);
write_optional_buffer(&gb, TRANSLATE_DIRECTORY_INDEX,
request.directory_index);
write_optional_packet(&gb, TRANSLATE_PARAM, request.param);
write_optional_buffer(&gb, TRANSLATE_PROBE_PATH_SUFFIXES,
request.probe_path_suffixes);
write_optional_packet(&gb, TRANSLATE_PROBE_SUFFIX,
request.probe_suffix);
write_optional_buffer(&gb, TRANSLATE_READ_FILE,
request.read_file);
write_optional_packet(&gb, TRANSLATE_USER, request.user);
write_packet(&gb, TRANSLATE_END, nullptr);
return gb;
}
/*
* receive response
*
*/
inline BufferedResult
TranslateClient::Feed(const uint8_t *data, size_t length)
try {
size_t consumed = 0;
while (consumed < length) {
size_t nbytes = parser.Feed(data + consumed, length - consumed);
if (nbytes == 0)
/* need more data */
break;
consumed += nbytes;
socket.Consumed(nbytes);
auto result = parser.Process();
switch (result) {
case TranslateParser::Result::MORE:
break;
case TranslateParser::Result::DONE:
ReleaseSocket(true);
handler.response(parser.GetResponse(), handler_ctx);
pool_unref(&pool);
return BufferedResult::CLOSED;
}
}
return BufferedResult::MORE;
} catch (const std::runtime_error &e) {
Fail(g_error_new_literal(translate_quark(), 0, e.what()));
return BufferedResult::CLOSED;
}
/*
* send requests
*
*/
static bool
translate_try_write(TranslateClient *client)
{
auto src = client->request.Read();
assert(!src.IsNull());
ssize_t nbytes = client->socket.Write(src.data, src.size);
if (gcc_unlikely(nbytes < 0)) {
if (gcc_likely(nbytes == WRITE_BLOCKING))
return true;
GError *error =
new_error_errno_msg("write error to translation server");
client->Fail(error);
return false;
}
client->request.Consume(nbytes);
if (client->request.IsEOF()) {
/* the buffer is empty, i.e. the request has been sent */
stopwatch_event(client->stopwatch, "request");
client->socket.UnscheduleWrite();
return client->socket.Read(true);
}
client->socket.ScheduleWrite();
return true;
}
/*
* buffered_socket handler
*
*/
static BufferedResult
translate_client_socket_data(const void *buffer, size_t size, void *ctx)
{
TranslateClient *client = (TranslateClient *)ctx;
return client->Feed((const uint8_t *)buffer, size);
}
static bool
translate_client_socket_closed(void *ctx)
{
TranslateClient *client = (TranslateClient *)ctx;
client->ReleaseSocket(false);
return true;
}
static bool
translate_client_socket_write(void *ctx)
{
TranslateClient *client = (TranslateClient *)ctx;
return translate_try_write(client);
}
static void
translate_client_socket_error(std::exception_ptr ep, void *ctx)
{
TranslateClient *client = (TranslateClient *)ctx;
auto *error = ToGError(ep);
g_prefix_error(&error, "Translation server connection failed: ");
client->Fail(error);
}
static constexpr BufferedSocketHandler translate_client_socket_handler = {
.data = translate_client_socket_data,
.direct = nullptr,
.closed = translate_client_socket_closed,
.remaining = nullptr,
.end = nullptr,
.write = translate_client_socket_write,
.drained = nullptr,
.timeout = nullptr,
.broken = nullptr,
.error = translate_client_socket_error,
};
/*
* constructor
*
*/
inline
TranslateClient::TranslateClient(struct pool &p, EventLoop &event_loop,
int fd, Lease &lease,
const TranslateRequest &request2,
GrowingBuffer &&_request,
const TranslateHandler &_handler, void *_ctx,
CancellablePointer &cancel_ptr)
:pool(p),
stopwatch(stopwatch_fd_new(&p, fd, request2.GetDiagnosticName())),
socket(event_loop),
request_buffer(std::move(_request)),
request(request_buffer),
handler(_handler), handler_ctx(_ctx),
parser(p, request2)
{
socket.Init(fd, FdType::FD_SOCKET,
&translate_read_timeout,
&translate_write_timeout,
translate_client_socket_handler, this);
p_lease_ref_set(lease_ref, lease, p, "translate_lease");
cancel_ptr = *this;
}
void
translate(struct pool &pool, EventLoop &event_loop,
int fd, Lease &lease,
const TranslateRequest &request,
const TranslateHandler &handler, void *ctx,
CancellablePointer &cancel_ptr)
try {
assert(fd >= 0);
assert(request.uri != nullptr || request.widget_type != nullptr ||
(!request.content_type_lookup.IsNull() &&
request.suffix != nullptr));
assert(handler.response != nullptr);
assert(handler.error != nullptr);
GrowingBuffer gb = marshal_request(pool, request);
auto *client = NewFromPool<TranslateClient>(pool, pool, event_loop,
fd, lease,
request, std::move(gb),
handler, ctx, cancel_ptr);
pool_ref(&client->pool);
translate_try_write(client);
} catch (const std::runtime_error &e) {
lease.ReleaseLease(true);
handler.error(ToGError(e), ctx);
}
<commit_msg>translate_client: add Fail() overload with std::exception<commit_after>/*
* Call the translation server.
*
* author: Max Kellermann <[email protected]>
*/
#include "translate_client.hxx"
#include "translate_quark.hxx"
#include "translate_parser.hxx"
#include "translate_request.hxx"
#include "TranslateHandler.hxx"
#include "buffered_socket.hxx"
#include "please.hxx"
#include "growing_buffer.hxx"
#include "stopwatch.hxx"
#include "GException.hxx"
#include "gerrno.h"
#include "pool.hxx"
#include "util/Cancellable.hxx"
#include "util/RuntimeError.hxx"
#include <socket/address.h>
#include <glib.h>
#include <stdexcept>
#include <assert.h>
#include <string.h>
#include <errno.h>
static const uint8_t PROTOCOL_VERSION = 3;
struct TranslateClient final : Cancellable {
struct pool &pool;
Stopwatch *const stopwatch;
BufferedSocket socket;
struct lease_ref lease_ref;
/** the marshalled translate request */
GrowingBufferReader request_buffer;
GrowingBufferReader request;
const TranslateHandler &handler;
void *handler_ctx;
TranslateParser parser;
TranslateClient(struct pool &p, EventLoop &event_loop,
int fd, Lease &lease,
const TranslateRequest &request2,
GrowingBuffer &&_request,
const TranslateHandler &_handler, void *_ctx,
CancellablePointer &cancel_ptr);
void ReleaseSocket(bool reuse);
void Release(bool reuse);
void Fail(GError *error);
void Fail(const std::exception &e);
BufferedResult Feed(const uint8_t *data, size_t length);
/* virtual methods from class Cancellable */
void Cancel() override {
stopwatch_event(stopwatch, "cancel");
Release(false);
}
};
static constexpr struct timeval translate_read_timeout = {
.tv_sec = 60,
.tv_usec = 0,
};
static constexpr struct timeval translate_write_timeout = {
.tv_sec = 10,
.tv_usec = 0,
};
void
TranslateClient::ReleaseSocket(bool reuse)
{
assert(socket.IsConnected());
stopwatch_dump(stopwatch);
socket.Abandon();
socket.Destroy();
p_lease_release(lease_ref, reuse, pool);
}
/**
* Release resources held by this object: the event object, the socket
* lease, and the pool reference.
*/
void
TranslateClient::Release(bool reuse)
{
ReleaseSocket(reuse);
pool_unref(&pool);
}
void
TranslateClient::Fail(GError *error)
{
stopwatch_event(stopwatch, "error");
ReleaseSocket(false);
handler.error(error, handler_ctx);
pool_unref(&pool);
}
void
TranslateClient::Fail(const std::exception &e)
{
Fail(ToGError(e));
}
/*
* request marshalling
*
*/
static void
write_packet_n(GrowingBuffer *gb, uint16_t command,
const void *payload, size_t length)
{
static struct beng_translation_header header;
if (length >= 0xffff)
throw FormatRuntimeError("payload for translate command %u too large",
command);
header.length = (uint16_t)length;
header.command = command;
gb->Write(&header, sizeof(header));
if (length > 0)
gb->Write(payload, length);
}
static void
write_packet(GrowingBuffer *gb, uint16_t command, const char *payload)
{
write_packet_n(gb, command, payload,
payload != nullptr ? strlen(payload) : 0);
}
template<typename T>
static void
write_buffer(GrowingBuffer *gb, uint16_t command,
ConstBuffer<T> buffer)
{
auto b = buffer.ToVoid();
write_packet_n(gb, command, b.data, b.size);
}
/**
* Forward the command to write_packet() only if #payload is not nullptr.
*/
static void
write_optional_packet(GrowingBuffer *gb, uint16_t command, const char *payload)
{
if (payload != nullptr)
write_packet(gb, command, payload);
}
template<typename T>
static void
write_optional_buffer(GrowingBuffer *gb, uint16_t command,
ConstBuffer<T> buffer)
{
if (!buffer.IsNull())
write_buffer(gb, command, buffer);
}
static void
write_short(GrowingBuffer *gb, uint16_t command, uint16_t payload)
{
write_packet_n(gb, command, &payload, sizeof(payload));
}
static void
write_sockaddr(GrowingBuffer *gb,
uint16_t command, uint16_t command_string,
SocketAddress address)
{
assert(!address.IsNull());
char address_string[1024];
write_packet_n(gb, command,
address.GetAddress(), address.GetSize());
if (socket_address_to_string(address_string, sizeof(address_string),
address.GetAddress(), address.GetSize()))
write_packet(gb, command_string, address_string);
}
static void
write_optional_sockaddr(GrowingBuffer *gb,
uint16_t command, uint16_t command_string,
SocketAddress address)
{
if (!address.IsNull())
write_sockaddr(gb, command, command_string, address);
}
static GrowingBuffer
marshal_request(struct pool &pool, const TranslateRequest &request)
{
GrowingBuffer gb(pool, 512);
write_packet_n(&gb, TRANSLATE_BEGIN,
&PROTOCOL_VERSION, sizeof(PROTOCOL_VERSION));
write_optional_buffer(&gb, TRANSLATE_ERROR_DOCUMENT,
request.error_document);
if (request.error_document_status != 0)
write_short(&gb, TRANSLATE_STATUS,
request.error_document_status);
write_optional_packet(&gb, TRANSLATE_LISTENER_TAG,
request.listener_tag);
write_optional_sockaddr(&gb, TRANSLATE_LOCAL_ADDRESS,
TRANSLATE_LOCAL_ADDRESS_STRING,
request.local_address);
write_optional_packet(&gb, TRANSLATE_REMOTE_HOST,
request.remote_host);
write_optional_packet(&gb, TRANSLATE_HOST, request.host);
write_optional_packet(&gb, TRANSLATE_USER_AGENT, request.user_agent);
write_optional_packet(&gb, TRANSLATE_UA_CLASS, request.ua_class);
write_optional_packet(&gb, TRANSLATE_LANGUAGE, request.accept_language);
write_optional_packet(&gb, TRANSLATE_AUTHORIZATION, request.authorization);
write_optional_packet(&gb, TRANSLATE_URI, request.uri);
write_optional_packet(&gb, TRANSLATE_ARGS, request.args);
write_optional_packet(&gb, TRANSLATE_QUERY_STRING, request.query_string);
write_optional_packet(&gb, TRANSLATE_WIDGET_TYPE, request.widget_type);
write_optional_buffer(&gb, TRANSLATE_SESSION, request.session);
write_optional_buffer(&gb, TRANSLATE_INTERNAL_REDIRECT,
request.internal_redirect);
write_optional_buffer(&gb, TRANSLATE_CHECK, request.check);
write_optional_buffer(&gb, TRANSLATE_AUTH, request.auth);
write_optional_buffer(&gb, TRANSLATE_WANT_FULL_URI, request.want_full_uri);
write_optional_buffer(&gb, TRANSLATE_WANT, request.want);
write_optional_buffer(&gb, TRANSLATE_FILE_NOT_FOUND,
request.file_not_found);
write_optional_buffer(&gb, TRANSLATE_CONTENT_TYPE_LOOKUP,
request.content_type_lookup);
write_optional_packet(&gb, TRANSLATE_SUFFIX, request.suffix);
write_optional_buffer(&gb, TRANSLATE_ENOTDIR, request.enotdir);
write_optional_buffer(&gb, TRANSLATE_DIRECTORY_INDEX,
request.directory_index);
write_optional_packet(&gb, TRANSLATE_PARAM, request.param);
write_optional_buffer(&gb, TRANSLATE_PROBE_PATH_SUFFIXES,
request.probe_path_suffixes);
write_optional_packet(&gb, TRANSLATE_PROBE_SUFFIX,
request.probe_suffix);
write_optional_buffer(&gb, TRANSLATE_READ_FILE,
request.read_file);
write_optional_packet(&gb, TRANSLATE_USER, request.user);
write_packet(&gb, TRANSLATE_END, nullptr);
return gb;
}
/*
* receive response
*
*/
inline BufferedResult
TranslateClient::Feed(const uint8_t *data, size_t length)
try {
size_t consumed = 0;
while (consumed < length) {
size_t nbytes = parser.Feed(data + consumed, length - consumed);
if (nbytes == 0)
/* need more data */
break;
consumed += nbytes;
socket.Consumed(nbytes);
auto result = parser.Process();
switch (result) {
case TranslateParser::Result::MORE:
break;
case TranslateParser::Result::DONE:
ReleaseSocket(true);
handler.response(parser.GetResponse(), handler_ctx);
pool_unref(&pool);
return BufferedResult::CLOSED;
}
}
return BufferedResult::MORE;
} catch (const std::runtime_error &e) {
Fail(e);
return BufferedResult::CLOSED;
}
/*
* send requests
*
*/
static bool
translate_try_write(TranslateClient *client)
{
auto src = client->request.Read();
assert(!src.IsNull());
ssize_t nbytes = client->socket.Write(src.data, src.size);
if (gcc_unlikely(nbytes < 0)) {
if (gcc_likely(nbytes == WRITE_BLOCKING))
return true;
GError *error =
new_error_errno_msg("write error to translation server");
client->Fail(error);
return false;
}
client->request.Consume(nbytes);
if (client->request.IsEOF()) {
/* the buffer is empty, i.e. the request has been sent */
stopwatch_event(client->stopwatch, "request");
client->socket.UnscheduleWrite();
return client->socket.Read(true);
}
client->socket.ScheduleWrite();
return true;
}
/*
* buffered_socket handler
*
*/
static BufferedResult
translate_client_socket_data(const void *buffer, size_t size, void *ctx)
{
TranslateClient *client = (TranslateClient *)ctx;
return client->Feed((const uint8_t *)buffer, size);
}
static bool
translate_client_socket_closed(void *ctx)
{
TranslateClient *client = (TranslateClient *)ctx;
client->ReleaseSocket(false);
return true;
}
static bool
translate_client_socket_write(void *ctx)
{
TranslateClient *client = (TranslateClient *)ctx;
return translate_try_write(client);
}
static void
translate_client_socket_error(std::exception_ptr ep, void *ctx)
{
TranslateClient *client = (TranslateClient *)ctx;
auto *error = ToGError(ep);
g_prefix_error(&error, "Translation server connection failed: ");
client->Fail(error);
}
static constexpr BufferedSocketHandler translate_client_socket_handler = {
.data = translate_client_socket_data,
.direct = nullptr,
.closed = translate_client_socket_closed,
.remaining = nullptr,
.end = nullptr,
.write = translate_client_socket_write,
.drained = nullptr,
.timeout = nullptr,
.broken = nullptr,
.error = translate_client_socket_error,
};
/*
* constructor
*
*/
inline
TranslateClient::TranslateClient(struct pool &p, EventLoop &event_loop,
int fd, Lease &lease,
const TranslateRequest &request2,
GrowingBuffer &&_request,
const TranslateHandler &_handler, void *_ctx,
CancellablePointer &cancel_ptr)
:pool(p),
stopwatch(stopwatch_fd_new(&p, fd, request2.GetDiagnosticName())),
socket(event_loop),
request_buffer(std::move(_request)),
request(request_buffer),
handler(_handler), handler_ctx(_ctx),
parser(p, request2)
{
socket.Init(fd, FdType::FD_SOCKET,
&translate_read_timeout,
&translate_write_timeout,
translate_client_socket_handler, this);
p_lease_ref_set(lease_ref, lease, p, "translate_lease");
cancel_ptr = *this;
}
void
translate(struct pool &pool, EventLoop &event_loop,
int fd, Lease &lease,
const TranslateRequest &request,
const TranslateHandler &handler, void *ctx,
CancellablePointer &cancel_ptr)
try {
assert(fd >= 0);
assert(request.uri != nullptr || request.widget_type != nullptr ||
(!request.content_type_lookup.IsNull() &&
request.suffix != nullptr));
assert(handler.response != nullptr);
assert(handler.error != nullptr);
GrowingBuffer gb = marshal_request(pool, request);
auto *client = NewFromPool<TranslateClient>(pool, pool, event_loop,
fd, lease,
request, std::move(gb),
handler, ctx, cancel_ptr);
pool_ref(&client->pool);
translate_try_write(client);
} catch (const std::runtime_error &e) {
lease.ReleaseLease(true);
handler.error(ToGError(e), ctx);
}
<|endoftext|> |
<commit_before>//
// ulib - a collection of useful classes
// Copyright (C) 2008,2009,2013,2017 Michael Fink
//
/// \file ProgramOptions.cpp program options implementation
//
#include "stdafx.h"
#include "ProgramOptions.hpp"
#include "CommandLineParser.hpp"
#include "Path.hpp"
void ProgramOptions::RegisterOption(const CString& shortOptionChars, const CString& longOption,
const CString& helpText, unsigned int numArgs, T_fnOptionHandler fnOptionHandler)
{
CString longOptionLower(longOption);
longOptionLower.MakeLower();
OptionInfo info(shortOptionChars, longOptionLower, helpText, numArgs, fnOptionHandler);
m_optionsList.push_back(info);
}
void ProgramOptions::RegisterOption(const CString& shortOptionChars, const CString& longOption,
const CString& helpText, T_fnOptionHandlerSingleArg fnOptionHandler)
{
T_fnOptionHandler fnOptionHandler2 =
std::bind(&ProgramOptions::CallSingleArgHandler, std::placeholders::_1, fnOptionHandler);
RegisterOption(shortOptionChars, longOption, helpText, 1, fnOptionHandler2);
}
void ProgramOptions::RegisterOption(const CString& shortOptionChars, const CString& longOption,
const CString& helpText, CString& argStorage)
{
T_fnOptionHandlerSingleArg fnOptionHandler =
std::bind(&ProgramOptions::SetStringArgStorage, std::placeholders::_1, std::ref(argStorage));
RegisterOption(shortOptionChars, longOption, helpText, fnOptionHandler);
}
void ProgramOptions::RegisterOption(const CString& shortOptionChars, const CString& longOption,
const CString& helpText, bool& optionFlag)
{
T_fnOptionHandlerSingleArg fnOptionHandler =
std::bind(&ProgramOptions::SetBoolArgStorage, std::ref(optionFlag));
RegisterOption(shortOptionChars, longOption, helpText, fnOptionHandler);
}
void ProgramOptions::RegisterHelpOption()
{
T_fnOptionHandler fnOptionHandler = std::bind(&ProgramOptions::OutputHelp, this);
RegisterOption(_T("h?"), _T("help"), _T("Shows help"), 0, fnOptionHandler);
}
bool ProgramOptions::OutputHelp()
{
if (!m_fnOptionOutputHandler)
return true;
CString appFilename = Path(m_executableFilename).FilenameAndExt();
CString helpText;
helpText.Format(
_T("Syntax: %s <params> <args>\n")
_T("Options:\n"),
appFilename.GetString());
// append all options
size_t maxOptionListIndex = m_optionsList.size();
for (size_t optionListIndex = 0; optionListIndex < maxOptionListIndex; optionListIndex++)
{
OptionInfo& optInfo = m_optionsList[optionListIndex];
// add short option chars
size_t maxShortOptions = optInfo.m_shortOptionChars.GetLength();
for (size_t shortOptionIndex = 0; shortOptionIndex < maxShortOptions; shortOptionIndex++)
{
helpText.AppendFormat(_T(" -%c"), optInfo.m_shortOptionChars[shortOptionIndex]);
}
// add long option string
helpText.AppendFormat(_T(" --%s"), optInfo.m_longOption.GetString());
helpText += _T("\n ");
// help text
CString temp = optInfo.m_helpText;
temp.Replace(_T("\n"), _T("\n ")); // add proper indentation
helpText += temp + _T("\n");
}
m_fnOptionOutputHandler(helpText);
m_handledHelp = true;
return true;
}
void ProgramOptions::Parse(int argc, _TCHAR* argv[])
{
CommandLineParser parser(argc, argv);
Parse(parser);
}
void ProgramOptions::Parse(LPCTSTR commandLine)
{
CommandLineParser parser(commandLine);
Parse(parser);
}
void ProgramOptions::Parse(CommandLineParser& parser)
{
// must contain at least one param
ATLVERIFY(true == parser.GetNext(m_executableFilename));
CString argument;
while (parser.GetNext(argument))
{
ATLASSERT(argument.GetLength() > 0);
// check for first char
TCHAR chArg = argument[0];
if (argument.GetLength() > 1 && (chArg == _T('/') || chArg == _T('-')))
{
TCHAR searchOptionChar = 0;
CString longSearchOption;
// it's an option, either short or long one
TCHAR optionChar = argument[1];
if (chArg == _T('-') && optionChar == _T('-'))
{
// we have a unix-style option, long name only
longSearchOption = argument.Mid(2);
longSearchOption.MakeLower();
}
else
{
// we have either /X or -X or option, short name only
searchOptionChar = optionChar;
}
// now search for the proper option
bool foundOption = false;
for (size_t optionsIndex = 0, maxOptionsIndex = m_optionsList.size(); optionsIndex < maxOptionsIndex; optionsIndex++)
{
OptionInfo& optInfo = m_optionsList[optionsIndex];
// check long name first, then short name
if ((!longSearchOption.IsEmpty() && longSearchOption == optInfo.m_longOption) ||
(searchOptionChar != 0 && CString(searchOptionChar).FindOneOf(optInfo.m_shortOptionChars) != -1))
{
// found long or short option
foundOption = true;
// get arguments
std::vector<CString> argsList;
CString paramArgs;
for (unsigned int numArgs = 0; numArgs < optInfo.m_numArgs; numArgs++)
{
parser.GetNext(paramArgs);
argsList.push_back(paramArgs);
}
if (argsList.size() < optInfo.m_numArgs)
{
// too few arguments
if (m_fnOptionOutputHandler)
m_fnOptionOutputHandler(CString(_T("Too few parameters for option: ") + argument));
break;
}
ATLASSERT(optInfo.m_fnOptionHandler != NULL);
bool ret2 = optInfo.m_fnOptionHandler(argsList);
if (!ret2)
{
if (m_fnOptionOutputHandler)
m_fnOptionOutputHandler(CString(_T("Syntax error for option: ") + argument));
}
break;
}
} // end for
if (!foundOption)
{
// unknown option
if (m_fnOptionOutputHandler)
m_fnOptionOutputHandler(CString(_T("Unknown option: ") + argument));
}
}
else
{
// no arg; it's a file
bool handled = false;
if (m_fnParameterHandler)
handled = m_fnParameterHandler(argument);
if (!handled)
{
// output: unhandled option
if (m_fnOptionOutputHandler)
m_fnOptionOutputHandler(CString(_T("Unknown parameter: ") + argument));
}
}
}
}
void ProgramOptions::OutputConsole(const CString& text)
{
_tprintf(_T("%s\n"), text.GetString());
}
<commit_msg>fixed warning in x64 configuration<commit_after>//
// ulib - a collection of useful classes
// Copyright (C) 2008,2009,2013,2017 Michael Fink
//
/// \file ProgramOptions.cpp program options implementation
//
#include "stdafx.h"
#include "ProgramOptions.hpp"
#include "CommandLineParser.hpp"
#include "Path.hpp"
void ProgramOptions::RegisterOption(const CString& shortOptionChars, const CString& longOption,
const CString& helpText, unsigned int numArgs, T_fnOptionHandler fnOptionHandler)
{
CString longOptionLower(longOption);
longOptionLower.MakeLower();
OptionInfo info(shortOptionChars, longOptionLower, helpText, numArgs, fnOptionHandler);
m_optionsList.push_back(info);
}
void ProgramOptions::RegisterOption(const CString& shortOptionChars, const CString& longOption,
const CString& helpText, T_fnOptionHandlerSingleArg fnOptionHandler)
{
T_fnOptionHandler fnOptionHandler2 =
std::bind(&ProgramOptions::CallSingleArgHandler, std::placeholders::_1, fnOptionHandler);
RegisterOption(shortOptionChars, longOption, helpText, 1, fnOptionHandler2);
}
void ProgramOptions::RegisterOption(const CString& shortOptionChars, const CString& longOption,
const CString& helpText, CString& argStorage)
{
T_fnOptionHandlerSingleArg fnOptionHandler =
std::bind(&ProgramOptions::SetStringArgStorage, std::placeholders::_1, std::ref(argStorage));
RegisterOption(shortOptionChars, longOption, helpText, fnOptionHandler);
}
void ProgramOptions::RegisterOption(const CString& shortOptionChars, const CString& longOption,
const CString& helpText, bool& optionFlag)
{
T_fnOptionHandlerSingleArg fnOptionHandler =
std::bind(&ProgramOptions::SetBoolArgStorage, std::ref(optionFlag));
RegisterOption(shortOptionChars, longOption, helpText, fnOptionHandler);
}
void ProgramOptions::RegisterHelpOption()
{
T_fnOptionHandler fnOptionHandler = std::bind(&ProgramOptions::OutputHelp, this);
RegisterOption(_T("h?"), _T("help"), _T("Shows help"), 0, fnOptionHandler);
}
bool ProgramOptions::OutputHelp()
{
if (!m_fnOptionOutputHandler)
return true;
CString appFilename = Path(m_executableFilename).FilenameAndExt();
CString helpText;
helpText.Format(
_T("Syntax: %s <params> <args>\n")
_T("Options:\n"),
appFilename.GetString());
// append all options
size_t maxOptionListIndex = m_optionsList.size();
for (size_t optionListIndex = 0; optionListIndex < maxOptionListIndex; optionListIndex++)
{
OptionInfo& optInfo = m_optionsList[optionListIndex];
// add short option chars
int maxShortOptions = optInfo.m_shortOptionChars.GetLength();
for (int shortOptionIndex = 0; shortOptionIndex < maxShortOptions; shortOptionIndex++)
{
helpText.AppendFormat(_T(" -%c"), optInfo.m_shortOptionChars[shortOptionIndex]);
}
// add long option string
helpText.AppendFormat(_T(" --%s"), optInfo.m_longOption.GetString());
helpText += _T("\n ");
// help text
CString temp = optInfo.m_helpText;
temp.Replace(_T("\n"), _T("\n ")); // add proper indentation
helpText += temp + _T("\n");
}
m_fnOptionOutputHandler(helpText);
m_handledHelp = true;
return true;
}
void ProgramOptions::Parse(int argc, _TCHAR* argv[])
{
CommandLineParser parser(argc, argv);
Parse(parser);
}
void ProgramOptions::Parse(LPCTSTR commandLine)
{
CommandLineParser parser(commandLine);
Parse(parser);
}
void ProgramOptions::Parse(CommandLineParser& parser)
{
// must contain at least one param
ATLVERIFY(true == parser.GetNext(m_executableFilename));
CString argument;
while (parser.GetNext(argument))
{
ATLASSERT(argument.GetLength() > 0);
// check for first char
TCHAR chArg = argument[0];
if (argument.GetLength() > 1 && (chArg == _T('/') || chArg == _T('-')))
{
TCHAR searchOptionChar = 0;
CString longSearchOption;
// it's an option, either short or long one
TCHAR optionChar = argument[1];
if (chArg == _T('-') && optionChar == _T('-'))
{
// we have a unix-style option, long name only
longSearchOption = argument.Mid(2);
longSearchOption.MakeLower();
}
else
{
// we have either /X or -X or option, short name only
searchOptionChar = optionChar;
}
// now search for the proper option
bool foundOption = false;
for (size_t optionsIndex = 0, maxOptionsIndex = m_optionsList.size(); optionsIndex < maxOptionsIndex; optionsIndex++)
{
OptionInfo& optInfo = m_optionsList[optionsIndex];
// check long name first, then short name
if ((!longSearchOption.IsEmpty() && longSearchOption == optInfo.m_longOption) ||
(searchOptionChar != 0 && CString(searchOptionChar).FindOneOf(optInfo.m_shortOptionChars) != -1))
{
// found long or short option
foundOption = true;
// get arguments
std::vector<CString> argsList;
CString paramArgs;
for (unsigned int numArgs = 0; numArgs < optInfo.m_numArgs; numArgs++)
{
parser.GetNext(paramArgs);
argsList.push_back(paramArgs);
}
if (argsList.size() < optInfo.m_numArgs)
{
// too few arguments
if (m_fnOptionOutputHandler)
m_fnOptionOutputHandler(CString(_T("Too few parameters for option: ") + argument));
break;
}
ATLASSERT(optInfo.m_fnOptionHandler != NULL);
bool ret2 = optInfo.m_fnOptionHandler(argsList);
if (!ret2)
{
if (m_fnOptionOutputHandler)
m_fnOptionOutputHandler(CString(_T("Syntax error for option: ") + argument));
}
break;
}
} // end for
if (!foundOption)
{
// unknown option
if (m_fnOptionOutputHandler)
m_fnOptionOutputHandler(CString(_T("Unknown option: ") + argument));
}
}
else
{
// no arg; it's a file
bool handled = false;
if (m_fnParameterHandler)
handled = m_fnParameterHandler(argument);
if (!handled)
{
// output: unhandled option
if (m_fnOptionOutputHandler)
m_fnOptionOutputHandler(CString(_T("Unknown parameter: ") + argument));
}
}
}
}
void ProgramOptions::OutputConsole(const CString& text)
{
_tprintf(_T("%s\n"), text.GetString());
}
<|endoftext|> |
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/memory/lib/mc/perf_reg.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2016,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file perf_reg.C
/// @brief Subroutines to manipulate the memory controller performance registers
///
// *HWP HWP Owner: Brian Silver <[email protected]>
// *HWP HWP Backup: Andre Marin <[email protected]>
// *HWP Team: Memory
// *HWP Level: 2
// *HWP Consumed by: FSP:HB
#include <fapi2.H>
#include <p9_mc_scom_addresses.H>
#include <p9_mc_scom_addresses_fld.H>
#include <lib/mss_attribute_accessors.H>
#include <lib/mc/mc.H>
#include <lib/utils/scom.H>
#include <lib/dimm/kind.H>
#include <lib/utils/find.H>
using fapi2::TARGET_TYPE_MCA;
using fapi2::TARGET_TYPE_MCS;
using fapi2::TARGET_TYPE_DIMM;
namespace mss
{
namespace mc
{
///
/// @brief Perform initializations of the MC performance registers
/// @note Some of these bits are taken care of in the scom initfiles
/// @param[in] i_target the target which has the MCA to map
/// @return FAPI2_RC_SUCCESS iff ok
///
fapi2::ReturnCode setup_perf2_register(const fapi2::Target<TARGET_TYPE_MCA>& i_target)
{
fapi2::buffer<uint64_t> l_data;
// Get the values we need to put in the register
uint64_t l_value;
FAPI_TRY( calculate_perf2(i_target, l_value) );
// Setup the registers
FAPI_TRY( mss::getScom(i_target, MCS_0_PORT02_MCPERF2, l_data) );
// Per S. Powell 7/16, setup these registers but don't enable the function yet. So enable bits are
// intentionally not set
l_data.insertFromRight<MCS_PORT02_MCPERF2_REFRESH_BLOCK_CONFIG,
MCS_PORT02_MCPERF2_REFRESH_BLOCK_CONFIG_LEN>(l_value);
FAPI_TRY( mss::putScom(i_target, MCS_0_PORT02_MCPERF2, l_data) );
fapi_try_exit:
return fapi2::FAPI2_RC_SUCCESS;
}
///
/// @brief Calculate the value of the MC perf2 register.
/// @param[in] i_target the target which has the MCA to map
/// @param[out] o_value the perf2 value for the MCA
/// @return FAPI2_RC_SUCCESS iff ok
///
fapi2::ReturnCode calculate_perf2(const fapi2::Target<TARGET_TYPE_MCA>& i_target, uint64_t& o_value)
{
//
// From Senor Powell 7/16
// if (slots=1, masters=1)
// MCPERF2_Refresh_Block_Config=0b000
// if (slots=1, masters=2)
// MCPERF2_Refresh_Block_Config=0b001
// if (slots=1, masters=4)
// MCPERF2_Refresh_Block_Config=0b100
// if (slots=2, masters=1)
// MCPERF2_Refresh_Block_Config=0b010
// if (slots=2, masters=2)
// MCPERF2_Refresh_Block_Config=0b011
// if (slots=2, masters=4)
// MCPERF2_Refresh_Block_Config=0b100
//
// if slot0 is 2 masters and slot1 is 1 master, just choose the 2 slot, 2 masters setting.
// (i.e., choose the max(mranks_dimm1, mranks_dimm2)
constexpr uint64_t l_refresh_values[MAX_DIMM_PER_PORT][MAX_RANK_PER_DIMM] =
{
{0b000, 0b001, 0, 0b100}, // Skip the ol' 3 rank DIMM
{0b010, 0b011, 0, 0b100}
};
FAPI_INF("Calculating perf2 register for MCA%d (%d)", mss::pos(i_target), mss::index(i_target));
// Find the DIMM on this port with the most master ranks.
// That's how we know which element in the table to use.
// uint8_t so I can use it to read from an attribute directly
uint8_t l_mrank_index = 0;
uint8_t l_master_ranks_zero = 0;
uint8_t l_master_ranks_one = 0;
fapi2::buffer<uint64_t> l_data;
const auto l_dimm = mss::find_targets<TARGET_TYPE_DIMM>(i_target);
const auto l_slot_index = l_dimm.size() - 1;
switch(l_dimm.size())
{
// No DIMM, nothing to do
case 0:
return fapi2::FAPI2_RC_SUCCESS;
break;
// One DIMM, we've got the slots of fun
case 1:
FAPI_TRY( mss::eff_num_master_ranks_per_dimm(l_dimm[0], l_mrank_index) );
--l_mrank_index;
FAPI_INF("1 DIMM mranks: D0[%d] index %d", l_mrank_index + 1, l_mrank_index);
break;
// Two DIMM, find the max of the master ranks
case 2:
{
FAPI_TRY( mss::eff_num_master_ranks_per_dimm(l_dimm[0], l_master_ranks_zero) );
FAPI_TRY( mss::eff_num_master_ranks_per_dimm(l_dimm[1], l_master_ranks_one) );
l_mrank_index = std::max(l_master_ranks_zero, l_master_ranks_one) - 1;
FAPI_INF("2 DIMM mranks: D0[%d] D1[%d] index %d", l_master_ranks_zero, l_master_ranks_one, l_mrank_index);
}
break;
default:
// We have a bug - no way to get more than 2 DIMM in a dual-drop system
FAPI_ERR("seeing %d DIMM on %s", l_dimm.size(), mss::c_str(i_target));
fapi2::Assert(false);
break;
};
FAPI_INF("Refresh Block Config: %u ([%d][%d] populated slots: %d, max mranks: %d)",
l_refresh_values[l_slot_index][l_mrank_index],
l_slot_index, l_mrank_index,
l_slot_index + 1, l_mrank_index + 1);
o_value = l_refresh_values[l_slot_index][l_mrank_index];
fapi_try_exit:
return fapi2::current_err;
}
} // namespace
} // namespace
<commit_msg>Move scom API to share among controllers<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/memory/lib/mc/perf_reg.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2016,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file perf_reg.C
/// @brief Subroutines to manipulate the memory controller performance registers
///
// *HWP HWP Owner: Brian Silver <[email protected]>
// *HWP HWP Backup: Andre Marin <[email protected]>
// *HWP Team: Memory
// *HWP Level: 2
// *HWP Consumed by: FSP:HB
#include <fapi2.H>
#include <p9_mc_scom_addresses.H>
#include <p9_mc_scom_addresses_fld.H>
#include <lib/mss_attribute_accessors.H>
#include <lib/mc/mc.H>
#include <generic/memory/lib/utils/scom.H>
#include <lib/dimm/kind.H>
#include <lib/utils/find.H>
using fapi2::TARGET_TYPE_MCA;
using fapi2::TARGET_TYPE_MCS;
using fapi2::TARGET_TYPE_DIMM;
namespace mss
{
namespace mc
{
///
/// @brief Perform initializations of the MC performance registers
/// @note Some of these bits are taken care of in the scom initfiles
/// @param[in] i_target the target which has the MCA to map
/// @return FAPI2_RC_SUCCESS iff ok
///
fapi2::ReturnCode setup_perf2_register(const fapi2::Target<TARGET_TYPE_MCA>& i_target)
{
fapi2::buffer<uint64_t> l_data;
// Get the values we need to put in the register
uint64_t l_value;
FAPI_TRY( calculate_perf2(i_target, l_value) );
// Setup the registers
FAPI_TRY( mss::getScom(i_target, MCS_0_PORT02_MCPERF2, l_data) );
// Per S. Powell 7/16, setup these registers but don't enable the function yet. So enable bits are
// intentionally not set
l_data.insertFromRight<MCS_PORT02_MCPERF2_REFRESH_BLOCK_CONFIG,
MCS_PORT02_MCPERF2_REFRESH_BLOCK_CONFIG_LEN>(l_value);
FAPI_TRY( mss::putScom(i_target, MCS_0_PORT02_MCPERF2, l_data) );
fapi_try_exit:
return fapi2::FAPI2_RC_SUCCESS;
}
///
/// @brief Calculate the value of the MC perf2 register.
/// @param[in] i_target the target which has the MCA to map
/// @param[out] o_value the perf2 value for the MCA
/// @return FAPI2_RC_SUCCESS iff ok
///
fapi2::ReturnCode calculate_perf2(const fapi2::Target<TARGET_TYPE_MCA>& i_target, uint64_t& o_value)
{
//
// From Senor Powell 7/16
// if (slots=1, masters=1)
// MCPERF2_Refresh_Block_Config=0b000
// if (slots=1, masters=2)
// MCPERF2_Refresh_Block_Config=0b001
// if (slots=1, masters=4)
// MCPERF2_Refresh_Block_Config=0b100
// if (slots=2, masters=1)
// MCPERF2_Refresh_Block_Config=0b010
// if (slots=2, masters=2)
// MCPERF2_Refresh_Block_Config=0b011
// if (slots=2, masters=4)
// MCPERF2_Refresh_Block_Config=0b100
//
// if slot0 is 2 masters and slot1 is 1 master, just choose the 2 slot, 2 masters setting.
// (i.e., choose the max(mranks_dimm1, mranks_dimm2)
constexpr uint64_t l_refresh_values[MAX_DIMM_PER_PORT][MAX_RANK_PER_DIMM] =
{
{0b000, 0b001, 0, 0b100}, // Skip the ol' 3 rank DIMM
{0b010, 0b011, 0, 0b100}
};
FAPI_INF("Calculating perf2 register for MCA%d (%d)", mss::pos(i_target), mss::index(i_target));
// Find the DIMM on this port with the most master ranks.
// That's how we know which element in the table to use.
// uint8_t so I can use it to read from an attribute directly
uint8_t l_mrank_index = 0;
uint8_t l_master_ranks_zero = 0;
uint8_t l_master_ranks_one = 0;
fapi2::buffer<uint64_t> l_data;
const auto l_dimm = mss::find_targets<TARGET_TYPE_DIMM>(i_target);
const auto l_slot_index = l_dimm.size() - 1;
switch(l_dimm.size())
{
// No DIMM, nothing to do
case 0:
return fapi2::FAPI2_RC_SUCCESS;
break;
// One DIMM, we've got the slots of fun
case 1:
FAPI_TRY( mss::eff_num_master_ranks_per_dimm(l_dimm[0], l_mrank_index) );
--l_mrank_index;
FAPI_INF("1 DIMM mranks: D0[%d] index %d", l_mrank_index + 1, l_mrank_index);
break;
// Two DIMM, find the max of the master ranks
case 2:
{
FAPI_TRY( mss::eff_num_master_ranks_per_dimm(l_dimm[0], l_master_ranks_zero) );
FAPI_TRY( mss::eff_num_master_ranks_per_dimm(l_dimm[1], l_master_ranks_one) );
l_mrank_index = std::max(l_master_ranks_zero, l_master_ranks_one) - 1;
FAPI_INF("2 DIMM mranks: D0[%d] D1[%d] index %d", l_master_ranks_zero, l_master_ranks_one, l_mrank_index);
}
break;
default:
// We have a bug - no way to get more than 2 DIMM in a dual-drop system
FAPI_ERR("seeing %d DIMM on %s", l_dimm.size(), mss::c_str(i_target));
fapi2::Assert(false);
break;
};
FAPI_INF("Refresh Block Config: %u ([%d][%d] populated slots: %d, max mranks: %d)",
l_refresh_values[l_slot_index][l_mrank_index],
l_slot_index, l_mrank_index,
l_slot_index + 1, l_mrank_index + 1);
o_value = l_refresh_values[l_slot_index][l_mrank_index];
fapi_try_exit:
return fapi2::current_err;
}
} // namespace
} // namespace
<|endoftext|> |
<commit_before>// Copyright (c) 2016, Baidu.com, Inc. All Rights Reserved
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
#include <string>
#include <map>
#include <gflags/gflags.h>
#include <leveldb/db.h>
#include <common/string_util.h>
#include <common/logging.h>
#include "proto/block.pb.h"
#include "utils/meta_converter.h"
namespace baidu {
namespace bfs {
const int CHUNKSERVER_META_VERSION = 1;
const int EMPTY_META = -1;
void CheckChunkserverMeta(const std::vector<std::string>& store_path_list) {
std::map<std::string, leveldb::DB*> meta_dbs;
int meta_version = EMPTY_META;
for (size_t i = 0; i < store_path_list.size(); ++i) {
const std::string& path = store_path_list[i];
leveldb::Options options;
options.create_if_missing = true;
leveldb::DB* metadb;
leveldb::Status s = leveldb::DB::Open(options, path + "/meta/", &metadb);
if (!s.ok()) {
LOG(ERROR, "[MetaCheck] Open meta on %s failed: %s", path.c_str(), s.ToString().c_str());
exit(EXIT_FAILURE);
return;
}
std::string version_key(8, '\0');
version_key.append("version");
std::string version_str;
s = metadb->Get(leveldb::ReadOptions(), version_key, &version_str);
if (s.IsNotFound()) {
LOG(INFO, "[MetaCheck] Load empty meta %s", path.c_str());
} else {
int64_t ns_v = *(reinterpret_cast<int64_t*>(&version_str[0]));
LOG(INFO, "[MetaCheck] Load namespace %ld on %s", ns_v, path.c_str());
std::string meta_key(8, '\0');
meta_key.append("meta");
std::string meta_str;
s = metadb->Get(leveldb::ReadOptions(), meta_key, &meta_str);
if (s.ok()) {
int cur_version = *(reinterpret_cast<int*>(&meta_str[0]));
LOG(INFO, "[MetaCheck] %s Load meta version %d", path.c_str(), cur_version);
if (meta_version != EMPTY_META && cur_version != meta_version) {
LOG(ERROR, "Cannot handle this situation!!!");
exit(EXIT_FAILURE);
}
meta_version = cur_version;
} else if (s.IsNotFound()) {
if (meta_version != EMPTY_META && meta_version != 0) {
LOG(ERROR, "Cannot handle this situation!!!");
exit(EXIT_FAILURE);
}
meta_version = 0;
LOG(INFO, "No meta version %s", path.c_str());
}
}
meta_dbs[path] = metadb;
}
if (meta_version == CHUNKSERVER_META_VERSION) {
LOG(INFO, "[MetaCheck] Chunkserver meta check pass");
} else if (meta_version == EMPTY_META) {
LOG(INFO, "[MetaCheck] Chunkserver empty");
SetChunkserverMetaVersion(meta_dbs);
} else if (meta_version == 0) {
ChunkserverMetaV02V1(meta_dbs);
SetChunkserverMetaVersion(meta_dbs);
} else {
LOG(ERROR, "[MetaCheck] Cannot handle this situation!!!");
exit(EXIT_FAILURE);
}
CloseMetaStore(meta_dbs);
}
void ChunkserverMetaV02V1(const std::map<std::string, leveldb::DB*>& meta_dbs) {
LOG(INFO, "[MetaCheck] Start converting chunkserver meta from verion 0");
leveldb::DB* src_meta = NULL;
std::string src_meta_path;
std::string version_key(8, '\0');
version_key.append("version");
std::string version_str;
for (auto it = meta_dbs.begin(); it != meta_dbs.end(); ++it) {
leveldb::DB* cur_db = it->second;
const std::string& cur_path = it->first;
leveldb::Status s = cur_db->Get(leveldb::ReadOptions(), version_key, &version_str);
if (s.ok()) {
src_meta = cur_db;
src_meta_path = it->first;
LOG(INFO, "[MetaCheck] Source meta store %s", cur_path.c_str());
break;
} else {
LOG(INFO, "[MetaCheck] No namespace version on %s, %s", cur_path.c_str(), s.ToString().c_str());
}
}
if (!src_meta) {
LOG(ERROR, "[MetaCheck] Cannot find a valid meta store");
exit(EXIT_FAILURE);
}
leveldb::Iterator* it = src_meta->NewIterator(leveldb::ReadOptions());
for (it->Seek(std::string(8, '\0') + "version" + '\0'); it->Valid(); it->Next()) {
BlockMeta meta;
if (!meta.ParseFromArray(it->value().data(), it->value().size())) {
LOG(ERROR, "[MetaCheck] Parse BlockMeta failed: key = %s", it->key().ToString().c_str());
exit(EXIT_FAILURE);
}
const std::string& path = meta.store_path();
auto db_it = meta_dbs.find(path);
if (db_it == meta_dbs.end()) {
LOG(WARNING, "[MetaCheck] Cannot find store_path %s", path.c_str());
continue;
}
leveldb::DB* disk_db = db_it->second;
disk_db->Put(leveldb::WriteOptions(), it->key(), it->value());
if (path != src_meta_path) {
src_meta->Delete(leveldb::WriteOptions(), it->key());
}
}
for (auto it = meta_dbs.begin(); it != meta_dbs.end(); ++it) {
leveldb::DB* ldb = it->second;
ldb->Put(leveldb::WriteOptions(), version_key, version_str);
}
delete it;
}
void SetChunkserverMetaVersion(const std::map<std::string, leveldb::DB*>& meta_dbs) {
for (auto it = meta_dbs.begin(); it != meta_dbs.end(); ++it) {
leveldb::DB* ldb = it->second;
std::string meta_key(8, '\0');
meta_key.append("meta");
std::string meta_str(4, '\0');
*(reinterpret_cast<int*>(&meta_str[0])) = CHUNKSERVER_META_VERSION;
leveldb::Status s = ldb->Put(leveldb::WriteOptions(), meta_key, meta_str);
if (!s.ok()) {
LOG(ERROR, "[MetaCheck] Put meta failed %s", it->first.c_str());
exit(EXIT_FAILURE);
}
LOG(INFO, "[MetaCheck] Set meta version %s = %d", it->first.c_str(), CHUNKSERVER_META_VERSION);
}
}
void CloseMetaStore(const std::map<std::string, leveldb::DB*>& meta_dbs) {
for (auto it = meta_dbs.begin(); it != meta_dbs.end(); ++it) {
delete it->second;
}
}
} // namespace bfs
} // namespace baidu<commit_msg>Small fix<commit_after>// Copyright (c) 2016, Baidu.com, Inc. All Rights Reserved
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
#include <string>
#include <map>
#include <gflags/gflags.h>
#include <leveldb/db.h>
#include <common/string_util.h>
#include <common/logging.h>
#include "proto/block.pb.h"
#include "utils/meta_converter.h"
namespace baidu {
namespace bfs {
const int CHUNKSERVER_META_VERSION = 1;
const int EMPTY_META = -1;
void CheckChunkserverMeta(const std::vector<std::string>& store_path_list) {
std::map<std::string, leveldb::DB*> meta_dbs;
int meta_version = EMPTY_META;
for (size_t i = 0; i < store_path_list.size(); ++i) {
const std::string& path = store_path_list[i];
leveldb::Options options;
options.create_if_missing = true;
leveldb::DB* metadb;
leveldb::Status s = leveldb::DB::Open(options, path + "/meta/", &metadb);
if (!s.ok()) {
LOG(ERROR, "[MetaCheck] Open meta on %s failed: %s", path.c_str(), s.ToString().c_str());
exit(EXIT_FAILURE);
return;
}
std::string version_key(8, '\0');
version_key.append("version");
std::string version_str;
s = metadb->Get(leveldb::ReadOptions(), version_key, &version_str);
if (s.IsNotFound()) {
LOG(INFO, "[MetaCheck] Load empty meta %s", path.c_str());
} else {
int64_t ns_v = *(reinterpret_cast<int64_t*>(&version_str[0]));
LOG(INFO, "[MetaCheck] Load namespace %ld on %s", ns_v, path.c_str());
std::string meta_key(8, '\0');
meta_key.append("meta");
std::string meta_str;
s = metadb->Get(leveldb::ReadOptions(), meta_key, &meta_str);
if (s.ok()) {
int cur_version = *(reinterpret_cast<int*>(&meta_str[0]));
LOG(INFO, "[MetaCheck] %s Load meta version %d", path.c_str(), cur_version);
if (meta_version != EMPTY_META && cur_version != meta_version) {
LOG(ERROR, "Cannot handle this situation!!!");
exit(EXIT_FAILURE);
}
meta_version = cur_version;
} else if (s.IsNotFound()) {
if (meta_version != EMPTY_META && meta_version != 0) {
LOG(ERROR, "Cannot handle this situation!!!");
exit(EXIT_FAILURE);
}
meta_version = 0;
LOG(INFO, "No meta version %s", path.c_str());
}
}
meta_dbs[path] = metadb;
}
if (meta_version == CHUNKSERVER_META_VERSION) {
LOG(INFO, "[MetaCheck] Chunkserver meta check pass");
} else if (meta_version == EMPTY_META) {
LOG(INFO, "[MetaCheck] Chunkserver empty");
SetChunkserverMetaVersion(meta_dbs);
} else if (meta_version == 0) {
ChunkserverMetaV02V1(meta_dbs);
SetChunkserverMetaVersion(meta_dbs);
} else {
LOG(ERROR, "[MetaCheck] Cannot handle this situation!!!");
exit(EXIT_FAILURE);
}
CloseMetaStore(meta_dbs);
}
void ChunkserverMetaV02V1(const std::map<std::string, leveldb::DB*>& meta_dbs) {
LOG(INFO, "[MetaCheck] Start converting chunkserver meta from verion 0");
leveldb::DB* src_meta = NULL;
std::string src_meta_path;
std::string version_key(8, '\0');
version_key.append("version");
std::string version_str;
for (auto it = meta_dbs.begin(); it != meta_dbs.end(); ++it) {
leveldb::DB* cur_db = it->second;
const std::string& cur_path = it->first;
leveldb::Status s = cur_db->Get(leveldb::ReadOptions(), version_key, &version_str);
if (s.ok()) {
src_meta = cur_db;
src_meta_path = it->first;
LOG(INFO, "[MetaCheck] Source meta store %s", cur_path.c_str());
break;
} else {
LOG(INFO, "[MetaCheck] No namespace version on %s, %s", cur_path.c_str(), s.ToString().c_str());
}
}
if (!src_meta) {
LOG(ERROR, "[MetaCheck] Cannot find a valid meta store");
exit(EXIT_FAILURE);
}
leveldb::Iterator* it = src_meta->NewIterator(leveldb::ReadOptions());
for (it->Seek(std::string(8, '\0') + "version" + '\0'); it->Valid(); it->Next()) {
BlockMeta meta;
if (!meta.ParseFromArray(it->value().data(), it->value().size())) {
LOG(ERROR, "[MetaCheck] Parse BlockMeta failed: key = %s", it->key().ToString().c_str());
exit(EXIT_FAILURE);
}
const std::string& path = meta.store_path();
auto db_it = meta_dbs.find(path);
if (db_it == meta_dbs.end()) {
src_meta->Delete(leveldb::WriteOptions(), it->key());
LOG(WARNING, "[MetaCheck] Cannot find store_path %s", path.c_str());
continue;
}
leveldb::DB* disk_db = db_it->second;
disk_db->Put(leveldb::WriteOptions(), it->key(), it->value());
if (path != src_meta_path) {
src_meta->Delete(leveldb::WriteOptions(), it->key());
}
}
for (auto it = meta_dbs.begin(); it != meta_dbs.end(); ++it) {
leveldb::DB* ldb = it->second;
ldb->Put(leveldb::WriteOptions(), version_key, version_str);
}
delete it;
}
void SetChunkserverMetaVersion(const std::map<std::string, leveldb::DB*>& meta_dbs) {
for (auto it = meta_dbs.begin(); it != meta_dbs.end(); ++it) {
leveldb::DB* ldb = it->second;
std::string meta_key(8, '\0');
meta_key.append("meta");
std::string meta_str(4, '\0');
*(reinterpret_cast<int*>(&meta_str[0])) = CHUNKSERVER_META_VERSION;
leveldb::Status s = ldb->Put(leveldb::WriteOptions(), meta_key, meta_str);
if (!s.ok()) {
LOG(ERROR, "[MetaCheck] Put meta failed %s", it->first.c_str());
exit(EXIT_FAILURE);
}
LOG(INFO, "[MetaCheck] Set meta version %s = %d", it->first.c_str(), CHUNKSERVER_META_VERSION);
}
}
void CloseMetaStore(const std::map<std::string, leveldb::DB*>& meta_dbs) {
for (auto it = meta_dbs.begin(); it != meta_dbs.end(); ++it) {
delete it->second;
}
}
} // namespace bfs
} // namespace baidu<|endoftext|> |
<commit_before>/*
* yosys -- Yosys Open SYnthesis Suite
*
* Copyright (C) 2012 Clifford Wolf <[email protected]>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*/
// [[CITE]] Tarjan's strongly connected components algorithm
// Tarjan, R. E. (1972), "Depth-first search and linear graph algorithms", SIAM Journal on Computing 1 (2): 146-160, doi:10.1137/0201010
// http://en.wikipedia.org/wiki/Tarjan's_strongly_connected_components_algorithm
#include "kernel/register.h"
#include "kernel/celltypes.h"
#include "kernel/sigtools.h"
#include "kernel/log.h"
#include <stdlib.h>
#include <stdio.h>
#include <set>
USING_YOSYS_NAMESPACE
PRIVATE_NAMESPACE_BEGIN
struct SccWorker
{
RTLIL::Design *design;
RTLIL::Module *module;
SigMap sigmap;
CellTypes ct;
std::set<RTLIL::Cell*> workQueue;
std::map<RTLIL::Cell*, std::set<RTLIL::Cell*>> cellToNextCell;
std::map<RTLIL::Cell*, RTLIL::SigSpec> cellToPrevSig, cellToNextSig;
std::map<RTLIL::Cell*, std::pair<int, int>> cellLabels;
std::map<RTLIL::Cell*, int> cellDepth;
std::set<RTLIL::Cell*> cellsOnStack;
std::vector<RTLIL::Cell*> cellStack;
int labelCounter;
std::map<RTLIL::Cell*, int> cell2scc;
std::vector<std::set<RTLIL::Cell*>> sccList;
void run(RTLIL::Cell *cell, int depth, int maxDepth)
{
log_assert(workQueue.count(cell) > 0);
workQueue.erase(cell);
cellLabels[cell] = std::pair<int, int>(labelCounter, labelCounter);
labelCounter++;
cellsOnStack.insert(cell);
cellStack.push_back(cell);
if (maxDepth >= 0)
cellDepth[cell] = depth;
for (auto nextCell : cellToNextCell[cell])
if (cellLabels.count(nextCell) == 0) {
run(nextCell, depth+1, maxDepth);
cellLabels[cell].second = min(cellLabels[cell].second, cellLabels[nextCell].second);
} else
if (cellsOnStack.count(nextCell) > 0 && (maxDepth < 0 || cellDepth[nextCell] + maxDepth > depth)) {
cellLabels[cell].second = min(cellLabels[cell].second, cellLabels[nextCell].second);
}
if (cellLabels[cell].first == cellLabels[cell].second)
{
if (cellStack.back() == cell)
{
cellStack.pop_back();
cellsOnStack.erase(cell);
}
else
{
log("Found an SCC:");
std::set<RTLIL::Cell*> scc;
while (cellsOnStack.count(cell) > 0) {
RTLIL::Cell *c = cellStack.back();
cellStack.pop_back();
cellsOnStack.erase(c);
log(" %s", RTLIL::id2cstr(c->name));
cell2scc[c] = sccList.size();
scc.insert(c);
}
sccList.push_back(scc);
log("\n");
}
}
}
SccWorker(RTLIL::Design *design, RTLIL::Module *module, bool nofeedbackMode, bool allCellTypes, int maxDepth) :
design(design), module(module), sigmap(module)
{
if (module->processes.size() > 0) {
log("Skipping module %s as it contains processes (run 'proc' pass first).\n", module->name.c_str());
return;
}
if (allCellTypes) {
ct.setup(design);
} else {
ct.setup_internals();
ct.setup_stdcells();
}
SigPool selectedSignals;
SigSet<RTLIL::Cell*> sigToNextCells;
for (auto &it : module->wires_)
if (design->selected(module, it.second))
selectedSignals.add(sigmap(RTLIL::SigSpec(it.second)));
for (auto &it : module->cells_)
{
RTLIL::Cell *cell = it.second;
if (!design->selected(module, cell))
continue;
if (!allCellTypes && !ct.cell_known(cell->type))
continue;
workQueue.insert(cell);
RTLIL::SigSpec inputSignals, outputSignals;
for (auto &conn : cell->connections())
{
bool isInput = true, isOutput = true;
if (ct.cell_known(cell->type)) {
isInput = ct.cell_input(cell->type, conn.first);
isOutput = ct.cell_output(cell->type, conn.first);
}
RTLIL::SigSpec sig = selectedSignals.extract(sigmap(conn.second));
sig.sort_and_unify();
if (isInput)
inputSignals.append(sig);
if (isOutput)
outputSignals.append(sig);
}
inputSignals.sort_and_unify();
outputSignals.sort_and_unify();
cellToPrevSig[cell] = inputSignals;
cellToNextSig[cell] = outputSignals;
sigToNextCells.insert(inputSignals, cell);
}
for (auto cell : workQueue)
{
cellToNextCell[cell] = sigToNextCells.find(cellToNextSig[cell]);
if (!nofeedbackMode && cellToNextCell[cell].count(cell)) {
log("Found an SCC:");
std::set<RTLIL::Cell*> scc;
log(" %s", RTLIL::id2cstr(cell->name));
cell2scc[cell] = sccList.size();
scc.insert(cell);
sccList.push_back(scc);
log("\n");
}
}
labelCounter = 0;
cellLabels.clear();
while (!workQueue.empty())
{
RTLIL::Cell *cell = *workQueue.begin();
log_assert(cellStack.size() == 0);
cellDepth.clear();
run(cell, 0, maxDepth);
}
log("Found %d SCCs in module %s.\n", int(sccList.size()), RTLIL::id2cstr(module->name));
}
void select(RTLIL::Selection &sel)
{
for (int i = 0; i < int(sccList.size()); i++)
{
std::set<RTLIL::Cell*> &cells = sccList[i];
RTLIL::SigSpec prevsig, nextsig, sig;
for (auto cell : cells) {
sel.selected_members[module->name].insert(cell->name);
prevsig.append(cellToPrevSig[cell]);
nextsig.append(cellToNextSig[cell]);
}
prevsig.sort_and_unify();
nextsig.sort_and_unify();
sig = prevsig.extract(nextsig);
for (auto &chunk : sig.chunks())
if (chunk.wire != NULL)
sel.selected_members[module->name].insert(chunk.wire->name);
}
}
};
struct SccPass : public Pass {
SccPass() : Pass("scc", "detect strongly connected components (logic loops)") { }
void help() YS_OVERRIDE
{
// |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
log("\n");
log(" scc [options] [selection]\n");
log("\n");
log("This command identifies strongly connected components (aka logic loops) in the\n");
log("design.\n");
log("\n");
log(" -expect <num>\n");
log(" expect to find exactly <num> SSCs. A different number of SSCs will\n");
log(" produce an error.\n");
log("\n");
log(" -max_depth <num>\n");
log(" limit to loops not longer than the specified number of cells. This\n");
log(" can e.g. be useful in identifying small local loops in a module that\n");
log(" implements one large SCC.\n");
log("\n");
log(" -nofeedback\n");
log(" do not count cells that have their output fed back into one of their\n");
log(" inputs as single-cell scc.\n");
log("\n");
log(" -all_cell_types\n");
log(" Usually this command only considers internal non-memory cells. With\n");
log(" this option set, all cells are considered. For unknown cells all ports\n");
log(" are assumed to be bidirectional 'inout' ports.\n");
log("\n");
log(" -set_attr <name> <value>\n");
log(" set the specified attribute on all cells that are part of a logic\n");
log(" loop. the special token {} in the value is replaced with a unique\n");
log(" identifier for the logic loop.\n");
log("\n");
log(" -select\n");
log(" replace the current selection with a selection of all cells and wires\n");
log(" that are part of a found logic loop\n");
log("\n");
}
void execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE
{
std::map<std::string, std::string> setAttr;
bool allCellTypes = false;
bool selectMode = false;
bool nofeedbackMode = false;
int maxDepth = -1;
int expect = -1;
log_header(design, "Executing SCC pass (detecting logic loops).\n");
size_t argidx;
for (argidx = 1; argidx < args.size(); argidx++) {
if (args[argidx] == "-max_depth" && argidx+1 < args.size()) {
maxDepth = atoi(args[++argidx].c_str());
continue;
}
if (args[argidx] == "-expect" && argidx+1 < args.size()) {
expect = atoi(args[++argidx].c_str());
continue;
}
if (args[argidx] == "-nofeedback") {
nofeedbackMode = true;
continue;
}
if (args[argidx] == "-all_cell_types") {
allCellTypes = true;
continue;
}
if (args[argidx] == "-set_attr" && argidx+2 < args.size()) {
setAttr[args[argidx+1]] = args[argidx+2];
argidx += 2;
continue;
}
if (args[argidx] == "-select") {
selectMode = true;
continue;
}
break;
}
int origSelectPos = design->selection_stack.size() - 1;
extra_args(args, argidx, design);
RTLIL::Selection newSelection(false);
int scc_counter = 0;
for (auto &mod_it : design->modules_)
if (design->selected(mod_it.second))
{
SccWorker worker(design, mod_it.second, nofeedbackMode, allCellTypes, maxDepth);
if (!setAttr.empty())
{
for (const auto &cells : worker.sccList)
{
for (auto attr : setAttr)
{
IdString attr_name(RTLIL::escape_id(attr.first));
string attr_valstr = attr.second;
string index = stringf("%d", scc_counter);
for (size_t pos = 0; (pos = attr_valstr.find("{}", pos)) != string::npos; pos += index.size())
attr_valstr.replace(pos, 2, index);
Const attr_value(attr_valstr);
for (auto cell : cells)
cell->attributes[attr_name] = attr_value;
}
scc_counter++;
}
}
else
{
scc_counter += GetSize(worker.sccList);
}
if (selectMode)
worker.select(newSelection);
}
if (expect >= 0) {
if (scc_counter == expect)
log("Found and expected %d SCCs.\n", scc_counter);
else
log_error("Found %d SCCs but expected %d.\n", scc_counter, expect);
} else
log("Found %d SCCs.\n", scc_counter);
if (selectMode) {
log_assert(origSelectPos >= 0);
design->selection_stack[origSelectPos] = newSelection;
design->selection_stack[origSelectPos].optimize(design);
}
}
} SccPass;
PRIVATE_NAMESPACE_END
<commit_msg>scc command to ignore blackboxes<commit_after>/*
* yosys -- Yosys Open SYnthesis Suite
*
* Copyright (C) 2012 Clifford Wolf <[email protected]>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*/
// [[CITE]] Tarjan's strongly connected components algorithm
// Tarjan, R. E. (1972), "Depth-first search and linear graph algorithms", SIAM Journal on Computing 1 (2): 146-160, doi:10.1137/0201010
// http://en.wikipedia.org/wiki/Tarjan's_strongly_connected_components_algorithm
#include "kernel/register.h"
#include "kernel/celltypes.h"
#include "kernel/sigtools.h"
#include "kernel/log.h"
#include <stdlib.h>
#include <stdio.h>
#include <set>
USING_YOSYS_NAMESPACE
PRIVATE_NAMESPACE_BEGIN
struct SccWorker
{
RTLIL::Design *design;
RTLIL::Module *module;
SigMap sigmap;
CellTypes ct;
std::set<RTLIL::Cell*> workQueue;
std::map<RTLIL::Cell*, std::set<RTLIL::Cell*>> cellToNextCell;
std::map<RTLIL::Cell*, RTLIL::SigSpec> cellToPrevSig, cellToNextSig;
std::map<RTLIL::Cell*, std::pair<int, int>> cellLabels;
std::map<RTLIL::Cell*, int> cellDepth;
std::set<RTLIL::Cell*> cellsOnStack;
std::vector<RTLIL::Cell*> cellStack;
int labelCounter;
std::map<RTLIL::Cell*, int> cell2scc;
std::vector<std::set<RTLIL::Cell*>> sccList;
void run(RTLIL::Cell *cell, int depth, int maxDepth)
{
log_assert(workQueue.count(cell) > 0);
workQueue.erase(cell);
cellLabels[cell] = std::pair<int, int>(labelCounter, labelCounter);
labelCounter++;
cellsOnStack.insert(cell);
cellStack.push_back(cell);
if (maxDepth >= 0)
cellDepth[cell] = depth;
for (auto nextCell : cellToNextCell[cell])
if (cellLabels.count(nextCell) == 0) {
run(nextCell, depth+1, maxDepth);
cellLabels[cell].second = min(cellLabels[cell].second, cellLabels[nextCell].second);
} else
if (cellsOnStack.count(nextCell) > 0 && (maxDepth < 0 || cellDepth[nextCell] + maxDepth > depth)) {
cellLabels[cell].second = min(cellLabels[cell].second, cellLabels[nextCell].second);
}
if (cellLabels[cell].first == cellLabels[cell].second)
{
if (cellStack.back() == cell)
{
cellStack.pop_back();
cellsOnStack.erase(cell);
}
else
{
log("Found an SCC:");
std::set<RTLIL::Cell*> scc;
while (cellsOnStack.count(cell) > 0) {
RTLIL::Cell *c = cellStack.back();
cellStack.pop_back();
cellsOnStack.erase(c);
log(" %s", RTLIL::id2cstr(c->name));
cell2scc[c] = sccList.size();
scc.insert(c);
}
sccList.push_back(scc);
log("\n");
}
}
}
SccWorker(RTLIL::Design *design, RTLIL::Module *module, bool nofeedbackMode, bool allCellTypes, int maxDepth) :
design(design), module(module), sigmap(module)
{
if (module->processes.size() > 0) {
log("Skipping module %s as it contains processes (run 'proc' pass first).\n", module->name.c_str());
return;
}
if (allCellTypes) {
ct.setup(design);
} else {
ct.setup_internals();
ct.setup_stdcells();
}
SigPool selectedSignals;
SigSet<RTLIL::Cell*> sigToNextCells;
for (auto &it : module->wires_)
if (design->selected(module, it.second))
selectedSignals.add(sigmap(RTLIL::SigSpec(it.second)));
for (auto &it : module->cells_)
{
RTLIL::Cell *cell = it.second;
if (!design->selected(module, cell))
continue;
if (!allCellTypes && !ct.cell_known(cell->type))
continue;
workQueue.insert(cell);
RTLIL::SigSpec inputSignals, outputSignals;
for (auto &conn : cell->connections())
{
bool isInput = true, isOutput = true;
if (ct.cell_known(cell->type)) {
isInput = ct.cell_input(cell->type, conn.first);
isOutput = ct.cell_output(cell->type, conn.first);
}
RTLIL::SigSpec sig = selectedSignals.extract(sigmap(conn.second));
sig.sort_and_unify();
if (isInput)
inputSignals.append(sig);
if (isOutput)
outputSignals.append(sig);
}
inputSignals.sort_and_unify();
outputSignals.sort_and_unify();
cellToPrevSig[cell] = inputSignals;
cellToNextSig[cell] = outputSignals;
sigToNextCells.insert(inputSignals, cell);
}
for (auto cell : workQueue)
{
cellToNextCell[cell] = sigToNextCells.find(cellToNextSig[cell]);
if (!nofeedbackMode && cellToNextCell[cell].count(cell)) {
log("Found an SCC:");
std::set<RTLIL::Cell*> scc;
log(" %s", RTLIL::id2cstr(cell->name));
cell2scc[cell] = sccList.size();
scc.insert(cell);
sccList.push_back(scc);
log("\n");
}
}
labelCounter = 0;
cellLabels.clear();
while (!workQueue.empty())
{
RTLIL::Cell *cell = *workQueue.begin();
log_assert(cellStack.size() == 0);
cellDepth.clear();
run(cell, 0, maxDepth);
}
log("Found %d SCCs in module %s.\n", int(sccList.size()), RTLIL::id2cstr(module->name));
}
void select(RTLIL::Selection &sel)
{
for (int i = 0; i < int(sccList.size()); i++)
{
std::set<RTLIL::Cell*> &cells = sccList[i];
RTLIL::SigSpec prevsig, nextsig, sig;
for (auto cell : cells) {
sel.selected_members[module->name].insert(cell->name);
prevsig.append(cellToPrevSig[cell]);
nextsig.append(cellToNextSig[cell]);
}
prevsig.sort_and_unify();
nextsig.sort_and_unify();
sig = prevsig.extract(nextsig);
for (auto &chunk : sig.chunks())
if (chunk.wire != NULL)
sel.selected_members[module->name].insert(chunk.wire->name);
}
}
};
struct SccPass : public Pass {
SccPass() : Pass("scc", "detect strongly connected components (logic loops)") { }
void help() YS_OVERRIDE
{
// |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
log("\n");
log(" scc [options] [selection]\n");
log("\n");
log("This command identifies strongly connected components (aka logic loops) in the\n");
log("design.\n");
log("\n");
log(" -expect <num>\n");
log(" expect to find exactly <num> SSCs. A different number of SSCs will\n");
log(" produce an error.\n");
log("\n");
log(" -max_depth <num>\n");
log(" limit to loops not longer than the specified number of cells. This\n");
log(" can e.g. be useful in identifying small local loops in a module that\n");
log(" implements one large SCC.\n");
log("\n");
log(" -nofeedback\n");
log(" do not count cells that have their output fed back into one of their\n");
log(" inputs as single-cell scc.\n");
log("\n");
log(" -all_cell_types\n");
log(" Usually this command only considers internal non-memory cells. With\n");
log(" this option set, all cells are considered. For unknown cells all ports\n");
log(" are assumed to be bidirectional 'inout' ports.\n");
log("\n");
log(" -set_attr <name> <value>\n");
log(" set the specified attribute on all cells that are part of a logic\n");
log(" loop. the special token {} in the value is replaced with a unique\n");
log(" identifier for the logic loop.\n");
log("\n");
log(" -select\n");
log(" replace the current selection with a selection of all cells and wires\n");
log(" that are part of a found logic loop\n");
log("\n");
}
void execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE
{
std::map<std::string, std::string> setAttr;
bool allCellTypes = false;
bool selectMode = false;
bool nofeedbackMode = false;
int maxDepth = -1;
int expect = -1;
log_header(design, "Executing SCC pass (detecting logic loops).\n");
size_t argidx;
for (argidx = 1; argidx < args.size(); argidx++) {
if (args[argidx] == "-max_depth" && argidx+1 < args.size()) {
maxDepth = atoi(args[++argidx].c_str());
continue;
}
if (args[argidx] == "-expect" && argidx+1 < args.size()) {
expect = atoi(args[++argidx].c_str());
continue;
}
if (args[argidx] == "-nofeedback") {
nofeedbackMode = true;
continue;
}
if (args[argidx] == "-all_cell_types") {
allCellTypes = true;
continue;
}
if (args[argidx] == "-set_attr" && argidx+2 < args.size()) {
setAttr[args[argidx+1]] = args[argidx+2];
argidx += 2;
continue;
}
if (args[argidx] == "-select") {
selectMode = true;
continue;
}
break;
}
int origSelectPos = design->selection_stack.size() - 1;
extra_args(args, argidx, design);
RTLIL::Selection newSelection(false);
int scc_counter = 0;
for (auto mod : design->modules())
if (!mod->get_blackbox_attribute() && design->selected(mod))
{
SccWorker worker(design, mod, nofeedbackMode, allCellTypes, maxDepth);
if (!setAttr.empty())
{
for (const auto &cells : worker.sccList)
{
for (auto attr : setAttr)
{
IdString attr_name(RTLIL::escape_id(attr.first));
string attr_valstr = attr.second;
string index = stringf("%d", scc_counter);
for (size_t pos = 0; (pos = attr_valstr.find("{}", pos)) != string::npos; pos += index.size())
attr_valstr.replace(pos, 2, index);
Const attr_value(attr_valstr);
for (auto cell : cells)
cell->attributes[attr_name] = attr_value;
}
scc_counter++;
}
}
else
{
scc_counter += GetSize(worker.sccList);
}
if (selectMode)
worker.select(newSelection);
}
if (expect >= 0) {
if (scc_counter == expect)
log("Found and expected %d SCCs.\n", scc_counter);
else
log_error("Found %d SCCs but expected %d.\n", scc_counter, expect);
} else
log("Found %d SCCs.\n", scc_counter);
if (selectMode) {
log_assert(origSelectPos >= 0);
design->selection_stack[origSelectPos] = newSelection;
design->selection_stack[origSelectPos].optimize(design);
}
}
} SccPass;
PRIVATE_NAMESPACE_END
<|endoftext|> |
<commit_before>#include <fstream>
#include <iostream>
#include <string>
#include <cstring>
#include <vector>
#include "token.h"
#include "token_exception.h"
#include "tokenreader.h"
using namespace std;
/* tokenreader reads a file formatted with s-expressions. examples:
* (hello)
* (hello world)
* (hello "world")
* (hello (world))
* (hello (world hi))
*/
TokenReader::TokenReader( const char * file ){
ifile.open( file );
myfile = string( file );
ifile >> noskipws;
// cout<<"Opened "<<file<<endl;
}
TokenReader::TokenReader( const string & file ){
ifile.open( file.c_str() );
myfile = file;
ifile >> noskipws;
}
TokenReader::~TokenReader(){
ifile.close();
/* tokenreader giveth, and tokenreader taketh */
for ( vector< Token * >::iterator it = my_tokens.begin(); it != my_tokens.end(); it++ ){
delete *it;
}
}
Token * TokenReader::readToken() throw( TokenException ){
if ( !ifile ){
throw TokenException( string("Could not open ") + myfile );
}
// Token * t;
// string token_string;
char open_paren = 'x';
int parens = 1;
while ( ifile.good() && open_paren != '(' ){
ifile >> open_paren;
}
// token_string += '(';
Token * cur_token = new Token();
cur_token->setFile( myfile );
my_tokens.push_back( cur_token );
Token * first = cur_token;
vector< Token * > token_stack;
token_stack.push_back( cur_token );
char n;
string cur_string = "";
// while ( parens != 0 ){
/* in_quote is true if a " is read and before another " is read */
bool in_quote = false;
/* escaped unconditionally adds the next character to the string */
bool escaped = false;
while ( !token_stack.empty() ){
if ( !ifile ){
cout<<__FILE__<<": "<<myfile<<" is bad. Open parens "<<parens<<endl;
// cout<<"Dump: "<< token_string << "Last token = [" << n << "]" << (int)n << endl;
first->print( " " );
throw TokenException("Wrong number of parentheses");
}
// char n;
// slow as we go
ifile >> n;
const char * alpha = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789./-_!";
const char * nonalpha = " ;()#\"";
// cout<<"Alpha char: "<<n<<endl;
if ( escaped ){
switch (n){
case 'n' : {
cur_string += "\n";
break;
}
default : {
cur_string += n;
break;
}
}
escaped = false;
continue;
}
if ( n == '\\' ){
escaped = true;
continue;
}
if ( in_quote ){
if ( n == '"' ){
in_quote = false;
Token * sub = new Token( cur_string, false );
sub->setParent( cur_token );
cur_token->addToken( sub );
cur_string = "";
} else
cur_string += n;
} else {
if ( n == '"' )
in_quote = true;
if ( strchr( alpha, n ) != NULL ){
cur_string += n;
} else if ( cur_string != "" && strchr( nonalpha, n ) != NULL ){
// cout<<"Made new token "<<cur_string<<endl;
Token * sub = new Token( cur_string, false );
sub->setParent( cur_token );
cur_token->addToken( sub );
cur_string = "";
}
}
if ( n == '#' || n == ';' ){
while ( n != '\n' && !ifile.eof() ){
ifile >> n;
}
continue;
} else if ( n == '(' ){
Token * another = new Token();
another->setParent( cur_token );
cur_token->addToken( another );
cur_token = another;
token_stack.push_back( cur_token );
/*
parens++;
cout<<"Inc Parens is "<<parens<<endl;
*/
} else if ( n == ')' ){
if ( token_stack.empty() ){
cout<<"Stack is empty"<<endl;
throw TokenException("Stack is empty");
}
token_stack.pop_back();
if ( ! token_stack.empty() ){
cur_token = token_stack.back();
}
}
}
// first->print("");
first->finalize();
return first;
}
<commit_msg>ignore tokens with ;@ or #@<commit_after>#include <fstream>
#include <iostream>
#include <string>
#include <cstring>
#include <vector>
#include "token.h"
#include "token_exception.h"
#include "tokenreader.h"
using namespace std;
/* tokenreader reads a file formatted with s-expressions. examples:
* (hello)
* (hello world)
* (hello "world")
* (hello (world))
* (hello (world hi))
*/
TokenReader::TokenReader( const char * file ){
ifile.open( file );
myfile = string( file );
ifile >> noskipws;
// cout<<"Opened "<<file<<endl;
}
TokenReader::TokenReader( const string & file ){
ifile.open( file.c_str() );
myfile = file;
ifile >> noskipws;
}
TokenReader::~TokenReader(){
ifile.close();
/* tokenreader giveth, and tokenreader taketh */
for ( vector< Token * >::iterator it = my_tokens.begin(); it != my_tokens.end(); it++ ){
delete *it;
}
}
Token * TokenReader::readToken() throw( TokenException ){
if ( !ifile ){
throw TokenException( string("Could not open ") + myfile );
}
// Token * t;
// string token_string;
char open_paren = 'x';
int parens = 1;
while ( ifile.good() && open_paren != '(' ){
ifile >> open_paren;
}
// token_string += '(';
Token * cur_token = new Token();
cur_token->setFile( myfile );
my_tokens.push_back( cur_token );
Token * first = cur_token;
vector< Token * > token_stack;
/* tokens that were ignored using ;@, and should be deleted */
vector<Token*> ignore_list;
token_stack.push_back( cur_token );
/* when a ;@ is seen, read the next s-expression but throw it away */
bool do_ignore = false;
char n;
string cur_string = "";
// while ( parens != 0 ){
/* in_quote is true if a " is read and before another " is read */
bool in_quote = false;
/* escaped unconditionally adds the next character to the string */
bool escaped = false;
while ( !token_stack.empty() ){
if ( !ifile ){
cout<<__FILE__<<": "<<myfile<<" is bad. Open parens "<<parens<<endl;
// cout<<"Dump: "<< token_string << "Last token = [" << n << "]" << (int)n << endl;
first->print( " " );
throw TokenException("Wrong number of parentheses");
}
// char n;
// slow as we go
ifile >> n;
const char * alpha = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789./-_!";
const char * nonalpha = " ;()#\"";
// cout<<"Alpha char: "<<n<<endl;
if ( escaped ){
switch (n){
case 'n' : {
cur_string += "\n";
break;
}
default : {
cur_string += n;
break;
}
}
escaped = false;
continue;
}
if ( n == '\\' ){
escaped = true;
continue;
}
if ( in_quote ){
if ( n == '"' ){
in_quote = false;
Token * sub = new Token( cur_string, false );
sub->setParent( cur_token );
if (do_ignore){
ignore_list.push_back(sub);
do_ignore = false;
} else {
cur_token->addToken( sub );
}
cur_string = "";
} else
cur_string += n;
} else {
if ( n == '"' )
in_quote = true;
if ( strchr( alpha, n ) != NULL ){
cur_string += n;
} else if ( cur_string != "" && strchr( nonalpha, n ) != NULL ){
// cout<<"Made new token "<<cur_string<<endl;
Token * sub = new Token( cur_string, false );
sub->setParent( cur_token );
if (do_ignore){
do_ignore = false;
ignore_list.push_back(sub);
} else {
cur_token->addToken( sub );
}
cur_string = "";
}
}
if ( n == '#' || n == ';' ){
ifile >> n;
if (n == '@'){
do_ignore = true;
} else {
while ( n != '\n' && !ifile.eof() ){
ifile >> n;
}
continue;
}
} else if ( n == '(' ){
Token * another = new Token();
another->setParent( cur_token );
if (do_ignore){
ignore_list.push_back(another);
do_ignore = false;
} else {
cur_token->addToken(another);
}
cur_token = another;
token_stack.push_back( cur_token );
/*
parens++;
cout<<"Inc Parens is "<<parens<<endl;
*/
} else if ( n == ')' ){
if ( token_stack.empty() ){
cout<<"Stack is empty"<<endl;
throw TokenException("Stack is empty");
}
token_stack.pop_back();
if ( ! token_stack.empty() ){
cur_token = token_stack.back();
}
}
}
for (vector<Token*>::iterator it = ignore_list.begin(); it != ignore_list.end(); it++){
delete (*it);
}
// first->print("");
first->finalize();
return first;
}
<|endoftext|> |
<commit_before>//******************************************************************
//
// Copyright 2015 Samsung Electronics All Rights Reserved.
//
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
#include <iostream>
#include <functional>
#include "mutex"
#include "condition_variable"
#include "RCSDiscoveryManager.h"
#include "RCSRemoteResourceObject.h"
#include "RCSResourceAttributes.h"
#include "RCSAddress.h"
#include "OCPlatform.h"
using namespace OC;
using namespace OIC::Service;
constexpr int CORRECT_INPUT = 1;
constexpr int INCORRECT_INPUT = 2;
constexpr int QUIT_INPUT = 3;
constexpr int REQUEST_TEMP = 1;
constexpr int REQUEST_LIGHT = 2;
std::unique_ptr<RCSDiscoveryTask> discoveryTask = nullptr;
std::shared_ptr<RCSRemoteResourceObject> resource;
std::string defaultKey = "Temperature";
const std::string relativeUri = OC_RSRVD_WELL_KNOWN_URI;
const std::string multicastAdd = "multi";
std::mutex mtx;
std::condition_variable cond;
void startMonitoring();
void startMonitoring();
void stopMonitoring();
void getAttributeFromRemoteServer();
void setAttributeToRemoteServer();
void startCachingWithoutCallback();
void startCachingWithCallback();
void getResourceCacheState();
void getCachedAttributes();
void getCachedAttribute();
void stopCaching();
void discoverResource();
void cancelDiscovery();
int processUserInput();
enum Menu
{
START_MONITORING = 1,
STOP_MONITORING,
GET_ATTRIBUTE,
SET_ATTRIBUTE,
START_CACHING_NO_UPDATE,
START_CACHING_UPDATE,
GET_RESOURCE_CACHE_STATE,
GET_CACHED_ATTRIBUTES,
GET_CACHED_ATTRIBUTE,
STOP_CACHING,
DISCOVERY_RESOURCE,
CANCEL_DISCOVERY,
QUIT,
END_OF_MENU
};
typedef void(*ClientMenuHandler)();
typedef int ReturnValue;
struct ClientMenu
{
Menu m_menu;
ClientMenuHandler m_handler;
ReturnValue m_result;
};
ClientMenu clientMenu[] = {
{Menu::START_MONITORING, startMonitoring, CORRECT_INPUT},
{Menu::STOP_MONITORING, stopMonitoring, CORRECT_INPUT},
{Menu::GET_ATTRIBUTE, getAttributeFromRemoteServer, CORRECT_INPUT},
{Menu::SET_ATTRIBUTE, setAttributeToRemoteServer, CORRECT_INPUT},
{Menu::START_CACHING_NO_UPDATE, startCachingWithoutCallback, CORRECT_INPUT},
{Menu::START_CACHING_UPDATE, startCachingWithCallback, CORRECT_INPUT},
{Menu::GET_RESOURCE_CACHE_STATE, getResourceCacheState, CORRECT_INPUT},
{Menu::GET_CACHED_ATTRIBUTES, getCachedAttributes, CORRECT_INPUT},
{Menu::GET_CACHED_ATTRIBUTE, getCachedAttribute, CORRECT_INPUT},
{Menu::STOP_CACHING, stopCaching, CORRECT_INPUT},
{Menu::DISCOVERY_RESOURCE, discoverResource, CORRECT_INPUT},
{Menu::CANCEL_DISCOVERY, cancelDiscovery, CORRECT_INPUT},
{Menu::QUIT, [](){}, QUIT_INPUT},
{Menu::END_OF_MENU, nullptr, INCORRECT_INPUT}
};
void onResourceDiscovered(std::shared_ptr<RCSRemoteResourceObject> discoveredResource)
{
std::cout << "onResourceDiscovered callback :: " << std::endl;
std::string resourceURI = discoveredResource->getUri();
std::string hostAddress = discoveredResource->getAddress();
std::cout << resourceURI << std::endl;
std::cout << hostAddress << std::endl;
resource = discoveredResource;
}
void onResourceStateChanged(const ResourceState& resourceState)
{
std::cout << "onResourceStateChanged callback" << std::endl;
switch(resourceState)
{
case ResourceState::NONE:
std::cout << "\tState changed to : NOT_MONITORING" << std::endl;
break;
case ResourceState::ALIVE:
std::cout << "\tState changed to : ALIVE" << std::endl;
break;
case ResourceState::REQUESTED:
std::cout << "\tState changed to : REQUESTED" << std::endl;
break;
case ResourceState::LOST_SIGNAL:
std::cout << "\tState changed to : LOST_SIGNAL" << std::endl;
resource = nullptr;
break;
case ResourceState::DESTROYED:
std::cout << "\tState changed to : DESTROYED" << std::endl;
break;
}
}
void onCacheUpdated(const RCSResourceAttributes& attributes)
{
std::cout << "onCacheUpdated callback" << std::endl;
if (attributes.empty())
{
std::cout << "\tAttribute is Empty" << std::endl;
return;
}
for(const auto& attr : attributes)
{
std::cout << "\tkey : " << attr.key() << std::endl
<< "\tvalue : " << attr.value().toString() << std::endl;
}
}
void onRemoteAttributesReceivedCallback(const RCSResourceAttributes& attributes)
{
std::cout << "onRemoteAttributesReceivedCallback callback" << std::endl;
if (attributes.empty())
{
std::cout << "\tAttribute is Empty" << std::endl;
return;
}
for(const auto& attr : attributes)
{
std::cout << "\tkey : " << attr.key() << std::endl
<< "\tvalue : " << attr.value().toString() << std::endl;
}
}
void displayMenu()
{
std::cout << std::endl;
std::cout << "1 :: Start Monitoring" << std::endl;
std::cout << "2 :: Stop Monitoring" << std::endl;
std::cout << "3 :: Get Attribute" << std::endl;
std::cout << "4 :: Set Attribute" << std::endl;
std::cout << "5 :: Start Caching (No update to Application)" << std::endl;
std::cout << "6 :: Start Caching (Update the application when data change)"<< std::endl;
std::cout << "7 :: Get Resource cache State" << std::endl;
std::cout << "8 :: Get Cached Attributes" << std::endl;
std::cout << "9 :: Get Cached Attribute" << std::endl;
std::cout << "10 :: Stop Caching" << std::endl;
std::cout << "11 :: Discover Resource" << std::endl;
std::cout << "12 :: Cancel Discovery" << std::endl;
std::cout << "13 :: Stop Server" << std::endl;
}
int processUserInput()
{
int userInput;
std::cin >> userInput;
if (std::cin.fail())
{
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
return -1;
}
return userInput;
}
void startMonitoring()
{
if (!resource->isMonitoring())
{
resource->startMonitoring(&onResourceStateChanged);
std::cout << "\tHosting Started..." << std::endl;
}
else
{
std::cout << "\tAlready Started..." << std::endl;
}
}
void stopMonitoring()
{
if (resource->isMonitoring())
{
resource->stopMonitoring();
std::cout << "\tHosting stopped..." << std::endl;
}
else
{
std::cout << "\tHosting not started..." << std::endl;
}
}
void getAttributeFromRemoteServer()
{
resource->getRemoteAttributes(&onRemoteAttributesReceivedCallback);
}
void setAttributeToRemoteServer()
{
std::string key;
int value;
RCSResourceAttributes setAttribute;
std::cout << "\tEnter the Key you want to set : ";
std::cin >> key;
std::cout << "\tEnter the value you want to set :";
std::cin >> value;
setAttribute[key] = value;
resource->setRemoteAttributes(setAttribute,
&onRemoteAttributesReceivedCallback);
}
void startCaching(std::function <void (const RCSResourceAttributes&)>cb)
{
if (!resource->isCaching())
{
if(cb) resource->startCaching(&onCacheUpdated);
else resource->startCaching();
std::cout << "\tCaching Started..." << std::endl;
}
else
{
std::cout << "\tAlready Started Caching..." << std::endl;
}
}
void startCachingWithoutCallback()
{
startCaching(nullptr);
}
void startCachingWithCallback()
{
startCaching(onCacheUpdated);
}
void getResourceCacheState()
{
switch(resource->getCacheState())
{
case CacheState::READY:
std::cout << "\tCurrent Cache State : " << "CACHE_STATE ::READY" << std::endl;
break;
case CacheState::UNREADY:
std::cout << "\tCurrent Cache State : " << "CACHE_STATE ::UNREADY" << std::endl;
break;
case CacheState::LOST_SIGNAL:
std::cout << "\tCurrent Cache State : " << "CACHE_STATE ::LOST_SIGNAL" << std::endl;
break;
case CacheState::NONE:
std::cout << "\tCurrent Cache State : " << "CACHE_STATE ::NONE" << std::endl;
break;
default:
break;
}
}
void getCachedAttributes()
{
try
{
if (resource->getCachedAttributes().empty())
{
std::cout << "\tReceived cached attribute is empty" << std::endl;
}
else
{
for(const auto& attr : resource->getCachedAttributes())
{
std::cout << "\tkey : " << attr.key() << std::endl
<< "\tvalue : " << attr.value().toString() << std::endl;
}
}
}
catch (const BadRequestException& e)
{
std::cout << "Exception in getCachedAttributes : " << e.what() << std::endl;
}
}
void getCachedAttribute()
{
try
{
std::cout << "\tkey : " << defaultKey << std::endl
<< "\tvalue : " << resource->getCachedAttribute(defaultKey).get< int >()
<< std::endl;
}
catch (const BadRequestException& e)
{
std::cout << "Exception in getCachedAttribute : " << e.what() << std::endl;
}
catch (const BadGetException& e)
{
std::cout << "Exception in getCachedAttribute : " << e.what() << std::endl;
}
}
void stopCaching()
{
if(resource->isCaching())
{
resource->stopCaching();
std::cout << "\tCaching stopped..." << std::endl;
}
else
{
std::cout << "\tCaching not started..." << std::endl;
}
}
int selectClientMenu(int selectedMenu)
{
for(int i = 0; clientMenu[i].m_menu != Menu::END_OF_MENU; i++)
{
if(clientMenu[i].m_menu == selectedMenu)
{
clientMenu[i].m_handler();
return clientMenu[i].m_result;
}
}
std::cout << "Invalid input, please try again" << std::endl;
return INCORRECT_INPUT;
}
void process()
{
while(true)
{
displayMenu();
if(selectClientMenu(processUserInput()) == QUIT_INPUT) break;
}
}
void platFormConfigure()
{
PlatformConfig config
{
OC::ServiceType::InProc, ModeType::Client, "0.0.0.0", 0, OC::QualityOfService::LowQos
};
OCPlatform::Configure(config);
}
void discoverResource()
{
std::string resourceType;
std::cout << "========================================================" << std::endl;
std::cout << "1. Temperature Resource Discovery" << std::endl;
std::cout << "2. Light Resource Discovery" << std::endl;
std::cout << "========================================================" << std::endl;
switch (processUserInput())
{
case REQUEST_TEMP:
resourceType = "core.TemperatureSensor";
break;
case REQUEST_LIGHT:
resourceType = "core.light";
defaultKey = "Light";
break;
default :
std::cout << "Invalid input, please try again" << std::endl;
return;
}
std::string addressInput;
std::cout << "========================================================" << std::endl;
std::cout << "Please input address" << std::endl;
std::cout << "(want to use multicast -> please input 'multi')" << std::endl;
std::cout << "========================================================" << std::endl;
std::cin >> addressInput;
if(addressInput == multicastAdd)
{
discoveryTask = RCSDiscoveryManager::getInstance()->discoverResourceByType(RCSAddress::multicast(),
relativeUri, resourceType, &onResourceDiscovered);
}
else
{
discoveryTask = RCSDiscoveryManager::getInstance()->discoverResourceByType(RCSAddress::unicast
(addressInput), relativeUri, resourceType, &onResourceDiscovered);
}
}
void cancelDiscovery()
{
if(!discoveryTask)
{
std::cout << "There isn't discovery request..." << std::endl;
return;
}
discoveryTask->cancel();
}
int main()
{
platFormConfigure();
try
{
process();
}
catch (const std::exception& e)
{
std::cout << "main exception : " << e.what() << std::endl;
}
std::cout << "Stopping the Client" << std::endl;
return 0;
}
<commit_msg>Adding scope to RCSDiscoveryTask<commit_after>//******************************************************************
//
// Copyright 2015 Samsung Electronics All Rights Reserved.
//
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
#include <iostream>
#include <functional>
#include "mutex"
#include "condition_variable"
#include "RCSDiscoveryManager.h"
#include "RCSRemoteResourceObject.h"
#include "RCSResourceAttributes.h"
#include "RCSAddress.h"
#include "OCPlatform.h"
using namespace OC;
using namespace OIC::Service;
constexpr int CORRECT_INPUT = 1;
constexpr int INCORRECT_INPUT = 2;
constexpr int QUIT_INPUT = 3;
constexpr int REQUEST_TEMP = 1;
constexpr int REQUEST_LIGHT = 2;
std::unique_ptr<RCSDiscoveryManager::DiscoveryTask> discoveryTask = nullptr;
std::shared_ptr<RCSRemoteResourceObject> resource;
std::string defaultKey = "Temperature";
const std::string relativeUri = OC_RSRVD_WELL_KNOWN_URI;
const std::string multicastAdd = "multi";
std::mutex mtx;
std::condition_variable cond;
void startMonitoring();
void startMonitoring();
void stopMonitoring();
void getAttributeFromRemoteServer();
void setAttributeToRemoteServer();
void startCachingWithoutCallback();
void startCachingWithCallback();
void getResourceCacheState();
void getCachedAttributes();
void getCachedAttribute();
void stopCaching();
void discoverResource();
void cancelDiscovery();
int processUserInput();
enum Menu
{
START_MONITORING = 1,
STOP_MONITORING,
GET_ATTRIBUTE,
SET_ATTRIBUTE,
START_CACHING_NO_UPDATE,
START_CACHING_UPDATE,
GET_RESOURCE_CACHE_STATE,
GET_CACHED_ATTRIBUTES,
GET_CACHED_ATTRIBUTE,
STOP_CACHING,
DISCOVERY_RESOURCE,
CANCEL_DISCOVERY,
QUIT,
END_OF_MENU
};
typedef void(*ClientMenuHandler)();
typedef int ReturnValue;
struct ClientMenu
{
Menu m_menu;
ClientMenuHandler m_handler;
ReturnValue m_result;
};
ClientMenu clientMenu[] = {
{Menu::START_MONITORING, startMonitoring, CORRECT_INPUT},
{Menu::STOP_MONITORING, stopMonitoring, CORRECT_INPUT},
{Menu::GET_ATTRIBUTE, getAttributeFromRemoteServer, CORRECT_INPUT},
{Menu::SET_ATTRIBUTE, setAttributeToRemoteServer, CORRECT_INPUT},
{Menu::START_CACHING_NO_UPDATE, startCachingWithoutCallback, CORRECT_INPUT},
{Menu::START_CACHING_UPDATE, startCachingWithCallback, CORRECT_INPUT},
{Menu::GET_RESOURCE_CACHE_STATE, getResourceCacheState, CORRECT_INPUT},
{Menu::GET_CACHED_ATTRIBUTES, getCachedAttributes, CORRECT_INPUT},
{Menu::GET_CACHED_ATTRIBUTE, getCachedAttribute, CORRECT_INPUT},
{Menu::STOP_CACHING, stopCaching, CORRECT_INPUT},
{Menu::DISCOVERY_RESOURCE, discoverResource, CORRECT_INPUT},
{Menu::CANCEL_DISCOVERY, cancelDiscovery, CORRECT_INPUT},
{Menu::QUIT, [](){}, QUIT_INPUT},
{Menu::END_OF_MENU, nullptr, INCORRECT_INPUT}
};
void onResourceDiscovered(std::shared_ptr<RCSRemoteResourceObject> discoveredResource)
{
std::cout << "onResourceDiscovered callback :: " << std::endl;
std::string resourceURI = discoveredResource->getUri();
std::string hostAddress = discoveredResource->getAddress();
std::cout << resourceURI << std::endl;
std::cout << hostAddress << std::endl;
resource = discoveredResource;
}
void onResourceStateChanged(const ResourceState& resourceState)
{
std::cout << "onResourceStateChanged callback" << std::endl;
switch(resourceState)
{
case ResourceState::NONE:
std::cout << "\tState changed to : NOT_MONITORING" << std::endl;
break;
case ResourceState::ALIVE:
std::cout << "\tState changed to : ALIVE" << std::endl;
break;
case ResourceState::REQUESTED:
std::cout << "\tState changed to : REQUESTED" << std::endl;
break;
case ResourceState::LOST_SIGNAL:
std::cout << "\tState changed to : LOST_SIGNAL" << std::endl;
resource = nullptr;
break;
case ResourceState::DESTROYED:
std::cout << "\tState changed to : DESTROYED" << std::endl;
break;
}
}
void onCacheUpdated(const RCSResourceAttributes& attributes)
{
std::cout << "onCacheUpdated callback" << std::endl;
if (attributes.empty())
{
std::cout << "\tAttribute is Empty" << std::endl;
return;
}
for(const auto& attr : attributes)
{
std::cout << "\tkey : " << attr.key() << std::endl
<< "\tvalue : " << attr.value().toString() << std::endl;
}
}
void onRemoteAttributesReceivedCallback(const RCSResourceAttributes& attributes)
{
std::cout << "onRemoteAttributesReceivedCallback callback" << std::endl;
if (attributes.empty())
{
std::cout << "\tAttribute is Empty" << std::endl;
return;
}
for(const auto& attr : attributes)
{
std::cout << "\tkey : " << attr.key() << std::endl
<< "\tvalue : " << attr.value().toString() << std::endl;
}
}
void displayMenu()
{
std::cout << std::endl;
std::cout << "1 :: Start Monitoring" << std::endl;
std::cout << "2 :: Stop Monitoring" << std::endl;
std::cout << "3 :: Get Attribute" << std::endl;
std::cout << "4 :: Set Attribute" << std::endl;
std::cout << "5 :: Start Caching (No update to Application)" << std::endl;
std::cout << "6 :: Start Caching (Update the application when data change)"<< std::endl;
std::cout << "7 :: Get Resource cache State" << std::endl;
std::cout << "8 :: Get Cached Attributes" << std::endl;
std::cout << "9 :: Get Cached Attribute" << std::endl;
std::cout << "10 :: Stop Caching" << std::endl;
std::cout << "11 :: Discover Resource" << std::endl;
std::cout << "12 :: Cancel Discovery" << std::endl;
std::cout << "13 :: Stop Server" << std::endl;
}
int processUserInput()
{
int userInput;
std::cin >> userInput;
if (std::cin.fail())
{
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
return -1;
}
return userInput;
}
void startMonitoring()
{
if (!resource->isMonitoring())
{
resource->startMonitoring(&onResourceStateChanged);
std::cout << "\tHosting Started..." << std::endl;
}
else
{
std::cout << "\tAlready Started..." << std::endl;
}
}
void stopMonitoring()
{
if (resource->isMonitoring())
{
resource->stopMonitoring();
std::cout << "\tHosting stopped..." << std::endl;
}
else
{
std::cout << "\tHosting not started..." << std::endl;
}
}
void getAttributeFromRemoteServer()
{
resource->getRemoteAttributes(&onRemoteAttributesReceivedCallback);
}
void setAttributeToRemoteServer()
{
std::string key;
int value;
RCSResourceAttributes setAttribute;
std::cout << "\tEnter the Key you want to set : ";
std::cin >> key;
std::cout << "\tEnter the value you want to set :";
std::cin >> value;
setAttribute[key] = value;
resource->setRemoteAttributes(setAttribute,
&onRemoteAttributesReceivedCallback);
}
void startCaching(std::function <void (const RCSResourceAttributes&)>cb)
{
if (!resource->isCaching())
{
if(cb) resource->startCaching(&onCacheUpdated);
else resource->startCaching();
std::cout << "\tCaching Started..." << std::endl;
}
else
{
std::cout << "\tAlready Started Caching..." << std::endl;
}
}
void startCachingWithoutCallback()
{
startCaching(nullptr);
}
void startCachingWithCallback()
{
startCaching(onCacheUpdated);
}
void getResourceCacheState()
{
switch(resource->getCacheState())
{
case CacheState::READY:
std::cout << "\tCurrent Cache State : " << "CACHE_STATE ::READY" << std::endl;
break;
case CacheState::UNREADY:
std::cout << "\tCurrent Cache State : " << "CACHE_STATE ::UNREADY" << std::endl;
break;
case CacheState::LOST_SIGNAL:
std::cout << "\tCurrent Cache State : " << "CACHE_STATE ::LOST_SIGNAL" << std::endl;
break;
case CacheState::NONE:
std::cout << "\tCurrent Cache State : " << "CACHE_STATE ::NONE" << std::endl;
break;
default:
break;
}
}
void getCachedAttributes()
{
try
{
if (resource->getCachedAttributes().empty())
{
std::cout << "\tReceived cached attribute is empty" << std::endl;
}
else
{
for(const auto& attr : resource->getCachedAttributes())
{
std::cout << "\tkey : " << attr.key() << std::endl
<< "\tvalue : " << attr.value().toString() << std::endl;
}
}
}
catch (const BadRequestException& e)
{
std::cout << "Exception in getCachedAttributes : " << e.what() << std::endl;
}
}
void getCachedAttribute()
{
try
{
std::cout << "\tkey : " << defaultKey << std::endl
<< "\tvalue : " << resource->getCachedAttribute(defaultKey).get< int >()
<< std::endl;
}
catch (const BadRequestException& e)
{
std::cout << "Exception in getCachedAttribute : " << e.what() << std::endl;
}
catch (const BadGetException& e)
{
std::cout << "Exception in getCachedAttribute : " << e.what() << std::endl;
}
}
void stopCaching()
{
if(resource->isCaching())
{
resource->stopCaching();
std::cout << "\tCaching stopped..." << std::endl;
}
else
{
std::cout << "\tCaching not started..." << std::endl;
}
}
int selectClientMenu(int selectedMenu)
{
for(int i = 0; clientMenu[i].m_menu != Menu::END_OF_MENU; i++)
{
if(clientMenu[i].m_menu == selectedMenu)
{
clientMenu[i].m_handler();
return clientMenu[i].m_result;
}
}
std::cout << "Invalid input, please try again" << std::endl;
return INCORRECT_INPUT;
}
void process()
{
while(true)
{
displayMenu();
if(selectClientMenu(processUserInput()) == QUIT_INPUT) break;
}
}
void platFormConfigure()
{
PlatformConfig config
{
OC::ServiceType::InProc, ModeType::Client, "0.0.0.0", 0, OC::QualityOfService::LowQos
};
OCPlatform::Configure(config);
}
void discoverResource()
{
std::string resourceType;
std::cout << "========================================================" << std::endl;
std::cout << "1. Temperature Resource Discovery" << std::endl;
std::cout << "2. Light Resource Discovery" << std::endl;
std::cout << "========================================================" << std::endl;
switch (processUserInput())
{
case REQUEST_TEMP:
resourceType = "core.TemperatureSensor";
break;
case REQUEST_LIGHT:
resourceType = "core.light";
defaultKey = "Light";
break;
default :
std::cout << "Invalid input, please try again" << std::endl;
return;
}
std::string addressInput;
std::cout << "========================================================" << std::endl;
std::cout << "Please input address" << std::endl;
std::cout << "(want to use multicast -> please input 'multi')" << std::endl;
std::cout << "========================================================" << std::endl;
std::cin >> addressInput;
if(addressInput == multicastAdd)
{
discoveryTask = RCSDiscoveryManager::getInstance()->discoverResourceByType(RCSAddress::multicast(),
relativeUri, resourceType, &onResourceDiscovered);
}
else
{
discoveryTask = RCSDiscoveryManager::getInstance()->discoverResourceByType(RCSAddress::unicast
(addressInput), relativeUri, resourceType, &onResourceDiscovered);
}
}
void cancelDiscovery()
{
if(!discoveryTask)
{
std::cout << "There isn't discovery request..." << std::endl;
return;
}
discoveryTask->cancel();
}
int main()
{
platFormConfigure();
try
{
process();
}
catch (const std::exception& e)
{
std::cout << "main exception : " << e.what() << std::endl;
}
std::cout << "Stopping the Client" << std::endl;
return 0;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2018 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <validationinterface.h>
#include <primitives/block.h>
#include <scheduler.h>
#include <txmempool.h>
#include <util/system.h>
#include <validation.h>
#include <list>
#include <atomic>
#include <future>
#include <utility>
#include <boost/signals2/signal.hpp>
struct ValidationInterfaceConnections {
boost::signals2::scoped_connection UpdatedBlockTip;
boost::signals2::scoped_connection TransactionAddedToMempool;
boost::signals2::scoped_connection BlockConnected;
boost::signals2::scoped_connection BlockDisconnected;
boost::signals2::scoped_connection TransactionRemovedFromMempool;
boost::signals2::scoped_connection ChainStateFlushed;
boost::signals2::scoped_connection Broadcast;
boost::signals2::scoped_connection BlockChecked;
boost::signals2::scoped_connection NewPoWValidBlock;
boost::signals2::scoped_connection ProcessModuleMessage;
boost::signals2::scoped_connection NotifyGovernanceObject;
boost::signals2::scoped_connection NotifyGovernanceVote;
};
struct MainSignalsInstance {
boost::signals2::signal<void (const CBlockIndex *, const CBlockIndex *, bool fInitialDownload)> UpdatedBlockTip;
boost::signals2::signal<void (const CTransactionRef &)> TransactionAddedToMempool;
boost::signals2::signal<void (const std::shared_ptr<const CBlock> &, const CBlockIndex *pindex, const std::vector<CTransactionRef>&)> BlockConnected;
boost::signals2::signal<void (const std::shared_ptr<const CBlock> &)> BlockDisconnected;
boost::signals2::signal<void (const CTransactionRef &)> TransactionRemovedFromMempool;
boost::signals2::signal<void (const CBlockLocator &)> ChainStateFlushed;
boost::signals2::signal<void (int64_t nBestBlockTime, CConnman* connman)> Broadcast;
boost::signals2::signal<void (const CBlock&, const CValidationState&)> BlockChecked;
boost::signals2::signal<void (const CBlockIndex *, const std::shared_ptr<const CBlock>&)> NewPoWValidBlock;
boost::signals2::signal<void (CNode*, const std::string&, CDataStream&, CConnman*)> ProcessModuleMessage;
boost::signals2::signal<void (const CGovernanceObject&)> NotifyGovernanceObject;
boost::signals2::signal<void (const CGovernanceVote&)> NotifyGovernanceVote;
// We are not allowed to assume the scheduler only runs in one thread,
// but must ensure all callbacks happen in-order, so we end up creating
// our own queue here :(
SingleThreadedSchedulerClient m_schedulerClient;
std::unordered_map<CValidationInterface*, ValidationInterfaceConnections> m_connMainSignals;
explicit MainSignalsInstance(CScheduler *pscheduler) : m_schedulerClient(pscheduler) {}
};
static CMainSignals g_signals;
// This map has to a separate global instead of a member of MainSignalsInstance,
// because RegisterWithMempoolSignals is currently called before RegisterBackgroundSignalScheduler,
// so MainSignalsInstance hasn't been created yet.
static std::unordered_map<CTxMemPool*, boost::signals2::scoped_connection> g_connNotifyEntryRemoved;
void CMainSignals::RegisterBackgroundSignalScheduler(CScheduler& scheduler) {
assert(!m_internals);
m_internals.reset(new MainSignalsInstance(&scheduler));
}
void CMainSignals::UnregisterBackgroundSignalScheduler() {
m_internals.reset(nullptr);
}
void CMainSignals::FlushBackgroundCallbacks() {
if (m_internals) {
m_internals->m_schedulerClient.EmptyQueue();
}
}
size_t CMainSignals::CallbacksPending() {
if (!m_internals) return 0;
return m_internals->m_schedulerClient.CallbacksPending();
}
void CMainSignals::RegisterWithMempoolSignals(CTxMemPool& pool) {
g_connNotifyEntryRemoved.emplace(std::piecewise_construct,
std::forward_as_tuple(&pool),
std::forward_as_tuple(pool.NotifyEntryRemoved.connect(std::bind(&CMainSignals::MempoolEntryRemoved, this, std::placeholders::_1, std::placeholders::_2)))
);
}
void CMainSignals::UnregisterWithMempoolSignals(CTxMemPool& pool) {
g_connNotifyEntryRemoved.erase(&pool);
}
CMainSignals& GetMainSignals()
{
return g_signals;
}
void RegisterValidationInterface(CValidationInterface* pwalletIn) {
ValidationInterfaceConnections& conns = g_signals.m_internals->m_connMainSignals[pwalletIn];
conns.UpdatedBlockTip = g_signals.m_internals->UpdatedBlockTip.connect(std::bind(&CValidationInterface::UpdatedBlockTip, pwalletIn, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
conns.TransactionAddedToMempool = g_signals.m_internals->TransactionAddedToMempool.connect(std::bind(&CValidationInterface::TransactionAddedToMempool, pwalletIn, std::placeholders::_1));
conns.BlockConnected = g_signals.m_internals->BlockConnected.connect(std::bind(&CValidationInterface::BlockConnected, pwalletIn, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
conns.BlockDisconnected = g_signals.m_internals->BlockDisconnected.connect(std::bind(&CValidationInterface::BlockDisconnected, pwalletIn, std::placeholders::_1));
conns.TransactionRemovedFromMempool = g_signals.m_internals->TransactionRemovedFromMempool.connect(std::bind(&CValidationInterface::TransactionRemovedFromMempool, pwalletIn, std::placeholders::_1));
conns.ChainStateFlushed = g_signals.m_internals->ChainStateFlushed.connect(std::bind(&CValidationInterface::ChainStateFlushed, pwalletIn, std::placeholders::_1));
conns.Broadcast = g_signals.m_internals->Broadcast.connect(std::bind(&CValidationInterface::ResendWalletTransactions, pwalletIn, std::placeholders::_1, std::placeholders::_2));
conns.BlockChecked = g_signals.m_internals->BlockChecked.connect(std::bind(&CValidationInterface::BlockChecked, pwalletIn, std::placeholders::_1, std::placeholders::_2));
conns.NewPoWValidBlock = g_signals.m_internals->NewPoWValidBlock.connect(std::bind(&CValidationInterface::NewPoWValidBlock, pwalletIn, std::placeholders::_1, std::placeholders::_2));
conns.ProcessModuleMessage = g_signals.m_internals->ProcessModuleMessage.connect(std::bind(&CValidationInterface::ProcessModuleMessage, pwalletIn, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4));
conns.NotifyGovernanceObject = g_signals.m_internals->NotifyGovernanceObject.connect(std::bind(&CValidationInterface::NotifyGovernanceObject, pwalletIn, std::placeholders::_1));
conns.NotifyGovernanceVote = g_signals.m_internals->NotifyGovernanceVote.connect(std::bind(&CValidationInterface::NotifyGovernanceVote, pwalletIn, std::placeholders::_1));
}
void UnregisterValidationInterface(CValidationInterface* pwalletIn) {
g_signals.m_internals->m_connMainSignals.erase(pwalletIn);
}
void UnregisterAllValidationInterfaces() {
if (!g_signals.m_internals) {
return;
}
g_signals.m_internals->m_connMainSignals.clear();
}
void CallFunctionInValidationInterfaceQueue(std::function<void ()> func) {
g_signals.m_internals->m_schedulerClient.AddToProcessQueue(std::move(func));
}
void SyncWithValidationInterfaceQueue() {
AssertLockNotHeld(cs_main);
// Block until the validation queue drains
std::promise<void> promise;
CallFunctionInValidationInterfaceQueue([&promise] {
promise.set_value();
});
promise.get_future().wait();
}
void CMainSignals::MempoolEntryRemoved(CTransactionRef ptx, MemPoolRemovalReason reason) {
if (reason != MemPoolRemovalReason::BLOCK && reason != MemPoolRemovalReason::CONFLICT) {
m_internals->m_schedulerClient.AddToProcessQueue([ptx, this] {
m_internals->TransactionRemovedFromMempool(ptx);
});
}
}
void CMainSignals::UpdatedBlockTip(const CBlockIndex *pindexNew, const CBlockIndex *pindexFork, bool fInitialDownload) {
// Dependencies exist that require UpdatedBlockTip events to be delivered in the order in which
// the chain actually updates. One way to ensure this is for the caller to invoke this signal
// in the same critical section where the chain is updated
m_internals->m_schedulerClient.AddToProcessQueue([pindexNew, pindexFork, fInitialDownload, this] {
m_internals->UpdatedBlockTip(pindexNew, pindexFork, fInitialDownload);
});
}
void CMainSignals::TransactionAddedToMempool(const CTransactionRef &ptx) {
m_internals->m_schedulerClient.AddToProcessQueue([ptx, this] {
m_internals->TransactionAddedToMempool(ptx);
});
}
void CMainSignals::BlockConnected(const std::shared_ptr<const CBlock> &pblock, const CBlockIndex *pindex, const std::shared_ptr<const std::vector<CTransactionRef>>& pvtxConflicted) {
m_internals->m_schedulerClient.AddToProcessQueue([pblock, pindex, pvtxConflicted, this] {
m_internals->BlockConnected(pblock, pindex, *pvtxConflicted);
});
}
void CMainSignals::BlockDisconnected(const std::shared_ptr<const CBlock> &pblock) {
m_internals->m_schedulerClient.AddToProcessQueue([pblock, this] {
m_internals->BlockDisconnected(pblock);
});
}
void CMainSignals::ChainStateFlushed(const CBlockLocator &locator) {
m_internals->m_schedulerClient.AddToProcessQueue([locator, this] {
m_internals->ChainStateFlushed(locator);
});
}
void CMainSignals::Broadcast(int64_t nBestBlockTime, CConnman* connman) {
m_internals->Broadcast(nBestBlockTime, connman);
}
void CMainSignals::BlockChecked(const CBlock& block, const CValidationState& state) {
m_internals->BlockChecked(block, state);
}
void CMainSignals::NewPoWValidBlock(const CBlockIndex *pindex, const std::shared_ptr<const CBlock> &block) {
m_internals->NewPoWValidBlock(pindex, block);
}
void CMainSignals::ProcessModuleMessage(CNode* pfrom, const std::string& strCommand, CDataStream& vRecv, CConnman* connman) {
m_internals->ProcessModuleMessage(pfrom, strCommand, vRecv, connman);
}
void CMainSignals::NotifyGovernanceObject(const CGovernanceObject &gobject) {
m_internals->NotifyGovernanceObject(gobject);
}
void CMainSignals::NotifyGovernanceVote(const CGovernanceVote &govote) {
m_internals->NotifyGovernanceVote(govote);
}
<commit_msg>Check m_internals in UnregisterValidationInterface<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2018 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <validationinterface.h>
#include <primitives/block.h>
#include <scheduler.h>
#include <txmempool.h>
#include <util/system.h>
#include <validation.h>
#include <list>
#include <atomic>
#include <future>
#include <utility>
#include <boost/signals2/signal.hpp>
struct ValidationInterfaceConnections {
boost::signals2::scoped_connection UpdatedBlockTip;
boost::signals2::scoped_connection TransactionAddedToMempool;
boost::signals2::scoped_connection BlockConnected;
boost::signals2::scoped_connection BlockDisconnected;
boost::signals2::scoped_connection TransactionRemovedFromMempool;
boost::signals2::scoped_connection ChainStateFlushed;
boost::signals2::scoped_connection Broadcast;
boost::signals2::scoped_connection BlockChecked;
boost::signals2::scoped_connection NewPoWValidBlock;
boost::signals2::scoped_connection ProcessModuleMessage;
boost::signals2::scoped_connection NotifyGovernanceObject;
boost::signals2::scoped_connection NotifyGovernanceVote;
};
struct MainSignalsInstance {
boost::signals2::signal<void (const CBlockIndex *, const CBlockIndex *, bool fInitialDownload)> UpdatedBlockTip;
boost::signals2::signal<void (const CTransactionRef &)> TransactionAddedToMempool;
boost::signals2::signal<void (const std::shared_ptr<const CBlock> &, const CBlockIndex *pindex, const std::vector<CTransactionRef>&)> BlockConnected;
boost::signals2::signal<void (const std::shared_ptr<const CBlock> &)> BlockDisconnected;
boost::signals2::signal<void (const CTransactionRef &)> TransactionRemovedFromMempool;
boost::signals2::signal<void (const CBlockLocator &)> ChainStateFlushed;
boost::signals2::signal<void (int64_t nBestBlockTime, CConnman* connman)> Broadcast;
boost::signals2::signal<void (const CBlock&, const CValidationState&)> BlockChecked;
boost::signals2::signal<void (const CBlockIndex *, const std::shared_ptr<const CBlock>&)> NewPoWValidBlock;
boost::signals2::signal<void (CNode*, const std::string&, CDataStream&, CConnman*)> ProcessModuleMessage;
boost::signals2::signal<void (const CGovernanceObject&)> NotifyGovernanceObject;
boost::signals2::signal<void (const CGovernanceVote&)> NotifyGovernanceVote;
// We are not allowed to assume the scheduler only runs in one thread,
// but must ensure all callbacks happen in-order, so we end up creating
// our own queue here :(
SingleThreadedSchedulerClient m_schedulerClient;
std::unordered_map<CValidationInterface*, ValidationInterfaceConnections> m_connMainSignals;
explicit MainSignalsInstance(CScheduler *pscheduler) : m_schedulerClient(pscheduler) {}
};
static CMainSignals g_signals;
// This map has to a separate global instead of a member of MainSignalsInstance,
// because RegisterWithMempoolSignals is currently called before RegisterBackgroundSignalScheduler,
// so MainSignalsInstance hasn't been created yet.
static std::unordered_map<CTxMemPool*, boost::signals2::scoped_connection> g_connNotifyEntryRemoved;
void CMainSignals::RegisterBackgroundSignalScheduler(CScheduler& scheduler) {
assert(!m_internals);
m_internals.reset(new MainSignalsInstance(&scheduler));
}
void CMainSignals::UnregisterBackgroundSignalScheduler() {
m_internals.reset(nullptr);
}
void CMainSignals::FlushBackgroundCallbacks() {
if (m_internals) {
m_internals->m_schedulerClient.EmptyQueue();
}
}
size_t CMainSignals::CallbacksPending() {
if (!m_internals) return 0;
return m_internals->m_schedulerClient.CallbacksPending();
}
void CMainSignals::RegisterWithMempoolSignals(CTxMemPool& pool) {
g_connNotifyEntryRemoved.emplace(std::piecewise_construct,
std::forward_as_tuple(&pool),
std::forward_as_tuple(pool.NotifyEntryRemoved.connect(std::bind(&CMainSignals::MempoolEntryRemoved, this, std::placeholders::_1, std::placeholders::_2)))
);
}
void CMainSignals::UnregisterWithMempoolSignals(CTxMemPool& pool) {
g_connNotifyEntryRemoved.erase(&pool);
}
CMainSignals& GetMainSignals()
{
return g_signals;
}
void RegisterValidationInterface(CValidationInterface* pwalletIn) {
ValidationInterfaceConnections& conns = g_signals.m_internals->m_connMainSignals[pwalletIn];
conns.UpdatedBlockTip = g_signals.m_internals->UpdatedBlockTip.connect(std::bind(&CValidationInterface::UpdatedBlockTip, pwalletIn, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
conns.TransactionAddedToMempool = g_signals.m_internals->TransactionAddedToMempool.connect(std::bind(&CValidationInterface::TransactionAddedToMempool, pwalletIn, std::placeholders::_1));
conns.BlockConnected = g_signals.m_internals->BlockConnected.connect(std::bind(&CValidationInterface::BlockConnected, pwalletIn, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
conns.BlockDisconnected = g_signals.m_internals->BlockDisconnected.connect(std::bind(&CValidationInterface::BlockDisconnected, pwalletIn, std::placeholders::_1));
conns.TransactionRemovedFromMempool = g_signals.m_internals->TransactionRemovedFromMempool.connect(std::bind(&CValidationInterface::TransactionRemovedFromMempool, pwalletIn, std::placeholders::_1));
conns.ChainStateFlushed = g_signals.m_internals->ChainStateFlushed.connect(std::bind(&CValidationInterface::ChainStateFlushed, pwalletIn, std::placeholders::_1));
conns.Broadcast = g_signals.m_internals->Broadcast.connect(std::bind(&CValidationInterface::ResendWalletTransactions, pwalletIn, std::placeholders::_1, std::placeholders::_2));
conns.BlockChecked = g_signals.m_internals->BlockChecked.connect(std::bind(&CValidationInterface::BlockChecked, pwalletIn, std::placeholders::_1, std::placeholders::_2));
conns.NewPoWValidBlock = g_signals.m_internals->NewPoWValidBlock.connect(std::bind(&CValidationInterface::NewPoWValidBlock, pwalletIn, std::placeholders::_1, std::placeholders::_2));
conns.ProcessModuleMessage = g_signals.m_internals->ProcessModuleMessage.connect(std::bind(&CValidationInterface::ProcessModuleMessage, pwalletIn, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4));
conns.NotifyGovernanceObject = g_signals.m_internals->NotifyGovernanceObject.connect(std::bind(&CValidationInterface::NotifyGovernanceObject, pwalletIn, std::placeholders::_1));
conns.NotifyGovernanceVote = g_signals.m_internals->NotifyGovernanceVote.connect(std::bind(&CValidationInterface::NotifyGovernanceVote, pwalletIn, std::placeholders::_1));
}
void UnregisterValidationInterface(CValidationInterface* pwalletIn) {
if (g_signals.m_internals) {
g_signals.m_internals->m_connMainSignals.erase(pwalletIn);
}
}
void UnregisterAllValidationInterfaces() {
if (!g_signals.m_internals) {
return;
}
g_signals.m_internals->m_connMainSignals.clear();
}
void CallFunctionInValidationInterfaceQueue(std::function<void ()> func) {
g_signals.m_internals->m_schedulerClient.AddToProcessQueue(std::move(func));
}
void SyncWithValidationInterfaceQueue() {
AssertLockNotHeld(cs_main);
// Block until the validation queue drains
std::promise<void> promise;
CallFunctionInValidationInterfaceQueue([&promise] {
promise.set_value();
});
promise.get_future().wait();
}
void CMainSignals::MempoolEntryRemoved(CTransactionRef ptx, MemPoolRemovalReason reason) {
if (reason != MemPoolRemovalReason::BLOCK && reason != MemPoolRemovalReason::CONFLICT) {
m_internals->m_schedulerClient.AddToProcessQueue([ptx, this] {
m_internals->TransactionRemovedFromMempool(ptx);
});
}
}
void CMainSignals::UpdatedBlockTip(const CBlockIndex *pindexNew, const CBlockIndex *pindexFork, bool fInitialDownload) {
// Dependencies exist that require UpdatedBlockTip events to be delivered in the order in which
// the chain actually updates. One way to ensure this is for the caller to invoke this signal
// in the same critical section where the chain is updated
m_internals->m_schedulerClient.AddToProcessQueue([pindexNew, pindexFork, fInitialDownload, this] {
m_internals->UpdatedBlockTip(pindexNew, pindexFork, fInitialDownload);
});
}
void CMainSignals::TransactionAddedToMempool(const CTransactionRef &ptx) {
m_internals->m_schedulerClient.AddToProcessQueue([ptx, this] {
m_internals->TransactionAddedToMempool(ptx);
});
}
void CMainSignals::BlockConnected(const std::shared_ptr<const CBlock> &pblock, const CBlockIndex *pindex, const std::shared_ptr<const std::vector<CTransactionRef>>& pvtxConflicted) {
m_internals->m_schedulerClient.AddToProcessQueue([pblock, pindex, pvtxConflicted, this] {
m_internals->BlockConnected(pblock, pindex, *pvtxConflicted);
});
}
void CMainSignals::BlockDisconnected(const std::shared_ptr<const CBlock> &pblock) {
m_internals->m_schedulerClient.AddToProcessQueue([pblock, this] {
m_internals->BlockDisconnected(pblock);
});
}
void CMainSignals::ChainStateFlushed(const CBlockLocator &locator) {
m_internals->m_schedulerClient.AddToProcessQueue([locator, this] {
m_internals->ChainStateFlushed(locator);
});
}
void CMainSignals::Broadcast(int64_t nBestBlockTime, CConnman* connman) {
m_internals->Broadcast(nBestBlockTime, connman);
}
void CMainSignals::BlockChecked(const CBlock& block, const CValidationState& state) {
m_internals->BlockChecked(block, state);
}
void CMainSignals::NewPoWValidBlock(const CBlockIndex *pindex, const std::shared_ptr<const CBlock> &block) {
m_internals->NewPoWValidBlock(pindex, block);
}
void CMainSignals::ProcessModuleMessage(CNode* pfrom, const std::string& strCommand, CDataStream& vRecv, CConnman* connman) {
m_internals->ProcessModuleMessage(pfrom, strCommand, vRecv, connman);
}
void CMainSignals::NotifyGovernanceObject(const CGovernanceObject &gobject) {
m_internals->NotifyGovernanceObject(gobject);
}
void CMainSignals::NotifyGovernanceVote(const CGovernanceVote &govote) {
m_internals->NotifyGovernanceVote(govote);
}
<|endoftext|> |
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/perv/p9_extract_sbe_rc.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
//------------------------------------------------------------------------------
/// @file p9_extract_sbe_rc.H
///
/// @brief Check for errors on the SBE, OTPROM, PIBMEM & SEEPROM
//------------------------------------------------------------------------------
// *HWP HW Owner : Soma BhanuTej <[email protected]>
// *HWP HW Backup Owner : Srinivas V Naga <[email protected]>
// *HWP FW Owner : Sunil Kumar <[email protected]>
// *HWP Team : Perv
// *HWP Level : 3
// *HWP Consumed by : FSP:HB
//------------------------------------------------------------------------------
#ifndef _P9_EXTRACT_SBE_RC_H_
#define _P9_EXTRACT_SBE_RC_H_
#include <fapi2.H>
namespace P9_EXTRACT_SBE_RC
{
enum RETURN_ACTION
{
ERROR_RECOVERED = 0, // Something happened with the SBE, we committed the errors involved
// (as informational), attempted and successfully rebooted the SBE
RESTART_SBE = 1, // Trigger external HRESET to reset SBE
RESTART_CBS = 2, // Trigger Warm ipl where we don't switch off VSB just toggle start_cbs from FSP
REIPL_BKP_SEEPROM = 3, // Run IPL by selecting backup seeprom
REIPL_UPD_SEEPROM = 4, // Reload/update of SEEPROM required or deconfig the chip
NO_RECOVERY_ACTION = 5, // No recovery action possible to correct this error
};
};
typedef fapi2::ReturnCode (*p9_extract_sbe_rc_FP_t)(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>&,
P9_EXTRACT_SBE_RC::RETURN_ACTION&, bool, bool);
/// @brief called on all chips(master and slaves) to look for any correctable errors on the SBE, OTPROM, PIBMEM & SEEPROM, the soft_error flag tells the procedure not to generate error if no HW issue.
///
/// @param[in] i_target_chiplet Reference to TARGET_TYPE_PROC_CHIP target
/// @param[out] o_return_action Returns the action to be taken on an error
/// @param[in] i_set_sdb To program the chip to set SDB
/// @param[in] i_unsecure_mode To get debug info in a unsecure mode
/// @return FAPI2_RC_SUCCESS if success, else error code.
extern "C"
{
fapi2::ReturnCode p9_extract_sbe_rc(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target_chip,
P9_EXTRACT_SBE_RC::RETURN_ACTION& o_return_action,
bool i_set_sdb = false,
bool i_unsecure_mode = false);
}
#endif
<commit_msg>Additional checks to p9_extract_sbe_rc<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/perv/p9_extract_sbe_rc.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
//------------------------------------------------------------------------------
/// @file p9_extract_sbe_rc.H
///
/// @brief Check for errors on the SBE, OTPROM, PIBMEM & SEEPROM
//------------------------------------------------------------------------------
// *HWP HW Owner : Soma BhanuTej <[email protected]>
// *HWP HW Backup Owner : Srinivas V Naga <[email protected]>
// *HWP FW Owner : Sunil Kumar <[email protected]>
// *HWP Team : Perv
// *HWP Level : 3
// *HWP Consumed by : FSP:HB
//------------------------------------------------------------------------------
#ifndef _P9_EXTRACT_SBE_RC_H_
#define _P9_EXTRACT_SBE_RC_H_
#define btos(x) ((x)?"TRUE":"FALSE")
#include <fapi2.H>
namespace P9_EXTRACT_SBE_RC
{
enum RETURN_ACTION
{
ERROR_RECOVERED = 0, // Something happened with the SBE, we committed the errors involved
// (as informational), attempted and successfully rebooted the SBE
RESTART_SBE = 1, // Trigger external HRESET to reset SBE
RESTART_CBS = 2, // Trigger Warm ipl where we don't switch off VSB just toggle start_cbs from FSP
REIPL_BKP_SEEPROM = 3, // Run IPL by selecting backup seeprom
REIPL_UPD_SEEPROM = 4, // Reload/update of SEEPROM required or deconfig the chip
NO_RECOVERY_ACTION = 5, // No recovery action possible to correct this error
};
};
typedef fapi2::ReturnCode (*p9_extract_sbe_rc_FP_t)(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>&,
P9_EXTRACT_SBE_RC::RETURN_ACTION&, bool, bool);
/// @brief called on all chips(master and slaves) to look for any correctable errors on the SBE, OTPROM, PIBMEM & SEEPROM, the soft_error flag tells the procedure not to generate error if no HW issue.
///
/// @param[in] i_target_chiplet Reference to TARGET_TYPE_PROC_CHIP target
/// @param[out] o_return_action Returns the action to be taken on an error
/// @param[in] i_set_sdb To program the chip to set SDB
/// @param[in] i_unsecure_mode To get debug info in a unsecure mode
/// @return FAPI2_RC_SUCCESS if success, else error code.
extern "C"
{
fapi2::ReturnCode p9_extract_sbe_rc(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target_chip,
P9_EXTRACT_SBE_RC::RETURN_ACTION& o_return_action,
bool i_set_sdb = false,
bool i_unsecure_mode = false);
}
#endif
<|endoftext|> |
<commit_before>#include "WindowViewer.h"
#include <unordered_map>
#include "renderer/Camera.h"
#include "renderer/ToonMapper.h"
#include "renderer/Renderer.h"
#include <iostream>
#include <Windows.h>
using namespace std;
namespace {
wstring widen(const std::string &src) {
wchar_t *wcs = new wchar_t[src.length() + 1];
size_t converted;
mbstowcs_s(&converted, wcs, src.length()+1, src.c_str(), src.length());
wstring dest = wcs;
delete [] wcs;
return dest;
}
}
namespace OmochiRenderer {
class WindowViewer::WindowImpl {
WindowViewer &viewer;
static unordered_map<size_t, WindowImpl *> handleToInstance;
wstring wstr_title;
HWND m_hWnd;
size_t m_timerID;
public:
explicit WindowImpl(WindowViewer &viewer_)
: viewer(viewer_)
, wstr_title()
, m_hWnd(NULL)
, m_timerID(0)
{
}
bool CreateNewWindow() {
HWND hWnd = CreateNewWindow_impl();
m_hWnd = hWnd;
if (hWnd != INVALID_HANDLE_VALUE) {
RegisterWindow(hWnd, this);
ResetTimer();
return true;
}
return false;
}
void ResetTimer() {
if (viewer.m_refreshTimeInMsec < 2) return;
if (m_timerID != 0) {
KillTimer(m_hWnd, m_timerID);
}
m_timerID = WM_USER + rand() % 10000;
SetTimer(m_hWnd, m_timerID, viewer.m_refreshTimeInMsec - 1, NULL);
}
static void MessageLoop() {
// bZ[W[v
MSG msg;
while(true)
{
BOOL ret = GetMessage( &msg, NULL, 0, 0 ); // bZ[W擾
if( ret == 0 || ret == -1 )
{
// AvP[VI郁bZ[WĂA
// 邢 GetMessage() s( -1 Ԃꂽ jA[v
break;
}
else
{
// bZ[W
TranslateMessage( &msg );
DispatchMessage( &msg );
}
}
}
private:
HWND CreateNewWindow_impl() {
WNDCLASSEX wc;
HWND hWnd;
HINSTANCE hInst = static_cast<HINSTANCE>(GetModuleHandle(NULL));
wstr_title = widen(viewer.m_windowTitle.c_str());
// EBhENX̏ݒ
wc.cbSize = sizeof(wc); // \̃TCY
wc.style = CS_HREDRAW | CS_VREDRAW; // X^C
wc.lpfnWndProc = WindowImpl::WndProc; // EBhEvV[W
wc.cbClsExtra = 0; // gP
wc.cbWndExtra = 0; // gQ
wc.hInstance = hInst; // CX^Xnh
wc.hIcon = (HICON)LoadImage( // ACR
NULL, MAKEINTRESOURCE(IDI_APPLICATION), IMAGE_ICON,
0, 0, LR_DEFAULTSIZE | LR_SHARED
);
wc.hIconSm = wc.hIcon; // qACR
wc.hCursor = (HCURSOR)LoadImage( // }EXJ[\
NULL, MAKEINTRESOURCE(IDC_ARROW), IMAGE_CURSOR,
0, 0, LR_DEFAULTSIZE | LR_SHARED
);
wc.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH); // EBhEwi
wc.lpszMenuName = NULL; // j[
// ugly code
wc.lpszClassName = wstr_title.c_str();// EBhENX
// EBhENXo^
if( RegisterClassEx( &wc ) == 0 ){ return (HWND)INVALID_HANDLE_VALUE; }
int width = viewer.m_camera.GetScreenWidth();
int height = viewer.m_camera.GetScreenHeight();
int x = ( GetSystemMetrics( SM_CXSCREEN ) - width ) / 2;
int y = ( GetSystemMetrics( SM_CYSCREEN ) - height ) / 2;
// EBhE쐬
hWnd = CreateWindow(
wc.lpszClassName, // EBhENX
wstr_title.c_str(), // ^Cgo[ɕ\镶
WS_OVERLAPPEDWINDOW, // EBhE̎
x, // EBhE\ʒuiXWj
y, // EBhE\ʒuiYWj
width, // EBhE̕
height, // EBhE̍
NULL, // eEBhẼEBhEnh
NULL, // j[nh
hInst, // CX^Xnh
NULL // ̑̍쐬f[^
);
if (hWnd == 0 || hWnd == INVALID_HANDLE_VALUE) return (HWND)INVALID_HANDLE_VALUE;
RECT wrect, crect;
GetWindowRect(hWnd, &wrect); GetClientRect(hWnd, &crect);
int truewidth = width + (wrect.right-wrect.left) - (crect.right-crect.left);
int trueheight = height + (wrect.bottom-wrect.top) - (crect.bottom-crect.top);
x = (GetSystemMetrics(SM_CXSCREEN) - truewidth)/2;
y = (GetSystemMetrics(SM_CYSCREEN) - trueheight)/2;
MoveWindow(hWnd, x, y, truewidth, trueheight, TRUE);
// EBhE\
ShowWindow( hWnd, SW_SHOW );
UpdateWindow( hWnd );
cerr << "HWND = " << hWnd << endl;
return hWnd;
}
static void RegisterWindow(HWND hWnd, WindowImpl *instance) {
size_t sizethWnd = reinterpret_cast<size_t>(hWnd);
handleToInstance[sizethWnd] = instance;
}
static LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wp, LPARAM lp) {
size_t sizethWnd = reinterpret_cast<size_t>(hWnd);
if (handleToInstance.find(sizethWnd) == handleToInstance.end()) {
return DefWindowProc( hWnd, msg, wp, lp );
}
return handleToInstance[sizethWnd]->WndProc_impl(hWnd, msg, wp, lp);
//return WndProc_impl(hWnd, msg, wp, lp);
}
private:
LRESULT WndProc_impl(HWND hWnd, UINT msg, WPARAM wp, LPARAM lp) {
switch (msg) {
case WM_CREATE:
cerr << "WM_CREATE = " << hWnd << endl;
InvalidateRect(hWnd, NULL, TRUE);
break;
case WM_DESTROY:
PostQuitMessage( 0 );
return 0;
case WM_PAINT:
{
PAINTSTRUCT paint;
HDC hdc = BeginPaint(hWnd, &paint);
int width = viewer.m_camera.GetScreenWidth();
int height = viewer.m_camera.GetScreenHeight();
const Color *result = viewer.m_renderer.GetResult();
for (int y=0; y<height; y++) {
for (int x=0; x<width; x++) {
int index = x+y*width;
SetPixel(hdc,x,y,
RGB(viewer.m_mapper.Map(result[index].x),
viewer.m_mapper.Map(result[index].y),
viewer.m_mapper.Map(result[index].z)
));
}
}
// draw information
//SetBkMode(hdc, TRANSPARENT);
wstring info = widen(viewer.m_renderer.GetCurrentRenderingInfo());
RECT rc; GetClientRect(hWnd, &rc);
DrawText(hdc, info.c_str(), -1, &rc, DT_LEFT|DT_WORDBREAK);
EndPaint(hWnd, &paint);
}
return 0;
case WM_TIMER:
if (static_cast<size_t>(wp) == m_timerID) {
InvalidateRect(hWnd, NULL, FALSE);
}
break;
}
return DefWindowProc( hWnd, msg, wp, lp );
}
};
unordered_map<size_t, WindowViewer::WindowImpl *> WindowViewer::WindowImpl::handleToInstance;
WindowViewer::WindowViewer(
const std::string &windowTitle,
const Camera &camera,
const PathTracer &renderer,
const ToonMapper &mapper,
const size_t refreshSpanInMsec)
: m_windowTitle(windowTitle)
, m_camera(camera)
, m_renderer(renderer)
, m_mapper(mapper)
, m_pWindow(NULL)
, m_windowThread()
, m_callbackWhenClosed()
, m_refreshTimeInMsec(refreshSpanInMsec)
{
}
WindowViewer::~WindowViewer() {
}
void WindowViewer::StartViewerOnThisThread() {
m_pWindow.reset(new WindowImpl(*this));
m_pWindow->CreateNewWindow();
WindowImpl::MessageLoop();
if (m_callbackWhenClosed) {
m_callbackWhenClosed();
}
}
void WindowViewer::StartViewerOnNewThread() {
m_windowThread.reset(new std::thread(
[this]{
m_pWindow.reset(new WindowImpl(*this));
m_pWindow->CreateNewWindow();
WindowImpl::MessageLoop();
if (m_callbackWhenClosed) {
m_callbackWhenClosed();
}
}
));
}
void WindowViewer::WaitWindowFinish() {
if (m_windowThread) {
m_windowThread->join();
m_windowThread.reset();
}
}
}
<commit_msg>add OpenGL init code (no glut)<commit_after>#include "WindowViewer.h"
#include <unordered_map>
#include "renderer/Camera.h"
#include "renderer/ToonMapper.h"
#include "renderer/Renderer.h"
#include <iostream>
#include <Windows.h>
using namespace std;
#include "glew.h"
#include "glext.h"
#include <gl/GL.h>
#pragma comment(lib, "opengl32.lib")
namespace {
wstring widen(const std::string &src) {
wchar_t *wcs = new wchar_t[src.length() + 1];
size_t converted;
mbstowcs_s(&converted, wcs, src.length()+1, src.c_str(), src.length());
wstring dest = wcs;
delete [] wcs;
return dest;
}
}
namespace OmochiRenderer {
class WindowViewer::WindowImpl {
WindowViewer &viewer;
static unordered_map<size_t, WindowImpl *> handleToInstance;
wstring wstr_title;
HWND m_hWnd;
size_t m_timerID;
HGLRC m_glrc;
public:
explicit WindowImpl(WindowViewer &viewer_)
: viewer(viewer_)
, wstr_title()
, m_hWnd(NULL)
, m_timerID(0)
, m_glrc(NULL)
{
}
~WindowImpl()
{
if (m_glrc != NULL) wglDeleteContext(m_glrc);
}
bool CreateNewWindow() {
HWND hWnd = CreateNewWindow_impl();
if (hWnd != INVALID_HANDLE_VALUE) {
RegisterWindow(hWnd, this);
InitOpenGL(hWnd);
//ResetTimer();
return true;
}
return false;
}
void ResetTimer() {
if (viewer.m_refreshTimeInMsec < 2) return;
if (m_timerID != 0) {
KillTimer(m_hWnd, m_timerID);
}
m_timerID = WM_USER + rand() % 10000;
SetTimer(m_hWnd, m_timerID, viewer.m_refreshTimeInMsec - 1, NULL);
}
static void MessageLoop() {
// bZ[W[v
MSG msg;
while(true)
{
BOOL ret = GetMessage( &msg, NULL, 0, 0 ); // bZ[W擾
if( ret == 0 || ret == -1 )
{
// AvP[VI郁bZ[WĂA
// 邢 GetMessage() s( -1 Ԃꂽ jA[v
break;
}
else
{
// bZ[W
TranslateMessage( &msg );
DispatchMessage( &msg );
}
}
}
private:
HWND CreateNewWindow_impl() {
WNDCLASSEX wc;
HWND hWnd;
HINSTANCE hInst = static_cast<HINSTANCE>(GetModuleHandle(NULL));
wstr_title = widen(viewer.m_windowTitle.c_str());
// EBhENX̏ݒ
wc.cbSize = sizeof(wc); // \̃TCY
wc.style = CS_HREDRAW | CS_VREDRAW; // X^C
wc.lpfnWndProc = WindowImpl::WndProc; // EBhEvV[W
wc.cbClsExtra = 0; // gP
wc.cbWndExtra = 0; // gQ
wc.hInstance = hInst; // CX^Xnh
wc.hIcon = (HICON)LoadImage( // ACR
NULL, MAKEINTRESOURCE(IDI_APPLICATION), IMAGE_ICON,
0, 0, LR_DEFAULTSIZE | LR_SHARED
);
wc.hIconSm = wc.hIcon; // qACR
wc.hCursor = (HCURSOR)LoadImage( // }EXJ[\
NULL, MAKEINTRESOURCE(IDC_ARROW), IMAGE_CURSOR,
0, 0, LR_DEFAULTSIZE | LR_SHARED
);
wc.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH); // EBhEwi
wc.lpszMenuName = NULL; // j[
// ugly code
wc.lpszClassName = wstr_title.c_str();// EBhENX
// EBhENXo^
if( RegisterClassEx( &wc ) == 0 ){ return (HWND)INVALID_HANDLE_VALUE; }
int width = viewer.m_camera.GetScreenWidth();
int height = viewer.m_camera.GetScreenHeight();
int x = ( GetSystemMetrics( SM_CXSCREEN ) - width ) / 2;
int y = ( GetSystemMetrics( SM_CYSCREEN ) - height ) / 2;
// EBhE쐬
hWnd = CreateWindow(
wc.lpszClassName, // EBhENX
wstr_title.c_str(), // ^Cgo[ɕ\镶
WS_OVERLAPPEDWINDOW, // EBhE̎
x, // EBhE\ʒuiXWj
y, // EBhE\ʒuiYWj
width, // EBhE̕
height, // EBhE̍
NULL, // eEBhẼEBhEnh
NULL, // j[nh
hInst, // CX^Xnh
NULL // ̑̍쐬f[^
);
if (hWnd == 0 || hWnd == INVALID_HANDLE_VALUE) return (HWND)INVALID_HANDLE_VALUE;
RECT wrect, crect;
GetWindowRect(hWnd, &wrect); GetClientRect(hWnd, &crect);
int truewidth = width + (wrect.right-wrect.left) - (crect.right-crect.left);
int trueheight = height + (wrect.bottom-wrect.top) - (crect.bottom-crect.top);
x = (GetSystemMetrics(SM_CXSCREEN) - truewidth)/2;
y = (GetSystemMetrics(SM_CYSCREEN) - trueheight)/2;
MoveWindow(hWnd, x, y, truewidth, trueheight, TRUE);
// EBhE\
ShowWindow( hWnd, SW_SHOW );
UpdateWindow( hWnd );
cerr << "HWND = " << hWnd << endl;
return hWnd;
}
static void RegisterWindow(HWND hWnd, WindowImpl *instance) {
size_t sizethWnd = reinterpret_cast<size_t>(hWnd);
handleToInstance[sizethWnd] = instance;
}
void InitOpenGL(HWND hWnd) {
HDC hdc = GetDC(hWnd);
try {
// sNZtH[}bg̐ݒ
PIXELFORMATDESCRIPTOR pdf = {
sizeof(PIXELFORMATDESCRIPTOR),
1, // version
PFD_DRAW_TO_WINDOW |
PFD_SUPPORT_OPENGL |
PFD_DOUBLEBUFFER,
24,
0, 0, 0, 0, 0, 0,
0,
0,
0,
0, 0, 0, 0,
32,
0,
0,
PFD_MAIN_PLANE,
0,
0, 0, 0
};
int format = ChoosePixelFormat(hdc, &pdf);
if (format == 0) throw "";
if (!SetPixelFormat(hdc, format, &pdf)) throw "";
// _OReLXg쐬
m_glrc = wglCreateContext(hdc);
}
catch (...) {
ReleaseDC(hWnd, hdc);
return;
}
wglMakeCurrent(hdc, m_glrc);
wglMakeCurrent(hdc, 0);
ReleaseDC(hWnd, hdc);
SendMessage(hWnd, WM_PAINT, NULL, NULL);
}
static LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wp, LPARAM lp) {
size_t sizethWnd = reinterpret_cast<size_t>(hWnd);
if (handleToInstance.find(sizethWnd) == handleToInstance.end()) {
return DefWindowProc( hWnd, msg, wp, lp );
}
return handleToInstance[sizethWnd]->WndProc_impl(hWnd, msg, wp, lp);
//return WndProc_impl(hWnd, msg, wp, lp);
}
private:
LRESULT WndProc_impl(HWND hWnd, UINT msg, WPARAM wp, LPARAM lp) {
switch (msg) {
case WM_CREATE:
cerr << "WM_CREATE = " << hWnd << endl;
InvalidateRect(hWnd, NULL, TRUE);
break;
case WM_DESTROY:
PostQuitMessage( 0 );
return 0;
case WM_PAINT:
{
PAINTSTRUCT paint;
HDC hdc = BeginPaint(hWnd, &paint);
wglMakeCurrent(hdc, m_glrc);
Render(hdc, hWnd);
wglMakeCurrent(hdc, NULL);
EndPaint(hWnd, &paint);
}
return 0;
case WM_TIMER:
if (static_cast<size_t>(wp) == m_timerID) {
InvalidateRect(hWnd, NULL, FALSE);
}
break;
}
return DefWindowProc( hWnd, msg, wp, lp );
}
void Render(HDC hdc, HWND hWnd) {
glClearColor(0.1f, 0.1f, 0.1f, 1.0f);
glClearDepth(1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
SwapBuffers(hdc);
/*
int width = viewer.m_camera.GetScreenWidth();
int height = viewer.m_camera.GetScreenHeight();
const Color *result = viewer.m_renderer.GetResult();
for (int y = 0; y<height; y++) {
for (int x = 0; x<width; x++) {
int index = x + y*width;
SetPixel(hdc, x, y,
RGB(viewer.m_mapper.Map(result[index].x),
viewer.m_mapper.Map(result[index].y),
viewer.m_mapper.Map(result[index].z)
));
}
}
// draw information
//SetBkMode(hdc, TRANSPARENT);
wstring info = widen(viewer.m_renderer.GetCurrentRenderingInfo());
RECT rc; GetClientRect(hWnd, &rc);
DrawText(hdc, info.c_str(), -1, &rc, DT_LEFT | DT_WORDBREAK);
*/
}
};
unordered_map<size_t, WindowViewer::WindowImpl *> WindowViewer::WindowImpl::handleToInstance;
WindowViewer::WindowViewer(
const std::string &windowTitle,
const Camera &camera,
const PathTracer &renderer,
const ToonMapper &mapper,
const size_t refreshSpanInMsec)
: m_windowTitle(windowTitle)
, m_camera(camera)
, m_renderer(renderer)
, m_mapper(mapper)
, m_pWindow(NULL)
, m_windowThread()
, m_callbackWhenClosed()
, m_refreshTimeInMsec(refreshSpanInMsec)
{
}
WindowViewer::~WindowViewer() {
}
void WindowViewer::StartViewerOnThisThread() {
m_pWindow.reset(new WindowImpl(*this));
m_pWindow->CreateNewWindow();
WindowImpl::MessageLoop();
if (m_callbackWhenClosed) {
m_callbackWhenClosed();
}
}
void WindowViewer::StartViewerOnNewThread() {
m_windowThread.reset(new std::thread(
[this]{
m_pWindow.reset(new WindowImpl(*this));
m_pWindow->CreateNewWindow();
WindowImpl::MessageLoop();
if (m_callbackWhenClosed) {
m_callbackWhenClosed();
}
}
));
}
void WindowViewer::WaitWindowFinish() {
if (m_windowThread) {
m_windowThread->join();
m_windowThread.reset();
}
}
}
<|endoftext|> |
<commit_before>#include "drawer.hpp"
#include "proto_to_styles.hpp"
#include "feature_styler.hpp"
#include "../std/bind.hpp"
#include "../indexer/drawing_rules.hpp"
#include "../indexer/scales.hpp"
#include "../graphics/defines.hpp"
#include "../graphics/screen.hpp"
#include "../graphics/resource_manager.hpp"
#include "../graphics/straight_text_element.hpp"
#include "../indexer/drules_include.hpp"
#include "../indexer/feature.hpp"
#include "../geometry/screenbase.hpp"
#include "../base/logging.hpp"
#include "../base/buffer_vector.hpp"
Drawer::Params::Params()
: m_visualScale(1)
{
}
Drawer::Drawer(Params const & params)
: m_visualScale(params.m_visualScale)
{
m_pScreen.reset(new graphics::Screen(params));
for (unsigned i = 0; i < m_pScreen->pipelinesCount(); ++i)
m_pScreen->addClearPageFn(i, bind(&Drawer::ClearResourceCache, ThreadSlot(), i), 0);
}
namespace
{
struct DoMakeInvalidRule
{
size_t m_threadSlot;
uint32_t m_pipelineIDMask;
DoMakeInvalidRule(size_t threadSlot, uint8_t pipelineID)
: m_threadSlot(threadSlot), m_pipelineIDMask(pipelineID << 24)
{}
void operator() (int, int, int, drule::BaseRule * p)
{
if ((p->GetID(m_threadSlot) & 0xFF000000) == m_pipelineIDMask)
p->MakeEmptyID(m_threadSlot);
if ((p->GetID2(m_threadSlot) & 0xFF000000) == m_pipelineIDMask)
p->MakeEmptyID2(m_threadSlot);
}
};
}
void Drawer::ClearResourceCache(size_t threadSlot, uint8_t pipelineID)
{
drule::rules().ForEachRule(DoMakeInvalidRule(threadSlot, pipelineID));
}
void Drawer::beginFrame()
{
m_pScreen->beginFrame();
}
void Drawer::endFrame()
{
m_pScreen->endFrame();
}
void Drawer::clear(graphics::Color const & c, bool clearRT, float depth, bool clearDepth)
{
m_pScreen->clear(c, clearRT, depth, clearDepth);
}
void Drawer::onSize(int w, int h)
{
m_pScreen->onSize(w, h);
}
void Drawer::drawSymbol(m2::PointD const & pt,
string const & symbolName,
graphics::EPosition pos,
double depth)
{
m_pScreen->drawSymbol(pt, symbolName, pos, depth);
}
void Drawer::drawCircle(m2::PointD const & pt,
graphics::EPosition pos,
di::DrawRule const & rule,
di::FeatureInfo::FeatureID const & id)
{
graphics::Circle::Info ci;
ConvertStyle(rule.m_rule->GetCircle(), m_visualScale, ci);
graphics::CircleElement::Params params;
params.m_depth = rule.m_depth;
params.m_position = pos;
params.m_pivot = pt;
params.m_ci = ci;
params.m_userInfo.m_mwmID = id.first;
params.m_userInfo.m_offset = id.second;
m_pScreen->drawCircle(params);
}
void Drawer::drawSymbol(m2::PointD const & pt,
graphics::EPosition pos,
di::DrawRule const & rule,
di::FeatureInfo::FeatureID const & id)
{
graphics::Icon::Info info;
ConvertStyle(rule.m_rule->GetSymbol(), info);
graphics::SymbolElement::Params params;
params.m_depth = rule.m_depth;
params.m_position = pos;
params.m_pivot = pt;
params.m_info = info;
params.m_renderer = m_pScreen.get();
params.m_userInfo.m_mwmID = id.first;
params.m_userInfo.m_offset = id.second;
m_pScreen->drawSymbol(params);
}
void Drawer::drawPath(di::PathInfo const & path, di::DrawRule const * rules, size_t count)
{
// if any rule needs caching - cache as a whole vector
bool flag = false;
for (size_t i = 0; i < count; ++i)
{
if (rules[i].GetID(m_pScreen->threadSlot()) == drule::BaseRule::empty_id)
{
flag = true;
break;
}
}
buffer_vector<graphics::Pen::Info, 8> penInfos(count);
buffer_vector<graphics::Resource::Info const*, 8> infos(count);
buffer_vector<uint32_t, 8> resIDs(count);
if (flag)
{
// collect graphics::PenInfo into array and pack them as a whole
for (size_t i = 0; i < count; ++i)
{
ConvertStyle(rules[i].m_rule->GetLine(), m_visualScale, penInfos[i]);
infos[i] = &penInfos[i];
if (rules[i].m_transparent)
penInfos[i].m_color.a = 100;
resIDs[i] = m_pScreen->invalidHandle();
}
// map array of pens
if (m_pScreen->mapInfo(&infos[0], &resIDs[0], count))
{
for (size_t i = 0; i < count; ++i)
rules[i].SetID(ThreadSlot(), resIDs[i]);
}
else
{
buffer_vector<m2::PointU, 8> rects;
for (unsigned i = 0; i < count; ++i)
rects.push_back(infos[i]->resourceSize());
LOG(LERROR, ("couldn't successfully pack a sequence of path styles as a whole :" , rects));
return;
}
}
// draw path with array of rules
for (size_t i = 0; i < count; ++i)
m_pScreen->drawPath(&path.m_path[0],
path.m_path.size(),
-path.GetOffset(),
rules[i].GetID(ThreadSlot()),
rules[i].m_depth);
}
void Drawer::drawArea(di::AreaInfo const & area, di::DrawRule const & rule)
{
// DO NOT cache 'id' in pRule, because one rule can use in drawPath and drawArea.
// Leave CBaseRule::m_id for drawPath. mapColor working fast enough.
graphics::Brush::Info info;
ConvertStyle(rule.m_rule->GetArea(), info);
uint32_t const id = m_pScreen->mapInfo(info);
ASSERT ( id != -1, () );
m_pScreen->drawTrianglesList(&area.m_path[0], area.m_path.size(), id, rule.m_depth);
}
void Drawer::drawText(m2::PointD const & pt,
graphics::EPosition pos,
di::FeatureStyler const & fs,
di::DrawRule const & rule,
di::FeatureInfo::FeatureID const & id)
{
graphics::FontDesc primaryFont;
m2::PointD primaryOffset;
ConvertStyle(rule.m_rule->GetCaption(0), m_visualScale, primaryFont, primaryOffset);
primaryFont.SetRank(fs.m_popRank);
graphics::FontDesc secondaryFont;
m2::PointD secondaryOffset;
if (rule.m_rule->GetCaption(1))
{
ConvertStyle(rule.m_rule->GetCaption(1), m_visualScale, secondaryFont, secondaryOffset);
secondaryFont.SetRank(fs.m_popRank);
}
graphics::StraightTextElement::Params params;
params.m_depth = rule.m_depth;
params.m_fontDesc = primaryFont;
params.m_auxFontDesc = secondaryFont;
params.m_offset = primaryOffset;
params.m_log2vis = true;
params.m_pivot = pt;
params.m_position = pos;
params.m_logText = strings::MakeUniString(fs.m_primaryText);
params.m_auxLogText = strings::MakeUniString(fs.m_secondaryText);
params.m_doSplit = true;
params.m_useAllParts = false;
params.m_userInfo.m_mwmID = id.first;
params.m_userInfo.m_offset = id.second;
m_pScreen->drawTextEx(params);
}
void Drawer::drawPathText(di::PathInfo const & path,
di::FeatureStyler const & fs,
di::DrawRule const & rule)
{
graphics::FontDesc font;
m2::PointD offset;
ConvertStyle(rule.m_rule->GetCaption(0), m_visualScale, font, offset);
if (fs.m_offsets.empty())
return;
m_pScreen->drawPathText(font,
&path.m_path[0],
path.m_path.size(),
fs.GetPathName(),
path.GetFullLength(),
path.GetOffset(),
&fs.m_offsets[0],
fs.m_offsets.size(),
rule.m_depth);
}
void Drawer::drawPathNumber(di::PathInfo const & path,
di::FeatureStyler const & fs)
{
int const textHeight = static_cast<int>(11 * m_visualScale);
m2::PointD pt;
double const length = path.GetFullLength();
if (length >= (fs.m_refText.size() + 2) * textHeight)
{
size_t const count = size_t(length / 1000.0) + 2;
for (size_t j = 1; j < count; ++j)
{
if (path.GetSmPoint(double(j) / double(count), pt))
{
graphics::FontDesc fontDesc(
textHeight,
graphics::Color(150, 75, 0, 255), // brown
true,
graphics::Color(255, 255, 255, 255));
m_pScreen->drawText(fontDesc,
pt,
graphics::EPosCenter,
fs.m_refText,
0,
true);
}
}
}
}
graphics::Screen * Drawer::screen() const
{
return m_pScreen.get();
}
double Drawer::VisualScale() const
{
return m_visualScale;
}
void Drawer::SetScale(int level)
{
m_level = level;
}
void Drawer::Draw(di::FeatureInfo const & fi)
{
di::FeatureInfo::FeatureID const & id = fi.m_id;
buffer_vector<di::DrawRule, 8> const & rules = fi.m_styler.m_rules;
buffer_vector<di::DrawRule, 8> pathRules;
bool const isPath = !fi.m_pathes.empty();
bool const isArea = !fi.m_areas.empty();
// separating path rules from other
for (size_t i = 0; i < rules.size(); ++i)
{
drule::BaseRule const * pRule = rules[i].m_rule;
bool const hasSymbol = pRule->GetSymbol() != 0;
bool const isCaption = pRule->GetCaption(0) != 0;
if (!isCaption && isPath && !hasSymbol && (pRule->GetLine() != 0))
pathRules.push_back(rules[i]);
}
if (!pathRules.empty())
{
for (list<di::PathInfo>::const_iterator i = fi.m_pathes.begin(); i != fi.m_pathes.end(); ++i)
drawPath(*i, pathRules.data(), pathRules.size());
}
for (size_t i = 0; i < rules.size(); ++i)
{
drule::BaseRule const * pRule = rules[i].m_rule;
double const depth = rules[i].m_depth;
bool const isCaption = pRule->GetCaption(0) != 0;
bool const hasSymbol = pRule->GetSymbol() != 0;
bool const isCircle = pRule->GetCircle() != 0;
if (!isCaption)
{
// draw area
if (isArea)
{
bool const isFill = pRule->GetArea() != 0;
bool const hasSym = hasSymbol && ((pRule->GetType() & drule::way) != 0);
for (list<di::AreaInfo>::const_iterator i = fi.m_areas.begin(); i != fi.m_areas.end(); ++i)
{
if (isFill)
drawArea(*i, di::DrawRule(pRule, depth, false));
else if (hasSym)
drawSymbol(i->GetCenter(), graphics::EPosCenter, di::DrawRule(pRule, depth, false), id);
}
}
// draw point symbol
if (!isPath && !isArea && ((pRule->GetType() & drule::node) != 0))
{
if (hasSymbol)
drawSymbol(fi.m_point, graphics::EPosCenter, di::DrawRule(pRule, depth, false), id);
else if (isCircle)
drawCircle(fi.m_point, graphics::EPosCenter, di::DrawRule(pRule, depth, false), id);
}
}
else
{
if (!fi.m_styler.m_primaryText.empty() && (pRule->GetCaption(0) != 0))
{
bool isN = ((pRule->GetType() & drule::way) != 0);
graphics::EPosition textPosition = graphics::EPosCenter;
if (pRule->GetCaption(0)->has_offset_y())
{
if (pRule->GetCaption(0)->offset_y() > 0)
textPosition = graphics::EPosUnder;
else
textPosition = graphics::EPosAbove;
}
if (pRule->GetCaption(0)->has_offset_x())
{
if (pRule->GetCaption(0)->offset_x() > 0)
textPosition = graphics::EPosRight;
else
textPosition = graphics::EPosLeft;
}
// draw area text
if (isArea/* && isN*/)
{
for (list<di::AreaInfo>::const_iterator i = fi.m_areas.begin(); i != fi.m_areas.end(); ++i)
drawText(i->GetCenter(), textPosition, fi.m_styler, di::DrawRule(pRule, depth, false), id);
}
// draw way name
if (isPath && !isArea && isN && !fi.m_styler.FilterTextSize(pRule))
{
for (list<di::PathInfo>::const_iterator i = fi.m_pathes.begin(); i != fi.m_pathes.end(); ++i)
drawPathText(*i, fi.m_styler, di::DrawRule(pRule, depth, false));
}
// draw point text
isN = ((pRule->GetType() & drule::node) != 0);
if (!isPath && !isArea && isN)
drawText(fi.m_point, textPosition, fi.m_styler, di::DrawRule(pRule, depth, false), id);
}
}
}
// draw road numbers
if (isPath && !fi.m_styler.m_refText.empty() && m_level >= 12)
{
for (list<di::PathInfo>::const_iterator i = fi.m_pathes.begin(); i != fi.m_pathes.end(); ++i)
drawPathNumber(*i, fi.m_styler);
}
}
int Drawer::ThreadSlot() const
{
return m_pScreen->threadSlot();
}
<commit_msg>[map] circles for polygons<commit_after>#include "drawer.hpp"
#include "proto_to_styles.hpp"
#include "feature_styler.hpp"
#include "../std/bind.hpp"
#include "../indexer/drawing_rules.hpp"
#include "../indexer/scales.hpp"
#include "../graphics/defines.hpp"
#include "../graphics/screen.hpp"
#include "../graphics/resource_manager.hpp"
#include "../graphics/straight_text_element.hpp"
#include "../indexer/drules_include.hpp"
#include "../indexer/feature.hpp"
#include "../geometry/screenbase.hpp"
#include "../base/logging.hpp"
#include "../base/buffer_vector.hpp"
Drawer::Params::Params()
: m_visualScale(1)
{
}
Drawer::Drawer(Params const & params)
: m_visualScale(params.m_visualScale)
{
m_pScreen.reset(new graphics::Screen(params));
for (unsigned i = 0; i < m_pScreen->pipelinesCount(); ++i)
m_pScreen->addClearPageFn(i, bind(&Drawer::ClearResourceCache, ThreadSlot(), i), 0);
}
namespace
{
struct DoMakeInvalidRule
{
size_t m_threadSlot;
uint32_t m_pipelineIDMask;
DoMakeInvalidRule(size_t threadSlot, uint8_t pipelineID)
: m_threadSlot(threadSlot), m_pipelineIDMask(pipelineID << 24)
{}
void operator() (int, int, int, drule::BaseRule * p)
{
if ((p->GetID(m_threadSlot) & 0xFF000000) == m_pipelineIDMask)
p->MakeEmptyID(m_threadSlot);
if ((p->GetID2(m_threadSlot) & 0xFF000000) == m_pipelineIDMask)
p->MakeEmptyID2(m_threadSlot);
}
};
}
void Drawer::ClearResourceCache(size_t threadSlot, uint8_t pipelineID)
{
drule::rules().ForEachRule(DoMakeInvalidRule(threadSlot, pipelineID));
}
void Drawer::beginFrame()
{
m_pScreen->beginFrame();
}
void Drawer::endFrame()
{
m_pScreen->endFrame();
}
void Drawer::clear(graphics::Color const & c, bool clearRT, float depth, bool clearDepth)
{
m_pScreen->clear(c, clearRT, depth, clearDepth);
}
void Drawer::onSize(int w, int h)
{
m_pScreen->onSize(w, h);
}
void Drawer::drawSymbol(m2::PointD const & pt,
string const & symbolName,
graphics::EPosition pos,
double depth)
{
m_pScreen->drawSymbol(pt, symbolName, pos, depth);
}
void Drawer::drawCircle(m2::PointD const & pt,
graphics::EPosition pos,
di::DrawRule const & rule,
di::FeatureInfo::FeatureID const & id)
{
graphics::Circle::Info ci;
ConvertStyle(rule.m_rule->GetCircle(), m_visualScale, ci);
graphics::CircleElement::Params params;
params.m_depth = rule.m_depth;
params.m_position = pos;
params.m_pivot = pt;
params.m_ci = ci;
params.m_userInfo.m_mwmID = id.first;
params.m_userInfo.m_offset = id.second;
m_pScreen->drawCircle(params);
}
void Drawer::drawSymbol(m2::PointD const & pt,
graphics::EPosition pos,
di::DrawRule const & rule,
di::FeatureInfo::FeatureID const & id)
{
graphics::Icon::Info info;
ConvertStyle(rule.m_rule->GetSymbol(), info);
graphics::SymbolElement::Params params;
params.m_depth = rule.m_depth;
params.m_position = pos;
params.m_pivot = pt;
params.m_info = info;
params.m_renderer = m_pScreen.get();
params.m_userInfo.m_mwmID = id.first;
params.m_userInfo.m_offset = id.second;
m_pScreen->drawSymbol(params);
}
void Drawer::drawPath(di::PathInfo const & path, di::DrawRule const * rules, size_t count)
{
// if any rule needs caching - cache as a whole vector
bool flag = false;
for (size_t i = 0; i < count; ++i)
{
if (rules[i].GetID(m_pScreen->threadSlot()) == drule::BaseRule::empty_id)
{
flag = true;
break;
}
}
buffer_vector<graphics::Pen::Info, 8> penInfos(count);
buffer_vector<graphics::Resource::Info const*, 8> infos(count);
buffer_vector<uint32_t, 8> resIDs(count);
if (flag)
{
// collect graphics::PenInfo into array and pack them as a whole
for (size_t i = 0; i < count; ++i)
{
ConvertStyle(rules[i].m_rule->GetLine(), m_visualScale, penInfos[i]);
infos[i] = &penInfos[i];
if (rules[i].m_transparent)
penInfos[i].m_color.a = 100;
resIDs[i] = m_pScreen->invalidHandle();
}
// map array of pens
if (m_pScreen->mapInfo(&infos[0], &resIDs[0], count))
{
for (size_t i = 0; i < count; ++i)
rules[i].SetID(ThreadSlot(), resIDs[i]);
}
else
{
buffer_vector<m2::PointU, 8> rects;
for (unsigned i = 0; i < count; ++i)
rects.push_back(infos[i]->resourceSize());
LOG(LERROR, ("couldn't successfully pack a sequence of path styles as a whole :" , rects));
return;
}
}
// draw path with array of rules
for (size_t i = 0; i < count; ++i)
m_pScreen->drawPath(&path.m_path[0],
path.m_path.size(),
-path.GetOffset(),
rules[i].GetID(ThreadSlot()),
rules[i].m_depth);
}
void Drawer::drawArea(di::AreaInfo const & area, di::DrawRule const & rule)
{
// DO NOT cache 'id' in pRule, because one rule can use in drawPath and drawArea.
// Leave CBaseRule::m_id for drawPath. mapColor working fast enough.
graphics::Brush::Info info;
ConvertStyle(rule.m_rule->GetArea(), info);
uint32_t const id = m_pScreen->mapInfo(info);
ASSERT ( id != -1, () );
m_pScreen->drawTrianglesList(&area.m_path[0], area.m_path.size(), id, rule.m_depth);
}
void Drawer::drawText(m2::PointD const & pt,
graphics::EPosition pos,
di::FeatureStyler const & fs,
di::DrawRule const & rule,
di::FeatureInfo::FeatureID const & id)
{
graphics::FontDesc primaryFont;
m2::PointD primaryOffset;
ConvertStyle(rule.m_rule->GetCaption(0), m_visualScale, primaryFont, primaryOffset);
primaryFont.SetRank(fs.m_popRank);
graphics::FontDesc secondaryFont;
m2::PointD secondaryOffset;
if (rule.m_rule->GetCaption(1))
{
ConvertStyle(rule.m_rule->GetCaption(1), m_visualScale, secondaryFont, secondaryOffset);
secondaryFont.SetRank(fs.m_popRank);
}
graphics::StraightTextElement::Params params;
params.m_depth = rule.m_depth;
params.m_fontDesc = primaryFont;
params.m_auxFontDesc = secondaryFont;
params.m_offset = primaryOffset;
params.m_log2vis = true;
params.m_pivot = pt;
params.m_position = pos;
params.m_logText = strings::MakeUniString(fs.m_primaryText);
params.m_auxLogText = strings::MakeUniString(fs.m_secondaryText);
params.m_doSplit = true;
params.m_useAllParts = false;
params.m_userInfo.m_mwmID = id.first;
params.m_userInfo.m_offset = id.second;
m_pScreen->drawTextEx(params);
}
void Drawer::drawPathText(di::PathInfo const & path,
di::FeatureStyler const & fs,
di::DrawRule const & rule)
{
graphics::FontDesc font;
m2::PointD offset;
ConvertStyle(rule.m_rule->GetCaption(0), m_visualScale, font, offset);
if (fs.m_offsets.empty())
return;
m_pScreen->drawPathText(font,
&path.m_path[0],
path.m_path.size(),
fs.GetPathName(),
path.GetFullLength(),
path.GetOffset(),
&fs.m_offsets[0],
fs.m_offsets.size(),
rule.m_depth);
}
void Drawer::drawPathNumber(di::PathInfo const & path,
di::FeatureStyler const & fs)
{
int const textHeight = static_cast<int>(11 * m_visualScale);
m2::PointD pt;
double const length = path.GetFullLength();
if (length >= (fs.m_refText.size() + 2) * textHeight)
{
size_t const count = size_t(length / 1000.0) + 2;
for (size_t j = 1; j < count; ++j)
{
if (path.GetSmPoint(double(j) / double(count), pt))
{
graphics::FontDesc fontDesc(
textHeight,
graphics::Color(150, 75, 0, 255), // brown
true,
graphics::Color(255, 255, 255, 255));
m_pScreen->drawText(fontDesc,
pt,
graphics::EPosCenter,
fs.m_refText,
0,
true);
}
}
}
}
graphics::Screen * Drawer::screen() const
{
return m_pScreen.get();
}
double Drawer::VisualScale() const
{
return m_visualScale;
}
void Drawer::SetScale(int level)
{
m_level = level;
}
void Drawer::Draw(di::FeatureInfo const & fi)
{
di::FeatureInfo::FeatureID const & id = fi.m_id;
buffer_vector<di::DrawRule, 8> const & rules = fi.m_styler.m_rules;
buffer_vector<di::DrawRule, 8> pathRules;
bool const isPath = !fi.m_pathes.empty();
bool const isArea = !fi.m_areas.empty();
// separating path rules from other
for (size_t i = 0; i < rules.size(); ++i)
{
drule::BaseRule const * pRule = rules[i].m_rule;
bool const hasSymbol = pRule->GetSymbol() != 0;
bool const isCaption = pRule->GetCaption(0) != 0;
if (!isCaption && isPath && !hasSymbol && (pRule->GetLine() != 0))
pathRules.push_back(rules[i]);
}
if (!pathRules.empty())
{
for (list<di::PathInfo>::const_iterator i = fi.m_pathes.begin(); i != fi.m_pathes.end(); ++i)
drawPath(*i, pathRules.data(), pathRules.size());
}
for (size_t i = 0; i < rules.size(); ++i)
{
drule::BaseRule const * pRule = rules[i].m_rule;
double const depth = rules[i].m_depth;
bool const isCaption = pRule->GetCaption(0) != 0;
bool const hasSymbol = pRule->GetSymbol() != 0;
bool const isCircle = pRule->GetCircle() != 0;
if (!isCaption)
{
// draw area
if (isArea)
{
bool const isFill = pRule->GetArea() != 0;
bool const isWay = (pRule->GetType() & drule::way) != 0;
for (list<di::AreaInfo>::const_iterator i = fi.m_areas.begin(); i != fi.m_areas.end(); ++i)
{
if (isFill)
drawArea(*i, di::DrawRule(pRule, depth, false));
else if (hasSymbol && !isWay)
drawSymbol(i->GetCenter(), graphics::EPosCenter, di::DrawRule(pRule, depth, false), id);
else if (isCircle && !isWay)
drawCircle(i->GetCenter(), graphics::EPosCenter, di::DrawRule(pRule, depth, false), id);
}
}
// draw point symbol
if (!isPath && !isArea && ((pRule->GetType() & drule::node) != 0))
{
if (hasSymbol)
drawSymbol(fi.m_point, graphics::EPosCenter, di::DrawRule(pRule, depth, false), id);
else if (isCircle)
drawCircle(fi.m_point, graphics::EPosCenter, di::DrawRule(pRule, depth, false), id);
}
}
else
{
if (!fi.m_styler.m_primaryText.empty() && (pRule->GetCaption(0) != 0))
{
bool isN = ((pRule->GetType() & drule::way) != 0);
graphics::EPosition textPosition = graphics::EPosCenter;
if (pRule->GetCaption(0)->has_offset_y())
{
if (pRule->GetCaption(0)->offset_y() > 0)
textPosition = graphics::EPosUnder;
else
textPosition = graphics::EPosAbove;
}
if (pRule->GetCaption(0)->has_offset_x())
{
if (pRule->GetCaption(0)->offset_x() > 0)
textPosition = graphics::EPosRight;
else
textPosition = graphics::EPosLeft;
}
// draw area text
if (isArea/* && isN*/)
{
for (list<di::AreaInfo>::const_iterator i = fi.m_areas.begin(); i != fi.m_areas.end(); ++i)
drawText(i->GetCenter(), textPosition, fi.m_styler, di::DrawRule(pRule, depth, false), id);
}
// draw way name
if (isPath && !isArea && isN && !fi.m_styler.FilterTextSize(pRule))
{
for (list<di::PathInfo>::const_iterator i = fi.m_pathes.begin(); i != fi.m_pathes.end(); ++i)
drawPathText(*i, fi.m_styler, di::DrawRule(pRule, depth, false));
}
// draw point text
isN = ((pRule->GetType() & drule::node) != 0);
if (!isPath && !isArea && isN)
drawText(fi.m_point, textPosition, fi.m_styler, di::DrawRule(pRule, depth, false), id);
}
}
}
// draw road numbers
if (isPath && !fi.m_styler.m_refText.empty() && m_level >= 12)
{
for (list<di::PathInfo>::const_iterator i = fi.m_pathes.begin(); i != fi.m_pathes.end(); ++i)
drawPathNumber(*i, fi.m_styler);
}
}
int Drawer::ThreadSlot() const
{
return m_pScreen->threadSlot();
}
<|endoftext|> |
<commit_before>/* Calf DSP Library
* Preset management.
*
* Copyright (C) 2001-2007 Krzysztof Foltman
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General
* Public License along with this program; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place, Suite 330,
* Boston, MA 02111-1307, USA.
*/
#include <config.h>
#include <fcntl.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <sys/stat.h>
#include <expat.h>
#include <calf/preset.h>
#include <calf/giface.h>
#include <calf/utils.h>
using namespace std;
using namespace calf_plugins;
using namespace calf_utils;
extern calf_plugins::preset_list &calf_plugins::get_builtin_presets()
{
static calf_plugins::preset_list plist;
return plist;
}
extern calf_plugins::preset_list &calf_plugins::get_user_presets()
{
static calf_plugins::preset_list plist;
return plist;
}
std::string plugin_preset::to_xml()
{
std::stringstream ss;
ss << "<preset bank=\"" << bank << "\" program=\"" << program << "\" plugin=\"" << xml_escape(plugin) << "\" name=\"" << xml_escape(name) << "\">\n";
for (unsigned int i = 0; i < values.size(); i++) {
if (i < param_names.size())
ss << " <param name=\"" << xml_escape(param_names[i]) << "\" value=\"" << values[i] << "\" />\n";
else
ss << " <param value=\"" << values[i] << "\" />\n";
}
for (map<string, string>::iterator i = variables.begin(); i != variables.end(); i++)
{
ss << " <var name=\"" << xml_escape(i->first) << "\">" << xml_escape(i->second) << "</var>\n";
}
ss << "</preset>\n";
return ss.str();
}
void plugin_preset::activate(plugin_ctl_iface *plugin)
{
// First, clear everything to default values (in case some parameters or variables are missing)
plugin->clear_preset();
map<string, int> names;
int count = plugin->get_param_count();
// this is deliberately done in two separate loops - if you wonder why, just think for a while :)
for (int i = 0; i < count; i++)
names[plugin->get_param_props(i)->name] = i;
for (int i = 0; i < count; i++)
names[plugin->get_param_props(i)->short_name] = i;
// no support for unnamed parameters... tough luck :)
for (unsigned int i = 0; i < min(param_names.size(), values.size()); i++)
{
map<string, int>::iterator pos = names.find(param_names[i]);
if (pos == names.end()) {
// XXXKF should have a mechanism for notifying a GUI
printf("Warning: unknown parameter %s for plugin %s\n", param_names[i].c_str(), this->plugin.c_str());
continue;
}
plugin->set_param_value(pos->second, values[i]);
}
for (map<string, string>::iterator i = variables.begin(); i != variables.end(); i++)
{
printf("configure %s: %s\n", i->first.c_str(), i->second.c_str());
plugin->configure(i->first.c_str(), i->second.c_str());
}
}
void plugin_preset::get_from(plugin_ctl_iface *plugin)
{
int count = plugin->get_param_count();
for (int i = 0; i < count; i++) {
param_names.push_back(plugin->get_param_props(i)->short_name);
values.push_back(plugin->get_param_value(i));
}
struct store_obj: public send_configure_iface
{
map<string, string> *data;
void send_configure(const char *key, const char *value)
{
(*data)[key] = value;
}
} tmp;
variables.clear();
tmp.data = &variables;
plugin->send_configures(&tmp);
}
string calf_plugins::preset_list::get_preset_filename(bool builtin)
{
if (builtin)
{
return PKGLIBDIR "/presets.xml";
}
else
{
const char *home = getenv("HOME");
return string(home)+"/.calfpresets";
}
}
void preset_list::xml_start_element_handler(void *user_data, const char *name, const char *attrs[])
{
preset_list &self = *(preset_list *)user_data;
parser_state &state = self.state;
plugin_preset &parser_preset = self.parser_preset;
switch(state)
{
case START:
if (!strcmp(name, "presets")) {
state = LIST;
return;
}
break;
case LIST:
if (!strcmp(name, "preset")) {
parser_preset.bank = parser_preset.program = 0;
parser_preset.name = "";
parser_preset.plugin = "";
parser_preset.param_names.clear();
parser_preset.values.clear();
parser_preset.variables.clear();
for(; *attrs; attrs += 2) {
if (!strcmp(attrs[0], "name")) self.parser_preset.name = attrs[1];
else
if (!strcmp(attrs[0], "plugin")) self.parser_preset.plugin = attrs[1];
}
// autonumbering of programs for DSSI
if (!self.last_preset_ids.count(self.parser_preset.plugin))
self.last_preset_ids[self.parser_preset.plugin] = 0;
self.parser_preset.program = ++self.last_preset_ids[self.parser_preset.plugin];
self.parser_preset.bank = (self.parser_preset.program >> 7);
self.parser_preset.program &= 127;
state = PRESET;
return;
}
break;
case PRESET:
if (!strcmp(name, "param")) {
std::string name;
float value = 0.f;
for(; *attrs; attrs += 2) {
if (!strcmp(attrs[0], "name")) name = attrs[1];
else
if (!strcmp(attrs[0], "value")) {
istringstream str(attrs[1]);
str >> value;
}
}
self.parser_preset.param_names.push_back(name);
self.parser_preset.values.push_back(value);
state = VALUE;
return;
}
if (!strcmp(name, "var")) {
self.current_key = "";
for(; *attrs; attrs += 2) {
if (!strcmp(attrs[0], "name")) self.current_key = attrs[1];
}
if (self.current_key.empty())
throw preset_exception("No name specified for preset variable", "", 0);
self.parser_preset.variables[self.current_key].clear();
state = VAR;
return;
}
break;
case VALUE:
// no nested elements allowed inside <param>
break;
case VAR:
// no nested elements allowed inside <var>
break;
}
// g_warning("Invalid XML element: %s", name);
throw preset_exception("Invalid XML element: %s", name, 0);
}
void preset_list::xml_end_element_handler(void *user_data, const char *name)
{
preset_list &self = *(preset_list *)user_data;
preset_vector &presets = self.presets;
parser_state &state = self.state;
switch(state)
{
case START:
break;
case LIST:
if (!strcmp(name, "presets")) {
state = START;
return;
}
break;
case PRESET:
if (!strcmp(name, "preset")) {
presets.push_back(self.parser_preset);
state = LIST;
return;
}
break;
case VALUE:
if (!strcmp(name, "param")) {
state = PRESET;
return;
}
break;
case VAR:
if (!strcmp(name, "var")) {
state = PRESET;
return;
}
break;
}
throw preset_exception("Invalid XML element close: %s", name, 0);
}
void preset_list::xml_character_data_handler(void *user_data, const XML_Char *data, int len)
{
preset_list &self = *(preset_list *)user_data;
parser_state &state = self.state;
if (state == VAR)
{
self.parser_preset.variables[self.current_key] += string(data, len);
return;
}
}
bool preset_list::load_defaults(bool builtin)
{
try {
struct stat st;
string name = preset_list::get_preset_filename(builtin);
if (!stat(name.c_str(), &st)) {
load(name.c_str());
if (!presets.empty())
return true;
}
}
catch(preset_exception &ex)
{
return false;
}
return false;
}
void preset_list::parse(const std::string &data)
{
state = START;
XML_Parser parser = XML_ParserCreate("UTF-8");
XML_SetUserData(parser, this);
XML_SetElementHandler(parser, xml_start_element_handler, xml_end_element_handler);
XML_SetCharacterDataHandler(parser, xml_character_data_handler);
XML_Status status = XML_Parse(parser, data.c_str(), data.length(), 1);
if (status == XML_STATUS_ERROR) {
string err = string("Parse error: ") + XML_ErrorString(XML_GetErrorCode(parser))+ " in ";
XML_ParserFree(parser);
throw preset_exception(err, "string", errno);
}
XML_ParserFree(parser);
}
void preset_list::load(const char *filename)
{
state = START;
XML_Parser parser = XML_ParserCreate("UTF-8");
XML_SetUserData(parser, this);
int fd = open(filename, O_RDONLY);
if (fd < 0)
throw preset_exception("Could not load the presets from ", filename, errno);
XML_SetElementHandler(parser, xml_start_element_handler, xml_end_element_handler);
XML_SetCharacterDataHandler(parser, xml_character_data_handler);
char buf[4096];
do
{
int len = read(fd, buf, 4096);
// XXXKF not an optimal error/EOF handling :)
if (len <= 0)
break;
XML_Status status = XML_Parse(parser, buf, len, 0);
if (status == XML_STATUS_ERROR)
throw preset_exception(string("Parse error: ") + XML_ErrorString(XML_GetErrorCode(parser))+ " in ", filename, errno);
} while(1);
XML_Status status = XML_Parse(parser, buf, 0, 1);
close(fd);
if (status == XML_STATUS_ERROR)
{
string err = string("Parse error: ") + XML_ErrorString(XML_GetErrorCode(parser))+ " in ";
XML_ParserFree(parser);
throw preset_exception(err, filename, errno);
}
XML_ParserFree(parser);
}
void preset_list::save(const char *filename)
{
string xml = "<presets>\n";
for (unsigned int i = 0; i < presets.size(); i++)
{
xml += presets[i].to_xml();
}
xml += "</presets>";
int fd = open(filename, O_CREAT | O_WRONLY | O_TRUNC, 0640);
if (fd < 0 || ((unsigned)write(fd, xml.c_str(), xml.length()) != xml.length()))
throw preset_exception("Could not save the presets in ", filename, errno);
close(fd);
}
void preset_list::get_for_plugin(preset_vector &vec, const char *plugin)
{
for (unsigned int i = 0; i < presets.size(); i++)
{
if (presets[i].plugin == plugin)
vec.push_back(presets[i]);
}
}
void preset_list::add(const plugin_preset &sp)
{
for (unsigned int i = 0; i < presets.size(); i++)
{
if (presets[i].plugin == sp.plugin && presets[i].name == sp.name)
{
presets[i] = sp;
return;
}
}
presets.push_back(sp);
}
<commit_msg>+ Preset system: do not produce float values for string ports in presets<commit_after>/* Calf DSP Library
* Preset management.
*
* Copyright (C) 2001-2007 Krzysztof Foltman
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General
* Public License along with this program; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place, Suite 330,
* Boston, MA 02111-1307, USA.
*/
#include <config.h>
#include <fcntl.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <sys/stat.h>
#include <expat.h>
#include <calf/preset.h>
#include <calf/giface.h>
#include <calf/utils.h>
using namespace std;
using namespace calf_plugins;
using namespace calf_utils;
extern calf_plugins::preset_list &calf_plugins::get_builtin_presets()
{
static calf_plugins::preset_list plist;
return plist;
}
extern calf_plugins::preset_list &calf_plugins::get_user_presets()
{
static calf_plugins::preset_list plist;
return plist;
}
std::string plugin_preset::to_xml()
{
std::stringstream ss;
ss << "<preset bank=\"" << bank << "\" program=\"" << program << "\" plugin=\"" << xml_escape(plugin) << "\" name=\"" << xml_escape(name) << "\">\n";
for (unsigned int i = 0; i < values.size(); i++) {
if (i < param_names.size())
ss << " <param name=\"" << xml_escape(param_names[i]) << "\" value=\"" << values[i] << "\" />\n";
else
ss << " <param value=\"" << values[i] << "\" />\n";
}
for (map<string, string>::iterator i = variables.begin(); i != variables.end(); i++)
{
ss << " <var name=\"" << xml_escape(i->first) << "\">" << xml_escape(i->second) << "</var>\n";
}
ss << "</preset>\n";
return ss.str();
}
void plugin_preset::activate(plugin_ctl_iface *plugin)
{
// First, clear everything to default values (in case some parameters or variables are missing)
plugin->clear_preset();
map<string, int> names;
int count = plugin->get_param_count();
// this is deliberately done in two separate loops - if you wonder why, just think for a while :)
for (int i = 0; i < count; i++)
names[plugin->get_param_props(i)->name] = i;
for (int i = 0; i < count; i++)
names[plugin->get_param_props(i)->short_name] = i;
// no support for unnamed parameters... tough luck :)
for (unsigned int i = 0; i < min(param_names.size(), values.size()); i++)
{
map<string, int>::iterator pos = names.find(param_names[i]);
if (pos == names.end()) {
// XXXKF should have a mechanism for notifying a GUI
printf("Warning: unknown parameter %s for plugin %s\n", param_names[i].c_str(), this->plugin.c_str());
continue;
}
plugin->set_param_value(pos->second, values[i]);
}
for (map<string, string>::iterator i = variables.begin(); i != variables.end(); i++)
{
printf("configure %s: %s\n", i->first.c_str(), i->second.c_str());
plugin->configure(i->first.c_str(), i->second.c_str());
}
}
void plugin_preset::get_from(plugin_ctl_iface *plugin)
{
int count = plugin->get_param_count();
for (int i = 0; i < count; i++) {
if ((plugin->get_param_props(i)->flags & PF_TYPEMASK) >= PF_STRING)
continue;
param_names.push_back(plugin->get_param_props(i)->short_name);
values.push_back(plugin->get_param_value(i));
}
struct store_obj: public send_configure_iface
{
map<string, string> *data;
void send_configure(const char *key, const char *value)
{
(*data)[key] = value;
}
} tmp;
variables.clear();
tmp.data = &variables;
plugin->send_configures(&tmp);
}
string calf_plugins::preset_list::get_preset_filename(bool builtin)
{
if (builtin)
{
return PKGLIBDIR "/presets.xml";
}
else
{
const char *home = getenv("HOME");
return string(home)+"/.calfpresets";
}
}
void preset_list::xml_start_element_handler(void *user_data, const char *name, const char *attrs[])
{
preset_list &self = *(preset_list *)user_data;
parser_state &state = self.state;
plugin_preset &parser_preset = self.parser_preset;
switch(state)
{
case START:
if (!strcmp(name, "presets")) {
state = LIST;
return;
}
break;
case LIST:
if (!strcmp(name, "preset")) {
parser_preset.bank = parser_preset.program = 0;
parser_preset.name = "";
parser_preset.plugin = "";
parser_preset.param_names.clear();
parser_preset.values.clear();
parser_preset.variables.clear();
for(; *attrs; attrs += 2) {
if (!strcmp(attrs[0], "name")) self.parser_preset.name = attrs[1];
else
if (!strcmp(attrs[0], "plugin")) self.parser_preset.plugin = attrs[1];
}
// autonumbering of programs for DSSI
if (!self.last_preset_ids.count(self.parser_preset.plugin))
self.last_preset_ids[self.parser_preset.plugin] = 0;
self.parser_preset.program = ++self.last_preset_ids[self.parser_preset.plugin];
self.parser_preset.bank = (self.parser_preset.program >> 7);
self.parser_preset.program &= 127;
state = PRESET;
return;
}
break;
case PRESET:
if (!strcmp(name, "param")) {
std::string name;
float value = 0.f;
for(; *attrs; attrs += 2) {
if (!strcmp(attrs[0], "name")) name = attrs[1];
else
if (!strcmp(attrs[0], "value")) {
istringstream str(attrs[1]);
str >> value;
}
}
self.parser_preset.param_names.push_back(name);
self.parser_preset.values.push_back(value);
state = VALUE;
return;
}
if (!strcmp(name, "var")) {
self.current_key = "";
for(; *attrs; attrs += 2) {
if (!strcmp(attrs[0], "name")) self.current_key = attrs[1];
}
if (self.current_key.empty())
throw preset_exception("No name specified for preset variable", "", 0);
self.parser_preset.variables[self.current_key].clear();
state = VAR;
return;
}
break;
case VALUE:
// no nested elements allowed inside <param>
break;
case VAR:
// no nested elements allowed inside <var>
break;
}
// g_warning("Invalid XML element: %s", name);
throw preset_exception("Invalid XML element: %s", name, 0);
}
void preset_list::xml_end_element_handler(void *user_data, const char *name)
{
preset_list &self = *(preset_list *)user_data;
preset_vector &presets = self.presets;
parser_state &state = self.state;
switch(state)
{
case START:
break;
case LIST:
if (!strcmp(name, "presets")) {
state = START;
return;
}
break;
case PRESET:
if (!strcmp(name, "preset")) {
presets.push_back(self.parser_preset);
state = LIST;
return;
}
break;
case VALUE:
if (!strcmp(name, "param")) {
state = PRESET;
return;
}
break;
case VAR:
if (!strcmp(name, "var")) {
state = PRESET;
return;
}
break;
}
throw preset_exception("Invalid XML element close: %s", name, 0);
}
void preset_list::xml_character_data_handler(void *user_data, const XML_Char *data, int len)
{
preset_list &self = *(preset_list *)user_data;
parser_state &state = self.state;
if (state == VAR)
{
self.parser_preset.variables[self.current_key] += string(data, len);
return;
}
}
bool preset_list::load_defaults(bool builtin)
{
try {
struct stat st;
string name = preset_list::get_preset_filename(builtin);
if (!stat(name.c_str(), &st)) {
load(name.c_str());
if (!presets.empty())
return true;
}
}
catch(preset_exception &ex)
{
return false;
}
return false;
}
void preset_list::parse(const std::string &data)
{
state = START;
XML_Parser parser = XML_ParserCreate("UTF-8");
XML_SetUserData(parser, this);
XML_SetElementHandler(parser, xml_start_element_handler, xml_end_element_handler);
XML_SetCharacterDataHandler(parser, xml_character_data_handler);
XML_Status status = XML_Parse(parser, data.c_str(), data.length(), 1);
if (status == XML_STATUS_ERROR) {
string err = string("Parse error: ") + XML_ErrorString(XML_GetErrorCode(parser))+ " in ";
XML_ParserFree(parser);
throw preset_exception(err, "string", errno);
}
XML_ParserFree(parser);
}
void preset_list::load(const char *filename)
{
state = START;
XML_Parser parser = XML_ParserCreate("UTF-8");
XML_SetUserData(parser, this);
int fd = open(filename, O_RDONLY);
if (fd < 0)
throw preset_exception("Could not load the presets from ", filename, errno);
XML_SetElementHandler(parser, xml_start_element_handler, xml_end_element_handler);
XML_SetCharacterDataHandler(parser, xml_character_data_handler);
char buf[4096];
do
{
int len = read(fd, buf, 4096);
// XXXKF not an optimal error/EOF handling :)
if (len <= 0)
break;
XML_Status status = XML_Parse(parser, buf, len, 0);
if (status == XML_STATUS_ERROR)
throw preset_exception(string("Parse error: ") + XML_ErrorString(XML_GetErrorCode(parser))+ " in ", filename, errno);
} while(1);
XML_Status status = XML_Parse(parser, buf, 0, 1);
close(fd);
if (status == XML_STATUS_ERROR)
{
string err = string("Parse error: ") + XML_ErrorString(XML_GetErrorCode(parser))+ " in ";
XML_ParserFree(parser);
throw preset_exception(err, filename, errno);
}
XML_ParserFree(parser);
}
void preset_list::save(const char *filename)
{
string xml = "<presets>\n";
for (unsigned int i = 0; i < presets.size(); i++)
{
xml += presets[i].to_xml();
}
xml += "</presets>";
int fd = open(filename, O_CREAT | O_WRONLY | O_TRUNC, 0640);
if (fd < 0 || ((unsigned)write(fd, xml.c_str(), xml.length()) != xml.length()))
throw preset_exception("Could not save the presets in ", filename, errno);
close(fd);
}
void preset_list::get_for_plugin(preset_vector &vec, const char *plugin)
{
for (unsigned int i = 0; i < presets.size(); i++)
{
if (presets[i].plugin == plugin)
vec.push_back(presets[i]);
}
}
void preset_list::add(const plugin_preset &sp)
{
for (unsigned int i = 0; i < presets.size(); i++)
{
if (presets[i].plugin == sp.plugin && presets[i].name == sp.name)
{
presets[i] = sp;
return;
}
}
presets.push_back(sp);
}
<|endoftext|> |
<commit_before>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2013 Adrian Draghici <[email protected]>
//
#include "KmlPlaylistTagWriter.h"
#include "GeoDataPlaylist.h"
#include "GeoDataTypes.h"
#include "GeoWriter.h"
#include "KmlElementDictionary.h"
namespace Marble
{
static GeoTagWriterRegistrar s_writerTour(
GeoTagWriter::QualifiedName( GeoDataTypes::GeoDataPlaylistType,
kml::kmlTag_nameSpace22 ),
new KmlPlaylistTagWriter );
bool KmlPlaylistTagWriter::write( const GeoNode *node, GeoWriter& writer ) const
{
const GeoDataPlaylist *playlist = static_cast<const GeoDataPlaylist*>( node );
writer.writeStartElement( "gx:Playlist" );
for ( int i = 0; i < playlist->size(); i++ ) {
writeTourPrimitive( playlist->primitive( i ), writer );
}
writer.writeEndElement();
return true;
}
void KmlPlaylistTagWriter::writeTourPrimitive( const GeoNode *primitive, GeoWriter& writer ) const
{
if ( primitive->nodeType() == GeoDataTypes::GeoDataTourControlType ) {
writeTourControl( static_cast<const GeoDataTourControl*>( primitive ), writer );
}
else if ( primitive->nodeType() == GeoDataTypes::GeoDataFlyToType ) {
writeElement( static_cast<const GeoDataFlyTo*>( primitive ), writer );
}
}
void KmlPlaylistTagWriter::writeTourControl( const GeoDataTourControl* tourControl, GeoWriter& writer ) const
{
writer.writeStartElement( kml::kmlTag_TourControl );
if ( !tourControl->id().isEmpty() ) {
writer.writeAttribute( "id", tourControl->id() );
}
writer.writeElement( kml::kmlTag_playMode, playModeToString( tourControl->playMode() ) );
writer.writeEndElement();
}
QString KmlPlaylistTagWriter::playModeToString( GeoDataTourControl::PlayMode playMode ) const
{
switch (playMode)
{
case GeoDataTourControl::Play: return "play";
case GeoDataTourControl::Pause: return "pause";
default: return "";
}
}
}
<commit_msg>Fix name (copy/paste error). Don't cast.<commit_after>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2013 Adrian Draghici <[email protected]>
//
#include "KmlPlaylistTagWriter.h"
#include "GeoDataPlaylist.h"
#include "GeoDataTypes.h"
#include "GeoWriter.h"
#include "KmlElementDictionary.h"
namespace Marble
{
static GeoTagWriterRegistrar s_writerPlaylist(
GeoTagWriter::QualifiedName( GeoDataTypes::GeoDataPlaylistType,
kml::kmlTag_nameSpace22 ),
new KmlPlaylistTagWriter );
bool KmlPlaylistTagWriter::write( const GeoNode *node, GeoWriter& writer ) const
{
const GeoDataPlaylist *playlist = static_cast<const GeoDataPlaylist*>( node );
writer.writeStartElement( "gx:Playlist" );
for ( int i = 0; i < playlist->size(); i++ ) {
writeTourPrimitive( playlist->primitive( i ), writer );
}
writer.writeEndElement();
return true;
}
void KmlPlaylistTagWriter::writeTourPrimitive( const GeoNode *primitive, GeoWriter& writer ) const
{
if ( primitive->nodeType() == GeoDataTypes::GeoDataTourControlType ) {
writeTourControl( static_cast<const GeoDataTourControl*>( primitive ), writer );
}
else if ( primitive->nodeType() == GeoDataTypes::GeoDataFlyToType ) {
writeElement( primitive, writer );
}
}
void KmlPlaylistTagWriter::writeTourControl( const GeoDataTourControl* tourControl, GeoWriter& writer ) const
{
writer.writeStartElement( kml::kmlTag_TourControl );
if ( !tourControl->id().isEmpty() ) {
writer.writeAttribute( "id", tourControl->id() );
}
writer.writeElement( kml::kmlTag_playMode, playModeToString( tourControl->playMode() ) );
writer.writeEndElement();
}
QString KmlPlaylistTagWriter::playModeToString( GeoDataTourControl::PlayMode playMode ) const
{
switch (playMode)
{
case GeoDataTourControl::Play: return "play";
case GeoDataTourControl::Pause: return "pause";
default: return "";
}
}
}
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* Version: MPL 1.1 / GPLv3+ / LGPLv3+
*
* The contents of this file are subject to the Mozilla Public 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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Initial Developer of the Original Code is
* Albert Thuswaldner <[email protected]>
* Portions created by the Initial Developer are Copyright (C) 2012 the
* Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 3 or later (the "GPLv3+"), or
* the GNU Lesser General Public License Version 3 or later (the "LGPLv3+"),
* in which case the provisions of the GPLv3+ or the LGPLv3+ are applicable
* instead of those above.
*/
#include <com/sun/star/uno/Any.hxx>
#include <com/sun/star/uno/Sequence.hxx>
#include <com/sun/star/lang/Locale.hpp>
#include <com/sun/star/i18n/LocaleDataItem.hpp>
#include "formulaopt.hxx"
#include "miscuno.hxx"
#include "global.hxx"
using namespace utl;
using namespace com::sun::star::uno;
using ::com::sun::star::lang::Locale;
using ::com::sun::star::i18n::LocaleDataItem;
using ::rtl::OUString;
// -----------------------------------------------------------------------
TYPEINIT1(ScTpFormulaItem, SfxPoolItem);
// -----------------------------------------------------------------------
ScFormulaOptions::ScFormulaOptions()
{
SetDefaults();
}
ScFormulaOptions::ScFormulaOptions( const ScFormulaOptions& rCpy ) :
bUseEnglishFuncName ( rCpy.bUseEnglishFuncName ),
eFormulaGrammar ( rCpy.eFormulaGrammar ),
aFormulaSepArg ( rCpy.aFormulaSepArg ),
aFormulaSepArrayRow ( rCpy.aFormulaSepArrayRow ),
aFormulaSepArrayCol ( rCpy.aFormulaSepArrayCol )
{
}
ScFormulaOptions::~ScFormulaOptions()
{
}
void ScFormulaOptions::SetDefaults()
{
bUseEnglishFuncName = false;
eFormulaGrammar = ::formula::FormulaGrammar::GRAM_NATIVE;
ResetFormulaSeparators();
}
void ScFormulaOptions::ResetFormulaSeparators()
{
GetDefaultFormulaSeparators(aFormulaSepArg, aFormulaSepArrayCol, aFormulaSepArrayRow);
}
void ScFormulaOptions::GetDefaultFormulaSeparators(
rtl::OUString& rSepArg, rtl::OUString& rSepArrayCol, rtl::OUString& rSepArrayRow)
{
// Defaults to the old separator values.
rSepArg = OUString(RTL_CONSTASCII_USTRINGPARAM(";"));
rSepArrayCol = OUString(RTL_CONSTASCII_USTRINGPARAM(";"));
rSepArrayRow = OUString(RTL_CONSTASCII_USTRINGPARAM("|"));
const Locale& rLocale = *ScGlobal::GetLocale();
const OUString& rLang = rLocale.Language;
if (rLang.equalsAsciiL(RTL_CONSTASCII_STRINGPARAM("ru")))
// Don't do automatic guess for these languages, and fall back to
// the old separator set.
return;
const LocaleDataWrapper& rLocaleData = GetLocaleDataWrapper();
const OUString& rDecSep = rLocaleData.getNumDecimalSep();
const OUString& rListSep = rLocaleData.getListSep();
if (rDecSep.isEmpty() || rListSep.isEmpty())
// Something is wrong. Stick with the default separators.
return;
sal_Unicode cDecSep = rDecSep.getStr()[0];
sal_Unicode cListSep = rListSep.getStr()[0];
// Excel by default uses system's list separator as the parameter
// separator, which in English locales is a comma. However, OOo's list
// separator value is set to ';' for all English locales. Because of this
// discrepancy, we will hardcode the separator value here, for now.
if (cDecSep == sal_Unicode('.'))
cListSep = sal_Unicode(',');
// Special case for de_CH locale.
if (rLocale.Language.equalsAsciiL("de", 2) && rLocale.Country.equalsAsciiL("CH", 2))
cListSep = sal_Unicode(';');
// by default, the parameter separator equals the locale-specific
// list separator.
rSepArg = OUString(cListSep);
if (cDecSep == cListSep && cDecSep != sal_Unicode(';'))
// if the decimal and list separators are equal, set the
// parameter separator to be ';', unless they are both
// semicolon in which case don't change the decimal separator.
rSepArg = OUString(RTL_CONSTASCII_USTRINGPARAM(";"));
rSepArrayCol = OUString(RTL_CONSTASCII_USTRINGPARAM(","));
if (cDecSep == sal_Unicode(','))
rSepArrayCol = OUString(RTL_CONSTASCII_USTRINGPARAM("."));
rSepArrayRow = OUString(RTL_CONSTASCII_USTRINGPARAM(";"));
}
const LocaleDataWrapper& ScFormulaOptions::GetLocaleDataWrapper()
{
return *ScGlobal::pLocaleData;
}
ScFormulaOptions& ScFormulaOptions::operator=( const ScFormulaOptions& rCpy )
{
bUseEnglishFuncName = rCpy.bUseEnglishFuncName;
eFormulaGrammar = rCpy.eFormulaGrammar;
aFormulaSepArg = rCpy.aFormulaSepArg;
aFormulaSepArrayRow = rCpy.aFormulaSepArrayRow;
aFormulaSepArrayCol = rCpy.aFormulaSepArrayCol;
return *this;
}
bool ScFormulaOptions::operator==( const ScFormulaOptions& rOpt ) const
{
return bUseEnglishFuncName == rOpt.bUseEnglishFuncName
&& eFormulaGrammar == rOpt.eFormulaGrammar
&& aFormulaSepArg == rOpt.aFormulaSepArg
&& aFormulaSepArrayRow == rOpt.aFormulaSepArrayRow
&& aFormulaSepArrayCol == rOpt.aFormulaSepArrayCol;
}
bool ScFormulaOptions::operator!=( const ScFormulaOptions& rOpt ) const
{
return !(operator==(rOpt));
}
// -----------------------------------------------------------------------
ScTpFormulaItem::ScTpFormulaItem( sal_uInt16 nWhichP, const ScFormulaOptions& rOpt ) :
SfxPoolItem ( nWhichP ),
theOptions ( rOpt )
{
}
ScTpFormulaItem::ScTpFormulaItem( const ScTpFormulaItem& rItem ) :
SfxPoolItem ( rItem ),
theOptions ( rItem.theOptions )
{
}
ScTpFormulaItem::~ScTpFormulaItem()
{
}
String ScTpFormulaItem::GetValueText() const
{
return String::CreateFromAscii( "ScTpFormulaItem" );
}
int ScTpFormulaItem::operator==( const SfxPoolItem& rItem ) const
{
OSL_ENSURE( SfxPoolItem::operator==( rItem ), "unequal Which or Type" );
const ScTpFormulaItem& rPItem = (const ScTpFormulaItem&)rItem;
return ( theOptions == rPItem.theOptions );
}
SfxPoolItem* ScTpFormulaItem::Clone( SfxItemPool * ) const
{
return new ScTpFormulaItem( *this );
}
// -----------------------------------------------------------------------
#define CFGPATH_FORMULA "Office.Calc/Formula"
#define SCFORMULAOPT_GRAMMAR 0
#define SCFORMULAOPT_ENGLISH_FUNCNAME 1
#define SCFORMULAOPT_SEP_ARG 2
#define SCFORMULAOPT_SEP_ARRAY_ROW 3
#define SCFORMULAOPT_SEP_ARRAY_COL 4
#define SCFORMULAOPT_INDIRECT_GRAMMAR 5
#define SCFORMULAOPT_COUNT 6
Sequence<OUString> ScFormulaCfg::GetPropertyNames()
{
static const char* aPropNames[] =
{
"Syntax/Grammar", // SCFORMULAOPT_GRAMMAR
"Syntax/EnglishFunctionName", // SCFORMULAOPT_ENGLISH_FUNCNAME
"Syntax/SeparatorArg", // SCFORMULAOPT_SEP_ARG
"Syntax/SeparatorArrayRow", // SCFORMULAOPT_SEP_ARRAY_ROW
"Syntax/SeparatorArrayCol", // SCFORMULAOPT_SEP_ARRAY_COL
"Syntax/IndirectFuncGrammar", // SCFORMULAOPT_INDIRECT_GRAMMAR
};
Sequence<OUString> aNames(SCFORMULAOPT_COUNT);
OUString* pNames = aNames.getArray();
for (int i = 0; i < SCFORMULAOPT_COUNT; ++i)
pNames[i] = OUString::createFromAscii(aPropNames[i]);
return aNames;
}
ScFormulaCfg::ScFormulaCfg() :
ConfigItem( OUString(RTL_CONSTASCII_USTRINGPARAM( CFGPATH_FORMULA )) )
{
Sequence<OUString> aNames = GetPropertyNames();
Sequence<Any> aValues = GetProperties(aNames);
const Any* pValues = aValues.getConstArray();
OSL_ENSURE(aValues.getLength() == aNames.getLength(), "GetProperties failed");
if(aValues.getLength() == aNames.getLength())
{
sal_Int32 nIntVal = 0;
for(int nProp = 0; nProp < aNames.getLength(); nProp++)
{
if(pValues[nProp].hasValue())
{
switch(nProp)
{
case SCFORMULAOPT_GRAMMAR:
{
// Get default value in case this option is not set.
::formula::FormulaGrammar::Grammar eGram = GetFormulaSyntax();
do
{
if (!(pValues[nProp] >>= nIntVal))
// extractino failed.
break;
switch (nIntVal)
{
case 0: // Calc A1
eGram = ::formula::FormulaGrammar::GRAM_NATIVE;
break;
case 1: // Excel A1
eGram = ::formula::FormulaGrammar::GRAM_NATIVE_XL_A1;
break;
case 2: // Excel R1C1
eGram = ::formula::FormulaGrammar::GRAM_NATIVE_XL_R1C1;
break;
default:
;
}
}
while (false);
SetFormulaSyntax(eGram);
}
break;
case SCFORMULAOPT_ENGLISH_FUNCNAME:
{
sal_Bool bEnglish = false;
if (pValues[nProp] >>= bEnglish)
SetUseEnglishFuncName(bEnglish);
}
break;
case SCFORMULAOPT_SEP_ARG:
{
OUString aSep;
if ((pValues[nProp] >>= aSep) && !aSep.isEmpty())
SetFormulaSepArg(aSep);
}
break;
case SCFORMULAOPT_SEP_ARRAY_ROW:
{
OUString aSep;
if ((pValues[nProp] >>= aSep) && !aSep.isEmpty())
SetFormulaSepArrayRow(aSep);
}
break;
case SCFORMULAOPT_SEP_ARRAY_COL:
{
OUString aSep;
if ((pValues[nProp] >>= aSep) && !aSep.isEmpty())
SetFormulaSepArrayCol(aSep);
}
case SCFORMULAOPT_INDIRECT_GRAMMAR:
{
// Get default value in case this option is not set.
::formula::FormulaGrammar::AddressConvention eConv = GetIndirectFuncSyntax();
do
{
if (!(pValues[nProp] >>= nIntVal))
// extractino failed.
break;
switch (nIntVal)
{
case -1: // Same as the formula grammar.
eConv = formula::FormulaGrammar::CONV_UNSPECIFIED;
break;
case 0: // Calc A1
eConv = formula::FormulaGrammar::CONV_OOO;
break;
case 1: // Excel A1
eConv = formula::FormulaGrammar::CONV_XL_A1;
break;
case 2: // Excel R1C1
eConv = formula::FormulaGrammar::CONV_XL_R1C1;
break;
default:
;
}
}
while (false);
SetIndirectFuncSyntax(eConv);
}
break;
break;
}
}
}
}
}
void ScFormulaCfg::Commit()
{
Sequence<OUString> aNames = GetPropertyNames();
Sequence<Any> aValues(aNames.getLength());
Any* pValues = aValues.getArray();
for (int nProp = 0; nProp < aNames.getLength(); ++nProp)
{
switch (nProp)
{
case SCFORMULAOPT_GRAMMAR :
{
sal_Int32 nVal = 0;
switch (GetFormulaSyntax())
{
case ::formula::FormulaGrammar::GRAM_NATIVE_XL_A1: nVal = 1; break;
case ::formula::FormulaGrammar::GRAM_NATIVE_XL_R1C1: nVal = 2; break;
default: break;
}
pValues[nProp] <<= nVal;
}
break;
case SCFORMULAOPT_ENGLISH_FUNCNAME:
{
sal_Bool b = GetUseEnglishFuncName();
pValues[nProp] <<= b;
}
break;
case SCFORMULAOPT_SEP_ARG:
pValues[nProp] <<= GetFormulaSepArg();
break;
case SCFORMULAOPT_SEP_ARRAY_ROW:
pValues[nProp] <<= GetFormulaSepArrayRow();
break;
case SCFORMULAOPT_SEP_ARRAY_COL:
pValues[nProp] <<= GetFormulaSepArrayCol();
break;
case SCFORMULAOPT_INDIRECT_GRAMMAR:
{
sal_Int32 nVal = -1;
switch (GetIndirectFuncSyntax())
{
case ::formula::FormulaGrammar::CONV_OOO: nVal = 0; break;
case ::formula::FormulaGrammar::CONV_XL_A1: nVal = 1; break;
case ::formula::FormulaGrammar::CONV_XL_R1C1: nVal = 2; break;
default: break;
}
pValues[nProp] <<= nVal;
}
break;
}
}
PutProperties(aNames, aValues);
}
void ScFormulaCfg::SetOptions( const ScFormulaOptions& rNew )
{
*(ScFormulaOptions*)this = rNew;
SetModified();
}
void ScFormulaCfg::Notify( const ::com::sun::star::uno::Sequence< OUString >& ) {}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Reset option.<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* Version: MPL 1.1 / GPLv3+ / LGPLv3+
*
* The contents of this file are subject to the Mozilla Public 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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Initial Developer of the Original Code is
* Albert Thuswaldner <[email protected]>
* Portions created by the Initial Developer are Copyright (C) 2012 the
* Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 3 or later (the "GPLv3+"), or
* the GNU Lesser General Public License Version 3 or later (the "LGPLv3+"),
* in which case the provisions of the GPLv3+ or the LGPLv3+ are applicable
* instead of those above.
*/
#include <com/sun/star/uno/Any.hxx>
#include <com/sun/star/uno/Sequence.hxx>
#include <com/sun/star/lang/Locale.hpp>
#include <com/sun/star/i18n/LocaleDataItem.hpp>
#include "formulaopt.hxx"
#include "miscuno.hxx"
#include "global.hxx"
using namespace utl;
using namespace com::sun::star::uno;
using ::com::sun::star::lang::Locale;
using ::com::sun::star::i18n::LocaleDataItem;
using ::rtl::OUString;
// -----------------------------------------------------------------------
TYPEINIT1(ScTpFormulaItem, SfxPoolItem);
// -----------------------------------------------------------------------
ScFormulaOptions::ScFormulaOptions()
{
SetDefaults();
}
ScFormulaOptions::ScFormulaOptions( const ScFormulaOptions& rCpy ) :
bUseEnglishFuncName ( rCpy.bUseEnglishFuncName ),
eFormulaGrammar ( rCpy.eFormulaGrammar ),
aFormulaSepArg ( rCpy.aFormulaSepArg ),
aFormulaSepArrayRow ( rCpy.aFormulaSepArrayRow ),
aFormulaSepArrayCol ( rCpy.aFormulaSepArrayCol )
{
}
ScFormulaOptions::~ScFormulaOptions()
{
}
void ScFormulaOptions::SetDefaults()
{
bUseEnglishFuncName = false;
eFormulaGrammar = ::formula::FormulaGrammar::GRAM_NATIVE;
// unspecified means use the current formula syntax.
eIndirectFuncRefSyntax = formula::FormulaGrammar::CONV_UNSPECIFIED;
ResetFormulaSeparators();
}
void ScFormulaOptions::ResetFormulaSeparators()
{
GetDefaultFormulaSeparators(aFormulaSepArg, aFormulaSepArrayCol, aFormulaSepArrayRow);
}
void ScFormulaOptions::GetDefaultFormulaSeparators(
rtl::OUString& rSepArg, rtl::OUString& rSepArrayCol, rtl::OUString& rSepArrayRow)
{
// Defaults to the old separator values.
rSepArg = OUString(RTL_CONSTASCII_USTRINGPARAM(";"));
rSepArrayCol = OUString(RTL_CONSTASCII_USTRINGPARAM(";"));
rSepArrayRow = OUString(RTL_CONSTASCII_USTRINGPARAM("|"));
const Locale& rLocale = *ScGlobal::GetLocale();
const OUString& rLang = rLocale.Language;
if (rLang.equalsAsciiL(RTL_CONSTASCII_STRINGPARAM("ru")))
// Don't do automatic guess for these languages, and fall back to
// the old separator set.
return;
const LocaleDataWrapper& rLocaleData = GetLocaleDataWrapper();
const OUString& rDecSep = rLocaleData.getNumDecimalSep();
const OUString& rListSep = rLocaleData.getListSep();
if (rDecSep.isEmpty() || rListSep.isEmpty())
// Something is wrong. Stick with the default separators.
return;
sal_Unicode cDecSep = rDecSep.getStr()[0];
sal_Unicode cListSep = rListSep.getStr()[0];
// Excel by default uses system's list separator as the parameter
// separator, which in English locales is a comma. However, OOo's list
// separator value is set to ';' for all English locales. Because of this
// discrepancy, we will hardcode the separator value here, for now.
if (cDecSep == sal_Unicode('.'))
cListSep = sal_Unicode(',');
// Special case for de_CH locale.
if (rLocale.Language.equalsAsciiL("de", 2) && rLocale.Country.equalsAsciiL("CH", 2))
cListSep = sal_Unicode(';');
// by default, the parameter separator equals the locale-specific
// list separator.
rSepArg = OUString(cListSep);
if (cDecSep == cListSep && cDecSep != sal_Unicode(';'))
// if the decimal and list separators are equal, set the
// parameter separator to be ';', unless they are both
// semicolon in which case don't change the decimal separator.
rSepArg = OUString(RTL_CONSTASCII_USTRINGPARAM(";"));
rSepArrayCol = OUString(RTL_CONSTASCII_USTRINGPARAM(","));
if (cDecSep == sal_Unicode(','))
rSepArrayCol = OUString(RTL_CONSTASCII_USTRINGPARAM("."));
rSepArrayRow = OUString(RTL_CONSTASCII_USTRINGPARAM(";"));
}
const LocaleDataWrapper& ScFormulaOptions::GetLocaleDataWrapper()
{
return *ScGlobal::pLocaleData;
}
ScFormulaOptions& ScFormulaOptions::operator=( const ScFormulaOptions& rCpy )
{
bUseEnglishFuncName = rCpy.bUseEnglishFuncName;
eFormulaGrammar = rCpy.eFormulaGrammar;
aFormulaSepArg = rCpy.aFormulaSepArg;
aFormulaSepArrayRow = rCpy.aFormulaSepArrayRow;
aFormulaSepArrayCol = rCpy.aFormulaSepArrayCol;
return *this;
}
bool ScFormulaOptions::operator==( const ScFormulaOptions& rOpt ) const
{
return bUseEnglishFuncName == rOpt.bUseEnglishFuncName
&& eFormulaGrammar == rOpt.eFormulaGrammar
&& aFormulaSepArg == rOpt.aFormulaSepArg
&& aFormulaSepArrayRow == rOpt.aFormulaSepArrayRow
&& aFormulaSepArrayCol == rOpt.aFormulaSepArrayCol;
}
bool ScFormulaOptions::operator!=( const ScFormulaOptions& rOpt ) const
{
return !(operator==(rOpt));
}
// -----------------------------------------------------------------------
ScTpFormulaItem::ScTpFormulaItem( sal_uInt16 nWhichP, const ScFormulaOptions& rOpt ) :
SfxPoolItem ( nWhichP ),
theOptions ( rOpt )
{
}
ScTpFormulaItem::ScTpFormulaItem( const ScTpFormulaItem& rItem ) :
SfxPoolItem ( rItem ),
theOptions ( rItem.theOptions )
{
}
ScTpFormulaItem::~ScTpFormulaItem()
{
}
String ScTpFormulaItem::GetValueText() const
{
return String::CreateFromAscii( "ScTpFormulaItem" );
}
int ScTpFormulaItem::operator==( const SfxPoolItem& rItem ) const
{
OSL_ENSURE( SfxPoolItem::operator==( rItem ), "unequal Which or Type" );
const ScTpFormulaItem& rPItem = (const ScTpFormulaItem&)rItem;
return ( theOptions == rPItem.theOptions );
}
SfxPoolItem* ScTpFormulaItem::Clone( SfxItemPool * ) const
{
return new ScTpFormulaItem( *this );
}
// -----------------------------------------------------------------------
#define CFGPATH_FORMULA "Office.Calc/Formula"
#define SCFORMULAOPT_GRAMMAR 0
#define SCFORMULAOPT_ENGLISH_FUNCNAME 1
#define SCFORMULAOPT_SEP_ARG 2
#define SCFORMULAOPT_SEP_ARRAY_ROW 3
#define SCFORMULAOPT_SEP_ARRAY_COL 4
#define SCFORMULAOPT_INDIRECT_GRAMMAR 5
#define SCFORMULAOPT_COUNT 6
Sequence<OUString> ScFormulaCfg::GetPropertyNames()
{
static const char* aPropNames[] =
{
"Syntax/Grammar", // SCFORMULAOPT_GRAMMAR
"Syntax/EnglishFunctionName", // SCFORMULAOPT_ENGLISH_FUNCNAME
"Syntax/SeparatorArg", // SCFORMULAOPT_SEP_ARG
"Syntax/SeparatorArrayRow", // SCFORMULAOPT_SEP_ARRAY_ROW
"Syntax/SeparatorArrayCol", // SCFORMULAOPT_SEP_ARRAY_COL
"Syntax/IndirectFuncGrammar", // SCFORMULAOPT_INDIRECT_GRAMMAR
};
Sequence<OUString> aNames(SCFORMULAOPT_COUNT);
OUString* pNames = aNames.getArray();
for (int i = 0; i < SCFORMULAOPT_COUNT; ++i)
pNames[i] = OUString::createFromAscii(aPropNames[i]);
return aNames;
}
ScFormulaCfg::ScFormulaCfg() :
ConfigItem( OUString(RTL_CONSTASCII_USTRINGPARAM( CFGPATH_FORMULA )) )
{
Sequence<OUString> aNames = GetPropertyNames();
Sequence<Any> aValues = GetProperties(aNames);
const Any* pValues = aValues.getConstArray();
OSL_ENSURE(aValues.getLength() == aNames.getLength(), "GetProperties failed");
if(aValues.getLength() == aNames.getLength())
{
sal_Int32 nIntVal = 0;
for(int nProp = 0; nProp < aNames.getLength(); nProp++)
{
if(pValues[nProp].hasValue())
{
switch(nProp)
{
case SCFORMULAOPT_GRAMMAR:
{
// Get default value in case this option is not set.
::formula::FormulaGrammar::Grammar eGram = GetFormulaSyntax();
do
{
if (!(pValues[nProp] >>= nIntVal))
// extractino failed.
break;
switch (nIntVal)
{
case 0: // Calc A1
eGram = ::formula::FormulaGrammar::GRAM_NATIVE;
break;
case 1: // Excel A1
eGram = ::formula::FormulaGrammar::GRAM_NATIVE_XL_A1;
break;
case 2: // Excel R1C1
eGram = ::formula::FormulaGrammar::GRAM_NATIVE_XL_R1C1;
break;
default:
;
}
}
while (false);
SetFormulaSyntax(eGram);
}
break;
case SCFORMULAOPT_ENGLISH_FUNCNAME:
{
sal_Bool bEnglish = false;
if (pValues[nProp] >>= bEnglish)
SetUseEnglishFuncName(bEnglish);
}
break;
case SCFORMULAOPT_SEP_ARG:
{
OUString aSep;
if ((pValues[nProp] >>= aSep) && !aSep.isEmpty())
SetFormulaSepArg(aSep);
}
break;
case SCFORMULAOPT_SEP_ARRAY_ROW:
{
OUString aSep;
if ((pValues[nProp] >>= aSep) && !aSep.isEmpty())
SetFormulaSepArrayRow(aSep);
}
break;
case SCFORMULAOPT_SEP_ARRAY_COL:
{
OUString aSep;
if ((pValues[nProp] >>= aSep) && !aSep.isEmpty())
SetFormulaSepArrayCol(aSep);
}
case SCFORMULAOPT_INDIRECT_GRAMMAR:
{
// Get default value in case this option is not set.
::formula::FormulaGrammar::AddressConvention eConv = GetIndirectFuncSyntax();
do
{
if (!(pValues[nProp] >>= nIntVal))
// extractino failed.
break;
switch (nIntVal)
{
case -1: // Same as the formula grammar.
eConv = formula::FormulaGrammar::CONV_UNSPECIFIED;
break;
case 0: // Calc A1
eConv = formula::FormulaGrammar::CONV_OOO;
break;
case 1: // Excel A1
eConv = formula::FormulaGrammar::CONV_XL_A1;
break;
case 2: // Excel R1C1
eConv = formula::FormulaGrammar::CONV_XL_R1C1;
break;
default:
;
}
}
while (false);
SetIndirectFuncSyntax(eConv);
}
break;
break;
}
}
}
}
}
void ScFormulaCfg::Commit()
{
Sequence<OUString> aNames = GetPropertyNames();
Sequence<Any> aValues(aNames.getLength());
Any* pValues = aValues.getArray();
for (int nProp = 0; nProp < aNames.getLength(); ++nProp)
{
switch (nProp)
{
case SCFORMULAOPT_GRAMMAR :
{
sal_Int32 nVal = 0;
switch (GetFormulaSyntax())
{
case ::formula::FormulaGrammar::GRAM_NATIVE_XL_A1: nVal = 1; break;
case ::formula::FormulaGrammar::GRAM_NATIVE_XL_R1C1: nVal = 2; break;
default: break;
}
pValues[nProp] <<= nVal;
}
break;
case SCFORMULAOPT_ENGLISH_FUNCNAME:
{
sal_Bool b = GetUseEnglishFuncName();
pValues[nProp] <<= b;
}
break;
case SCFORMULAOPT_SEP_ARG:
pValues[nProp] <<= GetFormulaSepArg();
break;
case SCFORMULAOPT_SEP_ARRAY_ROW:
pValues[nProp] <<= GetFormulaSepArrayRow();
break;
case SCFORMULAOPT_SEP_ARRAY_COL:
pValues[nProp] <<= GetFormulaSepArrayCol();
break;
case SCFORMULAOPT_INDIRECT_GRAMMAR:
{
sal_Int32 nVal = -1;
switch (GetIndirectFuncSyntax())
{
case ::formula::FormulaGrammar::CONV_OOO: nVal = 0; break;
case ::formula::FormulaGrammar::CONV_XL_A1: nVal = 1; break;
case ::formula::FormulaGrammar::CONV_XL_R1C1: nVal = 2; break;
default: break;
}
pValues[nProp] <<= nVal;
}
break;
}
}
PutProperties(aNames, aValues);
}
void ScFormulaCfg::SetOptions( const ScFormulaOptions& rNew )
{
*(ScFormulaOptions*)this = rNew;
SetModified();
}
void ScFormulaCfg::Notify( const ::com::sun::star::uno::Sequence< OUString >& ) {}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>#include "paddle/framework/grad_op_builder.h"
#include <gtest/gtest.h>
#include "paddle/framework/op_registry.h"
#include "paddle/framework/operator.h"
USE_OP(add);
namespace paddle {
namespace framework {
class MutiInOutOpMaker : public OpProtoAndCheckerMaker {
public:
MutiInOutOpMaker(OpProto *proto, OpAttrChecker *op_checker)
: OpProtoAndCheckerMaker(proto, op_checker) {
AddInput("In1", "a single input");
AddInput("In2_mult", "a multiple input").AsDuplicable();
AddInput("In3", "another single input");
AddOutput("Out1", "a single output");
AddOutput("Out2_mult", "a multiple output").AsDuplicable();
AddComment("test op with multiple inputs and outputs");
}
};
class IOIgnoredOpMaker : public OpProtoAndCheckerMaker {
public:
IOIgnoredOpMaker(OpProto *proto, OpAttrChecker *op_checker)
: OpProtoAndCheckerMaker(proto, op_checker) {
AddInput("In1", "a single input");
AddInput("In2_mult", "a multiple input").AsDuplicable().NotInGradient();
AddInput("In3_mult", "another multiple input").AsDuplicable();
AddOutput("Out1_mult", "a multiple output").AsDuplicable();
AddOutput("Out2", "a single output").NotInGradient();
AddComment("op with inputs and outputs ignored in gradient calculating");
}
};
} // namespace framework
} // namespace paddle
namespace f = paddle::framework;
TEST(GradOpBuilder, AddTwo) {
std::shared_ptr<f::OperatorBase> add_op(f::OpRegistry::CreateOp(
"add", {{"X", {"x"}}, {"Y", {"y"}}}, {{"Out", {"out"}}}, {}));
std::shared_ptr<f::OperatorBase> grad_add_op =
f::OpRegistry::CreateGradOp(*add_op);
EXPECT_EQ(grad_add_op->Inputs().size(), 4UL);
EXPECT_EQ(grad_add_op->Outputs().size(), 2UL);
EXPECT_EQ(grad_add_op->Input("X"), "x");
EXPECT_EQ(grad_add_op->Input("Y"), "y");
EXPECT_EQ(grad_add_op->Input("Out"), "out");
EXPECT_EQ(grad_add_op->Input(f::GradVarName("Out")), f::GradVarName("out"));
EXPECT_EQ(grad_add_op->Output(f::GradVarName("X")), f::GradVarName("x"));
EXPECT_EQ(grad_add_op->Output(f::GradVarName("Y")), f::GradVarName("y"));
}
REGISTER_OP(mult_io, f::NOP, f::MutiInOutOpMaker, mult_io_grad, f::NOP);
REGISTER_OP(io_ignored, f::NOP, f::IOIgnoredOpMaker, io_ignored_grad, f::NOP);
TEST(GradOpBuilder, MutiInOut) {
std::shared_ptr<f::OperatorBase> test_op(f::OpRegistry::CreateOp(
"mult_io", {{"In1", {"in1"}},
{"In2_mult", {"in2_1", "in2_2", "in2_3"}},
{"In3", {"in3"}}},
{{"Out1", {"out1"}}, {"Out2_mult", {"out2_1", "out2_2"}}}, {}));
std::shared_ptr<f::OperatorBase> grad_test_op =
f::OpRegistry::CreateGradOp(*test_op);
ASSERT_EQ(grad_test_op->Inputs().size(), 3UL + 2UL + 2UL);
EXPECT_EQ(grad_test_op->Input("In1"), "in1");
EXPECT_EQ(grad_test_op->Inputs("In2_mult"),
std::vector<std::string>({"in2_1", "in2_2", "in2_3"}));
EXPECT_EQ(grad_test_op->Input("In3"), "in3");
EXPECT_EQ(grad_test_op->Input("Out1"), "out1");
EXPECT_EQ(grad_test_op->Inputs("Out2_mult"),
std::vector<std::string>({"out2_1", "out2_2"}));
EXPECT_EQ(grad_test_op->Input(f::GradVarName("Out1")),
f::GradVarName("out1"));
EXPECT_EQ(grad_test_op->Inputs(f::GradVarName("Out2_mult")),
std::vector<std::string>(
{f::GradVarName("out2_1"), f::GradVarName("out2_2")}));
ASSERT_EQ(grad_test_op->Outputs().size(), 3UL);
EXPECT_EQ(grad_test_op->Output(f::GradVarName("In1")), f::GradVarName("in1"));
EXPECT_EQ(grad_test_op->Outputs(f::GradVarName("In2_mult")),
std::vector<std::string>({f::GradVarName("in2_1"),
f::GradVarName("in2_2"),
f::GradVarName("in2_3")}));
EXPECT_EQ(grad_test_op->Output(f::GradVarName("In3")), f::GradVarName("in3"));
}
TEST(GradOpBuilder, IOIgnoredInGradient) {
std::shared_ptr<f::OperatorBase> test_op(f::OpRegistry::CreateOp(
"io_ignored", {{"In1", {"in1"}},
{"In2_mult", {"in2_1", "in2_2"}},
{"In3_mult", {"in3_1", "in3_2"}}},
{{"Out1_mult", {"out1_1", "out1_2"}}, {"Out2", {"out2"}}}, {}));
std::shared_ptr<f::OperatorBase> grad_test_op =
f::OpRegistry::CreateGradOp(*test_op);
// 'In2' and 'Out2' are ignored in gradient calculating
ASSERT_EQ(grad_test_op->Inputs().size(), 2UL + 1UL + 2UL);
EXPECT_EQ(grad_test_op->Input("In1"), "in1");
EXPECT_EQ(grad_test_op->Inputs("In3_mult"),
std::vector<std::string>({"in3_1", "in3_2"}));
EXPECT_EQ(grad_test_op->Inputs("Out1_mult"),
std::vector<std::string>({"out1_1", "out1_2"}));
EXPECT_EQ(grad_test_op->Inputs(f::GradVarName("Out1_mult")),
std::vector<std::string>(
{f::GradVarName("out1_1"), f::GradVarName("out1_2")}));
EXPECT_EQ(grad_test_op->Input(f::GradVarName("Out2")),
f::GradVarName("out2"));
ASSERT_EQ(grad_test_op->Outputs().size(), 3UL);
EXPECT_EQ(grad_test_op->Output(f::GradVarName("In1")), f::GradVarName("in1"));
EXPECT_EQ(grad_test_op->Outputs(f::GradVarName("In2_mult")),
std::vector<std::string>(
{f::GradVarName("in2_1"), f::GradVarName("in2_2")}));
EXPECT_EQ(grad_test_op->Outputs(f::GradVarName("In3_mult")),
std::vector<std::string>(
{f::GradVarName("in3_1"), f::GradVarName("in3_2")}));
}
TEST(GradOpDescBuilder, MutiInOut) {
f::OpDescBind *forw_op = new f::OpDescBind();
forw_op->SetType("mult_io");
forw_op->SetInput("In1", {"in1"});
forw_op->SetInput("In2_mult", {"in2_1", "in2_2", "in2_3"});
forw_op->SetInput("In3", {"in3"});
forw_op->SetOutput("Out1", {"out1"});
forw_op->SetOutput("Out2_mult", {"out2_1", "out2_2"});
f::OpDescBind *grad_op = new f::OpDescBind();
f::CompleteGradOpDesc(forw_op, grad_op);
ASSERT_EQ(grad_op->InputNames().size(), 3UL + 2UL + 2UL);
EXPECT_EQ(grad_op->Input("In1"), std::vector<std::string>({"in1"}));
EXPECT_EQ(grad_op->Input("In2_mult"),
std::vector<std::string>({"in2_1", "in2_2", "in2_3"}));
EXPECT_EQ(grad_op->Input("In3"), std::vector<std::string>({"in3"}));
EXPECT_EQ(grad_op->Input("Out1"), std::vector<std::string>({"out1"}));
EXPECT_EQ(grad_op->Input("Out2_mult"),
std::vector<std::string>({"out2_1", "out2_2"}));
EXPECT_EQ(grad_op->Input(f::GradVarName("Out1")),
std::vector<std::string>({f::GradVarName("out1")}));
EXPECT_EQ(grad_op->Input(f::GradVarName("Out2_mult")),
std::vector<std::string>(
{f::GradVarName("out2_1"), f::GradVarName("out2_2")}));
ASSERT_EQ(grad_op->OutputNames().size(), 3UL);
EXPECT_EQ(grad_op->Output(f::GradVarName("In1")),
std::vector<std::string>({f::GradVarName("in1")}));
EXPECT_EQ(grad_op->Output(f::GradVarName("In2_mult")),
std::vector<std::string>({f::GradVarName("in2_1"),
f::GradVarName("in2_2"),
f::GradVarName("in2_3")}));
EXPECT_EQ(grad_op->Output(f::GradVarName("In3")),
std::vector<std::string>({f::GradVarName("in3")}));
}
<commit_msg>Add unit tests<commit_after>#include "paddle/framework/grad_op_builder.h"
#include <gtest/gtest.h>
#include "paddle/framework/op_registry.h"
#include "paddle/framework/operator.h"
USE_OP(add);
namespace paddle {
namespace framework {
class MutiInOutOpMaker : public OpProtoAndCheckerMaker {
public:
MutiInOutOpMaker(OpProto *proto, OpAttrChecker *op_checker)
: OpProtoAndCheckerMaker(proto, op_checker) {
AddInput("In1", "a single input");
AddInput("In2_mult", "a multiple input").AsDuplicable();
AddInput("In3", "another single input");
AddOutput("Out1", "a single output");
AddOutput("Out2_mult", "a multiple output").AsDuplicable();
AddComment("test op with multiple inputs and outputs");
}
};
class IOIgnoredOpMaker : public OpProtoAndCheckerMaker {
public:
IOIgnoredOpMaker(OpProto *proto, OpAttrChecker *op_checker)
: OpProtoAndCheckerMaker(proto, op_checker) {
AddInput("In1", "a single input");
AddInput("In2_mult", "a multiple input").AsDuplicable().NotInGradient();
AddInput("In3_mult", "another multiple input").AsDuplicable();
AddOutput("Out1_mult", "a multiple output").AsDuplicable();
AddOutput("Out2", "a single output").NotInGradient();
AddComment("op with inputs and outputs ignored in gradient calculating");
}
};
} // namespace framework
} // namespace paddle
namespace f = paddle::framework;
TEST(GradOpBuilder, AddTwo) {
std::shared_ptr<f::OperatorBase> add_op(f::OpRegistry::CreateOp(
"add", {{"X", {"x"}}, {"Y", {"y"}}}, {{"Out", {"out"}}}, {}));
std::shared_ptr<f::OperatorBase> grad_add_op =
f::OpRegistry::CreateGradOp(*add_op);
EXPECT_EQ(grad_add_op->Inputs().size(), 4UL);
EXPECT_EQ(grad_add_op->Outputs().size(), 2UL);
EXPECT_EQ(grad_add_op->Input("X"), "x");
EXPECT_EQ(grad_add_op->Input("Y"), "y");
EXPECT_EQ(grad_add_op->Input("Out"), "out");
EXPECT_EQ(grad_add_op->Input(f::GradVarName("Out")), f::GradVarName("out"));
EXPECT_EQ(grad_add_op->Output(f::GradVarName("X")), f::GradVarName("x"));
EXPECT_EQ(grad_add_op->Output(f::GradVarName("Y")), f::GradVarName("y"));
}
REGISTER_OP(mult_io, f::NOP, f::MutiInOutOpMaker, mult_io_grad, f::NOP);
REGISTER_OP(io_ignored, f::NOP, f::IOIgnoredOpMaker, io_ignored_grad, f::NOP);
TEST(GradOpBuilder, MutiInOut) {
std::shared_ptr<f::OperatorBase> test_op(f::OpRegistry::CreateOp(
"mult_io", {{"In1", {"in1"}},
{"In2_mult", {"in2_1", "in2_2", "in2_3"}},
{"In3", {"in3"}}},
{{"Out1", {"out1"}}, {"Out2_mult", {"out2_1", "out2_2"}}}, {}));
std::shared_ptr<f::OperatorBase> grad_test_op =
f::OpRegistry::CreateGradOp(*test_op);
ASSERT_EQ(grad_test_op->Inputs().size(), 3UL + 2UL + 2UL);
EXPECT_EQ(grad_test_op->Input("In1"), "in1");
EXPECT_EQ(grad_test_op->Inputs("In2_mult"),
std::vector<std::string>({"in2_1", "in2_2", "in2_3"}));
EXPECT_EQ(grad_test_op->Input("In3"), "in3");
EXPECT_EQ(grad_test_op->Input("Out1"), "out1");
EXPECT_EQ(grad_test_op->Inputs("Out2_mult"),
std::vector<std::string>({"out2_1", "out2_2"}));
EXPECT_EQ(grad_test_op->Input(f::GradVarName("Out1")),
f::GradVarName("out1"));
EXPECT_EQ(grad_test_op->Inputs(f::GradVarName("Out2_mult")),
std::vector<std::string>(
{f::GradVarName("out2_1"), f::GradVarName("out2_2")}));
ASSERT_EQ(grad_test_op->Outputs().size(), 3UL);
EXPECT_EQ(grad_test_op->Output(f::GradVarName("In1")), f::GradVarName("in1"));
EXPECT_EQ(grad_test_op->Outputs(f::GradVarName("In2_mult")),
std::vector<std::string>({f::GradVarName("in2_1"),
f::GradVarName("in2_2"),
f::GradVarName("in2_3")}));
EXPECT_EQ(grad_test_op->Output(f::GradVarName("In3")), f::GradVarName("in3"));
}
TEST(GradOpBuilder, IOIgnoredInGradient) {
std::shared_ptr<f::OperatorBase> test_op(f::OpRegistry::CreateOp(
"io_ignored", {{"In1", {"in1"}},
{"In2_mult", {"in2_1", "in2_2"}},
{"In3_mult", {"in3_1", "in3_2"}}},
{{"Out1_mult", {"out1_1", "out1_2"}}, {"Out2", {"out2"}}}, {}));
std::shared_ptr<f::OperatorBase> grad_test_op =
f::OpRegistry::CreateGradOp(*test_op);
// 'In2' and 'Out2' are ignored in gradient calculating
ASSERT_EQ(grad_test_op->Inputs().size(), 2UL + 1UL + 2UL);
EXPECT_EQ(grad_test_op->Input("In1"), "in1");
EXPECT_EQ(grad_test_op->Inputs("In3_mult"),
std::vector<std::string>({"in3_1", "in3_2"}));
EXPECT_EQ(grad_test_op->Inputs("Out1_mult"),
std::vector<std::string>({"out1_1", "out1_2"}));
EXPECT_EQ(grad_test_op->Inputs(f::GradVarName("Out1_mult")),
std::vector<std::string>(
{f::GradVarName("out1_1"), f::GradVarName("out1_2")}));
EXPECT_EQ(grad_test_op->Input(f::GradVarName("Out2")),
f::GradVarName("out2"));
ASSERT_EQ(grad_test_op->Outputs().size(), 3UL);
EXPECT_EQ(grad_test_op->Output(f::GradVarName("In1")), f::GradVarName("in1"));
EXPECT_EQ(grad_test_op->Outputs(f::GradVarName("In2_mult")),
std::vector<std::string>(
{f::GradVarName("in2_1"), f::GradVarName("in2_2")}));
EXPECT_EQ(grad_test_op->Outputs(f::GradVarName("In3_mult")),
std::vector<std::string>(
{f::GradVarName("in3_1"), f::GradVarName("in3_2")}));
}
TEST(GradOpDescBuilder, MutiInOut) {
f::OpDescBind *forw_op = new f::OpDescBind();
forw_op->SetType("mult_io");
forw_op->SetInput("In1", {"in1"});
forw_op->SetInput("In2_mult", {"in2_1", "in2_2", "in2_3"});
forw_op->SetInput("In3", {"in3"});
forw_op->SetOutput("Out1", {"out1"});
forw_op->SetOutput("Out2_mult", {"out2_1", "out2_2"});
f::OpDescBind *grad_op = new f::OpDescBind();
f::CompleteGradOpDesc(forw_op, grad_op);
EXPECT_EQ(grad_op->Type(), "mult_io_grad");
ASSERT_EQ(grad_op->InputNames().size(), 3UL + 2UL + 2UL);
EXPECT_EQ(grad_op->Input("In1"), std::vector<std::string>({"in1"}));
EXPECT_EQ(grad_op->Input("In2_mult"),
std::vector<std::string>({"in2_1", "in2_2", "in2_3"}));
EXPECT_EQ(grad_op->Input("In3"), std::vector<std::string>({"in3"}));
EXPECT_EQ(grad_op->Input("Out1"), std::vector<std::string>({"out1"}));
EXPECT_EQ(grad_op->Input("Out2_mult"),
std::vector<std::string>({"out2_1", "out2_2"}));
EXPECT_EQ(grad_op->Input(f::GradVarName("Out1")),
std::vector<std::string>({f::GradVarName("out1")}));
EXPECT_EQ(grad_op->Input(f::GradVarName("Out2_mult")),
std::vector<std::string>(
{f::GradVarName("out2_1"), f::GradVarName("out2_2")}));
ASSERT_EQ(grad_op->OutputNames().size(), 3UL);
EXPECT_EQ(grad_op->Output(f::GradVarName("In1")),
std::vector<std::string>({f::GradVarName("in1")}));
EXPECT_EQ(grad_op->Output(f::GradVarName("In2_mult")),
std::vector<std::string>({f::GradVarName("in2_1"),
f::GradVarName("in2_2"),
f::GradVarName("in2_3")}));
EXPECT_EQ(grad_op->Output(f::GradVarName("In3")),
std::vector<std::string>({f::GradVarName("in3")}));
delete forw_op;
delete grad_op;
}
TEST(GradOpDescBuilder, IOIgnoredInGradient) {
f::OpDescBind *forw_op = new f::OpDescBind();
forw_op->SetType("io_ignored");
forw_op->SetInput("In1", {"in1"});
forw_op->SetInput("In2_mult", {"in2_1", "in2_2"});
forw_op->SetInput("In3_mult", {"in3_1", "in3_2"});
forw_op->SetOutput("Out1_mult", {"out1_1", "out1_2"});
forw_op->SetOutput("Out2", {"out2"});
f::OpDescBind *grad_op = new f::OpDescBind();
f::CompleteGradOpDesc(forw_op, grad_op);
EXPECT_EQ(grad_op->Type(), "io_ignored_grad");
// 'In2' and 'Out2' are ignored in gradient calculating
ASSERT_EQ(grad_op->InputNames().size(), 2UL + 1UL + 2UL);
EXPECT_EQ(grad_op->Input("In1"), std::vector<std::string>({"in1"}));
EXPECT_EQ(grad_op->Input("In3_mult"),
std::vector<std::string>({"in3_1", "in3_2"}));
EXPECT_EQ(grad_op->Input("Out1_mult"),
std::vector<std::string>({"out1_1", "out1_2"}));
EXPECT_EQ(grad_op->Input(f::GradVarName("Out1_mult")),
std::vector<std::string>(
{f::GradVarName("out1_1"), f::GradVarName("out1_2")}));
EXPECT_EQ(grad_op->Input(f::GradVarName("Out2")),
std::vector<std::string>({f::GradVarName("out2")}));
ASSERT_EQ(grad_op->OutputNames().size(), 3UL);
EXPECT_EQ(grad_op->Output(f::GradVarName("In1")),
std::vector<std::string>({f::GradVarName("in1")}));
EXPECT_EQ(grad_op->Output(f::GradVarName("In2_mult")),
std::vector<std::string>(
{f::GradVarName("in2_1"), f::GradVarName("in2_2")}));
EXPECT_EQ(grad_op->Output(f::GradVarName("In3_mult")),
std::vector<std::string>(
{f::GradVarName("in3_1"), f::GradVarName("in3_2")}));
delete forw_op;
delete grad_op;
}<|endoftext|> |
<commit_before>/* http_bidder_interface.cc
Eric Robert, 2 April 2014
Copyright (c) 2011 Datacratic. All rights reserved.
*/
#include "http_bidder_interface.h"
#include "jml/db/persistent.h"
#include "soa/service/http_client.h"
#include "rtbkit/common/messages.h"
#include "rtbkit/plugins/bid_request/openrtb_bid_request.h"
#include "rtbkit/openrtb/openrtb_parsing.h"
#include "rtbkit/core/router/router.h"
using namespace Datacratic;
using namespace RTBKIT;
namespace {
DefaultDescription<OpenRTB::BidRequest> desc;
void tagRequest(OpenRTB::BidRequest &request,
const std::map<std::string, BidInfo> &bidders)
{
for (const auto &bidder: bidders) {
const auto &agentConfig = bidder.second.agentConfig;
const auto &spots = bidder.second.imp;
const auto &creatives = agentConfig->creatives;
Json::Value creativesValue(Json::arrayValue);
for (const auto &spot: spots) {
const int adSpotIndex = spot.first;
ExcCheck(adSpotIndex >= 0 && adSpotIndex < request.imp.size(),
"adSpotIndex out of range");
auto &imp = request.imp[adSpotIndex];
auto &ext = imp.ext;
for (int creativeIndex: spot.second) {
ExcCheck(creativeIndex >= 0 && creativeIndex < creatives.size(),
"creativeIndex out of range");
const int creativeId = creatives[creativeIndex].id;
creativesValue.append(creativeId);
}
ext["allowed_ids"][std::to_string(agentConfig->externalId)] =
std::move(creativesValue);
}
}
}
}
HttpBidderInterface::HttpBidderInterface(std::string name,
std::shared_ptr<ServiceProxies> proxies,
Json::Value const & json) {
host = json["host"].asString();
path = json["path"].asString();
httpClient.reset(new HttpClient(host));
loop.addSource("HttpBidderInterface::httpClient", httpClient);
}
void HttpBidderInterface::sendAuctionMessage(std::shared_ptr<Auction> const & auction,
double timeLeftMs,
std::map<std::string, BidInfo> const & bidders) {
using namespace std;
for(auto & item : bidders) {
auto & agent = item.first;
auto & info = router->agents[agent];
const auto &config = info.config;
BidRequest originalRequest = *auction->request;
WinCostModel wcm = auction->exchangeConnector->getWinCostModel(*auction, *info.config);
OpenRTB::BidRequest openRtbRequest = toOpenRtb(originalRequest);
bool ok = prepareRequest(openRtbRequest, originalRequest, bidders);
/* If we took too much time processing the request, then we don't send it.
Instead, we're making null bids for each impression
*/
if (!ok) {
Bids bids;
for_each(begin(openRtbRequest.imp), end(openRtbRequest.imp),
[&](const OpenRTB::Impression &imp) {
Bid theBid;
theBid.price = USD_CPM(0);
bids.push_back(move(theBid));
});
submitBids(agent, auction->id, bids, wcm);
return;
}
StructuredJsonPrintingContext context;
desc.printJson(&openRtbRequest, context);
auto requestStr = context.output.toString();
/* We need to capture by copy inside the lambda otherwise we might get
a dangling reference if we go out of scope before receiving the http response
*/
auto callbacks = std::make_shared<HttpClientSimpleCallbacks>(
[=](const HttpRequest &, HttpClientError errorCode,
int, const std::string &, const std::string &body)
{
if (errorCode != HttpClientError::NONE) {
auto toErrorString = [](HttpClientError code) -> std::string {
switch (code) {
#define CASE(code) \
case code: \
return #code;
CASE(HttpClientError::NONE)
CASE(HttpClientError::UNKNOWN)
CASE(HttpClientError::TIMEOUT)
CASE(HttpClientError::HOST_NOT_FOUND)
CASE(HttpClientError::COULD_NOT_CONNECT)
#undef CASE
}
ExcCheck(false, "Invalid code path");
return "";
};
cerr << "Error requesting " << host
<< ": " << toErrorString(errorCode);
}
else {
// cerr << "Response: " << body << endl;
OpenRTB::BidResponse response;
ML::Parse_Context context("payload",
body.c_str(), body.size());
StreamingJsonParsingContext jsonContext(context);
static DefaultDescription<OpenRTB::BidResponse> respDesc;
respDesc.parseJson(&response, jsonContext);
for (const auto &seatbid: response.seatbid) {
Bids bids;
for (const auto &bid: seatbid.bid) {
Bid theBid;
/* Looping over the creatives to find the corresponding
creativeIndex
*/
int crid = bid.crid.toInt();
auto crIt = find_if(
begin(config->creatives), end(config->creatives),
[&](const Creative &creative) {
return creative.id == crid;
});
if (crIt == end(config->creatives)) {
throw ML::Exception(ML::format(
"Unknown creative id: %d", crid));
}
auto creativeIndex = distance(begin(config->creatives),
crIt);
theBid.creativeIndex = creativeIndex;
theBid.price = USD_CPM(bid.price.val);
theBid.priority = 0.0;
/* Looping over the impressions to find the corresponding
adSpotIndex
*/
auto impIt = find_if(
begin(openRtbRequest.imp), end(openRtbRequest.imp),
[&](const OpenRTB::Impression &imp) {
return imp.id == bid.impid;
});
if (impIt == end(openRtbRequest.imp)) {
throw ML::Exception(ML::format(
"Unknown impression id: %s", bid.impid.toString()));
}
auto spotIndex = distance(begin(openRtbRequest.imp),
impIt);
theBid.spotIndex = spotIndex;
bids.push_back(std::move(theBid));
}
submitBids(agent, auction->id, bids, wcm);
}
}
}
);
HttpRequest::Content reqContent { requestStr, "application/json" };
RestParams headers { { "x-openrtb-version", "2.1" } };
// std::cerr << "Sending HTTP POST to: " << host << " " << path << std::endl;
// std::cerr << "Content " << reqContent.str << std::endl;
httpClient->post(path, callbacks, reqContent,
{ } /* queryParams */, headers);
}
}
void HttpBidderInterface::sendWinMessage(std::string const & agent,
std::string const & id,
Amount price) {
}
void HttpBidderInterface::sendWinMessage(std::string const & agent,
Amount price,
FinishedInfo const & event) {
}
void HttpBidderInterface::sendLateWinMessage(std::string const & agent,
Amount price,
FinishedInfo const & event) {
}
void HttpBidderInterface::sendLossMessage(std::string const & agent,
std::string const & id) {
}
void HttpBidderInterface::sendLossMessage(std::string const & agent,
FinishedInfo const & event) {
}
void HttpBidderInterface::sendCampaignEventMessage(std::string const & agent,
std::string const & label,
FinishedInfo const & event) {
}
void HttpBidderInterface::sendBidLostMessage(std::string const & agent,
std::shared_ptr<Auction> const & auction) {
}
void HttpBidderInterface::sendBidDroppedMessage(std::string const & agent,
std::shared_ptr<Auction> const & auction) {
}
void HttpBidderInterface::sendBidInvalidMessage(std::string const & agent,
std::string const & reason,
std::shared_ptr<Auction> const & auction) {
}
void HttpBidderInterface::sendNoBudgetMessage(std::string const & agent,
std::shared_ptr<Auction> const & auction) {
}
void HttpBidderInterface::sendTooLateMessage(std::string const & agent,
std::shared_ptr<Auction> const & auction) {
}
void HttpBidderInterface::sendMessage(std::string const & agent,
std::string const & message) {
}
void HttpBidderInterface::sendErrorMessage(std::string const & agent,
std::string const & error,
std::vector<std::string> const & payload) {
}
void HttpBidderInterface::sendPingMessage(std::string const & agent,
int ping) {
}
void HttpBidderInterface::send(std::shared_ptr<PostAuctionEvent> const & event) {
}
bool HttpBidderInterface::prepareRequest(OpenRTB::BidRequest &request,
const RTBKIT::BidRequest &originalRequest,
const std::map<std::string, BidInfo> &bidders) const {
tagRequest(request, bidders);
// We update the tmax value before sending the BidRequest to substract our processing time
double processingTimeMs = originalRequest.timestamp.secondsUntil(Date::now()) * 1000;
int oldTmax = request.tmax.value();
int newTmax = oldTmax - static_cast<int>(std::round(processingTimeMs));
if (newTmax <= 0) {
return false;
}
#if 0
std::cerr << "old tmax = " << oldTmax << std::endl
<< "new tmax = " << newTmax << std::endl;
#endif
ExcCheck(newTmax <= oldTmax, "Wrong tmax calculation");
request.tmax.val = newTmax;
return true;
}
void HttpBidderInterface::submitBids(const std::string &agent, Id auctionId,
const Bids &bids, WinCostModel wcm)
{
Json::FastWriter writer;
std::vector<std::string> message { agent, "BID" };
message.push_back(auctionId.toString());
std::string bidsStr = writer.write(bids.toJson());
std::string wcmStr = writer.write(wcm.toJson());
message.push_back(std::move(bidsStr));
message.push_back(std::move(wcmStr));
router->doBid(message);
}
//
// factory
//
namespace {
struct AtInit {
AtInit()
{
BidderInterface::registerFactory("http", [](std::string const & name , std::shared_ptr<ServiceProxies> const & proxies, Json::Value const & json) {
return new HttpBidderInterface(name, proxies, json);
});
}
} atInit;
}
<commit_msg>Used the generic indexOf function to retrieve the creative and adSpot indexes<commit_after>/* http_bidder_interface.cc
Eric Robert, 2 April 2014
Copyright (c) 2011 Datacratic. All rights reserved.
*/
#include "http_bidder_interface.h"
#include "jml/db/persistent.h"
#include "soa/service/http_client.h"
#include "soa/utils/generic_utils.h"
#include "rtbkit/common/messages.h"
#include "rtbkit/plugins/bid_request/openrtb_bid_request.h"
#include "rtbkit/openrtb/openrtb_parsing.h"
#include "rtbkit/core/router/router.h"
using namespace Datacratic;
using namespace RTBKIT;
namespace {
DefaultDescription<OpenRTB::BidRequest> desc;
void tagRequest(OpenRTB::BidRequest &request,
const std::map<std::string, BidInfo> &bidders)
{
for (const auto &bidder: bidders) {
const auto &agentConfig = bidder.second.agentConfig;
const auto &spots = bidder.second.imp;
const auto &creatives = agentConfig->creatives;
Json::Value creativesValue(Json::arrayValue);
for (const auto &spot: spots) {
const int adSpotIndex = spot.first;
ExcCheck(adSpotIndex >= 0 && adSpotIndex < request.imp.size(),
"adSpotIndex out of range");
auto &imp = request.imp[adSpotIndex];
auto &ext = imp.ext;
for (int creativeIndex: spot.second) {
ExcCheck(creativeIndex >= 0 && creativeIndex < creatives.size(),
"creativeIndex out of range");
const int creativeId = creatives[creativeIndex].id;
creativesValue.append(creativeId);
}
ext["allowed_ids"][std::to_string(agentConfig->externalId)] =
std::move(creativesValue);
}
}
}
}
HttpBidderInterface::HttpBidderInterface(std::string name,
std::shared_ptr<ServiceProxies> proxies,
Json::Value const & json) {
host = json["host"].asString();
path = json["path"].asString();
httpClient.reset(new HttpClient(host));
loop.addSource("HttpBidderInterface::httpClient", httpClient);
}
void HttpBidderInterface::sendAuctionMessage(std::shared_ptr<Auction> const & auction,
double timeLeftMs,
std::map<std::string, BidInfo> const & bidders) {
using namespace std;
for(auto & item : bidders) {
auto & agent = item.first;
auto & info = router->agents[agent];
const auto &config = info.config;
BidRequest originalRequest = *auction->request;
WinCostModel wcm = auction->exchangeConnector->getWinCostModel(*auction, *info.config);
OpenRTB::BidRequest openRtbRequest = toOpenRtb(originalRequest);
bool ok = prepareRequest(openRtbRequest, originalRequest, bidders);
/* If we took too much time processing the request, then we don't send it.
Instead, we're making null bids for each impression
*/
if (!ok) {
Bids bids;
for_each(begin(openRtbRequest.imp), end(openRtbRequest.imp),
[&](const OpenRTB::Impression &imp) {
Bid theBid;
theBid.price = USD_CPM(0);
bids.push_back(move(theBid));
});
submitBids(agent, auction->id, bids, wcm);
return;
}
StructuredJsonPrintingContext context;
desc.printJson(&openRtbRequest, context);
auto requestStr = context.output.toString();
/* We need to capture by copy inside the lambda otherwise we might get
a dangling reference if we go out of scope before receiving the http response
*/
auto callbacks = std::make_shared<HttpClientSimpleCallbacks>(
[=](const HttpRequest &, HttpClientError errorCode,
int, const std::string &, const std::string &body)
{
if (errorCode != HttpClientError::NONE) {
auto toErrorString = [](HttpClientError code) -> std::string {
switch (code) {
#define CASE(code) \
case code: \
return #code;
CASE(HttpClientError::NONE)
CASE(HttpClientError::UNKNOWN)
CASE(HttpClientError::TIMEOUT)
CASE(HttpClientError::HOST_NOT_FOUND)
CASE(HttpClientError::COULD_NOT_CONNECT)
#undef CASE
}
ExcCheck(false, "Invalid code path");
return "";
};
cerr << "Error requesting " << host
<< ": " << toErrorString(errorCode);
}
else {
// cerr << "Response: " << body << endl;
OpenRTB::BidResponse response;
ML::Parse_Context context("payload",
body.c_str(), body.size());
StreamingJsonParsingContext jsonContext(context);
static DefaultDescription<OpenRTB::BidResponse> respDesc;
respDesc.parseJson(&response, jsonContext);
for (const auto &seatbid: response.seatbid) {
Bids bids;
for (const auto &bid: seatbid.bid) {
Bid theBid;
int crid = bid.crid.toInt();
int creativeIndex = indexOf(config->creatives,
&Creative::id, crid);
if (creativeIndex == -1) {
throw ML::Exception(ML::format(
"Unknown creative id: %d", crid));
}
theBid.creativeIndex = creativeIndex;
theBid.price = USD_CPM(bid.price.val);
theBid.priority = 0.0;
int spotIndex = indexOf(openRtbRequest.imp,
&OpenRTB::Impression::id, bid.impid);
if (spotIndex == -1) {
throw ML::Exception(ML::format(
"Unknown impression id: %s", bid.impid.toString()));
}
theBid.spotIndex = spotIndex;
bids.push_back(std::move(theBid));
}
submitBids(agent, auction->id, bids, wcm);
}
}
}
);
HttpRequest::Content reqContent { requestStr, "application/json" };
RestParams headers { { "x-openrtb-version", "2.1" } };
// std::cerr << "Sending HTTP POST to: " << host << " " << path << std::endl;
// std::cerr << "Content " << reqContent.str << std::endl;
httpClient->post(path, callbacks, reqContent,
{ } /* queryParams */, headers);
}
}
void HttpBidderInterface::sendWinMessage(std::string const & agent,
std::string const & id,
Amount price) {
}
void HttpBidderInterface::sendWinMessage(std::string const & agent,
Amount price,
FinishedInfo const & event) {
}
void HttpBidderInterface::sendLateWinMessage(std::string const & agent,
Amount price,
FinishedInfo const & event) {
}
void HttpBidderInterface::sendLossMessage(std::string const & agent,
std::string const & id) {
}
void HttpBidderInterface::sendLossMessage(std::string const & agent,
FinishedInfo const & event) {
}
void HttpBidderInterface::sendCampaignEventMessage(std::string const & agent,
std::string const & label,
FinishedInfo const & event) {
}
void HttpBidderInterface::sendBidLostMessage(std::string const & agent,
std::shared_ptr<Auction> const & auction) {
}
void HttpBidderInterface::sendBidDroppedMessage(std::string const & agent,
std::shared_ptr<Auction> const & auction) {
}
void HttpBidderInterface::sendBidInvalidMessage(std::string const & agent,
std::string const & reason,
std::shared_ptr<Auction> const & auction) {
}
void HttpBidderInterface::sendNoBudgetMessage(std::string const & agent,
std::shared_ptr<Auction> const & auction) {
}
void HttpBidderInterface::sendTooLateMessage(std::string const & agent,
std::shared_ptr<Auction> const & auction) {
}
void HttpBidderInterface::sendMessage(std::string const & agent,
std::string const & message) {
}
void HttpBidderInterface::sendErrorMessage(std::string const & agent,
std::string const & error,
std::vector<std::string> const & payload) {
}
void HttpBidderInterface::sendPingMessage(std::string const & agent,
int ping) {
}
void HttpBidderInterface::send(std::shared_ptr<PostAuctionEvent> const & event) {
}
bool HttpBidderInterface::prepareRequest(OpenRTB::BidRequest &request,
const RTBKIT::BidRequest &originalRequest,
const std::map<std::string, BidInfo> &bidders) const {
tagRequest(request, bidders);
// We update the tmax value before sending the BidRequest to substract our processing time
double processingTimeMs = originalRequest.timestamp.secondsUntil(Date::now()) * 1000;
int oldTmax = request.tmax.value();
int newTmax = oldTmax - static_cast<int>(std::round(processingTimeMs));
if (newTmax <= 0) {
return false;
}
#if 0
std::cerr << "old tmax = " << oldTmax << std::endl
<< "new tmax = " << newTmax << std::endl;
#endif
ExcCheck(newTmax <= oldTmax, "Wrong tmax calculation");
request.tmax.val = newTmax;
return true;
}
void HttpBidderInterface::submitBids(const std::string &agent, Id auctionId,
const Bids &bids, WinCostModel wcm)
{
Json::FastWriter writer;
std::vector<std::string> message { agent, "BID" };
message.push_back(auctionId.toString());
std::string bidsStr = writer.write(bids.toJson());
std::string wcmStr = writer.write(wcm.toJson());
message.push_back(std::move(bidsStr));
message.push_back(std::move(wcmStr));
router->doBid(message);
}
//
// factory
//
namespace {
struct AtInit {
AtInit()
{
BidderInterface::registerFactory("http", [](std::string const & name , std::shared_ptr<ServiceProxies> const & proxies, Json::Value const & json) {
return new HttpBidderInterface(name, proxies, json);
});
}
} atInit;
}
<|endoftext|> |
<commit_before>#include <stdio.h>
#include <stdlib.h>
#include "field_descriptor.hpp"
int myrank, nprocs;
int main(int argc, char *argv[])
{
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &myrank);
MPI_Comm_size(MPI_COMM_WORLD, &nprocs);
int n[3];
field_descriptor *f0r, *f0c;
field_descriptor *f1r, *f1c;
if (argc != 4)
{
MPI_Finalize();
printf("wrong number of parameters.\n");
return EXIT_SUCCESS;
}
n[0] = atoi(argv[1]);
n[1] = atoi(argv[2]);
n[2] = atoi(argv[3]);
f0c = new field_descriptor(3, n, MPI_COMPLEX8);
n[0] = f0c->sizes[0];
n[1] = f0c->sizes[1];
n[2] = 2*(f0c->sizes[2]-1);
f0r = new field_descriptor(3, n, MPI_REAL4);
n[0] = 2*atoi(argv[1]);
n[1] = 2*atoi(argv[2]);
n[2] = 2*atoi(argv[3]);
f1c = new field_descriptor(3, n, MPI_COMPLEX8);
n[0] = f1c->sizes[0];
n[1] = f1c->sizes[1];
n[2] = 2*(f1c->sizes[2]-1);
f1r = new field_descriptor(3, n, MPI_REAL4);
fftwf_complex *a0, *a1c;
float *a1r;
a0 = fftwf_alloc_complex(f0c->local_size);
a1c = fftwf_alloc_complex(f1c->local_size);
a1r = fftwf_alloc_real(2*f1c->local_size);
f0c->read("data0c", (void*)a0);
fftwf_plan c2r = fftwf_mpi_plan_dft_c2r_3d(
f0r->sizes[0], f0r->sizes[1], f0r->sizes[2],
a0, a1r,
MPI_COMM_WORLD,
FFTW_ESTIMATE);
fftwf_execute(c2r);
fftwf_destroy_plan(c2r);
fftwf_clip_zero_padding(f0r, a1r);
f0r->write("data0r", (void*)a1r);
fftwf_copy_complex_array(
f0c, a0,
f1c, a1c);
c2r = fftwf_mpi_plan_dft_c2r_3d(
f1r->sizes[0], f1r->sizes[1], f1r->sizes[2],
a1c, a1r,
MPI_COMM_WORLD,
FFTW_ESTIMATE);
fftwf_execute(c2r);
fftwf_destroy_plan(c2r);
fftwf_clip_zero_padding(f1r, a1r);
f1r->write("data1r", (void*)a1r);
fftw_free(a0);
fftw_free(a1c);
fftw_free(a1r);
delete f0r;
delete f0c;
delete f1r;
delete f1c;
MPI_Finalize();
return EXIT_SUCCESS;
}
<commit_msg>add fftw mpi init and cleanup calls<commit_after>#include <stdio.h>
#include <stdlib.h>
#include "field_descriptor.hpp"
int myrank, nprocs;
int main(int argc, char *argv[])
{
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &myrank);
MPI_Comm_size(MPI_COMM_WORLD, &nprocs);
fftwf_mpi_init();
int n[3];
field_descriptor *f0r, *f0c;
field_descriptor *f1r, *f1c;
if (argc != 4)
{
MPI_Finalize();
printf("wrong number of parameters.\n");
return EXIT_SUCCESS;
}
n[0] = atoi(argv[1]);
n[1] = atoi(argv[2]);
n[2] = atoi(argv[3]);
f0c = new field_descriptor(3, n, MPI_COMPLEX8);
n[0] = f0c->sizes[0];
n[1] = f0c->sizes[1];
n[2] = 2*(f0c->sizes[2]-1);
f0r = new field_descriptor(3, n, MPI_REAL4);
n[0] = 2*atoi(argv[1]);
n[1] = 2*atoi(argv[2]);
n[2] = 2*atoi(argv[3]);
f1c = new field_descriptor(3, n, MPI_COMPLEX8);
n[0] = f1c->sizes[0];
n[1] = f1c->sizes[1];
n[2] = 2*(f1c->sizes[2]-1);
f1r = new field_descriptor(3, n, MPI_REAL4);
fftwf_complex *a0, *a1c;
float *a1r;
a0 = fftwf_alloc_complex(f0c->local_size);
a1c = fftwf_alloc_complex(f1c->local_size);
a1r = fftwf_alloc_real(2*f1c->local_size);
f0c->read("data0c", (void*)a0);
fftwf_plan c2r = fftwf_mpi_plan_dft_c2r_3d(
f0r->sizes[0], f0r->sizes[1], f0r->sizes[2],
a0, a1r,
MPI_COMM_WORLD,
FFTW_ESTIMATE);
fftwf_execute(c2r);
fftwf_destroy_plan(c2r);
fftwf_clip_zero_padding(f0r, a1r);
f0r->write("data0r", (void*)a1r);
fftwf_copy_complex_array(
f0c, a0,
f1c, a1c);
c2r = fftwf_mpi_plan_dft_c2r_3d(
f1r->sizes[0], f1r->sizes[1], f1r->sizes[2],
a1c, a1r,
MPI_COMM_WORLD,
FFTW_ESTIMATE);
fftwf_execute(c2r);
fftwf_destroy_plan(c2r);
fftwf_clip_zero_padding(f1r, a1r);
f1r->write("data1r", (void*)a1r);
fftw_free(a0);
fftw_free(a1c);
fftw_free(a1r);
fftwf_mpi_cleanup();
delete f0r;
delete f0c;
delete f1r;
delete f1c;
MPI_Finalize();
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>#ifndef DUNE_STUFF_COMMON_PARAMETER_TREE_HH
#define DUNE_STUFF_COMMON_PARAMETER_TREE_HH
#ifdef HAVE_CMAKE_CONFIG
#include "cmake_config.h"
#else
#include "config.h"
#endif // ifdef HAVE_CMAKE_CONFIG
// system
#include <sstream>
#include <boost/algorithm/string/join.hpp>
#include <boost/format.hpp>
// dune-common
#include <dune/common/exceptions.hh>
#include <dune/common/parametertreeparser.hh>
#include <dune/stuff/common/string.hh>
namespace Dune {
namespace Stuff {
namespace Common {
//! ParameterTree extension for nicer output
//! \todo This should go into dune-common.
class ExtendedParameterTree
: public Dune::ParameterTree {
public:
typedef Dune::ParameterTree BaseType;
ExtendedParameterTree()
{}
ExtendedParameterTree(int argc, char** argv, std::string filename)
: BaseType(init(argc, argv, filename))
{}
ExtendedParameterTree(const Dune::ParameterTree& other)
: BaseType(other)
{}
ExtendedParameterTree& operator=(const Dune::ParameterTree& other)
{
if (this != &other) {
Dune::ParameterTree::operator=(other);
}
return *this;
}
static void assertSub(const Dune::ParameterTree& paramTree, std::string sub, std::string id = "")
{
if (!paramTree.hasSub(sub)) {
std::stringstream msg;
msg << "Error";
if (id != "") {
msg << " in " << id;
}
msg << ": subTree '" << sub << "' not found in the following Dune::Parametertree" << std::endl;
paramTree.report(msg);
DUNE_THROW(Dune::InvalidStateException, msg.str());
}
} // static void assertSub(...)
void assertSub(const std::string subTree, const std::string id = "") const
{
assertSub(*this, subTree, id);
}
static void assertKey(const Dune::ParameterTree& paramTree, const std::string key, const std::string id = "")
{
if (!paramTree.hasKey(key)) {
std::stringstream msg;
msg << "Error";
if (id != "") {
msg << " in " << id;
}
msg << ": key '" << key << "' not found in the following Dune::Parametertree" << std::endl;
paramTree.report(msg);
DUNE_THROW(Dune::InvalidStateException, msg.str());
}
} // static void assertKey(...)
void assertKey(const std::string key, const std::string id = "") const
{
assertKey(*this, key, id);
}
void report(std::ostream& stream = std::cout,
const std::string& prefix = "") const
{
for(auto pair : values)
stream << pair.first << " = \"" << pair.second << "\"" << std::endl;
for(auto pair : subs)
{
ExtendedParameterTree subTree(pair.second);
if (subTree.getValueKeys().size())
stream << "[ " << prefix + pair.first << " ]" << std::endl;
subTree.report(stream, prefix + pair.first + ".");
}
}
/**
\brief Fills a Dune::ParameterTree given a parameter file or command line arguments.
\param[in] argc
From \c main()
\param[in] argv
From \c main()
\param[out] paramTree
The Dune::ParameterTree that is to be filled.
**/
static ExtendedParameterTree init(int argc, char** argv, std::string filename)
{
ExtendedParameterTree paramTree;
if (argc == 1) {
Dune::ParameterTreeParser::readINITree(filename, paramTree);
} else if (argc == 2) {
Dune::ParameterTreeParser::readINITree(argv[1], paramTree);
} else {
Dune::ParameterTreeParser::readOptions(argc, argv, paramTree);
}
if (paramTree.hasKey("paramfile")) {
Dune::ParameterTreeParser::readINITree(paramTree.get< std::string >("paramfile"), paramTree, false);
}
return paramTree;
} // static ExtendedParameterTree init(...)
};
} // namespace Common
} // namespace Stuff
} // namespace Dune
#endif // DUNE_STUFF_COMMON_PARAMETER_TREE_HH
<commit_msg>[commo.parameter.tree] added {assert,has,get}Vector()<commit_after>#ifndef DUNE_STUFF_COMMON_PARAMETER_TREE_HH
#define DUNE_STUFF_COMMON_PARAMETER_TREE_HH
#ifdef HAVE_CMAKE_CONFIG
#include "cmake_config.h"
#else
#include "config.h"
#endif // ifdef HAVE_CMAKE_CONFIG
// system
#include <cstring>
#include <sstream>
#include <vector>
// boost
#include <boost/algorithm/string/join.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/format.hpp>
// dune-common
#include <dune/common/exceptions.hh>
#include <dune/common/parametertreeparser.hh>
// dune-stuff
#include <dune/stuff/common/string.hh>
namespace Dune {
namespace Stuff {
namespace Common {
//! ParameterTree extension for nicer output
//! \todo This should go into dune-common.
class ExtendedParameterTree
: public Dune::ParameterTree {
public:
typedef Dune::ParameterTree BaseType;
ExtendedParameterTree()
{}
ExtendedParameterTree(int argc, char** argv, std::string filename)
: BaseType(init(argc, argv, filename))
{}
ExtendedParameterTree(const Dune::ParameterTree& other)
: BaseType(other)
{}
ExtendedParameterTree& operator=(const Dune::ParameterTree& other)
{
if (this != &other) {
Dune::ParameterTree::operator=(other);
}
return *this;
}
static void assertSub(const Dune::ParameterTree& paramTree, std::string sub, std::string id = "")
{
if (!paramTree.hasSub(sub)) {
std::stringstream msg;
msg << "Error";
if (id != "") {
msg << " in " << id;
}
msg << ": subTree '" << sub << "' not found in the following Dune::Parametertree" << std::endl;
ExtendedParameterTree(paramTree).report(msg);
DUNE_THROW(Dune::InvalidStateException, msg.str());
}
} // static void assertSub(...)
void assertSub(const std::string subTree, const std::string id = "") const
{
assertSub(*this, subTree, id);
}
static void assertKey(const Dune::ParameterTree& paramTree, const std::string key, const std::string id = "")
{
if (!paramTree.hasKey(key)) {
std::stringstream msg;
msg << "Error";
if (id != "") {
msg << " in " << id;
}
msg << ": key '" << key << "' not found in the following Dune::Parametertree" << std::endl;
ExtendedParameterTree(paramTree).report(msg);
DUNE_THROW(Dune::InvalidStateException, msg.str());
}
} // static void assertKey(...)
void assertKey(const std::string key, const std::string id = "") const
{
assertKey(*this, key, id);
}
void report(std::ostream& stream = std::cout, const std::string& prefix = "") const
{
for(auto pair : values)
stream << pair.first << " = \"" << pair.second << "\"" << std::endl;
for(auto pair : subs)
{
ExtendedParameterTree subTree(pair.second);
if (subTree.getValueKeys().size())
stream << "[ " << prefix + pair.first << " ]" << std::endl;
subTree.report(stream, prefix + pair.first + ".");
}
}
bool hasVector(const std::string& vector) const
{
if (hasKey(vector)) {
const std::string str = get< std::string >(vector, "default_value");
if (Dune::Stuff::Common::String::equal(str.substr(0, 1), "[")
&& Dune::Stuff::Common::String::equal(str.substr(str.size() - 1, 1), "]"))
return true;
}
return false;
} // bool hasVector(const std::string& vector) const
void assertVector(const std::string vector, const std::string id = "") const
{
if (!hasVector(vector)) {
std::stringstream msg;
msg << "Error";
if (id != "") {
msg << " in " << id;
}
msg << ": vector '" << vector << "' not found in the following Dune::Parametertree" << std::endl;
report(msg);
DUNE_THROW(Dune::InvalidStateException, msg.str());
}
} // void assertVector(...)
template< class T >
std::vector< T > getVector(const std::string& key, const T def) const
{
std::vector< T > ret;
if (!hasKey(key))
ret.push_back(def);
else {
const std::string str = get< std::string >(key, "default_value");
// the dune parametertree strips any leading and trailing whitespace
// so we can be sure that the first and last have to be the brackets []
assert(Dune::Stuff::Common::String::equal(str.substr(0, 1), "[")
&& "Vectors have to be of the form '[entry_0; entry_1; ... ]'!");
assert(Dune::Stuff::Common::String::equal(str.substr(str.size() - 1, 1), "]")
&& "Vectors have to be of the form '[entry_0; entry_1; ... ]'!");
const std::vector< std::string > tokens = Dune::Stuff::Common::tokenize< std::string >(str.substr(1, str.size() - 2), ";");
for (unsigned int i = 0; i < tokens.size(); ++i)
ret.push_back(Dune::Stuff::Common::fromString< T >(boost::algorithm::trim_copy(tokens[i])));
}
return ret;
} // std::vector< T > getVector(const std::string& key, const T def) const
/**
\brief Fills a Dune::ParameterTree given a parameter file or command line arguments.
\param[in] argc
From \c main()
\param[in] argv
From \c main()
\param[out] paramTree
The Dune::ParameterTree that is to be filled.
**/
static ExtendedParameterTree init(int argc, char** argv, std::string filename)
{
Dune::ParameterTree paramTree;
if (argc == 1) {
Dune::ParameterTreeParser::readINITree(filename, paramTree);
} else if (argc == 2) {
Dune::ParameterTreeParser::readINITree(argv[1], paramTree);
} else {
Dune::ParameterTreeParser::readOptions(argc, argv, paramTree);
}
if (paramTree.hasKey("paramfile")) {
Dune::ParameterTreeParser::readINITree(paramTree.get< std::string >("paramfile"), paramTree, false);
}
return paramTree;
} // static ExtendedParameterTree init(...)
};
} // namespace Common
} // namespace Stuff
} // namespace Dune
#endif // DUNE_STUFF_COMMON_PARAMETER_TREE_HH
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: pagedata.cxx,v $
*
* $Revision: 1.1.1.1 $
*
* last change: $Author: hr $ $Date: 2000-09-18 16:44:55 $
*
* 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): _______________________________________
*
*
************************************************************************/
#ifdef PCH
#include "ui_pch.hxx"
#endif
#include <string.h>
#ifndef _DEBUG_HXX //autogen
#include <tools/debug.hxx>
#endif
#pragma hdrstop
#ifndef PCH
#include "segmentc.hxx"
#endif
#include "pagedata.hxx"
//============================================================================
ScPrintRangeData::ScPrintRangeData()
{
nPagesX = nPagesY = 0;
pPageEndX = pPageEndY = NULL;
bTopDown = bAutomatic = TRUE;
nFirstPage = 1;
}
ScPrintRangeData::~ScPrintRangeData()
{
delete[] pPageEndX;
delete[] pPageEndY;
}
void ScPrintRangeData::SetPagesX( USHORT nCount, const USHORT* pData )
{
delete[] pPageEndX;
if ( nCount )
{
pPageEndX = new USHORT[nCount];
memcpy( pPageEndX, pData, nCount * sizeof(USHORT) );
}
else
pPageEndX = NULL;
nPagesX = nCount;
}
void ScPrintRangeData::SetPagesY( USHORT nCount, const USHORT* pData )
{
delete[] pPageEndY;
if ( nCount )
{
pPageEndY = new USHORT[nCount];
memcpy( pPageEndY, pData, nCount * sizeof(USHORT) );
}
else
pPageEndY = NULL;
nPagesY = nCount;
}
//============================================================================
ScPageBreakData::ScPageBreakData(USHORT nMax)
{
nUsed = 0;
if (nMax)
pData = new ScPrintRangeData[nMax];
else
pData = NULL;
nAlloc = nMax;
}
ScPageBreakData::~ScPageBreakData()
{
delete[] pData;
}
ScPrintRangeData& ScPageBreakData::GetData(USHORT nPos)
{
DBG_ASSERT(nPos < nAlloc, "ScPageBreakData::GetData bumm");
if ( nPos >= nUsed )
{
DBG_ASSERT(nPos == nUsed, "ScPageBreakData::GetData falsche Reihenfolge");
nUsed = nPos+1;
}
return pData[nPos];
}
BOOL ScPageBreakData::IsEqual( const ScPageBreakData& rOther ) const
{
if ( nUsed != rOther.nUsed )
return FALSE;
for (USHORT i=0; i<nUsed; i++)
if ( pData[i].GetPrintRange() != rOther.pData[i].GetPrintRange() )
return FALSE;
//! ScPrintRangeData komplett vergleichen ??
return TRUE;
}
void ScPageBreakData::AddPages()
{
if ( nUsed > 1 )
{
long nPage = pData[0].GetFirstPage();
for (USHORT i=0; i+1<nUsed; i++)
{
nPage += ((long)pData[i].GetPagesX())*pData[i].GetPagesY();
pData[i+1].SetFirstPage( nPage );
}
}
}
<commit_msg>del: segmentc.hxx<commit_after>/*************************************************************************
*
* $RCSfile: pagedata.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: mh $ $Date: 2001-10-23 08:42:02 $
*
* 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): _______________________________________
*
*
************************************************************************/
#ifdef PCH
#include "ui_pch.hxx"
#endif
#include <string.h>
#ifndef _DEBUG_HXX //autogen
#include <tools/debug.hxx>
#endif
#pragma hdrstop
#include "pagedata.hxx"
//============================================================================
ScPrintRangeData::ScPrintRangeData()
{
nPagesX = nPagesY = 0;
pPageEndX = pPageEndY = NULL;
bTopDown = bAutomatic = TRUE;
nFirstPage = 1;
}
ScPrintRangeData::~ScPrintRangeData()
{
delete[] pPageEndX;
delete[] pPageEndY;
}
void ScPrintRangeData::SetPagesX( USHORT nCount, const USHORT* pData )
{
delete[] pPageEndX;
if ( nCount )
{
pPageEndX = new USHORT[nCount];
memcpy( pPageEndX, pData, nCount * sizeof(USHORT) );
}
else
pPageEndX = NULL;
nPagesX = nCount;
}
void ScPrintRangeData::SetPagesY( USHORT nCount, const USHORT* pData )
{
delete[] pPageEndY;
if ( nCount )
{
pPageEndY = new USHORT[nCount];
memcpy( pPageEndY, pData, nCount * sizeof(USHORT) );
}
else
pPageEndY = NULL;
nPagesY = nCount;
}
//============================================================================
ScPageBreakData::ScPageBreakData(USHORT nMax)
{
nUsed = 0;
if (nMax)
pData = new ScPrintRangeData[nMax];
else
pData = NULL;
nAlloc = nMax;
}
ScPageBreakData::~ScPageBreakData()
{
delete[] pData;
}
ScPrintRangeData& ScPageBreakData::GetData(USHORT nPos)
{
DBG_ASSERT(nPos < nAlloc, "ScPageBreakData::GetData bumm");
if ( nPos >= nUsed )
{
DBG_ASSERT(nPos == nUsed, "ScPageBreakData::GetData falsche Reihenfolge");
nUsed = nPos+1;
}
return pData[nPos];
}
BOOL ScPageBreakData::IsEqual( const ScPageBreakData& rOther ) const
{
if ( nUsed != rOther.nUsed )
return FALSE;
for (USHORT i=0; i<nUsed; i++)
if ( pData[i].GetPrintRange() != rOther.pData[i].GetPrintRange() )
return FALSE;
//! ScPrintRangeData komplett vergleichen ??
return TRUE;
}
void ScPageBreakData::AddPages()
{
if ( nUsed > 1 )
{
long nPage = pData[0].GetFirstPage();
for (USHORT i=0; i+1<nUsed; i++)
{
nPage += ((long)pData[i].GetPagesX())*pData[i].GetPagesY();
pData[i+1].SetFirstPage( nPage );
}
}
}
<|endoftext|> |
<commit_before>#include "RigidBody.h"
#include "RbCollider.h"
#include "DistanceJoint.h"
#include "Application.h"
#include "Transform.h"
#include "jpPhysicsRigidBody.h"
RigidBody::RigidBody(GameObject * parent, bool isactive) : Component(parent, COMP_RIGIDBODY, true)
{
joint_ptr = nullptr;
if (parent != nullptr)
parent->AddComponent(this);
}
RigidBody::~RigidBody()
{
if (physics_body) {
delete physics_body;
physics_body = nullptr;
}
if (collider_comp != nullptr) {
collider_comp->SetRigidBodyComp(nullptr);
collider_comp->SetPhysicsBody(nullptr);
}
if (joint_ptr != nullptr)
{
joint_ptr->StopUsing(UUID);
}
}
void RigidBody::Update()
{
if (transform && physics_body && App->clock.delta_time > 0)
{
if (dynamic)
physics_body->px_body->wakeUp();
physx::PxVec3 pos;
physx::PxQuat rot;
physics_body->GetTransform(pos, rot);
transform->SetTransform(float3(pos.x, pos.y, pos.z), Quat(rot.x, rot.y, rot.z, rot.w));
own_update = true;
}
else own_update = false;
}
void RigidBody::UpdateTransform()
{
if(physics_body && !own_update) {
float3 fpos = transform->GetPosition();
Quat quat = transform->GetRotQuat();
physics_body->px_body->setGlobalPose(physx::PxTransform(physx::PxVec3(fpos.x, fpos.y, fpos.z),physx::PxQuat(quat.x,quat.y,quat.z,quat.w)));
}
}
void RigidBody::ChangeParent(GameObject * new_parent)
{
Component::ChangeParent(new_parent);
collider_comp = LookForCollider();
if (collider_comp != nullptr)
{
collider_comp->SetRigidBodyComp(this);
if (physics_body)
delete physics_body;
physics_body = collider_comp->GetPhysicsBody();
}
else {
physics_body = App->physics->GetNewRigidBody(0);
}
//Make sure is dynamic
physics_body->SetDynamic(dynamic);
transform = new_parent->GetTransform();
UpdateTransform();
}
void RigidBody::DrawComponent()
{
ImGui::PushID(UUID);
Component::DrawComponent();
if (ImGui::CollapsingHeader("RigidBody"))
{
if (ImGui::Checkbox("Dynamic", &dynamic)) physics_body->SetDynamic(dynamic);
if (ImGui::InputFloat("Mass", (float*)&mass, 0.1f, 1.f, 2, ImGuiInputTextFlags_EnterReturnsTrue))
SetPhysicsBodyMass();
}
ImGui::PopID();
}
void RigidBody::SetPhysicsBody(jpPhysicsRigidBody * new_physics_body)
{
// careful somethings wrong here
physics_body = new_physics_body;
}
void RigidBody::SetPhysicsBodyMass()
{
if (physics_body)
physics_body->SetMass(mass);
}
void RigidBody::SetColliderComp(RbCollider * new_collider)
{
collider_comp = new_collider;
if (new_collider){
jpPhysicsRigidBody* body = new_collider->GetPhysicsBody();
if (body && physics_body != body) {
if (physics_body)
delete physics_body;
physics_body = body;
physics_body->SetDynamic(dynamic);
}
}
}
jpPhysicsRigidBody * RigidBody::GetPhysicsBody()
{
return physics_body;
}
void RigidBody::Save(const char * buffer_data, char * cursor, int & bytes_copied)
{
//identifier and type
int identifier = COMPONENTIDENTIFIER;
uint bytes_to_copy = sizeof(identifier);
memcpy(cursor, &identifier, bytes_to_copy);
cursor += bytes_to_copy;
bytes_copied += bytes_to_copy;
bytes_to_copy = sizeof(type);
memcpy(cursor, &type, bytes_to_copy);
cursor += bytes_to_copy;
bytes_copied += bytes_to_copy;
//UUID and parent UUID
bytes_to_copy = sizeof(UUID);
memcpy(cursor, &UUID, bytes_to_copy);
cursor += bytes_to_copy;
bytes_copied += bytes_to_copy;
bytes_to_copy = sizeof(parent_UUID);
memcpy(cursor, &parent_UUID, bytes_to_copy);
cursor += bytes_to_copy;
bytes_copied += bytes_to_copy;
//active and unique
bytes_to_copy = sizeof(bool);
memcpy(cursor, &active, bytes_to_copy);
cursor += bytes_to_copy;
bytes_copied += bytes_to_copy;
memcpy(cursor, &unique, bytes_to_copy);
cursor += bytes_to_copy;
bytes_copied += bytes_to_copy;
///RigidBody comp
bytes_to_copy = sizeof(bool);
memcpy(cursor, &dynamic, bytes_to_copy);
cursor += bytes_to_copy;
bytes_copied += bytes_to_copy;
memcpy(cursor, &own_update, bytes_to_copy);
cursor += bytes_to_copy;
bytes_copied += bytes_to_copy;
}
void RigidBody::Load(char * cursor, int & bytes_copied)
{
//UUID and parentUUID
uint bytes_to_copy = sizeof(int);
memcpy(&UUID, cursor, bytes_to_copy);
cursor += bytes_to_copy;
bytes_copied += bytes_to_copy;
memcpy(&parent_UUID, cursor, bytes_to_copy);
cursor += bytes_to_copy;
bytes_copied += bytes_to_copy;
//active and unique
bytes_to_copy = sizeof(bool);
memcpy(&active, cursor, bytes_to_copy);
cursor += bytes_to_copy;
bytes_copied += bytes_to_copy;
memcpy(&unique, cursor, bytes_to_copy);
cursor += bytes_to_copy;
bytes_copied += bytes_to_copy;
///RigidBody comp
bytes_to_copy = sizeof(bool);
memcpy(&dynamic, cursor, bytes_to_copy);
cursor += bytes_to_copy;
bytes_copied += bytes_to_copy;
memcpy(&own_update, cursor, bytes_to_copy);
cursor += bytes_to_copy;
bytes_copied += bytes_to_copy;
}
void RigidBody::GetOwnBufferSize(uint & buffer_size)
{
Component::GetOwnBufferSize(buffer_size);
buffer_size += sizeof(bool) * 2;
}
RbCollider * RigidBody::LookForCollider()
{
if (parent != nullptr)
{
for (uint i = 0; i < parent->components.size(); i++)
{
if (parent->components[i]->GetType() == COMP_TYPE::COMP_RBSHAPE)
{
return (RbCollider*)parent->components[i];
}
}
}
return nullptr;
}
<commit_msg>mass save and load<commit_after>#include "RigidBody.h"
#include "RbCollider.h"
#include "DistanceJoint.h"
#include "Application.h"
#include "Transform.h"
#include "jpPhysicsRigidBody.h"
RigidBody::RigidBody(GameObject * parent, bool isactive) : Component(parent, COMP_RIGIDBODY, true)
{
joint_ptr = nullptr;
if (parent != nullptr)
parent->AddComponent(this);
}
RigidBody::~RigidBody()
{
if (physics_body) {
delete physics_body;
physics_body = nullptr;
}
if (collider_comp != nullptr) {
collider_comp->SetRigidBodyComp(nullptr);
collider_comp->SetPhysicsBody(nullptr);
}
if (joint_ptr != nullptr)
{
joint_ptr->StopUsing(UUID);
}
}
void RigidBody::Update()
{
if (transform && physics_body && App->clock.delta_time > 0)
{
if (dynamic)
physics_body->px_body->wakeUp();
physx::PxVec3 pos;
physx::PxQuat rot;
physics_body->GetTransform(pos, rot);
transform->SetTransform(float3(pos.x, pos.y, pos.z), Quat(rot.x, rot.y, rot.z, rot.w));
own_update = true;
}
else own_update = false;
}
void RigidBody::UpdateTransform()
{
if(physics_body && !own_update) {
float3 fpos = transform->GetPosition();
Quat quat = transform->GetRotQuat();
physics_body->px_body->setGlobalPose(physx::PxTransform(physx::PxVec3(fpos.x, fpos.y, fpos.z),physx::PxQuat(quat.x,quat.y,quat.z,quat.w)));
}
}
void RigidBody::ChangeParent(GameObject * new_parent)
{
Component::ChangeParent(new_parent);
collider_comp = LookForCollider();
if (collider_comp != nullptr)
{
collider_comp->SetRigidBodyComp(this);
if (physics_body)
delete physics_body;
physics_body = collider_comp->GetPhysicsBody();
}
else {
physics_body = App->physics->GetNewRigidBody(0);
}
//Make sure is dynamic
physics_body->SetDynamic(dynamic);
transform = new_parent->GetTransform();
UpdateTransform();
}
void RigidBody::DrawComponent()
{
ImGui::PushID(UUID);
Component::DrawComponent();
if (ImGui::CollapsingHeader("RigidBody"))
{
if (ImGui::Checkbox("Dynamic", &dynamic)) physics_body->SetDynamic(dynamic);
if (ImGui::InputFloat("Mass", (float*)&mass, 0.1f, 1.f, 2, ImGuiInputTextFlags_EnterReturnsTrue))
SetPhysicsBodyMass();
}
ImGui::PopID();
}
void RigidBody::SetPhysicsBody(jpPhysicsRigidBody * new_physics_body)
{
// careful somethings wrong here
physics_body = new_physics_body;
}
void RigidBody::SetPhysicsBodyMass()
{
if (physics_body)
physics_body->SetMass(mass);
}
void RigidBody::SetColliderComp(RbCollider * new_collider)
{
collider_comp = new_collider;
if (new_collider){
jpPhysicsRigidBody* body = new_collider->GetPhysicsBody();
if (body && physics_body != body) {
if (physics_body)
delete physics_body;
physics_body = body;
physics_body->SetDynamic(dynamic);
}
}
}
jpPhysicsRigidBody * RigidBody::GetPhysicsBody()
{
return physics_body;
}
void RigidBody::Save(const char * buffer_data, char * cursor, int & bytes_copied)
{
//identifier and type
int identifier = COMPONENTIDENTIFIER;
uint bytes_to_copy = sizeof(identifier);
memcpy(cursor, &identifier, bytes_to_copy);
cursor += bytes_to_copy;
bytes_copied += bytes_to_copy;
bytes_to_copy = sizeof(type);
memcpy(cursor, &type, bytes_to_copy);
cursor += bytes_to_copy;
bytes_copied += bytes_to_copy;
//UUID and parent UUID
bytes_to_copy = sizeof(UUID);
memcpy(cursor, &UUID, bytes_to_copy);
cursor += bytes_to_copy;
bytes_copied += bytes_to_copy;
bytes_to_copy = sizeof(parent_UUID);
memcpy(cursor, &parent_UUID, bytes_to_copy);
cursor += bytes_to_copy;
bytes_copied += bytes_to_copy;
//active and unique
bytes_to_copy = sizeof(bool);
memcpy(cursor, &active, bytes_to_copy);
cursor += bytes_to_copy;
bytes_copied += bytes_to_copy;
memcpy(cursor, &unique, bytes_to_copy);
cursor += bytes_to_copy;
bytes_copied += bytes_to_copy;
///RigidBody comp
bytes_to_copy = sizeof(bool);
memcpy(cursor, &dynamic, bytes_to_copy);
cursor += bytes_to_copy;
bytes_copied += bytes_to_copy;
memcpy(cursor, &own_update, bytes_to_copy);
cursor += bytes_to_copy;
bytes_copied += bytes_to_copy;
bytes_to_copy = sizeof(float);
memcpy(cursor, &mass, bytes_to_copy);
cursor += bytes_to_copy;
bytes_copied += bytes_to_copy;
}
void RigidBody::Load(char * cursor, int & bytes_copied)
{
//UUID and parentUUID
uint bytes_to_copy = sizeof(int);
memcpy(&UUID, cursor, bytes_to_copy);
cursor += bytes_to_copy;
bytes_copied += bytes_to_copy;
memcpy(&parent_UUID, cursor, bytes_to_copy);
cursor += bytes_to_copy;
bytes_copied += bytes_to_copy;
//active and unique
bytes_to_copy = sizeof(bool);
memcpy(&active, cursor, bytes_to_copy);
cursor += bytes_to_copy;
bytes_copied += bytes_to_copy;
memcpy(&unique, cursor, bytes_to_copy);
cursor += bytes_to_copy;
bytes_copied += bytes_to_copy;
///RigidBody comp
bytes_to_copy = sizeof(bool);
memcpy(&dynamic, cursor, bytes_to_copy);
cursor += bytes_to_copy;
bytes_copied += bytes_to_copy;
memcpy(&own_update, cursor, bytes_to_copy);
cursor += bytes_to_copy;
bytes_copied += bytes_to_copy;
bytes_to_copy = sizeof(float);
memcpy(&mass, cursor, bytes_to_copy);
cursor += bytes_to_copy;
bytes_copied += bytes_to_copy;
}
void RigidBody::GetOwnBufferSize(uint & buffer_size)
{
Component::GetOwnBufferSize(buffer_size);
buffer_size += sizeof(bool) * 2;
buffer_size += sizeof(float);
}
RbCollider * RigidBody::LookForCollider()
{
if (parent != nullptr)
{
for (uint i = 0; i < parent->components.size(); i++)
{
if (parent->components[i]->GetType() == COMP_TYPE::COMP_RBSHAPE)
{
return (RbCollider*)parent->components[i];
}
}
}
return nullptr;
}
<|endoftext|> |
<commit_before>/****************************************************************************
This file is part of the GLC-lib library.
Copyright (C) 2005-2008 Laurent Ribon ([email protected])
Version 1.2.0, packaged on September 2009.
http://glc-lib.sourceforge.net
GLC-lib 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.
GLC-lib 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 GLC-lib; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*****************************************************************************/
//! \file glc_cuttingplane.cpp Implementation of the GLC_CuttingPlane class.
#include "glc_cuttingplane.h"
#include "../glc_factory.h"
#include "../maths/glc_line3d.h"
#include "../maths/glc_geomtools.h"
#include "../geometry/glc_arrow.h"
#include "../geometry/glc_disc.h"
GLC_CuttingPlane::GLC_CuttingPlane(const GLC_Point3d& center, const GLC_Vector3d& normal, double l1, double l2, GLC_3DWidgetManagerHandle* pWidgetManagerHandle)
: GLC_3DWidget(pWidgetManagerHandle)
, m_Center(center)
, m_Normal(normal)
, m_L1(l1)
, m_L2(l2)
, m_Previous()
, m_SlidingPlane()
, m_Color(Qt::darkGreen)
, m_Opacity(0.3)
{
if (NULL != pWidgetManagerHandle)
{
create3DviewInstance();
}
}
GLC_CuttingPlane::GLC_CuttingPlane(const GLC_CuttingPlane& cuttingPlane)
: GLC_3DWidget(cuttingPlane)
, m_Center(cuttingPlane.m_Center)
, m_Normal(cuttingPlane.m_Normal)
, m_L1(cuttingPlane.m_L1)
, m_L2(cuttingPlane.m_L2)
, m_Previous()
, m_SlidingPlane()
, m_Color(cuttingPlane.m_Color)
, m_Opacity(cuttingPlane.m_Opacity)
{
}
GLC_CuttingPlane::~GLC_CuttingPlane()
{
}
GLC_CuttingPlane& GLC_CuttingPlane::operator=(const GLC_CuttingPlane& cuttingPlane)
{
GLC_3DWidget::operator=(cuttingPlane);
m_Center= cuttingPlane.m_Center;
m_Normal= cuttingPlane.m_Normal;
m_L1= cuttingPlane.m_L1;
m_L2= cuttingPlane.m_L2;
m_Color= cuttingPlane.m_Color;
m_Opacity= cuttingPlane.m_Opacity;
return *this;
}
void GLC_CuttingPlane::updateLength(double l1, double l2)
{
m_L1= l1;
m_L2= l2;
if (GLC_3DWidget::has3DWidgetManager())
{
GLC_3DWidget::remove3DViewInstance();
create3DviewInstance();
}
}
void GLC_CuttingPlane::viewportAsChanged()
{
const double viewTangent= GLC_3DWidget::widgetManagerHandle()->viewportTangent();
const GLC_Point3d eye(GLC_3DWidget::widgetManagerHandle()->cameraHandle()->eye());
const double distanceToNormal= (m_Previous - eye).length();
const double viewWidth= distanceToNormal * viewTangent;
updateArrow(viewWidth * 0.1);
}
glc::WidgetEventFlag GLC_CuttingPlane::select(const GLC_Point3d& pos)
{
// Update previous point
m_Previous= pos;
prepareToSlide();
GLC_3DWidget::set3DViewInstanceVisibility(1, true);
GLC_3DWidget::set3DViewInstanceVisibility(2, true);
GLC_Matrix4x4 translationMatrix(pos);
GLC_3DWidget::instanceHandle(1)->setMatrix(translationMatrix);
GLC_3DWidget::instanceHandle(2)->setMatrix(translationMatrix);
return glc::BlockedEvent;
}
glc::WidgetEventFlag GLC_CuttingPlane::mousePressed(const GLC_Point3d& pos, Qt::MouseButton button)
{
glc::WidgetEventFlag returnFlag= glc::IgnoreEvent;
if (button == Qt::LeftButton)
{
m_Previous= pos;
prepareToSlide();
returnFlag= glc::BlockedEvent;
GLC_3DWidget::set3DViewInstanceVisibility(1, true);
GLC_3DWidget::set3DViewInstanceVisibility(2, true);
GLC_Matrix4x4 translationMatrix(pos);
GLC_3DWidget::instanceHandle(1)->setMatrix(translationMatrix);
GLC_3DWidget::instanceHandle(2)->setMatrix(translationMatrix);
}
return returnFlag;
}
glc::WidgetEventFlag GLC_CuttingPlane::unselect(const GLC_Point3d&)
{
GLC_3DWidget::set3DViewInstanceVisibility(1, false);
GLC_3DWidget::set3DViewInstanceVisibility(2, false);
return glc::AcceptEvent;
}
glc::WidgetEventFlag GLC_CuttingPlane::mouseOver(const GLC_Point3d&)
{
return glc::AcceptEvent;
}
glc::WidgetEventFlag GLC_CuttingPlane::mouseMove(const GLC_Point3d& pos, Qt::MouseButtons)
{
// Projection of intersection point on slidding plane
const GLC_Point3d eye(GLC_3DWidget::widgetManagerHandle()->cameraHandle()->eye());
GLC_Vector3d direction;
if (GLC_3DWidget::useOrtho())
{
direction= GLC_3DWidget::widgetManagerHandle()->cameraHandle()->forward().normalize();
}
else
{
direction= (pos - eye);
}
GLC_Point3d sliddingPoint;
GLC_Line3d projectionLine(pos, direction);
glc::lineIntersectPlane(projectionLine, m_SlidingPlane, &sliddingPoint);
GLC_Vector3d projNormal= (GLC_3DWidget::widgetManagerHandle()->cameraHandle()->sideVector() ^ m_Normal).normalize();
GLC_Plane projPlane(projNormal, m_Previous);
glc::lineIntersectPlane(projectionLine, projPlane, &sliddingPoint);
// Projection of the slidding point on cutting plane normal
sliddingPoint= glc::project(sliddingPoint, GLC_Line3d(m_Previous, m_Normal));
GLC_Matrix4x4 translationMatrix(sliddingPoint - m_Previous);
// Update the instance
GLC_3DWidget::instanceHandle(0)->multMatrix(translationMatrix);
GLC_3DWidget::instanceHandle(1)->multMatrix(translationMatrix);
GLC_3DWidget::instanceHandle(2)->multMatrix(translationMatrix);
// Update plane center
m_Center= translationMatrix * m_Center;
m_Previous= sliddingPoint;
// Plane throw intersection and plane normal and camera up vector
GLC_Plane sliddingPlane(GLC_3DWidget::widgetManagerHandle()->cameraHandle()->forward().normalize(), m_Previous);
m_SlidingPlane= sliddingPlane;
emit asChanged();
return glc::AcceptEvent;
}
void GLC_CuttingPlane::create3DviewInstance()
{
Q_ASSERT(GLC_3DWidget::isEmpty());
// The cutting plane material
GLC_Material* pMaterial= new GLC_Material(m_Color);
pMaterial->setOpacity(m_Opacity);
// Cutting plane 3Dview instance
GLC_3DViewInstance cuttingPlaneInstance= GLC_Factory::instance()->createCuttingPlane(m_Center, m_Normal, m_L1, m_L2, pMaterial);
GLC_3DWidget::add3DViewInstance(cuttingPlaneInstance);
// Normal arrow geometry
GLC_Arrow* pArrow= new GLC_Arrow(GLC_Point3d(), -m_Normal, GLC_3DWidget::widgetManagerHandle()->cameraHandle()->forward().normalize());
pArrow->setLineWidth(2.5);
QColor arrowColor(Qt::red);
arrowColor.setAlphaF(0.4);
pArrow->setWireColor(arrowColor);
//Base arrow disc
pMaterial= new GLC_Material(Qt::red);
pMaterial->setOpacity(m_Opacity);
GLC_Disc* pDisc= new GLC_Disc(1.0);
pDisc->replaceMasterMaterial(pMaterial);
// Normal arrow + base instance
GLC_3DViewInstance normalLine(pArrow);
GLC_3DWidget::add3DViewInstance(normalLine);
GLC_3DWidget::set3DViewInstanceVisibility(1, false);
GLC_3DViewInstance normalBase(pDisc);
GLC_3DWidget::add3DViewInstance(normalBase);
GLC_3DWidget::set3DViewInstanceVisibility(2, false);
}
void GLC_CuttingPlane::prepareToSlide()
{
// Plane throw intersection and plane normal and camera up vector
GLC_Plane sliddingPlane(GLC_3DWidget::widgetManagerHandle()->cameraHandle()->forward().normalize(), m_Previous);
m_SlidingPlane= sliddingPlane;
// Projection of intersection point on slidding plane
const GLC_Point3d eye(GLC_3DWidget::widgetManagerHandle()->cameraHandle()->eye());
const GLC_Vector3d direction((m_Previous - eye).normalize());
GLC_Line3d projectionLine(m_Previous, direction);
glc::lineIntersectPlane(projectionLine, m_SlidingPlane, &m_Previous);
//m_Previous= glc::project(m_Previous, GLC_Line3d(m_Previous, m_Normal));
}
void GLC_CuttingPlane::updateArrow(double length)
{
GLC_Arrow* pArrow= dynamic_cast<GLC_Arrow*>(GLC_3DWidget::instanceHandle(1)->geomAt(0));
Q_ASSERT(NULL != pArrow);
pArrow->setEndPoint(-m_Normal * length);
pArrow->setHeadLength(length * 0.15);
pArrow->setViewDir(GLC_3DWidget::widgetManagerHandle()->cameraHandle()->forward().normalize());
GLC_Disc* pDisc= dynamic_cast<GLC_Disc*>(GLC_3DWidget::instanceHandle(2)->geomAt(0));
Q_ASSERT(NULL != pDisc);
pDisc->setRadius(pArrow->headLenght());
}
<commit_msg>Minor Change : Change arrow size.<commit_after>/****************************************************************************
This file is part of the GLC-lib library.
Copyright (C) 2005-2008 Laurent Ribon ([email protected])
Version 1.2.0, packaged on September 2009.
http://glc-lib.sourceforge.net
GLC-lib 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.
GLC-lib 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 GLC-lib; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*****************************************************************************/
//! \file glc_cuttingplane.cpp Implementation of the GLC_CuttingPlane class.
#include "glc_cuttingplane.h"
#include "../glc_factory.h"
#include "../maths/glc_line3d.h"
#include "../maths/glc_geomtools.h"
#include "../geometry/glc_arrow.h"
#include "../geometry/glc_disc.h"
GLC_CuttingPlane::GLC_CuttingPlane(const GLC_Point3d& center, const GLC_Vector3d& normal, double l1, double l2, GLC_3DWidgetManagerHandle* pWidgetManagerHandle)
: GLC_3DWidget(pWidgetManagerHandle)
, m_Center(center)
, m_Normal(normal)
, m_L1(l1)
, m_L2(l2)
, m_Previous()
, m_SlidingPlane()
, m_Color(Qt::darkGreen)
, m_Opacity(0.3)
{
if (NULL != pWidgetManagerHandle)
{
create3DviewInstance();
}
}
GLC_CuttingPlane::GLC_CuttingPlane(const GLC_CuttingPlane& cuttingPlane)
: GLC_3DWidget(cuttingPlane)
, m_Center(cuttingPlane.m_Center)
, m_Normal(cuttingPlane.m_Normal)
, m_L1(cuttingPlane.m_L1)
, m_L2(cuttingPlane.m_L2)
, m_Previous()
, m_SlidingPlane()
, m_Color(cuttingPlane.m_Color)
, m_Opacity(cuttingPlane.m_Opacity)
{
}
GLC_CuttingPlane::~GLC_CuttingPlane()
{
}
GLC_CuttingPlane& GLC_CuttingPlane::operator=(const GLC_CuttingPlane& cuttingPlane)
{
GLC_3DWidget::operator=(cuttingPlane);
m_Center= cuttingPlane.m_Center;
m_Normal= cuttingPlane.m_Normal;
m_L1= cuttingPlane.m_L1;
m_L2= cuttingPlane.m_L2;
m_Color= cuttingPlane.m_Color;
m_Opacity= cuttingPlane.m_Opacity;
return *this;
}
void GLC_CuttingPlane::updateLength(double l1, double l2)
{
m_L1= l1;
m_L2= l2;
if (GLC_3DWidget::has3DWidgetManager())
{
GLC_3DWidget::remove3DViewInstance();
create3DviewInstance();
}
}
void GLC_CuttingPlane::viewportAsChanged()
{
const double viewTangent= GLC_3DWidget::widgetManagerHandle()->viewportTangent();
const GLC_Point3d eye(GLC_3DWidget::widgetManagerHandle()->cameraHandle()->eye());
const double distanceToNormal= (m_Previous - eye).length();
const double viewWidth= distanceToNormal * viewTangent;
updateArrow(viewWidth * 0.06);
}
glc::WidgetEventFlag GLC_CuttingPlane::select(const GLC_Point3d& pos)
{
// Update previous point
m_Previous= pos;
prepareToSlide();
GLC_3DWidget::set3DViewInstanceVisibility(1, true);
GLC_3DWidget::set3DViewInstanceVisibility(2, true);
GLC_Matrix4x4 translationMatrix(pos);
GLC_3DWidget::instanceHandle(1)->setMatrix(translationMatrix);
GLC_3DWidget::instanceHandle(2)->setMatrix(translationMatrix);
return glc::BlockedEvent;
}
glc::WidgetEventFlag GLC_CuttingPlane::mousePressed(const GLC_Point3d& pos, Qt::MouseButton button)
{
glc::WidgetEventFlag returnFlag= glc::IgnoreEvent;
if (button == Qt::LeftButton)
{
m_Previous= pos;
prepareToSlide();
returnFlag= glc::BlockedEvent;
GLC_3DWidget::set3DViewInstanceVisibility(1, true);
GLC_3DWidget::set3DViewInstanceVisibility(2, true);
GLC_Matrix4x4 translationMatrix(pos);
GLC_3DWidget::instanceHandle(1)->setMatrix(translationMatrix);
GLC_3DWidget::instanceHandle(2)->setMatrix(translationMatrix);
}
return returnFlag;
}
glc::WidgetEventFlag GLC_CuttingPlane::unselect(const GLC_Point3d&)
{
GLC_3DWidget::set3DViewInstanceVisibility(1, false);
GLC_3DWidget::set3DViewInstanceVisibility(2, false);
return glc::AcceptEvent;
}
glc::WidgetEventFlag GLC_CuttingPlane::mouseOver(const GLC_Point3d&)
{
return glc::AcceptEvent;
}
glc::WidgetEventFlag GLC_CuttingPlane::mouseMove(const GLC_Point3d& pos, Qt::MouseButtons)
{
// Projection of intersection point on slidding plane
const GLC_Point3d eye(GLC_3DWidget::widgetManagerHandle()->cameraHandle()->eye());
GLC_Vector3d direction;
if (GLC_3DWidget::useOrtho())
{
direction= GLC_3DWidget::widgetManagerHandle()->cameraHandle()->forward().normalize();
}
else
{
direction= (pos - eye);
}
GLC_Point3d sliddingPoint;
GLC_Line3d projectionLine(pos, direction);
glc::lineIntersectPlane(projectionLine, m_SlidingPlane, &sliddingPoint);
GLC_Vector3d projNormal= (GLC_3DWidget::widgetManagerHandle()->cameraHandle()->sideVector() ^ m_Normal).normalize();
GLC_Plane projPlane(projNormal, m_Previous);
glc::lineIntersectPlane(projectionLine, projPlane, &sliddingPoint);
// Projection of the slidding point on cutting plane normal
sliddingPoint= glc::project(sliddingPoint, GLC_Line3d(m_Previous, m_Normal));
GLC_Matrix4x4 translationMatrix(sliddingPoint - m_Previous);
// Update the instance
GLC_3DWidget::instanceHandle(0)->multMatrix(translationMatrix);
GLC_3DWidget::instanceHandle(1)->multMatrix(translationMatrix);
GLC_3DWidget::instanceHandle(2)->multMatrix(translationMatrix);
// Update plane center
m_Center= translationMatrix * m_Center;
m_Previous= sliddingPoint;
// Plane throw intersection and plane normal and camera up vector
GLC_Plane sliddingPlane(GLC_3DWidget::widgetManagerHandle()->cameraHandle()->forward().normalize(), m_Previous);
m_SlidingPlane= sliddingPlane;
emit asChanged();
return glc::AcceptEvent;
}
void GLC_CuttingPlane::create3DviewInstance()
{
Q_ASSERT(GLC_3DWidget::isEmpty());
// The cutting plane material
GLC_Material* pMaterial= new GLC_Material(m_Color);
pMaterial->setOpacity(m_Opacity);
// Cutting plane 3Dview instance
GLC_3DViewInstance cuttingPlaneInstance= GLC_Factory::instance()->createCuttingPlane(m_Center, m_Normal, m_L1, m_L2, pMaterial);
GLC_3DWidget::add3DViewInstance(cuttingPlaneInstance);
// Normal arrow geometry
GLC_Arrow* pArrow= new GLC_Arrow(GLC_Point3d(), -m_Normal, GLC_3DWidget::widgetManagerHandle()->cameraHandle()->forward().normalize());
pArrow->setLineWidth(2.5);
QColor arrowColor(Qt::red);
arrowColor.setAlphaF(0.4);
pArrow->setWireColor(arrowColor);
if (pArrow->isTransparent())
{
qDebug() << "Arrow is transparent";
}
else
{
qDebug() << "Arrow is NOT transparent";
}
//Base arrow disc
pMaterial= new GLC_Material(Qt::red);
pMaterial->setOpacity(m_Opacity);
GLC_Disc* pDisc= new GLC_Disc(1.0);
pDisc->replaceMasterMaterial(pMaterial);
// Normal arrow + base instance
GLC_3DViewInstance normalLine(pArrow);
GLC_3DWidget::add3DViewInstance(normalLine);
GLC_3DWidget::set3DViewInstanceVisibility(1, false);
GLC_3DViewInstance normalBase(pDisc);
GLC_3DWidget::add3DViewInstance(normalBase);
GLC_3DWidget::set3DViewInstanceVisibility(2, false);
}
void GLC_CuttingPlane::prepareToSlide()
{
// Plane throw intersection and plane normal and camera up vector
GLC_Plane sliddingPlane(GLC_3DWidget::widgetManagerHandle()->cameraHandle()->forward().normalize(), m_Previous);
m_SlidingPlane= sliddingPlane;
// Projection of intersection point on slidding plane
const GLC_Point3d eye(GLC_3DWidget::widgetManagerHandle()->cameraHandle()->eye());
const GLC_Vector3d direction((m_Previous - eye).normalize());
GLC_Line3d projectionLine(m_Previous, direction);
glc::lineIntersectPlane(projectionLine, m_SlidingPlane, &m_Previous);
//m_Previous= glc::project(m_Previous, GLC_Line3d(m_Previous, m_Normal));
}
void GLC_CuttingPlane::updateArrow(double length)
{
GLC_Arrow* pArrow= dynamic_cast<GLC_Arrow*>(GLC_3DWidget::instanceHandle(1)->geomAt(0));
Q_ASSERT(NULL != pArrow);
pArrow->setEndPoint(-m_Normal * length);
pArrow->setHeadLength(length * 0.15);
pArrow->setViewDir(GLC_3DWidget::widgetManagerHandle()->cameraHandle()->forward().normalize());
GLC_Disc* pDisc= dynamic_cast<GLC_Disc*>(GLC_3DWidget::instanceHandle(2)->geomAt(0));
Q_ASSERT(NULL != pDisc);
pDisc->setRadius(length * 0.3);
}
<|endoftext|> |
<commit_before>/* Copyright 2016 Carnegie Mellon University
*
* 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 "scanner/video/decoder_automata.h"
#include "scanner/metadata.pb.h"
#include "scanner/util/h264.h"
#include "scanner/util/memory.h"
#include <thread>
namespace scanner {
namespace internal {
DecoderAutomata::DecoderAutomata(DeviceHandle device_handle, i32 num_devices,
VideoDecoderType decoder_type)
: device_handle_(device_handle),
num_devices_(num_devices),
decoder_type_(decoder_type),
decoder_(
VideoDecoder::make_from_config(device_handle, num_devices, decoder_type)),
feeder_waiting_(false),
not_done_(true),
frames_retrieved_(0),
skip_frames_(false) {
feeder_thread_ = std::thread(&DecoderAutomata::feeder, this);
}
DecoderAutomata::~DecoderAutomata() {
{
frames_to_get_ = 0;
frames_retrieved_ = 0;
while (decoder_->discard_frame()) {
}
std::unique_lock<std::mutex> lk(feeder_mutex_);
wake_feeder_.wait(lk, [this] { return feeder_waiting_.load(); });
if (frames_retrieved_ > 0) {
decoder_->feed(nullptr, 0, true);
}
not_done_ = false;
feeder_waiting_ = false;
}
wake_feeder_.notify_one();
feeder_thread_.join();
}
void DecoderAutomata::initialize(
const std::vector<proto::DecodeArgs>& encoded_data) {
assert(!encoded_data.empty());
encoded_data_ = encoded_data;
frame_size_ = encoded_data[0].width() * encoded_data[0].height() * 3;
current_frame_ = encoded_data[0].start_keyframe();
next_frame_.store(encoded_data[0].valid_frames(0), std::memory_order_release);
retriever_data_idx_.store(0, std::memory_order_release);
retriever_valid_idx_ = 0;
FrameInfo info;
info.set_width(encoded_data[0].width());
info.set_height(encoded_data[0].height());
while (decoder_->discard_frame()) {
}
std::unique_lock<std::mutex> lk(feeder_mutex_);
wake_feeder_.wait(lk, [this] { return feeder_waiting_.load(); });
if (info_.width() != info.width() || info_.height() != info.height()) {
decoder_->configure(info);
}
if (frames_retrieved_ > 0) {
decoder_->feed(nullptr, 0, true);
}
set_feeder_idx(0);
info_ = info;
std::atomic_thread_fence(std::memory_order_release);
seeking_ = false;
}
void DecoderAutomata::get_frames(u8* buffer, i32 num_frames) {
i64 total_frames_decoded = 0;
i64 total_frames_used = 0;
auto start = now();
// Wait until feeder is waiting
{
// Wait until frames are being requested
std::unique_lock<std::mutex> lk(feeder_mutex_);
wake_feeder_.wait(lk, [this] { return feeder_waiting_.load(); });
}
// Start up feeder thread
{
std::unique_lock<std::mutex> lk(feeder_mutex_);
frames_retrieved_ = 0;
frames_to_get_ = num_frames;
feeder_waiting_ = false;
}
wake_feeder_.notify_one();
if (profiler_) {
profiler_->add_interval("get_frames_wait", start, now());
}
while (frames_retrieved_ < frames_to_get_) {
if (decoder_->decoded_frames_buffered() > 0) {
auto iter = now();
// New frames
bool more_frames = true;
while (more_frames && frames_retrieved_ < frames_to_get_) {
const auto& valid_frames =
encoded_data_[retriever_data_idx_].valid_frames();
assert(valid_frames.size() > retriever_valid_idx_.load());
assert(current_frame_ <= valid_frames.Get(retriever_valid_idx_));
// printf("has buffered frames, curr %d, next %d\n",
// current_frame_, valid_frames.Get(retriever_valid_idx_));
if (current_frame_ == valid_frames.Get(retriever_valid_idx_)) {
u8* decoded_buffer = buffer + frames_retrieved_ * frame_size_;
more_frames = decoder_->get_frame(decoded_buffer, frame_size_);
retriever_valid_idx_++;
if (retriever_valid_idx_ == valid_frames.size()) {
// Move to next decode args
retriever_data_idx_ += 1;
retriever_valid_idx_ = 0;
// Trigger feeder to start again and set ourselves to the
// start of that keyframe
if (retriever_data_idx_ < encoded_data_.size()) {
{
// Wait until feeder is waiting
// skip_frames_ = true;
std::unique_lock<std::mutex> lk(feeder_mutex_);
wake_feeder_.wait(lk, [this, &total_frames_decoded] {
while (decoder_->discard_frame()) {
total_frames_decoded++;
}
return feeder_waiting_.load();
});
// skip_frames_ = false;
}
{
std::unique_lock<std::mutex> lk(feeder_mutex_);
feeder_waiting_ = false;
current_frame_ =
encoded_data_[retriever_data_idx_].keyframes(0) - 1;
}
wake_feeder_.notify_one();
} else {
assert(frames_retrieved_ + 1 == frames_to_get_);
}
}
if (retriever_data_idx_ < encoded_data_.size()) {
next_frame_.store(encoded_data_[retriever_data_idx_].valid_frames(
retriever_valid_idx_),
std::memory_order_release);
}
// printf("got frame %d\n", frames_retrieved_.load());
total_frames_used++;
frames_retrieved_++;
} else {
more_frames = decoder_->discard_frame();
}
current_frame_++;
total_frames_decoded++;
// printf("curr frame %d, frames decoded %d\n", current_frame_,
// total_frames_decoded);
}
if (profiler_) {
profiler_->add_interval("iter", iter, now());
}
}
std::this_thread::yield();
}
decoder_->wait_until_frames_copied();
if (profiler_) {
profiler_->add_interval("get_frames", start, now());
profiler_->increment("frames_used", total_frames_used);
profiler_->increment("frames_decoded", total_frames_decoded);
}
}
void DecoderAutomata::set_profiler(Profiler* profiler) {
profiler_ = profiler;
decoder_->set_profiler(profiler);
}
void DecoderAutomata::feeder() {
// printf("feeder start\n");
i64 total_frames_fed = 0;
i32 frames_fed = 0;
seeking_ = false;
while (not_done_) {
{
// Wait until frames are being requested
std::unique_lock<std::mutex> lk(feeder_mutex_);
feeder_waiting_ = true;
}
wake_feeder_.notify_one();
{
std::unique_lock<std::mutex> lk(feeder_mutex_);
wake_feeder_.wait(lk, [this] { return !feeder_waiting_; });
}
std::atomic_thread_fence(std::memory_order_acquire);
// Ignore requests to feed if we have alredy fed all data
if (encoded_data_.size() <= feeder_data_idx_) {
continue;
}
if (seeking_) {
decoder_->feed(nullptr, 0, true);
seeking_ = false;
}
if (profiler_) {
profiler_->increment("frames_fed", frames_fed);
}
frames_fed = 0;
bool seen_metadata = false;
while (frames_retrieved_ < frames_to_get_) {
i32 frames_to_wait = 8;
while (frames_retrieved_ < frames_to_get_ &&
decoder_->decoded_frames_buffered() > frames_to_wait) {
wake_feeder_.notify_one();
std::this_thread::yield();
}
if (skip_frames_) {
seen_metadata = false;
seeking_ = true;
set_feeder_idx(feeder_data_idx_ + 1);
break;
}
frames_fed++;
i32 fdi = feeder_data_idx_.load(std::memory_order_acquire);
const u8* encoded_buffer =
(const u8*)encoded_data_[fdi].mutable_encoded_video()->data();
size_t encoded_buffer_size =
encoded_data_[fdi].mutable_encoded_video()->size();
i32 encoded_packet_size = 0;
const u8* encoded_packet = NULL;
if (feeder_buffer_offset_ < encoded_buffer_size) {
encoded_packet_size =
*reinterpret_cast<const i32*>(encoded_buffer + feeder_buffer_offset_);
feeder_buffer_offset_ += sizeof(i32);
encoded_packet = encoded_buffer + feeder_buffer_offset_;
assert(encoded_packet_size < encoded_buffer_size);
feeder_buffer_offset_ += encoded_packet_size;
// printf("encoded packet size %d, ptr %p\n", encoded_packet_size,
// encoded_packet);
}
if (seen_metadata && encoded_packet_size > 0) {
const u8* start_buffer = encoded_packet;
i32 original_size = encoded_packet_size;
while (encoded_packet_size > 0) {
const u8* nal_start;
i32 nal_size;
next_nal(encoded_packet, encoded_packet_size, nal_start, nal_size);
if (encoded_packet_size == 0) {
break;
}
i32 nal_type = get_nal_unit_type(nal_start);
i32 nal_ref = get_nal_ref_idc(nal_start);
if (is_vcl_nal(nal_type)) {
encoded_packet = nal_start -= 3;
encoded_packet_size = nal_size + encoded_packet_size + 3;
break;
}
}
}
decoder_->feed(encoded_packet, encoded_packet_size, false);
if (feeder_current_frame_ == feeder_next_frame_) {
feeder_valid_idx_++;
if (feeder_valid_idx_ <
encoded_data_[feeder_data_idx_].valid_frames_size()) {
feeder_next_frame_ =
encoded_data_[feeder_data_idx_].valid_frames(feeder_valid_idx_);
} else {
// Done
feeder_next_frame_ = -1;
}
}
feeder_current_frame_++;
// Set a discontinuity if we sent an empty packet to reset
// the stream next time
if (encoded_packet_size == 0) {
assert(feeder_buffer_offset_ >= encoded_buffer_size);
// Reached the end of a decoded segment so wait for decoder to flush
// before moving onto next segment
seen_metadata = false;
seeking_ = true;
set_feeder_idx(feeder_data_idx_ + 1);
break;
} else {
seen_metadata = true;
}
std::this_thread::yield();
}
// printf("frames fed %d\n", frames_fed);
}
}
void DecoderAutomata::set_feeder_idx(i32 data_idx) {
feeder_data_idx_ = data_idx;
feeder_valid_idx_ = 0;
feeder_buffer_offset_ = 0;
if (feeder_data_idx_ < encoded_data_.size()) {
feeder_current_frame_ = encoded_data_[feeder_data_idx_].keyframes(0);
feeder_next_frame_ = encoded_data_[feeder_data_idx_].valid_frames(0);
feeder_next_keyframe_ = encoded_data_[feeder_data_idx_].keyframes(1);
}
}
}
}
<commit_msg>Fix race condition in decoder and reading invalid frames after seek<commit_after>/* Copyright 2016 Carnegie Mellon University
*
* 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 "scanner/video/decoder_automata.h"
#include "scanner/metadata.pb.h"
#include "scanner/util/h264.h"
#include "scanner/util/memory.h"
#include <thread>
namespace scanner {
namespace internal {
DecoderAutomata::DecoderAutomata(DeviceHandle device_handle, i32 num_devices,
VideoDecoderType decoder_type)
: device_handle_(device_handle),
num_devices_(num_devices),
decoder_type_(decoder_type),
decoder_(
VideoDecoder::make_from_config(device_handle, num_devices, decoder_type)),
feeder_waiting_(false),
not_done_(true),
frames_retrieved_(0),
skip_frames_(false) {
feeder_thread_ = std::thread(&DecoderAutomata::feeder, this);
}
DecoderAutomata::~DecoderAutomata() {
{
frames_to_get_ = 0;
frames_retrieved_ = 0;
while (decoder_->discard_frame()) {
}
std::unique_lock<std::mutex> lk(feeder_mutex_);
wake_feeder_.wait(lk, [this] { return feeder_waiting_.load(); });
if (frames_retrieved_ > 0) {
decoder_->feed(nullptr, 0, true);
}
not_done_ = false;
feeder_waiting_ = false;
}
wake_feeder_.notify_one();
feeder_thread_.join();
}
void DecoderAutomata::initialize(
const std::vector<proto::DecodeArgs>& encoded_data) {
assert(!encoded_data.empty());
encoded_data_ = encoded_data;
frame_size_ = encoded_data[0].width() * encoded_data[0].height() * 3;
current_frame_ = encoded_data[0].start_keyframe();
next_frame_.store(encoded_data[0].valid_frames(0), std::memory_order_release);
retriever_data_idx_.store(0, std::memory_order_release);
retriever_valid_idx_ = 0;
FrameInfo info;
info.set_width(encoded_data[0].width());
info.set_height(encoded_data[0].height());
while (decoder_->discard_frame()) {
}
std::unique_lock<std::mutex> lk(feeder_mutex_);
wake_feeder_.wait(lk, [this] { return feeder_waiting_.load(); });
if (info_.width() != info.width() || info_.height() != info.height()) {
decoder_->configure(info);
}
if (frames_retrieved_ > 0) {
decoder_->feed(nullptr, 0, true);
}
set_feeder_idx(0);
info_ = info;
std::atomic_thread_fence(std::memory_order_release);
seeking_ = false;
}
void DecoderAutomata::get_frames(u8* buffer, i32 num_frames) {
i64 total_frames_decoded = 0;
i64 total_frames_used = 0;
auto start = now();
// Wait until feeder is waiting
{
// Wait until frames are being requested
std::unique_lock<std::mutex> lk(feeder_mutex_);
wake_feeder_.wait(lk, [this] { return feeder_waiting_.load(); });
}
if (seeking_) {
decoder_->feed(nullptr, 0, true);
seeking_ = false;
}
// Start up feeder thread
{
std::unique_lock<std::mutex> lk(feeder_mutex_);
frames_retrieved_ = 0;
frames_to_get_ = num_frames;
feeder_waiting_ = false;
}
wake_feeder_.notify_one();
if (profiler_) {
profiler_->add_interval("get_frames_wait", start, now());
}
while (frames_retrieved_ < frames_to_get_) {
if (decoder_->decoded_frames_buffered() > 0) {
auto iter = now();
// New frames
bool more_frames = true;
while (more_frames && frames_retrieved_ < frames_to_get_) {
const auto& valid_frames =
encoded_data_[retriever_data_idx_].valid_frames();
assert(valid_frames.size() > retriever_valid_idx_.load());
assert(current_frame_ <= valid_frames.Get(retriever_valid_idx_));
// printf("has buffered frames, curr %d, next %d\n",
// current_frame_, valid_frames.Get(retriever_valid_idx_));
if (current_frame_ == valid_frames.Get(retriever_valid_idx_)) {
u8* decoded_buffer = buffer + frames_retrieved_ * frame_size_;
more_frames = decoder_->get_frame(decoded_buffer, frame_size_);
retriever_valid_idx_++;
if (retriever_valid_idx_ == valid_frames.size()) {
// Move to next decode args
retriever_data_idx_ += 1;
retriever_valid_idx_ = 0;
// Trigger feeder to start again and set ourselves to the
// start of that keyframe
if (retriever_data_idx_ < encoded_data_.size()) {
{
// Wait until feeder is waiting
// skip_frames_ = true;
std::unique_lock<std::mutex> lk(feeder_mutex_);
wake_feeder_.wait(lk, [this, &total_frames_decoded] {
while (decoder_->discard_frame()) {
total_frames_decoded++;
}
return feeder_waiting_.load();
});
// skip_frames_ = false;
}
if (seeking_) {
decoder_->feed(nullptr, 0, true);
seeking_ = false;
}
{
std::unique_lock<std::mutex> lk(feeder_mutex_);
feeder_waiting_ = false;
current_frame_ =
encoded_data_[retriever_data_idx_].keyframes(0) - 1;
}
wake_feeder_.notify_one();
// We reset the decoder, so we should wait until there are more
// frames in the buffer
more_frames = false;
} else {
assert(frames_retrieved_ + 1 == frames_to_get_);
}
}
if (retriever_data_idx_ < encoded_data_.size()) {
next_frame_.store(encoded_data_[retriever_data_idx_].valid_frames(
retriever_valid_idx_),
std::memory_order_release);
}
// printf("got frame %d\n", frames_retrieved_.load());
total_frames_used++;
frames_retrieved_++;
} else {
more_frames = decoder_->discard_frame();
}
current_frame_++;
total_frames_decoded++;
// printf("curr frame %d, frames decoded %d\n", current_frame_,
// total_frames_decoded);
}
if (profiler_) {
profiler_->add_interval("iter", iter, now());
}
}
std::this_thread::yield();
}
decoder_->wait_until_frames_copied();
if (profiler_) {
profiler_->add_interval("get_frames", start, now());
profiler_->increment("frames_used", total_frames_used);
profiler_->increment("frames_decoded", total_frames_decoded);
}
}
void DecoderAutomata::set_profiler(Profiler* profiler) {
profiler_ = profiler;
decoder_->set_profiler(profiler);
}
void DecoderAutomata::feeder() {
// printf("feeder start\n");
i64 total_frames_fed = 0;
i32 frames_fed = 0;
seeking_ = false;
while (not_done_) {
{
// Wait until frames are being requested
std::unique_lock<std::mutex> lk(feeder_mutex_);
feeder_waiting_ = true;
}
wake_feeder_.notify_one();
{
std::unique_lock<std::mutex> lk(feeder_mutex_);
wake_feeder_.wait(lk, [this] { return !feeder_waiting_; });
}
std::atomic_thread_fence(std::memory_order_acquire);
// Ignore requests to feed if we have alredy fed all data
if (encoded_data_.size() <= feeder_data_idx_) {
continue;
}
if (seeking_) {
decoder_->feed(nullptr, 0, true);
seeking_ = false;
}
if (profiler_) {
profiler_->increment("frames_fed", frames_fed);
}
frames_fed = 0;
bool seen_metadata = false;
while (frames_retrieved_ < frames_to_get_) {
i32 frames_to_wait = 8;
while (frames_retrieved_ < frames_to_get_ &&
decoder_->decoded_frames_buffered() > frames_to_wait) {
wake_feeder_.notify_one();
std::this_thread::yield();
}
if (skip_frames_) {
seen_metadata = false;
seeking_ = true;
set_feeder_idx(feeder_data_idx_ + 1);
break;
}
frames_fed++;
i32 fdi = feeder_data_idx_.load(std::memory_order_acquire);
const u8* encoded_buffer =
(const u8*)encoded_data_[fdi].mutable_encoded_video()->data();
size_t encoded_buffer_size =
encoded_data_[fdi].mutable_encoded_video()->size();
i32 encoded_packet_size = 0;
const u8* encoded_packet = NULL;
if (feeder_buffer_offset_ < encoded_buffer_size) {
encoded_packet_size =
*reinterpret_cast<const i32*>(encoded_buffer + feeder_buffer_offset_);
feeder_buffer_offset_ += sizeof(i32);
encoded_packet = encoded_buffer + feeder_buffer_offset_;
assert(encoded_packet_size < encoded_buffer_size);
feeder_buffer_offset_ += encoded_packet_size;
// printf("encoded packet size %d, ptr %p\n", encoded_packet_size,
// encoded_packet);
}
if (seen_metadata && encoded_packet_size > 0) {
const u8* start_buffer = encoded_packet;
i32 original_size = encoded_packet_size;
while (encoded_packet_size > 0) {
const u8* nal_start;
i32 nal_size;
next_nal(encoded_packet, encoded_packet_size, nal_start, nal_size);
if (encoded_packet_size == 0) {
break;
}
i32 nal_type = get_nal_unit_type(nal_start);
i32 nal_ref = get_nal_ref_idc(nal_start);
if (is_vcl_nal(nal_type)) {
encoded_packet = nal_start -= 3;
encoded_packet_size = nal_size + encoded_packet_size + 3;
break;
}
}
}
decoder_->feed(encoded_packet, encoded_packet_size, false);
if (feeder_current_frame_ == feeder_next_frame_) {
feeder_valid_idx_++;
if (feeder_valid_idx_ <
encoded_data_[feeder_data_idx_].valid_frames_size()) {
feeder_next_frame_ =
encoded_data_[feeder_data_idx_].valid_frames(feeder_valid_idx_);
} else {
// Done
feeder_next_frame_ = -1;
}
}
feeder_current_frame_++;
// Set a discontinuity if we sent an empty packet to reset
// the stream next time
if (encoded_packet_size == 0) {
assert(feeder_buffer_offset_ >= encoded_buffer_size);
// Reached the end of a decoded segment so wait for decoder to flush
// before moving onto next segment
seen_metadata = false;
seeking_ = true;
set_feeder_idx(feeder_data_idx_ + 1);
break;
} else {
seen_metadata = true;
}
std::this_thread::yield();
}
// printf("frames fed %d\n", frames_fed);
}
}
void DecoderAutomata::set_feeder_idx(i32 data_idx) {
feeder_data_idx_ = data_idx;
feeder_valid_idx_ = 0;
feeder_buffer_offset_ = 0;
if (feeder_data_idx_ < encoded_data_.size()) {
feeder_current_frame_ = encoded_data_[feeder_data_idx_].keyframes(0);
feeder_next_frame_ = encoded_data_[feeder_data_idx_].valid_frames(0);
feeder_next_keyframe_ = encoded_data_[feeder_data_idx_].keyframes(1);
}
}
}
}
<|endoftext|> |
<commit_before>#include "CASCImage.h"
#include "../DesktopEditor/raster/Metafile/MetaFile.h"
#include "../DesktopEditor/graphics/Image.h"
#if defined(_WIN32) || defined (_WIN64)
#else
#include <unistd.h>
#endif
namespace NSHtmlRenderer
{
CASCImage::CASCImage(CApplicationFonts *pAppFonts)
{
m_pMetafile = new MetaFile::CMetaFile(pAppFonts);
m_pMediaData = NULL;
m_bLoadOnlyMeta = false;
m_lImageType = c_lImageTypeUnknown;
m_dDpiX = 72;
m_dDpiY = 72;
m_wsTempFilePath.Empty();
}
CASCImage::~CASCImage()
{
Close();
RELEASEOBJECT(m_pMetafile);
}
void CASCImage::Open(const std::wstring& bsFilePath)
{
// Закроем раннее открытый файл (если он был открыт)
Close();
if (m_pMetafile == NULL) return;
// Сначала попытаемя открыть файл как WMF/EMF
if ( m_pMetafile->LoadFromFile( bsFilePath.c_str() ) == true )
{
// Файл открылся нормально
long MetaType = m_pMetafile->GetType();
m_lImageType = c_lImageTypeMetafile | MetaType;
if (MetaType == c_lMetaWmf) return;
//#if !defined(_WIN32) && !defined (_WIN64) // emf всеже под win лучше читать через gdi+
if (MetaType == c_lMetaEmf) return;
//#endif
}
// Это не Wmf & Emf
m_pMetafile->Close();
{
m_pMediaData = new Aggplus::CImage(bsFilePath);
if(Aggplus::Ok == m_pMediaData->GetLastStatus())
m_lImageType = c_lImageTypeBitmap;
else
m_pMediaData = NULL;
}
return;
}
void CASCImage::Close()
{
if ( m_lImageType & c_lImageTypeMetafile )
{
m_pMetafile->Close();
if ( m_lImageType & c_lMetaEmf )
{
// Удаляем временный файл
//todo может проверять не пустой ли m_wsTempFilePath, а не m_lImageType & c_lMetaEmf
#if defined(_WIN32) || defined (_WIN64)
::_wunlink( m_wsTempFilePath.GetBuffer() );
#else
std::string sTempFilePath = NSFile::CUtf8Converter::GetUtf8StringFromUnicode2(m_wsTempFilePath.c_str(), m_wsTempFilePath.length());
::unlink( sTempFilePath.c_str() );
#endif
}
}
m_lImageType = c_lImageTypeUnknown;
m_wsTempFilePath = _T("");
RELEASEOBJECT(m_pMediaData);
}
HRESULT CASCImage::get_Type(LONG* lType)
{
if (NULL != lType)
*lType = m_lImageType;
return S_OK;
}
HRESULT CASCImage::get_Width(LONG* lWidth)
{
if ( NULL != lWidth )
{
if (NULL != m_pMediaData)
{
*lWidth = m_pMediaData->GetWidth();
}
else if ( (c_lImageTypeMetafile | c_lMetaWmf) == m_lImageType || (c_lImageTypeMetafile | c_lMetaEmf) == m_lImageType )
{
double x=0, y=0, w=0, h=0;
m_pMetafile->GetBounds(&x,&y,&w,&h);
*lWidth = (LONG)w;
}
else
{
*lWidth = 0;
}
}
return S_OK;
}
HRESULT CASCImage::put_Width(LONG lWidth)
{
return S_OK;
}
HRESULT CASCImage::get_Height(LONG* lHeight)
{
if ( NULL != lHeight )
{
if (NULL != m_pMediaData)
{
*lHeight = m_pMediaData->GetHeight();
}
else if ( (c_lImageTypeMetafile | c_lMetaWmf) == m_lImageType || (c_lImageTypeMetafile | c_lMetaEmf) == m_lImageType )
{
double x=0, y=0, w=0, h=0;
m_pMetafile->GetBounds(&x,&y,&w,&h);
*lHeight = (LONG)h;
}
else
{
*lHeight = 0;
}
}
return S_OK;
}
HRESULT CASCImage::put_Height(LONG lHeight)
{
return S_OK;
}
HRESULT CASCImage::get_DpiX(double* dDpiX)
{
*dDpiX = m_dDpiX;
return S_OK;
}
HRESULT CASCImage::put_DpiX(double dDpiX)
{
m_dDpiX = dDpiX;
return S_OK;
}
HRESULT CASCImage::get_DpiY(double* dDpiY)
{
*dDpiY = m_dDpiY;
return S_OK;
}
HRESULT CASCImage::put_DpiY(double dDpiY)
{
m_dDpiY = dDpiY;
return S_OK;
}
HRESULT CASCImage::LoadFromFile(const std::wstring& bsFilePath)
{
// Внутри комманды Open выполняется команда Close
Open( bsFilePath );
return S_OK;
}
HRESULT CASCImage::DrawOnRenderer(IRenderer* pRenderer, double dX, double dY, double dWidth, double dHeight)
{
if (NULL == pRenderer)
return S_FALSE;
pRenderer->BeginCommand(c_nImageType);
if ( NULL != m_pMediaData )
{
pRenderer->DrawImage(m_pMediaData, dX, dY, dWidth, dHeight);
}
else if ( (c_lImageTypeMetafile | c_lMetaWmf) == m_lImageType ||
(c_lImageTypeMetafile | c_lMetaEmf) == m_lImageType )
{
m_pMetafile->DrawOnRenderer(pRenderer, dX, dY, dWidth, dHeight);
}
pRenderer->EndCommand(c_nImageType);
return S_OK;
}
//-------------------------------------------------------------------------------------------
// IASCGraphicsBase
//-------------------------------------------------------------------------------------------
HRESULT CASCImage::LoadOnlyMeta(bool bVal)
{
m_bLoadOnlyMeta = bVal;
return S_OK;
}
HRESULT CASCImage::LoadSVG(const std::wstring& sVal)
{
//Close();
//CoCreateInstance( __uuidof(SVGTransformer), NULL, CLSCTX_ALL, __uuidof(ISVGTransformer), (void**)(&m_pSVGFile) );
//if (NULL != m_pSVGFile)
//{
// if ( AVS_ERROR_FILEFORMAT == m_pSVGFile->Load( ParamValue.bstrVal ) )
// {
// RELEASEINTERFACE( m_pSVGFile );
// return S_FALSE;
// }
// else
// {
// m_lImageType = c_lImageTypeMetafile | c_lMetaSVG;
// }
//}
return S_OK;
}
CFontManager* CASCImage::get_FontManager()
{
return m_pMetafile->get_FontManager();
}
Aggplus::CImage* CASCImage::get_BitmapImage()
{
return m_pMediaData;
}
}
<commit_msg>to Revision: 65026<commit_after>#include "CASCImage.h"
#include "../DesktopEditor/raster/Metafile/MetaFile.h"
#include "../DesktopEditor/graphics/Image.h"
#if defined(_WIN32) || defined (_WIN64)
#else
#include <unistd.h>
#endif
namespace NSHtmlRenderer
{
CASCImage::CASCImage(CApplicationFonts *pAppFonts)
{
m_pMetafile = new MetaFile::CMetaFile(pAppFonts);
m_pMediaData = NULL;
m_bLoadOnlyMeta = false;
m_lImageType = c_lImageTypeUnknown;
m_dDpiX = 72;
m_dDpiY = 72;
m_wsTempFilePath.Empty();
}
CASCImage::~CASCImage()
{
Close();
RELEASEOBJECT(m_pMetafile);
}
void CASCImage::Open(const std::wstring& bsFilePath)
{
// Закроем раннее открытый файл (если он был открыт)
Close();
if (m_pMetafile == NULL) return;
// Сначала попытаемя открыть файл как WMF/EMF
if ( m_pMetafile->LoadFromFile( bsFilePath.c_str() ) == true )
{
// Файл открылся нормально
long MetaType = m_pMetafile->GetType();
m_lImageType = c_lImageTypeMetafile | MetaType;
if (MetaType == c_lMetaWmf) return;
//#if !defined(_WIN32) && !defined (_WIN64) // emf всеже под win лучше читать через gdi+
if (MetaType == c_lMetaEmf) return;
//#endif
}
// Это не Wmf & Emf
m_pMetafile->Close();
{
m_pMediaData = new Aggplus::CImage(bsFilePath);
if(Aggplus::Ok == m_pMediaData->GetLastStatus())
m_lImageType = c_lImageTypeBitmap;
else
m_pMediaData = NULL;
}
return;
}
void CASCImage::Close()
{
if ( m_lImageType & c_lImageTypeMetafile )
{
m_pMetafile->Close();
if ( m_lImageType & c_lMetaEmf )
{
// Удаляем временный файл
//todo может проверять не пустой ли m_wsTempFilePath, а не m_lImageType & c_lMetaEmf
#if defined(_WIN32) || defined (_WIN64)
::_wunlink( m_wsTempFilePath.GetBuffer() );
#else
std::string sTempFilePath = NSFile::CUtf8Converter::GetUtf8StringFromUnicode2(m_wsTempFilePath.c_str(), m_wsTempFilePath.length());
::unlink( sTempFilePath.c_str() );
#endif
}
}
m_lImageType = c_lImageTypeUnknown;
m_wsTempFilePath = _T("");
RELEASEOBJECT(m_pMediaData);
}
HRESULT CASCImage::get_Type(LONG* lType)
{
if (NULL != lType)
*lType = m_lImageType;
return S_OK;
}
HRESULT CASCImage::get_Width(LONG* lWidth)
{
if ( NULL != lWidth )
{
if (NULL != m_pMediaData)
{
*lWidth = m_pMediaData->GetWidth();
}
else if ( (c_lImageTypeMetafile | c_lMetaWmf) == m_lImageType || (c_lImageTypeMetafile | c_lMetaEmf) == m_lImageType )
{
double x=0, y=0, w=0, h=0;
m_pMetafile->GetBounds(&x,&y,&w,&h);
*lWidth = (LONG)w;
}
else
{
*lWidth = 0;
}
}
return S_OK;
}
HRESULT CASCImage::put_Width(LONG lWidth)
{
return S_OK;
}
HRESULT CASCImage::get_Height(LONG* lHeight)
{
if ( NULL != lHeight )
{
if (NULL != m_pMediaData)
{
*lHeight = m_pMediaData->GetHeight();
}
else if ( (c_lImageTypeMetafile | c_lMetaWmf) == m_lImageType || (c_lImageTypeMetafile | c_lMetaEmf) == m_lImageType )
{
double x=0, y=0, w=0, h=0;
m_pMetafile->GetBounds(&x,&y,&w,&h);
*lHeight = (LONG)h;
}
else
{
*lHeight = 0;
}
}
return S_OK;
}
HRESULT CASCImage::put_Height(LONG lHeight)
{
return S_OK;
}
HRESULT CASCImage::get_DpiX(double* dDpiX)
{
*dDpiX = m_dDpiX;
return S_OK;
}
HRESULT CASCImage::put_DpiX(double dDpiX)
{
m_dDpiX = dDpiX;
return S_OK;
}
HRESULT CASCImage::get_DpiY(double* dDpiY)
{
*dDpiY = m_dDpiY;
return S_OK;
}
HRESULT CASCImage::put_DpiY(double dDpiY)
{
m_dDpiY = dDpiY;
return S_OK;
}
HRESULT CASCImage::LoadFromFile(const std::wstring& bsFilePath)
{
// Внутри комманды Open выполняется команда Close
Open( bsFilePath );
return S_OK;
}
HRESULT CASCImage::DrawOnRenderer(IRenderer* pRenderer, double dX, double dY, double dWidth, double dHeight)
{
if (NULL == pRenderer)
return S_FALSE;
pRenderer->BeginCommand(c_nImageType);
if ( NULL != m_pMediaData )
{
pRenderer->DrawImage(m_pMediaData, dX, dY, dWidth, dHeight);
}
else if ( (c_lImageTypeMetafile | c_lMetaWmf) == m_lImageType ||
(c_lImageTypeMetafile | c_lMetaEmf) == m_lImageType )
{
m_pMetafile->DrawOnRenderer(pRenderer, dX, dY, dWidth, dHeight);
}
pRenderer->EndCommand(c_nImageType);
return S_OK;
}
//-------------------------------------------------------------------------------------------
// IASCGraphicsBase
//-------------------------------------------------------------------------------------------
HRESULT CASCImage::LoadOnlyMeta(bool bVal)
{
m_bLoadOnlyMeta = bVal;
return S_OK;
}
HRESULT CASCImage::LoadSVG(const std::wstring& sVal)
{
//Close();
//CoCreateInstance( __uuidof(SVGTransformer), NULL, CLSCTX_ALL, __uuidof(ISVGTransformer), (void**)(&m_pSVGFile) );
//if (NULL != m_pSVGFile)
//{
// if ( AVS_ERROR_FILEFORMAT == m_pSVGFile->Load( ParamValue.bstrVal ) )
// {
// RELEASEINTERFACE( m_pSVGFile );
// return S_FALSE;
// }
// else
// {
// m_lImageType = c_lImageTypeMetafile | c_lMetaSVG;
// }
//}
return S_OK;
}
CFontManager* CASCImage::get_FontManager()
{
return m_pMetafile->get_FontManager();
}
void CASCImage::put_FontManager(CFontManager* pManager)
{
//ничего не делаем, потому что CFontManager пришел в конструкторе.
}
Aggplus::CImage* CASCImage::get_BitmapImage()
{
return m_pMediaData;
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: TextObjectBar.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: kz $ $Date: 2006-12-12 17:39:12 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef SD_TEXT_OBJECT_BAR_HXX
#define SD_TEXT_OBJECT_BAR_HXX
#ifndef _SFXMODULE_HXX //autogen
#include <sfx2/module.hxx>
#endif
#ifndef _SFX_SHELL_HXX //autogen
#include <sfx2/shell.hxx>
#endif
#ifndef _SD_GLOB_HXX
#include "glob.hxx"
#endif
class CommandEvent;
namespace sd {
class View;
class ViewShell;
class Window;
class TextObjectBar
: public SfxShell
{
public:
TYPEINFO();
SFX_DECL_INTERFACE(SD_IF_SDDRAWTEXTOBJECTBAR)
TextObjectBar (
ViewShell* pSdViewShell,
SfxItemPool& rItemPool,
::sd::View* pSdView);
virtual ~TextObjectBar (void);
void GetAttrState( SfxItemSet& rSet );
void Execute( SfxRequest &rReq );
virtual void Command( const CommandEvent& rCEvt );
private:
ViewShell* mpViewShell;
::sd::View* mpView;
};
} // end of namespace sd
#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.5.298); FILE MERGED 2008/04/01 15:35:18 thb 1.5.298.2: #i85898# Stripping all external header guards 2008/03/31 13:58:11 rt 1.5.298.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: TextObjectBar.hxx,v $
* $Revision: 1.6 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef SD_TEXT_OBJECT_BAR_HXX
#define SD_TEXT_OBJECT_BAR_HXX
#include <sfx2/module.hxx>
#include <sfx2/shell.hxx>
#include "glob.hxx"
class CommandEvent;
namespace sd {
class View;
class ViewShell;
class Window;
class TextObjectBar
: public SfxShell
{
public:
TYPEINFO();
SFX_DECL_INTERFACE(SD_IF_SDDRAWTEXTOBJECTBAR)
TextObjectBar (
ViewShell* pSdViewShell,
SfxItemPool& rItemPool,
::sd::View* pSdView);
virtual ~TextObjectBar (void);
void GetAttrState( SfxItemSet& rSet );
void Execute( SfxRequest &rReq );
virtual void Command( const CommandEvent& rCEvt );
private:
ViewShell* mpViewShell;
::sd::View* mpView;
};
} // end of namespace sd
#endif
<|endoftext|> |
<commit_before>// Copyright (C) 2008 Till Busch [email protected]
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation; either version 2 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#include <osgDB/ReadFile>
#include <simgear/debug/logstream.hxx>
#include <simgear/structure/OSGVersion.hxx>
#include "modellib.hxx"
#include "SGReaderWriterXMLOptions.hxx"
#include "SGPagedLOD.hxx"
using namespace osg;
using namespace simgear;
SGPagedLOD::SGPagedLOD()
: PagedLOD()
{
}
SGPagedLOD::~SGPagedLOD()
{
//SG_LOG(SG_GENERAL, SG_ALERT, "SGPagedLOD::~SGPagedLOD(" << getFileName(0) << ")");
}
SGPagedLOD::SGPagedLOD(const SGPagedLOD& plod,const CopyOp& copyop)
: osg::PagedLOD(plod, copyop),
_readerWriterOptions(plod._readerWriterOptions)
{
}
bool SGPagedLOD::addChild(osg::Node *child)
{
//SG_LOG(SG_GENERAL, SG_ALERT, "SGPagedLOD::addChild(" << getFileName(getNumChildren()) << ")");
if (!PagedLOD::addChild(child))
return false;
setRadius(getBound().radius());
setCenter(getBound().center());
SGReaderWriterXMLOptions* opts;
opts = dynamic_cast<SGReaderWriterXMLOptions*>(_readerWriterOptions.get());
if(opts)
{
osg::ref_ptr<SGModelData> d = opts->getModelData();
if(d.valid())
d->modelLoaded(getFileName(getNumChildren()-1), 0, this);
}
return true;
}
void SGPagedLOD::forceLoad(osgDB::DatabasePager *dbp)
{
//SG_LOG(SG_GENERAL, SG_ALERT, "SGPagedLOD::forceLoad(" <<
//getFileName(getNumChildren()) << ")");
unsigned childNum = getNumChildren();
setTimeStamp(childNum, 0);
double priority=1.0;
dbp->requestNodeFile(getFileName(childNum),this,priority,0,
getDatabaseRequest(childNum),
_readerWriterOptions.get());
}
<commit_msg>Give the models properties as an argument to the init callback.<commit_after>// Copyright (C) 2008 Till Busch [email protected]
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation; either version 2 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#include <osgDB/ReadFile>
#include <simgear/debug/logstream.hxx>
#include <simgear/structure/OSGVersion.hxx>
#include "modellib.hxx"
#include "SGReaderWriterXMLOptions.hxx"
#include "SGPagedLOD.hxx"
using namespace osg;
using namespace simgear;
SGPagedLOD::SGPagedLOD()
: PagedLOD()
{
}
SGPagedLOD::~SGPagedLOD()
{
//SG_LOG(SG_GENERAL, SG_ALERT, "SGPagedLOD::~SGPagedLOD(" << getFileName(0) << ")");
}
SGPagedLOD::SGPagedLOD(const SGPagedLOD& plod,const CopyOp& copyop)
: osg::PagedLOD(plod, copyop),
_readerWriterOptions(plod._readerWriterOptions)
{
}
bool SGPagedLOD::addChild(osg::Node *child)
{
//SG_LOG(SG_GENERAL, SG_ALERT, "SGPagedLOD::addChild(" << getFileName(getNumChildren()) << ")");
if (!PagedLOD::addChild(child))
return false;
setRadius(getBound().radius());
setCenter(getBound().center());
SGReaderWriterXMLOptions* opts;
opts = dynamic_cast<SGReaderWriterXMLOptions*>(_readerWriterOptions.get());
if(opts)
{
osg::ref_ptr<SGModelData> d = opts->getModelData();
if(d.valid())
d->modelLoaded(getFileName(getNumChildren()-1), d->getProperties(),
this);
}
return true;
}
void SGPagedLOD::forceLoad(osgDB::DatabasePager *dbp)
{
//SG_LOG(SG_GENERAL, SG_ALERT, "SGPagedLOD::forceLoad(" <<
//getFileName(getNumChildren()) << ")");
unsigned childNum = getNumChildren();
setTimeStamp(childNum, 0);
double priority=1.0;
dbp->requestNodeFile(getFileName(childNum),this,priority,0,
getDatabaseRequest(childNum),
_readerWriterOptions.get());
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: NeuroLib (DTI command line tools)
Language: C++
Date: $Date: 2009-05-26 16:21:19 $
Version: $Revision: 1.6 $
Author: Casey Goodlett ([email protected])
Copyright (c) Casey Goodlett. All rights reserved.
See NeuroLibCopyright.txt or http://www.ia.unc.edu/dev/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
// STL includes
#include <string>
#include <iostream>
#include <fstream>
// boost includes
#include <boost/program_options/option.hpp>
#include <boost/program_options/options_description.hpp>
#include <boost/program_options/positional_options.hpp>
#include <boost/program_options/variables_map.hpp>
#include <boost/program_options/parsers.hpp>
#include <boost/program_options/cmdline.hpp>
// ITK includes
#include <itkDiffusionTensor3D.h>
#include <itkImageFileReader.h>
#include <itkImageFileWriter.h>
#include <itkTensorLinearInterpolateImageFunction.h>
#include <itkVectorLinearInterpolateImageFunction.h>
#include <itkVersion.h>
//#include "FiberCalculator.h"
#include "deformationfieldoperations.h"
#include "fiberio.h"
#include "dtitypes.h"
namespace po = boost::program_options;
int main(int argc, char* argv[])
{
// Read program options/configuration
po::options_description config("Usage: fiberprocess input-fiber [options]");
config.add_options()
("help,h", "produce this help message")
("verbose,v", "produces verbose output")
("fiber-output,o", po::value<std::string>(), "Output fiber file. May be warped or updated with new data depending on other options used.")
("h-field,H", po::value<std::string>(), "HField for warp and statistics lookup. If this option is used tensor-volume must also be specified.")
("displacement-field", po::value<std::string>(), "Displacement field for warp and statistics lookup. If this option is used tensor-volume must also be specified.")
("no-warp,n", "Do not warp the geometry of the tensors only obtain the new statistics")
("tensor-volume,T", po::value<std::string>(), "Interpolate tensor values from the given field")
// ****** TODO **********
("voxelize,V", po::value<std::string>(),"Voxelize fiber into a label map (the labelmap filename is the argument of -V). The tensor file must be specified using -T for information about the size, origin, spacing of the image.")
("voxelize-count-fibers", "Count number of fibers per-voxel instead of just setting to 1")
("voxel-label,l", po::value<ScalarPixelType>()->default_value(1),"Label for voxelized fiber")
// Compute 1-D statistics
// ("mean-statistics,s", po::value<std::string>(), "Write summary statistics to text file")
// ****** TODO **********
;
po::options_description hidden("Hidden options");
hidden.add_options()
("fiber-file", po::value<std::string>(), "DTI fiber file")
;
po::options_description all;
all.add(config).add(hidden);
po::positional_options_description p;
p.add("fiber-file",1);
po::variables_map vm;
try
{
po::store(po::command_line_parser(argc, argv).
options(all).positional(p).run(), vm);
po::notify(vm);
}
catch (const po::error &e)
{
std::cout << "Parse error: " << std::endl;
std::cout << config << std::endl;
return EXIT_FAILURE;
}
// End option reading configuration
// Display help if asked or program improperly called
if(vm.count("help") || !vm.count("fiber-file"))
{
std::cout << config << std::endl;
if(vm.count("help"))
{
std::cout << "Version $Revision: 1.6 $ "<< std::endl;
std::cout << ITK_SOURCE_VERSION << std::endl;
return EXIT_SUCCESS;
}
else
{
return EXIT_FAILURE;
}
}
const bool VERBOSE = vm.count("verbose");
// Reader fiber bundle
GroupType::Pointer group = readFiberFile(vm["fiber-file"].as<std::string>());
DeformationImageType::Pointer deformationfield(NULL);
if(vm.count("h-field"))
deformationfield = readDeformationField(vm["h-field"].as<std::string>(), HField);
else if(vm.count("displacement-field"))
deformationfield = readDeformationField(vm["displacement-field"].as<std::string>(), Displacement);
else
deformationfield = NULL;
typedef itk::VectorLinearInterpolateImageFunction<DeformationImageType, double> DeformationInterpolateType;
DeformationInterpolateType::Pointer definterp(NULL);
if(deformationfield)
{
definterp = DeformationInterpolateType::New();
definterp->SetInputImage(deformationfield);
}
// Setup new fiber bundle group
GroupType::Pointer newgroup = GroupType::New();
newgroup->SetId(0);
ChildrenListType* children = group->GetChildren(0);
if(VERBOSE)
std::cout << "Getting spacing" << std::endl;
// Get Spacing and offset from group
double spacing[3];
for(unsigned int i =0; i < 3; i++)
spacing[i] = (group->GetSpacing())[i];
newgroup->SetSpacing(spacing);
itk::Vector<double, 3> sooffset;
for(unsigned int i = 0; i < 3; i++)
sooffset[i] = (group->GetObjectToParentTransform()->GetOffset())[i];
newgroup->GetObjectToParentTransform()->SetOffset(sooffset.GetDataPointer());
if(VERBOSE)
{
std::cout << "Group Spacing: " << spacing[0] << ", " << spacing[1] << ", " << spacing[2] << std::endl;
std::cout << "Group Offset: " << sooffset[0] << ", " << sooffset[1] << ", " << sooffset[2] << std::endl;
}
// Setup tensor file if available
typedef itk::ImageFileReader<TensorImageType> TensorImageReader;
typedef itk::TensorLinearInterpolateImageFunction<TensorImageType, double> TensorInterpolateType;
TensorImageReader::Pointer tensorreader = NULL;
TensorInterpolateType::Pointer tensorinterp = NULL;
if(vm.count("tensor-volume"))
{
tensorreader = TensorImageReader::New();
tensorinterp = TensorInterpolateType::New();
tensorreader->SetFileName(vm["tensor-volume"].as<std::string>().c_str());
try
{
tensorreader->Update();
tensorinterp->SetInputImage(tensorreader->GetOutput());
}
catch(itk::ExceptionObject exp)
{
std::cerr << exp << std::endl;
return EXIT_FAILURE;
}
}
if(VERBOSE)
std::cout << "Starting Loop" << std::endl;
ChildrenListType::iterator it;
unsigned int id = 1;
// Need to allocate an image to write into for creating
// the fiber label map
IntImageType::Pointer labelimage;
if(vm.count("voxelize"))
{
if(!vm.count("tensor-volume"))
{
std::cerr << "Must specify tensor file to copy image metadata for fiber voxelize." << std::endl;
return EXIT_FAILURE;
}
tensorreader->GetOutput();
labelimage = IntImageType::New();
labelimage->SetSpacing(tensorreader->GetOutput()->GetSpacing());
labelimage->SetOrigin(tensorreader->GetOutput()->GetOrigin());
labelimage->SetDirection(tensorreader->GetOutput()->GetDirection());
labelimage->SetRegions(tensorreader->GetOutput()->GetLargestPossibleRegion());
labelimage->Allocate();
labelimage->FillBuffer(0);
}
double newspacing[3];
for(unsigned int i =0; i < 3; i++)
newspacing[i] = spacing[i];
if (vm.count("tensor-volume") || vm.count("voxelize"))
{
for(unsigned int i =0; i < 3; i++)
newspacing[i] = 1;
// fiber coordinates are newly in mm
}
// For each fiber
for(it = children->begin(); it != children->end(); it++)
{
// Get Spacing and offset from fiber
const double* fiberspacing = (*it).GetPointer()->GetSpacing();
const itk::Vector<double, 3> fibersooffset = dynamic_cast<DTITubeType*>((*it).GetPointer())->GetObjectToParentTransform()->GetOffset();
// TODO: mode for selecting which to use
if ((fiberspacing[0] != spacing[0]) || (fiberspacing[1] != spacing[1]) || (fiberspacing[1] != spacing[1]) ||
(sooffset[0] != fibersooffset[0]) || (sooffset[1] != fibersooffset[1]) || (sooffset[1] != fibersooffset[1]))
{
std::cout << "Fiber and group spacing/offset is not equal using the one from the fiber group." << std::endl;
if(VERBOSE)
{
std::cout << "Fiber Spacing: " << fiberspacing[0] << ", " << fiberspacing[1] << ", " << fiberspacing[2] << std::endl;
std::cout << "Fiber Offset: " << fibersooffset[0] << ", " << fibersooffset[1] << ", " << fibersooffset[2] << std::endl;
}
for(unsigned int i =0; i < 3; i++)
{
spacing[i] = fiberspacing[i];
sooffset[i] = fibersooffset[i];
}
newgroup->SetSpacing(spacing);
newgroup->GetObjectToParentTransform()->SetOffset(sooffset.GetDataPointer());
}
DTIPointListType pointlist = dynamic_cast<DTITubeType*>((*it).GetPointer())->GetPoints();
DTITubeType::Pointer newtube = DTITubeType::New();
DTIPointListType newpoints;
DTIPointListType::iterator pit;
// For each point alogng thje fiber
for(pit = pointlist.begin(); pit != pointlist.end(); ++pit)
{
DTIPointType newpoint;
typedef DTIPointType::PointType PointType;
// p is not really a point its a continuous index
const PointType p = pit->GetPosition();
itk::Point<double, 3> pt;
// pt is Point in world coordinates (without any reorientation, i.e. disregarding transform matrix)
pt[0] = p[0] * spacing[0] + sooffset[0];
pt[1] = p[1] * spacing[1] + sooffset[1];
pt[2] = p[2] * spacing[2] + sooffset[2];
typedef DeformationInterpolateType::ContinuousIndexType ContinuousIndexType;
ContinuousIndexType ci, origci;
for(unsigned int i =0; i < 3; i++)
origci[i] = ci[i] = p[i];
if (vm.count("tensor-volume"))
{
// get index in image
tensorreader->GetOutput()->TransformPhysicalPointToContinuousIndex(pt, ci);
for(unsigned int i =0; i < 3; i++)
origci[i] = ci[i];
if(deformationfield)
{
// just for debug
//std::cout << "p" << p[0] << "," << p[1] << "," << p[2] << std::endl;
//std::cout << "ci" << ci[0] << "," << ci[1] << "," << ci[2] << std::endl;
DeformationPixelType warp(definterp->EvaluateAtContinuousIndex(ci).GetDataPointer());
// Get Spacing from tensorfile
TensorImageType::SpacingType tensorspacing = tensorreader->GetOutput()->GetSpacing();
for(unsigned int i =0; i < 3; i++)
ci[i] = ci[i] + warp[i] / tensorspacing[i];
}
}
if(vm.count("voxelize"))
{
itk::Index<3> ind;
labelimage->TransformPhysicalPointToContinuousIndex(pt, ci);
ind[0] = static_cast<long int>(round(ci[0]));
ind[1] = static_cast<long int>(round(ci[1]));
ind[2] = static_cast<long int>(round(ci[2]));
if(!labelimage->GetLargestPossibleRegion().IsInside(ind))
{
std::cerr << "Error index: " << ind << " not in image" << std::endl;
return EXIT_FAILURE;
}
if(vm.count("voxelize-count-fibers"))
labelimage->SetPixel(ind, labelimage->GetPixel(ind) + 1);
else
labelimage->SetPixel(ind, vm["voxel-label"].as<ScalarPixelType>());
}
// Should not have to do this
if(vm.count("no-warp"))
newpoint.SetPosition(origci);
else
newpoint.SetPosition(ci);
newpoint.SetRadius(.4);
newpoint.SetRed(0.0);
newpoint.SetGreen(1.0);
newpoint.SetBlue(0.0);
// Attribute tensor data if provided
if(vm.count("tensor-volume") && vm.count("fiber-output"))
{
itk::DiffusionTensor3D<double> tensor(tensorinterp->EvaluateAtContinuousIndex(ci).GetDataPointer());
// TODO: Change SpatialObject interface to accept DiffusionTensor3D
float sotensor[6];
for(unsigned int i = 0; i < 6; ++i)
sotensor[i] = tensor[i];
newpoint.SetTensorMatrix(sotensor);
typedef itk::DiffusionTensor3D<double>::EigenValuesArrayType EigenValuesType;
EigenValuesType eigenvalues;
tensor.ComputeEigenValues(eigenvalues);
newpoint.AddField(itk::DTITubeSpatialObjectPoint<3>::FA, tensor.GetFractionalAnisotropy());
newpoint.AddField("md", tensor.GetTrace()/3);
newpoint.AddField("fro", sqrt(tensor[0]*tensor[0] +
2*tensor[1]*tensor[1] +
2*tensor[2]*tensor[2] +
tensor[3]*tensor[3] +
2*tensor[4]*tensor[4] +
tensor[5]*tensor[5]));
newpoint.AddField("l1", eigenvalues[0]);
newpoint.AddField("l2", eigenvalues[1]);
newpoint.AddField("l3", eigenvalues[2]);
}
else
{
newpoint.SetTensorMatrix(pit->GetTensorMatrix());
}
newpoints.push_back(newpoint);
}
newtube->SetSpacing(newspacing);
newtube->SetId(id++);
newtube->SetPoints(newpoints);
newgroup->AddSpatialObject(newtube);
}
newgroup->ComputeObjectToWorldTransform();
if(VERBOSE)
std::cout << "Ending Loop" << std::endl;
if(VERBOSE && vm.count("fiber-output"))
std::cout << "Output: " << vm["fiber-output"].as<std::string>() << std::endl;
if(vm.count("fiber-output"))
writeFiberFile(vm["fiber-output"].as<std::string>(), newgroup);
if(vm.count("voxelize"))
{
typedef itk::ImageFileWriter<IntImageType> LabelWriter;
LabelWriter::Pointer writer = LabelWriter::New();
writer->SetInput(labelimage);
writer->SetFileName(vm["voxelize"].as<std::string>());
writer->UseCompressionOn();
try
{
writer->Update();
}
catch(itk::ExceptionObject & e)
{
std::cerr << e.what() << std::endl;
return EXIT_FAILURE;
}
}
delete children;
return EXIT_SUCCESS;
}
<commit_msg>BUG: correct fiber coordinates when tensor mapping and deformation application<commit_after> /*=========================================================================
Program: NeuroLib (DTI command line tools)
Language: C++
Date: $Date: 2009-06-09 14:57:41 $
Version: $Revision: 1.7 $
Author: Casey Goodlett ([email protected])
Copyright (c) Casey Goodlett. All rights reserved.
See NeuroLibCopyright.txt or http://www.ia.unc.edu/dev/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
// STL includes
#include <string>
#include <iostream>
#include <fstream>
// boost includes
#include <boost/program_options/option.hpp>
#include <boost/program_options/options_description.hpp>
#include <boost/program_options/positional_options.hpp>
#include <boost/program_options/variables_map.hpp>
#include <boost/program_options/parsers.hpp>
#include <boost/program_options/cmdline.hpp>
// ITK includes
#include <itkDiffusionTensor3D.h>
#include <itkImageFileReader.h>
#include <itkImageFileWriter.h>
#include <itkTensorLinearInterpolateImageFunction.h>
#include <itkVectorLinearInterpolateImageFunction.h>
#include <itkVersion.h>
//#include "FiberCalculator.h"
#include "deformationfieldoperations.h"
#include "fiberio.h"
#include "dtitypes.h"
namespace po = boost::program_options;
int main(int argc, char* argv[])
{
// Read program options/configuration
po::options_description config("Usage: fiberprocess input-fiber [options]");
config.add_options()
("help,h", "produce this help message")
("verbose,v", "produces verbose output")
("fiber-output,o", po::value<std::string>(), "Output fiber file. May be warped or updated with new data depending on other options used.")
("h-field,H", po::value<std::string>(), "HField for warp and statistics lookup. If this option is used tensor-volume must also be specified.")
("displacement-field", po::value<std::string>(), "Displacement field for warp and statistics lookup. If this option is used tensor-volume must also be specified.")
("no-warp,n", "Do not warp the geometry of the tensors only obtain the new statistics")
("tensor-volume,T", po::value<std::string>(), "Interpolate tensor values from the given field")
// ****** TODO **********
("voxelize,V", po::value<std::string>(),"Voxelize fiber into a label map (the labelmap filename is the argument of -V). The tensor file must be specified using -T for information about the size, origin, spacing of the image.")
("voxelize-count-fibers", "Count number of fibers per-voxel instead of just setting to 1")
("voxel-label,l", po::value<ScalarPixelType>()->default_value(1),"Label for voxelized fiber")
("fiberRadius,R",po::value<double>(),"set radius of all fibers to this value")
// Compute 1-D statistics
// ("mean-statistics,s", po::value<std::string>(), "Write summary statistics to text file")
// ****** TODO **********
;
po::options_description hidden("Hidden options");
hidden.add_options()
("fiber-file", po::value<std::string>(), "DTI fiber file")
;
po::options_description all;
all.add(config).add(hidden);
po::positional_options_description p;
p.add("fiber-file",1);
po::variables_map vm;
try
{
po::store(po::command_line_parser(argc, argv).
options(all).positional(p).run(), vm);
po::notify(vm);
}
catch (const po::error &e)
{
std::cout << "Parse error: " << std::endl;
std::cout << config << std::endl;
return EXIT_FAILURE;
}
// End option reading configuration
// Display help if asked or program improperly called
if(vm.count("help") || !vm.count("fiber-file"))
{
std::cout << config << std::endl;
if(vm.count("help"))
{
std::cout << "Version $Revision: 1.7 $ "<< std::endl;
std::cout << ITK_SOURCE_VERSION << std::endl;
return EXIT_SUCCESS;
}
else
{
return EXIT_FAILURE;
}
}
const bool VERBOSE = vm.count("verbose");
// Reader fiber bundle
GroupType::Pointer group = readFiberFile(vm["fiber-file"].as<std::string>());
DeformationImageType::Pointer deformationfield(NULL);
if(vm.count("h-field"))
deformationfield = readDeformationField(vm["h-field"].as<std::string>(), HField);
else if(vm.count("displacement-field"))
deformationfield = readDeformationField(vm["displacement-field"].as<std::string>(), Displacement);
else
deformationfield = NULL;
typedef itk::VectorLinearInterpolateImageFunction<DeformationImageType, double> DeformationInterpolateType;
DeformationInterpolateType::Pointer definterp(NULL);
if(deformationfield)
{
definterp = DeformationInterpolateType::New();
definterp->SetInputImage(deformationfield);
}
// Setup new fiber bundle group
GroupType::Pointer newgroup = GroupType::New();
newgroup->SetId(0);
ChildrenListType* children = group->GetChildren(0);
if(VERBOSE)
std::cout << "Getting spacing" << std::endl;
// Get Spacing and offset from group
double spacing[3];
for(unsigned int i =0; i < 3; i++)
spacing[i] = (group->GetSpacing())[i];
newgroup->SetSpacing(spacing);
itk::Vector<double, 3> sooffset;
for(unsigned int i = 0; i < 3; i++)
sooffset[i] = (group->GetObjectToParentTransform()->GetOffset())[i];
newgroup->GetObjectToParentTransform()->SetOffset(sooffset.GetDataPointer());
if(VERBOSE)
{
std::cout << "Group Spacing: " << spacing[0] << ", " << spacing[1] << ", " << spacing[2] << std::endl;
std::cout << "Group Offset: " << sooffset[0] << ", " << sooffset[1] << ", " << sooffset[2] << std::endl;
}
// Setup tensor file if available
typedef itk::ImageFileReader<TensorImageType> TensorImageReader;
typedef itk::TensorLinearInterpolateImageFunction<TensorImageType, double> TensorInterpolateType;
TensorImageReader::Pointer tensorreader = NULL;
TensorInterpolateType::Pointer tensorinterp = NULL;
if(vm.count("tensor-volume"))
{
tensorreader = TensorImageReader::New();
tensorinterp = TensorInterpolateType::New();
tensorreader->SetFileName(vm["tensor-volume"].as<std::string>().c_str());
try
{
tensorreader->Update();
tensorinterp->SetInputImage(tensorreader->GetOutput());
}
catch(itk::ExceptionObject exp)
{
std::cerr << exp << std::endl;
return EXIT_FAILURE;
}
}
if(VERBOSE)
std::cout << "Starting Loop" << std::endl;
ChildrenListType::iterator it;
unsigned int id = 1;
// Need to allocate an image to write into for creating
// the fiber label map
IntImageType::Pointer labelimage;
if(vm.count("voxelize"))
{
if(!vm.count("tensor-volume"))
{
std::cerr << "Must specify tensor file to copy image metadata for fiber voxelize." << std::endl;
return EXIT_FAILURE;
}
tensorreader->GetOutput();
labelimage = IntImageType::New();
labelimage->SetSpacing(tensorreader->GetOutput()->GetSpacing());
labelimage->SetOrigin(tensorreader->GetOutput()->GetOrigin());
labelimage->SetDirection(tensorreader->GetOutput()->GetDirection());
labelimage->SetRegions(tensorreader->GetOutput()->GetLargestPossibleRegion());
labelimage->Allocate();
labelimage->FillBuffer(0);
}
double newspacing[3];
for(unsigned int i =0; i < 3; i++)
newspacing[i] = spacing[i];
if (vm.count("tensor-volume") || vm.count("voxelize"))
{
for(unsigned int i =0; i < 3; i++)
newspacing[i] = 1;
// fiber coordinates are newly in mm
}
// For each fiber
for(it = children->begin(); it != children->end(); it++)
{
// Get Spacing and offset from fiber
const double* fiberspacing = (*it).GetPointer()->GetSpacing();
const itk::Vector<double, 3> fibersooffset = dynamic_cast<DTITubeType*>((*it).GetPointer())->GetObjectToParentTransform()->GetOffset();
// TODO: mode for selecting which to use
if ((fiberspacing[0] != spacing[0]) || (fiberspacing[1] != spacing[1]) || (fiberspacing[1] != spacing[1]) ||
(sooffset[0] != fibersooffset[0]) || (sooffset[1] != fibersooffset[1]) || (sooffset[1] != fibersooffset[1]))
{
std::cout << "Fiber and group spacing/offset is not equal using the one from the fiber group." << std::endl;
if(VERBOSE)
{
std::cout << "Fiber Spacing: " << fiberspacing[0] << ", " << fiberspacing[1] << ", " << fiberspacing[2] << std::endl;
std::cout << "Fiber Offset: " << fibersooffset[0] << ", " << fibersooffset[1] << ", " << fibersooffset[2] << std::endl;
}
for(unsigned int i =0; i < 3; i++)
{
spacing[i] = fiberspacing[i];
sooffset[i] = fibersooffset[i];
}
newgroup->SetSpacing(spacing);
newgroup->GetObjectToParentTransform()->SetOffset(sooffset.GetDataPointer());
}
DTIPointListType pointlist = dynamic_cast<DTITubeType*>((*it).GetPointer())->GetPoints();
DTITubeType::Pointer newtube = DTITubeType::New();
DTIPointListType newpoints;
DTIPointListType::iterator pit;
// For each point alogng the fiber
for(pit = pointlist.begin(); pit != pointlist.end(); ++pit)
{
DTIPointType newpoint;
typedef DTIPointType::PointType PointType;
// p is not really a point its a continuous index
const PointType p = pit->GetPosition();
itk::Point<double, 3> pt;
// pt is Point in world coordinates (without any reorientation, i.e. disregarding transform matrix)
pt[0] = p[0] * spacing[0] + sooffset[0];
pt[1] = p[1] * spacing[1] + sooffset[1];
pt[2] = p[2] * spacing[2] + sooffset[2];
typedef DeformationInterpolateType::ContinuousIndexType ContinuousIndexType;
ContinuousIndexType ci, origci;
for(unsigned int i =0; i < 3; i++)
origci[i] = ci[i] = p[i];
newpoint.SetPosition(ci);
if (vm.count("tensor-volume"))
{
// get index in image
tensorreader->GetOutput()->TransformPhysicalPointToContinuousIndex(pt, ci);
for(unsigned int i =0; i < 3; i++)
origci[i] = ci[i];
if(deformationfield)
{
DeformationPixelType warp(definterp->EvaluateAtContinuousIndex(ci).GetDataPointer());
// Get Spacing from tensorfile
TensorImageType::SpacingType tensorspacing = tensorreader->GetOutput()->GetSpacing();
for(unsigned int i =0; i < 3; i++)
ci[i] = ci[i] + warp[i] / tensorspacing[i];
if(vm.count("no-warp"))
newpoint.SetPosition(origci);
else
newpoint.SetPosition(ci);
double newFiberSpacing[3];
for(unsigned int i =0; i < 3; i++)
newFiberSpacing[i] = tensorspacing[i];
newgroup->SetSpacing(newFiberSpacing);
}
}
if(vm.count("voxelize"))
{
itk::Index<3> ind;
labelimage->TransformPhysicalPointToContinuousIndex(pt, ci);
ind[0] = static_cast<long int>(round(ci[0]));
ind[1] = static_cast<long int>(round(ci[1]));
ind[2] = static_cast<long int>(round(ci[2]));
if(!labelimage->GetLargestPossibleRegion().IsInside(ind))
{
std::cerr << "Error index: " << ind << " not in image" << std::endl;
return EXIT_FAILURE;
}
if(vm.count("voxelize-count-fibers"))
labelimage->SetPixel(ind, labelimage->GetPixel(ind) + 1);
else
labelimage->SetPixel(ind, vm["voxel-label"].as<ScalarPixelType>());
}
if (vm.count("fiberRadius"))
{
newpoint.SetRadius(vm["fiberRadius"].as<double>());
}
else
{
newpoint.SetRadius(0.4);
}
newpoint.SetRed(0.0);
newpoint.SetGreen(1.0);
newpoint.SetBlue(0.0);
// Attribute tensor data if provided
if(vm.count("tensor-volume") && vm.count("fiber-output"))
{
//std::cout << "ci" << ci[0] << "," << ci[1] << "," << ci[2] << std::endl;
itk::DiffusionTensor3D<double> tensor(tensorinterp->EvaluateAtContinuousIndex(ci).GetDataPointer());
// TODO: Change SpatialObject interface to accept DiffusionTensor3D
float sotensor[6];
for(unsigned int i = 0; i < 6; ++i)
sotensor[i] = tensor[i];
newpoint.SetTensorMatrix(sotensor);
typedef itk::DiffusionTensor3D<double>::EigenValuesArrayType EigenValuesType;
EigenValuesType eigenvalues;
tensor.ComputeEigenValues(eigenvalues);
newpoint.AddField(itk::DTITubeSpatialObjectPoint<3>::FA, tensor.GetFractionalAnisotropy());
newpoint.AddField("md", tensor.GetTrace()/3);
newpoint.AddField("fro", sqrt(tensor[0]*tensor[0] +
2*tensor[1]*tensor[1] +
2*tensor[2]*tensor[2] +
tensor[3]*tensor[3] +
2*tensor[4]*tensor[4] +
tensor[5]*tensor[5]));
newpoint.AddField("l1", eigenvalues[0]);
newpoint.AddField("l2", eigenvalues[1]);
newpoint.AddField("l3", eigenvalues[2]);
}
else
{
newpoint.SetTensorMatrix(pit->GetTensorMatrix());
}
newpoints.push_back(newpoint);
}
newtube->SetSpacing(newspacing);
newtube->SetId(id++);
newtube->SetPoints(newpoints);
newgroup->AddSpatialObject(newtube);
}
newgroup->ComputeObjectToWorldTransform();
if(VERBOSE)
std::cout << "Ending Loop" << std::endl;
if(VERBOSE && vm.count("fiber-output"))
std::cout << "Output: " << vm["fiber-output"].as<std::string>() << std::endl;
if(vm.count("fiber-output"))
writeFiberFile(vm["fiber-output"].as<std::string>(), newgroup);
if(vm.count("voxelize"))
{
typedef itk::ImageFileWriter<IntImageType> LabelWriter;
LabelWriter::Pointer writer = LabelWriter::New();
writer->SetInput(labelimage);
writer->SetFileName(vm["voxelize"].as<std::string>());
writer->UseCompressionOn();
try
{
writer->Update();
}
catch(itk::ExceptionObject & e)
{
std::cerr << e.what() << std::endl;
return EXIT_FAILURE;
}
}
delete children;
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/centaur/procedures/hwp/perv/cen_chiplet_init.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2016,2017 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file cen_chiplet_init.C
/// @brief: identify good chiplets MBA01, MBA23 (tbd)
/// define multicast groups
/// setup chiplet pervasive within the chiplets
///
///
/// @author Peng Fei GOU <[email protected]>
///
//
// *HWP HWP Owner: Peng Fei GOU <[email protected]>
// *HWP FW Owner: Thi Tran <[email protected]>
// *HWP Team: Perv
// *HWP Level: 2
// *HWP Consumed by: HB
//
//------------------------------------------------------------------------------
// Includes
//------------------------------------------------------------------------------
#include <cen_chiplet_init.H>
#include <cen_common_funcs.H>
//------------------------------------------------------------------------------
// Function definitions
//------------------------------------------------------------------------------
fapi2::ReturnCode
cen_chiplet_init(const fapi2::Target<fapi2::TARGET_TYPE_MEMBUF_CHIP>& i_target)
{
FAPI_DBG("Start");
fapi2::buffer<uint64_t> l_tp_mcgr1_data = 0xE0001C0000000000;
fapi2::buffer<uint64_t> l_tp_mcgr2_data = 0xFC001C0000000000;
fapi2::buffer<uint64_t> l_tp_mcgr3_data = 0xFC001C0000000000;
fapi2::buffer<uint64_t> l_tp_mcgr4_data = 0xFC001C0000000000;
fapi2::buffer<uint64_t> l_nest_mcgr1_data = 0xE0001C0000000000;
fapi2::buffer<uint64_t> l_nest_mcgr2_data = 0xFC001C0000000000;
fapi2::buffer<uint64_t> l_nest_mcgr3_data = 0xFC001C0000000000;
fapi2::buffer<uint64_t> l_nest_mcgr4_data = 0xEC001C0000000000;
fapi2::buffer<uint64_t> l_mem_mcgr1_data = 0xE0001C0000000000;
fapi2::buffer<uint64_t> l_mem_mcgr2_data = 0xFC001C0000000000;
fapi2::buffer<uint64_t> l_mem_mcgr3_data = 0xFC001C0000000000;
fapi2::buffer<uint64_t> l_mem_mcgr4_data = 0xEC001C0000000000;
fapi2::buffer<uint64_t> l_write_all_func_gp3_data = 0;
fapi2::buffer<uint64_t> l_write_all_pcb_slave_errreg_data = ~0;
fapi2::buffer<uint64_t> l_mem_gp0_data = 0;
fapi2::buffer<uint64_t> l_ecid_part_1 = 0;
fapi2::buffer<uint64_t> l_nest_clk_scansel_data = 0;
fapi2::buffer<uint64_t> l_nest_clk_scandata0_data = 0;
uint64_t l_nest_clk_scansel_addr = get_scom_addr(SCAN_CHIPLET_NEST, CEN_GENERIC_CLK_SCANSEL);
uint64_t l_nest_clk_scandata0_addr = get_scom_addr(SCAN_CHIPLET_NEST, CEN_GENERIC_CLK_SCANDATA0);
fapi2::ATTR_CENTAUR_EC_FEATURE_SWITCH_REPAIR_COMMAND_VALIDATION_ENTRIES_Type
l_repair_command_validation_entries;
FAPI_DBG("*** Initialize good chiplets "
"and setup multicast registers ***" );
// Set up groups 0 and 3 multicast groups for Centaur
// Multicast Group 0: All functional chiplets (PRV NST MEM)
// Multicast Group 3: All functional chiplets, except PRV
FAPI_DBG("Initializing multicast group0 (all) and "
"group3 (all except PRV)");
FAPI_TRY(fapi2::putScom(i_target, CEN_PCBSLPERV_MULTICAST_GROUP_1_PCB, l_tp_mcgr1_data));
FAPI_TRY(fapi2::putScom(i_target, CEN_PCBSLNEST_MULTICAST_GROUP_1_PCB, l_nest_mcgr1_data));
FAPI_TRY(fapi2::putScom(i_target, CEN_PCBSLMEM_MULTICAST_GROUP_1_PCB, l_mem_mcgr1_data));
FAPI_TRY(fapi2::putScom(i_target, CEN_PCBSLNEST_MULTICAST_GROUP_4_PCB, l_nest_mcgr4_data));
FAPI_TRY(fapi2::putScom(i_target, CEN_PCBSLMEM_MULTICAST_GROUP_4_PCB, l_mem_mcgr4_data));
FAPI_DBG("Set unused group registers to broadcast, Group 7");
FAPI_TRY(fapi2::putScom(i_target, CEN_PCBSLPERV_MULTICAST_GROUP_2_PCB, l_tp_mcgr2_data));
FAPI_TRY(fapi2::putScom(i_target, CEN_PCBSLPERV_MULTICAST_GROUP_3_PCB, l_tp_mcgr3_data));
FAPI_TRY(fapi2::putScom(i_target, CEN_PCBSLPERV_MULTICAST_GROUP_4_PCB, l_tp_mcgr4_data));
FAPI_TRY(fapi2::putScom(i_target, CEN_PCBSLNEST_MULTICAST_GROUP_2_PCB, l_nest_mcgr2_data));
FAPI_TRY(fapi2::putScom(i_target, CEN_PCBSLNEST_MULTICAST_GROUP_3_PCB, l_nest_mcgr3_data));
FAPI_TRY(fapi2::putScom(i_target, CEN_PCBSLMEM_MULTICAST_GROUP_2_PCB, l_mem_mcgr2_data));
FAPI_TRY(fapi2::putScom(i_target, CEN_PCBSLMEM_MULTICAST_GROUP_3_PCB, l_mem_mcgr3_data));
FAPI_DBG( "Done initializing centaur multicast group0, group3" );
// Chiplet Init (all other pervasive endpoints within the different chiplets)
FAPI_DBG( "Start pervasive initialization of other chiplets" );
FAPI_DBG( "Reset GP3 for all chiplets" );
l_write_all_func_gp3_data.setBit<1>().setBit<11>().setBit<13, 2>().setBit<18>();
FAPI_TRY(fapi2::putScom(i_target, CEN_WRITE_ALL_FUNC_GP3, l_write_all_func_gp3_data));
FAPI_DBG( "Release endpoint reset for PCB" );
l_write_all_func_gp3_data = 0;
l_write_all_func_gp3_data.setBit<1>().invert();
FAPI_TRY(fapi2::putScom(i_target, CEN_WRITE_ALL_FUNC_GP3_AND, l_write_all_func_gp3_data));
FAPI_DBG( "Partial good setting GP3(00)='1'" );
l_write_all_func_gp3_data = 0;
l_write_all_func_gp3_data.setBit<0>();
FAPI_TRY(fapi2::putScom(i_target, CEN_WRITE_ALL_FUNC_GP3_OR, l_write_all_func_gp3_data));
FAPI_DBG( "DEBUG: clear force_to_known_2 (fencing for partial good) " );
FAPI_TRY(fapi2::getScom(i_target, CEN_TCM_GP0_PCB, l_mem_gp0_data));
l_mem_gp0_data.clearBit<16>();
FAPI_TRY(fapi2::putScom(i_target, CEN_TCM_GP0_PCB, l_mem_gp0_data));
FAPI_DBG( "PCB slave error reg reset" );
FAPI_TRY(fapi2::putScom(i_target, CEN_WRITE_ALL_PCB_SLAVE_ERRREG, l_write_all_pcb_slave_errreg_data));
// call cen_scan0_module( SCAN_CHIPLET_ALL, GPTR_TIME_REP )
FAPI_TRY(cen_scan0_module(i_target, SCAN_CHIPLET_GROUP3, SCAN_ALLREGIONEXVITAL, SCAN_GPTR_TIME_REP));
// call cen_scan0_module( SCAN_CHIPLET_ALL, ALLSCANEXPRV )
FAPI_TRY(cen_scan0_module(i_target, SCAN_CHIPLET_GROUP3, SCAN_ALLREGIONEXVITAL, SCAN_ALLSCANEXPRV));
// Repair Loader (exclude TP)
FAPI_DBG("Invoking repair loader...");
// DD1 is not allowed for repair command validation entries.
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CENTAUR_EC_FEATURE_SWITCH_REPAIR_COMMAND_VALIDATION_ENTRIES,
i_target, l_repair_command_validation_entries));
FAPI_ASSERT(l_repair_command_validation_entries,
fapi2::CEN_CHIPLET_INIT_REPAIR_NOT_ALLOWED_IN_DD1().set_TARGET(i_target),
"DD1 is not supported by repair command!");
FAPI_TRY(cen_repair_loader(i_target, REPAIR_COMMAND_VALIDATION_ENTRIES_DD2, REPAIR_COMMAND_START_ADDRESS));
// skip load if no repairs are present
FAPI_TRY(fapi2::getScom(i_target, CEN_OTPROM0_ECID_PART1_REGISTER_RO, l_ecid_part_1));
if (l_ecid_part_1.getBit<0>())
{
FAPI_DBG("SCANNING tcn_refr_time");
// inject header and rotate ring to position where repair loader will write data from OTPROM
// scan 0..210
l_nest_clk_scansel_data.setBit<10>().setBit<27>();
FAPI_TRY(fapi2::putScom(i_target, l_nest_clk_scansel_addr, l_nest_clk_scansel_data));
l_nest_clk_scandata0_data = 0xA5A55A5A00000000;
FAPI_TRY(fapi2::putScom(i_target, l_nest_clk_scandata0_addr, l_nest_clk_scandata0_data));
FAPI_TRY(fapi2::getScom(i_target, l_nest_clk_scandata0_addr + 0x6E, l_nest_clk_scandata0_data));
FAPI_TRY(fapi2::getScom(i_target, l_nest_clk_scandata0_addr + 0x65, l_nest_clk_scandata0_data));
// data 211..3006
FAPI_TRY(cen_repair_loader(i_target, REPAIR_COMMAND_VALIDATION_ENTRY_TCN_REFR_TIME_DD2, REPAIR_COMMAND_START_ADDRESS));
// scan 3007..3208
FAPI_TRY(fapi2::putScom(i_target, l_nest_clk_scansel_addr, l_nest_clk_scansel_data));
FAPI_TRY(fapi2::getScom(i_target, l_nest_clk_scandata0_addr + 0x6E, l_nest_clk_scandata0_data));
FAPI_TRY(fapi2::getScom(i_target, l_nest_clk_scandata0_addr + 0x5C, l_nest_clk_scandata0_data));
// data 3209..6004
FAPI_TRY(cen_repair_loader(i_target, REPAIR_COMMAND_VALIDATION_ENTRY_TCN_REFR_TIME_DD2, REPAIR_COMMAND_START_ADDRESS));
// scan 6005..6151
// check header
FAPI_TRY(fapi2::putScom(i_target, l_nest_clk_scansel_addr, l_nest_clk_scansel_data));
FAPI_TRY(fapi2::getScom(i_target, l_nest_clk_scandata0_addr + 0x6E, l_nest_clk_scandata0_data));
FAPI_TRY(fapi2::getScom(i_target, l_nest_clk_scandata0_addr + 0x25, l_nest_clk_scandata0_data));
FAPI_ASSERT((l_nest_clk_scandata0_data == 0xA5A55A5A00000000),
fapi2::CEN_CHIPLET_INIT_HEADER_MISMATCH().set_TARGET(i_target),
"Error rotating tcn_refr_time ring -- header mismatch!"
);
}
fapi_try_exit:
FAPI_DBG("End");
return fapi2::current_err;
}
<commit_msg>Centaur istep 11 support<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/centaur/procedures/hwp/perv/cen_chiplet_init.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2016,2017 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file cen_chiplet_init.C
/// @brief: identify good chiplets MBA01, MBA23 (tbd)
/// define multicast groups
/// setup chiplet pervasive within the chiplets
///
///
/// @author Peng Fei GOU <[email protected]>
///
//
// *HWP HWP Owner: Peng Fei GOU <[email protected]>
// *HWP FW Owner: Thi Tran <[email protected]>
// *HWP Team: Perv
// *HWP Level: 2
// *HWP Consumed by: HB
//
//------------------------------------------------------------------------------
// Includes
//------------------------------------------------------------------------------
#include <cen_chiplet_init.H>
#include <cen_common_funcs.H>
//------------------------------------------------------------------------------
// Function definitions
//------------------------------------------------------------------------------
fapi2::ReturnCode
cen_chiplet_init(const fapi2::Target<fapi2::TARGET_TYPE_MEMBUF_CHIP>& i_target)
{
FAPI_DBG("Start");
fapi2::buffer<uint64_t> l_tp_mcgr1_data = 0xE0001C0000000000;
fapi2::buffer<uint64_t> l_tp_mcgr2_data = 0xFC001C0000000000;
fapi2::buffer<uint64_t> l_tp_mcgr3_data = 0xFC001C0000000000;
fapi2::buffer<uint64_t> l_tp_mcgr4_data = 0xFC001C0000000000;
fapi2::buffer<uint64_t> l_nest_mcgr1_data = 0xE0001C0000000000;
fapi2::buffer<uint64_t> l_nest_mcgr2_data = 0xFC001C0000000000;
fapi2::buffer<uint64_t> l_nest_mcgr3_data = 0xFC001C0000000000;
fapi2::buffer<uint64_t> l_nest_mcgr4_data = 0xEC001C0000000000;
fapi2::buffer<uint64_t> l_mem_mcgr1_data = 0xE0001C0000000000;
fapi2::buffer<uint64_t> l_mem_mcgr2_data = 0xFC001C0000000000;
fapi2::buffer<uint64_t> l_mem_mcgr3_data = 0xFC001C0000000000;
fapi2::buffer<uint64_t> l_mem_mcgr4_data = 0xEC001C0000000000;
fapi2::buffer<uint64_t> l_write_all_func_gp3_data = 0;
fapi2::buffer<uint64_t> l_write_all_pcb_slave_errreg_data = ~0;
fapi2::buffer<uint64_t> l_mem_gp0_data = 0;
fapi2::buffer<uint64_t> l_ecid_part_1 = 0;
fapi2::buffer<uint64_t> l_nest_clk_scansel_data = 0;
fapi2::buffer<uint64_t> l_nest_clk_scandata0_data = 0;
uint64_t l_nest_clk_scansel_addr = get_scom_addr(SCAN_CHIPLET_NEST, CEN_GENERIC_CLK_SCANSEL);
uint64_t l_nest_clk_scandata0_addr = get_scom_addr(SCAN_CHIPLET_NEST, CEN_GENERIC_CLK_SCANDATA0);
FAPI_DBG("*** Initialize good chiplets "
"and setup multicast registers ***" );
// Set up groups 0 and 3 multicast groups for Centaur
// Multicast Group 0: All functional chiplets (PRV NST MEM)
// Multicast Group 3: All functional chiplets, except PRV
FAPI_DBG("Initializing multicast group0 (all) and "
"group3 (all except PRV)");
FAPI_TRY(fapi2::putScom(i_target, CEN_PCBSLPERV_MULTICAST_GROUP_1_PCB, l_tp_mcgr1_data));
FAPI_TRY(fapi2::putScom(i_target, CEN_PCBSLNEST_MULTICAST_GROUP_1_PCB, l_nest_mcgr1_data));
FAPI_TRY(fapi2::putScom(i_target, CEN_PCBSLMEM_MULTICAST_GROUP_1_PCB, l_mem_mcgr1_data));
FAPI_TRY(fapi2::putScom(i_target, CEN_PCBSLNEST_MULTICAST_GROUP_4_PCB, l_nest_mcgr4_data));
FAPI_TRY(fapi2::putScom(i_target, CEN_PCBSLMEM_MULTICAST_GROUP_4_PCB, l_mem_mcgr4_data));
FAPI_DBG("Set unused group registers to broadcast, Group 7");
FAPI_TRY(fapi2::putScom(i_target, CEN_PCBSLPERV_MULTICAST_GROUP_2_PCB, l_tp_mcgr2_data));
FAPI_TRY(fapi2::putScom(i_target, CEN_PCBSLPERV_MULTICAST_GROUP_3_PCB, l_tp_mcgr3_data));
FAPI_TRY(fapi2::putScom(i_target, CEN_PCBSLPERV_MULTICAST_GROUP_4_PCB, l_tp_mcgr4_data));
FAPI_TRY(fapi2::putScom(i_target, CEN_PCBSLNEST_MULTICAST_GROUP_2_PCB, l_nest_mcgr2_data));
FAPI_TRY(fapi2::putScom(i_target, CEN_PCBSLNEST_MULTICAST_GROUP_3_PCB, l_nest_mcgr3_data));
FAPI_TRY(fapi2::putScom(i_target, CEN_PCBSLMEM_MULTICAST_GROUP_2_PCB, l_mem_mcgr2_data));
FAPI_TRY(fapi2::putScom(i_target, CEN_PCBSLMEM_MULTICAST_GROUP_3_PCB, l_mem_mcgr3_data));
FAPI_DBG( "Done initializing centaur multicast group0, group3" );
// Chiplet Init (all other pervasive endpoints within the different chiplets)
FAPI_DBG( "Start pervasive initialization of other chiplets" );
FAPI_DBG( "Reset GP3 for all chiplets" );
l_write_all_func_gp3_data.setBit<1>().setBit<11>().setBit<13, 2>().setBit<18>();
FAPI_TRY(fapi2::putScom(i_target, CEN_WRITE_ALL_FUNC_GP3, l_write_all_func_gp3_data));
FAPI_DBG( "Release endpoint reset for PCB" );
l_write_all_func_gp3_data = 0;
l_write_all_func_gp3_data.setBit<1>().invert();
FAPI_TRY(fapi2::putScom(i_target, CEN_WRITE_ALL_FUNC_GP3_AND, l_write_all_func_gp3_data));
FAPI_DBG( "Partial good setting GP3(00)='1'" );
l_write_all_func_gp3_data = 0;
l_write_all_func_gp3_data.setBit<0>();
FAPI_TRY(fapi2::putScom(i_target, CEN_WRITE_ALL_FUNC_GP3_OR, l_write_all_func_gp3_data));
FAPI_DBG( "DEBUG: clear force_to_known_2 (fencing for partial good) " );
FAPI_TRY(fapi2::getScom(i_target, CEN_TCM_GP0_PCB, l_mem_gp0_data));
l_mem_gp0_data.clearBit<16>();
FAPI_TRY(fapi2::putScom(i_target, CEN_TCM_GP0_PCB, l_mem_gp0_data));
FAPI_DBG( "PCB slave error reg reset" );
FAPI_TRY(fapi2::putScom(i_target, CEN_WRITE_ALL_PCB_SLAVE_ERRREG, l_write_all_pcb_slave_errreg_data));
// call cen_scan0_module( SCAN_CHIPLET_ALL, GPTR_TIME_REP )
FAPI_TRY(cen_scan0_module(i_target, SCAN_CHIPLET_GROUP3, SCAN_ALLREGIONEXVITAL, SCAN_GPTR_TIME_REP));
// call cen_scan0_module( SCAN_CHIPLET_ALL, ALLSCANEXPRV )
FAPI_TRY(cen_scan0_module(i_target, SCAN_CHIPLET_GROUP3, SCAN_ALLREGIONEXVITAL, SCAN_ALLSCANEXPRV));
// Repair Loader (exclude TP)
FAPI_DBG("Invoking repair loader...");
FAPI_TRY(cen_repair_loader(i_target, REPAIR_COMMAND_VALIDATION_ENTRIES_DD2, REPAIR_COMMAND_START_ADDRESS));
// skip load if no repairs are present
FAPI_TRY(fapi2::getScom(i_target, CEN_OTPROM0_ECID_PART1_REGISTER_RO, l_ecid_part_1));
if (l_ecid_part_1.getBit<0>())
{
FAPI_DBG("SCANNING tcn_refr_time");
// inject header and rotate ring to position where repair loader will write data from OTPROM
// scan 0..210
l_nest_clk_scansel_data.setBit<10>().setBit<27>();
FAPI_TRY(fapi2::putScom(i_target, l_nest_clk_scansel_addr, l_nest_clk_scansel_data));
l_nest_clk_scandata0_data = 0xA5A55A5A00000000;
FAPI_TRY(fapi2::putScom(i_target, l_nest_clk_scandata0_addr, l_nest_clk_scandata0_data));
FAPI_TRY(fapi2::getScom(i_target, l_nest_clk_scandata0_addr + 0x6E, l_nest_clk_scandata0_data));
FAPI_TRY(fapi2::getScom(i_target, l_nest_clk_scandata0_addr + 0x65, l_nest_clk_scandata0_data));
// data 211..3006
FAPI_TRY(cen_repair_loader(i_target, REPAIR_COMMAND_VALIDATION_ENTRY_TCN_REFR_TIME_DD2, REPAIR_COMMAND_START_ADDRESS));
// scan 3007..3208
FAPI_TRY(fapi2::putScom(i_target, l_nest_clk_scansel_addr, l_nest_clk_scansel_data));
FAPI_TRY(fapi2::getScom(i_target, l_nest_clk_scandata0_addr + 0x6E, l_nest_clk_scandata0_data));
FAPI_TRY(fapi2::getScom(i_target, l_nest_clk_scandata0_addr + 0x5C, l_nest_clk_scandata0_data));
// data 3209..6004
FAPI_TRY(cen_repair_loader(i_target, REPAIR_COMMAND_VALIDATION_ENTRY_TCN_REFR_TIME_DD2, REPAIR_COMMAND_START_ADDRESS));
// scan 6005..6151
// check header
FAPI_TRY(fapi2::putScom(i_target, l_nest_clk_scansel_addr, l_nest_clk_scansel_data));
FAPI_TRY(fapi2::getScom(i_target, l_nest_clk_scandata0_addr + 0x6E, l_nest_clk_scandata0_data));
FAPI_TRY(fapi2::getScom(i_target, l_nest_clk_scandata0_addr + 0x25, l_nest_clk_scandata0_data));
FAPI_ASSERT((l_nest_clk_scandata0_data == 0xA5A55A5A00000000),
fapi2::CEN_CHIPLET_INIT_HEADER_MISMATCH().set_TARGET(i_target),
"Error rotating tcn_refr_time ring -- header mismatch!"
);
}
fapi_try_exit:
FAPI_DBG("End");
return fapi2::current_err;
}
<|endoftext|> |
<commit_before>#include "calibration_impl.h"
#include "system.h"
#include "global_include.h"
#include "px4_custom_mode.h"
#include <functional>
#include <string>
#include <sstream>
namespace dronecode_sdk {
using namespace std::placeholders;
CalibrationImpl::CalibrationImpl(System &system) : PluginImplBase(system)
{
_parent->register_plugin(this);
}
CalibrationImpl::~CalibrationImpl()
{
_parent->unregister_plugin(this);
}
void CalibrationImpl::init()
{
_parent->register_mavlink_message_handler(
MAVLINK_MSG_ID_STATUSTEXT, std::bind(&CalibrationImpl::process_statustext, this, _1), this);
}
void CalibrationImpl::deinit()
{
_parent->unregister_all_mavlink_message_handlers(this);
}
void CalibrationImpl::enable()
{
// The calibration check should eventually be better than this.
// For now, we just do the same as QGC does.
_parent->get_param_int_async(std::string("CAL_GYRO0_ID"),
std::bind(&CalibrationImpl::receive_param_cal_gyro, this, _1, _2));
_parent->get_param_int_async(
std::string("CAL_ACC0_ID"),
std::bind(&CalibrationImpl::receive_param_cal_accel, this, _1, _2));
_parent->get_param_int_async(std::string("CAL_MAG0_ID"),
std::bind(&CalibrationImpl::receive_param_cal_mag, this, _1, _2));
}
void CalibrationImpl::disable() {}
void CalibrationImpl::calibrate_gyro_async(const Calibration::calibration_callback_t &callback)
{
std::lock_guard<std::mutex> lock(_calibration_mutex);
if (_parent->is_armed()) {
report_failed("System is armed.");
return;
}
if (_state != State::NONE) {
if (callback) {
_parent->call_user_callback(
[callback]() { callback(Calibration::Result::BUSY, NAN, ""); });
}
return;
}
_state = State::GYRO_CALIBRATION;
_calibration_callback = callback;
MAVLinkCommands::CommandLong command{};
command.command = MAV_CMD_PREFLIGHT_CALIBRATION;
MAVLinkCommands::CommandLong::set_as_reserved(command.params, 0.0f);
command.params.param1 = 1.0f; // Gyro
command.target_component_id = MAV_COMP_ID_AUTOPILOT1;
_parent->send_command_async(command,
std::bind(&CalibrationImpl::command_result_callback, this, _1, _2));
}
void CalibrationImpl::calibrate_accelerometer_async(
const Calibration::calibration_callback_t &callback)
{
std::lock_guard<std::mutex> lock(_calibration_mutex);
if (_parent->is_armed()) {
report_failed("System is armed.");
return;
}
if (_state != State::NONE) {
if (callback) {
_parent->call_user_callback(
[callback]() { callback(Calibration::Result::BUSY, NAN, ""); });
}
return;
}
_state = State::ACCELEROMETER_CALIBRATION;
_calibration_callback = callback;
MAVLinkCommands::CommandLong command{};
command.command = MAV_CMD_PREFLIGHT_CALIBRATION;
MAVLinkCommands::CommandLong::set_as_reserved(command.params, 0.0f);
command.params.param5 = 1.0f; // Accel
command.target_component_id = MAV_COMP_ID_AUTOPILOT1;
_parent->send_command_async(command,
std::bind(&CalibrationImpl::command_result_callback, this, _1, _2));
}
void CalibrationImpl::calibrate_magnetometer_async(
const Calibration::calibration_callback_t &callback)
{
std::lock_guard<std::mutex> lock(_calibration_mutex);
if (_parent->is_armed()) {
report_failed("System is armed.");
return;
}
if (_state != State::NONE) {
if (callback) {
_parent->call_user_callback(
[callback]() { callback(Calibration::Result::BUSY, NAN, ""); });
}
return;
}
_state = State::MAGNETOMETER_CALIBRATION;
_calibration_callback = callback;
MAVLinkCommands::CommandLong command{};
command.command = MAV_CMD_PREFLIGHT_CALIBRATION;
MAVLinkCommands::CommandLong::set_as_reserved(command.params, 0.0f);
command.params.param2 = 1.0f; // Mag
command.target_component_id = MAV_COMP_ID_AUTOPILOT1;
_parent->send_command_async(command,
std::bind(&CalibrationImpl::command_result_callback, this, _1, _2));
}
bool CalibrationImpl::is_gyro_calibration_ok() const
{
std::lock_guard<std::mutex> lock(_calibration_mutex);
return _is_gyro_ok;
}
bool CalibrationImpl::is_accelerometer_calibration_ok() const
{
std::lock_guard<std::mutex> lock(_calibration_mutex);
return _is_accelerometer_ok;
}
bool CalibrationImpl::is_magnetometer_calibration_ok() const
{
std::lock_guard<std::mutex> lock(_calibration_mutex);
return _is_magnetometer_ok;
}
void CalibrationImpl::command_result_callback(MAVLinkCommands::Result command_result,
float progress)
{
std::lock_guard<std::mutex> lock(_calibration_mutex);
if (_state == State::NONE) {
// It might be someone else like a ground station trying to do a
// calibration. We silently ignore it.
return;
}
// If we get a progress result here, it is the new interface and we can
// use the progress info. If we get an ack, we need to translate that to
// a first progress update, and then parse the statustexts for progress.
switch (command_result) {
case MAVLinkCommands::Result::SUCCESS:
// Silently ignore.
break;
case MAVLinkCommands::Result::NO_SYSTEM:
// FALLTHROUGH
case MAVLinkCommands::Result::CONNECTION_ERROR:
// FALLTHROUGH
case MAVLinkCommands::Result::BUSY:
// FALLTHROUGH
case MAVLinkCommands::Result::COMMAND_DENIED:
// FALLTHROUGH
case MAVLinkCommands::Result::UNKNOWN_ERROR:
// FALLTHROUGH
case MAVLinkCommands::Result::TIMEOUT:
// Report all error cases.
if (_calibration_callback) {
auto calibration_callback_tmp = _calibration_callback;
_parent->call_user_callback([calibration_callback_tmp, command_result]() {
calibration_callback_tmp(
calibration_result_from_command_result(command_result), NAN, "");
});
}
_calibration_callback = nullptr;
_state = State::NONE;
break;
case MAVLinkCommands::Result::IN_PROGRESS:
if (_calibration_callback) {
auto calibration_callback_tmp = _calibration_callback;
_parent->call_user_callback([calibration_callback_tmp, command_result, progress]() {
calibration_callback_tmp(
calibration_result_from_command_result(command_result), progress, "");
});
}
break;
};
}
Calibration::Result
CalibrationImpl::calibration_result_from_command_result(MAVLinkCommands::Result result)
{
switch (result) {
case MAVLinkCommands::Result::SUCCESS:
return Calibration::Result::SUCCESS;
case MAVLinkCommands::Result::NO_SYSTEM:
return Calibration::Result::NO_SYSTEM;
case MAVLinkCommands::Result::CONNECTION_ERROR:
return Calibration::Result::CONNECTION_ERROR;
case MAVLinkCommands::Result::BUSY:
return Calibration::Result::BUSY;
case MAVLinkCommands::Result::COMMAND_DENIED:
return Calibration::Result::COMMAND_DENIED;
case MAVLinkCommands::Result::TIMEOUT:
return Calibration::Result::TIMEOUT;
case MAVLinkCommands::Result::IN_PROGRESS:
return Calibration::Result::IN_PROGRESS;
default:
return Calibration::Result::UNKNOWN;
}
}
void CalibrationImpl::receive_param_cal_gyro(bool success, int value)
{
if (!success) {
LogErr() << "Error: Param for gyro cal failed.";
return;
}
bool ok = (value != 0);
set_gyro_calibration(ok);
}
void CalibrationImpl::receive_param_cal_accel(bool success, int value)
{
if (!success) {
LogErr() << "Error: Param for accel cal failed.";
return;
}
bool ok = (value != 0);
set_accelerometer_calibration(ok);
}
void CalibrationImpl::receive_param_cal_mag(bool success, int value)
{
if (!success) {
LogErr() << "Error: Param for mag cal failed.";
return;
}
bool ok = (value != 0);
set_magnetometer_calibration(ok);
}
void CalibrationImpl::set_gyro_calibration(bool ok)
{
std::lock_guard<std::mutex> lock(_calibration_mutex);
_is_gyro_ok = ok;
}
void CalibrationImpl::set_accelerometer_calibration(bool ok)
{
std::lock_guard<std::mutex> lock(_calibration_mutex);
_is_accelerometer_ok = ok;
}
void CalibrationImpl::set_magnetometer_calibration(bool ok)
{
std::lock_guard<std::mutex> lock(_calibration_mutex);
_is_magnetometer_ok = ok;
}
void CalibrationImpl::process_statustext(const mavlink_message_t &message)
{
std::lock_guard<std::mutex> lock(_calibration_mutex);
if (_state == State::NONE) {
return;
}
mavlink_statustext_t statustext;
mavlink_msg_statustext_decode(&message, &statustext);
_parser.reset();
_parser.parse(statustext.text);
switch (_parser.get_status()) {
case CalibrationStatustextParser::Status::NONE:
// Ignore it.
break;
case CalibrationStatustextParser::Status::STARTED:
report_started();
break;
case CalibrationStatustextParser::Status::DONE:
report_done();
break;
case CalibrationStatustextParser::Status::FAILED:
report_failed(_parser.get_failed_message());
break;
case CalibrationStatustextParser::Status::CANCELLED:
report_cancelled();
break;
case CalibrationStatustextParser::Status::PROGRESS:
report_progress(_parser.get_progress());
break;
case CalibrationStatustextParser::Status::INSTRUCTION:
report_instruction(_parser.get_instruction());
break;
}
switch (_parser.get_status()) {
case CalibrationStatustextParser::Status::DONE:
// FALLTHROUGH
case CalibrationStatustextParser::Status::FAILED:
// FALLTHROUGH
case CalibrationStatustextParser::Status::CANCELLED:
_calibration_callback = nullptr;
_state == State::NONE;
break;
default:
break;
}
}
void CalibrationImpl::report_started()
{
report_progress(0.0f);
}
void CalibrationImpl::report_done()
{
if (_calibration_callback) {
auto calibration_callback_tmp = _calibration_callback;
_parent->call_user_callback([calibration_callback_tmp]() {
calibration_callback_tmp(Calibration::Result::SUCCESS, NAN, "");
});
}
}
void CalibrationImpl::report_failed(const std::string &failed)
{
LogErr() << "Calibration failed: " << failed;
if (_calibration_callback) {
auto calibration_callback_tmp = _calibration_callback;
_parent->call_user_callback([calibration_callback_tmp]() {
calibration_callback_tmp(Calibration::Result::FAILED, NAN, "");
});
}
}
void CalibrationImpl::report_cancelled()
{
LogWarn() << "Calibration was cancelled";
if (_calibration_callback) {
auto calibration_callback_tmp = _calibration_callback;
_parent->call_user_callback([calibration_callback_tmp]() {
calibration_callback_tmp(Calibration::Result::CANCELLED, NAN, "");
});
}
}
void CalibrationImpl::report_progress(float progress)
{
if (_calibration_callback) {
auto calibration_callback_tmp = _calibration_callback;
_parent->call_user_callback([calibration_callback_tmp, progress]() {
calibration_callback_tmp(Calibration::Result::IN_PROGRESS, progress, "");
});
}
}
void CalibrationImpl::report_instruction(const std::string &instruction)
{
if (_calibration_callback) {
auto calibration_callback_tmp = _calibration_callback;
_parent->call_user_callback([calibration_callback_tmp, instruction]() {
calibration_callback_tmp(Calibration::Result::INSTRUCTION, NAN, instruction);
});
}
}
} // namespace dronecode_sdk
<commit_msg>calibration: fix warning statement had no effect<commit_after>#include "calibration_impl.h"
#include "system.h"
#include "global_include.h"
#include "px4_custom_mode.h"
#include <functional>
#include <string>
#include <sstream>
namespace dronecode_sdk {
using namespace std::placeholders;
CalibrationImpl::CalibrationImpl(System &system) : PluginImplBase(system)
{
_parent->register_plugin(this);
}
CalibrationImpl::~CalibrationImpl()
{
_parent->unregister_plugin(this);
}
void CalibrationImpl::init()
{
_parent->register_mavlink_message_handler(
MAVLINK_MSG_ID_STATUSTEXT, std::bind(&CalibrationImpl::process_statustext, this, _1), this);
}
void CalibrationImpl::deinit()
{
_parent->unregister_all_mavlink_message_handlers(this);
}
void CalibrationImpl::enable()
{
// The calibration check should eventually be better than this.
// For now, we just do the same as QGC does.
_parent->get_param_int_async(std::string("CAL_GYRO0_ID"),
std::bind(&CalibrationImpl::receive_param_cal_gyro, this, _1, _2));
_parent->get_param_int_async(
std::string("CAL_ACC0_ID"),
std::bind(&CalibrationImpl::receive_param_cal_accel, this, _1, _2));
_parent->get_param_int_async(std::string("CAL_MAG0_ID"),
std::bind(&CalibrationImpl::receive_param_cal_mag, this, _1, _2));
}
void CalibrationImpl::disable() {}
void CalibrationImpl::calibrate_gyro_async(const Calibration::calibration_callback_t &callback)
{
std::lock_guard<std::mutex> lock(_calibration_mutex);
if (_parent->is_armed()) {
report_failed("System is armed.");
return;
}
if (_state != State::NONE) {
if (callback) {
_parent->call_user_callback(
[callback]() { callback(Calibration::Result::BUSY, NAN, ""); });
}
return;
}
_state = State::GYRO_CALIBRATION;
_calibration_callback = callback;
MAVLinkCommands::CommandLong command{};
command.command = MAV_CMD_PREFLIGHT_CALIBRATION;
MAVLinkCommands::CommandLong::set_as_reserved(command.params, 0.0f);
command.params.param1 = 1.0f; // Gyro
command.target_component_id = MAV_COMP_ID_AUTOPILOT1;
_parent->send_command_async(command,
std::bind(&CalibrationImpl::command_result_callback, this, _1, _2));
}
void CalibrationImpl::calibrate_accelerometer_async(
const Calibration::calibration_callback_t &callback)
{
std::lock_guard<std::mutex> lock(_calibration_mutex);
if (_parent->is_armed()) {
report_failed("System is armed.");
return;
}
if (_state != State::NONE) {
if (callback) {
_parent->call_user_callback(
[callback]() { callback(Calibration::Result::BUSY, NAN, ""); });
}
return;
}
_state = State::ACCELEROMETER_CALIBRATION;
_calibration_callback = callback;
MAVLinkCommands::CommandLong command{};
command.command = MAV_CMD_PREFLIGHT_CALIBRATION;
MAVLinkCommands::CommandLong::set_as_reserved(command.params, 0.0f);
command.params.param5 = 1.0f; // Accel
command.target_component_id = MAV_COMP_ID_AUTOPILOT1;
_parent->send_command_async(command,
std::bind(&CalibrationImpl::command_result_callback, this, _1, _2));
}
void CalibrationImpl::calibrate_magnetometer_async(
const Calibration::calibration_callback_t &callback)
{
std::lock_guard<std::mutex> lock(_calibration_mutex);
if (_parent->is_armed()) {
report_failed("System is armed.");
return;
}
if (_state != State::NONE) {
if (callback) {
_parent->call_user_callback(
[callback]() { callback(Calibration::Result::BUSY, NAN, ""); });
}
return;
}
_state = State::MAGNETOMETER_CALIBRATION;
_calibration_callback = callback;
MAVLinkCommands::CommandLong command{};
command.command = MAV_CMD_PREFLIGHT_CALIBRATION;
MAVLinkCommands::CommandLong::set_as_reserved(command.params, 0.0f);
command.params.param2 = 1.0f; // Mag
command.target_component_id = MAV_COMP_ID_AUTOPILOT1;
_parent->send_command_async(command,
std::bind(&CalibrationImpl::command_result_callback, this, _1, _2));
}
bool CalibrationImpl::is_gyro_calibration_ok() const
{
std::lock_guard<std::mutex> lock(_calibration_mutex);
return _is_gyro_ok;
}
bool CalibrationImpl::is_accelerometer_calibration_ok() const
{
std::lock_guard<std::mutex> lock(_calibration_mutex);
return _is_accelerometer_ok;
}
bool CalibrationImpl::is_magnetometer_calibration_ok() const
{
std::lock_guard<std::mutex> lock(_calibration_mutex);
return _is_magnetometer_ok;
}
void CalibrationImpl::command_result_callback(MAVLinkCommands::Result command_result,
float progress)
{
std::lock_guard<std::mutex> lock(_calibration_mutex);
if (_state == State::NONE) {
// It might be someone else like a ground station trying to do a
// calibration. We silently ignore it.
return;
}
// If we get a progress result here, it is the new interface and we can
// use the progress info. If we get an ack, we need to translate that to
// a first progress update, and then parse the statustexts for progress.
switch (command_result) {
case MAVLinkCommands::Result::SUCCESS:
// Silently ignore.
break;
case MAVLinkCommands::Result::NO_SYSTEM:
// FALLTHROUGH
case MAVLinkCommands::Result::CONNECTION_ERROR:
// FALLTHROUGH
case MAVLinkCommands::Result::BUSY:
// FALLTHROUGH
case MAVLinkCommands::Result::COMMAND_DENIED:
// FALLTHROUGH
case MAVLinkCommands::Result::UNKNOWN_ERROR:
// FALLTHROUGH
case MAVLinkCommands::Result::TIMEOUT:
// Report all error cases.
if (_calibration_callback) {
auto calibration_callback_tmp = _calibration_callback;
_parent->call_user_callback([calibration_callback_tmp, command_result]() {
calibration_callback_tmp(
calibration_result_from_command_result(command_result), NAN, "");
});
}
_calibration_callback = nullptr;
_state = State::NONE;
break;
case MAVLinkCommands::Result::IN_PROGRESS:
if (_calibration_callback) {
auto calibration_callback_tmp = _calibration_callback;
_parent->call_user_callback([calibration_callback_tmp, command_result, progress]() {
calibration_callback_tmp(
calibration_result_from_command_result(command_result), progress, "");
});
}
break;
};
}
Calibration::Result
CalibrationImpl::calibration_result_from_command_result(MAVLinkCommands::Result result)
{
switch (result) {
case MAVLinkCommands::Result::SUCCESS:
return Calibration::Result::SUCCESS;
case MAVLinkCommands::Result::NO_SYSTEM:
return Calibration::Result::NO_SYSTEM;
case MAVLinkCommands::Result::CONNECTION_ERROR:
return Calibration::Result::CONNECTION_ERROR;
case MAVLinkCommands::Result::BUSY:
return Calibration::Result::BUSY;
case MAVLinkCommands::Result::COMMAND_DENIED:
return Calibration::Result::COMMAND_DENIED;
case MAVLinkCommands::Result::TIMEOUT:
return Calibration::Result::TIMEOUT;
case MAVLinkCommands::Result::IN_PROGRESS:
return Calibration::Result::IN_PROGRESS;
default:
return Calibration::Result::UNKNOWN;
}
}
void CalibrationImpl::receive_param_cal_gyro(bool success, int value)
{
if (!success) {
LogErr() << "Error: Param for gyro cal failed.";
return;
}
bool ok = (value != 0);
set_gyro_calibration(ok);
}
void CalibrationImpl::receive_param_cal_accel(bool success, int value)
{
if (!success) {
LogErr() << "Error: Param for accel cal failed.";
return;
}
bool ok = (value != 0);
set_accelerometer_calibration(ok);
}
void CalibrationImpl::receive_param_cal_mag(bool success, int value)
{
if (!success) {
LogErr() << "Error: Param for mag cal failed.";
return;
}
bool ok = (value != 0);
set_magnetometer_calibration(ok);
}
void CalibrationImpl::set_gyro_calibration(bool ok)
{
std::lock_guard<std::mutex> lock(_calibration_mutex);
_is_gyro_ok = ok;
}
void CalibrationImpl::set_accelerometer_calibration(bool ok)
{
std::lock_guard<std::mutex> lock(_calibration_mutex);
_is_accelerometer_ok = ok;
}
void CalibrationImpl::set_magnetometer_calibration(bool ok)
{
std::lock_guard<std::mutex> lock(_calibration_mutex);
_is_magnetometer_ok = ok;
}
void CalibrationImpl::process_statustext(const mavlink_message_t &message)
{
std::lock_guard<std::mutex> lock(_calibration_mutex);
if (_state == State::NONE) {
return;
}
mavlink_statustext_t statustext;
mavlink_msg_statustext_decode(&message, &statustext);
_parser.reset();
_parser.parse(statustext.text);
switch (_parser.get_status()) {
case CalibrationStatustextParser::Status::NONE:
// Ignore it.
break;
case CalibrationStatustextParser::Status::STARTED:
report_started();
break;
case CalibrationStatustextParser::Status::DONE:
report_done();
break;
case CalibrationStatustextParser::Status::FAILED:
report_failed(_parser.get_failed_message());
break;
case CalibrationStatustextParser::Status::CANCELLED:
report_cancelled();
break;
case CalibrationStatustextParser::Status::PROGRESS:
report_progress(_parser.get_progress());
break;
case CalibrationStatustextParser::Status::INSTRUCTION:
report_instruction(_parser.get_instruction());
break;
}
switch (_parser.get_status()) {
case CalibrationStatustextParser::Status::DONE:
// FALLTHROUGH
case CalibrationStatustextParser::Status::FAILED:
// FALLTHROUGH
case CalibrationStatustextParser::Status::CANCELLED:
_calibration_callback = nullptr;
_state = State::NONE;
break;
default:
break;
}
}
void CalibrationImpl::report_started()
{
report_progress(0.0f);
}
void CalibrationImpl::report_done()
{
if (_calibration_callback) {
auto calibration_callback_tmp = _calibration_callback;
_parent->call_user_callback([calibration_callback_tmp]() {
calibration_callback_tmp(Calibration::Result::SUCCESS, NAN, "");
});
}
}
void CalibrationImpl::report_failed(const std::string &failed)
{
LogErr() << "Calibration failed: " << failed;
if (_calibration_callback) {
auto calibration_callback_tmp = _calibration_callback;
_parent->call_user_callback([calibration_callback_tmp]() {
calibration_callback_tmp(Calibration::Result::FAILED, NAN, "");
});
}
}
void CalibrationImpl::report_cancelled()
{
LogWarn() << "Calibration was cancelled";
if (_calibration_callback) {
auto calibration_callback_tmp = _calibration_callback;
_parent->call_user_callback([calibration_callback_tmp]() {
calibration_callback_tmp(Calibration::Result::CANCELLED, NAN, "");
});
}
}
void CalibrationImpl::report_progress(float progress)
{
if (_calibration_callback) {
auto calibration_callback_tmp = _calibration_callback;
_parent->call_user_callback([calibration_callback_tmp, progress]() {
calibration_callback_tmp(Calibration::Result::IN_PROGRESS, progress, "");
});
}
}
void CalibrationImpl::report_instruction(const std::string &instruction)
{
if (_calibration_callback) {
auto calibration_callback_tmp = _calibration_callback;
_parent->call_user_callback([calibration_callback_tmp, instruction]() {
calibration_callback_tmp(Calibration::Result::INSTRUCTION, NAN, instruction);
});
}
}
} // namespace dronecode_sdk
<|endoftext|> |
<commit_before>/**
* @file max_variance_new_cluster_impl.hpp
* @author Ryan Curtin
*
* Implementation of MaxVarianceNewCluster class.
*/
#ifndef __MLPACK_METHODS_KMEANS_MAX_VARIANCE_NEW_CLUSTER_IMPL_HPP
#define __MLPACK_METHODS_KMEANS_MAX_VARIANCE_NEW_CLUSTER_IMPL_HPP
// Just in case it has not been included.
#include "max_variance_new_cluster.hpp"
namespace mlpack {
namespace kmeans {
/**
* Take action about an empty cluster.
*/
template<typename MetricType, typename MatType>
size_t MaxVarianceNewCluster::EmptyCluster(const MatType& data,
const size_t emptyCluster,
const arma::mat& oldCentroids,
arma::mat& newCentroids,
arma::Col<size_t>& clusterCounts,
MetricType& metric,
const size_t iteration)
{
// If necessary, calculate the variances and assignments.
if (iteration != this->iteration || assignments.n_elem != data.n_cols)
Precalculate(data, oldCentroids, clusterCounts, metric);
this->iteration = iteration;
// Now find the cluster with maximum variance.
arma::uword maxVarCluster;
variances.max(maxVarCluster);
// Now, inside this cluster, find the point which is furthest away.
size_t furthestPoint = data.n_cols;
double maxDistance = -DBL_MAX;
for (size_t i = 0; i < data.n_cols; ++i)
{
if (assignments[i] == maxVarCluster)
{
const double distance = std::pow(metric.Evaluate(data.col(i),
newCentroids.col(maxVarCluster)), 2.0);
if (distance > maxDistance)
{
maxDistance = distance;
furthestPoint = i;
}
}
}
// Take that point and add it to the empty cluster.
newCentroids.col(maxVarCluster) *= (double(clusterCounts[maxVarCluster]) /
double(clusterCounts[maxVarCluster] - 1));
newCentroids.col(maxVarCluster) -= (1.0 / (clusterCounts[maxVarCluster] - 1.0)) *
arma::vec(data.col(furthestPoint));
clusterCounts[maxVarCluster]--;
clusterCounts[emptyCluster]++;
newCentroids.col(emptyCluster) = arma::vec(data.col(furthestPoint));
assignments[furthestPoint] = emptyCluster;
// Modify the variances, as necessary.
variances[emptyCluster] = 0;
// One has already been subtracted from clusterCounts[maxVarCluster].
variances[maxVarCluster] = (1.0 / (clusterCounts[maxVarCluster])) *
((clusterCounts[maxVarCluster] + 1) * variances[maxVarCluster] - maxDistance);
// Output some debugging information.
Log::Debug << "Point " << furthestPoint << " assigned to empty cluster " <<
emptyCluster << ".\n";
return 1; // We only changed one point.
}
//! Serialize the object.
template<typename Archive>
void MaxVarianceNewCluster::Serialize(Archive& /* ar */,
const unsigned int /* version */)
{
// Serialization is useless here, because the only thing we store is
// precalculated quantities, and if we're serializing, our precalculations are
// likely to be useless when we deserialize (because the user will be running
// a different clustering, probably). So there is no need to store anything,
// and if we are loading, we just reset the assignments array so
// precalculation will happen next time EmptyCluster() is called.
if (Archive::is_loading::value)
assignments.set_size(0);
}
template<typename MetricType, typename MatType>
void MaxVarianceNewCluster::Precalculate(const MatType& data,
const arma::mat& oldCentroids,
arma::Col<size_t>& clusterCounts,
MetricType& metric)
{
// We have to calculate the variances of each cluster and the assignments of
// each point. This is most easily done by iterating through the entire
// dataset.
variances.zeros(oldCentroids.n_cols);
assignments.set_size(data.n_cols);
// Add the variance of each point's distance away from the cluster. I think
// this is the sensible thing to do.
for (size_t i = 0; i < data.n_cols; ++i)
{
// Find the closest centroid to this point.
double minDistance = std::numeric_limits<double>::infinity();
size_t closestCluster = oldCentroids.n_cols; // Invalid value.
for (size_t j = 0; j < oldCentroids.n_cols; j++)
{
const double distance = metric.Evaluate(data.col(i), oldCentroids.col(j));
if (distance < minDistance)
{
minDistance = distance;
closestCluster = j;
}
}
assignments[i] = closestCluster;
variances[closestCluster] += std::pow(metric.Evaluate(data.col(i),
oldCentroids.col(closestCluster)), 2.0);
}
// Divide by the number of points in the cluster to produce the variance,
// unless the cluster is empty or contains only one point, in which case we
// set the variance to 0.
for (size_t i = 0; i < clusterCounts.n_elem; ++i)
if (clusterCounts[i] <= 1)
variances[i] = 0;
else
variances[i] /= clusterCounts[i];
}
}; // namespace kmeans
}; // namespace mlpack
#endif
<commit_msg>kmeans: small fix with inf variance<commit_after>/**
* @file max_variance_new_cluster_impl.hpp
* @author Ryan Curtin
*
* Implementation of MaxVarianceNewCluster class.
*/
#ifndef __MLPACK_METHODS_KMEANS_MAX_VARIANCE_NEW_CLUSTER_IMPL_HPP
#define __MLPACK_METHODS_KMEANS_MAX_VARIANCE_NEW_CLUSTER_IMPL_HPP
// Just in case it has not been included.
#include "max_variance_new_cluster.hpp"
namespace mlpack {
namespace kmeans {
/**
* Take action about an empty cluster.
*/
template<typename MetricType, typename MatType>
size_t MaxVarianceNewCluster::EmptyCluster(const MatType& data,
const size_t emptyCluster,
const arma::mat& oldCentroids,
arma::mat& newCentroids,
arma::Col<size_t>& clusterCounts,
MetricType& metric,
const size_t iteration)
{
// If necessary, calculate the variances and assignments.
if (iteration != this->iteration || assignments.n_elem != data.n_cols)
Precalculate(data, oldCentroids, clusterCounts, metric);
this->iteration = iteration;
// Now find the cluster with maximum variance.
arma::uword maxVarCluster;
variances.max(maxVarCluster);
// Now, inside this cluster, find the point which is furthest away.
size_t furthestPoint = data.n_cols;
double maxDistance = -DBL_MAX;
for (size_t i = 0; i < data.n_cols; ++i)
{
if (assignments[i] == maxVarCluster)
{
const double distance = std::pow(metric.Evaluate(data.col(i),
newCentroids.col(maxVarCluster)), 2.0);
if (distance > maxDistance)
{
maxDistance = distance;
furthestPoint = i;
}
}
}
// Take that point and add it to the empty cluster.
newCentroids.col(maxVarCluster) *= (double(clusterCounts[maxVarCluster]) /
double(clusterCounts[maxVarCluster] - 1));
newCentroids.col(maxVarCluster) -= (1.0 / (clusterCounts[maxVarCluster] - 1.0)) *
arma::vec(data.col(furthestPoint));
clusterCounts[maxVarCluster]--;
clusterCounts[emptyCluster]++;
newCentroids.col(emptyCluster) = arma::vec(data.col(furthestPoint));
assignments[furthestPoint] = emptyCluster;
// Modify the variances, as necessary.
variances[emptyCluster] = 0;
// One has already been subtracted from clusterCounts[maxVarCluster].
if (clusterCounts[maxVarCluster] <= 1)
variances[maxVarCluster] = 0;
else
variances[maxVarCluster] = (1.0 / clusterCounts[maxVarCluster]) *
((clusterCounts[maxVarCluster] + 1) * variances[maxVarCluster] - maxDistance);
// Output some debugging information.
Log::Debug << "Point " << furthestPoint << " assigned to empty cluster " <<
emptyCluster << ".\n";
return 1; // We only changed one point.
}
//! Serialize the object.
template<typename Archive>
void MaxVarianceNewCluster::Serialize(Archive& /* ar */,
const unsigned int /* version */)
{
// Serialization is useless here, because the only thing we store is
// precalculated quantities, and if we're serializing, our precalculations are
// likely to be useless when we deserialize (because the user will be running
// a different clustering, probably). So there is no need to store anything,
// and if we are loading, we just reset the assignments array so
// precalculation will happen next time EmptyCluster() is called.
if (Archive::is_loading::value)
assignments.set_size(0);
}
template<typename MetricType, typename MatType>
void MaxVarianceNewCluster::Precalculate(const MatType& data,
const arma::mat& oldCentroids,
arma::Col<size_t>& clusterCounts,
MetricType& metric)
{
// We have to calculate the variances of each cluster and the assignments of
// each point. This is most easily done by iterating through the entire
// dataset.
variances.zeros(oldCentroids.n_cols);
assignments.set_size(data.n_cols);
// Add the variance of each point's distance away from the cluster. I think
// this is the sensible thing to do.
for (size_t i = 0; i < data.n_cols; ++i)
{
// Find the closest centroid to this point.
double minDistance = std::numeric_limits<double>::infinity();
size_t closestCluster = oldCentroids.n_cols; // Invalid value.
for (size_t j = 0; j < oldCentroids.n_cols; j++)
{
const double distance = metric.Evaluate(data.col(i), oldCentroids.col(j));
if (distance < minDistance)
{
minDistance = distance;
closestCluster = j;
}
}
assignments[i] = closestCluster;
variances[closestCluster] += std::pow(metric.Evaluate(data.col(i),
oldCentroids.col(closestCluster)), 2.0);
}
// Divide by the number of points in the cluster to produce the variance,
// unless the cluster is empty or contains only one point, in which case we
// set the variance to 0.
for (size_t i = 0; i < clusterCounts.n_elem; ++i)
if (clusterCounts[i] <= 1)
variances[i] = 0;
else
variances[i] /= clusterCounts[i];
}
}; // namespace kmeans
}; // namespace mlpack
#endif
<|endoftext|> |
<commit_before>/* libs/graphics/ports/SkFontHost_fontconfig.cpp
**
** Copyright 2008, Google Inc.
**
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
// -----------------------------------------------------------------------------
// This file provides implementations of the font resolution members of
// SkFontHost by using the fontconfig[1] library. Fontconfig is usually found
// on Linux systems and handles configuration, parsing and caching issues
// involved with enumerating and matching fonts.
//
// [1] http://fontconfig.org
// -----------------------------------------------------------------------------
#include <map>
#include <string>
#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>
#include "SkFontHost.h"
#include "SkStream.h"
#include "SkFontHost_fontconfig_control.h"
#include "SkFontHost_fontconfig_impl.h"
#include "SkFontHost_fontconfig_direct.h"
static FontConfigInterface* global_fc_impl = NULL;
void SkiaFontConfigUseDirectImplementation() {
if (global_fc_impl)
delete global_fc_impl;
global_fc_impl = new FontConfigDirect;
}
void SkiaFontConfigSetImplementation(FontConfigInterface* font_config) {
if (global_fc_impl)
delete global_fc_impl;
global_fc_impl = font_config;
}
static FontConfigInterface* GetFcImpl() {
if (!global_fc_impl)
global_fc_impl = new FontConfigDirect;
return global_fc_impl;
}
static SkMutex global_fc_map_lock;
static std::map<uint32_t, SkTypeface *> global_fc_typefaces;
static SkMutex global_remote_font_map_lock;
static std::map<uint32_t, std::pair<uint8_t*, size_t> > global_remote_fonts;
static unsigned global_next_remote_font_id;
// This is the maximum size of the font cache.
static const unsigned kFontCacheMemoryBudget = 2 * 1024 * 1024; // 2MB
// UniqueIds are encoded as (filefaceid << 8) | style
// For system fonts, filefaceid = (fileid << 4) | face_index.
// For remote fonts, filefaceid = fileid.
static unsigned UniqueIdToFileFaceId(unsigned uniqueid)
{
return uniqueid >> 8;
}
static SkTypeface::Style UniqueIdToStyle(unsigned uniqueid)
{
return static_cast<SkTypeface::Style>(uniqueid & 0xff);
}
static unsigned FileFaceIdAndStyleToUniqueId(unsigned filefaceid,
SkTypeface::Style style)
{
SkASSERT((style & 0xff) == style);
return (filefaceid << 8) | static_cast<int>(style);
}
static const unsigned kRemoteFontMask = 0x00800000u;
static bool IsRemoteFont(unsigned filefaceid)
{
return filefaceid & kRemoteFontMask;
}
class FontConfigTypeface : public SkTypeface {
public:
FontConfigTypeface(Style style, uint32_t id)
: SkTypeface(style, id)
{ }
~FontConfigTypeface()
{
const uint32_t id = uniqueID();
if (IsRemoteFont(UniqueIdToFileFaceId(id))) {
SkAutoMutexAcquire ac(global_remote_font_map_lock);
std::map<uint32_t, std::pair<uint8_t*, size_t> >::iterator iter
= global_remote_fonts.find(id);
if (iter != global_remote_fonts.end()) {
sk_free(iter->second.first); // remove the font on memory.
global_remote_fonts.erase(iter);
}
}
}
};
// static
SkTypeface* SkFontHost::CreateTypeface(const SkTypeface* familyFace,
const char familyName[],
const void* data, size_t bytelength,
SkTypeface::Style style)
{
std::string resolved_family_name;
if (familyFace) {
// Given the fileid we can ask fontconfig for the familyname of the
// font.
const unsigned filefaceid = UniqueIdToFileFaceId(familyFace->uniqueID());
if (!GetFcImpl()->Match(&resolved_family_name, NULL,
true /* filefaceid valid */, filefaceid, "",
NULL, 0, NULL, NULL)) {
return NULL;
}
} else if (familyName) {
resolved_family_name = familyName;
}
bool bold = style & SkTypeface::kBold;
bool italic = style & SkTypeface::kItalic;
unsigned filefaceid;
if (!GetFcImpl()->Match(NULL, &filefaceid,
false, -1, /* no filefaceid */
resolved_family_name, data, bytelength,
&bold, &italic)) {
return NULL;
}
const SkTypeface::Style resulting_style = static_cast<SkTypeface::Style>(
(bold ? SkTypeface::kBold : 0) |
(italic ? SkTypeface::kItalic : 0));
const unsigned id = FileFaceIdAndStyleToUniqueId(filefaceid,
resulting_style);
SkTypeface* typeface = SkNEW_ARGS(FontConfigTypeface, (resulting_style, id));
{
SkAutoMutexAcquire ac(global_fc_map_lock);
global_fc_typefaces[id] = typeface;
}
return typeface;
}
// static
SkTypeface* SkFontHost::CreateTypefaceFromStream(SkStream* stream)
{
if (!stream)
return NULL;
const size_t length = stream->read(0, 0);
if (!length)
return NULL;
if (length >= 1024 * 1024 * 1024)
return NULL; // don't accept too large fonts (>= 1GB) for safety.
uint8_t* font = (uint8_t*)sk_malloc_throw(length);
if (stream->read(font, length) != length) {
sk_free(font);
return NULL;
}
SkTypeface::Style style = static_cast<SkTypeface::Style>(0);
unsigned id = 0;
{
SkAutoMutexAcquire ac(global_remote_font_map_lock);
id = FileFaceIdAndStyleToUniqueId(
global_next_remote_font_id | kRemoteFontMask, style);
if (++global_next_remote_font_id >= kRemoteFontMask)
global_next_remote_font_id = 0;
if (!global_remote_fonts.insert(
std::make_pair(id, std::make_pair(font, length))).second) {
sk_free(font);
return NULL;
}
}
SkTypeface* typeface = SkNEW_ARGS(FontConfigTypeface, (style, id));
return typeface;
}
// static
SkTypeface* SkFontHost::CreateTypefaceFromFile(const char path[])
{
SkASSERT(!"SkFontHost::CreateTypefaceFromFile unimplemented");
return NULL;
}
// static
bool SkFontHost::ValidFontID(SkFontID uniqueID) {
if (IsRemoteFont(UniqueIdToFileFaceId(uniqueID))) {
// remote font
SkAutoMutexAcquire ac(global_remote_font_map_lock);
return global_remote_fonts.find(uniqueID) != global_remote_fonts.end();
} else {
// local font
SkAutoMutexAcquire ac(global_fc_map_lock);
return global_fc_typefaces.find(uniqueID) != global_fc_typefaces.end();
}
}
void SkFontHost::Serialize(const SkTypeface*, SkWStream*) {
SkASSERT(!"SkFontHost::Serialize unimplemented");
}
SkTypeface* SkFontHost::Deserialize(SkStream* stream) {
SkASSERT(!"SkFontHost::Deserialize unimplemented");
return NULL;
}
// static
uint32_t SkFontHost::NextLogicalFont(SkFontID curr, SkFontID orig) {
// We don't handle font fallback, WebKit does.
return 0;
}
///////////////////////////////////////////////////////////////////////////////
class SkFileDescriptorStream : public SkStream {
public:
SkFileDescriptorStream(int fd) {
memory_ = NULL;
offset_ = 0;
// this ensures that if we fail in the constructor, we will safely
// ignore all subsequent calls to read() because we will always trim
// the requested size down to 0
length_ = 0;
struct stat st;
if (fstat(fd, &st))
return;
void* memory = mmap(NULL, st.st_size, PROT_READ, MAP_SHARED, fd, 0);
close(fd);
if (memory == MAP_FAILED)
return;
memory_ = reinterpret_cast<uint8_t*>(memory);
length_ = st.st_size;
}
~SkFileDescriptorStream() {
munmap(const_cast<uint8_t*>(memory_), length_);
}
virtual bool rewind() {
offset_ = 0;
return true;
}
// SkStream implementation.
virtual size_t read(void* buffer, size_t size) {
if (!buffer && !size) {
// This is request for the length of the stream.
return length_;
}
size_t remaining = length_ - offset_;
if (size > remaining)
size = remaining;
if (buffer)
memcpy(buffer, memory_ + offset_, size);
offset_ += size;
return size;
}
virtual const void* getMemoryBase() {
return memory_;
}
private:
const uint8_t* memory_;
size_t offset_, length_;
};
///////////////////////////////////////////////////////////////////////////////
// static
SkStream* SkFontHost::OpenStream(uint32_t id)
{
const unsigned filefaceid = UniqueIdToFileFaceId(id);
if (IsRemoteFont(filefaceid)) {
// remote font
SkAutoMutexAcquire ac(global_remote_font_map_lock);
std::map<uint32_t, std::pair<uint8_t*, size_t> >::const_iterator iter
= global_remote_fonts.find(id);
if (iter == global_remote_fonts.end())
return NULL;
return SkNEW_ARGS(
SkMemoryStream, (iter->second.first, iter->second.second));
}
// system font
const int fd = GetFcImpl()->Open(filefaceid);
if (fd < 0)
return NULL;
return SkNEW_ARGS(SkFileDescriptorStream, (fd));
}
// static
size_t SkFontHost::GetFileName(SkFontID fontID, char path[], size_t length,
int32_t* index) {
const unsigned filefaceid = UniqueIdToFileFaceId(fontID);
if (IsRemoteFont(filefaceid))
return 0;
if (index) {
*index = filefaceid & 0xfu;
// 1 is a bogus return value.
// We had better change the signature of this function in Skia
// to return bool to indicate success/failure and have another
// out param for fileName length.
if (!path)
return 1;
}
if (path)
SkASSERT(!"SkFontHost::GetFileName does not support the font path "
"retrieval.");
return 0;
}
<commit_msg>Remove ValidFontID.<commit_after>/* libs/graphics/ports/SkFontHost_fontconfig.cpp
**
** Copyright 2008, Google Inc.
**
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
// -----------------------------------------------------------------------------
// This file provides implementations of the font resolution members of
// SkFontHost by using the fontconfig[1] library. Fontconfig is usually found
// on Linux systems and handles configuration, parsing and caching issues
// involved with enumerating and matching fonts.
//
// [1] http://fontconfig.org
// -----------------------------------------------------------------------------
#include <map>
#include <string>
#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>
#include "SkFontHost.h"
#include "SkStream.h"
#include "SkFontHost_fontconfig_control.h"
#include "SkFontHost_fontconfig_impl.h"
#include "SkFontHost_fontconfig_direct.h"
static FontConfigInterface* global_fc_impl = NULL;
void SkiaFontConfigUseDirectImplementation() {
if (global_fc_impl)
delete global_fc_impl;
global_fc_impl = new FontConfigDirect;
}
void SkiaFontConfigSetImplementation(FontConfigInterface* font_config) {
if (global_fc_impl)
delete global_fc_impl;
global_fc_impl = font_config;
}
static FontConfigInterface* GetFcImpl() {
if (!global_fc_impl)
global_fc_impl = new FontConfigDirect;
return global_fc_impl;
}
static SkMutex global_fc_map_lock;
static std::map<uint32_t, SkTypeface *> global_fc_typefaces;
static SkMutex global_remote_font_map_lock;
static std::map<uint32_t, std::pair<uint8_t*, size_t> > global_remote_fonts;
static unsigned global_next_remote_font_id;
// This is the maximum size of the font cache.
static const unsigned kFontCacheMemoryBudget = 2 * 1024 * 1024; // 2MB
// UniqueIds are encoded as (filefaceid << 8) | style
// For system fonts, filefaceid = (fileid << 4) | face_index.
// For remote fonts, filefaceid = fileid.
static unsigned UniqueIdToFileFaceId(unsigned uniqueid)
{
return uniqueid >> 8;
}
static SkTypeface::Style UniqueIdToStyle(unsigned uniqueid)
{
return static_cast<SkTypeface::Style>(uniqueid & 0xff);
}
static unsigned FileFaceIdAndStyleToUniqueId(unsigned filefaceid,
SkTypeface::Style style)
{
SkASSERT((style & 0xff) == style);
return (filefaceid << 8) | static_cast<int>(style);
}
static const unsigned kRemoteFontMask = 0x00800000u;
static bool IsRemoteFont(unsigned filefaceid)
{
return filefaceid & kRemoteFontMask;
}
class FontConfigTypeface : public SkTypeface {
public:
FontConfigTypeface(Style style, uint32_t id)
: SkTypeface(style, id)
{ }
~FontConfigTypeface()
{
const uint32_t id = uniqueID();
if (IsRemoteFont(UniqueIdToFileFaceId(id))) {
SkAutoMutexAcquire ac(global_remote_font_map_lock);
std::map<uint32_t, std::pair<uint8_t*, size_t> >::iterator iter
= global_remote_fonts.find(id);
if (iter != global_remote_fonts.end()) {
sk_free(iter->second.first); // remove the font on memory.
global_remote_fonts.erase(iter);
}
}
}
};
// static
SkTypeface* SkFontHost::CreateTypeface(const SkTypeface* familyFace,
const char familyName[],
const void* data, size_t bytelength,
SkTypeface::Style style)
{
std::string resolved_family_name;
if (familyFace) {
// Given the fileid we can ask fontconfig for the familyname of the
// font.
const unsigned filefaceid = UniqueIdToFileFaceId(familyFace->uniqueID());
if (!GetFcImpl()->Match(&resolved_family_name, NULL,
true /* filefaceid valid */, filefaceid, "",
NULL, 0, NULL, NULL)) {
return NULL;
}
} else if (familyName) {
resolved_family_name = familyName;
}
bool bold = style & SkTypeface::kBold;
bool italic = style & SkTypeface::kItalic;
unsigned filefaceid;
if (!GetFcImpl()->Match(NULL, &filefaceid,
false, -1, /* no filefaceid */
resolved_family_name, data, bytelength,
&bold, &italic)) {
return NULL;
}
const SkTypeface::Style resulting_style = static_cast<SkTypeface::Style>(
(bold ? SkTypeface::kBold : 0) |
(italic ? SkTypeface::kItalic : 0));
const unsigned id = FileFaceIdAndStyleToUniqueId(filefaceid,
resulting_style);
SkTypeface* typeface = SkNEW_ARGS(FontConfigTypeface, (resulting_style, id));
{
SkAutoMutexAcquire ac(global_fc_map_lock);
global_fc_typefaces[id] = typeface;
}
return typeface;
}
// static
SkTypeface* SkFontHost::CreateTypefaceFromStream(SkStream* stream)
{
if (!stream)
return NULL;
const size_t length = stream->read(0, 0);
if (!length)
return NULL;
if (length >= 1024 * 1024 * 1024)
return NULL; // don't accept too large fonts (>= 1GB) for safety.
uint8_t* font = (uint8_t*)sk_malloc_throw(length);
if (stream->read(font, length) != length) {
sk_free(font);
return NULL;
}
SkTypeface::Style style = static_cast<SkTypeface::Style>(0);
unsigned id = 0;
{
SkAutoMutexAcquire ac(global_remote_font_map_lock);
id = FileFaceIdAndStyleToUniqueId(
global_next_remote_font_id | kRemoteFontMask, style);
if (++global_next_remote_font_id >= kRemoteFontMask)
global_next_remote_font_id = 0;
if (!global_remote_fonts.insert(
std::make_pair(id, std::make_pair(font, length))).second) {
sk_free(font);
return NULL;
}
}
SkTypeface* typeface = SkNEW_ARGS(FontConfigTypeface, (style, id));
return typeface;
}
// static
SkTypeface* SkFontHost::CreateTypefaceFromFile(const char path[])
{
SkASSERT(!"SkFontHost::CreateTypefaceFromFile unimplemented");
return NULL;
}
void SkFontHost::Serialize(const SkTypeface*, SkWStream*) {
SkASSERT(!"SkFontHost::Serialize unimplemented");
}
SkTypeface* SkFontHost::Deserialize(SkStream* stream) {
SkASSERT(!"SkFontHost::Deserialize unimplemented");
return NULL;
}
// static
uint32_t SkFontHost::NextLogicalFont(SkFontID curr, SkFontID orig) {
// We don't handle font fallback, WebKit does.
return 0;
}
///////////////////////////////////////////////////////////////////////////////
class SkFileDescriptorStream : public SkStream {
public:
SkFileDescriptorStream(int fd) {
memory_ = NULL;
offset_ = 0;
// this ensures that if we fail in the constructor, we will safely
// ignore all subsequent calls to read() because we will always trim
// the requested size down to 0
length_ = 0;
struct stat st;
if (fstat(fd, &st))
return;
void* memory = mmap(NULL, st.st_size, PROT_READ, MAP_SHARED, fd, 0);
close(fd);
if (memory == MAP_FAILED)
return;
memory_ = reinterpret_cast<uint8_t*>(memory);
length_ = st.st_size;
}
~SkFileDescriptorStream() {
munmap(const_cast<uint8_t*>(memory_), length_);
}
virtual bool rewind() {
offset_ = 0;
return true;
}
// SkStream implementation.
virtual size_t read(void* buffer, size_t size) {
if (!buffer && !size) {
// This is request for the length of the stream.
return length_;
}
size_t remaining = length_ - offset_;
if (size > remaining)
size = remaining;
if (buffer)
memcpy(buffer, memory_ + offset_, size);
offset_ += size;
return size;
}
virtual const void* getMemoryBase() {
return memory_;
}
private:
const uint8_t* memory_;
size_t offset_, length_;
};
///////////////////////////////////////////////////////////////////////////////
// static
SkStream* SkFontHost::OpenStream(uint32_t id)
{
const unsigned filefaceid = UniqueIdToFileFaceId(id);
if (IsRemoteFont(filefaceid)) {
// remote font
SkAutoMutexAcquire ac(global_remote_font_map_lock);
std::map<uint32_t, std::pair<uint8_t*, size_t> >::const_iterator iter
= global_remote_fonts.find(id);
if (iter == global_remote_fonts.end())
return NULL;
return SkNEW_ARGS(
SkMemoryStream, (iter->second.first, iter->second.second));
}
// system font
const int fd = GetFcImpl()->Open(filefaceid);
if (fd < 0)
return NULL;
return SkNEW_ARGS(SkFileDescriptorStream, (fd));
}
// static
size_t SkFontHost::GetFileName(SkFontID fontID, char path[], size_t length,
int32_t* index) {
const unsigned filefaceid = UniqueIdToFileFaceId(fontID);
if (IsRemoteFont(filefaceid))
return 0;
if (index) {
*index = filefaceid & 0xfu;
// 1 is a bogus return value.
// We had better change the signature of this function in Skia
// to return bool to indicate success/failure and have another
// out param for fileName length.
if (!path)
return 1;
}
if (path)
SkASSERT(!"SkFontHost::GetFileName does not support the font path "
"retrieval.");
return 0;
}
<|endoftext|> |
<commit_before>
#include "iaxclient.h"
// For compilers that supports precompilation , includes wx/wx.h
#include "wx/wxprec.h"
#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif
#include "wx.h"
IMPLEMENT_APP(IAXClient)
static int inputLevel = 0;
static int outputLevel = 0;
static char *buttonlabels[] = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "*", "0", "#" };
class IAXTimer : public wxTimer
{
public:
void IAXTimer::Notify();
};
class DialPad : public wxPanel
{
public:
DialPad(wxFrame *parent, wxPoint pos, wxSize size);
void ButtonHandler(wxEvent &evt);
wxButton *buttons[12];
protected:
DECLARE_EVENT_TABLE()
};
class IAXFrame : public wxFrame
{
public:
IAXFrame(const wxChar *title, int xpos, int ypos, int width, int height);
~IAXFrame();
void IAXFrame::ButtonHandler(wxEvent &evt);
wxGauge *input;
wxGauge *output;
DialPad *dialPad;
IAXTimer *timer;
wxTextCtrl *iaxDest;
wxButton *dialButton, *quitButton;
protected:
DECLARE_EVENT_TABLE()
};
static IAXFrame *theFrame;
void IAXTimer::Notify()
{
iaxc_process_calls();
}
DialPad::DialPad(wxFrame *parent, wxPoint pos, wxSize size)
: wxPanel(parent, -1, pos, size, wxTAB_TRAVERSAL, wxString("dial pad"))
{
int x=0 ,y=0;
int dX = size.GetWidth()/3;
int dY = size.GetHeight()/4;
#if 0
wxGauge *w = new wxGauge(this, -1, 50, wxPoint(0,0), wxSize(10,200),
wxGA_VERTICAL, wxDefaultValidator, wxString("test level"));
#endif
for(int i=0; i<12;)
{
fprintf(stderr, "creating button at %d,%d, %d by %d\n", x,y,dX,dY);
buttons[i] = new wxButton(this, i, wxString(buttonlabels[i]),
wxPoint(x,y), wxSize(dX-5,dY-5),
0, wxDefaultValidator, wxString(buttonlabels[i]));
i++;
if(i%3 == 0) {
x=0; y+=dY;
} else {
x+=dX;
}
}
}
void DialPad::ButtonHandler(wxEvent &evt)
{
int buttonNo = evt.m_id;
char *button = buttonlabels[buttonNo];
fprintf(stderr, "got Button Event for button %s\n", button);
iaxc_send_dtmf(*button);
}
BEGIN_EVENT_TABLE(DialPad, wxPanel)
EVT_BUTTON(0,DialPad::ButtonHandler)
EVT_BUTTON(1,DialPad::ButtonHandler)
EVT_BUTTON(2,DialPad::ButtonHandler)
EVT_BUTTON(3,DialPad::ButtonHandler)
EVT_BUTTON(4,DialPad::ButtonHandler)
EVT_BUTTON(5,DialPad::ButtonHandler)
EVT_BUTTON(6,DialPad::ButtonHandler)
EVT_BUTTON(7,DialPad::ButtonHandler)
EVT_BUTTON(8,DialPad::ButtonHandler)
EVT_BUTTON(9,DialPad::ButtonHandler)
EVT_BUTTON(10,DialPad::ButtonHandler)
EVT_BUTTON(11,DialPad::ButtonHandler)
END_EVENT_TABLE()
IAXFrame::IAXFrame(const wxChar *title, int xpos, int ypos, int width, int height)
: wxFrame((wxFrame *) NULL, -1, title, wxPoint(xpos, ypos), wxSize(width, height))
{
dialPad = new DialPad(this, wxPoint(0,0), wxSize(100,120));
input = new wxGauge(this, -1, 50, wxPoint(100,0), wxSize(10,120),
wxGA_VERTICAL, wxDefaultValidator, wxString("input level"));
output = new wxGauge(this, -1, 50, wxPoint(110,0), wxSize(10,120),
wxGA_VERTICAL, wxDefaultValidator, wxString("output level"));
iaxDest = new wxTextCtrl(this, -1, wxString("guest@server"),
wxPoint(0,120), wxSize(110,20) /*, wxTE_MULTILINE */);
dialButton = new wxButton(this, 100, wxString("Dial"),
wxPoint(0,150), wxSize(55,25));
quitButton = new wxButton(this, 101, wxString("Quit"),
wxPoint(60,150), wxSize(55,25));
timer = new IAXTimer();
timer->Start(10);
//output = new wxGauge(this, -1, 100);
}
void IAXFrame::ButtonHandler(wxEvent &evt)
{
int buttonNo = evt.m_id;
fprintf(stderr, "got Button Event for button %d\n", buttonNo);
switch(buttonNo) {
case 100:
// dial the number
iaxc_call(stderr,
(char *)(theFrame->iaxDest->GetValue().c_str()));
break;
case 101:
exit(0);
break;
default:
break;
}
}
BEGIN_EVENT_TABLE(IAXFrame, wxFrame)
EVT_BUTTON(100,IAXFrame::ButtonHandler)
EVT_BUTTON(101,IAXFrame::ButtonHandler)
END_EVENT_TABLE()
IAXFrame::~IAXFrame()
{
}
bool IAXClient::OnInit()
{
theFrame = new IAXFrame("IAXTest", 0,0,120,300);
theFrame->CreateStatusBar();
theFrame->SetStatusText("Hello World");
theFrame->Show(TRUE);
SetTopWindow(theFrame);
doTestCall(0,NULL);
return true;
}
extern "C" {
int levels_callback(float input, float output)
{
if (input < -50)
inputLevel=0;
else
inputLevel=(int)input+50;
if (output < -50)
outputLevel=0;
else
outputLevel=(int)output+50;
theFrame->input->SetValue(inputLevel);
theFrame->output->SetValue(outputLevel);
}
}
<commit_msg>change level meter range<commit_after>
#include "iaxclient.h"
// For compilers that supports precompilation , includes wx/wx.h
#include "wx/wxprec.h"
#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif
#include "wx.h"
#define LEVEL_MAX -10
#define LEVEL_MIN -50
IMPLEMENT_APP(IAXClient)
static int inputLevel = 0;
static int outputLevel = 0;
static char *buttonlabels[] = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "*", "0", "#" };
class IAXTimer : public wxTimer
{
public:
void IAXTimer::Notify();
};
class DialPad : public wxPanel
{
public:
DialPad(wxFrame *parent, wxPoint pos, wxSize size);
void ButtonHandler(wxEvent &evt);
wxButton *buttons[12];
protected:
DECLARE_EVENT_TABLE()
};
class IAXFrame : public wxFrame
{
public:
IAXFrame(const wxChar *title, int xpos, int ypos, int width, int height);
~IAXFrame();
void IAXFrame::ButtonHandler(wxEvent &evt);
wxGauge *input;
wxGauge *output;
DialPad *dialPad;
IAXTimer *timer;
wxTextCtrl *iaxDest;
wxButton *dialButton, *quitButton;
protected:
DECLARE_EVENT_TABLE()
};
static IAXFrame *theFrame;
void IAXTimer::Notify()
{
iaxc_process_calls();
}
DialPad::DialPad(wxFrame *parent, wxPoint pos, wxSize size)
: wxPanel(parent, -1, pos, size, wxTAB_TRAVERSAL, wxString("dial pad"))
{
int x=0 ,y=0;
int dX = size.GetWidth()/3;
int dY = size.GetHeight()/4;
#if 0
wxGauge *w = new wxGauge(this, -1, 50, wxPoint(0,0), wxSize(10,200),
wxGA_VERTICAL, wxDefaultValidator, wxString("test level"));
#endif
for(int i=0; i<12;)
{
fprintf(stderr, "creating button at %d,%d, %d by %d\n", x,y,dX,dY);
buttons[i] = new wxButton(this, i, wxString(buttonlabels[i]),
wxPoint(x,y), wxSize(dX-5,dY-5),
0, wxDefaultValidator, wxString(buttonlabels[i]));
i++;
if(i%3 == 0) {
x=0; y+=dY;
} else {
x+=dX;
}
}
}
void DialPad::ButtonHandler(wxEvent &evt)
{
int buttonNo = evt.m_id;
char *button = buttonlabels[buttonNo];
fprintf(stderr, "got Button Event for button %s\n", button);
iaxc_send_dtmf(*button);
}
BEGIN_EVENT_TABLE(DialPad, wxPanel)
EVT_BUTTON(0,DialPad::ButtonHandler)
EVT_BUTTON(1,DialPad::ButtonHandler)
EVT_BUTTON(2,DialPad::ButtonHandler)
EVT_BUTTON(3,DialPad::ButtonHandler)
EVT_BUTTON(4,DialPad::ButtonHandler)
EVT_BUTTON(5,DialPad::ButtonHandler)
EVT_BUTTON(6,DialPad::ButtonHandler)
EVT_BUTTON(7,DialPad::ButtonHandler)
EVT_BUTTON(8,DialPad::ButtonHandler)
EVT_BUTTON(9,DialPad::ButtonHandler)
EVT_BUTTON(10,DialPad::ButtonHandler)
EVT_BUTTON(11,DialPad::ButtonHandler)
END_EVENT_TABLE()
IAXFrame::IAXFrame(const wxChar *title, int xpos, int ypos, int width, int height)
: wxFrame((wxFrame *) NULL, -1, title, wxPoint(xpos, ypos), wxSize(width, height))
{
dialPad = new DialPad(this, wxPoint(0,0), wxSize(100,120));
input = new wxGauge(this, -1, LEVEL_MAX-LEVEL_MIN, wxPoint(100,0), wxSize(10,120),
wxGA_VERTICAL, wxDefaultValidator, wxString("input level"));
output = new wxGauge(this, -1, LEVEL_MAX-LEVEL_MIN, wxPoint(110,0), wxSize(10,120),
wxGA_VERTICAL, wxDefaultValidator, wxString("output level"));
iaxDest = new wxTextCtrl(this, -1, wxString("guest@ast1/8068"),
wxPoint(0,120), wxSize(110,20) /*, wxTE_MULTILINE */);
dialButton = new wxButton(this, 100, wxString("Dial"),
wxPoint(0,150), wxSize(55,25));
quitButton = new wxButton(this, 101, wxString("Quit"),
wxPoint(60,150), wxSize(55,25));
timer = new IAXTimer();
timer->Start(10);
//output = new wxGauge(this, -1, 100);
}
void IAXFrame::ButtonHandler(wxEvent &evt)
{
int buttonNo = evt.m_id;
fprintf(stderr, "got Button Event for button %d\n", buttonNo);
switch(buttonNo) {
case 100:
// dial the number
iaxc_call(stderr,
(char *)(theFrame->iaxDest->GetValue().c_str()));
break;
case 101:
exit(0);
break;
default:
break;
}
}
BEGIN_EVENT_TABLE(IAXFrame, wxFrame)
EVT_BUTTON(100,IAXFrame::ButtonHandler)
EVT_BUTTON(101,IAXFrame::ButtonHandler)
END_EVENT_TABLE()
IAXFrame::~IAXFrame()
{
}
bool IAXClient::OnInit()
{
theFrame = new IAXFrame("IAXTest", 0,0,120,300);
theFrame->CreateStatusBar();
theFrame->SetStatusText("Hello World");
theFrame->Show(TRUE);
SetTopWindow(theFrame);
doTestCall(0,NULL);
return true;
}
extern "C" {
int levels_callback(float input, float output)
{
if (input < LEVEL_MIN)
input = LEVEL_MIN;
else if (input > LEVEL_MAX)
input = LEVEL_MAX;
inputLevel = (int)input - (LEVEL_MIN);
if (output < LEVEL_MIN)
output = LEVEL_MIN;
else if (input > LEVEL_MAX)
output = LEVEL_MAX;
outputLevel = (int)output - (LEVEL_MIN);
theFrame->input->SetValue(inputLevel);
theFrame->output->SetValue(outputLevel);
}
}
<|endoftext|> |
<commit_before>/*
* GLShaderBindingLayout.cpp
*
* This file is part of the "LLGL" project (Copyright (c) 2015-2019 by Lukas Hermanns)
* See "LICENSE.txt" for license information.
*/
#include "GLShaderBindingLayout.h"
#include "../Ext/GLExtensionRegistry.h"
#include "../Ext/GLExtensions.h"
#include "../../../Core/HelperMacros.h"
namespace LLGL
{
GLShaderBindingLayout::GLShaderBindingLayout(const GLPipelineLayout& pipelineLayout)
{
/* Gather all uniform bindings */
for (const auto& binding : pipelineLayout.GetBindings())
{
if (!binding.name.empty())
{
if (binding.type == ResourceType::Sampler || binding.type == ResourceType::Texture)
{
bindings_.push_back({ binding.name, binding.slot });
++numUniformBindings_;
}
}
}
/* Gather all uniform-block bindings */
for (const auto& binding : pipelineLayout.GetBindings())
{
if (!binding.name.empty())
{
if (binding.type == ResourceType::Buffer && (binding.bindFlags & BindFlags::ConstantBuffer) != 0)
{
bindings_.push_back({ binding.name, binding.slot });
++numUniformBlockBindings_;
}
}
}
/* Gather all shader-storage bindings */
for (const auto& binding : pipelineLayout.GetBindings())
{
if (!binding.name.empty())
{
if (binding.type == ResourceType::Buffer && (binding.bindFlags & (BindFlags::Storage | BindFlags::Sampled)) != 0)
{
bindings_.push_back({ binding.name, binding.slot });
++numShaderStorageBindings_;
}
}
}
}
void GLShaderBindingLayout::BindResourceSlots(GLuint program) const
{
std::size_t resourceIndex = 0;
/* Set uniform bindings */
for (std::uint8_t i = 0; i < numUniformBindings_; ++i)
{
const auto& resource = bindings_[resourceIndex++];
auto blockIndex = glGetUniformLocation(program, resource.name.c_str());
if (blockIndex != GL_INVALID_INDEX)
glUniform1i(blockIndex, static_cast<GLint>(resource.slot));
}
/* Set uniform-block bindings */
for (std::uint8_t i = 0; i < numUniformBlockBindings_; ++i)
{
const auto& resource = bindings_[resourceIndex++];
auto blockIndex = glGetUniformBlockIndex(program, resource.name.c_str());
if (blockIndex != GL_INVALID_INDEX)
glUniformBlockBinding(program, blockIndex, resource.slot);
}
/* Set shader-storage bindings */
#ifdef LLGL_GLEXT_SHADER_STORAGE_BUFFER_OBJECT
for (std::uint8_t i = 0; i < numShaderStorageBindings_; ++i)
{
const auto& resource = bindings_[resourceIndex++];
auto blockIndex = glGetProgramResourceIndex(program, GL_SHADER_STORAGE_BLOCK, resource.name.c_str());
if (blockIndex != GL_INVALID_INDEX)
glShaderStorageBlockBinding(program, blockIndex, resource.slot);
}
#endif
}
int GLShaderBindingLayout::CompareSWO(const GLShaderBindingLayout& rhs) const
{
const auto& lhs = *this;
for (std::size_t i = 0, n = bindings_.size(); i < n; ++i)
{
LLGL_COMPARE_MEMBER_SWO( bindings_[i].slot );
LLGL_COMPARE_MEMBER_SWO( bindings_[i].name );
}
return 0;
}
bool GLShaderBindingLayout::HasBindings() const
{
return ((numUniformBindings_ | numUniformBlockBindings_ | numShaderStorageBindings_) != 0);
}
} // /namespace LLGL
// ================================================================================
<commit_msg>Bug fix: "GLShaderBindingLayout::CompareSWO" function did not account for different number of bindings between compared objects.<commit_after>/*
* GLShaderBindingLayout.cpp
*
* This file is part of the "LLGL" project (Copyright (c) 2015-2019 by Lukas Hermanns)
* See "LICENSE.txt" for license information.
*/
#include "GLShaderBindingLayout.h"
#include "../Ext/GLExtensionRegistry.h"
#include "../Ext/GLExtensions.h"
#include "../../../Core/HelperMacros.h"
namespace LLGL
{
GLShaderBindingLayout::GLShaderBindingLayout(const GLPipelineLayout& pipelineLayout)
{
/* Gather all uniform bindings */
for (const auto& binding : pipelineLayout.GetBindings())
{
if (!binding.name.empty())
{
if (binding.type == ResourceType::Sampler || binding.type == ResourceType::Texture)
{
bindings_.push_back({ binding.name, binding.slot });
++numUniformBindings_;
}
}
}
/* Gather all uniform-block bindings */
for (const auto& binding : pipelineLayout.GetBindings())
{
if (!binding.name.empty())
{
if (binding.type == ResourceType::Buffer && (binding.bindFlags & BindFlags::ConstantBuffer) != 0)
{
bindings_.push_back({ binding.name, binding.slot });
++numUniformBlockBindings_;
}
}
}
/* Gather all shader-storage bindings */
for (const auto& binding : pipelineLayout.GetBindings())
{
if (!binding.name.empty())
{
if (binding.type == ResourceType::Buffer && (binding.bindFlags & (BindFlags::Storage | BindFlags::Sampled)) != 0)
{
bindings_.push_back({ binding.name, binding.slot });
++numShaderStorageBindings_;
}
}
}
}
void GLShaderBindingLayout::BindResourceSlots(GLuint program) const
{
std::size_t resourceIndex = 0;
/* Set uniform bindings */
for (std::uint8_t i = 0; i < numUniformBindings_; ++i)
{
const auto& resource = bindings_[resourceIndex++];
auto blockIndex = glGetUniformLocation(program, resource.name.c_str());
if (blockIndex != GL_INVALID_INDEX)
glUniform1i(blockIndex, static_cast<GLint>(resource.slot));
}
/* Set uniform-block bindings */
for (std::uint8_t i = 0; i < numUniformBlockBindings_; ++i)
{
const auto& resource = bindings_[resourceIndex++];
auto blockIndex = glGetUniformBlockIndex(program, resource.name.c_str());
if (blockIndex != GL_INVALID_INDEX)
glUniformBlockBinding(program, blockIndex, resource.slot);
}
/* Set shader-storage bindings */
#ifdef LLGL_GLEXT_SHADER_STORAGE_BUFFER_OBJECT
for (std::uint8_t i = 0; i < numShaderStorageBindings_; ++i)
{
const auto& resource = bindings_[resourceIndex++];
auto blockIndex = glGetProgramResourceIndex(program, GL_SHADER_STORAGE_BLOCK, resource.name.c_str());
if (blockIndex != GL_INVALID_INDEX)
glShaderStorageBlockBinding(program, blockIndex, resource.slot);
}
#endif
}
int GLShaderBindingLayout::CompareSWO(const GLShaderBindingLayout& rhs) const
{
const auto& lhs = *this;
/* Compare number of bindings first; if equal we can use one of the arrays only */
LLGL_COMPARE_MEMBER_SWO( bindings_.size() );
for (std::size_t i = 0, n = bindings_.size(); i < n; ++i)
{
LLGL_COMPARE_MEMBER_SWO( bindings_[i].slot );
LLGL_COMPARE_MEMBER_SWO( bindings_[i].name );
}
return 0;
}
bool GLShaderBindingLayout::HasBindings() const
{
return ((numUniformBindings_ | numUniformBlockBindings_ | numShaderStorageBindings_) != 0);
}
} // /namespace LLGL
// ================================================================================
<|endoftext|> |
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/nest/p9_mpipl_chip_cleanup.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2016 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file p9_mpipl_chip_cleanup.C
/// @brief To enable MCD recovery
///
// *HWP HWP OWNER: Joshua Hannan Email: [email protected]
// *HWP FW OWNER: Thi Tran Email: [email protected]
// *HWP Team: Nest
// *HWP Level: 2
// *HWP Consumed by: FSP/HB
//
// Additional Note(s):
//
// Checks to see if MCD recovery is already enabled by checking bit 0 of the
// even and odd MCD config registers, which is the recovery enable bit.
// If the bits are 0, then the procedure enables them to start MCD recovery
//
//
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// Includes
//------------------------------------------------------------------------------
#include <p9_mpipl_chip_cleanup.H>
#include <p9_misc_scom_addresses.H>
#include <p9_misc_scom_addresses_fld.H>
extern "C"
{
//------------------------------------------------------------------------------
// Function definitions
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// name: p9_mpipl_chip_cleanup
//------------------------------------------------------------------------------
// purpose:
// To enable MCD recovery
//
// Note: PHBs are left in ETU reset state after executing proc_mpipl_nest_cleanup, which runs before this procedure. PHYP releases PHBs from ETU reset post HostBoot IPL.
//
// SCOM regs
//
// 1) MCD even recovery control register
// PU_BANK0_MCD_REC (SCOM)
// bit 0 (PU_BANK0_MCD_REC_ENABLE): 0 to 1 transition needed to start, reset to 0 at end of request.
//
// 2) MCD odd recovery control register
// PU_MCD1_BANK0_MCD_REC (SCOM)
// bit 0 (PU_BANK0_MCD_REC_ENABLE): 0 to 1 transition needed to start, reset to 0 at end of request.
//
//------------------------------------------------------------------------------
fapi2::ReturnCode p9_mpipl_chip_cleanup(fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target)
{
const uint8_t MAX_MCD_DIRS = 2; //Max of 2 MCD Directories (even and odd)
fapi2::buffer<uint64_t> fsi_data[MAX_MCD_DIRS];
const uint64_t ARY_MCD_RECOVERY_CTRL_REGS_ADDRS[MAX_MCD_DIRS] =
{
PU_BANK0_MCD_REC, //MCD even recovery control register address
PU_MCD1_BANK0_MCD_REC //MCD odd recovery control register address
};
const char* ARY_MCD_DIR_STRS[MAX_MCD_DIRS] =
{
"Even", //Ptr to char string "Even" for even MCD
"Odd" //Ptr to char string "Odd" for odd MCD
};
//Verify MCD recovery was previously disabled for even and odd slices
//If not, this is an error condition
for (uint8_t counter = 0; counter < MAX_MCD_DIRS; counter++)
{
FAPI_DBG("Verifying MCD %s Recovery is disabled", ARY_MCD_DIR_STRS[counter]);
FAPI_TRY(fapi2::getScom(i_target, ARY_MCD_RECOVERY_CTRL_REGS_ADDRS[counter], fsi_data[counter]),
"getScom error veryfing that MCD recovery is disabled");
FAPI_ASSERT(!fsi_data[counter].getBit<PU_BANK0_MCD_REC_ENABLE>(),
fapi2::P9_MPIPL_CHIP_CLEANUP_MCD_NOT_DISABLED().set_TARGET(i_target).set_ADDRESS(
ARY_MCD_RECOVERY_CTRL_REGS_ADDRS[counter]).set_DATA(fsi_data[counter]), "MCD recovery not disabled as expected");
}
//Assert bit 0 of MCD Recovery Ctrl regs to enable MCD recovery
for (int counter = 0; counter < MAX_MCD_DIRS; counter++)
{
FAPI_DBG("Enabling MCD %s Recovery", ARY_MCD_DIR_STRS[counter]);
//Assert bit 0 of MCD Even or Odd Recovery Control reg to enable recovery
fsi_data[counter].setBit<PU_BANK0_MCD_REC_ENABLE>();
//Write data to MCD Even or Odd Recovery Control reg
FAPI_TRY(fapi2::putScom(i_target, ARY_MCD_RECOVERY_CTRL_REGS_ADDRS[counter], fsi_data[counter]),
"putScom error assert bit 0 of MCD recovery control register");
}
fapi_try_exit:
FAPI_DBG("Exiting...");
return fapi2::current_err;
}
} // extern "C"
<commit_msg>HW386071 defect workaround<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/nest/p9_mpipl_chip_cleanup.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2016 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file p9_mpipl_chip_cleanup.C
/// @brief To enable MCD recovery
///
// *HWP HWP OWNER: Joshua Hannan Email: [email protected]
// *HWP FW OWNER: Thi Tran Email: [email protected]
// *HWP Team: Nest
// *HWP Level: 2
// *HWP Consumed by: FSP/HB
//
// Additional Note(s):
//
// Checks to see if MCD recovery is already enabled by checking bit 0 of the
// even and odd MCD config registers, which is the recovery enable bit.
// If the bits are 0, then the procedure enables them to start MCD recovery
//
//
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// Includes
//------------------------------------------------------------------------------
#include <p9_mpipl_chip_cleanup.H>
#include <p9_misc_scom_addresses.H>
#include <p9_misc_scom_addresses_fld.H>
extern "C"
{
//------------------------------------------------------------------------------
// Function definitions
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// name: p9_mpipl_chip_cleanup
//------------------------------------------------------------------------------
// purpose:
// To enable MCD recovery
//
// Note: PHBs are left in ETU reset state after executing proc_mpipl_nest_cleanup, which runs before this procedure. PHYP releases PHBs from ETU reset post HostBoot IPL.
//
// SCOM regs
//
// 1) MCD even recovery control register
// PU_BANK0_MCD_REC (SCOM)
// bit 0 (PU_BANK0_MCD_REC_ENABLE): 0 to 1 transition needed to start, reset to 0 at end of request.
//
// 2) MCD odd recovery control register
// PU_MCD1_BANK0_MCD_REC (SCOM)
// bit 0 (PU_BANK0_MCD_REC_ENABLE): 0 to 1 transition needed to start, reset to 0 at end of request.
//
//------------------------------------------------------------------------------
fapi2::ReturnCode p9_mpipl_chip_cleanup(fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target)
{
const uint8_t MAX_MCD_DIRS = 2; //Max of 2 MCD Directories (even and odd)
fapi2::buffer<uint64_t> fsi_data[MAX_MCD_DIRS];
fapi2::buffer<uint64_t> w_data(0x00030001);
fapi2::buffer<uint64_t> r_data;
const uint64_t C_INT_VC_VSD_TABLE_DATA(0x5013202);
const uint64_t ARY_MCD_RECOVERY_CTRL_REGS_ADDRS[MAX_MCD_DIRS] =
{
PU_BANK0_MCD_REC, //MCD even recovery control register address
PU_MCD1_BANK0_MCD_REC //MCD odd recovery control register address
};
const char* ARY_MCD_DIR_STRS[MAX_MCD_DIRS] =
{
"Even", //Ptr to char string "Even" for even MCD
"Odd" //Ptr to char string "Odd" for odd MCD
};
// HW386071: INT unit has a defect that might result in fake ecc errors. Have to do these four writes and reads to scom registers
FAPI_TRY(fapi2::putScom(i_target, PU_INT_VC_VSD_TABLE_ADDR, w_data),
"putScom error selecting address 1");
FAPI_TRY(fapi2::getScom(i_target, C_INT_VC_VSD_TABLE_DATA, r_data),
"getScom error reading from address 1");
w_data.clearBit<63>();
FAPI_TRY(fapi2::putScom(i_target, PU_INT_VC_VSD_TABLE_ADDR, w_data),
"putScom error selecting address 0");
w_data.flush<0>();
FAPI_TRY(fapi2::putScom(i_target, C_INT_VC_VSD_TABLE_DATA, w_data),
"putScom error writing to address 0");
// HW386071
//Verify MCD recovery was previously disabled for even and odd slices
//If not, this is an error condition
for (uint8_t counter = 0; counter < MAX_MCD_DIRS; counter++)
{
FAPI_DBG("Verifying MCD %s Recovery is disabled", ARY_MCD_DIR_STRS[counter]);
FAPI_TRY(fapi2::getScom(i_target, ARY_MCD_RECOVERY_CTRL_REGS_ADDRS[counter], fsi_data[counter]),
"getScom error veryfing that MCD recovery is disabled");
FAPI_ASSERT(!fsi_data[counter].getBit<PU_BANK0_MCD_REC_ENABLE>(),
fapi2::P9_MPIPL_CHIP_CLEANUP_MCD_NOT_DISABLED().set_TARGET(i_target).set_ADDRESS(
ARY_MCD_RECOVERY_CTRL_REGS_ADDRS[counter]).set_DATA(fsi_data[counter]), "MCD recovery not disabled as expected");
}
//Assert bit 0 of MCD Recovery Ctrl regs to enable MCD recovery
for (int counter = 0; counter < MAX_MCD_DIRS; counter++)
{
FAPI_DBG("Enabling MCD %s Recovery", ARY_MCD_DIR_STRS[counter]);
//Assert bit 0 of MCD Even or Odd Recovery Control reg to enable recovery
fsi_data[counter].setBit<PU_BANK0_MCD_REC_ENABLE>();
//Write data to MCD Even or Odd Recovery Control reg
FAPI_TRY(fapi2::putScom(i_target, ARY_MCD_RECOVERY_CTRL_REGS_ADDRS[counter], fsi_data[counter]),
"putScom error assert bit 0 of MCD recovery control register");
}
fapi_try_exit:
FAPI_DBG("Exiting...");
return fapi2::current_err;
}
} // extern "C"
<|endoftext|> |
<commit_before>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h> /* low-level i/o */
#include <unistd.h>
#include <signal.h>
#include <errno.h>
#include <malloc.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/ioctl.h>
#include <linux/videodev2.h>
#include <pthread.h>
#include <semaphore.h>
#include <iostream>
#include <fstream>
#include <ctime>
#include <stdint.h>
#include "Palettes.h"
#include "SPI.h"
#include "Lepton_I2C.h"
#define PACKET_SIZE 164
#define PACKET_SIZE_UINT16 (PACKET_SIZE/2)
#define PACKETS_PER_FRAME 60
#define FRAME_SIZE_UINT16 (PACKET_SIZE_UINT16*PACKETS_PER_FRAME)
#define FPS 27;
static char const *v4l2dev = "/dev/video1";
static int v4l2sink = -1;
static int width = 80; //640; // Default for Flash
static int height = 60; //480; // Default for Flash
static char *vidsendbuf = NULL;
static int vidsendsiz = 0;
static int resets = 0;
static uint8_t result[PACKET_SIZE*PACKETS_PER_FRAME];
static uint16_t *frameBuffer;
static void init_device() {
SpiOpenPort(0);
}
static void grab_frame() {
resets = 0;
for (int j = 0; j < PACKETS_PER_FRAME; j++) {
read(spi_cs0_fd, result + sizeof(uint8_t) * PACKET_SIZE * j, sizeof(uint8_t) * PACKET_SIZE);
int packetNumber = result[j * PACKET_SIZE + 1];
if (packetNumber != j) {
j = -1;
resets += 1;
usleep(1000);
if (resets == 750) {
SpiClosePort(0);
usleep(750000);
SpiOpenPort(0);
}
}
}
if (resets >= 30) {
fprintf( stderr, "done reading, resets: \n" );
}
frameBuffer = (uint16_t *)result;
int row, column;
uint16_t value;
uint16_t minValue = 65535;
uint16_t maxValue = 0;
for (int i = 0; i < FRAME_SIZE_UINT16; i++) {
if (i % PACKET_SIZE_UINT16 < 2) {
continue;
}
int temp = result[i * 2];
result[i * 2] = result[i * 2 + 1];
result[i * 2 + 1] = temp;
value = frameBuffer[i];
if (value > maxValue) {
maxValue = value;
}
if (value < minValue) {
minValue = value;
}
column = i % PACKET_SIZE_UINT16 - 2;
row = i / PACKET_SIZE_UINT16;
}
float diff = maxValue - minValue;
float scale = 255 / diff;
memset(vidsendbuf, 0, 3);
memcpy(vidsendbuf + 3, vidsendbuf, vidsendsiz - 3);
for (int i = 0; i < FRAME_SIZE_UINT16; i++) {
if (i % PACKET_SIZE_UINT16 < 2) {
continue;
}
value = (frameBuffer[i] - minValue) * scale;
const int *colormap = colormap_ironblack;
column = (i % PACKET_SIZE_UINT16) - 2;
row = i / PACKET_SIZE_UINT16;
int idx = row * width * 3 + column * 3;
vidsendbuf[idx + 0] = colormap[3 * value];
vidsendbuf[idx + 1] = colormap[3 * value + 1];
vidsendbuf[idx + 2] = colormap[3 * value + 2];
}
/*
struct timespec ts;
clock_gettime(CLOCK_REALTIME, &ts);
memset( vidsendbuf, 0, 3);
memcpy( vidsendbuf+3, vidsendbuf, vidsendsiz-3 );
*/
}
static void stop_device() {
SpiClosePort(0);
}
static void open_vpipe()
{
v4l2sink = open(v4l2dev, O_WRONLY);
if (v4l2sink < 0) {
fprintf(stderr, "Failed to open v4l2sink device. (%s)\n", strerror(errno));
exit(-2);
}
// setup video for proper format
struct v4l2_format v;
int t;
v.type = V4L2_BUF_TYPE_VIDEO_OUTPUT;
t = ioctl(v4l2sink, VIDIOC_G_FMT, &v);
if( t < 0 )
exit(t);
v.fmt.pix.width = width;
v.fmt.pix.height = height;
v.fmt.pix.pixelformat = V4L2_PIX_FMT_RGB24;
vidsendsiz = width * height * 3;
v.fmt.pix.sizeimage = vidsendsiz;
t = ioctl(v4l2sink, VIDIOC_S_FMT, &v);
if( t < 0 )
exit(t);
vidsendbuf = (char*)malloc( vidsendsiz );
}
static pthread_t sender;
static sem_t lock1,lock2;
static void *sendvid(void *v)
{
(void)v;
for (;;) {
sem_wait(&lock1);
if (vidsendsiz != write(v4l2sink, vidsendbuf, vidsendsiz))
exit(-1);
sem_post(&lock2);
}
}
int main(int argc, char **argv)
{
struct timespec ts;
if( argc == 2 )
v4l2dev = argv[1];
open_vpipe();
// open and lock response
if (sem_init(&lock2, 0, 1) == -1)
exit(-1);
sem_wait(&lock2);
if (sem_init(&lock1, 0, 1) == -1)
exit(-1);
pthread_create(&sender, NULL, sendvid, NULL);
for (;;) {
// wait until a frame can be written
fprintf( stderr, "Waiting for sink\n" );
sem_wait(&lock2);
// setup source
init_device(); // open and setup SPI
for (;;) {
grab_frame();
// push it out
sem_post(&lock1);
clock_gettime(CLOCK_REALTIME, &ts);
ts.tv_sec += 2;
// wait for it to get written (or is blocking)
if (sem_timedwait(&lock2, &ts))
break;
}
stop_device(); // close SPI
}
close(v4l2sink);
return 0;
}
<commit_msg>Removed unneeded memcpy<commit_after>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h> /* low-level i/o */
#include <unistd.h>
#include <signal.h>
#include <errno.h>
#include <malloc.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/ioctl.h>
#include <linux/videodev2.h>
#include <pthread.h>
#include <semaphore.h>
#include <iostream>
#include <fstream>
#include <ctime>
#include <stdint.h>
#include "Palettes.h"
#include "SPI.h"
#include "Lepton_I2C.h"
#define PACKET_SIZE 164
#define PACKET_SIZE_UINT16 (PACKET_SIZE/2)
#define PACKETS_PER_FRAME 60
#define FRAME_SIZE_UINT16 (PACKET_SIZE_UINT16*PACKETS_PER_FRAME)
#define FPS 27;
static char const *v4l2dev = "/dev/video1";
static int v4l2sink = -1;
static int width = 80; //640; // Default for Flash
static int height = 60; //480; // Default for Flash
static char *vidsendbuf = NULL;
static int vidsendsiz = 0;
static int resets = 0;
static uint8_t result[PACKET_SIZE*PACKETS_PER_FRAME];
static uint16_t *frameBuffer;
static void init_device() {
SpiOpenPort(0);
}
static void grab_frame() {
resets = 0;
for (int j = 0; j < PACKETS_PER_FRAME; j++) {
read(spi_cs0_fd, result + sizeof(uint8_t) * PACKET_SIZE * j, sizeof(uint8_t) * PACKET_SIZE);
int packetNumber = result[j * PACKET_SIZE + 1];
if (packetNumber != j) {
j = -1;
resets += 1;
usleep(1000);
if (resets == 750) {
SpiClosePort(0);
usleep(750000);
SpiOpenPort(0);
}
}
}
if (resets >= 30) {
fprintf( stderr, "done reading, resets: \n" );
}
frameBuffer = (uint16_t *)result;
int row, column;
uint16_t value;
uint16_t minValue = 65535;
uint16_t maxValue = 0;
for (int i = 0; i < FRAME_SIZE_UINT16; i++) {
if (i % PACKET_SIZE_UINT16 < 2) {
continue;
}
int temp = result[i * 2];
result[i * 2] = result[i * 2 + 1];
result[i * 2 + 1] = temp;
value = frameBuffer[i];
if (value > maxValue) {
maxValue = value;
}
if (value < minValue) {
minValue = value;
}
column = i % PACKET_SIZE_UINT16 - 2;
row = i / PACKET_SIZE_UINT16;
}
float diff = maxValue - minValue;
float scale = 255 / diff;
for (int i = 0; i < FRAME_SIZE_UINT16; i++) {
if (i % PACKET_SIZE_UINT16 < 2) {
continue;
}
value = (frameBuffer[i] - minValue) * scale;
const int *colormap = colormap_ironblack;
column = (i % PACKET_SIZE_UINT16) - 2;
row = i / PACKET_SIZE_UINT16;
// Set video buffer pixel to scaled colormap value
int idx = row * width * 3 + column * 3;
vidsendbuf[idx + 0] = colormap[3 * value];
vidsendbuf[idx + 1] = colormap[3 * value + 1];
vidsendbuf[idx + 2] = colormap[3 * value + 2];
}
/*
struct timespec ts;
clock_gettime(CLOCK_REALTIME, &ts);
memset( vidsendbuf, 0, 3);
memcpy( vidsendbuf+3, vidsendbuf, vidsendsiz-3 );
*/
}
static void stop_device() {
SpiClosePort(0);
}
static void open_vpipe()
{
v4l2sink = open(v4l2dev, O_WRONLY);
if (v4l2sink < 0) {
fprintf(stderr, "Failed to open v4l2sink device. (%s)\n", strerror(errno));
exit(-2);
}
// setup video for proper format
struct v4l2_format v;
int t;
v.type = V4L2_BUF_TYPE_VIDEO_OUTPUT;
t = ioctl(v4l2sink, VIDIOC_G_FMT, &v);
if( t < 0 )
exit(t);
v.fmt.pix.width = width;
v.fmt.pix.height = height;
v.fmt.pix.pixelformat = V4L2_PIX_FMT_RGB24;
vidsendsiz = width * height * 3;
v.fmt.pix.sizeimage = vidsendsiz;
t = ioctl(v4l2sink, VIDIOC_S_FMT, &v);
if( t < 0 )
exit(t);
vidsendbuf = (char*)malloc( vidsendsiz );
}
static pthread_t sender;
static sem_t lock1,lock2;
static void *sendvid(void *v)
{
(void)v;
for (;;) {
sem_wait(&lock1);
if (vidsendsiz != write(v4l2sink, vidsendbuf, vidsendsiz))
exit(-1);
sem_post(&lock2);
}
}
int main(int argc, char **argv)
{
struct timespec ts;
if( argc == 2 )
v4l2dev = argv[1];
open_vpipe();
// open and lock response
if (sem_init(&lock2, 0, 1) == -1)
exit(-1);
sem_wait(&lock2);
if (sem_init(&lock1, 0, 1) == -1)
exit(-1);
pthread_create(&sender, NULL, sendvid, NULL);
for (;;) {
// wait until a frame can be written
fprintf( stderr, "Waiting for sink\n" );
sem_wait(&lock2);
// setup source
init_device(); // open and setup SPI
for (;;) {
grab_frame();
// push it out
sem_post(&lock1);
clock_gettime(CLOCK_REALTIME, &ts);
ts.tv_sec += 2;
// wait for it to get written (or is blocking)
if (sem_timedwait(&lock2, &ts))
break;
}
stop_device(); // close SPI
}
close(v4l2sink);
return 0;
}
<|endoftext|> |
<commit_before>/*
* Main.cpp
*
* Created on: Dec 31, 2014
* Author: jrparks
*/
#include "opencv2/objdetect/objdetect.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <iostream>
#include <stdio.h>
#include "C920Camera.h"
using namespace std;
using namespace cv;
int g_h_max = 197;
int g_h_min = 102;
int g_s_max = 255;
int g_s_min = 72;
int g_v_max = 208;
int g_v_min = 0;
int Brightness = 128,
Contrast = 128,
Saturation = 128,
Sharpness = 128,
Gain = 20,
Focus = 20,
BacklightCompensation = 20,
WhiteBalanceTemperature = 20;
v4l2::C920Camera camera;
cv::Mat frame;
int main(int argc, char* argv[]) {
fprintf(stdout, "Preparing to open camera.\n");
camera.Open("/dev/video1");
if (!camera.IsOpen()) {
fprintf(stderr, "Unable to open camera.\n");
return -1;
}
bool batch = false;
if ((argc > 1) && (strcmp(argv[1], "--batch") == 0))
batch = true;
char name[256];
int index = 0;
int rc;
struct stat statbuf;
do
{
sprintf(name, "cap%d.avi", index++);
rc = stat(name, &statbuf);
}
while (rc == 0);
fprintf (stderr, "Writing to %s\n", name);
camera.ChangeCaptureSize(v4l2::CAPTURE_SIZE_800x600);
camera.ChangeCaptureFPS(v4l2::CAPTURE_FPS_30);
camera.GetBrightness(Brightness);
camera.GetContrast(Contrast);
camera.GetSaturation(Saturation);
camera.GetSharpness(Sharpness);
camera.GetGain(Gain);
camera.GetBacklightCompensation(BacklightCompensation);
camera.GetWhiteBalanceTemperature(WhiteBalanceTemperature);
++WhiteBalanceTemperature;
#if 0
camera.GetFocus(Focus);
++Focus;
#endif
cv::namedWindow("Adjustments", CV_WINDOW_NORMAL);
cv::createTrackbar("Brightness", "Adjustments", &Brightness, 255);
cv::createTrackbar("Contrast", "Adjustments", &Contrast, 255);
cv::createTrackbar("Saturation", "Adjustments", &Saturation, 255);
cv::createTrackbar("Sharpness", "Adjustments", &Sharpness, 255);
cv::createTrackbar("Gain", "Adjustments", &Gain, 255);
cv::createTrackbar("Backlight Compensation", "Adjustments", &BacklightCompensation, 1);
// Off by one to account for -1 being auto.
cv::createTrackbar("White Balance Temperature", "Adjustments", &WhiteBalanceTemperature, 6501);
cv::createTrackbar("Focus", "Adjustments", &Focus, 256);
cv::createTrackbar("Auto Exposure", "Adjustments", &AutoExposure, 3);
camera.GrabFrame();
camera.RetrieveMat(frame);
VideoWriter outputVideo(name, CV_FOURCC('M','J','P','G'), 30, Size(frame.cols, frame.rows), true);
int wait_key = 0;
while (true) {
camera.SetBrightness(Brightness);
camera.SetContrast(Contrast);
camera.SetSaturation(Saturation);
camera.SetSharpness(Sharpness);
camera.SetGain(Gain);
camera.SetBacklightCompensation(BacklightCompensation);
--WhiteBalanceTemperature;
camera.SetWhiteBalanceTemperature(WhiteBalanceTemperature);
++WhiteBalanceTemperature;
--Focus;
camera.SetFocus(Focus);
++Focus;
camera.SetAutoExposure(AutoExposure)
if (camera.GrabFrame() && camera.RetrieveMat(frame))
{
outputVideo << frame;
if (!batch)
imshow( "Detect", frame);
Mat btrack;
inRange(frame, Scalar(g_h_min, g_s_min, g_v_min), Scalar(g_h_max, g_s_max, g_v_max), btrack);
Mat element= getStructuringElement(MORPH_RECT, Size(5, 5), Point(2, 2));
dilate(btrack, btrack, element);
imshow("Tracking", btrack);
} else {
fprintf(stderr, "Unable to grab frame from camera.\n");
}
if (!batch)
{
wait_key = cv::waitKey(1);
if (wait_key == 27 || wait_key == 32)
break;
}
}
fprintf(stdout, "Closing camera.\n");
camera.Close();
}
<commit_msg>Use callbacks for controls rather than setting all the params every frame<commit_after>/*
* Main.cpp
*
* Created on: Dec 31, 2014
* Author: jrparks
*/
#include "opencv2/objdetect/objdetect.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <iostream>
#include <stdio.h>
#include "C920Camera.h"
using namespace std;
using namespace cv;
int g_h_max = 197;
int g_h_min = 102;
int g_s_max = 255;
int g_s_min = 72;
int g_v_max = 208;
int g_v_min = 0;
int Brightness = 128,
Contrast = 128,
Saturation = 128,
Sharpness = 128,
Gain = 20,
Focus = 20,
BacklightCompensation = 20,
WhiteBalanceTemperature = 20,
AutoExposure = 1;
v4l2::C920Camera camera(0);
void brightnessCallback(int value, void *data)
{
Brightness = value;
camera.SetBrightness(value);
}
void contrastCallback(int value, void *data)
{
Contrast = value;
camera.SetContrast(value);
}
void saturationCallback(int value, void *data)
{
Saturation = value;
camera.SetSaturation(value);
}
void sharpnessCallback(int value, void *data)
{
Sharpness = value;
camera.SetSharpness(value);
}
void gainCallback(int value, void *data)
{
Gain = value;
camera.SetGain(value);
}
void autoExposureCallback(int value, void *data)
{
AutoExposure = value;
camera.SetAutoExposure(value);
}
void backlightCompensationCallback(int value, void *data)
{
BacklightCompensation = value;
camera.SetBacklightCompensation(value);
}
void whiteBalanceTemperatureCallback(int value, void *data)
{
WhiteBalanceTemperature = value;
// Off by one to account for -1 being auto.
camera.SetWhiteBalanceTemperature(value-1);
}
void focusCallback(int value, void *data)
{
Focus = value;
// Off by one to account for -1 being auto.
camera.SetFocus(value-1);
}
int main(int argc, char* argv[]) {
if (!camera.IsOpen()) {
fprintf(stderr, "Unable to open camera.\n");
return -1;
}
bool batch = false;
if ((argc > 1) && (strcmp(argv[1], "--batch") == 0))
batch = true;
char name[PATH_MAX];
int index = 0;
int rc;
struct stat statbuf;
do
{
sprintf(name, "cap%d.avi", index++);
rc = stat(name, &statbuf);
}
while (rc == 0);
fprintf (stderr, "Writing to %s\n", name);
camera.ChangeCaptureSize(v4l2::CAPTURE_SIZE_800x600);
camera.ChangeCaptureFPS(v4l2::CAPTURE_FPS_30);
camera.GetBrightness(Brightness);
camera.GetContrast(Contrast);
camera.GetSaturation(Saturation);
camera.GetSharpness(Sharpness);
camera.GetGain(Gain);
camera.GetBacklightCompensation(BacklightCompensation);
camera.GetWhiteBalanceTemperature(WhiteBalanceTemperature);
++WhiteBalanceTemperature; // Off by 1 since -1 is auto
// Set auto-focus off on startup
focusCallback(20, NULL);
autoExposureCallback(1, NULL);
cv::namedWindow("Adjustments", CV_WINDOW_NORMAL);
cv::createTrackbar("Brightness", "Adjustments", &Brightness, 255, brightnessCallback);
cv::createTrackbar("Contrast", "Adjustments", &Contrast, 255, contrastCallback);
cv::createTrackbar("Saturation", "Adjustments", &Saturation, 255, saturationCallback);
cv::createTrackbar("Sharpness", "Adjustments", &Sharpness, 255, sharpnessCallback);
cv::createTrackbar("Gain", "Adjustments", &Gain, 255, gainCallback);
cv::createTrackbar("Backlight Compensation", "Adjustments", &BacklightCompensation, 1, backlightCompensationCallback);
// Off by one to account for -1 being auto.
cv::createTrackbar("White Balance Temperature", "Adjustments", &WhiteBalanceTemperature, 6501, whiteBalanceTemperatureCallback);
cv::createTrackbar("Focus", "Adjustments", &Focus, 256, focusCallback);
cv::createTrackbar("Auto Exposure", "Adjustments", &AutoExposure, 3, autoExposureCallback);
cv::Mat frame;
camera.GrabFrame();
camera.RetrieveMat(frame);
VideoWriter outputVideo(name, CV_FOURCC('M','J','P','G'), 30, Size(frame.cols, frame.rows), true);
while (true)
{
if (camera.GrabFrame() && camera.RetrieveMat(frame))
{
outputVideo << frame;
if (!batch)
{
imshow( "Detect", frame);
Mat btrack;
inRange(frame, Scalar(g_h_min, g_s_min, g_v_min), Scalar(g_h_max, g_s_max, g_v_max), btrack);
Mat element = getStructuringElement(MORPH_RECT, Size(5, 5), Point(2, 2));
dilate(btrack, btrack, element);
imshow("Tracking", btrack);
}
}
else
{
fprintf(stderr, "Unable to grab frame from camera.\n");
break;
}
if (!batch)
{
int wait_key = cv::waitKey(5);
if (wait_key == 27 || wait_key == 32)
break;
}
}
fprintf(stdout, "Closing camera.\n");
camera.Close();
}
<|endoftext|> |
<commit_before>/*
Qt4xHb - Bindings libraries for Harbour/xHarbour and Qt Framework 4
Copyright (C) 2020 Marcos Antonio Gambeta <marcosgambeta AT outlook DOT com>
*/
/*
DO NOT EDIT THIS FILE - the content was created using a source code generator
*/
#include "QSvgRendererSlots.h"
QSvgRendererSlots::QSvgRendererSlots(QObject *parent) : QObject(parent)
{
}
QSvgRendererSlots::~QSvgRendererSlots()
{
}
void QSvgRendererSlots::repaintNeeded()
{
QObject *object = qobject_cast<QObject *>(sender());
PHB_ITEM cb = Signals_return_codeblock( object, "repaintNeeded()" );
if( cb )
{
PHB_ITEM psender = Signals_return_qobject ( (QObject *) object, "QSVGRENDERER" );
hb_vmEvalBlockV( (PHB_ITEM) cb, 1, psender );
hb_itemRelease( psender );
}
}
void QSvgRendererSlots_connect_signal ( const QString & signal, const QString & slot )
{
QSvgRenderer * obj = (QSvgRenderer *) hb_itemGetPtr( hb_objSendMsg( hb_stackSelfItem(), "POINTER", 0 ) );
if( obj )
{
QSvgRendererSlots * s = QCoreApplication::instance()->findChild<QSvgRendererSlots *>();
if( s == NULL )
{
s = new QSvgRendererSlots();
s->moveToThread( QCoreApplication::instance()->thread() );
s->setParent( QCoreApplication::instance() );
}
hb_retl( Signals_connection_disconnection( s, signal, slot ) );
}
else
{
hb_retl( false );
}
}
<commit_msg>source/QtSvg: updated<commit_after>/*
Qt4xHb - Bindings libraries for Harbour/xHarbour and Qt Framework 4
Copyright (C) 2020 Marcos Antonio Gambeta <marcosgambeta AT outlook DOT com>
*/
/*
DO NOT EDIT THIS FILE - the content was created using a source code generator
*/
#include "QSvgRendererSlots.h"
QSvgRendererSlots::QSvgRendererSlots(QObject *parent) : QObject(parent)
{
}
QSvgRendererSlots::~QSvgRendererSlots()
{
}
void QSvgRendererSlots::repaintNeeded()
{
QObject *object = qobject_cast<QObject *>(sender());
PHB_ITEM cb = Signals_return_codeblock( object, "repaintNeeded()" );
if( cb )
{
PHB_ITEM psender = Signals_return_qobject ( (QObject *) object, "QSVGRENDERER" );
hb_vmEvalBlockV( cb, 1, psender );
hb_itemRelease( psender );
}
}
void QSvgRendererSlots_connect_signal ( const QString & signal, const QString & slot )
{
QSvgRenderer * obj = (QSvgRenderer *) hb_itemGetPtr( hb_objSendMsg( hb_stackSelfItem(), "POINTER", 0 ) );
if( obj )
{
QSvgRendererSlots * s = QCoreApplication::instance()->findChild<QSvgRendererSlots *>();
if( s == NULL )
{
s = new QSvgRendererSlots();
s->moveToThread( QCoreApplication::instance()->thread() );
s->setParent( QCoreApplication::instance() );
}
hb_retl( Signals_connection_disconnection( s, signal, slot ) );
}
else
{
hb_retl( false );
}
}
<|endoftext|> |
<commit_before>/**
* \file
* \brief Semaphore class header
*
* \author Copyright (C) 2014 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
*
* \par License
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
* distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* \date 2014-11-18
*/
#ifndef INCLUDE_DISTORTOS_SEMAPHORE_HPP_
#define INCLUDE_DISTORTOS_SEMAPHORE_HPP_
#include "distortos/scheduler/ThreadControlBlockList.hpp"
namespace distortos
{
/**
* \brief Semaphore is the basic synchronization primitive
*
* Similar to POSIX semaphores - http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_16
*/
class Semaphore
{
public:
/**
* \brief Semaphore constructor
*
* Similar to sem_init() - http://pubs.opengroup.org/onlinepubs/9699919799/functions/sem_init.html#
*
* \param [in] value is the initial value of the semaphore
*/
Semaphore(int value);
/**
* \brief Semaphore destructor
*
* Similar to sem_destroy() - http://pubs.opengroup.org/onlinepubs/9699919799/functions/sem_destroy.html#
*
* It is safe to destroy a semaphore upon which no threads are currently blocked. The effect of destroying a
* semaphore upon which other threads are currently blocked is system error.
*/
~Semaphore();
/**
* \brief Gets current value of semaphore.
*
* Similar to sem_getvalue() - http://pubs.opengroup.org/onlinepubs/9699919799/functions/sem_getvalue.html#
*
* \return current value of semaphore, positive value if semaphore is not locked, negative value or zero otherwise;
* negative value represents the number of threads waiting on this semaphore
*/
int getValue() const
{
return value_;
}
/**
* \brief Unlocks the semaphore.
*
* Similar to sem_post() - http://pubs.opengroup.org/onlinepubs/9699919799/functions/sem_post.html#
*
* This function shall unlock the semaphore by performing a semaphore unlock operation. If the semaphore value
* resulting from this operation is positive, then no threads were blocked waiting for the semaphore to become
* unlocked; the semaphore value is simply incremented. Otherwise one of the threads blocked waiting for the
* semaphore shall be allowed to return successfully from its call to lock() - the highest priority waiting thread
* shall be unblocked, and if there is more than one highest priority thread blocked waiting for the semaphore, then
* the highest priority thread that has been waiting the longest shall be unblocked.
*/
void post();
/**
* \brief Tries to lock the semaphore.
*
* Similar to sem_trywait() - http://pubs.opengroup.org/onlinepubs/9699919799/functions/sem_trywait.html#
*
* This function shall lock the semaphore only if the semaphore is currently not locked; that is, if the semaphore
* value is currently positive. Otherwise, it shall not lock the semaphore. Upon successful return, the state of the
* semaphore shall be locked and shall remain locked until unlock() function is executed.
*
* \return zero if the calling process successfully performed the semaphore lock operation, error code otherwise:
* - EAGAIN - semaphore was already locked, so it cannot be immediately locked by the tryWait() operation,
* - EDEADLK - a deadlock condition was detected,
* - EINTR - a signal interrupted this function;
*/
int tryWait();
/**
* \brief Locks the semaphore.
*
* Similar to sem_wait() - http://pubs.opengroup.org/onlinepubs/9699919799/functions/sem_trywait.html#
*
* This function shall lock the semaphore by performing a semaphore lock operation on that semaphore. If the
* semaphore value is currently zero, then the calling thread shall not return from the call to lock() until it
* either locks the semaphore or the call is interrupted by a signal. Upon successful return, the state of the
* semaphore shall be locked and shall remain locked until unlock() function is executed.
*
* \return zero if the calling process successfully performed the semaphore lock operation, error code otherwise:
* - EDEADLK - a deadlock condition was detected,
* - EINTR - a signal interrupted this function;
*/
int wait();
private:
/// ThreadControlBlock objects blocked on this semaphore
scheduler::ThreadControlBlockList blockedList_;
/// internal value of the semaphore
int value_;
};
} // namespace distortos
#endif // INCLUDE_DISTORTOS_SEMAPHORE_HPP_
<commit_msg>Semaphore: make constructor explicit<commit_after>/**
* \file
* \brief Semaphore class header
*
* \author Copyright (C) 2014 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
*
* \par License
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
* distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* \date 2014-11-18
*/
#ifndef INCLUDE_DISTORTOS_SEMAPHORE_HPP_
#define INCLUDE_DISTORTOS_SEMAPHORE_HPP_
#include "distortos/scheduler/ThreadControlBlockList.hpp"
namespace distortos
{
/**
* \brief Semaphore is the basic synchronization primitive
*
* Similar to POSIX semaphores - http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_16
*/
class Semaphore
{
public:
/**
* \brief Semaphore constructor
*
* Similar to sem_init() - http://pubs.opengroup.org/onlinepubs/9699919799/functions/sem_init.html#
*
* \param [in] value is the initial value of the semaphore
*/
explicit Semaphore(int value);
/**
* \brief Semaphore destructor
*
* Similar to sem_destroy() - http://pubs.opengroup.org/onlinepubs/9699919799/functions/sem_destroy.html#
*
* It is safe to destroy a semaphore upon which no threads are currently blocked. The effect of destroying a
* semaphore upon which other threads are currently blocked is system error.
*/
~Semaphore();
/**
* \brief Gets current value of semaphore.
*
* Similar to sem_getvalue() - http://pubs.opengroup.org/onlinepubs/9699919799/functions/sem_getvalue.html#
*
* \return current value of semaphore, positive value if semaphore is not locked, negative value or zero otherwise;
* negative value represents the number of threads waiting on this semaphore
*/
int getValue() const
{
return value_;
}
/**
* \brief Unlocks the semaphore.
*
* Similar to sem_post() - http://pubs.opengroup.org/onlinepubs/9699919799/functions/sem_post.html#
*
* This function shall unlock the semaphore by performing a semaphore unlock operation. If the semaphore value
* resulting from this operation is positive, then no threads were blocked waiting for the semaphore to become
* unlocked; the semaphore value is simply incremented. Otherwise one of the threads blocked waiting for the
* semaphore shall be allowed to return successfully from its call to lock() - the highest priority waiting thread
* shall be unblocked, and if there is more than one highest priority thread blocked waiting for the semaphore, then
* the highest priority thread that has been waiting the longest shall be unblocked.
*/
void post();
/**
* \brief Tries to lock the semaphore.
*
* Similar to sem_trywait() - http://pubs.opengroup.org/onlinepubs/9699919799/functions/sem_trywait.html#
*
* This function shall lock the semaphore only if the semaphore is currently not locked; that is, if the semaphore
* value is currently positive. Otherwise, it shall not lock the semaphore. Upon successful return, the state of the
* semaphore shall be locked and shall remain locked until unlock() function is executed.
*
* \return zero if the calling process successfully performed the semaphore lock operation, error code otherwise:
* - EAGAIN - semaphore was already locked, so it cannot be immediately locked by the tryWait() operation,
* - EDEADLK - a deadlock condition was detected,
* - EINTR - a signal interrupted this function;
*/
int tryWait();
/**
* \brief Locks the semaphore.
*
* Similar to sem_wait() - http://pubs.opengroup.org/onlinepubs/9699919799/functions/sem_trywait.html#
*
* This function shall lock the semaphore by performing a semaphore lock operation on that semaphore. If the
* semaphore value is currently zero, then the calling thread shall not return from the call to lock() until it
* either locks the semaphore or the call is interrupted by a signal. Upon successful return, the state of the
* semaphore shall be locked and shall remain locked until unlock() function is executed.
*
* \return zero if the calling process successfully performed the semaphore lock operation, error code otherwise:
* - EDEADLK - a deadlock condition was detected,
* - EINTR - a signal interrupted this function;
*/
int wait();
private:
/// ThreadControlBlock objects blocked on this semaphore
scheduler::ThreadControlBlockList blockedList_;
/// internal value of the semaphore
int value_;
};
} // namespace distortos
#endif // INCLUDE_DISTORTOS_SEMAPHORE_HPP_
<|endoftext|> |
<commit_before>#ifndef __NBA_CONFIG_HH__
#define __NBA_CONFIG_HH__
#include <unordered_map>
#include <vector>
#include <string>
#define NBA_MAX_NODES (2)
#define NBA_MAX_CORES (64)
#define NBA_MAX_PORTS (16)
#define NBA_MAX_QUEUES_PER_PORT (128)
#define NBA_MAX_COPROCESSORS (2) // Max number of coprocessor devices
#define NBA_MAX_PROCESSOR_TYPES (2) // Max number of device types (current: CPU and GPU)
#define NBA_BATCHING_TRADITIONAL (0)
#define NBA_BATCHING_CONTINUOUS (1)
#define NBA_BATCHING_BITVECTOR (2)
#define NBA_BATCHING_LINKEDLIST (3)
#define NBA_BATCHING_SCHEME NBA_BATCHING_LINKEDLIST
#define NBA_MAX_PACKET_SIZE (2048)
#ifdef NBA_NO_HUGE
#define NBA_MAX_IO_BATCH_SIZE (4u)
#define NBA_MAX_COMP_BATCH_SIZE (4u)
#else
#if NBA_BATCHING_SCHEME == NBA_BATCHING_BITVECTOR
#define NBA_MAX_IO_BATCH_SIZE (64u)
#define NBA_MAX_COMP_BATCH_SIZE (64u)
#else
#define NBA_MAX_IO_BATCH_SIZE (256u)
#define NBA_MAX_COMP_BATCH_SIZE (256u)
#endif
#endif
#define NBA_MAX_COMP_PREPKTQ_LENGTH (256u)
#if defined(NBA_PMD_MLX4) || defined(NBA_PMD_MLNX_UIO)
#define NBA_MAX_IO_DESC_PER_HWRXQ (8192)
#define NBA_MAX_IO_DESC_PER_HWTXQ (8192)
#else
#define NBA_MAX_IO_DESC_PER_HWRXQ (1024)
#define NBA_MAX_IO_DESC_PER_HWTXQ (1024)
#endif
#define NBA_MAX_COPROC_PPDEPTH (64u)
#define NBA_MAX_COPROC_INPUTQ_LENGTH (64)
#define NBA_MAX_COPROC_COMPLETIONQ_LENGTH (64)
#define NBA_MAX_COPROC_CTX_PER_COMPTHREAD (1)
#define NBA_MAX_TASKPOOL_SIZE (2048u)
#define NBA_MAX_BATCHPOOL_SIZE (2048u)
#define NBA_MAX_ANNOTATION_SET_SIZE (7)
#define NBA_MAX_NODELOCALSTORAGE_ENTRIES (16)
#define NBA_MAX_KERNEL_OVERLAP (8)
#define NBA_MAX_DATABLOCKS (12) // If too large (e.g., 64), batch_pool can not be allocated.
#define NBA_OQ (true) // Use output-queuing semantics when possible.
#undef NBA_CPU_MICROBENCH // Enable support for PAPI library for microbenchmarks.
/* If you change below, update HANDLE_ALL_PORTS macro in lib/element.hh as well!! */
#define NBA_MAX_ELEM_NEXTS (4)
namespace nba {
enum io_thread_mode {
IO_NORMAL = 0,
IO_ECHOBACK = 1,
IO_RR = 2,
IO_RXONLY = 3,
IO_EMUL = 4,
};
enum queue_template {
SWRXQ = 0,
TASKINQ = 1,
TASKOUTQ = 2,
};
struct hwrxq {
int ifindex;
int qidx;
};
struct io_thread_conf {
int core_id;
std::vector<struct hwrxq> attached_rxqs;
int mode;
int swrxq_idx;
void *priv;
};
struct comp_thread_conf {
int core_id;
int swrxq_idx;
int taskinq_idx;
int taskoutq_idx;
void *priv;
};
struct coproc_thread_conf {
int core_id;
int device_id;
int taskinq_idx;
int taskoutq_idx;
void *priv;
};
struct queue_conf {
int node_id;
enum queue_template template_;
bool mp_enq;
bool mc_deq;
void *priv;
};
extern std::unordered_map<std::string, long> system_params;
extern std::vector<struct io_thread_conf> io_thread_confs;
extern std::vector<struct comp_thread_conf> comp_thread_confs;
extern std::vector<struct coproc_thread_conf> coproc_thread_confs;
extern std::vector<struct queue_conf> queue_confs;
/* queue_idx_map is used to find the appropriate queue instance by
* the initialization code of io/comp/coproc threads. */
extern std::unordered_map<void*, int> queue_idx_map;
extern bool dummy_device;
extern bool emulate_io;
extern int emulated_packet_size;
extern int emulated_ip_version;
extern int emulated_num_fixed_flows;
extern size_t num_emulated_ifaces;
bool load_config(const char* pyfilename);
int get_ht_degree(void);
}
#undef HAVE_PSIO
/* For microbenchmarks (see lib/io.cc) */
//#define TEST_MINIMAL_L2FWD
//#define TEST_RXONLY
/* Inserts forced sleep when there is no packets received,
* to reduce PCIe traffic. The performance may increase or decrease
* depending on the system configuration.
* (see lib/io.cc)
*/
//#define NBA_SLEEPY_IO
#endif
// vim: ts=8 sts=4 sw=4 et
<commit_msg>Change the default batching scheme to bitvector.<commit_after>#ifndef __NBA_CONFIG_HH__
#define __NBA_CONFIG_HH__
#include <unordered_map>
#include <vector>
#include <string>
#define NBA_MAX_NODES (2)
#define NBA_MAX_CORES (64)
#define NBA_MAX_PORTS (16)
#define NBA_MAX_QUEUES_PER_PORT (128)
#define NBA_MAX_COPROCESSORS (2) // Max number of coprocessor devices
#define NBA_MAX_PROCESSOR_TYPES (2) // Max number of device types (current: CPU and GPU)
#define NBA_BATCHING_TRADITIONAL (0)
#define NBA_BATCHING_CONTINUOUS (1)
#define NBA_BATCHING_BITVECTOR (2)
#define NBA_BATCHING_LINKEDLIST (3)
#define NBA_BATCHING_SCHEME NBA_BATCHING_BITVECTOR
#define NBA_MAX_PACKET_SIZE (2048)
#ifdef NBA_NO_HUGE
#define NBA_MAX_IO_BATCH_SIZE (4u)
#define NBA_MAX_COMP_BATCH_SIZE (4u)
#else
#if NBA_BATCHING_SCHEME == NBA_BATCHING_BITVECTOR
#define NBA_MAX_IO_BATCH_SIZE (64u)
#define NBA_MAX_COMP_BATCH_SIZE (64u)
#else
#define NBA_MAX_IO_BATCH_SIZE (256u)
#define NBA_MAX_COMP_BATCH_SIZE (256u)
#endif
#endif
#define NBA_MAX_COMP_PREPKTQ_LENGTH (256u)
#if defined(NBA_PMD_MLX4) || defined(NBA_PMD_MLNX_UIO)
#define NBA_MAX_IO_DESC_PER_HWRXQ (8192)
#define NBA_MAX_IO_DESC_PER_HWTXQ (8192)
#else
#define NBA_MAX_IO_DESC_PER_HWRXQ (1024)
#define NBA_MAX_IO_DESC_PER_HWTXQ (1024)
#endif
#define NBA_MAX_COPROC_PPDEPTH (64u)
#define NBA_MAX_COPROC_INPUTQ_LENGTH (64)
#define NBA_MAX_COPROC_COMPLETIONQ_LENGTH (64)
#define NBA_MAX_COPROC_CTX_PER_COMPTHREAD (1)
#define NBA_MAX_TASKPOOL_SIZE (2048u)
#define NBA_MAX_BATCHPOOL_SIZE (2048u)
#define NBA_MAX_ANNOTATION_SET_SIZE (7)
#define NBA_MAX_NODELOCALSTORAGE_ENTRIES (16)
#define NBA_MAX_KERNEL_OVERLAP (8)
#define NBA_MAX_DATABLOCKS (12) // If too large (e.g., 64), batch_pool can not be allocated.
#define NBA_OQ (true) // Use output-queuing semantics when possible.
#undef NBA_CPU_MICROBENCH // Enable support for PAPI library for microbenchmarks.
/* If you change below, update HANDLE_ALL_PORTS macro in lib/element.hh as well!! */
#define NBA_MAX_ELEM_NEXTS (4)
namespace nba {
enum io_thread_mode {
IO_NORMAL = 0,
IO_ECHOBACK = 1,
IO_RR = 2,
IO_RXONLY = 3,
IO_EMUL = 4,
};
enum queue_template {
SWRXQ = 0,
TASKINQ = 1,
TASKOUTQ = 2,
};
struct hwrxq {
int ifindex;
int qidx;
};
struct io_thread_conf {
int core_id;
std::vector<struct hwrxq> attached_rxqs;
int mode;
int swrxq_idx;
void *priv;
};
struct comp_thread_conf {
int core_id;
int swrxq_idx;
int taskinq_idx;
int taskoutq_idx;
void *priv;
};
struct coproc_thread_conf {
int core_id;
int device_id;
int taskinq_idx;
int taskoutq_idx;
void *priv;
};
struct queue_conf {
int node_id;
enum queue_template template_;
bool mp_enq;
bool mc_deq;
void *priv;
};
extern std::unordered_map<std::string, long> system_params;
extern std::vector<struct io_thread_conf> io_thread_confs;
extern std::vector<struct comp_thread_conf> comp_thread_confs;
extern std::vector<struct coproc_thread_conf> coproc_thread_confs;
extern std::vector<struct queue_conf> queue_confs;
/* queue_idx_map is used to find the appropriate queue instance by
* the initialization code of io/comp/coproc threads. */
extern std::unordered_map<void*, int> queue_idx_map;
extern bool dummy_device;
extern bool emulate_io;
extern int emulated_packet_size;
extern int emulated_ip_version;
extern int emulated_num_fixed_flows;
extern size_t num_emulated_ifaces;
bool load_config(const char* pyfilename);
int get_ht_degree(void);
}
#undef HAVE_PSIO
/* For microbenchmarks (see lib/io.cc) */
//#define TEST_MINIMAL_L2FWD
//#define TEST_RXONLY
/* Inserts forced sleep when there is no packets received,
* to reduce PCIe traffic. The performance may increase or decrease
* depending on the system configuration.
* (see lib/io.cc)
*/
//#define NBA_SLEEPY_IO
#endif
// vim: ts=8 sts=4 sw=4 et
<|endoftext|> |
<commit_before>/*
* Software License Agreement (BSD License)
*
* Point Cloud Library (PCL) - www.pointclouds.org
* Copyright (c) 2010-2011, Willow Garage, Inc.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* $Id$
*
*/
#include <gtest/gtest.h>
#include <pcl/point_types.h>
#include <pcl/point_cloud.h>
#include <pcl/pcl_tests.h>
using namespace pcl;
using namespace pcl::test;
PointCloud<PointXYZ> cloud;
const size_t size = 10 * 480;
TEST (PointCloud, size)
{
EXPECT_EQ(cloud.points.size (), cloud.size ());
}
TEST (PointCloud, sq_brackets_wrapper)
{
for (uint32_t i = 0; i < size; ++i)
EXPECT_EQ_VECTORS (cloud.points[i].getVector3fMap (),
cloud[i].getVector3fMap ());
}
TEST (PointCloud, at)
{
for (uint32_t i = 0; i < size; ++i)
EXPECT_EQ_VECTORS (cloud.points.at (i).getVector3fMap (),
cloud.at (i).getVector3fMap ());
}
TEST (PointCloud, front)
{
EXPECT_EQ_VECTORS (cloud.points.front ().getVector3fMap (),
cloud.front ().getVector3fMap ());
}
TEST (PointCloud, back)
{
EXPECT_EQ_VECTORS (cloud.points.back ().getVector3fMap (),
cloud.back ().getVector3fMap ());
}
TEST (PointCloud, constructor_with_allocation)
{
PointCloud<PointXYZ> cloud2 (5, 80);
EXPECT_EQ (cloud2.width, 5);
EXPECT_EQ (cloud2.height, 80);
EXPECT_EQ (cloud2.size (), 5*80);
}
TEST (PointCloud, iterators)
{
EXPECT_EQ_VECTORS (cloud.begin ()->getVector3fMap (),
cloud.points.begin ()->getVector3fMap ());
EXPECT_EQ_VECTORS (cloud.end ()->getVector3fMap (),
cloud.points.end ()->getVector3fMap ());
PointCloud<PointXYZ>::const_iterator pit = cloud.begin ();
PointCloud<PointXYZ>::VectorType::const_iterator pit2 = cloud.points.begin ();
for (; pit < cloud.end (); ++pit2, ++pit)
EXPECT_EQ_VECTORS (pit->getVector3fMap (), pit2->getVector3fMap ());
}
TEST (PointCloud, insert_range)
{
PointCloud<PointXYZ> cloud2 (10, 1);
for (uint32_t i = 0; i < 10; ++i)
cloud2[i] = PointXYZ (5*i+0,5*i+1,5*i+2);
uint32_t old_size = cloud.size ();
cloud.insert (cloud.begin (), cloud2.begin (), cloud2.end ());
EXPECT_EQ (cloud.width, cloud.size ());
EXPECT_EQ (cloud.height, 1);
EXPECT_EQ (cloud.width, old_size + cloud2.size ());
PointCloud<PointXYZ>::const_iterator pit = cloud.begin ();
PointCloud<PointXYZ>::const_iterator pit2 = cloud2.begin ();
for (; pit2 < cloud2.end (); ++pit2, ++pit)
EXPECT_EQ_VECTORS (pit->getVector3fMap (), pit2->getVector3fMap ());
}
int
main (int argc, char** argv)
{
cloud.width = 10;
cloud.height = 480;
for (uint32_t i = 0; i < size; ++i)
cloud.points.push_back (PointXYZ (3*i+0,3*i+1,3*i+2));
testing::InitGoogleTest (&argc, argv);
return (RUN_ALL_TESTS ());
}
<commit_msg>nm remove extra line break<commit_after>/*
* Software License Agreement (BSD License)
*
* Point Cloud Library (PCL) - www.pointclouds.org
* Copyright (c) 2010-2011, Willow Garage, Inc.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* $Id$
*
*/
#include <gtest/gtest.h>
#include <pcl/point_types.h>
#include <pcl/point_cloud.h>
#include <pcl/pcl_tests.h>
using namespace pcl;
using namespace pcl::test;
PointCloud<PointXYZ> cloud;
const size_t size = 10 * 480;
TEST (PointCloud, size)
{
EXPECT_EQ(cloud.points.size (), cloud.size ());
}
TEST (PointCloud, sq_brackets_wrapper)
{
for (uint32_t i = 0; i < size; ++i)
EXPECT_EQ_VECTORS (cloud.points[i].getVector3fMap (),
cloud[i].getVector3fMap ());
}
TEST (PointCloud, at)
{
for (uint32_t i = 0; i < size; ++i)
EXPECT_EQ_VECTORS (cloud.points.at (i).getVector3fMap (),
cloud.at (i).getVector3fMap ());
}
TEST (PointCloud, front)
{
EXPECT_EQ_VECTORS (cloud.points.front ().getVector3fMap (),
cloud.front ().getVector3fMap ());
}
TEST (PointCloud, back)
{
EXPECT_EQ_VECTORS (cloud.points.back ().getVector3fMap (),
cloud.back ().getVector3fMap ());
}
TEST (PointCloud, constructor_with_allocation)
{
PointCloud<PointXYZ> cloud2 (5, 80);
EXPECT_EQ (cloud2.width, 5);
EXPECT_EQ (cloud2.height, 80);
EXPECT_EQ (cloud2.size (), 5*80);
}
TEST (PointCloud, iterators)
{
EXPECT_EQ_VECTORS (cloud.begin ()->getVector3fMap (),
cloud.points.begin ()->getVector3fMap ());
EXPECT_EQ_VECTORS (cloud.end ()->getVector3fMap (),
cloud.points.end ()->getVector3fMap ());
PointCloud<PointXYZ>::const_iterator pit = cloud.begin ();
PointCloud<PointXYZ>::VectorType::const_iterator pit2 = cloud.points.begin ();
for (; pit < cloud.end (); ++pit2, ++pit)
EXPECT_EQ_VECTORS (pit->getVector3fMap (), pit2->getVector3fMap ());
}
TEST (PointCloud, insert_range)
{
PointCloud<PointXYZ> cloud2 (10, 1);
for (uint32_t i = 0; i < 10; ++i)
cloud2[i] = PointXYZ (5*i+0,5*i+1,5*i+2);
uint32_t old_size = cloud.size ();
cloud.insert (cloud.begin (), cloud2.begin (), cloud2.end ());
EXPECT_EQ (cloud.width, cloud.size ());
EXPECT_EQ (cloud.height, 1);
EXPECT_EQ (cloud.width, old_size + cloud2.size ());
PointCloud<PointXYZ>::const_iterator pit = cloud.begin ();
PointCloud<PointXYZ>::const_iterator pit2 = cloud2.begin ();
for (; pit2 < cloud2.end (); ++pit2, ++pit)
EXPECT_EQ_VECTORS (pit->getVector3fMap (), pit2->getVector3fMap ());
}
int
main (int argc, char** argv)
{
cloud.width = 10;
cloud.height = 480;
for (uint32_t i = 0; i < size; ++i)
cloud.points.push_back (PointXYZ (3*i+0,3*i+1,3*i+2));
testing::InitGoogleTest (&argc, argv);
return (RUN_ALL_TESTS ());
}
<|endoftext|> |
<commit_before>#pragma once
#include <cstring>
#include <sys/mman.h>
#include "vfs/platform.hpp"
namespace vfs {
//----------------------------------------------------------------------------------------------
using file_view_impl = class posix_file_view;
//----------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------
class posix_file_view
{
protected:
//------------------------------------------------------------------------------------------
posix_file_view(file_sptr spFile, int64_t viewSize)
: spFile_(std::move(spFile))
, name_(spFile_->fileName())
//, fileMappingHandle_(nullptr)
, pData_(nullptr)
, pCursor_(nullptr)
, mappedTotalSize_(viewSize)
{
vfs_check(spFile_->isValid());
map(viewSize, false);
}
//------------------------------------------------------------------------------------------
posix_file_view(const path &name, int64_t size, bool openExisting)
: name_(name)
//, fileMappingHandle_(nullptr)
, pData_(nullptr)
, pCursor_(nullptr)
, mappedTotalSize_(size)
{
map(size, openExisting);
}
//------------------------------------------------------------------------------------------
~posix_file_view()
{
flush();
unmap();
/*
if (spFile_ == nullptr)
{
CloseHandle(fileMappingHandle_);
}
*/
}
//------------------------------------------------------------------------------------------
bool map(int64_t viewSize, bool openExisting)
{
const auto access = spFile_ ? spFile_->fileAccess() : file_access::read_write;
if (spFile_)
{
if (!spFile_->createMapping(viewSize))
{
return false;
}
//fileMappingHandle_ = spFile_->nativeFileMappingHandle();
const auto currentFileSize = spFile_->size();
fileTotalSize_ = viewSize == 0 ? currentFileSize : viewSize;
if (currentFileSize < viewSize)
{
spFile_->resize(viewSize);
}
}
else
{
vfs_check(false);
/*
if (openExisting)
{
fileMappingHandle_ = OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE, name_.c_str());
}
else
{
fileMappingHandle_ = CreateFileMapping
(
INVALID_HANDLE_VALUE,
nullptr,
PAGE_READWRITE,
DWORD(viewSize >> 32), DWORD((viewSize << 32) >> 32),
name_.c_str()
);
}
if (fileMappingHandle_ == nullptr)
{
const auto errorCode = GetLastError();
vfs_errorf("%sFileMapping(%ws) failed with error: %s", openExisting ? "Open" : "Create", name_.c_str(), get_last_error_as_string(errorCode).c_str());
return false;
}
fileTotalSize_ = viewSize;
*/
}
const auto fileMapAccess = (
(access == file_access::read_only)
? PROT_READ
: ((access == file_access::write_only)
? PROT_WRITE
: PROT_READ | PROT_WRITE
)
);
pData_ = reinterpret_cast<uint8_t*>(mmap(nullptr, fileTotalSize_, fileMapAccess, MAP_PRIVATE, spFile_->nativeHandle(), 0));
pCursor_ = pData_;
if (pData_ == MAP_FAILED)
{
vfs_errorf("mmap(%s) failed with error: %s", name_.c_str(), get_last_error_as_string(errno).c_str());
return false;
}
return true;
}
//------------------------------------------------------------------------------------------
bool unmap()
{
if (pData_ && munmap(pData_, fileTotalSize_) == -1)
{
return false;
}
return true;
}
//------------------------------------------------------------------------------------------
bool flush()
{
/*
if (!FlushViewOfFile(pData_, 0))
{
return false;
}
*/
return true;
}
//------------------------------------------------------------------------------------------
int64_t read(uint8_t *dst, int64_t sizeInBytes)
{
if (canMoveCursor(sizeInBytes))
{
memcpy(dst, pCursor_, sizeInBytes);
pCursor_ += sizeInBytes;
return sizeInBytes;
}
return 0;
}
//------------------------------------------------------------------------------------------
int64_t write(const uint8_t *src, int64_t sizeInBytes)
{
if (canMoveCursor(sizeInBytes))
{
memcpy(pCursor_, src, sizeInBytes);
pCursor_ += sizeInBytes;
return sizeInBytes;
}
return 0;
}
//------------------------------------------------------------------------------------------
bool isValid() const
{
return pData_ != nullptr;
}
//------------------------------------------------------------------------------------------
int64_t totalSize() const
{
return fileTotalSize_;
}
//------------------------------------------------------------------------------------------
bool canMoveCursor(int64_t offsetInBytes) const
{
return isValid() && (pCursor_ - pData_ + offsetInBytes) <= mappedTotalSize_;
}
//------------------------------------------------------------------------------------------
template<typename T = uint8_t>
T* data()
{
return reinterpret_cast<T*>(pData_);
}
//------------------------------------------------------------------------------------------
uint8_t* data()
{
return data<>();
}
//------------------------------------------------------------------------------------------
template<typename T = uint8_t>
T* cursor()
{
return reinterpret_cast<T*>(pCursor_);
}
//------------------------------------------------------------------------------------------
bool skip(int64_t offsetInBytes)
{
if (canMoveCursor(offsetInBytes))
{
pCursor_ += offsetInBytes;
return true;
}
return false;
}
private:
//------------------------------------------------------------------------------------------
file_sptr spFile_;
path name_;
//HANDLE fileMappingHandle_;
uint8_t *pData_;
uint8_t *pCursor_;
int64_t fileTotalSize_;
int64_t mappedTotalSize_;
};
//----------------------------------------------------------------------------------------------
} /*vfs*/
<commit_msg>Fixed file mapping not being flushed when closing the file.<commit_after>#pragma once
#include <cstring>
#include <sys/mman.h>
#include "vfs/platform.hpp"
namespace vfs {
//----------------------------------------------------------------------------------------------
using file_view_impl = class posix_file_view;
//----------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------
class posix_file_view
{
protected:
//------------------------------------------------------------------------------------------
posix_file_view(file_sptr spFile, int64_t viewSize)
: spFile_(std::move(spFile))
, name_(spFile_->fileName())
//, fileMappingHandle_(nullptr)
, pData_(nullptr)
, pCursor_(nullptr)
, mappedTotalSize_(viewSize)
{
vfs_check(spFile_->isValid());
map(viewSize, false);
}
//------------------------------------------------------------------------------------------
posix_file_view(const path &name, int64_t size, bool openExisting)
: name_(name)
//, fileMappingHandle_(nullptr)
, pData_(nullptr)
, pCursor_(nullptr)
, mappedTotalSize_(size)
{
map(size, openExisting);
}
//------------------------------------------------------------------------------------------
~posix_file_view()
{
flush();
unmap();
/*
if (spFile_ == nullptr)
{
CloseHandle(fileMappingHandle_);
}
*/
}
//------------------------------------------------------------------------------------------
bool map(int64_t viewSize, bool openExisting)
{
const auto access = spFile_ ? spFile_->fileAccess() : file_access::read_write;
if (spFile_)
{
if (!spFile_->createMapping(viewSize))
{
return false;
}
//fileMappingHandle_ = spFile_->nativeFileMappingHandle();
const auto currentFileSize = spFile_->size();
fileTotalSize_ = viewSize == 0 ? currentFileSize : viewSize;
if (currentFileSize < viewSize)
{
spFile_->resize(viewSize);
}
}
else
{
vfs_check(false);
/*
if (openExisting)
{
fileMappingHandle_ = OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE, name_.c_str());
}
else
{
fileMappingHandle_ = CreateFileMapping
(
INVALID_HANDLE_VALUE,
nullptr,
PAGE_READWRITE,
DWORD(viewSize >> 32), DWORD((viewSize << 32) >> 32),
name_.c_str()
);
}
if (fileMappingHandle_ == nullptr)
{
const auto errorCode = GetLastError();
vfs_errorf("%sFileMapping(%ws) failed with error: %s", openExisting ? "Open" : "Create", name_.c_str(), get_last_error_as_string(errorCode).c_str());
return false;
}
fileTotalSize_ = viewSize;
*/
}
const auto fileMapAccess = (
(access == file_access::read_only)
? PROT_READ
: ((access == file_access::write_only)
? PROT_WRITE
: PROT_READ | PROT_WRITE
)
);
pData_ = reinterpret_cast<uint8_t*>(mmap(nullptr, fileTotalSize_, fileMapAccess, MAP_SHARED, spFile_->nativeHandle(), 0));
pCursor_ = pData_;
if (pData_ == MAP_FAILED)
{
vfs_errorf("mmap(%s) failed with error: %s", name_.c_str(), get_last_error_as_string(errno).c_str());
return false;
}
return true;
}
//------------------------------------------------------------------------------------------
bool unmap()
{
if (pData_ && munmap(pData_, fileTotalSize_) == -1)
{
return false;
}
return true;
}
//------------------------------------------------------------------------------------------
bool flush()
{
/*
if (!FlushViewOfFile(pData_, 0))
{
return false;
}
*/
return true;
}
//------------------------------------------------------------------------------------------
int64_t read(uint8_t *dst, int64_t sizeInBytes)
{
if (canMoveCursor(sizeInBytes))
{
memcpy(dst, pCursor_, sizeInBytes);
pCursor_ += sizeInBytes;
return sizeInBytes;
}
return 0;
}
//------------------------------------------------------------------------------------------
int64_t write(const uint8_t *src, int64_t sizeInBytes)
{
if (canMoveCursor(sizeInBytes))
{
memcpy(pCursor_, src, sizeInBytes);
pCursor_ += sizeInBytes;
return sizeInBytes;
}
return 0;
}
//------------------------------------------------------------------------------------------
bool isValid() const
{
return pData_ != nullptr;
}
//------------------------------------------------------------------------------------------
int64_t totalSize() const
{
return fileTotalSize_;
}
//------------------------------------------------------------------------------------------
bool canMoveCursor(int64_t offsetInBytes) const
{
return isValid() && (pCursor_ - pData_ + offsetInBytes) <= mappedTotalSize_;
}
//------------------------------------------------------------------------------------------
template<typename T = uint8_t>
T* data()
{
return reinterpret_cast<T*>(pData_);
}
//------------------------------------------------------------------------------------------
uint8_t* data()
{
return data<>();
}
//------------------------------------------------------------------------------------------
template<typename T = uint8_t>
T* cursor()
{
return reinterpret_cast<T*>(pCursor_);
}
//------------------------------------------------------------------------------------------
bool skip(int64_t offsetInBytes)
{
if (canMoveCursor(offsetInBytes))
{
pCursor_ += offsetInBytes;
return true;
}
return false;
}
private:
//------------------------------------------------------------------------------------------
file_sptr spFile_;
path name_;
//HANDLE fileMappingHandle_;
uint8_t *pData_;
uint8_t *pCursor_;
int64_t fileTotalSize_;
int64_t mappedTotalSize_;
};
//----------------------------------------------------------------------------------------------
} /*vfs*/
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.