text
stringlengths 54
60.6k
|
|---|
<commit_before>/*=========================================================================
*
* Copyright Leiden University Medical Center, Erasmus University Medical
* Center and contributors
*
* 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.
*
*=========================================================================*/
#include "selxSuperElastixFilter.h"
#include "selxAnyFileReader.h"
#include "selxAnyFileWriter.h"
#include "selxLogger.h"
#include "selxGitInfo.h"
#include <boost/algorithm/string.hpp>
#include <boost/filesystem.hpp>
#include <boost/program_options.hpp>
#include <iostream>
#include <algorithm>
#include <iterator>
#include <string>
#include <stdexcept>
template< class T >
std::ostream &
operator<<( std::ostream & os, const std::vector< T > & v )
{
std::copy( v.begin(), v.end(), std::ostream_iterator< T >( os, " " ) );
return os;
}
namespace selx
{
// helper function to parse command line arguments for log level
std::istream& operator>>(std::istream& in, selx::LogLevel& loglevel)
{
std::string token;
in >> token;
if (token == "off")
loglevel = selx::LogLevel::OFF;
else if (token == "critical")
loglevel = selx::LogLevel::CRT;
else if (token == "error")
loglevel = selx::LogLevel::ERR;
else if (token == "warning")
loglevel = selx::LogLevel::WRN;
else if (token == "info")
loglevel = selx::LogLevel::INF;
else if (token == "debug")
loglevel = selx::LogLevel::DBG;
else if (token == "trace")
loglevel = selx::LogLevel::TRC;
else
in.setstate(std::ios_base::failbit);
return in;
}
}
int
main( int ac, char * av[] )
{
selx::Logger::Pointer logger = selx::Logger::New();
typedef std::vector< std::string > VectorOfStringsType;
typedef std::vector< boost::filesystem::path > VectorOfPathsType;
boost::filesystem::path logPath;
// default log level
selx::LogLevel logLevel = selx::LogLevel::WRN;
boost::filesystem::path configurationPath;
VectorOfPathsType configurationPaths;
VectorOfStringsType inputPairs;
VectorOfStringsType outputPairs;
boost::program_options::variables_map vm;
try
{
boost::program_options::options_description desc("Allowed options");
desc.add_options()
( "help", "produce help message" )
( "revision-sha", "produce git revision SHA-1 hash of SuperElastix source" )
("conf", boost::program_options::value< VectorOfPathsType >(&configurationPaths)->required()->multitoken(), "Configuration file: single or multiple Blueprints [.xml|.json]")
("in", boost::program_options::value< VectorOfStringsType >(&inputPairs)->multitoken(), "Input data: images, labels, meshes, etc. Usage arg: <name>=<path> (or multiple pairs)")
("out", boost::program_options::value< VectorOfStringsType >(&outputPairs)->multitoken(), "Output data: images, labels, meshes, etc. Usage arg: <name>=<path> (or multiple pairs)")
("graphout", boost::program_options::value< boost::filesystem::path >(), "Output Graphviz dot file")
("logfile", boost::program_options::value< boost::filesystem::path >(&logPath), "Log output file")
("loglevel", boost::program_options::value< selx::LogLevel >(&logLevel), "Log level [off|critical|error|warning|info|debug|trace]")
;
boost::program_options::store(boost::program_options::parse_command_line(ac, av, desc), vm);
if( vm.count( "help" ) )
{
std::cout
<< "SuperElastix GIT Revision SHA-1: " << selx::GitInfo::GetRevisionSha() << '\n'
<< desc << std::endl;
return 0;
}
if (vm.count("revision-sha"))
{
std::cout << selx::GitInfo::GetRevisionSha() << std::endl;
return 0;
}
boost::program_options::notify(vm);
}
catch (std::exception& e)
{
std::cerr << "Error: " << e.what() << "\n";
std::cerr << "See 'SuperElastix --help' for help" << "\n";
return 1;
}
catch (...)
{
std::cerr << "Unknown error!" << "\n";
return 1;
}
try
{
// optionally, stream to log file
std::ofstream outfile;
if ( vm.count("logfile") )
{
outfile = std::ofstream(logPath.c_str());
logger->AddStream("logfile", outfile);
}
logger->AddStream("cout", std::cout);
logger->SetLogLevel(logLevel);
// instantiate a SuperElastixFilter that is loaded with default components
selx::SuperElastixFilter::Pointer superElastixFilter = selx::SuperElastixFilter::New();
superElastixFilter->SetLogger(logger);
// create empty blueprint
selx::Blueprint::Pointer blueprint = selx::Blueprint::New();
blueprint->SetLogger(logger);
for (const auto & configurationPath : configurationPaths)
{
blueprint->MergeFromFile(configurationPath.string());
}
if( vm.count( "graphout" ) )
{
blueprint->Write(vm["graphout"].as< boost::filesystem::path >().string());
}
// The Blueprint needs to be set to superElastixFilter before GetInputFileReader and GetOutputFileWriter should be called.
superElastixFilter->SetBlueprint(blueprint);
// Store the readers so that they will not be destroyed before the pipeline is executed.
std::vector< selx::AnyFileReader::Pointer > fileReaders;
// Store the writers for the update call
std::vector< selx::AnyFileWriter::Pointer > fileWriters;
if( vm.count( "in" ) )
{
logger->Log( selx::LogLevel::INF, "Preparing input data ... ");
for( const auto & inputPair : inputPairs )
{
VectorOfStringsType nameAndPath;
boost::split( nameAndPath, inputPair, boost::is_any_of( "=" ) ); // NameAndPath == { "name","path" }
const std::string & name = nameAndPath[ 0 ];
const std::string & path = nameAndPath[ 1 ];
// since we do not know which reader type we should instantiate for input "name",
// we ask SuperElastix for a reader that matches the type of the source component "name"
logger->Log( selx::LogLevel::INF, "Preparing input '" + name + "': " + path + " ..." );
selx::AnyFileReader::Pointer reader = superElastixFilter->GetInputFileReader( name );
reader->SetFileName( path );
superElastixFilter->SetInput( name, reader->GetOutput() );
fileReaders.push_back( reader );
logger->Log( selx::LogLevel::INF, "Preparing input '" + name + "': " + path + " ... Done" );
}
logger->Log( selx::LogLevel::INF, "Preparing input data ... Done");
}
else
{
logger->Log( selx::LogLevel::INF, "No input data specified.");
}
if( vm.count( "out" ) )
{
logger->Log( selx::LogLevel::INF, "Preparing output data ... ");
for( const auto & outputPair : outputPairs )
{
VectorOfStringsType nameAndPath;
boost::split( nameAndPath, outputPair, boost::is_any_of( "=" ) ); // NameAndPath == { "name","path" }
const std::string & name = nameAndPath[ 0 ];
const std::string & path = nameAndPath[ 1 ];
// since we do not know which writer type we should instantiate for output "name",
// we ask SuperElastix for a writer that matches the type of the sink component "name"
logger->Log( selx::LogLevel::INF, "Preparing output '" + name + "': " + path + " ..." );
selx::AnyFileWriter::Pointer writer = superElastixFilter->GetOutputFileWriter( name );
writer->SetFileName( path );
writer->SetInput( superElastixFilter->GetOutput( name ) );
fileWriters.push_back( writer );
logger->Log( selx::LogLevel::INF, "Preparing output '" + name + "': " + path + " ... Done" );
}
}
else
{
logger->Log( selx::LogLevel::INF, "No output data specified.");
}
superElastixFilter->Update();
/* Execute SuperElastix by updating the writers */
logger->Log( selx::LogLevel::INF, "Executing ...");
for( auto & writer : fileWriters )
{
writer->Update();
}
logger->Log(selx:: LogLevel::INF, "Executing ... Done");
}
catch( std::exception & e )
{
logger->Log( selx::LogLevel::CRT, "Executing ... Error");
logger->Log( selx::LogLevel::CRT, e.what());
std::cerr << e.what();
return 1;
}
catch( ... )
{
logger->Log( selx::LogLevel::CRT, "Executing ... Error");
logger->Log( selx::LogLevel::CRT, "Exception of unknown type!");
std::cerr << "Exception of unknown type!";
return 1;
}
return 0;
}
<commit_msg>BUG: Remove extra call to update<commit_after>/*=========================================================================
*
* Copyright Leiden University Medical Center, Erasmus University Medical
* Center and contributors
*
* 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.
*
*=========================================================================*/
#include "selxSuperElastixFilter.h"
#include "selxAnyFileReader.h"
#include "selxAnyFileWriter.h"
#include "selxLogger.h"
#include "selxGitInfo.h"
#include <boost/algorithm/string.hpp>
#include <boost/filesystem.hpp>
#include <boost/program_options.hpp>
#include <iostream>
#include <algorithm>
#include <iterator>
#include <string>
#include <stdexcept>
template< class T >
std::ostream &
operator<<( std::ostream & os, const std::vector< T > & v )
{
std::copy( v.begin(), v.end(), std::ostream_iterator< T >( os, " " ) );
return os;
}
namespace selx
{
// helper function to parse command line arguments for log level
std::istream& operator>>(std::istream& in, selx::LogLevel& loglevel)
{
std::string token;
in >> token;
if (token == "off")
loglevel = selx::LogLevel::OFF;
else if (token == "critical")
loglevel = selx::LogLevel::CRT;
else if (token == "error")
loglevel = selx::LogLevel::ERR;
else if (token == "warning")
loglevel = selx::LogLevel::WRN;
else if (token == "info")
loglevel = selx::LogLevel::INF;
else if (token == "debug")
loglevel = selx::LogLevel::DBG;
else if (token == "trace")
loglevel = selx::LogLevel::TRC;
else
in.setstate(std::ios_base::failbit);
return in;
}
}
int
main( int ac, char * av[] )
{
selx::Logger::Pointer logger = selx::Logger::New();
typedef std::vector< std::string > VectorOfStringsType;
typedef std::vector< boost::filesystem::path > VectorOfPathsType;
boost::filesystem::path logPath;
// default log level
selx::LogLevel logLevel = selx::LogLevel::WRN;
boost::filesystem::path configurationPath;
VectorOfPathsType configurationPaths;
VectorOfStringsType inputPairs;
VectorOfStringsType outputPairs;
boost::program_options::variables_map vm;
try
{
boost::program_options::options_description desc("Allowed options");
desc.add_options()
( "help", "produce help message" )
( "revision-sha", "produce git revision SHA-1 hash of SuperElastix source" )
("conf", boost::program_options::value< VectorOfPathsType >(&configurationPaths)->required()->multitoken(), "Configuration file: single or multiple Blueprints [.xml|.json]")
("in", boost::program_options::value< VectorOfStringsType >(&inputPairs)->multitoken(), "Input data: images, labels, meshes, etc. Usage arg: <name>=<path> (or multiple pairs)")
("out", boost::program_options::value< VectorOfStringsType >(&outputPairs)->multitoken(), "Output data: images, labels, meshes, etc. Usage arg: <name>=<path> (or multiple pairs)")
("graphout", boost::program_options::value< boost::filesystem::path >(), "Output Graphviz dot file")
("logfile", boost::program_options::value< boost::filesystem::path >(&logPath), "Log output file")
("loglevel", boost::program_options::value< selx::LogLevel >(&logLevel), "Log level [off|critical|error|warning|info|debug|trace]")
;
boost::program_options::store(boost::program_options::parse_command_line(ac, av, desc), vm);
if( vm.count( "help" ) )
{
std::cout
<< "SuperElastix GIT Revision SHA-1: " << selx::GitInfo::GetRevisionSha() << '\n'
<< desc << std::endl;
return 0;
}
if (vm.count("revision-sha"))
{
std::cout << selx::GitInfo::GetRevisionSha() << std::endl;
return 0;
}
boost::program_options::notify(vm);
}
catch (std::exception& e)
{
std::cerr << "Error: " << e.what() << "\n";
std::cerr << "See 'SuperElastix --help' for help" << "\n";
return 1;
}
catch (...)
{
std::cerr << "Unknown error!" << "\n";
return 1;
}
try
{
// optionally, stream to log file
std::ofstream outfile;
if ( vm.count("logfile") )
{
outfile = std::ofstream(logPath.c_str());
logger->AddStream("logfile", outfile);
}
logger->AddStream("cout", std::cout);
logger->SetLogLevel(logLevel);
// instantiate a SuperElastixFilter that is loaded with default components
selx::SuperElastixFilter::Pointer superElastixFilter = selx::SuperElastixFilter::New();
superElastixFilter->SetLogger(logger);
// create empty blueprint
selx::Blueprint::Pointer blueprint = selx::Blueprint::New();
blueprint->SetLogger(logger);
for (const auto & configurationPath : configurationPaths)
{
blueprint->MergeFromFile(configurationPath.string());
}
if( vm.count( "graphout" ) )
{
blueprint->Write(vm["graphout"].as< boost::filesystem::path >().string());
}
// The Blueprint needs to be set to superElastixFilter before GetInputFileReader and GetOutputFileWriter should be called.
superElastixFilter->SetBlueprint(blueprint);
// Store the readers so that they will not be destroyed before the pipeline is executed.
std::vector< selx::AnyFileReader::Pointer > fileReaders;
// Store the writers for the update call
std::vector< selx::AnyFileWriter::Pointer > fileWriters;
if( vm.count( "in" ) )
{
logger->Log( selx::LogLevel::INF, "Preparing input data ... ");
for( const auto & inputPair : inputPairs )
{
VectorOfStringsType nameAndPath;
boost::split( nameAndPath, inputPair, boost::is_any_of( "=" ) ); // NameAndPath == { "name","path" }
const std::string & name = nameAndPath[ 0 ];
const std::string & path = nameAndPath[ 1 ];
// since we do not know which reader type we should instantiate for input "name",
// we ask SuperElastix for a reader that matches the type of the source component "name"
logger->Log( selx::LogLevel::INF, "Preparing input '" + name + "': " + path + " ..." );
selx::AnyFileReader::Pointer reader = superElastixFilter->GetInputFileReader( name );
reader->SetFileName( path );
superElastixFilter->SetInput( name, reader->GetOutput() );
fileReaders.push_back( reader );
logger->Log( selx::LogLevel::INF, "Preparing input '" + name + "': " + path + " ... Done" );
}
logger->Log( selx::LogLevel::INF, "Preparing input data ... Done");
}
else
{
logger->Log( selx::LogLevel::INF, "No input data specified.");
}
if( vm.count( "out" ) )
{
logger->Log( selx::LogLevel::INF, "Preparing output data ... ");
for( const auto & outputPair : outputPairs )
{
VectorOfStringsType nameAndPath;
boost::split( nameAndPath, outputPair, boost::is_any_of( "=" ) ); // NameAndPath == { "name","path" }
const std::string & name = nameAndPath[ 0 ];
const std::string & path = nameAndPath[ 1 ];
// since we do not know which writer type we should instantiate for output "name",
// we ask SuperElastix for a writer that matches the type of the sink component "name"
logger->Log( selx::LogLevel::INF, "Preparing output '" + name + "': " + path + " ..." );
selx::AnyFileWriter::Pointer writer = superElastixFilter->GetOutputFileWriter( name );
writer->SetFileName( path );
writer->SetInput( superElastixFilter->GetOutput( name ) );
fileWriters.push_back( writer );
logger->Log( selx::LogLevel::INF, "Preparing output '" + name + "': " + path + " ... Done" );
}
}
else
{
logger->Log( selx::LogLevel::INF, "No output data specified.");
}
/* Execute SuperElastix by updating the writers */
logger->Log( selx::LogLevel::INF, "Executing ...");
for( auto & writer : fileWriters )
{
writer->Update();
}
logger->Log(selx:: LogLevel::INF, "Executing ... Done");
}
catch( std::exception & e )
{
logger->Log( selx::LogLevel::CRT, "Executing ... Error");
logger->Log( selx::LogLevel::CRT, e.what());
std::cerr << e.what();
return 1;
}
catch( ... )
{
logger->Log( selx::LogLevel::CRT, "Executing ... Error");
logger->Log( selx::LogLevel::CRT, "Exception of unknown type!");
std::cerr << "Exception of unknown type!";
return 1;
}
return 0;
}
<|endoftext|>
|
<commit_before>#include "ros/ros.h"
#include "geometry_msgs/Twist.h"
#include "sensor_msgs/LaserScan.h"
#include <nav_msgs/Odometry.h>
#include "std_msgs/String.h"
#include <cstdlib> // Needed for rand()
#include <ctime> // Needed to seed random number generator with a time value
float prevclosestRange = 0;
double linear_x;
double angular_z;
//pose of the robot
double px;
double py;
double theta;
double prevpx;
double prevpy;
bool isRotate;
int checkcount=0;
class RandomWalk {
public:
// Construst a new RandomWalk object and hook up this ROS node
// to the simulated robot's velocity control and laser topics
RandomWalk(ros::NodeHandle& nh) :
fsm(FSM_MOVE_FORWARD),
rotateStartTime(ros::Time::now()),
rotateDuration(0.f) {
// Initialize random time generator
srand(time(NULL));
// Advertise a new publisher for the simulated robot's velocity command topic
// (the second argument indicates that if multiple command messages are in
// the queue to be sent, only the last command will be sent)
ros::NodeHandle n;
commandPub = nh.advertise<geometry_msgs::Twist>("robot_2/cmd_vel",1000);
truckPosPub = nh.advertise<std_msgs::String>("truck_position",1000);
// Subscribe to the simulated robot's laser scan topic and tell ROS to call
// this->commandCallback() whenever a new message is published on that topic
laserSub = nh.subscribe<sensor_msgs::LaserScan>("robot_2/base_scan", 1000, &RandomWalk::commandCallback, this);
StageOdo_sub = nh.subscribe<nav_msgs::Odometry>("robot_2/odom",1000, &RandomWalk::StageOdom_callback,this);
//ros::Subscriber StageOdo_sub = n.subscribe<nav_msgs::Odometry>("robot_0/odom",1000, StageOdom_callback);
};
void StageOdom_callback(nav_msgs::Odometry msg)
{
//This is the call back function to process odometry messages coming from Stage.
px = -3 + msg.pose.pose.position.x;
py = -3 + msg.pose.pose.position.y;
//printf("%f",px);
// If the current position is the same the previous position, then the robot is stuck and needs to move around
if ((px == prevpx) && (py == prevpy)) {
//msg.pose.pose.position.x = 5;
//ROS_INFO("Prevpx: %f",prevpx);
// Note the negative linear_x
//linear_x=-0.2;
//angular_z=1;
//theta=10;
//px = 5;
//py= 5;
//printf("Robot stuck");
if (!isRotate) {
ROS_INFO("Truck stuck");
double r2 = (double)rand()/((double)RAND_MAX/(M_PI/2));
double m2 = (double)rand()/((double)RAND_MAX/0.5);
//ROS_INFO("r2" << r2);
move(-m2, r2);
}
} else {
// One the robot becomes unstuck, then it moves around again normally
//linear_x = 0.2;
//angular_z = 0.2;
//ROS_INFO("Robot unstuck");
//checkcount=0;
}
ROS_INFO("Truck -- Current x position is: %f", px);
ROS_INFO("Truck -- Current y position is: %f", py);
prevpx = px;
prevpy = py;
};
// Send a velocity command
void move(double linearVelMPS, double angularVelRadPS) {
geometry_msgs::Twist msg; // The default constructor will set all commands to 0
msg.linear.x = linearVelMPS;
msg.angular.z = angularVelRadPS;
commandPub.publish(msg);
};
// Process the incoming laser scan message
void commandCallback(const sensor_msgs::LaserScan::ConstPtr& msg) {
if (fsm == FSM_MOVE_FORWARD) {
// Compute the average range value between MIN_SCAN_ANGLE and MAX_SCAN_ANGLE
//
// NOTE: ideally, the following loop should have additional checks to ensure
// that indices are not out of bounds, by computing:
//
//- currAngle = msg->angle_min + msg->angle_increment*currIndex
//
// and then ensuring that currAngle <= msg->angle_max
unsigned int minIndex = ceil((MIN_SCAN_ANGLE_RAD - msg->angle_min) / msg->angle_increment);
unsigned int maxIndex = ceil((MAX_SCAN_ANGLE_RAD - msg->angle_min) / msg->angle_increment);
float closestRange = msg->ranges[minIndex];
for (unsigned int currIndex = minIndex + 1; currIndex < maxIndex; currIndex++) {
if (msg->ranges[currIndex] < closestRange) {
closestRange = msg->ranges[currIndex];
}
}
//if (closestRange == prevclosestRange) {
// ROS_INFO_STREAM("STUCK");
// move(-FORWARD_SPEED_MPS, ROTATE_SPEED_RADPS);
// //move(0, ROTATE_SPEED_RADPS);
//} else {
//ROS_INFO_STREAM("Range: " << closestRange);
prevclosestRange = closestRange;
if (closestRange < PROXIMITY_RANGE_M) {
fsm=FSM_ROTATE;
rotateStartTime=ros::Time::now();
float r2 = (float)rand()/((float)RAND_MAX/100);
rotateDuration=ros::Duration(rand() % 2);
//fsm= FSM_MOVE_FORWARD;
}
//}
}
};
// Main FSM loop for ensuring that ROS messages are
// processed in a timely manner, and also for sending
// velocity controls to the simulated robot based on the FSM state
void spin() {
ros::Rate rate(10); // Specify the FSM loop rate in Hz
while (ros::ok()) { // Keep spinning loop until user presses Ctrl+C
std_msgs::String msg;
std::stringstream ss;
ss << "Truck -- px:" << px << " py:" << py << " theta:" << theta << " isRotate:" << isRotate;
msg.data = ss.str();
//ROS_INFO("%s", msg.data.c_str());
if (fsm == FSM_MOVE_FORWARD) {
//ROS_INFO_STREAM("Start forward");
move(FORWARD_SPEED_MPS, 0);
checkcount++;
if (checkcount > 3) {
isRotate=false;
}
}
if (fsm == FSM_ROTATE) {
//ROS_INFO_STREAM("Start rotate");
move(0, ROTATE_SPEED_RADPS);
rotateEndTime=ros::Time::now();
isRotate=true;
//ROS_INFO_STREAM("Time: " << rotateEndTime);
if ((rotateEndTime - rotateStartTime) > rotateDuration) {
fsm=FSM_MOVE_FORWARD;
//ROS_INFO_STREAM("End rotate");
checkcount=0;
}
}
truckPosPub.publish(msg);
ros::spinOnce(); // Need to call this function often to allow ROS to process incoming messages
rate.sleep(); // Sleep for the rest of the cycle, to enforce the FSM loop rate
}
};
enum FSM {FSM_MOVE_FORWARD, FSM_ROTATE};
// Tunable parameters
// TODO: tune parameters as you see fit
const static double MIN_SCAN_ANGLE_RAD = -10.0/180*M_PI;
const static double MAX_SCAN_ANGLE_RAD = +10.0/180*M_PI;
const static float PROXIMITY_RANGE_M = 4; // Should be smaller than sensor_msgs::LaserScan::range_max
const static double FORWARD_SPEED_MPS = 2;
const static double ROTATE_SPEED_RADPS = M_PI/2;
protected:
ros::Publisher commandPub; // Publisher to the simulated robot's velocity command topic
ros::Publisher truckPosPub;
ros::Subscriber laserSub; // Subscriber to the simulated robot's laser scan topic
enum FSM fsm; // Finite state machine for the random walk algorithm
ros::Time rotateStartTime; // Start time of the rotation
ros::Time rotateEndTime;
ros::Duration rotateDuration; // Duration of the rotation
ros::Subscriber StageOdo_sub;
};
int main(int argc, char **argv) {
ros::init(argc, argv, "Trust"); // Initiate new ROS node named "Truck"
ROS_INFO("This node is: Truck");
ros::NodeHandle n;
prevpx = 0;
prevpx= 0;
RandomWalk walker(n); // Create new random walk object
walker.spin(); // Execute FSM loop
return 0;
};
<commit_msg>Revert "Fixing Truck. Work in progress, saving changes with commit"<commit_after>#include "ros/ros.h"
#include "geometry_msgs/Twist.h"
#include "sensor_msgs/LaserScan.h"
#include <nav_msgs/Odometry.h>
#include "std_msgs/String.h"
#include <cstdlib> // Needed for rand()
#include <ctime> // Needed to seed random number generator with a time value
float prevclosestRange = 0;
double linear_x;
double angular_z;
//pose of the robot
double px;
double py;
double theta;
double prevpx;
double prevpy;
bool isRotate;
int checkcount=0;
class RandomWalk {
public:
// Construst a new RandomWalk object and hook up this ROS node
// to the simulated robot's velocity control and laser topics
RandomWalk(ros::NodeHandle& nh) :
fsm(FSM_MOVE_FORWARD),
rotateStartTime(ros::Time::now()),
rotateDuration(0.f) {
// Initialize random time generator
srand(time(NULL));
// Advertise a new publisher for the simulated robot's velocity command topic
// (the second argument indicates that if multiple command messages are in
// the queue to be sent, only the last command will be sent)
ros::NodeHandle n;
commandPub = nh.advertise<geometry_msgs::Twist>("robot_2/cmd_vel",1000);
truckPosPub = nh.advertise<std_msgs::String>("truck_position",1000);
// Subscribe to the simulated robot's laser scan topic and tell ROS to call
// this->commandCallback() whenever a new message is published on that topic
laserSub = nh.subscribe<sensor_msgs::LaserScan>("robot_2/base_scan", 1000, &RandomWalk::commandCallback, this);
StageOdo_sub = nh.subscribe<nav_msgs::Odometry>("robot_2/odom",1000, &RandomWalk::StageOdom_callback,this);
//ros::Subscriber StageOdo_sub = n.subscribe<nav_msgs::Odometry>("robot_0/odom",1000, StageOdom_callback);
};
void StageOdom_callback(nav_msgs::Odometry msg)
{
//This is the call back function to process odometry messages coming from Stage.
px = -3 + msg.pose.pose.position.x;
py = -3 + msg.pose.pose.position.y;
//printf("%f",px);
// If the current position is the same the previous position, then the robot is stuck and needs to move around
if ((px == prevpx) && (py == prevpy)) {
//msg.pose.pose.position.x = 5;
//ROS_INFO("Prevpx: %f",prevpx);
// Note the negative linear_x
//linear_x=-0.2;
//angular_z=1;
//theta=10;
//px = 5;
//py= 5;
//printf("Robot stuck");
if (!isRotate) {
ROS_INFO("Truck stuck");
double r2 = (double)rand()/((double)RAND_MAX/(M_PI/2));
double m2 = (double)rand()/((double)RAND_MAX/0.5);
//ROS_INFO("r2" << r2);
move(-m2, r2);
}
} else {
// One the robot becomes unstuck, then it moves around again normally
//linear_x = 0.2;
//angular_z = 0.2;
//ROS_INFO("Robot unstuck");
//checkcount=0;
}
ROS_INFO("Truck -- Current x position is: %f", px);
ROS_INFO("Truck -- Current y position is: %f", py);
prevpx = px;
prevpy = py;
};
// Send a velocity command
void move(double linearVelMPS, double angularVelRadPS) {
geometry_msgs::Twist msg; // The default constructor will set all commands to 0
msg.linear.x = linearVelMPS;
msg.angular.z = angularVelRadPS;
commandPub.publish(msg);
};
// Process the incoming laser scan message
void commandCallback(const sensor_msgs::LaserScan::ConstPtr& msg) {
if (fsm == FSM_MOVE_FORWARD) {
// Compute the average range value between MIN_SCAN_ANGLE and MAX_SCAN_ANGLE
//
// NOTE: ideally, the following loop should have additional checks to ensure
// that indices are not out of bounds, by computing:
//
//- currAngle = msg->angle_min + msg->angle_increment*currIndex
//
// and then ensuring that currAngle <= msg->angle_max
unsigned int minIndex = ceil((MIN_SCAN_ANGLE_RAD - msg->angle_min) / msg->angle_increment);
unsigned int maxIndex = ceil((MAX_SCAN_ANGLE_RAD - msg->angle_min) / msg->angle_increment);
float closestRange = msg->ranges[minIndex];
for (unsigned int currIndex = minIndex + 1; currIndex < maxIndex; currIndex++) {
if (msg->ranges[currIndex] < closestRange) {
closestRange = msg->ranges[currIndex];
}
}
//if (closestRange == prevclosestRange) {
// ROS_INFO_STREAM("STUCK");
// move(-FORWARD_SPEED_MPS, ROTATE_SPEED_RADPS);
// //move(0, ROTATE_SPEED_RADPS);
//} else {
//ROS_INFO_STREAM("Range: " << closestRange);
prevclosestRange = closestRange;
if (closestRange < PROXIMITY_RANGE_M) {
fsm=FSM_ROTATE;
rotateStartTime=ros::Time::now();
float r2 = (float)rand()/((float)RAND_MAX/100);
rotateDuration=ros::Duration(rand() % 2);
//fsm= FSM_MOVE_FORWARD;
}
//}
}
};
// Main FSM loop for ensuring that ROS messages are
// processed in a timely manner, and also for sending
// velocity controls to the simulated robot based on the FSM state
void spin() {
ros::Rate rate(10); // Specify the FSM loop rate in Hz
while (ros::ok()) { // Keep spinning loop until user presses Ctrl+C
std_msgs::String msg;
std::stringstream ss;
ss << "Truck -- px:" << px << " py:" << py << " theta:" << theta << " isRotate:" << isRotate;
msg.data = ss.str();
//ROS_INFO("%s", msg.data.c_str());
if (fsm == FSM_MOVE_FORWARD) {
//ROS_INFO_STREAM("Start forward");
move(FORWARD_SPEED_MPS, 0);
checkcount++;
if (checkcount > 3) {
isRotate=false;
}
}
if (fsm == FSM_ROTATE) {
//ROS_INFO_STREAM("Start rotate");
move(0, ROTATE_SPEED_RADPS);
rotateEndTime=ros::Time::now();
isRotate=true;
//ROS_INFO_STREAM("Time: " << rotateEndTime);
if ((rotateEndTime - rotateStartTime) > rotateDuration) {
fsm=FSM_MOVE_FORWARD;
//ROS_INFO_STREAM("End rotate");
checkcount=0;
}
}
truckPosPub.publish(msg);
ros::spinOnce(); // Need to call this function often to allow ROS to process incoming messages
rate.sleep(); // Sleep for the rest of the cycle, to enforce the FSM loop rate
}
};
enum FSM {FSM_MOVE_FORWARD, FSM_ROTATE};
// Tunable parameters
// TODO: tune parameters as you see fit
const static double MIN_SCAN_ANGLE_RAD = -10.0/180*M_PI;
const static double MAX_SCAN_ANGLE_RAD = +10.0/180*M_PI;
const static float PROXIMITY_RANGE_M = 1; // Should be smaller than sensor_msgs::LaserScan::range_max
const static double FORWARD_SPEED_MPS = 2;
const static double ROTATE_SPEED_RADPS = M_PI/2;
protected:
ros::Publisher commandPub; // Publisher to the simulated robot's velocity command topic
ros::Publisher truckPosPub;
ros::Subscriber laserSub; // Subscriber to the simulated robot's laser scan topic
enum FSM fsm; // Finite state machine for the random walk algorithm
ros::Time rotateStartTime; // Start time of the rotation
ros::Time rotateEndTime;
ros::Duration rotateDuration; // Duration of the rotation
ros::Subscriber StageOdo_sub;
};
int main(int argc, char **argv) {
ros::init(argc, argv, "Trust"); // Initiate new ROS node named "Truck"
ROS_INFO("This node is: Truck");
ros::NodeHandle n;
prevpx = 0;
prevpx= 0;
RandomWalk walker(n); // Create new random walk object
walker.spin(); // Execute FSM loop
return 0;
};
<|endoftext|>
|
<commit_before>//Copyright (c) 2021 Ultimaker B.V.
//CuraEngine is released under the terms of the AGPLv3 or higher.
#include <gtest/gtest.h>
#include "../../src/BeadingStrategy/CenterDeviationBeadingStrategy.h" //Code under test.
namespace cura
{
/*!
* Tests calling the constructor of the CenterDeviationBeadingStrategy and
* whether it sets members correctly.
*/
TEST(CenterDeviationBeadingStrategy, Construction)
{
CenterDeviationBeadingStrategy strategy(400, 0.6, 0.5, 0.5); //Pretty standard settings.
EXPECT_EQ(strategy.getSplitMiddleThreshold(), 200) << "Since the transition threshold was 50%, the minimum line width should be 0.5 times the preferred width.";
strategy = CenterDeviationBeadingStrategy(400, 0.6, 0, 0);
EXPECT_EQ(strategy.getSplitMiddleThreshold(), 0) << "Since the transition threshold was 0%, the minimum line width should be 0.";
strategy = CenterDeviationBeadingStrategy(0, 0.6, 0.5, 0.5);
EXPECT_EQ(strategy.getSplitMiddleThreshold(), 0) << "Since the line width was 0%, the minimum line width should also be 0.";
strategy = CenterDeviationBeadingStrategy(400, 0.6, 1, 1);
EXPECT_EQ(strategy.getSplitMiddleThreshold(), 400) << "Since the transition threshold was 100%, the minimum line width equals the preferred width.";
}
/*!
* Tests getting the optimal thickness with Center Deviation.
*
* This should simply be a multiplication of the line width, when using Center
* Deviation. It doesn't adjust the line widths by itself.
*/
TEST(CenterDeviationBeadingStrategy, GetOptimalThickness)
{
constexpr coord_t line_width = 400;
CenterDeviationBeadingStrategy strategy(line_width, 0.6, 0.5, 0.5);
EXPECT_EQ(strategy.getOptimalThickness(0), 0) << "With 0 beads, you'll fill 0 space.";
EXPECT_EQ(strategy.getOptimalThickness(1), line_width) << "With 1 bead, optimally you'll want to print that bead at the optimal line width.";
EXPECT_EQ(strategy.getOptimalThickness(4), 4 * line_width) << "With 4 beads, optimally fill 4 line widths.";
}
/*!
* Test getting the width at which we need to transition to a greater number of
* lines.
*/
TEST(CenterDeviationBeadingStrategy, GetTransitionThickness)
{
constexpr coord_t line_width = 400;
//Transition ratio 25%.
CenterDeviationBeadingStrategy strategy(line_width, 0.6, 0.25, 0.25);
EXPECT_EQ(strategy.getTransitionThickness(0), 0.25 * line_width) << "The transition from 0 beads to 1 happens at 25% line width.";
EXPECT_EQ(strategy.getTransitionThickness(1), 1.25 * line_width) << "The transition from 1 bead to 2 happens at 125% line width.";
EXPECT_EQ(strategy.getTransitionThickness(4), 4.25 * line_width) << "The transition from 4 beads to 5 happens at 4 + 25% line width.";
//Transition ratio 50%.
strategy = CenterDeviationBeadingStrategy(line_width, 0.6, 0.5, 0.5);
EXPECT_EQ(strategy.getTransitionThickness(0), 0.5 * line_width) << "The transition from 0 beads to 1 happens at 50% line width.";
EXPECT_EQ(strategy.getTransitionThickness(1), 1.5 * line_width) << "The transition from 1 bead to 2 happens at 150% line width.";
EXPECT_EQ(strategy.getTransitionThickness(5), 5.5 * line_width) << "The transition from 5 beads to 6 happens at 5 + 50% line width.";
//Transition ratio 95%.
strategy = CenterDeviationBeadingStrategy(line_width, 0.6, 0.95, 0.95);
EXPECT_EQ(strategy.getTransitionThickness(0), 0.95 * line_width) << "The transition from 0 beads to 1 happens at 95% line width.";
EXPECT_EQ(strategy.getTransitionThickness(1), 1.95 * line_width) << "The transition from 1 bead to 2 happens at 195% line width.";
EXPECT_EQ(strategy.getTransitionThickness(3), 3.95 * line_width) << "The transition from 3 beads to 4 happens at 3 + 95% line width.";
//Transition ratio 100%.
strategy = CenterDeviationBeadingStrategy(line_width, 0.6, 1, 1);
EXPECT_EQ(strategy.getTransitionThickness(0), line_width) << "Only transition to have a line if it fits completely.";
EXPECT_EQ(strategy.getTransitionThickness(1), 2 * line_width) << "Only transition to have two lines if they both fit completely.";
EXPECT_EQ(strategy.getTransitionThickness(2), 3 * line_width) << "Only transition to have three lines if they all fit completely.";
//Transition ratio 0%.
strategy = CenterDeviationBeadingStrategy(line_width, 0.6, 0, 0);
EXPECT_EQ(strategy.getTransitionThickness(0), 0) << "Always transition to 1 line. The minimum line width is 0 after all.";
EXPECT_EQ(strategy.getTransitionThickness(1), line_width) << "If 1 line fits completely, immediately transition to 2 lines.";
EXPECT_EQ(strategy.getTransitionThickness(6), 6 * line_width) << "If 6 lines fit completely, immediately transition to 7 lines.";
}
/*!
* Test getting the optimal bead count for a given shape width.
*/
TEST(CenterDeviationBeadingStrategy, GetOptimalBeadCount)
{
constexpr coord_t line_width = 400;
//Transition ratio 25%.
CenterDeviationBeadingStrategy strategy(line_width, 0.6, 0.25, 0.25);
//Anything below 25% line width should then produce 0 lines.
for(coord_t width = 0; width < 0.25 * line_width; width += 10)
{
EXPECT_EQ(strategy.getOptimalBeadCount(width), 0) << "Width is below the transition thickness from 0 to 1 line, so it should produce 0 lines.";
}
EXPECT_LE(strategy.getOptimalBeadCount(0.25 * line_width), 1) << "At exactly the transition thickness, either 0 or 1 line is acceptable.";
for(coord_t width = 0.25 * line_width + 1; width < 1.25 * line_width; width += 10)
{
EXPECT_EQ(strategy.getOptimalBeadCount(width), 1) << "Width is above the transition thickness from 0 to 1 line but below 1 to 2 lines, so it should produce 1 line.";
}
EXPECT_TRUE(strategy.getOptimalBeadCount(1.25 * line_width) == 1 || strategy.getOptimalBeadCount(1.25 * line_width) == 2) << "At exactly 125% line width, either 1 or 2 lines is acceptable.";
for(coord_t width = 1.25 * line_width + 1; width < 2.25 * line_width; width += 10)
{
EXPECT_EQ(strategy.getOptimalBeadCount(width), 2) << "Width is above the transition thickness from 1 to 2 lines but below 2 to 3 lines, so it should produce 2 lines.";
}
//Transition ratio 80%.
strategy = CenterDeviationBeadingStrategy(line_width, 0.6, 0.8, 0.8);
//Anything below 80% line width should then produce 0 lines.
for(coord_t width = 0; width < 0.8 * line_width; width += 10)
{
EXPECT_EQ(strategy.getOptimalBeadCount(width), 0) << "Width is below the transition thickness from 0 to 1 line, so it should produce 0 lines.";
}
EXPECT_LE(strategy.getOptimalBeadCount(0.8 * line_width), 1) << "At exactly the transition thickness, either 0 or 1 line is acceptable.";
for(coord_t width = 0.8 * line_width + 1; width < 1.8 * line_width; width += 10)
{
EXPECT_EQ(strategy.getOptimalBeadCount(width), 1) << "Width is above the transition thickness from 0 to 1 line but below 1 to 2 lines, so it should produce 1 line.";
}
EXPECT_TRUE(strategy.getOptimalBeadCount(1.8 * line_width) == 1 || strategy.getOptimalBeadCount(1.8 * line_width) == 2) << "At exactly 180% line width, either 1 or 2 lines is acceptable.";
for(coord_t width = 1.8 * line_width + 1; width < 2.8 * line_width; width += 10)
{
EXPECT_EQ(strategy.getOptimalBeadCount(width), 2) << "Width is above the transition thickness from 1 to 2 lines but below 2 to 3 lines, so it should produce 2 lines.";
}
}
/*!
* Tests whether the line compactness setting does what it is supposed to do,
* producing fewer, wider lines when the setting is high than when the setting
* is low.
*
* This is a test for requirements. The exact outcome of a function is not
* tested, but properties of the outcome is tested.
*/
TEST(CenterDeviationBeadingStrategy, LineCompactnessMonotonic)
{
constexpr coord_t line_width = 400;
constexpr coord_t widths[] = {0, 1, 99, 101, 150, 200, 299, 300, 301, 399, 400, 401, 410, 450, 500, 660, 770, 880, 910, 1000, 1200}; //Bunch of widths to test with.
constexpr float compactnesses[] = {0, 0.1, 0.2, 0.24, 0.25, 0.26, 0.3, 0.5, 0.7, 0.75, 0.99, 1}; //Bunch of line compactness factors to test with.
constexpr size_t num_compactnesses = sizeof(compactnesses) / sizeof(float);
for(coord_t width : widths)
{
for(size_t low_index = 0; low_index < num_compactnesses; ++low_index)
{
const float low_compactness = compactnesses[low_index];
for(size_t high_index = low_index; high_index < num_compactnesses; ++high_index)
{
const float high_compactness = compactnesses[high_index];
EXPECT_GE(
CenterDeviationBeadingStrategy(line_width, 0.6, low_compactness, low_compactness).getOptimalBeadCount(width),
CenterDeviationBeadingStrategy(line_width, 0.6, high_compactness, high_compactness).getOptimalBeadCount(width)
) << "When the compactness is low, the number of beads should always be greater or equal to when the compactness is high.";
}
}
}
}
}<commit_msg>'Fix' test 'Construction of Center-Deviation Strategy'.<commit_after>//Copyright (c) 2021 Ultimaker B.V.
//CuraEngine is released under the terms of the AGPLv3 or higher.
#include <gtest/gtest.h>
#include "../../src/BeadingStrategy/CenterDeviationBeadingStrategy.h" //Code under test.
namespace cura
{
/*!
* Tests calling the constructor of the CenterDeviationBeadingStrategy and
* whether it sets members correctly.
*/
TEST(CenterDeviationBeadingStrategy, Construction)
{
CenterDeviationBeadingStrategy strategy(400, 0.6, 0.5, 0.75);
EXPECT_EQ(strategy.getSplitMiddleThreshold(), 0.5) << "Split-middle threshold should be the one it's constructed with.";
EXPECT_EQ(strategy.getAddMiddleThreshold(), 0.75) << "Add-middle threshold should be the one it's constructed with.";
}
/*!
* Tests getting the optimal thickness with Center Deviation.
*
* This should simply be a multiplication of the line width, when using Center
* Deviation. It doesn't adjust the line widths by itself.
*/
TEST(CenterDeviationBeadingStrategy, GetOptimalThickness)
{
constexpr coord_t line_width = 400;
CenterDeviationBeadingStrategy strategy(line_width, 0.6, 0.5, 0.5);
EXPECT_EQ(strategy.getOptimalThickness(0), 0) << "With 0 beads, you'll fill 0 space.";
EXPECT_EQ(strategy.getOptimalThickness(1), line_width) << "With 1 bead, optimally you'll want to print that bead at the optimal line width.";
EXPECT_EQ(strategy.getOptimalThickness(4), 4 * line_width) << "With 4 beads, optimally fill 4 line widths.";
}
/*!
* Test getting the width at which we need to transition to a greater number of
* lines.
*/
TEST(CenterDeviationBeadingStrategy, GetTransitionThickness)
{
constexpr coord_t line_width = 400;
//Transition ratio 25%.
CenterDeviationBeadingStrategy strategy(line_width, 0.6, 0.25, 0.25);
EXPECT_EQ(strategy.getTransitionThickness(0), 0.25 * line_width) << "The transition from 0 beads to 1 happens at 25% line width.";
EXPECT_EQ(strategy.getTransitionThickness(1), 1.25 * line_width) << "The transition from 1 bead to 2 happens at 125% line width.";
EXPECT_EQ(strategy.getTransitionThickness(4), 4.25 * line_width) << "The transition from 4 beads to 5 happens at 4 + 25% line width.";
//Transition ratio 50%.
strategy = CenterDeviationBeadingStrategy(line_width, 0.6, 0.5, 0.5);
EXPECT_EQ(strategy.getTransitionThickness(0), 0.5 * line_width) << "The transition from 0 beads to 1 happens at 50% line width.";
EXPECT_EQ(strategy.getTransitionThickness(1), 1.5 * line_width) << "The transition from 1 bead to 2 happens at 150% line width.";
EXPECT_EQ(strategy.getTransitionThickness(5), 5.5 * line_width) << "The transition from 5 beads to 6 happens at 5 + 50% line width.";
//Transition ratio 95%.
strategy = CenterDeviationBeadingStrategy(line_width, 0.6, 0.95, 0.95);
EXPECT_EQ(strategy.getTransitionThickness(0), 0.95 * line_width) << "The transition from 0 beads to 1 happens at 95% line width.";
EXPECT_EQ(strategy.getTransitionThickness(1), 1.95 * line_width) << "The transition from 1 bead to 2 happens at 195% line width.";
EXPECT_EQ(strategy.getTransitionThickness(3), 3.95 * line_width) << "The transition from 3 beads to 4 happens at 3 + 95% line width.";
//Transition ratio 100%.
strategy = CenterDeviationBeadingStrategy(line_width, 0.6, 1, 1);
EXPECT_EQ(strategy.getTransitionThickness(0), line_width) << "Only transition to have a line if it fits completely.";
EXPECT_EQ(strategy.getTransitionThickness(1), 2 * line_width) << "Only transition to have two lines if they both fit completely.";
EXPECT_EQ(strategy.getTransitionThickness(2), 3 * line_width) << "Only transition to have three lines if they all fit completely.";
//Transition ratio 0%.
strategy = CenterDeviationBeadingStrategy(line_width, 0.6, 0, 0);
EXPECT_EQ(strategy.getTransitionThickness(0), 0) << "Always transition to 1 line. The minimum line width is 0 after all.";
EXPECT_EQ(strategy.getTransitionThickness(1), line_width) << "If 1 line fits completely, immediately transition to 2 lines.";
EXPECT_EQ(strategy.getTransitionThickness(6), 6 * line_width) << "If 6 lines fit completely, immediately transition to 7 lines.";
}
/*!
* Test getting the optimal bead count for a given shape width.
*/
TEST(CenterDeviationBeadingStrategy, GetOptimalBeadCount)
{
constexpr coord_t line_width = 400;
//Transition ratio 25%.
CenterDeviationBeadingStrategy strategy(line_width, 0.6, 0.25, 0.25);
//Anything below 25% line width should then produce 0 lines.
for(coord_t width = 0; width < 0.25 * line_width; width += 10)
{
EXPECT_EQ(strategy.getOptimalBeadCount(width), 0) << "Width is below the transition thickness from 0 to 1 line, so it should produce 0 lines.";
}
EXPECT_LE(strategy.getOptimalBeadCount(0.25 * line_width), 1) << "At exactly the transition thickness, either 0 or 1 line is acceptable.";
for(coord_t width = 0.25 * line_width + 1; width < 1.25 * line_width; width += 10)
{
EXPECT_EQ(strategy.getOptimalBeadCount(width), 1) << "Width is above the transition thickness from 0 to 1 line but below 1 to 2 lines, so it should produce 1 line.";
}
EXPECT_TRUE(strategy.getOptimalBeadCount(1.25 * line_width) == 1 || strategy.getOptimalBeadCount(1.25 * line_width) == 2) << "At exactly 125% line width, either 1 or 2 lines is acceptable.";
for(coord_t width = 1.25 * line_width + 1; width < 2.25 * line_width; width += 10)
{
EXPECT_EQ(strategy.getOptimalBeadCount(width), 2) << "Width is above the transition thickness from 1 to 2 lines but below 2 to 3 lines, so it should produce 2 lines.";
}
//Transition ratio 80%.
strategy = CenterDeviationBeadingStrategy(line_width, 0.6, 0.8, 0.8);
//Anything below 80% line width should then produce 0 lines.
for(coord_t width = 0; width < 0.8 * line_width; width += 10)
{
EXPECT_EQ(strategy.getOptimalBeadCount(width), 0) << "Width is below the transition thickness from 0 to 1 line, so it should produce 0 lines.";
}
EXPECT_LE(strategy.getOptimalBeadCount(0.8 * line_width), 1) << "At exactly the transition thickness, either 0 or 1 line is acceptable.";
for(coord_t width = 0.8 * line_width + 1; width < 1.8 * line_width; width += 10)
{
EXPECT_EQ(strategy.getOptimalBeadCount(width), 1) << "Width is above the transition thickness from 0 to 1 line but below 1 to 2 lines, so it should produce 1 line.";
}
EXPECT_TRUE(strategy.getOptimalBeadCount(1.8 * line_width) == 1 || strategy.getOptimalBeadCount(1.8 * line_width) == 2) << "At exactly 180% line width, either 1 or 2 lines is acceptable.";
for(coord_t width = 1.8 * line_width + 1; width < 2.8 * line_width; width += 10)
{
EXPECT_EQ(strategy.getOptimalBeadCount(width), 2) << "Width is above the transition thickness from 1 to 2 lines but below 2 to 3 lines, so it should produce 2 lines.";
}
}
/*!
* Tests whether the line compactness setting does what it is supposed to do,
* producing fewer, wider lines when the setting is high than when the setting
* is low.
*
* This is a test for requirements. The exact outcome of a function is not
* tested, but properties of the outcome is tested.
*/
TEST(CenterDeviationBeadingStrategy, LineCompactnessMonotonic)
{
constexpr coord_t line_width = 400;
constexpr coord_t widths[] = {0, 1, 99, 101, 150, 200, 299, 300, 301, 399, 400, 401, 410, 450, 500, 660, 770, 880, 910, 1000, 1200}; //Bunch of widths to test with.
constexpr float compactnesses[] = {0, 0.1, 0.2, 0.24, 0.25, 0.26, 0.3, 0.5, 0.7, 0.75, 0.99, 1}; //Bunch of line compactness factors to test with.
constexpr size_t num_compactnesses = sizeof(compactnesses) / sizeof(float);
for(coord_t width : widths)
{
for(size_t low_index = 0; low_index < num_compactnesses; ++low_index)
{
const float low_compactness = compactnesses[low_index];
for(size_t high_index = low_index; high_index < num_compactnesses; ++high_index)
{
const float high_compactness = compactnesses[high_index];
EXPECT_GE(
CenterDeviationBeadingStrategy(line_width, 0.6, low_compactness, low_compactness).getOptimalBeadCount(width),
CenterDeviationBeadingStrategy(line_width, 0.6, high_compactness, high_compactness).getOptimalBeadCount(width)
) << "When the compactness is low, the number of beads should always be greater or equal to when the compactness is high.";
}
}
}
}
}<|endoftext|>
|
<commit_before>/****************************************************************************
This file is part of the GLC-lib library.
Copyright (C) 2005-2008 Laurent Ribon (laumaya@users.sourceforge.net)
Version 1.0.0, packaged on August, 2008.
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_mesh2.cpp implementation of the GLC_Mesh2 class.
#include "glc_mesh2.h"
#include "glc_openglexception.h"
#include "glc_selectionmaterial.h"
#include <QtDebug>
//////////////////////////////////////////////////////////////////////
// Constructor Destructor
//////////////////////////////////////////////////////////////////////
GLC_Mesh2::GLC_Mesh2()
:GLC_Geometry("Mesh", false)
, m_CoordinateHash()
, m_CoordinateIndex()
, m_MaterialHash()
, m_MaterialIndex()
, m_NormalHash()
, m_NormalIndex()
, m_TextCoordinateHash()
, m_TextureIndex()
, m_NumberOfFaces(0)
, m_SelectionListID(0)
, m_IsSelected(false)
{
//qDebug() << "GLC_Mesh2::GLC_Mesh2" << getID();
}
GLC_Mesh2::GLC_Mesh2(const GLC_Mesh2 &meshToCopy)
: GLC_Geometry(meshToCopy)
, m_CoordinateHash(meshToCopy.m_CoordinateHash)
, m_CoordinateIndex(meshToCopy.m_CoordinateIndex)
, m_MaterialHash(meshToCopy.m_MaterialHash)
, m_MaterialIndex(meshToCopy.m_MaterialIndex)
, m_NormalHash(meshToCopy.m_NormalHash)
, m_NormalIndex(meshToCopy.m_NormalIndex)
, m_TextCoordinateHash(meshToCopy.m_TextCoordinateHash)
, m_TextureIndex(meshToCopy.m_TextureIndex)
, m_NumberOfFaces(meshToCopy.m_NumberOfFaces)
, m_SelectionListID(0)
, m_IsSelected(false)
{
//qDebug() << "GLC_Mesh2::GLC_Mesh2" << getID();
// Add this mesh to inner material
MaterialHash::const_iterator i= m_MaterialHash.begin();
while (i != m_MaterialHash.constEnd())
{
// update inner material use table
i.value()->addGLC_Geom(this);
++i;
}
}
GLC_Mesh2::~GLC_Mesh2(void)
{
//qDebug() << "GLC_Mesh2::~GLC_Mesh2" << getID();
m_CoordinateHash.clear();
m_CoordinateIndex.clear();
m_NormalHash.clear();
m_NormalIndex.clear();
m_TextCoordinateHash.clear();
m_TextureIndex.clear();
// delete mesh inner material
MaterialHash::const_iterator i= m_MaterialHash.begin();
while (i != m_MaterialHash.constEnd())
{
// delete the material if necessary
i.value()->delGLC_Geom(getID());
if (i.value()->isUnused()) delete i.value();
++i;
}
m_MaterialHash.clear();
m_MaterialIndex.clear();
// If display list is valid : delete it
if (0 != m_SelectionListID)
{
glDeleteLists(m_SelectionListID, 1);
}
}
/////////////////////////////////////////////////////////////////////
// Get Functions
//////////////////////////////////////////////////////////////////////
//! Return material index if Material is the same than a material already in the mesh
int GLC_Mesh2::materialIndex(const GLC_Material& mat) const
{
int index= -1;
MaterialHash::const_iterator iEntry= m_MaterialHash.begin();
while ((iEntry != m_MaterialHash.constEnd()) and !(*(iEntry.value()) == mat))
{
++iEntry;
}
if (iEntry != m_MaterialHash.constEnd())
{
index= iEntry.key();
}
return index;
}
// return the mesh bounding box
GLC_BoundingBox* GLC_Mesh2::getBoundingBox(void) const
{
GLC_BoundingBox* pBoundingBox= new GLC_BoundingBox();
Vector3dHash::const_iterator iEntry= m_CoordinateHash.begin();
while (iEntry != m_CoordinateHash.constEnd())
{
// Combine the vertex with the bounding box
pBoundingBox->combine(iEntry.value());
++iEntry;
}
return pBoundingBox;
}
// Return a copy of the current geometry
GLC_Geometry* GLC_Mesh2::clone() const
{
return new GLC_Mesh2(*this);
}
/////////////////////////////////////////////////////////////////////
// Set Functions
//////////////////////////////////////////////////////////////////////
// Add material to mesh
void GLC_Mesh2::addMaterial(int Index, GLC_Material* pMaterial)
{
if (pMaterial != NULL)
{
MaterialHash::const_iterator iMaterial= m_MaterialHash.find(Index);
// Check if there is a material at specified index
Q_ASSERT(iMaterial == m_MaterialHash.end());
// Add this geometry in the material use table
pMaterial->addGLC_Geom(this);
// Add the Material to Material hash table
m_MaterialHash.insert(Index, pMaterial);
// Test if the material is transparent
if (pMaterial->isTransparent() && (m_MaterialHash.size() == 1))
{
setTransparency(true);
}
else if (isTransparent() && !pMaterial->isTransparent())
{
setTransparency(false);
}
// Invalid the geometry
m_GeometryIsValid = false;
m_ListIsValid= false; // GLC_Mesh2 compatibility
}
}
// Remove material from the mesh
int GLC_Mesh2::removeMaterial(int index)
{
//qDebug() << "GLC_Mesh2::removeMaterial" << getID();
m_MaterialHash[index]->delGLC_Geom(getID());
// If the removed material is the last, change transparency
if((m_MaterialHash.size() == 1) && !getMaterial()->isTransparent())
{
setTransparency(false);
}
return m_MaterialHash.remove(index);
}
// Reverse mesh normal
void GLC_Mesh2::reverseNormal()
{
Vector3dHash::iterator iNormal= m_NormalHash.begin();
while (iNormal != m_NormalHash.constEnd())
{
// Reverse normal
iNormal.value().setInv();
++iNormal;
}
m_ListIsValid= false;
}
//////////////////////////////////////////////////////////////////////
// OpenGL Functions
//////////////////////////////////////////////////////////////////////
// if the geometry have a texture, load it
void GLC_Mesh2::glLoadTexture(void)
{
// Load texture of the master material
m_pMaterial->glLoadTexture();
MaterialHash::iterator iMaterial= m_MaterialHash.begin();
while (iMaterial != m_MaterialHash.constEnd())
{
// Load texture of mesh materials
iMaterial.value()->glLoadTexture();
++iMaterial;
}
}
// Specific glExecute method
void GLC_Mesh2::glExecute(GLenum Mode, bool isSelected, bool forceWire)
{
if (isSelected)
{
m_IsSelected= true;
// Define Geometry's property
glPropGeom(isSelected, forceWire);
// Geometry validity set to true
m_GeometryIsValid= true;
if (!m_ListIsValid)
{
// The list is not up to date or doesn't exist
createList(Mode);
}
else
{
glCallList(m_SelectionListID);
}
// OpenGL error handler
GLenum error= glGetError();
if (error != GL_NO_ERROR)
{
GLC_OpenGlException OpenGlException("GLC_Geometry::GlExecute ", error);
throw(OpenGlException);
}
m_IsSelected= false;
}
else
{
GLC_Geometry::glExecute(Mode, isSelected, forceWire);
}
}
// Specific createList method
void GLC_Mesh2::createList(GLenum Mode)
{
createSelectionList(Mode);
GLC_Geometry::createList(Mode);
}
// Create selection list
void GLC_Mesh2::createSelectionList(GLenum Mode)
{
m_IsSelected= true;
if(!m_SelectionListID) // The list doesn't exist
{
m_SelectionListID= glGenLists(1);
Q_ASSERT(0 != m_SelectionListID);
}
// List setting up
glNewList(m_SelectionListID, Mode);
// Geometry set up and display
glDraw(); // Virtual function defined in concrete class
glEndList();
m_IsSelected= false;
// OpenGL error handler
GLenum error= glGetError();
if (error != GL_NO_ERROR)
{
GLC_OpenGlException OpenGlException("GLC_Mesh2::createList ", error);
throw(OpenGlException);
}
}
// Virtual interface for OpenGL Geometry set up.
void GLC_Mesh2::glDraw()
{
//qDebug() << "GLC_Mesh2::glDraw ENTER";
// If the mesh is empty there is noting to do
if (m_CoordinateIndex.isEmpty()) return;
// Index face separator
const int separator= -1;
int CurrentMaterialIndex= -1;
bool IsNewFace= true;
for(int i=0; i < m_CoordinateIndex.size(); ++i)
{
if (m_CoordinateIndex.at(i) == separator)
{
Q_ASSERT((i != 0) && (!IsNewFace)); // the first index couldn't be a separator
// End of current face
glEnd();
// At the next round a new face will be create
IsNewFace=true;
}
else
{
if (CurrentMaterialIndex != m_MaterialIndex.at(i))
{ // If the material change, make it current
CurrentMaterialIndex= m_MaterialIndex.at(i);
//qDebug() << "GLC_Mesh2::glDraw : CurrentMaterialIndex" << CurrentMaterialIndex;
MaterialHash::const_iterator iMaterial= m_MaterialHash.find(CurrentMaterialIndex);
// Check if the key is already use
if (iMaterial != m_MaterialHash.end())
{
if (!m_IsSelected or (m_IsSelected and m_MaterialHash[CurrentMaterialIndex]->getAddRgbaTexture()))
{
m_MaterialHash[CurrentMaterialIndex]->glExecute();
}
if (m_IsSelected) GLC_SelectionMaterial::glExecute();
}
else
{
m_pMaterial->glExecute();
if (m_IsSelected) GLC_SelectionMaterial::glExecute();
}
}
if (IsNewFace)
{
if ((m_MaterialHash.find(CurrentMaterialIndex) != m_MaterialHash.end()) and m_MaterialHash[CurrentMaterialIndex]->getAddRgbaTexture())
{
glEnable(GL_TEXTURE_2D);
//qDebug() << "GLC_Mesh2::glDraw : Texture enabled";
}
else
{
glDisable(GL_TEXTURE_2D);
}
IsNewFace= false;
// New polygon creation
glBegin(GL_POLYGON);
} // end if isNewFace
// Vertex texture coordinate if necessary
if (i < m_TextureIndex.size())
{
glTexCoord2fv(m_TextCoordinateHash[m_TextureIndex.at(i)].return_dVect());
}
// Vertex Normal
Q_ASSERT(i < m_NormalIndex.size());
glNormal3fv(m_NormalHash[m_NormalIndex.at(i)].return_dVect());
// Vertex 3D coordinate
Q_ASSERT(i < m_CoordinateIndex.size());
glVertex3fv(m_CoordinateHash[m_CoordinateIndex.at(i)].return_dVect());
}
}
// OpenGL error handler
GLenum error= glGetError();
if (error != GL_NO_ERROR)
{
GLC_OpenGlException OpenGlException("GLC_Mesh2::GlDraw ", error);
throw(OpenGlException);
}
}
<commit_msg>When creating list, selectionList is always created in compile mode.<commit_after>/****************************************************************************
This file is part of the GLC-lib library.
Copyright (C) 2005-2008 Laurent Ribon (laumaya@users.sourceforge.net)
Version 1.0.0, packaged on August, 2008.
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_mesh2.cpp implementation of the GLC_Mesh2 class.
#include "glc_mesh2.h"
#include "glc_openglexception.h"
#include "glc_selectionmaterial.h"
#include <QtDebug>
//////////////////////////////////////////////////////////////////////
// Constructor Destructor
//////////////////////////////////////////////////////////////////////
GLC_Mesh2::GLC_Mesh2()
:GLC_Geometry("Mesh", false)
, m_CoordinateHash()
, m_CoordinateIndex()
, m_MaterialHash()
, m_MaterialIndex()
, m_NormalHash()
, m_NormalIndex()
, m_TextCoordinateHash()
, m_TextureIndex()
, m_NumberOfFaces(0)
, m_SelectionListID(0)
, m_IsSelected(false)
{
//qDebug() << "GLC_Mesh2::GLC_Mesh2" << getID();
}
GLC_Mesh2::GLC_Mesh2(const GLC_Mesh2 &meshToCopy)
: GLC_Geometry(meshToCopy)
, m_CoordinateHash(meshToCopy.m_CoordinateHash)
, m_CoordinateIndex(meshToCopy.m_CoordinateIndex)
, m_MaterialHash(meshToCopy.m_MaterialHash)
, m_MaterialIndex(meshToCopy.m_MaterialIndex)
, m_NormalHash(meshToCopy.m_NormalHash)
, m_NormalIndex(meshToCopy.m_NormalIndex)
, m_TextCoordinateHash(meshToCopy.m_TextCoordinateHash)
, m_TextureIndex(meshToCopy.m_TextureIndex)
, m_NumberOfFaces(meshToCopy.m_NumberOfFaces)
, m_SelectionListID(0)
, m_IsSelected(false)
{
//qDebug() << "GLC_Mesh2::GLC_Mesh2" << getID();
// Add this mesh to inner material
MaterialHash::const_iterator i= m_MaterialHash.begin();
while (i != m_MaterialHash.constEnd())
{
// update inner material use table
i.value()->addGLC_Geom(this);
++i;
}
}
GLC_Mesh2::~GLC_Mesh2(void)
{
//qDebug() << "GLC_Mesh2::~GLC_Mesh2" << getID();
m_CoordinateHash.clear();
m_CoordinateIndex.clear();
m_NormalHash.clear();
m_NormalIndex.clear();
m_TextCoordinateHash.clear();
m_TextureIndex.clear();
// delete mesh inner material
MaterialHash::const_iterator i= m_MaterialHash.begin();
while (i != m_MaterialHash.constEnd())
{
// delete the material if necessary
i.value()->delGLC_Geom(getID());
if (i.value()->isUnused()) delete i.value();
++i;
}
m_MaterialHash.clear();
m_MaterialIndex.clear();
// If display list is valid : delete it
if (0 != m_SelectionListID)
{
glDeleteLists(m_SelectionListID, 1);
}
}
/////////////////////////////////////////////////////////////////////
// Get Functions
//////////////////////////////////////////////////////////////////////
//! Return material index if Material is the same than a material already in the mesh
int GLC_Mesh2::materialIndex(const GLC_Material& mat) const
{
int index= -1;
MaterialHash::const_iterator iEntry= m_MaterialHash.begin();
while ((iEntry != m_MaterialHash.constEnd()) and !(*(iEntry.value()) == mat))
{
++iEntry;
}
if (iEntry != m_MaterialHash.constEnd())
{
index= iEntry.key();
}
return index;
}
// return the mesh bounding box
GLC_BoundingBox* GLC_Mesh2::getBoundingBox(void) const
{
GLC_BoundingBox* pBoundingBox= new GLC_BoundingBox();
Vector3dHash::const_iterator iEntry= m_CoordinateHash.begin();
while (iEntry != m_CoordinateHash.constEnd())
{
// Combine the vertex with the bounding box
pBoundingBox->combine(iEntry.value());
++iEntry;
}
return pBoundingBox;
}
// Return a copy of the current geometry
GLC_Geometry* GLC_Mesh2::clone() const
{
return new GLC_Mesh2(*this);
}
/////////////////////////////////////////////////////////////////////
// Set Functions
//////////////////////////////////////////////////////////////////////
// Add material to mesh
void GLC_Mesh2::addMaterial(int Index, GLC_Material* pMaterial)
{
if (pMaterial != NULL)
{
MaterialHash::const_iterator iMaterial= m_MaterialHash.find(Index);
// Check if there is a material at specified index
Q_ASSERT(iMaterial == m_MaterialHash.end());
// Add this geometry in the material use table
pMaterial->addGLC_Geom(this);
// Add the Material to Material hash table
m_MaterialHash.insert(Index, pMaterial);
// Test if the material is transparent
if (pMaterial->isTransparent() && (m_MaterialHash.size() == 1))
{
setTransparency(true);
}
else if (isTransparent() && !pMaterial->isTransparent())
{
setTransparency(false);
}
// Invalid the geometry
m_GeometryIsValid = false;
m_ListIsValid= false; // GLC_Mesh2 compatibility
}
}
// Remove material from the mesh
int GLC_Mesh2::removeMaterial(int index)
{
//qDebug() << "GLC_Mesh2::removeMaterial" << getID();
m_MaterialHash[index]->delGLC_Geom(getID());
// If the removed material is the last, change transparency
if((m_MaterialHash.size() == 1) && !getMaterial()->isTransparent())
{
setTransparency(false);
}
return m_MaterialHash.remove(index);
}
// Reverse mesh normal
void GLC_Mesh2::reverseNormal()
{
Vector3dHash::iterator iNormal= m_NormalHash.begin();
while (iNormal != m_NormalHash.constEnd())
{
// Reverse normal
iNormal.value().setInv();
++iNormal;
}
m_ListIsValid= false;
}
//////////////////////////////////////////////////////////////////////
// OpenGL Functions
//////////////////////////////////////////////////////////////////////
// if the geometry have a texture, load it
void GLC_Mesh2::glLoadTexture(void)
{
// Load texture of the master material
m_pMaterial->glLoadTexture();
MaterialHash::iterator iMaterial= m_MaterialHash.begin();
while (iMaterial != m_MaterialHash.constEnd())
{
// Load texture of mesh materials
iMaterial.value()->glLoadTexture();
++iMaterial;
}
}
// Specific glExecute method
void GLC_Mesh2::glExecute(GLenum Mode, bool isSelected, bool forceWire)
{
if (isSelected)
{
m_IsSelected= true;
// Define Geometry's property
glPropGeom(isSelected, forceWire);
// Geometry validity set to true
m_GeometryIsValid= true;
if (!m_ListIsValid)
{
// The list is not up to date or doesn't exist
createList(Mode);
}
else
{
glCallList(m_SelectionListID);
}
// OpenGL error handler
GLenum error= glGetError();
if (error != GL_NO_ERROR)
{
GLC_OpenGlException OpenGlException("GLC_Geometry::GlExecute ", error);
throw(OpenGlException);
}
m_IsSelected= false;
}
else
{
GLC_Geometry::glExecute(Mode, isSelected, forceWire);
}
}
// Specific createList method
void GLC_Mesh2::createList(GLenum Mode)
{
createSelectionList(GL_COMPILE);
GLC_Geometry::createList(Mode);
}
// Create selection list
void GLC_Mesh2::createSelectionList(GLenum Mode)
{
m_IsSelected= true;
if(!m_SelectionListID) // The list doesn't exist
{
m_SelectionListID= glGenLists(1);
Q_ASSERT(0 != m_SelectionListID);
}
// List setting up
glNewList(m_SelectionListID, Mode);
// Geometry set up and display
glDraw(); // Virtual function defined in concrete class
glEndList();
m_IsSelected= false;
// OpenGL error handler
GLenum error= glGetError();
if (error != GL_NO_ERROR)
{
GLC_OpenGlException OpenGlException("GLC_Mesh2::createList ", error);
throw(OpenGlException);
}
}
// Virtual interface for OpenGL Geometry set up.
void GLC_Mesh2::glDraw()
{
//qDebug() << "GLC_Mesh2::glDraw ENTER";
// If the mesh is empty there is noting to do
if (m_CoordinateIndex.isEmpty()) return;
// Index face separator
const int separator= -1;
int CurrentMaterialIndex= -1;
bool IsNewFace= true;
for(int i=0; i < m_CoordinateIndex.size(); ++i)
{
if (m_CoordinateIndex.at(i) == separator)
{
Q_ASSERT((i != 0) && (!IsNewFace)); // the first index couldn't be a separator
// End of current face
glEnd();
// At the next round a new face will be create
IsNewFace=true;
}
else
{
if (CurrentMaterialIndex != m_MaterialIndex.at(i))
{ // If the material change, make it current
CurrentMaterialIndex= m_MaterialIndex.at(i);
//qDebug() << "GLC_Mesh2::glDraw : CurrentMaterialIndex" << CurrentMaterialIndex;
MaterialHash::const_iterator iMaterial= m_MaterialHash.find(CurrentMaterialIndex);
// Check if the key is already use
if (iMaterial != m_MaterialHash.end())
{
if (!m_IsSelected or (m_IsSelected and m_MaterialHash[CurrentMaterialIndex]->getAddRgbaTexture()))
{
m_MaterialHash[CurrentMaterialIndex]->glExecute();
}
if (m_IsSelected) GLC_SelectionMaterial::glExecute();
}
else
{
m_pMaterial->glExecute();
if (m_IsSelected) GLC_SelectionMaterial::glExecute();
}
}
if (IsNewFace)
{
if ((m_MaterialHash.find(CurrentMaterialIndex) != m_MaterialHash.end()) and m_MaterialHash[CurrentMaterialIndex]->getAddRgbaTexture())
{
glEnable(GL_TEXTURE_2D);
//qDebug() << "GLC_Mesh2::glDraw : Texture enabled";
}
else
{
glDisable(GL_TEXTURE_2D);
}
IsNewFace= false;
// New polygon creation
glBegin(GL_POLYGON);
} // end if isNewFace
// Vertex texture coordinate if necessary
if (i < m_TextureIndex.size())
{
glTexCoord2fv(m_TextCoordinateHash[m_TextureIndex.at(i)].return_dVect());
}
// Vertex Normal
Q_ASSERT(i < m_NormalIndex.size());
glNormal3fv(m_NormalHash[m_NormalIndex.at(i)].return_dVect());
// Vertex 3D coordinate
Q_ASSERT(i < m_CoordinateIndex.size());
glVertex3fv(m_CoordinateHash[m_CoordinateIndex.at(i)].return_dVect());
}
}
// OpenGL error handler
GLenum error= glGetError();
if (error != GL_NO_ERROR)
{
GLC_OpenGlException OpenGlException("GLC_Mesh2::GlDraw ", error);
throw(OpenGlException);
}
}
<|endoftext|>
|
<commit_before>//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// 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 "platform/platform.h"
#include "app/version.h"
#include "console/console.h"
static const U32 csgVersionNumber = TORQUE_GAME_ENGINE;
U32 getVersionNumber()
{
return csgVersionNumber;
}
const char* getVersionString()
{
return TORQUE_GAME_ENGINE_VERSION_STRING;
}
/// TGE 0001
/// TGEA 0002
/// TGB 0003
/// TGEA 360 0004
/// TGE WII 0005
/// Torque 3D 0006
const char* getEngineProductString()
{
#ifndef TORQUE_ENGINE_PRODUCT
return "Torque Engine";
#else
switch (TORQUE_ENGINE_PRODUCT)
{
case 0001:
return "Torque Game Engine";
case 0002:
return "Torque Game Engine Advanced";
case 0003:
return "Torque 2D";
case 0004:
return "Torque 360";
case 0005:
return "Torque for Wii";
case 0006:
return "Torque 3D";
default:
return "Torque Engine";
};
#endif
}
const char* getCompileTimeString()
{
return __DATE__ " at " __TIME__;
}
//----------------------------------------------------------------
ConsoleFunctionGroupBegin( CompileInformation, "Functions to get version information about the current executable." );
ConsoleFunction( getVersionNumber, S32, 1, 1, "Get the version of the build, as a string.\n\n"
"@ingroup Debugging")
{
return getVersionNumber();
}
ConsoleFunction( getVersionString, const char*, 1, 1, "Get the version of the build, as a string.\n\n"
"@ingroup Debugging")
{
return getVersionString();
}
ConsoleFunction( getEngineName, const char*, 1, 1, "Get the name of the engine product that this is running from, as a string.\n\n"
"@ingroup Debugging")
{
return getEngineProductString();
}
ConsoleFunction( getCompileTimeString, const char*, 1, 1, "Get the time of compilation.\n\n"
"@ingroup Debugging")
{
return getCompileTimeString();
}
ConsoleFunction( getBuildString, const char*, 1, 1, "Get the type of build, \"Debug\" or \"Release\".\n\n"
"@ingroup Debugging")
{
#ifdef TORQUE_DEBUG
return "Debug";
#else
return "Release";
#endif
}
ConsoleFunctionGroupEnd( CompileInformation );
ConsoleFunction(isDemo, bool, 1, 1, "")
{
#ifdef TORQUE_DEMO
return true;
#else
return false;
#endif
}
ConsoleFunction(isWebDemo, bool, 1, 1, "")
{
#ifdef TORQUE_DEMO
return Platform::getWebDeployment();
#else
return false;
#endif
}<commit_msg>Fill in missing case for getEngineProductString switch block.<commit_after>//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// 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 "platform/platform.h"
#include "app/version.h"
#include "console/console.h"
static const U32 csgVersionNumber = TORQUE_GAME_ENGINE;
U32 getVersionNumber()
{
return csgVersionNumber;
}
const char* getVersionString()
{
return TORQUE_GAME_ENGINE_VERSION_STRING;
}
/// TGE 0001
/// TGEA 0002
/// TGB 0003
/// TGEA 360 0004
/// TGE WII 0005
/// Torque 3D 0006
const char* getEngineProductString()
{
#ifndef TORQUE_ENGINE_PRODUCT
return "Torque Engine";
#else
switch (TORQUE_ENGINE_PRODUCT)
{
case 0001:
return "Torque Game Engine";
case 0002:
return "Torque Game Engine Advanced";
case 0003:
return "Torque 2D";
case 0004:
return "Torque 360";
case 0005:
return "Torque for Wii";
case 0006:
return "Torque 3D";
case 0007:
return "Torque 3D MIT";
default:
return "Torque Engine";
};
#endif
}
const char* getCompileTimeString()
{
return __DATE__ " at " __TIME__;
}
//----------------------------------------------------------------
ConsoleFunctionGroupBegin( CompileInformation, "Functions to get version information about the current executable." );
ConsoleFunction( getVersionNumber, S32, 1, 1, "Get the version of the build, as a string.\n\n"
"@ingroup Debugging")
{
return getVersionNumber();
}
ConsoleFunction( getVersionString, const char*, 1, 1, "Get the version of the build, as a string.\n\n"
"@ingroup Debugging")
{
return getVersionString();
}
ConsoleFunction( getEngineName, const char*, 1, 1, "Get the name of the engine product that this is running from, as a string.\n\n"
"@ingroup Debugging")
{
return getEngineProductString();
}
ConsoleFunction( getCompileTimeString, const char*, 1, 1, "Get the time of compilation.\n\n"
"@ingroup Debugging")
{
return getCompileTimeString();
}
ConsoleFunction( getBuildString, const char*, 1, 1, "Get the type of build, \"Debug\" or \"Release\".\n\n"
"@ingroup Debugging")
{
#ifdef TORQUE_DEBUG
return "Debug";
#else
return "Release";
#endif
}
ConsoleFunctionGroupEnd( CompileInformation );
ConsoleFunction(isDemo, bool, 1, 1, "")
{
#ifdef TORQUE_DEMO
return true;
#else
return false;
#endif
}
ConsoleFunction(isWebDemo, bool, 1, 1, "")
{
#ifdef TORQUE_DEMO
return Platform::getWebDeployment();
#else
return false;
#endif
}<|endoftext|>
|
<commit_before>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
// Software Guide : BeginCommandLineArgs
// INPUTS: {XX.tif}
// OUTPUTS: {XX.txt}
// Software Guide : EndCommandLineArgs
// Software Guide : BeginLatex
//
// This example shows the basic approch to perform
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
#include "otbImage.h"
#include "otbVectorImage.h"
#include "otbImageFileReader.h"
#include "otbImageFileWriter.h"
#include "otbMeanShiftImageFilter.h"
#include "itkLabelImageToLabelMapFilter.h"
#include "otbAttributesMapLabelObject.h"
#include "itkLabelMap.h"
#include "otbShapeAttributesLabelMapFilter.h"
#include "otbStatisticsAttributesLabelMapFilter.h"
#include "otbRadiometricAttributesLabelMapFilter.h"
#include "otbAttributesMapOpeningLabelMapFilter.h"
#include "itkLabelMapToLabelImageFilter.h"
int main(int argc, char * argv[])
{
if(argc != 10)
{
std::cerr<<"Usage: "<<argv[0]<<" reffname outfname attribute_name lowerThan tresh spatialRadius rangeRadius minregionsize scale"<<std::endl;
return EXIT_FAILURE;
}
const char * reffname = argv[1];
const char * outfname = argv[2];
const char * attr = argv[3];
bool lowerThan = atoi(argv[4]);
double thresh = atof(argv[5]);
const unsigned int spatialRadius = atoi(argv[6]);
const double rangeRadius = atof(argv[7]);
const unsigned int minRegionSize = atoi(argv[8]);
const double scale = atoi(argv[9]);
const unsigned int Dimension = 2;
// Labeled image type
typedef unsigned short LabelType;
typedef double PixelType;
typedef otb::Image<LabelType,Dimension> LabeledImageType;
typedef otb::Image<PixelType,Dimension> ImageType;
typedef otb::VectorImage<PixelType,Dimension> VectorImageType;
typedef otb::ImageFileReader<LabeledImageType> LabeledReaderType;
typedef otb::ImageFileReader<ImageType> ReaderType;
typedef otb::ImageFileReader<VectorImageType> VectorReaderType;
typedef otb::ImageFileWriter<LabeledImageType> WriterType;
// Label map typedef
typedef otb::AttributesMapLabelObject<LabelType,Dimension,double> LabelObjectType;
typedef itk::LabelMap<LabelObjectType> LabelMapType;
typedef itk::LabelImageToLabelMapFilter<LabeledImageType,LabelMapType> LabelMapFilterType;
typedef otb::ShapeAttributesLabelMapFilter<LabelMapType> ShapeLabelMapFilterType;
typedef otb::StatisticsAttributesLabelMapFilter<LabelMapType,ImageType> StatisticsLabelMapFilterType;
typedef otb::RadiometricAttributesLabelMapFilter<LabelMapType,VectorImageType> RadiometricLabelMapFilterType;
typedef otb::AttributesMapOpeningLabelMapFilter<LabelMapType> OpeningLabelMapFilterType;
typedef itk::LabelMapToLabelImageFilter<LabelMapType,LabeledImageType> LabelMapToLabeledImageFilterType;
ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName(reffname);
//std::cout << reffname << std::endl;
//reader->Update();
//std::cout << reffname << std::endl;
VectorReaderType::Pointer vreader = VectorReaderType::New();
vreader->SetFileName(reffname);
//Segment the ref image using Mean Shift
typedef otb::MeanShiftImageFilter<ImageType,ImageType, LabeledImageType> FilterType;
FilterType::Pointer filter = FilterType::New();
filter->SetSpatialRadius(spatialRadius);
filter->SetRangeRadius(rangeRadius);
filter->SetMinimumRegionSize(minRegionSize);
filter->SetScale(scale);
filter->SetInput(reader->GetOutput());
LabelMapFilterType::Pointer labelMapFilter = LabelMapFilterType::New();
labelMapFilter->SetInput(filter->GetLabeledClusteredOutput());
labelMapFilter->SetBackgroundValue(itk::NumericTraits<LabelType>::max());
ShapeLabelMapFilterType::Pointer shapeLabelMapFilter = ShapeLabelMapFilterType::New();
shapeLabelMapFilter->SetInput(labelMapFilter->GetOutput());
StatisticsLabelMapFilterType::Pointer statisticsLabelMapFilter = StatisticsLabelMapFilterType::New();
statisticsLabelMapFilter->SetInput1(shapeLabelMapFilter->GetOutput());
statisticsLabelMapFilter->SetInput2(reader->GetOutput());
statisticsLabelMapFilter->Update();
RadiometricLabelMapFilterType::Pointer radiometricLabelMapFilter = RadiometricLabelMapFilterType::New();
radiometricLabelMapFilter->SetInput1(statisticsLabelMapFilter->GetOutput());
radiometricLabelMapFilter->SetInput2(vreader->GetOutput());
//radiometricLabelMapFilter->SetReducedAttributeSet(false);
radiometricLabelMapFilter->SetRedChannelIndex(1);
radiometricLabelMapFilter->SetNIRChannelIndex(2);
radiometricLabelMapFilter->Update();
OpeningLabelMapFilterType::Pointer opening = OpeningLabelMapFilterType::New();
opening->SetInput(radiometricLabelMapFilter->GetOutput());
opening->SetAttributeName(attr);
opening->SetReverseOrdering(lowerThan);
opening->SetLambda(thresh);
LabelMapToLabeledImageFilterType::Pointer labelMap2LabeledImage = LabelMapToLabeledImageFilterType::New();
labelMap2LabeledImage->SetInput(opening->GetOutput());
WriterType::Pointer writer = WriterType::New();
writer->SetFileName(outfname);
writer->SetInput(labelMap2LabeledImage->GetOutput());
writer->Update();
return EXIT_SUCCESS;
}
<commit_msg>DOC:obia<commit_after>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
// Software Guide : BeginCommandLineArgs
// INPUTS: {XX.tif}
// OUTPUTS: {XX.txt}
// Software Guide : EndCommandLineArgs
// Software Guide : BeginLatex
//
// This example shows the basic approch to perform object based analysis on a image.
// The input image is firstly segmented using the \doxygen{otb}{MeanShiftImageFilter}
// Then each segmented region is converted to a Map of labeled objects.
// After the \doxygen{otb}{RadiometricAttributesLabelMapFilter} computes computes
// radiometric attributes for each object.
// Images are supposed to be standard 4-bands image (B,G,R,NIR). The
// index of each channel can be set via the Set***ChannelIndex()
// accessors.
//
// This filter internally applies the
// StatisticsAttributesLabelMapFilter to the following features:
// \begin{itemize}
// \item GEMI
// \item NDVI
// \item IR
// \item IC
// \item IB
// \item NDWI2
// \item Intensity
// \item and original B, G, R and NIR channels
// \end{itemize},
//
//
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
#include "otbImage.h"
#include "otbVectorImage.h"
#include "otbImageFileReader.h"
#include "otbImageFileWriter.h"
#include "otbMeanShiftImageFilter.h"
#include "itkLabelImageToLabelMapFilter.h"
#include "otbAttributesMapLabelObject.h"
#include "itkLabelMap.h"
#include "otbShapeAttributesLabelMapFilter.h"
#include "otbStatisticsAttributesLabelMapFilter.h"
#include "otbRadiometricAttributesLabelMapFilter.h"
#include "otbAttributesMapOpeningLabelMapFilter.h"
#include "itkLabelMapToLabelImageFilter.h"
int main(int argc, char * argv[])
{
if(argc != 10)
{
std::cerr<<"Usage: "<<argv[0]<<" reffname outfname attribute_name lowerThan tresh spatialRadius rangeRadius minregionsize scale"<<std::endl;
return EXIT_FAILURE;
}
const char * reffname = argv[1];
const char * outfname = argv[2];
const char * attr = argv[3];
bool lowerThan = atoi(argv[4]);
double thresh = atof(argv[5]);
const unsigned int spatialRadius = atoi(argv[6]);
const double rangeRadius = atof(argv[7]);
const unsigned int minRegionSize = atoi(argv[8]);
const double scale = atoi(argv[9]);
const unsigned int Dimension = 2;
// Labeled image type
typedef unsigned short LabelType;
typedef double PixelType;
typedef otb::Image<LabelType,Dimension> LabeledImageType;
typedef otb::Image<PixelType,Dimension> ImageType;
typedef otb::VectorImage<PixelType,Dimension> VectorImageType;
typedef otb::ImageFileReader<LabeledImageType> LabeledReaderType;
typedef otb::ImageFileReader<ImageType> ReaderType;
typedef otb::ImageFileReader<VectorImageType> VectorReaderType;
typedef otb::ImageFileWriter<LabeledImageType> WriterType;
// Label map typedef
typedef otb::AttributesMapLabelObject<LabelType,Dimension,double> LabelObjectType;
typedef itk::LabelMap<LabelObjectType> LabelMapType;
typedef itk::LabelImageToLabelMapFilter<LabeledImageType,LabelMapType> LabelMapFilterType;
typedef otb::ShapeAttributesLabelMapFilter<LabelMapType> ShapeLabelMapFilterType;
typedef otb::StatisticsAttributesLabelMapFilter<LabelMapType,ImageType> StatisticsLabelMapFilterType;
typedef otb::RadiometricAttributesLabelMapFilter<LabelMapType,VectorImageType> RadiometricLabelMapFilterType;
typedef otb::AttributesMapOpeningLabelMapFilter<LabelMapType> OpeningLabelMapFilterType;
typedef itk::LabelMapToLabelImageFilter<LabelMapType,LabeledImageType> LabelMapToLabeledImageFilterType;
ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName(reffname);
//std::cout << reffname << std::endl;
//reader->Update();
//std::cout << reffname << std::endl;
VectorReaderType::Pointer vreader = VectorReaderType::New();
vreader->SetFileName(reffname);
//Segment the ref image using Mean Shift
typedef otb::MeanShiftImageFilter<ImageType,ImageType, LabeledImageType> FilterType;
FilterType::Pointer filter = FilterType::New();
filter->SetSpatialRadius(spatialRadius);
filter->SetRangeRadius(rangeRadius);
filter->SetMinimumRegionSize(minRegionSize);
filter->SetScale(scale);
filter->SetInput(reader->GetOutput());
LabelMapFilterType::Pointer labelMapFilter = LabelMapFilterType::New();
labelMapFilter->SetInput(filter->GetLabeledClusteredOutput());
labelMapFilter->SetBackgroundValue(itk::NumericTraits<LabelType>::max());
ShapeLabelMapFilterType::Pointer shapeLabelMapFilter = ShapeLabelMapFilterType::New();
shapeLabelMapFilter->SetInput(labelMapFilter->GetOutput());
StatisticsLabelMapFilterType::Pointer statisticsLabelMapFilter = StatisticsLabelMapFilterType::New();
statisticsLabelMapFilter->SetInput1(shapeLabelMapFilter->GetOutput());
statisticsLabelMapFilter->SetInput2(reader->GetOutput());
statisticsLabelMapFilter->Update();
RadiometricLabelMapFilterType::Pointer radiometricLabelMapFilter = RadiometricLabelMapFilterType::New();
radiometricLabelMapFilter->SetInput1(statisticsLabelMapFilter->GetOutput());
radiometricLabelMapFilter->SetInput2(vreader->GetOutput());
//radiometricLabelMapFilter->SetReducedAttributeSet(false);
radiometricLabelMapFilter->SetRedChannelIndex(1);
radiometricLabelMapFilter->SetNIRChannelIndex(2);
radiometricLabelMapFilter->Update();
OpeningLabelMapFilterType::Pointer opening = OpeningLabelMapFilterType::New();
opening->SetInput(radiometricLabelMapFilter->GetOutput());
opening->SetAttributeName(attr);
opening->SetReverseOrdering(lowerThan);
opening->SetLambda(thresh);
LabelMapToLabeledImageFilterType::Pointer labelMap2LabeledImage = LabelMapToLabeledImageFilterType::New();
labelMap2LabeledImage->SetInput(opening->GetOutput());
WriterType::Pointer writer = WriterType::New();
writer->SetFileName(outfname);
writer->SetInput(labelMap2LabeledImage->GetOutput());
writer->Update();
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before>/** @file test out VecVertices visitor
*/
#ifdef __WITH_PCL // PCL support required for these tests
#include "core/visitors/visitorvertices.h"
#include "core/exception.h"
#include "ts/ts.h"
using namespace std;
using namespace cv;
using namespace sem;
namespace {
/**
* @brief test class around VisitorVecVertices
*/
class VisitorVecVerticesTest : public ::testing::Test
{
protected:
virtual void SetUp()
{
to_.Reset();
}
VisitorVecVertices to_; ///< test object
};
TEST_F(VisitorVecVerticesTest, EmptyVecVertices)
{
EXPECT_TRUE(to_(VecVertices()).empty());
}
TEST_F(VisitorVecVerticesTest, EmptyVecVertices_Size)
{
EXPECT_SIZE(0, to_(VecVertices()));
}
template<class T>
class VisitorVecVerticesTypedTest : public VisitorVecVerticesTest
{
protected:
virtual void SetUp()
{
to_.Reset();
}
//typedef std::list<T> List;
static T shared_;
T value_;
};
/**
* @brief Value per type to use in fixtures below.
*/
template<class T>
struct Twos_
{
static const T val;
};
///< Register static variables to work with inside tests
template<> const float Twos_<float>::val = 2.f;
template<> const int Twos_<int>::val = 2;
template<> const uchar Twos_<uchar>::val = 2;
template<> const Mat1f Twos_<Mat1f>::val = Mat1f(1, 1, 2.f);
typedef ::testing::Types<Mat1f, float, int, uchar> VisitorTypes;
TYPED_TEST_CASE(VisitorVecVerticesTypedTest, VisitorTypes);
TYPED_TEST(VisitorVecVerticesTypedTest, Twos)
{
TypeParam in = Twos_<TypeParam >::val;
VecVertices vv = to_(in);
EXPECT_SIZE(1, vv);
EXPECT_SIZE(1, vv[0].vertices);
EXPECT_EQ(static_cast<uint32_t>(2), vv[0].vertices[0]);
}
} // annonymous namespace for VecVertices visitors' test fixtures
#else // __WITH_PCL
#warning "Skipping building VecVertices visitor unit tests due to no pcl support."
#endif // __WITH_PCL
<commit_msg>add test similar to scalars to cover cloud<commit_after>/** @file test out VecVertices visitor
*/
#ifdef __WITH_PCL // PCL support required for these tests
#include "core/visitors/visitorvertices.h"
#include "core/exception.h"
#include "ts/ts.h"
using namespace std;
using namespace cv;
using namespace sem;
namespace {
/**
* @brief test class around VisitorVecVertices
*/
class VisitorVecVerticesTest : public ::testing::Test
{
protected:
virtual void SetUp()
{
to_.Reset();
}
VisitorVecVertices to_; ///< test object
};
TEST_F(VisitorVecVerticesTest, EmptyVecVertices)
{
EXPECT_TRUE(to_(VecVertices()).empty());
}
TEST_F(VisitorVecVerticesTest, EmptyVecVertices_Size)
{
EXPECT_SIZE(0, to_(VecVertices()));
}
TEST_F(VisitorVecVerticesTest, Twos_cloud)
{
CloudXYZ::Ptr in = Mat2PointCloud(Mat1f(4, 3, 2));
VecVertices vv = to_(in);
EXPECT_SIZE(4, vv);
EXPECT_SIZE(4, vv[0].vertices);
for(uint32_t i=0; i<in->height; i++) {
for(uint32_t j=0; j<in->width; j++) {
EXPECT_EQ(static_cast<uint32_t>(2), vv[i].vertices[j]);
}
}
}
template<class T>
class VisitorVecVerticesTypedTest : public VisitorVecVerticesTest
{
protected:
virtual void SetUp()
{
to_.Reset();
}
//typedef std::list<T> List;
static T shared_;
T value_;
};
/**
* @brief Value per type to use in fixtures below.
*/
template<class T>
struct Twos_
{
static const T val;
};
///< Register static variables to work with inside tests
template<> const float Twos_<float>::val = 2.f;
template<> const int Twos_<int>::val = 2;
template<> const uchar Twos_<uchar>::val = 2;
template<> const Mat1f Twos_<Mat1f>::val = Mat1f(1, 1, 2.f);
typedef ::testing::Types<Mat1f, float, int, uchar> VisitorTypes;
TYPED_TEST_CASE(VisitorVecVerticesTypedTest, VisitorTypes);
TYPED_TEST(VisitorVecVerticesTypedTest, Twos)
{
TypeParam in = Twos_<TypeParam >::val;
VecVertices vv = to_(in);
EXPECT_SIZE(1, vv);
EXPECT_SIZE(1, vv[0].vertices);
EXPECT_EQ(static_cast<uint32_t>(2), vv[0].vertices[0]);
}
} // annonymous namespace for VecVertices visitors' test fixtures
#else // __WITH_PCL
#warning "Skipping building VecVertices visitor unit tests due to no pcl support."
#endif // __WITH_PCL
<|endoftext|>
|
<commit_before>/******************************************************************************
* This file is part of dirtsand. *
* *
* dirtsand is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* dirtsand 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 dirtsand. If not, see <http://www.gnu.org/licenses/>. *
******************************************************************************/
#include "GameServer_Private.h"
#include "settings.h"
#include "errors.h"
#include <unistd.h>
#include <dirent.h>
#include <sys/stat.h>
extern bool s_commdebug;
#define START_REPLY(msgId) \
client.m_buffer.truncate(); \
client.m_buffer.write<uint16_t>(msgId)
#define SEND_REPLY() \
DS::CryptSendBuffer(client.m_sock, client.m_crypt, \
client.m_buffer.buffer(), client.m_buffer.size())
void game_client_init(GameClient_Private& client)
{
/* Game client header: size, account uuid, age instance uuid */
uint32_t size = DS::RecvValue<uint32_t>(client.m_sock);
DS_PASSERT(size == 36);
DS::Uuid clientUuid, connUuid;
DS::RecvBuffer(client.m_sock, clientUuid.m_bytes, sizeof(clientUuid.m_bytes));
DS::RecvBuffer(client.m_sock, connUuid.m_bytes, sizeof(connUuid.m_bytes));
/* Establish encryption */
uint8_t msgId = DS::RecvValue<uint8_t>(client.m_sock);
DS_PASSERT(msgId == DS::e_CliToServConnect);
uint8_t msgSize = DS::RecvValue<uint8_t>(client.m_sock);
DS_PASSERT(msgSize == 66);
uint8_t Y[64];
DS::RecvBuffer(client.m_sock, Y, 64);
BYTE_SWAP_BUFFER(Y, 64);
uint8_t serverSeed[7];
uint8_t sharedKey[7];
DS::CryptEstablish(serverSeed, sharedKey, DS::Settings::CryptKey(DS::e_KeyGame_N),
DS::Settings::CryptKey(DS::e_KeyGame_K), Y);
client.m_buffer.truncate();
client.m_buffer.write<uint8_t>(DS::e_ServToCliEncrypt);
client.m_buffer.write<uint8_t>(9);
client.m_buffer.writeBytes(serverSeed, 7);
DS::SendBuffer(client.m_sock, client.m_buffer.buffer(), client.m_buffer.size());
client.m_crypt = DS::CryptStateInit(sharedKey, 7);
}
GameHost_Private* find_game_host(uint32_t ageMcpId)
{
pthread_mutex_lock(&s_gameHostMutex);
hostmap_t::iterator host_iter = s_gameHosts.find(ageMcpId);
GameHost_Private* host = 0;
if (host_iter != s_gameHosts.end())
host = host_iter->second;
pthread_mutex_unlock(&s_gameHostMutex);
return host ? host : start_game_host(ageMcpId);
}
void cb_ping(GameClient_Private& client)
{
START_REPLY(e_GameToCli_PingReply);
// Ping time
client.m_buffer.write<uint32_t>(DS::CryptRecvValue<uint32_t>(client.m_sock, client.m_crypt));
SEND_REPLY();
}
void cb_join(GameClient_Private& client)
{
START_REPLY(e_GameToCli_JoinAgeReply);
// Trans ID
client.m_buffer.write<uint32_t>(DS::CryptRecvValue<uint32_t>(client.m_sock, client.m_crypt));
uint32_t mcpId = DS::CryptRecvValue<uint32_t>(client.m_sock, client.m_crypt);
client.m_host = find_game_host(mcpId);
DS_PASSERT(client.m_host != 0);
Game_ClientMessage msg;
msg.m_client = &client;
DS::CryptRecvBuffer(client.m_sock, client.m_crypt, client.m_clientId.m_bytes,
sizeof(client.m_clientId.m_bytes));
client.m_clientInfo.set_PlayerId(DS::CryptRecvValue<uint32_t>(client.m_sock, client.m_crypt));
if (client.m_clientInfo.m_PlayerId == 0) {
client.m_buffer.write<uint32_t>(DS::e_NetInvalidParameter);
SEND_REPLY();
return;
}
// Get player info from the vault
Auth_NodeInfo nodeInfo;
nodeInfo.m_client = &client;
nodeInfo.m_node.set_NodeIdx(client.m_clientInfo.m_PlayerId);
s_authChannel.putMessage(e_VaultFetchNode, reinterpret_cast<void*>(&nodeInfo));
DS::FifoMessage reply = client.m_channel.getMessage();
if (reply.m_messageType != DS::e_NetSuccess) {
client.m_buffer.write<uint32_t>(reply.m_messageType);
SEND_REPLY();
return;
}
msg.m_client->m_clientInfo.set_PlayerName(nodeInfo.m_node.m_IString64_1);
msg.m_client->m_clientInfo.set_CCRLevel(0);
client.m_host->m_channel.putMessage(e_GameJoinAge, reinterpret_cast<void*>(&msg));
reply = client.m_channel.getMessage();
client.m_buffer.write<uint32_t>(reply.m_messageType);
SEND_REPLY();
pthread_mutex_lock(&client.m_host->m_clientMutex);
client.m_host->m_clients[client.m_clientInfo.m_PlayerId] = &client;
pthread_mutex_unlock(&client.m_host->m_clientMutex);
}
void cb_netmsg(GameClient_Private& client)
{
Game_PropagateMessage msg;
msg.m_client = &client;
msg.m_messageType = DS::CryptRecvValue<uint32_t>(client.m_sock, client.m_crypt);
uint32_t size = DS::CryptRecvValue<uint32_t>(client.m_sock, client.m_crypt);
uint8_t* buffer = new uint8_t[size];
DS::CryptRecvBuffer(client.m_sock, client.m_crypt, buffer, size);
msg.m_message = DS::Blob::Steal(buffer, size);
client.m_host->m_channel.putMessage(e_GamePropagate, reinterpret_cast<void*>(&msg));
client.m_channel.getMessage();
}
void cb_gameMgrMsg(GameClient_Private& client)
{
uint32_t size = DS::CryptRecvValue<uint32_t>(client.m_sock, client.m_crypt);
uint8_t* buffer = new uint8_t[size];
DS::CryptRecvBuffer(client.m_sock, client.m_crypt, buffer, size);
printf("GAME MGR MSG");
for (size_t i=0; i<size; ++i) {
if ((i % 16) == 0)
printf("\n ");
else if ((i % 16) == 8)
printf(" ");
printf("%02X ", buffer[i]);
}
printf("\n");
delete[] buffer;
}
void* wk_gameWorker(void* sockp)
{
GameClient_Private client;
client.m_sock = reinterpret_cast<DS::SocketHandle>(sockp);
client.m_host = 0;
try {
game_client_init(client);
} catch (DS::AssertException ex) {
fprintf(stderr, "[Game] Assertion failed at %s:%ld: %s\n",
ex.m_file, ex.m_line, ex.m_cond);
return 0;
} catch (DS::SockHup) {
// Socket closed...
return 0;
}
try {
for ( ;; ) {
uint16_t msgId = DS::CryptRecvValue<uint16_t>(client.m_sock, client.m_crypt);
switch (msgId) {
case e_CliToGame_PingRequest:
cb_ping(client);
break;
case e_CliToGame_JoinAgeRequest:
cb_join(client);
break;
case e_CliToGame_Propagatebuffer:
DS_PASSERT(client.m_host != 0);
cb_netmsg(client);
break;
case e_CliToGame_GameMgrMsg:
DS_PASSERT(client.m_host != 0);
cb_gameMgrMsg(client);
break;
default:
/* Invalid message */
fprintf(stderr, "[Game] Got invalid message ID %d from %s\n",
msgId, DS::SockIpAddress(client.m_sock).c_str());
DS::CloseSock(client.m_sock);
throw DS::SockHup();
}
}
} catch (DS::AssertException ex) {
fprintf(stderr, "[Game] Assertion failed at %s:%ld: %s\n",
ex.m_file, ex.m_line, ex.m_cond);
} catch (DS::SockHup) {
// Socket closed...
}
pthread_mutex_lock(&client.m_host->m_clientMutex);
client.m_host->m_clients.erase(client.m_clientInfo.m_PlayerId);
pthread_mutex_unlock(&client.m_host->m_clientMutex);
Game_ClientMessage msg;
msg.m_client = &client;
client.m_host->m_channel.putMessage(e_GameDisconnect, reinterpret_cast<void*>(&msg));
client.m_channel.getMessage();
DS::CryptStateFree(client.m_crypt);
DS::FreeSock(client.m_sock);
return 0;
}
static int sel_age(const dirent* de)
{
return strcmp(strrchr(de->d_name, '.'), ".age") == 0;
}
Game_AgeInfo age_parse(FILE* stream)
{
char lnbuffer[4096];
Game_AgeInfo age;
while (fgets(lnbuffer, 4096, stream)) {
std::vector<DS::String> line = DS::String(lnbuffer).strip('#').split('=');
if (line.size() == 0)
continue;
if (line.size() != 2) {
fprintf(stderr, "[Game] Invalid AGE line: %s", lnbuffer);
continue;
}
if (line[0] == "StartDateTime") {
age.m_startTime = line[1].toUint(10);
} else if (line[0] == "DayLength") {
age.m_dayLength = line[1].toDouble();
} else if (line[0] == "MaxCapacity") {
age.m_maxCapacity = line[1].toUint(10);
} else if (line[0] == "LingerTime") {
age.m_lingerTime = line[1].toUint(10);
} else if (line[0] == "SequencePrefix") {
age.m_seqPrefix = line[1].toInt(10);
} else if (line[0] == "ReleaseVersion" || line[0] == "Page") {
// Ignored
} else {
fprintf(stderr, "[Game] Invalid AGE line: %s", lnbuffer);
}
}
return age;
}
void DS::GameServer_Init()
{
dirent** dirls;
int count = scandir(DS::Settings::AgePath(), &dirls, &sel_age, &alphasort);
if (count < 0) {
fprintf(stderr, "[Game] Error reading age descriptors: %s\n", strerror(errno));
} else if (count == 0) {
fprintf(stderr, "[Game] Warning: No age descriptors found!\n");
free(dirls);
} else {
for (int i=0; i<count; ++i) {
DS::String filename = DS::String::Format("%s/%s", DS::Settings::AgePath(), dirls[i]->d_name);
FILE* ageFile = fopen(filename.c_str(), "r");
if (ageFile) {
char magic[12];
fread(magic, 1, 12, ageFile);
if (memcmp(magic, "whatdoyousee", 12) == 0 || memcmp(magic, "notthedroids", 12) == 0
|| memcmp(magic, "BriceIsSmart", 12) == 0) {
fprintf(stderr, "[Game] Error: Please decrypt your .age files before using!\n");
break;
}
fseek(ageFile, 0, SEEK_SET);
DS::String ageName = dirls[i]->d_name;
ageName = ageName.left(ageName.find(".age"));
Game_AgeInfo age = age_parse(ageFile);
if (age.m_seqPrefix >= 0)
s_ages[ageName] = age;
fclose(ageFile);
}
free(dirls[i]);
}
free(dirls);
}
pthread_mutex_init(&s_gameHostMutex, 0);
}
void DS::GameServer_Add(DS::SocketHandle client)
{
#ifdef DEBUG
if (s_commdebug)
printf("Connecting GAME on %s\n", DS::SockIpAddress(client).c_str());
#endif
pthread_t threadh;
pthread_create(&threadh, 0, &wk_gameWorker, reinterpret_cast<void*>(client));
pthread_detach(threadh);
}
void DS::GameServer_Shutdown()
{
pthread_mutex_lock(&s_gameHostMutex);
hostmap_t::iterator host_iter;
for (host_iter = s_gameHosts.begin(); host_iter != s_gameHosts.end(); ++host_iter)
host_iter->second->m_channel.putMessage(e_GameShutdown);
pthread_mutex_unlock(&s_gameHostMutex);
bool complete = false;
for (int i=0; i<50 && !complete; ++i) {
pthread_mutex_lock(&s_gameHostMutex);
size_t alive = s_gameHosts.size();
pthread_mutex_unlock(&s_gameHostMutex);
if (alive == 0)
complete = true;
usleep(100000);
}
if (!complete)
fprintf(stderr, "[Game] Servers didn't die after 5 seconds!\n");
pthread_mutex_destroy(&s_gameHostMutex);
}
void DS::GameServer_DisplayClients()
{
pthread_mutex_lock(&s_gameHostMutex);
if (s_gameHosts.size())
printf("Game Servers:\n");
for (hostmap_t::iterator host_iter = s_gameHosts.begin();
host_iter != s_gameHosts.end(); ++host_iter) {
printf(" {%s}\n", host_iter->second->m_instanceId.toString().c_str());
std::tr1::unordered_map<uint32_t, GameClient_Private*>::iterator client_iter;
for (client_iter = host_iter->second->m_clients.begin();
client_iter != host_iter->second->m_clients.end(); ++ client_iter)
printf(" * %s - %s (%u)\n", DS::SockIpAddress(client_iter->second->m_sock).c_str(),
client_iter->second->m_clientInfo.m_PlayerName.c_str(),
client_iter->second->m_clientInfo.m_PlayerId);
}
pthread_mutex_unlock(&s_gameHostMutex);
}
<commit_msg>Don't try to remove a client from the host if we're not connected to one.<commit_after>/******************************************************************************
* This file is part of dirtsand. *
* *
* dirtsand is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* dirtsand 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 dirtsand. If not, see <http://www.gnu.org/licenses/>. *
******************************************************************************/
#include "GameServer_Private.h"
#include "settings.h"
#include "errors.h"
#include <unistd.h>
#include <dirent.h>
#include <sys/stat.h>
extern bool s_commdebug;
#define START_REPLY(msgId) \
client.m_buffer.truncate(); \
client.m_buffer.write<uint16_t>(msgId)
#define SEND_REPLY() \
DS::CryptSendBuffer(client.m_sock, client.m_crypt, \
client.m_buffer.buffer(), client.m_buffer.size())
void game_client_init(GameClient_Private& client)
{
/* Game client header: size, account uuid, age instance uuid */
uint32_t size = DS::RecvValue<uint32_t>(client.m_sock);
DS_PASSERT(size == 36);
DS::Uuid clientUuid, connUuid;
DS::RecvBuffer(client.m_sock, clientUuid.m_bytes, sizeof(clientUuid.m_bytes));
DS::RecvBuffer(client.m_sock, connUuid.m_bytes, sizeof(connUuid.m_bytes));
/* Establish encryption */
uint8_t msgId = DS::RecvValue<uint8_t>(client.m_sock);
DS_PASSERT(msgId == DS::e_CliToServConnect);
uint8_t msgSize = DS::RecvValue<uint8_t>(client.m_sock);
DS_PASSERT(msgSize == 66);
uint8_t Y[64];
DS::RecvBuffer(client.m_sock, Y, 64);
BYTE_SWAP_BUFFER(Y, 64);
uint8_t serverSeed[7];
uint8_t sharedKey[7];
DS::CryptEstablish(serverSeed, sharedKey, DS::Settings::CryptKey(DS::e_KeyGame_N),
DS::Settings::CryptKey(DS::e_KeyGame_K), Y);
client.m_buffer.truncate();
client.m_buffer.write<uint8_t>(DS::e_ServToCliEncrypt);
client.m_buffer.write<uint8_t>(9);
client.m_buffer.writeBytes(serverSeed, 7);
DS::SendBuffer(client.m_sock, client.m_buffer.buffer(), client.m_buffer.size());
client.m_crypt = DS::CryptStateInit(sharedKey, 7);
}
GameHost_Private* find_game_host(uint32_t ageMcpId)
{
pthread_mutex_lock(&s_gameHostMutex);
hostmap_t::iterator host_iter = s_gameHosts.find(ageMcpId);
GameHost_Private* host = 0;
if (host_iter != s_gameHosts.end())
host = host_iter->second;
pthread_mutex_unlock(&s_gameHostMutex);
return host ? host : start_game_host(ageMcpId);
}
void cb_ping(GameClient_Private& client)
{
START_REPLY(e_GameToCli_PingReply);
// Ping time
client.m_buffer.write<uint32_t>(DS::CryptRecvValue<uint32_t>(client.m_sock, client.m_crypt));
SEND_REPLY();
}
void cb_join(GameClient_Private& client)
{
START_REPLY(e_GameToCli_JoinAgeReply);
// Trans ID
client.m_buffer.write<uint32_t>(DS::CryptRecvValue<uint32_t>(client.m_sock, client.m_crypt));
uint32_t mcpId = DS::CryptRecvValue<uint32_t>(client.m_sock, client.m_crypt);
client.m_host = find_game_host(mcpId);
DS_PASSERT(client.m_host != 0);
Game_ClientMessage msg;
msg.m_client = &client;
DS::CryptRecvBuffer(client.m_sock, client.m_crypt, client.m_clientId.m_bytes,
sizeof(client.m_clientId.m_bytes));
client.m_clientInfo.set_PlayerId(DS::CryptRecvValue<uint32_t>(client.m_sock, client.m_crypt));
if (client.m_clientInfo.m_PlayerId == 0) {
client.m_buffer.write<uint32_t>(DS::e_NetInvalidParameter);
SEND_REPLY();
return;
}
// Get player info from the vault
Auth_NodeInfo nodeInfo;
nodeInfo.m_client = &client;
nodeInfo.m_node.set_NodeIdx(client.m_clientInfo.m_PlayerId);
s_authChannel.putMessage(e_VaultFetchNode, reinterpret_cast<void*>(&nodeInfo));
DS::FifoMessage reply = client.m_channel.getMessage();
if (reply.m_messageType != DS::e_NetSuccess) {
client.m_buffer.write<uint32_t>(reply.m_messageType);
SEND_REPLY();
return;
}
msg.m_client->m_clientInfo.set_PlayerName(nodeInfo.m_node.m_IString64_1);
msg.m_client->m_clientInfo.set_CCRLevel(0);
client.m_host->m_channel.putMessage(e_GameJoinAge, reinterpret_cast<void*>(&msg));
reply = client.m_channel.getMessage();
client.m_buffer.write<uint32_t>(reply.m_messageType);
SEND_REPLY();
pthread_mutex_lock(&client.m_host->m_clientMutex);
client.m_host->m_clients[client.m_clientInfo.m_PlayerId] = &client;
pthread_mutex_unlock(&client.m_host->m_clientMutex);
}
void cb_netmsg(GameClient_Private& client)
{
Game_PropagateMessage msg;
msg.m_client = &client;
msg.m_messageType = DS::CryptRecvValue<uint32_t>(client.m_sock, client.m_crypt);
uint32_t size = DS::CryptRecvValue<uint32_t>(client.m_sock, client.m_crypt);
uint8_t* buffer = new uint8_t[size];
DS::CryptRecvBuffer(client.m_sock, client.m_crypt, buffer, size);
msg.m_message = DS::Blob::Steal(buffer, size);
client.m_host->m_channel.putMessage(e_GamePropagate, reinterpret_cast<void*>(&msg));
client.m_channel.getMessage();
}
void cb_gameMgrMsg(GameClient_Private& client)
{
uint32_t size = DS::CryptRecvValue<uint32_t>(client.m_sock, client.m_crypt);
uint8_t* buffer = new uint8_t[size];
DS::CryptRecvBuffer(client.m_sock, client.m_crypt, buffer, size);
printf("GAME MGR MSG");
for (size_t i=0; i<size; ++i) {
if ((i % 16) == 0)
printf("\n ");
else if ((i % 16) == 8)
printf(" ");
printf("%02X ", buffer[i]);
}
printf("\n");
delete[] buffer;
}
void* wk_gameWorker(void* sockp)
{
GameClient_Private client;
client.m_sock = reinterpret_cast<DS::SocketHandle>(sockp);
client.m_host = 0;
try {
game_client_init(client);
} catch (DS::AssertException ex) {
fprintf(stderr, "[Game] Assertion failed at %s:%ld: %s\n",
ex.m_file, ex.m_line, ex.m_cond);
return 0;
} catch (DS::SockHup) {
// Socket closed...
return 0;
}
try {
for ( ;; ) {
uint16_t msgId = DS::CryptRecvValue<uint16_t>(client.m_sock, client.m_crypt);
switch (msgId) {
case e_CliToGame_PingRequest:
cb_ping(client);
break;
case e_CliToGame_JoinAgeRequest:
cb_join(client);
break;
case e_CliToGame_Propagatebuffer:
DS_PASSERT(client.m_host != 0);
cb_netmsg(client);
break;
case e_CliToGame_GameMgrMsg:
DS_PASSERT(client.m_host != 0);
cb_gameMgrMsg(client);
break;
default:
/* Invalid message */
fprintf(stderr, "[Game] Got invalid message ID %d from %s\n",
msgId, DS::SockIpAddress(client.m_sock).c_str());
DS::CloseSock(client.m_sock);
throw DS::SockHup();
}
}
} catch (DS::AssertException ex) {
fprintf(stderr, "[Game] Assertion failed at %s:%ld: %s\n",
ex.m_file, ex.m_line, ex.m_cond);
} catch (DS::SockHup) {
// Socket closed...
}
if (client.m_host) {
pthread_mutex_lock(&client.m_host->m_clientMutex);
client.m_host->m_clients.erase(client.m_clientInfo.m_PlayerId);
pthread_mutex_unlock(&client.m_host->m_clientMutex);
Game_ClientMessage msg;
msg.m_client = &client;
client.m_host->m_channel.putMessage(e_GameDisconnect, reinterpret_cast<void*>(&msg));
client.m_channel.getMessage();
}
DS::CryptStateFree(client.m_crypt);
DS::FreeSock(client.m_sock);
return 0;
}
static int sel_age(const dirent* de)
{
return strcmp(strrchr(de->d_name, '.'), ".age") == 0;
}
Game_AgeInfo age_parse(FILE* stream)
{
char lnbuffer[4096];
Game_AgeInfo age;
while (fgets(lnbuffer, 4096, stream)) {
std::vector<DS::String> line = DS::String(lnbuffer).strip('#').split('=');
if (line.size() == 0)
continue;
if (line.size() != 2) {
fprintf(stderr, "[Game] Invalid AGE line: %s", lnbuffer);
continue;
}
if (line[0] == "StartDateTime") {
age.m_startTime = line[1].toUint(10);
} else if (line[0] == "DayLength") {
age.m_dayLength = line[1].toDouble();
} else if (line[0] == "MaxCapacity") {
age.m_maxCapacity = line[1].toUint(10);
} else if (line[0] == "LingerTime") {
age.m_lingerTime = line[1].toUint(10);
} else if (line[0] == "SequencePrefix") {
age.m_seqPrefix = line[1].toInt(10);
} else if (line[0] == "ReleaseVersion" || line[0] == "Page") {
// Ignored
} else {
fprintf(stderr, "[Game] Invalid AGE line: %s", lnbuffer);
}
}
return age;
}
void DS::GameServer_Init()
{
dirent** dirls;
int count = scandir(DS::Settings::AgePath(), &dirls, &sel_age, &alphasort);
if (count < 0) {
fprintf(stderr, "[Game] Error reading age descriptors: %s\n", strerror(errno));
} else if (count == 0) {
fprintf(stderr, "[Game] Warning: No age descriptors found!\n");
free(dirls);
} else {
for (int i=0; i<count; ++i) {
DS::String filename = DS::String::Format("%s/%s", DS::Settings::AgePath(), dirls[i]->d_name);
FILE* ageFile = fopen(filename.c_str(), "r");
if (ageFile) {
char magic[12];
fread(magic, 1, 12, ageFile);
if (memcmp(magic, "whatdoyousee", 12) == 0 || memcmp(magic, "notthedroids", 12) == 0
|| memcmp(magic, "BriceIsSmart", 12) == 0) {
fprintf(stderr, "[Game] Error: Please decrypt your .age files before using!\n");
break;
}
fseek(ageFile, 0, SEEK_SET);
DS::String ageName = dirls[i]->d_name;
ageName = ageName.left(ageName.find(".age"));
Game_AgeInfo age = age_parse(ageFile);
if (age.m_seqPrefix >= 0)
s_ages[ageName] = age;
fclose(ageFile);
}
free(dirls[i]);
}
free(dirls);
}
pthread_mutex_init(&s_gameHostMutex, 0);
}
void DS::GameServer_Add(DS::SocketHandle client)
{
#ifdef DEBUG
if (s_commdebug)
printf("Connecting GAME on %s\n", DS::SockIpAddress(client).c_str());
#endif
pthread_t threadh;
pthread_create(&threadh, 0, &wk_gameWorker, reinterpret_cast<void*>(client));
pthread_detach(threadh);
}
void DS::GameServer_Shutdown()
{
pthread_mutex_lock(&s_gameHostMutex);
hostmap_t::iterator host_iter;
for (host_iter = s_gameHosts.begin(); host_iter != s_gameHosts.end(); ++host_iter)
host_iter->second->m_channel.putMessage(e_GameShutdown);
pthread_mutex_unlock(&s_gameHostMutex);
bool complete = false;
for (int i=0; i<50 && !complete; ++i) {
pthread_mutex_lock(&s_gameHostMutex);
size_t alive = s_gameHosts.size();
pthread_mutex_unlock(&s_gameHostMutex);
if (alive == 0)
complete = true;
usleep(100000);
}
if (!complete)
fprintf(stderr, "[Game] Servers didn't die after 5 seconds!\n");
pthread_mutex_destroy(&s_gameHostMutex);
}
void DS::GameServer_DisplayClients()
{
pthread_mutex_lock(&s_gameHostMutex);
if (s_gameHosts.size())
printf("Game Servers:\n");
for (hostmap_t::iterator host_iter = s_gameHosts.begin();
host_iter != s_gameHosts.end(); ++host_iter) {
printf(" {%s}\n", host_iter->second->m_instanceId.toString().c_str());
std::tr1::unordered_map<uint32_t, GameClient_Private*>::iterator client_iter;
for (client_iter = host_iter->second->m_clients.begin();
client_iter != host_iter->second->m_clients.end(); ++ client_iter)
printf(" * %s - %s (%u)\n", DS::SockIpAddress(client_iter->second->m_sock).c_str(),
client_iter->second->m_clientInfo.m_PlayerName.c_str(),
client_iter->second->m_clientInfo.m_PlayerId);
}
pthread_mutex_unlock(&s_gameHostMutex);
}
<|endoftext|>
|
<commit_before>////////////////////////////////////////////////////////////////////////////////
// An example based on solving matrices based on a 1D hydrogen molecule.
#include <math.h>
#include <mpi.h>
#include <string>
using std::string;
#include <sstream>
using std::stringstream;
#include <vector>
using std::vector;
#include <iostream>
// NTPoly Headers
#include "DensityMatrixSolvers.h"
#include "PSMatrix.h"
#include "ProcessGrid.h"
#include "SolverParameters.h"
#include "Triplet.h"
#include "TripletList.h"
// ETC
const double x_start = -6.28;
const double x_end = 6.28;
////////////////////////////////////////////////////////////////////////////////
int main(int argc, char *argv[]) {
// Input Parameters
string density_file_out;
int process_rows, process_columns, process_slices;
double threshold, convergence_threshold;
int number_of_electrons;
int grid_points;
// Setup MPI
int provided;
MPI_Init_thread(&argc, &argv, MPI_THREAD_SERIALIZED, &provided);
int total_processors;
MPI_Comm_size(MPI_COMM_WORLD, &total_processors);
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
// Process The Input Parameters
string key, value;
for (int i = 1; i < argc; i += 2) {
key = string(argv[i]);
value = string(argv[i + 1]);
stringstream ss;
ss << value;
if (key == "--density") {
ss >> density_file_out;
} else if (key == "--process_rows") {
ss >> process_rows;
} else if (key == "--process_columns") {
ss >> process_columns;
} else if (key == "--process_slices") {
ss >> process_slices;
} else if (key == "--grid_points") {
ss >> grid_points;
} else if (key == "--number_of_electrons") {
ss >> number_of_electrons;
} else if (key == "--threshold") {
ss >> threshold;
} else if (key == "--convergence_threshold") {
ss >> convergence_threshold;
}
}
// Setup the process grid.
NTPoly::ConstructProcessGrid(MPI_COMM_WORLD, process_rows, process_columns,
process_slices, true);
// Set Up The Solver Parameters.
NTPoly::SolverParameters solver_parameters;
solver_parameters.SetConvergeDiff(convergence_threshold);
solver_parameters.SetThreshold(threshold);
solver_parameters.SetVerbosity(true);
// Divide The Work Amongst Processors.
int local_grid_points = grid_points / total_processors;
int start_row = local_grid_points * rank;
// Handle the edge case
if (rank == total_processors - 1) {
local_grid_points = grid_points - rank * local_grid_points;
}
vector<double> local_rows(local_grid_points);
for (int i = 0; i < local_grid_points; ++i) {
local_rows[i] = start_row + i;
}
// Construct A Linear Space.
vector<double> x_values(local_grid_points);
double grid_spacing = (x_end - x_start) / (grid_points - 1);
double local_x_start = x_start + start_row * grid_spacing;
for (int i = 0; i < local_grid_points; ++i) {
x_values[i] = local_x_start + i * grid_spacing;
}
// Construct The Kinetic Energy Operator.
NTPoly::TripletList_r triplet_list;
NTPoly::Triplet_r temp_value;
for (int counter = 0; counter < local_grid_points; ++counter) {
temp_value.index_row = start_row + counter + 1;
// Stencil Point 1
if (temp_value.index_row > 2) {
temp_value.index_column = temp_value.index_row - 2;
temp_value.point_value =
(-0.5) * (-1.0 / (12.0 * grid_spacing * grid_spacing));
triplet_list.Append(temp_value);
}
// Stencil Point 2
if (temp_value.index_row > 1) {
temp_value.index_column = temp_value.index_row - 1;
temp_value.point_value =
(-0.5) * (16.0 / (12.0 * grid_spacing * grid_spacing));
triplet_list.Append(temp_value);
}
// Stencil Point 3
temp_value.index_column = temp_value.index_row;
temp_value.point_value =
(-0.5) * (-30.0 / (12.0 * grid_spacing * grid_spacing));
triplet_list.Append(temp_value);
// Stencil Point 4
if (temp_value.index_row + 1 < grid_points) {
temp_value.index_column = temp_value.index_row + 1;
temp_value.point_value =
(-0.5) * (16.0 / (12.0 * grid_spacing * grid_spacing));
triplet_list.Append(temp_value);
}
// Stencil Point 5
if (temp_value.index_row + 2 < grid_points) {
temp_value.index_column = temp_value.index_row + 2;
temp_value.point_value =
(-0.5) * (-1.0 / (12.0 * grid_spacing * grid_spacing));
triplet_list.Append(temp_value);
}
}
NTPoly::Matrix_ps KineticEnergy(grid_points);
KineticEnergy.FillFromTripletList(triplet_list);
// Construct The Potential Energy Operator.
NTPoly::TripletList_r potential_triplet_list;
for (int i = 0; i < local_grid_points; ++i) {
temp_value.index_row = start_row + i + 1;
temp_value.index_column = start_row + i + 1;
temp_value.point_value = -1.0 / fabs(x_values[i]);
potential_triplet_list.Append(temp_value);
}
NTPoly::Matrix_ps PotentialEnergy(grid_points);
PotentialEnergy.FillFromTripletList(potential_triplet_list);
// Construct The Full Hamiltonian.
NTPoly::Matrix_ps Hamiltonian(KineticEnergy);
Hamiltonian.Increment(PotentialEnergy);
// Overlap Matrix is just the identity.
NTPoly::Matrix_ps Identity(grid_points);
Identity.FillIdentity();
// Call the solver routine.
NTPoly::Matrix_ps Density(grid_points);
double chemical_potential;
NTPoly::DensityMatrixSolvers::TRS2(Hamiltonian, Identity, 2, Density, energy
chemical_potential, solver_parameters);
// Print the density matrix to file.
Density.WriteToMatrixMarket(density_file_out);
// Cleanup
NTPoly::DestructProcessGrid();
MPI_Finalize();
return 0;
}
<commit_msg>Correction to last merge<commit_after>////////////////////////////////////////////////////////////////////////////////
// An example based on solving matrices based on a 1D hydrogen molecule.
#include <math.h>
#include <mpi.h>
#include <string>
using std::string;
#include <sstream>
using std::stringstream;
#include <vector>
using std::vector;
#include <iostream>
// NTPoly Headers
#include "DensityMatrixSolvers.h"
#include "PSMatrix.h"
#include "ProcessGrid.h"
#include "SolverParameters.h"
#include "Triplet.h"
#include "TripletList.h"
// ETC
const double x_start = -6.28;
const double x_end = 6.28;
////////////////////////////////////////////////////////////////////////////////
int main(int argc, char *argv[]) {
// Input Parameters
string density_file_out;
int process_rows, process_columns, process_slices;
double threshold, convergence_threshold;
int number_of_electrons;
int grid_points;
// Setup MPI
int provided;
MPI_Init_thread(&argc, &argv, MPI_THREAD_SERIALIZED, &provided);
int total_processors;
MPI_Comm_size(MPI_COMM_WORLD, &total_processors);
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
// Process The Input Parameters
string key, value;
for (int i = 1; i < argc; i += 2) {
key = string(argv[i]);
value = string(argv[i + 1]);
stringstream ss;
ss << value;
if (key == "--density") {
ss >> density_file_out;
} else if (key == "--process_rows") {
ss >> process_rows;
} else if (key == "--process_columns") {
ss >> process_columns;
} else if (key == "--process_slices") {
ss >> process_slices;
} else if (key == "--grid_points") {
ss >> grid_points;
} else if (key == "--number_of_electrons") {
ss >> number_of_electrons;
} else if (key == "--threshold") {
ss >> threshold;
} else if (key == "--convergence_threshold") {
ss >> convergence_threshold;
}
}
// Setup the process grid.
NTPoly::ConstructProcessGrid(MPI_COMM_WORLD, process_rows, process_columns,
process_slices, true);
// Set Up The Solver Parameters.
NTPoly::SolverParameters solver_parameters;
solver_parameters.SetConvergeDiff(convergence_threshold);
solver_parameters.SetThreshold(threshold);
solver_parameters.SetVerbosity(true);
// Divide The Work Amongst Processors.
int local_grid_points = grid_points / total_processors;
int start_row = local_grid_points * rank;
// Handle the edge case
if (rank == total_processors - 1) {
local_grid_points = grid_points - rank * local_grid_points;
}
vector<double> local_rows(local_grid_points);
for (int i = 0; i < local_grid_points; ++i) {
local_rows[i] = start_row + i;
}
// Construct A Linear Space.
vector<double> x_values(local_grid_points);
double grid_spacing = (x_end - x_start) / (grid_points - 1);
double local_x_start = x_start + start_row * grid_spacing;
for (int i = 0; i < local_grid_points; ++i) {
x_values[i] = local_x_start + i * grid_spacing;
}
// Construct The Kinetic Energy Operator.
NTPoly::TripletList_r triplet_list;
NTPoly::Triplet_r temp_value;
for (int counter = 0; counter < local_grid_points; ++counter) {
temp_value.index_row = start_row + counter + 1;
// Stencil Point 1
if (temp_value.index_row > 2) {
temp_value.index_column = temp_value.index_row - 2;
temp_value.point_value =
(-0.5) * (-1.0 / (12.0 * grid_spacing * grid_spacing));
triplet_list.Append(temp_value);
}
// Stencil Point 2
if (temp_value.index_row > 1) {
temp_value.index_column = temp_value.index_row - 1;
temp_value.point_value =
(-0.5) * (16.0 / (12.0 * grid_spacing * grid_spacing));
triplet_list.Append(temp_value);
}
// Stencil Point 3
temp_value.index_column = temp_value.index_row;
temp_value.point_value =
(-0.5) * (-30.0 / (12.0 * grid_spacing * grid_spacing));
triplet_list.Append(temp_value);
// Stencil Point 4
if (temp_value.index_row + 1 < grid_points) {
temp_value.index_column = temp_value.index_row + 1;
temp_value.point_value =
(-0.5) * (16.0 / (12.0 * grid_spacing * grid_spacing));
triplet_list.Append(temp_value);
}
// Stencil Point 5
if (temp_value.index_row + 2 < grid_points) {
temp_value.index_column = temp_value.index_row + 2;
temp_value.point_value =
(-0.5) * (-1.0 / (12.0 * grid_spacing * grid_spacing));
triplet_list.Append(temp_value);
}
}
NTPoly::Matrix_ps KineticEnergy(grid_points);
KineticEnergy.FillFromTripletList(triplet_list);
// Construct The Potential Energy Operator.
NTPoly::TripletList_r potential_triplet_list;
for (int i = 0; i < local_grid_points; ++i) {
temp_value.index_row = start_row + i + 1;
temp_value.index_column = start_row + i + 1;
temp_value.point_value = -1.0 / fabs(x_values[i]);
potential_triplet_list.Append(temp_value);
}
NTPoly::Matrix_ps PotentialEnergy(grid_points);
PotentialEnergy.FillFromTripletList(potential_triplet_list);
// Construct The Full Hamiltonian.
NTPoly::Matrix_ps Hamiltonian(KineticEnergy);
Hamiltonian.Increment(PotentialEnergy);
// Overlap Matrix is just the identity.
NTPoly::Matrix_ps Identity(grid_points);
Identity.FillIdentity();
// Call the solver routine.
NTPoly::Matrix_ps Density(grid_points);
double chemical_potential, energy;
NTPoly::DensityMatrixSolvers::TRS2(Hamiltonian, Identity, 2, Density, energy
chemical_potential, solver_parameters);
// Print the density matrix to file.
Density.WriteToMatrixMarket(density_file_out);
// Cleanup
NTPoly::DestructProcessGrid();
MPI_Finalize();
return 0;
}
<|endoftext|>
|
<commit_before>//=============================================================================================================
/**
* @file settingscontroller.cpp
* @author Juan Garcia-Prieto <Juan.GarciaPrieto@uth.tmc.edu> <juangpc@gmail.com>;
* Wayne Mead <wayne.mead@uth.tmc.edu> <wayne.isk@gmail.com>;
* Lorenz Esch <Lorenz.Esch@tu-ilmenau.de>;
* Matti Hamalainen <msh@nmr.mgh.harvard.edu>;
* John C. Mosher <John.C.Mosher@uth.tmc.edu> <jcmosher@gmail.com>;
* @version 1.0
* @date September, 2019
*
* @section LICENSE
*
* Copyright (C) 2019, Juan Garcia-Prieto and Matti Hamalainen. 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 MNE-CPP authors 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.
*
*
* @brief SettingsController class definition.
*
*/
//*************************************************************************************************************
//=============================================================================================================
// INCLUDES
//=============================================================================================================
#include "settingscontroller.h"
#include "fiffanonymizer.h"
//*************************************************************************************************************
//=============================================================================================================
// QT INCLUDES
//=============================================================================================================
//*************************************************************************************************************
//=============================================================================================================
// Eigen INCLUDES
//=============================================================================================================
//*************************************************************************************************************
//=============================================================================================================
// USED NAMESPACES
//=============================================================================================================
using namespace MNEANONYMIZE;
//*************************************************************************************************************
//=============================================================================================================
// DEFINE GLOBAL METHODS
//=============================================================================================================
//*************************************************************************************************************
//=============================================================================================================
// DEFINE MEMBER METHODS
//=============================================================================================================
SettingsController::SettingsController(const QStringList &arguments)
: m_bMultipleInFiles(false)
{
initParser();
parseInputs(arguments);
execute();
}
//*************************************************************************************************************
SettingsController::~SettingsController()
{
m_pAppList.clear();
}
//*************************************************************************************************************
void SettingsController::initParser()
{
m_parser.setApplicationDescription(QCoreApplication::translate("main",
m_anonymizer.description.toUtf8()));
m_parser.addHelpOption();
m_parser.addVersionOption();
QCommandLineOption inFileOpt("in",QCoreApplication::translate("main","File to anonymize. Wildcards are allowed and several --in <infile> statements can be present."),
QCoreApplication::translate("main","infile"));
m_parser.addOption(inFileOpt);
QCommandLineOption outFileOpt("out",QCoreApplication::translate("main","Output file <outfile>. Only allowed when anonymizing one single file."),
QCoreApplication::translate("main","outfile"));
m_parser.addOption(outFileOpt);
QCommandLineOption verboseOpt("verbose",QCoreApplication::translate("main","Prints out more information."));
m_parser.addOption(verboseOpt);
QCommandLineOption quietOpt("quiet",QCoreApplication::translate("main","Show no output."));
m_parser.addOption(quietOpt);
QCommandLineOption deleteInFileOpt("delete_input_file_after",
QCoreApplication::translate("main","Delete input fiff file after anonymization."));
m_parser.addOption(deleteInFileOpt);
QCommandLineOption deleteInFileConfirmOpt("avoid_delete_confirmation",
QCoreApplication::translate("main","Avoid confirming the deletion of the input fiff file."));
m_parser.addOption(deleteInFileConfirmOpt);
QCommandLineOption bruteOpt("brute",QCoreApplication::translate("main","Anonymize weight, height XXX if present in the input fiff file."));
m_parser.addOption(bruteOpt);
QCommandLineOption measDateOpt("measurement_date",
QCoreApplication::translate("main","Specify the measurement date. Only when anonymizing a single file. Format: YYYMMDD "),
QCoreApplication::translate("main","days"));
m_parser.addOption(measDateOpt);
QCommandLineOption measDateOffsetOpt("measurement_date_offset",
QCoreApplication::translate("main","Specify number of days to subtract to the measurement <date>. Only allowed when anonymizing a single file."),
QCoreApplication::translate("main","date"));
m_parser.addOption(measDateOffsetOpt);
QCommandLineOption birthdayOpt("subject_birthday",
QCoreApplication::translate("main","Specify the subject's birthday <date>. Only allowed when anonymizing a single file. Format: YYYMMDD "),
QCoreApplication::translate("main","date"));
m_parser.addOption(birthdayOpt);
QCommandLineOption birthdayOffsetOpt("subject_birthday_offset",
QCoreApplication::translate("main","Specify number of <days> to subtract to the subject's birthday. Only allowed when anonymizing a single file. "),
QCoreApplication::translate("main","days"));
m_parser.addOption(birthdayOffsetOpt);
QCommandLineOption SubjectIdOpt("his",QCoreApplication::translate("main","Specify the Subject's Id# within the Hospital system. Only allowed when anonymizing a single file. "),
QCoreApplication::translate("main","id#"));
m_parser.addOption(SubjectIdOpt);
}
//*************************************************************************************************************
void SettingsController::parseInputs(const QStringList& arguments)
{
m_parser.process(arguments);
parseInputAndOutputFiles();
if(m_parser.isSet("verbose")) {
m_anonymizer.setVerboseMode(true);
}
if(m_parser.isSet("brute")) {
m_anonymizer.setBruteMode(true);
}
if(m_parser.isSet("quiet")) {
if(m_anonymizer.getVerboseMode()) {
m_anonymizer.setVerboseMode(false);
}
m_anonymizer.setQuietMode(true);
}
if(m_parser.isSet("delete_input_file_after")) {
m_anonymizer.setDeleteInputFileAfter(true);
}
if(m_parser.isSet("avoid_delete_confirmation")) {
m_anonymizer.setDeleteInputFileAfterConfirmation(false);
}
if(m_parser.isSet("measurement_date")) {
if(m_bMultipleInFiles) {
qDebug() << "Error. Multiple Input files. You cannot specify the option \"measurement_date\".";
m_parser.showHelp();
}
QString d(m_parser.value("measurement_date"));
m_anonymizer.setMeasurementDay(d);
}
if(m_parser.isSet("measurement_date_offset")) {
if(m_bMultipleInFiles) {
qDebug() << "Error. Multiple Input files. You cannot specify the option \"measurement_date_offset\".";
m_parser.showHelp();
}
QString doffset(m_parser.value("measurement_date_offset"));
m_anonymizer.setMeasurementDayOffset(doffset.toInt());
}
if(m_parser.isSet("subject_birthday")) {
if(m_bMultipleInFiles) {
qDebug() << "Error. Multiple Input files. You cannot specify the option \"subject_birthday\".";
m_parser.showHelp();
}
QString birthday(m_parser.value("subject_birthday"));
m_anonymizer.setSubjectBirthday(birthday);
}
if(m_parser.isSet("subject_birthday_offset")) {
if(m_bMultipleInFiles) {
qDebug() << "Error. Multiple Input files. You cannot specify the option \"subject_birthday_offset\".";
m_parser.showHelp();
}
QString bdoffset(m_parser.value("subject_birthday_offset"));
m_anonymizer.setSubjectBirthdayOffset(bdoffset.toInt());
}
if(m_parser.isSet("his")) {
if(m_bMultipleInFiles) {
qDebug() << "Error. Multiple Input files. You cannot specify the optio \"his\".";
m_parser.showHelp();
}
m_anonymizer.setSubjectHisId(m_parser.value("his").toInt());
}
}
//*************************************************************************************************************
void SettingsController::parseInputAndOutputFiles()
{
if(m_parser.isSet("in")) {
QStringList inFilesAux(m_parser.values("in"));
for(QString f: inFilesAux) {
QFileInfo inFileInfo(QDir::toNativeSeparators(f));
inFileInfo.makeAbsolute();
if(inFileInfo.isDir()) {
qDebug() << "Error. " << f << " is a folder.";
}
QStringList filter;
filter << inFileInfo.fileName();
QDirIterator it(inFileInfo.absoluteDir().absolutePath(),filter,QDir::AllEntries | QDir::NoSymLinks | QDir::NoDotAndDotDot);
while(it.hasNext()) {
QFileInfo fi(it.next());
if(fi.isFile() && fi.isReadable()) {
m_SLInFiles.append(fi.absoluteFilePath());
}
}
}
}
if(m_SLInFiles.size() == 0) {
qDebug() << "Error. No valid input files.";
m_parser.showHelp();
} else if(m_SLInFiles.size() == 1) {
m_bMultipleInFiles = false;
} else {
m_bMultipleInFiles = true;
}
if(m_bMultipleInFiles) {
if(m_parser.isSet("out")) {
qDebug() << "Warning. Multiple input files selected. Output filename option will be ignored.";
}
for(QString fi:m_SLInFiles) {
QFileInfo fInfo(fi);
QString fout = QDir(fInfo.absolutePath()).filePath(
fInfo.baseName() + "_anonymized." + fInfo.completeSuffix());
m_SLOutFiles.append(fout);
}
} else {
QString fileOutName;
if(m_parser.isSet("out")) {
QFileInfo fInfo(m_parser.value("out"));
fInfo.makeAbsolute();
fileOutName = fInfo.absoluteFilePath();
} else {
QFileInfo fInfo(m_SLInFiles.first());
fileOutName = QDir(fInfo.absolutePath()).filePath(
fInfo.baseName() + "_anonymized." + fInfo.completeSuffix());
}
m_SLOutFiles.append(fileOutName);
}
if(m_SLInFiles.size() != m_SLOutFiles.size()) {
qDebug() << "Error. something went wrong while parsing the input files.";
}
}
//*************************************************************************************************************
void SettingsController::generateAnonymizerInstances()
{
if(m_SLInFiles.isEmpty() || m_SLOutFiles.isEmpty()) {
qDebug() << "SettingsController::generateAnonymizerInstances - No input and/or output file names specified.";
return;
}
if(m_bMultipleInFiles) {
for(int i=0; i< m_SLInFiles.size(); ++i) {
QSharedPointer<FiffAnonymizer> pAppAux(new FiffAnonymizer(m_anonymizer));
pAppAux->setFileIn(m_SLInFiles.at(i));
pAppAux->setFileOut(m_SLOutFiles.at(i));
//m_pAppList.append(QSharedPointer<FiffAnonymizer>(pAppAux));
//note that QList will copy & append.
m_pAppList.append(pAppAux);
}
} else {
m_anonymizer.setFileIn(m_SLInFiles.first());
m_anonymizer.setFileOut(m_SLOutFiles.first());
}
}
//*************************************************************************************************************
void SettingsController::execute()
{
generateAnonymizerInstances();
if(m_bMultipleInFiles) {
for(int th_i=0; th_i<m_pAppList.size(); ++th_i) {
QSharedPointer<QFuture<void> > promise( new QFuture<void>);
FiffAnonymizer localApp(*m_pAppList.at(th_i));
*promise = QtConcurrent::run(localApp,&FiffAnonymizer::anonymizeFile);
promisesList.append(promise);
}
for(int p_i=0;p_i<promisesList.size();++p_i) {
promisesList.at(p_i)->waitForFinished();
}
} else {
m_anonymizer.anonymizeFile();
}
}
<commit_msg>[ci skip] Parse SubjectHisId input and call setSubjectHisId with string<commit_after>//=============================================================================================================
/**
* @file settingscontroller.cpp
* @author Juan Garcia-Prieto <Juan.GarciaPrieto@uth.tmc.edu> <juangpc@gmail.com>;
* Wayne Mead <wayne.mead@uth.tmc.edu> <wayne.isk@gmail.com>;
* Lorenz Esch <Lorenz.Esch@tu-ilmenau.de>;
* Matti Hamalainen <msh@nmr.mgh.harvard.edu>;
* John C. Mosher <John.C.Mosher@uth.tmc.edu> <jcmosher@gmail.com>;
* @version 1.0
* @date September, 2019
*
* @section LICENSE
*
* Copyright (C) 2019, Juan Garcia-Prieto and Matti Hamalainen. 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 MNE-CPP authors 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.
*
*
* @brief SettingsController class definition.
*
*/
//*************************************************************************************************************
//=============================================================================================================
// INCLUDES
//=============================================================================================================
#include "settingscontroller.h"
#include "fiffanonymizer.h"
//*************************************************************************************************************
//=============================================================================================================
// QT INCLUDES
//=============================================================================================================
//*************************************************************************************************************
//=============================================================================================================
// Eigen INCLUDES
//=============================================================================================================
//*************************************************************************************************************
//=============================================================================================================
// USED NAMESPACES
//=============================================================================================================
using namespace MNEANONYMIZE;
//*************************************************************************************************************
//=============================================================================================================
// DEFINE GLOBAL METHODS
//=============================================================================================================
//*************************************************************************************************************
//=============================================================================================================
// DEFINE MEMBER METHODS
//=============================================================================================================
SettingsController::SettingsController(const QStringList &arguments)
: m_bMultipleInFiles(false)
{
initParser();
parseInputs(arguments);
execute();
}
//*************************************************************************************************************
SettingsController::~SettingsController()
{
m_pAppList.clear();
}
//*************************************************************************************************************
void SettingsController::initParser()
{
m_parser.setApplicationDescription(QCoreApplication::translate("main",
m_anonymizer.description.toUtf8()));
m_parser.addHelpOption();
m_parser.addVersionOption();
QCommandLineOption inFileOpt("in",QCoreApplication::translate("main","File to anonymize. Wildcards are allowed and several --in <infile> statements can be present."),
QCoreApplication::translate("main","infile"));
m_parser.addOption(inFileOpt);
QCommandLineOption outFileOpt("out",QCoreApplication::translate("main","Output file <outfile>. Only allowed when anonymizing one single file."),
QCoreApplication::translate("main","outfile"));
m_parser.addOption(outFileOpt);
QCommandLineOption verboseOpt("verbose",QCoreApplication::translate("main","Prints out more information."));
m_parser.addOption(verboseOpt);
QCommandLineOption quietOpt("quiet",QCoreApplication::translate("main","Show no output."));
m_parser.addOption(quietOpt);
QCommandLineOption deleteInFileOpt("delete_input_file_after",
QCoreApplication::translate("main","Delete input fiff file after anonymization."));
m_parser.addOption(deleteInFileOpt);
QCommandLineOption deleteInFileConfirmOpt("avoid_delete_confirmation",
QCoreApplication::translate("main","Avoid confirming the deletion of the input fiff file."));
m_parser.addOption(deleteInFileConfirmOpt);
QCommandLineOption bruteOpt("brute",QCoreApplication::translate("main","Anonymize weight, height XXX if present in the input fiff file."));
m_parser.addOption(bruteOpt);
QCommandLineOption measDateOpt("measurement_date",
QCoreApplication::translate("main","Specify the measurement date. Only when anonymizing a single file. Format: YYYMMDD "),
QCoreApplication::translate("main","days"));
m_parser.addOption(measDateOpt);
QCommandLineOption measDateOffsetOpt("measurement_date_offset",
QCoreApplication::translate("main","Specify number of days to subtract to the measurement <date>. Only allowed when anonymizing a single file."),
QCoreApplication::translate("main","date"));
m_parser.addOption(measDateOffsetOpt);
QCommandLineOption birthdayOpt("subject_birthday",
QCoreApplication::translate("main","Specify the subject's birthday <date>. Only allowed when anonymizing a single file. Format: YYYMMDD "),
QCoreApplication::translate("main","date"));
m_parser.addOption(birthdayOpt);
QCommandLineOption birthdayOffsetOpt("subject_birthday_offset",
QCoreApplication::translate("main","Specify number of <days> to subtract to the subject's birthday. Only allowed when anonymizing a single file. "),
QCoreApplication::translate("main","days"));
m_parser.addOption(birthdayOffsetOpt);
QCommandLineOption SubjectIdOpt("his",QCoreApplication::translate("main","Specify the Subject's Id# within the Hospital system. Only allowed when anonymizing a single file. "),
QCoreApplication::translate("main","id#"));
m_parser.addOption(SubjectIdOpt);
}
//*************************************************************************************************************
void SettingsController::parseInputs(const QStringList& arguments)
{
m_parser.process(arguments);
parseInputAndOutputFiles();
if(m_parser.isSet("verbose")) {
m_anonymizer.setVerboseMode(true);
}
if(m_parser.isSet("brute")) {
m_anonymizer.setBruteMode(true);
}
if(m_parser.isSet("quiet")) {
if(m_anonymizer.getVerboseMode()) {
m_anonymizer.setVerboseMode(false);
}
m_anonymizer.setQuietMode(true);
}
if(m_parser.isSet("delete_input_file_after")) {
m_anonymizer.setDeleteInputFileAfter(true);
}
if(m_parser.isSet("avoid_delete_confirmation")) {
m_anonymizer.setDeleteInputFileAfterConfirmation(false);
}
if(m_parser.isSet("measurement_date")) {
if(m_bMultipleInFiles) {
qDebug() << "Error. Multiple Input files. You cannot specify the option \"measurement_date\".";
m_parser.showHelp();
}
QString d(m_parser.value("measurement_date"));
m_anonymizer.setMeasurementDay(d);
}
if(m_parser.isSet("measurement_date_offset")) {
if(m_bMultipleInFiles) {
qDebug() << "Error. Multiple Input files. You cannot specify the option \"measurement_date_offset\".";
m_parser.showHelp();
}
QString doffset(m_parser.value("measurement_date_offset"));
m_anonymizer.setMeasurementDayOffset(doffset.toInt());
}
if(m_parser.isSet("subject_birthday")) {
if(m_bMultipleInFiles) {
qDebug() << "Error. Multiple Input files. You cannot specify the option \"subject_birthday\".";
m_parser.showHelp();
}
QString birthday(m_parser.value("subject_birthday"));
m_anonymizer.setSubjectBirthday(birthday);
}
if(m_parser.isSet("subject_birthday_offset")) {
if(m_bMultipleInFiles) {
qDebug() << "Error. Multiple Input files. You cannot specify the option \"subject_birthday_offset\".";
m_parser.showHelp();
}
QString bdoffset(m_parser.value("subject_birthday_offset"));
m_anonymizer.setSubjectBirthdayOffset(bdoffset.toInt());
}
if(m_parser.isSet("his")) {
if(m_bMultipleInFiles) {
qDebug() << "Error. Multiple Input files. You cannot specify the optio \"his\".";
m_parser.showHelp();
}
m_anonymizer.setSubjectHisId(m_parser.value("his"));
}
}
//*************************************************************************************************************
void SettingsController::parseInputAndOutputFiles()
{
if(m_parser.isSet("in")) {
QStringList inFilesAux(m_parser.values("in"));
for(QString f: inFilesAux) {
QFileInfo inFileInfo(QDir::toNativeSeparators(f));
inFileInfo.makeAbsolute();
if(inFileInfo.isDir()) {
qDebug() << "Error. " << f << " is a folder.";
}
QStringList filter;
filter << inFileInfo.fileName();
QDirIterator it(inFileInfo.absoluteDir().absolutePath(),filter,QDir::AllEntries | QDir::NoSymLinks | QDir::NoDotAndDotDot);
while(it.hasNext()) {
QFileInfo fi(it.next());
if(fi.isFile() && fi.isReadable()) {
m_SLInFiles.append(fi.absoluteFilePath());
}
}
}
}
if(m_SLInFiles.size() == 0) {
qDebug() << "Error. No valid input files.";
m_parser.showHelp();
} else if(m_SLInFiles.size() == 1) {
m_bMultipleInFiles = false;
} else {
m_bMultipleInFiles = true;
}
if(m_bMultipleInFiles) {
if(m_parser.isSet("out")) {
qDebug() << "Warning. Multiple input files selected. Output filename option will be ignored.";
}
for(QString fi:m_SLInFiles) {
QFileInfo fInfo(fi);
QString fout = QDir(fInfo.absolutePath()).filePath(
fInfo.baseName() + "_anonymized." + fInfo.completeSuffix());
m_SLOutFiles.append(fout);
}
} else {
QString fileOutName;
if(m_parser.isSet("out")) {
QFileInfo fInfo(m_parser.value("out"));
fInfo.makeAbsolute();
fileOutName = fInfo.absoluteFilePath();
} else {
QFileInfo fInfo(m_SLInFiles.first());
fileOutName = QDir(fInfo.absolutePath()).filePath(
fInfo.baseName() + "_anonymized." + fInfo.completeSuffix());
}
m_SLOutFiles.append(fileOutName);
}
if(m_SLInFiles.size() != m_SLOutFiles.size()) {
qDebug() << "Error. something went wrong while parsing the input files.";
}
}
//*************************************************************************************************************
void SettingsController::generateAnonymizerInstances()
{
if(m_SLInFiles.isEmpty() || m_SLOutFiles.isEmpty()) {
qDebug() << "SettingsController::generateAnonymizerInstances - No input and/or output file names specified.";
return;
}
if(m_bMultipleInFiles) {
for(int i=0; i< m_SLInFiles.size(); ++i) {
QSharedPointer<FiffAnonymizer> pAppAux(new FiffAnonymizer(m_anonymizer));
pAppAux->setFileIn(m_SLInFiles.at(i));
pAppAux->setFileOut(m_SLOutFiles.at(i));
//m_pAppList.append(QSharedPointer<FiffAnonymizer>(pAppAux));
//note that QList will copy & append.
m_pAppList.append(pAppAux);
}
} else {
m_anonymizer.setFileIn(m_SLInFiles.first());
m_anonymizer.setFileOut(m_SLOutFiles.first());
}
}
//*************************************************************************************************************
void SettingsController::execute()
{
generateAnonymizerInstances();
if(m_bMultipleInFiles) {
for(int th_i=0; th_i<m_pAppList.size(); ++th_i) {
QSharedPointer<QFuture<void> > promise( new QFuture<void>);
FiffAnonymizer localApp(*m_pAppList.at(th_i));
*promise = QtConcurrent::run(localApp,&FiffAnonymizer::anonymizeFile);
promisesList.append(promise);
}
for(int p_i=0;p_i<promisesList.size();++p_i) {
promisesList.at(p_i)->waitForFinished();
}
} else {
m_anonymizer.anonymizeFile();
}
}
<|endoftext|>
|
<commit_before>/*******************************************************************************
* ALMA - Atacama Large Millimiter Array
* (c) European Southern Observatory, 2002
* Copyright by ESO (in the framework of the ALMA collaboration)
* and Cosylab 2002, All rights reserved
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* "@(#) $Id: acsContainerDaemonImpl.cpp,v 1.5 2007/10/31 13:59:33 ntroncos Exp $"
*
* who when what
* -------- --------- ----------------------------------------------
* msekoran 2006-06-21 created
*/
#include "acsContainerDaemonImpl.h"
#include <tao/IORTable/IORTable.h>
#include <acserr.h>
#include <acsdaemonErrType.h>
#include <ACSErrTypeCommon.h>
/*****************************************************************/
ACSContainerDaemonImpl::ACSContainerDaemonImpl (LoggingProxy &logProxy) :
m_isInitialized(false),
m_logProxy(logProxy)
{
// noop here
m_isInitialized = true;
}
ACSContainerDaemonImpl::~ACSContainerDaemonImpl (void)
{
}
int
ACSContainerDaemonImpl::init_ORB (int& argc, char *argv [])
{
m_orb = CORBA::ORB_init(argc, argv, "TAO");
try
{
// get a reference to the RootPOA
CORBA::Object_var obj = m_orb->resolve_initial_references("RootPOA");
PortableServer::POA_var root_poa = PortableServer::POA::_narrow(obj.in());
PortableServer::POAManager_var poa_manager = root_poa->the_POAManager();
// create policies
CORBA::PolicyList policy_list;
policy_list.length(5);
policy_list[0] = root_poa->create_request_processing_policy(PortableServer::USE_DEFAULT_SERVANT);
policy_list[1] = root_poa->create_id_uniqueness_policy(PortableServer::MULTIPLE_ID);
policy_list[2] = root_poa->create_id_assignment_policy(PortableServer::USER_ID);
policy_list[3] = root_poa->create_servant_retention_policy(PortableServer::NON_RETAIN);
policy_list[4] = root_poa->create_lifespan_policy(PortableServer::PERSISTENT);
// create a ACSDaemon POA with policies
PortableServer::POA_var poa = root_poa->create_POA("ACSContainerDaemon", poa_manager.in(), policy_list);
// destroy policies
for (CORBA::ULong i = 0; i < policy_list.length(); ++i)
{
CORBA::Policy_ptr policy = policy_list[i];
policy->destroy();
}
// set as default servant
poa->set_servant(this);
// create reference
PortableServer::ObjectId_var oid = PortableServer::string_to_ObjectId("ACSContainerDaemon");
obj = poa->create_reference_with_id (oid.in(), _interface_repository_id());
m_ior = m_orb->object_to_string(obj.in());
// bind to IOR table
CORBA::Object_var table_object = m_orb->resolve_initial_references("IORTable");
IORTable::Table_var adapter = IORTable::Table::_narrow(table_object.in());
if (CORBA::is_nil(adapter.in()))
{
ACS_SHORT_LOG ((LM_ERROR, "Nil IORTable"));
return -1;
}
else
{
adapter->bind("ACSContainerDaemon", m_ior.in());
}
// activate POA
poa_manager->activate();
ACS_SHORT_LOG((LM_INFO, "ACS Container Daemon is waiting for incoming requests."));
}
catch( CORBA::Exception &ex )
{
ACE_PRINT_EXCEPTION (ex, "EXCEPTION CAUGHT");
return -1;
}
return 0;
}
int
ACSContainerDaemonImpl::startup (int argc, char *argv[])
{
ACS_SHORT_LOG ((LM_INFO, "Starting up the ACS Container Daemon..."));
// Initalize the ORB.
if (init_ORB (argc, argv) != 0)
{
return -1;
}
// Initialize AES.
if (!ACSError::init(m_orb.in()))
{
ACS_SHORT_LOG ((LM_ERROR, "Failed to initalize the ACS Error System."));
return -1;
}
ACS_SHORT_LOG ((LM_INFO, "ACS Container Daemon is initialized."));
return 0;
}
int
ACSContainerDaemonImpl::run (void)
{
ACS_SHORT_LOG ((LM_INFO, "ACS Container Daemon is up and running..."));
try
{
this->m_orb->run ();
}
catch(...)
{
return -1;
}
return 0;
}
void
ACSContainerDaemonImpl::shutdown ()
{
// shutdown the ORB.
if (!CORBA::is_nil (m_orb.in ()))
{
this->m_orb->shutdown (true);
}
// shutdown AES
ACSError::done();
}
/************************** CORBA interface ****************************/
void
ACSContainerDaemonImpl::start_container (
const char * container_type,
const char * container_name,
::CORBA::Short instance_number,
const char * additional_command_line
)
ACE_THROW_SPEC ((
CORBA::SystemException,
::acsdaemonErrType::FailedToStartContainerEx,
::ACSErrTypeCommon::BadParameterEx
))
{
if (container_type == 0 ||
*container_type == 0)
{
::ACSErrTypeCommon::BadParameterExImpl ex(__FILE__, __LINE__,
"::ACSContainerDaemonImpl::start_container");
ex.setParameter("container_type");
throw ex.getBadParameterEx();
}
if (container_name == 0 ||
*container_name == 0)
{
::ACSErrTypeCommon::BadParameterExImpl ex(__FILE__, __LINE__,
"::ACSContainerDaemonImpl::start_container");
ex.setParameter("container_name");
throw ex.getBadParameterEx();
}
const char * cmdln = (additional_command_line ? additional_command_line : "");
// execute: "acsStartContainer -<type> -b <instance> <name> <args>"
// TODO checks for ';', '&', '|' chars, they can run any other command!
//get the directory name to store the container stdout
std::string logDirectory="~/.acs/commandcenter/";
std::string containerName(container_name);
std::string::size_type pos=containerName.rfind("/");
if(pos != std::string::npos){
logDirectory.append(containerName,0,pos+1);
containerName.erase(0,pos+1);
}
//create the directory
std::string mkdir("mkdir -p ");
mkdir.append(logDirectory);
ACE_OS::system(mkdir.c_str());
std::string timeStamp(getStringifiedTimeStamp().c_str());
char command[1000];
snprintf(command, 1000, "acsStartContainer -%s -b %d %s %s &> %sacsStartContainer_%s_%s&", container_type, instance_number, container_name, cmdln, logDirectory.c_str(), containerName.c_str(), timeStamp.c_str());
ACS_SHORT_LOG ((LM_INFO, "Executing: '%s'.", command));
int result = ACE_OS::system(command);
if (result < 0)
{
throw ::acsdaemonErrType::FailedToStartContainerExImpl(
__FILE__, __LINE__,
"::ACSContainerDaemonImpl::start_container").getFailedToStartContainerEx();
}
}
void
ACSContainerDaemonImpl::stop_container (
const char * container_name,
::CORBA::Short instance_number,
const char * additional_command_line
)
ACE_THROW_SPEC ((
CORBA::SystemException,
::acsdaemonErrType::FailedToStopContainerEx,
::ACSErrTypeCommon::BadParameterEx
))
{
if (container_name == 0 ||
*container_name == 0)
{
::ACSErrTypeCommon::BadParameterExImpl ex(__FILE__, __LINE__,
"::ACSContainerDaemonImpl::stop_container");
ex.setParameter("container_name");
throw ex.getBadParameterEx();
}
const char * cmdln = (additional_command_line ? additional_command_line : "");
//get the directory name to store the container stdout
std::string logDirectory="~/.acs/commandcenter/";
std::string containerName(container_name);
std::string::size_type pos=containerName.rfind("/");
if(pos != std::string::npos){
logDirectory.append(containerName,0,pos);
containerName.erase(0,pos);
}
//create the directory
std::string mkdir("mkdir -p ");
mkdir.append(logDirectory);
ACE_OS::system(mkdir.c_str());
std::string timeStamp(getStringifiedTimeStamp().c_str());
// execute: "acsStopContainer -b <instance> <name> <args>"
// TODO checks for ';', '&', '|' chars, they can run any other command!
char command[1000];
snprintf(command, 1000, "acsStopContainer -b %d %s %s &> %sacsStopContainer_%s_%s&", instance_number, container_name, cmdln, logDirectory.c_str(), containerName.c_str(), timeStamp.c_str());
ACS_SHORT_LOG ((LM_INFO, "Executing: '%s'.", command));
int result = ACE_OS::system(command);
if (result < 0)
{
throw ::acsdaemonErrType::FailedToStopContainerExImpl(
__FILE__, __LINE__,
"::ACSContainerDaemonImpl::stop_container").getFailedToStopContainerEx();
}
}
<commit_msg>Fix for COMP-1317 in acsStopContainer<commit_after>/*******************************************************************************
* ALMA - Atacama Large Millimiter Array
* (c) European Southern Observatory, 2002
* Copyright by ESO (in the framework of the ALMA collaboration)
* and Cosylab 2002, All rights reserved
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* "@(#) $Id: acsContainerDaemonImpl.cpp,v 1.6 2007/10/31 16:23:24 ntroncos Exp $"
*
* who when what
* -------- --------- ----------------------------------------------
* msekoran 2006-06-21 created
*/
#include "acsContainerDaemonImpl.h"
#include <tao/IORTable/IORTable.h>
#include <acserr.h>
#include <acsdaemonErrType.h>
#include <ACSErrTypeCommon.h>
/*****************************************************************/
ACSContainerDaemonImpl::ACSContainerDaemonImpl (LoggingProxy &logProxy) :
m_isInitialized(false),
m_logProxy(logProxy)
{
// noop here
m_isInitialized = true;
}
ACSContainerDaemonImpl::~ACSContainerDaemonImpl (void)
{
}
int
ACSContainerDaemonImpl::init_ORB (int& argc, char *argv [])
{
m_orb = CORBA::ORB_init(argc, argv, "TAO");
try
{
// get a reference to the RootPOA
CORBA::Object_var obj = m_orb->resolve_initial_references("RootPOA");
PortableServer::POA_var root_poa = PortableServer::POA::_narrow(obj.in());
PortableServer::POAManager_var poa_manager = root_poa->the_POAManager();
// create policies
CORBA::PolicyList policy_list;
policy_list.length(5);
policy_list[0] = root_poa->create_request_processing_policy(PortableServer::USE_DEFAULT_SERVANT);
policy_list[1] = root_poa->create_id_uniqueness_policy(PortableServer::MULTIPLE_ID);
policy_list[2] = root_poa->create_id_assignment_policy(PortableServer::USER_ID);
policy_list[3] = root_poa->create_servant_retention_policy(PortableServer::NON_RETAIN);
policy_list[4] = root_poa->create_lifespan_policy(PortableServer::PERSISTENT);
// create a ACSDaemon POA with policies
PortableServer::POA_var poa = root_poa->create_POA("ACSContainerDaemon", poa_manager.in(), policy_list);
// destroy policies
for (CORBA::ULong i = 0; i < policy_list.length(); ++i)
{
CORBA::Policy_ptr policy = policy_list[i];
policy->destroy();
}
// set as default servant
poa->set_servant(this);
// create reference
PortableServer::ObjectId_var oid = PortableServer::string_to_ObjectId("ACSContainerDaemon");
obj = poa->create_reference_with_id (oid.in(), _interface_repository_id());
m_ior = m_orb->object_to_string(obj.in());
// bind to IOR table
CORBA::Object_var table_object = m_orb->resolve_initial_references("IORTable");
IORTable::Table_var adapter = IORTable::Table::_narrow(table_object.in());
if (CORBA::is_nil(adapter.in()))
{
ACS_SHORT_LOG ((LM_ERROR, "Nil IORTable"));
return -1;
}
else
{
adapter->bind("ACSContainerDaemon", m_ior.in());
}
// activate POA
poa_manager->activate();
ACS_SHORT_LOG((LM_INFO, "ACS Container Daemon is waiting for incoming requests."));
}
catch( CORBA::Exception &ex )
{
ACE_PRINT_EXCEPTION (ex, "EXCEPTION CAUGHT");
return -1;
}
return 0;
}
int
ACSContainerDaemonImpl::startup (int argc, char *argv[])
{
ACS_SHORT_LOG ((LM_INFO, "Starting up the ACS Container Daemon..."));
// Initalize the ORB.
if (init_ORB (argc, argv) != 0)
{
return -1;
}
// Initialize AES.
if (!ACSError::init(m_orb.in()))
{
ACS_SHORT_LOG ((LM_ERROR, "Failed to initalize the ACS Error System."));
return -1;
}
ACS_SHORT_LOG ((LM_INFO, "ACS Container Daemon is initialized."));
return 0;
}
int
ACSContainerDaemonImpl::run (void)
{
ACS_SHORT_LOG ((LM_INFO, "ACS Container Daemon is up and running..."));
try
{
this->m_orb->run ();
}
catch(...)
{
return -1;
}
return 0;
}
void
ACSContainerDaemonImpl::shutdown ()
{
// shutdown the ORB.
if (!CORBA::is_nil (m_orb.in ()))
{
this->m_orb->shutdown (true);
}
// shutdown AES
ACSError::done();
}
/************************** CORBA interface ****************************/
void
ACSContainerDaemonImpl::start_container (
const char * container_type,
const char * container_name,
::CORBA::Short instance_number,
const char * additional_command_line
)
ACE_THROW_SPEC ((
CORBA::SystemException,
::acsdaemonErrType::FailedToStartContainerEx,
::ACSErrTypeCommon::BadParameterEx
))
{
if (container_type == 0 ||
*container_type == 0)
{
::ACSErrTypeCommon::BadParameterExImpl ex(__FILE__, __LINE__,
"::ACSContainerDaemonImpl::start_container");
ex.setParameter("container_type");
throw ex.getBadParameterEx();
}
if (container_name == 0 ||
*container_name == 0)
{
::ACSErrTypeCommon::BadParameterExImpl ex(__FILE__, __LINE__,
"::ACSContainerDaemonImpl::start_container");
ex.setParameter("container_name");
throw ex.getBadParameterEx();
}
const char * cmdln = (additional_command_line ? additional_command_line : "");
// execute: "acsStartContainer -<type> -b <instance> <name> <args>"
// TODO checks for ';', '&', '|' chars, they can run any other command!
//get the directory name to store the container stdout
std::string logDirectory="~/.acs/commandcenter/";
std::string containerName(container_name);
std::string::size_type pos=containerName.rfind("/");
if(pos != std::string::npos){
logDirectory.append(containerName,0,pos+1);
containerName.erase(0,pos+1);
}
//create the directory
std::string mkdir("mkdir -p ");
mkdir.append(logDirectory);
ACE_OS::system(mkdir.c_str());
std::string timeStamp(getStringifiedTimeStamp().c_str());
char command[1000];
snprintf(command, 1000, "acsStartContainer -%s -b %d %s %s &> %sacsStartContainer_%s_%s&", container_type, instance_number, container_name, cmdln, logDirectory.c_str(), containerName.c_str(), timeStamp.c_str());
ACS_SHORT_LOG ((LM_INFO, "Executing: '%s'.", command));
int result = ACE_OS::system(command);
if (result < 0)
{
throw ::acsdaemonErrType::FailedToStartContainerExImpl(
__FILE__, __LINE__,
"::ACSContainerDaemonImpl::start_container").getFailedToStartContainerEx();
}
}
void
ACSContainerDaemonImpl::stop_container (
const char * container_name,
::CORBA::Short instance_number,
const char * additional_command_line
)
ACE_THROW_SPEC ((
CORBA::SystemException,
::acsdaemonErrType::FailedToStopContainerEx,
::ACSErrTypeCommon::BadParameterEx
))
{
if (container_name == 0 ||
*container_name == 0)
{
::ACSErrTypeCommon::BadParameterExImpl ex(__FILE__, __LINE__,
"::ACSContainerDaemonImpl::stop_container");
ex.setParameter("container_name");
throw ex.getBadParameterEx();
}
const char * cmdln = (additional_command_line ? additional_command_line : "");
//get the directory name to store the container stdout
std::string logDirectory="~/.acs/commandcenter/";
std::string containerName(container_name);
std::string::size_type pos=containerName.rfind("/");
if(pos != std::string::npos){
logDirectory.append(containerName,0,pos+1);
containerName.erase(0,pos+1);
}
//create the directory
std::string mkdir("mkdir -p ");
mkdir.append(logDirectory);
ACE_OS::system(mkdir.c_str());
std::string timeStamp(getStringifiedTimeStamp().c_str());
// execute: "acsStopContainer -b <instance> <name> <args>"
// TODO checks for ';', '&', '|' chars, they can run any other command!
char command[1000];
snprintf(command, 1000, "acsStopContainer -b %d %s %s &> %sacsStopContainer_%s_%s&", instance_number, container_name, cmdln, logDirectory.c_str(), containerName.c_str(), timeStamp.c_str());
ACS_SHORT_LOG ((LM_INFO, "Executing: '%s'.", command));
int result = ACE_OS::system(command);
if (result < 0)
{
throw ::acsdaemonErrType::FailedToStopContainerExImpl(
__FILE__, __LINE__,
"::ACSContainerDaemonImpl::stop_container").getFailedToStopContainerEx();
}
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <queue>
#include <utility>
#include <stdio.h>
#include <vector>
using namespace std;
typedef pair<long long ,long long> node;
long long re[1000000];
int main(int argc, char const *argv[])
{
priority_queue<node ,vector<node> ,greater<node> > pq;
pq.push(node(1,2));
node n;
int i=0;
while(i<100){
node n=pq.top();
//printf("%d",i);
pq.pop();
switch(n.second){
case 2:
pq.push(node(n.first*2,2));
case 3:
pq.push(node(n.first*3,3));
case 5:
pq.push(node(n.first*5,5));
}
re[i++]=n.first;
}
for (int j = 0; j < i; ++j)
{
printf("%d\n",re[j]);
}
return 0;
}
<commit_msg>update 346588<commit_after>#include <iostream>
#include <queue>
#include <utility>
#include <stdio.h>
#include <vector>
using namespace std;
typedef pair<long long ,long long> node;
long long re[1000000];
int main(int argc, char const *argv[])
{
priority_queue<node ,vector<node> ,greater<node> > pq;
pq.push(node(1,2));
node n;
int i=0;
while(i<1000){
node n=pq.top();
//printf("%d",i);
pq.pop();
switch(n.second){
case 2:
pq.push(node(n.first*2,2));
case 3:
pq.push(node(n.first*3,3));
case 5:
pq.push(node(n.first*5,5));
}
re[i++]=n.first;
}
for (int j = 0; j < i; ++j)
{
printf("%d\n",re[j]);
}
return 0;
}
<|endoftext|>
|
<commit_before>// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/app/chrome_command_ids.h"
#include "chrome/browser/extensions/api/commands/command_service.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_commands.h"
#include "chrome/browser/ui/views/bookmarks/bookmark_bubble_view.h"
#include "extensions/common/manifest_constants.h"
typedef ExtensionApiTest BookmarkOverrideTest;
namespace {
// Bookmark this page keybinding.
#if defined(OS_MACOSX)
const char kBookmarkKeybinding[] = "Command+D";
#else
const char kBookmarkKeybinding[] = "Ctrl+D";
#endif // defined(OS_MACOSX)
}
// Test that invoking the IDC_BOOKMARK_PAGE command (as done by the wrench menu)
// brings up the bookmark UI, if no extension requests to override ctrl-D and
// the user has assigned it to an extension.
IN_PROC_BROWSER_TEST_F(BookmarkOverrideTest, NonOverrideBookmarkPage) {
ASSERT_TRUE(test_server()->Start());
ASSERT_TRUE(RunExtensionTest("keybinding/basics")) << message_;
const extensions::Extension* extension = GetSingleLoadedExtension();
extensions::CommandService* command_service =
extensions::CommandService::Get(browser()->profile());
// Simulate the user setting the keybinding to Ctrl+D.
command_service->UpdateKeybindingPrefs(
extension->id(), extensions::manifest_values::kBrowserActionCommandEvent,
kBookmarkKeybinding);
// Check that the BookmarkBubbleView is shown when executing
// IDC_BOOKMARK_PAGE.
EXPECT_FALSE(BookmarkBubbleView::IsShowing());
chrome::ExecuteCommand(browser(), IDC_BOOKMARK_PAGE);
EXPECT_TRUE(BookmarkBubbleView::IsShowing());
}
<commit_msg>Add test for clicking bookmark star in presence of ctrl-D keybinding<commit_after>// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/app/chrome_command_ids.h"
#include "chrome/browser/extensions/api/commands/command_service.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_commands.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/browser/ui/views/bookmarks/bookmark_bubble_view.h"
#include "chrome/browser/ui/views/frame/browser_view.h"
#include "chrome/browser/ui/views/location_bar/star_view.h"
#include "chrome/browser/ui/views/toolbar/toolbar_view.h"
#include "chrome/test/base/ui_test_utils.h"
#include "extensions/common/manifest_constants.h"
#include "extensions/test/result_catcher.h"
typedef ExtensionApiTest BookmarkOverrideTest;
namespace {
// Bookmark this page keybinding.
#if defined(OS_MACOSX)
const char kBookmarkKeybinding[] = "Command+D";
#else
const char kBookmarkKeybinding[] = "Ctrl+D";
#endif // defined(OS_MACOSX)
}
// Test that clicking the star brings up the bookmark UI, if no extension
// requests to override ctrl-D and the user has assigned it to an extension.
IN_PROC_BROWSER_TEST_F(BookmarkOverrideTest, NonOverrideStarClick) {
ASSERT_TRUE(test_server()->Start());
ASSERT_TRUE(RunExtensionTest("keybinding/basics")) << message_;
const extensions::Extension* extension = GetSingleLoadedExtension();
extensions::CommandService* command_service =
extensions::CommandService::Get(browser()->profile());
// Simulate the user setting the keybinding to Ctrl+D.
command_service->UpdateKeybindingPrefs(
extension->id(), extensions::manifest_values::kBrowserActionCommandEvent,
kBookmarkKeybinding);
// Check that the BookmarkBubbleView is shown when clicking on the star.
BrowserView* browser_view = reinterpret_cast<BrowserView*>(
browser()->window());
views::View* star_view =
browser_view->GetToolbarView()->location_bar()->star_view();
ui::MouseEvent pressed_event(ui::ET_MOUSE_PRESSED, gfx::Point(), gfx::Point(),
ui::EF_LEFT_MOUSE_BUTTON,
ui::EF_LEFT_MOUSE_BUTTON);
ui::MouseEvent released_event(ui::ET_MOUSE_RELEASED, gfx::Point(),
gfx::Point(), ui::EF_LEFT_MOUSE_BUTTON,
ui::EF_LEFT_MOUSE_BUTTON);
// Verify that clicking once shows the bookmark bubble.
EXPECT_FALSE(BookmarkBubbleView::IsShowing());
star_view->OnMousePressed(pressed_event);
EXPECT_FALSE(BookmarkBubbleView::IsShowing());
star_view->OnMouseReleased(released_event);
EXPECT_TRUE(BookmarkBubbleView::IsShowing());
}
// Test that invoking the IDC_BOOKMARK_PAGE command (as done by the wrench menu)
// brings up the bookmark UI, if no extension requests to override ctrl-D and
// the user has assigned it to an extension.
IN_PROC_BROWSER_TEST_F(BookmarkOverrideTest, NonOverrideBookmarkPage) {
ASSERT_TRUE(test_server()->Start());
ASSERT_TRUE(RunExtensionTest("keybinding/basics")) << message_;
const extensions::Extension* extension = GetSingleLoadedExtension();
extensions::CommandService* command_service =
extensions::CommandService::Get(browser()->profile());
// Simulate the user setting the keybinding to Ctrl+D.
command_service->UpdateKeybindingPrefs(
extension->id(), extensions::manifest_values::kBrowserActionCommandEvent,
kBookmarkKeybinding);
// Check that the BookmarkBubbleView is shown when executing
// IDC_BOOKMARK_PAGE.
EXPECT_FALSE(BookmarkBubbleView::IsShowing());
chrome::ExecuteCommand(browser(), IDC_BOOKMARK_PAGE);
EXPECT_TRUE(BookmarkBubbleView::IsShowing());
}
<|endoftext|>
|
<commit_before>/*
Q Light Controller Plus
oscpacketizer.cpp
Copyright (c) Massimo Callegari
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.
*/
#include "oscpacketizer.h"
#include <QStringList>
#include <QDebug>
OSCPacketizer::OSCPacketizer()
{
}
OSCPacketizer::~OSCPacketizer()
{
}
/*********************************************************************
* Sender functions
*********************************************************************/
void OSCPacketizer::setupOSCDmx(QByteArray &data, quint32 universe, quint32 channel, uchar value)
{
data.clear();
QString path = QString("/%1/dmx/%2").arg(universe).arg(channel);
data.append(path);
// add trailing zeros to reach a multiple of 4
int zeroNumber = 4 - (path.length() % 4);
if (zeroNumber != 0 && zeroNumber != 4)
data.append(QByteArray(zeroNumber, 0x00));
data.append(",f");
data.append((char)0x00);
data.append((char)0x00);
float fVal = (float)value;
data.append(*(((char *)&fVal) + 3));
data.append(*(((char *)&fVal) + 2));
data.append(*(((char *)&fVal) + 1));
data.append(*(((char *)&fVal) + 0));
}
void OSCPacketizer::setupOSCGeneric(QByteArray &data, QString &path, QString types, QByteArray &values)
{
data.clear();
if (path.isEmpty())
{
qDebug() << Q_FUNC_INFO << "Empty path, can't create packet";
return;
}
data.append(path);
// add trailing zeros to reach a multiple of 4
int zeroNumber = 4 - (path.length() % 4);
if (zeroNumber > 0)
data.append(QByteArray(zeroNumber, 0x00));
data.append(",");
data.append(types);
zeroNumber = 4 - ((types.length() + 1) % 4);
if (zeroNumber > 0)
data.append(QByteArray(zeroNumber, 0x00));
for (int i = 0; i < types.length() && i < values.length(); i++)
{
if (types.at(i) == 'f')
{
uchar val = (uchar)values.at(i);
float fVal = (float)val / 255.0;
data.append(*(((char *)&fVal) + 3));
data.append(*(((char *)&fVal) + 2));
data.append(*(((char *)&fVal) + 1));
data.append(*(((char *)&fVal) + 0));
}
}
}
/*********************************************************************
* Receiver functions
*********************************************************************/
bool OSCPacketizer::parseMessage(QByteArray &data, QString &path, QByteArray &values)
{
path.clear();
values.clear();
QList<TagType> typeArray;
bool tagsEnded = false;
// first of all look for a comma
int commaPos = data.indexOf(0x2C);
if (commaPos == -1)
return false;
path = QString(data.mid(0, commaPos));
qDebug() << " [OSC] path extracted:" << path;
int currPos = commaPos + 1;
while (tagsEnded == false)
{
switch (data.at(currPos))
{
case 0x00: tagsEnded = true; break;
case 0x62: /* 'b' */ typeArray.append(Blob); break;
case 0x66: /* 'f' */ typeArray.append(Float); break;
case 0x69: /* 'i' */ typeArray.append(Integer); break;
case 0x73: /* 's' */ typeArray.append(String); break;
default: break;
}
currPos++;
}
// round current position to 4
if (typeArray.count() < 4)
currPos += (2 - typeArray.count());
qDebug () << "[OSC] Tags found:" << typeArray.count() << "currpos at" << currPos;
foreach(TagType tag, typeArray)
{
switch (tag)
{
case Integer:
{
if (currPos + 4 > data.size())
break;
quint32 iVal;
*((uchar*)(&iVal) + 3) = data.at(currPos);
*((uchar*)(&iVal) + 2) = data.at(currPos + 1);
*((uchar*)(&iVal) + 1) = data.at(currPos + 2);
*((uchar*)(&iVal) + 0) = data.at(currPos + 3);
if (iVal < 256)
values.append((char)iVal);
else
values.append((char)(iVal / 0xFFFFFF));
qDebug() << "[OSC] iVal:" << iVal;
currPos += 4;
}
break;
case Float:
{
if (currPos + 4 > data.size())
break;
float fVal;
*((uchar*)(&fVal) + 3) = data.at(currPos);
*((uchar*)(&fVal) + 2) = data.at(currPos + 1);
*((uchar*)(&fVal) + 1) = data.at(currPos + 2);
*((uchar*)(&fVal) + 0) = data.at(currPos + 3);
values.append((char)(255.0 * fVal));
qDebug() << "[OSC] fVal:" << fVal;
currPos += 4;
}
break;
case String:
{
int firstZeroPos = data.indexOf('\0', currPos);
QString str = QString(data.mid(currPos, firstZeroPos - currPos));
qDebug() << "[OSC] sVal:" << str;
// align current position to a multiple of 4
int zeroNumber = 4 - (str.length() % 4);
currPos = firstZeroPos + zeroNumber;
}
break;
default: break;
}
}
return true;
}
<commit_msg>plugins/osc: fixed 0 padding of generic outgoing packets<commit_after>/*
Q Light Controller Plus
oscpacketizer.cpp
Copyright (c) Massimo Callegari
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.
*/
#include "oscpacketizer.h"
#include <QStringList>
#include <QDebug>
OSCPacketizer::OSCPacketizer()
{
}
OSCPacketizer::~OSCPacketizer()
{
}
/*********************************************************************
* Sender functions
*********************************************************************/
void OSCPacketizer::setupOSCDmx(QByteArray &data, quint32 universe, quint32 channel, uchar value)
{
data.clear();
QString path = QString("/%1/dmx/%2").arg(universe).arg(channel);
data.append(path);
// add trailing zeros to reach a multiple of 4
int zeroNumber = 4 - (path.length() % 4);
if (zeroNumber > 0)
data.append(QByteArray(zeroNumber, 0x00));
data.append(",f");
data.append((char)0x00);
data.append((char)0x00);
float fVal = (float)value;
data.append(*(((char *)&fVal) + 3));
data.append(*(((char *)&fVal) + 2));
data.append(*(((char *)&fVal) + 1));
data.append(*(((char *)&fVal) + 0));
}
void OSCPacketizer::setupOSCGeneric(QByteArray &data, QString &path, QString types, QByteArray &values)
{
data.clear();
if (path.isEmpty())
{
qDebug() << Q_FUNC_INFO << "Empty path, can't create packet";
return;
}
data.append(path);
// add trailing zeros to reach a multiple of 4
int zeroNumber = 4 - (path.length() % 4);
if (zeroNumber > 0)
data.append(QByteArray(zeroNumber, 0x00));
data.append(",");
data.append(types);
zeroNumber = 4 - ((types.length() + 1) % 4);
if (zeroNumber > 0)
data.append(QByteArray(zeroNumber, 0x00));
for (int i = 0; i < types.length() && i < values.length(); i++)
{
if (types.at(i) == 'f')
{
uchar val = (uchar)values.at(i);
float fVal = (float)val / 255.0;
data.append(*(((char *)&fVal) + 3));
data.append(*(((char *)&fVal) + 2));
data.append(*(((char *)&fVal) + 1));
data.append(*(((char *)&fVal) + 0));
}
}
}
/*********************************************************************
* Receiver functions
*********************************************************************/
bool OSCPacketizer::parseMessage(QByteArray &data, QString &path, QByteArray &values)
{
path.clear();
values.clear();
QList<TagType> typeArray;
bool tagsEnded = false;
// first of all look for a comma
int commaPos = data.indexOf(0x2C);
if (commaPos == -1)
return false;
path = QString(data.mid(0, commaPos));
qDebug() << " [OSC] path extracted:" << path;
int currPos = commaPos + 1;
while (tagsEnded == false)
{
switch (data.at(currPos))
{
case 0x00: tagsEnded = true; break;
case 0x62: /* 'b' */ typeArray.append(Blob); break;
case 0x66: /* 'f' */ typeArray.append(Float); break;
case 0x69: /* 'i' */ typeArray.append(Integer); break;
case 0x73: /* 's' */ typeArray.append(String); break;
default: break;
}
currPos++;
}
// round current position to 4
if (typeArray.count() < 4)
currPos += (2 - typeArray.count());
qDebug () << "[OSC] Tags found:" << typeArray.count() << "currpos at" << currPos;
foreach(TagType tag, typeArray)
{
switch (tag)
{
case Integer:
{
if (currPos + 4 > data.size())
break;
quint32 iVal;
*((uchar*)(&iVal) + 3) = data.at(currPos);
*((uchar*)(&iVal) + 2) = data.at(currPos + 1);
*((uchar*)(&iVal) + 1) = data.at(currPos + 2);
*((uchar*)(&iVal) + 0) = data.at(currPos + 3);
if (iVal < 256)
values.append((char)iVal);
else
values.append((char)(iVal / 0xFFFFFF));
qDebug() << "[OSC] iVal:" << iVal;
currPos += 4;
}
break;
case Float:
{
if (currPos + 4 > data.size())
break;
float fVal;
*((uchar*)(&fVal) + 3) = data.at(currPos);
*((uchar*)(&fVal) + 2) = data.at(currPos + 1);
*((uchar*)(&fVal) + 1) = data.at(currPos + 2);
*((uchar*)(&fVal) + 0) = data.at(currPos + 3);
values.append((char)(255.0 * fVal));
qDebug() << "[OSC] fVal:" << fVal;
currPos += 4;
}
break;
case String:
{
int firstZeroPos = data.indexOf('\0', currPos);
QString str = QString(data.mid(currPos, firstZeroPos - currPos));
qDebug() << "[OSC] sVal:" << str;
// align current position to a multiple of 4
int zeroNumber = 4 - (str.length() % 4);
currPos = firstZeroPos + zeroNumber;
}
break;
default: break;
}
}
return true;
}
<|endoftext|>
|
<commit_before>// webadmin.cpp : Defines the entry point for the DLL application.
//
#include "bzfsAPI.h"
#include "plugin_utils.h"
#include "plugin_HTTP.h"
#include <fstream>
#include <cstring>
#include <algorithm>
class WebAdmin : public BZFSHTTPAuth, TemplateCallbackClass
{
public:
WebAdmin();
virtual const char * getVDir ( void ){return "webadmin";}
virtual const char * getDescription ( void ){return "Server Administration (Login Required)";}
void init (const char *tDir);
virtual bool handleAuthedRequest ( int level, const HTTPRequest &request, HTTPReply &reply );
// from TemplateCallbackClass
virtual void keyCallback (std::string &data, const std::string &key);
virtual bool loopCallback (const std::string &key);
virtual bool ifCallback (const std::string &key);
private:
size_t loopPos;
std::map<std::string,std::string> templateVars;
typedef void (WebAdmin::*page_callback)(const HTTPRequest &);
std::map<std::string,page_callback> controllers;
std::vector<std::string> pagenames;
void mainPageCallback (const HTTPRequest &request);
void banlistPageCallback (const HTTPRequest &request);
bz_APIIntList players;
};
WebAdmin *webAdmin = NULL;
BZ_GET_PLUGIN_VERSION
BZF_PLUGIN_CALL int bz_Load(const char* commandLine)
{
if(webAdmin)
delete(webAdmin);
webAdmin = new WebAdmin;
webAdmin->init(commandLine);
bz_debugMessage(4,"webadmin plugin loaded");
return 0;
}
BZF_PLUGIN_CALL int bz_Unload(void)
{
if(webAdmin)
delete(webAdmin);
webAdmin = NULL;
bz_debugMessage(4,"webadmin plugin unloaded");
return 0;
}
WebAdmin::WebAdmin():BZFSHTTPAuth(),loopPos(0)
{
registerVDir();
// add new pages here
controllers["main"] = &WebAdmin::mainPageCallback;
controllers["banlist"] = &WebAdmin::banlistPageCallback;
controllers["helpmsg"] = NULL;
controllers["group"] = NULL;
std::map<std::string,page_callback>::iterator pair;
for(pair = controllers.begin(); pair != controllers.end(); pair++)
pagenames.push_back(pair->first);
}
void WebAdmin::init(const char* cmdln)
{
templateSystem.addSearchPath(cmdln ? cmdln : "./");
// level one has admin perms
addPermToLevel(1,"ADMIN");
templateSystem.addIF("IsCurrentPage",this);
templateSystem.addIF("Error",this);
templateSystem.addKey("Error",this);
templateSystem.addKey("Callsign",this);
templateSystem.addKey("BannedUser",this);
templateSystem.addKey("PageName",this);
templateSystem.addLoop("Navigation",this);
templateSystem.addLoop("Players",this);
templateSystem.addLoop("IPBanList",this);
templateSystem.addLoop("IDBanList",this);
templateSystem.setPluginName("webadmin", getBaseURL().c_str());
setupAuth();
}
// event hook for [$Something] in templates
void WebAdmin::keyCallback (std::string &data, const std::string &key)
{
const std::map<std::string,std::string>::iterator &pair = templateVars.find(key);
if (pair != templateVars.end())
data = pair->second;
}
// condition check for [*START] in templates
bool WebAdmin::loopCallback (const std::string &key)
{
if (key == "players") {
if (!loopPos) bz_getPlayerIndexList(&players);
else if (loopPos < players.size()) {
templateVars["playerid"] = players[loopPos];
templateVars["callsign"] = bz_getPlayerCallsign(players[loopPos++]);
return true;
} else {
players.clear();
return loopPos = 0;
}
} else if (key == "navigation") {
if (loopPos < pagenames.size()) {
templateVars["pagename"] = pagenames[loopPos++];
return true;
} else return loopPos = 0;
} else if (key == "permissions") {
if (loopPos < bzu_standardPerms().size()) {
templateVars["permission"] = bzu_standardPerms()[loopPos++];
return true;
} else return loopPos = 0;
} else return false;
}
// condition check for [?IF] in templates
bool WebAdmin::ifCallback (const std::string &key)
{
if (key == "iscurrentpage")
return templateVars["pagename"] == templateVars["currentpage"];
return false;
}
bool WebAdmin::handleAuthedRequest ( int level, const HTTPRequest &request, HTTPReply &reply )
{
std::map<std::string,page_callback>::iterator pair;
size_t last;
std::string pagename = request.resource;
switch(level) {
case 1:
case VERIFIED:
last = pagename.size()-1;
if (pagename[last] == '/') pagename.erase(last);
if (pagename.empty()) pagename = "main";
pair = controllers.find(pagename);
if (pair != controllers.end()) {
(this->*pair->second)(request);
if (!templateSystem.processTemplateFile(reply.body, (pagename + ".tmpl").c_str())) {
reply.returnCode = HTTPReply::e500ServerError;
if (!templateSystem.processTemplateFile(reply.body, "500.tmpl"))
reply.body = format("Missing template: %s.tmpl", pagename.c_str());
}
} else {
reply.returnCode = HTTPReply::e404NotFound;
if (!templateSystem.processTemplateFile(reply.body, "404.tmpl"))
reply.body = format("No such resource: %s", pagename.c_str());
}
break;
//reply.body = format("Not authenticated(Verified) sessionID %d",request.sessionID);
default:
reply.body = format("Not authenticated sessionID %d",request.sessionID);
}
reply.docType = HTTPReply::eHTML;
templateVars.clear();
return true;
}
void WebAdmin::mainPageCallback (const HTTPRequest &request)
{
if (request.request != ePost) return;
std::vector<std::string> players;
if (!request.getParam("players", players)) return;
std::string dummy, reason;
bool notify = request.getParam("notify", dummy);
request.getParam("reason", reason);
std::vector<std::string>::iterator i;
if (request.getParam("kick", dummy))
for (i = players.begin(); i != players.end(); i++)
bz_kickUser(atoi(i->c_str()), reason.c_str(), notify);
else if (request.getParam("ipban", players)) {
request.getParam("duration", dummy);
int duration = atoi(dummy.c_str());
for (i = players.begin(); i != players.end(); i++) {
int playerID = atoi(i->c_str());
bz_BasePlayerRecord *player = bz_getPlayerByIndex(playerID);
bz_IPBanUser(playerID, bz_getPlayerIPAddress(playerID), duration, reason.c_str());
}
}
else if (request.getParam("idban", players)) {
request.getParam("duration", dummy);
int duration = atoi(dummy.c_str());
for (i = players.begin(); i != players.end(); i++) {
int playerID = atoi(i->c_str());
bz_BasePlayerRecord *player = bz_getPlayerByIndex(playerID);
bz_IPBanUser(playerID, bz_getPlayerCallsign(playerID), duration, reason.c_str());
}
}
}
void WebAdmin::banlistPageCallback (const HTTPRequest &request)
{
if (request.request != ePost) return;
std::vector<std::string> banRemovals;
std::vector<std::string>::iterator i;
if (request.getParam("delip", banRemovals))
for(i = banRemovals.begin(); i != banRemovals.end(); i++)
bz_IPUnbanUser(i->c_str());
if (request.getParam("delid", banRemovals))
for(i = banRemovals.begin(); i != banRemovals.end(); i++)
bz_IDUnbanUser(i->c_str());
}
// Local Variables: ***
// mode: C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=2 expandtab
<commit_msg>more keys, ifs, loops<commit_after>// webadmin.cpp : Defines the entry point for the DLL application.
//
#include "bzfsAPI.h"
#include "plugin_utils.h"
#include "plugin_HTTP.h"
#include <fstream>
#include <cstring>
#include <algorithm>
class WebAdmin : public BZFSHTTPAuth, TemplateCallbackClass
{
public:
WebAdmin();
virtual const char * getVDir ( void ){return "webadmin";}
virtual const char * getDescription ( void ){return "Server Administration (Login Required)";}
void init (const char *tDir);
virtual bool handleAuthedRequest ( int level, const HTTPRequest &request, HTTPReply &reply );
// from TemplateCallbackClass
virtual void keyCallback (std::string &data, const std::string &key);
virtual bool loopCallback (const std::string &key);
virtual bool ifCallback (const std::string &key);
private:
unsigned int loopPos;
std::map<std::string,std::string> templateVars;
typedef void (WebAdmin::*page_callback)(const HTTPRequest &);
std::map<std::string,page_callback> controllers;
std::vector<std::string> pagenames;
void mainPageCallback (const HTTPRequest &request);
void banlistPageCallback (const HTTPRequest &request);
bz_APIIntList players;
bz_APIStringList *stringList;
bool editing;
};
WebAdmin *webAdmin = NULL;
BZ_GET_PLUGIN_VERSION
BZF_PLUGIN_CALL int bz_Load(const char* commandLine)
{
if(webAdmin)
delete(webAdmin);
webAdmin = new WebAdmin;
webAdmin->init(commandLine);
bz_debugMessage(4,"webadmin plugin loaded");
return 0;
}
BZF_PLUGIN_CALL int bz_Unload(void)
{
if(webAdmin)
delete(webAdmin);
webAdmin = NULL;
bz_debugMessage(4,"webadmin plugin unloaded");
return 0;
}
WebAdmin::WebAdmin():BZFSHTTPAuth(),loopPos(0)
{
registerVDir();
// add new pages here
controllers["main"] = &WebAdmin::mainPageCallback;
controllers["banlist"] = &WebAdmin::banlistPageCallback;
controllers["helpmsg"] = NULL;
controllers["group"] = NULL;
std::map<std::string,page_callback>::iterator pair;
for(pair = controllers.begin(); pair != controllers.end(); pair++)
pagenames.push_back(pair->first);
}
void WebAdmin::init(const char* cmdln)
{
templateSystem.addSearchPath(cmdln ? cmdln : "./");
// level one has admin perms
addPermToLevel(1,"ADMIN");
templateSystem.addIF("IsCurrentPage",this);
templateSystem.addIF("Error",this);
templateSystem.addIF("Editing",this);
templateSystem.addKey("Error",this);
templateSystem.addKey("Callsign",this);
templateSystem.addKey("BannedUser",this);
templateSystem.addKey("PageName",this);
templateSystem.addKey("HelpMsgName",this);
templateSystem.addKey("HelpMsgBody",this);
templateSystem.addKey("GroupName",this);
templateSystem.addLoop("Navigation",this);
templateSystem.addLoop("Players",this);
templateSystem.addLoop("IPBanList",this);
templateSystem.addLoop("IDBanList",this);
templateSystem.addLoop("HelpMsgs",this);
templateSystem.addLoop("Groups",this);
templateSystem.setPluginName("webadmin", getBaseURL().c_str());
setupAuth();
}
// event hook for [$Something] in templates
void WebAdmin::keyCallback (std::string &data, const std::string &key)
{
const std::map<std::string,std::string>::iterator &pair = templateVars.find(key);
if (pair != templateVars.end())
data = pair->second;
}
// condition check for [*START] in templates
bool WebAdmin::loopCallback (const std::string &key)
{
if (key == "players") {
if (!loopPos) bz_getPlayerIndexList(&players);
else if (loopPos < players.size()) {
templateVars["playerid"] = players[loopPos];
templateVars["callsign"] = bz_getPlayerCallsign(players[loopPos++]);
return true;
} else {
players.clear();
return loopPos = 0;
}
} else if (key == "navigation") {
if (loopPos < pagenames.size()) {
templateVars["pagename"] = pagenames[loopPos++];
return true;
} else return loopPos = 0;
} else if (key == "permissions") {
if (loopPos < bzu_standardPerms().size()) {
templateVars["permission"] = bzu_standardPerms()[loopPos++];
return true;
} else return loopPos = 0;
} else if (key == "helpmsgs") {
if (!loopPos) stringList = bz_getHelpTopics();
if (loopPos < stringList.size()) {
templateVare["helpmsgname"] = stringList[loopPos++].c_str();
return true;
} else {
delete(stringList);
return loopPos = 0;
}
} else if (key == "groups") {
if (!loopPos) stringList = bz_getGroupList();
if (loopPos < stringList.size()) {
templateVare["groupname"] = stringList[loopPos++].c_str();
return true;
} else {
delete(stringList);
return loopPos = 0;
}
} else return false;
}
// condition check for [?IF] in templates
bool WebAdmin::ifCallback (const std::string &key)
{
if (key == "iscurrentpage")
return templateVars["pagename"] == templateVars["currentpage"];
if (key == "editing")
return editing;
return false;
}
bool WebAdmin::handleAuthedRequest ( int level, const HTTPRequest &request, HTTPReply &reply )
{
std::map<std::string,page_callback>::iterator pair;
size_t last;
std::string pagename = request.resource;
switch(level) {
case 1:
case VERIFIED:
last = pagename.size()-1;
if (pagename[last] == '/') pagename.erase(last);
if (pagename.empty()) pagename = "main";
pair = controllers.find(pagename);
if (pair != controllers.end()) {
(this->*pair->second)(request);
if (!templateSystem.processTemplateFile(reply.body, (pagename + ".tmpl").c_str())) {
reply.returnCode = HTTPReply::e500ServerError;
if (!templateSystem.processTemplateFile(reply.body, "500.tmpl"))
reply.body = format("Missing template: %s.tmpl", pagename.c_str());
}
} else {
reply.returnCode = HTTPReply::e404NotFound;
if (!templateSystem.processTemplateFile(reply.body, "404.tmpl"))
reply.body = format("No such resource: %s", pagename.c_str());
}
break;
//reply.body = format("Not authenticated(Verified) sessionID %d",request.sessionID);
default:
reply.body = format("Not authenticated sessionID %d, access level %d",request.sessionID,level);
}
reply.docType = HTTPReply::eHTML;
templateVars.clear();
return true;
}
void WebAdmin::mainPageCallback (const HTTPRequest &request)
{
if (request.request != ePost) return;
std::vector<std::string> players;
if (!request.getParam("players", players)) return;
std::string dummy, reason;
bool notify = request.getParam("notify", dummy);
request.getParam("reason", reason);
std::vector<std::string>::iterator i;
if (request.getParam("kick", dummy))
for (i = players.begin(); i != players.end(); i++)
bz_kickUser(atoi(i->c_str()), reason.c_str(), notify);
else if (request.getParam("ipban", players)) {
request.getParam("duration", dummy);
int duration = atoi(dummy.c_str());
for (i = players.begin(); i != players.end(); i++) {
int playerID = atoi(i->c_str());
bz_BasePlayerRecord *player = bz_getPlayerByIndex(playerID);
bz_IPBanUser(playerID, bz_getPlayerIPAddress(playerID), duration, reason.c_str());
}
}
else if (request.getParam("idban", players)) {
request.getParam("duration", dummy);
int duration = atoi(dummy.c_str());
for (i = players.begin(); i != players.end(); i++) {
int playerID = atoi(i->c_str());
bz_BasePlayerRecord *player = bz_getPlayerByIndex(playerID);
bz_IPBanUser(playerID, bz_getPlayerCallsign(playerID), duration, reason.c_str());
}
}
}
void WebAdmin::banlistPageCallback (const HTTPRequest &request)
{
if (request.request != ePost) return;
std::vector<std::string> banRemovals;
std::vector<std::string>::iterator i;
if (request.getParam("delip", banRemovals))
for(i = banRemovals.begin(); i != banRemovals.end(); i++)
bz_IPUnbanUser(i->c_str());
if (request.getParam("delid", banRemovals))
for(i = banRemovals.begin(); i != banRemovals.end(); i++)
bz_IDUnbanUser(i->c_str());
}
// Local Variables: ***
// mode: C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=2 expandtab
<|endoftext|>
|
<commit_before>#include "ovpCXMLStimulationScenarioPlayer.h"
#include <fstream>
#include <iostream>
using namespace OpenViBE;
using namespace OpenViBE::Plugins;
using namespace OpenViBE::Kernel;
using namespace OpenViBEPlugins;
using namespace OpenViBEPlugins::Stimulation;
using namespace OpenViBEToolkit;
using namespace std;
namespace OpenViBEPlugins
{
namespace Stimulation
{
void CXMLStimulationScenarioPlayer::writeStimulationOutput(const void* pBuffer, const EBML::uint64 ui64BufferSize)
{
appendOutputChunkData<0>(pBuffer, ui64BufferSize);
}
void CXMLStimulationScenarioPlayer::setStimulationCount(const uint32 ui32StimulationCount)
{
/* TODO nothing? */
}
void CXMLStimulationScenarioPlayer::setStimulation(const uint32 ui32StimulationIndex, const uint64 ui64StimulationIdentifier, const uint64 ui64StimulationDate)
{
m_oStimulationReceived.push_back(pair<uint64, uint64>(ui64StimulationIdentifier, ui64StimulationDate));
}
boolean CXMLStimulationScenarioPlayer::readAutomaton(const CString& oFilename)
{
ifstream l_oFile(oFilename.toASCIIString());
if(!l_oFile.good())
{
return false;
}
size_t l_iFileSize = 0;
l_oFile.seekg(0, ios::end);
l_iFileSize = l_oFile.tellg();
l_oFile.seekg(0, ios::beg);
char * l_pXmlBuffer = new char[l_iFileSize];
l_oFile.read(l_pXmlBuffer, l_iFileSize);
m_pXMLAutomatonReader->processData(l_pXmlBuffer, l_iFileSize);
l_oFile.close();
return true;
}
CXMLStimulationScenarioPlayer::CXMLStimulationScenarioPlayer(void) :
m_pReader(NULL),
m_pStimulationReaderCallBack(NULL),
m_pWriter(NULL),
m_pOutputWriterCallbackProxy(NULL),
m_pStimulationOutputWriterHelper(NULL),
m_pXMLAutomatonReader(NULL),
m_pAutomatonController(NULL),
m_pAutomatonContext(NULL),
m_bEndOfAutomaton(false),
m_ui64PreviousActivationTime(0)
{
}
boolean CXMLStimulationScenarioPlayer::initialize()
{
m_bEndOfAutomaton = false;
m_pStimulationReaderCallBack=createBoxAlgorithmStimulationInputReaderCallback(*this);
m_pReader = EBML::createReader(*m_pStimulationReaderCallBack);
m_pOutputWriterCallbackProxy = new EBML::TWriterCallbackProxy1<OpenViBEPlugins::Stimulation::CXMLStimulationScenarioPlayer>(*this, &CXMLStimulationScenarioPlayer::writeStimulationOutput);
m_pWriter=EBML::createWriter(*m_pOutputWriterCallbackProxy);
m_pStimulationOutputWriterHelper=createBoxAlgorithmStimulationOutputWriter();
const IBox* l_pBoxContext=getBoxAlgorithmContext()->getStaticBoxContext();
CString l_sFileName;
m_pXMLAutomatonReader = Automaton::createXMLAutomatonReader();
// Parses box settings to find input file's name
l_pBoxContext->getSettingValue(0, l_sFileName);
if(!readAutomaton(l_sFileName))
{
getBoxAlgorithmContext()->getPlayerContext()->getLogManager() << LogLevel_Warning << "Could not read automaton file\n";
return false;
}
m_pAutomatonController = m_pXMLAutomatonReader->getAutomatonController();
m_pAutomatonContext = m_pAutomatonController->getAutomatonContext();
//we don't need the XML reader anymore
releaseXMLAutomatonReader(m_pXMLAutomatonReader);
m_pStimulationOutputWriterHelper->writeHeader(*m_pWriter);
getBoxAlgorithmContext()->getDynamicBoxContext()->markOutputAsReadyToSend(0, 0, 0);
return true;
}
boolean CXMLStimulationScenarioPlayer::uninitialize()
{
releaseBoxAlgorithmStimulationInputReaderCallback(m_pStimulationReaderCallBack);
delete m_pOutputWriterCallbackProxy;
m_pOutputWriterCallbackProxy= NULL;
m_pWriter->release();
m_pWriter = NULL;
releaseBoxAlgorithmStimulationOutputWriter(m_pStimulationOutputWriterHelper);
m_pStimulationOutputWriterHelper=NULL;
releaseAutomatonController(m_pAutomatonController);
m_pAutomatonController=NULL;
releaseAutomatonContext(m_pAutomatonContext);
m_pAutomatonContext=NULL;
return true;
}
boolean CXMLStimulationScenarioPlayer::processInput(uint32 ui32InputIndex)
{
IDynamicBoxContext* l_pDynamicBoxContext=getBoxAlgorithmContext()->getDynamicBoxContext();
for(uint32 i=0; i<l_pDynamicBoxContext->getInputChunkCount(ui32InputIndex); i++)
{
uint64 l_ui64StartTime;
uint64 l_ui64EndTime;
uint64 l_ui64ChunkSize;
const uint8* l_pChunkBuffer=NULL;
if(l_pDynamicBoxContext->getInputChunk(ui32InputIndex, i, l_ui64StartTime, l_ui64EndTime, l_ui64ChunkSize, l_pChunkBuffer))
{
m_pReader->processData(l_pChunkBuffer, l_ui64ChunkSize);
}
l_pDynamicBoxContext->markInputAsDeprecated(ui32InputIndex, i);
}
getBoxAlgorithmContext()->markAlgorithmAsReadyToProcess();
return true;
}
boolean CXMLStimulationScenarioPlayer::processClock(CMessageClock &rMessageClock)
{
uint64 l_ui64CurrentTime = rMessageClock.getTime();
IDynamicBoxContext * l_pDynamicBoxContext = getBoxAlgorithmContext()->getDynamicBoxContext();
if(!m_bEndOfAutomaton)
{
//actualize context
m_pAutomatonContext->setCurrentTime(rMessageClock.getTime());
for(size_t i=0 ; i<m_oStimulationReceived.size() ; i++)
{
Automaton::CIdentifier l_oStimulationIdentifier = m_oStimulationReceived[i].first;
m_pAutomatonContext->addReceivedEvent(l_oStimulationIdentifier);
}
//process
m_bEndOfAutomaton = m_pAutomatonController->process();
const Automaton::CIdentifier * l_pSentEvents = m_pAutomatonContext->getSentEvents();
//set the number of stimulation to send
m_pStimulationOutputWriterHelper->setStimulationCount(m_pAutomatonContext->getSentEventsCount());
//if there were stimulations
if(l_pSentEvents)
{
//adds em
for(uint32 i = 0 ; i<m_pAutomatonContext->getSentEventsCount() ; i++)
{
/* TODO check Stimulation date */
m_pStimulationOutputWriterHelper->setStimulation(i, l_pSentEvents[i], l_ui64CurrentTime);
}
}
m_pStimulationOutputWriterHelper->writeBuffer(*m_pWriter);
/* TODO check Stimulation date */
l_pDynamicBoxContext->markOutputAsReadyToSend(0, m_ui64PreviousActivationTime, l_ui64CurrentTime);
m_pAutomatonContext->clearSentEvents();
//TODO clear all events?? or just used ones?
m_pAutomatonContext->clearReceivedEvents();
}
m_ui64PreviousActivationTime = l_ui64CurrentTime;
getBoxAlgorithmContext()->markAlgorithmAsReadyToProcess();
return true;
}
boolean CXMLStimulationScenarioPlayer::process()
{
// l_pDynamicBoxContext->markOutputAsReadyToSend(0, 0, 0);
return true;
}
};
};
<commit_msg>openvibe-plugins-stimulation : * XML stimulation scenario player: corrected bug causing crash when the scenario file could not be opened<commit_after>#include "ovpCXMLStimulationScenarioPlayer.h"
#include <fstream>
#include <iostream>
using namespace OpenViBE;
using namespace OpenViBE::Plugins;
using namespace OpenViBE::Kernel;
using namespace OpenViBEPlugins;
using namespace OpenViBEPlugins::Stimulation;
using namespace OpenViBEToolkit;
using namespace std;
namespace OpenViBEPlugins
{
namespace Stimulation
{
void CXMLStimulationScenarioPlayer::writeStimulationOutput(const void* pBuffer, const EBML::uint64 ui64BufferSize)
{
appendOutputChunkData<0>(pBuffer, ui64BufferSize);
}
void CXMLStimulationScenarioPlayer::setStimulationCount(const uint32 ui32StimulationCount)
{
/* TODO nothing? */
}
void CXMLStimulationScenarioPlayer::setStimulation(const uint32 ui32StimulationIndex, const uint64 ui64StimulationIdentifier, const uint64 ui64StimulationDate)
{
m_oStimulationReceived.push_back(pair<uint64, uint64>(ui64StimulationIdentifier, ui64StimulationDate));
}
boolean CXMLStimulationScenarioPlayer::readAutomaton(const CString& oFilename)
{
ifstream l_oFile(oFilename.toASCIIString());
if(!l_oFile.good())
{
return false;
}
size_t l_iFileSize = 0;
l_oFile.seekg(0, ios::end);
l_iFileSize = l_oFile.tellg();
l_oFile.seekg(0, ios::beg);
char * l_pXmlBuffer = new char[l_iFileSize];
l_oFile.read(l_pXmlBuffer, l_iFileSize);
m_pXMLAutomatonReader->processData(l_pXmlBuffer, l_iFileSize);
l_oFile.close();
return true;
}
CXMLStimulationScenarioPlayer::CXMLStimulationScenarioPlayer(void) :
m_pReader(NULL),
m_pStimulationReaderCallBack(NULL),
m_pWriter(NULL),
m_pOutputWriterCallbackProxy(NULL),
m_pStimulationOutputWriterHelper(NULL),
m_pXMLAutomatonReader(NULL),
m_pAutomatonController(NULL),
m_pAutomatonContext(NULL),
m_bEndOfAutomaton(false),
m_ui64PreviousActivationTime(0)
{
}
boolean CXMLStimulationScenarioPlayer::initialize()
{
m_bEndOfAutomaton = false;
m_pStimulationReaderCallBack=createBoxAlgorithmStimulationInputReaderCallback(*this);
m_pReader = EBML::createReader(*m_pStimulationReaderCallBack);
m_pOutputWriterCallbackProxy = new EBML::TWriterCallbackProxy1<OpenViBEPlugins::Stimulation::CXMLStimulationScenarioPlayer>(*this, &CXMLStimulationScenarioPlayer::writeStimulationOutput);
m_pWriter=EBML::createWriter(*m_pOutputWriterCallbackProxy);
m_pStimulationOutputWriterHelper=createBoxAlgorithmStimulationOutputWriter();
const IBox* l_pBoxContext=getBoxAlgorithmContext()->getStaticBoxContext();
CString l_sFileName;
m_pXMLAutomatonReader = Automaton::createXMLAutomatonReader();
// Parses box settings to find input file's name
l_pBoxContext->getSettingValue(0, l_sFileName);
m_pAutomatonController=NULL;
m_pAutomatonContext=NULL;
if(!readAutomaton(l_sFileName))
{
getBoxAlgorithmContext()->getPlayerContext()->getLogManager() << LogLevel_Warning << "Could not read automaton file\n";
return false;
}
m_pAutomatonController = m_pXMLAutomatonReader->getAutomatonController();
m_pAutomatonContext = m_pAutomatonController->getAutomatonContext();
//we don't need the XML reader anymore
releaseXMLAutomatonReader(m_pXMLAutomatonReader);
m_pStimulationOutputWriterHelper->writeHeader(*m_pWriter);
getBoxAlgorithmContext()->getDynamicBoxContext()->markOutputAsReadyToSend(0, 0, 0);
return true;
}
boolean CXMLStimulationScenarioPlayer::uninitialize()
{
if(m_pStimulationReaderCallBack)
{
releaseBoxAlgorithmStimulationInputReaderCallback(m_pStimulationReaderCallBack);
m_pStimulationReaderCallBack=NULL;
}
delete m_pOutputWriterCallbackProxy;
m_pOutputWriterCallbackProxy=NULL;
if(m_pWriter)
{
m_pWriter->release();
m_pWriter = NULL;
}
if(m_pStimulationOutputWriterHelper)
{
releaseBoxAlgorithmStimulationOutputWriter(m_pStimulationOutputWriterHelper);
m_pStimulationOutputWriterHelper=NULL;
}
if(m_pAutomatonController)
{
releaseAutomatonController(m_pAutomatonController);
m_pAutomatonController=NULL;
}
if(m_pAutomatonContext)
{
releaseAutomatonContext(m_pAutomatonContext);
m_pAutomatonContext=NULL;
}
return true;
}
boolean CXMLStimulationScenarioPlayer::processInput(uint32 ui32InputIndex)
{
IDynamicBoxContext* l_pDynamicBoxContext=getBoxAlgorithmContext()->getDynamicBoxContext();
for(uint32 i=0; i<l_pDynamicBoxContext->getInputChunkCount(ui32InputIndex); i++)
{
uint64 l_ui64StartTime;
uint64 l_ui64EndTime;
uint64 l_ui64ChunkSize;
const uint8* l_pChunkBuffer=NULL;
if(l_pDynamicBoxContext->getInputChunk(ui32InputIndex, i, l_ui64StartTime, l_ui64EndTime, l_ui64ChunkSize, l_pChunkBuffer))
{
m_pReader->processData(l_pChunkBuffer, l_ui64ChunkSize);
}
l_pDynamicBoxContext->markInputAsDeprecated(ui32InputIndex, i);
}
getBoxAlgorithmContext()->markAlgorithmAsReadyToProcess();
return true;
}
boolean CXMLStimulationScenarioPlayer::processClock(CMessageClock &rMessageClock)
{
uint64 l_ui64CurrentTime = rMessageClock.getTime();
IDynamicBoxContext * l_pDynamicBoxContext = getBoxAlgorithmContext()->getDynamicBoxContext();
if(!m_bEndOfAutomaton)
{
//actualize context
m_pAutomatonContext->setCurrentTime(rMessageClock.getTime());
for(size_t i=0 ; i<m_oStimulationReceived.size() ; i++)
{
Automaton::CIdentifier l_oStimulationIdentifier = m_oStimulationReceived[i].first;
m_pAutomatonContext->addReceivedEvent(l_oStimulationIdentifier);
}
//process
m_bEndOfAutomaton = m_pAutomatonController->process();
const Automaton::CIdentifier * l_pSentEvents = m_pAutomatonContext->getSentEvents();
//set the number of stimulation to send
m_pStimulationOutputWriterHelper->setStimulationCount(m_pAutomatonContext->getSentEventsCount());
//if there were stimulations
if(l_pSentEvents)
{
//adds em
for(uint32 i = 0 ; i<m_pAutomatonContext->getSentEventsCount() ; i++)
{
/* TODO check Stimulation date */
m_pStimulationOutputWriterHelper->setStimulation(i, l_pSentEvents[i], l_ui64CurrentTime);
}
}
m_pStimulationOutputWriterHelper->writeBuffer(*m_pWriter);
/* TODO check Stimulation date */
l_pDynamicBoxContext->markOutputAsReadyToSend(0, m_ui64PreviousActivationTime, l_ui64CurrentTime);
m_pAutomatonContext->clearSentEvents();
//TODO clear all events?? or just used ones?
m_pAutomatonContext->clearReceivedEvents();
}
m_ui64PreviousActivationTime = l_ui64CurrentTime;
getBoxAlgorithmContext()->markAlgorithmAsReadyToProcess();
return true;
}
boolean CXMLStimulationScenarioPlayer::process()
{
// l_pDynamicBoxContext->markOutputAsReadyToSend(0, 0, 0);
return true;
}
};
};
<|endoftext|>
|
<commit_before>/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the License);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include <yaml-cpp/yaml.h>
#include "cyber/common/log.h"
#include "modules/perception/camera/common/util.h"
#include "modules/perception/camera/tools/offline/transform_server.h"
namespace apollo {
namespace perception {
namespace camera {
bool TransformServer::Init(const std::vector<std::string> &camera_names,
const std::string ¶ms_path) {
std::string params_dir = params_path;
// 1. init lidar height
try {
YAML::Node lidar_height =
YAML::LoadFile(params_dir + "/" + "velodyne64_height.yaml");
Eigen::Affine3d trans;
trans.linear() = Eigen::Matrix3d::Identity();
AINFO << trans.translation() << " "
<< lidar_height["vehicle"]["parameters"]["height"];
trans.translation() << 0.0, 0.0,
lidar_height["vehicle"]["parameters"]["height"].as<double>();
AddTransform("velodyne64", "ground", trans);
} catch (YAML::InvalidNode &in) {
AERROR << "load velodyne64 extrisic file error"
<< " YAML::InvalidNode exception";
return false;
} catch (YAML::TypedBadConversion<float> &bc) {
AERROR << "load velodyne64 extrisic file error, "
<< "YAML::TypedBadConversion exception";
return false;
} catch (YAML::Exception &e) {
AERROR << "load velodyne64 extrisic file "
<< " error, YAML exception:" << e.what();
return false;
}
// 2. init lidar and camera extrinsic
std::vector<std::string> extrinsic_filelist;
extrinsic_filelist.push_back(
params_dir + "/velodyne64_novatel_extrinsics.yaml");
for (const auto &camera_name : camera_names) {
extrinsic_filelist.push_back(
params_dir + "/" + camera_name + "_extrinsics.yaml");
}
for (const auto &yaml_file : extrinsic_filelist) {
try {
YAML::Node node = YAML::LoadFile(yaml_file);
if (node.IsNull()) {
AINFO << "Load " << yaml_file << " failed! please check!";
return false;
}
std::string child_frame_id = node["child_frame_id"].as<std::string>();
std::string frame_id = node["header"]["frame_id"].as<std::string>();
double q[4] = {node["transform"]["rotation"]["w"].as<double>(),
node["transform"]["rotation"]["x"].as<double>(),
node["transform"]["rotation"]["y"].as<double>(),
node["transform"]["rotation"]["z"].as<double>()};
double t[3] = {node["transform"]["translation"]["x"].as<double>(),
node["transform"]["translation"]["y"].as<double>(),
node["transform"]["translation"]["z"].as<double>()};
Eigen::Quaterniond qq(q[0], q[1], q[2], q[3]);
Eigen::Affine3d trans;
trans.linear() = qq.matrix();
trans.translation() << t[0], t[1], t[2];
bool added = AddTransform(child_frame_id, frame_id, trans);
if (!added) {
AINFO << "failed to add transform from "
<< child_frame_id << " to " << frame_id << std::endl;
}
} catch (YAML::InvalidNode &in) {
AERROR << "load camera extrisic file " << yaml_file
<< " with error, YAML::InvalidNode exception";
return false;
} catch (YAML::TypedBadConversion<double> &bc) {
AERROR << "load camera extrisic file " << yaml_file
<< " with error, YAML::TypedBadConversion exception";
return false;
} catch (YAML::Exception &e) {
AERROR << "load camera extrisic file " << yaml_file
<< " with error, YAML exception:" << e.what();
return false;
}
}
return true;
}
bool TransformServer::LoadFromFile(const std::string &tf_input,
float frequency) {
if (frequency <= 0) {
AERROR << "Error frequency value:" << frequency;
return false;
}
std::ifstream fin(tf_input);
Transform tf;
int64_t ts;
while (fin >> ts) {
tf.timestamp = static_cast<double>(ts) * 1e-9;
fin >> tf.tx;
fin >> tf.ty;
fin >> tf.tz;
fin >> tf.qx;
fin >> tf.qy;
fin >> tf.qz;
fin >> tf.qw;
tf_.push_back(tf);
}
fin.close();
error_limit_ = 1 / frequency / 2.0f;
AINFO << "Load tf successfully. count: " << tf_.size()
<< " error limit:" << error_limit_;
return true;
}
bool TransformServer::QueryPos(double timestamp, Eigen::Affine3d *pose) {
for (auto &&tf : tf_) {
if (Equal(timestamp, tf.timestamp, error_limit_)) {
Eigen::Quaterniond rotation(tf.qw, tf.qx, tf.qy, tf.qz);
pose->linear() = rotation.matrix();
pose->translation() << tf.tx, tf.ty, tf.tz;
AINFO << "Get Pose:\n" << pose->matrix();
return true;
}
}
return false;
}
bool TransformServer::AddTransform(const std::string &child_frame_id,
const std::string &frame_id,
const Eigen::Affine3d &transform) {
vertices_.insert(child_frame_id);
vertices_.insert(frame_id);
auto begin = edges_.lower_bound(child_frame_id);
auto end = edges_.upper_bound(child_frame_id);
for (auto iter = begin; iter != end; ++iter) {
if (iter->second.frame_id == frame_id) {
return false;
}
}
Edge e;
e.child_frame_id = child_frame_id;
e.frame_id = frame_id;
e.transform = transform;
Edge e_inv;
e_inv.child_frame_id = frame_id;
e_inv.frame_id = child_frame_id;
e_inv.transform = transform.inverse();
ADEBUG
<< "Add transform between " << frame_id << " and " << child_frame_id;
edges_.insert({child_frame_id, e});
edges_.insert({frame_id, e_inv});
return true;
}
bool TransformServer::QueryTransform(const std::string &child_frame_id,
const std::string &frame_id,
Eigen::Affine3d *transform) {
*transform = Eigen::Affine3d::Identity();
if (child_frame_id == frame_id) {
return true;
}
auto cf_iter = vertices_.find(child_frame_id);
auto f_iter = vertices_.find(frame_id);
// vertices do not exist
if (cf_iter == vertices_.end() || f_iter == vertices_.end()) {
return false;
}
std::map<std::string, bool> visited;
for (const auto &item : vertices_) {
visited[item] = false;
}
bool bfound = FindTransform(child_frame_id, frame_id, transform, &visited);
return bfound;
}
bool TransformServer::FindTransform(const std::string &child_frame_id,
const std::string &frame_id,
Eigen::Affine3d *transform,
std::map<std::string, bool> *visited) {
Eigen::Affine3d loc_transform = Eigen::Affine3d::Identity();
auto begin = edges_.lower_bound(child_frame_id);
auto end = edges_.upper_bound(child_frame_id);
(*visited)[child_frame_id] = true;
for (auto iter = begin; iter != end; ++iter) {
auto &edge = iter->second;
if ((*visited)[edge.frame_id]) {
continue;
}
ADEBUG
<< "from " << edge.child_frame_id << " to " << edge.frame_id << std::endl;
loc_transform = edge.transform * loc_transform;
if (edge.frame_id == frame_id) {
*transform = loc_transform;
return true;
}
Eigen::Affine3d tr = Eigen::Affine3d::Identity();
bool bfound = FindTransform(edge.frame_id, frame_id, &tr, visited);
if (bfound) {
loc_transform = tr * loc_transform;
*transform = loc_transform;
return true;
}
loc_transform = edge.transform.inverse() * loc_transform;
}
return false;
}
void TransformServer::print() {
for (auto item : edges_) {
AINFO << "----------------" << std::endl;
AINFO << item.first << std::endl;
AINFO << "edge: " << std::endl;
AINFO << "from " << item.second.child_frame_id << " to "
<< item.second.frame_id << std::endl;
Eigen::Affine3d trans = item.second.transform;
Eigen::Quaterniond quat(trans.linear());
AINFO << "rot: " << quat.x() << " " << quat.y() << " " << quat.z() << " "
<< quat.w() << std::endl;
AINFO << "trans: "
<< trans.translation()[0] << " "
<< trans.translation()[1] << " "
<< trans.translation()[2] << std::endl;
}
}
} // namespace camera
} // namespace perception
} // namespace apollo
<commit_msg>Perception: nitpick, remove unnecessay bFound variable (#6768)<commit_after>/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the License);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include <yaml-cpp/yaml.h>
#include "cyber/common/log.h"
#include "modules/perception/camera/common/util.h"
#include "modules/perception/camera/tools/offline/transform_server.h"
namespace apollo {
namespace perception {
namespace camera {
bool TransformServer::Init(const std::vector<std::string> &camera_names,
const std::string ¶ms_path) {
std::string params_dir = params_path;
// 1. init lidar height
try {
YAML::Node lidar_height =
YAML::LoadFile(params_dir + "/" + "velodyne64_height.yaml");
Eigen::Affine3d trans;
trans.linear() = Eigen::Matrix3d::Identity();
AINFO << trans.translation() << " "
<< lidar_height["vehicle"]["parameters"]["height"];
trans.translation() << 0.0, 0.0,
lidar_height["vehicle"]["parameters"]["height"].as<double>();
AddTransform("velodyne64", "ground", trans);
} catch (YAML::InvalidNode &in) {
AERROR << "load velodyne64 extrisic file error"
<< " YAML::InvalidNode exception";
return false;
} catch (YAML::TypedBadConversion<float> &bc) {
AERROR << "load velodyne64 extrisic file error, "
<< "YAML::TypedBadConversion exception";
return false;
} catch (YAML::Exception &e) {
AERROR << "load velodyne64 extrisic file "
<< " error, YAML exception:" << e.what();
return false;
}
// 2. init lidar and camera extrinsic
std::vector<std::string> extrinsic_filelist;
extrinsic_filelist.push_back(
params_dir + "/velodyne64_novatel_extrinsics.yaml");
for (const auto &camera_name : camera_names) {
extrinsic_filelist.push_back(
params_dir + "/" + camera_name + "_extrinsics.yaml");
}
for (const auto &yaml_file : extrinsic_filelist) {
try {
YAML::Node node = YAML::LoadFile(yaml_file);
if (node.IsNull()) {
AINFO << "Load " << yaml_file << " failed! please check!";
return false;
}
std::string child_frame_id = node["child_frame_id"].as<std::string>();
std::string frame_id = node["header"]["frame_id"].as<std::string>();
double q[4] = {node["transform"]["rotation"]["w"].as<double>(),
node["transform"]["rotation"]["x"].as<double>(),
node["transform"]["rotation"]["y"].as<double>(),
node["transform"]["rotation"]["z"].as<double>()};
double t[3] = {node["transform"]["translation"]["x"].as<double>(),
node["transform"]["translation"]["y"].as<double>(),
node["transform"]["translation"]["z"].as<double>()};
Eigen::Quaterniond qq(q[0], q[1], q[2], q[3]);
Eigen::Affine3d trans;
trans.linear() = qq.matrix();
trans.translation() << t[0], t[1], t[2];
bool added = AddTransform(child_frame_id, frame_id, trans);
if (!added) {
AINFO << "failed to add transform from "
<< child_frame_id << " to " << frame_id << std::endl;
}
} catch (YAML::InvalidNode &in) {
AERROR << "load camera extrisic file " << yaml_file
<< " with error, YAML::InvalidNode exception";
return false;
} catch (YAML::TypedBadConversion<double> &bc) {
AERROR << "load camera extrisic file " << yaml_file
<< " with error, YAML::TypedBadConversion exception";
return false;
} catch (YAML::Exception &e) {
AERROR << "load camera extrisic file " << yaml_file
<< " with error, YAML exception:" << e.what();
return false;
}
}
return true;
}
bool TransformServer::LoadFromFile(const std::string &tf_input,
float frequency) {
if (frequency <= 0) {
AERROR << "Error frequency value:" << frequency;
return false;
}
std::ifstream fin(tf_input);
Transform tf;
int64_t ts;
while (fin >> ts) {
tf.timestamp = static_cast<double>(ts) * 1e-9;
fin >> tf.tx;
fin >> tf.ty;
fin >> tf.tz;
fin >> tf.qx;
fin >> tf.qy;
fin >> tf.qz;
fin >> tf.qw;
tf_.push_back(tf);
}
fin.close();
error_limit_ = 1 / frequency / 2.0f;
AINFO << "Load tf successfully. count: " << tf_.size()
<< " error limit:" << error_limit_;
return true;
}
bool TransformServer::QueryPos(double timestamp, Eigen::Affine3d *pose) {
for (auto &&tf : tf_) {
if (Equal(timestamp, tf.timestamp, error_limit_)) {
Eigen::Quaterniond rotation(tf.qw, tf.qx, tf.qy, tf.qz);
pose->linear() = rotation.matrix();
pose->translation() << tf.tx, tf.ty, tf.tz;
AINFO << "Get Pose:\n" << pose->matrix();
return true;
}
}
return false;
}
bool TransformServer::AddTransform(const std::string &child_frame_id,
const std::string &frame_id,
const Eigen::Affine3d &transform) {
vertices_.insert(child_frame_id);
vertices_.insert(frame_id);
auto begin = edges_.lower_bound(child_frame_id);
auto end = edges_.upper_bound(child_frame_id);
for (auto iter = begin; iter != end; ++iter) {
if (iter->second.frame_id == frame_id) {
return false;
}
}
Edge e;
e.child_frame_id = child_frame_id;
e.frame_id = frame_id;
e.transform = transform;
Edge e_inv;
e_inv.child_frame_id = frame_id;
e_inv.frame_id = child_frame_id;
e_inv.transform = transform.inverse();
ADEBUG
<< "Add transform between " << frame_id << " and " << child_frame_id;
edges_.insert({child_frame_id, e});
edges_.insert({frame_id, e_inv});
return true;
}
bool TransformServer::QueryTransform(const std::string &child_frame_id,
const std::string &frame_id,
Eigen::Affine3d *transform) {
*transform = Eigen::Affine3d::Identity();
if (child_frame_id == frame_id) {
return true;
}
auto cf_iter = vertices_.find(child_frame_id);
auto f_iter = vertices_.find(frame_id);
// vertices do not exist
if (cf_iter == vertices_.end() || f_iter == vertices_.end()) {
return false;
}
std::map<std::string, bool> visited;
for (const auto &item : vertices_) {
visited[item] = false;
}
return FindTransform(child_frame_id, frame_id, transform, &visited);
}
bool TransformServer::FindTransform(const std::string &child_frame_id,
const std::string &frame_id,
Eigen::Affine3d *transform,
std::map<std::string, bool> *visited) {
Eigen::Affine3d loc_transform = Eigen::Affine3d::Identity();
auto begin = edges_.lower_bound(child_frame_id);
auto end = edges_.upper_bound(child_frame_id);
(*visited)[child_frame_id] = true;
for (auto iter = begin; iter != end; ++iter) {
auto &edge = iter->second;
if ((*visited)[edge.frame_id]) {
continue;
}
ADEBUG
<< "from " << edge.child_frame_id << " to " << edge.frame_id << std::endl;
loc_transform = edge.transform * loc_transform;
if (edge.frame_id == frame_id) {
*transform = loc_transform;
return true;
}
Eigen::Affine3d tr = Eigen::Affine3d::Identity();
bool bfound = FindTransform(edge.frame_id, frame_id, &tr, visited);
if (bfound) {
loc_transform = tr * loc_transform;
*transform = loc_transform;
return true;
}
loc_transform = edge.transform.inverse() * loc_transform;
}
return false;
}
void TransformServer::print() {
for (auto item : edges_) {
AINFO << "----------------" << std::endl;
AINFO << item.first << std::endl;
AINFO << "edge: " << std::endl;
AINFO << "from " << item.second.child_frame_id << " to "
<< item.second.frame_id << std::endl;
Eigen::Affine3d trans = item.second.transform;
Eigen::Quaterniond quat(trans.linear());
AINFO << "rot: " << quat.x() << " " << quat.y() << " " << quat.z() << " "
<< quat.w() << std::endl;
AINFO << "trans: "
<< trans.translation()[0] << " "
<< trans.translation()[1] << " "
<< trans.translation()[2] << std::endl;
}
}
} // namespace camera
} // namespace perception
} // namespace apollo
<|endoftext|>
|
<commit_before>/*****************************************************************************
// * This source file is part of ArkGameFrame *
// * For the latest info, see https://github.com/ArkGame *
// * *
// * Copyright(c) 2013 - 2017 ArkGame authors. *
// * *
// * Licensed under the Apache License, Version 2.0 (the "License"); *
// * you may not use this file except in compliance with the License. *
// * You may obtain a copy of the License at *
// * *
// * http://www.apache.org/licenses/LICENSE-2.0 *
// * *
// * Unless required by applicable law or agreed to in writing, software *
// * distributed under the License is distributed on an "AS IS" BASIS, *
// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.*
// * See the License for the specific language governing permissions and *
// * limitations under the License. *
// * *
// * *
// * @file AFPlatform.h *
// * @author Ark Game Tech *
// * @date 2015-12-15 *
// * @brief AFPlatform *
*****************************************************************************/
#pragma once
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <math.h>
#include <assert.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <stdexcept>
#include <string>
#include <cstring>
#include <vector>
#include <map>
#include <list>
#include <set>
#include <deque>
#include <limits>
#include <algorithm>
#include <utility>
#include <functional>
#include <cctype>
#include <iterator>
#include <unordered_map>
#include <stdint.h>
#include <functional>
#include <memory>
#include <signal.h>
#include <chrono>
#include <sstream>
#include <random>
#include <thread>
#if defined(__WIN32__) || defined(WIN32) || defined(_WIN32) || defined(__WIN64__) || defined(WIN64) || defined(_WIN64)
// only windows include
#include <io.h>
#include <time.h>
#ifndef WIN32_LEAN_AND_MEAN
#include <WinSock2.h>
#include <MSWSock.h>
#define WIN32_LEAN_AND_MEAN
#endif // WIN32_LEAN_AND_MEAN
#include <windows.h>
#define _SCL_SECURE_NO_WARNINGS
#define SIGHUP 1
#define SIGINT 2
#define SIGQUIT 3
#define SIGUSR1 10
#define SIGPIPE 13
#define SIGCHLD 17
#define SIGSYS 32
#else
// only other unix/linux include
#include <sys/socket.h>
#endif
#define ARK_LITTLE_ENDIAN
#define ARK_BIG_ENDIAN
#if !defined(ARK_ENDIAN)
# if defined(USE_BIG_ENDIAN)
# define ARK_ENDIAN ARK_BIG_ENDIAN
# else
# define ARK_ENDIAN ARK_LITTLE_ENDIAN
# endif
#endif // !defined(ARK_ENDIAN)
#define PLATFORM_WIN 0
#define PLATFORM_UNIX 1
#define PLATFORM_APPLE 2
#define UNIX_FLAVOUR_LINUX 1
#define UNIX_FLAVOUR_BSD 2
#define UNIX_FLAVOUR_OTHER 3
#define UNIX_FLAVOUR_OSX 4
#if defined(__WIN32__) || defined(WIN32) || defined(_WIN32) || defined(__WIN64__) || defined(WIN64) || defined(_WIN64)
# define ARK_PLATFORM PLATFORM_WIN
#elif defined(__APPLE_CC__)
# define ARK_PLATFORM PLATFORM_APPLE
#else
# define ARK_PLATFORM PLATFORM_UNIX
#endif
#define COMPILER_MICROSOFT 0
#define COMPILER_GNU 1
#define COMPILER_BORLAND 2
#define COMPILER_INTEL 3
#define COMPILER_CLANG 4
#define GOOGLE_STRIP_LOG 2
#ifdef _MSC_VER
# define ARK_COMPILER COMPILER_MICROSOFT
#elif defined(__INTEL_COMPILER)
# define ARK_COMPILER COMPILER_INTEL
#elif defined(__BORLANDC__)
# define ARK_COMPILER COMPILER_BORLAND
#elif defined(__GNUC__)
# define ARK_COMPILER COMPILER_GNU
#elif defined( __clang__ )
# define ARK_COMPILER COMPILER_CLANG
#else
# pragma error "FATAL ERROR: Unknown compiler."
#endif
#if ARK_PLATFORM == PLATFORM_UNIX || ARK_PLATFORM == PLATFORM_APPLE
# if defined(HAVE_DARWIN)
# define ARK_PLATFORM_NAME "MacOSX"
# define UNIX_FLAVOUR UNIX_FLAVOUR_OSX
# elif defined(USE_KQUEUE)
# define ARK_PLATFORM_NAME "FreeBSD"
# define UNIX_FLAVOUR UNIX_FLAVOUR_BSD
# elif defined(USE_KQUEUE_DFLY)
# define ARK_PLATFORM_NAME "DragonFlyBSD"
# define UNIX_FLAVOUR UNIX_FLAVOUR_BSD
# else
# define ARK_PLATFORM_NAME "Linux"
# define UNIX_FLAVOUR UNIX_FLAVOUR_LINUX
# endif
#elif ARK_PLATFORM == PLATFORM_WIN
# define ARK_PLATFORM_NAME "Windows"
#else
# pragma error "FATAL ERROR: Unknown platform."
#endif
#define ARK_RUN_MODE_DEBUG 0
#define ARK_RUN_MODE_RELEASE 1
#ifndef ARK_RUN_MODE
# if defined(DEBUG) || defined(_DEBUG)
# define ARK_RUN_MODE ARK_RUN_MODE_DEBUG
# define ARK_RUN_MODE_NAME "Debug"
# else
# define ARK_RUN_MODE ARK_RUN_MODE_RELEASE
# define ARK_RUN_MODE_NAME "Release"
# endif // DEBUG
#endif
#ifndef X64
# if defined(_WIN64) || defined(__x86_64__) || defined(__amd64) || defined(__LP64__)
# define X64
# endif
#endif
#ifdef X64
# define ARK_ARCH_NAME "X64"
#else
# define ARK_ARCH_NAME "X86"
#endif // X64
#define ARK_LITTLE_ENDIAN
#ifndef ARK_DYNAMIC_PLUGIN
#define ARK_DYNAMIC_PLUGIN
#endif
<commit_msg>remove netmodule log<commit_after>/*****************************************************************************
// * This source file is part of ArkGameFrame *
// * For the latest info, see https://github.com/ArkGame *
// * *
// * Copyright(c) 2013 - 2017 ArkGame authors. *
// * *
// * Licensed under the Apache License, Version 2.0 (the "License"); *
// * you may not use this file except in compliance with the License. *
// * You may obtain a copy of the License at *
// * *
// * http://www.apache.org/licenses/LICENSE-2.0 *
// * *
// * Unless required by applicable law or agreed to in writing, software *
// * distributed under the License is distributed on an "AS IS" BASIS, *
// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.*
// * See the License for the specific language governing permissions and *
// * limitations under the License. *
// * *
// * *
// * @file AFPlatform.h *
// * @author Ark Game Tech *
// * @date 2015-12-15 *
// * @brief AFPlatform *
*****************************************************************************/
#pragma once
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <math.h>
#include <assert.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <stdexcept>
#include <string>
#include <cstring>
#include <vector>
#include <map>
#include <list>
#include <set>
#include <deque>
#include <limits>
#include <algorithm>
#include <utility>
#include <functional>
#include <cctype>
#include <iterator>
#include <unordered_map>
#include <stdint.h>
#include <functional>
#include <memory>
#include <signal.h>
#include <chrono>
#include <sstream>
#include <random>
#include <thread>
#if defined(__WIN32__) || defined(WIN32) || defined(_WIN32) || defined(__WIN64__) || defined(WIN64) || defined(_WIN64)
// only windows include
#include <io.h>
#include <time.h>
#ifndef WIN32_LEAN_AND_MEAN
#include <WinSock2.h>
#include <MSWSock.h>
#define WIN32_LEAN_AND_MEAN
#endif // WIN32_LEAN_AND_MEAN
#include <windows.h>
#define _SCL_SECURE_NO_WARNINGS
#define SIGHUP 1
#define SIGINT 2
#define SIGQUIT 3
#define SIGUSR1 10
#define SIGPIPE 13
#define SIGCHLD 17
#define SIGSYS 32
#else
// only other unix/linux include
#include <sys/socket.h>
#endif
#define ARK_LITTLE_ENDIAN
#define ARK_BIG_ENDIAN
#if !defined(ARK_ENDIAN)
# if defined(USE_BIG_ENDIAN)
# define ARK_ENDIAN ARK_BIG_ENDIAN
# else
# define ARK_ENDIAN ARK_LITTLE_ENDIAN
# endif
#endif // !defined(ARK_ENDIAN)
#define PLATFORM_WIN 0
#define PLATFORM_UNIX 1
#define PLATFORM_APPLE 2
#define UNIX_FLAVOUR_LINUX 1
#define UNIX_FLAVOUR_BSD 2
#define UNIX_FLAVOUR_OTHER 3
#define UNIX_FLAVOUR_OSX 4
#if defined(__WIN32__) || defined(WIN32) || defined(_WIN32) || defined(__WIN64__) || defined(WIN64) || defined(_WIN64)
# define ARK_PLATFORM PLATFORM_WIN
#elif defined(__APPLE_CC__)
# define ARK_PLATFORM PLATFORM_APPLE
#else
# define ARK_PLATFORM PLATFORM_UNIX
#endif
#define COMPILER_MICROSOFT 0
#define COMPILER_GNU 1
#define COMPILER_BORLAND 2
#define COMPILER_INTEL 3
#define COMPILER_CLANG 4
#ifdef _MSC_VER
# define ARK_COMPILER COMPILER_MICROSOFT
#elif defined(__INTEL_COMPILER)
# define ARK_COMPILER COMPILER_INTEL
#elif defined(__BORLANDC__)
# define ARK_COMPILER COMPILER_BORLAND
#elif defined(__GNUC__)
# define ARK_COMPILER COMPILER_GNU
#elif defined( __clang__ )
# define ARK_COMPILER COMPILER_CLANG
#else
# pragma error "FATAL ERROR: Unknown compiler."
#endif
#if ARK_PLATFORM == PLATFORM_UNIX || ARK_PLATFORM == PLATFORM_APPLE
# if defined(HAVE_DARWIN)
# define ARK_PLATFORM_NAME "MacOSX"
# define UNIX_FLAVOUR UNIX_FLAVOUR_OSX
# elif defined(USE_KQUEUE)
# define ARK_PLATFORM_NAME "FreeBSD"
# define UNIX_FLAVOUR UNIX_FLAVOUR_BSD
# elif defined(USE_KQUEUE_DFLY)
# define ARK_PLATFORM_NAME "DragonFlyBSD"
# define UNIX_FLAVOUR UNIX_FLAVOUR_BSD
# else
# define ARK_PLATFORM_NAME "Linux"
# define UNIX_FLAVOUR UNIX_FLAVOUR_LINUX
# endif
#elif ARK_PLATFORM == PLATFORM_WIN
# define ARK_PLATFORM_NAME "Windows"
#else
# pragma error "FATAL ERROR: Unknown platform."
#endif
#define ARK_RUN_MODE_DEBUG 0
#define ARK_RUN_MODE_RELEASE 1
#ifndef ARK_RUN_MODE
# if defined(DEBUG) || defined(_DEBUG)
# define ARK_RUN_MODE ARK_RUN_MODE_DEBUG
# define ARK_RUN_MODE_NAME "Debug"
# else
# define ARK_RUN_MODE ARK_RUN_MODE_RELEASE
# define ARK_RUN_MODE_NAME "Release"
# endif // DEBUG
#endif
#ifndef X64
# if defined(_WIN64) || defined(__x86_64__) || defined(__amd64) || defined(__LP64__)
# define X64
# endif
#endif
#ifdef X64
# define ARK_ARCH_NAME "X64"
#else
# define ARK_ARCH_NAME "X86"
#endif // X64
#define ARK_LITTLE_ENDIAN
#ifndef ARK_DYNAMIC_PLUGIN
#define ARK_DYNAMIC_PLUGIN
#endif
<|endoftext|>
|
<commit_before>/**
* \file RMF/Category.h
* \brief Handle read/write of Model data from/to files.
*
* Copyright 2007-2013 IMP Inventors. All rights reserved.
*
*/
#include "HDF5SharedData.h"
#include <RMF/NodeHandle.h>
#include <RMF/Validator.h>
#include <boost/unordered_set.hpp>
#include <RMF/HDF5/Group.h>
#include <RMF/log.h>
#include <algorithm>
RMF_ENABLE_WARNINGS
namespace RMF {
namespace hdf5_backend {
#define RMF_CLOSE(lcname, Ucname, PassValue, ReturnValue, PassValues, \
ReturnValues) \
lcname##_data_sets_ = DataDataSetCache2D<Ucname##Traits>(); \
per_frame_##lcname##_data_sets_ = DataDataSetCache3D<Ucname##Traits>()
void HDF5SharedData::close_things() {
node_names_.reset();
free_ids_.clear();
node_data_.reset();
index_cache_ = IndexCache();
key_name_data_sets_ = KeyNameDataSetCache();
category_names_.reset();
frame_names_.reset();
max_cache_.clear();
RMF_FOREACH_BACKWARDS_TYPE(RMF_CLOSE);
flush();
file_ = HDF5::Group();
H5garbage_collect();
}
void HDF5SharedData::open_things(bool create, bool read_only) {
read_only_ = read_only;
if (create) {
file_ = HDF5::create_file(get_file_path());
file_.set_attribute<HDF5::CharTraits>("version", std::string("rmf 1"));
{
HDF5::DataSetCreationPropertiesD<HDF5::StringTraits, 1> props;
props.set_compression(HDF5::GZIP_COMPRESSION);
(file_.add_child_data_set<HDF5::StringTraits,
1>)(get_node_name_data_set_name(), props);
}
{
HDF5::DataSetCreationPropertiesD<HDF5::IndexTraits, 2> props;
props.set_compression(HDF5::GZIP_COMPRESSION);
props.set_chunk_size(RMF::HDF5::DataSetIndexD<2>(128, 4));
(file_.add_child_data_set<HDF5::IndexTraits,
2>)(get_node_data_data_set_name(), props);
}
} else {
if (read_only) {
// walk around type checking
file_ = HDF5::open_file_read_only_returning_nonconst(get_file_path());
} else {
file_ = HDF5::open_file(get_file_path());
}
std::string version;
version = file_.get_attribute<HDF5::CharTraits>("version");
RMF_USAGE_CHECK(version == "rmf 1",
internal::get_error_message(
"Unsupported rmf version ", "string found: \"", version,
"\" expected \"", "rmf 1", "\""));
}
node_names_.set(file_, get_node_name_data_set_name());
node_data_.set(file_, get_node_data_data_set_name());
initialize_categories();
initialize_free_nodes();
initialize_keys(0);
std::string frn = get_frame_name_data_set_name();
frame_names_.set(file_, frn);
}
#define RMF_LIST_KEYS(lcname, Ucname, PassValue, ReturnValue, PassValues, \
ReturnValues) \
initialize_keys(cat, #lcname, Ucname##Traits());
void HDF5SharedData::initialize_keys(int) {
Categories cats = get_categories();
RMF_FOREACH(Category cat, cats) {
RMF_FOREACH_BACKWARDS_TYPE(RMF_LIST_KEYS);
}
}
void HDF5SharedData::initialize_free_nodes() {
HDF5::DataSetIndexD<2> dim = node_data_.get_size();
for (unsigned int i = 0; i < dim[0]; ++i) {
if (IndexTraits::get_is_null_value(
node_data_.get_value(HDF5::DataSetIndexD<2>(i, 0)))) {
free_ids_.push_back(i);
}
}
}
void HDF5SharedData::initialize_categories() {
std::string nm = get_category_name_data_set_name();
category_names_.set(file_, nm);
HDF5::DataSetIndex1D sz = category_names_.get_size();
for (unsigned int i = 0; i < sz[0]; ++i) {
std::string name = category_names_.get_value(HDF5::DataSetIndex1D(i));
Category cat(i);
name_category_map_[name] = cat;
category_data_map_[cat].name = name;
category_data_map_[cat].index = i;
}
}
HDF5SharedData::HDF5SharedData(std::string g, bool create, bool read_only)
: BackwardsIOBase(g), frames_hint_(0) {
open_things(create, read_only);
link_category_ = get_category("link");
link_key_ = get_key(link_category_, "linked", NodeIDTraits());
if (create) {
add_node("root", ROOT);
} else {
RMF_USAGE_CHECK(get_name(NodeID(0)) == "root", "Root node is not so named");
}
}
HDF5SharedData::~HDF5SharedData() { close_things(); }
void HDF5SharedData::flush() {
RMF_HDF5_CALL(H5Fflush(file_.get_handle(), H5F_SCOPE_GLOBAL));
// SharedData::validate();
node_names_.flush();
frame_names_.flush();
category_names_.flush();
node_data_.flush();
}
void HDF5SharedData::check_node(NodeID node) const {
RMF_USAGE_CHECK(
node_names_.get_size()[0] > node.get_index(),
internal::get_error_message("Invalid node specified: ", node));
}
NodeID HDF5SharedData::add_node(std::string name, NodeType type) {
NodeID ret;
if (free_ids_.empty()) {
HDF5::DataSetIndexD<1> nsz = node_names_.get_size();
ret = NodeID(nsz[0]);
++nsz[0];
node_names_.set_size(nsz);
HDF5::DataSetIndexD<2> dsz = node_data_.get_size();
dsz[0] = ret.get_index() + 1;
dsz[1] = std::max<hsize_t>(3, dsz[1]);
node_data_.set_size(dsz);
} else {
ret = NodeID(free_ids_.back());
free_ids_.pop_back();
}
node_names_.set_value(HDF5::DataSetIndexD<1>(ret.get_index()), name);
node_data_.set_value(HDF5::DataSetIndexD<2>(ret.get_index(), TYPE), type);
node_data_.set_value(HDF5::DataSetIndexD<2>(ret.get_index(), CHILD),
IndexTraits::get_null_value());
node_data_.set_value(HDF5::DataSetIndexD<2>(ret.get_index(), SIBLING),
IndexTraits::get_null_value());
return ret;
}
NodeID HDF5SharedData::get_first_child(NodeID node) const {
check_node(node);
int child =
node_data_.get_value(HDF5::DataSetIndexD<2>(node.get_index(), CHILD));
if (child == -1)
return NodeID();
else
return NodeID(child);
}
NodeID HDF5SharedData::get_sibling(NodeID node) const {
check_node(node);
int sib =
node_data_.get_value(HDF5::DataSetIndexD<2>(node.get_index(), SIBLING));
if (sib == -1) {
return NodeID();
} else {
return NodeID(sib);
}
}
void HDF5SharedData::set_first_child(NodeID node, NodeID c) {
check_node(node);
return node_data_.set_value(HDF5::DataSetIndexD<2>(node.get_index(), CHILD),
c.get_index());
}
void HDF5SharedData::set_sibling(NodeID node, NodeID c) {
check_node(node);
if (c == NodeID()) {
node_data_.set_value(HDF5::DataSetIndexD<2>(node.get_index(), SIBLING), -1);
} else {
node_data_.set_value(HDF5::DataSetIndexD<2>(node.get_index(), SIBLING),
c.get_index());
}
}
std::string HDF5SharedData::get_name(NodeID node) const {
if (static_cast<unsigned int>(node.get_index()) < get_number_of_nodes()) {
check_node(node);
return node_names_.get_value(HDF5::DataSetIndexD<1>(node.get_index()));
} else {
return "bond";
}
}
NodeType HDF5SharedData::get_type(NodeID index) const {
if (static_cast<unsigned int>(index.get_index()) < get_number_of_nodes()) {
check_node(index);
return NodeType(
node_data_.get_value(HDF5::DataSetIndexD<2>(index.get_index(), TYPE)));
} else {
return BOND;
}
}
NodeID HDF5SharedData::add_child(NodeID node, std::string name, NodeType t) {
NodeID old_child = get_first_child(node);
NodeID nn = add_node(name, t);
set_first_child(node, nn);
set_sibling(nn, old_child);
return nn;
}
void HDF5SharedData::add_child(NodeID node, NodeID child_node) {
RMF_INTERNAL_CHECK(NodeID() != child_node, "Bad child being added");
NodeID link = add_child(node, "link", LINK);
get_category_index_create(link_category_);
set_static_value(link, link_key_, child_node);
RMF_INTERNAL_CHECK(get_linked(link) == child_node, "Return does not match");
}
NodeID HDF5SharedData::get_linked(NodeID node) const {
NodeID ret = get_static_value(node, link_key_);
RMF_INTERNAL_CHECK(ret != NodeID(), "Bad link value found");
return ret;
}
NodeIDs HDF5SharedData::get_children(NodeID node) const {
NodeID cur = get_first_child(node);
NodeIDs ret;
while (!NodeIDTraits::get_is_null_value(cur)) {
if (get_type(cur) != LINK) {
ret.push_back(cur);
cur = get_sibling(cur);
} else {
ret.push_back(get_linked(cur));
cur = get_sibling(cur);
}
}
std::reverse(ret.begin(), ret.end());
return ret;
}
unsigned int HDF5SharedData::add_category_impl(std::string name) {
// fill in later
int sz = category_names_.get_size()[0];
category_names_.set_size(HDF5::DataSetIndex1D(sz + 1));
category_names_.set_value(HDF5::DataSetIndex1D(sz), name);
return sz;
}
Categories HDF5SharedData::get_categories() const {
Categories ret;
for (CategoryDataMap::const_iterator it = category_data_map_.begin();
it != category_data_map_.end(); ++it) {
if (it->second.name == "link") continue;
ret.push_back(it->first);
}
return ret;
}
Category HDF5SharedData::get_category(std::string name) {
NameCategoryMap::const_iterator it = name_category_map_.find(name);
if (it == name_category_map_.end()) {
Category cat(name_category_map_.size());
name_category_map_[name] = cat;
category_data_map_[cat].index = -1;
category_data_map_[cat].name = name;
return cat;
} else {
return it->second;
}
}
#define RMF_SEARCH_KEYS(lcname, Ucname, PassValue, ReturnValue, PassValues, \
ReturnValues) \
{ \
int category_index = get_category_index(cats[i]); \
if (category_index == -1) continue; \
ret = std::max<int>(ret, \
get_number_of_frames<Ucname##Traits>(category_index)); \
}
unsigned int HDF5SharedData::get_number_of_frames() const {
Categories cats = get_categories();
int ret = 0;
for (unsigned int i = 0; i < cats.size(); ++i) {
RMF_FOREACH_BACKWARDS_TYPE(RMF_SEARCH_KEYS);
}
return std::max<int>(frame_names_.get_size()[0], ret);
}
std::string HDF5SharedData::get_description() const {
if (!get_group().get_has_attribute("description")) {
return std::string();
} else
return get_group().get_char_attribute("description");
}
void HDF5SharedData::set_description(std::string str) {
RMF_USAGE_CHECK(str.empty() || str[str.size() - 1] == '\n',
"Description should end in a newline.");
get_group().set_char_attribute("description", str);
}
std::string HDF5SharedData::get_producer() const {
if (!get_group().get_has_attribute("producer")) {
return std::string();
} else
return get_group().get_char_attribute("producer");
}
void HDF5SharedData::set_producer(std::string str) {
RMF_USAGE_CHECK(str.empty() || str[str.size() - 1] == '\n',
"Producer should end in a newline.");
get_group().set_char_attribute("producer", str);
}
void HDF5SharedData::set_name(FrameID i, std::string str) {
RMF_USAGE_CHECK(i != ALL_FRAMES,
"Cannot set the name frame name for static data");
if (frame_names_.get_size()[0] <= i.get_index()) {
frame_names_.set_size(HDF5::DataSetIndexD<1>(i.get_index() + 1));
}
frame_names_.set_value(HDF5::DataSetIndexD<1>(i.get_index()), str);
}
std::string HDF5SharedData::get_loaded_frame_name() const {
FrameID i = get_loaded_frame();
if (frame_names_.get_size()[0] > i.get_index()) {
return frame_names_.get_value(HDF5::DataSetIndexD<1>(i.get_index()));
} else {
return std::string();
}
}
void HDF5SharedData::reload() {
close_things();
open_things(false, read_only_);
}
#define RMF_HDF5_SET_FRAME(lcname, Ucname, PassValue, ReturnValue, PassValues, \
ReturnValues) \
per_frame_##lcname##_data_sets_.set_current_frame(frame);
void HDF5SharedData::set_loaded_frame(FrameID frame) {
RMF_TRACE(get_logger(), "Loading frame " << frame);
BackwardsIOBase::set_loaded_frame(frame);
RMF_FOREACH_BACKWARDS_TYPE(RMF_HDF5_SET_FRAME);
}
} // namespace hdf5_backend
} /* namespace RMF */
RMF_DISABLE_WARNINGS
<commit_msg>make sure to load link keys<commit_after>/**
* \file RMF/Category.h
* \brief Handle read/write of Model data from/to files.
*
* Copyright 2007-2013 IMP Inventors. All rights reserved.
*
*/
#include "HDF5SharedData.h"
#include <RMF/NodeHandle.h>
#include <RMF/Validator.h>
#include <boost/unordered_set.hpp>
#include <RMF/HDF5/Group.h>
#include <RMF/log.h>
#include <algorithm>
RMF_ENABLE_WARNINGS
namespace RMF {
namespace hdf5_backend {
#define RMF_CLOSE(lcname, Ucname, PassValue, ReturnValue, PassValues, \
ReturnValues) \
lcname##_data_sets_ = DataDataSetCache2D<Ucname##Traits>(); \
per_frame_##lcname##_data_sets_ = DataDataSetCache3D<Ucname##Traits>()
void HDF5SharedData::close_things() {
node_names_.reset();
free_ids_.clear();
node_data_.reset();
index_cache_ = IndexCache();
key_name_data_sets_ = KeyNameDataSetCache();
category_names_.reset();
frame_names_.reset();
max_cache_.clear();
RMF_FOREACH_BACKWARDS_TYPE(RMF_CLOSE);
flush();
file_ = HDF5::Group();
H5garbage_collect();
}
void HDF5SharedData::open_things(bool create, bool read_only) {
read_only_ = read_only;
if (create) {
file_ = HDF5::create_file(get_file_path());
file_.set_attribute<HDF5::CharTraits>("version", std::string("rmf 1"));
{
HDF5::DataSetCreationPropertiesD<HDF5::StringTraits, 1> props;
props.set_compression(HDF5::GZIP_COMPRESSION);
(file_.add_child_data_set<HDF5::StringTraits,
1>)(get_node_name_data_set_name(), props);
}
{
HDF5::DataSetCreationPropertiesD<HDF5::IndexTraits, 2> props;
props.set_compression(HDF5::GZIP_COMPRESSION);
props.set_chunk_size(RMF::HDF5::DataSetIndexD<2>(128, 4));
(file_.add_child_data_set<HDF5::IndexTraits,
2>)(get_node_data_data_set_name(), props);
}
} else {
if (read_only) {
// walk around type checking
file_ = HDF5::open_file_read_only_returning_nonconst(get_file_path());
} else {
file_ = HDF5::open_file(get_file_path());
}
std::string version;
version = file_.get_attribute<HDF5::CharTraits>("version");
RMF_USAGE_CHECK(version == "rmf 1",
internal::get_error_message(
"Unsupported rmf version ", "string found: \"", version,
"\" expected \"", "rmf 1", "\""));
}
node_names_.set(file_, get_node_name_data_set_name());
node_data_.set(file_, get_node_data_data_set_name());
initialize_categories();
initialize_free_nodes();
initialize_keys(0);
std::string frn = get_frame_name_data_set_name();
frame_names_.set(file_, frn);
}
#define RMF_LIST_KEYS(lcname, Ucname, PassValue, ReturnValue, PassValues, \
ReturnValues) \
initialize_keys(cat, #lcname, Ucname##Traits());
void HDF5SharedData::initialize_keys(int) {
Categories cats = get_categories();
RMF_FOREACH(Category cat, cats) {
RMF_FOREACH_BACKWARDS_TYPE(RMF_LIST_KEYS);
}
initialize_keys(get_category("link"), "nodeid", NodeIDTraits());
}
void HDF5SharedData::initialize_free_nodes() {
HDF5::DataSetIndexD<2> dim = node_data_.get_size();
for (unsigned int i = 0; i < dim[0]; ++i) {
if (IndexTraits::get_is_null_value(
node_data_.get_value(HDF5::DataSetIndexD<2>(i, 0)))) {
free_ids_.push_back(i);
}
}
}
void HDF5SharedData::initialize_categories() {
std::string nm = get_category_name_data_set_name();
category_names_.set(file_, nm);
HDF5::DataSetIndex1D sz = category_names_.get_size();
for (unsigned int i = 0; i < sz[0]; ++i) {
std::string name = category_names_.get_value(HDF5::DataSetIndex1D(i));
Category cat(i);
name_category_map_[name] = cat;
category_data_map_[cat].name = name;
category_data_map_[cat].index = i;
}
}
HDF5SharedData::HDF5SharedData(std::string g, bool create, bool read_only)
: BackwardsIOBase(g), frames_hint_(0) {
open_things(create, read_only);
link_category_ = get_category("link");
link_key_ = get_key(link_category_, "linked", NodeIDTraits());
if (create) {
add_node("root", ROOT);
} else {
RMF_INFO(get_logger(), "Found " << node_names_.get_size() << " nodes");
RMF_USAGE_CHECK(
get_name(NodeID(0)) == "root",
std::string("Root node is not so named ") + get_name(NodeID(0)));
}
}
HDF5SharedData::~HDF5SharedData() { close_things(); }
void HDF5SharedData::flush() {
RMF_HDF5_CALL(H5Fflush(file_.get_handle(), H5F_SCOPE_GLOBAL));
// SharedData::validate();
node_names_.flush();
frame_names_.flush();
category_names_.flush();
node_data_.flush();
}
void HDF5SharedData::check_node(NodeID node) const {
RMF_USAGE_CHECK(
node_names_.get_size()[0] > node.get_index(),
internal::get_error_message("Invalid node specified: ", node));
}
NodeID HDF5SharedData::add_node(std::string name, NodeType type) {
NodeID ret;
if (free_ids_.empty()) {
HDF5::DataSetIndexD<1> nsz = node_names_.get_size();
ret = NodeID(nsz[0]);
++nsz[0];
node_names_.set_size(nsz);
HDF5::DataSetIndexD<2> dsz = node_data_.get_size();
dsz[0] = ret.get_index() + 1;
dsz[1] = std::max<hsize_t>(3, dsz[1]);
node_data_.set_size(dsz);
} else {
ret = NodeID(free_ids_.back());
free_ids_.pop_back();
}
node_names_.set_value(HDF5::DataSetIndexD<1>(ret.get_index()), name);
node_data_.set_value(HDF5::DataSetIndexD<2>(ret.get_index(), TYPE), type);
node_data_.set_value(HDF5::DataSetIndexD<2>(ret.get_index(), CHILD),
IndexTraits::get_null_value());
node_data_.set_value(HDF5::DataSetIndexD<2>(ret.get_index(), SIBLING),
IndexTraits::get_null_value());
return ret;
}
NodeID HDF5SharedData::get_first_child(NodeID node) const {
check_node(node);
int child =
node_data_.get_value(HDF5::DataSetIndexD<2>(node.get_index(), CHILD));
if (child == -1)
return NodeID();
else
return NodeID(child);
}
NodeID HDF5SharedData::get_sibling(NodeID node) const {
check_node(node);
int sib =
node_data_.get_value(HDF5::DataSetIndexD<2>(node.get_index(), SIBLING));
if (sib == -1) {
return NodeID();
} else {
return NodeID(sib);
}
}
void HDF5SharedData::set_first_child(NodeID node, NodeID c) {
check_node(node);
return node_data_.set_value(HDF5::DataSetIndexD<2>(node.get_index(), CHILD),
c.get_index());
}
void HDF5SharedData::set_sibling(NodeID node, NodeID c) {
check_node(node);
if (c == NodeID()) {
node_data_.set_value(HDF5::DataSetIndexD<2>(node.get_index(), SIBLING), -1);
} else {
node_data_.set_value(HDF5::DataSetIndexD<2>(node.get_index(), SIBLING),
c.get_index());
}
}
std::string HDF5SharedData::get_name(NodeID node) const {
if (static_cast<unsigned int>(node.get_index()) < get_number_of_nodes()) {
check_node(node);
return node_names_.get_value(HDF5::DataSetIndexD<1>(node.get_index()));
} else {
return "bond";
}
}
NodeType HDF5SharedData::get_type(NodeID index) const {
if (static_cast<unsigned int>(index.get_index()) < get_number_of_nodes()) {
check_node(index);
return NodeType(
node_data_.get_value(HDF5::DataSetIndexD<2>(index.get_index(), TYPE)));
} else {
return BOND;
}
}
NodeID HDF5SharedData::add_child(NodeID node, std::string name, NodeType t) {
NodeID old_child = get_first_child(node);
NodeID nn = add_node(name, t);
set_first_child(node, nn);
set_sibling(nn, old_child);
return nn;
}
void HDF5SharedData::add_child(NodeID node, NodeID child_node) {
RMF_INTERNAL_CHECK(NodeID() != child_node, "Bad child being added");
NodeID link = add_child(node, "link", LINK);
get_category_index_create(link_category_);
set_static_value(link, link_key_, child_node);
RMF_INTERNAL_CHECK(get_linked(link) == child_node, "Return does not match");
}
NodeID HDF5SharedData::get_linked(NodeID node) const {
NodeID ret = get_static_value(node, link_key_);
RMF_INTERNAL_CHECK(ret != NodeID(), "Bad link value found");
return ret;
}
NodeIDs HDF5SharedData::get_children(NodeID node) const {
NodeID cur = get_first_child(node);
NodeIDs ret;
while (!NodeIDTraits::get_is_null_value(cur)) {
if (get_type(cur) != LINK) {
ret.push_back(cur);
cur = get_sibling(cur);
} else {
ret.push_back(get_linked(cur));
cur = get_sibling(cur);
}
}
std::reverse(ret.begin(), ret.end());
return ret;
}
unsigned int HDF5SharedData::add_category_impl(std::string name) {
// fill in later
int sz = category_names_.get_size()[0];
category_names_.set_size(HDF5::DataSetIndex1D(sz + 1));
category_names_.set_value(HDF5::DataSetIndex1D(sz), name);
return sz;
}
Categories HDF5SharedData::get_categories() const {
Categories ret;
for (CategoryDataMap::const_iterator it = category_data_map_.begin();
it != category_data_map_.end(); ++it) {
if (it->second.name == "link") continue;
ret.push_back(it->first);
}
return ret;
}
Category HDF5SharedData::get_category(std::string name) {
NameCategoryMap::const_iterator it = name_category_map_.find(name);
if (it == name_category_map_.end()) {
Category cat(name_category_map_.size());
name_category_map_[name] = cat;
category_data_map_[cat].index = -1;
category_data_map_[cat].name = name;
return cat;
} else {
return it->second;
}
}
#define RMF_SEARCH_KEYS(lcname, Ucname, PassValue, ReturnValue, PassValues, \
ReturnValues) \
{ \
int category_index = get_category_index(cats[i]); \
if (category_index == -1) continue; \
ret = std::max<int>(ret, \
get_number_of_frames<Ucname##Traits>(category_index)); \
}
unsigned int HDF5SharedData::get_number_of_frames() const {
Categories cats = get_categories();
int ret = 0;
for (unsigned int i = 0; i < cats.size(); ++i) {
RMF_FOREACH_BACKWARDS_TYPE(RMF_SEARCH_KEYS);
}
return std::max<int>(frame_names_.get_size()[0], ret);
}
std::string HDF5SharedData::get_description() const {
if (!get_group().get_has_attribute("description")) {
return std::string();
} else
return get_group().get_char_attribute("description");
}
void HDF5SharedData::set_description(std::string str) {
RMF_USAGE_CHECK(str.empty() || str[str.size() - 1] == '\n',
"Description should end in a newline.");
get_group().set_char_attribute("description", str);
}
std::string HDF5SharedData::get_producer() const {
if (!get_group().get_has_attribute("producer")) {
return std::string();
} else
return get_group().get_char_attribute("producer");
}
void HDF5SharedData::set_producer(std::string str) {
RMF_USAGE_CHECK(str.empty() || str[str.size() - 1] == '\n',
"Producer should end in a newline.");
get_group().set_char_attribute("producer", str);
}
void HDF5SharedData::set_name(FrameID i, std::string str) {
RMF_USAGE_CHECK(i != ALL_FRAMES,
"Cannot set the name frame name for static data");
if (frame_names_.get_size()[0] <= i.get_index()) {
frame_names_.set_size(HDF5::DataSetIndexD<1>(i.get_index() + 1));
}
frame_names_.set_value(HDF5::DataSetIndexD<1>(i.get_index()), str);
}
std::string HDF5SharedData::get_loaded_frame_name() const {
FrameID i = get_loaded_frame();
if (frame_names_.get_size()[0] > i.get_index()) {
return frame_names_.get_value(HDF5::DataSetIndexD<1>(i.get_index()));
} else {
return std::string();
}
}
void HDF5SharedData::reload() {
close_things();
open_things(false, read_only_);
}
#define RMF_HDF5_SET_FRAME(lcname, Ucname, PassValue, ReturnValue, PassValues, \
ReturnValues) \
per_frame_##lcname##_data_sets_.set_current_frame(frame);
void HDF5SharedData::set_loaded_frame(FrameID frame) {
RMF_TRACE(get_logger(), "Loading frame " << frame);
BackwardsIOBase::set_loaded_frame(frame);
RMF_FOREACH_BACKWARDS_TYPE(RMF_HDF5_SET_FRAME);
}
} // namespace hdf5_backend
} /* namespace RMF */
RMF_DISABLE_WARNINGS
<|endoftext|>
|
<commit_before>#include <bits/stdc++.h>
#define NUM_NODES 8
using namespace std;
vector < int > g[NUM_NODES];
int d[NUM_NODES];
void show(){
for (int i = 0; i < NUM_NODES; i++){
cout << i << " " << d[i] << endl;
}
}
/*
* s -> origin
* n -> number of nodes
*/
void bfs(int o, int n){
for (int i = 0; i<=n; i++) d[i] = -1;
queue < int > q;
q.push(o);
d[o] = 0;
while(q.size() > 0){
int cur = q.front(); q.pop();
for ( int i = 0; i < g[cur].size(); i++){
int next = g[cur][i];
if(d[next] == -1){
d[next] = d[cur] +1;
q.push(next);
}
}
}
}
int main(){
g[0].push_back(1);
g[0].push_back(2);
g[0].push_back(3);
g[1].push_back(4);
g[1].push_back(5);
g[2].push_back(6);
g[3].push_back(7);
bfs(0, NUM_NODES);
show();
return 0 ;
}
<commit_msg>Improve implementation bfs.<commit_after>#include <bits/stdc++.h>
#define pb push_back
using namespace std;
typedef vector < int > vi;
vi dis;
vector < vi > graph;
void show_distances(){
for( int i = 0; i< dis.size(); i++){
cout << i << " : " << dis[i] << "\n";
}
}
void bfs(int origin){
queue < int > q;
dis[origin] = 0;
q.push(origin);
while( q.size() > 0){
int front = q.front(); q.pop();
for(int son: graph[front]){
if(dis[son] == -1){
dis[son] = dis[front] +1;
q.push(son);
}
}
}
}
int main(){
int num_nodes = 5;
dis.assign(num_nodes, -1);
graph.resize(num_nodes);
graph[0].pb(1);
graph[0].pb(2);
graph[0].pb(3);
graph[1].pb(4);
bfs(0);
show_distances();
return 0;
}
<|endoftext|>
|
<commit_before>/* bzflag
* Copyright (c) 1993 - 2008 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named LICENSE that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#include "RCRequests.h"
#include "RCReplies.h"
#include "RCRobotPlayer.h"
#include "MessageUtilities.h"
#include "BZDBCache.h"
#include "Roster.h"
#include "World.h"
#include "playing.h"
#include "version.h"
bool ExecuteReq::process(RCRobotPlayer *rrp)
{
if (!rrp->isSteadyState())
return false;
rrp->lastTickAt = TimeKeeper::getCurrent().getSeconds();
if (rrp->pendingUpdates[RCRobotPlayer::speedUpdate])
rrp->speed = rrp->nextSpeed;
if (rrp->pendingUpdates[RCRobotPlayer::turnRateUpdate])
rrp->turnRate = rrp->nextTurnRate;
if (rrp->pendingUpdates[RCRobotPlayer::distanceUpdate])
{
if (rrp->nextDistance < 0.0f)
rrp->distanceForward = false;
else
rrp->distanceForward = true;
rrp->distanceRemaining = (rrp->distanceForward ? 1 : -1) * rrp->nextDistance;
}
if (rrp->pendingUpdates[RCRobotPlayer::turnUpdate])
{
if (rrp->nextTurn < 0.0f)
rrp->turnLeft = false;
else
rrp->turnLeft = true;
rrp->turnRemaining = (rrp->turnLeft ? 1 : -1) * rrp->nextTurn * M_PI/180.0f; /* We have to convert to radians! */
}
for (int i = 0; i < RCRobotPlayer::updateCount; ++i)
rrp->pendingUpdates[i] = false;
if (rrp->shoot)
{
rrp->shoot = false;
rrp->fireShot();
}
return true;
}
bool SetSpeedReq::process(RCRobotPlayer *rrp)
{
rrp->nextSpeed = speed;
rrp->pendingUpdates[RCRobotPlayer::speedUpdate] = true;
return true;
}
bool SetTurnRateReq::process(RCRobotPlayer *rrp)
{
rrp->nextTurnRate = rate;
rrp->pendingUpdates[RCRobotPlayer::turnRateUpdate] = true;
return true;
}
bool SetAheadReq::process(RCRobotPlayer *rrp)
{
rrp->pendingUpdates[RCRobotPlayer::distanceUpdate] = true;
rrp->nextDistance = distance;
return true;
}
bool SetTurnLeftReq::process(RCRobotPlayer *rrp)
{
rrp->pendingUpdates[RCRobotPlayer::turnUpdate] = true;
rrp->nextTurn = turn;
return true;
}
bool SetFireReq::process(RCRobotPlayer *rrp)
{
rrp->shoot = true;
return true;
}
bool SetResumeReq::process(RCRobotPlayer *rrp)
{
if (!rrp->isSteadyState())
return false;
if (rrp->hasStopped)
{
rrp->hasStopped = false;
rrp->distanceRemaining = rrp->stoppedDistance;
rrp->turnRemaining = rrp->stoppedTurn;
rrp->distanceForward = rrp->stoppedForward;
rrp->turnLeft = rrp->stoppedLeft;
}
return true;
}
bool GetGunHeatReq::process(RCRobotPlayer *rrp)
{
if (!rrp->isSteadyState())
return false;
link->send(GunHeatReply(rrp->getReloadTime()));
return true;
}
bool GetDistanceRemainingReq::process(RCRobotPlayer *rrp)
{
if (!rrp->isSteadyState())
return false;
link->send(DistanceRemainingReply(rrp->distanceRemaining));
return true;
}
bool GetTurnRemainingReq::process(RCRobotPlayer *rrp)
{
if (!rrp->isSteadyState())
return false;
link->send(TurnRemainingReply(rrp->turnRemaining * 180.0f/M_PI));
return true;
}
bool GetTickDurationReq::process(RCRobotPlayer *rrp)
{
link->sendf("GetTickDuration %f\n", rrp->tickDuration);
return true;
}
bool SetTickDurationReq::process(RCRobotPlayer *rrp)
{
rrp->tickDuration = duration;
return true;
}
bool GetTickRemainingReq::process(RCRobotPlayer *rrp)
{
if (rrp->isSteadyState())
link->sendf("GetTickRemaining %f\n", (rrp->lastTickAt + rrp->tickDuration) - TimeKeeper::getCurrent().getSeconds());
else
link->send("GetTickRemaining 0.0\n");
return true;
}
bool GetBattleFieldSizeReq::process(RCRobotPlayer *)
{
link->send(BattleFieldSizeReply(BZDBCache::worldSize));
return true;
}
bool GetTeamsReq::process(RCRobotPlayer *)
{
// TODO: Implement this. :p
return true;
}
bool GetBasesReq::process(RCRobotPlayer *)
{
// TODO: Implement this. :p
return true;
}
bool GetObstaclesReq::process(RCRobotPlayer *)
{
// TODO: Implement this. :p
return true;
}
bool GetFlagsReq::process(RCRobotPlayer *)
{
// TODO: Implement this. :p
return true;
}
bool GetShotsReq::process(RCRobotPlayer *)
{
// TODO: Implement this. :p
return true;
}
bool GetMyTanksReq::process(RCRobotPlayer *)
{
// TODO: Implement this. :p
return true;
}
bool GetOtherTanksReq::process(RCRobotPlayer *)
{
// TODO: Implement this. :p
return true;
}
bool GetConstantsReq::process(RCRobotPlayer *)
{
// TODO: Implement this. :p
return true;
}
bool GetXReq::process(RCRobotPlayer *rrp)
{
link->send(XReply(rrp->getPosition()[0]));
return true;
}
bool GetYReq::process(RCRobotPlayer *rrp)
{
link->send(YReply(rrp->getPosition()[1]));
return true;
}
bool GetZReq::process(RCRobotPlayer *rrp)
{
link->send(ZReply(rrp->getPosition()[2]));
return true;
}
bool GetWidthReq::process(RCRobotPlayer *rrp)
{
link->send(WidthReply(rrp->getDimensions()[0]));
return true;
}
bool GetLengthReq::process(RCRobotPlayer *rrp)
{
link->send(LengthReply(rrp->getDimensions()[1]));
return true;
}
bool GetHeightReq::process(RCRobotPlayer *rrp)
{
link->send(HeightReply(rrp->getDimensions()[2]));
return true;
}
bool GetHeadingReq::process(RCRobotPlayer *rrp)
{
link->send(HeadingReply(rrp->getAngle()*180.0f/M_PI));
return true;
}
bool SetStopReq::process(RCRobotPlayer *rrp)
{
if (!rrp->isSteadyState())
return false;
if (!rrp->hasStopped || overwrite)
{
rrp->hasStopped = true;
rrp->stoppedDistance = rrp->distanceRemaining;
rrp->stoppedTurn = rrp->turnRemaining;
rrp->stoppedForward = rrp->distanceForward;
rrp->stoppedLeft = rrp->turnLeft;
}
return true;
}
bool GetPlayersReq::process(RCRobotPlayer *)
{
link->send(PlayersBeginReply());
for (int i = 0; i < curMaxPlayers; i++) {
if (!player[i])
continue;
if (robots[0]->getId() == player[i]->getId())
continue;
TeamColor team = player[i]->getTeam();
if (team == ObserverTeam)
continue;
if (team == startupInfo.team && startupInfo.team != AutomaticTeam)
continue;
link->send(PlayersReply(player[i]));
}
return true;
}
// Local Variables: ***
// mode: C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>don't need version.h<commit_after>/* bzflag
* Copyright (c) 1993 - 2008 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named LICENSE that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#include "RCRequests.h"
#include "RCReplies.h"
#include "RCRobotPlayer.h"
#include "MessageUtilities.h"
#include "BZDBCache.h"
#include "Roster.h"
#include "World.h"
#include "playing.h"
bool ExecuteReq::process(RCRobotPlayer *rrp)
{
if (!rrp->isSteadyState())
return false;
rrp->lastTickAt = TimeKeeper::getCurrent().getSeconds();
if (rrp->pendingUpdates[RCRobotPlayer::speedUpdate])
rrp->speed = rrp->nextSpeed;
if (rrp->pendingUpdates[RCRobotPlayer::turnRateUpdate])
rrp->turnRate = rrp->nextTurnRate;
if (rrp->pendingUpdates[RCRobotPlayer::distanceUpdate])
{
if (rrp->nextDistance < 0.0f)
rrp->distanceForward = false;
else
rrp->distanceForward = true;
rrp->distanceRemaining = (rrp->distanceForward ? 1 : -1) * rrp->nextDistance;
}
if (rrp->pendingUpdates[RCRobotPlayer::turnUpdate])
{
if (rrp->nextTurn < 0.0f)
rrp->turnLeft = false;
else
rrp->turnLeft = true;
rrp->turnRemaining = (rrp->turnLeft ? 1 : -1) * rrp->nextTurn * M_PI/180.0f; /* We have to convert to radians! */
}
for (int i = 0; i < RCRobotPlayer::updateCount; ++i)
rrp->pendingUpdates[i] = false;
if (rrp->shoot)
{
rrp->shoot = false;
rrp->fireShot();
}
return true;
}
bool SetSpeedReq::process(RCRobotPlayer *rrp)
{
rrp->nextSpeed = speed;
rrp->pendingUpdates[RCRobotPlayer::speedUpdate] = true;
return true;
}
bool SetTurnRateReq::process(RCRobotPlayer *rrp)
{
rrp->nextTurnRate = rate;
rrp->pendingUpdates[RCRobotPlayer::turnRateUpdate] = true;
return true;
}
bool SetAheadReq::process(RCRobotPlayer *rrp)
{
rrp->pendingUpdates[RCRobotPlayer::distanceUpdate] = true;
rrp->nextDistance = distance;
return true;
}
bool SetTurnLeftReq::process(RCRobotPlayer *rrp)
{
rrp->pendingUpdates[RCRobotPlayer::turnUpdate] = true;
rrp->nextTurn = turn;
return true;
}
bool SetFireReq::process(RCRobotPlayer *rrp)
{
rrp->shoot = true;
return true;
}
bool SetResumeReq::process(RCRobotPlayer *rrp)
{
if (!rrp->isSteadyState())
return false;
if (rrp->hasStopped)
{
rrp->hasStopped = false;
rrp->distanceRemaining = rrp->stoppedDistance;
rrp->turnRemaining = rrp->stoppedTurn;
rrp->distanceForward = rrp->stoppedForward;
rrp->turnLeft = rrp->stoppedLeft;
}
return true;
}
bool GetGunHeatReq::process(RCRobotPlayer *rrp)
{
if (!rrp->isSteadyState())
return false;
link->send(GunHeatReply(rrp->getReloadTime()));
return true;
}
bool GetDistanceRemainingReq::process(RCRobotPlayer *rrp)
{
if (!rrp->isSteadyState())
return false;
link->send(DistanceRemainingReply(rrp->distanceRemaining));
return true;
}
bool GetTurnRemainingReq::process(RCRobotPlayer *rrp)
{
if (!rrp->isSteadyState())
return false;
link->send(TurnRemainingReply(rrp->turnRemaining * 180.0f/M_PI));
return true;
}
bool GetTickDurationReq::process(RCRobotPlayer *rrp)
{
link->sendf("GetTickDuration %f\n", rrp->tickDuration);
return true;
}
bool SetTickDurationReq::process(RCRobotPlayer *rrp)
{
rrp->tickDuration = duration;
return true;
}
bool GetTickRemainingReq::process(RCRobotPlayer *rrp)
{
if (rrp->isSteadyState())
link->sendf("GetTickRemaining %f\n", (rrp->lastTickAt + rrp->tickDuration) - TimeKeeper::getCurrent().getSeconds());
else
link->send("GetTickRemaining 0.0\n");
return true;
}
bool GetBattleFieldSizeReq::process(RCRobotPlayer *)
{
link->send(BattleFieldSizeReply(BZDBCache::worldSize));
return true;
}
bool GetTeamsReq::process(RCRobotPlayer *)
{
// TODO: Implement this. :p
return true;
}
bool GetBasesReq::process(RCRobotPlayer *)
{
// TODO: Implement this. :p
return true;
}
bool GetObstaclesReq::process(RCRobotPlayer *)
{
// TODO: Implement this. :p
return true;
}
bool GetFlagsReq::process(RCRobotPlayer *)
{
// TODO: Implement this. :p
return true;
}
bool GetShotsReq::process(RCRobotPlayer *)
{
// TODO: Implement this. :p
return true;
}
bool GetMyTanksReq::process(RCRobotPlayer *)
{
// TODO: Implement this. :p
return true;
}
bool GetOtherTanksReq::process(RCRobotPlayer *)
{
// TODO: Implement this. :p
return true;
}
bool GetConstantsReq::process(RCRobotPlayer *)
{
// TODO: Implement this. :p
return true;
}
bool GetXReq::process(RCRobotPlayer *rrp)
{
link->send(XReply(rrp->getPosition()[0]));
return true;
}
bool GetYReq::process(RCRobotPlayer *rrp)
{
link->send(YReply(rrp->getPosition()[1]));
return true;
}
bool GetZReq::process(RCRobotPlayer *rrp)
{
link->send(ZReply(rrp->getPosition()[2]));
return true;
}
bool GetWidthReq::process(RCRobotPlayer *rrp)
{
link->send(WidthReply(rrp->getDimensions()[0]));
return true;
}
bool GetLengthReq::process(RCRobotPlayer *rrp)
{
link->send(LengthReply(rrp->getDimensions()[1]));
return true;
}
bool GetHeightReq::process(RCRobotPlayer *rrp)
{
link->send(HeightReply(rrp->getDimensions()[2]));
return true;
}
bool GetHeadingReq::process(RCRobotPlayer *rrp)
{
link->send(HeadingReply(rrp->getAngle()*180.0f/M_PI));
return true;
}
bool SetStopReq::process(RCRobotPlayer *rrp)
{
if (!rrp->isSteadyState())
return false;
if (!rrp->hasStopped || overwrite)
{
rrp->hasStopped = true;
rrp->stoppedDistance = rrp->distanceRemaining;
rrp->stoppedTurn = rrp->turnRemaining;
rrp->stoppedForward = rrp->distanceForward;
rrp->stoppedLeft = rrp->turnLeft;
}
return true;
}
bool GetPlayersReq::process(RCRobotPlayer *)
{
link->send(PlayersBeginReply());
for (int i = 0; i < curMaxPlayers; i++) {
if (!player[i])
continue;
if (robots[0]->getId() == player[i]->getId())
continue;
TeamColor team = player[i]->getTeam();
if (team == ObserverTeam)
continue;
if (team == startupInfo.team && startupInfo.team != AutomaticTeam)
continue;
link->send(PlayersReply(player[i]));
}
return true;
}
// Local Variables: ***
// mode: C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|>
|
<commit_before>/***********************************************************************
filename: CEGUIGeometryBuffer.cpp
created: Wed Jan 13 2010
author: Paul D Turner <paul@cegui.org.uk>
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2010 Paul D Turner & The CEGUI Development Team
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
***************************************************************************/
#include "CEGUI/GeometryBuffer.h"
#include "CEGUI/Vertex.h"
#include "CEGUI/ShaderParameterBindings.h"
#include <vector>
namespace CEGUI
{
//---------------------------------------------------------------------------//
GeometryBuffer::GeometryBuffer(RefCounted<RenderMaterial> renderMaterial)
: d_translation(0, 0, 0)
, d_rotation(Quaternion::IDENTITY)
, d_scale(1.0f, 1.0f, 1.0f)
, d_pivot(0, 0, 0)
, d_customTransform(1.0f)
, d_effect(0)
, d_matrixValid(false)
, d_blendMode(BM_NORMAL)
, d_renderMaterial(renderMaterial)
, d_polygonFillRule(PFR_NONE)
, d_postStencilVertexCount(0)
{
}
//---------------------------------------------------------------------------//
GeometryBuffer::~GeometryBuffer()
{
}
//---------------------------------------------------------------------------//
void GeometryBuffer::setBlendMode(const BlendMode mode)
{
d_blendMode = mode;
}
//---------------------------------------------------------------------------//
BlendMode GeometryBuffer::getBlendMode() const
{
return d_blendMode;
}
//---------------------------------------------------------------------------//
void GeometryBuffer::appendGeometry(const std::vector<ColouredVertex>& coloured_vertices)
{
if(coloured_vertices.empty())
return;
appendGeometry(&coloured_vertices[0], coloured_vertices.size());
}
//---------------------------------------------------------------------------//
void GeometryBuffer::appendGeometry(const ColouredVertex* vertex_array,
uint vertex_count)
{
// Add the vertex data in their default order into an array
std::vector<float> vertexData;
const ColouredVertex* vs = vertex_array;
for (uint i = 0; i < vertex_count; ++i, ++vs)
{
// Add all the elements in the default order for textured and coloured
// geometry into the vector
vertexData.push_back(vs->d_position.x);
vertexData.push_back(vs->d_position.y);
vertexData.push_back(vs->d_position.z);
vertexData.push_back(vs->d_colour.getRed());
vertexData.push_back(vs->d_colour.getGreen());
vertexData.push_back(vs->d_colour.getBlue());
vertexData.push_back(vs->d_colour.getAlpha());
}
// Append the prepared geometry data
appendGeometry(vertexData);
}
//---------------------------------------------------------------------------//
void GeometryBuffer::appendGeometry(const std::vector<TexturedColouredVertex>& textured_vertices)
{
if(textured_vertices.empty())
return;
appendGeometry(&textured_vertices[0], textured_vertices.size());
}
//---------------------------------------------------------------------------//
void GeometryBuffer::appendGeometry(const TexturedColouredVertex* vertex_array,
uint vertex_count)
{
// Add the vertex data in their default order into an array
std::vector<float> vertexData;
const TexturedColouredVertex* vs = vertex_array;
for (uint i = 0; i < vertex_count; ++i, ++vs)
{
// Add all the elements in the default order for textured and coloured
// geometry into the vector
vertexData.push_back(vs->d_position.x);
vertexData.push_back(vs->d_position.y);
vertexData.push_back(vs->d_position.z);
vertexData.push_back(vs->d_colour.getRed());
vertexData.push_back(vs->d_colour.getGreen());
vertexData.push_back(vs->d_colour.getBlue());
vertexData.push_back(vs->d_colour.getAlpha());
vertexData.push_back(vs->d_texCoords.x);
vertexData.push_back(vs->d_texCoords.y);
}
// Append the prepared geometry data
appendGeometry(vertexData);
}
//---------------------------------------------------------------------------//
void GeometryBuffer::appendGeometry(const float* const vertex_data,
uint array_size)
{
std::vector<float> vectorVertexData(vertex_data, vertex_data + array_size);
appendGeometry(vectorVertexData);
}
//---------------------------------------------------------------------------//
void GeometryBuffer::appendVertex(const TexturedColouredVertex& vertex)
{
// Add the vertex data in their default order into an array
float vertexData[9];
// Copy the vertex attributes into the array
vertexData[0] = vertex.d_position.x;
vertexData[1] = vertex.d_position.y;
vertexData[2] = vertex.d_position.z;
vertexData[3] = vertex.d_colour.getRed();
vertexData[4] = vertex.d_colour.getGreen();
vertexData[5] = vertex.d_colour.getBlue();
vertexData[6] = vertex.d_colour.getAlpha();
vertexData[7] = vertex.d_texCoords.x;
vertexData[8] = vertex.d_texCoords.y;
appendGeometry(vertexData, 9);
}
//---------------------------------------------------------------------------//
void GeometryBuffer::appendVertex(const ColouredVertex& vertex)
{
// Add the vertex data in their default order into an array
float vertexData[7];
// Copy the vertex attributes into the array
vertexData[0] = vertex.d_position.x;
vertexData[1] = vertex.d_position.y;
vertexData[2] = vertex.d_position.z;
vertexData[3] = vertex.d_colour.getRed();
vertexData[4] = vertex.d_colour.getGreen();
vertexData[5] = vertex.d_colour.getBlue();
vertexData[6] = vertex.d_colour.getAlpha();
appendGeometry(vertexData, 7);
}
//---------------------------------------------------------------------------//
int GeometryBuffer::getVertexAttributeElementCount() const
{
int count = 0;
const unsigned int attribute_count = d_vertexAttributes.size();
for (unsigned int i = 0; i < attribute_count; ++i)
{
switch(d_vertexAttributes.at(i))
{
case VAT_POSITION0:
count += 3;
break;
case VAT_COLOUR0:
count += 4;
break;
case VAT_TEXCOORD0:
count += 2;
break;
default:
break;
}
}
return count;
}
//---------------------------------------------------------------------------//
void GeometryBuffer::resetVertexAttributes()
{
d_vertexAttributes.clear();
}
//---------------------------------------------------------------------------//
void GeometryBuffer::addVertexAttribute(VertexAttributeType attribute)
{
d_vertexAttributes.push_back(attribute);
}
//---------------------------------------------------------------------------//
RefCounted<RenderMaterial> GeometryBuffer::getRenderMaterial() const
{
return d_renderMaterial;
}
//---------------------------------------------------------------------------//
void GeometryBuffer::setRenderMaterial(RefCounted<RenderMaterial> render_material)
{
d_renderMaterial = render_material;
}
//---------------------------------------------------------------------------//
void GeometryBuffer::setStencilRenderingActive(PolygonFillRule fill_rule)
{
d_polygonFillRule = fill_rule;
}
//---------------------------------------------------------------------------//
void GeometryBuffer::setStencilPostRenderingVertexCount(unsigned int vertex_count)
{
d_postStencilVertexCount = vertex_count;
}
//----------------------------------------------------------------------------//
void GeometryBuffer::setRenderEffect(RenderEffect* effect)
{
d_effect = effect;
}
//----------------------------------------------------------------------------//
RenderEffect* GeometryBuffer::getRenderEffect()
{
return d_effect;
}
//----------------------------------------------------------------------------//
void GeometryBuffer::setTranslation(const Vector3f& translation)
{
if(d_translation != translation)
{
d_translation = translation;
d_matrixValid = false;
}
}
//----------------------------------------------------------------------------//
void GeometryBuffer::setRotation(const Quaternion& rotationQuat)
{
if(d_rotation != rotationQuat)
{
d_rotation = rotationQuat;
d_matrixValid = false;
}
}
//----------------------------------------------------------------------------//
void GeometryBuffer::setScale(const Vector3f& scale)
{
if(d_scale != scale)
{
d_scale = scale;
d_matrixValid = false;
}
}
//----------------------------------------------------------------------------//
void GeometryBuffer::setScale(const Vector2f& scale)
{
setScale(Vector3f(scale, 0.f));
}
//----------------------------------------------------------------------------//
void GeometryBuffer::setPivot(const Vector3f& p)
{
if(d_pivot != p)
{
d_pivot = Vector3f(p.d_x, p.d_y, p.d_z);
d_matrixValid = false;
}
}
//----------------------------------------------------------------------------//
void GeometryBuffer::setCustomTransform(const glm::mat4x4& transformation)
{
if(d_customTransform != transformation)
{
d_customTransform = transformation;
d_matrixValid = false;
}
}
//----------------------------------------------------------------------------//
void GeometryBuffer::setClippingActive(const bool active)
{
d_clippingActive = active;
}
//----------------------------------------------------------------------------//
bool GeometryBuffer::isClippingActive() const
{
return d_clippingActive;
}
//----------------------------------------------------------------------------//
uint GeometryBuffer::getVertexCount() const
{
return d_vertexCount;
}
//----------------------------------------------------------------------------//
void GeometryBuffer::reset()
{
d_vertexData.clear();
d_clippingActive = true;
setTexture(0);
}
//----------------------------------------------------------------------------//
void GeometryBuffer::setTexture(Texture* texture)
{
CEGUI::ShaderParameterBindings* shaderParameterBindings = (*d_renderMaterial).getShaderParamBindings();
shaderParameterBindings->setParameter("texture0", texture);
}
//---------------------------------------------------------------------------//
}
<commit_msg>MOD: Fixed an issue with shader parameters and the GeomBuffer reset function Thanks to timotei for reporting this<commit_after>/***********************************************************************
filename: CEGUIGeometryBuffer.cpp
created: Wed Jan 13 2010
author: Paul D Turner <paul@cegui.org.uk>
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2010 Paul D Turner & The CEGUI Development Team
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
***************************************************************************/
#include "CEGUI/GeometryBuffer.h"
#include "CEGUI/Vertex.h"
#include "CEGUI/ShaderParameterBindings.h"
#include <vector>
namespace CEGUI
{
//---------------------------------------------------------------------------//
GeometryBuffer::GeometryBuffer(RefCounted<RenderMaterial> renderMaterial)
: d_translation(0, 0, 0)
, d_rotation(Quaternion::IDENTITY)
, d_scale(1.0f, 1.0f, 1.0f)
, d_pivot(0, 0, 0)
, d_customTransform(1.0f)
, d_effect(0)
, d_matrixValid(false)
, d_blendMode(BM_NORMAL)
, d_renderMaterial(renderMaterial)
, d_polygonFillRule(PFR_NONE)
, d_postStencilVertexCount(0)
{
}
//---------------------------------------------------------------------------//
GeometryBuffer::~GeometryBuffer()
{
}
//---------------------------------------------------------------------------//
void GeometryBuffer::setBlendMode(const BlendMode mode)
{
d_blendMode = mode;
}
//---------------------------------------------------------------------------//
BlendMode GeometryBuffer::getBlendMode() const
{
return d_blendMode;
}
//---------------------------------------------------------------------------//
void GeometryBuffer::appendGeometry(const std::vector<ColouredVertex>& coloured_vertices)
{
if(coloured_vertices.empty())
return;
appendGeometry(&coloured_vertices[0], coloured_vertices.size());
}
//---------------------------------------------------------------------------//
void GeometryBuffer::appendGeometry(const ColouredVertex* vertex_array,
uint vertex_count)
{
// Add the vertex data in their default order into an array
std::vector<float> vertexData;
const ColouredVertex* vs = vertex_array;
for (uint i = 0; i < vertex_count; ++i, ++vs)
{
// Add all the elements in the default order for textured and coloured
// geometry into the vector
vertexData.push_back(vs->d_position.x);
vertexData.push_back(vs->d_position.y);
vertexData.push_back(vs->d_position.z);
vertexData.push_back(vs->d_colour.getRed());
vertexData.push_back(vs->d_colour.getGreen());
vertexData.push_back(vs->d_colour.getBlue());
vertexData.push_back(vs->d_colour.getAlpha());
}
// Append the prepared geometry data
appendGeometry(vertexData);
}
//---------------------------------------------------------------------------//
void GeometryBuffer::appendGeometry(const std::vector<TexturedColouredVertex>& textured_vertices)
{
if(textured_vertices.empty())
return;
appendGeometry(&textured_vertices[0], textured_vertices.size());
}
//---------------------------------------------------------------------------//
void GeometryBuffer::appendGeometry(const TexturedColouredVertex* vertex_array,
uint vertex_count)
{
// Add the vertex data in their default order into an array
std::vector<float> vertexData;
const TexturedColouredVertex* vs = vertex_array;
for (uint i = 0; i < vertex_count; ++i, ++vs)
{
// Add all the elements in the default order for textured and coloured
// geometry into the vector
vertexData.push_back(vs->d_position.x);
vertexData.push_back(vs->d_position.y);
vertexData.push_back(vs->d_position.z);
vertexData.push_back(vs->d_colour.getRed());
vertexData.push_back(vs->d_colour.getGreen());
vertexData.push_back(vs->d_colour.getBlue());
vertexData.push_back(vs->d_colour.getAlpha());
vertexData.push_back(vs->d_texCoords.x);
vertexData.push_back(vs->d_texCoords.y);
}
// Append the prepared geometry data
appendGeometry(vertexData);
}
//---------------------------------------------------------------------------//
void GeometryBuffer::appendGeometry(const float* const vertex_data,
uint array_size)
{
std::vector<float> vectorVertexData(vertex_data, vertex_data + array_size);
appendGeometry(vectorVertexData);
}
//---------------------------------------------------------------------------//
void GeometryBuffer::appendVertex(const TexturedColouredVertex& vertex)
{
// Add the vertex data in their default order into an array
float vertexData[9];
// Copy the vertex attributes into the array
vertexData[0] = vertex.d_position.x;
vertexData[1] = vertex.d_position.y;
vertexData[2] = vertex.d_position.z;
vertexData[3] = vertex.d_colour.getRed();
vertexData[4] = vertex.d_colour.getGreen();
vertexData[5] = vertex.d_colour.getBlue();
vertexData[6] = vertex.d_colour.getAlpha();
vertexData[7] = vertex.d_texCoords.x;
vertexData[8] = vertex.d_texCoords.y;
appendGeometry(vertexData, 9);
}
//---------------------------------------------------------------------------//
void GeometryBuffer::appendVertex(const ColouredVertex& vertex)
{
// Add the vertex data in their default order into an array
float vertexData[7];
// Copy the vertex attributes into the array
vertexData[0] = vertex.d_position.x;
vertexData[1] = vertex.d_position.y;
vertexData[2] = vertex.d_position.z;
vertexData[3] = vertex.d_colour.getRed();
vertexData[4] = vertex.d_colour.getGreen();
vertexData[5] = vertex.d_colour.getBlue();
vertexData[6] = vertex.d_colour.getAlpha();
appendGeometry(vertexData, 7);
}
//---------------------------------------------------------------------------//
int GeometryBuffer::getVertexAttributeElementCount() const
{
int count = 0;
const unsigned int attribute_count = d_vertexAttributes.size();
for (unsigned int i = 0; i < attribute_count; ++i)
{
switch(d_vertexAttributes.at(i))
{
case VAT_POSITION0:
count += 3;
break;
case VAT_COLOUR0:
count += 4;
break;
case VAT_TEXCOORD0:
count += 2;
break;
default:
break;
}
}
return count;
}
//---------------------------------------------------------------------------//
void GeometryBuffer::resetVertexAttributes()
{
d_vertexAttributes.clear();
}
//---------------------------------------------------------------------------//
void GeometryBuffer::addVertexAttribute(VertexAttributeType attribute)
{
d_vertexAttributes.push_back(attribute);
}
//---------------------------------------------------------------------------//
RefCounted<RenderMaterial> GeometryBuffer::getRenderMaterial() const
{
return d_renderMaterial;
}
//---------------------------------------------------------------------------//
void GeometryBuffer::setRenderMaterial(RefCounted<RenderMaterial> render_material)
{
d_renderMaterial = render_material;
}
//---------------------------------------------------------------------------//
void GeometryBuffer::setStencilRenderingActive(PolygonFillRule fill_rule)
{
d_polygonFillRule = fill_rule;
}
//---------------------------------------------------------------------------//
void GeometryBuffer::setStencilPostRenderingVertexCount(unsigned int vertex_count)
{
d_postStencilVertexCount = vertex_count;
}
//----------------------------------------------------------------------------//
void GeometryBuffer::setRenderEffect(RenderEffect* effect)
{
d_effect = effect;
}
//----------------------------------------------------------------------------//
RenderEffect* GeometryBuffer::getRenderEffect()
{
return d_effect;
}
//----------------------------------------------------------------------------//
void GeometryBuffer::setTranslation(const Vector3f& translation)
{
if(d_translation != translation)
{
d_translation = translation;
d_matrixValid = false;
}
}
//----------------------------------------------------------------------------//
void GeometryBuffer::setRotation(const Quaternion& rotationQuat)
{
if(d_rotation != rotationQuat)
{
d_rotation = rotationQuat;
d_matrixValid = false;
}
}
//----------------------------------------------------------------------------//
void GeometryBuffer::setScale(const Vector3f& scale)
{
if(d_scale != scale)
{
d_scale = scale;
d_matrixValid = false;
}
}
//----------------------------------------------------------------------------//
void GeometryBuffer::setScale(const Vector2f& scale)
{
setScale(Vector3f(scale, 0.f));
}
//----------------------------------------------------------------------------//
void GeometryBuffer::setPivot(const Vector3f& p)
{
if(d_pivot != p)
{
d_pivot = Vector3f(p.d_x, p.d_y, p.d_z);
d_matrixValid = false;
}
}
//----------------------------------------------------------------------------//
void GeometryBuffer::setCustomTransform(const glm::mat4x4& transformation)
{
if(d_customTransform != transformation)
{
d_customTransform = transformation;
d_matrixValid = false;
}
}
//----------------------------------------------------------------------------//
void GeometryBuffer::setClippingActive(const bool active)
{
d_clippingActive = active;
}
//----------------------------------------------------------------------------//
bool GeometryBuffer::isClippingActive() const
{
return d_clippingActive;
}
//----------------------------------------------------------------------------//
uint GeometryBuffer::getVertexCount() const
{
return d_vertexCount;
}
//----------------------------------------------------------------------------//
void GeometryBuffer::reset()
{
d_vertexData.clear();
d_clippingActive = true;
// If the used render material uses a texture we will reset it in our shader parameter bindings
if((*d_renderMaterial).getShaderParamBindings()->getParameter("texture0") != 0)
setTexture(0);
}
//----------------------------------------------------------------------------//
void GeometryBuffer::setTexture(Texture* texture)
{
CEGUI::ShaderParameterBindings* shaderParameterBindings = (*d_renderMaterial).getShaderParamBindings();
shaderParameterBindings->setParameter("texture0", texture);
}
//---------------------------------------------------------------------------//
}
<|endoftext|>
|
<commit_before>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
#include "AliAnalysisManager.h"
#include "AliAnalysisTaskSE.h"
#include "AliAnalysisTaskPHOSTriggerQA.h"
#include "AliESDCaloCluster.h"
#include "AliPHOSGeometry.h"
#include "AliESDEvent.h"
#include "AliESDCaloCells.h"
#include "AliLog.h"
#include "TObjArray.h"
#include "TList.h"
#include "TH1.h"
#include "TH2.h"
// QA of PHOS Trigger data.
//...
// Author: Boris Polishchuk
// Date : 06.02.2012
ClassImp(AliAnalysisTaskPHOSTriggerQA)
//________________________________________________________________________
AliAnalysisTaskPHOSTriggerQA::AliAnalysisTaskPHOSTriggerQA() : AliAnalysisTaskSE(),
fOutputContainer(0),fPHOSGeo(0),fEventCounter(0),fL1Threshold(-1)
{
//Default constructor.
// Initialize the PHOS geometry
fPHOSGeo = AliPHOSGeometry::GetInstance("IHEP") ;
}
//________________________________________________________________________
AliAnalysisTaskPHOSTriggerQA::AliAnalysisTaskPHOSTriggerQA(const char *name, Int_t L1_threshold)
: AliAnalysisTaskSE(name),
fOutputContainer(0),fPHOSGeo(0),fEventCounter(0),fL1Threshold(L1_threshold)
{
// Output slots #0 write into a TH1 container
DefineOutput(1,TList::Class());
// Initialize the PHOS geometry
fPHOSGeo = AliPHOSGeometry::GetInstance("IHEP") ;
}
//________________________________________________________________________
void AliAnalysisTaskPHOSTriggerQA::UserCreateOutputObjects()
{
// Create histograms
// Called once
// ESD histograms
if(fOutputContainer != NULL){
delete fOutputContainer;
}
fOutputContainer = new TList();
fOutputContainer->SetOwner(kTRUE);
//Bin 1: total number of processed events.
//Bin 2: number of events contained PHOS trigger digits.
fOutputContainer->Add(new TH1F("hNev","Number of events",10,0.,10.));
char key[55],titl[55];
Int_t nCols = 56, nRows = 64;
Int_t nPtPhot = 1000 ;
Double_t ptPhotMax = 100. ;
Int_t nTrMax = 1200;
Float_t trMax = 600.;
fOutputContainer->Add(new TH1F("hNtr","Number of fired 4x4 regions per event",nTrMax,0.,trMax));
for(Int_t sm=1; sm<5; sm++) {
snprintf(key,55,"hNtrSM%d",sm);
snprintf(titl,55,"Number of fired 4x4 regions in SM%d",5-sm);
fOutputContainer->Add(new TH1F(key,titl,nTrMax/3,0.,trMax/3));
snprintf(key,55,"h4x4SM%d",sm);
snprintf(titl,55,"SM%d 4x4 occupancy",5-sm);
fOutputContainer->Add(new TH2F(key,titl,nRows,0.,nRows,nCols,0.,nCols));
snprintf(key,55,"h4x4CluSM%d",sm);
snprintf(titl,55,"SM%d 4x4 occupancy associated with clusters (E>2GeV)",5-sm);
fOutputContainer->Add(new TH2F(key,titl,nRows,0.,nRows,nCols,0.,nCols));
snprintf(key,55,"hCluSM%d",sm);
snprintf(titl,55,"SM%d cluster occupancy",5-sm);
fOutputContainer->Add(new TH2F(key,titl,nRows,0.,nRows,nCols,0.,nCols));
snprintf(key,55,"hCluTSM%d",sm);
snprintf(titl,55,"SM%d triggered cluster occupancy",5-sm);
fOutputContainer->Add(new TH2F(key,titl,nRows,0.,nRows,nCols,0.,nCols));
snprintf(key,55,"hPhotAllSM%d",sm);
snprintf(titl,55,"SM%d cluster energy",5-sm);
fOutputContainer->Add(new TH1F(key,titl,nPtPhot,0.,ptPhotMax));
for(Int_t iTRU=1; iTRU<=8; iTRU++) {
snprintf(key,55,"hPhotAllSM%dTRU%d",sm,iTRU);
snprintf(titl,55,"SM%d: clusters energy in TRU%d",5-sm,iTRU);
fOutputContainer->Add(new TH1F(key,titl,nPtPhot,0.,ptPhotMax));
}
snprintf(key,55,"hPhotTrigSM%d",sm);
snprintf(titl,55,"SM%d triggered cluster energy",5-sm);
fOutputContainer->Add(new TH1F(key,titl,nPtPhot,0.,ptPhotMax));
for(Int_t iTRU=1; iTRU<=8; iTRU++) {
snprintf(key,55,"hPhotTrigSM%dTRU%d",sm,iTRU);
snprintf(titl,55,"SM%d: triggered clusters energy in TRU%d",5-sm,iTRU);
fOutputContainer->Add(new TH1F(key,titl,nPtPhot,0.,ptPhotMax));
}
}
PostData(1, fOutputContainer);
}
//________________________________________________________________________
void AliAnalysisTaskPHOSTriggerQA::UserExec(Option_t *)
{
// Main loop, called for each event
// Analyze ESD/AOD
AliESDEvent *event = dynamic_cast<AliESDEvent*>(InputEvent());
if (!event) {
Printf("ERROR: Could not retrieve event");
PostData(1, fOutputContainer);
return;
}
FillHistogram("hNev",0.); // all events
fEventCounter++;
AliESDCaloTrigger* trgESD = event->GetCaloTrigger("PHOS");
trgESD->Reset();
if(trgESD->GetEntries())
FillHistogram("hNev",1.); // triggered events
TString trigClasses = event->GetFiredTriggerClasses();
printf("\nEvent %d: %d non-zero trigger digits %s\n",
fEventCounter,trgESD->GetEntries(),trigClasses.Data());
// Get PHOS rotation matrices from ESD and set them to the PHOS geometry
char key[55] ;
if(fEventCounter == 0) {
for(Int_t mod=0; mod<5; mod++) {
if(!event->GetPHOSMatrix(mod)) continue;
fPHOSGeo->SetMisalMatrix(event->GetPHOSMatrix(mod),mod) ;
}
}
Int_t multClu = event->GetNumberOfCaloClusters();
AliESDCaloCells *phsCells = event->GetPHOSCells();
Int_t inPHOS[3] = {};
Int_t ntr = 0;
//Loop over 4x4 fired regions
while(trgESD->Next()) {
// L1 threshold: -1-L0, 0-high, 1-medium, 2-low
if(trgESD->GetL1TimeSum() != fL1Threshold) continue;
ntr++;
Int_t tmod,tabsId; // "Online" module number, bottom-left 4x4 edge cell absId
trgESD->GetPosition(tmod,tabsId);
Int_t trelid[4] ;
fPHOSGeo->AbsToRelNumbering(tabsId,trelid);
snprintf(key,55,"h4x4SM%d",trelid[0]);
FillHistogram(key,trelid[2]-1,trelid[3]-1);
inPHOS[trelid[0]-1]++;
for (Int_t i=0; i<multClu; i++) {
AliESDCaloCluster *c1 = event->GetCaloCluster(i);
if(!c1->IsPHOS()) continue;
if(c1->GetType() == AliESDCaloCluster::kPHOSCharged) continue; // reject CPV cluster
if(c1->E()<0.3) continue;
if(c1->GetNCells()<3) continue ;
Int_t maxId, relid[4];
MaxEnergyCellPos(phsCells,c1,maxId);
fPHOSGeo->AbsToRelNumbering(maxId, relid);
snprintf(key,55,"hPhotAllSM%d",relid[0]);
FillHistogram(key,c1->E());
snprintf(key,55,"hPhotAllSM%dTRU%d",relid[0],GetTRUNum(relid[2]-1,relid[3]-1));
FillHistogram(key,c1->E());
snprintf(key,55,"hCluSM%d",relid[0]);
FillHistogram(key,relid[2]-1,relid[3]-1);
if( Matched(trelid,relid) ) {
snprintf(key,55,"hPhotTrigSM%d",relid[0]);
FillHistogram(key,c1->E());
snprintf(key,55,"hPhotTrigSM%dTRU%d",relid[0],GetTRUNum(relid[2]-1,relid[3]-1));
FillHistogram(key,c1->E());
snprintf(key,55,"hCluTSM%d",relid[0]);
FillHistogram(key,relid[2]-1,relid[3]-1);
if(c1->E()>2.) { // Eclu > 2 GeV
snprintf(key,55,"h4x4CluSM%d",trelid[0]);
FillHistogram(key,trelid[2]-1,trelid[3]-1);
}
continue;
}
}
} //while(trgESD->Next())
FillHistogram("hNtr",ntr); // number of selected triggers per event
for(Int_t sm=1; sm<4; sm++) {
snprintf(key,55,"hNtrSM%d",sm);
if(inPHOS[sm-1]) FillHistogram(key,inPHOS[sm-1]);
}
// Post output data.
PostData(1, fOutputContainer);
}
//_____________________________________________________________________________
void AliAnalysisTaskPHOSTriggerQA::FillHistogram(const char * key,Double_t x)const{
//FillHistogram
TH1I * tmpI = dynamic_cast<TH1I*>(fOutputContainer->FindObject(key)) ;
if(tmpI){
tmpI->Fill(x) ;
return ;
}
TH1F * tmpF = dynamic_cast<TH1F*>(fOutputContainer->FindObject(key)) ;
if(tmpF){
tmpF->Fill(x) ;
return ;
}
TH1D * tmpD = dynamic_cast<TH1D*>(fOutputContainer->FindObject(key)) ;
if(tmpD){
tmpD->Fill(x) ;
return ;
}
AliInfo(Form("can not find histogram <%s> ",key)) ;
}
//_____________________________________________________________________________
void AliAnalysisTaskPHOSTriggerQA::FillHistogram(const char * key,Double_t x,Double_t y)const{
//FillHistogram
TObject * tmp = fOutputContainer->FindObject(key) ;
if(!tmp){
AliInfo(Form("can not find histogram <%s> ",key)) ;
return ;
}
if(tmp->IsA() == TClass::GetClass("TH1F")){
((TH1F*)tmp)->Fill(x,y) ;
return ;
}
if(tmp->IsA() == TClass::GetClass("TH2F")){
((TH2F*)tmp)->Fill(x,y) ;
return ;
}
AliError(Form("Calling FillHistogram with 2 parameters for histo <%s> of type %s",key,tmp->IsA()->GetName())) ;
}
//_____________________________________________________________________________
void AliAnalysisTaskPHOSTriggerQA::MaxEnergyCellPos(AliESDCaloCells *cells, AliESDCaloCluster* clu, Int_t& maxId)
{
Double_t eMax = -111;
for (Int_t iDig=0; iDig< clu->GetNCells(); iDig++) {
Int_t cellAbsId = clu->GetCellAbsId(iDig);
Double_t eCell = cells->GetCellAmplitude(cellAbsId)*clu->GetCellAmplitudeFraction(iDig);
if(eCell>eMax) {
eMax = eCell;
maxId = cellAbsId;
}
}
}
//_____________________________________________________________________________
Bool_t AliAnalysisTaskPHOSTriggerQA::Matched(Int_t *trig_relid, Int_t *cluster_relid)
{
//Returns kTRUE if cluster position coincides with 4x4 position.
if( trig_relid[0] != cluster_relid[0] ) return kFALSE; // different modules!
if( TMath::Abs(trig_relid[2]-cluster_relid[2])>3 ) return kFALSE; // X-distance too large!
if( TMath::Abs(trig_relid[3]-cluster_relid[3])>3 ) return kFALSE; // Z-distance too large!
return kTRUE;
}
//_______________________________________________________________________________
Int_t AliAnalysisTaskPHOSTriggerQA::GetTRUNum(Int_t cellX, Int_t cellZ)
{
//Return TRU region number for given cell.
//cellX: [0-63], cellZ: [0-55]
Int_t iTRU=-111;
//RCU0: TRU 1,2
if(0<=cellX&&cellX<16) {
if(0<=cellZ&&cellZ<28) iTRU=2;
else iTRU=1;
}
//RCU1: TRU 3,4
if(16<=cellX&&cellX<32) {
if(0<=cellZ&&cellZ<28) iTRU=4;
else iTRU=3;
}
//RCU2: TRU 5,6
if(32<=cellX&&cellX<48) {
if(0<=cellZ&&cellZ<28) iTRU=6;
else iTRU=5;
}
//RCU3: TRU 7,8
if(48<=cellX&&cellX<64) {
if(0<=cellZ&&cellZ<28) iTRU=8;
else iTRU=7;
}
return iTRU;
}
<commit_msg>Wrong multiple counting of "triggered" clusters fixed.<commit_after>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
#include "AliAnalysisManager.h"
#include "AliAnalysisTaskSE.h"
#include "AliAnalysisTaskPHOSTriggerQA.h"
#include "AliESDCaloCluster.h"
#include "AliPHOSGeometry.h"
#include "AliESDEvent.h"
#include "AliESDCaloCells.h"
#include "AliLog.h"
#include "TObjArray.h"
#include "TList.h"
#include "TH1.h"
#include "TH2.h"
// QA of PHOS Trigger data.
//...
// Author: Boris Polishchuk
// Date : 06.02.2012
ClassImp(AliAnalysisTaskPHOSTriggerQA)
//________________________________________________________________________
AliAnalysisTaskPHOSTriggerQA::AliAnalysisTaskPHOSTriggerQA() : AliAnalysisTaskSE(),
fOutputContainer(0),fPHOSGeo(0),fEventCounter(0),fL1Threshold(-1)
{
//Default constructor.
// Initialize the PHOS geometry
fPHOSGeo = AliPHOSGeometry::GetInstance("IHEP") ;
}
//________________________________________________________________________
AliAnalysisTaskPHOSTriggerQA::AliAnalysisTaskPHOSTriggerQA(const char *name, Int_t L1_threshold)
: AliAnalysisTaskSE(name),
fOutputContainer(0),fPHOSGeo(0),fEventCounter(0),fL1Threshold(L1_threshold)
{
// Output slots #0 write into a TH1 container
DefineOutput(1,TList::Class());
// Initialize the PHOS geometry
fPHOSGeo = AliPHOSGeometry::GetInstance("IHEP") ;
}
//________________________________________________________________________
void AliAnalysisTaskPHOSTriggerQA::UserCreateOutputObjects()
{
// Create histograms
// Called once
// ESD histograms
if(fOutputContainer != NULL){
delete fOutputContainer;
}
fOutputContainer = new TList();
fOutputContainer->SetOwner(kTRUE);
//Bin 1: total number of processed events.
//Bin 2: number of events contained PHOS trigger digits.
fOutputContainer->Add(new TH1F("hNev","Number of events",10,0.,10.));
char key[55],titl[55];
Int_t nCols = 56, nRows = 64;
Int_t nPtPhot = 1000 ;
Double_t ptPhotMax = 100. ;
Int_t nTrMax = 1200;
Float_t trMax = 600.;
fOutputContainer->Add(new TH1F("hNtr","Number of fired 4x4 regions per event",nTrMax,0.,trMax));
for(Int_t sm=1; sm<5; sm++) {
snprintf(key,55,"hNtrSM%d",sm);
snprintf(titl,55,"Number of fired 4x4 regions in SM%d",5-sm);
fOutputContainer->Add(new TH1F(key,titl,nTrMax/3,0.,trMax/3));
snprintf(key,55,"h4x4SM%d",sm);
snprintf(titl,55,"SM%d 4x4 occupancy",5-sm);
fOutputContainer->Add(new TH2F(key,titl,nRows,0.,nRows,nCols,0.,nCols));
snprintf(key,55,"h4x4CluSM%d",sm);
snprintf(titl,55,"SM%d 4x4 occupancy associated with clusters (E>2GeV)",5-sm);
fOutputContainer->Add(new TH2F(key,titl,nRows,0.,nRows,nCols,0.,nCols));
snprintf(key,55,"hCluSM%d",sm);
snprintf(titl,55,"SM%d cluster occupancy",5-sm);
fOutputContainer->Add(new TH2F(key,titl,nRows,0.,nRows,nCols,0.,nCols));
snprintf(key,55,"hCluTSM%d",sm);
snprintf(titl,55,"SM%d triggered cluster occupancy",5-sm);
fOutputContainer->Add(new TH2F(key,titl,nRows,0.,nRows,nCols,0.,nCols));
snprintf(key,55,"hPhotAllSM%d",sm);
snprintf(titl,55,"SM%d cluster energy",5-sm);
fOutputContainer->Add(new TH1F(key,titl,nPtPhot,0.,ptPhotMax));
for(Int_t iTRU=1; iTRU<=8; iTRU++) {
snprintf(key,55,"hPhotAllSM%dTRU%d",sm,iTRU);
snprintf(titl,55,"SM%d: clusters energy in TRU%d",5-sm,iTRU);
fOutputContainer->Add(new TH1F(key,titl,nPtPhot,0.,ptPhotMax));
}
snprintf(key,55,"hPhotTrigSM%d",sm);
snprintf(titl,55,"SM%d triggered cluster energy",5-sm);
fOutputContainer->Add(new TH1F(key,titl,nPtPhot,0.,ptPhotMax));
for(Int_t iTRU=1; iTRU<=8; iTRU++) {
snprintf(key,55,"hPhotTrigSM%dTRU%d",sm,iTRU);
snprintf(titl,55,"SM%d: triggered clusters energy in TRU%d",5-sm,iTRU);
fOutputContainer->Add(new TH1F(key,titl,nPtPhot,0.,ptPhotMax));
}
}
PostData(1, fOutputContainer);
}
//________________________________________________________________________
void AliAnalysisTaskPHOSTriggerQA::UserExec(Option_t *)
{
// Main loop, called for each event
// Analyze ESD/AOD
AliESDEvent *event = dynamic_cast<AliESDEvent*>(InputEvent());
if (!event) {
Printf("ERROR: Could not retrieve event");
PostData(1, fOutputContainer);
return;
}
FillHistogram("hNev",0.); // all events
fEventCounter++;
AliESDCaloTrigger* trgESD = event->GetCaloTrigger("PHOS");
trgESD->Reset();
if(trgESD->GetEntries())
FillHistogram("hNev",1.); // triggered events
TString trigClasses = event->GetFiredTriggerClasses();
printf("\nEvent %d: %d non-zero trigger digits %s\n",
fEventCounter,trgESD->GetEntries(),trigClasses.Data());
// Get PHOS rotation matrices from ESD and set them to the PHOS geometry
char key[55] ;
if(fEventCounter == 0) {
for(Int_t mod=0; mod<5; mod++) {
if(!event->GetPHOSMatrix(mod)) continue;
fPHOSGeo->SetMisalMatrix(event->GetPHOSMatrix(mod),mod) ;
}
}
Int_t multClu = event->GetNumberOfCaloClusters();
AliESDCaloCells *phsCells = event->GetPHOSCells();
Int_t inPHOS[3] = {};
Int_t ntr = 0;
Int_t kUsedCluster[] = {multClu*0};
//Loop over 4x4 fired regions
while(trgESD->Next()) {
// L1 threshold: -1-L0, 0-high, 1-medium, 2-low
if(trgESD->GetL1TimeSum() != fL1Threshold) continue;
ntr++;
Int_t tmod,tabsId; // "Online" module number, bottom-left 4x4 edge cell absId
trgESD->GetPosition(tmod,tabsId);
Int_t trelid[4] ;
fPHOSGeo->AbsToRelNumbering(tabsId,trelid);
snprintf(key,55,"h4x4SM%d",trelid[0]);
FillHistogram(key,trelid[2]-1,trelid[3]-1);
inPHOS[trelid[0]-1]++;
for (Int_t i=0; i<multClu; i++) {
AliESDCaloCluster *c1 = event->GetCaloCluster(i);
if(kUsedCluster[i]) continue; // already matched to some trigger patch
if(!c1->IsPHOS()) continue;
if(c1->GetType() == AliESDCaloCluster::kPHOSCharged) continue; // reject CPV cluster
if(c1->E()<0.3) continue;
if(c1->GetNCells()<3) continue ;
Int_t maxId, relid[4];
MaxEnergyCellPos(phsCells,c1,maxId);
fPHOSGeo->AbsToRelNumbering(maxId, relid);
snprintf(key,55,"hPhotAllSM%d",relid[0]);
FillHistogram(key,c1->E());
snprintf(key,55,"hPhotAllSM%dTRU%d",relid[0],GetTRUNum(relid[2]-1,relid[3]-1));
FillHistogram(key,c1->E());
snprintf(key,55,"hCluSM%d",relid[0]);
FillHistogram(key,relid[2]-1,relid[3]-1);
if( Matched(trelid,relid) ) {
kUsedCluster[i] = 1;
snprintf(key,55,"hPhotTrigSM%d",relid[0]);
FillHistogram(key,c1->E());
snprintf(key,55,"hPhotTrigSM%dTRU%d",relid[0],GetTRUNum(relid[2]-1,relid[3]-1));
FillHistogram(key,c1->E());
snprintf(key,55,"hCluTSM%d",relid[0]);
FillHistogram(key,relid[2]-1,relid[3]-1);
if(c1->E()>2.) { // Eclu > 2 GeV
snprintf(key,55,"h4x4CluSM%d",trelid[0]);
FillHistogram(key,trelid[2]-1,trelid[3]-1);
}
continue;
}
}
} //while(trgESD->Next())
FillHistogram("hNtr",ntr); // number of selected triggers per event
for(Int_t sm=1; sm<4; sm++) {
snprintf(key,55,"hNtrSM%d",sm);
if(inPHOS[sm-1]) FillHistogram(key,inPHOS[sm-1]);
}
// Post output data.
PostData(1, fOutputContainer);
}
//_____________________________________________________________________________
void AliAnalysisTaskPHOSTriggerQA::FillHistogram(const char * key,Double_t x)const{
//FillHistogram
TH1I * tmpI = dynamic_cast<TH1I*>(fOutputContainer->FindObject(key)) ;
if(tmpI){
tmpI->Fill(x) ;
return ;
}
TH1F * tmpF = dynamic_cast<TH1F*>(fOutputContainer->FindObject(key)) ;
if(tmpF){
tmpF->Fill(x) ;
return ;
}
TH1D * tmpD = dynamic_cast<TH1D*>(fOutputContainer->FindObject(key)) ;
if(tmpD){
tmpD->Fill(x) ;
return ;
}
AliInfo(Form("can not find histogram <%s> ",key)) ;
}
//_____________________________________________________________________________
void AliAnalysisTaskPHOSTriggerQA::FillHistogram(const char * key,Double_t x,Double_t y)const{
//FillHistogram
TObject * tmp = fOutputContainer->FindObject(key) ;
if(!tmp){
AliInfo(Form("can not find histogram <%s> ",key)) ;
return ;
}
if(tmp->IsA() == TClass::GetClass("TH1F")){
((TH1F*)tmp)->Fill(x,y) ;
return ;
}
if(tmp->IsA() == TClass::GetClass("TH2F")){
((TH2F*)tmp)->Fill(x,y) ;
return ;
}
AliError(Form("Calling FillHistogram with 2 parameters for histo <%s> of type %s",key,tmp->IsA()->GetName())) ;
}
//_____________________________________________________________________________
void AliAnalysisTaskPHOSTriggerQA::MaxEnergyCellPos(AliESDCaloCells *cells, AliESDCaloCluster* clu, Int_t& maxId)
{
Double_t eMax = -111;
for (Int_t iDig=0; iDig< clu->GetNCells(); iDig++) {
Int_t cellAbsId = clu->GetCellAbsId(iDig);
Double_t eCell = cells->GetCellAmplitude(cellAbsId)*clu->GetCellAmplitudeFraction(iDig);
if(eCell>eMax) {
eMax = eCell;
maxId = cellAbsId;
}
}
}
//_____________________________________________________________________________
Bool_t AliAnalysisTaskPHOSTriggerQA::Matched(Int_t *trig_relid, Int_t *cluster_relid)
{
//Returns kTRUE if cluster position coincides with 4x4 position.
if( trig_relid[0] != cluster_relid[0] ) return kFALSE; // different modules!
if( TMath::Abs(trig_relid[2]-cluster_relid[2])>3 ) return kFALSE; // X-distance too large!
if( TMath::Abs(trig_relid[3]-cluster_relid[3])>3 ) return kFALSE; // Z-distance too large!
return kTRUE;
}
//_______________________________________________________________________________
Int_t AliAnalysisTaskPHOSTriggerQA::GetTRUNum(Int_t cellX, Int_t cellZ)
{
//Return TRU region number for given cell.
//cellX: [0-63], cellZ: [0-55]
Int_t iTRU=-111;
//RCU0: TRU 1,2
if(0<=cellX&&cellX<16) {
if(0<=cellZ&&cellZ<28) iTRU=2;
else iTRU=1;
}
//RCU1: TRU 3,4
if(16<=cellX&&cellX<32) {
if(0<=cellZ&&cellZ<28) iTRU=4;
else iTRU=3;
}
//RCU2: TRU 5,6
if(32<=cellX&&cellX<48) {
if(0<=cellZ&&cellZ<28) iTRU=6;
else iTRU=5;
}
//RCU3: TRU 7,8
if(48<=cellX&&cellX<64) {
if(0<=cellZ&&cellZ<28) iTRU=8;
else iTRU=7;
}
return iTRU;
}
<|endoftext|>
|
<commit_before>
#include "gtest/gtest.h"
#include "au/ThreadManager.h"
#include "engine/MemoryManager.h"
#include "engine/MemoryRequest.h"
#include "xmlparser/xmlParser.h"
#include "samson/client/SamsonClient.h"
#include "unitTest/common_engine_test.h"
#include "samson/common/ports.h" // for SAMSON_WORKER_PORT
TEST(samson_client, test_1 )
{
// SamsonClient to play with..
samson::SamsonClient* samson_client = init_samson_client_test();
// Connect to samsonWorker
au::ErrorManager error;
samson_client->initConnection( &error , "localhost" , SAMSON_WORKER_PORT , "anonymous" , "anonymous" );
EXPECT_EQ( error.isActivated() , false) << "Error connecting samsonClient to samsonWorker";
// Close samson client test
close_samson_client_test( samson_client );
}
TEST(samson_client, DISABLED_test_2 )
{
// SamsonClient to play with..
samson::SamsonClient* samson_client = init_samson_client_test();
// Connect to samsonWorker
au::ErrorManager error;
samson_client->initConnection( &error , "localhost" , SAMSON_WORKER_PORT , "anonymous" , "anonymous" );
ASSERT_TRUE(samson_client->connection_ready()) << "Connection not ready";
// Close samson client test
close_samson_client_test( samson_client );
}
<commit_msg>Test for SamsonClient. One test worked, let's try with the second one<commit_after>
#include "gtest/gtest.h"
#include "au/ThreadManager.h"
#include "engine/MemoryManager.h"
#include "engine/MemoryRequest.h"
#include "xmlparser/xmlParser.h"
#include "samson/client/SamsonClient.h"
#include "unitTest/common_engine_test.h"
#include "samson/common/ports.h" // for SAMSON_WORKER_PORT
TEST(samson_client, test_1 )
{
// SamsonClient to play with..
samson::SamsonClient* samson_client = init_samson_client_test();
// Connect to samsonWorker
au::ErrorManager error;
samson_client->initConnection( &error , "localhost" , SAMSON_WORKER_PORT , "anonymous" , "anonymous" );
EXPECT_EQ( error.isActivated() , false) << "Error connecting samsonClient to samsonWorker";
// Close samson client test
close_samson_client_test( samson_client );
}
TEST(samson_client, test_2 )
{
// SamsonClient to play with..
samson::SamsonClient* samson_client = init_samson_client_test();
// Connect to samsonWorker
au::ErrorManager error;
samson_client->initConnection( &error , "localhost" , SAMSON_WORKER_PORT , "anonymous" , "anonymous" );
ASSERT_TRUE(samson_client->connection_ready()) << "Connection not ready";
// Close samson client test
close_samson_client_test( samson_client );
}
<|endoftext|>
|
<commit_before>/*=============================================================================
Library: CTK
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics
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.
=============================================================================*/
// Qt includes
#include <QtPlugin>
#include <QRect>
#include <QDebug>
#include <QPushButton>
#include <QApplication>
#include <QLabel>
// CTK includes
#include "ctkDICOMImage.h"
#include "ctkExampleDicomAppLogic_p.h"
#include "ctkExampleDicomAppPlugin_p.h"
// DCMTK includes
#include <dcmimage.h>
//----------------------------------------------------------------------------
ctkExampleDicomAppLogic::ctkExampleDicomAppLogic()
: HostTracker(ctkExampleDicomAppPlugin::getPluginContext()), Button(0)
{
this->HostTracker.open();
connect(this, SIGNAL(stateChanged(int)), this, SLOT(changeState(int)), Qt::QueuedConnection);
emit stateChanged(ctkDicomAppHosting::IDLE);
}
//----------------------------------------------------------------------------
ctkExampleDicomAppLogic::~ctkExampleDicomAppLogic()
{
ctkPluginContext* context = ctkExampleDicomAppPlugin::getPluginContext();
QList <QSharedPointer<ctkPlugin> > plugins = context->getPlugins();
for (int i = 0; i < plugins.size(); ++i)
{
qDebug() << plugins.at(i)->getSymbolicName ();
}
}
//----------------------------------------------------------------------------
ctkDicomAppHosting::State ctkExampleDicomAppLogic::getState()
{
return ctkDicomAppHosting::IDLE;
}
//----------------------------------------------------------------------------
bool ctkExampleDicomAppLogic::setState(ctkDicomAppHosting::State newState)
{
qDebug() << "setState called";
emit stateChanged(newState);
return true;
}
//----------------------------------------------------------------------------
bool ctkExampleDicomAppLogic::bringToFront(const QRect& /*requestedScreenArea*/)
{
return false;
}
//----------------------------------------------------------------------------
void ctkExampleDicomAppLogic::do_something()
{
this->Button = new QPushButton("Button from App");
connect(this->Button, SIGNAL(clicked()), this, SLOT(buttonClicked()));
try
{
QRect preferred(50,50,100,100);
qDebug() << " Asking:getAvailableScreen";
QRect rect = getHostInterface()->getAvailableScreen(preferred);
qDebug() << " got sth:" << rect.top();
this->Button->move(rect.topLeft());
this->Button->resize(rect.size());
}
catch (const std::runtime_error& e)
{
qCritical() << e.what();
return;
}
this->Button->show();
}
//----------------------------------------------------------------------------
void ctkExampleDicomAppLogic::changeState(int anewstate)
{
ctkDicomAppHosting::State newstate = static_cast<ctkDicomAppHosting::State>(anewstate);
if (newstate == ctkDicomAppHosting::INPROGRESS)
{
do_something();
}
try
{
getHostInterface()->notifyStateChanged(newstate);
}
catch (const std::runtime_error& e)
{
qCritical() << e.what();
return;
}
if (newstate == ctkDicomAppHosting::CANCELED)
{
qDebug() << " Received changeState(CANCELED) ... now releasing all resources and afterwards changing to state IDLE.";
qDebug() << " Changing to state IDLE.";
try
{
getHostInterface()->notifyStateChanged(ctkDicomAppHosting::IDLE);
}
catch (const std::runtime_error& e)
{
qCritical() << e.what();
return;
}
}
if (newstate == ctkDicomAppHosting::EXIT)
{
qDebug() << " Received changeState(EXIT) ... exiting.";
this->getHostInterface()->notifyStateChanged(ctkDicomAppHosting::EXIT);
qApp->exit(0);
}
}
//----------------------------------------------------------------------------
bool ctkExampleDicomAppLogic::notifyDataAvailable(ctkDicomAppHosting::AvailableData data, bool lastData)
{
Q_UNUSED(lastData)
QString s;
if(this->Button == 0)
{
qCritical() << "Button is null!";
return false;
}
s = "Received notifyDataAvailable with patients.count()= " + QString().setNum(data.patients.count());
if(data.patients.count()>0)
{
s=s+" name:"+data.patients.begin()->name+" studies.count(): "+QString().setNum(data.patients.begin()->studies.count());
if(data.patients.begin()->studies.count()>0)
{
s=s+" series.count():" + QString().setNum(data.patients.begin()->studies.begin()->series.count());
if(data.patients.begin()->studies.begin()->series.count()>0)
{
s=s+" uid:" + data.patients.begin()->studies.begin()->series.begin()->seriesUID;
// QUuid uuid("93097dc1-caf9-43a3-a814-51a57f8d861d");//data.patients.begin()->studies.begin()->series.begin()->seriesUID);
uuid = data.patients.begin()->studies.begin()->series.begin()->objectDescriptors.begin()->descriptorUUID;
s=s+" uuid:"+uuid.toString();
}
}
}
this->Button->setText(s);
return false;
}
//----------------------------------------------------------------------------
QList<ctkDicomAppHosting::ObjectLocator> ctkExampleDicomAppLogic::getData(
QList<QUuid> objectUUIDs,
QList<QString> acceptableTransferSyntaxUIDs,
bool includeBulkData)
{
Q_UNUSED(objectUUIDs)
Q_UNUSED(acceptableTransferSyntaxUIDs)
Q_UNUSED(includeBulkData)
return QList<ctkDicomAppHosting::ObjectLocator>();
}
//----------------------------------------------------------------------------
void ctkExampleDicomAppLogic::releaseData(QList<QUuid> objectUUIDs)
{
Q_UNUSED(objectUUIDs)
}
ctkDicomHostInterface* ctkExampleDicomAppLogic::getHostInterface() const
{
ctkDicomHostInterface* host = this->HostTracker.getService();
if (!host) throw std::runtime_error("DICOM Host Interface not available");
return host;
}
void ctkExampleDicomAppLogic::buttonClicked()
{
QList<QUuid> uuidlist;
uuidlist.append(uuid);
QString transfersyntax("1.2.840.10008.1.2.1");
QList<QString> transfersyntaxlist;
transfersyntaxlist.append(transfersyntax);
QList<ctkDicomAppHosting::ObjectLocator> locators;
locators = getHostInterface()->getData(uuidlist, transfersyntaxlist, false);
qDebug() << "got locators! " << QString().setNum(locators.count());
QString s;
s=s+" loc.count:"+QString().setNum(locators.count());
if(locators.count()>0)
{
s=s+" URI: "+locators.begin()->URI;
qDebug() << "URI: " << locators.begin()->URI;
QString filename = locators.begin()->URI;
if(filename.startsWith("file:/",Qt::CaseInsensitive))
filename=filename.remove(0,6);
qDebug()<<filename;
DicomImage dcmtkImage(filename.toLatin1().data());
ctkDICOMImage ctkImage(&dcmtkImage);
QLabel* qtImage = new QLabel;
qtImage->setPixmap(ctkImage.getPixmap(0));
qtImage->show();
}
this->Button->setText(s);
}
<commit_msg>Comply with changed interface of ctkDICOMImage<commit_after>/*=============================================================================
Library: CTK
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics
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.
=============================================================================*/
// Qt includes
#include <QtPlugin>
#include <QRect>
#include <QDebug>
#include <QPushButton>
#include <QApplication>
#include <QLabel>
// CTK includes
#include "ctkDICOMImage.h"
#include "ctkExampleDicomAppLogic_p.h"
#include "ctkExampleDicomAppPlugin_p.h"
// DCMTK includes
#include <dcmimage.h>
//----------------------------------------------------------------------------
ctkExampleDicomAppLogic::ctkExampleDicomAppLogic()
: HostTracker(ctkExampleDicomAppPlugin::getPluginContext()), Button(0)
{
this->HostTracker.open();
connect(this, SIGNAL(stateChanged(int)), this, SLOT(changeState(int)), Qt::QueuedConnection);
emit stateChanged(ctkDicomAppHosting::IDLE);
}
//----------------------------------------------------------------------------
ctkExampleDicomAppLogic::~ctkExampleDicomAppLogic()
{
ctkPluginContext* context = ctkExampleDicomAppPlugin::getPluginContext();
QList <QSharedPointer<ctkPlugin> > plugins = context->getPlugins();
for (int i = 0; i < plugins.size(); ++i)
{
qDebug() << plugins.at(i)->getSymbolicName ();
}
}
//----------------------------------------------------------------------------
ctkDicomAppHosting::State ctkExampleDicomAppLogic::getState()
{
return ctkDicomAppHosting::IDLE;
}
//----------------------------------------------------------------------------
bool ctkExampleDicomAppLogic::setState(ctkDicomAppHosting::State newState)
{
qDebug() << "setState called";
emit stateChanged(newState);
return true;
}
//----------------------------------------------------------------------------
bool ctkExampleDicomAppLogic::bringToFront(const QRect& /*requestedScreenArea*/)
{
return false;
}
//----------------------------------------------------------------------------
void ctkExampleDicomAppLogic::do_something()
{
this->Button = new QPushButton("Button from App");
connect(this->Button, SIGNAL(clicked()), this, SLOT(buttonClicked()));
try
{
QRect preferred(50,50,100,100);
qDebug() << " Asking:getAvailableScreen";
QRect rect = getHostInterface()->getAvailableScreen(preferred);
qDebug() << " got sth:" << rect.top();
this->Button->move(rect.topLeft());
this->Button->resize(rect.size());
}
catch (const std::runtime_error& e)
{
qCritical() << e.what();
return;
}
this->Button->show();
}
//----------------------------------------------------------------------------
void ctkExampleDicomAppLogic::changeState(int anewstate)
{
ctkDicomAppHosting::State newstate = static_cast<ctkDicomAppHosting::State>(anewstate);
if (newstate == ctkDicomAppHosting::INPROGRESS)
{
do_something();
}
try
{
getHostInterface()->notifyStateChanged(newstate);
}
catch (const std::runtime_error& e)
{
qCritical() << e.what();
return;
}
if (newstate == ctkDicomAppHosting::CANCELED)
{
qDebug() << " Received changeState(CANCELED) ... now releasing all resources and afterwards changing to state IDLE.";
qDebug() << " Changing to state IDLE.";
try
{
getHostInterface()->notifyStateChanged(ctkDicomAppHosting::IDLE);
}
catch (const std::runtime_error& e)
{
qCritical() << e.what();
return;
}
}
if (newstate == ctkDicomAppHosting::EXIT)
{
qDebug() << " Received changeState(EXIT) ... exiting.";
this->getHostInterface()->notifyStateChanged(ctkDicomAppHosting::EXIT);
qApp->exit(0);
}
}
//----------------------------------------------------------------------------
bool ctkExampleDicomAppLogic::notifyDataAvailable(ctkDicomAppHosting::AvailableData data, bool lastData)
{
Q_UNUSED(lastData)
QString s;
if(this->Button == 0)
{
qCritical() << "Button is null!";
return false;
}
s = "Received notifyDataAvailable with patients.count()= " + QString().setNum(data.patients.count());
if(data.patients.count()>0)
{
s=s+" name:"+data.patients.begin()->name+" studies.count(): "+QString().setNum(data.patients.begin()->studies.count());
if(data.patients.begin()->studies.count()>0)
{
s=s+" series.count():" + QString().setNum(data.patients.begin()->studies.begin()->series.count());
if(data.patients.begin()->studies.begin()->series.count()>0)
{
s=s+" uid:" + data.patients.begin()->studies.begin()->series.begin()->seriesUID;
// QUuid uuid("93097dc1-caf9-43a3-a814-51a57f8d861d");//data.patients.begin()->studies.begin()->series.begin()->seriesUID);
uuid = data.patients.begin()->studies.begin()->series.begin()->objectDescriptors.begin()->descriptorUUID;
s=s+" uuid:"+uuid.toString();
}
}
}
this->Button->setText(s);
return false;
}
//----------------------------------------------------------------------------
QList<ctkDicomAppHosting::ObjectLocator> ctkExampleDicomAppLogic::getData(
QList<QUuid> objectUUIDs,
QList<QString> acceptableTransferSyntaxUIDs,
bool includeBulkData)
{
Q_UNUSED(objectUUIDs)
Q_UNUSED(acceptableTransferSyntaxUIDs)
Q_UNUSED(includeBulkData)
return QList<ctkDicomAppHosting::ObjectLocator>();
}
//----------------------------------------------------------------------------
void ctkExampleDicomAppLogic::releaseData(QList<QUuid> objectUUIDs)
{
Q_UNUSED(objectUUIDs)
}
ctkDicomHostInterface* ctkExampleDicomAppLogic::getHostInterface() const
{
ctkDicomHostInterface* host = this->HostTracker.getService();
if (!host) throw std::runtime_error("DICOM Host Interface not available");
return host;
}
void ctkExampleDicomAppLogic::buttonClicked()
{
QList<QUuid> uuidlist;
uuidlist.append(uuid);
QString transfersyntax("1.2.840.10008.1.2.1");
QList<QString> transfersyntaxlist;
transfersyntaxlist.append(transfersyntax);
QList<ctkDicomAppHosting::ObjectLocator> locators;
locators = getHostInterface()->getData(uuidlist, transfersyntaxlist, false);
qDebug() << "got locators! " << QString().setNum(locators.count());
QString s;
s=s+" loc.count:"+QString().setNum(locators.count());
if(locators.count()>0)
{
s=s+" URI: "+locators.begin()->URI;
qDebug() << "URI: " << locators.begin()->URI;
QString filename = locators.begin()->URI;
if(filename.startsWith("file:/",Qt::CaseInsensitive))
filename=filename.remove(0,6);
qDebug()<<filename;
DicomImage dcmtkImage(filename.toLatin1().data());
ctkDICOMImage ctkImage(&dcmtkImage);
QLabel* qtImage = new QLabel;
QPixmap pixmap = QPixmap::fromImage(ctkImage.getImage(0),Qt::AvoidDither);
if (pixmap.isNull())
{
qCritical() << "Failed to convert QImage to QPixmap" ;
}
else
{
qtImage->setPixmap(pixmap);
qtImage->show();
}
}
this->Button->setText(s);
}
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Medical Imaging & Interaction Toolkit
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html 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.
=========================================================================*/
// Blueberry
#include <berryISelectionService.h>
#include <berryIWorkbenchWindow.h>
#include <berryUIException.h>
#include <berryIWorkbenchPage.h>
#include <berryIPreferencesService.h>
#include <berryIPartListener.h>
#include <mitkGlobalInteraction.h>
#include <mitkDataStorageEditorInput.h>
#include "berryFileEditorInput.h"
// Qmitk
#include "QmitkDicomEditor.h"
#include "mitkPluginActivator.h"
#include <mitkDicomSeriesReader.h>
//#include "mitkProgressBar.h"
// Qt
#include <QCheckBox>
#include <QMessageBox>
#include <QWidget>
#include <QtSql>
#include <QSqlDatabase>
#include <QtCore/QVariant>
#include <QtGui/QAction>
#include <QtGui/QApplication>
#include <QtGui/QButtonGroup>
#include <QtGui/QGridLayout>
#include <QtGui/QHeaderView>
#include <QtGui/QPushButton>
#include <QtGui/QTextEdit>
#include <QtGui/QWidget>
//CTK
#include <ctkDICOMModel.h>
#include <ctkDICOMAppWidget.h>
#include <ctkDICOMQueryWidget.h>
#include <ctkFileDialog.h>
#include <ctkDICOMQueryRetrieveWidget.h>
const std::string QmitkDicomEditor::EDITOR_ID = "org.mitk.editors.dicomeditor";
QmitkDicomEditor::QmitkDicomEditor()
: m_Thread(new QThread())
, m_DicomDirectoryListener(new QmitkDicomDirectoryListener())
, m_ListenerDirectory(new QString())
, m_DatabaseDirectory(new QString())
, m_PluginDirectory(new QString())
{
}
QmitkDicomEditor::~QmitkDicomEditor()
{
m_Thread->terminate();
delete m_Handler;
delete m_Publisher;
delete m_StoreSCPLauncher;
delete m_Thread;
delete m_DicomDirectoryListener;
delete m_ListenerDirectory;
delete m_DatabaseDirectory;
delete m_PluginDirectory;
}
void QmitkDicomEditor::CreateQtPartControl(QWidget *parent )
{
m_Controls.setupUi( parent );
TestHandler();
SetPluginDirectory();
SetDatabaseDirectory("DatabaseDirectory");
SetListenerDirectory("ListenerDirectory");
StartDicomDirectoryListener();
m_Controls.m_ctkDICOMQueryRetrieveWidget->useProgressDialog(false);
connect(m_Controls.externalDataWidget,SIGNAL(SignalAddDicomData(const QString&)),m_Controls.internalDataWidget,SLOT(StartDicomImport(const QString&)));
connect(m_Controls.externalDataWidget,SIGNAL(SignalAddDicomData(const QStringList&)),m_Controls.internalDataWidget,SLOT(StartDicomImport(const QStringList&)));
connect(m_Controls.externalDataWidget,SIGNAL(SignalDicomToDataManager(const QStringList&)),this,SLOT(OnViewButtonAddToDataManager(const QStringList&)));
connect(m_Controls.externalDataWidget,SIGNAL(SignalChangePage(int)), this, SLOT(OnChangePage(int)));
connect(m_Controls.internalDataWidget,SIGNAL(FinishedImport(const QString&)),this,SLOT(OnDicomImportFinished(const QString&)));
connect(m_Controls.internalDataWidget,SIGNAL(FinishedImport(const QStringList&)),this,SLOT(OnDicomImportFinished(const QStringList&)));
connect(m_Controls.internalDataWidget,SIGNAL(SignalDicomToDataManager(const QStringList&)),this,SLOT(OnViewButtonAddToDataManager(const QStringList&)));
connect(m_Controls.CDButton, SIGNAL(clicked()), m_Controls.externalDataWidget, SLOT(OnFolderCDImport()));
connect(m_Controls.FolderButton, SIGNAL(clicked()), m_Controls.externalDataWidget, SLOT(OnFolderCDImport()));
connect(m_Controls.QueryRetrieveButton, SIGNAL(clicked()), this, SLOT(OnQueryRetrieve()));
connect(m_Controls.LocalStorageButton, SIGNAL(clicked()), this, SLOT(OnLocalStorage()));
//connect(m_Controls.radioButton,SIGNAL(clicked()),this,SLOT(StartStopStoreSCP()));
}
void QmitkDicomEditor::Init(berry::IEditorSite::Pointer site, berry::IEditorInput::Pointer input)
{
this->SetSite(site);
this->SetInput(input);
}
void QmitkDicomEditor::SetFocus()
{
}
berry::IPartListener::Events::Types QmitkDicomEditor::GetPartEventTypes() const
{
return Events::CLOSED | Events::HIDDEN | Events::VISIBLE;
}
void QmitkDicomEditor::OnQueryRetrieve()
{
OnChangePage(2);
StartStopStoreSCP();
}
void QmitkDicomEditor::OnLocalStorage()
{
OnChangePage(0);
}
void QmitkDicomEditor::OnChangePage(int page)
{
try{
m_Controls.stackedWidget->setCurrentIndex(page);
}catch(std::exception e){
MITK_ERROR <<"error: "<< e.what();
return;
}
}
void QmitkDicomEditor::OnDicomImportFinished(const QString& path)
{
}
void QmitkDicomEditor::OnDicomImportFinished(const QStringList& path)
{
}
void QmitkDicomEditor::StartDicomDirectoryListener()
{
if(!m_Thread->isRunning())
{
m_DicomDirectoryListener->SetDicomListenerDirectory(*m_ListenerDirectory);
connect(m_DicomDirectoryListener,SIGNAL(SignalAddDicomData(const QStringList&)),m_Controls.internalDataWidget,SLOT(StartDicomImport(const QStringList&)),Qt::DirectConnection);
connect(m_Controls.internalDataWidget,SIGNAL(FinishedImport(const QStringList&)),m_DicomDirectoryListener,SLOT(OnDicomImportFinished(const QStringList&)),Qt::DirectConnection);
m_DicomDirectoryListener->moveToThread(m_Thread);
m_Thread->start();
}
}
//TODO Remove
void QmitkDicomEditor::TestHandler()
{
m_Handler = new DicomEventHandler();
m_Handler->SubscribeSlots();
}
void QmitkDicomEditor::OnViewButtonAddToDataManager(const QStringList& eventProperties)
{
ctkDictionary properties;
properties["PatientName"] = eventProperties.at(0);
properties["StudyUID"] = eventProperties.at(1);
properties["StudyName"] = eventProperties.at(2);
properties["SeriesUID"] = eventProperties.at(3);
properties["SeriesName"] = eventProperties.at(4);
properties["Path"] = eventProperties.at(5);
m_Publisher = new QmitkDicomDataEventPublisher();
m_Publisher->PublishSignals(mitk::PluginActivator::getContext());
m_Publisher->AddSeriesToDataManagerEvent(properties);
}
void QmitkDicomEditor::StartStoreSCP()
{
QString storagePort = m_Controls.m_ctkDICOMQueryRetrieveWidget->getServerParameters()["StoragePort"].toString();
QString storageAET = m_Controls.m_ctkDICOMQueryRetrieveWidget->getServerParameters()["StorageAETitle"].toString();
builder.AddPort(storagePort)->AddAETitle(storageAET)->AddTransferSyntax()->AddOtherNetworkOptions()->AddMode()->AddOutputDirectory(*m_ListenerDirectory);
m_StoreSCPLauncher = new QmitkStoreSCPLauncher(&builder);
m_StoreSCPLauncher->StartStoreSCP();
m_Controls.radioButton->setChecked(true);
m_Controls.radioButton->setText(storageAET+QString(" ")+storagePort);
}
void QmitkDicomEditor::StopStoreSCP()
{
delete m_StoreSCPLauncher;
m_Controls.radioButton->setChecked(false);
m_Controls.radioButton->setText(QString("Storage service provider is not running!"));
}
void QmitkDicomEditor::StartStopStoreSCP()
{
QString storagePort = m_Controls.m_ctkDICOMQueryRetrieveWidget->getServerParameters()["StoragePort"].toString();
QString storageAET = m_Controls.m_ctkDICOMQueryRetrieveWidget->getServerParameters()["StorageAETitle"].toString();
if(!((builder.GetAETitle()->compare(storageAET,Qt::CaseSensitive)==0)&&
(builder.GetPort()->compare(storagePort,Qt::CaseSensitive)==0)))
{
if(m_Controls.radioButton->isChecked())
{
StopStoreSCP();
StartStoreSCP();
}else{
StartStoreSCP();
}
}
}
void QmitkDicomEditor::SetPluginDirectory()
{
mitk::PluginActivator::getContext()->getDataFile(*m_PluginDirectory);
m_PluginDirectory->append("/");
}
void QmitkDicomEditor::SetDatabaseDirectory(const QString& databaseDirectory)
{
m_DatabaseDirectory->clear();
m_DatabaseDirectory->append(m_PluginDirectory);
m_DatabaseDirectory->append(databaseDirectory);
m_Controls.internalDataWidget->SetDatabaseDirectory(*m_DatabaseDirectory);
}
void QmitkDicomEditor::SetListenerDirectory(const QString& listenerDirectory)
{
m_ListenerDirectory->clear();
m_ListenerDirectory->append(m_PluginDirectory);
m_ListenerDirectory->append(listenerDirectory);
}<commit_msg>fixed memory leak<commit_after>/*=========================================================================
Program: Medical Imaging & Interaction Toolkit
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html 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.
=========================================================================*/
// Blueberry
#include <berryISelectionService.h>
#include <berryIWorkbenchWindow.h>
#include <berryUIException.h>
#include <berryIWorkbenchPage.h>
#include <berryIPreferencesService.h>
#include <berryIPartListener.h>
#include <mitkGlobalInteraction.h>
#include <mitkDataStorageEditorInput.h>
#include "berryFileEditorInput.h"
// Qmitk
#include "QmitkDicomEditor.h"
#include "mitkPluginActivator.h"
#include <mitkDicomSeriesReader.h>
//#include "mitkProgressBar.h"
// Qt
#include <QCheckBox>
#include <QMessageBox>
#include <QWidget>
#include <QtSql>
#include <QSqlDatabase>
#include <QtCore/QVariant>
#include <QtGui/QAction>
#include <QtGui/QApplication>
#include <QtGui/QButtonGroup>
#include <QtGui/QGridLayout>
#include <QtGui/QHeaderView>
#include <QtGui/QPushButton>
#include <QtGui/QTextEdit>
#include <QtGui/QWidget>
//CTK
#include <ctkDICOMModel.h>
#include <ctkDICOMAppWidget.h>
#include <ctkDICOMQueryWidget.h>
#include <ctkFileDialog.h>
#include <ctkDICOMQueryRetrieveWidget.h>
const std::string QmitkDicomEditor::EDITOR_ID = "org.mitk.editors.dicomeditor";
QmitkDicomEditor::QmitkDicomEditor()
: m_Thread(new QThread())
, m_DicomDirectoryListener(new QmitkDicomDirectoryListener())
, m_ListenerDirectory(new QString())
, m_DatabaseDirectory(new QString())
, m_PluginDirectory(new QString())
, m_Publisher(new QmitkDicomDataEventPublisher())
, m_StoreSCPLauncher(new QmitkStoreSCPLauncher(&builder))
{
}
QmitkDicomEditor::~QmitkDicomEditor()
{
m_Thread->terminate();
delete m_Handler;
delete m_Publisher;
delete m_StoreSCPLauncher;
delete m_Thread;
delete m_DicomDirectoryListener;
delete m_ListenerDirectory;
delete m_DatabaseDirectory;
delete m_PluginDirectory;
}
void QmitkDicomEditor::CreateQtPartControl(QWidget *parent )
{
m_Controls.setupUi( parent );
TestHandler();
SetPluginDirectory();
SetDatabaseDirectory("DatabaseDirectory");
SetListenerDirectory("ListenerDirectory");
StartDicomDirectoryListener();
m_Controls.m_ctkDICOMQueryRetrieveWidget->useProgressDialog(false);
connect(m_Controls.externalDataWidget,SIGNAL(SignalAddDicomData(const QString&)),m_Controls.internalDataWidget,SLOT(StartDicomImport(const QString&)));
connect(m_Controls.externalDataWidget,SIGNAL(SignalAddDicomData(const QStringList&)),m_Controls.internalDataWidget,SLOT(StartDicomImport(const QStringList&)));
connect(m_Controls.externalDataWidget,SIGNAL(SignalDicomToDataManager(const QStringList&)),this,SLOT(OnViewButtonAddToDataManager(const QStringList&)));
connect(m_Controls.externalDataWidget,SIGNAL(SignalChangePage(int)), this, SLOT(OnChangePage(int)));
connect(m_Controls.internalDataWidget,SIGNAL(FinishedImport(const QString&)),this,SLOT(OnDicomImportFinished(const QString&)));
connect(m_Controls.internalDataWidget,SIGNAL(FinishedImport(const QStringList&)),this,SLOT(OnDicomImportFinished(const QStringList&)));
connect(m_Controls.internalDataWidget,SIGNAL(SignalDicomToDataManager(const QStringList&)),this,SLOT(OnViewButtonAddToDataManager(const QStringList&)));
connect(m_Controls.CDButton, SIGNAL(clicked()), m_Controls.externalDataWidget, SLOT(OnFolderCDImport()));
connect(m_Controls.FolderButton, SIGNAL(clicked()), m_Controls.externalDataWidget, SLOT(OnFolderCDImport()));
connect(m_Controls.QueryRetrieveButton, SIGNAL(clicked()), this, SLOT(OnQueryRetrieve()));
connect(m_Controls.LocalStorageButton, SIGNAL(clicked()), this, SLOT(OnLocalStorage()));
//connect(m_Controls.radioButton,SIGNAL(clicked()),this,SLOT(StartStopStoreSCP()));
}
void QmitkDicomEditor::Init(berry::IEditorSite::Pointer site, berry::IEditorInput::Pointer input)
{
this->SetSite(site);
this->SetInput(input);
}
void QmitkDicomEditor::SetFocus()
{
}
berry::IPartListener::Events::Types QmitkDicomEditor::GetPartEventTypes() const
{
return Events::CLOSED | Events::HIDDEN | Events::VISIBLE;
}
void QmitkDicomEditor::OnQueryRetrieve()
{
OnChangePage(2);
StartStopStoreSCP();
}
void QmitkDicomEditor::OnLocalStorage()
{
OnChangePage(0);
}
void QmitkDicomEditor::OnChangePage(int page)
{
try{
m_Controls.stackedWidget->setCurrentIndex(page);
}catch(std::exception e){
MITK_ERROR <<"error: "<< e.what();
return;
}
}
void QmitkDicomEditor::OnDicomImportFinished(const QString& path)
{
}
void QmitkDicomEditor::OnDicomImportFinished(const QStringList& path)
{
}
void QmitkDicomEditor::StartDicomDirectoryListener()
{
if(!m_Thread->isRunning())
{
m_DicomDirectoryListener->SetDicomListenerDirectory(*m_ListenerDirectory);
connect(m_DicomDirectoryListener,SIGNAL(SignalAddDicomData(const QStringList&)),m_Controls.internalDataWidget,SLOT(StartDicomImport(const QStringList&)),Qt::DirectConnection);
connect(m_Controls.internalDataWidget,SIGNAL(FinishedImport(const QStringList&)),m_DicomDirectoryListener,SLOT(OnDicomImportFinished(const QStringList&)),Qt::DirectConnection);
m_DicomDirectoryListener->moveToThread(m_Thread);
m_Thread->start();
}
}
//TODO Remove
void QmitkDicomEditor::TestHandler()
{
m_Handler = new DicomEventHandler();
m_Handler->SubscribeSlots();
}
void QmitkDicomEditor::OnViewButtonAddToDataManager(const QStringList& eventProperties)
{
ctkDictionary properties;
properties["PatientName"] = eventProperties.at(0);
properties["StudyUID"] = eventProperties.at(1);
properties["StudyName"] = eventProperties.at(2);
properties["SeriesUID"] = eventProperties.at(3);
properties["SeriesName"] = eventProperties.at(4);
properties["Path"] = eventProperties.at(5);
m_Publisher->PublishSignals(mitk::PluginActivator::getContext());
m_Publisher->AddSeriesToDataManagerEvent(properties);
}
void QmitkDicomEditor::StartStoreSCP()
{
QString storagePort = m_Controls.m_ctkDICOMQueryRetrieveWidget->getServerParameters()["StoragePort"].toString();
QString storageAET = m_Controls.m_ctkDICOMQueryRetrieveWidget->getServerParameters()["StorageAETitle"].toString();
builder.AddPort(storagePort)->AddAETitle(storageAET)->AddTransferSyntax()->AddOtherNetworkOptions()->AddMode()->AddOutputDirectory(*m_ListenerDirectory);
m_StoreSCPLauncher = new QmitkStoreSCPLauncher(&builder);
m_StoreSCPLauncher->StartStoreSCP();
m_Controls.radioButton->setChecked(true);
m_Controls.radioButton->setText(storageAET+QString(" ")+storagePort);
}
void QmitkDicomEditor::StopStoreSCP()
{
delete m_StoreSCPLauncher;
m_Controls.radioButton->setChecked(false);
m_Controls.radioButton->setText(QString("Storage service provider is not running!"));
}
void QmitkDicomEditor::StartStopStoreSCP()
{
QString storagePort = m_Controls.m_ctkDICOMQueryRetrieveWidget->getServerParameters()["StoragePort"].toString();
QString storageAET = m_Controls.m_ctkDICOMQueryRetrieveWidget->getServerParameters()["StorageAETitle"].toString();
if(!((builder.GetAETitle()->compare(storageAET,Qt::CaseSensitive)==0)&&
(builder.GetPort()->compare(storagePort,Qt::CaseSensitive)==0)))
{
if(m_Controls.radioButton->isChecked())
{
StopStoreSCP();
StartStoreSCP();
}else{
StartStoreSCP();
}
}
}
void QmitkDicomEditor::SetPluginDirectory()
{
mitk::PluginActivator::getContext()->getDataFile(*m_PluginDirectory);
m_PluginDirectory->append("/");
}
void QmitkDicomEditor::SetDatabaseDirectory(const QString& databaseDirectory)
{
m_DatabaseDirectory->clear();
m_DatabaseDirectory->append(m_PluginDirectory);
m_DatabaseDirectory->append(databaseDirectory);
m_Controls.internalDataWidget->SetDatabaseDirectory(*m_DatabaseDirectory);
}
void QmitkDicomEditor::SetListenerDirectory(const QString& listenerDirectory)
{
m_ListenerDirectory->clear();
m_ListenerDirectory->append(m_PluginDirectory);
m_ListenerDirectory->append(listenerDirectory);
}<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2015 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <chrono>
#include <map>
#include <optional>
#include <concepts>
#include <seastar/core/byteorder.hh>
#include <seastar/core/sstring.hh>
#include "seastarx.hh"
//
// This hashing differs from std::hash<> in that it decouples knowledge about
// type structure from the way the hash value is calculated:
// * appending_hash<T> instantiation knows about what data should be included in the hash for type T.
// * Hasher object knows how to combine the data into the final hash.
//
// The appending_hash<T> should always feed some data into the hasher, regardless of the state the object is in,
// in order for the hash to be highly sensitive for value changes. For example, vector<optional<T>> should
// ideally feed different values for empty vector and a vector with a single empty optional.
//
// appending_hash<T> is machine-independent.
//
template<typename H>
concept Hasher =
requires(H& h, const char* ptr, size_t size) {
{ h.update(ptr, size) } noexcept -> std::same_as<void>;
};
class hasher {
public:
virtual ~hasher() = default;
virtual void update(const char* ptr, size_t size) noexcept = 0;
};
static_assert(Hasher<hasher>);
template<typename T, typename Enable = void>
struct appending_hash;
template<typename H, typename T, typename... Args>
requires Hasher<H>
inline
void feed_hash(H& h, const T& value, Args&&... args) noexcept {
appending_hash<T>()(h, value, std::forward<Args>(args)...);
};
template<typename T>
struct appending_hash<T, std::enable_if_t<std::is_arithmetic<T>::value>> {
template<typename H>
requires Hasher<H>
void operator()(H& h, T value) const noexcept {
auto value_le = cpu_to_le(value);
h.update(reinterpret_cast<const char*>(&value_le), sizeof(T));
}
};
template<>
struct appending_hash<bool> {
template<typename H>
requires Hasher<H>
void operator()(H& h, bool value) const noexcept {
feed_hash(h, static_cast<uint8_t>(value));
}
};
template<typename T>
struct appending_hash<T, std::enable_if_t<std::is_enum<T>::value>> {
template<typename H>
requires Hasher<H>
void operator()(H& h, const T& value) const noexcept {
feed_hash(h, static_cast<std::underlying_type_t<T>>(value));
}
};
template<typename T>
struct appending_hash<std::optional<T>> {
template<typename H>
requires Hasher<H>
void operator()(H& h, const std::optional<T>& value) const noexcept {
if (value) {
feed_hash(h, true);
feed_hash(h, *value);
} else {
feed_hash(h, false);
}
}
};
template<size_t N>
struct appending_hash<char[N]> {
template<typename H>
requires Hasher<H>
void operator()(H& h, const char (&value) [N]) const noexcept {
feed_hash(h, N);
h.update(value, N);
}
};
template<typename T>
struct appending_hash<std::vector<T>> {
template<typename H>
requires Hasher<H>
void operator()(H& h, const std::vector<T>& value) const noexcept {
feed_hash(h, value.size());
for (auto&& v : value) {
appending_hash<T>()(h, v);
}
}
};
template<typename K, typename V>
struct appending_hash<std::map<K, V>> {
template<typename H>
requires Hasher<H>
void operator()(H& h, const std::map<K, V>& value) const noexcept {
feed_hash(h, value.size());
for (auto&& e : value) {
appending_hash<K>()(h, e.first);
appending_hash<V>()(h, e.second);
}
}
};
template<>
struct appending_hash<sstring> {
template<typename H>
requires Hasher<H>
void operator()(H& h, const sstring& v) const noexcept {
feed_hash(h, v.size());
h.update(reinterpret_cast<const char*>(v.cbegin()), v.size() * sizeof(sstring::value_type));
}
};
template<>
struct appending_hash<std::string> {
template<typename H>
requires Hasher<H>
void operator()(H& h, const std::string& v) const noexcept {
feed_hash(h, v.size());
h.update(reinterpret_cast<const char*>(v.data()), v.size() * sizeof(std::string::value_type));
}
};
template<typename T, typename R>
struct appending_hash<std::chrono::duration<T, R>> {
template<typename H>
requires Hasher<H>
void operator()(H& h, std::chrono::duration<T, R> v) const noexcept {
feed_hash(h, v.count());
}
};
template<typename Clock, typename Duration>
struct appending_hash<std::chrono::time_point<Clock, Duration>> {
template<typename H>
requires Hasher<H>
void operator()(H& h, std::chrono::time_point<Clock, Duration> v) const noexcept {
feed_hash(h, v.time_since_epoch().count());
}
};
<commit_msg>hashing: appending_hash: convert from enable_if to concepts<commit_after>/*
* Copyright (C) 2015 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <chrono>
#include <map>
#include <optional>
#include <concepts>
#include <seastar/core/byteorder.hh>
#include <seastar/core/sstring.hh>
#include "seastarx.hh"
//
// This hashing differs from std::hash<> in that it decouples knowledge about
// type structure from the way the hash value is calculated:
// * appending_hash<T> instantiation knows about what data should be included in the hash for type T.
// * Hasher object knows how to combine the data into the final hash.
//
// The appending_hash<T> should always feed some data into the hasher, regardless of the state the object is in,
// in order for the hash to be highly sensitive for value changes. For example, vector<optional<T>> should
// ideally feed different values for empty vector and a vector with a single empty optional.
//
// appending_hash<T> is machine-independent.
//
template<typename H>
concept Hasher =
requires(H& h, const char* ptr, size_t size) {
{ h.update(ptr, size) } noexcept -> std::same_as<void>;
};
class hasher {
public:
virtual ~hasher() = default;
virtual void update(const char* ptr, size_t size) noexcept = 0;
};
static_assert(Hasher<hasher>);
template<typename T>
struct appending_hash;
template<typename H, typename T, typename... Args>
requires Hasher<H>
inline
void feed_hash(H& h, const T& value, Args&&... args) noexcept {
appending_hash<T>()(h, value, std::forward<Args>(args)...);
};
template<typename T>
requires std::is_arithmetic_v<T>
struct appending_hash<T> {
template<typename H>
requires Hasher<H>
void operator()(H& h, T value) const noexcept {
auto value_le = cpu_to_le(value);
h.update(reinterpret_cast<const char*>(&value_le), sizeof(T));
}
};
template<>
struct appending_hash<bool> {
template<typename H>
requires Hasher<H>
void operator()(H& h, bool value) const noexcept {
feed_hash(h, static_cast<uint8_t>(value));
}
};
template<typename T>
requires std::is_enum_v<T>
struct appending_hash<T> {
template<typename H>
requires Hasher<H>
void operator()(H& h, const T& value) const noexcept {
feed_hash(h, static_cast<std::underlying_type_t<T>>(value));
}
};
template<typename T>
struct appending_hash<std::optional<T>> {
template<typename H>
requires Hasher<H>
void operator()(H& h, const std::optional<T>& value) const noexcept {
if (value) {
feed_hash(h, true);
feed_hash(h, *value);
} else {
feed_hash(h, false);
}
}
};
template<size_t N>
struct appending_hash<char[N]> {
template<typename H>
requires Hasher<H>
void operator()(H& h, const char (&value) [N]) const noexcept {
feed_hash(h, N);
h.update(value, N);
}
};
template<typename T>
struct appending_hash<std::vector<T>> {
template<typename H>
requires Hasher<H>
void operator()(H& h, const std::vector<T>& value) const noexcept {
feed_hash(h, value.size());
for (auto&& v : value) {
appending_hash<T>()(h, v);
}
}
};
template<typename K, typename V>
struct appending_hash<std::map<K, V>> {
template<typename H>
requires Hasher<H>
void operator()(H& h, const std::map<K, V>& value) const noexcept {
feed_hash(h, value.size());
for (auto&& e : value) {
appending_hash<K>()(h, e.first);
appending_hash<V>()(h, e.second);
}
}
};
template<>
struct appending_hash<sstring> {
template<typename H>
requires Hasher<H>
void operator()(H& h, const sstring& v) const noexcept {
feed_hash(h, v.size());
h.update(reinterpret_cast<const char*>(v.cbegin()), v.size() * sizeof(sstring::value_type));
}
};
template<>
struct appending_hash<std::string> {
template<typename H>
requires Hasher<H>
void operator()(H& h, const std::string& v) const noexcept {
feed_hash(h, v.size());
h.update(reinterpret_cast<const char*>(v.data()), v.size() * sizeof(std::string::value_type));
}
};
template<typename T, typename R>
struct appending_hash<std::chrono::duration<T, R>> {
template<typename H>
requires Hasher<H>
void operator()(H& h, std::chrono::duration<T, R> v) const noexcept {
feed_hash(h, v.count());
}
};
template<typename Clock, typename Duration>
struct appending_hash<std::chrono::time_point<Clock, Duration>> {
template<typename H>
requires Hasher<H>
void operator()(H& h, std::chrono::time_point<Clock, Duration> v) const noexcept {
feed_hash(h, v.time_since_epoch().count());
}
};
<|endoftext|>
|
<commit_before># pragma once
# include <Siv3D.hpp>
# include "AscChoiceManager.hpp"
# include "AscMessageManager.hpp"
# include "AscSoundManager.hpp"
# include "AscSpriteManager.hpp"
namespace asc
{
using namespace s3d;
using Commnad = std::pair<int32, String>;
class Novel
{
private:
bool m_isUpdating;
int32 m_currentLine;
int32 m_lastSeekPoint;
Array<Commnad> m_commands;
ChoiceManager m_choiceManager;
SoundManager m_soundManager;
MessageManager m_messageManager;
SpriteManager m_spriteManager;
void clearManager()
{
m_messageManager.clear();
m_spriteManager.clear();
m_choiceManager.clear();
}
void execute()
{
switch (m_commands[m_currentLine].first)
{
// Point
case 0:
m_isUpdating = false;
m_lastSeekPoint = Parse<int32>(m_commands[m_currentLine].second);
return;
// Text
case 1:
m_messageManager.setText(m_commands[m_currentLine].second);
m_messageManager.start();
break;
// Name
case 2:
m_messageManager.setName(m_commands[m_currentLine].second);
break;
// AddSprite
case 3:
m_spriteManager.add<Sprite>(m_commands[m_currentLine].second);
break;
// AddFixedSprite
case 4:
m_spriteManager.add<FixedSprite>(m_commands[m_currentLine].second);
break;
// Choice
case 5:
m_choiceManager.start(m_commands[m_currentLine].second);
break;
// Jump
case 6:
start(Parse<int32>(m_commands[m_currentLine].second));
return;
// AutomaticText
case 7:
m_messageManager.setText(m_commands[m_currentLine].second);
m_messageManager.start(true);
break;
default:
break;
}
m_currentLine++;
}
public:
Novel() :
m_isUpdating(false),
m_currentLine(0),
m_lastSeekPoint(-1),
m_messageManager(std::bind(&SoundManager::playCharSound, m_soundManager))
{
m_commands.push_back({ 0, L"1"});
m_commands.push_back({ 3, L"1,character1,0,0,640,720" });
m_commands.push_back({ 3, L"3,character3,480,180,320,360" });
m_commands.push_back({ 1, L"Characters" });
m_commands.push_back({ 0, L"2" });
m_commands.push_back({ 1, L"Only Text" });
m_commands.push_back({ 0, L"3" });
m_commands.push_back({ 7, L"Show Character?" });
m_commands.push_back({ 5, L"1,Yes,2,No" });
m_commands.push_back({ 0, L"4" });
m_commands.push_back({ 1, L"Jump 2" });
m_commands.push_back({ 6, L"2" });
m_commands.push_back({ 0, L"-1" });
}
virtual ~Novel() = default;
bool start(int32 seekPoint)
{
const auto size = m_commands.size() - 1;
for (auto i = 0u; i < size; i++)
{
const auto index = (m_currentLine + i) % m_commands.size();
const auto command = m_commands[index];
if (
command.first == 0 &&
Parse<int32>(command.second) == seekPoint
)
{
clearManager();
m_currentLine = index + 1;
m_isUpdating = true;
return true;
}
}
return false;
}
void update()
{
while (
m_isUpdating &&
!m_messageManager.isUpdating() &&
!m_choiceManager.isUpdating()
)
{
m_choiceManager.lastSelectedSeekPoint().then([&](int32 seekPoint){ start(seekPoint); });
execute();
}
m_messageManager.update();
m_choiceManager.update();
}
bool isUpdating() const
{
return m_isUpdating;
}
int32 seekPoint() const
{
return m_lastSeekPoint;
}
void draw() const
{
m_spriteManager.draw();
m_messageManager.draw();
m_choiceManager.draw();
}
};
}<commit_msg>SeekPoint is last started point.<commit_after># pragma once
# include <Siv3D.hpp>
# include "AscChoiceManager.hpp"
# include "AscMessageManager.hpp"
# include "AscSoundManager.hpp"
# include "AscSpriteManager.hpp"
namespace asc
{
using namespace s3d;
using Commnad = std::pair<int32, String>;
class Novel
{
private:
bool m_isUpdating;
int32 m_currentLine;
int32 m_lastSeekPoint;
Array<Commnad> m_commands;
ChoiceManager m_choiceManager;
SoundManager m_soundManager;
MessageManager m_messageManager;
SpriteManager m_spriteManager;
void clearManager()
{
m_messageManager.clear();
m_spriteManager.clear();
m_choiceManager.clear();
}
void execute()
{
switch (m_commands[m_currentLine].first)
{
// Point
case 0:
m_isUpdating = false;
return;
// Text
case 1:
m_messageManager.setText(m_commands[m_currentLine].second);
m_messageManager.start();
break;
// Name
case 2:
m_messageManager.setName(m_commands[m_currentLine].second);
break;
// AddSprite
case 3:
m_spriteManager.add<Sprite>(m_commands[m_currentLine].second);
break;
// AddFixedSprite
case 4:
m_spriteManager.add<FixedSprite>(m_commands[m_currentLine].second);
break;
// Choice
case 5:
m_choiceManager.start(m_commands[m_currentLine].second);
break;
// Jump
case 6:
start(Parse<int32>(m_commands[m_currentLine].second));
return;
// AutomaticText
case 7:
m_messageManager.setText(m_commands[m_currentLine].second);
m_messageManager.start(true);
break;
default:
break;
}
m_currentLine++;
}
public:
Novel() :
m_isUpdating(false),
m_currentLine(0),
m_lastSeekPoint(-1),
m_messageManager(std::bind(&SoundManager::playCharSound, m_soundManager))
{
m_commands.push_back({ 0, L"1"});
m_commands.push_back({ 3, L"1,character1,0,0,640,720" });
m_commands.push_back({ 3, L"3,character3,480,180,320,360" });
m_commands.push_back({ 1, L"Characters" });
m_commands.push_back({ 0, L"2" });
m_commands.push_back({ 1, L"Only Text" });
m_commands.push_back({ 0, L"3" });
m_commands.push_back({ 7, L"Show Character?" });
m_commands.push_back({ 5, L"1,Yes,2,No" });
m_commands.push_back({ 0, L"4" });
m_commands.push_back({ 1, L"Jump 2" });
m_commands.push_back({ 6, L"2" });
m_commands.push_back({ 0, L"-1" });
}
virtual ~Novel() = default;
bool start(int32 seekPoint)
{
const auto size = m_commands.size() - 1;
for (auto i = 0u; i < size; i++)
{
const auto index = (m_currentLine + i) % m_commands.size();
const auto command = m_commands[index];
if (
command.first == 0 &&
Parse<int32>(command.second) == seekPoint
)
{
clearManager();
m_currentLine = index + 1;
m_lastSeekPoint = seekPoint;
m_isUpdating = true;
return true;
}
}
return false;
}
void update()
{
while (
m_isUpdating &&
!m_messageManager.isUpdating() &&
!m_choiceManager.isUpdating()
)
{
m_choiceManager.lastSelectedSeekPoint().then([&](int32 seekPoint){ start(seekPoint); });
execute();
}
m_messageManager.update();
m_choiceManager.update();
}
bool isUpdating() const
{
return m_isUpdating;
}
int32 seekPoint() const
{
return m_lastSeekPoint;
}
void draw() const
{
m_spriteManager.draw();
m_messageManager.draw();
m_choiceManager.draw();
}
};
}<|endoftext|>
|
<commit_before>/*
* DbgCliTopic.cpp
*
* Created on: 11.02.2015
* Author: niklausd
*/
#include "DbgCliTopic.h"
#include <string.h>
#include <stdlib.h>
#ifdef ARDUINO
#include "Arduino.h"
#else
#include <stdio.h>
#endif
DbgCli_Topic::DbgCli_Topic(DbgCli_Node* parentNode, const char* nodeName, const char* helpText)
: DbgCli_Node(parentNode, nodeName, helpText)
, m_firstChild(0)
{ }
DbgCli_Topic::~DbgCli_Topic()
{
DbgCli_Node* next = m_firstChild;
while (0 != next)
{
DbgCli_Node* toBeDeleted = next;
delete next;
next = next->getNextSibling();
}
}
void DbgCli_Topic::addChildNode(DbgCli_Node* node)
{
if (0 == m_firstChild)
{
m_firstChild = node;
}
else
{
DbgCli_Node* next = m_firstChild;
while (0 != next->getNextSibling())
{
next = next->getNextSibling();
}
next->setNextSibling(node);
}
}
void DbgCli_Topic::removeChildNode(DbgCli_Node* node)
{
if (m_firstChild == node)
{
m_firstChild = node->getNextSibling();
}
else
{
DbgCli_Node* next = m_firstChild;
while ((next != 0) && (next->getNextSibling() != node))
{
next = next->getNextSibling();
}
if (next != 0)
{
next->setNextSibling(node->getNextSibling());
}
}
}
void DbgCli_Topic::printAllChildNodes()
{
#ifdef ARDUINO
Serial.print("Node ");
Serial.print(this->getNodeName());
Serial.print(": ");
Serial.println(this->getHelpText());
DbgCli_Node* tmpNode = this->getFirstChild();
if (0 != tmpNode)
{
Serial.print("Contains: ");
Serial.print(tmpNode->getNodeName());
tmpNode = tmpNode->getNextSibling();
while (0 != tmpNode)
{
Serial.print(", ");
Serial.print(tmpNode->getNodeName());
tmpNode = tmpNode->getNextSibling();
}
Serial.println(" ");
}
#else
printf("Node %s: %s\n", this->getNodeName(), this->getHelpText());
DbgCli_Node* tmpNode = this->getFirstChild();
if (0 != tmpNode)
{
printf("Contains: %s", tmpNode->getNodeName());
tmpNode = tmpNode->getNextSibling();
while (0 != tmpNode)
{
printf(", %s", tmpNode->getNodeName());
tmpNode = tmpNode->getNextSibling();
}
printf("\n");
}
#endif
}
DbgCli_Node* DbgCli_Topic::getChildNode(const char* nodeName)
{
bool found = false;
DbgCli_Node* tmpNode = m_firstChild;
while ((0 != tmpNode) && !found)
{
found = (strcmp(tmpNode->getNodeName(), nodeName) == 0);
if (!found)
{
tmpNode = tmpNode->getNextSibling();
}
}
return tmpNode;
}
DbgCli_Node* DbgCli_Topic::getFirstChild()
{
return m_firstChild;
}
void DbgCli_Topic::execute(unsigned int argc, const char** args, unsigned int idxToFirstArgToHandle)
{
if (idxToFirstArgToHandle < argc)
{
const char* nodeName = args[idxToFirstArgToHandle];
// #ifdef ARDUINO
// Serial.print("DbgCli_Topic::execute, curNodeName: ");
// Serial.print(this->getNodeName());
// Serial.print(", nodeName: ");
// Serial.println(nodeName);
// #else
// printf("DbgCli_Topic::execute, curNodeName: %s", this->getNodeName());
// printf(", nodeName: %s\n",nodeName);
// #endif
DbgCli_Node* tmpNode = this->getChildNode(nodeName); //get child or sibling with this nodeName
if (0 != tmpNode)
{
idxToFirstArgToHandle++;
tmpNode->execute(argc, args, idxToFirstArgToHandle);
}
else if (0==strcmp(DbgCli_Topic::RootNode()->getNodeName(),nodeName))
{
// root node was executed
this->printAllChildNodes();
}
else
{
// at least one node not found
#ifdef ARDUINO
Serial.print("Node or cmd \"");
Serial.print(nodeName);
Serial.println("\" not found!");
#else
printf("Node or cmd \"%s\" not found!\n", nodeName);
#endif
}
}
else
{ // at last node and its a topic
this->printAllChildNodes();
}
}
<commit_msg>fix silly mistake in DbgCli_Topic destructor<commit_after>/*
* DbgCliTopic.cpp
*
* Created on: 11.02.2015
* Author: niklausd
*/
#include "DbgCliTopic.h"
#include <string.h>
#include <stdlib.h>
#ifdef ARDUINO
#include "Arduino.h"
#else
#include <stdio.h>
#endif
DbgCli_Topic::DbgCli_Topic(DbgCli_Node* parentNode, const char* nodeName, const char* helpText)
: DbgCli_Node(parentNode, nodeName, helpText)
, m_firstChild(0)
{ }
DbgCli_Topic::~DbgCli_Topic()
{
DbgCli_Node* next = m_firstChild;
while (0 != next)
{
DbgCli_Node* toBeDeleted = next;
next = next->getNextSibling();
delete toBeDeleted;
toBeDeleted = 0;
}
}
void DbgCli_Topic::addChildNode(DbgCli_Node* node)
{
if (0 == m_firstChild)
{
m_firstChild = node;
}
else
{
DbgCli_Node* next = m_firstChild;
while (0 != next->getNextSibling())
{
next = next->getNextSibling();
}
next->setNextSibling(node);
}
}
void DbgCli_Topic::removeChildNode(DbgCli_Node* node)
{
if (m_firstChild == node)
{
m_firstChild = node->getNextSibling();
}
else
{
DbgCli_Node* next = m_firstChild;
while ((next != 0) && (next->getNextSibling() != node))
{
next = next->getNextSibling();
}
if (next != 0)
{
next->setNextSibling(node->getNextSibling());
}
}
}
void DbgCli_Topic::printAllChildNodes()
{
#ifdef ARDUINO
Serial.print("Node ");
Serial.print(this->getNodeName());
Serial.print(": ");
Serial.println(this->getHelpText());
DbgCli_Node* tmpNode = this->getFirstChild();
if (0 != tmpNode)
{
Serial.print("Contains: ");
Serial.print(tmpNode->getNodeName());
tmpNode = tmpNode->getNextSibling();
while (0 != tmpNode)
{
Serial.print(", ");
Serial.print(tmpNode->getNodeName());
tmpNode = tmpNode->getNextSibling();
}
Serial.println(" ");
}
#else
printf("Node %s: %s\n", this->getNodeName(), this->getHelpText());
DbgCli_Node* tmpNode = this->getFirstChild();
if (0 != tmpNode)
{
printf("Contains: %s", tmpNode->getNodeName());
tmpNode = tmpNode->getNextSibling();
while (0 != tmpNode)
{
printf(", %s", tmpNode->getNodeName());
tmpNode = tmpNode->getNextSibling();
}
printf("\n");
}
#endif
}
DbgCli_Node* DbgCli_Topic::getChildNode(const char* nodeName)
{
bool found = false;
DbgCli_Node* tmpNode = m_firstChild;
while ((0 != tmpNode) && !found)
{
found = (strcmp(tmpNode->getNodeName(), nodeName) == 0);
if (!found)
{
tmpNode = tmpNode->getNextSibling();
}
}
return tmpNode;
}
DbgCli_Node* DbgCli_Topic::getFirstChild()
{
return m_firstChild;
}
void DbgCli_Topic::execute(unsigned int argc, const char** args, unsigned int idxToFirstArgToHandle)
{
if (idxToFirstArgToHandle < argc)
{
const char* nodeName = args[idxToFirstArgToHandle];
// #ifdef ARDUINO
// Serial.print("DbgCli_Topic::execute, curNodeName: ");
// Serial.print(this->getNodeName());
// Serial.print(", nodeName: ");
// Serial.println(nodeName);
// #else
// printf("DbgCli_Topic::execute, curNodeName: %s", this->getNodeName());
// printf(", nodeName: %s\n",nodeName);
// #endif
DbgCli_Node* tmpNode = this->getChildNode(nodeName); //get child or sibling with this nodeName
if (0 != tmpNode)
{
idxToFirstArgToHandle++;
tmpNode->execute(argc, args, idxToFirstArgToHandle);
}
else if (0==strcmp(DbgCli_Topic::RootNode()->getNodeName(),nodeName))
{
// root node was executed
this->printAllChildNodes();
}
else
{
// at least one node not found
#ifdef ARDUINO
Serial.print("Node or cmd \"");
Serial.print(nodeName);
Serial.println("\" not found!");
#else
printf("Node or cmd \"%s\" not found!\n", nodeName);
#endif
}
}
else
{ // at last node and its a topic
this->printAllChildNodes();
}
}
<|endoftext|>
|
<commit_before>#include "Webclient.hpp"
Webclient::Webclient() :
curl(curl_easy_init())
{
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
curl_easy_setopt(curl, CURLOPT_MAXREDIRS, 10);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, Webclient::curlCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, this);
curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 2);
curl_easy_setopt(curl, CURLOPT_TIMEOUT, 10);
curl_easy_setopt(curl, CURLOPT_ACCEPT_ENCODING, "gzip");
curl_easy_setopt(curl, CURLOPT_USERAGENT, "GoogleLiteBot");
}
Webclient::~Webclient()
{
// Cleanup CURL
curl_easy_cleanup(curl);
}
std::string Webclient::getURL(std::string& url)
{
// Set the link
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
// Clear the current buffer
buffer.str("");
CURLcode res = curl_easy_perform(curl);
if (res != 0) {
CrawlException ex;
throw ex;
}
char* effectiveURL;
curl_easy_getinfo(curl, CURLINFO_EFFECTIVE_URL, &effectiveURL);
url = effectiveURL;
return buffer.str();
}
size_t Webclient::curlCallback(char* buffer, size_t size, size_t nmemb, Webclient* client)
{
const size_t real_size = size * nmemb;
client->buffer.write(buffer, real_size);
return real_size;
}
<commit_msg>Non-http 200 codes are now discarded.<commit_after>#include "Webclient.hpp"
Webclient::Webclient() :
curl(curl_easy_init())
{
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
curl_easy_setopt(curl, CURLOPT_MAXREDIRS, 10);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, Webclient::curlCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, this);
curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 2);
curl_easy_setopt(curl, CURLOPT_TIMEOUT, 10);
curl_easy_setopt(curl, CURLOPT_ACCEPT_ENCODING, "gzip");
curl_easy_setopt(curl, CURLOPT_USERAGENT, "MIRBot/1.0 - A robot made for a course at Leiden University - Abuse: l.j.peters@umail.leidenuniv.nl");
}
Webclient::~Webclient()
{
// Cleanup CURL
curl_easy_cleanup(curl);
}
std::string Webclient::getURL(std::string& url)
{
// Set the link
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
// Clear the current buffer
buffer.str("");
CURLcode res = curl_easy_perform(curl);
long http_code;
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_code);
if (res != 0 || http_code != 200) {
CrawlException ex;
throw ex;
}
char* effectiveURL;
curl_easy_getinfo(curl, CURLINFO_EFFECTIVE_URL, &effectiveURL);
url = effectiveURL;
return buffer.str();
}
size_t Webclient::curlCallback(char* buffer, size_t size, size_t nmemb, Webclient* client)
{
const size_t real_size = size * nmemb;
client->buffer.write(buffer, real_size);
return real_size;
}
<|endoftext|>
|
<commit_before>/*******************************************************************************
Licensed to the OpenCOR team under one or more contributor license agreements.
See the NOTICE.txt file distributed with this work for additional information
regarding copyright ownership. The OpenCOR team 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.
*******************************************************************************/
//==============================================================================
// CellML Model Repository widget
//==============================================================================
#include "cellmlmodelrepositorywindowwidget.h"
#include "corecliutils.h"
#include "coreguiutils.h"
//==============================================================================
#include "ui_cellmlmodelrepositorywindowwidget.h"
//==============================================================================
#include <QClipboard>
#include <QDesktopServices>
#include <QIODevice>
#include <QMenu>
#include <QPaintEvent>
#include <QRegularExpression>
#include <QWebElement>
#include <QWebFrame>
//==============================================================================
namespace OpenCOR {
namespace CellMLModelRepositoryWindow {
//==============================================================================
CellmlModelRepositoryWindowWidget::CellmlModelRepositoryWindowWidget(QWidget *pParent) :
Core::WebViewWidget(pParent),
Core::CommonWidget(pParent),
mGui(new Ui::CellmlModelRepositoryWindowWidget),
mModelNames(QStringList()),
mErrorMessage(QString()),
mNumberOfModels(0),
mNumberOfFilteredModels(0),
mLink(QString())
{
// Set up the GUI
mGui->setupUi(this);
// Add a small margin ourselves, so that no visual trace of the border drawn
// by drawBorder() in paintEvent() is left when scrolling (on Windows, but
// it doesn't harm doing it for all our supported platforms)
// Note: not sure why, but no matter how many pixels are specified for the
// margin, no margin actually exists, but it addresses the issue with
// the border drawn by drawBorder()...
setStyleSheet("QWebView {"
" margin: 1px;"
"}");
// Create and populate our context menu
mContextMenu = new QMenu(this);
mContextMenu->addAction(mGui->actionCopy);
// We want out own context menu
setContextMenuPolicy(Qt::CustomContextMenu);
connect(this, SIGNAL(customContextMenuRequested(const QPoint &)),
this, SLOT(showCustomContextMenu(const QPoint &)));
// Prevent objects from being dropped on us
setAcceptDrops(false);
// Have links opened in the user's browser rather than in our list
page()->setLinkDelegationPolicy(QWebPage::DelegateAllLinks);
// Some connections
connect(page(), SIGNAL(linkClicked(const QUrl &)),
this, SLOT(linkClicked(const QUrl &)));
// Retrieve the output template
Core::readTextFromFile(":/output.html", mOutputTemplate);
setHtml(mOutputTemplate.arg(Core::iconDataUri(":/oxygen/places/folder-downloads.png", 16, 16),
Core::iconDataUri(":/oxygen/places/folder-downloads.png", 16, 16, QIcon::Disabled)));
}
//==============================================================================
CellmlModelRepositoryWindowWidget::~CellmlModelRepositoryWindowWidget()
{
// Delete the GUI
delete mGui;
}
//==============================================================================
void CellmlModelRepositoryWindowWidget::retranslateUi()
{
// Retranslate our message
QWebElement messageElement = page()->mainFrame()->documentElement().findFirst("p[id=message]");
if (mErrorMessage.isEmpty()) {
if (!mNumberOfFilteredModels) {
if (!mNumberOfModels)
messageElement.removeAllChildren();
else
messageElement.setInnerXml(tr("No CellML model matches your criteria."));
} else if (mNumberOfFilteredModels == 1) {
messageElement.setInnerXml(tr("<strong>1</strong> CellML model was found:"));
} else {
messageElement.setInnerXml(tr("<strong>%1</strong> CellML models were found:").arg(mNumberOfFilteredModels));
}
} else {
messageElement.setInnerXml(tr("<strong>Error:</strong> ")+Core::formatMessage(mErrorMessage, true, true));
}
}
//==============================================================================
QSize CellmlModelRepositoryWindowWidget::sizeHint() const
{
// Suggest a default size for the CellML Model Repository widget
// Note: this is critical if we want a docked widget, with a CellML Model
// Repository widget on it, to have a decent size when docked to the
// main window...
return defaultSize(0.15);
}
//==============================================================================
void CellmlModelRepositoryWindowWidget::paintEvent(QPaintEvent *pEvent)
{
// Default handling of the event
QWebView::paintEvent(pEvent);
// Draw a border
drawBorder(
#if defined(Q_OS_WIN) || defined(Q_OS_LINUX)
true, true, true, true,
#elif defined(Q_OS_MAC)
true, false, false, false,
#else
#error Unsupported platform
#endif
true, false, false, false
);
}
//==============================================================================
void CellmlModelRepositoryWindowWidget::initialize(const QStringList &pModelNames,
const QStringList &pModelUrls,
const QString &pErrorMessage)
{
// Keep track of some properties
mModelNames = pModelNames;
mErrorMessage = pErrorMessage;
// Initialise our list of models, unless an error occurred
if (pErrorMessage.isEmpty()) {
mNumberOfModels = pModelNames.count();
if (mNumberOfModels) {
QString models = QString();
for (int i = 0; i < mNumberOfModels; ++i) {
models = models
+"<tr id=\"model_"+QString::number(i)+"\">\n"
+" <td>\n"
+" <ul>\n"
+" <li>\n"
+" <a href=\""+pModelUrls[i]+"\">"+pModelNames[i]+"</a>\n"
+" </li>\n"
+" </ul>\n"
+" </td>\n"
+" <td class=\"button\">\n"
+" <a class=\"noHover\" href=\""+pModelUrls[i]+"\"><img class=\"button clone\"/></a>\n"
+" </td>\n"
+"</tr>\n";
}
QWebElement modelsElement = page()->mainFrame()->documentElement().findFirst("tbody");
modelsElement.removeAllChildren();
modelsElement.appendInside(models);
}
}
}
//==============================================================================
void CellmlModelRepositoryWindowWidget::filter(const QString &pFilter)
{
// Make sure that we have something to filter (i.e. no error message)
if (!mErrorMessage.isEmpty())
return;
// Filter our list of models, remove duplicates (they will be reintroduced
// in the next step) and update our message (by retranslate ourselves)
QStringList filteredModelNames = mModelNames.filter(QRegularExpression(pFilter, QRegularExpression::CaseInsensitiveOption));
mNumberOfFilteredModels = filteredModelNames.count();
filteredModelNames.removeDuplicates();
retranslateUi();
// Determine which models should be shown/hidden
QIntList modelIndexes = QIntList();
int modelIndex;
foreach (const QString &filteredModelName, filteredModelNames) {
modelIndex = -1;
forever {
modelIndex = mModelNames.indexOf(filteredModelName, ++modelIndex);
if (modelIndex == -1)
break;
else
modelIndexes << modelIndex;
}
}
// Show/hide the relevant models
QWebElement documentElement = page()->mainFrame()->documentElement();
for (int i = 0, iMax = mModelNames.count(); i < iMax; ++i)
documentElement.findFirst(QString("tr[id=model_%1]").arg(i)).setStyleProperty("display", modelIndexes.contains(i)?"table-row":"none");
}
//==============================================================================
void CellmlModelRepositoryWindowWidget::on_actionCopy_triggered()
{
// Copy the URL of the model to the clipboard
QApplication::clipboard()->setText(mLink);
}
//==============================================================================
void CellmlModelRepositoryWindowWidget::linkClicked(const QUrl &pUrl)
{
// Retrieve some information about the link
QString textContent;
retrieveLinkInformation(mLink, textContent);
// Check whether we have clicked a model link or a button link, i.e. that we
// want to clone the model
if (textContent.isEmpty()) {
// We have clicked on a button link, so clone the model
qDebug(">>> Cloning %s...", qPrintable(mLink));
} else {
// Open the model link in the user's browser
QDesktopServices::openUrl(pUrl);
}
}
//==============================================================================
void CellmlModelRepositoryWindowWidget::showCustomContextMenu(const QPoint &pPosition)
{
Q_UNUSED(pPosition);
// Retrieve some information about the link, if any
QString textContent;
retrieveLinkInformation(mLink, textContent);
// Show our context menu to allow the copying of the URL of the model, but
// only if we are over a link, i.e. if both mLink and textContent are not
// empty
if (!mLink.isEmpty() && !textContent.isEmpty())
mContextMenu->exec(QCursor::pos());
}
//==============================================================================
} // namespace CellMLModelRepositoryWindow
} // namespace OpenCOR
//==============================================================================
// End of file
//==============================================================================
<commit_msg>PMR window: some work on allowing a workspace to be cloned (#593) [ci skip].<commit_after>/*******************************************************************************
Licensed to the OpenCOR team under one or more contributor license agreements.
See the NOTICE.txt file distributed with this work for additional information
regarding copyright ownership. The OpenCOR team 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.
*******************************************************************************/
//==============================================================================
// CellML Model Repository widget
//==============================================================================
#include "cellmlmodelrepositorywindowwidget.h"
#include "corecliutils.h"
#include "coreguiutils.h"
//==============================================================================
#include "ui_cellmlmodelrepositorywindowwidget.h"
//==============================================================================
#include <QClipboard>
#include <QDesktopServices>
#include <QIODevice>
#include <QMenu>
#include <QPaintEvent>
#include <QRegularExpression>
#include <QWebElement>
#include <QWebFrame>
//==============================================================================
namespace OpenCOR {
namespace CellMLModelRepositoryWindow {
//==============================================================================
CellmlModelRepositoryWindowWidget::CellmlModelRepositoryWindowWidget(QWidget *pParent) :
Core::WebViewWidget(pParent),
Core::CommonWidget(pParent),
mGui(new Ui::CellmlModelRepositoryWindowWidget),
mModelNames(QStringList()),
mErrorMessage(QString()),
mNumberOfModels(0),
mNumberOfFilteredModels(0),
mLink(QString())
{
// Set up the GUI
mGui->setupUi(this);
// Add a small margin ourselves, so that no visual trace of the border drawn
// by drawBorder() in paintEvent() is left when scrolling (on Windows and
// Linux, but it doesn't harm doing it for all our supported platforms)
// Note: not sure why, but no matter how many pixels are specified for the
// margin, no margin actually exists, but it addresses the issue with
// the border drawn by drawBorder()...
setStyleSheet("QWebView {"
" margin: 1px;"
"}");
// Create and populate our context menu
mContextMenu = new QMenu(this);
mContextMenu->addAction(mGui->actionCopy);
// We want out own context menu
setContextMenuPolicy(Qt::CustomContextMenu);
connect(this, SIGNAL(customContextMenuRequested(const QPoint &)),
this, SLOT(showCustomContextMenu(const QPoint &)));
// Prevent objects from being dropped on us
setAcceptDrops(false);
// Have links opened in the user's browser rather than in our list
page()->setLinkDelegationPolicy(QWebPage::DelegateAllLinks);
// Some connections
connect(page(), SIGNAL(linkClicked(const QUrl &)),
this, SLOT(linkClicked(const QUrl &)));
// Retrieve the output template
Core::readTextFromFile(":/output.html", mOutputTemplate);
setHtml(mOutputTemplate.arg(Core::iconDataUri(":/oxygen/places/folder-downloads.png", 16, 16),
Core::iconDataUri(":/oxygen/places/folder-downloads.png", 16, 16, QIcon::Disabled)));
}
//==============================================================================
CellmlModelRepositoryWindowWidget::~CellmlModelRepositoryWindowWidget()
{
// Delete the GUI
delete mGui;
}
//==============================================================================
void CellmlModelRepositoryWindowWidget::retranslateUi()
{
// Retranslate our message
QWebElement messageElement = page()->mainFrame()->documentElement().findFirst("p[id=message]");
if (mErrorMessage.isEmpty()) {
if (!mNumberOfFilteredModels) {
if (!mNumberOfModels)
messageElement.removeAllChildren();
else
messageElement.setInnerXml(tr("No CellML model matches your criteria."));
} else if (mNumberOfFilteredModels == 1) {
messageElement.setInnerXml(tr("<strong>1</strong> CellML model was found:"));
} else {
messageElement.setInnerXml(tr("<strong>%1</strong> CellML models were found:").arg(mNumberOfFilteredModels));
}
} else {
messageElement.setInnerXml(tr("<strong>Error:</strong> ")+Core::formatMessage(mErrorMessage, true, true));
}
}
//==============================================================================
QSize CellmlModelRepositoryWindowWidget::sizeHint() const
{
// Suggest a default size for the CellML Model Repository widget
// Note: this is critical if we want a docked widget, with a CellML Model
// Repository widget on it, to have a decent size when docked to the
// main window...
return defaultSize(0.15);
}
//==============================================================================
void CellmlModelRepositoryWindowWidget::paintEvent(QPaintEvent *pEvent)
{
// Default handling of the event
QWebView::paintEvent(pEvent);
// Draw a border
drawBorder(
#if defined(Q_OS_WIN) || defined(Q_OS_LINUX)
true, true, true, true,
#elif defined(Q_OS_MAC)
true, false, false, false,
#else
#error Unsupported platform
#endif
true, false, false, false
);
}
//==============================================================================
void CellmlModelRepositoryWindowWidget::initialize(const QStringList &pModelNames,
const QStringList &pModelUrls,
const QString &pErrorMessage)
{
// Keep track of some properties
mModelNames = pModelNames;
mErrorMessage = pErrorMessage;
// Initialise our list of models, unless an error occurred
if (pErrorMessage.isEmpty()) {
mNumberOfModels = pModelNames.count();
if (mNumberOfModels) {
QString models = QString();
for (int i = 0; i < mNumberOfModels; ++i) {
models = models
+"<tr id=\"model_"+QString::number(i)+"\">\n"
+" <td>\n"
+" <ul>\n"
+" <li>\n"
+" <a href=\""+pModelUrls[i]+"\">"+pModelNames[i]+"</a>\n"
+" </li>\n"
+" </ul>\n"
+" </td>\n"
+" <td class=\"button\">\n"
+" <a class=\"noHover\" href=\""+pModelUrls[i]+"\"><img class=\"button clone\"/></a>\n"
+" </td>\n"
+"</tr>\n";
}
QWebElement modelsElement = page()->mainFrame()->documentElement().findFirst("tbody");
modelsElement.removeAllChildren();
modelsElement.appendInside(models);
}
}
}
//==============================================================================
void CellmlModelRepositoryWindowWidget::filter(const QString &pFilter)
{
// Make sure that we have something to filter (i.e. no error message)
if (!mErrorMessage.isEmpty())
return;
// Filter our list of models, remove duplicates (they will be reintroduced
// in the next step) and update our message (by retranslate ourselves)
QStringList filteredModelNames = mModelNames.filter(QRegularExpression(pFilter, QRegularExpression::CaseInsensitiveOption));
mNumberOfFilteredModels = filteredModelNames.count();
filteredModelNames.removeDuplicates();
retranslateUi();
// Determine which models should be shown/hidden
QIntList modelIndexes = QIntList();
int modelIndex;
foreach (const QString &filteredModelName, filteredModelNames) {
modelIndex = -1;
forever {
modelIndex = mModelNames.indexOf(filteredModelName, ++modelIndex);
if (modelIndex == -1)
break;
else
modelIndexes << modelIndex;
}
}
// Show/hide the relevant models
QWebElement documentElement = page()->mainFrame()->documentElement();
for (int i = 0, iMax = mModelNames.count(); i < iMax; ++i)
documentElement.findFirst(QString("tr[id=model_%1]").arg(i)).setStyleProperty("display", modelIndexes.contains(i)?"table-row":"none");
}
//==============================================================================
void CellmlModelRepositoryWindowWidget::on_actionCopy_triggered()
{
// Copy the URL of the model to the clipboard
QApplication::clipboard()->setText(mLink);
}
//==============================================================================
void CellmlModelRepositoryWindowWidget::linkClicked(const QUrl &pUrl)
{
// Retrieve some information about the link
QString textContent;
retrieveLinkInformation(mLink, textContent);
// Check whether we have clicked a model link or a button link, i.e. that we
// want to clone the model
if (textContent.isEmpty()) {
// We have clicked on a button link, so clone the model
qDebug(">>> Cloning %s...", qPrintable(mLink));
} else {
// Open the model link in the user's browser
QDesktopServices::openUrl(pUrl);
}
}
//==============================================================================
void CellmlModelRepositoryWindowWidget::showCustomContextMenu(const QPoint &pPosition)
{
Q_UNUSED(pPosition);
// Retrieve some information about the link, if any
QString textContent;
retrieveLinkInformation(mLink, textContent);
// Show our context menu to allow the copying of the URL of the model, but
// only if we are over a link, i.e. if both mLink and textContent are not
// empty
if (!mLink.isEmpty() && !textContent.isEmpty())
mContextMenu->exec(QCursor::pos());
}
//==============================================================================
} // namespace CellMLModelRepositoryWindow
} // namespace OpenCOR
//==============================================================================
// End of file
//==============================================================================
<|endoftext|>
|
<commit_before>#pragma once
#include <string>
#include "blackhole/attribute.hpp"
#include "blackhole/expression/helper.hpp"
#include "blackhole/filter.hpp"
#include "blackhole/utils/underlying.hpp"
namespace blackhole {
namespace expression {
template<typename T, class = void>
struct get_attr_action_t {
typedef T result_type;
const std::string name;
const result_type& operator ()(const log::attributes_t& attributes) const {
return boost::get<T>(attributes.at(name).value);
}
filter_t operator ==(const T& other) const {
return aux::Eq<get_attr_action_t<T>>({ *this, other });
}
filter_t operator <(const T& other) const {
return aux::Less<get_attr_action_t<T>>({ *this, other });
}
};
template<typename T>
struct get_attr_action_t<T, typename std::enable_if<std::is_enum<T>::value>::type> {
typedef typename blackhole::aux::underlying_type<T>::type underlying_type;
typedef T result_type;
const std::string name;
result_type operator ()(const log::attributes_t& attributes) const {
return static_cast<result_type>(boost::get<underlying_type>(attributes.at(name).value));
}
filter_t operator ==(const T& other) const {
return aux::Eq<get_attr_action_t<T>>({ *this, other });
}
filter_t operator <(const T& other) const {
return aux::Less<get_attr_action_t<T>>({ *this, other });
}
};
template<typename T>
get_attr_action_t<T> get_attr(const std::string& name) {
return get_attr_action_t<T>({ name });
}
template<typename T>
get_attr_action_t<typename T::type> get_attr(const T&) {
return get_attr<typename T::type>(std::string(T::name()));
}
} // namespace expression
} // namespace blackhole
<commit_msg>Minor refactoring.<commit_after>#pragma once
#include <string>
#include "blackhole/attribute.hpp"
#include "blackhole/expression/helper.hpp"
#include "blackhole/filter.hpp"
#include "blackhole/utils/underlying.hpp"
namespace blackhole {
namespace expression {
template<typename T, class = void>
struct get_attr_action_t {
typedef T result_type;
const std::string name;
result_type operator ()(const log::attributes_t& attributes) const {
return attribute::traits<T>::extract(attributes, name);
}
filter_t operator ==(const T& other) const {
return aux::Eq<get_attr_action_t<T>>({ *this, other });
}
filter_t operator <(const T& other) const {
return aux::Less<get_attr_action_t<T>>({ *this, other });
}
};
template<typename T>
struct get_attr_action_t<T, typename std::enable_if<std::is_enum<T>::value>::type> {
typedef T result_type;
typedef typename blackhole::aux::underlying_type<T>::type underlying_type;
const std::string name;
result_type operator ()(const log::attributes_t& attributes) const {
return attribute::traits<T>::extract(attributes, name);
}
filter_t operator ==(const T& other) const {
return aux::Eq<get_attr_action_t<T>>({ *this, other });
}
filter_t operator <(const T& other) const {
return aux::Less<get_attr_action_t<T>>({ *this, other });
}
};
template<typename T>
get_attr_action_t<T> get_attr(const std::string& name) {
return get_attr_action_t<T>({ name });
}
template<typename T>
get_attr_action_t<typename T::type> get_attr(const T&) {
return get_attr<typename T::type>(std::string(T::name()));
}
} // namespace expression
} // namespace blackhole
<|endoftext|>
|
<commit_before>#include "../../lower_triangular_solve.hxx"
#include "../../SDP_Solver.hxx"
#include "../../../Timers.hxx"
// Compute the quantities needed to solve the Schur complement
// equation
//
// {{S, -B}, {B^T, 0}} . {dx, dy} = {r, s}
//
// (where S = SchurComplement, B = FreeVarMatrix), using the method
// described in the manual:
//
// - Compute S using BilinearPairingsXInv and BilinearPairingsY.
//
// - Compute the Cholesky decomposition S' = L' L'^T.
//
// - Form B' = (B U) and compute
//
// - SchurOffDiagonal = L'^{-1} B
// - L'^{-1} U
// - Q = (L'^{-1} B')^T (L'^{-1} B') - {{0, 0}, {0, 1}}
//
// - Compute the LU decomposition of Q.
//
// This data is sufficient to efficiently solve the above equation for
// a given r,s.
//
// Inputs:
// - BilinearPairingsXInv, BilinearPairingsY (these are members of
// SDPSolver, but we include them as arguments to emphasize that
// they must be computed first)
// Workspace (members of SDPSolver which are modified by this method
// and not used later):
// - SchurComplement
// Outputs (members of SDPSolver which are modified by this method and
// used later):
// - SchurComplementCholesky
// - SchurOffDiagonal
//
void compute_schur_complement(
const SDP &sdp, const Block_Diagonal_Matrix &bilinear_pairings_X_inv,
const Block_Diagonal_Matrix &bilinear_pairings_Y,
Block_Diagonal_Matrix &schur_complement);
void SDP_Solver::initialize_schur_complement_solver(
const Block_Diagonal_Matrix &bilinear_pairings_X_inv,
const Block_Diagonal_Matrix &bilinear_pairings_Y,
const std::vector<size_t> &block_sizes,
const std::vector<size_t> &block_indices, const size_t &num_schur_blocks,
const El::Grid &block_grid, const bool &debug,
Block_Diagonal_Matrix &schur_complement_cholesky,
Block_Matrix &schur_off_diagonal_block, El::DistMatrix<El::BigFloat> &Q)
{
// The Schur complement matrix S: a Block_Diagonal_Matrix with one
// block for each 0 <= j < J. SchurComplement.blocks[j] has dimension
// (d_j+1)*m_j*(m_j+1)/2
//
Block_Diagonal_Matrix schur_complement(block_sizes, block_indices,
num_schur_blocks, block_grid);
compute_schur_complement(sdp, bilinear_pairings_X_inv, bilinear_pairings_Y,
schur_complement);
// compute SchurComplementCholesky = L', where
//
// L' L'^T = S'
//
if(debug)
{
El::Output(
El::mpi::Rank(),
" run.step.initializeSchurComplementSolver.choleskyDecomposition");
}
timers["run.step.initializeSchurComplementSolver.choleskyDecomposition"]
.resume();
cholesky_decomposition(schur_complement, schur_complement_cholesky);
timers["run.step.initializeSchurComplementSolver.choleskyDecomposition"]
.stop();
// SchurOffDiagonal = L'^{-1} FreeVarMatrix
schur_off_diagonal_block = sdp.free_var_matrix;
if(debug)
{
El::Output(El::mpi::Rank(), " run.step.initializeSchurComplementSolver."
"blockMatrixLowerTriangularSolve");
}
timers["run.step.initializeSchurComplementSolver."
"blockMatrixLowerTriangularSolve"]
.resume();
lower_triangular_solve(schur_complement_cholesky, schur_off_diagonal_block);
timers["run.step.initializeSchurComplementSolver."
"blockMatrixLowerTriangularSolve"]
.stop();
// Next, we compute
//
// Q = (L'^{-1} B')^T (L'^{-1} B') - {{0, 0}, {0, 1}}
//
// Where B' = (B U). We think of Q as containing four blocks called
// Upper/Lower-Left/Right.
if(debug)
{
El::Output(El::mpi::Rank(),
" run.step.initializeSchurComplementSolver.Qcomputation");
}
timers["run.step.initializeSchurComplementSolver.Qcomputation"].resume();
{
// FIXME: This breaks if no blocks are assigned to this processor
El::DistMatrix<El::BigFloat> Q_local(
Q.Height(), Q.Width(), schur_off_diagonal_block.blocks.front().Grid());
El::Zero(Q_local);
for(auto &block : schur_off_diagonal_block.blocks)
{
El::DistMatrix<El::BigFloat> Q_local_view(
El::View(Q_local, 0, 0, block.Width(), block.Width()));
El::Syrk(El::UpperOrLowerNS::UPPER, El::OrientationNS::TRANSPOSE,
El::BigFloat(1), block, El::BigFloat(1), Q_local_view);
}
El::MakeSymmetric(El::UpperOrLower::UPPER, Q_local);
El::AllReduce(Q_local, El::mpi::COMM_WORLD);
for(int64_t row = 0; row < Q.LocalHeight(); ++row)
{
int64_t global_row(Q.GlobalRow(row));
for(int64_t column = 0; column < Q.LocalWidth(); ++column)
{
int64_t global_column(Q.GlobalCol(column));
// FIXME: This assumes that there is one process per block.
Q.SetLocal(row, column,
Q_local.GetLocal(global_row, global_column));
}
}
}
timers["run.step.initializeSchurComplementSolver.Qcomputation"].stop();
if(debug)
{
El::Output(El::mpi::Rank(),
" run.step.initializeSchurComplementSolver.LUDecomposition");
}
timers["run.step.initializeSchurComplementSolver.LUDecomposition"].resume();
Cholesky(El::UpperOrLowerNS::LOWER, Q);
timers["run.step.initializeSchurComplementSolver.LUDecomposition"].stop();
}
<commit_msg>Make a local copy of Cholesky(Q)<commit_after>#include "../../lower_triangular_solve.hxx"
#include "../../SDP_Solver.hxx"
#include "../../../Timers.hxx"
// Compute the quantities needed to solve the Schur complement
// equation
//
// {{S, -B}, {B^T, 0}} . {dx, dy} = {r, s}
//
// (where S = SchurComplement, B = FreeVarMatrix), using the method
// described in the manual:
//
// - Compute S using BilinearPairingsXInv and BilinearPairingsY.
//
// - Compute the Cholesky decomposition S' = L' L'^T.
//
// - Form B' = (B U) and compute
//
// - SchurOffDiagonal = L'^{-1} B
// - L'^{-1} U
// - Q = (L'^{-1} B')^T (L'^{-1} B') - {{0, 0}, {0, 1}}
//
// - Compute the LU decomposition of Q.
//
// This data is sufficient to efficiently solve the above equation for
// a given r,s.
//
// Inputs:
// - BilinearPairingsXInv, BilinearPairingsY (these are members of
// SDPSolver, but we include them as arguments to emphasize that
// they must be computed first)
// Workspace (members of SDPSolver which are modified by this method
// and not used later):
// - SchurComplement
// Outputs (members of SDPSolver which are modified by this method and
// used later):
// - SchurComplementCholesky
// - SchurOffDiagonal
//
void compute_schur_complement(
const SDP &sdp, const Block_Diagonal_Matrix &bilinear_pairings_X_inv,
const Block_Diagonal_Matrix &bilinear_pairings_Y,
Block_Diagonal_Matrix &schur_complement);
void SDP_Solver::initialize_schur_complement_solver(
const Block_Diagonal_Matrix &bilinear_pairings_X_inv,
const Block_Diagonal_Matrix &bilinear_pairings_Y,
const std::vector<size_t> &block_sizes,
const std::vector<size_t> &block_indices, const size_t &num_schur_blocks,
const El::Grid &block_grid, const bool &debug,
Block_Diagonal_Matrix &schur_complement_cholesky,
Block_Matrix &schur_off_diagonal_block, El::DistMatrix<El::BigFloat> &Q)
{
// The Schur complement matrix S: a Block_Diagonal_Matrix with one
// block for each 0 <= j < J. SchurComplement.blocks[j] has dimension
// (d_j+1)*m_j*(m_j+1)/2
//
Block_Diagonal_Matrix schur_complement(block_sizes, block_indices,
num_schur_blocks, block_grid);
compute_schur_complement(sdp, bilinear_pairings_X_inv, bilinear_pairings_Y,
schur_complement);
// compute SchurComplementCholesky = L', where
//
// L' L'^T = S'
//
if(debug)
{
El::Output(
El::mpi::Rank(),
" run.step.initializeSchurComplementSolver.choleskyDecomposition");
}
timers["run.step.initializeSchurComplementSolver.choleskyDecomposition"]
.resume();
cholesky_decomposition(schur_complement, schur_complement_cholesky);
timers["run.step.initializeSchurComplementSolver.choleskyDecomposition"]
.stop();
// SchurOffDiagonal = L'^{-1} FreeVarMatrix
schur_off_diagonal_block = sdp.free_var_matrix;
if(debug)
{
El::Output(El::mpi::Rank(), " run.step.initializeSchurComplementSolver."
"blockMatrixLowerTriangularSolve");
}
timers["run.step.initializeSchurComplementSolver."
"blockMatrixLowerTriangularSolve"]
.resume();
lower_triangular_solve(schur_complement_cholesky, schur_off_diagonal_block);
timers["run.step.initializeSchurComplementSolver."
"blockMatrixLowerTriangularSolve"]
.stop();
// Next, we compute
//
// Q = (L'^{-1} B')^T (L'^{-1} B') - {{0, 0}, {0, 1}}
//
// Where B' = (B U). We think of Q as containing four blocks called
// Upper/Lower-Left/Right.
if(debug)
{
El::Output(El::mpi::Rank(),
" run.step.initializeSchurComplementSolver.Q_Syrk");
}
timers["run.step.initializeSchurComplementSolver.Q_Syrk"].resume();
// FIXME: This breaks if no blocks are assigned to this processor
El::DistMatrix<El::BigFloat> Q_local(
Q.Height(), Q.Width(), schur_off_diagonal_block.blocks.front().Grid());
El::Zero(Q_local);
for(auto &block : schur_off_diagonal_block.blocks)
{
El::DistMatrix<El::BigFloat> Q_local_view(
El::View(Q_local, 0, 0, block.Width(), block.Width()));
El::Syrk(El::UpperOrLowerNS::UPPER, El::OrientationNS::TRANSPOSE,
El::BigFloat(1), block, El::BigFloat(1), Q_local_view);
}
El::MakeSymmetric(El::UpperOrLower::UPPER, Q_local);
El::AllReduce(Q_local, El::mpi::COMM_WORLD);
for(int64_t row = 0; row < Q.LocalHeight(); ++row)
{
int64_t global_row(Q.GlobalRow(row));
for(int64_t column = 0; column < Q.LocalWidth(); ++column)
{
int64_t global_column(Q.GlobalCol(column));
// FIXME: This assumes that there is one process per block.
Q.SetLocal(row, column, Q_local.GetLocal(global_row, global_column));
}
}
timers["run.step.initializeSchurComplementSolver.Q_Syrk"].stop();
if(debug)
{
El::Output(El::mpi::Rank(),
" run.step.initializeSchurComplementSolver.Q_Cholesky");
}
timers["run.step.initializeSchurComplementSolver.Q_Cholesky"].resume();
Cholesky(El::UpperOrLowerNS::LOWER, Q);
timers["run.step.initializeSchurComplementSolver.Q_Cholesky"].stop();
if(debug)
{
El::Output(El::mpi::Rank(),
" run.step.initializeSchurComplementSolver.Q_copy");
}
timers["run.step.initializeSchurComplementSolver.Q_copy"].resume();
Q.ReservePulls(Q_local.LocalHeight() * Q_local.LocalWidth());
for(int64_t row = 0; row < Q_local.LocalHeight(); ++row)
{
int64_t global_row(Q_local.GlobalRow(row));
for(int64_t column = 0; column < Q_local.LocalWidth(); ++column)
{
int64_t global_column(Q_local.GlobalCol(column));
Q.QueuePull(global_row, global_column);
}
}
std::vector<El::BigFloat> pulls;
Q.ProcessPullQueue(pulls);
auto pull(pulls.begin());
for(int64_t row = 0; row < Q_local.LocalHeight(); ++row)
{
for(int64_t column = 0; column < Q_local.LocalWidth(); ++column)
{
Q_local.SetLocal(row, column, *pull);
++pull;
}
}
timers["run.step.initializeSchurComplementSolver.Q_copy"].stop();
}
<|endoftext|>
|
<commit_before>#include <algorithm>
#include <iostream>
#include <string>
#include <boost/program_options.hpp>
#include <plasp/LanguageDetection.h>
#include <plasp/pddl/Description.h>
#include <plasp/pddl/TranslatorASP.h>
#include <plasp/sas/Description.h>
#include <plasp/sas/TranslatorASP.h>
#include <plasp/utils/LogStream.h>
#include <plasp/utils/TranslatorException.h>
int main(int argc, char **argv)
{
namespace po = boost::program_options;
po::options_description description("Allowed options");
description.add_options()
("help,h", "Display this help message.")
("version,v", "Display version information.")
("input,i", po::value<std::vector<std::string>>(), "Specify the PDDL or SAS input file.")
("language,l", po::value<std::string>(), "Specify the input language (sas or pddl). Omit for automatic detection.")
("warning-level", po::value<std::string>()->default_value("normal"), "Specify whether to output warnings normally (normal), to treat them as critical errors (error), or to ignore them (ignore).")
("color", po::value<std::string>()->default_value("auto"), "Specify whether to colorize the output (always, never, or auto).");
po::positional_options_description positionalOptionsDescription;
positionalOptionsDescription.add("input", -1);
po::variables_map variablesMap;
const auto printHelp =
[&]()
{
std::cout << "Usage: plasp [files] [options]" << std::endl;
std::cout << "Translate PDDL instances to ASP facts." << std::endl << std::endl;
std::cout << description;
};
plasp::utils::Logger logger;
try
{
po::store(po::command_line_parser(argc, argv)
.options(description)
.positional(positionalOptionsDescription)
.run(),
variablesMap);
po::notify(variablesMap);
}
catch (const po::error &e)
{
logger.logError(e.what());
std::cout << std::endl;
printHelp();
return EXIT_FAILURE;
}
if (variablesMap.count("help"))
{
printHelp();
return EXIT_SUCCESS;
}
if (variablesMap.count("version"))
{
std::cout << "plasp version 3.0.1-git" << std::endl;
return EXIT_SUCCESS;
}
const auto warningLevel = variablesMap["warning-level"].as<std::string>();
if (warningLevel == "error")
logger.setWarningLevel(plasp::utils::Logger::WarningLevel::Error);
else if (warningLevel == "ignore")
logger.setWarningLevel(plasp::utils::Logger::WarningLevel::Ignore);
else if (warningLevel == "normal")
logger.setWarningLevel(plasp::utils::Logger::WarningLevel::Normal);
else
{
logger.logError("unknown warning level “" + warningLevel + "”");
std::cout << std::endl;
printHelp();
return EXIT_FAILURE;
}
const auto colorPolicy = variablesMap["color"].as<std::string>();
if (colorPolicy == "auto")
logger.setColorPolicy(plasp::utils::LogStream::ColorPolicy::Auto);
else if (colorPolicy == "never")
logger.setColorPolicy(plasp::utils::LogStream::ColorPolicy::Never);
else if (colorPolicy == "always")
logger.setColorPolicy(plasp::utils::LogStream::ColorPolicy::Always);
else
{
logger.logError("unknown color policy “" + colorPolicy + "”");
std::cout << std::endl;
printHelp();
return EXIT_FAILURE;
}
try
{
plasp::utils::Parser<plasp::utils::CaseInsensitiveParserPolicy> parser;
if (variablesMap.count("input"))
{
const auto &inputFiles = variablesMap["input"].as<std::vector<std::string>>();
std::for_each(inputFiles.cbegin(), inputFiles.cend(),
[&](const auto &inputFile)
{
parser.read(inputFile);
});
}
else
parser.read("std::cin", std::cin);
const auto detectLanguage =
[&]()
{
if (variablesMap.count("language") == 0)
return plasp::detectLanguage(parser);
const auto languageName = variablesMap["language"].as<std::string>();
return plasp::Language::fromString(languageName);
};
const auto language = detectLanguage();
if (language == plasp::Language::Type::Unknown)
{
logger.logError("unknown input language");
std::cout << std::endl;
printHelp();
return EXIT_FAILURE;
}
if (language == plasp::Language::Type::PDDL)
{
auto pddlLogger = logger;
auto context = plasp::pddl::Context(std::move(parser), std::move(pddlLogger));
auto description = plasp::pddl::Description::fromContext(std::move(context));
const auto translator = plasp::pddl::TranslatorASP(description, description.context().logger.outputStream());
translator.translate();
}
else if (language == plasp::Language::Type::SAS)
{
const auto description = plasp::sas::Description::fromParser(std::move(parser));
const auto translator = plasp::sas::TranslatorASP(description, logger.outputStream());
translator.translate();
}
}
catch (const plasp::utils::ParserException &e)
{
logger.logError(e.coordinate(), e.message());
return EXIT_FAILURE;
}
catch (const plasp::utils::TranslatorException &e)
{
logger.logError(e.what());
return EXIT_FAILURE;
}
catch (const std::exception &e)
{
logger.logError(e.what());
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
<commit_msg>Version bump for release 3.0.2 RC 1.<commit_after>#include <algorithm>
#include <iostream>
#include <string>
#include <boost/program_options.hpp>
#include <plasp/LanguageDetection.h>
#include <plasp/pddl/Description.h>
#include <plasp/pddl/TranslatorASP.h>
#include <plasp/sas/Description.h>
#include <plasp/sas/TranslatorASP.h>
#include <plasp/utils/LogStream.h>
#include <plasp/utils/TranslatorException.h>
int main(int argc, char **argv)
{
namespace po = boost::program_options;
po::options_description description("Allowed options");
description.add_options()
("help,h", "Display this help message.")
("version,v", "Display version information.")
("input,i", po::value<std::vector<std::string>>(), "Specify the PDDL or SAS input file.")
("language,l", po::value<std::string>(), "Specify the input language (sas or pddl). Omit for automatic detection.")
("warning-level", po::value<std::string>()->default_value("normal"), "Specify whether to output warnings normally (normal), to treat them as critical errors (error), or to ignore them (ignore).")
("color", po::value<std::string>()->default_value("auto"), "Specify whether to colorize the output (always, never, or auto).");
po::positional_options_description positionalOptionsDescription;
positionalOptionsDescription.add("input", -1);
po::variables_map variablesMap;
const auto printHelp =
[&]()
{
std::cout << "Usage: plasp [files] [options]" << std::endl;
std::cout << "Translate PDDL instances to ASP facts." << std::endl << std::endl;
std::cout << description;
};
plasp::utils::Logger logger;
try
{
po::store(po::command_line_parser(argc, argv)
.options(description)
.positional(positionalOptionsDescription)
.run(),
variablesMap);
po::notify(variablesMap);
}
catch (const po::error &e)
{
logger.logError(e.what());
std::cout << std::endl;
printHelp();
return EXIT_FAILURE;
}
if (variablesMap.count("help"))
{
printHelp();
return EXIT_SUCCESS;
}
if (variablesMap.count("version"))
{
std::cout << "plasp version 3.0.2-rc.1" << std::endl;
return EXIT_SUCCESS;
}
const auto warningLevel = variablesMap["warning-level"].as<std::string>();
if (warningLevel == "error")
logger.setWarningLevel(plasp::utils::Logger::WarningLevel::Error);
else if (warningLevel == "ignore")
logger.setWarningLevel(plasp::utils::Logger::WarningLevel::Ignore);
else if (warningLevel == "normal")
logger.setWarningLevel(plasp::utils::Logger::WarningLevel::Normal);
else
{
logger.logError("unknown warning level “" + warningLevel + "”");
std::cout << std::endl;
printHelp();
return EXIT_FAILURE;
}
const auto colorPolicy = variablesMap["color"].as<std::string>();
if (colorPolicy == "auto")
logger.setColorPolicy(plasp::utils::LogStream::ColorPolicy::Auto);
else if (colorPolicy == "never")
logger.setColorPolicy(plasp::utils::LogStream::ColorPolicy::Never);
else if (colorPolicy == "always")
logger.setColorPolicy(plasp::utils::LogStream::ColorPolicy::Always);
else
{
logger.logError("unknown color policy “" + colorPolicy + "”");
std::cout << std::endl;
printHelp();
return EXIT_FAILURE;
}
try
{
plasp::utils::Parser<plasp::utils::CaseInsensitiveParserPolicy> parser;
if (variablesMap.count("input"))
{
const auto &inputFiles = variablesMap["input"].as<std::vector<std::string>>();
std::for_each(inputFiles.cbegin(), inputFiles.cend(),
[&](const auto &inputFile)
{
parser.read(inputFile);
});
}
else
parser.read("std::cin", std::cin);
const auto detectLanguage =
[&]()
{
if (variablesMap.count("language") == 0)
return plasp::detectLanguage(parser);
const auto languageName = variablesMap["language"].as<std::string>();
return plasp::Language::fromString(languageName);
};
const auto language = detectLanguage();
if (language == plasp::Language::Type::Unknown)
{
logger.logError("unknown input language");
std::cout << std::endl;
printHelp();
return EXIT_FAILURE;
}
if (language == plasp::Language::Type::PDDL)
{
auto pddlLogger = logger;
auto context = plasp::pddl::Context(std::move(parser), std::move(pddlLogger));
auto description = plasp::pddl::Description::fromContext(std::move(context));
const auto translator = plasp::pddl::TranslatorASP(description, description.context().logger.outputStream());
translator.translate();
}
else if (language == plasp::Language::Type::SAS)
{
const auto description = plasp::sas::Description::fromParser(std::move(parser));
const auto translator = plasp::sas::TranslatorASP(description, logger.outputStream());
translator.translate();
}
}
catch (const plasp::utils::ParserException &e)
{
logger.logError(e.coordinate(), e.message());
return EXIT_FAILURE;
}
catch (const plasp::utils::TranslatorException &e)
{
logger.logError(e.what());
return EXIT_FAILURE;
}
catch (const std::exception &e)
{
logger.logError(e.what());
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: SlsGenericPageCache.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: pjunck $ $Date: 2004-10-28 13:28:20 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef SD_SLIDESORTER_GENERIC_PAGE_CACHE_HXX
#define SD_SLIDESORTER_GENERIC_PAGE_CACHE_HXX
#include "SlsQueueProcessor.hxx"
#include "view/SlsPageObjectViewObjectContact.hxx"
namespace sd { namespace slidesorter { namespace model {
class SlideSorterModel;
} } }
namespace sd { namespace slidesorter { namespace view {
class SlideSorterView;
} } }
namespace sd { namespace slidesorter { namespace cache {
template<class RequestData,
class CreationManager,
class BitmapCache,
class RequestQueue,
class CacheCompactionPolicy,
class QueueProcessor>
class GenericPageCache
{
public:
/** The page chache is created with references both to the view and the
model so that it can fill itself with requests for all or just the
visible pages.
*/
GenericPageCache (
view::SlideSorterView& rView,
model::SlideSorterModel& rModel,
sal_Int32 nMaximalCacheSize);
~GenericPageCache (void);
/** Request a preview bitmap for the specified page object in the
specified size. The returned bitmap may be preview of the preview,
i.e. either a scaled (up or down) version of a previous preview (of
the wrong size) or an empty bitmap. In this case a request for the
generation of a new preview is created and inserted into the request
queue. When the preview is available the page shape will be told to
paint itself again. When it then calls this method again if
receives the correctly sized preview bitmap.
@param rRequestData
This data is used to determine the preview.
@param rSize
The size of the requested preview bitmap.
@return
Returns a bitmap that is either empty, contains a scaled (up or
down) version or is the requested bitmap.
*/
BitmapEx GetPreviewBitmap (
RequestData& rRequestData,
const Size& rSize);
/** When the requested preview bitmap does not yet exist or is not
up-to-date then the rendering of one is scheduled. Otherwise this
method does nothing.
@param rRequestData
This data is used to determine the preview.
@param rSize
The size of the requested preview bitmap in pixel coordinates.
@param bMayBeUpToDate
This flag helps the method to determine whether an existing
preview that matches the request is up to date. If the caller
know that it is not then by passing <FALSE/> he tells us that we
do not have to check the up-to-date flag a second time. If
unsure pass <TRUE/>.
*/
void RequestPreviewBitmap (
RequestData& rRequestData,
const Size& rSize,
bool bMayBeUpToDate = true);
/** Tell the cache to replace the bitmap associated with the given
request data with a new one that reflects recent changes in the
content of the page object.
*/
void InvalidatePreviewBitmap (const RequestData& rRequestData);
/** Lower the priority with which the request associated with the given
data will be processed. Call this method when the visibility of a
page object changes (from visible to not visible) and the request
becomes a ahead-of-time request. When the request is already in the
lowest class it will be removed.
*/
void DecreaseRequestPriority (RequestData& rRequestData);
/** Move the request associated with the given data into a higher
priority class and increase its priority in that class above all
other elements in the class.
*/
void IncreaseRequestPriority (RequestData& rRequestData);
/** Call this method when a view-object-contact object is being deleted
and does not need (a) its current bitmap in the cache and (b) a
requested new bitmap.
*/
void ReleasePreviewBitmap (RequestData& rRequestData);
/** Call this method when all preview bitmaps have to be generated anew.
This is the case when the size of the page objects on the screen has
changed or when the model has changed.
*/
void InvalidateCache (void);
/** With the precious flag you can control whether a bitmap can be
removed or reduced in size to make room for other bitmaps or is so
precious that it will not be touched. A typical use is to set the
precious flag for exactly the visible pages.
*/
void SetPreciousFlag (RequestData& rRequestData, bool bIsPrecious);
private:
view::SlideSorterView& mrView;
model::SlideSorterModel& mrModel;
BitmapCache maBitmapCache;
RequestQueue maRequestQueue;
QueueProcessor* mpQueueProcessor;
const sal_Int32 mnMaximalCacheSize;
/** Remember whether the cache limit has been reached at least once
after a Clear() call. This is important because afterwards the
cache will be constantly at its limit of capacity. Therefore
requests with another than the highest priority class will not be
processed since the resulting preview bitmaps would be removed
shortly afterwards.
*/
bool mbLimitHasBeenReached;
};
//===== GenericPageCache =====================================================
template<class RequestData,
class CreationManager,
class BitmapCache,
class RequestQueue,
class CompactionPolicy,
class QueueProcessor>
GenericPageCache<
RequestData,
CreationManager,
BitmapCache,
RequestQueue,
CompactionPolicy, QueueProcessor
>::GenericPageCache (
view::SlideSorterView& rView,
model::SlideSorterModel& rModel,
sal_Int32 nMaximalCacheSize)
: mrView(rView),
mrModel(rModel),
maBitmapCache (),
maRequestQueue(),
mpQueueProcessor(
new QueueProcessor(mrView,maRequestQueue,maBitmapCache)),
mnMaximalCacheSize(nMaximalCacheSize),
mbLimitHasBeenReached (false)
{
}
template<class RequestData,
class CreationManager,
class BitmapCache,
class RequestQueue,
class CompactionPolicy,
class QueueProcessor>
GenericPageCache<
RequestData, CreationManager, BitmapCache, RequestQueue,
CompactionPolicy, QueueProcessor
>::~GenericPageCache (void)
{
OSL_TRACE("terminating thread %p", mpQueueProcessor);
mpQueueProcessor->Stop();
maRequestQueue.Clear();
mpQueueProcessor->Terminate();
// delete mpQueueProcessor;
OSL_TRACE("thread %p stopped and terminated", mpQueueProcessor);
}
template<class RequestData,
class CreationManager,
class BitmapCache,
class RequestQueue,
class CompactionPolicy,
class QueueProcessor>
BitmapEx GenericPageCache<
RequestData, CreationManager, BitmapCache, RequestQueue,
CompactionPolicy, QueueProcessor
>::GetPreviewBitmap (
RequestData& rRequestData,
const Size& rSize)
{
BitmapEx aPreview;
bool bMayBeUpToDate = true;
if (maBitmapCache.HasBitmap (rRequestData.GetPage()))
{
aPreview = maBitmapCache.GetBitmap (rRequestData.GetPage());
Size aBitmapSize (aPreview.GetSizePixel());
if (aBitmapSize != rSize)
{
// The bitmap has the wrong size.
DBG_ASSERT (rSize.Width() < 1000,
"GenericPageCache<>::GetPreviewBitmap(): bitmap requested with large width. This may indicate an error.");
// Scale the bitmap to the desired size when that is possible,
// i.e. the bitmap is not empty.
if (aBitmapSize.Width()>0 && aBitmapSize.Height()>0)
aPreview.Scale (rSize, BMP_SCALE_FAST);
}
bMayBeUpToDate = true;
}
else
bMayBeUpToDate = false;
// Request the creation of a correctly sized preview bitmap. We do this
// even when the size of the bitmap in the cache is correct because its
// content may be not up-to-date anymore.
RequestPreviewBitmap (rRequestData, rSize, bMayBeUpToDate);
return aPreview;
}
template<class RequestData,
class CreationManager,
class BitmapCache,
class RequestQueue,
class CompactionPolicy,
class QueueProcessor>
void GenericPageCache<
RequestData, CreationManager, BitmapCache, RequestQueue,
CompactionPolicy, QueueProcessor
>::RequestPreviewBitmap (
RequestData& rRequestData,
const Size& rSize,
bool bMayBeUpToDate)
{
const SdrPage* pPage = rRequestData.GetPage();
// Determine if the available bitmap is up to date.
bool bIsUpToDate = false;
if (bMayBeUpToDate)
bIsUpToDate = maBitmapCache.BitmapIsUpToDate (pPage);
if (bIsUpToDate)
{
BitmapEx aPreview (maBitmapCache.GetBitmap (pPage));
if (aPreview.GetSizePixel() != rSize)
bIsUpToDate = false;
}
if ( ! bIsUpToDate)
{
// No, the bitmap is not up-to-date. Request a new one.
int nPriorityClass = rRequestData.GetPageDescriptor().IsVisible() ? 0 : 1;
maRequestQueue.AddRequest (rRequestData, nPriorityClass);
mpQueueProcessor->Start (nPriorityClass);
}
// Reduce the cache size if it grew too large.
if (maBitmapCache.GetSize() > mnMaximalCacheSize)
{
mbLimitHasBeenReached = true;
CompactionPolicy()(maBitmapCache, mnMaximalCacheSize);
}
}
template<class RequestData,
class CreationManager,
class BitmapCache,
class RequestQueue,
class CompactionPolicy,
class QueueProcessor>
void GenericPageCache<
RequestData, CreationManager, BitmapCache, RequestQueue,
CompactionPolicy, QueueProcessor
>::InvalidatePreviewBitmap (const RequestData& rRequestData)
{
maBitmapCache.InvalidateBitmap (rRequestData.GetPage());
}
template<class RequestData,
class CreationManager,
class BitmapCache,
class RequestQueue,
class CompactionPolicy,
class QueueProcessor>
void GenericPageCache<
RequestData, CreationManager, BitmapCache, RequestQueue,
CompactionPolicy, QueueProcessor
>::DecreaseRequestPriority (RequestData& rRequestData)
{
if (mbLimitHasBeenReached)
maRequestQueue.RemoveRequest (rRequestData);
else
maRequestQueue.ChangePriorityClass (rRequestData,+1);
}
template<class RequestData,
class CreationManager,
class BitmapCache,
class RequestQueue,
class CompactionPolicy,
class QueueProcessor>
void GenericPageCache<
RequestData, CreationManager, BitmapCache, RequestQueue,
CompactionPolicy, QueueProcessor
>::IncreaseRequestPriority (RequestData& rRequestData)
{
maRequestQueue.ChangePriorityClass (rRequestData,-1);
}
template<class RequestData,
class CreationManager,
class BitmapCache,
class RequestQueue,
class CompactionPolicy,
class QueueProcessor>
void GenericPageCache<
RequestData, CreationManager, BitmapCache, RequestQueue,
CompactionPolicy, QueueProcessor
>::ReleasePreviewBitmap (RequestData& rRequestData)
{
mpQueueProcessor->RemoveRequest (rRequestData);
maRequestQueue.RemoveRequest (rRequestData);
// We do not relase the preview bitmap that is associated with the page
// of the given request data because this method is called when the
// request data, typically a view-object-contact object, is destroyed.
// The page object usually lives longer than that and thus the preview
// bitmap may be used later on.
// maBitmapCache.ReleaseBitmap (rRequestData);
}
template<class RequestData,
class RequestFactory,
class BitmapCache,
class RequestQueue,
class CompactionPolicy,
class QueueProcessor>
void GenericPageCache<
RequestData, RequestFactory, BitmapCache, RequestQueue,
CompactionPolicy, QueueProcessor
>::InvalidateCache (void)
{
// 1.) Stop the timer while the queues are being updated.
mpQueueProcessor->Stop();
// 2.) Clear the request queue of their current content.
maRequestQueue.Clear();
mbLimitHasBeenReached = false;
// 3.) Create the new requests for filling the cache with at least the
// visible previews.
RequestFactory()(mrModel, mrView,maRequestQueue);
// 4.) Start the timer again.
mpQueueProcessor->Start();
}
template<class RequestData,
class RequestFactory,
class BitmapCache,
class RequestQueue,
class CompactionPolicy,
class QueueProcessor>
void GenericPageCache<
RequestData, RequestFactory, BitmapCache, RequestQueue,
CompactionPolicy, QueueProcessor
>::SetPreciousFlag (RequestData& rRequestData, bool bIsPrecious)
{
maBitmapCache.SetPrecious (rRequestData.GetPage(), bIsPrecious);
}
} } } // end of namespace ::sd::slidesorter::cache
#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.4.328); FILE MERGED 2005/09/05 13:24:15 rt 1.4.328.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: SlsGenericPageCache.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: rt $ $Date: 2005-09-09 06:10:13 $
*
* 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_SLIDESORTER_GENERIC_PAGE_CACHE_HXX
#define SD_SLIDESORTER_GENERIC_PAGE_CACHE_HXX
#include "SlsQueueProcessor.hxx"
#include "view/SlsPageObjectViewObjectContact.hxx"
namespace sd { namespace slidesorter { namespace model {
class SlideSorterModel;
} } }
namespace sd { namespace slidesorter { namespace view {
class SlideSorterView;
} } }
namespace sd { namespace slidesorter { namespace cache {
template<class RequestData,
class CreationManager,
class BitmapCache,
class RequestQueue,
class CacheCompactionPolicy,
class QueueProcessor>
class GenericPageCache
{
public:
/** The page chache is created with references both to the view and the
model so that it can fill itself with requests for all or just the
visible pages.
*/
GenericPageCache (
view::SlideSorterView& rView,
model::SlideSorterModel& rModel,
sal_Int32 nMaximalCacheSize);
~GenericPageCache (void);
/** Request a preview bitmap for the specified page object in the
specified size. The returned bitmap may be preview of the preview,
i.e. either a scaled (up or down) version of a previous preview (of
the wrong size) or an empty bitmap. In this case a request for the
generation of a new preview is created and inserted into the request
queue. When the preview is available the page shape will be told to
paint itself again. When it then calls this method again if
receives the correctly sized preview bitmap.
@param rRequestData
This data is used to determine the preview.
@param rSize
The size of the requested preview bitmap.
@return
Returns a bitmap that is either empty, contains a scaled (up or
down) version or is the requested bitmap.
*/
BitmapEx GetPreviewBitmap (
RequestData& rRequestData,
const Size& rSize);
/** When the requested preview bitmap does not yet exist or is not
up-to-date then the rendering of one is scheduled. Otherwise this
method does nothing.
@param rRequestData
This data is used to determine the preview.
@param rSize
The size of the requested preview bitmap in pixel coordinates.
@param bMayBeUpToDate
This flag helps the method to determine whether an existing
preview that matches the request is up to date. If the caller
know that it is not then by passing <FALSE/> he tells us that we
do not have to check the up-to-date flag a second time. If
unsure pass <TRUE/>.
*/
void RequestPreviewBitmap (
RequestData& rRequestData,
const Size& rSize,
bool bMayBeUpToDate = true);
/** Tell the cache to replace the bitmap associated with the given
request data with a new one that reflects recent changes in the
content of the page object.
*/
void InvalidatePreviewBitmap (const RequestData& rRequestData);
/** Lower the priority with which the request associated with the given
data will be processed. Call this method when the visibility of a
page object changes (from visible to not visible) and the request
becomes a ahead-of-time request. When the request is already in the
lowest class it will be removed.
*/
void DecreaseRequestPriority (RequestData& rRequestData);
/** Move the request associated with the given data into a higher
priority class and increase its priority in that class above all
other elements in the class.
*/
void IncreaseRequestPriority (RequestData& rRequestData);
/** Call this method when a view-object-contact object is being deleted
and does not need (a) its current bitmap in the cache and (b) a
requested new bitmap.
*/
void ReleasePreviewBitmap (RequestData& rRequestData);
/** Call this method when all preview bitmaps have to be generated anew.
This is the case when the size of the page objects on the screen has
changed or when the model has changed.
*/
void InvalidateCache (void);
/** With the precious flag you can control whether a bitmap can be
removed or reduced in size to make room for other bitmaps or is so
precious that it will not be touched. A typical use is to set the
precious flag for exactly the visible pages.
*/
void SetPreciousFlag (RequestData& rRequestData, bool bIsPrecious);
private:
view::SlideSorterView& mrView;
model::SlideSorterModel& mrModel;
BitmapCache maBitmapCache;
RequestQueue maRequestQueue;
QueueProcessor* mpQueueProcessor;
const sal_Int32 mnMaximalCacheSize;
/** Remember whether the cache limit has been reached at least once
after a Clear() call. This is important because afterwards the
cache will be constantly at its limit of capacity. Therefore
requests with another than the highest priority class will not be
processed since the resulting preview bitmaps would be removed
shortly afterwards.
*/
bool mbLimitHasBeenReached;
};
//===== GenericPageCache =====================================================
template<class RequestData,
class CreationManager,
class BitmapCache,
class RequestQueue,
class CompactionPolicy,
class QueueProcessor>
GenericPageCache<
RequestData,
CreationManager,
BitmapCache,
RequestQueue,
CompactionPolicy, QueueProcessor
>::GenericPageCache (
view::SlideSorterView& rView,
model::SlideSorterModel& rModel,
sal_Int32 nMaximalCacheSize)
: mrView(rView),
mrModel(rModel),
maBitmapCache (),
maRequestQueue(),
mpQueueProcessor(
new QueueProcessor(mrView,maRequestQueue,maBitmapCache)),
mnMaximalCacheSize(nMaximalCacheSize),
mbLimitHasBeenReached (false)
{
}
template<class RequestData,
class CreationManager,
class BitmapCache,
class RequestQueue,
class CompactionPolicy,
class QueueProcessor>
GenericPageCache<
RequestData, CreationManager, BitmapCache, RequestQueue,
CompactionPolicy, QueueProcessor
>::~GenericPageCache (void)
{
OSL_TRACE("terminating thread %p", mpQueueProcessor);
mpQueueProcessor->Stop();
maRequestQueue.Clear();
mpQueueProcessor->Terminate();
// delete mpQueueProcessor;
OSL_TRACE("thread %p stopped and terminated", mpQueueProcessor);
}
template<class RequestData,
class CreationManager,
class BitmapCache,
class RequestQueue,
class CompactionPolicy,
class QueueProcessor>
BitmapEx GenericPageCache<
RequestData, CreationManager, BitmapCache, RequestQueue,
CompactionPolicy, QueueProcessor
>::GetPreviewBitmap (
RequestData& rRequestData,
const Size& rSize)
{
BitmapEx aPreview;
bool bMayBeUpToDate = true;
if (maBitmapCache.HasBitmap (rRequestData.GetPage()))
{
aPreview = maBitmapCache.GetBitmap (rRequestData.GetPage());
Size aBitmapSize (aPreview.GetSizePixel());
if (aBitmapSize != rSize)
{
// The bitmap has the wrong size.
DBG_ASSERT (rSize.Width() < 1000,
"GenericPageCache<>::GetPreviewBitmap(): bitmap requested with large width. This may indicate an error.");
// Scale the bitmap to the desired size when that is possible,
// i.e. the bitmap is not empty.
if (aBitmapSize.Width()>0 && aBitmapSize.Height()>0)
aPreview.Scale (rSize, BMP_SCALE_FAST);
}
bMayBeUpToDate = true;
}
else
bMayBeUpToDate = false;
// Request the creation of a correctly sized preview bitmap. We do this
// even when the size of the bitmap in the cache is correct because its
// content may be not up-to-date anymore.
RequestPreviewBitmap (rRequestData, rSize, bMayBeUpToDate);
return aPreview;
}
template<class RequestData,
class CreationManager,
class BitmapCache,
class RequestQueue,
class CompactionPolicy,
class QueueProcessor>
void GenericPageCache<
RequestData, CreationManager, BitmapCache, RequestQueue,
CompactionPolicy, QueueProcessor
>::RequestPreviewBitmap (
RequestData& rRequestData,
const Size& rSize,
bool bMayBeUpToDate)
{
const SdrPage* pPage = rRequestData.GetPage();
// Determine if the available bitmap is up to date.
bool bIsUpToDate = false;
if (bMayBeUpToDate)
bIsUpToDate = maBitmapCache.BitmapIsUpToDate (pPage);
if (bIsUpToDate)
{
BitmapEx aPreview (maBitmapCache.GetBitmap (pPage));
if (aPreview.GetSizePixel() != rSize)
bIsUpToDate = false;
}
if ( ! bIsUpToDate)
{
// No, the bitmap is not up-to-date. Request a new one.
int nPriorityClass = rRequestData.GetPageDescriptor().IsVisible() ? 0 : 1;
maRequestQueue.AddRequest (rRequestData, nPriorityClass);
mpQueueProcessor->Start (nPriorityClass);
}
// Reduce the cache size if it grew too large.
if (maBitmapCache.GetSize() > mnMaximalCacheSize)
{
mbLimitHasBeenReached = true;
CompactionPolicy()(maBitmapCache, mnMaximalCacheSize);
}
}
template<class RequestData,
class CreationManager,
class BitmapCache,
class RequestQueue,
class CompactionPolicy,
class QueueProcessor>
void GenericPageCache<
RequestData, CreationManager, BitmapCache, RequestQueue,
CompactionPolicy, QueueProcessor
>::InvalidatePreviewBitmap (const RequestData& rRequestData)
{
maBitmapCache.InvalidateBitmap (rRequestData.GetPage());
}
template<class RequestData,
class CreationManager,
class BitmapCache,
class RequestQueue,
class CompactionPolicy,
class QueueProcessor>
void GenericPageCache<
RequestData, CreationManager, BitmapCache, RequestQueue,
CompactionPolicy, QueueProcessor
>::DecreaseRequestPriority (RequestData& rRequestData)
{
if (mbLimitHasBeenReached)
maRequestQueue.RemoveRequest (rRequestData);
else
maRequestQueue.ChangePriorityClass (rRequestData,+1);
}
template<class RequestData,
class CreationManager,
class BitmapCache,
class RequestQueue,
class CompactionPolicy,
class QueueProcessor>
void GenericPageCache<
RequestData, CreationManager, BitmapCache, RequestQueue,
CompactionPolicy, QueueProcessor
>::IncreaseRequestPriority (RequestData& rRequestData)
{
maRequestQueue.ChangePriorityClass (rRequestData,-1);
}
template<class RequestData,
class CreationManager,
class BitmapCache,
class RequestQueue,
class CompactionPolicy,
class QueueProcessor>
void GenericPageCache<
RequestData, CreationManager, BitmapCache, RequestQueue,
CompactionPolicy, QueueProcessor
>::ReleasePreviewBitmap (RequestData& rRequestData)
{
mpQueueProcessor->RemoveRequest (rRequestData);
maRequestQueue.RemoveRequest (rRequestData);
// We do not relase the preview bitmap that is associated with the page
// of the given request data because this method is called when the
// request data, typically a view-object-contact object, is destroyed.
// The page object usually lives longer than that and thus the preview
// bitmap may be used later on.
// maBitmapCache.ReleaseBitmap (rRequestData);
}
template<class RequestData,
class RequestFactory,
class BitmapCache,
class RequestQueue,
class CompactionPolicy,
class QueueProcessor>
void GenericPageCache<
RequestData, RequestFactory, BitmapCache, RequestQueue,
CompactionPolicy, QueueProcessor
>::InvalidateCache (void)
{
// 1.) Stop the timer while the queues are being updated.
mpQueueProcessor->Stop();
// 2.) Clear the request queue of their current content.
maRequestQueue.Clear();
mbLimitHasBeenReached = false;
// 3.) Create the new requests for filling the cache with at least the
// visible previews.
RequestFactory()(mrModel, mrView,maRequestQueue);
// 4.) Start the timer again.
mpQueueProcessor->Start();
}
template<class RequestData,
class RequestFactory,
class BitmapCache,
class RequestQueue,
class CompactionPolicy,
class QueueProcessor>
void GenericPageCache<
RequestData, RequestFactory, BitmapCache, RequestQueue,
CompactionPolicy, QueueProcessor
>::SetPreciousFlag (RequestData& rRequestData, bool bIsPrecious)
{
maBitmapCache.SetPrecious (rRequestData.GetPage(), bIsPrecious);
}
} } } // end of namespace ::sd::slidesorter::cache
#endif
<|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.
*/
/**
* @file utils_internal.cc
*/
#include "utils_internal.h"
#include <cassert>
#include <ts/ts.h>
#include <pthread.h>
#include <cstdlib>
#include <cassert>
#include <cstddef>
#include "atscppapi/Plugin.h"
#include "atscppapi/GlobalPlugin.h"
#include "atscppapi/Transaction.h"
#include "atscppapi/TransactionPlugin.h"
#include "atscppapi/TransformationPlugin.h"
#include "atscppapi/utils.h"
#include "logging_internal.h"
using namespace atscppapi;
namespace {
// This is the highest txn arg that can be used, we choose this
// value to minimize the likelihood of it causing any problems.
const int MAX_TXN_ARG = 15;
const int TRANSACTION_STORAGE_INDEX = MAX_TXN_ARG;
int handleTransactionEvents(TSCont cont, TSEvent event, void *edata) {
// This function is only here to clean up Transaction objects
TSHttpTxn ats_txn_handle = static_cast<TSHttpTxn>(edata);
Transaction &transaction = utils::internal::getTransaction(ats_txn_handle);
LOG_DEBUG("Got event %d on continuation %p for transaction (ats pointer %p, object %p)", event, cont,
ats_txn_handle, &transaction);
switch (event) {
case TS_EVENT_HTTP_POST_REMAP:
transaction.getClientRequest().getUrl().reset();
break;
case TS_EVENT_HTTP_SEND_REQUEST_HDR:
utils::internal::initTransactionServerRequest(transaction);
break;
case TS_EVENT_HTTP_READ_RESPONSE_HDR:
utils::internal::initTransactionServerResponse(transaction);
break;
case TS_EVENT_HTTP_SEND_RESPONSE_HDR:
utils::internal::initTransactionClientResponse(transaction);
break;
case TS_EVENT_HTTP_TXN_CLOSE:
{ // opening scope to declare plugins variable below
const std::list<TransactionPlugin *> &plugins = utils::internal::getTransactionPlugins(transaction);
for (std::list<TransactionPlugin *>::const_iterator iter = plugins.begin(), end = plugins.end();
iter != end; ++iter) {
shared_ptr<Mutex> trans_mutex = utils::internal::getTransactionPluginMutex(**iter);
LOG_DEBUG("Locking TransacitonPlugin mutex to delete transaction plugin at %p", *iter);
trans_mutex->lock();
LOG_DEBUG("Locked Mutex...Deleting transaction plugin at %p", *iter);
delete *iter;
trans_mutex->unlock();
}
delete &transaction;
}
break;
default:
assert(false); /* we should never get here */
break;
}
TSHttpTxnReenable(ats_txn_handle, TS_EVENT_HTTP_CONTINUE);
return 0;
}
void setupTransactionManagement() {
// We must always have a cleanup handler available
TSMutex mutex = NULL;
TSCont cont = TSContCreate(handleTransactionEvents, mutex);
TSHttpHookAdd(TS_HTTP_POST_REMAP_HOOK, cont);
TSHttpHookAdd(TS_HTTP_SEND_REQUEST_HDR_HOOK, cont);
TSHttpHookAdd(TS_HTTP_READ_RESPONSE_HDR_HOOK, cont);
TSHttpHookAdd(TS_HTTP_SEND_RESPONSE_HDR_HOOK, cont);
TSHttpHookAdd(TS_HTTP_TXN_CLOSE_HOOK, cont);
}
void inline invokePluginForEvent(Plugin *plugin, TSHttpTxn ats_txn_handle, TSEvent event) {
Transaction &transaction = utils::internal::getTransaction(ats_txn_handle);
switch (event) {
case TS_EVENT_HTTP_PRE_REMAP:
plugin->handleReadRequestHeadersPreRemap(transaction);
break;
case TS_EVENT_HTTP_POST_REMAP:
plugin->handleReadRequestHeadersPostRemap(transaction);
break;
case TS_EVENT_HTTP_SEND_REQUEST_HDR:
plugin->handleSendRequestHeaders(transaction);
break;
case TS_EVENT_HTTP_READ_RESPONSE_HDR:
plugin->handleReadResponseHeaders(transaction);
break;
case TS_EVENT_HTTP_SEND_RESPONSE_HDR:
plugin->handleSendResponseHeaders(transaction);
break;
case TS_EVENT_HTTP_OS_DNS:
plugin->handleOsDns(transaction);
break;
default:
assert(false); /* we should never get here */
break;
}
}
} /* anonymous namespace */
Transaction &utils::internal::getTransaction(TSHttpTxn ats_txn_handle) {
Transaction *transaction = static_cast<Transaction *>(TSHttpTxnArgGet(ats_txn_handle, TRANSACTION_STORAGE_INDEX));
if (!transaction) {
transaction = new Transaction(static_cast<void *>(ats_txn_handle));
LOG_DEBUG("Created new transaction object at %p for ats pointer %p", transaction, ats_txn_handle);
TSHttpTxnArgSet(ats_txn_handle, TRANSACTION_STORAGE_INDEX, transaction);
}
return *transaction;
}
shared_ptr<Mutex> utils::internal::getTransactionPluginMutex(TransactionPlugin &transaction_plugin) {
return transaction_plugin.getMutex();
}
TSHttpHookID utils::internal::convertInternalHookToTsHook(Plugin::HookType hooktype) {
switch (hooktype) {
case Plugin::HOOK_READ_REQUEST_HEADERS_POST_REMAP:
return TS_HTTP_POST_REMAP_HOOK;
case Plugin::HOOK_READ_REQUEST_HEADERS_PRE_REMAP:
return TS_HTTP_PRE_REMAP_HOOK;
case Plugin::HOOK_READ_RESPONSE_HEADERS:
return TS_HTTP_READ_RESPONSE_HDR_HOOK;
case Plugin::HOOK_SEND_REQUEST_HEADERS:
return TS_HTTP_SEND_REQUEST_HDR_HOOK;
case Plugin::HOOK_SEND_RESPONSE_HEADERS:
return TS_HTTP_SEND_RESPONSE_HDR_HOOK;
case Plugin::HOOK_OS_DNS:
return TS_HTTP_OS_DNS_HOOK;
default:
assert(false); // shouldn't happen, let's catch it early
break;
}
return static_cast<TSHttpHookID>(-1);
}
TSHttpHookID utils::internal::convertInternalTransformationTypeToTsHook(TransformationPlugin::Type type) {
switch (type) {
case TransformationPlugin::RESPONSE_TRANSFORMATION:
return TS_HTTP_RESPONSE_TRANSFORM_HOOK;
case TransformationPlugin::REQUEST_TRANSFORMATION:
return TS_HTTP_REQUEST_TRANSFORM_HOOK;
default:
assert(false); // shouldn't happen, let's catch it early
break;
}
return static_cast<TSHttpHookID>(-1);
}
void utils::internal::invokePluginForEvent(TransactionPlugin *plugin, TSHttpTxn ats_txn_handle, TSEvent event) {
ScopedSharedMutexLock scopedLock(plugin->getMutex());
::invokePluginForEvent(static_cast<Plugin *>(plugin), ats_txn_handle, event);
}
void utils::internal::invokePluginForEvent(GlobalPlugin *plugin, TSHttpTxn ats_txn_handle, TSEvent event) {
::invokePluginForEvent(static_cast<Plugin *>(plugin), ats_txn_handle, event);
}
std::string utils::internal::consumeFromTSIOBufferReader(TSIOBufferReader reader) {
std::string str;
int avail = TSIOBufferReaderAvail(reader);
if (avail != TS_ERROR) {
int consumed = 0;
if (avail > 0) {
str.reserve(avail + 1);
int64_t data_len;
const char *char_data;
TSIOBufferBlock block = TSIOBufferReaderStart(reader);
while (block != NULL) {
char_data = TSIOBufferBlockReadStart(block, reader, &data_len);
str.append(char_data, data_len);
consumed += data_len;
block = TSIOBufferBlockNext(block);
}
}
TSIOBufferReaderConsume(reader, consumed);
} else {
LOG_ERROR("TSIOBufferReaderAvail returned error code %d for reader %p", avail, reader);
}
return str;
}
HttpVersion utils::internal::getHttpVersion(TSMBuffer hdr_buf, TSMLoc hdr_loc) {
int version = TSHttpHdrVersionGet(hdr_buf, hdr_loc);
if (version != TS_ERROR) {
if ((TS_HTTP_MAJOR(version) == 0) && (TS_HTTP_MINOR(version) == 0)) {
return HTTP_VERSION_0_9;
}
if ((TS_HTTP_MAJOR(version) == 1) && (TS_HTTP_MINOR(version) == 0)) {
return HTTP_VERSION_1_0;
}
if ((TS_HTTP_MAJOR(version) == 1) && (TS_HTTP_MINOR(version) == 1)) {
return HTTP_VERSION_1_1;
} else {
LOG_ERROR("Unrecognized version %d", version);
}
} else {
LOG_ERROR("Could not get version; hdr_buf %p, hdr_loc %p", hdr_buf, hdr_loc);
}
return HTTP_VERSION_UNKNOWN;
}
void utils::internal::initTransactionManagement() {
static pthread_once_t setup_pthread_once_control = PTHREAD_ONCE_INIT;
pthread_once(&setup_pthread_once_control, setupTransactionManagement);
}
<commit_msg>Cppapi: small change to force refresh of cached url<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.
*/
/**
* @file utils_internal.cc
*/
#include "utils_internal.h"
#include <cassert>
#include <ts/ts.h>
#include <pthread.h>
#include <cstdlib>
#include <cassert>
#include <cstddef>
#include "atscppapi/Plugin.h"
#include "atscppapi/GlobalPlugin.h"
#include "atscppapi/Transaction.h"
#include "atscppapi/TransactionPlugin.h"
#include "atscppapi/TransformationPlugin.h"
#include "atscppapi/utils.h"
#include "logging_internal.h"
using namespace atscppapi;
namespace {
// This is the highest txn arg that can be used, we choose this
// value to minimize the likelihood of it causing any problems.
const int MAX_TXN_ARG = 15;
const int TRANSACTION_STORAGE_INDEX = MAX_TXN_ARG;
int handleTransactionEvents(TSCont cont, TSEvent event, void *edata) {
// This function is only here to clean up Transaction objects
TSHttpTxn ats_txn_handle = static_cast<TSHttpTxn>(edata);
Transaction &transaction = utils::internal::getTransaction(ats_txn_handle);
LOG_DEBUG("Got event %d on continuation %p for transaction (ats pointer %p, object %p)", event, cont,
ats_txn_handle, &transaction);
switch (event) {
case TS_EVENT_HTTP_POST_REMAP:
transaction.getClientRequest().getUrl().reset();
break;
case TS_EVENT_HTTP_SEND_REQUEST_HDR:
utils::internal::initTransactionServerRequest(transaction);
break;
case TS_EVENT_HTTP_READ_RESPONSE_HDR:
utils::internal::initTransactionServerResponse(transaction);
break;
case TS_EVENT_HTTP_SEND_RESPONSE_HDR:
utils::internal::initTransactionClientResponse(transaction);
break;
case TS_EVENT_HTTP_TXN_CLOSE:
{ // opening scope to declare plugins variable below
const std::list<TransactionPlugin *> &plugins = utils::internal::getTransactionPlugins(transaction);
for (std::list<TransactionPlugin *>::const_iterator iter = plugins.begin(), end = plugins.end();
iter != end; ++iter) {
shared_ptr<Mutex> trans_mutex = utils::internal::getTransactionPluginMutex(**iter);
LOG_DEBUG("Locking TransacitonPlugin mutex to delete transaction plugin at %p", *iter);
trans_mutex->lock();
LOG_DEBUG("Locked Mutex...Deleting transaction plugin at %p", *iter);
delete *iter;
trans_mutex->unlock();
}
delete &transaction;
}
break;
default:
assert(false); /* we should never get here */
break;
}
TSHttpTxnReenable(ats_txn_handle, TS_EVENT_HTTP_CONTINUE);
return 0;
}
void setupTransactionManagement() {
// We must always have a cleanup handler available
TSMutex mutex = NULL;
TSCont cont = TSContCreate(handleTransactionEvents, mutex);
TSHttpHookAdd(TS_HTTP_POST_REMAP_HOOK, cont);
TSHttpHookAdd(TS_HTTP_SEND_REQUEST_HDR_HOOK, cont);
TSHttpHookAdd(TS_HTTP_READ_RESPONSE_HDR_HOOK, cont);
TSHttpHookAdd(TS_HTTP_SEND_RESPONSE_HDR_HOOK, cont);
TSHttpHookAdd(TS_HTTP_TXN_CLOSE_HOOK, cont);
}
void inline invokePluginForEvent(Plugin *plugin, TSHttpTxn ats_txn_handle, TSEvent event) {
Transaction &transaction = utils::internal::getTransaction(ats_txn_handle);
switch (event) {
case TS_EVENT_HTTP_PRE_REMAP:
plugin->handleReadRequestHeadersPreRemap(transaction);
break;
case TS_EVENT_HTTP_POST_REMAP:
plugin->handleReadRequestHeadersPostRemap(transaction);
// This is hear to force a refresh of the cached client request url
TSMBuffer hdr_buf;
TSMLoc hdr_loc;
TSHttpTxnClientReqGet(static_cast<TSHttpTxn>(transaction.getAtsHandle()), &hdr_buf, &hdr_loc);
break;
case TS_EVENT_HTTP_SEND_REQUEST_HDR:
plugin->handleSendRequestHeaders(transaction);
break;
case TS_EVENT_HTTP_READ_RESPONSE_HDR:
plugin->handleReadResponseHeaders(transaction);
break;
case TS_EVENT_HTTP_SEND_RESPONSE_HDR:
plugin->handleSendResponseHeaders(transaction);
break;
case TS_EVENT_HTTP_OS_DNS:
plugin->handleOsDns(transaction);
break;
default:
assert(false); /* we should never get here */
break;
}
}
} /* anonymous namespace */
Transaction &utils::internal::getTransaction(TSHttpTxn ats_txn_handle) {
Transaction *transaction = static_cast<Transaction *>(TSHttpTxnArgGet(ats_txn_handle, TRANSACTION_STORAGE_INDEX));
if (!transaction) {
transaction = new Transaction(static_cast<void *>(ats_txn_handle));
LOG_DEBUG("Created new transaction object at %p for ats pointer %p", transaction, ats_txn_handle);
TSHttpTxnArgSet(ats_txn_handle, TRANSACTION_STORAGE_INDEX, transaction);
}
return *transaction;
}
shared_ptr<Mutex> utils::internal::getTransactionPluginMutex(TransactionPlugin &transaction_plugin) {
return transaction_plugin.getMutex();
}
TSHttpHookID utils::internal::convertInternalHookToTsHook(Plugin::HookType hooktype) {
switch (hooktype) {
case Plugin::HOOK_READ_REQUEST_HEADERS_POST_REMAP:
return TS_HTTP_POST_REMAP_HOOK;
case Plugin::HOOK_READ_REQUEST_HEADERS_PRE_REMAP:
return TS_HTTP_PRE_REMAP_HOOK;
case Plugin::HOOK_READ_RESPONSE_HEADERS:
return TS_HTTP_READ_RESPONSE_HDR_HOOK;
case Plugin::HOOK_SEND_REQUEST_HEADERS:
return TS_HTTP_SEND_REQUEST_HDR_HOOK;
case Plugin::HOOK_SEND_RESPONSE_HEADERS:
return TS_HTTP_SEND_RESPONSE_HDR_HOOK;
case Plugin::HOOK_OS_DNS:
return TS_HTTP_OS_DNS_HOOK;
default:
assert(false); // shouldn't happen, let's catch it early
break;
}
return static_cast<TSHttpHookID>(-1);
}
TSHttpHookID utils::internal::convertInternalTransformationTypeToTsHook(TransformationPlugin::Type type) {
switch (type) {
case TransformationPlugin::RESPONSE_TRANSFORMATION:
return TS_HTTP_RESPONSE_TRANSFORM_HOOK;
case TransformationPlugin::REQUEST_TRANSFORMATION:
return TS_HTTP_REQUEST_TRANSFORM_HOOK;
default:
assert(false); // shouldn't happen, let's catch it early
break;
}
return static_cast<TSHttpHookID>(-1);
}
void utils::internal::invokePluginForEvent(TransactionPlugin *plugin, TSHttpTxn ats_txn_handle, TSEvent event) {
ScopedSharedMutexLock scopedLock(plugin->getMutex());
::invokePluginForEvent(static_cast<Plugin *>(plugin), ats_txn_handle, event);
}
void utils::internal::invokePluginForEvent(GlobalPlugin *plugin, TSHttpTxn ats_txn_handle, TSEvent event) {
::invokePluginForEvent(static_cast<Plugin *>(plugin), ats_txn_handle, event);
}
std::string utils::internal::consumeFromTSIOBufferReader(TSIOBufferReader reader) {
std::string str;
int avail = TSIOBufferReaderAvail(reader);
if (avail != TS_ERROR) {
int consumed = 0;
if (avail > 0) {
str.reserve(avail + 1);
int64_t data_len;
const char *char_data;
TSIOBufferBlock block = TSIOBufferReaderStart(reader);
while (block != NULL) {
char_data = TSIOBufferBlockReadStart(block, reader, &data_len);
str.append(char_data, data_len);
consumed += data_len;
block = TSIOBufferBlockNext(block);
}
}
TSIOBufferReaderConsume(reader, consumed);
} else {
LOG_ERROR("TSIOBufferReaderAvail returned error code %d for reader %p", avail, reader);
}
return str;
}
HttpVersion utils::internal::getHttpVersion(TSMBuffer hdr_buf, TSMLoc hdr_loc) {
int version = TSHttpHdrVersionGet(hdr_buf, hdr_loc);
if (version != TS_ERROR) {
if ((TS_HTTP_MAJOR(version) == 0) && (TS_HTTP_MINOR(version) == 0)) {
return HTTP_VERSION_0_9;
}
if ((TS_HTTP_MAJOR(version) == 1) && (TS_HTTP_MINOR(version) == 0)) {
return HTTP_VERSION_1_0;
}
if ((TS_HTTP_MAJOR(version) == 1) && (TS_HTTP_MINOR(version) == 1)) {
return HTTP_VERSION_1_1;
} else {
LOG_ERROR("Unrecognized version %d", version);
}
} else {
LOG_ERROR("Could not get version; hdr_buf %p, hdr_loc %p", hdr_buf, hdr_loc);
}
return HTTP_VERSION_UNKNOWN;
}
void utils::internal::initTransactionManagement() {
static pthread_once_t setup_pthread_once_control = PTHREAD_ONCE_INIT;
pthread_once(&setup_pthread_once_control, setupTransactionManagement);
}
<|endoftext|>
|
<commit_before>#include "EdgesSubPix.h"
#include <cmath>
#include <opencv2/opencv.hpp>
using namespace cv;
using namespace std;
static void getCannyKernel(OutputArray _d, double alpha)
{
int r = cvRound(alpha * 3);
int ksize = 2 * r + 1;
_d.create(ksize, 1, CV_16S, -1, true);
Mat k = _d.getMat();
vector<float> kerF(ksize, 0.0f);
kerF[r] = 0.0f;
double a2 = alpha * alpha;
float sum = 0.0f;
for (int x = 1; x <= r; ++x)
{
float v = (float)(-x * std::exp(-x * x / (2 * a2)));
sum += v;
kerF[r + x] = v;
kerF[r - x] = -v;
}
float scale = 128 / sum;
for (int i = 0; i < ksize; ++i)
{
kerF[i] *= scale;
}
Mat temp(ksize, 1, CV_32F, &kerF[0]);
temp.convertTo(k, CV_16S);
}
// non-maximum supression and hysteresis
static void postCannyFilter(const Mat &src, Mat &dx, Mat &dy, int low, int high, Mat &dst)
{
ptrdiff_t mapstep = src.cols + 2;
AutoBuffer<uchar> buffer((src.cols + 2)*(src.rows + 2) + mapstep * 3 * sizeof(int));
// L2Gradient comparison with square
high = high * high;
low = low * low;
int* mag_buf[3];
mag_buf[0] = (int*)(uchar*)buffer;
mag_buf[1] = mag_buf[0] + mapstep;
mag_buf[2] = mag_buf[1] + mapstep;
memset(mag_buf[0], 0, /* cn* */mapstep*sizeof(int));
uchar* map = (uchar*)(mag_buf[2] + mapstep);
memset(map, 1, mapstep);
memset(map + mapstep*(src.rows + 1), 1, mapstep);
int maxsize = std::max(1 << 10, src.cols * src.rows / 10);
std::vector<uchar*> stack(maxsize);
uchar **stack_top = &stack[0];
uchar **stack_bottom = &stack[0];
/* sector numbers
(Top-Left Origin)
1 2 3
* * *
* * *
0*******0
* * *
* * *
3 2 1
*/
#define CANNY_PUSH(d) *(d) = uchar(2), *stack_top++ = (d)
#define CANNY_POP(d) (d) = *--stack_top
#if CV_SSE2
bool haveSSE2 = checkHardwareSupport(CV_CPU_SSE2);
#endif
// calculate magnitude and angle of gradient, perform non-maxima suppression.
// fill the map with one of the following values:
// 0 - the pixel might belong to an edge
// 1 - the pixel can not belong to an edge
// 2 - the pixel does belong to an edge
for (int i = 0; i <= src.rows; i++)
{
int* _norm = mag_buf[(i > 0) + 1] + 1;
if (i < src.rows)
{
short* _dx = dx.ptr<short>(i);
short* _dy = dy.ptr<short>(i);
int j = 0, width = src.cols;
#if CV_SSE2
if (haveSSE2)
{
for (; j <= width - 8; j += 8)
{
__m128i v_dx = _mm_loadu_si128((const __m128i *)(_dx + j));
__m128i v_dy = _mm_loadu_si128((const __m128i *)(_dy + j));
__m128i v_dx_ml = _mm_mullo_epi16(v_dx, v_dx), v_dx_mh = _mm_mulhi_epi16(v_dx, v_dx);
__m128i v_dy_ml = _mm_mullo_epi16(v_dy, v_dy), v_dy_mh = _mm_mulhi_epi16(v_dy, v_dy);
__m128i v_norm = _mm_add_epi32(_mm_unpacklo_epi16(v_dx_ml, v_dx_mh), _mm_unpacklo_epi16(v_dy_ml, v_dy_mh));
_mm_storeu_si128((__m128i *)(_norm + j), v_norm);
v_norm = _mm_add_epi32(_mm_unpackhi_epi16(v_dx_ml, v_dx_mh), _mm_unpackhi_epi16(v_dy_ml, v_dy_mh));
_mm_storeu_si128((__m128i *)(_norm + j + 4), v_norm);
}
}
#elif CV_NEON
for (; j <= width - 8; j += 8)
{
int16x8_t v_dx = vld1q_s16(_dx + j), v_dy = vld1q_s16(_dy + j);
int16x4_t v_dxp = vget_low_s16(v_dx), v_dyp = vget_low_s16(v_dy);
int32x4_t v_dst = vmlal_s16(vmull_s16(v_dxp, v_dxp), v_dyp, v_dyp);
vst1q_s32(_norm + j, v_dst);
v_dxp = vget_high_s16(v_dx), v_dyp = vget_high_s16(v_dy);
v_dst = vmlal_s16(vmull_s16(v_dxp, v_dxp), v_dyp, v_dyp);
vst1q_s32(_norm + j + 4, v_dst);
}
#endif
for (; j < width; ++j)
_norm[j] = int(_dx[j])*_dx[j] + int(_dy[j])*_dy[j];
_norm[-1] = _norm[src.cols] = 0;
}
else
memset(_norm - 1, 0, /* cn* */mapstep*sizeof(int));
// at the very beginning we do not have a complete ring
// buffer of 3 magnitude rows for non-maxima suppression
if (i == 0)
continue;
uchar* _map = map + mapstep*i + 1;
_map[-1] = _map[src.cols] = 1;
int* _mag = mag_buf[1] + 1; // take the central row
ptrdiff_t magstep1 = mag_buf[2] - mag_buf[1];
ptrdiff_t magstep2 = mag_buf[0] - mag_buf[1];
const short* _x = dx.ptr<short>(i - 1);
const short* _y = dy.ptr<short>(i - 1);
if ((stack_top - stack_bottom) + src.cols > maxsize)
{
int sz = (int)(stack_top - stack_bottom);
maxsize = std::max(maxsize * 3 / 2, sz + src.cols);
stack.resize(maxsize);
stack_bottom = &stack[0];
stack_top = stack_bottom + sz;
}
int prev_flag = 0;
for (int j = 0; j < src.cols; j++)
{
#define CANNY_SHIFT 15
const int TG22 = (int)(0.4142135623730950488016887242097*(1 << CANNY_SHIFT) + 0.5);
int m = _mag[j];
if (m > low)
{
int xs = _x[j];
int ys = _y[j];
int x = std::abs(xs);
int y = std::abs(ys) << CANNY_SHIFT;
int tg22x = x * TG22;
if (y < tg22x)
{
if (m > _mag[j - 1] && m >= _mag[j + 1]) goto __ocv_canny_push;
}
else
{
int tg67x = tg22x + (x << (CANNY_SHIFT + 1));
if (y > tg67x)
{
if (m > _mag[j + magstep2] && m >= _mag[j + magstep1]) goto __ocv_canny_push;
}
else
{
int s = (xs ^ ys) < 0 ? -1 : 1;
if (m > _mag[j + magstep2 - s] && m > _mag[j + magstep1 + s]) goto __ocv_canny_push;
}
}
}
prev_flag = 0;
_map[j] = uchar(1);
continue;
__ocv_canny_push:
if (!prev_flag && m > high && _map[j - mapstep] != 2)
{
CANNY_PUSH(_map + j);
prev_flag = 1;
}
else
_map[j] = 0;
}
// scroll the ring buffer
_mag = mag_buf[0];
mag_buf[0] = mag_buf[1];
mag_buf[1] = mag_buf[2];
mag_buf[2] = _mag;
}
// now track the edges (hysteresis thresholding)
while (stack_top > stack_bottom)
{
uchar* m;
if ((stack_top - stack_bottom) + 8 > maxsize)
{
int sz = (int)(stack_top - stack_bottom);
maxsize = maxsize * 3 / 2;
stack.resize(maxsize);
stack_bottom = &stack[0];
stack_top = stack_bottom + sz;
}
CANNY_POP(m);
if (!m[-1]) CANNY_PUSH(m - 1);
if (!m[1]) CANNY_PUSH(m + 1);
if (!m[-mapstep - 1]) CANNY_PUSH(m - mapstep - 1);
if (!m[-mapstep]) CANNY_PUSH(m - mapstep);
if (!m[-mapstep + 1]) CANNY_PUSH(m - mapstep + 1);
if (!m[mapstep - 1]) CANNY_PUSH(m + mapstep - 1);
if (!m[mapstep]) CANNY_PUSH(m + mapstep);
if (!m[mapstep + 1]) CANNY_PUSH(m + mapstep + 1);
}
// the final pass, form the final image
const uchar* pmap = map + mapstep + 1;
uchar* pdst = dst.ptr();
for (int i = 0; i < src.rows; i++, pmap += mapstep, pdst += dst.step)
{
for (int j = 0; j < src.cols; j++)
pdst[j] = (uchar)-(pmap[j] >> 1);
}
}
//---------------------------------------------------------------------
// INTERFACE FUNCTION
//---------------------------------------------------------------------
void EdgesSubPix(Mat &gray, double alpha, int low, int high,
vector<Contour> &contours, OutputArray hierarchy,
int mode, Point2f offset)
{
Mat blur;
GaussianBlur(gray, blur, Size(0, 0), alpha, alpha);
Mat d;
getCannyKernel(d, alpha);
Mat one = Mat::ones(Size(1, 1), CV_16S);
Mat dx, dy;
sepFilter2D(blur, dx, CV_16S, d, one);
sepFilter2D(blur, dy, CV_16S, one, d);
// non-maximum supression & hysteresis threshold
Mat edge = Mat::zeros(gray.size(), CV_8UC1);
double scale = 128.0; // sum of half Canny filter is 128
int lowThresh = cvRound(scale * low);
int highThresh = cvRound(scale * high);
postCannyFilter(gray, dx, dy, lowThresh, highThresh, edge);
}
void EdgesSubPix(Mat &gray, double alpha, int low, int high,
vector<Contour> &contours, Point2f offset)
{
vector<Vec4i> hierarchy;
EdgesSubPix(gray, alpha, low, high, contours, hierarchy, RETR_LIST);
}
<commit_msg>some text formating<commit_after>#include "EdgesSubPix.h"
#include <cmath>
#include <opencv2/opencv.hpp>
using namespace cv;
using namespace std;
static void getCannyKernel(OutputArray _d, double alpha)
{
int r = cvRound(alpha * 3);
int ksize = 2 * r + 1;
_d.create(ksize, 1, CV_16S, -1, true);
Mat k = _d.getMat();
vector<float> kerF(ksize, 0.0f);
kerF[r] = 0.0f;
double a2 = alpha * alpha;
float sum = 0.0f;
for (int x = 1; x <= r; ++x)
{
float v = (float)(-x * std::exp(-x * x / (2 * a2)));
sum += v;
kerF[r + x] = v;
kerF[r - x] = -v;
}
float scale = 128 / sum;
for (int i = 0; i < ksize; ++i)
{
kerF[i] *= scale;
}
Mat temp(ksize, 1, CV_32F, &kerF[0]);
temp.convertTo(k, CV_16S);
}
// non-maximum supression and hysteresis
static void postCannyFilter(const Mat &src, Mat &dx, Mat &dy, int low, int high, Mat &dst)
{
ptrdiff_t mapstep = src.cols + 2;
AutoBuffer<uchar> buffer((src.cols + 2)*(src.rows + 2) + mapstep * 3 * sizeof(int));
// L2Gradient comparison with square
high = high * high;
low = low * low;
int* mag_buf[3];
mag_buf[0] = (int*)(uchar*)buffer;
mag_buf[1] = mag_buf[0] + mapstep;
mag_buf[2] = mag_buf[1] + mapstep;
memset(mag_buf[0], 0, mapstep*sizeof(int));
uchar* map = (uchar*)(mag_buf[2] + mapstep);
memset(map, 1, mapstep);
memset(map + mapstep*(src.rows + 1), 1, mapstep);
int maxsize = std::max(1 << 10, src.cols * src.rows / 10);
std::vector<uchar*> stack(maxsize);
uchar **stack_top = &stack[0];
uchar **stack_bottom = &stack[0];
/* sector numbers
(Top-Left Origin)
1 2 3
* * *
* * *
0*******0
* * *
* * *
3 2 1
*/
#define CANNY_PUSH(d) *(d) = uchar(2), *stack_top++ = (d)
#define CANNY_POP(d) (d) = *--stack_top
#if CV_SSE2
bool haveSSE2 = checkHardwareSupport(CV_CPU_SSE2);
#endif
// calculate magnitude and angle of gradient, perform non-maxima suppression.
// fill the map with one of the following values:
// 0 - the pixel might belong to an edge
// 1 - the pixel can not belong to an edge
// 2 - the pixel does belong to an edge
for (int i = 0; i <= src.rows; i++)
{
int* _norm = mag_buf[(i > 0) + 1] + 1;
if (i < src.rows)
{
short* _dx = dx.ptr<short>(i);
short* _dy = dy.ptr<short>(i);
int j = 0, width = src.cols;
#if CV_SSE2
if (haveSSE2)
{
for (; j <= width - 8; j += 8)
{
__m128i v_dx = _mm_loadu_si128((const __m128i *)(_dx + j));
__m128i v_dy = _mm_loadu_si128((const __m128i *)(_dy + j));
__m128i v_dx_ml = _mm_mullo_epi16(v_dx, v_dx), v_dx_mh = _mm_mulhi_epi16(v_dx, v_dx);
__m128i v_dy_ml = _mm_mullo_epi16(v_dy, v_dy), v_dy_mh = _mm_mulhi_epi16(v_dy, v_dy);
__m128i v_norm = _mm_add_epi32(_mm_unpacklo_epi16(v_dx_ml, v_dx_mh), _mm_unpacklo_epi16(v_dy_ml, v_dy_mh));
_mm_storeu_si128((__m128i *)(_norm + j), v_norm);
v_norm = _mm_add_epi32(_mm_unpackhi_epi16(v_dx_ml, v_dx_mh), _mm_unpackhi_epi16(v_dy_ml, v_dy_mh));
_mm_storeu_si128((__m128i *)(_norm + j + 4), v_norm);
}
}
#elif CV_NEON
for (; j <= width - 8; j += 8)
{
int16x8_t v_dx = vld1q_s16(_dx + j), v_dy = vld1q_s16(_dy + j);
int16x4_t v_dxp = vget_low_s16(v_dx), v_dyp = vget_low_s16(v_dy);
int32x4_t v_dst = vmlal_s16(vmull_s16(v_dxp, v_dxp), v_dyp, v_dyp);
vst1q_s32(_norm + j, v_dst);
v_dxp = vget_high_s16(v_dx), v_dyp = vget_high_s16(v_dy);
v_dst = vmlal_s16(vmull_s16(v_dxp, v_dxp), v_dyp, v_dyp);
vst1q_s32(_norm + j + 4, v_dst);
}
#endif
for (; j < width; ++j)
_norm[j] = int(_dx[j])*_dx[j] + int(_dy[j])*_dy[j];
_norm[-1] = _norm[src.cols] = 0;
}
else
memset(_norm - 1, 0, /* cn* */mapstep*sizeof(int));
// at the very beginning we do not have a complete ring
// buffer of 3 magnitude rows for non-maxima suppression
if (i == 0)
continue;
uchar* _map = map + mapstep*i + 1;
_map[-1] = _map[src.cols] = 1;
int* _mag = mag_buf[1] + 1; // take the central row
ptrdiff_t magstep1 = mag_buf[2] - mag_buf[1];
ptrdiff_t magstep2 = mag_buf[0] - mag_buf[1];
const short* _x = dx.ptr<short>(i - 1);
const short* _y = dy.ptr<short>(i - 1);
if ((stack_top - stack_bottom) + src.cols > maxsize)
{
int sz = (int)(stack_top - stack_bottom);
maxsize = std::max(maxsize * 3 / 2, sz + src.cols);
stack.resize(maxsize);
stack_bottom = &stack[0];
stack_top = stack_bottom + sz;
}
int prev_flag = 0;
for (int j = 0; j < src.cols; j++)
{
#define CANNY_SHIFT 15
const int TG22 = (int)(0.4142135623730950488016887242097*(1 << CANNY_SHIFT) + 0.5);
int m = _mag[j];
if (m > low)
{
int xs = _x[j];
int ys = _y[j];
int x = std::abs(xs);
int y = std::abs(ys) << CANNY_SHIFT;
int tg22x = x * TG22;
if (y < tg22x)
{
if (m > _mag[j - 1] && m >= _mag[j + 1]) goto __ocv_canny_push;
}
else
{
int tg67x = tg22x + (x << (CANNY_SHIFT + 1));
if (y > tg67x)
{
if (m > _mag[j + magstep2] && m >= _mag[j + magstep1]) goto __ocv_canny_push;
}
else
{
int s = (xs ^ ys) < 0 ? -1 : 1;
if (m > _mag[j + magstep2 - s] && m > _mag[j + magstep1 + s]) goto __ocv_canny_push;
}
}
}
prev_flag = 0;
_map[j] = uchar(1);
continue;
__ocv_canny_push:
if (!prev_flag && m > high && _map[j - mapstep] != 2)
{
CANNY_PUSH(_map + j);
prev_flag = 1;
}
else
_map[j] = 0;
}
// scroll the ring buffer
_mag = mag_buf[0];
mag_buf[0] = mag_buf[1];
mag_buf[1] = mag_buf[2];
mag_buf[2] = _mag;
}
// now track the edges (hysteresis thresholding)
while (stack_top > stack_bottom)
{
uchar* m;
if ((stack_top - stack_bottom) + 8 > maxsize)
{
int sz = (int)(stack_top - stack_bottom);
maxsize = maxsize * 3 / 2;
stack.resize(maxsize);
stack_bottom = &stack[0];
stack_top = stack_bottom + sz;
}
CANNY_POP(m);
if (!m[-1]) CANNY_PUSH(m - 1);
if (!m[1]) CANNY_PUSH(m + 1);
if (!m[-mapstep - 1]) CANNY_PUSH(m - mapstep - 1);
if (!m[-mapstep]) CANNY_PUSH(m - mapstep);
if (!m[-mapstep + 1]) CANNY_PUSH(m - mapstep + 1);
if (!m[mapstep - 1]) CANNY_PUSH(m + mapstep - 1);
if (!m[mapstep]) CANNY_PUSH(m + mapstep);
if (!m[mapstep + 1]) CANNY_PUSH(m + mapstep + 1);
}
// the final pass, form the final image
const uchar* pmap = map + mapstep + 1;
uchar* pdst = dst.ptr();
for (int i = 0; i < src.rows; i++, pmap += mapstep, pdst += dst.step)
{
for (int j = 0; j < src.cols; j++)
pdst[j] = (uchar)-(pmap[j] >> 1);
}
}
//---------------------------------------------------------------------
// INTERFACE FUNCTION
//---------------------------------------------------------------------
void EdgesSubPix(Mat &gray, double alpha, int low, int high,
vector<Contour> &contours, OutputArray hierarchy,
int mode, Point2f offset)
{
Mat blur;
GaussianBlur(gray, blur, Size(0, 0), alpha, alpha);
Mat d;
getCannyKernel(d, alpha);
Mat one = Mat::ones(Size(1, 1), CV_16S);
Mat dx, dy;
sepFilter2D(blur, dx, CV_16S, d, one);
sepFilter2D(blur, dy, CV_16S, one, d);
// non-maximum supression & hysteresis threshold
Mat edge = Mat::zeros(gray.size(), CV_8UC1);
double scale = 128.0; // sum of half Canny filter is 128
int lowThresh = cvRound(scale * low);
int highThresh = cvRound(scale * high);
postCannyFilter(gray, dx, dy, lowThresh, highThresh, edge);
}
void EdgesSubPix(Mat &gray, double alpha, int low, int high,
vector<Contour> &contours, Point2f offset)
{
vector<Vec4i> hierarchy;
EdgesSubPix(gray, alpha, low, high, contours, hierarchy, RETR_LIST);
}
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkSpatialObjectToImageFilterTest.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 2002 Insight Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/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.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include "itkEllipseSpatialObject.h"
#include <itkSpatialObjectToImageFilter.h>
int itkSpatialObjectToImageFilterTest(int, char* [] )
{
typedef itk::EllipseSpatialObject<2> EllipseType;
EllipseType::Pointer ellipse = EllipseType::New();
ellipse->SetRadius(10);
// Center the circle in the image
EllipseType::TransformType::OffsetType offset;
offset.Fill(25);
ellipse->GetObjectToParentTransform()->SetOffset(offset);
ellipse->ComputeObjectToWorldTransform();
typedef itk::Image<double,2> ImageType;
typedef itk::SpatialObjectToImageFilter<EllipseType,ImageType> SpatialObjectToImageFilterType;
SpatialObjectToImageFilterType::Pointer imageFilter = SpatialObjectToImageFilterType::New();
imageFilter->SetInput(ellipse);
imageFilter->SetInsideValue(1);
imageFilter->SetOutsideValue(0);
ImageType::SizeType size;
size[0]=50;
size[1]=50;
imageFilter->SetSize(size);
// Testing spacing
std::cout << "Testing Spacing: ";
float spacing_float[2];
double spacing_double[2];
for(unsigned int i=0;i<2;i++)
{
spacing_float[i]=1.0;
spacing_double[i]=1.0;
}
imageFilter->SetSpacing(spacing_float);
imageFilter->SetSpacing(spacing_double);
const double* spacing_result = imageFilter->GetSpacing();
for(unsigned int i=0;i<2;i++)
{
if(spacing_result[i]!=1.0)
{
std::cout << "[FAILURE]" << std::endl;
return EXIT_FAILURE;
}
}
std::cout << "[PASSED]" << std::endl;
// Testing Origin
std::cout << "Testing Origin: ";
float origin_float[2];
double origin_double[2];
for(unsigned int i=0;i<2;i++)
{
origin_float[i]=0.0;
origin_double[i]=0.0;
}
imageFilter->SetOrigin(origin_float);
imageFilter->SetOrigin(origin_double);
const double* origin_result = imageFilter->GetOrigin();
for(unsigned int i=0;i<2;i++)
{
if(origin_result[i]!=0.0)
{
std::cout << "[FAILURE]" << std::endl;
return EXIT_FAILURE;
}
}
std::cout << "[PASSED]" << std::endl;
// Testing PrintSelf
std::cout << imageFilter << std::endl;
//Update the filter
imageFilter->Update();
ImageType::Pointer image = imageFilter->GetOutput();
std::cout << "Testing Output Image: ";
ImageType::IndexType index;
// Test only centered pixels
for(int i=-5;i<5;i++)
{
for(int j=-5;j<5;j++)
{
index[0] = 25+i;
index[1] = 25+j;
if(image->GetPixel(index) != 1.0)
{
std::cout << "[FAILURE]" << std::endl;
return EXIT_FAILURE;
}
}
}
std::cout << "[PASSED]" << std::endl;
return EXIT_SUCCESS;
}
<commit_msg>ENH: improve coverage<commit_after>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkSpatialObjectToImageFilterTest.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 2002 Insight Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/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.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include "itkEllipseSpatialObject.h"
#include <itkSpatialObjectToImageFilter.h>
int itkSpatialObjectToImageFilterTest(int, char* [] )
{
typedef itk::EllipseSpatialObject<2> EllipseType;
EllipseType::Pointer ellipse = EllipseType::New();
ellipse->SetRadius(10);
// Center the circle in the image
EllipseType::TransformType::OffsetType offset;
offset.Fill(25);
ellipse->GetObjectToParentTransform()->SetOffset(offset);
ellipse->ComputeObjectToWorldTransform();
typedef itk::Image<double,2> ImageType;
typedef itk::SpatialObjectToImageFilter<EllipseType,ImageType> SpatialObjectToImageFilterType;
SpatialObjectToImageFilterType::Pointer imageFilter = SpatialObjectToImageFilterType::New();
imageFilter->SetInput(ellipse);
imageFilter->SetInsideValue(1);
imageFilter->GetInsideValue();
imageFilter->SetOutsideValue(0);
imageFilter->GetOutsideValue();
imageFilter->SetChildrenDepth(1);
imageFilter->GetChildrenDepth();
ImageType::SizeType size;
size[0]=50;
size[1]=50;
imageFilter->SetSize(size);
// Testing spacing
std::cout << "Testing Spacing: ";
float spacing_float[2];
double spacing_double[2];
for(unsigned int i=0;i<2;i++)
{
spacing_float[i]=1.0;
spacing_double[i]=1.0;
}
imageFilter->SetSpacing(spacing_float);
imageFilter->SetSpacing(spacing_double);
const double* spacing_result = imageFilter->GetSpacing();
for(unsigned int i=0;i<2;i++)
{
if(spacing_result[i]!=1.0)
{
std::cout << "[FAILURE]" << std::endl;
return EXIT_FAILURE;
}
}
std::cout << "[PASSED]" << std::endl;
// Testing Origin
std::cout << "Testing Origin: ";
float origin_float[2];
double origin_double[2];
for(unsigned int i=0;i<2;i++)
{
origin_float[i]=0.0;
origin_double[i]=0.0;
}
imageFilter->SetOrigin(origin_float);
imageFilter->SetOrigin(origin_double);
const double* origin_result = imageFilter->GetOrigin();
for(unsigned int i=0;i<2;i++)
{
if(origin_result[i]!=0.0)
{
std::cout << "[FAILURE]" << std::endl;
return EXIT_FAILURE;
}
}
std::cout << "[PASSED]" << std::endl;
// Testing PrintSelf
std::cout << imageFilter << std::endl;
//Update the filter
imageFilter->Update();
ImageType::Pointer image = imageFilter->GetOutput();
std::cout << "Testing Output Image: ";
ImageType::IndexType index;
// Test only centered pixels
for(int i=-5;i<5;i++)
{
for(int j=-5;j<5;j++)
{
index[0] = 25+i;
index[1] = 25+j;
if(image->GetPixel(index) != 1.0)
{
std::cout << "[FAILURE]" << std::endl;
return EXIT_FAILURE;
}
}
}
std::cout << "[PASSED]" << std::endl;
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before>//===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// <functional>
// result_of<Fn(ArgTypes...)>
#include <type_traits>
#include <memory>
typedef bool (&PF1)();
typedef short (*PF2)(long);
struct S
{
operator PF2() const;
double operator()(char, int&);
void calc(long) const;
char data_;
};
typedef void (S::*PMS)(long) const;
typedef char S::*PMD;
int main()
{
static_assert((std::is_same<std::result_of<S(int)>::type, short>::value), "Error!");
static_assert((std::is_same<std::result_of<S&(unsigned char, int&)>::type, double>::value), "Error!");
static_assert((std::is_same<std::result_of<PF1()>::type, bool>::value), "Error!");
static_assert((std::is_same<std::result_of<PMS(std::unique_ptr<S>, int)>::type, void>::value), "Error!");
static_assert((std::is_same<std::result_of<PMS(S, int)>::type, void>::value), "Error!");
static_assert((std::is_same<std::result_of<PMS(const S&, int)>::type, void>::value), "Error!");
#ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES
static_assert((std::is_same<std::result_of<PMD(S)>::type, char&&>::value), "Error!");
#endif
static_assert((std::is_same<std::result_of<PMD(const S*)>::type, const char&>::value), "Error!");
}
<commit_msg>Constrain __invoke functions more accurately. This fixes http://llvm.org/bugs/show_bug.cgi?id=15861 .<commit_after>//===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// <functional>
// result_of<Fn(ArgTypes...)>
#include <type_traits>
#include <memory>
typedef bool (&PF1)();
typedef short (*PF2)(long);
struct S
{
operator PF2() const;
double operator()(char, int&);
void calc(long) const;
char data_;
};
typedef void (S::*PMS)(long) const;
typedef char S::*PMD;
struct wat
{
wat& operator*() { return *this; }
void foo();
};
int main()
{
static_assert((std::is_same<std::result_of<S(int)>::type, short>::value), "Error!");
static_assert((std::is_same<std::result_of<S&(unsigned char, int&)>::type, double>::value), "Error!");
static_assert((std::is_same<std::result_of<PF1()>::type, bool>::value), "Error!");
static_assert((std::is_same<std::result_of<PMS(std::unique_ptr<S>, int)>::type, void>::value), "Error!");
static_assert((std::is_same<std::result_of<PMS(S, int)>::type, void>::value), "Error!");
static_assert((std::is_same<std::result_of<PMS(const S&, int)>::type, void>::value), "Error!");
#ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES
static_assert((std::is_same<std::result_of<PMD(S)>::type, char&&>::value), "Error!");
#endif
static_assert((std::is_same<std::result_of<PMD(const S*)>::type, const char&>::value), "Error!");
using type = std::result_of<decltype(&wat::foo)(wat)>::type;
}
<|endoftext|>
|
<commit_before>// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/renderer_host/pepper/pepper_network_monitor_host.h"
#include "base/task_runner_util.h"
#include "base/threading/sequenced_worker_pool.h"
#include "content/browser/renderer_host/pepper/browser_ppapi_host_impl.h"
#include "content/browser/renderer_host/pepper/pepper_socket_utils.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/common/socket_permission_request.h"
#include "ppapi/proxy/ppapi_messages.h"
#include "ppapi/shared_impl/private/net_address_private_impl.h"
namespace content {
namespace {
bool CanUseNetworkMonitor(bool external_plugin,
int render_process_id,
int render_view_id) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
SocketPermissionRequest request = SocketPermissionRequest(
SocketPermissionRequest::NETWORK_STATE, std::string(), 0);
return pepper_socket_utils::CanUseSocketAPIs(
external_plugin, false /* private_api */, request, render_process_id,
render_view_id);
}
scoped_ptr<net::NetworkInterfaceList> GetNetworkList() {
scoped_ptr<net::NetworkInterfaceList> list(new net::NetworkInterfaceList());
net::GetNetworkList(list.get());
return list.Pass();
}
} // namespace
PepperNetworkMonitorHost::PepperNetworkMonitorHost(
BrowserPpapiHostImpl* host,
PP_Instance instance,
PP_Resource resource)
: ResourceHost(host->GetPpapiHost(), instance, resource),
weak_factory_(this) {
int render_process_id;
int render_view_id;
host->GetRenderViewIDsForInstance(instance,
&render_process_id,
&render_view_id);
BrowserThread::PostTaskAndReplyWithResult(
BrowserThread::UI, FROM_HERE,
base::Bind(&CanUseNetworkMonitor, host->external_plugin(),
render_process_id, render_view_id),
base::Bind(&PepperNetworkMonitorHost::OnPermissionCheckResult,
weak_factory_.GetWeakPtr()));
}
PepperNetworkMonitorHost::~PepperNetworkMonitorHost() {
net::NetworkChangeNotifier::RemoveIPAddressObserver(this);
}
void PepperNetworkMonitorHost::OnIPAddressChanged() {
GetAndSendNetworkList();
}
void PepperNetworkMonitorHost::OnPermissionCheckResult(
bool can_use_network_monitor) {
if (!can_use_network_monitor) {
host()->SendUnsolicitedReply(pp_resource(),
PpapiPluginMsg_NetworkMonitor_Forbidden());
return;
}
net::NetworkChangeNotifier::AddIPAddressObserver(this);
GetAndSendNetworkList();
}
void PepperNetworkMonitorHost::GetAndSendNetworkList() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
// Call GetNetworkList() on a thread that allows blocking IO.
base::PostTaskAndReplyWithResult(
BrowserThread::GetBlockingPool(), FROM_HERE,
base::Bind(&GetNetworkList),
base::Bind(&PepperNetworkMonitorHost::SendNetworkList,
weak_factory_.GetWeakPtr()));
}
void PepperNetworkMonitorHost::SendNetworkList(
scoped_ptr<net::NetworkInterfaceList> list) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
scoped_ptr<ppapi::proxy::SerializedNetworkList> list_copy(
new ppapi::proxy::SerializedNetworkList(list->size()));
for (size_t i = 0; i < list->size(); ++i) {
const net::NetworkInterface& network = list->at(i);
ppapi::proxy::SerializedNetworkInfo& network_copy = list_copy->at(i);
network_copy.name = network.name;
network_copy.addresses.resize(
1, ppapi::NetAddressPrivateImpl::kInvalidNetAddress);
bool result = ppapi::NetAddressPrivateImpl::IPEndPointToNetAddress(
network.address, 0, &(network_copy.addresses[0]));
DCHECK(result);
// TODO(sergeyu): Currently net::NetworkInterfaceList provides
// only name and one IP address. Add all other fields and copy
// them here.
network_copy.type = PP_NETWORKLIST_TYPE_UNKNOWN;
network_copy.state = PP_NETWORKLIST_STATE_UP;
network_copy.display_name = network.name;
network_copy.mtu = 0;
}
host()->SendUnsolicitedReply(
pp_resource(), PpapiPluginMsg_NetworkMonitor_NetworkList(*list_copy));
}
} // namespace content
<commit_msg>Fixed broken build.<commit_after>// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/renderer_host/pepper/pepper_network_monitor_host.h"
#include "base/task_runner_util.h"
#include "base/threading/sequenced_worker_pool.h"
#include "content/browser/renderer_host/pepper/browser_ppapi_host_impl.h"
#include "content/browser/renderer_host/pepper/pepper_socket_utils.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/common/socket_permission_request.h"
#include "ppapi/proxy/ppapi_messages.h"
#include "ppapi/shared_impl/private/net_address_private_impl.h"
namespace content {
namespace {
bool CanUseNetworkMonitor(bool external_plugin,
int render_process_id,
int render_view_id) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
SocketPermissionRequest request = SocketPermissionRequest(
SocketPermissionRequest::NETWORK_STATE, std::string(), 0);
return pepper_socket_utils::CanUseSocketAPIs(
external_plugin, false /* private_api */, &request, render_process_id,
render_view_id);
}
scoped_ptr<net::NetworkInterfaceList> GetNetworkList() {
scoped_ptr<net::NetworkInterfaceList> list(new net::NetworkInterfaceList());
net::GetNetworkList(list.get());
return list.Pass();
}
} // namespace
PepperNetworkMonitorHost::PepperNetworkMonitorHost(
BrowserPpapiHostImpl* host,
PP_Instance instance,
PP_Resource resource)
: ResourceHost(host->GetPpapiHost(), instance, resource),
weak_factory_(this) {
int render_process_id;
int render_view_id;
host->GetRenderViewIDsForInstance(instance,
&render_process_id,
&render_view_id);
BrowserThread::PostTaskAndReplyWithResult(
BrowserThread::UI, FROM_HERE,
base::Bind(&CanUseNetworkMonitor, host->external_plugin(),
render_process_id, render_view_id),
base::Bind(&PepperNetworkMonitorHost::OnPermissionCheckResult,
weak_factory_.GetWeakPtr()));
}
PepperNetworkMonitorHost::~PepperNetworkMonitorHost() {
net::NetworkChangeNotifier::RemoveIPAddressObserver(this);
}
void PepperNetworkMonitorHost::OnIPAddressChanged() {
GetAndSendNetworkList();
}
void PepperNetworkMonitorHost::OnPermissionCheckResult(
bool can_use_network_monitor) {
if (!can_use_network_monitor) {
host()->SendUnsolicitedReply(pp_resource(),
PpapiPluginMsg_NetworkMonitor_Forbidden());
return;
}
net::NetworkChangeNotifier::AddIPAddressObserver(this);
GetAndSendNetworkList();
}
void PepperNetworkMonitorHost::GetAndSendNetworkList() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
// Call GetNetworkList() on a thread that allows blocking IO.
base::PostTaskAndReplyWithResult(
BrowserThread::GetBlockingPool(), FROM_HERE,
base::Bind(&GetNetworkList),
base::Bind(&PepperNetworkMonitorHost::SendNetworkList,
weak_factory_.GetWeakPtr()));
}
void PepperNetworkMonitorHost::SendNetworkList(
scoped_ptr<net::NetworkInterfaceList> list) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
scoped_ptr<ppapi::proxy::SerializedNetworkList> list_copy(
new ppapi::proxy::SerializedNetworkList(list->size()));
for (size_t i = 0; i < list->size(); ++i) {
const net::NetworkInterface& network = list->at(i);
ppapi::proxy::SerializedNetworkInfo& network_copy = list_copy->at(i);
network_copy.name = network.name;
network_copy.addresses.resize(
1, ppapi::NetAddressPrivateImpl::kInvalidNetAddress);
bool result = ppapi::NetAddressPrivateImpl::IPEndPointToNetAddress(
network.address, 0, &(network_copy.addresses[0]));
DCHECK(result);
// TODO(sergeyu): Currently net::NetworkInterfaceList provides
// only name and one IP address. Add all other fields and copy
// them here.
network_copy.type = PP_NETWORKLIST_TYPE_UNKNOWN;
network_copy.state = PP_NETWORKLIST_STATE_UP;
network_copy.display_name = network.name;
network_copy.mtu = 0;
}
host()->SendUnsolicitedReply(
pp_resource(), PpapiPluginMsg_NetworkMonitor_NetworkList(*list_copy));
}
} // namespace content
<|endoftext|>
|
<commit_before>#include <Common.hpp>
#include <Engine.hpp>
#include <Dispatch.hpp>
#include <MessageProcessor.hpp>
#include <functional>
#include <iostream>
#include <sstream>
#include <boost/regex.hpp>
#include <boost/thread/thread.hpp>
#include <xUnit++/xUnit++.h>
namespace K3 {
std::string localhost = "127.0.0.1";
Address peer1;
Address peer2;
Address peer3;
Address rendezvous;
int nodeCounter(0);
using std::cout;
using std::endl;
using std::bind;
using std::string;
using std::shared_ptr;
// "Trigger" Declarations
void join(shared_ptr<Engine> engine, string message_contents) {
Message m = Message(rendezvous, "register", "1");
engine->send(m);
}
void register2(shared_ptr<Engine> engine, string message_contents) {
int n = std::stoi(message_contents);
nodeCounter += n;
}
// MP setup
TriggerDispatch buildTable(shared_ptr<Engine> engine) {
TriggerDispatch table = TriggerDispatch();
table["join"] = bind(&K3::join, engine, std::placeholders::_1);
table["register"] = bind(&K3::register2, engine, std::placeholders::_1);
return table;
}
shared_ptr<MessageProcessor> buildMP(shared_ptr<Engine> engine) {
auto table = buildTable(engine);
shared_ptr<MessageProcessor> mp = make_shared<DispatchMessageProcessor>(DispatchMessageProcessor(table));
return mp;
}
// Engine setup
shared_ptr<Engine> buildEngine(bool simulation, SystemEnvironment s_env) {
// Configure engine components
shared_ptr<InternalCodec> i_cdec = make_shared<DefaultInternalCodec>(DefaultInternalCodec());
shared_ptr<ExternalCodec> e_cdec = make_shared<DefaultCodec>(DefaultCodec());
// Construct an engine
Engine engine = Engine(simulation, s_env, i_cdec, e_cdec);
return make_shared<Engine>(engine);
}
}
FACT("Simulation mode CountPeers with 3 peers should count 3") {
K3::nodeCounter = 0;
K3::peer1 = K3::make_address(K3::localhost, 3000);
K3::peer2 = K3::make_address(K3::localhost, 3001);
K3::peer3 = K3::make_address(K3::localhost, 3002);
K3::rendezvous = K3::peer1;
std::list<K3::Address> peers = std::list<K3::Address>();
peers.push_back(K3::peer1);
peers.push_back(K3::peer2);
peers.push_back(K3::peer3);
K3::SystemEnvironment s_env = K3::defaultEnvironment(peers);
auto engine = K3::buildEngine(true, s_env);
auto mp = K3::buildMP(engine);
K3::Message m1 = K3::Message(K3::peer1, "join", "()");
K3::Message m2 = K3::Message(K3::peer2, "join", "()");
K3::Message m3 = K3::Message(K3::peer3, "join", "()");
engine->send(m1);
engine->send(m2);
engine->send(m3);
// Run Engine
engine->runEngine(mp);
// Check the result (the 6th fib number should = 8)
Assert.Equal(3, K3::nodeCounter);
}
FACT("Network mode CountPeers with 3 peers should count 3") {
K3::nodeCounter = 0;
using boost::thread;
using boost::thread_group;
// Create peers
K3::peer1 = K3::make_address(K3::localhost, 3000);
K3::peer2 = K3::make_address(K3::localhost, 3005);
K3::peer3 = K3::make_address(K3::localhost, 3002);
K3::rendezvous = K3::peer1;
// Create engines
auto engine1 = K3::buildEngine(false, K3::defaultEnvironment(K3::peer1));
auto engine2 = K3::buildEngine(false, K3::defaultEnvironment(K3::peer2));
auto engine3 = K3::buildEngine(false, K3::defaultEnvironment(K3::peer3));
// Create MPs
auto mp1 = K3::buildMP(engine1);
auto mp2 = K3::buildMP(engine2);
auto mp3 = K3::buildMP(engine3);
// Create initial messages (source)
K3::Message m1 = K3::Message(K3::peer1, "join", "()");
K3::Message m2 = K3::Message(K3::peer2, "join", "()");
K3::Message m3 = K3::Message(K3::peer3, "join", "()");
engine1->send(m1);
engine2->send(m2);
engine3->send(m3);
// Fork a thread for each engine
auto service_threads = std::shared_ptr<thread_group>(new thread_group());
thread t1 = engine1->forkEngine(mp1);
thread t2 = engine2->forkEngine(mp2);
thread t3 = engine3->forkEngine(mp3);
service_threads->add_thread(&t1);
service_threads->add_thread(&t2);
service_threads->add_thread(&t3);
boost::this_thread::sleep_for( boost::chrono::seconds(5) );
engine1->forceTerminateEngine();
engine2->forceTerminateEngine();
engine3->forceTerminateEngine();
service_threads->join_all();
service_threads->remove_thread(&t1);
service_threads->remove_thread(&t2);
service_threads->remove_thread(&t3);
// Check the result
Assert.Equal(3, K3::nodeCounter);
}
<commit_msg>fixed another comment<commit_after>#include <Common.hpp>
#include <Engine.hpp>
#include <Dispatch.hpp>
#include <MessageProcessor.hpp>
#include <functional>
#include <iostream>
#include <sstream>
#include <boost/regex.hpp>
#include <boost/thread/thread.hpp>
#include <xUnit++/xUnit++.h>
namespace K3 {
std::string localhost = "127.0.0.1";
Address peer1;
Address peer2;
Address peer3;
Address rendezvous;
int nodeCounter(0);
using std::cout;
using std::endl;
using std::bind;
using std::string;
using std::shared_ptr;
// "Trigger" Declarations
void join(shared_ptr<Engine> engine, string message_contents) {
Message m = Message(rendezvous, "register", "1");
engine->send(m);
}
void register2(shared_ptr<Engine> engine, string message_contents) {
int n = std::stoi(message_contents);
nodeCounter += n;
}
// MP setup
TriggerDispatch buildTable(shared_ptr<Engine> engine) {
TriggerDispatch table = TriggerDispatch();
table["join"] = bind(&K3::join, engine, std::placeholders::_1);
table["register"] = bind(&K3::register2, engine, std::placeholders::_1);
return table;
}
shared_ptr<MessageProcessor> buildMP(shared_ptr<Engine> engine) {
auto table = buildTable(engine);
shared_ptr<MessageProcessor> mp = make_shared<DispatchMessageProcessor>(DispatchMessageProcessor(table));
return mp;
}
// Engine setup
shared_ptr<Engine> buildEngine(bool simulation, SystemEnvironment s_env) {
// Configure engine components
shared_ptr<InternalCodec> i_cdec = make_shared<DefaultInternalCodec>(DefaultInternalCodec());
shared_ptr<ExternalCodec> e_cdec = make_shared<DefaultCodec>(DefaultCodec());
// Construct an engine
Engine engine = Engine(simulation, s_env, i_cdec, e_cdec);
return make_shared<Engine>(engine);
}
}
FACT("Simulation mode CountPeers with 3 peers should count 3") {
K3::nodeCounter = 0;
K3::peer1 = K3::make_address(K3::localhost, 3000);
K3::peer2 = K3::make_address(K3::localhost, 3001);
K3::peer3 = K3::make_address(K3::localhost, 3002);
K3::rendezvous = K3::peer1;
std::list<K3::Address> peers = std::list<K3::Address>();
peers.push_back(K3::peer1);
peers.push_back(K3::peer2);
peers.push_back(K3::peer3);
K3::SystemEnvironment s_env = K3::defaultEnvironment(peers);
auto engine = K3::buildEngine(true, s_env);
auto mp = K3::buildMP(engine);
K3::Message m1 = K3::Message(K3::peer1, "join", "()");
K3::Message m2 = K3::Message(K3::peer2, "join", "()");
K3::Message m3 = K3::Message(K3::peer3, "join", "()");
engine->send(m1);
engine->send(m2);
engine->send(m3);
// Run Engine
engine->runEngine(mp);
// Check the result
Assert.Equal(3, K3::nodeCounter);
}
FACT("Network mode CountPeers with 3 peers should count 3") {
K3::nodeCounter = 0;
using boost::thread;
using boost::thread_group;
// Create peers
K3::peer1 = K3::make_address(K3::localhost, 3000);
K3::peer2 = K3::make_address(K3::localhost, 3005);
K3::peer3 = K3::make_address(K3::localhost, 3002);
K3::rendezvous = K3::peer1;
// Create engines
auto engine1 = K3::buildEngine(false, K3::defaultEnvironment(K3::peer1));
auto engine2 = K3::buildEngine(false, K3::defaultEnvironment(K3::peer2));
auto engine3 = K3::buildEngine(false, K3::defaultEnvironment(K3::peer3));
// Create MPs
auto mp1 = K3::buildMP(engine1);
auto mp2 = K3::buildMP(engine2);
auto mp3 = K3::buildMP(engine3);
// Create initial messages (source)
K3::Message m1 = K3::Message(K3::peer1, "join", "()");
K3::Message m2 = K3::Message(K3::peer2, "join", "()");
K3::Message m3 = K3::Message(K3::peer3, "join", "()");
engine1->send(m1);
engine2->send(m2);
engine3->send(m3);
// Fork a thread for each engine
auto service_threads = std::shared_ptr<thread_group>(new thread_group());
thread t1 = engine1->forkEngine(mp1);
thread t2 = engine2->forkEngine(mp2);
thread t3 = engine3->forkEngine(mp3);
service_threads->add_thread(&t1);
service_threads->add_thread(&t2);
service_threads->add_thread(&t3);
boost::this_thread::sleep_for( boost::chrono::seconds(5) );
engine1->forceTerminateEngine();
engine2->forceTerminateEngine();
engine3->forceTerminateEngine();
service_threads->join_all();
service_threads->remove_thread(&t1);
service_threads->remove_thread(&t2);
service_threads->remove_thread(&t3);
// Check the result
Assert.Equal(3, K3::nodeCounter);
}
<|endoftext|>
|
<commit_before>/*
Copyright (C) 2013 Andreas Hartmetz <ahartmetz@gmail.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LGPL. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
Alternatively, this file is available under the Mozilla Public License
Version 1.1. You may obtain a copy of the License at
http://www.mozilla.org/MPL/
*/
#include "authclient.h"
#include "icompletionlistener.h"
#include "itransport.h"
#include "stringtools.h"
#include <cassert>
#include <iostream>
#include <sstream>
#ifdef __unix__
#include <sys/types.h>
#include <unistd.h>
#endif
#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <sddl.h>
#include "winutil.h"
#endif
using namespace std;
AuthClient::AuthClient(ITransport *transport)
: m_state(InitialState),
m_completionListener(nullptr)
{
cerr << "AuthClient constructing\n";
transport->addListener(this);
setReadNotificationEnabled(true);
byte nullBuf[1] = { 0 };
transport->write(chunk(nullBuf, 1));
stringstream uidEncoded;
#ifdef _WIN32
// Most common (or rather... actually used) authentication method on Windows:
// - Server publishes address of a nonce file; the file name is in a shared memory segment
// - Client reads nonce file
// - Client connects and sends the nonce data, TODO: before or after the null byte / is there a null byte?
// - Client uses EXTERNAL auth and says which Windows security ID (SID) it intends to have
uidEncoded << fetchWindowsSid();
#else
// Most common (or rather... actually used) authentication method on Unix derivatives:
// - Client sends a null byte so the server has something to receive with recvmsg()
// - Server checks UID using SCM_CREDENTIALS, a mechanism of Unix local sockets
// - Client uses EXTERNAL auth and says which Unix user ID it intends to have
// The numeric UID is first encoded to ASCII ("1000") and the ASCII to hex... because.
uidEncoded << geteuid();
#endif
string extLine = "AUTH EXTERNAL " + hexEncode(uidEncoded.str()) + "\r\n";
cout << extLine;
transport->write(chunk(extLine.c_str(), extLine.length()));
m_state = ExpectOkState;
}
bool AuthClient::isFinished() const
{
return m_state >= AuthenticationFailedState;
}
bool AuthClient::isAuthenticated() const
{
return m_state == AuthenticatedState;
}
void AuthClient::setCompletionListener(ICompletionListener *listener)
{
m_completionListener = listener;
}
void AuthClient::handleTransportCanRead()
{
bool wasFinished = isFinished();
while (!isFinished() && readLine()) {
advanceState();
}
if (isFinished() && !wasFinished && m_completionListener) {
m_completionListener->handleCompletion(this);
}
}
bool AuthClient::readLine()
{
// don't care about performance here, this doesn't run often or process much data
if (isEndOfLine()) {
m_line.clear(); // start a new line
}
while (transport()->availableBytesForReading()) {
byte readBuf[1];
chunk in = transport()->read(readBuf, 1);
assert(in.length == 1);
m_line += char(in.ptr[0]);
if (isEndOfLine()) {
return true;
}
}
return false;
}
bool AuthClient::isEndOfLine() const
{
return m_line.length() >= 2 &&
m_line[m_line.length() - 2] == '\r' && m_line[m_line.length() - 1] == '\n';
}
void AuthClient::advanceState()
{
// TODO authentication ping-pong done *properly* (grammar / some simple state machine),
// but hey, this works for now!
// some findings:
// - the string after the server OK is its UUID that also appears in the address string
cout << "> " << m_line;
switch (m_state) {
case ExpectOkState: {
// TODO check the OK
#ifdef __unix__
cstring negotiateLine("NEGOTIATE_UNIX_FD\r\n");
cout << negotiateLine.ptr;
transport()->write(chunk(negotiateLine.ptr, negotiateLine.length));
m_state = ExpectUnixFdResponseState;
break; }
case ExpectUnixFdResponseState: {
#endif
// TODO check the response
cstring beginLine("BEGIN\r\n");
cout << beginLine.ptr;
transport()->write(chunk(beginLine.ptr, beginLine.length));
m_state = AuthenticatedState;
break; }
default:
m_state = AuthenticationFailedState;
transport()->close();
}
}
<commit_msg>Remove some debug output<commit_after>/*
Copyright (C) 2013 Andreas Hartmetz <ahartmetz@gmail.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LGPL. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
Alternatively, this file is available under the Mozilla Public License
Version 1.1. You may obtain a copy of the License at
http://www.mozilla.org/MPL/
*/
#include "authclient.h"
#include "icompletionlistener.h"
#include "itransport.h"
#include "stringtools.h"
#include <cassert>
#include <iostream>
#include <sstream>
#ifdef __unix__
#include <sys/types.h>
#include <unistd.h>
#endif
#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <sddl.h>
#include "winutil.h"
#endif
using namespace std;
AuthClient::AuthClient(ITransport *transport)
: m_state(InitialState),
m_completionListener(nullptr)
{
transport->addListener(this);
setReadNotificationEnabled(true);
byte nullBuf[1] = { 0 };
transport->write(chunk(nullBuf, 1));
stringstream uidEncoded;
#ifdef _WIN32
// Most common (or rather... actually used) authentication method on Windows:
// - Server publishes address of a nonce file; the file name is in a shared memory segment
// - Client reads nonce file
// - Client connects and sends the nonce data, TODO: before or after the null byte / is there a null byte?
// - Client uses EXTERNAL auth and says which Windows security ID (SID) it intends to have
uidEncoded << fetchWindowsSid();
#else
// Most common (or rather... actually used) authentication method on Unix derivatives:
// - Client sends a null byte so the server has something to receive with recvmsg()
// - Server checks UID using SCM_CREDENTIALS, a mechanism of Unix local sockets
// - Client uses EXTERNAL auth and says which Unix user ID it intends to have
// The numeric UID is first encoded to ASCII ("1000") and the ASCII to hex... because.
uidEncoded << geteuid();
#endif
string extLine = "AUTH EXTERNAL " + hexEncode(uidEncoded.str()) + "\r\n";
cout << extLine;
transport->write(chunk(extLine.c_str(), extLine.length()));
m_state = ExpectOkState;
}
bool AuthClient::isFinished() const
{
return m_state >= AuthenticationFailedState;
}
bool AuthClient::isAuthenticated() const
{
return m_state == AuthenticatedState;
}
void AuthClient::setCompletionListener(ICompletionListener *listener)
{
m_completionListener = listener;
}
void AuthClient::handleTransportCanRead()
{
bool wasFinished = isFinished();
while (!isFinished() && readLine()) {
advanceState();
}
if (isFinished() && !wasFinished && m_completionListener) {
m_completionListener->handleCompletion(this);
}
}
bool AuthClient::readLine()
{
// don't care about performance here, this doesn't run often or process much data
if (isEndOfLine()) {
m_line.clear(); // start a new line
}
while (transport()->availableBytesForReading()) {
byte readBuf[1];
chunk in = transport()->read(readBuf, 1);
assert(in.length == 1);
m_line += char(in.ptr[0]);
if (isEndOfLine()) {
return true;
}
}
return false;
}
bool AuthClient::isEndOfLine() const
{
return m_line.length() >= 2 &&
m_line[m_line.length() - 2] == '\r' && m_line[m_line.length() - 1] == '\n';
}
void AuthClient::advanceState()
{
// TODO authentication ping-pong done *properly* (grammar / some simple state machine),
// but hey, this works for now!
// some findings:
// - the string after the server OK is its UUID that also appears in the address string
cout << "> " << m_line;
switch (m_state) {
case ExpectOkState: {
// TODO check the OK
#ifdef __unix__
cstring negotiateLine("NEGOTIATE_UNIX_FD\r\n");
cout << negotiateLine.ptr;
transport()->write(chunk(negotiateLine.ptr, negotiateLine.length));
m_state = ExpectUnixFdResponseState;
break; }
case ExpectUnixFdResponseState: {
#endif
// TODO check the response
cstring beginLine("BEGIN\r\n");
cout << beginLine.ptr;
transport()->write(chunk(beginLine.ptr, beginLine.length));
m_state = AuthenticatedState;
break; }
default:
m_state = AuthenticationFailedState;
transport()->close();
}
}
<|endoftext|>
|
<commit_before>/*
* Implement atoi to convert a string to an integer.
*
* Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.
*
* Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.
*
* Update (2015-02-10):
* The signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button to reset your code definition.
*
* spoilers alert... click to show requirements for atoi.
*
* Requirements for atoi:
* The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.
*
* The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.
*
* If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.
*
* If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.
* int myAtoi(string str)
* */
#include "common.h"
int myAtoi(string str) {
int size = str.size();
int64_t ret = 0;
int sign = 1;
int i = 0;
//filter spaces
while(i < size && isspace(str[i])) {i++;}
if (i == size) return 0;
//deal with sign
if (!isdigit(str[i])) {
if (str[i] == '-') {
sign = -1;
i++;
} else if (str[i] == '+') {
i++;
} else {
return 0;
}
}
while(i < size) {
if (!isdigit(str[i])) break;
ret = 10 * ret + str[i] - '0';
if (ret > std::numeric_limits<int>::max()) {
return std::numeric_limits<int>::max();
}
i++;
}
ret = ret * sign;
if (ret > std::numeric_limits<int>::max() || ret < std::numeric_limits<int>::min()) {
return std::numeric_limits<int>::max();
}
return ret;
}
int main() {
struct Case {
string str;
int expect;
} cases[] = {
{" +", 0},
{" -", 0},
{"0", 0},
{"-123", -123},
{"+123", 123},
{"123", 123},
{" 123", 123},
{"123abcde", 123},
{"abc1323", 0},
{"21474836499", std::numeric_limits<int>::max() },
};
int size = sizeof(cases)/sizeof(Case);
bool ok = true;
for (int i = 0; i < size; i++) {
int result = myAtoi(cases[i].str);
if (result != cases[i].expect) {
ok = false;
cerr << "Case " << i << " Failed. expect: " << cases[i].expect << " actual output: " << result << " \n";
}
}
if (ok) {
cout << "ALL PASSED.";
}
return 0;
}
<commit_msg>update no 8 reverse integer.<commit_after>/*
* Implement atoi to convert a string to an integer.
*
* Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.
*
* Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.
*
* Update (2015-02-10):
* The signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button to reset your code definition.
*
* spoilers alert... click to show requirements for atoi.
*
* Requirements for atoi:
* The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.
*
* The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.
*
* If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.
*
* If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.
* int myAtoi(string str)
* */
#include "common.h"
int myAtoi(string str) {
int size = str.size();
int64_t ret = 0;
int sign = 1;
int i = 0;
//filter spaces
while(i < size && isspace(str[i])) {i++;}
if (i == size) return 0;
//deal with sign
if (!isdigit(str[i])) {
if (str[i] == '-') {
sign = -1;
i++;
} else if (str[i] == '+') {
i++;
} else {
return 0;
}
}
while(i < size) {
if (!isdigit(str[i])) break;
ret = 10 * ret + str[i] - '0';
if (ret * sign > std::numeric_limits<int>::max()) {
return std::numeric_limits<int>::max();
} else if (ret * sign < std::numeric_limits<int>::min()) {
return std::numeric_limits<int>::min();
}
i++;
}
return sign * ret;
}
int main() {
struct Case {
string str;
int expect;
} cases[] = {
{" +", 0},
{" -", 0},
{"0", 0},
{"-123", -123},
{"+123", 123},
{"123", 123},
{" 123", 123},
{"123abcde", 123},
{"abc1323", 0},
{"+2147483647", std::numeric_limits<int>::max() },
{"+2147483648", std::numeric_limits<int>::max() },
{"-2147483648", std::numeric_limits<int>::min() },
{"-2147483649", std::numeric_limits<int>::min() },
};
int size = sizeof(cases)/sizeof(Case);
bool ok = true;
for (int i = 0; i < size; i++) {
int result = myAtoi(cases[i].str);
if (result != cases[i].expect) {
ok = false;
cerr << "Case " << i << " Failed. expect: " << cases[i].expect << " actual output: " << result << " \n";
}
}
if (ok) {
cout << "ALL PASSED.";
}
return 0;
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <fstream>
#include <util/PlatformUtils.hpp>
#include <PlatformSupport/DOMStringHelper.hpp>
#include <DOMSupport/DOMSupportDefault.hpp>
#include <XPath/XObjectFactoryDefault.hpp>
#include <XPath/XPathSupportDefault.hpp>
#include <XPath/XPathFactoryDefault.hpp>
#include <XPath/XPathProcessorImpl.hpp>
#include <XercesPlatformSupport/XercesDOMPrintWriter.hpp>
#include <XercesPlatformSupport/TextFileOutputStream.hpp>
#include <XercesPlatformSupport/XercesStdTextOutputStream.hpp>
#include <XercesParserLiaison/XercesParserLiaison.hpp>
#include <XSLT/XSLTEngineImpl.hpp>
#include <XSLT/XSLTInputSource.hpp>
#include <XSLT/XSLTResultTarget.hpp>
#include <XSLT/StylesheetConstructionContextDefault.hpp>
#include <XSLT/StylesheetExecutionContextDefault.hpp>
#include <XSLT/TraceListenerDefault.hpp>
#include <XSLT/XSLTProcessorEnvSupportDefault.hpp>
int
main(
int argc,
const char* argv[])
{
#if !defined(XALAN_NO_NAMESPACES)
using std::auto_ptr;
using std::cerr;
using std::endl;
#endif
// TraceListener flags...
bool traceTemplates = false;
bool traceTemplateChildren = false;
bool traceGenerationEvent = false;
bool traceSelectionEvent = false;
if (argc < 2 || argc > 5)
{
cerr << "Usage: TraceListen [+ 1 or more of following] -TT -TG -TS -TTC" << endl;
return -1;
}
// Set the TraceListener flags...
for (int i = 1; i < argc; i ++)
{
if(!stricmp("-TT", argv[i]))
{
traceTemplates = true;
}
else if(!stricmp("-TG", argv[i]))
{
traceGenerationEvent = true;
}
else if(!stricmp("-TS", argv[i]))
{
traceSelectionEvent = true;
}
else if(!stricmp("-TTC", argv[i]))
{
traceTemplateChildren = true;
}
else
{
cerr << "Usage: TraceListen [+ 1 or more of following] -TT -TG -TS -TTC" << endl;
return -1;
}
}
try
{
// Call the static initializers...
XMLPlatformUtils::Initialize();
XSLTEngineImpl::Initialize();
// Create the support objects that are necessary for running the processor...
DOMSupportDefault theDOMSupport;
XercesParserLiaison theParserLiaison(theDOMSupport);
XPathSupportDefault theXPathSupport(theDOMSupport);
XSLTProcessorEnvSupportDefault theXSLTProcessorEnvSupport;
XObjectFactoryDefault theXObjectFactory;
XPathFactoryDefault theXPathFactory;
// Create a processor...
XSLTEngineImpl theProcessor(
theParserLiaison,
theXPathSupport,
theXSLTProcessorEnvSupport,
theXObjectFactory,
theXPathFactory);
// Connect the processor to the support object...
theXSLTProcessorEnvSupport.setProcessor(&theProcessor);
// Create a stylesheet construction context, and a stylesheet
// execution context...
StylesheetConstructionContextDefault theConstructionContext(
theProcessor,
theXSLTProcessorEnvSupport,
theXPathFactory);
StylesheetExecutionContextDefault theExecutionContext(
theProcessor,
theXSLTProcessorEnvSupport,
theXPathSupport,
theXObjectFactory);
// Our input files...The assumption is that the executable will be run
// from same directory as the input files.
const XalanDOMString theXMLFileName("birds.xml");
const XalanDOMString theXSLFileName("birds.xsl");
// Our input sources...
XSLTInputSource theInputSource(c_wstr(theXMLFileName));
XSLTInputSource theStylesheetSource(c_wstr(theXSLFileName));
// Our output target...
TextFileOutputStream theOutputStream("birds.out");
XercesDOMPrintWriter theResultWriter(theOutputStream);
XSLTResultTarget theResultTarget(&theResultWriter);
// Set up a diagnostic writer to be used by the TraceListener...
XercesStdTextOutputStream theStdErr(cerr);
XercesDOMPrintWriter diagnosticsWriter(theStdErr);
// Set up the TraceListener...
auto_ptr<TraceListener> theTraceListener(
new TraceListenerDefault(
diagnosticsWriter,
traceTemplates,
traceTemplateChildren,
traceGenerationEvent,
traceSelectionEvent));
// Add the TraceListener to the XSLT processor...
theProcessor.setTraceSelects(traceSelectionEvent);
theProcessor.addTraceListener(theTraceListener.get());
// Perform the transformation...
theProcessor.process(
theInputSource,
theStylesheetSource,
theResultTarget,
theConstructionContext,
theExecutionContext);
// Call the static terminators...
XMLPlatformUtils::Terminate();
XSLTEngineImpl::Terminate();
}
catch(...)
{
cerr << "Exception caught! Exiting..." << endl;
}
return 0;
}
<commit_msg>Made some minor changes to support UNIX platforms.<commit_after>// Base header file. Must be first.
#include <Include/PlatformDefinitions.hpp>
#include <iostream>
#include <fstream>
#include <util/PlatformUtils.hpp>
#include <PlatformSupport/DOMStringHelper.hpp>
#include <DOMSupport/DOMSupportDefault.hpp>
#include <XPath/XObjectFactoryDefault.hpp>
#include <XPath/XPathSupportDefault.hpp>
#include <XPath/XPathFactoryDefault.hpp>
#include <XPath/XPathProcessorImpl.hpp>
#include <XercesPlatformSupport/XercesDOMPrintWriter.hpp>
#include <XercesPlatformSupport/TextFileOutputStream.hpp>
#include <XercesPlatformSupport/XercesStdTextOutputStream.hpp>
#include <XercesParserLiaison/XercesParserLiaison.hpp>
#include <XSLT/XSLTEngineImpl.hpp>
#include <XSLT/XSLTInputSource.hpp>
#include <XSLT/XSLTResultTarget.hpp>
#include <XSLT/StylesheetConstructionContextDefault.hpp>
#include <XSLT/StylesheetExecutionContextDefault.hpp>
#include <XSLT/TraceListenerDefault.hpp>
#include <XSLT/XSLTProcessorEnvSupportDefault.hpp>
int
main(
int argc,
const char* argv[])
{
#if !defined(XALAN_NO_NAMESPACES)
using std::auto_ptr;
using std::cerr;
using std::endl;
#endif
// TraceListener flags...
bool traceTemplates = false;
bool traceTemplateChildren = false;
bool traceGenerationEvent = false;
bool traceSelectionEvent = false;
if (argc < 2 || argc > 5)
{
cerr << "Usage: TraceListen [+ 1 or more of following] -TT -TG -TS -TTC" << endl;
return -1;
}
// Set the TraceListener flags...
for (int i = 1; i < argc; i ++)
{
if(!stricmp("-TT", argv[i]))
{
traceTemplates = true;
}
else if(!stricmp("-TG", argv[i]))
{
traceGenerationEvent = true;
}
else if(!stricmp("-TS", argv[i]))
{
traceSelectionEvent = true;
}
else if(!stricmp("-TTC", argv[i]))
{
traceTemplateChildren = true;
}
else
{
cerr << "Usage: TraceListen [+ 1 or more of following] -TT -TG -TS -TTC" << endl;
return -1;
}
}
try
{
// Call the static initializers...
XMLPlatformUtils::Initialize();
XSLTEngineImpl::Initialize();
// Create the support objects that are necessary for running the processor...
DOMSupportDefault theDOMSupport;
XercesParserLiaison theParserLiaison(theDOMSupport);
XPathSupportDefault theXPathSupport(theDOMSupport);
XSLTProcessorEnvSupportDefault theXSLTProcessorEnvSupport;
XObjectFactoryDefault theXObjectFactory;
XPathFactoryDefault theXPathFactory;
// Create a processor...
XSLTEngineImpl theProcessor(
theParserLiaison,
theXPathSupport,
theXSLTProcessorEnvSupport,
theXObjectFactory,
theXPathFactory);
// Connect the processor to the support object...
theXSLTProcessorEnvSupport.setProcessor(&theProcessor);
// Create a stylesheet construction context, and a stylesheet
// execution context...
StylesheetConstructionContextDefault theConstructionContext(
theProcessor,
theXSLTProcessorEnvSupport,
theXPathFactory);
StylesheetExecutionContextDefault theExecutionContext(
theProcessor,
theXSLTProcessorEnvSupport,
theXPathSupport,
theXObjectFactory);
// Our input files...The assumption is that the executable will be run
// from same directory as the input files.
const XalanDOMString theXMLFileName("birds.xml");
const XalanDOMString theXSLFileName("birds.xsl");
// Our input sources...
XSLTInputSource theInputSource(c_wstr(theXMLFileName));
XSLTInputSource theStylesheetSource(c_wstr(theXSLFileName));
// Our output target...
TextFileOutputStream theOutputStream("birds.out");
XercesDOMPrintWriter theResultWriter(theOutputStream);
XSLTResultTarget theResultTarget(&theResultWriter);
// Set up a diagnostic writer to be used by the TraceListener...
XercesStdTextOutputStream theStdErr(cerr);
XercesDOMPrintWriter diagnosticsWriter(theStdErr);
// Set up the TraceListener...
TraceListenerDefault theTraceListener(
diagnosticsWriter,
traceTemplates,
traceTemplateChildren,
traceGenerationEvent,
traceSelectionEvent);
// Add the TraceListener to the XSLT processor...
theProcessor.setTraceSelects(traceSelectionEvent);
theProcessor.addTraceListener(&theTraceListener);
// Perform the transformation...
theProcessor.process(
theInputSource,
theStylesheetSource,
theResultTarget,
theConstructionContext,
theExecutionContext);
// Call the static terminators...
XMLPlatformUtils::Terminate();
XSLTEngineImpl::Terminate();
}
catch(...)
{
cerr << "Exception caught! Exiting..." << endl;
}
return 0;
}
<|endoftext|>
|
<commit_before>#include "NeuralNetwork.hpp"
#include "FAST/Data/Image.hpp"
#include "FAST/Algorithms/ImageResizer/ImageResizer.hpp"
#include <tensorflow/core/framework/step_stats.pb.h>
#include <tensorflow/core/framework/tensor.h>
#include <tensorflow/core/framework/types.pb.h>
#include <tensorflow/core/lib/strings/stringprintf.h>
#include <tensorflow/core/platform/env.h>
#include <tensorflow/core/platform/logging.h>
#include <tensorflow/core/platform/mutex.h>
#include <tensorflow/core/platform/types.h>
#include <tensorflow/core/public/session.h>
#include <tensorflow/core/graph/default_device.h>
namespace fast {
// See here for reference: https://github.com/tensorflow/tensorflow/blob/86f5ab7474825da756838b34e1b4eac93f5fc68a/tensorflow/contrib/android/jni/tensorflow_inference_jni.cc
void NeuralNetwork::load(std::string networkFilename) {
tensorflow::SessionOptions options;
tensorflow::ConfigProto &config = options.config;
mSession.reset(tensorflow::NewSession(options));
tensorflow::GraphDef tensorflow_graph;
ReadBinaryProto(tensorflow::Env::Default(), networkFilename, &tensorflow_graph);
reportInfo() << "Creating session." << reportEnd();
tensorflow::Status s = mSession->Create(tensorflow_graph);
if (!s.ok()) {
throw Exception("Could not create TensorFlow Graph");
}
//tensorflow::graph::SetDefaultDevice("/gpu:0", &tensorflow_graph);
// Clear the proto to save memory space.
tensorflow_graph.Clear();
reportInfo() << "TensorFlow graph loaded from: " << networkFilename << reportEnd();
mModelLoaded = true;
}
NeuralNetwork::NeuralNetwork() {
createInputPort<Image>(0, true, INPUT_STATIC_OR_DYNAMIC, true);
mModelLoaded = false;
mInputName = "";
mWidth = -1;
mHeight = -1;
createOpenCLProgram(std::string(FAST_SOURCE_DIR) + "Algorithms/NeuralNetwork/NeuralNetwork.cl");
}
void NeuralNetwork::execute() {
std::vector<Image::pointer> images = getMultipleStaticInputData<Image>();
if(mWidth < 0 || mHeight < 0)
throw Exception("Network input layer width and height has to be specified before running the network");
images = resizeImages(images);
executeNetwork(images);
}
void NeuralNetwork::setInputParameters(std::string inputNodeNames, int width, int height) {
mWidth = width;
mHeight = height;
mInputName = inputNodeNames;
}
std::vector<std::vector<float> > NeuralNetwork::getNetworkOutput() {
if(mOutputData.size() != 1)
throw Exception("If network has more than 1 output can't return network output without name.");
return mOutputData[mOutputNames[0]];
}
std::vector<std::vector<float> > NeuralNetwork::getNetworkOutput(std::string name) {
return mOutputData.at(name);
}
void NeuralNetwork::executeNetwork(const std::vector<Image::pointer>& images) {
if(!mModelLoaded)
throw Exception("Network and weights must be loaded in NeuralNetwork before execution.");
if(mInputName == "")
throw Exception("An input name must ge given to the NeuralNetwork before execution");
if(mOutputNames.size() == 0)
throw Exception("An output name must ge given to the NeuralNetwork before execution");
int batchSize = images.size();
if(batchSize == 0)
throw Exception("Need at least one image to execute network.");
// Create input tensor
tensorflow::Tensor input_tensor(
tensorflow::DT_FLOAT,
tensorflow::TensorShape({batchSize, mHeight, mWidth, 1})
);
auto input_tensor_mapped = input_tensor.tensor<float, 4>();
mRuntimeManager->startRegularTimer("input_data_copy");
reportInfo() << "TensorFlow: Copying Data." << reportEnd();
for(int n = 0; n < batchSize; ++n) {
Image::pointer image = images[n];
if (image->getWidth() != mWidth || image->getHeight() != mHeight)
throw Exception("Input image sent to executeNetwork was of incrorrect size");
ImageAccess::pointer access = image->getImageAccess(ACCESS_READ);
for (int i = 0; i < mHeight; ++i) { // y
for (int j = 0; j < mWidth; ++j) { // x
input_tensor_mapped(n, i, j, 0) = access->getScalar(Vector2i(j, i)) / 255.0f;
}
}
}
mRuntimeManager->stopRegularTimer("input_data_copy");
// TODO Need to know names of inputs and outputs in advance
// Input: Only single for now
// Output: Can be multiple
// Create a scalar tensor which tells the system we are NOT doing training
tensorflow::Tensor input_tensor2(
tensorflow::DT_BOOL,
tensorflow::TensorShape() // Scalar
);
auto input_tensor_mapped2 = input_tensor2.tensor<bool, 0>();
input_tensor_mapped2(0) = false;
std::vector <std::pair<std::string, tensorflow::Tensor>> input_tensors(
{{mInputName, input_tensor}, {"keras_learning_phase", input_tensor2}});
std::vector <tensorflow::Tensor> output_tensors;
tensorflow::Status s;
mRuntimeManager->startRegularTimer("network_execution");
s = mSession->Run(input_tensors, mOutputNames, {}, &output_tensors);
mRuntimeManager->stopRegularTimer("network_execution");
if (!s.ok()) {
reportError() << "Error during inference: " << s << reportEnd();
}
reportInfo() << "Finished executing network" << reportEnd();
for(int j = 0; j < mOutputNames.size(); ++j) {
tensorflow::Tensor *output = &output_tensors[j];
std::string outputName = mOutputNames[j];
//const auto outputData = output->flat<float>(); // This is some sort of Eigen tensor type
auto output_tensor_mapped = output->tensor<float, 2>();
std::vector<std::vector<float>> resultData;
for(int n = 0; n < batchSize; ++n) {
std::vector<float> outputValues;
for (int i = 0; i < output_tensor_mapped.dimension(1); ++i) {
outputValues.push_back(output_tensor_mapped(0, i));
}
resultData.push_back(outputValues);
}
mOutputData[outputName] = resultData;
}
reportInfo() << "Finished parsing output" << reportEnd();
}
std::vector<SharedPointer<Image>> NeuralNetwork::resizeImages(const std::vector<SharedPointer<Image>> &images) {
reportInfo() << "Resizing images.." << reportEnd();
std::vector<Image::pointer> resizedImages;
for(Image::pointer image : images) {
// Resize image to fit input layer
if(mWidth != image->getWidth() || mHeight != image->getHeight()) {
// Only resize if needed
ImageResizer::pointer resizer = ImageResizer::New();
resizer->setWidth(mWidth);
resizer->setHeight(mHeight);
resizer->setInputData(image);
resizer->update();
Image::pointer resizedImage = resizer->getOutputData<Image>();
resizedImages.push_back(resizedImage);
} else {
resizedImages.push_back(image);
}
}
return resizedImages;
}
};
<commit_msg>Check if tensorflow graph file is loaded properly<commit_after>#include "NeuralNetwork.hpp"
#include "FAST/Data/Image.hpp"
#include "FAST/Algorithms/ImageResizer/ImageResizer.hpp"
#include <tensorflow/core/framework/step_stats.pb.h>
#include <tensorflow/core/framework/tensor.h>
#include <tensorflow/core/framework/types.pb.h>
#include <tensorflow/core/lib/strings/stringprintf.h>
#include <tensorflow/core/platform/env.h>
#include <tensorflow/core/platform/logging.h>
#include <tensorflow/core/platform/mutex.h>
#include <tensorflow/core/platform/types.h>
#include <tensorflow/core/public/session.h>
#include <tensorflow/core/graph/default_device.h>
namespace fast {
// See here for reference: https://github.com/tensorflow/tensorflow/blob/86f5ab7474825da756838b34e1b4eac93f5fc68a/tensorflow/contrib/android/jni/tensorflow_inference_jni.cc
void NeuralNetwork::load(std::string networkFilename) {
tensorflow::SessionOptions options;
tensorflow::ConfigProto &config = options.config;
mSession.reset(tensorflow::NewSession(options));
tensorflow::GraphDef tensorflow_graph;
{
tensorflow::Status s = ReadBinaryProto(tensorflow::Env::Default(), networkFilename, &tensorflow_graph);
if (!s.ok()) {
throw Exception("Could not read TensorFlow graph file " + networkFilename);
}
}
reportInfo() << "Creating session." << reportEnd();
tensorflow::Status s = mSession->Create(tensorflow_graph);
if (!s.ok()) {
throw Exception("Could not create TensorFlow Graph");
}
//tensorflow::graph::SetDefaultDevice("/gpu:0", &tensorflow_graph);
// Clear the proto to save memory space.
tensorflow_graph.Clear();
reportInfo() << "TensorFlow graph loaded from: " << networkFilename << reportEnd();
mModelLoaded = true;
}
NeuralNetwork::NeuralNetwork() {
createInputPort<Image>(0, true, INPUT_STATIC_OR_DYNAMIC, true);
mModelLoaded = false;
mInputName = "";
mWidth = -1;
mHeight = -1;
createOpenCLProgram(std::string(FAST_SOURCE_DIR) + "Algorithms/NeuralNetwork/NeuralNetwork.cl");
}
void NeuralNetwork::execute() {
std::vector<Image::pointer> images = getMultipleStaticInputData<Image>();
if(mWidth < 0 || mHeight < 0)
throw Exception("Network input layer width and height has to be specified before running the network");
images = resizeImages(images);
executeNetwork(images);
}
void NeuralNetwork::setInputParameters(std::string inputNodeNames, int width, int height) {
mWidth = width;
mHeight = height;
mInputName = inputNodeNames;
}
std::vector<std::vector<float> > NeuralNetwork::getNetworkOutput() {
if(mOutputData.size() != 1)
throw Exception("If network has more than 1 output can't return network output without name.");
return mOutputData[mOutputNames[0]];
}
std::vector<std::vector<float> > NeuralNetwork::getNetworkOutput(std::string name) {
return mOutputData.at(name);
}
void NeuralNetwork::executeNetwork(const std::vector<Image::pointer>& images) {
if(!mModelLoaded)
throw Exception("Network and weights must be loaded in NeuralNetwork before execution.");
if(mInputName == "")
throw Exception("An input name must ge given to the NeuralNetwork before execution");
if(mOutputNames.size() == 0)
throw Exception("An output name must ge given to the NeuralNetwork before execution");
int batchSize = images.size();
if(batchSize == 0)
throw Exception("Need at least one image to execute network.");
// Create input tensor
tensorflow::Tensor input_tensor(
tensorflow::DT_FLOAT,
tensorflow::TensorShape({batchSize, mHeight, mWidth, 1})
);
auto input_tensor_mapped = input_tensor.tensor<float, 4>();
mRuntimeManager->startRegularTimer("input_data_copy");
reportInfo() << "TensorFlow: Copying Data." << reportEnd();
for(int n = 0; n < batchSize; ++n) {
Image::pointer image = images[n];
if (image->getWidth() != mWidth || image->getHeight() != mHeight)
throw Exception("Input image sent to executeNetwork was of incrorrect size");
ImageAccess::pointer access = image->getImageAccess(ACCESS_READ);
for (int i = 0; i < mHeight; ++i) { // y
for (int j = 0; j < mWidth; ++j) { // x
input_tensor_mapped(n, i, j, 0) = access->getScalar(Vector2i(j, i)) / 255.0f;
}
}
}
mRuntimeManager->stopRegularTimer("input_data_copy");
// TODO Need to know names of inputs and outputs in advance
// Input: Only single for now
// Output: Can be multiple
// Create a scalar tensor which tells the system we are NOT doing training
tensorflow::Tensor input_tensor2(
tensorflow::DT_BOOL,
tensorflow::TensorShape() // Scalar
);
auto input_tensor_mapped2 = input_tensor2.tensor<bool, 0>();
input_tensor_mapped2(0) = false;
std::vector <std::pair<std::string, tensorflow::Tensor>> input_tensors(
{{mInputName, input_tensor}, {"keras_learning_phase", input_tensor2}});
std::vector <tensorflow::Tensor> output_tensors;
tensorflow::Status s;
mRuntimeManager->startRegularTimer("network_execution");
s = mSession->Run(input_tensors, mOutputNames, {}, &output_tensors);
mRuntimeManager->stopRegularTimer("network_execution");
if (!s.ok()) {
reportError() << "Error during inference: " << s << reportEnd();
}
reportInfo() << "Finished executing network" << reportEnd();
for(int j = 0; j < mOutputNames.size(); ++j) {
tensorflow::Tensor *output = &output_tensors[j];
std::string outputName = mOutputNames[j];
//const auto outputData = output->flat<float>(); // This is some sort of Eigen tensor type
auto output_tensor_mapped = output->tensor<float, 2>();
std::vector<std::vector<float>> resultData;
for(int n = 0; n < batchSize; ++n) {
std::vector<float> outputValues;
for (int i = 0; i < output_tensor_mapped.dimension(1); ++i) {
outputValues.push_back(output_tensor_mapped(0, i));
}
resultData.push_back(outputValues);
}
mOutputData[outputName] = resultData;
}
reportInfo() << "Finished parsing output" << reportEnd();
}
std::vector<SharedPointer<Image>> NeuralNetwork::resizeImages(const std::vector<SharedPointer<Image>> &images) {
reportInfo() << "Resizing images.." << reportEnd();
std::vector<Image::pointer> resizedImages;
for(Image::pointer image : images) {
// Resize image to fit input layer
if(mWidth != image->getWidth() || mHeight != image->getHeight()) {
// Only resize if needed
ImageResizer::pointer resizer = ImageResizer::New();
resizer->setWidth(mWidth);
resizer->setHeight(mHeight);
resizer->setInputData(image);
resizer->update();
Image::pointer resizedImage = resizer->getOutputData<Image>();
resizedImages.push_back(resizedImage);
} else {
resizedImages.push_back(image);
}
}
return resizedImages;
}
};
<|endoftext|>
|
<commit_before>/***************************************************************************
* Copyright (C) 2007 by Tobias Koenig <tokoe@kde.org> *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU Library General Public License as *
* published by the Free Software Foundation; either version 2 of the *
* License, or (at your option) any later version. *
* *
* This 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 Library 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 <QtCore/QCoreApplication>
#include <QtCore/QDebug>
#include <QtCore/QString>
#include <QtCore/QStringList>
#include <QtDBus/QDBusConnection>
#include <QtDBus/QDBusConnectionInterface>
#include "akapplication.h"
#include "protocol_p.h"
#include "controlmanagerinterface.h"
#include "akonadistarter.h"
#include <unistd.h>
static bool startServer()
{
if ( QDBusConnection::sessionBus().interface()->isServiceRegistered( AKONADI_DBUS_CONTROL_SERVICE )
|| QDBusConnection::sessionBus().interface()->isServiceRegistered( AKONADI_DBUS_SERVER_SERVICE ) ) {
qDebug() << "Akonadi is already running.";
return false;
}
AkonadiStarter starter;
return starter.start();
}
static bool stopServer()
{
org::freedesktop::Akonadi::ControlManager iface( AKONADI_DBUS_CONTROL_SERVICE, "/ControlManager", QDBusConnection::sessionBus(), 0 );
iface.shutdown();
return true;
}
static bool statusServer()
{
bool registered = QDBusConnection::sessionBus().interface()->isServiceRegistered( AKONADI_DBUS_CONTROL_SERVICE );
qDebug( "Akonadi Control: %s", registered ? "running" : "stopped" );
registered = QDBusConnection::sessionBus().interface()->isServiceRegistered( AKONADI_DBUS_SERVER_SERVICE );
qDebug( "Akonadi Server: %s", registered ? "running" : "stopped" );
return true;
}
int main( int argc, char **argv )
{
AkApplication app( argc, argv );
app.setDescription( "Akonadi server manipulation tool\n"
"Usage: akonadictl [command]\n\n"
"Commands:\n"
" start : Starts the Akonadi server with all its processes\n"
" stop : Stops the Akonadi server and all its processes cleanly\n"
" status : Shows a status overview of the Akonadi server\n"
" restart : Restart the Akonadi"
);
app.parseCommandLine();
QString optionsList;
optionsList.append( QLatin1String( "start" ) );
optionsList.append( QLatin1String( "stop" ) );
optionsList.append( QLatin1String( "status" ) );
optionsList.append( QLatin1String( "restart" ) );
const QStringList arguments = app.arguments();
if ( arguments.count() != 2 ) {
app.printUsage();
return 1;
} else if ( !optionsList.contains( arguments[ 1 ] ) ) {
app.printUsage();
return 2;
}
if ( arguments[ 1 ] == QLatin1String( "start" ) ) {
if ( !startServer() )
return 3;
} else if ( arguments[ 1 ] == QLatin1String( "stop" ) ) {
if ( !stopServer() )
return 4;
} else if ( arguments[ 1 ] == QLatin1String( "status" ) ) {
if ( !statusServer() )
return 5;
} else if ( arguments[ 1 ] == QLatin1String( "restart") ) {
if ( !stopServer() )
return 4;
else {
do {
usleep(100000);
} while( QDBusConnection::sessionBus().interface()->isServiceRegistered( AKONADI_DBUS_CONTROL_SERVICE ) );
if ( !startServer() )
return 3;
}
}
return 0;
}
<commit_msg>Oops ... let me try again<commit_after>/***************************************************************************
* Copyright (C) 2007 by Tobias Koenig <tokoe@kde.org> *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU Library General Public License as *
* published by the Free Software Foundation; either version 2 of the *
* License, or (at your option) any later version. *
* *
* This 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 Library 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 <QtCore/QCoreApplication>
#include <QtCore/QDebug>
#include <QtCore/QString>
#include <QtCore/QStringList>
#include <QtDBus/QDBusConnection>
#include <QtDBus/QDBusConnectionInterface>
#include "akapplication.h"
#include "protocol_p.h"
#include "controlmanagerinterface.h"
#include "akonadistarter.h"
#include <unistd.h>
static bool startServer()
{
if ( QDBusConnection::sessionBus().interface()->isServiceRegistered( AKONADI_DBUS_CONTROL_SERVICE )
|| QDBusConnection::sessionBus().interface()->isServiceRegistered( AKONADI_DBUS_SERVER_SERVICE ) ) {
qDebug() << "Akonadi is already running.";
return false;
}
AkonadiStarter starter;
return starter.start();
}
static bool stopServer()
{
org::freedesktop::Akonadi::ControlManager iface( AKONADI_DBUS_CONTROL_SERVICE, "/ControlManager", QDBusConnection::sessionBus(), 0 );
iface.shutdown();
return true;
}
static bool statusServer()
{
bool registered = QDBusConnection::sessionBus().interface()->isServiceRegistered( AKONADI_DBUS_CONTROL_SERVICE );
qDebug( "Akonadi Control: %s", registered ? "running" : "stopped" );
registered = QDBusConnection::sessionBus().interface()->isServiceRegistered( AKONADI_DBUS_SERVER_SERVICE );
qDebug( "Akonadi Server: %s", registered ? "running" : "stopped" );
return true;
}
int main( int argc, char **argv )
{
AkApplication app( argc, argv );
app.setDescription( "Akonadi server manipulation tool\n"
"Usage: akonadictl [command]\n\n"
"Commands:\n"
" start : Starts the Akonadi server with all its processes\n"
" stop : Stops the Akonadi server and all its processes cleanly\n"
" restart : Restart Akonadi server with all its processes\n"
" status : Shows a status overview of the Akonadi server"
);
app.parseCommandLine();
QString optionsList;
optionsList.append( QLatin1String( "start" ) );
optionsList.append( QLatin1String( "stop" ) );
optionsList.append( QLatin1String( "status" ) );
optionsList.append( QLatin1String( "restart" ) );
const QStringList arguments = app.arguments();
if ( arguments.count() != 2 ) {
app.printUsage();
return 1;
} else if ( !optionsList.contains( arguments[ 1 ] ) ) {
app.printUsage();
return 2;
}
if ( arguments[ 1 ] == QLatin1String( "start" ) ) {
if ( !startServer() )
return 3;
} else if ( arguments[ 1 ] == QLatin1String( "stop" ) ) {
if ( !stopServer() )
return 4;
} else if ( arguments[ 1 ] == QLatin1String( "status" ) ) {
if ( !statusServer() )
return 5;
} else if ( arguments[ 1 ] == QLatin1String( "restart") ) {
if ( !stopServer() )
return 4;
else {
do {
usleep(100000);
} while( QDBusConnection::sessionBus().interface()->isServiceRegistered( AKONADI_DBUS_CONTROL_SERVICE ) );
if ( !startServer() )
return 3;
}
}
return 0;
}
<|endoftext|>
|
<commit_before>/*
* (C) Copyright 2015 Kurento (http://kurento.org/)
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser General Public License
* (LGPL) version 2.1 which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/lgpl-2.1.html
*
* 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.
*
*/
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE WebRtcEndpoint
#include <boost/test/unit_test.hpp>
#include <MediaPipelineImpl.hpp>
#include <objects/WebRtcEndpointImpl.hpp>
#include <IceCandidate.hpp>
#include <mutex>
#include <condition_variable>
#include <ModuleManager.hpp>
#include <KurentoException.hpp>
#include <MediaSet.hpp>
using namespace kurento;
boost::property_tree::ptree config;
std::string mediaPipelineId;
ModuleManager moduleManager;
std::once_flag init_flag;
static void
init_internal()
{
boost::property_tree::ptree ac, audioCodecs, vc, videoCodecs;
gst_init (NULL, NULL);
moduleManager.loadModulesFromDirectories ("../../src/server");
config.add ("configPath", "../../../tests" );
config.add ("modules.kurento.SdpEndpoint.numAudioMedias", 1);
config.add ("modules.kurento.SdpEndpoint.numVideoMedias", 1);
ac.put ("name", "opus/48000/2");
audioCodecs.push_back (std::make_pair ("", ac) );
config.add_child ("modules.kurento.SdpEndpoint.audioCodecs", audioCodecs);
vc.put ("name", "VP8/90000");
videoCodecs.push_back (std::make_pair ("", vc) );
config.add_child ("modules.kurento.SdpEndpoint.videoCodecs", videoCodecs);
mediaPipelineId = moduleManager.getFactory ("MediaPipeline")->createObject (
config, "",
Json::Value() )->getId();
}
static void
init()
{
std::call_once (init_flag, init_internal);
}
static std::shared_ptr <WebRtcEndpointImpl>
createWebrtc (void)
{
std::shared_ptr <kurento::MediaObjectImpl> webrtcEndpoint;
Json::Value constructorParams;
constructorParams ["mediaPipeline"] = mediaPipelineId;
webrtcEndpoint = moduleManager.getFactory ("WebRtcEndpoint")->createObject (
config, "",
constructorParams );
return std::dynamic_pointer_cast <WebRtcEndpointImpl> (webrtcEndpoint);
}
static void
releaseWebRtc (std::shared_ptr<WebRtcEndpointImpl> &ep)
{
std::string id = ep->getId();
ep.reset();
MediaSet::getMediaSet ()->release (id);
}
BOOST_AUTO_TEST_CASE (gathering_done)
{
init ();
std::atomic<bool> gathering_done (false);
std::condition_variable cv;
std::mutex mtx;
std::unique_lock<std::mutex> lck (mtx);
std::shared_ptr <WebRtcEndpointImpl> webRtcEp = createWebrtc();
webRtcEp->signalOnIceGatheringDone.connect ([&] (OnIceGatheringDone event) {
gathering_done = true;
cv.notify_one();
});
webRtcEp->generateOffer ();
webRtcEp->gatherCandidates ();
cv.wait_for (lck, std::chrono::seconds (5), [&] () {
return gathering_done.load();
});
if (!gathering_done) {
BOOST_ERROR ("Gathering not done");
}
releaseWebRtc (webRtcEp);
}
BOOST_AUTO_TEST_CASE (ice_state_changes)
{
init ();
std::atomic<bool> ice_state_changed (false);
std::condition_variable cv;
std::mutex mtx;
std::unique_lock<std::mutex> lck (mtx);
std::shared_ptr <WebRtcEndpointImpl> webRtcEpOfferer = createWebrtc();
std::shared_ptr <WebRtcEndpointImpl> webRtcEpAnswerer = createWebrtc();
webRtcEpOfferer->setName ("offerer");
webRtcEpAnswerer->setName ("answerer");
webRtcEpOfferer->signalOnIceCandidate.connect ([&] (OnIceCandidate event) {
webRtcEpAnswerer->addIceCandidate (event.getCandidate() );
});
webRtcEpAnswerer->signalOnIceCandidate.connect ([&] (OnIceCandidate event) {
webRtcEpOfferer->addIceCandidate (event.getCandidate() );
});
webRtcEpOfferer->signalOnIceComponentStateChanged.connect ([&] (
OnIceComponentStateChanged event) {
ice_state_changed = true;
cv.notify_one();
});
std::string offer = webRtcEpOfferer->generateOffer ();
std::string answer = webRtcEpAnswerer->processOffer (offer);
webRtcEpOfferer->processAnswer (answer);
webRtcEpOfferer->gatherCandidates ();
webRtcEpAnswerer->gatherCandidates ();
cv.wait_for (lck, std::chrono::seconds (5), [&] () {
return ice_state_changed.load();
});
if (!ice_state_changed) {
BOOST_ERROR ("ICE state not chagned");
}
releaseWebRtc (webRtcEpOfferer);
releaseWebRtc (webRtcEpAnswerer);
}
BOOST_AUTO_TEST_CASE (stun_turn_properties)
{
std::string stunServerAddress ("10.0.0.1");
int stunServerPort = 2345;
std::string turnUrl ("user0:pass0@10.0.0.2:3456");
init ();
std::shared_ptr <WebRtcEndpointImpl> webRtcEp = createWebrtc();
webRtcEp->setStunServerAddress (stunServerAddress);
std::string stunServerAddressRet = webRtcEp->getStunServerAddress ();
BOOST_CHECK (stunServerAddressRet == stunServerAddress);
webRtcEp->setStunServerPort (stunServerPort);
int stunServerPortRet = webRtcEp->getStunServerPort ();
BOOST_CHECK (stunServerPortRet == stunServerPort);
webRtcEp->setTurnUrl (turnUrl);
std::string turnUrlRet = webRtcEp->getTurnUrl ();
BOOST_CHECK (turnUrlRet == turnUrl);
releaseWebRtc (webRtcEp);
}
<commit_msg>webRtcEndpoint: Test media flow through WebRTC<commit_after>/*
* (C) Copyright 2015 Kurento (http://kurento.org/)
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser General Public License
* (LGPL) version 2.1 which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/lgpl-2.1.html
*
* 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.
*
*/
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE WebRtcEndpoint
#include <boost/test/unit_test.hpp>
#include <MediaPipelineImpl.hpp>
#include <objects/WebRtcEndpointImpl.hpp>
#include <IceCandidate.hpp>
#include <mutex>
#include <condition_variable>
#include <ModuleManager.hpp>
#include <KurentoException.hpp>
#include <MediaSet.hpp>
#include <MediaElementImpl.hpp>
using namespace kurento;
boost::property_tree::ptree config;
std::string mediaPipelineId;
ModuleManager moduleManager;
std::once_flag init_flag;
static void
init_internal()
{
boost::property_tree::ptree ac, audioCodecs, vc, videoCodecs;
gst_init (NULL, NULL);
moduleManager.loadModulesFromDirectories ("../../src/server");
config.add ("configPath", "../../../tests" );
config.add ("modules.kurento.SdpEndpoint.numAudioMedias", 1);
config.add ("modules.kurento.SdpEndpoint.numVideoMedias", 1);
ac.put ("name", "opus/48000/2");
audioCodecs.push_back (std::make_pair ("", ac) );
config.add_child ("modules.kurento.SdpEndpoint.audioCodecs", audioCodecs);
vc.put ("name", "VP8/90000");
videoCodecs.push_back (std::make_pair ("", vc) );
config.add_child ("modules.kurento.SdpEndpoint.videoCodecs", videoCodecs);
mediaPipelineId = moduleManager.getFactory ("MediaPipeline")->createObject (
config, "",
Json::Value() )->getId();
}
static void
init()
{
std::call_once (init_flag, init_internal);
}
static std::shared_ptr <WebRtcEndpointImpl>
createWebrtc (void)
{
std::shared_ptr <kurento::MediaObjectImpl> webrtcEndpoint;
Json::Value constructorParams;
constructorParams ["mediaPipeline"] = mediaPipelineId;
webrtcEndpoint = moduleManager.getFactory ("WebRtcEndpoint")->createObject (
config, "",
constructorParams );
return std::dynamic_pointer_cast <WebRtcEndpointImpl> (webrtcEndpoint);
}
static void
releaseWebRtc (std::shared_ptr<WebRtcEndpointImpl> &ep)
{
std::string id = ep->getId();
ep.reset();
MediaSet::getMediaSet ()->release (id);
}
static std::shared_ptr <MediaElementImpl>
createTestSrc (void)
{
std::shared_ptr <MediaElementImpl> src = std::dynamic_pointer_cast
<MediaElementImpl> (MediaSet::getMediaSet()->ref (new MediaElementImpl (
boost::property_tree::ptree(),
MediaSet::getMediaSet()->getMediaObject (mediaPipelineId),
"dummysrc") ) );
g_object_set (src->getGstreamerElement(), "audio", TRUE, "video", TRUE, NULL);
return std::dynamic_pointer_cast <MediaElementImpl> (src);
}
static void
releaseTestSrc (std::shared_ptr<MediaElementImpl> &ep)
{
std::string id = ep->getId();
ep.reset();
MediaSet::getMediaSet ()->release (id);
}
BOOST_AUTO_TEST_CASE (gathering_done)
{
init ();
std::atomic<bool> gathering_done (false);
std::condition_variable cv;
std::mutex mtx;
std::unique_lock<std::mutex> lck (mtx);
std::shared_ptr <WebRtcEndpointImpl> webRtcEp = createWebrtc();
webRtcEp->signalOnIceGatheringDone.connect ([&] (OnIceGatheringDone event) {
gathering_done = true;
cv.notify_one();
});
webRtcEp->generateOffer ();
webRtcEp->gatherCandidates ();
cv.wait_for (lck, std::chrono::seconds (5), [&] () {
return gathering_done.load();
});
if (!gathering_done) {
BOOST_ERROR ("Gathering not done");
}
releaseWebRtc (webRtcEp);
}
BOOST_AUTO_TEST_CASE (ice_state_changes)
{
init ();
std::atomic<bool> ice_state_changed (false);
std::condition_variable cv;
std::mutex mtx;
std::unique_lock<std::mutex> lck (mtx);
std::shared_ptr <WebRtcEndpointImpl> webRtcEpOfferer = createWebrtc();
std::shared_ptr <WebRtcEndpointImpl> webRtcEpAnswerer = createWebrtc();
webRtcEpOfferer->setName ("offerer");
webRtcEpAnswerer->setName ("answerer");
webRtcEpOfferer->signalOnIceCandidate.connect ([&] (OnIceCandidate event) {
webRtcEpAnswerer->addIceCandidate (event.getCandidate() );
});
webRtcEpAnswerer->signalOnIceCandidate.connect ([&] (OnIceCandidate event) {
webRtcEpOfferer->addIceCandidate (event.getCandidate() );
});
webRtcEpOfferer->signalOnIceComponentStateChanged.connect ([&] (
OnIceComponentStateChanged event) {
ice_state_changed = true;
cv.notify_one();
});
std::string offer = webRtcEpOfferer->generateOffer ();
std::string answer = webRtcEpAnswerer->processOffer (offer);
webRtcEpOfferer->processAnswer (answer);
webRtcEpOfferer->gatherCandidates ();
webRtcEpAnswerer->gatherCandidates ();
cv.wait_for (lck, std::chrono::seconds (5), [&] () {
return ice_state_changed.load();
});
if (!ice_state_changed) {
BOOST_ERROR ("ICE state not chagned");
}
releaseWebRtc (webRtcEpOfferer);
releaseWebRtc (webRtcEpAnswerer);
}
BOOST_AUTO_TEST_CASE (stun_turn_properties)
{
std::string stunServerAddress ("10.0.0.1");
int stunServerPort = 2345;
std::string turnUrl ("user0:pass0@10.0.0.2:3456");
init ();
std::shared_ptr <WebRtcEndpointImpl> webRtcEp = createWebrtc();
webRtcEp->setStunServerAddress (stunServerAddress);
std::string stunServerAddressRet = webRtcEp->getStunServerAddress ();
BOOST_CHECK (stunServerAddressRet == stunServerAddress);
webRtcEp->setStunServerPort (stunServerPort);
int stunServerPortRet = webRtcEp->getStunServerPort ();
BOOST_CHECK (stunServerPortRet == stunServerPort);
webRtcEp->setTurnUrl (turnUrl);
std::string turnUrlRet = webRtcEp->getTurnUrl ();
BOOST_CHECK (turnUrlRet == turnUrl);
releaseWebRtc (webRtcEp);
}
BOOST_AUTO_TEST_CASE (media_state_changes)
{
std::atomic<bool> media_state_changed (false);
std::condition_variable cv;
std::mutex mtx;
std::unique_lock<std::mutex> lck (mtx);
init ();
std::shared_ptr <WebRtcEndpointImpl> webRtcEpOfferer = createWebrtc();
std::shared_ptr <WebRtcEndpointImpl> webRtcEpAnswerer = createWebrtc();
std::shared_ptr <MediaElementImpl> src = createTestSrc();
src->connect (webRtcEpOfferer);
webRtcEpOfferer->signalOnIceCandidate.connect ([&] (OnIceCandidate event) {
BOOST_TEST_MESSAGE ("Offerer: adding candidate " +
event.getCandidate()->getCandidate() );
webRtcEpAnswerer->addIceCandidate (event.getCandidate() );
});
webRtcEpAnswerer->signalOnIceCandidate.connect ([&] (OnIceCandidate event) {
BOOST_TEST_MESSAGE ("Answerer: adding candidate " +
event.getCandidate()->getCandidate() );
webRtcEpOfferer->addIceCandidate (event.getCandidate() );
});
webRtcEpOfferer->signalOnIceGatheringDone.connect ([&] (
OnIceGatheringDone event) {
BOOST_TEST_MESSAGE ("Offerer: Gathering done");
});
webRtcEpAnswerer->signalOnIceGatheringDone.connect ([&] (
OnIceGatheringDone event) {
BOOST_TEST_MESSAGE ("Answerer: Gathering done");
});
webRtcEpAnswerer->signalMediaStateChanged.connect ([&] (
MediaStateChanged event) {
media_state_changed = true;
cv.notify_one();
});
std::string offer = webRtcEpOfferer->generateOffer ();
BOOST_TEST_MESSAGE ("offer: " + offer);
std::string answer = webRtcEpAnswerer->processOffer (offer);
BOOST_TEST_MESSAGE ("answer: " + answer);
webRtcEpOfferer->processAnswer (answer);
webRtcEpOfferer->gatherCandidates ();
webRtcEpAnswerer->gatherCandidates ();
cv.wait_for (lck, std::chrono::seconds (5), [&] () {
return media_state_changed.load();
});
if (!media_state_changed) {
BOOST_ERROR ("Not media state chagned");
}
releaseTestSrc (src);
releaseWebRtc (webRtcEpOfferer);
releaseWebRtc (webRtcEpAnswerer);
}
<|endoftext|>
|
<commit_before><commit_msg>Mark NPAPITesterBase.GetURLRedirectNotification test as flaky on linux.<commit_after><|endoftext|>
|
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/file_util.h"
#include "base/path_service.h"
#include "build/build_config.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "net/base/net_util.h"
#include "net/test/test_server.h"
#include "webkit/glue/plugins/plugin_switches.h"
namespace {
// Platform-specific filename relative to the chrome executable.
#if defined(OS_WIN)
const wchar_t library_name[] = L"ppapi_tests.dll";
#elif defined(OS_MACOSX)
const char library_name[] = "ppapi_tests.plugin";
#elif defined(OS_POSIX)
const char library_name[] = "libppapi_tests.so";
#endif
} // namespace
class PPAPITest : public UITest {
public:
PPAPITest() {
// Append the switch to register the pepper plugin.
// library name = <out dir>/<test_name>.<library_extension>
// MIME type = application/x-ppapi-<test_name>
FilePath plugin_dir;
PathService::Get(base::DIR_EXE, &plugin_dir);
FilePath plugin_lib = plugin_dir.Append(library_name);
EXPECT_TRUE(file_util::PathExists(plugin_lib));
FilePath::StringType pepper_plugin = plugin_lib.value();
pepper_plugin.append(FILE_PATH_LITERAL(";application/x-ppapi-tests"));
launch_arguments_.AppendSwitchNative(switches::kRegisterPepperPlugins,
pepper_plugin);
// The test sends us the result via a cookie.
launch_arguments_.AppendSwitch(switches::kEnableFileCookies);
// Some stuff is hung off of the testing interface which is not enabled
// by default.
launch_arguments_.AppendSwitch(switches::kEnablePepperTesting);
// Give unlimited quota for files to Pepper tests.
// TODO(dumi): remove this switch once we have a quota management
// system in place.
launch_arguments_.AppendSwitch(switches::kUnlimitedQuotaForFiles);
}
void RunTest(const std::string& test_case) {
FilePath test_path;
PathService::Get(base::DIR_SOURCE_ROOT, &test_path);
test_path = test_path.Append(FILE_PATH_LITERAL("ppapi"));
test_path = test_path.Append(FILE_PATH_LITERAL("tests"));
test_path = test_path.Append(FILE_PATH_LITERAL("test_case.html"));
// Sanity check the file name.
EXPECT_TRUE(file_util::PathExists(test_path));
GURL::Replacements replacements;
replacements.SetQuery(test_case.c_str(),
url_parse::Component(0, test_case.size()));
GURL test_url = net::FilePathToFileURL(test_path);
RunTestURL(test_url.ReplaceComponents(replacements));
}
void RunTestViaHTTP(const std::string& test_case) {
net::TestServer test_server(
net::TestServer::TYPE_HTTP,
FilePath(FILE_PATH_LITERAL("third_party/ppapi/tests")));
ASSERT_TRUE(test_server.Start());
RunTestURL(test_server.GetURL("files/test_case.html?" + test_case));
}
private:
void RunTestURL(const GURL& test_url) {
scoped_refptr<TabProxy> tab(GetActiveTab());
ASSERT_TRUE(tab.get());
ASSERT_TRUE(tab->NavigateToURL(test_url));
std::string escaped_value =
WaitUntilCookieNonEmpty(tab.get(), test_url,
"COMPLETION_COOKIE", action_max_timeout_ms());
EXPECT_STREQ("PASS", escaped_value.c_str());
}
};
TEST_F(PPAPITest, FAILS_Instance) {
RunTest("Instance");
}
TEST_F(PPAPITest, Graphics2D) {
RunTest("Graphics2D");
}
// TODO(brettw) bug 51344: this is flaky on bots. Seems to timeout navigating.
// Possibly all the image allocations slow things down on a loaded bot too much.
TEST_F(PPAPITest, FLAKY_ImageData) {
RunTest("ImageData");
}
TEST_F(PPAPITest, Buffer) {
RunTest("Buffer");
}
// http://bugs.chromium.org/51345
TEST_F(PPAPITest, DISABLED_URLLoader) {
RunTestViaHTTP("URLLoader");
}
// Flaky, http://crbug.com/51012
TEST_F(PPAPITest, FLAKY_PaintAggregator) {
RunTestViaHTTP("PaintAggregator");
}
// Flaky, http://crbug.com/48544.
TEST_F(PPAPITest, FLAKY_Scrollbar) {
RunTest("Scrollbar");
}
TEST_F(PPAPITest, UrlUtil) {
RunTest("UrlUtil");
}
TEST_F(PPAPITest, CharSet) {
RunTest("CharSet");
}
TEST_F(PPAPITest, Var) {
RunTest("Var");
}
TEST_F(PPAPITest, FileRef) {
RunTestViaHTTP("FileRef");
}
TEST_F(PPAPITest, FileIO) {
RunTestViaHTTP("FileIO");
}
TEST_F(PPAPITest, DirectoryReader) {
RunTestViaHTTP("DirectoryReader");
}
<commit_msg>Remove FileRef, FileIO and DirectoryReader PPAPI tests from ui_tests for now. It looks like run_testserver is crashing.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/file_util.h"
#include "base/path_service.h"
#include "build/build_config.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "net/base/net_util.h"
#include "net/test/test_server.h"
#include "webkit/glue/plugins/plugin_switches.h"
namespace {
// Platform-specific filename relative to the chrome executable.
#if defined(OS_WIN)
const wchar_t library_name[] = L"ppapi_tests.dll";
#elif defined(OS_MACOSX)
const char library_name[] = "ppapi_tests.plugin";
#elif defined(OS_POSIX)
const char library_name[] = "libppapi_tests.so";
#endif
} // namespace
class PPAPITest : public UITest {
public:
PPAPITest() {
// Append the switch to register the pepper plugin.
// library name = <out dir>/<test_name>.<library_extension>
// MIME type = application/x-ppapi-<test_name>
FilePath plugin_dir;
PathService::Get(base::DIR_EXE, &plugin_dir);
FilePath plugin_lib = plugin_dir.Append(library_name);
EXPECT_TRUE(file_util::PathExists(plugin_lib));
FilePath::StringType pepper_plugin = plugin_lib.value();
pepper_plugin.append(FILE_PATH_LITERAL(";application/x-ppapi-tests"));
launch_arguments_.AppendSwitchNative(switches::kRegisterPepperPlugins,
pepper_plugin);
// The test sends us the result via a cookie.
launch_arguments_.AppendSwitch(switches::kEnableFileCookies);
// Some stuff is hung off of the testing interface which is not enabled
// by default.
launch_arguments_.AppendSwitch(switches::kEnablePepperTesting);
// Give unlimited quota for files to Pepper tests.
// TODO(dumi): remove this switch once we have a quota management
// system in place.
launch_arguments_.AppendSwitch(switches::kUnlimitedQuotaForFiles);
}
void RunTest(const std::string& test_case) {
FilePath test_path;
PathService::Get(base::DIR_SOURCE_ROOT, &test_path);
test_path = test_path.Append(FILE_PATH_LITERAL("ppapi"));
test_path = test_path.Append(FILE_PATH_LITERAL("tests"));
test_path = test_path.Append(FILE_PATH_LITERAL("test_case.html"));
// Sanity check the file name.
EXPECT_TRUE(file_util::PathExists(test_path));
GURL::Replacements replacements;
replacements.SetQuery(test_case.c_str(),
url_parse::Component(0, test_case.size()));
GURL test_url = net::FilePathToFileURL(test_path);
RunTestURL(test_url.ReplaceComponents(replacements));
}
void RunTestViaHTTP(const std::string& test_case) {
net::TestServer test_server(
net::TestServer::TYPE_HTTP,
FilePath(FILE_PATH_LITERAL("third_party/ppapi/tests")));
ASSERT_TRUE(test_server.Start());
RunTestURL(test_server.GetURL("files/test_case.html?" + test_case));
}
private:
void RunTestURL(const GURL& test_url) {
scoped_refptr<TabProxy> tab(GetActiveTab());
ASSERT_TRUE(tab.get());
ASSERT_TRUE(tab->NavigateToURL(test_url));
std::string escaped_value =
WaitUntilCookieNonEmpty(tab.get(), test_url,
"COMPLETION_COOKIE", action_max_timeout_ms());
EXPECT_STREQ("PASS", escaped_value.c_str());
}
};
TEST_F(PPAPITest, FAILS_Instance) {
RunTest("Instance");
}
TEST_F(PPAPITest, Graphics2D) {
RunTest("Graphics2D");
}
// TODO(brettw) bug 51344: this is flaky on bots. Seems to timeout navigating.
// Possibly all the image allocations slow things down on a loaded bot too much.
TEST_F(PPAPITest, FLAKY_ImageData) {
RunTest("ImageData");
}
TEST_F(PPAPITest, Buffer) {
RunTest("Buffer");
}
// http://bugs.chromium.org/51345
TEST_F(PPAPITest, DISABLED_URLLoader) {
RunTestViaHTTP("URLLoader");
}
// Flaky, http://crbug.com/51012
TEST_F(PPAPITest, FLAKY_PaintAggregator) {
RunTestViaHTTP("PaintAggregator");
}
// Flaky, http://crbug.com/48544.
TEST_F(PPAPITest, FLAKY_Scrollbar) {
RunTest("Scrollbar");
}
TEST_F(PPAPITest, UrlUtil) {
RunTest("UrlUtil");
}
TEST_F(PPAPITest, CharSet) {
RunTest("CharSet");
}
TEST_F(PPAPITest, Var) {
RunTest("Var");
}
<|endoftext|>
|
<commit_before><commit_msg>Disable WorkerHttpLayoutTests which is flaky (both debug and release winxp).<commit_after><|endoftext|>
|
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/worker_host/worker_service.h"
#include "chrome/test/automation/browser_proxy.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_layout_test.h"
static const char kTestCompleteCookie[] = "status";
static const char kTestCompleteSuccess[] = "OK";
class WorkerTest : public UILayoutTest {
protected:
virtual ~WorkerTest() { }
void RunTest(const std::wstring& test_case) {
scoped_refptr<TabProxy> tab(GetActiveTab());
ASSERT_TRUE(tab.get());
GURL url = GetTestUrl(L"workers", test_case);
ASSERT_TRUE(tab->NavigateToURL(url));
std::string value = WaitUntilCookieNonEmpty(tab.get(), url,
kTestCompleteCookie, kTestIntervalMs, kTestWaitTimeoutMs);
ASSERT_STREQ(kTestCompleteSuccess, value.c_str());
}
};
TEST_F(WorkerTest, SingleWorker) {
RunTest(L"single_worker.html");
}
TEST_F(WorkerTest, MultipleWorkers) {
RunTest(L"multi_worker.html");
}
// WorkerFastLayoutTests works on the linux try servers, but fails on the
// build bots and fails on mac valgrind.
#if !defined(OS_WIN)
#define WorkerFastLayoutTests DISABLED_WorkerFastLayoutTests
#endif
TEST_F(WorkerTest, WorkerFastLayoutTests) {
static const char* kLayoutTestFiles[] = {
"stress-js-execution.html",
#if defined(OS_WIN)
// Workers don't properly initialize the V8 stack guard.
// (http://code.google.com/p/chromium/issues/detail?id=21653).
"use-machine-stack.html",
#endif
"worker-call.html",
// Disabled because cloning ports are too slow in Chromium to meet the
// thresholds in this test.
// http://code.google.com/p/chromium/issues/detail?id=22780
// "worker-cloneport.html",
"worker-close.html",
"worker-constructor.html",
"worker-context-gc.html",
"worker-context-multi-port.html",
"worker-event-listener.html",
"worker-gc.html",
// worker-lifecycle.html relies on layoutTestController.workerThreadCount
// which is not currently implemented.
// "worker-lifecycle.html",
"worker-location.html",
"worker-messageport.html",
// Disabled after r27089 (WebKit merge), http://crbug.com/22947
// "worker-messageport-gc.html",
"worker-multi-port.html",
"worker-navigator.html",
"worker-replace-global-constructor.html",
"worker-replace-self.html",
"worker-script-error.html",
"worker-terminate.html",
"worker-timeout.html"
};
FilePath fast_test_dir;
fast_test_dir = fast_test_dir.AppendASCII("LayoutTests");
fast_test_dir = fast_test_dir.AppendASCII("fast");
FilePath worker_test_dir;
worker_test_dir = worker_test_dir.AppendASCII("workers");
InitializeForLayoutTest(fast_test_dir, worker_test_dir, false);
// Worker tests also rely on common files in js/resources.
FilePath js_dir = fast_test_dir.AppendASCII("js");
FilePath resource_dir;
resource_dir = resource_dir.AppendASCII("resources");
AddResourceForLayoutTest(js_dir, resource_dir);
for (size_t i = 0; i < arraysize(kLayoutTestFiles); ++i)
RunLayoutTest(kLayoutTestFiles[i], false);
}
TEST_F(WorkerTest, WorkerHttpLayoutTests) {
static const char* kLayoutTestFiles[] = {
// flakey? BUG 16934 "text-encoding.html",
#if defined(OS_WIN)
// Fails on the mac (and linux?):
// http://code.google.com/p/chromium/issues/detail?id=22599
"worker-importScripts.html",
#endif
"worker-redirect.html",
};
FilePath http_test_dir;
http_test_dir = http_test_dir.AppendASCII("LayoutTests");
http_test_dir = http_test_dir.AppendASCII("http");
http_test_dir = http_test_dir.AppendASCII("tests");
FilePath worker_test_dir;
worker_test_dir = worker_test_dir.AppendASCII("workers");
InitializeForLayoutTest(http_test_dir, worker_test_dir, true);
StartHttpServer(new_http_root_dir_);
for (size_t i = 0; i < arraysize(kLayoutTestFiles); ++i)
RunLayoutTest(kLayoutTestFiles[i], true);
StopHttpServer();
}
TEST_F(WorkerTest, WorkerXhrHttpLayoutTests) {
static const char* kLayoutTestFiles[] = {
"abort-exception-assert.html",
#if defined(OS_WIN)
// Fails on the mac (and linux?):
// http://code.google.com/p/chromium/issues/detail?id=22599
"close.html",
#endif
//"methods-async.html",
//"methods.html",
"xmlhttprequest-file-not-found.html"
};
FilePath http_test_dir;
http_test_dir = http_test_dir.AppendASCII("LayoutTests");
http_test_dir = http_test_dir.AppendASCII("http");
http_test_dir = http_test_dir.AppendASCII("tests");
FilePath worker_test_dir;
worker_test_dir = worker_test_dir.AppendASCII("xmlhttprequest");
worker_test_dir = worker_test_dir.AppendASCII("workers");
InitializeForLayoutTest(http_test_dir, worker_test_dir, true);
StartHttpServer(new_http_root_dir_);
for (size_t i = 0; i < arraysize(kLayoutTestFiles); ++i)
RunLayoutTest(kLayoutTestFiles[i], true);
StopHttpServer();
}
TEST_F(WorkerTest, DISABLED_MessagePorts) {
static const char* kLayoutTestFiles[] = {
"message-channel-gc.html",
"message-channel-gc-2.html",
"message-channel-gc-3.html",
"message-channel-gc-4.html",
"message-port.html",
"message-port-clone.html",
"message-port-constructor-for-deleted-document.html",
"message-port-deleted-document.html",
"message-port-deleted-frame.html",
"message-port-inactive-document.html",
"message-port-multi.html",
"message-port-no-wrapper.html",
// Only works with run-webkit-tests --leaks.
//"message-channel-listener-circular-ownership.html",
};
FilePath fast_test_dir;
fast_test_dir = fast_test_dir.AppendASCII("LayoutTests");
fast_test_dir = fast_test_dir.AppendASCII("fast");
FilePath worker_test_dir;
worker_test_dir = worker_test_dir.AppendASCII("events");
InitializeForLayoutTest(fast_test_dir, worker_test_dir, false);
// MessagePort tests also rely on common files in js/resources.
FilePath js_dir = fast_test_dir.AppendASCII("js");
FilePath resource_dir;
resource_dir = resource_dir.AppendASCII("resources");
AddResourceForLayoutTest(js_dir, resource_dir);
for (size_t i = 0; i < arraysize(kLayoutTestFiles); ++i)
RunLayoutTest(kLayoutTestFiles[i], false);
}
// Disable LimitPerPage on Linux. Seems to work on Mac though:
// http://code.google.com/p/chromium/issues/detail?id=22608
#if !defined(OS_LINUX)
TEST_F(WorkerTest, LimitPerPage) {
int max_workers_per_tab = WorkerService::kMaxWorkersPerTabWhenSeparate;
GURL url = GetTestUrl(L"workers", L"many_workers.html");
url = GURL(url.spec() + StringPrintf("?count=%d", max_workers_per_tab + 1));
scoped_refptr<TabProxy> tab(GetActiveTab());
ASSERT_TRUE(tab.get());
ASSERT_TRUE(tab->NavigateToURL(url));
EXPECT_EQ(max_workers_per_tab + 1 + (UITest::in_process_renderer() ? 0 : 1),
UITest::GetBrowserProcessCount());
}
#endif
// Disable LimitTotal on Linux and Mac.
// http://code.google.com/p/chromium/issues/detail?id=22608
#if defined(OS_WIN)
TEST_F(WorkerTest, LimitTotal) {
int max_workers_per_tab = WorkerService::kMaxWorkersPerTabWhenSeparate;
int total_workers = WorkerService::kMaxWorkersWhenSeparate;
int tab_count = (total_workers / max_workers_per_tab) + 1;
GURL url = GetTestUrl(L"workers", L"many_workers.html");
url = GURL(url.spec() + StringPrintf("?count=%d", max_workers_per_tab));
scoped_refptr<TabProxy> tab(GetActiveTab());
ASSERT_TRUE(tab.get());
ASSERT_TRUE(tab->NavigateToURL(url));
scoped_refptr<BrowserProxy> window(automation()->GetBrowserWindow(0));
for (int i = 1; i < tab_count; ++i)
window->AppendTab(url);
// Check that we didn't create more than the max number of workers.
EXPECT_EQ(total_workers + 1 + (UITest::in_process_renderer() ? 0 : tab_count),
UITest::GetBrowserProcessCount());
// Now close the first tab and check that the queued workers were started.
tab->Close(true);
tab->NavigateToURL(GetTestUrl(L"google", L"google.html"));
EXPECT_EQ(total_workers + 1 + (UITest::in_process_renderer() ? 0 : tab_count),
UITest::GetBrowserProcessCount());
}
#endif
<commit_msg>Disable WorkerTest.WorkerFastLayoutTests.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/worker_host/worker_service.h"
#include "chrome/test/automation/browser_proxy.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_layout_test.h"
static const char kTestCompleteCookie[] = "status";
static const char kTestCompleteSuccess[] = "OK";
class WorkerTest : public UILayoutTest {
protected:
virtual ~WorkerTest() { }
void RunTest(const std::wstring& test_case) {
scoped_refptr<TabProxy> tab(GetActiveTab());
ASSERT_TRUE(tab.get());
GURL url = GetTestUrl(L"workers", test_case);
ASSERT_TRUE(tab->NavigateToURL(url));
std::string value = WaitUntilCookieNonEmpty(tab.get(), url,
kTestCompleteCookie, kTestIntervalMs, kTestWaitTimeoutMs);
ASSERT_STREQ(kTestCompleteSuccess, value.c_str());
}
};
TEST_F(WorkerTest, SingleWorker) {
RunTest(L"single_worker.html");
}
TEST_F(WorkerTest, MultipleWorkers) {
RunTest(L"multi_worker.html");
}
// WorkerFastLayoutTests works on the linux try servers, but fails on the
// build bots and fails on mac valgrind.
#if !defined(OS_WIN)
#define WorkerFastLayoutTests DISABLED_WorkerFastLayoutTests
#endif
// WorkerFastLayoutTests failed on all platforms since r27553.
// http://crbug.com/23391
TEST_F(WorkerTest, DISABLED_WorkerFastLayoutTests) {
static const char* kLayoutTestFiles[] = {
"stress-js-execution.html",
#if defined(OS_WIN)
// Workers don't properly initialize the V8 stack guard.
// (http://code.google.com/p/chromium/issues/detail?id=21653).
"use-machine-stack.html",
#endif
"worker-call.html",
// Disabled because cloning ports are too slow in Chromium to meet the
// thresholds in this test.
// http://code.google.com/p/chromium/issues/detail?id=22780
// "worker-cloneport.html",
"worker-close.html",
"worker-constructor.html",
"worker-context-gc.html",
"worker-context-multi-port.html",
"worker-event-listener.html",
"worker-gc.html",
// worker-lifecycle.html relies on layoutTestController.workerThreadCount
// which is not currently implemented.
// "worker-lifecycle.html",
"worker-location.html",
"worker-messageport.html",
// Disabled after r27089 (WebKit merge), http://crbug.com/22947
// "worker-messageport-gc.html",
"worker-multi-port.html",
"worker-navigator.html",
"worker-replace-global-constructor.html",
"worker-replace-self.html",
"worker-script-error.html",
"worker-terminate.html",
"worker-timeout.html"
};
FilePath fast_test_dir;
fast_test_dir = fast_test_dir.AppendASCII("LayoutTests");
fast_test_dir = fast_test_dir.AppendASCII("fast");
FilePath worker_test_dir;
worker_test_dir = worker_test_dir.AppendASCII("workers");
InitializeForLayoutTest(fast_test_dir, worker_test_dir, false);
// Worker tests also rely on common files in js/resources.
FilePath js_dir = fast_test_dir.AppendASCII("js");
FilePath resource_dir;
resource_dir = resource_dir.AppendASCII("resources");
AddResourceForLayoutTest(js_dir, resource_dir);
for (size_t i = 0; i < arraysize(kLayoutTestFiles); ++i)
RunLayoutTest(kLayoutTestFiles[i], false);
}
TEST_F(WorkerTest, WorkerHttpLayoutTests) {
static const char* kLayoutTestFiles[] = {
// flakey? BUG 16934 "text-encoding.html",
#if defined(OS_WIN)
// Fails on the mac (and linux?):
// http://code.google.com/p/chromium/issues/detail?id=22599
"worker-importScripts.html",
#endif
"worker-redirect.html",
};
FilePath http_test_dir;
http_test_dir = http_test_dir.AppendASCII("LayoutTests");
http_test_dir = http_test_dir.AppendASCII("http");
http_test_dir = http_test_dir.AppendASCII("tests");
FilePath worker_test_dir;
worker_test_dir = worker_test_dir.AppendASCII("workers");
InitializeForLayoutTest(http_test_dir, worker_test_dir, true);
StartHttpServer(new_http_root_dir_);
for (size_t i = 0; i < arraysize(kLayoutTestFiles); ++i)
RunLayoutTest(kLayoutTestFiles[i], true);
StopHttpServer();
}
TEST_F(WorkerTest, WorkerXhrHttpLayoutTests) {
static const char* kLayoutTestFiles[] = {
"abort-exception-assert.html",
#if defined(OS_WIN)
// Fails on the mac (and linux?):
// http://code.google.com/p/chromium/issues/detail?id=22599
"close.html",
#endif
//"methods-async.html",
//"methods.html",
"xmlhttprequest-file-not-found.html"
};
FilePath http_test_dir;
http_test_dir = http_test_dir.AppendASCII("LayoutTests");
http_test_dir = http_test_dir.AppendASCII("http");
http_test_dir = http_test_dir.AppendASCII("tests");
FilePath worker_test_dir;
worker_test_dir = worker_test_dir.AppendASCII("xmlhttprequest");
worker_test_dir = worker_test_dir.AppendASCII("workers");
InitializeForLayoutTest(http_test_dir, worker_test_dir, true);
StartHttpServer(new_http_root_dir_);
for (size_t i = 0; i < arraysize(kLayoutTestFiles); ++i)
RunLayoutTest(kLayoutTestFiles[i], true);
StopHttpServer();
}
TEST_F(WorkerTest, DISABLED_MessagePorts) {
static const char* kLayoutTestFiles[] = {
"message-channel-gc.html",
"message-channel-gc-2.html",
"message-channel-gc-3.html",
"message-channel-gc-4.html",
"message-port.html",
"message-port-clone.html",
"message-port-constructor-for-deleted-document.html",
"message-port-deleted-document.html",
"message-port-deleted-frame.html",
"message-port-inactive-document.html",
"message-port-multi.html",
"message-port-no-wrapper.html",
// Only works with run-webkit-tests --leaks.
//"message-channel-listener-circular-ownership.html",
};
FilePath fast_test_dir;
fast_test_dir = fast_test_dir.AppendASCII("LayoutTests");
fast_test_dir = fast_test_dir.AppendASCII("fast");
FilePath worker_test_dir;
worker_test_dir = worker_test_dir.AppendASCII("events");
InitializeForLayoutTest(fast_test_dir, worker_test_dir, false);
// MessagePort tests also rely on common files in js/resources.
FilePath js_dir = fast_test_dir.AppendASCII("js");
FilePath resource_dir;
resource_dir = resource_dir.AppendASCII("resources");
AddResourceForLayoutTest(js_dir, resource_dir);
for (size_t i = 0; i < arraysize(kLayoutTestFiles); ++i)
RunLayoutTest(kLayoutTestFiles[i], false);
}
// Disable LimitPerPage on Linux. Seems to work on Mac though:
// http://code.google.com/p/chromium/issues/detail?id=22608
#if !defined(OS_LINUX)
TEST_F(WorkerTest, LimitPerPage) {
int max_workers_per_tab = WorkerService::kMaxWorkersPerTabWhenSeparate;
GURL url = GetTestUrl(L"workers", L"many_workers.html");
url = GURL(url.spec() + StringPrintf("?count=%d", max_workers_per_tab + 1));
scoped_refptr<TabProxy> tab(GetActiveTab());
ASSERT_TRUE(tab.get());
ASSERT_TRUE(tab->NavigateToURL(url));
EXPECT_EQ(max_workers_per_tab + 1 + (UITest::in_process_renderer() ? 0 : 1),
UITest::GetBrowserProcessCount());
}
#endif
// Disable LimitTotal on Linux and Mac.
// http://code.google.com/p/chromium/issues/detail?id=22608
#if defined(OS_WIN)
TEST_F(WorkerTest, LimitTotal) {
int max_workers_per_tab = WorkerService::kMaxWorkersPerTabWhenSeparate;
int total_workers = WorkerService::kMaxWorkersWhenSeparate;
int tab_count = (total_workers / max_workers_per_tab) + 1;
GURL url = GetTestUrl(L"workers", L"many_workers.html");
url = GURL(url.spec() + StringPrintf("?count=%d", max_workers_per_tab));
scoped_refptr<TabProxy> tab(GetActiveTab());
ASSERT_TRUE(tab.get());
ASSERT_TRUE(tab->NavigateToURL(url));
scoped_refptr<BrowserProxy> window(automation()->GetBrowserWindow(0));
for (int i = 1; i < tab_count; ++i)
window->AppendTab(url);
// Check that we didn't create more than the max number of workers.
EXPECT_EQ(total_workers + 1 + (UITest::in_process_renderer() ? 0 : tab_count),
UITest::GetBrowserProcessCount());
// Now close the first tab and check that the queued workers were started.
tab->Close(true);
tab->NavigateToURL(GetTestUrl(L"google", L"google.html"));
EXPECT_EQ(total_workers + 1 + (UITest::in_process_renderer() ? 0 : tab_count),
UITest::GetBrowserProcessCount());
}
#endif
<|endoftext|>
|
<commit_before><commit_msg>Disable Worker*.WorkerFastLayoutTests for now.<commit_after><|endoftext|>
|
<commit_before>#ifndef ALEPH_MATH_KAHAN_SUMMATION_HH__
#define ALEPH_MATH_KAHAN_SUMMATION_HH__
#include <algorithm>
#include <vector>
namespace aleph
{
namespace math
{
template <class T> class KahanSummation
{
public:
KahanSummation( T initial = T() )
: _sum( initial )
, _c( T() )
{
}
KahanSummation& operator+= ( T v )
{
T y = v - _c;
T t = _sum + y;
_c = ( t - _sum ) - y;
_sum = t;
return *this;
}
KahanSummation& operator-= ( T v )
{
return this->operator+=( -v );
}
KahanSummation& operator*= ( T v )
{
_sum *= v;
return *this;
}
KahanSummation& operator/= ( T v )
{
_sum /= v;
return *this;
}
operator const T () const
{
return _sum;
}
private:
T _sum;
T _c;
};
// ---------------------------------------------------------------------
/**
Accumulation function modelled after \c std::accumulate. Instead of summing
up the values without regards to floating point cancellation, this function
uses the Kahan summation algorithm on a sorted range of numbers. This gives
better stability guarantees for the sum.
*/
template <class InputIterator, class T> T accumulate_kahan( InputIterator first, InputIterator last, T init )
{
KahanSummation<T> sum = init;
std::vector<T> values( first, last );
std::sort( values.begin(), values.end() );
for( auto&& value : values )
sum += value;
return sum;
}
} // namespace math
} // namespace aleph
#endif
<commit_msg>Extended Kahan summation for sorted ranges<commit_after>#ifndef ALEPH_MATH_KAHAN_SUMMATION_HH__
#define ALEPH_MATH_KAHAN_SUMMATION_HH__
#include <algorithm>
#include <vector>
namespace aleph
{
namespace math
{
template <class T> class KahanSummation
{
public:
KahanSummation( T initial = T() )
: _sum( initial )
, _c( T() )
{
}
KahanSummation& operator+= ( T v )
{
T y = v - _c;
T t = _sum + y;
_c = ( t - _sum ) - y;
_sum = t;
return *this;
}
KahanSummation& operator-= ( T v )
{
return this->operator+=( -v );
}
KahanSummation& operator*= ( T v )
{
_sum *= v;
return *this;
}
KahanSummation& operator/= ( T v )
{
_sum /= v;
return *this;
}
operator const T () const
{
return _sum;
}
private:
T _sum;
T _c;
};
// ---------------------------------------------------------------------
/**
Accumulation function modelled after \c std::accumulate. Instead of summing
up the values without regards to floating point cancellation, this function
uses the Kahan summation algorithm on a sorted range of numbers. This gives
better stability guarantees for the sum.
*/
template <class InputIterator, class T> T accumulate_kahan( InputIterator first, InputIterator last, T init )
{
KahanSummation<T> sum = init;
for( auto it = first; it != last; ++it )
sum += *it;
return sum;
}
/**
Kahan summation with sorted values. This further increases the precision
of the summation algorithm but incurs a higher run-time complexity.
*/
template <class InputIterator, class T> T accumulate_kahan_sorted( InputIterator first, InputIterator last, T init )
{
KahanSummation<T> sum = init;
std::vector<T> values( first, last );
std::sort( values.begin(), values.end() );
for( auto&& value : values )
sum += value;
return sum;
}
} // namespace math
} // namespace aleph
#endif
<|endoftext|>
|
<commit_before>///
/// @file MessageControllerFull.cpp
/// @date 8/5/2008
/// @author TuanQuang Nguyen
///
///
/**************** Include module header files *******************/
// #include <BasicMessage.h>
#include <net/message-framework/MessageControllerFull.h>
#include <net/message-framework/MessageFrameworkConfiguration.h>
#include <net/message-framework/ServiceMessage.h>
#include <net/message-framework/MessageType.h>
#include <net/message-framework/ServiceRegistrationMessage.h>
#include <net/message-framework/ServiceRegistrationReplyMessage.h>
#include <net/message-framework/ClientIdReplyMessage.h>
#include <net/message-framework/ServicePermissionInfo.h>
#include <boost/filesystem.hpp>
/**************** Include boost header files *******************/
#include <boost/bind.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/thread.hpp>
/**************** Include std header files *******************/
#include <iostream>
/**************** Include sf1lib header files *******************/
const static string AvailServiceFileName = "_ctr_services.dat";
namespace messageframework {
//static member variables
std::string MessageControllerFullSingleton::controllerName_("");
unsigned int MessageControllerFullSingleton::controllerPort_ = 0;
boost::scoped_ptr<MessageControllerFull>
MessageControllerFullSingleton::messageController_(0);
boost::once_flag MessageControllerFullSingleton::flag= BOOST_ONCE_INIT;
MessageControllerFull::MessageControllerFull(const std::string& controllerName,
unsigned int servicePort) :
messageDispatcher_(this, this, this, this, this), asyncConnector_(this,
io_service_) {
ownerManager_ = controllerName;
servicePort_ = servicePort;
asyncConnector_.listen(servicePort_);
ipAddress_ = getLocalHostIp(io_service_);
saveLoadAvailableServiceList_(AvailServiceFileName, false);
// timeout is 1 second
timeOutMilliSecond_ = 1000;
//serviceResultReply_ = false;
// start from 1, so 0 is a invalid client id
nxtClientId_ = 1;
// create thread for I/O operations
ioThread_ = new boost::thread(boost::bind(&boost::asio::io_service::run, &io_service_));
}
MessageControllerFull::~MessageControllerFull() {
asyncConnector_.shutdown();
ioThread_->join();
delete ioThread_;
saveLoadAvailableServiceList_(AvailServiceFileName, true);
}
void MessageControllerFull::saveLoadAvailableServiceList_(
const string& fileName, bool bStore) {
if (bStore) {
std::ofstream ofs(fileName.data(), ios::binary | ios::trunc);
boost::archive::binary_oarchive oa(ofs);
oa & availableServiceList_;
} else {
if ( ! boost::filesystem::exists(fileName) )
return;
std::ifstream ifs(fileName.data(), ios::binary);
boost::archive::binary_iarchive ia(ifs);
ia & availableServiceList_;
std::map<std::string, ServicePermissionInfo>::iterator it;
it = availableServiceList_.begin();
for(; it != availableServiceList_.begin(); it++){
cout<<"!!!!!!!!1"<<endl;
cout<<it->first<<endl;
it->second.display();
}
}
}
/******************************************************************************
Description: This function processes all the waiting service registration requests.
It registers all the services from MessageServer (IP address, port number,
a list of service which can be provided by the MessageServer).
*******************************************************************************/
void MessageControllerFull::processServiceRegistrationRequest(void) {
try
{
boost::mutex::scoped_lock serviceRegistrationRequestQueueLock(
serviceRegistrationRequestQueueMutex_);
while(true)
{
newRegistrationEvent_.wait(serviceRegistrationRequestQueueLock);
#ifdef _LOGGING_
WriteToLog("log.log", "=============processServiceRegistrationRequest===========");
#endif
while(!serviceRegistrationRequestQueue_.empty())
{
std::pair<ServiceRegistrationMessage, MessageFrameworkNode> request =
serviceRegistrationRequestQueue_.front();
serviceRegistrationRequestQueue_.pop();
serviceRegistrationRequestQueueLock.unlock();
{
// check if the sevice has been registered
string serviceName = request.first.getServiceInfo().getServiceName();
MessageFrameworkNode server = request.first.getServiceInfo().getServer();
boost::mutex::scoped_lock availableServiceListLock(availableServiceListMutex_);
std::cout<<"ServiceRegistrationRequest: "<<serviceName<<std::endl;
if( availableServiceList_.find(serviceName) != availableServiceList_.end() )
{
#ifdef SF1_DEBUG
std::cout << "[Controller:" << getName();
std::cout << "] ServiceInfo " << request.first.getServiceName() << " already exists.";
std::cout << "New data overwrites old data." << std::endl;
#endif
availableServiceList_[serviceName].setServer(request.first.getAgentInfo(), server);
} else
{
ServicePermissionInfo permissionInfo;
permissionInfo.setServiceName(serviceName);
permissionInfo.setServer(request.first.getAgentInfo(), server);
availableServiceList_[serviceName] = permissionInfo;
}
//availableServiceList_[serviceName].display();
sendServiceRegistrationResult(request.second, request.first.getServiceInfo(), true);
}
saveLoadAvailableServiceList_(AvailServiceFileName, true);
#ifdef SF1_DEBUG
std::cout << "[Controller:" << getName() << "] ServiceInfo [" << request.first.getServiceName();
std::cout << ", " << request.first.getServer().nodeIP_ << ":";
std::cout << request.first.getServer().nodePort_ << "] is successfully registerd." << std::endl;
#endif
// connection to server
if(!messageDispatcher_.isExist(request.first.getServer()))
{
asyncConnector_.connect(request.first.getServer().nodeIP_,
request.first.getServer().nodePort_);
}
serviceRegistrationRequestQueueLock.lock();
}
}// end of while true
}
catch(MessageFrameworkException& e)
{
e.output(std::cout);
}
catch (boost::system::error_code& e)
{
std::cerr << "Exception: " << e << std::endl;
}
catch (std::exception& e)
{
std::cerr << "Exception: "<< e.what() << std::endl;
}
}
/******************************************************************************
Description: This function processes all the waiting service permission requests.
It determines whether it is available to process the service and issues
permission to the MessageClient. If the service needs to use the direct
connection, MessageControllerFull sends the permission to the MessageServer.
******************************************************************************/
bool MessageControllerFull::checkAgentInfo_(
ServicePermissionInfo& permissionInfo) {
const std::map<std::string, MessageFrameworkNode>& agentInfoMap =
permissionInfo.getServerMap();
std::map<std::string, MessageFrameworkNode>::const_iterator it =
agentInfoMap.begin();
for (; it != agentInfoMap.end(); it++) {
if ( !messageDispatcher_.isExist(it->second) ) {
DLOG(ERROR)<<"ServicePermissionInfo:"<<it->first<<" -> server:"
<<it->second<<"not exists";
permissionInfo.removeServer(it->first);
saveLoadAvailableServiceList_(AvailServiceFileName, true);
}
}
if (it != agentInfoMap.end() )
return false;
return true;
}
void MessageControllerFull::processServicePermissionRequest(void) {
try
{
std::pair<std::string, MessageFrameworkNode> requestItem;
ServiceInfo serviceInfo;
boost::mutex::scoped_lock permissionRequestQueueLock(servicePermissionRequestQueueMutex_);
while(true)
{
newPermissionRequestEvent_.wait(permissionRequestQueueLock);
#ifdef _LOGGING_
WriteToLog("log.log", "============= processServicePermissionRequest ===========");
#endif
// process all the waiting requests
while(!servicePermissionRequestQueue_.empty())
{
requestItem = servicePermissionRequestQueue_.front();
servicePermissionRequestQueue_.pop();
permissionRequestQueueLock.unlock();
if( availableServiceList_.find(requestItem.first) != availableServiceList_.end() )
{
boost::mutex::scoped_lock availableServiceListLock(availableServiceListMutex_);
checkAgentInfo_( availableServiceList_[requestItem.first] );
sendPermissionOfServiceResult(requestItem.second, availableServiceList_[requestItem.first] );
availableServiceList_[requestItem.first].display();
// to improve performance, direct connection to
// server is always made
//serviceInfo.setPermissionFlag(SERVE_AT_SERVER);
// serviceInfo.setServer(ipAddress_, servicePort_);
} else
{
ServicePermissionInfo permission;
permission.setServiceName(requestItem.first);
//serviceInfo.setPermissionFlag(UNKNOWN_PERMISSION_FLAG);
#ifdef SF1_DEBUG
std::cout << " [Controller:" << getName();
std::cout << "] Service " << requestItem.first;
std::cout << " is not listed." << std::endl;
#endif
sendPermissionOfServiceResult(requestItem.second, permission );
cout<<"!!! no listed"<<endl;
availableServiceList_[requestItem.first].display();
}
#ifdef SF1_DEBUG
std::cout << "[Controller:" << getName();
std::cout << "] Permission of " << requestItem.first;
std::cout << " is successfully sent to ";
std::cout << requestItem.second.nodeIP_ << ":" << requestItem.second.nodePort_ << std::endl;
#endif
permissionRequestQueueLock.lock();
}// end of while(!servicePermissionRequestQueue_.empty())
}// end of while(true)
}
catch(MessageFrameworkException& e)
{
e.output(std::cout);
}
catch (boost::system::error_code& e)
{
std::cerr << "Exception: " << e << std::endl;
}
catch (std::exception& e)
{
std::cerr << "Exception: "<< e.what() << std::endl;
}
}
/******************************************************************************
Description: When a new request of get client id comes, this function is called
in order to notify the server
******************************************************************************/
void MessageControllerFull::receiveClientIdRequest(
const MessageFrameworkNode& requester) {
{
boost::mutex::scoped_lock lock(nxtClientIdMutex_);
if (nxtClientId_ == MF_FULL_MAX_CLIENT_ID) {
std::cout << "Max Client ID reached" << std::endl;
throw MessageFrameworkException(SF1_MSGFRK_LOGIC_ERROR, __LINE__, __FILE__);
}
std::cout << "DEBUG: MessageControllerFull:: dispatch nxtClientId_="
<<nxtClientId_ << std::endl;
sendClientIdResult(requester, nxtClientId_);
nxtClientId_ ++;
}
}
/******************************************************************************
Description: This function replies to a request from ClientIdRequester
******************************************************************************/
void MessageControllerFull::sendClientIdResult(
const MessageFrameworkNode& requester, const int& clientId) {
ClientIdReplyMessage message(clientId);
messageDispatcher_.sendDataToLowerLayer(CLIENT_ID_REPLY_MSG, message,
requester);
}
/******************************************************************************
Description: This function put a request to get permission of service into the
waiting queue. The requests in the waitiing queue will be processed in function
processServicePermissionRequest().
******************************************************************************/
void MessageControllerFull::receivePermissionOfServiceRequest(
const MessageFrameworkNode& requester, const std::string& serviceName) {
#ifdef SF1_DEBUG
std::cout << "[Controller:" << getName() << "] Receive permission request of ";
std::cout << serviceName << " from " << requester.nodeName_ << std::endl;
#endif
{
boost::mutex::scoped_lock lock(servicePermissionRequestQueueMutex_);
servicePermissionRequestQueue_.push(std::pair<std::string, MessageFrameworkNode>(serviceName, requester));
}
newPermissionRequestEvent_.notify_all();
}
/******************************************************************************
Description: This function inserts a ServiceInfo to the serviceRegistrationRequestQueue_.
It returns false if the data alread exists in the queue.
Input:
serviceInfo - data to add
******************************************************************************/
void MessageControllerFull::receiveServiceRegistrationRequest(const MessageFrameworkNode& localEndPoint,
const ServiceRegistrationMessage& registMessage)
{
try
{
{
boost::mutex::scoped_lock lock(serviceRegistrationRequestQueueMutex_);
serviceRegistrationRequestQueue_.push(
std::pair<ServiceRegistrationMessage, MessageFrameworkNode>(registMessage, localEndPoint));
}
newRegistrationEvent_.notify_all();
}
catch (boost::system::error_code& e)
{
std::cerr << "Exception: " << e << std::endl;
}
catch (std::exception& e)
{
std::cerr << "Exception: "<< e.what() << std::endl;
}
}
/**
* @brief This function replies to a registration request from ServiceRegistrationRequester. It
* will sends registration result to the ServiceRegistrationRequester.
* @param localEndPoint the end point that connects to the ServiceRegistrationClient.
* @param serviceInfo the service information to register
* @param success the registration result
*/
void MessageControllerFull::sendServiceRegistrationResult(const MessageFrameworkNode& localEndPoint, const ServiceInfo& serviceInfo,
bool success)
{
ServiceRegistrationReplyMessage message(serviceInfo.getServiceName(), success);
messageDispatcher_.sendDataToLowerLayer(SERVICE_REGISTRATION_REPLY_MSG, message, localEndPoint);
}
/**
* @brief This function replies to a request from PermissionRequester
*/
void MessageControllerFull::sendPermissionOfServiceResult(const MessageFrameworkNode& requester,
const ServicePermissionInfo & permission)
{
messageDispatcher_.sendDataToLowerLayer(PERMISSION_OF_SERVICE_REPLY_MSG,
permission, requester);
}
/**
* @brief This function create a new AsyncStream that is based on tcp::socket
*/
AsyncStream* MessageControllerFull::createAsyncStream(boost::shared_ptr<tcp::socket> sock)
{
// tcp::endpoint endpoint = sock->local_endpoint();
tcp::endpoint endpoint = sock->remote_endpoint();
std::cout << "Remote IP = " << endpoint.address().to_string();
std::cout << ", port = " << endpoint.port() << std::endl;
return new AsyncStream(&messageDispatcher_, sock);
}
}// end of namespace messageframework
<commit_msg>disable load permisioninfo in controller<commit_after>///
/// @file MessageControllerFull.cpp
/// @date 8/5/2008
/// @author TuanQuang Nguyen
///
///
/**************** Include module header files *******************/
// #include <BasicMessage.h>
#include <net/message-framework/MessageControllerFull.h>
#include <net/message-framework/MessageFrameworkConfiguration.h>
#include <net/message-framework/ServiceMessage.h>
#include <net/message-framework/MessageType.h>
#include <net/message-framework/ServiceRegistrationMessage.h>
#include <net/message-framework/ServiceRegistrationReplyMessage.h>
#include <net/message-framework/ClientIdReplyMessage.h>
#include <net/message-framework/ServicePermissionInfo.h>
#include <boost/filesystem.hpp>
/**************** Include boost header files *******************/
#include <boost/bind.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/thread.hpp>
/**************** Include std header files *******************/
#include <iostream>
/**************** Include sf1lib header files *******************/
const static string AvailServiceFileName = "_ctr_services.dat";
namespace messageframework {
//static member variables
std::string MessageControllerFullSingleton::controllerName_("");
unsigned int MessageControllerFullSingleton::controllerPort_ = 0;
boost::scoped_ptr<MessageControllerFull>
MessageControllerFullSingleton::messageController_(0);
boost::once_flag MessageControllerFullSingleton::flag= BOOST_ONCE_INIT;
MessageControllerFull::MessageControllerFull(const std::string& controllerName,
unsigned int servicePort) :
messageDispatcher_(this, this, this, this, this), asyncConnector_(this,
io_service_) {
ownerManager_ = controllerName;
servicePort_ = servicePort;
asyncConnector_.listen(servicePort_);
ipAddress_ = getLocalHostIp(io_service_);
saveLoadAvailableServiceList_(AvailServiceFileName, false);
// timeout is 1 second
timeOutMilliSecond_ = 1000;
//serviceResultReply_ = false;
// start from 1, so 0 is a invalid client id
nxtClientId_ = 1;
// create thread for I/O operations
ioThread_ = new boost::thread(boost::bind(&boost::asio::io_service::run, &io_service_));
}
MessageControllerFull::~MessageControllerFull() {
asyncConnector_.shutdown();
ioThread_->join();
delete ioThread_;
saveLoadAvailableServiceList_(AvailServiceFileName, true);
}
void MessageControllerFull::saveLoadAvailableServiceList_(
const string& fileName, bool bStore) {
// if (bStore) {
// std::ofstream ofs(fileName.data(), ios::binary | ios::trunc);
// boost::archive::binary_oarchive oa(ofs);
// oa & availableServiceList_;
// } else {
// if ( ! boost::filesystem::exists(fileName) )
// return;
//
// std::ifstream ifs(fileName.data(), ios::binary);
// boost::archive::binary_iarchive ia(ifs);
// ia & availableServiceList_;
//
// std::map<std::string, ServicePermissionInfo>::iterator it;
// it = availableServiceList_.begin();
// for(; it != availableServiceList_.end(); it++){
// cout<<"!!!!!!!!1"<<endl;
// cout<<it->first<<endl;
// it->second.display();
// }
// }
}
/******************************************************************************
Description: This function processes all the waiting service registration requests.
It registers all the services from MessageServer (IP address, port number,
a list of service which can be provided by the MessageServer).
*******************************************************************************/
void MessageControllerFull::processServiceRegistrationRequest(void) {
try
{
boost::mutex::scoped_lock serviceRegistrationRequestQueueLock(
serviceRegistrationRequestQueueMutex_);
while(true)
{
newRegistrationEvent_.wait(serviceRegistrationRequestQueueLock);
#ifdef _LOGGING_
WriteToLog("log.log", "=============processServiceRegistrationRequest===========");
#endif
while(!serviceRegistrationRequestQueue_.empty())
{
std::pair<ServiceRegistrationMessage, MessageFrameworkNode> request =
serviceRegistrationRequestQueue_.front();
serviceRegistrationRequestQueue_.pop();
serviceRegistrationRequestQueueLock.unlock();
{
// check if the sevice has been registered
string serviceName = request.first.getServiceInfo().getServiceName();
MessageFrameworkNode server = request.first.getServiceInfo().getServer();
boost::mutex::scoped_lock availableServiceListLock(availableServiceListMutex_);
std::cout<<"ServiceRegistrationRequest: "<<serviceName<<std::endl;
if( availableServiceList_.find(serviceName) != availableServiceList_.end() )
{
#ifdef SF1_DEBUG
std::cout << "[Controller:" << getName();
std::cout << "] ServiceInfo " << request.first.getServiceName() << " already exists.";
std::cout << "New data overwrites old data." << std::endl;
#endif
availableServiceList_[serviceName].setServer(request.first.getAgentInfo(), server);
} else
{
ServicePermissionInfo permissionInfo;
permissionInfo.setServiceName(serviceName);
permissionInfo.setServer(request.first.getAgentInfo(), server);
availableServiceList_[serviceName] = permissionInfo;
}
//availableServiceList_[serviceName].display();
sendServiceRegistrationResult(request.second, request.first.getServiceInfo(), true);
}
saveLoadAvailableServiceList_(AvailServiceFileName, true);
#ifdef SF1_DEBUG
std::cout << "[Controller:" << getName() << "] ServiceInfo [" << request.first.getServiceName();
std::cout << ", " << request.first.getServer().nodeIP_ << ":";
std::cout << request.first.getServer().nodePort_ << "] is successfully registerd." << std::endl;
#endif
// connection to server
if(!messageDispatcher_.isExist(request.first.getServer()))
{
asyncConnector_.connect(request.first.getServer().nodeIP_,
request.first.getServer().nodePort_);
}
serviceRegistrationRequestQueueLock.lock();
}
}// end of while true
}
catch(MessageFrameworkException& e)
{
e.output(std::cout);
}
catch (boost::system::error_code& e)
{
std::cerr << "Exception: " << e << std::endl;
}
catch (std::exception& e)
{
std::cerr << "Exception: "<< e.what() << std::endl;
}
}
/******************************************************************************
Description: This function processes all the waiting service permission requests.
It determines whether it is available to process the service and issues
permission to the MessageClient. If the service needs to use the direct
connection, MessageControllerFull sends the permission to the MessageServer.
******************************************************************************/
bool MessageControllerFull::checkAgentInfo_(
ServicePermissionInfo& permissionInfo) {
const std::map<std::string, MessageFrameworkNode>& agentInfoMap =
permissionInfo.getServerMap();
std::map<std::string, MessageFrameworkNode>::const_iterator it =
agentInfoMap.begin();
for (; it != agentInfoMap.end(); it++) {
if ( !messageDispatcher_.isExist(it->second) ) {
DLOG(ERROR)<<"ServicePermissionInfo:"<<it->first<<" -> server:"
<<it->second<<"not exists";
permissionInfo.removeServer(it->first);
saveLoadAvailableServiceList_(AvailServiceFileName, true);
}
}
if (it != agentInfoMap.end() )
return false;
return true;
}
void MessageControllerFull::processServicePermissionRequest(void) {
try
{
std::pair<std::string, MessageFrameworkNode> requestItem;
ServiceInfo serviceInfo;
boost::mutex::scoped_lock permissionRequestQueueLock(servicePermissionRequestQueueMutex_);
while(true)
{
newPermissionRequestEvent_.wait(permissionRequestQueueLock);
#ifdef _LOGGING_
WriteToLog("log.log", "============= processServicePermissionRequest ===========");
#endif
// process all the waiting requests
while(!servicePermissionRequestQueue_.empty())
{
requestItem = servicePermissionRequestQueue_.front();
servicePermissionRequestQueue_.pop();
permissionRequestQueueLock.unlock();
if( availableServiceList_.find(requestItem.first) != availableServiceList_.end() )
{
boost::mutex::scoped_lock availableServiceListLock(availableServiceListMutex_);
checkAgentInfo_( availableServiceList_[requestItem.first] );
sendPermissionOfServiceResult(requestItem.second, availableServiceList_[requestItem.first] );
availableServiceList_[requestItem.first].display();
// to improve performance, direct connection to
// server is always made
//serviceInfo.setPermissionFlag(SERVE_AT_SERVER);
// serviceInfo.setServer(ipAddress_, servicePort_);
} else
{
ServicePermissionInfo permission;
permission.setServiceName(requestItem.first);
//serviceInfo.setPermissionFlag(UNKNOWN_PERMISSION_FLAG);
#ifdef SF1_DEBUG
std::cout << " [Controller:" << getName();
std::cout << "] Service " << requestItem.first;
std::cout << " is not listed." << std::endl;
#endif
sendPermissionOfServiceResult(requestItem.second, permission );
cout<<"!!! no listed"<<endl;
availableServiceList_[requestItem.first].display();
}
#ifdef SF1_DEBUG
std::cout << "[Controller:" << getName();
std::cout << "] Permission of " << requestItem.first;
std::cout << " is successfully sent to ";
std::cout << requestItem.second.nodeIP_ << ":" << requestItem.second.nodePort_ << std::endl;
#endif
permissionRequestQueueLock.lock();
}// end of while(!servicePermissionRequestQueue_.empty())
}// end of while(true)
}
catch(MessageFrameworkException& e)
{
e.output(std::cout);
}
catch (boost::system::error_code& e)
{
std::cerr << "Exception: " << e << std::endl;
}
catch (std::exception& e)
{
std::cerr << "Exception: "<< e.what() << std::endl;
}
}
/******************************************************************************
Description: When a new request of get client id comes, this function is called
in order to notify the server
******************************************************************************/
void MessageControllerFull::receiveClientIdRequest(
const MessageFrameworkNode& requester) {
{
boost::mutex::scoped_lock lock(nxtClientIdMutex_);
if (nxtClientId_ == MF_FULL_MAX_CLIENT_ID) {
std::cout << "Max Client ID reached" << std::endl;
throw MessageFrameworkException(SF1_MSGFRK_LOGIC_ERROR, __LINE__, __FILE__);
}
std::cout << "DEBUG: MessageControllerFull:: dispatch nxtClientId_="
<<nxtClientId_ << std::endl;
sendClientIdResult(requester, nxtClientId_);
nxtClientId_ ++;
}
}
/******************************************************************************
Description: This function replies to a request from ClientIdRequester
******************************************************************************/
void MessageControllerFull::sendClientIdResult(
const MessageFrameworkNode& requester, const int& clientId) {
ClientIdReplyMessage message(clientId);
messageDispatcher_.sendDataToLowerLayer(CLIENT_ID_REPLY_MSG, message,
requester);
}
/******************************************************************************
Description: This function put a request to get permission of service into the
waiting queue. The requests in the waitiing queue will be processed in function
processServicePermissionRequest().
******************************************************************************/
void MessageControllerFull::receivePermissionOfServiceRequest(
const MessageFrameworkNode& requester, const std::string& serviceName) {
#ifdef SF1_DEBUG
std::cout << "[Controller:" << getName() << "] Receive permission request of ";
std::cout << serviceName << " from " << requester.nodeName_ << std::endl;
#endif
{
boost::mutex::scoped_lock lock(servicePermissionRequestQueueMutex_);
servicePermissionRequestQueue_.push(std::pair<std::string, MessageFrameworkNode>(serviceName, requester));
}
newPermissionRequestEvent_.notify_all();
}
/******************************************************************************
Description: This function inserts a ServiceInfo to the serviceRegistrationRequestQueue_.
It returns false if the data alread exists in the queue.
Input:
serviceInfo - data to add
******************************************************************************/
void MessageControllerFull::receiveServiceRegistrationRequest(const MessageFrameworkNode& localEndPoint,
const ServiceRegistrationMessage& registMessage)
{
try
{
{
boost::mutex::scoped_lock lock(serviceRegistrationRequestQueueMutex_);
serviceRegistrationRequestQueue_.push(
std::pair<ServiceRegistrationMessage, MessageFrameworkNode>(registMessage, localEndPoint));
}
newRegistrationEvent_.notify_all();
}
catch (boost::system::error_code& e)
{
std::cerr << "Exception: " << e << std::endl;
}
catch (std::exception& e)
{
std::cerr << "Exception: "<< e.what() << std::endl;
}
}
/**
* @brief This function replies to a registration request from ServiceRegistrationRequester. It
* will sends registration result to the ServiceRegistrationRequester.
* @param localEndPoint the end point that connects to the ServiceRegistrationClient.
* @param serviceInfo the service information to register
* @param success the registration result
*/
void MessageControllerFull::sendServiceRegistrationResult(const MessageFrameworkNode& localEndPoint, const ServiceInfo& serviceInfo,
bool success)
{
ServiceRegistrationReplyMessage message(serviceInfo.getServiceName(), success);
messageDispatcher_.sendDataToLowerLayer(SERVICE_REGISTRATION_REPLY_MSG, message, localEndPoint);
}
/**
* @brief This function replies to a request from PermissionRequester
*/
void MessageControllerFull::sendPermissionOfServiceResult(const MessageFrameworkNode& requester,
const ServicePermissionInfo & permission)
{
messageDispatcher_.sendDataToLowerLayer(PERMISSION_OF_SERVICE_REPLY_MSG,
permission, requester);
}
/**
* @brief This function create a new AsyncStream that is based on tcp::socket
*/
AsyncStream* MessageControllerFull::createAsyncStream(boost::shared_ptr<tcp::socket> sock)
{
// tcp::endpoint endpoint = sock->local_endpoint();
tcp::endpoint endpoint = sock->remote_endpoint();
std::cout << "Remote IP = " << endpoint.address().to_string();
std::cout << ", port = " << endpoint.port() << std::endl;
return new AsyncStream(&messageDispatcher_, sock);
}
}// end of namespace messageframework
<|endoftext|>
|
<commit_before>/*
* Copyright 2008-2013 NVIDIA Corporation
*
* 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.
*/
#pragma once
#include <agency/detail/config.hpp>
#include <agency/cuda/detail/feature_test.hpp>
#include <agency/cuda/detail/terminate.hpp>
#include <agency/cuda/detail/unique_ptr.hpp>
#include <agency/cuda/detail/then_kernel.hpp>
#include <agency/cuda/detail/launch_kernel.hpp>
#include <agency/cuda/detail/workaround_unused_variable_warning.hpp>
#include <agency/future.hpp>
#include <agency/detail/type_traits.hpp>
#include <utility>
#include <type_traits>
namespace agency
{
namespace cuda
{
namespace detail
{
template<class T, class... Args>
struct is_constructible_or_void
: std::integral_constant<
bool,
std::is_constructible<T,Args...>::value ||
(std::is_void<T>::value && (sizeof...(Args) == 0))
>
{};
template<class T>
struct state_requires_storage
: std::integral_constant<
bool,
std::is_empty<T>::value || std::is_void<T>::value || agency::detail::is_empty_tuple<T>::value
>
{};
// XXX should maybe call this asynchronous_state to match the nomenclature of the std
template<class T,
bool requires_storage = state_requires_storage<T>::value>
class future_state
{
public:
__host__ __device__
future_state() = default;
template<class Arg1, class... Args,
class = typename std::enable_if<
std::is_constructible<T,Arg1,Args...>::value
>::type
>
__host__ __device__
future_state(cudaStream_t s, Arg1&& ready_arg1, Args&&... ready_args)
: data_(make_unique<T>(s, std::forward<Arg1>(ready_arg1), std::forward<Args>(ready_args)...))
{}
__host__ __device__
future_state(cudaStream_t s)
: future_state(s, T{})
{}
__host__ __device__
future_state(future_state&& other) : data_(std::move(other.data_)) {}
__host__ __device__
future_state& operator=(future_state&& other)
{
data_ = std::move(other.data_);
return *this;
}
__host__ __device__
T* data()
{
return data_.get();
}
__host__ __device__
T get()
{
T result = std::move(*data_);
data_.reset();
return std::move(result);
}
__host__ __device__
bool valid() const
{
return data_;
}
template<class... Args,
class = typename std::enable_if<
std::is_constructible<T,Args...>::value
>::type>
__host__ __device__
void set_valid(cudaStream_t s, Args&&... ready_args)
{
data_ = make_unique<T>(s, std::forward<Args>(ready_args)...);
}
__host__ __device__
void swap(future_state& other)
{
data_.swap(other.data_);
}
private:
unique_ptr<T> data_;
};
// when a type is empty, we can create it on the fly upon dereference
template<class T>
struct empty_type_ptr : T
{
using element_type = T;
__host__ __device__
T& operator*()
{
return *this;
}
__host__ __device__
const T& operator*() const
{
return *this;
}
};
template<>
struct empty_type_ptr<void> : unit_ptr {};
// zero storage optimization
template<class T>
class future_state<T,true>
{
public:
__host__ __device__
future_state() : valid_(false) {}
// constructs a valid state
template<class U,
class = typename std::enable_if<
std::is_constructible<T,U>::value
>::type>
__host__ __device__
future_state(cudaStream_t, U&&) : valid_(true) {}
// constructs a valid state
__host__ __device__
future_state(cudaStream_t) : valid_(true) {}
__host__ __device__
future_state(future_state&& other) : valid_(false)
{
valid_ = other.valid_;
other.valid_ = false;
}
// 1. allow moves to void states (this simply discards the state)
// 2. allow moves to empty types if the type can be constructed from an empty argument list
template<class U,
class T1 = T,
class = typename std::enable_if<
std::is_void<T1>::value ||
(std::is_empty<T>::value && std::is_void<U>::value && std::is_constructible<T>::value)
>::type>
__host__ __device__
future_state(future_state<U>&& other)
: valid_(other.valid())
{
if(valid())
{
// invalidate the old state by calling .get() if it was valid when we received it
other.get();
}
}
__host__ __device__
future_state& operator=(future_state&& other)
{
valid_ = other.valid_;
other.valid_ = false;
return *this;
}
__host__ __device__
empty_type_ptr<T> data()
{
return empty_type_ptr<T>();
}
__host__ __device__
T get()
{
valid_ = false;
return get_impl(std::is_void<T>());
}
__host__ __device__
bool valid() const
{
return valid_;
}
// constructor arguments are simply ignored
// XXX if the constructor has a side effect, we probably need to actually invoke it, even though
// the type has no state and requires no storage
template<class... Args>
__host__ __device__
void set_valid(cudaStream_t, Args&&...)
{
valid_ = true;
}
__host__ __device__
void swap(future_state& other)
{
bool other_valid_old = other.valid_;
other.valid_ = valid_;
valid_ = other_valid_old;
}
private:
__host__ __device__
static T get_impl(std::false_type)
{
return T{};
}
__host__ __device__
static T get_impl(std::true_type)
{
return;
}
bool valid_;
};
// declare this so future may befriend it
template<class Shape, class Index, class ThisIndexFunction>
class basic_grid_executor;
} // end detail
template<typename T>
class future
{
private:
cudaStream_t stream_;
cudaEvent_t event_;
detail::future_state<T> state_;
public:
// XXX this should be private
__host__ __device__
future(cudaStream_t s) : future(s, 0) {}
// XXX stream_ should default to per-thread default stream
__host__ __device__
future() : future(0) {}
__host__ __device__
future(future&& other)
: future()
{
future::swap(stream_, other.stream_);
future::swap(event_, other.event_);
state_.swap(other.state_);
} // end future()
__host__ __device__
future &operator=(future&& other)
{
future::swap(stream_, other.stream_);
future::swap(event_, other.event_);
future::swap(state_, other.state_);
return *this;
} // end operator=()
template<class U,
class = typename std::enable_if<
std::is_constructible<
detail::future_state<T>,
detail::future_state<U>&&
>::value
>::type>
__host__ __device__
future(future<U>&& other)
: stream_(),
event_(),
state_(std::move(other.state_))
{
future::swap(stream_, other.stream_);
future::swap(event_, other.event_);
} // end future()
__host__ __device__
~future()
{
if(valid())
{
destroy_event();
} // end if
} // end ~future()
__host__ __device__
void wait() const
{
// XXX should probably check for valid() here
#if __cuda_lib_has_cudart
#ifndef __CUDA_ARCH__
// XXX need to capture the error as an exception and then throw it in .get()
detail::throw_on_error(cudaEventSynchronize(event_), "cudaEventSynchronize in agency::cuda<void>::future::wait");
#else
// XXX need to capture the error as an exception and then throw it in .get()
detail::throw_on_error(cudaDeviceSynchronize(), "cudaDeviceSynchronize in agency::cuda<void>::future::wait");
#endif // __CUDA_ARCH__
#else
detail::terminate_with_message("agency::cuda::future<void>::wait() requires CUDART");
#endif // __cuda_lib_has_cudart
} // end wait()
__host__ __device__
T get()
{
wait();
return state_.get();
} // end get()
__host__ __device__
bool valid() const
{
return (event_ != 0) && state_.valid();
} // end valid()
__host__ __device__
cudaEvent_t event() const
{
return event_;
} // end event()
__host__ __device__
cudaStream_t stream() const
{
return stream_;
} // end stream()
template<class... Args,
class = typename std::enable_if<
detail::is_constructible_or_void<T,Args...>::value
>::type>
__host__ __device__
static future make_ready(Args&&... args)
{
cudaEvent_t ready_event = 0;
#if __cuda_lib_has_cudart
detail::throw_on_error(cudaEventCreateWithFlags(&ready_event, event_create_flags), "cudaEventCreateWithFlags in agency::cuda::future<void>::make_ready");
#else
detail::terminate_with_message("agency::cuda::future<void>::make_ready() requires CUDART");
#endif
future result;
result.set_valid(ready_event, std::forward<Args>(args)...);
return result;
}
// XXX this is only used by grid_executor::then_execute()
__host__ __device__
auto data() -> decltype(state_.data())
{
return state_.data();
}
template<class Function>
__host__ __device__
future<agency::detail::result_of_continuation_t<Function,future>>
then(Function f)
{
// create state for the continuation's result
using result_type = agency::detail::result_of_continuation_t<Function,future>;
detail::future_state<result_type> result_state(stream());
// get a pointer to the continuation's kernel
using result_ptr_type = decltype(result_state.data());
using arg_ptr_type = decltype(data());
void (*kernel_ptr)(result_ptr_type, Function, arg_ptr_type) = detail::then_kernel<result_ptr_type, Function, arg_ptr_type>;
detail::workaround_unused_variable_warning(kernel_ptr);
// launch the continuation
cudaEvent_t next_event = detail::checked_launch_kernel_after_event_returning_next_event(reinterpret_cast<void*>(kernel_ptr), dim3{1}, dim3{1}, 0, stream(), event(), result_state.data(), f, data());
// this future's event is no longer usable
// note this invalidates this future
destroy_event();
// return the continuation's future
return future<result_type>(stream(), next_event, std::move(result_state));
}
// XXX set_valid() should only be available to friends
// such as future<U> and grid_executor
template<class... Args,
class = typename std::enable_if<
detail::is_constructible_or_void<T,Args...>::value
>::type>
__host__ __device__
void set_valid(cudaEvent_t e, Args&&... args)
{
event_ = e;
state_.set_valid(stream(), std::forward<Args>(args)...);
}
private:
template<class U> friend class future;
template<class Shape, class Index, class ThisIndexFunction> friend class agency::cuda::detail::basic_grid_executor;
__host__ __device__
future(cudaStream_t s, cudaEvent_t e, detail::future_state<T>&& state)
: stream_(s), event_(e), state_(std::move(state))
{}
template<class... Args,
class = typename std::enable_if<
detail::is_constructible_or_void<T,Args...>::value
>::type>
__host__ __device__
future(cudaStream_t s, cudaEvent_t e, Args&&... ready_args)
: future(s, e, detail::future_state<T>(s, std::forward<Args>(ready_args)...))
{}
// implement swap to avoid depending on thrust::swap
template<class U>
__host__ __device__
static void swap(U& a, U& b)
{
U tmp{a};
a = b;
b = tmp;
}
static const int event_create_flags = cudaEventDisableTiming;
__host__ __device__
void destroy_event()
{
#if __cuda_lib_has_cudart
// since this will likely be called from destructors, swallow errors
cudaError_t e = cudaEventDestroy(event_);
event_ = 0;
#if __cuda_lib_has_printf
if(e)
{
printf("CUDA error after cudaEventDestroy in agency::cuda::future<void> dtor: %s", cudaGetErrorString(e));
} // end if
#endif // __cuda_lib_has_printf
#endif // __cuda_lib_has_cudart
}
};
inline __host__ __device__
future<void> make_ready_future()
{
return future<void>::make_ready();
} // end make_ready_future()
template<class T>
inline __host__ __device__
future<typename std::decay<T>::type> make_ready_future(T&& value)
{
return future<typename std::decay<T>::type>::make_ready(std::forward<T>(value));
} // end make_ready_future()
} // end namespace cuda
} // end namespace agency
<commit_msg>Simplify some of future_state's members<commit_after>/*
* Copyright 2008-2013 NVIDIA Corporation
*
* 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.
*/
#pragma once
#include <agency/detail/config.hpp>
#include <agency/cuda/detail/feature_test.hpp>
#include <agency/cuda/detail/terminate.hpp>
#include <agency/cuda/detail/unique_ptr.hpp>
#include <agency/cuda/detail/then_kernel.hpp>
#include <agency/cuda/detail/launch_kernel.hpp>
#include <agency/cuda/detail/workaround_unused_variable_warning.hpp>
#include <agency/future.hpp>
#include <agency/detail/type_traits.hpp>
#include <utility>
#include <type_traits>
namespace agency
{
namespace cuda
{
namespace detail
{
template<class T, class... Args>
struct is_constructible_or_void
: std::integral_constant<
bool,
std::is_constructible<T,Args...>::value ||
(std::is_void<T>::value && (sizeof...(Args) == 0))
>
{};
template<class T>
struct state_requires_storage
: std::integral_constant<
bool,
std::is_empty<T>::value || std::is_void<T>::value || agency::detail::is_empty_tuple<T>::value
>
{};
// XXX should maybe call this asynchronous_state to match the nomenclature of the std
template<class T,
bool requires_storage = state_requires_storage<T>::value>
class future_state
{
public:
__host__ __device__
future_state() = default;
template<class Arg1, class... Args,
class = typename std::enable_if<
std::is_constructible<T,Arg1,Args...>::value
>::type
>
__host__ __device__
future_state(cudaStream_t s, Arg1&& ready_arg1, Args&&... ready_args)
: data_(make_unique<T>(s, std::forward<Arg1>(ready_arg1), std::forward<Args>(ready_args)...))
{}
__host__ __device__
future_state(cudaStream_t s)
: future_state(s, T{})
{}
__host__ __device__
future_state(future_state&& other) = default;
__host__ __device__
future_state& operator=(future_state&&) = default;
__host__ __device__
T* data()
{
return data_.get();
}
__host__ __device__
T get()
{
T result = std::move(*data_);
data_.reset();
return std::move(result);
}
__host__ __device__
bool valid() const
{
return data_;
}
template<class... Args,
class = typename std::enable_if<
std::is_constructible<T,Args...>::value
>::type>
__host__ __device__
void set_valid(cudaStream_t s, Args&&... ready_args)
{
data_ = make_unique<T>(s, std::forward<Args>(ready_args)...);
}
__host__ __device__
void swap(future_state& other)
{
data_.swap(other.data_);
}
private:
unique_ptr<T> data_;
};
// when a type is empty, we can create it on the fly upon dereference
template<class T>
struct empty_type_ptr : T
{
using element_type = T;
__host__ __device__
T& operator*()
{
return *this;
}
__host__ __device__
const T& operator*() const
{
return *this;
}
};
template<>
struct empty_type_ptr<void> : unit_ptr {};
// zero storage optimization
template<class T>
class future_state<T,true>
{
public:
__host__ __device__
future_state() : valid_(false) {}
// constructs a valid state
template<class U,
class = typename std::enable_if<
std::is_constructible<T,U>::value
>::type>
__host__ __device__
future_state(cudaStream_t, U&&) : valid_(true) {}
// constructs a valid state
__host__ __device__
future_state(cudaStream_t) : valid_(true) {}
__host__ __device__
future_state(future_state&& other) : valid_(other.valid_)
{
other.valid_ = false;
}
// 1. allow moves to void states (this simply discards the state)
// 2. allow moves to empty types if the type can be constructed from an empty argument list
template<class U,
class T1 = T,
class = typename std::enable_if<
std::is_void<T1>::value ||
(std::is_empty<T>::value && std::is_void<U>::value && std::is_constructible<T>::value)
>::type>
__host__ __device__
future_state(future_state<U>&& other)
: valid_(other.valid())
{
if(valid())
{
// invalidate the old state by calling .get() if it was valid when we received it
other.get();
}
}
__host__ __device__
future_state& operator=(future_state&& other)
{
valid_ = other.valid_;
other.valid_ = false;
return *this;
}
__host__ __device__
empty_type_ptr<T> data()
{
return empty_type_ptr<T>();
}
__host__ __device__
T get()
{
valid_ = false;
return get_impl(std::is_void<T>());
}
__host__ __device__
bool valid() const
{
return valid_;
}
// constructor arguments are simply ignored
// XXX if the constructor has a side effect, we probably need to actually invoke it, even though
// the type has no state and requires no storage
template<class... Args>
__host__ __device__
void set_valid(cudaStream_t, Args&&...)
{
valid_ = true;
}
__host__ __device__
void swap(future_state& other)
{
bool other_valid_old = other.valid_;
other.valid_ = valid_;
valid_ = other_valid_old;
}
private:
__host__ __device__
static T get_impl(std::false_type)
{
return T{};
}
__host__ __device__
static T get_impl(std::true_type)
{
return;
}
bool valid_;
};
// declare this so future may befriend it
template<class Shape, class Index, class ThisIndexFunction>
class basic_grid_executor;
} // end detail
template<typename T>
class future
{
private:
cudaStream_t stream_;
cudaEvent_t event_;
detail::future_state<T> state_;
public:
// XXX this should be private
__host__ __device__
future(cudaStream_t s) : future(s, 0) {}
// XXX stream_ should default to per-thread default stream
__host__ __device__
future() : future(0) {}
__host__ __device__
future(future&& other)
: future()
{
future::swap(stream_, other.stream_);
future::swap(event_, other.event_);
state_.swap(other.state_);
} // end future()
__host__ __device__
future &operator=(future&& other)
{
future::swap(stream_, other.stream_);
future::swap(event_, other.event_);
future::swap(state_, other.state_);
return *this;
} // end operator=()
template<class U,
class = typename std::enable_if<
std::is_constructible<
detail::future_state<T>,
detail::future_state<U>&&
>::value
>::type>
__host__ __device__
future(future<U>&& other)
: stream_(),
event_(),
state_(std::move(other.state_))
{
future::swap(stream_, other.stream_);
future::swap(event_, other.event_);
} // end future()
__host__ __device__
~future()
{
if(valid())
{
destroy_event();
} // end if
} // end ~future()
__host__ __device__
void wait() const
{
// XXX should probably check for valid() here
#if __cuda_lib_has_cudart
#ifndef __CUDA_ARCH__
// XXX need to capture the error as an exception and then throw it in .get()
detail::throw_on_error(cudaEventSynchronize(event_), "cudaEventSynchronize in agency::cuda<void>::future::wait");
#else
// XXX need to capture the error as an exception and then throw it in .get()
detail::throw_on_error(cudaDeviceSynchronize(), "cudaDeviceSynchronize in agency::cuda<void>::future::wait");
#endif // __CUDA_ARCH__
#else
detail::terminate_with_message("agency::cuda::future<void>::wait() requires CUDART");
#endif // __cuda_lib_has_cudart
} // end wait()
__host__ __device__
T get()
{
wait();
return state_.get();
} // end get()
__host__ __device__
bool valid() const
{
return (event_ != 0) && state_.valid();
} // end valid()
__host__ __device__
cudaEvent_t event() const
{
return event_;
} // end event()
__host__ __device__
cudaStream_t stream() const
{
return stream_;
} // end stream()
template<class... Args,
class = typename std::enable_if<
detail::is_constructible_or_void<T,Args...>::value
>::type>
__host__ __device__
static future make_ready(Args&&... args)
{
cudaEvent_t ready_event = 0;
#if __cuda_lib_has_cudart
detail::throw_on_error(cudaEventCreateWithFlags(&ready_event, event_create_flags), "cudaEventCreateWithFlags in agency::cuda::future<void>::make_ready");
#else
detail::terminate_with_message("agency::cuda::future<void>::make_ready() requires CUDART");
#endif
future result;
result.set_valid(ready_event, std::forward<Args>(args)...);
return result;
}
// XXX this is only used by grid_executor::then_execute()
__host__ __device__
auto data() -> decltype(state_.data())
{
return state_.data();
}
template<class Function>
__host__ __device__
future<agency::detail::result_of_continuation_t<Function,future>>
then(Function f)
{
// create state for the continuation's result
using result_type = agency::detail::result_of_continuation_t<Function,future>;
detail::future_state<result_type> result_state(stream());
// get a pointer to the continuation's kernel
using result_ptr_type = decltype(result_state.data());
using arg_ptr_type = decltype(data());
void (*kernel_ptr)(result_ptr_type, Function, arg_ptr_type) = detail::then_kernel<result_ptr_type, Function, arg_ptr_type>;
detail::workaround_unused_variable_warning(kernel_ptr);
// launch the continuation
cudaEvent_t next_event = detail::checked_launch_kernel_after_event_returning_next_event(reinterpret_cast<void*>(kernel_ptr), dim3{1}, dim3{1}, 0, stream(), event(), result_state.data(), f, data());
// this future's event is no longer usable
// note this invalidates this future
destroy_event();
// return the continuation's future
return future<result_type>(stream(), next_event, std::move(result_state));
}
// XXX set_valid() should only be available to friends
// such as future<U> and grid_executor
template<class... Args,
class = typename std::enable_if<
detail::is_constructible_or_void<T,Args...>::value
>::type>
__host__ __device__
void set_valid(cudaEvent_t e, Args&&... args)
{
event_ = e;
state_.set_valid(stream(), std::forward<Args>(args)...);
}
private:
template<class U> friend class future;
template<class Shape, class Index, class ThisIndexFunction> friend class agency::cuda::detail::basic_grid_executor;
__host__ __device__
future(cudaStream_t s, cudaEvent_t e, detail::future_state<T>&& state)
: stream_(s), event_(e), state_(std::move(state))
{}
template<class... Args,
class = typename std::enable_if<
detail::is_constructible_or_void<T,Args...>::value
>::type>
__host__ __device__
future(cudaStream_t s, cudaEvent_t e, Args&&... ready_args)
: future(s, e, detail::future_state<T>(s, std::forward<Args>(ready_args)...))
{}
// implement swap to avoid depending on thrust::swap
template<class U>
__host__ __device__
static void swap(U& a, U& b)
{
U tmp{a};
a = b;
b = tmp;
}
static const int event_create_flags = cudaEventDisableTiming;
__host__ __device__
void destroy_event()
{
#if __cuda_lib_has_cudart
// since this will likely be called from destructors, swallow errors
cudaError_t e = cudaEventDestroy(event_);
event_ = 0;
#if __cuda_lib_has_printf
if(e)
{
printf("CUDA error after cudaEventDestroy in agency::cuda::future<void> dtor: %s", cudaGetErrorString(e));
} // end if
#endif // __cuda_lib_has_printf
#endif // __cuda_lib_has_cudart
}
};
inline __host__ __device__
future<void> make_ready_future()
{
return future<void>::make_ready();
} // end make_ready_future()
} // end namespace cuda
} // end namespace agency
<|endoftext|>
|
<commit_before>/* perform smoothing using an anisotropic diffusion filter */
#include "itkVVFilterModule.h"
#include "itkGradientAnisotropicDiffusionImageFilter.h"
static int ProcessData(void *inf, vtkVVProcessDataStruct *pds)
{
vtkVVPluginInfo *info = (vtkVVPluginInfo *)inf;
const unsigned int Dimension = 3;
typedef float InternalPixelType;
typedef itk::Image< InternalPixelType,Dimension > InternalImageType;
typedef itk::GradientAnisotropicDiffusionImageFilter<
InternalImageType,
InternalImageType > FilterType;
try
{
switch( info->InputVolumeScalarType )
{
case VTK_UNSIGNED_CHAR:
{
FilterModule< unsigned char, FilterType > module;
module.SetPlugInfo( info );
module.SetUpdateMessage("Smoothing with Gradient Anisotropic Diffusion...");
// Set the parameters on it
module.GetFilter()->SetIterations( atoi( info->GUIItems[ 0 ].CurrentValue) );
module.GetFilter()->SetConductanceParameter( atof( info->GUIItems[ 1 ].CurrentValue) );
module.SetNeedCasting( true );
// Execute the filter
module.ProcessData( pds );
break;
}
case VTK_UNSIGNED_SHORT:
{
FilterModule< unsigned short, FilterType > module;
module.SetPlugInfo( info );
module.SetUpdateMessage("Smoothing with Gradient Anisotropic Diffusion...");
// Set the parameters on it
module.GetFilter()->SetIterations( atoi( info->GUIItems[ 0 ].CurrentValue) );
module.GetFilter()->SetConductanceParameter( atof( info->GUIItems[ 1 ].CurrentValue) );
module.SetNeedCasting( true );
// Execute the filter
module.ProcessData( pds );
break;
}
}
}
catch( itk::ExceptionObject & except )
{
info->DisplayError( info, except.what() );
return -1;
}
return 0;
}
static int UpdateGUI(void *inf)
{
vtkVVPluginInfo *info = (vtkVVPluginInfo *)inf;
info->GUIItems[0].Label = "Number of Iterations";
info->GUIItems[0].GUIType = VV_GUI_SCALE;
info->GUIItems[0].Default = "5";
info->GUIItems[0].Help = "Number of times that the diffusion approximation will be computed. The more iterations, the stronger the smoothing";
info->GUIItems[0].Hints = "1 100 1";
info->GUIItems[1].Label = "Conductance";
info->GUIItems[1].GUIType = VV_GUI_SCALE;
info->GUIItems[1].Default = "3.0";
info->GUIItems[1].Help = "Factor that multiplies the image gradient in order to compute the effective conductance locally. The higher the value of this parameter, the stronger the diffusion will be";
info->GUIItems[1].Hints = "0.1 10.0 0.1";
info->RequiredZOverlap = 0;
info->OutputVolumeScalarType = info->InputVolumeScalarType;
info->OutputVolumeNumberOfComponents =
info->InputVolumeNumberOfComponents;
memcpy(info->OutputVolumeDimensions,info->InputVolumeDimensions,
3*sizeof(int));
memcpy(info->OutputVolumeSpacing,info->InputVolumeSpacing,
3*sizeof(float));
memcpy(info->OutputVolumeOrigin,info->InputVolumeOrigin,
3*sizeof(float));
return 1;
}
extern "C" {
void VV_PLUGIN_EXPORT vvGradientAnisotropicDiffusionInit(vtkVVPluginInfo *info)
{
// setup information that never changes
info->ProcessData = ProcessData;
info->UpdateGUI = UpdateGUI;
info->Name = "Gradient Anisotropic Diffusion";
info->TerseDocumentation = "Anisotropic diffusion smoothing";
info->FullDocumentation =
"This filter applies an edge-preserving smoothing to a volume by computing the evolution of an anisotropic diffusion partial differential equation. Diffusion is regulated by the gradient of the image. This filter processes the whole image in one piece, and does not change the dimensions, data type, or spacing of the volume.";
info->SupportsInPlaceProcessing = 0;
info->SupportsProcessingPieces = 0;
info->RequiredZOverlap = 0;
/* setup the GUI components */
info->NumberOfGUIItems = 2;
info->GUIItems = (vtkVVGUIItem *)malloc(info->NumberOfGUIItems*sizeof(vtkVVGUIItem));
}
}
<commit_msg>ENH: TimeStep parameter is back after confirmation from Josh that the parameter is still needed.<commit_after>/* perform smoothing using an anisotropic diffusion filter */
#include "itkVVFilterModule.h"
#include "itkGradientAnisotropicDiffusionImageFilter.h"
static int ProcessData(void *inf, vtkVVProcessDataStruct *pds)
{
vtkVVPluginInfo *info = (vtkVVPluginInfo *)inf;
const unsigned int Dimension = 3;
typedef float InternalPixelType;
typedef itk::Image< InternalPixelType,Dimension > InternalImageType;
typedef itk::GradientAnisotropicDiffusionImageFilter<
InternalImageType,
InternalImageType > FilterType;
try
{
switch( info->InputVolumeScalarType )
{
case VTK_UNSIGNED_CHAR:
{
FilterModule< unsigned char, FilterType > module;
module.SetPlugInfo( info );
module.SetUpdateMessage("Smoothing with Gradient Anisotropic Diffusion...");
// Set the parameters on it
module.GetFilter()->SetIterations( atoi( info->GUIItems[ 0 ].CurrentValue) );
module.GetFilter()->SetTimeStep( atof( info->GUIItems[ 1 ].CurrentValue) );
module.GetFilter()->SetConductanceParameter( atof( info->GUIItems[ 2 ].CurrentValue) );
module.SetNeedCasting( true );
// Execute the filter
module.ProcessData( pds );
break;
}
case VTK_UNSIGNED_SHORT:
{
FilterModule< unsigned short, FilterType > module;
module.SetPlugInfo( info );
module.SetUpdateMessage("Smoothing with Gradient Anisotropic Diffusion...");
// Set the parameters on it
module.GetFilter()->SetIterations( atoi( info->GUIItems[ 0 ].CurrentValue) );
module.GetFilter()->SetTimeStep( atof( info->GUIItems[ 1 ].CurrentValue) );
module.GetFilter()->SetConductanceParameter( atof( info->GUIItems[ 2 ].CurrentValue) );
module.SetNeedCasting( true );
// Execute the filter
module.ProcessData( pds );
break;
}
}
}
catch( itk::ExceptionObject & except )
{
info->DisplayError( info, except.what() );
return -1;
}
return 0;
}
static int UpdateGUI(void *inf)
{
vtkVVPluginInfo *info = (vtkVVPluginInfo *)inf;
info->GUIItems[0].Label = "Number of Iterations";
info->GUIItems[0].GUIType = VV_GUI_SCALE;
info->GUIItems[0].Default = "5";
info->GUIItems[0].Help = "Number of times that the diffusion approximation will be computed. The more iterations, the stronger the smoothing";
info->GUIItems[0].Hints = "1 100 1";
info->GUIItems[1].Label = "Time Step";
info->GUIItems[1].GUIType = VV_GUI_SCALE;
info->GUIItems[1].Default = "0.125";
info->GUIItems[1].Help = "Discretization of time for approximating the diffusion process.";
info->GUIItems[1].Hints = "0.01 1.0 0.005";
info->GUIItems[2].Label = "Conductance";
info->GUIItems[2].GUIType = VV_GUI_SCALE;
info->GUIItems[2].Default = "3.0";
info->GUIItems[2].Help = "Factor that multiplies the image gradient in order to compute the effective conductance locally. The higher the value of this parameter, the stronger the diffusion will be";
info->GUIItems[2].Hints = "0.1 10.0 0.1";
info->RequiredZOverlap = 0;
info->OutputVolumeScalarType = info->InputVolumeScalarType;
info->OutputVolumeNumberOfComponents =
info->InputVolumeNumberOfComponents;
memcpy(info->OutputVolumeDimensions,info->InputVolumeDimensions,
3*sizeof(int));
memcpy(info->OutputVolumeSpacing,info->InputVolumeSpacing,
3*sizeof(float));
memcpy(info->OutputVolumeOrigin,info->InputVolumeOrigin,
3*sizeof(float));
return 1;
}
extern "C" {
void VV_PLUGIN_EXPORT vvGradientAnisotropicDiffusionInit(vtkVVPluginInfo *info)
{
// setup information that never changes
info->ProcessData = ProcessData;
info->UpdateGUI = UpdateGUI;
info->Name = "Gradient Anisotropic Diffusion";
info->TerseDocumentation = "Anisotropic diffusion smoothing";
info->FullDocumentation =
"This filter applies an edge-preserving smoothing to a volume by computing the evolution of an anisotropic diffusion partial differential equation. Diffusion is regulated by the gradient of the image. This filter processes the whole image in one piece, and does not change the dimensions, data type, or spacing of the volume.";
info->SupportsInPlaceProcessing = 0;
info->SupportsProcessingPieces = 0;
info->RequiredZOverlap = 0;
/* setup the GUI components */
info->NumberOfGUIItems = 3;
info->GUIItems = (vtkVVGUIItem *)malloc(info->NumberOfGUIItems*sizeof(vtkVVGUIItem));
}
}
<|endoftext|>
|
<commit_before>//===--- Dexp.cpp - Dex EXPloration tool ------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements a simple interactive tool which can be used to manually
// evaluate symbol search quality of Clangd index.
//
//===----------------------------------------------------------------------===//
#include "SourceCode.h"
#include "index/Serialization.h"
#include "index/dex/Dex.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/LineEditor/LineEditor.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Signals.h"
using namespace llvm;
using namespace clang;
using namespace clangd;
namespace {
cl::opt<std::string> IndexPath("index-path", cl::desc("Path to the index"),
cl::Positional, cl::Required);
static const std::string Overview = R"(
This is an **experimental** interactive tool to process user-provided search
queries over given symbol collection obtained via clangd-indexer. The
tool can be used to evaluate search quality of existing index implementations
and manually construct non-trivial test cases.
Type use "help" request to get information about the details.
)";
void reportTime(StringRef Name, function_ref<void()> F) {
const auto TimerStart = std::chrono::high_resolution_clock::now();
F();
const auto TimerStop = std::chrono::high_resolution_clock::now();
const auto Duration = std::chrono::duration_cast<std::chrono::milliseconds>(
TimerStop - TimerStart);
outs() << formatv("{0} took {1:ms+n}.\n", Name, Duration);
}
std::vector<SymbolID> getSymbolIDsFromIndex(StringRef QualifiedName,
const SymbolIndex *Index) {
FuzzyFindRequest Request;
// Remove leading "::" qualifier as FuzzyFind doesn't need leading "::"
// qualifier for global scope.
bool IsGlobalScope = QualifiedName.consume_front("::");
auto Names = splitQualifiedName(QualifiedName);
if (IsGlobalScope || !Names.first.empty())
Request.Scopes = {Names.first};
else
// QualifiedName refers to a symbol in global scope (e.g. "GlobalSymbol"),
// add the global scope to the request.
Request.Scopes = {""};
Request.Query = Names.second;
std::vector<SymbolID> SymIDs;
Index->fuzzyFind(Request, [&](const Symbol &Sym) {
std::string SymQualifiedName = (Sym.Scope + Sym.Name).str();
if (QualifiedName == SymQualifiedName)
SymIDs.push_back(Sym.ID);
});
return SymIDs;
}
// REPL commands inherit from Command and contain their options as members.
// Creating a Command populates parser options, parseAndRun() resets them.
class Command {
// By resetting the parser options, we lost the standard -help flag.
cl::opt<bool, false, cl::parser<bool>> Help{
"help", cl::desc("Display available options"), cl::ValueDisallowed,
cl::cat(cl::GeneralCategory)};
virtual void run() = 0;
protected:
const SymbolIndex *Index;
public:
virtual ~Command() = default;
virtual void parseAndRun(ArrayRef<const char *> Argv, const char *Overview,
const SymbolIndex &Index) {
std::string ParseErrs;
raw_string_ostream OS(ParseErrs);
bool Ok =
cl::ParseCommandLineOptions(Argv.size(), Argv.data(), Overview, &OS);
if (Help.getNumOccurrences() > 0) {
// Avoid printing parse errors in this case.
// (Well, in theory. A bunch get printed to llvm::errs() regardless!)
cl::PrintHelpMessage();
} else {
outs() << OS.str();
if (Ok) {
this->Index = &Index;
reportTime(Argv[0], [&] { run(); });
}
}
cl::ResetCommandLineParser(); // must do this before opts are destroyed.
}
};
// FIXME(kbobyrev): Ideas for more commands:
// * load/swap/reload index: this would make it possible to get rid of llvm::cl
// usages in the tool driver and actually use llvm::cl library in the REPL.
// * show posting list density histogram (our dump data somewhere so that user
// could build one)
// * show number of tokens of each kind
// * print out tokens with the most dense posting lists
// * print out tokens with least dense posting lists
class FuzzyFind : public Command {
cl::opt<std::string> Query{
"query",
cl::Positional,
cl::Required,
cl::desc("Query string to be fuzzy-matched"),
};
cl::opt<std::string> Scopes{
"scopes",
cl::desc("Allowed symbol scopes (comma-separated list)"),
};
cl::opt<unsigned> Limit{
"limit",
cl::init(10),
cl::desc("Max results to display"),
};
void run() override {
FuzzyFindRequest Request;
Request.Limit = Limit;
Request.Query = Query;
if (Scopes.getNumOccurrences() > 0) {
SmallVector<StringRef, 8> Scopes;
StringRef(this->Scopes).split(Scopes, ',');
Request.Scopes = {Scopes.begin(), Scopes.end()};
}
Request.AnyScope = Request.Scopes.empty();
// FIXME(kbobyrev): Print symbol final scores to see the distribution.
static const auto OutputFormat = "{0,-4} | {1,-40} | {2,-25}\n";
outs() << formatv(OutputFormat, "Rank", "Symbol ID", "Symbol Name");
size_t Rank = 0;
Index->fuzzyFind(Request, [&](const Symbol &Sym) {
outs() << formatv(OutputFormat, Rank++, Sym.ID.str(), Sym.Name);
});
}
};
class Lookup : public Command {
cl::opt<std::string> ID{
"id",
cl::Positional,
cl::desc("Symbol ID to look up (hex)"),
};
cl::opt<std::string> Name{
"name", cl::desc("Qualified name to look up."),
};
void run() override {
if (ID.getNumOccurrences() == 0 && Name.getNumOccurrences() == 0) {
outs() << "Missing required argument: please provide id or -name.\n";
return;
}
std::vector<SymbolID> IDs;
if (ID.getNumOccurrences()) {
auto SID = SymbolID::fromStr(ID);
if (!SID) {
outs() << toString(SID.takeError()) << "\n";
return;
}
IDs.push_back(*SID);
} else {
IDs = getSymbolIDsFromIndex(Name, Index);
}
LookupRequest Request;
Request.IDs.insert(IDs.begin(), IDs.end());
bool FoundSymbol = false;
Index->lookup(Request, [&](const Symbol &Sym) {
FoundSymbol = true;
outs() << toYAML(Sym);
});
if (!FoundSymbol)
outs() << "not found\n";
}
};
class Refs : public Command {
cl::opt<std::string> ID{
"id", cl::Positional,
cl::desc("Symbol ID of the symbol being queried (hex)."),
};
cl::opt<std::string> Name{
"name", cl::desc("Qualified name of the symbol being queried."),
};
cl::opt<std::string> Filter{
"filter", cl::init(".*"),
cl::desc(
"Print all results from files matching this regular expression."),
};
void run() override {
if (ID.getNumOccurrences() == 0 && Name.getNumOccurrences() == 0) {
outs() << "Missing required argument: please provide id or -name.\n";
return;
}
std::vector<SymbolID> IDs;
if (ID.getNumOccurrences()) {
auto SID = SymbolID::fromStr(ID);
if (!SID) {
outs() << toString(SID.takeError()) << "\n";
return;
}
IDs.push_back(*SID);
} else {
IDs = getSymbolIDsFromIndex(Name, Index);
if (IDs.size() > 1) {
outs() << formatv("The name {0} is ambiguous, found {1} different "
"symbols. Please use id flag to disambiguate.\n",
Name, IDs.size());
return;
}
}
RefsRequest RefRequest;
RefRequest.IDs.insert(IDs.begin(), IDs.end());
Regex RegexFilter(Filter);
Index->refs(RefRequest, [&RegexFilter](const Ref &R) {
auto U = URI::parse(R.Location.FileURI);
if (!U) {
outs() << U.takeError();
return;
}
if (RegexFilter.match(U->body()))
outs() << R << "\n";
});
}
};
struct {
const char *Name;
const char *Description;
std::function<std::unique_ptr<Command>()> Implementation;
} CommandInfo[] = {
{"find", "Search for symbols with fuzzyFind", llvm::make_unique<FuzzyFind>},
{"lookup", "Dump symbol details by ID or qualified name",
llvm::make_unique<Lookup>},
{"refs", "Find references by ID or qualified name",
llvm::make_unique<Refs>},
};
std::unique_ptr<SymbolIndex> openIndex(StringRef Index) {
return loadIndex(Index, /*UseDex=*/true);
}
} // namespace
int main(int argc, const char *argv[]) {
cl::ParseCommandLineOptions(argc, argv, Overview);
cl::ResetCommandLineParser(); // We reuse it for REPL commands.
sys::PrintStackTraceOnErrorSignal(argv[0]);
std::unique_ptr<SymbolIndex> Index;
reportTime("Dex build", [&]() {
Index = openIndex(IndexPath);
});
if (!Index) {
outs() << "Failed to open the index.\n";
return -1;
}
LineEditor LE("dexp");
while (Optional<std::string> Request = LE.readLine()) {
// Split on spaces and add required null-termination.
std::replace(Request->begin(), Request->end(), ' ', '\0');
SmallVector<StringRef, 8> Args;
StringRef(*Request).split(Args, '\0', /*MaxSplit=*/-1, /*KeepEmpty=*/false);
if (Args.empty())
continue;
if (Args.front() == "help") {
outs() << "dexp - Index explorer\nCommands:\n";
for (const auto &C : CommandInfo)
outs() << formatv("{0,16} - {1}\n", C.Name, C.Description);
outs() << "Get detailed command help with e.g. `find -help`.\n";
continue;
}
SmallVector<const char *, 8> FakeArgv;
for (StringRef S : Args)
FakeArgv.push_back(S.data()); // Terminated by separator or end of string.
bool Recognized = false;
for (const auto &Cmd : CommandInfo) {
if (Cmd.Name == Args.front()) {
Recognized = true;
Cmd.Implementation()->parseAndRun(FakeArgv, Cmd.Description, *Index);
break;
}
}
if (!Recognized)
outs() << "Unknown command. Try 'help'.\n";
}
return 0;
}
<commit_msg>[dexp] Change FuzzyFind to also print scope of symbols<commit_after>//===--- Dexp.cpp - Dex EXPloration tool ------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements a simple interactive tool which can be used to manually
// evaluate symbol search quality of Clangd index.
//
//===----------------------------------------------------------------------===//
#include "SourceCode.h"
#include "index/Serialization.h"
#include "index/dex/Dex.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/LineEditor/LineEditor.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Signals.h"
using namespace llvm;
using namespace clang;
using namespace clangd;
namespace {
cl::opt<std::string> IndexPath("index-path", cl::desc("Path to the index"),
cl::Positional, cl::Required);
static const std::string Overview = R"(
This is an **experimental** interactive tool to process user-provided search
queries over given symbol collection obtained via clangd-indexer. The
tool can be used to evaluate search quality of existing index implementations
and manually construct non-trivial test cases.
Type use "help" request to get information about the details.
)";
void reportTime(StringRef Name, function_ref<void()> F) {
const auto TimerStart = std::chrono::high_resolution_clock::now();
F();
const auto TimerStop = std::chrono::high_resolution_clock::now();
const auto Duration = std::chrono::duration_cast<std::chrono::milliseconds>(
TimerStop - TimerStart);
outs() << formatv("{0} took {1:ms+n}.\n", Name, Duration);
}
std::vector<SymbolID> getSymbolIDsFromIndex(StringRef QualifiedName,
const SymbolIndex *Index) {
FuzzyFindRequest Request;
// Remove leading "::" qualifier as FuzzyFind doesn't need leading "::"
// qualifier for global scope.
bool IsGlobalScope = QualifiedName.consume_front("::");
auto Names = splitQualifiedName(QualifiedName);
if (IsGlobalScope || !Names.first.empty())
Request.Scopes = {Names.first};
else
// QualifiedName refers to a symbol in global scope (e.g. "GlobalSymbol"),
// add the global scope to the request.
Request.Scopes = {""};
Request.Query = Names.second;
std::vector<SymbolID> SymIDs;
Index->fuzzyFind(Request, [&](const Symbol &Sym) {
std::string SymQualifiedName = (Sym.Scope + Sym.Name).str();
if (QualifiedName == SymQualifiedName)
SymIDs.push_back(Sym.ID);
});
return SymIDs;
}
// REPL commands inherit from Command and contain their options as members.
// Creating a Command populates parser options, parseAndRun() resets them.
class Command {
// By resetting the parser options, we lost the standard -help flag.
cl::opt<bool, false, cl::parser<bool>> Help{
"help", cl::desc("Display available options"), cl::ValueDisallowed,
cl::cat(cl::GeneralCategory)};
virtual void run() = 0;
protected:
const SymbolIndex *Index;
public:
virtual ~Command() = default;
virtual void parseAndRun(ArrayRef<const char *> Argv, const char *Overview,
const SymbolIndex &Index) {
std::string ParseErrs;
raw_string_ostream OS(ParseErrs);
bool Ok =
cl::ParseCommandLineOptions(Argv.size(), Argv.data(), Overview, &OS);
if (Help.getNumOccurrences() > 0) {
// Avoid printing parse errors in this case.
// (Well, in theory. A bunch get printed to llvm::errs() regardless!)
cl::PrintHelpMessage();
} else {
outs() << OS.str();
if (Ok) {
this->Index = &Index;
reportTime(Argv[0], [&] { run(); });
}
}
cl::ResetCommandLineParser(); // must do this before opts are destroyed.
}
};
// FIXME(kbobyrev): Ideas for more commands:
// * load/swap/reload index: this would make it possible to get rid of llvm::cl
// usages in the tool driver and actually use llvm::cl library in the REPL.
// * show posting list density histogram (our dump data somewhere so that user
// could build one)
// * show number of tokens of each kind
// * print out tokens with the most dense posting lists
// * print out tokens with least dense posting lists
class FuzzyFind : public Command {
cl::opt<std::string> Query{
"query",
cl::Positional,
cl::Required,
cl::desc("Query string to be fuzzy-matched"),
};
cl::opt<std::string> Scopes{
"scopes",
cl::desc("Allowed symbol scopes (comma-separated list)"),
};
cl::opt<unsigned> Limit{
"limit",
cl::init(10),
cl::desc("Max results to display"),
};
void run() override {
FuzzyFindRequest Request;
Request.Limit = Limit;
Request.Query = Query;
if (Scopes.getNumOccurrences() > 0) {
SmallVector<StringRef, 8> Scopes;
StringRef(this->Scopes).split(Scopes, ',');
Request.Scopes = {Scopes.begin(), Scopes.end()};
}
Request.AnyScope = Request.Scopes.empty();
// FIXME(kbobyrev): Print symbol final scores to see the distribution.
static const auto OutputFormat = "{0,-4} | {1,-40} | {2,-25}\n";
outs() << formatv(OutputFormat, "Rank", "Symbol ID", "Symbol Name");
size_t Rank = 0;
Index->fuzzyFind(Request, [&](const Symbol &Sym) {
outs() << formatv(OutputFormat, Rank++, Sym.ID.str(),
Sym.Scope + Sym.Name);
});
}
};
class Lookup : public Command {
cl::opt<std::string> ID{
"id",
cl::Positional,
cl::desc("Symbol ID to look up (hex)"),
};
cl::opt<std::string> Name{
"name", cl::desc("Qualified name to look up."),
};
void run() override {
if (ID.getNumOccurrences() == 0 && Name.getNumOccurrences() == 0) {
outs() << "Missing required argument: please provide id or -name.\n";
return;
}
std::vector<SymbolID> IDs;
if (ID.getNumOccurrences()) {
auto SID = SymbolID::fromStr(ID);
if (!SID) {
outs() << toString(SID.takeError()) << "\n";
return;
}
IDs.push_back(*SID);
} else {
IDs = getSymbolIDsFromIndex(Name, Index);
}
LookupRequest Request;
Request.IDs.insert(IDs.begin(), IDs.end());
bool FoundSymbol = false;
Index->lookup(Request, [&](const Symbol &Sym) {
FoundSymbol = true;
outs() << toYAML(Sym);
});
if (!FoundSymbol)
outs() << "not found\n";
}
};
class Refs : public Command {
cl::opt<std::string> ID{
"id", cl::Positional,
cl::desc("Symbol ID of the symbol being queried (hex)."),
};
cl::opt<std::string> Name{
"name", cl::desc("Qualified name of the symbol being queried."),
};
cl::opt<std::string> Filter{
"filter", cl::init(".*"),
cl::desc(
"Print all results from files matching this regular expression."),
};
void run() override {
if (ID.getNumOccurrences() == 0 && Name.getNumOccurrences() == 0) {
outs() << "Missing required argument: please provide id or -name.\n";
return;
}
std::vector<SymbolID> IDs;
if (ID.getNumOccurrences()) {
auto SID = SymbolID::fromStr(ID);
if (!SID) {
outs() << toString(SID.takeError()) << "\n";
return;
}
IDs.push_back(*SID);
} else {
IDs = getSymbolIDsFromIndex(Name, Index);
if (IDs.size() > 1) {
outs() << formatv("The name {0} is ambiguous, found {1} different "
"symbols. Please use id flag to disambiguate.\n",
Name, IDs.size());
return;
}
}
RefsRequest RefRequest;
RefRequest.IDs.insert(IDs.begin(), IDs.end());
Regex RegexFilter(Filter);
Index->refs(RefRequest, [&RegexFilter](const Ref &R) {
auto U = URI::parse(R.Location.FileURI);
if (!U) {
outs() << U.takeError();
return;
}
if (RegexFilter.match(U->body()))
outs() << R << "\n";
});
}
};
struct {
const char *Name;
const char *Description;
std::function<std::unique_ptr<Command>()> Implementation;
} CommandInfo[] = {
{"find", "Search for symbols with fuzzyFind", llvm::make_unique<FuzzyFind>},
{"lookup", "Dump symbol details by ID or qualified name",
llvm::make_unique<Lookup>},
{"refs", "Find references by ID or qualified name",
llvm::make_unique<Refs>},
};
std::unique_ptr<SymbolIndex> openIndex(StringRef Index) {
return loadIndex(Index, /*UseDex=*/true);
}
} // namespace
int main(int argc, const char *argv[]) {
cl::ParseCommandLineOptions(argc, argv, Overview);
cl::ResetCommandLineParser(); // We reuse it for REPL commands.
sys::PrintStackTraceOnErrorSignal(argv[0]);
std::unique_ptr<SymbolIndex> Index;
reportTime("Dex build", [&]() {
Index = openIndex(IndexPath);
});
if (!Index) {
outs() << "Failed to open the index.\n";
return -1;
}
LineEditor LE("dexp");
while (Optional<std::string> Request = LE.readLine()) {
// Split on spaces and add required null-termination.
std::replace(Request->begin(), Request->end(), ' ', '\0');
SmallVector<StringRef, 8> Args;
StringRef(*Request).split(Args, '\0', /*MaxSplit=*/-1, /*KeepEmpty=*/false);
if (Args.empty())
continue;
if (Args.front() == "help") {
outs() << "dexp - Index explorer\nCommands:\n";
for (const auto &C : CommandInfo)
outs() << formatv("{0,16} - {1}\n", C.Name, C.Description);
outs() << "Get detailed command help with e.g. `find -help`.\n";
continue;
}
SmallVector<const char *, 8> FakeArgv;
for (StringRef S : Args)
FakeArgv.push_back(S.data()); // Terminated by separator or end of string.
bool Recognized = false;
for (const auto &Cmd : CommandInfo) {
if (Cmd.Name == Args.front()) {
Recognized = true;
Cmd.Implementation()->parseAndRun(FakeArgv, Cmd.Description, *Index);
break;
}
}
if (!Recognized)
outs() << "Unknown command. Try 'help'.\n";
}
return 0;
}
<|endoftext|>
|
<commit_before>#include "gtest/gtest.h"
#include "LinAlg/Vector.hpp"
#include "LinAlg/VectorView.hpp"
#include "LinAlg/DiagonalMatrix.hpp"
#include "LinAlg/Matrix.hpp"
#include "LinAlg/Selector.hpp"
#include "distributions.hpp"
#include "cpputil/math_utils.hpp"
#include "test_utils/test_utils.hpp"
#include <fstream>
namespace {
using namespace BOOM;
using std::endl;
using std::cout;
class SelectorTest : public ::testing::Test {
protected:
SelectorTest() {
GlobalRng::rng.seed(8675309);
}
};
TEST_F(SelectorTest, Equality) {
Selector s1("001");
Selector s2("101");
EXPECT_NE(s1, s2);
EXPECT_TRUE(s1 != s2);
EXPECT_FALSE(s1 == s2);
s2.flip(0); // now 001
EXPECT_EQ(s1, s2);
EXPECT_TRUE(s1 == s2);
EXPECT_FALSE(s1 != s2);
s2.flip(0);
swap(s1, s2);
Selector s3("001");
EXPECT_EQ(s2, s3);
EXPECT_NE(s1, s3);
s3.flip(0);
EXPECT_EQ(s1, s3);
EXPECT_NE(s2, s3);
}
TEST_F(SelectorTest, Indexing) {
Selector s1("101001101");
EXPECT_EQ(s1.nvars(), 5);
EXPECT_EQ(s1.nvars_possible(), 9);
EXPECT_EQ(s1.nvars_excluded(), 4);
EXPECT_EQ(0, s1.indx(0));
EXPECT_EQ(2, s1.indx(1));
EXPECT_EQ(5, s1.indx(2));
EXPECT_EQ(6, s1.indx(3));
EXPECT_EQ(8, s1.indx(4));
EXPECT_EQ(0, s1.INDX(0));
EXPECT_EQ(1, s1.INDX(2));
EXPECT_EQ(2, s1.INDX(5));
EXPECT_EQ(3, s1.INDX(6));
EXPECT_EQ(4, s1.INDX(8));
}
TEST_F(SelectorTest, Append) {
Selector s1("010");
EXPECT_EQ(s1.nvars(), 1);
EXPECT_EQ(s1.nvars_possible(), 3);
s1.push_back(true);
EXPECT_EQ(s1.nvars(), 2);
EXPECT_EQ(s1.nvars_possible(), 4);
s1.push_back(false);
EXPECT_EQ(s1.nvars(), 2);
EXPECT_EQ(s1.nvars_possible(), 5);
// Current state is "01010".
// Set it to "0100"
s1.erase(3);
EXPECT_EQ(s1.nvars(), 1);
EXPECT_EQ(s1.nvars_possible(), 4);
EXPECT_TRUE(s1[1]);
}
TEST_F(SelectorTest, ToVectorTest) {
Selector s("00010");
Vector v = s.to_Vector();
EXPECT_EQ(v.size(), 5);
EXPECT_DOUBLE_EQ(v[0], 0);
EXPECT_DOUBLE_EQ(v[1], 0);
EXPECT_DOUBLE_EQ(v[2], 0);
EXPECT_DOUBLE_EQ(v[3], 1);
EXPECT_DOUBLE_EQ(v[4], 0);
}
TEST_F(SelectorTest, SelectRowsTest) {
Matrix big(10, 4);
big.randomize();
Selector inc(10, false);
inc.add(2);
inc.add(7);
Matrix small = inc.select_rows(big);
EXPECT_EQ(2, small.nrow());
EXPECT_EQ(4, small.ncol());
EXPECT_TRUE(VectorEquals(small.row(0), big.row(2)));
big.randomize();
ConstSubMatrix big_view(big);
small = inc.select_rows(big_view);
EXPECT_EQ(2, small.nrow());
EXPECT_EQ(4, small.ncol());
EXPECT_TRUE(VectorEquals(small.row(0), big.row(2)));
big.randomize();
SubMatrix mutable_big_view(big);
small = inc.select_rows(big_view);
EXPECT_EQ(2, small.nrow());
EXPECT_EQ(4, small.ncol());
EXPECT_TRUE(VectorEquals(small.row(0), big.row(2)));
}
TEST_F(SelectorTest, SparseSum) {
Vector v(100);
v.randomize();
Selector inc(100);
inc.drop_all();
EXPECT_DOUBLE_EQ(0.0, inc.sparse_sum(v));
inc.add(3);
inc.add(17);
inc.add(12);
EXPECT_DOUBLE_EQ(
inc.sparse_sum(v),
v[3] + v[12] + v[17]);
}
// This test checks the Selector's ability to select from std::vector.
TEST_F(SelectorTest, VectorInt) {
std::vector<int> big = {1, 2, 3, 4, 5};
Selector inc("10010");
std::vector<int> small = inc.select(big);
EXPECT_EQ(2, small.size());
EXPECT_EQ(1, small[0]);
EXPECT_EQ(4, small[1]);
}
TEST_F(SelectorTest, SelectorMatrixTest) {
Selector inc_vec("111101");
SelectorMatrix inc(3, 2, inc_vec);
EXPECT_EQ(3, inc.nrow());
EXPECT_EQ(2, inc.ncol());
// Check that the input vector fills column-by-column.
EXPECT_TRUE(inc(0, 0));
EXPECT_TRUE(inc(1, 0));
EXPECT_TRUE(inc(2, 0));
EXPECT_TRUE(inc(0, 1));
EXPECT_FALSE(inc(1, 1));
EXPECT_TRUE(inc(2, 1));
EXPECT_EQ(inc_vec, inc.vectorize());
inc.drop(0, 1);
EXPECT_FALSE(inc(0, 1));
inc.add(0, 1);
EXPECT_TRUE(inc(0, 1));
inc.flip(0, 1);
EXPECT_FALSE(inc(0, 1));
inc.flip(0, 1);
EXPECT_TRUE(inc(0, 1));
EXPECT_FALSE(inc.all_in());
EXPECT_FALSE(inc.all_out());
inc.drop_all();
for (int i = 0; i < inc.nrow(); ++i) {
for (int j = 0; j < inc.ncol(); ++j) {
EXPECT_FALSE(inc(i, j));
}
}
EXPECT_TRUE(inc.all_out());
inc.add_all();
for (int i = 0; i < inc.nrow(); ++i) {
for (int j = 0; j < inc.ncol(); ++j) {
EXPECT_TRUE(inc(i, j));
}
}
EXPECT_TRUE(inc.all_in());
SelectorMatrix wide(4, 3, Selector("100000010010"));
// 1 0 0
// 0 0 0
// 0 0 1
// 0 1 0
Selector any(wide.row_any());
EXPECT_TRUE(any[0]);
EXPECT_FALSE(any[1]);
EXPECT_TRUE(any[2]);
EXPECT_TRUE(any[3]);
Selector all(wide.row_all());
EXPECT_FALSE(all[0]);
EXPECT_FALSE(all[0]);
EXPECT_FALSE(all[0]);
EXPECT_FALSE(all[3]);
Selector row2 = wide.row(2);
EXPECT_EQ(3, row2.nvars_possible());
EXPECT_FALSE(row2[0]);
EXPECT_FALSE(row2[1]);
EXPECT_TRUE(row2[2]);
Matrix selectable(4, 3);
selectable.randomize();
Vector selected = wide.vector_select(selectable);
EXPECT_EQ(3, selected.size());
EXPECT_DOUBLE_EQ(selected[0], selectable(0, 0));
EXPECT_DOUBLE_EQ(selected[1], selectable(3, 1));
EXPECT_DOUBLE_EQ(selected[2], selectable(2, 2));
Matrix expanded(4, 3, 0.0);
expanded(0, 0) = selectable(0, 0);
expanded(3, 1) = selectable(3, 1);
expanded(2, 2) = selectable(2, 2);
wide.add(3, 0);
wide.add(3, 2);
all = wide.row_all();
EXPECT_FALSE(all[0]);
EXPECT_FALSE(all[0]);
EXPECT_FALSE(all[0]);
EXPECT_TRUE(all[3]);
}
TEST_F(SelectorTest, DiagonalMatrixTest) {
Selector empty(4, false);
Selector full(4, true);
Selector one(4, false);
one.add(2);
Selector three(4, true);
three.drop(2);
Vector v(4);
v.randomize();
DiagonalMatrix dmat(v);
EXPECT_EQ(empty.select_square(dmat).nrow(), 0);
EXPECT_EQ(empty.select_square(dmat).ncol(), 0);
EXPECT_EQ(full.select_square(dmat).nrow(), 4);
EXPECT_EQ(full.select_square(dmat).ncol(), 4);
EXPECT_TRUE(VectorEquals(full.select_square(dmat).diag(), v));
EXPECT_EQ(one.select_square(dmat).nrow(), 1);
EXPECT_EQ(one.select_square(dmat).ncol(), 1);
EXPECT_TRUE(VectorEquals( one.select_square(dmat).diag(), one.select(v)));
EXPECT_EQ(three.select_square(dmat).nrow(), 3);
EXPECT_EQ(three.select_square(dmat).ncol(), 3);
EXPECT_TRUE(VectorEquals(three.select_square(dmat).diag(),
three.select(v)));
}
TEST_F(SelectorTest, FillMissingValues) {
Vector x(5);
x.randomize();
Selector all(5, true);
Selector none(5, false);
EXPECT_TRUE(VectorEquals(x, all.fill_missing_elements(x, 3.0)));
EXPECT_TRUE(VectorEquals(Vector(5, 3.0),
none.fill_missing_elements(x, 3.0)));
x.randomize();
Selector three("11010");
Vector y = x;
three.fill_missing_elements(x, 3.0);
y[2] = 3.0;
y[4] = 3.0;
EXPECT_TRUE(VectorEquals(x, y));
Vector values = {1.2, 2.4};
three.fill_missing_elements(x, values);
y[2] = 1.2;
y[4] = 2.4;
EXPECT_TRUE(VectorEquals(x, y));
}
} // namespace
<commit_msg>Add a test for Selector::complement.<commit_after>#include "gtest/gtest.h"
#include "LinAlg/Vector.hpp"
#include "LinAlg/VectorView.hpp"
#include "LinAlg/DiagonalMatrix.hpp"
#include "LinAlg/Matrix.hpp"
#include "LinAlg/Selector.hpp"
#include "distributions.hpp"
#include "cpputil/math_utils.hpp"
#include "test_utils/test_utils.hpp"
#include <fstream>
namespace {
using namespace BOOM;
using std::endl;
using std::cout;
class SelectorTest : public ::testing::Test {
protected:
SelectorTest() {
GlobalRng::rng.seed(8675309);
}
};
TEST_F(SelectorTest, Equality) {
Selector s1("001");
Selector s2("101");
EXPECT_NE(s1, s2);
EXPECT_TRUE(s1 != s2);
EXPECT_FALSE(s1 == s2);
s2.flip(0); // now 001
EXPECT_EQ(s1, s2);
EXPECT_TRUE(s1 == s2);
EXPECT_FALSE(s1 != s2);
s2.flip(0);
swap(s1, s2);
Selector s3("001");
EXPECT_EQ(s2, s3);
EXPECT_NE(s1, s3);
s3.flip(0);
EXPECT_EQ(s1, s3);
EXPECT_NE(s2, s3);
}
TEST_F(SelectorTest, Complement) {
Selector s1("101001101");
Selector s2 = s1.complement();
EXPECT_EQ(s2.nvars_possible(), s1.nvars_possible());
for (int i = 0; i < s1.nvars_possible(); ++i) {
EXPECT_EQ(s1[i], !s2[i]);
}
}
TEST_F(SelectorTest, Indexing) {
Selector s1("101001101");
EXPECT_EQ(s1.nvars(), 5);
EXPECT_EQ(s1.nvars_possible(), 9);
EXPECT_EQ(s1.nvars_excluded(), 4);
EXPECT_EQ(0, s1.indx(0));
EXPECT_EQ(2, s1.indx(1));
EXPECT_EQ(5, s1.indx(2));
EXPECT_EQ(6, s1.indx(3));
EXPECT_EQ(8, s1.indx(4));
EXPECT_EQ(0, s1.INDX(0));
EXPECT_EQ(1, s1.INDX(2));
EXPECT_EQ(2, s1.INDX(5));
EXPECT_EQ(3, s1.INDX(6));
EXPECT_EQ(4, s1.INDX(8));
}
TEST_F(SelectorTest, Append) {
Selector s1("010");
EXPECT_EQ(s1.nvars(), 1);
EXPECT_EQ(s1.nvars_possible(), 3);
s1.push_back(true);
EXPECT_EQ(s1.nvars(), 2);
EXPECT_EQ(s1.nvars_possible(), 4);
s1.push_back(false);
EXPECT_EQ(s1.nvars(), 2);
EXPECT_EQ(s1.nvars_possible(), 5);
// Current state is "01010".
// Set it to "0100"
s1.erase(3);
EXPECT_EQ(s1.nvars(), 1);
EXPECT_EQ(s1.nvars_possible(), 4);
EXPECT_TRUE(s1[1]);
}
TEST_F(SelectorTest, ToVectorTest) {
Selector s("00010");
Vector v = s.to_Vector();
EXPECT_EQ(v.size(), 5);
EXPECT_DOUBLE_EQ(v[0], 0);
EXPECT_DOUBLE_EQ(v[1], 0);
EXPECT_DOUBLE_EQ(v[2], 0);
EXPECT_DOUBLE_EQ(v[3], 1);
EXPECT_DOUBLE_EQ(v[4], 0);
}
TEST_F(SelectorTest, SelectRowsTest) {
Matrix big(10, 4);
big.randomize();
Selector inc(10, false);
inc.add(2);
inc.add(7);
Matrix small = inc.select_rows(big);
EXPECT_EQ(2, small.nrow());
EXPECT_EQ(4, small.ncol());
EXPECT_TRUE(VectorEquals(small.row(0), big.row(2)));
big.randomize();
ConstSubMatrix big_view(big);
small = inc.select_rows(big_view);
EXPECT_EQ(2, small.nrow());
EXPECT_EQ(4, small.ncol());
EXPECT_TRUE(VectorEquals(small.row(0), big.row(2)));
big.randomize();
SubMatrix mutable_big_view(big);
small = inc.select_rows(big_view);
EXPECT_EQ(2, small.nrow());
EXPECT_EQ(4, small.ncol());
EXPECT_TRUE(VectorEquals(small.row(0), big.row(2)));
}
TEST_F(SelectorTest, SparseSum) {
Vector v(100);
v.randomize();
Selector inc(100);
inc.drop_all();
EXPECT_DOUBLE_EQ(0.0, inc.sparse_sum(v));
inc.add(3);
inc.add(17);
inc.add(12);
EXPECT_DOUBLE_EQ(
inc.sparse_sum(v),
v[3] + v[12] + v[17]);
}
// This test checks the Selector's ability to select from std::vector.
TEST_F(SelectorTest, VectorInt) {
std::vector<int> big = {1, 2, 3, 4, 5};
Selector inc("10010");
std::vector<int> small = inc.select(big);
EXPECT_EQ(2, small.size());
EXPECT_EQ(1, small[0]);
EXPECT_EQ(4, small[1]);
}
TEST_F(SelectorTest, SelectorMatrixTest) {
Selector inc_vec("111101");
SelectorMatrix inc(3, 2, inc_vec);
EXPECT_EQ(3, inc.nrow());
EXPECT_EQ(2, inc.ncol());
// Check that the input vector fills column-by-column.
EXPECT_TRUE(inc(0, 0));
EXPECT_TRUE(inc(1, 0));
EXPECT_TRUE(inc(2, 0));
EXPECT_TRUE(inc(0, 1));
EXPECT_FALSE(inc(1, 1));
EXPECT_TRUE(inc(2, 1));
EXPECT_EQ(inc_vec, inc.vectorize());
inc.drop(0, 1);
EXPECT_FALSE(inc(0, 1));
inc.add(0, 1);
EXPECT_TRUE(inc(0, 1));
inc.flip(0, 1);
EXPECT_FALSE(inc(0, 1));
inc.flip(0, 1);
EXPECT_TRUE(inc(0, 1));
EXPECT_FALSE(inc.all_in());
EXPECT_FALSE(inc.all_out());
inc.drop_all();
for (int i = 0; i < inc.nrow(); ++i) {
for (int j = 0; j < inc.ncol(); ++j) {
EXPECT_FALSE(inc(i, j));
}
}
EXPECT_TRUE(inc.all_out());
inc.add_all();
for (int i = 0; i < inc.nrow(); ++i) {
for (int j = 0; j < inc.ncol(); ++j) {
EXPECT_TRUE(inc(i, j));
}
}
EXPECT_TRUE(inc.all_in());
SelectorMatrix wide(4, 3, Selector("100000010010"));
// 1 0 0
// 0 0 0
// 0 0 1
// 0 1 0
Selector any(wide.row_any());
EXPECT_TRUE(any[0]);
EXPECT_FALSE(any[1]);
EXPECT_TRUE(any[2]);
EXPECT_TRUE(any[3]);
Selector all(wide.row_all());
EXPECT_FALSE(all[0]);
EXPECT_FALSE(all[0]);
EXPECT_FALSE(all[0]);
EXPECT_FALSE(all[3]);
Selector row2 = wide.row(2);
EXPECT_EQ(3, row2.nvars_possible());
EXPECT_FALSE(row2[0]);
EXPECT_FALSE(row2[1]);
EXPECT_TRUE(row2[2]);
Matrix selectable(4, 3);
selectable.randomize();
Vector selected = wide.vector_select(selectable);
EXPECT_EQ(3, selected.size());
EXPECT_DOUBLE_EQ(selected[0], selectable(0, 0));
EXPECT_DOUBLE_EQ(selected[1], selectable(3, 1));
EXPECT_DOUBLE_EQ(selected[2], selectable(2, 2));
Matrix expanded(4, 3, 0.0);
expanded(0, 0) = selectable(0, 0);
expanded(3, 1) = selectable(3, 1);
expanded(2, 2) = selectable(2, 2);
wide.add(3, 0);
wide.add(3, 2);
all = wide.row_all();
EXPECT_FALSE(all[0]);
EXPECT_FALSE(all[0]);
EXPECT_FALSE(all[0]);
EXPECT_TRUE(all[3]);
}
TEST_F(SelectorTest, DiagonalMatrixTest) {
Selector empty(4, false);
Selector full(4, true);
Selector one(4, false);
one.add(2);
Selector three(4, true);
three.drop(2);
Vector v(4);
v.randomize();
DiagonalMatrix dmat(v);
EXPECT_EQ(empty.select_square(dmat).nrow(), 0);
EXPECT_EQ(empty.select_square(dmat).ncol(), 0);
EXPECT_EQ(full.select_square(dmat).nrow(), 4);
EXPECT_EQ(full.select_square(dmat).ncol(), 4);
EXPECT_TRUE(VectorEquals(full.select_square(dmat).diag(), v));
EXPECT_EQ(one.select_square(dmat).nrow(), 1);
EXPECT_EQ(one.select_square(dmat).ncol(), 1);
EXPECT_TRUE(VectorEquals( one.select_square(dmat).diag(), one.select(v)));
EXPECT_EQ(three.select_square(dmat).nrow(), 3);
EXPECT_EQ(three.select_square(dmat).ncol(), 3);
EXPECT_TRUE(VectorEquals(three.select_square(dmat).diag(),
three.select(v)));
}
TEST_F(SelectorTest, FillMissingValues) {
Vector x(5);
x.randomize();
Selector all(5, true);
Selector none(5, false);
EXPECT_TRUE(VectorEquals(x, all.fill_missing_elements(x, 3.0)));
EXPECT_TRUE(VectorEquals(Vector(5, 3.0),
none.fill_missing_elements(x, 3.0)));
x.randomize();
Selector three("11010");
Vector y = x;
three.fill_missing_elements(x, 3.0);
y[2] = 3.0;
y[4] = 3.0;
EXPECT_TRUE(VectorEquals(x, y));
Vector values = {1.2, 2.4};
three.fill_missing_elements(x, values);
y[2] = 1.2;
y[4] = 2.4;
EXPECT_TRUE(VectorEquals(x, y));
}
} // namespace
<|endoftext|>
|
<commit_before>//=====================================================================//
/*! @file
@brief LCD ドットマトリックスの簡単なサンプル @n
ST7565(R)、128 x 64 ピクセルの液晶を接続 @n
/CS ---> P53 (36) @n
A0 ---> P50 (33) @n
SD ---> P13/SO20 (43) @n
SCL ---> P15/SCK20 (41) @n
/RES ---> /RESET ( 6)
@author 平松邦仁 (hira@rvf-rc45.net)
*/
//=====================================================================//
#include <cstdint>
#include "G13/system.hpp"
#include "common/port_utils.hpp"
#include "common/fifo.hpp"
#include "common/uart_io.hpp"
#include "common/itimer.hpp"
#include "common/format.hpp"
#include "common/delay.hpp"
#include "common/monograph.hpp"
// ターゲットLCDのタイプを選択
// #define LCD_ST7565
#define LCD_SSD1306
#ifdef LCD_ST7565
#include "chip/ST7565.hpp"
#endif
#ifdef LCD_SSD1306
#include "chip/SSD1306.hpp"
#endif
namespace {
// 送信、受信バッファの定義
typedef utils::fifo<uint8_t, 32> buffer;
// UART の定義(SAU02、SAU03)
device::uart_io<device::SAU02, device::SAU03, buffer, buffer> uart_;
device::itimer<uint8_t> itm_;
// CSI(SPI) の定義、CSI20 の通信では、「SAU10」を利用、1ユニット、チャネル0
typedef device::csi_io<device::SAU10> csi;
csi csi_;
// LCD インターフェースの定義
typedef device::PORT<device::port_no::P5, device::bitpos::B5> lcd_sel; ///< LCD 選択信号
typedef device::PORT<device::port_no::P5, device::bitpos::B0> lcd_reg; ///< LCD レジスタ選択
#ifdef LCD_ST7565
chip::ST7565<csi, lcd_sel, lcd_reg> lcd_(csi_);
#endif
#ifdef LCD_SSD1306
chip::SSD1306<csi, lcd_sel, lcd_reg> lcd_(csi_);
#endif
graphics::monograph bitmap_;
uint8_t v_ = 91;
uint8_t m_ = 123;
uint8_t rand_()
{
v_ += v_ << 2;
++v_;
uint8_t n = 0;
if(m_ & 0x02) n = 1;
if(m_ & 0x40) n ^= 1;
m_ += m_;
if(n == 0) ++m_;
return v_ ^ m_;
}
}
const void* ivec_[] __attribute__ ((section (".ivec"))) = {
/* 0 */ nullptr,
/* 1 */ nullptr,
/* 2 */ nullptr,
/* 3 */ nullptr,
/* 4 */ nullptr,
/* 5 */ nullptr,
/* 6 */ nullptr,
/* 7 */ nullptr,
/* 8 */ nullptr,
/* 9 */ nullptr,
/* 10 */ nullptr,
/* 11 */ nullptr,
/* 12 */ nullptr,
/* 13 */ nullptr,
/* 14 */ nullptr,
/* 15 */ nullptr,
/* 16 */ reinterpret_cast<void*>(uart_.send_task),
/* 17 */ reinterpret_cast<void*>(uart_.recv_task),
/* 18 */ reinterpret_cast<void*>(uart_.error_task),
/* 19 */ nullptr,
/* 20 */ nullptr,
/* 21 */ nullptr,
/* 22 */ nullptr,
/* 23 */ nullptr,
/* 24 */ nullptr,
/* 25 */ nullptr,
/* 26 */ reinterpret_cast<void*>(itm_.task),
};
extern "C" {
void sci_putch(char ch)
{
uart_.putch(ch);
}
void sci_puts(const char* str)
{
uart_.puts(str);
}
};
int main(int argc, char* argv[])
{
using namespace device;
utils::port::pullup_all(); ///< 安全の為、全ての入力をプルアップ
// インターバル・タイマー開始
{
uint8_t intr_level = 1;
itm_.start(60, intr_level);
}
// UART 開始
{
uint8_t intr_level = 1;
uart_.start(115200, intr_level);
}
// CSI 開始
{
uint8_t intr_level = 0;
if(!csi_.start(8000000, csi::PHASE::TYPE4, intr_level)) {
uart_.puts("CSI Start fail...\n");
}
}
uart_.puts("Start RL78/G13 ST7565(R) sample\n");
PM4.B3 = 0; // output
{
lcd_.start(0x04);
bitmap_.start();
bitmap_.clear(0);
}
uint16_t x = rand_() & 127;
uint16_t y = rand_() & 63;
uint16_t xx;
uint16_t yy;
uint8_t loop = 0;
uint8_t nn = 0;
uint8_t n = 0;
while(1) {
itm_.sync();
if(nn >= 4) {
lcd_.copy(bitmap_.fb());
nn = 0;
}
++nn;
if(loop >= 20) {
loop = 0;
bitmap_.clear(0);
bitmap_.frame(0, 0, 128, 64, 1);
}
xx = rand_() & 127;
yy = rand_() & 63;
bitmap_.line(x, y, xx, yy, 1);
x = xx;
y = yy;
++loop;
++n;
if(n >= 30) n = 0;
P4.B3 = n < 10 ? false : true;
}
}
<commit_msg>update LCD define<commit_after>//=====================================================================//
/*! @file
@brief LCD ドットマトリックスの簡単なサンプル @n
ST7565(R)、128 x 64 ピクセルの液晶を接続 @n
/CS ---> P53 (36) @n
A0 ---> P50 (33) @n
SD ---> P13/SO20 (43) @n
SCL ---> P15/SCK20 (41) @n
/RES ---> /RESET ( 6)
@author 平松邦仁 (hira@rvf-rc45.net)
*/
//=====================================================================//
#include <cstdint>
#include "G13/system.hpp"
#include "common/port_utils.hpp"
#include "common/fifo.hpp"
#include "common/uart_io.hpp"
#include "common/itimer.hpp"
#include "common/format.hpp"
#include "common/delay.hpp"
#include "common/monograph.hpp"
// ターゲットLCDのタイプを選択
#define LCD_ST7565
// #define LCD_SSD1306
#ifdef LCD_ST7565
#include "chip/ST7565.hpp"
#endif
#ifdef LCD_SSD1306
#include "chip/SSD1306.hpp"
#endif
namespace {
// 送信、受信バッファの定義
typedef utils::fifo<uint8_t, 32> buffer;
// UART の定義(SAU02、SAU03)
device::uart_io<device::SAU02, device::SAU03, buffer, buffer> uart_;
device::itimer<uint8_t> itm_;
// CSI(SPI) の定義、CSI20 の通信では、「SAU10」を利用、1ユニット、チャネル0
typedef device::csi_io<device::SAU10> csi;
csi csi_;
// LCD インターフェースの定義
typedef device::PORT<device::port_no::P5, device::bitpos::B5> lcd_sel; ///< LCD 選択信号
typedef device::PORT<device::port_no::P5, device::bitpos::B0> lcd_reg; ///< LCD レジスタ選択
#ifdef LCD_ST7565
chip::ST7565<csi, lcd_sel, lcd_reg> lcd_(csi_);
#endif
#ifdef LCD_SSD1306
chip::SSD1306<csi, lcd_sel, lcd_reg> lcd_(csi_);
#endif
graphics::monograph bitmap_;
uint8_t v_ = 91;
uint8_t m_ = 123;
uint8_t rand_()
{
v_ += v_ << 2;
++v_;
uint8_t n = 0;
if(m_ & 0x02) n = 1;
if(m_ & 0x40) n ^= 1;
m_ += m_;
if(n == 0) ++m_;
return v_ ^ m_;
}
}
const void* ivec_[] __attribute__ ((section (".ivec"))) = {
/* 0 */ nullptr,
/* 1 */ nullptr,
/* 2 */ nullptr,
/* 3 */ nullptr,
/* 4 */ nullptr,
/* 5 */ nullptr,
/* 6 */ nullptr,
/* 7 */ nullptr,
/* 8 */ nullptr,
/* 9 */ nullptr,
/* 10 */ nullptr,
/* 11 */ nullptr,
/* 12 */ nullptr,
/* 13 */ nullptr,
/* 14 */ nullptr,
/* 15 */ nullptr,
/* 16 */ reinterpret_cast<void*>(uart_.send_task),
/* 17 */ reinterpret_cast<void*>(uart_.recv_task),
/* 18 */ reinterpret_cast<void*>(uart_.error_task),
/* 19 */ nullptr,
/* 20 */ nullptr,
/* 21 */ nullptr,
/* 22 */ nullptr,
/* 23 */ nullptr,
/* 24 */ nullptr,
/* 25 */ nullptr,
/* 26 */ reinterpret_cast<void*>(itm_.task),
};
extern "C" {
void sci_putch(char ch)
{
uart_.putch(ch);
}
void sci_puts(const char* str)
{
uart_.puts(str);
}
};
int main(int argc, char* argv[])
{
using namespace device;
utils::port::pullup_all(); ///< 安全の為、全ての入力をプルアップ
// インターバル・タイマー開始
{
uint8_t intr_level = 1;
itm_.start(60, intr_level);
}
// UART 開始
{
uint8_t intr_level = 1;
uart_.start(115200, intr_level);
}
// CSI 開始
{
uint8_t intr_level = 0;
if(!csi_.start(8000000, csi::PHASE::TYPE4, intr_level)) {
uart_.puts("CSI Start fail...\n");
}
}
uart_.puts("Start RL78/G13 ST7565(R) sample\n");
PM4.B3 = 0; // output
{
lcd_.start(0x04);
bitmap_.start();
bitmap_.clear(0);
}
uint16_t x = rand_() & 127;
uint16_t y = rand_() & 63;
uint16_t xx;
uint16_t yy;
uint8_t loop = 0;
uint8_t nn = 0;
uint8_t n = 0;
while(1) {
itm_.sync();
if(nn >= 4) {
lcd_.copy(bitmap_.fb());
nn = 0;
}
++nn;
if(loop >= 20) {
loop = 0;
bitmap_.clear(0);
bitmap_.frame(0, 0, 128, 64, 1);
}
xx = rand_() & 127;
yy = rand_() & 63;
bitmap_.line(x, y, xx, yy, 1);
x = xx;
y = yy;
++loop;
++n;
if(n >= 30) n = 0;
P4.B3 = n < 10 ? false : true;
}
}
<|endoftext|>
|
<commit_before>/*
* Copyright 2014 Kevin Brightwell <kevin.brightwell2@gmail.com>
*
* 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 "router/QWebRouter.h"
#include "router/QWebRoute.h"
#include "router/QWebRequest.h"
#include "router/QWebResponse.h"
#include <QDebug>
#include <QSharedPointer>
#include <QHttpServer/qhttpresponse.h>
#include <QHttpServer/qhttprequest.h>
const QString QWebRouter::DEFAULT_404_MSG =
"<html> "
"<head>"
" <title>404 Unknown Page</title>"
"</head>"
"<body>"
" <h1>404 Page Not Found</h1>"
" <p><b>Requested:</b> <pre>${page}</pre></p>"
"</body>"
"</html>\n\n";
const QRegExp QWebRouter::DEFAULT_404_PATH_REPL("\\$\\{page\\}");
const QWebRouter::RouteFunction QWebRouter::DEFAULT_404 = [](QSharedPointer<QWebRequest> req,
QSharedPointer<QWebResponse> resp) {
QString msg = QWebRouter::DEFAULT_404_MSG;
resp->setStatusCode(QWebResponse::StatusCode::STATUS_NOT_FOUND);
resp->writeText(msg.replace(QWebRouter::DEFAULT_404_PATH_REPL,
req->path()), "text/html");
};
QWebRouter::QWebRouter(const QHash<QWebService::HttpMethod, RoutePairList> routes,
const RouteFunction fourohfour,
QObject* parent)
: QObject(parent),
m_routes(routes),
m_404(fourohfour) {
}
QWebRouter::~QWebRouter()
{
}
inline
void parsePOSTVars(QString query, QHash<QString, QString> &out) {
const QStringList pairs = query.split('&', QString::SkipEmptyParts);
for (QString pair : pairs) {
const QStringList keyVals = pair.split('=', QString::KeepEmptyParts);
out[keyVals[0]] = keyVals[1];
}
}
void QWebRouter::handleRoute(QHttpRequest* request, QHttpResponse* resp)
{
qDebug() << request->methodString() << ":" << request->url();
const QString route = request->path();
request->storeBody();
QHash<QString, QString> postParams;
if (request->url().hasQuery()) {
parsePOSTVars(request->url().query(), postParams);
}
if (request->method() == QWebService::HttpMethod::HTTP_POST) {
QString bodyVals = QString(request->body());
parsePOSTVars(bodyVals, postParams);
}
// we recieved a request:
QWebRoute::ParsedRoute::Ptr routeResponse;
QWebRouter::RouteFunction func;
QWebService::HttpMethod method = request->method();
RoutePairList routes = m_routes[method];
// search for the first matching path
for (RoutePair pair : routes) {
QSharedPointer<QWebRoute::ParsedRoute> resp = pair.first->checkPath(route);
if (resp) {
func = pair.second;
routeResponse = resp;
break;
}
}
QSharedPointer<QWebRequest> reqPtr;
if (routeResponse) {
reqPtr = QWebRequest::create(request, postParams,
routeResponse->urlParams(),
routeResponse->splat());
} else {
reqPtr = QWebRequest::create(request, postParams, QHash<QString, QString>(), QStringList());
}
QSharedPointer<QWebResponse> webRespPtr = QWebResponse::create();
connect(webRespPtr.data(), &QWebResponse::responseDataPrepared,
m_service->getMiddleWareRegistrar(), &QWebMiddleWareRegistrar::webResponseDataPrepared);
connect(request, &QHttpRequest::end, [this, func, reqPtr, resp, webRespPtr]() {
if (func) {
// we found a proper route:
func(reqPtr, webRespPtr);
} else {
// 404:
m_404(reqPtr, webRespPtr);
}
webRespPtr->writeToResponse(reqPtr, resp);
});
}
<commit_msg>Fixed one segfault (line 108). Test case now triggers the other. See #10.<commit_after>/*
* Copyright 2014 Kevin Brightwell <kevin.brightwell2@gmail.com>
*
* 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 "router/QWebRouter.h"
#include "router/QWebRoute.h"
#include "router/QWebRequest.h"
#include "router/QWebResponse.h"
#include <QDebug>
#include <QSharedPointer>
#include <QHttpServer/qhttpresponse.h>
#include <QHttpServer/qhttprequest.h>
const QString QWebRouter::DEFAULT_404_MSG =
"<html> "
"<head>"
" <title>404 Unknown Page</title>"
"</head>"
"<body>"
" <h1>404 Page Not Found</h1>"
" <p><b>Requested:</b> <pre>${page}</pre></p>"
"</body>"
"</html>\n\n";
const QRegExp QWebRouter::DEFAULT_404_PATH_REPL("\\$\\{page\\}");
const QWebRouter::RouteFunction QWebRouter::DEFAULT_404 = [](QSharedPointer<QWebRequest> req,
QSharedPointer<QWebResponse> resp) {
QString msg = QWebRouter::DEFAULT_404_MSG;
resp->setStatusCode(QWebResponse::StatusCode::STATUS_NOT_FOUND);
resp->writeText(msg.replace(QWebRouter::DEFAULT_404_PATH_REPL,
req->path()), "text/html");
};
QWebRouter::QWebRouter(const QHash<QWebService::HttpMethod, RoutePairList> routes,
const RouteFunction fourohfour,
QObject* parent)
: QObject(parent),
m_routes(routes),
m_404(fourohfour) {
}
QWebRouter::~QWebRouter()
{
}
inline
void parsePOSTVars(QString query, QHash<QString, QString> &out) {
const QStringList pairs = query.split('&', QString::SkipEmptyParts);
for (QString pair : pairs) {
const QStringList keyVals = pair.split('=', QString::KeepEmptyParts);
out[keyVals[0]] = keyVals[1];
}
}
void QWebRouter::handleRoute(QHttpRequest* request, QHttpResponse* resp)
{
qDebug() << request->methodString() << ":" << request->url();
const QString route = request->path();
request->storeBody();
QHash<QString, QString> postParams;
if (request->url().hasQuery()) {
parsePOSTVars(request->url().query(), postParams);
}
if (request->method() == QWebService::HttpMethod::HTTP_POST) {
QString bodyVals = QString(request->body());
parsePOSTVars(bodyVals, postParams);
}
// we recieved a request:
QWebRoute::ParsedRoute::Ptr routeResponse;
QWebRouter::RouteFunction func;
QWebService::HttpMethod method = request->method();
RoutePairList routes = m_routes[method];
// search for the first matching path
for (RoutePair pair : routes) {
if(pair.first) {
QSharedPointer<QWebRoute::ParsedRoute> resp = pair.first->checkPath(route);
if (resp) {
func = pair.second;
routeResponse = resp;
break;
}
}
}
QSharedPointer<QWebRequest> reqPtr;
if (routeResponse) {
reqPtr = QWebRequest::create(request, postParams,
routeResponse->urlParams(),
routeResponse->splat());
} else {
reqPtr = QWebRequest::create(request, postParams, QHash<QString, QString>(), QStringList());
}
QSharedPointer<QWebResponse> webRespPtr = QWebResponse::create();
connect(webRespPtr.data(), &QWebResponse::responseDataPrepared,
m_service->getMiddleWareRegistrar(), &QWebMiddleWareRegistrar::webResponseDataPrepared);
connect(request, &QHttpRequest::end, [this, func, reqPtr, resp, webRespPtr]() {
if (func) {
// we found a proper route:
func(reqPtr, webRespPtr);
} else {
// 404:
m_404(reqPtr, webRespPtr);
}
webRespPtr->writeToResponse(reqPtr, resp);
});
}
<|endoftext|>
|
<commit_before>#ifndef LIA_TRANSFORMS_LIST_COMP_HPP
#define LIA_TRANSFORMS_LIST_COMP_HPP
// Includes
#include "../detail/iterator.hpp"
#include "../detail/type_traits.hpp"
#include <algorithm>
namespace lia {
template<class Cont, typename Map>
inline auto map(const Cont& cont, Map&& mapped) -> Rebind<Cont, ResultOf<Unqualified<Map>>> {
Rebind<Cont, ResultOf<Unqualified<Map>>> result;
std::transform(std::begin(cont),std::end(cont), std::back_inserter(result),mapped);
return result;
}
template<class Cont>
inline Unqualified<Cont> reverse(Cont&& cont) {
Unqualified<Cont> result;
std::reverse_copy(std::begin(cont),std::end(cont),std::back_inserter(result));
return result;
}
template<class Cont>
inline Unqualified<Cont> intersperse(const Cont& cont, ValueType<Unqualified<Cont>> elem) {
Unqualified<Cont> result;
auto first = std::begin(cont);
auto last = std::end(cont);
if(first != last)
result.push_back(*first++);
while(first != last) {
result.push_back(elem);
result.push_back(*first++);
}
return result;
}
template<class Cont>
inline auto subsequences(const Cont& cont) -> Rebind<Cont, Unqualified<Cont>> {
Rebind<Cont, Unqualified<Cont>> result;
auto first = std::begin(cont);
Unqualified<Cont> temp;
auto max = 1ULL << cont.size();
for(unsigned i = 0; i < max; ++i) {
for(unsigned j = 0, h = i; h; h >>= 1, ++j) {
if(h & 1)
temp.push_back(*(first + j));
}
result.push_back(temp);
temp.clear();
}
return result;
}
template<class Cont>
inline auto permutations(Cont&& cont) -> Rebind<Unqualified<Cont>, Unqualified<Cont>> {
Rebind<Unqualified<Cont>, Unqualified<Cont>> result;
Unqualified<Cont> temp(std::forward<Cont>(cont));
do {
result.push_back(temp);
}
while(std::next_permutation(std::begin(temp), std::end(temp)));
return result;
}
} // lia
#endif // LIA_TRANSFORMS_LIST_COMP_HPP<commit_msg>Universal reference to pass-by-value<commit_after>#ifndef LIA_TRANSFORMS_LIST_COMP_HPP
#define LIA_TRANSFORMS_LIST_COMP_HPP
// Includes
#include "../detail/iterator.hpp"
#include "../detail/type_traits.hpp"
#include <algorithm>
namespace lia {
template<class Cont, typename Map>
inline auto map(const Cont& cont, Map&& mapped) -> Rebind<Cont, ResultOf<Unqualified<Map>>> {
Rebind<Cont, ResultOf<Unqualified<Map>>> result;
std::transform(std::begin(cont),std::end(cont), std::back_inserter(result),mapped);
return result;
}
template<class Cont>
inline Unqualified<Cont> reverse(Cont&& cont) {
Unqualified<Cont> result;
std::reverse_copy(std::begin(cont), std::end(cont), std::back_inserter(result));
return result;
}
template<class Cont>
inline Unqualified<Cont> intersperse(const Cont& cont, ValueType<Unqualified<Cont>> elem) {
Unqualified<Cont> result;
auto first = std::begin(cont);
auto last = std::end(cont);
if(first != last)
result.push_back(*first++);
while(first != last) {
result.push_back(elem);
result.push_back(*first++);
}
return result;
}
template<class Cont>
inline auto subsequences(const Cont& cont) -> Rebind<Cont, Unqualified<Cont>> {
Rebind<Cont, Unqualified<Cont>> result;
auto first = std::begin(cont);
Unqualified<Cont> temp;
auto max = 1ULL << cont.size();
for(unsigned i = 0; i < max; ++i) {
for(unsigned j = 0, h = i; h; h >>= 1, ++j) {
if(h & 1)
temp.push_back(*(first + j));
}
result.push_back(temp);
temp.clear();
}
return result;
}
template<class Cont>
inline auto permutations(Cont cont) -> Rebind<Unqualified<Cont>, Unqualified<Cont>> {
Rebind<Unqualified<Cont>, Unqualified<Cont>> result;
do {
result.push_back(cont);
}
while(std::next_permutation(std::begin(cont), std::end(cont)));
return result;
}
} // lia
#endif // LIA_TRANSFORMS_LIST_COMP_HPP<|endoftext|>
|
<commit_before>/*//////////////////////////////////////////////////////////////////
//// SKIRT -- an advanced radiative transfer code ////
//// © Astronomical Observatory, Ghent University ////
///////////////////////////////////////////////////////////////// */
#ifdef BUILDING_WITH_MPI
#include <mpi.h>
#endif
#include "ProcessManager.hpp"
#include <QDataStream>
////////////////////////////////////////////////////////////////////
namespace
{
void createDisplacedDoubleBlocks(int blocklength, const std::vector<int>& displacements, MPI_Datatype* newtypeP,
int extent = -1)
{
int count = displacements.size();
// Multiply the displacements by the block length
std::vector<int> multiplied_disp;
multiplied_disp.reserve(count);
for(auto i: displacements) multiplied_disp.push_back(blocklength*i);
// Create a datatype representing a structure of displaced blocks of the same size;
MPI_Datatype indexedBlock;
MPI_Type_create_indexed_block(count, blocklength, &multiplied_disp[0], MPI_DOUBLE, &indexedBlock);
// Pad this datatype to modify the extent to the requested value
MPI_Aint lb;
MPI_Aint ex;
MPI_Type_get_extent(indexedBlock, &lb, &ex);
if (extent != -1)
{
MPI_Type_create_resized(indexedBlock, lb, extent*sizeof(double), newtypeP);
// Commit the final type and free the intermediary one
MPI_Type_commit(newtypeP);
MPI_Type_free(&indexedBlock);
}
else
{
// No padding, just store the indexed block
*newtypeP = indexedBlock;
MPI_Type_commit(newtypeP);
}
}
}
std::atomic<int> ProcessManager::requests(0);
//////////////////////////////////////////////////////////////////////
void ProcessManager::initialize(int *argc, char ***argv)
{
#ifdef BUILDING_WITH_MPI
int initialized;
MPI_Initialized(&initialized);
if (!initialized)
{
MPI_Init(argc, argv);
}
#else
Q_UNUSED(argc) Q_UNUSED(argv)
#endif
}
//////////////////////////////////////////////////////////////////////
void ProcessManager::finalize()
{
#ifdef BUILDING_WITH_MPI
MPI_Finalize();
#endif
}
//////////////////////////////////////////////////////////////////////
void ProcessManager::acquireMPI(int& rank, int& Nprocs)
{
#ifdef BUILDING_WITH_MPI
int oldrequests = requests++;
if (oldrequests) // if requests >=1
{
Nprocs = 1;
rank = 0;
}
else // requests == 0
{
MPI_Comm_size(MPI_COMM_WORLD, &Nprocs);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
}
#else
rank = 0;
Nprocs = 1;
#endif
}
//////////////////////////////////////////////////////////////////////
void ProcessManager::releaseMPI()
{
#ifdef BUILDING_WITH_MPI
requests--;
#endif
}
//////////////////////////////////////////////////////////////////////
void ProcessManager::barrier()
{
#ifdef BUILDING_WITH_MPI
MPI_Barrier(MPI_COMM_WORLD);
#endif
}
//////////////////////////////////////////////////////////////////////
void ProcessManager::sendByteBuffer(QByteArray& buffer, int receiver, int tag)
{
#ifdef BUILDING_WITH_MPI
MPI_Send(buffer.data(), buffer.size(), MPI_BYTE, receiver, tag, MPI_COMM_WORLD);
#else
Q_UNUSED(buffer) Q_UNUSED(receiver) Q_UNUSED(tag)
#endif
}
//////////////////////////////////////////////////////////////////////
void ProcessManager::receiveByteBuffer(QByteArray& buffer, int& sender)
{
#ifdef BUILDING_WITH_MPI
MPI_Status status;
MPI_Recv(buffer.data(), buffer.size(), MPI_BYTE, MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &status);
sender = status.MPI_SOURCE;
#else
Q_UNUSED(buffer) Q_UNUSED(sender)
#endif
}
//////////////////////////////////////////////////////////////////////
void ProcessManager::receiveByteBuffer(QByteArray &buffer, int sender, int& tag)
{
#ifdef BUILDING_WITH_MPI
MPI_Status status;
MPI_Recv(buffer.data(), buffer.size(), MPI_BYTE, sender, MPI_ANY_TAG, MPI_COMM_WORLD, &status);
tag = status.MPI_TAG;
#else
Q_UNUSED(buffer) Q_UNUSED(sender) Q_UNUSED(tag)
#endif
}
//////////////////////////////////////////////////////////////////////
void ProcessManager::gatherw(double* sendBuffer, int sendCount,
double* recvBuffer, int recvRank, int recvLength,
const std::vector<std::vector<int>>& recvDisplacements)
{
#ifdef BUILDING_WITH_MPI
int size;
int rank;
MPI_Comm_size(MPI_COMM_WORLD, &size);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
// parameters for the senders
std::vector<int> sendcnts(size, 0); // every process sends nothing to all processes
sendcnts[recvRank] = sendCount; // except to the receiver
std::vector<int> sdispls(size, 0); // starting from sendBuffer + 0
std::vector<MPI_Datatype> sendtypes(size, MPI_DOUBLE); // all doubles
// parameters on the receiving end
std::vector<int> recvcnts;
if (rank != recvRank) recvcnts.resize(size, 0); // I am not receiver: receive nothing from every process
else recvcnts.resize(size, 1); // I am receiver: receive 1 from every process
std::vector<int> rdispls(size, 0); // displacements will be contained in the datatypes
std::vector<MPI_Datatype> recvtypes; // we will construct derived datatypes for receiving from each process
recvtypes.reserve(size);
for (int r=0; r<size; r++)
{
MPI_Datatype newtype;
createDisplacedDoubleBlocks(recvLength, recvDisplacements[r], &newtype);
recvtypes.push_back(newtype);
}
MPI_Alltoallw(sendBuffer, &sendcnts[0], &sdispls[0], &sendtypes[0],
recvBuffer, &recvcnts[0], &rdispls[0], &recvtypes[0],
MPI_COMM_WORLD);
for (int rank=0; rank<size; rank++) MPI_Type_free(&recvtypes[rank]);
#else
Q_UNUSED(sendBuffer) Q_UNUSED(sendCount) Q_UNUSED(recvBuffer) Q_UNUSED(recvRank) Q_UNUSED(recvDisplacements)
#endif
}
//////////////////////////////////////////////////////////////////////
void ProcessManager::displacedBlocksAllToAll(double* sendBuffer, int sendCount,
const std::vector<std::vector<int>>& sendDisplacements, int sendLength,
int sendExtent, double* recvBuffer, int recvCount,
const std::vector<std::vector<int>>& recvDisplacements, int recvLength,
int recvExtent)
{
#ifdef BUILDING_WITH_MPI
int size;
MPI_Comm_size(MPI_COMM_WORLD, &size);
std::vector<int> sendcnts(size,sendCount);
std::vector<int> sdispls(size, 0);
std::vector<MPI_Datatype> sendtypes;
sendtypes.reserve(size);
std::vector<int> recvcnts(size, recvCount);
std::vector<int> rdispls(size, 0);
std::vector<MPI_Datatype> recvtypes;
recvtypes.reserve(size);
for (int r=0; r<size; r++)
{
MPI_Datatype newtype;
createDisplacedDoubleBlocks(sendLength, sendDisplacements[r], &newtype, sendExtent);
sendtypes.push_back(newtype);
createDisplacedDoubleBlocks(recvLength, recvDisplacements[r], &newtype, recvExtent);
recvtypes.push_back(newtype);
}
MPI_Alltoallw(sendBuffer, &sendcnts[0], &sdispls[0], &sendtypes[0],
recvBuffer, &recvcnts[0], &rdispls[0], &recvtypes[0],
MPI_COMM_WORLD);
for (int r=0; r<size; r++)
{
MPI_Type_free(&sendtypes[r]);
MPI_Type_free(&recvtypes[r]);
}
#else
Q_UNUSED(sendBuffer) Q_UNUSED(sendCount) Q_UNUSED(sendDisplacements) Q_UNUSED(sendLength)
Q_UNUSED(recvBuffer) Q_UNUSED(recvCount) Q_UNUSED(recvDisplacements) Q_UNUSED(recvLength)
#endif
}
//////////////////////////////////////////////////////////////////////
void ProcessManager::sum(double* my_array, double* result_array, int nvalues, int root)
{
#ifdef BUILDING_WITH_MPI
MPI_Reduce(my_array, result_array, nvalues, MPI_DOUBLE, MPI_SUM, root, MPI_COMM_WORLD);
#else
Q_UNUSED(my_array) Q_UNUSED(result_array) Q_UNUSED(nvalues) Q_UNUSED(root)
#endif
}
//////////////////////////////////////////////////////////////////////
void ProcessManager::sum_all(double* my_array, int nvalues)
{
#ifdef BUILDING_WITH_MPI
MPI_Allreduce(MPI_IN_PLACE, my_array, nvalues, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
#else
Q_UNUSED(my_array) Q_UNUSED(nvalues)
#endif
}
void ProcessManager::or_all(bool* boolean)
{
#ifdef BUILDING_WITH_MPI
MPI_Allreduce(MPI_IN_PLACE, boolean, 1, MPI_C_BOOL, MPI_LOR, MPI_COMM_WORLD);
#else
Q_UNUSED(boolean)
#endif
}
//////////////////////////////////////////////////////////////////////
void ProcessManager::broadcast(double* my_array, int nvalues, int root)
{
#ifdef BUILDING_WITH_MPI
MPI_Bcast(my_array, nvalues, MPI_DOUBLE, root, MPI_COMM_WORLD);
#else
Q_UNUSED(my_array) Q_UNUSED(nvalues) Q_UNUSED(root)
#endif
}
//////////////////////////////////////////////////////////////////////
void ProcessManager::broadcast(int* value, int root)
{
#ifdef BUILDING_WITH_MPI
MPI_Bcast(value, 1, MPI_INT, root, MPI_COMM_WORLD);
#else
Q_UNUSED(value) Q_UNUSED(root)
#endif
}
//////////////////////////////////////////////////////////////////////
bool ProcessManager::isRoot()
{
#ifdef BUILDING_WITH_MPI
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
return (rank == 0);
#else
return true;
#endif
}
//////////////////////////////////////////////////////////////////////
bool ProcessManager::isMultiProc()
{
#ifdef BUILDING_WITH_MPI
int size;
MPI_Comm_size(MPI_COMM_WORLD, &size);
return (size > 1);
#else
return false;
#endif
}
//////////////////////////////////////////////////////////////////////
<commit_msg>Add preprocessor directives for compiling without MPI<commit_after>/*//////////////////////////////////////////////////////////////////
//// SKIRT -- an advanced radiative transfer code ////
//// © Astronomical Observatory, Ghent University ////
///////////////////////////////////////////////////////////////// */
#ifdef BUILDING_WITH_MPI
#include <mpi.h>
#endif
#include "ProcessManager.hpp"
#include <QDataStream>
////////////////////////////////////////////////////////////////////
#ifdef BUILDING_WITH_MPI
namespace
{
void createDisplacedDoubleBlocks(int blocklength, const std::vector<int>& displacements, MPI_Datatype* newtypeP,
int extent = -1)
{
int count = displacements.size();
// Multiply the displacements by the block length
std::vector<int> multiplied_disp;
multiplied_disp.reserve(count);
for(auto i: displacements) multiplied_disp.push_back(blocklength*i);
// Create a datatype representing a structure of displaced blocks of the same size;
MPI_Datatype indexedBlock;
MPI_Type_create_indexed_block(count, blocklength, &multiplied_disp[0], MPI_DOUBLE, &indexedBlock);
// Pad this datatype to modify the extent to the requested value
MPI_Aint lb;
MPI_Aint ex;
MPI_Type_get_extent(indexedBlock, &lb, &ex);
if (extent != -1)
{
MPI_Type_create_resized(indexedBlock, lb, extent*sizeof(double), newtypeP);
// Commit the final type and free the intermediary one
MPI_Type_commit(newtypeP);
MPI_Type_free(&indexedBlock);
}
else
{
// No padding, just store the indexed block
*newtypeP = indexedBlock;
MPI_Type_commit(newtypeP);
}
}
}
#endif
std::atomic<int> ProcessManager::requests(0);
//////////////////////////////////////////////////////////////////////
void ProcessManager::initialize(int *argc, char ***argv)
{
#ifdef BUILDING_WITH_MPI
int initialized;
MPI_Initialized(&initialized);
if (!initialized)
{
MPI_Init(argc, argv);
}
#else
Q_UNUSED(argc) Q_UNUSED(argv)
#endif
}
//////////////////////////////////////////////////////////////////////
void ProcessManager::finalize()
{
#ifdef BUILDING_WITH_MPI
MPI_Finalize();
#endif
}
//////////////////////////////////////////////////////////////////////
void ProcessManager::acquireMPI(int& rank, int& Nprocs)
{
#ifdef BUILDING_WITH_MPI
int oldrequests = requests++;
if (oldrequests) // if requests >=1
{
Nprocs = 1;
rank = 0;
}
else // requests == 0
{
MPI_Comm_size(MPI_COMM_WORLD, &Nprocs);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
}
#else
rank = 0;
Nprocs = 1;
#endif
}
//////////////////////////////////////////////////////////////////////
void ProcessManager::releaseMPI()
{
#ifdef BUILDING_WITH_MPI
requests--;
#endif
}
//////////////////////////////////////////////////////////////////////
void ProcessManager::barrier()
{
#ifdef BUILDING_WITH_MPI
MPI_Barrier(MPI_COMM_WORLD);
#endif
}
//////////////////////////////////////////////////////////////////////
void ProcessManager::sendByteBuffer(QByteArray& buffer, int receiver, int tag)
{
#ifdef BUILDING_WITH_MPI
MPI_Send(buffer.data(), buffer.size(), MPI_BYTE, receiver, tag, MPI_COMM_WORLD);
#else
Q_UNUSED(buffer) Q_UNUSED(receiver) Q_UNUSED(tag)
#endif
}
//////////////////////////////////////////////////////////////////////
void ProcessManager::receiveByteBuffer(QByteArray& buffer, int& sender)
{
#ifdef BUILDING_WITH_MPI
MPI_Status status;
MPI_Recv(buffer.data(), buffer.size(), MPI_BYTE, MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &status);
sender = status.MPI_SOURCE;
#else
Q_UNUSED(buffer) Q_UNUSED(sender)
#endif
}
//////////////////////////////////////////////////////////////////////
void ProcessManager::receiveByteBuffer(QByteArray &buffer, int sender, int& tag)
{
#ifdef BUILDING_WITH_MPI
MPI_Status status;
MPI_Recv(buffer.data(), buffer.size(), MPI_BYTE, sender, MPI_ANY_TAG, MPI_COMM_WORLD, &status);
tag = status.MPI_TAG;
#else
Q_UNUSED(buffer) Q_UNUSED(sender) Q_UNUSED(tag)
#endif
}
//////////////////////////////////////////////////////////////////////
void ProcessManager::gatherw(double* sendBuffer, int sendCount,
double* recvBuffer, int recvRank, int recvLength,
const std::vector<std::vector<int>>& recvDisplacements)
{
#ifdef BUILDING_WITH_MPI
int size;
int rank;
MPI_Comm_size(MPI_COMM_WORLD, &size);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
// parameters for the senders
std::vector<int> sendcnts(size, 0); // every process sends nothing to all processes
sendcnts[recvRank] = sendCount; // except to the receiver
std::vector<int> sdispls(size, 0); // starting from sendBuffer + 0
std::vector<MPI_Datatype> sendtypes(size, MPI_DOUBLE); // all doubles
// parameters on the receiving end
std::vector<int> recvcnts;
if (rank != recvRank) recvcnts.resize(size, 0); // I am not receiver: receive nothing from every process
else recvcnts.resize(size, 1); // I am receiver: receive 1 from every process
std::vector<int> rdispls(size, 0); // displacements will be contained in the datatypes
std::vector<MPI_Datatype> recvtypes; // we will construct derived datatypes for receiving from each process
recvtypes.reserve(size);
for (int r=0; r<size; r++)
{
MPI_Datatype newtype;
createDisplacedDoubleBlocks(recvLength, recvDisplacements[r], &newtype);
recvtypes.push_back(newtype);
}
MPI_Alltoallw(sendBuffer, &sendcnts[0], &sdispls[0], &sendtypes[0],
recvBuffer, &recvcnts[0], &rdispls[0], &recvtypes[0],
MPI_COMM_WORLD);
for (int rank=0; rank<size; rank++) MPI_Type_free(&recvtypes[rank]);
#else
Q_UNUSED(sendBuffer) Q_UNUSED(sendCount) Q_UNUSED(recvBuffer) Q_UNUSED(recvRank) Q_UNUSED(recvLength) Q_UNUSED(recvDisplacements)
#endif
}
//////////////////////////////////////////////////////////////////////
void ProcessManager::displacedBlocksAllToAll(double* sendBuffer, int sendCount,
const std::vector<std::vector<int>>& sendDisplacements, int sendLength,
int sendExtent, double* recvBuffer, int recvCount,
const std::vector<std::vector<int>>& recvDisplacements, int recvLength,
int recvExtent)
{
#ifdef BUILDING_WITH_MPI
int size;
MPI_Comm_size(MPI_COMM_WORLD, &size);
std::vector<int> sendcnts(size,sendCount);
std::vector<int> sdispls(size, 0);
std::vector<MPI_Datatype> sendtypes;
sendtypes.reserve(size);
std::vector<int> recvcnts(size, recvCount);
std::vector<int> rdispls(size, 0);
std::vector<MPI_Datatype> recvtypes;
recvtypes.reserve(size);
for (int r=0; r<size; r++)
{
MPI_Datatype newtype;
createDisplacedDoubleBlocks(sendLength, sendDisplacements[r], &newtype, sendExtent);
sendtypes.push_back(newtype);
createDisplacedDoubleBlocks(recvLength, recvDisplacements[r], &newtype, recvExtent);
recvtypes.push_back(newtype);
}
MPI_Alltoallw(sendBuffer, &sendcnts[0], &sdispls[0], &sendtypes[0],
recvBuffer, &recvcnts[0], &rdispls[0], &recvtypes[0],
MPI_COMM_WORLD);
for (int r=0; r<size; r++)
{
MPI_Type_free(&sendtypes[r]);
MPI_Type_free(&recvtypes[r]);
}
#else
Q_UNUSED(sendBuffer) Q_UNUSED(sendCount) Q_UNUSED(sendDisplacements) Q_UNUSED(sendLength) Q_UNUSED(sendExtent)
Q_UNUSED(recvBuffer) Q_UNUSED(recvCount) Q_UNUSED(recvDisplacements) Q_UNUSED(recvLength) Q_UNUSED(recvExtent)
#endif
}
//////////////////////////////////////////////////////////////////////
void ProcessManager::sum(double* my_array, double* result_array, int nvalues, int root)
{
#ifdef BUILDING_WITH_MPI
MPI_Reduce(my_array, result_array, nvalues, MPI_DOUBLE, MPI_SUM, root, MPI_COMM_WORLD);
#else
Q_UNUSED(my_array) Q_UNUSED(result_array) Q_UNUSED(nvalues) Q_UNUSED(root)
#endif
}
//////////////////////////////////////////////////////////////////////
void ProcessManager::sum_all(double* my_array, int nvalues)
{
#ifdef BUILDING_WITH_MPI
MPI_Allreduce(MPI_IN_PLACE, my_array, nvalues, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
#else
Q_UNUSED(my_array) Q_UNUSED(nvalues)
#endif
}
void ProcessManager::or_all(bool* boolean)
{
#ifdef BUILDING_WITH_MPI
MPI_Allreduce(MPI_IN_PLACE, boolean, 1, MPI_C_BOOL, MPI_LOR, MPI_COMM_WORLD);
#else
Q_UNUSED(boolean)
#endif
}
//////////////////////////////////////////////////////////////////////
void ProcessManager::broadcast(double* my_array, int nvalues, int root)
{
#ifdef BUILDING_WITH_MPI
MPI_Bcast(my_array, nvalues, MPI_DOUBLE, root, MPI_COMM_WORLD);
#else
Q_UNUSED(my_array) Q_UNUSED(nvalues) Q_UNUSED(root)
#endif
}
//////////////////////////////////////////////////////////////////////
void ProcessManager::broadcast(int* value, int root)
{
#ifdef BUILDING_WITH_MPI
MPI_Bcast(value, 1, MPI_INT, root, MPI_COMM_WORLD);
#else
Q_UNUSED(value) Q_UNUSED(root)
#endif
}
//////////////////////////////////////////////////////////////////////
bool ProcessManager::isRoot()
{
#ifdef BUILDING_WITH_MPI
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
return (rank == 0);
#else
return true;
#endif
}
//////////////////////////////////////////////////////////////////////
bool ProcessManager::isMultiProc()
{
#ifdef BUILDING_WITH_MPI
int size;
MPI_Comm_size(MPI_COMM_WORLD, &size);
return (size > 1);
#else
return false;
#endif
}
//////////////////////////////////////////////////////////////////////
<|endoftext|>
|
<commit_before>#include "stdafx.h"
#include "Core/Common.h"
#include "Core/Assembler.h"
#include "CommandLineInterface.h"
static void printUsage(std::wstring executableName)
{
Logger::printLine(L"armips assembler v%d.%d.%d (%s %s) by Kingcom",
ARMIPS_VERSION_MAJOR, ARMIPS_VERSION_MINOR, ARMIPS_VERSION_REVISION, __DATE__, __TIME__);
Logger::printLine(L"Usage: %s [optional parameters] <FILE>", executableName);
Logger::printLine(L"");
Logger::printLine(L"Optional parameters:");
Logger::printLine(L" -temp <TEMP> Output temporary assembly data to <TEMP> file");
Logger::printLine(L" -sym <SYM> Output symbol data in the sym format to <SYM> file");
Logger::printLine(L" -sym2 <SYM2> Output symbol data in the sym2 format to <SYM2> file");
Logger::printLine(L" -root <ROOT> Use <ROOT> as working directory during execution");
Logger::printLine(L" -equ <NAME> <VAL> Equivalent to \'<NAME> equ <VAL>\' in code");
Logger::printLine(L" -strequ <NAME> <VAL> Equivalent to \'<NAME> equ \"<VAL>\"\' in code");
Logger::printLine(L" -definelabel <NAME> <VAL> Equivalent to \'.definelabel <NAME>, <VAL>\' in code");
Logger::printLine(L" -erroronwarning Treat all warnings like errors");
Logger::printLine(L"");
Logger::printLine(L"File arguments:");
Logger::printLine(L" <FILE> Main assembly code file");
}
static bool parseArguments(const StringList& arguments, ArmipsArguments& settings)
{
size_t argpos = 1;
bool readflags = true;
while (argpos < arguments.size())
{
if (readflags && arguments[argpos][0] == L'-')
{
if (arguments[argpos] == L"--")
{
readflags = false;
argpos += 1;
}
else if (arguments[argpos] == L"-temp" && argpos + 1 < arguments.size())
{
settings.tempFileName = arguments[argpos + 1];
argpos += 2;
}
else if (arguments[argpos] == L"-sym" && argpos + 1 < arguments.size())
{
settings.symFileName = arguments[argpos + 1];
settings.symFileVersion = 1;
argpos += 2;
}
else if (arguments[argpos] == L"-sym2" && argpos + 1 < arguments.size())
{
settings.symFileName = arguments[argpos + 1];
settings.symFileVersion = 2;
argpos += 2;
}
else if (arguments[argpos] == L"-erroronwarning")
{
settings.errorOnWarning = true;
argpos += 1;
}
else if (arguments[argpos] == L"-equ" && argpos + 2 < arguments.size())
{
EquationDefinition def;
def.name = arguments[argpos + 1];
if (!checkValidLabelName(def.name))
{
Logger::printError(Logger::Error, L"Invalid equation name %s", def.name);
return false;
}
std::transform(def.name.begin(), def.name.end(), def.name.begin(), ::towlower);
def.value = arguments[argpos + 2];
settings.equList.push_back(def);
argpos += 3;
}
else if (arguments[argpos] == L"-strequ" && argpos + 2 < arguments.size())
{
EquationDefinition def;
def.name = arguments[argpos + 1];
if (!checkValidLabelName(def.name))
{
Logger::printError(Logger::Error, L"Invalid equation name %s", def.name);
return false;
}
std::transform(def.name.begin(), def.name.end(), def.name.begin(), ::towlower);
def.value = formatString(L"\"%s\"", arguments[argpos + 2]);
settings.equList.push_back(def);
argpos += 3;
}
else if (arguments[argpos] == L"-time")
{
Logger::printError(Logger::Warning, L"-time flag is deprecated");
argpos += 1;
}
else if (arguments[argpos] == L"-root" && argpos + 1 < arguments.size())
{
if(!changeDirectory(arguments[argpos + 1]))
{
Logger::printError(Logger::Error, L"Could not open directory '%s'", arguments[argpos + 1]);
return false;
}
argpos += 2;
}
else if (arguments[argpos] == L"-definelabel" && argpos + 2 < arguments.size())
{
LabelDefinition def;
def.originalName = arguments[argpos + 1];
if (!checkValidLabelName(def.originalName))
{
Logger::printError(Logger::Error, L"Invalid definelabel name %s", def.originalName);
return false;
}
def.name = def.originalName;
std::transform(def.name.begin(), def.name.end(), def.name.begin(), ::towlower);
int64_t value;
if (!stringToInt(arguments[argpos + 2], 0, arguments[argpos + 2].size(), value))
{
Logger::printError(Logger::Error, L"Invalid definelabel value '%s'\n", arguments[argpos + 2]);
return false;
}
def.value = value;
settings.labels.push_back(def);
argpos += 3;
}
else {
Logger::printError(Logger::Error, L"Invalid command line argument '%s'\n", arguments[argpos]);
printUsage(arguments[0]);
return false;
}
}
else {
// only allow one input filename
if (settings.inputFileName == L"")
{
settings.inputFileName = arguments[argpos];
argpos++;
}
else {
Logger::printError(Logger::Error, L"Multiple input assembly files specified\n");
printUsage(arguments[0]);
return false;
}
}
}
// ensure input file was specified
if (settings.inputFileName == L"")
{
if (arguments.size() > 1)
Logger::printError(Logger::Error, L"Missing input assembly file\n");
printUsage(arguments[0]);
return false;
}
// turn input filename into an absolute path
if (settings.useAbsoluteFileNames && isAbsolutePath(settings.inputFileName) == false)
settings.inputFileName = formatString(L"%s/%s", getCurrentDirectory(), settings.inputFileName);
if (fileExists(settings.inputFileName) == false)
{
Logger::printError(Logger::Error, L"File '%s' not found", settings.inputFileName);
return false;
}
return true;
}
int runFromCommandLine(const StringList& arguments, ArmipsArguments settings)
{
if (parseArguments(arguments, settings) == false)
{
if (!settings.silent)
Logger::printLine(L"Cannot parse arguments; aborting.");
return 1;
}
if (runArmips(settings) == false)
{
if (!settings.silent)
Logger::printLine(L"Aborting.");
return 1;
}
return 0;
}
<commit_msg>Check that -strequ/-equ/-definelabel names do not have multiple definitions<commit_after>#include "stdafx.h"
#include "Core/Common.h"
#include "Core/Assembler.h"
#include "CommandLineInterface.h"
static void printUsage(std::wstring executableName)
{
Logger::printLine(L"armips assembler v%d.%d.%d (%s %s) by Kingcom",
ARMIPS_VERSION_MAJOR, ARMIPS_VERSION_MINOR, ARMIPS_VERSION_REVISION, __DATE__, __TIME__);
Logger::printLine(L"Usage: %s [optional parameters] <FILE>", executableName);
Logger::printLine(L"");
Logger::printLine(L"Optional parameters:");
Logger::printLine(L" -temp <TEMP> Output temporary assembly data to <TEMP> file");
Logger::printLine(L" -sym <SYM> Output symbol data in the sym format to <SYM> file");
Logger::printLine(L" -sym2 <SYM2> Output symbol data in the sym2 format to <SYM2> file");
Logger::printLine(L" -root <ROOT> Use <ROOT> as working directory during execution");
Logger::printLine(L" -equ <NAME> <VAL> Equivalent to \'<NAME> equ <VAL>\' in code");
Logger::printLine(L" -strequ <NAME> <VAL> Equivalent to \'<NAME> equ \"<VAL>\"\' in code");
Logger::printLine(L" -definelabel <NAME> <VAL> Equivalent to \'.definelabel <NAME>, <VAL>\' in code");
Logger::printLine(L" -erroronwarning Treat all warnings like errors");
Logger::printLine(L"");
Logger::printLine(L"File arguments:");
Logger::printLine(L" <FILE> Main assembly code file");
}
static bool parseArguments(const StringList& arguments, ArmipsArguments& settings)
{
size_t argpos = 1;
bool readflags = true;
while (argpos < arguments.size())
{
if (readflags && arguments[argpos][0] == L'-')
{
if (arguments[argpos] == L"--")
{
readflags = false;
argpos += 1;
}
else if (arguments[argpos] == L"-temp" && argpos + 1 < arguments.size())
{
settings.tempFileName = arguments[argpos + 1];
argpos += 2;
}
else if (arguments[argpos] == L"-sym" && argpos + 1 < arguments.size())
{
settings.symFileName = arguments[argpos + 1];
settings.symFileVersion = 1;
argpos += 2;
}
else if (arguments[argpos] == L"-sym2" && argpos + 1 < arguments.size())
{
settings.symFileName = arguments[argpos + 1];
settings.symFileVersion = 2;
argpos += 2;
}
else if (arguments[argpos] == L"-erroronwarning")
{
settings.errorOnWarning = true;
argpos += 1;
}
else if (arguments[argpos] == L"-equ" && argpos + 2 < arguments.size())
{
EquationDefinition def;
auto originalName = arguments[argpos+1];
def.name = originalName;
std::transform(def.name.begin(), def.name.end(), def.name.begin(), ::towlower);
if (!checkValidLabelName(originalName))
{
Logger::printError(Logger::Error, L"Invalid equation name %s", originalName);
return false;
}
auto it = std::find_if(settings.equList.begin(), settings.equList.end(),
[&def](EquationDefinition x) -> bool {return def.name == x.name;});
if(it != settings.equList.end())
{
Logger::printError(Logger::Error, L"Equation name %s defined more than once", originalName);
return false;
}
def.value = arguments[argpos + 2];
settings.equList.push_back(def);
argpos += 3;
}
else if (arguments[argpos] == L"-strequ" && argpos + 2 < arguments.size())
{
EquationDefinition def;
auto originalName = arguments[argpos+1];
def.name = originalName;
std::transform(def.name.begin(), def.name.end(), def.name.begin(), ::towlower);
if (!checkValidLabelName(originalName))
{
Logger::printError(Logger::Error, L"Invalid equation name %s", originalName);
return false;
}
auto it = std::find_if(settings.equList.begin(), settings.equList.end(),
[&def](EquationDefinition x) -> bool {return def.name == x.name;});
if(it != settings.equList.end())
{
Logger::printError(Logger::Error, L"Equation name %s defined more than once", originalName);
return false;
}
def.value = formatString(L"\"%s\"", arguments[argpos + 2]);
settings.equList.push_back(def);
argpos += 3;
}
else if (arguments[argpos] == L"-time")
{
Logger::printError(Logger::Warning, L"-time flag is deprecated");
argpos += 1;
}
else if (arguments[argpos] == L"-root" && argpos + 1 < arguments.size())
{
if(!changeDirectory(arguments[argpos + 1]))
{
Logger::printError(Logger::Error, L"Could not open directory '%s'", arguments[argpos + 1]);
return false;
}
argpos += 2;
}
else if (arguments[argpos] == L"-definelabel" && argpos + 2 < arguments.size())
{
LabelDefinition def;
def.originalName = arguments[argpos + 1];
def.name = def.originalName;
std::transform(def.name.begin(), def.name.end(), def.name.begin(), ::towlower);
if (!checkValidLabelName(def.originalName))
{
Logger::printError(Logger::Error, L"Invalid label name %s", def.originalName);
return false;
}
auto it = std::find_if(settings.labels.begin(), settings.labels.end(),
[&def](LabelDefinition x) -> bool {return def.name == x.name;});
if(it != settings.labels.end())
{
Logger::printError(Logger::Error, L"Label name %s defined more than once", def.originalName);
return false;
}
int64_t value;
if (!stringToInt(arguments[argpos + 2], 0, arguments[argpos + 2].size(), value))
{
Logger::printError(Logger::Error, L"Invalid label value '%s'\n", arguments[argpos + 2]);
return false;
}
def.value = value;
settings.labels.push_back(def);
argpos += 3;
}
else {
Logger::printError(Logger::Error, L"Invalid command line argument '%s'\n", arguments[argpos]);
printUsage(arguments[0]);
return false;
}
}
else {
// only allow one input filename
if (settings.inputFileName == L"")
{
settings.inputFileName = arguments[argpos];
argpos++;
}
else {
Logger::printError(Logger::Error, L"Multiple input assembly files specified\n");
printUsage(arguments[0]);
return false;
}
}
}
// ensure input file was specified
if (settings.inputFileName == L"")
{
if (arguments.size() > 1)
Logger::printError(Logger::Error, L"Missing input assembly file\n");
printUsage(arguments[0]);
return false;
}
// turn input filename into an absolute path
if (settings.useAbsoluteFileNames && isAbsolutePath(settings.inputFileName) == false)
settings.inputFileName = formatString(L"%s/%s", getCurrentDirectory(), settings.inputFileName);
if (fileExists(settings.inputFileName) == false)
{
Logger::printError(Logger::Error, L"File '%s' not found", settings.inputFileName);
return false;
}
return true;
}
int runFromCommandLine(const StringList& arguments, ArmipsArguments settings)
{
if (parseArguments(arguments, settings) == false)
{
if (arguments.size() > 1 && !settings.silent)
Logger::printLine(L"Cannot parse arguments; aborting.");
return 1;
}
if (runArmips(settings) == false)
{
if (!settings.silent)
Logger::printLine(L"Aborting.");
return 1;
}
return 0;
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <string>
#include "src/Options.hpp"
#include "src/Cluster.hpp"
#include <map>
using namespace std;
int main(int argc, char *argv[]){
std::map<string,string > options2;
/* Dirichlet, lumped */
options2["preconditioner"] = "Dirichlet";
options2["path2data"] = "data/";
options2["young_modulus"] = "1000";
options2["poissons_ratio"] = "0.3";
/* dissection | pardiso */
options2["linear_solver"] = "dissection";
/* {0, 1, 2, 3 } */
options2["print_matrices"] = "0";
/* ker, cor, all */
options2["typeBc"] = "ker";
/* true, false */
options2["Ac_extended_by_kerGc"] = "false";
/* true, false */
options2["GcTGc_assembl_block_by_block"] = "true";
/* true, false */
options2["Bc_fullRank"] = "true";
/* true, false */
options2["create_analytic_ker_K"] = "false";
options2["Nx"] = "2";
options2["Ny"] = "2";
options2["Nz"] = "2";
options2["nx"] = "5";
options2["ny"] = "5";
options2["nz"] = "5";
printf("+++++++++++++++++++++++++++++++++++ %s\n", options2["path2data"].c_str());
if (options2["linear_solver"] == "pardiso" &&
options2["create_analytic_ker_K"] == "false"){
cout <<"###########################################################" << endl;
cout << "if pardiso, kernel must be provided by analytical formula" << endl;
cout <<"###########################################################" << endl;
options2["create_analytic_ker_K"] = true;
}
if (argc > 1) {
options2["Nx"] = (argv[1]);
}
if (argc > 2) {
options2["Ny"] = (argv[2]);
}
if (argc > 3) {
options2["Nz"] = (argv[3]);
}
if (argc > 4) {
options2["nx"] = (argv[4]);
}
if (argc > 5) {
options2["ny"] = (argv[5]);
}
if (argc > 6) {
options2["nz"] = (argv[6]);
}
cout << argv[0] << endl;
Options options;
Cluster cluster(options,options2);
cout << "----------------- done -----------------\n" ;
return 0;
}
// HOW TO PRINT OPTIONS2
// cout << "\t\t\tK.options2.size() " << K.options2.size() << endl;
// for (std::map<string,string>::const_iterator it=K.options2.begin(); it!=K.options2.end(); ++it)
// std::cout << "\t\t\t" << it->first << " => " << it->second << '\n';
<commit_msg>new options added<commit_after>#include <iostream>
#include <string>
#include "src/Options.hpp"
#include "src/Cluster.hpp"
#include <map>
using namespace std;
int main(int argc, char *argv[]){
std::map<string,string > options2;
options2["eps_iter"] = "1e-4";
/* Dirichlet, lumped */
options2["preconditioner"] = "Dirichlet";
//options2["preconditioner"] = "lumped";
options2["path2data"] = "data/";
options2["young_modulus"] = "1000";
options2["poissons_ratio"] = "0.3";
/* dissection | pardiso */
options2["linear_solver"] = "dissection";
/* {0, 1, 2, 3 } */
options2["print_matrices"] = "0";
/* ker, cor, all */
options2["typeBc"] = "ker";
/* true, false */
options2["Ac_extended_by_kerGc"] = "false";
/* true, false */
options2["GcTGc_assembl_block_by_block"] = "true";
/* true, false */
options2["Bc_fullRank"] = "true";
/* true, false */
options2["create_analytic_ker_K"] = "false";
options2["Nx"] = "2";
options2["Ny"] = "2";
options2["Nz"] = "2";
options2["nx"] = "5";
options2["ny"] = "5";
options2["nz"] = "5";
printf("+++++++++++++++++++++++++++++++++++ %s\n", options2["path2data"].c_str());
if (options2["linear_solver"] == "pardiso" &&
options2["create_analytic_ker_K"] == "false"){
cout <<"###########################################################" << endl;
cout << "if pardiso, kernel must be provided by analytical formula" << endl;
cout <<"###########################################################" << endl;
options2["create_analytic_ker_K"] = true;
}
if (argc > 1) {
options2["Nx"] = (argv[1]);
}
if (argc > 2) {
options2["Ny"] = (argv[2]);
}
if (argc > 3) {
options2["Nz"] = (argv[3]);
}
if (argc > 4) {
options2["nx"] = (argv[4]);
}
if (argc > 5) {
options2["ny"] = (argv[5]);
}
if (argc > 6) {
options2["nz"] = (argv[6]);
}
cout << argv[0] << endl;
Options options;
Cluster cluster(options,options2);
cout << "----------------- done -----------------\n" ;
return 0;
}
// HOW TO PRINT OPTIONS2
// cout << "\t\t\tK.options2.size() " << K.options2.size() << endl;
// for (std::map<string,string>::const_iterator it=K.options2.begin(); it!=K.options2.end(); ++it)
// std::cout << "\t\t\t" << it->first << " => " << it->second << '\n';
<|endoftext|>
|
<commit_before>/* Copyright 2018 Kristofer Björnson
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/** @file FLEX.cpp
*
* @author Kristofer Björnson
*/
#include "TBTK/PropertyExtractor/BlockDiagonalizer.h"
#include "TBTK/PropertyExtractor/ElectronFluctuationVertex.h"
#include "TBTK/PropertyExtractor/MatsubaraSusceptibility.h"
#include "TBTK/PropertyExtractor/RPASusceptibility.h"
#include "TBTK/PropertyExtractor/SelfEnergy2.h"
#include "TBTK/Solver/BlockDiagonalizer.h"
#include "TBTK/Solver/ElectronFluctuationVertex.h"
#include "TBTK/Solver/Greens.h"
#include "TBTK/Solver/MatsubaraSusceptibility.h"
#include "TBTK/Solver/RPASusceptibility.h"
#include "TBTK/Solver/SelfEnergy2.h"
#include "TBTK/Solver/FLEX.h"
#include <complex>
using namespace std;
namespace TBTK{
namespace Solver{
FLEX::FLEX(const MomentumSpaceContext &momentumSpaceContext) :
momentumSpaceContext(momentumSpaceContext)
{
lowerFermionicMatsubaraEnergyIndex = -1;
upperFermionicMatsubaraEnergyIndex = 1;
lowerBosonicMatsubaraEnergyIndex = 0;
upperBosonicMatsubaraEnergyIndex = 0;
U = 0;
J = 0;
state = State::NotYetStarted;
maxIterations = 1;
callback = nullptr;
norm = Norm::Max;
convergenceParameter = 0;
}
void FLEX::run(){
//Calculate the non-interacting Green's function.
Timer::tick("Green's function 0");
calculateBareGreensFunction();
greensFunction = greensFunction0;
Timer::tock();
state = State::GreensFunctionCalculated;
if(callback != nullptr)
callback(*this);
//The main loop.
unsigned int iteration = 0;
while(iteration++ < maxIterations){
//Calculate the bare susceptibility.
calculateBareSusceptibility();
state = State::BareSusceptibilityCalculated;
if(callback != nullptr)
callback(*this);
//Calculate the RPA charge and spin susceptibilities.
calculateRPASusceptibilities();
state = State::RPASusceptibilitiesCalculated;
if(callback != nullptr)
callback(*this);
//Calculate the interaction vertex.
calculateInteractionVertex();
state = State::InteractionVertexCalculated;
if(callback != nullptr)
callback(*this);
//Calculate the self-energy.
calculateSelfEnergy();
state = State::SelfEnergyCalculated;
if(callback != nullptr)
callback(*this);
//Calculate the self energy.
oldGreensFunction = greensFunction;
calculateGreensFunction();
state = State::GreensFunctionCalculated;
if(callback != nullptr)
callback(*this);
if(convergenceParameter < tolerance)
break;
}
}
void FLEX::calculateBareGreensFunction(){
const vector<unsigned int> &numMeshPoints
= momentumSpaceContext.getNumMeshPoints();
TBTKAssert(
numMeshPoints.size() == 2,
"Solver::FLEX::run()",
"Only two-dimensional block indices supported yet, but the"
<< " MomentumSpaceContext has a '" << numMeshPoints.size()
<< "'-dimensional block structure.",
""
);
BlockDiagonalizer blockDiagonalizer;
blockDiagonalizer.setVerbose(false);
blockDiagonalizer.setModel(getModel());
blockDiagonalizer.run();
vector<Index> greensFunctionPatterns;
for(int kx = 0; kx < (int)numMeshPoints[0]; kx++){
for(int ky = 0; ky < (int)numMeshPoints[1]; ky++){
greensFunctionPatterns.push_back(
{{kx, ky, IDX_ALL}, {kx, ky, IDX_ALL}}
);
}
}
PropertyExtractor::BlockDiagonalizer
blockDiagonalizerPropertyExtractor(blockDiagonalizer);
blockDiagonalizerPropertyExtractor.setEnergyWindow(
lowerFermionicMatsubaraEnergyIndex,
upperFermionicMatsubaraEnergyIndex,
lowerBosonicMatsubaraEnergyIndex,
upperBosonicMatsubaraEnergyIndex
);
greensFunction0
= blockDiagonalizerPropertyExtractor.calculateGreensFunction(
greensFunctionPatterns,
Property::GreensFunction::Type::Matsubara
);
}
void FLEX::calculateBareSusceptibility(){
MatsubaraSusceptibility matsubaraSusceptibilitySolver(
momentumSpaceContext,
greensFunction
);
matsubaraSusceptibilitySolver.setVerbose(false);
matsubaraSusceptibilitySolver.setModel(getModel());
PropertyExtractor::MatsubaraSusceptibility
matsubaraSusceptibilityPropertyExtractor(
matsubaraSusceptibilitySolver
);
matsubaraSusceptibilityPropertyExtractor.setEnergyWindow(
lowerFermionicMatsubaraEnergyIndex,
upperFermionicMatsubaraEnergyIndex,
lowerBosonicMatsubaraEnergyIndex,
upperBosonicMatsubaraEnergyIndex
);
bareSusceptibility
= matsubaraSusceptibilityPropertyExtractor.calculateSusceptibility({
{
{IDX_ALL, IDX_ALL},
{IDX_ALL},
{IDX_ALL},
{IDX_ALL},
{IDX_ALL}
}
});
}
void FLEX::calculateRPASusceptibilities(){
RPASusceptibility rpaSusceptibilitySolver(
momentumSpaceContext,
bareSusceptibility
);
rpaSusceptibilitySolver.setVerbose(false);
rpaSusceptibilitySolver.setModel(getModel());
rpaSusceptibilitySolver.setU(U);
rpaSusceptibilitySolver.setJ(J);
rpaSusceptibilitySolver.setUp(U - 2.*J);
rpaSusceptibilitySolver.setJp(J);
PropertyExtractor::RPASusceptibility
rpaSusceptibilityPropertyExtractor(
rpaSusceptibilitySolver
);
rpaChargeSusceptibility
= rpaSusceptibilityPropertyExtractor.calculateChargeSusceptibility({
{
{IDX_ALL, IDX_ALL},
{IDX_ALL},
{IDX_ALL},
{IDX_ALL},
{IDX_ALL}
}
});
rpaSpinSusceptibility
= rpaSusceptibilityPropertyExtractor.calculateSpinSusceptibility({
{
{IDX_ALL, IDX_ALL},
{IDX_ALL},
{IDX_ALL},
{IDX_ALL},
{IDX_ALL}
}
});
}
void FLEX::calculateInteractionVertex(){
ElectronFluctuationVertex
electronFluctuationVertexSolver(
momentumSpaceContext,
rpaChargeSusceptibility,
rpaSpinSusceptibility
);
electronFluctuationVertexSolver.setVerbose(false);
electronFluctuationVertexSolver.setModel(getModel());
electronFluctuationVertexSolver.setU(U);
electronFluctuationVertexSolver.setJ(J);
electronFluctuationVertexSolver.setUp(U - 2.*J);
electronFluctuationVertexSolver.setJp(J);
PropertyExtractor::ElectronFluctuationVertex
electronFluctuationVertexPropertyExtractor(
electronFluctuationVertexSolver
);
interactionVertex
= electronFluctuationVertexPropertyExtractor.calculateInteractionVertex({
{
{IDX_ALL, IDX_ALL},
{IDX_ALL},
{IDX_ALL},
{IDX_ALL},
{IDX_ALL}
}
});
}
void FLEX::calculateSelfEnergy(){
SelfEnergy2 selfEnergySolver(
momentumSpaceContext,
interactionVertex,
greensFunction
);
selfEnergySolver.setVerbose(false);
selfEnergySolver.setModel(getModel());
PropertyExtractor::SelfEnergy2 selfEnergyPropertyExtractor(
selfEnergySolver
);
selfEnergyPropertyExtractor.setEnergyWindow(
lowerFermionicMatsubaraEnergyIndex,
upperFermionicMatsubaraEnergyIndex,
lowerBosonicMatsubaraEnergyIndex,
upperBosonicMatsubaraEnergyIndex
);
selfEnergy = selfEnergyPropertyExtractor.calculateSelfEnergy({
{{IDX_ALL, IDX_ALL}, {IDX_ALL}, {IDX_ALL}}
});
convertSelfEnergyIndexStructure();
}
void FLEX::calculateGreensFunction(){
Greens greensSolver;
greensSolver.setVerbose(false);
greensSolver.setModel(getModel());
greensSolver.setGreensFunction(greensFunction0);
greensFunction = greensSolver.calculateInteractingGreensFunction(
selfEnergy
);
}
void FLEX::convertSelfEnergyIndexStructure(){
const vector<unsigned int> &numMeshPoints
= momentumSpaceContext.getNumMeshPoints();
TBTKAssert(
numMeshPoints.size() == 2,
"Solver::FLEX::convertSelfEnergyBlockStructure()",
"Only two-dimensional block indices supported yet, but the"
<< " MomentumSpaceContext has a '" << numMeshPoints.size()
<< "'-dimensional block structure.",
""
);
unsigned int numOrbitals = momentumSpaceContext.getNumOrbitals();
IndexTree memoryLayout;
for(unsigned int kx = 0; kx < numMeshPoints[0]; kx++){
for(unsigned int ky = 0; ky < numMeshPoints[1]; ky++){
for(
unsigned int orbital0 = 0;
orbital0 < numOrbitals;
orbital0++
){
for(
unsigned int orbital1 = 0;
orbital1 < numOrbitals;
orbital1++
){
memoryLayout.add({
{(int)kx, (int)ky, (int)orbital0},
{(int)kx, (int)ky, (int)orbital1}
});
}
}
}
}
memoryLayout.generateLinearMap();
Property::SelfEnergy newSelfEnergy(
memoryLayout,
selfEnergy.getLowerMatsubaraEnergyIndex(),
selfEnergy.getUpperMatsubaraEnergyIndex(),
selfEnergy.getFundamentalMatsubaraEnergy()
);
for(unsigned int kx = 0; kx < numMeshPoints[0]; kx++){
for(unsigned int ky = 0; ky < numMeshPoints[1]; ky++){
for(
unsigned int orbital0 = 0;
orbital0 < numOrbitals;
orbital0++
){
for(
unsigned int orbital1 = 0;
orbital1 < numOrbitals;
orbital1++
){
for(
unsigned int n = 0;
n < selfEnergy.getNumMatsubaraEnergies();
n++
){
newSelfEnergy(
{
{
(int)kx,
(int)ky,
(int)orbital0
},
{
(int)kx,
(int)ky,
(int)orbital1
}
},
n
) = selfEnergy(
{
{
(int)kx,
(int)ky
},
{(int)orbital0},
{(int)orbital1}
},
n
);
}
}
}
}
}
selfEnergy = newSelfEnergy;
}
void FLEX::calculateConvergenceParameter(){
const vector<complex<double>> &oldData = oldGreensFunction.getData();
const vector<complex<double>> &newData = greensFunction.getData();
TBTKAssert(
oldData.size() == newData.size(),
"Solver::FLEX::calculateConvergenceParameter()",
"Incompatible Green's function data sizes.",
"This should never happen, contact the developer."
);
switch(norm){
case Norm::Max:
{
double oldMax = 0;
double differenceMax = 0;
for(unsigned int n = 0; n < oldData.size(); n++){
if(abs(oldData[n]) > oldMax)
oldMax = abs(oldData[n]);
if(abs(oldData[n] - newData[n]) > differenceMax)
differenceMax = abs(oldData[n] - newData[n]);
}
convergenceParameter = differenceMax/oldMax;
break;
}
case Norm::L2:
{
double oldL2 = 0;
double differenceL2 = 0;
for(unsigned int n = 0; n < oldData.size(); n++){
oldL2 += pow(abs(oldData[n]), 2);
differenceL2 += pow(abs(oldData[n] - newData[n]), 2);
}
convergenceParameter = differenceL2/oldL2;
break;
}
default:
TBTKExit(
"Solver::FLEX::calculateConvergenceParameter()",
"Unknown norm.",
"This should never happen, contact the developer."
);
}
}
} //End of namespace Solver
} //End of namesapce TBTK
<commit_msg>Reinserted function call for calculating the convergence parameter that was accidentally removed in previous commit.<commit_after>/* Copyright 2018 Kristofer Björnson
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/** @file FLEX.cpp
*
* @author Kristofer Björnson
*/
#include "TBTK/PropertyExtractor/BlockDiagonalizer.h"
#include "TBTK/PropertyExtractor/ElectronFluctuationVertex.h"
#include "TBTK/PropertyExtractor/MatsubaraSusceptibility.h"
#include "TBTK/PropertyExtractor/RPASusceptibility.h"
#include "TBTK/PropertyExtractor/SelfEnergy2.h"
#include "TBTK/Solver/BlockDiagonalizer.h"
#include "TBTK/Solver/ElectronFluctuationVertex.h"
#include "TBTK/Solver/Greens.h"
#include "TBTK/Solver/MatsubaraSusceptibility.h"
#include "TBTK/Solver/RPASusceptibility.h"
#include "TBTK/Solver/SelfEnergy2.h"
#include "TBTK/Solver/FLEX.h"
#include <complex>
using namespace std;
namespace TBTK{
namespace Solver{
FLEX::FLEX(const MomentumSpaceContext &momentumSpaceContext) :
momentumSpaceContext(momentumSpaceContext)
{
lowerFermionicMatsubaraEnergyIndex = -1;
upperFermionicMatsubaraEnergyIndex = 1;
lowerBosonicMatsubaraEnergyIndex = 0;
upperBosonicMatsubaraEnergyIndex = 0;
U = 0;
J = 0;
state = State::NotYetStarted;
maxIterations = 1;
callback = nullptr;
norm = Norm::Max;
convergenceParameter = 0;
}
void FLEX::run(){
//Calculate the non-interacting Green's function.
Timer::tick("Green's function 0");
calculateBareGreensFunction();
greensFunction = greensFunction0;
Timer::tock();
state = State::GreensFunctionCalculated;
if(callback != nullptr)
callback(*this);
//The main loop.
unsigned int iteration = 0;
while(iteration++ < maxIterations){
//Calculate the bare susceptibility.
calculateBareSusceptibility();
state = State::BareSusceptibilityCalculated;
if(callback != nullptr)
callback(*this);
//Calculate the RPA charge and spin susceptibilities.
calculateRPASusceptibilities();
state = State::RPASusceptibilitiesCalculated;
if(callback != nullptr)
callback(*this);
//Calculate the interaction vertex.
calculateInteractionVertex();
state = State::InteractionVertexCalculated;
if(callback != nullptr)
callback(*this);
//Calculate the self-energy.
calculateSelfEnergy();
state = State::SelfEnergyCalculated;
if(callback != nullptr)
callback(*this);
//Calculate the self energy.
oldGreensFunction = greensFunction;
calculateGreensFunction();
state = State::GreensFunctionCalculated;
if(callback != nullptr)
callback(*this);
calculateConvergenceParameter();
if(convergenceParameter < tolerance)
break;
}
}
void FLEX::calculateBareGreensFunction(){
const vector<unsigned int> &numMeshPoints
= momentumSpaceContext.getNumMeshPoints();
TBTKAssert(
numMeshPoints.size() == 2,
"Solver::FLEX::run()",
"Only two-dimensional block indices supported yet, but the"
<< " MomentumSpaceContext has a '" << numMeshPoints.size()
<< "'-dimensional block structure.",
""
);
BlockDiagonalizer blockDiagonalizer;
blockDiagonalizer.setVerbose(false);
blockDiagonalizer.setModel(getModel());
blockDiagonalizer.run();
vector<Index> greensFunctionPatterns;
for(int kx = 0; kx < (int)numMeshPoints[0]; kx++){
for(int ky = 0; ky < (int)numMeshPoints[1]; ky++){
greensFunctionPatterns.push_back(
{{kx, ky, IDX_ALL}, {kx, ky, IDX_ALL}}
);
}
}
PropertyExtractor::BlockDiagonalizer
blockDiagonalizerPropertyExtractor(blockDiagonalizer);
blockDiagonalizerPropertyExtractor.setEnergyWindow(
lowerFermionicMatsubaraEnergyIndex,
upperFermionicMatsubaraEnergyIndex,
lowerBosonicMatsubaraEnergyIndex,
upperBosonicMatsubaraEnergyIndex
);
greensFunction0
= blockDiagonalizerPropertyExtractor.calculateGreensFunction(
greensFunctionPatterns,
Property::GreensFunction::Type::Matsubara
);
}
void FLEX::calculateBareSusceptibility(){
MatsubaraSusceptibility matsubaraSusceptibilitySolver(
momentumSpaceContext,
greensFunction
);
matsubaraSusceptibilitySolver.setVerbose(false);
matsubaraSusceptibilitySolver.setModel(getModel());
PropertyExtractor::MatsubaraSusceptibility
matsubaraSusceptibilityPropertyExtractor(
matsubaraSusceptibilitySolver
);
matsubaraSusceptibilityPropertyExtractor.setEnergyWindow(
lowerFermionicMatsubaraEnergyIndex,
upperFermionicMatsubaraEnergyIndex,
lowerBosonicMatsubaraEnergyIndex,
upperBosonicMatsubaraEnergyIndex
);
bareSusceptibility
= matsubaraSusceptibilityPropertyExtractor.calculateSusceptibility({
{
{IDX_ALL, IDX_ALL},
{IDX_ALL},
{IDX_ALL},
{IDX_ALL},
{IDX_ALL}
}
});
}
void FLEX::calculateRPASusceptibilities(){
RPASusceptibility rpaSusceptibilitySolver(
momentumSpaceContext,
bareSusceptibility
);
rpaSusceptibilitySolver.setVerbose(false);
rpaSusceptibilitySolver.setModel(getModel());
rpaSusceptibilitySolver.setU(U);
rpaSusceptibilitySolver.setJ(J);
rpaSusceptibilitySolver.setUp(U - 2.*J);
rpaSusceptibilitySolver.setJp(J);
PropertyExtractor::RPASusceptibility
rpaSusceptibilityPropertyExtractor(
rpaSusceptibilitySolver
);
rpaChargeSusceptibility
= rpaSusceptibilityPropertyExtractor.calculateChargeSusceptibility({
{
{IDX_ALL, IDX_ALL},
{IDX_ALL},
{IDX_ALL},
{IDX_ALL},
{IDX_ALL}
}
});
rpaSpinSusceptibility
= rpaSusceptibilityPropertyExtractor.calculateSpinSusceptibility({
{
{IDX_ALL, IDX_ALL},
{IDX_ALL},
{IDX_ALL},
{IDX_ALL},
{IDX_ALL}
}
});
}
void FLEX::calculateInteractionVertex(){
ElectronFluctuationVertex
electronFluctuationVertexSolver(
momentumSpaceContext,
rpaChargeSusceptibility,
rpaSpinSusceptibility
);
electronFluctuationVertexSolver.setVerbose(false);
electronFluctuationVertexSolver.setModel(getModel());
electronFluctuationVertexSolver.setU(U);
electronFluctuationVertexSolver.setJ(J);
electronFluctuationVertexSolver.setUp(U - 2.*J);
electronFluctuationVertexSolver.setJp(J);
PropertyExtractor::ElectronFluctuationVertex
electronFluctuationVertexPropertyExtractor(
electronFluctuationVertexSolver
);
interactionVertex
= electronFluctuationVertexPropertyExtractor.calculateInteractionVertex({
{
{IDX_ALL, IDX_ALL},
{IDX_ALL},
{IDX_ALL},
{IDX_ALL},
{IDX_ALL}
}
});
}
void FLEX::calculateSelfEnergy(){
SelfEnergy2 selfEnergySolver(
momentumSpaceContext,
interactionVertex,
greensFunction
);
selfEnergySolver.setVerbose(false);
selfEnergySolver.setModel(getModel());
PropertyExtractor::SelfEnergy2 selfEnergyPropertyExtractor(
selfEnergySolver
);
selfEnergyPropertyExtractor.setEnergyWindow(
lowerFermionicMatsubaraEnergyIndex,
upperFermionicMatsubaraEnergyIndex,
lowerBosonicMatsubaraEnergyIndex,
upperBosonicMatsubaraEnergyIndex
);
selfEnergy = selfEnergyPropertyExtractor.calculateSelfEnergy({
{{IDX_ALL, IDX_ALL}, {IDX_ALL}, {IDX_ALL}}
});
convertSelfEnergyIndexStructure();
}
void FLEX::calculateGreensFunction(){
Greens greensSolver;
greensSolver.setVerbose(false);
greensSolver.setModel(getModel());
greensSolver.setGreensFunction(greensFunction0);
greensFunction = greensSolver.calculateInteractingGreensFunction(
selfEnergy
);
}
void FLEX::convertSelfEnergyIndexStructure(){
const vector<unsigned int> &numMeshPoints
= momentumSpaceContext.getNumMeshPoints();
TBTKAssert(
numMeshPoints.size() == 2,
"Solver::FLEX::convertSelfEnergyBlockStructure()",
"Only two-dimensional block indices supported yet, but the"
<< " MomentumSpaceContext has a '" << numMeshPoints.size()
<< "'-dimensional block structure.",
""
);
unsigned int numOrbitals = momentumSpaceContext.getNumOrbitals();
IndexTree memoryLayout;
for(unsigned int kx = 0; kx < numMeshPoints[0]; kx++){
for(unsigned int ky = 0; ky < numMeshPoints[1]; ky++){
for(
unsigned int orbital0 = 0;
orbital0 < numOrbitals;
orbital0++
){
for(
unsigned int orbital1 = 0;
orbital1 < numOrbitals;
orbital1++
){
memoryLayout.add({
{(int)kx, (int)ky, (int)orbital0},
{(int)kx, (int)ky, (int)orbital1}
});
}
}
}
}
memoryLayout.generateLinearMap();
Property::SelfEnergy newSelfEnergy(
memoryLayout,
selfEnergy.getLowerMatsubaraEnergyIndex(),
selfEnergy.getUpperMatsubaraEnergyIndex(),
selfEnergy.getFundamentalMatsubaraEnergy()
);
for(unsigned int kx = 0; kx < numMeshPoints[0]; kx++){
for(unsigned int ky = 0; ky < numMeshPoints[1]; ky++){
for(
unsigned int orbital0 = 0;
orbital0 < numOrbitals;
orbital0++
){
for(
unsigned int orbital1 = 0;
orbital1 < numOrbitals;
orbital1++
){
for(
unsigned int n = 0;
n < selfEnergy.getNumMatsubaraEnergies();
n++
){
newSelfEnergy(
{
{
(int)kx,
(int)ky,
(int)orbital0
},
{
(int)kx,
(int)ky,
(int)orbital1
}
},
n
) = selfEnergy(
{
{
(int)kx,
(int)ky
},
{(int)orbital0},
{(int)orbital1}
},
n
);
}
}
}
}
}
selfEnergy = newSelfEnergy;
}
void FLEX::calculateConvergenceParameter(){
const vector<complex<double>> &oldData = oldGreensFunction.getData();
const vector<complex<double>> &newData = greensFunction.getData();
TBTKAssert(
oldData.size() == newData.size(),
"Solver::FLEX::calculateConvergenceParameter()",
"Incompatible Green's function data sizes.",
"This should never happen, contact the developer."
);
switch(norm){
case Norm::Max:
{
double oldMax = 0;
double differenceMax = 0;
for(unsigned int n = 0; n < oldData.size(); n++){
if(abs(oldData[n]) > oldMax)
oldMax = abs(oldData[n]);
if(abs(oldData[n] - newData[n]) > differenceMax)
differenceMax = abs(oldData[n] - newData[n]);
}
convergenceParameter = differenceMax/oldMax;
break;
}
case Norm::L2:
{
double oldL2 = 0;
double differenceL2 = 0;
for(unsigned int n = 0; n < oldData.size(); n++){
oldL2 += pow(abs(oldData[n]), 2);
differenceL2 += pow(abs(oldData[n] - newData[n]), 2);
}
convergenceParameter = differenceL2/oldL2;
break;
}
default:
TBTKExit(
"Solver::FLEX::calculateConvergenceParameter()",
"Unknown norm.",
"This should never happen, contact the developer."
);
}
}
} //End of namespace Solver
} //End of namesapce TBTK
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include <math.h>
#include <string.h>
#include "common_video/libyuv/include/libyuv.h"
#include "gtest/gtest.h"
#include "system_wrappers/interface/tick_util.h"
#include "testsupport/fileutils.h"
namespace webrtc {
int PrintFrame(const uint8_t* frame, int width, int height) {
if (frame == NULL)
return -1;
int k = 0;
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
printf("%d ", frame[k++]);
}
printf(" \n");
}
printf(" \n");
return 0;
}
int PrintFrame(const uint8_t* frame, int width,
int height, const char* str) {
if (frame == NULL)
return -1;
printf("%s %dx%d \n", str, width, height);
const uint8_t* frame_y = frame;
const uint8_t* frame_u = frame_y + width * height;
const uint8_t* frame_v = frame_u + width * height / 4;
int ret = 0;
ret += PrintFrame(frame_y, width, height);
ret += PrintFrame(frame_u, width / 2, height / 2);
ret += PrintFrame(frame_v, width / 2, height / 2);
return ret;
}
void CreateImage(int width, int height,
uint8_t* frame, int offset,
int height_factor, int width_factor) {
if (frame == NULL)
return;
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
*frame = static_cast<uint8_t>((i + offset) * height_factor
+ j * width_factor);
frame++;
}
}
}
class TestLibYuv : public ::testing::Test {
protected:
TestLibYuv();
virtual void SetUp();
virtual void TearDown();
FILE* source_file_;
const int width_;
const int height_;
const int frame_length_;
};
// TODO (mikhal): Use scoped_ptr when handling buffers.
TestLibYuv::TestLibYuv()
: source_file_(NULL),
width_(352),
height_(288),
frame_length_(CalcBufferSize(kI420, 352, 288)) {
}
void TestLibYuv::SetUp() {
const std::string input_file_name = webrtc::test::ProjectRootPath() +
"resources/foreman_cif.yuv";
source_file_ = fopen(input_file_name.c_str(), "rb");
ASSERT_TRUE(source_file_ != NULL) << "Cannot read file: "<<
input_file_name << "\n";
}
void TestLibYuv::TearDown() {
if (source_file_ != NULL) {
ASSERT_EQ(0, fclose(source_file_));
}
source_file_ = NULL;
}
TEST_F(TestLibYuv, ConvertSanityTest) {
// TODO(mikhal)
}
TEST_F(TestLibYuv, ConvertTest) {
// Reading YUV frame - testing on the first frame of the foreman sequence
int j = 0;
std::string output_file_name = webrtc::test::OutputPath() +
"LibYuvTest_conversion.yuv";
FILE* output_file = fopen(output_file_name.c_str(), "wb");
ASSERT_TRUE(output_file != NULL);
double psnr = 0;
uint8_t* orig_buffer = new uint8_t[frame_length_];
EXPECT_GT(fread(orig_buffer, 1, frame_length_, source_file_), 0U);
// printf("\nConvert #%d I420 <-> RGB24\n", j);
uint8_t* res_rgb_buffer2 = new uint8_t[width_ * height_ * 3];
uint8_t* res_i420_buffer = new uint8_t[frame_length_];
EXPECT_EQ(0, ConvertFromI420(orig_buffer, width_, kRGB24, 0,
width_, height_, res_rgb_buffer2));
EXPECT_EQ(0, ConvertToI420(kRGB24, res_rgb_buffer2, 0, 0, width_, height_,
0, width_, height_, width_, kRotateNone,
res_i420_buffer));
fwrite(res_i420_buffer, frame_length_, 1, output_file);
psnr = I420PSNR(orig_buffer, res_i420_buffer, width_, height_);
// Optimization Speed- quality trade-off => 45 dB only (platform dependant).
EXPECT_GT(ceil(psnr), 44);
j++;
delete [] res_rgb_buffer2;
// printf("\nConvert #%d I420 <-> UYVY\n", j);
uint8_t* out_uyvy_buffer = new uint8_t[width_ * height_ * 2];
EXPECT_EQ(0, ConvertFromI420(orig_buffer, width_,
kUYVY, 0, width_, height_, out_uyvy_buffer));
EXPECT_EQ(0, ConvertToI420(kUYVY, out_uyvy_buffer, 0, 0, width_, height_,
0, width_, height_, width_,kRotateNone, res_i420_buffer));
psnr = I420PSNR(orig_buffer, res_i420_buffer, width_, height_);
EXPECT_EQ(48.0, psnr);
fwrite(res_i420_buffer, frame_length_, 1, output_file);
j++;
delete [] out_uyvy_buffer;
// printf("\nConvert #%d I420 <-> I420 \n", j);
uint8_t* out_i420_buffer = new uint8_t[width_ * height_ * 3 / 2 ];
EXPECT_EQ(0, ConvertToI420(kI420, orig_buffer, 0, 0, width_, height_,
0, width_, height_, width_,
kRotateNone, out_i420_buffer));
EXPECT_EQ(0, ConvertFromI420(out_i420_buffer, width_, kI420, 0,
width_, height_, res_i420_buffer));
fwrite(res_i420_buffer, frame_length_, 1, output_file);
psnr = I420PSNR(orig_buffer, res_i420_buffer, width_, height_);
EXPECT_EQ(48.0, psnr);
j++;
delete [] out_i420_buffer;
// printf("\nConvert #%d I420 <-> YV12\n", j);
uint8_t* outYV120Buffer = new uint8_t[frame_length_];
EXPECT_EQ(0, ConvertFromI420(orig_buffer, width_, kYV12, 0,
width_, height_, outYV120Buffer));
EXPECT_EQ(0, ConvertFromYV12(outYV120Buffer, width_,
kI420, 0,
width_, height_,
res_i420_buffer));
fwrite(res_i420_buffer, frame_length_, 1, output_file);
psnr = I420PSNR(orig_buffer, res_i420_buffer, width_, height_);
EXPECT_EQ(48.0, psnr);
j++;
delete [] outYV120Buffer;
// printf("\nConvert #%d I420 <-> YUY2\n", j);
uint8_t* out_yuy2_buffer = new uint8_t[width_ * height_ * 2];
EXPECT_EQ(0, ConvertFromI420(orig_buffer, width_,
kYUY2, 0, width_, height_, out_yuy2_buffer));
EXPECT_EQ(0, ConvertToI420(kYUY2, out_yuy2_buffer, 0, 0, width_, height_,
0, width_, height_, width_,
kRotateNone, res_i420_buffer));
fwrite(res_i420_buffer, frame_length_, 1, output_file);
psnr = I420PSNR(orig_buffer, res_i420_buffer, width_, height_);
EXPECT_EQ(48.0, psnr);
// printf("\nConvert #%d I420 <-> RGB565\n", j);
uint8_t* out_rgb565_buffer = new uint8_t[width_ * height_ * 2];
EXPECT_EQ(0, ConvertFromI420(orig_buffer, width_,
kRGB565, 0, width_, height_, out_rgb565_buffer));
EXPECT_EQ(0, ConvertToI420(kRGB565, out_rgb565_buffer, 0, 0, width_, height_,
0, width_, height_, width_,
kRotateNone, res_i420_buffer));
fwrite(res_i420_buffer, frame_length_, 1, output_file);
psnr = I420PSNR(orig_buffer, res_i420_buffer, width_, height_);
// TODO(leozwang) Investigate the right psnr should be set for I420ToRGB565,
// Another example is I420ToRGB24, the psnr is 44
EXPECT_GT(ceil(psnr), 40);
// printf("\nConvert #%d I420 <-> ARGB8888\n", j);
uint8_t* out_argb8888_buffer = new uint8_t[width_ * height_ * 4];
EXPECT_EQ(0, ConvertFromI420(orig_buffer, width_,
kARGB, 0, width_, height_, out_argb8888_buffer));
EXPECT_EQ(0, ConvertToI420(kARGB, out_argb8888_buffer, 0, 0, width_, height_,
0, width_, height_, width_,
kRotateNone, res_i420_buffer));
fwrite(res_i420_buffer, frame_length_, 1, output_file);
psnr = I420PSNR(orig_buffer, res_i420_buffer, width_, height_);
// TODO(leozwang) Investigate the right psnr should be set for I420ToARGB8888,
EXPECT_GT(ceil(psnr), 45);
ASSERT_EQ(0, fclose(output_file));
delete [] out_argb8888_buffer;
delete [] out_rgb565_buffer;
delete [] out_yuy2_buffer;
delete [] res_i420_buffer;
delete [] orig_buffer;
}
// TODO(holmer): Disabled for now due to crashes on Linux 32 bit. The theory
// is that it crashes due to the fact that the buffers are not 16 bit aligned.
// See http://code.google.com/p/webrtc/issues/detail?id=335 for more info.
TEST_F(TestLibYuv, DISABLED_MirrorTest) {
// TODO (mikhal): Add an automated test to confirm output.
std::string str;
int width = 16;
int height = 8;
int factor_y = 1;
int factor_u = 1;
int factor_v = 1;
int start_buffer_offset = 10;
int length = webrtc::CalcBufferSize(kI420, width, height);
uint8_t* test_frame = new uint8_t[length];
memset(test_frame, 255, length);
// Create input frame
uint8_t* in_frame = test_frame;
uint8_t* in_frame_cb = in_frame + width * height;
uint8_t* in_frame_cr = in_frame_cb + (width * height) / 4;
CreateImage(width, height, in_frame, 10, factor_y, 1); // Y
CreateImage(width / 2, height / 2, in_frame_cb, 100, factor_u, 1); // Cb
CreateImage(width / 2, height / 2, in_frame_cr, 200, factor_v, 1); // Cr
EXPECT_EQ(0, PrintFrame(test_frame, width, height, "InputFrame"));
uint8_t* test_frame2 = new uint8_t[length + start_buffer_offset * 2];
memset(test_frame2, 255, length + start_buffer_offset * 2);
uint8_t* out_frame = test_frame2;
// LeftRight
std::cout << "Test Mirror function: LeftRight" << std::endl;
EXPECT_EQ(0, MirrorI420LeftRight(in_frame, out_frame, width, height));
EXPECT_EQ(0, PrintFrame(test_frame2, width, height, "OutputFrame"));
EXPECT_EQ(0, MirrorI420LeftRight(out_frame, test_frame, width, height));
EXPECT_EQ(0, memcmp(in_frame, test_frame, length));
// UpDown
std::cout << "Test Mirror function: UpDown" << std::endl;
EXPECT_EQ(0, MirrorI420UpDown(in_frame, out_frame, width, height));
EXPECT_EQ(0, PrintFrame(test_frame2, width, height, "OutputFrame"));
EXPECT_EQ(0, MirrorI420UpDown(out_frame, test_frame, width, height));
EXPECT_EQ(0, memcmp(in_frame, test_frame, length));
// TODO(mikhal): Write to a file, and ask to look at the file.
std::cout << "Do the mirrored frames look correct?" << std::endl;
delete [] test_frame;
delete [] test_frame2;
}
} // namespace
<commit_msg>Reduce PSNR because I420ToARGB888 return lowers number on windows<commit_after>/*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include <math.h>
#include <string.h>
#include "common_video/libyuv/include/libyuv.h"
#include "gtest/gtest.h"
#include "system_wrappers/interface/tick_util.h"
#include "testsupport/fileutils.h"
namespace webrtc {
int PrintFrame(const uint8_t* frame, int width, int height) {
if (frame == NULL)
return -1;
int k = 0;
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
printf("%d ", frame[k++]);
}
printf(" \n");
}
printf(" \n");
return 0;
}
int PrintFrame(const uint8_t* frame, int width,
int height, const char* str) {
if (frame == NULL)
return -1;
printf("%s %dx%d \n", str, width, height);
const uint8_t* frame_y = frame;
const uint8_t* frame_u = frame_y + width * height;
const uint8_t* frame_v = frame_u + width * height / 4;
int ret = 0;
ret += PrintFrame(frame_y, width, height);
ret += PrintFrame(frame_u, width / 2, height / 2);
ret += PrintFrame(frame_v, width / 2, height / 2);
return ret;
}
void CreateImage(int width, int height,
uint8_t* frame, int offset,
int height_factor, int width_factor) {
if (frame == NULL)
return;
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
*frame = static_cast<uint8_t>((i + offset) * height_factor
+ j * width_factor);
frame++;
}
}
}
class TestLibYuv : public ::testing::Test {
protected:
TestLibYuv();
virtual void SetUp();
virtual void TearDown();
FILE* source_file_;
const int width_;
const int height_;
const int frame_length_;
};
// TODO (mikhal): Use scoped_ptr when handling buffers.
TestLibYuv::TestLibYuv()
: source_file_(NULL),
width_(352),
height_(288),
frame_length_(CalcBufferSize(kI420, 352, 288)) {
}
void TestLibYuv::SetUp() {
const std::string input_file_name = webrtc::test::ProjectRootPath() +
"resources/foreman_cif.yuv";
source_file_ = fopen(input_file_name.c_str(), "rb");
ASSERT_TRUE(source_file_ != NULL) << "Cannot read file: "<<
input_file_name << "\n";
}
void TestLibYuv::TearDown() {
if (source_file_ != NULL) {
ASSERT_EQ(0, fclose(source_file_));
}
source_file_ = NULL;
}
TEST_F(TestLibYuv, ConvertSanityTest) {
// TODO(mikhal)
}
TEST_F(TestLibYuv, ConvertTest) {
// Reading YUV frame - testing on the first frame of the foreman sequence
int j = 0;
std::string output_file_name = webrtc::test::OutputPath() +
"LibYuvTest_conversion.yuv";
FILE* output_file = fopen(output_file_name.c_str(), "wb");
ASSERT_TRUE(output_file != NULL);
double psnr = 0;
uint8_t* orig_buffer = new uint8_t[frame_length_];
EXPECT_GT(fread(orig_buffer, 1, frame_length_, source_file_), 0U);
// printf("\nConvert #%d I420 <-> RGB24\n", j);
uint8_t* res_rgb_buffer2 = new uint8_t[width_ * height_ * 3];
uint8_t* res_i420_buffer = new uint8_t[frame_length_];
EXPECT_EQ(0, ConvertFromI420(orig_buffer, width_, kRGB24, 0,
width_, height_, res_rgb_buffer2));
EXPECT_EQ(0, ConvertToI420(kRGB24, res_rgb_buffer2, 0, 0, width_, height_,
0, width_, height_, width_, kRotateNone,
res_i420_buffer));
fwrite(res_i420_buffer, frame_length_, 1, output_file);
psnr = I420PSNR(orig_buffer, res_i420_buffer, width_, height_);
// Optimization Speed- quality trade-off => 45 dB only (platform dependant).
EXPECT_GT(ceil(psnr), 44);
j++;
delete [] res_rgb_buffer2;
// printf("\nConvert #%d I420 <-> UYVY\n", j);
uint8_t* out_uyvy_buffer = new uint8_t[width_ * height_ * 2];
EXPECT_EQ(0, ConvertFromI420(orig_buffer, width_,
kUYVY, 0, width_, height_, out_uyvy_buffer));
EXPECT_EQ(0, ConvertToI420(kUYVY, out_uyvy_buffer, 0, 0, width_, height_,
0, width_, height_, width_,kRotateNone, res_i420_buffer));
psnr = I420PSNR(orig_buffer, res_i420_buffer, width_, height_);
EXPECT_EQ(48.0, psnr);
fwrite(res_i420_buffer, frame_length_, 1, output_file);
j++;
delete [] out_uyvy_buffer;
// printf("\nConvert #%d I420 <-> I420 \n", j);
uint8_t* out_i420_buffer = new uint8_t[width_ * height_ * 3 / 2 ];
EXPECT_EQ(0, ConvertToI420(kI420, orig_buffer, 0, 0, width_, height_,
0, width_, height_, width_,
kRotateNone, out_i420_buffer));
EXPECT_EQ(0, ConvertFromI420(out_i420_buffer, width_, kI420, 0,
width_, height_, res_i420_buffer));
fwrite(res_i420_buffer, frame_length_, 1, output_file);
psnr = I420PSNR(orig_buffer, res_i420_buffer, width_, height_);
EXPECT_EQ(48.0, psnr);
j++;
delete [] out_i420_buffer;
// printf("\nConvert #%d I420 <-> YV12\n", j);
uint8_t* outYV120Buffer = new uint8_t[frame_length_];
EXPECT_EQ(0, ConvertFromI420(orig_buffer, width_, kYV12, 0,
width_, height_, outYV120Buffer));
EXPECT_EQ(0, ConvertFromYV12(outYV120Buffer, width_,
kI420, 0,
width_, height_,
res_i420_buffer));
fwrite(res_i420_buffer, frame_length_, 1, output_file);
psnr = I420PSNR(orig_buffer, res_i420_buffer, width_, height_);
EXPECT_EQ(48.0, psnr);
j++;
delete [] outYV120Buffer;
// printf("\nConvert #%d I420 <-> YUY2\n", j);
uint8_t* out_yuy2_buffer = new uint8_t[width_ * height_ * 2];
EXPECT_EQ(0, ConvertFromI420(orig_buffer, width_,
kYUY2, 0, width_, height_, out_yuy2_buffer));
EXPECT_EQ(0, ConvertToI420(kYUY2, out_yuy2_buffer, 0, 0, width_, height_,
0, width_, height_, width_,
kRotateNone, res_i420_buffer));
fwrite(res_i420_buffer, frame_length_, 1, output_file);
psnr = I420PSNR(orig_buffer, res_i420_buffer, width_, height_);
EXPECT_EQ(48.0, psnr);
// printf("\nConvert #%d I420 <-> RGB565\n", j);
uint8_t* out_rgb565_buffer = new uint8_t[width_ * height_ * 2];
EXPECT_EQ(0, ConvertFromI420(orig_buffer, width_,
kRGB565, 0, width_, height_, out_rgb565_buffer));
EXPECT_EQ(0, ConvertToI420(kRGB565, out_rgb565_buffer, 0, 0, width_, height_,
0, width_, height_, width_,
kRotateNone, res_i420_buffer));
fwrite(res_i420_buffer, frame_length_, 1, output_file);
psnr = I420PSNR(orig_buffer, res_i420_buffer, width_, height_);
// TODO(leozwang) Investigate the right psnr should be set for I420ToRGB565,
// Another example is I420ToRGB24, the psnr is 44
EXPECT_GT(ceil(psnr), 40);
// printf("\nConvert #%d I420 <-> ARGB8888\n", j);
uint8_t* out_argb8888_buffer = new uint8_t[width_ * height_ * 4];
EXPECT_EQ(0, ConvertFromI420(orig_buffer, width_,
kARGB, 0, width_, height_, out_argb8888_buffer));
EXPECT_EQ(0, ConvertToI420(kARGB, out_argb8888_buffer, 0, 0, width_, height_,
0, width_, height_, width_,
kRotateNone, res_i420_buffer));
fwrite(res_i420_buffer, frame_length_, 1, output_file);
psnr = I420PSNR(orig_buffer, res_i420_buffer, width_, height_);
// TODO(leozwang) Investigate the right psnr should be set for I420ToARGB8888,
EXPECT_GT(ceil(psnr), 42);
ASSERT_EQ(0, fclose(output_file));
delete [] out_argb8888_buffer;
delete [] out_rgb565_buffer;
delete [] out_yuy2_buffer;
delete [] res_i420_buffer;
delete [] orig_buffer;
}
// TODO(holmer): Disabled for now due to crashes on Linux 32 bit. The theory
// is that it crashes due to the fact that the buffers are not 16 bit aligned.
// See http://code.google.com/p/webrtc/issues/detail?id=335 for more info.
TEST_F(TestLibYuv, DISABLED_MirrorTest) {
// TODO (mikhal): Add an automated test to confirm output.
std::string str;
int width = 16;
int height = 8;
int factor_y = 1;
int factor_u = 1;
int factor_v = 1;
int start_buffer_offset = 10;
int length = webrtc::CalcBufferSize(kI420, width, height);
uint8_t* test_frame = new uint8_t[length];
memset(test_frame, 255, length);
// Create input frame
uint8_t* in_frame = test_frame;
uint8_t* in_frame_cb = in_frame + width * height;
uint8_t* in_frame_cr = in_frame_cb + (width * height) / 4;
CreateImage(width, height, in_frame, 10, factor_y, 1); // Y
CreateImage(width / 2, height / 2, in_frame_cb, 100, factor_u, 1); // Cb
CreateImage(width / 2, height / 2, in_frame_cr, 200, factor_v, 1); // Cr
EXPECT_EQ(0, PrintFrame(test_frame, width, height, "InputFrame"));
uint8_t* test_frame2 = new uint8_t[length + start_buffer_offset * 2];
memset(test_frame2, 255, length + start_buffer_offset * 2);
uint8_t* out_frame = test_frame2;
// LeftRight
std::cout << "Test Mirror function: LeftRight" << std::endl;
EXPECT_EQ(0, MirrorI420LeftRight(in_frame, out_frame, width, height));
EXPECT_EQ(0, PrintFrame(test_frame2, width, height, "OutputFrame"));
EXPECT_EQ(0, MirrorI420LeftRight(out_frame, test_frame, width, height));
EXPECT_EQ(0, memcmp(in_frame, test_frame, length));
// UpDown
std::cout << "Test Mirror function: UpDown" << std::endl;
EXPECT_EQ(0, MirrorI420UpDown(in_frame, out_frame, width, height));
EXPECT_EQ(0, PrintFrame(test_frame2, width, height, "OutputFrame"));
EXPECT_EQ(0, MirrorI420UpDown(out_frame, test_frame, width, height));
EXPECT_EQ(0, memcmp(in_frame, test_frame, length));
// TODO(mikhal): Write to a file, and ask to look at the file.
std::cout << "Do the mirrored frames look correct?" << std::endl;
delete [] test_frame;
delete [] test_frame2;
}
} // namespace
<|endoftext|>
|
<commit_before>/*
* delegator.hpp
*/
// Copyright Shaun Harker 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <set>
#include <deque>
#include <unistd.h>
/***************************************
* USER INTERFACE *
***************************************/
namespace delegator {
void Start ( void ) {
/* Initialize the MPI communications */
int argc; char * * argv;
MPI_Init(&argc, &argv);
}
template < class Process >
int Run ( void ) {
int argc = 0; char * * argv = NULL;
return Run < Process > ( argc, argv );
} /* Run<> */
void Stop ( void ) {
/* Finalize the MPI communications. */
MPI_Finalize();
}
template < class Process >
int Run ( int argc, char * argv [] ) {
typedef Coordinator_Worker_Scheme Scheme;
return Run < Process, Scheme, Communicator > ( argc, argv );
} /* Start<> */
// Run (more advanced interface)
template < class Process, class Scheme, class Comm >
int Run ( int argc, char * argv [] ) {
/* Create Process, Scheme, and Communicator */
Comm my_communicator;
Scheme my_scheme ( argc, argv );
Process my_process;
// Run Scheme until it finishes
my_communicator . initialize ();
my_scheme . run ( & my_process, & my_communicator );
my_communicator . finalize ();
return 0;
} /* Run<> */
}
<commit_msg>added missing inline qualifiers<commit_after>/*
* delegator.hpp
*/
// Copyright Shaun Harker 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <set>
#include <deque>
#include <unistd.h>
/***************************************
* USER INTERFACE *
***************************************/
namespace delegator {
inline void Start ( void ) {
/* Initialize the MPI communications */
int argc; char * * argv;
MPI_Init(&argc, &argv);
}
template < class Process >
int Run ( void ) {
int argc = 0; char * * argv = NULL;
return Run < Process > ( argc, argv );
} /* Run<> */
inline void Stop ( void ) {
/* Finalize the MPI communications. */
MPI_Finalize();
}
template < class Process >
int Run ( int argc, char * argv [] ) {
typedef Coordinator_Worker_Scheme Scheme;
return Run < Process, Scheme, Communicator > ( argc, argv );
} /* Start<> */
// Run (more advanced interface)
template < class Process, class Scheme, class Comm >
int Run ( int argc, char * argv [] ) {
/* Create Process, Scheme, and Communicator */
Comm my_communicator;
Scheme my_scheme ( argc, argv );
Process my_process;
// Run Scheme until it finishes
my_communicator . initialize ();
my_scheme . run ( & my_process, & my_communicator );
my_communicator . finalize ();
return 0;
} /* Run<> */
}
<|endoftext|>
|
<commit_before>#include "./OGL.h"
namespace nme
{
bool gHasNPO2Extension = false;
bool NonPO2Supported(bool inNotRepeating)
{
static bool tried = false;
//OpenGL 2.0 introduced non PO2 as standard, in 2004 - safe to assume it exists on PC
#ifdef FORCE_NON_PO2
return true;
#endif
if (!tried)
{
tried = true;
const char* extensions = (char*) glGetString(GL_EXTENSIONS);
gHasNPO2Extension = strstr(extensions, "ARB_texture_non_power_of_two") != 0;
if (!gHasNPO2Extension)
{
gHasNPO2Extension = strstr(extensions, "GL_APPLE_texture_2D_limited_npot") != 0;
}
//printf("Has NPO2 Extension : %d\n", gHasNPO2Extension);
}
return gHasNPO2Extension && inNotRepeating;
}
class OGLTexture : public Texture
{
public:
OGLTexture(Surface *inSurface,unsigned int inFlags)
{
mPixelWidth = inSurface->Width();
mPixelHeight = inSurface->Height();
mDirtyRect = Rect(0,0);
mContextVersion = gTextureContextVersion;
bool non_po2 = NonPO2Supported(true && (inFlags & SURF_FLAGS_NOT_REPEAT_IF_NON_PO2));
//printf("Using non-power-of-2 texture %d\n",non_po2);
int w = non_po2 ? mPixelWidth : UpToPower2(mPixelWidth);
int h = non_po2 ? mPixelHeight : UpToPower2(mPixelHeight);
mCanRepeat = IsPower2(w) && IsPower2(h);
//__android_log_print(ANDROID_LOG_ERROR, "NME", "NewTexure %d %d", w, h);
mTextureWidth = w;
mTextureHeight = h;
bool copy_required = w!=mPixelWidth || h!=mPixelHeight;
Surface *load = inSurface;
if (copy_required)
{
int pw = inSurface->Format()==pfAlpha ? 1 : 4;
load = new SimpleSurface(w,h,inSurface->Format());
load->IncRef();
for(int y=0;y<mPixelHeight;y++)
{
const uint8 *src = inSurface->Row(y);
uint8 *dest= (uint8 *)load->Row(y);
memcpy(dest,src,mPixelWidth*pw);
if (w>mPixelWidth)
memcpy(dest+mPixelWidth*pw,dest+(mPixelWidth-1)*pw,pw);
}
if (h!=mPixelHeight)
{
memcpy((void *)load->Row(mPixelHeight),load->Row(mPixelHeight-1),
(mPixelWidth + (w!=mPixelWidth))*pw);
}
}
#ifdef IPHONE
uint8 *dest;
if ( inSurface->Format() == pfARGB4444 ) {
int size = mTextureWidth * mTextureHeight;
dest = (uint8 *)malloc( size * 2 );
const uint8 *src = (uint8 *)load->Row( 0 );
for ( int c = 0; c < size; c++ ) {
uint8 srca = src[ c * 4 ] / 16;
uint8 srcb = src[ c * 4 + 1 ] / 16;
uint8 srcc = src[ c * 4 + 2 ] / 16;
uint8 srcd = src[ c * 4 + 3 ] / 16;
dest[ c * 2 ] = ( srcc << 4 | srcd );
dest[ c * 2 + 1 ] = ( srca << 4 | srcb );
}
} else if ( inSurface->Format() == pfRGB565 ) {
int size = mTextureWidth * mTextureHeight;
dest = (uint8 *)malloc( size * 2 );
const uint8 *src = (uint8 *)load->Row( 0 );
for ( int c = 0; c < size; c++ ) {
uint8 srca = src[ c * 4 ] / 8;
uint8 srcb = src[ c * 4 + 1 ] / 4;
uint8 srcc = src[ c * 4 + 2 ] / 8;
//pack into 565
unsigned int combined = (srca << 11) | (srcb << 5) | (srcc << 0);
//write to the buffer
dest[ c * 2 +1] = combined >> 8;
dest[ c * 2 ] = combined & 0x00FF;
}
}
#endif
glGenTextures(1, &mTextureID);
// __android_log_print(ANDROID_LOG_ERROR, "NME", "CreateTexture %d (%dx%d)",
// mTextureID, mPixelWidth, mPixelHeight);
glBindTexture(GL_TEXTURE_2D,mTextureID);
mRepeat = mCanRepeat;
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, mRepeat ? GL_REPEAT : GL_CLAMP_TO_EDGE );
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, mRepeat ? GL_REPEAT : GL_CLAMP_TO_EDGE );
PixelFormat fmt = load->Format();
GLuint src_format = fmt==pfAlpha ? GL_ALPHA : GL_RGBA;
GLuint store_format = src_format;
#ifdef IPHONE
if ( inSurface->Format() == pfARGB4444 ) {
glTexImage2D(GL_TEXTURE_2D, 0, store_format, w, h, 0, src_format,
GL_UNSIGNED_SHORT_4_4_4_4, dest );
free( dest );
} else if ( inSurface->Format() == pfRGB565 ) {
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, w, h, 0, GL_RGB,
GL_UNSIGNED_SHORT_5_6_5, dest );
free( dest );
} else
#endif
glTexImage2D(GL_TEXTURE_2D, 0, store_format, w, h, 0, src_format,
GL_UNSIGNED_BYTE, load->Row(0) );
mSmooth = true;
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
#ifdef GPH
glTexEnvx(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
#else
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
#endif
if (copy_required)
{
load->DecRef();
}
//int err = glGetError();
//printf ("GL texture error: %i", err);
}
~OGLTexture()
{
if (mTextureID && mContextVersion==gTextureContextVersion)
{
//__android_log_print(ANDROID_LOG_ERROR, "NME", "DeleteTexture %d (%dx%d)",
//mTextureID, mPixelWidth, mPixelHeight);
glDeleteTextures(1,&mTextureID);
}
}
void Bind(class Surface *inSurface,int inSlot)
{
glBindTexture(GL_TEXTURE_2D,mTextureID);
if (gTextureContextVersion!=mContextVersion)
{
mContextVersion = gTextureContextVersion;
mDirtyRect = Rect(inSurface->Width(),inSurface->Height());
}
if (mDirtyRect.HasPixels())
{
//__android_log_print(ANDROID_LOG_INFO, "NME", "UpdateDirtyRect! %d %d",
//mPixelWidth, mPixelHeight);
PixelFormat fmt = inSurface->Format();
GLuint src_format = fmt==pfAlpha ? GL_ALPHA : GL_RGBA;
glGetError();
const uint8 *p0 =
inSurface->Row(mDirtyRect.y) + mDirtyRect.x*inSurface->BytesPP();
#if defined(NME_GLES)
for(int y=0;y<mDirtyRect.h;y++)
{
glTexSubImage2D(GL_TEXTURE_2D, 0, mDirtyRect.x,mDirtyRect.y + y,
mDirtyRect.w, 1,
src_format, GL_UNSIGNED_BYTE,
p0 + y*inSurface->GetStride());
}
#else
glPixelStorei(GL_UNPACK_ROW_LENGTH, inSurface->Width());
glTexSubImage2D(GL_TEXTURE_2D, 0, mDirtyRect.x,mDirtyRect.y,
mDirtyRect.w, mDirtyRect.h,
src_format, GL_UNSIGNED_BYTE,
p0);
glPixelStorei(GL_UNPACK_ROW_LENGTH,0);
#endif
int err = glGetError();
mDirtyRect = Rect();
}
}
void BindFlags(bool inRepeat,bool inSmooth)
{
if (!mCanRepeat) inRepeat = false;
if (mRepeat!=inRepeat)
{
mRepeat = inRepeat;
if (mRepeat)
{
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT );
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT );
}
else
{
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );
}
}
if (mSmooth!=inSmooth)
{
mSmooth = inSmooth;
if (mSmooth)
{
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
}
else
{
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
}
}
}
UserPoint PixelToTex(const UserPoint &inPixels)
{
return UserPoint(inPixels.x/mTextureWidth, inPixels.y/mTextureHeight);
}
UserPoint TexToPaddedTex(const UserPoint &inTex)
{
return UserPoint(inTex.x*mPixelWidth/mTextureWidth, inTex.y*mPixelHeight/mTextureHeight);
}
GLuint mTextureID;
bool mCanRepeat;
bool mRepeat;
bool mSmooth;
int mPixelWidth;
int mPixelHeight;
int mTextureWidth;
int mTextureHeight;
};
Texture *OGLCreateTexture(Surface *inSurface,unsigned int inFlags)
{
return new OGLTexture(inSurface,inFlags);
}
} // end namespace nme
<commit_msg>When ARB_texture_non_power_of_two is supported, allow non-PO2 for repeating fills as well<commit_after>#include "./OGL.h"
namespace nme
{
bool gFullNPO2Support = false;
bool gPartialNPO2Support = false;
bool NonPO2Supported(bool inNotRepeating)
{
static bool tried = false;
//OpenGL 2.0 introduced non PO2 as standard, in 2004 - safe to assume it exists on PC
#ifdef FORCE_NON_PO2
return true;
#endif
if (!tried)
{
tried = true;
const char* extensions = (char*) glGetString(GL_EXTENSIONS);
gFullNPO2Support = strstr(extensions, "ARB_texture_non_power_of_two") != 0;
if (!gFullNPO2Support)
{
gPartialNPO2Support = strstr(extensions, "GL_APPLE_texture_2D_limited_npot") != 0;
}
//printf("Full non-PO2 support : %d\n", gFullNPO2Support);
//printf("Partial non-PO2 support : %d\n", gPartialNPO2Support);
}
return (gFullNPO2Support || (gPartialNPO2Support && inNotRepeating));
}
class OGLTexture : public Texture
{
public:
OGLTexture(Surface *inSurface,unsigned int inFlags)
{
mPixelWidth = inSurface->Width();
mPixelHeight = inSurface->Height();
mDirtyRect = Rect(0,0);
mContextVersion = gTextureContextVersion;
bool non_po2 = NonPO2Supported(true && (inFlags & SURF_FLAGS_NOT_REPEAT_IF_NON_PO2));
//printf("Using non-power-of-2 texture %d\n",non_po2);
int w = non_po2 ? mPixelWidth : UpToPower2(mPixelWidth);
int h = non_po2 ? mPixelHeight : UpToPower2(mPixelHeight);
mCanRepeat = IsPower2(w) && IsPower2(h);
//__android_log_print(ANDROID_LOG_ERROR, "NME", "NewTexure %d %d", w, h);
mTextureWidth = w;
mTextureHeight = h;
bool copy_required = w!=mPixelWidth || h!=mPixelHeight;
Surface *load = inSurface;
if (copy_required)
{
int pw = inSurface->Format()==pfAlpha ? 1 : 4;
load = new SimpleSurface(w,h,inSurface->Format());
load->IncRef();
for(int y=0;y<mPixelHeight;y++)
{
const uint8 *src = inSurface->Row(y);
uint8 *dest= (uint8 *)load->Row(y);
memcpy(dest,src,mPixelWidth*pw);
if (w>mPixelWidth)
memcpy(dest+mPixelWidth*pw,dest+(mPixelWidth-1)*pw,pw);
}
if (h!=mPixelHeight)
{
memcpy((void *)load->Row(mPixelHeight),load->Row(mPixelHeight-1),
(mPixelWidth + (w!=mPixelWidth))*pw);
}
}
#ifdef IPHONE
uint8 *dest;
if ( inSurface->Format() == pfARGB4444 ) {
int size = mTextureWidth * mTextureHeight;
dest = (uint8 *)malloc( size * 2 );
const uint8 *src = (uint8 *)load->Row( 0 );
for ( int c = 0; c < size; c++ ) {
uint8 srca = src[ c * 4 ] / 16;
uint8 srcb = src[ c * 4 + 1 ] / 16;
uint8 srcc = src[ c * 4 + 2 ] / 16;
uint8 srcd = src[ c * 4 + 3 ] / 16;
dest[ c * 2 ] = ( srcc << 4 | srcd );
dest[ c * 2 + 1 ] = ( srca << 4 | srcb );
}
} else if ( inSurface->Format() == pfRGB565 ) {
int size = mTextureWidth * mTextureHeight;
dest = (uint8 *)malloc( size * 2 );
const uint8 *src = (uint8 *)load->Row( 0 );
for ( int c = 0; c < size; c++ ) {
uint8 srca = src[ c * 4 ] / 8;
uint8 srcb = src[ c * 4 + 1 ] / 4;
uint8 srcc = src[ c * 4 + 2 ] / 8;
//pack into 565
unsigned int combined = (srca << 11) | (srcb << 5) | (srcc << 0);
//write to the buffer
dest[ c * 2 +1] = combined >> 8;
dest[ c * 2 ] = combined & 0x00FF;
}
}
#endif
glGenTextures(1, &mTextureID);
// __android_log_print(ANDROID_LOG_ERROR, "NME", "CreateTexture %d (%dx%d)",
// mTextureID, mPixelWidth, mPixelHeight);
glBindTexture(GL_TEXTURE_2D,mTextureID);
mRepeat = mCanRepeat;
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, mRepeat ? GL_REPEAT : GL_CLAMP_TO_EDGE );
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, mRepeat ? GL_REPEAT : GL_CLAMP_TO_EDGE );
PixelFormat fmt = load->Format();
GLuint src_format = fmt==pfAlpha ? GL_ALPHA : GL_RGBA;
GLuint store_format = src_format;
#ifdef IPHONE
if ( inSurface->Format() == pfARGB4444 ) {
glTexImage2D(GL_TEXTURE_2D, 0, store_format, w, h, 0, src_format,
GL_UNSIGNED_SHORT_4_4_4_4, dest );
free( dest );
} else if ( inSurface->Format() == pfRGB565 ) {
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, w, h, 0, GL_RGB,
GL_UNSIGNED_SHORT_5_6_5, dest );
free( dest );
} else
#endif
glTexImage2D(GL_TEXTURE_2D, 0, store_format, w, h, 0, src_format,
GL_UNSIGNED_BYTE, load->Row(0) );
mSmooth = true;
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
#ifdef GPH
glTexEnvx(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
#else
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
#endif
if (copy_required)
{
load->DecRef();
}
//int err = glGetError();
//printf ("GL texture error: %i", err);
}
~OGLTexture()
{
if (mTextureID && mContextVersion==gTextureContextVersion)
{
//__android_log_print(ANDROID_LOG_ERROR, "NME", "DeleteTexture %d (%dx%d)",
//mTextureID, mPixelWidth, mPixelHeight);
glDeleteTextures(1,&mTextureID);
}
}
void Bind(class Surface *inSurface,int inSlot)
{
glBindTexture(GL_TEXTURE_2D,mTextureID);
if (gTextureContextVersion!=mContextVersion)
{
mContextVersion = gTextureContextVersion;
mDirtyRect = Rect(inSurface->Width(),inSurface->Height());
}
if (mDirtyRect.HasPixels())
{
//__android_log_print(ANDROID_LOG_INFO, "NME", "UpdateDirtyRect! %d %d",
//mPixelWidth, mPixelHeight);
PixelFormat fmt = inSurface->Format();
GLuint src_format = fmt==pfAlpha ? GL_ALPHA : GL_RGBA;
glGetError();
const uint8 *p0 =
inSurface->Row(mDirtyRect.y) + mDirtyRect.x*inSurface->BytesPP();
#if defined(NME_GLES)
for(int y=0;y<mDirtyRect.h;y++)
{
glTexSubImage2D(GL_TEXTURE_2D, 0, mDirtyRect.x,mDirtyRect.y + y,
mDirtyRect.w, 1,
src_format, GL_UNSIGNED_BYTE,
p0 + y*inSurface->GetStride());
}
#else
glPixelStorei(GL_UNPACK_ROW_LENGTH, inSurface->Width());
glTexSubImage2D(GL_TEXTURE_2D, 0, mDirtyRect.x,mDirtyRect.y,
mDirtyRect.w, mDirtyRect.h,
src_format, GL_UNSIGNED_BYTE,
p0);
glPixelStorei(GL_UNPACK_ROW_LENGTH,0);
#endif
int err = glGetError();
mDirtyRect = Rect();
}
}
void BindFlags(bool inRepeat,bool inSmooth)
{
if (!mCanRepeat) inRepeat = false;
if (mRepeat!=inRepeat)
{
mRepeat = inRepeat;
if (mRepeat)
{
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT );
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT );
}
else
{
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );
}
}
if (mSmooth!=inSmooth)
{
mSmooth = inSmooth;
if (mSmooth)
{
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
}
else
{
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
}
}
}
UserPoint PixelToTex(const UserPoint &inPixels)
{
return UserPoint(inPixels.x/mTextureWidth, inPixels.y/mTextureHeight);
}
UserPoint TexToPaddedTex(const UserPoint &inTex)
{
return UserPoint(inTex.x*mPixelWidth/mTextureWidth, inTex.y*mPixelHeight/mTextureHeight);
}
GLuint mTextureID;
bool mCanRepeat;
bool mRepeat;
bool mSmooth;
int mPixelWidth;
int mPixelHeight;
int mTextureWidth;
int mTextureHeight;
};
Texture *OGLCreateTexture(Surface *inSurface,unsigned int inFlags)
{
return new OGLTexture(inSurface,inFlags);
}
} // end namespace nme
<|endoftext|>
|
<commit_before>#include <algorithm>
#include <vector>
// Algorithm to be tested
unsigned corresponding_pow(unsigned num)
{
for ( ; (num & (num -1)) != 0 ; num &= num -1) {}
return num;
}
std::vector<unsigned> build_grays(unsigned num)
{
if (num == 0)
{
return {};
}
std::vector<unsigned> codes(1);
codes.reserve(num);
// Need to preallocate necessary memory in order to prevent from:
// If the new size() is greater than capacity() then all iterators and references (including the past-the-end iterator) are invalidated. Otherwise only the past-the-end iterator is invalidated.
unsigned corresponding = corresponding_pow(num);
unsigned more = 1;
while (codes.size() < corresponding)
{
std::transform(codes.rbegin(), codes.rend()
, std::back_inserter(codes)
, [more](auto prev){ return prev + more; });
more <<= 1;
}
std::transform(codes.rbegin(), std::next(codes.rbegin(), num - corresponding)
, std::back_inserter(codes)
, [more](auto prev){ return prev + more; });
return codes;
}
#include "tests.hpp"
<commit_msg>[visual studio] Fix bit-manipulation/gray-code<commit_after>#include <algorithm>
#include <iterator>
#include <vector>
// Algorithm to be tested
unsigned corresponding_pow(unsigned num)
{
for ( ; (num & (num -1)) != 0 ; num &= num -1) {}
return num;
}
std::vector<unsigned> build_grays(unsigned num)
{
if (num == 0)
{
return {};
}
std::vector<unsigned> codes(1);
codes.reserve(num);
// Need to preallocate necessary memory in order to prevent from:
// If the new size() is greater than capacity() then all iterators and references (including the past-the-end iterator) are invalidated. Otherwise only the past-the-end iterator is invalidated.
unsigned corresponding = corresponding_pow(num);
unsigned more = 1;
while (codes.size() < corresponding)
{
std::transform(codes.rbegin(), codes.rend()
, std::back_inserter(codes)
, [more](auto prev){ return prev + more; });
more <<= 1;
}
std::transform(codes.rbegin(), std::next(codes.rbegin(), num - corresponding)
, std::back_inserter(codes)
, [more](auto prev){ return prev + more; });
return codes;
}
#include "tests.hpp"
<|endoftext|>
|
<commit_before>/** \copyright
* Copyright (c) 2018, Balazs Racz
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* \file HwInit.cxx
*
* This file represents the hardware initialization for the STM32F091RC Nucelo
* board with the DevKit IO board plugged in.
*
* @author Balazs Racz
* @date April 18, 2018
*/
#include <new>
#include <cstdint>
#include "stm32f0xx_hal_rcc.h"
#include "stm32f0xx_hal_flash.h"
#include "stm32f0xx_hal_gpio.h"
#include "stm32f0xx_hal_gpio_ex.h"
#include "stm32f0xx_hal_dma.h"
#include "stm32f0xx_hal_tim.h"
#include "stm32f0xx_hal.h"
#include "os/OS.hxx"
#include "Stm32Uart.hxx"
#include "Stm32Can.hxx"
#include "Stm32SPI.hxx"
#include "Stm32EEPROMEmulation.hxx"
#include "Stm32PWM.hxx"
#include "hardware.hxx"
/** override stdin */
const char *STDIN_DEVICE = "/dev/ser0";
/** override stdout */
const char *STDOUT_DEVICE = "/dev/ser0";
/** override stderr */
const char *STDERR_DEVICE = "/dev/ser0";
/** UART 0 serial driver instance */
static Stm32Uart uart0("/dev/ser0", USART2, USART2_IRQn);
/** CAN 0 CAN driver instance */
static Stm32Can can0("/dev/can0");
/** EEPROM emulation driver. The file size might be made bigger. */
static Stm32EEPROMEmulation eeprom0("/dev/eeprom", 1900);
/** How many bytes of flash should hold the entire dataset. Must be an integer
* multiple of the minimum erase length (which is the flash page length, for
* the STM32F0 it is 2 kbytes). The file size maximum is half this value. */
const size_t EEPROMEmulation::SECTOR_SIZE = 4096;
Stm32PWMGroup servo_timer(TIM3,
/*prescaler=*/ (servoPwmCountPerMs * 6 + 65535) / 65536,
/*period_counts=*/ servoPwmCountPerMs * 6);
extern PWM* const servo_channels[];
/// The order of these channels follows the schematic arrangement of MCU pins
/// to logical servo ports.
PWM * const servo_channels[4] = { //
Stm32PWMGroup::get_channel(&servo_timer, 4),
Stm32PWMGroup::get_channel(&servo_timer, 2),
Stm32PWMGroup::get_channel(&servo_timer, 3),
Stm32PWMGroup::get_channel(&servo_timer, 1)};
/// Recursive mutex for SPI1 peripheral.
OSMutex spi1_lock(true);
static void noop_cs() {
}
/// SPI1 driver for io-board peripherals
static Stm32SPI spi1_0(
"/dev/spi1.ioboard", SPI1, SPI1_IRQn, &noop_cs, &noop_cs, &spi1_lock);
static void spi1_ext_cs_assert() {
EXT_CS_Pin::set(false);
}
static void spi1_ext_cs_deassert() {
EXT_CS_Pin::set(true);
}
/// SPI1 driver for the expansion port.
static Stm32SPI spi1_1("/dev/spi1.ext", SPI1, SPI1_IRQn, &spi1_ext_cs_assert,
&spi1_ext_cs_deassert, &spi1_lock);
/// SPI2 driver for the onboard input ports.
static Stm32SPI spi2("/dev/spi2", SPI2, SPI2_IRQn, &noop_cs, &noop_cs, nullptr);
extern "C" {
/** Blink LED */
uint32_t blinker_pattern = 0;
static uint32_t rest_pattern = 0;
void hw_set_to_safe(void)
{
}
void reboot()
{
NVIC_SystemReset();
}
void resetblink(uint32_t pattern)
{
blinker_pattern = pattern;
rest_pattern = pattern ? 1 : 0;
BLINKER_RAW_Pin::set(pattern ? true : false);
/* make a timer event trigger immediately */
}
void setblink(uint32_t pattern)
{
resetblink(pattern);
}
const uint8_t AHBPrescTable[16] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 6, 7, 8, 9};
const uint8_t APBPrescTable[8] = {0, 0, 0, 0, 1, 2, 3, 4};
void timer14_interrupt_handler(void)
{
//
// Clear the timer interrupt.
//
TIM14->SR = ~TIM_IT_UPDATE;
// Set output LED.
BLINKER_RAW_Pin::set(rest_pattern & 1);
// Shift and maybe reset pattern.
rest_pattern >>= 1;
if (!rest_pattern)
{
rest_pattern = blinker_pattern;
}
}
void diewith(uint32_t pattern)
{
// vPortClearInterruptMask(0x20);
asm("cpsie i\n");
resetblink(pattern);
while (1)
;
}
/** Setup the system clock */
static void clock_setup(void)
{
/* reset clock configuration to default state */
RCC->CR = RCC_CR_HSITRIM_4 | RCC_CR_HSION;
while (!(RCC->CR & RCC_CR_HSIRDY))
;
#define USE_EXTERNAL_8_MHz_CLOCK_SOURCE 1
/* configure PLL: 8 MHz * 6 = 48 MHz */
#if USE_EXTERNAL_8_MHz_CLOCK_SOURCE
RCC->CR |= RCC_CR_HSEON | RCC_CR_HSEBYP;
while (!(RCC->CR & RCC_CR_HSERDY))
;
RCC->CFGR = RCC_CFGR_PLLMUL6 | RCC_CFGR_PLLSRC_HSE_PREDIV | RCC_CFGR_SW_HSE;
while (!((RCC->CFGR & RCC_CFGR_SWS) == RCC_CFGR_SWS_HSE))
;
#else
RCC->CFGR = RCC_CFGR_PLLMUL6 | RCC_CFGR_PLLSRC_HSI_PREDIV | RCC_CFGR_SW_HSI;
while (!((RCC->CFGR & RCC_CFGR_SWS) == RCC_CFGR_SWS_HSI))
;
#endif
/* enable PLL */
RCC->CR |= RCC_CR_PLLON;
while (!(RCC->CR & RCC_CR_PLLRDY))
;
/* set PLL as system clock */
RCC->CFGR = (RCC->CFGR & (~RCC_CFGR_SW)) | RCC_CFGR_SW_PLL;
while (!((RCC->CFGR & RCC_CFGR_SWS) == RCC_CFGR_SWS_PLL))
;
}
/** Initialize the processor hardware.
*
* Don't depend on runtime-initialized global variables
* in this function; these will be initialized after
* hw_preinit in startup.c.
*/
void hw_preinit(void)
{
/* Globally disables interrupts until the FreeRTOS scheduler is up. */
asm("cpsid i\n");
/* these FLASH settings enable opertion at 48 MHz */
__HAL_FLASH_PREFETCH_BUFFER_ENABLE();
__HAL_FLASH_SET_LATENCY(FLASH_LATENCY_1);
/* setup the system clock */
clock_setup();
/* enable peripheral clocks */
__HAL_RCC_GPIOA_CLK_ENABLE();
__HAL_RCC_GPIOB_CLK_ENABLE();
__HAL_RCC_GPIOC_CLK_ENABLE();
__HAL_RCC_GPIOD_CLK_ENABLE();
__HAL_RCC_GPIOF_CLK_ENABLE();
__HAL_RCC_USART2_CLK_ENABLE();
__HAL_RCC_CAN1_CLK_ENABLE();
__HAL_RCC_TIM14_CLK_ENABLE();
__HAL_RCC_TIM3_CLK_ENABLE();
/* setup pinmux */
GPIO_InitTypeDef gpio_init;
memset(&gpio_init, 0, sizeof(gpio_init));
/* USART2 pinmux on PA2 and PA3 */
gpio_init.Mode = GPIO_MODE_AF_PP;
gpio_init.Pull = GPIO_PULLUP;
gpio_init.Speed = GPIO_SPEED_FREQ_HIGH;
gpio_init.Alternate = GPIO_AF1_USART2;
gpio_init.Pin = GPIO_PIN_2;
HAL_GPIO_Init(GPIOA, &gpio_init);
gpio_init.Pin = GPIO_PIN_3;
HAL_GPIO_Init(GPIOA, &gpio_init);
/* CAN pinmux on PB8 and PB9 */
gpio_init.Mode = GPIO_MODE_AF_PP;
// Disables pull-ups because this is a 5V tolerant pin.
gpio_init.Pull = GPIO_NOPULL;
gpio_init.Speed = GPIO_SPEED_FREQ_HIGH;
gpio_init.Alternate = GPIO_AF4_CAN;
gpio_init.Pin = GPIO_PIN_8;
HAL_GPIO_Init(GPIOB, &gpio_init);
gpio_init.Pin = GPIO_PIN_9;
HAL_GPIO_Init(GPIOB, &gpio_init);
/* SPI1 pinmux on PB3, PB4, and PB5 */
gpio_init.Mode = GPIO_MODE_AF_PP;
gpio_init.Pull = GPIO_NOPULL;
gpio_init.Speed = GPIO_SPEED_FREQ_HIGH;
gpio_init.Alternate = GPIO_AF0_SPI1;
gpio_init.Pin = GPIO_PIN_3;
HAL_GPIO_Init(GPIOB, &gpio_init);
gpio_init.Pin = GPIO_PIN_4;
HAL_GPIO_Init(GPIOB, &gpio_init);
gpio_init.Pin = GPIO_PIN_5;
HAL_GPIO_Init(GPIOB, &gpio_init);
/* SPI2 pinmux on PC2 (MISO2), and PB10 (SCK) */
gpio_init.Mode = GPIO_MODE_AF_PP;
gpio_init.Pull = GPIO_NOPULL;
gpio_init.Speed = GPIO_SPEED_FREQ_HIGH;
gpio_init.Alternate = GPIO_AF5_SPI2;
gpio_init.Pin = GPIO_PIN_10;
HAL_GPIO_Init(GPIOB, &gpio_init);
gpio_init.Alternate = GPIO_AF1_SPI2;
gpio_init.Pin = GPIO_PIN_2;
HAL_GPIO_Init(GPIOC, &gpio_init);
GpioInit::hw_init();
// Switches over servo timer pins to timer mode.
// PC6-7-8-9
gpio_init.Mode = GPIO_MODE_AF_PP;
gpio_init.Pull = GPIO_NOPULL;
gpio_init.Speed = GPIO_SPEED_FREQ_HIGH;
gpio_init.Alternate = GPIO_AF0_TIM3;
gpio_init.Pin = GPIO_PIN_6;
HAL_GPIO_Init(GPIOC, &gpio_init);
gpio_init.Pin = GPIO_PIN_7;
HAL_GPIO_Init(GPIOC, &gpio_init);
gpio_init.Pin = GPIO_PIN_8;
HAL_GPIO_Init(GPIOC, &gpio_init);
gpio_init.Pin = GPIO_PIN_9;
HAL_GPIO_Init(GPIOC, &gpio_init);
/* Initializes the blinker timer. */
TIM_HandleTypeDef TimHandle;
memset(&TimHandle, 0, sizeof(TimHandle));
TimHandle.Instance = TIM14;
TimHandle.Init.Period = configCPU_CLOCK_HZ / 10000 / 8;
TimHandle.Init.Prescaler = 10000;
TimHandle.Init.ClockDivision = 0;
TimHandle.Init.CounterMode = TIM_COUNTERMODE_UP;
TimHandle.Init.RepetitionCounter = 0;
if (HAL_TIM_Base_Init(&TimHandle) != HAL_OK)
{
/* Initialization Error */
HASSERT(0);
}
if (HAL_TIM_Base_Start_IT(&TimHandle) != HAL_OK)
{
/* Starting Error */
HASSERT(0);
}
__HAL_DBGMCU_FREEZE_TIM14();
NVIC_SetPriority(TIM14_IRQn, 0);
NVIC_EnableIRQ(TIM14_IRQn);
}
}
<commit_msg>Fix missing declaration on HSEValue. (#396)<commit_after>/** \copyright
* Copyright (c) 2018, Balazs Racz
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* \file HwInit.cxx
*
* This file represents the hardware initialization for the STM32F091RC Nucelo
* board with the DevKit IO board plugged in.
*
* @author Balazs Racz
* @date April 18, 2018
*/
#include <new>
#include <cstdint>
#include "stm32f0xx_hal_rcc.h"
#include "stm32f0xx_hal_flash.h"
#include "stm32f0xx_hal_gpio.h"
#include "stm32f0xx_hal_gpio_ex.h"
#include "stm32f0xx_hal_dma.h"
#include "stm32f0xx_hal_tim.h"
#include "stm32f0xx_hal.h"
#include "os/OS.hxx"
#include "Stm32Uart.hxx"
#include "Stm32Can.hxx"
#include "Stm32SPI.hxx"
#include "Stm32EEPROMEmulation.hxx"
#include "Stm32PWM.hxx"
#include "hardware.hxx"
/** override stdin */
const char *STDIN_DEVICE = "/dev/ser0";
/** override stdout */
const char *STDOUT_DEVICE = "/dev/ser0";
/** override stderr */
const char *STDERR_DEVICE = "/dev/ser0";
/** UART 0 serial driver instance */
static Stm32Uart uart0("/dev/ser0", USART2, USART2_IRQn);
/** CAN 0 CAN driver instance */
static Stm32Can can0("/dev/can0");
/** EEPROM emulation driver. The file size might be made bigger. */
static Stm32EEPROMEmulation eeprom0("/dev/eeprom", 1900);
/** How many bytes of flash should hold the entire dataset. Must be an integer
* multiple of the minimum erase length (which is the flash page length, for
* the STM32F0 it is 2 kbytes). The file size maximum is half this value. */
const size_t EEPROMEmulation::SECTOR_SIZE = 4096;
Stm32PWMGroup servo_timer(TIM3,
/*prescaler=*/ (servoPwmCountPerMs * 6 + 65535) / 65536,
/*period_counts=*/ servoPwmCountPerMs * 6);
extern PWM* const servo_channels[];
/// The order of these channels follows the schematic arrangement of MCU pins
/// to logical servo ports.
PWM * const servo_channels[4] = { //
Stm32PWMGroup::get_channel(&servo_timer, 4),
Stm32PWMGroup::get_channel(&servo_timer, 2),
Stm32PWMGroup::get_channel(&servo_timer, 3),
Stm32PWMGroup::get_channel(&servo_timer, 1)};
/// Recursive mutex for SPI1 peripheral.
OSMutex spi1_lock(true);
static void noop_cs() {
}
/// SPI1 driver for io-board peripherals
static Stm32SPI spi1_0(
"/dev/spi1.ioboard", SPI1, SPI1_IRQn, &noop_cs, &noop_cs, &spi1_lock);
static void spi1_ext_cs_assert() {
EXT_CS_Pin::set(false);
}
static void spi1_ext_cs_deassert() {
EXT_CS_Pin::set(true);
}
/// SPI1 driver for the expansion port.
static Stm32SPI spi1_1("/dev/spi1.ext", SPI1, SPI1_IRQn, &spi1_ext_cs_assert,
&spi1_ext_cs_deassert, &spi1_lock);
/// SPI2 driver for the onboard input ports.
static Stm32SPI spi2("/dev/spi2", SPI2, SPI2_IRQn, &noop_cs, &noop_cs, nullptr);
extern "C" {
/** Blink LED */
uint32_t blinker_pattern = 0;
static uint32_t rest_pattern = 0;
void hw_set_to_safe(void)
{
}
void reboot()
{
NVIC_SystemReset();
}
void resetblink(uint32_t pattern)
{
blinker_pattern = pattern;
rest_pattern = pattern ? 1 : 0;
BLINKER_RAW_Pin::set(pattern ? true : false);
/* make a timer event trigger immediately */
}
void setblink(uint32_t pattern)
{
resetblink(pattern);
}
const uint8_t AHBPrescTable[16] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 6, 7, 8, 9};
const uint8_t APBPrescTable[8] = {0, 0, 0, 0, 1, 2, 3, 4};
const uint32_t HSEValue = 8000000;
void timer14_interrupt_handler(void)
{
//
// Clear the timer interrupt.
//
TIM14->SR = ~TIM_IT_UPDATE;
// Set output LED.
BLINKER_RAW_Pin::set(rest_pattern & 1);
// Shift and maybe reset pattern.
rest_pattern >>= 1;
if (!rest_pattern)
{
rest_pattern = blinker_pattern;
}
}
void diewith(uint32_t pattern)
{
// vPortClearInterruptMask(0x20);
asm("cpsie i\n");
resetblink(pattern);
while (1)
;
}
/** Setup the system clock */
static void clock_setup(void)
{
/* reset clock configuration to default state */
RCC->CR = RCC_CR_HSITRIM_4 | RCC_CR_HSION;
while (!(RCC->CR & RCC_CR_HSIRDY))
;
#define USE_EXTERNAL_8_MHz_CLOCK_SOURCE 1
/* configure PLL: 8 MHz * 6 = 48 MHz */
#if USE_EXTERNAL_8_MHz_CLOCK_SOURCE
RCC->CR |= RCC_CR_HSEON | RCC_CR_HSEBYP;
while (!(RCC->CR & RCC_CR_HSERDY))
;
RCC->CFGR = RCC_CFGR_PLLMUL6 | RCC_CFGR_PLLSRC_HSE_PREDIV | RCC_CFGR_SW_HSE;
while (!((RCC->CFGR & RCC_CFGR_SWS) == RCC_CFGR_SWS_HSE))
;
#else
RCC->CFGR = RCC_CFGR_PLLMUL6 | RCC_CFGR_PLLSRC_HSI_PREDIV | RCC_CFGR_SW_HSI;
while (!((RCC->CFGR & RCC_CFGR_SWS) == RCC_CFGR_SWS_HSI))
;
#endif
/* enable PLL */
RCC->CR |= RCC_CR_PLLON;
while (!(RCC->CR & RCC_CR_PLLRDY))
;
/* set PLL as system clock */
RCC->CFGR = (RCC->CFGR & (~RCC_CFGR_SW)) | RCC_CFGR_SW_PLL;
while (!((RCC->CFGR & RCC_CFGR_SWS) == RCC_CFGR_SWS_PLL))
;
}
/** Initialize the processor hardware.
*
* Don't depend on runtime-initialized global variables
* in this function; these will be initialized after
* hw_preinit in startup.c.
*/
void hw_preinit(void)
{
/* Globally disables interrupts until the FreeRTOS scheduler is up. */
asm("cpsid i\n");
/* these FLASH settings enable opertion at 48 MHz */
__HAL_FLASH_PREFETCH_BUFFER_ENABLE();
__HAL_FLASH_SET_LATENCY(FLASH_LATENCY_1);
/* setup the system clock */
clock_setup();
/* enable peripheral clocks */
__HAL_RCC_GPIOA_CLK_ENABLE();
__HAL_RCC_GPIOB_CLK_ENABLE();
__HAL_RCC_GPIOC_CLK_ENABLE();
__HAL_RCC_GPIOD_CLK_ENABLE();
__HAL_RCC_GPIOF_CLK_ENABLE();
__HAL_RCC_USART2_CLK_ENABLE();
__HAL_RCC_CAN1_CLK_ENABLE();
__HAL_RCC_TIM14_CLK_ENABLE();
__HAL_RCC_TIM3_CLK_ENABLE();
/* setup pinmux */
GPIO_InitTypeDef gpio_init;
memset(&gpio_init, 0, sizeof(gpio_init));
/* USART2 pinmux on PA2 and PA3 */
gpio_init.Mode = GPIO_MODE_AF_PP;
gpio_init.Pull = GPIO_PULLUP;
gpio_init.Speed = GPIO_SPEED_FREQ_HIGH;
gpio_init.Alternate = GPIO_AF1_USART2;
gpio_init.Pin = GPIO_PIN_2;
HAL_GPIO_Init(GPIOA, &gpio_init);
gpio_init.Pin = GPIO_PIN_3;
HAL_GPIO_Init(GPIOA, &gpio_init);
/* CAN pinmux on PB8 and PB9 */
gpio_init.Mode = GPIO_MODE_AF_PP;
// Disables pull-ups because this is a 5V tolerant pin.
gpio_init.Pull = GPIO_NOPULL;
gpio_init.Speed = GPIO_SPEED_FREQ_HIGH;
gpio_init.Alternate = GPIO_AF4_CAN;
gpio_init.Pin = GPIO_PIN_8;
HAL_GPIO_Init(GPIOB, &gpio_init);
gpio_init.Pin = GPIO_PIN_9;
HAL_GPIO_Init(GPIOB, &gpio_init);
/* SPI1 pinmux on PB3, PB4, and PB5 */
gpio_init.Mode = GPIO_MODE_AF_PP;
gpio_init.Pull = GPIO_NOPULL;
gpio_init.Speed = GPIO_SPEED_FREQ_HIGH;
gpio_init.Alternate = GPIO_AF0_SPI1;
gpio_init.Pin = GPIO_PIN_3;
HAL_GPIO_Init(GPIOB, &gpio_init);
gpio_init.Pin = GPIO_PIN_4;
HAL_GPIO_Init(GPIOB, &gpio_init);
gpio_init.Pin = GPIO_PIN_5;
HAL_GPIO_Init(GPIOB, &gpio_init);
/* SPI2 pinmux on PC2 (MISO2), and PB10 (SCK) */
gpio_init.Mode = GPIO_MODE_AF_PP;
gpio_init.Pull = GPIO_NOPULL;
gpio_init.Speed = GPIO_SPEED_FREQ_HIGH;
gpio_init.Alternate = GPIO_AF5_SPI2;
gpio_init.Pin = GPIO_PIN_10;
HAL_GPIO_Init(GPIOB, &gpio_init);
gpio_init.Alternate = GPIO_AF1_SPI2;
gpio_init.Pin = GPIO_PIN_2;
HAL_GPIO_Init(GPIOC, &gpio_init);
GpioInit::hw_init();
// Switches over servo timer pins to timer mode.
// PC6-7-8-9
gpio_init.Mode = GPIO_MODE_AF_PP;
gpio_init.Pull = GPIO_NOPULL;
gpio_init.Speed = GPIO_SPEED_FREQ_HIGH;
gpio_init.Alternate = GPIO_AF0_TIM3;
gpio_init.Pin = GPIO_PIN_6;
HAL_GPIO_Init(GPIOC, &gpio_init);
gpio_init.Pin = GPIO_PIN_7;
HAL_GPIO_Init(GPIOC, &gpio_init);
gpio_init.Pin = GPIO_PIN_8;
HAL_GPIO_Init(GPIOC, &gpio_init);
gpio_init.Pin = GPIO_PIN_9;
HAL_GPIO_Init(GPIOC, &gpio_init);
/* Initializes the blinker timer. */
TIM_HandleTypeDef TimHandle;
memset(&TimHandle, 0, sizeof(TimHandle));
TimHandle.Instance = TIM14;
TimHandle.Init.Period = configCPU_CLOCK_HZ / 10000 / 8;
TimHandle.Init.Prescaler = 10000;
TimHandle.Init.ClockDivision = 0;
TimHandle.Init.CounterMode = TIM_COUNTERMODE_UP;
TimHandle.Init.RepetitionCounter = 0;
if (HAL_TIM_Base_Init(&TimHandle) != HAL_OK)
{
/* Initialization Error */
HASSERT(0);
}
if (HAL_TIM_Base_Start_IT(&TimHandle) != HAL_OK)
{
/* Starting Error */
HASSERT(0);
}
__HAL_DBGMCU_FREEZE_TIM14();
NVIC_SetPriority(TIM14_IRQn, 0);
NVIC_EnableIRQ(TIM14_IRQn);
}
}
<|endoftext|>
|
<commit_before>/*
* Copyright 2021 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "gm/gm.h"
#include "include/core/SkCanvas.h"
#include "include/core/SkColor.h"
#include "include/core/SkFont.h"
#include "include/core/SkFontMetrics.h"
#include "include/core/SkGraphics.h"
#include "include/core/SkPaint.h"
#include "include/core/SkRefCnt.h"
#include "include/core/SkScalar.h"
#include "include/core/SkSize.h"
#include "include/core/SkString.h"
#include "include/core/SkTypeface.h"
#include "tools/Resources.h"
#include "tools/ToolUtils.h"
#include <string.h>
#include <initializer_list>
namespace skiagm {
namespace {
const SkScalar kTextSizes[] = {12, 18, 30, 120};
const char kTestFontName[] = "fonts/test_glyphs-glyf_colr_1.ttf";
const char kTestFontNameVariable[] = "fonts/test_glyphs-glyf_colr_1_variable.ttf";
const SkScalar xWidth = 1200;
const SkScalar xTranslate = 200;
}
class ColrV1GM : public GM {
public:
ColrV1GM(const char* testName,
SkSpan<const uint32_t> codepoints,
SkScalar skewX,
SkScalar rotateDeg,
std::initializer_list<SkFontArguments::VariationPosition::Coordinate>
specifiedVariations)
: fTestName(testName)
, fCodepoints(codepoints)
, fSkewX(skewX)
, fRotateDeg(rotateDeg) {
fVariationPosition.coordinateCount = specifiedVariations.size();
fCoordinates = std::make_unique<SkFontArguments::VariationPosition::Coordinate[]>(
specifiedVariations.size());
for (size_t i = 0; i < specifiedVariations.size(); ++i) {
fCoordinates[i] = std::data(specifiedVariations)[i];
}
fVariationPosition.coordinates = fCoordinates.get();
}
protected:
void onOnceBeforeDraw() override {
if (fVariationPosition.coordinateCount) {
fTypeface = MakeResourceAsTypeface(kTestFontNameVariable);
} else {
fTypeface = MakeResourceAsTypeface(kTestFontName);
}
fVariationSliders = ToolUtils::VariationSliders(fTypeface.get(), fVariationPosition);
}
SkString onShortName() override {
SkASSERT(!fTestName.isEmpty());
SkString gm_name = SkStringPrintf("colrv1_%s", fTestName.c_str());
if (fSkewX) {
gm_name.append(SkStringPrintf("_skew_%.2f", fSkewX));
}
if (fRotateDeg) {
gm_name.append(SkStringPrintf("_rotate_%.2f", fRotateDeg));
}
for (int i = 0; i < fVariationPosition.coordinateCount; ++i) {
SkString tagName = ToolUtils::VariationSliders::tagToString(
fVariationPosition.coordinates[i].axis);
gm_name.append(SkStringPrintf(
"_%s_%.2f", tagName.c_str(), fVariationPosition.coordinates[i].value));
}
return gm_name;
}
bool onGetControls(SkMetaData* controls) override {
return fVariationSliders.writeControls(controls);
}
void onSetControls(const SkMetaData& controls) override {
return fVariationSliders.readControls(controls);
}
SkISize onISize() override {
return SkISize::Make(xWidth, xWidth);
}
sk_sp<SkTypeface> makeVariedTypeface() {
if (!fTypeface) {
return nullptr;
}
SkSpan<const SkFontArguments::VariationPosition::Coordinate> coords =
fVariationSliders.getCoordinates();
SkFontArguments::VariationPosition varPos = {coords.data(),
static_cast<int>(coords.size())};
SkFontArguments args;
args.setVariationDesignPosition(varPos);
return fTypeface->makeClone(args);
}
DrawResult onDraw(SkCanvas* canvas, SkString* errorMsg) override {
canvas->drawColor(SK_ColorWHITE);
SkPaint paint;
canvas->translate(xTranslate, 20);
if (!fTypeface) {
*errorMsg = "Did not recognize COLR v1 font format.";
return DrawResult::kSkip;
}
canvas->rotate(fRotateDeg);
canvas->skew(fSkewX, 0);
SkFont font(makeVariedTypeface());
SkFontMetrics metrics;
SkScalar y = 0;
std::vector<SkColor> paint_colors = {
SK_ColorBLACK, SK_ColorGREEN, SK_ColorRED, SK_ColorBLUE};
auto paint_color_iterator = paint_colors.begin();
for (SkScalar textSize : kTextSizes) {
font.setSize(textSize);
font.getMetrics(&metrics);
SkScalar y_shift = -(metrics.fAscent + metrics.fDescent + metrics.fLeading) * 1.2;
y += y_shift;
paint.setColor(*paint_color_iterator);
int x = 0;
// Perform simple line breaking to fit more glyphs into the GM canvas.
for (size_t i = 0; i < fCodepoints.size(); ++i) {
canvas->drawSimpleText(&fCodepoints[i],
sizeof(uint32_t),
SkTextEncoding::kUTF32,
x,
y,
font,
paint);
SkScalar glyphAdvance = font.measureText(
&fCodepoints[i], sizeof(uint32_t), SkTextEncoding::kUTF32, nullptr);
if (x + glyphAdvance < xWidth - xTranslate) {
x += glyphAdvance + glyphAdvance * 0.05f;
} else {
y += y_shift;
x = 0;
}
}
paint_color_iterator++;
}
return DrawResult::kOk;
}
private:
using INHERITED = GM;
SkString fTestName;
sk_sp<SkTypeface> fTypeface;
SkSpan<const uint32_t> fCodepoints;
SkScalar fSkewX;
SkScalar fRotateDeg;
std::unique_ptr<SkFontArguments::VariationPosition::Coordinate[]> fCoordinates;
SkFontArguments::VariationPosition fVariationPosition;
ToolUtils::VariationSliders fVariationSliders;
};
// Generated using test glyphs generator script from https://github.com/googlefonts/color-fonts:
// $ python3 config/test_glyphs-glyf_colr_1.py -vvv --generate-descriptions fonts/
// Regenerate descriptions and paste the generated arrays here when updating the test font.
namespace ColrV1TestDefinitions {
const uint32_t gradient_stops_repeat[] = {0xf0100, 0xf0101, 0xf0102, 0xf0103};
const uint32_t sweep_varsweep[] = {0xf0200, 0xf0201, 0xf0202, 0xf0203, 0xf0204, 0xf0205,
0xf0206, 0xf0207, 0xf0208, 0xf0209, 0xf020a, 0xf020b,
0xf020c, 0xf020d, 0xf020e, 0xf020f, 0xf0210, 0xf0211,
0xf0212, 0xf0213, 0xf0214, 0xf0215, 0xf0216, 0xf0217};
const uint32_t paint_scale[] = {0xf0300, 0xf0301, 0xf0302, 0xf0303, 0xf0304, 0xf0305};
const uint32_t extend_mode[] = {0xf0500, 0xf0501, 0xf0502, 0xf0503, 0xf0504, 0xf0505};
const uint32_t paint_rotate[] = {0xf0600, 0xf0601, 0xf0602, 0xf0603};
const uint32_t paint_skew[] = {0xf0700, 0xf0701, 0xf0702, 0xf0703, 0xf0704, 0xf0705};
const uint32_t paint_transform[] = {0xf0800, 0xf0801, 0xf0802, 0xf0803};
const uint32_t paint_translate[] = {0xf0900, 0xf0901, 0xf0902, 0xf0903, 0xf0904, 0xf0905, 0xf0906};
const uint32_t composite_mode[] = {0xf0a00, 0xf0a01, 0xf0a02, 0xf0a03, 0xf0a04, 0xf0a05, 0xf0a06,
0xf0a07, 0xf0a08, 0xf0a09, 0xf0a0a, 0xf0a0b, 0xf0a0c, 0xf0a0d,
0xf0a0e, 0xf0a0f, 0xf0a10, 0xf0a11, 0xf0a12, 0xf0a13, 0xf0a14,
0xf0a15, 0xf0a16, 0xf0a17, 0xf0a18, 0xf0a19, 0xf0a1a, 0xf0a1b};
const uint32_t foreground_color[] = {
0xf0b00, 0xf0b01, 0xf0b02, 0xf0b03, 0xf0b04, 0xf0b05, 0xf0b06, 0xf0b07};
const uint32_t clipbox[] = {0xf0c00, 0xf0c01, 0xf0c02, 0xf0c03, 0xf0c04};
const uint32_t gradient_p2_skewed[] = {0xf0d00};
const uint32_t variable_alpha[] = {0xf1000};
}; // namespace ColrV1TestDefinitions
namespace {
std::unique_ptr<ColrV1GM> F(
const char* name,
SkSpan<const uint32_t> codepoints,
SkScalar skewX,
SkScalar rotateDeg,
std::initializer_list<SkFontArguments::VariationPosition::Coordinate> variations)
{
return std::make_unique<ColrV1GM>(name, codepoints, skewX, rotateDeg, variations);
}
SkFourByteTag constexpr operator "" _t(const char* tagName, size_t size) {
SkASSERT(size == 4);
return SkSetFourByteTag(tagName[0], tagName[1], tagName[2], tagName[3]);
}
}
#define C(TEST_CATEGORY) #TEST_CATEGORY, ColrV1TestDefinitions::TEST_CATEGORY
DEF_GM(return F(C(clipbox), 0.0f, 0.0f, {}))
DEF_GM(return F(C(clipbox), 0.0f, 0.0f, {{"CLIO"_t, 200}}))
DEF_GM(return F(C(composite_mode), 0.0f, 0.0f, {}))
DEF_GM(return F(C(composite_mode), -0.5f, 0.0f, {}))
DEF_GM(return F(C(composite_mode), -0.5f, 20.0f, {}))
DEF_GM(return F(C(composite_mode), 0.0f, 20.0f, {}))
DEF_GM(return F(C(extend_mode), 0.0f, 0.0f, {}))
DEF_GM(return F(C(extend_mode), -0.5f, 0.0f, {}))
DEF_GM(return F(C(extend_mode), -0.5f, 20.0f, {}))
DEF_GM(return F(C(extend_mode), 0.0f, 20.0f, {}))
DEF_GM(return F(C(foreground_color), 0.0f, 0.0f, {}))
DEF_GM(return F(C(gradient_p2_skewed), 0.0f, 0.0f, {}))
DEF_GM(return F(C(gradient_stops_repeat), 0.0f, 0.0f, {}))
DEF_GM(return F(C(gradient_stops_repeat), -0.5f, 0.0f, {}))
DEF_GM(return F(C(gradient_stops_repeat), -0.5f, 20.0f, {}))
DEF_GM(return F(C(gradient_stops_repeat), 0.0f, 20.0f, {}))
DEF_GM(return F(C(paint_rotate), 0.0f, 0.0f, {}))
DEF_GM(return F(C(paint_scale), 0.0f, 0.0f, {}))
DEF_GM(return F(C(paint_skew), 0.0f, 0.0f, {}))
DEF_GM(return F(C(paint_transform), 0.0f, 0.0f, {}))
DEF_GM(return F(C(paint_translate), 0.0f, 0.0f, {}))
DEF_GM(return F(C(sweep_varsweep), 0.0f, 0.0f, {}))
DEF_GM(return F(C(sweep_varsweep), -0.5f, 0.0f, {}))
DEF_GM(return F(C(sweep_varsweep), -0.5f, 20.0f, {}))
DEF_GM(return F(C(sweep_varsweep), 0.0f, 20.0f, {}))
DEF_GM(return F(C(variable_alpha), 0.0f, 0.0f, {}))
} // namespace skiagm
<commit_msg>Define a set of variable COLRv1 variations tests<commit_after>/*
* Copyright 2021 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "gm/gm.h"
#include "include/core/SkCanvas.h"
#include "include/core/SkColor.h"
#include "include/core/SkFont.h"
#include "include/core/SkFontMetrics.h"
#include "include/core/SkGraphics.h"
#include "include/core/SkPaint.h"
#include "include/core/SkRefCnt.h"
#include "include/core/SkScalar.h"
#include "include/core/SkSize.h"
#include "include/core/SkString.h"
#include "include/core/SkTypeface.h"
#include "tools/Resources.h"
#include "tools/ToolUtils.h"
#include <string.h>
#include <initializer_list>
namespace skiagm {
namespace {
const SkScalar kTextSizes[] = {12, 18, 30, 120};
const char kTestFontName[] = "fonts/test_glyphs-glyf_colr_1.ttf";
const char kTestFontNameVariable[] = "fonts/test_glyphs-glyf_colr_1_variable.ttf";
const SkScalar xWidth = 1200;
const SkScalar xTranslate = 200;
}
class ColrV1GM : public GM {
public:
ColrV1GM(const char* testName,
SkSpan<const uint32_t> codepoints,
SkScalar skewX,
SkScalar rotateDeg,
std::initializer_list<SkFontArguments::VariationPosition::Coordinate>
specifiedVariations)
: fTestName(testName)
, fCodepoints(codepoints)
, fSkewX(skewX)
, fRotateDeg(rotateDeg) {
fVariationPosition.coordinateCount = specifiedVariations.size();
fCoordinates = std::make_unique<SkFontArguments::VariationPosition::Coordinate[]>(
specifiedVariations.size());
for (size_t i = 0; i < specifiedVariations.size(); ++i) {
fCoordinates[i] = std::data(specifiedVariations)[i];
}
fVariationPosition.coordinates = fCoordinates.get();
}
protected:
void onOnceBeforeDraw() override {
if (fVariationPosition.coordinateCount) {
fTypeface = MakeResourceAsTypeface(kTestFontNameVariable);
} else {
fTypeface = MakeResourceAsTypeface(kTestFontName);
}
fVariationSliders = ToolUtils::VariationSliders(fTypeface.get(), fVariationPosition);
}
SkString onShortName() override {
SkASSERT(!fTestName.isEmpty());
SkString gm_name = SkStringPrintf("colrv1_%s", fTestName.c_str());
if (fSkewX) {
gm_name.append(SkStringPrintf("_skew_%.2f", fSkewX));
}
if (fRotateDeg) {
gm_name.append(SkStringPrintf("_rotate_%.2f", fRotateDeg));
}
for (int i = 0; i < fVariationPosition.coordinateCount; ++i) {
SkString tagName = ToolUtils::VariationSliders::tagToString(
fVariationPosition.coordinates[i].axis);
gm_name.append(SkStringPrintf(
"_%s_%.2f", tagName.c_str(), fVariationPosition.coordinates[i].value));
}
return gm_name;
}
bool onGetControls(SkMetaData* controls) override {
return fVariationSliders.writeControls(controls);
}
void onSetControls(const SkMetaData& controls) override {
return fVariationSliders.readControls(controls);
}
SkISize onISize() override {
return SkISize::Make(xWidth, xWidth);
}
sk_sp<SkTypeface> makeVariedTypeface() {
if (!fTypeface) {
return nullptr;
}
SkSpan<const SkFontArguments::VariationPosition::Coordinate> coords =
fVariationSliders.getCoordinates();
SkFontArguments::VariationPosition varPos = {coords.data(),
static_cast<int>(coords.size())};
SkFontArguments args;
args.setVariationDesignPosition(varPos);
return fTypeface->makeClone(args);
}
DrawResult onDraw(SkCanvas* canvas, SkString* errorMsg) override {
canvas->drawColor(SK_ColorWHITE);
SkPaint paint;
canvas->translate(xTranslate, 20);
if (!fTypeface) {
*errorMsg = "Did not recognize COLR v1 font format.";
return DrawResult::kSkip;
}
canvas->rotate(fRotateDeg);
canvas->skew(fSkewX, 0);
SkFont font(makeVariedTypeface());
SkFontMetrics metrics;
SkScalar y = 0;
std::vector<SkColor> paint_colors = {
SK_ColorBLACK, SK_ColorGREEN, SK_ColorRED, SK_ColorBLUE};
auto paint_color_iterator = paint_colors.begin();
for (SkScalar textSize : kTextSizes) {
font.setSize(textSize);
font.getMetrics(&metrics);
SkScalar y_shift = -(metrics.fAscent + metrics.fDescent + metrics.fLeading) * 1.2;
y += y_shift;
paint.setColor(*paint_color_iterator);
int x = 0;
// Perform simple line breaking to fit more glyphs into the GM canvas.
for (size_t i = 0; i < fCodepoints.size(); ++i) {
canvas->drawSimpleText(&fCodepoints[i],
sizeof(uint32_t),
SkTextEncoding::kUTF32,
x,
y,
font,
paint);
SkScalar glyphAdvance = font.measureText(
&fCodepoints[i], sizeof(uint32_t), SkTextEncoding::kUTF32, nullptr);
if (x + glyphAdvance < xWidth - xTranslate) {
x += glyphAdvance + glyphAdvance * 0.05f;
} else {
y += y_shift;
x = 0;
}
}
paint_color_iterator++;
}
return DrawResult::kOk;
}
private:
using INHERITED = GM;
SkString fTestName;
sk_sp<SkTypeface> fTypeface;
SkSpan<const uint32_t> fCodepoints;
SkScalar fSkewX;
SkScalar fRotateDeg;
std::unique_ptr<SkFontArguments::VariationPosition::Coordinate[]> fCoordinates;
SkFontArguments::VariationPosition fVariationPosition;
ToolUtils::VariationSliders fVariationSliders;
};
// Generated using test glyphs generator script from https://github.com/googlefonts/color-fonts:
// $ python3 config/test_glyphs-glyf_colr_1.py -vvv --generate-descriptions fonts/
// Regenerate descriptions and paste the generated arrays here when updating the test font.
namespace ColrV1TestDefinitions {
const uint32_t gradient_stops_repeat[] = {0xf0100, 0xf0101, 0xf0102, 0xf0103};
const uint32_t sweep_varsweep[] = {0xf0200, 0xf0201, 0xf0202, 0xf0203, 0xf0204, 0xf0205,
0xf0206, 0xf0207, 0xf0208, 0xf0209, 0xf020a, 0xf020b,
0xf020c, 0xf020d, 0xf020e, 0xf020f, 0xf0210, 0xf0211,
0xf0212, 0xf0213, 0xf0214, 0xf0215, 0xf0216, 0xf0217};
const uint32_t paint_scale[] = {0xf0300, 0xf0301, 0xf0302, 0xf0303, 0xf0304, 0xf0305};
const uint32_t extend_mode[] = {0xf0500, 0xf0501, 0xf0502, 0xf0503, 0xf0504, 0xf0505};
const uint32_t paint_rotate[] = {0xf0600, 0xf0601, 0xf0602, 0xf0603};
const uint32_t paint_skew[] = {0xf0700, 0xf0701, 0xf0702, 0xf0703, 0xf0704, 0xf0705};
const uint32_t paint_transform[] = {0xf0800, 0xf0801, 0xf0802, 0xf0803};
const uint32_t paint_translate[] = {0xf0900, 0xf0901, 0xf0902, 0xf0903, 0xf0904, 0xf0905, 0xf0906};
const uint32_t composite_mode[] = {0xf0a00, 0xf0a01, 0xf0a02, 0xf0a03, 0xf0a04, 0xf0a05, 0xf0a06,
0xf0a07, 0xf0a08, 0xf0a09, 0xf0a0a, 0xf0a0b, 0xf0a0c, 0xf0a0d,
0xf0a0e, 0xf0a0f, 0xf0a10, 0xf0a11, 0xf0a12, 0xf0a13, 0xf0a14,
0xf0a15, 0xf0a16, 0xf0a17, 0xf0a18, 0xf0a19, 0xf0a1a, 0xf0a1b};
const uint32_t foreground_color[] = {
0xf0b00, 0xf0b01, 0xf0b02, 0xf0b03, 0xf0b04, 0xf0b05, 0xf0b06, 0xf0b07};
const uint32_t clipbox[] = {0xf0c00, 0xf0c01, 0xf0c02, 0xf0c03, 0xf0c04};
const uint32_t gradient_p2_skewed[] = {0xf0d00};
const uint32_t variable_alpha[] = {0xf1000};
}; // namespace ColrV1TestDefinitions
namespace {
std::unique_ptr<ColrV1GM> F(
const char* name,
SkSpan<const uint32_t> codepoints,
SkScalar skewX,
SkScalar rotateDeg,
std::initializer_list<SkFontArguments::VariationPosition::Coordinate> variations)
{
return std::make_unique<ColrV1GM>(name, codepoints, skewX, rotateDeg, variations);
}
SkFourByteTag constexpr operator "" _t(const char* tagName, size_t size) {
SkASSERT(size == 4);
return SkSetFourByteTag(tagName[0], tagName[1], tagName[2], tagName[3]);
}
}
#define C(TEST_CATEGORY) #TEST_CATEGORY, ColrV1TestDefinitions::TEST_CATEGORY
DEF_GM(return F(C(clipbox), 0.0f, 0.0f, {}))
DEF_GM(return F(C(clipbox), 0.0f, 0.0f, {{"CLIO"_t, 200.f}}))
DEF_GM(return F(C(composite_mode), 0.0f, 0.0f, {}))
DEF_GM(return F(C(composite_mode), -0.5f, 0.0f, {}))
DEF_GM(return F(C(composite_mode), -0.5f, 20.0f, {}))
DEF_GM(return F(C(composite_mode), 0.0f, 20.0f, {}))
DEF_GM(return F(C(extend_mode), 0.0f, 0.0f, {}))
DEF_GM(return F(C(extend_mode), -0.5f, 0.0f, {}))
DEF_GM(return F(C(extend_mode), -0.5f, 20.0f, {}))
DEF_GM(return F(C(extend_mode), 0.0f, 20.0f, {}))
DEF_GM(return F(C(extend_mode), 0.0f, 0.0f, {{"COL2"_t, -0.3f}}))
DEF_GM(return F(C(extend_mode), 0.0f, 0.0f, {{"GRR0"_t, 430.f}, {"GRR1"_t, 40.f}}))
DEF_GM(return F(C(foreground_color), 0.0f, 0.0f, {}))
DEF_GM(return F(C(gradient_p2_skewed), 0.0f, 0.0f, {}))
DEF_GM(return F(C(gradient_stops_repeat), 0.0f, 0.0f, {}))
DEF_GM(return F(C(gradient_stops_repeat), -0.5f, 0.0f, {}))
DEF_GM(return F(C(gradient_stops_repeat), -0.5f, 20.0f, {}))
DEF_GM(return F(C(gradient_stops_repeat), 0.0f, 20.0f, {}))
DEF_GM(return F(C(paint_rotate), 0.0f, 0.0f, {}))
DEF_GM(return F(C(paint_rotate), 0.0f, 0.0f, {{"ROTA"_t, 40.f}}))
DEF_GM(return F(C(paint_rotate), 0.0f, 0.0f, {{"ROTX"_t, -250.f}, {"ROTY"_t, -250.f}}))
DEF_GM(return F(C(paint_scale), 0.0f, 0.0f, {}))
DEF_GM(return F(C(paint_scale), 0.0f, 0.0f, {{"SCOX"_t, 200.f}, {"SCOY"_t, 200.f}}))
DEF_GM(return F(C(paint_scale), 0.0f, 0.0f, {{"SCSX"_t, 0.25f}, {"SCOY"_t, 0.25f}}))
DEF_GM(return F(C(paint_scale), 0.0f, 0.0f, {{"SCSX"_t, -1.f}, {"SCOY"_t, -1.f}}))
DEF_GM(return F(C(paint_scale), 0.0f, 0.0f, {}))
DEF_GM(return F(C(paint_scale), 0.0f, 0.0f, {}))
DEF_GM(return F(C(paint_skew), 0.0f, 0.0f, {}))
DEF_GM(return F(C(paint_skew), 0.0f, 0.0f, {{"SKXA"_t, 20.f}}))
DEF_GM(return F(C(paint_skew), 0.0f, 0.0f, {{"SKYA"_t, 20.f}}))
DEF_GM(return F(C(paint_skew), 0.0f, 0.0f, {{"SKCX"_t, 200.f},{"SKCY"_t, 200.f}}))
DEF_GM(return F(C(paint_transform), 0.0f, 0.0f, {}))
DEF_GM(return F(C(paint_translate), 0.0f, 0.0f, {}))
DEF_GM(return F(C(paint_translate), 0.0f, 0.0f, {{"TLDX"_t, 100.f}, {"TLDY"_t, 100.f}}))
DEF_GM(return F(C(sweep_varsweep), 0.0f, 0.0f, {}))
DEF_GM(return F(C(sweep_varsweep), -0.5f, 0.0f, {}))
DEF_GM(return F(C(sweep_varsweep), -0.5f, 20.0f, {}))
DEF_GM(return F(C(sweep_varsweep), 0.0f, 20.0f, {}))
DEF_GM(return F(C(variable_alpha), 0.0f, 0.0f, {}))
DEF_GM(return F(C(variable_alpha), 0.0f, 0.0f, {{"APH1"_t, -0.7f}}))
DEF_GM(return F(C(variable_alpha), 0.0f, 0.0f, {{"APH2"_t, -0.7f}, {"APH3"_t, -0.2f}}))
} // namespace skiagm
<|endoftext|>
|
<commit_before>// Begin CVS Header
// $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/math/CMathEnum.cpp,v $
// $Revision: 1.1 $
// $Name: $
// $Author: shoops $
// $Date: 2011/05/24 16:32:31 $
// End CVS Header
// Copyright (C) 2011 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., University of Heidelberg, and The University
// of Manchester.
// All rights reserved.
#include "copasi.h"
#include "CMathEnum.h"
CMath::CVariableStack::CVariableStack():
mpStack(NULL),
mContext(Body),
mVariableLevel(C_INVALID_INDEX),
mBodyLevel(C_INVALID_INDEX)
{}
CMath::CVariableStack::CVariableStack(CMath::CVariableStack::Buffer & stack):
mpStack(&stack),
mContext(Body),
mVariableLevel(C_INVALID_INDEX),
mBodyLevel(C_INVALID_INDEX)
{}
CMath::CVariableStack::CVariableStack(const CMath::CVariableStack & src):
mpStack(src.mpStack),
mContext(src.mContext),
mVariableLevel(src.mVariableLevel),
mBodyLevel(src.mBodyLevel)
{}
CMath::CVariableStack::~CVariableStack()
{}
void CMath::CVariableStack::push(const CMath::CVariableStack::StackElement & stackElement)
{
mpStack->push_back(stackElement);
mBodyLevel++;
}
void CMath::CVariableStack::pop()
{
mpStack->pop_back();
mBodyLevel--;
}
size_t CMath::CVariableStack::size() const
{
return mpStack->size();
}
const CEvaluationNode * CMath::CVariableStack::operator [](const size_t & index) const
{
size_t Level = C_INVALID_INDEX;
switch (mContext)
{
case Variable:
Level = mVariableLevel;
break;
case Body:
Level = mBodyLevel;
break;
}
assert(Level < mpStack->size());
assert(index < mpStack->at(Level).size());
return mpStack->at(Level)[index];
}
std::ostream & operator << (std::ostream & os, const CMath::CVariableStack & s)
{
switch (s.mContext)
{
case CMath::CVariableStack::Variable:
os << "Context: variable ";
break;
case CMath::CVariableStack::Body:
os << "Context: body ";
break;
}
os << "Variable Level: " << s.mVariableLevel << " Body Level: " << s.mBodyLevel;
return os;
}
CMath::CAllocationStack::CAllocation::CAllocation():
nDiscontinuous(0),
nTotalRoots(0),
nRootsPerDiscontinuity()
{}
CMath::CAllocationStack::CAllocation::CAllocation(const CMath::CAllocationStack::CAllocation & src):
nDiscontinuous(src.nDiscontinuous),
nTotalRoots(src.nTotalRoots),
nRootsPerDiscontinuity(src.nRootsPerDiscontinuity)
{}
CMath::CAllocationStack::CAllocation::~CAllocation()
{}
CMath::CAllocationStack::CAllocation::CAllocation &
CMath::CAllocationStack::CAllocation::operator = (const CMath::CAllocationStack::CAllocation::CAllocation & rhs)
{
nDiscontinuous = rhs.nDiscontinuous;
nTotalRoots = rhs.nTotalRoots;
nRootsPerDiscontinuity = rhs.nRootsPerDiscontinuity;
return *this;
}
CMath::CAllocationStack::CAllocation::CAllocation &
CMath::CAllocationStack::CAllocation::operator += (const CMath::CAllocationStack::CAllocation::CAllocation & rhs)
{
nDiscontinuous += rhs.nDiscontinuous;
nTotalRoots += rhs.nTotalRoots;
nRootsPerDiscontinuity.insert(nRootsPerDiscontinuity.end(),
rhs.nRootsPerDiscontinuity.begin(),
rhs.nRootsPerDiscontinuity.end());
return *this;
}
CMath::CAllocationStack::CAllocationStack():
mpStack(NULL),
mContext(Body),
mVariableLevel(C_INVALID_INDEX),
mBodyLevel(C_INVALID_INDEX)
{}
CMath::CAllocationStack::CAllocationStack(CMath::CAllocationStack::Buffer & stack):
mpStack(&stack),
mContext(Body),
mVariableLevel(C_INVALID_INDEX),
mBodyLevel(C_INVALID_INDEX)
{}
CMath::CAllocationStack::CAllocationStack(const CMath::CAllocationStack & src):
mpStack(src.mpStack),
mContext(src.mContext),
mVariableLevel(src.mVariableLevel),
mBodyLevel(src.mBodyLevel)
{}
CMath::CAllocationStack::~CAllocationStack()
{}
void CMath::CAllocationStack::push(const CMath::CAllocationStack::StackElement & stackElement)
{
mpStack->push_back(stackElement);
mBodyLevel++;
}
void CMath::CAllocationStack::pop()
{
mpStack->pop_back();
mBodyLevel--;
}
size_t CMath::CAllocationStack::size() const
{
return mpStack->size();
}
const CMath::CAllocationStack::CAllocation &
CMath::CAllocationStack::operator [](const size_t & index) const
{
size_t Level = C_INVALID_INDEX;
switch (mContext)
{
case Variable:
Level = mVariableLevel;
break;
case Body:
Level = mBodyLevel;
break;
}
assert(Level < mpStack->size());
assert(index < mpStack->at(Level).size());
return mpStack->at(Level)[index];
}
std::ostream & operator << (std::ostream & os, const CMath::CAllocationStack::CAllocation & s)
{
os << "Discontinuities: " << s.nDiscontinuous;
return os;
}
<commit_msg>Fixed to compile under Visual Studio 2005 (VC 8.0)<commit_after>// Begin CVS Header
// $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/math/CMathEnum.cpp,v $
// $Revision: 1.2 $
// $Name: $
// $Author: shoops $
// $Date: 2011/06/07 19:59:41 $
// End CVS Header
// Copyright (C) 2011 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., University of Heidelberg, and The University
// of Manchester.
// All rights reserved.
#include "copasi.h"
#include "CMathEnum.h"
CMath::CVariableStack::CVariableStack():
mpStack(NULL),
mContext(Body),
mVariableLevel(C_INVALID_INDEX),
mBodyLevel(C_INVALID_INDEX)
{}
CMath::CVariableStack::CVariableStack(CMath::CVariableStack::Buffer & stack):
mpStack(&stack),
mContext(Body),
mVariableLevel(C_INVALID_INDEX),
mBodyLevel(C_INVALID_INDEX)
{}
CMath::CVariableStack::CVariableStack(const CMath::CVariableStack & src):
mpStack(src.mpStack),
mContext(src.mContext),
mVariableLevel(src.mVariableLevel),
mBodyLevel(src.mBodyLevel)
{}
CMath::CVariableStack::~CVariableStack()
{}
void CMath::CVariableStack::push(const CMath::CVariableStack::StackElement & stackElement)
{
mpStack->push_back(stackElement);
mBodyLevel++;
}
void CMath::CVariableStack::pop()
{
mpStack->pop_back();
mBodyLevel--;
}
size_t CMath::CVariableStack::size() const
{
return mpStack->size();
}
const CEvaluationNode * CMath::CVariableStack::operator [](const size_t & index) const
{
size_t Level = C_INVALID_INDEX;
switch (mContext)
{
case Variable:
Level = mVariableLevel;
break;
case Body:
Level = mBodyLevel;
break;
}
assert(Level < mpStack->size());
assert(index < mpStack->at(Level).size());
return mpStack->at(Level)[index];
}
std::ostream & operator << (std::ostream & os, const CMath::CVariableStack & s)
{
switch (s.mContext)
{
case CMath::CVariableStack::Variable:
os << "Context: variable ";
break;
case CMath::CVariableStack::Body:
os << "Context: body ";
break;
}
os << "Variable Level: " << s.mVariableLevel << " Body Level: " << s.mBodyLevel;
return os;
}
CMath::CAllocationStack::CAllocation::CAllocation():
nDiscontinuous(0),
nTotalRoots(0),
nRootsPerDiscontinuity()
{}
CMath::CAllocationStack::CAllocation::CAllocation(const CMath::CAllocationStack::CAllocation & src):
nDiscontinuous(src.nDiscontinuous),
nTotalRoots(src.nTotalRoots),
nRootsPerDiscontinuity(src.nRootsPerDiscontinuity)
{}
CMath::CAllocationStack::CAllocation::~CAllocation()
{}
CMath::CAllocationStack::CAllocation &
CMath::CAllocationStack::CAllocation::operator = (const CMath::CAllocationStack::CAllocation & rhs)
{
nDiscontinuous = rhs.nDiscontinuous;
nTotalRoots = rhs.nTotalRoots;
nRootsPerDiscontinuity = rhs.nRootsPerDiscontinuity;
return *this;
}
CMath::CAllocationStack::CAllocation &
CMath::CAllocationStack::CAllocation::operator += (const CMath::CAllocationStack::CAllocation & rhs)
{
nDiscontinuous += rhs.nDiscontinuous;
nTotalRoots += rhs.nTotalRoots;
nRootsPerDiscontinuity.insert(nRootsPerDiscontinuity.end(),
rhs.nRootsPerDiscontinuity.begin(),
rhs.nRootsPerDiscontinuity.end());
return *this;
}
CMath::CAllocationStack::CAllocationStack():
mpStack(NULL),
mContext(Body),
mVariableLevel(C_INVALID_INDEX),
mBodyLevel(C_INVALID_INDEX)
{}
CMath::CAllocationStack::CAllocationStack(CMath::CAllocationStack::Buffer & stack):
mpStack(&stack),
mContext(Body),
mVariableLevel(C_INVALID_INDEX),
mBodyLevel(C_INVALID_INDEX)
{}
CMath::CAllocationStack::CAllocationStack(const CMath::CAllocationStack & src):
mpStack(src.mpStack),
mContext(src.mContext),
mVariableLevel(src.mVariableLevel),
mBodyLevel(src.mBodyLevel)
{}
CMath::CAllocationStack::~CAllocationStack()
{}
void CMath::CAllocationStack::push(const CMath::CAllocationStack::StackElement & stackElement)
{
mpStack->push_back(stackElement);
mBodyLevel++;
}
void CMath::CAllocationStack::pop()
{
mpStack->pop_back();
mBodyLevel--;
}
size_t CMath::CAllocationStack::size() const
{
return mpStack->size();
}
const CMath::CAllocationStack::CAllocation &
CMath::CAllocationStack::operator [](const size_t & index) const
{
size_t Level = C_INVALID_INDEX;
switch (mContext)
{
case Variable:
Level = mVariableLevel;
break;
case Body:
Level = mBodyLevel;
break;
}
assert(Level < mpStack->size());
assert(index < mpStack->at(Level).size());
return mpStack->at(Level)[index];
}
std::ostream & operator << (std::ostream & os, const CMath::CAllocationStack::CAllocation & s)
{
os << "Discontinuities: " << s.nDiscontinuous;
return os;
}
<|endoftext|>
|
<commit_before>/*
* LoggingEvent.hh
*
* Copyright 2000, LifeLine Networks BV (www.lifeline.nl). All rights reserved.
* Copyright 2000, Bastiaan Bakker. All rights reserved.
*
* See the COPYING file for the terms of usage and distribution.
*/
#ifndef _LOG4CPP_LOGGINGEVENT_HH
#define _LOG4CPP_LOGGINGEVENT_HH
#include <string>
#include <time.h>
/**
* The top level namespace for all 'Log for C++' types and classes.
**/
namespace log4cpp {
/**
* The internal representation of logging events. When a affirmative
* logging decision is made a <code>LoggingEvent</code> instance is
* created. This instance is passed around the different log4cpp
* components.
*
* <p>This class is of concern to those wishing to extend log4cpp.
**/
struct LoggingEvent {
public:
/**
* Instantiate a LoggingEvent from the supplied parameters.
*
* <p>Except <code>timeStamp</code> all the other fields of
* <code>LoggingEvent</code> are filled when actually needed.
* <p>
* @param category The category of this event.
* @param message The message of this event.
* @param ndc The nested diagnostic context of this event.
* @param priority The priority of this event.
**/
LoggingEvent(const std::string& category, const std::string& message,
const std::string& ndc, int priority);
/** The category name. */
const std::string& categoryName;
/** The application supplied message of logging event. */
const std::string& message;
/** The nested diagnostic context (NDC) of logging event. */
const std::string& ndc;
/** Priority of logging event. */
int priority;
/** The name of thread in which this logging event was generated,
e.g. the PID. */
const std::string& threadName;
//QQQ const std::string threadName;
/** The number of seconds elapsed since the epoch
(1/1/1970 00:00:00 UTC) until logging event was created. */
time_t timeStamp;
};
}
#endif // _LOG4CPP_LOGGINGEVENT_HH
<commit_msg>Made threadName a member to keep MSVC++ from crashing.<commit_after>/*
* LoggingEvent.hh
*
* Copyright 2000, LifeLine Networks BV (www.lifeline.nl). All rights reserved.
* Copyright 2000, Bastiaan Bakker. All rights reserved.
*
* See the COPYING file for the terms of usage and distribution.
*/
#ifndef _LOG4CPP_LOGGINGEVENT_HH
#define _LOG4CPP_LOGGINGEVENT_HH
#include <string>
#include <time.h>
/**
* The top level namespace for all 'Log for C++' types and classes.
**/
namespace log4cpp {
/**
* The internal representation of logging events. When a affirmative
* logging decision is made a <code>LoggingEvent</code> instance is
* created. This instance is passed around the different log4cpp
* components.
*
* <p>This class is of concern to those wishing to extend log4cpp.
**/
struct LoggingEvent {
public:
/**
* Instantiate a LoggingEvent from the supplied parameters.
*
* <p>Except <code>timeStamp</code> all the other fields of
* <code>LoggingEvent</code> are filled when actually needed.
* <p>
* @param category The category of this event.
* @param message The message of this event.
* @param ndc The nested diagnostic context of this event.
* @param priority The priority of this event.
**/
LoggingEvent(const std::string& category, const std::string& message,
const std::string& ndc, int priority);
/** The category name. */
const std::string& categoryName;
/** The application supplied message of logging event. */
const std::string& message;
/** The nested diagnostic context (NDC) of logging event. */
const std::string& ndc;
/** Priority of logging event. */
int priority;
/** The name of thread in which this logging event was generated,
e.g. the PID. Because MSVC++ crashes if it is declared as a
reference at this point I made it a member for now.
*/
const std::string threadName;
/** The number of seconds elapsed since the epoch
(1/1/1970 00:00:00 UTC) until logging event was created. */
time_t timeStamp;
};
}
#endif // _LOG4CPP_LOGGINGEVENT_HH
<|endoftext|>
|
<commit_before>#ifndef GP_NODE_INTERFACE
#define GP_NODE_INTERFACE
#include <typeinfo>
#include <memory>
#include <any>
#include <utility/evaluation_context.hpp>
#include <utility/type.hpp>
namespace gp::node{
enum class NodeType {
Normal,
Argument,
LocalVariable,
Progn,
Subroutine,
Const
};
//primary declarations for friend class declarations
template <typename T>
class NodeBase;
template <typename T, std::size_t n>
class PrognNode;
class NodeInterface {
public:
using type_info = const utility::TypeInfo&;
using node_instance_type = std::unique_ptr<NodeInterface>;
template <typename NodeType, typename ...Ts>
static node_instance_type createInstance(Ts&&... args) {return std::make_unique<NodeType>(std::forward<Ts>(args)...);}
private:
template <typename T> friend class NodeBase;
template <typename T, std::size_t n> friend class PrognNode;
virtual void setParent(NodeInterface* node) = 0;
public:
//type information methods
virtual type_info getReturnType()const noexcept= 0;
virtual type_info getChildReturnType(std::size_t n)const noexcept = 0;
//methods for children
virtual std::size_t getChildNum()const noexcept = 0;
virtual bool hasChild(std::size_t n)const noexcept = 0;
virtual NodeInterface& getChildNode(std::size_t n) = 0;
virtual const NodeInterface& getChildNode(std::size_t n)const = 0;
virtual void setChild(std::size_t n, std::unique_ptr<NodeInterface> node) = 0;
//methods for parent
virtual bool hasParent()const noexcept = 0;
virtual NodeInterface& getParent() = 0;
virtual const NodeInterface& getParent()const = 0;
//method for evaluation
virtual std::any evaluateByAny(utility::EvaluationContext&)const = 0;
//methods for properties
virtual void setNodePropertyByNodeName(const std::string&) = 0;
virtual void setNodePropertyByAny(const std::any&) = 0;
virtual std::any getNodePropertyByAny()const = 0;
virtual std::string getNodeName()const = 0;
virtual node_instance_type clone()const = 0;
virtual NodeType getNodeType()const noexcept = 0;
public:
virtual ~NodeInterface() = default;
NodeInterface(NodeInterface&&) = default;
NodeInterface& operator=(NodeInterface&&) = default;
NodeInterface(const NodeInterface&) = default;
NodeInterface& operator=(const NodeInterface&) = default;
NodeInterface() = default;
};
}
#endif<commit_msg>force users to derive TypedNodeInterface by setting the constructor of NodeInterface as private<commit_after>#ifndef GP_NODE_INTERFACE
#define GP_NODE_INTERFACE
#include <typeinfo>
#include <memory>
#include <any>
#include <utility/evaluation_context.hpp>
#include <utility/type.hpp>
namespace gp::node{
enum class NodeType {
Normal,
Argument,
LocalVariable,
Progn,
Subroutine,
Const
};
//primary declarations for friend class declarations
template <typename T>
class TypedNodeInterface;
template <typename T>
class NodeBase;
template <typename T, std::size_t n>
class PrognNode;
class NodeInterface {
public:
using type_info = const utility::TypeInfo&;
using node_instance_type = std::unique_ptr<NodeInterface>;
template <typename NodeType, typename ...Ts>
static node_instance_type createInstance(Ts&&... args) {return std::make_unique<NodeType>(std::forward<Ts>(args)...);}
private:
template <typename T> friend class TypedNodeInterface;
template <typename T> friend class NodeBase;
template <typename T, std::size_t n> friend class PrognNode;
NodeInterface() = default; //only the TypedNodeInterface can construct NodeInterface. Users who want to create custom node must derive NodeBase or TypedNodeInterface.
virtual void setParent(NodeInterface* node) = 0;
public:
//type information methods
virtual type_info getReturnType()const noexcept= 0;
virtual type_info getChildReturnType(std::size_t n)const noexcept = 0;
//methods for children
virtual std::size_t getChildNum()const noexcept = 0;
virtual bool hasChild(std::size_t n)const noexcept = 0;
virtual NodeInterface& getChildNode(std::size_t n) = 0;
virtual const NodeInterface& getChildNode(std::size_t n)const = 0;
virtual void setChild(std::size_t n, std::unique_ptr<NodeInterface> node) = 0;
//methods for parent
virtual bool hasParent()const noexcept = 0;
virtual NodeInterface& getParent() = 0;
virtual const NodeInterface& getParent()const = 0;
//method for evaluation
virtual std::any evaluateByAny(utility::EvaluationContext&)const = 0;
//methods for properties
virtual void setNodePropertyByNodeName(const std::string&) = 0;
virtual void setNodePropertyByAny(const std::any&) = 0;
virtual std::any getNodePropertyByAny()const = 0;
virtual std::string getNodeName()const = 0;
virtual node_instance_type clone()const = 0;
virtual NodeType getNodeType()const noexcept = 0;
public:
virtual ~NodeInterface() = default;
NodeInterface(NodeInterface&&) = default;
NodeInterface& operator=(NodeInterface&&) = default;
NodeInterface(const NodeInterface&) = default;
NodeInterface& operator=(const NodeInterface&) = default;
};
}
#endif<|endoftext|>
|
<commit_before>/*-------------------------------------------------------------------------
*
* FILE
* pqxx/subtransaction.hxx
*
* DESCRIPTION
* definition of the pqxx::subtransaction class.
* pqxx::subtransaction is a nested transaction, i.e. one within a transaction
* DO NOT INCLUDE THIS FILE DIRECTLY; include pqxx/subtransaction instead.
*
* Copyright (c) 2005, Jeroen T. Vermeulen <jtv@xs4all.nl>
*
* See COPYING for copyright license. If you did not receive a file called
* COPYING with this source code, please notify the distributor of this mistake,
* or contact the author.
*
*-------------------------------------------------------------------------
*/
#include "pqxx/compiler-public.hxx"
#include "pqxx/dbtransaction"
/* Methods tested in eg. self-test program test1 are marked with "//[t1]"
*/
namespace pqxx
{
/**
* @addtogroup transaction Transaction classes
*/
//@{
class PQXX_LIBEXPORT subtransaction :
public internal::transactionfocus,
public dbtransaction
{
public:
explicit subtransaction(dbtransaction &T,
const PGSTD::string &Name=PGSTD::string()); //[t88]
private:
virtual void do_begin(); //[t88]
virtual void do_commit(); //[t88]
virtual void do_abort(); //[t88]
dbtransaction &m_parent;
};
//@}
}
<commit_msg>Smarter detection of backend capability<commit_after>/*-------------------------------------------------------------------------
*
* FILE
* pqxx/subtransaction.hxx
*
* DESCRIPTION
* definition of the pqxx::subtransaction class.
* pqxx::subtransaction is a nested transaction, i.e. one within a transaction
* DO NOT INCLUDE THIS FILE DIRECTLY; include pqxx/subtransaction instead.
*
* Copyright (c) 2005-2006, Jeroen T. Vermeulen <jtv@xs4all.nl>
*
* See COPYING for copyright license. If you did not receive a file called
* COPYING with this source code, please notify the distributor of this mistake,
* or contact the author.
*
*-------------------------------------------------------------------------
*/
#include "pqxx/compiler-public.hxx"
#include "pqxx/dbtransaction"
/* Methods tested in eg. self-test program test1 are marked with "//[t1]"
*/
namespace pqxx
{
/**
* @addtogroup transaction Transaction classes
*/
//@{
class PQXX_LIBEXPORT subtransaction :
public internal::transactionfocus,
public dbtransaction
{
public:
explicit subtransaction(dbtransaction &T,
const PGSTD::string &Name=PGSTD::string()); //[t88]
private:
virtual void do_begin(); //[t88]
virtual void do_commit(); //[t88]
virtual void do_abort(); //[t88]
void check_backendsupport() const;
dbtransaction &m_parent;
};
//@}
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2008, Google 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 Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "config.h"
#include "ScrollbarThemeChromium.h"
#include "AffineTransform.h"
#include "NotImplemented.h"
#include "PlatformContextSkia.h"
#include "PlatformMouseEvent.h"
#include "Scrollbar.h"
#include "gtkdrawing.h"
#include "GdkSkia.h"
#include <gtk/gtk.h>
namespace WebCore {
int ScrollbarThemeChromium::scrollbarThickness(ScrollbarControlSize controlSize)
{
static int size = 0;
if (!size) {
MozGtkScrollbarMetrics metrics;
moz_gtk_get_scrollbar_metrics(&metrics);
size = metrics.slider_width;
}
return size;
}
bool ScrollbarThemeChromium::invalidateOnMouseEnterExit()
{
notImplemented();
return false;
}
// -----------------------------------------------------------------------------
// Given an uninitialised widget state object, set the members such that it's
// sane for drawing scrollbars
// -----------------------------------------------------------------------------
static void initMozState(GtkWidgetState* mozState)
{
mozState->active = true;
mozState->focused = false;
mozState->inHover = false;
mozState->disabled = false;
mozState->isDefault = false;
mozState->canDefault = false;
mozState->depressed = false;
mozState->curpos = 0;
mozState->maxpos = 0;
}
// -----------------------------------------------------------------------------
// Paint a GTK widget
// gc: context to draw onto
// rect: the area of the widget
// widget_type: the type of widget to draw
// flags: widget dependent flags (e.g. direction of scrollbar arrows etc)
//
// See paintMozWiget in RenderThemeGtk.cpp for an explanation of the clipping.
// -----------------------------------------------------------------------------
static void paintScrollbarWidget(GraphicsContext* gc, const IntRect& rect,
GtkThemeWidgetType widget_type, gint flags)
{
PlatformContextSkia* pcs = gc->platformContext();
GdkRectangle gdkRect = { rect.x(), rect.y(), rect.width(), rect.height() };
const SkIRect clip_region = pcs->canvas()->getTotalClip().getBounds();
AffineTransform ctm = gc->getCTM().inverse();
IntPoint pos = ctm.mapPoint(
IntPoint(SkScalarRound(clip_region.fLeft), SkScalarRound(clip_region.fTop)));
GdkRectangle gdkClipRect;
gdkClipRect.x = pos.x();
gdkClipRect.y = pos.y();
gdkClipRect.width = clip_region.width();
gdkClipRect.height = clip_region.height();
gdk_rectangle_intersect(&gdkRect, &gdkClipRect, &gdkClipRect);
GtkWidgetState mozState;
initMozState(&mozState);
moz_gtk_widget_paint(widget_type, pcs->gdk_skia(), &gdkRect, &gdkClipRect,
&mozState, flags, GTK_TEXT_DIR_LTR);
}
void ScrollbarThemeChromium::paintTrackPiece(GraphicsContext* gc, Scrollbar* scrollbar,
const IntRect& rect, ScrollbarPart partType)
{
const bool horz = scrollbar->orientation() == HorizontalScrollbar;
const GtkThemeWidgetType track_type =
horz ? MOZ_GTK_SCROLLBAR_TRACK_HORIZONTAL : MOZ_GTK_SCROLLBAR_TRACK_VERTICAL;
paintScrollbarWidget(gc, rect, track_type, 0);
return;
}
void ScrollbarThemeChromium::paintButton(GraphicsContext* gc, Scrollbar* scrollbar,
const IntRect& rect, ScrollbarPart part)
{
const bool horz = scrollbar->orientation() == HorizontalScrollbar;
gint flags = horz ? 0 : MOZ_GTK_STEPPER_VERTICAL;
flags |= ForwardButtonEndPart == part ? MOZ_GTK_STEPPER_DOWN : 0;
paintScrollbarWidget(gc, rect, MOZ_GTK_SCROLLBAR_BUTTON, flags);
}
void ScrollbarThemeChromium::paintThumb(GraphicsContext* gc, Scrollbar* scrollbar, const IntRect& rect)
{
const bool horz = scrollbar->orientation() == HorizontalScrollbar;
const GtkThemeWidgetType thumb_type =
horz ? MOZ_GTK_SCROLLBAR_THUMB_HORIZONTAL : MOZ_GTK_SCROLLBAR_THUMB_VERTICAL;
paintScrollbarWidget(gc, rect, thumb_type, 0);
}
} // namespace WebCore
<commit_msg>It appears that the GTK theme doesn't always draw the full rectangle when we ask it to draw a scrollbar button. It's not clear if it expects the background to already be filled in, or if we are brearking it by giving it WebKit metrics. Either way, it's messing up our pixeltest baselines with undefined pixels so we paint seafoam-green under scrollbar buttons before GTK draws.<commit_after>// Copyright (c) 2008, Google 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 Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "config.h"
#include "ScrollbarThemeChromium.h"
#include "AffineTransform.h"
#include "NotImplemented.h"
#include "PlatformContextSkia.h"
#include "PlatformMouseEvent.h"
#include "Scrollbar.h"
#include "gtkdrawing.h"
#include "GdkSkia.h"
#include <gtk/gtk.h>
namespace WebCore {
int ScrollbarThemeChromium::scrollbarThickness(ScrollbarControlSize controlSize)
{
static int size = 0;
if (!size) {
MozGtkScrollbarMetrics metrics;
moz_gtk_get_scrollbar_metrics(&metrics);
size = metrics.slider_width;
}
return size;
}
bool ScrollbarThemeChromium::invalidateOnMouseEnterExit()
{
notImplemented();
return false;
}
// -----------------------------------------------------------------------------
// Given an uninitialised widget state object, set the members such that it's
// sane for drawing scrollbars
// -----------------------------------------------------------------------------
static void initMozState(GtkWidgetState* mozState)
{
mozState->active = true;
mozState->focused = false;
mozState->inHover = false;
mozState->disabled = false;
mozState->isDefault = false;
mozState->canDefault = false;
mozState->depressed = false;
mozState->curpos = 0;
mozState->maxpos = 0;
}
// -----------------------------------------------------------------------------
// Paint a GTK widget
// gc: context to draw onto
// rect: the area of the widget
// widget_type: the type of widget to draw
// flags: widget dependent flags (e.g. direction of scrollbar arrows etc)
//
// See paintMozWiget in RenderThemeGtk.cpp for an explanation of the clipping.
// -----------------------------------------------------------------------------
static void paintScrollbarWidget(GraphicsContext* gc, const IntRect& rect,
GtkThemeWidgetType widget_type, gint flags)
{
PlatformContextSkia* pcs = gc->platformContext();
GdkRectangle gdkRect = { rect.x(), rect.y(), rect.width(), rect.height() };
const SkIRect clip_region = pcs->canvas()->getTotalClip().getBounds();
AffineTransform ctm = gc->getCTM().inverse();
IntPoint pos = ctm.mapPoint(
IntPoint(SkScalarRound(clip_region.fLeft), SkScalarRound(clip_region.fTop)));
GdkRectangle gdkClipRect;
gdkClipRect.x = pos.x();
gdkClipRect.y = pos.y();
gdkClipRect.width = clip_region.width();
gdkClipRect.height = clip_region.height();
gdk_rectangle_intersect(&gdkRect, &gdkClipRect, &gdkClipRect);
GtkWidgetState mozState;
initMozState(&mozState);
moz_gtk_widget_paint(widget_type, pcs->gdk_skia(), &gdkRect, &gdkClipRect,
&mozState, flags, GTK_TEXT_DIR_LTR);
}
void ScrollbarThemeChromium::paintTrackPiece(GraphicsContext* gc, Scrollbar* scrollbar,
const IntRect& rect, ScrollbarPart partType)
{
const bool horz = scrollbar->orientation() == HorizontalScrollbar;
const GtkThemeWidgetType track_type =
horz ? MOZ_GTK_SCROLLBAR_TRACK_HORIZONTAL : MOZ_GTK_SCROLLBAR_TRACK_VERTICAL;
paintScrollbarWidget(gc, rect, track_type, 0);
return;
}
void ScrollbarThemeChromium::paintButton(GraphicsContext* gc, Scrollbar* scrollbar,
const IntRect& rect, ScrollbarPart part)
{
// TODO(port): It appears the either we're upsetting GTK by forcing WebKit
// sizes on it, or the buttons expect the track to be drawn under them.
// Either way, we end up with unpainted pixels which are upsetting the
// pixel tests. Thus we paint green under the buttons to, at least, make
// the pixel output the same between debug and opt builds.
SkPaint paint;
paint.setARGB(255, 0, 255, 128);
SkRect skrect;
skrect.set(rect.x(), rect.y(), rect.x() + rect.width() - 1, rect.y() + rect.height() + 1);
gc->platformContext()->canvas()->drawRect(skrect, paint);
const bool horz = scrollbar->orientation() == HorizontalScrollbar;
gint flags = horz ? 0 : MOZ_GTK_STEPPER_VERTICAL;
flags |= ForwardButtonEndPart == part ? MOZ_GTK_STEPPER_DOWN : 0;
paintScrollbarWidget(gc, rect, MOZ_GTK_SCROLLBAR_BUTTON, flags);
}
void ScrollbarThemeChromium::paintThumb(GraphicsContext* gc, Scrollbar* scrollbar, const IntRect& rect)
{
const bool horz = scrollbar->orientation() == HorizontalScrollbar;
const GtkThemeWidgetType thumb_type =
horz ? MOZ_GTK_SCROLLBAR_THUMB_HORIZONTAL : MOZ_GTK_SCROLLBAR_THUMB_VERTICAL;
paintScrollbarWidget(gc, rect, thumb_type, 0);
}
} // namespace WebCore
<|endoftext|>
|
<commit_before>/*
* This file is open source software, licensed to you under the terms
* of the Apache License, Version 2.0 (the "License"). See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. 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.
*/
/*
* Copyright 2015 Cloudius Systems
*/
//
// request.hpp
// ~~~~~~~~~~~
//
// Copyright (c) 2003-2013 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#pragma once
#include <seastar/core/iostream.hh>
#include <seastar/core/sstring.hh>
#include <string>
#include <vector>
#include <strings.h>
#include <seastar/http/common.hh>
#include <seastar/core/iostream.hh>
namespace seastar {
namespace httpd {
class connection;
/**
* A request received from a client.
*/
struct request {
enum class ctclass
: char {
other, multipart, app_x_www_urlencoded,
};
struct case_insensitive_cmp {
bool operator()(const sstring& s1, const sstring& s2) const {
return std::equal(s1.begin(), s1.end(), s2.begin(), s2.end(),
[](char a, char b) { return ::tolower(a) == ::tolower(b); });
}
};
struct case_insensitive_hash {
size_t operator()(sstring s) const {
std::transform(s.begin(), s.end(), s.begin(), ::tolower);
return std::hash<sstring>()(s);
}
};
sstring _method;
sstring _url;
sstring _version;
int http_version_major;
int http_version_minor;
ctclass content_type_class;
size_t content_length = 0;
std::unordered_map<sstring, sstring, case_insensitive_hash, case_insensitive_cmp> _headers;
std::unordered_map<sstring, sstring> query_parameters;
connection* connection_ptr;
parameters param;
sstring content; // deprecated: use content_stream instead
/*
* The handler should read the contents of this stream till reaching eof (i.e., the end of this request's content). Failing to do so
* will force the server to close this connection, and the client will not be able to reuse this connection for the next request.
* The stream should not be closed by the handler, the server will close it for the handler.
* */
input_stream<char>* content_stream;
std::unordered_map<sstring, sstring> trailing_headers;
std::unordered_map<sstring, sstring> chunk_extensions;
sstring protocol_name = "http";
/**
* Search for the first header of a given name
* @param name the header name
* @return a pointer to the header value, if it exists or empty string
*/
sstring get_header(const sstring& name) const {
auto res = _headers.find(name);
if (res == _headers.end()) {
return "";
}
return res->second;
}
/**
* Search for the first header of a given name
* @param name the header name
* @return a pointer to the header value, if it exists or empty string
*/
sstring get_query_param(const sstring& name) const {
auto res = query_parameters.find(name);
if (res == query_parameters.end()) {
return "";
}
return res->second;
}
/**
* Get the request protocol name. Can be either "http" or "https".
*/
sstring get_protocol_name() const {
return protocol_name;
}
/**
* Get the request url.
* @return the request url
*/
sstring get_url() const {
return get_protocol_name() + "://" + get_header("Host") + _url;
}
bool is_multi_part() const {
return content_type_class == ctclass::multipart;
}
bool is_form_post() const {
return content_type_class == ctclass::app_x_www_urlencoded;
}
bool should_keep_alive() const {
if (_version == "0.9") {
return false;
}
// TODO: handle HTTP/2.0 when it releases
auto it = _headers.find("Connection");
if (_version == "1.0") {
return it != _headers.end()
&& case_insensitive_cmp()(it->second, "keep-alive");
} else { // HTTP/1.1
return it == _headers.end() || !case_insensitive_cmp()(it->second, "close");
}
}
};
} // namespace httpd
}
<commit_msg>http: Remove unused members from request<commit_after>/*
* This file is open source software, licensed to you under the terms
* of the Apache License, Version 2.0 (the "License"). See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. 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.
*/
/*
* Copyright 2015 Cloudius Systems
*/
//
// request.hpp
// ~~~~~~~~~~~
//
// Copyright (c) 2003-2013 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#pragma once
#include <seastar/core/iostream.hh>
#include <seastar/core/sstring.hh>
#include <string>
#include <vector>
#include <strings.h>
#include <seastar/http/common.hh>
#include <seastar/core/iostream.hh>
namespace seastar {
namespace httpd {
/**
* A request received from a client.
*/
struct request {
enum class ctclass
: char {
other, multipart, app_x_www_urlencoded,
};
struct case_insensitive_cmp {
bool operator()(const sstring& s1, const sstring& s2) const {
return std::equal(s1.begin(), s1.end(), s2.begin(), s2.end(),
[](char a, char b) { return ::tolower(a) == ::tolower(b); });
}
};
struct case_insensitive_hash {
size_t operator()(sstring s) const {
std::transform(s.begin(), s.end(), s.begin(), ::tolower);
return std::hash<sstring>()(s);
}
};
sstring _method;
sstring _url;
sstring _version;
ctclass content_type_class;
size_t content_length = 0;
std::unordered_map<sstring, sstring, case_insensitive_hash, case_insensitive_cmp> _headers;
std::unordered_map<sstring, sstring> query_parameters;
parameters param;
sstring content; // deprecated: use content_stream instead
/*
* The handler should read the contents of this stream till reaching eof (i.e., the end of this request's content). Failing to do so
* will force the server to close this connection, and the client will not be able to reuse this connection for the next request.
* The stream should not be closed by the handler, the server will close it for the handler.
* */
input_stream<char>* content_stream;
std::unordered_map<sstring, sstring> trailing_headers;
std::unordered_map<sstring, sstring> chunk_extensions;
sstring protocol_name = "http";
/**
* Search for the first header of a given name
* @param name the header name
* @return a pointer to the header value, if it exists or empty string
*/
sstring get_header(const sstring& name) const {
auto res = _headers.find(name);
if (res == _headers.end()) {
return "";
}
return res->second;
}
/**
* Search for the first header of a given name
* @param name the header name
* @return a pointer to the header value, if it exists or empty string
*/
sstring get_query_param(const sstring& name) const {
auto res = query_parameters.find(name);
if (res == query_parameters.end()) {
return "";
}
return res->second;
}
/**
* Get the request protocol name. Can be either "http" or "https".
*/
sstring get_protocol_name() const {
return protocol_name;
}
/**
* Get the request url.
* @return the request url
*/
sstring get_url() const {
return get_protocol_name() + "://" + get_header("Host") + _url;
}
bool is_multi_part() const {
return content_type_class == ctclass::multipart;
}
bool is_form_post() const {
return content_type_class == ctclass::app_x_www_urlencoded;
}
bool should_keep_alive() const {
if (_version == "0.9") {
return false;
}
// TODO: handle HTTP/2.0 when it releases
auto it = _headers.find("Connection");
if (_version == "1.0") {
return it != _headers.end()
&& case_insensitive_cmp()(it->second, "keep-alive");
} else { // HTTP/1.1
return it == _headers.end() || !case_insensitive_cmp()(it->second, "close");
}
}
};
} // namespace httpd
}
<|endoftext|>
|
<commit_before>#include <nsIFactory.h>
#include "sugar-download-manager.h"
#include "GeckoDownload.h"
class GeckoDownload : public nsITransfer
{
public:
GeckoDownload();
virtual ~GeckoDownload();
NS_DECL_ISUPPORTS
NS_DECL_NSIWEBPROGRESSLISTENER
NS_DECL_NSIWEBPROGRESSLISTENER2
NS_DECL_NSITRANSFER
protected:
nsIURI *mSource;
nsCString mTargetFileName;
nsIMIMEInfo *mMIMEInfo;
nsILocalFile *mTempFile;
};
GeckoDownload::GeckoDownload ()
{
}
GeckoDownload::~GeckoDownload ()
{
}
NS_IMPL_ISUPPORTS3 (GeckoDownload,
nsIWebProgressListener,
nsIWebProgressListener2,
nsITransfer)
NS_IMETHODIMP
GeckoDownload::Init (nsIURI *aSource,
nsIURI *aTarget,
const nsAString &aDisplayName,
nsIMIMEInfo *aMIMEInfo,
PRTime aStartTime,
nsILocalFile *aTempFile,
nsICancelable *aCancelable)
{
mSource = aSource;
aTarget->GetPath (mTargetFileName);
mMIMEInfo = aMIMEInfo;
mTempFile = aTempFile;
// mCancelable = aCancelable; Just a reminder for when we implement cancelling downloads.
return NS_OK;
}
NS_IMETHODIMP
GeckoDownload::OnStateChange (nsIWebProgress *aWebProgress,
nsIRequest *aRequest,
PRUint32 aStateFlags,
nsresult aStatus)
{
SugarDownloadManager *download_manager = sugar_get_download_manager ();
if (aStateFlags == STATE_START) {
nsCString url;
nsCString mimeType;
mMIMEInfo->GetMIMEType (mimeType);
mSource->GetSpec (url);
sugar_download_manager_download_started (download_manager,
url.get (),
mimeType.get (),
mTargetFileName.get ());
} else if (aStateFlags == STATE_STOP) {
if (NS_SUCCEEDED (aStatus)) {
sugar_download_manager_download_completed (download_manager,
mTargetFileName.get ());
} else {
sugar_download_manager_download_cancelled (download_manager,
mTargetFileName.get ());
}
}
return NS_OK;
}
NS_IMETHODIMP
GeckoDownload::OnProgressChange (nsIWebProgress *aWebProgress,
nsIRequest *aRequest,
PRInt32 aCurSelfProgress,
PRInt32 aMaxSelfProgress,
PRInt32 aCurTotalProgress,
PRInt32 aMaxTotalProgress)
{
return OnProgressChange64 (aWebProgress,
aRequest,
aCurSelfProgress,
aMaxSelfProgress,
aCurTotalProgress,
aMaxTotalProgress);
}
NS_IMETHODIMP
GeckoDownload::OnProgressChange64 (nsIWebProgress *aWebProgress,
nsIRequest *aRequest,
PRInt64 aCurSelfProgress,
PRInt64 aMaxSelfProgress,
PRInt64 aCurTotalProgress,
PRInt64 aMaxTotalProgress)
{
SugarDownloadManager *download_manager = sugar_get_download_manager ();
PRInt32 percentComplete =
(PRInt32)(((float)aCurSelfProgress / (float)aMaxSelfProgress) * 100.0);
sugar_download_manager_update_progress (download_manager,
mTargetFileName.get (),
percentComplete);
return NS_OK;
}
NS_IMETHODIMP
GeckoDownload::OnLocationChange (nsIWebProgress *aWebProgress,
nsIRequest *aRequest,
nsIURI *location)
{
return NS_OK;
}
NS_IMETHODIMP
GeckoDownload::OnStatusChange (nsIWebProgress *aWebProgress,
nsIRequest *aRequest,
nsresult aStatus,
const PRUnichar *aMessage)
{
return NS_OK;
}
NS_IMETHODIMP
GeckoDownload::OnSecurityChange (nsIWebProgress *aWebProgress,
nsIRequest *aRequest,
PRUint32 state)
{
return NS_OK;
}
NS_IMETHODIMP
GeckoDownload::OnRefreshAttempted (nsIWebProgress *aWebProgress,
nsIURI *aRefreshURI,
PRInt32 aMillis,
PRBool aSameURI,
PRBool *_retval)
{
return NS_OK;
}
//*****************************************************************************
// GeckoDownloadFactory
//*****************************************************************************
class GeckoDownloadFactory : public nsIFactory {
public:
NS_DECL_ISUPPORTS
NS_DECL_NSIFACTORY
GeckoDownloadFactory();
virtual ~GeckoDownloadFactory();
};
//*****************************************************************************
NS_IMPL_ISUPPORTS1(GeckoDownloadFactory, nsIFactory)
GeckoDownloadFactory::GeckoDownloadFactory() {
}
GeckoDownloadFactory::~GeckoDownloadFactory() {
}
NS_IMETHODIMP
GeckoDownloadFactory::CreateInstance(nsISupports *aOuter, const nsIID & aIID, void **aResult)
{
NS_ENSURE_ARG_POINTER(aResult);
*aResult = NULL;
GeckoDownload *inst = new GeckoDownload;
if (!inst)
return NS_ERROR_OUT_OF_MEMORY;
nsresult rv = inst->QueryInterface(aIID, aResult);
if (rv != NS_OK) {
// We didn't get the right interface, so clean up
delete inst;
}
return rv;
}
NS_IMETHODIMP
GeckoDownloadFactory::LockFactory(PRBool lock)
{
return NS_OK;
}
//*****************************************************************************
nsresult
NS_NewGeckoDownloadFactory(nsIFactory** aFactory)
{
NS_ENSURE_ARG_POINTER(aFactory);
*aFactory = nsnull;
GeckoDownloadFactory *result = new GeckoDownloadFactory;
if (!result)
return NS_ERROR_OUT_OF_MEMORY;
NS_ADDREF(result);
*aFactory = result;
return NS_OK;
}
<commit_msg>Compile the new method only if we are on 1.9<commit_after>#include <nsIFactory.h>
#include "sugar-download-manager.h"
#include "GeckoDownload.h"
class GeckoDownload : public nsITransfer
{
public:
GeckoDownload();
virtual ~GeckoDownload();
NS_DECL_ISUPPORTS
NS_DECL_NSIWEBPROGRESSLISTENER
NS_DECL_NSIWEBPROGRESSLISTENER2
NS_DECL_NSITRANSFER
protected:
nsIURI *mSource;
nsCString mTargetFileName;
nsIMIMEInfo *mMIMEInfo;
nsILocalFile *mTempFile;
};
GeckoDownload::GeckoDownload ()
{
}
GeckoDownload::~GeckoDownload ()
{
}
NS_IMPL_ISUPPORTS3 (GeckoDownload,
nsIWebProgressListener,
nsIWebProgressListener2,
nsITransfer)
NS_IMETHODIMP
GeckoDownload::Init (nsIURI *aSource,
nsIURI *aTarget,
const nsAString &aDisplayName,
nsIMIMEInfo *aMIMEInfo,
PRTime aStartTime,
nsILocalFile *aTempFile,
nsICancelable *aCancelable)
{
mSource = aSource;
aTarget->GetPath (mTargetFileName);
mMIMEInfo = aMIMEInfo;
mTempFile = aTempFile;
// mCancelable = aCancelable; Just a reminder for when we implement cancelling downloads.
return NS_OK;
}
NS_IMETHODIMP
GeckoDownload::OnStateChange (nsIWebProgress *aWebProgress,
nsIRequest *aRequest,
PRUint32 aStateFlags,
nsresult aStatus)
{
SugarDownloadManager *download_manager = sugar_get_download_manager ();
if (aStateFlags == STATE_START) {
nsCString url;
nsCString mimeType;
mMIMEInfo->GetMIMEType (mimeType);
mSource->GetSpec (url);
sugar_download_manager_download_started (download_manager,
url.get (),
mimeType.get (),
mTargetFileName.get ());
} else if (aStateFlags == STATE_STOP) {
if (NS_SUCCEEDED (aStatus)) {
sugar_download_manager_download_completed (download_manager,
mTargetFileName.get ());
} else {
sugar_download_manager_download_cancelled (download_manager,
mTargetFileName.get ());
}
}
return NS_OK;
}
NS_IMETHODIMP
GeckoDownload::OnProgressChange (nsIWebProgress *aWebProgress,
nsIRequest *aRequest,
PRInt32 aCurSelfProgress,
PRInt32 aMaxSelfProgress,
PRInt32 aCurTotalProgress,
PRInt32 aMaxTotalProgress)
{
return OnProgressChange64 (aWebProgress,
aRequest,
aCurSelfProgress,
aMaxSelfProgress,
aCurTotalProgress,
aMaxTotalProgress);
}
NS_IMETHODIMP
GeckoDownload::OnProgressChange64 (nsIWebProgress *aWebProgress,
nsIRequest *aRequest,
PRInt64 aCurSelfProgress,
PRInt64 aMaxSelfProgress,
PRInt64 aCurTotalProgress,
PRInt64 aMaxTotalProgress)
{
SugarDownloadManager *download_manager = sugar_get_download_manager ();
PRInt32 percentComplete =
(PRInt32)(((float)aCurSelfProgress / (float)aMaxSelfProgress) * 100.0);
sugar_download_manager_update_progress (download_manager,
mTargetFileName.get (),
percentComplete);
return NS_OK;
}
NS_IMETHODIMP
GeckoDownload::OnLocationChange (nsIWebProgress *aWebProgress,
nsIRequest *aRequest,
nsIURI *location)
{
return NS_OK;
}
NS_IMETHODIMP
GeckoDownload::OnStatusChange (nsIWebProgress *aWebProgress,
nsIRequest *aRequest,
nsresult aStatus,
const PRUnichar *aMessage)
{
return NS_OK;
}
NS_IMETHODIMP
GeckoDownload::OnSecurityChange (nsIWebProgress *aWebProgress,
nsIRequest *aRequest,
PRUint32 state)
{
return NS_OK;
}
#ifdef HAVE_MOZILLA_1_9
NS_IMETHODIMP
GeckoDownload::OnRefreshAttempted (nsIWebProgress *aWebProgress,
nsIURI *aRefreshURI,
PRInt32 aMillis,
PRBool aSameURI,
PRBool *_retval)
{
return NS_OK;
}
#endif
//*****************************************************************************
// GeckoDownloadFactory
//*****************************************************************************
class GeckoDownloadFactory : public nsIFactory {
public:
NS_DECL_ISUPPORTS
NS_DECL_NSIFACTORY
GeckoDownloadFactory();
virtual ~GeckoDownloadFactory();
};
//*****************************************************************************
NS_IMPL_ISUPPORTS1(GeckoDownloadFactory, nsIFactory)
GeckoDownloadFactory::GeckoDownloadFactory() {
}
GeckoDownloadFactory::~GeckoDownloadFactory() {
}
NS_IMETHODIMP
GeckoDownloadFactory::CreateInstance(nsISupports *aOuter, const nsIID & aIID, void **aResult)
{
NS_ENSURE_ARG_POINTER(aResult);
*aResult = NULL;
GeckoDownload *inst = new GeckoDownload;
if (!inst)
return NS_ERROR_OUT_OF_MEMORY;
nsresult rv = inst->QueryInterface(aIID, aResult);
if (rv != NS_OK) {
// We didn't get the right interface, so clean up
delete inst;
}
return rv;
}
NS_IMETHODIMP
GeckoDownloadFactory::LockFactory(PRBool lock)
{
return NS_OK;
}
//*****************************************************************************
nsresult
NS_NewGeckoDownloadFactory(nsIFactory** aFactory)
{
NS_ENSURE_ARG_POINTER(aFactory);
*aFactory = nsnull;
GeckoDownloadFactory *result = new GeckoDownloadFactory;
if (!result)
return NS_ERROR_OUT_OF_MEMORY;
NS_ADDREF(result);
*aFactory = result;
return NS_OK;
}
<|endoftext|>
|
<commit_before>/*
This file is part of Bohrium and copyright (c) 2012 the Bohrium
team <http://www.bh107.org>.
Bohrium is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3
of the License, or (at your option) any later version.
Bohrium is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the
GNU Lesser General Public License along with Bohrium.
If not, see <http://www.gnu.org/licenses/>.
*/
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/ini_parser.hpp>
#include <boost/property_tree/exceptions.hpp>
#include <boost/algorithm/string.hpp>
#include <cstdlib>
#include <bh_config_parser.hpp>
#ifdef _WIN32
#include <windows.h>
#include <dlfcn-win32.h>
#define HOME_INI_PATH "%APPDATA%\\bohrium\\config.ini"
#define SYSTEM_INI_PATH_1 "%PROGRAMFILES%\\bohrium\\config.ini"
#define SYSTEM_INI_PATH_2 "%PROGRAMFILES%\\bohrium\\config.ini"
//Nasty function renaming
#define snprintf _snprintf
#define strcasecmp _stricmp
#else
#include <dlfcn.h>
#include <limits.h>
#define HOME_INI_PATH "~/.bohrium/config.ini"
#define SYSTEM_INI_PATH_1 "/usr/local/etc/bohrium/config.ini"
#define SYSTEM_INI_PATH_2 "/usr/etc/bohrium/config.ini"
#endif
using namespace std;
using namespace boost;
namespace bohrium {
namespace {
// Path to the config file e.g. ~/.bohrium/config.ini
string get_config_path() {
const char* homepath = HOME_INI_PATH;
const char* syspath1 = SYSTEM_INI_PATH_1;
const char* syspath2 = SYSTEM_INI_PATH_2;
//
// Find the configuration file
//
// Start by looking a path set via environment variable.
const char *env = getenv("BH_CONFIG");
if (env != NULL)
{
FILE *fp = fopen(env,"r");
if( fp )
fclose(fp);
else
env = NULL;//Did not exist.
}
// Then the home directory.
if(env == NULL)
{
#if _WIN32
char _expand_buffer[MAX_PATH];
DWORD result = ExpandEnvironmentStrings(
homepath,
_expand_buffer,
MAX_PATH-1
);
if (result != 0)
{
homepath = _expand_buffer;
}
#else
char* h = getenv("HOME");
if (h != NULL)
{
char _expand_buffer[PATH_MAX];
snprintf(_expand_buffer, PATH_MAX, "%s/%s", h, homepath+1);
homepath = _expand_buffer;
}
#endif
FILE *fp = fopen(homepath,"r");
if( fp ) {
env = homepath;
fclose(fp);
}
}
//And then system-wide.
if(env == NULL)
{
#if _WIN32
char _expand_buffer[MAX_PATH];
DWORD result = ExpandEnvironmentStrings(
syspath1,
_expand_buffer,
MAX_PATH-1
);
if(result != 0)
{
syspath1 = _expand_buffer;
}
#endif
FILE *fp = fopen(syspath1,"r");
if(fp)
{
env = syspath1;
fclose(fp);
}
}
//And then system-wide.
if(env == NULL)
{
#if _WIN32
char _expand_buffer[MAX_PATH];
DWORD result = ExpandEnvironmentStrings(
syspath2,
_expand_buffer,
MAX_PATH-1
);
if(result != 0)
{
syspath2 = _expand_buffer;
}
#endif
FILE *fp = fopen(syspath2,"r");
if(fp)
{
env = syspath2;
fclose(fp);
}
}
// We could not find the configuration file anywhere
if(env == NULL)
{
fprintf(stderr, "Error: Bohrium could not find the config file.\n"
" The search is:\n"
"\t* The environment variable BH_CONFIG.\n"
"\t* The home directory \"%s\".\n"
"\t* The local directory \"%s\".\n"
"\t* And system-wide \"%s\".\n", homepath, syspath1, syspath2);
throw invalid_argument("No config file");
}
return string(env);
}
// Return section/option as an environment variable
// or the empty string if the environment variable wasn't found
string lookup_env(const string §ion, const string &option) {
string s = "BH_" + section + "_" + option;
to_upper(s);
const char *env = getenv(s.c_str());
if (env == NULL) {
return string();
} else {
return string(env);
}
}
}// namespace unnamed
string ConfigParser::lookup(const string §ion, const string &option) const {
//Check environment variable
string ret = lookup_env(section, option);
if (not ret.empty())
return ret;
//Check config file
ret = _config.get<string>(section + "." + option);
//Remove quotes "" or '' and return
if (ret.find_first_of("\"'") == 0 and ret.find_last_of("\"'") == ret.size()-1) {
return ret.substr(1, ret.size()-2);
} else {
return ret;
}
}
ConfigParser::ConfigParser(int stack_level) : file_path(get_config_path()),
stack_level(stack_level) {
// Load the bohrium configuration file
property_tree::ini_parser::read_ini(file_path, _config);
// Find the stack name specified by 'BH_STACK'
const char *env = getenv("BH_STACK");
string stack_name;
if (env == NULL){
stack_name = "default";
} else {
stack_name = env;
}
// Read stack, which is a comma separated list of component names,
// into a vector of component names.
_stack_list = getList("stacks", stack_name);
if (stack_level >= static_cast<int>(_stack_list.size()) or stack_level < -1) {
throw ConfigError("ConfigParser: stack level is out of bound");
}
if (stack_level == -1) {
_default_section = "bridge";
} else {
_default_section = _stack_list[stack_level];
}
}
vector<string> ConfigParser::getList(const std::string §ion,
const std::string &option) const {
vector<string> ret;
string s = get<string>(section, option);
algorithm::split(ret, s, is_any_of("\t, "), token_compress_on);
return ret;
}
string ConfigParser::getChildLibraryPath() const
{
// Do we have a child?
if (static_cast<int>(_stack_list.size()) <= stack_level+1) {
throw ConfigNoChild("ConfigParser: " + getName() + " has no child!");
}
// Our child is our stack level plus one
string child_name = _stack_list[stack_level+1];
return get<string>(child_name, "impl");
}
} //namespace bohrium
<commit_msg>config: now handling dash in env var as underscore<commit_after>/*
This file is part of Bohrium and copyright (c) 2012 the Bohrium
team <http://www.bh107.org>.
Bohrium is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3
of the License, or (at your option) any later version.
Bohrium is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the
GNU Lesser General Public License along with Bohrium.
If not, see <http://www.gnu.org/licenses/>.
*/
#include <string>
#include <algorithm>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/ini_parser.hpp>
#include <boost/property_tree/exceptions.hpp>
#include <boost/algorithm/string.hpp>
#include <cstdlib>
#include <bh_config_parser.hpp>
#ifdef _WIN32
#include <windows.h>
#include <dlfcn-win32.h>
#define HOME_INI_PATH "%APPDATA%\\bohrium\\config.ini"
#define SYSTEM_INI_PATH_1 "%PROGRAMFILES%\\bohrium\\config.ini"
#define SYSTEM_INI_PATH_2 "%PROGRAMFILES%\\bohrium\\config.ini"
//Nasty function renaming
#define snprintf _snprintf
#define strcasecmp _stricmp
#else
#include <dlfcn.h>
#include <limits.h>
#define HOME_INI_PATH "~/.bohrium/config.ini"
#define SYSTEM_INI_PATH_1 "/usr/local/etc/bohrium/config.ini"
#define SYSTEM_INI_PATH_2 "/usr/etc/bohrium/config.ini"
#endif
using namespace std;
using namespace boost;
namespace bohrium {
namespace {
// Path to the config file e.g. ~/.bohrium/config.ini
string get_config_path() {
const char* homepath = HOME_INI_PATH;
const char* syspath1 = SYSTEM_INI_PATH_1;
const char* syspath2 = SYSTEM_INI_PATH_2;
//
// Find the configuration file
//
// Start by looking a path set via environment variable.
const char *env = getenv("BH_CONFIG");
if (env != NULL)
{
FILE *fp = fopen(env,"r");
if( fp )
fclose(fp);
else
env = NULL;//Did not exist.
}
// Then the home directory.
if(env == NULL)
{
#if _WIN32
char _expand_buffer[MAX_PATH];
DWORD result = ExpandEnvironmentStrings(
homepath,
_expand_buffer,
MAX_PATH-1
);
if (result != 0)
{
homepath = _expand_buffer;
}
#else
char* h = getenv("HOME");
if (h != NULL)
{
char _expand_buffer[PATH_MAX];
snprintf(_expand_buffer, PATH_MAX, "%s/%s", h, homepath+1);
homepath = _expand_buffer;
}
#endif
FILE *fp = fopen(homepath,"r");
if( fp ) {
env = homepath;
fclose(fp);
}
}
//And then system-wide.
if(env == NULL)
{
#if _WIN32
char _expand_buffer[MAX_PATH];
DWORD result = ExpandEnvironmentStrings(
syspath1,
_expand_buffer,
MAX_PATH-1
);
if(result != 0)
{
syspath1 = _expand_buffer;
}
#endif
FILE *fp = fopen(syspath1,"r");
if(fp)
{
env = syspath1;
fclose(fp);
}
}
//And then system-wide.
if(env == NULL)
{
#if _WIN32
char _expand_buffer[MAX_PATH];
DWORD result = ExpandEnvironmentStrings(
syspath2,
_expand_buffer,
MAX_PATH-1
);
if(result != 0)
{
syspath2 = _expand_buffer;
}
#endif
FILE *fp = fopen(syspath2,"r");
if(fp)
{
env = syspath2;
fclose(fp);
}
}
// We could not find the configuration file anywhere
if(env == NULL)
{
fprintf(stderr, "Error: Bohrium could not find the config file.\n"
" The search is:\n"
"\t* The environment variable BH_CONFIG.\n"
"\t* The home directory \"%s\".\n"
"\t* The local directory \"%s\".\n"
"\t* And system-wide \"%s\".\n", homepath, syspath1, syspath2);
throw invalid_argument("No config file");
}
return string(env);
}
// Return section/option as an environment variable
// or the empty string if the environment variable wasn't found
string lookup_env(const string §ion, const string &option) {
string s = "BH_" + section + "_" + option;
to_upper(s);
std::replace(s.begin(), s.end(), '-', '_'); // replace all '-' to '_'
std::replace(s.begin(), s.end(), ' ', '_'); // replace all ' ' to '_'
const char *env = getenv(s.c_str());
if (env == NULL) {
return string();
} else {
return string(env);
}
}
}// namespace unnamed
string ConfigParser::lookup(const string §ion, const string &option) const {
//Check environment variable
string ret = lookup_env(section, option);
if (not ret.empty())
return ret;
//Check config file
ret = _config.get<string>(section + "." + option);
//Remove quotes "" or '' and return
if (ret.find_first_of("\"'") == 0 and ret.find_last_of("\"'") == ret.size()-1) {
return ret.substr(1, ret.size()-2);
} else {
return ret;
}
}
ConfigParser::ConfigParser(int stack_level) : file_path(get_config_path()),
stack_level(stack_level) {
// Load the bohrium configuration file
property_tree::ini_parser::read_ini(file_path, _config);
// Find the stack name specified by 'BH_STACK'
const char *env = getenv("BH_STACK");
string stack_name;
if (env == NULL){
stack_name = "default";
} else {
stack_name = env;
}
// Read stack, which is a comma separated list of component names,
// into a vector of component names.
_stack_list = getList("stacks", stack_name);
if (stack_level >= static_cast<int>(_stack_list.size()) or stack_level < -1) {
throw ConfigError("ConfigParser: stack level is out of bound");
}
if (stack_level == -1) {
_default_section = "bridge";
} else {
_default_section = _stack_list[stack_level];
}
}
vector<string> ConfigParser::getList(const std::string §ion,
const std::string &option) const {
vector<string> ret;
string s = get<string>(section, option);
algorithm::split(ret, s, is_any_of("\t, "), token_compress_on);
return ret;
}
string ConfigParser::getChildLibraryPath() const
{
// Do we have a child?
if (static_cast<int>(_stack_list.size()) <= stack_level+1) {
throw ConfigNoChild("ConfigParser: " + getName() + " has no child!");
}
// Our child is our stack level plus one
string child_name = _stack_list[stack_level+1];
return get<string>(child_name, "impl");
}
} //namespace bohrium
<|endoftext|>
|
<commit_before>// -------------------------------------------------------------------------
// @FileName : NFCDataList.h
// @Author : LvSheng.Huang
// @Date : 2012-03-01
// @Module : NFCDataList
//
// -------------------------------------------------------------------------
#include <cstdarg>
#include "NFCDataList.h"
#include "NFIDataList.h"
NFCDataList::NFCDataList()
: NFIDataList()
{
}
NFCDataList::NFCDataList(const char* str, const char* strSplit)
{
Clear();
Split(str, strSplit);
}
NFCDataList::NFCDataList(const NFCDataList& src)
{
Clear();
InnerAppendEx(src, 0, src.GetCount());
}
NFCDataList::NFCDataList(const NFIDataList& src)
{
Clear();
InnerAppendEx(src, 0, src.GetCount());
}
NFCDataList::~NFCDataList()
{
Clear();
};
/*
NFCDataList& NFCDataList::operator=(const NFCDataList& src)
{
Clear();
InnerAppendEx(src, 0, src.GetCount());
return *this;
}
NFCDataList& NFCDataList::operator=(const NFIDataList& src)
{
Clear();
InnerAppendEx(src, 0, src.GetCount());
return *this;
}
*/
//
bool NFCDataList::Append(const NFIDataList& src, const int start, const int count)
{
if (start >= src.GetCount())
{
return false;
}
int end = start + count;
if (end > src.GetCount())
{
return false;
}
InnerAppendEx(src, start, end);
return true;
}
bool NFCDataList::Append(const NFIDataList::TData& TData)
{
if (TData.nType <= TDATA_UNKNOWN
|| TData.nType >= TDATA_MAX)
{
return false;
}
switch (TData.nType)
{
case TDATA_INT:
case TDATA_FLOAT:
case TDATA_DOUBLE:
case TDATA_OBJECT:
{
AddValue(TData.nType, TData.variantData);
}
break;
case TDATA_STRING:
{
const std::string& strData = boost::get<std::string>(TData.variantData);
AddString(strData);
}
break;
default:
break;
}
return false;
}
bool NFCDataList::Append( const NFIDataList& src )
{
return Append(src, 0, src.GetCount());
}
bool NFCDataList::Add(const NFINT64 value)
{
return NFIDataList::AddValue<NFINT64>(TDATA_INT, value);
}
bool NFCDataList::Add(const float value)
{
return AddValue<float>(TDATA_FLOAT, value);
}
bool NFCDataList::Add(const double value)
{
return AddValue<double>(TDATA_DOUBLE, value);
}
bool NFCDataList::Add(const char* value)
{
return AddValue<std::string>(TDATA_STRING, std::string(value));
}
bool NFCDataList::Add(const std::string& value)
{
return AddValue<std::string>(TDATA_STRING, value);
}
bool NFCDataList::Add(const NFIDENTID& value)
{
return AddValue<NFIDENTID>(TDATA_OBJECT, value);
}
bool NFCDataList::Add(const void* value)
{
//return AddNumber<const void*>(TDATA_POINTER, value);
return true;
}
bool NFCDataList::Set(const int index, const NFINT64 value)
{
if (index < GetCount() && index >= 0)
{
return SetValue(index, value);
}
return false;
}
bool NFCDataList::Set(const int index, const float value)
{
if (index < GetCount() && index >= 0)
{
return SetValue(index, value);
}
return false;
}
bool NFCDataList::Set(const int index, const double value)
{
if (index < GetCount() && index >= 0)
{
return SetValue(index, value);
}
return false;
}
bool NFCDataList::Set(const int index, const char* value)
{
if (index < GetCount() && index > 0)
{
return SetString(index, value);
}
return false;
}
bool NFCDataList::Set(const int index, const NFIDENTID& value)
{
if (index < GetCount() && index >= 0)
{
return SetValue<NFIDENTID>(index, value);
}
return false;
}
bool NFCDataList::Set(const int index, const void* value)
{
if (index < GetCount() && index >= 0)
{
//return SetNumber(index, value);
}
return false;
}
NFINT64 NFCDataList::Int(const int index) const
{
if (index < GetCount() && index >= 0)
{
return NumberVal<NFINT64>(index);
}
return 0;
}
float NFCDataList::Float(const int index) const
{
if (index < GetCount() && index >= 0)
{
return NumberVal<float>(index);
}
return 0.0f;
}
double NFCDataList::Double(const int index) const
{
if (index < GetCount() && index >= 0)
{
return NumberVal<double>(index);
}
return 0.0f;
}
const std::string& NFCDataList::String(const int index) const
{
if (index < GetCount() && index >= 0)
{
const NF_SHARE_PTR<TData> var = mvList[index];
if (var && TDATA_STRING == var->nType)
{
return boost::get<const std::string&>(var->variantData);
}
}
return NULL_STR;
}
NFIDENTID NFCDataList::Object(const int index) const
{
// if (index < GetCount() && index >= 0)
// {
// return NumberVal<NFIDENTID>(index);
// }
if (index < GetCount() && index >= 0)
{
NFIDENTID result;
if (index < GetCount() && index >= 0)
{
TDATA_TYPE type = Type(index);
if (type == TDATA_OBJECT)
{
NF_SHARE_PTR<TData> var = GetStack(index);
result = boost::get<NFIDENTID>(var->variantData);
}
}
return result;
}
return NFIDENTID();
}
void* NFCDataList::Pointer(const int index) const
{
if (index < GetCount() && index >= 0)
{
return NumberVal<void*>(index);
}
return NULL;
}
bool NFCDataList::Split(const char* str, const char* strSplit)
{
Clear();
std::string strData(str);
if (strData.empty())
{
return true;
}
std::string temstrSplit(strSplit);
std::string::size_type pos;
strData += temstrSplit;
std::string::size_type size = strData.length();
for (std::string::size_type i = 0; i < size; i++)
{
pos = int(strData.find(temstrSplit, i));
if (pos < size)
{
std::string strSub = strData.substr(i, pos - i);
Add(strSub.c_str());
i = pos + temstrSplit.size() - 1;
}
}
return true;
}
TDATA_TYPE NFCDataList::Type(const int index) const
{
if (index >= GetCount() || index < 0)
{
return TDATA_UNKNOWN;
}
if (index < STACK_SIZE)
{
return mvList[index]->nType;
}
else
{
const NF_SHARE_PTR<TData> pData = GetStack(index);
if (pData)
{
return pData->nType;
}
}
return TDATA_UNKNOWN;
}
bool NFCDataList::TypeEx(const int nType, ...) const
{
bool bRet = true;
if (TDATA_UNKNOWN == nType)
{
bRet = false;
return bRet;
}
TDATA_TYPE pareType = (TDATA_TYPE)nType;
va_list arg_ptr;
va_start(arg_ptr, nType);
int index = 0;
while (pareType != TDATA_UNKNOWN)
{
//Ƚ
TDATA_TYPE varType = Type(index);
if (varType != pareType)
{
bRet = false;
break;
}
++index;
pareType = (TDATA_TYPE)va_arg(arg_ptr, int); //ȡһ
}
va_end(arg_ptr); //
return bRet;
}
bool NFCDataList::Concat(const NFIDataList& src)
{
InnerAppendEx(src, 0, src.GetCount());
return true;
}
void NFCDataList::Clear()
{
mnUseSize = 0;
//mnCapacity = STACK_SIZE;
//8Ժ
if (mvList.size() > STACK_SIZE)
{
for (int i = 0; i < STACK_SIZE; ++i)
{
mvList[i]->nType = TDATA_UNKNOWN;
}
mvList.erase(mvList.begin() + 8, mvList.end());
}
}
bool NFCDataList::IsEmpty() const
{
return (0 == mnUseSize);
}
int NFCDataList::GetCount() const
{
return mnUseSize;
}
void NFCDataList::InnerAppendEx(const NFIDataList& src, const int start, const int end)
{
for (int i = start; i < end; ++i)
{
TDATA_TYPE vType = src.Type(i);
switch (vType)
{
case TDATA_INT:
AddValue<NFINT64>(vType, src.Int(i));
break;
case TDATA_FLOAT:
AddValue<float>(vType, src.Float(i));
break;
case TDATA_DOUBLE:
AddValue<double>(vType, src.Double(i));
break;
case TDATA_STRING:
AddString(src.String(i).c_str());
break;
case TDATA_OBJECT:
AddValue<NFIDENTID>(vType, src.Object(i));
break;
//case TDATA_POINTER:
// AddNumber<void*>(vType, src.NumberVal<void*>(i));
// break;
default:
//Assert(0);
break;
}
}
}
std::string NFCDataList::StringValEx(const int index, const bool bForce) const
{
if (index < GetCount() && index >= 0)
{
TDATA_TYPE type = Type(index);
if (type == TDATA_STRING)
{
return String(index);
}
// const NF_SHARE_PTR<NFIDataList::TData> var = GetStack(index);
// if (var)
// {
// //return boost::lexical_cast<std::string>(var->variantData);
// }
}
return NULL_STR;
}
bool NFCDataList::ToString(std::string& str, const char* strSplit) const
{
for (int i = 0; i < GetCount(); ++i)
{
std::string strVal = StringValEx(i, true);
str += strVal;
str += strSplit;
}
std::string strTempSplit(strSplit);
std::string::size_type nPos = str.rfind(strSplit);
if (nPos == str.length() - strTempSplit.length())
{
str = str.substr(0, nPos);
}
return true;
}
<commit_msg>fixed bug for set data<commit_after>// -------------------------------------------------------------------------
// @FileName : NFCDataList.h
// @Author : LvSheng.Huang
// @Date : 2012-03-01
// @Module : NFCDataList
//
// -------------------------------------------------------------------------
#include <cstdarg>
#include "NFCDataList.h"
#include "NFIDataList.h"
NFCDataList::NFCDataList()
: NFIDataList()
{
}
NFCDataList::NFCDataList(const char* str, const char* strSplit)
{
Clear();
Split(str, strSplit);
}
NFCDataList::NFCDataList(const NFCDataList& src)
{
Clear();
InnerAppendEx(src, 0, src.GetCount());
}
NFCDataList::NFCDataList(const NFIDataList& src)
{
Clear();
InnerAppendEx(src, 0, src.GetCount());
}
NFCDataList::~NFCDataList()
{
Clear();
};
/*
NFCDataList& NFCDataList::operator=(const NFCDataList& src)
{
Clear();
InnerAppendEx(src, 0, src.GetCount());
return *this;
}
NFCDataList& NFCDataList::operator=(const NFIDataList& src)
{
Clear();
InnerAppendEx(src, 0, src.GetCount());
return *this;
}
*/
//
bool NFCDataList::Append(const NFIDataList& src, const int start, const int count)
{
if (start >= src.GetCount())
{
return false;
}
int end = start + count;
if (end > src.GetCount())
{
return false;
}
InnerAppendEx(src, start, end);
return true;
}
bool NFCDataList::Append(const NFIDataList::TData& TData)
{
if (TData.nType <= TDATA_UNKNOWN
|| TData.nType >= TDATA_MAX)
{
return false;
}
switch (TData.nType)
{
case TDATA_INT:
case TDATA_FLOAT:
case TDATA_DOUBLE:
case TDATA_OBJECT:
{
AddValue(TData.nType, TData.variantData);
}
break;
case TDATA_STRING:
{
const std::string& strData = boost::get<std::string>(TData.variantData);
AddString(strData);
}
break;
default:
break;
}
return false;
}
bool NFCDataList::Append( const NFIDataList& src )
{
return Append(src, 0, src.GetCount());
}
bool NFCDataList::Add(const NFINT64 value)
{
return NFIDataList::AddValue<NFINT64>(TDATA_INT, value);
}
bool NFCDataList::Add(const float value)
{
return AddValue<float>(TDATA_FLOAT, value);
}
bool NFCDataList::Add(const double value)
{
return AddValue<double>(TDATA_DOUBLE, value);
}
bool NFCDataList::Add(const char* value)
{
return AddValue<std::string>(TDATA_STRING, std::string(value));
}
bool NFCDataList::Add(const std::string& value)
{
return AddValue<std::string>(TDATA_STRING, value);
}
bool NFCDataList::Add(const NFIDENTID& value)
{
return AddValue<NFIDENTID>(TDATA_OBJECT, value);
}
bool NFCDataList::Add(const void* value)
{
//return AddNumber<const void*>(TDATA_POINTER, value);
return true;
}
bool NFCDataList::Set(const int index, const NFINT64 value)
{
if (index < GetCount() && index >= 0)
{
return SetValue(index, value);
}
return false;
}
bool NFCDataList::Set(const int index, const float value)
{
if (index < GetCount() && index >= 0)
{
return SetValue(index, value);
}
return false;
}
bool NFCDataList::Set(const int index, const double value)
{
if (index < GetCount() && index >= 0)
{
return SetValue(index, value);
}
return false;
}
bool NFCDataList::Set(const int index, const char* value)
{
if (index < GetCount() && index >= 0)
{
return SetString(index, value);
}
return false;
}
bool NFCDataList::Set(const int index, const NFIDENTID& value)
{
if (index < GetCount() && index >= 0)
{
return SetValue<NFIDENTID>(index, value);
}
return false;
}
bool NFCDataList::Set(const int index, const void* value)
{
if (index < GetCount() && index >= 0)
{
//return SetNumber(index, value);
}
return false;
}
NFINT64 NFCDataList::Int(const int index) const
{
if (index < GetCount() && index >= 0)
{
return NumberVal<NFINT64>(index);
}
return 0;
}
float NFCDataList::Float(const int index) const
{
if (index < GetCount() && index >= 0)
{
return NumberVal<float>(index);
}
return 0.0f;
}
double NFCDataList::Double(const int index) const
{
if (index < GetCount() && index >= 0)
{
return NumberVal<double>(index);
}
return 0.0f;
}
const std::string& NFCDataList::String(const int index) const
{
if (index < GetCount() && index >= 0)
{
const NF_SHARE_PTR<TData> var = mvList[index];
if (var && TDATA_STRING == var->nType)
{
return boost::get<const std::string&>(var->variantData);
}
}
return NULL_STR;
}
NFIDENTID NFCDataList::Object(const int index) const
{
// if (index < GetCount() && index >= 0)
// {
// return NumberVal<NFIDENTID>(index);
// }
if (index < GetCount() && index >= 0)
{
NFIDENTID result;
if (index < GetCount() && index >= 0)
{
TDATA_TYPE type = Type(index);
if (type == TDATA_OBJECT)
{
NF_SHARE_PTR<TData> var = GetStack(index);
result = boost::get<NFIDENTID>(var->variantData);
}
}
return result;
}
return NFIDENTID();
}
void* NFCDataList::Pointer(const int index) const
{
if (index < GetCount() && index >= 0)
{
return NumberVal<void*>(index);
}
return NULL;
}
bool NFCDataList::Split(const char* str, const char* strSplit)
{
Clear();
std::string strData(str);
if (strData.empty())
{
return true;
}
std::string temstrSplit(strSplit);
std::string::size_type pos;
strData += temstrSplit;
std::string::size_type size = strData.length();
for (std::string::size_type i = 0; i < size; i++)
{
pos = int(strData.find(temstrSplit, i));
if (pos < size)
{
std::string strSub = strData.substr(i, pos - i);
Add(strSub.c_str());
i = pos + temstrSplit.size() - 1;
}
}
return true;
}
TDATA_TYPE NFCDataList::Type(const int index) const
{
if (index >= GetCount() || index < 0)
{
return TDATA_UNKNOWN;
}
if (index < STACK_SIZE)
{
return mvList[index]->nType;
}
else
{
const NF_SHARE_PTR<TData> pData = GetStack(index);
if (pData)
{
return pData->nType;
}
}
return TDATA_UNKNOWN;
}
bool NFCDataList::TypeEx(const int nType, ...) const
{
bool bRet = true;
if (TDATA_UNKNOWN == nType)
{
bRet = false;
return bRet;
}
TDATA_TYPE pareType = (TDATA_TYPE)nType;
va_list arg_ptr;
va_start(arg_ptr, nType);
int index = 0;
while (pareType != TDATA_UNKNOWN)
{
//Ƚ
TDATA_TYPE varType = Type(index);
if (varType != pareType)
{
bRet = false;
break;
}
++index;
pareType = (TDATA_TYPE)va_arg(arg_ptr, int); //ȡһ
}
va_end(arg_ptr); //
return bRet;
}
bool NFCDataList::Concat(const NFIDataList& src)
{
InnerAppendEx(src, 0, src.GetCount());
return true;
}
void NFCDataList::Clear()
{
mnUseSize = 0;
//mnCapacity = STACK_SIZE;
//8Ժ
if (mvList.size() > STACK_SIZE)
{
for (int i = 0; i < STACK_SIZE; ++i)
{
mvList[i]->nType = TDATA_UNKNOWN;
}
mvList.erase(mvList.begin() + 8, mvList.end());
}
}
bool NFCDataList::IsEmpty() const
{
return (0 == mnUseSize);
}
int NFCDataList::GetCount() const
{
return mnUseSize;
}
void NFCDataList::InnerAppendEx(const NFIDataList& src, const int start, const int end)
{
for (int i = start; i < end; ++i)
{
TDATA_TYPE vType = src.Type(i);
switch (vType)
{
case TDATA_INT:
AddValue<NFINT64>(vType, src.Int(i));
break;
case TDATA_FLOAT:
AddValue<float>(vType, src.Float(i));
break;
case TDATA_DOUBLE:
AddValue<double>(vType, src.Double(i));
break;
case TDATA_STRING:
AddString(src.String(i).c_str());
break;
case TDATA_OBJECT:
AddValue<NFIDENTID>(vType, src.Object(i));
break;
//case TDATA_POINTER:
// AddNumber<void*>(vType, src.NumberVal<void*>(i));
// break;
default:
//Assert(0);
break;
}
}
}
std::string NFCDataList::StringValEx(const int index, const bool bForce) const
{
if (index < GetCount() && index >= 0)
{
TDATA_TYPE type = Type(index);
if (type == TDATA_STRING)
{
return String(index);
}
// const NF_SHARE_PTR<NFIDataList::TData> var = GetStack(index);
// if (var)
// {
// //return boost::lexical_cast<std::string>(var->variantData);
// }
}
return NULL_STR;
}
bool NFCDataList::ToString(std::string& str, const char* strSplit) const
{
for (int i = 0; i < GetCount(); ++i)
{
std::string strVal = StringValEx(i, true);
str += strVal;
str += strSplit;
}
std::string strTempSplit(strSplit);
std::string::size_type nPos = str.rfind(strSplit);
if (nPos == str.length() - strTempSplit.length())
{
str = str.substr(0, nPos);
}
return true;
}
<|endoftext|>
|
<commit_before>// Common libraries
#include "version.h"
#include <stdio.h>
// PJON library
#define TS_RESPONSE_TIME_OUT 35000
#define PJON_INCLUDE_TS true // Include only ThroughSerial
#ifndef RPI
#define RPI true
#endif
#include "PJON/PJON.h"
#include <inttypes.h>
#include <stdlib.h>
#include <string.h>
// RPI serial interface
#include <wiringPi.h>
#include <wiringSerial.h>
// gRPC library
#include <iostream>
#include <memory>
#include <grpc++/grpc++.h>
#include "pjongrpc.grpc.pb.h"
using grpc::Server;
using grpc::ServerBuilder;
using grpc::ServerContext;
using grpc::Status;
using pjongrpc::Arduino_Request;
using pjongrpc::Arduino_Reply;
using pjongrpc::Arduino;
// TODO: Find the way to change in from command line
PJON<ThroughSerial> bus(1);
uint64_t rcvd_cnt = 0;
std::string response;
static void receiver_function(
uint8_t *payload,
uint16_t length,
const PJON_Packet_Info &packet_info){
for (uint32_t i = 0; i != length; i++){
response += payload[i];
}
rcvd_cnt += 1;
std::cout << "#RCV snd_id=" << std::to_string(packet_info.sender_id)
<< " snd_net=";
for (uint32_t i = 0; i < sizeof(packet_info.sender_bus_id); i++) {
std::cout << std::to_string(packet_info.sender_bus_id[i]);
if (i < sizeof(packet_info.sender_bus_id) - 1)
std::cout << ".";
}
std::cout << " rcv_id=" << std::to_string(packet_info.receiver_id)
<< " rcv_net=";
for (uint32_t i = 0; i < sizeof(packet_info.receiver_bus_id); i++) {
std::cout << std::to_string(packet_info.receiver_bus_id[i]);
if (i < sizeof(packet_info.receiver_bus_id) - 1)
std::cout << ".";
}
std::cout << " id=" << std::to_string(packet_info.id)
<< " hdr=" << std::to_string(packet_info.header)
<< " pckt_cnt=" << std::to_string(rcvd_cnt)
<< " len=" << length
<< " data=" << response;
std::cout << std::endl;
};
static void error_handler_function(uint8_t code, uint8_t data) {
std::cout << "#ERR code=" << std::to_string(code);
std::cout << " data=" << std::to_string(data);
std::cout << std::endl;
};
bool is_enough_args(int argc, char **argv) {
if (argc < 4)
return false;
return true;
}
bool is_first_arg_com_port(int argc, char **argv) {
if (std::string(argv[1]).find("tty") != std::string::npos)
return true;
return false;
}
bool is_second_arg_bitrate(int argc, char **argv) {
if (0 < std::stoi(std::string(argv[2])))
if(std::stoi(std::string(argv[2])) <= 153600)
return true;
return false;
}
bool is_third_arg_bus_id(int argc, char **argv) {
if (0 <= std::stoi(std::string(argv[3])))
if (std::stoi(std::string(argv[3])) <= 255)
return true;
return false;
}
void print_usage_help() {
std::cout
<< "PJON_gRPC - gRPC server-client for PJON bus\n"
<< "VERSION: " << PJON_gRPC_SERVER_VERSION << "\n"
<< "\n"
<< "usage: pjon_grpc_server <COM PORT> <BITRATE> <NODE ID>\n"
<< " \\ \\ \\\n"
<< " \\ \\ 0-255\n"
<< " /dev/ttyXXXX 1200 - 153600\n"
<< std::endl
<< "example: pjon_grpc_server /dev/ttyUSB0 57600 1" << std::endl
<< std::endl
<< "other options:" << std::endl
<< " help - print this help" << std::endl
<< "version - displays program version" << std::endl
<< "--------------------------------------" << std::endl
;
}
void pjon_communication(int node_id, const char* data) {
printf("Attempting to send a packet... \n");
bus.send(node_id, data, strlen(data));
printf("Attempting to roll bus... \n");
bus.update();
printf("Attempting to receive from bus... \n");
bus.receive(5000000);
}
class ArduinoServiceImpl final : public Arduino::Service {
Status RPiArduino(ServerContext* context, const Arduino_Request* request,
Arduino_Reply* reply) override {
response = "";
int node_id = request->node_id();
const char* data = request->data().c_str();
pjon_communication(node_id, data);
reply->set_message(response);
return Status::OK;
}
};
void run_server() {
std::string server_address("0.0.0.0:50051");
ArduinoServiceImpl service;
ServerBuilder builder;
builder.AddListeningPort(server_address, grpc::InsecureServerCredentials());
builder.RegisterService(&service);
std::unique_ptr<Server> server(builder.BuildAndStart());
std::cout << "Server listening on " << server_address << std::endl;
server->Wait();
}
int main(int argc, char** argv) {
if (argc == 2) {
if (std::string(argv[1]) == "help") {
print_usage_help();
return 0;
} else if (std::string(argv[1]) == "version") {
std::cout << "VERSION: " << PJON_gRPC_SERVER_VERSION << "\n";
return 0;
}
print_usage_help();
std::cerr << "ERROR: option not supported\n";
return 1;
}
if (!is_enough_args(argc, argv)) {
print_usage_help();
std::cerr << "ERROR: not enough args\n";
return 1;
}
if (!is_first_arg_com_port(argc, argv)) {
print_usage_help();
std::cerr << "ERROR: first arg <COM PORT> should be /dev/ttyXXXX\n";
return 1;
}
if (!is_second_arg_bitrate(argc, argv)) {
print_usage_help();
std::cerr << "ERROR: second arg <BITRATE> should specify bitrate 1 - 153600 like 2400, 19200, 38400, 57600, 115200, 153600\n";
return 1;
}
if (!is_third_arg_bus_id(argc, argv)) {
print_usage_help();
std::cerr << "ERROR: third arg <NODE ID> should specify bus address 0 - 255\n";
return 1;
}
char* com_str = argv[1];
int bitRate = std::stoi(std::string(argv[2]));
// TODO: How we can define it globally?
// PJON<ThroughSerial> bus(std::stoi(std::string(argv[3])));
try {
printf("Opening serial... \n");
int s = serialOpen(com_str, bitRate);
if (int(s) < 0) {
printf("Serial open fail!\n");
exit (EXIT_FAILURE);
}
if (wiringPiSetup() == -1) {
printf("WiringPi setup fail");
exit (EXIT_FAILURE);
}
printf("Setting serial... \n");
bus.strategy.set_serial(s);
bus.strategy.set_baud_rate(bitRate);
printf("Opening bus... \n");
bus.begin();
bus.set_receiver(receiver_function);
bus.set_error(error_handler_function);
bus.set_synchronous_acknowledge(true);
// crc_8 doesn't work correctly with 8.x PJON version, can be fixed in v9.x
bus.set_crc_32(true);
run_server();
return 0;
}
catch (const char* msg) {
std::cout << "exc: "
<< msg
<< std::endl;
return 1;
}
}
<commit_msg>some changes<commit_after>// Common libraries
#include "version.h"
#include <stdio.h>
// PJON library
#define TS_RESPONSE_TIME_OUT 75000
#define PJON_INCLUDE_TS true // Include only ThroughSerial
#ifndef RPI
#define RPI true
#endif
#include "PJON/PJON.h"
#include <inttypes.h>
#include <stdlib.h>
#include <string.h>
// RPI serial interface
#include <wiringPi.h>
#include <wiringSerial.h>
// gRPC library
#include <iostream>
#include <memory>
#include <grpc++/grpc++.h>
#include "pjongrpc.grpc.pb.h"
using grpc::Server;
using grpc::ServerBuilder;
using grpc::ServerContext;
using grpc::Status;
using pjongrpc::Arduino_Request;
using pjongrpc::Arduino_Reply;
using pjongrpc::Arduino;
// TODO: Find the way to change in from command line
PJON<ThroughSerial> bus(1);
uint64_t rcvd_cnt = 0;
std::string response;
static void receiver_function(
uint8_t *payload,
uint16_t length,
const PJON_Packet_Info &packet_info){
for (uint32_t i = 0; i != length; i++){
response += payload[i];
}
rcvd_cnt += 1;
std::cout << "#RCV snd_id=" << std::to_string(packet_info.sender_id)
<< " snd_net=";
for (uint32_t i = 0; i < sizeof(packet_info.sender_bus_id); i++) {
std::cout << std::to_string(packet_info.sender_bus_id[i]);
if (i < sizeof(packet_info.sender_bus_id) - 1)
std::cout << ".";
}
std::cout << " rcv_id=" << std::to_string(packet_info.receiver_id)
<< " rcv_net=";
for (uint32_t i = 0; i < sizeof(packet_info.receiver_bus_id); i++) {
std::cout << std::to_string(packet_info.receiver_bus_id[i]);
if (i < sizeof(packet_info.receiver_bus_id) - 1)
std::cout << ".";
}
std::cout << " id=" << std::to_string(packet_info.id)
<< " hdr=" << std::to_string(packet_info.header)
<< " pckt_cnt=" << std::to_string(rcvd_cnt)
<< " len=" << length
<< " data=" << response;
std::cout << std::endl;
};
static void error_handler_function(uint8_t code, uint8_t data) {
std::cout << "#ERR code=" << std::to_string(code);
std::cout << " data=" << std::to_string(data);
std::cout << std::endl;
};
bool is_enough_args(int argc, char **argv) {
if (argc < 4)
return false;
return true;
}
bool is_first_arg_com_port(int argc, char **argv) {
if (std::string(argv[1]).find("tty") != std::string::npos)
return true;
return false;
}
bool is_second_arg_bitrate(int argc, char **argv) {
if (0 < std::stoi(std::string(argv[2])))
if(std::stoi(std::string(argv[2])) <= 153600)
return true;
return false;
}
bool is_third_arg_bus_id(int argc, char **argv) {
if (0 <= std::stoi(std::string(argv[3])))
if (std::stoi(std::string(argv[3])) <= 255)
return true;
return false;
}
void print_usage_help() {
std::cout
<< "PJON_gRPC - gRPC server-client for PJON bus\n"
<< "VERSION: " << PJON_gRPC_SERVER_VERSION << "\n"
<< "\n"
<< "usage: pjon_grpc_server <COM PORT> <BITRATE> <NODE ID>\n"
<< " \\ \\ \\\n"
<< " \\ \\ 0-255\n"
<< " /dev/ttyXXXX 1200 - 153600\n"
<< std::endl
<< "example: pjon_grpc_server /dev/ttyUSB0 57600 1" << std::endl
<< std::endl
<< "other options:" << std::endl
<< " help - print this help" << std::endl
<< "version - displays program version" << std::endl
<< "--------------------------------------" << std::endl
;
}
void pjon_communication(int node_id, const char* data) {
printf(data);
printf("\n");
printf("Attempting to send a packet... \n");
bus.send(node_id, data, strlen(data));
printf("Attempting to roll bus... \n");
bus.update();
printf("Attempting to receive from bus... \n");
bus.receive(5000000);
//uint32_t time = micros();
//while(micros() - time < 5000000) { bus.update(); bus.receive(); }
}
class ArduinoServiceImpl final : public Arduino::Service {
Status RPiArduino(ServerContext* context, const Arduino_Request* request,
Arduino_Reply* reply) override {
response = "";
int node_id = request->node_id();
const char* data = request->data().c_str();
pjon_communication(node_id, data);
reply->set_message(response);
return Status::OK;
}
};
void run_server() {
std::string server_address("0.0.0.0:50051");
ArduinoServiceImpl service;
ServerBuilder builder;
builder.AddListeningPort(server_address, grpc::InsecureServerCredentials());
builder.RegisterService(&service);
std::unique_ptr<Server> server(builder.BuildAndStart());
std::cout << "Server listening on " << server_address << std::endl;
server->Wait();
}
int main(int argc, char** argv) {
if (argc == 2) {
if (std::string(argv[1]) == "help") {
print_usage_help();
return 0;
} else if (std::string(argv[1]) == "version") {
std::cout << "VERSION: " << PJON_gRPC_SERVER_VERSION << "\n";
return 0;
}
print_usage_help();
std::cerr << "ERROR: option not supported\n";
return 1;
}
if (!is_enough_args(argc, argv)) {
print_usage_help();
std::cerr << "ERROR: not enough args\n";
return 1;
}
if (!is_first_arg_com_port(argc, argv)) {
print_usage_help();
std::cerr << "ERROR: first arg <COM PORT> should be /dev/ttyXXXX\n";
return 1;
}
if (!is_second_arg_bitrate(argc, argv)) {
print_usage_help();
std::cerr << "ERROR: second arg <BITRATE> should specify bitrate 1 - 153600 like 2400, 19200, 38400, 57600, 115200, 153600\n";
return 1;
}
if (!is_third_arg_bus_id(argc, argv)) {
print_usage_help();
std::cerr << "ERROR: third arg <NODE ID> should specify bus address 0 - 255\n";
return 1;
}
char* com_str = argv[1];
int bitRate = std::stoi(std::string(argv[2]));
// TODO: How we can define it globally?
// PJON<ThroughSerial> bus(std::stoi(std::string(argv[3])));
try {
printf("Opening serial... \n");
int s = serialOpen(com_str, bitRate);
if (int(s) < 0) {
printf("Serial open fail!\n");
exit (EXIT_FAILURE);
}
if (wiringPiSetup() == -1) {
printf("WiringPi setup fail");
exit (EXIT_FAILURE);
}
printf("Setting serial... \n");
bus.strategy.set_serial(s);
bus.strategy.set_baud_rate(bitRate);
printf("Opening bus... \n");
bus.begin();
bus.set_receiver(receiver_function);
bus.set_error(error_handler_function);
bus.set_synchronous_acknowledge(true);
// crc_8 doesn't work correctly with 8.x PJON version, can be fixed in v9.x
bus.set_crc_32(true);
run_server();
return 0;
}
catch (const char* msg) {
std::cout << "exc: "
<< msg
<< std::endl;
return 1;
}
}
<|endoftext|>
|
<commit_before>#ifndef STRONG_TYPEDEF_HPP
#define STRONG_TYPEDEF_HPP
#include <type_traits>
#include <functional>
namespace osrm
{
/* Creates strongly typed wrappers around scalar types.
* Useful for stopping accidental assignment of lats to lons,
* etc. Also clarifies what this random "int" value is
* being used for.
*/
#define OSRM_STRONG_TYPEDEF(From, To) \
class To final \
{ \
static_assert(std::is_arithmetic<From>(), ""); \
From x; \
\
public: \
To() = default; \
explicit To(const From x_) : x(x_) {} \
explicit operator From &() { return x; } \
explicit operator const From &() const { return x; } \
bool operator<(const To &z_) const { return x < static_cast<const From>(z_); } \
bool operator>(const To &z_) const { return x > static_cast<const From>(z_); } \
bool operator<=(const To &z_) const { return x <= static_cast<const From>(z_); } \
bool operator>=(const To &z_) const { return x >= static_cast<const From>(z_); } \
bool operator==(const To &z_) const { return x == static_cast<const From>(z_); } \
bool operator!=(const To &z_) const { return x != static_cast<const From>(z_); } \
}; \
inline From To##_to_##From(To to) { return static_cast<From>(to); } \
namespace std \
{ \
template <> struct hash<To> \
{ \
std::size_t operator()(const To &k) const \
{ \
return std::hash<From>()(static_cast<const From>(k)); \
} \
}; \
}
}
#endif // OSRM_STRONG_TYPEDEF_HPP
<commit_msg>Add operator<< to OSRM_STRONG_TYPEDEF<commit_after>#ifndef STRONG_TYPEDEF_HPP
#define STRONG_TYPEDEF_HPP
#include <iostream>
#include <type_traits>
#include <functional>
namespace osrm
{
/* Creates strongly typed wrappers around scalar types.
* Useful for stopping accidental assignment of lats to lons,
* etc. Also clarifies what this random "int" value is
* being used for.
*/
#define OSRM_STRONG_TYPEDEF(From, To) \
class To final \
{ \
static_assert(std::is_arithmetic<From>(), ""); \
From x; \
friend std::ostream& operator<<(std::ostream& stream, const To& inst); \
\
public: \
To() = default; \
explicit To(const From x_) : x(x_) {} \
explicit operator From &() { return x; } \
explicit operator const From &() const { return x; } \
bool operator<(const To &z_) const { return x < static_cast<const From>(z_); } \
bool operator>(const To &z_) const { return x > static_cast<const From>(z_); } \
bool operator<=(const To &z_) const { return x <= static_cast<const From>(z_); } \
bool operator>=(const To &z_) const { return x >= static_cast<const From>(z_); } \
bool operator==(const To &z_) const { return x == static_cast<const From>(z_); } \
bool operator!=(const To &z_) const { return x != static_cast<const From>(z_); } \
}; \
inline From To##_to_##From(To to) { return static_cast<From>(to); } \
namespace std \
{ \
template <> struct hash<To> \
{ \
std::size_t operator()(const To &k) const \
{ \
return std::hash<From>()(static_cast<const From>(k)); \
} \
}; \
} \
inline std::ostream& operator<<(std::ostream& stream, const To& inst) { \
return stream << #To << '(' << inst.x << ')'; \
}
}
#endif // OSRM_STRONG_TYPEDEF_HPP
<|endoftext|>
|
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/notifications/desktop_notification_service.h"
#include "base/memory/ref_counted.h"
#include "base/message_loop.h"
#include "base/synchronization/waitable_event.h"
#include "chrome/browser/notifications/notifications_prefs_cache.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/prefs/scoped_user_pref_update.h"
#include "chrome/common/pref_names.h"
#include "chrome/test/testing_profile.h"
#include "content/browser/browser_thread.h"
#include "content/browser/renderer_host/test_render_view_host.h"
#include "grit/generated_resources.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebNotificationPresenter.h"
namespace {
// NotificationsPrefsCache wants to be called on the IO thread. This class
// routes calls to the cache on the IO thread.
class ThreadProxy : public base::RefCountedThreadSafe<ThreadProxy> {
public:
ThreadProxy()
: io_event_(false, false),
ui_event_(false, false),
permission_(0) {
// The current message loop was already initalized by the test superclass.
ui_thread_.reset(
new BrowserThread(BrowserThread::UI, MessageLoop::current()));
// Create IO thread, start its message loop.
io_thread_.reset(new BrowserThread(BrowserThread::IO));
io_thread_->Start();
// Calling PauseIOThread() here isn't safe, because the runnable method
// could complete before the constructor is done, deleting |this|.
}
int CacheHasPermission(NotificationsPrefsCache* cache, const GURL& url) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
NewRunnableMethod(this, &ThreadProxy::CacheHasPermissionIO,
make_scoped_refptr(cache), url));
io_event_.Signal();
ui_event_.Wait(); // Wait for IO thread to be done.
BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
NewRunnableMethod(this, &ThreadProxy::PauseIOThreadIO));
return permission_;
}
void PauseIOThread() {
BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
NewRunnableMethod(this, &ThreadProxy::PauseIOThreadIO));
}
void DrainIOThread() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
io_event_.Signal();
io_thread_->Stop();
}
private:
friend class base::RefCountedThreadSafe<ThreadProxy>;
~ThreadProxy() {
DrainIOThread();
}
void PauseIOThreadIO() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
io_event_.Wait();
}
void CacheHasPermissionIO(NotificationsPrefsCache* cache, const GURL& url) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
permission_ = cache->HasPermission(url);
ui_event_.Signal();
}
base::WaitableEvent io_event_;
base::WaitableEvent ui_event_;
scoped_ptr<BrowserThread> ui_thread_;
scoped_ptr<BrowserThread> io_thread_;
int permission_;
};
class DesktopNotificationServiceTest : public RenderViewHostTestHarness {
public:
DesktopNotificationServiceTest() {
}
virtual void SetUp() {
RenderViewHostTestHarness::SetUp();
proxy_ = new ThreadProxy;
proxy_->PauseIOThread();
// Creates the service, calls InitPrefs() on it which loads data from the
// profile into the cache and then puts the cache in io thread mode.
service_ = profile()->GetDesktopNotificationService();
cache_ = service_->prefs_cache();
}
virtual void TearDown() {
// The io thread's waiting on the io_event_ might hold a ref to |proxy_|,
// preventing its destruction. Clear that ref.
proxy_->DrainIOThread();
RenderViewHostTestHarness::TearDown();
}
DesktopNotificationService* service_;
NotificationsPrefsCache* cache_;
scoped_refptr<ThreadProxy> proxy_;
};
TEST_F(DesktopNotificationServiceTest, DefaultContentSettingSentToCache) {
// The default pref registered in DesktopNotificationService is "ask",
// and that's what sent to the cache.
EXPECT_EQ(CONTENT_SETTING_ASK, cache_->CachedDefaultContentSetting());
// Change the default content setting. This will post a task on the IO thread
// to update the cache.
service_->SetDefaultContentSetting(CONTENT_SETTING_BLOCK);
// The updated pref shouldn't be sent to the cache immediately.
EXPECT_EQ(CONTENT_SETTING_ASK, cache_->CachedDefaultContentSetting());
// Run IO thread tasks.
proxy_->DrainIOThread();
// Now that IO thread events have been processed, it should be there.
EXPECT_EQ(CONTENT_SETTING_BLOCK, cache_->CachedDefaultContentSetting());
}
TEST_F(DesktopNotificationServiceTest, SettingsForSchemes) {
GURL url("file:///html/test.html");
EXPECT_EQ(CONTENT_SETTING_ASK, cache_->CachedDefaultContentSetting());
EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionNotAllowed,
proxy_->CacheHasPermission(cache_, url));
service_->GrantPermission(url);
EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionAllowed,
proxy_->CacheHasPermission(cache_, url));
service_->DenyPermission(url);
EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionDenied,
proxy_->CacheHasPermission(cache_, url));
GURL https_url("https://testurl");
GURL http_url("http://testurl");
EXPECT_EQ(CONTENT_SETTING_ASK, cache_->CachedDefaultContentSetting());
EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionNotAllowed,
proxy_->CacheHasPermission(cache_, http_url));
EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionNotAllowed,
proxy_->CacheHasPermission(cache_, https_url));
service_->GrantPermission(https_url);
EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionAllowed,
proxy_->CacheHasPermission(cache_, https_url));
EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionNotAllowed,
proxy_->CacheHasPermission(cache_, http_url));
service_->DenyPermission(http_url);
EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionDenied,
proxy_->CacheHasPermission(cache_, http_url));
EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionAllowed,
proxy_->CacheHasPermission(cache_, https_url));
}
TEST_F(DesktopNotificationServiceTest, GrantPermissionSentToCache) {
GURL url("http://allowed.com");
EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionNotAllowed,
proxy_->CacheHasPermission(cache_, url));
service_->GrantPermission(url);
EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionAllowed,
proxy_->CacheHasPermission(cache_, url));
}
TEST_F(DesktopNotificationServiceTest, DenyPermissionSentToCache) {
GURL url("http://denied.com");
EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionNotAllowed,
proxy_->CacheHasPermission(cache_, url));
service_->DenyPermission(url);
EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionDenied,
proxy_->CacheHasPermission(cache_, url));
}
TEST_F(DesktopNotificationServiceTest, PrefChangesSentToCache) {
PrefService* prefs = profile()->GetPrefs();
ListValue* allowed_sites =
prefs->GetMutableList(prefs::kDesktopNotificationAllowedOrigins);
{
allowed_sites->Append(new StringValue(GURL("http://allowed.com").spec()));
ScopedUserPrefUpdate updateAllowed(
prefs, prefs::kDesktopNotificationAllowedOrigins);
}
ListValue* denied_sites =
prefs->GetMutableList(prefs::kDesktopNotificationDeniedOrigins);
{
denied_sites->Append(new StringValue(GURL("http://denied.com").spec()));
ScopedUserPrefUpdate updateDenied(
prefs, prefs::kDesktopNotificationDeniedOrigins);
}
EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionAllowed,
proxy_->CacheHasPermission(cache_, GURL("http://allowed.com")));
EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionDenied,
proxy_->CacheHasPermission(cache_, GURL("http://denied.com")));
}
TEST_F(DesktopNotificationServiceTest, GetAllowedOrigins) {
service_->GrantPermission(GURL("http://allowed2.com"));
service_->GrantPermission(GURL("http://allowed.com"));
std::vector<GURL> allowed_origins(service_->GetAllowedOrigins());
ASSERT_EQ(2u, allowed_origins.size());
EXPECT_EQ(GURL("http://allowed2.com"), allowed_origins[0]);
EXPECT_EQ(GURL("http://allowed.com"), allowed_origins[1]);
}
TEST_F(DesktopNotificationServiceTest, GetBlockedOrigins) {
service_->DenyPermission(GURL("http://denied2.com"));
service_->DenyPermission(GURL("http://denied.com"));
std::vector<GURL> denied_origins(service_->GetBlockedOrigins());
ASSERT_EQ(2u, denied_origins.size());
EXPECT_EQ(GURL("http://denied2.com"), denied_origins[0]);
EXPECT_EQ(GURL("http://denied.com"), denied_origins[1]);
}
TEST_F(DesktopNotificationServiceTest, ResetAllSentToCache) {
GURL allowed_url("http://allowed.com");
service_->GrantPermission(allowed_url);
EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionAllowed,
proxy_->CacheHasPermission(cache_, allowed_url));
GURL denied_url("http://denied.com");
service_->DenyPermission(denied_url);
EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionDenied,
proxy_->CacheHasPermission(cache_, denied_url));
service_->ResetAllOrigins();
EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionNotAllowed,
proxy_->CacheHasPermission(cache_, allowed_url));
EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionNotAllowed,
proxy_->CacheHasPermission(cache_, denied_url));
}
TEST_F(DesktopNotificationServiceTest, ResetAllowedSentToCache) {
GURL allowed_url("http://allowed.com");
service_->GrantPermission(allowed_url);
EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionAllowed,
proxy_->CacheHasPermission(cache_, allowed_url));
service_->ResetAllowedOrigin(allowed_url);
EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionNotAllowed,
proxy_->CacheHasPermission(cache_, allowed_url));
}
TEST_F(DesktopNotificationServiceTest, ResetBlockedSentToCache) {
GURL denied_url("http://denied.com");
service_->DenyPermission(denied_url);
EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionDenied,
proxy_->CacheHasPermission(cache_, denied_url));
service_->ResetBlockedOrigin(denied_url);
EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionNotAllowed,
proxy_->CacheHasPermission(cache_, denied_url));
}
} // namespace
<commit_msg>Get rid of PrefService::GetMutableDictionary/GetMutableList<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/notifications/desktop_notification_service.h"
#include "base/memory/ref_counted.h"
#include "base/message_loop.h"
#include "base/synchronization/waitable_event.h"
#include "chrome/browser/notifications/notifications_prefs_cache.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/prefs/scoped_user_pref_update.h"
#include "chrome/common/pref_names.h"
#include "chrome/test/testing_profile.h"
#include "content/browser/browser_thread.h"
#include "content/browser/renderer_host/test_render_view_host.h"
#include "grit/generated_resources.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebNotificationPresenter.h"
namespace {
// NotificationsPrefsCache wants to be called on the IO thread. This class
// routes calls to the cache on the IO thread.
class ThreadProxy : public base::RefCountedThreadSafe<ThreadProxy> {
public:
ThreadProxy()
: io_event_(false, false),
ui_event_(false, false),
permission_(0) {
// The current message loop was already initalized by the test superclass.
ui_thread_.reset(
new BrowserThread(BrowserThread::UI, MessageLoop::current()));
// Create IO thread, start its message loop.
io_thread_.reset(new BrowserThread(BrowserThread::IO));
io_thread_->Start();
// Calling PauseIOThread() here isn't safe, because the runnable method
// could complete before the constructor is done, deleting |this|.
}
int CacheHasPermission(NotificationsPrefsCache* cache, const GURL& url) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
NewRunnableMethod(this, &ThreadProxy::CacheHasPermissionIO,
make_scoped_refptr(cache), url));
io_event_.Signal();
ui_event_.Wait(); // Wait for IO thread to be done.
BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
NewRunnableMethod(this, &ThreadProxy::PauseIOThreadIO));
return permission_;
}
void PauseIOThread() {
BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
NewRunnableMethod(this, &ThreadProxy::PauseIOThreadIO));
}
void DrainIOThread() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
io_event_.Signal();
io_thread_->Stop();
}
private:
friend class base::RefCountedThreadSafe<ThreadProxy>;
~ThreadProxy() {
DrainIOThread();
}
void PauseIOThreadIO() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
io_event_.Wait();
}
void CacheHasPermissionIO(NotificationsPrefsCache* cache, const GURL& url) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
permission_ = cache->HasPermission(url);
ui_event_.Signal();
}
base::WaitableEvent io_event_;
base::WaitableEvent ui_event_;
scoped_ptr<BrowserThread> ui_thread_;
scoped_ptr<BrowserThread> io_thread_;
int permission_;
};
class DesktopNotificationServiceTest : public RenderViewHostTestHarness {
public:
DesktopNotificationServiceTest() {
}
virtual void SetUp() {
RenderViewHostTestHarness::SetUp();
proxy_ = new ThreadProxy;
proxy_->PauseIOThread();
// Creates the service, calls InitPrefs() on it which loads data from the
// profile into the cache and then puts the cache in io thread mode.
service_ = profile()->GetDesktopNotificationService();
cache_ = service_->prefs_cache();
}
virtual void TearDown() {
// The io thread's waiting on the io_event_ might hold a ref to |proxy_|,
// preventing its destruction. Clear that ref.
proxy_->DrainIOThread();
RenderViewHostTestHarness::TearDown();
}
DesktopNotificationService* service_;
NotificationsPrefsCache* cache_;
scoped_refptr<ThreadProxy> proxy_;
};
TEST_F(DesktopNotificationServiceTest, DefaultContentSettingSentToCache) {
// The default pref registered in DesktopNotificationService is "ask",
// and that's what sent to the cache.
EXPECT_EQ(CONTENT_SETTING_ASK, cache_->CachedDefaultContentSetting());
// Change the default content setting. This will post a task on the IO thread
// to update the cache.
service_->SetDefaultContentSetting(CONTENT_SETTING_BLOCK);
// The updated pref shouldn't be sent to the cache immediately.
EXPECT_EQ(CONTENT_SETTING_ASK, cache_->CachedDefaultContentSetting());
// Run IO thread tasks.
proxy_->DrainIOThread();
// Now that IO thread events have been processed, it should be there.
EXPECT_EQ(CONTENT_SETTING_BLOCK, cache_->CachedDefaultContentSetting());
}
TEST_F(DesktopNotificationServiceTest, SettingsForSchemes) {
GURL url("file:///html/test.html");
EXPECT_EQ(CONTENT_SETTING_ASK, cache_->CachedDefaultContentSetting());
EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionNotAllowed,
proxy_->CacheHasPermission(cache_, url));
service_->GrantPermission(url);
EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionAllowed,
proxy_->CacheHasPermission(cache_, url));
service_->DenyPermission(url);
EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionDenied,
proxy_->CacheHasPermission(cache_, url));
GURL https_url("https://testurl");
GURL http_url("http://testurl");
EXPECT_EQ(CONTENT_SETTING_ASK, cache_->CachedDefaultContentSetting());
EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionNotAllowed,
proxy_->CacheHasPermission(cache_, http_url));
EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionNotAllowed,
proxy_->CacheHasPermission(cache_, https_url));
service_->GrantPermission(https_url);
EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionAllowed,
proxy_->CacheHasPermission(cache_, https_url));
EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionNotAllowed,
proxy_->CacheHasPermission(cache_, http_url));
service_->DenyPermission(http_url);
EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionDenied,
proxy_->CacheHasPermission(cache_, http_url));
EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionAllowed,
proxy_->CacheHasPermission(cache_, https_url));
}
TEST_F(DesktopNotificationServiceTest, GrantPermissionSentToCache) {
GURL url("http://allowed.com");
EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionNotAllowed,
proxy_->CacheHasPermission(cache_, url));
service_->GrantPermission(url);
EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionAllowed,
proxy_->CacheHasPermission(cache_, url));
}
TEST_F(DesktopNotificationServiceTest, DenyPermissionSentToCache) {
GURL url("http://denied.com");
EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionNotAllowed,
proxy_->CacheHasPermission(cache_, url));
service_->DenyPermission(url);
EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionDenied,
proxy_->CacheHasPermission(cache_, url));
}
TEST_F(DesktopNotificationServiceTest, PrefChangesSentToCache) {
PrefService* prefs = profile()->GetPrefs();
{
ListPrefUpdate update_allowed_origins(
prefs, prefs::kDesktopNotificationAllowedOrigins);
ListValue* allowed_origins = update_allowed_origins.Get();
allowed_origins->Append(new StringValue(GURL("http://allowed.com").spec()));
}
{
ListPrefUpdate update_denied_origins(
prefs, prefs::kDesktopNotificationDeniedOrigins);
ListValue* denied_origins = update_denied_origins.Get();
denied_origins->Append(new StringValue(GURL("http://denied.com").spec()));
}
EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionAllowed,
proxy_->CacheHasPermission(cache_, GURL("http://allowed.com")));
EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionDenied,
proxy_->CacheHasPermission(cache_, GURL("http://denied.com")));
}
TEST_F(DesktopNotificationServiceTest, GetAllowedOrigins) {
service_->GrantPermission(GURL("http://allowed2.com"));
service_->GrantPermission(GURL("http://allowed.com"));
std::vector<GURL> allowed_origins(service_->GetAllowedOrigins());
ASSERT_EQ(2u, allowed_origins.size());
EXPECT_EQ(GURL("http://allowed2.com"), allowed_origins[0]);
EXPECT_EQ(GURL("http://allowed.com"), allowed_origins[1]);
}
TEST_F(DesktopNotificationServiceTest, GetBlockedOrigins) {
service_->DenyPermission(GURL("http://denied2.com"));
service_->DenyPermission(GURL("http://denied.com"));
std::vector<GURL> denied_origins(service_->GetBlockedOrigins());
ASSERT_EQ(2u, denied_origins.size());
EXPECT_EQ(GURL("http://denied2.com"), denied_origins[0]);
EXPECT_EQ(GURL("http://denied.com"), denied_origins[1]);
}
TEST_F(DesktopNotificationServiceTest, ResetAllSentToCache) {
GURL allowed_url("http://allowed.com");
service_->GrantPermission(allowed_url);
EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionAllowed,
proxy_->CacheHasPermission(cache_, allowed_url));
GURL denied_url("http://denied.com");
service_->DenyPermission(denied_url);
EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionDenied,
proxy_->CacheHasPermission(cache_, denied_url));
service_->ResetAllOrigins();
EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionNotAllowed,
proxy_->CacheHasPermission(cache_, allowed_url));
EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionNotAllowed,
proxy_->CacheHasPermission(cache_, denied_url));
}
TEST_F(DesktopNotificationServiceTest, ResetAllowedSentToCache) {
GURL allowed_url("http://allowed.com");
service_->GrantPermission(allowed_url);
EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionAllowed,
proxy_->CacheHasPermission(cache_, allowed_url));
service_->ResetAllowedOrigin(allowed_url);
EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionNotAllowed,
proxy_->CacheHasPermission(cache_, allowed_url));
}
TEST_F(DesktopNotificationServiceTest, ResetBlockedSentToCache) {
GURL denied_url("http://denied.com");
service_->DenyPermission(denied_url);
EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionDenied,
proxy_->CacheHasPermission(cache_, denied_url));
service_->ResetBlockedOrigin(denied_url);
EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionNotAllowed,
proxy_->CacheHasPermission(cache_, denied_url));
}
} // namespace
<|endoftext|>
|
<commit_before>/*
Copyright (C) 2007 <SWGEmu>
This File is part of Core3.
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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
Linking Engine3 statically or dynamically with other modules
is making a combined work based on Engine3.
Thus, the terms and conditions of the GNU Lesser General Public License
cover the whole combination.
In addition, as a special exception, the copyright holders of Engine3
give you permission to combine Engine3 program with free software
programs or libraries that are released under the GNU LGPL and with
code included in the standard release of Core3 under the GNU LGPL
license (or modified versions of such code, with unchanged license).
You may copy and distribute such a system following the terms of the
GNU LGPL for Engine3 and the licenses of the other code concerned,
provided that you include the source code of that other code when
and as the GNU LGPL requires distribution of source code.
Note that people who make modified versions of Engine3 are not obligated
to grant this special exception for their modified versions;
it is their choice whether to do so. The GNU Lesser General Public License
gives permission to release a modified version without this exception;
this exception also makes it possible to release a modified version
which carries forward this exception.
*/
#include "server/ServerCore.h"
#include "server/zone/objects/tangible/Container.h"
/*#include "system/mm/AllocationTracker.h"
AllocationTracker* tracker;
void initializeTracker() {
printf("malloc initialization Hook installed\n");
tracker = AllocationTracker::getInstance();
tracker->install();
}*/
//void (*__malloc_initialize_hook)(void) = initializeTracker;
int main(int argc, char* argv[]) {
try {
Vector<String> arguments;
for (int i = 1; i < argc; ++i) {
arguments.add(argv[i]);
}
ServerCore core;
core.start();
} catch (Exception& e) {
System::out << e.getMessage() << "\n";
e.printStackTrace();
} catch (...) {
System::out << "unreported exception caught main()\n";
}
return 0;
}
<commit_msg>[fixed] missing file<commit_after>/*
Copyright (C) 2007 <SWGEmu>
This File is part of Core3.
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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
Linking Engine3 statically or dynamically with other modules
is making a combined work based on Engine3.
Thus, the terms and conditions of the GNU Lesser General Public License
cover the whole combination.
In addition, as a special exception, the copyright holders of Engine3
give you permission to combine Engine3 program with free software
programs or libraries that are released under the GNU LGPL and with
code included in the standard release of Core3 under the GNU LGPL
license (or modified versions of such code, with unchanged license).
You may copy and distribute such a system following the terms of the
GNU LGPL for Engine3 and the licenses of the other code concerned,
provided that you include the source code of that other code when
and as the GNU LGPL requires distribution of source code.
Note that people who make modified versions of Engine3 are not obligated
to grant this special exception for their modified versions;
it is their choice whether to do so. The GNU Lesser General Public License
gives permission to release a modified version without this exception;
this exception also makes it possible to release a modified version
which carries forward this exception.
*/
#include "server/ServerCore.h"
/*#include "system/mm/AllocationTracker.h"
AllocationTracker* tracker;
void initializeTracker() {
printf("malloc initialization Hook installed\n");
tracker = AllocationTracker::getInstance();
tracker->install();
}*/
int main(int argc, char* argv[]) {
try {
SortedVector<String> arguments;
for (int i = 1; i < argc; ++i) {
arguments.put(argv[i]);
}
bool truncateData = arguments.contains("clean");
ServerCore core(truncateData);
core.start();
} catch (Exception& e) {
System::out << e.getMessage() << "\n";
e.printStackTrace();
} catch (...) {
System::out << "unreported exception caught main()\n";
}
return 0;
}
<|endoftext|>
|
<commit_before>/*
* Copyright 2010 MQWeb - Franky Braem
*
* Licensed under the EUPL, Version 1.1 or – as soon they
* will be approved by the European Commission - subsequent
* versions of the EUPL (the "Licence");
* You may not use this work except in compliance with the
* Licence.
* You may obtain a copy of the Licence at:
*
* http://joinup.ec.europa.eu/software/page/eupl
*
* Unless required by applicable law or agreed to in
* writing, software distributed under the Licence is
* distributed on an "AS IS" basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied.
* See the Licence for the specific language governing
* permissions and limitations under the Licence.
*/
#include <string.h>
#include "Poco/DateTimeParser.h"
#include "Poco/Util/Application.h"
#include "Poco/StringTokenizer.h"
#include "MQ/QueueManager.h"
#include "MQ/MQException.h"
#include "MQ/MQSubsystem.h"
namespace MQ
{
QueueManager::QueueManager(const std::string& name)
: _handle(0),
_name(name),
_applicationType(0)
{
}
QueueManager::~QueueManager()
{
if ( _handle != 0 )
{
try
{
disconnect();
}
catch(MQException&)
{
// Don't throw exceptions from a destructor
// See: http://www.parashift.com/c++-faq-lite/exceptions.html#faq-17.9
}
}
}
void QueueManager::connect()
{
MQCNO cno = { MQCNO_DEFAULT };
cno.Version = MQCNO_VERSION_2;
cno.Options = MQCNO_HANDLE_SHARE_NONE;
MQ::MQSubsystem& mqSystem = Poco::Util::Application::instance().getSubsystem<MQ::MQSubsystem>();
_handle = mqSystem.functions().connx(_name, &cno);
inquireQmgrAttrs();
}
void QueueManager::connect(const std::string& channel, const std::string& server)
{
MQCNO cno = { MQCNO_DEFAULT };
cno.Version = MQCNO_VERSION_2;
cno.Options = MQCNO_HANDLE_SHARE_BLOCK;
MQCD cd = { MQCD_CLIENT_CONN_DEFAULT };
strncpy(cd.ChannelName, channel.c_str(), MQ_CHANNEL_NAME_LENGTH);
strncpy(cd.ConnectionName, server.c_str(), MQ_CONN_NAME_LENGTH);
cd.TransportType = MQXPT_TCP;
cno.ClientConnPtr = &cd;
MQ::MQSubsystem& mqSystem = Poco::Util::Application::instance().getSubsystem<MQ::MQSubsystem>();
_handle = mqSystem.functions().connx(_name, &cno);
inquireQmgrAttrs();
}
void QueueManager::connect(const Poco::DynamicStruct& connectionInformation)
{
if ( connectionInformation.contains("ssl") )
{
Poco::Dynamic::Var ssl = connectionInformation["ssl"];
if ( ssl.isStruct() )
{
connect(connectionInformation["channel"],
connectionInformation["connection"],
ssl.extract<Poco::Dynamic::Struct<std::string> >());
}
}
else
{
if ( connectionInformation.contains("channel") && connectionInformation.contains("connection") )
{
connect(connectionInformation["channel"], connectionInformation["connection"]);
}
else
{
connect();
}
}
}
void QueueManager::connect(const std::string& channel, const std::string& server, const Poco::DynamicStruct& ssl)
{
MQCNO cno = { MQCNO_DEFAULT };
/*
We must specify MQCNO version 4 to ensure that both the client
connection pointer and SSL configuration options are used
*/
cno.Version = MQCNO_VERSION_4;
cno.Options = MQCNO_HANDLE_SHARE_BLOCK;
MQCD cd = { MQCD_CLIENT_CONN_DEFAULT };
strncpy(cd.ChannelName, channel.c_str(), MQ_CHANNEL_NAME_LENGTH);
strncpy(cd.ConnectionName, server.c_str(), MQ_CONN_NAME_LENGTH);
if ( ssl.contains("cipherspec") )
{
strncpy(cd.SSLCipherSpec, ssl["cipherspec"].toString().c_str(), MQ_SSL_CIPHER_SPEC_LENGTH);
cd.Version = MQCD_VERSION_7; // SSL requires MQCD version 7 or later
}
cd.TransportType = MQXPT_TCP;
cno.ClientConnPtr = &cd;
MQSCO sco = { MQSCO_DEFAULT };
MQAIR authInfoRec = { MQAIR_DEFAULT };
Poco::Dynamic::Var keyrepos = ssl["keyrepos"];
strncpy(sco.KeyRepository, keyrepos.toString().c_str(), MQ_SSL_KEY_REPOSITORY_LENGTH);
if ( ssl.contains("fips") )
{
if ( ssl["fips"].convert<bool>() )
{
sco.FipsRequired = MQSSL_FIPS_YES;
sco.Version = MQSCO_VERSION_2; // A version 2 MQSCO supports FipsRequired
}
}
if ( ssl.contains("suiteb") )
{
static std::map<std::string, MQLONG> suiteBTable;
if ( suiteBTable.size() == 0 )
{
suiteBTable.insert(std::make_pair<std::string, MQLONG>("none", MQ_SUITE_B_NONE));
suiteBTable.insert(std::make_pair<std::string, MQLONG>("128 bit", MQ_SUITE_B_128_BIT));
suiteBTable.insert(std::make_pair<std::string, MQLONG>("192 bit", MQ_SUITE_B_192_BIT));
}
sco.Version = MQSCO_VERSION_3; /* A version 3 MQSCO supports Suite B encryption policy */
Poco::StringTokenizer tokenizer(ssl["suiteb"].toString(), ",", Poco::StringTokenizer::TOK_TRIM);
int n = 0;
for(Poco::StringTokenizer::Iterator it = tokenizer.begin(); it != tokenizer.end() && n < 4; ++it, ++n)
{
std::map<std::string, MQLONG>::iterator suiteBIterator = suiteBTable.find(*it);
if ( suiteBIterator == suiteBTable.end() )
{
throw Poco::NotFoundException(Poco::format("Unknown SuiteB value: %s", *it));
}
else
{
sco.EncryptionPolicySuiteB[n] = suiteBIterator->second;
}
}
}
#ifdef MQSCO_VERSION_4
if ( ssl.contains("certificate_validation_policy") )
{
static std::map<std::string, MQLONG> certValPolicyTable;
if ( certValPolicyTable.size() == 0 )
{
certValPolicyTable.insert(std::make_pair<std::string, MQLONG>("any", MQ_CERT_VAL_POLICY_ANY));
certValPolicyTable.insert(std::make_pair<std::string, MQLONG>("rfc5280", MQ_CERT_VAL_POLICY_RFC5280));
}
sco.Version = MQSCO_VERSION_4; /* A version 4 MQSCO supports certificate validation policy */
std::string certValPolicy = ssl["certificate_validation_policy"].toString();
std::map<std::string, MQLONG>::iterator certValPolicyIterator = certValPolicyTable.find(certValPolicy);
if ( certValPolicyIterator == certValPolicyTable.end() )
{
throw Poco::NotFoundException(Poco::format("Unknown Certification Validation Policy: %s", certValPolicy));
}
else
{
sco.CertificateValPolicy = certValPolicyIterator->second;
}
}
#endif
if ( ssl.contains("ocsp_url") )
{
/* OCSP requires MQAIR version 2 or later */
authInfoRec.Version = MQAIR_VERSION_2;
authInfoRec.AuthInfoType = MQAIT_OCSP;
strncpy(authInfoRec.OCSPResponderURL, ssl["ocsp_url"].toString().c_str(), MQ_AUTH_INFO_OCSP_URL_LENGTH);
/* The MQSCO must point to the MQAIR */
sco.AuthInfoRecCount = 1;
sco.AuthInfoRecPtr = &authInfoRec;
}
cno.SSLConfigPtr = &sco;
MQ::MQSubsystem& mqSystem = Poco::Util::Application::instance().getSubsystem<MQ::MQSubsystem>();
_handle = mqSystem.functions().connx(_name, &cno);
inquireQmgrAttrs();
}
void QueueManager::inquireQmgrAttrs()
{
MQ::MQSubsystem& mqSystem = Poco::Util::Application::instance().getSubsystem<MQ::MQSubsystem>();
MQOD qmgrObjectDesc = {MQOD_DEFAULT};
qmgrObjectDesc.ObjectType = MQOT_Q_MGR;
MQHOBJ qmgrObjectHandle = mqSystem.functions().open(_handle, &qmgrObjectDesc, MQOO_INQUIRE);
std::vector<int> intSelectors;
intSelectors.push_back(MQIA_PLATFORM);
std::map<int, int> charSelectors;
charSelectors[MQCA_Q_MGR_NAME] = MQ_Q_MGR_NAME_LENGTH;
charSelectors[MQCA_Q_MGR_IDENTIFIER] = MQ_Q_MGR_IDENTIFIER_LENGTH;
charSelectors[MQCA_COMMAND_INPUT_Q_NAME] = MQ_Q_NAME_LENGTH;
std::map<int, int> intResult;
std::map<int, std::string> charResult;
mqSystem.functions().inq(_handle, qmgrObjectHandle, intSelectors, charSelectors, intResult, charResult);
_applicationType = intResult[MQIA_PLATFORM];
_name = charResult[MQCA_Q_MGR_NAME];
_id = charResult[MQCA_Q_MGR_IDENTIFIER];
_commandQueue = charResult[MQCA_COMMAND_INPUT_Q_NAME];
mqSystem.functions().close(_handle, &qmgrObjectHandle, MQCO_NONE);
}
void QueueManager::disconnect()
{
if ( _handle != 0 )
{
MQ::MQSubsystem& mqSystem = Poco::Util::Application::instance().getSubsystem<MQ::MQSubsystem>();
mqSystem.functions().disc(&_handle);
_handle = 0;
}
}
}
<commit_msg>Options in connect must be MQCNO_HANDLE_SHARE_BLOCK<commit_after>/*
* Copyright 2010 MQWeb - Franky Braem
*
* Licensed under the EUPL, Version 1.1 or – as soon they
* will be approved by the European Commission - subsequent
* versions of the EUPL (the "Licence");
* You may not use this work except in compliance with the
* Licence.
* You may obtain a copy of the Licence at:
*
* http://joinup.ec.europa.eu/software/page/eupl
*
* Unless required by applicable law or agreed to in
* writing, software distributed under the Licence is
* distributed on an "AS IS" basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied.
* See the Licence for the specific language governing
* permissions and limitations under the Licence.
*/
#include <string.h>
#include "Poco/DateTimeParser.h"
#include "Poco/Util/Application.h"
#include "Poco/StringTokenizer.h"
#include "MQ/QueueManager.h"
#include "MQ/MQException.h"
#include "MQ/MQSubsystem.h"
namespace MQ
{
QueueManager::QueueManager(const std::string& name)
: _handle(0),
_name(name),
_applicationType(0)
{
}
QueueManager::~QueueManager()
{
if ( _handle != 0 )
{
try
{
disconnect();
}
catch(MQException&)
{
// Don't throw exceptions from a destructor
// See: http://www.parashift.com/c++-faq-lite/exceptions.html#faq-17.9
}
}
}
void QueueManager::connect()
{
MQCNO cno = { MQCNO_DEFAULT };
cno.Version = MQCNO_VERSION_2;
cno.Options = MQCNO_HANDLE_SHARE_BLOCK;
MQ::MQSubsystem& mqSystem = Poco::Util::Application::instance().getSubsystem<MQ::MQSubsystem>();
_handle = mqSystem.functions().connx(_name, &cno);
inquireQmgrAttrs();
}
void QueueManager::connect(const std::string& channel, const std::string& server)
{
MQCNO cno = { MQCNO_DEFAULT };
cno.Version = MQCNO_VERSION_2;
cno.Options = MQCNO_HANDLE_SHARE_BLOCK;
MQCD cd = { MQCD_CLIENT_CONN_DEFAULT };
strncpy(cd.ChannelName, channel.c_str(), MQ_CHANNEL_NAME_LENGTH);
strncpy(cd.ConnectionName, server.c_str(), MQ_CONN_NAME_LENGTH);
cd.TransportType = MQXPT_TCP;
cno.ClientConnPtr = &cd;
MQ::MQSubsystem& mqSystem = Poco::Util::Application::instance().getSubsystem<MQ::MQSubsystem>();
_handle = mqSystem.functions().connx(_name, &cno);
inquireQmgrAttrs();
}
void QueueManager::connect(const Poco::DynamicStruct& connectionInformation)
{
if ( connectionInformation.contains("ssl") )
{
Poco::Dynamic::Var ssl = connectionInformation["ssl"];
if ( ssl.isStruct() )
{
connect(connectionInformation["channel"],
connectionInformation["connection"],
ssl.extract<Poco::Dynamic::Struct<std::string> >());
}
}
else
{
if ( connectionInformation.contains("channel") && connectionInformation.contains("connection") )
{
connect(connectionInformation["channel"], connectionInformation["connection"]);
}
else
{
connect();
}
}
}
void QueueManager::connect(const std::string& channel, const std::string& server, const Poco::DynamicStruct& ssl)
{
MQCNO cno = { MQCNO_DEFAULT };
/*
We must specify MQCNO version 4 to ensure that both the client
connection pointer and SSL configuration options are used
*/
cno.Version = MQCNO_VERSION_4;
cno.Options = MQCNO_HANDLE_SHARE_BLOCK;
MQCD cd = { MQCD_CLIENT_CONN_DEFAULT };
strncpy(cd.ChannelName, channel.c_str(), MQ_CHANNEL_NAME_LENGTH);
strncpy(cd.ConnectionName, server.c_str(), MQ_CONN_NAME_LENGTH);
if ( ssl.contains("cipherspec") )
{
strncpy(cd.SSLCipherSpec, ssl["cipherspec"].toString().c_str(), MQ_SSL_CIPHER_SPEC_LENGTH);
cd.Version = MQCD_VERSION_7; // SSL requires MQCD version 7 or later
}
cd.TransportType = MQXPT_TCP;
cno.ClientConnPtr = &cd;
MQSCO sco = { MQSCO_DEFAULT };
MQAIR authInfoRec = { MQAIR_DEFAULT };
Poco::Dynamic::Var keyrepos = ssl["keyrepos"];
strncpy(sco.KeyRepository, keyrepos.toString().c_str(), MQ_SSL_KEY_REPOSITORY_LENGTH);
if ( ssl.contains("fips") )
{
if ( ssl["fips"].convert<bool>() )
{
sco.FipsRequired = MQSSL_FIPS_YES;
sco.Version = MQSCO_VERSION_2; // A version 2 MQSCO supports FipsRequired
}
}
if ( ssl.contains("suiteb") )
{
static std::map<std::string, MQLONG> suiteBTable;
if ( suiteBTable.size() == 0 )
{
suiteBTable.insert(std::make_pair<std::string, MQLONG>("none", MQ_SUITE_B_NONE));
suiteBTable.insert(std::make_pair<std::string, MQLONG>("128 bit", MQ_SUITE_B_128_BIT));
suiteBTable.insert(std::make_pair<std::string, MQLONG>("192 bit", MQ_SUITE_B_192_BIT));
}
sco.Version = MQSCO_VERSION_3; /* A version 3 MQSCO supports Suite B encryption policy */
Poco::StringTokenizer tokenizer(ssl["suiteb"].toString(), ",", Poco::StringTokenizer::TOK_TRIM);
int n = 0;
for(Poco::StringTokenizer::Iterator it = tokenizer.begin(); it != tokenizer.end() && n < 4; ++it, ++n)
{
std::map<std::string, MQLONG>::iterator suiteBIterator = suiteBTable.find(*it);
if ( suiteBIterator == suiteBTable.end() )
{
throw Poco::NotFoundException(Poco::format("Unknown SuiteB value: %s", *it));
}
else
{
sco.EncryptionPolicySuiteB[n] = suiteBIterator->second;
}
}
}
#ifdef MQSCO_VERSION_4
if ( ssl.contains("certificate_validation_policy") )
{
static std::map<std::string, MQLONG> certValPolicyTable;
if ( certValPolicyTable.size() == 0 )
{
certValPolicyTable.insert(std::make_pair<std::string, MQLONG>("any", MQ_CERT_VAL_POLICY_ANY));
certValPolicyTable.insert(std::make_pair<std::string, MQLONG>("rfc5280", MQ_CERT_VAL_POLICY_RFC5280));
}
sco.Version = MQSCO_VERSION_4; /* A version 4 MQSCO supports certificate validation policy */
std::string certValPolicy = ssl["certificate_validation_policy"].toString();
std::map<std::string, MQLONG>::iterator certValPolicyIterator = certValPolicyTable.find(certValPolicy);
if ( certValPolicyIterator == certValPolicyTable.end() )
{
throw Poco::NotFoundException(Poco::format("Unknown Certification Validation Policy: %s", certValPolicy));
}
else
{
sco.CertificateValPolicy = certValPolicyIterator->second;
}
}
#endif
if ( ssl.contains("ocsp_url") )
{
/* OCSP requires MQAIR version 2 or later */
authInfoRec.Version = MQAIR_VERSION_2;
authInfoRec.AuthInfoType = MQAIT_OCSP;
strncpy(authInfoRec.OCSPResponderURL, ssl["ocsp_url"].toString().c_str(), MQ_AUTH_INFO_OCSP_URL_LENGTH);
/* The MQSCO must point to the MQAIR */
sco.AuthInfoRecCount = 1;
sco.AuthInfoRecPtr = &authInfoRec;
}
cno.SSLConfigPtr = &sco;
MQ::MQSubsystem& mqSystem = Poco::Util::Application::instance().getSubsystem<MQ::MQSubsystem>();
_handle = mqSystem.functions().connx(_name, &cno);
inquireQmgrAttrs();
}
void QueueManager::inquireQmgrAttrs()
{
MQ::MQSubsystem& mqSystem = Poco::Util::Application::instance().getSubsystem<MQ::MQSubsystem>();
MQOD qmgrObjectDesc = {MQOD_DEFAULT};
qmgrObjectDesc.ObjectType = MQOT_Q_MGR;
MQHOBJ qmgrObjectHandle = mqSystem.functions().open(_handle, &qmgrObjectDesc, MQOO_INQUIRE);
std::vector<int> intSelectors;
intSelectors.push_back(MQIA_PLATFORM);
std::map<int, int> charSelectors;
charSelectors[MQCA_Q_MGR_NAME] = MQ_Q_MGR_NAME_LENGTH;
charSelectors[MQCA_Q_MGR_IDENTIFIER] = MQ_Q_MGR_IDENTIFIER_LENGTH;
charSelectors[MQCA_COMMAND_INPUT_Q_NAME] = MQ_Q_NAME_LENGTH;
std::map<int, int> intResult;
std::map<int, std::string> charResult;
mqSystem.functions().inq(_handle, qmgrObjectHandle, intSelectors, charSelectors, intResult, charResult);
_applicationType = intResult[MQIA_PLATFORM];
_name = charResult[MQCA_Q_MGR_NAME];
_id = charResult[MQCA_Q_MGR_IDENTIFIER];
_commandQueue = charResult[MQCA_COMMAND_INPUT_Q_NAME];
mqSystem.functions().close(_handle, &qmgrObjectHandle, MQCO_NONE);
}
void QueueManager::disconnect()
{
if ( _handle != 0 )
{
MQ::MQSubsystem& mqSystem = Poco::Util::Application::instance().getSubsystem<MQ::MQSubsystem>();
mqSystem.functions().disc(&_handle);
_handle = 0;
}
}
}
<|endoftext|>
|
<commit_before>// Copyright 2021 Proyectos y Sistemas de Mantenimiento SL (eProsima).
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @file StatisticsBase.hpp
*/
#ifndef _STATISTICS_RTPS_STATISTICSBASE_HPP_
#define _STATISTICS_RTPS_STATISTICSBASE_HPP_
#include <mutex>
#include <set>
#include <fastrtps/config.h>
#include <fastdds/rtps/common/Guid.h>
#include <fastdds/rtps/common/Locator.h>
#include <statistics/types/types.h>
#include <statistics/rtps/GuidUtils.hpp>
#include <fastdds/statistics/rtps/StatisticsCommon.hpp>
namespace eprosima {
namespace fastrtps {
namespace rtps {
class PDP;
} // rtps
} // fastrtps
namespace fastdds {
namespace statistics {
#ifdef FASTDDS_STATISTICS
// RTPSWriter and RTPSReader statistics members
struct StatisticsAncillary
{
std::set<std::shared_ptr<IListener>> listeners;
};
struct StatisticsWriterAncillary
: public StatisticsAncillary
{
unsigned long long data_counter = {};
unsigned long long gap_counter = {};
unsigned long long resent_counter = {};
};
struct StatisticsReaderAncillary
: public StatisticsAncillary
{
};
// lambda function to traverse the listener collection
template<class Function>
Function StatisticsListenersImpl::for_each_listener(
Function f)
{
// Use a collection copy to prevent locking on traversal
std::unique_lock<fastrtps::RecursiveTimedMutex> lock(get_statistics_mutex());
auto listeners = members_->listeners;
lock.unlock();
if (members_)
{
for (auto& listener : listeners)
{
f(listener);
}
}
return f;
}
class StatisticsParticipantImpl
{
friend class fastrtps::rtps::PDP;
// statistics members protection only
std::recursive_mutex statistics_mutex_;
public:
using GUID_t = fastrtps::rtps::GUID_t;
private:
// RTPS_SENT ancillary
struct rtps_sent_data
{
unsigned long long packet_count = {};
unsigned long long byte_count = {};
};
std::map<fastrtps::rtps::Locator_t, rtps_sent_data> traffic;
// PDP_PACKETS ancillary
unsigned long long pdp_counter_ = {};
/*
* Retrieve the GUID_t from derived class
* @return endpoint GUID_t
*/
const GUID_t& get_guid() const;
protected:
class ListenerProxy
: public IListener
, public std::enable_shared_from_this<ListenerProxy>
{
// the external_ listener is the actual key value
mutable uint32_t mask_;
std::shared_ptr<IListener> external_;
public:
ListenerProxy(
std::shared_ptr<IListener> listener,
uint32_t mask)
: mask_(mask)
, external_(listener)
{
}
void on_statistics_data(
const Data& data) override;
uint32_t mask() const;
void mask(
uint32_t update) const;
bool operator <(
const ListenerProxy& right) const;
std::shared_ptr<IListener> get_shared_ptr() const
{
return std::static_pointer_cast<IListener>(const_cast<ListenerProxy*>(this)->shared_from_this());
}
};
using Key = std::shared_ptr<ListenerProxy>;
// specialized comparison operator, the actual key is the external listener address
struct CompareProxies
{
bool operator ()(
const Key& left,
const Key& right) const
{
return *left < *right;
}
};
using ProxyCollection = std::set<Key, CompareProxies>;
ProxyCollection listeners_;
// retrieve the participant mutex
std::recursive_mutex& get_statistics_mutex();
/** Register a listener in participant RTPSWriter entities.
* @param listener, smart pointer to the listener interface to register
* @param guid, RTPSWriter identifier. If unknown the listener is registered in all enable ones
* @return true on success
*/
virtual bool register_in_writer(
std::shared_ptr<fastdds::statistics::IListener> listener,
GUID_t guid = GUID_t::unknown()) = 0;
/** Register a listener in participant RTPSReader entities.
* @param listener, smart pointer to the listener interface to register
* @param guid, RTPSReader identifier. If unknown the listener is registered in all enable ones
* @return true on success
*/
virtual bool register_in_reader(
std::shared_ptr<fastdds::statistics::IListener> listener,
GUID_t guid = GUID_t::unknown()) = 0;
/** Unregister a listener in participant RTPSWriter entities.
* @param listener, smart pointer to the listener interface to unregister
* @return true on success
*/
virtual bool unregister_in_writer(
std::shared_ptr<fastdds::statistics::IListener> listener) = 0;
/** Unregister a listener in participant RTPSReader entities.
* @param listener, smart pointer to the listener interface to unregister
* @return true on success
*/
virtual bool unregister_in_reader(
std::shared_ptr<fastdds::statistics::IListener> listener) = 0;
// lambda function to traverse the listener collection
template<class Function>
Function for_each_listener(
Function f)
{
std::unique_lock<std::recursive_mutex> lock(get_statistics_mutex());
auto temp_listeners = listeners_;
lock.unlock();
for (auto& listener : temp_listeners)
{
f(listener);
}
return f;
}
// returns if a mask statistics::EventKind may require participant writers update
bool are_writers_involved(
const uint32_t mask) const;
// returns if a mask statistics::EventKind may require participant readers update
bool are_readers_involved(
const uint32_t mask) const;
// TODO: methods for listeners callbacks
/*
* Report a message that is sent by the participant
* @param loc, destination
* @param payload_size, size of the current message
*/
void on_rtps_sent(
const fastrtps::rtps::Locator_t& loc,
unsigned long payload_size);
/*
* Report a message that is sent by the participant
* @param sender_guid GUID of the entity producing the message
* @param destination_locators_begin, start of locators range
* @param destination_locators_end, end of locators range
* @param payload_size, size of the current message
*/
template<class LocatorIteratorT>
void on_rtps_send(
const GUID_t& sender_guid,
const LocatorIteratorT& destination_locators_begin,
const LocatorIteratorT& destination_locators_end,
unsigned long payload_size)
{
if (false == is_statistics_builtin(sender_guid.entityId))
{
auto it = destination_locators_begin;
while (it != destination_locators_end)
{
on_rtps_sent(*it, payload_size);
++it;
}
}
}
/*
* Report that a new entity is discovered
* @param id, discovered entity GUID_t
*/
void on_entity_discovery(
const GUID_t& id);
/*
* Auxiliary method to report PDP message exchange.
* @param packages number of pdp packages sent
*/
void on_pdp_packet(
const uint32_t packages);
/*
* Report PDP message exchange.
* We filtered the non-pdp traffic here to minimize presence of statistics code in endpoints implementation.
* @param sender_guid GUID_t to filter
* @param destination_locators_begin, start of locators range
* @param destination_locators_end, end of locators range
*/
template<class LocatorIteratorT>
void on_pdp_packet(
const GUID_t& sender_guid,
const LocatorIteratorT& destination_locators_begin,
const LocatorIteratorT& destination_locators_end)
{
if (sender_guid.entityId == fastrtps::rtps::c_EntityId_SPDPWriter
&& destination_locators_begin != destination_locators_end)
{
uint32_t packages = 0;
auto it = destination_locators_begin;
while (it != destination_locators_end)
{
++it;
++packages;
}
on_pdp_packet(packages);
}
}
public:
/*
* Registers a listener in participant's statistics callback queue
* @param listener smart pointer to the listener being registered
* @param kind combination of fastdds::statistics::EventKind flags used as a mask
* @return successfully registered
*/
bool add_statistics_listener(
std::shared_ptr<fastdds::statistics::IListener> listener,
uint32_t kind);
/*
* Unregisters a listener in participant's statistics callback queue
* @param listener smart pointer to the listener being unregistered
* @param kind combination of fastdds::statistics::EventKind flags used as a mask
* @return successfully unregistered
*/
bool remove_statistics_listener(
std::shared_ptr<fastdds::statistics::IListener> listener,
uint32_t kind);
};
// auxiliary conversion functions
detail::Locator_s to_statistics_type(fastrtps::rtps::Locator_t);
detail::GUID_s to_statistics_type(fastrtps::rtps::GUID_t);
#else // dummy implementation
struct StatisticsAncillary {};
class StatisticsParticipantImpl
{
friend class fastrtps::rtps::PDP;
protected:
// inline methods for listeners callbacks
/*
* Report a message that is sent by the participant
* @param destination_locators_begin, start of locators range
* @param destination_locators_end, end of locators range
* @param payload_size, size of the current message
*/
template<class LocatorIteratorT>
inline void on_rtps_send(
const fastrtps::rtps::GUID_t&,
const LocatorIteratorT&,
const LocatorIteratorT&,
unsigned long)
{
}
/*
* Report that a new entity is discovered
* @param id, discovered entity GUID_t
*/
inline void on_entity_discovery(
const fastrtps::rtps::GUID_t&)
{
}
/*
* Report PDP message exchange.
* We filtered the non-pdp traffic here to minimize presence of statistics code in endpoints implementation.
* @param sender_guid GUID_t to filter
* @param destination_locators_begin, start of locators range
* @param destination_locators_end, end of locators range
*/
template<class LocatorIteratorT>
inline void on_pdp_packet(
const fastrtps::rtps::GUID_t& sender_guid,
const LocatorIteratorT& destination_locators_begin,
const LocatorIteratorT& destination_locators_end)
{
}
};
#endif // FASTDDS_STATISTICS
} // namespace statistics
} // namespace fastdds
} // namespace eprosima
#endif // _STATISTICS_RTPS_STATISTICSBASE_HPP_
<commit_msg>Fix unused-parameter warnings<commit_after>// Copyright 2021 Proyectos y Sistemas de Mantenimiento SL (eProsima).
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @file StatisticsBase.hpp
*/
#ifndef _STATISTICS_RTPS_STATISTICSBASE_HPP_
#define _STATISTICS_RTPS_STATISTICSBASE_HPP_
#include <mutex>
#include <set>
#include <fastrtps/config.h>
#include <fastdds/rtps/common/Guid.h>
#include <fastdds/rtps/common/Locator.h>
#include <statistics/types/types.h>
#include <statistics/rtps/GuidUtils.hpp>
#include <fastdds/statistics/rtps/StatisticsCommon.hpp>
namespace eprosima {
namespace fastrtps {
namespace rtps {
class PDP;
} // rtps
} // fastrtps
namespace fastdds {
namespace statistics {
#ifdef FASTDDS_STATISTICS
// RTPSWriter and RTPSReader statistics members
struct StatisticsAncillary
{
std::set<std::shared_ptr<IListener>> listeners;
};
struct StatisticsWriterAncillary
: public StatisticsAncillary
{
unsigned long long data_counter = {};
unsigned long long gap_counter = {};
unsigned long long resent_counter = {};
};
struct StatisticsReaderAncillary
: public StatisticsAncillary
{
};
// lambda function to traverse the listener collection
template<class Function>
Function StatisticsListenersImpl::for_each_listener(
Function f)
{
// Use a collection copy to prevent locking on traversal
std::unique_lock<fastrtps::RecursiveTimedMutex> lock(get_statistics_mutex());
auto listeners = members_->listeners;
lock.unlock();
if (members_)
{
for (auto& listener : listeners)
{
f(listener);
}
}
return f;
}
class StatisticsParticipantImpl
{
friend class fastrtps::rtps::PDP;
// statistics members protection only
std::recursive_mutex statistics_mutex_;
public:
using GUID_t = fastrtps::rtps::GUID_t;
private:
// RTPS_SENT ancillary
struct rtps_sent_data
{
unsigned long long packet_count = {};
unsigned long long byte_count = {};
};
std::map<fastrtps::rtps::Locator_t, rtps_sent_data> traffic;
// PDP_PACKETS ancillary
unsigned long long pdp_counter_ = {};
/*
* Retrieve the GUID_t from derived class
* @return endpoint GUID_t
*/
const GUID_t& get_guid() const;
protected:
class ListenerProxy
: public IListener
, public std::enable_shared_from_this<ListenerProxy>
{
// the external_ listener is the actual key value
mutable uint32_t mask_;
std::shared_ptr<IListener> external_;
public:
ListenerProxy(
std::shared_ptr<IListener> listener,
uint32_t mask)
: mask_(mask)
, external_(listener)
{
}
void on_statistics_data(
const Data& data) override;
uint32_t mask() const;
void mask(
uint32_t update) const;
bool operator <(
const ListenerProxy& right) const;
std::shared_ptr<IListener> get_shared_ptr() const
{
return std::static_pointer_cast<IListener>(const_cast<ListenerProxy*>(this)->shared_from_this());
}
};
using Key = std::shared_ptr<ListenerProxy>;
// specialized comparison operator, the actual key is the external listener address
struct CompareProxies
{
bool operator ()(
const Key& left,
const Key& right) const
{
return *left < *right;
}
};
using ProxyCollection = std::set<Key, CompareProxies>;
ProxyCollection listeners_;
// retrieve the participant mutex
std::recursive_mutex& get_statistics_mutex();
/** Register a listener in participant RTPSWriter entities.
* @param listener, smart pointer to the listener interface to register
* @param guid, RTPSWriter identifier. If unknown the listener is registered in all enable ones
* @return true on success
*/
virtual bool register_in_writer(
std::shared_ptr<fastdds::statistics::IListener> listener,
GUID_t guid = GUID_t::unknown()) = 0;
/** Register a listener in participant RTPSReader entities.
* @param listener, smart pointer to the listener interface to register
* @param guid, RTPSReader identifier. If unknown the listener is registered in all enable ones
* @return true on success
*/
virtual bool register_in_reader(
std::shared_ptr<fastdds::statistics::IListener> listener,
GUID_t guid = GUID_t::unknown()) = 0;
/** Unregister a listener in participant RTPSWriter entities.
* @param listener, smart pointer to the listener interface to unregister
* @return true on success
*/
virtual bool unregister_in_writer(
std::shared_ptr<fastdds::statistics::IListener> listener) = 0;
/** Unregister a listener in participant RTPSReader entities.
* @param listener, smart pointer to the listener interface to unregister
* @return true on success
*/
virtual bool unregister_in_reader(
std::shared_ptr<fastdds::statistics::IListener> listener) = 0;
// lambda function to traverse the listener collection
template<class Function>
Function for_each_listener(
Function f)
{
std::unique_lock<std::recursive_mutex> lock(get_statistics_mutex());
auto temp_listeners = listeners_;
lock.unlock();
for (auto& listener : temp_listeners)
{
f(listener);
}
return f;
}
// returns if a mask statistics::EventKind may require participant writers update
bool are_writers_involved(
const uint32_t mask) const;
// returns if a mask statistics::EventKind may require participant readers update
bool are_readers_involved(
const uint32_t mask) const;
// TODO: methods for listeners callbacks
/*
* Report a message that is sent by the participant
* @param loc, destination
* @param payload_size, size of the current message
*/
void on_rtps_sent(
const fastrtps::rtps::Locator_t& loc,
unsigned long payload_size);
/*
* Report a message that is sent by the participant
* @param sender_guid GUID of the entity producing the message
* @param destination_locators_begin, start of locators range
* @param destination_locators_end, end of locators range
* @param payload_size, size of the current message
*/
template<class LocatorIteratorT>
void on_rtps_send(
const GUID_t& sender_guid,
const LocatorIteratorT& destination_locators_begin,
const LocatorIteratorT& destination_locators_end,
unsigned long payload_size)
{
if (false == is_statistics_builtin(sender_guid.entityId))
{
auto it = destination_locators_begin;
while (it != destination_locators_end)
{
on_rtps_sent(*it, payload_size);
++it;
}
}
}
/*
* Report that a new entity is discovered
* @param id, discovered entity GUID_t
*/
void on_entity_discovery(
const GUID_t& id);
/*
* Auxiliary method to report PDP message exchange.
* @param packages number of pdp packages sent
*/
void on_pdp_packet(
const uint32_t packages);
/*
* Report PDP message exchange.
* We filtered the non-pdp traffic here to minimize presence of statistics code in endpoints implementation.
* @param sender_guid GUID_t to filter
* @param destination_locators_begin, start of locators range
* @param destination_locators_end, end of locators range
*/
template<class LocatorIteratorT>
void on_pdp_packet(
const GUID_t& sender_guid,
const LocatorIteratorT& destination_locators_begin,
const LocatorIteratorT& destination_locators_end)
{
if (sender_guid.entityId == fastrtps::rtps::c_EntityId_SPDPWriter
&& destination_locators_begin != destination_locators_end)
{
uint32_t packages = 0;
auto it = destination_locators_begin;
while (it != destination_locators_end)
{
++it;
++packages;
}
on_pdp_packet(packages);
}
}
public:
/*
* Registers a listener in participant's statistics callback queue
* @param listener smart pointer to the listener being registered
* @param kind combination of fastdds::statistics::EventKind flags used as a mask
* @return successfully registered
*/
bool add_statistics_listener(
std::shared_ptr<fastdds::statistics::IListener> listener,
uint32_t kind);
/*
* Unregisters a listener in participant's statistics callback queue
* @param listener smart pointer to the listener being unregistered
* @param kind combination of fastdds::statistics::EventKind flags used as a mask
* @return successfully unregistered
*/
bool remove_statistics_listener(
std::shared_ptr<fastdds::statistics::IListener> listener,
uint32_t kind);
};
// auxiliary conversion functions
detail::Locator_s to_statistics_type(fastrtps::rtps::Locator_t);
detail::GUID_s to_statistics_type(fastrtps::rtps::GUID_t);
#else // dummy implementation
struct StatisticsAncillary {};
class StatisticsParticipantImpl
{
friend class fastrtps::rtps::PDP;
protected:
// inline methods for listeners callbacks
/*
* Report a message that is sent by the participant
* @param destination_locators_begin, start of locators range
* @param destination_locators_end, end of locators range
* @param payload_size, size of the current message
*/
template<class LocatorIteratorT>
inline void on_rtps_send(
const fastrtps::rtps::GUID_t&,
const LocatorIteratorT&,
const LocatorIteratorT&,
unsigned long)
{
}
/*
* Report that a new entity is discovered
* @param id, discovered entity GUID_t
*/
inline void on_entity_discovery(
const fastrtps::rtps::GUID_t&)
{
}
/*
* Report PDP message exchange.
* We filtered the non-pdp traffic here to minimize presence of statistics code in endpoints implementation.
* @param GUID_t to filter
* @param start of locators range
* @param end of locators range
*/
template<class LocatorIteratorT>
inline void on_pdp_packet(
const fastrtps::rtps::GUID_t&,
const LocatorIteratorT&,
const LocatorIteratorT&)
{
}
};
#endif // FASTDDS_STATISTICS
} // namespace statistics
} // namespace fastdds
} // namespace eprosima
#endif // _STATISTICS_RTPS_STATISTICSBASE_HPP_
<|endoftext|>
|
<commit_before>/***********************************************************************
created: Wed, 8th Feb 2012
author: Lukas E Meindl (based on code by Paul D Turner)
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2012 Paul D Turner & The CEGUI Development Team
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
***************************************************************************/
#include "CEGUI/RendererModules/OpenGL/RenderTarget.h"
#include "CEGUI/RendererModules/OpenGL/GeometryBufferBase.h"
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <cmath>
// Start of CEGUI namespace section
namespace CEGUI
{
//----------------------------------------------------------------------------//
template <typename T>
OpenGLRenderTarget<T>::OpenGLRenderTarget(OpenGLRendererBase& owner) :
d_owner(owner)
{
}
//----------------------------------------------------------------------------//
template <typename T>
OpenGLRenderTarget<T>::~OpenGLRenderTarget()
{
}
//----------------------------------------------------------------------------//
template <typename T>
void OpenGLRenderTarget<T>::activate()
{
glViewport(static_cast<GLsizei>(RenderTarget::d_area.left()),
static_cast<GLsizei>(RenderTarget::d_area.top()),
static_cast<GLsizei>(RenderTarget::d_area.getWidth()),
static_cast<GLsizei>(RenderTarget::d_area.getHeight()));
if (!RenderTarget::d_matrixValid)
updateMatrix();
d_owner.setViewProjectionMatrix(RenderTarget::d_matrix);
RenderTarget::activate();
}
//----------------------------------------------------------------------------//
template <typename T>
void OpenGLRenderTarget<T>::unprojectPoint(const GeometryBuffer& buff,
const glm::vec2& p_in, glm::vec2& p_out) const
{
if (!RenderTarget::d_matrixValid)
updateMatrix();
const OpenGLGeometryBufferBase& gb =
static_cast<const OpenGLGeometryBufferBase&>(buff);
const GLint vp[4] = {
static_cast<GLint>(RenderTarget::d_area.left()),
static_cast<GLint>(RenderTarget::d_area.top()),
static_cast<GLint>(RenderTarget::d_area.getWidth()),
static_cast<GLint>(RenderTarget::d_area.getHeight())
};
GLdouble in_x, in_y, in_z;
glm::ivec4 viewPort = glm::ivec4(vp[0], vp[1], vp[2], vp[3]);
const glm::mat4& projMatrix = RenderTarget::d_matrix;
const glm::mat4& modelMatrix = gb.getModelMatrix();
// unproject the ends of the ray
glm::vec3 unprojected1;
glm::vec3 unprojected2;
in_x = vp[2] * 0.5;
in_y = vp[3] * 0.5;
in_z = -RenderTarget::d_viewDistance;
unprojected1 = glm::unProject(glm::vec3(in_x, in_y, in_z), modelMatrix, projMatrix, viewPort);
in_x = p_in.x;
in_y = vp[3] - p_in.y;
in_z = 0.0;
unprojected2 = glm::unProject(glm::vec3(in_x, in_y, in_z), modelMatrix, projMatrix, viewPort);
// project points to orientate them with GeometryBuffer plane
glm::vec3 projected1;
glm::vec3 projected2;
glm::vec3 projected3;
in_x = 0.0;
in_y = 0.0;
projected1 = glm::project(glm::vec3(in_x, in_y, in_z), modelMatrix, projMatrix, viewPort);
in_x = 1.0;
in_y = 0.0;
projected2 = glm::project(glm::vec3(in_x, in_y, in_z), modelMatrix, projMatrix, viewPort);
in_x = 0.0;
in_y = 1.0;
projected3 = glm::project(glm::vec3(in_x, in_y, in_z), modelMatrix, projMatrix, viewPort);
// calculate vectors for generating the plane
const glm::vec3 pv1 = projected2 - projected1;
const glm::vec3 pv2 = projected3 - projected1;
// given the vectors, calculate the plane normal
const glm::vec3 planeNormal = glm::cross(pv1, pv2);
// calculate plane
const glm::vec3 planeNormalNormalized = glm::normalize(planeNormal);
const double pl_d = - glm::dot(projected1, planeNormalNormalized);
// calculate vector of picking ray
const glm::vec3 rv = unprojected1 - unprojected2;
// calculate intersection of ray and plane
const double pn_dot_r1 = glm::dot(unprojected1, planeNormal);
const double pn_dot_rv = glm::dot(rv, planeNormal);
const double tmp1 = pn_dot_rv != 0.0 ? (pn_dot_r1 + pl_d) / pn_dot_rv : 0.0;
const double is_x = unprojected1.x - rv.x * tmp1;
const double is_y = unprojected1.y - rv.y * tmp1;
p_out.x = static_cast<float>(is_x);
p_out.y = static_cast<float>(is_y);
}
//----------------------------------------------------------------------------//
template <typename T>
void OpenGLRenderTarget<T>::updateMatrix() const
{
RenderTarget::updateMatrix( RenderTarget::createViewProjMatrixForOpenGL() );
}
//----------------------------------------------------------------------------//
template <typename T>
OpenGLRendererBase& OpenGLRenderTarget<T>::getOwner()
{
return d_owner;
}
//----------------------------------------------------------------------------//
} // End of CEGUI namespace section
<commit_msg>GLES2/3 does not support GLdouble<commit_after>/***********************************************************************
created: Wed, 8th Feb 2012
author: Lukas E Meindl (based on code by Paul D Turner)
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2012 Paul D Turner & The CEGUI Development Team
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
***************************************************************************/
#include "CEGUI/RendererModules/OpenGL/RenderTarget.h"
#include "CEGUI/RendererModules/OpenGL/GeometryBufferBase.h"
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <cmath>
// Start of CEGUI namespace section
namespace CEGUI
{
//----------------------------------------------------------------------------//
template <typename T>
OpenGLRenderTarget<T>::OpenGLRenderTarget(OpenGLRendererBase& owner) :
d_owner(owner)
{
}
//----------------------------------------------------------------------------//
template <typename T>
OpenGLRenderTarget<T>::~OpenGLRenderTarget()
{
}
//----------------------------------------------------------------------------//
template <typename T>
void OpenGLRenderTarget<T>::activate()
{
glViewport(static_cast<GLsizei>(RenderTarget::d_area.left()),
static_cast<GLsizei>(RenderTarget::d_area.top()),
static_cast<GLsizei>(RenderTarget::d_area.getWidth()),
static_cast<GLsizei>(RenderTarget::d_area.getHeight()));
if (!RenderTarget::d_matrixValid)
updateMatrix();
d_owner.setViewProjectionMatrix(RenderTarget::d_matrix);
RenderTarget::activate();
}
//----------------------------------------------------------------------------//
template <typename T>
void OpenGLRenderTarget<T>::unprojectPoint(const GeometryBuffer& buff,
const glm::vec2& p_in, glm::vec2& p_out) const
{
if (!RenderTarget::d_matrixValid)
updateMatrix();
const OpenGLGeometryBufferBase& gb =
static_cast<const OpenGLGeometryBufferBase&>(buff);
const GLint vp[4] = {
static_cast<GLint>(RenderTarget::d_area.left()),
static_cast<GLint>(RenderTarget::d_area.top()),
static_cast<GLint>(RenderTarget::d_area.getWidth()),
static_cast<GLint>(RenderTarget::d_area.getHeight())
};
GLfloat in_x, in_y, in_z;
glm::ivec4 viewPort = glm::ivec4(vp[0], vp[1], vp[2], vp[3]);
const glm::mat4& projMatrix = RenderTarget::d_matrix;
const glm::mat4& modelMatrix = gb.getModelMatrix();
// unproject the ends of the ray
glm::vec3 unprojected1;
glm::vec3 unprojected2;
in_x = vp[2] * 0.5;
in_y = vp[3] * 0.5;
in_z = -RenderTarget::d_viewDistance;
unprojected1 = glm::unProject(glm::vec3(in_x, in_y, in_z), modelMatrix, projMatrix, viewPort);
in_x = p_in.x;
in_y = vp[3] - p_in.y;
in_z = 0.0;
unprojected2 = glm::unProject(glm::vec3(in_x, in_y, in_z), modelMatrix, projMatrix, viewPort);
// project points to orientate them with GeometryBuffer plane
glm::vec3 projected1;
glm::vec3 projected2;
glm::vec3 projected3;
in_x = 0.0;
in_y = 0.0;
projected1 = glm::project(glm::vec3(in_x, in_y, in_z), modelMatrix, projMatrix, viewPort);
in_x = 1.0;
in_y = 0.0;
projected2 = glm::project(glm::vec3(in_x, in_y, in_z), modelMatrix, projMatrix, viewPort);
in_x = 0.0;
in_y = 1.0;
projected3 = glm::project(glm::vec3(in_x, in_y, in_z), modelMatrix, projMatrix, viewPort);
// calculate vectors for generating the plane
const glm::vec3 pv1 = projected2 - projected1;
const glm::vec3 pv2 = projected3 - projected1;
// given the vectors, calculate the plane normal
const glm::vec3 planeNormal = glm::cross(pv1, pv2);
// calculate plane
const glm::vec3 planeNormalNormalized = glm::normalize(planeNormal);
const double pl_d = - glm::dot(projected1, planeNormalNormalized);
// calculate vector of picking ray
const glm::vec3 rv = unprojected1 - unprojected2;
// calculate intersection of ray and plane
const double pn_dot_r1 = glm::dot(unprojected1, planeNormal);
const double pn_dot_rv = glm::dot(rv, planeNormal);
const double tmp1 = pn_dot_rv != 0.0 ? (pn_dot_r1 + pl_d) / pn_dot_rv : 0.0;
const double is_x = unprojected1.x - rv.x * tmp1;
const double is_y = unprojected1.y - rv.y * tmp1;
p_out.x = static_cast<float>(is_x);
p_out.y = static_cast<float>(is_y);
}
//----------------------------------------------------------------------------//
template <typename T>
void OpenGLRenderTarget<T>::updateMatrix() const
{
RenderTarget::updateMatrix( RenderTarget::createViewProjMatrixForOpenGL() );
}
//----------------------------------------------------------------------------//
template <typename T>
OpenGLRendererBase& OpenGLRenderTarget<T>::getOwner()
{
return d_owner;
}
//----------------------------------------------------------------------------//
} // End of CEGUI namespace section
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: PlottingPositionHelper.hxx,v $
*
* $Revision: 1.1.1.1 $
*
* last change: $Author: bm $ $Date: 2003-10-06 09:58:33 $
*
* 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: 2003 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _CHART2_PLOTTINGPOSITIONHELPER_HXX
#define _CHART2_PLOTTINGPOSITIONHELPER_HXX
#ifndef _DRAFTS_COM_SUN_STAR_CHART2_EXPLICITSCALEDATA_HPP_
#include <drafts/com/sun/star/chart2/ExplicitScaleData.hpp>
#endif
#ifndef _DRAFTS_COM_SUN_STAR_CHART2_XTRANSFORMATION_HPP_
#include <drafts/com/sun/star/chart2/XTransformation.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_HOMOGENMATRIX_HPP_
#include <com/sun/star/drawing/HomogenMatrix.hpp>
#endif
#ifndef _B3D_HMATRIX_HXX
#include <goodies/hmatrix.hxx>
#endif
//.............................................................................
namespace chart
{
//.............................................................................
//-----------------------------------------------------------------------------
/**
*/
class PlottingPositionHelper
{
public:
PlottingPositionHelper();
virtual ~PlottingPositionHelper();
void setTransformationSceneToScreen( const ::com::sun::star::drawing::HomogenMatrix& rMatrix);
void setScales( const ::com::sun::star::uno::Sequence<
::drafts::com::sun::star::chart2::ExplicitScaleData >& rScales );
inline bool isLogicVisible( double fX, double fY, double fZ ) const;
inline void doLogicScaling( double* pX, double* pY, double* pZ ) const;
inline void clipLogicValues( double* pX, double* pY, double* pZ ) const;
virtual ::com::sun::star::uno::Reference< ::drafts::com::sun::star::chart2::XTransformation >
getTransformationLogicToScene() const;
inline double getLogicMinX() const;
inline double getLogicMinY() const;
inline double getLogicMinZ() const;
inline double getLogicMaxX() const;
inline double getLogicMaxY() const;
inline double getLogicMaxZ() const;
void getLogicMinimum( ::com::sun::star::uno::Sequence< double >& rSeq ) const;
void getLogicMaximum( ::com::sun::star::uno::Sequence< double >& rSeq ) const;
void getScreenValuesForMinimum( ::com::sun::star::uno::Sequence< double >& rSeq ) const;
void getScreenValuesForMaximum( ::com::sun::star::uno::Sequence< double >& rSeq ) const;
protected: //member
::com::sun::star::uno::Sequence<
::drafts::com::sun::star::chart2::ExplicitScaleData > m_aScales;
Matrix4D m_aMatrixScreenToScene;
//this is calculated based on m_aScales and m_aMatrixScreenToScene
mutable ::com::sun::star::uno::Reference<
::drafts::com::sun::star::chart2::XTransformation > m_xTransformationLogicToScene;
};
bool PlottingPositionHelper::isLogicVisible(
double fX, double fY, double fZ ) const
{
return fX >= m_aScales[0].Minimum && fX <= m_aScales[0].Maximum
&& fY >= m_aScales[1].Minimum && fY <= m_aScales[1].Maximum
&& fZ >= m_aScales[2].Minimum && fZ <= m_aScales[2].Maximum;
}
void PlottingPositionHelper::doLogicScaling( double* pX, double* pY, double* pZ ) const
{
if(pX && m_aScales[0].Scaling.is())
*pX = m_aScales[0].Scaling->doScaling(*pX);
if(pY && m_aScales[1].Scaling.is())
*pY = m_aScales[1].Scaling->doScaling(*pY);
if(pZ && m_aScales[2].Scaling.is())
*pZ = m_aScales[2].Scaling->doScaling(*pZ);
}
void PlottingPositionHelper::clipLogicValues( double* pX, double* pY, double* pZ ) const
{
if(pX)
{
if( *pX < m_aScales[0].Minimum )
*pX = m_aScales[0].Minimum;
else if( *pX > m_aScales[0].Maximum )
*pX = m_aScales[0].Maximum;
}
if(pY)
{
if( *pY < m_aScales[1].Minimum )
*pY = m_aScales[1].Minimum;
else if( *pY > m_aScales[1].Maximum )
*pY = m_aScales[1].Maximum;
}
if(pZ)
{
if( *pZ < m_aScales[2].Minimum )
*pZ = m_aScales[2].Minimum;
else if( *pZ > m_aScales[2].Maximum )
*pZ = m_aScales[2].Maximum;
}
}
inline double PlottingPositionHelper::getLogicMinX() const
{
return m_aScales[0].Minimum;
}
inline double PlottingPositionHelper::getLogicMinY() const
{
return m_aScales[1].Minimum;
}
inline double PlottingPositionHelper::getLogicMinZ() const
{
return m_aScales[2].Minimum;
}
inline double PlottingPositionHelper::getLogicMaxX() const
{
return m_aScales[0].Maximum;
}
inline double PlottingPositionHelper::getLogicMaxY() const
{
return m_aScales[1].Maximum;
}
inline double PlottingPositionHelper::getLogicMaxZ() const
{
return m_aScales[2].Maximum;
}
//.............................................................................
} //namespace chart
//.............................................................................
#endif
<commit_msg>added methods isMathematicalOrientationX/Y/Z<commit_after>/*************************************************************************
*
* $RCSfile: PlottingPositionHelper.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: iha $ $Date: 2003-11-19 13:13:28 $
*
* 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: 2003 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _CHART2_PLOTTINGPOSITIONHELPER_HXX
#define _CHART2_PLOTTINGPOSITIONHELPER_HXX
#ifndef _DRAFTS_COM_SUN_STAR_CHART2_EXPLICITSCALEDATA_HPP_
#include <drafts/com/sun/star/chart2/ExplicitScaleData.hpp>
#endif
#ifndef _DRAFTS_COM_SUN_STAR_CHART2_XTRANSFORMATION_HPP_
#include <drafts/com/sun/star/chart2/XTransformation.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_HOMOGENMATRIX_HPP_
#include <com/sun/star/drawing/HomogenMatrix.hpp>
#endif
#ifndef _B3D_HMATRIX_HXX
#include <goodies/hmatrix.hxx>
#endif
//.............................................................................
namespace chart
{
//.............................................................................
//-----------------------------------------------------------------------------
/**
*/
class PlottingPositionHelper
{
public:
PlottingPositionHelper();
virtual ~PlottingPositionHelper();
void setTransformationSceneToScreen( const ::com::sun::star::drawing::HomogenMatrix& rMatrix);
void setScales( const ::com::sun::star::uno::Sequence<
::drafts::com::sun::star::chart2::ExplicitScaleData >& rScales );
inline bool isLogicVisible( double fX, double fY, double fZ ) const;
inline void doLogicScaling( double* pX, double* pY, double* pZ ) const;
inline void clipLogicValues( double* pX, double* pY, double* pZ ) const;
virtual ::com::sun::star::uno::Reference< ::drafts::com::sun::star::chart2::XTransformation >
getTransformationLogicToScene() const;
inline double getLogicMinX() const;
inline double getLogicMinY() const;
inline double getLogicMinZ() const;
inline double getLogicMaxX() const;
inline double getLogicMaxY() const;
inline double getLogicMaxZ() const;
inline bool isMathematicalOrientationX() const;
inline bool isMathematicalOrientationY() const;
inline bool isMathematicalOrientationZ() const;
void getLogicMinimum( ::com::sun::star::uno::Sequence< double >& rSeq ) const;
void getLogicMaximum( ::com::sun::star::uno::Sequence< double >& rSeq ) const;
void getScreenValuesForMinimum( ::com::sun::star::uno::Sequence< double >& rSeq ) const;
void getScreenValuesForMaximum( ::com::sun::star::uno::Sequence< double >& rSeq ) const;
protected: //member
::com::sun::star::uno::Sequence<
::drafts::com::sun::star::chart2::ExplicitScaleData > m_aScales;
Matrix4D m_aMatrixScreenToScene;
//this is calculated based on m_aScales and m_aMatrixScreenToScene
mutable ::com::sun::star::uno::Reference<
::drafts::com::sun::star::chart2::XTransformation > m_xTransformationLogicToScene;
};
bool PlottingPositionHelper::isLogicVisible(
double fX, double fY, double fZ ) const
{
return fX >= m_aScales[0].Minimum && fX <= m_aScales[0].Maximum
&& fY >= m_aScales[1].Minimum && fY <= m_aScales[1].Maximum
&& fZ >= m_aScales[2].Minimum && fZ <= m_aScales[2].Maximum;
}
void PlottingPositionHelper::doLogicScaling( double* pX, double* pY, double* pZ ) const
{
if(pX && m_aScales[0].Scaling.is())
*pX = m_aScales[0].Scaling->doScaling(*pX);
if(pY && m_aScales[1].Scaling.is())
*pY = m_aScales[1].Scaling->doScaling(*pY);
if(pZ && m_aScales[2].Scaling.is())
*pZ = m_aScales[2].Scaling->doScaling(*pZ);
}
void PlottingPositionHelper::clipLogicValues( double* pX, double* pY, double* pZ ) const
{
if(pX)
{
if( *pX < m_aScales[0].Minimum )
*pX = m_aScales[0].Minimum;
else if( *pX > m_aScales[0].Maximum )
*pX = m_aScales[0].Maximum;
}
if(pY)
{
if( *pY < m_aScales[1].Minimum )
*pY = m_aScales[1].Minimum;
else if( *pY > m_aScales[1].Maximum )
*pY = m_aScales[1].Maximum;
}
if(pZ)
{
if( *pZ < m_aScales[2].Minimum )
*pZ = m_aScales[2].Minimum;
else if( *pZ > m_aScales[2].Maximum )
*pZ = m_aScales[2].Maximum;
}
}
inline double PlottingPositionHelper::getLogicMinX() const
{
return m_aScales[0].Minimum;
}
inline double PlottingPositionHelper::getLogicMinY() const
{
return m_aScales[1].Minimum;
}
inline double PlottingPositionHelper::getLogicMinZ() const
{
return m_aScales[2].Minimum;
}
inline double PlottingPositionHelper::getLogicMaxX() const
{
return m_aScales[0].Maximum;
}
inline double PlottingPositionHelper::getLogicMaxY() const
{
return m_aScales[1].Maximum;
}
inline double PlottingPositionHelper::getLogicMaxZ() const
{
return m_aScales[2].Maximum;
}
inline bool PlottingPositionHelper::isMathematicalOrientationX() const
{
return ::drafts::com::sun::star::chart2::AxisOrientation_MATHEMATICAL == m_aScales[0].Orientation;
}
inline bool PlottingPositionHelper::isMathematicalOrientationY() const
{
return ::drafts::com::sun::star::chart2::AxisOrientation_MATHEMATICAL == m_aScales[1].Orientation;
}
inline bool PlottingPositionHelper::isMathematicalOrientationZ() const
{
return ::drafts::com::sun::star::chart2::AxisOrientation_MATHEMATICAL == m_aScales[2].Orientation;
}
//.............................................................................
} //namespace chart
//.............................................................................
#endif
<|endoftext|>
|
<commit_before>#include <chord.h>
#include "merkle_syncer.h"
#include "qhash.h"
#include "async.h"
#include "bigint.h"
#include <id_utils.h>
#include <comm.h>
//#define MERKLE_SYNC_TRACE
//#define MERKLE_SYNC_DETAILED_TRACE
// ---------------------------------------------------------------------------
// util junk
// Check whether [l1, r1] overlaps [l2, r2] on the circle.
static bool
overlap (const bigint &l1, const bigint &r1, const bigint &l2, const bigint &r2)
{
// There might be a more efficient way to do this..
return (betweenbothincl (l1, r1, l2) || betweenbothincl (l1, r1, r2)
|| betweenbothincl (l2, r2, l1) || betweenbothincl (l2, r2, r1));
}
// ---------------------------------------------------------------------------
// merkle_syncer
merkle_syncer::merkle_syncer (merkle_tree *ltree, rpcfnc_t rpcfnc, missingfnc_t missingfnc)
: ltree (ltree), rpcfnc (rpcfnc), missingfnc (missingfnc)
{
fatal_err = NULL;
sync_done = false;
}
void
merkle_syncer::sync (bigint rngmin, bigint rngmax)
{
local_rngmin = rngmin;
local_rngmax = rngmax;
// start at the root of the merkle tree
sendnode (0, 0);
}
void
merkle_syncer::dump ()
{
warn << "THIS: " << (u_int)this << "\n";
warn << " st.size () " << st.size () << "\n";
}
void
merkle_syncer::doRPC (int procno, ptr<void> in, void *out, aclnt_cb cb)
{
// Must resort to bundling all values into one argument since
// async/callback.h is configured with too few parameters.
struct RPC_delay_args args (merklesync_program_1, procno, in, out, cb,
NULL);
(*rpcfnc) (&args);
}
void
merkle_syncer::setdone ()
{
sync_done = true;
}
void
merkle_syncer::error (str err)
{
warn << (u_int)this << ": SYNCER ERROR: " << err << "\n";
fatal_err = err;
setdone ();
}
str
merkle_syncer::getsummary ()
{
assert (sync_done);
strbuf sb;
sb << "[" << local_rngmin << "," << local_rngmax << "] ";
if (fatal_err)
sb << fatal_err;
if (0)
sb << "<log " << log << ">\n";
return sb;
}
void
merkle_syncer::next (void)
{
#ifdef MERKLE_SYNC_DETAILED_TRACE
warn << "local range [" << local_rngmin << "," << local_rngmax << "]\n";
#endif
assert (!sync_done);
assert (!fatal_err);
// st is queue of pending index nodes
while (st.size ()) {
pair<merkle_rpc_node, int> &p = st.back ();
merkle_rpc_node *rnode = &p.first;
assert (!rnode->isleaf);
merkle_node *lnode = ltree->lookup_exact (rnode->depth, rnode->prefix);
if (!lnode) {
fatal << "lookup_exact didn't match for " << rnode->prefix << " at depth " << rnode->depth << "\n";
}
#ifdef MERKLE_SYNC_DETAILED_TRACE
warn << "starting from slot " << p.second << "\n";
#endif
// XXX not clear p.second will ever enter > 0
while (p.second < 64) {
u_int i = p.second;
p.second += 1;
#ifdef MERKLE_SYNC_DETAILED_TRACE
warn << "CHECKING: " << i;
#endif
bigint remote = tobigint (rnode->child_hash[i]);
bigint local = tobigint (lnode->child (i)->hash);
u_int depth = rnode->depth + 1;
//prefix is the high bits of the first key
// the node is responsible for.
merkle_hash prefix = rnode->prefix;
prefix.write_slot (rnode->depth, i);
bigint slot_rngmin = tobigint (prefix);
bigint slot_width = bigint (1) << (160 - 6*depth);
bigint slot_rngmax = slot_rngmin + slot_width - 1;
bool overlaps = overlap (local_rngmin, local_rngmax, slot_rngmin, slot_rngmax);
if (remote != local) {
#ifdef MERKLE_SYNC_DETAILED_TRACE
warnx << " differ. local " << local << " != remote " << remote;
#endif
if (overlaps) {
#ifdef MERKLE_SYNC_DETAILED_TRACE
warnx << " .. sending\n";
#endif
sendnode (depth, prefix);
return;
} else {
#ifdef MERKLE_SYNC_DETAILED_TRACE
warnx << " .. not sending\n";
#endif
}
} else {
#ifdef MERKLE_SYNC_DETAILED_TRACE
warnx << " same. local " << local << " == remote " << remote << "\n";
#endif
}
}
assert (p.second == 64);
st.pop_back ();
}
#ifdef MERKLE_SYNC_DETAILED_TRACE
warn << "DONE .. in NEXT\n";
#endif
setdone ();
#ifdef MERKLE_SYNC_DETAILED_TRACE
warn << "OK!\n";
#endif
}
void
merkle_syncer::sendnode (u_int depth, const merkle_hash &prefix)
{
ref<sendnode_arg> arg = New refcounted<sendnode_arg> ();
ref<sendnode_res> res = New refcounted<sendnode_res> ();
u_int lnode_depth;
merkle_node *lnode = ltree->lookup (&lnode_depth, depth, prefix);
assert (lnode);
assert (lnode_depth == depth);
format_rpcnode (ltree, depth, prefix, lnode, &arg->node);
arg->rngmin = local_rngmin;
arg->rngmax = local_rngmax;
doRPC (MERKLESYNC_SENDNODE, arg, res,
wrap (this, &merkle_syncer::sendnode_cb, arg, res));
}
void
merkle_syncer::sendnode_cb (ref<sendnode_arg> arg, ref<sendnode_res> res,
clnt_stat err)
{
if (err) {
error (strbuf () << "SENDNODE: rpc error " << err);
return;
} else if (res->status != MERKLE_OK) {
error (strbuf () << "SENDNODE: protocol error " << err2str (res->status));
return;
}
merkle_rpc_node *rnode = &res->resok->node;
merkle_node *lnode = ltree->lookup_exact (rnode->depth, rnode->prefix);
if (!lnode) {
fatal << "lookup failed: " << rnode->prefix << " at " << rnode->depth << "\n";
}
compare_nodes (ltree, local_rngmin, local_rngmax, lnode, rnode,
missingfnc, rpcfnc);
if (!lnode->isleaf () && !rnode->isleaf) {
#ifdef MERKLE_SYNC_TRACE
warn << "I vs I\n";
#endif
st.push_back (pair<merkle_rpc_node, int> (*rnode, 0));
}
next ();
}
// ---------------------------------------------------------------------------
// merkle_getkeyrange
void
merkle_getkeyrange::go ()
{
if (between (rngmax, incID (current), current)) {
#ifdef MERKLE_SYNC_TRACE
warn << "merkle_getkeyrange::go () ==> DONE\n";
#endif
delete this;
return;
}
ref<getkeys_arg> arg = New refcounted<getkeys_arg> ();
arg->rngmin = current;
arg->rngmax = rngmax;
ref<getkeys_res> res = New refcounted<getkeys_res> ();
doRPC (MERKLESYNC_GETKEYS, arg, res,
wrap (this, &merkle_getkeyrange::getkeys_cb, arg, res));
}
void
merkle_getkeyrange::getkeys_cb (ref<getkeys_arg> arg, ref<getkeys_res> res,
clnt_stat err)
{
if (err) {
warn << "GETKEYS: rpc error " << err << "\n";
delete this;
return;
} else if (res->status != MERKLE_OK) {
warn << "GETKEYS: protocol error " << err2str (res->status) << "\n";
delete this;
return;
}
vec<merkle_hash> rkeys;
chordID round_max = current;
chordID next_cur = current;
for (u_int i = 0; i < res->resok->keys.size (); i++) {
const merkle_hash &key = res->resok->keys[i];
rkeys.push_back (key);
bigint bkey = tobigint(key);
if (round_max < bkey) round_max = bkey;
if (betweenbothincl (next_cur, incID (bkey), bkey))
next_cur = incID (bkey);
}
compare_keylists (lkeys, rkeys, current, round_max, missing);
current = next_cur;
if (!res->resok->morekeys)
current = incID (rngmax); // set done
go ();
}
void
merkle_getkeyrange::doRPC (int procno, ptr<void> in, void *out, aclnt_cb cb)
{
// Must resort to bundling all values into one argument since
// async/callback.h is configured with too few parameters.
struct RPC_delay_args args (merklesync_program_1, procno, in, out, cb,
NULL);
(*rpcfnc) (&args);
}
// ---------------------------------------------------------------------------
void
compare_keylists (vec<merkle_hash> lkeys,
vec<merkle_hash> vrkeys,
chordID rngmin, chordID rngmax,
missingfnc_t missingfnc)
{
// populate a hash table with the remote keys
qhash<merkle_hash, int> rkeys;
for (u_int i = 0; i < vrkeys.size (); i++) {
if (betweenbothincl (rngmin, rngmax, tobigint(vrkeys[i])))
rkeys.insert (vrkeys[i], 1);
}
// do I have something he doesn't have?
for (unsigned int i = 0; i < lkeys.size (); i++) {
if (!rkeys[lkeys[i]]) {
(*missingfnc) (tobigint(lkeys[i]), false);
} else {
rkeys.remove (lkeys[i]);
}
}
//anything left: he has and I don't
qhash_slot<merkle_hash, int> *slot = rkeys.first ();
while (slot) {
warn << "local missing [" << rngmin << ", " << rngmax << "] key=" << slot->key << "\n";
(*missingfnc) (tobigint(slot->key), true);
slot = rkeys.next (slot);
}
}
void
compare_nodes (merkle_tree *ltree, bigint rngmin, bigint rngmax,
merkle_node *lnode, merkle_rpc_node *rnode,
missingfnc_t missingfnc, rpcfnc_t rpcfnc)
{
#ifdef MERKLE_SYNC_TRACE
warn << (lnode->isleaf () ? "L" : "I")
<< " vs "
<< (rnode->isleaf ? "L" : "I")
<< "\n";
#endif
if (rnode->isleaf) {
vec<merkle_hash> lkeys = database_get_keys (ltree->db, rnode->depth, rnode->prefix);
vec<merkle_hash> rkeys;
for (u_int i = 0; i < rnode->child_hash.size (); i++) {
assert (betweenbothincl (rngmin, rngmax, tobigint (rnode->child_hash[i])));
rkeys.push_back (rnode->child_hash[i]);
}
compare_keylists (lkeys, rkeys, rngmin, rngmax, missingfnc);
} else if (lnode->isleaf () && !rnode->isleaf) {
bigint tmpmin = tobigint (rnode->prefix);
bigint node_width = bigint (1) << (160 - rnode->depth);
bigint tmpmax = tmpmin + node_width - 1;
// further constrain to be within the host's range of interest
if (between (tmpmin, tmpmax, rngmin))
tmpmin = rngmin;
if (between (tmpmin, tmpmax, rngmax))
tmpmax = rngmax;
vec<merkle_hash> lkeys = database_get_keys (ltree->db, rnode->depth, rnode->prefix);
vNew merkle_getkeyrange (ltree->db, tmpmin, tmpmax, lkeys, missingfnc, rpcfnc);
}
}
// ---------------------------------------------------------------------------
void
format_rpcnode (merkle_tree *ltree, u_int depth, const merkle_hash &prefix,
const merkle_node *node, merkle_rpc_node *rpcnode)
{
rpcnode->depth = depth;
rpcnode->prefix = prefix;
rpcnode->count = node->count;
rpcnode->hash = node->hash;
rpcnode->isleaf = node->isleaf ();
if (!node->isleaf ()) {
rpcnode->child_hash.setsize (64);
for (int i = 0; i < 64; i++)
rpcnode->child_hash[i] = node->child (i)->hash;
} else {
vec<merkle_hash> keys = database_get_keys (ltree->db, depth, prefix);
if (keys.size () != rpcnode->count) {
warn << "\n\n\n----------------------------------------------------------\n";
warn << "BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG\n";
warn << "Send this output to chord@pdos.lcs.mit.edu\n";
warn << "BUG: " << depth << " " << prefix << "\n";
warn << "BUG: " << keys.size () << " != " << rpcnode->count << "\n";
ltree->check_invariants ();
warn << "BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG\n";
panic << "----------------------------------------------------------\n\n\n";
}
rpcnode->child_hash.setsize (keys.size ());
for (u_int i = 0; i < keys.size (); i++) {
rpcnode->child_hash[i] = keys[i];
}
}
}
<commit_msg>Filter keys pushed onto compare_keyslists lists based on range. Reduce warn verbosity.<commit_after>#include <chord.h>
#include "merkle_syncer.h"
#include "qhash.h"
#include "async.h"
#include "bigint.h"
#include <id_utils.h>
#include <comm.h>
//#define MERKLE_SYNC_TRACE
//#define MERKLE_SYNC_DETAILED_TRACE
// ---------------------------------------------------------------------------
// util junk
// Check whether [l1, r1] overlaps [l2, r2] on the circle.
static bool
overlap (const bigint &l1, const bigint &r1, const bigint &l2, const bigint &r2)
{
// There might be a more efficient way to do this..
return (betweenbothincl (l1, r1, l2) || betweenbothincl (l1, r1, r2)
|| betweenbothincl (l2, r2, l1) || betweenbothincl (l2, r2, r1));
}
// ---------------------------------------------------------------------------
// merkle_syncer
merkle_syncer::merkle_syncer (merkle_tree *ltree, rpcfnc_t rpcfnc, missingfnc_t missingfnc)
: ltree (ltree), rpcfnc (rpcfnc), missingfnc (missingfnc)
{
fatal_err = NULL;
sync_done = false;
}
void
merkle_syncer::sync (bigint rngmin, bigint rngmax)
{
local_rngmin = rngmin;
local_rngmax = rngmax;
// start at the root of the merkle tree
sendnode (0, 0);
}
void
merkle_syncer::dump ()
{
warn << "THIS: " << (u_int)this << "\n";
warn << " st.size () " << st.size () << "\n";
}
void
merkle_syncer::doRPC (int procno, ptr<void> in, void *out, aclnt_cb cb)
{
// Must resort to bundling all values into one argument since
// async/callback.h is configured with too few parameters.
struct RPC_delay_args args (merklesync_program_1, procno, in, out, cb,
NULL);
(*rpcfnc) (&args);
}
void
merkle_syncer::setdone ()
{
sync_done = true;
}
void
merkle_syncer::error (str err)
{
warn << (u_int)this << ": SYNCER ERROR: " << err << "\n";
fatal_err = err;
setdone ();
}
str
merkle_syncer::getsummary ()
{
assert (sync_done);
strbuf sb;
sb << "[" << local_rngmin << "," << local_rngmax << "] ";
if (fatal_err)
sb << fatal_err;
if (0)
sb << "<log " << log << ">\n";
return sb;
}
void
merkle_syncer::next (void)
{
#ifdef MERKLE_SYNC_DETAILED_TRACE
warn << "local range [" << local_rngmin << "," << local_rngmax << "]\n";
#endif
assert (!sync_done);
assert (!fatal_err);
// st is queue of pending index nodes
while (st.size ()) {
pair<merkle_rpc_node, int> &p = st.back ();
merkle_rpc_node *rnode = &p.first;
assert (!rnode->isleaf);
merkle_node *lnode = ltree->lookup_exact (rnode->depth, rnode->prefix);
if (!lnode) {
fatal << "lookup_exact didn't match for " << rnode->prefix << " at depth " << rnode->depth << "\n";
}
#ifdef MERKLE_SYNC_DETAILED_TRACE
warn << "starting from slot " << p.second << "\n";
#endif
// XXX not clear p.second will ever enter > 0
while (p.second < 64) {
u_int i = p.second;
p.second += 1;
#ifdef MERKLE_SYNC_DETAILED_TRACE
warn << "CHECKING: " << i;
#endif
bigint remote = tobigint (rnode->child_hash[i]);
bigint local = tobigint (lnode->child (i)->hash);
u_int depth = rnode->depth + 1;
//prefix is the high bits of the first key
// the node is responsible for.
merkle_hash prefix = rnode->prefix;
prefix.write_slot (rnode->depth, i);
bigint slot_rngmin = tobigint (prefix);
bigint slot_width = bigint (1) << (160 - 6*depth);
bigint slot_rngmax = slot_rngmin + slot_width - 1;
bool overlaps = overlap (local_rngmin, local_rngmax, slot_rngmin, slot_rngmax);
if (remote != local) {
#ifdef MERKLE_SYNC_DETAILED_TRACE
warnx << " differ. local " << local << " != remote " << remote;
#endif
if (overlaps) {
#ifdef MERKLE_SYNC_DETAILED_TRACE
warnx << " .. sending\n";
#endif
sendnode (depth, prefix);
return;
} else {
#ifdef MERKLE_SYNC_DETAILED_TRACE
warnx << " .. not sending\n";
#endif
}
} else {
#ifdef MERKLE_SYNC_DETAILED_TRACE
warnx << " same. local " << local << " == remote " << remote << "\n";
#endif
}
}
assert (p.second == 64);
st.pop_back ();
}
#ifdef MERKLE_SYNC_DETAILED_TRACE
warn << "DONE .. in NEXT\n";
#endif
setdone ();
#ifdef MERKLE_SYNC_DETAILED_TRACE
warn << "OK!\n";
#endif
}
void
merkle_syncer::sendnode (u_int depth, const merkle_hash &prefix)
{
ref<sendnode_arg> arg = New refcounted<sendnode_arg> ();
ref<sendnode_res> res = New refcounted<sendnode_res> ();
u_int lnode_depth;
merkle_node *lnode = ltree->lookup (&lnode_depth, depth, prefix);
assert (lnode);
assert (lnode_depth == depth);
format_rpcnode (ltree, depth, prefix, lnode, &arg->node);
arg->rngmin = local_rngmin;
arg->rngmax = local_rngmax;
doRPC (MERKLESYNC_SENDNODE, arg, res,
wrap (this, &merkle_syncer::sendnode_cb, arg, res));
}
void
merkle_syncer::sendnode_cb (ref<sendnode_arg> arg, ref<sendnode_res> res,
clnt_stat err)
{
if (err) {
error (strbuf () << "SENDNODE: rpc error " << err);
return;
} else if (res->status != MERKLE_OK) {
error (strbuf () << "SENDNODE: protocol error " << err2str (res->status));
return;
}
merkle_rpc_node *rnode = &res->resok->node;
merkle_node *lnode = ltree->lookup_exact (rnode->depth, rnode->prefix);
if (!lnode) {
fatal << "lookup failed: " << rnode->prefix << " at " << rnode->depth << "\n";
}
compare_nodes (ltree, local_rngmin, local_rngmax, lnode, rnode,
missingfnc, rpcfnc);
if (!lnode->isleaf () && !rnode->isleaf) {
#ifdef MERKLE_SYNC_TRACE
warn << "I vs I\n";
#endif
st.push_back (pair<merkle_rpc_node, int> (*rnode, 0));
}
next ();
}
// ---------------------------------------------------------------------------
// merkle_getkeyrange
void
merkle_getkeyrange::go ()
{
if (between (rngmax, incID (current), current)) {
#ifdef MERKLE_SYNC_TRACE
warn << "merkle_getkeyrange::go () ==> DONE\n";
#endif
delete this;
return;
}
ref<getkeys_arg> arg = New refcounted<getkeys_arg> ();
arg->rngmin = current;
arg->rngmax = rngmax;
ref<getkeys_res> res = New refcounted<getkeys_res> ();
doRPC (MERKLESYNC_GETKEYS, arg, res,
wrap (this, &merkle_getkeyrange::getkeys_cb, arg, res));
}
void
merkle_getkeyrange::getkeys_cb (ref<getkeys_arg> arg, ref<getkeys_res> res,
clnt_stat err)
{
if (err) {
warn << "GETKEYS: rpc error " << err << "\n";
delete this;
return;
} else if (res->status != MERKLE_OK) {
warn << "GETKEYS: protocol error " << err2str (res->status) << "\n";
delete this;
return;
}
vec<merkle_hash> rkeys;
chordID round_max = current;
chordID next_cur = current;
for (u_int i = 0; i < res->resok->keys.size (); i++) {
const merkle_hash &key = res->resok->keys[i];
rkeys.push_back (key);
bigint bkey = tobigint(key);
if (round_max < bkey) round_max = bkey;
if (betweenbothincl (next_cur, incID (bkey), bkey))
next_cur = incID (bkey);
}
compare_keylists (lkeys, rkeys, current, round_max, missing);
current = next_cur;
if (!res->resok->morekeys)
current = incID (rngmax); // set done
go ();
}
void
merkle_getkeyrange::doRPC (int procno, ptr<void> in, void *out, aclnt_cb cb)
{
// Must resort to bundling all values into one argument since
// async/callback.h is configured with too few parameters.
struct RPC_delay_args args (merklesync_program_1, procno, in, out, cb,
NULL);
(*rpcfnc) (&args);
}
// ---------------------------------------------------------------------------
void
compare_keylists (vec<merkle_hash> lkeys,
vec<merkle_hash> vrkeys,
chordID rngmin, chordID rngmax,
missingfnc_t missingfnc)
{
// populate a hash table with the remote keys
qhash<merkle_hash, int> rkeys;
for (u_int i = 0; i < vrkeys.size (); i++) {
if (betweenbothincl (rngmin, rngmax, tobigint(vrkeys[i])))
rkeys.insert (vrkeys[i], 1);
}
// do I have something he doesn't have?
for (unsigned int i = 0; i < lkeys.size (); i++) {
if (!rkeys[lkeys[i]]) {
#ifdef MERKLE_SYNC_DETAILED_TRACE
warn << "remote missing [" << rngmin << ", " << rngmax << "] key=" << lkeys[i] << "\n";
#endif
(*missingfnc) (tobigint(lkeys[i]), false);
} else {
rkeys.remove (lkeys[i]);
}
}
//anything left: he has and I don't
qhash_slot<merkle_hash, int> *slot = rkeys.first ();
while (slot) {
#ifdef MERKLE_SYNC_DETAILED_TRACE
warn << "local missing [" << rngmin << ", " << rngmax << "] key=" << slot->key << "\n";
#endif
(*missingfnc) (tobigint(slot->key), true);
slot = rkeys.next (slot);
}
}
void
compare_nodes (merkle_tree *ltree, bigint rngmin, bigint rngmax,
merkle_node *lnode, merkle_rpc_node *rnode,
missingfnc_t missingfnc, rpcfnc_t rpcfnc)
{
#ifdef MERKLE_SYNC_TRACE
warn << (lnode->isleaf () ? "L" : "I")
<< " vs "
<< (rnode->isleaf ? "L" : "I")
<< "\n";
#endif
if (rnode->isleaf) {
vec<merkle_hash> lkeys = database_get_keys (ltree->db, rnode->depth, rnode->prefix);
vec<merkle_hash> rkeys;
for (u_int i = 0; i < rnode->child_hash.size (); i++) {
if (betweenbothincl (rngmin, rngmax, tobigint (rnode->child_hash[i])))
rkeys.push_back (rnode->child_hash[i]);
}
compare_keylists (lkeys, rkeys, rngmin, rngmax, missingfnc);
} else if (lnode->isleaf () && !rnode->isleaf) {
bigint tmpmin = tobigint (rnode->prefix);
bigint node_width = bigint (1) << (160 - rnode->depth);
bigint tmpmax = tmpmin + node_width - 1;
// further constrain to be within the host's range of interest
if (between (tmpmin, tmpmax, rngmin))
tmpmin = rngmin;
if (between (tmpmin, tmpmax, rngmax))
tmpmax = rngmax;
vec<merkle_hash> lkeys = database_get_keys (ltree->db, rnode->depth, rnode->prefix);
vNew merkle_getkeyrange (ltree->db, tmpmin, tmpmax, lkeys, missingfnc, rpcfnc);
}
}
// ---------------------------------------------------------------------------
void
format_rpcnode (merkle_tree *ltree, u_int depth, const merkle_hash &prefix,
const merkle_node *node, merkle_rpc_node *rpcnode)
{
rpcnode->depth = depth;
rpcnode->prefix = prefix;
rpcnode->count = node->count;
rpcnode->hash = node->hash;
rpcnode->isleaf = node->isleaf ();
if (!node->isleaf ()) {
rpcnode->child_hash.setsize (64);
for (int i = 0; i < 64; i++)
rpcnode->child_hash[i] = node->child (i)->hash;
} else {
vec<merkle_hash> keys = database_get_keys (ltree->db, depth, prefix);
if (keys.size () != rpcnode->count) {
warn << "\n\n\n----------------------------------------------------------\n";
warn << "BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG\n";
warn << "Send this output to chord@pdos.lcs.mit.edu\n";
warn << "BUG: " << depth << " " << prefix << "\n";
warn << "BUG: " << keys.size () << " != " << rpcnode->count << "\n";
ltree->check_invariants ();
warn << "BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG\n";
panic << "----------------------------------------------------------\n\n\n";
}
rpcnode->child_hash.setsize (keys.size ());
for (u_int i = 0; i < keys.size (); i++) {
rpcnode->child_hash[i] = keys[i];
}
}
}
<|endoftext|>
|
<commit_before>#include "catch.hpp"
#include "mockPlatform.h"
#include "scene/importer.h"
#include "yaml-cpp/yaml.h"
#include <iostream>
#include <vector>
using namespace Tangram;
using namespace YAML;
std::shared_ptr<MockPlatform> getPlatformWithImportFiles() {
auto platform = std::make_shared<MockPlatform>();
platform->putMockUrlContents("/root/a.yaml", R"END(
import: b.yaml
value: a
has_a: true
)END");
platform->putMockUrlContents("/root/b.yaml", R"END(
value: b
has_b: true
)END");
platform->putMockUrlContents("/root/c.yaml", R"END(
import: [a.yaml, b.yaml]
value: c
has_c: true
)END");
platform->putMockUrlContents("/root/cycle_simple.yaml", R"END(
import: cycle_simple.yaml
value: cyclic
)END");
platform->putMockUrlContents("/root/cycle_tricky.yaml", R"END(
import: imports/cycle_tricky.yaml
has_cycle_tricky: true
)END");
platform->putMockUrlContents("/root/imports/cycle_tricky.yaml", R"END(
import: ../cycle_tricky.yaml
has_imports_cycle_tricky: true
)END");
platform->putMockUrlContents("/root/urls.yaml", R"END(
import: imports/urls.yaml
fonts: { fontA: { url: https://host/font.woff } }
sources: { sourceA: { url: 'https://host/tiles/{z}/{y}/{x}.mvt' } }
textures:
tex1: { url: "path/to/texture.png" }
tex2: { url: "../up_a_directory.png" }
styles:
styleA:
texture: "path/to/texture.png"
shaders:
uniforms:
u_tex1: "/at_root.png"
u_tex2: ["path/to/texture.png", tex2]
u_tex3: tex3
u_bool: true
u_float: 0.25
)END");
platform->putMockUrlContents("/root/imports/urls.yaml", R"END(
fonts: { fontB: [ { url: fonts/0.ttf }, { url: fonts/1.ttf } ] }
sources: { sourceB: { url: "tiles/{z}/{y}/{x}.mvt" } }
textures:
tex3: { url: "in_imports.png" }
tex4: { url: "../not_in_imports.png" }
tex5: { url: "/at_root.png" }
styles:
styleB:
texture: "in_imports.png"
shaders:
uniforms:
u_tex1: "in_imports.png"
u_tex2: tex2
)END");
platform->putMockUrlContents("/root/globals.yaml", R"END(
fonts: { aFont: { url: global.fontUrl } }
sources: { aSource: { url: global.sourceUrl } }
textures: { aTexture: { url: global.textureUrl } }
styles: { aStyle: { texture: global.textureUrl, shaders: { uniforms: { aUniform: global.textureUrl } } } }
)END");
return platform;
}
TEST_CASE("Imported scenes are merged with the parent scene", "[import][core]") {
std::shared_ptr<Platform> platform = getPlatformWithImportFiles();
Importer importer;
auto root = importer.applySceneImports(platform, Url("/root/a.yaml"));
CHECK(root["value"].Scalar() == "a");
CHECK(root["has_a"].Scalar() == "true");
CHECK(root["has_b"].Scalar() == "true");
}
TEST_CASE("Nested imports are merged recursively", "[import][core]") {
std::shared_ptr<Platform> platform = getPlatformWithImportFiles();
Importer importer;
auto root = importer.applySceneImports(platform, Url("/root/c.yaml"));
CHECK(root["value"].Scalar() == "c");
CHECK(root["has_a"].Scalar() == "true");
CHECK(root["has_b"].Scalar() == "true");
CHECK(root["has_c"].Scalar() == "true");
}
TEST_CASE("Imports that would start a cycle are ignored", "[import][core]") {
std::shared_ptr<Platform> platform = getPlatformWithImportFiles();
Importer importer;
// If import cycles aren't checked for and stopped, this call won't return.
auto root = importer.applySceneImports(platform, Url("/root/cycle_simple.yaml"));
// Check that the scene values were applied.
CHECK(root["value"].Scalar() == "cyclic");
}
TEST_CASE("Tricky import cycles are ignored", "[import][core]") {
std::shared_ptr<Platform> platform = getPlatformWithImportFiles();
Importer importer;
// The nested import should resolve to the same path as the original file,
// and so the importer should break the cycle.
auto root = importer.applySceneImports(platform, Url("/root/cycle_tricky.yaml"));
// Check that the imported scene values were merged.
CHECK(root["has_cycle_tricky"].Scalar() == "true");
CHECK(root["has_imports_cycle_tricky"].Scalar() == "true");
}
TEST_CASE("Scene URLs are resolved against their parent during import", "[import][core]") {
std::shared_ptr<Platform> platform = getPlatformWithImportFiles();
Importer importer;
auto root = importer.applySceneImports(platform, Url("/root/urls.yaml"));
// Check that global texture URLs are resolved correctly.
auto textures = root["textures"];
CHECK(textures["tex1"]["url"].Scalar() == "/root/path/to/texture.png");
CHECK(textures["tex2"]["url"].Scalar() == "/up_a_directory.png");
CHECK(textures["tex3"]["url"].Scalar() == "/root/imports/in_imports.png");
CHECK(textures["tex4"]["url"].Scalar() == "/root/not_in_imports.png");
CHECK(textures["tex5"]["url"].Scalar() == "/at_root.png");
// Check that "inline" texture URLs are resolved correctly.
auto styleA = root["styles"]["styleA"];
CHECK(styleA["texture"].Scalar() == "/root/path/to/texture.png");
auto uniformsA = styleA["shaders"]["uniforms"];
CHECK(uniformsA["u_tex1"].Scalar() == "/at_root.png");
CHECK(uniformsA["u_tex2"][0].Scalar() == "/root/path/to/texture.png");
CHECK(uniformsA["u_tex2"][1].Scalar() == "tex2");
CHECK(uniformsA["u_bool"].Scalar() == "true");
CHECK(uniformsA["u_float"].Scalar() == "0.25");
CHECK(uniformsA["u_tex3"].Scalar() == "tex3");
auto styleB = root["styles"]["styleB"];
CHECK(styleB["texture"].Scalar() == "/root/imports/in_imports.png");
auto uniformsB = styleB["shaders"]["uniforms"];
CHECK(uniformsB["u_tex1"].Scalar() == "/root/imports/in_imports.png");
// Don't use global textures from importing scene
CHECK(uniformsB["u_tex2"].Scalar() == "/root/imports/tex2");
// Check that data source URLs are resolved correctly.
CHECK(root["sources"]["sourceA"]["url"].Scalar() == "https://host/tiles/{z}/{y}/{x}.mvt");
CHECK(root["sources"]["sourceB"]["url"].Scalar() == "/root/imports/tiles/{z}/{y}/{x}.mvt");
// Check that font URLs are resolved correctly.
CHECK(root["fonts"]["fontA"]["url"].Scalar() == "https://host/font.woff");
CHECK(root["fonts"]["fontB"][0]["url"].Scalar() == "/root/imports/fonts/0.ttf");
CHECK(root["fonts"]["fontB"][1]["url"].Scalar() == "/root/imports/fonts/1.ttf");
// We don't explicitly check that import URLs are resolved correctly because if they were not,
// the scenes wouldn't be loaded and merged; i.e. we already test it implicitly.
}
TEST_CASE("References to globals are not treated like URLs during importing", "[import][core]") {
std::shared_ptr<Platform> platform = getPlatformWithImportFiles();
Importer importer;
auto root = importer.applySceneImports(platform, Url("/root/globals.yaml"));
// Check that font global references are preserved.
CHECK(root["fonts"]["aFont"]["url"].Scalar() == "global.fontUrl");
// Check that data source global references are preserved.
CHECK(root["sources"]["aSource"]["url"].Scalar() == "global.sourceUrl");
// Check that texture global references are preserved.
CHECK(root["textures"]["aTexture"]["url"].Scalar() == "global.textureUrl");
CHECK(root["styles"]["aStyle"]["texture"].Scalar() == "global.textureUrl");
CHECK(root["styles"]["aStyle"]["shaders"]["uniforms"]["aUniform"].Scalar() == "global.textureUrl");
}
TEST_CASE("Map overwrites sequence", "[import][core]") {
std::shared_ptr<MockPlatform> platform = getPlatformWithImportFiles();
platform->putMockUrlContents("/base.yaml", R"END(
import: [roads.yaml, roads-labels.yaml]
)END");
platform->putMockUrlContents("/roads.yaml", R"END(
filter:
- kind: highway
- $zoom: { min: 8 }
)END");
platform->putMockUrlContents("/roads-labels.yaml", R"END(
filter: { kind: highway }
)END");
Importer importer;
auto root = importer.applySceneImports(platform, Url("/base.yaml"));
CHECK(root["filter"].IsMap());
CHECK(root["filter"].size() == 1);
CHECK(root["filter"]["kind"].Scalar() == "highway");
}
TEST_CASE("Sequence overwrites map", "[import][core]") {
std::shared_ptr<MockPlatform> platform = std::make_shared<MockPlatform>();
platform->putMockUrlContents("/base.yaml", R"END(
import: [map.yaml, sequence.yaml]
)END");
platform->putMockUrlContents("/map.yaml", R"END(
a: { b: c }
)END");
platform->putMockUrlContents("/sequence.yaml", R"END(
a: [ b, c]
)END");
Importer importer;
auto root = importer.applySceneImports(platform, Url("/base.yaml"));
CHECK(root["a"].IsSequence());
CHECK(root["a"].size() == 2);
}
TEST_CASE("Scalar and null overwrite correctly", "[import][core]") {
std::shared_ptr<MockPlatform> platform = std::make_shared<MockPlatform>();
platform->putMockUrlContents("/base.yaml", R"END(
import: [scalar.yaml, null.yaml]
scalar_at_end: scalar
null_at_end: null
)END");
platform->putMockUrlContents("/scalar.yaml", R"END(
null_at_end: scalar
)END");
platform->putMockUrlContents("/null.yaml", R"END(
scalar_at_end: null
)END");
Importer importer;
auto root = importer.applySceneImports(platform, Url("/base.yaml"));
CHECK(root["scalar_at_end"].Scalar() == "scalar");
CHECK(root["null_at_end"].IsNull());
}
TEST_CASE("Scene load from source string", "[import][core]") {
std::shared_ptr<Platform> platform = std::make_shared<MockPlatform>();
std::unordered_map<Url, std::string> testScenes;
platform->putMockUrlContents("/resource_root/scalar.yaml", R"END(
null_at_end: scalar
)END");
platform->putMockUrlContents("/resource_root/null.yaml", R"END(
scalar_at_end: null
)END");
std::string base_yaml = R"END(
import: [scalar.yaml, null.yaml]
scalar_at_end: scalar
null_at_end: null
)END";
Importer importer;
auto scene = std::make_shared<Scene>(platform, base_yaml, "/resource_root/");
auto root = importer.applySceneImports(platform, scene);
for (auto& s : importer.scenes()) {
logMsg(":> %s\n", s.first.string().c_str());
}
CHECK(root["scalar_at_end"].Scalar() == "scalar");
CHECK(root["null_at_end"].IsNull());
}
<commit_msg>Fix compilation errors in sceneImportTests<commit_after>#include "catch.hpp"
#include "mockPlatform.h"
#include "scene/importer.h"
#include "yaml-cpp/yaml.h"
#include <iostream>
#include <vector>
using namespace Tangram;
using namespace YAML;
std::shared_ptr<MockPlatform> getPlatformWithImportFiles() {
auto platform = std::make_shared<MockPlatform>();
platform->putMockUrlContents("/root/a.yaml", R"END(
import: b.yaml
value: a
has_a: true
)END");
platform->putMockUrlContents("/root/b.yaml", R"END(
value: b
has_b: true
)END");
platform->putMockUrlContents("/root/c.yaml", R"END(
import: [a.yaml, b.yaml]
value: c
has_c: true
)END");
platform->putMockUrlContents("/root/cycle_simple.yaml", R"END(
import: cycle_simple.yaml
value: cyclic
)END");
platform->putMockUrlContents("/root/cycle_tricky.yaml", R"END(
import: imports/cycle_tricky.yaml
has_cycle_tricky: true
)END");
platform->putMockUrlContents("/root/imports/cycle_tricky.yaml", R"END(
import: ../cycle_tricky.yaml
has_imports_cycle_tricky: true
)END");
platform->putMockUrlContents("/root/urls.yaml", R"END(
import: imports/urls.yaml
fonts: { fontA: { url: https://host/font.woff } }
sources: { sourceA: { url: 'https://host/tiles/{z}/{y}/{x}.mvt' } }
textures:
tex1: { url: "path/to/texture.png" }
tex2: { url: "../up_a_directory.png" }
styles:
styleA:
texture: "path/to/texture.png"
shaders:
uniforms:
u_tex1: "/at_root.png"
u_tex2: ["path/to/texture.png", tex2]
u_tex3: tex3
u_bool: true
u_float: 0.25
)END");
platform->putMockUrlContents("/root/imports/urls.yaml", R"END(
fonts: { fontB: [ { url: fonts/0.ttf }, { url: fonts/1.ttf } ] }
sources: { sourceB: { url: "tiles/{z}/{y}/{x}.mvt" } }
textures:
tex3: { url: "in_imports.png" }
tex4: { url: "../not_in_imports.png" }
tex5: { url: "/at_root.png" }
styles:
styleB:
texture: "in_imports.png"
shaders:
uniforms:
u_tex1: "in_imports.png"
u_tex2: tex2
)END");
platform->putMockUrlContents("/root/globals.yaml", R"END(
fonts: { aFont: { url: global.fontUrl } }
sources: { aSource: { url: global.sourceUrl } }
textures: { aTexture: { url: global.textureUrl } }
styles: { aStyle: { texture: global.textureUrl, shaders: { uniforms: { aUniform: global.textureUrl } } } }
)END");
return platform;
}
TEST_CASE("Imported scenes are merged with the parent scene", "[import][core]") {
std::shared_ptr<Platform> platform = getPlatformWithImportFiles();
Importer importer(std::make_shared<Scene>(platform, Url("/root/a.yaml")));
auto root = importer.applySceneImports(platform);
CHECK(root["value"].Scalar() == "a");
CHECK(root["has_a"].Scalar() == "true");
CHECK(root["has_b"].Scalar() == "true");
}
TEST_CASE("Nested imports are merged recursively", "[import][core]") {
std::shared_ptr<Platform> platform = getPlatformWithImportFiles();
Importer importer(std::make_shared<Scene>(platform, Url("/root/c.yaml")));
auto root = importer.applySceneImports(platform);
CHECK(root["value"].Scalar() == "c");
CHECK(root["has_a"].Scalar() == "true");
CHECK(root["has_b"].Scalar() == "true");
CHECK(root["has_c"].Scalar() == "true");
}
TEST_CASE("Imports that would start a cycle are ignored", "[import][core]") {
std::shared_ptr<Platform> platform = getPlatformWithImportFiles();
Importer importer(std::make_shared<Scene>(platform, Url("/root/cycle_simple.yaml")));
// If import cycles aren't checked for and stopped, this call won't return.
auto root = importer.applySceneImports(platform);
// Check that the scene values were applied.
CHECK(root["value"].Scalar() == "cyclic");
}
TEST_CASE("Tricky import cycles are ignored", "[import][core]") {
std::shared_ptr<Platform> platform = getPlatformWithImportFiles();
Importer importer(std::make_shared<Scene>(platform, Url("/root/cycle_tricky.yaml")));
// The nested import should resolve to the same path as the original file,
// and so the importer should break the cycle.
auto root = importer.applySceneImports(platform);
// Check that the imported scene values were merged.
CHECK(root["has_cycle_tricky"].Scalar() == "true");
CHECK(root["has_imports_cycle_tricky"].Scalar() == "true");
}
TEST_CASE("Scene URLs are resolved against their parent during import", "[import][core]") {
std::shared_ptr<Platform> platform = getPlatformWithImportFiles();
Importer importer(std::make_shared<Scene>(platform, Url("/root/urls.yaml")));
auto root = importer.applySceneImports(platform);
// Check that global texture URLs are resolved correctly.
auto textures = root["textures"];
CHECK(textures["tex1"]["url"].Scalar() == "/root/path/to/texture.png");
CHECK(textures["tex2"]["url"].Scalar() == "/up_a_directory.png");
CHECK(textures["tex3"]["url"].Scalar() == "/root/imports/in_imports.png");
CHECK(textures["tex4"]["url"].Scalar() == "/root/not_in_imports.png");
CHECK(textures["tex5"]["url"].Scalar() == "/at_root.png");
// Check that "inline" texture URLs are resolved correctly.
auto styleA = root["styles"]["styleA"];
CHECK(styleA["texture"].Scalar() == "/root/path/to/texture.png");
auto uniformsA = styleA["shaders"]["uniforms"];
CHECK(uniformsA["u_tex1"].Scalar() == "/at_root.png");
CHECK(uniformsA["u_tex2"][0].Scalar() == "/root/path/to/texture.png");
CHECK(uniformsA["u_tex2"][1].Scalar() == "tex2");
CHECK(uniformsA["u_bool"].Scalar() == "true");
CHECK(uniformsA["u_float"].Scalar() == "0.25");
CHECK(uniformsA["u_tex3"].Scalar() == "tex3");
auto styleB = root["styles"]["styleB"];
CHECK(styleB["texture"].Scalar() == "/root/imports/in_imports.png");
auto uniformsB = styleB["shaders"]["uniforms"];
CHECK(uniformsB["u_tex1"].Scalar() == "/root/imports/in_imports.png");
// Don't use global textures from importing scene
CHECK(uniformsB["u_tex2"].Scalar() == "/root/imports/tex2");
// Check that data source URLs are resolved correctly.
CHECK(root["sources"]["sourceA"]["url"].Scalar() == "https://host/tiles/{z}/{y}/{x}.mvt");
CHECK(root["sources"]["sourceB"]["url"].Scalar() == "/root/imports/tiles/{z}/{y}/{x}.mvt");
// Check that font URLs are resolved correctly.
CHECK(root["fonts"]["fontA"]["url"].Scalar() == "https://host/font.woff");
CHECK(root["fonts"]["fontB"][0]["url"].Scalar() == "/root/imports/fonts/0.ttf");
CHECK(root["fonts"]["fontB"][1]["url"].Scalar() == "/root/imports/fonts/1.ttf");
// We don't explicitly check that import URLs are resolved correctly because if they were not,
// the scenes wouldn't be loaded and merged; i.e. we already test it implicitly.
}
TEST_CASE("References to globals are not treated like URLs during importing", "[import][core]") {
std::shared_ptr<Platform> platform = getPlatformWithImportFiles();
Importer importer(std::make_shared<Scene>(platform, Url("/root/globals.yaml")));
auto root = importer.applySceneImports(platform);
// Check that font global references are preserved.
CHECK(root["fonts"]["aFont"]["url"].Scalar() == "global.fontUrl");
// Check that data source global references are preserved.
CHECK(root["sources"]["aSource"]["url"].Scalar() == "global.sourceUrl");
// Check that texture global references are preserved.
CHECK(root["textures"]["aTexture"]["url"].Scalar() == "global.textureUrl");
CHECK(root["styles"]["aStyle"]["texture"].Scalar() == "global.textureUrl");
CHECK(root["styles"]["aStyle"]["shaders"]["uniforms"]["aUniform"].Scalar() == "global.textureUrl");
}
TEST_CASE("Map overwrites sequence", "[import][core]") {
std::shared_ptr<MockPlatform> platform = getPlatformWithImportFiles();
platform->putMockUrlContents("/base.yaml", R"END(
import: [roads.yaml, roads-labels.yaml]
)END");
platform->putMockUrlContents("/roads.yaml", R"END(
filter:
- kind: highway
- $zoom: { min: 8 }
)END");
platform->putMockUrlContents("/roads-labels.yaml", R"END(
filter: { kind: highway }
)END");
Importer importer(std::make_shared<Scene>(platform, Url("/base.yaml")));
auto root = importer.applySceneImports(platform);
CHECK(root["filter"].IsMap());
CHECK(root["filter"].size() == 1);
CHECK(root["filter"]["kind"].Scalar() == "highway");
}
TEST_CASE("Sequence overwrites map", "[import][core]") {
std::shared_ptr<MockPlatform> platform = std::make_shared<MockPlatform>();
platform->putMockUrlContents("/base.yaml", R"END(
import: [map.yaml, sequence.yaml]
)END");
platform->putMockUrlContents("/map.yaml", R"END(
a: { b: c }
)END");
platform->putMockUrlContents("/sequence.yaml", R"END(
a: [ b, c]
)END");
Importer importer(std::make_shared<Scene>(platform, Url("/base.yaml")));
auto root = importer.applySceneImports(platform);
CHECK(root["a"].IsSequence());
CHECK(root["a"].size() == 2);
}
TEST_CASE("Scalar and null overwrite correctly", "[import][core]") {
std::shared_ptr<MockPlatform> platform = std::make_shared<MockPlatform>();
platform->putMockUrlContents("/base.yaml", R"END(
import: [scalar.yaml, null.yaml]
scalar_at_end: scalar
null_at_end: null
)END");
platform->putMockUrlContents("/scalar.yaml", R"END(
null_at_end: scalar
)END");
platform->putMockUrlContents("/null.yaml", R"END(
scalar_at_end: null
)END");
Importer importer(std::make_shared<Scene>(platform, Url("/base.yaml")));
auto root = importer.applySceneImports(platform);
CHECK(root["scalar_at_end"].Scalar() == "scalar");
CHECK(root["null_at_end"].IsNull());
}
TEST_CASE("Scene load from source string", "[import][core]") {
std::shared_ptr<MockPlatform> platform = std::make_shared<MockPlatform>();
std::unordered_map<Url, std::string> testScenes;
platform->putMockUrlContents("/resource_root/scalar.yaml", R"END(
null_at_end: scalar
)END");
platform->putMockUrlContents("/resource_root/null.yaml", R"END(
scalar_at_end: null
)END");
std::string base_yaml = R"END(
import: [scalar.yaml, null.yaml]
scalar_at_end: scalar
null_at_end: null
)END";
auto scene = std::make_shared<Scene>(platform, base_yaml, "/resource_root/");
Importer importer(scene);
auto root = importer.applySceneImports(platform);
CHECK(root["scalar_at_end"].Scalar() == "scalar");
CHECK(root["null_at_end"].IsNull());
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/login/webui_login_view.h"
#include <vector>
#include "base/logging.h"
#include "chrome/browser/chromeos/login/login_utils.h"
#include "chrome/browser/chromeos/login/proxy_settings_dialog.h"
#include "chrome/browser/chromeos/status/clock_menu_button.h"
#include "chrome/browser/chromeos/status/input_method_menu_button.h"
#include "chrome/browser/chromeos/status/network_menu_button.h"
#include "chrome/browser/chromeos/status/status_area_view.h"
#include "chrome/browser/chromeos/wm_ipc.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/renderer_host/render_widget_host_view_views.h"
#include "chrome/browser/ui/touch/frame/keyboard_container_view.h"
#include "chrome/browser/ui/views/dom_view.h"
#include "chrome/browser/ui/views/tab_contents/tab_contents_view_touch.h"
#include "content/browser/renderer_host/render_view_host.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "content/common/notification_service.h"
#include "googleurl/src/gurl.h"
#include "ui/base/x/x11_util.h"
#include "ui/gfx/transform.h"
#include "views/controls/textfield/textfield.h"
#include "views/widget/widget.h"
// TODO(rharrison): Modify this class to support both touch and non-touch
namespace {
const int kKeyboardHeight = 300;
const int kKeyboardSlideDuration = 500; // In milliseconds
PropertyAccessor<bool>* GetFocusedStateAccessor() {
static PropertyAccessor<bool> state;
return &state;
}
bool TabContentsHasFocus(const TabContents* contents) {
views::View* view = static_cast<TabContentsViewTouch*>(contents->view());
return view->Contains(view->GetFocusManager()->GetFocusedView());
}
} // namespace
namespace chromeos {
// static
const char WebUILoginView::kViewClassName[] =
"browser/chromeos/login/WebUILoginView";
// WebUILoginView public: ------------------------------------------------------
WebUILoginView::WebUILoginView()
: profile_(NULL),
status_area_(NULL),
webui_login_(NULL),
keyboard_showing_(false),
focus_listener_added_(false),
keyboard_(NULL) {
}
void WebUILoginView::Init(const GURL& login_url) {
CHECK(!login_url.is_empty());
profile_ = ProfileManager::GetDefaultProfile();
webui_login_ = new DOMView();
AddChildView(webui_login_);
webui_login_->Init(profile_, NULL);
webui_login_->LoadURL(login_url);
webui_login_->SetVisible(true);
InitStatusArea();
registrar_.Add(this,
NotificationType::FOCUS_CHANGED_IN_PAGE,
NotificationService::AllSources());
registrar_.Add(this,
NotificationType::TAB_CONTENTS_DESTROYED,
NotificationService::AllSources());
}
// static
views::Widget* WebUILoginView::CreateWindowContainingView(
const gfx::Rect& bounds,
const GURL& login_url,
WebUILoginView** view) {
views::Widget* window = new views::Widget;
views::Widget::InitParams params(views::Widget::InitParams::TYPE_WINDOW);
params.bounds = bounds;
window->Init(params);
*view = new WebUILoginView();
(*view)->Init(login_url);
window->SetContentsView(*view);
(*view)->UpdateWindowType();
return window;
}
std::string WebUILoginView::GetClassName() const {
return kViewClassName;
}
gfx::NativeWindow WebUILoginView::GetNativeWindow() const {
return GetWidget()->GetNativeWindow();
}
void WebUILoginView::FocusWillChange(views::View* focused_before,
views::View* focused_now) {
VirtualKeyboardType before = DecideKeyboardStateForView(focused_before);
VirtualKeyboardType now = DecideKeyboardStateForView(focused_now);
if (before != now) {
// TODO(varunjain): support other types of keyboard.
UpdateKeyboardAndLayout(now == GENERIC);
}
}
// WebUILoginView protected: ---------------------------------------------------
void WebUILoginView::Layout() {
const int kCornerPadding = 5;
gfx::Size status_area_size = status_area_->GetPreferredSize();
status_area_->SetBounds(
width() - status_area_size.width() - kCornerPadding,
kCornerPadding,
status_area_size.width(),
status_area_size.height());
if (webui_login_)
webui_login_->SetBoundsRect(bounds());
// TODO(rharrison): Hide touch specific code behind TOUCH_UI defines
if (!keyboard_)
return;
keyboard_->SetVisible(keyboard_showing_);
gfx::Rect keyboard_bounds = bounds();
keyboard_bounds.set_y(keyboard_bounds.height() - kKeyboardHeight);
keyboard_bounds.set_height(kKeyboardHeight);
keyboard_->SetBoundsRect(keyboard_bounds);
}
void WebUILoginView::ChildPreferredSizeChanged(View* child) {
Layout();
SchedulePaint();
}
Profile* WebUILoginView::GetProfile() const {
return NULL;
}
void WebUILoginView::ExecuteBrowserCommand(int id) const {
}
bool WebUILoginView::ShouldOpenButtonOptions(
const views::View* button_view) const {
if (button_view == status_area_->network_view())
return true;
if (button_view == status_area_->clock_view() ||
button_view == status_area_->input_method_view())
return false;
return true;
}
void WebUILoginView::OpenButtonOptions(const views::View* button_view) {
if (button_view == status_area_->network_view()) {
if (proxy_settings_dialog_.get() == NULL) {
proxy_settings_dialog_.reset(new ProxySettingsDialog(
this, GetNativeWindow()));
}
proxy_settings_dialog_->Show();
}
}
StatusAreaHost::ScreenMode WebUILoginView::GetScreenMode() const {
return kLoginMode;
}
StatusAreaHost::TextStyle WebUILoginView::GetTextStyle() const {
return kWhitePlain;
}
void WebUILoginView::OnDialogClosed() {
}
void WebUILoginView::OnLocaleChanged() {
// Proxy settings dialog contains localized strings.
proxy_settings_dialog_.reset();
SchedulePaint();
}
// WebUILoginView private: -----------------------------------------------------
void WebUILoginView::InitStatusArea() {
DCHECK(status_area_ == NULL);
status_area_ = new StatusAreaView(this);
status_area_->Init();
AddChildView(status_area_);
}
void WebUILoginView::UpdateWindowType() {
std::vector<int> params;
WmIpc::instance()->SetWindowType(
GTK_WIDGET(GetNativeWindow()),
WM_IPC_WINDOW_LOGIN_WEBUI,
¶ms);
}
void WebUILoginView::InitVirtualKeyboard() {
if (keyboard_)
return;
keyboard_ = new KeyboardContainerView(profile_, NULL);
keyboard_->SetVisible(false);
AddChildView(keyboard_);
}
void WebUILoginView::UpdateKeyboardAndLayout(bool should_show_keyboard) {
if (should_show_keyboard)
InitVirtualKeyboard();
if (should_show_keyboard == keyboard_showing_)
return;
DCHECK(keyboard_);
keyboard_showing_ = should_show_keyboard;
Layout();
}
WebUILoginView::VirtualKeyboardType
WebUILoginView::DecideKeyboardStateForView(views::View* view) {
if (!view)
return NONE;
std::string cname = view->GetClassName();
if (cname == views::Textfield::kViewClassName) {
return GENERIC;
} else if (cname == RenderWidgetHostViewViews::kViewClassName) {
TabContents* contents = webui_login_->tab_contents();
bool* editable = contents ? GetFocusedStateAccessor()->GetProperty(
contents->property_bag()) : NULL;
if (editable && *editable)
return GENERIC;
}
return NONE;
}
void WebUILoginView::Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
if (type == NotificationType::FOCUS_CHANGED_IN_PAGE) {
// Only modify the keyboard state if the currently active tab sent the
// notification.
const TabContents* current_tab = webui_login_->tab_contents();
TabContents* source_tab = Source<TabContents>(source).ptr();
const bool editable = *Details<const bool>(details).ptr();
if (current_tab == source_tab && TabContentsHasFocus(source_tab))
UpdateKeyboardAndLayout(editable);
// Save the state of the focused field so that the keyboard visibility
// can be determined after tab switching.
GetFocusedStateAccessor()->SetProperty(
source_tab->property_bag(), editable);
} else if (type == NotificationType::TAB_CONTENTS_DESTROYED) {
GetFocusedStateAccessor()->DeleteProperty(
Source<TabContents>(source).ptr()->property_bag());
}
}
} // namespace chromeos
<commit_msg>Changed kKeyboardHeight in WebUILoginView to reflect change in TouchBrowserFrameView<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/login/webui_login_view.h"
#include <vector>
#include "base/logging.h"
#include "chrome/browser/chromeos/login/login_utils.h"
#include "chrome/browser/chromeos/login/proxy_settings_dialog.h"
#include "chrome/browser/chromeos/status/clock_menu_button.h"
#include "chrome/browser/chromeos/status/input_method_menu_button.h"
#include "chrome/browser/chromeos/status/network_menu_button.h"
#include "chrome/browser/chromeos/status/status_area_view.h"
#include "chrome/browser/chromeos/wm_ipc.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/renderer_host/render_widget_host_view_views.h"
#include "chrome/browser/ui/touch/frame/keyboard_container_view.h"
#include "chrome/browser/ui/views/dom_view.h"
#include "chrome/browser/ui/views/tab_contents/tab_contents_view_touch.h"
#include "content/browser/renderer_host/render_view_host.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "content/common/notification_service.h"
#include "googleurl/src/gurl.h"
#include "ui/base/x/x11_util.h"
#include "ui/gfx/transform.h"
#include "views/controls/textfield/textfield.h"
#include "views/widget/widget.h"
// TODO(rharrison): Modify this class to support both touch and non-touch
namespace {
const int kKeyboardHeight = 360;
const int kKeyboardSlideDuration = 500; // In milliseconds
PropertyAccessor<bool>* GetFocusedStateAccessor() {
static PropertyAccessor<bool> state;
return &state;
}
bool TabContentsHasFocus(const TabContents* contents) {
views::View* view = static_cast<TabContentsViewTouch*>(contents->view());
return view->Contains(view->GetFocusManager()->GetFocusedView());
}
} // namespace
namespace chromeos {
// static
const char WebUILoginView::kViewClassName[] =
"browser/chromeos/login/WebUILoginView";
// WebUILoginView public: ------------------------------------------------------
WebUILoginView::WebUILoginView()
: profile_(NULL),
status_area_(NULL),
webui_login_(NULL),
keyboard_showing_(false),
focus_listener_added_(false),
keyboard_(NULL) {
}
void WebUILoginView::Init(const GURL& login_url) {
CHECK(!login_url.is_empty());
profile_ = ProfileManager::GetDefaultProfile();
webui_login_ = new DOMView();
AddChildView(webui_login_);
webui_login_->Init(profile_, NULL);
webui_login_->LoadURL(login_url);
webui_login_->SetVisible(true);
InitStatusArea();
registrar_.Add(this,
NotificationType::FOCUS_CHANGED_IN_PAGE,
NotificationService::AllSources());
registrar_.Add(this,
NotificationType::TAB_CONTENTS_DESTROYED,
NotificationService::AllSources());
}
// static
views::Widget* WebUILoginView::CreateWindowContainingView(
const gfx::Rect& bounds,
const GURL& login_url,
WebUILoginView** view) {
views::Widget* window = new views::Widget;
views::Widget::InitParams params(views::Widget::InitParams::TYPE_WINDOW);
params.bounds = bounds;
window->Init(params);
*view = new WebUILoginView();
(*view)->Init(login_url);
window->SetContentsView(*view);
(*view)->UpdateWindowType();
return window;
}
std::string WebUILoginView::GetClassName() const {
return kViewClassName;
}
gfx::NativeWindow WebUILoginView::GetNativeWindow() const {
return GetWidget()->GetNativeWindow();
}
void WebUILoginView::FocusWillChange(views::View* focused_before,
views::View* focused_now) {
VirtualKeyboardType before = DecideKeyboardStateForView(focused_before);
VirtualKeyboardType now = DecideKeyboardStateForView(focused_now);
if (before != now) {
// TODO(varunjain): support other types of keyboard.
UpdateKeyboardAndLayout(now == GENERIC);
}
}
// WebUILoginView protected: ---------------------------------------------------
void WebUILoginView::Layout() {
const int kCornerPadding = 5;
gfx::Size status_area_size = status_area_->GetPreferredSize();
status_area_->SetBounds(
width() - status_area_size.width() - kCornerPadding,
kCornerPadding,
status_area_size.width(),
status_area_size.height());
if (webui_login_)
webui_login_->SetBoundsRect(bounds());
// TODO(rharrison): Hide touch specific code behind TOUCH_UI defines
if (!keyboard_)
return;
keyboard_->SetVisible(keyboard_showing_);
gfx::Rect keyboard_bounds = bounds();
keyboard_bounds.set_y(keyboard_bounds.height() - kKeyboardHeight);
keyboard_bounds.set_height(kKeyboardHeight);
keyboard_->SetBoundsRect(keyboard_bounds);
}
void WebUILoginView::ChildPreferredSizeChanged(View* child) {
Layout();
SchedulePaint();
}
Profile* WebUILoginView::GetProfile() const {
return NULL;
}
void WebUILoginView::ExecuteBrowserCommand(int id) const {
}
bool WebUILoginView::ShouldOpenButtonOptions(
const views::View* button_view) const {
if (button_view == status_area_->network_view())
return true;
if (button_view == status_area_->clock_view() ||
button_view == status_area_->input_method_view())
return false;
return true;
}
void WebUILoginView::OpenButtonOptions(const views::View* button_view) {
if (button_view == status_area_->network_view()) {
if (proxy_settings_dialog_.get() == NULL) {
proxy_settings_dialog_.reset(new ProxySettingsDialog(
this, GetNativeWindow()));
}
proxy_settings_dialog_->Show();
}
}
StatusAreaHost::ScreenMode WebUILoginView::GetScreenMode() const {
return kLoginMode;
}
StatusAreaHost::TextStyle WebUILoginView::GetTextStyle() const {
return kWhitePlain;
}
void WebUILoginView::OnDialogClosed() {
}
void WebUILoginView::OnLocaleChanged() {
// Proxy settings dialog contains localized strings.
proxy_settings_dialog_.reset();
SchedulePaint();
}
// WebUILoginView private: -----------------------------------------------------
void WebUILoginView::InitStatusArea() {
DCHECK(status_area_ == NULL);
status_area_ = new StatusAreaView(this);
status_area_->Init();
AddChildView(status_area_);
}
void WebUILoginView::UpdateWindowType() {
std::vector<int> params;
WmIpc::instance()->SetWindowType(
GTK_WIDGET(GetNativeWindow()),
WM_IPC_WINDOW_LOGIN_WEBUI,
¶ms);
}
void WebUILoginView::InitVirtualKeyboard() {
if (keyboard_)
return;
keyboard_ = new KeyboardContainerView(profile_, NULL);
keyboard_->SetVisible(false);
AddChildView(keyboard_);
}
void WebUILoginView::UpdateKeyboardAndLayout(bool should_show_keyboard) {
if (should_show_keyboard)
InitVirtualKeyboard();
if (should_show_keyboard == keyboard_showing_)
return;
DCHECK(keyboard_);
keyboard_showing_ = should_show_keyboard;
Layout();
}
WebUILoginView::VirtualKeyboardType
WebUILoginView::DecideKeyboardStateForView(views::View* view) {
if (!view)
return NONE;
std::string cname = view->GetClassName();
if (cname == views::Textfield::kViewClassName) {
return GENERIC;
} else if (cname == RenderWidgetHostViewViews::kViewClassName) {
TabContents* contents = webui_login_->tab_contents();
bool* editable = contents ? GetFocusedStateAccessor()->GetProperty(
contents->property_bag()) : NULL;
if (editable && *editable)
return GENERIC;
}
return NONE;
}
void WebUILoginView::Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
if (type == NotificationType::FOCUS_CHANGED_IN_PAGE) {
// Only modify the keyboard state if the currently active tab sent the
// notification.
const TabContents* current_tab = webui_login_->tab_contents();
TabContents* source_tab = Source<TabContents>(source).ptr();
const bool editable = *Details<const bool>(details).ptr();
if (current_tab == source_tab && TabContentsHasFocus(source_tab))
UpdateKeyboardAndLayout(editable);
// Save the state of the focused field so that the keyboard visibility
// can be determined after tab switching.
GetFocusedStateAccessor()->SetProperty(
source_tab->property_bag(), editable);
} else if (type == NotificationType::TAB_CONTENTS_DESTROYED) {
GetFocusedStateAccessor()->DeleteProperty(
Source<TabContents>(source).ptr()->property_bag());
}
}
} // namespace chromeos
<|endoftext|>
|
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/extension_install_ui.h"
#include <map>
#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "base/file_util.h"
#include "base/rand_util.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/extensions/theme_installed_infobar_delegate.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#if defined(TOOLKIT_VIEWS) // TODO(port)
#include "chrome/browser/views/extensions/extension_installed_bubble.h"
#elif defined(TOOLKIT_GTK)
#include "chrome/browser/gtk/extension_installed_bubble_gtk.h"
#endif
#include "chrome/common/extensions/extension.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/platform_util.h"
#include "chrome/common/url_constants.h"
#include "grit/browser_resources.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#if defined(TOOLKIT_GTK)
#include "chrome/browser/extensions/gtk_theme_installed_infobar_delegate.h"
#include "chrome/browser/gtk/gtk_theme_provider.h"
#endif
#if defined(OS_MACOSX)
#include "chrome/browser/cocoa/extension_installed_bubble_bridge.h"
#endif
// static
const int ExtensionInstallUI::kTitleIds[NUM_PROMPT_TYPES] = {
IDS_EXTENSION_INSTALL_PROMPT_TITLE,
IDS_EXTENSION_UNINSTALL_PROMPT_TITLE
};
// static
const int ExtensionInstallUI::kHeadingIds[NUM_PROMPT_TYPES] = {
IDS_EXTENSION_INSTALL_PROMPT_HEADING,
IDS_EXTENSION_UNINSTALL_PROMPT_HEADING
};
// static
const int ExtensionInstallUI::kButtonIds[NUM_PROMPT_TYPES] = {
IDS_EXTENSION_PROMPT_INSTALL_BUTTON,
IDS_EXTENSION_PROMPT_UNINSTALL_BUTTON
};
namespace {
// We also show the severe warning if the extension has access to any file://
// URLs. They aren't *quite* as dangerous as full access to the system via
// NPAPI, but pretty dang close. Content scripts are currently the only way
// that extension can get access to file:// URLs.
static bool ExtensionHasFileAccess(Extension* extension) {
for (UserScriptList::const_iterator script =
extension->content_scripts().begin();
script != extension->content_scripts().end();
++script) {
for (UserScript::PatternList::const_iterator pattern =
script->url_patterns().begin();
pattern != script->url_patterns().end();
++pattern) {
if (pattern->scheme() == chrome::kFileScheme)
return true;
}
}
return false;
}
static void GetV2Warnings(Extension* extension,
std::vector<string16>* warnings) {
if (!extension->plugins().empty() || ExtensionHasFileAccess(extension)) {
// TODO(aa): This one is a bit awkward. Should we have a separate
// presentation for this case?
warnings->push_back(
l10n_util::GetStringUTF16(IDS_EXTENSION_PROMPT2_WARNING_FULL_ACCESS));
return;
}
if (extension->HasAccessToAllHosts()) {
warnings->push_back(
l10n_util::GetStringUTF16(IDS_EXTENSION_PROMPT2_WARNING_ALL_HOSTS));
} else {
std::set<std::string> hosts = extension->GetEffectiveHostPermissions();
if (hosts.size() == 1) {
warnings->push_back(
l10n_util::GetStringFUTF16(IDS_EXTENSION_PROMPT2_WARNING_1_HOST,
UTF8ToUTF16(*hosts.begin())));
} else if (hosts.size() == 2) {
warnings->push_back(
l10n_util::GetStringFUTF16(IDS_EXTENSION_PROMPT2_WARNING_2_HOSTS,
UTF8ToUTF16(*hosts.begin()),
UTF8ToUTF16(*(++hosts.begin()))));
} else if (hosts.size() == 3) {
warnings->push_back(
l10n_util::GetStringFUTF16(IDS_EXTENSION_PROMPT2_WARNING_3_HOSTS,
UTF8ToUTF16(*hosts.begin()),
UTF8ToUTF16(*(++hosts.begin())),
UTF8ToUTF16(*(++++hosts.begin()))));
} else if (hosts.size() >= 4) {
warnings->push_back(
l10n_util::GetStringFUTF16(
IDS_EXTENSION_PROMPT2_WARNING_4_OR_MORE_HOSTS,
UTF8ToUTF16(*hosts.begin()),
UTF8ToUTF16(*(++hosts.begin())),
IntToString16(hosts.size() - 2)));
}
}
if (extension->HasEffectiveBrowsingHistoryPermission()) {
warnings->push_back(
l10n_util::GetStringUTF16(
IDS_EXTENSION_PROMPT2_WARNING_BROWSING_HISTORY));
}
// TODO(aa): Geolocation, camera/mic, what else?
}
} // namespace
ExtensionInstallUI::ExtensionInstallUI(Profile* profile)
: profile_(profile),
ui_loop_(MessageLoop::current()),
previous_use_system_theme_(false),
extension_(NULL),
delegate_(NULL),
prompt_type_(NUM_PROMPT_TYPES),
ALLOW_THIS_IN_INITIALIZER_LIST(tracker_(this)) {}
void ExtensionInstallUI::ConfirmInstall(Delegate* delegate,
Extension* extension) {
DCHECK(ui_loop_ == MessageLoop::current());
extension_ = extension;
delegate_ = delegate;
// We special-case themes to not show any confirm UI. Instead they are
// immediately installed, and then we show an infobar (see OnInstallSuccess)
// to allow the user to revert if they don't like it.
if (extension->IsTheme()) {
// Remember the current theme in case the user pressed undo.
Extension* previous_theme = profile_->GetTheme();
if (previous_theme)
previous_theme_id_ = previous_theme->id();
#if defined(TOOLKIT_GTK)
// On Linux, we also need to take the user's system settings into account
// to undo theme installation.
previous_use_system_theme_ =
GtkThemeProvider::GetFrom(profile_)->UseGtkTheme();
#else
DCHECK(!previous_use_system_theme_);
#endif
delegate->InstallUIProceed(false);
return;
}
ShowConfirmation(INSTALL_PROMPT);
}
void ExtensionInstallUI::ConfirmUninstall(Delegate* delegate,
Extension* extension) {
DCHECK(ui_loop_ == MessageLoop::current());
extension_ = extension;
delegate_ = delegate;
ShowConfirmation(UNINSTALL_PROMPT);
}
void ExtensionInstallUI::OnInstallSuccess(Extension* extension) {
if (extension->IsTheme()) {
ShowThemeInfoBar(previous_theme_id_, previous_use_system_theme_,
extension, profile_);
return;
}
// GetLastActiveWithProfile will fail on the build bots. This needs to be
// implemented differently if any test is created which depends on
// ExtensionInstalledBubble showing.
Browser* browser = BrowserList::GetLastActiveWithProfile(profile_);
#if defined(TOOLKIT_VIEWS)
if (!browser)
return;
ExtensionInstalledBubble::Show(extension, browser, icon_);
#elif defined(OS_MACOSX)
DCHECK(browser);
// Note that browser actions don't appear in incognito mode initially,
// so fall back to the generic case.
if ((extension->browser_action() && !browser->profile()->IsOffTheRecord()) ||
(extension->page_action() &&
!extension->page_action()->default_icon_path().empty())) {
ExtensionInstalledBubbleCocoa::ShowExtensionInstalledBubble(
browser->window()->GetNativeHandle(),
extension, browser, icon_);
} else {
// If the extension is of type GENERIC, meaning it doesn't have a UI
// surface to display for this window, launch infobar instead of popup
// bubble, because we have no guaranteed wrench menu button to point to.
ShowGenericExtensionInstalledInfoBar(extension);
}
#elif defined(TOOLKIT_GTK)
if (!browser)
return;
ExtensionInstalledBubbleGtk::Show(extension, browser, icon_);
#endif // TOOLKIT_VIEWS
}
void ExtensionInstallUI::OnInstallFailure(const std::string& error) {
DCHECK(ui_loop_ == MessageLoop::current());
Browser* browser = BrowserList::GetLastActiveWithProfile(profile_);
platform_util::SimpleErrorBox(
browser ? browser->window()->GetNativeHandle() : NULL,
l10n_util::GetStringUTF16(IDS_EXTENSION_INSTALL_FAILURE_TITLE),
UTF8ToUTF16(error));
}
void ExtensionInstallUI::OnOverinstallAttempted(Extension* extension) {
ShowThemeInfoBar(previous_theme_id_, previous_use_system_theme_,
extension, profile_);
}
void ExtensionInstallUI::OnImageLoaded(
SkBitmap* image, ExtensionResource resource, int index) {
if (image)
icon_ = *image;
else
icon_ = SkBitmap();
if (icon_.empty()) {
icon_ = *ResourceBundle::GetSharedInstance().GetBitmapNamed(
IDR_EXTENSION_DEFAULT_ICON);
}
switch (prompt_type_) {
case INSTALL_PROMPT: {
NotificationService* service = NotificationService::current();
service->Notify(NotificationType::EXTENSION_WILL_SHOW_CONFIRM_DIALOG,
Source<ExtensionInstallUI>(this),
NotificationService::NoDetails());
std::vector<string16> warnings;
GetV2Warnings(extension_, &warnings);
ShowExtensionInstallUIPrompt2Impl(
profile_, delegate_, extension_, &icon_, warnings);
break;
}
case UNINSTALL_PROMPT: {
string16 message =
l10n_util::GetStringUTF16(IDS_EXTENSION_UNINSTALL_CONFIRMATION);
ShowExtensionInstallUIPromptImpl(profile_, delegate_, extension_, &icon_,
message, UNINSTALL_PROMPT);
break;
}
default:
NOTREACHED() << "Unknown message";
break;
}
}
void ExtensionInstallUI::ShowThemeInfoBar(
const std::string& previous_theme_id, bool previous_use_system_theme,
Extension* new_theme, Profile* profile) {
if (!new_theme->IsTheme())
return;
Browser* browser = BrowserList::GetLastActiveWithProfile(profile);
if (!browser)
return;
TabContents* tab_contents = browser->GetSelectedTabContents();
if (!tab_contents)
return;
// First find any previous theme preview infobars.
InfoBarDelegate* old_delegate = NULL;
for (int i = 0; i < tab_contents->infobar_delegate_count(); ++i) {
InfoBarDelegate* delegate = tab_contents->GetInfoBarDelegateAt(i);
if (delegate->AsThemePreviewInfobarDelegate()) {
old_delegate = delegate;
break;
}
}
// Then either replace that old one or add a new one.
InfoBarDelegate* new_delegate =
GetNewThemeInstalledInfoBarDelegate(
tab_contents, new_theme,
previous_theme_id, previous_use_system_theme);
if (old_delegate)
tab_contents->ReplaceInfoBar(old_delegate, new_delegate);
else
tab_contents->AddInfoBar(new_delegate);
}
void ExtensionInstallUI::ShowConfirmation(PromptType prompt_type) {
// Load the image asynchronously. For the response, check OnImageLoaded.
prompt_type_ = prompt_type;
ExtensionResource image =
extension_->GetIconPath(Extension::EXTENSION_ICON_LARGE);
tracker_.LoadImage(extension_, image,
gfx::Size(Extension::EXTENSION_ICON_LARGE,
Extension::EXTENSION_ICON_LARGE),
ImageLoadingTracker::DONT_CACHE);
}
#if defined(OS_MACOSX)
void ExtensionInstallUI::ShowGenericExtensionInstalledInfoBar(
Extension* new_extension) {
Browser* browser = BrowserList::GetLastActiveWithProfile(profile_);
if (!browser)
return;
TabContents* tab_contents = browser->GetSelectedTabContents();
if (!tab_contents)
return;
std::wstring msg = l10n_util::GetStringF(IDS_EXTENSION_INSTALLED_HEADING,
UTF8ToWide(new_extension->name())) +
L" " + l10n_util::GetString(IDS_EXTENSION_INSTALLED_MANAGE_INFO_MAC);
InfoBarDelegate* delegate = new SimpleAlertInfoBarDelegate(
tab_contents, msg, new SkBitmap(icon_), true);
tab_contents->AddInfoBar(delegate);
}
#endif
InfoBarDelegate* ExtensionInstallUI::GetNewThemeInstalledInfoBarDelegate(
TabContents* tab_contents, Extension* new_theme,
const std::string& previous_theme_id, bool previous_use_system_theme) {
#if defined(TOOLKIT_GTK)
return new GtkThemeInstalledInfoBarDelegate(tab_contents, new_theme,
previous_theme_id, previous_use_system_theme);
#else
return new ThemeInstalledInfoBarDelegate(tab_contents, new_theme,
previous_theme_id);
#endif
}
<commit_msg>Auto-launch apps after installation.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/extension_install_ui.h"
#include <map>
#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "base/file_util.h"
#include "base/rand_util.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/extensions/theme_installed_infobar_delegate.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#if defined(TOOLKIT_VIEWS) // TODO(port)
#include "chrome/browser/views/extensions/extension_installed_bubble.h"
#elif defined(TOOLKIT_GTK)
#include "chrome/browser/gtk/extension_installed_bubble_gtk.h"
#endif
#include "chrome/common/extensions/extension.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/platform_util.h"
#include "chrome/common/url_constants.h"
#include "grit/browser_resources.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#if defined(TOOLKIT_GTK)
#include "chrome/browser/extensions/gtk_theme_installed_infobar_delegate.h"
#include "chrome/browser/gtk/gtk_theme_provider.h"
#endif
#if defined(OS_MACOSX)
#include "chrome/browser/cocoa/extension_installed_bubble_bridge.h"
#endif
// static
const int ExtensionInstallUI::kTitleIds[NUM_PROMPT_TYPES] = {
IDS_EXTENSION_INSTALL_PROMPT_TITLE,
IDS_EXTENSION_UNINSTALL_PROMPT_TITLE
};
// static
const int ExtensionInstallUI::kHeadingIds[NUM_PROMPT_TYPES] = {
IDS_EXTENSION_INSTALL_PROMPT_HEADING,
IDS_EXTENSION_UNINSTALL_PROMPT_HEADING
};
// static
const int ExtensionInstallUI::kButtonIds[NUM_PROMPT_TYPES] = {
IDS_EXTENSION_PROMPT_INSTALL_BUTTON,
IDS_EXTENSION_PROMPT_UNINSTALL_BUTTON
};
namespace {
// We also show the severe warning if the extension has access to any file://
// URLs. They aren't *quite* as dangerous as full access to the system via
// NPAPI, but pretty dang close. Content scripts are currently the only way
// that extension can get access to file:// URLs.
static bool ExtensionHasFileAccess(Extension* extension) {
for (UserScriptList::const_iterator script =
extension->content_scripts().begin();
script != extension->content_scripts().end();
++script) {
for (UserScript::PatternList::const_iterator pattern =
script->url_patterns().begin();
pattern != script->url_patterns().end();
++pattern) {
if (pattern->scheme() == chrome::kFileScheme)
return true;
}
}
return false;
}
static void GetV2Warnings(Extension* extension,
std::vector<string16>* warnings) {
if (!extension->plugins().empty() || ExtensionHasFileAccess(extension)) {
// TODO(aa): This one is a bit awkward. Should we have a separate
// presentation for this case?
warnings->push_back(
l10n_util::GetStringUTF16(IDS_EXTENSION_PROMPT2_WARNING_FULL_ACCESS));
return;
}
if (extension->HasAccessToAllHosts()) {
warnings->push_back(
l10n_util::GetStringUTF16(IDS_EXTENSION_PROMPT2_WARNING_ALL_HOSTS));
} else {
std::set<std::string> hosts = extension->GetEffectiveHostPermissions();
if (hosts.size() == 1) {
warnings->push_back(
l10n_util::GetStringFUTF16(IDS_EXTENSION_PROMPT2_WARNING_1_HOST,
UTF8ToUTF16(*hosts.begin())));
} else if (hosts.size() == 2) {
warnings->push_back(
l10n_util::GetStringFUTF16(IDS_EXTENSION_PROMPT2_WARNING_2_HOSTS,
UTF8ToUTF16(*hosts.begin()),
UTF8ToUTF16(*(++hosts.begin()))));
} else if (hosts.size() == 3) {
warnings->push_back(
l10n_util::GetStringFUTF16(IDS_EXTENSION_PROMPT2_WARNING_3_HOSTS,
UTF8ToUTF16(*hosts.begin()),
UTF8ToUTF16(*(++hosts.begin())),
UTF8ToUTF16(*(++++hosts.begin()))));
} else if (hosts.size() >= 4) {
warnings->push_back(
l10n_util::GetStringFUTF16(
IDS_EXTENSION_PROMPT2_WARNING_4_OR_MORE_HOSTS,
UTF8ToUTF16(*hosts.begin()),
UTF8ToUTF16(*(++hosts.begin())),
IntToString16(hosts.size() - 2)));
}
}
if (extension->HasEffectiveBrowsingHistoryPermission()) {
warnings->push_back(
l10n_util::GetStringUTF16(
IDS_EXTENSION_PROMPT2_WARNING_BROWSING_HISTORY));
}
// TODO(aa): Geolocation, camera/mic, what else?
}
} // namespace
ExtensionInstallUI::ExtensionInstallUI(Profile* profile)
: profile_(profile),
ui_loop_(MessageLoop::current()),
previous_use_system_theme_(false),
extension_(NULL),
delegate_(NULL),
prompt_type_(NUM_PROMPT_TYPES),
ALLOW_THIS_IN_INITIALIZER_LIST(tracker_(this)) {}
void ExtensionInstallUI::ConfirmInstall(Delegate* delegate,
Extension* extension) {
DCHECK(ui_loop_ == MessageLoop::current());
extension_ = extension;
delegate_ = delegate;
// We special-case themes to not show any confirm UI. Instead they are
// immediately installed, and then we show an infobar (see OnInstallSuccess)
// to allow the user to revert if they don't like it.
if (extension->IsTheme()) {
// Remember the current theme in case the user pressed undo.
Extension* previous_theme = profile_->GetTheme();
if (previous_theme)
previous_theme_id_ = previous_theme->id();
#if defined(TOOLKIT_GTK)
// On Linux, we also need to take the user's system settings into account
// to undo theme installation.
previous_use_system_theme_ =
GtkThemeProvider::GetFrom(profile_)->UseGtkTheme();
#else
DCHECK(!previous_use_system_theme_);
#endif
delegate->InstallUIProceed(false);
return;
}
ShowConfirmation(INSTALL_PROMPT);
}
void ExtensionInstallUI::ConfirmUninstall(Delegate* delegate,
Extension* extension) {
DCHECK(ui_loop_ == MessageLoop::current());
extension_ = extension;
delegate_ = delegate;
ShowConfirmation(UNINSTALL_PROMPT);
}
void ExtensionInstallUI::OnInstallSuccess(Extension* extension) {
if (extension->IsTheme()) {
ShowThemeInfoBar(previous_theme_id_, previous_use_system_theme_,
extension, profile_);
return;
}
if (extension->GetFullLaunchURL().is_valid()) {
Browser::OpenApplicationTab(profile_, extension);
return;
}
// GetLastActiveWithProfile will fail on the build bots. This needs to be
// implemented differently if any test is created which depends on
// ExtensionInstalledBubble showing.
Browser* browser = BrowserList::GetLastActiveWithProfile(profile_);
#if defined(TOOLKIT_VIEWS)
if (!browser)
return;
ExtensionInstalledBubble::Show(extension, browser, icon_);
#elif defined(OS_MACOSX)
DCHECK(browser);
// Note that browser actions don't appear in incognito mode initially,
// so fall back to the generic case.
if ((extension->browser_action() && !browser->profile()->IsOffTheRecord()) ||
(extension->page_action() &&
!extension->page_action()->default_icon_path().empty())) {
ExtensionInstalledBubbleCocoa::ShowExtensionInstalledBubble(
browser->window()->GetNativeHandle(),
extension, browser, icon_);
} else {
// If the extension is of type GENERIC, meaning it doesn't have a UI
// surface to display for this window, launch infobar instead of popup
// bubble, because we have no guaranteed wrench menu button to point to.
ShowGenericExtensionInstalledInfoBar(extension);
}
#elif defined(TOOLKIT_GTK)
if (!browser)
return;
ExtensionInstalledBubbleGtk::Show(extension, browser, icon_);
#endif // TOOLKIT_VIEWS
}
void ExtensionInstallUI::OnInstallFailure(const std::string& error) {
DCHECK(ui_loop_ == MessageLoop::current());
Browser* browser = BrowserList::GetLastActiveWithProfile(profile_);
platform_util::SimpleErrorBox(
browser ? browser->window()->GetNativeHandle() : NULL,
l10n_util::GetStringUTF16(IDS_EXTENSION_INSTALL_FAILURE_TITLE),
UTF8ToUTF16(error));
}
void ExtensionInstallUI::OnOverinstallAttempted(Extension* extension) {
ShowThemeInfoBar(previous_theme_id_, previous_use_system_theme_,
extension, profile_);
}
void ExtensionInstallUI::OnImageLoaded(
SkBitmap* image, ExtensionResource resource, int index) {
if (image)
icon_ = *image;
else
icon_ = SkBitmap();
if (icon_.empty()) {
icon_ = *ResourceBundle::GetSharedInstance().GetBitmapNamed(
IDR_EXTENSION_DEFAULT_ICON);
}
switch (prompt_type_) {
case INSTALL_PROMPT: {
NotificationService* service = NotificationService::current();
service->Notify(NotificationType::EXTENSION_WILL_SHOW_CONFIRM_DIALOG,
Source<ExtensionInstallUI>(this),
NotificationService::NoDetails());
std::vector<string16> warnings;
GetV2Warnings(extension_, &warnings);
ShowExtensionInstallUIPrompt2Impl(
profile_, delegate_, extension_, &icon_, warnings);
break;
}
case UNINSTALL_PROMPT: {
string16 message =
l10n_util::GetStringUTF16(IDS_EXTENSION_UNINSTALL_CONFIRMATION);
ShowExtensionInstallUIPromptImpl(profile_, delegate_, extension_, &icon_,
message, UNINSTALL_PROMPT);
break;
}
default:
NOTREACHED() << "Unknown message";
break;
}
}
void ExtensionInstallUI::ShowThemeInfoBar(
const std::string& previous_theme_id, bool previous_use_system_theme,
Extension* new_theme, Profile* profile) {
if (!new_theme->IsTheme())
return;
Browser* browser = BrowserList::GetLastActiveWithProfile(profile);
if (!browser)
return;
TabContents* tab_contents = browser->GetSelectedTabContents();
if (!tab_contents)
return;
// First find any previous theme preview infobars.
InfoBarDelegate* old_delegate = NULL;
for (int i = 0; i < tab_contents->infobar_delegate_count(); ++i) {
InfoBarDelegate* delegate = tab_contents->GetInfoBarDelegateAt(i);
if (delegate->AsThemePreviewInfobarDelegate()) {
old_delegate = delegate;
break;
}
}
// Then either replace that old one or add a new one.
InfoBarDelegate* new_delegate =
GetNewThemeInstalledInfoBarDelegate(
tab_contents, new_theme,
previous_theme_id, previous_use_system_theme);
if (old_delegate)
tab_contents->ReplaceInfoBar(old_delegate, new_delegate);
else
tab_contents->AddInfoBar(new_delegate);
}
void ExtensionInstallUI::ShowConfirmation(PromptType prompt_type) {
// Load the image asynchronously. For the response, check OnImageLoaded.
prompt_type_ = prompt_type;
ExtensionResource image =
extension_->GetIconPath(Extension::EXTENSION_ICON_LARGE);
tracker_.LoadImage(extension_, image,
gfx::Size(Extension::EXTENSION_ICON_LARGE,
Extension::EXTENSION_ICON_LARGE),
ImageLoadingTracker::DONT_CACHE);
}
#if defined(OS_MACOSX)
void ExtensionInstallUI::ShowGenericExtensionInstalledInfoBar(
Extension* new_extension) {
Browser* browser = BrowserList::GetLastActiveWithProfile(profile_);
if (!browser)
return;
TabContents* tab_contents = browser->GetSelectedTabContents();
if (!tab_contents)
return;
std::wstring msg = l10n_util::GetStringF(IDS_EXTENSION_INSTALLED_HEADING,
UTF8ToWide(new_extension->name())) +
L" " + l10n_util::GetString(IDS_EXTENSION_INSTALLED_MANAGE_INFO_MAC);
InfoBarDelegate* delegate = new SimpleAlertInfoBarDelegate(
tab_contents, msg, new SkBitmap(icon_), true);
tab_contents->AddInfoBar(delegate);
}
#endif
InfoBarDelegate* ExtensionInstallUI::GetNewThemeInstalledInfoBarDelegate(
TabContents* tab_contents, Extension* new_theme,
const std::string& previous_theme_id, bool previous_use_system_theme) {
#if defined(TOOLKIT_GTK)
return new GtkThemeInstalledInfoBarDelegate(tab_contents, new_theme,
previous_theme_id, previous_use_system_theme);
#else
return new ThemeInstalledInfoBarDelegate(tab_contents, new_theme,
previous_theme_id);
#endif
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/prerender/prerender_field_trial.h"
#include "base/command_line.h"
#include "base/logging.h"
#include "base/metrics/field_trial.h"
#include "base/metrics/histogram.h"
#include "chrome/browser/metrics/metrics_service.h"
#include "chrome/browser/predictors/autocomplete_action_predictor.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/prerender/prerender_manager.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/chrome_version_info.h"
using base::FieldTrial;
using base::FieldTrialList;
namespace prerender {
namespace {
const char kOmniboxTrialName[] = "PrerenderFromOmnibox";
int g_omnibox_trial_default_group_number = kint32min;
const char kSpeculativePrefetchingTrialName[] = "SpeculativePrefetching";
int g_speculative_prefetching_learning_group = kint32min;
int g_speculative_prefetching_prefetching_group = kint32min;
const char kLocalPredictorTrialName[] = "PrerenderLocalPredictor";
int g_local_predictor_default_group_number = kint32min;
void SetupPrefetchFieldTrial() {
chrome::VersionInfo::Channel channel = chrome::VersionInfo::GetChannel();
if (channel == chrome::VersionInfo::CHANNEL_STABLE ||
channel == chrome::VersionInfo::CHANNEL_BETA) {
return;
}
const FieldTrial::Probability divisor = 1000;
const FieldTrial::Probability prefetch_probability = 500;
scoped_refptr<FieldTrial> trial(
FieldTrialList::FactoryGetFieldTrial(
"Prefetch", divisor, "ContentPrefetchPrefetchOff",
2013, 6, 30, NULL));
const int kPrefetchOnGroup = trial->AppendGroup("ContentPrefetchPrefetchOn",
prefetch_probability);
PrerenderManager::SetIsPrefetchEnabled(trial->group() == kPrefetchOnGroup);
}
void SetupPrerenderFieldTrial() {
const FieldTrial::Probability divisor = 1000;
FieldTrial::Probability control_probability;
FieldTrial::Probability experiment_multi_prerender_probability;
FieldTrial::Probability experiment_15min_ttl_probability;
FieldTrial::Probability experiment_no_use_probability;
chrome::VersionInfo::Channel channel = chrome::VersionInfo::GetChannel();
if (channel == chrome::VersionInfo::CHANNEL_STABLE ||
channel == chrome::VersionInfo::CHANNEL_BETA) {
// Use very conservatives and stable settings in beta and stable.
const FieldTrial::Probability release_prerender_enabled_probability = 980;
const FieldTrial::Probability release_control_probability = 10;
const FieldTrial::Probability
release_experiment_multi_prerender_probability = 0;
const FieldTrial::Probability release_experiment_15min_ttl_probability = 10;
const FieldTrial::Probability release_experiment_no_use_probability = 0;
COMPILE_ASSERT(
release_prerender_enabled_probability + release_control_probability +
release_experiment_multi_prerender_probability +
release_experiment_15min_ttl_probability +
release_experiment_no_use_probability == divisor,
release_experiment_probabilities_must_equal_divisor);
control_probability = release_experiment_15min_ttl_probability;
experiment_multi_prerender_probability =
release_experiment_multi_prerender_probability;
experiment_15min_ttl_probability = release_control_probability;
experiment_no_use_probability = release_experiment_no_use_probability;
} else {
// In testing channels, use more experiments and a larger control group to
// improve quality of data.
const FieldTrial::Probability dev_prerender_enabled_probability = 250;
const FieldTrial::Probability dev_control_probability = 250;
const FieldTrial::Probability
dev_experiment_multi_prerender_probability = 250;
const FieldTrial::Probability dev_experiment_15min_ttl_probability = 125;
const FieldTrial::Probability dev_experiment_no_use_probability = 125;
COMPILE_ASSERT(dev_prerender_enabled_probability + dev_control_probability +
dev_experiment_multi_prerender_probability +
dev_experiment_15min_ttl_probability +
dev_experiment_no_use_probability == divisor,
dev_experiment_probabilities_must_equal_divisor);
control_probability = dev_experiment_15min_ttl_probability;
experiment_multi_prerender_probability =
dev_experiment_multi_prerender_probability;
experiment_15min_ttl_probability = dev_control_probability;
experiment_no_use_probability = dev_experiment_no_use_probability;
}
int prerender_enabled_group = -1;
scoped_refptr<FieldTrial> trial(
FieldTrialList::FactoryGetFieldTrial(
"Prerender", divisor, "PrerenderEnabled",
2013, 6, 30, &prerender_enabled_group));
const int control_group =
trial->AppendGroup("PrerenderControl",
control_probability);
const int experiment_multi_prerender_group =
trial->AppendGroup("PrerenderMulti",
experiment_multi_prerender_probability);
const int experiment_15_min_TTL_group =
trial->AppendGroup("Prerender15minTTL",
experiment_15min_ttl_probability);
const int experiment_no_use_group =
trial->AppendGroup("PrerenderNoUse",
experiment_no_use_probability);
const int trial_group = trial->group();
if (trial_group == prerender_enabled_group) {
PrerenderManager::SetMode(
PrerenderManager::PRERENDER_MODE_EXPERIMENT_PRERENDER_GROUP);
} else if (trial_group == control_group) {
PrerenderManager::SetMode(
PrerenderManager::PRERENDER_MODE_EXPERIMENT_CONTROL_GROUP);
} else if (trial_group == experiment_multi_prerender_group) {
PrerenderManager::SetMode(
PrerenderManager::PRERENDER_MODE_EXPERIMENT_MULTI_PRERENDER_GROUP);
} else if (trial_group == experiment_15_min_TTL_group) {
PrerenderManager::SetMode(
PrerenderManager::PRERENDER_MODE_EXPERIMENT_15MIN_TTL_GROUP);
} else if (trial_group == experiment_no_use_group) {
PrerenderManager::SetMode(
PrerenderManager::PRERENDER_MODE_EXPERIMENT_NO_USE_GROUP);
} else {
NOTREACHED();
}
}
} // end namespace
void ConfigureOmniboxPrerender();
void ConfigureSpeculativePrefetching();
void ConfigureLocalPredictor();
void ConfigurePrefetchAndPrerender(const CommandLine& command_line) {
enum PrerenderOption {
PRERENDER_OPTION_AUTO,
PRERENDER_OPTION_DISABLED,
PRERENDER_OPTION_ENABLED,
PRERENDER_OPTION_PREFETCH_ONLY,
};
PrerenderOption prerender_option = PRERENDER_OPTION_AUTO;
if (command_line.HasSwitch(switches::kPrerenderMode)) {
const std::string switch_value =
command_line.GetSwitchValueASCII(switches::kPrerenderMode);
if (switch_value == switches::kPrerenderModeSwitchValueAuto) {
prerender_option = PRERENDER_OPTION_AUTO;
} else if (switch_value == switches::kPrerenderModeSwitchValueDisabled) {
prerender_option = PRERENDER_OPTION_DISABLED;
} else if (switch_value.empty() ||
switch_value == switches::kPrerenderModeSwitchValueEnabled) {
// The empty string means the option was provided with no value, and that
// means enable.
prerender_option = PRERENDER_OPTION_ENABLED;
} else if (switch_value ==
switches::kPrerenderModeSwitchValuePrefetchOnly) {
prerender_option = PRERENDER_OPTION_PREFETCH_ONLY;
} else {
prerender_option = PRERENDER_OPTION_DISABLED;
LOG(ERROR) << "Invalid --prerender option received on command line: "
<< switch_value;
LOG(ERROR) << "Disabling prerendering!";
}
}
switch (prerender_option) {
case PRERENDER_OPTION_AUTO:
SetupPrefetchFieldTrial();
SetupPrerenderFieldTrial();
break;
case PRERENDER_OPTION_DISABLED:
PrerenderManager::SetIsPrefetchEnabled(false);
PrerenderManager::SetMode(PrerenderManager::PRERENDER_MODE_DISABLED);
break;
case PRERENDER_OPTION_ENABLED:
PrerenderManager::SetIsPrefetchEnabled(true);
PrerenderManager::SetMode(PrerenderManager::PRERENDER_MODE_ENABLED);
break;
case PRERENDER_OPTION_PREFETCH_ONLY:
PrerenderManager::SetIsPrefetchEnabled(true);
PrerenderManager::SetMode(PrerenderManager::PRERENDER_MODE_DISABLED);
break;
default:
NOTREACHED();
}
UMA_HISTOGRAM_ENUMERATION("Prerender.Sessions",
PrerenderManager::GetMode(),
PrerenderManager::PRERENDER_MODE_MAX);
ConfigureOmniboxPrerender();
ConfigureSpeculativePrefetching();
ConfigureLocalPredictor();
}
void ConfigureOmniboxPrerender() {
// Field trial to see if we're enabled.
const FieldTrial::Probability kDivisor = 100;
FieldTrial::Probability kDisabledProbability = 10;
chrome::VersionInfo::Channel channel = chrome::VersionInfo::GetChannel();
if (channel == chrome::VersionInfo::CHANNEL_STABLE ||
channel == chrome::VersionInfo::CHANNEL_BETA) {
kDisabledProbability = 1;
}
scoped_refptr<FieldTrial> omnibox_prerender_trial(
FieldTrialList::FactoryGetFieldTrial(
kOmniboxTrialName, kDivisor, "OmniboxPrerenderEnabled",
2012, 12, 30, &g_omnibox_trial_default_group_number));
omnibox_prerender_trial->AppendGroup("OmniboxPrerenderDisabled",
kDisabledProbability);
}
bool IsOmniboxEnabled(Profile* profile) {
if (!profile)
return false;
if (!PrerenderManager::IsPrerenderingPossible())
return false;
// Override any field trial groups if the user has set a command line flag.
if (CommandLine::ForCurrentProcess()->HasSwitch(
switches::kPrerenderFromOmnibox)) {
const std::string switch_value =
CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
switches::kPrerenderFromOmnibox);
if (switch_value == switches::kPrerenderFromOmniboxSwitchValueEnabled)
return true;
if (switch_value == switches::kPrerenderFromOmniboxSwitchValueDisabled)
return false;
DCHECK(switch_value == switches::kPrerenderFromOmniboxSwitchValueAuto);
}
const int group = FieldTrialList::FindValue(kOmniboxTrialName);
return group == FieldTrial::kNotFinalized ||
group == g_omnibox_trial_default_group_number;
}
void ConfigureSpeculativePrefetching() {
// Field trial to see if we're enabled.
const FieldTrial::Probability kDivisor = 100;
FieldTrial::Probability kLearningProbability = 0;
FieldTrial::Probability kPrefetchingProbability = 0;
chrome::VersionInfo::Channel channel = chrome::VersionInfo::GetChannel();
switch (channel) {
case chrome::VersionInfo::CHANNEL_CANARY:
case chrome::VersionInfo::CHANNEL_DEV:
kLearningProbability = 90;
kPrefetchingProbability = 1;
break;
case chrome::VersionInfo::CHANNEL_BETA:
kLearningProbability = 5;
break;
case chrome::VersionInfo::CHANNEL_STABLE:
case chrome::VersionInfo::CHANNEL_UNKNOWN:
break;
}
scoped_refptr<FieldTrial> speculative_prefetching_trial(
FieldTrialList::FactoryGetFieldTrial(
kSpeculativePrefetchingTrialName,
kDivisor,
"Disabled",
2012, 12, 30,
NULL));
if (kLearningProbability > 0) {
g_speculative_prefetching_learning_group =
speculative_prefetching_trial->AppendGroup("Learning",
kLearningProbability);
}
if (kPrefetchingProbability > 0) {
g_speculative_prefetching_prefetching_group =
speculative_prefetching_trial->AppendGroup("Prefetching",
kPrefetchingProbability);
}
}
bool IsSpeculativeResourcePrefetchingLearningEnabled(Profile* profile) {
if (!profile || profile->IsOffTheRecord())
return false;
// Override any field trial groups if the user has set a command line flag.
if (CommandLine::ForCurrentProcess()->HasSwitch(
switches::kSpeculativeResourcePrefetching)) {
const std::string switch_value =
CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
switches::kSpeculativeResourcePrefetching);
return switch_value == switches::kSpeculativeResourcePrefetchingLearning;
}
const int group = FieldTrialList::FindValue(
kSpeculativePrefetchingTrialName);
return group == g_speculative_prefetching_learning_group;
}
bool IsSpeculativeResourcePrefetchingEnabled(Profile* profile) {
if (!profile)
return false;
// Check if the user has set a command line flag.
if (CommandLine::ForCurrentProcess()->HasSwitch(
switches::kSpeculativeResourcePrefetching)) {
const std::string switch_value =
CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
switches::kSpeculativeResourcePrefetching);
return switch_value == switches::kSpeculativeResourcePrefetchingEnabled;
}
const int group = FieldTrialList::FindValue(
kSpeculativePrefetchingTrialName);
return group == g_speculative_prefetching_prefetching_group;
}
void ConfigureLocalPredictor() {
const FieldTrial::Probability kDivisor = 100;
FieldTrial::Probability kEnableProbability = 90;
chrome::VersionInfo::Channel channel = chrome::VersionInfo::GetChannel();
if (channel == chrome::VersionInfo::CHANNEL_STABLE ||
channel == chrome::VersionInfo::CHANNEL_BETA) {
kEnableProbability = 1;
}
scoped_refptr<FieldTrial> local_predictor_trial(
FieldTrialList::FactoryGetFieldTrial(
kLocalPredictorTrialName, kDivisor, "Disabled",
2013, 12, 31, &g_local_predictor_default_group_number));
local_predictor_trial->AppendGroup("Enabled", kEnableProbability);
}
bool IsLocalPredictorEnabled() {
const int group = FieldTrialList::FindValue(kLocalPredictorTrialName);
return (group != FieldTrial::kNotFinalized &&
group != g_omnibox_trial_default_group_number);
}
} // namespace prerender
<commit_msg>Remove Prerender.Sessions histogram, which was just making sure the field trials groups were being set up correctly.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/prerender/prerender_field_trial.h"
#include "base/command_line.h"
#include "base/logging.h"
#include "base/metrics/field_trial.h"
#include "base/metrics/histogram.h"
#include "chrome/browser/metrics/metrics_service.h"
#include "chrome/browser/predictors/autocomplete_action_predictor.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/prerender/prerender_manager.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/chrome_version_info.h"
using base::FieldTrial;
using base::FieldTrialList;
namespace prerender {
namespace {
const char kOmniboxTrialName[] = "PrerenderFromOmnibox";
int g_omnibox_trial_default_group_number = kint32min;
const char kSpeculativePrefetchingTrialName[] = "SpeculativePrefetching";
int g_speculative_prefetching_learning_group = kint32min;
int g_speculative_prefetching_prefetching_group = kint32min;
const char kLocalPredictorTrialName[] = "PrerenderLocalPredictor";
int g_local_predictor_default_group_number = kint32min;
void SetupPrefetchFieldTrial() {
chrome::VersionInfo::Channel channel = chrome::VersionInfo::GetChannel();
if (channel == chrome::VersionInfo::CHANNEL_STABLE ||
channel == chrome::VersionInfo::CHANNEL_BETA) {
return;
}
const FieldTrial::Probability divisor = 1000;
const FieldTrial::Probability prefetch_probability = 500;
scoped_refptr<FieldTrial> trial(
FieldTrialList::FactoryGetFieldTrial(
"Prefetch", divisor, "ContentPrefetchPrefetchOff",
2013, 6, 30, NULL));
const int kPrefetchOnGroup = trial->AppendGroup("ContentPrefetchPrefetchOn",
prefetch_probability);
PrerenderManager::SetIsPrefetchEnabled(trial->group() == kPrefetchOnGroup);
}
void SetupPrerenderFieldTrial() {
const FieldTrial::Probability divisor = 1000;
FieldTrial::Probability control_probability;
FieldTrial::Probability experiment_multi_prerender_probability;
FieldTrial::Probability experiment_15min_ttl_probability;
FieldTrial::Probability experiment_no_use_probability;
chrome::VersionInfo::Channel channel = chrome::VersionInfo::GetChannel();
if (channel == chrome::VersionInfo::CHANNEL_STABLE ||
channel == chrome::VersionInfo::CHANNEL_BETA) {
// Use very conservatives and stable settings in beta and stable.
const FieldTrial::Probability release_prerender_enabled_probability = 980;
const FieldTrial::Probability release_control_probability = 10;
const FieldTrial::Probability
release_experiment_multi_prerender_probability = 0;
const FieldTrial::Probability release_experiment_15min_ttl_probability = 10;
const FieldTrial::Probability release_experiment_no_use_probability = 0;
COMPILE_ASSERT(
release_prerender_enabled_probability + release_control_probability +
release_experiment_multi_prerender_probability +
release_experiment_15min_ttl_probability +
release_experiment_no_use_probability == divisor,
release_experiment_probabilities_must_equal_divisor);
control_probability = release_experiment_15min_ttl_probability;
experiment_multi_prerender_probability =
release_experiment_multi_prerender_probability;
experiment_15min_ttl_probability = release_control_probability;
experiment_no_use_probability = release_experiment_no_use_probability;
} else {
// In testing channels, use more experiments and a larger control group to
// improve quality of data.
const FieldTrial::Probability dev_prerender_enabled_probability = 250;
const FieldTrial::Probability dev_control_probability = 250;
const FieldTrial::Probability
dev_experiment_multi_prerender_probability = 250;
const FieldTrial::Probability dev_experiment_15min_ttl_probability = 125;
const FieldTrial::Probability dev_experiment_no_use_probability = 125;
COMPILE_ASSERT(dev_prerender_enabled_probability + dev_control_probability +
dev_experiment_multi_prerender_probability +
dev_experiment_15min_ttl_probability +
dev_experiment_no_use_probability == divisor,
dev_experiment_probabilities_must_equal_divisor);
control_probability = dev_experiment_15min_ttl_probability;
experiment_multi_prerender_probability =
dev_experiment_multi_prerender_probability;
experiment_15min_ttl_probability = dev_control_probability;
experiment_no_use_probability = dev_experiment_no_use_probability;
}
int prerender_enabled_group = -1;
scoped_refptr<FieldTrial> trial(
FieldTrialList::FactoryGetFieldTrial(
"Prerender", divisor, "PrerenderEnabled",
2013, 6, 30, &prerender_enabled_group));
const int control_group =
trial->AppendGroup("PrerenderControl",
control_probability);
const int experiment_multi_prerender_group =
trial->AppendGroup("PrerenderMulti",
experiment_multi_prerender_probability);
const int experiment_15_min_TTL_group =
trial->AppendGroup("Prerender15minTTL",
experiment_15min_ttl_probability);
const int experiment_no_use_group =
trial->AppendGroup("PrerenderNoUse",
experiment_no_use_probability);
const int trial_group = trial->group();
if (trial_group == prerender_enabled_group) {
PrerenderManager::SetMode(
PrerenderManager::PRERENDER_MODE_EXPERIMENT_PRERENDER_GROUP);
} else if (trial_group == control_group) {
PrerenderManager::SetMode(
PrerenderManager::PRERENDER_MODE_EXPERIMENT_CONTROL_GROUP);
} else if (trial_group == experiment_multi_prerender_group) {
PrerenderManager::SetMode(
PrerenderManager::PRERENDER_MODE_EXPERIMENT_MULTI_PRERENDER_GROUP);
} else if (trial_group == experiment_15_min_TTL_group) {
PrerenderManager::SetMode(
PrerenderManager::PRERENDER_MODE_EXPERIMENT_15MIN_TTL_GROUP);
} else if (trial_group == experiment_no_use_group) {
PrerenderManager::SetMode(
PrerenderManager::PRERENDER_MODE_EXPERIMENT_NO_USE_GROUP);
} else {
NOTREACHED();
}
}
} // end namespace
void ConfigureOmniboxPrerender();
void ConfigureSpeculativePrefetching();
void ConfigureLocalPredictor();
void ConfigurePrefetchAndPrerender(const CommandLine& command_line) {
enum PrerenderOption {
PRERENDER_OPTION_AUTO,
PRERENDER_OPTION_DISABLED,
PRERENDER_OPTION_ENABLED,
PRERENDER_OPTION_PREFETCH_ONLY,
};
PrerenderOption prerender_option = PRERENDER_OPTION_AUTO;
if (command_line.HasSwitch(switches::kPrerenderMode)) {
const std::string switch_value =
command_line.GetSwitchValueASCII(switches::kPrerenderMode);
if (switch_value == switches::kPrerenderModeSwitchValueAuto) {
prerender_option = PRERENDER_OPTION_AUTO;
} else if (switch_value == switches::kPrerenderModeSwitchValueDisabled) {
prerender_option = PRERENDER_OPTION_DISABLED;
} else if (switch_value.empty() ||
switch_value == switches::kPrerenderModeSwitchValueEnabled) {
// The empty string means the option was provided with no value, and that
// means enable.
prerender_option = PRERENDER_OPTION_ENABLED;
} else if (switch_value ==
switches::kPrerenderModeSwitchValuePrefetchOnly) {
prerender_option = PRERENDER_OPTION_PREFETCH_ONLY;
} else {
prerender_option = PRERENDER_OPTION_DISABLED;
LOG(ERROR) << "Invalid --prerender option received on command line: "
<< switch_value;
LOG(ERROR) << "Disabling prerendering!";
}
}
switch (prerender_option) {
case PRERENDER_OPTION_AUTO:
SetupPrefetchFieldTrial();
SetupPrerenderFieldTrial();
break;
case PRERENDER_OPTION_DISABLED:
PrerenderManager::SetIsPrefetchEnabled(false);
PrerenderManager::SetMode(PrerenderManager::PRERENDER_MODE_DISABLED);
break;
case PRERENDER_OPTION_ENABLED:
PrerenderManager::SetIsPrefetchEnabled(true);
PrerenderManager::SetMode(PrerenderManager::PRERENDER_MODE_ENABLED);
break;
case PRERENDER_OPTION_PREFETCH_ONLY:
PrerenderManager::SetIsPrefetchEnabled(true);
PrerenderManager::SetMode(PrerenderManager::PRERENDER_MODE_DISABLED);
break;
default:
NOTREACHED();
}
ConfigureOmniboxPrerender();
ConfigureSpeculativePrefetching();
ConfigureLocalPredictor();
}
void ConfigureOmniboxPrerender() {
// Field trial to see if we're enabled.
const FieldTrial::Probability kDivisor = 100;
FieldTrial::Probability kDisabledProbability = 10;
chrome::VersionInfo::Channel channel = chrome::VersionInfo::GetChannel();
if (channel == chrome::VersionInfo::CHANNEL_STABLE ||
channel == chrome::VersionInfo::CHANNEL_BETA) {
kDisabledProbability = 1;
}
scoped_refptr<FieldTrial> omnibox_prerender_trial(
FieldTrialList::FactoryGetFieldTrial(
kOmniboxTrialName, kDivisor, "OmniboxPrerenderEnabled",
2012, 12, 30, &g_omnibox_trial_default_group_number));
omnibox_prerender_trial->AppendGroup("OmniboxPrerenderDisabled",
kDisabledProbability);
}
bool IsOmniboxEnabled(Profile* profile) {
if (!profile)
return false;
if (!PrerenderManager::IsPrerenderingPossible())
return false;
// Override any field trial groups if the user has set a command line flag.
if (CommandLine::ForCurrentProcess()->HasSwitch(
switches::kPrerenderFromOmnibox)) {
const std::string switch_value =
CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
switches::kPrerenderFromOmnibox);
if (switch_value == switches::kPrerenderFromOmniboxSwitchValueEnabled)
return true;
if (switch_value == switches::kPrerenderFromOmniboxSwitchValueDisabled)
return false;
DCHECK(switch_value == switches::kPrerenderFromOmniboxSwitchValueAuto);
}
const int group = FieldTrialList::FindValue(kOmniboxTrialName);
return group == FieldTrial::kNotFinalized ||
group == g_omnibox_trial_default_group_number;
}
void ConfigureSpeculativePrefetching() {
// Field trial to see if we're enabled.
const FieldTrial::Probability kDivisor = 100;
FieldTrial::Probability kLearningProbability = 0;
FieldTrial::Probability kPrefetchingProbability = 0;
chrome::VersionInfo::Channel channel = chrome::VersionInfo::GetChannel();
switch (channel) {
case chrome::VersionInfo::CHANNEL_CANARY:
case chrome::VersionInfo::CHANNEL_DEV:
kLearningProbability = 90;
kPrefetchingProbability = 1;
break;
case chrome::VersionInfo::CHANNEL_BETA:
kLearningProbability = 5;
break;
case chrome::VersionInfo::CHANNEL_STABLE:
case chrome::VersionInfo::CHANNEL_UNKNOWN:
break;
}
scoped_refptr<FieldTrial> speculative_prefetching_trial(
FieldTrialList::FactoryGetFieldTrial(
kSpeculativePrefetchingTrialName,
kDivisor,
"Disabled",
2012, 12, 30,
NULL));
if (kLearningProbability > 0) {
g_speculative_prefetching_learning_group =
speculative_prefetching_trial->AppendGroup("Learning",
kLearningProbability);
}
if (kPrefetchingProbability > 0) {
g_speculative_prefetching_prefetching_group =
speculative_prefetching_trial->AppendGroup("Prefetching",
kPrefetchingProbability);
}
}
bool IsSpeculativeResourcePrefetchingLearningEnabled(Profile* profile) {
if (!profile || profile->IsOffTheRecord())
return false;
// Override any field trial groups if the user has set a command line flag.
if (CommandLine::ForCurrentProcess()->HasSwitch(
switches::kSpeculativeResourcePrefetching)) {
const std::string switch_value =
CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
switches::kSpeculativeResourcePrefetching);
return switch_value == switches::kSpeculativeResourcePrefetchingLearning;
}
const int group = FieldTrialList::FindValue(
kSpeculativePrefetchingTrialName);
return group == g_speculative_prefetching_learning_group;
}
bool IsSpeculativeResourcePrefetchingEnabled(Profile* profile) {
if (!profile)
return false;
// Check if the user has set a command line flag.
if (CommandLine::ForCurrentProcess()->HasSwitch(
switches::kSpeculativeResourcePrefetching)) {
const std::string switch_value =
CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
switches::kSpeculativeResourcePrefetching);
return switch_value == switches::kSpeculativeResourcePrefetchingEnabled;
}
const int group = FieldTrialList::FindValue(
kSpeculativePrefetchingTrialName);
return group == g_speculative_prefetching_prefetching_group;
}
void ConfigureLocalPredictor() {
const FieldTrial::Probability kDivisor = 100;
FieldTrial::Probability kEnableProbability = 90;
chrome::VersionInfo::Channel channel = chrome::VersionInfo::GetChannel();
if (channel == chrome::VersionInfo::CHANNEL_STABLE ||
channel == chrome::VersionInfo::CHANNEL_BETA) {
kEnableProbability = 1;
}
scoped_refptr<FieldTrial> local_predictor_trial(
FieldTrialList::FactoryGetFieldTrial(
kLocalPredictorTrialName, kDivisor, "Disabled",
2013, 12, 31, &g_local_predictor_default_group_number));
local_predictor_trial->AppendGroup("Enabled", kEnableProbability);
}
bool IsLocalPredictorEnabled() {
const int group = FieldTrialList::FindValue(kLocalPredictorTrialName);
return (group != FieldTrial::kNotFinalized &&
group != g_omnibox_trial_default_group_number);
}
} // namespace prerender
<|endoftext|>
|
<commit_before>#include <string.h>
#include "serial/ASIOSerialPort.h"
#include <iostream>
#include "actuators/motors/OSMC_driver/OSMC_driver.hpp"
#include <time.h>
using namespace std;
ASIOSerialPort arduinoLeft("/dev/igvc_2012_left_motor_shield", 9600);
ASIOSerialPort arduinoRight("/dev/igvc_2012_right_motor_shield", 9600);
ASIOSerialPort arduinoEncoder("/dev/igvc_2012_right_encoder_shield", 9600);
OSMC_driver::~OSMC_driver()
{
stopMotors();
arduinoRight.close();
arduinoLeft.close();
arduinoEncoder.close();
}
//Checks we are connected and able to send and receive data from the arduinos
bool OSMC_driver::arduinoCheck()
{
std::cout << "Testing serial API..." << std::endl;
arduinoLeft.write("T");
arduinoRight.write("T");
sleep(0.01);
if (arduinoRight.readln() == "T" and arduinoLeft.readln() == "T")
{
std::cout<<"Successfully read from Arduinos" << std::endl;
return true;
}
else
{
std::cout<<"Failed to read from Arduinos"<<std::endl;
arduinoLeft.close();
arduinoRight.close();
return false;
}
}
//writes pwm to arduinos setting both motors to the same pwm and direction (0 = forwards, 1 = backwards)
void OSMC_driver::setPwm(char pwm, Direction dir)
{
if(dir==FORWARD)
{
setRightLeftPwm(pwm, 0, pwm, 0);
}
else if(dir==BACKWARD)
{
}
else
{
cout<<"Bad Direction"<<endl;
}
}
// Writes to arduinos a string of ints dirRight, pwmRight, dirLeft, pwmLeft.
void OSMC_driver::setRightLeftPwm(char pwmRight, char dirRight, char pwmLeft, char dirLeft)
{
pwmRight = adjustSpeedRight(pwmRight, dirRight);
dirLeft = adjustDirLeft(dirLeft);
pwmLeft = adjustSpeedLeft(pwmLeft, dirLeft);
string w = "SW";
w.append(intToString(dirRight));
w.append(" ");
w.append(intToString(pwmRight));
w.append(" ");
w.append(intToString(dirLeft));
w.append(" ");
w.append(intToString(pwmLeft));
arduinoRight.write(w);
string w1 = "SW";
w1.append(intToString(dirLeft));
w1.append(" ");
w1.append(intToString(pwmLeft));
w1.append(" ");
w1.append(intToString(dirRight));
w1.append(" ");
w1.append(intToString(pwmRight));
arduinoLeft.write(w1);
}
//adjusts the pwm of the right motors based on the direction
char OSMC_driver::adjustSpeedRight(char pwm, char dir)
{
if (dir == 1)
{
pwm = 255-pwm;
}
if (dir == 0)
{
pwm = pwm;
}
return (pwm);
}
//adjusts the pwm of the left motors based on the direction
char OSMC_driver::adjustSpeedLeft(char pwm, char dir)
{
if (dir == 1)
{
pwm = 255-pwm;
}
if (dir == 0)
{
pwm = pwm;
}
return (pwm);
}
//adjusts the direction of the left motors because they are mirrors of the right motors
char OSMC_driver::adjustDirLeft(char dirLeft)
{
dirLeft = 1-dirLeft;
return (dirLeft);
}
//turn the robot at a pwm around a circle of a certain radius with a direction
void OSMC_driver::turn(double radius, int pwm, Direction dir) //dir = 0 Right dir = 1 Left
{
double v1 = 0;
double v2 = 0;
double halfWB = WHEELBASE/2;
double comp1 = (radius+halfWB)/(radius-halfWB);
v2 = (2*pwm*comp1)/(1+comp1);
v1 = 2*pwm-v2;
if (dir == RIGHT)
{
setRightLeftPwm(v1, 0, v2, 0);
}
else if(dir == LEFT)
{
setRightLeftPwm(v2, 0, v1, 0);
}
else
{
cout<<"Bad direction"<<endl;
}
}
//Used in writing integers to the arduinos as strings
string OSMC_driver::intToString(int input)
{
std::ostringstream s;
s << input;
return s.str();
}
//Used in writing doubles to the arduinos as strings
string OSMC_driver::doubleToString(double input)
{
std::ostringstream s;
s << input;
return s.str();
}
/*
//Go forward a set distance at a set speed in a certain direction
void OSMC_driver::forward(char pwm, char dir, double dist)
{
setPwm(pwm, dir)
string d = " ";
d.append(doubleToString(dist));
arduino.write(d);
//TODO event listener for a ! from arduino
//while(arduino.readln() != "!") {};
}
void OSMC_driver::turn(double radius, double degree, int pwm, char dir) //dir = 0 Right dir = 1 Left
{
double v1 = 0;
double v2 = 0;
double halfWB = WHEELBASE/2;
double comp1 = (radius+halfWB)/(radius-halfWB);
v2 = (2*pwm*comp1)/(1+comp1);
v1 = 2*pwm-v2;
if (dir == 0)
{
setRightLeftPwm(v1, 0, v2, 0);
}
else if(dir == 1)
{
setRightLeftPwm(v2, 0, v1, 0);
}
else
{
cout<<"Bad direction"<<endl;
}
string r = "SR";
r.append(doubleToString(degree))
arduino.write(r);
}
*/
//Dont quite work at the moment
//functions for reading encoder data from the arduinos and moving a set distance
/*
double OSMC_driver::readEncoder()
{
string r = "R";
arduinoEncoder.write("R");
sleep(0.1);
std::string dist1 = arduinoEncoder.readln();
double dist = ::atof(dist1.c_str());
return dist;
}
void OSMC_driver::encoderLoop(double totalDist)
{
double dist = readEncoder();
while (dist<totalDist)
{
dist = readEncoder();
cout<<dist<<endl;
sleep(0.05);
}
cout<<"Dropped Loop"<<endl;
stopMotors();
}
void OSMC_driver::goForwardOld(double totalDist, char pwm, char dir)
{
string f = "F";
arduinoEncoder.write(f);
sleep(1);
string var;
var = "";
var = arduinoEncoder.readln();
setRightLeftPwm(pwm, dir, pwm, dir);
encoderLoop(totalDist);
}
*/
//Stops the motors
void OSMC_driver::stopMotors()
{
setRightLeftPwm(0,1,0,1);
}
<commit_msg>working on enums<commit_after>#include <string.h>
#include "serial/ASIOSerialPort.h"
#include <iostream>
#include "actuators/motors/OSMC_driver/OSMC_driver.hpp"
#include <time.h>
using namespace std;
ASIOSerialPort arduinoLeft("/dev/igvc_2012_left_motor_shield", 9600);
ASIOSerialPort arduinoRight("/dev/igvc_2012_right_motor_shield", 9600);
ASIOSerialPort arduinoEncoder("/dev/igvc_2012_right_encoder_shield", 9600);
OSMC_driver::~OSMC_driver()
{
stopMotors();
arduinoRight.close();
arduinoLeft.close();
arduinoEncoder.close();
}
//Checks we are connected and able to send and receive data from the arduinos
bool OSMC_driver::arduinoCheck()
{
std::cout << "Testing serial API..." << std::endl;
arduinoLeft.write("T");
arduinoRight.write("T");
sleep(0.01);
if (arduinoRight.readln() == "T" and arduinoLeft.readln() == "T")
{
std::cout<<"Successfully read from Arduinos" << std::endl;
return true;
}
else
{
std::cout<<"Failed to read from Arduinos"<<std::endl;
arduinoLeft.close();
arduinoRight.close();
return false;
}
}
//writes pwm to arduinos setting both motors to the same pwm and direction (0 = forwards, 1 = backwards)
void OSMC_driver::setPwm(char pwm, char dir)
{
/*
if(dir==FORWARD)
{
setRightLeftPwm(pwm, 0, pwm, 0);
}
else if(dir==BACKWARD)
{
}
else
{
cout<<"Bad Direction"<<endl;
}
*/
setRightLeftPwm(pwm,dir,pwm,dir);
}
// Writes to arduinos a string of ints dirRight, pwmRight, dirLeft, pwmLeft.
void OSMC_driver::setRightLeftPwm(char pwmRight, char dirRight, char pwmLeft, char dirLeft)
{
pwmRight = adjustSpeedRight(pwmRight, dirRight);
dirLeft = adjustDirLeft(dirLeft);
pwmLeft = adjustSpeedLeft(pwmLeft, dirLeft);
string w = "SW";
w.append(intToString(dirRight));
w.append(" ");
w.append(intToString(pwmRight));
w.append(" ");
w.append(intToString(dirLeft));
w.append(" ");
w.append(intToString(pwmLeft));
arduinoRight.write(w);
string w1 = "SW";
w1.append(intToString(dirLeft));
w1.append(" ");
w1.append(intToString(pwmLeft));
w1.append(" ");
w1.append(intToString(dirRight));
w1.append(" ");
w1.append(intToString(pwmRight));
arduinoLeft.write(w1);
}
//adjusts the pwm of the right motors based on the direction
char OSMC_driver::adjustSpeedRight(char pwm, char dir)
{
if (dir == 1)
{
pwm = 255-pwm;
}
if (dir == 0)
{
pwm = pwm;
}
return (pwm);
}
//adjusts the pwm of the left motors based on the direction
char OSMC_driver::adjustSpeedLeft(char pwm, char dir)
{
if (dir == 1)
{
pwm = 255-pwm;
}
if (dir == 0)
{
pwm = pwm;
}
return (pwm);
}
//adjusts the direction of the left motors because they are mirrors of the right motors
char OSMC_driver::adjustDirLeft(char dirLeft)
{
dirLeft = 1-dirLeft;
return (dirLeft);
}
//turn the robot at a pwm around a circle of a certain radius with a direction
void OSMC_driver::turn(double radius, int pwm, Direction dir) //dir = 0 Right dir = 1 Left
{
double v1 = 0;
double v2 = 0;
double halfWB = WHEELBASE/2;
double comp1 = (radius+halfWB)/(radius-halfWB);
v2 = (2*pwm*comp1)/(1+comp1);
v1 = 2*pwm-v2;
if (dir == RIGHT)
{
setRightLeftPwm(v1, 0, v2, 0);
}
else if(dir == LEFT)
{
setRightLeftPwm(v2, 0, v1, 0);
}
else
{
cout<<"Bad direction"<<endl;
}
}
//Used in writing integers to the arduinos as strings
string OSMC_driver::intToString(int input)
{
std::ostringstream s;
s << input;
return s.str();
}
//Used in writing doubles to the arduinos as strings
string OSMC_driver::doubleToString(double input)
{
std::ostringstream s;
s << input;
return s.str();
}
/*
//Go forward a set distance at a set speed in a certain direction
void OSMC_driver::forward(char pwm, char dir, double dist)
{
setPwm(pwm, dir)
string d = " ";
d.append(doubleToString(dist));
arduino.write(d);
//TODO event listener for a ! from arduino
//while(arduino.readln() != "!") {};
}
void OSMC_driver::turn(double radius, double degree, int pwm, char dir) //dir = 0 Right dir = 1 Left
{
double v1 = 0;
double v2 = 0;
double halfWB = WHEELBASE/2;
double comp1 = (radius+halfWB)/(radius-halfWB);
v2 = (2*pwm*comp1)/(1+comp1);
v1 = 2*pwm-v2;
if (dir == 0)
{
setRightLeftPwm(v1, 0, v2, 0);
}
else if(dir == 1)
{
setRightLeftPwm(v2, 0, v1, 0);
}
else
{
cout<<"Bad direction"<<endl;
}
string r = "SR";
r.append(doubleToString(degree))
arduino.write(r);
}
*/
//Dont quite work at the moment
//functions for reading encoder data from the arduinos and moving a set distance
/*
double OSMC_driver::readEncoder()
{
string r = "R";
arduinoEncoder.write("R");
sleep(0.1);
std::string dist1 = arduinoEncoder.readln();
double dist = ::atof(dist1.c_str());
return dist;
}
void OSMC_driver::encoderLoop(double totalDist)
{
double dist = readEncoder();
while (dist<totalDist)
{
dist = readEncoder();
cout<<dist<<endl;
sleep(0.05);
}
cout<<"Dropped Loop"<<endl;
stopMotors();
}
void OSMC_driver::goForwardOld(double totalDist, char pwm, char dir)
{
string f = "F";
arduinoEncoder.write(f);
sleep(1);
string var;
var = "";
var = arduinoEncoder.readln();
setRightLeftPwm(pwm, dir, pwm, dir);
encoderLoop(totalDist);
}
*/
//Stops the motors
void OSMC_driver::stopMotors()
{
setRightLeftPwm(0,1,0,1);
}
<|endoftext|>
|
<commit_before>/***************************************************************
*
* Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,
* University of Wisconsin-Madison, WI.
*
* 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.
*
***************************************************************/
/************************************************************************
**
** Set up the various dprintf variables based on the configuration file.
**
************************************************************************/
#define _FILE_OFFSET_BITS 64
#include "condor_common.h"
#include "condor_debug.h"
#include "condor_string.h"
#include "condor_sys_types.h"
#if HAVE_BACKTRACE
#include "sig_install.h"
#endif
int Termlog = 0;
extern int DebugFlags;
extern FILE *DebugFPs[D_NUMLEVELS+1];
extern off_t MaxLog[D_NUMLEVELS+1];
extern int MaxLogNum[D_NUMLEVELS+1];
extern char *DebugFile[D_NUMLEVELS+1];
extern char *DebugLock;
extern const char *_condor_DebugFlagNames[];
extern int _condor_dprintf_works;
extern time_t DebugLastMod;
extern int DebugUseTimestamps;
extern int DebugContinueOnOpenFailure;
extern int log_keep_open;
extern void _condor_set_debug_flags( const char *strflags );
extern void _condor_dprintf_saved_lines( void );
#if HAVE_EXT_GCB
void _condor_gcb_dprintf_va( int flags, char* fmt, va_list args );
extern "C" void Generic_set_log_va(void(*app_log_va)(int level, char *fmt, va_list args));
#endif
#if HAVE_BACKTRACE
static void
sig_backtrace_handler(int signum)
{
dprintf_dump_stack();
// terminate for the same reason.
struct sigaction sa;
sa.sa_handler = SIG_DFL;
sigemptyset(&sa.sa_mask);
sa.sa_flags = 0;
sigaction(signum, &sa, NULL);
sigprocmask(SIG_SETMASK, &sa.sa_mask, NULL);
raise(signum);
}
static void
install_backtrace_handler(void)
{
sigset_t fullset;
sigfillset( &fullset );
install_sig_handler_with_mask(SIGSEGV, &fullset, sig_backtrace_handler);
install_sig_handler_with_mask(SIGABRT, &fullset, sig_backtrace_handler);
install_sig_handler_with_mask(SIGILL, &fullset, sig_backtrace_handler);
install_sig_handler_with_mask(SIGFPE, &fullset, sig_backtrace_handler);
install_sig_handler_with_mask(SIGBUS, &fullset, sig_backtrace_handler);
}
#endif
int
dprintf_config_ContinueOnFailure ( int fContinue )
{
int fOld = DebugContinueOnOpenFailure;
DebugContinueOnOpenFailure = fContinue;
return fOld;
}
void
dprintf_config( const char *subsys )
{
char pname[ BUFSIZ ];
char *pval;
static int first_time = 1;
int want_truncate;
int debug_level;
FILE *debug_file_fp;
int log_open_default = TRUE;
/*
** We want to initialize this here so if we reconfig and the
** debug flags have changed, we actually use the new
** flags. -Derek Wright 12/8/97
*/
DebugFlags = D_ALWAYS;
/*
** First, add the debug flags that are shared by everyone.
*/
pval = param("ALL_DEBUG");
if( pval ) {
_condor_set_debug_flags( pval );
free( pval );
}
/*
** Then, pick up the subsys_DEBUG parameters. Note: if we don't have
** anything set, we just leave it as D_ALWAYS.
*/
(void)sprintf(pname, "%s_DEBUG", subsys);
pval = param(pname);
if( pval ) {
_condor_set_debug_flags( pval );
free( pval );
}
#ifdef WIN32
/* Two reasons why we need to lock the log in Windows
* (when a lock is configured)
* 1) File rotation requires exclusive access in Windows.
* 2) O_APPEND doesn't guarantee atomic writes in Windows
*/
DebugShouldLockToAppend = 1;
#else
DebugShouldLockToAppend = param_boolean_int("LOCK_DEBUG_LOG_TO_APPEND",0);
#endif
/*
** If this is not going to the terminal, pick up the name
** of the log file, maximum log size, and the name of the
** lock file (if it is specified).
*/
if( !( Termlog) ) {
for (debug_level = 0; debug_level <= D_NUMLEVELS; debug_level++) {
want_truncate = 0;
if (debug_level == 0) {
/*
** the level 0 file gets all debug messages; thus, the
** offset into DebugFlagNames is off by one, since the
** first level-specific file goes into the other arrays at
** index 1
*/
(void)sprintf(pname, "%s_LOG", subsys);
} else {
(void)sprintf(pname, "%s_%s_LOG", subsys,
_condor_DebugFlagNames[debug_level-1]+2);
}
// Hold a temporary copy of the old file pointer until
// *after* the param -- param can dprintf() in some cases
{
char *tmp = DebugFile[debug_level];
// NEGOTIATOR_MATCH_LOG is necessary by default, but debug_level
// is not 0
if(debug_level == 0)
{
char *tmp2 = param(pname);
// No default value found, so use $(LOG)/$(SUBSYSTEM)Log
if(!tmp2) {
// This char* will never be freed, but as long as
// defaults are defined in condor_c++_util/param_info.in
// we will never get here.
char *str;
char *log = param("LOG");
char *lsubsys = param("SUBSYSTEM");
if(!log || !lsubsys) {
EXCEPT("Unable to find LOG or SUBSYSTEM.\n");
}
str = (char*)malloc(strlen(log) + strlen(lsubsys) + 5);
sprintf(str, "%s%c%sLog", log, DIR_DELIM_CHAR, lsubsys);
DebugFile[debug_level] = str;
free(log);
free(lsubsys);
}
else {
DebugFile[debug_level] = tmp2;
}
}
else {
// This is looking up configuration options that I can't
// find documentation for, so intead of coding in an
// incorrect default value, I'm gonna use
// param_without_default.
// tristan 5/29/09
DebugFile[debug_level] = param_without_default(pname);
}
if ( tmp ) {
free( tmp );
}
}
if( debug_level == 0 && DebugFile[0] == NULL ) {
EXCEPT("No '%s' parameter specified.", pname);
} else if ( DebugFile[debug_level] != NULL ) {
if (debug_level == 0 && first_time) {
struct stat stat_buf;
if ( stat( DebugFile[debug_level], &stat_buf ) >= 0 ) {
DebugLastMod = stat_buf.st_mtime > stat_buf.st_ctime ? stat_buf.st_mtime : stat_buf.st_ctime;
} else {
DebugLastMod = -errno;
}
}
if (debug_level == 0) {
(void)sprintf(pname, "TRUNC_%s_LOG_ON_OPEN", subsys);
} else {
(void)sprintf(pname, "TRUNC_%s_%s_LOG_ON_OPEN", subsys,
_condor_DebugFlagNames[debug_level-1]+2);
}
pval = param(pname);
if( pval ) {
if( *pval == 't' || *pval == 'T' ) {
want_truncate = 1;
}
free(pval);
}
if (debug_level == 0) {
(void)sprintf(pname, "%s_LOCK", subsys);
if (DebugLock) {
free(DebugLock);
}
DebugLock = param(pname);
}
if( first_time && want_truncate ) {
debug_file_fp = debug_lock(debug_level, "w", 0);
} else {
debug_file_fp = debug_lock(debug_level, "a", 0);
}
if( debug_file_fp == NULL && debug_level == 0 ) {
#ifdef WIN32
/*
** If we could not open the log file, we might want to keep running anyway.
** If we do, then set the log filename to NUL so we don't keep trying
** (and failing) to open the file.
*/
if (DebugContinueOnOpenFailure) {
// change the debug file to point to the NUL device.
static const char strDevNull[] = "NUL";//"\\\\.\\Device\\Null";
char * psz = (char*)malloc(sizeof(strDevNull));
strcpy(psz, strDevNull);
if (DebugFile[debug_level])
free(DebugFile[debug_level]);
DebugFile[debug_level] = psz;
} else
#endif
{
EXCEPT("Cannot open log file '%s'",
DebugFile[debug_level]);
}
}
if (debug_file_fp) (void)debug_unlock( debug_level );
debug_file_fp = NULL;
if (debug_level == 0) {
(void)sprintf(pname, "MAX_%s_LOG", subsys);
} else {
(void)sprintf(pname, "MAX_%s_%s_LOG", subsys,
_condor_DebugFlagNames[debug_level-1]+2);
}
MaxLog[debug_level] = param_integer(pname, 1024*1024);
if (debug_level == 0) {
(void)sprintf(pname, "MAX_NUM_%s_LOG", subsys);
} else {
(void)sprintf(pname, "MAX_NUM_%s_%s_LOG", subsys,
_condor_DebugFlagNames[debug_level-1]+2);
}
MaxLogNum[debug_level] = param_integer(pname, 1);
}
}
} else {
#if !defined(WIN32)
setlinebuf( stderr );
#endif
(void)fflush( stderr ); /* Don't know why we need this, but if not here
the first couple dprintf don't come out right */
}
#ifndef WIN32
if((strcmp(subsys, "SHADOW") == 0) || (strcmp(subsys, "GRIDMANAGER") == 0))
{
log_open_default = FALSE;
}
#endif
if(!DebugLock) {
sprintf(pname, "%s_LOG_KEEP_OPEN", subsys);
log_keep_open = param_boolean_int(pname, log_open_default);
}
first_time = 0;
_condor_dprintf_works = 1;
#if HAVE_EXT_GCB
/*
this method currently only lives in libGCB.a, so don't even
try to param() or call this function unless we're on a
platform where we're using the GCB external
*/
if ( param_boolean_int("NET_REMAP_ENABLE", 0) ) {
Generic_set_log_va(_condor_gcb_dprintf_va);
}
#endif
/*
If LOGS_USE_TIMESTAMP is enabled, we will print out Unix timestamps
instead of the standard date format in all the log messages
*/
DebugUseTimestamps = param_boolean_int( "LOGS_USE_TIMESTAMP", FALSE );
#if HAVE_BACKTRACE
install_backtrace_handler();
#endif
_condor_dprintf_saved_lines();
}
#if HAVE_EXT_GCB
void
_condor_gcb_dprintf_va( int flags, char* fmt, va_list args )
{
char* new_fmt;
int len;
len = strlen(fmt);
new_fmt = (char*) malloc( (len + 6) * sizeof(char) );
if( ! new_fmt ) {
EXCEPT( "_condor_gcb_dprintf_va() out of memory!" );
}
snprintf( new_fmt, len + 6, "GCB: %s", fmt );
_condor_dprintf_va( flags, new_fmt, args );
free( new_fmt );
}
#endif /* HAVE_EXT_GCB */
<commit_msg>Handled by eje, pending review of #2471<commit_after>/***************************************************************
*
* Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,
* University of Wisconsin-Madison, WI.
*
* 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.
*
***************************************************************/
/************************************************************************
**
** Set up the various dprintf variables based on the configuration file.
**
************************************************************************/
#define _FILE_OFFSET_BITS 64
#include "condor_common.h"
#include "condor_debug.h"
#include "condor_string.h"
#include "condor_sys_types.h"
#if HAVE_BACKTRACE
#include "sig_install.h"
#endif
int Termlog = 0;
extern int DebugFlags;
extern FILE *DebugFPs[D_NUMLEVELS+1];
extern off_t MaxLog[D_NUMLEVELS+1];
extern int MaxLogNum[D_NUMLEVELS+1];
extern char *DebugFile[D_NUMLEVELS+1];
extern char *DebugLock;
extern const char *_condor_DebugFlagNames[];
extern int _condor_dprintf_works;
extern time_t DebugLastMod;
extern int DebugUseTimestamps;
extern int DebugContinueOnOpenFailure;
extern int log_keep_open;
extern void _condor_set_debug_flags( const char *strflags );
extern void _condor_dprintf_saved_lines( void );
#if HAVE_EXT_GCB
void _condor_gcb_dprintf_va( int flags, char* fmt, va_list args );
extern "C" void Generic_set_log_va(void(*app_log_va)(int level, char *fmt, va_list args));
#endif
#if HAVE_BACKTRACE
static void
sig_backtrace_handler(int signum)
{
dprintf_dump_stack();
// terminate for the same reason.
struct sigaction sa;
sa.sa_handler = SIG_DFL;
sigemptyset(&sa.sa_mask);
sa.sa_flags = 0;
sigaction(signum, &sa, NULL);
sigprocmask(SIG_SETMASK, &sa.sa_mask, NULL);
raise(signum);
}
static void
install_backtrace_handler(void)
{
sigset_t fullset;
sigfillset( &fullset );
install_sig_handler_with_mask(SIGSEGV, &fullset, sig_backtrace_handler);
install_sig_handler_with_mask(SIGABRT, &fullset, sig_backtrace_handler);
install_sig_handler_with_mask(SIGILL, &fullset, sig_backtrace_handler);
install_sig_handler_with_mask(SIGFPE, &fullset, sig_backtrace_handler);
install_sig_handler_with_mask(SIGBUS, &fullset, sig_backtrace_handler);
}
#endif
int
dprintf_config_ContinueOnFailure ( int fContinue )
{
int fOld = DebugContinueOnOpenFailure;
DebugContinueOnOpenFailure = fContinue;
return fOld;
}
void
dprintf_config( const char *subsys )
{
char pname[ BUFSIZ ];
char *pval;
static int first_time = 1;
int want_truncate;
int debug_level;
FILE *debug_file_fp;
int log_open_default = TRUE;
/*
** We want to initialize this here so if we reconfig and the
** debug flags have changed, we actually use the new
** flags. -Derek Wright 12/8/97
*/
DebugFlags = D_ALWAYS;
/*
** First, add the debug flags that are shared by everyone.
*/
pval = param("ALL_DEBUG");
if( pval ) {
_condor_set_debug_flags( pval );
free( pval );
}
/*
** Then, pick up the subsys_DEBUG parameters. Note: if we don't have
** anything set, we just leave it as D_ALWAYS.
*/
(void)sprintf(pname, "%s_DEBUG", subsys);
pval = param(pname);
if( pval ) {
_condor_set_debug_flags( pval );
free( pval );
}
#ifdef WIN32
/* Two reasons why we need to lock the log in Windows
* (when a lock is configured)
* 1) File rotation requires exclusive access in Windows.
* 2) O_APPEND doesn't guarantee atomic writes in Windows
*/
DebugShouldLockToAppend = 1;
#else
DebugShouldLockToAppend = param_boolean_int("LOCK_DEBUG_LOG_TO_APPEND",0);
#endif
/*
** If this is not going to the terminal, pick up the name
** of the log file, maximum log size, and the name of the
** lock file (if it is specified).
*/
if( !( Termlog) ) {
for (debug_level = 0; debug_level <= D_NUMLEVELS; debug_level++) {
want_truncate = 0;
if (debug_level == 0) {
/*
** the level 0 file gets all debug messages; thus, the
** offset into DebugFlagNames is off by one, since the
** first level-specific file goes into the other arrays at
** index 1
*/
(void)sprintf(pname, "%s_LOG", subsys);
} else {
(void)sprintf(pname, "%s_%s_LOG", subsys,
_condor_DebugFlagNames[debug_level-1]+2);
}
// Hold a temporary copy of the old file pointer until
// *after* the param -- param can dprintf() in some cases
{
char *tmp = DebugFile[debug_level];
// NEGOTIATOR_MATCH_LOG is necessary by default, but debug_level
// is not 0
if(debug_level == 0)
{
char *tmp2 = param(pname);
// No default value found, so use $(LOG)/$(SUBSYSTEM)Log
if(!tmp2) {
// This char* will never be freed, but as long as
// defaults are defined in condor_c++_util/param_info.in
// we will never get here.
char *str;
char *log = param("LOG");
char *lsubsys = param("SUBSYSTEM");
if(!log || !lsubsys) {
EXCEPT("Unable to find LOG or SUBSYSTEM.\n");
}
str = (char*)malloc(strlen(log) + strlen(lsubsys) + 5);
sprintf(str, "%s%c%sLog", log, DIR_DELIM_CHAR, lsubsys);
DebugFile[debug_level] = str;
free(log);
free(lsubsys);
}
else {
DebugFile[debug_level] = tmp2;
}
}
else {
// This is looking up configuration options that I can't
// find documentation for, so intead of coding in an
// incorrect default value, I'm gonna use
// param_without_default.
// tristan 5/29/09
DebugFile[debug_level] = param_without_default(pname);
}
if ( tmp ) {
free( tmp );
}
}
if( debug_level == 0 && DebugFile[0] == NULL ) {
EXCEPT("No '%s' parameter specified.", pname);
} else if ( DebugFile[debug_level] != NULL ) {
if (debug_level == 0 && first_time) {
struct stat stat_buf;
if ( stat( DebugFile[debug_level], &stat_buf ) >= 0 ) {
DebugLastMod = stat_buf.st_mtime > stat_buf.st_ctime ? stat_buf.st_mtime : stat_buf.st_ctime;
} else {
DebugLastMod = -errno;
}
}
if (debug_level == 0) {
(void)sprintf(pname, "TRUNC_%s_LOG_ON_OPEN", subsys);
} else {
(void)sprintf(pname, "TRUNC_%s_%s_LOG_ON_OPEN", subsys,
_condor_DebugFlagNames[debug_level-1]+2);
}
pval = param(pname);
if( pval ) {
if( *pval == 't' || *pval == 'T' ) {
want_truncate = 1;
}
free(pval);
}
if (debug_level == 0) {
(void)sprintf(pname, "%s_LOCK", subsys);
if (DebugLock) {
free(DebugLock);
}
DebugLock = param(pname);
}
if( first_time && want_truncate ) {
debug_file_fp = debug_lock(debug_level, "w", 0);
} else {
debug_file_fp = debug_lock(debug_level, "a", 0);
}
if( debug_file_fp == NULL && debug_level == 0 ) {
#ifdef WIN32
/*
** If we could not open the log file, we might want to keep running anyway.
** If we do, then set the log filename to NUL so we don't keep trying
** (and failing) to open the file.
*/
if (DebugContinueOnOpenFailure) {
// change the debug file to point to the NUL device.
static const char strDevNull[] = "NUL";//"\\\\.\\Device\\Null";
char * psz = (char*)malloc(sizeof(strDevNull));
strcpy(psz, strDevNull);
if (DebugFile[debug_level])
free(DebugFile[debug_level]);
DebugFile[debug_level] = psz;
} else
#endif
{
EXCEPT("Cannot open log file '%s'",
DebugFile[debug_level]);
}
}
if (debug_file_fp) (void)debug_unlock( debug_level );
debug_file_fp = NULL;
if (debug_level == 0) {
(void)sprintf(pname, "MAX_%s_LOG", subsys);
} else {
(void)sprintf(pname, "MAX_%s_%s_LOG", subsys,
_condor_DebugFlagNames[debug_level-1]+2);
}
pval = param(pname);
if( pval != NULL ) {
MaxLog[debug_level] = atoi( pval );
free(pval);
} else {
MaxLog[debug_level] = 1024*1024;
}
if (debug_level == 0) {
(void)sprintf(pname, "MAX_NUM_%s_LOG", subsys);
} else {
(void)sprintf(pname, "MAX_NUM_%s_%s_LOG", subsys,
_condor_DebugFlagNames[debug_level-1]+2);
}
MaxLogNum[debug_level] = param_integer(pname, 1);
}
}
} else {
#if !defined(WIN32)
setlinebuf( stderr );
#endif
(void)fflush( stderr ); /* Don't know why we need this, but if not here
the first couple dprintf don't come out right */
}
#ifndef WIN32
if((strcmp(subsys, "SHADOW") == 0) || (strcmp(subsys, "GRIDMANAGER") == 0))
{
log_open_default = FALSE;
}
#endif
if(!DebugLock) {
sprintf(pname, "%s_LOG_KEEP_OPEN", subsys);
log_keep_open = param_boolean_int(pname, log_open_default);
}
first_time = 0;
_condor_dprintf_works = 1;
#if HAVE_EXT_GCB
/*
this method currently only lives in libGCB.a, so don't even
try to param() or call this function unless we're on a
platform where we're using the GCB external
*/
if ( param_boolean_int("NET_REMAP_ENABLE", 0) ) {
Generic_set_log_va(_condor_gcb_dprintf_va);
}
#endif
/*
If LOGS_USE_TIMESTAMP is enabled, we will print out Unix timestamps
instead of the standard date format in all the log messages
*/
DebugUseTimestamps = param_boolean_int( "LOGS_USE_TIMESTAMP", FALSE );
#if HAVE_BACKTRACE
install_backtrace_handler();
#endif
_condor_dprintf_saved_lines();
}
#if HAVE_EXT_GCB
void
_condor_gcb_dprintf_va( int flags, char* fmt, va_list args )
{
char* new_fmt;
int len;
len = strlen(fmt);
new_fmt = (char*) malloc( (len + 6) * sizeof(char) );
if( ! new_fmt ) {
EXCEPT( "_condor_gcb_dprintf_va() out of memory!" );
}
snprintf( new_fmt, len + 6, "GCB: %s", fmt );
_condor_dprintf_va( flags, new_fmt, args );
free( new_fmt );
}
#endif /* HAVE_EXT_GCB */
<|endoftext|>
|
<commit_before>/*********************************************************************
** Author: Zach Colbert
** Date: 22 November 2017
** Description: The T3Reader class interacts with the Board class to
"play" a game of tic-tac-toe based on a set of instructions read from
a text file. It features a simple constructor and a member function to
feed the input file to.
*********************************************************************/
#include "T3Reader.hpp"
#include <fstream>
#include <string>
#include <iostream>
using std::string;
using std::cout;
using std::endl;
// The constructor takes a char argument to indicate which "player"
// will go first in the game
T3Reader::T3Reader(char firstTurn)
{
nextTurn = firstTurn;
}
/*********************************************************************
** Description: readGameFile takes a string argument for the name of
the input file. It reads the text file line by line, passing
instructions to the makeMove function of the Board class.
It checks the state of the game after each move, returning false if
the instructions continue beyond the end of the game. It also returns
false when it encounters an illegal move.
After each move, it toggles the game piece that is placed in the
succeeding turn.
*********************************************************************/
bool T3Reader::readGameFile(string fileName)
{
// Initialize variables to store the coords and results for each move
int xCoord, yCoord;
int breakReturn = 0;
bool moveResult;
// Open the input file
std::ifstream inFile(fileName);
// Loop until the end of the file
while (inFile >> xCoord >> yCoord)
{
// If the game is finished, return false
if (gameBoard.gameState() != 3)
{
// Make sure to close the file!
inFile.close();
breakReturn = 1;
break;
}
// Otherwise, record the result of each move
moveResult = gameBoard.makeMove(xCoord, yCoord, nextTurn);
// Return false if the move failed
if (moveResult == false)
{
// Make sure to close the file!
inFile.close();
breakReturn = 1;
break;
}
// Toggle the next player
if (nextTurn == 'x')
{
nextTurn = 'o';
}
else
{
nextTurn = 'x';
}
}
// Return false for the things that break the while loop
if (breakReturn == 1)
{
return false;
}
else
{
// If you got this far, it worked! Close the file and return true.
inFile.close();
return true;
}
}
<commit_msg>Fixed a flip error<commit_after>/*********************************************************************
** Author: Zach Colbert
** Date: 22 November 2017
** Description: The T3Reader class interacts with the Board class to
"play" a game of tic-tac-toe based on a set of instructions read from
a text file. It features a simple constructor and a member function to
feed the input file to.
*********************************************************************/
#include "T3Reader.hpp"
#include <fstream>
#include <string>
#include <iostream>
using std::string;
using std::cout;
using std::endl;
// The constructor takes a char argument to indicate which "player"
// will go first in the game
T3Reader::T3Reader(char firstTurn)
{
nextTurn = firstTurn;
}
/*********************************************************************
** Description: readGameFile takes a string argument for the name of
the input file. It reads the text file line by line, passing
instructions to the makeMove function of the Board class.
It checks the state of the game after each move, returning false if
the instructions continue beyond the end of the game. It also returns
false when it encounters an illegal move.
After each move, it toggles the game piece that is placed in the
succeeding turn.
*********************************************************************/
bool T3Reader::readGameFile(string fileName)
{
// Initialize variables to store the coords and results for each move
int xCoord, yCoord;
int breakReturn = 0;
bool moveResult;
// Open the input file
std::ifstream inFile;
inFile.open(fileName);
// Loop until the end of the file
while (inFile >> xCoord >> yCoord)
{
// If the game is finished, return false
if (gameBoard.gameState() != 3)
{
// Make sure to close the file!
inFile.close();
breakReturn = 1;
break;
}
// Otherwise, record the result of each move
moveResult = gameBoard.makeMove(xCoord, yCoord, nextTurn);
// Return false if the move failed
if (moveResult == false)
{
// Make sure to close the file!
inFile.close();
breakReturn = 1;
break;
}
// Toggle the next player
if (nextTurn == 'x')
{
nextTurn = 'o';
}
else
{
nextTurn = 'x';
}
}
// Return false for the things that break the while loop
if (breakReturn == 1)
{
return false;
}
else
{
// If you got this far, it worked! Close the file and return true.
inFile.close();
return true;
}
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: resultcolumn.hxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: obo $ $Date: 2005-12-19 17:15:05 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _DBACORE_RESULTCOLUMN_HXX_
#define _DBACORE_RESULTCOLUMN_HXX_
#ifndef _COM_SUN_STAR_SDBC_XRESULTSETMETADATA_HDL_
#include <com/sun/star/sdbc/XResultSetMetaData.hdl>
#endif
#ifndef _DBA_COREAPI_COLUMN_HXX_
#include <column.hxx>
#endif
namespace dbaccess
{
//************************************************************
// OResultColumn
//************************************************************
class OResultColumn : public OColumn,
public ::comphelper::OPropertyArrayUsageHelper < OResultColumn >
{
protected:
::com::sun::star::uno::Reference < ::com::sun::star::sdbc::XResultSetMetaData > m_xMetaData;
::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData > m_xDBMetaData;
sal_Int32 m_nPos;
::com::sun::star::uno::Any m_aIsRowVersion;
virtual ~OResultColumn();
public:
OResultColumn(
const ::com::sun::star::uno::Reference < ::com::sun::star::sdbc::XResultSetMetaData >& _xMetaData,
sal_Int32 _nPos,
const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData >& _rxDBMeta );
// com::sun::star::lang::XTypeProvider
virtual ::com::sun::star::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() throw (::com::sun::star::uno::RuntimeException);
// com::sun::star::lang::XServiceInfo
virtual ::rtl::OUString SAL_CALL getImplementationName( ) throw(::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames( ) throw(::com::sun::star::uno::RuntimeException);
// cppu::OComponentHelper
virtual void SAL_CALL disposing(void);
// comphelper::OPropertyArrayUsageHelper
virtual ::cppu::IPropertyArrayHelper* createArrayHelper( ) const;
// cppu::OPropertySetHelper
virtual ::cppu::IPropertyArrayHelper& SAL_CALL getInfoHelper();
virtual void SAL_CALL getFastPropertyValue(
::com::sun::star::uno::Any& rValue,
sal_Int32 nHandle
) const;
private:
void impl_determineIsRowVersion_nothrow();
};
}
#endif // _DBACORE_RESULTCOLUMN_HXX_
<commit_msg>INTEGRATION: CWS warnings01 (1.6.28); FILE MERGED 2006/03/24 15:35:49 fs 1.6.28.1: #i57457# warning-free code (unxlngi6/.pro + unxsoli4.pro)<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: resultcolumn.hxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: hr $ $Date: 2006-06-20 02:40:45 $
*
* 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 _DBACORE_RESULTCOLUMN_HXX_
#define _DBACORE_RESULTCOLUMN_HXX_
#ifndef _COM_SUN_STAR_SDBC_XRESULTSETMETADATA_HDL_
#include <com/sun/star/sdbc/XResultSetMetaData.hdl>
#endif
#ifndef _DBA_COREAPI_COLUMN_HXX_
#include <column.hxx>
#endif
namespace dbaccess
{
//************************************************************
// OResultColumn
//************************************************************
class OResultColumn : public OColumn,
public ::comphelper::OPropertyArrayUsageHelper < OResultColumn >
{
protected:
::com::sun::star::uno::Reference < ::com::sun::star::sdbc::XResultSetMetaData > m_xMetaData;
::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData > m_xDBMetaData;
sal_Int32 m_nPos;
::com::sun::star::uno::Any m_aIsRowVersion;
virtual ~OResultColumn();
public:
OResultColumn(
const ::com::sun::star::uno::Reference < ::com::sun::star::sdbc::XResultSetMetaData >& _xMetaData,
sal_Int32 _nPos,
const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData >& _rxDBMeta );
// com::sun::star::lang::XTypeProvider
virtual ::com::sun::star::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() throw (::com::sun::star::uno::RuntimeException);
// com::sun::star::lang::XServiceInfo
virtual ::rtl::OUString SAL_CALL getImplementationName( ) throw(::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames( ) throw(::com::sun::star::uno::RuntimeException);
// cppu::OComponentHelper
virtual void SAL_CALL disposing(void);
// comphelper::OPropertyArrayUsageHelper
virtual ::cppu::IPropertyArrayHelper* createArrayHelper( ) const;
// cppu::OPropertySetHelper
virtual ::cppu::IPropertyArrayHelper& SAL_CALL getInfoHelper();
virtual void SAL_CALL getFastPropertyValue(
::com::sun::star::uno::Any& rValue,
sal_Int32 nHandle
) const;
private:
void impl_determineIsRowVersion_nothrow();
protected:
using ::cppu::OPropertySetHelper::getFastPropertyValue;
};
}
#endif // _DBACORE_RESULTCOLUMN_HXX_
<|endoftext|>
|
<commit_before>// @(#)root/meta:$Id$
// Author: Rene Brun 09/02/95
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
/** \class TMethod
Each ROOT class (see TClass) has a linked list of methods.
This class describes one single method (member function).
The method info is obtained via the CINT api. See class TCling.
The method information is used a.o. by the THml class and by the
TTree class.
*/
#include "strtok.h"
#include "strlcpy.h"
#include "snprintf.h"
#include "TClass.h"
#include "TList.h"
#include "TMethod.h"
#include "TMethodArg.h"
#include "TMethodCall.h"
#include "TInterpreter.h"
#include "Strlen.h"
#include "TDataMember.h"
ClassImp(TMethod);
////////////////////////////////////////////////////////////////////////////////
/// Default TMethod ctor. TMethods are constructed in TClass.
/// Comment strings are pre-parsed to find out whether the method is
/// a context-menu item.
TMethod::TMethod(MethodInfo_t *info, TClass *cl) : TFunction(info)
{
fClass = cl;
fGetterMethod = 0;
fSetterMethod = 0;
fMenuItem = kMenuNoMenu;
if (fInfo) {
SetMenuItem(gCling->MethodInfo_Title(fInfo));
}
}
////////////////////////////////////////////////////////////////////////////////
/// Copy ctor.
TMethod::TMethod(const TMethod& orig) : TFunction(orig)
{
fClass = orig.fClass;
fMenuItem = orig.fMenuItem;
fGetter = orig.fGetter;
fGetterMethod = 0;
fSetterMethod = 0;
}
////////////////////////////////////////////////////////////////////////////////
/// Assignment operator.
TMethod& TMethod::operator=(const TMethod& rhs)
{
if (this != &rhs) {
TFunction::operator=(rhs);
fClass = rhs.fClass;
fMenuItem = rhs.fMenuItem;
fGetter = rhs.fGetter;
if (fGetterMethod)
delete fGetterMethod;
fGetterMethod = 0;
if (fSetterMethod)
delete fSetterMethod;
fSetterMethod = 0;
}
return *this;
}
////////////////////////////////////////////////////////////////////////////////
/// Cleanup.
TMethod::~TMethod()
{
delete fGetterMethod;
delete fSetterMethod;
}
////////////////////////////////////////////////////////////////////////////////
/// Clone method.
TObject *TMethod::Clone(const char *newname) const
{
TNamed *newobj = new TMethod(*this);
if (newname && strlen(newname)) newobj->SetName(newname);
return newobj;
}
////////////////////////////////////////////////////////////////////////////////
/// Returns a comment string from the class declaration.
const char *TMethod::GetCommentString()
{
return fInfo ? gCling->MethodInfo_Title(fInfo) : "";
}
////////////////////////////////////////////////////////////////////////////////
/// Using the CINT method arg information create a complete signature string.
void TMethod::CreateSignature()
{
TFunction::CreateSignature();
if (Property() & kIsConstMethod) fSignature += " const";
}
////////////////////////////////////////////////////////////////////////////////
/// Tries to guess DataMember from comment string
/// and Method's name <==(only if 1 Argument!).
/// If more then one argument=> returns pointer to the last argument.
/// It also sets MethodArgs' pointers to point to specified data members.
///
/// The form of comment string defining arguments is:
/// void XXX(Int_t x1, Float_t y2) //*ARGS={x1=>fX1,y2=>fY2}
/// where fX1, fY2 are data fields in the same class.
/// ("pointers" to data members)
TDataMember *TMethod::FindDataMember()
{
Char_t *argstring = (char*)strstr(GetCommentString(),"*ARGS={");
// the following statement has been commented (Rene). Not needed
// it was making troubles in BuildRealData for classes with protected
// default constructors.
// if (!(GetClass()->GetListOfRealData())) GetClass()->BuildRealData();
if (argstring) {
// if we found any argument-specifying hints - parse it
if (!fMethodArgs) return 0;
Int_t nchs = strlen(argstring); // workspace...
char *argstr = new char[nchs+1]; // workspace...
char *ptr1 = 0;
char *tok = 0;
char *ptr2 = 0;
Int_t i;
strlcpy(argstr,argstring,nchs+1); //let's move it to "workspace" copy
char *rest;
ptr2 = R__STRTOK_R(argstr, "{}", &rest); // extract the data!
if (ptr2 == 0) {
Fatal("FindDataMember","Internal error found '*ARGS=\"' but not \"{}\" in %s",GetCommentString());
delete [] argstr;
return 0;
}
ptr2 = R__STRTOK_R((char *)0, "{}", &rest);
//extract argument tokens//
char *tokens[20];
Int_t cnt = 0;
Int_t token_cnt = 0;
do {
ptr1 = R__STRTOK_R((char *)(cnt++ ? 0 : ptr2), ",;", &rest); // extract tokens
// separated by , or ;
if (ptr1) {
Int_t nch = strlen(ptr1);
tok = new char[nch+1];
strlcpy(tok,ptr1,nch+1);
tokens[token_cnt] = tok; //store this token.
token_cnt++;
}
} while (ptr1);
//now let's parse all argument tokens...
TClass *cl = 0;
TMethodArg *a = 0;
TMethodArg *ar = 0;
TDataMember *member = 0;
for (i=0; i<token_cnt;i++) {
cnt = 0;
ptr1 = R__STRTOK_R(tokens[i], "=>", &rest); // LeftHandedSide=methodarg
ptr2 = R__STRTOK_R((char *)0, "=>", &rest); // RightHandedSide-points to datamember
//find the MethodArg
a = 0;
ar = 0;
member = 0;
TIter nextarg(fMethodArgs); // iterate through all arguments.
while ((ar = (TMethodArg*)nextarg())) {
if (!strcmp(ptr1,ar->GetName())) {
a = ar;
break;
}
}
//now find the data member
cl = GetClass()->GetBaseDataMember(ptr2);
if (cl) {
member = cl->GetDataMember(ptr2);
if (a) a->fDataMember = member; //SET THE APROPRIATE FIELD !!!
//We can do it - friend decl. in MethodArg
}
delete [] tokens[i];
}
delete [] argstr;
return member; // nothing else to do! We return a pointer to the last
// found data member
// if not found in comment string - try to guess it from name!
} else {
if (fMethodArgs)
if (fMethodArgs->GetSize() != 1) return 0;
TMethodArg *a = 0;
if (fMethodArgs) a = (TMethodArg*)(fMethodArgs->First());
char dataname[67] = "";
char basename[64] = "";
const char *funcname = GetName();
if ( strncmp(funcname,"Get",3) == 0 || strncmp(funcname,"Set",3) == 0 )
snprintf(basename,64,"%s",funcname+3);
else if ( strncmp(funcname,"Is",2) == 0 )
snprintf(basename,64,"%s",funcname+2);
else if (strncmp(funcname, "Has", 3) == 0)
snprintf(basename,64,"%s", funcname+3);
else
return 0;
snprintf(dataname,67,"f%s",basename);
TClass *cl = GetClass()->GetBaseDataMember(dataname);
if (cl) {
TDataMember *member = cl->GetDataMember(dataname);
if (a) a->fDataMember = member;
return member;
} else {
snprintf(dataname,67,"fIs%s",basename); //in case of IsEditable()
//and fIsEditable
cl = GetClass()->GetBaseDataMember(dataname);
if (cl) {
TDataMember *member = cl->GetDataMember(dataname);
if (a) a->fDataMember = member;
return member;
}
}
}
//if nothing found - return null -pointer:
return 0;
}
////////////////////////////////////////////////////////////////////////////////
/// Return call environment for the getter method in case this is a
/// *TOGGLE method (for the context menu).
TMethodCall *TMethod::GetterMethod()
{
if (!fGetterMethod && fMenuItem == kMenuToggle && fGetter != "" && fClass) {
fGetterMethod = new TMethodCall(fClass, Getter(), "");
}
return fGetterMethod;
}
////////////////////////////////////////////////////////////////////////////////
/// Return true if this function object is pointing to a currently
/// loaded function. If a function is unloaded after the TMethod
/// is created, the TMethod will be set to be invalid.
Bool_t TMethod::IsValid()
{
// Register the transaction when checking the validity of the object.
if (!fInfo && UpdateInterpreterStateMarker()) {
DeclId_t newId = gInterpreter->GetFunction(fClass->GetClassInfo(), fName);
if (newId) {
MethodInfo_t *info = gInterpreter->MethodInfo_Factory(newId);
Update(info);
}
return newId != 0;
}
return fInfo != 0;
}
////////////////////////////////////////////////////////////////////////////////
/// Return call environment for this method in case this is a
/// *TOGGLE method which takes a single boolean or integer argument.
TMethodCall *TMethod::SetterMethod()
{
if (!fSetterMethod && fMenuItem == kMenuToggle && fClass) {
fSetterMethod = new TMethodCall(fClass, GetName(), "1");
}
return fSetterMethod;
}
////////////////////////////////////////////////////////////////////////////////
/// Returns methodarg list and additionally updates fDataMember in TMethod by
/// calling FindDataMember();
TList *TMethod::GetListOfMethodArgs()
{
if (!fMethodArgs){
TFunction::GetListOfMethodArgs();
FindDataMember();
}
return fMethodArgs;
}
////////////////////////////////////////////////////////////////////////////////
/// Set the menu item as prescribed in the doctstring.
void TMethod::SetMenuItem(const char *docstring)
{
if (docstring && strstr(docstring, "*TOGGLE")) {
fMenuItem = kMenuToggle;
const char *s;
if ((s = strstr(docstring, "*GETTER="))) {
fGetter = s+8;
fGetter = fGetter.Strip(TString::kBoth);
}
} else
if (docstring && strstr(docstring, "*MENU"))
fMenuItem = kMenuDialog;
else
if (docstring && strstr(docstring, "*SUBMENU"))
fMenuItem = kMenuSubMenu;
else
fMenuItem = kMenuNoMenu;
}
////////////////////////////////////////////////////////////////////////////////
/// Update the TMethod to reflect the new info.
///
/// This can be used to implement unloading (info == 0) and then reloading
/// (info being the 'new' decl address).
Bool_t TMethod::Update(MethodInfo_t *info)
{
if (TFunction::Update(info)) {
delete fGetterMethod; fGetterMethod = 0;
delete fSetterMethod; fSetterMethod = 0;
if (fInfo) {
SetMenuItem(gCling->MethodInfo_Title(fInfo));
}
return kTRUE;
} else {
return kFALSE;
}
}
<commit_msg>Remove unused variable from TMethod.cxx<commit_after>// @(#)root/meta:$Id$
// Author: Rene Brun 09/02/95
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
/** \class TMethod
Each ROOT class (see TClass) has a linked list of methods.
This class describes one single method (member function).
The method info is obtained via the CINT api. See class TCling.
The method information is used a.o. by the THml class and by the
TTree class.
*/
#include "strtok.h"
#include "strlcpy.h"
#include "snprintf.h"
#include "TClass.h"
#include "TList.h"
#include "TMethod.h"
#include "TMethodArg.h"
#include "TMethodCall.h"
#include "TInterpreter.h"
#include "Strlen.h"
#include "TDataMember.h"
ClassImp(TMethod);
////////////////////////////////////////////////////////////////////////////////
/// Default TMethod ctor. TMethods are constructed in TClass.
/// Comment strings are pre-parsed to find out whether the method is
/// a context-menu item.
TMethod::TMethod(MethodInfo_t *info, TClass *cl) : TFunction(info)
{
fClass = cl;
fGetterMethod = 0;
fSetterMethod = 0;
fMenuItem = kMenuNoMenu;
if (fInfo) {
SetMenuItem(gCling->MethodInfo_Title(fInfo));
}
}
////////////////////////////////////////////////////////////////////////////////
/// Copy ctor.
TMethod::TMethod(const TMethod& orig) : TFunction(orig)
{
fClass = orig.fClass;
fMenuItem = orig.fMenuItem;
fGetter = orig.fGetter;
fGetterMethod = 0;
fSetterMethod = 0;
}
////////////////////////////////////////////////////////////////////////////////
/// Assignment operator.
TMethod& TMethod::operator=(const TMethod& rhs)
{
if (this != &rhs) {
TFunction::operator=(rhs);
fClass = rhs.fClass;
fMenuItem = rhs.fMenuItem;
fGetter = rhs.fGetter;
if (fGetterMethod)
delete fGetterMethod;
fGetterMethod = 0;
if (fSetterMethod)
delete fSetterMethod;
fSetterMethod = 0;
}
return *this;
}
////////////////////////////////////////////////////////////////////////////////
/// Cleanup.
TMethod::~TMethod()
{
delete fGetterMethod;
delete fSetterMethod;
}
////////////////////////////////////////////////////////////////////////////////
/// Clone method.
TObject *TMethod::Clone(const char *newname) const
{
TNamed *newobj = new TMethod(*this);
if (newname && strlen(newname)) newobj->SetName(newname);
return newobj;
}
////////////////////////////////////////////////////////////////////////////////
/// Returns a comment string from the class declaration.
const char *TMethod::GetCommentString()
{
return fInfo ? gCling->MethodInfo_Title(fInfo) : "";
}
////////////////////////////////////////////////////////////////////////////////
/// Using the CINT method arg information create a complete signature string.
void TMethod::CreateSignature()
{
TFunction::CreateSignature();
if (Property() & kIsConstMethod) fSignature += " const";
}
////////////////////////////////////////////////////////////////////////////////
/// Tries to guess DataMember from comment string
/// and Method's name <==(only if 1 Argument!).
/// If more then one argument=> returns pointer to the last argument.
/// It also sets MethodArgs' pointers to point to specified data members.
///
/// The form of comment string defining arguments is:
/// void XXX(Int_t x1, Float_t y2) //*ARGS={x1=>fX1,y2=>fY2}
/// where fX1, fY2 are data fields in the same class.
/// ("pointers" to data members)
TDataMember *TMethod::FindDataMember()
{
Char_t *argstring = (char*)strstr(GetCommentString(),"*ARGS={");
// the following statement has been commented (Rene). Not needed
// it was making troubles in BuildRealData for classes with protected
// default constructors.
// if (!(GetClass()->GetListOfRealData())) GetClass()->BuildRealData();
if (argstring) {
// if we found any argument-specifying hints - parse it
if (!fMethodArgs) return 0;
Int_t nchs = strlen(argstring); // workspace...
char *argstr = new char[nchs+1]; // workspace...
char *ptr1 = 0;
char *tok = 0;
char *ptr2 = 0;
Int_t i;
strlcpy(argstr,argstring,nchs+1); //let's move it to "workspace" copy
char *rest;
ptr2 = R__STRTOK_R(argstr, "{}", &rest); // extract the data!
if (ptr2 == 0) {
Fatal("FindDataMember","Internal error found '*ARGS=\"' but not \"{}\" in %s",GetCommentString());
delete [] argstr;
return 0;
}
ptr2 = R__STRTOK_R((char *)0, "{}", &rest);
//extract argument tokens//
char *tokens[20];
Int_t cnt = 0;
Int_t token_cnt = 0;
do {
ptr1 = R__STRTOK_R((char *)(cnt++ ? 0 : ptr2), ",;", &rest); // extract tokens
// separated by , or ;
if (ptr1) {
Int_t nch = strlen(ptr1);
tok = new char[nch+1];
strlcpy(tok,ptr1,nch+1);
tokens[token_cnt] = tok; //store this token.
token_cnt++;
}
} while (ptr1);
//now let's parse all argument tokens...
TClass *cl = nullptr;
TMethodArg *a = nullptr;
TMethodArg *ar = nullptr;
TDataMember *member = nullptr;
for (i=0; i<token_cnt;i++) {
ptr1 = R__STRTOK_R(tokens[i], "=>", &rest); // LeftHandedSide=methodarg
ptr2 = R__STRTOK_R((char *) nullptr, "=>", &rest); // RightHandedSide-points to datamember
//find the MethodArg
a = 0;
ar = 0;
member = 0;
TIter nextarg(fMethodArgs); // iterate through all arguments.
while ((ar = (TMethodArg*)nextarg())) {
if (!strcmp(ptr1,ar->GetName())) {
a = ar;
break;
}
}
//now find the data member
cl = GetClass()->GetBaseDataMember(ptr2);
if (cl) {
member = cl->GetDataMember(ptr2);
if (a) a->fDataMember = member; //SET THE APROPRIATE FIELD !!!
//We can do it - friend decl. in MethodArg
}
delete [] tokens[i];
}
delete [] argstr;
return member; // nothing else to do! We return a pointer to the last
// found data member
// if not found in comment string - try to guess it from name!
} else {
if (fMethodArgs)
if (fMethodArgs->GetSize() != 1) return 0;
TMethodArg *a = 0;
if (fMethodArgs) a = (TMethodArg*)(fMethodArgs->First());
char dataname[67] = "";
char basename[64] = "";
const char *funcname = GetName();
if ( strncmp(funcname,"Get",3) == 0 || strncmp(funcname,"Set",3) == 0 )
snprintf(basename,64,"%s",funcname+3);
else if ( strncmp(funcname,"Is",2) == 0 )
snprintf(basename,64,"%s",funcname+2);
else if (strncmp(funcname, "Has", 3) == 0)
snprintf(basename,64,"%s", funcname+3);
else
return 0;
snprintf(dataname,67,"f%s",basename);
TClass *cl = GetClass()->GetBaseDataMember(dataname);
if (cl) {
TDataMember *member = cl->GetDataMember(dataname);
if (a) a->fDataMember = member;
return member;
} else {
snprintf(dataname,67,"fIs%s",basename); //in case of IsEditable()
//and fIsEditable
cl = GetClass()->GetBaseDataMember(dataname);
if (cl) {
TDataMember *member = cl->GetDataMember(dataname);
if (a) a->fDataMember = member;
return member;
}
}
}
//if nothing found - return null -pointer:
return 0;
}
////////////////////////////////////////////////////////////////////////////////
/// Return call environment for the getter method in case this is a
/// *TOGGLE method (for the context menu).
TMethodCall *TMethod::GetterMethod()
{
if (!fGetterMethod && fMenuItem == kMenuToggle && fGetter != "" && fClass) {
fGetterMethod = new TMethodCall(fClass, Getter(), "");
}
return fGetterMethod;
}
////////////////////////////////////////////////////////////////////////////////
/// Return true if this function object is pointing to a currently
/// loaded function. If a function is unloaded after the TMethod
/// is created, the TMethod will be set to be invalid.
Bool_t TMethod::IsValid()
{
// Register the transaction when checking the validity of the object.
if (!fInfo && UpdateInterpreterStateMarker()) {
DeclId_t newId = gInterpreter->GetFunction(fClass->GetClassInfo(), fName);
if (newId) {
MethodInfo_t *info = gInterpreter->MethodInfo_Factory(newId);
Update(info);
}
return newId != 0;
}
return fInfo != 0;
}
////////////////////////////////////////////////////////////////////////////////
/// Return call environment for this method in case this is a
/// *TOGGLE method which takes a single boolean or integer argument.
TMethodCall *TMethod::SetterMethod()
{
if (!fSetterMethod && fMenuItem == kMenuToggle && fClass) {
fSetterMethod = new TMethodCall(fClass, GetName(), "1");
}
return fSetterMethod;
}
////////////////////////////////////////////////////////////////////////////////
/// Returns methodarg list and additionally updates fDataMember in TMethod by
/// calling FindDataMember();
TList *TMethod::GetListOfMethodArgs()
{
if (!fMethodArgs){
TFunction::GetListOfMethodArgs();
FindDataMember();
}
return fMethodArgs;
}
////////////////////////////////////////////////////////////////////////////////
/// Set the menu item as prescribed in the doctstring.
void TMethod::SetMenuItem(const char *docstring)
{
if (docstring && strstr(docstring, "*TOGGLE")) {
fMenuItem = kMenuToggle;
const char *s;
if ((s = strstr(docstring, "*GETTER="))) {
fGetter = s+8;
fGetter = fGetter.Strip(TString::kBoth);
}
} else
if (docstring && strstr(docstring, "*MENU"))
fMenuItem = kMenuDialog;
else
if (docstring && strstr(docstring, "*SUBMENU"))
fMenuItem = kMenuSubMenu;
else
fMenuItem = kMenuNoMenu;
}
////////////////////////////////////////////////////////////////////////////////
/// Update the TMethod to reflect the new info.
///
/// This can be used to implement unloading (info == 0) and then reloading
/// (info being the 'new' decl address).
Bool_t TMethod::Update(MethodInfo_t *info)
{
if (TFunction::Update(info)) {
delete fGetterMethod; fGetterMethod = 0;
delete fSetterMethod; fSetterMethod = 0;
if (fInfo) {
SetMenuItem(gCling->MethodInfo_Title(fInfo));
}
return kTRUE;
} else {
return kFALSE;
}
}
<|endoftext|>
|
<commit_before>#include "Application.hpp"
#include "StringIDImpl.hpp"
#include <iomanip>
#include <iostream>
#include <fstream>
#include <sstream>
#include <regex>
#include "File.hpp"
#include <stdio.h>
#include <windows.h>
#include <algorithm>
static const char* g_help =
"-help Display this help and do nothing\n"
"-project Name of the project (default=\"StringIDProj\"\n"
"-gui Launch GUI application\n"
"-sources List folders to search (=\"C:/Folder1;../Folder2\")\n"
"-destination Destination root folder where to copy results.\n"
" If empty, modifications will be in place\n"
"-excludedFolders List folders to exclude (=\"C:/Folder1;../Folder2\")\n"
"-excludedSources List sources to exclude (=\"path1;path2\")\n"
"-extensions List extensions to parse (default=\".cpp;.h;.hh;.inl\")\n"
"-clean Will not use cache infos, will re-parse all files\n"
"-verbose Show detailed diagnostic information for debugging\n"
"-saveForUndo Will keep a save of modified files in project's file\n"
"-undo Used in association with -project will undo last generation\n"
"-summary Display a detailed summary\n";
Application::Application()
:
_projectName("StringIDProj"),
_guiEnabled(false),
_destination(""),
_clean(false),
_verbose(false),
_saveforundo(false),
_undo(false),
_displaySummary(false),
_inPlace(false)
{
}
Application::~Application()
{
}
bool Application::init(int argc, char *argv[])
{
for (int i = 1; i < argc; ++i)
{
std::string arg = argv[i];
if (arg.empty())
continue;
if (arg[0] == '-')
{
if (arg == "-help")
{
std::cout << g_help << std::endl;
continue;
}
if (arg == "-project")
{
int projectPathIndex = i + 1;
if (projectPathIndex >= argc)
{
//ERROR
std::cerr << "Project path missing\n";
return false;
}
_projectName = argv[projectPathIndex];
++i;
continue;
}
if (arg == "-gui")
{
_guiEnabled = true;
continue;
}
if (arg == "-sources")
{
int sourcesIndex = i + 1;
if (sourcesIndex >= argc)
{
std::cerr << "Sources missing\n";
return false;
//ERROR
}
std::string source = argv[sourcesIndex];
while (source.empty() == false && source[0] != '-')
{
_sources.push_back(CleanPath(MakePathAbsolute(source)) + "/");
++sourcesIndex;
source = "";
if (sourcesIndex < argc)
{
source = argv[sourcesIndex];
}
}
if (_sources.empty())
{
std::cerr << "Sources missing\n";
return false;
//ERROR
}
i = sourcesIndex - 1;
continue;
}
if (arg == "-destination")
{
int destIndex = i + 1;
if (destIndex >= argc)
{
std::cerr << "Destination missing\n";
return false;
//ERROR
}
arg = argv[destIndex];
if (arg.empty() || arg[0] == '-')
{
std::cerr << "Destination missing\n";
return false;
//ERROR
}
_destination = CleanPath(MakePathAbsolute(arg));
++i;
continue;
}
if (arg == "-excludedFolders")
{
int excludedFoldersIndex = i + 1;
if (excludedFoldersIndex >= argc)
{
std::cerr << "Excluded folders missing\n";
return false;
//ERROR
}
std::string source = argv[excludedFoldersIndex];
while (source.empty() == false && source[0] != '-')
{
_excludedFolders.push_back(CleanPath(MakePathAbsolute(source)));
++excludedFoldersIndex;
source = "";
if (excludedFoldersIndex < argc)
{
source = argv[excludedFoldersIndex];
}
}
if (_excludedFolders.empty())
{
std::cerr << "Excluded folders missing\n";
return false;
//ERROR
}
i = excludedFoldersIndex - 1;
continue;
}
if (arg == "-excludedSources")
{
int excludedSourcesIndex = i + 1;
if (excludedSourcesIndex >= argc)
{
std::cerr << "Excluded sources missing\n";
return false;
//ERROR
}
std::string source = argv[excludedSourcesIndex];
while (source.empty() == false && source[0] != '-')
{
_excludedSources.push_back(CleanPath(MakePathAbsolute(source)));
++excludedSourcesIndex;
source = "";
if (excludedSourcesIndex < argc)
{
source = argv[excludedSourcesIndex];
}
}
if (_excludedSources.empty())
{
std::cerr << "Excluded sources missing\n";
return false;
//ERROR
}
i = excludedSourcesIndex - 1;
continue;
}
if (arg == "-extensions")
{
int extIndex = i + 1;
if (extIndex >= argc)
{
std::cerr << "Extensions missing\n";
return false;
//ERROR
}
std::string source = argv[extIndex];
while (source.empty() == false && source[0] != '-')
{
_extensions.push_back(source);
++extIndex;
source = "";
if (extIndex < argc)
{
source = argv[extIndex];
}
}
if (_extensions.empty())
{
std::cerr << "Extensions missing\n";
return false;
//ERROR
}
i = extIndex - 1;
continue;
}
if (arg == "-clean")
{
_clean = true;
continue;
}
if (arg == "-verbose")
{
_verbose = true;
continue;
}
if (arg == "-saveForUndo")
{
_saveforundo = true;
continue;
}
if (arg == "-undo")
{
_undo = true;
continue;
}
if (arg == "-summary")
{
_displaySummary = true;
continue;
}
}
}
if (_extensions.empty())
{
_extensions.push_back("h");
_extensions.push_back("cpp");
_extensions.push_back("hpp");
_extensions.push_back("inl");
}
if (_sources.empty())
{
std::cerr << "Sources missing\n";
return false;
//ERROR
}
if (_destination.empty())
{
_inPlace = true;
}
_currentDirectory = GetCurrentDirectory();
return true;
}
/*
Regexp :
StringID("String") :
[\\s+|\\t|\\n|\\r]StringID\s*[(]{1}\s*["]{1}.+["]{1}\s*[)]
\bStringID\s*[(]{1}\s*["]{1}.+["]{1}\s*[)]{1}
\\bStringID\\s*[(]{1}\\s*[\"]{1}.+[\"]{1}\\s*[)]{1}
StringID("String", 0x123) :
(\\s+|\\t|\\n|\\r)StringID\s*[(]{1}\s*["]{1}.+["]{1}\s*[,]{1}\s*(0x\d+|\d+)\s*[)]{1}
StringID(0x123) :
(\\s+|\\t|\\n|\\r)StringID\s*[(]{1}\s*(0x\d+|\d+)\s*[)]{1}
For test :
StringID("StringA")
StringID( "StringB" )
StringID ("StringC")
StringID ("StringD")
StringID ( "StringE")
StringID( " StringF " )
StringID ( "StringG" )
TotoStringID ( "StringH" )
TotoStringID ( "StringI" )
*/
template< typename T >
std::string IntToHex(T i)
{
std::stringstream stream;
stream << "0x"
<< std::setfill('0') << std::setw(sizeof(T) * 2)
<< std::hex << i;
return stream.str();
}
void Application::treatFile(const FileInfo &fileInfo)
{
std::ifstream file(fileInfo.absPath.c_str());
std::ofstream output(std::string(_destination + fileInfo.absPath + ".sid").c_str());
std::string line;
std::size_t counter = 0;
/*
1 : crap
2 : str
*/
std::regex regStringOnly ("(.*?)\\bStringID\\s*[(]{1}\\s*[\"]{1}(.+?)[\"]{1}\\s*[)]{1}");
/*
1 : Crap
2 : str
3 : 0x123
*/
std::regex regStringAndHash("(.*?)\\bStringID\\s*[(]{1}\\s*\"(.+?)\"\\s*,\\s*(0x[\\d|a-f]+|[\\d|a-f]+)\\s*[)]{1}");
std::match_results<std::string::const_iterator> match;
while (std::getline(file, line))
{
std::istringstream iss(line);
line += "\n";
if (line.find("StringID") != std::string::npos)
{
std::string lineCopy = line;
line.clear();
auto flags = std::regex_constants::match_default | std::regex_constants::format_first_only | std::regex_constants::format_no_copy;
bool pass = false;
// We search for already hashed strings like StringID("Literal", 0x123);
// We check if the hash is up to date, if not we re-generate it
// We also register the hash if not already in db cache to check for collisions
while (std::regex_search(lineCopy, match, regStringAndHash, flags))
{
auto &str = match[2].str();
auto &h = match[3].str();
StringIDType id = strtoll(h.c_str(), nullptr, 16);
StringID sid = StringID(str);
if (sid.getId() != id)
{
std::string replacer = "$1StringID(\"$2\", ";
replacer += IntToHex(sid.getId());
replacer += ")";
line += std::regex_replace(lineCopy, regStringAndHash, replacer, flags);
pass = true;
}
else
{
line = lineCopy;
}
lineCopy = match.suffix().str();
}
if (pass)
{
line += lineCopy;
}
if (!line.empty())
lineCopy = line;
line.clear();
pass = false;
// We search for StringID("Literal");
// And generate ID for it
while (std::regex_search(lineCopy, match, regStringOnly, flags))
{
std::string replacer = "$1StringID(\"$2\", ";
auto &str = match[2].str();
replacer += IntToHex(StringID(str).getId());
replacer += ")";
line += std::regex_replace(lineCopy, regStringOnly, replacer, flags);
lineCopy = match.suffix().str();
pass = true;
}
if (pass)
{
line += lineCopy;
}
if (line.empty())
{
line = lineCopy;
}
}
output << line;
}
}
void Application::run()
{
if (_guiEnabled)
{
//_initGui();
}
std::vector<FileInfo> infos;
FileFilter filter;
filter._extensions = _extensions;
filter._excludedPath = _excludedSources;
filter._excludedDir = _excludedFolders;
filter._minimumWriteTime = 0;
for (auto &source : _sources)
{
SearchFiles(/*"D:\Epic Games/"*/ source /*"../Tests/"*/, &filter, infos);
// we set relative path
for (auto &res : infos)
{
res.relPath = res.absPath;
res.relPath.erase(0, source.size());
}
}
for (auto &s : infos)
{
treatFile(s);
}
}<commit_msg>Small fix<commit_after>#include "Application.hpp"
#include "StringIDImpl.hpp"
#include <iomanip>
#include <iostream>
#include <fstream>
#include <sstream>
#include <regex>
#include "File.hpp"
#include <stdio.h>
#include <windows.h>
#include <algorithm>
static const char* g_help =
"-help Display this help and do nothing\n"
"-project Name of the project (default=\"StringIDProj\"\n"
"-gui Launch GUI application\n"
"-sources List folders to search (=\"C:/Folder1;../Folder2\")\n"
"-destination Destination root folder where to copy results.\n"
" If empty, modifications will be in place\n"
"-excludedFolders List folders to exclude (=\"C:/Folder1;../Folder2\")\n"
"-excludedSources List sources to exclude (=\"path1;path2\")\n"
"-extensions List extensions to parse (default=\".cpp;.h;.hh;.inl\")\n"
"-clean Will not use cache infos, will re-parse all files\n"
"-verbose Show detailed diagnostic information for debugging\n"
"-saveForUndo Will keep a save of modified files in project's file\n"
"-undo Used in association with -project will undo last generation\n"
"-summary Display a detailed summary\n";
Application::Application()
:
_projectName("StringIDProj"),
_guiEnabled(false),
_destination(""),
_clean(false),
_verbose(false),
_saveforundo(false),
_undo(false),
_displaySummary(false),
_inPlace(false)
{
}
Application::~Application()
{
}
bool Application::init(int argc, char *argv[])
{
for (int i = 1; i < argc; ++i)
{
std::string arg = argv[i];
if (arg.empty())
continue;
if (arg[0] == '-')
{
if (arg == "-help")
{
std::cout << g_help << std::endl;
continue;
}
if (arg == "-project")
{
int projectPathIndex = i + 1;
if (projectPathIndex >= argc)
{
//ERROR
std::cerr << "Project path missing\n";
return false;
}
_projectName = argv[projectPathIndex];
++i;
continue;
}
if (arg == "-gui")
{
_guiEnabled = true;
continue;
}
if (arg == "-sources")
{
int sourcesIndex = i + 1;
if (sourcesIndex >= argc)
{
std::cerr << "Sources missing\n";
return false;
//ERROR
}
std::string source = argv[sourcesIndex];
while (source.empty() == false && source[0] != '-')
{
_sources.push_back(CleanPath(MakePathAbsolute(source)) + "/");
++sourcesIndex;
source = "";
if (sourcesIndex < argc)
{
source = argv[sourcesIndex];
}
}
if (_sources.empty())
{
std::cerr << "Sources missing\n";
return false;
//ERROR
}
i = sourcesIndex - 1;
continue;
}
if (arg == "-destination")
{
int destIndex = i + 1;
if (destIndex >= argc)
{
std::cerr << "Destination missing\n";
return false;
//ERROR
}
arg = argv[destIndex];
if (arg.empty() || arg[0] == '-')
{
std::cerr << "Destination missing\n";
return false;
//ERROR
}
_destination = CleanPath(MakePathAbsolute(arg));
++i;
continue;
}
if (arg == "-excludedFolders")
{
int excludedFoldersIndex = i + 1;
if (excludedFoldersIndex >= argc)
{
std::cerr << "Excluded folders missing\n";
return false;
//ERROR
}
std::string source = argv[excludedFoldersIndex];
while (source.empty() == false && source[0] != '-')
{
_excludedFolders.push_back(CleanPath(MakePathAbsolute(source)));
++excludedFoldersIndex;
source = "";
if (excludedFoldersIndex < argc)
{
source = argv[excludedFoldersIndex];
}
}
if (_excludedFolders.empty())
{
std::cerr << "Excluded folders missing\n";
return false;
//ERROR
}
i = excludedFoldersIndex - 1;
continue;
}
if (arg == "-excludedSources")
{
int excludedSourcesIndex = i + 1;
if (excludedSourcesIndex >= argc)
{
std::cerr << "Excluded sources missing\n";
return false;
//ERROR
}
std::string source = argv[excludedSourcesIndex];
while (source.empty() == false && source[0] != '-')
{
_excludedSources.push_back(CleanPath(MakePathAbsolute(source)));
++excludedSourcesIndex;
source = "";
if (excludedSourcesIndex < argc)
{
source = argv[excludedSourcesIndex];
}
}
if (_excludedSources.empty())
{
std::cerr << "Excluded sources missing\n";
return false;
//ERROR
}
i = excludedSourcesIndex - 1;
continue;
}
if (arg == "-extensions")
{
int extIndex = i + 1;
if (extIndex >= argc)
{
std::cerr << "Extensions missing\n";
return false;
//ERROR
}
std::string source = argv[extIndex];
while (source.empty() == false && source[0] != '-')
{
_extensions.push_back(source);
++extIndex;
source = "";
if (extIndex < argc)
{
source = argv[extIndex];
}
}
if (_extensions.empty())
{
std::cerr << "Extensions missing\n";
return false;
//ERROR
}
i = extIndex - 1;
continue;
}
if (arg == "-clean")
{
_clean = true;
continue;
}
if (arg == "-verbose")
{
_verbose = true;
continue;
}
if (arg == "-saveForUndo")
{
_saveforundo = true;
continue;
}
if (arg == "-undo")
{
_undo = true;
continue;
}
if (arg == "-summary")
{
_displaySummary = true;
continue;
}
}
}
if (_extensions.empty())
{
_extensions.push_back("h");
_extensions.push_back("cpp");
_extensions.push_back("hpp");
_extensions.push_back("inl");
}
if (_sources.empty())
{
std::cerr << "Sources missing\n";
return false;
//ERROR
}
if (_destination.empty())
{
_inPlace = true;
}
_currentDirectory = GetCurrentDirectory();
return true;
}
/*
Regexp :
StringID("String") :
[\\s+|\\t|\\n|\\r]StringID\s*[(]{1}\s*["]{1}.+["]{1}\s*[)]
\bStringID\s*[(]{1}\s*["]{1}.+["]{1}\s*[)]{1}
\\bStringID\\s*[(]{1}\\s*[\"]{1}.+[\"]{1}\\s*[)]{1}
StringID("String", 0x123) :
(\\s+|\\t|\\n|\\r)StringID\s*[(]{1}\s*["]{1}.+["]{1}\s*[,]{1}\s*(0x\d+|\d+)\s*[)]{1}
StringID(0x123) :
(\\s+|\\t|\\n|\\r)StringID\s*[(]{1}\s*(0x\d+|\d+)\s*[)]{1}
For test :
StringID("StringA")
StringID( "StringB" )
StringID ("StringC")
StringID ("StringD")
StringID ( "StringE")
StringID( " StringF " )
StringID ( "StringG" )
TotoStringID ( "StringH" )
TotoStringID ( "StringI" )
*/
template< typename T >
std::string IntToHex(T i)
{
std::stringstream stream;
stream << "0x"
<< std::setfill('0') << std::setw(sizeof(T) * 2)
<< std::hex << i;
return stream.str();
}
void Application::treatFile(const FileInfo &fileInfo)
{
std::ifstream file(fileInfo.absPath.c_str());
std::ofstream output(std::string(_destination + fileInfo.absPath + ".sid").c_str());
std::string line;
std::size_t counter = 0;
/*
1 : crap StringID("
2 : str
*/
std::regex regStringOnly ("(.*?\\bStringID\\s*[(]{1}\\s*[\"]{1})(.+?)[\"]{1}\\s*[)]{1}");
/*
1 : Crap StringID
2 : str
3 : ,
4 : 0x123
*/
std::regex regStringAndHash("(.*?\\bStringID\\s*[(]{1}\\s*\")(.+?)(\"\\s*,\\s*)(0x[\\d|a-f]+|[\\d|a-f]+)\\s*[)]{1}");
std::match_results<std::string::const_iterator> match;
while (std::getline(file, line))
{
std::istringstream iss(line);
line += "\n";
if (line.find("StringID") != std::string::npos)
{
std::string lineCopy = line;
line.clear();
auto flags = std::regex_constants::match_default | std::regex_constants::format_first_only | std::regex_constants::format_no_copy;
bool pass = false;
// We search for already hashed strings like StringID("Literal", 0x123);
// We check if the hash is up to date, if not we re-generate it
// We also register the hash if not already in db cache to check for collisions
while (std::regex_search(lineCopy, match, regStringAndHash, flags))
{
auto &str = match[2].str();
auto &h = match[4].str();
StringIDType id = strtoll(h.c_str(), nullptr, 16);
StringID sid = StringID(str);
if (sid.getId() != id)
{
std::string replacer = "$1$2\", ";
replacer += IntToHex(sid.getId());
replacer += ")";
line += std::regex_replace(lineCopy, regStringAndHash, replacer, flags);
pass = true;
}
else
{
line = lineCopy;
}
lineCopy = match.suffix().str();
}
if (pass)
{
line += lineCopy;
}
if (!line.empty())
lineCopy = line;
line.clear();
pass = false;
// We search for StringID("Literal");
// And generate ID for it
while (std::regex_search(lineCopy, match, regStringOnly, flags))
{
std::string replacer = "$1$2\", ";
auto &str = match[2].str();
replacer += IntToHex(StringID(str).getId());
replacer += ")";
line += std::regex_replace(lineCopy, regStringOnly, replacer, flags);
lineCopy = match.suffix().str();
pass = true;
}
if (pass)
{
line += lineCopy;
}
if (line.empty())
{
line = lineCopy;
}
}
output << line;
}
}
void Application::run()
{
if (_guiEnabled)
{
//_initGui();
}
std::vector<FileInfo> infos;
FileFilter filter;
filter._extensions = _extensions;
filter._excludedPath = _excludedSources;
filter._excludedDir = _excludedFolders;
filter._minimumWriteTime = 0;
for (auto &source : _sources)
{
SearchFiles(/*"D:\Epic Games/"*/ source /*"../Tests/"*/, &filter, infos);
// we set relative path
for (auto &res : infos)
{
res.relPath = res.absPath;
res.relPath.erase(0, source.size());
}
}
for (auto &s : infos)
{
treatFile(s);
}
}<|endoftext|>
|
<commit_before>#include <ros/ros.h>
#include <geometry_msgs/Twist.h>
#include <sensor_msgs/PointCloud2.h>
#include <sensor_msgs/PointCloud.h>
#include <sensor_msgs/point_cloud_conversion.h>
#include <tf/transform_listener.h>
#include <octomap/octomap.h>
#include <octomap/OcTree.h>
#include <octomap_msgs/Octomap.h>
#include <octomap_msgs/conversions.h>
#include <geometry_msgs/PointStamped.h>
#include <string>
#include <math.h>
#include <vector>
#include "dmath/geometry.h"
class ArtificialPotentialField{
public:
ArtificialPotentialField(ros::NodeHandle &node) :
base_link_("base_link"),
cmd_pub_(node.advertise<geometry_msgs::Twist>("cmd_vel", 10)),
obs_sub_(node.subscribe("octomap_full", 10, &ArtificialPotentialField::obstacleCallback, this)),
goal_sub_(node.subscribe("clicked_point", 10, &ArtificialPotentialField::goalCallback, this))
{
collision_map_.header.stamp = ros::Time(0);
}
void spin(){
ros::Rate r(10);
ros::Duration(1).sleep();
geometry_msgs::Twist cmd;
cmd.linear.z = 0.15;
cmd_pub_.publish(cmd);
ros::Duration(3).sleep();
cmd.linear.z = 0;
cmd_pub_.publish(cmd);
ros::Duration(3).sleep();
const double force = 0.025;
while(ros::ok()){
if(collision_map_.header.stamp != ros::Time(0)){
std::vector<dmath::Vector3D> obstacles_lc;
std::string map_frame = collision_map_.header.frame_id;
octomap::OcTree *tree = dynamic_cast<octomap::OcTree*>(octomap_msgs::msgToMap(collision_map_));
octomap::OcTree::leaf_iterator const end_it = tree->end_leafs();
for(octomap::OcTree::leaf_iterator it = tree->begin_leafs(0); it != end_it; it++){
geometry_msgs::PointStamped p_in, p_out;
p_in.header.frame_id = map_frame;
p_in.point.x = it.getX();
p_in.point.y = it.getY();
p_in.point.z = it.getZ();
try{
tf_listener_.transformPoint(base_link_, p_in, p_out);
dmath::Vector3D obs(p_out.point.x, p_out.point.y, p_out.point.z);
if(magnitude(obs) < 2.0){
obstacles_lc.push_back(obs);
}
}catch(tf::TransformException &ex){
ROS_ERROR_STREAM("Exception trying to transform octomap: " << ex.what());
}
}
dmath::Vector3D Fs;
for(int i=0; i < obstacles_lc.size(); i++){
Fs += get_potential_force(obstacles_lc[i], 0, 0.3, 1.0, 1.0);
}
geometry_msgs::PointStamped goal_msg_lc;
dmath::Vector3D goal_lc;
try{
tf_listener_.waitForTransform(goal_msg_gl_.header.frame_id, base_link_, ros::Time(0), ros::Duration(1));
goal_msg_gl_.header.stamp = ros::Time(0);
tf_listener_.transformPoint(base_link_, goal_msg_gl_, goal_msg_lc);
goal_lc = -dmath::Vector3D(goal_msg_lc.point.x, goal_msg_lc.point.y, goal_msg_lc.point.z);
}catch(tf::TransformException &ex){
ROS_ERROR_STREAM("Exception trying to transform goal position: " << ex.what());
goal_lc = dmath::Vector3D();
}
Fs += get_potential_force(goal_lc, 100, 0, 1, 1);
dmath::Vector3D vel = Fs * force;
cmd.linear.x = vel.x;
cmd.linear.y = vel.y;
cmd.linear.z = vel.z;
cmd_pub_.publish(cmd);
}
r.sleep();
ros::spinOnce();
}
}
private:
dmath::Vector3D get_potential_force(const dmath::Vector3D &dest_lc, double A = 1, double B = 1, double n = 1, double m = 1){
dmath::Vector3D u = dest_lc;
u = normalize(u);
const double d = magnitude(dest_lc);
ROS_INFO_STREAM("dist = " << d);
double U = 0;
if(fabs(d) > dmath::tol){
U = -A/pow(d, n) + B/pow(d, m);
}
return U * u;
}
void obstacleCallback(const octomap_msgs::OctomapPtr &obs_msg){
collision_map_ = *obs_msg;
}
void goalCallback(const geometry_msgs::PointStamped &goal_msg){
goal_msg_gl_ = goal_msg;
}
octomap_msgs::Octomap collision_map_;
ros::Publisher cmd_pub_;
ros::Subscriber obs_sub_, goal_sub_;
tf::TransformListener tf_listener_;
std::string base_link_;
geometry_msgs::PointStamped goal_msg_gl_;
};
int main(int argc, char *argv[]){
ros::init(argc, argv, "apf_planner");
ros::NodeHandle node;
ArtificialPotentialField apf(node);
apf.spin();
return 0;
}
<commit_msg>Limit x-velocity<commit_after>#include <ros/ros.h>
#include <geometry_msgs/Twist.h>
#include <sensor_msgs/PointCloud2.h>
#include <sensor_msgs/PointCloud.h>
#include <sensor_msgs/point_cloud_conversion.h>
#include <tf/transform_listener.h>
#include <octomap/octomap.h>
#include <octomap/OcTree.h>
#include <octomap_msgs/Octomap.h>
#include <octomap_msgs/conversions.h>
#include <geometry_msgs/PointStamped.h>
#include <string>
#include <math.h>
#include <vector>
#include "dmath/geometry.h"
class ArtificialPotentialField{
public:
ArtificialPotentialField(ros::NodeHandle &node) :
base_link_("base_link"),
cmd_pub_(node.advertise<geometry_msgs::Twist>("cmd_vel", 10)),
obs_sub_(node.subscribe("octomap_full", 10, &ArtificialPotentialField::obstacleCallback, this)),
goal_sub_(node.subscribe("clicked_point", 10, &ArtificialPotentialField::goalCallback, this))
{
collision_map_.header.stamp = ros::Time(0);
}
void spin(){
ros::Rate r(10);
ros::Duration(1).sleep();
geometry_msgs::Twist cmd;
cmd.linear.z = 0.15;
cmd_pub_.publish(cmd);
ros::Duration(3).sleep();
cmd.linear.z = 0;
cmd_pub_.publish(cmd);
ros::Duration(3).sleep();
const double force = 0.025;
while(ros::ok()){
if(collision_map_.header.stamp != ros::Time(0)){
std::vector<dmath::Vector3D> obstacles_lc;
std::string map_frame = collision_map_.header.frame_id;
octomap::OcTree *tree = dynamic_cast<octomap::OcTree*>(octomap_msgs::msgToMap(collision_map_));
octomap::OcTree::leaf_iterator const end_it = tree->end_leafs();
for(octomap::OcTree::leaf_iterator it = tree->begin_leafs(0); it != end_it; it++){
geometry_msgs::PointStamped p_in, p_out;
p_in.header.frame_id = map_frame;
p_in.point.x = it.getX();
p_in.point.y = it.getY();
p_in.point.z = it.getZ();
try{
tf_listener_.transformPoint(base_link_, p_in, p_out);
dmath::Vector3D obs(p_out.point.x, p_out.point.y, p_out.point.z);
if(magnitude(obs) < 2.0){
obstacles_lc.push_back(obs);
}
}catch(tf::TransformException &ex){
ROS_ERROR_STREAM("Exception trying to transform octomap: " << ex.what());
}
}
dmath::Vector3D Fs;
for(int i=0; i < obstacles_lc.size(); i++){
Fs += get_potential_force(obstacles_lc[i], 0, 0.3, 1.0, 1.0);
}
geometry_msgs::PointStamped goal_msg_lc;
dmath::Vector3D goal_lc;
try{
tf_listener_.waitForTransform(goal_msg_gl_.header.frame_id, base_link_, ros::Time(0), ros::Duration(1));
goal_msg_gl_.header.stamp = ros::Time(0);
tf_listener_.transformPoint(base_link_, goal_msg_gl_, goal_msg_lc);
goal_lc = -dmath::Vector3D(goal_msg_lc.point.x, goal_msg_lc.point.y, goal_msg_lc.point.z);
}catch(tf::TransformException &ex){
ROS_ERROR_STREAM("Exception trying to transform goal position: " << ex.what());
goal_lc = dmath::Vector3D();
}
Fs += get_potential_force(goal_lc, 100, 0, 1, 1);
dmath::Vector3D vel = Fs * force;
if(vel.x > 0.5) vel.x = 0.5;
if(vel.x < -0.5) vel.x = -0.5;
cmd.linear.x = vel.x;
cmd.linear.y = vel.y;
cmd.linear.z = vel.z;
cmd_pub_.publish(cmd);
}
r.sleep();
ros::spinOnce();
}
}
private:
dmath::Vector3D get_potential_force(const dmath::Vector3D &dest_lc, double A = 1, double B = 1, double n = 1, double m = 1){
dmath::Vector3D u = dest_lc;
u = normalize(u);
const double d = magnitude(dest_lc);
ROS_INFO_STREAM("dist = " << d);
double U = 0;
if(fabs(d) > dmath::tol){
U = -A/pow(d, n) + B/pow(d, m);
}
return U * u;
}
void obstacleCallback(const octomap_msgs::OctomapPtr &obs_msg){
collision_map_ = *obs_msg;
}
void goalCallback(const geometry_msgs::PointStamped &goal_msg){
goal_msg_gl_ = goal_msg;
}
octomap_msgs::Octomap collision_map_;
ros::Publisher cmd_pub_;
ros::Subscriber obs_sub_, goal_sub_;
tf::TransformListener tf_listener_;
std::string base_link_;
geometry_msgs::PointStamped goal_msg_gl_;
};
int main(int argc, char *argv[]){
ros::init(argc, argv, "apf_planner");
ros::NodeHandle node;
ArtificialPotentialField apf(node);
apf.spin();
return 0;
}
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.